Skip to content

Commit

Permalink
Now auto-adds trailing newline if necessary
Browse files Browse the repository at this point in the history
A "-p" / "--preserve" flag has been added for times when one needs to
preserve the exact whitespacing of the source string.
  • Loading branch information
Steven Xie committed Aug 12, 2018
1 parent de05293 commit 0a06afa
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 8 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
## ----- REPOSITORY -----
## The compiled binary
## The compiled binary (excluding Go source files)
/dgen*
!/dgen*.go

## ---- CODECOV -----
coverage.txt
Expand Down
3 changes: 2 additions & 1 deletion flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ var (
// Opts are flag-enabled options for dgen.
Opts struct {
// Stats will show statistics at the end of the string dump.
Stats bool `short:"s" long:"stats" description:"Show statistics after string dump."`
Stats bool `short:"s" long:"stats" description:"Show statistics after string dump."`
Preserve bool `short:"p" long:"preserve" description:"Preserve whitespacing; do not add terminating newlines."`
}

fparser = flags.NewParser(&Opts, flags.Default)
Expand Down
20 changes: 14 additions & 6 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"fmt"
"github.com/steven-xie/dgen/throughput"
"os"
"strings"
)

func main() {
Expand All @@ -13,16 +12,17 @@ func main() {

n, err := throughput.Dump(str, reps, Bufsize, os.Stdout)

hasnl := hasTrailingNewline(str)
// Ensure that if extra info is about to be produced, there are at least two
// newlines before that info is printed.
if err != nil || Opts.Stats {
nlcount := strings.Count(str, "\n")
switch nlcount {
case 0:
fmt.Print("\n\n")
case 1:
if hasnl {
fmt.Print("\n")
} else {
fmt.Print("\n\n")
}
} else if !Opts.Preserve && !hasnl {
fmt.Print("\n")
}

if err != nil {
Expand All @@ -34,3 +34,11 @@ func main() {
fmt.Printf("Successfully printed %d bytes.\n", n)
}
}

func hasTrailingNewline(s string) bool {
strlen := len(s)
if strlen < 1 {
return false
}
return s[strlen-1] == '\n'
}

0 comments on commit 0a06afa

Please sign in to comment.