From 8a7f922b52188e07442f005239d655683e8dbb71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Herv=C3=A9=20BECHER?= Date: Mon, 6 Apr 2026 19:22:08 +0200 Subject: [PATCH] handle missing configuration file --- .gitignore | 1 + goto.bash | 39 ++++++++++++++++++++++++++++++++------- 2 files changed, 33 insertions(+), 7 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..419edb1 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +goto.yaml \ No newline at end of file diff --git a/goto.bash b/goto.bash index f841680..9a32e11 100644 --- a/goto.bash +++ b/goto.bash @@ -9,17 +9,25 @@ readonly __GOTO_FILE=${__GOTO_ROOT_DIR}/goto.yaml # path to yq executable readonly __GOTO_YQ=/usr/local/bin/yq +__goto_exists() { + [[ -f ${__GOTO_FILE} ]] +} + __goto_load() { # load the directory mappings from the configuration file into the variable reference passed as parameter # $1: name of the result associative array to create local -n data_ref=$1 + data_ref=() + + if ! __goto_exists; then + return + fi + local entries entry key value mapfile entries < <(${__GOTO_YQ} 'explode(.) | to_entries[] | "\(.key) \(.value)"' ${__GOTO_FILE}) - data_ref=() - for entry in "${entries[@]}"; do if [[ -z "${entry}" ]]; then continue @@ -146,7 +154,11 @@ __goto_add() { dir_path="${PWD}" fi - dir_alias="${dir_alias}" dir_path="${dir_path}" ${__GOTO_YQ} -i '. | (.[env(dir_alias)] = env(dir_path))' ${__GOTO_FILE} + if __goto_exists; then + dir_alias="${dir_alias}" dir_path="${dir_path}" ${__GOTO_YQ} -i '. | (.[env(dir_alias)] = env(dir_path))' ${__GOTO_FILE} + else + dir_alias="${dir_alias}" dir_path="${dir_path}" ${__GOTO_YQ} '.[env(dir_alias)] = env(dir_path)' ${__GOTO_FILE} + fi } __goto_remove() { @@ -154,6 +166,10 @@ __goto_remove() { # command: goto -r # $1: directory alias + if ! __goto_exists; then + return + fi + dir_alias="$1" ${__GOTO_YQ} -i 'del(.[env(dir_alias)])' ${__GOTO_FILE} } @@ -162,13 +178,17 @@ __goto_get() { # command: goto -g # $1: directory alias + if ! __goto_exists; then + return 11 + fi + local dir_path="$(dir_alias="$1" ${__GOTO_YQ} '.[env(dir_alias)] // ""' ${__GOTO_FILE})" - if [[ -n "${dir_path}" ]]; then - __goto_resolve_path "${dir_path}" - else - return 10; + if [[ -z "${dir_path}" ]]; then + return 10 fi + + __goto_resolve_path "${dir_path}" } goto() { @@ -221,6 +241,11 @@ goto() { return fi + if ! __goto_exists; then + echo "goto: $1: configuration file not found" >&2 + return 3 + fi + local dir_path="$(dir_alias="$1" ${__GOTO_YQ} '.[env(dir_alias)] // ""' ${__GOTO_FILE})" if [[ -z "${dir_path}" ]]; then