From f500903cba77083042927cae15df1966b8d68a3a Mon Sep 17 00:00:00 2001 From: Lucas Date: Wed, 2 Dec 2020 03:40:50 +0000 Subject: [PATCH] sekrit: small refactor --- bin/sekrit.sh | 48 ++++++++++++++++++++++++++++-------------------- 1 file changed, 28 insertions(+), 20 deletions(-) diff --git a/bin/sekrit.sh b/bin/sekrit.sh index 97a1806..fcf9e47 100644 --- a/bin/sekrit.sh +++ b/bin/sekrit.sh @@ -56,11 +56,21 @@ check_key() esac } +make_key_path() +{ + check_key "$1" && printf "%s/%s.gpg" "$SEKRIT_DIR" "$1" +} + to_number() { printf "%u" "$*" 2>/dev/null } +_sekrit_decrypt() +{ + gpg2 -qd "$1" +} + sekrit_add() { force=no @@ -75,22 +85,24 @@ sekrit_add() [ $# -ge 1 ] && [ -n "$1" ] || usage key=$1 - check_key "$key" shift + path=$(make_key_path "$key") - f=$SEKRIT_DIR/$key.gpg - mkdir -p "${f%/*}" + if [ -f "$path" ] && [ $force = no ]; then + err "key $key already exists" + fi - [ -f "$f" ] && [ $force = no ] && err "key $key already exists" + path=$SEKRIT_DIR/$key.gpg + mkdir -p "${path%/*}" if [ $# -gt 0 ]; then # use all additional parameters as a single string printf "%s\n" "$*" else cat - - fi | gpg2 -qae -r "$SEKRIT_GPG_ID" >|"$f" + fi | gpg2 -qae -r "$SEKRIT_GPG_ID" >|"$path" # make it read-only - chmod -- 400 "$f" + chmod -- 400 "$path" } sekrit_cp() @@ -110,8 +122,9 @@ sekrit_cp() [ $# -eq 1 ] || usage key=$1 - - sekrit_has "$key" && sekrit_get "$key" | + path=$(make_key_path "$key") + [ -f "$path" ] || err "no data for key $key" + _sekrit_decrypt "$path" | xclip $rmlastnl -loops 1 -quiet -selection clip 2>/dev/null } @@ -146,22 +159,17 @@ sekrit_get() { [ $# -eq 1 ] || usage key=$1 - check_key "$key" - shift - - f=$SEKRIT_DIR/$key.gpg - [ -f "$f" ] || err "no data for key $key" - gpg2 -qd "$f" + path=$(make_key_path "$key") + [ -f "$path" ] || err "no data for key $key" + _sekrit_decrypt "$path" } sekrit_has() { [ $# -eq 1 ] || usage key=$1 - check_key "$key" - shift - - [ -f "$SEKRIT_DIR/$key.gpg" ] + path=$(make_key_path "$key") + [ -f "$path" ] } ls_key() @@ -169,7 +177,7 @@ ls_key() d=$SEKRIT_DIR$1 find "$d" -type f -name "*.gpg" | sort | - sed -e "s#^$d##" -e "s#\.gpg\$##" + sed -e "s#^$d##" -e 's#\.gpg$##' } sekrit_ls() @@ -179,7 +187,7 @@ sekrit_ls() else for key; do printf "%s:\n" "$key" - ls_key /"$key"/ | sed "s/^/ /" + ls_key "/$key/" | sed "s/^/ /" printf "\n" done fi