[PATCH 1/2] generate: refactor to use temporary file

Arsen Arsenović arsen at aarsen.me
Sun Jun 27 20:23:58 UTC 2021


This allows us to optionally run an editor on the file, and also
simplifies the code a bit.
---
 src/password-store.sh | 22 ++++++++++++----------
 1 file changed, 12 insertions(+), 10 deletions(-)

diff --git a/src/password-store.sh b/src/password-store.sh
index a0dcf2e..d1d8aa6 100755
--- a/src/password-store.sh
+++ b/src/password-store.sh
@@ -538,17 +538,19 @@ cmd_generate() {
 
 	read -r -n $length pass < <(LC_ALL=C tr -dc "$characters" < /dev/urandom)
 	[[ ${#pass} -eq $length ]] || die "Could not generate password from /dev/urandom."
-	if [[ $inplace -eq 0 ]]; then
-		echo "$pass" | $GPG -e "${GPG_RECIPIENT_ARGS[@]}" -o "$passfile" "${GPG_OPTS[@]}" || die "Password encryption aborted."
-	else
-		local passfile_temp="${passfile}.tmp.${RANDOM}.${RANDOM}.${RANDOM}.${RANDOM}.--"
-		if { echo "$pass"; $GPG -d "${GPG_OPTS[@]}" "$passfile" | tail -n +2; } | $GPG -e "${GPG_RECIPIENT_ARGS[@]}" -o "$passfile_temp" "${GPG_OPTS[@]}"; then
-			mv "$passfile_temp" "$passfile"
-		else
-			rm -f "$passfile_temp"
-			die "Could not reencrypt new password."
-		fi
+
+	tmpdir # Defines $SECURE_TMPDIR
+	local tmp_file="$(mktemp -u "$SECURE_TMPDIR/XXXXXX")-${path//\//-}.txt"
+	printf '%s\n' "$pass" > "$tmp_file"
+
+	if ! [[ $inplace -eq 0 ]]; then
+		$GPG -d "${GPG_OPTS[@]}" "$passfile" | sed 1d >> "$tmp_file"
 	fi
+
+	while ! $GPG -e "${GPG_RECIPIENT_ARGS[@]}" -o "$passfile" "${GPG_OPTS[@]}" "$tmp_file"; do
+		yesno "GPG encryption failed. Would you like to try again?"
+	done
+
 	local verb="Add"
 	[[ $inplace -eq 1 ]] && verb="Replace"
 	git_add_file "$passfile" "$verb generated password for ${path}."
-- 
2.31.1



More information about the Password-Store mailing list