From 8c9c9901a14eb838002e99d8613e2afcfdabea26 Mon Sep 17 00:00:00 2001 From: Roger Date: Wed, 28 Oct 2026 17:05:28 +0800 Subject: [PATCH] fix(export): pack --zip before removing the outputs (#663) CompressDir deleted each file as it was added and wrote the zip last, so a failure lost the output, and it packed and deleted every file in -d. The writer now packs only the files it wrote, renames the zip into place, and only then removes them. --- cmd/hack-browser-data/export_golden_test.go | 19 ++-- cmd/hack-browser-data/extract.go | 16 +--- internal/app/app.go | 3 + internal/app/execute.go | 2 +- internal/export/writer.go | 91 ++++++++++++++++-- internal/export/writer_test.go | 101 +++++++++++++++++++- rfcs/008-output-and-export.md | 2 +- utils/fileutil/fileutil.go | 76 +-------------- utils/fileutil/fileutil_test.go | 52 ---------- 9 files changed, 198 insertions(+), 164 deletions(-) delete mode 100644 utils/fileutil/fileutil_test.go diff --git a/cmd/hack-browser-data/export_golden_test.go b/cmd/hack-browser-data/export_golden_test.go index 1f42950..a9d1879 100644 --- a/cmd/hack-browser-data/export_golden_test.go +++ b/cmd/hack-browser-data/export_golden_test.go @@ -18,7 +18,6 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/export" "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/types" - "github.com/moond4rk/hackbrowserdata/utils/fileutil" ) const ( @@ -66,11 +65,11 @@ func TestExportGolden(t *testing.T) { tc := tc t.Run(tc.format, func(t *testing.T) { dir := filepath.Join(t.TempDir(), "results") - exportWrite(t, dir, tc.format, exportStamps()) + exportWrite(t, dir, tc.format, false, exportStamps()) got := bundleDir(t, dir) if tc.jsonFallback { jsonDir := filepath.Join(t.TempDir(), "results") - exportWrite(t, jsonDir, "json", exportStamps()) + exportWrite(t, jsonDir, "json", false, exportStamps()) assertJSONFallback(t, dir, jsonDir) got = bundleFiles(t, dir, "cookie.json") } @@ -82,29 +81,29 @@ func TestExportGolden(t *testing.T) { } sparse := filepath.Join(t.TempDir(), "sparse") - exportWrite(t, sparse, tc.format, exportSparseStamps()) + exportWrite(t, sparse, tc.format, false, exportSparseStamps()) assert.Equal(t, exportCategoryFiles(tc.ext, category.Password, category.LocalStorage), exportDirFiles(t, sparse)) }) } t.Run("zip", func(t *testing.T) { + loose := filepath.Join(t.TempDir(), "results") + exportWrite(t, loose, "csv", false, exportStamps()) dir := filepath.Join(t.TempDir(), "results") - exportWrite(t, dir, "csv", exportStamps()) - loose := readDirFiles(t, dir) - require.NoError(t, fileutil.CompressDir(dir)) + exportWrite(t, dir, "csv", true, exportStamps()) assert.Equal(t, []string{"results.zip"}, exportDirFiles(t, dir)) archive := filepath.Join(dir, "results.zip") assertGolden(t, "export-zip.golden", zipListing(t, archive)) - assert.Equal(t, loose, exportReadZip(t, archive)) + assert.Equal(t, readDirFiles(t, loose), exportReadZip(t, archive)) }) } -func exportWrite(t *testing.T, dir, format string, stamps []exportStamp) { +func exportWrite(t *testing.T, dir, format string, compress bool, stamps []exportStamp) { t.Helper() f, err := export.ParseFormat(format) require.NoError(t, err) - w, err := export.NewWriter(dir, f) + w, err := export.NewWriter(dir, f, compress) require.NoError(t, err) for _, s := range stamps { require.NoError(t, writeResult(w, s.browser, types.ExtractResult{Profile: types.Profile{Name: s.profile}, Data: s.data})) diff --git a/cmd/hack-browser-data/extract.go b/cmd/hack-browser-data/extract.go index b252cc3..f55aca8 100644 --- a/cmd/hack-browser-data/extract.go +++ b/cmd/hack-browser-data/extract.go @@ -2,8 +2,6 @@ package main import ( "errors" - "fmt" - "path/filepath" "github.com/moond4rk/hackbrowserdata/browser" "github.com/moond4rk/hackbrowserdata/internal/category" @@ -11,7 +9,6 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/log" "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/types" - "github.com/moond4rk/hackbrowserdata/utils/fileutil" ) func extractAndWrite(browsers []browser.Browser, categories []category.Category, outputDir, outputFormat string, compress bool) error { @@ -19,7 +16,7 @@ func extractAndWrite(browsers []browser.Browser, categories []category.Category, if err != nil { return err } - w, err := export.NewWriter(outputDir, format) + w, err := export.NewWriter(outputDir, format, compress) if err != nil { return err } @@ -35,16 +32,7 @@ func extractAndWrite(browsers []browser.Browser, categories []category.Category, } } } - if err := w.Close(); err != nil { - return err - } - if compress { - if err := fileutil.CompressDir(outputDir); err != nil { - return fmt.Errorf("compress: %w", err) - } - log.Infof("Compressed: %s/%s.zip", outputDir, filepath.Base(outputDir)) - } - return nil + return w.Close() } // writeResult bridges today's BrowserData to the writer until the pipeline replaces it. diff --git a/internal/app/app.go b/internal/app/app.go index 050837a..163b127 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -21,6 +21,7 @@ type Flags struct { Categories string Format string Dir string + Zip bool ProfilePath string KeychainPassword string } @@ -31,6 +32,7 @@ type Request struct { Categories []category.Category Format export.Format Dir string + Zip bool ProfilePath string Home string @@ -64,6 +66,7 @@ func Validate(f Flags) (Request, error) { Categories: categories, Format: format, Dir: f.Dir, + Zip: f.Zip, ProfilePath: f.ProfilePath, Home: home, KeychainPassword: func(context.Context) (string, error) { return password, nil }, diff --git a/internal/app/execute.go b/internal/app/execute.go index 2bc31e7..ab16217 100644 --- a/internal/app/execute.go +++ b/internal/app/execute.go @@ -39,7 +39,7 @@ func Execute(ctx context.Context, p Plan, req Request) (Summary, error) { } func execute(ctx context.Context, p Plan, req Request, extractors extractorsFunc, keys keySource) (Summary, error) { - w, err := export.NewWriter(req.Dir, req.Format) + w, err := export.NewWriter(req.Dir, req.Format, req.Zip) if err != nil { return Summary{}, err } diff --git a/internal/export/writer.go b/internal/export/writer.go index 1b8ab06..029a23e 100644 --- a/internal/export/writer.go +++ b/internal/export/writer.go @@ -1,11 +1,14 @@ package export import ( + "archive/zip" "bufio" "errors" "fmt" + "io" "os" "path/filepath" + "sort" "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/internal/log" @@ -13,10 +16,11 @@ import ( ) type Writer struct { - dir string - format Format - files map[category.Category]*categoryFile - failed bool + dir string + format Format + compress bool + files map[category.Category]*categoryFile + failed bool } type categoryFile struct { @@ -27,11 +31,12 @@ type categoryFile struct { count int } -func NewWriter(dir string, f Format) (*Writer, error) { +// NewWriter creates dir. With compress, Close packs the files it wrote into /.zip. +func NewWriter(dir string, f Format, compress bool) (*Writer, error) { if err := os.MkdirAll(dir, 0o750); err != nil { return nil, fmt.Errorf("create output dir: %w", err) } - return &Writer{dir: dir, format: f, files: make(map[category.Category]*categoryFile)}, nil + return &Writer{dir: dir, format: f, compress: compress, files: make(map[category.Category]*categoryFile)}, nil } // Write reorders records in place. @@ -77,7 +82,13 @@ func (w *Writer) Close() error { if err := errors.Join(errs...); err != nil { return err } - if w.failed || len(w.files) == 0 { + if w.failed { + return nil + } + if len(w.files) == 0 { + if w.compress { + return fmt.Errorf("compress: no files to compress in %s", w.dir) + } return nil } fmt.Fprintln(os.Stderr) @@ -87,9 +98,75 @@ func (w *Writer) Close() error { log.Infof(" %-24s %d entries", cf.name, cf.count) } } + if w.compress { + return w.pack() + } return nil } +// pack removes the loose files only after the zip is in place, so a failure leaves every one of them where it was. +func (w *Writer) pack() error { + names := make([]string, 0, len(w.files)) + for _, cf := range w.files { + names = append(names, cf.name) + } + sort.Strings(names) + zipName := filepath.Base(w.dir) + ".zip" + if err := writeZip(filepath.Join(w.dir, zipName), w.dir, names); err != nil { + return fmt.Errorf("compress: %w", err) + } + for _, name := range names { + if err := os.Remove(filepath.Join(w.dir, name)); err != nil { + return fmt.Errorf("compress: remove %s: %w", name, err) + } + } + log.Infof("Compressed: %s/%s", w.dir, zipName) + return nil +} + +// writeZip writes the zip under a temp name beside dst and renames it into place once it is complete. +func writeZip(dst, dir string, names []string) (err error) { + tmp, err := os.OpenFile(dst+".tmp", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o666) + if err != nil { + return fmt.Errorf("create %s: %w", dst, err) + } + defer func() { + if err != nil { + err = errors.Join(err, os.Remove(tmp.Name())) + } + }() + zw := zip.NewWriter(tmp) + for _, name := range names { + if err := addZipFile(zw, filepath.Join(dir, name), name); err != nil { + return errors.Join(fmt.Errorf("add %s: %w", name, err), zw.Close(), tmp.Close()) + } + } + if err := zw.Close(); err != nil { + return errors.Join(fmt.Errorf("finish %s: %w", dst, err), tmp.Close()) + } + if err := tmp.Close(); err != nil { + return fmt.Errorf("finish %s: %w", dst, err) + } + if err := os.Rename(tmp.Name(), dst); err != nil { + return fmt.Errorf("move zip into place: %w", err) + } + return nil +} + +func addZipFile(zw *zip.Writer, path, name string) error { + src, err := os.Open(path) + if err != nil { + return err + } + defer src.Close() + dst, err := zw.Create(name) + if err != nil { + return err + } + _, err = io.Copy(dst, src) + return err +} + func (w *Writer) open(c category.Category) (*categoryFile, error) { if cf, ok := w.files[c]; ok { return cf, nil diff --git a/internal/export/writer_test.go b/internal/export/writer_test.go index 357c5d4..35b1b27 100644 --- a/internal/export/writer_test.go +++ b/internal/export/writer_test.go @@ -1,9 +1,12 @@ package export import ( + "archive/zip" "bytes" "encoding/csv" "encoding/json" + "errors" + "io" "os" "path/filepath" "strings" @@ -59,7 +62,7 @@ func firefoxExtractions() []extraction { func writeAll(t *testing.T, dir string, f Format, extractions ...extraction) { t.Helper() - w, err := NewWriter(dir, f) + w, err := NewWriter(dir, f, false) require.NoError(t, err) for _, e := range extractions { require.NoError(t, w.Write(e.c, e.records)) @@ -94,7 +97,7 @@ func TestFormat_ZeroIsJSON(t *testing.T) { func TestNewWriter_CreatesDir(t *testing.T) { dir := filepath.Join(t.TempDir(), "nested", "results") - _, err := NewWriter(dir, JSON) + _, err := NewWriter(dir, JSON, false) require.NoError(t, err) assert.DirExists(t, dir) } @@ -302,7 +305,7 @@ func TestWrite_AppendsExtractionsInWriteOrder(t *testing.T) { func TestWrite_RejectsRecordOfAnotherCategory(t *testing.T) { dir := t.TempDir() - w, err := NewWriter(dir, JSON) + w, err := NewWriter(dir, JSON, false) require.NoError(t, err) require.EqualError(t, w.Write(category.Cookie, []record.Record{&record.Login{}}), "*record.Login is not a cookie record") require.NoError(t, w.Close()) @@ -315,7 +318,7 @@ func TestWrite_RejectsRecordOfAnotherCategory(t *testing.T) { // A failed Write must not cost the files already written: Close still completes them. func TestClose_AfterFailedWriteKeepsEarlierFiles(t *testing.T) { dir := t.TempDir() - w, err := NewWriter(dir, JSON) + w, err := NewWriter(dir, JSON, false) require.NoError(t, err) require.NoError(t, w.Write(category.Password, []record.Record{&record.Login{URL: "https://kept.example"}})) @@ -333,8 +336,98 @@ func TestClose_AfterFailedWriteKeepsEarlierFiles(t *testing.T) { assert.Empty(t, cookies) } +// --- --zip --- + +func TestClose_ZipReplacesTheFilesWithOneArchive(t *testing.T) { + loose := filepath.Join(t.TempDir(), "results") + writeAll(t, loose, CSV, chromeExtractions()...) + + dir := filepath.Join(t.TempDir(), "results") + require.NoError(t, zipAll(dir, chromeExtractions()...)) + + assert.Equal(t, []string{"results.zip"}, dirNames(t, dir)) + assert.Equal(t, dirFiles(t, loose), zipFiles(t, filepath.Join(dir, "results.zip"))) +} + +// The output is the files this run wrote; anything else in the directory is not the writer's to pack or delete. +func TestClose_ZipLeavesOtherFilesAlone(t *testing.T) { + dir := filepath.Join(t.TempDir(), "results") + require.NoError(t, os.MkdirAll(dir, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "notes.txt"), []byte("mine"), 0o600)) + + require.NoError(t, zipAll(dir, chromeExtractions()...)) + assert.Equal(t, []string{"notes.txt", "results.zip"}, dirNames(t, dir)) + assert.NotContains(t, zipFiles(t, filepath.Join(dir, "results.zip")), "notes.txt") +} + +func TestClose_ZipFailureKeepsTheFiles(t *testing.T) { + dir := filepath.Join(t.TempDir(), "results") + // A non-empty directory in the zip's place makes the final rename fail on every OS. + require.NoError(t, os.MkdirAll(filepath.Join(dir, "results.zip", "taken"), 0o755)) + + require.Error(t, zipAll(dir, chromeExtractions()...)) + assert.Equal(t, []string{"cookie.csv", "history.csv", "password.csv", "results.zip"}, dirNames(t, dir)) +} + +func TestClose_ZipWithNothingWrittenFails(t *testing.T) { + dir := filepath.Join(t.TempDir(), "results") + require.Error(t, zipAll(dir)) + assert.Empty(t, dirNames(t, dir)) +} + // --- helpers --- +func zipAll(dir string, extractions ...extraction) error { + w, err := NewWriter(dir, CSV, true) + if err != nil { + return err + } + for _, e := range extractions { + if err := w.Write(e.c, e.records); err != nil { + return errors.Join(err, w.Close()) + } + } + return w.Close() +} + +func dirNames(t *testing.T, dir string) []string { + t.Helper() + entries, err := os.ReadDir(dir) + require.NoError(t, err) + names := make([]string, 0, len(entries)) + for _, e := range entries { + names = append(names, e.Name()) + } + return names +} + +func dirFiles(t *testing.T, dir string) map[string]string { + t.Helper() + files := make(map[string]string) + for _, name := range dirNames(t, dir) { + data, err := os.ReadFile(filepath.Join(dir, name)) + require.NoError(t, err) + files[name] = string(data) + } + return files +} + +func zipFiles(t *testing.T, path string) map[string]string { + t.Helper() + r, err := zip.OpenReader(path) + require.NoError(t, err) + defer r.Close() + files := make(map[string]string, len(r.File)) + for _, f := range r.File { + rc, err := f.Open() + require.NoError(t, err) + data, err := io.ReadAll(rc) + require.NoError(t, errors.Join(err, rc.Close())) + files[f.Name] = string(data) + } + return files +} + func readCSV(t *testing.T, path string) [][]string { t.Helper() raw, err := os.ReadFile(path) diff --git a/rfcs/008-output-and-export.md b/rfcs/008-output-and-export.md index 18af4df..a035539 100644 --- a/rfcs/008-output-and-export.md +++ b/rfcs/008-output-and-export.md @@ -64,7 +64,7 @@ Extractors emit records one at a time ([RFC-003](003-core-types.md)), but sortin ## `--zip` -`--zip` keeps today's result — `/.zip` with the files at its top level, and the loose files removed — but fixes the order. Today `fileutil.CompressDir` deletes each file as soon as it is added to an in-memory zip and writes the zip to disk last, so any failure along the way loses the output. The rewrite writes the zip to a temp file, closes and renames it into place, and only then deletes the originals; a failure leaves every output file where it was. +`--zip` keeps today's result — `/.zip` with the files at its top level, and the loose files removed — but fixes the order. Today `fileutil.CompressDir` deletes each file as soon as it is added to an in-memory zip and writes the zip to disk last, so any failure along the way loses the output. The rewrite writes the zip to a temp file, closes and renames it into place, and only then deletes the originals; a failure leaves every output file where it was. It packs only the files the run wrote: today every file in the directory is packed and deleted, whoever wrote it. ## Output fixes (listed exceptions to "unchanged") diff --git a/utils/fileutil/fileutil.go b/utils/fileutil/fileutil.go index 8d6c072..948558b 100644 --- a/utils/fileutil/fileutil.go +++ b/utils/fileutil/fileutil.go @@ -1,12 +1,6 @@ package fileutil -import ( - "archive/zip" - "bytes" - "fmt" - "os" - "path/filepath" -) +import "os" // FileExists checks if the file exists in the provided path. func FileExists(filename string) bool { @@ -19,71 +13,3 @@ func FileExists(filename string) bool { } return !info.IsDir() } - -// CompressDir compresses the directory into a zip file -func CompressDir(dir string) error { - files, err := os.ReadDir(dir) - if err != nil { - return fmt.Errorf("read dir error: %w", err) - } - if len(files) == 0 { - return fmt.Errorf("no files to compress in: %s", dir) - } - - buffer := new(bytes.Buffer) - zipWriter := zip.NewWriter(buffer) - defer func() { - _ = zipWriter.Close() - }() - - for _, file := range files { - if err := addFileToZip(zipWriter, filepath.Join(dir, file.Name())); err != nil { - return fmt.Errorf("failed to add file to zip: %w", err) - } - } - - if err := zipWriter.Close(); err != nil { - return fmt.Errorf("error closing zip writer: %w", err) - } - - zipFilename := filepath.Join(dir, filepath.Base(dir)+".zip") - return writeFile(buffer, zipFilename) -} - -func addFileToZip(zw *zip.Writer, filename string) error { - content, err := os.ReadFile(filename) - if err != nil { - return fmt.Errorf("error reading file %s: %w", filename, err) - } - - fw, err := zw.Create(filepath.Base(filename)) - if err != nil { - return fmt.Errorf("error creating zip entry for %s: %w", filename, err) - } - - if _, err = fw.Write(content); err != nil { - return fmt.Errorf("error writing content to zip for %s: %w", filename, err) - } - - if err = os.Remove(filename); err != nil { - return fmt.Errorf("error removing original file %s: %w", filename, err) - } - - return nil -} - -func writeFile(buffer *bytes.Buffer, filename string) error { - outFile, err := os.Create(filename) - if err != nil { - return fmt.Errorf("error creating output file %s: %w", filename, err) - } - defer func() { - _ = outFile.Close() - }() - - if _, err = buffer.WriteTo(outFile); err != nil { - return fmt.Errorf("error writing data to file %s: %w", filename, err) - } - - return nil -} diff --git a/utils/fileutil/fileutil_test.go b/utils/fileutil/fileutil_test.go deleted file mode 100644 index 080e00c..0000000 --- a/utils/fileutil/fileutil_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package fileutil - -import ( - "os" - "path/filepath" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func setupTestDir(t *testing.T, files []string) string { - t.Helper() // Marks the function as a helper function. - - tempDir, err := os.MkdirTemp("", "testCompressDir") - require.NoError(t, err, "failed to create a temporary directory") - - for _, file := range files { - filePath := filepath.Join(tempDir, file) - err := os.WriteFile(filePath, []byte("test content"), 0o644) - require.NoError(t, err, "failed to create a test file") - } - return tempDir -} - -func TestCompressDir(t *testing.T) { - t.Run("Normal Operation", func(t *testing.T) { - tempDir := setupTestDir(t, []string{"file1.txt", "file2.txt", "file3.txt"}) - defer os.RemoveAll(tempDir) - - err := CompressDir(tempDir) - require.NoError(t, err, "compressDir should not return an error") - - // Check if the zip file exists - zipFile := filepath.Join(tempDir, filepath.Base(tempDir)+".zip") - assert.FileExists(t, zipFile, "zip file should be created") - }) - - t.Run("Directory Does Not Exist", func(t *testing.T) { - err := CompressDir("/path/to/nonexistent/directory") - require.Error(t, err, "should return an error for non-existent directory") - }) - - t.Run("Empty Directory", func(t *testing.T) { - tempDir, err := os.MkdirTemp("", "testEmptyDir") - require.NoError(t, err, "failed to create empty test directory") - defer os.RemoveAll(tempDir) - - err = CompressDir(tempDir) - require.Error(t, err, "should return an error for an empty directory") - }) -}