Created
February 26, 2020 15:09
-
-
Save kevin-cantwell/308eabc36c911f617c70c1620e617130 to your computer and use it in GitHub Desktop.
Expand psql output
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Accepts an unexpanded psql result set on stdin and expands it. | |
*/ | |
package main | |
import ( | |
"bufio" | |
"fmt" | |
"os" | |
"strings" | |
"golang.org/x/crypto/ssh/terminal" | |
) | |
func main() { | |
width := 80 | |
if terminal.IsTerminal(int(os.Stdout.Fd())) { | |
w, _, _ := terminal.GetSize(int(os.Stdout.Fd())) | |
if w != 0 { | |
width = w | |
} | |
} | |
var header []string | |
pad := "" | |
scanner := bufio.NewScanner(os.Stdin) | |
i := 0 | |
for scanner.Scan() { | |
line := scanner.Text() | |
switch i { | |
case 0: | |
max := 0 | |
header = strings.Split(line, "|") | |
for j, e := range header { | |
header[j] = strings.TrimSpace(e) | |
if l := len(header[j]); l > max { | |
max = l | |
} | |
} | |
pad = fmt.Sprint(max) | |
case 1: | |
// skip | |
default: | |
row := strings.Split(line, "|") | |
for j, e := range row { | |
row[j] = strings.TrimSpace(e) | |
} | |
hr := fmt.Sprintf("-[ RECORD %d ]", i-1) | |
for j := len(hr); j < width; j++ { | |
hr += "-" | |
} | |
fmt.Print(hr + "\n") | |
for j, f := range header { | |
fmt.Printf("%-"+pad+"s | %s\n", f, row[j]) | |
} | |
} | |
i++ | |
} | |
if err := scanner.Err(); err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment