From 952c7eeb9007516e5923030a7750810ca712e1ad Mon Sep 17 00:00:00 2001 From: Michael Wolf Date: Sat, 30 Sep 2023 14:54:11 -0600 Subject: [PATCH] Add various utility functions --- _reformat-common.bash | 71 ++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 66 insertions(+), 5 deletions(-) diff --git a/_reformat-common.bash b/_reformat-common.bash index eddb791..5927f9a 100644 --- a/_reformat-common.bash +++ b/_reformat-common.bash @@ -1,10 +1,71 @@ -function root() { - git rev-parse --show-toplevel +function get_os() { + un=$(uname) + + if [[ "$un" = "Linux" ]] ; then + echo -n "linux" + return 0 + fi + + if [[ "$un" = "Darwin" ]] ; then + echo -n "osx" + return 0 + fi } -wfroot() { - dir="$1" - cat "$dir/.root" +OPERATING_SYSTEM=$(get_os) + +# For a given file, return its corresponding project root. +function project_root() { + pushd $(dirname "$1") 2>&1 > /dev/null + out=$(git rev-parse --show-toplevel) + ret="$?" + popd 2>&1 > /dev/null + + if [[ "$ret" != "0" ]] ; then + echo -n "" + return 1 + fi + + echo -n "$out" + return 0 +} + +# When run from a dir with would-format configured, return +# would-format's own directory +wf_root() { + arg=$(pwd)/bin/would-reformat.sh + + pr=$(project_root $arg) + + link="$pr/bin/would-reformat.sh" + + original0=$(resolve_symlink "$link") + original=$(normalize_dir_of_file $original0) + + out="$original" + + echo "$out" + return 0 +} + +# FIXME: Make this bail if it fails +function normalize_dir_of_file() { + out0=$(readlink -m "$1") + + out=$(dirname "$out0") + + echo -n "$out" + return 0 +} + +function resolve_symlink() { + if [[ "$OPERATING_SYSTEM" = "osx" ]] ; then + out=$(readlink "$1") + else + out=$(readlink -f "$1") + fi + + echo "$out" } function custom_formatter() {