-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmain.go
105 lines (81 loc) · 1.81 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"bytes"
"flag"
"fmt"
"io"
"log"
"os"
"os/signal"
)
const (
VERSION = "1.1.0"
defaultPlaceholder = "{{}}"
)
var placeholder string
var usage = `fzz allows you to run a command interactively.
Usage:
fzz command
The command MUST include the placeholder '{{}}'.
Arguments:
-p Print interactively typed input after exiting if command produced
no output
-v Print version and exit
`
func printUsage() {
fmt.Printf(usage)
}
var flPrint = flag.Bool("p", false, "Print command input if command had no output")
var flVersion = flag.Bool("v", false, "Print fzz version and quit")
func main() {
flag.Usage = printUsage
flag.Parse()
if *flVersion {
fmt.Printf("fzz %s\n", VERSION)
os.Exit(0)
}
if len(flag.Args()) < 2 {
fmt.Fprintf(os.Stderr, usage)
os.Exit(1)
}
if placeholder = os.Getenv("FZZ_PLACEHOLDER"); placeholder == "" {
placeholder = defaultPlaceholder
}
if !validPlaceholder(placeholder) {
fmt.Fprintln(os.Stderr, "Placeholder is not valid, needs even number of characters")
os.Exit(1)
}
input, args := extractInput(flag.Args(), placeholder)
if !containsPlaceholder(args, placeholder) {
fmt.Fprintln(os.Stderr, "No placeholder in arguments")
os.Exit(1)
}
tty, err := NewTTY()
if err != nil {
log.Fatal(err)
}
defer tty.resetState()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
<-c
tty.resetState()
os.Exit(1)
}()
tty.setSttyState("cbreak", "-echo")
stdinbuf := bytes.Buffer{}
if isPipe(os.Stdin) {
io.Copy(&stdinbuf, os.Stdin)
}
printer := NewPrinter(tty, tty.cols, tty.rows-1) // prompt is one row
fzz := &Fzz{
printer: printer,
tty: tty,
stdinbuf: &stdinbuf,
input: []byte(input),
placeholder: placeholder,
args: args,
printInput: *flPrint,
}
fzz.Loop()
}