-
Notifications
You must be signed in to change notification settings - Fork 0
/
tenjin.go
executable file
·308 lines (270 loc) · 6.99 KB
/
tenjin.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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
/// 2>/dev/null ; gorun "$0" "$@" ; exit $?
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/atotto/clipboard"
"github.com/fatih/color"
"github.com/manifoldco/promptui"
"github.com/urfave/cli/v2"
"github.com/zyedidia/highlight"
)
var BuildVersion string = "1.0.0"
func getDirectories(home string) []string {
var directories []string
err := filepath.Walk(home, func(path string, info os.FileInfo, err error) error {
if err == nil && info.IsDir() {
// remove home directory from path
path = strings.Replace(path, home, "", 1)
// filter hidden directories and
if !strings.Contains(path, ".") && path != "" {
directories = append(directories, path)
}
}
return nil
})
if err != nil {
log.Fatal(err)
}
return directories
}
func copyFile(contents []byte) {
// convert file's []byte to string
text := string(contents)
// and write to clipboard
clipboard.WriteAll(text)
}
func moveFile(name string, contents []byte) {
// get current direcotry
path, err := os.Getwd()
if err != nil {
log.Println(err)
}
// save file to cwd
error := os.WriteFile(path+"/"+name, contents, 0755)
if error != nil {
log.Fatal(error)
}
}
func highlightFile(name string, path string, contents []byte) {
// get home directory
home, err := os.UserHomeDir()
if err != nil {
log.Fatal(err)
}
// get file type
pattern := regexp.MustCompile(`.*\.([a-z]{1,3})$`)
ext := pattern.ReplaceAllString(name, `$1`)
// match language
langTypes := map[string]string{
"conf": "conf",
"css": "css",
"go": "go",
"html": "html",
"js": "javascript",
"json": "json",
"jsx": "javascript",
"md": "markdown",
"py": "python3",
"scss": "css",
"sh": "sh",
"toml": "toml",
"ts": "typescript",
"tsx": "typescript",
"yaml": "yaml",
}
lang := langTypes["conf"]
if ext != name {
lang = langTypes[ext]
}
// load the go syntax file
syntaxFile, _ := os.ReadFile(home + "/tenjin/syntax/" + lang + ".yaml")
// parse it into a `*highlight.Def`
syntaxDef, err := highlight.ParseDef(syntaxFile)
if err != nil {
log.Fatal(err)
}
// new highlighter from definition
hl := highlight.NewHighlighter(syntaxDef)
// convert file's []byte to string
text := string(contents)
// highlight the string
matches := hl.HighlightString(text)
// split the string into a bunch of lines
// print the string
lines := strings.Split(text, "\n")
for lineN, l := range lines {
for colN, c := range l {
// check if the group changed at the current position
if group, ok := matches[lineN][colN]; ok {
// check the group name and set the color accordingly (the colors chosen are arbitrary)
if group == highlight.Groups["statement"] {
color.Set(color.FgGreen)
} else if group == highlight.Groups["preproc"] {
color.Set(color.FgHiRed)
} else if group == highlight.Groups["special"] {
color.Set(color.FgBlue)
} else if group == highlight.Groups["constant.string"] {
color.Set(color.FgCyan)
} else if group == highlight.Groups["constant.specialChar"] {
color.Set(color.FgHiMagenta)
} else if group == highlight.Groups["type"] {
color.Set(color.FgYellow)
} else if group == highlight.Groups["constant.number"] {
color.Set(color.FgCyan)
} else if group == highlight.Groups["comment"] {
color.Set(color.FgHiGreen)
} else {
color.Unset()
}
}
// Print the character
fmt.Print(string(c))
}
// This is at a newline, but highlighting might have been turned off at the very end of the line so we should check that.
if group, ok := matches[lineN][len(l)]; ok {
if group == highlight.Groups["default"] || group == highlight.Groups[""] {
color.Unset()
}
}
fmt.Print("\n")
}
}
func prompt(directories []string, home string, repo string, selectedAction string, preSelectedDirectory string, preSelectedPosition int) {
directory := preSelectedDirectory
postion := preSelectedPosition
action := strings.ToLower(selectedAction)
// if no directory is selected, prompt for one
if directory == "" {
// create directory selector
promptDir := promptui.Select{
Label: "Select a directory",
Items: directories,
}
_, selectedDirectory, err := promptDir.Run()
if err != nil {
log.Fatal(err)
}
directory = selectedDirectory
}
// read files from selected directory
dirPath := home + repo + directory
files, err := os.ReadDir(dirPath)
if err != nil {
log.Fatal(err)
}
// save filenames from selection to array
var fileNames []string
for _, file := range files {
fileNames = append(fileNames, file.Name())
}
// create file selector
searcher := func(input string, index int) bool {
file := fileNames[index]
name := strings.Replace(strings.ToLower(file), " ", "", -1)
input = strings.Replace(strings.ToLower(input), " ", "", -1)
return strings.Contains(name, input)
}
// select file and get position
promptFile := promptui.Select{
Label: "Select a file",
Items: fileNames,
Searcher: searcher,
CursorPos: postion,
}
selPos, file, err := promptFile.Run()
if err != nil {
log.Fatal(err)
}
postion = selPos
// get file contents
filePath := dirPath + "/" + file
fileContent, err := os.ReadFile(filePath)
if err != nil {
log.Fatal(err)
}
// create action selector if no action was passed
if selectedAction == "" {
promptAction := promptui.Select{
Label: "Select a action",
Items: []string{"Save", "Copy", "Preview"},
}
_, actionSelector, err := promptAction.Run()
if err != nil {
log.Fatal(err)
} else {
action = strings.ToLower(actionSelector)
}
}
// execute actions
switch action {
case "save":
moveFile(file, fileContent)
color.Cyan("Saved to current directory!")
case "copy":
copyFile(fileContent)
color.Cyan("Copied to clipboard!")
case "preview":
highlightFile(file, filePath, fileContent)
// return to file selection prompt
prompt(directories, home, repo, "", directory, postion)
default:
color.Red("No selection made.")
}
}
func main() {
var action string
repo := "/tenjin/templates/"
// get home directory
home, err := os.UserHomeDir()
if err != nil {
log.Fatal(err)
}
directories := getDirectories(home + repo)
// versioning
cli.VersionFlag = &cli.BoolFlag{
Name: "version",
Aliases: []string{"v"},
Usage: "print app version",
}
// help
cli.AppHelpTemplate = `NAME:
{{.Name}} - {{.Usage}}
VERSION:
{{.Version}}
USAGE:
{{.HelpName}} [optional options]
OPTIONS:
{{range .VisibleFlags}} {{.}}{{ "\n" }}{{end}}
`
cli.HelpFlag = &cli.BoolFlag{
Name: "help",
Aliases: []string{"h"},
Usage: "show help",
}
// execute app
app := &cli.App{
Name: "tenjin",
Usage: "Simple code snippet manager",
Version: BuildVersion,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "action",
Aliases: []string{"a"},
Usage: "file handling action",
Destination: &action,
},
},
Action: func(*cli.Context) error {
prompt(directories, home, repo, action, "", 0)
return nil
},
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}