From 8dda8ec9b2bca897db22b0f0d57808d8e5cf6840 Mon Sep 17 00:00:00 2001 From: Martin Kobetic Date: Tue, 14 Nov 2023 17:23:38 -0500 Subject: [PATCH] format -t: trim excessive whitespace --- cmd/coin/format.go | 8 +++++++- cmd/coin/utils.go | 25 +++++++++++++++++++++++++ cmd/coin/utils_test.go | 18 ++++++++++++++++++ 3 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 cmd/coin/utils_test.go diff --git a/cmd/coin/format.go b/cmd/coin/format.go index aece811..f85578e 100644 --- a/cmd/coin/format.go +++ b/cmd/coin/format.go @@ -19,13 +19,15 @@ type cmdFormat struct { *flag.FlagSet ledger bool replace bool + trimWS bool } func (*cmdFormat) newCommand(names ...string) command { var cmd cmdFormat cmd.FlagSet = newCommand(&cmd, names...) cmd.BoolVar(&cmd.ledger, "ledger", false, "use ledger compatible format") - cmd.BoolVar(&cmd.replace, "replace", false, "format files in place") + cmd.BoolVar(&cmd.replace, "i", false, "format files in-place") + cmd.BoolVar(&cmd.trimWS, "t", false, "trim excessive whitespace") return &cmd } @@ -47,6 +49,10 @@ func (cmd *cmdFormat) execute(f io.Writer) { f = tf } for _, t := range coin.Transactions { + if cmd.trimWS { + t.Description = trimWS(t.Description) + t.Note = trimWS(t.Note) + } t.Write(f, cmd.ledger) fmt.Fprintln(f) } diff --git a/cmd/coin/utils.go b/cmd/coin/utils.go index e7d7453..f64033a 100644 --- a/cmd/coin/utils.go +++ b/cmd/coin/utils.go @@ -1,6 +1,8 @@ package main import ( + "bufio" + "bytes" "compress/gzip" "encoding/base64" "io" @@ -43,3 +45,26 @@ func trim(ps []*coin.Posting, begin, end coin.Date) []*coin.Posting { } return ps } + +func trimWS(in string) string { + lines := bufio.NewScanner(strings.NewReader(in)) + var w strings.Builder + lIsFirst := true + for lines.Scan() { + if !lIsFirst { + w.WriteByte('\n') + } + lIsFirst = false + words := bufio.NewScanner(bytes.NewReader(lines.Bytes())) + words.Split(bufio.ScanWords) + wIsFirst := true + for words.Scan() { + if !wIsFirst { + w.WriteByte(' ') + } + w.Write(words.Bytes()) + wIsFirst = false + } + } + return w.String() +} diff --git a/cmd/coin/utils_test.go b/cmd/coin/utils_test.go new file mode 100644 index 0000000..9679d2f --- /dev/null +++ b/cmd/coin/utils_test.go @@ -0,0 +1,18 @@ +package main + +import ( + "testing" + + "github.com/mkobetic/coin/assert" +) + +func Test_TrimWS(t *testing.T) { + for _, tc := range []struct { + in, out string + }{ + {" a bb \n ddd \n ", "a bb\nddd\n"}, + {"xx[ 7 ]\n !yyy", "xx[ 7 ]\n!yyy"}, + } { + assert.Equal(t, trimWS(tc.in), tc.out) + } +}