-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prism.go
105 lines (80 loc) · 2.26 KB
/
prism.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
package main
import (
"fmt"
"io/ioutil"
"strings"
"github.com/alecthomas/kong"
"github.com/mrmarble/prism"
"github.com/mrmarble/prism/themer"
"github.com/mrmarble/prism/tokenizer/languages"
)
type VersionFlag string
var (
// Populated by goreleaser during build
version = "master"
commit = "?"
date = ""
)
var CLI struct {
File string `arg:"" type:"existingfile" help:"File with code"`
Language string `name:"lang" short:"l" help:"Language to parse." required:""`
Output string `name:"output" short:"o" help:"Output file name" type:"path" default:"prism.png"`
Version VersionFlag `name:"version" help:"Print version information and quit"`
Header bool `help:"Display header"`
Lines string `help:"Specify a range of lines instead of reading the whole file. Ex: 10-20"`
Numbers bool `short:"n" help:"Display line numbers"`
Relative bool `short:"r" help:"Use relative numbers. Needs --lines and --numbers"`
}
func (v VersionFlag) Decode(ctx *kong.DecodeContext) error { return nil }
func (v VersionFlag) IsBool() bool { return true }
func (v VersionFlag) BeforeApply(app *kong.Kong) error {
fmt.Printf("Prism has version %s built from %s on %s\n", version, commit, date)
app.Exit(0)
return nil
}
func main() {
ctx := kong.Parse(&CLI,
kong.Name("prism"),
kong.UsageOnError(),
kong.Description(fmt.Sprintf(`Create beautiful images of your source code from your terminal.
Supported languages: %s`, strings.Join(languages.List(), ", "))),
)
ctx.FatalIfErrorf(run(ctx))
}
func run(ctx *kong.Context) error {
pr := prism.NewContext()
pr.SetTheme(themer.Dark())
if lang, ok := languages.Get(CLI.Language); ok {
pr.SetLanguage(lang)
} else {
return fmt.Errorf("Invalid language")
}
code, err := ioutil.ReadFile(CLI.File)
if err != nil {
return err
}
options := prism.Options{}
if CLI.Numbers {
options.LineNumbers = true
}
if CLI.Header {
options.Header = true
}
if CLI.Lines != "" {
r := prism.Range{}
err = r.Parse(CLI.Lines)
if err != nil {
return err
}
options.Range = r
}
if CLI.Relative {
options.Relative = true
}
err = pr.SavePNG(string(code), CLI.Output, options)
if err != nil {
return err
}
fmt.Printf("Image created at %s\n", CLI.Output)
return nil
}