-
Notifications
You must be signed in to change notification settings - Fork 234
/
Copy pathnew.go
274 lines (242 loc) · 5.88 KB
/
new.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
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/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")
}
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, 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
editor := config.Conf.General.Editor
err := editFile(editor, snippetFile, startLine)
if err != nil {
return err
}
if config.Conf.Gist.AutoSync {
return petSync.AutoSync(snippetFile)
}
return nil
}
func countSnippetLines() int {
// Count lines in snippet file
f, err := os.Open(config.Conf.General.SnippetFile)
if err != nil {
panic("Error reading snippet file")
}
lineCount, err := CountLines(f)
if err != nil {
panic("Error counting lines in snippet file")
}
return lineCount
}
func new(cmd *cobra.Command, args []string) (err error) {
var filename string = ""
var command string
var description string
var tags []string
var snippets snippet.Snippets
if err := snippets.Load(); 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(".......> "),
os.Stdout, os.Stdin,
)
} else if config.Flag.UseEditor {
// Create and save empty snippet
newSnippet := snippet.SnippetInfo{
Description: description,
Command: command,
Tag: tags,
}
return createAndEditSnippet(newSnippet, snippets, lineCount+3)
} else {
command, err = scan(color.HiYellowString("Command> "), os.Stdout, os.Stdin, false)
}
if err != nil {
return err
}
}
description, err = scan(color.HiGreenString("Description> "), os.Stdout, os.Stdin, false)
if err != nil {
return err
}
if config.Flag.Tag {
var t string
if t, err = scan(color.HiCyanString("Tag> "), os.Stdout, os.Stdin, 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,
}
snippets.Snippets = append(snippets.Snippets, newSnippet)
if err = snippets.Save(); err != nil {
return err
}
if config.Conf.Gist.AutoSync {
return petSync.AutoSync(filename)
}
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`)
}