Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions internal/cli/archive_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,26 @@ func TestArchiveTasksStillWorks(t *testing.T) {
t.Errorf("no-arg archive should still move done tasks: %s", out)
}
}

// TestArchiveRejectsBadHandleBeforeWriting is the regression guard for a
// partial-application bug: archiveNotes used to resolve-and-save inside one
// loop, so a trailing bad handle returned an error AFTER the earlier notes had
// already been archived. The command reported failure while the store had
// quietly lost entries from index/search/recall.
func TestArchiveRejectsBadHandleBeforeWriting(t *testing.T) {
t.Setenv("NT_DIR", t.TempDir())
captureRun(t, "note", "Alpha Note", "--body", "first")
captureRun(t, "note", "Bravo Note", "--body", "second")

// A valid handle followed by a typo must archive NOTHING. The command is
// expected to fail, so use runWithStdout rather than captureRun.
if _, code := runWithStdout("archive", "Alpha Note", "Bravo Note", "no-such-note"); code == 0 {
t.Fatal("archive with an unresolvable handle should exit non-zero")
}

for _, title := range []string{"Alpha Note", "Bravo Note"} {
if out := captureRun(t, "search", title); !strings.Contains(out, title) {
t.Errorf("a failed archive must not archive earlier handles; %q is gone:\n%s", title, out)
}
}
}
15 changes: 14 additions & 1 deletion internal/cli/maintenance.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,27 @@ func cmdArchive(args []string) int {
// and search — a soft, reversible retire.
func archiveNotes(e *mutate.Engine, handles []string, unarchive bool) int {
notes, _ := note.List(e.S)
count := 0
// Resolve EVERY handle before writing anything — the same guarantee cmdRm
// documents and enforces. The previous loop saved as it went and returned
// on the first unresolvable handle, so `nt archive good1 good2 typo` left
// good1 and good2 archived (dropped out of index/search/recall) while the
// only output was an error and a non-zero exit. Nobody re-checks a command
// that reported failure, so that silently shrank the store.
resolved := make([]*note.Note, 0, len(handles))
for _, h := range handles {
n, err := resolveNote(notes, h)
if err != nil {
return fail(fmt.Errorf("archive: %w", err))
}
resolved = append(resolved, n)
}
count := 0
for _, n := range resolved {
n.Archived = !unarchive
n.Updated = time.Now().Format(time.RFC3339)
// A mid-loop Save failure can still leave a partial application, but
// that needs an I/O error rather than a typo — and every note that did
// flip is reported by the count below.
if err := n.Save(); err != nil {
return fail(err)
}
Expand Down
42 changes: 41 additions & 1 deletion internal/mutate/rename.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,10 +158,50 @@ func (e *Engine) TrashNote(n *note.Note) error {
rel = filepath.ToSlash(r)
}
}
dest := filepath.Join(trash, strings.ReplaceAll(rel, "/", "_"))
dest, err := trashDest(trash, rel)
if err != nil {
return err
}
return os.Rename(n.Path, dest)
}

// trashDest picks a free filename inside .trash/ for rel and claims it
// atomically (O_CREATE|O_EXCL), so the subsequent os.Rename can only ever land
// on a name nothing else holds.
//
// This matters because os.Rename silently overwrites its destination, and
// .trash/ is the ONLY recovery path for a trashed note — TrashNote is
// deliberately not a journaled undo transaction, so a clobbered copy is gone
// for good. Two collisions are reachable in normal use: deleting the same rel
// twice (create → delete → recreate → delete), and two distinct notes whose
// paths flatten to the same name (`a/b.md` and `a_b.md` both → `a_b.md`).
// `nt gc --yes` trashes in a loop, so a single run could destroy several notes
// while reporting only "collected N note(s) → .trash/ (recoverable)".
//
// Colliding names get a -2, -3, … suffix before the extension.
func trashDest(trash, rel string) (string, error) {
flat := strings.ReplaceAll(rel, "/", "_")
stem, ext := flat, ""
if e := filepath.Ext(flat); e != "" {
stem, ext = strings.TrimSuffix(flat, e), e
}
for i := 1; i <= 10000; i++ {
cand := filepath.Join(trash, stem+ext)
if i > 1 {
cand = filepath.Join(trash, fmt.Sprintf("%s-%d%s", stem, i, ext))
}
f, err := os.OpenFile(cand, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
if err == nil {
_ = f.Close() // reclaimed by the rename below
return cand, nil
}
if !os.IsExist(err) {
return "", err
}
}
return "", fmt.Errorf("trash: no free name for %q after 10000 attempts", flat)
}

func base(rel string) string {
return strings.TrimSuffix(filepath.Base(rel), ".md")
}
52 changes: 52 additions & 0 deletions internal/mutate/rename_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,55 @@ func TestPureMoveNoRewrite(t *testing.T) {
t.Fatal("file was not moved into the subfolder")
}
}

// TestTrashNoteNeverClobbers is the regression guard for silent data loss:
// TrashNote used to os.Rename straight onto .trash/<flattened rel>, and
// os.Rename overwrites. Deleting the same rel twice therefore destroyed the
// first copy — and .trash/ is the only recovery path, since TrashNote is not a
// journaled undo transaction.
func TestTrashNoteNeverClobbers(t *testing.T) {
e := newEngine(t)
trash := filepath.Join(e.S.Dir, ".trash")

write := func(rel, body string) *note.Note {
t.Helper()
p := filepath.Join(e.S.NotesDir(), filepath.FromSlash(rel))
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
t.Fatal(err)
}
return &note.Note{Path: p, Rel: rel}
}

// Same rel, trashed twice: both copies must survive.
if err := e.TrashNote(write("ref/retry-policy.md", "VERSION ONE")); err != nil {
t.Fatal(err)
}
if err := e.TrashNote(write("ref/retry-policy.md", "VERSION TWO")); err != nil {
t.Fatal(err)
}
// Distinct notes that FLATTEN to the same trash name must also both survive.
if err := e.TrashNote(write("ref_retry-policy.md", "FLATTENED")); err != nil {
t.Fatal(err)
}

found := map[string]bool{}
entries, err := os.ReadDir(trash)
if err != nil {
t.Fatal(err)
}
for _, de := range entries {
b, err := os.ReadFile(filepath.Join(trash, de.Name()))
if err != nil {
t.Fatal(err)
}
found[string(b)] = true
}
for _, want := range []string{"VERSION ONE", "VERSION TWO", "FLATTENED"} {
if !found[want] {
t.Errorf("trash lost %q — .trash/ holds %d file(s): %v", want, len(entries), found)
}
}
}
Loading