From bb3e845a7a2ac6fb7f20f532634b1e2179240bbb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tufan=20Bar=C4=B1=C5=9F=20Y=C4=B1ld=C4=B1r=C4=B1m?= Date: Tue, 9 Jan 2024 18:16:51 +0300 Subject: [PATCH] added WithCustomDirectives option (#38) --- parser/parser.go | 17 +++++++++++++++-- parser/parser_test.go | 11 +++++++++++ testdata/issues/37.conf | 7 +++++++ 3 files changed, 33 insertions(+), 2 deletions(-) create mode 100644 testdata/issues/37.conf diff --git a/parser/parser.go b/parser/parser.go index 4467da9..c611d1f 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -19,6 +19,7 @@ type options struct { parseInclude bool skipIncludeParsingErr bool skipComments bool + customDirectives map[string]string } // Parser is an nginx config parser @@ -83,6 +84,15 @@ func WithIncludeParsing() Option { } } +// WithCustomDirectives add your custom directives as valid directives +func WithCustomDirectives(directives ...string) Option { + return func(p *Parser) { + for _, directive := range directives { + p.opts.customDirectives[directive] = directive + } + } +} + // NewStringParser parses nginx conf from string func NewStringParser(str string, opts ...Option) *Parser { return NewParserFromLexer(lex(str), opts...) @@ -106,7 +116,7 @@ func NewParserFromLexer(lexer *lexer, opts ...Option) *Parser { configRoot, _ := filepath.Split(lexer.file) parser := &Parser{ lexer: lexer, - opts: options{}, + opts: options{customDirectives: make(map[string]string)}, parsedIncludes: make(map[string]*gonginx.Config), configRoot: configRoot, } @@ -229,7 +239,10 @@ func (p *Parser) parseStatement() (gonginx.IDirective, error) { Name: p.currentToken.Literal, } - if _, ok := ValidDirectives[d.Name]; !ok { + _, ok := ValidDirectives[d.Name] + _, ok2 := p.opts.customDirectives[d.Name] + + if !ok && !ok2 { return nil, fmt.Errorf("unknown directive '%s' on line %d, column %d", d.Name, p.currentToken.Line, p.currentToken.Column) } diff --git a/parser/parser_test.go b/parser/parser_test.go index 44aed48..1496e86 100644 --- a/parser/parser_test.go +++ b/parser/parser_test.go @@ -348,3 +348,14 @@ func TestParser_Issue31(t *testing.T) { t.Fatal("error expected here") } } + +func TestParser_Issue32(t *testing.T) { + t.Parallel() + p, err := NewParser("../testdata/issues/37.conf", + WithCustomDirectives("my_custom_directive", "my_custom_directive2"), + WithCustomDirectives("my_custom_directive3"), + ) + assert.NilError(t, err, "no error expected here") + _, err = p.Parse() + assert.NilError(t, err, "no error expected here") +} diff --git a/testdata/issues/37.conf b/testdata/issues/37.conf new file mode 100644 index 0000000..0663b65 --- /dev/null +++ b/testdata/issues/37.conf @@ -0,0 +1,7 @@ +http { + include mime.types; + default_type application/octet-stream; + my_custom_directive myParam1 myParam2; + my_custom_directive2 myParam1 myParam2; + my_custom_directive3 myParam1 myParam2; +} \ No newline at end of file