Created
November 3, 2014 21:55
-
-
Save homburg/a1b76bc8a03084c379b0 to your computer and use it in GitHub Desktop.
Pager pipe (like git)
This file contains hidden or 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
package main | |
// From | |
// http://stackoverflow.com/questions/21738674/how-do-i-print-a-buffer-to-stdout-piped-through-a-pager | |
// http://rosettacode.org/wiki/Terminal_control/Dimensions | |
import ( | |
"bufio" | |
"io" | |
"os" | |
"os/exec" | |
"bytes" | |
"code.google.com/p/go.crypto/ssh/terminal" | |
"log" | |
) | |
func page(b bytes.Buffer) { | |
pager := os.Getenv("PAGER") | |
if pager == "" { | |
pager = "pager" | |
} | |
cmd := exec.Command(pager) | |
r, stdin := io.Pipe() | |
cmd.Stdin = r | |
cmd.Stdout = os.Stdout | |
cmd.Stderr = os.Stderr | |
c := make(chan struct{}) | |
go func() { | |
defer close(c) | |
cmd.Run() | |
}() | |
b.WriteTo(stdin) | |
io.Copy(stdin, os.Stdin) | |
stdin.Close() | |
<-c | |
} | |
func main() { | |
w, h, err := terminal.GetSize(int(os.Stdout.Fd())) | |
if nil != err { | |
log.Fatal(err) | |
} | |
var b bytes.Buffer | |
scanner := bufio.NewScanner(os.Stdin) | |
height := 0 | |
for scanner.Scan() { | |
line := scanner.Text() | |
add := len(line) / w | |
if len(line)%w > 0 { | |
add++ | |
} | |
b.WriteString(line + "\n") | |
height += add | |
if height > h { | |
page(b) | |
return | |
} | |
} | |
b.WriteTo(os.Stdout) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment