Skip to content

Commit 6e9810a

Browse files
committed
Make scripts/init-submodules.sh mac friendly
1 parent 973f873 commit 6e9810a

File tree

1 file changed

+51
-14
lines changed

1 file changed

+51
-14
lines changed

scripts/utils.sh

Lines changed: 51 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,63 @@
1-
#/usr/bin/env bash
1+
#!/usr/bin/env bash
22

33
#######################################
44
# Common setup. Init MacOS compatibility
55
# variables.
66
# Globals:
7-
# READLINK
7+
# READLINK (best-effort; no GNU requirement)
88
#######################################
99
function common_setup
1010
{
11-
# On macOS, use GNU readlink from 'coreutils' package in Homebrew/MacPorts
12-
if [ "$(uname -s)" = "Darwin" ] ; then
13-
READLINK=greadlink
14-
else
11+
# Prefer system readlink if present; do not require GNU variant
12+
if command -v readlink >/dev/null 2>&1 ; then
1513
READLINK=readlink
14+
else
15+
READLINK=:
16+
fi
17+
}
18+
19+
#######################################
20+
# Portable realpath implementation.
21+
# Resolves to an absolute, canonical path without requiring GNU readlink.
22+
# Arguments:
23+
# $1: path to resolve
24+
#######################################
25+
function realpath_portable
26+
{
27+
# Prefer python3 if available
28+
if command -v python3 >/dev/null 2>&1; then
29+
python3 - "$1" <<'PY'
30+
import os, sys
31+
print(os.path.realpath(sys.argv[1]))
32+
PY
33+
return
1634
fi
35+
36+
# Fallback to perl, commonly available on macOS
37+
if command -v perl >/dev/null 2>&1; then
38+
perl -MCwd -e 'print Cwd::abs_path(shift), "\n"' "$1"
39+
return
40+
fi
41+
42+
# Pure shell fallback using readlink (no -f) and cd -P
43+
target="$1"
44+
dir="$(dirname -- "$target")"
45+
base="$(basename -- "$target")"
46+
[ -d "$target" ] && { dir="$target"; base=""; }
47+
48+
# Resolve symlinks
49+
while [ -n "$base" ] && [ -L "$dir/$base" ]; do
50+
link="$($READLINK "$dir/$base" 2>/dev/null)" || break
51+
case "$link" in
52+
/*) target="$link" ;;
53+
*) target="$dir/$link" ;;
54+
esac
55+
dir="$(dirname -- "$target")"
56+
base="$(basename -- "$target")"
57+
done
58+
59+
dir="$(cd -P "$dir" >/dev/null 2>&1 && pwd)"
60+
[ -n "$base" ] && echo "$dir/$base" || echo "$dir"
1761
}
1862

1963
#######################################
@@ -61,16 +105,9 @@ function restore_bash_options
61105
#######################################
62106
function replace_content
63107
{
64-
# On macOS, use GNU readlink from 'coreutils' package in Homebrew/MacPorts
65-
if [ "$(uname -s)" = "Darwin" ] ; then
66-
READLINK=greadlink
67-
else
68-
READLINK=readlink
69-
fi
70-
71108
# If BASH_SOURCE is undefined, we may be running under zsh, in that case
72109
# provide a zsh-compatible alternative
73-
DIR="$(dirname "$($READLINK -f "${BASH_SOURCE[0]:-${(%):-%x}}")")"
110+
DIR="$(dirname "$(realpath_portable "${BASH_SOURCE[0]:-${(%):-%x}}")")"
74111
file="$1"
75112
shift
76113
key="$1"

0 commit comments

Comments
 (0)