commit 8c4930cfcef7c2310f05b7007f95750513e1fd79 from: Omar Polo date: Sat Jan 21 16:46:46 2023 UTC refactor cmd_edit Now it always deletes the temporary file. commit - fc9fec0528e6bbd15f3b6ebbc175b3b907b52a94 commit + 8c4930cfcef7c2310f05b7007f95750513e1fd79 blob - 1c9dd2e24ad508e0c473ae3e524c98fa419cf7bc blob + c71cc3fa34ba3306ee9a0510cd0e48a97fe2d324 --- plass +++ plass @@ -80,6 +80,33 @@ sub mkdirs { unless -d $dir; } +sub edit { + my ($editor, $fh, $tempfile, $epath) = @_; + + open (my $stdout, ">&", STDOUT) or die "can't redirect stdout: $!"; + open (STDOUT, ">&", $fh) or die "can't redirect stdout to $tempfile"; + system ($gpg, @gpg_flags, '-d', $epath); + die "$gpg exited with $?\n" if $? != 0; + open (STDOUT, ">&", $stdout) or die "can't restore stdout: $!"; + + my $oldtime = (stat($fh))[9]; + close($fh); + + system ($editor, $tempfile); + die "editor $editor failed\n" if $? != 0; + + my $newtime = (stat($tempfile))[9]; + if ($oldtime == $newtime) { + say STDERR "no changes made."; + return + } + + open(STDOUT, '>', $epath) or die "can't redirect stdout: $!"; + system ($gpg, @gpg_flags, '-e', '-r', recipient(), '-o', '-', + $tempfile); + die "gpg failed" if $? != 0; +} + sub recipient { open my $fh, '<', "$store/.gpg-id" or die "can't open recipient file"; @@ -168,36 +195,11 @@ sub cmd_edit { my $entry = shift @ARGV; my $epath = name2file $entry; - my ($fh, $filename) = tempfile "/tmp/plass-XXXXXXXXXX"; - - open (my $stdout, ">&", STDOUT) or die "can't redirect stdout: $!"; + my ($fh, $tempfile) = tempfile "/tmp/plass-XXXXXXXXXX"; + eval { edit $editor, $fh, $tempfile, $epath }; + unlink $tempfile; + die "$@\n" if $@; - open (STDOUT, ">&", $fh) or die "can't redirect stdout to $filename"; - system ($gpg, @gpg_flags, '-d', $epath); - die "$gpg exited with $?\n" if $? != 0; - - # restore stdout so the editor can access the TTY if needed. - open (STDOUT, ">&", $stdout) or die "can't restore stdout: $!"; - - my $oldtime = (stat($fh))[9]; - - system ($editor, $filename); - die "editor $editor failed\n" if $? != 0; - - my $newtime = (stat($filename))[9]; - - if ($oldtime == $newtime) { - say STDERR "no changes made."; - unlink $filename or die "can't delete $filename: $!\n"; - return - } - - open(STDIN, '<', $filename) or die "can't redirect stdin: $!"; - open(STDOUT, '>', $epath) or die "can't redirect stdout: $!"; - system ($gpg, @gpg_flags, '-e', '-r', recipient(), '-o', '-'); - unlink $filename or die "can't delete $filename: $!\n"; - die "gpg failed" if $? != 0; - got_add $epath; got_ci "update $entry"; }