diff --git a/lib/path b/lib/path index 8c432f7..71da37d 100644 --- a/lib/path +++ b/lib/path @@ -6,6 +6,9 @@ # @go.canonicalize_path # Removes all extra slashes from a path and resolves all relative components # +# @go.add_parent_dir_if_relative_path +# Adds a parent dir to a relative path +# # @go.walk_file_system # Performs an operation on file system objects and recurses into directories # @@ -61,6 +64,32 @@ fi } +# Adds a parent dir to a relative path +# +# If the path is absolute, the original path is assigned. +# +# Options: +# --parent: Parent dir to add to `path` (default `PWD`) +# +# Arguments: +# result_var_name: Name of the variable into which the result will be stored +# path: Path to make absolute if it's relative +@go.add_parent_dir_if_relative_path() { + local __gapdirp_parent="$PWD" + + if [[ "$1" == '--parent' ]]; then + __gapdirp_parent="$2" + shift 2 + fi + @go.validate_identifier_or_die 'Absolute path result variable' "$1" + + if [[ "${2:0:1}" != '/' ]]; then + printf -v "$1" '%s/%s' "$__gapdirp_parent" "$2" + else + printf -v "$1" '%s' "$2" + fi +} + # Performs an operation on file system objects and recurses into directories # # Each call to `operation` receives a path to an existing file system object. @@ -83,7 +112,7 @@ # Nonzero if the algorithm was terminated by a nonzero return from `operation` @go.walk_file_system() { local operation - local current + local current local do_bfs local bfs_queue=() diff --git a/tests/path-module/add-parent-dir-if-relative-path.bats b/tests/path-module/add-parent-dir-if-relative-path.bats new file mode 100644 index 0000000..47db2d8 --- /dev/null +++ b/tests/path-module/add-parent-dir-if-relative-path.bats @@ -0,0 +1,31 @@ +#! /usr/bin/env bats + +load ../environment + +setup() { + test_filter + @go.create_test_go_script \ + '. "$_GO_USE_MODULES" "path"' \ + 'declare result' \ + '@go.add_parent_dir_if_relative_path "$@"' \ + 'printf "%s\n" "$result"' +} + +teardown() { + @go.remove_test_go_rootdir +} + +@test "$SUITE: converts a relative path to an absolute path based on PWD" { + run "$TEST_GO_SCRIPT" 'result' 'foo' + assert_success "$TEST_GO_ROOTDIR/foo" +} + +@test "$SUITE: adds a parent to a relative path" { + run "$TEST_GO_SCRIPT" --parent 'foo' 'result' 'bar' + assert_success 'foo/bar' +} + +@test "$SUITE: leaves an absolute path unmodified" { + run "$TEST_GO_SCRIPT" --parent 'foo' 'result' '/bar/baz' + assert_success '/bar/baz' +}