Skip to content

Commit

Permalink
Add Plugin.ID()
Browse files Browse the repository at this point in the history
  • Loading branch information
breml committed Feb 15, 2021
1 parent baf3e9b commit 04f44c3
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 0 deletions.
19 changes: 19 additions & 0 deletions ast/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package ast

import (
"bytes"
"errors"
"fmt"
)

Expand Down Expand Up @@ -160,6 +161,24 @@ func (p Plugin) String() string {
return s.String()
}

// ID returns the id of a Logstash plugin.
// The id attribute is one of the common options, that is optionally available
// on every Logstash plugin. In generall, it is highly recommended for a Logstash
// plugin to have an id.
func (p Plugin) ID() (string, error) {
for _, attr := range p.Attributes {
if attr != nil && attr.Name() == "id" {
switch stringAttr := attr.(type) {
case StringAttribute:
return stringAttr.value, nil
default:
return "", errors.New("attribut id is not of type string attribute")
}
}
}
return "", fmt.Errorf("plugin %s does not contain an id attribute", p.name)
}

// Attribute interface combines Logstash plugin attribute types.
type Attribute interface {
Name() string
Expand Down
73 changes: 73 additions & 0 deletions ast/ast_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,79 @@ output {
}
}

func TestPluginID(t *testing.T) {
cases := []struct {
name string
plugin Plugin

wantID string
wantErr bool
}{
{
name: "double quoted id",
plugin: NewPlugin("stdin",
NewStringAttribute("id", "123", DoubleQuoted),
),

wantID: "123",
},
{
name: "bareword id",
plugin: NewPlugin("stdin",
NewStringAttribute("id", "123", Bareword),
),

wantID: "123",
},
{
name: "bareword id",
plugin: NewPlugin("stdin",
NewNumberAttribute("id", 123),
),

wantID: "",
wantErr: true,
},
{
name: "multiple attributes with id",
plugin: NewPlugin("stdin",
NewStringAttribute("name", "fobar", Bareword),
NewStringAttribute("id", "123", Bareword),
NewStringAttribute("description", "the description", DoubleQuoted),
),

wantID: "123",
},
{
name: "multiple attributes without id",
plugin: NewPlugin("stdin",
NewStringAttribute("name", "fobar", Bareword),
NewStringAttribute("alternative", "baz", Bareword),
NewStringAttribute("description", "the description", DoubleQuoted),
),

wantID: "",
wantErr: true,
},
}

for _, test := range cases {
t.Run(test.name, func(t *testing.T) {
id, err := test.plugin.ID()

if test.wantErr && err == nil {
t.Error("Expected an error, but go none.")
}
if !test.wantErr && err != nil {
t.Errorf("Expected no error but got: %v", err)
}
if test.wantID != id {
t.Errorf("Expected id to be %q, but got %q", test.wantID, id)
}
})
}
}

func TestPluginType(t *testing.T) {
cases := []struct {
name string
Expand Down

0 comments on commit 04f44c3

Please sign in to comment.