perl-env-setup 18.6 KB
Newer Older
1 2 3 4 5
#!/bin/bash
##
# Set up the environment for use with perl.
#
# Common usage:
6
#   ci/perl-env-setup [-e <environment>] [-v] requirements.txt ...
7 8 9 10 11 12 13 14 15 16 17 18
#
# The requirements passed may be an explicit module requirement, prefixed by a
# '+', rather than a filename. Use @<version> suffixes to fix the version of the
# module.
#

set -eo pipefail

# The icon to use beside the environment name.
# This is a Camel symbol, to indicate this is Perl.
environment_icon="🐪 "

19 20 21
# The logfile we will write to
log_file='output_cpan.txt'

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80

##
# Convert a given path into one that starts from the root.
#
# @param $1     Path to make absolute
function abspath() {
    local path="$1"
    if [[ "$path" != '' && "${path:0:1}" != '/' ]] ; then
        path="$(pwd)/$path"
    fi

    while [[ "$path" =~ /\.\.?/ || "$path" =~ /\.\.$ ]] ; do
        path="$(sed -E 's!//*!/!g;
                        s!/\.\/!/!g;
                        s!/[^/][^/]*/\.\./!/!;
                        s!/[^/][^/]*/\.\.$!/!;
                        s!^/\.\./!/!;
                        s!^/\.\.$!/!;' <<< "$path")"
    done

    local parent
    local leaf
    parent="$(dirname "$path")"
    leaf="$(basename "$path")"
    if [[ "$leaf" == '.' ]] ; then
        leaf=''
    fi

    if [[ "$parent" != '/' && "$parent" != '.' && ! -d "$parent" ]] ; then
        path="$(abspath "$parent")${leaf:+/$leaf}"
    else
        path="$( cd "$parent" && pwd -P)${leaf:+/$leaf}"
    fi

    echo -n "${path//\/\//\/}"
}


scriptdir="$( abspath "$(dirname "${BASH_SOURCE[0]}")" )"
root="$( abspath "$scriptdir/.." )"
debug=false

# Library directory
environment="${root}/perllib"


function usage() {
    script_name=$(basename "${BASH_SOURCE[0]}")
    cat <<EOM
Usage: $script_name [-v] [-e <environment>] {<requirements>}*

Script for configuring and updating a Perl isolated environment.
It is not really that isolated, but it will ensure a lot more isolation than
not using it.

Optional arguments:
    -v                    verbose; be more noisy about what is being done
    -e <env-dir>          path to the directory in which to create the
                          environment (default 'perllib')
81
    -l <log-file>         path to the file into which the log is written
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
    -h                    show this help message and exit

Positional arguments:
    requirements          path to the file containing the CPAN modules
                          required
                          OR '+<module-def>'

The module definition may (should) be suffixed by @<version> to fix a
given version to the environment.
EOM
}


##
# Debug.
function debug() {
    if $debug ; then
        echo "$@"
    fi
}

##
# Check that the correct version of a module is installed.
#
# @param $1     Module in form '<module>' or '<module>@<version>'
#
# @retval   1 if failed
#           0 if passing
function check_module() {
    local def="$1"
    local module="${def%@*}"
    local version="${def#*@}"
    if [[ "$version" == "$module" ]] ; then
        version=''
    fi

    debug "Checking for '$module' @ '$version'"

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    if ! perl -f -e "# Find the module
                  my \$leaf = '${module}.pm';
                  \$leaf =~ s/::/\\//g;
                  my \$filename;
                  # Try to find the file by name first - this has less
                  # risk in executing code, and may be faster.
                  for my \$dir (@INC) {
                      if (-r \"\$dir/\$leaf\") {
                          \$filename = \"\$dir/\$leaf\";
                          last;
                      }
                  }
                  my \$modversion;
                  if (defined \$filename) {
                      if (open(my \$fh, '<', \$filename)) {
                          my \$nlines = 0;
                          while (<\$fh>) {
Charles Ferguson's avatar
Charles Ferguson committed
137
                              if (/\\\$VERSION *= *(?:[\"']([0-9\\.]+)[\"']|([0-9\.]+))/) {
138 139 140 141 142 143 144 145 146 147 148
                                  \$modversion = \$1 // \$2;
                                  last;
                              }
                              last if (\$nlines++ > 100);
                          }
                      }
                  }
                  if (!defined \$modversion) {
                      require ${module};
                      \$modversion = \$${module}::VERSION;
                  }
149
                  if ('${version}' ne '' &&
150 151 152
                      \"\$modversion\" ne '${version}') {
                      die \"Version should be ${version}, not \$modversion\\n\";
                  }" > /dev/null ; then
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
        return 1
    fi

    return 0
}


##
# Ensure that all the CPAN requirements are met
#
# @param $1  The file we're to read.
function install_requirements() {
    local reqfile="$1"
    local line

    # First we need to resolve the dependencies on the requirements,
    # in order to check the ordering.
    # This is required because cpanm will not resolve the version requirements
    # before attempting installs.
    # Thus, if you request 'Perl::Critic@1.224 PPI@1.220' it may install
    # Perl::Critic, look at the requirements for it and determine that PPI >= 1.220
    # is required, download and install PPI 1.223, and then install Perl::Critic.
    # THEN it sees that PPI 1.220 is required and so downloads and installs that
    # version.
    # We avoid this by attempting to download the modules in the order in which
    # they will be required. If at the end of that process, the module versions are
    # not what was requested, we report a failure.

    local -a required_defs
    local -a required_modules

    debug "Getting dependencies"
    while read line ; do
        if [[ "$line" =~ ^\ *$ ]] || \
           [[ "$line" =~ ^\ *# ]] ; then
            continue
        fi

        local def="$line"
        local depfile="${environment}/${def}.deps"
        required_defs+=("$def")
        required_modules+=("${def%@*}")

        # Ensure that a dependency list exists for the module
        if [ ! -f "${depfile}" ] ; then
            debug "Reading dependency information for '$def'"
            if ! cpanm --showdeps "$def" \
                    | sed '/^[A-Za-z][A-Za-z0-9_:]*\($\|@\|~\)/!d ; s/[~@].*$//' \
                    | sort -u \
                    > "${depfile}" ; then
                echo "Attempting to find dependencies for '$depfile' failed" >&2
                exit 1
            fi
        fi
    done < <(sort -u "$reqfile")

    debug "Initial required defs: ${required_defs[*]}"

    # Moving the dependencies around.
    # Essentially we move any explicitly specified versions to be installed before
    # the things that they depend on.
    # Assuming no loops, this should take a maximum of <num requirements> iterations
    # to complete.
    local still_sorting=true
    local iterations=20
218
    while $still_sorting && [ "$iterations" -gt 0 ] && [ "${#required_defs[@]}" != 0 ] ; do
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
        still_sorting=false
        local -a new_required_defs
        new_required_defs=()
        debug "Reordering..."
        for defindex in $(seq 0 $(( ${#required_defs[@]} - 1 ))) ; do
            # Obtain a list of the modules that will be installed
            local -a toinstall
            local def="${required_defs[$defindex]}"
            local depfile="${environment}/${def}.deps"
            toinstall=($(comm -12 <(sed 's/[~@].*$//' "$reqfile") "$depfile"))
            debug "  Checking $defindex - $def: ${toinstall[*]}"

            local -a promotedef
            local -a taildef
            local laterdef
            promotedef=()
            taildef=()
            for laterdef in "${required_defs[@]:$(( defindex + 1 ))}" ; do
                debug "    Laterdef: $laterdef"
                if [[ " ${toinstall[@]} " =~ \ ${laterdef%@*}\  ]] ; then
                    # One of the packages depended on appears later in the list.
                    debug "    - need to promote ${laterdef} in front of ${def}"
                    promotedef+=("$laterdef")
                else
                    taildef+=("$laterdef")
                fi
            done
            if [ "${#promotedef[@]}" != '0' ] ; then
                debug "  Promotedefs: ${promotedef[@]}"
                debug "  taildefs: ${taildef[@]}"
                new_required_defs+=("${promotedef[@]}" "$def" "${taildef[@]}")
                still_sorting=true
                break
            else
                new_required_defs+=("$def")
            fi
        done
        required_defs=("${new_required_defs[@]}")
        iterations=$(( iterations - 1 ))
        debug "  Now required defs: ${required_defs[@]}"
    done

261
    echo "Ready to install CPAN modules:" >> "${log_file}"
262
    for module in "${required_defs[@]}" ; do
263
        echo "  $module" >> "${log_file}"
264 265
    done

266
    echo $'\nInstalling modules...\n' >> "${log_file}"
267
    if [ "${#required_defs[@]}" != '0' ] ; then
268
        if ! cpanm --skip-satisfied -n "${required_defs[@]}" >> "${log_file}" 2>&1 ; then
269
            echo "CPAN installation failed" >&2
270
            sed 's/^/  /' < "${log_file}"
271 272 273 274
            exit 1
        fi
    fi

275
    echo $'\nChecking installation...\n' >> "${log_file}"
276 277
    failed=false
    for module in "${required_defs[@]}" ; do
278 279
        if ! check_module "${module}" 2>> "${log_file}"; then
           echo "  $module was not installed properly" >> "${log_file}"
280 281 282
           echo "ERROR: $module was not installed properly" >&2
           failed=true
        else
283
           echo "  $module ok" >> "${log_file}"
284 285 286 287 288 289 290
        fi
    done

    if $failed ; then
        echo "Environment setup failed." >&2
        exit 1
    fi
291
    echo $'\nInstalled ok!' >> "${log_file}"
292 293 294
}

# Parse the command line
295
while getopts ":he:l:v" opt ; do
296 297 298 299 300 301 302
    case $opt in
        v)
            debug=true
            ;;
        e)
            environment="$(abspath "$OPTARG")"
            ;;
303 304 305
        l)
            log_file="$(abspath "$OPTARG")"
            ;;
306 307 308 309 310 311 312 313 314 315
        h)
            usage
            exit
            ;;
    esac
done


# Our temporary directory
tmpdir="$(mktemp -d -t perl-env.XXXXXXXX)"
316
if [[ "$?" != '0' || "$tmpdir" == '' ]] ; then
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
    echo "Cannot create temporary directory. That would be bad." >&2
    exit 1
fi
function cleanup() {
    if [[ "$(uname -s)" == 'Darwin' ]] ; then
        # On OSX, '--one-file-system' does not exist.
        rm -rf "${tmpdir}"
    else
        rm -rf --one-file-system "${tmpdir}"
    fi
}
trap cleanup EXIT


tmprequirements="${tmpdir}/requirements.txt"
tmpinput="${tmpdir}/inputrequirements.txt"

# Determine the modules we're going to install
echo > "${tmpinput}"
336
if [[ -f "${root}/cpan.txt" ]] ; then
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
    cat "${root}/cpan.txt" >> "${tmpinput}"
fi
for file in "${@:$OPTIND}" ; do
    if [[ "${file:0:1}" == '+' ]] ; then
        echo "${file:1}" >> "${tmpinput}"
    elif [ -f "$file" ] ; then
        cat "$file" >> "${tmpinput}"
    fi
done

sed -E "s/^#.*//; /^ *$/d;" "${tmpinput}" \
    | sort -u > "${tmprequirements}"


# Ensure that our environment is set up properly
mkdir -p "${environment}"
353
eval "$(SHELL=/bin/bash perl -f -M"local::lib=${environment}" 2> /dev/null)"
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
if [ $? != 0 ] ; then
    echo "Failed to create local::lib environment"
    exit 1
fi

environment_name="$(basename "$environment")"
envpath="$environment"
while [[ "$environment_name" == 'perllib' ||
         "$environment_name" == 'perl' ||
         "${environment_name:0:1}" == '.' ]] ; do
    # That's not a helpful name, so use the name of the parent directory
    envpath="$(dirname "$envpath")"
    environment_name="$(basename "$envpath")"
done


370
echo "CPAN output" > "${log_file}"
371 372

# Ensure that we have a version of CPAN
373 374 375
if ! check_module App::cpanminus 2>> "${log_file}" ; then
    echo "==== cpanminus install ====" >> "${log_file}"
    cpan -T App::cpanminus >> "${log_file}" 2>&1
376
fi
377 378 379
if ! check_module ExtUtils::MakeMaker@7.10 2>> "${log_file}" ; then
    echo "==== ExtUtils::MakeMaker install ====" >> "${log_file}"
    cpanm -n ExtUtils::MakeMaker@7.10 >> "${log_file}" 2>&1
380
fi
381 382 383
if ! check_module Module::Build@0.4222 2>> "${log_file}" ; then
    echo "==== Module::Build install ====" >> "${log_file}"
    cpanm -n Module::Build@0.4222 >> "${log_file}" 2>&1
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
fi

debug "Requirements from input:"
if $debug ; then
    sed 's/^/  /' "${tmprequirements}"
fi

debug "Installing"
install_requirements "${tmprequirements}"
debug "Installation complete"

# Construct some 'activate' scripts, which set up the environment
# in the style of virtualenv.

function generate_activate_script() {
    local scriptname="$1"
    sed "s/<envdir>/${environment//\//\\/}/g; \
         s/<icon>/${environment_icon}/g; \
         s/<name>/${environment_name}/g;" > "${environment}/bin/${scriptname}"
}

# Bash script
generate_activate_script activate_perllib <<'EOM'
#!/bin/false /bin/bash
##
# Activate the 'perllib' environment.
#
# NOTE: Use 'source' on this file; do not try to execute it.
#       That would be ineffective.
#

export PERLLIB_ENVVARS
PERLLIB_ENVVARS=(PERL_LOCAL_LIB_ROOT \
                 PERL_MB_OPT \
                 PERL_MM_OPT \
                 PERL5LIB \
                 PATH \
                 PS1)

function deactivate_perllib() {

    local oldvar
    local oldval
    local var

    # reset old environment variables
    for var in "${PERLLIB_ENVVARS[@]}" ; do
        oldvar="_OLD_PERLLIB_$var"
        oldval="${!oldvar}"
        eval "$var='$oldval'"
        export "$var"
        unset "$oldvar"
    done

    # This should detect bash and zsh, which have a hash command that must
    # be called to get it to forget past commands.  Without forgetting
    # past commands the $PATH changes we made may not be respected
    if [ -n "${BASH-}" ] || [ -n "${ZSH_VERSION-}" ] ; then
        hash -r 2>/dev/null
    fi

    unset PERLLIB_ENV
    if [ ! "${1-}" = "nondestructive" ] ; then
        # Self destruct!
        unset -f deactivate_perllib
    fi
}

PERLLIB_ENV="<envdir>"
export PERLLIB_ENV

function _perllib_setup() {
    local var
    local val
    local oldvar
    local oldval
    local tmpfile="$(mktemp -t perllib.XXXXXXXX)"

462
    SHELL=/bin/bash perl -f -Mlocal::lib="$PERLLIB_ENV" > "${tmpfile}"
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550

    for var in "${PERLLIB_ENVVARS[@]}" ; do
        oldvar="_OLD_PERLLIB_$var"
        oldval="${!oldvar}"
        val="${!var}"
        eval "$oldvar='$val'"
        if [ "$var" != 'PS1' -a "$var" != 'PATH' ] ; then
            eval "export $var=''"
        fi
        eval "$(grep -e "export $var\|$var=" "${tmpfile}")"
    done
    rm -f "${tmpfile}"

    _OLD_PERLLIB_PS1="$PS1"
    if [ -z "${PERLLIB_DISABLE_PROMPT-}" ] ; then
        PS1="(<icon><name>) $PS1"
        export PS1
    fi
    unset -f _perllib_setup
}

_perllib_setup

EOM

# Fish script
generate_activate_script activate_perllib.fish <<'EOM'
#!/bin/false /bin/bash
##
# Activate the 'perllib' environment.
#
# NOTE: Use 'source' on this file; do not try to execute it.
#       That would be ineffective.
#

set PERLLIB_ENVVARS PERL_LOCAL_LIB_ROOT \
                    PERL_MB_OPT \
                    PERL_MM_OPT \
                    PERL5LIB \
                    PATH

function deactivate_perllib -d 'Exit perllib mode and return to the normal environment.'

    set -l oldvar
    set -l oldval
    set -l var

    # reset old environment variables
    for var in $PERLLIB_ENVVARS
        set oldvar "_OLD_PERLLIB_$var"
        set oldval "$$oldvar"
        if [ "$var" = 'PATH' ]
            eval "set -gx '$var' $oldval"
        else
            set -gx "$var" "$oldval"
        end
        set -e "$oldvar"
    end

    if test -n "$_OLD_PERLLIB_FISH_PROMPT_OVERRIDE"
        # Set an empty local `$fish_function_path` to allow the removal of `fish_prompt` using `functions -e`.
        set -l fish_function_path

        # Erase virtualenv's `fish_prompt` and restore the original.
        functions -e fish_prompt
        functions -c _old_perllib_fish_prompt fish_prompt
        functions -e _old_perllib_fish_prompt
        set -e _OLD_PERLLIB_FISH_PROMPT_OVERRIDE
    end

    set -e PERLLIB_ENV

    if test "$argv[1]" != 'nondestructive'
        # Self-destruct!
        functions -e deactivate_perllib
    end
end

set -gx PERLLIB_ENV "<envdir>"

function _perllib_setup

    set -l var
    set -l val
    set -l oldvar
    set -l oldval
    set -l tmpfile (mktemp -t perllib.XXXXXXXX)

551
    env SHELL=/bin/bash perl -f -Mlocal::lib="$PERLLIB_ENV" > "$tmpfile"
552 553 554 555 556 557 558 559 560 561 562 563

    for var in $PERLLIB_ENVVARS
        set oldvar "_OLD_PERLLIB_$var"
        set oldval "$$oldvar"
        set val "$$var"
        set -g "$oldvar" "$val"

        if [ "$var" != 'PATH' ]
            set -gx "$var" ''
        end

        if [ "$var" = 'PATH' ]
564 565 566
            # The path variable needs to have the colons translated to spaces,
            # and the path parameters as a whole un-quoted, as the PATH is
            # an array in fish.
567 568 569
            eval (sed -E '/^(export )?'$var'=/ ! d;
                          s/export '$var';//g;
                          s/^(export )?'$var'="(.*)";?/set -gx "'$var'" \2/;
570 571
                          s/\$\{'$var':\+:\$\{'$var'\}\}/'":\$$var"'/;
                          s/:/ /g;' "$tmpfile")
572
        else
573 574
            # Non-PATH variables only need to be translated to the format
            # with quotes around the string, and colons retained.
575 576 577
            eval (sed -E '/^(export )?'$var'=/ ! d;
                          s/export '$var';//g;
                          s/^(export )?'$var'="(.*)";?/set -gx "'$var'" "\2"/;
578
                          s/\$\{'$var':\+:\$\{'$var'\}\}/'":\$$var"'/;' "$tmpfile")
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
        end
    end
    rm -f "$tmpfile"

    if test -z "$PERLLIB_DISABLE_PROMPT"
        # Copy the current `fish_prompt` function as `_old_fish_prompt`.
        functions -c fish_prompt _old_perllib_fish_prompt

        function fish_prompt
            # Save the current $status, for fish_prompts that display it.
            set -l old_status $status

            # Prompt override provided?
            # If not, just prepend the environment name.
            printf '%s(%s%s%s) ' (set_color normal) (set_color -o white) "<icon><name>" (set_color normal)

            # Restore the original $status
            echo "exit $old_status" | source
            _old_perllib_fish_prompt
        end

        set -g _OLD_PERLLIB_FISH_PROMPT_OVERRIDE "$PERLLIB_ENV"
    end

    functions -e _perllib_setup
end

_perllib_setup
EOM

if [[ -t 0 && -t 1 ]] ; then
    # Tiny bit of simplification of the path
    dir="${scriptdir}"
    pwd="$(pwd -P)/"
    home="$HOME/"
    if [[ "${dir:0:${#pwd}}" == "$pwd" ]] ; then
        dir="${dir:${#pwd}}"
    elif [[ "${dir:0:${#home}}" == "$home" ]] ; then
617
        dir='~'"/${dir:${#home}}"
618 619 620 621 622 623 624 625 626 627 628 629 630
    fi

    cat <<EOM
To use the Perl environment, use:

  ${dir}/perl-env <commands>
      - to execute commands within the environment and return
  ${dir}/perl-env -s
      - to drop to a shell within the environment (bash and fish supported)
  source ${dir}/perl-env
      - to enter the environment directly (bash only)
EOM
fi