-
Notifications
You must be signed in to change notification settings - Fork 271
/
Copy pathmain.go
229 lines (196 loc) · 5.36 KB
/
main.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
package main
import (
"context"
_ "embed"
"errors"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"regexp"
"runtime/debug"
"strings"
"syscall"
version "github.com/hashicorp/go-version"
"github.com/spf13/cobra"
)
const extension = ".tape"
var (
// Version stores the build version of VHS at the time of packaging through -ldflags
//
// go build -ldflags "-s -w -X=main.Version=$(VERSION)" main.go
Version string
// CommitSHA stores the commit SHA of VHS at the time of packaging through -ldflags
CommitSHA string
ttydMinVersion = version.Must(version.NewVersion("1.7.2"))
rootCmd = &cobra.Command{
Use: "vhs <file>",
Short: "Run a given tape file and generates its outputs.",
Args: cobra.MaximumNArgs(1),
SilenceUsage: true,
SilenceErrors: true, // we print our own errors
RunE: func(cmd *cobra.Command, args []string) error {
err := ensureDependencies()
if err != nil {
return err
}
in := cmd.InOrStdin()
// Set the input to the file contents if a file is given
// otherwise, use stdin
if len(args) > 0 && args[0] != "-" {
in, err = os.Open(args[0])
if err != nil {
return err
}
fmt.Println(FileStyle.Render("File: " + args[0]))
}
input, err := io.ReadAll(in)
if err != nil {
return err
}
if string(input) == "" {
return errors.New("no input provided")
}
return Evaluate(cmd.Context(), string(input), os.Stdout)
},
}
markdown bool
themesCmd = &cobra.Command{
Use: "themes",
Short: "List all the available themes, one per line",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
var prefix, suffix string
if markdown {
fmt.Fprintf(cmd.OutOrStdout(), "# Themes\n\n")
prefix, suffix = "* `", "`"
}
for _, theme := range sortedThemeNames() {
fmt.Fprintf(cmd.OutOrStdout(), "%s%s%s\n", prefix, theme, suffix)
}
},
}
newCmd = &cobra.Command{
Use: "new <name>",
Short: "Create a new tape file with example tape file contents and documentation",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
fileName := strings.TrimSuffix(args[0], extension) + extension
f, err := os.Create(fileName)
if err != nil {
return err
}
_, err = f.Write(DemoTape)
if err != nil {
return err
}
fmt.Println("Created " + fileName)
return nil
},
}
validateCmd = &cobra.Command{
Use: "validate <file>...",
Short: "Validate a glob file path and parses all the files to ensure they are valid without running them.",
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
valid := true
for _, file := range args {
b, err := os.ReadFile(file)
if err != nil {
continue
}
l := NewLexer(string(b))
p := NewParser(l)
_ = p.Parse()
errs := p.Errors()
if len(errs) != 0 {
lines := strings.Split(string(b), "\n")
fmt.Println(ErrorFileStyle.Render(file))
for _, err := range errs {
fmt.Print(LineNumber(err.Token.Line))
fmt.Println(lines[err.Token.Line-1])
fmt.Print(strings.Repeat(" ", err.Token.Column+ErrorColumnOffset))
fmt.Println(Underline(len(err.Token.Literal)), err.Msg)
fmt.Println()
}
valid = false
}
}
if !valid {
return errors.New("invalid tape file(s)")
}
return nil
},
}
)
func main() {
ctx, cancel := signal.NotifyContext(
context.Background(),
os.Interrupt, syscall.SIGTERM,
)
defer cancel()
if err := rootCmd.ExecuteContext(ctx); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func init() {
themesCmd.Flags().BoolVar(&markdown, "markdown", false, "output as markdown")
_ = themesCmd.Flags().MarkHidden("markdown")
rootCmd.AddCommand(
newCmd,
themesCmd,
validateCmd,
manCmd,
serveCmd,
)
rootCmd.CompletionOptions.HiddenDefaultCmd = true
if len(CommitSHA) >= 7 { //nolint:gomnd
vt := rootCmd.VersionTemplate()
rootCmd.SetVersionTemplate(vt[:len(vt)-1] + " (" + CommitSHA[0:7] + ")\n")
}
if Version == "" {
if info, ok := debug.ReadBuildInfo(); ok && info.Main.Sum != "" {
Version = info.Main.Version
} else {
Version = "unknown (built from source)"
}
}
rootCmd.Version = Version
}
var versionRegex = regexp.MustCompile(`\d+\.\d+\.\d+`)
// getVersion returns the parsed version of a program
func getVersion(program string) *version.Version {
cmd := exec.Command(program, "--version")
out, err := cmd.Output()
if err != nil {
return nil
}
programVersion, _ := version.NewVersion(versionRegex.FindString(string(out)))
return programVersion
}
// ensureDependencies ensures that all dependencies are correctly installed
// and versioned before continuing
func ensureDependencies() error {
_, ffmpegErr := exec.LookPath("ffmpeg")
if ffmpegErr != nil {
return fmt.Errorf("ffmpeg is not installed. Install it from: http://ffmpeg.org")
}
_, ttydErr := exec.LookPath("ttyd")
if ttydErr != nil {
return fmt.Errorf("ttyd is not installed. Install it from: https://github.com/tsl0922/ttyd")
}
_, bashErr := exec.LookPath("bash")
if bashErr != nil {
return fmt.Errorf("bash is not installed")
}
ttydVersion := getVersion("ttyd")
if ttydVersion == nil || ttydVersion.LessThan(ttydMinVersion) {
return fmt.Errorf("ttyd version (%s) is out of date, VHS requires %s\n%s",
ttydVersion,
ttydMinVersion,
"Install the latest version from: https://github.com/tsl0922/ttyd")
}
return nil
}