forked from stateful/runme
/
snippet.go
96 lines (77 loc) · 1.72 KB
/
snippet.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
package parser
import (
"regexp"
"strings"
)
type Snippet struct {
attributes map[string]string
content string
description string // preceeding paragraph
name string
language string
}
func (s *Snippet) Executable() string {
if s.language != "" && s.language != "console" {
return s.language
}
return "sh"
}
func (s *Snippet) Content() string {
return strings.TrimSpace(s.content)
}
func (s *Snippet) ReplaceContent(val string) {
s.content = val
}
func (s *Snippet) Lines() []string {
var cmds []string
firstHasDollar := false
lines := strings.Split(s.content, "\n")
for _, line := range lines {
if strings.HasPrefix(line, "$") {
firstHasDollar = true
line = strings.TrimLeft(line, "$")
} else if firstHasDollar {
// If the first line was prefixed with "$",
// then all commands should be as well.
// If they are not, it's likely that
// they indicate the expected output instead.
continue
}
line = strings.TrimSpace(line)
if line == "" {
continue
}
cmds = append(cmds, line)
}
return cmds
}
func (s *Snippet) FirstLine() string {
cmds := s.Lines()
if len(cmds) > 0 {
return cmds[0]
}
return ""
}
var descriptionEndingsRe = regexp.MustCompile(`[:?!]$`)
func (s *Snippet) Description() string {
result := descriptionEndingsRe.ReplaceAllString(s.description, ".")
return result
}
func (s *Snippet) Name() string {
return s.name
}
type Snippets []*Snippet
func (s Snippets) Lookup(name string) (*Snippet, bool) {
for _, snippet := range s {
if snippet.Name() == name {
return snippet, true
}
}
return nil, false
}
func (s Snippets) Names() (result []string) {
for _, snippet := range s {
result = append(result, snippet.Name())
}
return result
}