~chambln/dots

ref: 8c1b88ef6cd0fdc96cf4996ca5f2172f5edd594f dots/pkgs/stow/bin/stow -rwxr-xr-x 1.3 KiB
8c1b88efGregory Chamberlain Fix whitespace 4 months ago
                                                                                
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
#!/bin/sh
# Unstowing (-D) requires the '-ef' option in test(1) which is not
# specified by POSIX but is present nontheless in most Bourne shells
# including bash(1), dash(1) and ksh(1).

set -u

die() {
	printf '%s: %s\n' "${0##*/}" "${1-Usage: ${0##*/} [-Dhv] [-t TARGET] PACKAGE...}" >&2
	exit "${2-2}"
}

unstow_file() {
	if [ "$f" -ef "$dst" ]; then
		$VERBOSE && printf 'RM %s\n' "$dst"
		rm "$dst"
	fi
}

stow_file() {
	if [ -d "$f" ]; then
		if [ ! -d "$dst" ]; then
			$VERBOSE && printf 'MKDIR %s\n' "$dst"
			mkdir -p "$dst"
		fi
	elif [ ! "$f" -ef "$dst" ]; then
		$VERBOSE && printf 'LINK  %s -> %s\n' "$dst" "$f"
		ln -s "$f" "$dst"
	fi
}

ACTION=stow_file
TARGET=..
VERBOSE=false
while getopts Dht:v OPT; do
	case $OPT in
		D) ACTION=unstow_file ;;
		t) TARGET=${OPTARG%${OPTARG##*[!/]}} ;;
		v) VERBOSE=true ;;
		?) die
	esac
done
shift $((OPTIND - 1))

[ $# -gt 0 ] || die

for pkg do
	[ -d "$pkg" ] || die "No such package '$pkg'"
done

mkdir -p "$TARGET"
for pkg do
	# Convert relative paths to absolute paths.
	case $pkg in /*);; *) pkg=$PWD/$pkg; esac

	# Remove all trailing slashes.
	pkg=${pkg%${pkg##*[!/]}}

	# Stow or unstow this package.
	set -- "$pkg"/.[!.]* "$pkg"/..?* "$pkg"/*
	while [ $# -gt 0 ] && f=$1 && shift; do
		[ -e "$f" ] || [ -h "$f" ] || continue
		dst=$TARGET${f#$pkg}
		$ACTION
		set -- "$f"/.[!.]* "$f"/..?* "$f"/* "$@"
	done
done