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

Fix flaky tab writing behavior using text/tabwriter #25

Merged
merged 5 commits into from
Dec 16, 2024
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
6 changes: 3 additions & 3 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package cmd

import (
"fmt"
"io"
"os"
"sort"
"strings"
Expand Down Expand Up @@ -74,15 +73,15 @@ var (
vt = arguments.ViewHuman
}

var w io.Writer = os.Stdout
var w = view.NewTabWriter(os.Stdout, debug)
logFile := os.Getenv("ZNS_LOG_FILE")
if logFile != "" {
f, err := os.Create(logFile)
if err != nil {
panic(fmt.Sprintf("Failed to create log file: %v", err))
}
defer f.Close()
w = f
w = view.NewTabWriter(f, debug)
}

v := view.NewRenderer(vt, &view.View{
Expand Down Expand Up @@ -152,6 +151,7 @@ var (
v.Render(args[0], record)
}
}
w.Flush() // we need to flush the buffer to ensure all data is written to the underlying stream.
},
}
)
Expand Down
22 changes: 21 additions & 1 deletion internal/view/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,34 @@ package view

import (
"fmt"
"io"
"strconv"
"strings"
"text/tabwriter"
"time"

"github.com/fatih/color"
"github.com/miekg/dns"
)

// NewTabWriter initializes and returns a new tabwriter.Writer.
// ZNS uses this writer to format DNS records into a clear, human-readable table.
// See https://pkg.go.dev/text/tabwriter#Writer.Init for details.
func NewTabWriter(w io.Writer, debug bool) *tabwriter.Writer {
flags := uint(0)
if debug {
flags = tabwriter.Debug
}
return tabwriter.NewWriter(
w,
0, // Minwidth
8, // Tabwidth
3, // Padding
' ', // Padchar
flags,
)
}

// formatTTL converts TTL to a more readable format (hours, minutes, seconds).
func formatTTL(ttl uint32) string {
duration := time.Duration(ttl) * time.Second
Expand Down Expand Up @@ -89,8 +109,8 @@ func formatRecord(domainName string, answer dns.RR) string {
Unknown record type: %s

We encountered an unsupported DNS record type: %s.
Please consider raising an issue on GitHub to add support for this record type.

Please consider raising an issue on GitHub to add support for this record type.
https://github.com/znscli/zns/issues/new

Thank you for your contribution!
Expand Down
Loading