aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/%HOME%/.bash_utils/path.sh
blob: 326cbf76fd10677eb47d1e76697b011f000076ef (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
#!/usr/bin/env bash

# Copyright (c) 2016 Egor Tensin <Egor.Tensin@gmail.com>
# This file is part of the "linux-home" project.
# For details, see https://github.com/egor-tensin/linux-home.
# Distributed under the MIT License.

# These are a couple of routines that allow you to add to your $PATH correctly
# and safely. Originally added as a dependency for other routines, currently
# are unused. TODO: remove?

path_add() (
    set -o errexit -o nounset -o pipefail
    shopt -s inherit_errexit lastpipe

    [ "$#" -eq 0 ] && return 0

    local -a src_list

    local path
    readlink -z --canonicalize-missing -- "$@" | while IFS= read -d '' -r path; do
        src_list+=("$path")
    done

    for path; do
        if str_contains "$path" ':'; then
            echo "${FUNCNAME[0]}: mustn't contain colon (':') characters: $path" >&2
            return 1
        fi
    done

    local -A dest_dict
    local -a dest_list

    for path in ${src_list[@]+"${src_list[@]}"}; do
        [ -n "${dest_dict[$path]+x}" ] && continue
        dest_dict[$path]=1
        dest_list+=("$path")
    done

    if [ -n "${PATH-}" ]; then
        str_split -z -- "${PATH-}" ':' | xargs -0 -- readlink -z --canonicalize-missing -- | while IFS= read -d '' -r path; do
            [ -n "${dest_dict[$path]+x}" ] && continue
            dest_dict[$path]=1
            dest_list+=("$path")
        done
    fi

    str_join ':' ${dest_list[@]+"${dest_list[@]}"}
)

path_export() {
    local new_path
    local ret

    new_path="$( path_add "$@" )"
    ret="$?"

    [ "$ret" -ne 0 ] && return "$ret"

    export PATH="$new_path"
}