From d6c0fa35188473b5572b166355a143d94121ab86 Mon Sep 17 00:00:00 2001 From: "Sascha L. Teichmann" Date: Tue, 10 May 2022 16:38:34 +0200 Subject: [PATCH] Make extraction of fields optional --- csaf/summary.go | 4 ++-- util/json.go | 25 ++++++++++++++++++++----- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/csaf/summary.go b/csaf/summary.go index a04d140..d6cc882 100644 --- a/csaf/summary.go +++ b/csaf/summary.go @@ -51,8 +51,8 @@ func NewAdvisorySummary( {Expr: titleExpr, Action: util.StringMatcher(&e.Title)}, {Expr: currentReleaseDateExpr, Action: util.TimeMatcher(&e.CurrentReleaseDate, time.RFC3339)}, {Expr: initialReleaseDateExpr, Action: util.TimeMatcher(&e.InitialReleaseDate, time.RFC3339)}, - {Expr: summaryExpr, Action: util.StringMatcher(&e.Summary)}, - {Expr: tlpLabelExpr, Action: util.StringMatcher(&e.TLPLabel)}, + {Expr: summaryExpr, Action: util.StringMatcher(&e.Summary), Optional: true}, + {Expr: tlpLabelExpr, Action: util.StringMatcher(&e.TLPLabel), Optional: true}, {Expr: publisherExpr, Action: util.ReMarshalMatcher(e.Publisher)}, }, doc); err != nil { return nil, err diff --git a/util/json.go b/util/json.go index 24202f9..c4a111c 100644 --- a/util/json.go +++ b/util/json.go @@ -65,6 +65,8 @@ type PathEvalMatcher struct { Expr string // Action is executed with the result of the match. Action func(interface{}) error + // Optional expresses if the expression is optional. + Optional bool } // ReMarshalMatcher is an action to re-marshal the result to another type. @@ -102,14 +104,27 @@ func TimeMatcher(dst *time.Time, format string) func(interface{}) error { } } +// Extract extracts a value from a given document with a given expression/action. +func (pe *PathEval) Extract( + expr string, + action func(interface{}) error, + optional bool, + doc interface{}, +) error { + x, err := pe.Eval(expr, doc) + if err != nil { + if optional { + return nil + } + return err + } + return action(x) +} + // Match matches a list of PathEvalMatcher pairs against a document. func (pe *PathEval) Match(matcher []PathEvalMatcher, doc interface{}) error { for _, m := range matcher { - x, err := pe.Eval(m.Expr, doc) - if err != nil { - return err - } - if err := m.Action(x); err != nil { + if err := pe.Extract(m.Expr, m.Action, m.Optional, doc); err != nil { return err } }