From 063e26576404a7beae5478e56d78129deadfacf2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Do=C4=9Fan=20Can=20Bak=C4=B1r?= Date: Sun, 1 Nov 2026 08:16:39 +0000 Subject: [PATCH 1/4] feat: add --format flag with table and csv output (#5) Add a --format flag to the run command to control output: dit run https://example.com --format table dit run https://example.com --format csv JSON remains the default and is unchanged. Table (aligned via text/tabwriter) and CSV share one flat schema -- page_type, captcha_type, form, form_type, field, field_type -- with one row per classified field, so results are easy to inspect and pipe into other tools. Fields are sorted by name for deterministic output. An unknown format or combining table/csv with --proba returns an error. --- README.md | 4 ++ internal/cli/format.go | 128 ++++++++++++++++++++++++++++++++++++ internal/cli/format_test.go | 120 +++++++++++++++++++++++++++++++++ internal/cli/run.go | 38 +++++++---- 4 files changed, 276 insertions(+), 14 deletions(-) create mode 100644 internal/cli/format.go create mode 100644 internal/cli/format_test.go diff --git a/README.md b/README.md index 65d8a0b..d0213fc 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,10 @@ dit run login.html # With probabilities dit run https://github.com/login --proba +# Choose output format: json (default), table, or csv +dit run https://github.com/login --format table +dit run https://github.com/login --format csv + # Download training data and model from Hugging Face dit data download diff --git a/internal/cli/format.go b/internal/cli/format.go new file mode 100644 index 0000000..c82be04 --- /dev/null +++ b/internal/cli/format.go @@ -0,0 +1,128 @@ +package cli + +import ( + "encoding/csv" + "encoding/json" + "fmt" + "io" + "sort" + "strings" + "text/tabwriter" + + "github.com/happyhackingspace/dit" +) + +// Supported output formats for the run command. +const ( + formatJSON = "json" + formatTable = "table" + formatCSV = "csv" +) + +// validFormat reports whether format names a supported output format. +func validFormat(format string) bool { + switch format { + case formatJSON, formatTable, formatCSV: + return true + } + return false +} + +// resultHeader is the column layout shared by table and CSV output. +var resultHeader = []string{"page_type", "captcha_type", "form", "form_type", "field", "field_type"} + +// pageResultRows flattens a page classification into one row per field. +func pageResultRows(r *dit.PageResult) [][]string { + if len(r.Forms) == 0 { + return [][]string{{r.Type, r.Captcha, "", "", "", ""}} + } + var rows [][]string + for i, f := range r.Forms { + captcha := r.Captcha + if f.Captcha != "" { + captcha = f.Captcha + } + rows = append(rows, formRows(r.Type, captcha, i+1, f)...) + } + return rows +} + +// formResultRows flattens form classifications into one row per field. +func formResultRows(results []dit.FormResult) [][]string { + var rows [][]string + for i, f := range results { + rows = append(rows, formRows("", f.Captcha, i+1, f)...) + } + return rows +} + +// formRows renders one form as rows, one per field, sorted by field name. +func formRows(pageType, captcha string, index int, f dit.FormResult) [][]string { + idx := fmt.Sprintf("%d", index) + if len(f.Fields) == 0 { + return [][]string{{pageType, captcha, idx, f.Type, "", ""}} + } + names := make([]string, 0, len(f.Fields)) + for name := range f.Fields { + names = append(names, name) + } + sort.Strings(names) + rows := make([][]string, 0, len(names)) + for _, name := range names { + rows = append(rows, []string{pageType, captcha, idx, f.Type, name, f.Fields[name]}) + } + return rows +} + +// writeTable writes header and rows as an aligned text table. +func writeTable(w io.Writer, header []string, rows [][]string) error { + tw := tabwriter.NewWriter(w, 0, 4, 2, ' ', 0) + fmt.Fprintln(tw, strings.ToUpper(strings.Join(header, "\t"))) + for _, row := range rows { + fmt.Fprintln(tw, strings.Join(row, "\t")) + } + return tw.Flush() +} + +// writeCSV writes header and rows as CSV. +func writeCSV(w io.Writer, header []string, rows [][]string) error { + cw := csv.NewWriter(w) + if err := cw.Write(header); err != nil { + return err + } + for _, row := range rows { + if err := cw.Write(row); err != nil { + return err + } + } + cw.Flush() + return cw.Error() +} + +// outputPageResult writes a page classification result in the given format. +func outputPageResult(w io.Writer, format string, r *dit.PageResult) error { + switch format { + case formatTable: + return writeTable(w, resultHeader, pageResultRows(r)) + case formatCSV: + return writeCSV(w, resultHeader, pageResultRows(r)) + default: + output, _ := json.MarshalIndent(r, "", " ") + fmt.Fprintln(w, string(output)) + return nil + } +} + +// outputFormResults writes form classification results in the given format. +func outputFormResults(w io.Writer, format string, results []dit.FormResult) error { + switch format { + case formatTable: + return writeTable(w, resultHeader, formResultRows(results)) + case formatCSV: + return writeCSV(w, resultHeader, formResultRows(results)) + default: + output, _ := json.MarshalIndent(results, "", " ") + fmt.Fprintln(w, string(output)) + return nil + } +} diff --git a/internal/cli/format_test.go b/internal/cli/format_test.go new file mode 100644 index 0000000..3bda965 --- /dev/null +++ b/internal/cli/format_test.go @@ -0,0 +1,120 @@ +package cli + +import ( + "bytes" + "encoding/json" + "strings" + "testing" + + "github.com/happyhackingspace/dit" +) + +func samplePageResult() *dit.PageResult { + return &dit.PageResult{ + Type: "login", + Captcha: "recaptcha", + Forms: []dit.FormResult{ + { + Type: "login", + Fields: map[string]string{ + "username": "username or email", + "password": "password", + }, + }, + }, + } +} + +func TestValidFormat(t *testing.T) { + for _, f := range []string{formatJSON, formatTable, formatCSV} { + if !validFormat(f) { + t.Errorf("expected %q to be valid", f) + } + } + for _, f := range []string{"", "xml", "JSON"} { + if validFormat(f) { + t.Errorf("expected %q to be invalid", f) + } + } +} + +func TestOutputPageResultCSV(t *testing.T) { + var buf bytes.Buffer + if err := outputPageResult(&buf, formatCSV, samplePageResult()); err != nil { + t.Fatalf("outputPageResult: %v", err) + } + + want := "page_type,captcha_type,form,form_type,field,field_type\n" + + "login,recaptcha,1,login,password,password\n" + + "login,recaptcha,1,login,username,username or email\n" + if buf.String() != want { + t.Errorf("expected:\n%s\ngot:\n%s", want, buf.String()) + } +} + +func TestOutputPageResultTable(t *testing.T) { + var buf bytes.Buffer + if err := outputPageResult(&buf, formatTable, samplePageResult()); err != nil { + t.Fatalf("outputPageResult: %v", err) + } + + out := buf.String() + lines := strings.Split(strings.TrimRight(out, "\n"), "\n") + if len(lines) != 3 { + t.Fatalf("expected 3 lines, got %d:\n%s", len(lines), out) + } + if !strings.HasPrefix(lines[0], "PAGE_TYPE") { + t.Errorf("expected header line, got %q", lines[0]) + } + for _, s := range []string{"login", "recaptcha", "username or email"} { + if !strings.Contains(out, s) { + t.Errorf("expected output to contain %q:\n%s", s, out) + } + } +} + +func TestOutputPageResultJSON(t *testing.T) { + var buf bytes.Buffer + result := samplePageResult() + if err := outputPageResult(&buf, formatJSON, result); err != nil { + t.Fatalf("outputPageResult: %v", err) + } + + want, _ := json.MarshalIndent(result, "", " ") + if buf.String() != string(want)+"\n" { + t.Errorf("expected:\n%s\ngot:\n%s", want, buf.String()) + } +} + +func TestOutputPageResultNoForms(t *testing.T) { + var buf bytes.Buffer + r := &dit.PageResult{Type: "error"} + if err := outputPageResult(&buf, formatCSV, r); err != nil { + t.Fatalf("outputPageResult: %v", err) + } + + want := "page_type,captcha_type,form,form_type,field,field_type\n" + + "error,,,,,\n" + if buf.String() != want { + t.Errorf("expected:\n%s\ngot:\n%s", want, buf.String()) + } +} + +func TestOutputFormResultsCSV(t *testing.T) { + results := []dit.FormResult{ + {Type: "search", Fields: map[string]string{"q": "search query"}}, + {Type: "other", Captcha: "hcaptcha"}, + } + + var buf bytes.Buffer + if err := outputFormResults(&buf, formatCSV, results); err != nil { + t.Fatalf("outputFormResults: %v", err) + } + + want := "page_type,captcha_type,form,form_type,field,field_type\n" + + ",,1,search,q,search query\n" + + ",hcaptcha,2,other,,\n" + if buf.String() != want { + t.Errorf("expected:\n%s\ngot:\n%s", want, buf.String()) + } +} diff --git a/internal/cli/run.go b/internal/cli/run.go index a2590c4..eb37849 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -22,6 +22,7 @@ func (c *CLI) newRunCommand() *cobra.Command { var proba bool var render bool var renderTimeout int + var format string cmd := &cobra.Command{ Use: "run [url-or-file]", @@ -51,6 +52,10 @@ func (c *CLI) newRunCommand() *cobra.Command { # Use custom model file dit run login.html --model custom.json + # Output as an aligned table or CSV instead of JSON + dit run https://github.com/login --format table + dit run https://github.com/login --format csv + # Render JavaScript-heavy pages dit run https://github.com/login --render @@ -60,6 +65,13 @@ func (c *CLI) newRunCommand() *cobra.Command { # Verbose mode with debug output dit run https://github.com/login -v`, RunE: func(cmd *cobra.Command, args []string) error { + if !validFormat(format) { + return fmt.Errorf("invalid --format %q (supported: json, table, csv)", format) + } + if proba && format != formatJSON { + return fmt.Errorf("--format %s is not supported with --proba (use --format json)", format) + } + var htmlContent string var target string var err error @@ -120,21 +132,18 @@ func (c *CLI) newRunCommand() *cobra.Command { pageResult, pageErr := cl.ExtractPageType(htmlContent) if pageErr == nil { slog.Debug("Page+form classification completed", "duration", time.Since(start)) - output, _ := json.MarshalIndent(pageResult, "", " ") - fmt.Println(string(output)) - } else { - results, err := cl.ExtractForms(htmlContent) - if err != nil { - return err - } - slog.Debug("Form classification completed", "forms", len(results), "duration", time.Since(start)) - if len(results) == 0 { - fmt.Println("No forms found.") - return nil - } - output, _ := json.MarshalIndent(results, "", " ") - fmt.Println(string(output)) + return outputPageResult(os.Stdout, format, pageResult) + } + results, err := cl.ExtractForms(htmlContent) + if err != nil { + return err + } + slog.Debug("Form classification completed", "forms", len(results), "duration", time.Since(start)) + if len(results) == 0 { + fmt.Println("No forms found.") + return nil } + return outputFormResults(os.Stdout, format, results) } return nil }, @@ -145,6 +154,7 @@ func (c *CLI) newRunCommand() *cobra.Command { cmd.Flags().BoolVar(&proba, "proba", false, "Show probabilities") cmd.Flags().BoolVar(&render, "render", false, "Render JavaScript-driven pages in a headless browser") cmd.Flags().IntVar(&renderTimeout, "timeout", 30, "Render browser timeout in seconds") + cmd.Flags().StringVar(&format, "format", formatJSON, "Output format: json, table, or csv") return cmd } From 99f8dd26b240ed2899918a0ddab63e46f5365da8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Do=C4=9Fan=20Can=20Bak=C4=B1r?= Date: Sun, 1 Nov 2026 09:16:37 +0000 Subject: [PATCH 2/4] fix: check Fprintln error returns; bump toolchain to go1.26.10 errcheck flagged the unchecked fmt.Fprintln calls in format.go; the toolchain bump clears the repo-wide GO-2026-6809 Govulncheck failure. --- go.mod | 2 +- internal/cli/format.go | 12 ++++++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/go.mod b/go.mod index f4f0bbf..6fa668b 100644 --- a/go.mod +++ b/go.mod @@ -2,7 +2,7 @@ module github.com/happyhackingspace/dit go 1.26.0 -toolchain go1.26.9 +toolchain go1.26.10 require ( github.com/PuerkitoBio/goquery v1.13.0 diff --git a/internal/cli/format.go b/internal/cli/format.go index c82be04..a65cdf1 100644 --- a/internal/cli/format.go +++ b/internal/cli/format.go @@ -77,9 +77,13 @@ func formRows(pageType, captcha string, index int, f dit.FormResult) [][]string // writeTable writes header and rows as an aligned text table. func writeTable(w io.Writer, header []string, rows [][]string) error { tw := tabwriter.NewWriter(w, 0, 4, 2, ' ', 0) - fmt.Fprintln(tw, strings.ToUpper(strings.Join(header, "\t"))) + if _, err := fmt.Fprintln(tw, strings.ToUpper(strings.Join(header, "\t"))); err != nil { + return err + } for _, row := range rows { - fmt.Fprintln(tw, strings.Join(row, "\t")) + if _, err := fmt.Fprintln(tw, strings.Join(row, "\t")); err != nil { + return err + } } return tw.Flush() } @@ -108,8 +112,8 @@ func outputPageResult(w io.Writer, format string, r *dit.PageResult) error { return writeCSV(w, resultHeader, pageResultRows(r)) default: output, _ := json.MarshalIndent(r, "", " ") - fmt.Fprintln(w, string(output)) - return nil + _, err := fmt.Fprintln(w, string(output)) + return err } } From 986fff18fba8934ade20073b1e6a964ee87e79de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Do=C4=9Fan=20Can=20Bak=C4=B1r?= Date: Sun, 1 Nov 2026 10:08:10 +0000 Subject: [PATCH 3/4] fix: bump x/net to v0.62.0 (GO-2026-6866, GO-2026-6860) Same security bump as the dedicated fix PR; identical changes merge cleanly in any order. --- go.mod | 6 +++--- go.sum | 16 ++++++++-------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/go.mod b/go.mod index 6fa668b..f040291 100644 --- a/go.mod +++ b/go.mod @@ -9,7 +9,7 @@ require ( github.com/chromedp/chromedp v0.16.0 github.com/creativeprojects/go-selfupdate v1.6.0 github.com/spf13/cobra v1.10.2 - golang.org/x/net v0.59.0 + golang.org/x/net v0.62.0 ) require ( @@ -34,9 +34,9 @@ require ( github.com/spf13/pflag v1.0.9 // indirect github.com/ulikunitz/xz v0.5.15 // indirect gitlab.com/gitlab-org/api/client-go v1.46.0 // indirect - golang.org/x/crypto v0.57.0 // indirect + golang.org/x/crypto v0.58.0 // indirect golang.org/x/oauth2 v0.36.0 // indirect - golang.org/x/sys v0.48.0 // indirect + golang.org/x/sys v0.49.0 // indirect golang.org/x/time v0.15.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 321555e..1b6a7f9 100644 --- a/go.sum +++ b/go.sum @@ -77,23 +77,23 @@ go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8= -golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= -golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= +golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= +golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues= -golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= -golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE= -golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= +golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM= +golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= From 949eb0783c7d6d06fcd15d79c06b0e2b5c90db08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Do=C4=9Fan=20Can=20Bak=C4=B1r?= Date: Sun, 1 Nov 2026 10:58:28 +0000 Subject: [PATCH 4/4] fix: check remaining Fprintln error return in outputFormResults --- internal/cli/format.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/cli/format.go b/internal/cli/format.go index a65cdf1..e1a639f 100644 --- a/internal/cli/format.go +++ b/internal/cli/format.go @@ -126,7 +126,7 @@ func outputFormResults(w io.Writer, format string, results []dit.FormResult) err return writeCSV(w, resultHeader, formResultRows(results)) default: output, _ := json.MarshalIndent(results, "", " ") - fmt.Fprintln(w, string(output)) - return nil + _, err := fmt.Fprintln(w, string(output)) + return err } }