Skip to content

Commit

Permalink
added WithCustomDirectives option (#38)
Browse files Browse the repository at this point in the history
  • Loading branch information
tufanbarisyildirim authored Jan 9, 2024
1 parent ba16e88 commit bb3e845
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
17 changes: 15 additions & 2 deletions parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ type options struct {
parseInclude bool
skipIncludeParsingErr bool
skipComments bool
customDirectives map[string]string
}

// Parser is an nginx config parser
Expand Down Expand Up @@ -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...)
Expand All @@ -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,
}
Expand Down Expand Up @@ -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)
}

Expand Down
11 changes: 11 additions & 0 deletions parser/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
7 changes: 7 additions & 0 deletions testdata/issues/37.conf
Original file line number Diff line number Diff line change
@@ -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;
}

0 comments on commit bb3e845

Please # to comment.