don't bake lists if not asked to remove anything
[p5sagit/local-lib.git] / lib / local / lib.pm
CommitLineData
b5cc15f7 1use strict;
2use warnings;
3
4package local::lib;
5
387f8022 6use 5.006;
b5cc15f7 7
8use File::Spec ();
b5cc15f7 9use Config;
10
7c0e6b54 11our $VERSION = '1.008026'; # 1.8.26
d04dfa50 12$VERSION = eval $VERSION;
1f8043c8 13
b5cc15f7 14sub import {
0fb70b9a 15 my ($class, @args) = @_;
16
e4b5a839 17 my @steps;
db6f44a9 18 my %opts;
e4892f2b 19
e4b5a839 20 while (@args) {
21 my $arg = shift @args;
b9c94c15 22 # check for lethal dash first to stop processing before causing problems
5eff9c24 23 # the fancy dash is U+2212 or \xE2\x88\x92
24 if ($arg =~ /\xE2\x88\x92/ or $arg =~ /−/) {
d4dbe584 25 die <<'DEATH';
26WHOA THERE! It looks like you've got some fancy dashes in your commandline!
27These are *not* the traditional -- dashes that software recognizes. You
28probably got these by copy-pasting from the perldoc for this module as
29rendered by a UTF8-capable formatter. This most typically happens on an OS X
30terminal, but can happen elsewhere too. Please try again after replacing the
31dashes with normal minus signs.
32DEATH
b9c94c15 33 }
e4b5a839 34 elsif ($arg eq '--self-contained') {
35 die "FATAL: The local::lib --self-contained flag has never worked reliably and the original author, Mark Stosberg, was unable or unwilling to maintain it. As such, this flag has been removed from the local::lib codebase in order to prevent misunderstandings and potentially broken builds. The local::lib authors recommend that you look at the lib::core::only module shipped with this distribution in order to create a more robust environment that is equivalent to what --self-contained provided (although quite possibly not what you originally thought it provided due to the poor quality of the documentation, for which we apologise).\n";
36 }
939821af 37 elsif( $arg =~ /^--deactivate(?:=(.*))?$/ ) {
38 my $path = defined $1 ? $1 : shift @args;
e4b5a839 39 push @steps, ['deactivate', $path];
b9c94c15 40 }
e4b5a839 41 elsif ( $arg eq '--deactivate-all' ) {
42 push @steps, ['deactivate_all'];
43 }
db6f44a9 44 elsif ( $arg =~ /^--shelltype(?:=(.*))?$/ ) {
45 my $shell = defined $1 ? $1 : shift @args;
46 $opts{shelltype} = $shell;
47 }
80816e53 48 elsif ( $arg eq '--no-create' ) {
49 $opts{no_create} = 1;
50 }
e4b5a839 51 elsif ( $arg =~ /^--/ ) {
b9c94c15 52 die "Unknown import argument: $arg";
53 }
54 else {
e4b5a839 55 push @steps, ['activate', $arg];
b9c94c15 56 }
d4dbe584 57 }
e4b5a839 58 if (!@steps) {
59 push @steps, ['activate', undef];
60 }
61
db6f44a9 62 my $self = $class->new(%opts);
e4b5a839 63
64 for (@steps) {
65 my ($method, @args) = @$_;
66 $self = $self->$method(@args);
67 }
68
69 if ($0 eq '-') {
70 $self->print_environment_vars_for;
71 exit 0;
72 }
73 else {
74 $self->setup_local_lib_for;
75 }
76}
77
78sub new {
79 my $class = shift;
80 bless {@_}, $class;
81}
82
83sub clone {
84 my $self = shift;
85 bless {%$self, @_}, ref $self;
86}
87
88sub inc { $_[0]->{inc} ||= \@INC }
89sub libs { $_[0]->{libs} ||= [ \'PERL5LIB' ] }
90sub bins { $_[0]->{bins} ||= [ \'PATH' ] }
91sub roots { $_[0]->{roots} ||= [ \'PERL_LOCAL_LIB_ROOT' ] }
92sub extra { $_[0]->{extra} ||= {} }
93sub shelltype { $_[0]->{shelltype} ||= $_[0]->guess_shelltype }
80816e53 94sub no_create { $_[0]->{no_create} }
e4b5a839 95
96my $_archname = $Config{archname};
97my $_version = $Config{version};
98my @_inc_version_list = reverse split / /, $Config{inc_version_list};
99my $_path_sep = $Config{path_sep};
100
101sub _as_list {
102 my $list = shift;
103 grep length, map {
104 !(ref $_ && ref $_ eq 'SCALAR') ? $_ : (
105 defined $ENV{$$_} ? split(/\Q$_path_sep/, $ENV{$$_})
106 : ()
107 )
108 } ref $list ? @$list : $list;
109}
110sub _remove_from {
111 my ($list, @remove) = @_;
779c192a 112 return @$list
113 if !@remove;
e4b5a839 114 my %remove = map { $_ => 1 } @remove;
115 grep !$remove{$_}, _as_list($list);
116}
117
118my @_lib_subdirs = (
119 [$_version, $_archname],
120 [$_version],
121 [$_archname],
122 (@_inc_version_list ? \@_inc_version_list : ()),
123 [],
124);
125
126sub install_base_bin_path {
127 my ($class, $path) = @_;
128 return File::Spec->catdir($path, 'bin');
129}
130sub install_base_perl_path {
131 my ($class, $path) = @_;
132 return File::Spec->catdir($path, 'lib', 'perl5');
133}
134sub install_base_arch_path {
135 my ($class, $path) = @_;
136 File::Spec->catdir($class->install_base_perl_path($path), $_archname);
137}
138
139sub lib_paths_for {
140 my ($class, $path) = @_;
141 my $base = $class->install_base_perl_path($path);
142 return map { File::Spec->catdir($base, @$_) } @_lib_subdirs;
143}
144
145sub _mm_escape_path {
146 my $path = shift;
147 $path =~ s/\\/\\\\\\\\/g;
148 if ($path =~ s/ /\\ /g) {
149 $path = qq{"\\"$path\\""};
150 }
151 return $path;
152}
153
154sub _mb_escape_path {
155 my $path = shift;
156 $path =~ s/\\/\\\\/g;
157 return qq{"$path"};
158}
159
160sub installer_options_for {
161 my ($class, $path) = @_;
162 return {
163 PERL_MM_OPT => defined $path ? "INSTALL_BASE="._mm_escape_path($path) : undef,
164 PERL_MB_OPT => defined $path ? "--install_base "._mb_escape_path($path) : undef,
165 };
166}
b9c94c15 167
e4b5a839 168sub active_paths {
169 my ($self) = @_;
170 $self = ref $self ? $self : $self->new;
171
172 return grep {
173 # screen out entries that aren't actually reflected in @INC
174 my $active_ll = $self->install_base_perl_path($_);
175 grep { $_ eq $active_ll } @{$self->inc};
176 } _as_list($self->roots);
177}
178
179
180sub deactivate {
181 my ($self, $path) = @_;
182 $self = $self->new unless ref $self;
183 $path = $self->resolve_path($path);
184
185 my @active_lls = $self->active_paths;
186
187 if (!grep { $_ eq $path } @active_lls) {
188 warn "Tried to deactivate inactive local::lib '$path'\n";
fe125a69 189 return $self;
0fb70b9a 190 }
b9c94c15 191
e4b5a839 192 my %args = (
193 bins => [ _remove_from($self->bins, $self->install_base_bin_path($path)) ],
194 libs => [ _remove_from($self->libs, $self->install_base_perl_path($path)) ],
195 inc => [ _remove_from($self->inc, $self->lib_paths_for($path)) ],
196 roots => [ _remove_from($self->roots, $path) ],
197 );
198
199 $args{extra} = $self->installer_options_for($args{roots}[0]);
200
201 $self->clone(%args);
202}
203
204sub deactivate_all {
205 my ($self) = @_;
206 $self = $self->new unless ref $self;
207
208 my @active_lls = $self->active_paths;
209
779c192a 210 my %args;
211 if (@active_lls) {
212 %args = (
213 bins => [ _remove_from($self->bins,
214 map $self->install_base_bin_path($_), @active_lls) ],
215 libs => [ _remove_from($self->libs,
216 map $self->install_base_perl_path($_), @active_lls) ],
217 inc => [ _remove_from($self->inc,
218 map $self->lib_paths_for($_), @active_lls) ],
219 roots => [ _remove_from($self->roots, @active_lls) ],
220 );
221 }
e4b5a839 222
223 $args{extra} = $self->installer_options_for(undef);
224
225 $self->clone(%args);
226}
227
228sub activate {
229 my ($self, $path) = @_;
230 $self = $self->new unless ref $self;
231 $path = $self->resolve_path($path);
80816e53 232 $self->ensure_dir_structure_for($path)
233 unless $self->no_create;
e4b5a839 234
b209481c 235 $path = ( Win32::GetShortPathName($path) || $path )
236 if $^O eq 'MSWin32';
237
e4b5a839 238 my @active_lls = $self->active_paths;
239
240 if (grep { $_ eq $path } @active_lls) {
241 $self = $self->deactivate($path);
15f79556 242 }
e4b5a839 243
244 my %args = (
245 bins => [ $self->install_base_bin_path($path), @{$self->bins} ],
246 libs => [ $self->install_base_perl_path($path), @{$self->libs} ],
247 inc => [ $self->lib_paths_for($path), @{$self->inc} ],
248 roots => [ $path, @{$self->roots} ],
249 );
250
251 $args{extra} = $self->installer_options_for($path);
252
253 $self->clone(%args);
254}
255
256sub _legacy {
42c70458 257 my ($self, $path) = @_;
e4b5a839 258 $self = $self->new unless ref $self;
42c70458 259 if (defined $path) {
260 $self = $self->activate($path);
261 }
e4b5a839 262 $self;
263}
264
265sub build_environment_vars_for {
266 my ($self) = _legacy(@_);
267 (
268 PATH => join($_path_sep, _as_list($self->bins)),
269 PERL5LIB => join($_path_sep, _as_list($self->libs)),
270 PERL_LOCAL_LIB_ROOT => join($_path_sep, _as_list($self->roots)),
271 %{$self->extra},
272 );
273}
274
275sub setup_local_lib_for {
276 my ($self) = _legacy(@_);
277 $self->setup_env_hash_for;
278 @INC = @{$self->inc};
279}
280
281sub setup_env_hash_for {
282 my $self = shift;
283 my %env = $self->build_environment_vars_for(@_);
284 for my $key (keys %env) {
285 if (defined $env{$key}) {
286 $ENV{$key} = $env{$key};
287 }
288 else {
289 delete $ENV{$key};
290 }
15f79556 291 }
e4b5a839 292}
15f79556 293
e4b5a839 294sub print_environment_vars_for {
295 my $self = shift;
296 print $self->environment_vars_string_for(@_);
297}
298
299sub environment_vars_string_for {
300 my $self = _legacy(@_);
301
302 my $build_method = 'build_' . $self->shelltype . '_env_declaration';
303
304 my @envs = (
305 PATH => $self->bins,
306 PERL5LIB => $self->libs,
307 PERL_LOCAL_LIB_ROOT => $self->roots,
308 %{$self->extra},
309 );
310 my $out = '';
311 while (@envs) {
312 my ($name, $value) = (shift(@envs), shift(@envs));
313 if (
314 ref $value
315 && @$value == 1
316 && ref $value->[0]
317 && ref $value->[0] eq 'SCALAR'
318 && ${$value->[0]} eq $name) {
319 next;
320 }
f643299c 321 if (!ref $value
b01292d6 322 && defined $value ? $value eq $ENV{$name} : !defined $ENV{$name}
323 ) {
f643299c 324 next;
325 }
e4b5a839 326 $out .= $self->$build_method($name, $value);
327 }
328 return $out;
329}
330
331sub build_bourne_env_declaration {
332 my ($class, $name, $args) = @_;
333 my $value = $class->_interpolate($args);
35f4f261 334 defined $value
335 ? qq{export ${name}="${value}";\n}
336 : qq{unset ${name};\n};
e4b5a839 337}
338sub build_csh_env_declaration {
339 my ($class, $name, $args) = @_;
35f4f261 340 my ($value, @vars) = $class->_interpolate($args, undef, undef, '"', qq{"\\"});
341 (join '', map qq{if ! \$?$_ setenv $_ "";\n}, @vars)
342 . defined $value
e4b5a839 343 ? qq{setenv $name "$value";\n}
35f4f261 344 : qq{unsetenv $name;\n};
e4b5a839 345}
346sub build_cmd_env_declaration {
347 my ($class, $name, $args) = @_;
35f4f261 348 my $value = $class->_interpolate($args, '%', '%', qr([()!^"<>&|]), '^');
349 defined $value
350 ? qq{set $name=$value\n}
351 : qq{set $name=\n};
e4b5a839 352}
fbbea0e7 353sub build_powershell_env_declaration {
354 my ($class, $name, $args) = @_;
35f4f261 355 my $value = $class->_interpolate($args, '$env:', '', '"', '`');
356 defined $value
357 ? qq{\$env:$name = "$value"\n}
358 : "Remove-Item Env:\\$name\n";
fbbea0e7 359}
360
e4b5a839 361
362sub _interpolate {
35f4f261 363 my ($class, $args, $start, $end, $escape, $escape_char) = @_;
e4b5a839 364 return
365 unless defined $args;
366 return $args
367 unless ref $args;
368 return
369 unless @$args;
370 $start = '$' unless defined $start;
371 $end = '' unless defined $end;
35f4f261 372 $escape = '"' unless defined $escape;
373 $escape_char = "\\" unless defined $escape_char;
e4b5a839 374 my @vars;
375 my $string = join($Config{path_sep}, map {
35f4f261 376 if (ref $_ && ref $_ eq 'SCALAR') {
377 push @vars, $$_;
378 $start.$$_.$end;
379 }
380 else {
381 my $str = $_;
382 $str =~ s/($escape)/$escape_char$1/g;
383 $str;
384 }
e4b5a839 385 } @$args);
386 return wantarray ? ($string, @vars) : $string;
b5cc15f7 387}
388
5b94dce5 389sub pipeline;
b5cc15f7 390
5b94dce5 391sub pipeline {
b5cc15f7 392 my @methods = @_;
393 my $last = pop(@methods);
394 if (@methods) {
395 \sub {
396 my ($obj, @args) = @_;
5b94dce5 397 $obj->${pipeline @methods}(
b5cc15f7 398 $obj->$last(@args)
399 );
400 };
401 } else {
402 \sub {
403 shift->$last(@_);
404 };
405 }
406}
407
275c9dae 408=begin testing
409
410#:: test pipeline
b5cc15f7 411
412package local::lib;
413
414{ package Foo; sub foo { -$_[1] } sub bar { $_[1]+2 } sub baz { $_[1]+3 } }
8522f4d5 415my $foo = bless({}, 'Foo');
4c375968 416Test::More::ok($foo->${pipeline qw(foo bar baz)}(10) == -15);
b5cc15f7 417
275c9dae 418=end testing
419
b5cc15f7 420=cut
421
422sub resolve_path {
423 my ($class, $path) = @_;
e4b5a839 424
425 $path = $class->${pipeline qw(
b5cc15f7 426 resolve_relative_path
427 resolve_home_path
428 resolve_empty_path
429 )}($path);
e4b5a839 430
e4b5a839 431 $path;
b5cc15f7 432}
433
434sub resolve_empty_path {
435 my ($class, $path) = @_;
436 if (defined $path) {
437 $path;
438 } else {
439 '~/perl5';
440 }
441}
442
275c9dae 443=begin testing
444
445#:: test classmethod setup
b5cc15f7 446
447my $c = 'local::lib';
448
275c9dae 449=end testing
450
451=begin testing
b5cc15f7 452
275c9dae 453#:: test classmethod
b5cc15f7 454
455is($c->resolve_empty_path, '~/perl5');
456is($c->resolve_empty_path('foo'), 'foo');
457
275c9dae 458=end testing
459
b5cc15f7 460=cut
461
462sub resolve_home_path {
463 my ($class, $path) = @_;
464 return $path unless ($path =~ /^~/);
465 my ($user) = ($path =~ /^~([^\/]+)/); # can assume ^~ so undef for 'us'
b5cc15f7 466 my $homedir = do {
5c957a4b 467 if (!defined $user && defined $ENV{HOME}) {
468 $ENV{HOME}
469 }
470 else {
471 require File::Glob;
472 File::Glob::bsd_glob("~$user", File::Glob::GLOB_TILDE());
b5cc15f7 473 }
474 };
475 unless (defined $homedir) {
cd3eb741 476 require Carp;
b5cc15f7 477 Carp::croak(
478 "Couldn't resolve homedir for "
479 .(defined $user ? $user : 'current user')
b5cc15f7 480 );
481 }
482 $path =~ s/^~[^\/]*/$homedir/;
483 $path;
484}
485
486sub resolve_relative_path {
487 my ($class, $path) = @_;
53699c99 488 $path = File::Spec->rel2abs($path);
b5cc15f7 489}
490
275c9dae 491=begin testing
492
493#:: test classmethod
b5cc15f7 494
495local *File::Spec::rel2abs = sub { shift; 'FOO'.shift; };
496is($c->resolve_relative_path('bar'),'FOObar');
497
275c9dae 498=end testing
499
b5cc15f7 500=cut
501
b5cc15f7 502sub ensure_dir_structure_for {
503 my ($class, $path) = @_;
504 unless (-d $path) {
505 warn "Attempting to create directory ${path}\n";
506 }
5c957a4b 507 require File::Basename;
508 my @dirs;
509 while(!-d $path) {
510 push @dirs, $path;
511 $path = File::Basename::dirname($path);
512 }
513 mkdir $_ for reverse @dirs;
514 return;
b5cc15f7 515}
516
0d6470a5 517=begin testing
518
519#:: test classmethod
520
521File::Path::rmtree('t/var/splat');
522
523$c->ensure_dir_structure_for('t/var/splat');
524
525ok(-d 't/var/splat');
526
527=end testing
528
529=cut
530
c4e3c83b 531sub guess_shelltype {
fc5f07c3 532 my $shellbin
533 = defined $ENV{SHELL}
534 ? (File::Spec->splitpath($ENV{SHELL}))[-1]
535 : ( $^O eq 'MSWin32' && exists $ENV{'!EXITCODE'} )
536 ? 'bash'
537 : ( $^O eq 'MSWin32' && $ENV{PROMPT} && $ENV{COMSPEC} )
538 ? (File::Spec->splitpath($ENV{COMSPEC}))[-1]
539 : ( $^O eq 'MSWin32' && !$ENV{PROMPT} )
540 ? 'powershell.exe'
541 : 'sh';
542
543 for ($shellbin) {
544 return
545 /csh/ ? 'csh'
546 : /command\.com/ ? 'cmd'
547 : /cmd\.exe/ ? 'cmd'
548 : /4nt\.exe/ ? 'cmd'
549 : /powershell\.exe/ ? 'powershell'
550 : 'bourne';
0353dbc0 551 }
c4e3c83b 552}
553
0d6470a5 5541;
555__END__
275c9dae 556
898f36cf 557=encoding utf8
558
b5cc15f7 559=head1 NAME
560
561local::lib - create and use a local lib/ for perl modules with PERL5LIB
562
563=head1 SYNOPSIS
564
565In code -
566
567 use local::lib; # sets up a local lib at ~/perl5
568
569 use local::lib '~/foo'; # same, but ~/foo
570
1bc71e56 571 # Or...
572 use FindBin;
573 use local::lib "$FindBin::Bin/../support"; # app-local support library
574
b5cc15f7 575From the shell -
576
359329d3 577 # Install LWP and its missing dependencies to the '~/perl5' directory
578 perl -MCPAN -Mlocal::lib -e 'CPAN::install(LWP)'
0fb70b9a 579
0fb70b9a 580 # Just print out useful shell commands
b5cc15f7 581 $ perl -Mlocal::lib
e322149f 582 export PERL_MB_OPT='--install_base /home/username/perl5'
c4e3c83b 583 export PERL_MM_OPT='INSTALL_BASE=/home/username/perl5'
0d6470a5 584 export PERL5LIB="/home/username/perl5/lib/perl5"
c4e3c83b 585 export PATH="/home/username/perl5/bin:$PATH"
b5cc15f7 586
322b0a0d 587=head2 The bootstrapping technique
bc30e1d5 588
730f5dda 589A typical way to install local::lib is using what is known as the
590"bootstrapping" technique. You would do this if your system administrator
591hasn't already installed local::lib. In this case, you'll need to install
8522f4d5 592local::lib in your home directory.
898f36cf 593
0ad9f83d 594Even if you do have administrative privileges, you will still want to set up your
898f36cf 595environment variables, as discussed in step 4. Without this, you would still
596install the modules into the system CPAN installation and also your Perl scripts
597will not use the lib/ path you bootstrapped with local::lib.
598
04f8efde 599By default local::lib installs itself and the CPAN modules into ~/perl5.
600
898f36cf 601Windows users must also see L</Differences when using this module under Win32>.
715c31a0 602
730f5dda 6031. Download and unpack the local::lib tarball from CPAN (search for "Download"
604on the CPAN page about local::lib). Do this as an ordinary user, not as root
605or administrator. Unpack the file in your home directory or in any other
606convenient location.
715c31a0 607
730f5dda 6082. Run this:
715c31a0 609
730f5dda 610 perl Makefile.PL --bootstrap
715c31a0 611
730f5dda 612If the system asks you whether it should automatically configure as much
613as possible, you would typically answer yes.
614
04f8efde 615In order to install local::lib into a directory other than the default, you need
616to specify the name of the directory when you call bootstrap, as follows:
898f36cf 617
618 perl Makefile.PL --bootstrap=~/foo
619
6203. Run this: (local::lib assumes you have make installed on your system)
730f5dda 621
622 make test && make install
623
8522f4d5 6244. Now we need to setup the appropriate environment variables, so that Perl
898f36cf 625starts using our newly generated lib/ directory. If you are using bash or
626any other Bourne shells, you can add this to your shell startup script this
627way:
730f5dda 628
629 echo 'eval $(perl -I$HOME/perl5/lib/perl5 -Mlocal::lib)' >>~/.bashrc
630
631If you are using C shell, you can do this as follows:
632
633 /bin/csh
634 echo $SHELL
618272fe 635 /bin/csh
730f5dda 636 perl -I$HOME/perl5/lib/perl5 -Mlocal::lib >> ~/.cshrc
dc8ddd06 637
0d6470a5 638If you passed to bootstrap a directory other than default, you also need to
639give that as import parameter to the call of the local::lib module like this
640way:
8b1e8e69 641
730f5dda 642 echo 'eval $(perl -I$HOME/foo/lib/perl5 -Mlocal::lib=$HOME/foo)' >>~/.bashrc
618272fe 643
aab64481 644After writing your shell configuration file, be sure to re-read it to get the
8522f4d5 645changed settings into your current shell's environment. Bourne shells use
898f36cf 646C<. ~/.bashrc> for this, whereas C shells use C<source ~/.cshrc>.
aab64481 647
b9c94c15 648If you're on a slower machine, or are operating under draconian disk space
649limitations, you can disable the automatic generation of manpages from POD when
650installing modules by using the C<--no-manpages> argument when bootstrapping:
651
730f5dda 652 perl Makefile.PL --bootstrap --no-manpages
b9c94c15 653
8522f4d5 654To avoid doing several bootstrap for several Perl module environments on the
655same account, for example if you use it for several different deployed
656applications independently, you can use one bootstrapped local::lib
898f36cf 657installation to install modules in different directories directly this way:
977a9ca3 658
730f5dda 659 cd ~/mydir1
660 perl -Mlocal::lib=./
661 eval $(perl -Mlocal::lib=./) ### To set the environment for this shell alone
898f36cf 662 printenv ### You will see that ~/mydir1 is in the PERL5LIB
730f5dda 663 perl -MCPAN -e install ... ### whatever modules you want
664 cd ../mydir2
665 ... REPEAT ...
666
480534a8 667If you are working with several C<local::lib> environments, you may want to
668remove some of them from the current environment without disturbing the others.
669You can deactivate one environment like this (using bourne sh):
670
671 eval $(perl -Mlocal::lib=--deactivate,~/path)
672
673which will generate and run the commands needed to remove C<~/path> from your
674various search paths. Whichever environment was B<activated most recently> will
675remain the target for module installations. That is, if you activate
676C<~/path_A> and then you activate C<~/path_B>, new modules you install will go
677in C<~/path_B>. If you deactivate C<~/path_B> then modules will be installed
678into C<~/pathA> -- but if you deactivate C<~/path_A> then they will still be
679installed in C<~/pathB> because pathB was activated later.
680
681You can also ask C<local::lib> to clean itself completely out of the current
682shell's environment with the C<--deactivate-all> option.
730f5dda 683For multiple environments for multiple apps you may need to include a modified
684version of the C<< use FindBin >> instructions in the "In code" sample above.
685If you did something like the above, you have a set of Perl modules at C<<
686~/mydir1/lib >>. If you have a script at C<< ~/mydir1/scripts/myscript.pl >>,
687you need to tell it where to find the modules you installed for it at C<<
688~/mydir1/lib >>.
977a9ca3 689
690In C<< ~/mydir1/scripts/myscript.pl >>:
691
730f5dda 692 use strict;
693 use warnings;
694 use local::lib "$FindBin::Bin/.."; ### points to ~/mydir1 and local::lib finds lib
695 use lib "$FindBin::Bin/../lib"; ### points to ~/mydir1/lib
977a9ca3 696
697Put this before any BEGIN { ... } blocks that require the modules you installed.
698
53699c99 699=head2 Differences when using this module under Win32
700
76f30678 701To set up the proper environment variables for your current session of
702C<CMD.exe>, you can use this:
703
730f5dda 704 C:\>perl -Mlocal::lib
e322149f 705 set PERL_MB_OPT=--install_base C:\DOCUME~1\ADMINI~1\perl5
730f5dda 706 set PERL_MM_OPT=INSTALL_BASE=C:\DOCUME~1\ADMINI~1\perl5
0d6470a5 707 set PERL5LIB=C:\DOCUME~1\ADMINI~1\perl5\lib\perl5
730f5dda 708 set PATH=C:\DOCUME~1\ADMINI~1\perl5\bin;%PATH%
8522f4d5 709
898f36cf 710 ### To set the environment for this shell alone
d4ccf2ea 711 C:\>perl -Mlocal::lib > %TEMP%\tmp.bat && %TEMP%\tmp.bat && del %TEMP%\tmp.bat
730f5dda 712 ### instead of $(perl -Mlocal::lib=./)
53699c99 713
714If you want the environment entries to persist, you'll need to add then to the
76f30678 715Control Panel's System applet yourself or use L<App::local::lib::Win32Helper>.
53699c99 716
717The "~" is translated to the user's profile directory (the directory named for
718the user under "Documents and Settings" (Windows XP or earlier) or "Users"
9bc0788f 719(Windows Vista or later)) unless $ENV{HOME} exists. After that, the home
53699c99 720directory is translated to a short name (which means the directory must exist)
721and the subdirectories are created.
722
730f5dda 723=head1 RATIONALE
724
725The version of a Perl package on your machine is not always the version you
726need. Obviously, the best thing to do would be to update to the version you
727need. However, you might be in a situation where you're prevented from doing
728this. Perhaps you don't have system administrator privileges; or perhaps you
729are using a package management system such as Debian, and nobody has yet gotten
730around to packaging up the version you need.
731
732local::lib solves this problem by allowing you to create your own directory of
733Perl packages downloaded from CPAN (in a multi-user system, this would typically
734be within your own home directory). The existing system Perl installation is
735not affected; you simply invoke Perl with special options so that Perl uses the
736packages in your own local package directory rather than the system packages.
737local::lib arranges things so that your locally installed version of the Perl
738packages takes precedence over the system installation.
739
740If you are using a package management system (such as Debian), you don't need to
741worry about Debian and CPAN stepping on each other's toes. Your local version
742of the packages will be written to an entirely separate directory from those
8522f4d5 743installed by Debian.
730f5dda 744
618272fe 745=head1 DESCRIPTION
746
747This module provides a quick, convenient way of bootstrapping a user-local Perl
748module library located within the user's home directory. It also constructs and
749prints out for the user the list of environment variables using the syntax
750appropriate for the user's current shell (as specified by the C<SHELL>
730f5dda 751environment variable), suitable for directly adding to one's shell
752configuration file.
753
754More generally, local::lib allows for the bootstrapping and usage of a
755directory containing Perl modules outside of Perl's C<@INC>. This makes it
756easier to ship an application with an app-specific copy of a Perl module, or
757collection of modules. Useful in cases like when an upstream maintainer hasn't
758applied a patch to a module of theirs that you need for your application.
1bc71e56 759
760On import, local::lib sets the following environment variables to appropriate
761values:
762
763=over 4
764
e322149f 765=item PERL_MB_OPT
1bc71e56 766
767=item PERL_MM_OPT
768
769=item PERL5LIB
770
771=item PATH
772
1bc71e56 773=back
774
0d6470a5 775When possible, these will be appended to instead of overwritten entirely.
776
1bc71e56 777These values are then available for reference by any code after import.
778
b0c48f8e 779=head1 CREATING A SELF-CONTAINED SET OF MODULES
780
a949ebcd 781See L<lib::core::only> for one way to do this - but note that
d8b1a404 782there are a number of caveats, and the best approach is always to perform a
783build against a clean perl (i.e. site and vendor as close to empty as possible).
b0c48f8e 784
480534a8 785=head1 OPTIONS
786
787Options are values that can be passed to the C<local::lib> import besides the
788directory to use. They are specified as C<use local::lib '--option'[, path];>
789or C<perl -Mlocal::lib=--option[,path]>.
790
791=head2 --deactivate
792
793Remove the chosen path (or the default path) from the module search paths if it
794was added by C<local::lib>, instead of adding it.
795
796=head2 --deactivate-all
797
798Remove all directories that were added to search paths by C<local::lib> from the
799search paths.
800
daad8782 801=head2 --shelltype
802
803Specify the shell type to use for output. By default, the shell will be
804detected based on the environment. Should be one of: C<bourne>, C<csh>,
805C<cmd>, or C<powershell>.
806
80816e53 807=head2 --no-create
808
809Prevents C<local::lib> from creating directories when activating dirs. This is
810likely to cause issues on Win32 systems.
811
480e6e85 812=head1 METHODS
813
a949ebcd 814=head2 ensure_dir_structure_for
480e6e85 815
816=over 4
817
a949ebcd 818=item Arguments: $path
819
820=item Return value: None
480e6e85 821
822=back
823
824Attempts to create the given path, and all required parent directories. Throws
825an exception on failure.
826
827=head2 print_environment_vars_for
828
829=over 4
830
a949ebcd 831=item Arguments: $path
832
833=item Return value: None
480e6e85 834
835=back
836
837Prints to standard output the variables listed above, properly set to use the
838given path as the base directory.
839
a949ebcd 840=head2 build_environment_vars_for
841
842=over 4
843
c40e10d7 844=item Arguments: $path
a949ebcd 845
9f9da00a 846=item Return value: %environment_vars
a949ebcd 847
848=back
849
291b5a3a 850Returns a hash with the variables listed above, properly set to use the
851given path as the base directory.
852
480e6e85 853=head2 setup_env_hash_for
854
855=over 4
856
a949ebcd 857=item Arguments: $path
858
859=item Return value: None
480e6e85 860
861=back
862
863Constructs the C<%ENV> keys for the given path, by calling
a949ebcd 864L</build_environment_vars_for>.
480e6e85 865
5a63c13e 866=head2 active_paths
867
868=over 4
869
870=item Arguments: None
871
872=item Return value: @paths
873
874=back
875
876Returns a list of active C<local::lib> paths, according to the
24351831 877C<PERL_LOCAL_LIB_ROOT> environment variable and verified against
878what is really in C<@INC>.
5a63c13e 879
480e6e85 880=head2 install_base_perl_path
881
882=over 4
883
a949ebcd 884=item Arguments: $path
885
886=item Return value: $install_base_perl_path
480e6e85 887
888=back
889
890Returns a path describing where to install the Perl modules for this local
891library installation. Appends the directories C<lib> and C<perl5> to the given
892path.
893
480e6e85 894=head2 install_base_bin_path
895
896=over 4
897
a949ebcd 898=item Arguments: $path
899
900=item Return value: $install_base_bin_path
480e6e85 901
902=back
903
904Returns a path describing where to install the executable programs for this
9f9da00a 905local library installation. Appends the directory C<bin> to the given path.
480e6e85 906
480e6e85 907=head2 resolve_empty_path
908
909=over 4
910
a949ebcd 911=item Arguments: $path
912
913=item Return value: $base_path
480e6e85 914
915=back
916
917Builds and returns the base path into which to set up the local module
918installation. Defaults to C<~/perl5>.
919
920=head2 resolve_home_path
921
922=over 4
923
a949ebcd 924=item Arguments: $path
925
926=item Return value: $home_path
480e6e85 927
928=back
929
930Attempts to find the user's home directory. If installed, uses C<File::HomeDir>
931for this purpose. If no definite answer is available, throws an exception.
932
933=head2 resolve_relative_path
934
935=over 4
936
a949ebcd 937=item Arguments: $path
938
939=item Return value: $absolute_path
480e6e85 940
941=back
942
943Translates the given path into an absolute path.
944
945=head2 resolve_path
946
947=over 4
948
a949ebcd 949=item Arguments: $path
950
951=item Return value: $absolute_path
480e6e85 952
953=back
954
955Calls the following in a pipeline, passing the result from the previous to the
956next, in an attempt to find where to configure the environment for a local
957library installation: L</resolve_empty_path>, L</resolve_home_path>,
958L</resolve_relative_path>. Passes the given path argument to
959L</resolve_empty_path> which then returns a result that is passed to
960L</resolve_home_path>, which then has its result passed to
961L</resolve_relative_path>. The result of this final call is returned from
962L</resolve_path>.
963
0fb70b9a 964=head1 A WARNING ABOUT UNINST=1
965
966Be careful about using local::lib in combination with "make install UNINST=1".
967The idea of this feature is that will uninstall an old version of a module
968before installing a new one. However it lacks a safety check that the old
969version and the new version will go in the same directory. Used in combination
970with local::lib, you can potentially delete a globally accessible version of a
381738d7 971module while installing the new version in a local place. Only combine "make
0fb70b9a 972install UNINST=1" and local::lib if you understand these possible consequences.
973
dc8ddd06 974=head1 LIMITATIONS
975
788ea146 976=over 4
977
0d6470a5 978=item * Directory names with spaces in them are not well supported by the perl
979toolchain and the programs it uses. Pure-perl distributions should support
980spaces, but problems are more likely with dists that require compilation. A
981workaround you can do is moving your local::lib to a directory with spaces
982B<after> you installed all modules inside your local::lib bootstrap. But be
983aware that you can't update or install CPAN modules after the move.
47e70ca1 984
788ea146 985=item * Rather basic shell detection. Right now anything with csh in its name is
618272fe 986assumed to be a C shell or something compatible, and everything else is assumed
53699c99 987to be Bourne, except on Win32 systems. If the C<SHELL> environment variable is
988not set, a Bourne-compatible shell is assumed.
dc8ddd06 989
0d6470a5 990=item * Kills any existing PERL_MM_OPT or PERL_MB_OPT.
dc8ddd06 991
788ea146 992=item * Should probably auto-fixup CPAN config if not already done.
993
994=back
e423efce 995
dc8ddd06 996Patches very much welcome for any of the above.
bc30e1d5 997
788ea146 998=over 4
999
0d6470a5 1000=item * On Win32 systems, does not have a way to write the created environment
1001variables to the registry, so that they can persist through a reboot.
53699c99 1002
788ea146 1003=back
1004
9a021b2b 1005=head1 TROUBLESHOOTING
1006
1007If you've configured local::lib to install CPAN modules somewhere in to your
1008home directory, and at some point later you try to install a module with C<cpan
1009-i Foo::Bar>, but it fails with an error like: C<Warning: You do not have
1010permissions to install into /usr/lib64/perl5/site_perl/5.8.8/x86_64-linux at
1011/usr/lib64/perl5/5.8.8/Foo/Bar.pm> and buried within the install log is an
1012error saying C<'INSTALL_BASE' is not a known MakeMaker parameter name>, then
1013you've somehow lost your updated ExtUtils::MakeMaker module.
1014
1015To remedy this situation, rerun the bootstrapping procedure documented above.
1016
1017Then, run C<rm -r ~/.cpan/build/Foo-Bar*>
1018
1019Finally, re-run C<cpan -i Foo::Bar> and it should install without problems.
1020
618272fe 1021=head1 ENVIRONMENT
1022
1023=over 4
1024
1025=item SHELL
1026
53699c99 1027=item COMSPEC
1028
618272fe 1029local::lib looks at the user's C<SHELL> environment variable when printing out
1030commands to add to the shell configuration file.
1031
53699c99 1032On Win32 systems, C<COMSPEC> is also examined.
1033
618272fe 1034=back
1035
163f162c 1036=head1 SEE ALSO
1037
1038=over 4
1039
1040=item * L<Perl Advent article, 2011|http://perladvent.org/2011/2011-12-01.html>
1041
1042=back
1043
cc19e8d4 1044=head1 SUPPORT
1045
1046IRC:
1047
1048 Join #local-lib on irc.perl.org.
1049
b5cc15f7 1050=head1 AUTHOR
1051
1052Matt S Trout <mst@shadowcat.co.uk> http://www.shadowcat.co.uk/
1053
d6b71a2d 1054auto_install fixes kindly sponsored by http://www.takkle.com/
1055
b5c1154d 1056=head1 CONTRIBUTORS
1057
1058Patches to correctly output commands for csh style shells, as well as some
1059documentation additions, contributed by Christopher Nehren <apeiron@cpan.org>.
1060
cc19e8d4 1061Doc patches for a custom local::lib directory, more cleanups in the english
0d6470a5 1062documentation and a L<german documentation|POD2::DE::local::lib> contributed by
1063Torsten Raudssus <torsten@raudssus.de>.
8b1e8e69 1064
be160790 1065Hans Dieter Pearcey <hdp@cpan.org> sent in some additional tests for ensuring
9a021b2b 1066things will install properly, submitted a fix for the bug causing problems with
1067writing Makefiles during bootstrapping, contributed an example program, and
1068submitted yet another fix to ensure that local::lib can install and bootstrap
1069properly. Many, many thanks!
1070
1071pattern of Freenode IRC contributed the beginnings of the Troubleshooting
1072section. Many thanks!
be160790 1073
53699c99 1074Patch to add Win32 support contributed by Curtis Jewell <csjewell@cpan.org>.
1075
03b91976 1076Warnings for missing PATH/PERL5LIB (as when not running interactively) silenced
1077by a patch from Marco Emilio Poleggi.
1078
1f8043c8 1079Mark Stosberg <mark@summersault.com> provided the code for the now deleted
1080'--self-contained' option.
1081
76f30678 1082Documentation patches to make win32 usage clearer by
1083David Mertens <dcmertens.perl@gmail.com> (run4flat).
1084
0d6470a5 1085Brazilian L<portuguese translation|POD2::PT_BR::local::lib> and minor doc
1086patches contributed by Breno G. de Oliveira <garu@cpan.org>.
ccf362c0 1087
a0b3d98a 1088Improvements to stacking multiple local::lib dirs and removing them from the
1089environment later on contributed by Andrew Rodland <arodland@cpan.org>.
1090
0d6470a5 1091Patch for Carp version mismatch contributed by Hakim Cassimally
1092<osfameron@cpan.org>.
cd3eb741 1093
7c0db165 1094=head1 COPYRIGHT
1095
cc19e8d4 1096Copyright (c) 2007 - 2010 the local::lib L</AUTHOR> and L</CONTRIBUTORS> as
7c0db165 1097listed above.
1098
b5cc15f7 1099=head1 LICENSE
1100
73c9a8ad 1101This is free software; you can redistribute it and/or modify it under
1102the same terms as the Perl 5 programming language system itself.
b5cc15f7 1103
1104=cut