Skip to content

Commit

Permalink
style: fix linter errors
Browse files Browse the repository at this point in the history
  • Loading branch information
MrMarble committed May 4, 2022
1 parent 7a9ffd7 commit 6bb225f
Show file tree
Hide file tree
Showing 11 changed files with 174 additions and 97 deletions.
46 changes: 46 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
linters:
enable:
- asciicheck
- bidichk
- containedctx
- contextcheck
- gocognit
- decorder
- dupl
- durationcheck
- errchkjson
- errname
- errorlint
- funlen
- goimports
- gci
- goconst
- gofumpt
- gomnd
- gosec
- lll
- misspell
- revive
- unconvert
- wsl
- gosec
- gocritic

linters-settings:
errcheck:
# report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`.
check-blank: true
gosimple:
# Select the Go version to target.
go: "1.18"
# https://staticcheck.io/docs/options#checks
checks: ["all"]
govet:
check-shadowing: true
staticcheck:
go: "1.18"
# https://staticcheck.io/docs/options#checks
checks: ["all"]
decorder:
disable-dec-order-check: false
disable-init-func-first-check: false
46 changes: 13 additions & 33 deletions cmd/prism/prism.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,84 +3,64 @@ package main
import (
"fmt"
"io/ioutil"
"os"
"strings"

"github.com/alecthomas/kong"
"github.com/mrmarble/prism"
"github.com/mrmarble/prism/themer"
"github.com/mrmarble/prism/tokenizer/languages"

"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)

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 image" type:"path"`
Output string `name:"output" short:"o" help:"output image" type:"path" default:"prism.png"`

Numbers bool `short:"n" help:"display line numbers"`
Header bool `help:"display header"`

Debug bool `help:"Debug logging"`
}

func init() {
zerolog.SetGlobalLevel(zerolog.InfoLevel)
func main() {
ctx := kong.Parse(&CLI,
kong.UsageOnError(),
kong.Description(fmt.Sprintf(`Create beautiful images of your source code from your terminal.
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr, PartsExclude: []string{"time"}})
}
Supported languages: %s`, strings.Join(languages.List(), ", "))),
)

func main() {
ctx := kong.Parse(&CLI, kong.UsageOnError(), kong.Description(fmt.Sprintf("Create beautiful images of your source code from your command line.\n\nSupported languages: %s", strings.Join(languages.List(), ", "))))
if CLI.Debug {
zerolog.SetGlobalLevel(zerolog.DebugLevel)
}
ctx.FatalIfErrorf(run(ctx))
}

func run(ctx *kong.Context) error {
pr := prism.NewContext()
log.Debug().Msg("Created context")

pr.SetTheme(themer.Dark())
log.Debug().Msg("Theme set")

if lang, ok := languages.Get(CLI.Language); ok {
pr.SetLanguage(lang)
}

log.Debug().Msg("Language set")

code, err := ioutil.ReadFile(CLI.File)
if err != nil {
return err
}
log.Debug().Msg("Code loaded")

options := prism.Options{}

if CLI.Numbers {
options.LineNumbers = true
}

if CLI.Header {
options.Header = true
}
if CLI.Output != "" {
err := pr.SavePNG(string(code), CLI.Output, options)
if err != nil {
return err
}
log.Info().Str("Output", CLI.Output).Msg("Image saved!")
} else {
err := pr.SavePNG(string(code), "prism.png", options)
if err != nil {
return err
}
log.Info().Str("Output", "prism.png").Msg("Image saved!")

err = pr.SavePNG(string(code), CLI.Output, options)
if err != nil {
return err
}

fmt.Printf("Image created at %s\n", CLI.Output)

return nil
}
52 changes: 38 additions & 14 deletions prism.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,17 +38,23 @@ type Options struct {
var firaCode []byte

func NewContext() *Context {
font, _ := parseFontFace(firaCode, 46)
return &Context{points: 46, margin: 50, lineSpacing: 1.25, font: font, theme: themer.Dark()}
points := 46.0
margin := 50
lineSpacing := 1.25
font, _ := parseFontFace(firaCode, points) //nolint

return &Context{points: points, margin: margin, lineSpacing: lineSpacing, font: font, theme: themer.Dark()}
}

func (ctx *Context) SetFontFace(path string, points float64) error {
font, err := loadFontFace(path, points)
if err != nil {
return err
}

ctx.font = font
ctx.points = points

return nil
}

Expand All @@ -70,22 +76,23 @@ func (ctx *Context) SavePNG(code string, output string, options Options) error {
return dc.SavePNG(output)
}

func (ctx *Context) calculate(code string, options Options) (width, height int, horizontalMargin, verticalMargin float64) {
func (ctx *Context) calculate(code string, options Options) (width, height int, hMargin, vMargin float64) {
codeWidth, codeHeight := ctx.measureMultilineString(code)
horizontalMargin = float64(ctx.margin)
verticalMargin = horizontalMargin
hMargin = float64(ctx.margin)
vMargin = hMargin

if options.LineNumbers {
horizontalMargin += ctx.measureString(fmt.Sprint(ctx.lines)) + (horizontalMargin / 2)
hMargin += ctx.measureString(fmt.Sprint(ctx.lines)) + (hMargin / 2) //nolint
}

if options.Header {
verticalMargin += 70
vMargin += 70
}

width = int(codeWidth) + ctx.margin + int(horizontalMargin)
height = int(codeHeight) + ctx.margin + int(verticalMargin)
return width, height, horizontalMargin, verticalMargin
width = int(codeWidth) + ctx.margin + int(hMargin)
height = int(codeHeight) + ctx.margin + int(vMargin)

return width, height, hMargin, vMargin
}

func (ctx *Context) parse(code string, options Options) *gg.Context {
Expand All @@ -107,33 +114,43 @@ func (ctx *Context) parse(code string, options Options) *gg.Context {
dc.SetFontFace(ctx.font)

if options.Header {
radius := 15.0

colors := [3]string{"#ff5f58", "#ffbd2e", "#18c132"}
for i, color := range colors {
dc.DrawCircle(float64(ctx.margin*(i+1)), float64(ctx.margin), 15)
dc.DrawCircle(float64(ctx.margin*(i+1)), float64(ctx.margin), radius)
dc.SetHexColor(color)
dc.Fill()
}
}

if options.LineNumbers {
pad := int(math.Log10(float64(ctx.lines)) + 1)

for i := 0; i < ctx.lines; i++ {
dc.SetHexColor(ctx.theme[tokenizer.COMMENT])
dc.DrawString(fmt.Sprintf("%*d", pad, i+1), float64(ctx.margin), vMargin+ctx.points+((ctx.points*ctx.lineSpacing)*float64(i)))

x := float64(ctx.margin)
y := vMargin + ctx.points + ((ctx.points * ctx.lineSpacing) * float64(i))
dc.DrawString(fmt.Sprintf("%*d", pad, i+1), x, y)
}
}

// tokens
tokens := tokenizer.Tokenize(code, ctx.lang)

runeWidth := ctx.measureString(" ") // rethink this for variable-width fonts

for _, token := range tokens {
color := ctx.theme.GetColor(token)
dc.SetHexColor(color)

x := hMargin + float64(token.Col)*runeWidth
y := vMargin + ctx.points + ((ctx.points * ctx.lineSpacing) * float64(token.Line))

dc.DrawString(token.Content, x, y)
}

return dc
}

Expand All @@ -151,7 +168,8 @@ func (ctx *Context) measureMultilineString(s string) (width, height float64) {
// max width from lines
for _, line := range lines {
adv := d.MeasureString(line)
currentWidth := float64(adv >> 6) // from gg.Context.MeasureString
currentWidth := float64(adv >> 6) //nolint

if currentWidth > width {
width = currentWidth
}
Expand All @@ -167,15 +185,18 @@ func (ctx *Context) measureString(s string) float64 {
Face: ctx.font,
}
a := d.MeasureString(s)
return float64(a >> 6)

return float64(a >> 6) //nolint
}

func removeAccents(s string) string {
t := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC)
output, _, e := transform.String(t, s)

if e != nil {
panic(e)
}

return output
}

Expand All @@ -184,6 +205,7 @@ func loadFontFace(path string, points float64) (font.Face, error) {
if err != nil {
return nil, err
}

return parseFontFace(fontBytes, points)
}

Expand All @@ -192,9 +214,11 @@ func parseFontFace(fontBytes []byte, points float64) (font.Face, error) {
if err != nil {
return nil, err
}

face := truetype.NewFace(f, &truetype.Options{
Size: points,
// Hinting: font.HintingFull,
})

return face, nil
}
2 changes: 2 additions & 0 deletions prism_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@ func BenchmarkEncodePNG(b *testing.B) {
ctx := prism.NewContext()
lang, _ := languages.Get("golang")
ctx.SetLanguage(lang)

for i := 0; i < b.N; i++ {
var buf bytes.Buffer

err := ctx.EncodePNG(code, &buf, prism.Options{})
if err != nil {
b.Fatal()
Expand Down
36 changes: 0 additions & 36 deletions themer/dark.css

This file was deleted.

Loading

0 comments on commit 6bb225f

Please sign in to comment.