-
Notifications
You must be signed in to change notification settings - Fork 243
Expand file tree
/
Copy pathnew.go
More file actions
317 lines (274 loc) · 7.02 KB
/
new.go
File metadata and controls
317 lines (274 loc) · 7.02 KB
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
309
310
311
312
313
314
315
316
317
package cmd
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/chzyer/readline"
"github.com/fatih/color"
"github.com/knqyf263/pet/config"
"github.com/knqyf263/pet/path"
"github.com/knqyf263/pet/snippet"
petSync "github.com/knqyf263/pet/sync"
"github.com/spf13/cobra"
)
// newCmd represents the new command
var newCmd = &cobra.Command{
Use: "new COMMAND",
Short: "Create a new snippet",
Long: `Create a new snippet (default: $HOME/.config/pet/snippet.toml)`,
RunE: new,
}
func CanceledError() error {
return errors.New("canceled")
}
// setStaticField sets the static field on a snippet if the static flag is enabled
func setStaticField(snippetInfo *snippet.SnippetInfo) {
if config.Flag.Static {
static := true
snippetInfo.Static = &static
}
}
func scan(prompt string, out io.Writer, in io.ReadCloser, allowEmpty bool) (string, error) {
f, err := os.CreateTemp("", "pet-")
if err != nil {
return "", err
}
defer os.Remove(f.Name()) // clean up temp file
tempFile := f.Name()
l, err := readline.NewEx(&readline.Config{
Stdout: out,
Stdin: in,
Prompt: prompt,
HistoryFile: tempFile,
InterruptPrompt: "^C",
EOFPrompt: "exit",
HistorySearchFold: true,
})
if err != nil {
return "", err
}
defer l.Close()
for {
line, err := l.Readline()
if err == readline.ErrInterrupt {
if len(line) == 0 {
break
} else {
continue
}
} else if err == io.EOF {
break
}
// If empty string, just ignore tags
line = strings.TrimSpace(line)
if line == "" && !allowEmpty {
continue
} else if line == "" {
return "", nil
}
return line, nil
}
return "", CanceledError()
}
// States of scanMultiLine state machine
const (
start = iota
lastLineNotEmpty
lastLineEmpty
)
func scanMultiLine(prompt string, secondMessage string, out io.Writer, in io.ReadCloser) (string, error) {
tempFile := "/tmp/pet.tmp"
if runtime.GOOS == "windows" {
tempDir := os.Getenv("TEMP")
tempFile = filepath.Join(tempDir, "pet.tmp")
}
l, err := readline.NewEx(&readline.Config{
Stdout: out,
Stdin: in,
Prompt: prompt,
HistoryFile: tempFile,
InterruptPrompt: "^C",
EOFPrompt: "exit",
VimMode: false,
HistorySearchFold: true,
})
if err != nil {
return "", err
}
defer l.Close()
state := start
multiline := ""
for {
line, err := l.Readline()
if err == readline.ErrInterrupt {
if len(line) == 0 {
break
} else {
continue
}
} else if err == io.EOF {
break
}
switch state {
case start:
if line == "" {
continue
}
multiline += line
state = lastLineNotEmpty
l.SetPrompt(secondMessage)
case lastLineNotEmpty:
if line == "" {
state = lastLineEmpty
continue
}
multiline += "\n" + line
case lastLineEmpty:
if line == "" {
return multiline, nil
}
multiline += "\n" + line
state = lastLineNotEmpty
}
}
return "", errors.New("canceled")
}
// createAndEditSnippet creates and saves a given snippet to the main snippet file
// then opens the configured editor to edit the snippet file at startLine.
func createAndEditSnippet(newSnippet snippet.SnippetInfo, snippets snippet.Snippets, startLine int) error {
snippets.Snippets = append(snippets.Snippets, newSnippet)
if err := snippets.Save(); err != nil {
return err
}
// Open snippet for editing
snippetFile := config.Conf.General.SnippetFile
snippetFilePath, err := path.NewAbsolutePath(snippetFile)
if err != nil {
return err
}
editor := config.Conf.General.Editor
err = editFile(editor, snippetFilePath, startLine)
if err != nil {
return err
}
if config.Conf.Gist.AutoSync {
return petSync.AutoSync(snippetFilePath)
}
return nil
}
func countSnippetLines() int {
// Count lines in snippet file
path, err := path.NewAbsolutePath(config.Conf.General.SnippetFile)
if err != nil {
panic(fmt.Sprintf("Error getting snippet file path: %v", err.Error()))
}
f, err := os.Open(path.Get())
if err != nil {
panic("Snippet file must be specified - could not read snippet file.")
}
lineCount, err := CountLines(f)
if err != nil {
panic("Error counting lines in snippet file")
}
return lineCount
}
// new creates a new snippet and saves it to the main snippet file
// then syncs the snippet file if configured to do so.
func new(cmd *cobra.Command, args []string) (err error) {
return _new(os.Stdin, os.Stdout, args)
}
func _new(in io.ReadCloser, out io.Writer, args []string) (err error) {
var filename string = ""
var command string
var description string
var tags []string
// Load snippets from the main file only
var snippets snippet.Snippets
if err := snippets.Load(false); err != nil {
return err
}
lineCount := countSnippetLines()
if len(args) > 0 {
command = strings.Join(args, " ")
fmt.Fprintf(color.Output, "%s %s\n", color.HiYellowString("Command>"), command)
} else {
if config.Flag.UseMultiLine {
command, err = scanMultiLine(
color.YellowString("Command> "),
color.YellowString(".......> "),
out, in,
)
} else if config.Flag.UseEditor {
// Create and save empty snippet
newSnippet := snippet.SnippetInfo{
Description: description,
Command: command,
Tag: tags,
}
// Set static field if static flag is used
setStaticField(&newSnippet)
return createAndEditSnippet(newSnippet, snippets, lineCount+3)
} else {
command, err = scan(color.HiYellowString("Command> "), out, in, false)
}
if err != nil {
return err
}
}
description, err = scan(color.HiGreenString("Description> "), out, in, false)
if err != nil {
return err
}
if config.Flag.Tag {
var t string
if t, err = scan(color.HiCyanString("Tag> "), out, in, true); err != nil {
return err
}
if t != "" {
tags = strings.Fields(t)
}
}
for _, s := range snippets.Snippets {
if s.Description == description {
return fmt.Errorf("snippet [%s] already exists", description)
}
}
if config.Conf.General.SnippetFile != "" {
filename = config.Conf.General.SnippetFile
}
newSnippet := snippet.SnippetInfo{
Filename: filename,
Description: description,
Command: command,
Tag: tags,
}
// Set static field if static flag is used
setStaticField(&newSnippet)
snippets.Snippets = append(snippets.Snippets, newSnippet)
if err = snippets.Save(); err != nil {
return err
}
if config.Conf.Gist.AutoSync {
filePath, err := path.NewAbsolutePath(filename)
if err != nil {
return err
}
return petSync.AutoSync(filePath)
}
return nil
}
func init() {
RootCmd.AddCommand(newCmd)
newCmd.Flags().BoolVarP(&config.Flag.Tag, "tag", "t", false,
`Display tag prompt (delimiter: space)`)
newCmd.Flags().BoolVarP(&config.Flag.UseMultiLine, "multiline", "m", false,
`Can enter multiline snippet (Double \n to quit)`)
newCmd.Flags().BoolVarP(&config.Flag.UseEditor, "editor", "e", false,
`Use editor to create snippet`)
newCmd.Flags().BoolVarP(&config.Flag.Static, "static", "s", false,
`Create snippet without parameter expansion (static = true)`)
}