forked from knqyf263/pet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.go
85 lines (77 loc) · 2.25 KB
/
list.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
package cmd
import (
"fmt"
"strings"
"github.com/fatih/color"
"github.com/kulack/pet/config"
"github.com/kulack/pet/snippet"
runewidth "github.com/mattn/go-runewidth"
"github.com/spf13/cobra"
)
const (
column = 40
)
// listCmd represents the list command
var listCmd = &cobra.Command{
Use: "list",
Short: "Show all snippets",
Long: `Show all snippets`,
RunE: list,
}
func list(cmd *cobra.Command, args []string) error {
var snippets snippet.Snippets
if err := snippets.Load(); err != nil {
return err
}
col := config.Conf.General.Column
if col == 0 {
col = column
}
for _, snippet := range snippets.Snippets {
if config.Flag.OneLine {
description := runewidth.FillRight(runewidth.Truncate(snippet.Description, col, "..."), col)
command := snippet.Command
// make sure multiline command printed as oneline
command = strings.Replace(command, "\n", "\\n", -1)
fmt.Fprintf(color.Output, "%s : %s\n",
color.HiGreenString(description), color.HiYellowString(command))
} else {
if config.Flag.Debug {
fmt.Fprintf(color.Output, "%12s %s\n",
color.RedString(" Filename:"), snippet.Filename)
}
fmt.Fprintf(color.Output, "%12s %s\n",
color.HiGreenString("Description:"), snippet.Description)
if strings.Contains(snippet.Command, "\n") {
lines := strings.Split(snippet.Command, "\n")
firstLine, restLines := lines[0], lines[1:]
fmt.Fprintf(color.Output, "%12s %s\n",
color.HiYellowString(" Command:"), firstLine)
for _, line := range restLines {
fmt.Fprintf(color.Output, "%12s %s\n",
" ", line)
}
} else {
fmt.Fprintf(color.Output, "%12s %s\n",
color.HiYellowString(" Command:"), snippet.Command)
}
if snippet.Tag != nil {
tag := strings.Join(snippet.Tag, " ")
fmt.Fprintf(color.Output, "%12s %s\n",
color.HiCyanString(" Tag:"), tag)
}
if snippet.Output != "" {
output := strings.Replace(snippet.Output, "\n", "\n ", -1)
fmt.Fprintf(color.Output, "%12s %s\n",
color.HiRedString(" Output:"), output)
}
fmt.Println(strings.Repeat("-", 30))
}
}
return nil
}
func init() {
RootCmd.AddCommand(listCmd)
listCmd.Flags().BoolVarP(&config.Flag.OneLine, "oneline", "", false,
`Display snippets in one line`)
}