Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

format -t: trim excessive whitespace #3

Merged
merged 1 commit into from
Nov 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
}
Loading