-
Notifications
You must be signed in to change notification settings - Fork 261
/
main.go
331 lines (287 loc) · 8.06 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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
package main
import (
"bytes"
"context"
_ "embed"
"errors"
"fmt"
"io"
"log"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"runtime/debug"
"strings"
"syscall"
"github.com/charmbracelet/vhs/lexer"
"github.com/charmbracelet/vhs/parser"
version "github.com/hashicorp/go-version"
"github.com/mattn/go-isatty"
"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"))
publishFlag bool
outputs *[]string
quietFlag bool
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
PersistentPreRun: func(_ *cobra.Command, _ []string) {
log.SetFlags(0)
if quietFlag {
log.SetOutput(io.Discard)
}
},
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
}
log.Println(GrayStyle.Render("File: " + args[0]))
} else {
stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) != 0 {
// The user ran vhs without any arguments or stdin.
// Print the usage.
return cmd.Help()
}
}
input, err := io.ReadAll(in)
if err != nil {
return err
}
if string(input) == "" {
return errors.New("no input provided")
}
var publishFile string
out := cmd.OutOrStdout()
if quietFlag {
out = io.Discard
}
errs := Evaluate(cmd.Context(), string(input), out, func(v *VHS) {
// Output is being overridden, prevent all outputs
if len(*outputs) <= 0 {
publishFile = v.Options.Video.Output.GIF
return
}
for _, output := range *outputs {
if strings.HasSuffix(output, gif) {
v.Options.Video.Output.GIF = output
} else if strings.HasSuffix(output, webm) {
v.Options.Video.Output.WebM = output
} else if strings.HasSuffix(output, mp4) {
v.Options.Video.Output.MP4 = output
}
}
publishFile = v.Options.Video.Output.GIF
})
publishEnv, publishEnvSet := os.LookupEnv("VHS_PUBLISH")
if !publishEnvSet && !publishFlag && len(errs) == 0 {
log.Println(FaintStyle.Render("Host your GIF on vhs.charm.sh: vhs publish <file>.gif"))
}
if len(errs) > 0 {
printErrors(os.Stderr, string(input), errs)
return errors.New("recording failed")
}
if (publishFlag || publishEnv == "true") && publishFile != "" {
if isatty.IsTerminal(os.Stdout.Fd()) {
log.Printf(GrayStyle.Render("Publishing %s... "), publishFile)
}
url, err := Publish(cmd.Context(), publishFile)
if err != nil {
return err
}
if quietFlag {
cmd.Println(url)
return nil
}
if isatty.IsTerminal(os.Stdout.Fd()) {
log.Println(StringStyle.Render("Done!"))
publishShareInstructions(url)
}
log.Println(" " + URLStyle.Render(url))
if isatty.IsTerminal(os.Stdout.Fd()) {
log.Println()
}
}
return nil
},
}
markdown bool
themesCmd = &cobra.Command{
Use: "themes",
Short: "List all the available themes, one per line",
Args: cobra.NoArgs,
RunE: func(_ *cobra.Command, _ []string) error {
var prefix, suffix string
if markdown {
log.Printf("# Themes\n\n")
prefix, suffix = "* `", "`"
}
themes, err := sortedThemeNames()
if err != nil {
return err
}
for _, theme := range themes {
log.Printf("%s%s%s\n", prefix, theme, suffix)
}
return nil
},
}
shell string
recordCmd = &cobra.Command{
Use: "record",
Short: "Create a new tape file by recording your actions",
Args: cobra.NoArgs,
RunE: Record,
}
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(_ *cobra.Command, args []string) error {
name := strings.TrimSuffix(args[0], extension)
fileName := name + extension
f, err := os.Create(fileName)
if err != nil {
return err
}
_, err = f.Write(bytes.Replace(DemoTape, []byte("examples/demo.gif"), []byte(name+".gif"), 1))
if err != nil {
return err
}
log.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(_ *cobra.Command, args []string) error {
valid := true
for _, file := range args {
b, err := os.ReadFile(file)
if err != nil {
continue
}
l := lexer.New(string(b))
p := parser.New(l)
_ = p.Parse()
errs := p.Errors()
if len(errs) != 0 {
log.Println(ErrorFileStyle.Render(file))
for _, err := range errs {
printError(os.Stderr, string(b), err)
}
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() {
rootCmd.Flags().BoolVarP(&publishFlag, "publish", "p", false, "publish your GIF to vhs.charm.sh and get a shareable URL")
rootCmd.PersistentFlags().BoolVarP(&quietFlag, "quiet", "q", false, "quiet do not log messages. If publish flag is provided, it will log shareable URL")
outputs = rootCmd.Flags().StringSliceP("output", "o", []string{}, "file name(s) of video output")
themesCmd.Flags().BoolVar(&markdown, "markdown", false, "output as markdown")
_ = themesCmd.Flags().MarkHidden("markdown")
recordShell := filepath.Base(os.Getenv("SHELL"))
if recordShell == "" {
recordShell = defaultShell
}
recordCmd.Flags().StringVarP(&shell, "shell", "s", recordShell, "shell for recording")
rootCmd.AddCommand(
recordCmd,
newCmd,
themesCmd,
validateCmd,
manCmd,
serveCmd,
publishCmd,
)
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")
}
_, shellErr := exec.LookPath(defaultShell)
if shellErr != nil {
return fmt.Errorf("%v is not installed", defaultShell)
}
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
}