package zitcli
import (
"context"
"errors"
"os"
"path/filepath"
"testing"
"craftdesign.group/quarry/internal/lease"
)
// A pack that rewrote the store reports the store file's size before
// and after, measured here, and how many shunned artifacts it reclaimed;
// a second pack with nothing to do says so.
func TestPackReportsSizesAndNothingToDo(t *testing.T) {
repo := testRepo(t, 3)
c := New(repo)
tok := lease.Unguarded("test")
res, err := c.Pack(tok, context.Background())
if err != nil {
t.Fatalf("FAIL: pack: %v", err)
}
if res.Before <= 0 || res.After <= 0 {
t.Errorf("FAIL: sizes before/after = %d/%d, want both measured", res.Before, res.After)
}
again, err := c.Pack(tok, context.Background())
if err != nil {
t.Fatalf("FAIL: second pack: %v", err)
}
if !again.Nothing || again.Before != again.After {
t.Errorf("FAIL: second pack = %+v, want nothing-to-do with equal sizes", again)
}
if !t.Failed() {
t.Log("ok")
}
}
// zit's own refusal of a pack a write landed in is the typed error, not
// a generic failure, and the reclaim count is read off the summary line.
func TestPackTypedAbortAndReclaimCount(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, ".zit"), make([]byte, 100), 0o644); err != nil {
t.Fatal(err)
}
fakeZit(t, `echo "zit pack: repository changed during pack; aborted (original is intact)" >&2; exit 1`)
c := &Client{repo: dir}
if _, err := c.Pack(lease.Unguarded("test"), context.Background()); !errors.Is(err, ErrPackAborted) {
t.Errorf("FAIL: err = %v, want ErrPackAborted", err)
}
fakeZit(t, `echo "packed: 5 artifacts walked, 2 re-deltaed, 3 shunned reclaimed, 100 -> 90 bytes"`)
res, err := c.Pack(lease.Unguarded("test"), context.Background())
if err != nil {
t.Fatalf("FAIL: %v", err)
}
if res.Reclaimed != 3 || res.Nothing {
t.Errorf("FAIL: result = %+v, want 3 reclaimed", res)
}
fakeZit(t, `echo "already packed: 6009 artifacts walked, 5 re-deltaed, 893608 -> 993608 bytes"`)
res, err = c.Pack(lease.Unguarded("test"), context.Background())
if err != nil || !res.Nothing {
t.Errorf("FAIL: 0.14.21's already-packed line = %+v, %v, want Nothing", res, err)
}
fakeZit(t, `echo "some other wording"`)
if _, err := c.Pack(lease.Unguarded("test"), context.Background()); err == nil {
t.Errorf("FAIL: an unrecognized result was taken for success")
}
if !t.Failed() {
t.Log("ok")
}
}