relocatable-perl: like relocatable-script, but for Perl scripts
[gnulib.git] / build-aux / relocatable.pl.in
1 # The functions in this file provide support for relocatability of
2 # Perl scripts.  They should be included near the beginning of each
3 # Perl script in a relocatable program, by adding @relocatable_pl@
4 # and causing the script to be expanded with AC_CONFIG_FILES.  A
5 # small amount of additional code must be added and adapted to the
6 # package by hand; see doc/relocatable-maint.texi (in Gnulib) for
7 # details.
8 #
9 # This code is based on relocatable.sh.in, and design changes (and
10 # bugs) should probably be cross-checked with it.
11 #
12 # Copyright (C) 2013 Free Software Foundation, Inc.
13 #
14 # This program is free software: you can redistribute it and/or modify
15 # it under the terms of the GNU General Public License as published by
16 # the Free Software Foundation; either version 3 of the License, or
17 # (at your option) any later version.
18 #
19 # This program is distributed in the hope that it will be useful,
20 # but WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 # GNU General Public License for more details.
23 #
24 # You should have received a copy of the GNU General Public License
25 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
26 #
27
28 use Config;
29 use File::Basename;
30 use File::Spec::Functions;
31 use Cwd 'realpath';
32
33 # Support for relocatability.
34 sub find_curr_installdir {
35   # Determine curr_installdir, even taking into account symlinks.
36   my $curr_executable = $0;
37   my $basename = basename($0);
38   if ($curr_executable eq $basename) {
39     LOOP: for my $dir (split /$Config{path_sep}/, $ENV{PATH}) {
40       $dir = "." unless $dir;
41       for my $ext ('') {
42         my $filename = catfile($dir, "$curr_executable$ext");
43         if (-f $filename) {
44           $curr_executable = $filename;
45           last LOOP;
46         }
47       }
48     }
49   }
50   # Resolve symlinks and canonicalize.
51   return realpath(dirname($curr_executable));
52 }
53 sub find_prefixes {
54   # Compute the original/current installation prefixes by stripping the
55   # trailing directories off the original/current installation directories.
56   my ($orig_installprefix, $curr_installprefix) = @_;
57   my $orig_last = basename($orig_installprefix);
58   my $curr_last = basename($curr_installprefix);
59   if ($orig_last && $curr_last && $orig_last eq $curr_last) {
60     $orig_installprefix = dirname($orig_installprefix);
61     $curr_installprefix = dirname($curr_installprefix);
62   }
63   return $orig_installprefix, $curr_installprefix;
64 }