Skip to content

Commit

Permalink
format -t: trim excessive whitespace
Browse files Browse the repository at this point in the history
  • Loading branch information
mkobetic committed Nov 14, 2023
1 parent bb9ac57 commit 8dda8ec
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 1 deletion.
8 changes: 7 additions & 1 deletion cmd/coin/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand All @@ -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)
}
Expand Down
25 changes: 25 additions & 0 deletions cmd/coin/utils.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package main

import (
"bufio"
"bytes"
"compress/gzip"
"encoding/base64"
"io"
Expand Down Expand Up @@ -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()
}
18 changes: 18 additions & 0 deletions cmd/coin/utils_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}

0 comments on commit 8dda8ec

Please sign in to comment.