summaryrefslogtreecommitdiffstats
path: root/pkgs/shell/deref
blob: 05da4baf0b37810d69a0788d483d7f15079e755d (plain)
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#! /bin/sh
#!buildShellBin prepend-path=coreutils:which
#
# NAME
#       deref - dereference a name or path, showing all intermediaries
#
# SYNOPSIS
#       deref [OPTION]... NAME...
#
# DESCRIPTION
#       
#
#       --show=asis, --show=as-is
#         When encountering relative file names, show them as-is.
#         This is the default behavior.
#
#       --show=all
#         When encountering relative file names, show them as-is
#         and additionally show their absolute file name.
#
#       --show=abs, --show=absolute
#         When encountering relative file names, show their absolute
#         file name.
#

set -efu

showname=asis
case $1 in
  (--show=asis|--show=as-is|--show=all|--show=abs|--show=absolute)
    showname=${1#--show=}
    shift
    ;;
  (-*)
    echo "$0: bad argument: $1" >&2
    exit 1
    ;;
esac

showname() {
  if test -L "$1" || test -e "$1"; then
    case $1 in
      /*)
        ls -d --color "$1"
        ;;
      *)
        case $showname in
          asis|as-is)
            ls -d --color "$1"
            ;;
          abs|absolute)
            ls -d --color "$(realpath -sm "$1")"
            ;;
          all)
            echo "$(ls -d --color "$1")=$(ls -d --color "$(realpath -sm "$1")")"
            ;;
        esac
      ;;
    esac
  else
    printf '%s' "$name"
  fi
}

pwd=$PWD
for name; do
  cd "$pwd"
  path=
  sep=

  if ! test -L "$name" && ! test -e "$name"; then
    if which=$(which "$name" 2>/dev/null); then
      path=$name
      sep=' ⇒ '
      name=$which
    fi
  fi

  while test -L "$name"; do
    cd "$(dirname "$name")"
    path=${path+$path$sep}$(showname "$name")
    sep=' → '
    name=$(readlink "$name")
  done

  path=${path+$path$sep}$(showname "$name")

  echo "$path"
done