fix: report unreadable sources and tidy the pipeline (#675)

A Stat error other than not-exist was reported as absent, and the --zip archive was readable by other users.
The rest is review follow-up: export no longer prints, one runner type, shared name helpers, a trimmed log API.
This commit is contained in:
Roger authored and GitHub committed 2026-11-01 23:42:13 +08:00
1 parent 6d6191b4c6
commit 4e98ba7884
33 files changed
+303 -315

No files matched your search

+8 -17
View File
@@ -134,7 +134,7 @@ func ListRequest() (Request, error) {
if err != nil {
return Request{}, err
}
return Request{Browser: "all", Categories: category.All(), Home: home}, nil
return Request{Browser: allBrowsers, Categories: category.All(), Home: home}, nil
}
func homeDir() (string, error) {
@@ -145,20 +145,20 @@ func homeDir() (string, error) {
return home, nil
}
const allBrowsers = "all"
// parseBrowser accepts all or one of this OS's browser IDs; an ID from another OS's table has nothing to find here.
func parseBrowser(s string) (string, error) {
id := strings.ToLower(strings.TrimSpace(s))
if id == "" || id == "all" {
return "all", nil
if id == "" || id == allBrowsers {
return allBrowsers, nil
}
ids := []string{"all"}
for _, def := range browser.Supported() {
if def.ID == id {
return id, nil
}
ids = append(ids, def.ID)
}
return "", fmt.Errorf("unknown browser %q, available: %s", s, strings.Join(ids, "|"))
return "", fmt.Errorf("unknown browser %q, available: %s|%s", s, allBrowsers, strings.Join(browser.IDs(), "|"))
}
// checkOutputDir creates nothing: -d must already be a directory, or its nearest existing ancestor must be one that a
@@ -191,7 +191,7 @@ func checkProfilePath(id, path string) (string, error) {
if path == "" {
return "", nil
}
if id == "all" {
if id == allBrowsers {
log.Warnf("-p needs a specific -b; ignoring %s", path)
return "", nil
}
@@ -221,7 +221,7 @@ func parseCategories(s string) ([]category.Category, error) {
}
c, err := category.Parse(name)
if err != nil {
return nil, fmt.Errorf("%w, available: all|%s", err, categoryNames())
return nil, fmt.Errorf("%w, available: all|%s", err, strings.Join(category.Names(), ","))
}
if !seen[c] {
seen[c] = true
@@ -233,12 +233,3 @@ func parseCategories(s string) ([]category.Category, error) {
}
return categories, nil
}
func categoryNames() string {
all := category.All()
names := make([]string, len(all))
for i, c := range all {
names[i] = c.String()
}
return strings.Join(names, ",")
}
+1 -1
View File
@@ -56,7 +56,7 @@ func archiveFiles(p Plan, dirs []browser.UserDataDir) []snapshot.File {
for _, dir := range dirs {
for _, prof := range dir.Profiles {
for _, src := range chromium.ArchiveSources(dir) {
if f, ok := firstOnDisk(dir, prof, src); ok {
if f, ok, err := firstOnDisk(dir, prof, src); err == nil && ok {
add(f)
}
}
+5 -4
View File
@@ -20,11 +20,11 @@ type Discovery struct {
func Discover(req Request) Discovery {
var d Discovery
for _, def := range browser.Supported() {
if req.Browser != "all" && def.ID != req.Browser {
if req.Browser != allBrowsers && def.ID != req.Browser {
continue
}
opts := browser.DiscoverOptions{Home: req.Home}
if req.Browser != "all" {
if req.Browser != allBrowsers {
opts.ProfilePath = req.ProfilePath
}
dirs, err := discover(def, opts)
@@ -37,7 +37,8 @@ func Discover(req Request) Discovery {
}
// withData keeps the profiles holding a file some category reads, and the user data dirs with such a profile: a
// Preferences marker alone is no data, so a profile created and never used is not listed, archived, or keyed.
// Preferences marker alone is no data, so a profile created and never used is not listed, archived, or keyed. A
// profile whose files cannot be checked stays, so the plan reports the error.
func withData(dirs []browser.UserDataDir) []browser.UserDataDir {
extractors := extractorsWith(nil)
var out []browser.UserDataDir
@@ -61,7 +62,7 @@ func hasData(dir browser.UserDataDir, p browser.Profile, ex browser.Extractors)
if len(x.Sources) == 0 {
continue
}
if _, ok := locate(dir, p, x.Sources); ok {
if _, ok, err := locate(dir, p, x.Sources); ok || err != nil {
return true
}
}
+7
View File
@@ -88,3 +88,10 @@ func TestDiscover_UnreadableDirIsReported(t *testing.T) {
assert.Equal(t, Extraction{DirID: "chrome"}, d.Failed[0].Extraction)
assert.Equal(t, OutcomeError, d.Failed[0].Outcome)
}
// Dropping a profile whose files cannot be checked would hide the failure; the plan reports it instead.
func TestWithData_KeepsAProfileItCannotCheck(t *testing.T) {
dir := chromeDir(t, "chrome", "Default")
lock(t, filepath.Join(dir.Path, "Default"))
assert.Len(t, withData([]browser.UserDataDir{dir}), 1)
}
+35 -12
View File
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"io/fs"
"os"
"sync"
"github.com/moond4rk/hackbrowserdata/internal/browser"
@@ -44,14 +45,30 @@ func execute(ctx context.Context, p Plan, req Request, extractors extractorsFunc
if err != nil {
return Summary{}, err
}
s, err := runPlan(ctx, p, w, extractors, keys, true)
return s, errors.Join(err, w.Close())
s, err := runner{w: w, extractors: extractors, keys: keys, announce: true}.run(ctx, p)
closeErr := w.Close()
announceOutput(w.Output())
return s, errors.Join(err, closeErr)
}
func announceOutput(out export.Output) {
if len(out.Files) == 0 {
return
}
fmt.Fprintln(os.Stderr)
log.Infof("Exported to %s/", out.Dir)
for _, f := range out.Files {
log.Infof(" %-24s %d entries", f.Name, f.Count)
}
if out.Zip != "" {
log.Infof("Compressed: %s/%s", out.Dir, out.Zip)
}
}
// Count runs every planned extraction with no key and the keychain locked, and counts the records instead of exporting
// them, which is all list --detail shows.
func Count(ctx context.Context, p Plan, req Request) (Summary, error) {
return runPlan(ctx, p, discard{}, extractorsWith(loginKeychain(req)), dumpKeys(nil), false)
return runner{w: discard{}, extractors: extractorsWith(loginKeychain(req)), keys: dumpKeys(nil)}.run(ctx, p)
}
// recordWriter takes each extraction's records as it finishes.
@@ -63,13 +80,21 @@ type discard struct{}
func (discard) Write(category.Category, []record.Record) error { return nil }
func runPlan(ctx context.Context, p Plan, w recordWriter, extractors extractorsFunc, keys keySource, announce bool) (Summary, error) {
// runner is what every user data dir of one run shares; announce logs each dir as it starts.
type runner struct {
w recordWriter
extractors extractorsFunc
keys keySource
announce bool
}
func (r runner) run(ctx context.Context, p Plan) (Summary, error) {
results := append([]Result(nil), p.Skipped...)
for _, dir := range p.Dirs {
if err := ctx.Err(); err != nil {
return Summary{Results: results}, fmt.Errorf("run stopped: %w", err)
}
dirResults, err := executeDir(ctx, dir, p, w, extractors, keys, announce)
dirResults, err := r.runDir(ctx, dir, p)
results = append(results, dirResults...)
if err != nil {
return Summary{Results: results}, err
@@ -78,14 +103,12 @@ func runPlan(ctx context.Context, p Plan, w recordWriter, extractors extractorsF
return Summary{Results: results}, nil
}
func executeDir(ctx context.Context, dir browser.UserDataDir, p Plan, w recordWriter, extractors extractorsFunc,
keys keySource, announce bool,
) ([]Result, error) {
func (r runner) runDir(ctx context.Context, dir browser.UserDataDir, p Plan) ([]Result, error) {
extractions := extractionsOf(p, dir.ID)
if len(extractions) == 0 {
return nil, nil
}
if announce {
if r.announce {
log.Infof("Extracting %s...", dir.Def.Name)
}
@@ -107,7 +130,7 @@ func executeDir(ctx context.Context, dir browser.UserDataDir, p Plan, w recordWr
masterKeys func(context.Context) masterkey.Set
)
if dir.Def.Base == browser.Chromium {
dk = &dirKeys{retrieve: func(ctx context.Context) (masterkey.Set, error) { return keys(ctx, dir, snap) }}
dk = &dirKeys{retrieve: func(ctx context.Context) (masterkey.Set, error) { return r.keys(ctx, dir, snap) }}
masterKeys = dk.get
}
@@ -115,7 +138,7 @@ func executeDir(ctx context.Context, dir browser.UserDataDir, p Plan, w recordWr
byProfile := make(map[string]browser.Extractors, len(dir.Profiles))
for _, prof := range dir.Profiles {
profiles[prof.Name] = prof
byProfile[prof.Name] = extractors(dir, prof)
byProfile[prof.Name] = r.extractors(dir, prof)
}
results := make([]Result, 0, len(extractions)+1)
@@ -132,7 +155,7 @@ func executeDir(ctx context.Context, dir browser.UserDataDir, p Plan, w recordWr
c := &collector{browser: dir.Def.Name, profile: prof.Name}
err := x.Extract(ctx, browser.NewProfileSnapshot(snap, prof, masterKeys), c)
// Records emitted before an extraction failed are kept, as they always were.
if writeErr := w.Write(e.Category, c.records); writeErr != nil {
if writeErr := r.w.Write(e.Category, c.records); writeErr != nil {
return results, writeErr
}
results = append(results, c.result(e, err))
+1 -1
View File
@@ -61,7 +61,7 @@ func retrieveKeys(ctx context.Context, dir browser.UserDataDir, keys keySource)
defer closeSnapshot(d)
var files []snapshot.File
for _, src := range chromium.KeySources(dir) {
if f, ok := firstOnDisk(dir, browser.Profile{}, src); ok {
if f, ok, err := firstOnDisk(dir, browser.Profile{}, src); err == nil && ok {
files = append(files, f)
}
}
+23 -16
View File
@@ -1,8 +1,9 @@
package app
import (
"errors"
"io/fs"
"os"
"path"
"path/filepath"
"github.com/moond4rk/hackbrowserdata/internal/browser"
@@ -48,7 +49,11 @@ func newPlan(d Discovery, req Request, extractors extractorsFunc) Plan {
p.Skipped = append(p.Skipped, Result{Extraction: e, Outcome: OutcomeUnsupported})
continue
}
files, ok := locate(dir, prof, x.Sources)
files, ok, err := locate(dir, prof, x.Sources)
if err != nil {
p.Skipped = append(p.Skipped, Result{Extraction: e, Outcome: OutcomeError, Err: err})
continue
}
if !ok {
p.Skipped = append(p.Skipped, Result{Extraction: e, Outcome: OutcomeAbsent})
continue
@@ -68,35 +73,37 @@ func newPlan(d Discovery, req Request, extractors extractorsFunc) Plan {
// locate finds each source's first candidate on disk. An extraction needs every required source and at least one of
// the profile's own; a shared one such as Local State never makes it present by itself. An extraction that reads no
// file, such as Safari's keychain passwords, always runs.
func locate(dir browser.UserDataDir, p browser.Profile, sources []browser.Source) ([]snapshot.File, bool) {
// file, such as Safari's keychain passwords, always runs. A candidate that cannot be checked is an error, not absence.
func locate(dir browser.UserDataDir, p browser.Profile, sources []browser.Source) ([]snapshot.File, bool, error) {
if len(sources) == 0 {
return nil, true
return nil, true, nil
}
var files []snapshot.File
present := false
for _, src := range sources {
f, ok := firstOnDisk(dir, p, src)
f, ok, err := firstOnDisk(dir, p, src)
switch {
case err != nil:
return nil, false, err
case ok:
files = append(files, f)
present = present || !src.Shared
case !src.Optional:
return nil, false
return nil, false, nil
}
}
return files, present
return files, present, nil
}
func firstOnDisk(dir browser.UserDataDir, p browser.Profile, src browser.Source) (snapshot.File, bool) {
for _, rel := range src.Paths {
if !src.Shared {
rel = path.Join(p.Dir, rel)
}
func firstOnDisk(dir browser.UserDataDir, p browser.Profile, src browser.Source) (snapshot.File, bool, error) {
for _, rel := range src.Candidates(p) {
info, err := os.Stat(filepath.Join(dir.Path, filepath.FromSlash(rel)))
if err == nil && info.IsDir() == src.IsDir {
return snapshot.File{DirID: string(dir.ID), From: dir.Path, Rel: rel, IsDir: src.IsDir}, true
switch {
case err == nil && info.IsDir() == src.IsDir:
return snapshot.File{DirID: string(dir.ID), From: dir.Path, Rel: rel, IsDir: src.IsDir}, true, nil
case err != nil && !errors.Is(err, fs.ErrNotExist):
return snapshot.File{}, false, err
}
}
return snapshot.File{}, false
return snapshot.File{}, false, nil
}
+30
View File
@@ -2,8 +2,10 @@ package app
import (
"errors"
"io/fs"
"os"
"path/filepath"
"runtime"
"testing"
"github.com/stretchr/testify/assert"
@@ -115,3 +117,31 @@ func TestNewPlan_ExtractorWithoutSourcesRuns(t *testing.T) {
assert.Empty(t, got.Files)
assert.Empty(t, got.Skipped)
}
// lock makes dir unsearchable until the test ends, so a Stat of anything under it fails with permission denied.
func lock(t *testing.T, dir string) {
t.Helper()
if runtime.GOOS == "windows" {
t.Skip("mode bits do not restrict Stat on Windows")
}
if os.Geteuid() == 0 {
t.Skip("root ignores mode bits")
}
require.NoError(t, os.Chmod(dir, 0))
t.Cleanup(func() { assert.NoError(t, os.Chmod(dir, 0o700)) })
}
// A candidate that cannot be checked is not absence: the extraction is an error, and nothing is captured for it.
func TestNewPlan_UnreadableSourceIsAnError(t *testing.T) {
dir := chromeDir(t, "chrome", "Default")
lock(t, filepath.Join(dir.Path, "Default"))
base := fakeBase(map[category.Category]extractFunc{category.History: nil})
got := newPlan(Discovery{Dirs: []browser.UserDataDir{dir}}, Request{Categories: []category.Category{category.History}}, base)
require.Len(t, got.Skipped, 1)
assert.Equal(t, OutcomeError, got.Skipped[0].Outcome)
require.ErrorIs(t, got.Skipped[0].Err, fs.ErrPermission)
assert.Empty(t, got.Extractions)
assert.Empty(t, got.Files)
}
+4 -4
View File
@@ -57,9 +57,9 @@ func ValidateRestore(f RestoreFlags) (Request, masterkey.Dump, error) {
}
filter := strings.ToLower(strings.TrimSpace(f.Browser))
if filter == "" {
filter = "all"
filter = allBrowsers
}
if filter != "all" && len(vaultsOf(dump, filter)) == 0 {
if filter != allBrowsers && len(vaultsOf(dump, filter)) == 0 {
return Request{}, masterkey.Dump{}, fmt.Errorf("no vault for browser %q in keys (have: %s)", filter, vaultKeys(dump.Vaults))
}
req := Request{Browser: filter, Categories: categories, Format: format, Dir: f.Dir, Zip: f.Zip}
@@ -115,7 +115,7 @@ func fromManifest(root string, m snapshot.Manifest, vaults []masterkey.Vault, fi
var d Discovery
keys := make(map[browser.DirID]masterkey.Set)
for _, md := range m.Dirs {
if filter != "all" && md.Browser != filter {
if filter != allBrowsers && md.Browser != filter {
continue
}
v, ok := vaultOf(vaults, md)
@@ -247,7 +247,7 @@ func vaultDirID(v masterkey.Vault) browser.DirID {
func vaultsOf(dump masterkey.Dump, filter string) []masterkey.Vault {
var out []masterkey.Vault
for _, v := range dump.Vaults {
if filter == "all" || strings.EqualFold(v.Browser, filter) {
if filter == allBrowsers || strings.EqualFold(v.Browser, filter) {
out = append(out, v)
}
}
+16 -1
View File
@@ -2,7 +2,11 @@
// and the extractors that read them.
package browser
import "github.com/moond4rk/hackbrowserdata/internal/masterkey"
import (
"sort"
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
)
// Def is one browser HBD knows. ID is the -b value and the keys.json vault key; Name is stamped on every record.
type Def struct {
@@ -58,6 +62,17 @@ func Supported() []Def {
return out
}
// IDs are this OS's browser IDs, sorted as the -b help has always listed them.
func IDs() []string {
defs := Supported()
ids := make([]string, len(defs))
for i, d := range defs {
ids[i] = d.ID
}
sort.Strings(ids)
return ids
}
// Lookup finds a browser by ID in the whole table, whatever the running OS, so restore resolves another host's vaults.
func Lookup(id string) (Def, bool) {
for _, d := range defs {
+7
View File
@@ -4,6 +4,7 @@ import (
"os"
"path"
"regexp"
"sort"
"strings"
"testing"
@@ -129,3 +130,9 @@ func TestABERowsMatchPayloadTable(t *testing.T) {
}
}
}
func TestIDs_AreSupportedSorted(t *testing.T) {
ids := IDs()
assert.True(t, sort.StringsAreSorted(ids), "the -b help has always listed them sorted")
assert.ElementsMatch(t, idsOn(Def.Platform), ids)
}
+13 -4
View File
@@ -22,6 +22,18 @@ type Source struct {
Optional bool // the extraction still runs without it
}
// Candidates are the Paths for profile p, relative to the user data dir, in priority order.
func (s Source) Candidates(p Profile) []string {
rels := make([]string, len(s.Paths))
for i, rel := range s.Paths {
if !s.Shared {
rel = path.Join(p.Dir, rel)
}
rels[i] = rel
}
return rels
}
// Extractor declares the sources a category needs and how to parse them.
type Extractor struct {
Sources []Source
@@ -55,10 +67,7 @@ func NewProfileSnapshot(snap snapshot.Snapshot, p Profile, masterKeys func(conte
// Path returns where src was captured: its first candidate present in the snapshot. A candidate that was never captured
// is skipped; one whose copy failed returns that copy's error.
func (ps ProfileSnapshot) Path(src Source) (string, error) {
for _, rel := range src.Paths {
if !src.Shared {
rel = path.Join(ps.Profile.Dir, rel)
}
for _, rel := range src.Candidates(ps.Profile) {
p, err := ps.snap.Path(rel)
if errors.Is(err, fs.ErrNotExist) {
continue
+8
View File
@@ -84,3 +84,11 @@ func TestProfileSnapshotMasterKeys(t *testing.T) {
assert.Equal(t, want, ps.MasterKeys(context.Background()))
assert.Equal(t, 1, calls)
}
func TestSource_Candidates(t *testing.T) {
p := Profile{Name: "Default", Dir: "Default"}
assert.Equal(t, []string{"Default/Network/Cookies", "Default/Cookies"}, Source{Paths: []string{"Network/Cookies", "Cookies"}}.Candidates(p))
assert.Equal(t, []string{"Local State"}, Source{Paths: []string{"Local State"}, Shared: true}.Candidates(p))
assert.Equal(t, []string{"History"}, Source{Paths: []string{"History"}}.Candidates(Profile{Name: "default"}),
"a user data dir that is itself the profile")
}
+9
View File
@@ -47,6 +47,15 @@ func All() []Category {
return []Category{Password, Cookie, Bookmark, History, Download, CreditCard, Extension, LocalStorage, SessionStorage}
}
func Names() []string {
all := All()
names := make([]string, len(all))
for i, c := range all {
names[i] = c.String()
}
return names
}
func Parse(s string) (Category, error) {
for _, c := range All() {
if c.String() == s {
+6
View File
@@ -60,3 +60,9 @@ func TestZeroIsNone(t *testing.T) {
var c Category
assert.NotContains(t, All(), c)
}
func TestNames(t *testing.T) {
assert.Equal(t, []string{
"password", "cookie", "bookmark", "history", "download", "creditcard", "extension", "localstorage", "sessionstorage",
}, Names())
}
+26 -12
View File
@@ -11,7 +11,6 @@ import (
"sort"
"github.com/moond4rk/hackbrowserdata/internal/category"
"github.com/moond4rk/hackbrowserdata/internal/log"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
@@ -21,6 +20,19 @@ type Writer struct {
compress bool
files map[category.Category]*categoryFile
failed bool
out Output
}
// Output is what a clean Close left in the output dir: each category file in category order, and the zip with --zip.
type Output struct {
Dir string
Files []File
Zip string
}
type File struct {
Name string
Count int // records written
}
type categoryFile struct {
@@ -71,12 +83,16 @@ func (w *Writer) write(c category.Category, records []record.Record) error {
return nil
}
// Close finishes the files even after a failed Write, so they keep what was written; only a clean run lists them.
// Close finishes the files even after a failed Write, so they keep what was written; only a clean run lists them in Output.
func (w *Writer) Close() error {
var errs []error
var (
errs []error
files []File
)
for _, c := range category.All() {
if cf, ok := w.files[c]; ok {
errs = append(errs, cf.close())
files = append(files, File{Name: cf.name, Count: cf.count})
}
}
if err := errors.Join(errs...); err != nil {
@@ -91,19 +107,17 @@ func (w *Writer) Close() error {
}
return nil
}
fmt.Fprintln(os.Stderr)
log.Infof("Exported to %s/", w.dir)
for _, c := range category.All() {
if cf, ok := w.files[c]; ok {
log.Infof(" %-24s %d entries", cf.name, cf.count)
}
}
w.out = Output{Dir: w.dir, Files: files}
if w.compress {
return w.pack()
}
return nil
}
func (w *Writer) Output() Output {
return w.out
}
// 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))
@@ -120,13 +134,13 @@ func (w *Writer) pack() error {
return fmt.Errorf("compress: remove %s: %w", name, err)
}
}
log.Infof("Compressed: %s/%s", w.dir, zipName)
w.out.Zip = 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)
tmp, err := os.OpenFile(dst+".tmp", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
if err != nil {
return fmt.Errorf("create %s: %w", dst, err)
}
+38
View File
@@ -9,6 +9,7 @@ import (
"io"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
@@ -334,6 +335,20 @@ func TestClose_AfterFailedWriteKeepsEarlierFiles(t *testing.T) {
var cookies []record.Cookie
readJSON(t, filepath.Join(dir, "cookie.json"), &cookies)
assert.Empty(t, cookies)
assert.Zero(t, w.Output(), "a failed run lists nothing")
}
func TestClose_OutputListsTheFilesInCategoryOrder(t *testing.T) {
dir := t.TempDir()
w, err := NewWriter(dir, JSON, false)
require.NoError(t, err)
require.NoError(t, w.Write(category.History, []record.Record{&record.History{URL: "https://a.example"}}))
require.NoError(t, w.Write(category.Password, []record.Record{
&record.Login{URL: "https://b.example"}, &record.Login{URL: "https://c.example"},
}))
require.NoError(t, w.Close())
assert.Equal(t, Output{Dir: dir, Files: []File{{Name: "password.json", Count: 2}, {Name: "history.json", Count: 1}}}, w.Output())
}
// --- --zip ---
@@ -369,6 +384,29 @@ func TestClose_ZipFailureKeepsTheFiles(t *testing.T) {
assert.Equal(t, []string{"cookie.csv", "history.csv", "password.csv", "results.zip"}, dirNames(t, dir))
}
func TestClose_ZipOutputNamesTheArchive(t *testing.T) {
dir := filepath.Join(t.TempDir(), "results")
w, err := NewWriter(dir, CSV, true)
require.NoError(t, err)
require.NoError(t, w.Write(category.Password, []record.Record{&record.Login{URL: "https://a.example"}}))
require.NoError(t, w.Close())
assert.Equal(t, Output{Dir: dir, Files: []File{{Name: "password.csv", Count: 1}}, Zip: "results.zip"}, w.Output())
}
// The zip holds the same records as the category files, so it gets their owner-only mode.
func TestClose_ZipIsOwnerOnly(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Windows has no mode bits to check")
}
dir := filepath.Join(t.TempDir(), "results")
require.NoError(t, zipAll(dir, chromeExtractions()...))
info, err := os.Stat(filepath.Join(dir, "results.zip"))
require.NoError(t, err)
assert.Equal(t, os.FileMode(0o600), info.Mode().Perm())
}
func TestClose_ZipWithNothingWrittenFails(t *testing.T) {
dir := filepath.Join(t.TempDir(), "results")
require.Error(t, zipAll(dir))
-12
View File
@@ -14,14 +14,6 @@ const (
// WarnLevel is used for undesired but relatively expected events,
// which may indicate a problem.
WarnLevel
// ErrorLevel is used for undesired and unexpected events that
// the program can recover from.
ErrorLevel
// FatalLevel is used for undesired and unexpected events that
// the program cannot recover from.
FatalLevel
)
func (l Level) String() string {
@@ -32,10 +24,6 @@ func (l Level) String() string {
return "INF"
case WarnLevel:
return "WRN"
case ErrorLevel:
return "ERR"
case FatalLevel:
return "FTL"
default:
return "???"
}
+1 -39
View File
@@ -5,57 +5,19 @@ import "fmt"
// defaultLogger is the default logger used by the package-level functions.
var defaultLogger = NewLogger(nil)
// SetLevel sets the minimum level of the package-level logger; messages below v
// are suppressed. Consumers embedding HackBrowserData as a library use it to
// quiet output, e.g. SetLevel(FatalLevel) to silence everything short of a fatal
// error. It panics if v is less than DebugLevel or greater than FatalLevel.
func SetLevel(v Level) {
defaultLogger.SetLevel(v)
}
// SetVerbose lowers the package-level logger to DebugLevel.
func SetVerbose() {
SetLevel(DebugLevel)
}
func Debug(args ...any) {
defaultLogger.logMsg(DebugLevel, fmt.Sprint(args...))
defaultLogger.SetLevel(DebugLevel)
}
func Debugf(format string, args ...any) {
defaultLogger.logMsg(DebugLevel, fmt.Sprintf(format, args...))
}
func Info(args ...any) {
defaultLogger.logMsg(InfoLevel, fmt.Sprint(args...))
}
func Infof(format string, args ...any) {
defaultLogger.logMsg(InfoLevel, fmt.Sprintf(format, args...))
}
func Warn(args ...any) {
defaultLogger.logMsg(WarnLevel, fmt.Sprint(args...))
}
func Warnf(format string, args ...any) {
defaultLogger.logMsg(WarnLevel, fmt.Sprintf(format, args...))
}
func Error(args ...any) {
defaultLogger.logMsg(ErrorLevel, fmt.Sprint(args...))
}
func Errorf(format string, args ...any) {
defaultLogger.logMsg(ErrorLevel, fmt.Sprintf(format, args...))
}
func Fatal(args ...any) {
defaultLogger.logMsg(FatalLevel, fmt.Sprint(args...))
osExit(1)
}
func Fatalf(format string, args ...any) {
defaultLogger.logMsg(FatalLevel, fmt.Sprintf(format, args...))
osExit(1)
}
+7 -10
View File
@@ -1,25 +1,22 @@
package log
import (
"io"
"testing"
"github.com/stretchr/testify/assert"
)
func TestSetLevel(t *testing.T) {
t.Cleanup(func() { SetLevel(InfoLevel) }) // restore package default
SetLevel(FatalLevel)
assert.False(t, defaultLogger.canLogAt(InfoLevel), "Info must be suppressed at FatalLevel")
assert.False(t, defaultLogger.canLogAt(WarnLevel), "Warn must be suppressed at FatalLevel")
assert.False(t, defaultLogger.canLogAt(ErrorLevel), "Error must be suppressed at FatalLevel")
assert.True(t, defaultLogger.canLogAt(FatalLevel), "Fatal must still log at FatalLevel")
func TestSetVerbose(t *testing.T) {
t.Cleanup(func() { defaultLogger.SetLevel(InfoLevel) }) // restore package default
assert.False(t, defaultLogger.canLogAt(DebugLevel), "Debug must be suppressed by default")
SetVerbose()
assert.True(t, defaultLogger.canLogAt(DebugLevel), "SetVerbose must enable Debug")
}
func TestSetLevelInvalidPanics(t *testing.T) {
t.Cleanup(func() { SetLevel(InfoLevel) })
assert.Panics(t, func() { SetLevel(FatalLevel + 1) })
logger := NewLogger(newBase(io.Discard))
assert.Panics(t, func() { logger.SetLevel(DebugLevel - 1) })
assert.Panics(t, func() { logger.SetLevel(WarnLevel + 1) })
}
+2 -36
View File
@@ -35,9 +35,9 @@ func (l *Logger) canLogAt(v Level) bool {
}
// SetLevel sets the logger level.
// It panics if v is less than DebugLevel or greater than FatalLevel.
// It panics if v is less than DebugLevel or greater than WarnLevel.
func (l *Logger) SetLevel(v Level) {
if v < DebugLevel || v > FatalLevel {
if v < DebugLevel || v > WarnLevel {
panic("log: invalid log level")
}
atomic.StoreInt32((*int32)(&l.minLevel), int32(v))
@@ -57,48 +57,18 @@ func (l *Logger) logMsg(lvl Level, msg string) {
l.base.Log(baseCallerSkip, lvl, msg)
}
func (l *Logger) Debug(args ...any) {
l.logMsg(DebugLevel, fmt.Sprint(args...))
}
func (l *Logger) Debugf(format string, args ...any) {
l.logMsg(DebugLevel, fmt.Sprintf(format, args...))
}
func (l *Logger) Info(args ...any) {
l.logMsg(InfoLevel, fmt.Sprint(args...))
}
func (l *Logger) Infof(format string, args ...any) {
l.logMsg(InfoLevel, fmt.Sprintf(format, args...))
}
func (l *Logger) Warn(args ...any) {
l.logMsg(WarnLevel, fmt.Sprint(args...))
}
func (l *Logger) Warnf(format string, args ...any) {
l.logMsg(WarnLevel, fmt.Sprintf(format, args...))
}
func (l *Logger) Error(args ...any) {
l.logMsg(ErrorLevel, fmt.Sprint(args...))
}
func (l *Logger) Errorf(format string, args ...any) {
l.logMsg(ErrorLevel, fmt.Sprintf(format, args...))
}
func (l *Logger) Fatal(args ...any) {
l.logMsg(FatalLevel, fmt.Sprint(args...))
osExit(1)
}
func (l *Logger) Fatalf(format string, args ...any) {
l.logMsg(FatalLevel, fmt.Sprintf(format, args...))
osExit(1)
}
// Base is the interface that underlies the Logger. It receives the caller
// skip count, log level, and formatted message.
type Base interface {
@@ -111,8 +81,6 @@ type Base interface {
// [DBG] file.go:42: message
// [INF] message
// [WRN] message
// [ERR] message
// [FTL] message
type baseLogger struct {
out io.Writer
mu sync.Mutex
@@ -122,8 +90,6 @@ func newBase(out io.Writer) *baseLogger {
return &baseLogger{out: out}
}
var osExit = os.Exit
// continuation is the indent for multi-line messages.
// Width matches "[DBG] " (6 chars).
const continuation = " "
+12 -109
View File
@@ -39,7 +39,7 @@ func TestLoggerDebug(t *testing.T) {
var buf bytes.Buffer
logger := NewLogger(newBase(&buf))
logger.SetLevel(DebugLevel)
logger.Debug(message)
logger.Debugf("%s", message)
got := buf.String()
assert.Regexp(t, tc.wantedPattern, got)
})
@@ -55,7 +55,7 @@ func TestLoggerInfo(t *testing.T) {
t.Run(tc.description, func(t *testing.T) {
var buf bytes.Buffer
logger := NewLogger(newBase(&buf))
logger.Info(message)
logger.Infof("%s", message)
got := buf.String()
assert.Regexp(t, tc.wantedPattern, got)
})
@@ -71,56 +71,13 @@ func TestLoggerWarn(t *testing.T) {
t.Run(tc.description, func(t *testing.T) {
var buf bytes.Buffer
logger := NewLogger(newBase(&buf))
logger.Warn(message)
logger.Warnf("%s", message)
got := buf.String()
assert.Regexp(t, tc.wantedPattern, got)
})
}
}
func TestLoggerError(t *testing.T) {
for _, tc := range baseTestCases {
tc := tc
tc.level = ErrorLevel
message := tc.message + tc.suffix
tc.wantedPattern = fmt.Sprintf(`^\[ERR\] %s\n$`, tc.message)
t.Run(tc.description, func(t *testing.T) {
var buf bytes.Buffer
logger := NewLogger(newBase(&buf))
logger.Error(message)
got := buf.String()
assert.Regexp(t, tc.wantedPattern, got)
})
}
}
func TestLoggerFatal(t *testing.T) {
originalOsExit := osExit
defer func() { osExit = originalOsExit }()
for _, tc := range baseTestCases {
tc := tc
tc.level = FatalLevel
message := tc.message + tc.suffix
tc.wantedPattern = fmt.Sprintf(`^\[FTL\] %s\n$`, tc.message)
t.Run(tc.description, func(t *testing.T) {
var buf bytes.Buffer
exitCalled := false
exitCode := 0
osExit = func(code int) {
exitCalled = true
exitCode = code
}
logger := NewLogger(newBase(&buf))
logger.Fatal(message)
got := buf.String()
assert.Regexp(t, tc.wantedPattern, got)
assert.True(t, exitCalled)
assert.Equal(t, 1, exitCode)
})
}
}
type formatTestCase struct {
description string
format string
@@ -196,63 +153,16 @@ func TestLoggerWarnf(t *testing.T) {
}
}
func TestLoggerErrorf(t *testing.T) {
for _, tc := range formatTestCases {
tc := tc
tc.level = ErrorLevel
message := fmt.Sprintf(tc.format, tc.args...)
tc.wantedPattern = fmt.Sprintf(`^\[ERR\] %s\n$`, message)
t.Run(tc.description, func(t *testing.T) {
var buf bytes.Buffer
logger := NewLogger(newBase(&buf))
logger.Errorf(tc.format, tc.args...)
got := buf.String()
assert.Regexp(t, tc.wantedPattern, got)
})
}
}
func TestLoggerFatalf(t *testing.T) {
originalOsExit := osExit
defer func() { osExit = originalOsExit }()
for _, tc := range formatTestCases {
tc := tc
tc.level = FatalLevel
message := fmt.Sprintf(tc.format, tc.args...)
tc.wantedPattern = fmt.Sprintf(`^\[FTL\] %s\n$`, message)
t.Run(tc.description, func(t *testing.T) {
var buf bytes.Buffer
exitCalled := false
exitCode := 0
osExit = func(code int) {
exitCalled = true
exitCode = code
}
logger := NewLogger(newBase(&buf))
logger.Fatalf(tc.format, tc.args...)
got := buf.String()
assert.Regexp(t, tc.wantedPattern, got)
assert.True(t, exitCalled)
assert.Equal(t, 1, exitCode)
})
}
}
func TestLoggerWithLowerLevels(t *testing.T) {
originalOsExit := osExit
defer func() { osExit = originalOsExit }()
levels := []Level{DebugLevel, InfoLevel, WarnLevel, ErrorLevel, FatalLevel}
levels := []Level{DebugLevel, InfoLevel, WarnLevel}
ops := []struct {
op string
level Level
logFunc func(*Logger)
}{
{"Debug", DebugLevel, func(l *Logger) { l.Debug("hello") }},
{"Info", InfoLevel, func(l *Logger) { l.Info("hello") }},
{"Warn", WarnLevel, func(l *Logger) { l.Warn("hello") }},
{"Error", ErrorLevel, func(l *Logger) { l.Error("hello") }},
{"Fatal", FatalLevel, func(l *Logger) { l.Fatal("hello") }},
{"Debugf", DebugLevel, func(l *Logger) { l.Debugf("hello") }},
{"Infof", InfoLevel, func(l *Logger) { l.Infof("hello") }},
{"Warnf", WarnLevel, func(l *Logger) { l.Warnf("hello") }},
}
for _, setLevel := range levels {
@@ -262,10 +172,6 @@ func TestLoggerWithLowerLevels(t *testing.T) {
logger.SetLevel(setLevel)
expectedOutput := op.level >= setLevel
exitCalled := false
osExit = func(code int) {
exitCalled = true
}
op.logFunc(logger)
output := buf.String()
@@ -274,9 +180,6 @@ func TestLoggerWithLowerLevels(t *testing.T) {
} else {
assert.Empty(t, output, "setLevel=%s op=%s should be suppressed", setLevel, op.op)
}
if op.op == "Fatal" && expectedOutput {
assert.True(t, exitCalled, "Fatal should call osExit")
}
}
}
}
@@ -286,11 +189,11 @@ func TestDefaultLevelIsInfo(t *testing.T) {
logger := NewLogger(newBase(&buf))
// Debug should be suppressed at default level (InfoLevel).
logger.Debug("debug msg")
logger.Debugf("debug msg")
assert.Empty(t, buf.String(), "Debug should be suppressed at default InfoLevel")
// Info should be visible at default level.
logger.Info("info msg")
logger.Infof("info msg")
assert.Contains(t, buf.String(), "info msg")
}
@@ -298,7 +201,7 @@ func TestDebugIncludesFileLine(t *testing.T) {
var buf bytes.Buffer
logger := NewLogger(newBase(&buf))
logger.SetLevel(DebugLevel)
logger.Debug("test location")
logger.Debugf("test location")
got := buf.String()
assert.Regexp(t, `^\[DBG\] logger_test\.go:\d+: test location\n$`, got)
}
@@ -306,14 +209,14 @@ func TestDebugIncludesFileLine(t *testing.T) {
func TestInfoHasLabel(t *testing.T) {
var buf bytes.Buffer
logger := NewLogger(newBase(&buf))
logger.Info("clean message")
logger.Infof("clean message")
assert.Equal(t, "[INF] clean message\n", buf.String())
}
func TestMultilineMessageIndented(t *testing.T) {
var buf bytes.Buffer
logger := NewLogger(newBase(&buf))
logger.Warn("line1\nline2\nline3")
logger.Warnf("line1\nline2\nline3")
got := buf.String()
assert.Equal(t, "[WRN] line1\n line2\n line3\n", got)
}