From ac03e733b1bf01fc5e62d3d2dddd3e23c49f7744 Mon Sep 17 00:00:00 2001 From: Matt Dale <9760375+matthewdale@users.noreply.github.com> Date: Wed, 4 Sep 2024 18:05:19 -0700 Subject: [PATCH] GODRIVER-3324 Upgrade CI Go to 1.22 and golangci-lint to 1.59.1. (#1783) --- .evergreen/config.yml | 114 +++++++------- .golangci.yml | 21 ++- .pre-commit-config.yaml | 2 +- Makefile | 2 +- README.md | 2 +- bson/bson_corpus_spec_test.go | 9 +- bson/bsoncodec/bsoncodec_test.go | 4 +- bson/bsoncodec/default_value_encoders_test.go | 4 +- bson/bsoncodec/registry_examples_test.go | 8 +- bson/bsoncodec/registry_test.go | 4 +- bson/bsonrw/extjson_parser.go | 2 +- bson/bsonrw/extjson_writer.go | 13 +- bson/bsonrw/json_scanner.go | 37 +++-- bson/bsonrw/value_writer.go | 2 +- bson/mgocompat/bson_test.go | 4 +- bson/primitive/decimal.go | 6 +- bson/unmarshal_test.go | 10 +- cmd/build-oss-fuzz-corpus/main.go | 20 +-- cmd/parse-api-report/main.go | 10 +- cmd/testentauth/main.go | 8 +- cmd/testoidcauth/main.go | 144 +++++++++--------- docs/CONTRIBUTING.md | 4 +- examples/_logger/zap/go.mod | 2 +- examples/_logger/zerolog/go.mod | 2 +- .../documentation_examples/examples_test.go | 4 +- internal/integtest/integtest.go | 7 +- internal/test/faas/awslambda/mongodb/go.mod | 2 +- mongo/client_examples_test.go | 28 ++-- mongo/client_side_encryption_examples_test.go | 24 +-- mongo/crud_examples_test.go | 90 +++++------ mongo/cursor_test.go | 5 - mongo/description/selector_test.go | 8 +- mongo/description/server.go | 18 ++- mongo/gridfs/bucket.go | 2 +- mongo/gridfs/gridfs_examples_test.go | 32 ++-- mongo/integration/clam_prose_test.go | 2 +- mongo/integration/crud_helpers_test.go | 6 +- mongo/integration/errors_test.go | 6 +- mongo/integration/main_test.go | 4 +- mongo/integration/mtest/mongotest.go | 2 +- mongo/integration/mtest/setup.go | 7 +- .../retryable_writes_prose_test.go | 2 +- mongo/integration/sdam_prose_test.go | 4 +- mongo/integration/unified/logger.go | 2 +- mongo/integration/unified/main_test.go | 4 +- mongo/integration/unified/matches.go | 3 +- .../unified/testrunner_operation.go | 2 +- mongo/options/clientoptions.go | 5 +- mongo/options/example_test.go | 4 +- mongo/options/serverapioptions.go | 3 +- mongo/with_transactions_test.go | 8 +- x/bsonx/bsoncore/document_sequence_test.go | 10 +- x/bsonx/bsoncore/element.go | 8 +- x/bsonx/bsoncore/value.go | 13 +- x/mongo/driver/auth/auth_test.go | 23 ++- x/mongo/driver/auth/mongodbcr_test.go | 10 +- x/mongo/driver/auth/oidc.go | 4 +- x/mongo/driver/auth/plain_test.go | 18 +-- x/mongo/driver/batch_cursor.go | 12 +- x/mongo/driver/connstring/connstring.go | 13 +- x/mongo/driver/errors.go | 2 +- x/mongo/driver/integration/aggregate_test.go | 6 +- x/mongo/driver/operation.go | 3 +- x/mongo/driver/operation/command.go | 2 +- x/mongo/driver/operation/delete.go | 3 +- x/mongo/driver/operation/distinct.go | 3 +- x/mongo/driver/operation/drop_indexes.go | 9 +- x/mongo/driver/operation/drop_search_index.go | 3 +- x/mongo/driver/operation/insert.go | 3 +- .../driver/operation/update_search_index.go | 3 +- x/mongo/driver/operation_test.go | 8 +- x/mongo/driver/session/client_session.go | 16 +- x/mongo/driver/topology/CMAP_spec_test.go | 2 +- x/mongo/driver/topology/connection_test.go | 2 +- x/mongo/driver/topology/pool_test.go | 19 +-- x/mongo/driver/topology/sdam_spec_test.go | 2 +- x/mongo/driver/topology/server.go | 2 +- x/mongo/driver/topology/server_test.go | 10 +- x/mongo/driver/topology/topology_options.go | 6 +- x/mongo/driver/topology/topology_test.go | 2 +- 80 files changed, 464 insertions(+), 471 deletions(-) diff --git a/.evergreen/config.yml b/.evergreen/config.yml index 0ca823056f..b328d471eb 100644 --- a/.evergreen/config.yml +++ b/.evergreen/config.yml @@ -2090,81 +2090,81 @@ axes: - id: os-ssl-32 display_name: OS values: - - id: "windows-64-go-1-20" + - id: "windows-64" display_name: "Windows 64-bit" run_on: - windows-vsCurrent-small variables: GCC_PATH: "/cygdrive/c/ProgramData/chocolatey/lib/mingw/tools/install/mingw64/bin" - GO_DIST: "C:\\golang\\go1.20" + GO_DIST: "C:\\golang\\go1.22" VENV_BIN_DIR: "Scripts" - - id: "rhel87-64-go-1-20" + - id: "rhel87-64" display_name: "RHEL 8.7" run_on: rhel8.7-large variables: - GO_DIST: "/opt/golang/go1.20" - - id: "macos11-go-1-20" + GO_DIST: "/opt/golang/go1.22" + - id: "macos11" display_name: "MacOS 11.0" run_on: macos-1100 batchtime: 1440 # Run at most once per 24 hours. variables: - GO_DIST: "/opt/golang/go1.20" + GO_DIST: "/opt/golang/go1.22" # OSes that require >= 4.0 for SSL - id: os-ssl-40 display_name: OS values: - - id: "windows-64-go-1-20" + - id: "windows-64" display_name: "Windows 64-bit" run_on: - windows-vsCurrent-small variables: GCC_PATH: "/cygdrive/c/ProgramData/chocolatey/lib/mingw/tools/install/mingw64/bin" - GO_DIST: "C:\\golang\\go1.20" + GO_DIST: "C:\\golang\\go1.22" VENV_BIN_DIR: "Scripts" - - id: "rhel87-64-go-1-20" + - id: "rhel87-64" display_name: "RHEL 8.7" run_on: rhel8.7-large variables: - GO_DIST: "/opt/golang/go1.20" - - id: "macos11-go-1-20" + GO_DIST: "/opt/golang/go1.22" + - id: "macos11" display_name: "MacOS 11.0" run_on: macos-1100 batchtime: 1440 # Run at most once per 24 hours. variables: - GO_DIST: "/opt/golang/go1.20" + GO_DIST: "/opt/golang/go1.22" - id: ocsp-rhel-87 display_name: OS values: - - id: "rhel87-go-1-20" + - id: "rhel87" display_name: "RHEL 8.7" run_on: rhel8.7-large variables: - GO_DIST: "/opt/golang/go1.20" + GO_DIST: "/opt/golang/go1.22" - id: os-aws-auth display_name: OS values: - - id: "windows-64-vsCurrent-latest-small-go-1-20" + - id: "windows-64-vsCurrent-latest-small" display_name: "Windows 64-bit" run_on: - windows-vsCurrent-small variables: GCC_PATH: "/cygdrive/c/ProgramData/chocolatey/lib/mingw/tools/install/mingw64/bin" - GO_DIST: "C:\\golang\\go1.20" + GO_DIST: "C:\\golang\\go1.22" SKIP_ECS_AUTH_TEST: true - - id: "ubuntu2004-64-go-1-20" + - id: "ubuntu2004-64" display_name: "Ubuntu 20.04" run_on: ubuntu2004-test variables: - GO_DIST: "/opt/golang/go1.20" - - id: "macos11-go-1-20" + GO_DIST: "/opt/golang/go1.22" + - id: "macos11" display_name: "MacOS 11.0" run_on: macos-1100 batchtime: 1440 # Run at most once per 24 hours. variables: - GO_DIST: "/opt/golang/go1.20" + GO_DIST: "/opt/golang/go1.22" SKIP_ECS_AUTH_TEST: true SKIP_EC2_AUTH_TEST: true SKIP_WEB_IDENTITY_AUTH_TEST: true @@ -2172,20 +2172,20 @@ axes: - id: os-faas-80 display_name: OS values: - - id: "rhel87-large-go-1-20" + - id: "rhel87-large" display_name: "RHEL 8.7" run_on: rhel8.7-large variables: - GO_DIST: "/opt/golang/go1.20" + GO_DIST: "/opt/golang/go1.22" - id: os-serverless display_name: OS values: - - id: "rhel87-go-1-20" + - id: "rhel87" display_name: "RHEL 8.7" run_on: rhel8.7-small variables: - GO_DIST: "/opt/golang/go1.20" + GO_DIST: "/opt/golang/go1.22" task_groups: - name: serverless_task_group @@ -2470,7 +2470,7 @@ buildvariants: run_on: - rhel8.7-large expansions: - GO_DIST: "/opt/golang/go1.20" + GO_DIST: "/opt/golang/go1.22" tasks: - name: ".static-analysis" @@ -2480,7 +2480,7 @@ buildvariants: run_on: - rhel8.7-small expansions: - GO_DIST: "/opt/golang/go1.20" + GO_DIST: "/opt/golang/go1.22" tasks: - name: "pull-request-helpers" @@ -2489,7 +2489,7 @@ buildvariants: run_on: - rhel8.7-large expansions: - GO_DIST: "/opt/golang/go1.20" + GO_DIST: "/opt/golang/go1.22" tasks: - name: ".performance" @@ -2499,7 +2499,7 @@ buildvariants: run_on: - rhel8.7-large expansions: - GO_DIST: "/opt/golang/go1.20" + GO_DIST: "/opt/golang/go1.22" tasks: - name: ".compile-check" @@ -2508,7 +2508,7 @@ buildvariants: run_on: - rhel8.7-large expansions: - GO_DIST: "/opt/golang/go1.20" + GO_DIST: "/opt/golang/go1.22" tasks: - name: "backport-pr" @@ -2518,7 +2518,7 @@ buildvariants: run_on: - rhel8.7-large expansions: - GO_DIST: "/opt/golang/go1.20" + GO_DIST: "/opt/golang/go1.22" tasks: - name: "atlas-test" @@ -2528,7 +2528,7 @@ buildvariants: run_on: - ubuntu2004-large expansions: - GO_DIST: "/opt/golang/go1.20" + GO_DIST: "/opt/golang/go1.22" tasks: - name: "test-atlas-data-lake" @@ -2538,58 +2538,58 @@ buildvariants: run_on: - ubuntu2204-large expansions: - GO_DIST: "/opt/golang/go1.20" + GO_DIST: "/opt/golang/go1.22" tasks: - name: "test-docker-runner" - matrix_name: "tests-rhel-36-with-zlib-support" tags: ["pullrequest"] - matrix_spec: { version: ["3.6"], os-ssl-32: ["rhel87-64-go-1-20"] } + matrix_spec: { version: ["3.6"], os-ssl-32: ["rhel87-64"] } display_name: "${version} ${os-ssl-32}" tasks: - name: ".test !.enterprise-auth !.snappy !.zstd" - matrix_name: "tests-windows-36-with-zlib-support" - matrix_spec: { version: ["3.6"], os-ssl-32: ["windows-64-go-1-20"] } + matrix_spec: { version: ["3.6"], os-ssl-32: ["windows-64"] } display_name: "${version} ${os-ssl-32}" tasks: - name: ".test !.enterprise-auth !.snappy !.zstd" - matrix_name: "tests-rhel-40-with-zlib-support" tags: ["pullrequest"] - matrix_spec: { version: ["4.0"], os-ssl-40: ["rhel87-64-go-1-20"] } + matrix_spec: { version: ["4.0"], os-ssl-40: ["rhel87-64"] } display_name: "${version} ${os-ssl-40}" tasks: - name: ".test !.enterprise-auth !.snappy !.zstd" - matrix_name: "tests-windows-40-with-zlib-support" - matrix_spec: { version: ["4.0"], os-ssl-40: ["windows-64-go-1-20"] } + matrix_spec: { version: ["4.0"], os-ssl-40: ["windows-64"] } display_name: "${version} ${os-ssl-40}" tasks: - name: ".test !.enterprise-auth !.snappy !.zstd" - matrix_name: "tests-rhel-42-plus-zlib-zstd-support" tags: ["pullrequest"] - matrix_spec: { version: ["4.2", "4.4", "5.0", "6.0", "7.0", "8.0"], os-ssl-40: ["rhel87-64-go-1-20"] } + matrix_spec: { version: ["4.2", "4.4", "5.0", "6.0", "7.0", "8.0"], os-ssl-40: ["rhel87-64"] } display_name: "${version} ${os-ssl-40}" tasks: - name: ".test !.enterprise-auth !.snappy" - matrix_name: "tests-windows-42-plus-zlib-zstd-support" - matrix_spec: { version: ["4.2", "4.4", "5.0", "6.0", "7.0"], os-ssl-40: ["windows-64-go-1-20"] } + matrix_spec: { version: ["4.2", "4.4", "5.0", "6.0", "7.0"], os-ssl-40: ["windows-64"] } display_name: "${version} ${os-ssl-40}" tasks: - name: ".test !.enterprise-auth !.snappy" - matrix_name: "tests-windows-80-zlib-zstd-support" tags: ["pullrequest"] - matrix_spec: { version: ["8.0"], os-ssl-40: ["windows-64-go-1-20"] } + matrix_spec: { version: ["8.0"], os-ssl-40: ["windows-64"] } display_name: "${version} ${os-ssl-40}" tasks: - name: ".test !.enterprise-auth !.snappy" - matrix_name: "tests-latest-zlib-zstd-support" - matrix_spec: { version: ["latest"], os-ssl-40: ["windows-64-go-1-20", "rhel87-64-go-1-20"] } + matrix_spec: { version: ["latest"], os-ssl-40: ["windows-64", "rhel87-64"] } display_name: "${version} ${os-ssl-40}" tasks: - name: ".test !.enterprise-auth !.snappy" @@ -2607,14 +2607,14 @@ buildvariants: - name: "aws-auth-test" - matrix_name: "ocsp-test" - matrix_spec: { version: ["4.4", "5.0", "6.0", "7.0", "8.0", "latest"], ocsp-rhel-87: ["rhel87-go-1-20"] } + matrix_spec: { version: ["4.4", "5.0", "6.0", "7.0", "8.0", "latest"], ocsp-rhel-87: ["rhel87"] } display_name: "OCSP ${version} ${ocsp-rhel-87}" batchtime: 20160 # Use a batchtime of 14 days as suggested by the OCSP test README tasks: - name: ".ocsp" - matrix_name: "ocsp-test-windows" - matrix_spec: { version: ["4.4", "5.0", "6.0", "7.0", "8.0", "latest"], os-ssl-40: ["windows-64-go-1-20"] } + matrix_spec: { version: ["4.4", "5.0", "6.0", "7.0", "8.0", "latest"], os-ssl-40: ["windows-64"] } display_name: "OCSP ${version} ${os-ssl-40}" batchtime: 20160 # Use a batchtime of 14 days as suggested by the OCSP test README tasks: @@ -2622,7 +2622,7 @@ buildvariants: - name: ".ocsp-rsa !.ocsp-staple" - matrix_name: "ocsp-test-macos" - matrix_spec: { version: ["4.4", "5.0", "6.0", "7.0", "8.0", "latest"], os-ssl-40: ["macos11-go-1-20"] } + matrix_spec: { version: ["4.4", "5.0", "6.0", "7.0", "8.0", "latest"], os-ssl-40: ["macos11"] } display_name: "OCSP ${version} ${os-ssl-40}" batchtime: 20160 # Use a batchtime of 14 days as suggested by the OCSP test README tasks: @@ -2631,39 +2631,39 @@ buildvariants: - matrix_name: "race-test" tags: ["pullrequest"] - matrix_spec: { version: ["7.0"], os-ssl-40: ["rhel87-64-go-1-20"] } + matrix_spec: { version: ["7.0"], os-ssl-40: ["rhel87-64"] } display_name: "Race Detector Test" tasks: - name: ".race" - matrix_name: "versioned-api-test" tags: ["pullrequest"] - matrix_spec: { version: ["5.0", "6.0", "7.0", "8.0"], os-ssl-40: ["windows-64-go-1-20", "rhel87-64-go-1-20"] } + matrix_spec: { version: ["5.0", "6.0", "7.0", "8.0"], os-ssl-40: ["windows-64", "rhel87-64"] } display_name: "API Version ${version} ${os-ssl-40}" tasks: - name: ".versioned-api" - matrix_name: "versioned-api-latest-test" - matrix_spec: { version: ["latest"], os-ssl-40: ["windows-64-go-1-20", "rhel87-64-go-1-20"] } + matrix_spec: { version: ["latest"], os-ssl-40: ["windows-64", "rhel87-64"] } display_name: "API Version ${version} ${os-ssl-40}" tasks: - name: ".versioned-api" - matrix_name: "kms-tls-test" - matrix_spec: { version: ["7.0"], os-ssl-40: ["rhel87-64-go-1-20"] } + matrix_spec: { version: ["7.0"], os-ssl-40: ["rhel87-64"] } display_name: "KMS TLS ${os-ssl-40}" tasks: - name: ".kms-tls" - matrix_name: "load-balancer-test" tags: ["pullrequest"] - matrix_spec: { version: ["5.0", "6.0", "7.0", "8.0"], os-ssl-40: ["rhel87-64-go-1-20"] } + matrix_spec: { version: ["5.0", "6.0", "7.0", "8.0"], os-ssl-40: ["rhel87-64"] } display_name: "Load Balancer Support ${version} ${os-ssl-40}" tasks: - name: ".load-balancer" - matrix_name: "load-balancer-latest-test" - matrix_spec: { version: ["latest"], os-ssl-40: ["rhel87-64-go-1-20"] } + matrix_spec: { version: ["latest"], os-ssl-40: ["rhel87-64"] } display_name: "Load Balancer Support ${version} ${os-ssl-40}" tasks: - name: ".load-balancer" @@ -2676,26 +2676,26 @@ buildvariants: - "serverless_task_group" - matrix_name: "kms-kmip-test" - matrix_spec: { version: ["7.0"], os-ssl-40: ["rhel87-64-go-1-20"] } + matrix_spec: { version: ["7.0"], os-ssl-40: ["rhel87-64"] } display_name: "KMS KMIP ${os-ssl-40}" tasks: - name: ".kms-kmip" - matrix_name: "fuzz-test" - matrix_spec: { version: ["5.0"], os-ssl-40: ["rhel87-64-go-1-20"] } + matrix_spec: { version: ["5.0"], os-ssl-40: ["rhel87-64"] } display_name: "Fuzz ${version} ${os-ssl-40}" tasks: - name: "test-fuzz" batchtime: 1440 # Run at most once per 24 hours. - matrix_name: "faas-test" - matrix_spec: { version: ["7.0"], os-faas-80: ["rhel87-large-go-1-20"] } + matrix_spec: { version: ["7.0"], os-faas-80: ["rhel87-large"] } display_name: "FaaS ${version} ${os-faas-80}" tasks: - test-aws-lambda-task-group - matrix_name: "searchindex-test" - matrix_spec: { version: ["7.0"], os-faas-80: ["rhel87-large-go-1-20"] } + matrix_spec: { version: ["7.0"], os-faas-80: ["rhel87-large"] } display_name: "Search Index ${version} ${os-faas-80}" tasks: - test-search-index-task-group @@ -2705,7 +2705,7 @@ buildvariants: run_on: - rhel8.7-small expansions: - GO_DIST: "/opt/golang/go1.20" + GO_DIST: "/opt/golang/go1.22" tasks: - name: testgcpkms_task_group batchtime: 20160 # Use a batchtime of 14 days as suggested by the CSFLE test README @@ -2716,7 +2716,7 @@ buildvariants: run_on: - rhel8.7-small expansions: - GO_DIST: "/opt/golang/go1.20" + GO_DIST: "/opt/golang/go1.22" tasks: - testawskms-task - testawskms-fail-task @@ -2726,7 +2726,7 @@ buildvariants: run_on: - rhel8.7-small expansions: - GO_DIST: "/opt/golang/go1.20" + GO_DIST: "/opt/golang/go1.22" tasks: - name: testazurekms_task_group batchtime: 20160 # Use a batchtime of 14 days as suggested by the CSFLE test README @@ -2737,7 +2737,7 @@ buildvariants: run_on: - ubuntu2204-large expansions: - GO_DIST: "/opt/golang/go1.20" + GO_DIST: "/opt/golang/go1.22" tasks: - name: testoidc_task_group batchtime: 20160 # Use a batchtime of 14 days as suggested by the CSFLE test README diff --git a/.golangci.yml b/.golangci.yml index 9075b9321d..b3c66c4d7d 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,12 +1,5 @@ run: timeout: 5m - skip-dirs-use-default: false - skip-dirs: - - (^|/)vendor($|/) - - (^|/)testdata($|/) - - (^|/)etc($|/) - # Disable all linters for "golang.org/x/exp/rand" package in internal/rand. - - internal/rand linters: disable-all: true @@ -35,11 +28,7 @@ linters: linters-settings: errcheck: - exclude: .errcheck-excludes - gocritic: - enabled-checks: - # Detects suspicious append result assignments. E.g. "b := append(a, 1, 2, 3)" - - appendAssign + exclude-functions: .errcheck-excludes govet: disable: - cgocall @@ -55,6 +44,14 @@ linters-settings: ] issues: + exclude-dirs-use-default: false + exclude-dirs: + - (^|/)testdata($|/) + - (^|/)etc($|/) + # Disable all linters for copied third-party code. + - internal/rand + - internal/aws + - internal/assert exclude-use-default: false exclude: # Add all default excluded issues except issues related to exported types/functions not having diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index d28a2056d9..1c7e4b60fe 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -51,6 +51,6 @@ repos: exclude: ^(vendor) - repo: https://github.com/golangci/golangci-lint - rev: v1.55.1 + rev: v1.59.1 hooks: - id: golangci-lint diff --git a/Makefile b/Makefile index 76715bddbc..8922d4d82c 100644 --- a/Makefile +++ b/Makefile @@ -72,7 +72,7 @@ fmt: .PHONY: install-golangci-lint install-golangci-lint: - go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.52.2 + go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.59.1 # Lint with various GOOS and GOARCH targets to catch static analysis failures that may only affect # specific operating systems or architectures. For example, staticcheck will only check for 64-bit diff --git a/README.md b/README.md index 7a709fc010..35f54db219 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ ______________________________________________________________________ ## Requirements - Go 1.18 or higher. We aim to support the latest versions of Go. -- Go 1.20 or higher is required to run the driver test suite. +- Go 1.22 or higher is required to run the driver test suite. - MongoDB 3.6 and higher. ______________________________________________________________________ diff --git a/bson/bson_corpus_spec_test.go b/bson/bson_corpus_spec_test.go index 8a27b06272..74d2338abf 100644 --- a/bson/bson_corpus_spec_test.go +++ b/bson/bson_corpus_spec_test.go @@ -187,13 +187,14 @@ func unescapeUnicode(s, bsonType string) string { func formatDouble(f float64) string { var s string - if math.IsInf(f, 1) { + switch { + case math.IsInf(f, 1): s = "Infinity" - } else if math.IsInf(f, -1) { + case math.IsInf(f, -1): s = "-Infinity" - } else if math.IsNaN(f) { + case math.IsNaN(f): s = "NaN" - } else { + default: // Print exactly one decimalType place for integers; otherwise, print as many are necessary to // perfectly represent it. s = strconv.FormatFloat(f, 'G', -1, 64) diff --git a/bson/bsoncodec/bsoncodec_test.go b/bson/bsoncodec/bsoncodec_test.go index 2051b08539..1194539ba7 100644 --- a/bson/bsoncodec/bsoncodec_test.go +++ b/bson/bsoncodec/bsoncodec_test.go @@ -18,7 +18,7 @@ import ( ) func ExampleValueEncoder() { - var _ ValueEncoderFunc = func(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + var _ ValueEncoderFunc = func(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { if val.Kind() != reflect.String { return ValueEncoderError{Name: "StringEncodeValue", Kinds: []reflect.Kind{reflect.String}, Received: val} } @@ -28,7 +28,7 @@ func ExampleValueEncoder() { } func ExampleValueDecoder() { - var _ ValueDecoderFunc = func(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + var _ ValueDecoderFunc = func(_ DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { if !val.CanSet() || val.Kind() != reflect.String { return ValueDecoderError{Name: "StringDecodeValue", Kinds: []reflect.Kind{reflect.String}, Received: val} } diff --git a/bson/bsoncodec/default_value_encoders_test.go b/bson/bsoncodec/default_value_encoders_test.go index 12410a0b19..36a7e42cd5 100644 --- a/bson/bsoncodec/default_value_encoders_test.go +++ b/bson/bsoncodec/default_value_encoders_test.go @@ -1159,7 +1159,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "WriteArrayElement Error", - bsoncore.Array(buildDocumentArray(func(doc []byte) []byte { + bsoncore.Array(buildDocumentArray(func([]byte) []byte { return bsoncore.AppendNullElement(nil, "foo") })), nil, @@ -1169,7 +1169,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "encodeValue error", - bsoncore.Array(buildDocumentArray(func(doc []byte) []byte { + bsoncore.Array(buildDocumentArray(func([]byte) []byte { return bsoncore.AppendNullElement(nil, "foo") })), nil, diff --git a/bson/bsoncodec/registry_examples_test.go b/bson/bsoncodec/registry_examples_test.go index 9dc72bd503..bf039d02bf 100644 --- a/bson/bsoncodec/registry_examples_test.go +++ b/bson/bsoncodec/registry_examples_test.go @@ -25,7 +25,7 @@ func ExampleRegistry_customEncoder() { negatedIntType := reflect.TypeOf(negatedInt(0)) negatedIntEncoder := func( - ec bsoncodec.EncodeContext, + _ bsoncodec.EncodeContext, vw bsonrw.ValueWriter, val reflect.Value, ) error { @@ -83,7 +83,7 @@ func ExampleRegistry_customDecoder() { lenientBoolType := reflect.TypeOf(lenientBool(true)) lenientBoolDecoder := func( - dc bsoncodec.DecodeContext, + _ bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value, ) error { @@ -160,7 +160,7 @@ func ExampleRegistry_RegisterKindEncoder() { // encoder for kind reflect.Int32. That way, even user-defined types with // underlying type int32 will be encoded as a BSON int64. int32To64Encoder := func( - ec bsoncodec.EncodeContext, + _ bsoncodec.EncodeContext, vw bsonrw.ValueWriter, val reflect.Value, ) error { @@ -215,7 +215,7 @@ func ExampleRegistry_RegisterKindDecoder() { // "kind" decoder for kind reflect.Int64. That way, we can even decode to // user-defined types with underlying type int64. flexibleInt64KindDecoder := func( - dc bsoncodec.DecodeContext, + _ bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value, ) error { diff --git a/bson/bsoncodec/registry_test.go b/bson/bsoncodec/registry_test.go index 03500dca44..20f85a9a2d 100644 --- a/bson/bsoncodec/registry_test.go +++ b/bson/bsoncodec/registry_test.go @@ -338,7 +338,7 @@ func TestRegistryBuilder(t *testing.T) { } allowunexported := cmp.AllowUnexported(fakeCodec{}, fakeStructCodec{}, fakeSliceCodec{}, fakeMapCodec{}) - comparepc := func(pc1, pc2 *PointerCodec) bool { return true } + comparepc := func(pc1, pc2 *PointerCodec) bool { return pc1 == pc2 } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { t.Run("Encoder", func(t *testing.T) { @@ -754,7 +754,7 @@ func TestRegistry(t *testing.T) { } allowunexported := cmp.AllowUnexported(fakeCodec{}, fakeStructCodec{}, fakeSliceCodec{}, fakeMapCodec{}) - comparepc := func(pc1, pc2 *PointerCodec) bool { return true } + comparepc := func(pc1, pc2 *PointerCodec) bool { return pc1 == pc2 } for _, tc := range testCases { tc := tc diff --git a/bson/bsonrw/extjson_parser.go b/bson/bsonrw/extjson_parser.go index bb52a0ec3d..f0702d9d30 100644 --- a/bson/bsonrw/extjson_parser.go +++ b/bson/bsonrw/extjson_parser.go @@ -305,7 +305,7 @@ func (ejp *extJSONParser) readValue(t bsontype.Type) (*extJSONValue, error) { } // remove hyphens - uuidNoHyphens := strings.Replace(uuid, "-", "", -1) + uuidNoHyphens := strings.ReplaceAll(uuid, "-", "") if len(uuidNoHyphens) != 32 { return nil, fmt.Errorf("$uuid value does not follow RFC 4122 format regarding length and hyphens") } diff --git a/bson/bsonrw/extjson_writer.go b/bson/bsonrw/extjson_writer.go index bb9303167c..57781ff9f3 100644 --- a/bson/bsonrw/extjson_writer.go +++ b/bson/bsonrw/extjson_writer.go @@ -628,13 +628,14 @@ func (ejvw *extJSONValueWriter) WriteArrayEnd() error { func formatDouble(f float64) string { var s string - if math.IsInf(f, 1) { + switch { + case math.IsInf(f, 1): s = "Infinity" - } else if math.IsInf(f, -1) { + case math.IsInf(f, -1): s = "-Infinity" - } else if math.IsNaN(f) { + case math.IsNaN(f): s = "NaN" - } else { + default: // Print exactly one decimalType place for integers; otherwise, print as many are necessary to // perfectly represent it. s = strconv.FormatFloat(f, 'G', -1, 64) @@ -739,9 +740,7 @@ func (ss sortableString) Less(i, j int) bool { } func (ss sortableString) Swap(i, j int) { - oldI := ss[i] - ss[i] = ss[j] - ss[j] = oldI + ss[i], ss[j] = ss[j], ss[i] } func sortStringAlphebeticAscending(s string) string { diff --git a/bson/bsonrw/json_scanner.go b/bson/bsonrw/json_scanner.go index 43f3e4f383..9782891916 100644 --- a/bson/bsonrw/json_scanner.go +++ b/bson/bsonrw/json_scanner.go @@ -82,12 +82,13 @@ func (js *jsonScanner) nextToken() (*jsonToken, error) { return js.scanString() default: // check if it's a number - if c == '-' || isDigit(c) { + switch { + case c == '-' || isDigit(c): return js.scanNumber(c) - } else if c == 't' || c == 'f' || c == 'n' { + case c == 't' || c == 'f' || c == 'n': // maybe a literal return js.scanLiteral(c) - } else { + default: return nil, fmt.Errorf("invalid JSON input. Position: %d. Character: %c", js.pos-1, c) } } @@ -174,7 +175,7 @@ func getu4(s []byte) rune { for _, c := range s[:4] { switch { case '0' <= c && c <= '9': - c = c - '0' + c -= '0' case 'a' <= c && c <= 'f': c = c - 'a' + 10 case 'A' <= c && c <= 'F': @@ -325,13 +326,14 @@ func (js *jsonScanner) scanLiteral(first byte) (*jsonToken, error) { c5, err := js.readNextByte() - if bytes.Equal([]byte("true"), lit) && (isValueTerminator(c5) || errors.Is(err, io.EOF)) { + switch { + case bytes.Equal([]byte("true"), lit) && (isValueTerminator(c5) || errors.Is(err, io.EOF)): js.pos = int(math.Max(0, float64(js.pos-1))) return &jsonToken{t: jttBool, v: true, p: p}, nil - } else if bytes.Equal([]byte("null"), lit) && (isValueTerminator(c5) || errors.Is(err, io.EOF)) { + case bytes.Equal([]byte("null"), lit) && (isValueTerminator(c5) || errors.Is(err, io.EOF)): js.pos = int(math.Max(0, float64(js.pos-1))) return &jsonToken{t: jttNull, v: nil, p: p}, nil - } else if bytes.Equal([]byte("fals"), lit) { + case bytes.Equal([]byte("fals"), lit): if c5 == 'e' { c5, err = js.readNextByte() @@ -430,12 +432,13 @@ func (js *jsonScanner) scanNumber(first byte) (*jsonToken, error) { case '}', ']', ',': s = nssDone default: - if isWhiteSpace(c) || errors.Is(err, io.EOF) { + switch { + case isWhiteSpace(c) || errors.Is(err, io.EOF): s = nssDone - } else if isDigit(c) { + case isDigit(c): s = nssSawIntegerDigits b.WriteByte(c) - } else { + default: s = nssInvalid } } @@ -455,12 +458,13 @@ func (js *jsonScanner) scanNumber(first byte) (*jsonToken, error) { case '}', ']', ',': s = nssDone default: - if isWhiteSpace(c) || errors.Is(err, io.EOF) { + switch { + case isWhiteSpace(c) || errors.Is(err, io.EOF): s = nssDone - } else if isDigit(c) { + case isDigit(c): s = nssSawFractionDigits b.WriteByte(c) - } else { + default: s = nssInvalid } } @@ -490,12 +494,13 @@ func (js *jsonScanner) scanNumber(first byte) (*jsonToken, error) { case '}', ']', ',': s = nssDone default: - if isWhiteSpace(c) || errors.Is(err, io.EOF) { + switch { + case isWhiteSpace(c) || errors.Is(err, io.EOF): s = nssDone - } else if isDigit(c) { + case isDigit(c): s = nssSawExponentDigits b.WriteByte(c) - } else { + default: s = nssInvalid } } diff --git a/bson/bsonrw/value_writer.go b/bson/bsonrw/value_writer.go index 311518a80d..501c6d7f97 100644 --- a/bson/bsonrw/value_writer.go +++ b/bson/bsonrw/value_writer.go @@ -598,7 +598,7 @@ func (vw *valueWriter) writeLength() error { return errMaxDocumentSizeExceeded{size: int64(len(vw.buf))} } frame := &vw.stack[vw.frame] - length = length - int(frame.start) + length -= int(frame.start) start := frame.start _ = vw.buf[start+3] // BCE diff --git a/bson/mgocompat/bson_test.go b/bson/mgocompat/bson_test.go index 45fb5b27f6..37ccb0e843 100644 --- a/bson/mgocompat/bson_test.go +++ b/bson/mgocompat/bson_test.go @@ -126,7 +126,7 @@ var allItems = []testItemType{ {bson.M{"_": primitive.Undefined{}}, // Obsolete, but still seen in the wild. "\x06_\x00"}, {bson.M{"_": primitive.ObjectID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B}}, - "\x07_\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B"}, //technically this is not the same as the original mgo test + "\x07_\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B"}, // technically this is not the same as the original mgo test {bson.M{"_": primitive.DBPointer{DB: "testnamespace", Pointer: primitive.ObjectID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B}}}, "\x0C_\x00\x0e\x00\x00\x00testnamespace\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B"}, {bson.M{"_": false}, @@ -1581,6 +1581,8 @@ var jsonIDTests = []struct { func TestObjectIdJSONMarshaling(t *testing.T) { for i, test := range jsonIDTests { + test := test // Capture range variable. + t.Run(strconv.Itoa(i), func(t *testing.T) { if test.marshal { data, err := json.Marshal(&test.value) diff --git a/bson/primitive/decimal.go b/bson/primitive/decimal.go index 08c39514be..db8be74d84 100644 --- a/bson/primitive/decimal.go +++ b/bson/primitive/decimal.go @@ -70,7 +70,6 @@ func (d Decimal128) String() string { // Bits: 1*sign 2*ignored 14*exponent 111*significand. // Implicit 0b100 prefix in significand. exp = int(d.h >> 47 & (1<<14 - 1)) - //high = 4<<47 | d.h&(1<<47-1) // Spec says all of these values are out of range. high, low = 0, 0 } else { @@ -152,13 +151,12 @@ func (d Decimal128) BigInt() (*big.Int, int, error) { // Bits: 1*sign 2*ignored 14*exponent 111*significand. // Implicit 0b100 prefix in significand. exp = int(high >> 47 & (1<<14 - 1)) - //high = 4<<47 | d.h&(1<<47-1) // Spec says all of these values are out of range. high, low = 0, 0 } else { // Bits: 1*sign 14*exponent 113*significand exp = int(high >> 49 & (1<<14 - 1)) - high = high & (1<<49 - 1) + high &= (1<<49 - 1) } exp += MinDecimal128Exp @@ -352,7 +350,7 @@ var ( // ParseDecimal128FromBigInt attempts to parse the given significand and exponent into a valid Decimal128 value. func ParseDecimal128FromBigInt(bi *big.Int, exp int) (Decimal128, bool) { - //copy + // copy bi = new(big.Int).Set(bi) q := new(big.Int) diff --git a/bson/unmarshal_test.go b/bson/unmarshal_test.go index 70f2c321d0..24e224fd68 100644 --- a/bson/unmarshal_test.go +++ b/bson/unmarshal_test.go @@ -612,7 +612,7 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { Foo: []byte{0, 1, 2, 3, 4, 5}, }, getByteSlice: func(val interface{}) []byte { - return (*(val.(*fooBytes))).Foo + return (val.(*fooBytes)).Foo }, }, { @@ -638,7 +638,7 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { Foo: myBytes{0, 1, 2, 3, 4, 5}, }, getByteSlice: func(val interface{}) []byte { - return (*(val.(*fooMyBytes))).Foo + return (val.(*fooMyBytes)).Foo }, }, { @@ -664,7 +664,7 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { Foo: primitive.Binary{Subtype: 0, Data: []byte{0, 1, 2, 3, 4, 5}}, }, getByteSlice: func(val interface{}) []byte { - return (*(val.(*fooBinary))).Foo.Data + return (val.(*fooBinary)).Foo.Data }, }, { @@ -690,7 +690,7 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { Foo: primitive.ObjectID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, }, getByteSlice: func(val interface{}) []byte { - return (*(val.(*fooObjectID))).Foo[:] + return (val.(*fooObjectID)).Foo[:] }, }, { @@ -723,7 +723,7 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { }, }, getByteSlice: func(val interface{}) []byte { - return (*(val.(*fooDBPointer))).Foo.Pointer[:] + return (val.(*fooDBPointer)).Foo.Pointer[:] }, }, { diff --git a/cmd/build-oss-fuzz-corpus/main.go b/cmd/build-oss-fuzz-corpus/main.go index 4dc014b5aa..416f90f491 100644 --- a/cmd/build-oss-fuzz-corpus/main.go +++ b/cmd/build-oss-fuzz-corpus/main.go @@ -79,7 +79,7 @@ func jsonToBytes(ej, ejType, testDesc string) ([]byte, error) { func seedExtJSON(zw *zip.Writer, extJSON string, extJSONType string, desc string) { jbytes, err := jsonToBytes(extJSON, extJSONType, desc) if err != nil { - log.Fatalf("failed to convert JSON to bytes: %v", err) + log.Panicf("failed to convert JSON to bytes: %v", err) } // Use a SHA256 hash of the BSON bytes for the filename. This isn't an oss-fuzz requirement, it @@ -88,12 +88,12 @@ func seedExtJSON(zw *zip.Writer, extJSON string, extJSONType string, desc string f, err := zw.Create(zipFile) if err != nil { - log.Fatalf("error creating zip file: %v", err) + log.Panicf("error creating zip file: %v", err) } _, err = f.Write(jbytes) if err != nil { - log.Fatalf("failed to write file: %s into zip file: %v", zipFile, err) + log.Panicf("failed to write file: %s into zip file: %v", zipFile, err) } } @@ -125,7 +125,7 @@ func seedTestCase(zw *zip.Writer, tcase []*validityTestCase) { func seedBSONCorpus(zw *zip.Writer) { fileNames, err := findJSONFilesInDir(dataDir) if err != nil { - log.Fatalf("failed to find JSON files in directory %q: %v", dataDir, err) + log.Panicf("failed to find JSON files in directory %q: %v", dataDir, err) } for _, fileName := range fileNames { @@ -133,7 +133,7 @@ func seedBSONCorpus(zw *zip.Writer) { file, err := os.Open(filePath) if err != nil { - log.Fatalf("failed to open file %q: %v", filePath, err) + log.Panicf("failed to open file %q: %v", filePath, err) } tc := struct { @@ -141,7 +141,7 @@ func seedBSONCorpus(zw *zip.Writer) { }{} if err := json.NewDecoder(file).Decode(&tc); err != nil { - log.Fatalf("failed to decode file %q: %v", filePath, err) + log.Panicf("failed to decode file %q: %v", filePath, err) } seedTestCase(zw, tc.Valid) @@ -153,18 +153,18 @@ func seedBSONCorpus(zw *zip.Writer) { func main() { seedCorpus := os.Args[1] if filepath.Ext(seedCorpus) != ".zip" { - log.Fatalf("expected zip file .zip, got %s", seedCorpus) + log.Panicf("expected zip file .zip, got %s", seedCorpus) } zipFile, err := os.Create(seedCorpus) if err != nil { - log.Fatalf("failed creating zip file: %v", err) + log.Panicf("failed creating zip file: %v", err) } defer func() { err := zipFile.Close() if err != nil { - log.Fatalf("failed to close zip file: %v", err) + log.Panicf("failed to close zip file: %v", err) } }() @@ -172,6 +172,6 @@ func main() { seedBSONCorpus(zipWriter) if err := zipWriter.Close(); err != nil { - log.Fatalf("failed to close zip writer: %v", err) + log.Panicf("failed to close zip writer: %v", err) } } diff --git a/cmd/parse-api-report/main.go b/cmd/parse-api-report/main.go index 5d4d4e0743..d83baa6aae 100644 --- a/cmd/parse-api-report/main.go +++ b/cmd/parse-api-report/main.go @@ -23,7 +23,7 @@ func main() { // open file to read fRead, err := os.Open("api-report.txt") if err != nil { - log.Fatal(err) + log.Panic(err) } // remember to close the file at the end of the program defer fRead.Close() @@ -31,7 +31,7 @@ func main() { // open file to write fWrite, err := os.Create("api-report.md") if err != nil { - log.Fatal(err) + log.Panic(err) } // remember to close the file at the end of the program defer fWrite.Close() @@ -57,7 +57,7 @@ func main() { } if strings.Contains(line, "go.mongodb.org/mongo-driver") { - line = strings.Replace(line, "go.mongodb.org/mongo-driver", ".", -1) + line = strings.ReplaceAll(line, "go.mongodb.org/mongo-driver", ".") line = "##" + line } if !suppress { @@ -74,11 +74,11 @@ func main() { } if !foundSummary { - log.Fatal("Could not parse api summary") + log.Panic("Could not parse api summary") } if err := scanner.Err(); err != nil { - log.Fatal(err) + log.Panic(err) } } diff --git a/cmd/testentauth/main.go b/cmd/testentauth/main.go index 9bcea33294..1af1c8c690 100644 --- a/cmd/testentauth/main.go +++ b/cmd/testentauth/main.go @@ -25,17 +25,17 @@ func main() { context.Background(), options.Client().ApplyURI(uri).SetCompressors([]string{compressor})) if err != nil { - log.Fatalf("Error connecting client: %v", err) + log.Panicf("Error connecting client: %v", err) } // Use the defaultauthdb (i.e. the database name after the "/") specified in the connection // string to run the count operation. cs, err := connstring.Parse(uri) if err != nil { - log.Fatalf("Error parsing connection string: %v", err) + log.Panicf("Error parsing connection string: %v", err) } if cs.Database == "" { - log.Fatal("Connection string must contain a defaultauthdb.") + log.Panic("Connection string must contain a defaultauthdb.") } coll := client.Database(cs.Database).Collection("test") @@ -45,7 +45,7 @@ func main() { count, err := coll.EstimatedDocumentCount(ctx) if err != nil { - log.Fatalf("failed executing count command: %v", err) + log.Panicf("failed executing count command: %v", err) } log.Println("Count of test collection:", count) } diff --git a/cmd/testoidcauth/main.go b/cmd/testoidcauth/main.go index aede5cbbfe..711bac4ae2 100644 --- a/cmd/testoidcauth/main.go +++ b/cmd/testoidcauth/main.go @@ -150,7 +150,7 @@ func machine11callbackIsCalled() error { var callbackFailed error countMutex := sync.Mutex{} - client, err := connectWithMachineCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithMachineCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -167,7 +167,7 @@ func machine11callbackIsCalled() error { }, nil }) - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() if err != nil { return fmt.Errorf("machine_1_1: failed connecting client: %v", err) @@ -192,7 +192,7 @@ func machine12callbackIsCalledOnlyOneForMultipleConnections() error { var callbackFailed error countMutex := sync.Mutex{} - client, err := connectWithMachineCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithMachineCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -209,7 +209,7 @@ func machine12callbackIsCalledOnlyOneForMultipleConnections() error { }, nil }) - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() if err != nil { return fmt.Errorf("machine_1_2: failed connecting client: %v", err) @@ -280,7 +280,7 @@ func machine21validCallbackInputs() error { }, nil }) - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() if err != nil { return fmt.Errorf("machine_2_1: failed connecting client: %v", err) @@ -304,7 +304,7 @@ func machine23oidcCallbackReturnMissingData() error { callbackCount := 0 countMutex := sync.Mutex{} - client, err := connectWithMachineCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithMachineCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -316,7 +316,7 @@ func machine23oidcCallbackReturnMissingData() error { }, nil }) - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() if err != nil { return fmt.Errorf("machine_2_3: failed connecting client: %v", err) @@ -337,7 +337,7 @@ func machine23oidcCallbackReturnMissingData() error { } func machine24invalidClientConfigurationWithCallback() error { - _, err := connectWithMachineCBAndProperties(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + _, err := connectWithMachineCBAndProperties(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { t := time.Now().Add(time.Hour) return &options.OIDCCredential{ AccessToken: "", @@ -354,7 +354,7 @@ func machine24invalidClientConfigurationWithCallback() error { } func machine25InvalidUseofAllowedHosts() error { - _, err := connectWithMachineCBAndProperties(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + _, err := connectWithMachineCBAndProperties(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { t := time.Now().Add(time.Hour) return &options.OIDCCredential{ AccessToken: "", @@ -378,7 +378,7 @@ func machine31failureWithCachedTokensFetchANewTokenAndRetryAuth() error { var callbackFailed error countMutex := sync.Mutex{} - client, err := connectWithMachineCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithMachineCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -395,7 +395,7 @@ func machine31failureWithCachedTokensFetchANewTokenAndRetryAuth() error { }, nil }) - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() if err != nil { return fmt.Errorf("machine_3_1: failed connecting client: %v", err) @@ -430,7 +430,7 @@ func machine32authFailuresWithoutCachedTokensReturnsAnError() error { var callbackFailed error countMutex := sync.Mutex{} - client, err := connectWithMachineCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithMachineCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -442,7 +442,7 @@ func machine32authFailuresWithoutCachedTokensReturnsAnError() error { }, nil }) - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() if err != nil { return fmt.Errorf("machine_3_2: failed connecting client: %v", err) @@ -470,9 +470,9 @@ func machine33UnexpectedErrorCodeDoesNotClearTheCache() error { if err != nil { return fmt.Errorf("machine_3_3: failed connecting admin client: %v", err) } - defer adminClient.Disconnect(context.Background()) + defer func() { _ = adminClient.Disconnect(context.Background()) }() - client, err := connectWithMachineCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithMachineCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -489,7 +489,7 @@ func machine33UnexpectedErrorCodeDoesNotClearTheCache() error { }, nil }) - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() if err != nil { return fmt.Errorf("machine_3_3: failed connecting client: %v", err) @@ -544,9 +544,9 @@ func machine41ReauthenticationSucceeds() error { if err != nil { return fmt.Errorf("machine_4_1: failed connecting admin client: %v", err) } - defer adminClient.Disconnect(context.Background()) + defer func() { _ = adminClient.Disconnect(context.Background()) }() - client, err := connectWithMachineCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithMachineCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -563,7 +563,7 @@ func machine41ReauthenticationSucceeds() error { }, nil }) - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() if err != nil { return fmt.Errorf("machine_4_1: failed connecting client: %v", err) @@ -609,9 +609,9 @@ func machine42ReadCommandsFailIfReauthenticationFails() error { if err != nil { return fmt.Errorf("machine_4_2: failed connecting admin client: %v", err) } - defer adminClient.Disconnect(context.Background()) + defer func() { _ = adminClient.Disconnect(context.Background()) }() - client, err := connectWithMachineCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithMachineCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -637,7 +637,7 @@ func machine42ReadCommandsFailIfReauthenticationFails() error { }) - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() if err != nil { return fmt.Errorf("machine_4_2: failed connecting client: %v", err) @@ -689,9 +689,9 @@ func machine43WriteCommandsFailIfReauthenticationFails() error { if err != nil { return fmt.Errorf("machine_4_3: failed connecting admin client: %v", err) } - defer adminClient.Disconnect(context.Background()) + defer func() { _ = adminClient.Disconnect(context.Background()) }() - client, err := connectWithMachineCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithMachineCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -716,7 +716,7 @@ func machine43WriteCommandsFailIfReauthenticationFails() error { }, nil }) - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() if err != nil { return fmt.Errorf("machine_4_3: failed connecting client: %v", err) @@ -763,7 +763,7 @@ func human11singlePrincipalImplictUsername() error { var callbackFailed error countMutex := sync.Mutex{} - client, err := connectWithHumanCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithHumanCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -780,7 +780,7 @@ func human11singlePrincipalImplictUsername() error { }, nil }) - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() if err != nil { return fmt.Errorf("human_1_1: failed connecting client: %v", err) @@ -805,7 +805,7 @@ func human12singlePrincipalExplicitUsername() error { var callbackFailed error countMutex := sync.Mutex{} - client, err := connectWithHumanCBAndUser(uriSingle, "test_user1", func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithHumanCBAndUser(uriSingle, "test_user1", func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -824,7 +824,7 @@ func human12singlePrincipalExplicitUsername() error { if err != nil { return fmt.Errorf("human_1_2: failed connecting client: %v", err) } - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() coll := client.Database("test").Collection("test") @@ -846,7 +846,7 @@ func human13mulitplePrincipalUser1() error { countMutex := sync.Mutex{} opts := options.Client().ApplyURI(uriMulti) - opts.Auth.OIDCHumanCallback = func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + opts.Auth.OIDCHumanCallback = func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -867,7 +867,7 @@ func human13mulitplePrincipalUser1() error { if err != nil { return fmt.Errorf("human_1_3: failed connecting client: %v", err) } - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() coll := client.Database("test").Collection("test") @@ -889,7 +889,7 @@ func human14mulitplePrincipalUser2() error { countMutex := sync.Mutex{} opts := options.Client().ApplyURI(uriMulti) - opts.Auth.OIDCHumanCallback = func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + opts.Auth.OIDCHumanCallback = func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -910,7 +910,7 @@ func human14mulitplePrincipalUser2() error { if err != nil { return fmt.Errorf("human_1_4: failed connecting client: %v", err) } - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() coll := client.Database("test").Collection("test") @@ -931,7 +931,7 @@ func human15mulitplePrincipalNoUser() error { var callbackFailed error countMutex := sync.Mutex{} - client, err := connectWithHumanCB(uriMulti, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithHumanCB(uriMulti, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -950,7 +950,7 @@ func human15mulitplePrincipalNoUser() error { if err != nil { return fmt.Errorf("human_1_5: failed connecting client: %v", err) } - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() coll := client.Database("test").Collection("test") @@ -970,7 +970,7 @@ func human16allowedHostsBlocked() error { var callbackFailed error { opts := options.Client().ApplyURI(uriSingle) - opts.Auth.OIDCHumanCallback = func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + opts.Auth.OIDCHumanCallback = func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { t := time.Now().Add(time.Hour) tokenFile := tokenFile("test_user1") accessToken, err := os.ReadFile(tokenFile) @@ -988,7 +988,7 @@ func human16allowedHostsBlocked() error { if err != nil { return fmt.Errorf("human_1_4: failed connecting client: %v", err) } - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() coll := client.Database("test").Collection("test") @@ -999,7 +999,7 @@ func human16allowedHostsBlocked() error { } { opts := options.Client().ApplyURI("mongodb://localhost/?authMechanism=MONGODB-OIDC&ignored=example.com") - opts.Auth.OIDCHumanCallback = func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + opts.Auth.OIDCHumanCallback = func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { t := time.Now().Add(time.Hour) tokenFile := tokenFile("test_user1") accessToken, err := os.ReadFile(tokenFile) @@ -1017,7 +1017,7 @@ func human16allowedHostsBlocked() error { if err != nil { return fmt.Errorf("human_1_4: failed connecting client: %v", err) } - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() coll := client.Database("test").Collection("test") @@ -1048,7 +1048,7 @@ func human18MachineIDPHumanCallback() error { var callbackFailed error countMutex := sync.Mutex{} - client, err := connectWithHumanCBAndUser(uriSingle, "test_machine", func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithHumanCBAndUser(uriSingle, "test_machine", func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -1065,7 +1065,7 @@ func human18MachineIDPHumanCallback() error { }, nil }) - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() if err != nil { return fmt.Errorf("human_1_8: failed connecting client: %v", err) @@ -1091,7 +1091,7 @@ func human21validCallbackInputs() error { var callbackFailed error countMutex := sync.Mutex{} - client, err := connectWithHumanCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithHumanCB(uriSingle, func(_ context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -1114,7 +1114,7 @@ func human21validCallbackInputs() error { }, nil }) - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() if err != nil { return fmt.Errorf("human_2_1: failed connecting client: %v", err) @@ -1138,14 +1138,14 @@ func human22CallbackReturnsMissingData() error { callbackCount := 0 countMutex := sync.Mutex{} - client, err := connectWithHumanCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithHumanCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ return &options.OIDCCredential{}, nil }) - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() if err != nil { return fmt.Errorf("human_2_2: failed connecting client: %v", err) @@ -1174,9 +1174,9 @@ func human23RefreshTokenIsPassedToCallback() error { if err != nil { return fmt.Errorf("human_2_3: failed connecting admin client: %v", err) } - defer adminClient.Disconnect(context.Background()) + defer func() { _ = adminClient.Disconnect(context.Background()) }() - client, err := connectWithHumanCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithHumanCB(uriSingle, func(_ context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -1200,7 +1200,7 @@ func human23RefreshTokenIsPassedToCallback() error { }, nil }) - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() if err != nil { return fmt.Errorf("human_2_3: failed connecting client: %v", err) @@ -1242,9 +1242,9 @@ func human31usesSpeculativeAuth() error { if err != nil { return fmt.Errorf("human_3_1: failed connecting admin client: %v", err) } - defer adminClient.Disconnect(context.Background()) + defer func() { _ = adminClient.Disconnect(context.Background()) }() - client, err := connectWithHumanCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithHumanCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { // the callback should not even be called due to spec auth. return &options.OIDCCredential{}, nil }) @@ -1252,7 +1252,7 @@ func human31usesSpeculativeAuth() error { if err != nil { return fmt.Errorf("human_3_1: failed connecting client: %v", err) } - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() // We deviate from the Prose test since the failPoint on find with no error code does not seem to // work. Rather we put an access token in the cache to force speculative auth. @@ -1303,9 +1303,9 @@ func human32doesNotUseSpecualtiveAuth() error { if err != nil { return fmt.Errorf("human_3_2: failed connecting admin client: %v", err) } - defer adminClient.Disconnect(context.Background()) + defer func() { _ = adminClient.Disconnect(context.Background()) }() - client, err := connectWithHumanCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithHumanCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { t := time.Now().Add(time.Hour) tokenFile := tokenFile("test_user1") accessToken, err := os.ReadFile(tokenFile) @@ -1319,7 +1319,7 @@ func human32doesNotUseSpecualtiveAuth() error { }, nil }) - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() if err != nil { return fmt.Errorf("human_3_2: failed connecting client: %v", err) @@ -1360,7 +1360,7 @@ func human41ReauthenticationSucceeds() error { if err != nil { return fmt.Errorf("human_4_1: failed connecting admin client: %v", err) } - defer adminClient.Disconnect(context.Background()) + defer func() { _ = adminClient.Disconnect(context.Background()) }() clearChannels := func(s chan *event.CommandStartedEvent, succ chan *event.CommandSucceededEvent, f chan *event.CommandFailedEvent) { for len(s) > 0 { @@ -1379,18 +1379,18 @@ func human41ReauthenticationSucceeds() error { failed := make(chan *event.CommandFailedEvent, 100) monitor := event.CommandMonitor{ - Started: func(ctx context.Context, e *event.CommandStartedEvent) { + Started: func(_ context.Context, e *event.CommandStartedEvent) { started <- e }, - Succeeded: func(ctx context.Context, e *event.CommandSucceededEvent) { + Succeeded: func(_ context.Context, e *event.CommandSucceededEvent) { succeeded <- e }, - Failed: func(ctx context.Context, e *event.CommandFailedEvent) { + Failed: func(_ context.Context, e *event.CommandFailedEvent) { failed <- e }, } - client, err := connectWithHumanCBAndMonitor(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithHumanCBAndMonitor(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -1409,7 +1409,7 @@ func human41ReauthenticationSucceeds() error { if err != nil { return fmt.Errorf("human_4_1: failed connecting client: %v", err) } - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() clearChannels(started, succeeded, failed) coll := client.Database("test").Collection("test") @@ -1491,9 +1491,9 @@ func human42ReauthenticationSucceedsNoRefreshToken() error { if err != nil { return fmt.Errorf("human_4_2: failed connecting admin client: %v", err) } - defer adminClient.Disconnect(context.Background()) + defer func() { _ = adminClient.Disconnect(context.Background()) }() - client, err := connectWithHumanCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithHumanCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -1510,7 +1510,7 @@ func human42ReauthenticationSucceedsNoRefreshToken() error { }, nil }) - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() if err != nil { return fmt.Errorf("human_4_2: failed connecting client: %v", err) @@ -1568,9 +1568,9 @@ func human43ReauthenticationSucceedsAfterRefreshFails() error { if err != nil { return fmt.Errorf("human_4_3: failed connecting admin client: %v", err) } - defer adminClient.Disconnect(context.Background()) + defer func() { _ = adminClient.Disconnect(context.Background()) }() - client, err := connectWithHumanCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithHumanCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -1588,7 +1588,7 @@ func human43ReauthenticationSucceedsAfterRefreshFails() error { }, nil }) - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() if err != nil { return fmt.Errorf("human_4_3: failed connecting client: %v", err) @@ -1646,9 +1646,9 @@ func human44ReauthenticationFails() error { if err != nil { return fmt.Errorf("human_4_4: failed connecting admin client: %v", err) } - defer adminClient.Disconnect(context.Background()) + defer func() { _ = adminClient.Disconnect(context.Background()) }() - client, err := connectWithHumanCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithHumanCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -1673,7 +1673,7 @@ func human44ReauthenticationFails() error { }, fmt.Errorf("failed to refresh token") }) - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() if err != nil { return fmt.Errorf("human_4_4: failed connecting client: %v", err) @@ -1731,7 +1731,7 @@ func machine51azureWithNoUsername() error { if err != nil { return fmt.Errorf("machine_5_1: failed connecting client: %v", err) } - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() coll := client.Database("test").Collection("test") @@ -1752,7 +1752,7 @@ func machine52azureWithBadUsername() error { if err != nil { return fmt.Errorf("machine_5_2: failed connecting client: %v", err) } - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() coll := client.Database("test").Collection("test") @@ -1772,7 +1772,7 @@ func machine61gcpWithNoUsername() error { if err != nil { return fmt.Errorf("machine_6_1: failed connecting client: %v", err) } - defer client.Disconnect(context.Background()) + defer func() { _ = client.Disconnect(context.Background()) }() coll := client.Database("test").Collection("test") diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index dce7829b7f..a316f19020 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -6,7 +6,7 @@ We are building this software together and strongly encourage contributions from ## Requirements -Go 1.20 or higher is required to run the driver test suite. +Go 1.22 or higher is required to run the driver test suite. ## Bug Fixes and New Features @@ -17,7 +17,7 @@ Before starting to write code, look for existing [tickets](https://jira.mongodb. The Go Driver team uses GitHub to manage and review all code changes. Patches should generally be made against the master (default) branch and include relevant tests, if applicable. -Code should compile and tests should pass under all Go versions which the driver currently supports. Currently the Go Driver supports a minimum version of Go 1.18 and requires Go 1.20 for development. Please run the following Make targets to validate your changes: +Code should compile and tests should pass under all Go versions which the driver currently supports. Currently the Go Driver supports a minimum version of Go 1.18 and requires Go 1.22 for development. Please run the following Make targets to validate your changes: - `make fmt` - `make lint` (requires [golangci-lint](https://github.com/golangci/golangci-lint) and [lll](https://github.com/walle/lll) to be installed and available in the `PATH`) diff --git a/examples/_logger/zap/go.mod b/examples/_logger/zap/go.mod index 9478fb50ef..ce6ac61745 100644 --- a/examples/_logger/zap/go.mod +++ b/examples/_logger/zap/go.mod @@ -1,6 +1,6 @@ module go.mongodb.go/mongo-driver/examples/logger/zap -go 1.20 +go 1.22 replace go.mongodb.org/mongo-driver => ../../../ diff --git a/examples/_logger/zerolog/go.mod b/examples/_logger/zerolog/go.mod index b7c4fc046a..fa0a968f39 100644 --- a/examples/_logger/zerolog/go.mod +++ b/examples/_logger/zerolog/go.mod @@ -1,6 +1,6 @@ module go.mongodb.go/mongo-driver/examples/logger/zerolog -go 1.20 +go 1.22 replace go.mongodb.org/mongo-driver => ../../../ diff --git a/examples/documentation_examples/examples_test.go b/examples/documentation_examples/examples_test.go index 141056f6da..6b2c946796 100644 --- a/examples/documentation_examples/examples_test.go +++ b/examples/documentation_examples/examples_test.go @@ -32,11 +32,11 @@ func TestMain(m *testing.M) { } if err := mtest.Setup(); err != nil { - log.Fatal(err) + log.Panic(err) } defer os.Exit(m.Run()) if err := mtest.Teardown(); err != nil { - log.Fatal(err) + log.Panic(err) } } diff --git a/internal/integtest/integtest.go b/internal/integtest/integtest.go index fb7fbf459f..c9048362b4 100644 --- a/internal/integtest/integtest.go +++ b/internal/integtest/integtest.go @@ -198,11 +198,12 @@ func AddServerlessAuthCredentials(uri string) (string, error) { var scheme string // remove the scheme - if strings.HasPrefix(uri, "mongodb+srv://") { + switch { + case strings.HasPrefix(uri, "mongodb+srv://"): scheme = "mongodb+srv://" - } else if strings.HasPrefix(uri, "mongodb://") { + case strings.HasPrefix(uri, "mongodb://"): scheme = "mongodb://" - } else { + default: return "", errors.New(`scheme must be "mongodb" or "mongodb+srv"`) } diff --git a/internal/test/faas/awslambda/mongodb/go.mod b/internal/test/faas/awslambda/mongodb/go.mod index 109c93ece0..280a024f48 100644 --- a/internal/test/faas/awslambda/mongodb/go.mod +++ b/internal/test/faas/awslambda/mongodb/go.mod @@ -1,6 +1,6 @@ module go.mongodb.go/mongo-driver/internal/test/mongodb -go 1.20 +go 1.22 replace go.mongodb.org/mongo-driver => ../../../../../ diff --git a/mongo/client_examples_test.go b/mongo/client_examples_test.go index 4123e8e0e4..d89f4aa11d 100644 --- a/mongo/client_examples_test.go +++ b/mongo/client_examples_test.go @@ -24,18 +24,18 @@ func ExampleClient() { context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017")) if err != nil { - log.Fatal(err) + log.Panic(err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { - log.Fatal(err) + log.Panic(err) } }() collection := client.Database("db").Collection("coll") result, err := collection.InsertOne(context.TODO(), bson.D{{"x", 1}}) if err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Printf("inserted ID: %v\n", result.InsertedID) } @@ -47,11 +47,11 @@ func ExampleConnect_ping() { clientOpts := options.Client().ApplyURI("mongodb://localhost:27017") client, err := mongo.Connect(context.TODO(), clientOpts) if err != nil { - log.Fatal(err) + log.Panic(err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { - log.Fatal(err) + log.Panic(err) } }() @@ -60,7 +60,7 @@ func ExampleConnect_ping() { // reduces application resiliency as the server may be temporarily // unavailable when Ping is called. if err = client.Ping(context.TODO(), readpref.Primary()); err != nil { - log.Fatal(err) + log.Panic(err) } } @@ -76,7 +76,7 @@ func ExampleConnect_replicaSet() { "mongodb://localhost:27017,localhost:27018/?replicaSet=replset") client, err := mongo.Connect(context.TODO(), clientOpts) if err != nil { - log.Fatal(err) + log.Panic(err) } _ = client } @@ -90,7 +90,7 @@ func ExampleConnect_sharded() { "mongodb://localhost:27017,localhost:27018") client, err := mongo.Connect(context.TODO(), clientOpts) if err != nil { - log.Fatal(err) + log.Panic(err) } _ = client } @@ -108,7 +108,7 @@ func ExampleConnect_sRV() { clientOpts := options.Client().ApplyURI("mongodb+srv://mongodb.example.com") client, err := mongo.Connect(context.TODO(), clientOpts) if err != nil { - log.Fatal(err) + log.Panic(err) } _ = client } @@ -122,7 +122,7 @@ func ExampleConnect_direct() { "mongodb://localhost:27017/?connect=direct") client, err := mongo.Connect(context.TODO(), clientOpts) if err != nil { - log.Fatal(err) + log.Panic(err) } _ = client } @@ -145,7 +145,7 @@ func ExampleConnect_sCRAM() { SetAuth(credential) client, err := mongo.Connect(context.TODO(), clientOpts) if err != nil { - log.Fatal(err) + log.Panic(err) } _ = client } @@ -181,7 +181,7 @@ func ExampleConnect_x509() { client, err := mongo.Connect(context.TODO(), clientOpts) if err != nil { - log.Fatal(err) + log.Panic(err) } _ = client } @@ -206,7 +206,7 @@ func ExampleConnect_pLAIN() { client, err := mongo.Connect(context.TODO(), clientOpts) if err != nil { - log.Fatal(err) + log.Panic(err) } _ = client } @@ -241,7 +241,7 @@ func ExampleConnect_kerberos() { client, err := mongo.Connect(context.TODO(), clientOpts) if err != nil { - log.Fatal(err) + log.Panic(err) } _ = client } diff --git a/mongo/client_side_encryption_examples_test.go b/mongo/client_side_encryption_examples_test.go index 70243c4cc9..1f3e189396 100644 --- a/mongo/client_side_encryption_examples_test.go +++ b/mongo/client_side_encryption_examples_test.go @@ -23,7 +23,7 @@ func Example_clientSideEncryption() { // encryption key. localKey := make([]byte, 96) if _, err := rand.Read(localKey); err != nil { - log.Fatal(err) + log.Panic(err) } kmsProviders := map[string]map[string]interface{}{ "local": { @@ -41,28 +41,28 @@ func Example_clientSideEncryption() { SetAutoEncryptionOptions(autoEncryptionOpts) client, err := Connect(context.TODO(), clientOpts) if err != nil { - log.Fatalf("Connect error: %v", err) + log.Panicf("Connect error: %v", err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { - log.Fatalf("Disconnect error: %v", err) + log.Panicf("Disconnect error: %v", err) } }() collection := client.Database("test").Collection("coll") if err := collection.Drop(context.TODO()); err != nil { - log.Fatalf("Collection.Drop error: %v", err) + log.Panicf("Collection.Drop error: %v", err) } _, err = collection.InsertOne( context.TODO(), bson.D{{"encryptedField", "123456789"}}) if err != nil { - log.Fatalf("InsertOne error: %v", err) + log.Panicf("InsertOne error: %v", err) } res, err := collection.FindOne(context.TODO(), bson.D{}).Raw() if err != nil { - log.Fatalf("FindOne error: %v", err) + log.Panicf("FindOne error: %v", err) } fmt.Println(res) } @@ -82,23 +82,23 @@ func Example_clientSideEncryptionCreateKey() { context.TODO(), options.Client().ApplyURI(uri)) if err != nil { - log.Fatalf("Connect error for keyVaultClient: %v", err) + log.Panicf("Connect error for keyVaultClient: %v", err) } clientEnc, err := NewClientEncryption(keyVaultClient, clientEncryptionOpts) if err != nil { - log.Fatalf("NewClientEncryption error: %v", err) + log.Panicf("NewClientEncryption error: %v", err) } defer func() { // this will disconnect the keyVaultClient as well if err = clientEnc.Close(context.TODO()); err != nil { - log.Fatalf("Close error: %v", err) + log.Panicf("Close error: %v", err) } }() // Create a new data key and encode it as base64 dataKeyID, err := clientEnc.CreateDataKey(context.TODO(), "local") if err != nil { - log.Fatalf("CreateDataKey error: %v", err) + log.Panicf("CreateDataKey error: %v", err) } dataKeyBase64 := base64.StdEncoding.EncodeToString(dataKeyID.Data) @@ -125,7 +125,7 @@ func Example_clientSideEncryptionCreateKey() { var schemaDoc bson.Raw err = bson.UnmarshalExtJSON([]byte(schema), true, &schemaDoc) if err != nil { - log.Fatalf("UnmarshalExtJSON error: %v", err) + log.Panicf("UnmarshalExtJSON error: %v", err) } // Configure a Client with auto encryption using the new schema @@ -144,7 +144,7 @@ func Example_clientSideEncryptionCreateKey() { SetAutoEncryptionOptions(autoEncryptionOpts) client, err := Connect(context.TODO(), clientOptions) if err != nil { - log.Fatalf("Connect error for encrypted client: %v", err) + log.Panicf("Connect error for encrypted client: %v", err) } defer func() { _ = client.Disconnect(context.TODO()) diff --git a/mongo/crud_examples_test.go b/mongo/crud_examples_test.go index dbe7d1d23b..5469fdd7dd 100644 --- a/mongo/crud_examples_test.go +++ b/mongo/crud_examples_test.go @@ -32,7 +32,7 @@ func ExampleClient_ListDatabaseNames() { context.TODO(), bson.D{{"empty", false}}) if err != nil { - log.Fatal(err) + log.Panic(err) } for _, db := range result { @@ -53,7 +53,7 @@ func ExampleClient_Watch() { mongo.Pipeline{matchStage}, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } // Print out all change stream events in the order they're received. @@ -96,7 +96,7 @@ func ExampleDatabase_CreateCollection() { err := db.CreateCollection(context.TODO(), "users", opts) if err != nil { - log.Fatal(err) + log.Panic(err) } } @@ -124,7 +124,7 @@ func ExampleDatabase_CreateView() { err := db.CreateView(context.TODO(), "usernames", "users", pipeline, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } } @@ -136,7 +136,7 @@ func ExampleDatabase_ListCollectionNames() { context.TODO(), bson.D{{"options.capped", true}}) if err != nil { - log.Fatal(err) + log.Panic(err) } for _, coll := range result { @@ -156,7 +156,7 @@ func ExampleDatabase_RunCommand() { var result bson.M err := db.RunCommand(context.TODO(), command, opts).Decode(&result) if err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Println(result) } @@ -174,7 +174,7 @@ func ExampleDatabase_Watch() { mongo.Pipeline{matchStage}, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } // Print out all change stream events in the order they're received. @@ -208,14 +208,14 @@ func ExampleCollection_Aggregate() { mongo.Pipeline{groupStage}, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } // Get a list of all returned documents and print them out. // See the mongo.Cursor documentation for more examples of using cursors. var results []bson.M if err = cursor.All(context.TODO(), &results); err != nil { - log.Fatal(err) + log.Panic(err) } for _, result := range results { fmt.Printf( @@ -253,7 +253,7 @@ func ExampleCollection_BulkWrite() { opts := options.BulkWrite().SetOrdered(false) res, err := coll.BulkWrite(context.TODO(), models, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Printf( @@ -274,7 +274,7 @@ func ExampleCollection_CountDocuments() { bson.D{{"name", "Bob"}}, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Printf("name Bob appears in %v documents", count) } @@ -292,7 +292,7 @@ func ExampleCollection_DeleteMany() { }) res, err := coll.DeleteMany(context.TODO(), bson.D{{"name", "bob"}}, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Printf("deleted %v documents\n", res.DeletedCount) } @@ -310,7 +310,7 @@ func ExampleCollection_DeleteOne() { }) res, err := coll.DeleteOne(context.TODO(), bson.D{{"name", "bob"}}, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Printf("deleted %v documents\n", res.DeletedCount) } @@ -326,7 +326,7 @@ func ExampleCollection_Distinct() { opts := options.Distinct().SetMaxTime(2 * time.Second) values, err := coll.Distinct(context.TODO(), "name", filter, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } for _, value := range values { @@ -343,7 +343,7 @@ func ExampleCollection_EstimatedDocumentCount() { opts := options.EstimatedDocumentCount().SetMaxTime(2 * time.Second) count, err := coll.EstimatedDocumentCount(context.TODO(), opts) if err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Printf("estimated document count: %v", count) } @@ -357,14 +357,14 @@ func ExampleCollection_Find() { opts := options.Find().SetSort(bson.D{{"age", 1}}) cursor, err := coll.Find(context.TODO(), bson.D{{"name", "Bob"}}, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } // Get a list of all returned documents and print them out. // See the mongo.Cursor documentation for more examples of using cursors. var results []bson.M if err = cursor.All(context.TODO(), &results); err != nil { - log.Fatal(err) + log.Panic(err) } for _, result := range results { fmt.Println(result) @@ -391,7 +391,7 @@ func ExampleCollection_FindOne() { if errors.Is(err, mongo.ErrNoDocuments) { return } - log.Fatal(err) + log.Panic(err) } fmt.Printf("found document %v", result) } @@ -417,7 +417,7 @@ func ExampleCollection_FindOneAndDelete() { if errors.Is(err, mongo.ErrNoDocuments) { return } - log.Fatal(err) + log.Panic(err) } fmt.Printf("deleted document %v", deletedDocument) } @@ -446,7 +446,7 @@ func ExampleCollection_FindOneAndReplace() { if errors.Is(err, mongo.ErrNoDocuments) { return } - log.Fatal(err) + log.Panic(err) } fmt.Printf("replaced document %v", replacedDocument) } @@ -475,7 +475,7 @@ func ExampleCollection_FindOneAndUpdate() { if errors.Is(err, mongo.ErrNoDocuments) { return } - log.Fatal(err) + log.Panic(err) } fmt.Printf("updated document %v", updatedDocument) } @@ -493,7 +493,7 @@ func ExampleCollection_InsertMany() { opts := options.InsertMany().SetOrdered(false) res, err := coll.InsertMany(context.TODO(), docs, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Printf("inserted documents with IDs %v\n", res.InsertedIDs) } @@ -504,7 +504,7 @@ func ExampleCollection_InsertOne() { // Insert the document {name: "Alice"}. res, err := coll.InsertOne(context.TODO(), bson.D{{"name", "Alice"}}) if err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Printf("inserted document with ID %v\n", res.InsertedID) } @@ -522,7 +522,7 @@ func ExampleCollection_ReplaceOne() { replacement := bson.D{{"location", "NYC"}} result, err := coll.ReplaceOne(context.TODO(), filter, replacement, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } if result.MatchedCount != 0 { @@ -544,7 +544,7 @@ func ExampleCollection_UpdateMany() { result, err := coll.UpdateMany(context.TODO(), filter, update) if err != nil { - log.Fatal(err) + log.Panic(err) } if result.MatchedCount != 0 { @@ -567,7 +567,7 @@ func ExampleCollection_UpdateOne() { result, err := coll.UpdateOne(context.TODO(), filter, update, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } if result.MatchedCount != 0 { @@ -592,7 +592,7 @@ func ExampleCollection_Watch() { mongo.Pipeline{matchStage}, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } // Print out all change stream events in the order they're received. @@ -618,7 +618,7 @@ func ExampleWithSession() { opts := options.Session().SetDefaultReadConcern(readconcern.Majority()) sess, err := client.StartSession(opts) if err != nil { - log.Fatal(err) + log.Panic(err) } defer sess.EndSession(context.TODO()) @@ -667,7 +667,7 @@ func ExampleWithSession() { return sess.CommitTransaction(context.Background()) }) if err != nil { - log.Fatal(err) + log.Panic(err) } } @@ -724,7 +724,7 @@ func ExampleClient_UseSessionWithOptions() { return ctx.CommitTransaction(context.Background()) }) if err != nil { - log.Fatal(err) + log.Panic(err) } } @@ -741,7 +741,7 @@ func ExampleClient_StartSession_withTransaction() { opts := options.Session().SetDefaultReadConcern(readconcern.Majority()) sess, err := client.StartSession(opts) if err != nil { - log.Fatal(err) + log.Panic(err) } defer sess.EndSession(context.TODO()) @@ -774,7 +774,7 @@ func ExampleClient_StartSession_withTransaction() { }, txnOpts) if err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Printf("result: %v\n", result) } @@ -837,7 +837,7 @@ func ExampleCursor_All() { var results []bson.M if err := cursor.All(context.TODO(), &results); err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Println(results) } @@ -852,12 +852,12 @@ func ExampleCursor_Next() { // A new result variable should be declared for each document. var result bson.M if err := cursor.Decode(&result); err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Println(result) } if err := cursor.Err(); err != nil { - log.Fatal(err) + log.Panic(err) } } @@ -872,7 +872,7 @@ func ExampleCursor_TryNext() { // A new result variable should be declared for each document. var result bson.M if err := cursor.Decode(&result); err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Println(result) continue @@ -882,7 +882,7 @@ func ExampleCursor_TryNext() { // cursor was exhausted and was closed, or an error occurred. TryNext // should only be called again for the empty batch case. if err := cursor.Err(); err != nil { - log.Fatal(err) + log.Panic(err) } if cursor.ID() == 0 { break @@ -945,12 +945,12 @@ func ExampleChangeStream_Next() { // A new event variable should be declared for each event. var event bson.M if err := stream.Decode(&event); err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Println(event) } if err := stream.Err(); err != nil { - log.Fatal(err) + log.Panic(err) } } @@ -966,7 +966,7 @@ func ExampleChangeStream_TryNext() { // A new event variable should be declared for each event. var event bson.M if err := stream.Decode(&event); err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Println(event) continue @@ -976,7 +976,7 @@ func ExampleChangeStream_TryNext() { // change stream was closed by the server, or an error occurred. TryNext // should only be called again for the empty batch case. if err := stream.Err(); err != nil { - log.Fatal(err) + log.Panic(err) } if stream.ID() == 0 { break @@ -1021,7 +1021,7 @@ func ExampleChangeStream_ResumeToken() { opts := options.ChangeStream().SetResumeAfter(resumeToken) newStream, err := newClient.Watch(context.TODO(), mongo.Pipeline{}, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } defer newStream.Close(context.TODO()) } @@ -1051,7 +1051,7 @@ func ExampleIndexView_CreateMany() { opts := options.CreateIndexes().SetMaxTime(2 * time.Second) names, err := indexView.CreateMany(context.TODO(), models, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Printf("created indexes %v\n", names) @@ -1065,13 +1065,13 @@ func ExampleIndexView_List() { opts := options.ListIndexes().SetMaxTime(2 * time.Second) cursor, err := indexView.List(context.TODO(), opts) if err != nil { - log.Fatal(err) + log.Panic(err) } // Get a slice of all indexes returned and print them out. var results []bson.M if err = cursor.All(context.TODO(), &results); err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Println(results) } diff --git a/mongo/cursor_test.go b/mongo/cursor_test.go index 3781109019..3e2992132f 100644 --- a/mongo/cursor_test.go +++ b/mongo/cursor_test.go @@ -94,11 +94,6 @@ func (tbc *testBatchCursor) SetComment(interface{}) {} func (tbc *testBatchCursor) SetMaxTime(time.Duration) {} func TestCursor(t *testing.T) { - t.Run("loops until docs available", func(t *testing.T) {}) - t.Run("returns false on context cancellation", func(t *testing.T) {}) - t.Run("returns false if error occurred", func(t *testing.T) {}) - t.Run("returns false if ID is zero and no more docs", func(t *testing.T) {}) - t.Run("TestAll", func(t *testing.T) { t.Run("errors if argument is not pointer to slice", func(t *testing.T) { cursor, err := newCursor(newTestBatchCursor(1, 5), nil, nil) diff --git a/mongo/description/selector_test.go b/mongo/description/selector_test.go index a3566783dd..baf93a7611 100644 --- a/mongo/description/selector_test.go +++ b/mongo/description/selector_test.go @@ -236,7 +236,7 @@ func BenchmarkLatencySelector(b *testing.B) { }{ { name: "AllFit", - serversHook: func(servers []Server) {}, + serversHook: func([]Server) {}, }, { name: "AllButOneFit", @@ -279,8 +279,8 @@ func BenchmarkLatencySelector(b *testing.B) { servers[i] = s } bcase.serversHook(servers) - //this will make base 1 sec latency < min (0.5) + conf (1) - //and high latency 2 higher than the threshold + // this will make base 1 sec latency < min (0.5) + conf (1) + // and high latency 2 higher than the threshold servers[99].AverageRTT = 500 * time.Millisecond c := Topology{ Kind: Sharded, @@ -305,7 +305,7 @@ func BenchmarkSelector_Sharded(b *testing.B) { }{ { name: "AllFit", - serversHook: func(servers []Server) {}, + serversHook: func([]Server) {}, }, { name: "AllButOneFit", diff --git a/mongo/description/server.go b/mongo/description/server.go index cf39423839..19f2760e2f 100644 --- a/mongo/description/server.go +++ b/mongo/description/server.go @@ -316,21 +316,23 @@ func NewServer(addr address.Address, response bson.Raw) Server { desc.Kind = Standalone - if isReplicaSet { + switch { + case isReplicaSet: desc.Kind = RSGhost - } else if desc.SetName != "" { - if isWritablePrimary { + case desc.SetName != "": + switch { + case isWritablePrimary: desc.Kind = RSPrimary - } else if hidden { + case hidden: desc.Kind = RSMember - } else if secondary { + case secondary: desc.Kind = RSSecondary - } else if arbiterOnly { + case arbiterOnly: desc.Kind = RSArbiter - } else { + default: desc.Kind = RSMember } - } else if msg == "isdbgrid" { + case msg == "isdbgrid": desc.Kind = Mongos } diff --git a/mongo/gridfs/bucket.go b/mongo/gridfs/bucket.go index 3bad4cb7c0..866e90a48e 100644 --- a/mongo/gridfs/bucket.go +++ b/mongo/gridfs/bucket.go @@ -534,7 +534,7 @@ func numericalIndexDocsEqual(expected, actual bsoncore.Document) (bool, error) { actualInt, actualOK := actualVal.AsInt64OK() expectedInt, expectedOK := expectedVal.AsInt64OK() - //GridFS indexes always have numeric values + // GridFS indexes always have numeric values if !actualOK || !expectedOK { return false, nil } diff --git a/mongo/gridfs/gridfs_examples_test.go b/mongo/gridfs/gridfs_examples_test.go index 7203444dd4..c6b0947ba9 100644 --- a/mongo/gridfs/gridfs_examples_test.go +++ b/mongo/gridfs/gridfs_examples_test.go @@ -30,11 +30,11 @@ func ExampleBucket_OpenUploadStream() { SetMetadata(bson.D{{"metadata tag", "tag"}}) uploadStream, err := bucket.OpenUploadStream("filename", uploadOpts) if err != nil { - log.Fatal(err) + log.Panic(err) } defer func() { if err = uploadStream.Close(); err != nil { - log.Fatal(err) + log.Panic(err) } }() @@ -42,11 +42,11 @@ func ExampleBucket_OpenUploadStream() { // 2 seconds. err = uploadStream.SetWriteDeadline(time.Now().Add(2 * time.Second)) if err != nil { - log.Fatal(err) + log.Panic(err) } if _, err = uploadStream.Write(fileContent); err != nil { - log.Fatal(err) + log.Panic(err) } } @@ -63,7 +63,7 @@ func ExampleBucket_UploadFromStream() { bytes.NewBuffer(fileContent), uploadOpts) if err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Printf("new file created with ID %s", fileID) @@ -75,11 +75,11 @@ func ExampleBucket_OpenDownloadStream() { downloadStream, err := bucket.OpenDownloadStream(fileID) if err != nil { - log.Fatal(err) + log.Panic(err) } defer func() { if err := downloadStream.Close(); err != nil { - log.Fatal(err) + log.Panic(err) } }() @@ -87,12 +87,12 @@ func ExampleBucket_OpenDownloadStream() { // in 2 seconds. err = downloadStream.SetReadDeadline(time.Now().Add(2 * time.Second)) if err != nil { - log.Fatal(err) + log.Panic(err) } fileBuffer := bytes.NewBuffer(nil) if _, err := io.Copy(fileBuffer, downloadStream); err != nil { - log.Fatal(err) + log.Panic(err) } } @@ -102,7 +102,7 @@ func ExampleBucket_DownloadToStream() { fileBuffer := bytes.NewBuffer(nil) if _, err := bucket.DownloadToStream(fileID, fileBuffer); err != nil { - log.Fatal(err) + log.Panic(err) } } @@ -111,7 +111,7 @@ func ExampleBucket_Delete() { var fileID primitive.ObjectID if err := bucket.Delete(fileID); err != nil { - log.Fatal(err) + log.Panic(err) } } @@ -124,11 +124,11 @@ func ExampleBucket_Find() { } cursor, err := bucket.Find(filter) if err != nil { - log.Fatal(err) + log.Panic(err) } defer func() { if err := cursor.Close(context.TODO()); err != nil { - log.Fatal(err) + log.Panic(err) } }() @@ -138,7 +138,7 @@ func ExampleBucket_Find() { } var foundFiles []gridfsFile if err = cursor.All(context.TODO(), &foundFiles); err != nil { - log.Fatal(err) + log.Panic(err) } for _, file := range foundFiles { @@ -151,7 +151,7 @@ func ExampleBucket_Rename() { var fileID primitive.ObjectID if err := bucket.Rename(fileID, "new file name"); err != nil { - log.Fatal(err) + log.Panic(err) } } @@ -159,6 +159,6 @@ func ExampleBucket_Drop() { var bucket *gridfs.Bucket if err := bucket.Drop(); err != nil { - log.Fatal(err) + log.Panic(err) } } diff --git a/mongo/integration/clam_prose_test.go b/mongo/integration/clam_prose_test.go index 3b0ad2cde1..d9aca6550b 100644 --- a/mongo/integration/clam_prose_test.go +++ b/mongo/integration/clam_prose_test.go @@ -346,7 +346,7 @@ func TestCommandLoggingAndMonitoringProse(t *testing.T) { sinkCtx, sinkCancel := context.WithDeadline(ctx, time.Now().Add(deadline)) defer sinkCancel() - validator := func(order int, level int, msg string, keysAndValues ...interface{}) error { + validator := func(order int, _ int, _ string, keysAndValues ...interface{}) error { // If the order exceeds the length of the // "orderedCaseValidators," then throw an error. if order >= len(tcase.orderedLogValidators) { diff --git a/mongo/integration/crud_helpers_test.go b/mongo/integration/crud_helpers_test.go index 3344ac297b..f74c70f44a 100644 --- a/mongo/integration/crud_helpers_test.go +++ b/mongo/integration/crud_helpers_test.go @@ -1046,7 +1046,7 @@ func executeWithTransaction(mt *mtest.T, sess mongo.Session, args bson.Raw) erro assert.Nil(mt, err, "error creating withTransactionArgs: %v", err) opts := createTransactionOptions(mt, testArgs.Options) - _, err = sess.WithTransaction(context.Background(), func(sc mongo.SessionContext) (interface{}, error) { + _, err = sess.WithTransaction(context.Background(), func(mongo.SessionContext) (interface{}, error) { err := runWithTransactionOperations(mt, testArgs.Callback.Operations, sess) return nil, err }, opts) @@ -1584,11 +1584,11 @@ func verifyInsertManyResult(mt *mtest.T, actualResult *mongo.InsertManyResult, e } assert.NotNil(mt, actualResult, "expected InsertMany result %v but got nil", expectedResult) - var expected struct{ InsertedIds map[string]interface{} } + var expected struct{ InsertedIDs map[string]interface{} } err := bson.Unmarshal(expectedResult.(bson.Raw), &expected) assert.Nil(mt, err, "error creating expected InsertMany result: %v", err) - for _, val := range expected.InsertedIds { + for _, val := range expected.InsertedIDs { var found bool for _, inserted := range actualResult.InsertedIDs { if val == inserted { diff --git a/mongo/integration/errors_test.go b/mongo/integration/errors_test.go index ad2da491aa..0a206ca148 100644 --- a/mongo/integration/errors_test.go +++ b/mongo/integration/errors_test.go @@ -398,7 +398,7 @@ func TestErrors(t *testing.T) { }) }) mt.Run("error helpers", func(mt *mtest.T) { - //IsDuplicateKeyError + // IsDuplicateKeyError mt.Run("IsDuplicateKeyError", func(mt *mtest.T) { testCases := []struct { name string @@ -477,7 +477,7 @@ func TestErrors(t *testing.T) { }) } }) - //IsNetworkError + // IsNetworkError mt.Run("IsNetworkError", func(mt *mtest.T) { const networkLabel = "NetworkError" const otherLabel = "other" @@ -498,7 +498,7 @@ func TestErrors(t *testing.T) { }) } }) - //IsTimeout + // IsTimeout mt.Run("IsTimeout", func(mt *mtest.T) { testCases := []struct { name string diff --git a/mongo/integration/main_test.go b/mongo/integration/main_test.go index 394fd5be6c..d0ae06f33d 100644 --- a/mongo/integration/main_test.go +++ b/mongo/integration/main_test.go @@ -26,10 +26,10 @@ func TestMain(m *testing.M) { } if err := mtest.Setup(); err != nil { - log.Fatal(err) + log.Panic(err) } defer os.Exit(m.Run()) if err := mtest.Teardown(); err != nil { - log.Fatal(err) + log.Panic(err) } } diff --git a/mongo/integration/mtest/mongotest.go b/mongo/integration/mtest/mongotest.go index 25f30849b0..41292e67a3 100644 --- a/mongo/integration/mtest/mongotest.go +++ b/mongo/integration/mtest/mongotest.go @@ -614,7 +614,7 @@ func (t *T) CloneCollection(opts *options.CollectionOptions) { func sanitizeCollectionName(db string, coll string) string { // Collections can't have "$" in their names, so we substitute it with "%". - coll = strings.Replace(coll, "$", "%", -1) + coll = strings.ReplaceAll(coll, "$", "%") // Namespaces can only have 120 bytes max. if len(db+"."+coll) >= 120 { diff --git a/mongo/integration/mtest/setup.go b/mongo/integration/mtest/setup.go index 9a6c1996e0..cdd33219c3 100644 --- a/mongo/integration/mtest/setup.go +++ b/mongo/integration/mtest/setup.go @@ -318,11 +318,12 @@ func addServerlessAuthCredentials(uri string) (string, error) { var scheme string // remove the scheme - if strings.HasPrefix(uri, "mongodb+srv://") { + switch { + case strings.HasPrefix(uri, "mongodb+srv://"): scheme = "mongodb+srv://" - } else if strings.HasPrefix(uri, "mongodb://") { + case strings.HasPrefix(uri, "mongodb://"): scheme = "mongodb://" - } else { + default: return "", errors.New(`scheme must be "mongodb" or "mongodb+srv"`) } diff --git a/mongo/integration/retryable_writes_prose_test.go b/mongo/integration/retryable_writes_prose_test.go index 0c93a45417..0e55badc7e 100644 --- a/mongo/integration/retryable_writes_prose_test.go +++ b/mongo/integration/retryable_writes_prose_test.go @@ -242,7 +242,7 @@ func TestRetryableWritesProse(t *testing.T) { // shutdownInProgressErrorCode actually configures the "NoWritablePrimary" fail command. var secondFailPointConfigured bool - //Set a command monitor on the client that configures a failpoint with a "NoWritesPerformed" + // Set a command monitor on the client that configures a failpoint with a "NoWritesPerformed" monitor.Succeeded = func(_ context.Context, evt *event.CommandSucceededEvent) { var errorCode int32 if wce := evt.Reply.Lookup("writeConcernError"); wce.Type == bsontype.EmbeddedDocument { diff --git a/mongo/integration/sdam_prose_test.go b/mongo/integration/sdam_prose_test.go index 3107dcb97d..7f62abfc4a 100644 --- a/mongo/integration/sdam_prose_test.go +++ b/mongo/integration/sdam_prose_test.go @@ -209,10 +209,10 @@ func TestServerHeartbeatStartedEvent(t *testing.T) { primitive.NewObjectID(), topology.WithServerMonitor(func(*event.ServerMonitor) *event.ServerMonitor { return &event.ServerMonitor{ - ServerHeartbeatStarted: func(e *event.ServerHeartbeatStartedEvent) { + ServerHeartbeatStarted: func(*event.ServerHeartbeatStartedEvent) { events <- "serverHeartbeatStartedEvent" }, - ServerHeartbeatFailed: func(e *event.ServerHeartbeatFailedEvent) { + ServerHeartbeatFailed: func(*event.ServerHeartbeatFailedEvent) { events <- "serverHeartbeatFailedEvent" }, } diff --git a/mongo/integration/unified/logger.go b/mongo/integration/unified/logger.go index eb9379f9e3..0574fb225a 100644 --- a/mongo/integration/unified/logger.go +++ b/mongo/integration/unified/logger.go @@ -70,7 +70,7 @@ func (log *Logger) Info(level int, msg string, args ...interface{}) { // Add the Diff back to the level, as there is no need to create a // logging offset. - level = level + logger.DiffToInfo + level += logger.DiffToInfo logMessage, err := newLogMessage(level, msg, args...) if err != nil { diff --git a/mongo/integration/unified/main_test.go b/mongo/integration/unified/main_test.go index 3758b2856e..7462adc6e0 100644 --- a/mongo/integration/unified/main_test.go +++ b/mongo/integration/unified/main_test.go @@ -26,10 +26,10 @@ func TestMain(m *testing.M) { } if err := mtest.Setup(); err != nil { - log.Fatal(err) + log.Panic(err) } defer os.Exit(m.Run()) if err := mtest.Teardown(); err != nil { - log.Fatal(err) + log.Panic(err) } } diff --git a/mongo/integration/unified/matches.go b/mongo/integration/unified/matches.go index 51df30a7dd..63ba0920c0 100644 --- a/mongo/integration/unified/matches.go +++ b/mongo/integration/unified/matches.go @@ -207,8 +207,7 @@ func compareDocumentToString(expected, actual bson.RawValue) error { // evaluateMixedTypeComparison compares an expected document with an actual string. If this comparison occurs, then // the function will return `true` along with any resulting error. func evaluateMixedTypeComparison(expectedKey string, expected, actual bson.RawValue) (bool, error) { - switch expectedKey { - case "comment": + if expectedKey == "comment" { if expected.Type == bsontype.EmbeddedDocument && actual.Type == bsontype.String { return true, compareDocumentToString(expected, actual) } diff --git a/mongo/integration/unified/testrunner_operation.go b/mongo/integration/unified/testrunner_operation.go index b1af95b5ba..5979ff842c 100644 --- a/mongo/integration/unified/testrunner_operation.go +++ b/mongo/integration/unified/testrunner_operation.go @@ -80,7 +80,7 @@ func executeTestRunnerOperation(ctx context.Context, op *operation, loopDone <-c targetHost := clientSession.PinnedServer.Addr.String() fpDoc := args.Lookup("failPoint").Document() - commandFn := func(ctx context.Context, client *mongo.Client) error { + commandFn := func(_ context.Context, client *mongo.Client) error { return mtest.SetRawFailPoint(fpDoc, client) } diff --git a/mongo/options/clientoptions.go b/mongo/options/clientoptions.go index 5e5d47e4a0..c3a9d439e9 100644 --- a/mongo/options/clientoptions.go +++ b/mongo/options/clientoptions.go @@ -1318,7 +1318,10 @@ func addClientCertFromBytes(cfg *tls.Config, data []byte, keyPasswd string) (str } } var encoded bytes.Buffer - pem.Encode(&encoded, &pem.Block{Type: currentBlock.Type, Bytes: keyBytes}) + err = pem.Encode(&encoded, &pem.Block{Type: currentBlock.Type, Bytes: keyBytes}) + if err != nil { + return "", fmt.Errorf("error encoding private key as PEM: %w", err) + } keyBlock := encoded.Bytes() keyBlocks = append(keyBlocks, keyBlock) start = len(data) - len(remaining) diff --git a/mongo/options/example_test.go b/mongo/options/example_test.go index 1c5fbe4356..9630faa9ef 100644 --- a/mongo/options/example_test.go +++ b/mongo/options/example_test.go @@ -56,7 +56,7 @@ func ExampleClientOptions_SetLoggerOptions_customLogger() { client, err := mongo.Connect(context.TODO(), clientOptions) if err != nil { - log.Fatalf("error connecting to MongoDB: %v", err) + log.Panicf("error connecting to MongoDB: %v", err) } defer func() { _ = client.Disconnect(context.TODO()) }() @@ -66,7 +66,7 @@ func ExampleClientOptions_SetLoggerOptions_customLogger() { _, err = coll.InsertOne(context.TODO(), map[string]string{"foo": "bar"}) if err != nil { - log.Fatalf("InsertOne failed: %v", err) + log.Panicf("InsertOne failed: %v", err) } // Print the logs. diff --git a/mongo/options/serverapioptions.go b/mongo/options/serverapioptions.go index 5beb795e43..4eef2e1993 100644 --- a/mongo/options/serverapioptions.go +++ b/mongo/options/serverapioptions.go @@ -52,8 +52,7 @@ const ( // Validate determines if the provided ServerAPIVersion is currently supported by the driver. func (sav ServerAPIVersion) Validate() error { - switch sav { - case ServerAPIVersion1: + if sav == ServerAPIVersion1 { return nil } return fmt.Errorf("api version %q not supported; this driver version only supports API version \"1\"", sav) diff --git a/mongo/with_transactions_test.go b/mongo/with_transactions_test.go index 544053b973..a69a95bcda 100644 --- a/mongo/with_transactions_test.go +++ b/mongo/with_transactions_test.go @@ -120,7 +120,7 @@ func TestConvenientTransactions(t *testing.T) { "expected error with label %v, got %v", driver.TransientTransactionError, cmdErr) }) t.Run("unknown transaction commit result", func(t *testing.T) { - //set failpoint + // set failpoint failpoint := bson.D{{"configureFailPoint", "failCommand"}, {"mode", "alwaysOn"}, {"data", bson.D{ @@ -153,7 +153,7 @@ func TestConvenientTransactions(t *testing.T) { "expected error with label %v, got %v", driver.UnknownTransactionCommitResult, cmdErr) }) t.Run("commit transient transaction error", func(t *testing.T) { - //set failpoint + // set failpoint failpoint := bson.D{{"configureFailPoint", "failCommand"}, {"mode", "alwaysOn"}, {"data", bson.D{ @@ -271,7 +271,7 @@ func TestConvenientTransactions(t *testing.T) { var abortSucceeded []*event.CommandSucceededEvent var abortFailed []*event.CommandFailedEvent monitor := &event.CommandMonitor{ - Started: func(ctx context.Context, evt *event.CommandStartedEvent) { + Started: func(_ context.Context, evt *event.CommandStartedEvent) { if evt.CommandName == "abortTransaction" { abortStarted = append(abortStarted, evt) } @@ -349,7 +349,7 @@ func TestConvenientTransactions(t *testing.T) { var abortSucceeded []*event.CommandSucceededEvent var abortFailed []*event.CommandFailedEvent monitor := &event.CommandMonitor{ - Started: func(ctx context.Context, evt *event.CommandStartedEvent) { + Started: func(_ context.Context, evt *event.CommandStartedEvent) { if evt.CommandName == "abortTransaction" { abortStarted = append(abortStarted, evt) } diff --git a/x/bsonx/bsoncore/document_sequence_test.go b/x/bsonx/bsoncore/document_sequence_test.go index bf40fa878d..247123b800 100644 --- a/x/bsonx/bsoncore/document_sequence_test.go +++ b/x/bsonx/bsoncore/document_sequence_test.go @@ -393,27 +393,27 @@ func TestDocumentSequence(t *testing.T) { t.Errorf("Unexpected panic. got %v; want ", err) } } - t.Run("DocumentCount", func(t *testing.T) { + t.Run("DocumentCount", func(*testing.T) { defer capturePanic() var ds *DocumentSequence _ = ds.DocumentCount() }) - t.Run("Empty", func(t *testing.T) { + t.Run("Empty", func(*testing.T) { defer capturePanic() var ds *DocumentSequence _ = ds.Empty() }) - t.Run("ResetIterator", func(t *testing.T) { + t.Run("ResetIterator", func(*testing.T) { defer capturePanic() var ds *DocumentSequence ds.ResetIterator() }) - t.Run("Documents", func(t *testing.T) { + t.Run("Documents", func(*testing.T) { defer capturePanic() var ds *DocumentSequence _, _ = ds.Documents() }) - t.Run("Next", func(t *testing.T) { + t.Run("Next", func(*testing.T) { defer capturePanic() var ds *DocumentSequence _, _ = ds.Next() diff --git a/x/bsonx/bsoncore/element.go b/x/bsonx/bsoncore/element.go index 1fe0897c91..9c1ab2ae96 100644 --- a/x/bsonx/bsoncore/element.go +++ b/x/bsonx/bsoncore/element.go @@ -51,7 +51,7 @@ func (e Element) KeyErr() (string, error) { // KeyBytesErr returns the key for this element as a []byte, returning an error if the element is // not valid. func (e Element) KeyBytesErr() ([]byte, error) { - if len(e) <= 0 { + if len(e) == 0 { return nil, ErrElementMissingType } idx := bytes.IndexByte(e[1:], 0x00) @@ -99,7 +99,7 @@ func (e Element) Value() Value { // ValueErr returns the value for this element, returning an error if the element is not valid. func (e Element) ValueErr() (Value, error) { - if len(e) <= 0 { + if len(e) == 0 { return Value{}, ErrElementMissingType } idx := bytes.IndexByte(e[1:], 0x00) @@ -116,7 +116,7 @@ func (e Element) ValueErr() (Value, error) { // String implements the fmt.String interface. The output will be in extended JSON format. func (e Element) String() string { - if len(e) <= 0 { + if len(e) == 0 { return "" } t := bsontype.Type(e[0]) @@ -135,7 +135,7 @@ func (e Element) String() string { // DebugString outputs a human readable version of RawElement. It will attempt to stringify the // valid components of the element even if the entire element is not valid. func (e Element) DebugString() string { - if len(e) <= 0 { + if len(e) == 0 { return "" } t := bsontype.Type(e[0]) diff --git a/x/bsonx/bsoncore/value.go b/x/bsonx/bsoncore/value.go index 69c1f9edbb..fcb0428bbd 100644 --- a/x/bsonx/bsoncore/value.go +++ b/x/bsonx/bsoncore/value.go @@ -924,13 +924,14 @@ func escapeString(s string) string { func formatDouble(f float64) string { var s string - if math.IsInf(f, 1) { + switch { + case math.IsInf(f, 1): s = "Infinity" - } else if math.IsInf(f, -1) { + case math.IsInf(f, -1): s = "-Infinity" - } else if math.IsNaN(f) { + case math.IsNaN(f): s = "NaN" - } else { + default: // Print exactly one decimalType place for integers; otherwise, print as many are necessary to // perfectly represent it. s = strconv.FormatFloat(f, 'G', -1, 64) @@ -953,9 +954,7 @@ func (ss sortableString) Less(i, j int) bool { } func (ss sortableString) Swap(i, j int) { - oldI := ss[i] - ss[i] = ss[j] - ss[j] = oldI + ss[i], ss[j] = ss[j], ss[i] } func sortStringAlphebeticAscending(s string) string { diff --git a/x/mongo/driver/auth/auth_test.go b/x/mongo/driver/auth/auth_test.go index 3c07ed2cd8..2988387d29 100644 --- a/x/mongo/driver/auth/auth_test.go +++ b/x/mongo/driver/auth/auth_test.go @@ -13,7 +13,7 @@ import ( "github.com/google/go-cmp/cmp" "go.mongodb.org/mongo-driver/internal/require" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" - . "go.mongodb.org/mongo-driver/x/mongo/driver/auth" + "go.mongodb.org/mongo-driver/x/mongo/driver/auth" "go.mongodb.org/mongo-driver/x/mongo/driver/wiremessage" ) @@ -22,25 +22,25 @@ func TestCreateAuthenticator(t *testing.T) { tests := []struct { name string source string - auth Authenticator + auth auth.Authenticator }{ - {name: "", auth: &DefaultAuthenticator{}}, - {name: "SCRAM-SHA-1", auth: &ScramAuthenticator{}}, - {name: "SCRAM-SHA-256", auth: &ScramAuthenticator{}}, - {name: "MONGODB-CR", auth: &MongoDBCRAuthenticator{}}, - {name: "PLAIN", auth: &PlainAuthenticator{}}, - {name: "MONGODB-X509", auth: &MongoDBX509Authenticator{}}, + {name: "", auth: &auth.DefaultAuthenticator{}}, + {name: "SCRAM-SHA-1", auth: &auth.ScramAuthenticator{}}, + {name: "SCRAM-SHA-256", auth: &auth.ScramAuthenticator{}}, + {name: "MONGODB-CR", auth: &auth.MongoDBCRAuthenticator{}}, + {name: "PLAIN", auth: &auth.PlainAuthenticator{}}, + {name: "MONGODB-X509", auth: &auth.MongoDBX509Authenticator{}}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - cred := &Cred{ + cred := &auth.Cred{ Username: "user", Password: "pencil", PasswordSet: true, } - a, err := CreateAuthenticator(test.name, cred, &http.Client{}) + a, err := auth.CreateAuthenticator(test.name, cred, &http.Client{}) require.NoError(t, err) require.IsType(t, test.auth, a) }) @@ -53,8 +53,7 @@ func compareResponses(t *testing.T, wm []byte, expectedPayload bsoncore.Document t.Fatalf("wiremessage is too short to unmarshal") } var actualPayload bsoncore.Document - switch opcode { - case wiremessage.OpMsg: + if opcode == wiremessage.OpMsg { // Append the $db field. elems, err := expectedPayload.Elements() if err != nil { diff --git a/x/mongo/driver/auth/mongodbcr_test.go b/x/mongo/driver/auth/mongodbcr_test.go index e2f43b2f21..7e97559808 100644 --- a/x/mongo/driver/auth/mongodbcr_test.go +++ b/x/mongo/driver/auth/mongodbcr_test.go @@ -14,14 +14,14 @@ import ( "go.mongodb.org/mongo-driver/mongo/description" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" - . "go.mongodb.org/mongo-driver/x/mongo/driver/auth" + "go.mongodb.org/mongo-driver/x/mongo/driver/auth" "go.mongodb.org/mongo-driver/x/mongo/driver/drivertest" ) func TestMongoDBCRAuthenticator_Fails(t *testing.T) { t.Parallel() - authenticator := MongoDBCRAuthenticator{ + authenticator := auth.MongoDBCRAuthenticator{ DB: "source", Username: "user", Password: "pencil", @@ -46,7 +46,7 @@ func TestMongoDBCRAuthenticator_Fails(t *testing.T) { Desc: desc, } - err := authenticator.Auth(context.Background(), &Config{Description: desc, Connection: c}) + err := authenticator.Auth(context.Background(), &auth.Config{Description: desc, Connection: c}) if err == nil { t.Fatalf("expected an error but got none") } @@ -60,7 +60,7 @@ func TestMongoDBCRAuthenticator_Fails(t *testing.T) { func TestMongoDBCRAuthenticator_Succeeds(t *testing.T) { t.Parallel() - authenticator := MongoDBCRAuthenticator{ + authenticator := auth.MongoDBCRAuthenticator{ DB: "source", Username: "user", Password: "pencil", @@ -85,7 +85,7 @@ func TestMongoDBCRAuthenticator_Succeeds(t *testing.T) { Desc: desc, } - err := authenticator.Auth(context.Background(), &Config{Description: desc, Connection: c}) + err := authenticator.Auth(context.Background(), &auth.Config{Description: desc, Connection: c}) if err != nil { t.Fatalf("expected no error but got \"%s\"", err) } diff --git a/x/mongo/driver/auth/oidc.go b/x/mongo/driver/auth/oidc.go index 00a4775af8..13fd10ec3d 100644 --- a/x/mongo/driver/auth/oidc.go +++ b/x/mongo/driver/auth/oidc.go @@ -289,7 +289,7 @@ func (oa *OIDCAuthenticator) providerCallback() (OIDCCallback, error) { func getAzureOIDCCallback(clientID string, resource string, httpClient *http.Client) OIDCCallback { // return the callback parameterized by the clientID and resource, also passing in the user // configured httpClient. - return func(ctx context.Context, args *OIDCArgs) (*OIDCCredential, error) { + return func(ctx context.Context, _ *OIDCArgs) (*OIDCCredential, error) { resource = url.QueryEscape(resource) var uri string if clientID != "" { @@ -332,7 +332,7 @@ func getAzureOIDCCallback(clientID string, resource string, httpClient *http.Cli func getGCPOIDCCallback(resource string, httpClient *http.Client) OIDCCallback { // return the callback parameterized by the clientID and resource, also passing in the user // configured httpClient. - return func(ctx context.Context, args *OIDCArgs) (*OIDCCredential, error) { + return func(ctx context.Context, _ *OIDCArgs) (*OIDCCredential, error) { resource = url.QueryEscape(resource) uri := fmt.Sprintf("http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?audience=%s", resource) req, err := http.NewRequestWithContext(ctx, http.MethodGet, uri, nil) diff --git a/x/mongo/driver/auth/plain_test.go b/x/mongo/driver/auth/plain_test.go index 05abb69071..cdfa7ad64f 100644 --- a/x/mongo/driver/auth/plain_test.go +++ b/x/mongo/driver/auth/plain_test.go @@ -15,14 +15,14 @@ import ( "go.mongodb.org/mongo-driver/internal/require" "go.mongodb.org/mongo-driver/mongo/description" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" - . "go.mongodb.org/mongo-driver/x/mongo/driver/auth" + "go.mongodb.org/mongo-driver/x/mongo/driver/auth" "go.mongodb.org/mongo-driver/x/mongo/driver/drivertest" ) func TestPlainAuthenticator_Fails(t *testing.T) { t.Parallel() - authenticator := PlainAuthenticator{ + authenticator := auth.PlainAuthenticator{ Username: "user", Password: "pencil", } @@ -47,7 +47,7 @@ func TestPlainAuthenticator_Fails(t *testing.T) { Desc: desc, } - err := authenticator.Auth(context.Background(), &Config{Description: desc, Connection: c}) + err := authenticator.Auth(context.Background(), &auth.Config{Description: desc, Connection: c}) if err == nil { t.Fatalf("expected an error but got none") } @@ -61,7 +61,7 @@ func TestPlainAuthenticator_Fails(t *testing.T) { func TestPlainAuthenticator_Extra_server_message(t *testing.T) { t.Parallel() - authenticator := PlainAuthenticator{ + authenticator := auth.PlainAuthenticator{ Username: "user", Password: "pencil", } @@ -90,7 +90,7 @@ func TestPlainAuthenticator_Extra_server_message(t *testing.T) { Desc: desc, } - err := authenticator.Auth(context.Background(), &Config{Description: desc, Connection: c}) + err := authenticator.Auth(context.Background(), &auth.Config{Description: desc, Connection: c}) if err == nil { t.Fatalf("expected an error but got none") } @@ -104,7 +104,7 @@ func TestPlainAuthenticator_Extra_server_message(t *testing.T) { func TestPlainAuthenticator_Succeeds(t *testing.T) { t.Parallel() - authenticator := PlainAuthenticator{ + authenticator := auth.PlainAuthenticator{ Username: "user", Password: "pencil", } @@ -128,7 +128,7 @@ func TestPlainAuthenticator_Succeeds(t *testing.T) { Desc: desc, } - err := authenticator.Auth(context.Background(), &Config{Description: desc, Connection: c}) + err := authenticator.Auth(context.Background(), &auth.Config{Description: desc, Connection: c}) if err != nil { t.Fatalf("expected no error but got \"%s\"", err) } @@ -149,7 +149,7 @@ func TestPlainAuthenticator_Succeeds(t *testing.T) { func TestPlainAuthenticator_SucceedsBoolean(t *testing.T) { t.Parallel() - authenticator := PlainAuthenticator{ + authenticator := auth.PlainAuthenticator{ Username: "user", Password: "pencil", } @@ -173,7 +173,7 @@ func TestPlainAuthenticator_SucceedsBoolean(t *testing.T) { Desc: desc, } - err := authenticator.Auth(context.Background(), &Config{Description: desc, Connection: c}) + err := authenticator.Auth(context.Background(), &auth.Config{Description: desc, Connection: c}) require.NoError(t, err, "Auth error") require.Len(t, c.Written, 1, "expected 1 messages to be sent") diff --git a/x/mongo/driver/batch_cursor.go b/x/mongo/driver/batch_cursor.go index 23b4a6539d..2aa0aca694 100644 --- a/x/mongo/driver/batch_cursor.go +++ b/x/mongo/driver/batch_cursor.go @@ -108,12 +108,12 @@ func NewCursorResponse(info ResponseInfo) (CursorResponse, error) { if !ok { return CursorResponse{}, fmt.Errorf("ns should be a string but is a BSON %s", elem.Value().Type) } - index := strings.Index(ns, ".") - if index == -1 { + database, collection, ok := strings.Cut(ns, ".") + if !ok { return CursorResponse{}, errors.New("ns field must contain a valid namespace, but is missing '.'") } - curresp.Database = ns[:index] - curresp.Collection = ns[index+1:] + curresp.Database = database + curresp.Collection = collection case "id": curresp.ID, ok = elem.Value().Int64OK() if !ok { @@ -314,7 +314,7 @@ func (bc *BatchCursor) KillCursor(ctx context.Context) error { } return Operation{ - CommandFn: func(dst []byte, desc description.SelectedServer) ([]byte, error) { + CommandFn: func(dst []byte, _ description.SelectedServer) ([]byte, error) { dst = bsoncore.AppendStringElement(dst, "killCursors", bc.collection) dst = bsoncore.BuildArrayElement(dst, "cursors", bsoncore.Value{Type: bsontype.Int64, Data: bsoncore.AppendInt64(nil, bc.id)}) return dst, nil @@ -369,7 +369,7 @@ func (bc *BatchCursor) getMore(ctx context.Context) { } bc.err = Operation{ - CommandFn: func(dst []byte, desc description.SelectedServer) ([]byte, error) { + CommandFn: func(dst []byte, _ description.SelectedServer) ([]byte, error) { dst = bsoncore.AppendInt64Element(dst, "getMore", bc.id) dst = bsoncore.AppendStringElement(dst, "collection", bc.collection) if numToReturn > 0 { diff --git a/x/mongo/driver/connstring/connstring.go b/x/mongo/driver/connstring/connstring.go index 081b57843c..fd69eb4904 100644 --- a/x/mongo/driver/connstring/connstring.go +++ b/x/mongo/driver/connstring/connstring.go @@ -902,15 +902,16 @@ func (p *parser) parse(original string) (*ConnString, error) { uri := original var err error - if strings.HasPrefix(uri, SchemeMongoDBSRV+"://") { + switch { + case strings.HasPrefix(uri, SchemeMongoDBSRV+"://"): connStr.Scheme = SchemeMongoDBSRV // remove the scheme uri = uri[len(SchemeMongoDBSRV)+3:] - } else if strings.HasPrefix(uri, SchemeMongoDB+"://") { + case strings.HasPrefix(uri, SchemeMongoDB+"://"): connStr.Scheme = SchemeMongoDB // remove the scheme uri = uri[len(SchemeMongoDB)+3:] - } else { + default: return nil, errors.New(`scheme must be "mongodb" or "mongodb+srv"`) } @@ -921,9 +922,9 @@ func (p *parser) parse(original string) (*ConnString, error) { username := userInfo var password string - if idx := strings.Index(userInfo, ":"); idx != -1 { - username = userInfo[:idx] - password = userInfo[idx+1:] + if u, p, ok := strings.Cut(userInfo, ":"); ok { + username = u + password = p connStr.PasswordSet = true } diff --git a/x/mongo/driver/errors.go b/x/mongo/driver/errors.go index 177c2d4501..59c3992e9a 100644 --- a/x/mongo/driver/errors.go +++ b/x/mongo/driver/errors.go @@ -140,7 +140,7 @@ func (wce WriteCommandError) Retryable(wireVersion *description.VersionRange) bo if wce.WriteConcernError == nil { return false } - return (*wce.WriteConcernError).Retryable() + return wce.WriteConcernError.Retryable() } // HasErrorLabel returns true if the error contains the specified label. diff --git a/x/mongo/driver/integration/aggregate_test.go b/x/mongo/driver/integration/aggregate_test.go index 95a9b821ae..6b45ccbaa3 100644 --- a/x/mongo/driver/integration/aggregate_test.go +++ b/x/mongo/driver/integration/aggregate_test.go @@ -30,13 +30,13 @@ func setUpMonitor() (*event.CommandMonitor, chan *event.CommandStartedEvent, cha failed := make(chan *event.CommandFailedEvent, 1) return &event.CommandMonitor{ - Started: func(ctx context.Context, e *event.CommandStartedEvent) { + Started: func(_ context.Context, e *event.CommandStartedEvent) { started <- e }, - Succeeded: func(ctx context.Context, e *event.CommandSucceededEvent) { + Succeeded: func(_ context.Context, e *event.CommandSucceededEvent) { succeeded <- e }, - Failed: func(ctx context.Context, e *event.CommandFailedEvent) { + Failed: func(_ context.Context, e *event.CommandFailedEvent) { failed <- e }, }, started, succeeded, failed diff --git a/x/mongo/driver/operation.go b/x/mongo/driver/operation.go index 9dc243fdf0..ec6f69eca0 100644 --- a/x/mongo/driver/operation.go +++ b/x/mongo/driver/operation.go @@ -577,8 +577,7 @@ func (op Operation) Execute(ctx context.Context) error { // Set the previous indefinite error to be returned in any case where a retryable write error does not have a // NoWritesPerfomed label (the definite case). - switch err := err.(type) { - case labeledError: + if err, ok := err.(labeledError); ok { // If the "prevIndefiniteErr" is nil, then the current error is the first error encountered // during the retry attempt cycle. We must persist the first error in the case where all // following errors are labeled "NoWritesPerformed", which would otherwise raise nil as the diff --git a/x/mongo/driver/operation/command.go b/x/mongo/driver/operation/command.go index 9dd10f3cb0..64c98ba19a 100644 --- a/x/mongo/driver/operation/command.go +++ b/x/mongo/driver/operation/command.go @@ -79,7 +79,7 @@ func (c *Command) Execute(ctx context.Context) error { } return driver.Operation{ - CommandFn: func(dst []byte, desc description.SelectedServer) ([]byte, error) { + CommandFn: func(dst []byte, _ description.SelectedServer) ([]byte, error) { return append(dst, c.command[4:len(c.command)-1]...), nil }, ProcessResponseFn: func(info driver.ResponseInfo) error { diff --git a/x/mongo/driver/operation/delete.go b/x/mongo/driver/operation/delete.go index 298ec44196..4b520a5480 100644 --- a/x/mongo/driver/operation/delete.go +++ b/x/mongo/driver/operation/delete.go @@ -60,8 +60,7 @@ func buildDeleteResult(response bsoncore.Document) (DeleteResult, error) { } dr := DeleteResult{} for _, element := range elements { - switch element.Key() { - case "n": + if element.Key() == "n" { var ok bool dr.N, ok = element.Value().AsInt64OK() if !ok { diff --git a/x/mongo/driver/operation/distinct.go b/x/mongo/driver/operation/distinct.go index 484d96b66b..0c39027e76 100644 --- a/x/mongo/driver/operation/distinct.go +++ b/x/mongo/driver/operation/distinct.go @@ -59,8 +59,7 @@ func buildDistinctResult(response bsoncore.Document) (DistinctResult, error) { } dr := DistinctResult{} for _, element := range elements { - switch element.Key() { - case "values": + if element.Key() == "values" { dr.Values = element.Value() } } diff --git a/x/mongo/driver/operation/drop_indexes.go b/x/mongo/driver/operation/drop_indexes.go index 9cbd797be2..a22496b1e8 100644 --- a/x/mongo/driver/operation/drop_indexes.go +++ b/x/mongo/driver/operation/drop_indexes.go @@ -53,8 +53,7 @@ func buildDropIndexesResult(response bsoncore.Document) (DropIndexesResult, erro } dir := DropIndexesResult{} for _, element := range elements { - switch element.Key() { - case "nIndexesWas": + if element.Key() == "nIndexesWas" { var ok bool dir.NIndexesWas, ok = element.Value().AsInt32OK() if !ok { @@ -110,12 +109,12 @@ func (di *DropIndexes) Execute(ctx context.Context) error { func (di *DropIndexes) command(dst []byte, _ description.SelectedServer) ([]byte, error) { dst = bsoncore.AppendStringElement(dst, "dropIndexes", di.collection) - switch di.index.(type) { + switch t := di.index.(type) { case string: - dst = bsoncore.AppendStringElement(dst, "index", di.index.(string)) + dst = bsoncore.AppendStringElement(dst, "index", t) case bsoncore.Document: if di.index != nil { - dst = bsoncore.AppendDocumentElement(dst, "index", di.index.(bsoncore.Document)) + dst = bsoncore.AppendDocumentElement(dst, "index", t) } } diff --git a/x/mongo/driver/operation/drop_search_index.go b/x/mongo/driver/operation/drop_search_index.go index 3d273434d5..94e4ddfb0d 100644 --- a/x/mongo/driver/operation/drop_search_index.go +++ b/x/mongo/driver/operation/drop_search_index.go @@ -48,8 +48,7 @@ func buildDropSearchIndexResult(response bsoncore.Document) (DropSearchIndexResu } dsir := DropSearchIndexResult{} for _, element := range elements { - switch element.Key() { - case "ok": + if element.Key() == "ok" { var ok bool dsir.Ok, ok = element.Value().AsInt32OK() if !ok { diff --git a/x/mongo/driver/operation/insert.go b/x/mongo/driver/operation/insert.go index f5afe31169..a65a4895f0 100644 --- a/x/mongo/driver/operation/insert.go +++ b/x/mongo/driver/operation/insert.go @@ -59,8 +59,7 @@ func buildInsertResult(response bsoncore.Document) (InsertResult, error) { } ir := InsertResult{} for _, element := range elements { - switch element.Key() { - case "n": + if element.Key() == "n" { var ok bool ir.N, ok = element.Value().AsInt64OK() if !ok { diff --git a/x/mongo/driver/operation/update_search_index.go b/x/mongo/driver/operation/update_search_index.go index 4ed9946c69..c63e048f21 100644 --- a/x/mongo/driver/operation/update_search_index.go +++ b/x/mongo/driver/operation/update_search_index.go @@ -49,8 +49,7 @@ func buildUpdateSearchIndexResult(response bsoncore.Document) (UpdateSearchIndex } usir := UpdateSearchIndexResult{} for _, element := range elements { - switch element.Key() { - case "ok": + if element.Key() == "ok" { var ok bool usir.Ok, ok = element.Value().AsInt32OK() if !ok { diff --git a/x/mongo/driver/operation_test.go b/x/mongo/driver/operation_test.go index 27ef3a090d..a6d674e2d2 100644 --- a/x/mongo/driver/operation_test.go +++ b/x/mongo/driver/operation_test.go @@ -582,7 +582,7 @@ func TestOperation(t *testing.T) { rCanStream: false, } op := Operation{ - CommandFn: func(dst []byte, desc description.SelectedServer) ([]byte, error) { + CommandFn: func(dst []byte, _ description.SelectedServer) ([]byte, error) { return bsoncore.AppendInt32Element(dst, handshake.LegacyHello, 1), nil }, Database: "admin", @@ -621,7 +621,7 @@ func TestOperation(t *testing.T) { op := Operation{ Database: "foobar", Deployment: SingleConnectionDeployment{C: conn}, - CommandFn: func(dst []byte, desc description.SelectedServer) ([]byte, error) { + CommandFn: func(dst []byte, _ description.SelectedServer) ([]byte, error) { dst = bsoncore.AppendInt32Element(dst, "ping", 1) return dst, nil }, @@ -642,7 +642,7 @@ func TestOperation(t *testing.T) { op := Operation{ Database: "foobar", Deployment: SingleConnectionDeployment{C: conn}, - CommandFn: func(dst []byte, desc description.SelectedServer) ([]byte, error) { + CommandFn: func(dst []byte, _ description.SelectedServer) ([]byte, error) { dst = bsoncore.AppendInt32Element(dst, "ping", 1) return dst, nil }, @@ -668,7 +668,7 @@ func TestOperation(t *testing.T) { op := Operation{ Database: "foobar", Deployment: d, - CommandFn: func(dst []byte, desc description.SelectedServer) ([]byte, error) { + CommandFn: func(dst []byte, _ description.SelectedServer) ([]byte, error) { return dst, nil }, Timeout: &dur, diff --git a/x/mongo/driver/session/client_session.go b/x/mongo/driver/session/client_session.go index 4a6be9c5e4..eff27bfe33 100644 --- a/x/mongo/driver/session/client_session.go +++ b/x/mongo/driver/session/client_session.go @@ -160,13 +160,14 @@ func MaxClusterTime(ct1, ct2 bson.Raw) bson.Raw { epoch1, ord1 := getClusterTime(ct1) epoch2, ord2 := getClusterTime(ct2) - if epoch1 > epoch2 { + switch { + case epoch1 > epoch2: return ct1 - } else if epoch1 < epoch2 { + case epoch1 < epoch2: return ct2 - } else if ord1 > ord2 { + case ord1 > ord2: return ct1 - } else if ord1 < ord2 { + case ord1 < ord2: return ct2 } @@ -478,11 +479,12 @@ func (c *Client) UpdateCommitTransactionWriteConcern() { // CheckAbortTransaction checks to see if allowed to abort transaction and returns // an error if not allowed. func (c *Client) CheckAbortTransaction() error { - if c.TransactionState == None { + switch { + case c.TransactionState == None: return ErrNoTransactStarted - } else if c.TransactionState == Committed { + case c.TransactionState == Committed: return ErrAbortAfterCommit - } else if c.TransactionState == Aborted { + case c.TransactionState == Aborted: return ErrAbortTwice } return nil diff --git a/x/mongo/driver/topology/CMAP_spec_test.go b/x/mongo/driver/topology/CMAP_spec_test.go index 92cbb7cf31..8a159b29b6 100644 --- a/x/mongo/driver/topology/CMAP_spec_test.go +++ b/x/mongo/driver/topology/CMAP_spec_test.go @@ -201,7 +201,7 @@ func runCMAPTest(t *testing.T, testFileName string) { return msc, nil }) }), - WithHandshaker(func(h Handshaker) Handshaker { + WithHandshaker(func(Handshaker) Handshaker { return operation.NewHello() }), } diff --git a/x/mongo/driver/topology/connection_test.go b/x/mongo/driver/topology/connection_test.go index 946f74d8f2..c79d05f947 100644 --- a/x/mongo/driver/topology/connection_test.go +++ b/x/mongo/driver/topology/connection_test.go @@ -783,7 +783,7 @@ func TestConnection(t *testing.T) { makeMultipleConnections := func(t *testing.T, numConns int) (*pool, []*Connection, func()) { t.Helper() - addr := bootstrapConnections(t, numConns, func(nc net.Conn) {}) + addr := bootstrapConnections(t, numConns, func(net.Conn) {}) pool := newPool(poolConfig{ Address: address.Address(addr.String()), }) diff --git a/x/mongo/driver/topology/pool_test.go b/x/mongo/driver/topology/pool_test.go index bc7115ee2c..96c0d66edd 100644 --- a/x/mongo/driver/topology/pool_test.go +++ b/x/mongo/driver/topology/pool_test.go @@ -19,7 +19,6 @@ import ( "go.mongodb.org/mongo-driver/internal/eventtest" "go.mongodb.org/mongo-driver/internal/require" "go.mongodb.org/mongo-driver/mongo/address" - "go.mongodb.org/mongo-driver/x/mongo/driver" "go.mongodb.org/mongo-driver/x/mongo/driver/operation" ) @@ -1179,21 +1178,19 @@ func TestPool_PoolMonitor(t *testing.T) { }) tpm := eventtest.NewTestPoolMonitor() + dialer := &net.Dialer{} p := newPool( poolConfig{ Address: address.Address(addr.String()), PoolMonitor: tpm.PoolMonitor, }, - // Add a 10ms delay in the handshake so the test is reliable on - // operating systems that can't measure very short durations (e.g. - // Windows). - WithHandshaker(func(Handshaker) Handshaker { - return &testHandshaker{ - getHandshakeInformation: func(context.Context, address.Address, driver.Connection) (driver.HandshakeInformation, error) { - time.Sleep(10 * time.Millisecond) - return driver.HandshakeInformation{}, nil - }, - } + // Add a 10ms delay to dialing so the test is reliable on operating + // systems that can't measure very short durations (e.g. Windows). + WithDialer(func(Dialer) Dialer { + return DialerFunc(func(ctx context.Context, n, a string) (net.Conn, error) { + time.Sleep(10 * time.Millisecond) + return dialer.DialContext(ctx, n, a) + }) })) err := p.ready() diff --git a/x/mongo/driver/topology/sdam_spec_test.go b/x/mongo/driver/topology/sdam_spec_test.go index 6e360509c1..1b73a5b2d0 100644 --- a/x/mongo/driver/topology/sdam_spec_test.go +++ b/x/mongo/driver/topology/sdam_spec_test.go @@ -320,7 +320,7 @@ func applyErrors(t *testing.T, topo *Topology, errors []applicationError) { if appErr.Generation != nil { generation = *appErr.Generation } - //use generation number to check conn stale + // use generation number to check conn stale innerConn := connection{ desc: desc, generation: generation, diff --git a/x/mongo/driver/topology/server.go b/x/mongo/driver/topology/server.go index a29eea4a6d..0623632672 100644 --- a/x/mongo/driver/topology/server.go +++ b/x/mongo/driver/topology/server.go @@ -730,7 +730,7 @@ func (s *Server) createConnection() *connection { WithWriteTimeout(func(time.Duration) time.Duration { return s.cfg.heartbeatTimeout }), // We override whatever handshaker is currently attached to the options with a basic // one because need to make sure we don't do auth. - WithHandshaker(func(h Handshaker) Handshaker { + WithHandshaker(func(Handshaker) Handshaker { return operation.NewHello().AppName(s.cfg.appname).Compressors(s.cfg.compressionOpts). ServerAPI(s.cfg.serverAPI) }), diff --git a/x/mongo/driver/topology/server_test.go b/x/mongo/driver/topology/server_test.go index e23c604156..a418e690a5 100644 --- a/x/mongo/driver/topology/server_test.go +++ b/x/mongo/driver/topology/server_test.go @@ -170,19 +170,19 @@ func TestServerHeartbeatTimeout(t *testing.T) { }), WithConnectionOptions(func(opts ...ConnectionOption) []ConnectionOption { return append(opts, - WithDialer(func(d Dialer) Dialer { + WithDialer(func(Dialer) Dialer { var dialer net.Dialer return &timeoutDialer{&dialer, errors} })) }), WithServerMonitor(func(*event.ServerMonitor) *event.ServerMonitor { return &event.ServerMonitor{ - ServerHeartbeatSucceeded: func(e *event.ServerHeartbeatSucceededEvent) { + ServerHeartbeatSucceeded: func(*event.ServerHeartbeatSucceededEvent) { if !errors.dequeue() { wg.Done() } }, - ServerHeartbeatFailed: func(e *event.ServerHeartbeatFailedEvent) { + ServerHeartbeatFailed: func(*event.ServerHeartbeatFailedEvent) { if !errors.dequeue() { wg.Done() } @@ -600,10 +600,10 @@ func TestServer(t *testing.T) { d := newdialer(&net.Dialer{}) s := NewServer(address.Address(addr.String()), primitive.NewObjectID(), - WithConnectionOptions(func(option ...ConnectionOption) []ConnectionOption { + WithConnectionOptions(func(...ConnectionOption) []ConnectionOption { return []ConnectionOption{WithDialer(func(_ Dialer) Dialer { return d })} }), - WithMaxConnections(func(u uint64) uint64 { + WithMaxConnections(func(uint64) uint64 { return 1 })) s.state = serverConnected diff --git a/x/mongo/driver/topology/topology_options.go b/x/mongo/driver/topology/topology_options.go index f551fd7a2a..2c0518a54e 100644 --- a/x/mongo/driver/topology/topology_options.go +++ b/x/mongo/driver/topology/topology_options.go @@ -206,11 +206,11 @@ func NewConfigWithAuthenticator( for _, comp := range comps { switch comp { case "zlib": - connOpts = append(connOpts, WithZlibLevel(func(level *int) *int { + connOpts = append(connOpts, WithZlibLevel(func(*int) *int { return co.ZlibLevel })) case "zstd": - connOpts = append(connOpts, WithZstdLevel(func(level *int) *int { + connOpts = append(connOpts, WithZstdLevel(func(*int) *int { return co.ZstdLevel })) } @@ -244,7 +244,7 @@ func NewConfigWithAuthenticator( } if co.AuthenticateToAnything != nil && *co.AuthenticateToAnything { // Authenticate arbiters - handshakeOpts.PerformAuthentication = func(serv description.Server) bool { + handshakeOpts.PerformAuthentication = func(description.Server) bool { return true } } diff --git a/x/mongo/driver/topology/topology_test.go b/x/mongo/driver/topology/topology_test.go index 18c119876f..fd0703b97b 100644 --- a/x/mongo/driver/topology/topology_test.go +++ b/x/mongo/driver/topology/topology_test.go @@ -1150,7 +1150,7 @@ func BenchmarkSelectServerFromDescription(b *testing.B) { }{ { name: "AllFit", - serversHook: func(servers []description.Server) {}, + serversHook: func([]description.Server) {}, }, { name: "AllButOneFit",