From 71d2a3eb3494085098f914ac5a573399935dadb9 Mon Sep 17 00:00:00 2001 From: Francesco Giudici Date: Mon, 22 Aug 2022 13:11:01 +0200 Subject: [PATCH] fix linter: cyclomatic complexity of ServeHTTP is 16 Error: cyclomatic complexity 16 of func `(*InventoryServer).ServeHTTP` is high (> 15) (gocyclo) Move code to update labels from headers to subfunction Signed-off-by: Francesco Giudici --- pkg/server/register.go | 36 ++++++++++++++++++++++++++---------- 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/pkg/server/register.go b/pkg/server/register.go index 9549d05fe..2c24779fc 100644 --- a/pkg/server/register.go +++ b/pkg/server/register.go @@ -95,19 +95,12 @@ func (i *InventoryServer) ServeHTTP(resp http.ResponseWriter, req *http.Request) logrus.Infof("new machine inventory created: %s", inventory.Name) } - labels, err := getLabels(req) + invUpdated, err := fillLabels(req, inventory) if err != nil { - logrus.Warn("failed to parse labels header: ", err) + logrus.Warn("error extracting labels from headers: ", err) } - if len(labels) > 0 { - if inventory.Labels == nil { - inventory.Labels = labels - } else { - for k, v := range labels { - inventory.Labels[k] = v - } - } + if invUpdated { inventory, err = i.machineClient.Update(inventory) if err != nil { logrus.Error("failed to update inventory labels: ", err) @@ -328,3 +321,26 @@ func getLabels(req *http.Request) (map[string]string, error) { var labels map[string]string return labels, json.Unmarshal(labelString, &labels) } + +func fillLabels(req *http.Request, inventory *elm.MachineInventory) (bool, error) { + updated := false + labels, err := getLabels(req) + + if err != nil { + return updated, fmt.Errorf("extracting labels from headers: %w", err) + } + if len(labels) == 0 { + return updated, nil + } + + updated = true + logrus.Debugf("found labels in request headers: %#v", labels) + if inventory.Labels == nil { + inventory.Labels = labels + } else { + for k, v := range labels { + inventory.Labels[k] = v + } + } + return updated, nil +}