From 414c940baf2f143e5f112a404e422792b308f917 Mon Sep 17 00:00:00 2001 From: JBD Date: Fri, 1 Sep 2017 17:43:29 -0700 Subject: [PATCH] output better aligned results (#46) Before the change, the output looked: 43819 gops go1.9 /Users/jbd/bin/gops 20160 corp-ssh-helper go1.8.1.typealias /usr/local/bin/corp-ssh-helper 30492 dlv go1.9 /Users/jbd/bin/dlv 31212 godoc devel +990dac2723 Fri Jun 30 18:24:58 2017 +0000 /Users/jbd/bin/godoc 18579 mnp_logger go1.7.1 /usr/local/bin/mnp_logger After the change, it looks: 48071 gops go1.9 /Users/jbd/bin/gops 31212 godoc devel +990dac2723 Fri Jun 30 18:24:58 2017 +0000 /Users/jbd/bin/godoc 18579 mnp_logger go1.7.1 /usr/local/bin/mnp_logger 20160 corp-ssh-helper go1.8.1.typealias /usr/local/bin/corp-ssh-helper 30492 dlv go1.9 /Users/jbd/bin/dlv 44512 gocode devel +990dac2723 Fri Jun 30 18:24:58 2017 +0000 /Users/jbd/bin/gocode --- main.go | 40 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/main.go b/main.go index 4bf7c8b..28819d1 100644 --- a/main.go +++ b/main.go @@ -9,6 +9,8 @@ import ( "bytes" "fmt" "os" + "strconv" + "strings" "github.com/google/gops/goprocess" ) @@ -64,13 +66,31 @@ func main() { } func processes() { - for _, p := range goprocess.Find() { + ps := goprocess.Find() + + var maxPID, maxExec, maxVersion int + for _, p := range ps { + maxPID = max(maxPID, len(strconv.Itoa(p.PID))) + maxExec = max(maxExec, len(p.Exec)) + maxVersion = max(maxVersion, len(p.BuildVersion)) + } + + for _, p := range ps { buf := bytes.NewBuffer(nil) - fmt.Fprintf(buf, "%d", p.PID) + pid := strconv.Itoa(p.PID) + fmt.Fprint(buf, pad(pid, maxPID)) if p.Agent { fmt.Fprint(buf, "*") + } else { + fmt.Fprint(buf, " ") } - fmt.Fprintf(buf, "\t%v\t%v\t%v\n", p.Exec, p.BuildVersion, p.Path) + fmt.Fprint(buf, " ") + fmt.Fprint(buf, pad(p.Exec, maxExec)) + fmt.Fprint(buf, " ") + fmt.Fprint(buf, pad(p.BuildVersion, maxVersion)) + fmt.Fprint(buf, " ") + fmt.Fprint(buf, p.Path) + fmt.Fprintln(buf) buf.WriteTo(os.Stdout) } } @@ -82,3 +102,17 @@ func usage(msg string) { fmt.Fprintf(os.Stderr, "%v\n", helpText) os.Exit(1) } + +func pad(s string, total int) string { + if len(s) >= total { + return s + } + return s + strings.Repeat(" ", total-len(s)) +} + +func max(i, j int) int { + if i > j { + return i + } + return j +}