feat: a running lazysecrets says when a newer one was installed over it (#90)

Co-authored-by: Karl-Einar Bergstrøm <karl-einarb@outlook.com>
This commit was merged in pull request #90.
This commit is contained in:
keb authored and keb committed 2026-10-19 21:31:05 +02:00
1 parent d0a8b1390d
commit 6a7f53e236
7 files changed
+164 -1

No files matched your search

+47
View File
@@ -0,0 +1,47 @@
package update
import (
"context"
"os"
"os/exec"
"strings"
)
// Binary is the binary a running lazysecrets started from, to notice a
// newer one installed over it (by install.sh, go install, a package
// manager or another lazysecrets): the running one keeps its old code
// until it restarts.
type Binary struct {
path string // as started, not resolved: a symlink a package manager moves is followed
info os.FileInfo
}
// Running is the binary this process runs, as it is now.
func Running() (*Binary, error) {
exe, err := os.Executable()
if err != nil {
return nil, err
}
info, err := os.Stat(exe)
if err != nil {
return nil, err
}
return &Binary{path: exe, info: info}, nil
}
// Replaced is the version of a binary installed over b since it was last
// looked at, as its --version says; ok is false while it's the same
// file. A look costs a stat; --version runs only when it changed.
func (b *Binary) Replaced(ctx context.Context) (version string, ok bool) {
info, err := os.Stat(b.path)
if err != nil || (os.SameFile(b.info, info) && info.ModTime().Equal(b.info.ModTime())) {
return "", false
}
out, err := exec.CommandContext(ctx, b.path, "--version").Output()
if err != nil {
return "", false // mid-install, or broken: look again later
}
b.info = info
v, ok := strings.CutPrefix(strings.TrimSpace(string(out)), "lazysecrets ")
return v, ok
}
+40
View File
@@ -0,0 +1,40 @@
package update
import (
"context"
"os"
"path/filepath"
"testing"
"time"
)
func TestBinaryReplaced(t *testing.T) {
dir := t.TempDir()
exe := filepath.Join(dir, "lazysecrets")
write := func(version string) {
t.Helper()
tmp := filepath.Join(dir, ".new")
if err := os.WriteFile(tmp, []byte("#!/bin/sh\necho lazysecrets "+version+"\n"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.Rename(tmp, exe); err != nil { // as Install and install.sh do
t.Fatal(err)
}
}
write("v0.3.0")
info, _ := os.Stat(exe)
b := &Binary{path: exe, info: info}
ctx := context.Background()
if v, ok := b.Replaced(ctx); ok {
t.Errorf("the same file: replaced by %q", v)
}
time.Sleep(10 * time.Millisecond)
write("v0.3.1")
if v, ok := b.Replaced(ctx); !ok || v != "v0.3.1" {
t.Errorf("installed over: %q %t", v, ok)
}
if v, ok := b.Replaced(ctx); ok {
t.Errorf("said again: %q", v)
}
}