forked from charmbracelet/freeze
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
457 lines (390 loc) · 11.8 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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
package main
import (
"bytes"
"errors"
"fmt"
"os"
"path/filepath"
"runtime/debug"
"strings"
"github.com/alecthomas/chroma/v2"
formatter "github.com/alecthomas/chroma/v2/formatters/svg"
"github.com/alecthomas/chroma/v2/lexers"
"github.com/alecthomas/chroma/v2/styles"
"github.com/alecthomas/kong"
"github.com/beevik/etree"
in "github.com/charmbracelet/freeze/input"
"github.com/charmbracelet/freeze/svg"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/log"
"github.com/charmbracelet/x/ansi"
"github.com/charmbracelet/x/ansi/parser"
"github.com/mattn/go-isatty"
"github.com/muesli/reflow/wordwrap"
)
const (
defaultFontSize = 14.0
defaultLineHeight = 1.2
)
var (
// Version contains the application version number. It's set via ldflags
// when building.
Version = ""
// CommitSHA contains the SHA of the commit that this application was built
// against. It's set via ldflags when building.
CommitSHA = ""
)
func main() {
const shaLen = 7
var (
input string
err error
lexer chroma.Lexer
config Config
scale float64
)
k, err := kong.New(&config, kong.Help(helpPrinter))
if err != nil {
printErrorFatal("Something went wrong", err)
}
ctx, err := k.Parse(os.Args[1:])
if err != nil || ctx.Error != nil {
printErrorFatal("Invalid Usage", err)
}
//nolint: nestif
if len(ctx.Args) > 0 {
switch ctx.Args[0] {
case "version":
if Version == "" {
if info, ok := debug.ReadBuildInfo(); ok && info.Main.Sum != "" {
Version = info.Main.Version
} else {
Version = "unknown (built from source)"
}
}
version := fmt.Sprintf("freeze version %s", Version)
if len(CommitSHA) >= shaLen {
version += " (" + CommitSHA[:shaLen] + ")"
}
fmt.Println(version)
os.Exit(0)
}
}
// Copy the pty output to buffer
if config.Execute != "" {
input, err = executeCommand(config)
if err != nil {
printErrorFatal("Something went wrong", err)
}
if input == "" {
printErrorFatal("Something went wrong", errors.New("no command output"))
}
}
isDefaultConfig := config.Config == "default"
configFile, err := configs.Open("configurations/" + config.Config + ".json")
if config.Config == "user" {
configFile, err = loadUserConfig()
}
if err != nil {
configFile, err = os.Open(config.Config)
}
if err != nil {
configFile, _ = configs.Open("configurations/base.json")
}
r, err := kong.JSON(configFile)
if err != nil {
printErrorFatal("Invalid JSON", err)
}
k, err = kong.New(&config, kong.Help(helpPrinter), kong.Resolvers(r))
if err != nil {
printErrorFatal("Something went wrong", err)
}
ctx, err = k.Parse(os.Args[1:])
if err != nil {
printErrorFatal("Invalid Usage", err)
}
if config.Interactive {
cfg, interactiveErr := runForm(&config)
config = *cfg
if interactiveErr != nil {
printErrorFatal("", interactiveErr)
}
if isDefaultConfig {
_ = saveUserConfig(*cfg)
}
}
autoHeight := config.Height == 0
autoWidth := config.Width == 0
if config.Output == "" {
config.Output = defaultOutputFilename
}
scale = 1
if autoHeight && autoWidth && strings.HasSuffix(config.Output, ".png") {
scale = 4
}
config.Margin = expandMargin(config.Margin, scale)
config.Padding = expandPadding(config.Padding, scale)
if config.Input == "" && !in.IsPipe(os.Stdin) && len(ctx.Args) <= 0 {
_ = helpPrinter(kong.HelpOptions{}, ctx)
os.Exit(0)
}
if config.Input == "-" || in.IsPipe(os.Stdin) {
input, err = in.ReadInput(os.Stdin)
lexer = lexers.Analyse(input)
} else if config.Execute != "" {
config.Language = "ansi"
} else {
input, err = in.ReadFile(config.Input)
if err != nil {
printErrorFatal("File not found", err)
}
lexer = lexers.Get(config.Input)
}
if config.Language != "" {
lexer = lexers.Get(config.Language)
}
// adjust for 1-indexing
for i := range config.Lines {
config.Lines[i]--
}
var strippedInput string = ansi.Strip(input)
isAnsi := strings.ToLower(config.Language) == "ansi" || strippedInput != input
strippedInput = cut(strippedInput, config.Lines)
// wrap to character limit.
if config.Wrap > 0 {
strippedInput = wordwrap.String(strippedInput, config.Wrap)
input = wordwrap.String(input, config.Wrap)
}
if !isAnsi && lexer == nil {
printErrorFatal("Language Unknown", errors.New("specify a language with the --language flag"))
}
input = cut(input, config.Lines)
if input == "" {
if err != nil {
printErrorFatal("No input", err)
} else {
printErrorFatal("No input", errors.New("check --lines is within bounds"))
}
}
s, ok := styles.Registry[strings.ToLower(config.Theme)]
if s == nil || !ok {
s = charmStyle
}
if !s.Has(chroma.Background) {
s, err = s.Builder().Add(chroma.Background, "bg:"+config.Background).Build()
if err != nil {
printErrorFatal("Could not add background", err)
}
}
// Create a token iterator.
var it chroma.Iterator
if isAnsi {
// For ANSI output, we'll inject our own SVG. For now, let's just strip the ANSI
// codes and print the text to properly size the input.
it = chroma.Literator(chroma.Token{Type: chroma.Text, Value: strippedInput})
} else {
it, err = chroma.Coalesce(lexer).Tokenise(nil, input)
if err != nil {
printErrorFatal("Could not lex file", err)
}
}
// Format the code to an SVG.
options, err := fontOptions(&config)
if err != nil {
printErrorFatal("Invalid font options", err)
}
f := formatter.New(options...)
if err != nil {
printErrorFatal("Malformed text", err)
}
buf := &bytes.Buffer{}
err = f.Format(buf, s, it)
if err != nil {
log.Fatal(err)
}
// Parse SVG (XML document)
doc := etree.NewDocument()
_, err = doc.ReadFrom(buf)
if err != nil {
printErrorFatal("Bad SVG", err)
}
elements := doc.ChildElements()
if len(elements) < 1 {
printErrorFatal("Bad Output", nil)
}
image := elements[0]
hPadding := config.Padding[left] + config.Padding[right]
hMargin := config.Margin[left] + config.Margin[right]
vMargin := config.Margin[top] + config.Margin[bottom]
vPadding := config.Padding[top] + config.Padding[bottom]
terminal := image.SelectElement("rect")
w, h := svg.GetDimensions(image)
imageWidth := float64(w)
imageHeight := float64(h)
imageWidth *= scale
imageHeight *= scale
// chroma automatically calculates the height based on a font size of 14
// and a line height of 1.2
imageHeight *= (config.Font.Size / defaultFontSize)
imageHeight *= (config.LineHeight / defaultLineHeight)
terminalWidth := imageWidth
terminalHeight := imageHeight
if !autoWidth {
imageWidth = config.Width
terminalWidth = config.Width - hMargin
} else {
imageWidth += hMargin + hPadding
terminalWidth += hPadding
}
if !autoHeight {
imageHeight = config.Height
terminalHeight = config.Height - vMargin
} else {
imageHeight += vMargin + vPadding
terminalHeight += vPadding
}
if config.Window {
windowControls := svg.NewWindowControls(5.5*float64(scale), 19.0*scale, 12.0*scale)
svg.Move(windowControls, float64(config.Margin[left]), float64(config.Margin[top]))
image.AddChild(windowControls)
config.Padding[top] += (15 * scale)
}
if config.Border.Radius > 0 {
svg.AddCornerRadius(terminal, config.Border.Radius*scale)
}
if config.Shadow.Blur > 0 || config.Shadow.X > 0 || config.Shadow.Y > 0 {
id := "shadow"
svg.AddShadow(image, id, config.Shadow.X*scale, config.Shadow.Y*scale, config.Shadow.Blur*scale)
terminal.CreateAttr("filter", fmt.Sprintf("url(#%s)", id))
}
textGroup := image.SelectElement("g")
textGroup.CreateAttr("font-size", fmt.Sprintf("%.2fpx", config.Font.Size*float64(scale)))
textGroup.CreateAttr("clip-path", "url(#terminalMask)")
text := textGroup.SelectElements("text")
d := dispatcher{lines: text, svg: textGroup, config: &config, scale: scale}
offsetLine := 0
if len(config.Lines) > 0 {
offsetLine = config.Lines[0]
}
config.LineHeight *= float64(scale)
for i, line := range text {
if isAnsi {
line.SetText("")
}
// Offset the text by padding...
// (x, y) -> (x+p, y+p)
if config.ShowLineNumbers {
ln := etree.NewElement("tspan")
ln.CreateAttr("xml:space", "preserve")
ln.CreateAttr("fill", s.Get(chroma.LineNumbers).Colour.String())
ln.SetText(fmt.Sprintf("%3d ", i+1+offsetLine))
line.InsertChildAt(0, ln)
}
x := float64(config.Padding[left] + config.Margin[left])
y := (float64(i+1))*(config.Font.Size*config.LineHeight) + float64(config.Padding[top]) + float64(config.Margin[top])
svg.Move(line, x, y)
// We are passed visible lines, remove the rest.
if y > float64(imageHeight-config.Margin[bottom]-config.Padding[bottom]) {
textGroup.RemoveChild(line)
}
}
if autoWidth {
tabWidth := 4
if isAnsi {
tabWidth = 6
}
longestLine := lipgloss.Width(strings.ReplaceAll(strippedInput, "\t", strings.Repeat(" ", tabWidth)))
terminalWidth = float64(longestLine+1) * (config.Font.Size / fontHeightToWidthRatio)
terminalWidth *= scale
terminalWidth += hPadding
imageWidth = terminalWidth + hMargin
}
if config.Border.Width > 0 {
svg.AddOutline(terminal, config.Border.Width, config.Border.Color)
// NOTE: necessary so that we don't clip the outline.
terminalHeight -= (config.Border.Width * 2)
terminalWidth -= (config.Border.Width * 2)
}
if config.ShowLineNumbers {
if autoWidth {
terminalWidth += config.Font.Size * 3 * scale
imageWidth += config.Font.Size * 3 * scale
} else {
terminalWidth -= config.Font.Size * 3
}
}
if !autoHeight || !autoWidth {
svg.AddClipPath(image, "terminalMask",
config.Margin[left], config.Margin[top],
terminalWidth, terminalHeight-config.Padding[bottom])
}
svg.Move(terminal, max(float64(config.Margin[left]), float64(config.Border.Width)/2), max(float64(config.Margin[top]), float64(config.Border.Width)/2))
svg.SetDimensions(image, imageWidth, imageHeight)
svg.SetDimensions(terminal, terminalWidth, terminalHeight)
if isAnsi {
parser := ansi.NewParser(parser.MaxParamsSize, 0)
// parser := ansi.Parser{
// Print: d.Print,
// Execute: d.Execute,
// CsiDispatch: d.CsiDispatch,
// }
for _, line := range strings.Split(input, "\n") {
parser.Parse(d.dispatch, []byte(line))
d.Execute(ansi.LF) // simulate a newline
}
}
istty := isatty.IsTerminal(os.Stdout.Fd())
switch {
case strings.HasSuffix(config.Output, ".png"):
// use libsvg conversion.
svgConversionErr := libsvgConvert(doc, imageWidth, imageHeight, config.Output)
if svgConversionErr == nil {
printFilenameOutput(config.Output)
break
}
// could not convert with libsvg, try resvg
svgConversionErr = resvgConvert(doc, imageWidth, imageHeight, config.Output)
if svgConversionErr != nil {
printErrorFatal("Unable to convert SVG to PNG", svgConversionErr)
}
printFilenameOutput(config.Output)
default:
// output file specified.
if config.Output != "" {
err = doc.WriteToFile(config.Output)
if err != nil {
printErrorFatal("Unable to write output", err)
}
printFilenameOutput(config.Output)
return
}
// reading from stdin.
if config.Input == "" || config.Input == "-" {
if istty {
err = doc.WriteToFile(defaultOutputFilename)
printFilenameOutput(defaultOutputFilename)
} else {
_, err = doc.WriteTo(os.Stdout)
}
if err != nil {
printErrorFatal("Unable to write output", err)
}
return
}
// reading from file.
if istty {
config.Output = strings.TrimSuffix(filepath.Base(config.Input), filepath.Ext(config.Input)) + ".svg"
err = doc.WriteToFile(config.Output)
printFilenameOutput(config.Output)
} else {
_, err = doc.WriteTo(os.Stdout)
}
if err != nil {
printErrorFatal("Unable to write output", err)
}
}
}
var outputHeader = lipgloss.NewStyle().Foreground(lipgloss.Color("#F1F1F1")).Background(lipgloss.Color("#6C50FF")).Bold(true).Padding(0, 1).MarginRight(1).SetString("WROTE")
func printFilenameOutput(filename string) {
fmt.Println(lipgloss.JoinHorizontal(lipgloss.Center, outputHeader.String(), filename))
}