-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
132 lines (115 loc) · 2.5 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/akamensky/argparse"
"github.com/mattn/go-shellwords"
)
// Variables definition
var rofiCmd *string
// Create interface for the json file
type File map[string]Program
type Program struct {
Name string `json:"name"`
Commands []struct {
Key string `json:"key"`
Command string `json:"command"`
} `json:"commands"`
}
func main() {
// Create new parser object
parser := argparse.NewParser("rofi-help-shortcuts", "Use rofi to display shortcuts")
jsonPath := parser.String(
"d",
"dir",
&argparse.Options{
Required: false,
Help: "Path to the json file",
Default: "./my-shortcuts.json",
},
)
rofiCmd = parser.String(
"r",
"rofi",
&argparse.Options{
Required: false,
Help: "Command line to launch rofi",
Default: "rofi -dmenu -p \"Shortcuts Help\" -i -no-custom -matching fuzzy",
},
)
var err error = parser.Parse(os.Args)
if err != nil {
fmt.Print(parser.Usage(err))
}
// get arguments from command line
var File = loadJSON(*jsonPath)
runRofi(File)
}
func loadJSON(filename string) File {
filename, _ = filepath.Abs(filename)
fmt.Println(filename)
// open the json file
jsonFile, err := os.Open(filename)
if err != nil {
panic(err)
}
fmt.Println("Successfully opened the file")
byteValue, err := ioutil.ReadAll(jsonFile)
if err != nil {
panic(err)
}
var File File
json.Unmarshal(byteValue, &File)
defer jsonFile.Close()
return File
}
func runRofi(file File) {
args, err := shellwords.Parse(*rofiCmd)
if err != nil {
log.Fatal(err)
}
// Get the first selection
cmd1 := exec.Command(args[0], args[1:]...)
stdin1, err := cmd1.StdinPipe()
if err != nil {
log.Fatal(err)
}
go func() {
defer stdin1.Close()
for _, s := range file {
io.WriteString(stdin1, s.Name+"\n")
}
}()
out1, err := cmd1.CombinedOutput()
if err != nil {
log.Fatal(err)
}
// remove trailing newline
selectedProgram := strings.TrimSpace(string(out1))
// Get the second selection
cmd2 := exec.Command(args[0], args[1:]...)
stdin2, err := cmd2.StdinPipe()
if err != nil {
log.Fatal(err)
}
go func() {
defer stdin2.Close()
for _, s := range file[selectedProgram].Commands {
io.WriteString(stdin2, "("+s.Key+") "+s.Command+"\n")
}
}()
out2, err := cmd2.CombinedOutput()
if err != nil {
log.Fatal(err)
}
var selectedCommand = strings.TrimSpace(string(out2))
// remove trailing newline
fmt.Println(selectedCommand)
}