From 5c83a8ae73cdf7e06fec1baff49683ccebc8ab52 Mon Sep 17 00:00:00 2001 From: myaaaaaaaaa <103326468+myaaaaaaaaa@users.noreply.github.com> Date: Fri, 20 Sep 2024 21:04:32 -0400 Subject: [PATCH] implement -j --- prog.go | 24 +++++++++++++----------- prog_test.go | 6 +++++- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/prog.go b/prog.go index 67d54dd..77c340c 100644 --- a/prog.go +++ b/prog.go @@ -53,16 +53,18 @@ type flags struct { script string filenames []string - tab bool - raw bool - dry bool + dry bool + tab bool + rawIn bool + jsonOut bool } func (f *flags) populate(args []string) { fset := flag.NewFlagSet("", flag.ExitOnError) - fset.BoolVar(&f.tab, "t", false, `always indent output`) - fset.BoolVar(&f.raw, "r", false, `stdin, stdout, and files are newline-separated strings`) fset.BoolVar(&f.dry, "dry-run", false, `don't persist snapshots`) + fset.BoolVar(&f.tab, "t", false, `always indent output`) + fset.BoolVar(&f.rawIn, "r", false, `inputs are newline-separated strings`) + fset.BoolVar(&f.jsonOut, "j", false, `always output json (strings are unwrapped by default)`) usage := fset.Usage fset.Usage = func() { @@ -98,22 +100,22 @@ func (p *Program) Main() (rtErr error) { failif(err, "loading") defer file.Close() - v := slices.Collect(decoder(file, filename, f.raw)) - if len(v) == 1 && !f.raw { + v := slices.Collect(decoder(file, filename, f.rawIn)) + if len(v) == 1 && !f.rawIn { files[filename] = v[0] } else { files[filename] = v } } - input := decoder(p.Stdin, "stdin", f.raw) + input := decoder(p.Stdin, "stdin", f.rawIn) if p.StdinIsTerminal { input = func(yield func(any) bool) { yield(files) } } marshal := getMarshaler( - f.tab || (p.StdoutIsTerminal && !f.raw), - f.raw || p.StdoutIsTerminal, + f.tab || (p.StdoutIsTerminal && !f.jsonOut), + !f.jsonOut, ) var state State @@ -131,7 +133,7 @@ func (p *Program) Main() (rtErr error) { } state.Files = nil } - p.FS = toFS(state.Files, getMarshaler(f.tab, true)) // f.raw)) + p.FS = toFS(state.Files, getMarshaler(f.tab, !f.jsonOut)) return nil } diff --git a/prog_test.go b/prog_test.go index eb6e59b..73fc17f 100644 --- a/prog_test.go +++ b/prog_test.go @@ -34,11 +34,15 @@ func TestProgram(t *testing.T) { testRun(t, "[] []", "{}", &Program{StdinIsTerminal: true}) testRun(t, "[10]", "[10]", &Program{}) + testRun(t, "[10]", "[10]", &Program{Args: []string{"-j"}}) + testRun(t, "[10]", "[10]", &Program{Args: []string{"-j"}, StdoutIsTerminal: true}) testRun(t, "[10]", "[\n\t10\n]", &Program{StdoutIsTerminal: true}) testRun(t, "[10]", "[\n\t10\n]", &Program{Args: []string{"-t"}}) + testRun(t, "[10]", "[\n\t10\n]", &Program{Args: []string{"-t", "-j"}}) - testRun(t, `"a"`, `"a"`, &Program{}) + testRun(t, `"a"`, `a`, &Program{}) testRun(t, `"a"`, `a`, &Program{StdoutIsTerminal: true}) + testRun(t, `"a"`, `"a"`, &Program{Args: []string{"-j"}}) testRun(t, "[10]", "[10]", &Program{}) testRun(t, "[10]", "[10]", &Program{Args: []string{"."}})