Typo fix and missed dependencies files.

master
Stanislav Nikitin 2 years ago
parent a2a21482e2
commit 7f04a9a7bb
Signed by: pztrn
GPG Key ID: 1E944A0F0568B550

1
.gitignore vendored

@ -2,4 +2,5 @@ examples/fastpastebin.yaml
dist/
data/
.idea
.vscode
*DS_Store*

@ -103,7 +103,7 @@ func pastePOSTWebInterface(ec echo.Context) error {
}
keepForUnitRaw := keepForUnitRegex.FindAllString(params["paste-keep-for"][0], 1)[0]
keepForUnit = structs.PasteKeepsCorellation[keepForUnitRaw]
keepForUnit = structs.PasteKeepsCorrelation[keepForUnitRaw]
}
paste.KeepFor = keepFor

@ -45,15 +45,13 @@ const (
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
)
var (
PasteKeepsCorellation = map[string]int{
"M": PasteKeepForMinutes,
"h": PasteKeepForHours,
"d": PasteKeepForDays,
"m": PasteKeepForMonths,
"forever": PasteKeepForever,
}
)
var PasteKeepsCorrelation = map[string]int{
"M": PasteKeepForMinutes,
"h": PasteKeepForHours,
"d": PasteKeepForDays,
"m": PasteKeepForMonths,
"forever": PasteKeepForever,
}
// Paste represents paste itself.
type Paste struct {

@ -0,0 +1,19 @@
.PHONY: chromad upload all
all: README.md tokentype_string.go
README.md: lexers/*/*.go
./table.py
tokentype_string.go: types.go
go generate
chromad:
(cd ./cmd/chromad && go get github.com/GeertJohan/go.rice/rice@master && go install github.com/GeertJohan/go.rice/rice)
rm -f chromad
(export CGOENABLED=0 GOOS=linux ; cd ./cmd/chromad && go build -o ../../chromad .)
rice append -i ./cmd/chromad --exec=./chromad
upload: chromad
scp chromad root@swapoff.org: && \
ssh root@swapoff.org 'install -m755 ./chromad /srv/http/swapoff.org/bin && service chromad restart'

File diff suppressed because one or more lines are too long

@ -0,0 +1,222 @@
// Package svg contains an SVG formatter.
package svg
import (
"encoding/base64"
"errors"
"fmt"
"io"
"io/ioutil"
"path"
"strings"
"github.com/alecthomas/chroma"
)
// Option sets an option of the SVG formatter.
type Option func(f *Formatter)
// FontFamily sets the font-family.
func FontFamily(fontFamily string) Option { return func(f *Formatter) { f.fontFamily = fontFamily } }
// EmbedFontFile embeds given font file
func EmbedFontFile(fontFamily string, fileName string) (option Option, err error) {
var format FontFormat
switch path.Ext(fileName) {
case ".woff":
format = WOFF
case ".woff2":
format = WOFF2
case ".ttf":
format = TRUETYPE
default:
return nil, errors.New("unexpected font file suffix")
}
var content []byte
if content, err = ioutil.ReadFile(fileName); err == nil {
option = EmbedFont(fontFamily, base64.StdEncoding.EncodeToString(content), format)
}
return
}
// EmbedFont embeds given base64 encoded font
func EmbedFont(fontFamily string, font string, format FontFormat) Option {
return func(f *Formatter) { f.fontFamily = fontFamily; f.embeddedFont = font; f.fontFormat = format }
}
// New SVG formatter.
func New(options ...Option) *Formatter {
f := &Formatter{fontFamily: "Consolas, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace"}
for _, option := range options {
option(f)
}
return f
}
// Formatter that generates SVG.
type Formatter struct {
fontFamily string
embeddedFont string
fontFormat FontFormat
}
func (f *Formatter) Format(w io.Writer, style *chroma.Style, iterator chroma.Iterator) (err error) {
f.writeSVG(w, style, iterator.Tokens())
return err
}
var svgEscaper = strings.NewReplacer(
`&`, "&",
`<`, "&lt;",
`>`, "&gt;",
`"`, "&quot;",
` `, "&#160;",
` `, "&#160;&#160;&#160;&#160;",
)
// EscapeString escapes special characters.
func escapeString(s string) string {
return svgEscaper.Replace(s)
}
func (f *Formatter) writeSVG(w io.Writer, style *chroma.Style, tokens []chroma.Token) { // nolint: gocyclo
svgStyles := f.styleToSVG(style)
lines := chroma.SplitTokensIntoLines(tokens)
fmt.Fprint(w, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
fmt.Fprint(w, "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\" \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n")
fmt.Fprintf(w, "<svg width=\"%dpx\" height=\"%dpx\" xmlns=\"http://www.w3.org/2000/svg\">\n", 8*maxLineWidth(lines), 10+int(16.8*float64(len(lines)+1)))
if f.embeddedFont != "" {
f.writeFontStyle(w)
}
fmt.Fprintf(w, "<rect width=\"100%%\" height=\"100%%\" fill=\"%s\"/>\n", style.Get(chroma.Background).Background.String())
fmt.Fprintf(w, "<g font-family=\"%s\" font-size=\"14px\" fill=\"%s\">\n", f.fontFamily, style.Get(chroma.Text).Colour.String())
f.writeTokenBackgrounds(w, lines, style)
for index, tokens := range lines {
fmt.Fprintf(w, "<text x=\"0\" y=\"%fem\" xml:space=\"preserve\">", 1.2*float64(index+1))
for _, token := range tokens {
text := escapeString(token.String())
attr := f.styleAttr(svgStyles, token.Type)
if attr != "" {
text = fmt.Sprintf("<tspan %s>%s</tspan>", attr, text)
}
fmt.Fprint(w, text)
}
fmt.Fprint(w, "</text>")
}
fmt.Fprint(w, "\n</g>\n")
fmt.Fprint(w, "</svg>\n")
}
func maxLineWidth(lines [][]chroma.Token) int {
maxWidth := 0
for _, tokens := range lines {
length := 0
for _, token := range tokens {
length += len(strings.Replace(token.String(), ` `, " ", -1))
}
if length > maxWidth {
maxWidth = length
}
}
return maxWidth
}
// There is no background attribute for text in SVG so simply calculate the position and text
// of tokens with a background color that differs from the default and add a rectangle for each before
// adding the token.
func (f *Formatter) writeTokenBackgrounds(w io.Writer, lines [][]chroma.Token, style *chroma.Style) {
for index, tokens := range lines {
lineLength := 0
for _, token := range tokens {
length := len(strings.Replace(token.String(), ` `, " ", -1))
tokenBackground := style.Get(token.Type).Background
if tokenBackground.IsSet() && tokenBackground != style.Get(chroma.Background).Background {
fmt.Fprintf(w, "<rect id=\"%s\" x=\"%dch\" y=\"%fem\" width=\"%dch\" height=\"1.2em\" fill=\"%s\" />\n", escapeString(token.String()), lineLength, 1.2*float64(index)+0.25, length, style.Get(token.Type).Background.String())
}
lineLength += length
}
}
}
type FontFormat int
// https://transfonter.org/formats
const (
WOFF FontFormat = iota
WOFF2
TRUETYPE
)
var fontFormats = [...]string{
"woff",
"woff2",
"truetype",
}
func (f *Formatter) writeFontStyle(w io.Writer) {
fmt.Fprintf(w, `<style>
@font-face {
font-family: '%s';
src: url(data:application/x-font-%s;charset=utf-8;base64,%s) format('%s');'
font-weight: normal;
font-style: normal;
}
</style>`, f.fontFamily, fontFormats[f.fontFormat], f.embeddedFont, fontFormats[f.fontFormat])
}
func (f *Formatter) styleAttr(styles map[chroma.TokenType]string, tt chroma.TokenType) string {
if _, ok := styles[tt]; !ok {
tt = tt.SubCategory()
if _, ok := styles[tt]; !ok {
tt = tt.Category()
if _, ok := styles[tt]; !ok {
return ""
}
}
}
return styles[tt]
}
func (f *Formatter) styleToSVG(style *chroma.Style) map[chroma.TokenType]string {
converted := map[chroma.TokenType]string{}
bg := style.Get(chroma.Background)
// Convert the style.
for t := range chroma.StandardTypes {
entry := style.Get(t)
if t != chroma.Background {
entry = entry.Sub(bg)
}
if entry.IsZero() {
continue
}
converted[t] = StyleEntryToSVG(entry)
}
return converted
}
// StyleEntryToSVG converts a chroma.StyleEntry to SVG attributes.
func StyleEntryToSVG(e chroma.StyleEntry) string {
var styles []string
if e.Colour.IsSet() {
styles = append(styles, "fill=\""+e.Colour.String()+"\"")
}
if e.Bold == chroma.Yes {
styles = append(styles, "font-weight=\"bold\"")
}
if e.Italic == chroma.Yes {
styles = append(styles, "font-style=\"italic\"")
}
if e.Underline == chroma.Yes {
styles = append(styles, "text-decoration=\"underline\"")
}
return strings.Join(styles, " ")
}

@ -0,0 +1,76 @@
package b
import (
. "github.com/alecthomas/chroma" // nolint
"github.com/alecthomas/chroma/lexers/internal"
)
// Bibtex lexer.
var Bibtex = internal.Register(MustNewLexer(
&Config{
Name: "BibTeX",
Aliases: []string{"bib", "bibtex"},
Filenames: []string{"*.bib"},
MimeTypes: []string{"text/x-bibtex"},
NotMultiline: true,
CaseInsensitive: true,
},
Rules{
"root": {
Include("whitespace"),
{`@comment`, Comment, nil},
{`@preamble`, NameClass, Push("closing-brace", "value", "opening-brace")},
{`@string`, NameClass, Push("closing-brace", "field", "opening-brace")},
{"@[a-z_@!$&*+\\-./:;<>?\\[\\\\\\]^`|~][\\w@!$&*+\\-./:;<>?\\[\\\\\\]^`|~]*", NameClass, Push("closing-brace", "command-body", "opening-brace")},
{`.+`, Comment, nil},
},
"opening-brace": {
Include("whitespace"),
{`[{(]`, Punctuation, Pop(1)},
},
"closing-brace": {
Include("whitespace"),
{`[})]`, Punctuation, Pop(1)},
},
"command-body": {
Include("whitespace"),
{`[^\s\,\}]+`, NameLabel, Push("#pop", "fields")},
},
"fields": {
Include("whitespace"),
{`,`, Punctuation, Push("field")},
Default(Pop(1)),
},
"field": {
Include("whitespace"),
{"[a-z_@!$&*+\\-./:;<>?\\[\\\\\\]^`|~][\\w@!$&*+\\-./:;<>?\\[\\\\\\]^`|~]*", NameAttribute, Push("value", "=")},
Default(Pop(1)),
},
"=": {
Include("whitespace"),
{`=`, Punctuation, Pop(1)},
},
"value": {
Include("whitespace"),
{"[a-z_@!$&*+\\-./:;<>?\\[\\\\\\]^`|~][\\w@!$&*+\\-./:;<>?\\[\\\\\\]^`|~]*", NameVariable, nil},
{`"`, LiteralString, Push("quoted-string")},
{`\{`, LiteralString, Push("braced-string")},
{`[\d]+`, LiteralNumber, nil},
{`#`, Punctuation, nil},
Default(Pop(1)),
},
"quoted-string": {
{`\{`, LiteralString, Push("braced-string")},
{`"`, LiteralString, Pop(1)},
{`[^\{\"]+`, LiteralString, nil},
},
"braced-string": {
{`\{`, LiteralString, Push()},
{`\}`, LiteralString, Pop(1)},
{`[^\{\}]+`, LiteralString, nil},
},
"whitespace": {
{`\s+`, Text, nil},
},
},
))

@ -0,0 +1,54 @@
package lexers
import (
. "github.com/alecthomas/chroma" // nolint
"github.com/alecthomas/chroma/lexers/internal"
)
// HLB lexer.
var HLB = internal.Register(MustNewLexer(
&Config{
Name: "HLB",
Aliases: []string{"hlb"},
Filenames: []string{"*.hlb"},
MimeTypes: []string{},
},
Rules{
"root": {
{`(#.*)`, ByGroups(CommentSingle), nil},
{`((\b(0(b|B|o|O|x|X)[a-fA-F0-9]+)\b)|(\b(0|[1-9][0-9]*)\b))`, ByGroups(LiteralNumber), nil},
{`((\b(true|false)\b))`, ByGroups(NameBuiltin), nil},
{`(\bstring\b|\bint\b|\bbool\b|\bfs\b|\boption\b)`, ByGroups(KeywordType), nil},
{`(\b[a-zA-Z_][a-zA-Z0-9]*\b)(\()`, ByGroups(NameFunction, Punctuation), Push("params")},
{`(\{)`, ByGroups(Punctuation), Push("block")},
{`(\n|\r|\r\n)`, Text, nil},
{`.`, Text, nil},
},
"string": {
{`"`, LiteralString, Pop(1)},
{`\\"`, LiteralString, nil},
{`[^\\"]+`, LiteralString, nil},
},
"block": {
{`(\})`, ByGroups(Punctuation), Pop(1)},
{`(#.*)`, ByGroups(CommentSingle), nil},
{`((\b(0(b|B|o|O|x|X)[a-fA-F0-9]+)\b)|(\b(0|[1-9][0-9]*)\b))`, ByGroups(LiteralNumber), nil},
{`((\b(true|false)\b))`, ByGroups(KeywordConstant), nil},
{`"`, LiteralString, Push("string")},
{`(with)`, ByGroups(KeywordReserved), nil},
{`(as)([\t ]+)(\b[a-zA-Z_][a-zA-Z0-9]*\b)`, ByGroups(KeywordReserved, Text, NameFunction), nil},
{`(\bstring\b|\bint\b|\bbool\b|\bfs\b|\boption\b)([\t ]+)(\{)`, ByGroups(KeywordType, Text, Punctuation), Push("block")},
{`(?!\b(?:scratch|image|resolve|http|checksum|chmod|filename|git|keepGitDir|local|includePatterns|excludePatterns|followPaths|generate|frontendInput|shell|run|readonlyRootfs|env|dir|user|network|security|host|ssh|secret|mount|target|localPath|uid|gid|mode|readonly|tmpfs|sourcePath|cache|mkdir|createParents|chown|createdTime|mkfile|rm|allowNotFound|allowWildcards|copy|followSymlinks|contentsOnly|unpack|createDestPath)\b)(\b[a-zA-Z_][a-zA-Z0-9]*\b)`, ByGroups(NameOther), nil},
{`(\n|\r|\r\n)`, Text, nil},
{`.`, Text, nil},
},
"params": {
{`(\))`, ByGroups(Punctuation), Pop(1)},
{`(variadic)`, ByGroups(Keyword), nil},
{`(\bstring\b|\bint\b|\bbool\b|\bfs\b|\boption\b)`, ByGroups(KeywordType), nil},
{`(\b[a-zA-Z_][a-zA-Z0-9]*\b)`, ByGroups(NameOther), nil},
{`(\n|\r|\r\n)`, Text, nil},
{`.`, Text, nil},
},
},
))

@ -0,0 +1,73 @@
package j
import (
. "github.com/alecthomas/chroma" // nolint
"github.com/alecthomas/chroma/lexers/internal"
)
// J lexer.
var J = internal.Register(MustNewLexer(
&Config{
Name: "J",
Aliases: []string{"j"},
Filenames: []string{"*.ijs"},
MimeTypes: []string{"text/x-j"},
},
Rules{
"root": {
{`#!.*$`, CommentPreproc, nil},
{`NB\..*`, CommentSingle, nil},
{`\n+\s*Note`, CommentMultiline, Push("comment")},
{`\s*Note.*`, CommentSingle, nil},
{`\s+`, Text, nil},
{`'`, LiteralString, Push("singlequote")},
{`0\s+:\s*0|noun\s+define\s*$`, NameEntity, Push("nounDefinition")},
{`(([1-4]|13)\s+:\s*0|(adverb|conjunction|dyad|monad|verb)\s+define)\b`, NameFunction, Push("explicitDefinition")},
{Words(``, `\b[a-zA-Z]\w*\.`, `for_`, `goto_`, `label_`), NameLabel, nil},
{Words(``, `\.`, `assert`, `break`, `case`, `catch`, `catchd`, `catcht`, `continue`, `do`, `else`, `elseif`, `end`, `fcase`, `for`, `if`, `return`, `select`, `throw`, `try`, `while`, `whilst`), NameLabel, nil},
{`\b[a-zA-Z]\w*`, NameVariable, nil},
{Words(``, ``, `ARGV`, `CR`, `CRLF`, `DEL`, `Debug`, `EAV`, `EMPTY`, `FF`, `JVERSION`, `LF`, `LF2`, `Note`, `TAB`, `alpha17`, `alpha27`, `apply`, `bind`, `boxopen`, `boxxopen`, `bx`, `clear`, `cutLF`, `cutopen`, `datatype`, `def`, `dfh`, `drop`, `each`, `echo`, `empty`, `erase`, `every`, `evtloop`, `exit`, `expand`, `fetch`, `file2url`, `fixdotdot`, `fliprgb`, `getargs`, `getenv`, `hfd`, `inv`, `inverse`, `iospath`, `isatty`, `isutf8`, `items`, `leaf`, `list`, `nameclass`, `namelist`, `names`, `nc`, `nl`, `on`, `pick`, `rows`, `script`, `scriptd`, `sign`, `sminfo`, `smoutput`, `sort`, `split`, `stderr`, `stdin`, `stdout`, `table`, `take`, `timespacex`, `timex`, `tmoutput`, `toCRLF`, `toHOST`, `toJ`, `tolower`, `toupper`, `type`, `ucp`, `ucpcount`, `usleep`, `utf8`, `uucp`), NameFunction, nil},
{`=[.:]`, Operator, nil},
{"[-=+*#$%@!~`^&\";:.,<>{}\\[\\]\\\\|/]", Operator, nil},
{`[abCdDeEfHiIjLMoprtT]\.`, KeywordReserved, nil},
{`[aDiLpqsStux]\:`, KeywordReserved, nil},
{`(_[0-9])\:`, KeywordConstant, nil},
{`\(`, Punctuation, Push("parentheses")},
Include("numbers"),
},
"comment": {
{`[^)]`, CommentMultiline, nil},
{`^\)`, CommentMultiline, Pop(1)},
{`[)]`, CommentMultiline, nil},
},
"explicitDefinition": {
{`\b[nmuvxy]\b`, NameDecorator, nil},
Include("root"),
{`[^)]`, Name, nil},
{`^\)`, NameLabel, Pop(1)},
{`[)]`, Name, nil},
},
"numbers": {
{`\b_{1,2}\b`, LiteralNumber, nil},
{`_?\d+(\.\d+)?(\s*[ejr]\s*)_?\d+(\.?=\d+)?`, LiteralNumber, nil},
{`_?\d+\.(?=\d+)`, LiteralNumberFloat, nil},
{`_?\d+x`, LiteralNumberIntegerLong, nil},
{`_?\d+`, LiteralNumberInteger, nil},
},
"nounDefinition": {
{`[^)]`, LiteralString, nil},
{`^\)`, NameLabel, Pop(1)},
{`[)]`, LiteralString, nil},
},
"parentheses": {
{`\)`, Punctuation, Pop(1)},
Include("explicitDefinition"),
Include("root"),
},
"singlequote": {
{`[^']`, LiteralString, nil},
{`''`, LiteralString, nil},
{`'`, LiteralString, Pop(1)},
},
},
))

@ -0,0 +1,43 @@
package m
import (
. "github.com/alecthomas/chroma" // nolint
"github.com/alecthomas/chroma/lexers/internal"
)
// MLIR lexer.
var Mlir = internal.Register(MustNewLexer(
&Config{
Name: "MLIR",
Aliases: []string{"mlir"},
Filenames: []string{"*.mlir"},
MimeTypes: []string{"text/x-mlir"},
},
Rules{
"root": {
Include("whitespace"),
{`c?"[^"]*?"`, LiteralString, nil},
{`\^([-a-zA-Z$._][\w\-$.0-9]*)\s*`, NameLabel, nil},
{`([\w\d_$.]+)\s*=`, NameLabel, nil},
Include("keyword"),
{`->`, Punctuation, nil},
{`@([\w_][\w\d_$.]*)`, NameFunction, nil},
{`[%#][\w\d_$.]+`, NameVariable, nil},
{`([1-9?][\d?]*\s*x)+`, LiteralNumber, nil},
{`0[xX][a-fA-F0-9]+`, LiteralNumber, nil},
{`-?\d+(?:[.]\d+)?(?:[eE][-+]?\d+(?:[.]\d+)?)?`, LiteralNumber, nil},
{`[=<>{}\[\]()*.,!:]|x\b`, Punctuation, nil},
{`[\w\d]+`, Text, nil},
},
"whitespace": {
{`(\n|\s)+`, Text, nil},
{`//.*?\n`, Comment, nil},
},
"keyword": {
{Words(``, ``, `constant`, `return`), KeywordType, nil},
{Words(``, ``, `func`, `loc`, `memref`, `tensor`, `vector`), KeywordType, nil},
{`bf16|f16|f32|f64|index`, Keyword, nil},
{`i[1-9]\d*`, Keyword, nil},
},
},
))

@ -0,0 +1,94 @@
package s
import (
. "github.com/alecthomas/chroma" // nolint
"github.com/alecthomas/chroma/lexers/internal"
)
// Sas lexer.
var Sas = internal.Register(MustNewLexer(
&Config{
Name: "SAS",
Aliases: []string{"sas"},
Filenames: []string{"*.SAS", "*.sas"},
MimeTypes: []string{"text/x-sas", "text/sas", "application/x-sas"},
CaseInsensitive: true,
},
Rules{
"root": {
Include("comments"),
Include("proc-data"),
Include("cards-datalines"),
Include("logs"),
Include("general"),
{`.`, Text, nil},
{`\\\n`, Text, nil},
{`\n`, Text, nil},
},
"comments": {
{`^\s*\*.*?;`, Comment, nil},
{`/\*.*?\*/`, Comment, nil},
{`^\s*\*(.|\n)*?;`, CommentMultiline, nil},
{`/[*](.|\n)*?[*]/`, CommentMultiline, nil},
},
"proc-data": {
{`(^|;)\s*(proc \w+|data|run|quit)[\s;]`, KeywordReserved, nil},
},
"cards-datalines": {
{`^\s*(datalines|cards)\s*;\s*$`, Keyword, Push("data")},
},
"data": {
{`(.|\n)*^\s*;\s*$`, Other, Pop(1)},
},
"logs": {
{`\n?^\s*%?put `, Keyword, Push("log-messages")},
},
"log-messages": {
{`NOTE(:|-).*`, Generic, Pop(1)},
{`WARNING(:|-).*`, GenericEmph, Pop(1)},
{`ERROR(:|-).*`, GenericError, Pop(1)},
Include("general"),
},
"general": {
Include("keywords"),
Include("vars-strings"),
Include("special"),
Include("numbers"),
},
"keywords": {
{Words(`\b`, `\b`, `abort`, `array`, `attrib`, `by`, `call`, `cards`, `cards4`, `catname`, `continue`, `datalines`, `datalines4`, `delete`, `delim`, `delimiter`, `display`, `dm`, `drop`, `endsas`, `error`, `file`, `filename`, `footnote`, `format`, `goto`, `in`, `infile`, `informat`, `input`, `keep`, `label`, `leave`, `length`, `libname`, `link`, `list`, `lostcard`, `merge`, `missing`, `modify`, `options`, `output`, `out`, `page`, `put`, `redirect`, `remove`, `rename`, `replace`, `retain`, `return`, `select`, `set`, `skip`, `startsas`, `stop`, `title`, `update`, `waitsas`, `where`, `window`, `x`, `systask`), Keyword, nil},
{Words(`\b`, `\b`, `add`, `and`, `alter`, `as`, `cascade`, `check`, `create`, `delete`, `describe`, `distinct`, `drop`, `foreign`, `from`, `group`, `having`, `index`, `insert`, `into`, `in`, `key`, `like`, `message`, `modify`, `msgtype`, `not`, `null`, `on`, `or`, `order`, `primary`, `references`, `reset`, `restrict`, `select`, `set`, `table`, `unique`, `update`, `validate`, `view`, `where`), Keyword, nil},
{Words(`\b`, `\b`, `do`, `if`, `then`, `else`, `end`, `until`, `while`), Keyword, nil},
{Words(`%`, `\b`, `bquote`, `nrbquote`, `cmpres`, `qcmpres`, `compstor`, `datatyp`, `display`, `do`, `else`, `end`, `eval`, `global`, `goto`, `if`, `index`, `input`, `keydef`, `label`, `left`, `length`, `let`, `local`, `lowcase`, `macro`, `mend`, `nrquote`, `nrstr`, `put`, `qleft`, `qlowcase`, `qscan`, `qsubstr`, `qsysfunc`, `qtrim`, `quote`, `qupcase`, `scan`, `str`, `substr`, `superq`, `syscall`, `sysevalf`, `sysexec`, `sysfunc`, `sysget`, `syslput`, `sysprod`, `sysrc`, `sysrput`, `then`, `to`, `trim`, `unquote`, `until`, `upcase`, `verify`, `while`, `window`), NameBuiltin, nil},
{Words(`\b`, `\(`, `abs`, `addr`, `airy`, `arcos`, `arsin`, `atan`, `attrc`, `attrn`, `band`, `betainv`, `blshift`, `bnot`, `bor`, `brshift`, `bxor`, `byte`, `cdf`, `ceil`, `cexist`, `cinv`, `close`, `cnonct`, `collate`, `compbl`, `compound`, `compress`, `cos`, `cosh`, `css`, `curobs`, `cv`, `daccdb`, `daccdbsl`, `daccsl`, `daccsyd`, `dacctab`, `dairy`, `date`, `datejul`, `datepart`, `datetime`, `day`, `dclose`, `depdb`, `depdbsl`, `depsl`, `depsyd`, `deptab`, `dequote`, `dhms`, `dif`, `digamma`, `dim`, `dinfo`, `dnum`, `dopen`, `doptname`, `doptnum`, `dread`, `dropnote`, `dsname`, `erf`, `erfc`, `exist`, `exp`, `fappend`, `fclose`, `fcol`, `fdelete`, `fetch`, `fetchobs`, `fexist`, `fget`, `fileexist`, `filename`, `fileref`, `finfo`, `finv`, `fipname`, `fipnamel`, `fipstate`, `floor`, `fnonct`, `fnote`, `fopen`, `foptname`, `foptnum`, `fpoint`, `fpos`, `fput`, `fread`, `frewind`, `frlen`, `fsep`, `fuzz`, `fwrite`, `gaminv`, `gamma`, `getoption`, `getvarc`, `getvarn`, `hbound`, `hms`, `hosthelp`, `hour`, `ibessel`, `index`, `indexc`, `indexw`, `input`, `inputc`, `inputn`, `int`, `intck`, `intnx`, `intrr`, `irr`, `jbessel`, `juldate`, `kurtosis`, `lag`, `lbound`, `left`, `length`, `lgamma`, `libname`, `libref`, `log`, `log10`, `log2`, `logpdf`, `logpmf`, `logsdf`, `lowcase`, `max`, `mdy`, `mean`, `min`, `minute`, `mod`, `month`, `mopen`, `mort`, `n`, `netpv`, `nmiss`, `normal`, `note`, `npv`, `open`, `ordinal`, `pathname`, `pdf`, `peek`, `peekc`, `pmf`, `point`, `poisson`, `poke`, `probbeta`, `probbnml`, `probchi`, `probf`, `probgam`, `probhypr`, `probit`, `probnegb`, `probnorm`, `probt`, `put`, `putc`, `putn`, `qtr`, `quote`, `ranbin`, `rancau`, `ranexp`, `rangam`, `range`, `rank`, `rannor`, `ranpoi`, `rantbl`, `rantri`, `ranuni`, `repeat`, `resolve`, `reverse`, `rewind`, `right`, `round`, `saving`, `scan`, `sdf`, `second`, `sign`, `sin`, `sinh`, `skewness`, `soundex`, `spedis`, `sqrt`, `std`, `stderr`, `stfips`, `stname`, `stnamel`, `substr`, `sum`, `symget`, `sysget`, `sysmsg`, `sysprod`, `sysrc`, `system`, `tan`, `tanh`, `time`, `timepart`, `tinv`, `tnonct`, `today`, `translate`, `tranwrd`, `trigamma`, `trim`, `trimn`, `trunc`, `uniform`, `upcase`, `uss`, `var`, `varfmt`, `varinfmt`, `varlabel`, `varlen`, `varname`, `varnum`, `varray`, `varrayx`, `vartype`, `verify`, `vformat`, `vformatd`, `vformatdx`, `vformatn`, `vformatnx`, `vformatw`, `vformatwx`, `vformatx`, `vinarray`, `vinarrayx`, `vinformat`, `vinformatd`, `vinformatdx`, `vinformatn`, `vinformatnx`, `vinformatw`, `vinformatwx`, `vinformatx`, `vlabel`, `vlabelx`, `vlength`, `vlengthx`, `vname`, `vnamex`, `vtype`, `vtypex`, `weekday`, `year`, `yyq`, `zipfips`, `zipname`, `zipnamel`, `zipstate`), NameBuiltin, nil},
},
"vars-strings": {
{`&[a-z_]\w{0,31}\.?`, NameVariable, nil},
{`%[a-z_]\w{0,31}`, NameFunction, nil},
{`\'`, LiteralString, Push("string_squote")},
{`"`, LiteralString, Push("string_dquote")},
},
"string_squote": {
{`'`, LiteralString, Pop(1)},
{`\\\\|\\"|\\\n`, LiteralStringEscape, nil},
{`[^$\'\\]+`, LiteralString, nil},
{`[$\'\\]`, LiteralString, nil},
},
"string_dquote": {
{`"`, LiteralString, Pop(1)},
{`\\\\|\\"|\\\n`, LiteralStringEscape, nil},
{`&`, NameVariable, Push("validvar")},
{`[^$&"\\]+`, LiteralString, nil},
{`[$"\\]`, LiteralString, nil},
},
"validvar": {
{`[a-z_]\w{0,31}\.?`, NameVariable, Pop(1)},
},
"numbers": {
{`\b[+-]?([0-9]+(\.[0-9]+)?|\.[0-9]+|\.)(E[+-]?[0-9]+)?i?\b`, LiteralNumber, nil},
},
"special": {
{`(null|missing|_all_|_automatic_|_character_|_n_|_infile_|_name_|_null_|_numeric_|_user_|_webout_)`, KeywordConstant, nil},
},
},
))

@ -0,0 +1,200 @@
package s
import (
. "github.com/alecthomas/chroma" // nolint
"github.com/alecthomas/chroma/lexers/internal"
)
// Standard ML lexer.
var StandardML = internal.Register(MustNewLexer(
&Config{
Name: "Standard ML",
Aliases: []string{"sml"},
Filenames: []string{"*.sml", "*.sig", "*.fun"},
MimeTypes: []string{"text/x-standardml", "application/x-standardml"},
},
Rules{
"whitespace": {
{`\s+`, Text, nil},
{`\(\*`, CommentMultiline, Push("comment")},
},
"delimiters": {
{`\(|\[|\{`, Punctuation, Push("main")},
{`\)|\]|\}`, Punctuation, Pop(1)},
{`\b(let|if|local)\b(?!\')`, KeywordReserved, Push("main", "main")},
{`\b(struct|sig|while)\b(?!\')`, KeywordReserved, Push("main")},
{`\b(do|else|end|in|then)\b(?!\')`, KeywordReserved, Pop(1)},
},
"core": {
{`(_|\}|\{|\)|;|,|\[|\(|\]|\.\.\.)`, Punctuation, nil},
{`#"`, LiteralStringChar, Push("char")},
{`"`, LiteralStringDouble, Push("string")},
{`~?0x[0-9a-fA-F]+`, LiteralNumberHex, nil},
{`0wx[0-9a-fA-F]+`, LiteralNumberHex, nil},
{`0w\d+`, LiteralNumberInteger, nil},
{`~?\d+\.\d+[eE]~?\d+`, LiteralNumberFloat, nil},
{`~?\d+\.\d+`, LiteralNumberFloat, nil},
{`~?\d+[eE]~?\d+`, LiteralNumberFloat, nil},
{`~?\d+`, LiteralNumberInteger, nil},
{`#\s*[1-9][0-9]*`, NameLabel, nil},
{`#\s*([a-zA-Z][\w']*)`, NameLabel, nil},
{"#\\s+([!%&$#+\\-/:<=>?@\\\\~`^|*]+)", NameLabel, nil},
{`\b(datatype|abstype)\b(?!\')`, KeywordReserved, Push("dname")},
{`(?=\b(exception)\b(?!\'))`, Text, Push("ename")},
{`\b(functor|include|open|signature|structure)\b(?!\')`, KeywordReserved, Push("sname")},
{`\b(type|eqtype)\b(?!\')`, KeywordReserved, Push("tname")},
{`\'[\w\']*`, NameDecorator, nil},
{`([a-zA-Z][\w']*)(\.)`, NameNamespace, Push("dotted")},
{`\b(abstype|and|andalso|as|case|datatype|do|else|end|exception|fn|fun|handle|if|in|infix|infixr|let|local|nonfix|of|op|open|orelse|raise|rec|then|type|val|with|withtype|while|eqtype|functor|include|sharing|sig|signature|struct|structure|where)\b`, KeywordReserved, nil},
{`([a-zA-Z][\w']*)`, Name, nil},
{`\b(:|\|,=|=>|->|#|:>)\b`, KeywordReserved, nil},
{"([!%&$#+\\-/:<=>?@\\\\~`^|*]+)", Name, nil},
},
"dotted": {
{`([a-zA-Z][\w']*)(\.)`, NameNamespace, nil},
// ignoring reserved words
{`([a-zA-Z][\w']*)`, Name, Pop(1)},
// ignoring reserved words
{"([!%&$#+\\-/:<=>?@\\\\~`^|*]+)", Name, Pop(1)},
{`\s+`, Error, nil},
{`\S+`, Error, nil},
},
"root": {
Default(Push("main")),
},
"main": {
Include("whitespace"),
{`\b(val|and)\b(?!\')`, KeywordReserved, Push("vname")},
{`\b(fun)\b(?!\')`, KeywordReserved, Push("#pop", "main-fun", "fname")},
Include("delimiters"),
Include("core"),
{`\S+`, Error, nil},
},
"main-fun": {
Include("whitespace"),
{`\s`, Text, nil},
{`\(\*`, CommentMultiline, Push("comment")},
{`\b(fun|and)\b(?!\')`, KeywordReserved, Push("fname")},
{`\b(val)\b(?!\')`, KeywordReserved, Push("#pop", "main", "vname")},
{`\|`, Punctuation, Push("fname")},
{`\b(case|handle)\b(?!\')`, KeywordReserved, Push("#pop", "main")},
Include("delimiters"),
Include("core"),
{`\S+`, Error, nil},
},
"char": {
{`[^"\\]`, LiteralStringChar, nil},
{`\\[\\"abtnvfr]`, LiteralStringEscape, nil},
{`\\\^[\x40-\x5e]`, LiteralStringEscape, nil},
{`\\[0-9]{3}`, LiteralStringEscape, nil},
{`\\u[0-9a-fA-F]{4}`, LiteralStringEscape, nil},
{`\\\s+\\`, LiteralStringInterpol, nil},
{`"`, LiteralStringChar, Pop(1)},
},
"string": {
{`[^"\\]`, LiteralStringDouble, nil},
{`\\[\\"abtnvfr]`, LiteralStringEscape, nil},
{`\\\^[\x40-\x5e]`, LiteralStringEscape, nil},
{`\\[0-9]{3}`, LiteralStringEscape, nil},
{`\\u[0-9a-fA-F]{4}`, LiteralStringEscape, nil},
{`\\\s+\\`, LiteralStringInterpol, nil},
{`"`, LiteralStringDouble, Pop(1)},
},
"breakout": {
{`(?=\b(where|do|handle|if|sig|op|while|case|as|else|signature|andalso|struct|infixr|functor|in|structure|then|local|rec|end|fun|of|orelse|val|include|fn|with|exception|let|and|infix|sharing|datatype|type|abstype|withtype|eqtype|nonfix|raise|open)\b(?!\'))`, Text, Pop(1)},
},
"sname": {
Include("whitespace"),
Include("breakout"),
{`([a-zA-Z][\w']*)`, NameNamespace, nil},
Default(Pop(1)),
},
"fname": {
Include("whitespace"),
{`\'[\w\']*`, NameDecorator, nil},
{`\(`, Punctuation, Push("tyvarseq")},
{`([a-zA-Z][\w']*)`, NameFunction, Pop(1)},
{"([!%&$#+\\-/:<=>?@\\\\~`^|*]+)", NameFunction, Pop(1)},
Default(Pop(1)),
},
"vname": {
Include("whitespace"),
{`\'[\w\']*`, NameDecorator, nil},
{`\(`, Punctuation, Push("tyvarseq")},
{"([a-zA-Z][\\w']*)(\\s*)(=(?![!%&$#+\\-/:<=>?@\\\\~`^|*]+))", ByGroups(NameVariable, Text, Punctuation), Pop(1)},
{"([!%&$#+\\-/:<=>?@\\\\~`^|*]+)(\\s*)(=(?![!%&$#+\\-/:<=>?@\\\\~`^|*]+))", ByGroups(NameVariable, Text, Punctuation), Pop(1)},
{`([a-zA-Z][\w']*)`, NameVariable, Pop(1)},
{"([!%&$#+\\-/:<=>?@\\\\~`^|*]+)", NameVariable, Pop(1)},
Default(Pop(1)),
},
"tname": {
Include("whitespace"),
Include("breakout"),
{`\'[\w\']*`, NameDecorator, nil},
{`\(`, Punctuation, Push("tyvarseq")},
{"=(?![!%&$#+\\-/:<=>?@\\\\~`^|*]+)", Punctuation, Push("#pop", "typbind")},
{`([a-zA-Z][\w']*)`, KeywordType, nil},
{"([!%&$#+\\-/:<=>?@\\\\~`^|*]+)", KeywordType, nil},
{`\S+`, Error, Pop(1)},
},
"typbind": {
Include("whitespace"),
{`\b(and)\b(?!\')`, KeywordReserved, Push("#pop", "tname")},
Include("breakout"),
Include("core"),
{`\S+`, Error, Pop(1)},
},
"dname": {
Include("whitespace"),
Include("breakout"),
{`\'[\w\']*`, NameDecorator, nil},
{`\(`, Punctuation, Push("tyvarseq")},
{`(=)(\s*)(datatype)`, ByGroups(Punctuation, Text, KeywordReserved), Pop(1)},
{"=(?![!%&$#+\\-/:<=>?@\\\\~`^|*]+)", Punctuation, Push("#pop", "datbind", "datcon")},
{`([a-zA-Z][\w']*)`, KeywordType, nil},
{"([!%&$#+\\-/:<=>?@\\\\~`^|*]+)", KeywordType, nil},
{`\S+`, Error, Pop(1)},
},
"datbind": {
Include("whitespace"),
{`\b(and)\b(?!\')`, KeywordReserved, Push("#pop", "dname")},
{`\b(withtype)\b(?!\')`, KeywordReserved, Push("#pop", "tname")},
{`\b(of)\b(?!\')`, KeywordReserved, nil},
{`(\|)(\s*)([a-zA-Z][\w']*)`, ByGroups(Punctuation, Text, NameClass), nil},
{"(\\|)(\\s+)([!%&$#+\\-/:<=>?@\\\\~`^|*]+)", ByGroups(Punctuation, Text, NameClass), nil},
Include("breakout"),
Include("core"),
{`\S+`, Error, nil},
},
"ename": {
Include("whitespace"),
{`(exception|and)\b(\s+)([a-zA-Z][\w']*)`, ByGroups(KeywordReserved, Text, NameClass), nil},
{"(exception|and)\\b(\\s*)([!%&$#+\\-/:<=>?@\\\\~`^|*]+)", ByGroups(KeywordReserved, Text, NameClass), nil},
{`\b(of)\b(?!\')`, KeywordReserved, nil},
Include("breakout"),
Include("core"),
{`\S+`, Error, nil},
},
"datcon": {
Include("whitespace"),
{`([a-zA-Z][\w']*)`, NameClass, Pop(1)},
{"([!%&$#+\\-/:<=>?@\\\\~`^|*]+)", NameClass, Pop(1)},
{`\S+`, Error, Pop(1)},
},
"tyvarseq": {
{`\s`, Text, nil},
{`\(\*`, CommentMultiline, Push("comment")},
{`\'[\w\']*`, NameDecorator, nil},
{`[a-zA-Z][\w']*`, Name, nil},
{`,`, Punctuation, nil},
{`\)`, Punctuation, Pop(1)},
{"[!%&$#+\\-/:<=>?@\\\\~`^|*]+", Name, nil},
},
"comment": {
{`[^(*)]`, CommentMultiline, nil},
{`\(\*`, CommentMultiline, Push()},
{`\*\)`, CommentMultiline, Pop(1)},
{`[(*)]`, CommentMultiline, nil},
},
},
))

@ -0,0 +1,42 @@
package t
import (
. "github.com/alecthomas/chroma" // nolint
"github.com/alecthomas/chroma/lexers/internal"
)
// TableGen lexer.
var Tablegen = internal.Register(MustNewLexer(
&Config{
Name: "TableGen",
Aliases: []string{"tablegen"},
Filenames: []string{"*.td"},
MimeTypes: []string{"text/x-tablegen"},
},
Rules{
"root": {
Include("macro"),
Include("whitespace"),
{`c?"[^"]*?"`, LiteralString, nil},
Include("keyword"),
{`\$[_a-zA-Z][_\w]*`, NameVariable, nil},
{`\d*[_a-zA-Z][_\w]*`, NameVariable, nil},
{`\[\{[\w\W]*?\}\]`, LiteralString, nil},
{`[+-]?\d+|0x[\da-fA-F]+|0b[01]+`, LiteralNumber, nil},
{`[=<>{}\[\]()*.,!:;]`, Punctuation, nil},
},
"macro": {
{`(#include\s+)("[^"]*")`, ByGroups(CommentPreproc, LiteralString), nil},
{`^\s*#(ifdef|ifndef)\s+[_\w][_\w\d]*`, CommentPreproc, nil},
{`^\s*#define\s+[_\w][_\w\d]*`, CommentPreproc, nil},
{`^\s*#endif`, CommentPreproc, nil},
},
"whitespace": {
{`(\n|\s)+`, Text, nil},
{`//.*?\n`, Comment, nil},
},
"keyword": {
{Words(``, `\b`, `bit`, `bits`, `class`, `code`, `dag`, `def`, `defm`, `field`, `foreach`, `in`, `int`, `let`, `list`, `multiclass`, `string`), Keyword, nil},
},
},
))

@ -0,0 +1,66 @@
---
kind: pipeline
type: docker
name: test-and-lint
steps:
- name: notify-start
image: pztrn/discordrone
when:
instance: ci.dev.pztrn.name
settings:
webhook_id:
from_secret: discord_webhook_id
webhook_token:
from_secret: discord_webhook_secret
message: 'Starting building **{{repo.name}}#{{build.number}}@{{commit.sha}}** @ {{datetime build.started "02-Jan-2006 15:04:05 MST" "Asia/Yekaterinburg"}} (See {{build.link}} for logs).'
- name: lint
image: golangci/golangci-lint:latest
environment:
CGO_ENABLED: "0"
commands:
- golangci-lint run
depends_on:
- notify-start
- name: test-1.14
image: golang:1.14.4-alpine
environment:
CGO_ENABLED: "0"
commands:
- go test -cover -test.v .
depends_on:
- notify-start
- name: test-1.13
image: golang:1.13.12-alpine
environment:
CGO_ENABLED: "0"
commands:
- go test -cover -test.v .
depends_on:
- notify-start
- name: notify-end
when:
instance: ci.dev.pztrn.name
status:
- success
- failure
image: pztrn/discordrone
settings:
webhook_id:
from_secret: discord_webhook_id
webhook_token:
from_secret: discord_webhook_secret
message: "
{{#success build.status}}
**{{repo.name}}#{{build.number}}@{{commit.sha}}** pipeline completed in {{since build.startedint}}.
{{ else }}
**{{repo.name}}#{{build.number}}@{{commit.sha}}** failed. See {{build.link}}.
{{/success}}"
depends_on:
- lint
- test-1.13
- test-1.14

@ -0,0 +1,23 @@
run:
deadline: 5m
linters:
enable-all: true
disable:
# Because globals might exist, but according to our codestyle they
# should be lowercased and considered as unexported.
- gochecknoglobals
# While it might be useful it'll create more problems that will solve.
- gocritic
# Complains about main() lengths, which isn't an issue.
- funlen
linters-settings:
lll:
line-length: 420
gocyclo:
min-complexity: 40
issues:
exclude-rules:
# We do not want to enforce black-box testing.
- path: flagger_test.go
linters:
- testpackage

@ -0,0 +1,7 @@
Copyright 2017-2019, Stanislav N. aka pztrn
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@ -0,0 +1,57 @@
# Flagger
[![GoDoc](https://godoc.org/go.dev.pztrn.name/flagger?status.svg)](https://godoc.org/go.dev.pztrn.name/flagger) [![Drone (self-hosted)](https://img.shields.io/drone/build/libraries/flagger?server=https%3A%2F%2Fci.dev.pztrn.name)](https://ci.dev.pztrn.name/libraries/flagger/) [![Discord](https://img.shields.io/discord/632359730089689128)](https://discord.gg/qHN6KsD) ![Keybase XLM](https://img.shields.io/keybase/xlm/pztrn) [![Go Report Card](https://goreportcard.com/badge/go.dev.pztrn.name/flagger)](https://goreportcard.com/report/go.dev.pztrn.name/flagger)
Flagger is an arbitrary CLI flags parser, like argparse in Python.
Flagger is able to parse boolean, integer and string flags.
## Installation
```bash
go get -u -v go.dev.pztrn.name/flagger
```
## Usage
Flagger requires logging interface to be passed on initialization.
See ``loggerinterface.go`` for required logging functions.
It is able to run with standart log package, in that case
initialize flagger like:
```go
flgr = flagger.New("My Super Program", flagger.LoggerInterface(log.New(os.Stdout, "testing logger: ", log.Lshortfile)))
flgr.Initialize()
```
Adding a flag is easy, just fill ``Flag`` structure and pass to ``AddFlag()`` call:
```go
flag_bool := Flag{
Name: "boolflag",
Description: "Boolean flag",
Type: "bool",
DefaultValue: true,
}
err := flgr.AddFlag(&flag_bool)
if err != nil {
...
}
```
After adding all neccessary flags you should issue ``Parse()`` call to get
them parsed:
```go
flgr.Parse()
```
After parsed they can be obtained everywhere you want, like:
```go
val, err := flgr.GetBoolValue("boolflag")
if err != nil {
...
}
```
For more examples take a look at ``flagger_test.go`` file or [at GoDoc](https://godoc.org/go.dev.pztrn.name/flagger).

@ -0,0 +1,36 @@
// Flagger - arbitrary CLI flags parser.
//
// Copyright (c) 2017-2019, Stanislav N. aka pztrn.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject
// to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package flagger
import "errors"
var (
// ErrFlagAlreadyAdded appears when trying to register a flag with
// an already used name (field Name).
ErrFlagAlreadyAdded = errors.New("flag already added")
// ErrNoSuchFlag appears when trying to request a value for a flag
// that wasn't registered.
ErrNoSuchFlag = errors.New("no such flag")
)

@ -0,0 +1,53 @@
// Flagger - arbitrary CLI flags parser.
//
// Copyright (c) 2017-2019, Stanislav N. aka pztrn.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject
// to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package flagger
import (
// stdlib
"log"
"os"
)
var (
logger LoggerInterface
applicationName string
)
// New creates new Flagger instance.
// If no logger will be passed - we will use default "log" module and will
// print logs to stdout.
func New(appName string, l LoggerInterface) *Flagger {
applicationName = appName
if l == nil {
lg := log.New(os.Stdout, "Flagger: ", log.LstdFlags)
logger = LoggerInterface(lg)
} else {
logger = l
}
f := Flagger{}
return &f
}

@ -0,0 +1,36 @@
// Flagger - arbitrary CLI flags parser.
//
// Copyright (c) 2017-2019, Stanislav N. aka pztrn.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject
// to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package flagger
// Flag represents addable flag for Flagger.
type Flag struct {
// Flag name. It will be accessible using this name later.
Name string
// Description for help output.
Description string
// Type can be one of "bool", "int", "string".
Type string
// This value will be reflected.
DefaultValue interface{}
}

@ -0,0 +1,141 @@
// Flagger - arbitrary CLI flags parser.
//
// Copyright (c) 2017-2019, Stanislav N. aka pztrn.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject
// to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package flagger
import (
// stdlib
"flag"
"os"
)
// Flagger implements (kinda) extended CLI parameters parser. As it
// available from CommonContext, these flags will be available to
// whole application.
//
// It uses reflection to determine what kind of variable we should
// parse or get.
type Flagger struct {
// Flags that was added by user.
flags map[string]*Flag
// Flags that will be passed to flag module.
flagsBool map[string]*bool
flagsInt map[string]*int
flagsString map[string]*string
flagSet *flag.FlagSet
}
// AddFlag adds flag to list of flags we will pass to ``flag`` package.
func (f *Flagger) AddFlag(flag *Flag) error {
_, present := f.flags[flag.Name]
if present {
return ErrFlagAlreadyAdded
}
f.flags[flag.Name] = flag
return nil
}
// GetBoolValue returns boolean value for flag with given name.
// Returns bool value for flag and nil as error on success
// and false bool plus error with text on error.
func (f *Flagger) GetBoolValue(name string) (bool, error) {
fl, present := f.flagsBool[name]
if !present {
return false, ErrNoSuchFlag
}
return (*fl), nil
}
// GetIntValue returns integer value for flag with given name.
// Returns integer on success and 0 on error.
func (f *Flagger) GetIntValue(name string) (int, error) {
fl, present := f.flagsInt[name]
if !present {
return 0, ErrNoSuchFlag
}
return (*fl), nil
}
// GetStringValue returns string value for flag with given name.
// Returns string on success or empty string on error.
func (f *Flagger) GetStringValue(name string) (string, error) {
fl, present := f.flagsString[name]
if !present {
return "", ErrNoSuchFlag
}
return (*fl), nil
}
// Initialize initializes Flagger.
func (f *Flagger) Initialize() {
logger.Print("Initializing CLI parameters parser...")
f.flags = make(map[string]*Flag)
f.flagsBool = make(map[string]*bool)
f.flagsInt = make(map[string]*int)
f.flagsString = make(map[string]*string)
f.flagSet = flag.NewFlagSet(applicationName, flag.ContinueOnError)
}
// Parse adds flags from flags map to flag package and parse
// them. They can be obtained later by calling GetTYPEValue(name),
// where TYPE is one of Bool, Int, String.
func (f *Flagger) Parse() {
// If flags was already parsed - do nothing.
if f.flagSet.Parsed() {
return
}
for name, fl := range f.flags {
if fl.Type == "bool" {
fdef := fl.DefaultValue.(bool)
f.flagsBool[name] = &fdef
f.flagSet.BoolVar(&fdef, name, fdef, fl.Description)
} else if fl.Type == "int" {
fdef := fl.DefaultValue.(int)
f.flagsInt[name] = &fdef
f.flagSet.IntVar(&fdef, name, fdef, fl.Description)
} else if fl.Type == "string" {
fdef := fl.DefaultValue.(string)
f.flagsString[name] = &fdef
f.flagSet.StringVar(&fdef, name, fdef, fl.Description)
}
}
logger.Print("Parsing CLI parameters:", os.Args)
err := f.flagSet.Parse(os.Args[1:])
if err != nil {
os.Exit(0)
}
}

@ -0,0 +1,8 @@
module go.dev.pztrn.name/flagger
go 1.13
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/stretchr/testify v1.6.1
)

@ -0,0 +1,13 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

@ -0,0 +1,31 @@
// Flagger - arbitrary CLI flags parser.
//
// Copyright (c) 2017-2019, Stanislav N. aka pztrn.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject
// to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE