forked from knqyf263/pet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
edit.go
77 lines (62 loc) · 1.55 KB
/
edit.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
package cmd
import (
"fmt"
"os"
"al.essio.dev/pkg/shellescape"
"github.com/kulack/pet/config"
petSync "github.com/kulack/pet/sync"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
// editCmd represents the edit command
var editCmd = &cobra.Command{
Use: "edit",
Short: "Edit snippet file",
Long: `Edit snippet file (default: opened by vim)`,
RunE: edit,
}
func edit(cmd *cobra.Command, args []string) (err error) {
flag := config.Flag
editor := config.Conf.General.Editor
snippetFile := config.Conf.General.SnippetFile
var options []string
if flag.Query != "" {
options = append(options, fmt.Sprintf("--query %s", shellescape.Quote(flag.Query)))
}
if len(config.Conf.General.SnippetDirs) > 0 {
snippetFile, err = selectFile(options, flag.FilterTag)
if err != nil {
return err
}
}
if snippetFile == "" {
return errors.New("No sippet file seleted")
}
// file content before editing
before := fileContent(snippetFile)
err = editFile(editor, snippetFile, 0)
if err != nil {
return
}
// file content after editing
after := fileContent(snippetFile)
// return if same file content
if before == after {
return nil
}
if config.Conf.Gist.AutoSync {
return petSync.AutoSync(snippetFile)
}
return nil
}
func fileContent(fname string) string {
data, _ := os.ReadFile(fname)
return string(data)
}
func init() {
RootCmd.AddCommand(editCmd)
editCmd.Flags().StringVarP(&config.Flag.Query, "query", "q", "",
`Initial value for query`)
editCmd.Flags().StringVarP(&config.Flag.FilterTag, "tag", "t", "",
`Filter tag`)
}