Ver Código Fonte

Add a tool to run a command with the output piped in

This is useful to e.g. run `sort` on the output of a long-running
program.  Input is displayed directly, and only later/then fed to the
program.
Lucas Stadler 9 anos atrás
pai
commit
093085230d
1 arquivos alterados com 56 adições e 0 exclusões
  1. 56 0
      go/after/after.go

+ 56 - 0
go/after/after.go

@ -0,0 +1,56 @@
1
package main
2
3
// after - Run a command when the input is finished.
4
//
5
// Usage: <input> | after <cmd>
6
7
import (
8
	"bytes"
9
	"fmt"
10
	"io"
11
	"os"
12
	"os/exec"
13
	"time"
14
)
15
16
const (
17
	Cr  = 13
18
	Esc = 27
19
)
20
21
func main() {
22
	if len(os.Args) == 1 {
23
		fmt.Fprintf(os.Stderr, "Usage: <input> | %s <cmd>", os.Args[0])
24
		os.Exit(1)
25
	}
26
27
	buf := new(bytes.Buffer)
28
	r := io.TeeReader(os.Stdin, buf)
29
30
	// Copy output from command to stdout
31
	io.Copy(os.Stdout, r)
32
33
	// Clear output (after stdin was closed)
34
	numLines := 0
35
	for _, ch := range buf.Bytes() {
36
		if ch == '\n' {
37
			numLines += 1
38
		}
39
	}
40
41
	fmt.Fprintf(os.Stdout, "\r")
42
	for i := 0; i < numLines; i++ {
43
		fmt.Fprintf(os.Stdout, "%c[K", Esc)
44
		fmt.Fprintf(os.Stdout, "%c[1A", Esc)
45
	}
46
	time.Sleep(2 * time.Second)
47
48
	// Run command
49
	cmd := exec.Command(os.Args[1])
50
	cmd.Args = os.Args[2:]
51
	cmd.Stdin = buf
52
	cmd.Stdout = os.Stdout
53
	cmd.Stderr = os.Stderr
54
55
	cmd.Run()
56
}