forked from knqyf263/pet
/
new.go
78 lines (67 loc) · 1.51 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
package cmd
import (
"bufio"
"errors"
"fmt"
"os"
"strings"
"github.com/fatih/color"
"github.com/knqyf263/pet/snippet"
"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 scan(message string) (string, error) {
fmt.Print(message)
scanner := bufio.NewScanner(os.Stdin)
if !scanner.Scan() {
return "", errors.New("canceled")
}
if scanner.Err() != nil {
return "", scanner.Err()
}
return scanner.Text(), nil
}
func new(cmd *cobra.Command, args []string) (err error) {
var command string
var description string
var snippets snippet.Snippets
if err := snippets.Load(); err != nil {
return err
}
if len(args) > 0 {
command = strings.Join(args, " ")
fmt.Printf("%s %s\n", color.YellowString("Command:"), command)
} else {
command, err = scan(color.YellowString("Command: "))
if err != nil {
return err
}
}
description, err = scan(color.GreenString("Description: "))
if err != nil {
return err
}
for _, s := range snippets.Snippets {
if s.Description == description {
return fmt.Errorf("Snippet [%s] already exists", description)
}
}
newSnippet := snippet.SnippetInfo{
Description: description,
Command: command,
}
snippets.Snippets = append(snippets.Snippets, newSnippet)
if err = snippets.Save(); err != nil {
return err
}
return nil
}
func init() {
RootCmd.AddCommand(newCmd)
}