~chambln/dots

6aea47230988a519597588885685904de67fd8f1 — Gregory Chamberlain 17 days ago 8f10369
Add script ppwd and WIP script relpath
2 files changed, 58 insertions(+), 0 deletions(-)

A pkgs/ppwd/bin/ppwd
A pkgs/relpath/bin/relpath
A pkgs/ppwd/bin/ppwd => pkgs/ppwd/bin/ppwd +6 -0
@@ 0,0 1,6 @@
#!/bin/sh

case $PWD in
    "$HOME"/*|"$HOME") printf '%s\n' "~${PWD#$HOME}" ;;
    *) printf '%s\n' "$PWD" ;;
esac

A pkgs/relpath/bin/relpath => pkgs/relpath/bin/relpath +52 -0
@@ 0,0 1,52 @@
#!/bin/sh -efu

# Usage: $0 FILENAME [DIRECTORY]
#
# Print the location of FILENAME relative to DIRECTORY or $PWD.

length() {
    printf '%d\n' "$#"
}

absolve() {
    case $1 in
        /*) printf '%s\n' "$1" ;;
        *) printf '%s/%s\n' "$PWD" "$1" ;;
    esac
}

canonicalise() {
    set -f -- $(absolve "$1")

    # Drop ‘.’ and ‘’ components.
    for component; do
        shift
        case $component in
            .|'') ;;
            *) set -- "$@" "$component" ;;
        esac
    done

    # Resolve ‘..’ components.
    path=
    for component; do
        case $component in
            ..) path=${path%/*} ;;
            *) path=$path/$component ;;
        esac
    done

    printf '%s\n' "${path:-/}"
}

# Print location of $1 relative to $2.
relate() {
    fn=$(canonicalise "$1")
    dir=$(canonicalise "$2")

    printf 'Not yet implemented!\n' >&2
    printf '%s relative to %s\n' "$fn" "$dir"  # TODO
}

IFS=/
relate "$1" "${2-$PWD}"