From 05afe9074215af5ce346e0f22fbe7356bac26075 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pavel=20Kut=C3=A1=C4=8D?= Date: Fri, 6 Oct 2023 08:39:57 +0200 Subject: [PATCH] style: improve linter rules --- .golangci.yml | 113 +++++++++++++---- authorization/client_test.go | 1 - authorization/is_authorized_test.go | 4 - authorization/what_authorized_test.go | 4 - authorization/who_authorized_test.go | 2 - config/application_agent_credentials_test.go | 5 - config/application_agent_test.go | 9 -- config/application_space_test.go | 10 -- config/application_test.go | 9 -- config/config_client_test.go | 1 - config/config_node_test.go | 35 ++---- config/config_request.go | 6 +- config/container_configuration_test.go | 1 - config/customer_test.go | 1 - config/example_test.go | 8 +- config/oauth2_application_test.go | 8 -- config/oauth2_provider_test.go | 8 -- config/service_account_credentials_test.go | 5 - config/service_account_test.go | 6 - config/tenant_test.go | 8 -- errors/errors.go | 20 +-- examples/authorization/cmd/is_authorized.go | 3 - examples/authorization/cmd/root.go | 3 +- examples/authorization/cmd/what_authorized.go | 3 - examples/authorization/cmd/who_authorized.go | 1 - examples/config/cmd/root.go | 2 +- examples/identity/cmd/enrich_token.go | 1 - examples/identity/cmd/root.go | 2 +- examples/ingest/cmd/root.go | 3 +- examples/knowledge/cmd/root.go | 3 +- examples/oauth2/cmd/root.go | 3 +- examples/oauth2/cmd/token.go | 4 +- .../identity/v1beta1/attributes.ext.go | 11 +- gen/indykite/identity/v1beta1/model.ext.go | 38 ------ .../identity/v1beta2/attributes.ext.go | 11 +- .../identity/v1beta2/document.pb.validate.go | 6 - .../knowledge/v1beta1/model.ext_test.go | 2 - gen/indykite/objects/v1beta1/id.ext.go | 117 ------------------ gen/indykite/objects/v1beta1/struct.ext.go | 32 ++--- .../objects/v1beta1/struct.ext_test.go | 52 ++++---- grpc/config/credentials_test.go | 2 +- grpc/config/tls.go | 11 +- grpc/credentials_test.go | 8 +- grpc/internal/settings.go | 18 ++- grpc/jwt/jwt.go | 39 +++--- grpc/jwt/jwt_test.go | 4 +- grpc/option.go | 2 +- grpc/pool.go | 12 +- grpc/pool_test.go | 6 +- grpc/transport.go | 2 +- identity/digital_twin.go | 1 + identity/example_test.go | 12 +- identity/invitation.go | 2 +- identity/invitation_test.go | 2 +- ingest/example_test.go | 12 +- ingest/ingest_retry_client.go | 5 +- ingest/stream_records.go | 29 ++--- knowledge/example_test.go | 30 ++--- knowledge/knowledge_read_test.go | 8 -- oauth2/token_test.go | 3 +- test/matchers.go | 59 ++++----- 61 files changed, 298 insertions(+), 530 deletions(-) delete mode 100644 gen/indykite/identity/v1beta1/model.ext.go delete mode 100644 gen/indykite/objects/v1beta1/id.ext.go diff --git a/.golangci.yml b/.golangci.yml index c5e8052c..0c73c0e9 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,4 +1,5 @@ --- +# All rules here were written in the time of GolangCI lint v1.54.1 linters: enable: # By Default @@ -12,14 +13,20 @@ linters: - unused # Extra + - asasalint - asciicheck - bidichk + - bodyclose + - containedctx - contextcheck - dogsled - - durationcheck - dupword + - durationcheck - errchkjson + - errname + - errorlint - exhaustive + - exportloopref - forbidigo - gci - ginkgolinter @@ -34,10 +41,18 @@ linters: - grouper - lll - loggercheck + - makezero + - mirror - misspell - nakedret + - nestif + - nilerr + - noctx - nolintlint + - nonamedreturns + - nosprintfhostport - prealloc + - predeclared - reassign - revive - tagalign @@ -52,6 +67,7 @@ linters-settings: lll: line-length: 120 tab-width: 4 + gci: # Keep in sync with GNUMakefile sections: @@ -60,23 +76,32 @@ linters-settings: - prefix(github.com/indykite/indykite-sdk-go) - blank - dot - govet: - check-shadowing: true - # This enable is on top of the defaults, it does not override everything - enable: - - fieldalignment + staticcheck: - go: '1.21' checks: [all] + stylecheck: - go: '1.21' checks: [all] + govet: + check-shadowing: true + enable-all: true + + gocritic: + enabled-tags: + - diagnostic + - style + - performance + - experimental + - opinionated + disabled-checks: + - whyNoLint # Is checked by nolintlint with excluding lll much easier + goheader: values: regexp: # As long we decide which format of YEAR in copyright we want, add this hack - our_year: 202[0-3] + our_year: 202[0-3] # Just change to 202[2-3] or other when changed template: |- Copyright (c) {{OUR_YEAR}} IndyKite @@ -95,6 +120,11 @@ linters-settings: nakedret: max-func-lines: 8 # Counting also declaration, not just body + nolintlint: + allow-no-explanation: [lll] + require-explanation: true + require-specific: true + exhaustive: check: - switch @@ -110,48 +140,85 @@ linters-settings: - name: context-as-argument - name: context-keys-type - name: dot-imports + - name: empty-block + - name: error-naming - name: error-return - name: error-strings - - name: error-naming + - name: errorf - name: exported - - name: if-return - name: increment-decrement - - name: var-naming - - name: var-declaration + - name: indent-error-flow - name: package-comments - name: range - name: receiver-naming + - name: redefines-builtin-id + - name: superfluous-else - name: time-naming - name: unexported-return - - name: indent-error-flow - - name: errorf + - name: unreachable-code + - name: unused-parameter + - name: var-declaration + - name: var-naming # Extra ones + - name: atomic + - name: bare-return + - name: bool-literal-in-expr + - name: comment-spacings - name: confusing-naming - name: confusing-results + - name: constant-logical-expr + - name: datarace + - name: deep-exit + - name: defer + - name: duplicated-imports - name: early-return - - name: empty-block - name: empty-lines - name: get-return + - name: identical-branches + - name: if-return + # - name: import-alias-naming # GolangCI doesn't implement latest rules of Revive, enable later + - name: import-shadowing + - name: modifies-parameter - name: modifies-value-receiver - name: nested-structs - - name: redefines-builtin-id + - name: optimize-operands-order + - name: range-val-address + - name: range-val-in-closure + # - name: redundant-import-alias # GolangCI doesn't implement latest rules of Revive, enable later - name: string-of-int - - name: superfluous-else + - name: struct-tag + - name: time-equal + # - name: unchecked-type-assertion # GolangCI doesn't implement latest rules of Revive, enable later + - name: unconditional-recursion + - name: unexported-naming + - name: unhandled-error # It is OK not to check errors from some specific cases + arguments: + - fmt.Println - name: unnecessary-stmt + - name: unused-receiver + - name: use-any + - name: useless-break + - name: waitgroup-by-value + + usestdlibvars: + default-rpc-path: true + os-dev-null: true + sql-isolation-level: true issues: exclude-use-default: false # Some rules are excluded by GolangCI Linter by default, this one will prevent that max-issues-per-linter: 0 max-same-issues: 0 - exclude-rules: - linters: - revive text: exported .* should have comment .*or be unexported # TODO fix this for proper documentation - linters: - revive - text: 'empty-lines:' # Ignore one-liners - false positive, fix from revive is coming - - linters: - - contextcheck - text: verifyTokenFormat->.*parseBytes # False positive, context is internal in JWT, not in our control + - gocritic + text: 'deep-exit: calls to log.Fatalf|exitAfterDefer: log.Fatalf will exit' + path: .*_test.go + # - linters: + # - contextcheck + # text: verifyTokenFormat->.*parseBytes # False positive, context is internal in JWT, not in our control diff --git a/authorization/client_test.go b/authorization/client_test.go index 807c58cc..dc53b063 100644 --- a/authorization/client_test.go +++ b/authorization/client_test.go @@ -46,6 +46,5 @@ var _ = Describe("IsAuthorized", func() { Expect(authorizationClient).To(Not(BeNil())) Expect(authorizationClient.Close()).To(Succeed()) }) - }) }) diff --git a/authorization/is_authorized_test.go b/authorization/is_authorized_test.go index dc887a0f..617f4ff2 100644 --- a/authorization/is_authorized_test.go +++ b/authorization/is_authorized_test.go @@ -88,11 +88,9 @@ var _ = Describe("IsAuthorized", func() { var clientErr *sdkerrors.ClientError Expect(errors.As(err, &clientErr)).To(BeTrue(), "is client error") Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Nil token", func() { - resp, err := authorizationClient.IsAuthorizedByToken(ctx, "", nil, nil, nil) Expect(err).To(HaveOccurred()) Expect(resp).To(BeNil()) @@ -101,7 +99,6 @@ var _ = Describe("IsAuthorized", func() { Expect(errors.As(err, &clientErr)).To(BeTrue(), "is client error") Expect(clientErr.Message()).To(ContainSubstring("unable to call IsAuthorized client endpoint")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Wrong DT should return a validation error in the response", func() { @@ -120,7 +117,6 @@ var _ = Describe("IsAuthorized", func() { Expect(err).To(MatchError(ContainSubstring( "invalid DigitalTwin.Id: value length must be between 27 and 100 runes", ))) - }) It("IsAuthorizedDT", func() { diff --git a/authorization/what_authorized_test.go b/authorization/what_authorized_test.go index de5d8459..ceec781b 100644 --- a/authorization/what_authorized_test.go +++ b/authorization/what_authorized_test.go @@ -88,11 +88,9 @@ var _ = Describe("WhatAuthorized", func() { var clientErr *sdkerrors.ClientError Expect(errors.As(err, &clientErr)).To(BeTrue(), "is client error") Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Nil token", func() { - resp, err := authorizationClient.WhatAuthorizedByToken(ctx, "", nil, nil, nil) Expect(err).To(HaveOccurred()) Expect(resp).To(BeNil()) @@ -101,7 +99,6 @@ var _ = Describe("WhatAuthorized", func() { Expect(errors.As(err, &clientErr)).To(BeTrue(), "is client error") Expect(clientErr.Message()).To(ContainSubstring("unable to call WhatAuthorized client endpoint")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Wrong DT should return a validation error in the response", func() { @@ -120,7 +117,6 @@ var _ = Describe("WhatAuthorized", func() { Expect(err).To(MatchError(ContainSubstring( "invalid DigitalTwin.Id: value length must be between 27 and 100 runes", ))) - }) It("WhatAuthorizedDT", func() { diff --git a/authorization/who_authorized_test.go b/authorization/who_authorized_test.go index f174e44a..95c68512 100644 --- a/authorization/who_authorized_test.go +++ b/authorization/who_authorized_test.go @@ -98,7 +98,6 @@ var _ = Describe("WhoAuthorized", func() { var clientErr *sdkerrors.ClientError Expect(errors.As(err, &clientErr)).To(BeTrue(), "is client error") Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Wrong resource should return a validation error in the response", func() { @@ -111,7 +110,6 @@ var _ = Describe("WhoAuthorized", func() { resp, err := authorizationClient.WhoAuthorized(ctx, req) Expect(resp).To(BeNil()) Expect(err).To(MatchError(ContainSubstring("invalid WhoAuthorizedRequest_Resource.ExternalId"))) - }) It("WhoAuthorized", func() { diff --git a/config/application_agent_credentials_test.go b/config/application_agent_credentials_test.go index 3a3c8693..5ed2ef5e 100644 --- a/config/application_agent_credentials_test.go +++ b/config/application_agent_credentials_test.go @@ -63,7 +63,6 @@ var _ = Describe("ApplicationAgentCredentials", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Wrong id should return a validation error in the response", func() { @@ -73,7 +72,6 @@ var _ = Describe("ApplicationAgentCredentials", func() { resp, err := configClient.ReadApplicationAgentCredential(ctx, req) Expect(resp).To(BeNil()) Expect(err).To(MatchError(ContainSubstring("Id: value length must be between 22"))) - }) It("Read", func() { @@ -134,7 +132,6 @@ var _ = Describe("ApplicationAgentCredentials", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Register", func() { @@ -203,7 +200,6 @@ var _ = Describe("ApplicationAgentCredentials", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("should return an length error in the response", func() { @@ -215,7 +211,6 @@ var _ = Describe("ApplicationAgentCredentials", func() { resp, err := configClient.DeleteApplicationAgentCredential(ctx, req) Expect(resp).To(BeNil()) Expect(err).To(MatchError(ContainSubstring("Id: value length must be between 22"))) - }) It("Delete", func() { diff --git a/config/application_agent_test.go b/config/application_agent_test.go index 0eec77ba..26f103f8 100644 --- a/config/application_agent_test.go +++ b/config/application_agent_test.go @@ -64,7 +64,6 @@ var _ = Describe("ApplicationAgent", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Wrong id should return a validation error in the response", func() { @@ -74,7 +73,6 @@ var _ = Describe("ApplicationAgent", func() { resp, err := configClient.ReadApplicationAgent(ctx, req) Expect(resp).To(BeNil()) Expect(err).To(MatchError(ContainSubstring("Id: value length must be between 22"))) - }) DescribeTable("ReadSuccess", @@ -173,7 +171,6 @@ var _ = Describe("ApplicationAgent", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Create", func() { @@ -247,7 +244,6 @@ var _ = Describe("ApplicationAgent", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Update", func() { @@ -323,7 +319,6 @@ var _ = Describe("ApplicationAgent", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("MatchName", func() { @@ -366,7 +361,6 @@ var _ = Describe("ApplicationAgent", func() { resp, err = stream.Recv() Ω(err).To(Equal(io.EOF)) Ω(resp).To(BeNil()) - }) It("MatchNameError", func() { @@ -410,7 +404,6 @@ var _ = Describe("ApplicationAgent", func() { "Match: value must contain at least 1 item", ), ) - }) Describe("ApplicationAgentDelete", func() { @@ -424,7 +417,6 @@ var _ = Describe("ApplicationAgent", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Wrong id should return a validation error in the response", func() { @@ -436,7 +428,6 @@ var _ = Describe("ApplicationAgent", func() { resp, err := configClient.DeleteApplicationAgent(ctx, req) Expect(resp).To(BeNil()) Expect(err).To(MatchError(ContainSubstring("Id: value length must be between 22"))) - }) It("Delete", func() { diff --git a/config/application_space_test.go b/config/application_space_test.go index 529d19e5..dd9523b0 100644 --- a/config/application_space_test.go +++ b/config/application_space_test.go @@ -64,7 +64,6 @@ var _ = Describe("AppSpace", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Wrong id should return a validation error in the response", func() { @@ -74,7 +73,6 @@ var _ = Describe("AppSpace", func() { resp, err := configClient.ReadApplicationSpace(ctx, req) Expect(resp).To(BeNil()) Expect(err).To(MatchError(ContainSubstring("Id: value length must be between 22"))) - }) DescribeTable("ReadSuccess", @@ -173,7 +171,6 @@ var _ = Describe("AppSpace", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Create", func() { @@ -247,7 +244,6 @@ var _ = Describe("AppSpace", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Update", func() { @@ -323,7 +319,6 @@ var _ = Describe("AppSpace", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("MatchName", func() { @@ -365,7 +360,6 @@ var _ = Describe("AppSpace", func() { resp, err = stream.Recv() Ω(err).To(Equal(io.EOF)) Ω(resp).To(BeNil()) - }) DescribeTable("ListError", @@ -408,9 +402,7 @@ var _ = Describe("AppSpace", func() { stream, err := configClient.ListApplicationSpaces(context.Background(), &mockListApplicationSpacesRequest) Expect(err).ToNot(Succeed()) Expect(stream).To(BeNil()) - }) - }) Describe("AppSpaceDelete", func() { @@ -424,7 +416,6 @@ var _ = Describe("AppSpace", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("should return an length error in the response", func() { @@ -436,7 +427,6 @@ var _ = Describe("AppSpace", func() { resp, err := configClient.DeleteApplicationSpace(ctx, req) Expect(resp).To(BeNil()) Expect(err).To(MatchError(ContainSubstring("Id: value length must be between 22"))) - }) It("Delete", func() { diff --git a/config/application_test.go b/config/application_test.go index e248b809..0d73973e 100644 --- a/config/application_test.go +++ b/config/application_test.go @@ -64,7 +64,6 @@ var _ = Describe("Application", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Wrong id should return a validation error in the response", func() { @@ -74,7 +73,6 @@ var _ = Describe("Application", func() { resp, err := configClient.ReadApplication(ctx, req) Expect(resp).To(BeNil()) Expect(err).To(MatchError(ContainSubstring("Id: value length must be between 22"))) - }) DescribeTable("ReadSuccess", @@ -173,7 +171,6 @@ var _ = Describe("Application", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Create", func() { @@ -247,7 +244,6 @@ var _ = Describe("Application", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Update", func() { @@ -323,7 +319,6 @@ var _ = Describe("Application", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("MatchName", func() { @@ -366,7 +361,6 @@ var _ = Describe("Application", func() { resp, err = stream.Recv() Ω(err).To(Equal(io.EOF)) Ω(resp).To(BeNil()) - }) DescribeTable("ListError", @@ -410,7 +404,6 @@ var _ = Describe("Application", func() { Expect(err).ToNot(Succeed()) Expect(stream).To(BeNil()) }) - }) Describe("ApplicationDelete", func() { @@ -424,7 +417,6 @@ var _ = Describe("Application", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("should return an length error in the response", func() { @@ -436,7 +428,6 @@ var _ = Describe("Application", func() { resp, err := configClient.DeleteApplication(ctx, req) Expect(resp).To(BeNil()) Expect(err).To(MatchError(ContainSubstring("Id: value length must be between 22"))) - }) It("Delete", func() { diff --git a/config/config_client_test.go b/config/config_client_test.go index 77c8f538..adc3e384 100644 --- a/config/config_client_test.go +++ b/config/config_client_test.go @@ -51,6 +51,5 @@ var _ = Describe("ConfigNode", func() { Expect(configClient.Close()).To(Succeed()) } }) - }) }) diff --git a/config/config_node_test.go b/config/config_node_test.go index fad2352a..e2ea8247 100644 --- a/config/config_node_test.go +++ b/config/config_node_test.go @@ -65,7 +65,6 @@ var _ = Describe("ConfigNode", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil or not read request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Wrong id should return a validation error in the response", func() { @@ -74,7 +73,6 @@ var _ = Describe("ConfigNode", func() { resp, err := configClient.ReadConfigNode(ctx, configNodeRequest) Expect(resp).To(BeNil()) Expect(err).To(MatchError(ContainSubstring("Id: value length must be between 22"))) - }) It("ReadSuccessReadId", func() { @@ -231,7 +229,6 @@ var _ = Describe("ConfigNode", func() { }) It("ReadString", func() { - configNodeRequest, err := config.NewRead("gid:like-real-config-node-id") resp := configNodeRequest.String() @@ -257,7 +254,6 @@ var _ = Describe("ConfigNode", func() { Expect(configNodeRequest.String()).To(Not(BeNil())) Expect(configNodeRequest.String()).To(ContainSubstring("Invalid empty request")) }) - }) Describe("ConfigNodeCreate", func() { @@ -271,7 +267,6 @@ var _ = Describe("ConfigNode", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil or not create request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("CreateReadId", func() { @@ -628,17 +623,14 @@ var _ = Describe("ConfigNode", func() { resp, err := configClient.CreateConfigNode(ctx, configNodeRequest) Expect(resp).To(BeNil()) Expect(err).To(MatchError(ContainSubstring("SubmitterSecret: value length must be at least 36 runes"))) - }) It("CreateNonValidName", func() { - configNodeRequest, err := config.NewCreate("1234") Expect(err).ToNot(Succeed()) resp, err := configClient.CreateConfigNode(ctx, configNodeRequest) Expect(resp).To(BeNil()) Expect(err).To(MatchError(ContainSubstring("invalid nil or not create request"))) - }) It("CreateError", func() { @@ -681,7 +673,6 @@ var _ = Describe("ConfigNode", func() { }) It("CreateString", func() { - configNodeRequest, err := config.NewCreate("like-real-config-node-name") Ω(err).To(Succeed()) configNodeRequest.ForLocation("gid:like-real-customer-id") @@ -705,7 +696,6 @@ var _ = Describe("ConfigNode", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil or not update request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("UpdateReadId", func() { @@ -721,9 +711,9 @@ var _ = Describe("ConfigNode", func() { } configNodeRequest, err := config.NewUpdate("gid:like-real-config-node-id") Ω(err).To(Succeed()) - configNodeRequest.EmptyDisplayName("Like real ConfigNode Name") + configNodeRequest.EmptyDisplayName() configNodeRequest.WithDisplayName("Like real ConfigNode Name Update") - configNodeRequest.EmptyDescription("Description") + configNodeRequest.EmptyDescription() configNodeRequest.WithDescription("Description") configNodeRequest.WithPreCondition("qwert1234") configNodeRequest.WithBookmarks([]string{"something-like-bookmark-which-is-long-enough"}) @@ -767,7 +757,7 @@ var _ = Describe("ConfigNode", func() { configNodeRequest, err := config.NewUpdate("gid:like-real-config-node-id") Ω(err).To(Succeed()) - configNodeRequest.EmptyDisplayName("Like real ConfigNode Name") + configNodeRequest.EmptyDisplayName() configNodeRequest.WithDisplayName("Like real ConfigNode Name Update") configNodeRequest.WithOAuth2ClientConfig(configuration) @@ -811,7 +801,7 @@ var _ = Describe("ConfigNode", func() { configNodeRequest, err := config.NewUpdate("gid:like-real-config-node-id") Ω(err).To(Succeed()) - configNodeRequest.EmptyDisplayName("Like real ConfigNode Name") + configNodeRequest.EmptyDisplayName() configNodeRequest.WithDisplayName("Like real ConfigNode Name Update") configNodeRequest.WithWebauthnProviderConfig(configuration) @@ -871,7 +861,7 @@ var _ = Describe("ConfigNode", func() { } configNodeRequest, err := config.NewUpdate("gid:like-real-config-node-id") Ω(err).To(Succeed()) - configNodeRequest.EmptyDisplayName("Like real ConfigNode Name") + configNodeRequest.EmptyDisplayName() configNodeRequest.WithDisplayName("Like real ConfigNode Name Update") configNodeRequest.WithEmailNotificationConfig(configuration) @@ -914,7 +904,7 @@ var _ = Describe("ConfigNode", func() { configNodeRequest, err := config.NewUpdate("gid:like-real-config-node-id") Ω(err).To(Succeed()) - configNodeRequest.EmptyDisplayName("Like real ConfigNode Name") + configNodeRequest.EmptyDisplayName() configNodeRequest.WithDisplayName("Like real ConfigNode Name Update") configNodeRequest.WithAuthFlowConfig(configuration) @@ -959,7 +949,7 @@ var _ = Describe("ConfigNode", func() { configNodeRequest, err := config.NewUpdate("gid:like-real-config-node-id") Ω(err).To(Succeed()) - configNodeRequest.EmptyDisplayName("Like real ConfigNode Name") + configNodeRequest.EmptyDisplayName() configNodeRequest.WithDisplayName("Like real ConfigNode Name Update") configNodeRequest.WithAuthorizationPolicyConfig(configuration) @@ -1006,7 +996,7 @@ var _ = Describe("ConfigNode", func() { configNodeRequest, err := config.NewUpdate("gid:like-real-config-node-id") Ω(err).To(Succeed()) - configNodeRequest.EmptyDisplayName("Like real ConfigNode Name") + configNodeRequest.EmptyDisplayName() configNodeRequest.WithDisplayName("Like real ConfigNode Name Update") configNodeRequest.WithKnowledgeGraphSchemaConfig(configuration) @@ -1082,7 +1072,6 @@ var _ = Describe("ConfigNode", func() { }) It("UpdateString", func() { - configNodeRequest, err := config.NewUpdate("gid:like-real-config-node-id") Ω(err).To(Succeed()) configNodeRequest.ForLocation("gid:like-real-customer-id") @@ -1093,7 +1082,6 @@ var _ = Describe("ConfigNode", func() { Expect(err).To(Succeed()) Expect(configNodeRequest).To(ContainSubstring("Update gid:like-real-config-node-id configuration")) }) - }) Describe("ConfigNodeDelete", func() { @@ -1107,7 +1095,6 @@ var _ = Describe("ConfigNode", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil or not delete request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Wrong id should return a validation error in the response", func() { @@ -1116,7 +1103,6 @@ var _ = Describe("ConfigNode", func() { resp, err := configClient.DeleteConfigNode(ctx, configNodeRequest) Expect(resp).To(BeNil()) Expect(err).To(MatchError(ContainSubstring("Id: value length must be between 22"))) - }) It("Delete", func() { @@ -1162,7 +1148,6 @@ var _ = Describe("ConfigNode", func() { }) It("DeleteString", func() { - configNodeRequest, err := config.NewDelete("gid:like-real-config-node-id") resp := configNodeRequest.String() @@ -1183,7 +1168,6 @@ var _ = Describe("ConfigNode", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil or not read request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Wrong id should return a validation error in the response", func() { @@ -1192,7 +1176,6 @@ var _ = Describe("ConfigNode", func() { resp, err := configClient.ListConfigNodeVersions(ctx, configNodeRequest) Expect(resp).To(BeNil()) Expect(err).To(MatchError(ContainSubstring("value length must be between 22 and 254 runes, inclusive"))) - }) It("ListVersionsSuccess", func() { @@ -1254,8 +1237,6 @@ var _ = Describe("ConfigNode", func() { resp, err := configClient.ListConfigNodeVersions(ctx, configNodeRequest) Expect(err).ToNot(Succeed()) Expect(resp).To(BeNil()) - }) }) - }) diff --git a/config/config_request.go b/config/config_request.go index b046f0e7..0b0508f2 100644 --- a/config/config_request.go +++ b/config/config_request.go @@ -127,7 +127,7 @@ func (x *NodeRequest) WithPreCondition(etag string) *NodeRequest { } // EmptyDisplayName removes the current displayName value. -func (x *NodeRequest) EmptyDisplayName(v string) *NodeRequest { +func (x *NodeRequest) EmptyDisplayName() *NodeRequest { return x.WithDisplayName("") } @@ -143,7 +143,7 @@ func (x *NodeRequest) WithDisplayName(v string) *NodeRequest { } // EmptyDescription removes the current description value. -func (x *NodeRequest) EmptyDescription(v string) *NodeRequest { +func (x *NodeRequest) EmptyDescription() *NodeRequest { return x.WithDescription("") } @@ -326,7 +326,7 @@ func (x *NodeRequest) WithVersion(version int64) *NodeRequest { return x } -func (x *NodeRequest) optionalString(v string) *wrapperspb.StringValue { +func (*NodeRequest) optionalString(v string) *wrapperspb.StringValue { return wrapperspb.String(strings.TrimSpace(v)) } diff --git a/config/container_configuration_test.go b/config/container_configuration_test.go index cf1a11ae..082e8d18 100644 --- a/config/container_configuration_test.go +++ b/config/container_configuration_test.go @@ -447,5 +447,4 @@ var _ = Describe("Container Configuration", func() { Expect(resp).To(BeNil()) }) }) - }) diff --git a/config/customer_test.go b/config/customer_test.go index 8587b4c4..fbb8c153 100644 --- a/config/customer_test.go +++ b/config/customer_test.go @@ -62,7 +62,6 @@ var _ = Describe("Customer", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Wrong id should return a validation error in the response", func() { diff --git a/config/example_test.go b/config/example_test.go index 6613b246..b60e79ab 100644 --- a/config/example_test.go +++ b/config/example_test.go @@ -28,9 +28,7 @@ func ExampleNewClient_default() { if err != nil { log.Fatalf("failed to create client %v", err) } - defer func() { - _ = client.Close() - }() + _ = client.Close() } // This example demonstrates how to create a new Config Client. @@ -40,7 +38,5 @@ func ExampleNewClient_options() { if err != nil { log.Fatalf("failed to create client %v", err) } - defer func() { - _ = client.Close() - }() + _ = client.Close() } diff --git a/config/oauth2_application_test.go b/config/oauth2_application_test.go index bc5e797c..579dcf34 100644 --- a/config/oauth2_application_test.go +++ b/config/oauth2_application_test.go @@ -63,7 +63,6 @@ var _ = Describe("OAuth2Application", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Wrong id should return a validation error in the response", func() { @@ -71,7 +70,6 @@ var _ = Describe("OAuth2Application", func() { resp, err := configClient.ReadOAuth2Application(ctx, req) Expect(resp).To(BeNil()) Expect(err).To(MatchError(ContainSubstring("Id: value length must be between 22"))) - }) It("ReadSuccess", func() { @@ -157,7 +155,6 @@ var _ = Describe("OAuth2Application", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Create", func() { @@ -258,7 +255,6 @@ var _ = Describe("OAuth2Application", func() { Expect(err).ToNot(Succeed()) Expect(resp).To(BeNil()) }) - }) Describe("OAuth2ApplicationUpdate", func() { @@ -272,7 +268,6 @@ var _ = Describe("OAuth2Application", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Update", func() { @@ -376,7 +371,6 @@ var _ = Describe("OAuth2Application", func() { Expect(err).ToNot(Succeed()) Expect(resp).To(BeNil()) }) - }) Describe("OAuth2ApplicationDelete", func() { @@ -390,7 +384,6 @@ var _ = Describe("OAuth2Application", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("should return an length error in the response", func() { @@ -402,7 +395,6 @@ var _ = Describe("OAuth2Application", func() { resp, err := configClient.DeleteOAuth2Application(ctx, req) Expect(resp).To(BeNil()) Expect(err).To(MatchError(ContainSubstring("Id: value length must be between 22"))) - }) It("Delete", func() { diff --git a/config/oauth2_provider_test.go b/config/oauth2_provider_test.go index 202fcc65..6b760475 100644 --- a/config/oauth2_provider_test.go +++ b/config/oauth2_provider_test.go @@ -63,7 +63,6 @@ var _ = Describe("OAuth2Provider", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Wrong id should return a validation error in the response", func() { @@ -71,7 +70,6 @@ var _ = Describe("OAuth2Provider", func() { resp, err := configClient.ReadOAuth2Provider(ctx, req) Expect(resp).To(BeNil()) Expect(err).To(MatchError(ContainSubstring("Id: value length must be between 22"))) - }) It("ReadSuccess", func() { @@ -148,7 +146,6 @@ var _ = Describe("OAuth2Provider", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Create", func() { @@ -234,7 +231,6 @@ var _ = Describe("OAuth2Provider", func() { Expect(err).ToNot(Succeed()) Expect(resp).To(BeNil()) }) - }) Describe("OAuth2ProviderUpdate", func() { @@ -248,7 +244,6 @@ var _ = Describe("OAuth2Provider", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Update", func() { @@ -338,7 +333,6 @@ var _ = Describe("OAuth2Provider", func() { Expect(err).ToNot(Succeed()) Expect(resp).To(BeNil()) }) - }) Describe("OAuth2ProviderDelete", func() { @@ -352,7 +346,6 @@ var _ = Describe("OAuth2Provider", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("should return an length error in the response", func() { @@ -364,7 +357,6 @@ var _ = Describe("OAuth2Provider", func() { resp, err := configClient.DeleteOAuth2Provider(ctx, req) Expect(resp).To(BeNil()) Expect(err).To(MatchError(ContainSubstring("Id: value length must be between 22"))) - }) It("Delete", func() { diff --git a/config/service_account_credentials_test.go b/config/service_account_credentials_test.go index 82dc8e0b..22e75160 100644 --- a/config/service_account_credentials_test.go +++ b/config/service_account_credentials_test.go @@ -61,7 +61,6 @@ var _ = Describe("Service Account Credentials", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Register", func() { @@ -123,7 +122,6 @@ var _ = Describe("Service Account Credentials", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Read", func() { @@ -155,7 +153,6 @@ var _ = Describe("Service Account Credentials", func() { resp, err := configClient.ReadServiceAccountCredential(ctx, req) Expect(resp).To(BeNil()) Expect(err).To(MatchError(ContainSubstring("Id: value length must be between 22"))) - }) It("ReadError", func() { @@ -186,7 +183,6 @@ var _ = Describe("Service Account Credentials", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Delete", func() { @@ -217,7 +213,6 @@ var _ = Describe("Service Account Credentials", func() { resp, err := configClient.DeleteServiceAccountCredential(ctx, req) Expect(resp).To(BeNil()) Expect(err).To(MatchError(ContainSubstring("Id: value length must be between 22"))) - }) It("Delete", func() { diff --git a/config/service_account_test.go b/config/service_account_test.go index 8340f02b..a4f2b3b7 100644 --- a/config/service_account_test.go +++ b/config/service_account_test.go @@ -63,7 +63,6 @@ var _ = Describe("ServiceAccount", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Wrong id should return a validation error in the response", func() { @@ -73,7 +72,6 @@ var _ = Describe("ServiceAccount", func() { resp, err := configClient.ReadServiceAccount(ctx, req) Expect(resp).To(BeNil()) Expect(err).To(MatchError(ContainSubstring("Id: value length must be between 22"))) - }) DescribeTable("ReadSuccess", @@ -174,7 +172,6 @@ var _ = Describe("ServiceAccount", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Create", func() { @@ -264,7 +261,6 @@ var _ = Describe("ServiceAccount", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Update", func() { @@ -340,7 +336,6 @@ var _ = Describe("ServiceAccount", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("should return an length error in the response", func() { @@ -352,7 +347,6 @@ var _ = Describe("ServiceAccount", func() { resp, err := configClient.DeleteServiceAccount(ctx, req) Expect(resp).To(BeNil()) Expect(err).To(MatchError(ContainSubstring("Id: value length must be between 22"))) - }) It("Delete", func() { diff --git a/config/tenant_test.go b/config/tenant_test.go index 0e69ba63..20cbf994 100644 --- a/config/tenant_test.go +++ b/config/tenant_test.go @@ -64,7 +64,6 @@ var _ = Describe("Tenant", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Wrong id should return a validation error in the response", func() { @@ -170,7 +169,6 @@ var _ = Describe("Tenant", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Create", func() { @@ -243,7 +241,6 @@ var _ = Describe("Tenant", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("Update", func() { @@ -306,7 +303,6 @@ var _ = Describe("Tenant", func() { Expect(err).ToNot(Succeed()) Expect(resp).To(BeNil()) }) - }) Describe("TenantList", func() { It("Nil request", func() { @@ -319,7 +315,6 @@ var _ = Describe("Tenant", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("MatchName", func() { @@ -361,7 +356,6 @@ var _ = Describe("Tenant", func() { resp, err = stream.Recv() Ω(err).To(Equal(io.EOF)) Ω(resp).To(BeNil()) - }) DescribeTable("ListNonValid", @@ -418,7 +412,6 @@ var _ = Describe("Tenant", func() { Expect(clientErr.Unwrap()).To(Succeed()) Expect(clientErr.Message()).To(Equal("invalid nil request")) Expect(clientErr.Code()).To(Equal(codes.InvalidArgument)) - }) It("should return an length error in the response", func() { @@ -430,7 +423,6 @@ var _ = Describe("Tenant", func() { resp, err := configClient.DeleteTenant(ctx, req) Expect(resp).To(BeNil()) Expect(err).To(MatchError(ContainSubstring("Id: value length must be between 22"))) - }) It("Delete", func() { diff --git a/errors/errors.go b/errors/errors.go index 686be4fa..18b32949 100644 --- a/errors/errors.go +++ b/errors/errors.go @@ -51,7 +51,7 @@ func (err *ClientError) Unwrap() error { return err.cause } -func (err *ClientError) As(out interface{}) bool { +func (err *ClientError) As(out any) bool { switch t := out.(type) { case *ClientError: *t = *err @@ -62,22 +62,22 @@ func (err *ClientError) As(out interface{}) bool { } // NewInvalidArgumentError returns a new ClientError represents an InvalidArgument. -func NewInvalidArgumentError(msg string, args ...interface{}) error { +func NewInvalidArgumentError(msg string, args ...any) error { return New(codes.InvalidArgument, msg, args...) } // NewInvalidArgumentErrorWithCause returns a new ClientError represents an InvalidArgument. -func NewInvalidArgumentErrorWithCause(cause error, msg string, args ...interface{}) error { +func NewInvalidArgumentErrorWithCause(cause error, msg string, args ...any) error { return NewWithCause(codes.InvalidArgument, cause, msg, args...) } // New returns a new ClientError with code and formatted message. -func New(code codes.Code, msg string, args ...interface{}) error { +func New(code codes.Code, msg string, args ...any) error { return NewWithCause(code, nil, msg, args...) } // NewWithCause returns a new ClientError with code and formatted message. -func NewWithCause(code codes.Code, err error, msg string, args ...interface{}) error { +func NewWithCause(code codes.Code, err error, msg string, args ...any) error { if code == codes.OK { if err == nil { return nil @@ -106,10 +106,11 @@ func NewWithCause(code codes.Code, err error, msg string, args ...interface{}) e // IsServiceError checks if the Error code represents a service call error. func IsServiceError(err error) bool { + //nolint:errorlint // TODO: Should be fixed, but also heavily tested if se, ok := err.(interface { Code() codes.Code }); ok { - //nolint:exhaustive + //nolint:exhaustive // No need to use default, because last statement will handle all switch se.Code() { case codes.Unknown, codes.DeadlineExceeded, @@ -138,12 +139,15 @@ func FromError(err error) *StatusError { if err == nil { return nil } + //nolint:errorlint // TODO: Should be fixed, but also heavily tested if s, ok := err.(*StatusError); ok { return s } + //nolint:errorlint // TODO: Should be fixed, but also heavily tested if s, ok := err.(*ClientError); ok { return &StatusError{grpcStatus: status.New(s.code, s.msg), origin: s.cause} } + //nolint:errorlint // TODO: Should be fixed, but also heavily tested if se, ok := err.(interface { GRPCStatus() *status.Status }); ok { @@ -153,7 +157,7 @@ func FromError(err error) *StatusError { } // NewGRPCError unwrap original GRPC status and wraps into GRPCErrorWrapper for easier access. -func NewGRPCError(entryErr interface{}) *StatusError { +func NewGRPCError(entryErr any) *StatusError { if entryErr == nil { return nil } @@ -200,7 +204,7 @@ func (err *StatusError) Status() *status.Status { } // WithPrefix set prefix which will be printed in when Error is called. -func (err *StatusError) WithPrefix(prefix string) *StatusError { +func (err *StatusError) WithPrefix(_ string) *StatusError { return err } diff --git a/examples/authorization/cmd/is_authorized.go b/examples/authorization/cmd/is_authorized.go index 01da782d..d4a47f70 100644 --- a/examples/authorization/cmd/is_authorized.go +++ b/examples/authorization/cmd/is_authorized.go @@ -63,7 +63,6 @@ var withTokenCmd = &cobra.Command{ log.Fatalf("failed to invoke operation on IndyKite Client %v", err) } fmt.Println(jsonp.Format(resp)) - }, } @@ -102,7 +101,6 @@ var withDigitalTwinCmd = &cobra.Command{ log.Fatalf("failed to invoke operation on IndyKite Client %v", err) } fmt.Println(jsonp.Format(resp)) - }, } @@ -145,7 +143,6 @@ var withPropertyCmd = &cobra.Command{ log.Fatalf("failed to invoke operation on IndyKite Client %v", err) } fmt.Println(jsonp.Format(resp)) - }, } diff --git a/examples/authorization/cmd/root.go b/examples/authorization/cmd/root.go index 518ecf60..26534ae5 100644 --- a/examples/authorization/cmd/root.go +++ b/examples/authorization/cmd/root.go @@ -100,7 +100,6 @@ func initConfig() { err := viper.ReadInConfig() if err == nil { fmt.Println("Using config file:", viper.ConfigFileUsed()) - } client, err = authorization.NewClient(context.Background(), @@ -112,7 +111,7 @@ func initConfig() { } } -func er(msg interface{}) { +func er(msg any) { _, _ = fmt.Fprintf(os.Stderr, "Error: %v\n", msg) os.Exit(1) } diff --git a/examples/authorization/cmd/what_authorized.go b/examples/authorization/cmd/what_authorized.go index 10ec06fb..b0607ac4 100644 --- a/examples/authorization/cmd/what_authorized.go +++ b/examples/authorization/cmd/what_authorized.go @@ -60,7 +60,6 @@ var whatWithTokenCmd = &cobra.Command{ log.Fatalf("failed to invoke operation on IndyKite Client %v", err) } fmt.Println(jsonp.Format(resp)) - }, } @@ -98,7 +97,6 @@ var whatWithDigitalTwinCmd = &cobra.Command{ log.Fatalf("failed to invoke operation on IndyKite Client %v", err) } fmt.Println(jsonp.Format(resp)) - }, } @@ -138,7 +136,6 @@ var whatWithPropertyCmd = &cobra.Command{ log.Fatalf("failed to invoke operation on IndyKite Client %v", err) } fmt.Println(jsonp.Format(resp)) - }, } diff --git a/examples/authorization/cmd/who_authorized.go b/examples/authorization/cmd/who_authorized.go index 9cd17ab0..30272780 100644 --- a/examples/authorization/cmd/who_authorized.go +++ b/examples/authorization/cmd/who_authorized.go @@ -53,7 +53,6 @@ var whoAuthorizedCmd = &cobra.Command{ log.Fatalf("failed to invoke operation on IndyKite Client %v", err) } fmt.Println(jsonp.Format(resp)) - }, } diff --git a/examples/config/cmd/root.go b/examples/config/cmd/root.go index 1975e312..b68179cb 100644 --- a/examples/config/cmd/root.go +++ b/examples/config/cmd/root.go @@ -113,7 +113,7 @@ func initConfig() { } } -func er(msg interface{}) { +func er(msg any) { _, _ = fmt.Fprintf(os.Stderr, "Error: %v\n", msg) os.Exit(1) } diff --git a/examples/identity/cmd/enrich_token.go b/examples/identity/cmd/enrich_token.go index ef674bd3..4ecec7b7 100644 --- a/examples/identity/cmd/enrich_token.go +++ b/examples/identity/cmd/enrich_token.go @@ -76,7 +76,6 @@ var enrichTokenCmd = &cobra.Command{ } fmt.Println("successfully enriched token and session") - }, } diff --git a/examples/identity/cmd/root.go b/examples/identity/cmd/root.go index 74470d39..e56b9ddb 100644 --- a/examples/identity/cmd/root.go +++ b/examples/identity/cmd/root.go @@ -127,7 +127,7 @@ func initConfig() { } } -func er(msg interface{}) { +func er(msg any) { _, _ = fmt.Fprintf(os.Stderr, "Error: %v\n", msg) os.Exit(1) } diff --git a/examples/ingest/cmd/root.go b/examples/ingest/cmd/root.go index 62b52f38..809201a9 100644 --- a/examples/ingest/cmd/root.go +++ b/examples/ingest/cmd/root.go @@ -102,7 +102,6 @@ func initConfig() { err := viper.ReadInConfig() if err == nil { fmt.Println("Using config file:", viper.ConfigFileUsed()) - } client, err = ingest.NewClient(context.Background(), @@ -125,7 +124,7 @@ func initConfig() { } } -func er(msg interface{}) { +func er(msg any) { _, _ = fmt.Fprintf(os.Stderr, "Error: %v\n", msg) os.Exit(1) } diff --git a/examples/knowledge/cmd/root.go b/examples/knowledge/cmd/root.go index 248eb198..4dde5674 100644 --- a/examples/knowledge/cmd/root.go +++ b/examples/knowledge/cmd/root.go @@ -91,7 +91,6 @@ func initConfig() { err := viper.ReadInConfig() if err == nil { fmt.Println("Using config file:", viper.ConfigFileUsed()) - } client, err = knowledge.NewClient(context.Background(), @@ -103,7 +102,7 @@ func initConfig() { } } -func er(msg interface{}) { +func er(msg any) { _, _ = fmt.Fprintf(os.Stderr, "Error: %v\n", msg) os.Exit(1) } diff --git a/examples/oauth2/cmd/root.go b/examples/oauth2/cmd/root.go index 65d52f57..b473f54e 100644 --- a/examples/oauth2/cmd/root.go +++ b/examples/oauth2/cmd/root.go @@ -88,11 +88,10 @@ func initConfig() { err := viper.ReadInConfig() if err == nil { fmt.Println("Using config file:", viper.ConfigFileUsed()) - } } -func er(msg interface{}) { +func er(msg any) { _, _ = fmt.Fprintf(os.Stderr, "Error: %v\n", msg) os.Exit(1) } diff --git a/examples/oauth2/cmd/token.go b/examples/oauth2/cmd/token.go index 98ce8a91..e225145b 100644 --- a/examples/oauth2/cmd/token.go +++ b/examples/oauth2/cmd/token.go @@ -80,10 +80,10 @@ var queryKnowledgeAPI = &cobra.Command{ } var body bytes.Buffer - json.NewEncoder(&body).Encode(map[string]interface{}{ + json.NewEncoder(&body).Encode(map[string]any{ "operationName": "Tests", "query": "query Tests { tests { testField }}", - "variables": map[string]interface{}{}, + "variables": map[string]any{}, }) knowledgeAPIUrl := fmt.Sprintf("%s/knowledge/%s", cfg.BaseURL, cfg.AppSpaceID) diff --git a/gen/indykite/identity/v1beta1/attributes.ext.go b/gen/indykite/identity/v1beta1/attributes.ext.go index 99e50b7d..e16311fc 100644 --- a/gen/indykite/identity/v1beta1/attributes.ext.go +++ b/gen/indykite/identity/v1beta1/attributes.ext.go @@ -80,7 +80,7 @@ func (x *Property) GetAnyValue(msg proto.Message) error { return errors.New("invalid AnyPB value") } -func (x *Property) GetMapValue() (val map[string]interface{}, err error) { +func (x *Property) GetMapValue() (map[string]any, error) { if val, ok := x.Value.(*Property_ObjectValue); ok { if mapVal, ok := val.ObjectValue.GetValue().(*objects.Value_MapValue); ok { return objects.ToMap(mapVal.MapValue.Fields) @@ -105,7 +105,7 @@ func (PropertyBatchOperations) validateValue(value isProperty_Value, enableNil b return errors.New("object value must be specified") } case *Property_ReferenceValue: - if len(propertyValue.ReferenceValue) == 0 { + if propertyValue.ReferenceValue == "" { return errors.New("reference value must be specified") } default: @@ -159,17 +159,18 @@ func (x PropertyBatchOperations) Validate(isTrusted bool) error { // PreValidate checks the PropertyBatchOperations values. All public calls are considered non-trusted. // // It checks if the operations represent a valid collection of property updates. -func (x PropertyBatchOperations) PreValidate(isTrusted bool) ([]string, []string, error) { +// +//nolint:nonamedreturns // It is named here for better readability +func (x PropertyBatchOperations) PreValidate(isTrusted bool) (replaced, removed []string, _ error) { if len(x) == 0 { return nil, nil, errors.New("empty batch operation") } // This logic cannot be really tight to internal property logic, because PreValidate is used also in public part - var replaced, removed []string for i, v := range x { err := v.Validate() if err != nil { - return nil, nil, fmt.Errorf("invalid operation at index %d: %v", i, err) + return nil, nil, fmt.Errorf("invalid operation at index %d: %w", i, err) } switch bo := v.Operation.(type) { case *PropertyBatchOperation_Add: diff --git a/gen/indykite/identity/v1beta1/model.ext.go b/gen/indykite/identity/v1beta1/model.ext.go deleted file mode 100644 index 15820ed8..00000000 --- a/gen/indykite/identity/v1beta1/model.ext.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2022 IndyKite -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package identityv1beta1 - -import ( - "errors" - - "github.com/pborman/uuid" -) - -// Verify checks if the *DigitalTwin has RFC4122 TenantId and Id value. -func (x *DigitalTwin) Verify() (tenantID uuid.UUID, digitalTwinID uuid.UUID, _ error) { - if x == nil { - return nil, nil, errors.New("DigitalTwin value is required") - } - tenantID, digitalTwinID = x.TenantId, x.Id - if tenantID.Variant() != uuid.RFC4122 { - return nil, nil, errors.New("tenantId in DigitalTwin must be RFC4122 variant UUID") - } - if digitalTwinID.Variant() != uuid.RFC4122 { - return nil, nil, errors.New("id in DigitalTwin must be RFC4122 variant UUID") - } - return tenantID, digitalTwinID, nil -} - -func (*DigitalTwin) IsNode() {} diff --git a/gen/indykite/identity/v1beta2/attributes.ext.go b/gen/indykite/identity/v1beta2/attributes.ext.go index a8286995..7d6ac83d 100644 --- a/gen/indykite/identity/v1beta2/attributes.ext.go +++ b/gen/indykite/identity/v1beta2/attributes.ext.go @@ -79,7 +79,7 @@ func (x *Property) GetAnyValue(msg proto.Message) error { return errors.New("invalid AnyPB value") } -func (x *Property) GetMapValue() (val map[string]interface{}, err error) { +func (x *Property) GetMapValue() (map[string]any, error) { if val, ok := x.Value.(*Property_ObjectValue); ok { if mapVal, ok := val.ObjectValue.GetValue().(*objects.Value_MapValue); ok { return objects.ToMap(mapVal.MapValue.Fields) @@ -104,7 +104,7 @@ func (PropertyBatchOperations) validateValue(value isProperty_Value, enableNil b return errors.New("object value must be specified") } case *Property_ReferenceValue: - if len(propertyValue.ReferenceValue) == 0 { + if propertyValue.ReferenceValue == "" { return errors.New("reference value must be specified") } default: @@ -142,17 +142,18 @@ func (x PropertyBatchOperations) Validate() error { // PreValidate checks the PropertyBatchOperations values. All public calls are considered non-trusted. // // It checks if the operations represent a valid collection of property updates. -func (x PropertyBatchOperations) PreValidate() ([]string, []string, error) { +// +//nolint:nonamedreturns // It is named here for better readability +func (x PropertyBatchOperations) PreValidate() (replaced, removed []string, _ error) { if len(x) == 0 { return nil, nil, errors.New("empty batch operation") } // This logic cannot be really tight to internal property logic, because PreValidate is used also in public part - var replaced, removed []string for i, v := range x { err := v.Validate() if err != nil { - return nil, nil, fmt.Errorf("invalid operation at index %d: %v", i, err) + return nil, nil, fmt.Errorf("invalid operation at index %d: %w", i, err) } switch bo := v.Operation.(type) { case *PropertyBatchOperation_Add: diff --git a/gen/indykite/identity/v1beta2/document.pb.validate.go b/gen/indykite/identity/v1beta2/document.pb.validate.go index 8d4556b3..79e783b4 100644 --- a/gen/indykite/identity/v1beta2/document.pb.validate.go +++ b/gen/indykite/identity/v1beta2/document.pb.validate.go @@ -101,7 +101,6 @@ func (m *Document) validate(all bool) error { } } } - } } @@ -396,7 +395,6 @@ func (m *Precondition) validate(all bool) error { } } } - } if len(errors) > 0 { @@ -557,7 +555,6 @@ func (m *Write) validate(all bool) error { } } } - } if all { @@ -655,7 +652,6 @@ func (m *Write) validate(all bool) error { } } } - } if len(errors) > 0 { @@ -918,7 +914,6 @@ func (m *DocumentTransform) validate(all bool) error { } } } - } if len(errors) > 0 { @@ -1089,7 +1084,6 @@ func (m *DocumentTransform_FieldTransform) validate(all bool) error { } } } - } if len(errors) > 0 { diff --git a/gen/indykite/knowledge/v1beta1/model.ext_test.go b/gen/indykite/knowledge/v1beta1/model.ext_test.go index 8c9688e7..1231a926 100644 --- a/gen/indykite/knowledge/v1beta1/model.ext_test.go +++ b/gen/indykite/knowledge/v1beta1/model.ext_test.go @@ -24,7 +24,6 @@ import ( ) var _ = Describe("Node test", func() { - testNode := &knowledgev1beta1.Node{ Properties: []*knowledgev1beta1.Property{ { @@ -57,5 +56,4 @@ var _ = Describe("Node test", func() { Expect(ok).To(BeFalse()) Expect(v).To(BeNil()) }) - }) diff --git a/gen/indykite/objects/v1beta1/id.ext.go b/gen/indykite/objects/v1beta1/id.ext.go deleted file mode 100644 index 416366e5..00000000 --- a/gen/indykite/objects/v1beta1/id.ext.go +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2022 IndyKite -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package objectsv1beta1 - -import ( - "github.com/leodido/go-urn" - "github.com/multiformats/go-base36" - "github.com/pborman/uuid" - "google.golang.org/protobuf/proto" -) - -// NewIdentifier generates a new random (Version 4) UUID identifier. -func NewIdentifier() *Identifier { - return &Identifier{ - Id: &Identifier_IdBytes{ - IdBytes: uuid.NewRandom(), - }, - } -} - -// FromUUID converts UUID to *Identifier. -// -// Converts from: -// * String -// * UUID -// * *Identifier -// -// Returns nil if failed to parse. -func FromUUID(from interface{}) *Identifier { - var id uuid.UUID - switch v := from.(type) { - case string: - id = uuid.Parse(v) - case []byte: - id = v - if id.Variant() != uuid.RFC4122 { - return nil - } - case *Identifier: - return v - default: - return nil - } - return &Identifier{ - Id: &Identifier_IdBytes{ - IdBytes: id, - }, - } -} - -func (x *Identifier) AsString() string { - switch v := x.GetId().(type) { - case *Identifier_IdString: - return v.IdString - case *Identifier_IdBytes: - id := uuid.UUID(v.IdBytes) - if id.Variant() == uuid.RFC4122 { - return id.String() - } - } - return "" -} - -func (x *Identifier) AsUUID() uuid.UUID { - switch v := x.GetId().(type) { - case *Identifier_IdString: - return uuid.Parse(v.IdString) - case *Identifier_IdBytes: - id := uuid.UUID(v.IdBytes) - if id.Variant() == uuid.RFC4122 { - return id - } - } - return nil -} - -func (x *ObjectReference) AsString() string { - data, err := proto.Marshal(x) - if err != nil { - return "" - } - return (&urn.URN{ - ID: "indy", - SS: base36.EncodeToStringLc(data), - }).String() -} - -func ParseReferenceBytes(raw []byte) *ObjectReference { - if u, ok := urn.Parse(raw); ok { - if u.ID == "indy" { - var ref ObjectReference - data, err := base36.DecodeString(u.SS) - if err == nil { - if err = proto.Unmarshal(data, &ref); err == nil { - return &ref - } - } - } - } - return nil -} - -func ParseReference(raw string) *ObjectReference { - return ParseReferenceBytes([]byte(raw)) -} diff --git a/gen/indykite/objects/v1beta1/struct.ext.go b/gen/indykite/objects/v1beta1/struct.ext.go index 3219410f..ae13aac9 100644 --- a/gen/indykite/objects/v1beta1/struct.ext.go +++ b/gen/indykite/objects/v1beta1/struct.ext.go @@ -66,16 +66,16 @@ func Any(v proto.Message) (*Value, error) { return &Value{Value: &Value_AnyValue{AnyValue: a}}, nil } -func ToValue(v interface{}) (*Value, error) { +func ToValue(v any) (*Value, error) { val, _, err := toProtoValue(reflect.ValueOf(v)) return val, err } -func FromValue(v *Value) (interface{}, error) { +func FromValue(v *Value) (any, error) { return createFromProtoValue(v) } -func ToMapValue(in map[string]interface{}) (map[string]*Value, error) { +func ToMapValue(in map[string]any) (map[string]*Value, error) { if in == nil { return nil, nil } @@ -93,11 +93,11 @@ func ToMapValue(in map[string]interface{}) (map[string]*Value, error) { return out, nil } -func ToMap(fields map[string]*Value) (map[string]interface{}, error) { +func ToMap(fields map[string]*Value) (map[string]any, error) { if fields == nil { return nil, nil } - ret := make(map[string]interface{}, len(fields)) + ret := make(map[string]any, len(fields)) for k, v := range fields { r, err := createFromProtoValue(v) if err != nil { @@ -108,7 +108,7 @@ func ToMap(fields map[string]*Value) (map[string]interface{}, error) { return ret, nil } -func createFromProtoValue(v *Value) (interface{}, error) { +func createFromProtoValue(v *Value) (any, error) { if v == nil || v.Value == nil { return nil, nil } @@ -138,7 +138,7 @@ func createFromProtoValue(v *Value) (interface{}, error) { return nil, nil } values := v.ArrayValue.Values - ret := make([]interface{}, len(values)) + ret := make([]any, len(values)) for i, v := range values { r, err := createFromProtoValue(v) if err != nil { @@ -152,7 +152,7 @@ func createFromProtoValue(v *Value) (interface{}, error) { return nil, nil } fields := v.MapValue.Fields - ret := make(map[string]interface{}, len(fields)) + ret := make(map[string]any, len(fields)) for k, v := range fields { r, err := createFromProtoValue(v) if err != nil { @@ -167,14 +167,14 @@ func createFromProtoValue(v *Value) (interface{}, error) { } typeURL := v.AnyValue.GetTypeUrl() value := v.AnyValue.GetValue() - ret := map[string]interface{}{"typeUrl": typeURL, "value": value} + ret := map[string]any{"typeUrl": typeURL, "value": value} return ret, nil default: return nil, fmt.Errorf("unknown value type %T", v) } } -func toProtoValue(v reflect.Value) (pbv *Value, sawTransform bool, err error) { +func toProtoValue(v reflect.Value) (*Value, bool, error) { if !v.IsValid() { return nullValue, false, nil } @@ -298,26 +298,26 @@ func (x *ArrayValue) Get(i int) protoreflect.Value { return protoreflect.ValueOf(nil) } -func (x *ArrayValue) Set(i int, value protoreflect.Value) { +func (*ArrayValue) Set(int, protoreflect.Value) { panic("implement me") } -func (x *ArrayValue) Append(value protoreflect.Value) { +func (*ArrayValue) Append(protoreflect.Value) { panic("implement me") } -func (x *ArrayValue) AppendMutable() protoreflect.Value { +func (*ArrayValue) AppendMutable() protoreflect.Value { panic("implement me") } -func (x *ArrayValue) Truncate(i int) { +func (*ArrayValue) Truncate(int) { panic("implement me") } -func (x *ArrayValue) NewElement() protoreflect.Value { +func (*ArrayValue) NewElement() protoreflect.Value { panic("implement me") } -func (x *ArrayValue) IsValid() bool { +func (*ArrayValue) IsValid() bool { return true } diff --git a/gen/indykite/objects/v1beta1/struct.ext_test.go b/gen/indykite/objects/v1beta1/struct.ext_test.go index 9e76d06f..4de9ae0f 100644 --- a/gen/indykite/objects/v1beta1/struct.ext_test.go +++ b/gen/indykite/objects/v1beta1/struct.ext_test.go @@ -31,7 +31,7 @@ import ( var _ = Describe("Objects", func() { DescribeTable("SendVerificationEmailActivity - Verify attributes", - func(fields map[string]*objects.Value, expect map[string]interface{}) { + func(fields map[string]*objects.Value, expect map[string]any) { result, err := objects.ToMap(fields) Expect(err).To(Succeed()) @@ -45,7 +45,7 @@ var _ = Describe("Objects", func() { map[string]*objects.Value{ "Key": objects.String("String"), }, - map[string]interface{}{ + map[string]any{ "Key": "String", }, ), @@ -53,7 +53,7 @@ var _ = Describe("Objects", func() { map[string]*objects.Value{ "Key": objects.Int64(-64), }, - map[string]interface{}{ + map[string]any{ "Key": int64(-64), }, ), @@ -61,7 +61,7 @@ var _ = Describe("Objects", func() { map[string]*objects.Value{ "Key": {Value: &objects.Value_UnsignedIntegerValue{UnsignedIntegerValue: 64}}, }, - map[string]interface{}{ + map[string]any{ "Key": uint64(64), }, ), @@ -69,7 +69,7 @@ var _ = Describe("Objects", func() { map[string]*objects.Value{ "Key": objects.Bool(true), }, - map[string]interface{}{ + map[string]any{ "Key": true, }, ), @@ -77,7 +77,7 @@ var _ = Describe("Objects", func() { map[string]*objects.Value{ "Key": objects.Float64(6.4), }, - map[string]interface{}{ + map[string]any{ "Key": 6.4, }, ), @@ -86,7 +86,7 @@ var _ = Describe("Objects", func() { "Key": {Value: &objects.Value_ValueTime{ ValueTime: timestamppb.New(time.Date(2020, 8, 8, 8, 8, 8, 8, time.UTC))}}, }, - map[string]interface{}{ + map[string]any{ "Key": timestamppb.New( time.Date(2020, 8, 8, 8, 8, 8, 8, time.UTC)).AsTime().UTC().Format(time.RFC3339), }, @@ -96,7 +96,7 @@ var _ = Describe("Objects", func() { "Key": {Value: &objects.Value_DurationValue{ DurationValue: durationpb.New(time.Duration(10) * time.Second)}}, }, - map[string]interface{}{ + map[string]any{ "Key": durationpb.New(time.Duration(10) * time.Second).AsDuration().String(), }, ), @@ -104,7 +104,7 @@ var _ = Describe("Objects", func() { map[string]*objects.Value{ "Key": {Value: &objects.Value_BytesValue{BytesValue: []byte("somefunnyjokeaboutdinosaurs")}}, }, - map[string]interface{}{ + map[string]any{ "Key": []byte("somefunnyjokeaboutdinosaurs"), }, ), @@ -113,7 +113,7 @@ var _ = Describe("Objects", func() { "Key": {Value: &objects.Value_GeoPointValue{ GeoPointValue: &latlng.LatLng{Latitude: 64, Longitude: 64.03}}}, }, - map[string]interface{}{ + map[string]any{ "Key": fmt.Sprintf("POINT (%v %v)", 64, 64.03), }, ), @@ -121,7 +121,7 @@ var _ = Describe("Objects", func() { map[string]*objects.Value{ "Key": objects.Null(), }, - map[string]interface{}{ + map[string]any{ "Key": nil, }, ), @@ -129,7 +129,7 @@ var _ = Describe("Objects", func() { map[string]*objects.Value{ "Key": nil, }, - map[string]interface{}{ + map[string]any{ "Key": nil, }, ), @@ -142,8 +142,8 @@ var _ = Describe("Objects", func() { nil, }}}}, }, - map[string]interface{}{ - "Key": []interface{}{ + map[string]any{ + "Key": []any{ "item1", int64(2), nil, @@ -156,7 +156,7 @@ var _ = Describe("Objects", func() { map[string]*objects.Value{ "Key": {Value: &objects.Value_ArrayValue{ArrayValue: nil}}, }, - map[string]interface{}{ + map[string]any{ "Key": nil, }, ), @@ -164,8 +164,8 @@ var _ = Describe("Objects", func() { map[string]*objects.Value{ "Key": {Value: &objects.Value_ArrayValue{ArrayValue: &objects.ArrayValue{Values: nil}}}, }, - map[string]interface{}{ - "Key": []interface{}{}, + map[string]any{ + "Key": []any{}, }, ), Entry("Map", @@ -177,8 +177,8 @@ var _ = Describe("Objects", func() { "item4": nil, }}}}, }, - map[string]interface{}{ - "Key": map[string]interface{}{ + map[string]any{ + "Key": map[string]any{ "item1": "item1", "item2": int64(2), "item3": nil, @@ -190,7 +190,7 @@ var _ = Describe("Objects", func() { map[string]*objects.Value{ "Key": {Value: &objects.Value_MapValue{MapValue: nil}}, }, - map[string]interface{}{ + map[string]any{ "Key": nil, }, ), @@ -198,8 +198,8 @@ var _ = Describe("Objects", func() { map[string]*objects.Value{ "Key": {Value: &objects.Value_MapValue{MapValue: &objects.MapValue{Fields: nil}}}, }, - map[string]interface{}{ - "Key": map[string]interface{}{}, + map[string]any{ + "Key": map[string]any{}, }, ), Entry("Any", @@ -209,8 +209,8 @@ var _ = Describe("Objects", func() { Value: []byte("somefunnyjokeaboutdinosaurs"), }}}, }, - map[string]interface{}{ - "Key": map[string]interface{}{ + map[string]any{ + "Key": map[string]any{ "typeUrl": "TypeUrl", "value": []byte("somefunnyjokeaboutdinosaurs"), }, @@ -220,7 +220,7 @@ var _ = Describe("Objects", func() { map[string]*objects.Value{ "Key": {Value: nil}, }, - map[string]interface{}{ + map[string]any{ "Key": nil, }, ), @@ -228,7 +228,7 @@ var _ = Describe("Objects", func() { map[string]*objects.Value{ "Key": {Value: &objects.Value_AnyValue{AnyValue: nil}}, }, - map[string]interface{}{ + map[string]any{ "Key": nil, }, ), diff --git a/grpc/config/credentials_test.go b/grpc/config/credentials_test.go index 66a24dcf..55c0f99f 100644 --- a/grpc/config/credentials_test.go +++ b/grpc/config/credentials_test.go @@ -45,7 +45,7 @@ var _ = Describe("UnmarshalCredentialConfig", func() { data, err := os.ReadFile(filePath) Expect(err).To(Succeed()) // Quickly parse JSON to avoid hardcoded values - jsonData := make(map[string]interface{}) + jsonData := make(map[string]any) err = json.Unmarshal(data, &jsonData) Expect(err).To(Succeed()) diff --git a/grpc/config/tls.go b/grpc/config/tls.go index acd3d549..63cbb166 100644 --- a/grpc/config/tls.go +++ b/grpc/config/tls.go @@ -94,14 +94,13 @@ func getBaseTLSConfig() *tls.Config { } // DefaultServerTLSConfig setting https://wiki.mozilla.org/Security/Server_Side_TLS -func DefaultServerTLSConfig(serverKeyPair *tls.Certificate) (serverConfig *tls.Config) { - serverConfig = getBaseTLSConfig() +func DefaultServerTLSConfig(serverKeyPair *tls.Certificate) *tls.Config { + serverConfig := getBaseTLSConfig() serverConfig.Certificates = append(serverConfig.Certificates, *serverKeyPair) - return + return serverConfig } // ClientTLSConfig returns TLS Config for client. -func ClientTLSConfig() (clientTLSConf *tls.Config, err error) { - clientTLSConf = getBaseTLSConfig() - return +func ClientTLSConfig() (*tls.Config, error) { + return getBaseTLSConfig(), nil } diff --git a/grpc/credentials_test.go b/grpc/credentials_test.go index 59439e29..327d686c 100644 --- a/grpc/credentials_test.go +++ b/grpc/credentials_test.go @@ -53,7 +53,7 @@ var _ = Describe("Test JSON and YAML to JSON credentials", func() { data, err := os.ReadFile(filePath) Expect(err).To(Succeed()) // Quickly parse JSON to avoid hardcoded values - jsonData := make(map[string]interface{}) + jsonData := make(map[string]any) err = json.Unmarshal(data, &jsonData) Expect(err).To(Succeed()) @@ -83,7 +83,7 @@ var _ = Describe("Test JSON and YAML to JSON credentials", func() { data, err = yaml.YAMLToJSON(data) Expect(err).To(Succeed()) // Quickly parse JSON to avoid hardcoded values - jsonData := make(map[string]interface{}) + jsonData := make(map[string]any) err = json.Unmarshal(data, &jsonData) Expect(err).To(Succeed()) @@ -109,7 +109,7 @@ var _ = Describe("Test JSON and YAML to JSON credentials", func() { data, err := os.ReadFile("testdata/valid_jwt_as_map.json") Expect(err).To(Succeed()) // Quickly parse JSON to avoid hardcoded values - jsonData := make(map[string]interface{}) + jsonData := make(map[string]any) err = json.Unmarshal(data, &jsonData) Expect(err).To(Succeed()) @@ -172,7 +172,7 @@ var _ = Describe("Test JSON and YAML to JSON credentials", func() { data, err := os.ReadFile("testdata/valid_jwt_service.json") Ω(err).To(Succeed()) // Quickly parse JSON to avoid hardcoded values - var jsonData map[string]interface{} + var jsonData map[string]any err = json.Unmarshal(data, &jsonData) Ω(err).To(Succeed()) diff --git a/grpc/internal/settings.go b/grpc/internal/settings.go index 1a936cfa..077291e0 100644 --- a/grpc/internal/settings.go +++ b/grpc/internal/settings.go @@ -44,7 +44,7 @@ const ( // DialSettings holds information needed to establish a connection with a service. // -//nolint:govet +//nolint:govet // TODO Align fields type DialSettings struct { GRPCConn *grpc.ClientConn RetryOpts []retry.CallOption @@ -78,15 +78,13 @@ func (ds *DialSettings) Build(ctx context.Context) ([]grpc.DialOption, *config.C break } } + //nolint:nestif // Needs bigger refactor if ds.credentials != nil { - if ds.ServiceAccount { - if ds.credentials.ServiceAccountID == "" { - return nil, nil, errors.New("empty serviceAccountId") - } - } else { - if ds.credentials.AppAgentID == "" { - return nil, nil, errors.New("empty appAgentId") - } + if ds.ServiceAccount && ds.credentials.ServiceAccountID == "" { + return nil, nil, errors.New("empty serviceAccountId") + } + if !ds.ServiceAccount && ds.credentials.AppAgentID == "" { + return nil, nil, errors.New("empty appAgentId") } var err error @@ -169,7 +167,7 @@ func addInterceptors(opts []grpc.DialOption, settings *DialSettings) []grpc.Dial retOpts = []retry.CallOption{ retry.WithBackoff(retry.BackoffLinear(100 * time.Millisecond)), // retry.WithBackoff(retry.BackoffExponential(100 * time.Millisecond)), - retry.WithCodes(codes.ResourceExhausted /*codes.Internal,*/, codes.Unavailable), + retry.WithCodes(codes.ResourceExhausted, codes.Unavailable), retry.WithMax(12), } } diff --git a/grpc/jwt/jwt.go b/grpc/jwt/jwt.go index 5db1dc6c..22d5a203 100644 --- a/grpc/jwt/jwt.go +++ b/grpc/jwt/jwt.go @@ -37,7 +37,7 @@ type ( } ) -func CreateTokenSourceFromPrivateKey(privateKeyJWK interface{}, clientID string) (oauth2.TokenSource, error) { +func CreateTokenSourceFromPrivateKey(privateKeyJWK any, clientID string) (oauth2.TokenSource, error) { privateKeyJWKBytes, err := interfaceToBytes(privateKeyJWK) if err != nil { return nil, err @@ -84,7 +84,7 @@ func CreateTokenSource(credentials *config.CredentialsConfig) (oauth2.TokenSourc } } -func interfaceToBytes(privateKeyJWK interface{}) ([]byte, error) { +func interfaceToBytes(privateKeyJWK any) ([]byte, error) { if stringValue, ok := privateKeyJWK.(string); ok { return []byte(stringValue), nil } @@ -97,30 +97,29 @@ func interfaceToBytes(privateKeyJWK interface{}) ([]byte, error) { return privateKeyJWKBytes, nil } -func JWTokenSource(secretKey []byte, pem bool, clientID string, - tokenLifetime time.Duration) (oauth2.TokenSource, error) { - var ( - key jwk.Key - err error - ) +func parseKey(secretKey []byte, pem bool) (jwk.Key, error) { if pem { - key, err = jwk.ParseKey(secretKey, jwk.WithPEM(pem)) - } else { - if secretKey[0] == '"' { - var raw string - err = json.Unmarshal(secretKey, &raw) - if err != nil { - return nil, err - } - key, err = jwk.ParseKey([]byte(raw)) - } else { - key, err = jwk.ParseKey(secretKey) - } + return jwk.ParseKey(secretKey, jwk.WithPEM(pem)) + } + + if secretKey[0] != '"' { + return jwk.ParseKey(secretKey) } + + var raw string + err := json.Unmarshal(secretKey, &raw) if err != nil { return nil, err } + return jwk.ParseKey([]byte(raw)) +} +func JWTokenSource(secretKey []byte, pem bool, clientID string, + tokenLifetime time.Duration) (oauth2.TokenSource, error) { + key, err := parseKey(secretKey, pem) + if err != nil { + return nil, err + } // Remove user defined kid and generate new one same way as we do on BE // This is micro-optimization on client-side. _ = key.Remove(jwk.KeyIDKey) diff --git a/grpc/jwt/jwt_test.go b/grpc/jwt/jwt_test.go index d35b687f..a15ad509 100644 --- a/grpc/jwt/jwt_test.go +++ b/grpc/jwt/jwt_test.go @@ -39,14 +39,14 @@ var _ = Describe("CreateTokenSourceFromPrivateKey", func() { DescribeTable( "validate JSON correctly create tokenSource", - func(privateKeyJWK interface{}) { + func(privateKeyJWK any) { resp, err := CreateTokenSourceFromPrivateKey(privateKeyJWK, IntTestAppAgentID.String()) Expect(resp).To(Not(BeNil())) Expect(err).To(Succeed()) }, //nolint:lll Entry("valid string key", "{\"kty\":\"EC\",\"d\":\"2to-_wtohfn2PAgHr3RHQbhDf8g9zy6ndr05ZS-hS8s\",\"use\":\"sig\",\"crv\":\"P-256\",\"kid\":\"vDUXHBZcRw1KyFPyB0EI2XLBzyP9iGyfvaSX3MNtUlk\",\"x\":\"Cn2tSCxcQYVKuexBTzqRShvrJG8eQeZUq0ISIp9wXSA\",\"y\":\"DVSlYTLzns37LmjdscBA8q5ko1N8CZ-ETwviAJ78vW4\",\"alg\":\"ES256\"}"), - Entry("valid map key", map[string]interface{}{ + Entry("valid map key", map[string]any{ "kty": "EC", "d": "2to-_wtohfn2PAgHr3RHQbhDf8g9zy6ndr05ZS-hS8s", "use": "sig", diff --git a/grpc/option.go b/grpc/option.go index bff2e13b..1f924499 100644 --- a/grpc/option.go +++ b/grpc/option.go @@ -124,7 +124,7 @@ func WithTelemetryDisabled() ClientOption { type withTelemetryDisabled struct{} -func (w withTelemetryDisabled) Apply(o *internal.DialSettings) { +func (withTelemetryDisabled) Apply(o *internal.DialSettings) { o.TelemetryDisabled = true } diff --git a/grpc/pool.go b/grpc/pool.go index 5f50f584..433ecb7a 100644 --- a/grpc/pool.go +++ b/grpc/pool.go @@ -59,7 +59,7 @@ func (p *singleConnPool) Conn() *grpc.ClientConn { return p.ClientConn } -func (p *singleConnPool) Num() int { +func (*singleConnPool) Num() int { return 1 } @@ -79,7 +79,7 @@ func (p *roundRobinConnPool) Conn() *grpc.ClientConn { } func (p *roundRobinConnPool) Close() error { - var errs multiError + var errs multiErrors for _, conn := range p.conns { if err := conn.Close(); err != nil { errs = append(errs, err) @@ -92,7 +92,7 @@ func (p *roundRobinConnPool) Close() error { } func (p *roundRobinConnPool) Invoke(ctx context.Context, - method string, args interface{}, reply interface{}, opts ...grpc.CallOption) error { + method string, args any, reply any, opts ...grpc.CallOption) error { return p.Conn().Invoke(ctx, method, args, reply, opts...) } @@ -101,14 +101,14 @@ func (p *roundRobinConnPool) NewStream(ctx context.Context, return p.Conn().NewStream(ctx, desc, method, opts...) } -// multiError represents errors from multiple conns in the group. +// multiErrors represents errors from multiple conns in the group. // // TODO: figure out how and whether this is useful to export. End users should // not be depending on the transport/grpc package directly, so there might need // to be some service-specific multi-error type. -type multiError []error +type multiErrors []error -func (m multiError) Error() string { +func (m multiErrors) Error() string { s, n := "", 0 for _, e := range m { if e != nil { diff --git a/grpc/pool_test.go b/grpc/pool_test.go index c8d8708b..87b3f9ee 100644 --- a/grpc/pool_test.go +++ b/grpc/pool_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -//nolint:testpackage +//nolint:testpackage // We are not able to name that grpc_test for now. Needs bigger refactor. package grpc import ( @@ -81,13 +81,13 @@ func mockServer() (*grpc.Server, net.Listener) { } func GinkgoUnaryInterceptor(ctx context.Context, - req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { + req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { defer GinkgoRecover() return handler(ctx, req) } func GinkgoStreamInterceptor( - srv interface{}, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + srv any, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { defer GinkgoRecover() return handler(srv, ss) } diff --git a/grpc/transport.go b/grpc/transport.go index 5777901e..5a5b6a90 100644 --- a/grpc/transport.go +++ b/grpc/transport.go @@ -87,7 +87,7 @@ func DialPool(ctx context.Context, opts ...ClientOption) (ConnPool, *config.Cred for i := 0; i < poolSize; i++ { conn, err = grpc.DialContext(ctx, o.Endpoint, dop...) if err != nil { - defer func() { _ = pool.Close() }() + defer func() { _ = pool.Close() }() //nolint:revive,gocritic // If this happen, loop is exited return nil, nil, err } pool.conns = append(pool.conns, conn) diff --git a/identity/digital_twin.go b/identity/digital_twin.go index 00d6c40e..a62a906f 100644 --- a/identity/digital_twin.go +++ b/identity/digital_twin.go @@ -75,6 +75,7 @@ func (c *Client) VerifyDigitalTwinEmail(ctx context.Context, func (c *Client) IntrospectToken(ctx context.Context, token string, opts ...grpc.CallOption) (*identitypb.TokenIntrospectResponse, error) { if err := verifyTokenFormat(token); err != nil { + //nolint:nilerr // If there is error, we want to ignore error and just return false here return &identitypb.TokenIntrospectResponse{Active: false}, nil } diff --git a/identity/example_test.go b/identity/example_test.go index 6413853f..b4effef3 100644 --- a/identity/example_test.go +++ b/identity/example_test.go @@ -32,9 +32,7 @@ func ExampleNewClient_default() { if err != nil { log.Fatalf("failed to create client %v", err) } - defer func() { - _ = client.Close() - }() + _ = client.Close() } // This example demonstrates how to create a new Identity Client. @@ -44,9 +42,7 @@ func ExampleNewClient_options() { if err != nil { log.Fatalf("failed to create client %v", err) } - defer func() { - _ = client.Close() - }() + _ = client.Close() } // This example demonstrates the use of a identity client to introspect the @@ -64,7 +60,7 @@ func ExampleClient_IntrospectToken() { token := "JWT TOKEN HERE" tenant, err := client.IntrospectToken(context.Background(), token, retry.WithMax(2)) if err != nil { - log.Fatalf("failed to invoke operation on IndyKite Client %v", err) //nolint:gocritic + log.Fatalf("failed to invoke operation on IndyKite Client %v", err) } json := protojson.MarshalOptions{ Multiline: true, @@ -88,7 +84,7 @@ func ExampleClient_CreateEmailInvitation() { "696e6479-6b69-4465-8000-030100000002", "my-reference", time.Now().AddDate(0, 0, 7), time.Now(), - map[string]interface{}{ + map[string]any{ "lang": "en", }) if err != nil { diff --git a/identity/invitation.go b/identity/invitation.go index ab1b7ef0..0e6eb6ef 100644 --- a/identity/invitation.go +++ b/identity/invitation.go @@ -96,7 +96,7 @@ func (c *Client) CancelInvitation(ctx context.Context, referenceID string, opts // CreateEmailInvitation receive all properties for digital twin. func (c *Client) CreateEmailInvitation(ctx context.Context, invitee string, tenantID string, referenceID string, - expireTime, inviteAtTime time.Time, messageAttributes map[string]interface{}, + expireTime, inviteAtTime time.Time, messageAttributes map[string]any, opts ...grpc.CallOption) error { var request = &identitypb.CreateInvitationRequest{ ReferenceId: referenceID, diff --git a/identity/invitation_test.go b/identity/invitation_test.go index 573a9e21..69359323 100644 --- a/identity/invitation_test.go +++ b/identity/invitation_test.go @@ -59,7 +59,7 @@ var _ = Describe("Invitation", func() { "gid:AAAAA2luZHlraURlgAADDwAAAAE", "my-reference", now.AddDate(0, 0, 7), now, - map[string]interface{}{ + map[string]any{ "lang": "en", }) Ω(err).To(Succeed()) diff --git a/ingest/example_test.go b/ingest/example_test.go index df43a8d0..b54c4f8c 100644 --- a/ingest/example_test.go +++ b/ingest/example_test.go @@ -33,9 +33,7 @@ func ExampleNewClient_default() { if err != nil { log.Fatalf("failed to create client %v", err) } - defer func() { - _ = client.Close() - }() + _ = client.Close() } // This example demonstrates how to create a new Ingest Client. @@ -45,9 +43,7 @@ func ExampleNewClient_options() { if err != nil { log.Fatalf("failed to create client %v", err) } - defer func() { - _ = client.Close() - }() + _ = client.Close() } // This example demonstrates how to use the Ingest Client to stream multiple records. @@ -65,7 +61,7 @@ func ExampleClient_StreamRecords() { err = client.OpenStreamClient(ctx) if err != nil { - log.Fatalf("failed to open stream %v", err) //nolint:gocritic + log.Fatalf("failed to open stream %v", err) } for _, record := range []*ingestv2pb.Record{record1, record2} { @@ -102,7 +98,7 @@ func ExampleClient_IngestRecord() { response, err := client.IngestRecord(context.Background(), record1) if err != nil { - log.Fatalf("failed to invoke operation on IndyKite Client %v", err) //nolint:gocritic + log.Fatalf("failed to invoke operation on IndyKite Client %v", err) } json := protojson.MarshalOptions{ Multiline: true, diff --git a/ingest/ingest_retry_client.go b/ingest/ingest_retry_client.go index ab1a61f0..06a18f44 100644 --- a/ingest/ingest_retry_client.go +++ b/ingest/ingest_retry_client.go @@ -35,7 +35,7 @@ type RetryPolicy struct { type RetryClient struct { *Client - clientContext context.Context + clientContext context.Context //nolint:containedctx // we need client context here retryPolicy *RetryPolicy isUnableToReconnect bool } @@ -60,9 +60,6 @@ func NewTestRetryClient(client ingestpb.IngestAPIClient, retryPolicy *RetryPolic if err != nil { return nil, err } - if err != nil { - return nil, err - } rc := &RetryClient{ Client: c, retryPolicy: retryPolicy, diff --git a/ingest/stream_records.go b/ingest/stream_records.go index 0c837a22..afc6b32a 100644 --- a/ingest/stream_records.go +++ b/ingest/stream_records.go @@ -16,12 +16,13 @@ package ingest import ( "context" + "errors" "io" "time" "google.golang.org/grpc/codes" - "github.com/indykite/indykite-sdk-go/errors" + sdkerrors "github.com/indykite/indykite-sdk-go/errors" ingestpb "github.com/indykite/indykite-sdk-go/gen/indykite/ingest/v1beta2" ) @@ -35,7 +36,7 @@ func (c *Client) StreamRecords(records []*ingestpb.Record) ( stream, err := c.client.StreamRecords(ctx) if err != nil { - return nil, errors.FromError(err) + return nil, sdkerrors.FromError(err) } responses := make([]*ingestpb.StreamRecordsResponse, len(records)) @@ -46,18 +47,18 @@ func (c *Client) StreamRecords(records []*ingestpb.Record) ( err = stream.Send(req) if err != nil { - return nil, errors.FromError(err) + return nil, sdkerrors.FromError(err) } var resp *ingestpb.StreamRecordsResponse resp, err = stream.Recv() if err != nil { - return nil, errors.FromError(err) + return nil, sdkerrors.FromError(err) } responses[i] = resp } err = stream.CloseSend() if err != nil { - return nil, errors.FromError(err) + return nil, sdkerrors.FromError(err) } return responses, nil } @@ -66,7 +67,7 @@ func (c *Client) StreamRecords(records []*ingestpb.Record) ( func (c *Client) OpenStreamClient(ctx context.Context) error { stream, err := c.client.StreamRecords(ctx) if err != nil { - return errors.FromError(err) + return sdkerrors.FromError(err) } c.stream = stream return nil @@ -75,7 +76,7 @@ func (c *Client) OpenStreamClient(ctx context.Context) error { // SendRecord sends a record on the opened stream. func (c *Client) SendRecord(record *ingestpb.Record) error { if c.stream == nil { - return errors.New(codes.FailedPrecondition, "a stream must be opened first") + return sdkerrors.New(codes.FailedPrecondition, "a stream must be opened first") } req := &ingestpb.StreamRecordsRequest{ @@ -83,34 +84,34 @@ func (c *Client) SendRecord(record *ingestpb.Record) error { } err := c.stream.Send(req) - if err == nil || err == io.EOF { + if err == nil || errors.Is(err, io.EOF) { return err } - return errors.FromError(err) + return sdkerrors.FromError(err) } // ReceiveResponse returns the next response available on the stream. func (c *Client) ReceiveResponse() (*ingestpb.StreamRecordsResponse, error) { if c.stream == nil { - return nil, errors.New(codes.FailedPrecondition, "a stream must be opened first") + return nil, sdkerrors.New(codes.FailedPrecondition, "a stream must be opened first") } resp, err := c.stream.Recv() - if err == nil || err == io.EOF { + if err == nil || errors.Is(err, io.EOF) { return resp, err } - return nil, errors.FromError(err) + return nil, sdkerrors.FromError(err) } // CloseStream closes the gRPC stream. func (c *Client) CloseStream() error { if c.stream == nil { - return errors.New(codes.FailedPrecondition, "the stream has already been closed") + return sdkerrors.New(codes.FailedPrecondition, "the stream has already been closed") } err := c.stream.CloseSend() if err != nil { - return errors.FromError(err) + return sdkerrors.FromError(err) } return nil } diff --git a/knowledge/example_test.go b/knowledge/example_test.go index 314ab693..c0f87c44 100644 --- a/knowledge/example_test.go +++ b/knowledge/example_test.go @@ -33,9 +33,7 @@ func ExampleNewClient_default() { if err != nil { log.Fatalf("failed to create client %v", err) } - defer func() { - _ = client.Close() - }() + _ = client.Close() } // This example demonstrates how to create a new Identity Knowledge Client. @@ -45,9 +43,7 @@ func ExampleNewClient_options() { if err != nil { log.Fatalf("failed to create client %v", err) } - defer func() { - _ = client.Close() - }() + _ = client.Close() } // This example demonstrates how to use the Identity Knowledge Client to do a READ query. @@ -70,7 +66,7 @@ func ExampleClient_Read() { response, err := client.Read(context.Background(), path, conditions, params) if err != nil { - log.Fatalf("failed to invoke operation on IndyKite Client %v", err) //nolint:gocritic + log.Fatalf("failed to invoke operation on IndyKite Client %v", err) } json := protojson.MarshalOptions{ Multiline: true, @@ -90,7 +86,7 @@ func ExampleClient_GetDigitalTwinByID() { response, err := client.GetDigitalTwinByID(context.Background(), "gid:AAAAAmluZHlraURlgAABDwAAAAA") if err != nil { - log.Fatalf("failed to invoke operation on IndyKite Client %v", err) //nolint:gocritic + log.Fatalf("failed to invoke operation on IndyKite Client %v", err) } json := protojson.MarshalOptions{ Multiline: true, @@ -110,7 +106,7 @@ func ExampleClient_GetResourceByID() { response, err := client.GetResourceByID(context.Background(), "gid:AAAAAmluZHlraURlgAABDwAAAAA") if err != nil { - log.Fatalf("failed to invoke operation on IndyKite Client %v", err) //nolint:gocritic + log.Fatalf("failed to invoke operation on IndyKite Client %v", err) } json := protojson.MarshalOptions{ Multiline: true, @@ -134,7 +130,7 @@ func ExampleClient_GetDigitalTwinByIdentifier() { Type: "Person", }) if err != nil { - log.Fatalf("failed to invoke operation on IndyKite Client %v", err) //nolint:gocritic + log.Fatalf("failed to invoke operation on IndyKite Client %v", err) } json := protojson.MarshalOptions{ Multiline: true, @@ -158,7 +154,7 @@ func ExampleClient_GetResourceByIdentifier() { Type: "Store", }) if err != nil { - log.Fatalf("failed to invoke operation on IndyKite Client %v", err) //nolint:gocritic + log.Fatalf("failed to invoke operation on IndyKite Client %v", err) } json := protojson.MarshalOptions{ Multiline: true, @@ -187,7 +183,7 @@ func ExampleClient_ListDigitalTwinsByProperty() { }, ) if err != nil { - log.Fatalf("failed to invoke operation on IndyKite Client %v", err) //nolint:gocritic + log.Fatalf("failed to invoke operation on IndyKite Client %v", err) } json := protojson.MarshalOptions{ Multiline: true, @@ -218,7 +214,7 @@ func ExampleClient_ListResourcesByProperty() { }, ) if err != nil { - log.Fatalf("failed to invoke operation on IndyKite Client %v", err) //nolint:gocritic + log.Fatalf("failed to invoke operation on IndyKite Client %v", err) } json := protojson.MarshalOptions{ Multiline: true, @@ -240,7 +236,7 @@ func ExampleClient_ListResources() { response, err := client.ListResources(context.Background()) if err != nil { - log.Fatalf("failed to invoke operation on IndyKite Client %v", err) //nolint:gocritic + log.Fatalf("failed to invoke operation on IndyKite Client %v", err) } json := protojson.MarshalOptions{ Multiline: true, @@ -262,7 +258,7 @@ func ExampleClient_ListDigitalTwins() { response, err := client.ListDigitalTwins(context.Background()) if err != nil { - log.Fatalf("failed to invoke operation on IndyKite Client %v", err) //nolint:gocritic + log.Fatalf("failed to invoke operation on IndyKite Client %v", err) } json := protojson.MarshalOptions{ Multiline: true, @@ -284,7 +280,7 @@ func ExampleClient_ListNodes() { response, err := client.ListNodes(context.Background(), "Person") if err != nil { - log.Fatalf("failed to invoke operation on IndyKite Client %v", err) //nolint:gocritic + log.Fatalf("failed to invoke operation on IndyKite Client %v", err) } json := protojson.MarshalOptions{ Multiline: true, @@ -314,7 +310,7 @@ func ExampleClient_ListNodesByProperty() { Value: &objects.Value_StringValue{ StringValue: "test@test.com"}}}) if err != nil { - log.Fatalf("failed to invoke operation on IndyKite Client %v", err) //nolint:gocritic + log.Fatalf("failed to invoke operation on IndyKite Client %v", err) } json := protojson.MarshalOptions{ Multiline: true, diff --git a/knowledge/knowledge_read_test.go b/knowledge/knowledge_read_test.go index 4f2f9c97..a964befc 100644 --- a/knowledge/knowledge_read_test.go +++ b/knowledge/knowledge_read_test.go @@ -99,7 +99,6 @@ var _ = Describe("Identity Knowledge API", func() { }))), }))), }))) - }) Context("GetDigitalTwinByID", func() { @@ -152,7 +151,6 @@ var _ = Describe("Identity Knowledge API", func() { "Type": Equal("Person"), "Properties": HaveLen(1), }))) - }) It("return 0 nodes - success", func() { @@ -295,7 +293,6 @@ var _ = Describe("Identity Knowledge API", func() { "Type": Equal("Person"), "Properties": HaveLen(1), }))) - }) It("return 0 nodes - success", func() { @@ -435,7 +432,6 @@ var _ = Describe("Identity Knowledge API", func() { "ExternalId": Equal("0000"), "Type": Equal("Store"), }))) - }) It("return 0 nodes - success", func() { @@ -561,7 +557,6 @@ var _ = Describe("Identity Knowledge API", func() { "ExternalId": Equal("0000"), "Type": Equal("Store"), }))) - }) It("return 0 nodes - success", func() { @@ -769,7 +764,6 @@ var _ = Describe("Identity Knowledge API", func() { Expect(err).To(Succeed()) Expect(nodes).To(HaveLen(1)) }) - }) Context("List by property", func() { @@ -956,7 +950,5 @@ var _ = Describe("Identity Knowledge API", func() { Expect(err).To(Succeed()) Expect(nodes).To(HaveLen(1)) }) - }) - }) diff --git a/oauth2/token_test.go b/oauth2/token_test.go index 23890fe2..0ec85144 100644 --- a/oauth2/token_test.go +++ b/oauth2/token_test.go @@ -28,14 +28,13 @@ import ( ) var _ = Describe("Bearer token", func() { - BeforeEach(func() { // Prepare test data // #nosec: G304: Potential file inclusion via variable data, err := os.ReadFile("../grpc/testdata/valid_jwt_as_string.json") Expect(err).To(Succeed()) // Quickly parse JSON to avoid hardcoded values - jsonData := make(map[string]interface{}) + jsonData := make(map[string]any) err = json.Unmarshal(data, &jsonData) Expect(err).To(Succeed()) diff --git a/test/matchers.go b/test/matchers.go index ca6bd07a..889508af 100644 --- a/test/matchers.go +++ b/test/matchers.go @@ -58,7 +58,7 @@ func MatchErrorCode(errorCode codes.Code) types.GomegaMatcher { // // Error must be google.golang.org/grpc/status.Error // It is an error for err to be nil or an object that does not implement the Error interface. -func MatchStatusError(errorCode codes.Code, msg interface{}) types.GomegaMatcher { +func MatchStatusError(errorCode codes.Code, msg any) types.GomegaMatcher { switch m := msg.(type) { case string: return &MatchSDKStatusErrorMatcher{ @@ -85,7 +85,7 @@ func MatchStatusError(errorCode codes.Code, msg interface{}) types.GomegaMatcher } } -func (matcher *MatchSDKStatusErrorMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *MatchSDKStatusErrorMatcher) Match(actual any) (bool, error) { sdkError, ok := actual.(*errors.StatusError) if !ok { return false, fmt.Errorf("expected a SDK *errors.StatusError, got %T", actual) @@ -94,19 +94,19 @@ func (matcher *MatchSDKStatusErrorMatcher) Match(actual interface{}) (success bo if matcher.message == nil { return s.Code() == matcher.Expected, nil } - return matcher.message.Match(map[string]interface{}{ + return matcher.message.Match(map[string]any{ "Code": s.Code(), "Message": s.Message(), "Details": s.Details(), }) } -func (matcher *MatchSDKStatusErrorMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *MatchSDKStatusErrorMatcher) FailureMessage(actual any) string { if matcher.message == nil { return format.Message(status.Code(actual.(error)), "to match error", matcher.Expected) } return matcher.message.FailureMessage(actual) } -func (matcher *MatchSDKStatusErrorMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *MatchSDKStatusErrorMatcher) NegatedFailureMessage(actual any) string { if matcher.message == nil { return format.Message(status.Code(actual.(error)), "not to match error", matcher.Expected) } @@ -124,7 +124,7 @@ func MatchProtoMessage(message proto.Message) types.GomegaMatcher { } } -func (matcher *MatchProtoMessageMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *MatchProtoMessageMatcher) Match(actual any) (bool, error) { eq := &matchers.EqualMatcher{ Expected: matcher.Expected, } @@ -139,10 +139,10 @@ func (matcher *MatchProtoMessageMatcher) Match(actual interface{}) (success bool return proto.Equal(e, matcher.Expected), nil } -func (matcher *MatchProtoMessageMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *MatchProtoMessageMatcher) FailureMessage(actual any) string { return format.Message(actual, "to equal", matcher.Expected) } -func (matcher *MatchProtoMessageMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *MatchProtoMessageMatcher) NegatedFailureMessage(actual any) string { return format.Message(actual, "not to equal", matcher.Expected) } @@ -165,12 +165,12 @@ func (matcher *EqualProtoMatcher) GomegaString() string { return string(ex) } -func (matcher *EqualProtoMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *EqualProtoMatcher) Match(actual any) (bool, error) { if actual == nil && matcher.Expected == nil { //nolint:lll return false, fmt.Errorf("refusing to compare to .\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized") } - + var err error if a, ok := actual.(*anypb.Any); ok { var pa proto.Message pa, err = a.UnmarshalNew() @@ -187,7 +187,7 @@ func (matcher *EqualProtoMatcher) Match(actual interface{}) (success bool, err e return proto.Equal(pa, matcher.Expected), nil } -func (matcher *EqualProtoMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *EqualProtoMatcher) FailureMessage(actual any) string { actualMessage, actualOK := actual.(proto.Message) if actualOK { op := protojson.MarshalOptions{AllowPartial: true} @@ -205,7 +205,7 @@ func (matcher *EqualProtoMatcher) FailureMessage(actual interface{}) (message st return format.Message(actual, "to equal", matcher.Expected) } -func (matcher *EqualProtoMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *EqualProtoMatcher) NegatedFailureMessage(actual any) string { actualMessage, actualOK := actual.(proto.Message) if actualOK { op := protojson.MarshalOptions{AllowPartial: true} @@ -236,7 +236,7 @@ type EqualAnyProtoMatcher struct { actual proto.Message } -func (matcher *EqualAnyProtoMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *EqualAnyProtoMatcher) Match(actual any) (bool, error) { if actual == nil && matcher.Expected == nil { //nolint:lll return false, fmt.Errorf("refusing to compare to .\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized") @@ -246,7 +246,7 @@ func (matcher *EqualAnyProtoMatcher) Match(actual interface{}) (success bool, er if !ok { return false, fmt.Errorf("expected a proto.Message. Got:\n%s", format.Object(actual, 1)) } - + var err error matcher.actual, err = a.UnmarshalNew() if err != nil { return false, err @@ -254,7 +254,7 @@ func (matcher *EqualAnyProtoMatcher) Match(actual interface{}) (success bool, er return proto.Equal(matcher.actual, matcher.Expected), nil } -func (matcher *EqualAnyProtoMatcher) FailureMessage(interface{}) (message string) { +func (matcher *EqualAnyProtoMatcher) FailureMessage(any) string { // This function does not display if the type is different!! op := protojson.MarshalOptions{AllowPartial: true} ac, _ := op.Marshal(matcher.actual) @@ -262,7 +262,7 @@ func (matcher *EqualAnyProtoMatcher) FailureMessage(interface{}) (message string return format.MessageWithDiff(string(ac), "to equal", string(ex)) } -func (matcher *EqualAnyProtoMatcher) NegatedFailureMessage(interface{}) (message string) { +func (matcher *EqualAnyProtoMatcher) NegatedFailureMessage(any) string { // This function does not display if the type is different!! op := protojson.MarshalOptions{AllowPartial: true} ac, _ := op.Marshal(matcher.actual) @@ -275,9 +275,9 @@ type MatchJSONMatcher struct { } // MatchJSON uses the expected value to build a value matcher. -func MatchJSON(expected interface{}) types.GomegaMatcher { +func MatchJSON(expected any) types.GomegaMatcher { var ( - m interface{} + m any err error ) switch v := expected.(type) { @@ -300,8 +300,9 @@ func MatchJSON(expected interface{}) types.GomegaMatcher { return &MatchJSONMatcher{GomegaMatcher: valueMatcher(m)} } -func (matcher *MatchJSONMatcher) Match(actual interface{}) (success bool, err error) { - var aval interface{} +func (matcher *MatchJSONMatcher) Match(actual any) (bool, error) { + var aval any + var err error switch v := actual.(type) { case string: err = json.Unmarshal([]byte(v), &aval) @@ -320,7 +321,7 @@ func (matcher *MatchJSONMatcher) Match(actual interface{}) (success bool, err er return matcher.GomegaMatcher.Match(aval) } -func valueMatcher(v interface{}) types.GomegaMatcher { +func valueMatcher(v any) types.GomegaMatcher { switch jv := v.(type) { case nil: return gomega.BeNil() @@ -329,13 +330,13 @@ func valueMatcher(v interface{}) types.GomegaMatcher { return gomega.BeTrue() } return gomega.BeFalse() - case map[string]interface{}: - keys := map[interface{}]types.GomegaMatcher{} + case map[string]any: + keys := map[any]types.GomegaMatcher{} for k, mv := range jv { keys[k] = valueMatcher(mv) } return gstruct.MatchAllKeys(keys) - case []interface{}: + case []any: m := &matchers.ConsistOfMatcher{} for _, sv := range jv { m.Elements = append(m.Elements, valueMatcher(sv)) @@ -352,20 +353,20 @@ type matcherWrapper struct { matcher types.GomegaMatcher // This is used to save variable between calls to Matches and String in case of error // to be able to print better messages on failure - actual interface{} + actual any } func WrapMatcher(matcher types.GomegaMatcher) gomock.Matcher { return &matcherWrapper{matcher: matcher} } -func (m *matcherWrapper) Matches(x interface{}) (ok bool) { +func (m *matcherWrapper) Matches(x any) bool { m.actual = x - var err error - if ok, err = m.matcher.Match(x); err != nil { + ok, err := m.matcher.Match(x) + if err != nil { ok = false } - return + return ok } func (m *matcherWrapper) String() string {