refactor(app): typed per-command options, render in cmd (#693)

Validate now returns only what each command reads, with -b resolved to browsers or vaults, so no
stage compares against "all"; printing moves to cmd, which already printed the list tables.
This commit is contained in:
Roger authored and GitHub committed 2026-11-10 17:00:44 +08:00
1 parent a7741eaab2
commit b5eddf799b
21 files changed
+281 -266

No files matched your search

+2 -44
View File
@@ -1,15 +1,9 @@
package main
import (
"fmt"
"io"
"path/filepath"
"text/tabwriter"
"github.com/spf13/cobra"
"github.com/moond4rk/hackbrowserdata/internal/app"
"github.com/moond4rk/hackbrowserdata/internal/category"
"github.com/moond4rk/hackbrowserdata/internal/log"
)
@@ -22,7 +16,7 @@ func newListCommand() *cobra.Command {
Example: ` hack-browser-data list
hack-browser-data list --detail`,
RunE: func(command *cobra.Command, args []string) error {
options, err := app.ListOptions()
options, err := app.ValidateList()
if err != nil {
return err
}
@@ -37,7 +31,7 @@ func newListCommand() *cobra.Command {
if !detail {
return printProfiles(command.OutOrStdout(), discovery)
}
summary, err := app.CountRecords(command.Context(), discovery, options.Categories, options.Keychain)
summary, err := app.CountRecords(command.Context(), discovery, options.Keychain)
if err != nil {
return err
}
@@ -48,39 +42,3 @@ func newListCommand() *cobra.Command {
command.Flags().BoolVar(&detail, "detail", false, "show per-category entry counts")
return command
}
func printProfiles(out io.Writer, discovery app.Discovery) error {
table := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0)
fmt.Fprintln(table, "Browser\tProfile\tPath")
for _, dir := range discovery.Dirs {
for _, profile := range dir.Profiles {
profilePath := filepath.Join(dir.Path, filepath.FromSlash(profile.RelativePath))
fmt.Fprintf(table, "%s\t%s\t%s\n", dir.Browser.DisplayName, profile.Name, profilePath)
}
}
return table.Flush()
}
func printRecordCounts(out io.Writer, discovery app.Discovery, summary app.Summary) error {
counts := make(map[app.Extraction]int, len(summary.Results))
for _, result := range summary.Results {
counts[result.Extraction] = result.Records
}
table := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0)
fmt.Fprint(table, "Browser\tProfile")
for _, dataCategory := range category.All() {
fmt.Fprintf(table, "\t%s", dataCategory.String())
}
fmt.Fprintln(table)
for _, dir := range discovery.Dirs {
for _, profile := range dir.Profiles {
fmt.Fprintf(table, "%s\t%s", dir.Browser.DisplayName, profile.Name)
for _, dataCategory := range category.All() {
fmt.Fprintf(table, "\t%d", counts[app.Extraction{UserDataDirID: dir.ID, ProfileName: profile.Name, Category: dataCategory}])
}
fmt.Fprintln(table)
}
}
return table.Flush()
}
-38
View File
@@ -3,8 +3,6 @@ package main
import (
"context"
"errors"
"fmt"
"io"
"os"
"os/signal"
"syscall"
@@ -12,8 +10,6 @@ import (
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/moond4rk/hackbrowserdata/internal/app"
"github.com/moond4rk/hackbrowserdata/internal/export"
"github.com/moond4rk/hackbrowserdata/internal/log"
)
@@ -73,40 +69,6 @@ func silenceWhenStopped(command *cobra.Command) {
}
}
// report prints the run's summary; it is not part of the output, so failing to print it never fails the run.
func report(writer io.Writer, summary app.Summary) {
if err := app.Report(writer, summary); err != nil {
log.Warnf("print summary: %v", err)
}
}
// warnIfNothingFound reports discovery's failures, the likely reason it found no browser data, then says so.
func warnIfNothingFound(stderr io.Writer, discovery app.Discovery, message string) bool {
if len(discovery.Dirs) > 0 {
return false
}
if len(discovery.DirFailures) > 0 {
report(stderr, app.Summary{DirFailures: discovery.DirFailures})
}
log.Warnf("%s", message)
return true
}
// announceExport lists the files a run wrote, even when it stopped early, so the user finds what it left.
func announceExport(stderr io.Writer, exported export.Listing) {
if len(exported.Files) == 0 {
return
}
fmt.Fprintln(stderr)
log.Infof("Exported to %s/", exported.Dir)
for _, file := range exported.Files {
log.Infof(" %-24s %d entries", file.Name, file.Count)
}
if exported.ZipName != "" {
log.Infof("Compressed: %s/%s", exported.Dir, exported.ZipName)
}
}
// stopSignals end the process by default; each first cancels the run, so its temporary copies are removed.
var stopSignals = []os.Signal{os.Interrupt, syscall.SIGTERM, syscall.SIGHUP}
+103
View File
@@ -0,0 +1,103 @@
package main
import (
"fmt"
"io"
"path/filepath"
"text/tabwriter"
"github.com/moond4rk/hackbrowserdata/internal/app"
"github.com/moond4rk/hackbrowserdata/internal/category"
"github.com/moond4rk/hackbrowserdata/internal/export"
"github.com/moond4rk/hackbrowserdata/internal/log"
)
// report prints the run's summary; it is not part of the output, so failing to print it never fails the run.
func report(stderr io.Writer, summary app.Summary) {
table := tabwriter.NewWriter(stderr, 0, 0, 2, ' ', 0)
fmt.Fprintln(table, "Browser\tProfile\tCategory\tResult\tRecords\tDetail")
for _, failure := range summary.DirFailures {
fmt.Fprintf(table, "%s\t-\t-\t%s\t0\t%s\n", failure.UserDataDirID, app.OutcomeError, failure.Err)
}
for _, result := range summary.Results {
fmt.Fprintf(table, "%s\t%s\t%s\t%s\t%d\t%s\n",
result.UserDataDirID, result.ProfileName, result.Category, result.Outcome, result.Records, resultDetail(result))
}
if err := table.Flush(); err != nil {
log.Warnf("print summary: %v", err)
}
}
func resultDetail(result app.Result) string {
switch {
case result.Err != nil:
return result.Err.Error()
case result.Failures > 0:
return fmt.Sprintf("%d not recovered", result.Failures)
default:
return ""
}
}
// warnIfNothingFound reports discovery's failures, the likely reason it found no browser data, then says so.
func warnIfNothingFound(stderr io.Writer, discovery app.Discovery, message string) bool {
if len(discovery.Dirs) > 0 {
return false
}
if len(discovery.DirFailures) > 0 {
report(stderr, app.Summary{DirFailures: discovery.DirFailures})
}
log.Warnf("%s", message)
return true
}
// announceExport lists the files a run wrote, even when it stopped early, so the user finds what it left.
func announceExport(stderr io.Writer, exported export.Listing) {
if len(exported.Files) == 0 {
return
}
fmt.Fprintln(stderr)
log.Infof("Exported to %s/", exported.Dir)
for _, file := range exported.Files {
log.Infof(" %-24s %d entries", file.Name, file.Count)
}
if exported.ZipName != "" {
log.Infof("Compressed: %s/%s", exported.Dir, exported.ZipName)
}
}
func printProfiles(out io.Writer, discovery app.Discovery) error {
table := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0)
fmt.Fprintln(table, "Browser\tProfile\tPath")
for _, dir := range discovery.Dirs {
for _, profile := range dir.Profiles {
profilePath := filepath.Join(dir.Path, filepath.FromSlash(profile.RelativePath))
fmt.Fprintf(table, "%s\t%s\t%s\n", dir.Browser.DisplayName, profile.Name, profilePath)
}
}
return table.Flush()
}
func printRecordCounts(out io.Writer, discovery app.Discovery, summary app.Summary) error {
counts := make(map[app.Extraction]int, len(summary.Results))
for _, result := range summary.Results {
counts[result.Extraction] = result.Records
}
table := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0)
fmt.Fprint(table, "Browser\tProfile")
for _, dataCategory := range category.All() {
fmt.Fprintf(table, "\t%s", dataCategory.String())
}
fmt.Fprintln(table)
for _, dir := range discovery.Dirs {
for _, profile := range dir.Profiles {
fmt.Fprintf(table, "%s\t%s", dir.Browser.DisplayName, profile.Name)
for _, dataCategory := range category.All() {
fmt.Fprintf(table, "\t%d", counts[app.Extraction{UserDataDirID: dir.ID, ProfileName: profile.Name, Category: dataCategory}])
}
fmt.Fprintln(table)
}
}
return table.Flush()
}
+38
View File
@@ -0,0 +1,38 @@
package main
import (
"bytes"
"errors"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/moond4rk/hackbrowserdata/internal/app"
"github.com/moond4rk/hackbrowserdata/internal/category"
)
func TestReport(t *testing.T) {
cookie := app.Extraction{UserDataDirID: "chrome", ProfileName: "Default", Category: category.Cookie}
var buffer bytes.Buffer
report(&buffer, app.Summary{
Results: []app.Result{
{Extraction: cookie, Outcome: app.OutcomePartial, Records: 224, Failures: 4},
{
Extraction: app.Extraction{UserDataDirID: "chrome", ProfileName: "Default", Category: category.Password},
Outcome: app.OutcomeError, Failures: 2, Err: errors.New("password not decrypted"),
},
{Extraction: app.Extraction{UserDataDirID: "edge", ProfileName: "Default", Category: category.Password}},
},
DirFailures: []app.DirFailure{{UserDataDirID: "arc-2", Err: errors.New("permission denied")}},
})
lines := strings.Split(strings.TrimSpace(buffer.String()), "\n")
require.Len(t, lines, 5)
assert.Equal(t, []string{"arc-2", "-", "-", "error", "0", "permission", "denied"}, strings.Fields(lines[1]), "a dir failure leads")
assert.Equal(t, []string{"chrome", "Default", "cookie", "partial", "224", "4", "not", "recovered"}, strings.Fields(lines[2]))
assert.Equal(t, []string{"chrome", "Default", "password", "error", "0", "password", "not", "decrypted"}, strings.Fields(lines[3]),
"an error's message wins over the failure count")
assert.Equal(t, "unset", strings.Fields(lines[4])[3], "a result whose outcome was never set must not read as ok")
}
+3 -2
View File
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"io"
"os"
"github.com/spf13/cobra"
@@ -43,7 +44,7 @@ func newRestoreCommand() *cobra.Command {
}
func runRestore(ctx context.Context, stderr io.Writer, flags app.RestoreFlags) error {
options, keyFile, err := app.ValidateRestore(flags)
options, err := app.ValidateRestore(flags, os.Stdin)
if err != nil {
return err
}
@@ -53,7 +54,7 @@ func runRestore(ctx context.Context, stderr io.Writer, flags app.RestoreFlags) e
}
defer closeRestoreData(root)
discovery, keys, err := app.DiscoverRestore(root.Path(), keyFile, options.Target.BrowserName)
discovery, keys, err := app.DiscoverRestore(root.Path(), options.Vaults)
if err != nil {
return err
}