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