cpanminus/fatscript.pm untested

filter: Statementstmt 0.0% 0 / 78 Branchbran 0.0% 0 / 10 Conditioncond 0.0% 0 / 5 MC/DCmcdc 0.0% 0 / 3 Subroutinesub 0.0% 0 / 4 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 101 CC 5 SCAR 29.7
CC
5
Cov
0%
BEGIN
30.0
BEGIN
2.0
BEGIN
2.0
CRAP 19.5
1 package App::cpanminus::fatscript;
2 #
3 # This is a pre-compiled source code for the cpanm (cpanminus) program.
4 # For more details about how to install cpanm, go to the following URL:
5 #
6 # https://github.com/miyagawa/cpanminus
7 #
8 # Quickstart: Run the following command and it will install itself for
9 # you. You might want to run it as a root with sudo if you want to install
10 # to places like /usr/local/bin.
11 #
12 # % curl -L https://cpanmin.us | perl - App::cpanminus
13 #
14 # If you don't have curl but wget, replace `curl -L` with `wget -O -`.
15  
16 # DO NOT EDIT -- this is an auto generated file
17  
18 # This chunk of stuff was generated by App::FatPacker. To find the original
19 # file's code, look for the end of this BEGIN block or the string 'FATPACK'
20 BEGIN {
21 my %fatpacked;
22  
23 $fatpacked{"App/cpanminus.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'APP_CPANMINUS';
24 package App::cpanminus;
25 our $VERSION = "1.7049";
26
27 =encoding utf8
28
29 =head1 NAME
30
31 App::cpanminus - get, unpack, build and install modules from CPAN
32
33 =head1 SYNOPSIS
34
35 cpanm Module
36
37 Run C<cpanm -h> or C<perldoc cpanm> for more options.
38
39 =head1 DESCRIPTION
40
41 cpanminus is a script to get, unpack, build and install modules from
42 CPAN and does nothing else.
43
44 It's dependency free (can bootstrap itself), requires zero
45 configuration, and stands alone. When running, it requires only 10MB
46 of RAM.
47
48 =head1 INSTALLATION
49
50 There are several ways to install cpanminus to your system.
51
52 =head2 Package management system
53
54 There are Debian packages, RPMs, FreeBSD ports, and packages for other
55 operation systems available. If you want to use the package management system,
56 search for cpanminus and use the appropriate command to install. This makes it
57 easy to install C<cpanm> to your system without thinking about where to
58 install, and later upgrade.
59
60 =head2 Installing to system perl
61
62 You can also use the latest cpanminus to install cpanminus itself:
63
64 curl -L https://cpanmin.us | perl - --sudo App::cpanminus
65
66 This will install C<cpanm> to your bin directory like
67 C</usr/local/bin> and you'll need the C<--sudo> option to write to
68 the directory, unless you configured C<INSTALL_BASE> with L<local::lib>.
69
70 =head2 Installing to local perl (perlbrew, plenv etc.)
71
72 If you have perl in your home directory, which is the case if you use
73 tools like L<perlbrew> or plenv, you don't need the C<--sudo> option, since
74 you're most likely to have a write permission to the perl's library
75 path. You can just do:
76
77 curl -L https://cpanmin.us | perl - App::cpanminus
78
79 to install the C<cpanm> executable to the perl's bin path, like
80 C<~/perl5/perlbrew/bin/cpanm>.
81
82 =head2 Downloading the standalone executable
83
84 You can also copy the standalone executable to whatever location you'd like.
85
86 cd ~/bin
87 curl -L https://cpanmin.us/ -o cpanm
88 chmod +x cpanm
89
90 This just works, but be sure to grab the new version manually when you
91 upgrade because C<--self-upgrade> might not work with this installation setup.
92
93 =head2 Troubleshoot: HTTPS warnings
94
95 When you run C<curl> commands above, you may encounter SSL handshake
96 errors or certification warnings. This is due to your HTTP client
97 (curl) being old, or SSL certificates installed on your system needs
98 to be updated.
99
100 You're recommended to update the software or system if you can. If
101 that is impossible or difficult, use the C<-k> option with curl.
102
103 =head1 DEPENDENCIES
104
105 perl 5.8.1 or later.
106
107 =over 4
108
109 =item *
110
111 'tar' executable (bsdtar or GNU tar version 1.22 are recommended) or Archive::Tar to unpack files.
112
113 =item *
114
115 C compiler, if you want to build XS modules.
116
117 =item *
118
119 make
120
121 =item *
122
123 Module::Build (core in 5.10)
124
125 =back
126
127 =head1 QUESTIONS
128
129 =head2 How does cpanm get/parse/update the CPAN index?
130
131 It queries the CPAN Meta DB site at L<http://cpanmetadb.plackperl.org/>.
132 The site is updated at least every hour to reflect the latest changes
133 from fast syncing mirrors. The script then also falls back to query the
134 module at L<http://metacpan.org/> using its search API.
135
136 Upon calling these API hosts, cpanm (1.6004 or later) will send the
137 local perl versions to the server in User-Agent string by default. You
138 can turn it off with C<--no-report-perl-version> option. Read more
139 about the option with L<cpanm>, and read more about the privacy policy
140 about this data collection at L<http://cpanmetadb.plackperl.org/#privacy>
141
142 Fetched files are unpacked in C<~/.cpanm> and automatically cleaned up
143 periodically. You can configure the location of this with the
144 C<PERL_CPANM_HOME> environment variable.
145
146 =head2 Where does this install modules to? Do I need root access?
147
148 It installs to wherever ExtUtils::MakeMaker and Module::Build are
149 configured to (via C<PERL_MM_OPT> and C<PERL_MB_OPT>).
150
151 By default, it installs to the site_perl directory that belongs to
152 your perl. You can see the locations for that by running C<perl -V>
153 and it will be likely something under C</opt/local/perl/...> if you're
154 using system perl, or under your home directory if you have built perl
155 yourself using perlbrew or plenv.
156
157 If you've already configured local::lib on your shell, cpanm respects
158 that settings and modules will be installed to your local perl5
159 directory.
160
161 At a boot time, cpanminus checks whether you have already configured
162 local::lib, or have a permission to install modules to the site_perl
163 directory. If neither, i.e. you're using system perl and do not run
164 cpanm as a root, it automatically sets up local::lib compatible
165 installation path in a C<perl5> directory under your home
166 directory.
167
168 To avoid this, run C<cpanm> either as a root user, with C<--sudo>
169 option, or with C<--local-lib> option.
170
171 =head2 cpanminus can't install the module XYZ. Is it a bug?
172
173 It is more likely a problem with the distribution itself. cpanminus
174 doesn't support or may have issues with distributions such as follows:
175
176 =over 4
177
178 =item *
179
180 Tests that require input from STDIN.
181
182 =item *
183
184 Build.PL or Makefile.PL that prompts for input even when
185 C<PERL_MM_USE_DEFAULT> is enabled.
186
187 =item *
188
189 Modules that have invalid numeric values as VERSION (such as C<1.1a>)
190
191 =back
192
193 These failures can be reported back to the author of the module so
194 that they can fix it accordingly, rather than to cpanminus.
195
196 =head2 Does cpanm support the feature XYZ of L<CPAN> and L<CPANPLUS>?
197
198 Most likely not. Here are the things that cpanm doesn't do by
199 itself.
200
201 If you need these features, use L<CPAN>, L<CPANPLUS> or the standalone
202 tools that are mentioned.
203
204 =over 4
205
206 =item *
207
208 CPAN testers reporting. See L<App::cpanminus::reporter>
209
210 =item *
211
212 Building RPM packages from CPAN modules
213
214 =item *
215
216 Listing the outdated modules that needs upgrading. See L<App::cpanoutdated>
217
218 =item *
219
220 Showing the changes of the modules you're about to upgrade. See L<cpan-listchanges>
221
222 =item *
223
224 Patching CPAN modules with distroprefs.
225
226 =back
227
228 See L<cpanm> or C<cpanm -h> to see what cpanminus I<can> do :)
229
230 =head1 COPYRIGHT
231
232 Copyright 2010- Tatsuhiko Miyagawa
233
234 The standalone executable contains the following modules embedded.
235
236 =over 4
237
238 =item L<CPAN::DistnameInfo> Copyright 2003 Graham Barr
239
240 =item L<local::lib> Copyright 2007-2009 Matt S Trout
241
242 =item L<HTTP::Tiny> Copyright 2011 Christian Hansen
243
244 =item L<Module::Metadata> Copyright 2001-2006 Ken Williams. 2010 Matt S Trout
245
246 =item L<version> Copyright 2004-2010 John Peacock
247
248 =item L<JSON::PP> Copyright 2007-2011 by Makamaka Hannyaharamitu
249
250 =item L<CPAN::Meta>, L<CPAN::Meta::Requirements> Copyright (c) 2010 by David Golden and Ricardo Signes
251
252 =item L<CPAN::Meta::YAML> Copyright 2010 Adam Kennedy
253
254 =item L<CPAN::Meta::Check> Copyright (c) 2012 by Leon Timmermans
255
256 =item L<File::pushd> Copyright 2012 David Golden
257
258 =item L<parent> Copyright (c) 2007-10 Max Maischein
259
260 =item L<Parse::PMFile> Copyright 1995 - 2013 by Andreas Koenig, Copyright 2013 by Kenichi Ishigaki
261
262 =item L<String::ShellQuote> by Roderick Schertler
263
264
265 =back
266
267 =head1 LICENSE
268
269 This software is licensed under the same terms as Perl.
270
271 =head1 CREDITS
272
273 =head2 CONTRIBUTORS
274
275 Patches and code improvements were contributed by:
276
277 Goro Fuji, Kazuhiro Osawa, Tokuhiro Matsuno, Kenichi Ishigaki, Ian
278 Wells, Pedro Melo, Masayoshi Sekimura, Matt S Trout (mst), squeeky,
279 horus and Ingy dot Net.
280
281 =head2 ACKNOWLEDGEMENTS
282
283 Bug reports, suggestions and feedbacks were sent by, or general
284 acknowledgement goes to:
285
286 Jesse Vincent, David Golden, Andreas Koenig, Jos Boumans, Chris
287 Williams, Adam Kennedy, Audrey Tang, J. Shirley, Chris Prather, Jesse
288 Luehrs, Marcus Ramberg, Shawn M Moore, chocolateboy, Chirs Nehren,
289 Jonathan Rockway, Leon Brocard, Simon Elliott, Ricardo Signes, AEvar
290 Arnfjord Bjarmason, Eric Wilhelm, Florian Ragwitz and xaicron.
291
292 =head1 COMMUNITY
293
294 =over 4
295
296 =item L<http://github.com/miyagawa/cpanminus> - source code repository, issue tracker
297
298 =item L<irc://irc.perl.org/#cpanm> - discussions about cpanm and its related tools
299
300 =back
301
302 =head1 NO WARRANTY
303
304 This software is provided "as-is," without any express or implied
305 warranty. In no event shall the author be held liable for any damages
306 arising from the use of the software.
307
308 =head1 SEE ALSO
309
310 L<CPAN> L<CPANPLUS> L<pip>
311
312 =cut
313
314 1;
315 APP_CPANMINUS
316  
317 $fatpacked{"App/cpanminus/Dependency.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'APP_CPANMINUS_DEPENDENCY';
318 package App::cpanminus::Dependency;
319 use strict;
320 use CPAN::Meta::Requirements;
321
322 sub from_prereqs {
323 my($class, $prereqs, $phases, $types) = @_;
324
325 my @deps;
326 for my $type (@$types) {
327 push @deps, $class->from_versions(
328 $prereqs->merged_requirements($phases, [$type])->as_string_hash,
329 $type,
330 );
331 }
332
333 return @deps;
334 }
335
336 sub from_versions {
337 my($class, $versions, $type) = @_;
338
339 my @deps;
340 while (my($module, $version) = each %$versions) {
341 push @deps, $class->new($module, $version, $type)
342 }
343
344 @deps;
345 }
346
347 sub merge_with {
348 my($self, $requirements) = @_;
349
350 # save the original requirement
351 $self->{original_version} = $self->version;
352
353 # should it clone? not cloning means we upgrade root $requirements on our way
354 eval {
355 $requirements->add_string_requirement($self->module, $self->version);
356 };
357 if ($@ =~ /illegal requirements/) {
358 # Just give a warning then replace with the root requirements
359 # so that later CPAN::Meta::Check can give a valid error
360 warn sprintf("Can't merge requirements for %s: '%s' and '%s'",
361 $self->module, $self->version,
362 $requirements->requirements_for_module($self->module));
363 }
364
365 $self->{version} = $requirements->requirements_for_module($self->module);
366 }
367
368 sub new {
369 my($class, $module, $version, $type) = @_;
370
371 bless {
372 module => $module,
373 version => $version,
374 type => $type || 'requires',
375 }, $class;
376 }
377
378 sub module { $_[0]->{module} }
379 sub version { $_[0]->{version} }
380 sub type { $_[0]->{type} }
381
382 sub requires_version {
383 my $self = shift;
384
385 # original_version may be 0
386 if (defined $self->{original_version}) {
387 return $self->{original_version};
388 }
389
390 $self->version;
391 }
392
393 sub is_requirement {
394 $_[0]->{type} eq 'requires';
395 }
396
397 1;
398 APP_CPANMINUS_DEPENDENCY
399  
400 $fatpacked{"App/cpanminus/script.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'APP_CPANMINUS_SCRIPT';
401 package App::cpanminus::script;
402 use strict;
403 use Config;
404 use Cwd ();
405 use App::cpanminus;
406 use App::cpanminus::Dependency;
407 use File::Basename ();
408 use File::Find ();
409 use File::Path ();
410 use File::Spec ();
411 use File::Copy ();
412 use File::Temp ();
413 use Getopt::Long ();
414 use Symbol ();
415 use String::ShellQuote ();
416 use version ();
417
418 use constant WIN32 => $^O eq 'MSWin32';
419 use constant BAD_TAR => ($^O eq 'solaris' || $^O eq 'hpux');
420 use constant CAN_SYMLINK => eval { symlink("", ""); 1 };
421
422 our $VERSION = $App::cpanminus::VERSION;
423
424 if ($INC{"App/FatPacker/Trace.pm"}) {
425 require version::vpp;
426 }
427
428 my $quote = WIN32 ? q/"/ : q/'/;
429
430 sub agent {
431 my $self = shift;
432 my $agent = "cpanminus/$VERSION";
433 $agent .= " perl/$]" if $self->{report_perl_version};
434 $agent;
435 }
436
437 sub determine_home {
438 my $class = shift;
439
440 my $homedir = $ENV{HOME}
441 || eval { require File::HomeDir; File::HomeDir->my_home }
442 || join('', @ENV{qw(HOMEDRIVE HOMEPATH)}); # Win32
443
444 if (WIN32) {
445 require Win32; # no fatpack
446 $homedir = Win32::GetShortPathName($homedir);
447 }
448
449 return "$homedir/.cpanm";
450 }
451
452 sub new {
453 my $class = shift;
454
455 bless {
456 home => $class->determine_home,
457 cmd => 'install',
458 seen => {},
459 notest => undef,
460 test_only => undef,
461 installdeps => undef,
462 force => undef,
463 sudo => undef,
464 make => undef,
465 verbose => undef,
466 quiet => undef,
467 interactive => undef,
468 log => undef,
469 mirrors => [],
470 mirror_only => undef,
471 mirror_index => undef,
472 cpanmetadb => "http://cpanmetadb.plackperl.org/v1.0/",
473 perl => $^X,
474 argv => [],
475 local_lib => undef,
476 self_contained => undef,
477 exclude_vendor => undef,
478 prompt_timeout => 0,
479 prompt => undef,
480 configure_timeout => 60,
481 build_timeout => 3600,
482 test_timeout => 1800,
483 try_lwp => 1,
484 try_wget => 1,
485 try_curl => 1,
486 uninstall_shadows => ($] < 5.012),
487 skip_installed => 1,
488 skip_satisfied => 0,
489 auto_cleanup => 7, # days
490 pod2man => 1,
491 installed_dists => 0,
492 install_types => ['requires'],
493 with_develop => 0,
494 with_configure => 0,
495 showdeps => 0,
496 scandeps => 0,
497 scandeps_tree => [],
498 format => 'tree',
499 save_dists => undef,
500 skip_configure => 0,
501 verify => 0,
502 report_perl_version => !$class->maybe_ci,
503 build_args => {},
504 features => {},
505 pure_perl => 0,
506 cpanfile_path => 'cpanfile',
507 @_,
508 }, $class;
509 }
510
511 sub env {
512 my($self, $key) = @_;
513 $ENV{"PERL_CPANM_" . $key};
514 }
515
516 sub maybe_ci {
517 my $class = shift;
518 grep $ENV{$_}, qw( TRAVIS CI AUTOMATED_TESTING AUTHOR_TESTING );
519 }
520
521 sub install_type_handlers {
522 my $self = shift;
523
524 my @handlers;
525 for my $type (qw( recommends suggests )) {
526 push @handlers, "with-$type" => sub {
527 my %uniq;
528 $self->{install_types} = [ grep !$uniq{$_}++, @{$self->{install_types}}, $type ];
529 };
530 push @handlers, "without-$type" => sub {
531 $self->{install_types} = [ grep $_ ne $type, @{$self->{install_types}} ];
532 };
533 }
534
535 @handlers;
536 }
537
538 sub build_args_handlers {
539 my $self = shift;
540
541 my @handlers;
542 for my $phase (qw( configure build test install )) {
543 push @handlers, "$phase-args=s" => \($self->{build_args}{$phase});
544 }
545
546 @handlers;
547 }
548
549 sub parse_options {
550 my $self = shift;
551
552 local @ARGV = @{$self->{argv}};
553 push @ARGV, grep length, split /\s+/, $self->env('OPT');
554 push @ARGV, @_;
555
556 Getopt::Long::Configure("bundling");
557 Getopt::Long::GetOptions(
558 'f|force' => sub { $self->{skip_installed} = 0; $self->{force} = 1 },
559 'n|notest!' => \$self->{notest},
560 'test-only' => sub { $self->{notest} = 0; $self->{skip_installed} = 0; $self->{test_only} = 1 },
561 'S|sudo!' => \$self->{sudo},
562 'v|verbose' => \$self->{verbose},
563 'verify!' => \$self->{verify},
564 'q|quiet!' => \$self->{quiet},
565 'h|help' => sub { $self->{action} = 'show_help' },
566 'V|version' => sub { $self->{action} = 'show_version' },
567 'perl=s' => sub {
568 $self->diag("--perl is deprecated since it's known to be fragile in figuring out dependencies. Run `$_[1] -S cpanm` instead.\n", 1);
569 $self->{perl} = $_[1];
570 },
571 'l|local-lib=s' => sub { $self->{local_lib} = $self->maybe_abs($_[1]) },
572 'L|local-lib-contained=s' => sub {
573 $self->{local_lib} = $self->maybe_abs($_[1]);
574 $self->{self_contained} = 1;
575 $self->{pod2man} = undef;
576 },
577 'self-contained!' => \$self->{self_contained},
578 'exclude-vendor!' => \$self->{exclude_vendor},
579 'mirror=s@' => $self->{mirrors},
580 'mirror-only!' => \$self->{mirror_only},
581 'mirror-index=s' => sub { $self->{mirror_index} = $self->maybe_abs($_[1]) },
582 'M|from=s' => sub {
583 $self->{mirrors} = [$_[1]];
584 $self->{mirror_only} = 1;
585 },
586 'cpanmetadb=s' => \$self->{cpanmetadb},
587 'cascade-search!' => \$self->{cascade_search},
588 'prompt!' => \$self->{prompt},
589 'installdeps' => \$self->{installdeps},
590 'skip-installed!' => \$self->{skip_installed},
591 'skip-satisfied!' => \$self->{skip_satisfied},
592 'reinstall' => sub { $self->{skip_installed} = 0 },
593 'interactive!' => \$self->{interactive},
594 'i|install' => sub { $self->{cmd} = 'install' },
595 'info' => sub { $self->{cmd} = 'info' },
596 'look' => sub { $self->{cmd} = 'look'; $self->{skip_installed} = 0 },
597 'U|uninstall' => sub { $self->{cmd} = 'uninstall' },
598 'self-upgrade' => sub { $self->{action} = 'self_upgrade' },
599 'uninst-shadows!' => \$self->{uninstall_shadows},
600 'lwp!' => \$self->{try_lwp},
601 'wget!' => \$self->{try_wget},
602 'curl!' => \$self->{try_curl},
603 'auto-cleanup=s' => \$self->{auto_cleanup},
604 'man-pages!' => \$self->{pod2man},
605 'scandeps' => \$self->{scandeps},
606 'showdeps' => sub { $self->{showdeps} = 1; $self->{skip_installed} = 0 },
607 'format=s' => \$self->{format},
608 'save-dists=s' => sub {
609 $self->{save_dists} = $self->maybe_abs($_[1]);
610 },
611 'skip-configure!' => \$self->{skip_configure},
612 'dev!' => \$self->{dev_release},
613 'metacpan!' => \$self->{metacpan},
614 'report-perl-version!' => \$self->{report_perl_version},
615 'configure-timeout=i' => \$self->{configure_timeout},
616 'build-timeout=i' => \$self->{build_timeout},
617 'test-timeout=i' => \$self->{test_timeout},
618 'with-develop' => \$self->{with_develop},
619 'without-develop' => sub { $self->{with_develop} = 0 },
620 'with-configure' => \$self->{with_configure},
621 'without-configure' => sub { $self->{with_configure} = 0 },
622 'with-feature=s' => sub { $self->{features}{$_[1]} = 1 },
623 'without-feature=s' => sub { $self->{features}{$_[1]} = 0 },
624 'with-all-features' => sub { $self->{features}{__all} = 1 },
625 'pp|pureperl!' => \$self->{pure_perl},
626 "cpanfile=s" => \$self->{cpanfile_path},
627 $self->install_type_handlers,
628 $self->build_args_handlers,
629 );
630
631 if (!@ARGV && $0 ne '-' && !-t STDIN){ # e.g. # cpanm < author/requires.cpanm
632 push @ARGV, $self->load_argv_from_fh(\*STDIN);
633 $self->{load_from_stdin} = 1;
634 }
635
636 $self->{argv} = \@ARGV;
637 }
638
639 sub check_upgrade {
640 my $self = shift;
641 my $install_base = $ENV{PERL_LOCAL_LIB_ROOT} ? $self->local_lib_target($ENV{PERL_LOCAL_LIB_ROOT}) : $Config{installsitebin};
642 if ($0 eq '-') {
643 # run from curl, that's fine
644 return;
645 } elsif ($0 !~ /^$install_base/) {
646 if ($0 =~ m!perlbrew/bin!) {
647 die <<DIE;
648 It appears your cpanm executable was installed via `perlbrew install-cpanm`.
649 cpanm --self-upgrade won't upgrade the version of cpanm you're running.
650
651 Run the following command to get it upgraded.
652
653 perlbrew install-cpanm
654
655 DIE
656 } else {
657 die <<DIE;
658 You are running cpanm from the path where your current perl won't install executables to.
659 Because of that, cpanm --self-upgrade won't upgrade the version of cpanm you're running.
660
661 cpanm path : $0
662 Install path : $Config{installsitebin}
663
664 It means you either installed cpanm globally with system perl, or use distro packages such
665 as rpm or apt-get, and you have to use them again to upgrade cpanm.
666 DIE
667 }
668 }
669 }
670
671 sub check_libs {
672 my $self = shift;
673 return if $self->{_checked}++;
674 $self->bootstrap_local_lib;
675 }
676
677 sub setup_verify {
678 my $self = shift;
679
680 my $has_modules = eval { require Module::Signature; require Digest::SHA; 1 };
681 $self->{cpansign} = $self->which('cpansign');
682
683 unless ($has_modules && $self->{cpansign}) {
684 warn "WARNING: Module::Signature and Digest::SHA is required for distribution verifications.\n";
685 $self->{verify} = 0;
686 }
687 }
688
689 sub parse_module_args {
690 my($self, $module) = @_;
691
692 # Plack@1.2 -> Plack~"==1.2"
693 # BUT don't expand @ in git URLs
694 $module =~ s/^([A-Za-z0-9_:]+)@([v\d\._]+)$/$1~== $2/;
695
696 # Plack~1.20, DBI~"> 1.0, <= 2.0"
697 if ($module =~ /\~[v\d\._,\!<>= ]+$/) {
698 return split /\~/, $module, 2;
699 } else {
700 return $module, undef;
701 }
702 }
703
704 sub doit {
705 my $self = shift;
706
707 my $code;
708 eval {
709 $code = ($self->_doit == 0);
710 }; if (my $e = $@) {
711 warn $e;
712 $code = 1;
713 }
714
715 return $code;
716 }
717
718 sub _doit {
719 my $self = shift;
720
721 $self->setup_home;
722 $self->init_tools;
723 $self->setup_verify if $self->{verify};
724
725 if (my $action = $self->{action}) {
726 $self->$action() and return 1;
727 }
728
729 return $self->show_help(1)
730 unless @{$self->{argv}} or $self->{load_from_stdin};
731
732 $self->configure_mirrors;
733
734 my $cwd = Cwd::cwd;
735
736 my @fail;
737 for my $module (@{$self->{argv}}) {
738 if ($module =~ s/\.pm$//i) {
739 my ($volume, $dirs, $file) = File::Spec->splitpath($module);
740 $module = join '::', grep { $_ } File::Spec->splitdir($dirs), $file;
741 }
742 ($module, my $version) = $self->parse_module_args($module);
743
744 $self->chdir($cwd);
745 if ($self->{cmd} eq 'uninstall') {
746 $self->uninstall_module($module)
747 or push @fail, $module;
748 } else {
749 $self->install_module($module, 0, $version)
750 or push @fail, $module;
751 }
752 }
753
754 if ($self->{base} && $self->{auto_cleanup}) {
755 $self->cleanup_workdirs;
756 }
757
758 if ($self->{installed_dists}) {
759 my $dists = $self->{installed_dists} > 1 ? "distributions" : "distribution";
760 $self->diag("$self->{installed_dists} $dists installed\n", 1);
761 }
762
763 if ($self->{scandeps}) {
764 $self->dump_scandeps();
765 }
766 # Workaround for older File::Temp's
767 # where creating a tempdir with an implicit $PWD
768 # causes tempdir non-cleanup if $PWD changes
769 # as paths are stored internally without being resolved
770 # absolutely.
771 # https://rt.cpan.org/Public/Bug/Display.html?id=44924
772 $self->chdir($cwd);
773
774 return !@fail;
775 }
776
777 sub setup_home {
778 my $self = shift;
779
780 $self->{home} = $self->env('HOME') if $self->env('HOME');
781
782 unless (_writable($self->{home})) {
783 die "Can't write to cpanm home '$self->{home}': You should fix it with chown/chmod first.\n";
784 }
785
786 $self->{base} = "$self->{home}/work/" . time . ".$$";
787 File::Path::mkpath([ $self->{base} ], 0, 0777);
788
789 # native path because we use shell redirect
790 $self->{log} = File::Spec->catfile($self->{base}, "build.log");
791 my $final_log = "$self->{home}/build.log";
792
793 { open my $out, ">$self->{log}" or die "$self->{log}: $!" }
794
795 if (CAN_SYMLINK) {
796 my $build_link = "$self->{home}/latest-build";
797 unlink $build_link;
798 symlink $self->{base}, $build_link;
799
800 unlink $final_log;
801 symlink $self->{log}, $final_log;
802 } else {
803 my $log = $self->{log}; my $home = $self->{home};
804 $self->{at_exit} = sub {
805 my $self = shift;
806 my $temp_log = "$home/build.log." . time . ".$$";
807 File::Copy::copy($log, $temp_log)
808 && unlink($final_log);
809 rename($temp_log, $final_log);
810 }
811 }
812
813 $self->chat("cpanm (App::cpanminus) $VERSION on perl $] built for $Config{archname}\n" .
814 "Work directory is $self->{base}\n");
815 }
816
817 sub package_index_for {
818 my ($self, $mirror) = @_;
819 return $self->source_for($mirror) . "/02packages.details.txt";
820 }
821
822 sub generate_mirror_index {
823 my ($self, $mirror) = @_;
824 my $file = $self->package_index_for($mirror);
825 my $gz_file = $file . '.gz';
826 my $index_mtime = (stat $gz_file)[9];
827
828 unless (-e $file && (stat $file)[9] >= $index_mtime) {
829 $self->chat("Uncompressing index file...\n");
830 if (eval {require Compress::Zlib}) {
831 my $gz = Compress::Zlib::gzopen($gz_file, "rb")
832 or do { $self->diag_fail("$Compress::Zlib::gzerrno opening compressed index"); return};
833 open my $fh, '>', $file
834 or do { $self->diag_fail("$! opening uncompressed index for write"); return };
835 my $buffer;
836 while (my $status = $gz->gzread($buffer)) {
837 if ($status < 0) {
838 $self->diag_fail($gz->gzerror . " reading compressed index");
839 return;
840 }
841 print $fh $buffer;
842 }
843 } else {
844 if (system("gunzip -c $gz_file > $file")) {
845 $self->diag_fail("Cannot uncompress -- please install gunzip or Compress::Zlib");
846 return;
847 }
848 }
849 utime $index_mtime, $index_mtime, $file;
850 }
851 return 1;
852 }
853
854 sub search_mirror_index {
855 my ($self, $mirror, $module, $version) = @_;
856 $self->search_mirror_index_file($self->package_index_for($mirror), $module, $version);
857 }
858
859 sub search_mirror_index_file {
860 my($self, $file, $module, $version) = @_;
861
862 open my $fh, '<', $file or return;
863 my $found;
864 while (<$fh>) {
865 if (m!^\Q$module\E\s+([\w\.]+)\s+(\S*)!m) {
866 $found = $self->cpan_module($module, $2, $1);
867 last;
868 }
869 }
870
871 return $found unless $self->{cascade_search};
872
873 if ($found) {
874 if ($self->satisfy_version($module, $found->{module_version}, $version)) {
875 return $found;
876 } else {
877 $self->chat("Found $module $found->{module_version} which doesn't satisfy $version.\n");
878 }
879 }
880
881 return;
882 }
883
884 sub with_version_range {
885 my($self, $version) = @_;
886 defined($version) && $version =~ /(?:<|!=|==)/;
887 }
888
889 sub encode_json {
890 my($self, $data) = @_;
891 require JSON::PP;
892
893 my $json = JSON::PP::encode_json($data);
894 $self->uri_escape($json);
895 }
896
897 sub decode_json {
898 my($self, $json) = @_;
899 require JSON::PP;
900
901 JSON::PP::decode_json($json);
902 }
903
904 sub uri_escape {
905 my($self, $fragment) = @_;
906 $fragment =~ s/([^A-Za-z0-9\-\._~])/uc sprintf("%%%02X", ord($1))/eg;
907 $fragment;
908 }
909
910 sub uri_params {
911 my($self, @params) = @_;
912 my @param_strings;
913 while (my $key = shift @params) {
914 my $value = shift @params;
915 push @param_strings, join '=', map $self->uri_escape($_), $key, $value;
916 }
917 return join '&', @param_strings;
918 }
919
920 # version->new("1.00_00")->numify => "1.00_00" :/
921 sub numify_ver {
922 my($self, $ver) = @_;
923 eval version->new($ver)->numify;
924 }
925
926 sub search_metacpan {
927 my($self, $module, $version, $dev_release) = @_;
928
929 my $metacpan_uri = 'http://fastapi.metacpan.org/v1/download_url/';
930
931 my $url = $metacpan_uri . $module;
932
933 my $query = $self->uri_params(
934 ($version ? (version => $version) : ()),
935 ($dev_release ? (dev => 1) : ()),
936 );
937 $url .= '?' . $query
938 if length $query;
939
940 my $dist_json = $self->get($url);
941 my $dist_meta = eval { $self->decode_json($dist_json) };
942
943 if ($dist_meta && $dist_meta->{download_url}) {
944 (my $distfile = $dist_meta->{download_url}) =~ s!.+/authors/id/!!;
945 local $self->{mirrors} = $self->{mirrors};
946 $self->{mirrors} = [ 'http://cpan.metacpan.org' ];
947 return $self->cpan_module($module, $distfile, $dist_meta->{version});
948 }
949
950 $self->chat("! Could not find a release matching $module".($version?" ($version)":'')." on MetaCPAN.\n");
951 return;
952 }
953
954 sub search_database {
955 my($self, $module, $version) = @_;
956
957 my $found;
958
959 if ($self->{dev_release} or $self->{metacpan}) {
960 $found = $self->search_metacpan($module, $version, $self->{dev_release}) and return $found;
961 $found = $self->search_cpanmetadb($module, $version, $self->{dev_release}) and return $found;
962 } else {
963 $found = $self->search_cpanmetadb($module, $version) and return $found;
964 $found = $self->search_metacpan($module, $version) and return $found;
965 }
966 }
967
968 sub search_cpanmetadb {
969 my($self, $module, $version, $dev_release) = @_;
970
971
972 $self->chat("Searching $module ($version) on cpanmetadb ...\n");
973
974 if ($self->with_version_range($version)) {
975 return $self->search_cpanmetadb_history($module, $version, $dev_release);
976 } else {
977 return $self->search_cpanmetadb_package($module, $version, $dev_release);
978 }
979 }
980
981 sub search_cpanmetadb_package {
982 my($self, $module, $version, $dev_release) = @_;
983
984 require CPAN::Meta::YAML;
985
986 (my $uri = $self->{cpanmetadb}) =~ s{/?$}{/package/$module};
987 my $yaml = $self->get($uri);
988 my $meta = eval { CPAN::Meta::YAML::Load($yaml) };
989 if ($meta && $meta->{distfile}) {
990 return $self->cpan_module($module, $meta->{distfile}, $meta->{version});
991 }
992
993 $self->diag_fail("Finding $module on cpanmetadb failed.");
994 return;
995 }
996
997 sub search_cpanmetadb_history {
998 my($self, $module, $version) = @_;
999
1000 (my $uri = $self->{cpanmetadb}) =~ s{/?$}{/history/$module};
1001 my $content = $self->get($uri) or return;
1002
1003 my @found;
1004 for my $line (split /\r?\n/, $content) {
1005 if ($line =~ /^$module\s+(\S+)\s+(\S+)$/) {
1006 push @found, {
1007 version => $1,
1008 version_obj => version::->parse($1),
1009 distfile => $2,
1010 };
1011 }
1012 }
1013
1014 return unless @found;
1015
1016 $found[-1]->{latest} = 1;
1017
1018 my $match;
1019 for my $try (sort { $b->{version_obj} cmp $a->{version_obj} } @found) {
1020 if ($self->satisfy_version($module, $try->{version_obj}, $version)) {
1021 local $self->{mirrors} = $self->{mirrors};
1022 unshift @{$self->{mirrors}}, 'http://backpan.perl.org'
1023 unless $try->{latest};
1024 return $self->cpan_module($module, $try->{distfile}, $try->{version});
1025 }
1026 }
1027
1028 $self->diag_fail("Finding $module ($version) on cpanmetadb failed.");
1029 return;
1030 }
1031
1032
1033 sub search_module {
1034 my($self, $module, $version) = @_;
1035
1036 if ($self->{mirror_index}) {
1037 $self->mask_output( chat => "Searching $module on mirror index $self->{mirror_index} ...\n" );
1038 my $pkg = $self->search_mirror_index_file($self->{mirror_index}, $module, $version);
1039 return $pkg if $pkg;
1040
1041 unless ($self->{cascade_search}) {
1042 $self->mask_output( diag_fail => "Finding $module ($version) on mirror index $self->{mirror_index} failed." );
1043 return;
1044 }
1045 }
1046
1047 unless ($self->{mirror_only}) {
1048 my $found = $self->search_database($module, $version);
1049 return $found if $found;
1050 }
1051
1052 MIRROR: for my $mirror (@{ $self->{mirrors} }) {
1053 $self->mask_output( chat => "Searching $module on mirror $mirror ...\n" );
1054 my $name = '02packages.details.txt.gz';
1055 my $uri = "$mirror/modules/$name";
1056 my $gz_file = $self->package_index_for($mirror) . '.gz';
1057
1058 unless ($self->{pkgs}{$uri}) {
1059 $self->mask_output( chat => "Downloading index file $uri ...\n" );
1060 $self->mirror($uri, $gz_file);
1061 $self->generate_mirror_index($mirror) or next MIRROR;
1062 $self->{pkgs}{$uri} = "!!retrieved!!";
1063 }
1064
1065 my $pkg = $self->search_mirror_index($mirror, $module, $version);
1066 return $pkg if $pkg;
1067
1068 $self->mask_output( diag_fail => "Finding $module ($version) on mirror $mirror failed." );
1069 }
1070
1071 return;
1072 }
1073
1074 sub source_for {
1075 my($self, $mirror) = @_;
1076 $mirror =~ s/[^\w\.\-]+/%/g;
1077
1078 my $dir = "$self->{home}/sources/$mirror";
1079 File::Path::mkpath([ $dir ], 0, 0777);
1080
1081 return $dir;
1082 }
1083
1084 sub load_argv_from_fh {
1085 my($self, $fh) = @_;
1086
1087 my @argv;
1088 while(defined(my $line = <$fh>)){
1089 chomp $line;
1090 $line =~ s/#.+$//; # comment
1091 $line =~ s/^\s+//; # trim spaces
1092 $line =~ s/\s+$//; # trim spaces
1093
1094 push @argv, split ' ', $line if $line;
1095 }
1096 return @argv;
1097 }
1098
1099 sub show_version {
1100 my $self = shift;
1101
1102 print "cpanm (App::cpanminus) version $VERSION ($0)\n";
1103 print "perl version $] ($^X)\n\n";
1104
1105 print " \%Config:\n";
1106 for my $key (qw( archname installsitelib installsitebin installman1dir installman3dir
1107 sitearchexp sitelibexp vendorarch vendorlibexp archlibexp privlibexp )) {
1108 print " $key=$Config{$key}\n" if $Config{$key};
1109 }
1110
1111 print " \%ENV:\n";
1112 for my $key (grep /^PERL/, sort keys %ENV) {
1113 print " $key=$ENV{$key}\n";
1114 }
1115
1116 print " \@INC:\n";
1117 for my $inc (@INC) {
1118 print " $inc\n" unless ref($inc) eq 'CODE';
1119 }
1120
1121 return 1;
1122 }
1123
1124 sub show_help {
1125 my $self = shift;
1126
1127 if ($_[0]) {
1128 print <<USAGE;
1129 Usage: cpanm [options] Module [...]
1130
1131 Try `cpanm --help` or `man cpanm` for more options.
1132 USAGE
1133 return;
1134 }
1135
1136 print <<HELP;
1137 Usage: cpanm [options] Module [...]
1138
1139 Options:
1140 -v,--verbose Turns on chatty output
1141 -q,--quiet Turns off the most output
1142 --interactive Turns on interactive configure (required for Task:: modules)
1143 -f,--force force install
1144 -n,--notest Do not run unit tests
1145 --test-only Run tests only, do not install
1146 -S,--sudo sudo to run install commands
1147 --installdeps Only install dependencies
1148 --showdeps Only display direct dependencies
1149 --reinstall Reinstall the distribution even if you already have the latest version installed
1150 --mirror Specify the base URL for the mirror (e.g. http://cpan.cpantesters.org/)
1151 --mirror-only Use the mirror's index file instead of the CPAN Meta DB
1152 -M,--from Use only this mirror base URL and its index file
1153 --prompt Prompt when configure/build/test fails
1154 -l,--local-lib Specify the install base to install modules
1155 -L,--local-lib-contained Specify the install base to install all non-core modules
1156 --self-contained Install all non-core modules, even if they're already installed.
1157 --auto-cleanup Number of days that cpanm's work directories expire in. Defaults to 7
1158
1159 Commands:
1160 --self-upgrade upgrades itself
1161 --info Displays distribution info on CPAN
1162 --look Opens the distribution with your SHELL
1163 -U,--uninstall Uninstalls the modules (EXPERIMENTAL)
1164 -V,--version Displays software version
1165
1166 Examples:
1167
1168 cpanm Test::More # install Test::More
1169 cpanm MIYAGAWA/Plack-0.99_05.tar.gz # full distribution path
1170 cpanm http://example.org/LDS/CGI.pm-3.20.tar.gz # install from URL
1171 cpanm ~/dists/MyCompany-Enterprise-1.00.tar.gz # install from a local file
1172 cpanm --interactive Task::Kensho # Configure interactively
1173 cpanm . # install from local directory
1174 cpanm --installdeps . # install all the deps for the current directory
1175 cpanm -L extlib Plack # install Plack and all non-core deps into extlib
1176 cpanm --mirror http://cpan.cpantesters.org/ DBI # use the fast-syncing mirror
1177 cpanm -M https://cpan.metacpan.org App::perlbrew # use only this secure mirror and its index
1178
1179 You can also specify the default options in PERL_CPANM_OPT environment variable in the shell rc:
1180
1181 export PERL_CPANM_OPT="--prompt --reinstall -l ~/perl --mirror http://cpan.cpantesters.org"
1182
1183 Type `man cpanm` or `perldoc cpanm` for the more detailed explanation of the options.
1184
1185 HELP
1186
1187 return 1;
1188 }
1189
1190 sub _writable {
1191 my $dir = shift;
1192 my @dir = File::Spec->splitdir($dir);
1193 while (@dir) {
1194 $dir = File::Spec->catdir(@dir);
1195 if (-e $dir) {
1196 return -w _;
1197 }
1198 pop @dir;
1199 }
1200
1201 return;
1202 }
1203
1204 sub maybe_abs {
1205 my($self, $lib) = @_;
1206 if ($lib eq '_' or $lib =~ /^~/ or File::Spec->file_name_is_absolute($lib)) {
1207 return $lib;
1208 } else {
1209 return File::Spec->canonpath(File::Spec->catdir(Cwd::cwd(), $lib));
1210 }
1211 }
1212
1213 sub local_lib_target {
1214 my($self, $root) = @_;
1215 # local::lib 1.008025 changed the order of PERL_LOCAL_LIB_ROOT
1216 (grep { $_ ne '' } split /\Q$Config{path_sep}/, $root)[0];
1217 }
1218
1219 sub bootstrap_local_lib {
1220 my $self = shift;
1221
1222 # If -l is specified, use that.
1223 if ($self->{local_lib}) {
1224 return $self->setup_local_lib($self->{local_lib});
1225 }
1226
1227 # PERL_LOCAL_LIB_ROOT is defined. Run as local::lib mode without overwriting ENV
1228 if ($ENV{PERL_LOCAL_LIB_ROOT} && $ENV{PERL_MM_OPT}) {
1229 return $self->setup_local_lib($self->local_lib_target($ENV{PERL_LOCAL_LIB_ROOT}), 1);
1230 }
1231
1232 # root, locally-installed perl or --sudo: don't care about install_base
1233 return if $self->{sudo} or (_writable($Config{installsitelib}) and _writable($Config{installsitebin}));
1234
1235 # local::lib is configured in the shell -- yay
1236 if ($ENV{PERL_MM_OPT} and ($ENV{MODULEBUILDRC} or $ENV{PERL_MB_OPT})) {
1237 return;
1238 }
1239
1240 $self->setup_local_lib;
1241
1242 $self->diag(<<DIAG, 1);
1243 !
1244 ! Can't write to $Config{installsitelib} and $Config{installsitebin}: Installing modules to $ENV{HOME}/perl5
1245 ! To turn off this warning, you have to do one of the following:
1246 ! - run me as a root or with --sudo option (to install to $Config{installsitelib} and $Config{installsitebin})
1247 ! - Configure local::lib in your existing shell to set PERL_MM_OPT etc.
1248 ! - Install local::lib by running the following commands
1249 !
1250 ! cpanm --local-lib=~/perl5 local::lib && eval \$(perl -I ~/perl5/lib/perl5/ -Mlocal::lib)
1251 !
1252 DIAG
1253 sleep 2;
1254 }
1255
1256 sub upgrade_toolchain {
1257 my($self, $config_deps) = @_;
1258
1259 my %deps = map { $_->module => $_ } @$config_deps;
1260
1261 # M::B 0.38 and EUMM 6.58 for MYMETA
1262 # EU::Install 1.46 for local::lib
1263 my $reqs = CPAN::Meta::Requirements->from_string_hash({
1264 'Module::Build' => '0.38',
1265 'ExtUtils::MakeMaker' => '6.58',
1266 'ExtUtils::Install' => '1.46',
1267 });
1268
1269 if ($deps{"ExtUtils::MakeMaker"}) {
1270 $deps{"ExtUtils::MakeMaker"}->merge_with($reqs);
1271 } elsif ($deps{"Module::Build"}) {
1272 $deps{"Module::Build"}->merge_with($reqs);
1273 $deps{"ExtUtils::Install"} ||= App::cpanminus::Dependency->new("ExtUtils::Install", 0, 'configure');
1274 $deps{"ExtUtils::Install"}->merge_with($reqs);
1275 }
1276
1277 @$config_deps = values %deps;
1278 }
1279
1280 sub _core_only_inc {
1281 my($self, $base) = @_;
1282 require local::lib;
1283 (
1284 local::lib->resolve_path(local::lib->install_base_arch_path($base)),
1285 local::lib->resolve_path(local::lib->install_base_perl_path($base)),
1286 (!$self->{exclude_vendor} ? grep {$_} @Config{qw(vendorarch vendorlibexp)} : ()),
1287 @Config{qw(archlibexp privlibexp)},
1288 );
1289 }
1290
1291 sub _diff {
1292 my($self, $old, $new) = @_;
1293
1294 my @diff;
1295 my %old = map { $_ => 1 } @$old;
1296 for my $n (@$new) {
1297 push @diff, $n unless exists $old{$n};
1298 }
1299
1300 @diff;
1301 }
1302
1303 sub _setup_local_lib_env {
1304 my($self, $base) = @_;
1305
1306 $self->diag(<<WARN, 1) if $base =~ /\s/;
1307 WARNING: Your lib directory name ($base) contains a space in it. It's known to cause issues with perl builder tools such as local::lib and MakeMaker. You're recommended to rename your directory.
1308 WARN
1309
1310 local $SIG{__WARN__} = sub { }; # catch 'Attempting to write ...'
1311 local::lib->setup_env_hash_for($base, 0);
1312 }
1313
1314 sub setup_local_lib {
1315 my($self, $base, $no_env) = @_;
1316 $base = undef if $base eq '_';
1317
1318 require local::lib;
1319 {
1320 local $0 = 'cpanm'; # so curl/wget | perl works
1321 $base ||= "~/perl5";
1322 $base = local::lib->resolve_path($base);
1323 if ($self->{self_contained}) {
1324 my @inc = $self->_core_only_inc($base);
1325 $self->{search_inc} = [ @inc ];
1326 } else {
1327 $self->{search_inc} = [
1328 local::lib->install_base_arch_path($base),
1329 local::lib->install_base_perl_path($base),
1330 @INC,
1331 ];
1332 }
1333 $self->_setup_local_lib_env($base) unless $no_env;
1334 $self->{local_lib} = $base;
1335 }
1336 }
1337
1338 sub prompt_bool {
1339 my($self, $mess, $def) = @_;
1340
1341 my $val = $self->prompt($mess, $def);
1342 return lc $val eq 'y';
1343 }
1344
1345 sub prompt {
1346 my($self, $mess, $def) = @_;
1347
1348 my $isa_tty = -t STDIN && (-t STDOUT || !(-f STDOUT || -c STDOUT)) ;
1349 my $dispdef = defined $def ? "[$def] " : " ";
1350 $def = defined $def ? $def : "";
1351
1352 if (!$self->{prompt} || (!$isa_tty && eof STDIN)) {
1353 return $def;
1354 }
1355
1356 local $|=1;
1357 local $\;
1358 my $ans;
1359 eval {
1360 local $SIG{ALRM} = sub { undef $ans; die "alarm\n" };
1361 print STDOUT "$mess $dispdef";
1362 alarm $self->{prompt_timeout} if $self->{prompt_timeout};
1363 $ans = <STDIN>;
1364 alarm 0;
1365 };
1366 if ( defined $ans ) {
1367 chomp $ans;
1368 } else { # user hit ctrl-D or alarm timeout
1369 print STDOUT "\n";
1370 }
1371
1372 return (!defined $ans || $ans eq '') ? $def : $ans;
1373 }
1374
1375 sub diag_ok {
1376 my($self, $msg) = @_;
1377 chomp $msg;
1378 $msg ||= "OK";
1379 if ($self->{in_progress}) {
1380 $self->_diag("$msg\n");
1381 $self->{in_progress} = 0;
1382 }
1383 $self->log("-> $msg\n");
1384 }
1385
1386 sub diag_fail {
1387 my($self, $msg, $always) = @_;
1388 chomp $msg;
1389 if ($self->{in_progress}) {
1390 $self->_diag("FAIL\n");
1391 $self->{in_progress} = 0;
1392 }
1393
1394 if ($msg) {
1395 $self->_diag("! $msg\n", $always, 1);
1396 $self->log("-> FAIL $msg\n");
1397 }
1398 }
1399
1400 sub diag_progress {
1401 my($self, $msg) = @_;
1402 chomp $msg;
1403 $self->{in_progress} = 1;
1404 $self->_diag("$msg ... ");
1405 $self->log("$msg\n");
1406 }
1407
1408 sub _diag {
1409 my($self, $msg, $always, $error) = @_;
1410 my $fh = $error ? *STDERR : *STDOUT;
1411 print {$fh} $msg if $always or $self->{verbose} or !$self->{quiet};
1412 }
1413
1414 sub diag {
1415 my($self, $msg, $always) = @_;
1416 $self->_diag($msg, $always);
1417 $self->log($msg);
1418 }
1419
1420 sub chat {
1421 my $self = shift;
1422 print STDERR @_ if $self->{verbose};
1423 $self->log(@_);
1424 }
1425
1426 sub mask_output {
1427 my $self = shift;
1428 my $method = shift;
1429 $self->$method( $self->mask_uri_passwords(@_) );
1430 }
1431
1432 sub log {
1433 my $self = shift;
1434 open my $out, ">>$self->{log}";
1435 print $out @_;
1436 }
1437
1438 sub run {
1439 my($self, $cmd) = @_;
1440
1441 if (WIN32) {
1442 $cmd = $self->shell_quote(@$cmd) if ref $cmd eq 'ARRAY';
1443 unless ($self->{verbose}) {
1444 $cmd .= " >> " . $self->shell_quote($self->{log}) . " 2>&1";
1445 }
1446 !system $cmd;
1447 } else {
1448 my $pid = fork;
1449 if ($pid) {
1450 waitpid $pid, 0;
1451 return !$?;
1452 } else {
1453 $self->run_exec($cmd);
1454 }
1455 }
1456 }
1457
1458 sub run_exec {
1459 my($self, $cmd) = @_;
1460
1461 if (ref $cmd eq 'ARRAY') {
1462 unless ($self->{verbose}) {
1463 open my $logfh, ">>", $self->{log};
1464 open STDERR, '>&', $logfh;
1465 open STDOUT, '>&', $logfh;
1466 close $logfh;
1467 }
1468 exec @$cmd;
1469 } else {
1470 unless ($self->{verbose}) {
1471 $cmd .= " >> " . $self->shell_quote($self->{log}) . " 2>&1";
1472 }
1473 exec $cmd;
1474 }
1475 }
1476
1477 sub run_timeout {
1478 my($self, $cmd, $timeout) = @_;
1479 return $self->run($cmd) if WIN32 || $self->{verbose} || !$timeout;
1480
1481 my $pid = fork;
1482 if ($pid) {
1483 eval {
1484 local $SIG{ALRM} = sub { die "alarm\n" };
1485 alarm $timeout;
1486 waitpid $pid, 0;
1487 alarm 0;
1488 };
1489 if ($@ && $@ eq "alarm\n") {
1490 $self->diag_fail("Timed out (> ${timeout}s). Use --verbose to retry.");
1491 local $SIG{TERM} = 'IGNORE';
1492 kill TERM => 0;
1493 waitpid $pid, 0;
1494 return;
1495 }
1496 return !$?;
1497 } elsif ($pid == 0) {
1498 $self->run_exec($cmd);
1499 } else {
1500 $self->chat("! fork failed: falling back to system()\n");
1501 $self->run($cmd);
1502 }
1503 }
1504
1505 sub append_args {
1506 my($self, $cmd, $phase) = @_;
1507
1508 if (my $args = $self->{build_args}{$phase}) {
1509 $cmd = join ' ', $self->shell_quote(@$cmd), $args;
1510 }
1511
1512 $cmd;
1513 }
1514
1515 sub configure {
1516 my($self, $cmd, $depth) = @_;
1517
1518 # trick AutoInstall
1519 local $ENV{PERL5_CPAN_IS_RUNNING} = local $ENV{PERL5_CPANPLUS_IS_RUNNING} = $$;
1520
1521 # e.g. skip CPAN configuration on local::lib
1522 local $ENV{PERL5_CPANM_IS_RUNNING} = $$;
1523
1524 my $use_default = !$self->{interactive};
1525 local $ENV{PERL_MM_USE_DEFAULT} = $use_default;
1526
1527 local $ENV{PERL_MM_OPT} = $ENV{PERL_MM_OPT};
1528 local $ENV{PERL_MB_OPT} = $ENV{PERL_MB_OPT};
1529
1530 # skip man page generation
1531 unless ($self->{pod2man}) {
1532 $ENV{PERL_MM_OPT} .= " INSTALLMAN1DIR=none INSTALLMAN3DIR=none";
1533 $ENV{PERL_MB_OPT} .= " --config installman1dir= --config installsiteman1dir= --config installman3dir= --config installsiteman3dir=";
1534 }
1535
1536 # Lancaster Consensus
1537 if ($self->{pure_perl}) {
1538 $ENV{PERL_MM_OPT} .= " PUREPERL_ONLY=1";
1539 $ENV{PERL_MB_OPT} .= " --pureperl-only";
1540 }
1541
1542 local $ENV{PERL_USE_UNSAFE_INC} = 1
1543 unless exists $ENV{PERL_USE_UNSAFE_INC};
1544
1545 $cmd = $self->append_args($cmd, 'configure') if $depth == 0;
1546
1547 local $self->{verbose} = $self->{verbose} || $self->{interactive};
1548 $self->run_timeout($cmd, $self->{configure_timeout});
1549 }
1550
1551 sub build {
1552 my($self, $cmd, $distname, $depth) = @_;
1553
1554 local $ENV{PERL_MM_USE_DEFAULT} = !$self->{interactive};
1555
1556 local $ENV{PERL_USE_UNSAFE_INC} = 1
1557 unless exists $ENV{PERL_USE_UNSAFE_INC};
1558
1559 $cmd = $self->append_args($cmd, 'build') if $depth == 0;
1560
1561 return 1 if $self->run_timeout($cmd, $self->{build_timeout});
1562 while (1) {
1563 my $ans = lc $self->prompt("Building $distname failed.\nYou can s)kip, r)etry, e)xamine build log, or l)ook ?", "s");
1564 return if $ans eq 's';
1565 return $self->build($cmd, $distname, $depth) if $ans eq 'r';
1566 $self->show_build_log if $ans eq 'e';
1567 $self->look if $ans eq 'l';
1568 }
1569 }
1570
1571 sub test {
1572 my($self, $cmd, $distname, $depth) = @_;
1573 return 1 if $self->{notest};
1574
1575 # https://rt.cpan.org/Ticket/Display.html?id=48965#txn-1013385
1576 local $ENV{PERL_MM_USE_DEFAULT} = !$self->{interactive};
1577
1578 # https://github.com/Perl-Toolchain-Gang/toolchain-site/blob/master/lancaster-consensus.md
1579 local $ENV{NONINTERACTIVE_TESTING} = !$self->{interactive};
1580
1581 $cmd = $self->append_args($cmd, 'test') if $depth == 0;
1582
1583 local $ENV{PERL_USE_UNSAFE_INC} = 1
1584 unless exists $ENV{PERL_USE_UNSAFE_INC};
1585
1586 return 1 if $self->run_timeout($cmd, $self->{test_timeout});
1587 if ($self->{force}) {
1588 $self->diag_fail("Testing $distname failed but installing it anyway.");
1589 return 1;
1590 } else {
1591 $self->diag_fail;
1592 while (1) {
1593 my $ans = lc $self->prompt("Testing $distname failed.\nYou can s)kip, r)etry, f)orce install, e)xamine build log, or l)ook ?", "s");
1594 return if $ans eq 's';
1595 return $self->test($cmd, $distname, $depth) if $ans eq 'r';
1596 return 1 if $ans eq 'f';
1597 $self->show_build_log if $ans eq 'e';
1598 $self->look if $ans eq 'l';
1599 }
1600 }
1601 }
1602
1603 sub install {
1604 my($self, $cmd, $uninst_opts, $depth) = @_;
1605
1606 if ($depth == 0 && $self->{test_only}) {
1607 return 1;
1608 }
1609
1610 local $ENV{PERL_USE_UNSAFE_INC} = 1
1611 unless exists $ENV{PERL_USE_UNSAFE_INC};
1612
1613 if ($self->{sudo}) {
1614 unshift @$cmd, "sudo";
1615 }
1616
1617 if ($self->{uninstall_shadows} && !$ENV{PERL_MM_OPT}) {
1618 push @$cmd, @$uninst_opts;
1619 }
1620
1621 $cmd = $self->append_args($cmd, 'install') if $depth == 0;
1622
1623 $self->run($cmd);
1624 }
1625
1626 sub look {
1627 my $self = shift;
1628
1629 my $shell = $ENV{SHELL};
1630 $shell ||= $ENV{COMSPEC} if WIN32;
1631 if ($shell) {
1632 my $cwd = Cwd::cwd;
1633 $self->diag("Entering $cwd with $shell\n");
1634 system $shell;
1635 } else {
1636 $self->diag_fail("You don't seem to have a SHELL :/");
1637 }
1638 }
1639
1640 sub show_build_log {
1641 my $self = shift;
1642
1643 my @pagers = (
1644 $ENV{PAGER},
1645 (WIN32 ? () : ('less')),
1646 'more'
1647 );
1648 my $pager;
1649 while (@pagers) {
1650 $pager = shift @pagers;
1651 next unless $pager;
1652 $pager = $self->which($pager);
1653 next unless $pager;
1654 last;
1655 }
1656
1657 if ($pager) {
1658 # win32 'more' doesn't allow "more build.log", the < is required
1659 system("$pager < $self->{log}");
1660 }
1661 else {
1662 $self->diag_fail("You don't seem to have a PAGER :/");
1663 }
1664 }
1665
1666 sub chdir {
1667 my $self = shift;
1668 Cwd::chdir(File::Spec->canonpath($_[0])) or die "$_[0]: $!";
1669 }
1670
1671 sub configure_mirrors {
1672 my $self = shift;
1673 unless (@{$self->{mirrors}}) {
1674 $self->{mirrors} = [ 'http://www.cpan.org' ];
1675 }
1676 for (@{$self->{mirrors}}) {
1677 s!^/!file:///!;
1678 s!/$!!;
1679 }
1680 }
1681
1682 sub self_upgrade {
1683 my $self = shift;
1684 $self->check_upgrade;
1685 $self->{argv} = [ 'App::cpanminus' ];
1686 return; # continue
1687 }
1688
1689 sub install_module {
1690 my($self, $module, $depth, $version) = @_;
1691
1692 $self->check_libs;
1693
1694 if ($self->{seen}{$module}++) {
1695 # TODO: circular dependencies
1696 $self->chat("Already tried $module. Skipping.\n");
1697 return 1;
1698 }
1699
1700 if ($self->{skip_satisfied}) {
1701 my($ok, $local) = $self->check_module($module, $version || 0);
1702 if ($ok) {
1703 $self->diag("You have $module ($local)\n", 1);
1704 return 1;
1705 }
1706 }
1707
1708 my $dist = $self->resolve_name($module, $version);
1709 unless ($dist) {
1710 my $what = $module . ($version ? " ($version)" : "");
1711 $self->diag_fail("Couldn't find module or a distribution $what", 1);
1712 return;
1713 }
1714
1715 if ($dist->{distvname} && $self->{seen}{$dist->{distvname}}++) {
1716 $self->chat("Already tried $dist->{distvname}. Skipping.\n");
1717 return 1;
1718 }
1719
1720 if ($self->{cmd} eq 'info') {
1721 print $self->format_dist($dist), "\n";
1722 return 1;
1723 }
1724
1725 $dist->{depth} = $depth; # ugly hack
1726
1727 if ($dist->{module}) {
1728 unless ($self->satisfy_version($dist->{module}, $dist->{module_version}, $version)) {
1729 $self->diag("Found $dist->{module} $dist->{module_version} which doesn't satisfy $version.\n", 1);
1730 return;
1731 }
1732
1733 # If a version is requested, it has to be the exact same version, otherwise, check as if
1734 # it is the minimum version you need.
1735 my $cmp = $version ? "==" : "";
1736 my $requirement = $dist->{module_version} ? "$cmp$dist->{module_version}" : 0;
1737 my($ok, $local) = $self->check_module($dist->{module}, $requirement);
1738 if ($self->{skip_installed} && $ok) {
1739 $self->diag("$dist->{module} is up to date. ($local)\n", 1);
1740 return 1;
1741 }
1742 }
1743
1744 if ($dist->{dist} eq 'perl'){
1745 $self->diag("skipping $dist->{pathname}\n");
1746 return 1;
1747 }
1748
1749 $self->diag("--> Working on $module\n");
1750
1751 $dist->{dir} ||= $self->fetch_module($dist);
1752
1753 unless ($dist->{dir}) {
1754 $self->diag_fail("Failed to fetch distribution $dist->{distvname}", 1);
1755 return;
1756 }
1757
1758 $self->chat("Entering $dist->{dir}\n");
1759 $self->chdir($self->{base});
1760 $self->chdir($dist->{dir});
1761
1762 if ($self->{cmd} eq 'look') {
1763 $self->look;
1764 return 1;
1765 }
1766
1767 return $self->build_stuff($module, $dist, $depth);
1768 }
1769
1770 sub uninstall_search_path {
1771 my $self = shift;
1772
1773 $self->{local_lib}
1774 ? (local::lib->install_base_arch_path($self->{local_lib}),
1775 local::lib->install_base_perl_path($self->{local_lib}))
1776 : @Config{qw(installsitearch installsitelib)};
1777 }
1778
1779 sub uninstall_module {
1780 my ($self, $module) = @_;
1781
1782 $self->check_libs;
1783
1784 my @inc = $self->uninstall_search_path;
1785
1786 my($metadata, $packlist) = $self->packlists_containing($module, \@inc);
1787 unless ($packlist) {
1788 $self->diag_fail(<<DIAG, 1);
1789 $module is not found in the following directories and can't be uninstalled.
1790
1791 @{[ join(" \n", map " $_", @inc) ]}
1792
1793 DIAG
1794 return;
1795 }
1796
1797 my @uninst_files = $self->uninstall_target($metadata, $packlist);
1798
1799 $self->ask_permission($module, \@uninst_files) or return;
1800 $self->uninstall_files(@uninst_files, $packlist);
1801
1802 $self->diag("Successfully uninstalled $module\n", 1);
1803
1804 return 1;
1805 }
1806
1807 sub packlists_containing {
1808 my($self, $module, $inc) = @_;
1809
1810 require Module::Metadata;
1811 my $metadata = Module::Metadata->new_from_module($module, inc => $inc)
1812 or return;
1813
1814 my $packlist;
1815 my $wanted = sub {
1816 return unless $_ eq '.packlist' && -f $_;
1817 for my $file ($self->unpack_packlist($File::Find::name)) {
1818 $packlist ||= $File::Find::name if $file eq $metadata->filename;
1819 }
1820 };
1821
1822 {
1823 require File::pushd;
1824 my $pushd = File::pushd::pushd();
1825 my @search = grep -d $_, map File::Spec->catdir($_, 'auto'), @$inc;
1826 File::Find::find($wanted, @search);
1827 }
1828
1829 return $metadata, $packlist;
1830 }
1831
1832 sub uninstall_target {
1833 my($self, $metadata, $packlist) = @_;
1834
1835 # If the module has a shadow install, or uses local::lib, then you can't just remove
1836 # all files in .packlist since it might have shadows in there
1837 if ($self->has_shadow_install($metadata) or $self->{local_lib}) {
1838 grep $self->should_unlink($_), $self->unpack_packlist($packlist);
1839 } else {
1840 $self->unpack_packlist($packlist);
1841 }
1842 }
1843
1844 sub has_shadow_install {
1845 my($self, $metadata) = @_;
1846
1847 # check if you have the module in site_perl *and* perl
1848 my @shadow = grep defined, map Module::Metadata->new_from_module($metadata->name, inc => [$_]), @INC;
1849 @shadow >= 2;
1850 }
1851
1852 sub should_unlink {
1853 my($self, $file) = @_;
1854
1855 # If local::lib is used, everything under the directory can be safely removed
1856 # Otherwise, bin and man files might be shared with the shadows i.e. site_perl vs perl
1857 # This is not 100% safe to keep the script there hoping to work with older version of .pm
1858 # files in the shadow, but there's nothing you can do about it.
1859 if ($self->{local_lib}) {
1860 $file =~ /^\Q$self->{local_lib}\E/;
1861 } else {
1862 !(grep $file =~ /^\Q$_\E/, @Config{qw(installbin installscript installman1dir installman3dir)});
1863 }
1864 }
1865
1866 sub ask_permission {
1867 my ($self, $module, $files) = @_;
1868
1869 $self->diag("$module contains the following files:\n\n");
1870 for my $file (@$files) {
1871 $self->diag(" $file\n");
1872 }
1873 $self->diag("\n");
1874
1875 return 'force uninstall' if $self->{force};
1876 local $self->{prompt} = 1;
1877 return $self->prompt_bool("Are you sure you want to uninstall $module?", 'y');
1878 }
1879
1880 sub unpack_packlist {
1881 my ($self, $packlist) = @_;
1882 open my $fh, '<', $packlist or die "$packlist: $!";
1883 map { chomp; $_ } <$fh>;
1884 }
1885
1886 sub uninstall_files {
1887 my ($self, @files) = @_;
1888
1889 $self->diag("\n");
1890
1891 for my $file (@files) {
1892 $self->diag("Unlink: $file\n");
1893 unlink $file or $self->diag_fail("$!: $file");
1894 }
1895
1896 $self->diag("\n");
1897
1898 return 1;
1899 }
1900
1901 sub format_dist {
1902 my($self, $dist) = @_;
1903
1904 # TODO support --dist-format?
1905 return "$dist->{cpanid}/$dist->{filename}";
1906 }
1907
1908 sub trim {
1909 local $_ = shift;
1910 tr/\n/ /d;
1911 s/^\s*|\s*$//g;
1912 $_;
1913 }
1914
1915 sub fetch_module {
1916 my($self, $dist) = @_;
1917
1918 $self->chdir($self->{base});
1919
1920 for my $uri (@{$dist->{uris}}) {
1921 $self->mask_output( diag_progress => "Fetching $uri" );
1922
1923 # Ugh, $dist->{filename} can contain sub directory
1924 my $filename = $dist->{filename} || $uri;
1925 my $name = File::Basename::basename($filename);
1926
1927 my $cancelled;
1928 my $fetch = sub {
1929 my $file;
1930 eval {
1931 local $SIG{INT} = sub { $cancelled = 1; die "SIGINT\n" };
1932 $self->mirror($uri, $name);
1933 $file = $name if -e $name;
1934 };
1935 $self->diag("ERROR: " . trim("$@") . "\n", 1) if $@ && $@ ne "SIGINT\n";
1936 return $file;
1937 };
1938
1939 my($try, $file);
1940 while ($try++ < 3) {
1941 $file = $fetch->();
1942 last if $cancelled or $file;
1943 $self->mask_output( diag_fail => "Download $uri failed. Retrying ... ");
1944 }
1945
1946 if ($cancelled) {
1947 $self->diag_fail("Download cancelled.");
1948 return;
1949 }
1950
1951 unless ($file) {
1952 $self->mask_output( diag_fail => "Failed to download $uri");
1953 next;
1954 }
1955
1956 $self->diag_ok;
1957 $dist->{local_path} = File::Spec->rel2abs($name);
1958
1959 my $dir = $self->unpack($file, $uri, $dist);
1960 next unless $dir; # unpack failed
1961
1962 if (my $save = $self->{save_dists}) {
1963 # Only distros retrieved from CPAN have a pathname set
1964 my $path = $dist->{pathname} ? "$save/authors/id/$dist->{pathname}"
1965 : "$save/vendor/$file";
1966 $self->chat("Copying $name to $path\n");
1967 File::Path::mkpath([ File::Basename::dirname($path) ], 0, 0777);
1968 File::Copy::copy($file, $path) or warn $!;
1969 }
1970
1971 return $dist, $dir;
1972 }
1973 }
1974
1975 sub unpack {
1976 my($self, $file, $uri, $dist) = @_;
1977
1978 if ($self->{verify}) {
1979 $self->verify_archive($file, $uri, $dist) or return;
1980 }
1981
1982 $self->chat("Unpacking $file\n");
1983 my $dir = $file =~ /\.zip/i ? $self->unzip($file) : $self->untar($file);
1984 unless ($dir) {
1985 $self->diag_fail("Failed to unpack $file: no directory");
1986 }
1987 return $dir;
1988 }
1989
1990 sub verify_archive {
1991 my($self, $file, $uri, $dist) = @_;
1992
1993 unless ($dist->{cpanid}) {
1994 $self->chat("Archive '$file' does not seem to be from PAUSE. Skip verification.\n");
1995 return 1;
1996 }
1997
1998 (my $mirror = $uri) =~ s!/authors/id.*$!!;
1999
2000 (my $chksum_uri = $uri) =~ s!/[^/]*$!/CHECKSUMS!;
2001 my $chk_file = $self->source_for($mirror) . "/$dist->{cpanid}.CHECKSUMS";
2002 $self->mask_output( diag_progress => "Fetching $chksum_uri" );
2003 $self->mirror($chksum_uri, $chk_file);
2004
2005 unless (-e $chk_file) {
2006 $self->diag_fail("Fetching $chksum_uri failed.\n");
2007 return;
2008 }
2009
2010 $self->diag_ok;
2011 $self->verify_checksum($file, $chk_file);
2012 }
2013
2014 sub verify_checksum {
2015 my($self, $file, $chk_file) = @_;
2016
2017 $self->chat("Verifying the SHA1 for $file\n");
2018
2019 open my $fh, "<$chk_file" or die "$chk_file: $!";
2020 my $data = join '', <$fh>;
2021 $data =~ s/\015?\012/\n/g;
2022
2023 require Safe; # no fatpack
2024 my $chksum = Safe->new->reval($data);
2025
2026 if (!ref $chksum or ref $chksum ne 'HASH') {
2027 $self->diag_fail("! Checksum file downloaded from $chk_file is broken.\n");
2028 return;
2029 }
2030
2031 if (my $sha = $chksum->{$file}{sha256}) {
2032 my $hex = $self->sha1_for($file);
2033 if ($hex eq $sha) {
2034 $self->chat("Checksum for $file: Verified!\n");
2035 } else {
2036 $self->diag_fail("Checksum mismatch for $file\n");
2037 return;
2038 }
2039 } else {
2040 $self->chat("Checksum for $file not found in CHECKSUMS.\n");
2041 return;
2042 }
2043 }
2044
2045 sub sha1_for {
2046 my($self, $file) = @_;
2047
2048 require Digest::SHA; # no fatpack
2049
2050 open my $fh, "<", $file or die "$file: $!";
2051 my $dg = Digest::SHA->new(256);
2052 my($data);
2053 while (read($fh, $data, 4096)) {
2054 $dg->add($data);
2055 }
2056
2057 return $dg->hexdigest;
2058 }
2059
2060 sub verify_signature {
2061 my($self, $dist) = @_;
2062
2063 $self->diag_progress("Verifying the SIGNATURE file");
2064 my $out = `$self->{cpansign} -v --skip 2>&1`;
2065 $self->log($out);
2066
2067 if ($out =~ /Signature verified OK/) {
2068 $self->diag_ok("Verified OK");
2069 return 1;
2070 } else {
2071 $self->diag_fail("SIGNATURE verification for $dist->{filename} failed\n");
2072 return;
2073 }
2074 }
2075
2076 sub resolve_name {
2077 my($self, $module, $version) = @_;
2078
2079 # Git
2080 if ($module =~ /(?:^git:|\.git(?:@.+)?$)/) {
2081 return $self->git_uri($module);
2082 }
2083
2084 # URL
2085 if ($module =~ /^(ftp|https?|file):/) {
2086 if ($module =~ m!authors/id/(.*)!) {
2087 return $self->cpan_dist($1, $module);
2088 } else {
2089 return { uris => [ $module ] };
2090 }
2091 }
2092
2093 # Directory
2094 if ($module =~ m!^[\./]! && -d $module) {
2095 return {
2096 source => 'local',
2097 dir => Cwd::abs_path($module),
2098 };
2099 }
2100
2101 # File
2102 if (-f $module) {
2103 return {
2104 source => 'local',
2105 uris => [ "file://" . Cwd::abs_path($module) ],
2106 };
2107 }
2108
2109 # cpan URI
2110 if ($module =~ s!^cpan:///distfile/!!) {
2111 return $self->cpan_dist($module);
2112 }
2113
2114 # PAUSEID/foo
2115 # P/PA/PAUSEID/foo
2116 if ($module =~ m!^(?:[A-Z]/[A-Z]{2}/)?([A-Z]{2}[\-A-Z0-9]*/.*)$!) {
2117 return $self->cpan_dist($1);
2118 }
2119
2120 # Module name
2121 return $self->search_module($module, $version);
2122 }
2123
2124 sub cpan_module {
2125 my($self, $module, $dist_file, $version) = @_;
2126
2127 my $dist = $self->cpan_dist($dist_file);
2128 $dist->{module} = $module;
2129 $dist->{module_version} = $version if $version && $version ne 'undef';
2130
2131 return $dist;
2132 }
2133
2134 sub cpan_dist {
2135 my($self, $dist, $url) = @_;
2136
2137 $dist =~ s!^([A-Z]{2})!substr($1,0,1)."/".substr($1,0,2)."/".$1!e;
2138
2139 require CPAN::DistnameInfo;
2140 my $d = CPAN::DistnameInfo->new($dist);
2141
2142 if ($url) {
2143 $url = [ $url ] unless ref $url eq 'ARRAY';
2144 } else {
2145 my $id = $d->cpanid;
2146 my $fn = substr($id, 0, 1) . "/" . substr($id, 0, 2) . "/" . $id . "/" . $d->filename;
2147
2148 my @mirrors = @{$self->{mirrors}};
2149 my @urls = map "$_/authors/id/$fn", @mirrors;
2150
2151 $url = \@urls,
2152 }
2153
2154 return {
2155 $d->properties,
2156 source => 'cpan',
2157 uris => $url,
2158 };
2159 }
2160
2161 sub git_uri {
2162 my ($self, $uri) = @_;
2163
2164 # similar to http://www.pip-installer.org/en/latest/logic.html#vcs-support
2165 # git URL has to end with .git when you need to use pin @ commit/tag/branch
2166
2167 ($uri, my $commitish) = split /(?<=\.git)@/i, $uri, 2;
2168
2169 my $dir = File::Temp::tempdir(CLEANUP => 1);
2170
2171 $self->mask_output( diag_progress => "Cloning $uri" );
2172 $self->run([ 'git', 'clone', $uri, $dir ]);
2173
2174 unless (-e "$dir/.git") {
2175 $self->diag_fail("Failed cloning git repository $uri", 1);
2176 return;
2177 }
2178
2179 if ($commitish) {
2180 require File::pushd;
2181 my $dir = File::pushd::pushd($dir);
2182
2183 unless ($self->run([ 'git', 'checkout', $commitish ])) {
2184 $self->diag_fail("Failed to checkout '$commitish' in git repository $uri\n");
2185 return;
2186 }
2187 }
2188
2189 $self->diag_ok;
2190
2191 return {
2192 source => 'local',
2193 dir => $dir,
2194 };
2195 }
2196
2197 sub setup_module_build_patch {
2198 my $self = shift;
2199
2200 open my $out, ">$self->{base}/ModuleBuildSkipMan.pm" or die $!;
2201 print $out <<EOF;
2202 package ModuleBuildSkipMan;
2203 CHECK {
2204 if (%Module::Build::) {
2205 no warnings 'redefine';
2206 *Module::Build::Base::ACTION_manpages = sub {};
2207 *Module::Build::Base::ACTION_docs = sub {};
2208 }
2209 }
2210 1;
2211 EOF
2212 }
2213
2214 sub core_version_for {
2215 my($self, $module) = @_;
2216
2217 require Module::CoreList; # no fatpack
2218 unless (exists $Module::CoreList::version{$]+0}) {
2219 die sprintf("Module::CoreList %s (loaded from %s) doesn't seem to have entries for perl $]. " .
2220 "You're strongly recommended to upgrade Module::CoreList from CPAN.\n",
2221 $Module::CoreList::VERSION, $INC{"Module/CoreList.pm"});
2222 }
2223
2224 unless (exists $Module::CoreList::version{$]+0}{$module}) {
2225 return -1;
2226 }
2227
2228 return $Module::CoreList::version{$]+0}{$module};
2229 }
2230
2231 sub search_inc {
2232 my $self = shift;
2233 $self->{search_inc} ||= do {
2234 # strip lib/ and fatlib/ from search path when booted from dev
2235 if (defined $::Bin) {
2236 [grep !/^\Q$::Bin\E\/..\/(?:fat)?lib$/, @INC]
2237 } else {
2238 [@INC]
2239 }
2240 };
2241 }
2242
2243 sub check_module {
2244 my($self, $mod, $want_ver) = @_;
2245
2246 require Module::Metadata;
2247 my $meta = Module::Metadata->new_from_module($mod, inc => $self->search_inc)
2248 or return 0, undef;
2249
2250 my $version = $meta->version;
2251
2252 # When -L is in use, the version loaded from 'perl' library path
2253 # might be newer than (or actually wasn't core at) the version
2254 # that is shipped with the current perl
2255 if ($self->{self_contained} && $self->loaded_from_perl_lib($meta)) {
2256 $version = $self->core_version_for($mod);
2257 return 0, undef if $version && $version == -1;
2258 }
2259
2260 $self->{local_versions}{$mod} = $version;
2261
2262 if ($self->is_deprecated($meta)){
2263 return 0, $version;
2264 } elsif ($self->satisfy_version($mod, $version, $want_ver)) {
2265 return 1, ($version || 'undef');
2266 } else {
2267 return 0, $version;
2268 }
2269 }
2270
2271 sub satisfy_version {
2272 my($self, $mod, $version, $want_ver) = @_;
2273
2274 $want_ver = '0' unless defined($want_ver) && length($want_ver);
2275
2276 require CPAN::Meta::Requirements;
2277 my $requirements = CPAN::Meta::Requirements->new;
2278 $requirements->add_string_requirement($mod, $want_ver);
2279 $requirements->accepts_module($mod, $version);
2280 }
2281
2282 sub unsatisfy_how {
2283 my($self, $ver, $want_ver) = @_;
2284
2285 if ($want_ver =~ /^[v0-9\.\_]+$/) {
2286 return "$ver < $want_ver";
2287 } else {
2288 return "$ver doesn't satisfy $want_ver";
2289 }
2290 }
2291
2292 sub is_deprecated {
2293 my($self, $meta) = @_;
2294
2295 my $deprecated = eval {
2296 require Module::CoreList; # no fatpack
2297 Module::CoreList::is_deprecated($meta->{module});
2298 };
2299
2300 return $deprecated && $self->loaded_from_perl_lib($meta);
2301 }
2302
2303 sub loaded_from_perl_lib {
2304 my($self, $meta) = @_;
2305
2306 require Config;
2307 my @dirs = qw(archlibexp privlibexp);
2308 if ($self->{self_contained} && ! $self->{exclude_vendor} && $Config{vendorarch}) {
2309 unshift @dirs, qw(vendorarch vendorlibexp);
2310 }
2311 for my $dir (@dirs) {
2312 my $confdir = $Config{$dir};
2313 if ($confdir eq substr($meta->filename, 0, length($confdir))) {
2314 return 1;
2315 }
2316 }
2317
2318 return;
2319 }
2320
2321 sub should_install {
2322 my($self, $mod, $ver) = @_;
2323
2324 $self->chat("Checking if you have $mod $ver ... ");
2325 my($ok, $local) = $self->check_module($mod, $ver);
2326
2327 if ($ok) { $self->chat("Yes ($local)\n") }
2328 elsif ($local) { $self->chat("No (" . $self->unsatisfy_how($local, $ver) . ")\n") }
2329 else { $self->chat("No\n") }
2330
2331 return $mod unless $ok;
2332 return;
2333 }
2334
2335 sub check_perl_version {
2336 my($self, $version) = @_;
2337 require CPAN::Meta::Requirements;
2338 my $req = CPAN::Meta::Requirements->from_string_hash({ perl => $version });
2339 $req->accepts_module(perl => $]);
2340 }
2341
2342 sub install_deps {
2343 my($self, $dir, $depth, @deps) = @_;
2344
2345 my(@install, %seen, @fail);
2346 for my $dep (@deps) {
2347 next if $seen{$dep->module};
2348 if ($dep->module eq 'perl') {
2349 if ($dep->is_requirement && !$self->check_perl_version($dep->version)) {
2350 $self->diag("Needs perl @{[$dep->version]}, you have $]\n");
2351 push @fail, 'perl';
2352 }
2353 } elsif ($self->should_install($dep->module, $dep->version)) {
2354 push @install, $dep;
2355 $seen{$dep->module} = 1;
2356 }
2357 }
2358
2359 if (@install) {
2360 $self->diag("==> Found dependencies: " . join(", ", map $_->module, @install) . "\n");
2361 }
2362
2363 for my $dep (@install) {
2364 $self->install_module($dep->module, $depth + 1, $dep->version);
2365 }
2366
2367 $self->chdir($self->{base});
2368 $self->chdir($dir) if $dir;
2369
2370 if ($self->{scandeps}) {
2371 return 1; # Don't check if dependencies are installed, since with --scandeps they aren't
2372 }
2373 my @not_ok = $self->unsatisfied_deps(@deps);
2374 if (@not_ok) {
2375 return 0, \@not_ok;
2376 } else {
2377 return 1;
2378 }
2379 }
2380
2381 sub unsatisfied_deps {
2382 my($self, @deps) = @_;
2383
2384 require CPAN::Meta::Check;
2385 require CPAN::Meta::Requirements;
2386
2387 my $reqs = CPAN::Meta::Requirements->new;
2388 for my $dep (grep $_->is_requirement, @deps) {
2389 $reqs->add_string_requirement($dep->module => $dep->requires_version || '0');
2390 }
2391
2392 my $ret = CPAN::Meta::Check::check_requirements($reqs, 'requires', $self->{search_inc});
2393 grep defined, values %$ret;
2394 }
2395
2396 sub install_deps_bailout {
2397 my($self, $target, $dir, $depth, @deps) = @_;
2398
2399 my($ok, $fail) = $self->install_deps($dir, $depth, @deps);
2400 if (!$ok) {
2401 $self->diag_fail("Installing the dependencies failed: " . join(", ", @$fail), 1);
2402 unless ($self->prompt_bool("Do you want to continue building $target anyway?", "n")) {
2403 $self->diag_fail("Bailing out the installation for $target.", 1);
2404 return;
2405 }
2406 }
2407
2408 return 1;
2409 }
2410
2411 sub build_stuff {
2412 my($self, $stuff, $dist, $depth) = @_;
2413
2414 if ($self->{verify} && -e 'SIGNATURE') {
2415 $self->verify_signature($dist) or return;
2416 }
2417
2418 require CPAN::Meta;
2419
2420 my($meta_file) = grep -f, qw(META.json META.yml);
2421 if ($meta_file) {
2422 $self->chat("Checking configure dependencies from $meta_file\n");
2423 $dist->{cpanmeta} = eval { CPAN::Meta->load_file($meta_file) };
2424 } elsif ($dist->{dist} && $dist->{version}) {
2425 $self->chat("META.yml/json not found. Creating skeleton for it.\n");
2426 $dist->{cpanmeta} = CPAN::Meta->new({ name => $dist->{dist}, version => $dist->{version} });
2427 }
2428
2429 $dist->{meta} = $dist->{cpanmeta} ? $dist->{cpanmeta}->as_struct : {};
2430
2431 my @config_deps;
2432
2433 if ($dist->{cpanmeta}) {
2434 push @config_deps, App::cpanminus::Dependency->from_prereqs(
2435 $dist->{cpanmeta}->effective_prereqs, ['configure'], $self->{install_types},
2436 );
2437 }
2438
2439 if (-e 'Build.PL' && !$self->should_use_mm($dist->{dist}) && !@config_deps) {
2440 push @config_deps, App::cpanminus::Dependency->from_versions(
2441 { 'Module::Build' => '0.38' }, 'configure',
2442 );
2443 }
2444
2445 $self->merge_with_cpanfile($dist, \@config_deps);
2446
2447 $self->upgrade_toolchain(\@config_deps);
2448
2449 my $target = $dist->{meta}{name} ? "$dist->{meta}{name}-$dist->{meta}{version}" : $dist->{dir};
2450 {
2451 $self->install_deps_bailout($target, $dist->{dir}, $depth, @config_deps)
2452 or return;
2453 }
2454
2455 $self->diag_progress("Configuring $target");
2456
2457 my $configure_state = $self->configure_this($dist, $depth);
2458 $self->diag_ok($configure_state->{configured_ok} ? "OK" : "N/A");
2459
2460 if ($dist->{cpanmeta} && $dist->{source} eq 'cpan') {
2461 $dist->{provides} = $dist->{cpanmeta}{provides} || $self->extract_packages($dist->{cpanmeta}, ".");
2462 }
2463
2464 # install direct 'test' dependencies for --installdeps, even with --notest
2465 my $root_target = (($self->{installdeps} or $self->{showdeps}) and $depth == 0);
2466 $dist->{want_phases} = $self->{notest} && !$root_target
2467 ? [qw( build runtime )] : [qw( build test runtime )];
2468
2469 push @{$dist->{want_phases}}, 'develop' if $self->{with_develop} && $depth == 0;
2470 push @{$dist->{want_phases}}, 'configure' if $self->{with_configure} && $depth == 0;
2471
2472 my @deps = $self->find_prereqs($dist);
2473 my $module_name = $self->find_module_name($configure_state) || $dist->{meta}{name};
2474 $module_name =~ s/-/::/g;
2475
2476 if ($self->{showdeps}) {
2477 for my $dep (@config_deps, @deps) {
2478 print $dep->module, ($dep->version ? ("~".$dep->version) : ""), "\n";
2479 }
2480 return 1;
2481 }
2482
2483 my $distname = $dist->{meta}{name} ? "$dist->{meta}{name}-$dist->{meta}{version}" : $stuff;
2484
2485 my $walkup;
2486 if ($self->{scandeps}) {
2487 $walkup = $self->scandeps_append_child($dist);
2488 }
2489
2490 $self->install_deps_bailout($distname, $dist->{dir}, $depth, @deps)
2491 or return;
2492
2493 if ($self->{scandeps}) {
2494 unless ($configure_state->{configured_ok}) {
2495 my $diag = <<DIAG;
2496 ! Configuring $distname failed. See $self->{log} for details.
2497 ! You might have to install the following modules first to get --scandeps working correctly.
2498 DIAG
2499 if (@config_deps) {
2500 my @tree = @{$self->{scandeps_tree}};
2501 $diag .= "!\n" . join("", map "! * $_->[0]{module}\n", @tree[0..$#tree-1]) if @tree;
2502 }
2503 $self->diag("!\n$diag!\n", 1);
2504 }
2505 $walkup->();
2506 return 1;
2507 }
2508
2509 if ($self->{installdeps} && $depth == 0) {
2510 if ($configure_state->{configured_ok}) {
2511 $self->diag("<== Installed dependencies for $stuff. Finishing.\n");
2512 return 1;
2513 } else {
2514 $self->diag("! Configuring $distname failed. See $self->{log} for details.\n", 1);
2515 return;
2516 }
2517 }
2518
2519 my $installed;
2520 if ($configure_state->{use_module_build} && -e 'Build' && -f _) {
2521 $self->diag_progress("Building " . ($self->{notest} ? "" : "and testing ") . $distname);
2522 $self->build([ $self->{perl}, "./Build" ], $distname, $depth) &&
2523 $self->test([ $self->{perl}, "./Build", "test" ], $distname, $depth) &&
2524 $self->install([ $self->{perl}, "./Build", "install" ], [ "--uninst", 1 ], $depth) &&
2525 $installed++;
2526 } elsif ($self->{make} && -e 'Makefile') {
2527 $self->diag_progress("Building " . ($self->{notest} ? "" : "and testing ") . $distname);
2528 $self->build([ $self->{make} ], $distname, $depth) &&
2529 $self->test([ $self->{make}, "test" ], $distname, $depth) &&
2530 $self->install([ $self->{make}, "install" ], [ "UNINST=1" ], $depth) &&
2531 $installed++;
2532 } else {
2533 my $why;
2534 my $configure_failed = $configure_state->{configured} && !$configure_state->{configured_ok};
2535 if ($configure_failed) { $why = "Configure failed for $distname." }
2536 elsif ($self->{make}) { $why = "The distribution doesn't have a proper Makefile.PL/Build.PL" }
2537 else { $why = "Can't configure the distribution. You probably need to have 'make'." }
2538
2539 $self->diag_fail("$why See $self->{log} for details.", 1);
2540 return;
2541 }
2542
2543 if ($installed && $self->{test_only}) {
2544 $self->diag_ok;
2545 $self->diag("Successfully tested $distname\n", 1);
2546 } elsif ($installed) {
2547 my $local = $self->{local_versions}{$dist->{module} || ''};
2548 my $version = $dist->{module_version} || $dist->{meta}{version} || $dist->{version};
2549 my $reinstall = $local && ($local eq $version);
2550 my $action = $local && !$reinstall
2551 ? $self->numify_ver($version) < $self->numify_ver($local)
2552 ? "downgraded"
2553 : "upgraded"
2554 : undef;
2555
2556 my $how = $reinstall ? "reinstalled $distname"
2557 : $local ? "installed $distname ($action from $local)"
2558 : "installed $distname" ;
2559 my $msg = "Successfully $how";
2560 $self->diag_ok;
2561 $self->diag("$msg\n", 1);
2562 $self->{installed_dists}++;
2563 $self->save_meta($stuff, $dist, $module_name, \@config_deps, \@deps);
2564 return 1;
2565 } else {
2566 my $what = $self->{test_only} ? "Testing" : "Installing";
2567 $self->diag_fail("$what $stuff failed. See $self->{log} for details. Retry with --force to force install it.", 1);
2568 return;
2569 }
2570 }
2571
2572 sub perl_requirements {
2573 my($self, @requires) = @_;
2574
2575 my @perl;
2576 for my $requires (grep defined, @requires) {
2577 if (exists $requires->{perl}) {
2578 push @perl, App::cpanminus::Dependency->new(perl => $requires->{perl});
2579 }
2580 }
2581
2582 return @perl;
2583 }
2584
2585 sub should_use_mm {
2586 my($self, $dist) = @_;
2587
2588 # Module::Build deps should use MakeMaker because that causes circular deps and fail
2589 # Otherwise we should prefer Build.PL
2590 my %should_use_mm = map { $_ => 1 } qw( version ExtUtils-ParseXS ExtUtils-Install ExtUtils-Manifest );
2591
2592 $should_use_mm{$dist};
2593 }
2594
2595 sub configure_this {
2596 my($self, $dist, $depth) = @_;
2597
2598 # Short-circuit `cpanm --installdeps .` because it doesn't need to build the current dir
2599 if (-e $self->{cpanfile_path} && $self->{installdeps} && $depth == 0) {
2600 require Module::CPANfile;
2601 $dist->{cpanfile} = eval { Module::CPANfile->load($self->{cpanfile_path}) };
2602 $self->diag_fail($@, 1) if $@;
2603 return {
2604 configured => 1,
2605 configured_ok => !!$dist->{cpanfile},
2606 use_module_build => 0,
2607 };
2608 }
2609
2610 if ($self->{skip_configure}) {
2611 my $eumm = -e 'Makefile';
2612 my $mb = -e 'Build' && -f _;
2613 return {
2614 configured => 1,
2615 configured_ok => $eumm || $mb,
2616 use_module_build => $mb,
2617 };
2618 }
2619
2620 my $state = {};
2621
2622 my $try_eumm = sub {
2623 if (-e 'Makefile.PL') {
2624 $self->chat("Running Makefile.PL\n");
2625
2626 # NOTE: according to Devel::CheckLib, most XS modules exit
2627 # with 0 even if header files are missing, to avoid receiving
2628 # tons of FAIL reports in such cases. So exit code can't be
2629 # trusted if it went well.
2630 if ($self->configure([ $self->{perl}, "Makefile.PL" ], $depth)) {
2631 $state->{configured_ok} = -e 'Makefile';
2632 }
2633 $state->{configured}++;
2634 }
2635 };
2636
2637 my $try_mb = sub {
2638 if (-e 'Build.PL') {
2639 $self->chat("Running Build.PL\n");
2640 if ($self->configure([ $self->{perl}, "Build.PL" ], $depth)) {
2641 $state->{configured_ok} = -e 'Build' && -f _;
2642 }
2643 $state->{use_module_build}++;
2644 $state->{configured}++;
2645 }
2646 };
2647
2648 my @try;
2649 if ($dist->{dist} && $self->should_use_mm($dist->{dist})) {
2650 @try = ($try_eumm, $try_mb);
2651 } else {
2652 @try = ($try_mb, $try_eumm);
2653 }
2654
2655 for my $try (@try) {
2656 $try->();
2657 last if $state->{configured_ok};
2658 }
2659
2660 unless ($state->{configured_ok}) {
2661 while (1) {
2662 my $ans = lc $self->prompt("Configuring $dist->{dist} failed.\nYou can s)kip, r)etry, e)xamine build log, or l)ook ?", "s");
2663 last if $ans eq 's';
2664 return $self->configure_this($dist, $depth) if $ans eq 'r';
2665 $self->show_build_log if $ans eq 'e';
2666 $self->look if $ans eq 'l';
2667 }
2668 }
2669
2670 return $state;
2671 }
2672
2673 sub find_module_name {
2674 my($self, $state) = @_;
2675
2676 return unless $state->{configured_ok};
2677
2678 if ($state->{use_module_build} &&
2679 -e "_build/build_params") {
2680 my $params = do { open my $in, "_build/build_params"; $self->safe_eval(join "", <$in>) };
2681 return eval { $params->[2]{module_name} } || undef;
2682 } elsif (-e "Makefile") {
2683 open my $mf, "Makefile";
2684 while (<$mf>) {
2685 if (/^\#\s+NAME\s+=>\s+(.*)/) {
2686 return $self->safe_eval($1);
2687 }
2688 }
2689 }
2690
2691 return;
2692 }
2693
2694 sub list_files {
2695 my $self = shift;
2696
2697 if (-e 'MANIFEST') {
2698 require ExtUtils::Manifest;
2699 my $manifest = eval { ExtUtils::Manifest::manifind() } || {};
2700 return sort { lc $a cmp lc $b } keys %$manifest;
2701 } else {
2702 require File::Find;
2703 my @files;
2704 my $finder = sub {
2705 my $name = $File::Find::name;
2706 $name =~ s!\.[/\\]!!;
2707 push @files, $name;
2708 };
2709 File::Find::find($finder, ".");
2710 return sort { lc $a cmp lc $b } @files;
2711 }
2712 }
2713
2714 sub extract_packages {
2715 my($self, $meta, $dir) = @_;
2716
2717 my $try = sub {
2718 my $file = shift;
2719 return 0 if $file =~ m!^(?:x?t|inc|local|perl5|fatlib|_build)/!;
2720 return 1 unless $meta->{no_index};
2721 return 0 if grep { $file =~ m!^$_/! } @{$meta->{no_index}{directory} || []};
2722 return 0 if grep { $file eq $_ } @{$meta->{no_index}{file} || []};
2723 return 1;
2724 };
2725
2726 require Parse::PMFile;
2727
2728 my @files = grep { /\.pm(?:\.PL)?$/ && $try->($_) } $self->list_files;
2729
2730 my $provides = { };
2731
2732 for my $file (@files) {
2733 my $parser = Parse::PMFile->new($meta, { UNSAFE => 1, ALLOW_DEV_VERSION => 1 });
2734 my $packages = $parser->parse($file);
2735
2736 while (my($package, $meta) = each %$packages) {
2737 $provides->{$package} ||= {
2738 file => $meta->{infile},
2739 ($meta->{version} eq 'undef') ? () : (version => $meta->{version}),
2740 };
2741 }
2742 }
2743
2744 return $provides;
2745 }
2746
2747 sub save_meta {
2748 my($self, $module, $dist, $module_name, $config_deps, $build_deps) = @_;
2749
2750 return unless $dist->{distvname} && $dist->{source} eq 'cpan';
2751
2752 my $base = ($ENV{PERL_MM_OPT} || '') =~ /INSTALL_BASE=/
2753 ? ($self->install_base($ENV{PERL_MM_OPT}) . "/lib/perl5") : $Config{sitelibexp};
2754
2755 my $provides = $dist->{provides};
2756
2757 File::Path::mkpath("blib/meta", 0, 0777);
2758
2759 my $local = {
2760 name => $module_name,
2761 target => $module,
2762 version => exists $provides->{$module_name}
2763 ? ($provides->{$module_name}{version} || $dist->{version}) : $dist->{version},
2764 dist => $dist->{distvname},
2765 pathname => $dist->{pathname},
2766 provides => $provides,
2767 };
2768
2769 require JSON::PP;
2770 open my $fh, ">", "blib/meta/install.json" or die $!;
2771 print $fh JSON::PP::encode_json($local);
2772
2773 # Existence of MYMETA.* Depends on EUMM/M::B versions and CPAN::Meta
2774 if (-e "MYMETA.json") {
2775 File::Copy::copy("MYMETA.json", "blib/meta/MYMETA.json");
2776 }
2777
2778 my @cmd = (
2779 ($self->{sudo} ? 'sudo' : ()),
2780 $^X,
2781 '-MExtUtils::Install=install',
2782 '-e',
2783 qq[install({ 'blib/meta' => '$base/$Config{archname}/.meta/$dist->{distvname}' })],
2784 );
2785 $self->run(\@cmd);
2786 }
2787
2788 sub _merge_hashref {
2789 my($self, @hashrefs) = @_;
2790
2791 my %hash;
2792 for my $h (@hashrefs) {
2793 %hash = (%hash, %$h);
2794 }
2795
2796 return \%hash;
2797 }
2798
2799 sub install_base {
2800 my($self, $mm_opt) = @_;
2801 $mm_opt =~ /INSTALL_BASE=(\S+)/ and return $1;
2802 die "Your PERL_MM_OPT doesn't contain INSTALL_BASE";
2803 }
2804
2805 sub safe_eval {
2806 my($self, $code) = @_;
2807 eval $code;
2808 }
2809
2810 sub configure_features {
2811 my($self, $dist, @features) = @_;
2812 map $_->identifier, grep { $self->effective_feature($dist, $_) } @features;
2813 }
2814
2815 sub effective_feature {
2816 my($self, $dist, $feature) = @_;
2817
2818 if ($dist->{depth} == 0) {
2819 my $value = $self->{features}{$feature->identifier};
2820 return $value if defined $value;
2821 return 1 if $self->{features}{__all};
2822 }
2823
2824 if ($self->{interactive}) {
2825 require CPAN::Meta::Requirements;
2826
2827 $self->diag("[@{[ $feature->description ]}]\n", 1);
2828
2829 my $req = CPAN::Meta::Requirements->new;
2830 for my $phase (@{$dist->{want_phases}}) {
2831 for my $type (@{$self->{install_types}}) {
2832 $req->add_requirements($feature->prereqs->requirements_for($phase, $type));
2833 }
2834 }
2835
2836 my $reqs = $req->as_string_hash;
2837 my @missing;
2838 for my $module (keys %$reqs) {
2839 if ($self->should_install($module, $req->{$module})) {
2840 push @missing, $module;
2841 }
2842 }
2843
2844 if (@missing) {
2845 my $howmany = @missing;
2846 $self->diag("==> Found missing dependencies: " . join(", ", @missing) . "\n", 1);
2847 local $self->{prompt} = 1;
2848 return $self->prompt_bool("Install the $howmany optional module(s)?", "y");
2849 }
2850 }
2851
2852 return;
2853 }
2854
2855 sub find_prereqs {
2856 my($self, $dist) = @_;
2857
2858 my @deps = $self->extract_meta_prereqs($dist);
2859
2860 if ($dist->{module} =~ /^Bundle::/i) {
2861 push @deps, $self->bundle_deps($dist);
2862 }
2863
2864 $self->merge_with_cpanfile($dist, \@deps);
2865
2866 return @deps;
2867 }
2868
2869 sub merge_with_cpanfile {
2870 my($self, $dist, $deps) = @_;
2871
2872 if ($self->{cpanfile_requirements} && !$dist->{cpanfile}) {
2873 for my $dep (@$deps) {
2874 $dep->merge_with($self->{cpanfile_requirements});
2875 }
2876 }
2877 }
2878
2879 sub extract_meta_prereqs {
2880 my($self, $dist) = @_;
2881
2882 if ($dist->{cpanfile}) {
2883 my @features = $self->configure_features($dist, $dist->{cpanfile}->features);
2884 my $prereqs = $dist->{cpanfile}->prereqs_with(@features);
2885 # TODO: creating requirements is useful even without cpanfile to detect conflicting prereqs
2886 $self->{cpanfile_requirements} = $prereqs->merged_requirements($dist->{want_phases}, ['requires']);
2887 return App::cpanminus::Dependency->from_prereqs($prereqs, $dist->{want_phases}, $self->{install_types});
2888 }
2889
2890 require CPAN::Meta;
2891
2892 my @deps;
2893 my($meta_file) = grep -f, qw(MYMETA.json MYMETA.yml);
2894 if ($meta_file) {
2895 $self->chat("Checking dependencies from $meta_file ...\n");
2896 my $mymeta = eval { CPAN::Meta->load_file($meta_file, { lazy_validation => 1 }) };
2897 if ($mymeta) {
2898 $dist->{meta}{name} = $mymeta->name;
2899 $dist->{meta}{version} = $mymeta->version;
2900 return $self->extract_prereqs($mymeta, $dist);
2901 }
2902 }
2903
2904 if (-e '_build/prereqs') {
2905 $self->chat("Checking dependencies from _build/prereqs ...\n");
2906 my $prereqs = do { open my $in, "_build/prereqs"; $self->safe_eval(join "", <$in>) };
2907 my $meta = CPAN::Meta->new(
2908 { name => $dist->{meta}{name}, version => $dist->{meta}{version}, %$prereqs },
2909 { lazy_validation => 1 },
2910 );
2911 @deps = $self->extract_prereqs($meta, $dist);
2912 } elsif (-e 'Makefile') {
2913 $self->chat("Finding PREREQ from Makefile ...\n");
2914 open my $mf, "Makefile";
2915 while (<$mf>) {
2916 if (/^\#\s+PREREQ_PM => \{\s*(.*?)\s*\}/) {
2917 my @all;
2918 my @pairs = split ', ', $1;
2919 for (@pairs) {
2920 my ($pkg, $v) = split '=>', $_;
2921 push @all, [ $pkg, $v ];
2922 }
2923 my $list = join ", ", map { "'$_->[0]' => $_->[1]" } @all;
2924 my $prereq = $self->safe_eval("no strict; +{ $list }");
2925 push @deps, App::cpanminus::Dependency->from_versions($prereq) if $prereq;
2926 last;
2927 }
2928 }
2929 }
2930
2931 return @deps;
2932 }
2933
2934 sub bundle_deps {
2935 my($self, $dist) = @_;
2936
2937 my $match;
2938 if ($dist->{module}) {
2939 $match = sub {
2940 my $meta = Module::Metadata->new_from_file($_[0]);
2941 $meta && ($meta->name eq $dist->{module});
2942 };
2943 } else {
2944 $match = sub { 1 };
2945 }
2946
2947 my @files;
2948 File::Find::find({
2949 wanted => sub {
2950 push @files, File::Spec->rel2abs($_) if /\.pm$/i && $match->($_);
2951 },
2952 no_chdir => 1,
2953 }, '.');
2954
2955 my @deps;
2956
2957 for my $file (@files) {
2958 open my $pod, "<", $file or next;
2959 my $in_contents;
2960 while (<$pod>) {
2961 if (/^=head\d\s+CONTENTS/) {
2962 $in_contents = 1;
2963 } elsif (/^=/) {
2964 $in_contents = 0;
2965 } elsif ($in_contents) {
2966 /^(\S+)\s*(\S+)?/
2967 and push @deps, App::cpanminus::Dependency->new($1, $self->maybe_version($2));
2968 }
2969 }
2970 }
2971
2972 return @deps;
2973 }
2974
2975 sub maybe_version {
2976 my($self, $string) = @_;
2977 return $string && $string =~ /^\.?\d/ ? $string : undef;
2978 }
2979
2980 sub extract_prereqs {
2981 my($self, $meta, $dist) = @_;
2982
2983 my @features = $self->configure_features($dist, $meta->features);
2984 my $prereqs = $self->soften_makemaker_prereqs($meta->effective_prereqs(\@features)->clone);
2985
2986 return App::cpanminus::Dependency->from_prereqs($prereqs, $dist->{want_phases}, $self->{install_types});
2987 }
2988
2989 # Workaround for Module::Install 1.04 creating a bogus (higher) MakeMaker requirement that it needs in build_requires
2990 # Assuming MakeMaker requirement is already satisfied in configure_requires, there's no need to have higher version of
2991 # MakeMaker in build/test anyway. https://github.com/miyagawa/cpanminus/issues/463
2992 sub soften_makemaker_prereqs {
2993 my($self, $prereqs) = @_;
2994
2995 return $prereqs unless -e "inc/Module/Install.pm";
2996
2997 for my $phase (qw( build test runtime )) {
2998 my $reqs = $prereqs->requirements_for($phase, 'requires');
2999 if ($reqs->requirements_for_module('ExtUtils::MakeMaker')) {
3000 $reqs->clear_requirement('ExtUtils::MakeMaker');
3001 $reqs->add_minimum('ExtUtils::MakeMaker' => 0);
3002 }
3003 }
3004
3005 $prereqs;
3006 }
3007
3008 sub cleanup_workdirs {
3009 my $self = shift;
3010
3011 my $expire = time - 24 * 60 * 60 * $self->{auto_cleanup};
3012 my @targets;
3013
3014 opendir my $dh, "$self->{home}/work";
3015 while (my $e = readdir $dh) {
3016 next if $e !~ /^(\d+)\.\d+$/; # {UNIX time}.{PID}
3017 my $time = $1;
3018 if ($time < $expire) {
3019 push @targets, "$self->{home}/work/$e";
3020 }
3021 }
3022
3023 if (@targets) {
3024 if (@targets >= 64) {
3025 $self->diag("Expiring " . scalar(@targets) . " work directories. This might take a while...\n");
3026 } else {
3027 $self->chat("Expiring " . scalar(@targets) . " work directories.\n");
3028 }
3029 File::Path::rmtree(\@targets, 0, 0); # safe = 0, since blib usually doesn't have write bits
3030 }
3031 }
3032
3033 sub scandeps_append_child {
3034 my($self, $dist) = @_;
3035
3036 my $new_node = [ $dist, [] ];
3037
3038 my $curr_node = $self->{scandeps_current} || [ undef, $self->{scandeps_tree} ];
3039 push @{$curr_node->[1]}, $new_node;
3040
3041 $self->{scandeps_current} = $new_node;
3042
3043 return sub { $self->{scandeps_current} = $curr_node };
3044 }
3045
3046 sub dump_scandeps {
3047 my $self = shift;
3048
3049 if ($self->{format} eq 'tree') {
3050 $self->walk_down(sub {
3051 my($dist, $depth) = @_;
3052 if ($depth == 0) {
3053 print "$dist->{distvname}\n";
3054 } else {
3055 print " " x ($depth - 1);
3056 print "\\_ $dist->{distvname}\n";
3057 }
3058 }, 1);
3059 } elsif ($self->{format} =~ /^dists?$/) {
3060 $self->walk_down(sub {
3061 my($dist, $depth) = @_;
3062 print $self->format_dist($dist), "\n";
3063 }, 0);
3064 } elsif ($self->{format} eq 'json') {
3065 require JSON::PP;
3066 print JSON::PP::encode_json($self->{scandeps_tree});
3067 } elsif ($self->{format} eq 'yaml') {
3068 require YAML; # no fatpack
3069 print YAML::Dump($self->{scandeps_tree});
3070 } else {
3071 $self->diag("Unknown format: $self->{format}\n");
3072 }
3073 }
3074
3075 sub walk_down {
3076 my($self, $cb, $pre) = @_;
3077 $self->_do_walk_down($self->{scandeps_tree}, $cb, 0, $pre);
3078 }
3079
3080 sub _do_walk_down {
3081 my($self, $children, $cb, $depth, $pre) = @_;
3082
3083 # DFS - $pre determines when we call the callback
3084 for my $node (@$children) {
3085 $cb->($node->[0], $depth) if $pre;
3086 $self->_do_walk_down($node->[1], $cb, $depth + 1, $pre);
3087 $cb->($node->[0], $depth) unless $pre;
3088 }
3089 }
3090
3091 sub DESTROY {
3092 my $self = shift;
3093 $self->{at_exit}->($self) if $self->{at_exit};
3094 }
3095
3096 # Utils
3097
3098 sub shell_quote {
3099 my($self, @stuff) = @_;
3100 if (WIN32) {
3101 join ' ', map { /^${quote}.+${quote}$/ ? $_ : ($quote . $_ . $quote) } @stuff;
3102 } else {
3103 String::ShellQuote::shell_quote_best_effort(@stuff);
3104 }
3105 }
3106
3107 sub which {
3108 my($self, $name) = @_;
3109 if (File::Spec->file_name_is_absolute($name)) {
3110 if (-x $name && !-d _) {
3111 return $name;
3112 }
3113 }
3114 my $exe_ext = $Config{_exe};
3115 for my $dir (File::Spec->path) {
3116 my $fullpath = File::Spec->catfile($dir, $name);
3117 if ((-x $fullpath || -x ($fullpath .= $exe_ext)) && !-d _) {
3118 if ($fullpath =~ /\s/) {
3119 $fullpath = $self->shell_quote($fullpath);
3120 }
3121 return $fullpath;
3122 }
3123 }
3124 return;
3125 }
3126
3127 sub get {
3128 my($self, $uri) = @_;
3129 if ($uri =~ /^file:/) {
3130 $self->file_get($uri);
3131 } else {
3132 $self->{_backends}{get}->(@_);
3133 }
3134 }
3135
3136 sub mirror {
3137 my($self, $uri, $local) = @_;
3138 if ($uri =~ /^file:/) {
3139 $self->file_mirror($uri, $local);
3140 } else {
3141 $self->{_backends}{mirror}->(@_);
3142 }
3143 }
3144
3145 sub untar { $_[0]->{_backends}{untar}->(@_) };
3146 sub unzip { $_[0]->{_backends}{unzip}->(@_) };
3147
3148 sub uri_to_file {
3149 my($self, $uri) = @_;
3150
3151 # file:///path/to/file -> /path/to/file
3152 # file://C:/path -> C:/path
3153 if ($uri =~ s!file:/+!!) {
3154 $uri = "/$uri" unless $uri =~ m![a-zA-Z]:!;
3155 }
3156
3157 return $uri;
3158 }
3159
3160 sub file_get {
3161 my($self, $uri) = @_;
3162 my $file = $self->uri_to_file($uri);
3163 open my $fh, "<$file" or return;
3164 join '', <$fh>;
3165 }
3166
3167 sub file_mirror {
3168 my($self, $uri, $path) = @_;
3169 my $file = $self->uri_to_file($uri);
3170
3171 my $source_mtime = (stat $file)[9];
3172
3173 # Don't mirror a file that's already there (like the index)
3174 return 1 if -e $path && (stat $path)[9] >= $source_mtime;
3175
3176 File::Copy::copy($file, $path);
3177
3178 utime $source_mtime, $source_mtime, $path;
3179 }
3180
3181 sub has_working_lwp {
3182 my($self, $mirrors) = @_;
3183 my $https = grep /^https:/, @$mirrors;
3184 eval {
3185 require LWP::UserAgent; # no fatpack
3186 LWP::UserAgent->VERSION(5.802);
3187 require LWP::Protocol::https if $https; # no fatpack
3188 1;
3189 };
3190 }
3191
3192 sub init_tools {
3193 my $self = shift;
3194
3195 return if $self->{initialized}++;
3196
3197 if ($self->{make} = $self->which($Config{make})) {
3198 $self->chat("You have make $self->{make}\n");
3199 }
3200
3201 # use --no-lwp if they have a broken LWP, to upgrade LWP
3202 if ($self->{try_lwp} && $self->has_working_lwp($self->{mirrors})) {
3203 $self->chat("You have LWP $LWP::VERSION\n");
3204 my $ua = sub {
3205 LWP::UserAgent->new(
3206 parse_head => 0,
3207 env_proxy => 1,
3208 agent => $self->agent,
3209 timeout => 30,
3210 @_,
3211 );
3212 };
3213 $self->{_backends}{get} = sub {
3214 my $self = shift;
3215 my $res = $ua->()->request(HTTP::Request->new(GET => $_[0]));
3216 return unless $res->is_success;
3217 return $res->decoded_content;
3218 };
3219 $self->{_backends}{mirror} = sub {
3220 my $self = shift;
3221 my $res = $ua->()->mirror(@_);
3222 die $res->content if $res->code == 501;
3223 $res->code;
3224 };
3225 } elsif ($self->{try_wget} and my $wget = $self->which('wget')) {
3226 $self->chat("You have $wget\n");
3227 my @common = (
3228 '--user-agent', $self->agent,
3229 '--retry-connrefused',
3230 ($self->{verbose} ? () : ('-q')),
3231 );
3232 $self->{_backends}{get} = sub {
3233 my($self, $uri) = @_;
3234 $self->safeexec( my $fh, $wget, $uri, @common, '-O', '-' ) or die "wget $uri: $!";
3235 local $/;
3236 <$fh>;
3237 };
3238 $self->{_backends}{mirror} = sub {
3239 my($self, $uri, $path) = @_;
3240 $self->safeexec( my $fh, $wget, $uri, @common, '-O', $path ) or die "wget $uri: $!";
3241 local $/;
3242 <$fh>;
3243 };
3244 } elsif ($self->{try_curl} and my $curl = $self->which('curl')) {
3245 $self->chat("You have $curl\n");
3246 my @common = (
3247 '--location',
3248 '--user-agent', $self->agent,
3249 ($self->{verbose} ? () : '-s'),
3250 );
3251 $self->{_backends}{get} = sub {
3252 my($self, $uri) = @_;
3253 $self->safeexec( my $fh, $curl, @common, $uri ) or die "curl $uri: $!";
3254 local $/;
3255 <$fh>;
3256 };
3257 $self->{_backends}{mirror} = sub {
3258 my($self, $uri, $path) = @_;
3259 $self->safeexec( my $fh, $curl, @common, $uri, '-#', '-o', $path ) or die "curl $uri: $!";
3260 local $/;
3261 <$fh>;
3262 };
3263 } else {
3264 require HTTP::Tiny;
3265 $self->chat("Falling back to HTTP::Tiny $HTTP::Tiny::VERSION\n");
3266 my %common = (
3267 agent => $self->agent,
3268 );
3269 $self->{_backends}{get} = sub {
3270 my $self = shift;
3271 my $res = HTTP::Tiny->new(%common)->get($_[0]);
3272 return unless $res->{success};
3273 return $res->{content};
3274 };
3275 $self->{_backends}{mirror} = sub {
3276 my $self = shift;
3277 my $res = HTTP::Tiny->new(%common)->mirror(@_);
3278 return $res->{status};
3279 };
3280 }
3281
3282 my $tar = $self->which('tar');
3283 my $tar_ver;
3284 my $maybe_bad_tar = sub { WIN32 || BAD_TAR || (($tar_ver = `$tar --version 2>/dev/null`) =~ /GNU.*1\.13/i) };
3285
3286 if ($tar && !$maybe_bad_tar->()) {
3287 chomp $tar_ver;
3288 $self->chat("You have $tar: $tar_ver\n");
3289 $self->{_backends}{untar} = sub {
3290 my($self, $tarfile) = @_;
3291
3292 my $xf = ($self->{verbose} ? 'v' : '')."xf";
3293 my $ar = $tarfile =~ /bz2$/ ? 'j' : 'z';
3294
3295 my($root, @others) = `$tar ${ar}tf $tarfile`
3296 or return undef;
3297
3298 FILE: {
3299 chomp $root;
3300 $root =~ s!^\./!!;
3301 $root =~ s{^(.+?)/.*$}{$1};
3302
3303 if (!length($root)) {
3304 # archive had ./ as the first entry, so try again
3305 $root = shift(@others);
3306 redo FILE if $root;
3307 }
3308 }
3309
3310 system "$tar $ar$xf $tarfile";
3311 return $root if -d $root;
3312
3313 $self->diag_fail("Bad archive: $tarfile");
3314 return undef;
3315 }
3316 } elsif ( $tar
3317 and my $gzip = $self->which('gzip')
3318 and my $bzip2 = $self->which('bzip2')) {
3319 $self->chat("You have $tar, $gzip and $bzip2\n");
3320 $self->{_backends}{untar} = sub {
3321 my($self, $tarfile) = @_;
3322
3323 my $x = "x" . ($self->{verbose} ? 'v' : '') . "f -";
3324 my $ar = $tarfile =~ /bz2$/ ? $bzip2 : $gzip;
3325
3326 my($root, @others) = `$ar -dc $tarfile | $tar tf -`
3327 or return undef;
3328
3329 FILE: {
3330 chomp $root;
3331 $root =~ s!^\./!!;
3332 $root =~ s{^(.+?)/.*$}{$1};
3333
3334 if (!length($root)) {
3335 # archive had ./ as the first entry, so try again
3336 $root = shift(@others);
3337 redo FILE if $root;
3338 }
3339 }
3340
3341 system "$ar -dc $tarfile | $tar $x";
3342 return $root if -d $root;
3343
3344 $self->diag_fail("Bad archive: $tarfile");
3345 return undef;
3346 }
3347 } elsif (eval { require Archive::Tar }) { # uses too much memory!
3348 $self->chat("Falling back to Archive::Tar $Archive::Tar::VERSION\n");
3349 $self->{_backends}{untar} = sub {
3350 my $self = shift;
3351 my $t = Archive::Tar->new($_[0]);
3352 my($root, @others) = $t->list_files;
3353 FILE: {
3354 $root =~ s!^\./!!;
3355 $root =~ s{^(.+?)/.*$}{$1};
3356
3357 if (!length($root)) {
3358 # archive had ./ as the first entry, so try again
3359 $root = shift(@others);
3360 redo FILE if $root;
3361 }
3362 }
3363 $t->extract;
3364 return -d $root ? $root : undef;
3365 };
3366 } else {
3367 $self->{_backends}{untar} = sub {
3368 die "Failed to extract $_[1] - You need to have tar or Archive::Tar installed.\n";
3369 };
3370 }
3371
3372 if (my $unzip = $self->which('unzip')) {
3373 $self->chat("You have $unzip\n");
3374 $self->{_backends}{unzip} = sub {
3375 my($self, $zipfile) = @_;
3376
3377 my $opt = $self->{verbose} ? '' : '-q';
3378 my(undef, $root, @others) = `$unzip -t $zipfile`
3379 or return undef;
3380 FILE: {
3381 chomp $root;
3382 if ($root !~ s{^\s+testing:\s+([^/]+)/.*?\s+OK$}{$1}) {
3383 $root = shift(@others);
3384 redo FILE if $root;
3385 }
3386 }
3387
3388 system "$unzip $opt $zipfile";
3389 return $root if -d $root;
3390
3391 $self->diag_fail("Bad archive: [$root] $zipfile");
3392 return undef;
3393 }
3394 } else {
3395 $self->{_backends}{unzip} = sub {
3396 eval { require Archive::Zip }
3397 or die "Failed to extract $_[1] - You need to have unzip or Archive::Zip installed.\n";
3398 my($self, $file) = @_;
3399 my $zip = Archive::Zip->new();
3400 my $status;
3401 $status = $zip->read($file);
3402 $self->diag_fail("Read of file[$file] failed")
3403 if $status != Archive::Zip::AZ_OK();
3404 my @members = $zip->members();
3405 for my $member ( @members ) {
3406 my $af = $member->fileName();
3407 next if ($af =~ m!^(/|\.\./)!);
3408 $status = $member->extractToFileNamed( $af );
3409 $self->diag_fail("Extracting of file[$af] from zipfile[$file failed")
3410 if $status != Archive::Zip::AZ_OK();
3411 }
3412
3413 my ($root) = $zip->membersMatching( qr<^[^/]+/$> );
3414 $root &&= $root->fileName;
3415 return -d $root ? $root : undef;
3416 };
3417 }
3418 }
3419
3420 sub safeexec {
3421 my $self = shift;
3422 my $rdr = $_[0] ||= Symbol::gensym();
3423
3424 if (WIN32) {
3425 my $cmd = $self->shell_quote(@_[1..$#_]);
3426 return open( $rdr, "$cmd |" );
3427 }
3428
3429 if ( my $pid = open( $rdr, '-|' ) ) {
3430 return $pid;
3431 }
3432 elsif ( defined $pid ) {
3433 exec( @_[ 1 .. $#_ ] );
3434 exit 1;
3435 }
3436 else {
3437 return;
3438 }
3439 }
3440
3441 sub mask_uri_passwords {
3442 my($self, @strings) = @_;
3443 s{ (https?://) ([^:/]+) : [^@/]+ @ }{$1$2:********@}gx for @strings;
3444 return @strings;
3445 }
3446
3447 1;
3448 APP_CPANMINUS_SCRIPT
3449  
3450 $fatpacked{"CPAN/DistnameInfo.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CPAN_DISTNAMEINFO';
3451
3452 package CPAN::DistnameInfo;
3453
3454 $VERSION = "0.12";
3455 use strict;
3456
3457 sub distname_info {
3458 my $file = shift or return;
3459
3460 my ($dist, $version) = $file =~ /^
3461 ((?:[-+.]*(?:[A-Za-z0-9]+|(?<=\D)_|_(?=\D))*
3462 (?:
3463 [A-Za-z](?=[^A-Za-z]|$)
3464 |
3465 \d(?=-)
3466 )(?<![._-][vV])
3467 )+)(.*)
3468 $/xs or return ($file,undef,undef);
3469
3470 if ($dist =~ /-undef\z/ and ! length $version) {
3471 $dist =~ s/-undef\z//;
3472 }
3473
3474 # Remove potential -withoutworldwriteables suffix
3475 $version =~ s/-withoutworldwriteables$//;
3476
3477 if ($version =~ /^(-[Vv].*)-(\d.*)/) {
3478
3479 # Catch names like Unicode-Collate-Standard-V3_1_1-0.1
3480 # where the V3_1_1 is part of the distname
3481 $dist .= $1;
3482 $version = $2;
3483 }
3484
3485 if ($version =~ /(.+_.*)-(\d.*)/) {
3486 # Catch names like Task-Deprecations5_14-1.00.tar.gz where the 5_14 is
3487 # part of the distname. However, names like libao-perl_0.03-1.tar.gz
3488 # should still have 0.03-1 as their version.
3489 $dist .= $1;
3490 $version = $2;
3491 }
3492
3493 # Normalize the Dist.pm-1.23 convention which CGI.pm and
3494 # a few others use.
3495 $dist =~ s{\.pm$}{};
3496
3497 $version = $1
3498 if !length $version and $dist =~ s/-(\d+\w)$//;
3499
3500 $version = $1 . $version
3501 if $version =~ /^\d+$/ and $dist =~ s/-(\w+)$//;
3502
3503 if ($version =~ /\d\.\d/) {
3504 $version =~ s/^[-_.]+//;
3505 }
3506 else {
3507 $version =~ s/^[-_]+//;
3508 }
3509
3510 my $dev;
3511 if (length $version) {
3512 if ($file =~ /^perl-?\d+\.(\d+)(?:\D(\d+))?(-(?:TRIAL|RC)\d+)?$/) {
3513 $dev = 1 if (($1 > 6 and $1 & 1) or ($2 and $2 >= 50)) or $3;
3514 }
3515 elsif ($version =~ /\d\D\d+_\d/ or $version =~ /-TRIAL/) {
3516 $dev = 1;
3517 }
3518 }
3519 else {
3520 $version = undef;
3521 }
3522
3523 ($dist, $version, $dev);
3524 }
3525
3526 sub new {
3527 my $class = shift;
3528 my $distfile = shift;
3529
3530 $distfile =~ s,//+,/,g;
3531
3532 my %info = ( pathname => $distfile );
3533
3534 ($info{filename} = $distfile) =~ s,^(((.*?/)?authors/)?id/)?([A-Z])/(\4[A-Z])/(\5[-A-Z0-9]*)/,,
3535 and $info{cpanid} = $6;
3536
3537 if ($distfile =~ m,([^/]+)\.(tar\.(?:g?z|bz2)|zip|tgz)$,i) { # support more ?
3538 $info{distvname} = $1;
3539 $info{extension} = $2;
3540 }
3541
3542 @info{qw(dist version beta)} = distname_info($info{distvname});
3543 $info{maturity} = delete $info{beta} ? 'developer' : 'released';
3544
3545 return bless \%info, $class;
3546 }
3547
3548 sub dist { shift->{dist} }
3549 sub version { shift->{version} }
3550 sub maturity { shift->{maturity} }
3551 sub filename { shift->{filename} }
3552 sub cpanid { shift->{cpanid} }
3553 sub distvname { shift->{distvname} }
3554 sub extension { shift->{extension} }
3555 sub pathname { shift->{pathname} }
3556
3557 sub properties { %{ $_[0] } }
3558
3559 1;
3560
3561 __END__
3562
3563 =head1 NAME
3564
3565 CPAN::DistnameInfo - Extract distribution name and version from a distribution filename
3566
3567 =head1 SYNOPSIS
3568
3569 my $pathname = "authors/id/G/GB/GBARR/CPAN-DistnameInfo-0.02.tar.gz";
3570
3571 my $d = CPAN::DistnameInfo->new($pathname);
3572
3573 my $dist = $d->dist; # "CPAN-DistnameInfo"
3574 my $version = $d->version; # "0.02"
3575 my $maturity = $d->maturity; # "released"
3576 my $filename = $d->filename; # "CPAN-DistnameInfo-0.02.tar.gz"
3577 my $cpanid = $d->cpanid; # "GBARR"
3578 my $distvname = $d->distvname; # "CPAN-DistnameInfo-0.02"
3579 my $extension = $d->extension; # "tar.gz"
3580 my $pathname = $d->pathname; # "authors/id/G/GB/GBARR/..."
3581
3582 my %prop = $d->properties;
3583
3584 =head1 DESCRIPTION
3585
3586 Many online services that are centered around CPAN attempt to
3587 associate multiple uploads by extracting a distribution name from
3588 the filename of the upload. For most distributions this is easy as
3589 they have used ExtUtils::MakeMaker or Module::Build to create the
3590 distribution, which results in a uniform name. But sadly not all
3591 uploads are created in this way.
3592
3593 C<CPAN::DistnameInfo> uses heuristics that have been learnt by
3594 L<http://search.cpan.org/> to extract the distribution name and
3595 version from filenames and also report if the version is to be
3596 treated as a developer release
3597
3598 The constructor takes a single pathname, returning an object with the following methods
3599
3600 =over
3601
3602 =item cpanid
3603
3604 If the path given looked like a CPAN authors directory path, then this will be the
3605 the CPAN id of the author.
3606
3607 =item dist
3608
3609 The name of the distribution
3610
3611 =item distvname
3612
3613 The file name with any suffix and leading directory names removed
3614
3615 =item filename
3616
3617 If the path given looked like a CPAN authors directory path, then this will be the
3618 path to the file relative to the detected CPAN author directory. Otherwise it is the path
3619 that was passed in.
3620
3621 =item maturity
3622
3623 The maturity of the distribution. This will be either C<released> or C<developer>
3624
3625 =item extension
3626
3627 The extension of the distribution, often used to denote the archive type (e.g. 'tar.gz')
3628
3629 =item pathname
3630
3631 The pathname that was passed to the constructor when creating the object.
3632
3633 =item properties
3634
3635 This will return a list of key-value pairs, suitable for assigning to a hash,
3636 for the known properties.
3637
3638 =item version
3639
3640 The extracted version
3641
3642 =back
3643
3644 =head1 AUTHOR
3645
3646 Graham Barr <gbarr@pobox.com>
3647
3648 =head1 COPYRIGHT
3649
3650 Copyright (c) 2003 Graham Barr. All rights reserved. This program is
3651 free software; you can redistribute it and/or modify it under the same
3652 terms as Perl itself.
3653
3654 =cut
3655
3656 CPAN_DISTNAMEINFO
3657  
3658 $fatpacked{"CPAN/Meta.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CPAN_META';
3659 use 5.006;
3660 use strict;
3661 use warnings;
3662 package CPAN::Meta;
3663
3664 our $VERSION = '2.150005';
3665
3666 #pod =head1 SYNOPSIS
3667 #pod
3668 #pod use v5.10;
3669 #pod use strict;
3670 #pod use warnings;
3671 #pod use CPAN::Meta;
3672 #pod use Module::Load;
3673 #pod
3674 #pod my $meta = CPAN::Meta->load_file('META.json');
3675 #pod
3676 #pod printf "testing requirements for %s version %s\n",
3677 #pod $meta->name,
3678 #pod $meta->version;
3679 #pod
3680 #pod my $prereqs = $meta->effective_prereqs;
3681 #pod
3682 #pod for my $phase ( qw/configure runtime build test/ ) {
3683 #pod say "Requirements for $phase:";
3684 #pod my $reqs = $prereqs->requirements_for($phase, "requires");
3685 #pod for my $module ( sort $reqs->required_modules ) {
3686 #pod my $status;
3687 #pod if ( eval { load $module unless $module eq 'perl'; 1 } ) {
3688 #pod my $version = $module eq 'perl' ? $] : $module->VERSION;
3689 #pod $status = $reqs->accepts_module($module, $version)
3690 #pod ? "$version ok" : "$version not ok";
3691 #pod } else {
3692 #pod $status = "missing"
3693 #pod };
3694 #pod say " $module ($status)";
3695 #pod }
3696 #pod }
3697 #pod
3698 #pod =head1 DESCRIPTION
3699 #pod
3700 #pod Software distributions released to the CPAN include a F<META.json> or, for
3701 #pod older distributions, F<META.yml>, which describes the distribution, its
3702 #pod contents, and the requirements for building and installing the distribution.
3703 #pod The data structure stored in the F<META.json> file is described in
3704 #pod L<CPAN::Meta::Spec>.
3705 #pod
3706 #pod CPAN::Meta provides a simple class to represent this distribution metadata (or
3707 #pod I<distmeta>), along with some helpful methods for interrogating that data.
3708 #pod
3709 #pod The documentation below is only for the methods of the CPAN::Meta object. For
3710 #pod information on the meaning of individual fields, consult the spec.
3711 #pod
3712 #pod =cut
3713
3714 use Carp qw(carp croak);
3715 use CPAN::Meta::Feature;
3716 use CPAN::Meta::Prereqs;
3717 use CPAN::Meta::Converter;
3718 use CPAN::Meta::Validator;
3719 use Parse::CPAN::Meta 1.4414 ();
3720
3721 BEGIN { *_dclone = \&CPAN::Meta::Converter::_dclone }
3722
3723 #pod =head1 STRING DATA
3724 #pod
3725 #pod The following methods return a single value, which is the value for the
3726 #pod corresponding entry in the distmeta structure. Values should be either undef
3727 #pod or strings.
3728 #pod
3729 #pod =for :list
3730 #pod * abstract
3731 #pod * description
3732 #pod * dynamic_config
3733 #pod * generated_by
3734 #pod * name
3735 #pod * release_status
3736 #pod * version
3737 #pod
3738 #pod =cut
3739
3740 BEGIN {
3741 my @STRING_READERS = qw(
3742 abstract
3743 description
3744 dynamic_config
3745 generated_by
3746 name
3747 release_status
3748 version
3749 );
3750
3751 no strict 'refs';
3752 for my $attr (@STRING_READERS) {
3753 *$attr = sub { $_[0]{ $attr } };
3754 }
3755 }
3756
3757 #pod =head1 LIST DATA
3758 #pod
3759 #pod These methods return lists of string values, which might be represented in the
3760 #pod distmeta structure as arrayrefs or scalars:
3761 #pod
3762 #pod =for :list
3763 #pod * authors
3764 #pod * keywords
3765 #pod * licenses
3766 #pod
3767 #pod The C<authors> and C<licenses> methods may also be called as C<author> and
3768 #pod C<license>, respectively, to match the field name in the distmeta structure.
3769 #pod
3770 #pod =cut
3771
3772 BEGIN {
3773 my @LIST_READERS = qw(
3774 author
3775 keywords
3776 license
3777 );
3778
3779 no strict 'refs';
3780 for my $attr (@LIST_READERS) {
3781 *$attr = sub {
3782 my $value = $_[0]{ $attr };
3783 croak "$attr must be called in list context"
3784 unless wantarray;
3785 return @{ _dclone($value) } if ref $value;
3786 return $value;
3787 };
3788 }
3789 }
3790
3791 sub authors { $_[0]->author }
3792 sub licenses { $_[0]->license }
3793
3794 #pod =head1 MAP DATA
3795 #pod
3796 #pod These readers return hashrefs of arbitrary unblessed data structures, each
3797 #pod described more fully in the specification:
3798 #pod
3799 #pod =for :list
3800 #pod * meta_spec
3801 #pod * resources
3802 #pod * provides
3803 #pod * no_index
3804 #pod * prereqs
3805 #pod * optional_features
3806 #pod
3807 #pod =cut
3808
3809 BEGIN {
3810 my @MAP_READERS = qw(
3811 meta-spec
3812 resources
3813 provides
3814 no_index
3815
3816 prereqs
3817 optional_features
3818 );
3819
3820 no strict 'refs';
3821 for my $attr (@MAP_READERS) {
3822 (my $subname = $attr) =~ s/-/_/;
3823 *$subname = sub {
3824 my $value = $_[0]{ $attr };
3825 return _dclone($value) if $value;
3826 return {};
3827 };
3828 }
3829 }
3830
3831 #pod =head1 CUSTOM DATA
3832 #pod
3833 #pod A list of custom keys are available from the C<custom_keys> method and
3834 #pod particular keys may be retrieved with the C<custom> method.
3835 #pod
3836 #pod say $meta->custom($_) for $meta->custom_keys;
3837 #pod
3838 #pod If a custom key refers to a data structure, a deep clone is returned.
3839 #pod
3840 #pod =cut
3841
3842 sub custom_keys {
3843 return grep { /^x_/i } keys %{$_[0]};
3844 }
3845
3846 sub custom {
3847 my ($self, $attr) = @_;
3848 my $value = $self->{$attr};
3849 return _dclone($value) if ref $value;
3850 return $value;
3851 }
3852
3853 #pod =method new
3854 #pod
3855 #pod my $meta = CPAN::Meta->new($distmeta_struct, \%options);
3856 #pod
3857 #pod Returns a valid CPAN::Meta object or dies if the supplied metadata hash
3858 #pod reference fails to validate. Older-format metadata will be up-converted to
3859 #pod version 2 if they validate against the original stated specification.
3860 #pod
3861 #pod It takes an optional hashref of options. Valid options include:
3862 #pod
3863 #pod =over
3864 #pod
3865 #pod =item *
3866 #pod
3867 #pod lazy_validation -- if true, new will attempt to convert the given metadata
3868 #pod to version 2 before attempting to validate it. This means than any
3869 #pod fixable errors will be handled by CPAN::Meta::Converter before validation.
3870 #pod (Note that this might result in invalid optional data being silently
3871 #pod dropped.) The default is false.
3872 #pod
3873 #pod =back
3874 #pod
3875 #pod =cut
3876
3877 sub _new {
3878 my ($class, $struct, $options) = @_;
3879 my $self;
3880
3881 if ( $options->{lazy_validation} ) {
3882 # try to convert to a valid structure; if succeeds, then return it
3883 my $cmc = CPAN::Meta::Converter->new( $struct );
3884 $self = $cmc->convert( version => 2 ); # valid or dies
3885 return bless $self, $class;
3886 }
3887 else {
3888 # validate original struct
3889 my $cmv = CPAN::Meta::Validator->new( $struct );
3890 unless ( $cmv->is_valid) {
3891 die "Invalid metadata structure. Errors: "
3892 . join(", ", $cmv->errors) . "\n";
3893 }
3894 }
3895
3896 # up-convert older spec versions
3897 my $version = $struct->{'meta-spec'}{version} || '1.0';
3898 if ( $version == 2 ) {
3899 $self = $struct;
3900 }
3901 else {
3902 my $cmc = CPAN::Meta::Converter->new( $struct );
3903 $self = $cmc->convert( version => 2 );
3904 }
3905
3906 return bless $self, $class;
3907 }
3908
3909 sub new {
3910 my ($class, $struct, $options) = @_;
3911 my $self = eval { $class->_new($struct, $options) };
3912 croak($@) if $@;
3913 return $self;
3914 }
3915
3916 #pod =method create
3917 #pod
3918 #pod my $meta = CPAN::Meta->create($distmeta_struct, \%options);
3919 #pod
3920 #pod This is same as C<new()>, except that C<generated_by> and C<meta-spec> fields
3921 #pod will be generated if not provided. This means the metadata structure is
3922 #pod assumed to otherwise follow the latest L<CPAN::Meta::Spec>.
3923 #pod
3924 #pod =cut
3925
3926 sub create {
3927 my ($class, $struct, $options) = @_;
3928 my $version = __PACKAGE__->VERSION || 2;
3929 $struct->{generated_by} ||= __PACKAGE__ . " version $version" ;
3930 $struct->{'meta-spec'}{version} ||= int($version);
3931 my $self = eval { $class->_new($struct, $options) };
3932 croak ($@) if $@;
3933 return $self;
3934 }
3935
3936 #pod =method load_file
3937 #pod
3938 #pod my $meta = CPAN::Meta->load_file($distmeta_file, \%options);
3939 #pod
3940 #pod Given a pathname to a file containing metadata, this deserializes the file
3941 #pod according to its file suffix and constructs a new C<CPAN::Meta> object, just
3942 #pod like C<new()>. It will die if the deserialized version fails to validate
3943 #pod against its stated specification version.
3944 #pod
3945 #pod It takes the same options as C<new()> but C<lazy_validation> defaults to
3946 #pod true.
3947 #pod
3948 #pod =cut
3949
3950 sub load_file {
3951 my ($class, $file, $options) = @_;
3952 $options->{lazy_validation} = 1 unless exists $options->{lazy_validation};
3953
3954 croak "load_file() requires a valid, readable filename"
3955 unless -r $file;
3956
3957 my $self;
3958 eval {
3959 my $struct = Parse::CPAN::Meta->load_file( $file );
3960 $self = $class->_new($struct, $options);
3961 };
3962 croak($@) if $@;
3963 return $self;
3964 }
3965
3966 #pod =method load_yaml_string
3967 #pod
3968 #pod my $meta = CPAN::Meta->load_yaml_string($yaml, \%options);
3969 #pod
3970 #pod This method returns a new CPAN::Meta object using the first document in the
3971 #pod given YAML string. In other respects it is identical to C<load_file()>.
3972 #pod
3973 #pod =cut
3974
3975 sub load_yaml_string {
3976 my ($class, $yaml, $options) = @_;
3977 $options->{lazy_validation} = 1 unless exists $options->{lazy_validation};
3978
3979 my $self;
3980 eval {
3981 my ($struct) = Parse::CPAN::Meta->load_yaml_string( $yaml );
3982 $self = $class->_new($struct, $options);
3983 };
3984 croak($@) if $@;
3985 return $self;
3986 }
3987
3988 #pod =method load_json_string
3989 #pod
3990 #pod my $meta = CPAN::Meta->load_json_string($json, \%options);
3991 #pod
3992 #pod This method returns a new CPAN::Meta object using the structure represented by
3993 #pod the given JSON string. In other respects it is identical to C<load_file()>.
3994 #pod
3995 #pod =cut
3996
3997 sub load_json_string {
3998 my ($class, $json, $options) = @_;
3999 $options->{lazy_validation} = 1 unless exists $options->{lazy_validation};
4000
4001 my $self;
4002 eval {
4003 my $struct = Parse::CPAN::Meta->load_json_string( $json );
4004 $self = $class->_new($struct, $options);
4005 };
4006 croak($@) if $@;
4007 return $self;
4008 }
4009
4010 #pod =method load_string
4011 #pod
4012 #pod my $meta = CPAN::Meta->load_string($string, \%options);
4013 #pod
4014 #pod If you don't know if a string contains YAML or JSON, this method will use
4015 #pod L<Parse::CPAN::Meta> to guess. In other respects it is identical to
4016 #pod C<load_file()>.
4017 #pod
4018 #pod =cut
4019
4020 sub load_string {
4021 my ($class, $string, $options) = @_;
4022 $options->{lazy_validation} = 1 unless exists $options->{lazy_validation};
4023
4024 my $self;
4025 eval {
4026 my $struct = Parse::CPAN::Meta->load_string( $string );
4027 $self = $class->_new($struct, $options);
4028 };
4029 croak($@) if $@;
4030 return $self;
4031 }
4032
4033 #pod =method save
4034 #pod
4035 #pod $meta->save($distmeta_file, \%options);
4036 #pod
4037 #pod Serializes the object as JSON and writes it to the given file. The only valid
4038 #pod option is C<version>, which defaults to '2'. On Perl 5.8.1 or later, the file
4039 #pod is saved with UTF-8 encoding.
4040 #pod
4041 #pod For C<version> 2 (or higher), the filename should end in '.json'. L<JSON::PP>
4042 #pod is the default JSON backend. Using another JSON backend requires L<JSON> 2.5 or
4043 #pod later and you must set the C<$ENV{PERL_JSON_BACKEND}> to a supported alternate
4044 #pod backend like L<JSON::XS>.
4045 #pod
4046 #pod For C<version> less than 2, the filename should end in '.yml'.
4047 #pod L<CPAN::Meta::Converter> is used to generate an older metadata structure, which
4048 #pod is serialized to YAML. CPAN::Meta::YAML is the default YAML backend. You may
4049 #pod set the C<$ENV{PERL_YAML_BACKEND}> to a supported alternative backend, though
4050 #pod this is not recommended due to subtle incompatibilities between YAML parsers on
4051 #pod CPAN.
4052 #pod
4053 #pod =cut
4054
4055 sub save {
4056 my ($self, $file, $options) = @_;
4057
4058 my $version = $options->{version} || '2';
4059 my $layer = $] ge '5.008001' ? ':utf8' : '';
4060
4061 if ( $version ge '2' ) {
4062 carp "'$file' should end in '.json'"
4063 unless $file =~ m{\.json$};
4064 }
4065 else {
4066 carp "'$file' should end in '.yml'"
4067 unless $file =~ m{\.yml$};
4068 }
4069
4070 my $data = $self->as_string( $options );
4071 open my $fh, ">$layer", $file
4072 or die "Error opening '$file' for writing: $!\n";
4073
4074 print {$fh} $data;
4075 close $fh
4076 or die "Error closing '$file': $!\n";
4077
4078 return 1;
4079 }
4080
4081 #pod =method meta_spec_version
4082 #pod
4083 #pod This method returns the version part of the C<meta_spec> entry in the distmeta
4084 #pod structure. It is equivalent to:
4085 #pod
4086 #pod $meta->meta_spec->{version};
4087 #pod
4088 #pod =cut
4089
4090 sub meta_spec_version {
4091 my ($self) = @_;
4092 return $self->meta_spec->{version};
4093 }
4094
4095 #pod =method effective_prereqs
4096 #pod
4097 #pod my $prereqs = $meta->effective_prereqs;
4098 #pod
4099 #pod my $prereqs = $meta->effective_prereqs( \@feature_identifiers );
4100 #pod
4101 #pod This method returns a L<CPAN::Meta::Prereqs> object describing all the
4102 #pod prereqs for the distribution. If an arrayref of feature identifiers is given,
4103 #pod the prereqs for the identified features are merged together with the
4104 #pod distribution's core prereqs before the CPAN::Meta::Prereqs object is returned.
4105 #pod
4106 #pod =cut
4107
4108 sub effective_prereqs {
4109 my ($self, $features) = @_;
4110 $features ||= [];
4111
4112 my $prereq = CPAN::Meta::Prereqs->new($self->prereqs);
4113
4114 return $prereq unless @$features;
4115
4116 my @other = map {; $self->feature($_)->prereqs } @$features;
4117
4118 return $prereq->with_merged_prereqs(\@other);
4119 }
4120
4121 #pod =method should_index_file
4122 #pod
4123 #pod ... if $meta->should_index_file( $filename );
4124 #pod
4125 #pod This method returns true if the given file should be indexed. It decides this
4126 #pod by checking the C<file> and C<directory> keys in the C<no_index> property of
4127 #pod the distmeta structure. Note that neither the version format nor
4128 #pod C<release_status> are considered.
4129 #pod
4130 #pod C<$filename> should be given in unix format.
4131 #pod
4132 #pod =cut
4133
4134 sub should_index_file {
4135 my ($self, $filename) = @_;
4136
4137 for my $no_index_file (@{ $self->no_index->{file} || [] }) {
4138 return if $filename eq $no_index_file;
4139 }
4140
4141 for my $no_index_dir (@{ $self->no_index->{directory} }) {
4142 $no_index_dir =~ s{$}{/} unless $no_index_dir =~ m{/\z};
4143 return if index($filename, $no_index_dir) == 0;
4144 }
4145
4146 return 1;
4147 }
4148
4149 #pod =method should_index_package
4150 #pod
4151 #pod ... if $meta->should_index_package( $package );
4152 #pod
4153 #pod This method returns true if the given package should be indexed. It decides
4154 #pod this by checking the C<package> and C<namespace> keys in the C<no_index>
4155 #pod property of the distmeta structure. Note that neither the version format nor
4156 #pod C<release_status> are considered.
4157 #pod
4158 #pod =cut
4159
4160 sub should_index_package {
4161 my ($self, $package) = @_;
4162
4163 for my $no_index_pkg (@{ $self->no_index->{package} || [] }) {
4164 return if $package eq $no_index_pkg;
4165 }
4166
4167 for my $no_index_ns (@{ $self->no_index->{namespace} }) {
4168 return if index($package, "${no_index_ns}::") == 0;
4169 }
4170
4171 return 1;
4172 }
4173
4174 #pod =method features
4175 #pod
4176 #pod my @feature_objects = $meta->features;
4177 #pod
4178 #pod This method returns a list of L<CPAN::Meta::Feature> objects, one for each
4179 #pod optional feature described by the distribution's metadata.
4180 #pod
4181 #pod =cut
4182
4183 sub features {
4184 my ($self) = @_;
4185
4186 my $opt_f = $self->optional_features;
4187 my @features = map {; CPAN::Meta::Feature->new($_ => $opt_f->{ $_ }) }
4188 keys %$opt_f;
4189
4190 return @features;
4191 }
4192
4193 #pod =method feature
4194 #pod
4195 #pod my $feature_object = $meta->feature( $identifier );
4196 #pod
4197 #pod This method returns a L<CPAN::Meta::Feature> object for the optional feature
4198 #pod with the given identifier. If no feature with that identifier exists, an
4199 #pod exception will be raised.
4200 #pod
4201 #pod =cut
4202
4203 sub feature {
4204 my ($self, $ident) = @_;
4205
4206 croak "no feature named $ident"
4207 unless my $f = $self->optional_features->{ $ident };
4208
4209 return CPAN::Meta::Feature->new($ident, $f);
4210 }
4211
4212 #pod =method as_struct
4213 #pod
4214 #pod my $copy = $meta->as_struct( \%options );
4215 #pod
4216 #pod This method returns a deep copy of the object's metadata as an unblessed hash
4217 #pod reference. It takes an optional hashref of options. If the hashref contains
4218 #pod a C<version> argument, the copied metadata will be converted to the version
4219 #pod of the specification and returned. For example:
4220 #pod
4221 #pod my $old_spec = $meta->as_struct( {version => "1.4"} );
4222 #pod
4223 #pod =cut
4224
4225 sub as_struct {
4226 my ($self, $options) = @_;
4227 my $struct = _dclone($self);
4228 if ( $options->{version} ) {
4229 my $cmc = CPAN::Meta::Converter->new( $struct );
4230 $struct = $cmc->convert( version => $options->{version} );
4231 }
4232 return $struct;
4233 }
4234
4235 #pod =method as_string
4236 #pod
4237 #pod my $string = $meta->as_string( \%options );
4238 #pod
4239 #pod This method returns a serialized copy of the object's metadata as a character
4240 #pod string. (The strings are B<not> UTF-8 encoded.) It takes an optional hashref
4241 #pod of options. If the hashref contains a C<version> argument, the copied metadata
4242 #pod will be converted to the version of the specification and returned. For
4243 #pod example:
4244 #pod
4245 #pod my $string = $meta->as_string( {version => "1.4"} );
4246 #pod
4247 #pod For C<version> greater than or equal to 2, the string will be serialized as
4248 #pod JSON. For C<version> less than 2, the string will be serialized as YAML. In
4249 #pod both cases, the same rules are followed as in the C<save()> method for choosing
4250 #pod a serialization backend.
4251 #pod
4252 #pod The serialized structure will include a C<x_serialization_backend> entry giving
4253 #pod the package and version used to serialize. Any existing key in the given
4254 #pod C<$meta> object will be clobbered.
4255 #pod
4256 #pod =cut
4257
4258 sub as_string {
4259 my ($self, $options) = @_;
4260
4261 my $version = $options->{version} || '2';
4262
4263 my $struct;
4264 if ( $self->meta_spec_version ne $version ) {
4265 my $cmc = CPAN::Meta::Converter->new( $self->as_struct );
4266 $struct = $cmc->convert( version => $version );
4267 }
4268 else {
4269 $struct = $self->as_struct;
4270 }
4271
4272 my ($data, $backend);
4273 if ( $version ge '2' ) {
4274 $backend = Parse::CPAN::Meta->json_backend();
4275 local $struct->{x_serialization_backend} = sprintf '%s version %s',
4276 $backend, $backend->VERSION;
4277 $data = $backend->new->pretty->canonical->encode($struct);
4278 }
4279 else {
4280 $backend = Parse::CPAN::Meta->yaml_backend();
4281 local $struct->{x_serialization_backend} = sprintf '%s version %s',
4282 $backend, $backend->VERSION;
4283 $data = eval { no strict 'refs'; &{"$backend\::Dump"}($struct) };
4284 if ( $@ ) {
4285 croak $backend->can('errstr') ? $backend->errstr : $@
4286 }
4287 }
4288
4289 return $data;
4290 }
4291
4292 # Used by JSON::PP, etc. for "convert_blessed"
4293 sub TO_JSON {
4294 return { %{ $_[0] } };
4295 }
4296
4297 1;
4298
4299 # ABSTRACT: the distribution metadata for a CPAN dist
4300
4301 =pod
4302
4303 =encoding UTF-8
4304
4305 =head1 NAME
4306
4307 CPAN::Meta - the distribution metadata for a CPAN dist
4308
4309 =head1 VERSION
4310
4311 version 2.150005
4312
4313 =head1 SYNOPSIS
4314
4315 use v5.10;
4316 use strict;
4317 use warnings;
4318 use CPAN::Meta;
4319 use Module::Load;
4320
4321 my $meta = CPAN::Meta->load_file('META.json');
4322
4323 printf "testing requirements for %s version %s\n",
4324 $meta->name,
4325 $meta->version;
4326
4327 my $prereqs = $meta->effective_prereqs;
4328
4329 for my $phase ( qw/configure runtime build test/ ) {
4330 say "Requirements for $phase:";
4331 my $reqs = $prereqs->requirements_for($phase, "requires");
4332 for my $module ( sort $reqs->required_modules ) {
4333 my $status;
4334 if ( eval { load $module unless $module eq 'perl'; 1 } ) {
4335 my $version = $module eq 'perl' ? $] : $module->VERSION;
4336 $status = $reqs->accepts_module($module, $version)
4337 ? "$version ok" : "$version not ok";
4338 } else {
4339 $status = "missing"
4340 };
4341 say " $module ($status)";
4342 }
4343 }
4344
4345 =head1 DESCRIPTION
4346
4347 Software distributions released to the CPAN include a F<META.json> or, for
4348 older distributions, F<META.yml>, which describes the distribution, its
4349 contents, and the requirements for building and installing the distribution.
4350 The data structure stored in the F<META.json> file is described in
4351 L<CPAN::Meta::Spec>.
4352
4353 CPAN::Meta provides a simple class to represent this distribution metadata (or
4354 I<distmeta>), along with some helpful methods for interrogating that data.
4355
4356 The documentation below is only for the methods of the CPAN::Meta object. For
4357 information on the meaning of individual fields, consult the spec.
4358
4359 =head1 METHODS
4360
4361 =head2 new
4362
4363 my $meta = CPAN::Meta->new($distmeta_struct, \%options);
4364
4365 Returns a valid CPAN::Meta object or dies if the supplied metadata hash
4366 reference fails to validate. Older-format metadata will be up-converted to
4367 version 2 if they validate against the original stated specification.
4368
4369 It takes an optional hashref of options. Valid options include:
4370
4371 =over
4372
4373 =item *
4374
4375 lazy_validation -- if true, new will attempt to convert the given metadata
4376 to version 2 before attempting to validate it. This means than any
4377 fixable errors will be handled by CPAN::Meta::Converter before validation.
4378 (Note that this might result in invalid optional data being silently
4379 dropped.) The default is false.
4380
4381 =back
4382
4383 =head2 create
4384
4385 my $meta = CPAN::Meta->create($distmeta_struct, \%options);
4386
4387 This is same as C<new()>, except that C<generated_by> and C<meta-spec> fields
4388 will be generated if not provided. This means the metadata structure is
4389 assumed to otherwise follow the latest L<CPAN::Meta::Spec>.
4390
4391 =head2 load_file
4392
4393 my $meta = CPAN::Meta->load_file($distmeta_file, \%options);
4394
4395 Given a pathname to a file containing metadata, this deserializes the file
4396 according to its file suffix and constructs a new C<CPAN::Meta> object, just
4397 like C<new()>. It will die if the deserialized version fails to validate
4398 against its stated specification version.
4399
4400 It takes the same options as C<new()> but C<lazy_validation> defaults to
4401 true.
4402
4403 =head2 load_yaml_string
4404
4405 my $meta = CPAN::Meta->load_yaml_string($yaml, \%options);
4406
4407 This method returns a new CPAN::Meta object using the first document in the
4408 given YAML string. In other respects it is identical to C<load_file()>.
4409
4410 =head2 load_json_string
4411
4412 my $meta = CPAN::Meta->load_json_string($json, \%options);
4413
4414 This method returns a new CPAN::Meta object using the structure represented by
4415 the given JSON string. In other respects it is identical to C<load_file()>.
4416
4417 =head2 load_string
4418
4419 my $meta = CPAN::Meta->load_string($string, \%options);
4420
4421 If you don't know if a string contains YAML or JSON, this method will use
4422 L<Parse::CPAN::Meta> to guess. In other respects it is identical to
4423 C<load_file()>.
4424
4425 =head2 save
4426
4427 $meta->save($distmeta_file, \%options);
4428
4429 Serializes the object as JSON and writes it to the given file. The only valid
4430 option is C<version>, which defaults to '2'. On Perl 5.8.1 or later, the file
4431 is saved with UTF-8 encoding.
4432
4433 For C<version> 2 (or higher), the filename should end in '.json'. L<JSON::PP>
4434 is the default JSON backend. Using another JSON backend requires L<JSON> 2.5 or
4435 later and you must set the C<$ENV{PERL_JSON_BACKEND}> to a supported alternate
4436 backend like L<JSON::XS>.
4437
4438 For C<version> less than 2, the filename should end in '.yml'.
4439 L<CPAN::Meta::Converter> is used to generate an older metadata structure, which
4440 is serialized to YAML. CPAN::Meta::YAML is the default YAML backend. You may
4441 set the C<$ENV{PERL_YAML_BACKEND}> to a supported alternative backend, though
4442 this is not recommended due to subtle incompatibilities between YAML parsers on
4443 CPAN.
4444
4445 =head2 meta_spec_version
4446
4447 This method returns the version part of the C<meta_spec> entry in the distmeta
4448 structure. It is equivalent to:
4449
4450 $meta->meta_spec->{version};
4451
4452 =head2 effective_prereqs
4453
4454 my $prereqs = $meta->effective_prereqs;
4455
4456 my $prereqs = $meta->effective_prereqs( \@feature_identifiers );
4457
4458 This method returns a L<CPAN::Meta::Prereqs> object describing all the
4459 prereqs for the distribution. If an arrayref of feature identifiers is given,
4460 the prereqs for the identified features are merged together with the
4461 distribution's core prereqs before the CPAN::Meta::Prereqs object is returned.
4462
4463 =head2 should_index_file
4464
4465 ... if $meta->should_index_file( $filename );
4466
4467 This method returns true if the given file should be indexed. It decides this
4468 by checking the C<file> and C<directory> keys in the C<no_index> property of
4469 the distmeta structure. Note that neither the version format nor
4470 C<release_status> are considered.
4471
4472 C<$filename> should be given in unix format.
4473
4474 =head2 should_index_package
4475
4476 ... if $meta->should_index_package( $package );
4477
4478 This method returns true if the given package should be indexed. It decides
4479 this by checking the C<package> and C<namespace> keys in the C<no_index>
4480 property of the distmeta structure. Note that neither the version format nor
4481 C<release_status> are considered.
4482
4483 =head2 features
4484
4485 my @feature_objects = $meta->features;
4486
4487 This method returns a list of L<CPAN::Meta::Feature> objects, one for each
4488 optional feature described by the distribution's metadata.
4489
4490 =head2 feature
4491
4492 my $feature_object = $meta->feature( $identifier );
4493
4494 This method returns a L<CPAN::Meta::Feature> object for the optional feature
4495 with the given identifier. If no feature with that identifier exists, an
4496 exception will be raised.
4497
4498 =head2 as_struct
4499
4500 my $copy = $meta->as_struct( \%options );
4501
4502 This method returns a deep copy of the object's metadata as an unblessed hash
4503 reference. It takes an optional hashref of options. If the hashref contains
4504 a C<version> argument, the copied metadata will be converted to the version
4505 of the specification and returned. For example:
4506
4507 my $old_spec = $meta->as_struct( {version => "1.4"} );
4508
4509 =head2 as_string
4510
4511 my $string = $meta->as_string( \%options );
4512
4513 This method returns a serialized copy of the object's metadata as a character
4514 string. (The strings are B<not> UTF-8 encoded.) It takes an optional hashref
4515 of options. If the hashref contains a C<version> argument, the copied metadata
4516 will be converted to the version of the specification and returned. For
4517 example:
4518
4519 my $string = $meta->as_string( {version => "1.4"} );
4520
4521 For C<version> greater than or equal to 2, the string will be serialized as
4522 JSON. For C<version> less than 2, the string will be serialized as YAML. In
4523 both cases, the same rules are followed as in the C<save()> method for choosing
4524 a serialization backend.
4525
4526 The serialized structure will include a C<x_serialization_backend> entry giving
4527 the package and version used to serialize. Any existing key in the given
4528 C<$meta> object will be clobbered.
4529
4530 =head1 STRING DATA
4531
4532 The following methods return a single value, which is the value for the
4533 corresponding entry in the distmeta structure. Values should be either undef
4534 or strings.
4535
4536 =over 4
4537
4538 =item *
4539
4540 abstract
4541
4542 =item *
4543
4544 description
4545
4546 =item *
4547
4548 dynamic_config
4549
4550 =item *
4551
4552 generated_by
4553
4554 =item *
4555
4556 name
4557
4558 =item *
4559
4560 release_status
4561
4562 =item *
4563
4564 version
4565
4566 =back
4567
4568 =head1 LIST DATA
4569
4570 These methods return lists of string values, which might be represented in the
4571 distmeta structure as arrayrefs or scalars:
4572
4573 =over 4
4574
4575 =item *
4576
4577 authors
4578
4579 =item *
4580
4581 keywords
4582
4583 =item *
4584
4585 licenses
4586
4587 =back
4588
4589 The C<authors> and C<licenses> methods may also be called as C<author> and
4590 C<license>, respectively, to match the field name in the distmeta structure.
4591
4592 =head1 MAP DATA
4593
4594 These readers return hashrefs of arbitrary unblessed data structures, each
4595 described more fully in the specification:
4596
4597 =over 4
4598
4599 =item *
4600
4601 meta_spec
4602
4603 =item *
4604
4605 resources
4606
4607 =item *
4608
4609 provides
4610
4611 =item *
4612
4613 no_index
4614
4615 =item *
4616
4617 prereqs
4618
4619 =item *
4620
4621 optional_features
4622
4623 =back
4624
4625 =head1 CUSTOM DATA
4626
4627 A list of custom keys are available from the C<custom_keys> method and
4628 particular keys may be retrieved with the C<custom> method.
4629
4630 say $meta->custom($_) for $meta->custom_keys;
4631
4632 If a custom key refers to a data structure, a deep clone is returned.
4633
4634 =for Pod::Coverage TO_JSON abstract author authors custom custom_keys description dynamic_config
4635 generated_by keywords license licenses meta_spec name no_index
4636 optional_features prereqs provides release_status resources version
4637
4638 =head1 BUGS
4639
4640 Please report any bugs or feature using the CPAN Request Tracker.
4641 Bugs can be submitted through the web interface at
4642 L<http://rt.cpan.org/Dist/Display.html?Queue=CPAN-Meta>
4643
4644 When submitting a bug or request, please include a test-file or a patch to an
4645 existing test-file that illustrates the bug or desired feature.
4646
4647 =head1 SEE ALSO
4648
4649 =over 4
4650
4651 =item *
4652
4653 L<CPAN::Meta::Converter>
4654
4655 =item *
4656
4657 L<CPAN::Meta::Validator>
4658
4659 =back
4660
4661 =for :stopwords cpan testmatrix url annocpan anno bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan
4662
4663 =head1 SUPPORT
4664
4665 =head2 Bugs / Feature Requests
4666
4667 Please report any bugs or feature requests through the issue tracker
4668 at L<https://github.com/Perl-Toolchain-Gang/CPAN-Meta/issues>.
4669 You will be notified automatically of any progress on your issue.
4670
4671 =head2 Source Code
4672
4673 This is open source software. The code repository is available for
4674 public review and contribution under the terms of the license.
4675
4676 L<https://github.com/Perl-Toolchain-Gang/CPAN-Meta>
4677
4678 git clone https://github.com/Perl-Toolchain-Gang/CPAN-Meta.git
4679
4680 =head1 AUTHORS
4681
4682 =over 4
4683
4684 =item *
4685
4686 David Golden <dagolden@cpan.org>
4687
4688 =item *
4689
4690 Ricardo Signes <rjbs@cpan.org>
4691
4692 =back
4693
4694 =head1 CONTRIBUTORS
4695
4696 =for stopwords Ansgar Burchardt Avar Arnfjord Bjarmason Christopher J. Madsen Chuck Adams Cory G Watson Damyan Ivanov Eric Wilhelm Graham Knop Gregor Hermann Karen Etheridge Kenichi Ishigaki Ken Williams Lars Dieckow Leon Timmermans majensen Mark Fowler Matt S Trout Michael G. Schwern mohawk2 moznion Niko Tyni Olaf Alders Olivier Mengué Randy Sims Tomohiro Hosaka
4697
4698 =over 4
4699
4700 =item *
4701
4702 Ansgar Burchardt <ansgar@cpan.org>
4703
4704 =item *
4705
4706 Avar Arnfjord Bjarmason <avar@cpan.org>
4707
4708 =item *
4709
4710 Christopher J. Madsen <cjm@cpan.org>
4711
4712 =item *
4713
4714 Chuck Adams <cja987@gmail.com>
4715
4716 =item *
4717
4718 Cory G Watson <gphat@cpan.org>
4719
4720 =item *
4721
4722 Damyan Ivanov <dam@cpan.org>
4723
4724 =item *
4725
4726 Eric Wilhelm <ewilhelm@cpan.org>
4727
4728 =item *
4729
4730 Graham Knop <haarg@haarg.org>
4731
4732 =item *
4733
4734 Gregor Hermann <gregoa@debian.org>
4735
4736 =item *
4737
4738 Karen Etheridge <ether@cpan.org>
4739
4740 =item *
4741
4742 Kenichi Ishigaki <ishigaki@cpan.org>
4743
4744 =item *
4745
4746 Ken Williams <kwilliams@cpan.org>
4747
4748 =item *
4749
4750 Lars Dieckow <daxim@cpan.org>
4751
4752 =item *
4753
4754 Leon Timmermans <leont@cpan.org>
4755
4756 =item *
4757
4758 majensen <maj@fortinbras.us>
4759
4760 =item *
4761
4762 Mark Fowler <markf@cpan.org>
4763
4764 =item *
4765
4766 Matt S Trout <mst@shadowcat.co.uk>
4767
4768 =item *
4769
4770 Michael G. Schwern <mschwern@cpan.org>
4771
4772 =item *
4773
4774 mohawk2 <mohawk2@users.noreply.github.com>
4775
4776 =item *
4777
4778 moznion <moznion@gmail.com>
4779
4780 =item *
4781
4782 Niko Tyni <ntyni@debian.org>
4783
4784 =item *
4785
4786 Olaf Alders <olaf@wundersolutions.com>
4787
4788 =item *
4789
4790 Olivier Mengué <dolmen@cpan.org>
4791
4792 =item *
4793
4794 Randy Sims <randys@thepierianspring.org>
4795
4796 =item *
4797
4798 Tomohiro Hosaka <bokutin@bokut.in>
4799
4800 =back
4801
4802 =head1 COPYRIGHT AND LICENSE
4803
4804 This software is copyright (c) 2010 by David Golden and Ricardo Signes.
4805
4806 This is free software; you can redistribute it and/or modify it under
4807 the same terms as the Perl 5 programming language system itself.
4808
4809 =cut
4810
4811 __END__
4812
4813
4814 # vim: ts=2 sts=2 sw=2 et :
4815 CPAN_META
4816  
4817 $fatpacked{"CPAN/Meta/Check.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CPAN_META_CHECK';
4818 package CPAN::Meta::Check;
4819 # vi:noet:sts=2:sw=2:ts=2
4820 $CPAN::Meta::Check::VERSION = '0.018';
4821 use strict;
4822 use warnings;
4823
4824 use base 'Exporter';
4825 our @EXPORT = qw//;
4826 our @EXPORT_OK = qw/check_requirements requirements_for verify_dependencies/;
4827 our %EXPORT_TAGS = (all => [ @EXPORT, @EXPORT_OK ] );
4828
4829 use CPAN::Meta::Prereqs 2.132830;
4830 use CPAN::Meta::Requirements 2.121;
4831 use Module::Metadata 1.000023;
4832
4833 sub _check_dep {
4834 my ($reqs, $module, $dirs) = @_;
4835
4836 return $reqs->accepts_module($module, $]) ? () : sprintf "Your Perl (%s) is not in the range '%s'", $], $reqs->requirements_for_module($module) if $module eq 'perl';
4837
4838 my $metadata = Module::Metadata->new_from_module($module, inc => $dirs);
4839 return "Module '$module' is not installed" if not defined $metadata;
4840
4841 my $version = eval { $metadata->version };
4842 return sprintf 'Installed version (%s) of %s is not in range \'%s\'',
4843 (defined $version ? $version : 'undef'), $module, $reqs->requirements_for_module($module)
4844 if not $reqs->accepts_module($module, $version || 0);
4845 return;
4846 }
4847
4848 sub _check_conflict {
4849 my ($reqs, $module, $dirs) = @_;
4850 my $metadata = Module::Metadata->new_from_module($module, inc => $dirs);
4851 return if not defined $metadata;
4852
4853 my $version = eval { $metadata->version };
4854 return sprintf 'Installed version (%s) of %s is in range \'%s\'',
4855 (defined $version ? $version : 'undef'), $module, $reqs->requirements_for_module($module)
4856 if $reqs->accepts_module($module, $version);
4857 return;
4858 }
4859
4860 sub requirements_for {
4861 my ($meta, $phases, $type) = @_;
4862 my $prereqs = ref($meta) eq 'CPAN::Meta' ? $meta->effective_prereqs : $meta;
4863 return $prereqs->merged_requirements(ref($phases) ? $phases : [ $phases ], [ $type ]);
4864 }
4865
4866 sub check_requirements {
4867 my ($reqs, $type, $dirs) = @_;
4868
4869 return +{
4870 map {
4871 $_ => $type ne 'conflicts'
4872 ? scalar _check_dep($reqs, $_, $dirs)
4873 : scalar _check_conflict($reqs, $_, $dirs)
4874 } $reqs->required_modules
4875 };
4876 }
4877
4878 sub verify_dependencies {
4879 my ($meta, $phases, $type, $dirs) = @_;
4880 my $reqs = requirements_for($meta, $phases, $type);
4881 my $issues = check_requirements($reqs, $type, $dirs);
4882 return grep { defined } values %{ $issues };
4883 }
4884
4885 1;
4886
4887 #ABSTRACT: Verify requirements in a CPAN::Meta object
4888
4889 __END__
4890
4891 =pod
4892
4893 =encoding UTF-8
4894
4895 =head1 NAME
4896
4897 CPAN::Meta::Check - Verify requirements in a CPAN::Meta object
4898
4899 =head1 VERSION
4900
4901 version 0.018
4902
4903 =head1 SYNOPSIS
4904
4905 warn "$_\n" for verify_dependencies($meta, [qw/runtime build test/], 'requires');
4906
4907 =head1 DESCRIPTION
4908
4909 This module verifies if requirements described in a CPAN::Meta object are present.
4910
4911 =head1 FUNCTIONS
4912
4913 =head2 check_requirements($reqs, $type, $incdirs)
4914
4915 This function checks if all dependencies in C<$reqs> (a L<CPAN::Meta::Requirements|CPAN::Meta::Requirements> object) are met, taking into account that 'conflicts' dependencies have to be checked in reverse. It returns a hash with the modules as keys and any problems as values; the value for a successfully found module will be undef. Modules are searched for in C<@$incdirs>, defaulting to C<@INC>.
4916
4917 =head2 verify_dependencies($meta, $phases, $types, $incdirs)
4918
4919 Check all requirements in C<$meta> for phases C<$phases> and type C<$type>. Modules are searched for in C<@$incdirs>, defaulting to C<@INC>. C<$meta> should be a L<CPAN::Meta::Prereqs> or L<CPAN::Meta> object.
4920
4921 =head2 requirements_for($meta, $phases, $types)
4922
4923 B<< This function is deprecated and may be removed at some point in the future, please use CPAN::Meta::Prereqs->merged_requirements instead. >>
4924
4925 This function returns a unified L<CPAN::Meta::Requirements|CPAN::Meta::Requirements> object for all C<$type> requirements for C<$phases>. C<$phases> may be either one (scalar) value or an arrayref of valid values as defined by the L<CPAN::Meta spec|CPAN::Meta::Spec>. C<$type> must be a relationship as defined by the same spec. C<$meta> should be a L<CPAN::Meta::Prereqs> or L<CPAN::Meta> object.
4926
4927 =head1 SEE ALSO
4928
4929 =over 4
4930
4931 =item * L<Test::CheckDeps|Test::CheckDeps>
4932
4933 =item * L<CPAN::Meta|CPAN::Meta>
4934
4935 =back
4936
4937 =head1 AUTHOR
4938
4939 Leon Timmermans <leont@cpan.org>
4940
4941 =head1 COPYRIGHT AND LICENSE
4942
4943 This software is copyright (c) 2012 by Leon Timmermans.
4944
4945 This is free software; you can redistribute it and/or modify it under
4946 the same terms as the Perl 5 programming language system itself.
4947
4948 =cut
4949 CPAN_META_CHECK
4950  
4951 $fatpacked{"CPAN/Meta/Converter.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CPAN_META_CONVERTER';
4952 use 5.006;
4953 use strict;
4954 use warnings;
4955 package CPAN::Meta::Converter;
4956
4957 our $VERSION = '2.150005';
4958
4959 #pod =head1 SYNOPSIS
4960 #pod
4961 #pod my $struct = decode_json_file('META.json');
4962 #pod
4963 #pod my $cmc = CPAN::Meta::Converter->new( $struct );
4964 #pod
4965 #pod my $new_struct = $cmc->convert( version => "2" );
4966 #pod
4967 #pod =head1 DESCRIPTION
4968 #pod
4969 #pod This module converts CPAN Meta structures from one form to another. The
4970 #pod primary use is to convert older structures to the most modern version of
4971 #pod the specification, but other transformations may be implemented in the
4972 #pod future as needed. (E.g. stripping all custom fields or stripping all
4973 #pod optional fields.)
4974 #pod
4975 #pod =cut
4976
4977 use CPAN::Meta::Validator;
4978 use CPAN::Meta::Requirements;
4979 use Parse::CPAN::Meta 1.4400 ();
4980
4981 # To help ExtUtils::MakeMaker bootstrap CPAN::Meta::Requirements on perls
4982 # before 5.10, we fall back to the EUMM bundled compatibility version module if
4983 # that's the only thing available. This shouldn't ever happen in a normal CPAN
4984 # install of CPAN::Meta::Requirements, as version.pm will be picked up from
4985 # prereqs and be available at runtime.
4986
4987 BEGIN {
4988 eval "use version ()"; ## no critic
4989 if ( my $err = $@ ) {
4990 eval "use ExtUtils::MakeMaker::version" or die $err; ## no critic
4991 }
4992 }
4993
4994 # Perl 5.10.0 didn't have "is_qv" in version.pm
4995 *_is_qv = version->can('is_qv') ? sub { $_[0]->is_qv } : sub { exists $_[0]->{qv} };
4996
4997 sub _dclone {
4998 my $ref = shift;
4999
5000 # if an object is in the data structure and doesn't specify how to
5001 # turn itself into JSON, we just stringify the object. That does the
5002 # right thing for typical things that might be there, like version objects,
5003 # Path::Class objects, etc.
5004 no warnings 'once';
5005 no warnings 'redefine';
5006 local *UNIVERSAL::TO_JSON = sub { "$_[0]" };
5007
5008 my $json = Parse::CPAN::Meta->json_backend()->new
5009 ->utf8
5010 ->allow_blessed
5011 ->convert_blessed;
5012 $json->decode($json->encode($ref))
5013 }
5014
5015 my %known_specs = (
5016 '2' => 'http://search.cpan.org/perldoc?CPAN::Meta::Spec',
5017 '1.4' => 'http://module-build.sourceforge.net/META-spec-v1.4.html',
5018 '1.3' => 'http://module-build.sourceforge.net/META-spec-v1.3.html',
5019 '1.2' => 'http://module-build.sourceforge.net/META-spec-v1.2.html',
5020 '1.1' => 'http://module-build.sourceforge.net/META-spec-v1.1.html',
5021 '1.0' => 'http://module-build.sourceforge.net/META-spec-v1.0.html'
5022 );
5023
5024 my @spec_list = sort { $a <=> $b } keys %known_specs;
5025 my ($LOWEST, $HIGHEST) = @spec_list[0,-1];
5026
5027 #--------------------------------------------------------------------------#
5028 # converters
5029 #
5030 # called as $converter->($element, $field_name, $full_meta, $to_version)
5031 #
5032 # defined return value used for field
5033 # undef return value means field is skipped
5034 #--------------------------------------------------------------------------#
5035
5036 sub _keep { $_[0] }
5037
5038 sub _keep_or_one { defined($_[0]) ? $_[0] : 1 }
5039
5040 sub _keep_or_zero { defined($_[0]) ? $_[0] : 0 }
5041
5042 sub _keep_or_unknown { defined($_[0]) && length($_[0]) ? $_[0] : "unknown" }
5043
5044 sub _generated_by {
5045 my $gen = shift;
5046 my $sig = __PACKAGE__ . " version " . (__PACKAGE__->VERSION || "<dev>");
5047
5048 return $sig unless defined $gen and length $gen;
5049 return $gen if $gen =~ /\Q$sig/;
5050 return "$gen, $sig";
5051 }
5052
5053 sub _listify { ! defined $_[0] ? undef : ref $_[0] eq 'ARRAY' ? $_[0] : [$_[0]] }
5054
5055 sub _prefix_custom {
5056 my $key = shift;
5057 $key =~ s/^(?!x_) # Unless it already starts with x_
5058 (?:x-?)? # Remove leading x- or x (if present)
5059 /x_/ix; # and prepend x_
5060 return $key;
5061 }
5062
5063 sub _ucfirst_custom {
5064 my $key = shift;
5065 $key = ucfirst $key unless $key =~ /[A-Z]/;
5066 return $key;
5067 }
5068
5069 sub _no_prefix_ucfirst_custom {
5070 my $key = shift;
5071 $key =~ s/^x_//;
5072 return _ucfirst_custom($key);
5073 }
5074
5075 sub _change_meta_spec {
5076 my ($element, undef, undef, $version) = @_;
5077 return {
5078 version => $version,
5079 url => $known_specs{$version},
5080 };
5081 }
5082
5083 my @open_source = (
5084 'perl',
5085 'gpl',
5086 'apache',
5087 'artistic',
5088 'artistic_2',
5089 'lgpl',
5090 'bsd',
5091 'gpl',
5092 'mit',
5093 'mozilla',
5094 'open_source',
5095 );
5096
5097 my %is_open_source = map {; $_ => 1 } @open_source;
5098
5099 my @valid_licenses_1 = (
5100 @open_source,
5101 'unrestricted',
5102 'restrictive',
5103 'unknown',
5104 );
5105
5106 my %license_map_1 = (
5107 ( map { $_ => $_ } @valid_licenses_1 ),
5108 artistic2 => 'artistic_2',
5109 );
5110
5111 sub _license_1 {
5112 my ($element) = @_;
5113 return 'unknown' unless defined $element;
5114 if ( $license_map_1{lc $element} ) {
5115 return $license_map_1{lc $element};
5116 }
5117 else {
5118 return 'unknown';
5119 }
5120 }
5121
5122 my @valid_licenses_2 = qw(
5123 agpl_3
5124 apache_1_1
5125 apache_2_0
5126 artistic_1
5127 artistic_2
5128 bsd
5129 freebsd
5130 gfdl_1_2
5131 gfdl_1_3
5132 gpl_1
5133 gpl_2
5134 gpl_3
5135 lgpl_2_1
5136 lgpl_3_0
5137 mit
5138 mozilla_1_0
5139 mozilla_1_1
5140 openssl
5141 perl_5
5142 qpl_1_0
5143 ssleay
5144 sun
5145 zlib
5146 open_source
5147 restricted
5148 unrestricted
5149 unknown
5150 );
5151
5152 # The "old" values were defined by Module::Build, and were often vague. I have
5153 # made the decisions below based on reading Module::Build::API and how clearly
5154 # it specifies the version of the license.
5155 my %license_map_2 = (
5156 (map { $_ => $_ } @valid_licenses_2),
5157 apache => 'apache_2_0', # clearly stated as 2.0
5158 artistic => 'artistic_1', # clearly stated as 1
5159 artistic2 => 'artistic_2', # clearly stated as 2
5160 gpl => 'open_source', # we don't know which GPL; punt
5161 lgpl => 'open_source', # we don't know which LGPL; punt
5162 mozilla => 'open_source', # we don't know which MPL; punt
5163 perl => 'perl_5', # clearly Perl 5
5164 restrictive => 'restricted',
5165 );
5166
5167 sub _license_2 {
5168 my ($element) = @_;
5169 return [ 'unknown' ] unless defined $element;
5170 $element = [ $element ] unless ref $element eq 'ARRAY';
5171 my @new_list;
5172 for my $lic ( @$element ) {
5173 next unless defined $lic;
5174 if ( my $new = $license_map_2{lc $lic} ) {
5175 push @new_list, $new;
5176 }
5177 }
5178 return @new_list ? \@new_list : [ 'unknown' ];
5179 }
5180
5181 my %license_downgrade_map = qw(
5182 agpl_3 open_source
5183 apache_1_1 apache
5184 apache_2_0 apache
5185 artistic_1 artistic
5186 artistic_2 artistic_2
5187 bsd bsd
5188 freebsd open_source
5189 gfdl_1_2 open_source
5190 gfdl_1_3 open_source
5191 gpl_1 gpl
5192 gpl_2 gpl
5193 gpl_3 gpl
5194 lgpl_2_1 lgpl
5195 lgpl_3_0 lgpl
5196 mit mit
5197 mozilla_1_0 mozilla
5198 mozilla_1_1 mozilla
5199 openssl open_source
5200 perl_5 perl
5201 qpl_1_0 open_source
5202 ssleay open_source
5203 sun open_source
5204 zlib open_source
5205 open_source open_source
5206 restricted restrictive
5207 unrestricted unrestricted
5208 unknown unknown
5209 );
5210
5211 sub _downgrade_license {
5212 my ($element) = @_;
5213 if ( ! defined $element ) {
5214 return "unknown";
5215 }
5216 elsif( ref $element eq 'ARRAY' ) {
5217 if ( @$element > 1) {
5218 if (grep { !$is_open_source{ $license_downgrade_map{lc $_} || 'unknown' } } @$element) {
5219 return 'unknown';
5220 }
5221 else {
5222 return 'open_source';
5223 }
5224 }
5225 elsif ( @$element == 1 ) {
5226 return $license_downgrade_map{lc $element->[0]} || "unknown";
5227 }
5228 }
5229 elsif ( ! ref $element ) {
5230 return $license_downgrade_map{lc $element} || "unknown";
5231 }
5232 return "unknown";
5233 }
5234
5235 my $no_index_spec_1_2 = {
5236 'file' => \&_listify,
5237 'dir' => \&_listify,
5238 'package' => \&_listify,
5239 'namespace' => \&_listify,
5240 };
5241
5242 my $no_index_spec_1_3 = {
5243 'file' => \&_listify,
5244 'directory' => \&_listify,
5245 'package' => \&_listify,
5246 'namespace' => \&_listify,
5247 };
5248
5249 my $no_index_spec_2 = {
5250 'file' => \&_listify,
5251 'directory' => \&_listify,
5252 'package' => \&_listify,
5253 'namespace' => \&_listify,
5254 ':custom' => \&_prefix_custom,
5255 };
5256
5257 sub _no_index_1_2 {
5258 my (undef, undef, $meta) = @_;
5259 my $no_index = $meta->{no_index} || $meta->{private};
5260 return unless $no_index;
5261
5262 # cleanup wrong format
5263 if ( ! ref $no_index ) {
5264 my $item = $no_index;
5265 $no_index = { dir => [ $item ], file => [ $item ] };
5266 }
5267 elsif ( ref $no_index eq 'ARRAY' ) {
5268 my $list = $no_index;
5269 $no_index = { dir => [ @$list ], file => [ @$list ] };
5270 }
5271
5272 # common mistake: files -> file
5273 if ( exists $no_index->{files} ) {
5274 $no_index->{file} = delete $no_index->{files};
5275 }
5276 # common mistake: modules -> module
5277 if ( exists $no_index->{modules} ) {
5278 $no_index->{module} = delete $no_index->{modules};
5279 }
5280 return _convert($no_index, $no_index_spec_1_2);
5281 }
5282
5283 sub _no_index_directory {
5284 my ($element, $key, $meta, $version) = @_;
5285 return unless $element;
5286
5287 # cleanup wrong format
5288 if ( ! ref $element ) {
5289 my $item = $element;
5290 $element = { directory => [ $item ], file => [ $item ] };
5291 }
5292 elsif ( ref $element eq 'ARRAY' ) {
5293 my $list = $element;
5294 $element = { directory => [ @$list ], file => [ @$list ] };
5295 }
5296
5297 if ( exists $element->{dir} ) {
5298 $element->{directory} = delete $element->{dir};
5299 }
5300 # common mistake: files -> file
5301 if ( exists $element->{files} ) {
5302 $element->{file} = delete $element->{files};
5303 }
5304 # common mistake: modules -> module
5305 if ( exists $element->{modules} ) {
5306 $element->{module} = delete $element->{modules};
5307 }
5308 my $spec = $version == 2 ? $no_index_spec_2 : $no_index_spec_1_3;
5309 return _convert($element, $spec);
5310 }
5311
5312 sub _is_module_name {
5313 my $mod = shift;
5314 return unless defined $mod && length $mod;
5315 return $mod =~ m{^[A-Za-z][A-Za-z0-9_]*(?:::[A-Za-z0-9_]+)*$};
5316 }
5317
5318 sub _clean_version {
5319 my ($element) = @_;
5320 return 0 if ! defined $element;
5321
5322 $element =~ s{^\s*}{};
5323 $element =~ s{\s*$}{};
5324 $element =~ s{^\.}{0.};
5325
5326 return 0 if ! length $element;
5327 return 0 if ( $element eq 'undef' || $element eq '<undef>' );
5328
5329 my $v = eval { version->new($element) };
5330 # XXX check defined $v and not just $v because version objects leak memory
5331 # in boolean context -- dagolden, 2012-02-03
5332 if ( defined $v ) {
5333 return _is_qv($v) ? $v->normal : $element;
5334 }
5335 else {
5336 return 0;
5337 }
5338 }
5339
5340 sub _bad_version_hook {
5341 my ($v) = @_;
5342 $v =~ s{^\s*}{};
5343 $v =~ s{\s*$}{};
5344 $v =~ s{[a-z]+$}{}; # strip trailing alphabetics
5345 my $vobj = eval { version->new($v) };
5346 return defined($vobj) ? $vobj : version->new(0); # or give up
5347 }
5348
5349 sub _version_map {
5350 my ($element) = @_;
5351 return unless defined $element;
5352 if ( ref $element eq 'HASH' ) {
5353 # XXX turn this into CPAN::Meta::Requirements with bad version hook
5354 # and then turn it back into a hash
5355 my $new_map = CPAN::Meta::Requirements->new(
5356 { bad_version_hook => \&_bad_version_hook } # punt
5357 );
5358 while ( my ($k,$v) = each %$element ) {
5359 next unless _is_module_name($k);
5360 if ( !defined($v) || !length($v) || $v eq 'undef' || $v eq '<undef>' ) {
5361 $v = 0;
5362 }
5363 # some weird, old META have bad yml with module => module
5364 # so check if value is like a module name and not like a version
5365 if ( _is_module_name($v) && ! version::is_lax($v) ) {
5366 $new_map->add_minimum($k => 0);
5367 $new_map->add_minimum($v => 0);
5368 }
5369 $new_map->add_string_requirement($k => $v);
5370 }
5371 return $new_map->as_string_hash;
5372 }
5373 elsif ( ref $element eq 'ARRAY' ) {
5374 my $hashref = { map { $_ => 0 } @$element };
5375 return _version_map($hashref); # cleanup any weird stuff
5376 }
5377 elsif ( ref $element eq '' && length $element ) {
5378 return { $element => 0 }
5379 }
5380 return;
5381 }
5382
5383 sub _prereqs_from_1 {
5384 my (undef, undef, $meta) = @_;
5385 my $prereqs = {};
5386 for my $phase ( qw/build configure/ ) {
5387 my $key = "${phase}_requires";
5388 $prereqs->{$phase}{requires} = _version_map($meta->{$key})
5389 if $meta->{$key};
5390 }
5391 for my $rel ( qw/requires recommends conflicts/ ) {
5392 $prereqs->{runtime}{$rel} = _version_map($meta->{$rel})
5393 if $meta->{$rel};
5394 }
5395 return $prereqs;
5396 }
5397
5398 my $prereqs_spec = {
5399 configure => \&_prereqs_rel,
5400 build => \&_prereqs_rel,
5401 test => \&_prereqs_rel,
5402 runtime => \&_prereqs_rel,
5403 develop => \&_prereqs_rel,
5404 ':custom' => \&_prefix_custom,
5405 };
5406
5407 my $relation_spec = {
5408 requires => \&_version_map,
5409 recommends => \&_version_map,
5410 suggests => \&_version_map,
5411 conflicts => \&_version_map,
5412 ':custom' => \&_prefix_custom,
5413 };
5414
5415 sub _cleanup_prereqs {
5416 my ($prereqs, $key, $meta, $to_version) = @_;
5417 return unless $prereqs && ref $prereqs eq 'HASH';
5418 return _convert( $prereqs, $prereqs_spec, $to_version );
5419 }
5420
5421 sub _prereqs_rel {
5422 my ($relation, $key, $meta, $to_version) = @_;
5423 return unless $relation && ref $relation eq 'HASH';
5424 return _convert( $relation, $relation_spec, $to_version );
5425 }
5426
5427
5428 BEGIN {
5429 my @old_prereqs = qw(
5430 requires
5431 configure_requires
5432 recommends
5433 conflicts
5434 );
5435
5436 for ( @old_prereqs ) {
5437 my $sub = "_get_$_";
5438 my ($phase,$type) = split qr/_/, $_;
5439 if ( ! defined $type ) {
5440 $type = $phase;
5441 $phase = 'runtime';
5442 }
5443 no strict 'refs';
5444 *{$sub} = sub { _extract_prereqs($_[2]->{prereqs},$phase,$type) };
5445 }
5446 }
5447
5448 sub _get_build_requires {
5449 my ($data, $key, $meta) = @_;
5450
5451 my $test_h = _extract_prereqs($_[2]->{prereqs}, qw(test requires)) || {};
5452 my $build_h = _extract_prereqs($_[2]->{prereqs}, qw(build requires)) || {};
5453
5454 my $test_req = CPAN::Meta::Requirements->from_string_hash($test_h);
5455 my $build_req = CPAN::Meta::Requirements->from_string_hash($build_h);
5456
5457 $test_req->add_requirements($build_req)->as_string_hash;
5458 }
5459
5460 sub _extract_prereqs {
5461 my ($prereqs, $phase, $type) = @_;
5462 return unless ref $prereqs eq 'HASH';
5463 return scalar _version_map($prereqs->{$phase}{$type});
5464 }
5465
5466 sub _downgrade_optional_features {
5467 my (undef, undef, $meta) = @_;
5468 return unless exists $meta->{optional_features};
5469 my $origin = $meta->{optional_features};
5470 my $features = {};
5471 for my $name ( keys %$origin ) {
5472 $features->{$name} = {
5473 description => $origin->{$name}{description},
5474 requires => _extract_prereqs($origin->{$name}{prereqs},'runtime','requires'),
5475 configure_requires => _extract_prereqs($origin->{$name}{prereqs},'runtime','configure_requires'),
5476 build_requires => _extract_prereqs($origin->{$name}{prereqs},'runtime','build_requires'),
5477 recommends => _extract_prereqs($origin->{$name}{prereqs},'runtime','recommends'),
5478 conflicts => _extract_prereqs($origin->{$name}{prereqs},'runtime','conflicts'),
5479 };
5480 for my $k (keys %{$features->{$name}} ) {
5481 delete $features->{$name}{$k} unless defined $features->{$name}{$k};
5482 }
5483 }
5484 return $features;
5485 }
5486
5487 sub _upgrade_optional_features {
5488 my (undef, undef, $meta) = @_;
5489 return unless exists $meta->{optional_features};
5490 my $origin = $meta->{optional_features};
5491 my $features = {};
5492 for my $name ( keys %$origin ) {
5493 $features->{$name} = {
5494 description => $origin->{$name}{description},
5495 prereqs => _prereqs_from_1(undef, undef, $origin->{$name}),
5496 };
5497 delete $features->{$name}{prereqs}{configure};
5498 }
5499 return $features;
5500 }
5501
5502 my $optional_features_2_spec = {
5503 description => \&_keep,
5504 prereqs => \&_cleanup_prereqs,
5505 ':custom' => \&_prefix_custom,
5506 };
5507
5508 sub _feature_2 {
5509 my ($element, $key, $meta, $to_version) = @_;
5510 return unless $element && ref $element eq 'HASH';
5511 _convert( $element, $optional_features_2_spec, $to_version );
5512 }
5513
5514 sub _cleanup_optional_features_2 {
5515 my ($element, $key, $meta, $to_version) = @_;
5516 return unless $element && ref $element eq 'HASH';
5517 my $new_data = {};
5518 for my $k ( keys %$element ) {
5519 $new_data->{$k} = _feature_2( $element->{$k}, $k, $meta, $to_version );
5520 }
5521 return unless keys %$new_data;
5522 return $new_data;
5523 }
5524
5525 sub _optional_features_1_4 {
5526 my ($element) = @_;
5527 return unless $element;
5528 $element = _optional_features_as_map($element);
5529 for my $name ( keys %$element ) {
5530 for my $drop ( qw/requires_packages requires_os excluded_os/ ) {
5531 delete $element->{$name}{$drop};
5532 }
5533 }
5534 return $element;
5535 }
5536
5537 sub _optional_features_as_map {
5538 my ($element) = @_;
5539 return unless $element;
5540 if ( ref $element eq 'ARRAY' ) {
5541 my %map;
5542 for my $feature ( @$element ) {
5543 my (@parts) = %$feature;
5544 $map{$parts[0]} = $parts[1];
5545 }
5546 $element = \%map;
5547 }
5548 return $element;
5549 }
5550
5551 sub _is_urlish { defined $_[0] && $_[0] =~ m{\A[-+.a-z0-9]+:.+}i }
5552
5553 sub _url_or_drop {
5554 my ($element) = @_;
5555 return $element if _is_urlish($element);
5556 return;
5557 }
5558
5559 sub _url_list {
5560 my ($element) = @_;
5561 return unless $element;
5562 $element = _listify( $element );
5563 $element = [ grep { _is_urlish($_) } @$element ];
5564 return unless @$element;
5565 return $element;
5566 }
5567
5568 sub _author_list {
5569 my ($element) = @_;
5570 return [ 'unknown' ] unless $element;
5571 $element = _listify( $element );
5572 $element = [ map { defined $_ && length $_ ? $_ : 'unknown' } @$element ];
5573 return [ 'unknown' ] unless @$element;
5574 return $element;
5575 }
5576
5577 my $resource2_upgrade = {
5578 license => sub { return _is_urlish($_[0]) ? _listify( $_[0] ) : undef },
5579 homepage => \&_url_or_drop,
5580 bugtracker => sub {
5581 my ($item) = @_;
5582 return unless $item;
5583 if ( $item =~ m{^mailto:(.*)$} ) { return { mailto => $1 } }
5584 elsif( _is_urlish($item) ) { return { web => $item } }
5585 else { return }
5586 },
5587 repository => sub { return _is_urlish($_[0]) ? { url => $_[0] } : undef },
5588 ':custom' => \&_prefix_custom,
5589 };
5590
5591 sub _upgrade_resources_2 {
5592 my (undef, undef, $meta, $version) = @_;
5593 return unless exists $meta->{resources};
5594 return _convert($meta->{resources}, $resource2_upgrade);
5595 }
5596
5597 my $bugtracker2_spec = {
5598 web => \&_url_or_drop,
5599 mailto => \&_keep,
5600 ':custom' => \&_prefix_custom,
5601 };
5602
5603 sub _repo_type {
5604 my ($element, $key, $meta, $to_version) = @_;
5605 return $element if defined $element;
5606 return unless exists $meta->{url};
5607 my $repo_url = $meta->{url};
5608 for my $type ( qw/git svn/ ) {
5609 return $type if $repo_url =~ m{\A$type};
5610 }
5611 return;
5612 }
5613
5614 my $repository2_spec = {
5615 web => \&_url_or_drop,
5616 url => \&_url_or_drop,
5617 type => \&_repo_type,
5618 ':custom' => \&_prefix_custom,
5619 };
5620
5621 my $resources2_cleanup = {
5622 license => \&_url_list,
5623 homepage => \&_url_or_drop,
5624 bugtracker => sub { ref $_[0] ? _convert( $_[0], $bugtracker2_spec ) : undef },
5625 repository => sub { my $data = shift; ref $data ? _convert( $data, $repository2_spec ) : undef },
5626 ':custom' => \&_prefix_custom,
5627 };
5628
5629 sub _cleanup_resources_2 {
5630 my ($resources, $key, $meta, $to_version) = @_;
5631 return unless $resources && ref $resources eq 'HASH';
5632 return _convert($resources, $resources2_cleanup, $to_version);
5633 }
5634
5635 my $resource1_spec = {
5636 license => \&_url_or_drop,
5637 homepage => \&_url_or_drop,
5638 bugtracker => \&_url_or_drop,
5639 repository => \&_url_or_drop,
5640 ':custom' => \&_keep,
5641 };
5642
5643 sub _resources_1_3 {
5644 my (undef, undef, $meta, $version) = @_;
5645 return unless exists $meta->{resources};
5646 return _convert($meta->{resources}, $resource1_spec);
5647 }
5648
5649 *_resources_1_4 = *_resources_1_3;
5650
5651 sub _resources_1_2 {
5652 my (undef, undef, $meta) = @_;
5653 my $resources = $meta->{resources} || {};
5654 if ( $meta->{license_url} && ! $resources->{license} ) {
5655 $resources->{license} = $meta->{license_url}
5656 if _is_urlish($meta->{license_url});
5657 }
5658 return unless keys %$resources;
5659 return _convert($resources, $resource1_spec);
5660 }
5661
5662 my $resource_downgrade_spec = {
5663 license => sub { return ref $_[0] ? $_[0]->[0] : $_[0] },
5664 homepage => \&_url_or_drop,
5665 bugtracker => sub { return $_[0]->{web} },
5666 repository => sub { return $_[0]->{url} || $_[0]->{web} },
5667 ':custom' => \&_no_prefix_ucfirst_custom,
5668 };
5669
5670 sub _downgrade_resources {
5671 my (undef, undef, $meta, $version) = @_;
5672 return unless exists $meta->{resources};
5673 return _convert($meta->{resources}, $resource_downgrade_spec);
5674 }
5675
5676 sub _release_status {
5677 my ($element, undef, $meta) = @_;
5678 return $element if $element && $element =~ m{\A(?:stable|testing|unstable)\z};
5679 return _release_status_from_version(undef, undef, $meta);
5680 }
5681
5682 sub _release_status_from_version {
5683 my (undef, undef, $meta) = @_;
5684 my $version = $meta->{version} || '';
5685 return ( $version =~ /_/ ) ? 'testing' : 'stable';
5686 }
5687
5688 my $provides_spec = {
5689 file => \&_keep,
5690 version => \&_keep,
5691 };
5692
5693 my $provides_spec_2 = {
5694 file => \&_keep,
5695 version => \&_keep,
5696 ':custom' => \&_prefix_custom,
5697 };
5698
5699 sub _provides {
5700 my ($element, $key, $meta, $to_version) = @_;
5701 return unless defined $element && ref $element eq 'HASH';
5702 my $spec = $to_version == 2 ? $provides_spec_2 : $provides_spec;
5703 my $new_data = {};
5704 for my $k ( keys %$element ) {
5705 $new_data->{$k} = _convert($element->{$k}, $spec, $to_version);
5706 $new_data->{$k}{version} = _clean_version($element->{$k}{version})
5707 if exists $element->{$k}{version};
5708 }
5709 return $new_data;
5710 }
5711
5712 sub _convert {
5713 my ($data, $spec, $to_version, $is_fragment) = @_;
5714
5715 my $new_data = {};
5716 for my $key ( keys %$spec ) {
5717 next if $key eq ':custom' || $key eq ':drop';
5718 next unless my $fcn = $spec->{$key};
5719 if ( $is_fragment && $key eq 'generated_by' ) {
5720 $fcn = \&_keep;
5721 }
5722 die "spec for '$key' is not a coderef"
5723 unless ref $fcn && ref $fcn eq 'CODE';
5724 my $new_value = $fcn->($data->{$key}, $key, $data, $to_version);
5725 $new_data->{$key} = $new_value if defined $new_value;
5726 }
5727
5728 my $drop_list = $spec->{':drop'};
5729 my $customizer = $spec->{':custom'} || \&_keep;
5730
5731 for my $key ( keys %$data ) {
5732 next if $drop_list && grep { $key eq $_ } @$drop_list;
5733 next if exists $spec->{$key}; # we handled it
5734 $new_data->{ $customizer->($key) } = $data->{$key};
5735 }
5736
5737 return $new_data;
5738 }
5739
5740 #--------------------------------------------------------------------------#
5741 # define converters for each conversion
5742 #--------------------------------------------------------------------------#
5743
5744 # each converts from prior version
5745 # special ":custom" field is used for keys not recognized in spec
5746 my %up_convert = (
5747 '2-from-1.4' => {
5748 # PRIOR MANDATORY
5749 'abstract' => \&_keep_or_unknown,
5750 'author' => \&_author_list,
5751 'generated_by' => \&_generated_by,
5752 'license' => \&_license_2,
5753 'meta-spec' => \&_change_meta_spec,
5754 'name' => \&_keep,
5755 'version' => \&_keep,
5756 # CHANGED TO MANDATORY
5757 'dynamic_config' => \&_keep_or_one,
5758 # ADDED MANDATORY
5759 'release_status' => \&_release_status,
5760 # PRIOR OPTIONAL
5761 'keywords' => \&_keep,
5762 'no_index' => \&_no_index_directory,
5763 'optional_features' => \&_upgrade_optional_features,
5764 'provides' => \&_provides,
5765 'resources' => \&_upgrade_resources_2,
5766 # ADDED OPTIONAL
5767 'description' => \&_keep,
5768 'prereqs' => \&_prereqs_from_1,
5769
5770 # drop these deprecated fields, but only after we convert
5771 ':drop' => [ qw(
5772 build_requires
5773 configure_requires
5774 conflicts
5775 distribution_type
5776 license_url
5777 private
5778 recommends
5779 requires
5780 ) ],
5781
5782 # other random keys need x_ prefixing
5783 ':custom' => \&_prefix_custom,
5784 },
5785 '1.4-from-1.3' => {
5786 # PRIOR MANDATORY
5787 'abstract' => \&_keep_or_unknown,
5788 'author' => \&_author_list,
5789 'generated_by' => \&_generated_by,
5790 'license' => \&_license_1,
5791 'meta-spec' => \&_change_meta_spec,
5792 'name' => \&_keep,
5793 'version' => \&_keep,
5794 # PRIOR OPTIONAL
5795 'build_requires' => \&_version_map,
5796 'conflicts' => \&_version_map,
5797 'distribution_type' => \&_keep,
5798 'dynamic_config' => \&_keep_or_one,
5799 'keywords' => \&_keep,
5800 'no_index' => \&_no_index_directory,
5801 'optional_features' => \&_optional_features_1_4,
5802 'provides' => \&_provides,
5803 'recommends' => \&_version_map,
5804 'requires' => \&_version_map,
5805 'resources' => \&_resources_1_4,
5806 # ADDED OPTIONAL
5807 'configure_requires' => \&_keep,
5808
5809 # drop these deprecated fields, but only after we convert
5810 ':drop' => [ qw(
5811 license_url
5812 private
5813 )],
5814
5815 # other random keys are OK if already valid
5816 ':custom' => \&_keep
5817 },
5818 '1.3-from-1.2' => {
5819 # PRIOR MANDATORY
5820 'abstract' => \&_keep_or_unknown,
5821 'author' => \&_author_list,
5822 'generated_by' => \&_generated_by,
5823 'license' => \&_license_1,
5824 'meta-spec' => \&_change_meta_spec,
5825 'name' => \&_keep,
5826 'version' => \&_keep,
5827 # PRIOR OPTIONAL
5828 'build_requires' => \&_version_map,
5829 'conflicts' => \&_version_map,
5830 'distribution_type' => \&_keep,
5831 'dynamic_config' => \&_keep_or_one,
5832 'keywords' => \&_keep,
5833 'no_index' => \&_no_index_directory,
5834 'optional_features' => \&_optional_features_as_map,
5835 'provides' => \&_provides,
5836 'recommends' => \&_version_map,
5837 'requires' => \&_version_map,
5838 'resources' => \&_resources_1_3,
5839
5840 # drop these deprecated fields, but only after we convert
5841 ':drop' => [ qw(
5842 license_url
5843 private
5844 )],
5845
5846 # other random keys are OK if already valid
5847 ':custom' => \&_keep
5848 },
5849 '1.2-from-1.1' => {
5850 # PRIOR MANDATORY
5851 'version' => \&_keep,
5852 # CHANGED TO MANDATORY
5853 'license' => \&_license_1,
5854 'name' => \&_keep,
5855 'generated_by' => \&_generated_by,
5856 # ADDED MANDATORY
5857 'abstract' => \&_keep_or_unknown,
5858 'author' => \&_author_list,
5859 'meta-spec' => \&_change_meta_spec,
5860 # PRIOR OPTIONAL
5861 'build_requires' => \&_version_map,
5862 'conflicts' => \&_version_map,
5863 'distribution_type' => \&_keep,
5864 'dynamic_config' => \&_keep_or_one,
5865 'recommends' => \&_version_map,
5866 'requires' => \&_version_map,
5867 # ADDED OPTIONAL
5868 'keywords' => \&_keep,
5869 'no_index' => \&_no_index_1_2,
5870 'optional_features' => \&_optional_features_as_map,
5871 'provides' => \&_provides,
5872 'resources' => \&_resources_1_2,
5873
5874 # drop these deprecated fields, but only after we convert
5875 ':drop' => [ qw(
5876 license_url
5877 private
5878 )],
5879
5880 # other random keys are OK if already valid
5881 ':custom' => \&_keep
5882 },
5883 '1.1-from-1.0' => {
5884 # CHANGED TO MANDATORY
5885 'version' => \&_keep,
5886 # IMPLIED MANDATORY
5887 'name' => \&_keep,
5888 # PRIOR OPTIONAL
5889 'build_requires' => \&_version_map,
5890 'conflicts' => \&_version_map,
5891 'distribution_type' => \&_keep,
5892 'dynamic_config' => \&_keep_or_one,
5893 'generated_by' => \&_generated_by,
5894 'license' => \&_license_1,
5895 'recommends' => \&_version_map,
5896 'requires' => \&_version_map,
5897 # ADDED OPTIONAL
5898 'license_url' => \&_url_or_drop,
5899 'private' => \&_keep,
5900
5901 # other random keys are OK if already valid
5902 ':custom' => \&_keep
5903 },
5904 );
5905
5906 my %down_convert = (
5907 '1.4-from-2' => {
5908 # MANDATORY
5909 'abstract' => \&_keep_or_unknown,
5910 'author' => \&_author_list,
5911 'generated_by' => \&_generated_by,
5912 'license' => \&_downgrade_license,
5913 'meta-spec' => \&_change_meta_spec,
5914 'name' => \&_keep,
5915 'version' => \&_keep,
5916 # OPTIONAL
5917 'build_requires' => \&_get_build_requires,
5918 'configure_requires' => \&_get_configure_requires,
5919 'conflicts' => \&_get_conflicts,
5920 'distribution_type' => \&_keep,
5921 'dynamic_config' => \&_keep_or_one,
5922 'keywords' => \&_keep,
5923 'no_index' => \&_no_index_directory,
5924 'optional_features' => \&_downgrade_optional_features,
5925 'provides' => \&_provides,
5926 'recommends' => \&_get_recommends,
5927 'requires' => \&_get_requires,
5928 'resources' => \&_downgrade_resources,
5929
5930 # drop these unsupported fields (after conversion)
5931 ':drop' => [ qw(
5932 description
5933 prereqs
5934 release_status
5935 )],
5936
5937 # custom keys will be left unchanged
5938 ':custom' => \&_keep
5939 },
5940 '1.3-from-1.4' => {
5941 # MANDATORY
5942 'abstract' => \&_keep_or_unknown,
5943 'author' => \&_author_list,
5944 'generated_by' => \&_generated_by,
5945 'license' => \&_license_1,
5946 'meta-spec' => \&_change_meta_spec,
5947 'name' => \&_keep,
5948 'version' => \&_keep,
5949 # OPTIONAL
5950 'build_requires' => \&_version_map,
5951 'conflicts' => \&_version_map,
5952 'distribution_type' => \&_keep,
5953 'dynamic_config' => \&_keep_or_one,
5954 'keywords' => \&_keep,
5955 'no_index' => \&_no_index_directory,
5956 'optional_features' => \&_optional_features_as_map,
5957 'provides' => \&_provides,
5958 'recommends' => \&_version_map,
5959 'requires' => \&_version_map,
5960 'resources' => \&_resources_1_3,
5961
5962 # drop these unsupported fields, but only after we convert
5963 ':drop' => [ qw(
5964 configure_requires
5965 )],
5966
5967 # other random keys are OK if already valid
5968 ':custom' => \&_keep,
5969 },
5970 '1.2-from-1.3' => {
5971 # MANDATORY
5972 'abstract' => \&_keep_or_unknown,
5973 'author' => \&_author_list,
5974 'generated_by' => \&_generated_by,
5975 'license' => \&_license_1,
5976 'meta-spec' => \&_change_meta_spec,
5977 'name' => \&_keep,
5978 'version' => \&_keep,
5979 # OPTIONAL
5980 'build_requires' => \&_version_map,
5981 'conflicts' => \&_version_map,
5982 'distribution_type' => \&_keep,
5983 'dynamic_config' => \&_keep_or_one,
5984 'keywords' => \&_keep,
5985 'no_index' => \&_no_index_1_2,
5986 'optional_features' => \&_optional_features_as_map,
5987 'provides' => \&_provides,
5988 'recommends' => \&_version_map,
5989 'requires' => \&_version_map,
5990 'resources' => \&_resources_1_3,
5991
5992 # other random keys are OK if already valid
5993 ':custom' => \&_keep,
5994 },
5995 '1.1-from-1.2' => {
5996 # MANDATORY
5997 'version' => \&_keep,
5998 # IMPLIED MANDATORY
5999 'name' => \&_keep,
6000 'meta-spec' => \&_change_meta_spec,
6001 # OPTIONAL
6002 'build_requires' => \&_version_map,
6003 'conflicts' => \&_version_map,
6004 'distribution_type' => \&_keep,
6005 'dynamic_config' => \&_keep_or_one,
6006 'generated_by' => \&_generated_by,
6007 'license' => \&_license_1,
6008 'private' => \&_keep,
6009 'recommends' => \&_version_map,
6010 'requires' => \&_version_map,
6011
6012 # drop unsupported fields
6013 ':drop' => [ qw(
6014 abstract
6015 author
6016 provides
6017 no_index
6018 keywords
6019 resources
6020 )],
6021
6022 # other random keys are OK if already valid
6023 ':custom' => \&_keep,
6024 },
6025 '1.0-from-1.1' => {
6026 # IMPLIED MANDATORY
6027 'name' => \&_keep,
6028 'meta-spec' => \&_change_meta_spec,
6029 'version' => \&_keep,
6030 # PRIOR OPTIONAL
6031 'build_requires' => \&_version_map,
6032 'conflicts' => \&_version_map,
6033 'distribution_type' => \&_keep,
6034 'dynamic_config' => \&_keep_or_one,
6035 'generated_by' => \&_generated_by,
6036 'license' => \&_license_1,
6037 'recommends' => \&_version_map,
6038 'requires' => \&_version_map,
6039
6040 # other random keys are OK if already valid
6041 ':custom' => \&_keep,
6042 },
6043 );
6044
6045 my %cleanup = (
6046 '2' => {
6047 # PRIOR MANDATORY
6048 'abstract' => \&_keep_or_unknown,
6049 'author' => \&_author_list,
6050 'generated_by' => \&_generated_by,
6051 'license' => \&_license_2,
6052 'meta-spec' => \&_change_meta_spec,
6053 'name' => \&_keep,
6054 'version' => \&_keep,
6055 # CHANGED TO MANDATORY
6056 'dynamic_config' => \&_keep_or_one,
6057 # ADDED MANDATORY
6058 'release_status' => \&_release_status,
6059 # PRIOR OPTIONAL
6060 'keywords' => \&_keep,
6061 'no_index' => \&_no_index_directory,
6062 'optional_features' => \&_cleanup_optional_features_2,
6063 'provides' => \&_provides,
6064 'resources' => \&_cleanup_resources_2,
6065 # ADDED OPTIONAL
6066 'description' => \&_keep,
6067 'prereqs' => \&_cleanup_prereqs,
6068
6069 # drop these deprecated fields, but only after we convert
6070 ':drop' => [ qw(
6071 build_requires
6072 configure_requires
6073 conflicts
6074 distribution_type
6075 license_url
6076 private
6077 recommends
6078 requires
6079 ) ],
6080
6081 # other random keys need x_ prefixing
6082 ':custom' => \&_prefix_custom,
6083 },
6084 '1.4' => {
6085 # PRIOR MANDATORY
6086 'abstract' => \&_keep_or_unknown,
6087 'author' => \&_author_list,
6088 'generated_by' => \&_generated_by,
6089 'license' => \&_license_1,
6090 'meta-spec' => \&_change_meta_spec,
6091 'name' => \&_keep,
6092 'version' => \&_keep,
6093 # PRIOR OPTIONAL
6094 'build_requires' => \&_version_map,
6095 'conflicts' => \&_version_map,
6096 'distribution_type' => \&_keep,
6097 'dynamic_config' => \&_keep_or_one,
6098 'keywords' => \&_keep,
6099 'no_index' => \&_no_index_directory,
6100 'optional_features' => \&_optional_features_1_4,
6101 'provides' => \&_provides,
6102 'recommends' => \&_version_map,
6103 'requires' => \&_version_map,
6104 'resources' => \&_resources_1_4,
6105 # ADDED OPTIONAL
6106 'configure_requires' => \&_keep,
6107
6108 # other random keys are OK if already valid
6109 ':custom' => \&_keep
6110 },
6111 '1.3' => {
6112 # PRIOR MANDATORY
6113 'abstract' => \&_keep_or_unknown,
6114 'author' => \&_author_list,
6115 'generated_by' => \&_generated_by,
6116 'license' => \&_license_1,
6117 'meta-spec' => \&_change_meta_spec,
6118 'name' => \&_keep,
6119 'version' => \&_keep,
6120 # PRIOR OPTIONAL
6121 'build_requires' => \&_version_map,
6122 'conflicts' => \&_version_map,
6123 'distribution_type' => \&_keep,
6124 'dynamic_config' => \&_keep_or_one,
6125 'keywords' => \&_keep,
6126 'no_index' => \&_no_index_directory,
6127 'optional_features' => \&_optional_features_as_map,
6128 'provides' => \&_provides,
6129 'recommends' => \&_version_map,
6130 'requires' => \&_version_map,
6131 'resources' => \&_resources_1_3,
6132
6133 # other random keys are OK if already valid
6134 ':custom' => \&_keep
6135 },
6136 '1.2' => {
6137 # PRIOR MANDATORY
6138 'version' => \&_keep,
6139 # CHANGED TO MANDATORY
6140 'license' => \&_license_1,
6141 'name' => \&_keep,
6142 'generated_by' => \&_generated_by,
6143 # ADDED MANDATORY
6144 'abstract' => \&_keep_or_unknown,
6145 'author' => \&_author_list,
6146 'meta-spec' => \&_change_meta_spec,
6147 # PRIOR OPTIONAL
6148 'build_requires' => \&_version_map,
6149 'conflicts' => \&_version_map,
6150 'distribution_type' => \&_keep,
6151 'dynamic_config' => \&_keep_or_one,
6152 'recommends' => \&_version_map,
6153 'requires' => \&_version_map,
6154 # ADDED OPTIONAL
6155 'keywords' => \&_keep,
6156 'no_index' => \&_no_index_1_2,
6157 'optional_features' => \&_optional_features_as_map,
6158 'provides' => \&_provides,
6159 'resources' => \&_resources_1_2,
6160
6161 # other random keys are OK if already valid
6162 ':custom' => \&_keep
6163 },
6164 '1.1' => {
6165 # CHANGED TO MANDATORY
6166 'version' => \&_keep,
6167 # IMPLIED MANDATORY
6168 'name' => \&_keep,
6169 'meta-spec' => \&_change_meta_spec,
6170 # PRIOR OPTIONAL
6171 'build_requires' => \&_version_map,
6172 'conflicts' => \&_version_map,
6173 'distribution_type' => \&_keep,
6174 'dynamic_config' => \&_keep_or_one,
6175 'generated_by' => \&_generated_by,
6176 'license' => \&_license_1,
6177 'recommends' => \&_version_map,
6178 'requires' => \&_version_map,
6179 # ADDED OPTIONAL
6180 'license_url' => \&_url_or_drop,
6181 'private' => \&_keep,
6182
6183 # other random keys are OK if already valid
6184 ':custom' => \&_keep
6185 },
6186 '1.0' => {
6187 # IMPLIED MANDATORY
6188 'name' => \&_keep,
6189 'meta-spec' => \&_change_meta_spec,
6190 'version' => \&_keep,
6191 # IMPLIED OPTIONAL
6192 'build_requires' => \&_version_map,
6193 'conflicts' => \&_version_map,
6194 'distribution_type' => \&_keep,
6195 'dynamic_config' => \&_keep_or_one,
6196 'generated_by' => \&_generated_by,
6197 'license' => \&_license_1,
6198 'recommends' => \&_version_map,
6199 'requires' => \&_version_map,
6200
6201 # other random keys are OK if already valid
6202 ':custom' => \&_keep,
6203 },
6204 );
6205
6206 # for a given field in a spec version, what fields will it feed
6207 # into in the *latest* spec (i.e. v2); meta-spec omitted because
6208 # we always expect a meta-spec to be generated
6209 my %fragments_generate = (
6210 '2' => {
6211 'abstract' => 'abstract',
6212 'author' => 'author',
6213 'generated_by' => 'generated_by',
6214 'license' => 'license',
6215 'name' => 'name',
6216 'version' => 'version',
6217 'dynamic_config' => 'dynamic_config',
6218 'release_status' => 'release_status',
6219 'keywords' => 'keywords',
6220 'no_index' => 'no_index',
6221 'optional_features' => 'optional_features',
6222 'provides' => 'provides',
6223 'resources' => 'resources',
6224 'description' => 'description',
6225 'prereqs' => 'prereqs',
6226 },
6227 '1.4' => {
6228 'abstract' => 'abstract',
6229 'author' => 'author',
6230 'generated_by' => 'generated_by',
6231 'license' => 'license',
6232 'name' => 'name',
6233 'version' => 'version',
6234 'build_requires' => 'prereqs',
6235 'conflicts' => 'prereqs',
6236 'distribution_type' => 'distribution_type',
6237 'dynamic_config' => 'dynamic_config',
6238 'keywords' => 'keywords',
6239 'no_index' => 'no_index',
6240 'optional_features' => 'optional_features',
6241 'provides' => 'provides',
6242 'recommends' => 'prereqs',
6243 'requires' => 'prereqs',
6244 'resources' => 'resources',
6245 'configure_requires' => 'prereqs',
6246 },
6247 );
6248 # this is not quite true but will work well enough
6249 # as 1.4 is a superset of earlier ones
6250 $fragments_generate{$_} = $fragments_generate{'1.4'} for qw/1.3 1.2 1.1 1.0/;
6251
6252 #--------------------------------------------------------------------------#
6253 # Code
6254 #--------------------------------------------------------------------------#
6255
6256 #pod =method new
6257 #pod
6258 #pod my $cmc = CPAN::Meta::Converter->new( $struct );
6259 #pod
6260 #pod The constructor should be passed a valid metadata structure but invalid
6261 #pod structures are accepted. If no meta-spec version is provided, version 1.0 will
6262 #pod be assumed.
6263 #pod
6264 #pod Optionally, you can provide a C<default_version> argument after C<$struct>:
6265 #pod
6266 #pod my $cmc = CPAN::Meta::Converter->new( $struct, default_version => "1.4" );
6267 #pod
6268 #pod This is only needed when converting a metadata fragment that does not include a
6269 #pod C<meta-spec> field.
6270 #pod
6271 #pod =cut
6272
6273 sub new {
6274 my ($class,$data,%args) = @_;
6275
6276 # create an attributes hash
6277 my $self = {
6278 'data' => $data,
6279 'spec' => _extract_spec_version($data, $args{default_version}),
6280 };
6281
6282 # create the object
6283 return bless $self, $class;
6284 }
6285
6286 sub _extract_spec_version {
6287 my ($data, $default) = @_;
6288 my $spec = $data->{'meta-spec'};
6289
6290 # is meta-spec there and valid?
6291 return( $default || "1.0" ) unless defined $spec && ref $spec eq 'HASH'; # before meta-spec?
6292
6293 # does the version key look like a valid version?
6294 my $v = $spec->{version};
6295 if ( defined $v && $v =~ /^\d+(?:\.\d+)?$/ ) {
6296 return $v if defined $v && grep { $v eq $_ } keys %known_specs; # known spec
6297 return $v+0 if defined $v && grep { $v == $_ } keys %known_specs; # 2.0 => 2
6298 }
6299
6300 # otherwise, use heuristics: look for 1.x vs 2.0 fields
6301 return "2" if exists $data->{prereqs};
6302 return "1.4" if exists $data->{configure_requires};
6303 return( $default || "1.2" ); # when meta-spec was first defined
6304 }
6305
6306 #pod =method convert
6307 #pod
6308 #pod my $new_struct = $cmc->convert( version => "2" );
6309 #pod
6310 #pod Returns a new hash reference with the metadata converted to a different form.
6311 #pod C<convert> will die if any conversion/standardization still results in an
6312 #pod invalid structure.
6313 #pod
6314 #pod Valid parameters include:
6315 #pod
6316 #pod =over
6317 #pod
6318 #pod =item *
6319 #pod
6320 #pod C<version> -- Indicates the desired specification version (e.g. "1.0", "1.1" ... "1.4", "2").
6321 #pod Defaults to the latest version of the CPAN Meta Spec.
6322 #pod
6323 #pod =back
6324 #pod
6325 #pod Conversion proceeds through each version in turn. For example, a version 1.2
6326 #pod structure might be converted to 1.3 then 1.4 then finally to version 2. The
6327 #pod conversion process attempts to clean-up simple errors and standardize data.
6328 #pod For example, if C<author> is given as a scalar, it will converted to an array
6329 #pod reference containing the item. (Converting a structure to its own version will
6330 #pod also clean-up and standardize.)
6331 #pod
6332 #pod When data are cleaned and standardized, missing or invalid fields will be
6333 #pod replaced with sensible defaults when possible. This may be lossy or imprecise.
6334 #pod For example, some badly structured META.yml files on CPAN have prerequisite
6335 #pod modules listed as both keys and values:
6336 #pod
6337 #pod requires => { 'Foo::Bar' => 'Bam::Baz' }
6338 #pod
6339 #pod These would be split and each converted to a prerequisite with a minimum
6340 #pod version of zero.
6341 #pod
6342 #pod When some mandatory fields are missing or invalid, the conversion will attempt
6343 #pod to provide a sensible default or will fill them with a value of 'unknown'. For
6344 #pod example a missing or unrecognized C<license> field will result in a C<license>
6345 #pod field of 'unknown'. Fields that may get an 'unknown' include:
6346 #pod
6347 #pod =for :list
6348 #pod * abstract
6349 #pod * author
6350 #pod * license
6351 #pod
6352 #pod =cut
6353
6354 sub convert {
6355 my ($self, %args) = @_;
6356 my $args = { %args };
6357
6358 my $new_version = $args->{version} || $HIGHEST;
6359 my $is_fragment = $args->{is_fragment};
6360
6361 my ($old_version) = $self->{spec};
6362 my $converted = _dclone($self->{data});
6363
6364 if ( $old_version == $new_version ) {
6365 $converted = _convert( $converted, $cleanup{$old_version}, $old_version, $is_fragment );
6366 unless ( $args->{is_fragment} ) {
6367 my $cmv = CPAN::Meta::Validator->new( $converted );
6368 unless ( $cmv->is_valid ) {
6369 my $errs = join("\n", $cmv->errors);
6370 die "Failed to clean-up $old_version metadata. Errors:\n$errs\n";
6371 }
6372 }
6373 return $converted;
6374 }
6375 elsif ( $old_version > $new_version ) {
6376 my @vers = sort { $b <=> $a } keys %known_specs;
6377 for my $i ( 0 .. $#vers-1 ) {
6378 next if $vers[$i] > $old_version;
6379 last if $vers[$i+1] < $new_version;
6380 my $spec_string = "$vers[$i+1]-from-$vers[$i]";
6381 $converted = _convert( $converted, $down_convert{$spec_string}, $vers[$i+1], $is_fragment );
6382 unless ( $args->{is_fragment} ) {
6383 my $cmv = CPAN::Meta::Validator->new( $converted );
6384 unless ( $cmv->is_valid ) {
6385 my $errs = join("\n", $cmv->errors);
6386 die "Failed to downconvert metadata to $vers[$i+1]. Errors:\n$errs\n";
6387 }
6388 }
6389 }
6390 return $converted;
6391 }
6392 else {
6393 my @vers = sort { $a <=> $b } keys %known_specs;
6394 for my $i ( 0 .. $#vers-1 ) {
6395 next if $vers[$i] < $old_version;
6396 last if $vers[$i+1] > $new_version;
6397 my $spec_string = "$vers[$i+1]-from-$vers[$i]";
6398 $converted = _convert( $converted, $up_convert{$spec_string}, $vers[$i+1], $is_fragment );
6399 unless ( $args->{is_fragment} ) {
6400 my $cmv = CPAN::Meta::Validator->new( $converted );
6401 unless ( $cmv->is_valid ) {
6402 my $errs = join("\n", $cmv->errors);
6403 die "Failed to upconvert metadata to $vers[$i+1]. Errors:\n$errs\n";
6404 }
6405 }
6406 }
6407 return $converted;
6408 }
6409 }
6410
6411 #pod =method upgrade_fragment
6412 #pod
6413 #pod my $new_struct = $cmc->upgrade_fragment;
6414 #pod
6415 #pod Returns a new hash reference with the metadata converted to the latest version
6416 #pod of the CPAN Meta Spec. No validation is done on the result -- you must
6417 #pod validate after merging fragments into a complete metadata document.
6418 #pod
6419 #pod Available since version 2.141170.
6420 #pod
6421 #pod =cut
6422
6423 sub upgrade_fragment {
6424 my ($self) = @_;
6425 my ($old_version) = $self->{spec};
6426 my %expected =
6427 map {; $_ => 1 }
6428 grep { defined }
6429 map { $fragments_generate{$old_version}{$_} }
6430 keys %{ $self->{data} };
6431 my $converted = $self->convert( version => $HIGHEST, is_fragment => 1 );
6432 for my $key ( keys %$converted ) {
6433 next if $key =~ /^x_/i || $key eq 'meta-spec';
6434 delete $converted->{$key} unless $expected{$key};
6435 }
6436 return $converted;
6437 }
6438
6439 1;
6440
6441 # ABSTRACT: Convert CPAN distribution metadata structures
6442
6443 =pod
6444
6445 =encoding UTF-8
6446
6447 =head1 NAME
6448
6449 CPAN::Meta::Converter - Convert CPAN distribution metadata structures
6450
6451 =head1 VERSION
6452
6453 version 2.150005
6454
6455 =head1 SYNOPSIS
6456
6457 my $struct = decode_json_file('META.json');
6458
6459 my $cmc = CPAN::Meta::Converter->new( $struct );
6460
6461 my $new_struct = $cmc->convert( version => "2" );
6462
6463 =head1 DESCRIPTION
6464
6465 This module converts CPAN Meta structures from one form to another. The
6466 primary use is to convert older structures to the most modern version of
6467 the specification, but other transformations may be implemented in the
6468 future as needed. (E.g. stripping all custom fields or stripping all
6469 optional fields.)
6470
6471 =head1 METHODS
6472
6473 =head2 new
6474
6475 my $cmc = CPAN::Meta::Converter->new( $struct );
6476
6477 The constructor should be passed a valid metadata structure but invalid
6478 structures are accepted. If no meta-spec version is provided, version 1.0 will
6479 be assumed.
6480
6481 Optionally, you can provide a C<default_version> argument after C<$struct>:
6482
6483 my $cmc = CPAN::Meta::Converter->new( $struct, default_version => "1.4" );
6484
6485 This is only needed when converting a metadata fragment that does not include a
6486 C<meta-spec> field.
6487
6488 =head2 convert
6489
6490 my $new_struct = $cmc->convert( version => "2" );
6491
6492 Returns a new hash reference with the metadata converted to a different form.
6493 C<convert> will die if any conversion/standardization still results in an
6494 invalid structure.
6495
6496 Valid parameters include:
6497
6498 =over
6499
6500 =item *
6501
6502 C<version> -- Indicates the desired specification version (e.g. "1.0", "1.1" ... "1.4", "2").
6503 Defaults to the latest version of the CPAN Meta Spec.
6504
6505 =back
6506
6507 Conversion proceeds through each version in turn. For example, a version 1.2
6508 structure might be converted to 1.3 then 1.4 then finally to version 2. The
6509 conversion process attempts to clean-up simple errors and standardize data.
6510 For example, if C<author> is given as a scalar, it will converted to an array
6511 reference containing the item. (Converting a structure to its own version will
6512 also clean-up and standardize.)
6513
6514 When data are cleaned and standardized, missing or invalid fields will be
6515 replaced with sensible defaults when possible. This may be lossy or imprecise.
6516 For example, some badly structured META.yml files on CPAN have prerequisite
6517 modules listed as both keys and values:
6518
6519 requires => { 'Foo::Bar' => 'Bam::Baz' }
6520
6521 These would be split and each converted to a prerequisite with a minimum
6522 version of zero.
6523
6524 When some mandatory fields are missing or invalid, the conversion will attempt
6525 to provide a sensible default or will fill them with a value of 'unknown'. For
6526 example a missing or unrecognized C<license> field will result in a C<license>
6527 field of 'unknown'. Fields that may get an 'unknown' include:
6528
6529 =over 4
6530
6531 =item *
6532
6533 abstract
6534
6535 =item *
6536
6537 author
6538
6539 =item *
6540
6541 license
6542
6543 =back
6544
6545 =head2 upgrade_fragment
6546
6547 my $new_struct = $cmc->upgrade_fragment;
6548
6549 Returns a new hash reference with the metadata converted to the latest version
6550 of the CPAN Meta Spec. No validation is done on the result -- you must
6551 validate after merging fragments into a complete metadata document.
6552
6553 Available since version 2.141170.
6554
6555 =head1 BUGS
6556
6557 Please report any bugs or feature using the CPAN Request Tracker.
6558 Bugs can be submitted through the web interface at
6559 L<http://rt.cpan.org/Dist/Display.html?Queue=CPAN-Meta>
6560
6561 When submitting a bug or request, please include a test-file or a patch to an
6562 existing test-file that illustrates the bug or desired feature.
6563
6564 =head1 AUTHORS
6565
6566 =over 4
6567
6568 =item *
6569
6570 David Golden <dagolden@cpan.org>
6571
6572 =item *
6573
6574 Ricardo Signes <rjbs@cpan.org>
6575
6576 =back
6577
6578 =head1 COPYRIGHT AND LICENSE
6579
6580 This software is copyright (c) 2010 by David Golden and Ricardo Signes.
6581
6582 This is free software; you can redistribute it and/or modify it under
6583 the same terms as the Perl 5 programming language system itself.
6584
6585 =cut
6586
6587 __END__
6588
6589
6590 # vim: ts=2 sts=2 sw=2 et :
6591 CPAN_META_CONVERTER
6592  
6593 $fatpacked{"CPAN/Meta/Feature.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CPAN_META_FEATURE';
6594 use 5.006;
6595 use strict;
6596 use warnings;
6597 package CPAN::Meta::Feature;
6598
6599 our $VERSION = '2.150005';
6600
6601 use CPAN::Meta::Prereqs;
6602
6603 #pod =head1 DESCRIPTION
6604 #pod
6605 #pod A CPAN::Meta::Feature object describes an optional feature offered by a CPAN
6606 #pod distribution and specified in the distribution's F<META.json> (or F<META.yml>)
6607 #pod file.
6608 #pod
6609 #pod For the most part, this class will only be used when operating on the result of
6610 #pod the C<feature> or C<features> methods on a L<CPAN::Meta> object.
6611 #pod
6612 #pod =method new
6613 #pod
6614 #pod my $feature = CPAN::Meta::Feature->new( $identifier => \%spec );
6615 #pod
6616 #pod This returns a new Feature object. The C<%spec> argument to the constructor
6617 #pod should be the same as the value of the C<optional_feature> entry in the
6618 #pod distmeta. It must contain entries for C<description> and C<prereqs>.
6619 #pod
6620 #pod =cut
6621
6622 sub new {
6623 my ($class, $identifier, $spec) = @_;
6624
6625 my %guts = (
6626 identifier => $identifier,
6627 description => $spec->{description},
6628 prereqs => CPAN::Meta::Prereqs->new($spec->{prereqs}),
6629 );
6630
6631 bless \%guts => $class;
6632 }
6633
6634 #pod =method identifier
6635 #pod
6636 #pod This method returns the feature's identifier.
6637 #pod
6638 #pod =cut
6639
6640 sub identifier { $_[0]{identifier} }
6641
6642 #pod =method description
6643 #pod
6644 #pod This method returns the feature's long description.
6645 #pod
6646 #pod =cut
6647
6648 sub description { $_[0]{description} }
6649
6650 #pod =method prereqs
6651 #pod
6652 #pod This method returns the feature's prerequisites as a L<CPAN::Meta::Prereqs>
6653 #pod object.
6654 #pod
6655 #pod =cut
6656
6657 sub prereqs { $_[0]{prereqs} }
6658
6659 1;
6660
6661 # ABSTRACT: an optional feature provided by a CPAN distribution
6662
6663 =pod
6664
6665 =encoding UTF-8
6666
6667 =head1 NAME
6668
6669 CPAN::Meta::Feature - an optional feature provided by a CPAN distribution
6670
6671 =head1 VERSION
6672
6673 version 2.150005
6674
6675 =head1 DESCRIPTION
6676
6677 A CPAN::Meta::Feature object describes an optional feature offered by a CPAN
6678 distribution and specified in the distribution's F<META.json> (or F<META.yml>)
6679 file.
6680
6681 For the most part, this class will only be used when operating on the result of
6682 the C<feature> or C<features> methods on a L<CPAN::Meta> object.
6683
6684 =head1 METHODS
6685
6686 =head2 new
6687
6688 my $feature = CPAN::Meta::Feature->new( $identifier => \%spec );
6689
6690 This returns a new Feature object. The C<%spec> argument to the constructor
6691 should be the same as the value of the C<optional_feature> entry in the
6692 distmeta. It must contain entries for C<description> and C<prereqs>.
6693
6694 =head2 identifier
6695
6696 This method returns the feature's identifier.
6697
6698 =head2 description
6699
6700 This method returns the feature's long description.
6701
6702 =head2 prereqs
6703
6704 This method returns the feature's prerequisites as a L<CPAN::Meta::Prereqs>
6705 object.
6706
6707 =head1 BUGS
6708
6709 Please report any bugs or feature using the CPAN Request Tracker.
6710 Bugs can be submitted through the web interface at
6711 L<http://rt.cpan.org/Dist/Display.html?Queue=CPAN-Meta>
6712
6713 When submitting a bug or request, please include a test-file or a patch to an
6714 existing test-file that illustrates the bug or desired feature.
6715
6716 =head1 AUTHORS
6717
6718 =over 4
6719
6720 =item *
6721
6722 David Golden <dagolden@cpan.org>
6723
6724 =item *
6725
6726 Ricardo Signes <rjbs@cpan.org>
6727
6728 =back
6729
6730 =head1 COPYRIGHT AND LICENSE
6731
6732 This software is copyright (c) 2010 by David Golden and Ricardo Signes.
6733
6734 This is free software; you can redistribute it and/or modify it under
6735 the same terms as the Perl 5 programming language system itself.
6736
6737 =cut
6738
6739 __END__
6740
6741
6742 # vim: ts=2 sts=2 sw=2 et :
6743 CPAN_META_FEATURE
6744  
6745 $fatpacked{"CPAN/Meta/History.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CPAN_META_HISTORY';
6746 # vi:tw=72
6747 use 5.006;
6748 use strict;
6749 use warnings;
6750 package CPAN::Meta::History;
6751
6752 our $VERSION = '2.150005';
6753
6754 1;
6755
6756 # ABSTRACT: history of CPAN Meta Spec changes
6757
6758 __END__
6759
6760 =pod
6761
6762 =encoding UTF-8
6763
6764 =head1 NAME
6765
6766 CPAN::Meta::History - history of CPAN Meta Spec changes
6767
6768 =head1 VERSION
6769
6770 version 2.150005
6771
6772 =head1 DESCRIPTION
6773
6774 The CPAN Meta Spec has gone through several iterations. It was
6775 originally written in HTML and later revised into POD (though published
6776 in HTML generated from the POD). Fields were added, removed or changed,
6777 sometimes by design and sometimes to reflect real-world usage after the
6778 fact.
6779
6780 This document reconstructs the history of the CPAN Meta Spec based on
6781 change logs, repository commit messages and the published HTML files.
6782 In some cases, particularly prior to version 1.2, the exact version
6783 when certain fields were introduced or changed is inconsistent between
6784 sources. When in doubt, the published HTML files for versions 1.0 to
6785 1.4 as they existed when version 2 was developed are used as the
6786 definitive source.
6787
6788 Starting with version 2, the specification document is part of the
6789 CPAN-Meta distribution and will be published on CPAN as
6790 L<CPAN::Meta::Spec>.
6791
6792 Going forward, specification version numbers will be integers and
6793 decimal portions will correspond to a release date for the CPAN::Meta
6794 library.
6795
6796 =head1 HISTORY
6797
6798 =head2 Version 2
6799
6800 April 2010
6801
6802 =over
6803
6804 =item *
6805
6806 Revised spec examples as perl data structures rather than YAML
6807
6808 =item *
6809
6810 Switched to JSON serialization from YAML
6811
6812 =item *
6813
6814 Specified allowed version number formats
6815
6816 =item *
6817
6818 Replaced 'requires', 'build_requires', 'configure_requires',
6819 'recommends' and 'conflicts' with new 'prereqs' data structure divided
6820 by I<phase> (configure, build, test, runtime, etc.) and I<relationship>
6821 (requires, recommends, suggests, conflicts)
6822
6823 =item *
6824
6825 Added support for 'develop' phase for requirements for maintaining
6826 a list of authoring tools
6827
6828 =item *
6829
6830 Changed 'license' to a list and revised the set of valid licenses
6831
6832 =item *
6833
6834 Made 'dynamic_config' mandatory to reduce confusion
6835
6836 =item *
6837
6838 Changed 'resources' subkey 'repository' to a hash that clarifies
6839 repository type, url for browsing and url for checkout
6840
6841 =item *
6842
6843 Changed 'resources' subkey 'bugtracker' to a hash for either web
6844 or mailto resource
6845
6846 =item *
6847
6848 Changed specification of 'optional_features':
6849
6850 =over
6851
6852 =item *
6853
6854 Added formal specification and usage guide instead of just example
6855
6856 =item *
6857
6858 Changed to use new prereqs data structure instead of individual keys
6859
6860 =back
6861
6862 =item *
6863
6864 Clarified intended use of 'author' as generalized contact list
6865
6866 =item *
6867
6868 Added 'release_status' field to indicate stable, testing or unstable
6869 status to provide hints to indexers
6870
6871 =item *
6872
6873 Added 'description' field for a longer description of the distribution
6874
6875 =item *
6876
6877 Formalized use of "x_" or "X_" for all custom keys not listed in the
6878 official spec
6879
6880 =back
6881
6882 =head2 Version 1.4
6883
6884 June 2008
6885
6886 =over
6887
6888 =item *
6889
6890 Noted explicit support for 'perl' in prerequisites
6891
6892 =item *
6893
6894 Added 'configure_requires' prerequisite type
6895
6896 =item *
6897
6898 Changed 'optional_features'
6899
6900 =over
6901
6902 =item *
6903
6904 Example corrected to show map of maps instead of list of maps
6905 (though descriptive text said 'map' even in v1.3)
6906
6907 =item *
6908
6909 Removed 'requires_packages', 'requires_os' and 'excluded_os'
6910 as valid subkeys
6911
6912 =back
6913
6914 =back
6915
6916 =head2 Version 1.3
6917
6918 November 2006
6919
6920 =over
6921
6922 =item *
6923
6924 Added 'no_index' subkey 'directory' and removed 'dir' to match actual
6925 usage in the wild
6926
6927 =item *
6928
6929 Added a 'repository' subkey to 'resources'
6930
6931 =back
6932
6933 =head2 Version 1.2
6934
6935 August 2005
6936
6937 =over
6938
6939 =item *
6940
6941 Re-wrote and restructured spec in POD syntax
6942
6943 =item *
6944
6945 Changed 'name' to be mandatory
6946
6947 =item *
6948
6949 Changed 'generated_by' to be mandatory
6950
6951 =item *
6952
6953 Changed 'license' to be mandatory
6954
6955 =item *
6956
6957 Added version range specifications for prerequisites
6958
6959 =item *
6960
6961 Added required 'abstract' field
6962
6963 =item *
6964
6965 Added required 'author' field
6966
6967 =item *
6968
6969 Added required 'meta-spec' field to define 'version' (and 'url') of the
6970 CPAN Meta Spec used for metadata
6971
6972 =item *
6973
6974 Added 'provides' field
6975
6976 =item *
6977
6978 Added 'no_index' field and deprecated 'private' field. 'no_index'
6979 subkeys include 'file', 'dir', 'package' and 'namespace'
6980
6981 =item *
6982
6983 Added 'keywords' field
6984
6985 =item *
6986
6987 Added 'resources' field with subkeys 'homepage', 'license', and
6988 'bugtracker'
6989
6990 =item *
6991
6992 Added 'optional_features' field as an alternate under 'recommends'.
6993 Includes 'description', 'requires', 'build_requires', 'conflicts',
6994 'requires_packages', 'requires_os' and 'excluded_os' as valid subkeys
6995
6996 =item *
6997
6998 Removed 'license_uri' field
6999
7000 =back
7001
7002 =head2 Version 1.1
7003
7004 May 2003
7005
7006 =over
7007
7008 =item *
7009
7010 Changed 'version' to be mandatory
7011
7012 =item *
7013
7014 Added 'private' field
7015
7016 =item *
7017
7018 Added 'license_uri' field
7019
7020 =back
7021
7022 =head2 Version 1.0
7023
7024 March 2003
7025
7026 =over
7027
7028 =item *
7029
7030 Original release (in HTML format only)
7031
7032 =item *
7033
7034 Included 'name', 'version', 'license', 'distribution_type', 'requires',
7035 'recommends', 'build_requires', 'conflicts', 'dynamic_config',
7036 'generated_by'
7037
7038 =back
7039
7040 =head1 AUTHORS
7041
7042 =over 4
7043
7044 =item *
7045
7046 David Golden <dagolden@cpan.org>
7047
7048 =item *
7049
7050 Ricardo Signes <rjbs@cpan.org>
7051
7052 =back
7053
7054 =head1 COPYRIGHT AND LICENSE
7055
7056 This software is copyright (c) 2010 by David Golden and Ricardo Signes.
7057
7058 This is free software; you can redistribute it and/or modify it under
7059 the same terms as the Perl 5 programming language system itself.
7060
7061 =cut
7062 CPAN_META_HISTORY
7063  
7064 $fatpacked{"CPAN/Meta/Merge.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CPAN_META_MERGE';
7065 use strict;
7066 use warnings;
7067
7068 package CPAN::Meta::Merge;
7069
7070 our $VERSION = '2.150005';
7071
7072 use Carp qw/croak/;
7073 use Scalar::Util qw/blessed/;
7074 use CPAN::Meta::Converter 2.141170;
7075
7076 sub _is_identical {
7077 my ($left, $right) = @_;
7078 return
7079 (not defined $left and not defined $right)
7080 # if either of these are references, we compare the serialized value
7081 || (defined $left and defined $right and $left eq $right);
7082 }
7083
7084 sub _identical {
7085 my ($left, $right, $path) = @_;
7086 croak sprintf "Can't merge attribute %s: '%s' does not equal '%s'", join('.', @{$path}), $left, $right
7087 unless _is_identical($left, $right);
7088 return $left;
7089 }
7090
7091 sub _merge {
7092 my ($current, $next, $mergers, $path) = @_;
7093 for my $key (keys %{$next}) {
7094 if (not exists $current->{$key}) {
7095 $current->{$key} = $next->{$key};
7096 }
7097 elsif (my $merger = $mergers->{$key}) {
7098 $current->{$key} = $merger->($current->{$key}, $next->{$key}, [ @{$path}, $key ]);
7099 }
7100 elsif ($merger = $mergers->{':default'}) {
7101 $current->{$key} = $merger->($current->{$key}, $next->{$key}, [ @{$path}, $key ]);
7102 }
7103 else {
7104 croak sprintf "Can't merge unknown attribute '%s'", join '.', @{$path}, $key;
7105 }
7106 }
7107 return $current;
7108 }
7109
7110 sub _uniq {
7111 my %seen = ();
7112 return grep { not $seen{$_}++ } @_;
7113 }
7114
7115 sub _set_addition {
7116 my ($left, $right) = @_;
7117 return [ +_uniq(@{$left}, @{$right}) ];
7118 }
7119
7120 sub _uniq_map {
7121 my ($left, $right, $path) = @_;
7122 for my $key (keys %{$right}) {
7123 if (not exists $left->{$key}) {
7124 $left->{$key} = $right->{$key};
7125 }
7126 # identical strings or references are merged identically
7127 elsif (_is_identical($left->{$key}, $right->{$key})) {
7128 1; # do nothing - keep left
7129 }
7130 elsif (ref $left->{$key} eq 'HASH' and ref $right->{$key} eq 'HASH') {
7131 $left->{$key} = _uniq_map($left->{$key}, $right->{$key}, [ @{$path}, $key ]);
7132 }
7133 else {
7134 croak 'Duplication of element ' . join '.', @{$path}, $key;
7135 }
7136 }
7137 return $left;
7138 }
7139
7140 sub _improvize {
7141 my ($left, $right, $path) = @_;
7142 my ($name) = reverse @{$path};
7143 if ($name =~ /^x_/) {
7144 if (ref($left) eq 'ARRAY') {
7145 return _set_addition($left, $right, $path);
7146 }
7147 elsif (ref($left) eq 'HASH') {
7148 return _uniq_map($left, $right, $path);
7149 }
7150 else {
7151 return _identical($left, $right, $path);
7152 }
7153 }
7154 croak sprintf "Can't merge '%s'", join '.', @{$path};
7155 }
7156
7157 sub _optional_features {
7158 my ($left, $right, $path) = @_;
7159
7160 for my $key (keys %{$right}) {
7161 if (not exists $left->{$key}) {
7162 $left->{$key} = $right->{$key};
7163 }
7164 else {
7165 for my $subkey (keys %{ $right->{$key} }) {
7166 next if $subkey eq 'prereqs';
7167 if (not exists $left->{$key}{$subkey}) {
7168 $left->{$key}{$subkey} = $right->{$key}{$subkey};
7169 }
7170 else {
7171 Carp::croak "Cannot merge two optional_features named '$key' with different '$subkey' values"
7172 if do { no warnings 'uninitialized'; $left->{$key}{$subkey} ne $right->{$key}{$subkey} };
7173 }
7174 }
7175
7176 require CPAN::Meta::Prereqs;
7177 $left->{$key}{prereqs} =
7178 CPAN::Meta::Prereqs->new($left->{$key}{prereqs})
7179 ->with_merged_prereqs(CPAN::Meta::Prereqs->new($right->{$key}{prereqs}))
7180 ->as_string_hash;
7181 }
7182 }
7183 return $left;
7184 }
7185
7186
7187 my %default = (
7188 abstract => \&_identical,
7189 author => \&_set_addition,
7190 dynamic_config => sub {
7191 my ($left, $right) = @_;
7192 return $left || $right;
7193 },
7194 generated_by => sub {
7195 my ($left, $right) = @_;
7196 return join ', ', _uniq(split(/, /, $left), split(/, /, $right));
7197 },
7198 license => \&_set_addition,
7199 'meta-spec' => {
7200 version => \&_identical,
7201 url => \&_identical
7202 },
7203 name => \&_identical,
7204 release_status => \&_identical,
7205 version => \&_identical,
7206 description => \&_identical,
7207 keywords => \&_set_addition,
7208 no_index => { map { ($_ => \&_set_addition) } qw/file directory package namespace/ },
7209 optional_features => \&_optional_features,
7210 prereqs => sub {
7211 require CPAN::Meta::Prereqs;
7212 my ($left, $right) = map { CPAN::Meta::Prereqs->new($_) } @_[0,1];
7213 return $left->with_merged_prereqs($right)->as_string_hash;
7214 },
7215 provides => \&_uniq_map,
7216 resources => {
7217 license => \&_set_addition,
7218 homepage => \&_identical,
7219 bugtracker => \&_uniq_map,
7220 repository => \&_uniq_map,
7221 ':default' => \&_improvize,
7222 },
7223 ':default' => \&_improvize,
7224 );
7225
7226 sub new {
7227 my ($class, %arguments) = @_;
7228 croak 'default version required' if not exists $arguments{default_version};
7229 my %mapping = %default;
7230 my %extra = %{ $arguments{extra_mappings} || {} };
7231 for my $key (keys %extra) {
7232 if (ref($mapping{$key}) eq 'HASH') {
7233 $mapping{$key} = { %{ $mapping{$key} }, %{ $extra{$key} } };
7234 }
7235 else {
7236 $mapping{$key} = $extra{$key};
7237 }
7238 }
7239 return bless {
7240 default_version => $arguments{default_version},
7241 mapping => _coerce_mapping(\%mapping, []),
7242 }, $class;
7243 }
7244
7245 my %coderef_for = (
7246 set_addition => \&_set_addition,
7247 uniq_map => \&_uniq_map,
7248 identical => \&_identical,
7249 improvize => \&_improvize,
7250 );
7251
7252 sub _coerce_mapping {
7253 my ($orig, $map_path) = @_;
7254 my %ret;
7255 for my $key (keys %{$orig}) {
7256 my $value = $orig->{$key};
7257 if (ref($orig->{$key}) eq 'CODE') {
7258 $ret{$key} = $value;
7259 }
7260 elsif (ref($value) eq 'HASH') {
7261 my $mapping = _coerce_mapping($value, [ @{$map_path}, $key ]);
7262 $ret{$key} = sub {
7263 my ($left, $right, $path) = @_;
7264 return _merge($left, $right, $mapping, [ @{$path} ]);
7265 };
7266 }
7267 elsif ($coderef_for{$value}) {
7268 $ret{$key} = $coderef_for{$value};
7269 }
7270 else {
7271 croak "Don't know what to do with " . join '.', @{$map_path}, $key;
7272 }
7273 }
7274 return \%ret;
7275 }
7276
7277 sub merge {
7278 my ($self, @items) = @_;
7279 my $current = {};
7280 for my $next (@items) {
7281 if ( blessed($next) && $next->isa('CPAN::Meta') ) {
7282 $next = $next->as_struct;
7283 }
7284 elsif ( ref($next) eq 'HASH' ) {
7285 my $cmc = CPAN::Meta::Converter->new(
7286 $next, default_version => $self->{default_version}
7287 );
7288 $next = $cmc->upgrade_fragment;
7289 }
7290 else {
7291 croak "Don't know how to merge '$next'";
7292 }
7293 $current = _merge($current, $next, $self->{mapping}, []);
7294 }
7295 return $current;
7296 }
7297
7298 1;
7299
7300 # ABSTRACT: Merging CPAN Meta fragments
7301
7302
7303 # vim: ts=2 sts=2 sw=2 et :
7304
7305 __END__
7306
7307 =pod
7308
7309 =encoding UTF-8
7310
7311 =head1 NAME
7312
7313 CPAN::Meta::Merge - Merging CPAN Meta fragments
7314
7315 =head1 VERSION
7316
7317 version 2.150005
7318
7319 =head1 SYNOPSIS
7320
7321 my $merger = CPAN::Meta::Merge->new(default_version => "2");
7322 my $meta = $merger->merge($base, @additional);
7323
7324 =head1 DESCRIPTION
7325
7326 =head1 METHODS
7327
7328 =head2 new
7329
7330 This creates a CPAN::Meta::Merge object. It takes one mandatory named
7331 argument, C<version>, declaring the version of the meta-spec that must be
7332 used for the merge. It can optionally take an C<extra_mappings> argument
7333 that allows one to add additional merging functions for specific elements.
7334
7335 =head2 merge(@fragments)
7336
7337 Merge all C<@fragments> together. It will accept both CPAN::Meta objects and
7338 (possibly incomplete) hashrefs of metadata.
7339
7340 =head1 AUTHORS
7341
7342 =over 4
7343
7344 =item *
7345
7346 David Golden <dagolden@cpan.org>
7347
7348 =item *
7349
7350 Ricardo Signes <rjbs@cpan.org>
7351
7352 =back
7353
7354 =head1 COPYRIGHT AND LICENSE
7355
7356 This software is copyright (c) 2010 by David Golden and Ricardo Signes.
7357
7358 This is free software; you can redistribute it and/or modify it under
7359 the same terms as the Perl 5 programming language system itself.
7360
7361 =cut
7362 CPAN_META_MERGE
7363  
7364 $fatpacked{"CPAN/Meta/Prereqs.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CPAN_META_PREREQS';
7365 use 5.006;
7366 use strict;
7367 use warnings;
7368 package CPAN::Meta::Prereqs;
7369
7370 our $VERSION = '2.150005';
7371
7372 #pod =head1 DESCRIPTION
7373 #pod
7374 #pod A CPAN::Meta::Prereqs object represents the prerequisites for a CPAN
7375 #pod distribution or one of its optional features. Each set of prereqs is
7376 #pod organized by phase and type, as described in L<CPAN::Meta::Prereqs>.
7377 #pod
7378 #pod =cut
7379
7380 use Carp qw(confess);
7381 use Scalar::Util qw(blessed);
7382 use CPAN::Meta::Requirements 2.121;
7383
7384 #pod =method new
7385 #pod
7386 #pod my $prereq = CPAN::Meta::Prereqs->new( \%prereq_spec );
7387 #pod
7388 #pod This method returns a new set of Prereqs. The input should look like the
7389 #pod contents of the C<prereqs> field described in L<CPAN::Meta::Spec>, meaning
7390 #pod something more or less like this:
7391 #pod
7392 #pod my $prereq = CPAN::Meta::Prereqs->new({
7393 #pod runtime => {
7394 #pod requires => {
7395 #pod 'Some::Module' => '1.234',
7396 #pod ...,
7397 #pod },
7398 #pod ...,
7399 #pod },
7400 #pod ...,
7401 #pod });
7402 #pod
7403 #pod You can also construct an empty set of prereqs with:
7404 #pod
7405 #pod my $prereqs = CPAN::Meta::Prereqs->new;
7406 #pod
7407 #pod This empty set of prereqs is useful for accumulating new prereqs before finally
7408 #pod dumping the whole set into a structure or string.
7409 #pod
7410 #pod =cut
7411
7412 sub __legal_phases { qw(configure build test runtime develop) }
7413 sub __legal_types { qw(requires recommends suggests conflicts) }
7414
7415 # expect a prereq spec from META.json -- rjbs, 2010-04-11
7416 sub new {
7417 my ($class, $prereq_spec) = @_;
7418 $prereq_spec ||= {};
7419
7420 my %is_legal_phase = map {; $_ => 1 } $class->__legal_phases;
7421 my %is_legal_type = map {; $_ => 1 } $class->__legal_types;
7422
7423 my %guts;
7424 PHASE: for my $phase (keys %$prereq_spec) {
7425 next PHASE unless $phase =~ /\Ax_/i or $is_legal_phase{$phase};
7426
7427 my $phase_spec = $prereq_spec->{ $phase };
7428 next PHASE unless keys %$phase_spec;
7429
7430 TYPE: for my $type (keys %$phase_spec) {
7431 next TYPE unless $type =~ /\Ax_/i or $is_legal_type{$type};
7432
7433 my $spec = $phase_spec->{ $type };
7434
7435 next TYPE unless keys %$spec;
7436
7437 $guts{prereqs}{$phase}{$type} = CPAN::Meta::Requirements->from_string_hash(
7438 $spec
7439 );
7440 }
7441 }
7442
7443 return bless \%guts => $class;
7444 }
7445
7446 #pod =method requirements_for
7447 #pod
7448 #pod my $requirements = $prereqs->requirements_for( $phase, $type );
7449 #pod
7450 #pod This method returns a L<CPAN::Meta::Requirements> object for the given
7451 #pod phase/type combination. If no prerequisites are registered for that
7452 #pod combination, a new CPAN::Meta::Requirements object will be returned, and it may
7453 #pod be added to as needed.
7454 #pod
7455 #pod If C<$phase> or C<$type> are undefined or otherwise invalid, an exception will
7456 #pod be raised.
7457 #pod
7458 #pod =cut
7459
7460 sub requirements_for {
7461 my ($self, $phase, $type) = @_;
7462
7463 confess "requirements_for called without phase" unless defined $phase;
7464 confess "requirements_for called without type" unless defined $type;
7465
7466 unless ($phase =~ /\Ax_/i or grep { $phase eq $_ } $self->__legal_phases) {
7467 confess "requested requirements for unknown phase: $phase";
7468 }
7469
7470 unless ($type =~ /\Ax_/i or grep { $type eq $_ } $self->__legal_types) {
7471 confess "requested requirements for unknown type: $type";
7472 }
7473
7474 my $req = ($self->{prereqs}{$phase}{$type} ||= CPAN::Meta::Requirements->new);
7475
7476 $req->finalize if $self->is_finalized;
7477
7478 return $req;
7479 }
7480
7481 #pod =method with_merged_prereqs
7482 #pod
7483 #pod my $new_prereqs = $prereqs->with_merged_prereqs( $other_prereqs );
7484 #pod
7485 #pod my $new_prereqs = $prereqs->with_merged_prereqs( \@other_prereqs );
7486 #pod
7487 #pod This method returns a new CPAN::Meta::Prereqs objects in which all the
7488 #pod other prerequisites given are merged into the current set. This is primarily
7489 #pod provided for combining a distribution's core prereqs with the prereqs of one of
7490 #pod its optional features.
7491 #pod
7492 #pod The new prereqs object has no ties to the originals, and altering it further
7493 #pod will not alter them.
7494 #pod
7495 #pod =cut
7496
7497 sub with_merged_prereqs {
7498 my ($self, $other) = @_;
7499
7500 my @other = blessed($other) ? $other : @$other;
7501
7502 my @prereq_objs = ($self, @other);
7503
7504 my %new_arg;
7505
7506 for my $phase ($self->__legal_phases) {
7507 for my $type ($self->__legal_types) {
7508 my $req = CPAN::Meta::Requirements->new;
7509
7510 for my $prereq (@prereq_objs) {
7511 my $this_req = $prereq->requirements_for($phase, $type);
7512 next unless $this_req->required_modules;
7513
7514 $req->add_requirements($this_req);
7515 }
7516
7517 next unless $req->required_modules;
7518
7519 $new_arg{ $phase }{ $type } = $req->as_string_hash;
7520 }
7521 }
7522
7523 return (ref $self)->new(\%new_arg);
7524 }
7525
7526 #pod =method merged_requirements
7527 #pod
7528 #pod my $new_reqs = $prereqs->merged_requirements( \@phases, \@types );
7529 #pod my $new_reqs = $prereqs->merged_requirements( \@phases );
7530 #pod my $new_reqs = $prereqs->merged_requirements();
7531 #pod
7532 #pod This method joins together all requirements across a number of phases
7533 #pod and types into a new L<CPAN::Meta::Requirements> object. If arguments
7534 #pod are omitted, it defaults to "runtime", "build" and "test" for phases
7535 #pod and "requires" and "recommends" for types.
7536 #pod
7537 #pod =cut
7538
7539 sub merged_requirements {
7540 my ($self, $phases, $types) = @_;
7541 $phases = [qw/runtime build test/] unless defined $phases;
7542 $types = [qw/requires recommends/] unless defined $types;
7543
7544 confess "merged_requirements phases argument must be an arrayref"
7545 unless ref $phases eq 'ARRAY';
7546 confess "merged_requirements types argument must be an arrayref"
7547 unless ref $types eq 'ARRAY';
7548
7549 my $req = CPAN::Meta::Requirements->new;
7550
7551 for my $phase ( @$phases ) {
7552 unless ($phase =~ /\Ax_/i or grep { $phase eq $_ } $self->__legal_phases) {
7553 confess "requested requirements for unknown phase: $phase";
7554 }
7555 for my $type ( @$types ) {
7556 unless ($type =~ /\Ax_/i or grep { $type eq $_ } $self->__legal_types) {
7557 confess "requested requirements for unknown type: $type";
7558 }
7559 $req->add_requirements( $self->requirements_for($phase, $type) );
7560 }
7561 }
7562
7563 $req->finalize if $self->is_finalized;
7564
7565 return $req;
7566 }
7567
7568
7569 #pod =method as_string_hash
7570 #pod
7571 #pod This method returns a hashref containing structures suitable for dumping into a
7572 #pod distmeta data structure. It is made up of hashes and strings, only; there will
7573 #pod be no Prereqs, CPAN::Meta::Requirements, or C<version> objects inside it.
7574 #pod
7575 #pod =cut
7576
7577 sub as_string_hash {
7578 my ($self) = @_;
7579
7580 my %hash;
7581
7582 for my $phase ($self->__legal_phases) {
7583 for my $type ($self->__legal_types) {
7584 my $req = $self->requirements_for($phase, $type);
7585 next unless $req->required_modules;
7586
7587 $hash{ $phase }{ $type } = $req->as_string_hash;
7588 }
7589 }
7590
7591 return \%hash;
7592 }
7593
7594 #pod =method is_finalized
7595 #pod
7596 #pod This method returns true if the set of prereqs has been marked "finalized," and
7597 #pod cannot be altered.
7598 #pod
7599 #pod =cut
7600
7601 sub is_finalized { $_[0]{finalized} }
7602
7603 #pod =method finalize
7604 #pod
7605 #pod Calling C<finalize> on a Prereqs object will close it for further modification.
7606 #pod Attempting to make any changes that would actually alter the prereqs will
7607 #pod result in an exception being thrown.
7608 #pod
7609 #pod =cut
7610
7611 sub finalize {
7612 my ($self) = @_;
7613
7614 $self->{finalized} = 1;
7615
7616 for my $phase (keys %{ $self->{prereqs} }) {
7617 $_->finalize for values %{ $self->{prereqs}{$phase} };
7618 }
7619 }
7620
7621 #pod =method clone
7622 #pod
7623 #pod my $cloned_prereqs = $prereqs->clone;
7624 #pod
7625 #pod This method returns a Prereqs object that is identical to the original object,
7626 #pod but can be altered without affecting the original object. Finalization does
7627 #pod not survive cloning, meaning that you may clone a finalized set of prereqs and
7628 #pod then modify the clone.
7629 #pod
7630 #pod =cut
7631
7632 sub clone {
7633 my ($self) = @_;
7634
7635 my $clone = (ref $self)->new( $self->as_string_hash );
7636 }
7637
7638 1;
7639
7640 # ABSTRACT: a set of distribution prerequisites by phase and type
7641
7642 =pod
7643
7644 =encoding UTF-8
7645
7646 =head1 NAME
7647
7648 CPAN::Meta::Prereqs - a set of distribution prerequisites by phase and type
7649
7650 =head1 VERSION
7651
7652 version 2.150005
7653
7654 =head1 DESCRIPTION
7655
7656 A CPAN::Meta::Prereqs object represents the prerequisites for a CPAN
7657 distribution or one of its optional features. Each set of prereqs is
7658 organized by phase and type, as described in L<CPAN::Meta::Prereqs>.
7659
7660 =head1 METHODS
7661
7662 =head2 new
7663
7664 my $prereq = CPAN::Meta::Prereqs->new( \%prereq_spec );
7665
7666 This method returns a new set of Prereqs. The input should look like the
7667 contents of the C<prereqs> field described in L<CPAN::Meta::Spec>, meaning
7668 something more or less like this:
7669
7670 my $prereq = CPAN::Meta::Prereqs->new({
7671 runtime => {
7672 requires => {
7673 'Some::Module' => '1.234',
7674 ...,
7675 },
7676 ...,
7677 },
7678 ...,
7679 });
7680
7681 You can also construct an empty set of prereqs with:
7682
7683 my $prereqs = CPAN::Meta::Prereqs->new;
7684
7685 This empty set of prereqs is useful for accumulating new prereqs before finally
7686 dumping the whole set into a structure or string.
7687
7688 =head2 requirements_for
7689
7690 my $requirements = $prereqs->requirements_for( $phase, $type );
7691
7692 This method returns a L<CPAN::Meta::Requirements> object for the given
7693 phase/type combination. If no prerequisites are registered for that
7694 combination, a new CPAN::Meta::Requirements object will be returned, and it may
7695 be added to as needed.
7696
7697 If C<$phase> or C<$type> are undefined or otherwise invalid, an exception will
7698 be raised.
7699
7700 =head2 with_merged_prereqs
7701
7702 my $new_prereqs = $prereqs->with_merged_prereqs( $other_prereqs );
7703
7704 my $new_prereqs = $prereqs->with_merged_prereqs( \@other_prereqs );
7705
7706 This method returns a new CPAN::Meta::Prereqs objects in which all the
7707 other prerequisites given are merged into the current set. This is primarily
7708 provided for combining a distribution's core prereqs with the prereqs of one of
7709 its optional features.
7710
7711 The new prereqs object has no ties to the originals, and altering it further
7712 will not alter them.
7713
7714 =head2 merged_requirements
7715
7716 my $new_reqs = $prereqs->merged_requirements( \@phases, \@types );
7717 my $new_reqs = $prereqs->merged_requirements( \@phases );
7718 my $new_reqs = $prereqs->merged_requirements();
7719
7720 This method joins together all requirements across a number of phases
7721 and types into a new L<CPAN::Meta::Requirements> object. If arguments
7722 are omitted, it defaults to "runtime", "build" and "test" for phases
7723 and "requires" and "recommends" for types.
7724
7725 =head2 as_string_hash
7726
7727 This method returns a hashref containing structures suitable for dumping into a
7728 distmeta data structure. It is made up of hashes and strings, only; there will
7729 be no Prereqs, CPAN::Meta::Requirements, or C<version> objects inside it.
7730
7731 =head2 is_finalized
7732
7733 This method returns true if the set of prereqs has been marked "finalized," and
7734 cannot be altered.
7735
7736 =head2 finalize
7737
7738 Calling C<finalize> on a Prereqs object will close it for further modification.
7739 Attempting to make any changes that would actually alter the prereqs will
7740 result in an exception being thrown.
7741
7742 =head2 clone
7743
7744 my $cloned_prereqs = $prereqs->clone;
7745
7746 This method returns a Prereqs object that is identical to the original object,
7747 but can be altered without affecting the original object. Finalization does
7748 not survive cloning, meaning that you may clone a finalized set of prereqs and
7749 then modify the clone.
7750
7751 =head1 BUGS
7752
7753 Please report any bugs or feature using the CPAN Request Tracker.
7754 Bugs can be submitted through the web interface at
7755 L<http://rt.cpan.org/Dist/Display.html?Queue=CPAN-Meta>
7756
7757 When submitting a bug or request, please include a test-file or a patch to an
7758 existing test-file that illustrates the bug or desired feature.
7759
7760 =head1 AUTHORS
7761
7762 =over 4
7763
7764 =item *
7765
7766 David Golden <dagolden@cpan.org>
7767
7768 =item *
7769
7770 Ricardo Signes <rjbs@cpan.org>
7771
7772 =back
7773
7774 =head1 COPYRIGHT AND LICENSE
7775
7776 This software is copyright (c) 2010 by David Golden and Ricardo Signes.
7777
7778 This is free software; you can redistribute it and/or modify it under
7779 the same terms as the Perl 5 programming language system itself.
7780
7781 =cut
7782
7783 __END__
7784
7785
7786 # vim: ts=2 sts=2 sw=2 et :
7787 CPAN_META_PREREQS
7788  
7789 $fatpacked{"CPAN/Meta/Requirements.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CPAN_META_REQUIREMENTS';
7790 use strict;
7791 use warnings;
7792 package CPAN::Meta::Requirements;
7793 # ABSTRACT: a set of version requirements for a CPAN dist
7794
7795 our $VERSION = '2.133';
7796
7797 #pod =head1 SYNOPSIS
7798 #pod
7799 #pod use CPAN::Meta::Requirements;
7800 #pod
7801 #pod my $build_requires = CPAN::Meta::Requirements->new;
7802 #pod
7803 #pod $build_requires->add_minimum('Library::Foo' => 1.208);
7804 #pod
7805 #pod $build_requires->add_minimum('Library::Foo' => 2.602);
7806 #pod
7807 #pod $build_requires->add_minimum('Module::Bar' => 'v1.2.3');
7808 #pod
7809 #pod $METAyml->{build_requires} = $build_requires->as_string_hash;
7810 #pod
7811 #pod =head1 DESCRIPTION
7812 #pod
7813 #pod A CPAN::Meta::Requirements object models a set of version constraints like
7814 #pod those specified in the F<META.yml> or F<META.json> files in CPAN distributions,
7815 #pod and as defined by L<CPAN::Meta::Spec>;
7816 #pod It can be built up by adding more and more constraints, and it will reduce them
7817 #pod to the simplest representation.
7818 #pod
7819 #pod Logically impossible constraints will be identified immediately by thrown
7820 #pod exceptions.
7821 #pod
7822 #pod =cut
7823
7824 use Carp ();
7825
7826 # To help ExtUtils::MakeMaker bootstrap CPAN::Meta::Requirements on perls
7827 # before 5.10, we fall back to the EUMM bundled compatibility version module if
7828 # that's the only thing available. This shouldn't ever happen in a normal CPAN
7829 # install of CPAN::Meta::Requirements, as version.pm will be picked up from
7830 # prereqs and be available at runtime.
7831
7832 BEGIN {
7833 eval "use version ()"; ## no critic
7834 if ( my $err = $@ ) {
7835 eval "use ExtUtils::MakeMaker::version" or die $err; ## no critic
7836 }
7837 }
7838
7839 # Perl 5.10.0 didn't have "is_qv" in version.pm
7840 *_is_qv = version->can('is_qv') ? sub { $_[0]->is_qv } : sub { exists $_[0]->{qv} };
7841
7842 # construct once, reuse many times
7843 my $V0 = version->new(0);
7844
7845 #pod =method new
7846 #pod
7847 #pod my $req = CPAN::Meta::Requirements->new;
7848 #pod
7849 #pod This returns a new CPAN::Meta::Requirements object. It takes an optional
7850 #pod hash reference argument. Currently, only one key is supported:
7851 #pod
7852 #pod =for :list
7853 #pod * C<bad_version_hook> -- if provided, when a version cannot be parsed into
7854 #pod a version object, this code reference will be called with the invalid
7855 #pod version string as first argument, and the module name as second
7856 #pod argument. It must return a valid version object.
7857 #pod
7858 #pod All other keys are ignored.
7859 #pod
7860 #pod =cut
7861
7862 my @valid_options = qw( bad_version_hook );
7863
7864 sub new {
7865 my ($class, $options) = @_;
7866 $options ||= {};
7867 Carp::croak "Argument to $class\->new() must be a hash reference"
7868 unless ref $options eq 'HASH';
7869 my %self = map {; $_ => $options->{$_}} @valid_options;
7870
7871 return bless \%self => $class;
7872 }
7873
7874 # from version::vpp
7875 sub _find_magic_vstring {
7876 my $value = shift;
7877 my $tvalue = '';
7878 require B;
7879 my $sv = B::svref_2object(\$value);
7880 my $magic = ref($sv) eq 'B::PVMG' ? $sv->MAGIC : undef;
7881 while ( $magic ) {
7882 if ( $magic->TYPE eq 'V' ) {
7883 $tvalue = $magic->PTR;
7884 $tvalue =~ s/^v?(.+)$/v$1/;
7885 last;
7886 }
7887 else {
7888 $magic = $magic->MOREMAGIC;
7889 }
7890 }
7891 return $tvalue;
7892 }
7893
7894 # safe if given an unblessed reference
7895 sub _isa_version {
7896 UNIVERSAL::isa( $_[0], 'UNIVERSAL' ) && $_[0]->isa('version')
7897 }
7898
7899 sub _version_object {
7900 my ($self, $module, $version) = @_;
7901
7902 my ($vobj, $err);
7903
7904 if (not defined $version or (!ref($version) && $version eq '0')) {
7905 return $V0;
7906 }
7907 elsif ( ref($version) eq 'version' || _isa_version($version) ) {
7908 $vobj = $version;
7909 }
7910 else {
7911 # hack around version::vpp not handling <3 character vstring literals
7912 if ( $INC{'version/vpp.pm'} || $INC{'ExtUtils/MakeMaker/version/vpp.pm'} ) {
7913 my $magic = _find_magic_vstring( $version );
7914 $version = $magic if length $magic;
7915 }
7916 eval {
7917 local $SIG{__WARN__} = sub { die "Invalid version: $_[0]" };
7918 $vobj = version->new($version);
7919 };
7920 if ( my $err = $@ ) {
7921 my $hook = $self->{bad_version_hook};
7922 $vobj = eval { $hook->($version, $module) }
7923 if ref $hook eq 'CODE';
7924 unless (eval { $vobj->isa("version") }) {
7925 $err =~ s{ at .* line \d+.*$}{};
7926 die "Can't convert '$version': $err";
7927 }
7928 }
7929 }
7930
7931 # ensure no leading '.'
7932 if ( $vobj =~ m{\A\.} ) {
7933 $vobj = version->new("0$vobj");
7934 }
7935
7936 # ensure normal v-string form
7937 if ( _is_qv($vobj) ) {
7938 $vobj = version->new($vobj->normal);
7939 }
7940
7941 return $vobj;
7942 }
7943
7944 #pod =method add_minimum
7945 #pod
7946 #pod $req->add_minimum( $module => $version );
7947 #pod
7948 #pod This adds a new minimum version requirement. If the new requirement is
7949 #pod redundant to the existing specification, this has no effect.
7950 #pod
7951 #pod Minimum requirements are inclusive. C<$version> is required, along with any
7952 #pod greater version number.
7953 #pod
7954 #pod This method returns the requirements object.
7955 #pod
7956 #pod =method add_maximum
7957 #pod
7958 #pod $req->add_maximum( $module => $version );
7959 #pod
7960 #pod This adds a new maximum version requirement. If the new requirement is
7961 #pod redundant to the existing specification, this has no effect.
7962 #pod
7963 #pod Maximum requirements are inclusive. No version strictly greater than the given
7964 #pod version is allowed.
7965 #pod
7966 #pod This method returns the requirements object.
7967 #pod
7968 #pod =method add_exclusion
7969 #pod
7970 #pod $req->add_exclusion( $module => $version );
7971 #pod
7972 #pod This adds a new excluded version. For example, you might use these three
7973 #pod method calls:
7974 #pod
7975 #pod $req->add_minimum( $module => '1.00' );
7976 #pod $req->add_maximum( $module => '1.82' );
7977 #pod
7978 #pod $req->add_exclusion( $module => '1.75' );
7979 #pod
7980 #pod Any version between 1.00 and 1.82 inclusive would be acceptable, except for
7981 #pod 1.75.
7982 #pod
7983 #pod This method returns the requirements object.
7984 #pod
7985 #pod =method exact_version
7986 #pod
7987 #pod $req->exact_version( $module => $version );
7988 #pod
7989 #pod This sets the version required for the given module to I<exactly> the given
7990 #pod version. No other version would be considered acceptable.
7991 #pod
7992 #pod This method returns the requirements object.
7993 #pod
7994 #pod =cut
7995
7996 BEGIN {
7997 for my $type (qw(maximum exclusion exact_version)) {
7998 my $method = "with_$type";
7999 my $to_add = $type eq 'exact_version' ? $type : "add_$type";
8000
8001 my $code = sub {
8002 my ($self, $name, $version) = @_;
8003
8004 $version = $self->_version_object( $name, $version );
8005
8006 $self->__modify_entry_for($name, $method, $version);
8007
8008 return $self;
8009 };
8010
8011 no strict 'refs';
8012 *$to_add = $code;
8013 }
8014 }
8015
8016 # add_minimum is optimized compared to generated subs above because
8017 # it is called frequently and with "0" or equivalent input
8018 sub add_minimum {
8019 my ($self, $name, $version) = @_;
8020
8021 # stringify $version so that version->new("0.00")->stringify ne "0"
8022 # which preserves the user's choice of "0.00" as the requirement
8023 if (not defined $version or "$version" eq '0') {
8024 return $self if $self->__entry_for($name);
8025 Carp::confess("can't add new requirements to finalized requirements")
8026 if $self->is_finalized;
8027
8028 $self->{requirements}{ $name } =
8029 CPAN::Meta::Requirements::_Range::Range->with_minimum($V0);
8030 }
8031 else {
8032 $version = $self->_version_object( $name, $version );
8033
8034 $self->__modify_entry_for($name, 'with_minimum', $version);
8035 }
8036 return $self;
8037 }
8038
8039 #pod =method add_requirements
8040 #pod
8041 #pod $req->add_requirements( $another_req_object );
8042 #pod
8043 #pod This method adds all the requirements in the given CPAN::Meta::Requirements object
8044 #pod to the requirements object on which it was called. If there are any conflicts,
8045 #pod an exception is thrown.
8046 #pod
8047 #pod This method returns the requirements object.
8048 #pod
8049 #pod =cut
8050
8051 sub add_requirements {
8052 my ($self, $req) = @_;
8053
8054 for my $module ($req->required_modules) {
8055 my $modifiers = $req->__entry_for($module)->as_modifiers;
8056 for my $modifier (@$modifiers) {
8057 my ($method, @args) = @$modifier;
8058 $self->$method($module => @args);
8059 };
8060 }
8061
8062 return $self;
8063 }
8064
8065 #pod =method accepts_module
8066 #pod
8067 #pod my $bool = $req->accepts_module($module => $version);
8068 #pod
8069 #pod Given an module and version, this method returns true if the version
8070 #pod specification for the module accepts the provided version. In other words,
8071 #pod given:
8072 #pod
8073 #pod Module => '>= 1.00, < 2.00'
8074 #pod
8075 #pod We will accept 1.00 and 1.75 but not 0.50 or 2.00.
8076 #pod
8077 #pod For modules that do not appear in the requirements, this method will return
8078 #pod true.
8079 #pod
8080 #pod =cut
8081
8082 sub accepts_module {
8083 my ($self, $module, $version) = @_;
8084
8085 $version = $self->_version_object( $module, $version );
8086
8087 return 1 unless my $range = $self->__entry_for($module);
8088 return $range->_accepts($version);
8089 }
8090
8091 #pod =method clear_requirement
8092 #pod
8093 #pod $req->clear_requirement( $module );
8094 #pod
8095 #pod This removes the requirement for a given module from the object.
8096 #pod
8097 #pod This method returns the requirements object.
8098 #pod
8099 #pod =cut
8100
8101 sub clear_requirement {
8102 my ($self, $module) = @_;
8103
8104 return $self unless $self->__entry_for($module);
8105
8106 Carp::confess("can't clear requirements on finalized requirements")
8107 if $self->is_finalized;
8108
8109 delete $self->{requirements}{ $module };
8110
8111 return $self;
8112 }
8113
8114 #pod =method requirements_for_module
8115 #pod
8116 #pod $req->requirements_for_module( $module );
8117 #pod
8118 #pod This returns a string containing the version requirements for a given module in
8119 #pod the format described in L<CPAN::Meta::Spec> or undef if the given module has no
8120 #pod requirements. This should only be used for informational purposes such as error
8121 #pod messages and should not be interpreted or used for comparison (see
8122 #pod L</accepts_module> instead.)
8123 #pod
8124 #pod =cut
8125
8126 sub requirements_for_module {
8127 my ($self, $module) = @_;
8128 my $entry = $self->__entry_for($module);
8129 return unless $entry;
8130 return $entry->as_string;
8131 }
8132
8133 #pod =method required_modules
8134 #pod
8135 #pod This method returns a list of all the modules for which requirements have been
8136 #pod specified.
8137 #pod
8138 #pod =cut
8139
8140 sub required_modules { keys %{ $_[0]{requirements} } }
8141
8142 #pod =method clone
8143 #pod
8144 #pod $req->clone;
8145 #pod
8146 #pod This method returns a clone of the invocant. The clone and the original object
8147 #pod can then be changed independent of one another.
8148 #pod
8149 #pod =cut
8150
8151 sub clone {
8152 my ($self) = @_;
8153 my $new = (ref $self)->new;
8154
8155 return $new->add_requirements($self);
8156 }
8157
8158 sub __entry_for { $_[0]{requirements}{ $_[1] } }
8159
8160 sub __modify_entry_for {
8161 my ($self, $name, $method, $version) = @_;
8162
8163 my $fin = $self->is_finalized;
8164 my $old = $self->__entry_for($name);
8165
8166 Carp::confess("can't add new requirements to finalized requirements")
8167 if $fin and not $old;
8168
8169 my $new = ($old || 'CPAN::Meta::Requirements::_Range::Range')
8170 ->$method($version);
8171
8172 Carp::confess("can't modify finalized requirements")
8173 if $fin and $old->as_string ne $new->as_string;
8174
8175 $self->{requirements}{ $name } = $new;
8176 }
8177
8178 #pod =method is_simple
8179 #pod
8180 #pod This method returns true if and only if all requirements are inclusive minimums
8181 #pod -- that is, if their string expression is just the version number.
8182 #pod
8183 #pod =cut
8184
8185 sub is_simple {
8186 my ($self) = @_;
8187 for my $module ($self->required_modules) {
8188 # XXX: This is a complete hack, but also entirely correct.
8189 return if $self->__entry_for($module)->as_string =~ /\s/;
8190 }
8191
8192 return 1;
8193 }
8194
8195 #pod =method is_finalized
8196 #pod
8197 #pod This method returns true if the requirements have been finalized by having the
8198 #pod C<finalize> method called on them.
8199 #pod
8200 #pod =cut
8201
8202 sub is_finalized { $_[0]{finalized} }
8203
8204 #pod =method finalize
8205 #pod
8206 #pod This method marks the requirements finalized. Subsequent attempts to change
8207 #pod the requirements will be fatal, I<if> they would result in a change. If they
8208 #pod would not alter the requirements, they have no effect.
8209 #pod
8210 #pod If a finalized set of requirements is cloned, the cloned requirements are not
8211 #pod also finalized.
8212 #pod
8213 #pod =cut
8214
8215 sub finalize { $_[0]{finalized} = 1 }
8216
8217 #pod =method as_string_hash
8218 #pod
8219 #pod This returns a reference to a hash describing the requirements using the
8220 #pod strings in the L<CPAN::Meta::Spec> specification.
8221 #pod
8222 #pod For example after the following program:
8223 #pod
8224 #pod my $req = CPAN::Meta::Requirements->new;
8225 #pod
8226 #pod $req->add_minimum('CPAN::Meta::Requirements' => 0.102);
8227 #pod
8228 #pod $req->add_minimum('Library::Foo' => 1.208);
8229 #pod
8230 #pod $req->add_maximum('Library::Foo' => 2.602);
8231 #pod
8232 #pod $req->add_minimum('Module::Bar' => 'v1.2.3');
8233 #pod
8234 #pod $req->add_exclusion('Module::Bar' => 'v1.2.8');
8235 #pod
8236 #pod $req->exact_version('Xyzzy' => '6.01');
8237 #pod
8238 #pod my $hashref = $req->as_string_hash;
8239 #pod
8240 #pod C<$hashref> would contain:
8241 #pod
8242 #pod {
8243 #pod 'CPAN::Meta::Requirements' => '0.102',
8244 #pod 'Library::Foo' => '>= 1.208, <= 2.206',
8245 #pod 'Module::Bar' => '>= v1.2.3, != v1.2.8',
8246 #pod 'Xyzzy' => '== 6.01',
8247 #pod }
8248 #pod
8249 #pod =cut
8250
8251 sub as_string_hash {
8252 my ($self) = @_;
8253
8254 my %hash = map {; $_ => $self->{requirements}{$_}->as_string }
8255 $self->required_modules;
8256
8257 return \%hash;
8258 }
8259
8260 #pod =method add_string_requirement
8261 #pod
8262 #pod $req->add_string_requirement('Library::Foo' => '>= 1.208, <= 2.206');
8263 #pod $req->add_string_requirement('Library::Foo' => v1.208);
8264 #pod
8265 #pod This method parses the passed in string and adds the appropriate requirement
8266 #pod for the given module. A version can be a Perl "v-string". It understands
8267 #pod version ranges as described in the L<CPAN::Meta::Spec/Version Ranges>. For
8268 #pod example:
8269 #pod
8270 #pod =over 4
8271 #pod
8272 #pod =item 1.3
8273 #pod
8274 #pod =item >= 1.3
8275 #pod
8276 #pod =item <= 1.3
8277 #pod
8278 #pod =item == 1.3
8279 #pod
8280 #pod =item != 1.3
8281 #pod
8282 #pod =item > 1.3
8283 #pod
8284 #pod =item < 1.3
8285 #pod
8286 #pod =item >= 1.3, != 1.5, <= 2.0
8287 #pod
8288 #pod A version number without an operator is equivalent to specifying a minimum
8289 #pod (C<E<gt>=>). Extra whitespace is allowed.
8290 #pod
8291 #pod =back
8292 #pod
8293 #pod =cut
8294
8295 my %methods_for_op = (
8296 '==' => [ qw(exact_version) ],
8297 '!=' => [ qw(add_exclusion) ],
8298 '>=' => [ qw(add_minimum) ],
8299 '<=' => [ qw(add_maximum) ],
8300 '>' => [ qw(add_minimum add_exclusion) ],
8301 '<' => [ qw(add_maximum add_exclusion) ],
8302 );
8303
8304 sub add_string_requirement {
8305 my ($self, $module, $req) = @_;
8306
8307 unless ( defined $req && length $req ) {
8308 $req = 0;
8309 $self->_blank_carp($module);
8310 }
8311
8312 my $magic = _find_magic_vstring( $req );
8313 if (length $magic) {
8314 $self->add_minimum($module => $magic);
8315 return;
8316 }
8317
8318 my @parts = split qr{\s*,\s*}, $req;
8319
8320 for my $part (@parts) {
8321 my ($op, $ver) = $part =~ m{\A\s*(==|>=|>|<=|<|!=)\s*(.*)\z};
8322
8323 if (! defined $op) {
8324 $self->add_minimum($module => $part);
8325 } else {
8326 Carp::confess("illegal requirement string: $req")
8327 unless my $methods = $methods_for_op{ $op };
8328
8329 $self->$_($module => $ver) for @$methods;
8330 }
8331 }
8332 }
8333
8334 #pod =method from_string_hash
8335 #pod
8336 #pod my $req = CPAN::Meta::Requirements->from_string_hash( \%hash );
8337 #pod my $req = CPAN::Meta::Requirements->from_string_hash( \%hash, \%opts );
8338 #pod
8339 #pod This is an alternate constructor for a CPAN::Meta::Requirements
8340 #pod object. It takes a hash of module names and version requirement
8341 #pod strings and returns a new CPAN::Meta::Requirements object. As with
8342 #pod add_string_requirement, a version can be a Perl "v-string". Optionally,
8343 #pod you can supply a hash-reference of options, exactly as with the L</new>
8344 #pod method.
8345 #pod
8346 #pod =cut
8347
8348 sub _blank_carp {
8349 my ($self, $module) = @_;
8350 Carp::carp("Undefined requirement for $module treated as '0'");
8351 }
8352
8353 sub from_string_hash {
8354 my ($class, $hash, $options) = @_;
8355
8356 my $self = $class->new($options);
8357
8358 for my $module (keys %$hash) {
8359 my $req = $hash->{$module};
8360 unless ( defined $req && length $req ) {
8361 $req = 0;
8362 $class->_blank_carp($module);
8363 }
8364 $self->add_string_requirement($module, $req);
8365 }
8366
8367 return $self;
8368 }
8369
8370 ##############################################################
8371
8372 {
8373 package
8374 CPAN::Meta::Requirements::_Range::Exact;
8375 sub _new { bless { version => $_[1] } => $_[0] }
8376
8377 sub _accepts { return $_[0]{version} == $_[1] }
8378
8379 sub as_string { return "== $_[0]{version}" }
8380
8381 sub as_modifiers { return [ [ exact_version => $_[0]{version} ] ] }
8382
8383 sub _clone {
8384 (ref $_[0])->_new( version->new( $_[0]{version} ) )
8385 }
8386
8387 sub with_exact_version {
8388 my ($self, $version) = @_;
8389
8390 return $self->_clone if $self->_accepts($version);
8391
8392 Carp::confess("illegal requirements: unequal exact version specified");
8393 }
8394
8395 sub with_minimum {
8396 my ($self, $minimum) = @_;
8397 return $self->_clone if $self->{version} >= $minimum;
8398 Carp::confess("illegal requirements: minimum above exact specification");
8399 }
8400
8401 sub with_maximum {
8402 my ($self, $maximum) = @_;
8403 return $self->_clone if $self->{version} <= $maximum;
8404 Carp::confess("illegal requirements: maximum below exact specification");
8405 }
8406
8407 sub with_exclusion {
8408 my ($self, $exclusion) = @_;
8409 return $self->_clone unless $exclusion == $self->{version};
8410 Carp::confess("illegal requirements: excluded exact specification");
8411 }
8412 }
8413
8414 ##############################################################
8415
8416 {
8417 package
8418 CPAN::Meta::Requirements::_Range::Range;
8419
8420 sub _self { ref($_[0]) ? $_[0] : (bless { } => $_[0]) }
8421
8422 sub _clone {
8423 return (bless { } => $_[0]) unless ref $_[0];
8424
8425 my ($s) = @_;
8426 my %guts = (
8427 (exists $s->{minimum} ? (minimum => version->new($s->{minimum})) : ()),
8428 (exists $s->{maximum} ? (maximum => version->new($s->{maximum})) : ()),
8429
8430 (exists $s->{exclusions}
8431 ? (exclusions => [ map { version->new($_) } @{ $s->{exclusions} } ])
8432 : ()),
8433 );
8434
8435 bless \%guts => ref($s);
8436 }
8437
8438 sub as_modifiers {
8439 my ($self) = @_;
8440 my @mods;
8441 push @mods, [ add_minimum => $self->{minimum} ] if exists $self->{minimum};
8442 push @mods, [ add_maximum => $self->{maximum} ] if exists $self->{maximum};
8443 push @mods, map {; [ add_exclusion => $_ ] } @{$self->{exclusions} || []};
8444 return \@mods;
8445 }
8446
8447 sub as_string {
8448 my ($self) = @_;
8449
8450 return 0 if ! keys %$self;
8451
8452 return "$self->{minimum}" if (keys %$self) == 1 and exists $self->{minimum};
8453
8454 my @exclusions = @{ $self->{exclusions} || [] };
8455
8456 my @parts;
8457
8458 for my $pair (
8459 [ qw( >= > minimum ) ],
8460 [ qw( <= < maximum ) ],
8461 ) {
8462 my ($op, $e_op, $k) = @$pair;
8463 if (exists $self->{$k}) {
8464 my @new_exclusions = grep { $_ != $self->{ $k } } @exclusions;
8465 if (@new_exclusions == @exclusions) {
8466 push @parts, "$op $self->{ $k }";
8467 } else {
8468 push @parts, "$e_op $self->{ $k }";
8469 @exclusions = @new_exclusions;
8470 }
8471 }
8472 }
8473
8474 push @parts, map {; "!= $_" } @exclusions;
8475
8476 return join q{, }, @parts;
8477 }
8478
8479 sub with_exact_version {
8480 my ($self, $version) = @_;
8481 $self = $self->_clone;
8482
8483 Carp::confess("illegal requirements: exact specification outside of range")
8484 unless $self->_accepts($version);
8485
8486 return CPAN::Meta::Requirements::_Range::Exact->_new($version);
8487 }
8488
8489 sub _simplify {
8490 my ($self) = @_;
8491
8492 if (defined $self->{minimum} and defined $self->{maximum}) {
8493 if ($self->{minimum} == $self->{maximum}) {
8494 Carp::confess("illegal requirements: excluded all values")
8495 if grep { $_ == $self->{minimum} } @{ $self->{exclusions} || [] };
8496
8497 return CPAN::Meta::Requirements::_Range::Exact->_new($self->{minimum})
8498 }
8499
8500 Carp::confess("illegal requirements: minimum exceeds maximum")
8501 if $self->{minimum} > $self->{maximum};
8502 }
8503
8504 # eliminate irrelevant exclusions
8505 if ($self->{exclusions}) {
8506 my %seen;
8507 @{ $self->{exclusions} } = grep {
8508 (! defined $self->{minimum} or $_ >= $self->{minimum})
8509 and
8510 (! defined $self->{maximum} or $_ <= $self->{maximum})
8511 and
8512 ! $seen{$_}++
8513 } @{ $self->{exclusions} };
8514 }
8515
8516 return $self;
8517 }
8518
8519 sub with_minimum {
8520 my ($self, $minimum) = @_;
8521 $self = $self->_clone;
8522
8523 if (defined (my $old_min = $self->{minimum})) {
8524 $self->{minimum} = (sort { $b cmp $a } ($minimum, $old_min))[0];
8525 } else {
8526 $self->{minimum} = $minimum;
8527 }
8528
8529 return $self->_simplify;
8530 }
8531
8532 sub with_maximum {
8533 my ($self, $maximum) = @_;
8534 $self = $self->_clone;
8535
8536 if (defined (my $old_max = $self->{maximum})) {
8537 $self->{maximum} = (sort { $a cmp $b } ($maximum, $old_max))[0];
8538 } else {
8539 $self->{maximum} = $maximum;
8540 }
8541
8542 return $self->_simplify;
8543 }
8544
8545 sub with_exclusion {
8546 my ($self, $exclusion) = @_;
8547 $self = $self->_clone;
8548
8549 push @{ $self->{exclusions} ||= [] }, $exclusion;
8550
8551 return $self->_simplify;
8552 }
8553
8554 sub _accepts {
8555 my ($self, $version) = @_;
8556
8557 return if defined $self->{minimum} and $version < $self->{minimum};
8558 return if defined $self->{maximum} and $version > $self->{maximum};
8559 return if defined $self->{exclusions}
8560 and grep { $version == $_ } @{ $self->{exclusions} };
8561
8562 return 1;
8563 }
8564 }
8565
8566 1;
8567 # vim: ts=2 sts=2 sw=2 et:
8568
8569 __END__
8570
8571 =pod
8572
8573 =encoding UTF-8
8574
8575 =head1 NAME
8576
8577 CPAN::Meta::Requirements - a set of version requirements for a CPAN dist
8578
8579 =head1 VERSION
8580
8581 version 2.133
8582
8583 =head1 SYNOPSIS
8584
8585 use CPAN::Meta::Requirements;
8586
8587 my $build_requires = CPAN::Meta::Requirements->new;
8588
8589 $build_requires->add_minimum('Library::Foo' => 1.208);
8590
8591 $build_requires->add_minimum('Library::Foo' => 2.602);
8592
8593 $build_requires->add_minimum('Module::Bar' => 'v1.2.3');
8594
8595 $METAyml->{build_requires} = $build_requires->as_string_hash;
8596
8597 =head1 DESCRIPTION
8598
8599 A CPAN::Meta::Requirements object models a set of version constraints like
8600 those specified in the F<META.yml> or F<META.json> files in CPAN distributions,
8601 and as defined by L<CPAN::Meta::Spec>;
8602 It can be built up by adding more and more constraints, and it will reduce them
8603 to the simplest representation.
8604
8605 Logically impossible constraints will be identified immediately by thrown
8606 exceptions.
8607
8608 =head1 METHODS
8609
8610 =head2 new
8611
8612 my $req = CPAN::Meta::Requirements->new;
8613
8614 This returns a new CPAN::Meta::Requirements object. It takes an optional
8615 hash reference argument. Currently, only one key is supported:
8616
8617 =over 4
8618
8619 =item *
8620
8621 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.
8622
8623 =back
8624
8625 All other keys are ignored.
8626
8627 =head2 add_minimum
8628
8629 $req->add_minimum( $module => $version );
8630
8631 This adds a new minimum version requirement. If the new requirement is
8632 redundant to the existing specification, this has no effect.
8633
8634 Minimum requirements are inclusive. C<$version> is required, along with any
8635 greater version number.
8636
8637 This method returns the requirements object.
8638
8639 =head2 add_maximum
8640
8641 $req->add_maximum( $module => $version );
8642
8643 This adds a new maximum version requirement. If the new requirement is
8644 redundant to the existing specification, this has no effect.
8645
8646 Maximum requirements are inclusive. No version strictly greater than the given
8647 version is allowed.
8648
8649 This method returns the requirements object.
8650
8651 =head2 add_exclusion
8652
8653 $req->add_exclusion( $module => $version );
8654
8655 This adds a new excluded version. For example, you might use these three
8656 method calls:
8657
8658 $req->add_minimum( $module => '1.00' );
8659 $req->add_maximum( $module => '1.82' );
8660
8661 $req->add_exclusion( $module => '1.75' );
8662
8663 Any version between 1.00 and 1.82 inclusive would be acceptable, except for
8664 1.75.
8665
8666 This method returns the requirements object.
8667
8668 =head2 exact_version
8669
8670 $req->exact_version( $module => $version );
8671
8672 This sets the version required for the given module to I<exactly> the given
8673 version. No other version would be considered acceptable.
8674
8675 This method returns the requirements object.
8676
8677 =head2 add_requirements
8678
8679 $req->add_requirements( $another_req_object );
8680
8681 This method adds all the requirements in the given CPAN::Meta::Requirements object
8682 to the requirements object on which it was called. If there are any conflicts,
8683 an exception is thrown.
8684
8685 This method returns the requirements object.
8686
8687 =head2 accepts_module
8688
8689 my $bool = $req->accepts_module($module => $version);
8690
8691 Given an module and version, this method returns true if the version
8692 specification for the module accepts the provided version. In other words,
8693 given:
8694
8695 Module => '>= 1.00, < 2.00'
8696
8697 We will accept 1.00 and 1.75 but not 0.50 or 2.00.
8698
8699 For modules that do not appear in the requirements, this method will return
8700 true.
8701
8702 =head2 clear_requirement
8703
8704 $req->clear_requirement( $module );
8705
8706 This removes the requirement for a given module from the object.
8707
8708 This method returns the requirements object.
8709
8710 =head2 requirements_for_module
8711
8712 $req->requirements_for_module( $module );
8713
8714 This returns a string containing the version requirements for a given module in
8715 the format described in L<CPAN::Meta::Spec> or undef if the given module has no
8716 requirements. This should only be used for informational purposes such as error
8717 messages and should not be interpreted or used for comparison (see
8718 L</accepts_module> instead.)
8719
8720 =head2 required_modules
8721
8722 This method returns a list of all the modules for which requirements have been
8723 specified.
8724
8725 =head2 clone
8726
8727 $req->clone;
8728
8729 This method returns a clone of the invocant. The clone and the original object
8730 can then be changed independent of one another.
8731
8732 =head2 is_simple
8733
8734 This method returns true if and only if all requirements are inclusive minimums
8735 -- that is, if their string expression is just the version number.
8736
8737 =head2 is_finalized
8738
8739 This method returns true if the requirements have been finalized by having the
8740 C<finalize> method called on them.
8741
8742 =head2 finalize
8743
8744 This method marks the requirements finalized. Subsequent attempts to change
8745 the requirements will be fatal, I<if> they would result in a change. If they
8746 would not alter the requirements, they have no effect.
8747
8748 If a finalized set of requirements is cloned, the cloned requirements are not
8749 also finalized.
8750
8751 =head2 as_string_hash
8752
8753 This returns a reference to a hash describing the requirements using the
8754 strings in the L<CPAN::Meta::Spec> specification.
8755
8756 For example after the following program:
8757
8758 my $req = CPAN::Meta::Requirements->new;
8759
8760 $req->add_minimum('CPAN::Meta::Requirements' => 0.102);
8761
8762 $req->add_minimum('Library::Foo' => 1.208);
8763
8764 $req->add_maximum('Library::Foo' => 2.602);
8765
8766 $req->add_minimum('Module::Bar' => 'v1.2.3');
8767
8768 $req->add_exclusion('Module::Bar' => 'v1.2.8');
8769
8770 $req->exact_version('Xyzzy' => '6.01');
8771
8772 my $hashref = $req->as_string_hash;
8773
8774 C<$hashref> would contain:
8775
8776 {
8777 'CPAN::Meta::Requirements' => '0.102',
8778 'Library::Foo' => '>= 1.208, <= 2.206',
8779 'Module::Bar' => '>= v1.2.3, != v1.2.8',
8780 'Xyzzy' => '== 6.01',
8781 }
8782
8783 =head2 add_string_requirement
8784
8785 $req->add_string_requirement('Library::Foo' => '>= 1.208, <= 2.206');
8786 $req->add_string_requirement('Library::Foo' => v1.208);
8787
8788 This method parses the passed in string and adds the appropriate requirement
8789 for the given module. A version can be a Perl "v-string". It understands
8790 version ranges as described in the L<CPAN::Meta::Spec/Version Ranges>. For
8791 example:
8792
8793 =over 4
8794
8795 =item 1.3
8796
8797 =item >= 1.3
8798
8799 =item <= 1.3
8800
8801 =item == 1.3
8802
8803 =item != 1.3
8804
8805 =item > 1.3
8806
8807 =item < 1.3
8808
8809 =item >= 1.3, != 1.5, <= 2.0
8810
8811 A version number without an operator is equivalent to specifying a minimum
8812 (C<E<gt>=>). Extra whitespace is allowed.
8813
8814 =back
8815
8816 =head2 from_string_hash
8817
8818 my $req = CPAN::Meta::Requirements->from_string_hash( \%hash );
8819 my $req = CPAN::Meta::Requirements->from_string_hash( \%hash, \%opts );
8820
8821 This is an alternate constructor for a CPAN::Meta::Requirements
8822 object. It takes a hash of module names and version requirement
8823 strings and returns a new CPAN::Meta::Requirements object. As with
8824 add_string_requirement, a version can be a Perl "v-string". Optionally,
8825 you can supply a hash-reference of options, exactly as with the L</new>
8826 method.
8827
8828 =for :stopwords cpan testmatrix url annocpan anno bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan
8829
8830 =head1 SUPPORT
8831
8832 =head2 Bugs / Feature Requests
8833
8834 Please report any bugs or feature requests through the issue tracker
8835 at L<https://github.com/dagolden/CPAN-Meta-Requirements/issues>.
8836 You will be notified automatically of any progress on your issue.
8837
8838 =head2 Source Code
8839
8840 This is open source software. The code repository is available for
8841 public review and contribution under the terms of the license.
8842
8843 L<https://github.com/dagolden/CPAN-Meta-Requirements>
8844
8845 git clone https://github.com/dagolden/CPAN-Meta-Requirements.git
8846
8847 =head1 AUTHORS
8848
8849 =over 4
8850
8851 =item *
8852
8853 David Golden <dagolden@cpan.org>
8854
8855 =item *
8856
8857 Ricardo Signes <rjbs@cpan.org>
8858
8859 =back
8860
8861 =head1 CONTRIBUTORS
8862
8863 =for stopwords Ed J Karen Etheridge Leon Timmermans robario
8864
8865 =over 4
8866
8867 =item *
8868
8869 Ed J <mohawk2@users.noreply.github.com>
8870
8871 =item *
8872
8873 Karen Etheridge <ether@cpan.org>
8874
8875 =item *
8876
8877 Leon Timmermans <fawaka@gmail.com>
8878
8879 =item *
8880
8881 robario <webmaster@robario.com>
8882
8883 =back
8884
8885 =head1 COPYRIGHT AND LICENSE
8886
8887 This software is copyright (c) 2010 by David Golden and Ricardo Signes.
8888
8889 This is free software; you can redistribute it and/or modify it under
8890 the same terms as the Perl 5 programming language system itself.
8891
8892 =cut
8893 CPAN_META_REQUIREMENTS
8894  
8895 $fatpacked{"CPAN/Meta/Spec.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CPAN_META_SPEC';
8896 # XXX RULES FOR PATCHING THIS FILE XXX
8897 # Patches that fix typos or formatting are acceptable. Patches
8898 # that change semantics are not acceptable without prior approval
8899 # by David Golden or Ricardo Signes.
8900
8901 use 5.006;
8902 use strict;
8903 use warnings;
8904 package CPAN::Meta::Spec;
8905
8906 our $VERSION = '2.150005';
8907
8908 1;
8909
8910 # ABSTRACT: specification for CPAN distribution metadata
8911
8912
8913 # vi:tw=72
8914
8915 __END__
8916
8917 =pod
8918
8919 =encoding UTF-8
8920
8921 =head1 NAME
8922
8923 CPAN::Meta::Spec - specification for CPAN distribution metadata
8924
8925 =head1 VERSION
8926
8927 version 2.150005
8928
8929 =head1 SYNOPSIS
8930
8931 my $distmeta = {
8932 name => 'Module-Build',
8933 abstract => 'Build and install Perl modules',
8934 description => "Module::Build is a system for "
8935 . "building, testing, and installing Perl modules. "
8936 . "It is meant to ... blah blah blah ...",
8937 version => '0.36',
8938 release_status => 'stable',
8939 author => [
8940 'Ken Williams <kwilliams@cpan.org>',
8941 'Module-Build List <module-build@perl.org>', # additional contact
8942 ],
8943 license => [ 'perl_5' ],
8944 prereqs => {
8945 runtime => {
8946 requires => {
8947 'perl' => '5.006',
8948 'ExtUtils::Install' => '0',
8949 'File::Basename' => '0',
8950 'File::Compare' => '0',
8951 'IO::File' => '0',
8952 },
8953 recommends => {
8954 'Archive::Tar' => '1.00',
8955 'ExtUtils::Install' => '0.3',
8956 'ExtUtils::ParseXS' => '2.02',
8957 },
8958 },
8959 build => {
8960 requires => {
8961 'Test::More' => '0',
8962 },
8963 }
8964 },
8965 resources => {
8966 license => ['http://dev.perl.org/licenses/'],
8967 },
8968 optional_features => {
8969 domination => {
8970 description => 'Take over the world',
8971 prereqs => {
8972 develop => { requires => { 'Genius::Evil' => '1.234' } },
8973 runtime => { requires => { 'Machine::Weather' => '2.0' } },
8974 },
8975 },
8976 },
8977 dynamic_config => 1,
8978 keywords => [ qw/ toolchain cpan dual-life / ],
8979 'meta-spec' => {
8980 version => '2',
8981 url => 'https://metacpan.org/pod/CPAN::Meta::Spec',
8982 },
8983 generated_by => 'Module::Build version 0.36',
8984 };
8985
8986 =head1 DESCRIPTION
8987
8988 This document describes version 2 of the CPAN distribution metadata
8989 specification, also known as the "CPAN Meta Spec".
8990
8991 Revisions of this specification for typo corrections and prose
8992 clarifications may be issued as CPAN::Meta::Spec 2.I<x>. These
8993 revisions will never change semantics or add or remove specified
8994 behavior.
8995
8996 Distribution metadata describe important properties of Perl
8997 distributions. Distribution building tools like Module::Build,
8998 Module::Install, ExtUtils::MakeMaker or Dist::Zilla should create a
8999 metadata file in accordance with this specification and include it with
9000 the distribution for use by automated tools that index, examine, package
9001 or install Perl distributions.
9002
9003 =head1 TERMINOLOGY
9004
9005 =over 4
9006
9007 =item distribution
9008
9009 This is the primary object described by the metadata. In the context of
9010 this document it usually refers to a collection of modules, scripts,
9011 and/or documents that are distributed together for other developers to
9012 use. Examples of distributions are C<Class-Container>, C<libwww-perl>,
9013 or C<DBI>.
9014
9015 =item module
9016
9017 This refers to a reusable library of code contained in a single file.
9018 Modules usually contain one or more packages and are often referred
9019 to by the name of a primary package that can be mapped to the file
9020 name. For example, one might refer to C<File::Spec> instead of
9021 F<File/Spec.pm>
9022
9023 =item package
9024
9025 This refers to a namespace declared with the Perl C<package> statement.
9026 In Perl, packages often have a version number property given by the
9027 C<$VERSION> variable in the namespace.
9028
9029 =item consumer
9030
9031 This refers to code that reads a metadata file, deserializes it into a
9032 data structure in memory, or interprets a data structure of metadata
9033 elements.
9034
9035 =item producer
9036
9037 This refers to code that constructs a metadata data structure,
9038 serializes into a bytestream and/or writes it to disk.
9039
9040 =item must, should, may, etc.
9041
9042 These terms are interpreted as described in IETF RFC 2119.
9043
9044 =back
9045
9046 =head1 DATA TYPES
9047
9048 Fields in the L</STRUCTURE> section describe data elements, each of
9049 which has an associated data type as described herein. There are four
9050 primitive types: Boolean, String, List and Map. Other types are
9051 subtypes of primitives and define compound data structures or define
9052 constraints on the values of a data element.
9053
9054 =head2 Boolean
9055
9056 A I<Boolean> is used to provide a true or false value. It B<must> be
9057 represented as a defined value.
9058
9059 =head2 String
9060
9061 A I<String> is data element containing a non-zero length sequence of
9062 Unicode characters, such as an ordinary Perl scalar that is not a
9063 reference.
9064
9065 =head2 List
9066
9067 A I<List> is an ordered collection of zero or more data elements.
9068 Elements of a List may be of mixed types.
9069
9070 Producers B<must> represent List elements using a data structure which
9071 unambiguously indicates that multiple values are possible, such as a
9072 reference to a Perl array (an "arrayref").
9073
9074 Consumers expecting a List B<must> consider a String as equivalent to a
9075 List of length 1.
9076
9077 =head2 Map
9078
9079 A I<Map> is an unordered collection of zero or more data elements
9080 ("values"), indexed by associated String elements ("keys"). The Map's
9081 value elements may be of mixed types.
9082
9083 =head2 License String
9084
9085 A I<License String> is a subtype of String with a restricted set of
9086 values. Valid values are described in detail in the description of
9087 the L</license> field.
9088
9089 =head2 URL
9090
9091 I<URL> is a subtype of String containing a Uniform Resource Locator or
9092 Identifier. [ This type is called URL and not URI for historical reasons. ]
9093
9094 =head2 Version
9095
9096 A I<Version> is a subtype of String containing a value that describes
9097 the version number of packages or distributions. Restrictions on format
9098 are described in detail in the L</Version Formats> section.
9099
9100 =head2 Version Range
9101
9102 The I<Version Range> type is a subtype of String. It describes a range
9103 of Versions that may be present or installed to fulfill prerequisites.
9104 It is specified in detail in the L</Version Ranges> section.
9105
9106 =head1 STRUCTURE
9107
9108 The metadata structure is a data element of type Map. This section
9109 describes valid keys within the Map.
9110
9111 Any keys not described in this specification document (whether top-level
9112 or within compound data structures described herein) are considered
9113 I<custom keys> and B<must> begin with an "x" or "X" and be followed by an
9114 underscore; i.e. they must match the pattern: C<< qr{\Ax_}i >>. If a
9115 custom key refers to a compound data structure, subkeys within it do not
9116 need an "x_" or "X_" prefix.
9117
9118 Consumers of metadata may ignore any or all custom keys. All other keys
9119 not described herein are invalid and should be ignored by consumers.
9120 Producers must not generate or output invalid keys.
9121
9122 For each key, an example is provided followed by a description. The
9123 description begins with the version of spec in which the key was added
9124 or in which the definition was modified, whether the key is I<required>
9125 or I<optional> and the data type of the corresponding data element.
9126 These items are in parentheses, brackets and braces, respectively.
9127
9128 If a data type is a Map or Map subtype, valid subkeys will be described
9129 as well.
9130
9131 Some fields are marked I<Deprecated>. These are shown for historical
9132 context and must not be produced in or consumed from any metadata structure
9133 of version 2 or higher.
9134
9135 =head2 REQUIRED FIELDS
9136
9137 =head3 abstract
9138
9139 Example:
9140
9141 abstract => 'Build and install Perl modules'
9142
9143 (Spec 1.2) [required] {String}
9144
9145 This is a short description of the purpose of the distribution.
9146
9147 =head3 author
9148
9149 Example:
9150
9151 author => [ 'Ken Williams <kwilliams@cpan.org>' ]
9152
9153 (Spec 1.2) [required] {List of one or more Strings}
9154
9155 This List indicates the person(s) to contact concerning the
9156 distribution. The preferred form of the contact string is:
9157
9158 contact-name <email-address>
9159
9160 This field provides a general contact list independent of other
9161 structured fields provided within the L</resources> field, such as
9162 C<bugtracker>. The addressee(s) can be contacted for any purpose
9163 including but not limited to (security) problems with the distribution,
9164 questions about the distribution or bugs in the distribution.
9165
9166 A distribution's original author is usually the contact listed within
9167 this field. Co-maintainers, successor maintainers or mailing lists
9168 devoted to the distribution may also be listed in addition to or instead
9169 of the original author.
9170
9171 =head3 dynamic_config
9172
9173 Example:
9174
9175 dynamic_config => 1
9176
9177 (Spec 2) [required] {Boolean}
9178
9179 A boolean flag indicating whether a F<Build.PL> or F<Makefile.PL> (or
9180 similar) must be executed to determine prerequisites.
9181
9182 This field should be set to a true value if the distribution performs
9183 some dynamic configuration (asking questions, sensing the environment,
9184 etc.) as part of its configuration. This field should be set to a false
9185 value to indicate that prerequisites included in metadata may be
9186 considered final and valid for static analysis.
9187
9188 Note: when this field is true, post-configuration prerequisites are not
9189 guaranteed to bear any relation whatsoever to those stated in the metadata,
9190 and relying on them doing so is an error. See also
9191 L</Prerequisites for dynamically configured distributions> in the implementors'
9192 notes.
9193
9194 This field explicitly B<does not> indicate whether installation may be
9195 safely performed without using a Makefile or Build file, as there may be
9196 special files to install or custom installation targets (e.g. for
9197 dual-life modules that exist on CPAN as well as in the Perl core). This
9198 field only defines whether or not prerequisites are exactly as given in the
9199 metadata.
9200
9201 =head3 generated_by
9202
9203 Example:
9204
9205 generated_by => 'Module::Build version 0.36'
9206
9207 (Spec 1.0) [required] {String}
9208
9209 This field indicates the tool that was used to create this metadata.
9210 There are no defined semantics for this field, but it is traditional to
9211 use a string in the form "Generating::Package version 1.23" or the
9212 author's name, if the file was generated by hand.
9213
9214 =head3 license
9215
9216 Example:
9217
9218 license => [ 'perl_5' ]
9219
9220 license => [ 'apache_2_0', 'mozilla_1_0' ]
9221
9222 (Spec 2) [required] {List of one or more License Strings}
9223
9224 One or more licenses that apply to some or all of the files in the
9225 distribution. If multiple licenses are listed, the distribution
9226 documentation should be consulted to clarify the interpretation of
9227 multiple licenses.
9228
9229 The following list of license strings are valid:
9230
9231 string description
9232 ------------- -----------------------------------------------
9233 agpl_3 GNU Affero General Public License, Version 3
9234 apache_1_1 Apache Software License, Version 1.1
9235 apache_2_0 Apache License, Version 2.0
9236 artistic_1 Artistic License, (Version 1)
9237 artistic_2 Artistic License, Version 2.0
9238 bsd BSD License (three-clause)
9239 freebsd FreeBSD License (two-clause)
9240 gfdl_1_2 GNU Free Documentation License, Version 1.2
9241 gfdl_1_3 GNU Free Documentation License, Version 1.3
9242 gpl_1 GNU General Public License, Version 1
9243 gpl_2 GNU General Public License, Version 2
9244 gpl_3 GNU General Public License, Version 3
9245 lgpl_2_1 GNU Lesser General Public License, Version 2.1
9246 lgpl_3_0 GNU Lesser General Public License, Version 3.0
9247 mit MIT (aka X11) License
9248 mozilla_1_0 Mozilla Public License, Version 1.0
9249 mozilla_1_1 Mozilla Public License, Version 1.1
9250 openssl OpenSSL License
9251 perl_5 The Perl 5 License (Artistic 1 & GPL 1 or later)
9252 qpl_1_0 Q Public License, Version 1.0
9253 ssleay Original SSLeay License
9254 sun Sun Internet Standards Source License (SISSL)
9255 zlib zlib License
9256
9257 The following license strings are also valid and indicate other
9258 licensing not described above:
9259
9260 string description
9261 ------------- -----------------------------------------------
9262 open_source Other Open Source Initiative (OSI) approved license
9263 restricted Requires special permission from copyright holder
9264 unrestricted Not an OSI approved license, but not restricted
9265 unknown License not provided in metadata
9266
9267 All other strings are invalid in the license field.
9268
9269 =head3 meta-spec
9270
9271 Example:
9272
9273 'meta-spec' => {
9274 version => '2',
9275 url => 'http://search.cpan.org/perldoc?CPAN::Meta::Spec',
9276 }
9277
9278 (Spec 1.2) [required] {Map}
9279
9280 This field indicates the version of the CPAN Meta Spec that should be
9281 used to interpret the metadata. Consumers must check this key as soon
9282 as possible and abort further metadata processing if the meta-spec
9283 version is not supported by the consumer.
9284
9285 The following keys are valid, but only C<version> is required.
9286
9287 =over
9288
9289 =item version
9290
9291 This subkey gives the integer I<Version> of the CPAN Meta Spec against
9292 which the document was generated.
9293
9294 =item url
9295
9296 This is a I<URL> of the metadata specification document corresponding to
9297 the given version. This is strictly for human-consumption and should
9298 not impact the interpretation of the document.
9299
9300 For the version 2 spec, either of these are recommended:
9301
9302 =over 4
9303
9304 =item *
9305
9306 C<https://metacpan.org/pod/CPAN::Meta::Spec>
9307
9308 =item *
9309
9310 C<http://search.cpan.org/perldoc?CPAN::Meta::Spec>
9311
9312 =back
9313
9314 =back
9315
9316 =head3 name
9317
9318 Example:
9319
9320 name => 'Module-Build'
9321
9322 (Spec 1.0) [required] {String}
9323
9324 This field is the name of the distribution. This is often created by
9325 taking the "main package" in the distribution and changing C<::> to
9326 C<->, but the name may be completely unrelated to the packages within
9327 the distribution. For example, L<LWP::UserAgent> is distributed as part
9328 of the distribution name "libwww-perl".
9329
9330 =head3 release_status
9331
9332 Example:
9333
9334 release_status => 'stable'
9335
9336 (Spec 2) [required] {String}
9337
9338 This field provides the release status of this distribution. If the
9339 C<version> field contains an underscore character, then
9340 C<release_status> B<must not> be "stable."
9341
9342 The C<release_status> field B<must> have one of the following values:
9343
9344 =over
9345
9346 =item stable
9347
9348 This indicates an ordinary, "final" release that should be indexed by PAUSE
9349 or other indexers.
9350
9351 =item testing
9352
9353 This indicates a "beta" release that is substantially complete, but has an
9354 elevated risk of bugs and requires additional testing. The distribution
9355 should not be installed over a stable release without an explicit request
9356 or other confirmation from a user. This release status may also be used
9357 for "release candidate" versions of a distribution.
9358
9359 =item unstable
9360
9361 This indicates an "alpha" release that is under active development, but has
9362 been released for early feedback or testing and may be missing features or
9363 may have serious bugs. The distribution should not be installed over a
9364 stable release without an explicit request or other confirmation from a
9365 user.
9366
9367 =back
9368
9369 Consumers B<may> use this field to determine how to index the
9370 distribution for CPAN or other repositories in addition to or in
9371 replacement of heuristics based on version number or file name.
9372
9373 =head3 version
9374
9375 Example:
9376
9377 version => '0.36'
9378
9379 (Spec 1.0) [required] {Version}
9380
9381 This field gives the version of the distribution to which the metadata
9382 structure refers.
9383
9384 =head2 OPTIONAL FIELDS
9385
9386 =head3 description
9387
9388 Example:
9389
9390 description => "Module::Build is a system for "
9391 . "building, testing, and installing Perl modules. "
9392 . "It is meant to ... blah blah blah ...",
9393
9394 (Spec 2) [optional] {String}
9395
9396 A longer, more complete description of the purpose or intended use of
9397 the distribution than the one provided by the C<abstract> key.
9398
9399 =head3 keywords
9400
9401 Example:
9402
9403 keywords => [ qw/ toolchain cpan dual-life / ]
9404
9405 (Spec 1.1) [optional] {List of zero or more Strings}
9406
9407 A List of keywords that describe this distribution. Keywords
9408 B<must not> include whitespace.
9409
9410 =head3 no_index
9411
9412 Example:
9413
9414 no_index => {
9415 file => [ 'My/Module.pm' ],
9416 directory => [ 'My/Private' ],
9417 package => [ 'My::Module::Secret' ],
9418 namespace => [ 'My::Module::Sample' ],
9419 }
9420
9421 (Spec 1.2) [optional] {Map}
9422
9423 This Map describes any files, directories, packages, and namespaces that
9424 are private to the packaging or implementation of the distribution and
9425 should be ignored by indexing or search tools. Note that this is a list of
9426 exclusions, and the spec does not define what to I<include> - see
9427 L</Indexing distributions a la PAUSE> in the implementors notes for more
9428 information.
9429
9430 Valid subkeys are as follows:
9431
9432 =over
9433
9434 =item file
9435
9436 A I<List> of relative paths to files. Paths B<must be> specified with
9437 unix conventions.
9438
9439 =item directory
9440
9441 A I<List> of relative paths to directories. Paths B<must be> specified
9442 with unix conventions.
9443
9444 [ Note: previous editions of the spec had C<dir> instead of C<directory> ]
9445
9446 =item package
9447
9448 A I<List> of package names.
9449
9450 =item namespace
9451
9452 A I<List> of package namespaces, where anything below the namespace
9453 must be ignored, but I<not> the namespace itself.
9454
9455 In the example above for C<no_index>, C<My::Module::Sample::Foo> would
9456 be ignored, but C<My::Module::Sample> would not.
9457
9458 =back
9459
9460 =head3 optional_features
9461
9462 Example:
9463
9464 optional_features => {
9465 sqlite => {
9466 description => 'Provides SQLite support',
9467 prereqs => {
9468 runtime => {
9469 requires => {
9470 'DBD::SQLite' => '1.25'
9471 }
9472 }
9473 }
9474 }
9475 }
9476
9477 (Spec 2) [optional] {Map}
9478
9479 This Map describes optional features with incremental prerequisites.
9480 Each key of the C<optional_features> Map is a String used to identify
9481 the feature and each value is a Map with additional information about
9482 the feature. Valid subkeys include:
9483
9484 =over
9485
9486 =item description
9487
9488 This is a String describing the feature. Every optional feature
9489 should provide a description
9490
9491 =item prereqs
9492
9493 This entry is required and has the same structure as that of the
9494 C<L</prereqs>> key. It provides a list of package requirements
9495 that must be satisfied for the feature to be supported or enabled.
9496
9497 There is one crucial restriction: the prereqs of an optional feature
9498 B<must not> include C<configure> phase prereqs.
9499
9500 =back
9501
9502 Consumers B<must not> include optional features as prerequisites without
9503 explicit instruction from users (whether via interactive prompting,
9504 a function parameter or a configuration value, etc. ).
9505
9506 If an optional feature is used by a consumer to add additional
9507 prerequisites, the consumer should merge the optional feature
9508 prerequisites into those given by the C<prereqs> key using the same
9509 semantics. See L</Merging and Resolving Prerequisites> for details on
9510 merging prerequisites.
9511
9512 I<Suggestion for disuse:> Because there is currently no way for a
9513 distribution to specify a dependency on an optional feature of another
9514 dependency, the use of C<optional_feature> is discouraged. Instead,
9515 create a separate, installable distribution that ensures the desired
9516 feature is available. For example, if C<Foo::Bar> has a C<Baz> feature,
9517 release a separate C<Foo-Bar-Baz> distribution that satisfies
9518 requirements for the feature.
9519
9520 =head3 prereqs
9521
9522 Example:
9523
9524 prereqs => {
9525 runtime => {
9526 requires => {
9527 'perl' => '5.006',
9528 'File::Spec' => '0.86',
9529 'JSON' => '2.16',
9530 },
9531 recommends => {
9532 'JSON::XS' => '2.26',
9533 },
9534 suggests => {
9535 'Archive::Tar' => '0',
9536 },
9537 },
9538 build => {
9539 requires => {
9540 'Alien::SDL' => '1.00',
9541 },
9542 },
9543 test => {
9544 recommends => {
9545 'Test::Deep' => '0.10',
9546 },
9547 }
9548 }
9549
9550 (Spec 2) [optional] {Map}
9551
9552 This is a Map that describes all the prerequisites of the distribution.
9553 The keys are phases of activity, such as C<configure>, C<build>, C<test>
9554 or C<runtime>. Values are Maps in which the keys name the type of
9555 prerequisite relationship such as C<requires>, C<recommends>, or
9556 C<suggests> and the value provides a set of prerequisite relations. The
9557 set of relations B<must> be specified as a Map of package names to
9558 version ranges.
9559
9560 The full definition for this field is given in the L</Prereq Spec>
9561 section.
9562
9563 =head3 provides
9564
9565 Example:
9566
9567 provides => {
9568 'Foo::Bar' => {
9569 file => 'lib/Foo/Bar.pm',
9570 version => '0.27_02',
9571 },
9572 'Foo::Bar::Blah' => {
9573 file => 'lib/Foo/Bar/Blah.pm',
9574 },
9575 'Foo::Bar::Baz' => {
9576 file => 'lib/Foo/Bar/Baz.pm',
9577 version => '0.3',
9578 },
9579 }
9580
9581 (Spec 1.2) [optional] {Map}
9582
9583 This describes all packages provided by this distribution. This
9584 information is used by distribution and automation mechanisms like
9585 PAUSE, CPAN, metacpan.org and search.cpan.org to build indexes saying in
9586 which distribution various packages can be found.
9587
9588 The keys of C<provides> are package names that can be found within
9589 the distribution. If a package name key is provided, it must
9590 have a Map with the following valid subkeys:
9591
9592 =over
9593
9594 =item file
9595
9596 This field is required. It must contain a Unix-style relative file path
9597 from the root of the distribution directory to a file that contains or
9598 generates the package. It may be given as C<META.yml> or C<META.json>
9599 to claim a package for indexing without needing a C<*.pm>.
9600
9601 =item version
9602
9603 If it exists, this field must contains a I<Version> String for the
9604 package. If the package does not have a C<$VERSION>, this field must
9605 be omitted.
9606
9607 =back
9608
9609 =head3 resources
9610
9611 Example:
9612
9613 resources => {
9614 license => [ 'http://dev.perl.org/licenses/' ],
9615 homepage => 'http://sourceforge.net/projects/module-build',
9616 bugtracker => {
9617 web => 'http://rt.cpan.org/Public/Dist/Display.html?Name=CPAN-Meta',
9618 mailto => 'meta-bugs@example.com',
9619 },
9620 repository => {
9621 url => 'git://github.com/dagolden/cpan-meta.git',
9622 web => 'http://github.com/dagolden/cpan-meta',
9623 type => 'git',
9624 },
9625 x_twitter => 'http://twitter.com/cpan_linked/',
9626 }
9627
9628 (Spec 2) [optional] {Map}
9629
9630 This field describes resources related to this distribution.
9631
9632 Valid subkeys include:
9633
9634 =over
9635
9636 =item homepage
9637
9638 The official home of this project on the web.
9639
9640 =item license
9641
9642 A List of I<URL>'s that relate to this distribution's license. As with the
9643 top-level C<license> field, distribution documentation should be consulted
9644 to clarify the interpretation of multiple licenses provided here.
9645
9646 =item bugtracker
9647
9648 This entry describes the bug tracking system for this distribution. It
9649 is a Map with the following valid keys:
9650
9651 web - a URL pointing to a web front-end for the bug tracker
9652 mailto - an email address to which bugs can be sent
9653
9654 =item repository
9655
9656 This entry describes the source control repository for this distribution. It
9657 is a Map with the following valid keys:
9658
9659 url - a URL pointing to the repository itself
9660 web - a URL pointing to a web front-end for the repository
9661 type - a lowercase string indicating the VCS used
9662
9663 Because a url like C<http://myrepo.example.com/> is ambiguous as to
9664 type, producers should provide a C<type> whenever a C<url> key is given.
9665 The C<type> field should be the name of the most common program used
9666 to work with the repository, e.g. C<git>, C<svn>, C<cvs>, C<darcs>,
9667 C<bzr> or C<hg>.
9668
9669 =back
9670
9671 =head2 DEPRECATED FIELDS
9672
9673 =head3 build_requires
9674
9675 I<(Deprecated in Spec 2)> [optional] {String}
9676
9677 Replaced by C<prereqs>
9678
9679 =head3 configure_requires
9680
9681 I<(Deprecated in Spec 2)> [optional] {String}
9682
9683 Replaced by C<prereqs>
9684
9685 =head3 conflicts
9686
9687 I<(Deprecated in Spec 2)> [optional] {String}
9688
9689 Replaced by C<prereqs>
9690
9691 =head3 distribution_type
9692
9693 I<(Deprecated in Spec 2)> [optional] {String}
9694
9695 This field indicated 'module' or 'script' but was considered
9696 meaningless, since many distributions are hybrids of several kinds of
9697 things.
9698
9699 =head3 license_uri
9700
9701 I<(Deprecated in Spec 1.2)> [optional] {URL}
9702
9703 Replaced by C<license> in C<resources>
9704
9705 =head3 private
9706
9707 I<(Deprecated in Spec 1.2)> [optional] {Map}
9708
9709 This field has been renamed to L</"no_index">.
9710
9711 =head3 recommends
9712
9713 I<(Deprecated in Spec 2)> [optional] {String}
9714
9715 Replaced by C<prereqs>
9716
9717 =head3 requires
9718
9719 I<(Deprecated in Spec 2)> [optional] {String}
9720
9721 Replaced by C<prereqs>
9722
9723 =head1 VERSION NUMBERS
9724
9725 =head2 Version Formats
9726
9727 This section defines the Version type, used by several fields in the
9728 CPAN Meta Spec.
9729
9730 Version numbers must be treated as strings, not numbers. For
9731 example, C<1.200> B<must not> be serialized as C<1.2>. Version
9732 comparison should be delegated to the Perl L<version> module, version
9733 0.80 or newer.
9734
9735 Unless otherwise specified, version numbers B<must> appear in one of two
9736 formats:
9737
9738 =over
9739
9740 =item Decimal versions
9741
9742 Decimal versions are regular "decimal numbers", with some limitations.
9743 They B<must> be non-negative and B<must> begin and end with a digit. A
9744 single underscore B<may> be included, but B<must> be between two digits.
9745 They B<must not> use exponential notation ("1.23e-2").
9746
9747 version => '1.234' # OK
9748 version => '1.23_04' # OK
9749
9750 version => '1.23_04_05' # Illegal
9751 version => '1.' # Illegal
9752 version => '.1' # Illegal
9753
9754 =item Dotted-integer versions
9755
9756 Dotted-integer (also known as dotted-decimal) versions consist of
9757 positive integers separated by full stop characters (i.e. "dots",
9758 "periods" or "decimal points"). This are equivalent in format to Perl
9759 "v-strings", with some additional restrictions on form. They must be
9760 given in "normal" form, which has a leading "v" character and at least
9761 three integer components. To retain a one-to-one mapping with decimal
9762 versions, all components after the first B<should> be restricted to the
9763 range 0 to 999. The final component B<may> be separated by an
9764 underscore character instead of a period.
9765
9766 version => 'v1.2.3' # OK
9767 version => 'v1.2_3' # OK
9768 version => 'v1.2.3.4' # OK
9769 version => 'v1.2.3_4' # OK
9770 version => 'v2009.10.31' # OK
9771
9772 version => 'v1.2' # Illegal
9773 version => '1.2.3' # Illegal
9774 version => 'v1.2_3_4' # Illegal
9775 version => 'v1.2009.10.31' # Not recommended
9776
9777 =back
9778
9779 =head2 Version Ranges
9780
9781 Some fields (prereq, optional_features) indicate the particular
9782 version(s) of some other module that may be required as a prerequisite.
9783 This section details the Version Range type used to provide this
9784 information.
9785
9786 The simplest format for a Version Range is just the version
9787 number itself, e.g. C<2.4>. This means that B<at least> version 2.4
9788 must be present. To indicate that B<any> version of a prerequisite is
9789 okay, even if the prerequisite doesn't define a version at all, use
9790 the version C<0>.
9791
9792 Alternatively, a version range B<may> use the operators E<lt> (less than),
9793 E<lt>= (less than or equal), E<gt> (greater than), E<gt>= (greater than
9794 or equal), == (equal), and != (not equal). For example, the
9795 specification C<E<lt> 2.0> means that any version of the prerequisite
9796 less than 2.0 is suitable.
9797
9798 For more complicated situations, version specifications B<may> be AND-ed
9799 together using commas. The specification C<E<gt>= 1.2, != 1.5, E<lt>
9800 2.0> indicates a version that must be B<at least> 1.2, B<less than> 2.0,
9801 and B<not equal to> 1.5.
9802
9803 =head1 PREREQUISITES
9804
9805 =head2 Prereq Spec
9806
9807 The C<prereqs> key in the top-level metadata and within
9808 C<optional_features> define the relationship between a distribution and
9809 other packages. The prereq spec structure is a hierarchical data
9810 structure which divides prerequisites into I<Phases> of activity in the
9811 installation process and I<Relationships> that indicate how
9812 prerequisites should be resolved.
9813
9814 For example, to specify that C<Data::Dumper> is C<required> during the
9815 C<test> phase, this entry would appear in the distribution metadata:
9816
9817 prereqs => {
9818 test => {
9819 requires => {
9820 'Data::Dumper' => '2.00'
9821 }
9822 }
9823 }
9824
9825 =head3 Phases
9826
9827 Requirements for regular use must be listed in the C<runtime> phase.
9828 Other requirements should be listed in the earliest stage in which they
9829 are required and consumers must accumulate and satisfy requirements
9830 across phases before executing the activity. For example, C<build>
9831 requirements must also be available during the C<test> phase.
9832
9833 before action requirements that must be met
9834 ---------------- --------------------------------
9835 perl Build.PL configure
9836 perl Makefile.PL
9837
9838 make configure, runtime, build
9839 Build
9840
9841 make test configure, runtime, build, test
9842 Build test
9843
9844 Consumers that install the distribution must ensure that
9845 I<runtime> requirements are also installed and may install
9846 dependencies from other phases.
9847
9848 after action requirements that must be met
9849 ---------------- --------------------------------
9850 make install runtime
9851 Build install
9852
9853 =over
9854
9855 =item configure
9856
9857 The configure phase occurs before any dynamic configuration has been
9858 attempted. Libraries required by the configure phase B<must> be
9859 available for use before the distribution building tool has been
9860 executed.
9861
9862 =item build
9863
9864 The build phase is when the distribution's source code is compiled (if
9865 necessary) and otherwise made ready for installation.
9866
9867 =item test
9868
9869 The test phase is when the distribution's automated test suite is run.
9870 Any library that is needed only for testing and not for subsequent use
9871 should be listed here.
9872
9873 =item runtime
9874
9875 The runtime phase refers not only to when the distribution's contents
9876 are installed, but also to its continued use. Any library that is a
9877 prerequisite for regular use of this distribution should be indicated
9878 here.
9879
9880 =item develop
9881
9882 The develop phase's prereqs are libraries needed to work on the
9883 distribution's source code as its author does. These tools might be
9884 needed to build a release tarball, to run author-only tests, or to
9885 perform other tasks related to developing new versions of the
9886 distribution.
9887
9888 =back
9889
9890 =head3 Relationships
9891
9892 =over
9893
9894 =item requires
9895
9896 These dependencies B<must> be installed for proper completion of the
9897 phase.
9898
9899 =item recommends
9900
9901 Recommended dependencies are I<strongly> encouraged and should be
9902 satisfied except in resource constrained environments.
9903
9904 =item suggests
9905
9906 These dependencies are optional, but are suggested for enhanced operation
9907 of the described distribution.
9908
9909 =item conflicts
9910
9911 These libraries cannot be installed when the phase is in operation.
9912 This is a very rare situation, and the C<conflicts> relationship should
9913 be used with great caution, or not at all.
9914
9915 =back
9916
9917 =head2 Merging and Resolving Prerequisites
9918
9919 Whenever metadata consumers merge prerequisites, either from different
9920 phases or from C<optional_features>, they should merged in a way which
9921 preserves the intended semantics of the prerequisite structure. Generally,
9922 this means concatenating the version specifications using commas, as
9923 described in the L<Version Ranges> section.
9924
9925 Another subtle error that can occur in resolving prerequisites comes from
9926 the way that modules in prerequisites are indexed to distribution files on
9927 CPAN. When a module is deleted from a distribution, prerequisites calling
9928 for that module could indicate an older distribution should be installed,
9929 potentially overwriting files from a newer distribution.
9930
9931 For example, as of Oct 31, 2009, the CPAN index file contained these
9932 module-distribution mappings:
9933
9934 Class::MOP 0.94 D/DR/DROLSKY/Class-MOP-0.94.tar.gz
9935 Class::MOP::Class 0.94 D/DR/DROLSKY/Class-MOP-0.94.tar.gz
9936 Class::MOP::Class::Immutable 0.04 S/ST/STEVAN/Class-MOP-0.36.tar.gz
9937
9938 Consider the case where "Class::MOP" 0.94 is installed. If a
9939 distribution specified "Class::MOP::Class::Immutable" as a prerequisite,
9940 it could result in Class-MOP-0.36.tar.gz being installed, overwriting
9941 any files from Class-MOP-0.94.tar.gz.
9942
9943 Consumers of metadata B<should> test whether prerequisites would result
9944 in installed module files being "downgraded" to an older version and
9945 B<may> warn users or ignore the prerequisite that would cause such a
9946 result.
9947
9948 =head1 SERIALIZATION
9949
9950 Distribution metadata should be serialized (as a hashref) as
9951 JSON-encoded data and packaged with distributions as the file
9952 F<META.json>.
9953
9954 In the past, the distribution metadata structure had been packed with
9955 distributions as F<META.yml>, a file in the YAML Tiny format (for which,
9956 see L<YAML::Tiny>). Tools that consume distribution metadata from disk
9957 should be capable of loading F<META.yml>, but should prefer F<META.json>
9958 if both are found.
9959
9960 =head1 NOTES FOR IMPLEMENTORS
9961
9962 =head2 Extracting Version Numbers from Perl Modules
9963
9964 To get the version number from a Perl module, consumers should use the
9965 C<< MM->parse_version($file) >> method provided by
9966 L<ExtUtils::MakeMaker> or L<Module::Metadata>. For example, for the
9967 module given by C<$mod>, the version may be retrieved in one of the
9968 following ways:
9969
9970 # via ExtUtils::MakeMaker
9971 my $file = MM->_installed_file_for_module($mod);
9972 my $version = MM->parse_version($file)
9973
9974 The private C<_installed_file_for_module> method may be replaced with
9975 other methods for locating a module in C<@INC>.
9976
9977 # via Module::Metadata
9978 my $info = Module::Metadata->new_from_module($mod);
9979 my $version = $info->version;
9980
9981 If only a filename is available, the following approach may be used:
9982
9983 # via Module::Build
9984 my $info = Module::Metadata->new_from_file($file);
9985 my $version = $info->version;
9986
9987 =head2 Comparing Version Numbers
9988
9989 The L<version> module provides the most reliable way to compare version
9990 numbers in all the various ways they might be provided or might exist
9991 within modules. Given two strings containing version numbers, C<$v1> and
9992 C<$v2>, they should be converted to C<version> objects before using
9993 ordinary comparison operators. For example:
9994
9995 use version;
9996 if ( version->new($v1) <=> version->new($v2) ) {
9997 print "Versions are not equal\n";
9998 }
9999
10000 If the only comparison needed is whether an installed module is of a
10001 sufficiently high version, a direct test may be done using the string
10002 form of C<eval> and the C<use> function. For example, for module C<$mod>
10003 and version prerequisite C<$prereq>:
10004
10005 if ( eval "use $mod $prereq (); 1" ) {
10006 print "Module $mod version is OK.\n";
10007 }
10008
10009 If the values of C<$mod> and C<$prereq> have not been scrubbed, however,
10010 this presents security implications.
10011
10012 =head2 Prerequisites for dynamically configured distributions
10013
10014 When C<dynamic_config> is true, it is an error to presume that the
10015 prerequisites given in distribution metadata will have any relationship
10016 whatsoever to the actual prerequisites of the distribution.
10017
10018 In practice, however, one can generally expect such prerequisites to be
10019 one of two things:
10020
10021 =over 4
10022
10023 =item *
10024
10025 The minimum prerequisites for the distribution, to which dynamic configuration will only add items
10026
10027 =item *
10028
10029 Whatever the distribution configured with on the releaser's machine at release time
10030
10031 =back
10032
10033 The second case often turns out to have identical results to the first case,
10034 albeit only by accident.
10035
10036 As such, consumers may use this data for informational analysis, but
10037 presenting it to the user as canonical or relying on it as such is
10038 invariably the height of folly.
10039
10040 =head2 Indexing distributions a la PAUSE
10041
10042 While no_index tells you what must be ignored when indexing, this spec holds
10043 no opinion on how you should get your initial candidate list of things to
10044 possibly index. For "normal" distributions you might consider simply indexing
10045 the contents of lib/, but there are many fascinating oddities on CPAN and
10046 many dists from the days when it was normal to put the main .pm file in the
10047 root of the distribution archive - so PAUSE currently indexes all .pm and .PL
10048 files that are not either (a) specifically excluded by no_index (b) in
10049 C<inc>, C<xt>, or C<t> directories, or common 'mistake' directories such as
10050 C<perl5>.
10051
10052 Or: If you're trying to be PAUSE-like, make sure you skip C<inc>, C<xt> and
10053 C<t> as well as anything marked as no_index.
10054
10055 Also remember: If the META file contains a provides field, you shouldn't be
10056 indexing anything in the first place - just use that.
10057
10058 =head1 SEE ALSO
10059
10060 =over 4
10061
10062 =item *
10063
10064 CPAN, L<http://www.cpan.org/>
10065
10066 =item *
10067
10068 JSON, L<http://json.org/>
10069
10070 =item *
10071
10072 YAML, L<http://www.yaml.org/>
10073
10074 =item *
10075
10076 L<CPAN>
10077
10078 =item *
10079
10080 L<CPANPLUS>
10081
10082 =item *
10083
10084 L<ExtUtils::MakeMaker>
10085
10086 =item *
10087
10088 L<Module::Build>
10089
10090 =item *
10091
10092 L<Module::Install>
10093
10094 =back
10095
10096 =head1 HISTORY
10097
10098 Ken Williams wrote the original CPAN Meta Spec (also known as the
10099 "META.yml spec") in 2003 and maintained it through several revisions
10100 with input from various members of the community. In 2005, Randy
10101 Sims redrafted it from HTML to POD for the version 1.2 release. Ken
10102 continued to maintain the spec through version 1.4.
10103
10104 In late 2009, David Golden organized the version 2 proposal review
10105 process. David and Ricardo Signes drafted the final version 2 spec
10106 in April 2010 based on the version 1.4 spec and patches contributed
10107 during the proposal process.
10108
10109 =head1 AUTHORS
10110
10111 =over 4
10112
10113 =item *
10114
10115 David Golden <dagolden@cpan.org>
10116
10117 =item *
10118
10119 Ricardo Signes <rjbs@cpan.org>
10120
10121 =back
10122
10123 =head1 COPYRIGHT AND LICENSE
10124
10125 This software is copyright (c) 2010 by David Golden and Ricardo Signes.
10126
10127 This is free software; you can redistribute it and/or modify it under
10128 the same terms as the Perl 5 programming language system itself.
10129
10130 =cut
10131 CPAN_META_SPEC
10132  
10133 $fatpacked{"CPAN/Meta/Validator.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CPAN_META_VALIDATOR';
10134 use 5.006;
10135 use strict;
10136 use warnings;
10137 package CPAN::Meta::Validator;
10138
10139 our $VERSION = '2.150005';
10140
10141 #pod =head1 SYNOPSIS
10142 #pod
10143 #pod my $struct = decode_json_file('META.json');
10144 #pod
10145 #pod my $cmv = CPAN::Meta::Validator->new( $struct );
10146 #pod
10147 #pod unless ( $cmv->is_valid ) {
10148 #pod my $msg = "Invalid META structure. Errors found:\n";
10149 #pod $msg .= join( "\n", $cmv->errors );
10150 #pod die $msg;
10151 #pod }
10152 #pod
10153 #pod =head1 DESCRIPTION
10154 #pod
10155 #pod This module validates a CPAN Meta structure against the version of the
10156 #pod the specification claimed in the C<meta-spec> field of the structure.
10157 #pod
10158 #pod =cut
10159
10160 #--------------------------------------------------------------------------#
10161 # This code copied and adapted from Test::CPAN::Meta
10162 # by Barbie, <barbie@cpan.org> for Miss Barbell Productions,
10163 # L<http://www.missbarbell.co.uk>
10164 #--------------------------------------------------------------------------#
10165
10166 #--------------------------------------------------------------------------#
10167 # Specification Definitions
10168 #--------------------------------------------------------------------------#
10169
10170 my %known_specs = (
10171 '1.4' => 'http://module-build.sourceforge.net/META-spec-v1.4.html',
10172 '1.3' => 'http://module-build.sourceforge.net/META-spec-v1.3.html',
10173 '1.2' => 'http://module-build.sourceforge.net/META-spec-v1.2.html',
10174 '1.1' => 'http://module-build.sourceforge.net/META-spec-v1.1.html',
10175 '1.0' => 'http://module-build.sourceforge.net/META-spec-v1.0.html'
10176 );
10177 my %known_urls = map {$known_specs{$_} => $_} keys %known_specs;
10178
10179 my $module_map1 = { 'map' => { ':key' => { name => \&module, value => \&exversion } } };
10180
10181 my $module_map2 = { 'map' => { ':key' => { name => \&module, value => \&version } } };
10182
10183 my $no_index_2 = {
10184 'map' => { file => { list => { value => \&string } },
10185 directory => { list => { value => \&string } },
10186 'package' => { list => { value => \&string } },
10187 namespace => { list => { value => \&string } },
10188 ':key' => { name => \&custom_2, value => \&anything },
10189 }
10190 };
10191
10192 my $no_index_1_3 = {
10193 'map' => { file => { list => { value => \&string } },
10194 directory => { list => { value => \&string } },
10195 'package' => { list => { value => \&string } },
10196 namespace => { list => { value => \&string } },
10197 ':key' => { name => \&string, value => \&anything },
10198 }
10199 };
10200
10201 my $no_index_1_2 = {
10202 'map' => { file => { list => { value => \&string } },
10203 dir => { list => { value => \&string } },
10204 'package' => { list => { value => \&string } },
10205 namespace => { list => { value => \&string } },
10206 ':key' => { name => \&string, value => \&anything },
10207 }
10208 };
10209
10210 my $no_index_1_1 = {
10211 'map' => { ':key' => { name => \&string, list => { value => \&string } },
10212 }
10213 };
10214
10215 my $prereq_map = {
10216 map => {
10217 ':key' => {
10218 name => \&phase,
10219 'map' => {
10220 ':key' => {
10221 name => \&relation,
10222 %$module_map1,
10223 },
10224 },
10225 }
10226 },
10227 };
10228
10229 my %definitions = (
10230 '2' => {
10231 # REQUIRED
10232 'abstract' => { mandatory => 1, value => \&string },
10233 'author' => { mandatory => 1, list => { value => \&string } },
10234 'dynamic_config' => { mandatory => 1, value => \&boolean },
10235 'generated_by' => { mandatory => 1, value => \&string },
10236 'license' => { mandatory => 1, list => { value => \&license } },
10237 'meta-spec' => {
10238 mandatory => 1,
10239 'map' => {
10240 version => { mandatory => 1, value => \&version},
10241 url => { value => \&url },
10242 ':key' => { name => \&custom_2, value => \&anything },
10243 }
10244 },
10245 'name' => { mandatory => 1, value => \&string },
10246 'release_status' => { mandatory => 1, value => \&release_status },
10247 'version' => { mandatory => 1, value => \&version },
10248
10249 # OPTIONAL
10250 'description' => { value => \&string },
10251 'keywords' => { list => { value => \&string } },
10252 'no_index' => $no_index_2,
10253 'optional_features' => {
10254 'map' => {
10255 ':key' => {
10256 name => \&string,
10257 'map' => {
10258 description => { value => \&string },
10259 prereqs => $prereq_map,
10260 ':key' => { name => \&custom_2, value => \&anything },
10261 }
10262 }
10263 }
10264 },
10265 'prereqs' => $prereq_map,
10266 'provides' => {
10267 'map' => {
10268 ':key' => {
10269 name => \&module,
10270 'map' => {
10271 file => { mandatory => 1, value => \&file },
10272 version => { value => \&version },
10273 ':key' => { name => \&custom_2, value => \&anything },
10274 }
10275 }
10276 }
10277 },
10278 'resources' => {
10279 'map' => {
10280 license => { list => { value => \&url } },
10281 homepage => { value => \&url },
10282 bugtracker => {
10283 'map' => {
10284 web => { value => \&url },
10285 mailto => { value => \&string},
10286 ':key' => { name => \&custom_2, value => \&anything },
10287 }
10288 },
10289 repository => {
10290 'map' => {
10291 web => { value => \&url },
10292 url => { value => \&url },
10293 type => { value => \&string },
10294 ':key' => { name => \&custom_2, value => \&anything },
10295 }
10296 },
10297 ':key' => { value => \&string, name => \&custom_2 },
10298 }
10299 },
10300
10301 # CUSTOM -- additional user defined key/value pairs
10302 # note we can only validate the key name, as the structure is user defined
10303 ':key' => { name => \&custom_2, value => \&anything },
10304 },
10305
10306 '1.4' => {
10307 'meta-spec' => {
10308 mandatory => 1,
10309 'map' => {
10310 version => { mandatory => 1, value => \&version},
10311 url => { mandatory => 1, value => \&urlspec },
10312 ':key' => { name => \&string, value => \&anything },
10313 },
10314 },
10315
10316 'name' => { mandatory => 1, value => \&string },
10317 'version' => { mandatory => 1, value => \&version },
10318 'abstract' => { mandatory => 1, value => \&string },
10319 'author' => { mandatory => 1, list => { value => \&string } },
10320 'license' => { mandatory => 1, value => \&license },
10321 'generated_by' => { mandatory => 1, value => \&string },
10322
10323 'distribution_type' => { value => \&string },
10324 'dynamic_config' => { value => \&boolean },
10325
10326 'requires' => $module_map1,
10327 'recommends' => $module_map1,
10328 'build_requires' => $module_map1,
10329 'configure_requires' => $module_map1,
10330 'conflicts' => $module_map2,
10331
10332 'optional_features' => {
10333 'map' => {
10334 ':key' => { name => \&string,
10335 'map' => { description => { value => \&string },
10336 requires => $module_map1,
10337 recommends => $module_map1,
10338 build_requires => $module_map1,
10339 conflicts => $module_map2,
10340 ':key' => { name => \&string, value => \&anything },
10341 }
10342 }
10343 }
10344 },
10345
10346 'provides' => {
10347 'map' => {
10348 ':key' => { name => \&module,
10349 'map' => {
10350 file => { mandatory => 1, value => \&file },
10351 version => { value => \&version },
10352 ':key' => { name => \&string, value => \&anything },
10353 }
10354 }
10355 }
10356 },
10357
10358 'no_index' => $no_index_1_3,
10359 'private' => $no_index_1_3,
10360
10361 'keywords' => { list => { value => \&string } },
10362
10363 'resources' => {
10364 'map' => { license => { value => \&url },
10365 homepage => { value => \&url },
10366 bugtracker => { value => \&url },
10367 repository => { value => \&url },
10368 ':key' => { value => \&string, name => \&custom_1 },
10369 }
10370 },
10371
10372 # additional user defined key/value pairs
10373 # note we can only validate the key name, as the structure is user defined
10374 ':key' => { name => \&string, value => \&anything },
10375 },
10376
10377 '1.3' => {
10378 'meta-spec' => {
10379 mandatory => 1,
10380 'map' => {
10381 version => { mandatory => 1, value => \&version},
10382 url => { mandatory => 1, value => \&urlspec },
10383 ':key' => { name => \&string, value => \&anything },
10384 },
10385 },
10386
10387 'name' => { mandatory => 1, value => \&string },
10388 'version' => { mandatory => 1, value => \&version },
10389 'abstract' => { mandatory => 1, value => \&string },
10390 'author' => { mandatory => 1, list => { value => \&string } },
10391 'license' => { mandatory => 1, value => \&license },
10392 'generated_by' => { mandatory => 1, value => \&string },
10393
10394 'distribution_type' => { value => \&string },
10395 'dynamic_config' => { value => \&boolean },
10396
10397 'requires' => $module_map1,
10398 'recommends' => $module_map1,
10399 'build_requires' => $module_map1,
10400 'conflicts' => $module_map2,
10401
10402 'optional_features' => {
10403 'map' => {
10404 ':key' => { name => \&string,
10405 'map' => { description => { value => \&string },
10406 requires => $module_map1,
10407 recommends => $module_map1,
10408 build_requires => $module_map1,
10409 conflicts => $module_map2,
10410 ':key' => { name => \&string, value => \&anything },
10411 }
10412 }
10413 }
10414 },
10415
10416 'provides' => {
10417 'map' => {
10418 ':key' => { name => \&module,
10419 'map' => {
10420 file => { mandatory => 1, value => \&file },
10421 version => { value => \&version },
10422 ':key' => { name => \&string, value => \&anything },
10423 }
10424 }
10425 }
10426 },
10427
10428
10429 'no_index' => $no_index_1_3,
10430 'private' => $no_index_1_3,
10431
10432 'keywords' => { list => { value => \&string } },
10433
10434 'resources' => {
10435 'map' => { license => { value => \&url },
10436 homepage => { value => \&url },
10437 bugtracker => { value => \&url },
10438 repository => { value => \&url },
10439 ':key' => { value => \&string, name => \&custom_1 },
10440 }
10441 },
10442
10443 # additional user defined key/value pairs
10444 # note we can only validate the key name, as the structure is user defined
10445 ':key' => { name => \&string, value => \&anything },
10446 },
10447
10448 # v1.2 is misleading, it seems to assume that a number of fields where created
10449 # within v1.1, when they were created within v1.2. This may have been an
10450 # original mistake, and that a v1.1 was retro fitted into the timeline, when
10451 # v1.2 was originally slated as v1.1. But I could be wrong ;)
10452 '1.2' => {
10453 'meta-spec' => {
10454 mandatory => 1,
10455 'map' => {
10456 version => { mandatory => 1, value => \&version},
10457 url => { mandatory => 1, value => \&urlspec },
10458 ':key' => { name => \&string, value => \&anything },
10459 },
10460 },
10461
10462
10463 'name' => { mandatory => 1, value => \&string },
10464 'version' => { mandatory => 1, value => \&version },
10465 'license' => { mandatory => 1, value => \&license },
10466 'generated_by' => { mandatory => 1, value => \&string },
10467 'author' => { mandatory => 1, list => { value => \&string } },
10468 'abstract' => { mandatory => 1, value => \&string },
10469
10470 'distribution_type' => { value => \&string },
10471 'dynamic_config' => { value => \&boolean },
10472
10473 'keywords' => { list => { value => \&string } },
10474
10475 'private' => $no_index_1_2,
10476 '$no_index' => $no_index_1_2,
10477
10478 'requires' => $module_map1,
10479 'recommends' => $module_map1,
10480 'build_requires' => $module_map1,
10481 'conflicts' => $module_map2,
10482
10483 'optional_features' => {
10484 'map' => {
10485 ':key' => { name => \&string,
10486 'map' => { description => { value => \&string },
10487 requires => $module_map1,
10488 recommends => $module_map1,
10489 build_requires => $module_map1,
10490 conflicts => $module_map2,
10491 ':key' => { name => \&string, value => \&anything },
10492 }
10493 }
10494 }
10495 },
10496
10497 'provides' => {
10498 'map' => {
10499 ':key' => { name => \&module,
10500 'map' => {
10501 file => { mandatory => 1, value => \&file },
10502 version => { value => \&version },
10503 ':key' => { name => \&string, value => \&anything },
10504 }
10505 }
10506 }
10507 },
10508
10509 'resources' => {
10510 'map' => { license => { value => \&url },
10511 homepage => { value => \&url },
10512 bugtracker => { value => \&url },
10513 repository => { value => \&url },
10514 ':key' => { value => \&string, name => \&custom_1 },
10515 }
10516 },
10517
10518 # additional user defined key/value pairs
10519 # note we can only validate the key name, as the structure is user defined
10520 ':key' => { name => \&string, value => \&anything },
10521 },
10522
10523 # note that the 1.1 spec only specifies 'version' as mandatory
10524 '1.1' => {
10525 'name' => { value => \&string },
10526 'version' => { mandatory => 1, value => \&version },
10527 'license' => { value => \&license },
10528 'generated_by' => { value => \&string },
10529
10530 'license_uri' => { value => \&url },
10531 'distribution_type' => { value => \&string },
10532 'dynamic_config' => { value => \&boolean },
10533
10534 'private' => $no_index_1_1,
10535
10536 'requires' => $module_map1,
10537 'recommends' => $module_map1,
10538 'build_requires' => $module_map1,
10539 'conflicts' => $module_map2,
10540
10541 # additional user defined key/value pairs
10542 # note we can only validate the key name, as the structure is user defined
10543 ':key' => { name => \&string, value => \&anything },
10544 },
10545
10546 # note that the 1.0 spec doesn't specify optional or mandatory fields
10547 # but we will treat version as mandatory since otherwise META 1.0 is
10548 # completely arbitrary and pointless
10549 '1.0' => {
10550 'name' => { value => \&string },
10551 'version' => { mandatory => 1, value => \&version },
10552 'license' => { value => \&license },
10553 'generated_by' => { value => \&string },
10554
10555 'license_uri' => { value => \&url },
10556 'distribution_type' => { value => \&string },
10557 'dynamic_config' => { value => \&boolean },
10558
10559 'requires' => $module_map1,
10560 'recommends' => $module_map1,
10561 'build_requires' => $module_map1,
10562 'conflicts' => $module_map2,
10563
10564 # additional user defined key/value pairs
10565 # note we can only validate the key name, as the structure is user defined
10566 ':key' => { name => \&string, value => \&anything },
10567 },
10568 );
10569
10570 #--------------------------------------------------------------------------#
10571 # Code
10572 #--------------------------------------------------------------------------#
10573
10574 #pod =method new
10575 #pod
10576 #pod my $cmv = CPAN::Meta::Validator->new( $struct )
10577 #pod
10578 #pod The constructor must be passed a metadata structure.
10579 #pod
10580 #pod =cut
10581
10582 sub new {
10583 my ($class,$data) = @_;
10584
10585 # create an attributes hash
10586 my $self = {
10587 'data' => $data,
10588 'spec' => eval { $data->{'meta-spec'}{'version'} } || "1.0",
10589 'errors' => undef,
10590 };
10591
10592 # create the object
10593 return bless $self, $class;
10594 }
10595
10596 #pod =method is_valid
10597 #pod
10598 #pod if ( $cmv->is_valid ) {
10599 #pod ...
10600 #pod }
10601 #pod
10602 #pod Returns a boolean value indicating whether the metadata provided
10603 #pod is valid.
10604 #pod
10605 #pod =cut
10606
10607 sub is_valid {
10608 my $self = shift;
10609 my $data = $self->{data};
10610 my $spec_version = $self->{spec};
10611 $self->check_map($definitions{$spec_version},$data);
10612 return ! $self->errors;
10613 }
10614
10615 #pod =method errors
10616 #pod
10617 #pod warn( join "\n", $cmv->errors );
10618 #pod
10619 #pod Returns a list of errors seen during validation.
10620 #pod
10621 #pod =cut
10622
10623 sub errors {
10624 my $self = shift;
10625 return () unless(defined $self->{errors});
10626 return @{$self->{errors}};
10627 }
10628
10629 #pod =begin :internals
10630 #pod
10631 #pod =head2 Check Methods
10632 #pod
10633 #pod =over
10634 #pod
10635 #pod =item *
10636 #pod
10637 #pod check_map($spec,$data)
10638 #pod
10639 #pod Checks whether a map (or hash) part of the data structure conforms to the
10640 #pod appropriate specification definition.
10641 #pod
10642 #pod =item *
10643 #pod
10644 #pod check_list($spec,$data)
10645 #pod
10646 #pod Checks whether a list (or array) part of the data structure conforms to
10647 #pod the appropriate specification definition.
10648 #pod
10649 #pod =item *
10650 #pod
10651 #pod =back
10652 #pod
10653 #pod =cut
10654
10655 my $spec_error = "Missing validation action in specification. "
10656 . "Must be one of 'map', 'list', or 'value'";
10657
10658 sub check_map {
10659 my ($self,$spec,$data) = @_;
10660
10661 if(ref($spec) ne 'HASH') {
10662 $self->_error( "Unknown META specification, cannot validate." );
10663 return;
10664 }
10665
10666 if(ref($data) ne 'HASH') {
10667 $self->_error( "Expected a map structure from string or file." );
10668 return;
10669 }
10670
10671 for my $key (keys %$spec) {
10672 next unless($spec->{$key}->{mandatory});
10673 next if(defined $data->{$key});
10674 push @{$self->{stack}}, $key;
10675 $self->_error( "Missing mandatory field, '$key'" );
10676 pop @{$self->{stack}};
10677 }
10678
10679 for my $key (keys %$data) {
10680 push @{$self->{stack}}, $key;
10681 if($spec->{$key}) {
10682 if($spec->{$key}{value}) {
10683 $spec->{$key}{value}->($self,$key,$data->{$key});
10684 } elsif($spec->{$key}{'map'}) {
10685 $self->check_map($spec->{$key}{'map'},$data->{$key});
10686 } elsif($spec->{$key}{'list'}) {
10687 $self->check_list($spec->{$key}{'list'},$data->{$key});
10688 } else {
10689 $self->_error( "$spec_error for '$key'" );
10690 }
10691
10692 } elsif ($spec->{':key'}) {
10693 $spec->{':key'}{name}->($self,$key,$key);
10694 if($spec->{':key'}{value}) {
10695 $spec->{':key'}{value}->($self,$key,$data->{$key});
10696 } elsif($spec->{':key'}{'map'}) {
10697 $self->check_map($spec->{':key'}{'map'},$data->{$key});
10698 } elsif($spec->{':key'}{'list'}) {
10699 $self->check_list($spec->{':key'}{'list'},$data->{$key});
10700 } else {
10701 $self->_error( "$spec_error for ':key'" );
10702 }
10703
10704
10705 } else {
10706 $self->_error( "Unknown key, '$key', found in map structure" );
10707 }
10708 pop @{$self->{stack}};
10709 }
10710 }
10711
10712 sub check_list {
10713 my ($self,$spec,$data) = @_;
10714
10715 if(ref($data) ne 'ARRAY') {
10716 $self->_error( "Expected a list structure" );
10717 return;
10718 }
10719
10720 if(defined $spec->{mandatory}) {
10721 if(!defined $data->[0]) {
10722 $self->_error( "Missing entries from mandatory list" );
10723 }
10724 }
10725
10726 for my $value (@$data) {
10727 push @{$self->{stack}}, $value || "<undef>";
10728 if(defined $spec->{value}) {
10729 $spec->{value}->($self,'list',$value);
10730 } elsif(defined $spec->{'map'}) {
10731 $self->check_map($spec->{'map'},$value);
10732 } elsif(defined $spec->{'list'}) {
10733 $self->check_list($spec->{'list'},$value);
10734 } elsif ($spec->{':key'}) {
10735 $self->check_map($spec,$value);
10736 } else {
10737 $self->_error( "$spec_error associated with '$self->{stack}[-2]'" );
10738 }
10739 pop @{$self->{stack}};
10740 }
10741 }
10742
10743 #pod =head2 Validator Methods
10744 #pod
10745 #pod =over
10746 #pod
10747 #pod =item *
10748 #pod
10749 #pod header($self,$key,$value)
10750 #pod
10751 #pod Validates that the header is valid.
10752 #pod
10753 #pod Note: No longer used as we now read the data structure, not the file.
10754 #pod
10755 #pod =item *
10756 #pod
10757 #pod url($self,$key,$value)
10758 #pod
10759 #pod Validates that a given value is in an acceptable URL format
10760 #pod
10761 #pod =item *
10762 #pod
10763 #pod urlspec($self,$key,$value)
10764 #pod
10765 #pod Validates that the URL to a META specification is a known one.
10766 #pod
10767 #pod =item *
10768 #pod
10769 #pod string_or_undef($self,$key,$value)
10770 #pod
10771 #pod Validates that the value is either a string or an undef value. Bit of a
10772 #pod catchall function for parts of the data structure that are completely user
10773 #pod defined.
10774 #pod
10775 #pod =item *
10776 #pod
10777 #pod string($self,$key,$value)
10778 #pod
10779 #pod Validates that a string exists for the given key.
10780 #pod
10781 #pod =item *
10782 #pod
10783 #pod file($self,$key,$value)
10784 #pod
10785 #pod Validate that a file is passed for the given key. This may be made more
10786 #pod thorough in the future. For now it acts like \&string.
10787 #pod
10788 #pod =item *
10789 #pod
10790 #pod exversion($self,$key,$value)
10791 #pod
10792 #pod Validates a list of versions, e.g. '<= 5, >=2, ==3, !=4, >1, <6, 0'.
10793 #pod
10794 #pod =item *
10795 #pod
10796 #pod version($self,$key,$value)
10797 #pod
10798 #pod Validates a single version string. Versions of the type '5.8.8' and '0.00_00'
10799 #pod are both valid. A leading 'v' like 'v1.2.3' is also valid.
10800 #pod
10801 #pod =item *
10802 #pod
10803 #pod boolean($self,$key,$value)
10804 #pod
10805 #pod Validates for a boolean value. Currently these values are '1', '0', 'true',
10806 #pod 'false', however the latter 2 may be removed.
10807 #pod
10808 #pod =item *
10809 #pod
10810 #pod license($self,$key,$value)
10811 #pod
10812 #pod Validates that a value is given for the license. Returns 1 if an known license
10813 #pod type, or 2 if a value is given but the license type is not a recommended one.
10814 #pod
10815 #pod =item *
10816 #pod
10817 #pod custom_1($self,$key,$value)
10818 #pod
10819 #pod Validates that the given key is in CamelCase, to indicate a user defined
10820 #pod keyword and only has characters in the class [-_a-zA-Z]. In version 1.X
10821 #pod of the spec, this was only explicitly stated for 'resources'.
10822 #pod
10823 #pod =item *
10824 #pod
10825 #pod custom_2($self,$key,$value)
10826 #pod
10827 #pod Validates that the given key begins with 'x_' or 'X_', to indicate a user
10828 #pod defined keyword and only has characters in the class [-_a-zA-Z]
10829 #pod
10830 #pod =item *
10831 #pod
10832 #pod identifier($self,$key,$value)
10833 #pod
10834 #pod Validates that key is in an acceptable format for the META specification,
10835 #pod for an identifier, i.e. any that matches the regular expression
10836 #pod qr/[a-z][a-z_]/i.
10837 #pod
10838 #pod =item *
10839 #pod
10840 #pod module($self,$key,$value)
10841 #pod
10842 #pod Validates that a given key is in an acceptable module name format, e.g.
10843 #pod 'Test::CPAN::Meta::Version'.
10844 #pod
10845 #pod =back
10846 #pod
10847 #pod =end :internals
10848 #pod
10849 #pod =cut
10850
10851 sub header {
10852 my ($self,$key,$value) = @_;
10853 if(defined $value) {
10854 return 1 if($value && $value =~ /^--- #YAML:1.0/);
10855 }
10856 $self->_error( "file does not have a valid YAML header." );
10857 return 0;
10858 }
10859
10860 sub release_status {
10861 my ($self,$key,$value) = @_;
10862 if(defined $value) {
10863 my $version = $self->{data}{version} || '';
10864 if ( $version =~ /_/ ) {
10865 return 1 if ( $value =~ /\A(?:testing|unstable)\z/ );
10866 $self->_error( "'$value' for '$key' is invalid for version '$version'" );
10867 }
10868 else {
10869 return 1 if ( $value =~ /\A(?:stable|testing|unstable)\z/ );
10870 $self->_error( "'$value' for '$key' is invalid" );
10871 }
10872 }
10873 else {
10874 $self->_error( "'$key' is not defined" );
10875 }
10876 return 0;
10877 }
10878
10879 # _uri_split taken from URI::Split by Gisle Aas, Copyright 2003
10880 sub _uri_split {
10881 return $_[0] =~ m,(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?,;
10882 }
10883
10884 sub url {
10885 my ($self,$key,$value) = @_;
10886 if(defined $value) {
10887 my ($scheme, $auth, $path, $query, $frag) = _uri_split($value);
10888 unless ( defined $scheme && length $scheme ) {
10889 $self->_error( "'$value' for '$key' does not have a URL scheme" );
10890 return 0;
10891 }
10892 unless ( defined $auth && length $auth ) {
10893 $self->_error( "'$value' for '$key' does not have a URL authority" );
10894 return 0;
10895 }
10896 return 1;
10897 }
10898 $value ||= '';
10899 $self->_error( "'$value' for '$key' is not a valid URL." );
10900 return 0;
10901 }
10902
10903 sub urlspec {
10904 my ($self,$key,$value) = @_;
10905 if(defined $value) {
10906 return 1 if($value && $known_specs{$self->{spec}} eq $value);
10907 if($value && $known_urls{$value}) {
10908 $self->_error( 'META specification URL does not match version' );
10909 return 0;
10910 }
10911 }
10912 $self->_error( 'Unknown META specification' );
10913 return 0;
10914 }
10915
10916 sub anything { return 1 }
10917
10918 sub string {
10919 my ($self,$key,$value) = @_;
10920 if(defined $value) {
10921 return 1 if($value || $value =~ /^0$/);
10922 }
10923 $self->_error( "value is an undefined string" );
10924 return 0;
10925 }
10926
10927 sub string_or_undef {
10928 my ($self,$key,$value) = @_;
10929 return 1 unless(defined $value);
10930 return 1 if($value || $value =~ /^0$/);
10931 $self->_error( "No string defined for '$key'" );
10932 return 0;
10933 }
10934
10935 sub file {
10936 my ($self,$key,$value) = @_;
10937 return 1 if(defined $value);
10938 $self->_error( "No file defined for '$key'" );
10939 return 0;
10940 }
10941
10942 sub exversion {
10943 my ($self,$key,$value) = @_;
10944 if(defined $value && ($value || $value =~ /0/)) {
10945 my $pass = 1;
10946 for(split(",",$value)) { $self->version($key,$_) or ($pass = 0); }
10947 return $pass;
10948 }
10949 $value = '<undef>' unless(defined $value);
10950 $self->_error( "'$value' for '$key' is not a valid version." );
10951 return 0;
10952 }
10953
10954 sub version {
10955 my ($self,$key,$value) = @_;
10956 if(defined $value) {
10957 return 0 unless($value || $value =~ /0/);
10958 return 1 if($value =~ /^\s*((<|<=|>=|>|!=|==)\s*)?v?\d+((\.\d+((_|\.)\d+)?)?)/);
10959 } else {
10960 $value = '<undef>';
10961 }
10962 $self->_error( "'$value' for '$key' is not a valid version." );
10963 return 0;
10964 }
10965
10966 sub boolean {
10967 my ($self,$key,$value) = @_;
10968 if(defined $value) {
10969 return 1 if($value =~ /^(0|1|true|false)$/);
10970 } else {
10971 $value = '<undef>';
10972 }
10973 $self->_error( "'$value' for '$key' is not a boolean value." );
10974 return 0;
10975 }
10976
10977 my %v1_licenses = (
10978 'perl' => 'http://dev.perl.org/licenses/',
10979 'gpl' => 'http://www.opensource.org/licenses/gpl-license.php',
10980 'apache' => 'http://apache.org/licenses/LICENSE-2.0',
10981 'artistic' => 'http://opensource.org/licenses/artistic-license.php',
10982 'artistic_2' => 'http://opensource.org/licenses/artistic-license-2.0.php',
10983 'lgpl' => 'http://www.opensource.org/licenses/lgpl-license.php',
10984 'bsd' => 'http://www.opensource.org/licenses/bsd-license.php',
10985 'gpl' => 'http://www.opensource.org/licenses/gpl-license.php',
10986 'mit' => 'http://opensource.org/licenses/mit-license.php',
10987 'mozilla' => 'http://opensource.org/licenses/mozilla1.1.php',
10988 'open_source' => undef,
10989 'unrestricted' => undef,
10990 'restrictive' => undef,
10991 'unknown' => undef,
10992 );
10993
10994 my %v2_licenses = map { $_ => 1 } qw(
10995 agpl_3
10996 apache_1_1
10997 apache_2_0
10998 artistic_1
10999 artistic_2
11000 bsd
11001 freebsd
11002 gfdl_1_2
11003 gfdl_1_3
11004 gpl_1
11005 gpl_2
11006 gpl_3
11007 lgpl_2_1
11008 lgpl_3_0
11009 mit
11010 mozilla_1_0
11011 mozilla_1_1
11012 openssl
11013 perl_5
11014 qpl_1_0
11015 ssleay
11016 sun
11017 zlib
11018 open_source
11019 restricted
11020 unrestricted
11021 unknown
11022 );
11023
11024 sub license {
11025 my ($self,$key,$value) = @_;
11026 my $licenses = $self->{spec} < 2 ? \%v1_licenses : \%v2_licenses;
11027 if(defined $value) {
11028 return 1 if($value && exists $licenses->{$value});
11029 } else {
11030 $value = '<undef>';
11031 }
11032 $self->_error( "License '$value' is invalid" );
11033 return 0;
11034 }
11035
11036 sub custom_1 {
11037 my ($self,$key) = @_;
11038 if(defined $key) {
11039 # a valid user defined key should be alphabetic
11040 # and contain at least one capital case letter.
11041 return 1 if($key && $key =~ /^[_a-z]+$/i && $key =~ /[A-Z]/);
11042 } else {
11043 $key = '<undef>';
11044 }
11045 $self->_error( "Custom resource '$key' must be in CamelCase." );
11046 return 0;
11047 }
11048
11049 sub custom_2 {
11050 my ($self,$key) = @_;
11051 if(defined $key) {
11052 return 1 if($key && $key =~ /^x_/i); # user defined
11053 } else {
11054 $key = '<undef>';
11055 }
11056 $self->_error( "Custom key '$key' must begin with 'x_' or 'X_'." );
11057 return 0;
11058 }
11059
11060 sub identifier {
11061 my ($self,$key) = @_;
11062 if(defined $key) {
11063 return 1 if($key && $key =~ /^([a-z][_a-z]+)$/i); # spec 2.0 defined
11064 } else {
11065 $key = '<undef>';
11066 }
11067 $self->_error( "Key '$key' is not a legal identifier." );
11068 return 0;
11069 }
11070
11071 sub module {
11072 my ($self,$key) = @_;
11073 if(defined $key) {
11074 return 1 if($key && $key =~ /^[A-Za-z0-9_]+(::[A-Za-z0-9_]+)*$/);
11075 } else {
11076 $key = '<undef>';
11077 }
11078 $self->_error( "Key '$key' is not a legal module name." );
11079 return 0;
11080 }
11081
11082 my @valid_phases = qw/ configure build test runtime develop /;
11083 sub phase {
11084 my ($self,$key) = @_;
11085 if(defined $key) {
11086 return 1 if( length $key && grep { $key eq $_ } @valid_phases );
11087 return 1 if $key =~ /x_/i;
11088 } else {
11089 $key = '<undef>';
11090 }
11091 $self->_error( "Key '$key' is not a legal phase." );
11092 return 0;
11093 }
11094
11095 my @valid_relations = qw/ requires recommends suggests conflicts /;
11096 sub relation {
11097 my ($self,$key) = @_;
11098 if(defined $key) {
11099 return 1 if( length $key && grep { $key eq $_ } @valid_relations );
11100 return 1 if $key =~ /x_/i;
11101 } else {
11102 $key = '<undef>';
11103 }
11104 $self->_error( "Key '$key' is not a legal prereq relationship." );
11105 return 0;
11106 }
11107
11108 sub _error {
11109 my $self = shift;
11110 my $mess = shift;
11111
11112 $mess .= ' ('.join(' -> ',@{$self->{stack}}).')' if($self->{stack});
11113 $mess .= " [Validation: $self->{spec}]";
11114
11115 push @{$self->{errors}}, $mess;
11116 }
11117
11118 1;
11119
11120 # ABSTRACT: validate CPAN distribution metadata structures
11121
11122 =pod
11123
11124 =encoding UTF-8
11125
11126 =head1 NAME
11127
11128 CPAN::Meta::Validator - validate CPAN distribution metadata structures
11129
11130 =head1 VERSION
11131
11132 version 2.150005
11133
11134 =head1 SYNOPSIS
11135
11136 my $struct = decode_json_file('META.json');
11137
11138 my $cmv = CPAN::Meta::Validator->new( $struct );
11139
11140 unless ( $cmv->is_valid ) {
11141 my $msg = "Invalid META structure. Errors found:\n";
11142 $msg .= join( "\n", $cmv->errors );
11143 die $msg;
11144 }
11145
11146 =head1 DESCRIPTION
11147
11148 This module validates a CPAN Meta structure against the version of the
11149 the specification claimed in the C<meta-spec> field of the structure.
11150
11151 =head1 METHODS
11152
11153 =head2 new
11154
11155 my $cmv = CPAN::Meta::Validator->new( $struct )
11156
11157 The constructor must be passed a metadata structure.
11158
11159 =head2 is_valid
11160
11161 if ( $cmv->is_valid ) {
11162 ...
11163 }
11164
11165 Returns a boolean value indicating whether the metadata provided
11166 is valid.
11167
11168 =head2 errors
11169
11170 warn( join "\n", $cmv->errors );
11171
11172 Returns a list of errors seen during validation.
11173
11174 =begin :internals
11175
11176 =head2 Check Methods
11177
11178 =over
11179
11180 =item *
11181
11182 check_map($spec,$data)
11183
11184 Checks whether a map (or hash) part of the data structure conforms to the
11185 appropriate specification definition.
11186
11187 =item *
11188
11189 check_list($spec,$data)
11190
11191 Checks whether a list (or array) part of the data structure conforms to
11192 the appropriate specification definition.
11193
11194 =item *
11195
11196 =back
11197
11198 =head2 Validator Methods
11199
11200 =over
11201
11202 =item *
11203
11204 header($self,$key,$value)
11205
11206 Validates that the header is valid.
11207
11208 Note: No longer used as we now read the data structure, not the file.
11209
11210 =item *
11211
11212 url($self,$key,$value)
11213
11214 Validates that a given value is in an acceptable URL format
11215
11216 =item *
11217
11218 urlspec($self,$key,$value)
11219
11220 Validates that the URL to a META specification is a known one.
11221
11222 =item *
11223
11224 string_or_undef($self,$key,$value)
11225
11226 Validates that the value is either a string or an undef value. Bit of a
11227 catchall function for parts of the data structure that are completely user
11228 defined.
11229
11230 =item *
11231
11232 string($self,$key,$value)
11233
11234 Validates that a string exists for the given key.
11235
11236 =item *
11237
11238 file($self,$key,$value)
11239
11240 Validate that a file is passed for the given key. This may be made more
11241 thorough in the future. For now it acts like \&string.
11242
11243 =item *
11244
11245 exversion($self,$key,$value)
11246
11247 Validates a list of versions, e.g. '<= 5, >=2, ==3, !=4, >1, <6, 0'.
11248
11249 =item *
11250
11251 version($self,$key,$value)
11252
11253 Validates a single version string. Versions of the type '5.8.8' and '0.00_00'
11254 are both valid. A leading 'v' like 'v1.2.3' is also valid.
11255
11256 =item *
11257
11258 boolean($self,$key,$value)
11259
11260 Validates for a boolean value. Currently these values are '1', '0', 'true',
11261 'false', however the latter 2 may be removed.
11262
11263 =item *
11264
11265 license($self,$key,$value)
11266
11267 Validates that a value is given for the license. Returns 1 if an known license
11268 type, or 2 if a value is given but the license type is not a recommended one.
11269
11270 =item *
11271
11272 custom_1($self,$key,$value)
11273
11274 Validates that the given key is in CamelCase, to indicate a user defined
11275 keyword and only has characters in the class [-_a-zA-Z]. In version 1.X
11276 of the spec, this was only explicitly stated for 'resources'.
11277
11278 =item *
11279
11280 custom_2($self,$key,$value)
11281
11282 Validates that the given key begins with 'x_' or 'X_', to indicate a user
11283 defined keyword and only has characters in the class [-_a-zA-Z]
11284
11285 =item *
11286
11287 identifier($self,$key,$value)
11288
11289 Validates that key is in an acceptable format for the META specification,
11290 for an identifier, i.e. any that matches the regular expression
11291 qr/[a-z][a-z_]/i.
11292
11293 =item *
11294
11295 module($self,$key,$value)
11296
11297 Validates that a given key is in an acceptable module name format, e.g.
11298 'Test::CPAN::Meta::Version'.
11299
11300 =back
11301
11302 =end :internals
11303
11304 =for Pod::Coverage anything boolean check_list custom_1 custom_2 exversion file
11305 identifier license module phase relation release_status string string_or_undef
11306 url urlspec version header check_map
11307
11308 =head1 BUGS
11309
11310 Please report any bugs or feature using the CPAN Request Tracker.
11311 Bugs can be submitted through the web interface at
11312 L<http://rt.cpan.org/Dist/Display.html?Queue=CPAN-Meta>
11313
11314 When submitting a bug or request, please include a test-file or a patch to an
11315 existing test-file that illustrates the bug or desired feature.
11316
11317 =head1 AUTHORS
11318
11319 =over 4
11320
11321 =item *
11322
11323 David Golden <dagolden@cpan.org>
11324
11325 =item *
11326
11327 Ricardo Signes <rjbs@cpan.org>
11328
11329 =back
11330
11331 =head1 COPYRIGHT AND LICENSE
11332
11333 This software is copyright (c) 2010 by David Golden and Ricardo Signes.
11334
11335 This is free software; you can redistribute it and/or modify it under
11336 the same terms as the Perl 5 programming language system itself.
11337
11338 =cut
11339
11340 __END__
11341
11342
11343 # vim: ts=2 sts=2 sw=2 et :
11344 CPAN_META_VALIDATOR
11345  
11346 $fatpacked{"CPAN/Meta/YAML.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CPAN_META_YAML';
11347 use 5.008001; # sane UTF-8 support
11348 use strict;
11349 use warnings;
11350 package CPAN::Meta::YAML; # git description: v1.66-5-ge09e1ae
11351 # XXX-INGY is 5.8.1 too old/broken for utf8?
11352 # XXX-XDG Lancaster consensus was that it was sufficient until
11353 # proven otherwise
11354 $CPAN::Meta::YAML::VERSION = '0.016';
11355 ; # original $VERSION removed by Doppelgaenger
11356
11357 #####################################################################
11358 # The CPAN::Meta::YAML API.
11359 #
11360 # These are the currently documented API functions/methods and
11361 # exports:
11362
11363 use Exporter;
11364 our @ISA = qw{ Exporter };
11365 our @EXPORT = qw{ Load Dump };
11366 our @EXPORT_OK = qw{ LoadFile DumpFile freeze thaw };
11367
11368 ###
11369 # Functional/Export API:
11370
11371 sub Dump {
11372 return CPAN::Meta::YAML->new(@_)->_dump_string;
11373 }
11374
11375 # XXX-INGY Returning last document seems a bad behavior.
11376 # XXX-XDG I think first would seem more natural, but I don't know
11377 # that it's worth changing now
11378 sub Load {
11379 my $self = CPAN::Meta::YAML->_load_string(@_);
11380 if ( wantarray ) {
11381 return @$self;
11382 } else {
11383 # To match YAML.pm, return the last document
11384 return $self->[-1];
11385 }
11386 }
11387
11388 # XXX-INGY Do we really need freeze and thaw?
11389 # XXX-XDG I don't think so. I'd support deprecating them.
11390 BEGIN {
11391 *freeze = \&Dump;
11392 *thaw = \&Load;
11393 }
11394
11395 sub DumpFile {
11396 my $file = shift;
11397 return CPAN::Meta::YAML->new(@_)->_dump_file($file);
11398 }
11399
11400 sub LoadFile {
11401 my $file = shift;
11402 my $self = CPAN::Meta::YAML->_load_file($file);
11403 if ( wantarray ) {
11404 return @$self;
11405 } else {
11406 # Return only the last document to match YAML.pm,
11407 return $self->[-1];
11408 }
11409 }
11410
11411
11412 ###
11413 # Object Oriented API:
11414
11415 # Create an empty CPAN::Meta::YAML object
11416 # XXX-INGY Why do we use ARRAY object?
11417 # NOTE: I get it now, but I think it's confusing and not needed.
11418 # Will change it on a branch later, for review.
11419 #
11420 # XXX-XDG I don't support changing it yet. It's a very well-documented
11421 # "API" of CPAN::Meta::YAML. I'd support deprecating it, but Adam suggested
11422 # we not change it until YAML.pm's own OO API is established so that
11423 # users only have one API change to digest, not two
11424 sub new {
11425 my $class = shift;
11426 bless [ @_ ], $class;
11427 }
11428
11429 # XXX-INGY It probably doesn't matter, and it's probably too late to
11430 # change, but 'read/write' are the wrong names. Read and Write
11431 # are actions that take data from storage to memory
11432 # characters/strings. These take the data to/from storage to native
11433 # Perl objects, which the terms dump and load are meant. As long as
11434 # this is a legacy quirk to CPAN::Meta::YAML it's ok, but I'd prefer not
11435 # to add new {read,write}_* methods to this API.
11436
11437 sub read_string {
11438 my $self = shift;
11439 $self->_load_string(@_);
11440 }
11441
11442 sub write_string {
11443 my $self = shift;
11444 $self->_dump_string(@_);
11445 }
11446
11447 sub read {
11448 my $self = shift;
11449 $self->_load_file(@_);
11450 }
11451
11452 sub write {
11453 my $self = shift;
11454 $self->_dump_file(@_);
11455 }
11456
11457
11458
11459
11460 #####################################################################
11461 # Constants
11462
11463 # Printed form of the unprintable characters in the lowest range
11464 # of ASCII characters, listed by ASCII ordinal position.
11465 my @UNPRINTABLE = qw(
11466 0 x01 x02 x03 x04 x05 x06 a
11467 b t n v f r x0E x0F
11468 x10 x11 x12 x13 x14 x15 x16 x17
11469 x18 x19 x1A e x1C x1D x1E x1F
11470 );
11471
11472 # Printable characters for escapes
11473 my %UNESCAPES = (
11474 0 => "\x00", z => "\x00", N => "\x85",
11475 a => "\x07", b => "\x08", t => "\x09",
11476 n => "\x0a", v => "\x0b", f => "\x0c",
11477 r => "\x0d", e => "\x1b", '\\' => '\\',
11478 );
11479
11480 # XXX-INGY
11481 # I(ngy) need to decide if these values should be quoted in
11482 # CPAN::Meta::YAML or not. Probably yes.
11483
11484 # These 3 values have special meaning when unquoted and using the
11485 # default YAML schema. They need quotes if they are strings.
11486 my %QUOTE = map { $_ => 1 } qw{
11487 null true false
11488 };
11489
11490 # The commented out form is simpler, but overloaded the Perl regex
11491 # engine due to recursion and backtracking problems on strings
11492 # larger than 32,000ish characters. Keep it for reference purposes.
11493 # qr/\"((?:\\.|[^\"])*)\"/
11494 my $re_capture_double_quoted = qr/\"([^\\"]*(?:\\.[^\\"]*)*)\"/;
11495 my $re_capture_single_quoted = qr/\'([^\']*(?:\'\'[^\']*)*)\'/;
11496 # unquoted re gets trailing space that needs to be stripped
11497 my $re_capture_unquoted_key = qr/([^:]+(?::+\S(?:[^:]*|.*?(?=:)))*)(?=\s*\:(?:\s+|$))/;
11498 my $re_trailing_comment = qr/(?:\s+\#.*)?/;
11499 my $re_key_value_separator = qr/\s*:(?:\s+(?:\#.*)?|$)/;
11500
11501
11502
11503
11504
11505 #####################################################################
11506 # CPAN::Meta::YAML Implementation.
11507 #
11508 # These are the private methods that do all the work. They may change
11509 # at any time.
11510
11511
11512 ###
11513 # Loader functions:
11514
11515 # Create an object from a file
11516 sub _load_file {
11517 my $class = ref $_[0] ? ref shift : shift;
11518
11519 # Check the file
11520 my $file = shift or $class->_error( 'You did not specify a file name' );
11521 $class->_error( "File '$file' does not exist" )
11522 unless -e $file;
11523 $class->_error( "'$file' is a directory, not a file" )
11524 unless -f _;
11525 $class->_error( "Insufficient permissions to read '$file'" )
11526 unless -r _;
11527
11528 # Open unbuffered with strict UTF-8 decoding and no translation layers
11529 open( my $fh, "<:unix:encoding(UTF-8)", $file );
11530 unless ( $fh ) {
11531 $class->_error("Failed to open file '$file': $!");
11532 }
11533
11534 # flock if available (or warn if not possible for OS-specific reasons)
11535 if ( _can_flock() ) {
11536 flock( $fh, Fcntl::LOCK_SH() )
11537 or warn "Couldn't lock '$file' for reading: $!";
11538 }
11539
11540 # slurp the contents
11541 my $contents = eval {
11542 use warnings FATAL => 'utf8';
11543 local $/;
11544 <$fh>
11545 };
11546 if ( my $err = $@ ) {
11547 $class->_error("Error reading from file '$file': $err");
11548 }
11549
11550 # close the file (release the lock)
11551 unless ( close $fh ) {
11552 $class->_error("Failed to close file '$file': $!");
11553 }
11554
11555 $class->_load_string( $contents );
11556 }
11557
11558 # Create an object from a string
11559 sub _load_string {
11560 my $class = ref $_[0] ? ref shift : shift;
11561 my $self = bless [], $class;
11562 my $string = $_[0];
11563 eval {
11564 unless ( defined $string ) {
11565 die \"Did not provide a string to load";
11566 }
11567
11568 # Check if Perl has it marked as characters, but it's internally
11569 # inconsistent. E.g. maybe latin1 got read on a :utf8 layer
11570 if ( utf8::is_utf8($string) && ! utf8::valid($string) ) {
11571 die \<<'...';
11572 Read an invalid UTF-8 string (maybe mixed UTF-8 and 8-bit character set).
11573 Did you decode with lax ":utf8" instead of strict ":encoding(UTF-8)"?
11574 ...
11575 }
11576
11577 # Ensure Unicode character semantics, even for 0x80-0xff
11578 utf8::upgrade($string);
11579
11580 # Check for and strip any leading UTF-8 BOM
11581 $string =~ s/^\x{FEFF}//;
11582
11583 # Check for some special cases
11584 return $self unless length $string;
11585
11586 # Split the file into lines
11587 my @lines = grep { ! /^\s*(?:\#.*)?\z/ }
11588 split /(?:\015{1,2}\012|\015|\012)/, $string;
11589
11590 # Strip the initial YAML header
11591 @lines and $lines[0] =~ /^\%YAML[: ][\d\.]+.*\z/ and shift @lines;
11592
11593 # A nibbling parser
11594 my $in_document = 0;
11595 while ( @lines ) {
11596 # Do we have a document header?
11597 if ( $lines[0] =~ /^---\s*(?:(.+)\s*)?\z/ ) {
11598 # Handle scalar documents
11599 shift @lines;
11600 if ( defined $1 and $1 !~ /^(?:\#.+|\%YAML[: ][\d\.]+)\z/ ) {
11601 push @$self,
11602 $self->_load_scalar( "$1", [ undef ], \@lines );
11603 next;
11604 }
11605 $in_document = 1;
11606 }
11607
11608 if ( ! @lines or $lines[0] =~ /^(?:---|\.\.\.)/ ) {
11609 # A naked document
11610 push @$self, undef;
11611 while ( @lines and $lines[0] !~ /^---/ ) {
11612 shift @lines;
11613 }
11614 $in_document = 0;
11615
11616 # XXX The final '-+$' is to look for -- which ends up being an
11617 # error later.
11618 } elsif ( ! $in_document && @$self ) {
11619 # only the first document can be explicit
11620 die \"CPAN::Meta::YAML failed to classify the line '$lines[0]'";
11621 } elsif ( $lines[0] =~ /^\s*\-(?:\s|$|-+$)/ ) {
11622 # An array at the root
11623 my $document = [ ];
11624 push @$self, $document;
11625 $self->_load_array( $document, [ 0 ], \@lines );
11626
11627 } elsif ( $lines[0] =~ /^(\s*)\S/ ) {
11628 # A hash at the root
11629 my $document = { };
11630 push @$self, $document;
11631 $self->_load_hash( $document, [ length($1) ], \@lines );
11632
11633 } else {
11634 # Shouldn't get here. @lines have whitespace-only lines
11635 # stripped, and previous match is a line with any
11636 # non-whitespace. So this clause should only be reachable via
11637 # a perlbug where \s is not symmetric with \S
11638
11639 # uncoverable statement
11640 die \"CPAN::Meta::YAML failed to classify the line '$lines[0]'";
11641 }
11642 }
11643 };
11644 my $err = $@;
11645 if ( ref $err eq 'SCALAR' ) {
11646 $self->_error(${$err});
11647 } elsif ( $err ) {
11648 $self->_error($err);
11649 }
11650
11651 return $self;
11652 }
11653
11654 sub _unquote_single {
11655 my ($self, $string) = @_;
11656 return '' unless length $string;
11657 $string =~ s/\'\'/\'/g;
11658 return $string;
11659 }
11660
11661 sub _unquote_double {
11662 my ($self, $string) = @_;
11663 return '' unless length $string;
11664 $string =~ s/\\"/"/g;
11665 $string =~
11666 s{\\([Nnever\\fartz0b]|x([0-9a-fA-F]{2}))}
11667 {(length($1)>1)?pack("H2",$2):$UNESCAPES{$1}}gex;
11668 return $string;
11669 }
11670
11671 # Load a YAML scalar string to the actual Perl scalar
11672 sub _load_scalar {
11673 my ($self, $string, $indent, $lines) = @_;
11674
11675 # Trim trailing whitespace
11676 $string =~ s/\s*\z//;
11677
11678 # Explitic null/undef
11679 return undef if $string eq '~';
11680
11681 # Single quote
11682 if ( $string =~ /^$re_capture_single_quoted$re_trailing_comment\z/ ) {
11683 return $self->_unquote_single($1);
11684 }
11685
11686 # Double quote.
11687 if ( $string =~ /^$re_capture_double_quoted$re_trailing_comment\z/ ) {
11688 return $self->_unquote_double($1);
11689 }
11690
11691 # Special cases
11692 if ( $string =~ /^[\'\"!&]/ ) {
11693 die \"CPAN::Meta::YAML does not support a feature in line '$string'";
11694 }
11695 return {} if $string =~ /^{}(?:\s+\#.*)?\z/;
11696 return [] if $string =~ /^\[\](?:\s+\#.*)?\z/;
11697
11698 # Regular unquoted string
11699 if ( $string !~ /^[>|]/ ) {
11700 die \"CPAN::Meta::YAML found illegal characters in plain scalar: '$string'"
11701 if $string =~ /^(?:-(?:\s|$)|[\@\%\`])/ or
11702 $string =~ /:(?:\s|$)/;
11703 $string =~ s/\s+#.*\z//;
11704 return $string;
11705 }
11706
11707 # Error
11708 die \"CPAN::Meta::YAML failed to find multi-line scalar content" unless @$lines;
11709
11710 # Check the indent depth
11711 $lines->[0] =~ /^(\s*)/;
11712 $indent->[-1] = length("$1");
11713 if ( defined $indent->[-2] and $indent->[-1] <= $indent->[-2] ) {
11714 die \"CPAN::Meta::YAML found bad indenting in line '$lines->[0]'";
11715 }
11716
11717 # Pull the lines
11718 my @multiline = ();
11719 while ( @$lines ) {
11720 $lines->[0] =~ /^(\s*)/;
11721 last unless length($1) >= $indent->[-1];
11722 push @multiline, substr(shift(@$lines), length($1));
11723 }
11724
11725 my $j = (substr($string, 0, 1) eq '>') ? ' ' : "\n";
11726 my $t = (substr($string, 1, 1) eq '-') ? '' : "\n";
11727 return join( $j, @multiline ) . $t;
11728 }
11729
11730 # Load an array
11731 sub _load_array {
11732 my ($self, $array, $indent, $lines) = @_;
11733
11734 while ( @$lines ) {
11735 # Check for a new document
11736 if ( $lines->[0] =~ /^(?:---|\.\.\.)/ ) {
11737 while ( @$lines and $lines->[0] !~ /^---/ ) {
11738 shift @$lines;
11739 }
11740 return 1;
11741 }
11742
11743 # Check the indent level
11744 $lines->[0] =~ /^(\s*)/;
11745 if ( length($1) < $indent->[-1] ) {
11746 return 1;
11747 } elsif ( length($1) > $indent->[-1] ) {
11748 die \"CPAN::Meta::YAML found bad indenting in line '$lines->[0]'";
11749 }
11750
11751 if ( $lines->[0] =~ /^(\s*\-\s+)[^\'\"]\S*\s*:(?:\s+|$)/ ) {
11752 # Inline nested hash
11753 my $indent2 = length("$1");
11754 $lines->[0] =~ s/-/ /;
11755 push @$array, { };
11756 $self->_load_hash( $array->[-1], [ @$indent, $indent2 ], $lines );
11757
11758 } elsif ( $lines->[0] =~ /^\s*\-\s*\z/ ) {
11759 shift @$lines;
11760 unless ( @$lines ) {
11761 push @$array, undef;
11762 return 1;
11763 }
11764 if ( $lines->[0] =~ /^(\s*)\-/ ) {
11765 my $indent2 = length("$1");
11766 if ( $indent->[-1] == $indent2 ) {
11767 # Null array entry
11768 push @$array, undef;
11769 } else {
11770 # Naked indenter
11771 push @$array, [ ];
11772 $self->_load_array(
11773 $array->[-1], [ @$indent, $indent2 ], $lines
11774 );
11775 }
11776
11777 } elsif ( $lines->[0] =~ /^(\s*)\S/ ) {
11778 push @$array, { };
11779 $self->_load_hash(
11780 $array->[-1], [ @$indent, length("$1") ], $lines
11781 );
11782
11783 } else {
11784 die \"CPAN::Meta::YAML failed to classify line '$lines->[0]'";
11785 }
11786
11787 } elsif ( $lines->[0] =~ /^\s*\-(\s*)(.+?)\s*\z/ ) {
11788 # Array entry with a value
11789 shift @$lines;
11790 push @$array, $self->_load_scalar(
11791 "$2", [ @$indent, undef ], $lines
11792 );
11793
11794 } elsif ( defined $indent->[-2] and $indent->[-1] == $indent->[-2] ) {
11795 # This is probably a structure like the following...
11796 # ---
11797 # foo:
11798 # - list
11799 # bar: value
11800 #
11801 # ... so lets return and let the hash parser handle it
11802 return 1;
11803
11804 } else {
11805 die \"CPAN::Meta::YAML failed to classify line '$lines->[0]'";
11806 }
11807 }
11808
11809 return 1;
11810 }
11811
11812 # Load a hash
11813 sub _load_hash {
11814 my ($self, $hash, $indent, $lines) = @_;
11815
11816 while ( @$lines ) {
11817 # Check for a new document
11818 if ( $lines->[0] =~ /^(?:---|\.\.\.)/ ) {
11819 while ( @$lines and $lines->[0] !~ /^---/ ) {
11820 shift @$lines;
11821 }
11822 return 1;
11823 }
11824
11825 # Check the indent level
11826 $lines->[0] =~ /^(\s*)/;
11827 if ( length($1) < $indent->[-1] ) {
11828 return 1;
11829 } elsif ( length($1) > $indent->[-1] ) {
11830 die \"CPAN::Meta::YAML found bad indenting in line '$lines->[0]'";
11831 }
11832
11833 # Find the key
11834 my $key;
11835
11836 # Quoted keys
11837 if ( $lines->[0] =~
11838 s/^\s*$re_capture_single_quoted$re_key_value_separator//
11839 ) {
11840 $key = $self->_unquote_single($1);
11841 }
11842 elsif ( $lines->[0] =~
11843 s/^\s*$re_capture_double_quoted$re_key_value_separator//
11844 ) {
11845 $key = $self->_unquote_double($1);
11846 }
11847 elsif ( $lines->[0] =~
11848 s/^\s*$re_capture_unquoted_key$re_key_value_separator//
11849 ) {
11850 $key = $1;
11851 $key =~ s/\s+$//;
11852 }
11853 elsif ( $lines->[0] =~ /^\s*\?/ ) {
11854 die \"CPAN::Meta::YAML does not support a feature in line '$lines->[0]'";
11855 }
11856 else {
11857 die \"CPAN::Meta::YAML failed to classify line '$lines->[0]'";
11858 }
11859
11860 if ( exists $hash->{$key} ) {
11861 warn "CPAN::Meta::YAML found a duplicate key '$key' in line '$lines->[0]'";
11862 }
11863
11864 # Do we have a value?
11865 if ( length $lines->[0] ) {
11866 # Yes
11867 $hash->{$key} = $self->_load_scalar(
11868 shift(@$lines), [ @$indent, undef ], $lines
11869 );
11870 } else {
11871 # An indent
11872 shift @$lines;
11873 unless ( @$lines ) {
11874 $hash->{$key} = undef;
11875 return 1;
11876 }
11877 if ( $lines->[0] =~ /^(\s*)-/ ) {
11878 $hash->{$key} = [];
11879 $self->_load_array(
11880 $hash->{$key}, [ @$indent, length($1) ], $lines
11881 );
11882 } elsif ( $lines->[0] =~ /^(\s*)./ ) {
11883 my $indent2 = length("$1");
11884 if ( $indent->[-1] >= $indent2 ) {
11885 # Null hash entry
11886 $hash->{$key} = undef;
11887 } else {
11888 $hash->{$key} = {};
11889 $self->_load_hash(
11890 $hash->{$key}, [ @$indent, length($1) ], $lines
11891 );
11892 }
11893 }
11894 }
11895 }
11896
11897 return 1;
11898 }
11899
11900
11901 ###
11902 # Dumper functions:
11903
11904 # Save an object to a file
11905 sub _dump_file {
11906 my $self = shift;
11907
11908 require Fcntl;
11909
11910 # Check the file
11911 my $file = shift or $self->_error( 'You did not specify a file name' );
11912
11913 my $fh;
11914 # flock if available (or warn if not possible for OS-specific reasons)
11915 if ( _can_flock() ) {
11916 # Open without truncation (truncate comes after lock)
11917 my $flags = Fcntl::O_WRONLY()|Fcntl::O_CREAT();
11918 sysopen( $fh, $file, $flags );
11919 unless ( $fh ) {
11920 $self->_error("Failed to open file '$file' for writing: $!");
11921 }
11922
11923 # Use no translation and strict UTF-8
11924 binmode( $fh, ":raw:encoding(UTF-8)");
11925
11926 flock( $fh, Fcntl::LOCK_EX() )
11927 or warn "Couldn't lock '$file' for reading: $!";
11928
11929 # truncate and spew contents
11930 truncate $fh, 0;
11931 seek $fh, 0, 0;
11932 }
11933 else {
11934 open $fh, ">:unix:encoding(UTF-8)", $file;
11935 }
11936
11937 # serialize and spew to the handle
11938 print {$fh} $self->_dump_string;
11939
11940 # close the file (release the lock)
11941 unless ( close $fh ) {
11942 $self->_error("Failed to close file '$file': $!");
11943 }
11944
11945 return 1;
11946 }
11947
11948 # Save an object to a string
11949 sub _dump_string {
11950 my $self = shift;
11951 return '' unless ref $self && @$self;
11952
11953 # Iterate over the documents
11954 my $indent = 0;
11955 my @lines = ();
11956
11957 eval {
11958 foreach my $cursor ( @$self ) {
11959 push @lines, '---';
11960
11961 # An empty document
11962 if ( ! defined $cursor ) {
11963 # Do nothing
11964
11965 # A scalar document
11966 } elsif ( ! ref $cursor ) {
11967 $lines[-1] .= ' ' . $self->_dump_scalar( $cursor );
11968
11969 # A list at the root
11970 } elsif ( ref $cursor eq 'ARRAY' ) {
11971 unless ( @$cursor ) {
11972 $lines[-1] .= ' []';
11973 next;
11974 }
11975 push @lines, $self->_dump_array( $cursor, $indent, {} );
11976
11977 # A hash at the root
11978 } elsif ( ref $cursor eq 'HASH' ) {
11979 unless ( %$cursor ) {
11980 $lines[-1] .= ' {}';
11981 next;
11982 }
11983 push @lines, $self->_dump_hash( $cursor, $indent, {} );
11984
11985 } else {
11986 die \("Cannot serialize " . ref($cursor));
11987 }
11988 }
11989 };
11990 if ( ref $@ eq 'SCALAR' ) {
11991 $self->_error(${$@});
11992 } elsif ( $@ ) {
11993 $self->_error($@);
11994 }
11995
11996 join '', map { "$_\n" } @lines;
11997 }
11998
11999 sub _has_internal_string_value {
12000 my $value = shift;
12001 my $b_obj = B::svref_2object(\$value); # for round trip problem
12002 return $b_obj->FLAGS & B::SVf_POK();
12003 }
12004
12005 sub _dump_scalar {
12006 my $string = $_[1];
12007 my $is_key = $_[2];
12008 # Check this before checking length or it winds up looking like a string!
12009 my $has_string_flag = _has_internal_string_value($string);
12010 return '~' unless defined $string;
12011 return "''" unless length $string;
12012 if (Scalar::Util::looks_like_number($string)) {
12013 # keys and values that have been used as strings get quoted
12014 if ( $is_key || $has_string_flag ) {
12015 return qq['$string'];
12016 }
12017 else {
12018 return $string;
12019 }
12020 }
12021 if ( $string =~ /[\x00-\x09\x0b-\x0d\x0e-\x1f\x7f-\x9f\'\n]/ ) {
12022 $string =~ s/\\/\\\\/g;
12023 $string =~ s/"/\\"/g;
12024 $string =~ s/\n/\\n/g;
12025 $string =~ s/[\x85]/\\N/g;
12026 $string =~ s/([\x00-\x1f])/\\$UNPRINTABLE[ord($1)]/g;
12027 $string =~ s/([\x7f-\x9f])/'\x' . sprintf("%X",ord($1))/ge;
12028 return qq|"$string"|;
12029 }
12030 if ( $string =~ /(?:^[~!@#%&*|>?:,'"`{}\[\]]|^-+$|\s|:\z)/ or
12031 $QUOTE{$string}
12032 ) {
12033 return "'$string'";
12034 }
12035 return $string;
12036 }
12037
12038 sub _dump_array {
12039 my ($self, $array, $indent, $seen) = @_;
12040 if ( $seen->{refaddr($array)}++ ) {
12041 die \"CPAN::Meta::YAML does not support circular references";
12042 }
12043 my @lines = ();
12044 foreach my $el ( @$array ) {
12045 my $line = (' ' x $indent) . '-';
12046 my $type = ref $el;
12047 if ( ! $type ) {
12048 $line .= ' ' . $self->_dump_scalar( $el );
12049 push @lines, $line;
12050
12051 } elsif ( $type eq 'ARRAY' ) {
12052 if ( @$el ) {
12053 push @lines, $line;
12054 push @lines, $self->_dump_array( $el, $indent + 1, $seen );
12055 } else {
12056 $line .= ' []';
12057 push @lines, $line;
12058 }
12059
12060 } elsif ( $type eq 'HASH' ) {
12061 if ( keys %$el ) {
12062 push @lines, $line;
12063 push @lines, $self->_dump_hash( $el, $indent + 1, $seen );
12064 } else {
12065 $line .= ' {}';
12066 push @lines, $line;
12067 }
12068
12069 } else {
12070 die \"CPAN::Meta::YAML does not support $type references";
12071 }
12072 }
12073
12074 @lines;
12075 }
12076
12077 sub _dump_hash {
12078 my ($self, $hash, $indent, $seen) = @_;
12079 if ( $seen->{refaddr($hash)}++ ) {
12080 die \"CPAN::Meta::YAML does not support circular references";
12081 }
12082 my @lines = ();
12083 foreach my $name ( sort keys %$hash ) {
12084 my $el = $hash->{$name};
12085 my $line = (' ' x $indent) . $self->_dump_scalar($name, 1) . ":";
12086 my $type = ref $el;
12087 if ( ! $type ) {
12088 $line .= ' ' . $self->_dump_scalar( $el );
12089 push @lines, $line;
12090
12091 } elsif ( $type eq 'ARRAY' ) {
12092 if ( @$el ) {
12093 push @lines, $line;
12094 push @lines, $self->_dump_array( $el, $indent + 1, $seen );
12095 } else {
12096 $line .= ' []';
12097 push @lines, $line;
12098 }
12099
12100 } elsif ( $type eq 'HASH' ) {
12101 if ( keys %$el ) {
12102 push @lines, $line;
12103 push @lines, $self->_dump_hash( $el, $indent + 1, $seen );
12104 } else {
12105 $line .= ' {}';
12106 push @lines, $line;
12107 }
12108
12109 } else {
12110 die \"CPAN::Meta::YAML does not support $type references";
12111 }
12112 }
12113
12114 @lines;
12115 }
12116
12117
12118
12119 #####################################################################
12120 # DEPRECATED API methods:
12121
12122 # Error storage (DEPRECATED as of 1.57)
12123 our $errstr = '';
12124
12125 # Set error
12126 sub _error {
12127 require Carp;
12128 $errstr = $_[1];
12129 $errstr =~ s/ at \S+ line \d+.*//;
12130 Carp::croak( $errstr );
12131 }
12132
12133 # Retrieve error
12134 my $errstr_warned;
12135 sub errstr {
12136 require Carp;
12137 Carp::carp( "CPAN::Meta::YAML->errstr and \$CPAN::Meta::YAML::errstr is deprecated" )
12138 unless $errstr_warned++;
12139 $errstr;
12140 }
12141
12142
12143
12144
12145 #####################################################################
12146 # Helper functions. Possibly not needed.
12147
12148
12149 # Use to detect nv or iv
12150 use B;
12151
12152 # XXX-INGY Is flock CPAN::Meta::YAML's responsibility?
12153 # Some platforms can't flock :-(
12154 # XXX-XDG I think it is. When reading and writing files, we ought
12155 # to be locking whenever possible. People (foolishly) use YAML
12156 # files for things like session storage, which has race issues.
12157 my $HAS_FLOCK;
12158 sub _can_flock {
12159 if ( defined $HAS_FLOCK ) {
12160 return $HAS_FLOCK;
12161 }
12162 else {
12163 require Config;
12164 my $c = \%Config::Config;
12165 $HAS_FLOCK = grep { $c->{$_} } qw/d_flock d_fcntl_can_lock d_lockf/;
12166 require Fcntl if $HAS_FLOCK;
12167 return $HAS_FLOCK;
12168 }
12169 }
12170
12171
12172 # XXX-INGY Is this core in 5.8.1? Can we remove this?
12173 # XXX-XDG Scalar::Util 1.18 didn't land until 5.8.8, so we need this
12174 #####################################################################
12175 # Use Scalar::Util if possible, otherwise emulate it
12176
12177 use Scalar::Util ();
12178 BEGIN {
12179 local $@;
12180 if ( eval { Scalar::Util->VERSION(1.18); } ) {
12181 *refaddr = *Scalar::Util::refaddr;
12182 }
12183 else {
12184 eval <<'END_PERL';
12185 # Scalar::Util failed to load or too old
12186 sub refaddr {
12187 my $pkg = ref($_[0]) or return undef;
12188 if ( !! UNIVERSAL::can($_[0], 'can') ) {
12189 bless $_[0], 'Scalar::Util::Fake';
12190 } else {
12191 $pkg = undef;
12192 }
12193 "$_[0]" =~ /0x(\w+)/;
12194 my $i = do { no warnings 'portable'; hex $1 };
12195 bless $_[0], $pkg if defined $pkg;
12196 $i;
12197 }
12198 END_PERL
12199 }
12200 }
12201
12202 delete $CPAN::Meta::YAML::{refaddr};
12203
12204 1;
12205
12206 # XXX-INGY Doc notes I'm putting up here. Changing the doc when it's wrong
12207 # but leaving grey area stuff up here.
12208 #
12209 # I would like to change Read/Write to Load/Dump below without
12210 # changing the actual API names.
12211 #
12212 # It might be better to put Load/Dump API in the SYNOPSIS instead of the
12213 # dubious OO API.
12214 #
12215 # null and bool explanations may be outdated.
12216
12217 =pod
12218
12219 =encoding UTF-8
12220
12221 =head1 NAME
12222
12223 CPAN::Meta::YAML - Read and write a subset of YAML for CPAN Meta files
12224
12225 =head1 VERSION
12226
12227 version 0.016
12228
12229 =head1 SYNOPSIS
12230
12231 use CPAN::Meta::YAML;
12232
12233 # reading a META file
12234 open $fh, "<:utf8", "META.yml";
12235 $yaml_text = do { local $/; <$fh> };
12236 $yaml = CPAN::Meta::YAML->read_string($yaml_text)
12237 or die CPAN::Meta::YAML->errstr;
12238
12239 # finding the metadata
12240 $meta = $yaml->[0];
12241
12242 # writing a META file
12243 $yaml_text = $yaml->write_string
12244 or die CPAN::Meta::YAML->errstr;
12245 open $fh, ">:utf8", "META.yml";
12246 print $fh $yaml_text;
12247
12248 =head1 DESCRIPTION
12249
12250 This module implements a subset of the YAML specification for use in reading
12251 and writing CPAN metadata files like F<META.yml> and F<MYMETA.yml>. It should
12252 not be used for any other general YAML parsing or generation task.
12253
12254 NOTE: F<META.yml> (and F<MYMETA.yml>) files should be UTF-8 encoded. Users are
12255 responsible for proper encoding and decoding. In particular, the C<read> and
12256 C<write> methods do B<not> support UTF-8 and should not be used.
12257
12258 =head1 SUPPORT
12259
12260 This module is currently derived from L<YAML::Tiny> by Adam Kennedy. If
12261 there are bugs in how it parses a particular META.yml file, please file
12262 a bug report in the YAML::Tiny bugtracker:
12263 L<https://github.com/Perl-Toolchain-Gang/YAML-Tiny/issues>
12264
12265 =head1 SEE ALSO
12266
12267 L<YAML::Tiny>, L<YAML>, L<YAML::XS>
12268
12269 =head1 AUTHORS
12270
12271 =over 4
12272
12273 =item *
12274
12275 Adam Kennedy <adamk@cpan.org>
12276
12277 =item *
12278
12279 David Golden <dagolden@cpan.org>
12280
12281 =back
12282
12283 =head1 COPYRIGHT AND LICENSE
12284
12285 This software is copyright (c) 2010 by Adam Kennedy.
12286
12287 This is free software; you can redistribute it and/or modify it under
12288 the same terms as the Perl 5 programming language system itself.
12289
12290 =cut
12291
12292 __END__
12293
12294
12295 # ABSTRACT: Read and write a subset of YAML for CPAN Meta files
12296
12297
12298 CPAN_META_YAML
12299  
12300 $fatpacked{"Exporter.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'EXPORTER';
12301 package Exporter;
12302
12303 require 5.006;
12304
12305 # Be lean.
12306 #use strict;
12307 #no strict 'refs';
12308
12309 our $Debug = 0;
12310 our $ExportLevel = 0;
12311 our $Verbose ||= 0;
12312 our $VERSION = '5.70';
12313 our (%Cache);
12314
12315 sub as_heavy {
12316 require Exporter::Heavy;
12317 # Unfortunately, this does not work if the caller is aliased as *name = \&foo
12318 # Thus the need to create a lot of identical subroutines
12319 my $c = (caller(1))[3];
12320 $c =~ s/.*:://;
12321 \&{"Exporter::Heavy::heavy_$c"};
12322 }
12323
12324 sub export {
12325 goto &{as_heavy()};
12326 }
12327
12328 sub import {
12329 my $pkg = shift;
12330 my $callpkg = caller($ExportLevel);
12331
12332 if ($pkg eq "Exporter" and @_ and $_[0] eq "import") {
12333 *{$callpkg."::import"} = \&import;
12334 return;
12335 }
12336
12337 # We *need* to treat @{"$pkg\::EXPORT_FAIL"} since Carp uses it :-(
12338 my $exports = \@{"$pkg\::EXPORT"};
12339 # But, avoid creating things if they don't exist, which saves a couple of
12340 # hundred bytes per package processed.
12341 my $fail = ${$pkg . '::'}{EXPORT_FAIL} && \@{"$pkg\::EXPORT_FAIL"};
12342 return export $pkg, $callpkg, @_
12343 if $Verbose or $Debug or $fail && @$fail > 1;
12344 my $export_cache = ($Cache{$pkg} ||= {});
12345 my $args = @_ or @_ = @$exports;
12346
12347 if ($args and not %$export_cache) {
12348 s/^&//, $export_cache->{$_} = 1
12349 foreach (@$exports, @{"$pkg\::EXPORT_OK"});
12350 }
12351 my $heavy;
12352 # Try very hard not to use {} and hence have to enter scope on the foreach
12353 # We bomb out of the loop with last as soon as heavy is set.
12354 if ($args or $fail) {
12355 ($heavy = (/\W/ or $args and not exists $export_cache->{$_}
12356 or $fail and @$fail and $_ eq $fail->[0])) and last
12357 foreach (@_);
12358 } else {
12359 ($heavy = /\W/) and last
12360 foreach (@_);
12361 }
12362 return export $pkg, $callpkg, ($args ? @_ : ()) if $heavy;
12363 local $SIG{__WARN__} =
12364 sub {require Carp; &Carp::carp} if not $SIG{__WARN__};
12365 # shortcut for the common case of no type character
12366 *{"$callpkg\::$_"} = \&{"$pkg\::$_"} foreach @_;
12367 }
12368
12369 # Default methods
12370
12371 sub export_fail {
12372 my $self = shift;
12373 @_;
12374 }
12375
12376 # Unfortunately, caller(1)[3] "does not work" if the caller is aliased as
12377 # *name = \&foo. Thus the need to create a lot of identical subroutines
12378 # Otherwise we could have aliased them to export().
12379
12380 sub export_to_level {
12381 goto &{as_heavy()};
12382 }
12383
12384 sub export_tags {
12385 goto &{as_heavy()};
12386 }
12387
12388 sub export_ok_tags {
12389 goto &{as_heavy()};
12390 }
12391
12392 sub require_version {
12393 goto &{as_heavy()};
12394 }
12395
12396 1;
12397 __END__
12398
12399 =head1 NAME
12400
12401 Exporter - Implements default import method for modules
12402
12403 =head1 SYNOPSIS
12404
12405 In module F<YourModule.pm>:
12406
12407 package YourModule;
12408 require Exporter;
12409 @ISA = qw(Exporter);
12410 @EXPORT_OK = qw(munge frobnicate); # symbols to export on request
12411
12412 or
12413
12414 package YourModule;
12415 use Exporter 'import'; # gives you Exporter's import() method directly
12416 @EXPORT_OK = qw(munge frobnicate); # symbols to export on request
12417
12418 In other files which wish to use C<YourModule>:
12419
12420 use YourModule qw(frobnicate); # import listed symbols
12421 frobnicate ($left, $right) # calls YourModule::frobnicate
12422
12423 Take a look at L</Good Practices> for some variants
12424 you will like to use in modern Perl code.
12425
12426 =head1 DESCRIPTION
12427
12428 The Exporter module implements an C<import> method which allows a module
12429 to export functions and variables to its users' namespaces. Many modules
12430 use Exporter rather than implementing their own C<import> method because
12431 Exporter provides a highly flexible interface, with an implementation optimised
12432 for the common case.
12433
12434 Perl automatically calls the C<import> method when processing a
12435 C<use> statement for a module. Modules and C<use> are documented
12436 in L<perlfunc> and L<perlmod>. Understanding the concept of
12437 modules and how the C<use> statement operates is important to
12438 understanding the Exporter.
12439
12440 =head2 How to Export
12441
12442 The arrays C<@EXPORT> and C<@EXPORT_OK> in a module hold lists of
12443 symbols that are going to be exported into the users name space by
12444 default, or which they can request to be exported, respectively. The
12445 symbols can represent functions, scalars, arrays, hashes, or typeglobs.
12446 The symbols must be given by full name with the exception that the
12447 ampersand in front of a function is optional, e.g.
12448
12449 @EXPORT = qw(afunc $scalar @array); # afunc is a function
12450 @EXPORT_OK = qw(&bfunc %hash *typeglob); # explicit prefix on &bfunc
12451
12452 If you are only exporting function names it is recommended to omit the
12453 ampersand, as the implementation is faster this way.
12454
12455 =head2 Selecting What to Export
12456
12457 Do B<not> export method names!
12458
12459 Do B<not> export anything else by default without a good reason!
12460
12461 Exports pollute the namespace of the module user. If you must export
12462 try to use C<@EXPORT_OK> in preference to C<@EXPORT> and avoid short or
12463 common symbol names to reduce the risk of name clashes.
12464
12465 Generally anything not exported is still accessible from outside the
12466 module using the C<YourModule::item_name> (or C<< $blessed_ref->method >>)
12467 syntax. By convention you can use a leading underscore on names to
12468 informally indicate that they are 'internal' and not for public use.
12469
12470 (It is actually possible to get private functions by saying:
12471
12472 my $subref = sub { ... };
12473 $subref->(@args); # Call it as a function
12474 $obj->$subref(@args); # Use it as a method
12475
12476 However if you use them for methods it is up to you to figure out
12477 how to make inheritance work.)
12478
12479 As a general rule, if the module is trying to be object oriented
12480 then export nothing. If it's just a collection of functions then
12481 C<@EXPORT_OK> anything but use C<@EXPORT> with caution. For function and
12482 method names use barewords in preference to names prefixed with
12483 ampersands for the export lists.
12484
12485 Other module design guidelines can be found in L<perlmod>.
12486
12487 =head2 How to Import
12488
12489 In other files which wish to use your module there are three basic ways for
12490 them to load your module and import its symbols:
12491
12492 =over 4
12493
12494 =item C<use YourModule;>
12495
12496 This imports all the symbols from YourModule's C<@EXPORT> into the namespace
12497 of the C<use> statement.
12498
12499 =item C<use YourModule ();>
12500
12501 This causes perl to load your module but does not import any symbols.
12502
12503 =item C<use YourModule qw(...);>
12504
12505 This imports only the symbols listed by the caller into their namespace.
12506 All listed symbols must be in your C<@EXPORT> or C<@EXPORT_OK>, else an error
12507 occurs. The advanced export features of Exporter are accessed like this,
12508 but with list entries that are syntactically distinct from symbol names.
12509
12510 =back
12511
12512 Unless you want to use its advanced features, this is probably all you
12513 need to know to use Exporter.
12514
12515 =head1 Advanced Features
12516
12517 =head2 Specialised Import Lists
12518
12519 If any of the entries in an import list begins with !, : or / then
12520 the list is treated as a series of specifications which either add to
12521 or delete from the list of names to import. They are processed left to
12522 right. Specifications are in the form:
12523
12524 [!]name This name only
12525 [!]:DEFAULT All names in @EXPORT
12526 [!]:tag All names in $EXPORT_TAGS{tag} anonymous list
12527 [!]/pattern/ All names in @EXPORT and @EXPORT_OK which match
12528
12529 A leading ! indicates that matching names should be deleted from the
12530 list of names to import. If the first specification is a deletion it
12531 is treated as though preceded by :DEFAULT. If you just want to import
12532 extra names in addition to the default set you will still need to
12533 include :DEFAULT explicitly.
12534
12535 e.g., F<Module.pm> defines:
12536
12537 @EXPORT = qw(A1 A2 A3 A4 A5);
12538 @EXPORT_OK = qw(B1 B2 B3 B4 B5);
12539 %EXPORT_TAGS = (T1 => [qw(A1 A2 B1 B2)], T2 => [qw(A1 A2 B3 B4)]);
12540
12541 Note that you cannot use tags in @EXPORT or @EXPORT_OK.
12542
12543 Names in EXPORT_TAGS must also appear in @EXPORT or @EXPORT_OK.
12544
12545 An application using Module can say something like:
12546
12547 use Module qw(:DEFAULT :T2 !B3 A3);
12548
12549 Other examples include:
12550
12551 use Socket qw(!/^[AP]F_/ !SOMAXCONN !SOL_SOCKET);
12552 use POSIX qw(:errno_h :termios_h !TCSADRAIN !/^EXIT/);
12553
12554 Remember that most patterns (using //) will need to be anchored
12555 with a leading ^, e.g., C</^EXIT/> rather than C</EXIT/>.
12556
12557 You can say C<BEGIN { $Exporter::Verbose=1 }> to see how the
12558 specifications are being processed and what is actually being imported
12559 into modules.
12560
12561 =head2 Exporting Without Using Exporter's import Method
12562
12563 Exporter has a special method, 'export_to_level' which is used in situations
12564 where you can't directly call Exporter's
12565 import method. The export_to_level
12566 method looks like:
12567
12568 MyPackage->export_to_level(
12569 $where_to_export, $package, @what_to_export
12570 );
12571
12572 where C<$where_to_export> is an integer telling how far up the calling stack
12573 to export your symbols, and C<@what_to_export> is an array telling what
12574 symbols *to* export (usually this is C<@_>). The C<$package> argument is
12575 currently unused.
12576
12577 For example, suppose that you have a module, A, which already has an
12578 import function:
12579
12580 package A;
12581
12582 @ISA = qw(Exporter);
12583 @EXPORT_OK = qw($b);
12584
12585 sub import
12586 {
12587 $A::b = 1; # not a very useful import method
12588 }
12589
12590 and you want to Export symbol C<$A::b> back to the module that called
12591 package A. Since Exporter relies on the import method to work, via
12592 inheritance, as it stands Exporter::import() will never get called.
12593 Instead, say the following:
12594
12595 package A;
12596 @ISA = qw(Exporter);
12597 @EXPORT_OK = qw($b);
12598
12599 sub import
12600 {
12601 $A::b = 1;
12602 A->export_to_level(1, @_);
12603 }
12604
12605 This will export the symbols one level 'above' the current package - ie: to
12606 the program or module that used package A.
12607
12608 Note: Be careful not to modify C<@_> at all before you call export_to_level
12609 - or people using your package will get very unexplained results!
12610
12611 =head2 Exporting Without Inheriting from Exporter
12612
12613 By including Exporter in your C<@ISA> you inherit an Exporter's import() method
12614 but you also inherit several other helper methods which you probably don't
12615 want. To avoid this you can do:
12616
12617 package YourModule;
12618 use Exporter qw(import);
12619
12620 which will export Exporter's own import() method into YourModule.
12621 Everything will work as before but you won't need to include Exporter in
12622 C<@YourModule::ISA>.
12623
12624 Note: This feature was introduced in version 5.57
12625 of Exporter, released with perl 5.8.3.
12626
12627 =head2 Module Version Checking
12628
12629 The Exporter module will convert an attempt to import a number from a
12630 module into a call to C<< $module_name->VERSION($value) >>. This can
12631 be used to validate that the version of the module being used is
12632 greater than or equal to the required version.
12633
12634 For historical reasons, Exporter supplies a C<require_version> method that
12635 simply delegates to C<VERSION>. Originally, before C<UNIVERSAL::VERSION>
12636 existed, Exporter would call C<require_version>.
12637
12638 Since the C<UNIVERSAL::VERSION> method treats the C<$VERSION> number as
12639 a simple numeric value it will regard version 1.10 as lower than
12640 1.9. For this reason it is strongly recommended that you use numbers
12641 with at least two decimal places, e.g., 1.09.
12642
12643 =head2 Managing Unknown Symbols
12644
12645 In some situations you may want to prevent certain symbols from being
12646 exported. Typically this applies to extensions which have functions
12647 or constants that may not exist on some systems.
12648
12649 The names of any symbols that cannot be exported should be listed
12650 in the C<@EXPORT_FAIL> array.
12651
12652 If a module attempts to import any of these symbols the Exporter
12653 will give the module an opportunity to handle the situation before
12654 generating an error. The Exporter will call an export_fail method
12655 with a list of the failed symbols:
12656
12657 @failed_symbols = $module_name->export_fail(@failed_symbols);
12658
12659 If the C<export_fail> method returns an empty list then no error is
12660 recorded and all the requested symbols are exported. If the returned
12661 list is not empty then an error is generated for each symbol and the
12662 export fails. The Exporter provides a default C<export_fail> method which
12663 simply returns the list unchanged.
12664
12665 Uses for the C<export_fail> method include giving better error messages
12666 for some symbols and performing lazy architectural checks (put more
12667 symbols into C<@EXPORT_FAIL> by default and then take them out if someone
12668 actually tries to use them and an expensive check shows that they are
12669 usable on that platform).
12670
12671 =head2 Tag Handling Utility Functions
12672
12673 Since the symbols listed within C<%EXPORT_TAGS> must also appear in either
12674 C<@EXPORT> or C<@EXPORT_OK>, two utility functions are provided which allow
12675 you to easily add tagged sets of symbols to C<@EXPORT> or C<@EXPORT_OK>:
12676
12677 %EXPORT_TAGS = (foo => [qw(aa bb cc)], bar => [qw(aa cc dd)]);
12678
12679 Exporter::export_tags('foo'); # add aa, bb and cc to @EXPORT
12680 Exporter::export_ok_tags('bar'); # add aa, cc and dd to @EXPORT_OK
12681
12682 Any names which are not tags are added to C<@EXPORT> or C<@EXPORT_OK>
12683 unchanged but will trigger a warning (with C<-w>) to avoid misspelt tags
12684 names being silently added to C<@EXPORT> or C<@EXPORT_OK>. Future versions
12685 may make this a fatal error.
12686
12687 =head2 Generating Combined Tags
12688
12689 If several symbol categories exist in C<%EXPORT_TAGS>, it's usually
12690 useful to create the utility ":all" to simplify "use" statements.
12691
12692 The simplest way to do this is:
12693
12694 %EXPORT_TAGS = (foo => [qw(aa bb cc)], bar => [qw(aa cc dd)]);
12695
12696 # add all the other ":class" tags to the ":all" class,
12697 # deleting duplicates
12698 {
12699 my %seen;
12700
12701 push @{$EXPORT_TAGS{all}},
12702 grep {!$seen{$_}++} @{$EXPORT_TAGS{$_}} foreach keys %EXPORT_TAGS;
12703 }
12704
12705 F<CGI.pm> creates an ":all" tag which contains some (but not really
12706 all) of its categories. That could be done with one small
12707 change:
12708
12709 # add some of the other ":class" tags to the ":all" class,
12710 # deleting duplicates
12711 {
12712 my %seen;
12713
12714 push @{$EXPORT_TAGS{all}},
12715 grep {!$seen{$_}++} @{$EXPORT_TAGS{$_}}
12716 foreach qw/html2 html3 netscape form cgi internal/;
12717 }
12718
12719 Note that the tag names in C<%EXPORT_TAGS> don't have the leading ':'.
12720
12721 =head2 C<AUTOLOAD>ed Constants
12722
12723 Many modules make use of C<AUTOLOAD>ing for constant subroutines to
12724 avoid having to compile and waste memory on rarely used values (see
12725 L<perlsub> for details on constant subroutines). Calls to such
12726 constant subroutines are not optimized away at compile time because
12727 they can't be checked at compile time for constancy.
12728
12729 Even if a prototype is available at compile time, the body of the
12730 subroutine is not (it hasn't been C<AUTOLOAD>ed yet). perl needs to
12731 examine both the C<()> prototype and the body of a subroutine at
12732 compile time to detect that it can safely replace calls to that
12733 subroutine with the constant value.
12734
12735 A workaround for this is to call the constants once in a C<BEGIN> block:
12736
12737 package My ;
12738
12739 use Socket ;
12740
12741 foo( SO_LINGER ); ## SO_LINGER NOT optimized away; called at runtime
12742 BEGIN { SO_LINGER }
12743 foo( SO_LINGER ); ## SO_LINGER optimized away at compile time.
12744
12745 This forces the C<AUTOLOAD> for C<SO_LINGER> to take place before
12746 SO_LINGER is encountered later in C<My> package.
12747
12748 If you are writing a package that C<AUTOLOAD>s, consider forcing
12749 an C<AUTOLOAD> for any constants explicitly imported by other packages
12750 or which are usually used when your package is C<use>d.
12751
12752 =head1 Good Practices
12753
12754 =head2 Declaring C<@EXPORT_OK> and Friends
12755
12756 When using C<Exporter> with the standard C<strict> and C<warnings>
12757 pragmas, the C<our> keyword is needed to declare the package
12758 variables C<@EXPORT_OK>, C<@EXPORT>, C<@ISA>, etc.
12759
12760 our @ISA = qw(Exporter);
12761 our @EXPORT_OK = qw(munge frobnicate);
12762
12763 If backward compatibility for Perls under 5.6 is important,
12764 one must write instead a C<use vars> statement.
12765
12766 use vars qw(@ISA @EXPORT_OK);
12767 @ISA = qw(Exporter);
12768 @EXPORT_OK = qw(munge frobnicate);
12769
12770 =head2 Playing Safe
12771
12772 There are some caveats with the use of runtime statements
12773 like C<require Exporter> and the assignment to package
12774 variables, which can be very subtle for the unaware programmer.
12775 This may happen for instance with mutually recursive
12776 modules, which are affected by the time the relevant
12777 constructions are executed.
12778
12779 The ideal (but a bit ugly) way to never have to think
12780 about that is to use C<BEGIN> blocks. So the first part
12781 of the L</SYNOPSIS> code could be rewritten as:
12782
12783 package YourModule;
12784
12785 use strict;
12786 use warnings;
12787
12788 our (@ISA, @EXPORT_OK);
12789 BEGIN {
12790 require Exporter;
12791 @ISA = qw(Exporter);
12792 @EXPORT_OK = qw(munge frobnicate); # symbols to export on request
12793 }
12794
12795 The C<BEGIN> will assure that the loading of F<Exporter.pm>
12796 and the assignments to C<@ISA> and C<@EXPORT_OK> happen
12797 immediately, leaving no room for something to get awry
12798 or just plain wrong.
12799
12800 With respect to loading C<Exporter> and inheriting, there
12801 are alternatives with the use of modules like C<base> and C<parent>.
12802
12803 use base qw(Exporter);
12804 # or
12805 use parent qw(Exporter);
12806
12807 Any of these statements are nice replacements for
12808 C<BEGIN { require Exporter; @ISA = qw(Exporter); }>
12809 with the same compile-time effect. The basic difference
12810 is that C<base> code interacts with declared C<fields>
12811 while C<parent> is a streamlined version of the older
12812 C<base> code to just establish the IS-A relationship.
12813
12814 For more details, see the documentation and code of
12815 L<base> and L<parent>.
12816
12817 Another thorough remedy to that runtime
12818 vs. compile-time trap is to use L<Exporter::Easy>,
12819 which is a wrapper of Exporter that allows all
12820 boilerplate code at a single gulp in the
12821 use statement.
12822
12823 use Exporter::Easy (
12824 OK => [ qw(munge frobnicate) ],
12825 );
12826 # @ISA setup is automatic
12827 # all assignments happen at compile time
12828
12829 =head2 What Not to Export
12830
12831 You have been warned already in L</Selecting What to Export>
12832 to not export:
12833
12834 =over 4
12835
12836 =item *
12837
12838 method names (because you don't need to
12839 and that's likely to not do what you want),
12840
12841 =item *
12842
12843 anything by default (because you don't want to surprise your users...
12844 badly)
12845
12846 =item *
12847
12848 anything you don't need to (because less is more)
12849
12850 =back
12851
12852 There's one more item to add to this list. Do B<not>
12853 export variable names. Just because C<Exporter> lets you
12854 do that, it does not mean you should.
12855
12856 @EXPORT_OK = qw($svar @avar %hvar); # DON'T!
12857
12858 Exporting variables is not a good idea. They can
12859 change under the hood, provoking horrible
12860 effects at-a-distance that are too hard to track
12861 and to fix. Trust me: they are not worth it.
12862
12863 To provide the capability to set/get class-wide
12864 settings, it is best instead to provide accessors
12865 as subroutines or class methods instead.
12866
12867 =head1 SEE ALSO
12868
12869 C<Exporter> is definitely not the only module with
12870 symbol exporter capabilities. At CPAN, you may find
12871 a bunch of them. Some are lighter. Some
12872 provide improved APIs and features. Pick the one
12873 that fits your needs. The following is
12874 a sample list of such modules.
12875
12876 Exporter::Easy
12877 Exporter::Lite
12878 Exporter::Renaming
12879 Exporter::Tidy
12880 Sub::Exporter / Sub::Installer
12881 Perl6::Export / Perl6::Export::Attrs
12882
12883 =head1 LICENSE
12884
12885 This library is free software. You can redistribute it
12886 and/or modify it under the same terms as Perl itself.
12887
12888 =cut
12889
12890
12891
12892 EXPORTER
12893  
12894 $fatpacked{"Exporter/Heavy.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'EXPORTER_HEAVY';
12895 package Exporter::Heavy;
12896
12897 use strict;
12898 no strict 'refs';
12899
12900 # On one line so MakeMaker will see it.
12901 require Exporter; our $VERSION = $Exporter::VERSION;
12902
12903 =head1 NAME
12904
12905 Exporter::Heavy - Exporter guts
12906
12907 =head1 SYNOPSIS
12908
12909 (internal use only)
12910
12911 =head1 DESCRIPTION
12912
12913 No user-serviceable parts inside.
12914
12915 =cut
12916
12917 #
12918 # We go to a lot of trouble not to 'require Carp' at file scope,
12919 # because Carp requires Exporter, and something has to give.
12920 #
12921
12922 sub _rebuild_cache {
12923 my ($pkg, $exports, $cache) = @_;
12924 s/^&// foreach @$exports;
12925 @{$cache}{@$exports} = (1) x @$exports;
12926 my $ok = \@{"${pkg}::EXPORT_OK"};
12927 if (@$ok) {
12928 s/^&// foreach @$ok;
12929 @{$cache}{@$ok} = (1) x @$ok;
12930 }
12931 }
12932
12933 sub heavy_export {
12934
12935 # Save the old __WARN__ handler in case it was defined
12936 my $oldwarn = $SIG{__WARN__};
12937
12938 # First make import warnings look like they're coming from the "use".
12939 local $SIG{__WARN__} = sub {
12940 # restore it back so proper stacking occurs
12941 local $SIG{__WARN__} = $oldwarn;
12942 my $text = shift;
12943 if ($text =~ s/ at \S*Exporter\S*.pm line \d+.*\n//) {
12944 require Carp;
12945 local $Carp::CarpLevel = 1; # ignore package calling us too.
12946 Carp::carp($text);
12947 }
12948 else {
12949 warn $text;
12950 }
12951 };
12952 local $SIG{__DIE__} = sub {
12953 require Carp;
12954 local $Carp::CarpLevel = 1; # ignore package calling us too.
12955 Carp::croak("$_[0]Illegal null symbol in \@${1}::EXPORT")
12956 if $_[0] =~ /^Unable to create sub named "(.*?)::"/;
12957 };
12958
12959 my($pkg, $callpkg, @imports) = @_;
12960 my($type, $sym, $cache_is_current, $oops);
12961 my($exports, $export_cache) = (\@{"${pkg}::EXPORT"},
12962 $Exporter::Cache{$pkg} ||= {});
12963
12964 if (@imports) {
12965 if (!%$export_cache) {
12966 _rebuild_cache ($pkg, $exports, $export_cache);
12967 $cache_is_current = 1;
12968 }
12969
12970 if (grep m{^[/!:]}, @imports) {
12971 my $tagsref = \%{"${pkg}::EXPORT_TAGS"};
12972 my $tagdata;
12973 my %imports;
12974 my($remove, $spec, @names, @allexports);
12975 # negated first item implies starting with default set:
12976 unshift @imports, ':DEFAULT' if $imports[0] =~ m/^!/;
12977 foreach $spec (@imports){
12978 $remove = $spec =~ s/^!//;
12979
12980 if ($spec =~ s/^://){
12981 if ($spec eq 'DEFAULT'){
12982 @names = @$exports;
12983 }
12984 elsif ($tagdata = $tagsref->{$spec}) {
12985 @names = @$tagdata;
12986 }
12987 else {
12988 warn qq["$spec" is not defined in %${pkg}::EXPORT_TAGS];
12989 ++$oops;
12990 next;
12991 }
12992 }
12993 elsif ($spec =~ m:^/(.*)/$:){
12994 my $patn = $1;
12995 @allexports = keys %$export_cache unless @allexports; # only do keys once
12996 @names = grep(/$patn/, @allexports); # not anchored by default
12997 }
12998 else {
12999 @names = ($spec); # is a normal symbol name
13000 }
13001
13002 warn "Import ".($remove ? "del":"add").": @names "
13003 if $Exporter::Verbose;
13004
13005 if ($remove) {
13006 foreach $sym (@names) { delete $imports{$sym} }
13007 }
13008 else {
13009 @imports{@names} = (1) x @names;
13010 }
13011 }
13012 @imports = keys %imports;
13013 }
13014
13015 my @carp;
13016 foreach $sym (@imports) {
13017 if (!$export_cache->{$sym}) {
13018 if ($sym =~ m/^\d/) {
13019 $pkg->VERSION($sym); # inherit from UNIVERSAL
13020 # If the version number was the only thing specified
13021 # then we should act as if nothing was specified:
13022 if (@imports == 1) {
13023 @imports = @$exports;
13024 last;
13025 }
13026 # We need a way to emulate 'use Foo ()' but still
13027 # allow an easy version check: "use Foo 1.23, ''";
13028 if (@imports == 2 and !$imports[1]) {
13029 @imports = ();
13030 last;
13031 }
13032 } elsif ($sym !~ s/^&// || !$export_cache->{$sym}) {
13033 # Last chance - see if they've updated EXPORT_OK since we
13034 # cached it.
13035
13036 unless ($cache_is_current) {
13037 %$export_cache = ();
13038 _rebuild_cache ($pkg, $exports, $export_cache);
13039 $cache_is_current = 1;
13040 }
13041
13042 if (!$export_cache->{$sym}) {
13043 # accumulate the non-exports
13044 push @carp,
13045 qq["$sym" is not exported by the $pkg module\n];
13046 $oops++;
13047 }
13048 }
13049 }
13050 }
13051 if ($oops) {
13052 require Carp;
13053 Carp::croak("@{carp}Can't continue after import errors");
13054 }
13055 }
13056 else {
13057 @imports = @$exports;
13058 }
13059
13060 my($fail, $fail_cache) = (\@{"${pkg}::EXPORT_FAIL"},
13061 $Exporter::FailCache{$pkg} ||= {});
13062
13063 if (@$fail) {
13064 if (!%$fail_cache) {
13065 # Build cache of symbols. Optimise the lookup by adding
13066 # barewords twice... both with and without a leading &.
13067 # (Technique could be applied to $export_cache at cost of memory)
13068 my @expanded = map { /^\w/ ? ($_, '&'.$_) : $_ } @$fail;
13069 warn "${pkg}::EXPORT_FAIL cached: @expanded" if $Exporter::Verbose;
13070 @{$fail_cache}{@expanded} = (1) x @expanded;
13071 }
13072 my @failed;
13073 foreach $sym (@imports) { push(@failed, $sym) if $fail_cache->{$sym} }
13074 if (@failed) {
13075 @failed = $pkg->export_fail(@failed);
13076 foreach $sym (@failed) {
13077 require Carp;
13078 Carp::carp(qq["$sym" is not implemented by the $pkg module ],
13079 "on this architecture");
13080 }
13081 if (@failed) {
13082 require Carp;
13083 Carp::croak("Can't continue after import errors");
13084 }
13085 }
13086 }
13087
13088 warn "Importing into $callpkg from $pkg: ",
13089 join(", ",sort @imports) if $Exporter::Verbose;
13090
13091 foreach $sym (@imports) {
13092 # shortcut for the common case of no type character
13093 (*{"${callpkg}::$sym"} = \&{"${pkg}::$sym"}, next)
13094 unless $sym =~ s/^(\W)//;
13095 $type = $1;
13096 no warnings 'once';
13097 *{"${callpkg}::$sym"} =
13098 $type eq '&' ? \&{"${pkg}::$sym"} :
13099 $type eq '$' ? \${"${pkg}::$sym"} :
13100 $type eq '@' ? \@{"${pkg}::$sym"} :
13101 $type eq '%' ? \%{"${pkg}::$sym"} :
13102 $type eq '*' ? *{"${pkg}::$sym"} :
13103 do { require Carp; Carp::croak("Can't export symbol: $type$sym") };
13104 }
13105 }
13106
13107 sub heavy_export_to_level
13108 {
13109 my $pkg = shift;
13110 my $level = shift;
13111 (undef) = shift; # XXX redundant arg
13112 my $callpkg = caller($level);
13113 $pkg->export($callpkg, @_);
13114 }
13115
13116 # Utility functions
13117
13118 sub _push_tags {
13119 my($pkg, $var, $syms) = @_;
13120 my @nontag = ();
13121 my $export_tags = \%{"${pkg}::EXPORT_TAGS"};
13122 push(@{"${pkg}::$var"},
13123 map { $export_tags->{$_} ? @{$export_tags->{$_}}
13124 : scalar(push(@nontag,$_),$_) }
13125 (@$syms) ? @$syms : keys %$export_tags);
13126 if (@nontag and $^W) {
13127 # This may change to a die one day
13128 require Carp;
13129 Carp::carp(join(", ", @nontag)." are not tags of $pkg");
13130 }
13131 }
13132
13133 sub heavy_require_version {
13134 my($self, $wanted) = @_;
13135 my $pkg = ref $self || $self;
13136 return ${pkg}->VERSION($wanted);
13137 }
13138
13139 sub heavy_export_tags {
13140 _push_tags((caller)[0], "EXPORT", \@_);
13141 }
13142
13143 sub heavy_export_ok_tags {
13144 _push_tags((caller)[0], "EXPORT_OK", \@_);
13145 }
13146
13147 1;
13148 EXPORTER_HEAVY
13149  
13150 $fatpacked{"File/pushd.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'FILE_PUSHD';
13151 use strict;
13152 use warnings;
13153
13154 package File::pushd;
13155 # ABSTRACT: change directory temporarily for a limited scope
13156 our $VERSION = '1.009'; # VERSION
13157
13158 our @EXPORT = qw( pushd tempd );
13159 our @ISA = qw( Exporter );
13160
13161 use Exporter;
13162 use Carp;
13163 use Cwd qw( getcwd abs_path );
13164 use File::Path qw( rmtree );
13165 use File::Temp qw();
13166 use File::Spec;
13167
13168 use overload
13169 q{""} => sub { File::Spec->canonpath( $_[0]->{_pushd} ) },
13170 fallback => 1;
13171
13172 #--------------------------------------------------------------------------#
13173 # pushd()
13174 #--------------------------------------------------------------------------#
13175
13176 sub pushd {
13177 my ( $target_dir, $options ) = @_;
13178 $options->{untaint_pattern} ||= qr{^([-+@\w./]+)$};
13179
13180 $target_dir = "." unless defined $target_dir;
13181 croak "Can't locate directory $target_dir" unless -d $target_dir;
13182
13183 my $tainted_orig = getcwd;
13184 my $orig;
13185 if ( $tainted_orig =~ $options->{untaint_pattern} ) {
13186 $orig = $1;
13187 }
13188 else {
13189 $orig = $tainted_orig;
13190 }
13191
13192 my $tainted_dest;
13193 eval { $tainted_dest = $target_dir ? abs_path($target_dir) : $orig };
13194 croak "Can't locate absolute path for $target_dir: $@" if $@;
13195
13196 my $dest;
13197 if ( $tainted_dest =~ $options->{untaint_pattern} ) {
13198 $dest = $1;
13199 }
13200 else {
13201 $dest = $tainted_dest;
13202 }
13203
13204 if ( $dest ne $orig ) {
13205 chdir $dest or croak "Can't chdir to $dest\: $!";
13206 }
13207
13208 my $self = bless {
13209 _pushd => $dest,
13210 _original => $orig
13211 },
13212 __PACKAGE__;
13213
13214 return $self;
13215 }
13216
13217 #--------------------------------------------------------------------------#
13218 # tempd()
13219 #--------------------------------------------------------------------------#
13220
13221 sub tempd {
13222 my ($options) = @_;
13223 my $dir;
13224 eval { $dir = pushd( File::Temp::tempdir( CLEANUP => 0 ), $options ) };
13225 croak $@ if $@;
13226 $dir->{_tempd} = 1;
13227 return $dir;
13228 }
13229
13230 #--------------------------------------------------------------------------#
13231 # preserve()
13232 #--------------------------------------------------------------------------#
13233
13234 sub preserve {
13235 my $self = shift;
13236 return 1 if !$self->{"_tempd"};
13237 if ( @_ == 0 ) {
13238 return $self->{_preserve} = 1;
13239 }
13240 else {
13241 return $self->{_preserve} = $_[0] ? 1 : 0;
13242 }
13243 }
13244
13245 #--------------------------------------------------------------------------#
13246 # DESTROY()
13247 # Revert to original directory as object is destroyed and cleanup
13248 # if necessary
13249 #--------------------------------------------------------------------------#
13250
13251 sub DESTROY {
13252 my ($self) = @_;
13253 my $orig = $self->{_original};
13254 chdir $orig if $orig; # should always be so, but just in case...
13255 if ( $self->{_tempd}
13256 && !$self->{_preserve} )
13257 {
13258 # don't destroy existing $@ if there is no error.
13259 my $err = do {
13260 local $@;
13261 eval { rmtree( $self->{_pushd} ) };
13262 $@;
13263 };
13264 carp $err if $err;
13265 }
13266 }
13267
13268 1;
13269
13270 =pod
13271
13272 =encoding UTF-8
13273
13274 =head1 NAME
13275
13276 File::pushd - change directory temporarily for a limited scope
13277
13278 =head1 VERSION
13279
13280 version 1.009
13281
13282 =head1 SYNOPSIS
13283
13284 use File::pushd;
13285
13286 chdir $ENV{HOME};
13287
13288 # change directory again for a limited scope
13289 {
13290 my $dir = pushd( '/tmp' );
13291 # working directory changed to /tmp
13292 }
13293 # working directory has reverted to $ENV{HOME}
13294
13295 # tempd() is equivalent to pushd( File::Temp::tempdir )
13296 {
13297 my $dir = tempd();
13298 }
13299
13300 # object stringifies naturally as an absolute path
13301 {
13302 my $dir = pushd( '/tmp' );
13303 my $filename = File::Spec->catfile( $dir, "somefile.txt" );
13304 # gives /tmp/somefile.txt
13305 }
13306
13307 =head1 DESCRIPTION
13308
13309 File::pushd does a temporary C<chdir> that is easily and automatically
13310 reverted, similar to C<pushd> in some Unix command shells. It works by
13311 creating an object that caches the original working directory. When the object
13312 is destroyed, the destructor calls C<chdir> to revert to the original working
13313 directory. By storing the object in a lexical variable with a limited scope,
13314 this happens automatically at the end of the scope.
13315
13316 This is very handy when working with temporary directories for tasks like
13317 testing; a function is provided to streamline getting a temporary
13318 directory from L<File::Temp>.
13319
13320 For convenience, the object stringifies as the canonical form of the absolute
13321 pathname of the directory entered.
13322
13323 B<Warning>: if you create multiple C<pushd> objects in the same lexical scope,
13324 their destruction order is not guaranteed and you might not wind up in the
13325 directory you expect.
13326
13327 =head1 USAGE
13328
13329 use File::pushd;
13330
13331 Using File::pushd automatically imports the C<pushd> and C<tempd> functions.
13332
13333 =head2 pushd
13334
13335 {
13336 my $dir = pushd( $target_directory );
13337 }
13338
13339 Caches the current working directory, calls C<chdir> to change to the target
13340 directory, and returns a File::pushd object. When the object is
13341 destroyed, the working directory reverts to the original directory.
13342
13343 The provided target directory can be a relative or absolute path. If
13344 called with no arguments, it uses the current directory as its target and
13345 returns to the current directory when the object is destroyed.
13346
13347 If the target directory does not exist or if the directory change fails
13348 for some reason, C<pushd> will die with an error message.
13349
13350 Can be given a hashref as an optional second argument. The only supported
13351 option is C<untaint_pattern>, which is used to untaint file paths involved.
13352 It defaults to {qr{^(L<-+@\w./>+)$}}, which is reasonably restrictive (e.g.
13353 it does not even allow spaces in the path). Change this to suit your
13354 circumstances and security needs if running under taint mode. *Note*: you
13355 must include the parentheses in the pattern to capture the untainted
13356 portion of the path.
13357
13358 =head2 tempd
13359
13360 {
13361 my $dir = tempd();
13362 }
13363
13364 This function is like C<pushd> but automatically creates and calls C<chdir> to
13365 a temporary directory created by L<File::Temp>. Unlike normal L<File::Temp>
13366 cleanup which happens at the end of the program, this temporary directory is
13367 removed when the object is destroyed. (But also see C<preserve>.) A warning
13368 will be issued if the directory cannot be removed.
13369
13370 As with C<pushd>, C<tempd> will die if C<chdir> fails.
13371
13372 It may be given a single options hash that will be passed internally
13373 to C<pushd>.
13374
13375 =head2 preserve
13376
13377 {
13378 my $dir = tempd();
13379 $dir->preserve; # mark to preserve at end of scope
13380 $dir->preserve(0); # mark to delete at end of scope
13381 }
13382
13383 Controls whether a temporary directory will be cleaned up when the object is
13384 destroyed. With no arguments, C<preserve> sets the directory to be preserved.
13385 With an argument, the directory will be preserved if the argument is true, or
13386 marked for cleanup if the argument is false. Only C<tempd> objects may be
13387 marked for cleanup. (Target directories to C<pushd> are always preserved.)
13388 C<preserve> returns true if the directory will be preserved, and false
13389 otherwise.
13390
13391 =head1 SEE ALSO
13392
13393 =over 4
13394
13395 =item *
13396
13397 L<File::chdir>
13398
13399 =back
13400
13401 =for :stopwords cpan testmatrix url annocpan anno bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan
13402
13403 =head1 SUPPORT
13404
13405 =head2 Bugs / Feature Requests
13406
13407 Please report any bugs or feature requests through the issue tracker
13408 at L<https://github.com/dagolden/File-pushd/issues>.
13409 You will be notified automatically of any progress on your issue.
13410
13411 =head2 Source Code
13412
13413 This is open source software. The code repository is available for
13414 public review and contribution under the terms of the license.
13415
13416 L<https://github.com/dagolden/File-pushd>
13417
13418 git clone https://github.com/dagolden/File-pushd.git
13419
13420 =head1 AUTHOR
13421
13422 David Golden <dagolden@cpan.org>
13423
13424 =head1 CONTRIBUTORS
13425
13426 =over 4
13427
13428 =item *
13429
13430 Diab Jerius <djerius@cfa.harvard.edu>
13431
13432 =item *
13433
13434 Graham Ollis <plicease@cpan.org>
13435
13436 =back
13437
13438 =head1 COPYRIGHT AND LICENSE
13439
13440 This software is Copyright (c) 2014 by David A Golden.
13441
13442 This is free software, licensed under:
13443
13444 The Apache License, Version 2.0, January 2004
13445
13446 =cut
13447
13448 __END__
13449
13450
13451 # vim: ts=4 sts=4 sw=4 et:
13452 FILE_PUSHD
13453  
13454 $fatpacked{"HTTP/Tiny.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'HTTP_TINY';
13455 # vim: ts=4 sts=4 sw=4 et:
13456 package HTTP::Tiny;
13457 use strict;
13458 use warnings;
13459 # ABSTRACT: A small, simple, correct HTTP/1.1 client
13460
13461 our $VERSION = '0.056';
13462
13463 use Carp ();
13464
13465 #pod =method new
13466 #pod
13467 #pod $http = HTTP::Tiny->new( %attributes );
13468 #pod
13469 #pod This constructor returns a new HTTP::Tiny object. Valid attributes include:
13470 #pod
13471 #pod =for :list
13472 #pod * C<agent> —
13473 #pod A user-agent string (defaults to 'HTTP-Tiny/$VERSION'). If C<agent> — ends in a space character, the default user-agent string is appended.
13474 #pod * C<cookie_jar> —
13475 #pod An instance of L<HTTP::CookieJar> — or equivalent class that supports the C<add> and C<cookie_header> methods
13476 #pod * C<default_headers> —
13477 #pod A hashref of default headers to apply to requests
13478 #pod * C<local_address> —
13479 #pod The local IP address to bind to
13480 #pod * C<keep_alive> —
13481 #pod Whether to reuse the last connection (if for the same scheme, host and port) (defaults to 1)
13482 #pod * C<max_redirect> —
13483 #pod Maximum number of redirects allowed (defaults to 5)
13484 #pod * C<max_size> —
13485 #pod Maximum response size in bytes (only when not using a data callback). If defined, responses larger than this will return an exception.
13486 #pod * C<http_proxy> —
13487 #pod URL of a proxy server to use for HTTP connections (default is C<$ENV{http_proxy}> — if set)
13488 #pod * C<https_proxy> —
13489 #pod URL of a proxy server to use for HTTPS connections (default is C<$ENV{https_proxy}> — if set)
13490 #pod * C<proxy> —
13491 #pod URL of a generic proxy server for both HTTP and HTTPS connections (default is C<$ENV{all_proxy}> — if set)
13492 #pod * C<no_proxy> —
13493 #pod 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}> —)
13494 #pod * C<timeout> —
13495 #pod Request timeout in seconds (default is 60)
13496 #pod * C<verify_SSL> —
13497 #pod A boolean that indicates whether to validate the SSL certificate of an C<https> —
13498 #pod connection (default is false)
13499 #pod * C<SSL_options> —
13500 #pod A hashref of C<SSL_*> — options to pass through to L<IO::Socket::SSL>
13501 #pod
13502 #pod Passing an explicit C<undef> for C<proxy>, C<http_proxy> or C<https_proxy> will
13503 #pod prevent getting the corresponding proxies from the environment.
13504 #pod
13505 #pod Exceptions from C<max_size>, C<timeout> or other errors will result in a
13506 #pod pseudo-HTTP status code of 599 and a reason of "Internal Exception". The
13507 #pod content field in the response will contain the text of the exception.
13508 #pod
13509 #pod The C<keep_alive> parameter enables a persistent connection, but only to a
13510 #pod single destination scheme, host and port. Also, if any connection-relevant
13511 #pod attributes are modified, or if the process ID or thread ID change, the
13512 #pod persistent connection will be dropped. If you want persistent connections
13513 #pod across multiple destinations, use multiple HTTP::Tiny objects.
13514 #pod
13515 #pod See L</SSL SUPPORT> for more on the C<verify_SSL> and C<SSL_options> attributes.
13516 #pod
13517 #pod =cut
13518
13519 my @attributes;
13520 BEGIN {
13521 @attributes = qw(
13522 cookie_jar default_headers http_proxy https_proxy keep_alive
13523 local_address max_redirect max_size proxy no_proxy timeout
13524 SSL_options verify_SSL
13525 );
13526 my %persist_ok = map {; $_ => 1 } qw(
13527 cookie_jar default_headers max_redirect max_size
13528 );
13529 no strict 'refs';
13530 no warnings 'uninitialized';
13531 for my $accessor ( @attributes ) {
13532 *{$accessor} = sub {
13533 @_ > 1
13534 ? do {
13535 delete $_[0]->{handle} if !$persist_ok{$accessor} && $_[1] ne $_[0]->{$accessor};
13536 $_[0]->{$accessor} = $_[1]
13537 }
13538 : $_[0]->{$accessor};
13539 };
13540 }
13541 }
13542
13543 sub agent {
13544 my($self, $agent) = @_;
13545 if( @_ > 1 ){
13546 $self->{agent} =
13547 (defined $agent && $agent =~ / $/) ? $agent . $self->_agent : $agent;
13548 }
13549 return $self->{agent};
13550 }
13551
13552 sub new {
13553 my($class, %args) = @_;
13554
13555 my $self = {
13556 max_redirect => 5,
13557 timeout => 60,
13558 keep_alive => 1,
13559 verify_SSL => $args{verify_SSL} || $args{verify_ssl} || 0, # no verification by default
13560 no_proxy => $ENV{no_proxy},
13561 };
13562
13563 bless $self, $class;
13564
13565 $class->_validate_cookie_jar( $args{cookie_jar} ) if $args{cookie_jar};
13566
13567 for my $key ( @attributes ) {
13568 $self->{$key} = $args{$key} if exists $args{$key}
13569 }
13570
13571 $self->agent( exists $args{agent} ? $args{agent} : $class->_agent );
13572
13573 $self->_set_proxies;
13574
13575 return $self;
13576 }
13577
13578 sub _set_proxies {
13579 my ($self) = @_;
13580
13581 # get proxies from %ENV only if not provided; explicit undef will disable
13582 # getting proxies from the environment
13583
13584 # generic proxy
13585 if (! exists $self->{proxy} ) {
13586 $self->{proxy} = $ENV{all_proxy} || $ENV{ALL_PROXY};
13587 }
13588
13589 if ( defined $self->{proxy} ) {
13590 $self->_split_proxy( 'generic proxy' => $self->{proxy} ); # validate
13591 }
13592 else {
13593 delete $self->{proxy};
13594 }
13595
13596 # http proxy
13597 if (! exists $self->{http_proxy} ) {
13598 # under CGI, bypass HTTP_PROXY as request sets it from Proxy header
13599 local $ENV{HTTP_PROXY} if $ENV{REQUEST_METHOD};
13600 $self->{http_proxy} = $ENV{http_proxy} || $ENV{HTTP_PROXY} || $self->{proxy};
13601 }
13602
13603 if ( defined $self->{http_proxy} ) {
13604 $self->_split_proxy( http_proxy => $self->{http_proxy} ); # validate
13605 $self->{_has_proxy}{http} = 1;
13606 }
13607 else {
13608 delete $self->{http_proxy};
13609 }
13610
13611 # https proxy
13612 if (! exists $self->{https_proxy} ) {
13613 $self->{https_proxy} = $ENV{https_proxy} || $ENV{HTTPS_PROXY} || $self->{proxy};
13614 }
13615
13616 if ( $self->{https_proxy} ) {
13617 $self->_split_proxy( https_proxy => $self->{https_proxy} ); # validate
13618 $self->{_has_proxy}{https} = 1;
13619 }
13620 else {
13621 delete $self->{https_proxy};
13622 }
13623
13624 # Split no_proxy to array reference if not provided as such
13625 unless ( ref $self->{no_proxy} eq 'ARRAY' ) {
13626 $self->{no_proxy} =
13627 (defined $self->{no_proxy}) ? [ split /\s*,\s*/, $self->{no_proxy} ] : [];
13628 }
13629
13630 return;
13631 }
13632
13633 #pod =method get|head|put|post|delete
13634 #pod
13635 #pod $response = $http->get($url);
13636 #pod $response = $http->get($url, \%options);
13637 #pod $response = $http->head($url);
13638 #pod
13639 #pod These methods are shorthand for calling C<request()> for the given method. The
13640 #pod URL must have unsafe characters escaped and international domain names encoded.
13641 #pod See C<request()> for valid options and a description of the response.
13642 #pod
13643 #pod The C<success> field of the response will be true if the status code is 2XX.
13644 #pod
13645 #pod =cut
13646
13647 for my $sub_name ( qw/get head put post delete/ ) {
13648 my $req_method = uc $sub_name;
13649 no strict 'refs';
13650 eval <<"HERE"; ## no critic
13651 sub $sub_name {
13652 my (\$self, \$url, \$args) = \@_;
13653 \@_ == 2 || (\@_ == 3 && ref \$args eq 'HASH')
13654 or Carp::croak(q/Usage: \$http->$sub_name(URL, [HASHREF])/ . "\n");
13655 return \$self->request('$req_method', \$url, \$args || {});
13656 }
13657 HERE
13658 }
13659
13660 #pod =method post_form
13661 #pod
13662 #pod $response = $http->post_form($url, $form_data);
13663 #pod $response = $http->post_form($url, $form_data, \%options);
13664 #pod
13665 #pod This method executes a C<POST> request and sends the key/value pairs from a
13666 #pod form data hash or array reference to the given URL with a C<content-type> of
13667 #pod C<application/x-www-form-urlencoded>. If data is provided as an array
13668 #pod reference, the order is preserved; if provided as a hash reference, the terms
13669 #pod are sorted on key and value for consistency. See documentation for the
13670 #pod C<www_form_urlencode> method for details on the encoding.
13671 #pod
13672 #pod The URL must have unsafe characters escaped and international domain names
13673 #pod encoded. See C<request()> for valid options and a description of the response.
13674 #pod Any C<content-type> header or content in the options hashref will be ignored.
13675 #pod
13676 #pod The C<success> field of the response will be true if the status code is 2XX.
13677 #pod
13678 #pod =cut
13679
13680 sub post_form {
13681 my ($self, $url, $data, $args) = @_;
13682 (@_ == 3 || @_ == 4 && ref $args eq 'HASH')
13683 or Carp::croak(q/Usage: $http->post_form(URL, DATAREF, [HASHREF])/ . "\n");
13684
13685 my $headers = {};
13686 while ( my ($key, $value) = each %{$args->{headers} || {}} ) {
13687 $headers->{lc $key} = $value;
13688 }
13689 delete $args->{headers};
13690
13691 return $self->request('POST', $url, {
13692 %$args,
13693 content => $self->www_form_urlencode($data),
13694 headers => {
13695 %$headers,
13696 'content-type' => 'application/x-www-form-urlencoded'
13697 },
13698 }
13699 );
13700 }
13701
13702 #pod =method mirror
13703 #pod
13704 #pod $response = $http->mirror($url, $file, \%options)
13705 #pod if ( $response->{success} ) {
13706 #pod print "$file is up to date\n";
13707 #pod }
13708 #pod
13709 #pod Executes a C<GET> request for the URL and saves the response body to the file
13710 #pod name provided. The URL must have unsafe characters escaped and international
13711 #pod domain names encoded. If the file already exists, the request will include an
13712 #pod C<If-Modified-Since> header with the modification timestamp of the file. You
13713 #pod may specify a different C<If-Modified-Since> header yourself in the C<<
13714 #pod $options->{headers} >> hash.
13715 #pod
13716 #pod The C<success> field of the response will be true if the status code is 2XX
13717 #pod or if the status code is 304 (unmodified).
13718 #pod
13719 #pod If the file was modified and the server response includes a properly
13720 #pod formatted C<Last-Modified> header, the file modification time will
13721 #pod be updated accordingly.
13722 #pod
13723 #pod =cut
13724
13725 sub mirror {
13726 my ($self, $url, $file, $args) = @_;
13727 @_ == 3 || (@_ == 4 && ref $args eq 'HASH')
13728 or Carp::croak(q/Usage: $http->mirror(URL, FILE, [HASHREF])/ . "\n");
13729 if ( -e $file and my $mtime = (stat($file))[9] ) {
13730 $args->{headers}{'if-modified-since'} ||= $self->_http_date($mtime);
13731 }
13732 my $tempfile = $file . int(rand(2**31));
13733
13734 require Fcntl;
13735 sysopen my $fh, $tempfile, Fcntl::O_CREAT()|Fcntl::O_EXCL()|Fcntl::O_WRONLY()
13736 or Carp::croak(qq/Error: Could not create temporary file $tempfile for downloading: $!\n/);
13737 binmode $fh;
13738 $args->{data_callback} = sub { print {$fh} $_[0] };
13739 my $response = $self->request('GET', $url, $args);
13740 close $fh
13741 or Carp::croak(qq/Error: Caught error closing temporary file $tempfile: $!\n/);
13742
13743 if ( $response->{success} ) {
13744 rename $tempfile, $file
13745 or Carp::croak(qq/Error replacing $file with $tempfile: $!\n/);
13746 my $lm = $response->{headers}{'last-modified'};
13747 if ( $lm and my $mtime = $self->_parse_http_date($lm) ) {
13748 utime $mtime, $mtime, $file;
13749 }
13750 }
13751 $response->{success} ||= $response->{status} eq '304';
13752 unlink $tempfile;
13753 return $response;
13754 }
13755
13756 #pod =method request
13757 #pod
13758 #pod $response = $http->request($method, $url);
13759 #pod $response = $http->request($method, $url, \%options);
13760 #pod
13761 #pod Executes an HTTP request of the given method type ('GET', 'HEAD', 'POST',
13762 #pod 'PUT', etc.) on the given URL. The URL must have unsafe characters escaped and
13763 #pod international domain names encoded.
13764 #pod
13765 #pod If the URL includes a "user:password" stanza, they will be used for Basic-style
13766 #pod authorization headers. (Authorization headers will not be included in a
13767 #pod redirected request.) For example:
13768 #pod
13769 #pod $http->request('GET', 'http://Aladdin:open sesame@example.com/');
13770 #pod
13771 #pod If the "user:password" stanza contains reserved characters, they must
13772 #pod be percent-escaped:
13773 #pod
13774 #pod $http->request('GET', 'http://john%40example.com:password@example.com/');
13775 #pod
13776 #pod A hashref of options may be appended to modify the request.
13777 #pod
13778 #pod Valid options are:
13779 #pod
13780 #pod =for :list
13781 #pod * C<headers> —
13782 #pod A hashref containing headers to include with the request. If the value for
13783 #pod a header is an array reference, the header will be output multiple times with
13784 #pod each value in the array. These headers over-write any default headers.
13785 #pod * C<content> —
13786 #pod A scalar to include as the body of the request OR a code reference
13787 #pod that will be called iteratively to produce the body of the request
13788 #pod * C<trailer_callback> —
13789 #pod A code reference that will be called if it exists to provide a hashref
13790 #pod of trailing headers (only used with chunked transfer-encoding)
13791 #pod * C<data_callback> —
13792 #pod A code reference that will be called for each chunks of the response
13793 #pod body received.
13794 #pod
13795 #pod The C<Host> header is generated from the URL in accordance with RFC 2616. It
13796 #pod is a fatal error to specify C<Host> in the C<headers> option. Other headers
13797 #pod may be ignored or overwritten if necessary for transport compliance.
13798 #pod
13799 #pod If the C<content> option is a code reference, it will be called iteratively
13800 #pod to provide the content body of the request. It should return the empty
13801 #pod string or undef when the iterator is exhausted.
13802 #pod
13803 #pod If the C<content> option is the empty string, no C<content-type> or
13804 #pod C<content-length> headers will be generated.
13805 #pod
13806 #pod If the C<data_callback> option is provided, it will be called iteratively until
13807 #pod the entire response body is received. The first argument will be a string
13808 #pod containing a chunk of the response body, the second argument will be the
13809 #pod in-progress response hash reference, as described below. (This allows
13810 #pod customizing the action of the callback based on the C<status> or C<headers>
13811 #pod received prior to the content body.)
13812 #pod
13813 #pod The C<request> method returns a hashref containing the response. The hashref
13814 #pod will have the following keys:
13815 #pod
13816 #pod =for :list
13817 #pod * C<success> —
13818 #pod Boolean indicating whether the operation returned a 2XX status code
13819 #pod * C<url> —
13820 #pod URL that provided the response. This is the URL of the request unless
13821 #pod there were redirections, in which case it is the last URL queried
13822 #pod in a redirection chain
13823 #pod * C<status> —
13824 #pod The HTTP status code of the response
13825 #pod * C<reason> —
13826 #pod The response phrase returned by the server
13827 #pod * C<content> —
13828 #pod The body of the response. If the response does not have any content
13829 #pod or if a data callback is provided to consume the response body,
13830 #pod this will be the empty string
13831 #pod * C<headers> —
13832 #pod A hashref of header fields. All header field names will be normalized
13833 #pod to be lower case. If a header is repeated, the value will be an arrayref;
13834 #pod it will otherwise be a scalar string containing the value
13835 #pod
13836 #pod On an exception during the execution of the request, the C<status> field will
13837 #pod contain 599, and the C<content> field will contain the text of the exception.
13838 #pod
13839 #pod =cut
13840
13841 my %idempotent = map { $_ => 1 } qw/GET HEAD PUT DELETE OPTIONS TRACE/;
13842
13843 sub request {
13844 my ($self, $method, $url, $args) = @_;
13845 @_ == 3 || (@_ == 4 && ref $args eq 'HASH')
13846 or Carp::croak(q/Usage: $http->request(METHOD, URL, [HASHREF])/ . "\n");
13847 $args ||= {}; # we keep some state in this during _request
13848
13849 # RFC 2616 Section 8.1.4 mandates a single retry on broken socket
13850 my $response;
13851 for ( 0 .. 1 ) {
13852 $response = eval { $self->_request($method, $url, $args) };
13853 last unless $@ && $idempotent{$method}
13854 && $@ =~ m{^(?:Socket closed|Unexpected end)};
13855 }
13856
13857 if (my $e = $@) {
13858 # maybe we got a response hash thrown from somewhere deep
13859 if ( ref $e eq 'HASH' && exists $e->{status} ) {
13860 return $e;
13861 }
13862
13863 # otherwise, stringify it
13864 $e = "$e";
13865 $response = {
13866 url => $url,
13867 success => q{},
13868 status => 599,
13869 reason => 'Internal Exception',
13870 content => $e,
13871 headers => {
13872 'content-type' => 'text/plain',
13873 'content-length' => length $e,
13874 }
13875 };
13876 }
13877 return $response;
13878 }
13879
13880 #pod =method www_form_urlencode
13881 #pod
13882 #pod $params = $http->www_form_urlencode( $data );
13883 #pod $response = $http->get("http://example.com/query?$params");
13884 #pod
13885 #pod This method converts the key/value pairs from a data hash or array reference
13886 #pod into a C<x-www-form-urlencoded> string. The keys and values from the data
13887 #pod reference will be UTF-8 encoded and escaped per RFC 3986. If a value is an
13888 #pod array reference, the key will be repeated with each of the values of the array
13889 #pod reference. If data is provided as a hash reference, the key/value pairs in the
13890 #pod resulting string will be sorted by key and value for consistent ordering.
13891 #pod
13892 #pod =cut
13893
13894 sub www_form_urlencode {
13895 my ($self, $data) = @_;
13896 (@_ == 2 && ref $data)
13897 or Carp::croak(q/Usage: $http->www_form_urlencode(DATAREF)/ . "\n");
13898 (ref $data eq 'HASH' || ref $data eq 'ARRAY')
13899 or Carp::croak("form data must be a hash or array reference\n");
13900
13901 my @params = ref $data eq 'HASH' ? %$data : @$data;
13902 @params % 2 == 0
13903 or Carp::croak("form data reference must have an even number of terms\n");
13904
13905 my @terms;
13906 while( @params ) {
13907 my ($key, $value) = splice(@params, 0, 2);
13908 if ( ref $value eq 'ARRAY' ) {
13909 unshift @params, map { $key => $_ } @$value;
13910 }
13911 else {
13912 push @terms, join("=", map { $self->_uri_escape($_) } $key, $value);
13913 }
13914 }
13915
13916 return join("&", (ref $data eq 'ARRAY') ? (@terms) : (sort @terms) );
13917 }
13918
13919 #pod =method can_ssl
13920 #pod
13921 #pod $ok = HTTP::Tiny->can_ssl;
13922 #pod ($ok, $why) = HTTP::Tiny->can_ssl;
13923 #pod ($ok, $why) = $http->can_ssl;
13924 #pod
13925 #pod Indicates if SSL support is available. When called as a class object, it
13926 #pod checks for the correct version of L<Net::SSLeay> and L<IO::Socket::SSL>.
13927 #pod When called as an object methods, if C<SSL_verify> is true or if C<SSL_verify_mode>
13928 #pod is set in C<SSL_options>, it checks that a CA file is available.
13929 #pod
13930 #pod In scalar context, returns a boolean indicating if SSL is available.
13931 #pod In list context, returns the boolean and a (possibly multi-line) string of
13932 #pod errors indicating why SSL isn't available.
13933 #pod
13934 #pod =cut
13935
13936 sub can_ssl {
13937 my ($self) = @_;
13938
13939 my($ok, $reason) = (1, '');
13940
13941 # Need IO::Socket::SSL 1.42 for SSL_create_ctx_callback
13942 unless (eval {require IO::Socket::SSL; IO::Socket::SSL->VERSION(1.42)}) {
13943 $ok = 0;
13944 $reason .= qq/IO::Socket::SSL 1.42 must be installed for https support\n/;
13945 }
13946
13947 # Need Net::SSLeay 1.49 for MODE_AUTO_RETRY
13948 unless (eval {require Net::SSLeay; Net::SSLeay->VERSION(1.49)}) {
13949 $ok = 0;
13950 $reason .= qq/Net::SSLeay 1.49 must be installed for https support\n/;
13951 }
13952
13953 # If an object, check that SSL config lets us get a CA if necessary
13954 if ( ref($self) && ( $self->{verify_SSL} || $self->{SSL_options}{SSL_verify_mode} ) ) {
13955 my $handle = HTTP::Tiny::Handle->new(
13956 SSL_options => $self->{SSL_options},
13957 verify_SSL => $self->{verify_SSL},
13958 );
13959 unless ( eval { $handle->_find_CA_file; 1 } ) {
13960 $ok = 0;
13961 $reason .= "$@";
13962 }
13963 }
13964
13965 wantarray ? ($ok, $reason) : $ok;
13966 }
13967
13968 #--------------------------------------------------------------------------#
13969 # private methods
13970 #--------------------------------------------------------------------------#
13971
13972 my %DefaultPort = (
13973 http => 80,
13974 https => 443,
13975 );
13976
13977 sub _agent {
13978 my $class = ref($_[0]) || $_[0];
13979 (my $default_agent = $class) =~ s{::}{-}g;
13980 return $default_agent . "/" . $class->VERSION;
13981 }
13982
13983 sub _request {
13984 my ($self, $method, $url, $args) = @_;
13985
13986 my ($scheme, $host, $port, $path_query, $auth) = $self->_split_url($url);
13987
13988 my $request = {
13989 method => $method,
13990 scheme => $scheme,
13991 host => $host,
13992 port => $port,
13993 host_port => ($port == $DefaultPort{$scheme} ? $host : "$host:$port"),
13994 uri => $path_query,
13995 headers => {},
13996 };
13997
13998 # We remove the cached handle so it is not reused in the case of redirect.
13999 # If all is well, it will be recached at the end of _request. We only
14000 # reuse for the same scheme, host and port
14001 my $handle = delete $self->{handle};
14002 if ( $handle ) {
14003 unless ( $handle->can_reuse( $scheme, $host, $port ) ) {
14004 $handle->close;
14005 undef $handle;
14006 }
14007 }
14008 $handle ||= $self->_open_handle( $request, $scheme, $host, $port );
14009
14010 $self->_prepare_headers_and_cb($request, $args, $url, $auth);
14011 $handle->write_request($request);
14012
14013 my $response;
14014 do { $response = $handle->read_response_header }
14015 until (substr($response->{status},0,1) ne '1');
14016
14017 $self->_update_cookie_jar( $url, $response ) if $self->{cookie_jar};
14018
14019 if ( my @redir_args = $self->_maybe_redirect($request, $response, $args) ) {
14020 $handle->close;
14021 return $self->_request(@redir_args, $args);
14022 }
14023
14024 my $known_message_length;
14025 if ($method eq 'HEAD' || $response->{status} =~ /^[23]04/) {
14026 # response has no message body
14027 $known_message_length = 1;
14028 }
14029 else {
14030 my $data_cb = $self->_prepare_data_cb($response, $args);
14031 $known_message_length = $handle->read_body($data_cb, $response);
14032 }
14033
14034 if ( $self->{keep_alive}
14035 && $known_message_length
14036 && $response->{protocol} eq 'HTTP/1.1'
14037 && ($response->{headers}{connection} || '') ne 'close'
14038 ) {
14039 $self->{handle} = $handle;
14040 }
14041 else {
14042 $handle->close;
14043 }
14044
14045 $response->{success} = substr( $response->{status}, 0, 1 ) eq '2';
14046 $response->{url} = $url;
14047 return $response;
14048 }
14049
14050 sub _open_handle {
14051 my ($self, $request, $scheme, $host, $port) = @_;
14052
14053 my $handle = HTTP::Tiny::Handle->new(
14054 timeout => $self->{timeout},
14055 SSL_options => $self->{SSL_options},
14056 verify_SSL => $self->{verify_SSL},
14057 local_address => $self->{local_address},
14058 keep_alive => $self->{keep_alive}
14059 );
14060
14061 if ($self->{_has_proxy}{$scheme} && ! grep { $host =~ /\Q$_\E$/ } @{$self->{no_proxy}}) {
14062 return $self->_proxy_connect( $request, $handle );
14063 }
14064 else {
14065 return $handle->connect($scheme, $host, $port);
14066 }
14067 }
14068
14069 sub _proxy_connect {
14070 my ($self, $request, $handle) = @_;
14071
14072 my @proxy_vars;
14073 if ( $request->{scheme} eq 'https' ) {
14074 Carp::croak(qq{No https_proxy defined}) unless $self->{https_proxy};
14075 @proxy_vars = $self->_split_proxy( https_proxy => $self->{https_proxy} );
14076 if ( $proxy_vars[0] eq 'https' ) {
14077 Carp::croak(qq{Can't proxy https over https: $request->{uri} via $self->{https_proxy}});
14078 }
14079 }
14080 else {
14081 Carp::croak(qq{No http_proxy defined}) unless $self->{http_proxy};
14082 @proxy_vars = $self->_split_proxy( http_proxy => $self->{http_proxy} );
14083 }
14084
14085 my ($p_scheme, $p_host, $p_port, $p_auth) = @proxy_vars;
14086
14087 if ( length $p_auth && ! defined $request->{headers}{'proxy-authorization'} ) {
14088 $self->_add_basic_auth_header( $request, 'proxy-authorization' => $p_auth );
14089 }
14090
14091 $handle->connect($p_scheme, $p_host, $p_port);
14092
14093 if ($request->{scheme} eq 'https') {
14094 $self->_create_proxy_tunnel( $request, $handle );
14095 }
14096 else {
14097 # non-tunneled proxy requires absolute URI
14098 $request->{uri} = "$request->{scheme}://$request->{host_port}$request->{uri}";
14099 }
14100
14101 return $handle;
14102 }
14103
14104 sub _split_proxy {
14105 my ($self, $type, $proxy) = @_;
14106
14107 my ($scheme, $host, $port, $path_query, $auth) = eval { $self->_split_url($proxy) };
14108
14109 unless(
14110 defined($scheme) && length($scheme) && length($host) && length($port)
14111 && $path_query eq '/'
14112 ) {
14113 Carp::croak(qq{$type URL must be in format http[s]://[auth@]<host>:<port>/\n});
14114 }
14115
14116 return ($scheme, $host, $port, $auth);
14117 }
14118
14119 sub _create_proxy_tunnel {
14120 my ($self, $request, $handle) = @_;
14121
14122 $handle->_assert_ssl;
14123
14124 my $agent = exists($request->{headers}{'user-agent'})
14125 ? $request->{headers}{'user-agent'} : $self->{agent};
14126
14127 my $connect_request = {
14128 method => 'CONNECT',
14129 uri => "$request->{host}:$request->{port}",
14130 headers => {
14131 host => "$request->{host}:$request->{port}",
14132 'user-agent' => $agent,
14133 }
14134 };
14135
14136 if ( $request->{headers}{'proxy-authorization'} ) {
14137 $connect_request->{headers}{'proxy-authorization'} =
14138 delete $request->{headers}{'proxy-authorization'};
14139 }
14140
14141 $handle->write_request($connect_request);
14142 my $response;
14143 do { $response = $handle->read_response_header }
14144 until (substr($response->{status},0,1) ne '1');
14145
14146 # if CONNECT failed, throw the response so it will be
14147 # returned from the original request() method;
14148 unless (substr($response->{status},0,1) eq '2') {
14149 die $response;
14150 }
14151
14152 # tunnel established, so start SSL handshake
14153 $handle->start_ssl( $request->{host} );
14154
14155 return;
14156 }
14157
14158 sub _prepare_headers_and_cb {
14159 my ($self, $request, $args, $url, $auth) = @_;
14160
14161 for ($self->{default_headers}, $args->{headers}) {
14162 next unless defined;
14163 while (my ($k, $v) = each %$_) {
14164 $request->{headers}{lc $k} = $v;
14165 }
14166 }
14167
14168 if (exists $request->{headers}{'host'}) {
14169 die(qq/The 'Host' header must not be provided as header option\n/);
14170 }
14171
14172 $request->{headers}{'host'} = $request->{host_port};
14173 $request->{headers}{'user-agent'} ||= $self->{agent};
14174 $request->{headers}{'connection'} = "close"
14175 unless $self->{keep_alive};
14176
14177 if ( defined $args->{content} ) {
14178 if (ref $args->{content} eq 'CODE') {
14179 $request->{headers}{'content-type'} ||= "application/octet-stream";
14180 $request->{headers}{'transfer-encoding'} = 'chunked'
14181 unless $request->{headers}{'content-length'}
14182 || $request->{headers}{'transfer-encoding'};
14183 $request->{cb} = $args->{content};
14184 }
14185 elsif ( length $args->{content} ) {
14186 my $content = $args->{content};
14187 if ( $] ge '5.008' ) {
14188 utf8::downgrade($content, 1)
14189 or die(qq/Wide character in request message body\n/);
14190 }
14191 $request->{headers}{'content-type'} ||= "application/octet-stream";
14192 $request->{headers}{'content-length'} = length $content
14193 unless $request->{headers}{'content-length'}
14194 || $request->{headers}{'transfer-encoding'};
14195 $request->{cb} = sub { substr $content, 0, length $content, '' };
14196 }
14197 $request->{trailer_cb} = $args->{trailer_callback}
14198 if ref $args->{trailer_callback} eq 'CODE';
14199 }
14200
14201 ### If we have a cookie jar, then maybe add relevant cookies
14202 if ( $self->{cookie_jar} ) {
14203 my $cookies = $self->cookie_jar->cookie_header( $url );
14204 $request->{headers}{cookie} = $cookies if length $cookies;
14205 }
14206
14207 # if we have Basic auth parameters, add them
14208 if ( length $auth && ! defined $request->{headers}{authorization} ) {
14209 $self->_add_basic_auth_header( $request, 'authorization' => $auth );
14210 }
14211
14212 return;
14213 }
14214
14215 sub _add_basic_auth_header {
14216 my ($self, $request, $header, $auth) = @_;
14217 require MIME::Base64;
14218 $request->{headers}{$header} =
14219 "Basic " . MIME::Base64::encode_base64($auth, "");
14220 return;
14221 }
14222
14223 sub _prepare_data_cb {
14224 my ($self, $response, $args) = @_;
14225 my $data_cb = $args->{data_callback};
14226 $response->{content} = '';
14227
14228 if (!$data_cb || $response->{status} !~ /^2/) {
14229 if (defined $self->{max_size}) {
14230 $data_cb = sub {
14231 $_[1]->{content} .= $_[0];
14232 die(qq/Size of response body exceeds the maximum allowed of $self->{max_size}\n/)
14233 if length $_[1]->{content} > $self->{max_size};
14234 };
14235 }
14236 else {
14237 $data_cb = sub { $_[1]->{content} .= $_[0] };
14238 }
14239 }
14240 return $data_cb;
14241 }
14242
14243 sub _update_cookie_jar {
14244 my ($self, $url, $response) = @_;
14245
14246 my $cookies = $response->{headers}->{'set-cookie'};
14247 return unless defined $cookies;
14248
14249 my @cookies = ref $cookies ? @$cookies : $cookies;
14250
14251 $self->cookie_jar->add( $url, $_ ) for @cookies;
14252
14253 return;
14254 }
14255
14256 sub _validate_cookie_jar {
14257 my ($class, $jar) = @_;
14258
14259 # duck typing
14260 for my $method ( qw/add cookie_header/ ) {
14261 Carp::croak(qq/Cookie jar must provide the '$method' method\n/)
14262 unless ref($jar) && ref($jar)->can($method);
14263 }
14264
14265 return;
14266 }
14267
14268 sub _maybe_redirect {
14269 my ($self, $request, $response, $args) = @_;
14270 my $headers = $response->{headers};
14271 my ($status, $method) = ($response->{status}, $request->{method});
14272 if (($status eq '303' or ($status =~ /^30[1278]/ && $method =~ /^GET|HEAD$/))
14273 and $headers->{location}
14274 and ++$args->{redirects} <= $self->{max_redirect}
14275 ) {
14276 my $location = ($headers->{location} =~ /^\//)
14277 ? "$request->{scheme}://$request->{host_port}$headers->{location}"
14278 : $headers->{location} ;
14279 return (($status eq '303' ? 'GET' : $method), $location);
14280 }
14281 return;
14282 }
14283
14284 sub _split_url {
14285 my $url = pop;
14286
14287 # URI regex adapted from the URI module
14288 my ($scheme, $host, $path_query) = $url =~ m<\A([^:/?#]+)://([^/?#]*)([^#]*)>
14289 or die(qq/Cannot parse URL: '$url'\n/);
14290
14291 $scheme = lc $scheme;
14292 $path_query = "/$path_query" unless $path_query =~ m<\A/>;
14293
14294 my $auth = '';
14295 if ( (my $i = index $host, '@') != -1 ) {
14296 # user:pass@host
14297 $auth = substr $host, 0, $i, ''; # take up to the @ for auth
14298 substr $host, 0, 1, ''; # knock the @ off the host
14299
14300 # userinfo might be percent escaped, so recover real auth info
14301 $auth =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
14302 }
14303 my $port = $host =~ s/:(\d*)\z// && length $1 ? $1
14304 : $scheme eq 'http' ? 80
14305 : $scheme eq 'https' ? 443
14306 : undef;
14307
14308 return ($scheme, (length $host ? lc $host : "localhost") , $port, $path_query, $auth);
14309 }
14310
14311 # Date conversions adapted from HTTP::Date
14312 my $DoW = "Sun|Mon|Tue|Wed|Thu|Fri|Sat";
14313 my $MoY = "Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec";
14314 sub _http_date {
14315 my ($sec, $min, $hour, $mday, $mon, $year, $wday) = gmtime($_[1]);
14316 return sprintf("%s, %02d %s %04d %02d:%02d:%02d GMT",
14317 substr($DoW,$wday*4,3),
14318 $mday, substr($MoY,$mon*4,3), $year+1900,
14319 $hour, $min, $sec
14320 );
14321 }
14322
14323 sub _parse_http_date {
14324 my ($self, $str) = @_;
14325 require Time::Local;
14326 my @tl_parts;
14327 if ($str =~ /^[SMTWF][a-z]+, +(\d{1,2}) ($MoY) +(\d\d\d\d) +(\d\d):(\d\d):(\d\d) +GMT$/) {
14328 @tl_parts = ($6, $5, $4, $1, (index($MoY,$2)/4), $3);
14329 }
14330 elsif ($str =~ /^[SMTWF][a-z]+, +(\d\d)-($MoY)-(\d{2,4}) +(\d\d):(\d\d):(\d\d) +GMT$/ ) {
14331 @tl_parts = ($6, $5, $4, $1, (index($MoY,$2)/4), $3);
14332 }
14333 elsif ($str =~ /^[SMTWF][a-z]+ +($MoY) +(\d{1,2}) +(\d\d):(\d\d):(\d\d) +(?:[^0-9]+ +)?(\d\d\d\d)$/ ) {
14334 @tl_parts = ($5, $4, $3, $2, (index($MoY,$1)/4), $6);
14335 }
14336 return eval {
14337 my $t = @tl_parts ? Time::Local::timegm(@tl_parts) : -1;
14338 $t < 0 ? undef : $t;
14339 };
14340 }
14341
14342 # URI escaping adapted from URI::Escape
14343 # c.f. http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
14344 # perl 5.6 ready UTF-8 encoding adapted from JSON::PP
14345 my %escapes = map { chr($_) => sprintf("%%%02X", $_) } 0..255;
14346 $escapes{' '}="+";
14347 my $unsafe_char = qr/[^A-Za-z0-9\-\._~]/;
14348
14349 sub _uri_escape {
14350 my ($self, $str) = @_;
14351 if ( $] ge '5.008' ) {
14352 utf8::encode($str);
14353 }
14354 else {
14355 $str = pack("U*", unpack("C*", $str)) # UTF-8 encode a byte string
14356 if ( length $str == do { use bytes; length $str } );
14357 $str = pack("C*", unpack("C*", $str)); # clear UTF-8 flag
14358 }
14359 $str =~ s/($unsafe_char)/$escapes{$1}/ge;
14360 return $str;
14361 }
14362
14363 package
14364 HTTP::Tiny::Handle; # hide from PAUSE/indexers
14365 use strict;
14366 use warnings;
14367
14368 use Errno qw[EINTR EPIPE];
14369 use IO::Socket qw[SOCK_STREAM];
14370
14371 # PERL_HTTP_TINY_IPV4_ONLY is a private environment variable to force old
14372 # behavior if someone is unable to boostrap CPAN from a new perl install; it is
14373 # not intended for general, per-client use and may be removed in the future
14374 my $SOCKET_CLASS =
14375 $ENV{PERL_HTTP_TINY_IPV4_ONLY} ? 'IO::Socket::INET' :
14376 eval { require IO::Socket::IP; IO::Socket::IP->VERSION(0.25) } ? 'IO::Socket::IP' :
14377 'IO::Socket::INET';
14378
14379 sub BUFSIZE () { 32768 } ## no critic
14380
14381 my $Printable = sub {
14382 local $_ = shift;
14383 s/\r/\\r/g;
14384 s/\n/\\n/g;
14385 s/\t/\\t/g;
14386 s/([^\x20-\x7E])/sprintf('\\x%.2X', ord($1))/ge;
14387 $_;
14388 };
14389
14390 my $Token = qr/[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E-\x7A\x7C\x7E]/;
14391
14392 sub new {
14393 my ($class, %args) = @_;
14394 return bless {
14395 rbuf => '',
14396 timeout => 60,
14397 max_line_size => 16384,
14398 max_header_lines => 64,
14399 verify_SSL => 0,
14400 SSL_options => {},
14401 %args
14402 }, $class;
14403 }
14404
14405 sub connect {
14406 @_ == 4 || die(q/Usage: $handle->connect(scheme, host, port)/ . "\n");
14407 my ($self, $scheme, $host, $port) = @_;
14408
14409 if ( $scheme eq 'https' ) {
14410 $self->_assert_ssl;
14411 }
14412 elsif ( $scheme ne 'http' ) {
14413 die(qq/Unsupported URL scheme '$scheme'\n/);
14414 }
14415 $self->{fh} = $SOCKET_CLASS->new(
14416 PeerHost => $host,
14417 PeerPort => $port,
14418 $self->{local_address} ?
14419 ( LocalAddr => $self->{local_address} ) : (),
14420 Proto => 'tcp',
14421 Type => SOCK_STREAM,
14422 Timeout => $self->{timeout},
14423 KeepAlive => !!$self->{keep_alive}
14424 ) or die(qq/Could not connect to '$host:$port': $@\n/);
14425
14426 binmode($self->{fh})
14427 or die(qq/Could not binmode() socket: '$!'\n/);
14428
14429 $self->start_ssl($host) if $scheme eq 'https';
14430
14431 $self->{scheme} = $scheme;
14432 $self->{host} = $host;
14433 $self->{port} = $port;
14434 $self->{pid} = $$;
14435 $self->{tid} = _get_tid();
14436
14437 return $self;
14438 }
14439
14440 sub start_ssl {
14441 my ($self, $host) = @_;
14442
14443 # As this might be used via CONNECT after an SSL session
14444 # to a proxy, we shut down any existing SSL before attempting
14445 # the handshake
14446 if ( ref($self->{fh}) eq 'IO::Socket::SSL' ) {
14447 unless ( $self->{fh}->stop_SSL ) {
14448 my $ssl_err = IO::Socket::SSL->errstr;
14449 die(qq/Error halting prior SSL connection: $ssl_err/);
14450 }
14451 }
14452
14453 my $ssl_args = $self->_ssl_args($host);
14454 IO::Socket::SSL->start_SSL(
14455 $self->{fh},
14456 %$ssl_args,
14457 SSL_create_ctx_callback => sub {
14458 my $ctx = shift;
14459 Net::SSLeay::CTX_set_mode($ctx, Net::SSLeay::MODE_AUTO_RETRY());
14460 },
14461 );
14462
14463 unless ( ref($self->{fh}) eq 'IO::Socket::SSL' ) {
14464 my $ssl_err = IO::Socket::SSL->errstr;
14465 die(qq/SSL connection failed for $host: $ssl_err\n/);
14466 }
14467 }
14468
14469 sub close {
14470 @_ == 1 || die(q/Usage: $handle->close()/ . "\n");
14471 my ($self) = @_;
14472 CORE::close($self->{fh})
14473 or die(qq/Could not close socket: '$!'\n/);
14474 }
14475
14476 sub write {
14477 @_ == 2 || die(q/Usage: $handle->write(buf)/ . "\n");
14478 my ($self, $buf) = @_;
14479
14480 if ( $] ge '5.008' ) {
14481 utf8::downgrade($buf, 1)
14482 or die(qq/Wide character in write()\n/);
14483 }
14484
14485 my $len = length $buf;
14486 my $off = 0;
14487
14488 local $SIG{PIPE} = 'IGNORE';
14489
14490 while () {
14491 $self->can_write
14492 or die(qq/Timed out while waiting for socket to become ready for writing\n/);
14493 my $r = syswrite($self->{fh}, $buf, $len, $off);
14494 if (defined $r) {
14495 $len -= $r;
14496 $off += $r;
14497 last unless $len > 0;
14498 }
14499 elsif ($! == EPIPE) {
14500 die(qq/Socket closed by remote server: $!\n/);
14501 }
14502 elsif ($! != EINTR) {
14503 if ($self->{fh}->can('errstr')){
14504 my $err = $self->{fh}->errstr();
14505 die (qq/Could not write to SSL socket: '$err'\n /);
14506 }
14507 else {
14508 die(qq/Could not write to socket: '$!'\n/);
14509 }
14510
14511 }
14512 }
14513 return $off;
14514 }
14515
14516 sub read {
14517 @_ == 2 || @_ == 3 || die(q/Usage: $handle->read(len [, allow_partial])/ . "\n");
14518 my ($self, $len, $allow_partial) = @_;
14519
14520 my $buf = '';
14521 my $got = length $self->{rbuf};
14522
14523 if ($got) {
14524 my $take = ($got < $len) ? $got : $len;
14525 $buf = substr($self->{rbuf}, 0, $take, '');
14526 $len -= $take;
14527 }
14528
14529 while ($len > 0) {
14530 $self->can_read
14531 or die(q/Timed out while waiting for socket to become ready for reading/ . "\n");
14532 my $r = sysread($self->{fh}, $buf, $len, length $buf);
14533 if (defined $r) {
14534 last unless $r;
14535 $len -= $r;
14536 }
14537 elsif ($! != EINTR) {
14538 if ($self->{fh}->can('errstr')){
14539 my $err = $self->{fh}->errstr();
14540 die (qq/Could not read from SSL socket: '$err'\n /);
14541 }
14542 else {
14543 die(qq/Could not read from socket: '$!'\n/);
14544 }
14545 }
14546 }
14547 if ($len && !$allow_partial) {
14548 die(qq/Unexpected end of stream\n/);
14549 }
14550 return $buf;
14551 }
14552
14553 sub readline {
14554 @_ == 1 || die(q/Usage: $handle->readline()/ . "\n");
14555 my ($self) = @_;
14556
14557 while () {
14558 if ($self->{rbuf} =~ s/\A ([^\x0D\x0A]* \x0D?\x0A)//x) {
14559 return $1;
14560 }
14561 if (length $self->{rbuf} >= $self->{max_line_size}) {
14562 die(qq/Line size exceeds the maximum allowed size of $self->{max_line_size}\n/);
14563 }
14564 $self->can_read
14565 or die(qq/Timed out while waiting for socket to become ready for reading\n/);
14566 my $r = sysread($self->{fh}, $self->{rbuf}, BUFSIZE, length $self->{rbuf});
14567 if (defined $r) {
14568 last unless $r;
14569 }
14570 elsif ($! != EINTR) {
14571 if ($self->{fh}->can('errstr')){
14572 my $err = $self->{fh}->errstr();
14573 die (qq/Could not read from SSL socket: '$err'\n /);
14574 }
14575 else {
14576 die(qq/Could not read from socket: '$!'\n/);
14577 }
14578 }
14579 }
14580 die(qq/Unexpected end of stream while looking for line\n/);
14581 }
14582
14583 sub read_header_lines {
14584 @_ == 1 || @_ == 2 || die(q/Usage: $handle->read_header_lines([headers])/ . "\n");
14585 my ($self, $headers) = @_;
14586 $headers ||= {};
14587 my $lines = 0;
14588 my $val;
14589
14590 while () {
14591 my $line = $self->readline;
14592
14593 if (++$lines >= $self->{max_header_lines}) {
14594 die(qq/Header lines exceeds maximum number allowed of $self->{max_header_lines}\n/);
14595 }
14596 elsif ($line =~ /\A ([^\x00-\x1F\x7F:]+) : [\x09\x20]* ([^\x0D\x0A]*)/x) {
14597 my ($field_name) = lc $1;
14598 if (exists $headers->{$field_name}) {
14599 for ($headers->{$field_name}) {
14600 $_ = [$_] unless ref $_ eq "ARRAY";
14601 push @$_, $2;
14602 $val = \$_->[-1];
14603 }
14604 }
14605 else {
14606 $val = \($headers->{$field_name} = $2);
14607 }
14608 }
14609 elsif ($line =~ /\A [\x09\x20]+ ([^\x0D\x0A]*)/x) {
14610 $val
14611 or die(qq/Unexpected header continuation line\n/);
14612 next unless length $1;
14613 $$val .= ' ' if length $$val;
14614 $$val .= $1;
14615 }
14616 elsif ($line =~ /\A \x0D?\x0A \z/x) {
14617 last;
14618 }
14619 else {
14620 die(q/Malformed header line: / . $Printable->($line) . "\n");
14621 }
14622 }
14623 return $headers;
14624 }
14625
14626 sub write_request {
14627 @_ == 2 || die(q/Usage: $handle->write_request(request)/ . "\n");
14628 my($self, $request) = @_;
14629 $self->write_request_header(@{$request}{qw/method uri headers/});
14630 $self->write_body($request) if $request->{cb};
14631 return;
14632 }
14633
14634 my %HeaderCase = (
14635 'content-md5' => 'Content-MD5',
14636 'etag' => 'ETag',
14637 'te' => 'TE',
14638 'www-authenticate' => 'WWW-Authenticate',
14639 'x-xss-protection' => 'X-XSS-Protection',
14640 );
14641
14642 # to avoid multiple small writes and hence nagle, you can pass the method line or anything else to
14643 # combine writes.
14644 sub write_header_lines {
14645 (@_ == 2 || @_ == 3 && ref $_[1] eq 'HASH') || die(q/Usage: $handle->write_header_lines(headers[,prefix])/ . "\n");
14646 my($self, $headers, $prefix_data) = @_;
14647
14648 my $buf = (defined $prefix_data ? $prefix_data : '');
14649 while (my ($k, $v) = each %$headers) {
14650 my $field_name = lc $k;
14651 if (exists $HeaderCase{$field_name}) {
14652 $field_name = $HeaderCase{$field_name};
14653 }
14654 else {
14655 $field_name =~ /\A $Token+ \z/xo
14656 or die(q/Invalid HTTP header field name: / . $Printable->($field_name) . "\n");
14657 $field_name =~ s/\b(\w)/\u$1/g;
14658 $HeaderCase{lc $field_name} = $field_name;
14659 }
14660 for (ref $v eq 'ARRAY' ? @$v : $v) {
14661 $_ = '' unless defined $_;
14662 $buf .= "$field_name: $_\x0D\x0A";
14663 }
14664 }
14665 $buf .= "\x0D\x0A";
14666 return $self->write($buf);
14667 }
14668
14669 # return value indicates whether message length was defined; this is generally
14670 # true unless there was no content-length header and we just read until EOF.
14671 # Other message length errors are thrown as exceptions
14672 sub read_body {
14673 @_ == 3 || die(q/Usage: $handle->read_body(callback, response)/ . "\n");
14674 my ($self, $cb, $response) = @_;
14675 my $te = $response->{headers}{'transfer-encoding'} || '';
14676 my $chunked = grep { /chunked/i } ( ref $te eq 'ARRAY' ? @$te : $te ) ;
14677 return $chunked
14678 ? $self->read_chunked_body($cb, $response)
14679 : $self->read_content_body($cb, $response);
14680 }
14681
14682 sub write_body {
14683 @_ == 2 || die(q/Usage: $handle->write_body(request)/ . "\n");
14684 my ($self, $request) = @_;
14685 if ($request->{headers}{'content-length'}) {
14686 return $self->write_content_body($request);
14687 }
14688 else {
14689 return $self->write_chunked_body($request);
14690 }
14691 }
14692
14693 sub read_content_body {
14694 @_ == 3 || @_ == 4 || die(q/Usage: $handle->read_content_body(callback, response, [read_length])/ . "\n");
14695 my ($self, $cb, $response, $content_length) = @_;
14696 $content_length ||= $response->{headers}{'content-length'};
14697
14698 if ( defined $content_length ) {
14699 my $len = $content_length;
14700 while ($len > 0) {
14701 my $read = ($len > BUFSIZE) ? BUFSIZE : $len;
14702 $cb->($self->read($read, 0), $response);
14703 $len -= $read;
14704 }
14705 return length($self->{rbuf}) == 0;
14706 }
14707
14708 my $chunk;
14709 $cb->($chunk, $response) while length( $chunk = $self->read(BUFSIZE, 1) );
14710
14711 return;
14712 }
14713
14714 sub write_content_body {
14715 @_ == 2 || die(q/Usage: $handle->write_content_body(request)/ . "\n");
14716 my ($self, $request) = @_;
14717
14718 my ($len, $content_length) = (0, $request->{headers}{'content-length'});
14719 while () {
14720 my $data = $request->{cb}->();
14721
14722 defined $data && length $data
14723 or last;
14724
14725 if ( $] ge '5.008' ) {
14726 utf8::downgrade($data, 1)
14727 or die(qq/Wide character in write_content()\n/);
14728 }
14729
14730 $len += $self->write($data);
14731 }
14732
14733 $len == $content_length
14734 or die(qq/Content-Length mismatch (got: $len expected: $content_length)\n/);
14735
14736 return $len;
14737 }
14738
14739 sub read_chunked_body {
14740 @_ == 3 || die(q/Usage: $handle->read_chunked_body(callback, $response)/ . "\n");
14741 my ($self, $cb, $response) = @_;
14742
14743 while () {
14744 my $head = $self->readline;
14745
14746 $head =~ /\A ([A-Fa-f0-9]+)/x
14747 or die(q/Malformed chunk head: / . $Printable->($head) . "\n");
14748
14749 my $len = hex($1)
14750 or last;
14751
14752 $self->read_content_body($cb, $response, $len);
14753
14754 $self->read(2) eq "\x0D\x0A"
14755 or die(qq/Malformed chunk: missing CRLF after chunk data\n/);
14756 }
14757 $self->read_header_lines($response->{headers});
14758 return 1;
14759 }
14760
14761 sub write_chunked_body {
14762 @_ == 2 || die(q/Usage: $handle->write_chunked_body(request)/ . "\n");
14763 my ($self, $request) = @_;
14764
14765 my $len = 0;
14766 while () {
14767 my $data = $request->{cb}->();
14768
14769 defined $data && length $data
14770 or last;
14771
14772 if ( $] ge '5.008' ) {
14773 utf8::downgrade($data, 1)
14774 or die(qq/Wide character in write_chunked_body()\n/);
14775 }
14776
14777 $len += length $data;
14778
14779 my $chunk = sprintf '%X', length $data;
14780 $chunk .= "\x0D\x0A";
14781 $chunk .= $data;
14782 $chunk .= "\x0D\x0A";
14783
14784 $self->write($chunk);
14785 }
14786 $self->write("0\x0D\x0A");
14787 $self->write_header_lines($request->{trailer_cb}->())
14788 if ref $request->{trailer_cb} eq 'CODE';
14789 return $len;
14790 }
14791
14792 sub read_response_header {
14793 @_ == 1 || die(q/Usage: $handle->read_response_header()/ . "\n");
14794 my ($self) = @_;
14795
14796 my $line = $self->readline;
14797
14798 $line =~ /\A (HTTP\/(0*\d+\.0*\d+)) [\x09\x20]+ ([0-9]{3}) [\x09\x20]+ ([^\x0D\x0A]*) \x0D?\x0A/x
14799 or die(q/Malformed Status-Line: / . $Printable->($line). "\n");
14800
14801 my ($protocol, $version, $status, $reason) = ($1, $2, $3, $4);
14802
14803 die (qq/Unsupported HTTP protocol: $protocol\n/)
14804 unless $version =~ /0*1\.0*[01]/;
14805
14806 return {
14807 status => $status,
14808 reason => $reason,
14809 headers => $self->read_header_lines,
14810 protocol => $protocol,
14811 };
14812 }
14813
14814 sub write_request_header {
14815 @_ == 4 || die(q/Usage: $handle->write_request_header(method, request_uri, headers)/ . "\n");
14816 my ($self, $method, $request_uri, $headers) = @_;
14817
14818 return $self->write_header_lines($headers, "$method $request_uri HTTP/1.1\x0D\x0A");
14819 }
14820
14821 sub _do_timeout {
14822 my ($self, $type, $timeout) = @_;
14823 $timeout = $self->{timeout}
14824 unless defined $timeout && $timeout >= 0;
14825
14826 my $fd = fileno $self->{fh};
14827 defined $fd && $fd >= 0
14828 or die(qq/select(2): 'Bad file descriptor'\n/);
14829
14830 my $initial = time;
14831 my $pending = $timeout;
14832 my $nfound;
14833
14834 vec(my $fdset = '', $fd, 1) = 1;
14835
14836 while () {
14837 $nfound = ($type eq 'read')
14838 ? select($fdset, undef, undef, $pending)
14839 : select(undef, $fdset, undef, $pending) ;
14840 if ($nfound == -1) {
14841 $! == EINTR
14842 or die(qq/select(2): '$!'\n/);
14843 redo if !$timeout || ($pending = $timeout - (time - $initial)) > 0;
14844 $nfound = 0;
14845 }
14846 last;
14847 }
14848 $! = 0;
14849 return $nfound;
14850 }
14851
14852 sub can_read {
14853 @_ == 1 || @_ == 2 || die(q/Usage: $handle->can_read([timeout])/ . "\n");
14854 my $self = shift;
14855 if ( ref($self->{fh}) eq 'IO::Socket::SSL' ) {
14856 return 1 if $self->{fh}->pending;
14857 }
14858 return $self->_do_timeout('read', @_)
14859 }
14860
14861 sub can_write {
14862 @_ == 1 || @_ == 2 || die(q/Usage: $handle->can_write([timeout])/ . "\n");
14863 my $self = shift;
14864 return $self->_do_timeout('write', @_)
14865 }
14866
14867 sub _assert_ssl {
14868 my($ok, $reason) = HTTP::Tiny->can_ssl();
14869 die $reason unless $ok;
14870 }
14871
14872 sub can_reuse {
14873 my ($self,$scheme,$host,$port) = @_;
14874 return 0 if
14875 $self->{pid} != $$
14876 || $self->{tid} != _get_tid()
14877 || length($self->{rbuf})
14878 || $scheme ne $self->{scheme}
14879 || $host ne $self->{host}
14880 || $port ne $self->{port}
14881 || eval { $self->can_read(0) }
14882 || $@ ;
14883 return 1;
14884 }
14885
14886 # Try to find a CA bundle to validate the SSL cert,
14887 # prefer Mozilla::CA or fallback to a system file
14888 sub _find_CA_file {
14889 my $self = shift();
14890
14891 if ( $self->{SSL_options}->{SSL_ca_file} ) {
14892 unless ( -r $self->{SSL_options}->{SSL_ca_file} ) {
14893 die qq/SSL_ca_file '$self->{SSL_options}->{SSL_ca_file}' not found or not readable\n/;
14894 }
14895 return $self->{SSL_options}->{SSL_ca_file};
14896 }
14897
14898 return Mozilla::CA::SSL_ca_file()
14899 if eval { require Mozilla::CA; 1 };
14900
14901 # cert list copied from golang src/crypto/x509/root_unix.go
14902 foreach my $ca_bundle (
14903 "/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo etc.
14904 "/etc/pki/tls/certs/ca-bundle.crt", # Fedora/RHEL
14905 "/etc/ssl/ca-bundle.pem", # OpenSUSE
14906 "/etc/openssl/certs/ca-certificates.crt", # NetBSD
14907 "/etc/ssl/cert.pem", # OpenBSD
14908 "/usr/local/share/certs/ca-root-nss.crt", # FreeBSD/DragonFly
14909 "/etc/pki/tls/cacert.pem", # OpenELEC
14910 "/etc/certs/ca-certificates.crt", # Solaris 11.2+
14911 ) {
14912 return $ca_bundle if -e $ca_bundle;
14913 }
14914
14915 die qq/Couldn't find a CA bundle with which to verify the SSL certificate.\n/
14916 . qq/Try installing Mozilla::CA from CPAN\n/;
14917 }
14918
14919 # for thread safety, we need to know thread id if threads are loaded
14920 sub _get_tid {
14921 no warnings 'reserved'; # for 'threads'
14922 return threads->can("tid") ? threads->tid : 0;
14923 }
14924
14925 sub _ssl_args {
14926 my ($self, $host) = @_;
14927
14928 my %ssl_args;
14929
14930 # This test reimplements IO::Socket::SSL::can_client_sni(), which wasn't
14931 # added until IO::Socket::SSL 1.84
14932 if ( Net::SSLeay::OPENSSL_VERSION_NUMBER() >= 0x01000000 ) {
14933 $ssl_args{SSL_hostname} = $host, # Sane SNI support
14934 }
14935
14936 if ($self->{verify_SSL}) {
14937 $ssl_args{SSL_verifycn_scheme} = 'http'; # enable CN validation
14938 $ssl_args{SSL_verifycn_name} = $host; # set validation hostname
14939 $ssl_args{SSL_verify_mode} = 0x01; # enable cert validation
14940 $ssl_args{SSL_ca_file} = $self->_find_CA_file;
14941 }
14942 else {
14943 $ssl_args{SSL_verifycn_scheme} = 'none'; # disable CN validation
14944 $ssl_args{SSL_verify_mode} = 0x00; # disable cert validation
14945 }
14946
14947 # user options override settings from verify_SSL
14948 for my $k ( keys %{$self->{SSL_options}} ) {
14949 $ssl_args{$k} = $self->{SSL_options}{$k} if $k =~ m/^SSL_/;
14950 }
14951
14952 return \%ssl_args;
14953 }
14954
14955 1;
14956
14957 __END__
14958
14959 =pod
14960
14961 =encoding UTF-8
14962
14963 =head1 NAME
14964
14965 HTTP::Tiny - A small, simple, correct HTTP/1.1 client
14966
14967 =head1 VERSION
14968
14969 version 0.056
14970
14971 =head1 SYNOPSIS
14972
14973 use HTTP::Tiny;
14974
14975 my $response = HTTP::Tiny->new->get('http://example.com/');
14976
14977 die "Failed!\n" unless $response->{success};
14978
14979 print "$response->{status} $response->{reason}\n";
14980
14981 while (my ($k, $v) = each %{$response->{headers}}) {
14982 for (ref $v eq 'ARRAY' ? @$v : $v) {
14983 print "$k: $_\n";
14984 }
14985 }
14986
14987 print $response->{content} if length $response->{content};
14988
14989 =head1 DESCRIPTION
14990
14991 This is a very simple HTTP/1.1 client, designed for doing simple
14992 requests without the overhead of a large framework like L<LWP::UserAgent>.
14993
14994 It is more correct and more complete than L<HTTP::Lite>. It supports
14995 proxies and redirection. It also correctly resumes after EINTR.
14996
14997 If L<IO::Socket::IP> 0.25 or later is installed, HTTP::Tiny will use it instead
14998 of L<IO::Socket::INET> for transparent support for both IPv4 and IPv6.
14999
15000 Cookie support requires L<HTTP::CookieJar> or an equivalent class.
15001
15002 =head1 METHODS
15003
15004 =head2 new
15005
15006 $http = HTTP::Tiny->new( %attributes );
15007
15008 This constructor returns a new HTTP::Tiny object. Valid attributes include:
15009
15010 =over 4
15011
15012 =item *
15013
15014 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.
15015
15016 =item *
15017
15018 C<cookie_jar> — An instance of L<HTTP::CookieJar> — or equivalent class that supports the C<add> and C<cookie_header> methods
15019
15020 =item *
15021
15022 C<default_headers> — A hashref of default headers to apply to requests
15023
15024 =item *
15025
15026 C<local_address> — The local IP address to bind to
15027
15028 =item *
15029
15030 C<keep_alive> — Whether to reuse the last connection (if for the same scheme, host and port) (defaults to 1)
15031
15032 =item *
15033
15034 C<max_redirect> — Maximum number of redirects allowed (defaults to 5)
15035
15036 =item *
15037
15038 C<max_size> — Maximum response size in bytes (only when not using a data callback). If defined, responses larger than this will return an exception.
15039
15040 =item *
15041
15042 C<http_proxy> — URL of a proxy server to use for HTTP connections (default is C<$ENV{http_proxy}> — if set)
15043
15044 =item *
15045
15046 C<https_proxy> — URL of a proxy server to use for HTTPS connections (default is C<$ENV{https_proxy}> — if set)
15047
15048 =item *
15049
15050 C<proxy> — URL of a generic proxy server for both HTTP and HTTPS connections (default is C<$ENV{all_proxy}> — if set)
15051
15052 =item *
15053
15054 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}> —)
15055
15056 =item *
15057
15058 C<timeout> — Request timeout in seconds (default is 60)
15059
15060 =item *
15061
15062 C<verify_SSL> — A boolean that indicates whether to validate the SSL certificate of an C<https> — connection (default is false)
15063
15064 =item *
15065
15066 C<SSL_options> — A hashref of C<SSL_*> — options to pass through to L<IO::Socket::SSL>
15067
15068 =back
15069
15070 Passing an explicit C<undef> for C<proxy>, C<http_proxy> or C<https_proxy> will
15071 prevent getting the corresponding proxies from the environment.
15072
15073 Exceptions from C<max_size>, C<timeout> or other errors will result in a
15074 pseudo-HTTP status code of 599 and a reason of "Internal Exception". The
15075 content field in the response will contain the text of the exception.
15076
15077 The C<keep_alive> parameter enables a persistent connection, but only to a
15078 single destination scheme, host and port. Also, if any connection-relevant
15079 attributes are modified, or if the process ID or thread ID change, the
15080 persistent connection will be dropped. If you want persistent connections
15081 across multiple destinations, use multiple HTTP::Tiny objects.
15082
15083 See L</SSL SUPPORT> for more on the C<verify_SSL> and C<SSL_options> attributes.
15084
15085 =head2 get|head|put|post|delete
15086
15087 $response = $http->get($url);
15088 $response = $http->get($url, \%options);
15089 $response = $http->head($url);
15090
15091 These methods are shorthand for calling C<request()> for the given method. The
15092 URL must have unsafe characters escaped and international domain names encoded.
15093 See C<request()> for valid options and a description of the response.
15094
15095 The C<success> field of the response will be true if the status code is 2XX.
15096
15097 =head2 post_form
15098
15099 $response = $http->post_form($url, $form_data);
15100 $response = $http->post_form($url, $form_data, \%options);
15101
15102 This method executes a C<POST> request and sends the key/value pairs from a
15103 form data hash or array reference to the given URL with a C<content-type> of
15104 C<application/x-www-form-urlencoded>. If data is provided as an array
15105 reference, the order is preserved; if provided as a hash reference, the terms
15106 are sorted on key and value for consistency. See documentation for the
15107 C<www_form_urlencode> method for details on the encoding.
15108
15109 The URL must have unsafe characters escaped and international domain names
15110 encoded. See C<request()> for valid options and a description of the response.
15111 Any C<content-type> header or content in the options hashref will be ignored.
15112
15113 The C<success> field of the response will be true if the status code is 2XX.
15114
15115 =head2 mirror
15116
15117 $response = $http->mirror($url, $file, \%options)
15118 if ( $response->{success} ) {
15119 print "$file is up to date\n";
15120 }
15121
15122 Executes a C<GET> request for the URL and saves the response body to the file
15123 name provided. The URL must have unsafe characters escaped and international
15124 domain names encoded. If the file already exists, the request will include an
15125 C<If-Modified-Since> header with the modification timestamp of the file. You
15126 may specify a different C<If-Modified-Since> header yourself in the C<<
15127 $options->{headers} >> hash.
15128
15129 The C<success> field of the response will be true if the status code is 2XX
15130 or if the status code is 304 (unmodified).
15131
15132 If the file was modified and the server response includes a properly
15133 formatted C<Last-Modified> header, the file modification time will
15134 be updated accordingly.
15135
15136 =head2 request
15137
15138 $response = $http->request($method, $url);
15139 $response = $http->request($method, $url, \%options);
15140
15141 Executes an HTTP request of the given method type ('GET', 'HEAD', 'POST',
15142 'PUT', etc.) on the given URL. The URL must have unsafe characters escaped and
15143 international domain names encoded.
15144
15145 If the URL includes a "user:password" stanza, they will be used for Basic-style
15146 authorization headers. (Authorization headers will not be included in a
15147 redirected request.) For example:
15148
15149 $http->request('GET', 'http://Aladdin:open sesame@example.com/');
15150
15151 If the "user:password" stanza contains reserved characters, they must
15152 be percent-escaped:
15153
15154 $http->request('GET', 'http://john%40example.com:password@example.com/');
15155
15156 A hashref of options may be appended to modify the request.
15157
15158 Valid options are:
15159
15160 =over 4
15161
15162 =item *
15163
15164 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.
15165
15166 =item *
15167
15168 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
15169
15170 =item *
15171
15172 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)
15173
15174 =item *
15175
15176 C<data_callback> — A code reference that will be called for each chunks of the response body received.
15177
15178 =back
15179
15180 The C<Host> header is generated from the URL in accordance with RFC 2616. It
15181 is a fatal error to specify C<Host> in the C<headers> option. Other headers
15182 may be ignored or overwritten if necessary for transport compliance.
15183
15184 If the C<content> option is a code reference, it will be called iteratively
15185 to provide the content body of the request. It should return the empty
15186 string or undef when the iterator is exhausted.
15187
15188 If the C<content> option is the empty string, no C<content-type> or
15189 C<content-length> headers will be generated.
15190
15191 If the C<data_callback> option is provided, it will be called iteratively until
15192 the entire response body is received. The first argument will be a string
15193 containing a chunk of the response body, the second argument will be the
15194 in-progress response hash reference, as described below. (This allows
15195 customizing the action of the callback based on the C<status> or C<headers>
15196 received prior to the content body.)
15197
15198 The C<request> method returns a hashref containing the response. The hashref
15199 will have the following keys:
15200
15201 =over 4
15202
15203 =item *
15204
15205 C<success> — Boolean indicating whether the operation returned a 2XX status code
15206
15207 =item *
15208
15209 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
15210
15211 =item *
15212
15213 C<status> — The HTTP status code of the response
15214
15215 =item *
15216
15217 C<reason> — The response phrase returned by the server
15218
15219 =item *
15220
15221 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
15222
15223 =item *
15224
15225 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
15226
15227 =back
15228
15229 On an exception during the execution of the request, the C<status> field will
15230 contain 599, and the C<content> field will contain the text of the exception.
15231
15232 =head2 www_form_urlencode
15233
15234 $params = $http->www_form_urlencode( $data );
15235 $response = $http->get("http://example.com/query?$params");
15236
15237 This method converts the key/value pairs from a data hash or array reference
15238 into a C<x-www-form-urlencoded> string. The keys and values from the data
15239 reference will be UTF-8 encoded and escaped per RFC 3986. If a value is an
15240 array reference, the key will be repeated with each of the values of the array
15241 reference. If data is provided as a hash reference, the key/value pairs in the
15242 resulting string will be sorted by key and value for consistent ordering.
15243
15244 =head2 can_ssl
15245
15246 $ok = HTTP::Tiny->can_ssl;
15247 ($ok, $why) = HTTP::Tiny->can_ssl;
15248 ($ok, $why) = $http->can_ssl;
15249
15250 Indicates if SSL support is available. When called as a class object, it
15251 checks for the correct version of L<Net::SSLeay> and L<IO::Socket::SSL>.
15252 When called as an object methods, if C<SSL_verify> is true or if C<SSL_verify_mode>
15253 is set in C<SSL_options>, it checks that a CA file is available.
15254
15255 In scalar context, returns a boolean indicating if SSL is available.
15256 In list context, returns the boolean and a (possibly multi-line) string of
15257 errors indicating why SSL isn't available.
15258
15259 =for Pod::Coverage SSL_options
15260 agent
15261 cookie_jar
15262 default_headers
15263 http_proxy
15264 https_proxy
15265 keep_alive
15266 local_address
15267 max_redirect
15268 max_size
15269 no_proxy
15270 proxy
15271 timeout
15272 verify_SSL
15273
15274 =head1 SSL SUPPORT
15275
15276 Direct C<https> connections are supported only if L<IO::Socket::SSL> 1.56 or
15277 greater and L<Net::SSLeay> 1.49 or greater are installed. An exception will be
15278 thrown if new enough versions of these modules are not installed or if the SSL
15279 encryption fails. You can also use C<HTTP::Tiny::can_ssl()> utility function
15280 that returns boolean to see if the required modules are installed.
15281
15282 An C<https> connection may be made via an C<http> proxy that supports the CONNECT
15283 command (i.e. RFC 2817). You may not proxy C<https> via a proxy that itself
15284 requires C<https> to communicate.
15285
15286 SSL provides two distinct capabilities:
15287
15288 =over 4
15289
15290 =item *
15291
15292 Encrypted communication channel
15293
15294 =item *
15295
15296 Verification of server identity
15297
15298 =back
15299
15300 B<By default, HTTP::Tiny does not verify server identity>.
15301
15302 Server identity verification is controversial and potentially tricky because it
15303 depends on a (usually paid) third-party Certificate Authority (CA) trust model
15304 to validate a certificate as legitimate. This discriminates against servers
15305 with self-signed certificates or certificates signed by free, community-driven
15306 CA's such as L<CAcert.org|http://cacert.org>.
15307
15308 By default, HTTP::Tiny does not make any assumptions about your trust model,
15309 threat level or risk tolerance. It just aims to give you an encrypted channel
15310 when you need one.
15311
15312 Setting the C<verify_SSL> attribute to a true value will make HTTP::Tiny verify
15313 that an SSL connection has a valid SSL certificate corresponding to the host
15314 name of the connection and that the SSL certificate has been verified by a CA.
15315 Assuming you trust the CA, this will protect against a L<man-in-the-middle
15316 attack|http://en.wikipedia.org/wiki/Man-in-the-middle_attack>. If you are
15317 concerned about security, you should enable this option.
15318
15319 Certificate verification requires a file containing trusted CA certificates.
15320 If the L<Mozilla::CA> module is installed, HTTP::Tiny will use the CA file
15321 included with it as a source of trusted CA's. (This means you trust Mozilla,
15322 the author of Mozilla::CA, the CPAN mirror where you got Mozilla::CA, the
15323 toolchain used to install it, and your operating system security, right?)
15324
15325 If that module is not available, then HTTP::Tiny will search several
15326 system-specific default locations for a CA certificate file:
15327
15328 =over 4
15329
15330 =item *
15331
15332 /etc/ssl/certs/ca-certificates.crt
15333
15334 =item *
15335
15336 /etc/pki/tls/certs/ca-bundle.crt
15337
15338 =item *
15339
15340 /etc/ssl/ca-bundle.pem
15341
15342 =back
15343
15344 An exception will be raised if C<verify_SSL> is true and no CA certificate file
15345 is available.
15346
15347 If you desire complete control over SSL connections, the C<SSL_options> attribute
15348 lets you provide a hash reference that will be passed through to
15349 C<IO::Socket::SSL::start_SSL()>, overriding any options set by HTTP::Tiny. For
15350 example, to provide your own trusted CA file:
15351
15352 SSL_options => {
15353 SSL_ca_file => $file_path,
15354 }
15355
15356 The C<SSL_options> attribute could also be used for such things as providing a
15357 client certificate for authentication to a server or controlling the choice of
15358 cipher used for the SSL connection. See L<IO::Socket::SSL> documentation for
15359 details.
15360
15361 =head1 PROXY SUPPORT
15362
15363 HTTP::Tiny can proxy both C<http> and C<https> requests. Only Basic proxy
15364 authorization is supported and it must be provided as part of the proxy URL:
15365 C<http://user:pass@proxy.example.com/>.
15366
15367 HTTP::Tiny supports the following proxy environment variables:
15368
15369 =over 4
15370
15371 =item *
15372
15373 http_proxy or HTTP_PROXY
15374
15375 =item *
15376
15377 https_proxy or HTTPS_PROXY
15378
15379 =item *
15380
15381 all_proxy or ALL_PROXY
15382
15383 =back
15384
15385 If the C<REQUEST_METHOD> environment variable is set, then this might be a CGI
15386 process and C<HTTP_PROXY> would be set from the C<Proxy:> header, which is a
15387 security risk. If C<REQUEST_METHOD> is set, C<HTTP_PROXY> (the upper case
15388 variant only) is ignored.
15389
15390 Tunnelling C<https> over an C<http> proxy using the CONNECT method is
15391 supported. If your proxy uses C<https> itself, you can not tunnel C<https>
15392 over it.
15393
15394 Be warned that proxying an C<https> connection opens you to the risk of a
15395 man-in-the-middle attack by the proxy server.
15396
15397 The C<no_proxy> environment variable is supported in the format of a
15398 comma-separated list of domain extensions proxy should not be used for.
15399
15400 Proxy arguments passed to C<new> will override their corresponding
15401 environment variables.
15402
15403 =head1 LIMITATIONS
15404
15405 HTTP::Tiny is I<conditionally compliant> with the
15406 L<HTTP/1.1 specifications|http://www.w3.org/Protocols/>:
15407
15408 =over 4
15409
15410 =item *
15411
15412 "Message Syntax and Routing" [RFC7230]
15413
15414 =item *
15415
15416 "Semantics and Content" [RFC7231]
15417
15418 =item *
15419
15420 "Conditional Requests" [RFC7232]
15421
15422 =item *
15423
15424 "Range Requests" [RFC7233]
15425
15426 =item *
15427
15428 "Caching" [RFC7234]
15429
15430 =item *
15431
15432 "Authentication" [RFC7235]
15433
15434 =back
15435
15436 It attempts to meet all "MUST" requirements of the specification, but does not
15437 implement all "SHOULD" requirements. (Note: it was developed against the
15438 earlier RFC 2616 specification and may not yet meet the revised RFC 7230-7235
15439 spec.)
15440
15441 Some particular limitations of note include:
15442
15443 =over
15444
15445 =item *
15446
15447 HTTP::Tiny focuses on correct transport. Users are responsible for ensuring
15448 that user-defined headers and content are compliant with the HTTP/1.1
15449 specification.
15450
15451 =item *
15452
15453 Users must ensure that URLs are properly escaped for unsafe characters and that
15454 international domain names are properly encoded to ASCII. See L<URI::Escape>,
15455 L<URI::_punycode> and L<Net::IDN::Encode>.
15456
15457 =item *
15458
15459 Redirection is very strict against the specification. Redirection is only
15460 automatic for response codes 301, 302, 307 and 308 if the request method is
15461 'GET' or 'HEAD'. Response code 303 is always converted into a 'GET'
15462 redirection, as mandated by the specification. There is no automatic support
15463 for status 305 ("Use proxy") redirections.
15464
15465 =item *
15466
15467 There is no provision for delaying a request body using an C<Expect> header.
15468 Unexpected C<1XX> responses are silently ignored as per the specification.
15469
15470 =item *
15471
15472 Only 'chunked' C<Transfer-Encoding> is supported.
15473
15474 =item *
15475
15476 There is no support for a Request-URI of '*' for the 'OPTIONS' request.
15477
15478 =back
15479
15480 Despite the limitations listed above, HTTP::Tiny is considered
15481 feature-complete. New feature requests should be directed to
15482 L<HTTP::Tiny::UA>.
15483
15484 =head1 SEE ALSO
15485
15486 =over 4
15487
15488 =item *
15489
15490 L<HTTP::Tiny::UA> - Higher level UA features for HTTP::Tiny
15491
15492 =item *
15493
15494 L<HTTP::Thin> - HTTP::Tiny wrapper with L<HTTP::Request>/L<HTTP::Response> compatibility
15495
15496 =item *
15497
15498 L<HTTP::Tiny::Mech> - Wrap L<WWW::Mechanize> instance in HTTP::Tiny compatible interface
15499
15500 =item *
15501
15502 L<IO::Socket::IP> - Required for IPv6 support
15503
15504 =item *
15505
15506 L<IO::Socket::SSL> - Required for SSL support
15507
15508 =item *
15509
15510 L<LWP::UserAgent> - If HTTP::Tiny isn't enough for you, this is the "standard" way to do things
15511
15512 =item *
15513
15514 L<Mozilla::CA> - Required if you want to validate SSL certificates
15515
15516 =item *
15517
15518 L<Net::SSLeay> - Required for SSL support
15519
15520 =back
15521
15522 =for :stopwords cpan testmatrix url annocpan anno bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan
15523
15524 =head1 SUPPORT
15525
15526 =head2 Bugs / Feature Requests
15527
15528 Please report any bugs or feature requests through the issue tracker
15529 at L<https://github.com/chansen/p5-http-tiny/issues>.
15530 You will be notified automatically of any progress on your issue.
15531
15532 =head2 Source Code
15533
15534 This is open source software. The code repository is available for
15535 public review and contribution under the terms of the license.
15536
15537 L<https://github.com/chansen/p5-http-tiny>
15538
15539 git clone https://github.com/chansen/p5-http-tiny.git
15540
15541 =head1 AUTHORS
15542
15543 =over 4
15544
15545 =item *
15546
15547 Christian Hansen <chansen@cpan.org>
15548
15549 =item *
15550
15551 David Golden <dagolden@cpan.org>
15552
15553 =back
15554
15555 =head1 CONTRIBUTORS
15556
15557 =for stopwords Alan Gardner Alessandro Ghedini Brad Gilbert Chris Nehren Weyl Claes Jakobsson Clinton Gormley Dean Pearce Edward Zborowski James Raspass Jeremy Mates Jess Robinson Lukas Eklund Martin J. Evans Martin-Louis Bright Mike Doherty Olaf Alders Olivier Mengué Petr Písař Sören Kornetzki Syohei YOSHIDA Tatsuhiko Miyagawa Tom Hukins Tony Cook
15558
15559 =over 4
15560
15561 =item *
15562
15563 Alan Gardner <gardner@pythian.com>
15564
15565 =item *
15566
15567 Alessandro Ghedini <al3xbio@gmail.com>
15568
15569 =item *
15570
15571 Brad Gilbert <bgills@cpan.org>
15572
15573 =item *
15574
15575 Chris Nehren <apeiron@cpan.org>
15576
15577 =item *
15578
15579 Chris Weyl <cweyl@alumni.drew.edu>
15580
15581 =item *
15582
15583 Claes Jakobsson <claes@surfar.nu>
15584
15585 =item *
15586
15587 Clinton Gormley <clint@traveljury.com>
15588
15589 =item *
15590
15591 Dean Pearce <pearce@pythian.com>
15592
15593 =item *
15594
15595 Edward Zborowski <ed@rubensteintech.com>
15596
15597 =item *
15598
15599 James Raspass <jraspass@gmail.com>
15600
15601 =item *
15602
15603 Jeremy Mates <jmates@cpan.org>
15604
15605 =item *
15606
15607 Jess Robinson <castaway@desert-island.me.uk>
15608
15609 =item *
15610
15611 Lukas Eklund <leklund@gmail.com>
15612
15613 =item *
15614
15615 Martin J. Evans <mjegh@ntlworld.com>
15616
15617 =item *
15618
15619 Martin-Louis Bright <mlbright@gmail.com>
15620
15621 =item *
15622
15623 Mike Doherty <doherty@cpan.org>
15624
15625 =item *
15626
15627 Olaf Alders <olaf@wundersolutions.com>
15628
15629 =item *
15630
15631 Olivier Mengué <dolmen@cpan.org>
15632
15633 =item *
15634
15635 Petr Písař <ppisar@redhat.com>
15636
15637 =item *
15638
15639 Sören Kornetzki <soeren.kornetzki@delti.com>
15640
15641 =item *
15642
15643 Syohei YOSHIDA <syohex@gmail.com>
15644
15645 =item *
15646
15647 Tatsuhiko Miyagawa <miyagawa@bulknews.net>
15648
15649 =item *
15650
15651 Tom Hukins <tom@eborcom.com>
15652
15653 =item *
15654
15655 Tony Cook <tony@develop-help.com>
15656
15657 =back
15658
15659 =head1 COPYRIGHT AND LICENSE
15660
15661 This software is copyright (c) 2015 by Christian Hansen.
15662
15663 This is free software; you can redistribute it and/or modify it under
15664 the same terms as the Perl 5 programming language system itself.
15665
15666 =cut
15667 HTTP_TINY
15668  
15669 $fatpacked{"JSON/PP.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'JSON_PP';
15670 package JSON::PP;
15671
15672 # JSON-2.0
15673
15674 use 5.005;
15675 use strict;
15676 use base qw(Exporter);
15677 use overload ();
15678
15679 use Carp ();
15680 use B ();
15681 #use Devel::Peek;
15682
15683 $JSON::PP::VERSION = '2.27300';
15684
15685 @JSON::PP::EXPORT = qw(encode_json decode_json from_json to_json);
15686
15687 # instead of hash-access, i tried index-access for speed.
15688 # but this method is not faster than what i expected. so it will be changed.
15689
15690 use constant P_ASCII => 0;
15691 use constant P_LATIN1 => 1;
15692 use constant P_UTF8 => 2;
15693 use constant P_INDENT => 3;
15694 use constant P_CANONICAL => 4;
15695 use constant P_SPACE_BEFORE => 5;
15696 use constant P_SPACE_AFTER => 6;
15697 use constant P_ALLOW_NONREF => 7;
15698 use constant P_SHRINK => 8;
15699 use constant P_ALLOW_BLESSED => 9;
15700 use constant P_CONVERT_BLESSED => 10;
15701 use constant P_RELAXED => 11;
15702
15703 use constant P_LOOSE => 12;
15704 use constant P_ALLOW_BIGNUM => 13;
15705 use constant P_ALLOW_BAREKEY => 14;
15706 use constant P_ALLOW_SINGLEQUOTE => 15;
15707 use constant P_ESCAPE_SLASH => 16;
15708 use constant P_AS_NONBLESSED => 17;
15709
15710 use constant P_ALLOW_UNKNOWN => 18;
15711
15712 use constant OLD_PERL => $] < 5.008 ? 1 : 0;
15713
15714 BEGIN {
15715 my @xs_compati_bit_properties = qw(
15716 latin1 ascii utf8 indent canonical space_before space_after allow_nonref shrink
15717 allow_blessed convert_blessed relaxed allow_unknown
15718 );
15719 my @pp_bit_properties = qw(
15720 allow_singlequote allow_bignum loose
15721 allow_barekey escape_slash as_nonblessed
15722 );
15723
15724 # Perl version check, Unicode handling is enable?
15725 # Helper module sets @JSON::PP::_properties.
15726 if ($] < 5.008 ) {
15727 my $helper = $] >= 5.006 ? 'JSON::PP::Compat5006' : 'JSON::PP::Compat5005';
15728 eval qq| require $helper |;
15729 if ($@) { Carp::croak $@; }
15730 }
15731
15732 for my $name (@xs_compati_bit_properties, @pp_bit_properties) {
15733 my $flag_name = 'P_' . uc($name);
15734
15735 eval qq/
15736 sub $name {
15737 my \$enable = defined \$_[1] ? \$_[1] : 1;
15738
15739 if (\$enable) {
15740 \$_[0]->{PROPS}->[$flag_name] = 1;
15741 }
15742 else {
15743 \$_[0]->{PROPS}->[$flag_name] = 0;
15744 }
15745
15746 \$_[0];
15747 }
15748
15749 sub get_$name {
15750 \$_[0]->{PROPS}->[$flag_name] ? 1 : '';
15751 }
15752 /;
15753 }
15754
15755 }
15756
15757
15758
15759 # Functions
15760
15761 my %encode_allow_method
15762 = map {($_ => 1)} qw/utf8 pretty allow_nonref latin1 self_encode escape_slash
15763 allow_blessed convert_blessed indent indent_length allow_bignum
15764 as_nonblessed
15765 /;
15766 my %decode_allow_method
15767 = map {($_ => 1)} qw/utf8 allow_nonref loose allow_singlequote allow_bignum
15768 allow_barekey max_size relaxed/;
15769
15770
15771 my $JSON; # cache
15772
15773 sub encode_json ($) { # encode
15774 ($JSON ||= __PACKAGE__->new->utf8)->encode(@_);
15775 }
15776
15777
15778 sub decode_json { # decode
15779 ($JSON ||= __PACKAGE__->new->utf8)->decode(@_);
15780 }
15781
15782 # Obsoleted
15783
15784 sub to_json($) {
15785 Carp::croak ("JSON::PP::to_json has been renamed to encode_json.");
15786 }
15787
15788
15789 sub from_json($) {
15790 Carp::croak ("JSON::PP::from_json has been renamed to decode_json.");
15791 }
15792
15793
15794 # Methods
15795
15796 sub new {
15797 my $class = shift;
15798 my $self = {
15799 max_depth => 512,
15800 max_size => 0,
15801 indent => 0,
15802 FLAGS => 0,
15803 fallback => sub { encode_error('Invalid value. JSON can only reference.') },
15804 indent_length => 3,
15805 };
15806
15807 bless $self, $class;
15808 }
15809
15810
15811 sub encode {
15812 return $_[0]->PP_encode_json($_[1]);
15813 }
15814
15815
15816 sub decode {
15817 return $_[0]->PP_decode_json($_[1], 0x00000000);
15818 }
15819
15820
15821 sub decode_prefix {
15822 return $_[0]->PP_decode_json($_[1], 0x00000001);
15823 }
15824
15825
15826 # accessor
15827
15828
15829 # pretty printing
15830
15831 sub pretty {
15832 my ($self, $v) = @_;
15833 my $enable = defined $v ? $v : 1;
15834
15835 if ($enable) { # indent_length(3) for JSON::XS compatibility
15836 $self->indent(1)->indent_length(3)->space_before(1)->space_after(1);
15837 }
15838 else {
15839 $self->indent(0)->space_before(0)->space_after(0);
15840 }
15841
15842 $self;
15843 }
15844
15845 # etc
15846
15847 sub max_depth {
15848 my $max = defined $_[1] ? $_[1] : 0x80000000;
15849 $_[0]->{max_depth} = $max;
15850 $_[0];
15851 }
15852
15853
15854 sub get_max_depth { $_[0]->{max_depth}; }
15855
15856
15857 sub max_size {
15858 my $max = defined $_[1] ? $_[1] : 0;
15859 $_[0]->{max_size} = $max;
15860 $_[0];
15861 }
15862
15863
15864 sub get_max_size { $_[0]->{max_size}; }
15865
15866
15867 sub filter_json_object {
15868 $_[0]->{cb_object} = defined $_[1] ? $_[1] : 0;
15869 $_[0]->{F_HOOK} = ($_[0]->{cb_object} or $_[0]->{cb_sk_object}) ? 1 : 0;
15870 $_[0];
15871 }
15872
15873 sub filter_json_single_key_object {
15874 if (@_ > 1) {
15875 $_[0]->{cb_sk_object}->{$_[1]} = $_[2];
15876 }
15877 $_[0]->{F_HOOK} = ($_[0]->{cb_object} or $_[0]->{cb_sk_object}) ? 1 : 0;
15878 $_[0];
15879 }
15880
15881 sub indent_length {
15882 if (!defined $_[1] or $_[1] > 15 or $_[1] < 0) {
15883 Carp::carp "The acceptable range of indent_length() is 0 to 15.";
15884 }
15885 else {
15886 $_[0]->{indent_length} = $_[1];
15887 }
15888 $_[0];
15889 }
15890
15891 sub get_indent_length {
15892 $_[0]->{indent_length};
15893 }
15894
15895 sub sort_by {
15896 $_[0]->{sort_by} = defined $_[1] ? $_[1] : 1;
15897 $_[0];
15898 }
15899
15900 sub allow_bigint {
15901 Carp::carp("allow_bigint() is obsoleted. use allow_bignum() insted.");
15902 }
15903
15904 ###############################
15905
15906 ###
15907 ### Perl => JSON
15908 ###
15909
15910
15911 { # Convert
15912
15913 my $max_depth;
15914 my $indent;
15915 my $ascii;
15916 my $latin1;
15917 my $utf8;
15918 my $space_before;
15919 my $space_after;
15920 my $canonical;
15921 my $allow_blessed;
15922 my $convert_blessed;
15923
15924 my $indent_length;
15925 my $escape_slash;
15926 my $bignum;
15927 my $as_nonblessed;
15928
15929 my $depth;
15930 my $indent_count;
15931 my $keysort;
15932
15933
15934 sub PP_encode_json {
15935 my $self = shift;
15936 my $obj = shift;
15937
15938 $indent_count = 0;
15939 $depth = 0;
15940
15941 my $idx = $self->{PROPS};
15942
15943 ($ascii, $latin1, $utf8, $indent, $canonical, $space_before, $space_after, $allow_blessed,
15944 $convert_blessed, $escape_slash, $bignum, $as_nonblessed)
15945 = @{$idx}[P_ASCII .. P_SPACE_AFTER, P_ALLOW_BLESSED, P_CONVERT_BLESSED,
15946 P_ESCAPE_SLASH, P_ALLOW_BIGNUM, P_AS_NONBLESSED];
15947
15948 ($max_depth, $indent_length) = @{$self}{qw/max_depth indent_length/};
15949
15950 $keysort = $canonical ? sub { $a cmp $b } : undef;
15951
15952 if ($self->{sort_by}) {
15953 $keysort = ref($self->{sort_by}) eq 'CODE' ? $self->{sort_by}
15954 : $self->{sort_by} =~ /\D+/ ? $self->{sort_by}
15955 : sub { $a cmp $b };
15956 }
15957
15958 encode_error("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)")
15959 if(!ref $obj and !$idx->[ P_ALLOW_NONREF ]);
15960
15961 my $str = $self->object_to_json($obj);
15962
15963 $str .= "\n" if ( $indent ); # JSON::XS 2.26 compatible
15964
15965 unless ($ascii or $latin1 or $utf8) {
15966 utf8::upgrade($str);
15967 }
15968
15969 if ($idx->[ P_SHRINK ]) {
15970 utf8::downgrade($str, 1);
15971 }
15972
15973 return $str;
15974 }
15975
15976
15977 sub object_to_json {
15978 my ($self, $obj) = @_;
15979 my $type = ref($obj);
15980
15981 if($type eq 'HASH'){
15982 return $self->hash_to_json($obj);
15983 }
15984 elsif($type eq 'ARRAY'){
15985 return $self->array_to_json($obj);
15986 }
15987 elsif ($type) { # blessed object?
15988 if (blessed($obj)) {
15989
15990 return $self->value_to_json($obj) if ( $obj->isa('JSON::PP::Boolean') );
15991
15992 if ( $convert_blessed and $obj->can('TO_JSON') ) {
15993 my $result = $obj->TO_JSON();
15994 if ( defined $result and ref( $result ) ) {
15995 if ( refaddr( $obj ) eq refaddr( $result ) ) {
15996 encode_error( sprintf(
15997 "%s::TO_JSON method returned same object as was passed instead of a new one",
15998 ref $obj
15999 ) );
16000 }
16001 }
16002
16003 return $self->object_to_json( $result );
16004 }
16005
16006 return "$obj" if ( $bignum and _is_bignum($obj) );
16007 return $self->blessed_to_json($obj) if ($allow_blessed and $as_nonblessed); # will be removed.
16008
16009 encode_error( sprintf("encountered object '%s', but neither allow_blessed "
16010 . "nor convert_blessed settings are enabled", $obj)
16011 ) unless ($allow_blessed);
16012
16013 return 'null';
16014 }
16015 else {
16016 return $self->value_to_json($obj);
16017 }
16018 }
16019 else{
16020 return $self->value_to_json($obj);
16021 }
16022 }
16023
16024
16025 sub hash_to_json {
16026 my ($self, $obj) = @_;
16027 my @res;
16028
16029 encode_error("json text or perl structure exceeds maximum nesting level (max_depth set too low?)")
16030 if (++$depth > $max_depth);
16031
16032 my ($pre, $post) = $indent ? $self->_up_indent() : ('', '');
16033 my $del = ($space_before ? ' ' : '') . ':' . ($space_after ? ' ' : '');
16034
16035 for my $k ( _sort( $obj ) ) {
16036 if ( OLD_PERL ) { utf8::decode($k) } # key for Perl 5.6 / be optimized
16037 push @res, string_to_json( $self, $k )
16038 . $del
16039 . ( $self->object_to_json( $obj->{$k} ) || $self->value_to_json( $obj->{$k} ) );
16040 }
16041
16042 --$depth;
16043 $self->_down_indent() if ($indent);
16044
16045 return '{' . ( @res ? $pre : '' ) . ( @res ? join( ",$pre", @res ) . $post : '' ) . '}';
16046 }
16047
16048
16049 sub array_to_json {
16050 my ($self, $obj) = @_;
16051 my @res;
16052
16053 encode_error("json text or perl structure exceeds maximum nesting level (max_depth set too low?)")
16054 if (++$depth > $max_depth);
16055
16056 my ($pre, $post) = $indent ? $self->_up_indent() : ('', '');
16057
16058 for my $v (@$obj){
16059 push @res, $self->object_to_json($v) || $self->value_to_json($v);
16060 }
16061
16062 --$depth;
16063 $self->_down_indent() if ($indent);
16064
16065 return '[' . ( @res ? $pre : '' ) . ( @res ? join( ",$pre", @res ) . $post : '' ) . ']';
16066 }
16067
16068
16069 sub value_to_json {
16070 my ($self, $value) = @_;
16071
16072 return 'null' if(!defined $value);
16073
16074 my $b_obj = B::svref_2object(\$value); # for round trip problem
16075 my $flags = $b_obj->FLAGS;
16076
16077 return $value # as is
16078 if $flags & ( B::SVp_IOK | B::SVp_NOK ) and !( $flags & B::SVp_POK ); # SvTYPE is IV or NV?
16079
16080 my $type = ref($value);
16081
16082 if(!$type){
16083 return string_to_json($self, $value);
16084 }
16085 elsif( blessed($value) and $value->isa('JSON::PP::Boolean') ){
16086 return $$value == 1 ? 'true' : 'false';
16087 }
16088 elsif ($type) {
16089 if ((overload::StrVal($value) =~ /=(\w+)/)[0]) {
16090 return $self->value_to_json("$value");
16091 }
16092
16093 if ($type eq 'SCALAR' and defined $$value) {
16094 return $$value eq '1' ? 'true'
16095 : $$value eq '0' ? 'false'
16096 : $self->{PROPS}->[ P_ALLOW_UNKNOWN ] ? 'null'
16097 : encode_error("cannot encode reference to scalar");
16098 }
16099
16100 if ( $self->{PROPS}->[ P_ALLOW_UNKNOWN ] ) {
16101 return 'null';
16102 }
16103 else {
16104 if ( $type eq 'SCALAR' or $type eq 'REF' ) {
16105 encode_error("cannot encode reference to scalar");
16106 }
16107 else {
16108 encode_error("encountered $value, but JSON can only represent references to arrays or hashes");
16109 }
16110 }
16111
16112 }
16113 else {
16114 return $self->{fallback}->($value)
16115 if ($self->{fallback} and ref($self->{fallback}) eq 'CODE');
16116 return 'null';
16117 }
16118
16119 }
16120
16121
16122 my %esc = (
16123 "\n" => '\n',
16124 "\r" => '\r',
16125 "\t" => '\t',
16126 "\f" => '\f',
16127 "\b" => '\b',
16128 "\"" => '\"',
16129 "\\" => '\\\\',
16130 "\'" => '\\\'',
16131 );
16132
16133
16134 sub string_to_json {
16135 my ($self, $arg) = @_;
16136
16137 $arg =~ s/([\x22\x5c\n\r\t\f\b])/$esc{$1}/g;
16138 $arg =~ s/\//\\\//g if ($escape_slash);
16139 $arg =~ s/([\x00-\x08\x0b\x0e-\x1f])/'\\u00' . unpack('H2', $1)/eg;
16140
16141 if ($ascii) {
16142 $arg = JSON_PP_encode_ascii($arg);
16143 }
16144
16145 if ($latin1) {
16146 $arg = JSON_PP_encode_latin1($arg);
16147 }
16148
16149 if ($utf8) {
16150 utf8::encode($arg);
16151 }
16152
16153 return '"' . $arg . '"';
16154 }
16155
16156
16157 sub blessed_to_json {
16158 my $reftype = reftype($_[1]) || '';
16159 if ($reftype eq 'HASH') {
16160 return $_[0]->hash_to_json($_[1]);
16161 }
16162 elsif ($reftype eq 'ARRAY') {
16163 return $_[0]->array_to_json($_[1]);
16164 }
16165 else {
16166 return 'null';
16167 }
16168 }
16169
16170
16171 sub encode_error {
16172 my $error = shift;
16173 Carp::croak "$error";
16174 }
16175
16176
16177 sub _sort {
16178 defined $keysort ? (sort $keysort (keys %{$_[0]})) : keys %{$_[0]};
16179 }
16180
16181
16182 sub _up_indent {
16183 my $self = shift;
16184 my $space = ' ' x $indent_length;
16185
16186 my ($pre,$post) = ('','');
16187
16188 $post = "\n" . $space x $indent_count;
16189
16190 $indent_count++;
16191
16192 $pre = "\n" . $space x $indent_count;
16193
16194 return ($pre,$post);
16195 }
16196
16197
16198 sub _down_indent { $indent_count--; }
16199
16200
16201 sub PP_encode_box {
16202 {
16203 depth => $depth,
16204 indent_count => $indent_count,
16205 };
16206 }
16207
16208 } # Convert
16209
16210
16211 sub _encode_ascii {
16212 join('',
16213 map {
16214 $_ <= 127 ?
16215 chr($_) :
16216 $_ <= 65535 ?
16217 sprintf('\u%04x', $_) : sprintf('\u%x\u%x', _encode_surrogates($_));
16218 } unpack('U*', $_[0])
16219 );
16220 }
16221
16222
16223 sub _encode_latin1 {
16224 join('',
16225 map {
16226 $_ <= 255 ?
16227 chr($_) :
16228 $_ <= 65535 ?
16229 sprintf('\u%04x', $_) : sprintf('\u%x\u%x', _encode_surrogates($_));
16230 } unpack('U*', $_[0])
16231 );
16232 }
16233
16234
16235 sub _encode_surrogates { # from perlunicode
16236 my $uni = $_[0] - 0x10000;
16237 return ($uni / 0x400 + 0xD800, $uni % 0x400 + 0xDC00);
16238 }
16239
16240
16241 sub _is_bignum {
16242 $_[0]->isa('Math::BigInt') or $_[0]->isa('Math::BigFloat');
16243 }
16244
16245
16246
16247 #
16248 # JSON => Perl
16249 #
16250
16251 my $max_intsize;
16252
16253 BEGIN {
16254 my $checkint = 1111;
16255 for my $d (5..64) {
16256 $checkint .= 1;
16257 my $int = eval qq| $checkint |;
16258 if ($int =~ /[eE]/) {
16259 $max_intsize = $d - 1;
16260 last;
16261 }
16262 }
16263 }
16264
16265 { # PARSE
16266
16267 my %escapes = ( # by Jeremy Muhlich <jmuhlich [at] bitflood.org>
16268 b => "\x8",
16269 t => "\x9",
16270 n => "\xA",
16271 f => "\xC",
16272 r => "\xD",
16273 '\\' => '\\',
16274 '"' => '"',
16275 '/' => '/',
16276 );
16277
16278 my $text; # json data
16279 my $at; # offset
16280 my $ch; # 1chracter
16281 my $len; # text length (changed according to UTF8 or NON UTF8)
16282 # INTERNAL
16283 my $depth; # nest counter
16284 my $encoding; # json text encoding
16285 my $is_valid_utf8; # temp variable
16286 my $utf8_len; # utf8 byte length
16287 # FLAGS
16288 my $utf8; # must be utf8
16289 my $max_depth; # max nest nubmer of objects and arrays
16290 my $max_size;
16291 my $relaxed;
16292 my $cb_object;
16293 my $cb_sk_object;
16294
16295 my $F_HOOK;
16296
16297 my $allow_bigint; # using Math::BigInt
16298 my $singlequote; # loosely quoting
16299 my $loose; #
16300 my $allow_barekey; # bareKey
16301
16302 # $opt flag
16303 # 0x00000001 .... decode_prefix
16304 # 0x10000000 .... incr_parse
16305
16306 sub PP_decode_json {
16307 my ($self, $opt); # $opt is an effective flag during this decode_json.
16308
16309 ($self, $text, $opt) = @_;
16310
16311 ($at, $ch, $depth) = (0, '', 0);
16312
16313 if ( !defined $text or ref $text ) {
16314 decode_error("malformed JSON string, neither array, object, number, string or atom");
16315 }
16316
16317 my $idx = $self->{PROPS};
16318
16319 ($utf8, $relaxed, $loose, $allow_bigint, $allow_barekey, $singlequote)
16320 = @{$idx}[P_UTF8, P_RELAXED, P_LOOSE .. P_ALLOW_SINGLEQUOTE];
16321
16322 if ( $utf8 ) {
16323 utf8::downgrade( $text, 1 ) or Carp::croak("Wide character in subroutine entry");
16324 }
16325 else {
16326 utf8::upgrade( $text );
16327 utf8::encode( $text );
16328 }
16329
16330 $len = length $text;
16331
16332 ($max_depth, $max_size, $cb_object, $cb_sk_object, $F_HOOK)
16333 = @{$self}{qw/max_depth max_size cb_object cb_sk_object F_HOOK/};
16334
16335 if ($max_size > 1) {
16336 use bytes;
16337 my $bytes = length $text;
16338 decode_error(
16339 sprintf("attempted decode of JSON text of %s bytes size, but max_size is set to %s"
16340 , $bytes, $max_size), 1
16341 ) if ($bytes > $max_size);
16342 }
16343
16344 # Currently no effect
16345 # should use regexp
16346 my @octets = unpack('C4', $text);
16347 $encoding = ( $octets[0] and $octets[1]) ? 'UTF-8'
16348 : (!$octets[0] and $octets[1]) ? 'UTF-16BE'
16349 : (!$octets[0] and !$octets[1]) ? 'UTF-32BE'
16350 : ( $octets[2] ) ? 'UTF-16LE'
16351 : (!$octets[2] ) ? 'UTF-32LE'
16352 : 'unknown';
16353
16354 white(); # remove head white space
16355
16356 my $valid_start = defined $ch; # Is there a first character for JSON structure?
16357
16358 my $result = value();
16359
16360 return undef if ( !$result && ( $opt & 0x10000000 ) ); # for incr_parse
16361
16362 decode_error("malformed JSON string, neither array, object, number, string or atom") unless $valid_start;
16363
16364 if ( !$idx->[ P_ALLOW_NONREF ] and !ref $result ) {
16365 decode_error(
16366 'JSON text must be an object or array (but found number, string, true, false or null,'
16367 . ' use allow_nonref to allow this)', 1);
16368 }
16369
16370 Carp::croak('something wrong.') if $len < $at; # we won't arrive here.
16371
16372 my $consumed = defined $ch ? $at - 1 : $at; # consumed JSON text length
16373
16374 white(); # remove tail white space
16375
16376 if ( $ch ) {
16377 return ( $result, $consumed ) if ($opt & 0x00000001); # all right if decode_prefix
16378 decode_error("garbage after JSON object");
16379 }
16380
16381 ( $opt & 0x00000001 ) ? ( $result, $consumed ) : $result;
16382 }
16383
16384
16385 sub next_chr {
16386 return $ch = undef if($at >= $len);
16387 $ch = substr($text, $at++, 1);
16388 }
16389
16390
16391 sub value {
16392 white();
16393 return if(!defined $ch);
16394 return object() if($ch eq '{');
16395 return array() if($ch eq '[');
16396 return string() if($ch eq '"' or ($singlequote and $ch eq "'"));
16397 return number() if($ch =~ /[0-9]/ or $ch eq '-');
16398 return word();
16399 }
16400
16401 sub string {
16402 my ($i, $s, $t, $u);
16403 my $utf16;
16404 my $is_utf8;
16405
16406 ($is_valid_utf8, $utf8_len) = ('', 0);
16407
16408 $s = ''; # basically UTF8 flag on
16409
16410 if($ch eq '"' or ($singlequote and $ch eq "'")){
16411 my $boundChar = $ch;
16412
16413 OUTER: while( defined(next_chr()) ){
16414
16415 if($ch eq $boundChar){
16416 next_chr();
16417
16418 if ($utf16) {
16419 decode_error("missing low surrogate character in surrogate pair");
16420 }
16421
16422 utf8::decode($s) if($is_utf8);
16423
16424 return $s;
16425 }
16426 elsif($ch eq '\\'){
16427 next_chr();
16428 if(exists $escapes{$ch}){
16429 $s .= $escapes{$ch};
16430 }
16431 elsif($ch eq 'u'){ # UNICODE handling
16432 my $u = '';
16433
16434 for(1..4){
16435 $ch = next_chr();
16436 last OUTER if($ch !~ /[0-9a-fA-F]/);
16437 $u .= $ch;
16438 }
16439
16440 # U+D800 - U+DBFF
16441 if ($u =~ /^[dD][89abAB][0-9a-fA-F]{2}/) { # UTF-16 high surrogate?
16442 $utf16 = $u;
16443 }
16444 # U+DC00 - U+DFFF
16445 elsif ($u =~ /^[dD][c-fC-F][0-9a-fA-F]{2}/) { # UTF-16 low surrogate?
16446 unless (defined $utf16) {
16447 decode_error("missing high surrogate character in surrogate pair");
16448 }
16449 $is_utf8 = 1;
16450 $s .= JSON_PP_decode_surrogates($utf16, $u) || next;
16451 $utf16 = undef;
16452 }
16453 else {
16454 if (defined $utf16) {
16455 decode_error("surrogate pair expected");
16456 }
16457
16458 if ( ( my $hex = hex( $u ) ) > 127 ) {
16459 $is_utf8 = 1;
16460 $s .= JSON_PP_decode_unicode($u) || next;
16461 }
16462 else {
16463 $s .= chr $hex;
16464 }
16465 }
16466
16467 }
16468 else{
16469 unless ($loose) {
16470 $at -= 2;
16471 decode_error('illegal backslash escape sequence in string');
16472 }
16473 $s .= $ch;
16474 }
16475 }
16476 else{
16477
16478 if ( ord $ch > 127 ) {
16479 unless( $ch = is_valid_utf8($ch) ) {
16480 $at -= 1;
16481 decode_error("malformed UTF-8 character in JSON string");
16482 }
16483 else {
16484 $at += $utf8_len - 1;
16485 }
16486
16487 $is_utf8 = 1;
16488 }
16489
16490 if (!$loose) {
16491 if ($ch =~ /[\x00-\x1f\x22\x5c]/) { # '/' ok
16492 $at--;
16493 decode_error('invalid character encountered while parsing JSON string');
16494 }
16495 }
16496
16497 $s .= $ch;
16498 }
16499 }
16500 }
16501
16502 decode_error("unexpected end of string while parsing JSON string");
16503 }
16504
16505
16506 sub white {
16507 while( defined $ch ){
16508 if($ch le ' '){
16509 next_chr();
16510 }
16511 elsif($ch eq '/'){
16512 next_chr();
16513 if(defined $ch and $ch eq '/'){
16514 1 while(defined(next_chr()) and $ch ne "\n" and $ch ne "\r");
16515 }
16516 elsif(defined $ch and $ch eq '*'){
16517 next_chr();
16518 while(1){
16519 if(defined $ch){
16520 if($ch eq '*'){
16521 if(defined(next_chr()) and $ch eq '/'){
16522 next_chr();
16523 last;
16524 }
16525 }
16526 else{
16527 next_chr();
16528 }
16529 }
16530 else{
16531 decode_error("Unterminated comment");
16532 }
16533 }
16534 next;
16535 }
16536 else{
16537 $at--;
16538 decode_error("malformed JSON string, neither array, object, number, string or atom");
16539 }
16540 }
16541 else{
16542 if ($relaxed and $ch eq '#') { # correctly?
16543 pos($text) = $at;
16544 $text =~ /\G([^\n]*(?:\r\n|\r|\n|$))/g;
16545 $at = pos($text);
16546 next_chr;
16547 next;
16548 }
16549
16550 last;
16551 }
16552 }
16553 }
16554
16555
16556 sub array {
16557 my $a = $_[0] || []; # you can use this code to use another array ref object.
16558
16559 decode_error('json text or perl structure exceeds maximum nesting level (max_depth set too low?)')
16560 if (++$depth > $max_depth);
16561
16562 next_chr();
16563 white();
16564
16565 if(defined $ch and $ch eq ']'){
16566 --$depth;
16567 next_chr();
16568 return $a;
16569 }
16570 else {
16571 while(defined($ch)){
16572 push @$a, value();
16573
16574 white();
16575
16576 if (!defined $ch) {
16577 last;
16578 }
16579
16580 if($ch eq ']'){
16581 --$depth;
16582 next_chr();
16583 return $a;
16584 }
16585
16586 if($ch ne ','){
16587 last;
16588 }
16589
16590 next_chr();
16591 white();
16592
16593 if ($relaxed and $ch eq ']') {
16594 --$depth;
16595 next_chr();
16596 return $a;
16597 }
16598
16599 }
16600 }
16601
16602 decode_error(", or ] expected while parsing array");
16603 }
16604
16605
16606 sub object {
16607 my $o = $_[0] || {}; # you can use this code to use another hash ref object.
16608 my $k;
16609
16610 decode_error('json text or perl structure exceeds maximum nesting level (max_depth set too low?)')
16611 if (++$depth > $max_depth);
16612 next_chr();
16613 white();
16614
16615 if(defined $ch and $ch eq '}'){
16616 --$depth;
16617 next_chr();
16618 if ($F_HOOK) {
16619 return _json_object_hook($o);
16620 }
16621 return $o;
16622 }
16623 else {
16624 while (defined $ch) {
16625 $k = ($allow_barekey and $ch ne '"' and $ch ne "'") ? bareKey() : string();
16626 white();
16627
16628 if(!defined $ch or $ch ne ':'){
16629 $at--;
16630 decode_error("':' expected");
16631 }
16632
16633 next_chr();
16634 $o->{$k} = value();
16635 white();
16636
16637 last if (!defined $ch);
16638
16639 if($ch eq '}'){
16640 --$depth;
16641 next_chr();
16642 if ($F_HOOK) {
16643 return _json_object_hook($o);
16644 }
16645 return $o;
16646 }
16647
16648 if($ch ne ','){
16649 last;
16650 }
16651
16652 next_chr();
16653 white();
16654
16655 if ($relaxed and $ch eq '}') {
16656 --$depth;
16657 next_chr();
16658 if ($F_HOOK) {
16659 return _json_object_hook($o);
16660 }
16661 return $o;
16662 }
16663
16664 }
16665
16666 }
16667
16668 $at--;
16669 decode_error(", or } expected while parsing object/hash");
16670 }
16671
16672
16673 sub bareKey { # doesn't strictly follow Standard ECMA-262 3rd Edition
16674 my $key;
16675 while($ch =~ /[^\x00-\x23\x25-\x2F\x3A-\x40\x5B-\x5E\x60\x7B-\x7F]/){
16676 $key .= $ch;
16677 next_chr();
16678 }
16679 return $key;
16680 }
16681
16682
16683 sub word {
16684 my $word = substr($text,$at-1,4);
16685
16686 if($word eq 'true'){
16687 $at += 3;
16688 next_chr;
16689 return $JSON::PP::true;
16690 }
16691 elsif($word eq 'null'){
16692 $at += 3;
16693 next_chr;
16694 return undef;
16695 }
16696 elsif($word eq 'fals'){
16697 $at += 3;
16698 if(substr($text,$at,1) eq 'e'){
16699 $at++;
16700 next_chr;
16701 return $JSON::PP::false;
16702 }
16703 }
16704
16705 $at--; # for decode_error report
16706
16707 decode_error("'null' expected") if ($word =~ /^n/);
16708 decode_error("'true' expected") if ($word =~ /^t/);
16709 decode_error("'false' expected") if ($word =~ /^f/);
16710 decode_error("malformed JSON string, neither array, object, number, string or atom");
16711 }
16712
16713
16714 sub number {
16715 my $n = '';
16716 my $v;
16717
16718 # According to RFC4627, hex or oct digts are invalid.
16719 if($ch eq '0'){
16720 my $peek = substr($text,$at,1);
16721 my $hex = $peek =~ /[xX]/; # 0 or 1
16722
16723 if($hex){
16724 decode_error("malformed number (leading zero must not be followed by another digit)");
16725 ($n) = ( substr($text, $at+1) =~ /^([0-9a-fA-F]+)/);
16726 }
16727 else{ # oct
16728 ($n) = ( substr($text, $at) =~ /^([0-7]+)/);
16729 if (defined $n and length $n > 1) {
16730 decode_error("malformed number (leading zero must not be followed by another digit)");
16731 }
16732 }
16733
16734 if(defined $n and length($n)){
16735 if (!$hex and length($n) == 1) {
16736 decode_error("malformed number (leading zero must not be followed by another digit)");
16737 }
16738 $at += length($n) + $hex;
16739 next_chr;
16740 return $hex ? hex($n) : oct($n);
16741 }
16742 }
16743
16744 if($ch eq '-'){
16745 $n = '-';
16746 next_chr;
16747 if (!defined $ch or $ch !~ /\d/) {
16748 decode_error("malformed number (no digits after initial minus)");
16749 }
16750 }
16751
16752 while(defined $ch and $ch =~ /\d/){
16753 $n .= $ch;
16754 next_chr;
16755 }
16756
16757 if(defined $ch and $ch eq '.'){
16758 $n .= '.';
16759
16760 next_chr;
16761 if (!defined $ch or $ch !~ /\d/) {
16762 decode_error("malformed number (no digits after decimal point)");
16763 }
16764 else {
16765 $n .= $ch;
16766 }
16767
16768 while(defined(next_chr) and $ch =~ /\d/){
16769 $n .= $ch;
16770 }
16771 }
16772
16773 if(defined $ch and ($ch eq 'e' or $ch eq 'E')){
16774 $n .= $ch;
16775 next_chr;
16776
16777 if(defined($ch) and ($ch eq '+' or $ch eq '-')){
16778 $n .= $ch;
16779 next_chr;
16780 if (!defined $ch or $ch =~ /\D/) {
16781 decode_error("malformed number (no digits after exp sign)");
16782 }
16783 $n .= $ch;
16784 }
16785 elsif(defined($ch) and $ch =~ /\d/){
16786 $n .= $ch;
16787 }
16788 else {
16789 decode_error("malformed number (no digits after exp sign)");
16790 }
16791
16792 while(defined(next_chr) and $ch =~ /\d/){
16793 $n .= $ch;
16794 }
16795
16796 }
16797
16798 $v .= $n;
16799
16800 if ($v !~ /[.eE]/ and length $v > $max_intsize) {
16801 if ($allow_bigint) { # from Adam Sussman
16802 require Math::BigInt;
16803 return Math::BigInt->new($v);
16804 }
16805 else {
16806 return "$v";
16807 }
16808 }
16809 elsif ($allow_bigint) {
16810 require Math::BigFloat;
16811 return Math::BigFloat->new($v);
16812 }
16813
16814 return 0+$v;
16815 }
16816
16817
16818 sub is_valid_utf8 {
16819
16820 $utf8_len = $_[0] =~ /[\x00-\x7F]/ ? 1
16821 : $_[0] =~ /[\xC2-\xDF]/ ? 2
16822 : $_[0] =~ /[\xE0-\xEF]/ ? 3
16823 : $_[0] =~ /[\xF0-\xF4]/ ? 4
16824 : 0
16825 ;
16826
16827 return unless $utf8_len;
16828
16829 my $is_valid_utf8 = substr($text, $at - 1, $utf8_len);
16830
16831 return ( $is_valid_utf8 =~ /^(?:
16832 [\x00-\x7F]
16833 |[\xC2-\xDF][\x80-\xBF]
16834 |[\xE0][\xA0-\xBF][\x80-\xBF]
16835 |[\xE1-\xEC][\x80-\xBF][\x80-\xBF]
16836 |[\xED][\x80-\x9F][\x80-\xBF]
16837 |[\xEE-\xEF][\x80-\xBF][\x80-\xBF]
16838 |[\xF0][\x90-\xBF][\x80-\xBF][\x80-\xBF]
16839 |[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF]
16840 |[\xF4][\x80-\x8F][\x80-\xBF][\x80-\xBF]
16841 )$/x ) ? $is_valid_utf8 : '';
16842 }
16843
16844
16845 sub decode_error {
16846 my $error = shift;
16847 my $no_rep = shift;
16848 my $str = defined $text ? substr($text, $at) : '';
16849 my $mess = '';
16850 my $type = $] >= 5.008 ? 'U*'
16851 : $] < 5.006 ? 'C*'
16852 : utf8::is_utf8( $str ) ? 'U*' # 5.6
16853 : 'C*'
16854 ;
16855
16856 for my $c ( unpack( $type, $str ) ) { # emulate pv_uni_display() ?
16857 $mess .= $c == 0x07 ? '\a'
16858 : $c == 0x09 ? '\t'
16859 : $c == 0x0a ? '\n'
16860 : $c == 0x0d ? '\r'
16861 : $c == 0x0c ? '\f'
16862 : $c < 0x20 ? sprintf('\x{%x}', $c)
16863 : $c == 0x5c ? '\\\\'
16864 : $c < 0x80 ? chr($c)
16865 : sprintf('\x{%x}', $c)
16866 ;
16867 if ( length $mess >= 20 ) {
16868 $mess .= '...';
16869 last;
16870 }
16871 }
16872
16873 unless ( length $mess ) {
16874 $mess = '(end of string)';
16875 }
16876
16877 Carp::croak (
16878 $no_rep ? "$error" : "$error, at character offset $at (before \"$mess\")"
16879 );
16880
16881 }
16882
16883
16884 sub _json_object_hook {
16885 my $o = $_[0];
16886 my @ks = keys %{$o};
16887
16888 if ( $cb_sk_object and @ks == 1 and exists $cb_sk_object->{ $ks[0] } and ref $cb_sk_object->{ $ks[0] } ) {
16889 my @val = $cb_sk_object->{ $ks[0] }->( $o->{$ks[0]} );
16890 if (@val == 1) {
16891 return $val[0];
16892 }
16893 }
16894
16895 my @val = $cb_object->($o) if ($cb_object);
16896 if (@val == 0 or @val > 1) {
16897 return $o;
16898 }
16899 else {
16900 return $val[0];
16901 }
16902 }
16903
16904
16905 sub PP_decode_box {
16906 {
16907 text => $text,
16908 at => $at,
16909 ch => $ch,
16910 len => $len,
16911 depth => $depth,
16912 encoding => $encoding,
16913 is_valid_utf8 => $is_valid_utf8,
16914 };
16915 }
16916
16917 } # PARSE
16918
16919
16920 sub _decode_surrogates { # from perlunicode
16921 my $uni = 0x10000 + (hex($_[0]) - 0xD800) * 0x400 + (hex($_[1]) - 0xDC00);
16922 my $un = pack('U*', $uni);
16923 utf8::encode( $un );
16924 return $un;
16925 }
16926
16927
16928 sub _decode_unicode {
16929 my $un = pack('U', hex shift);
16930 utf8::encode( $un );
16931 return $un;
16932 }
16933
16934 #
16935 # Setup for various Perl versions (the code from JSON::PP58)
16936 #
16937
16938 BEGIN {
16939
16940 unless ( defined &utf8::is_utf8 ) {
16941 require Encode;
16942 *utf8::is_utf8 = *Encode::is_utf8;
16943 }
16944
16945 if ( $] >= 5.008 ) {
16946 *JSON::PP::JSON_PP_encode_ascii = \&_encode_ascii;
16947 *JSON::PP::JSON_PP_encode_latin1 = \&_encode_latin1;
16948 *JSON::PP::JSON_PP_decode_surrogates = \&_decode_surrogates;
16949 *JSON::PP::JSON_PP_decode_unicode = \&_decode_unicode;
16950 }
16951
16952 if ($] >= 5.008 and $] < 5.008003) { # join() in 5.8.0 - 5.8.2 is broken.
16953 package JSON::PP;
16954 require subs;
16955 subs->import('join');
16956 eval q|
16957 sub join {
16958 return '' if (@_ < 2);
16959 my $j = shift;
16960 my $str = shift;
16961 for (@_) { $str .= $j . $_; }
16962 return $str;
16963 }
16964 |;
16965 }
16966
16967
16968 sub JSON::PP::incr_parse {
16969 local $Carp::CarpLevel = 1;
16970 ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_parse( @_ );
16971 }
16972
16973
16974 sub JSON::PP::incr_skip {
16975 ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_skip;
16976 }
16977
16978
16979 sub JSON::PP::incr_reset {
16980 ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_reset;
16981 }
16982
16983 eval q{
16984 sub JSON::PP::incr_text : lvalue {
16985 $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new;
16986
16987 if ( $_[0]->{_incr_parser}->{incr_parsing} ) {
16988 Carp::croak("incr_text can not be called when the incremental parser already started parsing");
16989 }
16990 $_[0]->{_incr_parser}->{incr_text};
16991 }
16992 } if ( $] >= 5.006 );
16993
16994 } # Setup for various Perl versions (the code from JSON::PP58)
16995
16996
16997 ###############################
16998 # Utilities
16999 #
17000
17001 BEGIN {
17002 eval 'require Scalar::Util';
17003 unless($@){
17004 *JSON::PP::blessed = \&Scalar::Util::blessed;
17005 *JSON::PP::reftype = \&Scalar::Util::reftype;
17006 *JSON::PP::refaddr = \&Scalar::Util::refaddr;
17007 }
17008 else{ # This code is from Sclar::Util.
17009 # warn $@;
17010 eval 'sub UNIVERSAL::a_sub_not_likely_to_be_here { ref($_[0]) }';
17011 *JSON::PP::blessed = sub {
17012 local($@, $SIG{__DIE__}, $SIG{__WARN__});
17013 ref($_[0]) ? eval { $_[0]->a_sub_not_likely_to_be_here } : undef;
17014 };
17015 my %tmap = qw(
17016 B::NULL SCALAR
17017 B::HV HASH
17018 B::AV ARRAY
17019 B::CV CODE
17020 B::IO IO
17021 B::GV GLOB
17022 B::REGEXP REGEXP
17023 );
17024 *JSON::PP::reftype = sub {
17025 my $r = shift;
17026
17027 return undef unless length(ref($r));
17028
17029 my $t = ref(B::svref_2object($r));
17030
17031 return
17032 exists $tmap{$t} ? $tmap{$t}
17033 : length(ref($$r)) ? 'REF'
17034 : 'SCALAR';
17035 };
17036 *JSON::PP::refaddr = sub {
17037 return undef unless length(ref($_[0]));
17038
17039 my $addr;
17040 if(defined(my $pkg = blessed($_[0]))) {
17041 $addr .= bless $_[0], 'Scalar::Util::Fake';
17042 bless $_[0], $pkg;
17043 }
17044 else {
17045 $addr .= $_[0]
17046 }
17047
17048 $addr =~ /0x(\w+)/;
17049 local $^W;
17050 #no warnings 'portable';
17051 hex($1);
17052 }
17053 }
17054 }
17055
17056
17057 # shamely copied and modified from JSON::XS code.
17058
17059 $JSON::PP::true = do { bless \(my $dummy = 1), "JSON::PP::Boolean" };
17060 $JSON::PP::false = do { bless \(my $dummy = 0), "JSON::PP::Boolean" };
17061
17062 sub is_bool { defined $_[0] and UNIVERSAL::isa($_[0], "JSON::PP::Boolean"); }
17063
17064 sub true { $JSON::PP::true }
17065 sub false { $JSON::PP::false }
17066 sub null { undef; }
17067
17068 ###############################
17069
17070 package JSON::PP::Boolean;
17071
17072 use overload (
17073 "0+" => sub { ${$_[0]} },
17074 "++" => sub { $_[0] = ${$_[0]} + 1 },
17075 "--" => sub { $_[0] = ${$_[0]} - 1 },
17076 fallback => 1,
17077 );
17078
17079
17080 ###############################
17081
17082 package JSON::PP::IncrParser;
17083
17084 use strict;
17085
17086 use constant INCR_M_WS => 0; # initial whitespace skipping
17087 use constant INCR_M_STR => 1; # inside string
17088 use constant INCR_M_BS => 2; # inside backslash
17089 use constant INCR_M_JSON => 3; # outside anything, count nesting
17090 use constant INCR_M_C0 => 4;
17091 use constant INCR_M_C1 => 5;
17092
17093 $JSON::PP::IncrParser::VERSION = '1.01';
17094
17095 my $unpack_format = $] < 5.006 ? 'C*' : 'U*';
17096
17097 sub new {
17098 my ( $class ) = @_;
17099
17100 bless {
17101 incr_nest => 0,
17102 incr_text => undef,
17103 incr_parsing => 0,
17104 incr_p => 0,
17105 }, $class;
17106 }
17107
17108
17109 sub incr_parse {
17110 my ( $self, $coder, $text ) = @_;
17111
17112 $self->{incr_text} = '' unless ( defined $self->{incr_text} );
17113
17114 if ( defined $text ) {
17115 if ( utf8::is_utf8( $text ) and !utf8::is_utf8( $self->{incr_text} ) ) {
17116 utf8::upgrade( $self->{incr_text} ) ;
17117 utf8::decode( $self->{incr_text} ) ;
17118 }
17119 $self->{incr_text} .= $text;
17120 }
17121
17122
17123 my $max_size = $coder->get_max_size;
17124
17125 if ( defined wantarray ) {
17126
17127 $self->{incr_mode} = INCR_M_WS unless defined $self->{incr_mode};
17128
17129 if ( wantarray ) {
17130 my @ret;
17131
17132 $self->{incr_parsing} = 1;
17133
17134 do {
17135 push @ret, $self->_incr_parse( $coder, $self->{incr_text} );
17136
17137 unless ( !$self->{incr_nest} and $self->{incr_mode} == INCR_M_JSON ) {
17138 $self->{incr_mode} = INCR_M_WS if $self->{incr_mode} != INCR_M_STR;
17139 }
17140
17141 } until ( length $self->{incr_text} >= $self->{incr_p} );
17142
17143 $self->{incr_parsing} = 0;
17144
17145 return @ret;
17146 }
17147 else { # in scalar context
17148 $self->{incr_parsing} = 1;
17149 my $obj = $self->_incr_parse( $coder, $self->{incr_text} );
17150 $self->{incr_parsing} = 0 if defined $obj; # pointed by Martin J. Evans
17151 return $obj ? $obj : undef; # $obj is an empty string, parsing was completed.
17152 }
17153
17154 }
17155
17156 }
17157
17158
17159 sub _incr_parse {
17160 my ( $self, $coder, $text, $skip ) = @_;
17161 my $p = $self->{incr_p};
17162 my $restore = $p;
17163
17164 my @obj;
17165 my $len = length $text;
17166
17167 if ( $self->{incr_mode} == INCR_M_WS ) {
17168 while ( $len > $p ) {
17169 my $s = substr( $text, $p, 1 );
17170 $p++ and next if ( 0x20 >= unpack($unpack_format, $s) );
17171 $self->{incr_mode} = INCR_M_JSON;
17172 last;
17173 }
17174 }
17175
17176 while ( $len > $p ) {
17177 my $s = substr( $text, $p++, 1 );
17178
17179 if ( $s eq '"' ) {
17180 if (substr( $text, $p - 2, 1 ) eq '\\' ) {
17181 next;
17182 }
17183
17184 if ( $self->{incr_mode} != INCR_M_STR ) {
17185 $self->{incr_mode} = INCR_M_STR;
17186 }
17187 else {
17188 $self->{incr_mode} = INCR_M_JSON;
17189 unless ( $self->{incr_nest} ) {
17190 last;
17191 }
17192 }
17193 }
17194
17195 if ( $self->{incr_mode} == INCR_M_JSON ) {
17196
17197 if ( $s eq '[' or $s eq '{' ) {
17198 if ( ++$self->{incr_nest} > $coder->get_max_depth ) {
17199 Carp::croak('json text or perl structure exceeds maximum nesting level (max_depth set too low?)');
17200 }
17201 }
17202 elsif ( $s eq ']' or $s eq '}' ) {
17203 last if ( --$self->{incr_nest} <= 0 );
17204 }
17205 elsif ( $s eq '#' ) {
17206 while ( $len > $p ) {
17207 last if substr( $text, $p++, 1 ) eq "\n";
17208 }
17209 }
17210
17211 }
17212
17213 }
17214
17215 $self->{incr_p} = $p;
17216
17217 return if ( $self->{incr_mode} == INCR_M_STR and not $self->{incr_nest} );
17218 return if ( $self->{incr_mode} == INCR_M_JSON and $self->{incr_nest} > 0 );
17219
17220 return '' unless ( length substr( $self->{incr_text}, 0, $p ) );
17221
17222 local $Carp::CarpLevel = 2;
17223
17224 $self->{incr_p} = $restore;
17225 $self->{incr_c} = $p;
17226
17227 my ( $obj, $tail ) = $coder->PP_decode_json( substr( $self->{incr_text}, 0, $p ), 0x10000001 );
17228
17229 $self->{incr_text} = substr( $self->{incr_text}, $p );
17230 $self->{incr_p} = 0;
17231
17232 return $obj || '';
17233 }
17234
17235
17236 sub incr_text {
17237 if ( $_[0]->{incr_parsing} ) {
17238 Carp::croak("incr_text can not be called when the incremental parser already started parsing");
17239 }
17240 $_[0]->{incr_text};
17241 }
17242
17243
17244 sub incr_skip {
17245 my $self = shift;
17246 $self->{incr_text} = substr( $self->{incr_text}, $self->{incr_c} );
17247 $self->{incr_p} = 0;
17248 }
17249
17250
17251 sub incr_reset {
17252 my $self = shift;
17253 $self->{incr_text} = undef;
17254 $self->{incr_p} = 0;
17255 $self->{incr_mode} = 0;
17256 $self->{incr_nest} = 0;
17257 $self->{incr_parsing} = 0;
17258 }
17259
17260 ###############################
17261
17262
17263 1;
17264 __END__
17265 =pod
17266
17267 =head1 NAME
17268
17269 JSON::PP - JSON::XS compatible pure-Perl module.
17270
17271 =head1 SYNOPSIS
17272
17273 use JSON::PP;
17274
17275 # exported functions, they croak on error
17276 # and expect/generate UTF-8
17277
17278 $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
17279 $perl_hash_or_arrayref = decode_json $utf8_encoded_json_text;
17280
17281 # OO-interface
17282
17283 $coder = JSON::PP->new->ascii->pretty->allow_nonref;
17284
17285 $json_text = $json->encode( $perl_scalar );
17286 $perl_scalar = $json->decode( $json_text );
17287
17288 $pretty_printed = $json->pretty->encode( $perl_scalar ); # pretty-printing
17289
17290 # Note that JSON version 2.0 and above will automatically use
17291 # JSON::XS or JSON::PP, so you should be able to just:
17292
17293 use JSON;
17294
17295
17296 =head1 VERSION
17297
17298 2.27300
17299
17300 L<JSON::XS> 2.27 (~2.30) compatible.
17301
17302 =head1 NOTE
17303
17304 JSON::PP had been inculded in JSON distribution (CPAN module).
17305 It was a perl core module in Perl 5.14.
17306
17307 =head1 DESCRIPTION
17308
17309 This module is L<JSON::XS> compatible pure Perl module.
17310 (Perl 5.8 or later is recommended)
17311
17312 JSON::XS is the fastest and most proper JSON module on CPAN.
17313 It is written by Marc Lehmann in C, so must be compiled and
17314 installed in the used environment.
17315
17316 JSON::PP is a pure-Perl module and has compatibility to JSON::XS.
17317
17318
17319 =head2 FEATURES
17320
17321 =over
17322
17323 =item * correct unicode handling
17324
17325 This module knows how to handle Unicode (depending on Perl version).
17326
17327 See to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL> and L<UNICODE HANDLING ON PERLS>.
17328
17329
17330 =item * round-trip integrity
17331
17332 When you serialise a perl data structure using only data types supported
17333 by JSON and Perl, the deserialised data structure is identical on the Perl
17334 level. (e.g. the string "2.0" doesn't suddenly become "2" just because
17335 it looks like a number). There I<are> minor exceptions to this, read the
17336 MAPPING section below to learn about those.
17337
17338
17339 =item * strict checking of JSON correctness
17340
17341 There is no guessing, no generating of illegal JSON texts by default,
17342 and only JSON is accepted as input by default (the latter is a security feature).
17343 But when some options are set, loose chcking features are available.
17344
17345 =back
17346
17347 =head1 FUNCTIONAL INTERFACE
17348
17349 Some documents are copied and modified from L<JSON::XS/FUNCTIONAL INTERFACE>.
17350
17351 =head2 encode_json
17352
17353 $json_text = encode_json $perl_scalar
17354
17355 Converts the given Perl data structure to a UTF-8 encoded, binary string.
17356
17357 This function call is functionally identical to:
17358
17359 $json_text = JSON::PP->new->utf8->encode($perl_scalar)
17360
17361 =head2 decode_json
17362
17363 $perl_scalar = decode_json $json_text
17364
17365 The opposite of C<encode_json>: expects an UTF-8 (binary) string and tries
17366 to parse that as an UTF-8 encoded JSON text, returning the resulting
17367 reference.
17368
17369 This function call is functionally identical to:
17370
17371 $perl_scalar = JSON::PP->new->utf8->decode($json_text)
17372
17373 =head2 JSON::PP::is_bool
17374
17375 $is_boolean = JSON::PP::is_bool($scalar)
17376
17377 Returns true if the passed scalar represents either JSON::PP::true or
17378 JSON::PP::false, two constants that act like C<1> and C<0> respectively
17379 and are also used to represent JSON C<true> and C<false> in Perl strings.
17380
17381 =head2 JSON::PP::true
17382
17383 Returns JSON true value which is blessed object.
17384 It C<isa> JSON::PP::Boolean object.
17385
17386 =head2 JSON::PP::false
17387
17388 Returns JSON false value which is blessed object.
17389 It C<isa> JSON::PP::Boolean object.
17390
17391 =head2 JSON::PP::null
17392
17393 Returns C<undef>.
17394
17395 See L<MAPPING>, below, for more information on how JSON values are mapped to
17396 Perl.
17397
17398
17399 =head1 HOW DO I DECODE A DATA FROM OUTER AND ENCODE TO OUTER
17400
17401 This section supposes that your perl vresion is 5.8 or later.
17402
17403 If you know a JSON text from an outer world - a network, a file content, and so on,
17404 is encoded in UTF-8, you should use C<decode_json> or C<JSON> module object
17405 with C<utf8> enable. And the decoded result will contain UNICODE characters.
17406
17407 # from network
17408 my $json = JSON::PP->new->utf8;
17409 my $json_text = CGI->new->param( 'json_data' );
17410 my $perl_scalar = $json->decode( $json_text );
17411
17412 # from file content
17413 local $/;
17414 open( my $fh, '<', 'json.data' );
17415 $json_text = <$fh>;
17416 $perl_scalar = decode_json( $json_text );
17417
17418 If an outer data is not encoded in UTF-8, firstly you should C<decode> it.
17419
17420 use Encode;
17421 local $/;
17422 open( my $fh, '<', 'json.data' );
17423 my $encoding = 'cp932';
17424 my $unicode_json_text = decode( $encoding, <$fh> ); # UNICODE
17425
17426 # or you can write the below code.
17427 #
17428 # open( my $fh, "<:encoding($encoding)", 'json.data' );
17429 # $unicode_json_text = <$fh>;
17430
17431 In this case, C<$unicode_json_text> is of course UNICODE string.
17432 So you B<cannot> use C<decode_json> nor C<JSON> module object with C<utf8> enable.
17433 Instead of them, you use C<JSON> module object with C<utf8> disable.
17434
17435 $perl_scalar = $json->utf8(0)->decode( $unicode_json_text );
17436
17437 Or C<encode 'utf8'> and C<decode_json>:
17438
17439 $perl_scalar = decode_json( encode( 'utf8', $unicode_json_text ) );
17440 # this way is not efficient.
17441
17442 And now, you want to convert your C<$perl_scalar> into JSON data and
17443 send it to an outer world - a network or a file content, and so on.
17444
17445 Your data usually contains UNICODE strings and you want the converted data to be encoded
17446 in UTF-8, you should use C<encode_json> or C<JSON> module object with C<utf8> enable.
17447
17448 print encode_json( $perl_scalar ); # to a network? file? or display?
17449 # or
17450 print $json->utf8->encode( $perl_scalar );
17451
17452 If C<$perl_scalar> does not contain UNICODE but C<$encoding>-encoded strings
17453 for some reason, then its characters are regarded as B<latin1> for perl
17454 (because it does not concern with your $encoding).
17455 You B<cannot> use C<encode_json> nor C<JSON> module object with C<utf8> enable.
17456 Instead of them, you use C<JSON> module object with C<utf8> disable.
17457 Note that the resulted text is a UNICODE string but no problem to print it.
17458
17459 # $perl_scalar contains $encoding encoded string values
17460 $unicode_json_text = $json->utf8(0)->encode( $perl_scalar );
17461 # $unicode_json_text consists of characters less than 0x100
17462 print $unicode_json_text;
17463
17464 Or C<decode $encoding> all string values and C<encode_json>:
17465
17466 $perl_scalar->{ foo } = decode( $encoding, $perl_scalar->{ foo } );
17467 # ... do it to each string values, then encode_json
17468 $json_text = encode_json( $perl_scalar );
17469
17470 This method is a proper way but probably not efficient.
17471
17472 See to L<Encode>, L<perluniintro>.
17473
17474
17475 =head1 METHODS
17476
17477 Basically, check to L<JSON> or L<JSON::XS>.
17478
17479 =head2 new
17480
17481 $json = JSON::PP->new
17482
17483 Rturns a new JSON::PP object that can be used to de/encode JSON
17484 strings.
17485
17486 All boolean flags described below are by default I<disabled>.
17487
17488 The mutators for flags all return the JSON object again and thus calls can
17489 be chained:
17490
17491 my $json = JSON::PP->new->utf8->space_after->encode({a => [1,2]})
17492 => {"a": [1, 2]}
17493
17494 =head2 ascii
17495
17496 $json = $json->ascii([$enable])
17497
17498 $enabled = $json->get_ascii
17499
17500 If $enable is true (or missing), then the encode method will not generate characters outside
17501 the code range 0..127. Any Unicode characters outside that range will be escaped using either
17502 a single \uXXXX or a double \uHHHH\uLLLLL escape sequence, as per RFC4627.
17503 (See to L<JSON::XS/OBJECT-ORIENTED INTERFACE>).
17504
17505 In Perl 5.005, there is no character having high value (more than 255).
17506 See to L<UNICODE HANDLING ON PERLS>.
17507
17508 If $enable is false, then the encode method will not escape Unicode characters unless
17509 required by the JSON syntax or other flags. This results in a faster and more compact format.
17510
17511 JSON::PP->new->ascii(1)->encode([chr 0x10401])
17512 => ["\ud801\udc01"]
17513
17514 =head2 latin1
17515
17516 $json = $json->latin1([$enable])
17517
17518 $enabled = $json->get_latin1
17519
17520 If $enable is true (or missing), then the encode method will encode the resulting JSON
17521 text as latin1 (or iso-8859-1), escaping any characters outside the code range 0..255.
17522
17523 If $enable is false, then the encode method will not escape Unicode characters
17524 unless required by the JSON syntax or other flags.
17525
17526 JSON::XS->new->latin1->encode (["\x{89}\x{abc}"]
17527 => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not)
17528
17529 See to L<UNICODE HANDLING ON PERLS>.
17530
17531 =head2 utf8
17532
17533 $json = $json->utf8([$enable])
17534
17535 $enabled = $json->get_utf8
17536
17537 If $enable is true (or missing), then the encode method will encode the JSON result
17538 into UTF-8, as required by many protocols, while the decode method expects to be handled
17539 an UTF-8-encoded string. Please note that UTF-8-encoded strings do not contain any
17540 characters outside the range 0..255, they are thus useful for bytewise/binary I/O.
17541
17542 (In Perl 5.005, any character outside the range 0..255 does not exist.
17543 See to L<UNICODE HANDLING ON PERLS>.)
17544
17545 In future versions, enabling this option might enable autodetection of the UTF-16 and UTF-32
17546 encoding families, as described in RFC4627.
17547
17548 If $enable is false, then the encode method will return the JSON string as a (non-encoded)
17549 Unicode string, while decode expects thus a Unicode string. Any decoding or encoding
17550 (e.g. to UTF-8 or UTF-16) needs to be done yourself, e.g. using the Encode module.
17551
17552 Example, output UTF-16BE-encoded JSON:
17553
17554 use Encode;
17555 $jsontext = encode "UTF-16BE", JSON::PP->new->encode ($object);
17556
17557 Example, decode UTF-32LE-encoded JSON:
17558
17559 use Encode;
17560 $object = JSON::PP->new->decode (decode "UTF-32LE", $jsontext);
17561
17562
17563 =head2 pretty
17564
17565 $json = $json->pretty([$enable])
17566
17567 This enables (or disables) all of the C<indent>, C<space_before> and
17568 C<space_after> flags in one call to generate the most readable
17569 (or most compact) form possible.
17570
17571 Equivalent to:
17572
17573 $json->indent->space_before->space_after
17574
17575 =head2 indent
17576
17577 $json = $json->indent([$enable])
17578
17579 $enabled = $json->get_indent
17580
17581 The default indent space length is three.
17582 You can use C<indent_length> to change the length.
17583
17584 =head2 space_before
17585
17586 $json = $json->space_before([$enable])
17587
17588 $enabled = $json->get_space_before
17589
17590 If C<$enable> is true (or missing), then the C<encode> method will add an extra
17591 optional space before the C<:> separating keys from values in JSON objects.
17592
17593 If C<$enable> is false, then the C<encode> method will not add any extra
17594 space at those places.
17595
17596 This setting has no effect when decoding JSON texts.
17597
17598 Example, space_before enabled, space_after and indent disabled:
17599
17600 {"key" :"value"}
17601
17602 =head2 space_after
17603
17604 $json = $json->space_after([$enable])
17605
17606 $enabled = $json->get_space_after
17607
17608 If C<$enable> is true (or missing), then the C<encode> method will add an extra
17609 optional space after the C<:> separating keys from values in JSON objects
17610 and extra whitespace after the C<,> separating key-value pairs and array
17611 members.
17612
17613 If C<$enable> is false, then the C<encode> method will not add any extra
17614 space at those places.
17615
17616 This setting has no effect when decoding JSON texts.
17617
17618 Example, space_before and indent disabled, space_after enabled:
17619
17620 {"key": "value"}
17621
17622 =head2 relaxed
17623
17624 $json = $json->relaxed([$enable])
17625
17626 $enabled = $json->get_relaxed
17627
17628 If C<$enable> is true (or missing), then C<decode> will accept some
17629 extensions to normal JSON syntax (see below). C<encode> will not be
17630 affected in anyway. I<Be aware that this option makes you accept invalid
17631 JSON texts as if they were valid!>. I suggest only to use this option to
17632 parse application-specific files written by humans (configuration files,
17633 resource files etc.)
17634
17635 If C<$enable> is false (the default), then C<decode> will only accept
17636 valid JSON texts.
17637
17638 Currently accepted extensions are:
17639
17640 =over 4
17641
17642 =item * list items can have an end-comma
17643
17644 JSON I<separates> array elements and key-value pairs with commas. This
17645 can be annoying if you write JSON texts manually and want to be able to
17646 quickly append elements, so this extension accepts comma at the end of
17647 such items not just between them:
17648
17649 [
17650 1,
17651 2, <- this comma not normally allowed
17652 ]
17653 {
17654 "k1": "v1",
17655 "k2": "v2", <- this comma not normally allowed
17656 }
17657
17658 =item * shell-style '#'-comments
17659
17660 Whenever JSON allows whitespace, shell-style comments are additionally
17661 allowed. They are terminated by the first carriage-return or line-feed
17662 character, after which more white-space and comments are allowed.
17663
17664 [
17665 1, # this comment not allowed in JSON
17666 # neither this one...
17667 ]
17668
17669 =back
17670
17671 =head2 canonical
17672
17673 $json = $json->canonical([$enable])
17674
17675 $enabled = $json->get_canonical
17676
17677 If C<$enable> is true (or missing), then the C<encode> method will output JSON objects
17678 by sorting their keys. This is adding a comparatively high overhead.
17679
17680 If C<$enable> is false, then the C<encode> method will output key-value
17681 pairs in the order Perl stores them (which will likely change between runs
17682 of the same script).
17683
17684 This option is useful if you want the same data structure to be encoded as
17685 the same JSON text (given the same overall settings). If it is disabled,
17686 the same hash might be encoded differently even if contains the same data,
17687 as key-value pairs have no inherent ordering in Perl.
17688
17689 This setting has no effect when decoding JSON texts.
17690
17691 If you want your own sorting routine, you can give a code referece
17692 or a subroutine name to C<sort_by>. See to C<JSON::PP OWN METHODS>.
17693
17694 =head2 allow_nonref
17695
17696 $json = $json->allow_nonref([$enable])
17697
17698 $enabled = $json->get_allow_nonref
17699
17700 If C<$enable> is true (or missing), then the C<encode> method can convert a
17701 non-reference into its corresponding string, number or null JSON value,
17702 which is an extension to RFC4627. Likewise, C<decode> will accept those JSON
17703 values instead of croaking.
17704
17705 If C<$enable> is false, then the C<encode> method will croak if it isn't
17706 passed an arrayref or hashref, as JSON texts must either be an object
17707 or array. Likewise, C<decode> will croak if given something that is not a
17708 JSON object or array.
17709
17710 JSON::PP->new->allow_nonref->encode ("Hello, World!")
17711 => "Hello, World!"
17712
17713 =head2 allow_unknown
17714
17715 $json = $json->allow_unknown ([$enable])
17716
17717 $enabled = $json->get_allow_unknown
17718
17719 If $enable is true (or missing), then "encode" will *not* throw an
17720 exception when it encounters values it cannot represent in JSON (for
17721 example, filehandles) but instead will encode a JSON "null" value.
17722 Note that blessed objects are not included here and are handled
17723 separately by c<allow_nonref>.
17724
17725 If $enable is false (the default), then "encode" will throw an
17726 exception when it encounters anything it cannot encode as JSON.
17727
17728 This option does not affect "decode" in any way, and it is
17729 recommended to leave it off unless you know your communications
17730 partner.
17731
17732 =head2 allow_blessed
17733
17734 $json = $json->allow_blessed([$enable])
17735
17736 $enabled = $json->get_allow_blessed
17737
17738 If C<$enable> is true (or missing), then the C<encode> method will not
17739 barf when it encounters a blessed reference. Instead, the value of the
17740 B<convert_blessed> option will decide whether C<null> (C<convert_blessed>
17741 disabled or no C<TO_JSON> method found) or a representation of the
17742 object (C<convert_blessed> enabled and C<TO_JSON> method found) is being
17743 encoded. Has no effect on C<decode>.
17744
17745 If C<$enable> is false (the default), then C<encode> will throw an
17746 exception when it encounters a blessed object.
17747
17748 =head2 convert_blessed
17749
17750 $json = $json->convert_blessed([$enable])
17751
17752 $enabled = $json->get_convert_blessed
17753
17754 If C<$enable> is true (or missing), then C<encode>, upon encountering a
17755 blessed object, will check for the availability of the C<TO_JSON> method
17756 on the object's class. If found, it will be called in scalar context
17757 and the resulting scalar will be encoded instead of the object. If no
17758 C<TO_JSON> method is found, the value of C<allow_blessed> will decide what
17759 to do.
17760
17761 The C<TO_JSON> method may safely call die if it wants. If C<TO_JSON>
17762 returns other blessed objects, those will be handled in the same
17763 way. C<TO_JSON> must take care of not causing an endless recursion cycle
17764 (== crash) in this case. The name of C<TO_JSON> was chosen because other
17765 methods called by the Perl core (== not by the user of the object) are
17766 usually in upper case letters and to avoid collisions with the C<to_json>
17767 function or method.
17768
17769 This setting does not yet influence C<decode> in any way.
17770
17771 If C<$enable> is false, then the C<allow_blessed> setting will decide what
17772 to do when a blessed object is found.
17773
17774 =head2 filter_json_object
17775
17776 $json = $json->filter_json_object([$coderef])
17777
17778 When C<$coderef> is specified, it will be called from C<decode> each
17779 time it decodes a JSON object. The only argument passed to the coderef
17780 is a reference to the newly-created hash. If the code references returns
17781 a single scalar (which need not be a reference), this value
17782 (i.e. a copy of that scalar to avoid aliasing) is inserted into the
17783 deserialised data structure. If it returns an empty list
17784 (NOTE: I<not> C<undef>, which is a valid scalar), the original deserialised
17785 hash will be inserted. This setting can slow down decoding considerably.
17786
17787 When C<$coderef> is omitted or undefined, any existing callback will
17788 be removed and C<decode> will not change the deserialised hash in any
17789 way.
17790
17791 Example, convert all JSON objects into the integer 5:
17792
17793 my $js = JSON::PP->new->filter_json_object (sub { 5 });
17794 # returns [5]
17795 $js->decode ('[{}]'); # the given subroutine takes a hash reference.
17796 # throw an exception because allow_nonref is not enabled
17797 # so a lone 5 is not allowed.
17798 $js->decode ('{"a":1, "b":2}');
17799
17800 =head2 filter_json_single_key_object
17801
17802 $json = $json->filter_json_single_key_object($key [=> $coderef])
17803
17804 Works remotely similar to C<filter_json_object>, but is only called for
17805 JSON objects having a single key named C<$key>.
17806
17807 This C<$coderef> is called before the one specified via
17808 C<filter_json_object>, if any. It gets passed the single value in the JSON
17809 object. If it returns a single value, it will be inserted into the data
17810 structure. If it returns nothing (not even C<undef> but the empty list),
17811 the callback from C<filter_json_object> will be called next, as if no
17812 single-key callback were specified.
17813
17814 If C<$coderef> is omitted or undefined, the corresponding callback will be
17815 disabled. There can only ever be one callback for a given key.
17816
17817 As this callback gets called less often then the C<filter_json_object>
17818 one, decoding speed will not usually suffer as much. Therefore, single-key
17819 objects make excellent targets to serialise Perl objects into, especially
17820 as single-key JSON objects are as close to the type-tagged value concept
17821 as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not
17822 support this in any way, so you need to make sure your data never looks
17823 like a serialised Perl hash.
17824
17825 Typical names for the single object key are C<__class_whatever__>, or
17826 C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even
17827 things like C<__class_md5sum(classname)__>, to reduce the risk of clashing
17828 with real hashes.
17829
17830 Example, decode JSON objects of the form C<< { "__widget__" => <id> } >>
17831 into the corresponding C<< $WIDGET{<id>} >> object:
17832
17833 # return whatever is in $WIDGET{5}:
17834 JSON::PP
17835 ->new
17836 ->filter_json_single_key_object (__widget__ => sub {
17837 $WIDGET{ $_[0] }
17838 })
17839 ->decode ('{"__widget__": 5')
17840
17841 # this can be used with a TO_JSON method in some "widget" class
17842 # for serialisation to json:
17843 sub WidgetBase::TO_JSON {
17844 my ($self) = @_;
17845
17846 unless ($self->{id}) {
17847 $self->{id} = ..get..some..id..;
17848 $WIDGET{$self->{id}} = $self;
17849 }
17850
17851 { __widget__ => $self->{id} }
17852 }
17853
17854 =head2 shrink
17855
17856 $json = $json->shrink([$enable])
17857
17858 $enabled = $json->get_shrink
17859
17860 In JSON::XS, this flag resizes strings generated by either
17861 C<encode> or C<decode> to their minimum size possible.
17862 It will also try to downgrade any strings to octet-form if possible.
17863
17864 In JSON::PP, it is noop about resizing strings but tries
17865 C<utf8::downgrade> to the returned string by C<encode>.
17866 See to L<utf8>.
17867
17868 See to L<JSON::XS/OBJECT-ORIENTED INTERFACE>
17869
17870 =head2 max_depth
17871
17872 $json = $json->max_depth([$maximum_nesting_depth])
17873
17874 $max_depth = $json->get_max_depth
17875
17876 Sets the maximum nesting level (default C<512>) accepted while encoding
17877 or decoding. If a higher nesting level is detected in JSON text or a Perl
17878 data structure, then the encoder and decoder will stop and croak at that
17879 point.
17880
17881 Nesting level is defined by number of hash- or arrayrefs that the encoder
17882 needs to traverse to reach a given point or the number of C<{> or C<[>
17883 characters without their matching closing parenthesis crossed to reach a
17884 given character in a string.
17885
17886 If no argument is given, the highest possible setting will be used, which
17887 is rarely useful.
17888
17889 See L<JSON::XS/SSECURITY CONSIDERATIONS> for more info on why this is useful.
17890
17891 When a large value (100 or more) was set and it de/encodes a deep nested object/text,
17892 it may raise a warning 'Deep recursion on subroutin' at the perl runtime phase.
17893
17894 =head2 max_size
17895
17896 $json = $json->max_size([$maximum_string_size])
17897
17898 $max_size = $json->get_max_size
17899
17900 Set the maximum length a JSON text may have (in bytes) where decoding is
17901 being attempted. The default is C<0>, meaning no limit. When C<decode>
17902 is called on a string that is longer then this many bytes, it will not
17903 attempt to decode the string but throw an exception. This setting has no
17904 effect on C<encode> (yet).
17905
17906 If no argument is given, the limit check will be deactivated (same as when
17907 C<0> is specified).
17908
17909 See L<JSON::XS/SSECURITY CONSIDERATIONS> for more info on why this is useful.
17910
17911 =head2 encode
17912
17913 $json_text = $json->encode($perl_scalar)
17914
17915 Converts the given Perl data structure (a simple scalar or a reference
17916 to a hash or array) to its JSON representation. Simple scalars will be
17917 converted into JSON string or number sequences, while references to arrays
17918 become JSON arrays and references to hashes become JSON objects. Undefined
17919 Perl values (e.g. C<undef>) become JSON C<null> values.
17920 References to the integers C<0> and C<1> are converted into C<true> and C<false>.
17921
17922 =head2 decode
17923
17924 $perl_scalar = $json->decode($json_text)
17925
17926 The opposite of C<encode>: expects a JSON text and tries to parse it,
17927 returning the resulting simple scalar or reference. Croaks on error.
17928
17929 JSON numbers and strings become simple Perl scalars. JSON arrays become
17930 Perl arrayrefs and JSON objects become Perl hashrefs. C<true> becomes
17931 C<1> (C<JSON::true>), C<false> becomes C<0> (C<JSON::false>) and
17932 C<null> becomes C<undef>.
17933
17934 =head2 decode_prefix
17935
17936 ($perl_scalar, $characters) = $json->decode_prefix($json_text)
17937
17938 This works like the C<decode> method, but instead of raising an exception
17939 when there is trailing garbage after the first JSON object, it will
17940 silently stop parsing there and return the number of characters consumed
17941 so far.
17942
17943 JSON->new->decode_prefix ("[1] the tail")
17944 => ([], 3)
17945
17946 =head1 INCREMENTAL PARSING
17947
17948 Most of this section are copied and modified from L<JSON::XS/INCREMENTAL PARSING>.
17949
17950 In some cases, there is the need for incremental parsing of JSON texts.
17951 This module does allow you to parse a JSON stream incrementally.
17952 It does so by accumulating text until it has a full JSON object, which
17953 it then can decode. This process is similar to using C<decode_prefix>
17954 to see if a full JSON object is available, but is much more efficient
17955 (and can be implemented with a minimum of method calls).
17956
17957 This module will only attempt to parse the JSON text once it is sure it
17958 has enough text to get a decisive result, using a very simple but
17959 truly incremental parser. This means that it sometimes won't stop as
17960 early as the full parser, for example, it doesn't detect parenthese
17961 mismatches. The only thing it guarantees is that it starts decoding as
17962 soon as a syntactically valid JSON text has been seen. This means you need
17963 to set resource limits (e.g. C<max_size>) to ensure the parser will stop
17964 parsing in the presence if syntax errors.
17965
17966 The following methods implement this incremental parser.
17967
17968 =head2 incr_parse
17969
17970 $json->incr_parse( [$string] ) # void context
17971
17972 $obj_or_undef = $json->incr_parse( [$string] ) # scalar context
17973
17974 @obj_or_empty = $json->incr_parse( [$string] ) # list context
17975
17976 This is the central parsing function. It can both append new text and
17977 extract objects from the stream accumulated so far (both of these
17978 functions are optional).
17979
17980 If C<$string> is given, then this string is appended to the already
17981 existing JSON fragment stored in the C<$json> object.
17982
17983 After that, if the function is called in void context, it will simply
17984 return without doing anything further. This can be used to add more text
17985 in as many chunks as you want.
17986
17987 If the method is called in scalar context, then it will try to extract
17988 exactly I<one> JSON object. If that is successful, it will return this
17989 object, otherwise it will return C<undef>. If there is a parse error,
17990 this method will croak just as C<decode> would do (one can then use
17991 C<incr_skip> to skip the errornous part). This is the most common way of
17992 using the method.
17993
17994 And finally, in list context, it will try to extract as many objects
17995 from the stream as it can find and return them, or the empty list
17996 otherwise. For this to work, there must be no separators between the JSON
17997 objects or arrays, instead they must be concatenated back-to-back. If
17998 an error occurs, an exception will be raised as in the scalar context
17999 case. Note that in this case, any previously-parsed JSON texts will be
18000 lost.
18001
18002 Example: Parse some JSON arrays/objects in a given string and return them.
18003
18004 my @objs = JSON->new->incr_parse ("[5][7][1,2]");
18005
18006 =head2 incr_text
18007
18008 $lvalue_string = $json->incr_text
18009
18010 This method returns the currently stored JSON fragment as an lvalue, that
18011 is, you can manipulate it. This I<only> works when a preceding call to
18012 C<incr_parse> in I<scalar context> successfully returned an object. Under
18013 all other circumstances you must not call this function (I mean it.
18014 although in simple tests it might actually work, it I<will> fail under
18015 real world conditions). As a special exception, you can also call this
18016 method before having parsed anything.
18017
18018 This function is useful in two cases: a) finding the trailing text after a
18019 JSON object or b) parsing multiple JSON objects separated by non-JSON text
18020 (such as commas).
18021
18022 $json->incr_text =~ s/\s*,\s*//;
18023
18024 In Perl 5.005, C<lvalue> attribute is not available.
18025 You must write codes like the below:
18026
18027 $string = $json->incr_text;
18028 $string =~ s/\s*,\s*//;
18029 $json->incr_text( $string );
18030
18031 =head2 incr_skip
18032
18033 $json->incr_skip
18034
18035 This will reset the state of the incremental parser and will remove the
18036 parsed text from the input buffer. This is useful after C<incr_parse>
18037 died, in which case the input buffer and incremental parser state is left
18038 unchanged, to skip the text parsed so far and to reset the parse state.
18039
18040 =head2 incr_reset
18041
18042 $json->incr_reset
18043
18044 This completely resets the incremental parser, that is, after this call,
18045 it will be as if the parser had never parsed anything.
18046
18047 This is useful if you want ot repeatedly parse JSON objects and want to
18048 ignore any trailing data, which means you have to reset the parser after
18049 each successful decode.
18050
18051 See to L<JSON::XS/INCREMENTAL PARSING> for examples.
18052
18053
18054 =head1 JSON::PP OWN METHODS
18055
18056 =head2 allow_singlequote
18057
18058 $json = $json->allow_singlequote([$enable])
18059
18060 If C<$enable> is true (or missing), then C<decode> will accept
18061 JSON strings quoted by single quotations that are invalid JSON
18062 format.
18063
18064 $json->allow_singlequote->decode({"foo":'bar'});
18065 $json->allow_singlequote->decode({'foo':"bar"});
18066 $json->allow_singlequote->decode({'foo':'bar'});
18067
18068 As same as the C<relaxed> option, this option may be used to parse
18069 application-specific files written by humans.
18070
18071
18072 =head2 allow_barekey
18073
18074 $json = $json->allow_barekey([$enable])
18075
18076 If C<$enable> is true (or missing), then C<decode> will accept
18077 bare keys of JSON object that are invalid JSON format.
18078
18079 As same as the C<relaxed> option, this option may be used to parse
18080 application-specific files written by humans.
18081
18082 $json->allow_barekey->decode('{foo:"bar"}');
18083
18084 =head2 allow_bignum
18085
18086 $json = $json->allow_bignum([$enable])
18087
18088 If C<$enable> is true (or missing), then C<decode> will convert
18089 the big integer Perl cannot handle as integer into a L<Math::BigInt>
18090 object and convert a floating number (any) into a L<Math::BigFloat>.
18091
18092 On the contary, C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
18093 objects into JSON numbers with C<allow_blessed> enable.
18094
18095 $json->allow_nonref->allow_blessed->allow_bignum;
18096 $bigfloat = $json->decode('2.000000000000000000000000001');
18097 print $json->encode($bigfloat);
18098 # => 2.000000000000000000000000001
18099
18100 See to L<JSON::XS/MAPPING> aboout the normal conversion of JSON number.
18101
18102 =head2 loose
18103
18104 $json = $json->loose([$enable])
18105
18106 The unescaped [\x00-\x1f\x22\x2f\x5c] strings are invalid in JSON strings
18107 and the module doesn't allow to C<decode> to these (except for \x2f).
18108 If C<$enable> is true (or missing), then C<decode> will accept these
18109 unescaped strings.
18110
18111 $json->loose->decode(qq|["abc
18112 def"]|);
18113
18114 See L<JSON::XS/SSECURITY CONSIDERATIONS>.
18115
18116 =head2 escape_slash
18117
18118 $json = $json->escape_slash([$enable])
18119
18120 According to JSON Grammar, I<slash> (U+002F) is escaped. But default
18121 JSON::PP (as same as JSON::XS) encodes strings without escaping slash.
18122
18123 If C<$enable> is true (or missing), then C<encode> will escape slashes.
18124
18125 =head2 indent_length
18126
18127 $json = $json->indent_length($length)
18128
18129 JSON::XS indent space length is 3 and cannot be changed.
18130 JSON::PP set the indent space length with the given $length.
18131 The default is 3. The acceptable range is 0 to 15.
18132
18133 =head2 sort_by
18134
18135 $json = $json->sort_by($function_name)
18136 $json = $json->sort_by($subroutine_ref)
18137
18138 If $function_name or $subroutine_ref are set, its sort routine are used
18139 in encoding JSON objects.
18140
18141 $js = $pc->sort_by(sub { $JSON::PP::a cmp $JSON::PP::b })->encode($obj);
18142 # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
18143
18144 $js = $pc->sort_by('own_sort')->encode($obj);
18145 # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
18146
18147 sub JSON::PP::own_sort { $JSON::PP::a cmp $JSON::PP::b }
18148
18149 As the sorting routine runs in the JSON::PP scope, the given
18150 subroutine name and the special variables C<$a>, C<$b> will begin
18151 'JSON::PP::'.
18152
18153 If $integer is set, then the effect is same as C<canonical> on.
18154
18155 =head1 INTERNAL
18156
18157 For developers.
18158
18159 =over
18160
18161 =item PP_encode_box
18162
18163 Returns
18164
18165 {
18166 depth => $depth,
18167 indent_count => $indent_count,
18168 }
18169
18170
18171 =item PP_decode_box
18172
18173 Returns
18174
18175 {
18176 text => $text,
18177 at => $at,
18178 ch => $ch,
18179 len => $len,
18180 depth => $depth,
18181 encoding => $encoding,
18182 is_valid_utf8 => $is_valid_utf8,
18183 };
18184
18185 =back
18186
18187 =head1 MAPPING
18188
18189 This section is copied from JSON::XS and modified to C<JSON::PP>.
18190 JSON::XS and JSON::PP mapping mechanisms are almost equivalent.
18191
18192 See to L<JSON::XS/MAPPING>.
18193
18194 =head2 JSON -> PERL
18195
18196 =over 4
18197
18198 =item object
18199
18200 A JSON object becomes a reference to a hash in Perl. No ordering of object
18201 keys is preserved (JSON does not preserver object key ordering itself).
18202
18203 =item array
18204
18205 A JSON array becomes a reference to an array in Perl.
18206
18207 =item string
18208
18209 A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON
18210 are represented by the same codepoints in the Perl string, so no manual
18211 decoding is necessary.
18212
18213 =item number
18214
18215 A JSON number becomes either an integer, numeric (floating point) or
18216 string scalar in perl, depending on its range and any fractional parts. On
18217 the Perl level, there is no difference between those as Perl handles all
18218 the conversion details, but an integer may take slightly less memory and
18219 might represent more values exactly than floating point numbers.
18220
18221 If the number consists of digits only, C<JSON> will try to represent
18222 it as an integer value. If that fails, it will try to represent it as
18223 a numeric (floating point) value if that is possible without loss of
18224 precision. Otherwise it will preserve the number as a string value (in
18225 which case you lose roundtripping ability, as the JSON number will be
18226 re-encoded toa JSON string).
18227
18228 Numbers containing a fractional or exponential part will always be
18229 represented as numeric (floating point) values, possibly at a loss of
18230 precision (in which case you might lose perfect roundtripping ability, but
18231 the JSON number will still be re-encoded as a JSON number).
18232
18233 Note that precision is not accuracy - binary floating point values cannot
18234 represent most decimal fractions exactly, and when converting from and to
18235 floating point, C<JSON> only guarantees precision up to but not including
18236 the leats significant bit.
18237
18238 When C<allow_bignum> is enable, the big integers
18239 and the numeric can be optionally converted into L<Math::BigInt> and
18240 L<Math::BigFloat> objects.
18241
18242 =item true, false
18243
18244 These JSON atoms become C<JSON::PP::true> and C<JSON::PP::false>,
18245 respectively. They are overloaded to act almost exactly like the numbers
18246 C<1> and C<0>. You can check wether a scalar is a JSON boolean by using
18247 the C<JSON::is_bool> function.
18248
18249 print JSON::PP::true . "\n";
18250 => true
18251 print JSON::PP::true + 1;
18252 => 1
18253
18254 ok(JSON::true eq '1');
18255 ok(JSON::true == 1);
18256
18257 C<JSON> will install these missing overloading features to the backend modules.
18258
18259
18260 =item null
18261
18262 A JSON null atom becomes C<undef> in Perl.
18263
18264 C<JSON::PP::null> returns C<unddef>.
18265
18266 =back
18267
18268
18269 =head2 PERL -> JSON
18270
18271 The mapping from Perl to JSON is slightly more difficult, as Perl is a
18272 truly typeless language, so we can only guess which JSON type is meant by
18273 a Perl value.
18274
18275 =over 4
18276
18277 =item hash references
18278
18279 Perl hash references become JSON objects. As there is no inherent ordering
18280 in hash keys (or JSON objects), they will usually be encoded in a
18281 pseudo-random order that can change between runs of the same program but
18282 stays generally the same within a single run of a program. C<JSON>
18283 optionally sort the hash keys (determined by the I<canonical> flag), so
18284 the same datastructure will serialise to the same JSON text (given same
18285 settings and version of JSON::XS), but this incurs a runtime overhead
18286 and is only rarely useful, e.g. when you want to compare some JSON text
18287 against another for equality.
18288
18289
18290 =item array references
18291
18292 Perl array references become JSON arrays.
18293
18294 =item other references
18295
18296 Other unblessed references are generally not allowed and will cause an
18297 exception to be thrown, except for references to the integers C<0> and
18298 C<1>, which get turned into C<false> and C<true> atoms in JSON. You can
18299 also use C<JSON::false> and C<JSON::true> to improve readability.
18300
18301 to_json [\0,JSON::PP::true] # yields [false,true]
18302
18303 =item JSON::PP::true, JSON::PP::false, JSON::PP::null
18304
18305 These special values become JSON true and JSON false values,
18306 respectively. You can also use C<\1> and C<\0> directly if you want.
18307
18308 JSON::PP::null returns C<undef>.
18309
18310 =item blessed objects
18311
18312 Blessed objects are not directly representable in JSON. See the
18313 C<allow_blessed> and C<convert_blessed> methods on various options on
18314 how to deal with this: basically, you can choose between throwing an
18315 exception, encoding the reference as if it weren't blessed, or provide
18316 your own serialiser method.
18317
18318 See to L<convert_blessed>.
18319
18320 =item simple scalars
18321
18322 Simple Perl scalars (any scalar that is not a reference) are the most
18323 difficult objects to encode: JSON::XS and JSON::PP will encode undefined scalars as
18324 JSON C<null> values, scalars that have last been used in a string context
18325 before encoding as JSON strings, and anything else as number value:
18326
18327 # dump as number
18328 encode_json [2] # yields [2]
18329 encode_json [-3.0e17] # yields [-3e+17]
18330 my $value = 5; encode_json [$value] # yields [5]
18331
18332 # used as string, so dump as string
18333 print $value;
18334 encode_json [$value] # yields ["5"]
18335
18336 # undef becomes null
18337 encode_json [undef] # yields [null]
18338
18339 You can force the type to be a string by stringifying it:
18340
18341 my $x = 3.1; # some variable containing a number
18342 "$x"; # stringified
18343 $x .= ""; # another, more awkward way to stringify
18344 print $x; # perl does it for you, too, quite often
18345
18346 You can force the type to be a number by numifying it:
18347
18348 my $x = "3"; # some variable containing a string
18349 $x += 0; # numify it, ensuring it will be dumped as a number
18350 $x *= 1; # same thing, the choise is yours.
18351
18352 You can not currently force the type in other, less obscure, ways.
18353
18354 Note that numerical precision has the same meaning as under Perl (so
18355 binary to decimal conversion follows the same rules as in Perl, which
18356 can differ to other languages). Also, your perl interpreter might expose
18357 extensions to the floating point numbers of your platform, such as
18358 infinities or NaN's - these cannot be represented in JSON, and it is an
18359 error to pass those in.
18360
18361 =item Big Number
18362
18363 When C<allow_bignum> is enable,
18364 C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
18365 objects into JSON numbers.
18366
18367
18368 =back
18369
18370 =head1 UNICODE HANDLING ON PERLS
18371
18372 If you do not know about Unicode on Perl well,
18373 please check L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>.
18374
18375 =head2 Perl 5.8 and later
18376
18377 Perl can handle Unicode and the JSON::PP de/encode methods also work properly.
18378
18379 $json->allow_nonref->encode(chr hex 3042);
18380 $json->allow_nonref->encode(chr hex 12345);
18381
18382 Reuturns C<"\u3042"> and C<"\ud808\udf45"> respectively.
18383
18384 $json->allow_nonref->decode('"\u3042"');
18385 $json->allow_nonref->decode('"\ud808\udf45"');
18386
18387 Returns UTF-8 encoded strings with UTF8 flag, regarded as C<U+3042> and C<U+12345>.
18388
18389 Note that the versions from Perl 5.8.0 to 5.8.2, Perl built-in C<join> was broken,
18390 so JSON::PP wraps the C<join> with a subroutine. Thus JSON::PP works slow in the versions.
18391
18392
18393 =head2 Perl 5.6
18394
18395 Perl can handle Unicode and the JSON::PP de/encode methods also work.
18396
18397 =head2 Perl 5.005
18398
18399 Perl 5.005 is a byte sementics world -- all strings are sequences of bytes.
18400 That means the unicode handling is not available.
18401
18402 In encoding,
18403
18404 $json->allow_nonref->encode(chr hex 3042); # hex 3042 is 12354.
18405 $json->allow_nonref->encode(chr hex 12345); # hex 12345 is 74565.
18406
18407 Returns C<B> and C<E>, as C<chr> takes a value more than 255, it treats
18408 as C<$value % 256>, so the above codes are equivalent to :
18409
18410 $json->allow_nonref->encode(chr 66);
18411 $json->allow_nonref->encode(chr 69);
18412
18413 In decoding,
18414
18415 $json->decode('"\u00e3\u0081\u0082"');
18416
18417 The returned is a byte sequence C<0xE3 0x81 0x82> for UTF-8 encoded
18418 japanese character (C<HIRAGANA LETTER A>).
18419 And if it is represented in Unicode code point, C<U+3042>.
18420
18421 Next,
18422
18423 $json->decode('"\u3042"');
18424
18425 We ordinary expect the returned value is a Unicode character C<U+3042>.
18426 But here is 5.005 world. This is C<0xE3 0x81 0x82>.
18427
18428 $json->decode('"\ud808\udf45"');
18429
18430 This is not a character C<U+12345> but bytes - C<0xf0 0x92 0x8d 0x85>.
18431
18432
18433 =head1 TODO
18434
18435 =over
18436
18437 =item speed
18438
18439 =item memory saving
18440
18441 =back
18442
18443
18444 =head1 SEE ALSO
18445
18446 Most of the document are copied and modified from JSON::XS doc.
18447
18448 L<JSON::XS>
18449
18450 RFC4627 (L<http://www.ietf.org/rfc/rfc4627.txt>)
18451
18452 =head1 AUTHOR
18453
18454 Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt>
18455
18456
18457 =head1 COPYRIGHT AND LICENSE
18458
18459 Copyright 2007-2014 by Makamaka Hannyaharamitu
18460
18461 This library is free software; you can redistribute it and/or modify
18462 it under the same terms as Perl itself.
18463
18464 =cut
18465 JSON_PP
18466  
18467 $fatpacked{"JSON/PP/Boolean.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'JSON_PP_BOOLEAN';
18468 =head1 NAME
18469
18470 JSON::PP::Boolean - dummy module providing JSON::PP::Boolean
18471
18472 =head1 SYNOPSIS
18473
18474 # do not "use" yourself
18475
18476 =head1 DESCRIPTION
18477
18478 This module exists only to provide overload resolution for Storable and similar modules. See
18479 L<JSON::PP> for more info about this class.
18480
18481 =cut
18482
18483 use JSON::PP ();
18484 use strict;
18485
18486 1;
18487
18488 =head1 AUTHOR
18489
18490 This idea is from L<JSON::XS::Boolean> written by Marc Lehmann <schmorp[at]schmorp.de>
18491
18492 =cut
18493
18494 JSON_PP_BOOLEAN
18495  
18496 $fatpacked{"Module/CPANfile.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'MODULE_CPANFILE';
18497 package Module::CPANfile;
18498 use strict;
18499 use warnings;
18500 use Cwd;
18501 use Carp ();
18502 use Module::CPANfile::Environment;
18503 use Module::CPANfile::Requirement;
18504
18505 our $VERSION = '1.1000';
18506
18507 sub new {
18508 my($class, $file) = @_;
18509 bless {}, $class;
18510 }
18511
18512 sub load {
18513 my($proto, $file) = @_;
18514
18515 my $self = ref $proto ? $proto : $proto->new;
18516 $self->parse($file || Cwd::abs_path('cpanfile'));
18517 $self;
18518 }
18519
18520 sub save {
18521 my($self, $path) = @_;
18522
18523 open my $out, ">", $path or die "$path: $!";
18524 print {$out} $self->to_string;
18525 }
18526
18527 sub parse {
18528 my($self, $file) = @_;
18529
18530 my $code = do {
18531 open my $fh, "<", $file or die "$file: $!";
18532 join '', <$fh>;
18533 };
18534
18535 my $env = Module::CPANfile::Environment->new($file);
18536 $env->parse($code) or die $@;
18537
18538 $self->{_mirrors} = $env->mirrors;
18539 $self->{_prereqs} = $env->prereqs;
18540 }
18541
18542 sub from_prereqs {
18543 my($proto, $prereqs) = @_;
18544
18545 my $self = $proto->new;
18546 $self->{_prereqs} = Module::CPANfile::Prereqs->from_cpan_meta($prereqs);
18547
18548 $self;
18549 }
18550
18551 sub mirrors {
18552 my $self = shift;
18553 $self->{_mirrors} || [];
18554 }
18555
18556 sub features {
18557 my $self = shift;
18558 map $self->feature($_), $self->{_prereqs}->identifiers;
18559 }
18560
18561 sub feature {
18562 my($self, $identifier) = @_;
18563 $self->{_prereqs}->feature($identifier);
18564 }
18565
18566 sub prereq { shift->prereqs }
18567
18568 sub prereqs {
18569 my $self = shift;
18570 $self->{_prereqs}->as_cpan_meta;
18571 }
18572
18573 sub merged_requirements {
18574 my $self = shift;
18575 $self->{_prereqs}->merged_requirements;
18576 }
18577
18578 sub effective_prereqs {
18579 my($self, $features) = @_;
18580 $self->prereqs_with(@{$features || []});
18581 }
18582
18583 sub prereqs_with {
18584 my($self, @feature_identifiers) = @_;
18585
18586 my $prereqs = $self->prereqs;
18587 my @others = map { $self->feature($_)->prereqs } @feature_identifiers;
18588
18589 $prereqs->with_merged_prereqs(\@others);
18590 }
18591
18592 sub prereq_specs {
18593 my $self = shift;
18594 $self->prereqs->as_string_hash;
18595 }
18596
18597 sub prereq_for_module {
18598 my($self, $module) = @_;
18599 $self->{_prereqs}->find($module);
18600 }
18601
18602 sub options_for_module {
18603 my($self, $module) = @_;
18604 my $prereq = $self->prereq_for_module($module) or return;
18605 $prereq->requirement->options;
18606 }
18607
18608 sub merge_meta {
18609 my($self, $file, $version) = @_;
18610
18611 require CPAN::Meta;
18612
18613 $version ||= $file =~ /\.yml$/ ? '1.4' : '2';
18614
18615 my $prereq = $self->prereqs;
18616
18617 my $meta = CPAN::Meta->load_file($file);
18618 my $prereqs_hash = $prereq->with_merged_prereqs($meta->effective_prereqs)->as_string_hash;
18619 my $struct = { %{$meta->as_struct}, prereqs => $prereqs_hash };
18620
18621 CPAN::Meta->new($struct)->save($file, { version => $version });
18622 }
18623
18624 sub _dump {
18625 my $str = shift;
18626 require Data::Dumper;
18627 chomp(my $value = Data::Dumper->new([$str])->Terse(1)->Dump);
18628 $value;
18629 }
18630
18631 sub to_string {
18632 my($self, $include_empty) = @_;
18633
18634 my $mirrors = $self->mirrors;
18635 my $prereqs = $self->prereq_specs;
18636
18637 my $code = '';
18638 $code .= $self->_dump_mirrors($mirrors);
18639 $code .= $self->_dump_prereqs($prereqs, $include_empty);
18640
18641 for my $feature ($self->features) {
18642 $code .= sprintf "feature %s, %s => sub {\n", _dump($feature->{identifier}), _dump($feature->{description});
18643 $code .= $self->_dump_prereqs($feature->{spec}, $include_empty, 4);
18644 $code .= "}\n\n";
18645 }
18646
18647 $code =~ s/\n+$/\n/s;
18648 $code;
18649 }
18650
18651 sub _dump_mirrors {
18652 my($self, $mirrors) = @_;
18653
18654 my $code = "";
18655
18656 for my $url (@$mirrors) {
18657 $code .= "mirror '$url';\n";
18658 }
18659
18660 $code =~ s/\n+$/\n/s;
18661 $code;
18662 }
18663
18664 sub _dump_prereqs {
18665 my($self, $prereqs, $include_empty, $base_indent) = @_;
18666
18667 my $code = '';
18668 for my $phase (qw(runtime configure build test develop)) {
18669 my $indent = $phase eq 'runtime' ? '' : ' ';
18670 $indent = (' ' x ($base_indent || 0)) . $indent;
18671
18672 my($phase_code, $requirements);
18673 $phase_code .= "on $phase => sub {\n" unless $phase eq 'runtime';
18674
18675 for my $type (qw(requires recommends suggests conflicts)) {
18676 for my $mod (sort keys %{$prereqs->{$phase}{$type}}) {
18677 my $ver = $prereqs->{$phase}{$type}{$mod};
18678 $phase_code .= $ver eq '0'
18679 ? "${indent}$type '$mod';\n"
18680 : "${indent}$type '$mod', '$ver';\n";
18681 $requirements++;
18682 }
18683 }
18684
18685 $phase_code .= "\n" unless $requirements;
18686 $phase_code .= "};\n" unless $phase eq 'runtime';
18687
18688 $code .= $phase_code . "\n" if $requirements or $include_empty;
18689 }
18690
18691 $code =~ s/\n+$/\n/s;
18692 $code;
18693 }
18694
18695 1;
18696
18697 __END__
18698
18699 =head1 NAME
18700
18701 Module::CPANfile - Parse cpanfile
18702
18703 =head1 SYNOPSIS
18704
18705 use Module::CPANfile;
18706
18707 my $file = Module::CPANfile->load("cpanfile");
18708 my $prereqs = $file->prereqs; # CPAN::Meta::Prereqs object
18709
18710 my @features = $file->features; # CPAN::Meta::Feature objects
18711 my $merged_prereqs = $file->prereqs_with(@identifiers); # CPAN::Meta::Prereqs
18712
18713 $file->merge_meta('MYMETA.json');
18714
18715 =head1 DESCRIPTION
18716
18717 Module::CPANfile is a tool to handle L<cpanfile> format to load application
18718 specific dependencies, not just for CPAN distributions.
18719
18720 =head1 METHODS
18721
18722 =over 4
18723
18724 =item load
18725
18726 $file = Module::CPANfile->load;
18727 $file = Module::CPANfile->load('cpanfile');
18728
18729 Load and parse a cpanfile. By default it tries to load C<cpanfile> in
18730 the current directory, unless you pass the path to its argument.
18731
18732 =item from_prereqs
18733
18734 $file = Module::CPANfile->from_prereqs({
18735 runtime => { requires => { DBI => '1.000' } },
18736 });
18737
18738 Creates a new Module::CPANfile object from prereqs hash you can get
18739 via L<CPAN::Meta>'s C<prereqs>, or L<CPAN::Meta::Prereqs>'
18740 C<as_string_hash>.
18741
18742 # read MYMETA, then feed the prereqs to create Module::CPANfile
18743 my $meta = CPAN::Meta->load_file('MYMETA.json');
18744 my $file = Module::CPANfile->from_prereqs($meta->prereqs);
18745
18746 # load cpanfile, then recreate it with round-trip
18747 my $file = Module::CPANfile->load('cpanfile');
18748 $file = Module::CPANfile->from_prereqs($file->prereq_specs);
18749 # or $file->prereqs->as_string_hash
18750
18751 =item prereqs
18752
18753 Returns L<CPAN::Meta::Prereqs> object out of the parsed cpanfile.
18754
18755 =item prereq_specs
18756
18757 Returns a hash reference that should be passed to C<< CPAN::Meta::Prereqs->new >>.
18758
18759 =item features
18760
18761 Returns a list of features available in the cpanfile as L<CPAN::Meta::Feature>.
18762
18763 =item prereqs_with(@identifiers), effective_prereqs(\@identifiers)
18764
18765 Returns L<CPAN::Meta::Prereqs> object, with merged prereqs for
18766 features identified with the C<@identifiers>.
18767
18768 =item to_string($include_empty)
18769
18770 $file->to_string;
18771 $file->to_string(1);
18772
18773 Returns a canonical string (code) representation for cpanfile. Useful
18774 if you want to convert L<CPAN::Meta::Prereqs> to a new cpanfile.
18775
18776 # read MYMETA's prereqs and print cpanfile representation of it
18777 my $meta = CPAN::Meta->load_file('MYMETA.json');
18778 my $file = Module::CPANfile->from_prereqs($meta->prereqs);
18779 print $file->to_string;
18780
18781 By default, it omits the phase where there're no modules
18782 registered. If you pass the argument of a true value, it will print
18783 them as well.
18784
18785 =item save
18786
18787 $file->save('cpanfile');
18788
18789 Saves the currently loaded prereqs as a new C<cpanfile> by calling
18790 C<to_string>. Beware B<this method will overwrite the existing
18791 cpanfile without any warning or backup>. Taking a backup or giving
18792 warnings to users is a caller's responsibility.
18793
18794 # Read MYMETA.json and creates a new cpanfile
18795 my $meta = CPAN::Meta->load_file('MYMETA.json');
18796 my $file = Module::CPANfile->from_prereqs($meta->prereqs);
18797 $file->save('cpanfile');
18798
18799 =item merge_meta
18800
18801 $file->merge_meta('META.yml');
18802 $file->merge_meta('MYMETA.json', '2.0');
18803
18804 Merge the effective prereqs with Meta specification loaded from the
18805 given META file, using CPAN::Meta. You can specify the META spec
18806 version in the second argument, which defaults to 1.4 in case the
18807 given file is YAML, and 2 if it is JSON.
18808
18809 =back
18810
18811 =head1 AUTHOR
18812
18813 Tatsuhiko Miyagawa
18814
18815 =head1 SEE ALSO
18816
18817 L<cpanfile>, L<CPAN::Meta>, L<CPAN::Meta::Spec>
18818
18819 =cut
18820 MODULE_CPANFILE
18821  
18822 $fatpacked{"Module/CPANfile/Environment.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'MODULE_CPANFILE_ENVIRONMENT';
18823 package Module::CPANfile::Environment;
18824 use strict;
18825 use warnings;
18826 use Module::CPANfile::Prereqs;
18827 use Carp ();
18828
18829 my @bindings = qw(
18830 on requires recommends suggests conflicts
18831 feature
18832 osname
18833 mirror
18834 configure_requires build_requires test_requires author_requires
18835 );
18836
18837 my $file_id = 1;
18838
18839 sub new {
18840 my($class, $file) = @_;
18841 bless {
18842 file => $file,
18843 phase => 'runtime', # default phase
18844 feature => undef,
18845 features => {},
18846 prereqs => Module::CPANfile::Prereqs->new,
18847 mirrors => [],
18848 }, $class;
18849 }
18850
18851 sub bind {
18852 my $self = shift;
18853 my $pkg = caller;
18854
18855 for my $binding (@bindings) {
18856 no strict 'refs';
18857 *{"$pkg\::$binding"} = sub { $self->$binding(@_) };
18858 }
18859 }
18860
18861 sub parse {
18862 my($self, $code) = @_;
18863
18864 my $err;
18865 {
18866 local $@;
18867 $file_id++;
18868 $self->_evaluate(<<EVAL);
18869 package Module::CPANfile::Sandbox$file_id;
18870 no warnings;
18871 BEGIN { \$_environment->bind }
18872
18873 # line 1 "$self->{file}"
18874 $code;
18875 EVAL
18876 $err = $@;
18877 }
18878
18879 if ($err) { die "Parsing $self->{file} failed: $err" };
18880
18881 return 1;
18882 }
18883
18884 sub _evaluate {
18885 my $_environment = $_[0];
18886 eval $_[1];
18887 }
18888
18889 sub prereqs { $_[0]->{prereqs} }
18890
18891 sub mirrors { $_[0]->{mirrors} }
18892
18893 # DSL goes from here
18894
18895 sub on {
18896 my($self, $phase, $code) = @_;
18897 local $self->{phase} = $phase;
18898 $code->();
18899 }
18900
18901 sub feature {
18902 my($self, $identifier, $description, $code) = @_;
18903
18904 # shortcut: feature identifier => sub { ... }
18905 if (@_ == 3 && ref($description) eq 'CODE') {
18906 $code = $description;
18907 $description = $identifier;
18908 }
18909
18910 unless (ref $description eq '' && ref $code eq 'CODE') {
18911 Carp::croak("Usage: feature 'identifier', 'Description' => sub { ... }");
18912 }
18913
18914 local $self->{feature} = $identifier;
18915 $self->prereqs->add_feature($identifier, $description);
18916
18917 $code->();
18918 }
18919
18920 sub osname { die "TODO" }
18921
18922 sub mirror {
18923 my($self, $url) = @_;
18924 push @{$self->{mirrors}}, $url;
18925 }
18926
18927 sub requirement_for {
18928 my($self, $module, @args) = @_;
18929
18930 my $requirement = 0;
18931 $requirement = shift @args if @args % 2;
18932
18933 return Module::CPANfile::Requirement->new(
18934 name => $module,
18935 version => $requirement,
18936 @args,
18937 );
18938 }
18939
18940 sub requires {
18941 my $self = shift;
18942 $self->add_prereq(requires => @_);
18943 }
18944
18945 sub recommends {
18946 my $self = shift;
18947 $self->add_prereq(recommends => @_);
18948 }
18949
18950 sub suggests {
18951 my $self = shift;
18952 $self->add_prereq(suggests => @_);
18953 }
18954
18955 sub conflicts {
18956 my $self = shift;
18957 $self->add_prereq(conflicts => @_);
18958 }
18959
18960 sub add_prereq {
18961 my($self, $type, $module, @args) = @_;
18962
18963 $self->prereqs->add_prereq(
18964 feature => $self->{feature},
18965 phase => $self->{phase},
18966 type => $type,
18967 module => $module,
18968 requirement => $self->requirement_for($module, @args),
18969 );
18970 }
18971
18972 # Module::Install compatible shortcuts
18973
18974 sub configure_requires {
18975 my($self, @args) = @_;
18976 $self->on(configure => sub { $self->requires(@args) });
18977 }
18978
18979 sub build_requires {
18980 my($self, @args) = @_;
18981 $self->on(build => sub { $self->requires(@args) });
18982 }
18983
18984 sub test_requires {
18985 my($self, @args) = @_;
18986 $self->on(test => sub { $self->requires(@args) });
18987 }
18988
18989 sub author_requires {
18990 my($self, @args) = @_;
18991 $self->on(develop => sub { $self->requires(@args) });
18992 }
18993
18994 1;
18995
18996 MODULE_CPANFILE_ENVIRONMENT
18997  
18998 $fatpacked{"Module/CPANfile/Prereq.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'MODULE_CPANFILE_PREREQ';
18999 package Module::CPANfile::Prereq;
19000 use strict;
19001
19002 sub new {
19003 my($class, %options) = @_;
19004 bless \%options, $class;
19005 }
19006
19007 sub feature { $_[0]->{feature} }
19008 sub phase { $_[0]->{phase} }
19009 sub type { $_[0]->{type} }
19010 sub module { $_[0]->{module} }
19011 sub requirement { $_[0]->{requirement} }
19012
19013 sub match_feature {
19014 my($self, $identifier) = @_;
19015 no warnings 'uninitialized';
19016 $self->feature eq $identifier;
19017 }
19018
19019 1;
19020 MODULE_CPANFILE_PREREQ
19021  
19022 $fatpacked{"Module/CPANfile/Prereqs.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'MODULE_CPANFILE_PREREQS';
19023 package Module::CPANfile::Prereqs;
19024 use strict;
19025 use Carp ();
19026 use CPAN::Meta::Feature;
19027 use Module::CPANfile::Prereq;
19028
19029 sub from_cpan_meta {
19030 my($class, $prereqs) = @_;
19031
19032 my $self = $class->new;
19033
19034 for my $phase (keys %$prereqs) {
19035 for my $type (keys %{ $prereqs->{$phase} }) {
19036 while (my($module, $requirement) = each %{ $prereqs->{$phase}{$type} }) {
19037 $self->add_prereq(
19038 phase => $phase,
19039 type => $type,
19040 module => $module,
19041 requirement => Module::CPANfile::Requirement->new(name => $module, version => $requirement),
19042 );
19043 }
19044 }
19045 }
19046
19047 $self;
19048 }
19049
19050 sub new {
19051 my $class = shift;
19052 bless {
19053 prereqs => [],
19054 features => {},
19055 }, $class;
19056 }
19057
19058 sub add_feature {
19059 my($self, $identifier, $description) = @_;
19060 $self->{features}{$identifier} = { description => $description };
19061 }
19062
19063 sub add_prereq {
19064 my($self, %args) = @_;
19065 $self->add( Module::CPANfile::Prereq->new(%args) );
19066 }
19067
19068 sub add {
19069 my($self, $prereq) = @_;
19070 push @{$self->{prereqs}}, $prereq;
19071 }
19072
19073 sub as_cpan_meta {
19074 my $self = shift;
19075 $self->{cpanmeta} ||= $self->build_cpan_meta;
19076 }
19077
19078 sub build_cpan_meta {
19079 my($self, $identifier) = @_;
19080
19081 my $prereq_spec = {};
19082 $self->prereq_each($identifier, sub {
19083 my $prereq = shift;
19084 $prereq_spec->{$prereq->phase}{$prereq->type}{$prereq->module} = $prereq->requirement->version;
19085 });
19086
19087 CPAN::Meta::Prereqs->new($prereq_spec);
19088 }
19089
19090 sub prereq_each {
19091 my($self, $identifier, $code) = @_;
19092
19093 for my $prereq (@{$self->{prereqs}}) {
19094 next unless $prereq->match_feature($identifier);
19095 $code->($prereq);
19096 }
19097 }
19098
19099 sub merged_requirements {
19100 my $self = shift;
19101
19102 my $reqs = CPAN::Meta::Requirements->new;
19103 for my $prereq (@{$self->{prereqs}}) {
19104 $reqs->add_string_requirement($prereq->module, $prereq->requirement->version);
19105 }
19106
19107 $reqs;
19108 }
19109
19110 sub find {
19111 my($self, $module) = @_;
19112
19113 for my $prereq (@{$self->{prereqs}}) {
19114 return $prereq if $prereq->module eq $module;
19115 }
19116
19117 return;
19118 }
19119
19120 sub identifiers {
19121 my $self = shift;
19122 keys %{$self->{features}};
19123 }
19124
19125 sub feature {
19126 my($self, $identifier) = @_;
19127
19128 my $data = $self->{features}{$identifier}
19129 or Carp::croak("Unknown feature '$identifier'");
19130
19131 my $prereqs = $self->build_cpan_meta($identifier);
19132
19133 CPAN::Meta::Feature->new($identifier, {
19134 description => $data->{description},
19135 prereqs => $prereqs->as_string_hash,
19136 });
19137 }
19138
19139 1;
19140 MODULE_CPANFILE_PREREQS
19141  
19142 $fatpacked{"Module/CPANfile/Requirement.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'MODULE_CPANFILE_REQUIREMENT';
19143 package Module::CPANfile::Requirement;
19144 use strict;
19145
19146 sub new {
19147 my ($class, %args) = @_;
19148
19149 $args{version} ||= 0;
19150
19151 bless +{
19152 name => delete $args{name},
19153 version => delete $args{version},
19154 options => \%args,
19155 }, $class;
19156 }
19157
19158 sub name { $_[0]->{name} }
19159 sub version { $_[0]->{version} }
19160
19161 sub options { $_[0]->{options} }
19162
19163 sub has_options {
19164 keys %{$_[0]->{options}} > 0;
19165 }
19166
19167 1;
19168 MODULE_CPANFILE_REQUIREMENT
19169  
19170 $fatpacked{"Module/Metadata.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'MODULE_METADATA';
19171 # -*- mode: cperl; tab-width: 8; indent-tabs-mode: nil; basic-offset: 2 -*-
19172 # vim:ts=8:sw=2:et:sta:sts=2:tw=78
19173 package Module::Metadata; # git description: v1.000037-8-g92dec6c
19174 # ABSTRACT: Gather package and POD information from perl module files
19175
19176 # Adapted from Perl-licensed code originally distributed with
19177 # Module-Build by Ken Williams
19178
19179 # This module provides routines to gather information about
19180 # perl modules (assuming this may be expanded in the distant
19181 # parrot future to look at other types of modules).
19182
19183 sub __clean_eval { eval $_[0] }
19184 use strict;
19185 use warnings;
19186
19187 our $VERSION = '1.000038';
19188
19189 use Carp qw/croak/;
19190 use File::Spec;
19191 BEGIN {
19192 # Try really hard to not depend ony any DynaLoaded module, such as IO::File or Fcntl
19193 eval {
19194 require Fcntl; Fcntl->import('SEEK_SET'); 1;
19195 } or *SEEK_SET = sub { 0 }
19196 }
19197 use version 0.87;
19198 BEGIN {
19199 if ($INC{'Log/Contextual.pm'}) {
19200 require "Log/Contextual/WarnLogger.pm"; # Hide from AutoPrereqs
19201 Log::Contextual->import('log_info',
19202 '-default_logger' => Log::Contextual::WarnLogger->new({ env_prefix => 'MODULE_METADATA', }),
19203 );
19204 }
19205 else {
19206 *log_info = sub (&) { warn $_[0]->() };
19207 }
19208 }
19209 use File::Find qw(find);
19210
19211 my $V_NUM_REGEXP = qr{v?[0-9._]+}; # crudely, a v-string or decimal
19212
19213 my $PKG_FIRST_WORD_REGEXP = qr{ # the FIRST word in a package name
19214 [a-zA-Z_] # the first word CANNOT start with a digit
19215 (?:
19216 [\w']? # can contain letters, digits, _, or ticks
19217 \w # But, NO multi-ticks or trailing ticks
19218 )*
19219 }x;
19220
19221 my $PKG_ADDL_WORD_REGEXP = qr{ # the 2nd+ word in a package name
19222 \w # the 2nd+ word CAN start with digits
19223 (?:
19224 [\w']? # and can contain letters or ticks
19225 \w # But, NO multi-ticks or trailing ticks
19226 )*
19227 }x;
19228
19229 my $PKG_NAME_REGEXP = qr{ # match a package name
19230 (?: :: )? # a pkg name can start with arisdottle
19231 $PKG_FIRST_WORD_REGEXP # a package word
19232 (?:
19233 (?: :: )+ ### arisdottle (allow one or many times)
19234 $PKG_ADDL_WORD_REGEXP ### a package word
19235 )* # ^ zero, one or many times
19236 (?:
19237 :: # allow trailing arisdottle
19238 )?
19239 }x;
19240
19241 my $PKG_REGEXP = qr{ # match a package declaration
19242 ^[\s\{;]* # intro chars on a line
19243 package # the word 'package'
19244 \s+ # whitespace
19245 ($PKG_NAME_REGEXP) # a package name
19246 \s* # optional whitespace
19247 ($V_NUM_REGEXP)? # optional version number
19248 \s* # optional whitespace
19249 [;\{] # semicolon line terminator or block start (since 5.16)
19250 }x;
19251
19252 my $CLASS_REGEXP = qr{ # match a class declaration (core since 5.38)
19253 ^[\s\{;]* # intro chars on a line
19254 class # the word 'class'
19255 \s+ # whitespace
19256 ($PKG_NAME_REGEXP) # a package name
19257 \s* # optional whitespace
19258 ($V_NUM_REGEXP)? # optional version number
19259 \s* # optional whitespace
19260 [;\{] # semicolon line terminator or block start
19261 }x;
19262
19263 my $VARNAME_REGEXP = qr{ # match fully-qualified VERSION name
19264 ([\$*]) # sigil - $ or *
19265 (
19266 ( # optional leading package name
19267 (?:::|\')? # possibly starting like just :: (a la $::VERSION)
19268 (?:\w+(?:::|\'))* # Foo::Bar:: ...
19269 )?
19270 VERSION
19271 )\b
19272 }x;
19273
19274 my $VERS_REGEXP = qr{ # match a VERSION definition
19275 (?:
19276 \(\s*$VARNAME_REGEXP\s*\) # with parens
19277 |
19278 $VARNAME_REGEXP # without parens
19279 )
19280 \s*
19281 =[^=~>] # = but not ==, nor =~, nor =>
19282 }x;
19283
19284 sub new_from_file {
19285 my $class = shift;
19286 my $filename = File::Spec->rel2abs( shift );
19287
19288 return undef unless defined( $filename ) && -f $filename;
19289 return $class->_init(undef, $filename, @_);
19290 }
19291
19292 sub new_from_handle {
19293 my $class = shift;
19294 my $handle = shift;
19295 my $filename = shift;
19296 return undef unless defined($handle) && defined($filename);
19297 $filename = File::Spec->rel2abs( $filename );
19298
19299 return $class->_init(undef, $filename, @_, handle => $handle);
19300
19301 }
19302
19303
19304 sub new_from_module {
19305 my $class = shift;
19306 my $module = shift;
19307 my %props = @_;
19308
19309 $props{inc} ||= \@INC;
19310 my $filename = $class->find_module_by_name( $module, $props{inc} );
19311 return undef unless defined( $filename ) && -f $filename;
19312 return $class->_init($module, $filename, %props);
19313 }
19314
19315 {
19316
19317 my $compare_versions = sub {
19318 my ($v1, $op, $v2) = @_;
19319 $v1 = version->new($v1)
19320 unless UNIVERSAL::isa($v1,'version');
19321
19322 my $eval_str = "\$v1 $op \$v2";
19323 my $result = eval $eval_str;
19324 log_info { "error comparing versions: '$eval_str' $@" } if $@;
19325
19326 return $result;
19327 };
19328
19329 my $normalize_version = sub {
19330 my ($version) = @_;
19331 if ( $version =~ /[=<>!,]/ ) { # logic, not just version
19332 # take as is without modification
19333 }
19334 elsif ( ref $version eq 'version' ) { # version objects
19335 $version = $version->is_qv ? $version->normal : $version->stringify;
19336 }
19337 elsif ( $version =~ /^[^v][^.]*\.[^.]+\./ ) { # no leading v, multiple dots
19338 # normalize string tuples without "v": "1.2.3" -> "v1.2.3"
19339 $version = "v$version";
19340 }
19341 else {
19342 # leave alone
19343 }
19344 return $version;
19345 };
19346
19347 # separate out some of the conflict resolution logic
19348
19349 my $resolve_module_versions = sub {
19350 my $packages = shift;
19351
19352 my( $file, $version );
19353 my $err = '';
19354 foreach my $p ( @$packages ) {
19355 if ( defined( $p->{version} ) ) {
19356 if ( defined( $version ) ) {
19357 if ( $compare_versions->( $version, '!=', $p->{version} ) ) {
19358 $err .= " $p->{file} ($p->{version})\n";
19359 }
19360 else {
19361 # same version declared multiple times, ignore
19362 }
19363 }
19364 else {
19365 $file = $p->{file};
19366 $version = $p->{version};
19367 }
19368 }
19369 $file ||= $p->{file} if defined( $p->{file} );
19370 }
19371
19372 if ( $err ) {
19373 $err = " $file ($version)\n" . $err;
19374 }
19375
19376 my %result = (
19377 file => $file,
19378 version => $version,
19379 err => $err
19380 );
19381
19382 return \%result;
19383 };
19384
19385 sub provides {
19386 my $class = shift;
19387
19388 croak "provides() requires key/value pairs \n" if @_ % 2;
19389 my %args = @_;
19390
19391 croak "provides() takes only one of 'dir' or 'files'\n"
19392 if $args{dir} && $args{files};
19393
19394 croak "provides() requires a 'version' argument"
19395 unless defined $args{version};
19396
19397 croak "provides() does not support version '$args{version}' metadata"
19398 unless grep $args{version} eq $_, qw/1.4 2/;
19399
19400 $args{prefix} = 'lib' unless defined $args{prefix};
19401
19402 my $p;
19403 if ( $args{dir} ) {
19404 $p = $class->package_versions_from_directory($args{dir});
19405 }
19406 else {
19407 croak "provides() requires 'files' to be an array reference\n"
19408 unless ref $args{files} eq 'ARRAY';
19409 $p = $class->package_versions_from_directory($args{files});
19410 }
19411
19412 # Now, fix up files with prefix
19413 if ( length $args{prefix} ) { # check in case disabled with q{}
19414 $args{prefix} =~ s{/$}{};
19415 for my $v ( values %$p ) {
19416 $v->{file} = "$args{prefix}/$v->{file}";
19417 }
19418 }
19419
19420 return $p
19421 }
19422
19423 sub package_versions_from_directory {
19424 my ( $class, $dir, $files ) = @_;
19425
19426 my @files;
19427
19428 if ( $files ) {
19429 @files = @$files;
19430 }
19431 else {
19432 find( {
19433 wanted => sub {
19434 push @files, $_ if -f $_ && /\.pm$/;
19435 },
19436 no_chdir => 1,
19437 }, $dir );
19438 }
19439
19440 # First, we enumerate all packages & versions,
19441 # separating into primary & alternative candidates
19442 my( %prime, %alt );
19443 foreach my $file (@files) {
19444 my $mapped_filename = File::Spec->abs2rel( $file, $dir );
19445 my @path = File::Spec->splitdir( $mapped_filename );
19446 (my $prime_package = join( '::', @path )) =~ s/\.pm$//;
19447
19448 my $pm_info = $class->new_from_file( $file );
19449
19450 foreach my $package ( $pm_info->packages_inside ) {
19451 next if $package eq 'main'; # main can appear numerous times, ignore
19452 next if $package eq 'DB'; # special debugging package, ignore
19453 next if grep /^_/, split( /::/, $package ); # private package, ignore
19454
19455 my $version = $pm_info->version( $package );
19456
19457 $prime_package = $package if lc($prime_package) eq lc($package);
19458 if ( $package eq $prime_package ) {
19459 if ( exists( $prime{$package} ) ) {
19460 croak "Unexpected conflict in '$package'; multiple versions found.\n";
19461 }
19462 else {
19463 $mapped_filename = "$package.pm" if lc("$package.pm") eq lc($mapped_filename);
19464 $prime{$package}{file} = $mapped_filename;
19465 $prime{$package}{version} = $version if defined( $version );
19466 }
19467 }
19468 else {
19469 push( @{$alt{$package}}, {
19470 file => $mapped_filename,
19471 version => $version,
19472 } );
19473 }
19474 }
19475 }
19476
19477 # Then we iterate over all the packages found above, identifying conflicts
19478 # and selecting the "best" candidate for recording the file & version
19479 # for each package.
19480 foreach my $package ( keys( %alt ) ) {
19481 my $result = $resolve_module_versions->( $alt{$package} );
19482
19483 if ( exists( $prime{$package} ) ) { # primary package selected
19484
19485 if ( $result->{err} ) {
19486 # Use the selected primary package, but there are conflicting
19487 # errors among multiple alternative packages that need to be
19488 # reported
19489 log_info {
19490 "Found conflicting versions for package '$package'\n" .
19491 " $prime{$package}{file} ($prime{$package}{version})\n" .
19492 $result->{err}
19493 };
19494
19495 }
19496 elsif ( defined( $result->{version} ) ) {
19497 # There is a primary package selected, and exactly one
19498 # alternative package
19499
19500 if ( exists( $prime{$package}{version} ) &&
19501 defined( $prime{$package}{version} ) ) {
19502 # Unless the version of the primary package agrees with the
19503 # version of the alternative package, report a conflict
19504 if ( $compare_versions->(
19505 $prime{$package}{version}, '!=', $result->{version}
19506 )
19507 ) {
19508
19509 log_info {
19510 "Found conflicting versions for package '$package'\n" .
19511 " $prime{$package}{file} ($prime{$package}{version})\n" .
19512 " $result->{file} ($result->{version})\n"
19513 };
19514 }
19515
19516 }
19517 else {
19518 # The prime package selected has no version so, we choose to
19519 # use any alternative package that does have a version
19520 $prime{$package}{file} = $result->{file};
19521 $prime{$package}{version} = $result->{version};
19522 }
19523
19524 }
19525 else {
19526 # no alt package found with a version, but we have a prime
19527 # package so we use it whether it has a version or not
19528 }
19529
19530 }
19531 else { # No primary package was selected, use the best alternative
19532
19533 if ( $result->{err} ) {
19534 log_info {
19535 "Found conflicting versions for package '$package'\n" .
19536 $result->{err}
19537 };
19538 }
19539
19540 # Despite possible conflicting versions, we choose to record
19541 # something rather than nothing
19542 $prime{$package}{file} = $result->{file};
19543 $prime{$package}{version} = $result->{version}
19544 if defined( $result->{version} );
19545 }
19546 }
19547
19548 # Normalize versions. Can't use exists() here because of bug in YAML::Node.
19549 # XXX "bug in YAML::Node" comment seems irrelevant -- dagolden, 2009-05-18
19550 for (grep defined $_->{version}, values %prime) {
19551 $_->{version} = $normalize_version->( $_->{version} );
19552 }
19553
19554 return \%prime;
19555 }
19556 }
19557
19558
19559 sub _init {
19560 my $class = shift;
19561 my $module = shift;
19562 my $filename = shift;
19563 my %props = @_;
19564
19565 my $handle = delete $props{handle};
19566 my( %valid_props, @valid_props );
19567 @valid_props = qw( collect_pod inc decode_pod );
19568 @valid_props{@valid_props} = delete( @props{@valid_props} );
19569 warn "Unknown properties: @{[keys %props]}\n" if scalar( %props );
19570
19571 my %data = (
19572 module => $module,
19573 filename => $filename,
19574 version => undef,
19575 packages => [],
19576 versions => {},
19577 pod => {},
19578 pod_headings => [],
19579 collect_pod => 0,
19580
19581 %valid_props,
19582 );
19583
19584 my $self = bless(\%data, $class);
19585
19586 if ( not $handle ) {
19587 my $filename = $self->{filename};
19588 open $handle, '<', $filename
19589 or croak( "Can't open '$filename': $!" );
19590
19591 $self->_handle_bom($handle, $filename);
19592 }
19593 $self->_parse_fh($handle);
19594
19595 @{$self->{packages}} = __uniq(@{$self->{packages}});
19596
19597 unless($self->{module} and length($self->{module})) {
19598 # CAVEAT (possible TODO): .pmc files not treated the same as .pm
19599 if ($self->{filename} =~ /\.pm$/) {
19600 my ($v, $d, $f) = File::Spec->splitpath($self->{filename});
19601 $f =~ s/\..+$//;
19602 my @candidates = grep /(^|::)$f$/, @{$self->{packages}};
19603 $self->{module} = shift(@candidates); # this may be undef
19604 }
19605 else {
19606 # this seems like an atrocious heuristic, albeit marginally better than
19607 # what was here before. It should be rewritten entirely to be more like
19608 # "if it's not a .pm file, it's not require()able as a name, therefore
19609 # name() should be undef."
19610 if ((grep /main/, @{$self->{packages}})
19611 or (grep /main/, keys %{$self->{versions}})) {
19612 $self->{module} = 'main';
19613 }
19614 else {
19615 # TODO: this should maybe default to undef instead
19616 $self->{module} = $self->{packages}[0] || '';
19617 }
19618 }
19619 }
19620
19621 $self->{version} = $self->{versions}{$self->{module}}
19622 if defined( $self->{module} );
19623
19624 return $self;
19625 }
19626
19627 # class method
19628 sub _do_find_module {
19629 my $class = shift;
19630 my $module = shift || croak 'find_module_by_name() requires a package name';
19631 my $dirs = shift || \@INC;
19632
19633 my $file = File::Spec->catfile(split( /::/, $module));
19634 foreach my $dir ( @$dirs ) {
19635 my $testfile = File::Spec->catfile($dir, $file);
19636 return [ File::Spec->rel2abs( $testfile ), $dir ]
19637 if -e $testfile and !-d _; # For stuff like ExtUtils::xsubpp
19638 # CAVEAT (possible TODO): .pmc files are not discoverable here
19639 $testfile .= '.pm';
19640 return [ File::Spec->rel2abs( $testfile ), $dir ]
19641 if -e $testfile;
19642 }
19643 return;
19644 }
19645
19646 # class method
19647 sub find_module_by_name {
19648 my $found = shift()->_do_find_module(@_) or return;
19649 return $found->[0];
19650 }
19651
19652 # class method
19653 sub find_module_dir_by_name {
19654 my $found = shift()->_do_find_module(@_) or return;
19655 return $found->[1];
19656 }
19657
19658
19659 # given a line of perl code, attempt to parse it if it looks like a
19660 # $VERSION assignment, returning sigil, full name, & package name
19661 sub _parse_version_expression {
19662 my $self = shift;
19663 my $line = shift;
19664
19665 my( $sigil, $variable_name, $package);
19666 if ( $line =~ /$VERS_REGEXP/o ) {
19667 ( $sigil, $variable_name, $package) = $2 ? ( $1, $2, $3 ) : ( $4, $5, $6 );
19668 if ( $package ) {
19669 $package = ($package eq '::') ? 'main' : $package;
19670 $package =~ s/::$//;
19671 }
19672 }
19673
19674 return ( $sigil, $variable_name, $package );
19675 }
19676
19677 # Look for a UTF-8/UTF-16BE/UTF-16LE BOM at the beginning of the stream.
19678 # If there's one, then skip it and set the :encoding layer appropriately.
19679 sub _handle_bom {
19680 my ($self, $fh, $filename) = @_;
19681
19682 my $pos = tell $fh;
19683 return unless defined $pos;
19684
19685 my $buf = ' ' x 2;
19686 my $count = read $fh, $buf, length $buf;
19687 return unless defined $count and $count >= 2;
19688
19689 my $encoding;
19690 if ( $buf eq "\x{FE}\x{FF}" ) {
19691 $encoding = 'UTF-16BE';
19692 }
19693 elsif ( $buf eq "\x{FF}\x{FE}" ) {
19694 $encoding = 'UTF-16LE';
19695 }
19696 elsif ( $buf eq "\x{EF}\x{BB}" ) {
19697 $buf = ' ';
19698 $count = read $fh, $buf, length $buf;
19699 if ( defined $count and $count >= 1 and $buf eq "\x{BF}" ) {
19700 $encoding = 'UTF-8';
19701 }
19702 }
19703
19704 if ( defined $encoding ) {
19705 if ( "$]" >= 5.008 ) {
19706 binmode( $fh, ":encoding($encoding)" );
19707 }
19708 }
19709 else {
19710 seek $fh, $pos, SEEK_SET
19711 or croak( sprintf "Can't reset position to the top of '$filename'" );
19712 }
19713
19714 return $encoding;
19715 }
19716
19717 sub _parse_fh {
19718 my ($self, $fh) = @_;
19719
19720 my( $in_pod, $seen_end, $need_vers ) = ( 0, 0, 0 );
19721 my( @packages, %vers, %pod, @pod );
19722 my $package = 'main';
19723 my $pod_sect = '';
19724 my $pod_data = '';
19725 my $in_end = 0;
19726 my $encoding = '';
19727
19728 while (defined( my $line = <$fh> )) {
19729 my $line_num = $.;
19730
19731 chomp( $line );
19732
19733 # From toke.c : any line that begins by "=X", where X is an alphabetic
19734 # character, introduces a POD segment.
19735 my $is_cut;
19736 if ( $line =~ /^=([a-zA-Z].*)/ ) {
19737 my $cmd = $1;
19738 # Then it goes back to Perl code for "=cutX" where X is a non-alphabetic
19739 # character (which includes the newline, but here we chomped it away).
19740 $is_cut = $cmd =~ /^cut(?:[^a-zA-Z]|$)/;
19741 $in_pod = !$is_cut;
19742 }
19743
19744 if ( $in_pod ) {
19745
19746 if ( $line =~ /^=head[1-4]\s+(.+)\s*$/ ) {
19747 push( @pod, $1 );
19748 if ( $self->{collect_pod} && length( $pod_data ) ) {
19749 $pod{$pod_sect} = $pod_data;
19750 $pod_data = '';
19751 }
19752 $pod_sect = $1;
19753 }
19754 elsif ( $self->{collect_pod} ) {
19755 if ( $self->{decode_pod} && $line =~ /^=encoding ([\w-]+)/ ) {
19756 $encoding = $1;
19757 }
19758 $pod_data .= "$line\n";
19759 }
19760 next;
19761 }
19762 elsif ( $is_cut ) {
19763 if ( $self->{collect_pod} && length( $pod_data ) ) {
19764 $pod{$pod_sect} = $pod_data;
19765 $pod_data = '';
19766 }
19767 $pod_sect = '';
19768 next;
19769 }
19770
19771 # Skip after __END__
19772 next if $in_end;
19773
19774 # Skip comments in code
19775 next if $line =~ /^\s*#/;
19776
19777 # Would be nice if we could also check $in_string or something too
19778 if ($line eq '__END__') {
19779 $in_end++;
19780 next;
19781 }
19782
19783 last if $line eq '__DATA__';
19784
19785 # parse $line to see if it's a $VERSION declaration
19786 my( $version_sigil, $version_fullname, $version_package ) =
19787 index($line, 'VERSION') >= 1
19788 ? $self->_parse_version_expression( $line )
19789 : ();
19790
19791 if ( $line =~ /$PKG_REGEXP/o or $line =~ /$CLASS_REGEXP/ ) {
19792 $package = $1;
19793 my $version = $2;
19794 push( @packages, $package ) unless grep( $package eq $_, @packages );
19795 $need_vers = defined $version ? 0 : 1;
19796
19797 if ( not exists $vers{$package} and defined $version ){
19798 # Upgrade to a version object.
19799 my $dwim_version = eval { _dwim_version($version) };
19800 croak "Version '$version' from $self->{filename} does not appear to be valid:\n$line\n\nThe fatal error was: $@\n"
19801 unless defined $dwim_version; # "0" is OK!
19802 $vers{$package} = $dwim_version;
19803 }
19804 }
19805
19806 # VERSION defined with full package spec, i.e. $Module::VERSION
19807 elsif ( $version_fullname && $version_package ) {
19808 # we do NOT save this package in found @packages
19809 $need_vers = 0 if $version_package eq $package;
19810
19811 unless ( defined $vers{$version_package} && length $vers{$version_package} ) {
19812 $vers{$version_package} = $self->_evaluate_version_line( $version_sigil, $version_fullname, $line );
19813 }
19814 }
19815
19816 # first non-comment line in undeclared package main is VERSION
19817 elsif ( $package eq 'main' && $version_fullname && !exists($vers{main}) ) {
19818 $need_vers = 0;
19819 my $v = $self->_evaluate_version_line( $version_sigil, $version_fullname, $line );
19820 $vers{$package} = $v;
19821 push( @packages, 'main' );
19822 }
19823
19824 # first non-comment line in undeclared package defines package main
19825 elsif ( $package eq 'main' && !exists($vers{main}) && $line =~ /\w/ ) {
19826 $need_vers = 1;
19827 $vers{main} = '';
19828 push( @packages, 'main' );
19829 }
19830
19831 # only keep if this is the first $VERSION seen
19832 elsif ( $version_fullname && $need_vers ) {
19833 $need_vers = 0;
19834 my $v = $self->_evaluate_version_line( $version_sigil, $version_fullname, $line );
19835
19836 unless ( defined $vers{$package} && length $vers{$package} ) {
19837 $vers{$package} = $v;
19838 }
19839 }
19840 } # end loop over each line
19841
19842 if ( $self->{collect_pod} && length($pod_data) ) {
19843 $pod{$pod_sect} = $pod_data;
19844 }
19845
19846 if ( $self->{decode_pod} && $encoding ) {
19847 require Encode;
19848 $_ = Encode::decode( $encoding, $_ ) for values %pod;
19849 }
19850
19851 $self->{versions} = \%vers;
19852 $self->{packages} = \@packages;
19853 $self->{pod} = \%pod;
19854 $self->{pod_headings} = \@pod;
19855 }
19856
19857 sub __uniq (@)
19858 {
19859 my (%seen, $key);
19860 grep !$seen{ $key = $_ }++, @_;
19861 }
19862
19863 {
19864 my $pn = 0;
19865 sub _evaluate_version_line {
19866 my $self = shift;
19867 my( $sigil, $variable_name, $line ) = @_;
19868
19869 # We compile into a local sub because 'use version' would cause
19870 # compiletime/runtime issues with local()
19871 $pn++; # everybody gets their own package
19872 my $eval = qq{ my \$dummy = q# Hide from _packages_inside()
19873 #; package Module::Metadata::_version::p${pn};
19874 use version;
19875 sub {
19876 local $sigil$variable_name;
19877 $line;
19878 return \$$variable_name if defined \$$variable_name;
19879 return \$Module::Metadata::_version::p${pn}::$variable_name;
19880 };
19881 };
19882
19883 $eval = $1 if $eval =~ m{^(.+)}s;
19884
19885 local $^W;
19886 # Try to get the $VERSION
19887 my $vsub = __clean_eval($eval);
19888 # some modules say $VERSION <equal sign> $Foo::Bar::VERSION, but Foo::Bar isn't
19889 # installed, so we need to hunt in ./lib for it
19890 if ( $@ =~ /Can't locate/ && -d 'lib' ) {
19891 local @INC = ('lib',@INC);
19892 $vsub = __clean_eval($eval);
19893 }
19894 warn "Error evaling version line '$eval' in $self->{filename}: $@\n"
19895 if $@;
19896
19897 (ref($vsub) eq 'CODE') or
19898 croak "failed to build version sub for $self->{filename}";
19899
19900 my $result = eval { $vsub->() };
19901 # FIXME: $eval is not the right thing to print here
19902 croak "Could not get version from $self->{filename} by executing:\n$eval\n\nThe fatal error was: $@\n"
19903 if $@;
19904
19905 # Upgrade it into a version object
19906 my $version = eval { _dwim_version($result) };
19907
19908 # FIXME: $eval is not the right thing to print here
19909 croak "Version '$result' from $self->{filename} does not appear to be valid:\n$eval\n\nThe fatal error was: $@\n"
19910 unless defined $version; # "0" is OK!
19911
19912 return $version;
19913 }
19914 }
19915
19916 # Try to DWIM when things fail the lax version test in obvious ways
19917 {
19918 my @version_prep = (
19919 # Best case, it just works
19920 sub { return shift },
19921
19922 # If we still don't have a version, try stripping any
19923 # trailing junk that is prohibited by lax rules
19924 sub {
19925 my $v = shift;
19926 $v =~ s{([0-9])[a-z-].*$}{$1}i; # 1.23-alpha or 1.23b
19927 return $v;
19928 },
19929
19930 # Activestate apparently creates custom versions like '1.23_45_01', which
19931 # cause version.pm to think it's an invalid alpha. So check for that
19932 # and strip them
19933 sub {
19934 my $v = shift;
19935 my $num_dots = () = $v =~ m{(\.)}g;
19936 my $num_unders = () = $v =~ m{(_)}g;
19937 my $leading_v = substr($v,0,1) eq 'v';
19938 if ( ! $leading_v && $num_dots < 2 && $num_unders > 1 ) {
19939 $v =~ s{_}{}g;
19940 $num_unders = () = $v =~ m{(_)}g;
19941 }
19942 return $v;
19943 },
19944
19945 # Worst case, try numifying it like we would have before version objects
19946 sub {
19947 my $v = shift;
19948 no warnings 'numeric';
19949 return 0 + $v;
19950 },
19951
19952 );
19953
19954 sub _dwim_version {
19955 my ($result) = shift;
19956
19957 return $result if ref($result) eq 'version';
19958
19959 my ($version, $error);
19960 for my $f (@version_prep) {
19961 $result = $f->($result);
19962 $version = eval { version->new($result) };
19963 $error ||= $@ if $@; # capture first failure
19964 last if defined $version;
19965 }
19966
19967 croak $error unless defined $version;
19968
19969 return $version;
19970 }
19971 }
19972
19973 ############################################################
19974
19975 # accessors
19976 sub name { $_[0]->{module} }
19977
19978 sub filename { $_[0]->{filename} }
19979 sub packages_inside { @{$_[0]->{packages}} }
19980 sub pod_inside { @{$_[0]->{pod_headings}} }
19981 sub contains_pod { 0+@{$_[0]->{pod_headings}} }
19982
19983 sub version {
19984 my $self = shift;
19985 my $mod = shift || $self->{module};
19986 my $vers;
19987 if ( defined( $mod ) && length( $mod ) &&
19988 exists( $self->{versions}{$mod} ) ) {
19989 return $self->{versions}{$mod};
19990 }
19991 else {
19992 return undef;
19993 }
19994 }
19995
19996 sub pod {
19997 my $self = shift;
19998 my $sect = shift;
19999 if ( defined( $sect ) && length( $sect ) &&
20000 exists( $self->{pod}{$sect} ) ) {
20001 return $self->{pod}{$sect};
20002 }
20003 else {
20004 return undef;
20005 }
20006 }
20007
20008 sub is_indexable {
20009 my ($self, $package) = @_;
20010
20011 my @indexable_packages = grep $_ ne 'main', $self->packages_inside;
20012
20013 # check for specific package, if provided
20014 return !! grep $_ eq $package, @indexable_packages if $package;
20015
20016 # otherwise, check for any indexable packages at all
20017 return !! @indexable_packages;
20018 }
20019
20020 1;
20021
20022 __END__
20023
20024 =pod
20025
20026 =encoding UTF-8
20027
20028 =head1 NAME
20029
20030 Module::Metadata - Gather package and POD information from perl module files
20031
20032 =head1 VERSION
20033
20034 version 1.000038
20035
20036 =head1 SYNOPSIS
20037
20038 use Module::Metadata;
20039
20040 # information about a .pm file
20041 my $info = Module::Metadata->new_from_file( $file );
20042 my $version = $info->version;
20043
20044 # CPAN META 'provides' field for .pm files in a directory
20045 my $provides = Module::Metadata->provides(
20046 dir => 'lib', version => 2
20047 );
20048
20049 =head1 DESCRIPTION
20050
20051 This module provides a standard way to gather metadata about a .pm file through
20052 (mostly) static analysis and (some) code execution. When determining the
20053 version of a module, the C<$VERSION> assignment is C<eval>ed, as is traditional
20054 in the CPAN toolchain.
20055
20056 =head1 CLASS METHODS
20057
20058 =head2 C<< new_from_file($filename, collect_pod => 1, decode_pod => 1) >>
20059
20060 Constructs a C<Module::Metadata> object given the path to a file. Returns
20061 undef if the filename does not exist.
20062
20063 C<collect_pod> is a optional boolean argument that determines whether POD
20064 data is collected and stored for reference. POD data is not collected by
20065 default. POD headings are always collected.
20066
20067 If the file begins by an UTF-8, UTF-16BE or UTF-16LE byte-order mark, then
20068 it is skipped before processing, and the content of the file is also decoded
20069 appropriately starting from perl 5.8.
20070
20071 Alternatively, if C<decode_pod> is set, it will decode the collected pod
20072 sections according to the C<=encoding> declaration.
20073
20074 =head2 C<< new_from_handle($handle, $filename, collect_pod => 1, decode_pod => 1) >>
20075
20076 This works just like C<new_from_file>, except that a handle can be provided
20077 as the first argument.
20078
20079 Note that there is no validation to confirm that the handle is a handle or
20080 something that can act like one. Passing something that isn't a handle will
20081 cause a exception when trying to read from it. The C<filename> argument is
20082 mandatory or undef will be returned.
20083
20084 You are responsible for setting the decoding layers on C<$handle> if
20085 required.
20086
20087 =head2 C<< new_from_module($module, collect_pod => 1, inc => \@dirs, decode_pod => 1) >>
20088
20089 Constructs a C<Module::Metadata> object given a module or package name.
20090 Returns undef if the module cannot be found.
20091
20092 In addition to accepting the C<collect_pod> and C<decode_pod> arguments as
20093 described above, this method accepts a C<inc> argument which is a reference to
20094 an array of directories to search for the module. If none are given, the
20095 default is @INC.
20096
20097 If the file that contains the module begins by an UTF-8, UTF-16BE or
20098 UTF-16LE byte-order mark, then it is skipped before processing, and the
20099 content of the file is also decoded appropriately starting from perl 5.8.
20100
20101 =head2 C<< find_module_by_name($module, \@dirs) >>
20102
20103 Returns the path to a module given the module or package name. A list
20104 of directories can be passed in as an optional parameter, otherwise
20105 @INC is searched.
20106
20107 Can be called as either an object or a class method.
20108
20109 =head2 C<< find_module_dir_by_name($module, \@dirs) >>
20110
20111 Returns the entry in C<@dirs> (or C<@INC> by default) that contains
20112 the module C<$module>. A list of directories can be passed in as an
20113 optional parameter, otherwise @INC is searched.
20114
20115 Can be called as either an object or a class method.
20116
20117 =head2 C<< provides( %options ) >>
20118
20119 This is a convenience wrapper around C<package_versions_from_directory>
20120 to generate a CPAN META C<provides> data structure. It takes key/value
20121 pairs. Valid option keys include:
20122
20123 =over
20124
20125 =item version B<(required)>
20126
20127 Specifies which version of the L<CPAN::Meta::Spec> should be used as
20128 the format of the C<provides> output. Currently only '1.4' and '2'
20129 are supported (and their format is identical). This may change in
20130 the future as the definition of C<provides> changes.
20131
20132 The C<version> option is required. If it is omitted or if
20133 an unsupported version is given, then C<provides> will throw an error.
20134
20135 =item dir
20136
20137 Directory to search recursively for F<.pm> files. May not be specified with
20138 C<files>.
20139
20140 =item files
20141
20142 Array reference of files to examine. May not be specified with C<dir>.
20143
20144 =item prefix
20145
20146 String to prepend to the C<file> field of the resulting output. This defaults
20147 to F<lib>, which is the common case for most CPAN distributions with their
20148 F<.pm> files in F<lib>. This option ensures the META information has the
20149 correct relative path even when the C<dir> or C<files> arguments are
20150 absolute or have relative paths from a location other than the distribution
20151 root.
20152
20153 =back
20154
20155 For example, given C<dir> of 'lib' and C<prefix> of 'lib', the return value
20156 is a hashref of the form:
20157
20158 {
20159 'Package::Name' => {
20160 version => '0.123',
20161 file => 'lib/Package/Name.pm'
20162 },
20163 'OtherPackage::Name' => ...
20164 }
20165
20166 =head2 C<< package_versions_from_directory($dir, \@files?) >>
20167
20168 Scans C<$dir> for .pm files (unless C<@files> is given, in which case looks
20169 for those files in C<$dir> - and reads each file for packages and versions,
20170 returning a hashref of the form:
20171
20172 {
20173 'Package::Name' => {
20174 version => '0.123',
20175 file => 'Package/Name.pm'
20176 },
20177 'OtherPackage::Name' => ...
20178 }
20179
20180 The C<DB> and C<main> packages are always omitted, as are any "private"
20181 packages that have leading underscores in the namespace (e.g.
20182 C<Foo::_private>)
20183
20184 Note that the file path is relative to C<$dir> if that is specified.
20185 This B<must not> be used directly for CPAN META C<provides>. See
20186 the C<provides> method instead.
20187
20188 =head2 C<< log_info (internal) >>
20189
20190 Used internally to perform logging; imported from Log::Contextual if
20191 Log::Contextual has already been loaded, otherwise simply calls warn.
20192
20193 =head1 OBJECT METHODS
20194
20195 =head2 C<< name() >>
20196
20197 Returns the name of the package represented by this module. If there
20198 is more than one package, it makes a best guess based on the
20199 filename. If it's a script (i.e. not a *.pm) the package name is
20200 'main'.
20201
20202 =head2 C<< version($package) >>
20203
20204 Returns the version as defined by the $VERSION variable for the
20205 package as returned by the C<name> method if no arguments are
20206 given. If given the name of a package it will attempt to return the
20207 version of that package if it is specified in the file.
20208
20209 =head2 C<< filename() >>
20210
20211 Returns the absolute path to the file.
20212 Note that this file may not actually exist on disk yet, e.g. if the module was read from an in-memory filehandle.
20213
20214 =head2 C<< packages_inside() >>
20215
20216 Returns a list of packages. Note: this is a raw list of packages
20217 discovered (or assumed, in the case of C<main>). It is not
20218 filtered for C<DB>, C<main> or private packages the way the
20219 C<provides> method does. Invalid package names are not returned,
20220 for example "Foo:Bar". Strange but valid package names are
20221 returned, for example "Foo::Bar::", and are left up to the caller
20222 on how to handle.
20223
20224 =head2 C<< pod_inside() >>
20225
20226 Returns a list of POD sections.
20227
20228 =head2 C<< contains_pod() >>
20229
20230 Returns true if there is any POD in the file.
20231
20232 =head2 C<< pod($section) >>
20233
20234 Returns the POD data in the given section.
20235
20236 =head2 C<< is_indexable($package) >> or C<< is_indexable() >>
20237
20238 Available since version 1.000020.
20239
20240 Returns a boolean indicating whether the package (if provided) or any package
20241 (otherwise) is eligible for indexing by PAUSE, the Perl Authors Upload Server.
20242 Note This only checks for valid C<package> declarations, and does not take any
20243 ownership information into account.
20244
20245 =head1 SUPPORT
20246
20247 Bugs may be submitted through L<the RT bug tracker|https://rt.cpan.org/Public/Dist/Display.html?Name=Module-Metadata>
20248 (or L<bug-Module-Metadata@rt.cpan.org|mailto:bug-Module-Metadata@rt.cpan.org>).
20249
20250 There is also a mailing list available for users of this distribution, at
20251 L<http://lists.perl.org/list/cpan-workers.html>.
20252
20253 There is also an irc channel available for users of this distribution, at
20254 L<C<#toolchain> on C<irc.perl.org>|irc://irc.perl.org/#toolchain>.
20255
20256 =head1 AUTHOR
20257
20258 Original code from Module::Build::ModuleInfo by Ken Williams
20259 <kwilliams@cpan.org>, Randy W. Sims <RandyS@ThePierianSpring.org>
20260
20261 Released as Module::Metadata by Matt S Trout (mst) <mst@shadowcat.co.uk> with
20262 assistance from David Golden (xdg) <dagolden@cpan.org>.
20263
20264 =head1 CONTRIBUTORS
20265
20266 =for stopwords Karen Etheridge David Golden Vincent Pit Matt S Trout Chris Nehren Graham Knop Olivier Mengué Tomas Doran Christian Walde Craig A. Berry Tatsuhiko Miyagawa tokuhirom 'BinGOs' Williams Mitchell Steinbrunner Edward Zborowski Gareth Harper James Raspass Jerry D. Hedden Josh Jore Kent Fredric Leon Timmermans Peter Rabbitson Steve Hay
20267
20268 =over 4
20269
20270 =item *
20271
20272 Karen Etheridge <ether@cpan.org>
20273
20274 =item *
20275
20276 David Golden <dagolden@cpan.org>
20277
20278 =item *
20279
20280 Vincent Pit <perl@profvince.com>
20281
20282 =item *
20283
20284 Matt S Trout <mst@shadowcat.co.uk>
20285
20286 =item *
20287
20288 Chris Nehren <apeiron@cpan.org>
20289
20290 =item *
20291
20292 Graham Knop <haarg@haarg.org>
20293
20294 =item *
20295
20296 Olivier Mengué <dolmen@cpan.org>
20297
20298 =item *
20299
20300 Tomas Doran <bobtfish@bobtfish.net>
20301
20302 =item *
20303
20304 Christian Walde <walde.christian@googlemail.com>
20305
20306 =item *
20307
20308 Craig A. Berry <cberry@cpan.org>
20309
20310 =item *
20311
20312 Tatsuhiko Miyagawa <miyagawa@bulknews.net>
20313
20314 =item *
20315
20316 tokuhirom <tokuhirom@gmail.com>
20317
20318 =item *
20319
20320 Chris 'BinGOs' Williams <chris@bingosnet.co.uk>
20321
20322 =item *
20323
20324 David Mitchell <davem@iabyn.com>
20325
20326 =item *
20327
20328 David Steinbrunner <dsteinbrunner@pobox.com>
20329
20330 =item *
20331
20332 Edward Zborowski <ed@rubensteintech.com>
20333
20334 =item *
20335
20336 Gareth Harper <gareth@broadbean.com>
20337
20338 =item *
20339
20340 James Raspass <jraspass@gmail.com>
20341
20342 =item *
20343
20344 Jerry D. Hedden <jdhedden@cpan.org>
20345
20346 =item *
20347
20348 Josh Jore <jjore@cpan.org>
20349
20350 =item *
20351
20352 Kent Fredric <kentnl@cpan.org>
20353
20354 =item *
20355
20356 Leon Timmermans <fawaka@gmail.com>
20357
20358 =item *
20359
20360 Peter Rabbitson <ribasushi@cpan.org>
20361
20362 =item *
20363
20364 Steve Hay <steve.m.hay@googlemail.com>
20365
20366 =back
20367
20368 =head1 COPYRIGHT & LICENSE
20369
20370 Original code Copyright (c) 2001-2011 Ken Williams.
20371 Additional code Copyright (c) 2010-2011 Matt Trout and David Golden.
20372 All rights reserved.
20373
20374 This library is free software; you can redistribute it and/or
20375 modify it under the same terms as Perl itself.
20376
20377 =cut
20378 MODULE_METADATA
20379  
20380 $fatpacked{"Parse/CPAN/Meta.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'PARSE_CPAN_META';
20381 use 5.008001;
20382 use strict;
20383 package Parse::CPAN::Meta;
20384 # ABSTRACT: Parse META.yml and META.json CPAN metadata files
20385 our $VERSION = '1.4414'; # VERSION
20386
20387 use Exporter;
20388 use Carp 'croak';
20389
20390 our @ISA = qw/Exporter/;
20391 our @EXPORT_OK = qw/Load LoadFile/;
20392
20393 sub load_file {
20394 my ($class, $filename) = @_;
20395
20396 my $meta = _slurp($filename);
20397
20398 if ($filename =~ /\.ya?ml$/) {
20399 return $class->load_yaml_string($meta);
20400 }
20401 elsif ($filename =~ /\.json$/) {
20402 return $class->load_json_string($meta);
20403 }
20404 else {
20405 $class->load_string($meta); # try to detect yaml/json
20406 }
20407 }
20408
20409 sub load_string {
20410 my ($class, $string) = @_;
20411 if ( $string =~ /^---/ ) { # looks like YAML
20412 return $class->load_yaml_string($string);
20413 }
20414 elsif ( $string =~ /^\s*\{/ ) { # looks like JSON
20415 return $class->load_json_string($string);
20416 }
20417 else { # maybe doc-marker-free YAML
20418 return $class->load_yaml_string($string);
20419 }
20420 }
20421
20422 sub load_yaml_string {
20423 my ($class, $string) = @_;
20424 my $backend = $class->yaml_backend();
20425 my $data = eval { no strict 'refs'; &{"$backend\::Load"}($string) };
20426 croak $@ if $@;
20427 return $data || {}; # in case document was valid but empty
20428 }
20429
20430 sub load_json_string {
20431 my ($class, $string) = @_;
20432 my $data = eval { $class->json_backend()->new->decode($string) };
20433 croak $@ if $@;
20434 return $data || {};
20435 }
20436
20437 sub yaml_backend {
20438 if (! defined $ENV{PERL_YAML_BACKEND} ) {
20439 _can_load( 'CPAN::Meta::YAML', 0.011 )
20440 or croak "CPAN::Meta::YAML 0.011 is not available\n";
20441 return "CPAN::Meta::YAML";
20442 }
20443 else {
20444 my $backend = $ENV{PERL_YAML_BACKEND};
20445 _can_load( $backend )
20446 or croak "Could not load PERL_YAML_BACKEND '$backend'\n";
20447 $backend->can("Load")
20448 or croak "PERL_YAML_BACKEND '$backend' does not implement Load()\n";
20449 return $backend;
20450 }
20451 }
20452
20453 sub json_backend {
20454 if (! $ENV{PERL_JSON_BACKEND} or $ENV{PERL_JSON_BACKEND} eq 'JSON::PP') {
20455 _can_load( 'JSON::PP' => 2.27103 )
20456 or croak "JSON::PP 2.27103 is not available\n";
20457 return 'JSON::PP';
20458 }
20459 else {
20460 _can_load( 'JSON' => 2.5 )
20461 or croak "JSON 2.5 is required for " .
20462 "\$ENV{PERL_JSON_BACKEND} = '$ENV{PERL_JSON_BACKEND}'\n";
20463 return "JSON";
20464 }
20465 }
20466
20467 sub _slurp {
20468 require Encode;
20469 open my $fh, "<:raw", "$_[0]" ## no critic
20470 or die "can't open $_[0] for reading: $!";
20471 my $content = do { local $/; <$fh> };
20472 $content = Encode::decode('UTF-8', $content, Encode::PERLQQ());
20473 return $content;
20474 }
20475
20476 sub _can_load {
20477 my ($module, $version) = @_;
20478 (my $file = $module) =~ s{::}{/}g;
20479 $file .= ".pm";
20480 return 1 if $INC{$file};
20481 return 0 if exists $INC{$file}; # prior load failed
20482 eval { require $file; 1 }
20483 or return 0;
20484 if ( defined $version ) {
20485 eval { $module->VERSION($version); 1 }
20486 or return 0;
20487 }
20488 return 1;
20489 }
20490
20491 # Kept for backwards compatibility only
20492 # Create an object from a file
20493 sub LoadFile ($) {
20494 return Load(_slurp(shift));
20495 }
20496
20497 # Parse a document from a string.
20498 sub Load ($) {
20499 require CPAN::Meta::YAML;
20500 my $object = eval { CPAN::Meta::YAML::Load(shift) };
20501 croak $@ if $@;
20502 return $object;
20503 }
20504
20505 1;
20506
20507 __END__
20508
20509 =pod
20510
20511 =encoding UTF-8
20512
20513 =head1 NAME
20514
20515 Parse::CPAN::Meta - Parse META.yml and META.json CPAN metadata files
20516
20517 =head1 VERSION
20518
20519 version 1.4414
20520
20521 =head1 SYNOPSIS
20522
20523 #############################################
20524 # In your file
20525
20526 ---
20527 name: My-Distribution
20528 version: 1.23
20529 resources:
20530 homepage: "http://example.com/dist/My-Distribution"
20531
20532
20533 #############################################
20534 # In your program
20535
20536 use Parse::CPAN::Meta;
20537
20538 my $distmeta = Parse::CPAN::Meta->load_file('META.yml');
20539
20540 # Reading properties
20541 my $name = $distmeta->{name};
20542 my $version = $distmeta->{version};
20543 my $homepage = $distmeta->{resources}{homepage};
20544
20545 =head1 DESCRIPTION
20546
20547 B<Parse::CPAN::Meta> is a parser for F<META.json> and F<META.yml> files, using
20548 L<JSON::PP> and/or L<CPAN::Meta::YAML>.
20549
20550 B<Parse::CPAN::Meta> provides three methods: C<load_file>, C<load_json_string>,
20551 and C<load_yaml_string>. These will read and deserialize CPAN metafiles, and
20552 are described below in detail.
20553
20554 B<Parse::CPAN::Meta> provides a legacy API of only two functions,
20555 based on the YAML functions of the same name. Wherever possible,
20556 identical calling semantics are used. These may only be used with YAML sources.
20557
20558 All error reporting is done with exceptions (die'ing).
20559
20560 Note that META files are expected to be in UTF-8 encoding, only. When
20561 converted string data, it must first be decoded from UTF-8.
20562
20563 =begin Pod::Coverage
20564
20565
20566
20567
20568 =end Pod::Coverage
20569
20570 =head1 METHODS
20571
20572 =head2 load_file
20573
20574 my $metadata_structure = Parse::CPAN::Meta->load_file('META.json');
20575
20576 my $metadata_structure = Parse::CPAN::Meta->load_file('META.yml');
20577
20578 This method will read the named file and deserialize it to a data structure,
20579 determining whether it should be JSON or YAML based on the filename.
20580 The file will be read using the ":utf8" IO layer.
20581
20582 =head2 load_yaml_string
20583
20584 my $metadata_structure = Parse::CPAN::Meta->load_yaml_string($yaml_string);
20585
20586 This method deserializes the given string of YAML and returns the first
20587 document in it. (CPAN metadata files should always have only one document.)
20588 If the source was UTF-8 encoded, the string must be decoded before calling
20589 C<load_yaml_string>.
20590
20591 =head2 load_json_string
20592
20593 my $metadata_structure = Parse::CPAN::Meta->load_json_string($json_string);
20594
20595 This method deserializes the given string of JSON and the result.
20596 If the source was UTF-8 encoded, the string must be decoded before calling
20597 C<load_json_string>.
20598
20599 =head2 load_string
20600
20601 my $metadata_structure = Parse::CPAN::Meta->load_string($some_string);
20602
20603 If you don't know whether a string contains YAML or JSON data, this method
20604 will use some heuristics and guess. If it can't tell, it assumes YAML.
20605
20606 =head2 yaml_backend
20607
20608 my $backend = Parse::CPAN::Meta->yaml_backend;
20609
20610 Returns the module name of the YAML serializer. See L</ENVIRONMENT>
20611 for details.
20612
20613 =head2 json_backend
20614
20615 my $backend = Parse::CPAN::Meta->json_backend;
20616
20617 Returns the module name of the JSON serializer. This will either
20618 be L<JSON::PP> or L<JSON>. Even if C<PERL_JSON_BACKEND> is set,
20619 this will return L<JSON> as further delegation is handled by
20620 the L<JSON> module. See L</ENVIRONMENT> for details.
20621
20622 =head1 FUNCTIONS
20623
20624 For maintenance clarity, no functions are exported by default. These functions
20625 are available for backwards compatibility only and are best avoided in favor of
20626 C<load_file>.
20627
20628 =head2 Load
20629
20630 my @yaml = Parse::CPAN::Meta::Load( $string );
20631
20632 Parses a string containing a valid YAML stream into a list of Perl data
20633 structures.
20634
20635 =head2 LoadFile
20636
20637 my @yaml = Parse::CPAN::Meta::LoadFile( 'META.yml' );
20638
20639 Reads the YAML stream from a file instead of a string.
20640
20641 =head1 ENVIRONMENT
20642
20643 =head2 PERL_JSON_BACKEND
20644
20645 By default, L<JSON::PP> will be used for deserializing JSON data. If the
20646 C<PERL_JSON_BACKEND> environment variable exists, is true and is not
20647 "JSON::PP", then the L<JSON> module (version 2.5 or greater) will be loaded and
20648 used to interpret C<PERL_JSON_BACKEND>. If L<JSON> is not installed or is too
20649 old, an exception will be thrown.
20650
20651 =head2 PERL_YAML_BACKEND
20652
20653 By default, L<CPAN::Meta::YAML> will be used for deserializing YAML data. If
20654 the C<PERL_YAML_BACKEND> environment variable is defined, then it is interpreted
20655 as a module to use for deserialization. The given module must be installed,
20656 must load correctly and must implement the C<Load()> function or an exception
20657 will be thrown.
20658
20659 =for :stopwords cpan testmatrix url annocpan anno bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan
20660
20661 =head1 SUPPORT
20662
20663 =head2 Bugs / Feature Requests
20664
20665 Please report any bugs or feature requests through the issue tracker
20666 at L<http://rt.cpan.org/Public/Dist/Display.html?Name=Parse-CPAN-Meta>.
20667 You will be notified automatically of any progress on your issue.
20668
20669 =head2 Source Code
20670
20671 This is open source software. The code repository is available for
20672 public review and contribution under the terms of the license.
20673
20674 L<https://github.com/Perl-Toolchain-Gang/Parse-CPAN-Meta>
20675
20676 git clone https://github.com/Perl-Toolchain-Gang/Parse-CPAN-Meta.git
20677
20678 =head1 AUTHORS
20679
20680 =over 4
20681
20682 =item *
20683
20684 Adam Kennedy <adamk@cpan.org>
20685
20686 =item *
20687
20688 David Golden <dagolden@cpan.org>
20689
20690 =back
20691
20692 =head1 CONTRIBUTORS
20693
20694 =over 4
20695
20696 =item *
20697
20698 Graham Knop <haarg@haarg.org>
20699
20700 =item *
20701
20702 Joshua ben Jore <jjore@cpan.org>
20703
20704 =item *
20705
20706 Neil Bowers <neil@bowers.com>
20707
20708 =item *
20709
20710 Ricardo Signes <rjbs@cpan.org>
20711
20712 =item *
20713
20714 Steffen Mueller <smueller@cpan.org>
20715
20716 =back
20717
20718 =head1 COPYRIGHT AND LICENSE
20719
20720 This software is copyright (c) 2014 by Adam Kennedy and Contributors.
20721
20722 This is free software; you can redistribute it and/or modify it under
20723 the same terms as the Perl 5 programming language system itself.
20724
20725 =cut
20726 PARSE_CPAN_META
20727  
20728 $fatpacked{"Parse/PMFile.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'PARSE_PMFILE';
20729 package Parse::PMFile;
20730
20731 sub __clean_eval { eval $_[0] } # needs to be here (RT#101273)
20732
20733 use strict;
20734 use warnings;
20735 use Safe;
20736 use JSON::PP ();
20737 use Dumpvalue;
20738 use version ();
20739 use File::Spec ();
20740
20741 our $VERSION = '0.36';
20742 our $VERBOSE = 0;
20743 our $ALLOW_DEV_VERSION = 0;
20744 our $FORK = 0;
20745 our $UNSAFE = $] < 5.010000 ? 1 : 0;
20746
20747 sub new {
20748 my ($class, $meta, $opts) = @_;
20749 bless {%{ $opts || {} }, META_CONTENT => $meta}, $class;
20750 }
20751
20752 # from PAUSE::pmfile::examine_fio
20753 sub parse {
20754 my ($self, $pmfile) = @_;
20755
20756 $pmfile =~ s|\\|/|g;
20757
20758 my($filemtime) = (stat $pmfile)[9];
20759 $self->{MTIME} = $filemtime;
20760 $self->{PMFILE} = $pmfile;
20761
20762 unless ($self->_version_from_meta_ok) {
20763 my $version;
20764 unless (eval { $version = $self->_parse_version; 1 }) {
20765 $self->_verbose(1, "error with version in $pmfile: $@");
20766 return;
20767 }
20768
20769 $self->{VERSION} = $version;
20770 if ($self->{VERSION} =~ /^\{.*\}$/) {
20771 # JSON error message
20772 } elsif ($self->{VERSION} =~ /[_\s]/ && !$self->{ALLOW_DEV_VERSION} && !$ALLOW_DEV_VERSION){ # ignore developer releases and "You suck!"
20773 return;
20774 }
20775 }
20776
20777 my($ppp) = $self->_packages_per_pmfile;
20778 my @keys_ppp = $self->_filter_ppps(sort keys %$ppp);
20779 $self->_verbose(1,"Will check keys_ppp[@keys_ppp]\n");
20780
20781 #
20782 # Immediately after each package (pmfile) examined contact
20783 # the database
20784 #
20785
20786 my ($package, %errors);
20787 my %checked_in;
20788 DBPACK: foreach $package (@keys_ppp) {
20789 # this part is taken from PAUSE::package::examine_pkg
20790 # and PAUSE::package::_pkg_name_insane
20791 if ($package !~ /^\w[\w\:\']*\w?\z/
20792 || $package !~ /\w\z/
20793 || $package =~ /:/ && $package !~ /::/
20794 || $package =~ /\w:\w/
20795 || $package =~ /:::/
20796 ){
20797 $self->_verbose(1,"Package[$package] did not pass the ultimate sanity check");
20798 delete $ppp->{$package};
20799 next;
20800 }
20801
20802 if ($self->{USERID} && $self->{PERMISSIONS} && !$self->_perm_check($package)) {
20803 delete $ppp->{$package};
20804 next;
20805 }
20806
20807 # Check that package name matches case of file name
20808 {
20809 my (undef, $module) = split m{/lib/}, $self->{PMFILE}, 2;
20810 if ($module) {
20811 $module =~ s{\.pm\z}{};
20812 $module =~ s{/}{::}g;
20813
20814 if (lc $module eq lc $package && $module ne $package) {
20815 # warn "/// $self->{PMFILE} vs. $module vs. $package\n";
20816 $errors{$package} = {
20817 indexing_warning => "Capitalization of package ($package) does not match filename!",
20818 infile => $self->{PMFILE},
20819 };
20820 }
20821 }
20822 }
20823
20824 my $pp = $ppp->{$package};
20825 if ($pp->{version} && $pp->{version} =~ /^\{.*\}$/) { # JSON parser error
20826 my $err = JSON::PP::decode_json($pp->{version});
20827 if ($err->{x_normalize}) {
20828 $errors{$package} = {
20829 normalize => $err->{version},
20830 infile => $pp->{infile},
20831 };
20832 $pp->{version} = "undef";
20833 } elsif ($err->{openerr}) {
20834 $pp->{version} = "undef";
20835 $self->_verbose(1,
20836 qq{Parse::PMFile was not able to
20837 read the file. It issued the following error: C< $err->{r} >},
20838 );
20839 $errors{$package} = {
20840 open => $err->{r},
20841 infile => $pp->{infile},
20842 };
20843 } else {
20844 $pp->{version} = "undef";
20845 $self->_verbose(1,
20846 qq{Parse::PMFile was not able to
20847 parse the following line in that file: C< $err->{line} >
20848
20849 Note: the indexer is running in a Safe compartement and cannot
20850 provide the full functionality of perl in the VERSION line. It
20851 is trying hard, but sometime it fails. As a workaround, please
20852 consider writing a META.yml that contains a 'provides'
20853 attribute or contact the CPAN admins to investigate (yet
20854 another) workaround against "Safe" limitations.)},
20855
20856 );
20857 $errors{$package} = {
20858 parse_version => $err->{line},
20859 infile => $err->{file},
20860 };
20861 }
20862 }
20863
20864 # Sanity checks
20865
20866 for (
20867 $package,
20868 $pp->{version},
20869 ) {
20870 if (!defined || /^\s*$/ || /\s/){ # for whatever reason I come here
20871 delete $ppp->{$package};
20872 next; # don't screw up 02packages
20873 }
20874 }
20875 $checked_in{$package} = $ppp->{$package};
20876 } # end foreach package
20877
20878 return (wantarray && %errors) ? (\%checked_in, \%errors) : \%checked_in;
20879 }
20880
20881 sub _perm_check {
20882 my ($self, $package) = @_;
20883 my $userid = $self->{USERID};
20884 my $module = $self->{PERMISSIONS}->module_permissions($package);
20885 return 1 if !$module; # not listed yet
20886 return 1 if defined $module->m && $module->m eq $userid;
20887 return 1 if defined $module->f && $module->f eq $userid;
20888 return 1 if defined $module->c && grep {$_ eq $userid} @{$module->c};
20889 return;
20890 }
20891
20892 # from PAUSE::pmfile;
20893 sub _parse_version {
20894 my $self = shift;
20895
20896 use strict;
20897
20898 my $pmfile = $self->{PMFILE};
20899 my $tmpfile = File::Spec->catfile(File::Spec->tmpdir, "ParsePMFile$$" . rand(1000));
20900
20901 my $pmcp = $pmfile;
20902 for ($pmcp) {
20903 s/([^\\](\\\\)*)@/$1\\@/g; # thanks to Raphael Manfredi for the
20904 # solution to escape @s and \
20905 }
20906 my($v);
20907 {
20908
20909 package main; # seems necessary
20910
20911 # XXX: do we need to fork as PAUSE does?
20912 # or, is alarm() just fine?
20913 my $pid;
20914 if ($self->{FORK} || $FORK) {
20915 $pid = fork();
20916 die "Can't fork: $!" unless defined $pid;
20917 }
20918 if ($pid) {
20919 waitpid($pid, 0);
20920 if (open my $fh, '<', $tmpfile) {
20921 $v = <$fh>;
20922 }
20923 } else {
20924 # XXX Limit Resources too
20925
20926 my($comp) = Safe->new;
20927 my $eval = qq{
20928 local(\$^W) = 0;
20929 Parse::PMFile::_parse_version_safely("$pmcp");
20930 };
20931 $comp->permit("entereval"); # for MBARBON/Module-Info-0.30.tar.gz
20932 $comp->share("*Parse::PMFile::_parse_version_safely");
20933 $comp->share("*version::new");
20934 $comp->share("*version::numify");
20935 $comp->share_from('main', ['*version::',
20936 '*charstar::',
20937 '*Exporter::',
20938 '*DynaLoader::']);
20939 $comp->share_from('version', ['&qv']);
20940 $comp->permit(":base_math"); # atan2 (Acme-Pi)
20941 # $comp->permit("require"); # no strict!
20942 $comp->deny(qw/enteriter iter unstack goto/); # minimum protection against Acme::BadExample
20943
20944 version->import('qv') if $self->{UNSAFE} || $UNSAFE;
20945 {
20946 no strict;
20947 $v = ($self->{UNSAFE} || $UNSAFE) ? eval $eval : $comp->reval($eval);
20948 }
20949 if ($@){ # still in the child process, out of Safe::reval
20950 my $err = $@;
20951 # warn ">>>>>>>err[$err]<<<<<<<<";
20952 if (ref $err) {
20953 if ($err->{line} =~ /([\$*])([\w\:\']*)\bVERSION\b.*?\=(.*)/) {
20954 local($^W) = 0;
20955 my ($sigil, $vstr) = ($1, $3);
20956 $self->_restore_overloaded_stuff(1) if $err->{line} =~ /use\s+version\b|version\->|qv\(/;
20957 $v = ($self->{UNSAFE} || $UNSAFE) ? eval $vstr : $comp->reval($vstr);
20958 $v = $$v if $sigil eq '*' && ref $v;
20959 }
20960 if ($@ or !$v) {
20961 $self->_verbose(1, sprintf("reval failed: err[%s] for eval[%s]",
20962 JSON::PP::encode_json($err),
20963 $eval,
20964 ));
20965 $v = JSON::PP::encode_json($err);
20966 }
20967 } else {
20968 $v = JSON::PP::encode_json({ openerr => $err });
20969 }
20970 }
20971 if (defined $v) {
20972 $v = $v->numify if ref($v) =~ /^version(::vpp)?$/;
20973 } else {
20974 $v = "";
20975 }
20976 if ($self->{FORK} || $FORK) {
20977 open my $fh, '>:utf8', $tmpfile;
20978 print $fh $v;
20979 exit 0;
20980 } else {
20981 utf8::encode($v);
20982 # undefine empty $v as if read from the tmpfile
20983 $v = undef if defined $v && !length $v;
20984 $comp->erase;
20985 $self->_restore_overloaded_stuff;
20986 }
20987 }
20988 }
20989 unlink $tmpfile if ($self->{FORK} || $FORK) && -e $tmpfile;
20990
20991 return $self->_normalize_version($v);
20992 }
20993
20994 sub _restore_overloaded_stuff {
20995 my ($self, $used_version_in_safe) = @_;
20996 return if $self->{UNSAFE} || $UNSAFE;
20997
20998 no strict 'refs';
20999 no warnings 'redefine';
21000
21001 # version XS in CPAN
21002 my $restored;
21003 if ($INC{'version/vxs.pm'}) {
21004 *{'version::(""'} = \&version::vxs::stringify;
21005 *{'version::(0+'} = \&version::vxs::numify;
21006 *{'version::(cmp'} = \&version::vxs::VCMP;
21007 *{'version::(<=>'} = \&version::vxs::VCMP;
21008 *{'version::(bool'} = \&version::vxs::boolean;
21009 $restored = 1;
21010 }
21011 # version PP in CPAN
21012 if ($INC{'version/vpp.pm'}) {
21013 {
21014 package # hide from PAUSE
21015 charstar;
21016 overload->import;
21017 }
21018 if (!$used_version_in_safe) {
21019 package # hide from PAUSE
21020 version::vpp;
21021 overload->import;
21022 }
21023 unless ($restored) {
21024 *{'version::(""'} = \&version::vpp::stringify;
21025 *{'version::(0+'} = \&version::vpp::numify;
21026 *{'version::(cmp'} = \&version::vpp::vcmp;
21027 *{'version::(<=>'} = \&version::vpp::vcmp;
21028 *{'version::(bool'} = \&version::vpp::vbool;
21029 }
21030 *{'version::vpp::(""'} = \&version::vpp::stringify;
21031 *{'version::vpp::(0+'} = \&version::vpp::numify;
21032 *{'version::vpp::(cmp'} = \&version::vpp::vcmp;
21033 *{'version::vpp::(<=>'} = \&version::vpp::vcmp;
21034 *{'version::vpp::(bool'} = \&version::vpp::vbool;
21035 *{'charstar::(""'} = \&charstar::thischar;
21036 *{'charstar::(0+'} = \&charstar::thischar;
21037 *{'charstar::(++'} = \&charstar::increment;
21038 *{'charstar::(--'} = \&charstar::decrement;
21039 *{'charstar::(+'} = \&charstar::plus;
21040 *{'charstar::(-'} = \&charstar::minus;
21041 *{'charstar::(*'} = \&charstar::multiply;
21042 *{'charstar::(cmp'} = \&charstar::cmp;
21043 *{'charstar::(<=>'} = \&charstar::spaceship;
21044 *{'charstar::(bool'} = \&charstar::thischar;
21045 *{'charstar::(='} = \&charstar::clone;
21046 $restored = 1;
21047 }
21048 # version in core
21049 if (!$restored) {
21050 *{'version::(""'} = \&version::stringify;
21051 *{'version::(0+'} = \&version::numify;
21052 *{'version::(cmp'} = \&version::vcmp;
21053 *{'version::(<=>'} = \&version::vcmp;
21054 *{'version::(bool'} = \&version::boolean;
21055 }
21056 }
21057
21058 # from PAUSE::pmfile;
21059 sub _packages_per_pmfile {
21060 my $self = shift;
21061
21062 my $ppp = {};
21063 my $pmfile = $self->{PMFILE};
21064 my $filemtime = $self->{MTIME};
21065 my $version = $self->{VERSION};
21066
21067 open my $fh, "<", "$pmfile" or return $ppp;
21068
21069 local $/ = "\n";
21070 my $inpod = 0;
21071
21072 PLINE: while (<$fh>) {
21073 chomp;
21074 my($pline) = $_;
21075 $inpod = $pline =~ /^=(?!cut)/ ? 1 :
21076 $pline =~ /^=cut/ ? 0 : $inpod;
21077 next if $inpod;
21078 next if substr($pline,0,4) eq "=cut";
21079
21080 $pline =~ s/\#.*//;
21081 next if $pline =~ /^\s*$/;
21082 if ($pline =~ /^__(?:END|DATA)__\b/
21083 and $pmfile !~ /\.PL$/ # PL files may well have code after __DATA__
21084 ){
21085 last PLINE;
21086 }
21087
21088 my $pkg;
21089 my $strict_version;
21090
21091 if (
21092 $pline =~ m{
21093 # (.*) # takes too much time if $pline is long
21094 (?<![*\$\\@%&]) # no sigils
21095 \bpackage\s+
21096 ([\w\:\']+)
21097 \s*
21098 (?: $ | [\}\;] | \{ | \s+($version::STRICT) )
21099 }x) {
21100 $pkg = $1;
21101 $strict_version = $2;
21102 if ($pkg eq "DB"){
21103 # XXX if pumpkin and perl make him comaintainer! I
21104 # think I always made the pumpkins comaint on DB
21105 # without further ado (?)
21106 next PLINE;
21107 }
21108 }
21109
21110 if ($pkg) {
21111 # Found something
21112
21113 # from package
21114 $pkg =~ s/\'/::/;
21115 next PLINE unless $pkg =~ /^[A-Za-z]/;
21116 next PLINE unless $pkg =~ /\w$/;
21117 next PLINE if $pkg eq "main";
21118 # Perl::Critic::Policy::TestingAndDebugging::ProhibitShebangWarningsArg
21119 # database for modid in mods, package in packages, package in perms
21120 # alter table mods modify modid varchar(128) binary NOT NULL default '';
21121 # alter table packages modify package varchar(128) binary NOT NULL default '';
21122 next PLINE if length($pkg) > 128;
21123 #restriction
21124 $ppp->{$pkg}{parsed}++;
21125 $ppp->{$pkg}{infile} = $pmfile;
21126 if ($self->_simile($pmfile,$pkg)) {
21127 $ppp->{$pkg}{simile} = $pmfile;
21128 if ($self->_version_from_meta_ok) {
21129 my $provides = $self->{META_CONTENT}{provides};
21130 if (exists $provides->{$pkg}) {
21131 if (defined $provides->{$pkg}{version}) {
21132 my $v = $provides->{$pkg}{version};
21133 if ($v =~ /[_\s]/ && !$self->{ALLOW_DEV_VERSION} && !$ALLOW_DEV_VERSION){ # ignore developer releases and "You suck!"
21134 next PLINE;
21135 }
21136
21137 unless (eval { $version = $self->_normalize_version($v); 1 }) {
21138 $self->_verbose(1, "error with version in $pmfile: $@");
21139 next;
21140
21141 }
21142 $ppp->{$pkg}{version} = $version;
21143 } else {
21144 $ppp->{$pkg}{version} = "undef";
21145 }
21146 }
21147 } else {
21148 if (defined $strict_version){
21149 $ppp->{$pkg}{version} = $strict_version ;
21150 } else {
21151 $ppp->{$pkg}{version} = defined $version ? $version : "";
21152 }
21153 no warnings;
21154 if ($version eq 'undef') {
21155 $ppp->{$pkg}{version} = $version unless defined $ppp->{$pkg}{version};
21156 } else {
21157 $ppp->{$pkg}{version} =
21158 $version
21159 if $version
21160 > $ppp->{$pkg}{version} ||
21161 $version
21162 gt $ppp->{$pkg}{version};
21163 }
21164 }
21165 } else { # not simile
21166 #### it comes later, it would be nonsense
21167 #### to set to "undef". MM_Unix gives us
21168 #### the best we can reasonably consider
21169 $ppp->{$pkg}{version} =
21170 $version
21171 unless defined $ppp->{$pkg}{version} &&
21172 length($ppp->{$pkg}{version});
21173 }
21174 $ppp->{$pkg}{filemtime} = $filemtime;
21175 } else {
21176 # $self->_verbose(2,"no pkg found");
21177 }
21178 }
21179
21180 close $fh;
21181 $ppp;
21182 }
21183
21184 # from PAUSE::pmfile;
21185 {
21186 no strict;
21187 sub _parse_version_safely {
21188 my($parsefile) = @_;
21189 my $result;
21190 local *FH;
21191 local $/ = "\n";
21192 open(FH,$parsefile) or die "Could not open '$parsefile': $!";
21193 my $inpod = 0;
21194 while (<FH>) {
21195 $inpod = /^=(?!cut)/ ? 1 : /^=cut/ ? 0 : $inpod;
21196 next if $inpod || /^\s*#/;
21197 last if /^__(?:END|DATA)__\b/; # fails on quoted __END__ but this is rare -> __END__ in the middle of a line is rarer
21198 chop;
21199
21200 if (my ($ver) = /package \s+ \S+ \s+ (\S+) \s* [;{]/x) {
21201 # XXX: should handle this better if version is bogus -- rjbs,
21202 # 2014-03-16
21203 return $ver if version::is_lax($ver);
21204 }
21205
21206 # next unless /\$(([\w\:\']*)\bVERSION)\b.*\=/;
21207 next unless /(?<!\\)([\$*])(([\w\:\']*)\bVERSION)\b.*(?<![!><=])\=(?![=>])/;
21208 my $current_parsed_line = $_;
21209 my $eval = qq{
21210 package #
21211 ExtUtils::MakeMaker::_version;
21212
21213 local $1$2;
21214 \$$2=undef; do {
21215 $_
21216 }; \$$2
21217 };
21218 local $^W = 0;
21219 local $SIG{__WARN__} = sub {};
21220 $result = __clean_eval($eval);
21221 # warn "current_parsed_line[$current_parsed_line]\$\@[$@]";
21222 if ($@ or !defined $result){
21223 die +{
21224 eval => $eval,
21225 line => $current_parsed_line,
21226 file => $parsefile,
21227 err => $@,
21228 };
21229 }
21230 last;
21231 } #;
21232 close FH;
21233
21234 $result = "undef" unless defined $result;
21235 if ((ref $result) =~ /^version(?:::vpp)?\b/) {
21236 $result = $result->numify;
21237 }
21238 return $result;
21239 }
21240 }
21241
21242 # from PAUSE::pmfile;
21243 sub _filter_ppps {
21244 my($self,@ppps) = @_;
21245 my @res;
21246
21247 # very similar code is in PAUSE::dist::filter_pms
21248 MANI: for my $ppp ( @ppps ) {
21249 if ($self->{META_CONTENT}){
21250 my $no_index = $self->{META_CONTENT}{no_index}
21251 || $self->{META_CONTENT}{private}; # backward compat
21252 if (ref($no_index) eq 'HASH') {
21253 my %map = (
21254 package => qr{\z},
21255 namespace => qr{::},
21256 );
21257 for my $k (qw(package namespace)) {
21258 next unless my $v = $no_index->{$k};
21259 my $rest = $map{$k};
21260 if (ref $v eq "ARRAY") {
21261 for my $ve (@$v) {
21262 $ve =~ s|::$||;
21263 if ($ppp =~ /^$ve$rest/){
21264 $self->_verbose(1,"Skipping ppp[$ppp] due to ve[$ve]");
21265 next MANI;
21266 } else {
21267 $self->_verbose(1,"NOT skipping ppp[$ppp] due to ve[$ve]");
21268 }
21269 }
21270 } else {
21271 $v =~ s|::$||;
21272 if ($ppp =~ /^$v$rest/){
21273 $self->_verbose(1,"Skipping ppp[$ppp] due to v[$v]");
21274 next MANI;
21275 } else {
21276 $self->_verbose(1,"NOT skipping ppp[$ppp] due to v[$v]");
21277 }
21278 }
21279 }
21280 } else {
21281 $self->_verbose(1,"No keyword 'no_index' or 'private' in META_CONTENT");
21282 }
21283 } else {
21284 # $self->_verbose(1,"no META_CONTENT"); # too noisy
21285 }
21286 push @res, $ppp;
21287 }
21288 $self->_verbose(1,"Result of filter_ppps: res[@res]");
21289 @res;
21290 }
21291
21292 # from PAUSE::pmfile;
21293 sub _simile {
21294 my($self,$file,$package) = @_;
21295 # MakeMaker gives them the chance to have the file Simple.pm in
21296 # this directory but have the package HTML::Simple in it.
21297 # Afaik, they wouldn't be able to do so with deeper nested packages
21298 $file =~ s|.*/||;
21299 $file =~ s|\.pm(?:\.PL)?||;
21300 my $ret = $package =~ m/\b\Q$file\E$/;
21301 $ret ||= 0;
21302 unless ($ret) {
21303 # Apache::mod_perl_guide stuffs it into Version.pm
21304 $ret = 1 if lc $file eq 'version';
21305 }
21306 $self->_verbose(1,"Result of simile(): file[$file] package[$package] ret[$ret]\n");
21307 $ret;
21308 }
21309
21310 # from PAUSE::pmfile
21311 sub _normalize_version {
21312 my($self,$v) = @_;
21313 $v = "undef" unless defined $v;
21314 my $dv = Dumpvalue->new;
21315 my $sdv = $dv->stringify($v,1); # second argument prevents ticks
21316 $self->_verbose(1,"Result of normalize_version: sdv[$sdv]\n");
21317
21318 return $v if $v eq "undef";
21319 return $v if $v =~ /^\{.*\}$/; # JSON object
21320 $v =~ s/^\s+//;
21321 $v =~ s/\s+\z//;
21322 if ($v =~ /_/) {
21323 # XXX should pass something like EDEVELOPERRELEASE up e.g.
21324 # SIXTEASE/XML-Entities-0.0306.tar.gz had nothing but one
21325 # such modules and the mesage was not helpful that "nothing
21326 # was found".
21327 return $v ;
21328 }
21329 if (!version::is_lax($v)) {
21330 return JSON::PP::encode_json({ x_normalize => 'version::is_lax failed', version => $v });
21331 }
21332 # may warn "Integer overflow"
21333 my $vv = eval { no warnings; version->new($v)->numify };
21334 if ($@) {
21335 # warn "$v: $@";
21336 return JSON::PP::encode_json({ x_normalize => $@, version => $v });
21337 # return "undef";
21338 }
21339 if ($vv eq $v) {
21340 # the boring 3.14
21341 } else {
21342 my $forced = $self->_force_numeric($v);
21343 if ($forced eq $vv) {
21344 } elsif ($forced =~ /^v(.+)/) {
21345 # rare case where a v1.0.23 slipped in (JANL/w3mir-1.0.10.tar.gz)
21346 $vv = version->new($1)->numify;
21347 } else {
21348 # warn "Unequal forced[$forced] and vv[$vv]";
21349 if ($forced == $vv) {
21350 # the trailing zeroes would cause unnecessary havoc
21351 $vv = $forced;
21352 }
21353 }
21354 }
21355 return $vv;
21356 }
21357
21358 # from PAUSE::pmfile;
21359 sub _force_numeric {
21360 my($self,$v) = @_;
21361 $v = $self->_readable($v);
21362
21363 if (
21364 $v =~
21365 /^(\+?)(\d*)(\.(\d*))?/ &&
21366 # "$2$4" ne ''
21367 (
21368 defined $2 && length $2
21369 ||
21370 defined $4 && length $4
21371 )
21372 ) {
21373 my $two = defined $2 ? $2 : "";
21374 my $three = defined $3 ? $3 : "";
21375 $v = "$two$three";
21376 }
21377 # no else branch! We simply say, everything else is a string.
21378 $v;
21379 }
21380
21381 # from PAUSE::dist
21382 sub _version_from_meta_ok {
21383 my($self) = @_;
21384 return $self->{VERSION_FROM_META_OK} if exists $self->{VERSION_FROM_META_OK};
21385 my $c = $self->{META_CONTENT};
21386
21387 # If there's no provides hash, we can't get our module versions from the
21388 # provides hash! -- rjbs, 2012-03-31
21389 return($self->{VERSION_FROM_META_OK} = 0) unless $c->{provides};
21390
21391 # Some versions of Module::Build geneated an empty provides hash. If we're
21392 # *not* looking at a Module::Build-generated metafile, then it's okay.
21393 my ($mb_v) = (defined $c->{generated_by} ? $c->{generated_by} : '') =~ /Module::Build version ([\d\.]+)/;
21394 return($self->{VERSION_FROM_META_OK} = 1) unless $mb_v;
21395
21396 # ??? I don't know why this is here.
21397 return($self->{VERSION_FROM_META_OK} = 1) if $mb_v eq '0.250.0';
21398
21399 if ($mb_v >= 0.19 && $mb_v < 0.26 && ! keys %{$c->{provides}}) {
21400 # RSAVAGE/Javascript-SHA1-1.01.tgz had an empty provides hash. Ron
21401 # did not find the reason why this happened, but let's not go
21402 # overboard, 0.26 seems a good threshold from the statistics: there
21403 # are not many empty provides hashes from 0.26 up.
21404 return($self->{VERSION_FROM_META_OK} = 0);
21405 }
21406
21407 # We're not in the suspect range of M::B versions. It's good to go.
21408 return($self->{VERSION_FROM_META_OK} = 1);
21409 }
21410
21411 sub _verbose {
21412 my($self,$level,@what) = @_;
21413 warn @what if $level <= ((ref $self && $self->{VERBOSE}) || $VERBOSE);
21414 }
21415
21416 # all of the following methods are stripped from CPAN::Version
21417 # (as of version 5.5001, bundled in CPAN 2.03), and slightly
21418 # modified (ie. made private, as well as CPAN->debug(...) are
21419 # replaced with $self->_verbose(9, ...).)
21420
21421 # CPAN::Version::vcmp courtesy Jost Krieger
21422 sub _vcmp {
21423 my($self,$l,$r) = @_;
21424 local($^W) = 0;
21425 $self->_verbose(9, "l[$l] r[$r]");
21426
21427 return 0 if $l eq $r; # short circuit for quicker success
21428
21429 for ($l,$r) {
21430 s/_//g;
21431 }
21432 $self->_verbose(9, "l[$l] r[$r]");
21433 for ($l,$r) {
21434 next unless tr/.// > 1 || /^v/;
21435 s/^v?/v/;
21436 1 while s/\.0+(\d)/.$1/; # remove leading zeroes per group
21437 }
21438 $self->_verbose(9, "l[$l] r[$r]");
21439 if ($l=~/^v/ <=> $r=~/^v/) {
21440 for ($l,$r) {
21441 next if /^v/;
21442 $_ = $self->_float2vv($_);
21443 }
21444 }
21445 $self->_verbose(9, "l[$l] r[$r]");
21446 my $lvstring = "v0";
21447 my $rvstring = "v0";
21448 if ($] >= 5.006
21449 && $l =~ /^v/
21450 && $r =~ /^v/) {
21451 $lvstring = $self->_vstring($l);
21452 $rvstring = $self->_vstring($r);
21453 $self->_verbose(9, sprintf "lv[%vd] rv[%vd]", $lvstring, $rvstring);
21454 }
21455
21456 return (
21457 ($l ne "undef") <=> ($r ne "undef")
21458 ||
21459 $lvstring cmp $rvstring
21460 ||
21461 $l <=> $r
21462 ||
21463 $l cmp $r
21464 );
21465 }
21466
21467 sub _vgt {
21468 my($self,$l,$r) = @_;
21469 $self->_vcmp($l,$r) > 0;
21470 }
21471
21472 sub _vlt {
21473 my($self,$l,$r) = @_;
21474 $self->_vcmp($l,$r) < 0;
21475 }
21476
21477 sub _vge {
21478 my($self,$l,$r) = @_;
21479 $self->_vcmp($l,$r) >= 0;
21480 }
21481
21482 sub _vle {
21483 my($self,$l,$r) = @_;
21484 $self->_vcmp($l,$r) <= 0;
21485 }
21486
21487 sub _vstring {
21488 my($self,$n) = @_;
21489 $n =~ s/^v// or die "Parse::PMFile::_vstring() called with invalid arg [$n]";
21490 pack "U*", split /\./, $n;
21491 }
21492
21493 # vv => visible vstring
21494 sub _float2vv {
21495 my($self,$n) = @_;
21496 my($rev) = int($n);
21497 $rev ||= 0;
21498 my($mantissa) = $n =~ /\.(\d{1,12})/; # limit to 12 digits to limit
21499 # architecture influence
21500 $mantissa ||= 0;
21501 $mantissa .= "0" while length($mantissa)%3;
21502 my $ret = "v" . $rev;
21503 while ($mantissa) {
21504 $mantissa =~ s/(\d{1,3})// or
21505 die "Panic: length>0 but not a digit? mantissa[$mantissa]";
21506 $ret .= ".".int($1);
21507 }
21508 # warn "n[$n]ret[$ret]";
21509 $ret =~ s/(\.0)+/.0/; # v1.0.0 => v1.0
21510 $ret;
21511 }
21512
21513 sub _readable {
21514 my($self,$n) = @_;
21515 $n =~ /^([\w\-\+\.]+)/;
21516
21517 return $1 if defined $1 && length($1)>0;
21518 # if the first user reaches version v43, he will be treated as "+".
21519 # We'll have to decide about a new rule here then, depending on what
21520 # will be the prevailing versioning behavior then.
21521
21522 if ($] < 5.006) { # or whenever v-strings were introduced
21523 # we get them wrong anyway, whatever we do, because 5.005 will
21524 # have already interpreted 0.2.4 to be "0.24". So even if he
21525 # indexer sends us something like "v0.2.4" we compare wrongly.
21526
21527 # And if they say v1.2, then the old perl takes it as "v12"
21528
21529 $self->_verbose(9, "Suspicious version string seen [$n]\n");
21530 return $n;
21531 }
21532 my $better = sprintf "v%vd", $n;
21533 $self->_verbose(9, "n[$n] better[$better]");
21534 return $better;
21535 }
21536
21537 1;
21538
21539 __END__
21540
21541 =head1 NAME
21542
21543 Parse::PMFile - parses .pm file as PAUSE does
21544
21545 =head1 SYNOPSIS
21546
21547 use Parse::PMFile;
21548
21549 my $parser = Parse::PMFile->new($metadata, {VERBOSE => 1});
21550 my $packages_info = $parser->parse($pmfile);
21551
21552 # if you need info about invalid versions
21553 my ($packages_info, $errors) = $parser->parse($pmfile);
21554
21555 # to check permissions
21556 my $parser = Parse::PMFile->new($metadata, {
21557 USERID => 'ISHIGAKI',
21558 PERMISSIONS => PAUSE::Permissions->new,
21559 });
21560
21561 =head1 DESCRIPTION
21562
21563 The most of the code of this module is taken from the PAUSE code as of April 2013 almost verbatim. Thus, the heart of this module should be quite stable. However, I made it not to use pipe ("-|") as well as I stripped database-related code. If you encounter any issue, that's most probably because of my modification.
21564
21565 This module doesn't provide features to extract a distribution or parse meta files intentionally.
21566
21567 =head1 METHODS
21568
21569 =head2 new
21570
21571 creates an object. You can also pass a hashref taken from META.yml etc, and an optional hashref. Options are:
21572
21573 =over 4
21574
21575 =item ALLOW_DEV_VERSION
21576
21577 Parse::PMFile usually ignores a version with an underscore as PAUSE does (because it's for a developer release, and should not be indexed). Set this option to true if you happen to need to keep such a version for better analysis.
21578
21579 =item VERBOSE
21580
21581 Set this to true if you need to know some details.
21582
21583 =item FORK
21584
21585 As of version 0.17, Parse::PMFile stops forking while parsing a version for better performance. Parse::PMFile should return the same result no matter how this option is set, but if you do care, set this to true to fork as PAUSE does.
21586
21587 =item USERID, PERMISSIONS
21588
21589 As of version 0.21, Parse::PMFile checks permissions of a package if both USERID and PERMISSIONS (which should be an instance of L<PAUSE::Permissions>) are provided. Unauthorized packages are removed.
21590
21591 =item UNSAFE
21592
21593 Parse::PMFile usually parses a module version in a Safe compartment. However, this approach doesn't work smoothly under older perls (prior to 5.10) plus some combinations of recent versions of Safe.pm (2.24 and above) and version.pm (0.9905 and above) for various reasons. As of version 0.27, Parse::PMFile simply uses C<eval> to parse a version under older perls. If you want it to use always C<eval> (even under recent perls), set this to true.
21594
21595 =back
21596
21597 =head2 parse
21598
21599 takes a path to a .pm file, and returns a hash reference that holds information for package(s) found in the file.
21600
21601 =head1 SEE ALSO
21602
21603 L<Parse::LocalDistribution>, L<PAUSE::Permissions>
21604
21605 Most part of this module is derived from PAUSE and CPAN::Version.
21606
21607 L<https://github.com/andk/pause>
21608
21609 L<https://github.com/andk/cpanpm>
21610
21611 =head1 AUTHOR
21612
21613 Andreas Koenig E<lt>andreas.koenig@anima.deE<gt>
21614
21615 Kenichi Ishigaki, E<lt>ishigaki@cpan.orgE<gt>
21616
21617 =head1 COPYRIGHT AND LICENSE
21618
21619 Copyright 1995 - 2013 by Andreas Koenig E<lt>andk@cpan.orgE<gt> for most of the code.
21620
21621 Copyright 2013 by Kenichi Ishigaki for some.
21622
21623 This program is free software; you can redistribute it and/or
21624 modify it under the same terms as Perl itself.
21625
21626 =cut
21627 PARSE_PMFILE
21628  
21629 $fatpacked{"String/ShellQuote.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'STRING_SHELLQUOTE';
21630 # $Id: ShellQuote.pm,v 1.11 2010-06-11 20:08:57 roderick Exp $
21631 #
21632 # Copyright (c) 1997 Roderick Schertler. All rights reserved. This
21633 # program is free software; you can redistribute it and/or modify it
21634 # under the same terms as Perl itself.
21635
21636 =head1 NAME
21637
21638 String::ShellQuote - quote strings for passing through the shell
21639
21640 =head1 SYNOPSIS
21641
21642 $string = shell_quote @list;
21643 $string = shell_quote_best_effort @list;
21644 $string = shell_comment_quote $string;
21645
21646 =head1 DESCRIPTION
21647
21648 This module contains some functions which are useful for quoting strings
21649 which are going to pass through the shell or a shell-like object.
21650
21651 =over
21652
21653 =cut
21654
21655 package String::ShellQuote;
21656
21657 use strict;
21658 use vars qw($VERSION @ISA @EXPORT);
21659
21660 require Exporter;
21661
21662 $VERSION = '1.04';
21663 @ISA = qw(Exporter);
21664 @EXPORT = qw(shell_quote shell_quote_best_effort shell_comment_quote);
21665
21666 sub croak {
21667 require Carp;
21668 goto &Carp::croak;
21669 }
21670
21671 sub _shell_quote_backend {
21672 my @in = @_;
21673 my @err = ();
21674
21675 if (0) {
21676 require RS::Handy;
21677 print RS::Handy::data_dump(\@in);
21678 }
21679
21680 return \@err, '' unless @in;
21681
21682 my $ret = '';
21683 my $saw_non_equal = 0;
21684 foreach (@in) {
21685 if (!defined $_ or $_ eq '') {
21686 $_ = "''";
21687 next;
21688 }
21689
21690 if (s/\x00//g) {
21691 push @err, "No way to quote string containing null (\\000) bytes";
21692 }
21693
21694 my $escape = 0;
21695
21696 # = needs quoting when it's the first element (or part of a
21697 # series of such elements), as in command position it's a
21698 # program-local environment setting
21699
21700 if (/=/) {
21701 if (!$saw_non_equal) {
21702 $escape = 1;
21703 }
21704 }
21705 else {
21706 $saw_non_equal = 1;
21707 }
21708
21709 if (m|[^\w!%+,\-./:=@^]|) {
21710 $escape = 1;
21711 }
21712
21713 if ($escape
21714 || (!$saw_non_equal && /=/)) {
21715
21716 # ' -> '\''
21717 s/'/'\\''/g;
21718
21719 # make multiple ' in a row look simpler
21720 # '\'''\'''\'' -> '"'''"'
21721 s|((?:'\\''){2,})|q{'"} . (q{'} x (length($1) / 4)) . q{"'}|ge;
21722
21723 $_ = "'$_'";
21724 s/^''//;
21725 s/''$//;
21726 }
21727 }
21728 continue {
21729 $ret .= "$_ ";
21730 }
21731
21732 chop $ret;
21733 return \@err, $ret;
21734 }
21735
21736 =item B<shell_quote> [I<string>]...
21737
21738 B<shell_quote> quotes strings so they can be passed through the shell.
21739 Each I<string> is quoted so that the shell will pass it along as a
21740 single argument and without further interpretation. If no I<string>s
21741 are given an empty string is returned.
21742
21743 If any I<string> can't be safely quoted B<shell_quote> will B<croak>.
21744
21745 =cut
21746
21747 sub shell_quote {
21748 my ($rerr, $s) = _shell_quote_backend @_;
21749
21750 if (@$rerr) {
21751 my %seen;
21752 @$rerr = grep { !$seen{$_}++ } @$rerr;
21753 my $s = join '', map { "shell_quote(): $_\n" } @$rerr;
21754 chomp $s;
21755 croak $s;
21756 }
21757 return $s;
21758 }
21759
21760 =item B<shell_quote_best_effort> [I<string>]...
21761
21762 This is like B<shell_quote>, excpet if the string can't be safely quoted
21763 it does the best it can and returns the result, instead of dying.
21764
21765 =cut
21766
21767 sub shell_quote_best_effort {
21768 my ($rerr, $s) = _shell_quote_backend @_;
21769
21770 return $s;
21771 }
21772
21773 =item B<shell_comment_quote> [I<string>]
21774
21775 B<shell_comment_quote> quotes the I<string> so that it can safely be
21776 included in a shell-style comment (the current algorithm is that a sharp
21777 character is placed after any newlines in the string).
21778
21779 This routine might be changed to accept multiple I<string> arguments
21780 in the future. I haven't done this yet because I'm not sure if the
21781 I<string>s should be joined with blanks ($") or nothing ($,). Cast
21782 your vote today! Be sure to justify your answer.
21783
21784 =cut
21785
21786 sub shell_comment_quote {
21787 return '' unless @_;
21788 unless (@_ == 1) {
21789 croak "Too many arguments to shell_comment_quote "
21790 . "(got " . @_ . " expected 1)";
21791 }
21792 local $_ = shift;
21793 s/\n/\n#/g;
21794 return $_;
21795 }
21796
21797 1;
21798
21799 __END__
21800
21801 =back
21802
21803 =head1 EXAMPLES
21804
21805 $cmd = 'fuser 2>/dev/null ' . shell_quote @files;
21806 @pids = split ' ', `$cmd`;
21807
21808 print CFG "# Configured by: ",
21809 shell_comment_quote($ENV{LOGNAME}), "\n";
21810
21811 =head1 BUGS
21812
21813 Only Bourne shell quoting is supported. I'd like to add other shells
21814 (particularly cmd.exe), but I'm not familiar with them. It would be a
21815 big help if somebody supplied the details.
21816
21817 =head1 AUTHOR
21818
21819 Roderick Schertler <F<roderick@argon.org>>
21820
21821 =head1 SEE ALSO
21822
21823 perl(1).
21824
21825 =cut
21826 STRING_SHELLQUOTE
21827  
21828 $fatpacked{"lib/core/only.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LIB_CORE_ONLY';
21829 package lib::core::only;
21830
21831 use strict;
21832 use warnings FATAL => 'all';
21833 use Config;
21834
21835 sub import {
21836 @INC = @Config{qw(privlibexp archlibexp)};
21837 return
21838 }
21839
21840 =head1 NAME
21841
21842 lib::core::only - Remove all non-core paths from @INC to avoid site/vendor dirs
21843
21844 =head1 SYNOPSIS
21845
21846 use lib::core::only; # now @INC contains only the two core directories
21847
21848 To get only the core directories plus the ones for the local::lib in scope:
21849
21850 $ perl -mlocal::lib -Mlib::core::only -Mlocal::lib=~/perl5 myscript.pl
21851
21852 To attempt to do a self-contained build (but note this will not reliably
21853 propagate into subprocesses, see the CAVEATS below):
21854
21855 $ PERL5OPT='-mlocal::lib -Mlib::core::only -Mlocal::lib=~/perl5' cpan
21856
21857 Please note that it is necessary to use C<local::lib> twice for this to work.
21858 First so that C<lib::core::only> doesn't prevent C<local::lib> from loading
21859 (it's not currently in core) and then again after C<lib::core::only> so that
21860 the local paths are not removed.
21861
21862 =head1 DESCRIPTION
21863
21864 lib::core::only is simply a shortcut to say "please reduce my @INC to only
21865 the core lib and archlib (architecture-specific lib) directories of this perl".
21866
21867 You might want to do this to ensure a local::lib contains only the code you
21868 need, or to test an L<App::FatPacker|App::FatPacker> tree, or to avoid known
21869 bad vendor packages.
21870
21871 You might want to use this to try and install a self-contained tree of perl
21872 modules. Be warned that that probably won't work (see L</CAVEATS>).
21873
21874 This module was extracted from L<local::lib|local::lib>'s --self-contained
21875 feature, and contains the only part that ever worked. I apologise to anybody
21876 who thought anything else did.
21877
21878 =head1 CAVEATS
21879
21880 This does B<not> propagate properly across perl invocations like local::lib's
21881 stuff does. It can't. It's only a module import, so it B<only affects the
21882 specific perl VM instance in which you load and import() it>.
21883
21884 If you want to cascade it across invocations, you can set the PERL5OPT
21885 environment variable to '-Mlib::core::only' and it'll sort of work. But be
21886 aware that taint mode ignores this, so some modules' build and test code
21887 probably will as well.
21888
21889 You also need to be aware that perl's command line options are not processed
21890 in order - -I options take effect before -M options, so
21891
21892 perl -Mlib::core::only -Ilib
21893
21894 is unlike to do what you want - it's exactly equivalent to:
21895
21896 perl -Mlib::core::only
21897
21898 If you want to combine a core-only @INC with additional paths, you need to
21899 add the additional paths using -M options and the L<lib|lib> module:
21900
21901 perl -Mlib::core::only -Mlib=lib
21902
21903 # or if you're trying to test compiled code:
21904
21905 perl -Mlib::core::only -Mblib
21906
21907 For more information on the impossibility of sanely propagating this across
21908 module builds without help from the build program, see
21909 L<http://www.shadowcat.co.uk/blog/matt-s-trout/tainted-love> - and for ways
21910 to achieve the old --self-contained feature's results, look at
21911 L<App::FatPacker|App::FatPacker>'s tree function, and at
21912 L<App::cpanminus|cpanm>'s --local-lib-contained feature.
21913
21914 =head1 AUTHOR
21915
21916 Matt S. Trout <mst@shadowcat.co.uk>
21917
21918 =head1 LICENSE
21919
21920 This library is free software under the same terms as perl itself.
21921
21922 =head1 COPYRIGHT
21923
21924 (c) 2010 the lib::core::only L</AUTHOR> as specified above.
21925
21926 =cut
21927
21928 1;
21929 LIB_CORE_ONLY
21930  
21931 $fatpacked{"local/lib.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LOCAL_LIB';
21932 package local::lib;
21933 use 5.006;
21934 use strict;
21935 use warnings;
21936 use Config;
21937
21938 our $VERSION = '2.000015';
21939 $VERSION = eval $VERSION;
21940
21941 BEGIN {
21942 *_WIN32 = ($^O eq 'MSWin32' || $^O eq 'NetWare' || $^O eq 'symbian')
21943 ? sub(){1} : sub(){0};
21944 # punt on these systems
21945 *_USE_FSPEC = ($^O eq 'MacOS' || $^O eq 'VMS' || $INC{'File/Spec.pm'})
21946 ? sub(){1} : sub(){0};
21947 }
21948 our $_DIR_JOIN = _WIN32 ? '\\' : '/';
21949 our $_DIR_SPLIT = (_WIN32 || $^O eq 'cygwin') ? qr{[\\/]}
21950 : qr{/};
21951 our $_ROOT = _WIN32 ? do {
21952 my $UNC = qr{[\\/]{2}[^\\/]+[\\/][^\\/]+};
21953 qr{^(?:$UNC|[A-Za-z]:|)$_DIR_SPLIT};
21954 } : qr{^/};
21955 our $_PERL;
21956
21957 sub _cwd {
21958 my $drive = shift;
21959 if (!$_PERL) {
21960 ($_PERL) = $^X =~ /(.+)/; # $^X is internal how could it be tainted?!
21961 if (_is_abs($_PERL)) {
21962 }
21963 elsif (-x $Config{perlpath}) {
21964 $_PERL = $Config{perlpath};
21965 }
21966 else {
21967 ($_PERL) =
21968 map { /(.*)/ }
21969 grep { -x $_ }
21970 map { join($_DIR_JOIN, $_, $_PERL) }
21971 split /\Q$Config{path_sep}\E/, $ENV{PATH};
21972 }
21973 }
21974 local @ENV{qw(PATH IFS CDPATH ENV BASH_ENV)};
21975 my $cmd = $drive ? "eval { Cwd::getdcwd(q($drive)) }"
21976 : 'getcwd';
21977 my $cwd = `"$_PERL" -MCwd -le "print $cmd"`;
21978 chomp $cwd;
21979 if (!length $cwd && $drive) {
21980 $cwd = $drive;
21981 }
21982 $cwd =~ s/$_DIR_SPLIT?$/$_DIR_JOIN/;
21983 $cwd;
21984 }
21985
21986 sub _catdir {
21987 if (_USE_FSPEC) {
21988 require File::Spec;
21989 File::Spec->catdir(@_);
21990 }
21991 else {
21992 my $dir = join($_DIR_JOIN, @_);
21993 $dir =~ s{($_DIR_SPLIT)(?:\.?$_DIR_SPLIT)+}{$1}g;
21994 $dir;
21995 }
21996 }
21997
21998 sub _is_abs {
21999 if (_USE_FSPEC) {
22000 require File::Spec;
22001 File::Spec->file_name_is_absolute($_[0]);
22002 }
22003 else {
22004 $_[0] =~ $_ROOT;
22005 }
22006 }
22007
22008 sub _rel2abs {
22009 my ($dir, $base) = @_;
22010 return $dir
22011 if _is_abs($dir);
22012
22013 $base = _WIN32 && $dir =~ s/^([A-Za-z]:)// ? _cwd("$1")
22014 : $base ? $base
22015 : _cwd;
22016 return _catdir($base, $dir);
22017 }
22018
22019 sub import {
22020 my ($class, @args) = @_;
22021 push @args, @ARGV
22022 if $0 eq '-';
22023
22024 my @steps;
22025 my %opts;
22026 my $shelltype;
22027
22028 while (@args) {
22029 my $arg = shift @args;
22030 # check for lethal dash first to stop processing before causing problems
22031 # the fancy dash is U+2212 or \xE2\x88\x92
22032 if ($arg =~ /\xE2\x88\x92/ or $arg =~ /−/) {
22033 die <<'DEATH';
22034 WHOA THERE! It looks like you've got some fancy dashes in your commandline!
22035 These are *not* the traditional -- dashes that software recognizes. You
22036 probably got these by copy-pasting from the perldoc for this module as
22037 rendered by a UTF8-capable formatter. This most typically happens on an OS X
22038 terminal, but can happen elsewhere too. Please try again after replacing the
22039 dashes with normal minus signs.
22040 DEATH
22041 }
22042 elsif ($arg eq '--self-contained') {
22043 die <<'DEATH';
22044 FATAL: The local::lib --self-contained flag has never worked reliably and the
22045 original author, Mark Stosberg, was unable or unwilling to maintain it. As
22046 such, this flag has been removed from the local::lib codebase in order to
22047 prevent misunderstandings and potentially broken builds. The local::lib authors
22048 recommend that you look at the lib::core::only module shipped with this
22049 distribution in order to create a more robust environment that is equivalent to
22050 what --self-contained provided (although quite possibly not what you originally
22051 thought it provided due to the poor quality of the documentation, for which we
22052 apologise).
22053 DEATH
22054 }
22055 elsif( $arg =~ /^--deactivate(?:=(.*))?$/ ) {
22056 my $path = defined $1 ? $1 : shift @args;
22057 push @steps, ['deactivate', $path];
22058 }
22059 elsif ( $arg eq '--deactivate-all' ) {
22060 push @steps, ['deactivate_all'];
22061 }
22062 elsif ( $arg =~ /^--shelltype(?:=(.*))?$/ ) {
22063 $shelltype = defined $1 ? $1 : shift @args;
22064 }
22065 elsif ( $arg eq '--no-create' ) {
22066 $opts{no_create} = 1;
22067 }
22068 elsif ( $arg =~ /^--/ ) {
22069 die "Unknown import argument: $arg";
22070 }
22071 else {
22072 push @steps, ['activate', $arg];
22073 }
22074 }
22075 if (!@steps) {
22076 push @steps, ['activate', undef];
22077 }
22078
22079 my $self = $class->new(%opts);
22080
22081 for (@steps) {
22082 my ($method, @args) = @$_;
22083 $self = $self->$method(@args);
22084 }
22085
22086 if ($0 eq '-') {
22087 print $self->environment_vars_string($shelltype);
22088 exit 0;
22089 }
22090 else {
22091 $self->setup_local_lib;
22092 }
22093 }
22094
22095 sub new {
22096 my $class = shift;
22097 bless {@_}, $class;
22098 }
22099
22100 sub clone {
22101 my $self = shift;
22102 bless {%$self, @_}, ref $self;
22103 }
22104
22105 sub inc { $_[0]->{inc} ||= \@INC }
22106 sub libs { $_[0]->{libs} ||= [ \'PERL5LIB' ] }
22107 sub bins { $_[0]->{bins} ||= [ \'PATH' ] }
22108 sub roots { $_[0]->{roots} ||= [ \'PERL_LOCAL_LIB_ROOT' ] }
22109 sub extra { $_[0]->{extra} ||= {} }
22110 sub no_create { $_[0]->{no_create} }
22111
22112 my $_archname = $Config{archname};
22113 my $_version = $Config{version};
22114 my @_inc_version_list = reverse split / /, $Config{inc_version_list};
22115 my $_path_sep = $Config{path_sep};
22116
22117 sub _as_list {
22118 my $list = shift;
22119 grep length, map {
22120 !(ref $_ && ref $_ eq 'SCALAR') ? $_ : (
22121 defined $ENV{$$_} ? split(/\Q$_path_sep/, $ENV{$$_})
22122 : ()
22123 )
22124 } ref $list ? @$list : $list;
22125 }
22126 sub _remove_from {
22127 my ($list, @remove) = @_;
22128 return @$list
22129 if !@remove;
22130 my %remove = map { $_ => 1 } @remove;
22131 grep !$remove{$_}, _as_list($list);
22132 }
22133
22134 my @_lib_subdirs = (
22135 [$_version, $_archname],
22136 [$_version],
22137 [$_archname],
22138 (@_inc_version_list ? \@_inc_version_list : ()),
22139 [],
22140 );
22141
22142 sub install_base_bin_path {
22143 my ($class, $path) = @_;
22144 return _catdir($path, 'bin');
22145 }
22146 sub install_base_perl_path {
22147 my ($class, $path) = @_;
22148 return _catdir($path, 'lib', 'perl5');
22149 }
22150 sub install_base_arch_path {
22151 my ($class, $path) = @_;
22152 _catdir($class->install_base_perl_path($path), $_archname);
22153 }
22154
22155 sub lib_paths_for {
22156 my ($class, $path) = @_;
22157 my $base = $class->install_base_perl_path($path);
22158 return map { _catdir($base, @$_) } @_lib_subdirs;
22159 }
22160
22161 sub _mm_escape_path {
22162 my $path = shift;
22163 $path =~ s/\\/\\\\/g;
22164 if ($path =~ s/ /\\ /g) {
22165 $path = qq{"$path"};
22166 }
22167 return $path;
22168 }
22169
22170 sub _mb_escape_path {
22171 my $path = shift;
22172 $path =~ s/\\/\\\\/g;
22173 return qq{"$path"};
22174 }
22175
22176 sub installer_options_for {
22177 my ($class, $path) = @_;
22178 return (
22179 PERL_MM_OPT =>
22180 defined $path ? "INSTALL_BASE="._mm_escape_path($path) : undef,
22181 PERL_MB_OPT =>
22182 defined $path ? "--install_base "._mb_escape_path($path) : undef,
22183 );
22184 }
22185
22186 sub active_paths {
22187 my ($self) = @_;
22188 $self = ref $self ? $self : $self->new;
22189
22190 return grep {
22191 # screen out entries that aren't actually reflected in @INC
22192 my $active_ll = $self->install_base_perl_path($_);
22193 grep { $_ eq $active_ll } @{$self->inc};
22194 } _as_list($self->roots);
22195 }
22196
22197
22198 sub deactivate {
22199 my ($self, $path) = @_;
22200 $self = $self->new unless ref $self;
22201 $path = $self->resolve_path($path);
22202 $path = $self->normalize_path($path);
22203
22204 my @active_lls = $self->active_paths;
22205
22206 if (!grep { $_ eq $path } @active_lls) {
22207 warn "Tried to deactivate inactive local::lib '$path'\n";
22208 return $self;
22209 }
22210
22211 my %args = (
22212 bins => [ _remove_from($self->bins,
22213 $self->install_base_bin_path($path)) ],
22214 libs => [ _remove_from($self->libs,
22215 $self->install_base_perl_path($path)) ],
22216 inc => [ _remove_from($self->inc,
22217 $self->lib_paths_for($path)) ],
22218 roots => [ _remove_from($self->roots, $path) ],
22219 );
22220
22221 $args{extra} = { $self->installer_options_for($args{roots}[0]) };
22222
22223 $self->clone(%args);
22224 }
22225
22226 sub deactivate_all {
22227 my ($self) = @_;
22228 $self = $self->new unless ref $self;
22229
22230 my @active_lls = $self->active_paths;
22231
22232 my %args;
22233 if (@active_lls) {
22234 %args = (
22235 bins => [ _remove_from($self->bins,
22236 map $self->install_base_bin_path($_), @active_lls) ],
22237 libs => [ _remove_from($self->libs,
22238 map $self->install_base_perl_path($_), @active_lls) ],
22239 inc => [ _remove_from($self->inc,
22240 map $self->lib_paths_for($_), @active_lls) ],
22241 roots => [ _remove_from($self->roots, @active_lls) ],
22242 );
22243 }
22244
22245 $args{extra} = { $self->installer_options_for(undef) };
22246
22247 $self->clone(%args);
22248 }
22249
22250 sub activate {
22251 my ($self, $path) = @_;
22252 $self = $self->new unless ref $self;
22253 $path = $self->resolve_path($path);
22254 $self->ensure_dir_structure_for($path)
22255 unless $self->no_create;
22256
22257 $path = $self->normalize_path($path);
22258
22259 my @active_lls = $self->active_paths;
22260
22261 if (grep { $_ eq $path } @active_lls[1 .. $#active_lls]) {
22262 $self = $self->deactivate($path);
22263 }
22264
22265 my %args;
22266 if (!@active_lls || $active_lls[0] ne $path) {
22267 %args = (
22268 bins => [ $self->install_base_bin_path($path), @{$self->bins} ],
22269 libs => [ $self->install_base_perl_path($path), @{$self->libs} ],
22270 inc => [ $self->lib_paths_for($path), @{$self->inc} ],
22271 roots => [ $path, @{$self->roots} ],
22272 );
22273 }
22274
22275 $args{extra} = { $self->installer_options_for($path) };
22276
22277 $self->clone(%args);
22278 }
22279
22280 sub normalize_path {
22281 my ($self, $path) = @_;
22282 $path = ( Win32::GetShortPathName($path) || $path )
22283 if $^O eq 'MSWin32';
22284 return $path;
22285 }
22286
22287 sub build_environment_vars_for {
22288 my $self = $_[0]->new->activate($_[1]);
22289 $self->build_environment_vars;
22290 }
22291 sub build_activate_environment_vars_for {
22292 my $self = $_[0]->new->activate($_[1]);
22293 $self->build_environment_vars;
22294 }
22295 sub build_deactivate_environment_vars_for {
22296 my $self = $_[0]->new->deactivate($_[1]);
22297 $self->build_environment_vars;
22298 }
22299 sub build_deact_all_environment_vars_for {
22300 my $self = $_[0]->new->deactivate_all;
22301 $self->build_environment_vars;
22302 }
22303 sub build_environment_vars {
22304 my $self = shift;
22305 (
22306 PATH => join($_path_sep, _as_list($self->bins)),
22307 PERL5LIB => join($_path_sep, _as_list($self->libs)),
22308 PERL_LOCAL_LIB_ROOT => join($_path_sep, _as_list($self->roots)),
22309 %{$self->extra},
22310 );
22311 }
22312
22313 sub setup_local_lib_for {
22314 my $self = $_[0]->new->activate($_[1]);
22315 $self->setup_local_lib;
22316 }
22317
22318 sub setup_local_lib {
22319 my $self = shift;
22320
22321 # if Carp is already loaded, ensure Carp::Heavy is also loaded, to avoid
22322 # $VERSION mismatch errors (Carp::Heavy loads Carp, so we do not need to
22323 # check in the other direction)
22324 require Carp::Heavy if $INC{'Carp.pm'};
22325
22326 $self->setup_env_hash;
22327 @INC = @{$self->inc};
22328 }
22329
22330 sub setup_env_hash_for {
22331 my $self = $_[0]->new->activate($_[1]);
22332 $self->setup_env_hash;
22333 }
22334 sub setup_env_hash {
22335 my $self = shift;
22336 my %env = $self->build_environment_vars;
22337 for my $key (keys %env) {
22338 if (defined $env{$key}) {
22339 $ENV{$key} = $env{$key};
22340 }
22341 else {
22342 delete $ENV{$key};
22343 }
22344 }
22345 }
22346
22347 sub print_environment_vars_for {
22348 print $_[0]->environment_vars_string_for(@_[1..$#_]);
22349 }
22350
22351 sub environment_vars_string_for {
22352 my $self = $_[0]->new->activate($_[1]);
22353 $self->environment_vars_string;
22354 }
22355 sub environment_vars_string {
22356 my ($self, $shelltype) = @_;
22357
22358 $shelltype ||= $self->guess_shelltype;
22359
22360 my $extra = $self->extra;
22361 my @envs = (
22362 PATH => $self->bins,
22363 PERL5LIB => $self->libs,
22364 PERL_LOCAL_LIB_ROOT => $self->roots,
22365 map { $_ => $extra->{$_} } sort keys %$extra,
22366 );
22367 $self->_build_env_string($shelltype, \@envs);
22368 }
22369
22370 sub _build_env_string {
22371 my ($self, $shelltype, $envs) = @_;
22372 my @envs = @$envs;
22373
22374 my $build_method = "build_${shelltype}_env_declaration";
22375
22376 my $out = '';
22377 while (@envs) {
22378 my ($name, $value) = (shift(@envs), shift(@envs));
22379 if (
22380 ref $value
22381 && @$value == 1
22382 && ref $value->[0]
22383 && ref $value->[0] eq 'SCALAR'
22384 && ${$value->[0]} eq $name) {
22385 next;
22386 }
22387 $out .= $self->$build_method($name, $value);
22388 }
22389 my $wrap_method = "wrap_${shelltype}_output";
22390 if ($self->can($wrap_method)) {
22391 return $self->$wrap_method($out);
22392 }
22393 return $out;
22394 }
22395
22396 sub build_bourne_env_declaration {
22397 my ($class, $name, $args) = @_;
22398 my $value = $class->_interpolate($args, '${%s}', qr/["\\\$!`]/, '\\%s');
22399
22400 if (!defined $value) {
22401 return qq{unset $name;\n};
22402 }
22403
22404 $value =~ s/(^|\G|$_path_sep)\$\{$name\}$_path_sep/$1\${$name}\${$name+$_path_sep}/g;
22405 $value =~ s/$_path_sep\$\{$name\}$/\${$name+$_path_sep}\${$name}/;
22406
22407 qq{${name}="$value"; export ${name};\n}
22408 }
22409
22410 sub build_csh_env_declaration {
22411 my ($class, $name, $args) = @_;
22412 my ($value, @vars) = $class->_interpolate($args, '${%s}', '"', '"\\%s"');
22413 if (!defined $value) {
22414 return qq{unsetenv $name;\n};
22415 }
22416
22417 my $out = '';
22418 for my $var (@vars) {
22419 $out .= qq{if ! \$?$name setenv $name '';\n};
22420 }
22421
22422 my $value_without = $value;
22423 if ($value_without =~ s/(?:^|$_path_sep)\$\{$name\}(?:$_path_sep|$)//g) {
22424 $out .= qq{if "\${$name}" != '' setenv $name "$value";\n};
22425 $out .= qq{if "\${$name}" == '' };
22426 }
22427 $out .= qq{setenv $name "$value_without";\n};
22428 return $out;
22429 }
22430
22431 sub build_cmd_env_declaration {
22432 my ($class, $name, $args) = @_;
22433 my $value = $class->_interpolate($args, '%%%s%%', qr(%), '%s');
22434 if (!$value) {
22435 return qq{\@set $name=\n};
22436 }
22437
22438 my $out = '';
22439 my $value_without = $value;
22440 if ($value_without =~ s/(?:^|$_path_sep)%$name%(?:$_path_sep|$)//g) {
22441 $out .= qq{\@if not "%$name%"=="" set "$name=$value"\n};
22442 $out .= qq{\@if "%$name%"=="" };
22443 }
22444 $out .= qq{\@set "$name=$value_without"\n};
22445 return $out;
22446 }
22447
22448 sub build_powershell_env_declaration {
22449 my ($class, $name, $args) = @_;
22450 my $value = $class->_interpolate($args, '$env:%s', '"', '`%s');
22451
22452 if (!$value) {
22453 return qq{Remove-Item -ErrorAction 0 Env:\\$name;\n};
22454 }
22455
22456 my $maybe_path_sep = qq{\$(if("\$env:$name"-eq""){""}else{"$_path_sep"})};
22457 $value =~ s/(^|\G|$_path_sep)\$env:$name$_path_sep/$1\$env:$name"+$maybe_path_sep+"/g;
22458 $value =~ s/$_path_sep\$env:$name$/"+$maybe_path_sep+\$env:$name+"/;
22459
22460 qq{\$env:$name = \$("$value");\n};
22461 }
22462 sub wrap_powershell_output {
22463 my ($class, $out) = @_;
22464 return $out || " \n";
22465 }
22466
22467 sub build_fish_env_declaration {
22468 my ($class, $name, $args) = @_;
22469 my $value = $class->_interpolate($args, '$%s', qr/[\\"' ]/, '\\%s');
22470 if (!defined $value) {
22471 return qq{set -e $name;\n};
22472 }
22473 $value =~ s/$_path_sep/ /g;
22474 qq{set -x $name $value;\n};
22475 }
22476
22477 sub _interpolate {
22478 my ($class, $args, $var_pat, $escape, $escape_pat) = @_;
22479 return
22480 unless defined $args;
22481 my @args = ref $args ? @$args : $args;
22482 return
22483 unless @args;
22484 my @vars = map { $$_ } grep { ref $_ eq 'SCALAR' } @args;
22485 my $string = join $_path_sep, map {
22486 ref $_ eq 'SCALAR' ? sprintf($var_pat, $$_) : do {
22487 s/($escape)/sprintf($escape_pat, $1)/ge; $_;
22488 };
22489 } @args;
22490 return wantarray ? ($string, \@vars) : $string;
22491 }
22492
22493 sub pipeline;
22494
22495 sub pipeline {
22496 my @methods = @_;
22497 my $last = pop(@methods);
22498 if (@methods) {
22499 \sub {
22500 my ($obj, @args) = @_;
22501 $obj->${pipeline @methods}(
22502 $obj->$last(@args)
22503 );
22504 };
22505 } else {
22506 \sub {
22507 shift->$last(@_);
22508 };
22509 }
22510 }
22511
22512 sub resolve_path {
22513 my ($class, $path) = @_;
22514
22515 $path = $class->${pipeline qw(
22516 resolve_relative_path
22517 resolve_home_path
22518 resolve_empty_path
22519 )}($path);
22520
22521 $path;
22522 }
22523
22524 sub resolve_empty_path {
22525 my ($class, $path) = @_;
22526 if (defined $path) {
22527 $path;
22528 } else {
22529 '~/perl5';
22530 }
22531 }
22532
22533 sub resolve_home_path {
22534 my ($class, $path) = @_;
22535 $path =~ /^~([^\/]*)/ or return $path;
22536 my $user = $1;
22537 my $homedir = do {
22538 if (! length($user) && defined $ENV{HOME}) {
22539 $ENV{HOME};
22540 }
22541 else {
22542 require File::Glob;
22543 File::Glob::bsd_glob("~$user", File::Glob::GLOB_TILDE());
22544 }
22545 };
22546 unless (defined $homedir) {
22547 require Carp; require Carp::Heavy;
22548 Carp::croak(
22549 "Couldn't resolve homedir for "
22550 .(defined $user ? $user : 'current user')
22551 );
22552 }
22553 $path =~ s/^~[^\/]*/$homedir/;
22554 $path;
22555 }
22556
22557 sub resolve_relative_path {
22558 my ($class, $path) = @_;
22559 _rel2abs($path);
22560 }
22561
22562 sub ensure_dir_structure_for {
22563 my ($class, $path) = @_;
22564 unless (-d $path) {
22565 warn "Attempting to create directory ${path}\n";
22566 }
22567 require File::Basename;
22568 my @dirs;
22569 while(!-d $path) {
22570 push @dirs, $path;
22571 $path = File::Basename::dirname($path);
22572 }
22573 mkdir $_ for reverse @dirs;
22574 return;
22575 }
22576
22577 sub guess_shelltype {
22578 my $shellbin
22579 = defined $ENV{SHELL}
22580 ? ($ENV{SHELL} =~ /([\w.]+)$/)[-1]
22581 : ( $^O eq 'MSWin32' && exists $ENV{'!EXITCODE'} )
22582 ? 'bash'
22583 : ( $^O eq 'MSWin32' && $ENV{PROMPT} && $ENV{COMSPEC} )
22584 ? ($ENV{COMSPEC} =~ /([\w.]+)$/)[-1]
22585 : ( $^O eq 'MSWin32' && !$ENV{PROMPT} )
22586 ? 'powershell.exe'
22587 : 'sh';
22588
22589 for ($shellbin) {
22590 return
22591 /csh$/ ? 'csh'
22592 : /fish/ ? 'fish'
22593 : /command(?:\.com)?$/i ? 'cmd'
22594 : /cmd(?:\.exe)?$/i ? 'cmd'
22595 : /4nt(?:\.exe)?$/i ? 'cmd'
22596 : /powershell(?:\.exe)?$/i ? 'powershell'
22597 : 'bourne';
22598 }
22599 }
22600
22601 1;
22602 __END__
22603
22604 =encoding utf8
22605
22606 =head1 NAME
22607
22608 local::lib - create and use a local lib/ for perl modules with PERL5LIB
22609
22610 =head1 SYNOPSIS
22611
22612 In code -
22613
22614 use local::lib; # sets up a local lib at ~/perl5
22615
22616 use local::lib '~/foo'; # same, but ~/foo
22617
22618 # Or...
22619 use FindBin;
22620 use local::lib "$FindBin::Bin/../support"; # app-local support library
22621
22622 From the shell -
22623
22624 # Install LWP and its missing dependencies to the '~/perl5' directory
22625 perl -MCPAN -Mlocal::lib -e 'CPAN::install(LWP)'
22626
22627 # Just print out useful shell commands
22628 $ perl -Mlocal::lib
22629 PERL_MB_OPT='--install_base /home/username/perl5'; export PERL_MB_OPT;
22630 PERL_MM_OPT='INSTALL_BASE=/home/username/perl5'; export PERL_MM_OPT;
22631 PERL5LIB="/home/username/perl5/lib/perl5"; export PERL5LIB;
22632 PATH="/home/username/perl5/bin:$PATH"; export PATH;
22633 PERL_LOCAL_LIB_ROOT="/home/usename/perl5:$PERL_LOCAL_LIB_ROOT"; export PERL_LOCAL_LIB_ROOT;
22634
22635 From a .bashrc file -
22636
22637 [ $SHLVL -eq 1 ] && eval "$(perl -I$HOME/perl5/lib/perl5 -Mlocal::lib)"
22638
22639 =head2 The bootstrapping technique
22640
22641 A typical way to install local::lib is using what is known as the
22642 "bootstrapping" technique. You would do this if your system administrator
22643 hasn't already installed local::lib. In this case, you'll need to install
22644 local::lib in your home directory.
22645
22646 Even if you do have administrative privileges, you will still want to set up your
22647 environment variables, as discussed in step 4. Without this, you would still
22648 install the modules into the system CPAN installation and also your Perl scripts
22649 will not use the lib/ path you bootstrapped with local::lib.
22650
22651 By default local::lib installs itself and the CPAN modules into ~/perl5.
22652
22653 Windows users must also see L</Differences when using this module under Win32>.
22654
22655 =over 4
22656
22657 =item 1.
22658
22659 Download and unpack the local::lib tarball from CPAN (search for "Download"
22660 on the CPAN page about local::lib). Do this as an ordinary user, not as root
22661 or administrator. Unpack the file in your home directory or in any other
22662 convenient location.
22663
22664 =item 2.
22665
22666 Run this:
22667
22668 perl Makefile.PL --bootstrap
22669
22670 If the system asks you whether it should automatically configure as much
22671 as possible, you would typically answer yes.
22672
22673 In order to install local::lib into a directory other than the default, you need
22674 to specify the name of the directory when you call bootstrap, as follows:
22675
22676 perl Makefile.PL --bootstrap=~/foo
22677
22678 =item 3.
22679
22680 Run this: (local::lib assumes you have make installed on your system)
22681
22682 make test && make install
22683
22684 =item 4.
22685
22686 Now we need to setup the appropriate environment variables, so that Perl
22687 starts using our newly generated lib/ directory. If you are using bash or
22688 any other Bourne shells, you can add this to your shell startup script this
22689 way:
22690
22691 echo '[ $SHLVL -eq 1 ] && eval "$(perl -I$HOME/perl5/lib/perl5 -Mlocal::lib)"' >>~/.bashrc
22692
22693 If you are using C shell, you can do this as follows:
22694
22695 /bin/csh
22696 echo $SHELL
22697 /bin/csh
22698 echo 'eval `perl -I$HOME/perl5/lib/perl5 -Mlocal::lib`' >> ~/.cshrc
22699
22700 If you passed to bootstrap a directory other than default, you also need to
22701 give that as import parameter to the call of the local::lib module like this
22702 way:
22703
22704 echo '[ $SHLVL -eq 1 ] && eval "$(perl -I$HOME/foo/lib/perl5 -Mlocal::lib=$HOME/foo)"' >>~/.bashrc
22705
22706 After writing your shell configuration file, be sure to re-read it to get the
22707 changed settings into your current shell's environment. Bourne shells use
22708 C<. ~/.bashrc> for this, whereas C shells use C<source ~/.cshrc>.
22709
22710 =back
22711
22712 If you're on a slower machine, or are operating under draconian disk space
22713 limitations, you can disable the automatic generation of manpages from POD when
22714 installing modules by using the C<--no-manpages> argument when bootstrapping:
22715
22716 perl Makefile.PL --bootstrap --no-manpages
22717
22718 To avoid doing several bootstrap for several Perl module environments on the
22719 same account, for example if you use it for several different deployed
22720 applications independently, you can use one bootstrapped local::lib
22721 installation to install modules in different directories directly this way:
22722
22723 cd ~/mydir1
22724 perl -Mlocal::lib=./
22725 eval $(perl -Mlocal::lib=./) ### To set the environment for this shell alone
22726 printenv ### You will see that ~/mydir1 is in the PERL5LIB
22727 perl -MCPAN -e install ... ### whatever modules you want
22728 cd ../mydir2
22729 ... REPEAT ...
22730
22731 When used in a C<.bashrc> file, it is recommended that you protect against
22732 re-activating a directory in a sub-shell. This can be done by checking the
22733 C<$SHLVL> variable as shown in synopsis. Without this, sub-shells created by
22734 the user or other programs will override changes made to the parent shell's
22735 environment.
22736
22737 If you are working with several C<local::lib> environments, you may want to
22738 remove some of them from the current environment without disturbing the others.
22739 You can deactivate one environment like this (using bourne sh):
22740
22741 eval $(perl -Mlocal::lib=--deactivate,~/path)
22742
22743 which will generate and run the commands needed to remove C<~/path> from your
22744 various search paths. Whichever environment was B<activated most recently> will
22745 remain the target for module installations. That is, if you activate
22746 C<~/path_A> and then you activate C<~/path_B>, new modules you install will go
22747 in C<~/path_B>. If you deactivate C<~/path_B> then modules will be installed
22748 into C<~/pathA> -- but if you deactivate C<~/path_A> then they will still be
22749 installed in C<~/pathB> because pathB was activated later.
22750
22751 You can also ask C<local::lib> to clean itself completely out of the current
22752 shell's environment with the C<--deactivate-all> option.
22753 For multiple environments for multiple apps you may need to include a modified
22754 version of the C<< use FindBin >> instructions in the "In code" sample above.
22755 If you did something like the above, you have a set of Perl modules at C<<
22756 ~/mydir1/lib >>. If you have a script at C<< ~/mydir1/scripts/myscript.pl >>,
22757 you need to tell it where to find the modules you installed for it at C<<
22758 ~/mydir1/lib >>.
22759
22760 In C<< ~/mydir1/scripts/myscript.pl >>:
22761
22762 use strict;
22763 use warnings;
22764 use local::lib "$FindBin::Bin/.."; ### points to ~/mydir1 and local::lib finds lib
22765 use lib "$FindBin::Bin/../lib"; ### points to ~/mydir1/lib
22766
22767 Put this before any BEGIN { ... } blocks that require the modules you installed.
22768
22769 =head2 Differences when using this module under Win32
22770
22771 To set up the proper environment variables for your current session of
22772 C<CMD.exe>, you can use this:
22773
22774 C:\>perl -Mlocal::lib
22775 set PERL_MB_OPT=--install_base C:\DOCUME~1\ADMINI~1\perl5
22776 set PERL_MM_OPT=INSTALL_BASE=C:\DOCUME~1\ADMINI~1\perl5
22777 set PERL5LIB=C:\DOCUME~1\ADMINI~1\perl5\lib\perl5
22778 set PATH=C:\DOCUME~1\ADMINI~1\perl5\bin;%PATH%
22779
22780 ### To set the environment for this shell alone
22781 C:\>perl -Mlocal::lib > %TEMP%\tmp.bat && %TEMP%\tmp.bat && del %TEMP%\tmp.bat
22782 ### instead of $(perl -Mlocal::lib=./)
22783
22784 If you want the environment entries to persist, you'll need to add them to the
22785 Control Panel's System applet yourself or use L<App::local::lib::Win32Helper>.
22786
22787 The "~" is translated to the user's profile directory (the directory named for
22788 the user under "Documents and Settings" (Windows XP or earlier) or "Users"
22789 (Windows Vista or later)) unless $ENV{HOME} exists. After that, the home
22790 directory is translated to a short name (which means the directory must exist)
22791 and the subdirectories are created.
22792
22793 =head3 PowerShell
22794
22795 local::lib also supports PowerShell, and can be used with the
22796 C<Invoke-Expression> cmdlet.
22797
22798 Invoke-Expression "$(perl -Mlocal::lib)"
22799
22800 =head1 RATIONALE
22801
22802 The version of a Perl package on your machine is not always the version you
22803 need. Obviously, the best thing to do would be to update to the version you
22804 need. However, you might be in a situation where you're prevented from doing
22805 this. Perhaps you don't have system administrator privileges; or perhaps you
22806 are using a package management system such as Debian, and nobody has yet gotten
22807 around to packaging up the version you need.
22808
22809 local::lib solves this problem by allowing you to create your own directory of
22810 Perl packages downloaded from CPAN (in a multi-user system, this would typically
22811 be within your own home directory). The existing system Perl installation is
22812 not affected; you simply invoke Perl with special options so that Perl uses the
22813 packages in your own local package directory rather than the system packages.
22814 local::lib arranges things so that your locally installed version of the Perl
22815 packages takes precedence over the system installation.
22816
22817 If you are using a package management system (such as Debian), you don't need to
22818 worry about Debian and CPAN stepping on each other's toes. Your local version
22819 of the packages will be written to an entirely separate directory from those
22820 installed by Debian.
22821
22822 =head1 DESCRIPTION
22823
22824 This module provides a quick, convenient way of bootstrapping a user-local Perl
22825 module library located within the user's home directory. It also constructs and
22826 prints out for the user the list of environment variables using the syntax
22827 appropriate for the user's current shell (as specified by the C<SHELL>
22828 environment variable), suitable for directly adding to one's shell
22829 configuration file.
22830
22831 More generally, local::lib allows for the bootstrapping and usage of a
22832 directory containing Perl modules outside of Perl's C<@INC>. This makes it
22833 easier to ship an application with an app-specific copy of a Perl module, or
22834 collection of modules. Useful in cases like when an upstream maintainer hasn't
22835 applied a patch to a module of theirs that you need for your application.
22836
22837 On import, local::lib sets the following environment variables to appropriate
22838 values:
22839
22840 =over 4
22841
22842 =item PERL_MB_OPT
22843
22844 =item PERL_MM_OPT
22845
22846 =item PERL5LIB
22847
22848 =item PATH
22849
22850 =item PERL_LOCAL_LIB_ROOT
22851
22852 =back
22853
22854 When possible, these will be appended to instead of overwritten entirely.
22855
22856 These values are then available for reference by any code after import.
22857
22858 =head1 CREATING A SELF-CONTAINED SET OF MODULES
22859
22860 See L<lib::core::only> for one way to do this - but note that
22861 there are a number of caveats, and the best approach is always to perform a
22862 build against a clean perl (i.e. site and vendor as close to empty as possible).
22863
22864 =head1 IMPORT OPTIONS
22865
22866 Options are values that can be passed to the C<local::lib> import besides the
22867 directory to use. They are specified as C<use local::lib '--option'[, path];>
22868 or C<perl -Mlocal::lib=--option[,path]>.
22869
22870 =head2 --deactivate
22871
22872 Remove the chosen path (or the default path) from the module search paths if it
22873 was added by C<local::lib>, instead of adding it.
22874
22875 =head2 --deactivate-all
22876
22877 Remove all directories that were added to search paths by C<local::lib> from the
22878 search paths.
22879
22880 =head2 --shelltype
22881
22882 Specify the shell type to use for output. By default, the shell will be
22883 detected based on the environment. Should be one of: C<bourne>, C<csh>,
22884 C<cmd>, or C<powershell>.
22885
22886 =head2 --no-create
22887
22888 Prevents C<local::lib> from creating directories when activating dirs. This is
22889 likely to cause issues on Win32 systems.
22890
22891 =head1 CLASS METHODS
22892
22893 =head2 ensure_dir_structure_for
22894
22895 =over 4
22896
22897 =item Arguments: $path
22898
22899 =item Return value: None
22900
22901 =back
22902
22903 Attempts to create the given path, and all required parent directories. Throws
22904 an exception on failure.
22905
22906 =head2 print_environment_vars_for
22907
22908 =over 4
22909
22910 =item Arguments: $path
22911
22912 =item Return value: None
22913
22914 =back
22915
22916 Prints to standard output the variables listed above, properly set to use the
22917 given path as the base directory.
22918
22919 =head2 build_environment_vars_for
22920
22921 =over 4
22922
22923 =item Arguments: $path
22924
22925 =item Return value: %environment_vars
22926
22927 =back
22928
22929 Returns a hash with the variables listed above, properly set to use the
22930 given path as the base directory.
22931
22932 =head2 setup_env_hash_for
22933
22934 =over 4
22935
22936 =item Arguments: $path
22937
22938 =item Return value: None
22939
22940 =back
22941
22942 Constructs the C<%ENV> keys for the given path, by calling
22943 L</build_environment_vars_for>.
22944
22945 =head2 active_paths
22946
22947 =over 4
22948
22949 =item Arguments: None
22950
22951 =item Return value: @paths
22952
22953 =back
22954
22955 Returns a list of active C<local::lib> paths, according to the
22956 C<PERL_LOCAL_LIB_ROOT> environment variable and verified against
22957 what is really in C<@INC>.
22958
22959 =head2 install_base_perl_path
22960
22961 =over 4
22962
22963 =item Arguments: $path
22964
22965 =item Return value: $install_base_perl_path
22966
22967 =back
22968
22969 Returns a path describing where to install the Perl modules for this local
22970 library installation. Appends the directories C<lib> and C<perl5> to the given
22971 path.
22972
22973 =head2 lib_paths_for
22974
22975 =over 4
22976
22977 =item Arguments: $path
22978
22979 =item Return value: @lib_paths
22980
22981 =back
22982
22983 Returns the list of paths perl will search for libraries, given a base path.
22984 This includes the base path itself, the architecture specific subdirectory, and
22985 perl version specific subdirectories. These paths may not all exist.
22986
22987 =head2 install_base_bin_path
22988
22989 =over 4
22990
22991 =item Arguments: $path
22992
22993 =item Return value: $install_base_bin_path
22994
22995 =back
22996
22997 Returns a path describing where to install the executable programs for this
22998 local library installation. Appends the directory C<bin> to the given path.
22999
23000 =head2 installer_options_for
23001
23002 =over 4
23003
23004 =item Arguments: $path
23005
23006 =item Return value: %installer_env_vars
23007
23008 =back
23009
23010 Returns a hash of environment variables that should be set to cause
23011 installation into the given path.
23012
23013 =head2 resolve_empty_path
23014
23015 =over 4
23016
23017 =item Arguments: $path
23018
23019 =item Return value: $base_path
23020
23021 =back
23022
23023 Builds and returns the base path into which to set up the local module
23024 installation. Defaults to C<~/perl5>.
23025
23026 =head2 resolve_home_path
23027
23028 =over 4
23029
23030 =item Arguments: $path
23031
23032 =item Return value: $home_path
23033
23034 =back
23035
23036 Attempts to find the user's home directory. If installed, uses C<File::HomeDir>
23037 for this purpose. If no definite answer is available, throws an exception.
23038
23039 =head2 resolve_relative_path
23040
23041 =over 4
23042
23043 =item Arguments: $path
23044
23045 =item Return value: $absolute_path
23046
23047 =back
23048
23049 Translates the given path into an absolute path.
23050
23051 =head2 resolve_path
23052
23053 =over 4
23054
23055 =item Arguments: $path
23056
23057 =item Return value: $absolute_path
23058
23059 =back
23060
23061 Calls the following in a pipeline, passing the result from the previous to the
23062 next, in an attempt to find where to configure the environment for a local
23063 library installation: L</resolve_empty_path>, L</resolve_home_path>,
23064 L</resolve_relative_path>. Passes the given path argument to
23065 L</resolve_empty_path> which then returns a result that is passed to
23066 L</resolve_home_path>, which then has its result passed to
23067 L</resolve_relative_path>. The result of this final call is returned from
23068 L</resolve_path>.
23069
23070 =head1 OBJECT INTERFACE
23071
23072 =head2 new
23073
23074 =over 4
23075
23076 =item Arguments: %attributes
23077
23078 =item Return value: $local_lib
23079
23080 =back
23081
23082 Constructs a new C<local::lib> object, representing the current state of
23083 C<@INC> and the relevant environment variables.
23084
23085 =head1 ATTRIBUTES
23086
23087 =head2 roots
23088
23089 An arrayref representing active C<local::lib> directories.
23090
23091 =head2 inc
23092
23093 An arrayref representing C<@INC>.
23094
23095 =head2 libs
23096
23097 An arrayref representing the PERL5LIB environment variable.
23098
23099 =head2 bins
23100
23101 An arrayref representing the PATH environment variable.
23102
23103 =head2 extra
23104
23105 A hashref of extra environment variables (e.g. C<PERL_MM_OPT> and
23106 C<PERL_MB_OPT>)
23107
23108 =head2 no_create
23109
23110 If set, C<local::lib> will not try to create directories when activating them.
23111
23112 =head1 OBJECT METHODS
23113
23114 =head2 clone
23115
23116 =over 4
23117
23118 =item Arguments: %attributes
23119
23120 =item Return value: $local_lib
23121
23122 =back
23123
23124 Constructs a new C<local::lib> object based on the existing one, overriding the
23125 specified attributes.
23126
23127 =head2 activate
23128
23129 =over 4
23130
23131 =item Arguments: $path
23132
23133 =item Return value: $new_local_lib
23134
23135 =back
23136
23137 Constructs a new instance with the specified path active.
23138
23139 =head2 deactivate
23140
23141 =over 4
23142
23143 =item Arguments: $path
23144
23145 =item Return value: $new_local_lib
23146
23147 =back
23148
23149 Constructs a new instance with the specified path deactivated.
23150
23151 =head2 deactivate_all
23152
23153 =over 4
23154
23155 =item Arguments: None
23156
23157 =item Return value: $new_local_lib
23158
23159 =back
23160
23161 Constructs a new instance with all C<local::lib> directories deactivated.
23162
23163 =head2 environment_vars_string
23164
23165 =over 4
23166
23167 =item Arguments: [ $shelltype ]
23168
23169 =item Return value: $shell_env_string
23170
23171 =back
23172
23173 Returns a string to set up the C<local::lib>, meant to be run by a shell.
23174
23175 =head2 build_environment_vars
23176
23177 =over 4
23178
23179 =item Arguments: None
23180
23181 =item Return value: %environment_vars
23182
23183 =back
23184
23185 Returns a hash with the variables listed above, properly set to use the
23186 given path as the base directory.
23187
23188 =head2 setup_env_hash
23189
23190 =over 4
23191
23192 =item Arguments: None
23193
23194 =item Return value: None
23195
23196 =back
23197
23198 Constructs the C<%ENV> keys for the given path, by calling
23199 L</build_environment_vars>.
23200
23201 =head2 setup_local_lib
23202
23203 Constructs the C<%ENV> hash using L</setup_env_hash>, and set up C<@INC>.
23204
23205 =head1 A WARNING ABOUT UNINST=1
23206
23207 Be careful about using local::lib in combination with "make install UNINST=1".
23208 The idea of this feature is that will uninstall an old version of a module
23209 before installing a new one. However it lacks a safety check that the old
23210 version and the new version will go in the same directory. Used in combination
23211 with local::lib, you can potentially delete a globally accessible version of a
23212 module while installing the new version in a local place. Only combine "make
23213 install UNINST=1" and local::lib if you understand these possible consequences.
23214
23215 =head1 LIMITATIONS
23216
23217 =over 4
23218
23219 =item * Directory names with spaces in them are not well supported by the perl
23220 toolchain and the programs it uses. Pure-perl distributions should support
23221 spaces, but problems are more likely with dists that require compilation. A
23222 workaround you can do is moving your local::lib to a directory with spaces
23223 B<after> you installed all modules inside your local::lib bootstrap. But be
23224 aware that you can't update or install CPAN modules after the move.
23225
23226 =item * Rather basic shell detection. Right now anything with csh in its name is
23227 assumed to be a C shell or something compatible, and everything else is assumed
23228 to be Bourne, except on Win32 systems. If the C<SHELL> environment variable is
23229 not set, a Bourne-compatible shell is assumed.
23230
23231 =item * Kills any existing PERL_MM_OPT or PERL_MB_OPT.
23232
23233 =item * Should probably auto-fixup CPAN config if not already done.
23234
23235 =item * On VMS and MacOS Classic (pre-OS X), local::lib loads L<File::Spec>.
23236 This means any L<File::Spec> version installed in the local::lib will be
23237 ignored by scripts using local::lib. A workaround for this is using
23238 C<use lib "$local_lib/lib/perl5";> instead of using C<local::lib> directly.
23239
23240 =item * Conflicts with L<ExtUtils::MakeMaker>'s C<PREFIX> option.
23241 C<local::lib> uses the C<INSTALL_BASE> option, as it has more predictable and
23242 sane behavior. If something attempts to use the C<PREFIX> option when running
23243 a F<Makefile.PL>, L<ExtUtils::MakeMaker> will refuse to run, as the two
23244 options conflict. This can be worked around by temporarily unsetting the
23245 C<PERL_MM_OPT> environment variable.
23246
23247 =item * Conflicts with L<Module::Build>'s C<--prefix> option. Similar to the
23248 previous limitation, but any C<--prefix> option specified will be ignored.
23249 This can be worked around by temporarily unsetting the C<PERL_MB_OPT>
23250 environment variable.
23251
23252 =back
23253
23254 Patches very much welcome for any of the above.
23255
23256 =over 4
23257
23258 =item * On Win32 systems, does not have a way to write the created environment
23259 variables to the registry, so that they can persist through a reboot.
23260
23261 =back
23262
23263 =head1 TROUBLESHOOTING
23264
23265 If you've configured local::lib to install CPAN modules somewhere in to your
23266 home directory, and at some point later you try to install a module with C<cpan
23267 -i Foo::Bar>, but it fails with an error like: C<Warning: You do not have
23268 permissions to install into /usr/lib64/perl5/site_perl/5.8.8/x86_64-linux at
23269 /usr/lib64/perl5/5.8.8/Foo/Bar.pm> and buried within the install log is an
23270 error saying C<'INSTALL_BASE' is not a known MakeMaker parameter name>, then
23271 you've somehow lost your updated ExtUtils::MakeMaker module.
23272
23273 To remedy this situation, rerun the bootstrapping procedure documented above.
23274
23275 Then, run C<rm -r ~/.cpan/build/Foo-Bar*>
23276
23277 Finally, re-run C<cpan -i Foo::Bar> and it should install without problems.
23278
23279 =head1 ENVIRONMENT
23280
23281 =over 4
23282
23283 =item SHELL
23284
23285 =item COMSPEC
23286
23287 local::lib looks at the user's C<SHELL> environment variable when printing out
23288 commands to add to the shell configuration file.
23289
23290 On Win32 systems, C<COMSPEC> is also examined.
23291
23292 =back
23293
23294 =head1 SEE ALSO
23295
23296 =over 4
23297
23298 =item * L<Perl Advent article, 2011|http://perladvent.org/2011/2011-12-01.html>
23299
23300 =back
23301
23302 =head1 SUPPORT
23303
23304 IRC:
23305
23306 Join #local-lib on irc.perl.org.
23307
23308 =head1 AUTHOR
23309
23310 Matt S Trout <mst@shadowcat.co.uk> http://www.shadowcat.co.uk/
23311
23312 auto_install fixes kindly sponsored by http://www.takkle.com/
23313
23314 =head1 CONTRIBUTORS
23315
23316 Patches to correctly output commands for csh style shells, as well as some
23317 documentation additions, contributed by Christopher Nehren <apeiron@cpan.org>.
23318
23319 Doc patches for a custom local::lib directory, more cleanups in the english
23320 documentation and a L<german documentation|POD2::DE::local::lib> contributed by
23321 Torsten Raudssus <torsten@raudssus.de>.
23322
23323 Hans Dieter Pearcey <hdp@cpan.org> sent in some additional tests for ensuring
23324 things will install properly, submitted a fix for the bug causing problems with
23325 writing Makefiles during bootstrapping, contributed an example program, and
23326 submitted yet another fix to ensure that local::lib can install and bootstrap
23327 properly. Many, many thanks!
23328
23329 pattern of Freenode IRC contributed the beginnings of the Troubleshooting
23330 section. Many thanks!
23331
23332 Patch to add Win32 support contributed by Curtis Jewell <csjewell@cpan.org>.
23333
23334 Warnings for missing PATH/PERL5LIB (as when not running interactively) silenced
23335 by a patch from Marco Emilio Poleggi.
23336
23337 Mark Stosberg <mark@summersault.com> provided the code for the now deleted
23338 '--self-contained' option.
23339
23340 Documentation patches to make win32 usage clearer by
23341 David Mertens <dcmertens.perl@gmail.com> (run4flat).
23342
23343 Brazilian L<portuguese translation|POD2::PT_BR::local::lib> and minor doc
23344 patches contributed by Breno G. de Oliveira <garu@cpan.org>.
23345
23346 Improvements to stacking multiple local::lib dirs and removing them from the
23347 environment later on contributed by Andrew Rodland <arodland@cpan.org>.
23348
23349 Patch for Carp version mismatch contributed by Hakim Cassimally
23350 <osfameron@cpan.org>.
23351
23352 Rewrite of internals and numerous bug fixes and added features contributed by
23353 Graham Knop <haarg@haarg.org>.
23354
23355 =head1 COPYRIGHT
23356
23357 Copyright (c) 2007 - 2013 the local::lib L</AUTHOR> and L</CONTRIBUTORS> as
23358 listed above.
23359
23360 =head1 LICENSE
23361
23362 This is free software; you can redistribute it and/or modify it under
23363 the same terms as the Perl 5 programming language system itself.
23364
23365 =cut
23366 LOCAL_LIB
23367  
23368 $fatpacked{"parent.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'PARENT';
23369 package parent;
23370 use strict;
23371 use vars qw($VERSION);
23372 $VERSION = '0.228';
23373
23374 sub import {
23375 my $class = shift;
23376
23377 my $inheritor = caller(0);
23378
23379 if ( @_ and $_[0] eq '-norequire' ) {
23380 shift @_;
23381 } else {
23382 for ( my @filename = @_ ) {
23383 if ( $_ eq $inheritor ) {
23384 warn "Class '$inheritor' tried to inherit from itself\n";
23385 };
23386
23387 s{::|'}{/}g;
23388 require "$_.pm"; # dies if the file is not found
23389 }
23390 }
23391
23392 {
23393 no strict 'refs';
23394 push @{"$inheritor\::ISA"}, @_;
23395 };
23396 };
23397
23398 "All your base are belong to us"
23399
23400 __END__
23401
23402 =encoding utf8
23403
23404 =head1 NAME
23405
23406 parent - Establish an ISA relationship with base classes at compile time
23407
23408 =head1 SYNOPSIS
23409
23410 package Baz;
23411 use parent qw(Foo Bar);
23412
23413 =head1 DESCRIPTION
23414
23415 Allows you to both load one or more modules, while setting up inheritance from
23416 those modules at the same time. Mostly similar in effect to
23417
23418 package Baz;
23419 BEGIN {
23420 require Foo;
23421 require Bar;
23422 push @ISA, qw(Foo Bar);
23423 }
23424
23425 By default, every base class needs to live in a file of its own.
23426 If you want to have a subclass and its parent class in the same file, you
23427 can tell C<parent> not to load any modules by using the C<-norequire> switch:
23428
23429 package Foo;
23430 sub exclaim { "I CAN HAS PERL" }
23431
23432 package DoesNotLoadFooBar;
23433 use parent -norequire, 'Foo', 'Bar';
23434 # will not go looking for Foo.pm or Bar.pm
23435
23436 This is equivalent to the following code:
23437
23438 package Foo;
23439 sub exclaim { "I CAN HAS PERL" }
23440
23441 package DoesNotLoadFooBar;
23442 push @DoesNotLoadFooBar::ISA, 'Foo', 'Bar';
23443
23444 This is also helpful for the case where a package lives within
23445 a differently named file:
23446
23447 package MyHash;
23448 use Tie::Hash;
23449 use parent -norequire, 'Tie::StdHash';
23450
23451 This is equivalent to the following code:
23452
23453 package MyHash;
23454 require Tie::Hash;
23455 push @ISA, 'Tie::StdHash';
23456
23457 If you want to load a subclass from a file that C<require> would
23458 not consider an eligible filename (that is, it does not end in
23459 either C<.pm> or C<.pmc>), use the following code:
23460
23461 package MySecondPlugin;
23462 require './plugins/custom.plugin'; # contains Plugin::Custom
23463 use parent -norequire, 'Plugin::Custom';
23464
23465 =head1 DIAGNOSTICS
23466
23467 =over 4
23468
23469 =item Class 'Foo' tried to inherit from itself
23470
23471 Attempting to inherit from yourself generates a warning.
23472
23473 package Foo;
23474 use parent 'Foo';
23475
23476 =back
23477
23478 =head1 HISTORY
23479
23480 This module was forked from L<base> to remove the cruft
23481 that had accumulated in it.
23482
23483 =head1 CAVEATS
23484
23485 =head1 SEE ALSO
23486
23487 L<base>
23488
23489 =head1 AUTHORS AND CONTRIBUTORS
23490
23491 Rafaël Garcia-Suarez, Bart Lateur, Max Maischein, Anno Siegel, Michael Schwern
23492
23493 =head1 MAINTAINER
23494
23495 Max Maischein C< corion@cpan.org >
23496
23497 Copyright (c) 2007-10 Max Maischein C<< <corion@cpan.org> >>
23498 Based on the idea of C<base.pm>, which was introduced with Perl 5.004_04.
23499
23500 =head1 LICENSE
23501
23502 This module is released under the same terms as Perl itself.
23503
23504 =cut
23505 PARENT
23506  
23507 $fatpacked{"version.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'VERSION';
23508 #!perl -w
23509 package version;
23510
23511 use 5.006002;
23512 use strict;
23513 use warnings::register;
23514 if ($] >= 5.015) {
23515 warnings::register_categories(qw/version/);
23516 }
23517
23518 our $VERSION = 0.9929;
23519 our $CLASS = 'version';
23520 our (@ISA, $STRICT, $LAX);
23521
23522 # !!!!Delete this next block completely when adding to Perl core!!!!
23523 {
23524 local $SIG{'__DIE__'};
23525 if (1) { # always pretend there's no XS
23526 eval "use version::vpp $VERSION"; # don't tempt fate
23527 die "$@" if ( $@ );
23528 push @ISA, "version::vpp";
23529 local $^W;
23530 *version::qv = \&version::vpp::qv;
23531 *version::declare = \&version::vpp::declare;
23532 *version::_VERSION = \&version::vpp::_VERSION;
23533 *version::vcmp = \&version::vpp::vcmp;
23534 *version::new = \&version::vpp::new;
23535 *version::numify = \&version::vpp::numify;
23536 *version::normal = \&version::vpp::normal;
23537 if ($] >= 5.009000) {
23538 no strict 'refs';
23539 *version::stringify = \&version::vpp::stringify;
23540 *{'version::(""'} = \&version::vpp::stringify;
23541 *{'version::(<=>'} = \&version::vpp::vcmp;
23542 *{'version::(cmp'} = \&version::vpp::vcmp;
23543 *version::parse = \&version::vpp::parse;
23544 }
23545 }
23546 else { # use XS module
23547 push @ISA, "version::vxs";
23548 local $^W;
23549 *version::declare = \&version::vxs::declare;
23550 *version::qv = \&version::vxs::qv;
23551 *version::_VERSION = \&version::vxs::_VERSION;
23552 *version::vcmp = \&version::vxs::VCMP;
23553 *version::new = \&version::vxs::new;
23554 *version::numify = \&version::vxs::numify;
23555 *version::normal = \&version::vxs::normal;
23556 if ($] >= 5.009000) {
23557 no strict 'refs';
23558 *version::stringify = \&version::vxs::stringify;
23559 *{'version::(""'} = \&version::vxs::stringify;
23560 *{'version::(<=>'} = \&version::vxs::VCMP;
23561 *{'version::(cmp'} = \&version::vxs::VCMP;
23562 *version::parse = \&version::vxs::parse;
23563 }
23564 }
23565 }
23566
23567 # avoid using Exporter
23568 require version::regex;
23569 *version::is_lax = \&version::regex::is_lax;
23570 *version::is_strict = \&version::regex::is_strict;
23571 *LAX = \$version::regex::LAX;
23572 *LAX_DECIMAL_VERSION = \$version::regex::LAX_DECIMAL_VERSION;
23573 *LAX_DOTTED_DECIMAL_VERSION = \$version::regex::LAX_DOTTED_DECIMAL_VERSION;
23574 *STRICT = \$version::regex::STRICT;
23575 *STRICT_DECIMAL_VERSION = \$version::regex::STRICT_DECIMAL_VERSION;
23576 *STRICT_DOTTED_DECIMAL_VERSION = \$version::regex::STRICT_DOTTED_DECIMAL_VERSION;
23577
23578 sub import {
23579 no strict 'refs';
23580 my ($class) = shift;
23581
23582 # Set up any derived class
23583 unless ($class eq $CLASS) {
23584 local $^W;
23585 *{$class.'::declare'} = \&{$CLASS.'::declare'};
23586 *{$class.'::qv'} = \&{$CLASS.'::qv'};
23587 }
23588
23589 my %args;
23590 if (@_) { # any remaining terms are arguments
23591 map { $args{$_} = 1 } @_
23592 }
23593 else { # no parameters at all on use line
23594 %args =
23595 (
23596 qv => 1,
23597 'UNIVERSAL::VERSION' => 1,
23598 );
23599 }
23600
23601 my $callpkg = caller();
23602
23603 if (exists($args{declare})) {
23604 *{$callpkg.'::declare'} =
23605 sub {return $class->declare(shift) }
23606 unless defined(&{$callpkg.'::declare'});
23607 }
23608
23609 if (exists($args{qv})) {
23610 *{$callpkg.'::qv'} =
23611 sub {return $class->qv(shift) }
23612 unless defined(&{$callpkg.'::qv'});
23613 }
23614
23615 if (exists($args{'UNIVERSAL::VERSION'})) {
23616 local $^W;
23617 *UNIVERSAL::VERSION
23618 = \&{$CLASS.'::_VERSION'};
23619 }
23620
23621 if (exists($args{'VERSION'})) {
23622 *{$callpkg.'::VERSION'} = \&{$CLASS.'::_VERSION'};
23623 }
23624
23625 if (exists($args{'is_strict'})) {
23626 *{$callpkg.'::is_strict'} = \&{$CLASS.'::is_strict'}
23627 unless defined(&{$callpkg.'::is_strict'});
23628 }
23629
23630 if (exists($args{'is_lax'})) {
23631 *{$callpkg.'::is_lax'} = \&{$CLASS.'::is_lax'}
23632 unless defined(&{$callpkg.'::is_lax'});
23633 }
23634 }
23635
23636
23637 1;
23638 VERSION
23639  
23640 $fatpacked{"version/regex.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'VERSION_REGEX';
23641 package version::regex;
23642
23643 use strict;
23644
23645 our $VERSION = 0.9929;
23646
23647 #--------------------------------------------------------------------------#
23648 # Version regexp components
23649 #--------------------------------------------------------------------------#
23650
23651 # Fraction part of a decimal version number. This is a common part of
23652 # both strict and lax decimal versions
23653
23654 my $FRACTION_PART = qr/\.[0-9]+/;
23655
23656 # First part of either decimal or dotted-decimal strict version number.
23657 # Unsigned integer with no leading zeroes (except for zero itself) to
23658 # avoid confusion with octal.
23659
23660 my $STRICT_INTEGER_PART = qr/0|[1-9][0-9]*/;
23661
23662 # First part of either decimal or dotted-decimal lax version number.
23663 # Unsigned integer, but allowing leading zeros. Always interpreted
23664 # as decimal. However, some forms of the resulting syntax give odd
23665 # results if used as ordinary Perl expressions, due to how perl treats
23666 # octals. E.g.
23667 # version->new("010" ) == 10
23668 # version->new( 010 ) == 8
23669 # version->new( 010.2) == 82 # "8" . "2"
23670
23671 my $LAX_INTEGER_PART = qr/[0-9]+/;
23672
23673 # Second and subsequent part of a strict dotted-decimal version number.
23674 # Leading zeroes are permitted, and the number is always decimal.
23675 # Limited to three digits to avoid overflow when converting to decimal
23676 # form and also avoid problematic style with excessive leading zeroes.
23677
23678 my $STRICT_DOTTED_DECIMAL_PART = qr/\.[0-9]{1,3}/;
23679
23680 # Second and subsequent part of a lax dotted-decimal version number.
23681 # Leading zeroes are permitted, and the number is always decimal. No
23682 # limit on the numerical value or number of digits, so there is the
23683 # possibility of overflow when converting to decimal form.
23684
23685 my $LAX_DOTTED_DECIMAL_PART = qr/\.[0-9]+/;
23686
23687 # Alpha suffix part of lax version number syntax. Acts like a
23688 # dotted-decimal part.
23689
23690 my $LAX_ALPHA_PART = qr/_[0-9]+/;
23691
23692 #--------------------------------------------------------------------------#
23693 # Strict version regexp definitions
23694 #--------------------------------------------------------------------------#
23695
23696 # Strict decimal version number.
23697
23698 our $STRICT_DECIMAL_VERSION =
23699 qr/ $STRICT_INTEGER_PART $FRACTION_PART? /x;
23700
23701 # Strict dotted-decimal version number. Must have both leading "v" and
23702 # at least three parts, to avoid confusion with decimal syntax.
23703
23704 our $STRICT_DOTTED_DECIMAL_VERSION =
23705 qr/ v $STRICT_INTEGER_PART $STRICT_DOTTED_DECIMAL_PART{2,} /x;
23706
23707 # Complete strict version number syntax -- should generally be used
23708 # anchored: qr/ \A $STRICT \z /x
23709
23710 our $STRICT =
23711 qr/ $STRICT_DECIMAL_VERSION | $STRICT_DOTTED_DECIMAL_VERSION /x;
23712
23713 #--------------------------------------------------------------------------#
23714 # Lax version regexp definitions
23715 #--------------------------------------------------------------------------#
23716
23717 # Lax decimal version number. Just like the strict one except for
23718 # allowing an alpha suffix or allowing a leading or trailing
23719 # decimal-point
23720
23721 our $LAX_DECIMAL_VERSION =
23722 qr/ $LAX_INTEGER_PART (?: $FRACTION_PART | \. )? $LAX_ALPHA_PART?
23723 |
23724 $FRACTION_PART $LAX_ALPHA_PART?
23725 /x;
23726
23727 # Lax dotted-decimal version number. Distinguished by having either
23728 # leading "v" or at least three non-alpha parts. Alpha part is only
23729 # permitted if there are at least two non-alpha parts. Strangely
23730 # enough, without the leading "v", Perl takes .1.2 to mean v0.1.2,
23731 # so when there is no "v", the leading part is optional
23732
23733 our $LAX_DOTTED_DECIMAL_VERSION =
23734 qr/
23735 v $LAX_INTEGER_PART (?: $LAX_DOTTED_DECIMAL_PART+ $LAX_ALPHA_PART? )?
23736 |
23737 $LAX_INTEGER_PART? $LAX_DOTTED_DECIMAL_PART{2,} $LAX_ALPHA_PART?
23738 /x;
23739
23740 # Complete lax version number syntax -- should generally be used
23741 # anchored: qr/ \A $LAX \z /x
23742 #
23743 # The string 'undef' is a special case to make for easier handling
23744 # of return values from ExtUtils::MM->parse_version
23745
23746 our $LAX =
23747 qr/ undef | $LAX_DOTTED_DECIMAL_VERSION | $LAX_DECIMAL_VERSION /x;
23748
23749 #--------------------------------------------------------------------------#
23750
23751 # Preloaded methods go here.
23752 sub is_strict { defined $_[0] && $_[0] =~ qr/ \A $STRICT \z /x }
23753 sub is_lax { defined $_[0] && $_[0] =~ qr/ \A $LAX \z /x }
23754
23755 1;
23756 VERSION_REGEX
23757  
23758 $fatpacked{"version/vpp.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'VERSION_VPP';
23759 package charstar;
23760 # a little helper class to emulate C char* semantics in Perl
23761 # so that prescan_version can use the same code as in C
23762
23763 use overload (
23764 '""' => \&thischar,
23765 '0+' => \&thischar,
23766 '++' => \&increment,
23767 '--' => \&decrement,
23768 '+' => \&plus,
23769 '-' => \&minus,
23770 '*' => \&multiply,
23771 'cmp' => \&cmp,
23772 '<=>' => \&spaceship,
23773 'bool' => \&thischar,
23774 '=' => \&clone,
23775 );
23776
23777 sub new {
23778 my ($self, $string) = @_;
23779 my $class = ref($self) || $self;
23780
23781 my $obj = {
23782 string => [split(//,$string)],
23783 current => 0,
23784 };
23785 return bless $obj, $class;
23786 }
23787
23788 sub thischar {
23789 my ($self) = @_;
23790 my $last = $#{$self->{string}};
23791 my $curr = $self->{current};
23792 if ($curr >= 0 && $curr <= $last) {
23793 return $self->{string}->[$curr];
23794 }
23795 else {
23796 return '';
23797 }
23798 }
23799
23800 sub increment {
23801 my ($self) = @_;
23802 $self->{current}++;
23803 }
23804
23805 sub decrement {
23806 my ($self) = @_;
23807 $self->{current}--;
23808 }
23809
23810 sub plus {
23811 my ($self, $offset) = @_;
23812 my $rself = $self->clone;
23813 $rself->{current} += $offset;
23814 return $rself;
23815 }
23816
23817 sub minus {
23818 my ($self, $offset) = @_;
23819 my $rself = $self->clone;
23820 $rself->{current} -= $offset;
23821 return $rself;
23822 }
23823
23824 sub multiply {
23825 my ($left, $right, $swapped) = @_;
23826 my $char = $left->thischar();
23827 return $char * $right;
23828 }
23829
23830 sub spaceship {
23831 my ($left, $right, $swapped) = @_;
23832 unless (ref($right)) { # not an object already
23833 $right = $left->new($right);
23834 }
23835 return $left->{current} <=> $right->{current};
23836 }
23837
23838 sub cmp {
23839 my ($left, $right, $swapped) = @_;
23840 unless (ref($right)) { # not an object already
23841 if (length($right) == 1) { # comparing single character only
23842 return $left->thischar cmp $right;
23843 }
23844 $right = $left->new($right);
23845 }
23846 return $left->currstr cmp $right->currstr;
23847 }
23848
23849 sub bool {
23850 my ($self) = @_;
23851 my $char = $self->thischar;
23852 return ($char ne '');
23853 }
23854
23855 sub clone {
23856 my ($left, $right, $swapped) = @_;
23857 $right = {
23858 string => [@{$left->{string}}],
23859 current => $left->{current},
23860 };
23861 return bless $right, ref($left);
23862 }
23863
23864 sub currstr {
23865 my ($self, $s) = @_;
23866 my $curr = $self->{current};
23867 my $last = $#{$self->{string}};
23868 if (defined($s) && $s->{current} < $last) {
23869 $last = $s->{current};
23870 }
23871
23872 my $string = join('', @{$self->{string}}[$curr..$last]);
23873 return $string;
23874 }
23875
23876 package version::vpp;
23877
23878 use 5.006002;
23879 use strict;
23880 use warnings::register;
23881
23882 use Config;
23883
23884 our $VERSION = 0.9929;
23885 our $CLASS = 'version::vpp';
23886 our ($LAX, $STRICT, $WARN_CATEGORY);
23887
23888 if ($] > 5.015) {
23889 warnings::register_categories(qw/version/);
23890 $WARN_CATEGORY = 'version';
23891 } else {
23892 $WARN_CATEGORY = 'numeric';
23893 }
23894
23895 require version::regex;
23896 *version::vpp::is_strict = \&version::regex::is_strict;
23897 *version::vpp::is_lax = \&version::regex::is_lax;
23898 *LAX = \$version::regex::LAX;
23899 *STRICT = \$version::regex::STRICT;
23900
23901 use overload (
23902 '""' => \&stringify,
23903 '0+' => \&numify,
23904 'cmp' => \&vcmp,
23905 '<=>' => \&vcmp,
23906 'bool' => \&vbool,
23907 '+' => \&vnoop,
23908 '-' => \&vnoop,
23909 '*' => \&vnoop,
23910 '/' => \&vnoop,
23911 '+=' => \&vnoop,
23912 '-=' => \&vnoop,
23913 '*=' => \&vnoop,
23914 '/=' => \&vnoop,
23915 'abs' => \&vnoop,
23916 );
23917
23918 sub import {
23919 no strict 'refs';
23920 my ($class) = shift;
23921
23922 # Set up any derived class
23923 unless ($class eq $CLASS) {
23924 local $^W;
23925 *{$class.'::declare'} = \&{$CLASS.'::declare'};
23926 *{$class.'::qv'} = \&{$CLASS.'::qv'};
23927 }
23928
23929 my %args;
23930 if (@_) { # any remaining terms are arguments
23931 map { $args{$_} = 1 } @_
23932 }
23933 else { # no parameters at all on use line
23934 %args =
23935 (
23936 qv => 1,
23937 'UNIVERSAL::VERSION' => 1,
23938 );
23939 }
23940
23941 my $callpkg = caller();
23942
23943 if (exists($args{declare})) {
23944 *{$callpkg.'::declare'} =
23945 sub {return $class->declare(shift) }
23946 unless defined(&{$callpkg.'::declare'});
23947 }
23948
23949 if (exists($args{qv})) {
23950 *{$callpkg.'::qv'} =
23951 sub {return $class->qv(shift) }
23952 unless defined(&{$callpkg.'::qv'});
23953 }
23954
23955 if (exists($args{'UNIVERSAL::VERSION'})) {
23956 no warnings qw/redefine/;
23957 *UNIVERSAL::VERSION
23958 = \&{$CLASS.'::_VERSION'};
23959 }
23960
23961 if (exists($args{'VERSION'})) {
23962 *{$callpkg.'::VERSION'} = \&{$CLASS.'::_VERSION'};
23963 }
23964
23965 if (exists($args{'is_strict'})) {
23966 *{$callpkg.'::is_strict'} = \&{$CLASS.'::is_strict'}
23967 unless defined(&{$callpkg.'::is_strict'});
23968 }
23969
23970 if (exists($args{'is_lax'})) {
23971 *{$callpkg.'::is_lax'} = \&{$CLASS.'::is_lax'}
23972 unless defined(&{$callpkg.'::is_lax'});
23973 }
23974 }
23975
23976 my $VERSION_MAX = 0x7FFFFFFF;
23977
23978 # implement prescan_version as closely to the C version as possible
23979 use constant TRUE => 1;
23980 use constant FALSE => 0;
23981
23982 sub isDIGIT {
23983 my ($char) = shift->thischar();
23984 return ($char =~ /\d/);
23985 }
23986
23987 sub isALPHA {
23988 my ($char) = shift->thischar();
23989 return ($char =~ /[a-zA-Z]/);
23990 }
23991
23992 sub isSPACE {
23993 my ($char) = shift->thischar();
23994 return ($char =~ /\s/);
23995 }
23996
23997 sub BADVERSION {
23998 my ($s, $errstr, $error) = @_;
23999 if ($errstr) {
24000 $$errstr = $error;
24001 }
24002 return $s;
24003 }
24004
24005 sub prescan_version {
24006 my ($s, $strict, $errstr, $sqv, $ssaw_decimal, $swidth, $salpha) = @_;
24007 my $qv = defined $sqv ? $$sqv : FALSE;
24008 my $saw_decimal = defined $ssaw_decimal ? $$ssaw_decimal : 0;
24009 my $width = defined $swidth ? $$swidth : 3;
24010 my $alpha = defined $salpha ? $$salpha : FALSE;
24011
24012 my $d = $s;
24013
24014 if ($qv && isDIGIT($d)) {
24015 goto dotted_decimal_version;
24016 }
24017
24018 if ($d eq 'v') { # explicit v-string
24019 $d++;
24020 if (isDIGIT($d)) {
24021 $qv = TRUE;
24022 }
24023 else { # degenerate v-string
24024 # requires v1.2.3
24025 return BADVERSION($s,$errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
24026 }
24027
24028 dotted_decimal_version:
24029 if ($strict && $d eq '0' && isDIGIT($d+1)) {
24030 # no leading zeros allowed
24031 return BADVERSION($s,$errstr,"Invalid version format (no leading zeros)");
24032 }
24033
24034 while (isDIGIT($d)) { # integer part
24035 $d++;
24036 }
24037
24038 if ($d eq '.')
24039 {
24040 $saw_decimal++;
24041 $d++; # decimal point
24042 }
24043 else
24044 {
24045 if ($strict) {
24046 # require v1.2.3
24047 return BADVERSION($s,$errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
24048 }
24049 else {
24050 goto version_prescan_finish;
24051 }
24052 }
24053
24054 {
24055 my $i = 0;
24056 my $j = 0;
24057 while (isDIGIT($d)) { # just keep reading
24058 $i++;
24059 while (isDIGIT($d)) {
24060 $d++; $j++;
24061 # maximum 3 digits between decimal
24062 if ($strict && $j > 3) {
24063 return BADVERSION($s,$errstr,"Invalid version format (maximum 3 digits between decimals)");
24064 }
24065 }
24066 if ($d eq '_') {
24067 if ($strict) {
24068 return BADVERSION($s,$errstr,"Invalid version format (no underscores)");
24069 }
24070 if ( $alpha ) {
24071 return BADVERSION($s,$errstr,"Invalid version format (multiple underscores)");
24072 }
24073 $d++;
24074 $alpha = TRUE;
24075 }
24076 elsif ($d eq '.') {
24077 if ($alpha) {
24078 return BADVERSION($s,$errstr,"Invalid version format (underscores before decimal)");
24079 }
24080 $saw_decimal++;
24081 $d++;
24082 }
24083 elsif (!isDIGIT($d)) {
24084 last;
24085 }
24086 $j = 0;
24087 }
24088
24089 if ($strict && $i < 2) {
24090 # requires v1.2.3
24091 return BADVERSION($s,$errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
24092 }
24093 }
24094 } # end if dotted-decimal
24095 else
24096 { # decimal versions
24097 my $j = 0;
24098 # special $strict case for leading '.' or '0'
24099 if ($strict) {
24100 if ($d eq '.') {
24101 return BADVERSION($s,$errstr,"Invalid version format (0 before decimal required)");
24102 }
24103 if ($d eq '0' && isDIGIT($d+1)) {
24104 return BADVERSION($s,$errstr,"Invalid version format (no leading zeros)");
24105 }
24106 }
24107
24108 # and we never support negative version numbers
24109 if ($d eq '-') {
24110 return BADVERSION($s,$errstr,"Invalid version format (negative version number)");
24111 }
24112
24113 # consume all of the integer part
24114 while (isDIGIT($d)) {
24115 $d++;
24116 }
24117
24118 # look for a fractional part
24119 if ($d eq '.') {
24120 # we found it, so consume it
24121 $saw_decimal++;
24122 $d++;
24123 }
24124 elsif (!$d || $d eq ';' || isSPACE($d) || $d eq '}') {
24125 if ( $d == $s ) {
24126 # found nothing
24127 return BADVERSION($s,$errstr,"Invalid version format (version required)");
24128 }
24129 # found just an integer
24130 goto version_prescan_finish;
24131 }
24132 elsif ( $d == $s ) {
24133 # didn't find either integer or period
24134 return BADVERSION($s,$errstr,"Invalid version format (non-numeric data)");
24135 }
24136 elsif ($d eq '_') {
24137 # underscore can't come after integer part
24138 if ($strict) {
24139 return BADVERSION($s,$errstr,"Invalid version format (no underscores)");
24140 }
24141 elsif (isDIGIT($d+1)) {
24142 return BADVERSION($s,$errstr,"Invalid version format (alpha without decimal)");
24143 }
24144 else {
24145 return BADVERSION($s,$errstr,"Invalid version format (misplaced underscore)");
24146 }
24147 }
24148 elsif ($d) {
24149 # anything else after integer part is just invalid data
24150 return BADVERSION($s,$errstr,"Invalid version format (non-numeric data)");
24151 }
24152
24153 # scan the fractional part after the decimal point
24154 if ($d && !isDIGIT($d) && ($strict || ! ($d eq ';' || isSPACE($d) || $d eq '}') )) {
24155 # $strict or lax-but-not-the-end
24156 return BADVERSION($s,$errstr,"Invalid version format (fractional part required)");
24157 }
24158
24159 while (isDIGIT($d)) {
24160 $d++; $j++;
24161 if ($d eq '.' && isDIGIT($d-1)) {
24162 if ($alpha) {
24163 return BADVERSION($s,$errstr,"Invalid version format (underscores before decimal)");
24164 }
24165 if ($strict) {
24166 return BADVERSION($s,$errstr,"Invalid version format (dotted-decimal versions must begin with 'v')");
24167 }
24168 $d = $s; # start all over again
24169 $qv = TRUE;
24170 goto dotted_decimal_version;
24171 }
24172 if ($d eq '_') {
24173 if ($strict) {
24174 return BADVERSION($s,$errstr,"Invalid version format (no underscores)");
24175 }
24176 if ( $alpha ) {
24177 return BADVERSION($s,$errstr,"Invalid version format (multiple underscores)");
24178 }
24179 if ( ! isDIGIT($d+1) ) {
24180 return BADVERSION($s,$errstr,"Invalid version format (misplaced underscore)");
24181 }
24182 $width = $j;
24183 $d++;
24184 $alpha = TRUE;
24185 }
24186 }
24187 }
24188
24189 version_prescan_finish:
24190 while (isSPACE($d)) {
24191 $d++;
24192 }
24193
24194 if ($d && !isDIGIT($d) && (! ($d eq ';' || $d eq '}') )) {
24195 # trailing non-numeric data
24196 return BADVERSION($s,$errstr,"Invalid version format (non-numeric data)");
24197 }
24198 if ($saw_decimal > 1 && ($d-1) eq '.') {
24199 # no trailing period allowed
24200 return BADVERSION($s,$errstr,"Invalid version format (trailing decimal)");
24201 }
24202
24203 if (defined $sqv) {
24204 $$sqv = $qv;
24205 }
24206 if (defined $swidth) {
24207 $$swidth = $width;
24208 }
24209 if (defined $ssaw_decimal) {
24210 $$ssaw_decimal = $saw_decimal;
24211 }
24212 if (defined $salpha) {
24213 $$salpha = $alpha;
24214 }
24215 return $d;
24216 }
24217
24218 sub scan_version {
24219 my ($s, $rv, $qv) = @_;
24220 my $start;
24221 my $pos;
24222 my $last;
24223 my $errstr;
24224 my $saw_decimal = 0;
24225 my $width = 3;
24226 my $alpha = FALSE;
24227 my $vinf = FALSE;
24228 my @av;
24229
24230 $s = new charstar $s;
24231
24232 while (isSPACE($s)) { # leading whitespace is OK
24233 $s++;
24234 }
24235
24236 $last = prescan_version($s, FALSE, \$errstr, \$qv, \$saw_decimal,
24237 \$width, \$alpha);
24238
24239 if ($errstr) {
24240 # 'undef' is a special case and not an error
24241 if ( $s ne 'undef') {
24242 require Carp;
24243 Carp::croak($errstr);
24244 }
24245 }
24246
24247 $start = $s;
24248 if ($s eq 'v') {
24249 $s++;
24250 }
24251 $pos = $s;
24252
24253 if ( $qv ) {
24254 $$rv->{qv} = $qv;
24255 }
24256 if ( $alpha ) {
24257 $$rv->{alpha} = $alpha;
24258 }
24259 if ( !$qv && $width < 3 ) {
24260 $$rv->{width} = $width;
24261 }
24262
24263 while (isDIGIT($pos) || $pos eq '_') {
24264 $pos++;
24265 }
24266 if (!isALPHA($pos)) {
24267 my $rev;
24268
24269 for (;;) {
24270 $rev = 0;
24271 {
24272 # this is atoi() that delimits on underscores
24273 my $end = $pos;
24274 my $mult = 1;
24275 my $orev;
24276
24277 # the following if() will only be true after the decimal
24278 # point of a version originally created with a bare
24279 # floating point number, i.e. not quoted in any way
24280 #
24281 if ( !$qv && $s > $start && $saw_decimal == 1 ) {
24282 $mult *= 100;
24283 while ( $s < $end ) {
24284 next if $s eq '_';
24285 $orev = $rev;
24286 $rev += $s * $mult;
24287 $mult /= 10;
24288 if ( (abs($orev) > abs($rev))
24289 || (abs($rev) > $VERSION_MAX )) {
24290 warn("Integer overflow in version %d",
24291 $VERSION_MAX);
24292 $s = $end - 1;
24293 $rev = $VERSION_MAX;
24294 $vinf = 1;
24295 }
24296 $s++;
24297 if ( $s eq '_' ) {
24298 $s++;
24299 }
24300 }
24301 }
24302 else {
24303 while (--$end >= $s) {
24304 next if $end eq '_';
24305 $orev = $rev;
24306 $rev += $end * $mult;
24307 $mult *= 10;
24308 if ( (abs($orev) > abs($rev))
24309 || (abs($rev) > $VERSION_MAX )) {
24310 warn("Integer overflow in version");
24311 $end = $s - 1;
24312 $rev = $VERSION_MAX;
24313 $vinf = 1;
24314 }
24315 }
24316 }
24317 }
24318
24319 # Append revision
24320 push @av, $rev;
24321 if ( $vinf ) {
24322 $s = $last;
24323 last;
24324 }
24325 elsif ( $pos eq '.' ) {
24326 $s = ++$pos;
24327 }
24328 elsif ( $pos eq '_' && isDIGIT($pos+1) ) {
24329 $s = ++$pos;
24330 }
24331 elsif ( $pos eq ',' && isDIGIT($pos+1) ) {
24332 $s = ++$pos;
24333 }
24334 elsif ( isDIGIT($pos) ) {
24335 $s = $pos;
24336 }
24337 else {
24338 $s = $pos;
24339 last;
24340 }
24341 if ( $qv ) {
24342 while ( isDIGIT($pos) || $pos eq '_') {
24343 $pos++;
24344 }
24345 }
24346 else {
24347 my $digits = 0;
24348 while ( ( isDIGIT($pos) || $pos eq '_' ) && $digits < 3 ) {
24349 if ( $pos ne '_' ) {
24350 $digits++;
24351 }
24352 $pos++;
24353 }
24354 }
24355 }
24356 }
24357 if ( $qv ) { # quoted versions always get at least three terms
24358 my $len = $#av;
24359 # This for loop appears to trigger a compiler bug on OS X, as it
24360 # loops infinitely. Yes, len is negative. No, it makes no sense.
24361 # Compiler in question is:
24362 # gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
24363 # for ( len = 2 - len; len > 0; len-- )
24364 # av_push(MUTABLE_AV(sv), newSViv(0));
24365 #
24366 $len = 2 - $len;
24367 while ($len-- > 0) {
24368 push @av, 0;
24369 }
24370 }
24371
24372 # need to save off the current version string for later
24373 if ( $vinf ) {
24374 $$rv->{original} = "v.Inf";
24375 $$rv->{vinf} = 1;
24376 }
24377 elsif ( $s > $start ) {
24378 $$rv->{original} = $start->currstr($s);
24379 if ( $qv && $saw_decimal == 1 && $start ne 'v' ) {
24380 # need to insert a v to be consistent
24381 $$rv->{original} = 'v' . $$rv->{original};
24382 }
24383 }
24384 else {
24385 $$rv->{original} = '0';
24386 push(@av, 0);
24387 }
24388
24389 # And finally, store the AV in the hash
24390 $$rv->{version} = \@av;
24391
24392 # fix RT#19517 - special case 'undef' as string
24393 if ($s eq 'undef') {
24394 $s += 5;
24395 }
24396
24397 return $s;
24398 }
24399
24400 sub new {
24401 my $class = shift;
24402 unless (defined $class or $#_ > 1) {
24403 require Carp;
24404 Carp::croak('Usage: version::new(class, version)');
24405 }
24406
24407 my $self = bless ({}, ref ($class) || $class);
24408 my $qv = FALSE;
24409
24410 if ( $#_ == 1 ) { # must be CVS-style
24411 $qv = TRUE;
24412 }
24413 my $value = pop; # always going to be the last element
24414
24415 if ( ref($value) && eval('$value->isa("version")') ) {
24416 # Can copy the elements directly
24417 $self->{version} = [ @{$value->{version} } ];
24418 $self->{qv} = 1 if $value->{qv};
24419 $self->{alpha} = 1 if $value->{alpha};
24420 $self->{original} = ''.$value->{original};
24421 return $self;
24422 }
24423
24424 if ( not defined $value or $value =~ /^undef$/ ) {
24425 # RT #19517 - special case for undef comparison
24426 # or someone forgot to pass a value
24427 push @{$self->{version}}, 0;
24428 $self->{original} = "0";
24429 return ($self);
24430 }
24431
24432
24433 if (ref($value) =~ m/ARRAY|HASH/) {
24434 require Carp;
24435 Carp::croak("Invalid version format (non-numeric data)");
24436 }
24437
24438 $value = _un_vstring($value);
24439
24440 if ($Config{d_setlocale}) {
24441 use POSIX qw/locale_h/;
24442 use if $Config{d_setlocale}, 'locale';
24443 my $currlocale = setlocale(LC_ALL);
24444
24445 # if the current locale uses commas for decimal points, we
24446 # just replace commas with decimal places, rather than changing
24447 # locales
24448 if ( localeconv()->{decimal_point} eq ',' ) {
24449 $value =~ tr/,/./;
24450 }
24451 }
24452
24453 # exponential notation
24454 if ( $value =~ /\d+.?\d*e[-+]?\d+/ ) {
24455 $value = sprintf("%.9f",$value);
24456 $value =~ s/(0+)$//; # trim trailing zeros
24457 }
24458
24459 my $s = scan_version($value, \$self, $qv);
24460
24461 if ($s) { # must be something left over
24462 warn(sprintf "Version string '%s' contains invalid data; "
24463 ."ignoring: '%s'", $value, $s);
24464 }
24465
24466 return ($self);
24467 }
24468
24469 *parse = \&new;
24470
24471 sub numify {
24472 my ($self) = @_;
24473 unless (_verify($self)) {
24474 require Carp;
24475 Carp::croak("Invalid version object");
24476 }
24477 my $alpha = $self->{alpha} || "";
24478 my $len = $#{$self->{version}};
24479 my $digit = $self->{version}[0];
24480 my $string = sprintf("%d.", $digit );
24481
24482 if ($alpha and warnings::enabled()) {
24483 warnings::warn($WARN_CATEGORY, 'alpha->numify() is lossy');
24484 }
24485
24486 for ( my $i = 1 ; $i <= $len ; $i++ ) {
24487 $digit = $self->{version}[$i];
24488 $string .= sprintf("%03d", $digit);
24489 }
24490
24491 if ( $len == 0 ) {
24492 $string .= sprintf("000");
24493 }
24494
24495 return $string;
24496 }
24497
24498 sub normal {
24499 my ($self) = @_;
24500 unless (_verify($self)) {
24501 require Carp;
24502 Carp::croak("Invalid version object");
24503 }
24504
24505 my $len = $#{$self->{version}};
24506 my $digit = $self->{version}[0];
24507 my $string = sprintf("v%d", $digit );
24508
24509 for ( my $i = 1 ; $i <= $len ; $i++ ) {
24510 $digit = $self->{version}[$i];
24511 $string .= sprintf(".%d", $digit);
24512 }
24513
24514 if ( $len <= 2 ) {
24515 for ( $len = 2 - $len; $len != 0; $len-- ) {
24516 $string .= sprintf(".%0d", 0);
24517 }
24518 }
24519
24520 return $string;
24521 }
24522
24523 sub stringify {
24524 my ($self) = @_;
24525 unless (_verify($self)) {
24526 require Carp;
24527 Carp::croak("Invalid version object");
24528 }
24529 return exists $self->{original}
24530 ? $self->{original}
24531 : exists $self->{qv}
24532 ? $self->normal
24533 : $self->numify;
24534 }
24535
24536 sub vcmp {
24537 my ($left,$right,$swap) = @_;
24538 die "Usage: version::vcmp(lobj, robj, ...)" if @_ < 2;
24539 my $class = ref($left);
24540 unless ( UNIVERSAL::isa($right, $class) ) {
24541 $right = $class->new($right);
24542 }
24543
24544 if ( $swap ) {
24545 ($left, $right) = ($right, $left);
24546 }
24547 unless (_verify($left)) {
24548 require Carp;
24549 Carp::croak("Invalid version object");
24550 }
24551 unless (_verify($right)) {
24552 require Carp;
24553 Carp::croak("Invalid version format");
24554 }
24555 my $l = $#{$left->{version}};
24556 my $r = $#{$right->{version}};
24557 my $m = $l < $r ? $l : $r;
24558 my $lalpha = $left->is_alpha;
24559 my $ralpha = $right->is_alpha;
24560 my $retval = 0;
24561 my $i = 0;
24562 while ( $i <= $m && $retval == 0 ) {
24563 $retval = $left->{version}[$i] <=> $right->{version}[$i];
24564 $i++;
24565 }
24566
24567 # possible match except for trailing 0's
24568 if ( $retval == 0 && $l != $r ) {
24569 if ( $l < $r ) {
24570 while ( $i <= $r && $retval == 0 ) {
24571 if ( $right->{version}[$i] != 0 ) {
24572 $retval = -1; # not a match after all
24573 }
24574 $i++;
24575 }
24576 }
24577 else {
24578 while ( $i <= $l && $retval == 0 ) {
24579 if ( $left->{version}[$i] != 0 ) {
24580 $retval = +1; # not a match after all
24581 }
24582 $i++;
24583 }
24584 }
24585 }
24586
24587 return $retval;
24588 }
24589
24590 sub vbool {
24591 my ($self) = @_;
24592 return vcmp($self,$self->new("0"),1);
24593 }
24594
24595 sub vnoop {
24596 require Carp;
24597 Carp::croak("operation not supported with version object");
24598 }
24599
24600 sub is_alpha {
24601 my ($self) = @_;
24602 return (exists $self->{alpha});
24603 }
24604
24605 sub qv {
24606 my $value = shift;
24607 my $class = $CLASS;
24608 if (@_) {
24609 $class = ref($value) || $value;
24610 $value = shift;
24611 }
24612
24613 $value = _un_vstring($value);
24614 $value = 'v'.$value unless $value =~ /(^v|\d+\.\d+\.\d)/;
24615 my $obj = $CLASS->new($value);
24616 return bless $obj, $class;
24617 }
24618
24619 *declare = \&qv;
24620
24621 sub is_qv {
24622 my ($self) = @_;
24623 return (exists $self->{qv});
24624 }
24625
24626
24627 sub _verify {
24628 my ($self) = @_;
24629 if ( ref($self)
24630 && eval { exists $self->{version} }
24631 && ref($self->{version}) eq 'ARRAY'
24632 ) {
24633 return 1;
24634 }
24635 else {
24636 return 0;
24637 }
24638 }
24639
24640 sub _is_non_alphanumeric {
24641 my $s = shift;
24642 $s = new charstar $s;
24643 while ($s) {
24644 return 0 if isSPACE($s); # early out
24645 return 1 unless (isALPHA($s) || isDIGIT($s) || $s =~ /[.-]/);
24646 $s++;
24647 }
24648 return 0;
24649 }
24650
24651 sub _un_vstring {
24652 my $value = shift;
24653 # may be a v-string
24654 if ( length($value) >= 1 && $value !~ /[,._]/
24655 && _is_non_alphanumeric($value)) {
24656 my $tvalue;
24657 if ( $] >= 5.008_001 ) {
24658 $tvalue = _find_magic_vstring($value);
24659 $value = $tvalue if length $tvalue;
24660 }
24661 elsif ( $] >= 5.006_000 ) {
24662 $tvalue = sprintf("v%vd",$value);
24663 if ( $tvalue =~ /^v\d+(\.\d+)*$/ ) {
24664 # must be a v-string
24665 $value = $tvalue;
24666 }
24667 }
24668 }
24669 return $value;
24670 }
24671
24672 sub _find_magic_vstring {
24673 my $value = shift;
24674 my $tvalue = '';
24675 require B;
24676 my $sv = B::svref_2object(\$value);
24677 my $magic = ref($sv) eq 'B::PVMG' ? $sv->MAGIC : undef;
24678 while ( $magic ) {
24679 if ( $magic->TYPE eq 'V' ) {
24680 $tvalue = $magic->PTR;
24681 $tvalue =~ s/^v?(.+)$/v$1/;
24682 last;
24683 }
24684 else {
24685 $magic = $magic->MOREMAGIC;
24686 }
24687 }
24688 $tvalue =~ tr/_//d;
24689 return $tvalue;
24690 }
24691
24692 sub _VERSION {
24693 my ($obj, $req) = @_;
24694 my $class = ref($obj) || $obj;
24695
24696 no strict 'refs';
24697 if ( exists $INC{"$class.pm"} and not %{"$class\::"} and $] >= 5.008) {
24698 # file but no package
24699 require Carp;
24700 Carp::croak( "$class defines neither package nor VERSION"
24701 ."--version check failed");
24702 }
24703
24704 my $version = eval "\$$class\::VERSION";
24705 if ( defined $version ) {
24706 local $^W if $] <= 5.008;
24707 $version = version::vpp->new($version);
24708 }
24709
24710 if ( defined $req ) {
24711 unless ( defined $version ) {
24712 require Carp;
24713 my $msg = $] < 5.006
24714 ? "$class version $req required--this is only version "
24715 : "$class does not define \$$class\::VERSION"
24716 ."--version check failed";
24717
24718 if ( $ENV{VERSION_DEBUG} ) {
24719 Carp::confess($msg);
24720 }
24721 else {
24722 Carp::croak($msg);
24723 }
24724 }
24725
24726 $req = version::vpp->new($req);
24727
24728 if ( $req > $version ) {
24729 require Carp;
24730 if ( $req->is_qv ) {
24731 Carp::croak(
24732 sprintf ("%s version %s required--".
24733 "this is only version %s", $class,
24734 $req->normal, $version->normal)
24735 );
24736 }
24737 else {
24738 Carp::croak(
24739 sprintf ("%s version %s required--".
24740 "this is only version %s", $class,
24741 $req->stringify, $version->stringify)
24742 );
24743 }
24744 }
24745 }
24746
24747 return defined $version ? $version->stringify : undef;
24748 }
24749
24750 1; #this line is important and will help the module return a true value
24751 VERSION_VPP
24752  
24753 s/^ //mg for values %fatpacked;
24754  
24755 my $class = 'FatPacked::'.(0+\%fatpacked);
24756 no strict 'refs';
24757 *{"${class}::files"} = sub { keys %{$_[0]} };
24758  
24759 if ($] < 5.008) {
24760 *{"${class}::INC"} = sub {
24761 if (my $fat = $_[0]{$_[1]}) {
24762 my $pos = 0;
24763 my $last = length $fat;
24764 return (sub {
24765 return 0 if $pos == $last;
24766 my $next = (1 + index $fat, "\n", $pos) || $last;
24767 $_ .= substr $fat, $pos, $next - $pos;
24768 $pos = $next;
24769 return 1;
24770 });
24771 }
24772 };
24773 }
24774  
24775 else {
24776 *{"${class}::INC"} = sub {
24777 if (my $fat = $_[0]{$_[1]}) {
24778 open my $fh, '<', \$fat
24779 or die "FatPacker error loading $_[1] (could be a perl installation issue?)";
24780 return $fh;
24781 }
24782 return;
24783 };
24784 }
24785  
24786 unshift @INC, bless \%fatpacked, $class;
24787 } # END OF FATPACK CODE
24788  
24789  
24790  
24791 use strict;
24792 use App::cpanminus::script;
24793  
24794  
24795 unless (caller) {
24796 my $app = App::cpanminus::script->new;
24797 $app->parse_options(@ARGV);
24798 exit $app->doit;
24799 }
24800  
24801 __END__