mirror of
https://github.com/spf13/viper.git
synced 2024-04-21 12:31:38 +00:00
Compare commits
168
Commits
@@ -13,3 +13,6 @@ indent_style = tab
|
|||||||
|
|
||||||
[{Makefile,*.mk}]
|
[{Makefile,*.mk}]
|
||||||
indent_style = tab
|
indent_style = tab
|
||||||
|
|
||||||
|
[*.nix]
|
||||||
|
indent_size = 2
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
if ! has nix_direnv_version || ! nix_direnv_version 2.3.0; then
|
||||||
|
source_url "https://raw.githubusercontent.com/nix-community/nix-direnv/2.3.0/direnvrc" "sha256-Dmd+j63L84wuzgyjITIfSxSD57Tx7v51DMxVZOsiUD8="
|
||||||
|
fi
|
||||||
|
use flake . --impure
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 21 KiB After Width: | Height: | Size: 38 KiB |
@@ -11,8 +11,20 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Check minimum labels
|
- name: Check minimum labels
|
||||||
uses: mheap/github-action-required-labels@v1
|
uses: mheap/github-action-required-labels@4e9ef4ce8c697cf55716ecbf7f13a3d9e0b6ac6a # v5.1.0
|
||||||
with:
|
with:
|
||||||
mode: minimum
|
mode: minimum
|
||||||
count: 1
|
count: 1
|
||||||
labels: "release-note/ignore, kind/feature, release-note/new-feature, kind/enhancement, release-note/enhancement, kind/bug, release-note/bug-fix, release-note/breaking-change, release-note/deprecation, area/dependencies, release-note/dependency-update"
|
labels: |
|
||||||
|
release-note/ignore
|
||||||
|
kind/feature
|
||||||
|
release-note/new-feature
|
||||||
|
kind/enhancement
|
||||||
|
release-note/enhancement
|
||||||
|
kind/bug
|
||||||
|
release-note/bug-fix
|
||||||
|
release-note/breaking-change
|
||||||
|
release-note/deprecation
|
||||||
|
area/dependencies
|
||||||
|
release-note/dependency-update
|
||||||
|
release-note/misc
|
||||||
|
|||||||
+78
-22
@@ -2,58 +2,114 @@ name: CI
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches:
|
branches: [master]
|
||||||
- master
|
|
||||||
pull_request:
|
pull_request:
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
|
build:
|
||||||
|
name: Build
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- goos: js
|
||||||
|
goarch: wasm
|
||||||
|
- goos: aix
|
||||||
|
goarch: ppc64
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
|
||||||
|
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@0c52d547c9bc32b1aa3301fd7a9cb496313a4491 # v5.0.0
|
||||||
|
with:
|
||||||
|
go-version: "1.21"
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
run: go build .
|
||||||
|
env:
|
||||||
|
GOOS: ${{ matrix.goos }}
|
||||||
|
GOARCH: ${{ matrix.goarch }}
|
||||||
|
|
||||||
test:
|
test:
|
||||||
name: Test
|
name: Test
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
|
|
||||||
strategy:
|
strategy:
|
||||||
# Fail fast is disabled because there are Go version specific features and tests
|
# Fail fast is disabled because there are Go version specific features and tests
|
||||||
# that should be able to fail independently.
|
# that should be able to fail independently.
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||||
go: ['1.15', '1.16', '1.17', '1.18']
|
go: ["1.19", "1.20", "1.21"]
|
||||||
tags: ['', 'viper_yaml2', 'viper_toml1']
|
tags: ["", "finder", "viper_bind_struct"]
|
||||||
env:
|
|
||||||
GOFLAGS: -mod=readonly
|
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
|
||||||
|
|
||||||
- name: Set up Go
|
- name: Set up Go
|
||||||
uses: actions/setup-go@v3
|
uses: actions/setup-go@0c52d547c9bc32b1aa3301fd7a9cb496313a4491 # v5.0.0
|
||||||
with:
|
with:
|
||||||
go-version: ${{ matrix.go }}
|
go-version: ${{ matrix.go }}
|
||||||
|
|
||||||
- name: Checkout code
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Test
|
- name: Test
|
||||||
run: go test -race -tags '${{ matrix.tags }}' -v ./...
|
run: go test -race -v -tags '${{ matrix.tags }}' -shuffle=on ./...
|
||||||
if: runner.os != 'Windows'
|
if: runner.os != 'Windows'
|
||||||
|
|
||||||
- name: Test (without race detector)
|
- name: Test (without race detector)
|
||||||
run: go test -tags '${{ matrix.tags }}' -v ./...
|
run: go test -v -tags '${{ matrix.tags }}' -shuffle=on ./...
|
||||||
if: runner.os == 'Windows'
|
if: runner.os == 'Windows'
|
||||||
|
|
||||||
lint:
|
lint:
|
||||||
name: Lint
|
name: Lint
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
env:
|
|
||||||
GOFLAGS: -mod=readonly
|
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Set up Go
|
- name: Checkout repository
|
||||||
uses: actions/setup-go@v3
|
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
|
||||||
with:
|
|
||||||
go-version: 1.17
|
|
||||||
|
|
||||||
- name: Checkout code
|
- name: Set up Go
|
||||||
uses: actions/checkout@v3
|
uses: actions/setup-go@0c52d547c9bc32b1aa3301fd7a9cb496313a4491 # v5.0.0
|
||||||
|
with:
|
||||||
|
go-version: "1.21"
|
||||||
|
|
||||||
- name: Lint
|
- name: Lint
|
||||||
uses: golangci/golangci-lint-action@v3
|
uses: golangci/golangci-lint-action@3a919529898de77ec3da873e3063ca4b10e7f5cc # v3.7.0
|
||||||
with:
|
with:
|
||||||
version: v1.45.2
|
version: v1.54.2
|
||||||
|
|
||||||
|
dev:
|
||||||
|
name: Developer environment
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
|
||||||
|
|
||||||
|
- name: Set up Nix
|
||||||
|
uses: cachix/install-nix-action@7ac1ec25491415c381d9b62f0657c7a028df52a7 # v24
|
||||||
|
with:
|
||||||
|
extra_nix_config: |
|
||||||
|
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Check
|
||||||
|
run: nix flake check --impure
|
||||||
|
|
||||||
|
- name: Dev shell
|
||||||
|
run: nix develop --impure
|
||||||
|
|
||||||
|
dependency-review:
|
||||||
|
name: Dependency review
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: github.event_name == 'pull_request'
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
|
||||||
|
|
||||||
|
- name: Dependency Review
|
||||||
|
uses: actions/dependency-review-action@01bc87099ba56df1e897b6874784491ea6309bc4 # v3.1.4
|
||||||
|
|||||||
@@ -39,11 +39,11 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
|
||||||
|
|
||||||
# Initializes the CodeQL tools for scanning.
|
# Initializes the CodeQL tools for scanning.
|
||||||
- name: Initialize CodeQL
|
- name: Initialize CodeQL
|
||||||
uses: github/codeql-action/init@v2
|
uses: github/codeql-action/init@b374143c1149a9115d881581d29b8390bbcbb59c # v3.22.11
|
||||||
with:
|
with:
|
||||||
languages: ${{ matrix.language }}
|
languages: ${{ matrix.language }}
|
||||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||||
@@ -54,7 +54,7 @@ jobs:
|
|||||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||||
# If this step fails, then you should remove it and run the build manually (see below)
|
# If this step fails, then you should remove it and run the build manually (see below)
|
||||||
- name: Autobuild
|
- name: Autobuild
|
||||||
uses: github/codeql-action/autobuild@v2
|
uses: github/codeql-action/autobuild@b374143c1149a9115d881581d29b8390bbcbb59c # v3.22.11
|
||||||
|
|
||||||
# ℹ️ Command-line programs to run using the OS shell.
|
# ℹ️ Command-line programs to run using the OS shell.
|
||||||
# 📚 https://git.io/JvXDl
|
# 📚 https://git.io/JvXDl
|
||||||
@@ -68,5 +68,5 @@ jobs:
|
|||||||
# make release
|
# make release
|
||||||
|
|
||||||
- name: Perform CodeQL Analysis
|
- name: Perform CodeQL Analysis
|
||||||
uses: github/codeql-action/analyze@v2
|
uses: github/codeql-action/analyze@b374143c1149a9115d881581d29b8390bbcbb59c # v3.22.11
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ jobs:
|
|||||||
comment:
|
comment:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/github-script@v6
|
- uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
|
||||||
with:
|
with:
|
||||||
github-token: ${{secrets.GITHUB_TOKEN}}
|
github-token: ${{secrets.GITHUB_TOKEN}}
|
||||||
script: |
|
script: |
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ jobs:
|
|||||||
comment:
|
comment:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/github-script@v6
|
- uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
|
||||||
with:
|
with:
|
||||||
github-token: ${{secrets.GITHUB_TOKEN}}
|
github-token: ${{secrets.GITHUB_TOKEN}}
|
||||||
script: |
|
script: |
|
||||||
|
|||||||
@@ -1,26 +0,0 @@
|
|||||||
name: WASM
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- master
|
|
||||||
pull_request:
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
name: Build
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
env:
|
|
||||||
GOFLAGS: -mod=readonly
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Set up Go
|
|
||||||
uses: actions/setup-go@v3
|
|
||||||
with:
|
|
||||||
go-version: '1.17'
|
|
||||||
|
|
||||||
- name: Checkout code
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Ensure Viper compiles for WASM
|
|
||||||
run: GOOS=js GOARCH=wasm go build .
|
|
||||||
@@ -1,4 +1,7 @@
|
|||||||
|
/.devenv/
|
||||||
|
/.direnv/
|
||||||
/.idea/
|
/.idea/
|
||||||
|
/.pre-commit-config.yaml
|
||||||
/bin/
|
/bin/
|
||||||
/build/
|
/build/
|
||||||
/var/
|
/var/
|
||||||
|
|||||||
+17
-5
@@ -7,6 +7,16 @@ linters-settings:
|
|||||||
- standard
|
- standard
|
||||||
- default
|
- default
|
||||||
- prefix(github.com/spf13/viper)
|
- prefix(github.com/spf13/viper)
|
||||||
|
gocritic:
|
||||||
|
# Enable multiple checks by tags. See "Tags" section in https://github.com/go-critic/go-critic#usage.
|
||||||
|
enabled-tags:
|
||||||
|
- diagnostic
|
||||||
|
- experimental
|
||||||
|
- opinionated
|
||||||
|
- style
|
||||||
|
disabled-checks:
|
||||||
|
- importShadow
|
||||||
|
- unnamedResult
|
||||||
golint:
|
golint:
|
||||||
min-confidence: 0
|
min-confidence: 0
|
||||||
goimports:
|
goimports:
|
||||||
@@ -16,13 +26,14 @@ linters:
|
|||||||
disable-all: true
|
disable-all: true
|
||||||
enable:
|
enable:
|
||||||
- bodyclose
|
- bodyclose
|
||||||
- deadcode
|
|
||||||
- dogsled
|
- dogsled
|
||||||
- dupl
|
- dupl
|
||||||
- durationcheck
|
- durationcheck
|
||||||
- exhaustive
|
- exhaustive
|
||||||
- exportloopref
|
- exportloopref
|
||||||
- gci
|
- gci
|
||||||
|
- gocritic
|
||||||
|
- godot
|
||||||
- gofmt
|
- gofmt
|
||||||
- gofumpt
|
- gofumpt
|
||||||
- goimports
|
- goimports
|
||||||
@@ -43,14 +54,12 @@ linters:
|
|||||||
- rowserrcheck
|
- rowserrcheck
|
||||||
- sqlclosecheck
|
- sqlclosecheck
|
||||||
- staticcheck
|
- staticcheck
|
||||||
- structcheck
|
|
||||||
- stylecheck
|
- stylecheck
|
||||||
- tparallel
|
- tparallel
|
||||||
- typecheck
|
- typecheck
|
||||||
- unconvert
|
- unconvert
|
||||||
- unparam
|
- unparam
|
||||||
- unused
|
- unused
|
||||||
- varcheck
|
|
||||||
- wastedassign
|
- wastedassign
|
||||||
- whitespace
|
- whitespace
|
||||||
|
|
||||||
@@ -65,9 +74,7 @@ linters:
|
|||||||
# - gochecknoinits
|
# - gochecknoinits
|
||||||
# - gocognit
|
# - gocognit
|
||||||
# - goconst
|
# - goconst
|
||||||
# - gocritic
|
|
||||||
# - gocyclo
|
# - gocyclo
|
||||||
# - godot
|
|
||||||
# - gosec
|
# - gosec
|
||||||
# - gosimple
|
# - gosimple
|
||||||
# - ifshort
|
# - ifshort
|
||||||
@@ -83,6 +90,11 @@ linters:
|
|||||||
# - goheader
|
# - goheader
|
||||||
# - gomodguard
|
# - gomodguard
|
||||||
|
|
||||||
|
# deprecated
|
||||||
|
# - deadcode
|
||||||
|
# - structcheck
|
||||||
|
# - varcheck
|
||||||
|
|
||||||
# don't enable:
|
# don't enable:
|
||||||
# - asciicheck
|
# - asciicheck
|
||||||
# - funlen
|
# - funlen
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
# TODO: FIXME
|
||||||
|
/.github/
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
ignore-from-file: [.gitignore, .yamlignore]
|
||||||
|
|
||||||
|
extends: default
|
||||||
|
|
||||||
|
rules:
|
||||||
|
line-length: disable
|
||||||
@@ -15,8 +15,8 @@ TEST_FORMAT = short-verbose
|
|||||||
endif
|
endif
|
||||||
|
|
||||||
# Dependency versions
|
# Dependency versions
|
||||||
GOTESTSUM_VERSION = 1.8.0
|
GOTESTSUM_VERSION = 1.9.0
|
||||||
GOLANGCI_VERSION = 1.45.2
|
GOLANGCI_VERSION = 1.53.3
|
||||||
|
|
||||||
# Add the ability to override some variables
|
# Add the ability to override some variables
|
||||||
# Use with care
|
# Use with care
|
||||||
@@ -29,11 +29,6 @@ clear: ## Clear the working area and the project
|
|||||||
.PHONY: check
|
.PHONY: check
|
||||||
check: test lint ## Run tests and linters
|
check: test lint ## Run tests and linters
|
||||||
|
|
||||||
bin/gotestsum: bin/gotestsum-${GOTESTSUM_VERSION}
|
|
||||||
@ln -sf gotestsum-${GOTESTSUM_VERSION} bin/gotestsum
|
|
||||||
bin/gotestsum-${GOTESTSUM_VERSION}:
|
|
||||||
@mkdir -p bin
|
|
||||||
curl -L https://github.com/gotestyourself/gotestsum/releases/download/v${GOTESTSUM_VERSION}/gotestsum_${GOTESTSUM_VERSION}_${OS}_amd64.tar.gz | tar -zOxf - gotestsum > ./bin/gotestsum-${GOTESTSUM_VERSION} && chmod +x ./bin/gotestsum-${GOTESTSUM_VERSION}
|
|
||||||
|
|
||||||
TEST_PKGS ?= ./...
|
TEST_PKGS ?= ./...
|
||||||
.PHONY: test
|
.PHONY: test
|
||||||
@@ -44,20 +39,36 @@ test: bin/gotestsum ## Run tests
|
|||||||
@mkdir -p ${BUILD_DIR}
|
@mkdir -p ${BUILD_DIR}
|
||||||
bin/gotestsum --no-summary=skipped --junitfile ${BUILD_DIR}/coverage.xml --format ${TEST_FORMAT} -- -race -coverprofile=${BUILD_DIR}/coverage.txt -covermode=atomic $(filter-out -v,${GOARGS}) $(if ${TEST_PKGS},${TEST_PKGS},./...)
|
bin/gotestsum --no-summary=skipped --junitfile ${BUILD_DIR}/coverage.xml --format ${TEST_FORMAT} -- -race -coverprofile=${BUILD_DIR}/coverage.txt -covermode=atomic $(filter-out -v,${GOARGS}) $(if ${TEST_PKGS},${TEST_PKGS},./...)
|
||||||
|
|
||||||
bin/golangci-lint: bin/golangci-lint-${GOLANGCI_VERSION}
|
|
||||||
@ln -sf golangci-lint-${GOLANGCI_VERSION} bin/golangci-lint
|
|
||||||
bin/golangci-lint-${GOLANGCI_VERSION}:
|
|
||||||
@mkdir -p bin
|
|
||||||
curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | bash -s -- -b ./bin/ v${GOLANGCI_VERSION}
|
|
||||||
@mv bin/golangci-lint "$@"
|
|
||||||
|
|
||||||
.PHONY: lint
|
.PHONY: lint
|
||||||
lint: bin/golangci-lint ## Run linter
|
lint: lint-go lint-yaml
|
||||||
bin/golangci-lint run
|
lint: ## Run linters
|
||||||
|
|
||||||
.PHONY: fix
|
.PHONY: lint-go
|
||||||
fix: bin/golangci-lint ## Fix lint violations
|
lint-go:
|
||||||
bin/golangci-lint run --fix
|
golangci-lint run $(if ${CI},--out-format github-actions,)
|
||||||
|
|
||||||
|
.PHONY: lint-yaml
|
||||||
|
lint-yaml:
|
||||||
|
yamllint $(if ${CI},-f github,) --no-warnings .
|
||||||
|
|
||||||
|
.PHONY: fmt
|
||||||
|
fmt: ## Format code
|
||||||
|
golangci-lint run --fix
|
||||||
|
|
||||||
|
deps: bin/golangci-lint bin/gotestsum yamllint
|
||||||
|
deps: ## Install dependencies
|
||||||
|
|
||||||
|
bin/gotestsum:
|
||||||
|
@mkdir -p bin
|
||||||
|
curl -L https://github.com/gotestyourself/gotestsum/releases/download/v${GOTESTSUM_VERSION}/gotestsum_${GOTESTSUM_VERSION}_${OS}_amd64.tar.gz | tar -zOxf - gotestsum > ./bin/gotestsum && chmod +x ./bin/gotestsum
|
||||||
|
|
||||||
|
bin/golangci-lint:
|
||||||
|
@mkdir -p bin
|
||||||
|
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | bash -s -- v${GOLANGCI_VERSION}
|
||||||
|
|
||||||
|
.PHONY: yamllint
|
||||||
|
yamllint:
|
||||||
|
pip3 install --user yamllint
|
||||||
|
|
||||||
# Add custom targets here
|
# Add custom targets here
|
||||||
-include custom.mk
|
-include custom.mk
|
||||||
|
|||||||
@@ -8,10 +8,10 @@
|
|||||||
[](https://github.com/avelino/awesome-go#configuration)
|
[](https://github.com/avelino/awesome-go#configuration)
|
||||||
[](https://repl.it/@sagikazarmark/Viper-example#main.go)
|
[](https://repl.it/@sagikazarmark/Viper-example#main.go)
|
||||||
|
|
||||||
[](https://github.com/spf13/viper/actions?query=workflow%3ACI)
|
[](https://github.com/spf13/viper/actions?query=workflow%3ACI)
|
||||||
[](https://gitter.im/spf13/viper?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
[](https://gitter.im/spf13/viper?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||||
[](https://goreportcard.com/report/github.com/spf13/viper)
|
[](https://goreportcard.com/report/github.com/spf13/viper)
|
||||||

|

|
||||||
[](https://pkg.go.dev/mod/github.com/spf13/viper)
|
[](https://pkg.go.dev/mod/github.com/spf13/viper)
|
||||||
|
|
||||||
**Go configuration with fangs!**
|
**Go configuration with fangs!**
|
||||||
@@ -27,6 +27,10 @@ Many Go projects are built using Viper including:
|
|||||||
* [doctl](https://github.com/digitalocean/doctl)
|
* [doctl](https://github.com/digitalocean/doctl)
|
||||||
* [Clairctl](https://github.com/jgsqware/clairctl)
|
* [Clairctl](https://github.com/jgsqware/clairctl)
|
||||||
* [Mercure](https://mercure.rocks)
|
* [Mercure](https://mercure.rocks)
|
||||||
|
* [Meshery](https://github.com/meshery/meshery)
|
||||||
|
* [Bearer](https://github.com/bearer/bearer)
|
||||||
|
* [Coder](https://github.com/coder/coder)
|
||||||
|
* [Vitess](https://vitess.io/)
|
||||||
|
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
@@ -40,8 +44,8 @@ go get github.com/spf13/viper
|
|||||||
|
|
||||||
## What is Viper?
|
## What is Viper?
|
||||||
|
|
||||||
Viper is a complete configuration solution for Go applications including 12-Factor apps. It is designed
|
Viper is a complete configuration solution for Go applications including [12-Factor apps](https://12factor.net/#the_twelve_factors).
|
||||||
to work within an application, and can handle all types of configuration needs
|
It is designed to work within an application, and can handle all types of configuration needs
|
||||||
and formats. It supports:
|
and formats. It supports:
|
||||||
|
|
||||||
* setting defaults
|
* setting defaults
|
||||||
@@ -119,7 +123,7 @@ viper.AddConfigPath("$HOME/.appname") // call multiple times to add many search
|
|||||||
viper.AddConfigPath(".") // optionally look for config in the working directory
|
viper.AddConfigPath(".") // optionally look for config in the working directory
|
||||||
err := viper.ReadInConfig() // Find and read the config file
|
err := viper.ReadInConfig() // Find and read the config file
|
||||||
if err != nil { // Handle errors reading the config file
|
if err != nil { // Handle errors reading the config file
|
||||||
panic(fmt.Errorf("Fatal error config file: %w \n", err))
|
panic(fmt.Errorf("fatal error config file: %w", err))
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -137,7 +141,7 @@ if err := viper.ReadInConfig(); err != nil {
|
|||||||
// Config file found and successfully parsed
|
// Config file found and successfully parsed
|
||||||
```
|
```
|
||||||
|
|
||||||
*NOTE [since 1.6]:* You can also have a file without an extension and specify the format programmaticaly. For those configuration files that lie in the home of the user without any extension like `.bashrc`
|
*NOTE [since 1.6]:* You can also have a file without an extension and specify the format programmatically. For those configuration files that lie in the home of the user without any extension like `.bashrc`
|
||||||
|
|
||||||
### Writing Config Files
|
### Writing Config Files
|
||||||
|
|
||||||
@@ -218,6 +222,7 @@ These could be from a command line flag, or from your own application logic.
|
|||||||
```go
|
```go
|
||||||
viper.Set("Verbose", true)
|
viper.Set("Verbose", true)
|
||||||
viper.Set("LogFile", LogFile)
|
viper.Set("LogFile", LogFile)
|
||||||
|
viper.Set("host.port", 5899) // set subset
|
||||||
```
|
```
|
||||||
|
|
||||||
### Registering and Using Aliases
|
### Registering and Using Aliases
|
||||||
@@ -413,6 +418,8 @@ in a Key/Value store such as etcd or Consul. These values take precedence over
|
|||||||
default values, but are overridden by configuration values retrieved from disk,
|
default values, but are overridden by configuration values retrieved from disk,
|
||||||
flags, or environment variables.
|
flags, or environment variables.
|
||||||
|
|
||||||
|
Viper supports multiple hosts. To use, pass a list of endpoints separated by `;`. For example `http://127.0.0.1:4001;http://127.0.0.1:4002`.
|
||||||
|
|
||||||
Viper uses [crypt](https://github.com/bketelsen/crypt) to retrieve
|
Viper uses [crypt](https://github.com/bketelsen/crypt) to retrieve
|
||||||
configuration from the K/V store, which means that you can store your
|
configuration from the K/V store, which means that you can store your
|
||||||
configuration values encrypted and have them automatically decrypted if you have
|
configuration values encrypted and have them automatically decrypted if you have
|
||||||
@@ -447,6 +454,13 @@ viper.SetConfigType("json") // because there is no file extension in a stream of
|
|||||||
err := viper.ReadRemoteConfig()
|
err := viper.ReadRemoteConfig()
|
||||||
```
|
```
|
||||||
|
|
||||||
|
#### etcd3
|
||||||
|
```go
|
||||||
|
viper.AddRemoteProvider("etcd3", "http://127.0.0.1:4001","/config/hugo.json")
|
||||||
|
viper.SetConfigType("json") // because there is no file extension in a stream of bytes, supported extensions are "json", "toml", "yaml", "yml", "properties", "props", "prop", "env", "dotenv"
|
||||||
|
err := viper.ReadRemoteConfig()
|
||||||
|
```
|
||||||
|
|
||||||
#### Consul
|
#### Consul
|
||||||
You need to set a key to Consul key/value storage with JSON value containing your desired config.
|
You need to set a key to Consul key/value storage with JSON value containing your desired config.
|
||||||
For example, create a Consul key/value store key `MY_CONSUL_KEY` with value:
|
For example, create a Consul key/value store key `MY_CONSUL_KEY` with value:
|
||||||
@@ -477,6 +491,15 @@ err := viper.ReadRemoteConfig()
|
|||||||
|
|
||||||
Of course, you're allowed to use `SecureRemoteProvider` also
|
Of course, you're allowed to use `SecureRemoteProvider` also
|
||||||
|
|
||||||
|
|
||||||
|
#### NATS
|
||||||
|
|
||||||
|
```go
|
||||||
|
viper.AddRemoteProvider("nats", "nats://127.0.0.1:4222", "myapp.config")
|
||||||
|
viper.SetConfigType("json")
|
||||||
|
err := viper.ReadRemoteConfig()
|
||||||
|
```
|
||||||
|
|
||||||
### Remote Key/Value Store Example - Encrypted
|
### Remote Key/Value Store Example - Encrypted
|
||||||
|
|
||||||
```go
|
```go
|
||||||
@@ -524,24 +547,27 @@ go func(){
|
|||||||
In Viper, there are a few ways to get a value depending on the value’s type.
|
In Viper, there are a few ways to get a value depending on the value’s type.
|
||||||
The following functions and methods exist:
|
The following functions and methods exist:
|
||||||
|
|
||||||
* `Get(key string) : interface{}`
|
* `Get(key string) : any`
|
||||||
* `GetBool(key string) : bool`
|
* `GetBool(key string) : bool`
|
||||||
* `GetFloat64(key string) : float64`
|
* `GetFloat64(key string) : float64`
|
||||||
* `GetInt(key string) : int`
|
* `GetInt(key string) : int`
|
||||||
* `GetIntSlice(key string) : []int`
|
* `GetIntSlice(key string) : []int`
|
||||||
* `GetString(key string) : string`
|
* `GetString(key string) : string`
|
||||||
* `GetStringMap(key string) : map[string]interface{}`
|
* `GetStringMap(key string) : map[string]any`
|
||||||
* `GetStringMapString(key string) : map[string]string`
|
* `GetStringMapString(key string) : map[string]string`
|
||||||
* `GetStringSlice(key string) : []string`
|
* `GetStringSlice(key string) : []string`
|
||||||
* `GetTime(key string) : time.Time`
|
* `GetTime(key string) : time.Time`
|
||||||
* `GetDuration(key string) : time.Duration`
|
* `GetDuration(key string) : time.Duration`
|
||||||
* `IsSet(key string) : bool`
|
* `IsSet(key string) : bool`
|
||||||
* `AllSettings() : map[string]interface{}`
|
* `AllSettings() : map[string]any`
|
||||||
|
|
||||||
One important thing to recognize is that each Get function will return a zero
|
One important thing to recognize is that each Get function will return a zero
|
||||||
value if it’s not found. To check if a given key exists, the `IsSet()` method
|
value if it’s not found. To check if a given key exists, the `IsSet()` method
|
||||||
has been provided.
|
has been provided.
|
||||||
|
|
||||||
|
The zero value will also be returned if the value is set, but fails to parse
|
||||||
|
as the requested type.
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
```go
|
```go
|
||||||
viper.GetString("logfile") // case-insensitive Setting & Getting
|
viper.GetString("logfile") // case-insensitive Setting & Getting
|
||||||
@@ -594,7 +620,7 @@ configuration level.
|
|||||||
|
|
||||||
Viper can access array indices by using numbers in the path. For example:
|
Viper can access array indices by using numbers in the path. For example:
|
||||||
|
|
||||||
```json
|
```jsonc
|
||||||
{
|
{
|
||||||
"host": {
|
"host": {
|
||||||
"address": "localhost",
|
"address": "localhost",
|
||||||
@@ -622,7 +648,7 @@ GetInt("host.ports.1") // returns 6029
|
|||||||
Lastly, if there exists a key that matches the delimited key path, its value
|
Lastly, if there exists a key that matches the delimited key path, its value
|
||||||
will be returned instead. E.g.
|
will be returned instead. E.g.
|
||||||
|
|
||||||
```json
|
```jsonc
|
||||||
{
|
{
|
||||||
"datastore.metric.host": "0.0.0.0",
|
"datastore.metric.host": "0.0.0.0",
|
||||||
"host": {
|
"host": {
|
||||||
@@ -699,8 +725,8 @@ etc.
|
|||||||
|
|
||||||
There are two methods to do this:
|
There are two methods to do this:
|
||||||
|
|
||||||
* `Unmarshal(rawVal interface{}) : error`
|
* `Unmarshal(rawVal any) : error`
|
||||||
* `UnmarshalKey(key string, rawVal interface{}) : error`
|
* `UnmarshalKey(key string, rawVal any) : error`
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
|
|
||||||
@@ -725,9 +751,9 @@ you have to change the delimiter:
|
|||||||
```go
|
```go
|
||||||
v := viper.NewWithOptions(viper.KeyDelimiter("::"))
|
v := viper.NewWithOptions(viper.KeyDelimiter("::"))
|
||||||
|
|
||||||
v.SetDefault("chart::values", map[string]interface{}{
|
v.SetDefault("chart::values", map[string]any{
|
||||||
"ingress": map[string]interface{}{
|
"ingress": map[string]any{
|
||||||
"annotations": map[string]interface{}{
|
"annotations": map[string]any{
|
||||||
"traefik.frontend.rule.type": "PathPrefix",
|
"traefik.frontend.rule.type": "PathPrefix",
|
||||||
"traefik.ingress.kubernetes.io/ssl-redirect": "true",
|
"traefik.ingress.kubernetes.io/ssl-redirect": "true",
|
||||||
},
|
},
|
||||||
@@ -736,7 +762,7 @@ v.SetDefault("chart::values", map[string]interface{}{
|
|||||||
|
|
||||||
type config struct {
|
type config struct {
|
||||||
Chart struct{
|
Chart struct{
|
||||||
Values map[string]interface{}
|
Values map[string]any
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -776,7 +802,7 @@ if err != nil {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Viper uses [github.com/mitchellh/mapstructure](https://github.com/mitchellh/mapstructure) under the hood for unmarshaling values which uses `mapstructure` tags by default.
|
Viper uses [github.com/go-viper/mapstructure](https://github.com/go-viper/mapstructure) under the hood for unmarshaling values which uses `mapstructure` tags by default.
|
||||||
|
|
||||||
### Decoding custom formats
|
### Decoding custom formats
|
||||||
|
|
||||||
@@ -872,3 +898,31 @@ No, you will need to synchronize access to the viper yourself (for example by us
|
|||||||
## Troubleshooting
|
## Troubleshooting
|
||||||
|
|
||||||
See [TROUBLESHOOTING.md](TROUBLESHOOTING.md).
|
See [TROUBLESHOOTING.md](TROUBLESHOOTING.md).
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
**For an optimal developer experience, it is recommended to install [Nix](https://nixos.org/download.html) and [direnv](https://direnv.net/docs/installation.html).**
|
||||||
|
|
||||||
|
_Alternatively, install [Go](https://go.dev/dl/) on your computer then run `make deps` to install the rest of the dependencies._
|
||||||
|
|
||||||
|
Run the test suite:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
make test
|
||||||
|
```
|
||||||
|
|
||||||
|
Run linters:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
make lint # pass -j option to run them in parallel
|
||||||
|
```
|
||||||
|
|
||||||
|
Some linter violations can automatically be fixed:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
make fmt
|
||||||
|
```
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
The project is licensed under the [MIT License](LICENSE).
|
||||||
|
|||||||
@@ -1,11 +0,0 @@
|
|||||||
//go:build viper_logger
|
|
||||||
// +build viper_logger
|
|
||||||
|
|
||||||
package viper
|
|
||||||
|
|
||||||
// WithLogger sets a custom logger.
|
|
||||||
func WithLogger(l Logger) Option {
|
|
||||||
return optionFunc(func(v *Viper) {
|
|
||||||
v.logger = l
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
//go:build !go1.16 || !finder
|
//go:build !finder
|
||||||
// +build !go1.16 !finder
|
|
||||||
|
|
||||||
package viper
|
package viper
|
||||||
|
|
||||||
@@ -44,7 +43,7 @@ func (v *Viper) searchInPath(in string) (filename string) {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if file Exists
|
// exists checks if file exists.
|
||||||
func exists(fs afero.Fs, path string) (bool, error) {
|
func exists(fs afero.Fs, path string) (bool, error) {
|
||||||
stat, err := fs.Stat(path)
|
stat, err := fs.Stat(path)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
//go:build finder
|
||||||
|
|
||||||
|
package viper
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/sagikazarmark/locafero"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Search all configPaths for any config file.
|
||||||
|
// Returns the first path that exists (and is a config file).
|
||||||
|
func (v *Viper) findConfigFile() (string, error) {
|
||||||
|
var names []string
|
||||||
|
|
||||||
|
if v.configType != "" {
|
||||||
|
names = locafero.NameWithOptionalExtensions(v.configName, SupportedExts...)
|
||||||
|
} else {
|
||||||
|
names = locafero.NameWithExtensions(v.configName, SupportedExts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
finder := locafero.Finder{
|
||||||
|
Paths: v.configPaths,
|
||||||
|
Names: names,
|
||||||
|
Type: locafero.FileTypeFile,
|
||||||
|
}
|
||||||
|
|
||||||
|
results, err := finder.Find(v.fs)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(results) == 0 {
|
||||||
|
return "", ConfigFileNotFoundError{v.configName, fmt.Sprintf("%s", v.configPaths)}
|
||||||
|
}
|
||||||
|
|
||||||
|
return results[0], nil
|
||||||
|
}
|
||||||
@@ -30,8 +30,8 @@ func (p pflagValueSet) VisitAll(fn func(flag FlagValue)) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// pflagValue is a wrapper aroung *pflag.flag
|
// pflagValue is a wrapper around *pflag.flag
|
||||||
// that implements FlagValue
|
// that implements FlagValue.
|
||||||
type pflagValue struct {
|
type pflagValue struct {
|
||||||
flag *pflag.Flag
|
flag *pflag.Flag
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-4
@@ -5,9 +5,11 @@ import (
|
|||||||
|
|
||||||
"github.com/spf13/pflag"
|
"github.com/spf13/pflag"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestBindFlagValueSet(t *testing.T) {
|
func TestBindFlagValueSet(t *testing.T) {
|
||||||
|
Reset()
|
||||||
flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
|
flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
|
||||||
|
|
||||||
testValues := map[string]*string{
|
testValues := map[string]*string{
|
||||||
@@ -29,9 +31,7 @@ func TestBindFlagValueSet(t *testing.T) {
|
|||||||
flagValueSet := pflagValueSet{flagSet}
|
flagValueSet := pflagValueSet{flagSet}
|
||||||
|
|
||||||
err := BindFlagValues(flagValueSet)
|
err := BindFlagValues(flagValueSet)
|
||||||
if err != nil {
|
require.NoError(t, err, "error binding flag set")
|
||||||
t.Fatalf("error binding flag set, %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
flagSet.VisitAll(func(flag *pflag.Flag) {
|
flagSet.VisitAll(func(flag *pflag.Flag) {
|
||||||
flag.Value.Set(mutatedTestValues[flag.Name])
|
flag.Value.Set(mutatedTestValues[flag.Name])
|
||||||
@@ -39,7 +39,7 @@ func TestBindFlagValueSet(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
for name, expected := range mutatedTestValues {
|
for name, expected := range mutatedTestValues {
|
||||||
assert.Equal(t, Get(name), expected)
|
assert.Equal(t, expected, Get(name))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Generated
+255
@@ -0,0 +1,255 @@
|
|||||||
|
{
|
||||||
|
"nodes": {
|
||||||
|
"devenv": {
|
||||||
|
"inputs": {
|
||||||
|
"flake-compat": "flake-compat",
|
||||||
|
"nix": "nix",
|
||||||
|
"nixpkgs": "nixpkgs",
|
||||||
|
"pre-commit-hooks": "pre-commit-hooks"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1687972261,
|
||||||
|
"narHash": "sha256-+mxvZfwMVoaZYETmuQWqTi/7T9UKoAE+WpdSQkOVJ2g=",
|
||||||
|
"owner": "cachix",
|
||||||
|
"repo": "devenv",
|
||||||
|
"rev": "e85df562088573305e55906eaa964341f8cb0d9f",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "cachix",
|
||||||
|
"repo": "devenv",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"flake-compat": {
|
||||||
|
"flake": false,
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1673956053,
|
||||||
|
"narHash": "sha256-4gtG9iQuiKITOjNQQeQIpoIB6b16fm+504Ch3sNKLd8=",
|
||||||
|
"owner": "edolstra",
|
||||||
|
"repo": "flake-compat",
|
||||||
|
"rev": "35bb57c0c8d8b62bbfd284272c928ceb64ddbde9",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "edolstra",
|
||||||
|
"repo": "flake-compat",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"flake-parts": {
|
||||||
|
"inputs": {
|
||||||
|
"nixpkgs-lib": "nixpkgs-lib"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1687762428,
|
||||||
|
"narHash": "sha256-DIf7mi45PKo+s8dOYF+UlXHzE0Wl/+k3tXUyAoAnoGE=",
|
||||||
|
"owner": "hercules-ci",
|
||||||
|
"repo": "flake-parts",
|
||||||
|
"rev": "37dd7bb15791c86d55c5121740a1887ab55ee836",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "hercules-ci",
|
||||||
|
"repo": "flake-parts",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"flake-utils": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1667395993,
|
||||||
|
"narHash": "sha256-nuEHfE/LcWyuSWnS8t12N1wc105Qtau+/OdUAjtQ0rA=",
|
||||||
|
"owner": "numtide",
|
||||||
|
"repo": "flake-utils",
|
||||||
|
"rev": "5aed5285a952e0b949eb3ba02c12fa4fcfef535f",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "numtide",
|
||||||
|
"repo": "flake-utils",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"gitignore": {
|
||||||
|
"inputs": {
|
||||||
|
"nixpkgs": [
|
||||||
|
"devenv",
|
||||||
|
"pre-commit-hooks",
|
||||||
|
"nixpkgs"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1660459072,
|
||||||
|
"narHash": "sha256-8DFJjXG8zqoONA1vXtgeKXy68KdJL5UaXR8NtVMUbx8=",
|
||||||
|
"owner": "hercules-ci",
|
||||||
|
"repo": "gitignore.nix",
|
||||||
|
"rev": "a20de23b925fd8264fd7fad6454652e142fd7f73",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "hercules-ci",
|
||||||
|
"repo": "gitignore.nix",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"lowdown-src": {
|
||||||
|
"flake": false,
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1633514407,
|
||||||
|
"narHash": "sha256-Dw32tiMjdK9t3ETl5fzGrutQTzh2rufgZV4A/BbxuD4=",
|
||||||
|
"owner": "kristapsdz",
|
||||||
|
"repo": "lowdown",
|
||||||
|
"rev": "d2c2b44ff6c27b936ec27358a2653caaef8f73b8",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "kristapsdz",
|
||||||
|
"repo": "lowdown",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nix": {
|
||||||
|
"inputs": {
|
||||||
|
"lowdown-src": "lowdown-src",
|
||||||
|
"nixpkgs": [
|
||||||
|
"devenv",
|
||||||
|
"nixpkgs"
|
||||||
|
],
|
||||||
|
"nixpkgs-regression": "nixpkgs-regression"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1676545802,
|
||||||
|
"narHash": "sha256-EK4rZ+Hd5hsvXnzSzk2ikhStJnD63odF7SzsQ8CuSPU=",
|
||||||
|
"owner": "domenkozar",
|
||||||
|
"repo": "nix",
|
||||||
|
"rev": "7c91803598ffbcfe4a55c44ac6d49b2cf07a527f",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "domenkozar",
|
||||||
|
"ref": "relaxed-flakes",
|
||||||
|
"repo": "nix",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nixpkgs": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1678875422,
|
||||||
|
"narHash": "sha256-T3o6NcQPwXjxJMn2shz86Chch4ljXgZn746c2caGxd8=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "126f49a01de5b7e35a43fd43f891ecf6d3a51459",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "NixOS",
|
||||||
|
"ref": "nixpkgs-unstable",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nixpkgs-lib": {
|
||||||
|
"locked": {
|
||||||
|
"dir": "lib",
|
||||||
|
"lastModified": 1685564631,
|
||||||
|
"narHash": "sha256-8ywr3AkblY4++3lIVxmrWZFzac7+f32ZEhH/A8pNscI=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "4f53efe34b3a8877ac923b9350c874e3dcd5dc0a",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"dir": "lib",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"ref": "nixos-unstable",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nixpkgs-regression": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1643052045,
|
||||||
|
"narHash": "sha256-uGJ0VXIhWKGXxkeNnq4TvV3CIOkUJ3PAoLZ3HMzNVMw=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nixpkgs-stable": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1678872516,
|
||||||
|
"narHash": "sha256-/E1YwtMtFAu2KUQKV/1+KFuReYPANM2Rzehk84VxVoc=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "9b8e5abb18324c7fe9f07cb100c3cd4a29cda8b8",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "NixOS",
|
||||||
|
"ref": "nixos-22.11",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nixpkgs_2": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1687886075,
|
||||||
|
"narHash": "sha256-PeayJDDDy+uw1Ats4moZnRdL1OFuZm1Tj+KiHlD67+o=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "a565059a348422af5af9026b5174dc5c0dcefdae",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "NixOS",
|
||||||
|
"ref": "nixpkgs-unstable",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"pre-commit-hooks": {
|
||||||
|
"inputs": {
|
||||||
|
"flake-compat": [
|
||||||
|
"devenv",
|
||||||
|
"flake-compat"
|
||||||
|
],
|
||||||
|
"flake-utils": "flake-utils",
|
||||||
|
"gitignore": "gitignore",
|
||||||
|
"nixpkgs": [
|
||||||
|
"devenv",
|
||||||
|
"nixpkgs"
|
||||||
|
],
|
||||||
|
"nixpkgs-stable": "nixpkgs-stable"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1686050334,
|
||||||
|
"narHash": "sha256-R0mczWjDzBpIvM3XXhO908X5e2CQqjyh/gFbwZk/7/Q=",
|
||||||
|
"owner": "cachix",
|
||||||
|
"repo": "pre-commit-hooks.nix",
|
||||||
|
"rev": "6881eb2ae5d8a3516e34714e7a90d9d95914c4dc",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "cachix",
|
||||||
|
"repo": "pre-commit-hooks.nix",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": {
|
||||||
|
"inputs": {
|
||||||
|
"devenv": "devenv",
|
||||||
|
"flake-parts": "flake-parts",
|
||||||
|
"nixpkgs": "nixpkgs_2"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": "root",
|
||||||
|
"version": 7
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
{
|
||||||
|
description = "Viper";
|
||||||
|
|
||||||
|
inputs = {
|
||||||
|
nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
|
||||||
|
flake-parts.url = "github:hercules-ci/flake-parts";
|
||||||
|
devenv.url = "github:cachix/devenv";
|
||||||
|
};
|
||||||
|
|
||||||
|
outputs = inputs@{ flake-parts, ... }:
|
||||||
|
flake-parts.lib.mkFlake { inherit inputs; } {
|
||||||
|
imports = [
|
||||||
|
inputs.devenv.flakeModule
|
||||||
|
];
|
||||||
|
|
||||||
|
systems = [ "x86_64-linux" "x86_64-darwin" "aarch64-darwin" ];
|
||||||
|
|
||||||
|
perSystem = { config, self', inputs', pkgs, system, ... }: rec {
|
||||||
|
devenv.shells = {
|
||||||
|
default = {
|
||||||
|
languages = {
|
||||||
|
go.enable = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
pre-commit.hooks = {
|
||||||
|
nixpkgs-fmt.enable = true;
|
||||||
|
yamllint.enable = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
packages = with pkgs; [
|
||||||
|
gnumake
|
||||||
|
|
||||||
|
golangci-lint
|
||||||
|
yamllint
|
||||||
|
];
|
||||||
|
|
||||||
|
scripts = {
|
||||||
|
versions.exec = ''
|
||||||
|
go version
|
||||||
|
golangci-lint version
|
||||||
|
'';
|
||||||
|
};
|
||||||
|
|
||||||
|
enterShell = ''
|
||||||
|
versions
|
||||||
|
'';
|
||||||
|
|
||||||
|
# https://github.com/cachix/devenv/issues/528#issuecomment-1556108767
|
||||||
|
containers = pkgs.lib.mkForce { };
|
||||||
|
};
|
||||||
|
|
||||||
|
ci = devenv.shells.default;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
//go:build go1.16 && finder
|
|
||||||
// +build go1.16,finder
|
|
||||||
|
|
||||||
package viper
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"io/fs"
|
|
||||||
"path"
|
|
||||||
)
|
|
||||||
|
|
||||||
type finder struct {
|
|
||||||
paths []string
|
|
||||||
fileNames []string
|
|
||||||
extensions []string
|
|
||||||
|
|
||||||
withoutExtension bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f finder) Find(fsys fs.FS) (string, error) {
|
|
||||||
for _, searchPath := range f.paths {
|
|
||||||
for _, fileName := range f.fileNames {
|
|
||||||
for _, extension := range f.extensions {
|
|
||||||
filePath := path.Join(searchPath, fileName+"."+extension)
|
|
||||||
|
|
||||||
ok, err := fileExists(fsys, filePath)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
if ok {
|
|
||||||
return filePath, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if f.withoutExtension {
|
|
||||||
filePath := path.Join(searchPath, fileName)
|
|
||||||
|
|
||||||
ok, err := fileExists(fsys, filePath)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
if ok {
|
|
||||||
return filePath, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return "", nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func fileExists(fsys fs.FS, filePath string) (bool, error) {
|
|
||||||
fileInfo, err := fs.Stat(fsys, filePath)
|
|
||||||
if err == nil {
|
|
||||||
return !fileInfo.IsDir(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if errors.Is(err, fs.ErrNotExist) {
|
|
||||||
return false, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return false, err
|
|
||||||
}
|
|
||||||
-100
@@ -1,100 +0,0 @@
|
|||||||
//go:build go1.16 && finder
|
|
||||||
// +build go1.16,finder
|
|
||||||
|
|
||||||
package viper
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io/fs"
|
|
||||||
"testing"
|
|
||||||
"testing/fstest"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestFinder(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
fsys := fstest.MapFS{
|
|
||||||
"home/user/.config": &fstest.MapFile{},
|
|
||||||
"home/user/config.json": &fstest.MapFile{},
|
|
||||||
"home/user/config.yaml": &fstest.MapFile{},
|
|
||||||
"home/user/data.json": &fstest.MapFile{},
|
|
||||||
"etc/config/.config": &fstest.MapFile{},
|
|
||||||
"etc/config/a_random_file.txt": &fstest.MapFile{},
|
|
||||||
"etc/config/config.json": &fstest.MapFile{},
|
|
||||||
"etc/config/config.yaml": &fstest.MapFile{},
|
|
||||||
"etc/config/config.xml": &fstest.MapFile{},
|
|
||||||
}
|
|
||||||
|
|
||||||
testCases := []struct {
|
|
||||||
name string
|
|
||||||
fsys func() fs.FS
|
|
||||||
finder finder
|
|
||||||
result string
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "find file",
|
|
||||||
fsys: func() fs.FS { return fsys },
|
|
||||||
finder: finder{
|
|
||||||
paths: []string{"etc/config"},
|
|
||||||
fileNames: []string{"config"},
|
|
||||||
extensions: []string{"json"},
|
|
||||||
},
|
|
||||||
result: "etc/config/config.json",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "file not found",
|
|
||||||
fsys: func() fs.FS { return fsys },
|
|
||||||
finder: finder{
|
|
||||||
paths: []string{"var/config"},
|
|
||||||
fileNames: []string{"config"},
|
|
||||||
extensions: []string{"json"},
|
|
||||||
},
|
|
||||||
result: "",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "empty search params",
|
|
||||||
fsys: func() fs.FS { return fsys },
|
|
||||||
finder: finder{},
|
|
||||||
result: "",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "precedence",
|
|
||||||
fsys: func() fs.FS { return fsys },
|
|
||||||
finder: finder{
|
|
||||||
paths: []string{"var/config", "home/user", "etc/config"},
|
|
||||||
fileNames: []string{"aconfig", "config"},
|
|
||||||
extensions: []string{"zml", "xml", "json"},
|
|
||||||
},
|
|
||||||
result: "home/user/config.json",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "without extension",
|
|
||||||
fsys: func() fs.FS { return fsys },
|
|
||||||
finder: finder{
|
|
||||||
paths: []string{"var/config", "home/user", "etc/config"},
|
|
||||||
fileNames: []string{".config"},
|
|
||||||
extensions: []string{"zml", "xml", "json"},
|
|
||||||
|
|
||||||
withoutExtension: true,
|
|
||||||
},
|
|
||||||
result: "home/user/.config",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, testCase := range testCases {
|
|
||||||
testCase := testCase
|
|
||||||
|
|
||||||
t.Run(testCase.name, func(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
fsys := testCase.fsys()
|
|
||||||
|
|
||||||
result, err := testCase.finder.Find(fsys)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
assert.Equal(t, testCase.result, result)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,72 +1,85 @@
|
|||||||
module github.com/spf13/viper
|
module github.com/spf13/viper
|
||||||
|
|
||||||
go 1.17
|
go 1.18
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/fsnotify/fsnotify v1.5.4
|
github.com/fsnotify/fsnotify v1.7.0
|
||||||
|
github.com/go-viper/mapstructure/v2 v2.0.0-alpha.1
|
||||||
github.com/hashicorp/hcl v1.0.0
|
github.com/hashicorp/hcl v1.0.0
|
||||||
github.com/magiconair/properties v1.8.6
|
github.com/magiconair/properties v1.8.7
|
||||||
github.com/mitchellh/mapstructure v1.5.0
|
github.com/pelletier/go-toml/v2 v2.1.1
|
||||||
github.com/pelletier/go-toml v1.9.5
|
github.com/sagikazarmark/crypt v0.17.0
|
||||||
github.com/pelletier/go-toml/v2 v2.0.1
|
github.com/sagikazarmark/locafero v0.4.0
|
||||||
github.com/sagikazarmark/crypt v0.6.0
|
github.com/sagikazarmark/slog-shim v0.1.0
|
||||||
github.com/spf13/afero v1.8.2
|
github.com/spf13/afero v1.11.0
|
||||||
github.com/spf13/cast v1.5.0
|
github.com/spf13/cast v1.6.0
|
||||||
github.com/spf13/jwalterweatherman v1.1.0
|
|
||||||
github.com/spf13/pflag v1.0.5
|
github.com/spf13/pflag v1.0.5
|
||||||
github.com/stretchr/testify v1.7.1
|
github.com/stretchr/testify v1.8.4
|
||||||
github.com/subosito/gotenv v1.3.0
|
github.com/subosito/gotenv v1.6.0
|
||||||
gopkg.in/ini.v1 v1.66.4
|
gopkg.in/ini.v1 v1.67.0
|
||||||
gopkg.in/yaml.v2 v2.4.0
|
gopkg.in/yaml.v3 v3.0.1
|
||||||
gopkg.in/yaml.v3 v3.0.0
|
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
cloud.google.com/go v0.100.2 // indirect
|
cloud.google.com/go v0.110.10 // indirect
|
||||||
cloud.google.com/go/compute v1.6.1 // indirect
|
cloud.google.com/go/compute v1.23.3 // indirect
|
||||||
cloud.google.com/go/firestore v1.6.1 // indirect
|
cloud.google.com/go/compute/metadata v0.2.3 // indirect
|
||||||
github.com/armon/go-metrics v0.3.10 // indirect
|
cloud.google.com/go/firestore v1.14.0 // indirect
|
||||||
|
cloud.google.com/go/longrunning v0.5.4 // indirect
|
||||||
|
github.com/armon/go-metrics v0.4.1 // indirect
|
||||||
github.com/coreos/go-semver v0.3.0 // indirect
|
github.com/coreos/go-semver v0.3.0 // indirect
|
||||||
github.com/coreos/go-systemd/v22 v22.3.2 // indirect
|
github.com/coreos/go-systemd/v22 v22.3.2 // indirect
|
||||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||||
github.com/fatih/color v1.13.0 // indirect
|
github.com/fatih/color v1.14.1 // indirect
|
||||||
github.com/gogo/protobuf v1.3.2 // indirect
|
github.com/gogo/protobuf v1.3.2 // indirect
|
||||||
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
|
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
|
||||||
github.com/golang/protobuf v1.5.2 // indirect
|
github.com/golang/protobuf v1.5.3 // indirect
|
||||||
github.com/google/go-cmp v0.5.8 // indirect
|
github.com/google/s2a-go v0.1.7 // indirect
|
||||||
github.com/googleapis/gax-go/v2 v2.4.0 // indirect
|
github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect
|
||||||
github.com/hashicorp/consul/api v1.12.0 // indirect
|
github.com/googleapis/gax-go/v2 v2.12.0 // indirect
|
||||||
|
github.com/hashicorp/consul/api v1.25.1 // indirect
|
||||||
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
|
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
|
||||||
github.com/hashicorp/go-hclog v1.2.0 // indirect
|
github.com/hashicorp/go-hclog v1.5.0 // indirect
|
||||||
github.com/hashicorp/go-immutable-radix v1.3.1 // indirect
|
github.com/hashicorp/go-immutable-radix v1.3.1 // indirect
|
||||||
github.com/hashicorp/go-rootcerts v1.0.2 // indirect
|
github.com/hashicorp/go-rootcerts v1.0.2 // indirect
|
||||||
github.com/hashicorp/golang-lru v0.5.4 // indirect
|
github.com/hashicorp/golang-lru v0.5.4 // indirect
|
||||||
github.com/hashicorp/serf v0.9.7 // indirect
|
github.com/hashicorp/serf v0.10.1 // indirect
|
||||||
github.com/json-iterator/go v1.1.12 // indirect
|
github.com/json-iterator/go v1.1.12 // indirect
|
||||||
github.com/mattn/go-colorable v0.1.12 // indirect
|
github.com/klauspost/compress v1.17.0 // indirect
|
||||||
github.com/mattn/go-isatty v0.0.14 // indirect
|
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||||
|
github.com/mattn/go-isatty v0.0.17 // indirect
|
||||||
github.com/mitchellh/go-homedir v1.1.0 // indirect
|
github.com/mitchellh/go-homedir v1.1.0 // indirect
|
||||||
|
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||||
|
github.com/nats-io/nats.go v1.31.0 // indirect
|
||||||
|
github.com/nats-io/nkeys v0.4.6 // indirect
|
||||||
|
github.com/nats-io/nuid v1.0.1 // indirect
|
||||||
github.com/pkg/errors v0.9.1 // indirect
|
github.com/pkg/errors v0.9.1 // indirect
|
||||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||||
go.etcd.io/etcd/api/v3 v3.5.4 // indirect
|
github.com/sourcegraph/conc v0.3.0 // indirect
|
||||||
go.etcd.io/etcd/client/pkg/v3 v3.5.4 // indirect
|
go.etcd.io/etcd/api/v3 v3.5.10 // indirect
|
||||||
go.etcd.io/etcd/client/v2 v2.305.4 // indirect
|
go.etcd.io/etcd/client/pkg/v3 v3.5.10 // indirect
|
||||||
go.etcd.io/etcd/client/v3 v3.5.4 // indirect
|
go.etcd.io/etcd/client/v2 v2.305.10 // indirect
|
||||||
go.opencensus.io v0.23.0 // indirect
|
go.etcd.io/etcd/client/v3 v3.5.10 // indirect
|
||||||
go.uber.org/atomic v1.7.0 // indirect
|
go.opencensus.io v0.24.0 // indirect
|
||||||
go.uber.org/multierr v1.6.0 // indirect
|
go.uber.org/atomic v1.9.0 // indirect
|
||||||
go.uber.org/zap v1.17.0 // indirect
|
go.uber.org/multierr v1.9.0 // indirect
|
||||||
golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 // indirect
|
go.uber.org/zap v1.21.0 // indirect
|
||||||
golang.org/x/net v0.0.0-20220520000938-2e3eb7b945c2 // indirect
|
golang.org/x/crypto v0.16.0 // indirect
|
||||||
golang.org/x/oauth2 v0.0.0-20220411215720-9780585627b5 // indirect
|
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
|
||||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a // indirect
|
golang.org/x/net v0.19.0 // indirect
|
||||||
golang.org/x/text v0.3.7 // indirect
|
golang.org/x/oauth2 v0.15.0 // indirect
|
||||||
golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df // indirect
|
golang.org/x/sync v0.5.0 // indirect
|
||||||
google.golang.org/api v0.81.0 // indirect
|
golang.org/x/sys v0.15.0 // indirect
|
||||||
|
golang.org/x/text v0.14.0 // indirect
|
||||||
|
golang.org/x/time v0.5.0 // indirect
|
||||||
|
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect
|
||||||
|
google.golang.org/api v0.153.0 // indirect
|
||||||
google.golang.org/appengine v1.6.7 // indirect
|
google.golang.org/appengine v1.6.7 // indirect
|
||||||
google.golang.org/genproto v0.0.0-20220519153652-3a47de7e79bd // indirect
|
google.golang.org/genproto v0.0.0-20231106174013-bbf56f31fb17 // indirect
|
||||||
google.golang.org/grpc v1.46.2 // indirect
|
google.golang.org/genproto/googleapis/api v0.0.0-20231106174013-bbf56f31fb17 // indirect
|
||||||
google.golang.org/protobuf v1.28.0 // indirect
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20231120223509-83a465c0220f // indirect
|
||||||
|
google.golang.org/grpc v1.59.0 // indirect
|
||||||
|
google.golang.org/protobuf v1.31.0 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -5,9 +5,9 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Decoder decodes the contents of b into v.
|
// Decoder decodes the contents of b into v.
|
||||||
// It's primarily used for decoding contents of a file into a map[string]interface{}.
|
// It's primarily used for decoding contents of a file into a map[string]any.
|
||||||
type Decoder interface {
|
type Decoder interface {
|
||||||
Decode(b []byte, v map[string]interface{}) error
|
Decode(b []byte, v map[string]any) error
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -48,7 +48,7 @@ func (e *DecoderRegistry) RegisterDecoder(format string, enc Decoder) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Decode calls the underlying Decoder based on the format.
|
// Decode calls the underlying Decoder based on the format.
|
||||||
func (e *DecoderRegistry) Decode(format string, b []byte, v map[string]interface{}) error {
|
func (e *DecoderRegistry) Decode(format string, b []byte, v map[string]any) error {
|
||||||
e.mu.RLock()
|
e.mu.RLock()
|
||||||
decoder, ok := e.decoders[format]
|
decoder, ok := e.decoders[format]
|
||||||
e.mu.RUnlock()
|
e.mu.RUnlock()
|
||||||
|
|||||||
@@ -1,15 +1,17 @@
|
|||||||
package encoding
|
package encoding
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"reflect"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
type decoder struct {
|
type decoder struct {
|
||||||
v map[string]interface{}
|
v map[string]any
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d decoder) Decode(_ []byte, v map[string]interface{}) error {
|
func (d decoder) Decode(_ []byte, v map[string]any) error {
|
||||||
for key, value := range d.v {
|
for key, value := range d.v {
|
||||||
v[key] = value
|
v[key] = value
|
||||||
}
|
}
|
||||||
@@ -22,23 +24,17 @@ func TestDecoderRegistry_RegisterDecoder(t *testing.T) {
|
|||||||
registry := NewDecoderRegistry()
|
registry := NewDecoderRegistry()
|
||||||
|
|
||||||
err := registry.RegisterDecoder("myformat", decoder{})
|
err := registry.RegisterDecoder("myformat", decoder{})
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("AlreadyRegistered", func(t *testing.T) {
|
t.Run("AlreadyRegistered", func(t *testing.T) {
|
||||||
registry := NewDecoderRegistry()
|
registry := NewDecoderRegistry()
|
||||||
|
|
||||||
err := registry.RegisterDecoder("myformat", decoder{})
|
err := registry.RegisterDecoder("myformat", decoder{})
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = registry.RegisterDecoder("myformat", decoder{})
|
err = registry.RegisterDecoder("myformat", decoder{})
|
||||||
if err != ErrDecoderFormatAlreadyRegistered {
|
assert.ErrorIs(t, err, ErrDecoderFormatAlreadyRegistered)
|
||||||
t.Fatalf("expected ErrDecoderFormatAlreadyRegistered, got: %v", err)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,36 +42,28 @@ func TestDecoderRegistry_Decode(t *testing.T) {
|
|||||||
t.Run("OK", func(t *testing.T) {
|
t.Run("OK", func(t *testing.T) {
|
||||||
registry := NewDecoderRegistry()
|
registry := NewDecoderRegistry()
|
||||||
decoder := decoder{
|
decoder := decoder{
|
||||||
v: map[string]interface{}{
|
v: map[string]any{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
err := registry.RegisterDecoder("myformat", decoder)
|
err := registry.RegisterDecoder("myformat", decoder)
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
v := map[string]interface{}{}
|
v := map[string]any{}
|
||||||
|
|
||||||
err = registry.Decode("myformat", []byte("key: value"), v)
|
err = registry.Decode("myformat", []byte("key: value"), v)
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !reflect.DeepEqual(decoder.v, v) {
|
assert.Equal(t, decoder.v, v)
|
||||||
t.Fatalf("decoded value does not match the expected one\nactual: %+v\nexpected: %+v", v, decoder.v)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("DecoderNotFound", func(t *testing.T) {
|
t.Run("DecoderNotFound", func(t *testing.T) {
|
||||||
registry := NewDecoderRegistry()
|
registry := NewDecoderRegistry()
|
||||||
|
|
||||||
v := map[string]interface{}{}
|
v := map[string]any{}
|
||||||
|
|
||||||
err := registry.Decode("myformat", nil, v)
|
err := registry.Decode("myformat", nil, v)
|
||||||
if err != ErrDecoderNotFound {
|
assert.ErrorIs(t, err, ErrDecoderNotFound)
|
||||||
t.Fatalf("expected ErrDecoderNotFound, got: %v", err)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,8 +15,8 @@ const keyDelimiter = "_"
|
|||||||
// (commonly called as dotenv format).
|
// (commonly called as dotenv format).
|
||||||
type Codec struct{}
|
type Codec struct{}
|
||||||
|
|
||||||
func (Codec) Encode(v map[string]interface{}) ([]byte, error) {
|
func (Codec) Encode(v map[string]any) ([]byte, error) {
|
||||||
flattened := map[string]interface{}{}
|
flattened := map[string]any{}
|
||||||
|
|
||||||
flattened = flattenAndMergeMap(flattened, v, "", keyDelimiter)
|
flattened = flattenAndMergeMap(flattened, v, "", keyDelimiter)
|
||||||
|
|
||||||
@@ -40,7 +40,7 @@ func (Codec) Encode(v map[string]interface{}) ([]byte, error) {
|
|||||||
return buf.Bytes(), nil
|
return buf.Bytes(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (Codec) Decode(b []byte, v map[string]interface{}) error {
|
func (Codec) Decode(b []byte, v map[string]any) error {
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
|
|
||||||
_, err := buf.Write(b)
|
_, err := buf.Write(b)
|
||||||
|
|||||||
@@ -1,21 +1,23 @@
|
|||||||
package dotenv
|
package dotenv
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"reflect"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
// original form of the data
|
// original form of the data.
|
||||||
const original = `# key-value pair
|
const original = `# key-value pair
|
||||||
KEY=value
|
KEY=value
|
||||||
`
|
`
|
||||||
|
|
||||||
// encoded form of the data
|
// encoded form of the data.
|
||||||
const encoded = `KEY=value
|
const encoded = `KEY=value
|
||||||
`
|
`
|
||||||
|
|
||||||
// Viper's internal representation
|
// data is Viper's internal representation.
|
||||||
var data = map[string]interface{}{
|
var data = map[string]any{
|
||||||
"KEY": "value",
|
"KEY": "value",
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,40 +25,30 @@ func TestCodec_Encode(t *testing.T) {
|
|||||||
codec := Codec{}
|
codec := Codec{}
|
||||||
|
|
||||||
b, err := codec.Encode(data)
|
b, err := codec.Encode(data)
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if encoded != string(b) {
|
assert.Equal(t, encoded, string(b))
|
||||||
t.Fatalf("decoded value does not match the expected one\nactual: %#v\nexpected: %#v", string(b), encoded)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCodec_Decode(t *testing.T) {
|
func TestCodec_Decode(t *testing.T) {
|
||||||
t.Run("OK", func(t *testing.T) {
|
t.Run("OK", func(t *testing.T) {
|
||||||
codec := Codec{}
|
codec := Codec{}
|
||||||
|
|
||||||
v := map[string]interface{}{}
|
v := map[string]any{}
|
||||||
|
|
||||||
err := codec.Decode([]byte(original), v)
|
err := codec.Decode([]byte(original), v)
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !reflect.DeepEqual(data, v) {
|
assert.Equal(t, data, v)
|
||||||
t.Fatalf("decoded value does not match the expected one\nactual: %#v\nexpected: %#v", v, data)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("InvalidData", func(t *testing.T) {
|
t.Run("InvalidData", func(t *testing.T) {
|
||||||
codec := Codec{}
|
codec := Codec{}
|
||||||
|
|
||||||
v := map[string]interface{}{}
|
v := map[string]any{}
|
||||||
|
|
||||||
err := codec.Decode([]byte(`invalid data`), v)
|
err := codec.Decode([]byte(`invalid data`), v)
|
||||||
if err == nil {
|
require.Error(t, err)
|
||||||
t.Fatal("expected decoding to fail")
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Logf("decoding failed as expected: %s", err)
|
t.Logf("decoding failed as expected: %s", err)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -7,27 +7,27 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// flattenAndMergeMap recursively flattens the given map into a new map
|
// flattenAndMergeMap recursively flattens the given map into a new map
|
||||||
// Code is based on the function with the same name in tha main package.
|
// Code is based on the function with the same name in the main package.
|
||||||
// TODO: move it to a common place
|
// TODO: move it to a common place.
|
||||||
func flattenAndMergeMap(shadow map[string]interface{}, m map[string]interface{}, prefix string, delimiter string) map[string]interface{} {
|
func flattenAndMergeMap(shadow, m map[string]any, prefix, delimiter string) map[string]any {
|
||||||
if shadow != nil && prefix != "" && shadow[prefix] != nil {
|
if shadow != nil && prefix != "" && shadow[prefix] != nil {
|
||||||
// prefix is shadowed => nothing more to flatten
|
// prefix is shadowed => nothing more to flatten
|
||||||
return shadow
|
return shadow
|
||||||
}
|
}
|
||||||
if shadow == nil {
|
if shadow == nil {
|
||||||
shadow = make(map[string]interface{})
|
shadow = make(map[string]any)
|
||||||
}
|
}
|
||||||
|
|
||||||
var m2 map[string]interface{}
|
var m2 map[string]any
|
||||||
if prefix != "" {
|
if prefix != "" {
|
||||||
prefix += delimiter
|
prefix += delimiter
|
||||||
}
|
}
|
||||||
for k, val := range m {
|
for k, val := range m {
|
||||||
fullKey := prefix + k
|
fullKey := prefix + k
|
||||||
switch val.(type) {
|
switch val := val.(type) {
|
||||||
case map[string]interface{}:
|
case map[string]any:
|
||||||
m2 = val.(map[string]interface{})
|
m2 = val
|
||||||
case map[interface{}]interface{}:
|
case map[any]any:
|
||||||
m2 = cast.ToStringMap(val)
|
m2 = cast.ToStringMap(val)
|
||||||
default:
|
default:
|
||||||
// immediate value
|
// immediate value
|
||||||
|
|||||||
@@ -5,9 +5,9 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Encoder encodes the contents of v into a byte representation.
|
// Encoder encodes the contents of v into a byte representation.
|
||||||
// It's primarily used for encoding a map[string]interface{} into a file format.
|
// It's primarily used for encoding a map[string]any into a file format.
|
||||||
type Encoder interface {
|
type Encoder interface {
|
||||||
Encode(v map[string]interface{}) ([]byte, error)
|
Encode(v map[string]any) ([]byte, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -47,7 +47,7 @@ func (e *EncoderRegistry) RegisterEncoder(format string, enc Encoder) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (e *EncoderRegistry) Encode(format string, v map[string]interface{}) ([]byte, error) {
|
func (e *EncoderRegistry) Encode(format string, v map[string]any) ([]byte, error) {
|
||||||
e.mu.RLock()
|
e.mu.RLock()
|
||||||
encoder, ok := e.encoders[format]
|
encoder, ok := e.encoders[format]
|
||||||
e.mu.RUnlock()
|
e.mu.RUnlock()
|
||||||
|
|||||||
@@ -2,13 +2,16 @@ package encoding
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
type encoder struct {
|
type encoder struct {
|
||||||
b []byte
|
b []byte
|
||||||
}
|
}
|
||||||
|
|
||||||
func (e encoder) Encode(_ map[string]interface{}) ([]byte, error) {
|
func (e encoder) Encode(_ map[string]any) ([]byte, error) {
|
||||||
return e.b, nil
|
return e.b, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -17,23 +20,17 @@ func TestEncoderRegistry_RegisterEncoder(t *testing.T) {
|
|||||||
registry := NewEncoderRegistry()
|
registry := NewEncoderRegistry()
|
||||||
|
|
||||||
err := registry.RegisterEncoder("myformat", encoder{})
|
err := registry.RegisterEncoder("myformat", encoder{})
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("AlreadyRegistered", func(t *testing.T) {
|
t.Run("AlreadyRegistered", func(t *testing.T) {
|
||||||
registry := NewEncoderRegistry()
|
registry := NewEncoderRegistry()
|
||||||
|
|
||||||
err := registry.RegisterEncoder("myformat", encoder{})
|
err := registry.RegisterEncoder("myformat", encoder{})
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = registry.RegisterEncoder("myformat", encoder{})
|
err = registry.RegisterEncoder("myformat", encoder{})
|
||||||
if err != ErrEncoderFormatAlreadyRegistered {
|
assert.ErrorIs(t, err, ErrEncoderFormatAlreadyRegistered)
|
||||||
t.Fatalf("expected ErrEncoderFormatAlreadyRegistered, got: %v", err)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,26 +42,18 @@ func TestEncoderRegistry_Decode(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
err := registry.RegisterEncoder("myformat", encoder)
|
err := registry.RegisterEncoder("myformat", encoder)
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
b, err := registry.Encode("myformat", map[string]interface{}{"key": "value"})
|
b, err := registry.Encode("myformat", map[string]any{"key": "value"})
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if string(b) != "key: value" {
|
assert.Equal(t, "key: value", string(b))
|
||||||
t.Fatalf("expected 'key: value', got: %#v", string(b))
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("EncoderNotFound", func(t *testing.T) {
|
t.Run("EncoderNotFound", func(t *testing.T) {
|
||||||
registry := NewEncoderRegistry()
|
registry := NewEncoderRegistry()
|
||||||
|
|
||||||
_, err := registry.Encode("myformat", map[string]interface{}{"key": "value"})
|
_, err := registry.Encode("myformat", map[string]any{"key": "value"})
|
||||||
if err != ErrEncoderNotFound {
|
assert.ErrorIs(t, err, ErrEncoderNotFound)
|
||||||
t.Fatalf("expected ErrEncoderNotFound, got: %v", err)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import (
|
|||||||
// TODO: add printer config to the codec?
|
// TODO: add printer config to the codec?
|
||||||
type Codec struct{}
|
type Codec struct{}
|
||||||
|
|
||||||
func (Codec) Encode(v map[string]interface{}) ([]byte, error) {
|
func (Codec) Encode(v map[string]any) ([]byte, error) {
|
||||||
b, err := json.Marshal(v)
|
b, err := json.Marshal(v)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -35,6 +35,6 @@ func (Codec) Encode(v map[string]interface{}) ([]byte, error) {
|
|||||||
return buf.Bytes(), nil
|
return buf.Bytes(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (Codec) Decode(b []byte, v map[string]interface{}) error {
|
func (Codec) Decode(b []byte, v map[string]any) error {
|
||||||
return hcl.Unmarshal(b, &v)
|
return hcl.Unmarshal(b, &v)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
package hcl
|
package hcl
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"reflect"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
// original form of the data
|
// original form of the data.
|
||||||
const original = `# key-value pair
|
const original = `# key-value pair
|
||||||
"key" = "value"
|
"key" = "value"
|
||||||
|
|
||||||
@@ -26,7 +28,7 @@ nested map
|
|||||||
"list" = ["item1", "item2", "item3"]
|
"list" = ["item1", "item2", "item3"]
|
||||||
}`
|
}`
|
||||||
|
|
||||||
// encoded form of the data
|
// encoded form of the data.
|
||||||
const encoded = `"key" = "value"
|
const encoded = `"key" = "value"
|
||||||
|
|
||||||
"list" = ["item1", "item2", "item3"]
|
"list" = ["item1", "item2", "item3"]
|
||||||
@@ -41,28 +43,28 @@ const encoded = `"key" = "value"
|
|||||||
"list" = ["item1", "item2", "item3"]
|
"list" = ["item1", "item2", "item3"]
|
||||||
}`
|
}`
|
||||||
|
|
||||||
// decoded form of the data
|
// decoded form of the data.
|
||||||
//
|
//
|
||||||
// in case of HCL it's slightly different from Viper's internal representation
|
// In case of HCL it's slightly different from Viper's internal representation
|
||||||
// (eg. map is decoded into a list of maps)
|
// (e.g. map is decoded into a list of maps).
|
||||||
var decoded = map[string]interface{}{
|
var decoded = map[string]any{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
"list": []interface{}{
|
"list": []any{
|
||||||
"item1",
|
"item1",
|
||||||
"item2",
|
"item2",
|
||||||
"item3",
|
"item3",
|
||||||
},
|
},
|
||||||
"map": []map[string]interface{}{
|
"map": []map[string]any{
|
||||||
{
|
{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"nested_map": []map[string]interface{}{
|
"nested_map": []map[string]any{
|
||||||
{
|
{
|
||||||
"map": []map[string]interface{}{
|
"map": []map[string]any{
|
||||||
{
|
{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
"list": []interface{}{
|
"list": []any{
|
||||||
"item1",
|
"item1",
|
||||||
"item2",
|
"item2",
|
||||||
"item3",
|
"item3",
|
||||||
@@ -73,21 +75,21 @@ var decoded = map[string]interface{}{
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
// Viper's internal representation
|
// data is Viper's internal representation.
|
||||||
var data = map[string]interface{}{
|
var data = map[string]any{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
"list": []interface{}{
|
"list": []any{
|
||||||
"item1",
|
"item1",
|
||||||
"item2",
|
"item2",
|
||||||
"item3",
|
"item3",
|
||||||
},
|
},
|
||||||
"map": map[string]interface{}{
|
"map": map[string]any{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
},
|
},
|
||||||
"nested_map": map[string]interface{}{
|
"nested_map": map[string]any{
|
||||||
"map": map[string]interface{}{
|
"map": map[string]any{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
"list": []interface{}{
|
"list": []any{
|
||||||
"item1",
|
"item1",
|
||||||
"item2",
|
"item2",
|
||||||
"item3",
|
"item3",
|
||||||
@@ -100,40 +102,30 @@ func TestCodec_Encode(t *testing.T) {
|
|||||||
codec := Codec{}
|
codec := Codec{}
|
||||||
|
|
||||||
b, err := codec.Encode(data)
|
b, err := codec.Encode(data)
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if encoded != string(b) {
|
assert.Equal(t, encoded, string(b))
|
||||||
t.Fatalf("decoded value does not match the expected one\nactual: %#v\nexpected: %#v", string(b), encoded)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCodec_Decode(t *testing.T) {
|
func TestCodec_Decode(t *testing.T) {
|
||||||
t.Run("OK", func(t *testing.T) {
|
t.Run("OK", func(t *testing.T) {
|
||||||
codec := Codec{}
|
codec := Codec{}
|
||||||
|
|
||||||
v := map[string]interface{}{}
|
v := map[string]any{}
|
||||||
|
|
||||||
err := codec.Decode([]byte(original), v)
|
err := codec.Decode([]byte(original), v)
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !reflect.DeepEqual(decoded, v) {
|
assert.Equal(t, decoded, v)
|
||||||
t.Fatalf("decoded value does not match the expected one\nactual: %#v\nexpected: %#v", v, decoded)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("InvalidData", func(t *testing.T) {
|
t.Run("InvalidData", func(t *testing.T) {
|
||||||
codec := Codec{}
|
codec := Codec{}
|
||||||
|
|
||||||
v := map[string]interface{}{}
|
v := map[string]any{}
|
||||||
|
|
||||||
err := codec.Decode([]byte(`invalid data`), v)
|
err := codec.Decode([]byte(`invalid data`), v)
|
||||||
if err == nil {
|
require.Error(t, err)
|
||||||
t.Fatal("expected decoding to fail")
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Logf("decoding failed as expected: %s", err)
|
t.Logf("decoding failed as expected: %s", err)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -19,11 +19,11 @@ type Codec struct {
|
|||||||
LoadOptions LoadOptions
|
LoadOptions LoadOptions
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c Codec) Encode(v map[string]interface{}) ([]byte, error) {
|
func (c Codec) Encode(v map[string]any) ([]byte, error) {
|
||||||
cfg := ini.Empty()
|
cfg := ini.Empty()
|
||||||
ini.PrettyFormat = false
|
ini.PrettyFormat = false
|
||||||
|
|
||||||
flattened := map[string]interface{}{}
|
flattened := map[string]any{}
|
||||||
|
|
||||||
flattened = flattenAndMergeMap(flattened, v, "", c.keyDelimiter())
|
flattened = flattenAndMergeMap(flattened, v, "", c.keyDelimiter())
|
||||||
|
|
||||||
@@ -62,7 +62,7 @@ func (c Codec) Encode(v map[string]interface{}) ([]byte, error) {
|
|||||||
return buf.Bytes(), nil
|
return buf.Bytes(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c Codec) Decode(b []byte, v map[string]interface{}) error {
|
func (c Codec) Decode(b []byte, v map[string]any) error {
|
||||||
cfg := ini.Empty(c.LoadOptions)
|
cfg := ini.Empty(c.LoadOptions)
|
||||||
|
|
||||||
err := cfg.Append(b)
|
err := cfg.Append(b)
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
package ini
|
package ini
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"reflect"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
// original form of the data
|
// original form of the data.
|
||||||
const original = `; key-value pair
|
const original = `; key-value pair
|
||||||
key=value ; key-value pair
|
key=value ; key-value pair
|
||||||
|
|
||||||
@@ -15,31 +17,30 @@ key=%(key)s
|
|||||||
|
|
||||||
`
|
`
|
||||||
|
|
||||||
// encoded form of the data
|
// encoded form of the data.
|
||||||
const encoded = `key=value
|
const encoded = `key=value
|
||||||
|
|
||||||
[map]
|
[map]
|
||||||
key=value
|
key=value
|
||||||
|
|
||||||
`
|
`
|
||||||
|
|
||||||
// decoded form of the data
|
// decoded form of the data.
|
||||||
//
|
//
|
||||||
// in case of INI it's slightly different from Viper's internal representation
|
// In case of INI it's slightly different from Viper's internal representation
|
||||||
// (eg. top level keys land in a section called default)
|
// (e.g. top level keys land in a section called default).
|
||||||
var decoded = map[string]interface{}{
|
var decoded = map[string]any{
|
||||||
"DEFAULT": map[string]interface{}{
|
"DEFAULT": map[string]any{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
},
|
},
|
||||||
"map": map[string]interface{}{
|
"map": map[string]any{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
// Viper's internal representation
|
// data is Viper's internal representation.
|
||||||
var data = map[string]interface{}{
|
var data = map[string]any{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
"map": map[string]interface{}{
|
"map": map[string]any{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -49,35 +50,27 @@ func TestCodec_Encode(t *testing.T) {
|
|||||||
codec := Codec{}
|
codec := Codec{}
|
||||||
|
|
||||||
b, err := codec.Encode(data)
|
b, err := codec.Encode(data)
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if encoded != string(b) {
|
assert.Equal(t, encoded, string(b))
|
||||||
t.Fatalf("decoded value does not match the expected one\nactual: %#v\nexpected: %#v", string(b), encoded)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Default", func(t *testing.T) {
|
t.Run("Default", func(t *testing.T) {
|
||||||
codec := Codec{}
|
codec := Codec{}
|
||||||
|
|
||||||
data := map[string]interface{}{
|
data := map[string]any{
|
||||||
"default": map[string]interface{}{
|
"default": map[string]any{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
},
|
},
|
||||||
"map": map[string]interface{}{
|
"map": map[string]any{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
b, err := codec.Encode(data)
|
b, err := codec.Encode(data)
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if encoded != string(b) {
|
assert.Equal(t, encoded, string(b))
|
||||||
t.Fatalf("decoded value does not match the expected one\nactual: %#v\nexpected: %#v", string(b), encoded)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -85,27 +78,21 @@ func TestCodec_Decode(t *testing.T) {
|
|||||||
t.Run("OK", func(t *testing.T) {
|
t.Run("OK", func(t *testing.T) {
|
||||||
codec := Codec{}
|
codec := Codec{}
|
||||||
|
|
||||||
v := map[string]interface{}{}
|
v := map[string]any{}
|
||||||
|
|
||||||
err := codec.Decode([]byte(original), v)
|
err := codec.Decode([]byte(original), v)
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !reflect.DeepEqual(decoded, v) {
|
assert.Equal(t, decoded, v)
|
||||||
t.Fatalf("decoded value does not match the expected one\nactual: %#v\nexpected: %#v", v, decoded)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("InvalidData", func(t *testing.T) {
|
t.Run("InvalidData", func(t *testing.T) {
|
||||||
codec := Codec{}
|
codec := Codec{}
|
||||||
|
|
||||||
v := map[string]interface{}{}
|
v := map[string]any{}
|
||||||
|
|
||||||
err := codec.Decode([]byte(`invalid data`), v)
|
err := codec.Decode([]byte(`invalid data`), v)
|
||||||
if err == nil {
|
require.Error(t, err)
|
||||||
t.Fatal("expected decoding to fail")
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Logf("decoding failed as expected: %s", err)
|
t.Logf("decoding failed as expected: %s", err)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -15,22 +15,22 @@ import (
|
|||||||
// In case intermediate keys do not exist, or map to a non-map value,
|
// In case intermediate keys do not exist, or map to a non-map value,
|
||||||
// a new map is created and inserted, and the search continues from there:
|
// a new map is created and inserted, and the search continues from there:
|
||||||
// the initial map "m" may be modified!
|
// the initial map "m" may be modified!
|
||||||
func deepSearch(m map[string]interface{}, path []string) map[string]interface{} {
|
func deepSearch(m map[string]any, path []string) map[string]any {
|
||||||
for _, k := range path {
|
for _, k := range path {
|
||||||
m2, ok := m[k]
|
m2, ok := m[k]
|
||||||
if !ok {
|
if !ok {
|
||||||
// intermediate key does not exist
|
// intermediate key does not exist
|
||||||
// => create it and continue from there
|
// => create it and continue from there
|
||||||
m3 := make(map[string]interface{})
|
m3 := make(map[string]any)
|
||||||
m[k] = m3
|
m[k] = m3
|
||||||
m = m3
|
m = m3
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
m3, ok := m2.(map[string]interface{})
|
m3, ok := m2.(map[string]any)
|
||||||
if !ok {
|
if !ok {
|
||||||
// intermediate key is a value
|
// intermediate key is a value
|
||||||
// => replace with a new map
|
// => replace with a new map
|
||||||
m3 = make(map[string]interface{})
|
m3 = make(map[string]any)
|
||||||
m[k] = m3
|
m[k] = m3
|
||||||
}
|
}
|
||||||
// continue search from here
|
// continue search from here
|
||||||
@@ -40,27 +40,27 @@ func deepSearch(m map[string]interface{}, path []string) map[string]interface{}
|
|||||||
}
|
}
|
||||||
|
|
||||||
// flattenAndMergeMap recursively flattens the given map into a new map
|
// flattenAndMergeMap recursively flattens the given map into a new map
|
||||||
// Code is based on the function with the same name in tha main package.
|
// Code is based on the function with the same name in the main package.
|
||||||
// TODO: move it to a common place
|
// TODO: move it to a common place.
|
||||||
func flattenAndMergeMap(shadow map[string]interface{}, m map[string]interface{}, prefix string, delimiter string) map[string]interface{} {
|
func flattenAndMergeMap(shadow, m map[string]any, prefix, delimiter string) map[string]any {
|
||||||
if shadow != nil && prefix != "" && shadow[prefix] != nil {
|
if shadow != nil && prefix != "" && shadow[prefix] != nil {
|
||||||
// prefix is shadowed => nothing more to flatten
|
// prefix is shadowed => nothing more to flatten
|
||||||
return shadow
|
return shadow
|
||||||
}
|
}
|
||||||
if shadow == nil {
|
if shadow == nil {
|
||||||
shadow = make(map[string]interface{})
|
shadow = make(map[string]any)
|
||||||
}
|
}
|
||||||
|
|
||||||
var m2 map[string]interface{}
|
var m2 map[string]any
|
||||||
if prefix != "" {
|
if prefix != "" {
|
||||||
prefix += delimiter
|
prefix += delimiter
|
||||||
}
|
}
|
||||||
for k, val := range m {
|
for k, val := range m {
|
||||||
fullKey := prefix + k
|
fullKey := prefix + k
|
||||||
switch val.(type) {
|
switch val := val.(type) {
|
||||||
case map[string]interface{}:
|
case map[string]any:
|
||||||
m2 = val.(map[string]interface{})
|
m2 = val
|
||||||
case map[interface{}]interface{}:
|
case map[any]any:
|
||||||
m2 = cast.ToStringMap(val)
|
m2 = cast.ToStringMap(val)
|
||||||
default:
|
default:
|
||||||
// immediate value
|
// immediate value
|
||||||
|
|||||||
@@ -20,12 +20,12 @@ type Codec struct {
|
|||||||
Properties *properties.Properties
|
Properties *properties.Properties
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Codec) Encode(v map[string]interface{}) ([]byte, error) {
|
func (c *Codec) Encode(v map[string]any) ([]byte, error) {
|
||||||
if c.Properties == nil {
|
if c.Properties == nil {
|
||||||
c.Properties = properties.NewProperties()
|
c.Properties = properties.NewProperties()
|
||||||
}
|
}
|
||||||
|
|
||||||
flattened := map[string]interface{}{}
|
flattened := map[string]any{}
|
||||||
|
|
||||||
flattened = flattenAndMergeMap(flattened, v, "", c.keyDelimiter())
|
flattened = flattenAndMergeMap(flattened, v, "", c.keyDelimiter())
|
||||||
|
|
||||||
@@ -54,7 +54,7 @@ func (c *Codec) Encode(v map[string]interface{}) ([]byte, error) {
|
|||||||
return buf.Bytes(), nil
|
return buf.Bytes(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Codec) Decode(b []byte, v map[string]interface{}) error {
|
func (c *Codec) Decode(b []byte, v map[string]any) error {
|
||||||
var err error
|
var err error
|
||||||
c.Properties, err = properties.Load(b, properties.UTF8)
|
c.Properties, err = properties.Load(b, properties.UTF8)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -1,25 +1,27 @@
|
|||||||
package javaproperties
|
package javaproperties
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"reflect"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
// original form of the data
|
// original form of the data.
|
||||||
const original = `#key-value pair
|
const original = `#key-value pair
|
||||||
key = value
|
key = value
|
||||||
map.key = value
|
map.key = value
|
||||||
`
|
`
|
||||||
|
|
||||||
// encoded form of the data
|
// encoded form of the data.
|
||||||
const encoded = `key = value
|
const encoded = `key = value
|
||||||
map.key = value
|
map.key = value
|
||||||
`
|
`
|
||||||
|
|
||||||
// Viper's internal representation
|
// data is Viper's internal representation.
|
||||||
var data = map[string]interface{}{
|
var data = map[string]any{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
"map": map[string]interface{}{
|
"map": map[string]any{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -28,29 +30,21 @@ func TestCodec_Encode(t *testing.T) {
|
|||||||
codec := Codec{}
|
codec := Codec{}
|
||||||
|
|
||||||
b, err := codec.Encode(data)
|
b, err := codec.Encode(data)
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if encoded != string(b) {
|
assert.Equal(t, encoded, string(b))
|
||||||
t.Fatalf("decoded value does not match the expected one\nactual: %#v\nexpected: %#v", string(b), encoded)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCodec_Decode(t *testing.T) {
|
func TestCodec_Decode(t *testing.T) {
|
||||||
t.Run("OK", func(t *testing.T) {
|
t.Run("OK", func(t *testing.T) {
|
||||||
codec := Codec{}
|
codec := Codec{}
|
||||||
|
|
||||||
v := map[string]interface{}{}
|
v := map[string]any{}
|
||||||
|
|
||||||
err := codec.Decode([]byte(original), v)
|
err := codec.Decode([]byte(original), v)
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !reflect.DeepEqual(data, v) {
|
assert.Equal(t, data, v)
|
||||||
t.Fatalf("decoded value does not match the expected one\nactual: %#v\nexpected: %#v", v, data)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("InvalidData", func(t *testing.T) {
|
t.Run("InvalidData", func(t *testing.T) {
|
||||||
@@ -58,32 +52,24 @@ func TestCodec_Decode(t *testing.T) {
|
|||||||
|
|
||||||
codec := Codec{}
|
codec := Codec{}
|
||||||
|
|
||||||
v := map[string]interface{}{}
|
v := map[string]any{}
|
||||||
|
|
||||||
codec.Decode([]byte(``), v)
|
codec.Decode([]byte(``), v)
|
||||||
|
|
||||||
if len(v) > 0 {
|
assert.Empty(t, v)
|
||||||
t.Fatalf("expected map to be empty when data is invalid\nactual: %#v", v)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCodec_DecodeEncode(t *testing.T) {
|
func TestCodec_DecodeEncode(t *testing.T) {
|
||||||
codec := Codec{}
|
codec := Codec{}
|
||||||
|
|
||||||
v := map[string]interface{}{}
|
v := map[string]any{}
|
||||||
|
|
||||||
err := codec.Decode([]byte(original), v)
|
err := codec.Decode([]byte(original), v)
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
b, err := codec.Encode(data)
|
b, err := codec.Encode(data)
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if original != string(b) {
|
assert.Equal(t, original, string(b))
|
||||||
t.Fatalf("encoded value does not match the original\nactual: %#v\nexpected: %#v", string(b), original)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,22 +15,22 @@ import (
|
|||||||
// In case intermediate keys do not exist, or map to a non-map value,
|
// In case intermediate keys do not exist, or map to a non-map value,
|
||||||
// a new map is created and inserted, and the search continues from there:
|
// a new map is created and inserted, and the search continues from there:
|
||||||
// the initial map "m" may be modified!
|
// the initial map "m" may be modified!
|
||||||
func deepSearch(m map[string]interface{}, path []string) map[string]interface{} {
|
func deepSearch(m map[string]any, path []string) map[string]any {
|
||||||
for _, k := range path {
|
for _, k := range path {
|
||||||
m2, ok := m[k]
|
m2, ok := m[k]
|
||||||
if !ok {
|
if !ok {
|
||||||
// intermediate key does not exist
|
// intermediate key does not exist
|
||||||
// => create it and continue from there
|
// => create it and continue from there
|
||||||
m3 := make(map[string]interface{})
|
m3 := make(map[string]any)
|
||||||
m[k] = m3
|
m[k] = m3
|
||||||
m = m3
|
m = m3
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
m3, ok := m2.(map[string]interface{})
|
m3, ok := m2.(map[string]any)
|
||||||
if !ok {
|
if !ok {
|
||||||
// intermediate key is a value
|
// intermediate key is a value
|
||||||
// => replace with a new map
|
// => replace with a new map
|
||||||
m3 = make(map[string]interface{})
|
m3 = make(map[string]any)
|
||||||
m[k] = m3
|
m[k] = m3
|
||||||
}
|
}
|
||||||
// continue search from here
|
// continue search from here
|
||||||
@@ -40,27 +40,27 @@ func deepSearch(m map[string]interface{}, path []string) map[string]interface{}
|
|||||||
}
|
}
|
||||||
|
|
||||||
// flattenAndMergeMap recursively flattens the given map into a new map
|
// flattenAndMergeMap recursively flattens the given map into a new map
|
||||||
// Code is based on the function with the same name in tha main package.
|
// Code is based on the function with the same name in the main package.
|
||||||
// TODO: move it to a common place
|
// TODO: move it to a common place.
|
||||||
func flattenAndMergeMap(shadow map[string]interface{}, m map[string]interface{}, prefix string, delimiter string) map[string]interface{} {
|
func flattenAndMergeMap(shadow, m map[string]any, prefix, delimiter string) map[string]any {
|
||||||
if shadow != nil && prefix != "" && shadow[prefix] != nil {
|
if shadow != nil && prefix != "" && shadow[prefix] != nil {
|
||||||
// prefix is shadowed => nothing more to flatten
|
// prefix is shadowed => nothing more to flatten
|
||||||
return shadow
|
return shadow
|
||||||
}
|
}
|
||||||
if shadow == nil {
|
if shadow == nil {
|
||||||
shadow = make(map[string]interface{})
|
shadow = make(map[string]any)
|
||||||
}
|
}
|
||||||
|
|
||||||
var m2 map[string]interface{}
|
var m2 map[string]any
|
||||||
if prefix != "" {
|
if prefix != "" {
|
||||||
prefix += delimiter
|
prefix += delimiter
|
||||||
}
|
}
|
||||||
for k, val := range m {
|
for k, val := range m {
|
||||||
fullKey := prefix + k
|
fullKey := prefix + k
|
||||||
switch val.(type) {
|
switch val := val.(type) {
|
||||||
case map[string]interface{}:
|
case map[string]any:
|
||||||
m2 = val.(map[string]interface{})
|
m2 = val
|
||||||
case map[interface{}]interface{}:
|
case map[any]any:
|
||||||
m2 = cast.ToStringMap(val)
|
m2 = cast.ToStringMap(val)
|
||||||
default:
|
default:
|
||||||
// immediate value
|
// immediate value
|
||||||
|
|||||||
@@ -7,11 +7,11 @@ import (
|
|||||||
// Codec implements the encoding.Encoder and encoding.Decoder interfaces for JSON encoding.
|
// Codec implements the encoding.Encoder and encoding.Decoder interfaces for JSON encoding.
|
||||||
type Codec struct{}
|
type Codec struct{}
|
||||||
|
|
||||||
func (Codec) Encode(v map[string]interface{}) ([]byte, error) {
|
func (Codec) Encode(v map[string]any) ([]byte, error) {
|
||||||
// TODO: expose prefix and indent in the Codec as setting?
|
// TODO: expose prefix and indent in the Codec as setting?
|
||||||
return json.MarshalIndent(v, "", " ")
|
return json.MarshalIndent(v, "", " ")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (Codec) Decode(b []byte, v map[string]interface{}) error {
|
func (Codec) Decode(b []byte, v map[string]any) error {
|
||||||
return json.Unmarshal(b, &v)
|
return json.Unmarshal(b, &v)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
package json
|
package json
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"reflect"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
// encoded form of the data
|
// encoded form of the data.
|
||||||
const encoded = `{
|
const encoded = `{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
"list": [
|
"list": [
|
||||||
@@ -28,21 +30,21 @@ const encoded = `{
|
|||||||
}
|
}
|
||||||
}`
|
}`
|
||||||
|
|
||||||
// Viper's internal representation
|
// data is Viper's internal representation.
|
||||||
var data = map[string]interface{}{
|
var data = map[string]any{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
"list": []interface{}{
|
"list": []any{
|
||||||
"item1",
|
"item1",
|
||||||
"item2",
|
"item2",
|
||||||
"item3",
|
"item3",
|
||||||
},
|
},
|
||||||
"map": map[string]interface{}{
|
"map": map[string]any{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
},
|
},
|
||||||
"nested_map": map[string]interface{}{
|
"nested_map": map[string]any{
|
||||||
"map": map[string]interface{}{
|
"map": map[string]any{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
"list": []interface{}{
|
"list": []any{
|
||||||
"item1",
|
"item1",
|
||||||
"item2",
|
"item2",
|
||||||
"item3",
|
"item3",
|
||||||
@@ -55,40 +57,30 @@ func TestCodec_Encode(t *testing.T) {
|
|||||||
codec := Codec{}
|
codec := Codec{}
|
||||||
|
|
||||||
b, err := codec.Encode(data)
|
b, err := codec.Encode(data)
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if encoded != string(b) {
|
assert.Equal(t, encoded, string(b))
|
||||||
t.Fatalf("decoded value does not match the expected one\nactual: %#v\nexpected: %#v", string(b), encoded)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCodec_Decode(t *testing.T) {
|
func TestCodec_Decode(t *testing.T) {
|
||||||
t.Run("OK", func(t *testing.T) {
|
t.Run("OK", func(t *testing.T) {
|
||||||
codec := Codec{}
|
codec := Codec{}
|
||||||
|
|
||||||
v := map[string]interface{}{}
|
v := map[string]any{}
|
||||||
|
|
||||||
err := codec.Decode([]byte(encoded), v)
|
err := codec.Decode([]byte(encoded), v)
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !reflect.DeepEqual(data, v) {
|
assert.Equal(t, data, v)
|
||||||
t.Fatalf("decoded value does not match the expected one\nactual: %#v\nexpected: %#v", v, data)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("InvalidData", func(t *testing.T) {
|
t.Run("InvalidData", func(t *testing.T) {
|
||||||
codec := Codec{}
|
codec := Codec{}
|
||||||
|
|
||||||
v := map[string]interface{}{}
|
v := map[string]any{}
|
||||||
|
|
||||||
err := codec.Decode([]byte(`invalid data`), v)
|
err := codec.Decode([]byte(`invalid data`), v)
|
||||||
if err == nil {
|
require.Error(t, err)
|
||||||
t.Fatal("expected decoding to fail")
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Logf("decoding failed as expected: %s", err)
|
t.Logf("decoding failed as expected: %s", err)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,39 +1,16 @@
|
|||||||
//go:build viper_toml1
|
|
||||||
// +build viper_toml1
|
|
||||||
|
|
||||||
package toml
|
package toml
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/pelletier/go-toml"
|
"github.com/pelletier/go-toml/v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Codec implements the encoding.Encoder and encoding.Decoder interfaces for TOML encoding.
|
// Codec implements the encoding.Encoder and encoding.Decoder interfaces for TOML encoding.
|
||||||
type Codec struct{}
|
type Codec struct{}
|
||||||
|
|
||||||
func (Codec) Encode(v map[string]interface{}) ([]byte, error) {
|
func (Codec) Encode(v map[string]any) ([]byte, error) {
|
||||||
t, err := toml.TreeFromMap(v)
|
return toml.Marshal(v)
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
s, err := t.ToTomlString()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return []byte(s), nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (Codec) Decode(b []byte, v map[string]interface{}) error {
|
func (Codec) Decode(b []byte, v map[string]any) error {
|
||||||
tree, err := toml.LoadBytes(b)
|
return toml.Unmarshal(b, &v)
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
tmap := tree.ToMap()
|
|
||||||
for key, value := range tmap {
|
|
||||||
v[key] = value
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +0,0 @@
|
|||||||
//go:build !viper_toml1
|
|
||||||
// +build !viper_toml1
|
|
||||||
|
|
||||||
package toml
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/pelletier/go-toml/v2"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Codec implements the encoding.Encoder and encoding.Decoder interfaces for TOML encoding.
|
|
||||||
type Codec struct{}
|
|
||||||
|
|
||||||
func (Codec) Encode(v map[string]interface{}) ([]byte, error) {
|
|
||||||
return toml.Marshal(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (Codec) Decode(b []byte, v map[string]interface{}) error {
|
|
||||||
return toml.Unmarshal(b, &v)
|
|
||||||
}
|
|
||||||
@@ -1,109 +0,0 @@
|
|||||||
//go:build !viper_toml1
|
|
||||||
// +build !viper_toml1
|
|
||||||
|
|
||||||
package toml
|
|
||||||
|
|
||||||
import (
|
|
||||||
"reflect"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
// original form of the data
|
|
||||||
const original = `# key-value pair
|
|
||||||
key = "value"
|
|
||||||
list = ["item1", "item2", "item3"]
|
|
||||||
|
|
||||||
[map]
|
|
||||||
key = "value"
|
|
||||||
|
|
||||||
# nested
|
|
||||||
# map
|
|
||||||
[nested_map]
|
|
||||||
[nested_map.map]
|
|
||||||
key = "value"
|
|
||||||
list = [
|
|
||||||
"item1",
|
|
||||||
"item2",
|
|
||||||
"item3",
|
|
||||||
]
|
|
||||||
`
|
|
||||||
|
|
||||||
// encoded form of the data
|
|
||||||
const encoded = `key = 'value'
|
|
||||||
list = ['item1', 'item2', 'item3']
|
|
||||||
[map]
|
|
||||||
key = 'value'
|
|
||||||
|
|
||||||
[nested_map]
|
|
||||||
[nested_map.map]
|
|
||||||
key = 'value'
|
|
||||||
list = ['item1', 'item2', 'item3']
|
|
||||||
|
|
||||||
|
|
||||||
`
|
|
||||||
|
|
||||||
// Viper's internal representation
|
|
||||||
var data = map[string]interface{}{
|
|
||||||
"key": "value",
|
|
||||||
"list": []interface{}{
|
|
||||||
"item1",
|
|
||||||
"item2",
|
|
||||||
"item3",
|
|
||||||
},
|
|
||||||
"map": map[string]interface{}{
|
|
||||||
"key": "value",
|
|
||||||
},
|
|
||||||
"nested_map": map[string]interface{}{
|
|
||||||
"map": map[string]interface{}{
|
|
||||||
"key": "value",
|
|
||||||
"list": []interface{}{
|
|
||||||
"item1",
|
|
||||||
"item2",
|
|
||||||
"item3",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCodec_Encode(t *testing.T) {
|
|
||||||
codec := Codec{}
|
|
||||||
|
|
||||||
b, err := codec.Encode(data)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if encoded != string(b) {
|
|
||||||
t.Fatalf("decoded value does not match the expected one\nactual: %#v\nexpected: %#v", string(b), encoded)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCodec_Decode(t *testing.T) {
|
|
||||||
t.Run("OK", func(t *testing.T) {
|
|
||||||
codec := Codec{}
|
|
||||||
|
|
||||||
v := map[string]interface{}{}
|
|
||||||
|
|
||||||
err := codec.Decode([]byte(original), v)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !reflect.DeepEqual(data, v) {
|
|
||||||
t.Fatalf("decoded value does not match the expected one\nactual: %#v\nexpected: %#v", v, data)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("InvalidData", func(t *testing.T) {
|
|
||||||
codec := Codec{}
|
|
||||||
|
|
||||||
v := map[string]interface{}{}
|
|
||||||
|
|
||||||
err := codec.Decode([]byte(`invalid data`), v)
|
|
||||||
if err == nil {
|
|
||||||
t.Fatal("expected decoding to fail")
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Logf("decoding failed as expected: %s", err)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,14 +1,13 @@
|
|||||||
//go:build viper_toml1
|
|
||||||
// +build viper_toml1
|
|
||||||
|
|
||||||
package toml
|
package toml
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"reflect"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
// original form of the data
|
// original form of the data.
|
||||||
const original = `# key-value pair
|
const original = `# key-value pair
|
||||||
key = "value"
|
key = "value"
|
||||||
list = ["item1", "item2", "item3"]
|
list = ["item1", "item2", "item3"]
|
||||||
@@ -28,35 +27,34 @@ list = [
|
|||||||
]
|
]
|
||||||
`
|
`
|
||||||
|
|
||||||
// encoded form of the data
|
// encoded form of the data.
|
||||||
const encoded = `key = "value"
|
const encoded = `key = 'value'
|
||||||
list = ["item1", "item2", "item3"]
|
list = ['item1', 'item2', 'item3']
|
||||||
|
|
||||||
[map]
|
[map]
|
||||||
key = "value"
|
key = 'value'
|
||||||
|
|
||||||
[nested_map]
|
[nested_map]
|
||||||
|
[nested_map.map]
|
||||||
[nested_map.map]
|
key = 'value'
|
||||||
key = "value"
|
list = ['item1', 'item2', 'item3']
|
||||||
list = ["item1", "item2", "item3"]
|
|
||||||
`
|
`
|
||||||
|
|
||||||
// Viper's internal representation
|
// data is Viper's internal representation.
|
||||||
var data = map[string]interface{}{
|
var data = map[string]any{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
"list": []interface{}{
|
"list": []any{
|
||||||
"item1",
|
"item1",
|
||||||
"item2",
|
"item2",
|
||||||
"item3",
|
"item3",
|
||||||
},
|
},
|
||||||
"map": map[string]interface{}{
|
"map": map[string]any{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
},
|
},
|
||||||
"nested_map": map[string]interface{}{
|
"nested_map": map[string]any{
|
||||||
"map": map[string]interface{}{
|
"map": map[string]any{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
"list": []interface{}{
|
"list": []any{
|
||||||
"item1",
|
"item1",
|
||||||
"item2",
|
"item2",
|
||||||
"item3",
|
"item3",
|
||||||
@@ -69,40 +67,30 @@ func TestCodec_Encode(t *testing.T) {
|
|||||||
codec := Codec{}
|
codec := Codec{}
|
||||||
|
|
||||||
b, err := codec.Encode(data)
|
b, err := codec.Encode(data)
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if encoded != string(b) {
|
assert.Equal(t, encoded, string(b))
|
||||||
t.Fatalf("decoded value does not match the expected one\nactual: %#v\nexpected: %#v", string(b), encoded)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCodec_Decode(t *testing.T) {
|
func TestCodec_Decode(t *testing.T) {
|
||||||
t.Run("OK", func(t *testing.T) {
|
t.Run("OK", func(t *testing.T) {
|
||||||
codec := Codec{}
|
codec := Codec{}
|
||||||
|
|
||||||
v := map[string]interface{}{}
|
v := map[string]any{}
|
||||||
|
|
||||||
err := codec.Decode([]byte(original), v)
|
err := codec.Decode([]byte(original), v)
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !reflect.DeepEqual(data, v) {
|
assert.Equal(t, data, v)
|
||||||
t.Fatalf("decoded value does not match the expected one\nactual: %#v\nexpected: %#v", v, data)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("InvalidData", func(t *testing.T) {
|
t.Run("InvalidData", func(t *testing.T) {
|
||||||
codec := Codec{}
|
codec := Codec{}
|
||||||
|
|
||||||
v := map[string]interface{}{}
|
v := map[string]any{}
|
||||||
|
|
||||||
err := codec.Decode([]byte(`invalid data`), v)
|
err := codec.Decode([]byte(`invalid data`), v)
|
||||||
if err == nil {
|
require.Error(t, err)
|
||||||
t.Fatal("expected decoding to fail")
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Logf("decoding failed as expected: %s", err)
|
t.Logf("decoding failed as expected: %s", err)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
package yaml
|
package yaml
|
||||||
|
|
||||||
// import "gopkg.in/yaml.v2"
|
import "gopkg.in/yaml.v3"
|
||||||
|
|
||||||
// Codec implements the encoding.Encoder and encoding.Decoder interfaces for YAML encoding.
|
// Codec implements the encoding.Encoder and encoding.Decoder interfaces for YAML encoding.
|
||||||
type Codec struct{}
|
type Codec struct{}
|
||||||
|
|
||||||
func (Codec) Encode(v map[string]interface{}) ([]byte, error) {
|
func (Codec) Encode(v map[string]any) ([]byte, error) {
|
||||||
return yaml.Marshal(v)
|
return yaml.Marshal(v)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (Codec) Decode(b []byte, v map[string]interface{}) error {
|
func (Codec) Decode(b []byte, v map[string]any) error {
|
||||||
return yaml.Unmarshal(b, &v)
|
return yaml.Unmarshal(b, &v)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,48 +1,127 @@
|
|||||||
package yaml
|
package yaml
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"reflect"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// original form of the data.
|
||||||
|
const original = `# key-value pair
|
||||||
|
key: value
|
||||||
|
list:
|
||||||
|
- item1
|
||||||
|
- item2
|
||||||
|
- item3
|
||||||
|
map:
|
||||||
|
key: value
|
||||||
|
|
||||||
|
# nested
|
||||||
|
# map
|
||||||
|
nested_map:
|
||||||
|
map:
|
||||||
|
key: value
|
||||||
|
list:
|
||||||
|
- item1
|
||||||
|
- item2
|
||||||
|
- item3
|
||||||
|
`
|
||||||
|
|
||||||
|
// encoded form of the data.
|
||||||
|
const encoded = `key: value
|
||||||
|
list:
|
||||||
|
- item1
|
||||||
|
- item2
|
||||||
|
- item3
|
||||||
|
map:
|
||||||
|
key: value
|
||||||
|
nested_map:
|
||||||
|
map:
|
||||||
|
key: value
|
||||||
|
list:
|
||||||
|
- item1
|
||||||
|
- item2
|
||||||
|
- item3
|
||||||
|
`
|
||||||
|
|
||||||
|
// decoded form of the data.
|
||||||
|
//
|
||||||
|
// In case of YAML it's slightly different from Viper's internal representation
|
||||||
|
// (e.g. map is decoded into a map with interface key).
|
||||||
|
var decoded = map[string]any{
|
||||||
|
"key": "value",
|
||||||
|
"list": []any{
|
||||||
|
"item1",
|
||||||
|
"item2",
|
||||||
|
"item3",
|
||||||
|
},
|
||||||
|
"map": map[string]any{
|
||||||
|
"key": "value",
|
||||||
|
},
|
||||||
|
"nested_map": map[string]any{
|
||||||
|
"map": map[string]any{
|
||||||
|
"key": "value",
|
||||||
|
"list": []any{
|
||||||
|
"item1",
|
||||||
|
"item2",
|
||||||
|
"item3",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// data is Viper's internal representation.
|
||||||
|
var data = map[string]any{
|
||||||
|
"key": "value",
|
||||||
|
"list": []any{
|
||||||
|
"item1",
|
||||||
|
"item2",
|
||||||
|
"item3",
|
||||||
|
},
|
||||||
|
"map": map[string]any{
|
||||||
|
"key": "value",
|
||||||
|
},
|
||||||
|
"nested_map": map[string]any{
|
||||||
|
"map": map[string]any{
|
||||||
|
"key": "value",
|
||||||
|
"list": []any{
|
||||||
|
"item1",
|
||||||
|
"item2",
|
||||||
|
"item3",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
func TestCodec_Encode(t *testing.T) {
|
func TestCodec_Encode(t *testing.T) {
|
||||||
codec := Codec{}
|
codec := Codec{}
|
||||||
|
|
||||||
b, err := codec.Encode(data)
|
b, err := codec.Encode(data)
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if encoded != string(b) {
|
assert.Equal(t, encoded, string(b))
|
||||||
t.Fatalf("decoded value does not match the expected one\nactual: %#v\nexpected: %#v", string(b), encoded)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCodec_Decode(t *testing.T) {
|
func TestCodec_Decode(t *testing.T) {
|
||||||
t.Run("OK", func(t *testing.T) {
|
t.Run("OK", func(t *testing.T) {
|
||||||
codec := Codec{}
|
codec := Codec{}
|
||||||
|
|
||||||
v := map[string]interface{}{}
|
v := map[string]any{}
|
||||||
|
|
||||||
err := codec.Decode([]byte(original), v)
|
err := codec.Decode([]byte(original), v)
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !reflect.DeepEqual(decoded, v) {
|
assert.Equal(t, decoded, v)
|
||||||
t.Fatalf("decoded value does not match the expected one\nactual: %#v\nexpected: %#v", v, decoded)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("InvalidData", func(t *testing.T) {
|
t.Run("InvalidData", func(t *testing.T) {
|
||||||
codec := Codec{}
|
codec := Codec{}
|
||||||
|
|
||||||
v := map[string]interface{}{}
|
v := map[string]any{}
|
||||||
|
|
||||||
err := codec.Decode([]byte(`invalid data`), v)
|
err := codec.Decode([]byte(`invalid data`), v)
|
||||||
if err == nil {
|
require.Error(t, err)
|
||||||
t.Fatal("expected decoding to fail")
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Logf("decoding failed as expected: %s", err)
|
t.Logf("decoding failed as expected: %s", err)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,14 +0,0 @@
|
|||||||
//go:build viper_yaml2
|
|
||||||
// +build viper_yaml2
|
|
||||||
|
|
||||||
package yaml
|
|
||||||
|
|
||||||
import yamlv2 "gopkg.in/yaml.v2"
|
|
||||||
|
|
||||||
var yaml = struct {
|
|
||||||
Marshal func(in interface{}) (out []byte, err error)
|
|
||||||
Unmarshal func(in []byte, out interface{}) (err error)
|
|
||||||
}{
|
|
||||||
Marshal: yamlv2.Marshal,
|
|
||||||
Unmarshal: yamlv2.Unmarshal,
|
|
||||||
}
|
|
||||||
@@ -1,91 +0,0 @@
|
|||||||
//go:build viper_yaml2
|
|
||||||
// +build viper_yaml2
|
|
||||||
|
|
||||||
package yaml
|
|
||||||
|
|
||||||
// original form of the data
|
|
||||||
const original = `# key-value pair
|
|
||||||
key: value
|
|
||||||
list:
|
|
||||||
- item1
|
|
||||||
- item2
|
|
||||||
- item3
|
|
||||||
map:
|
|
||||||
key: value
|
|
||||||
|
|
||||||
# nested
|
|
||||||
# map
|
|
||||||
nested_map:
|
|
||||||
map:
|
|
||||||
key: value
|
|
||||||
list:
|
|
||||||
- item1
|
|
||||||
- item2
|
|
||||||
- item3
|
|
||||||
`
|
|
||||||
|
|
||||||
// encoded form of the data
|
|
||||||
const encoded = `key: value
|
|
||||||
list:
|
|
||||||
- item1
|
|
||||||
- item2
|
|
||||||
- item3
|
|
||||||
map:
|
|
||||||
key: value
|
|
||||||
nested_map:
|
|
||||||
map:
|
|
||||||
key: value
|
|
||||||
list:
|
|
||||||
- item1
|
|
||||||
- item2
|
|
||||||
- item3
|
|
||||||
`
|
|
||||||
|
|
||||||
// decoded form of the data
|
|
||||||
//
|
|
||||||
// in case of YAML it's slightly different from Viper's internal representation
|
|
||||||
// (eg. map is decoded into a map with interface key)
|
|
||||||
var decoded = map[string]interface{}{
|
|
||||||
"key": "value",
|
|
||||||
"list": []interface{}{
|
|
||||||
"item1",
|
|
||||||
"item2",
|
|
||||||
"item3",
|
|
||||||
},
|
|
||||||
"map": map[interface{}]interface{}{
|
|
||||||
"key": "value",
|
|
||||||
},
|
|
||||||
"nested_map": map[interface{}]interface{}{
|
|
||||||
"map": map[interface{}]interface{}{
|
|
||||||
"key": "value",
|
|
||||||
"list": []interface{}{
|
|
||||||
"item1",
|
|
||||||
"item2",
|
|
||||||
"item3",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
// Viper's internal representation
|
|
||||||
var data = map[string]interface{}{
|
|
||||||
"key": "value",
|
|
||||||
"list": []interface{}{
|
|
||||||
"item1",
|
|
||||||
"item2",
|
|
||||||
"item3",
|
|
||||||
},
|
|
||||||
"map": map[string]interface{}{
|
|
||||||
"key": "value",
|
|
||||||
},
|
|
||||||
"nested_map": map[string]interface{}{
|
|
||||||
"map": map[string]interface{}{
|
|
||||||
"key": "value",
|
|
||||||
"list": []interface{}{
|
|
||||||
"item1",
|
|
||||||
"item2",
|
|
||||||
"item3",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
//go:build !viper_yaml2
|
|
||||||
// +build !viper_yaml2
|
|
||||||
|
|
||||||
package yaml
|
|
||||||
|
|
||||||
import yamlv3 "gopkg.in/yaml.v3"
|
|
||||||
|
|
||||||
var yaml = struct {
|
|
||||||
Marshal func(in interface{}) (out []byte, err error)
|
|
||||||
Unmarshal func(in []byte, out interface{}) (err error)
|
|
||||||
}{
|
|
||||||
Marshal: yamlv3.Marshal,
|
|
||||||
Unmarshal: yamlv3.Unmarshal,
|
|
||||||
}
|
|
||||||
@@ -1,91 +0,0 @@
|
|||||||
//go:build !viper_yaml2
|
|
||||||
// +build !viper_yaml2
|
|
||||||
|
|
||||||
package yaml
|
|
||||||
|
|
||||||
// original form of the data
|
|
||||||
const original = `# key-value pair
|
|
||||||
key: value
|
|
||||||
list:
|
|
||||||
- item1
|
|
||||||
- item2
|
|
||||||
- item3
|
|
||||||
map:
|
|
||||||
key: value
|
|
||||||
|
|
||||||
# nested
|
|
||||||
# map
|
|
||||||
nested_map:
|
|
||||||
map:
|
|
||||||
key: value
|
|
||||||
list:
|
|
||||||
- item1
|
|
||||||
- item2
|
|
||||||
- item3
|
|
||||||
`
|
|
||||||
|
|
||||||
// encoded form of the data
|
|
||||||
const encoded = `key: value
|
|
||||||
list:
|
|
||||||
- item1
|
|
||||||
- item2
|
|
||||||
- item3
|
|
||||||
map:
|
|
||||||
key: value
|
|
||||||
nested_map:
|
|
||||||
map:
|
|
||||||
key: value
|
|
||||||
list:
|
|
||||||
- item1
|
|
||||||
- item2
|
|
||||||
- item3
|
|
||||||
`
|
|
||||||
|
|
||||||
// decoded form of the data
|
|
||||||
//
|
|
||||||
// in case of YAML it's slightly different from Viper's internal representation
|
|
||||||
// (eg. map is decoded into a map with interface key)
|
|
||||||
var decoded = map[string]interface{}{
|
|
||||||
"key": "value",
|
|
||||||
"list": []interface{}{
|
|
||||||
"item1",
|
|
||||||
"item2",
|
|
||||||
"item3",
|
|
||||||
},
|
|
||||||
"map": map[string]interface{}{
|
|
||||||
"key": "value",
|
|
||||||
},
|
|
||||||
"nested_map": map[string]interface{}{
|
|
||||||
"map": map[string]interface{}{
|
|
||||||
"key": "value",
|
|
||||||
"list": []interface{}{
|
|
||||||
"item1",
|
|
||||||
"item2",
|
|
||||||
"item3",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
// Viper's internal representation
|
|
||||||
var data = map[string]interface{}{
|
|
||||||
"key": "value",
|
|
||||||
"list": []interface{}{
|
|
||||||
"item1",
|
|
||||||
"item2",
|
|
||||||
"item3",
|
|
||||||
},
|
|
||||||
"map": map[string]interface{}{
|
|
||||||
"key": "value",
|
|
||||||
},
|
|
||||||
"nested_map": map[string]interface{}{
|
|
||||||
"map": map[string]interface{}{
|
|
||||||
"key": "value",
|
|
||||||
"list": []interface{}{
|
|
||||||
"item1",
|
|
||||||
"item2",
|
|
||||||
"item3",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
//go:build viper_bind_struct
|
||||||
|
|
||||||
|
package features
|
||||||
|
|
||||||
|
const BindStruct = true
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
//go:build !viper_bind_struct
|
||||||
|
|
||||||
|
package features
|
||||||
|
|
||||||
|
const BindStruct = false
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
//go:build !go1.17
|
|
||||||
// +build !go1.17
|
|
||||||
|
|
||||||
package testutil
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Based on https://github.com/frankban/quicktest/blob/577841610793d24f99e31cc2c0ef3a541fefd7c7/patch.go#L34-L64
|
|
||||||
// Licensed under the MIT license
|
|
||||||
// Copyright (c) 2017 Canonical Ltd.
|
|
||||||
|
|
||||||
// Setenv sets an environment variable to a temporary value for the
|
|
||||||
// duration of the test.
|
|
||||||
//
|
|
||||||
// At the end of the test (see "Deferred execution" in the package docs), the
|
|
||||||
// environment variable is returned to its original value.
|
|
||||||
func Setenv(t *testing.T, name, val string) {
|
|
||||||
setenv(t, name, val, true)
|
|
||||||
}
|
|
||||||
|
|
||||||
// setenv sets or unsets an environment variable to a temporary value for the
|
|
||||||
// duration of the test
|
|
||||||
func setenv(t *testing.T, name, val string, valOK bool) {
|
|
||||||
oldVal, oldOK := os.LookupEnv(name)
|
|
||||||
if valOK {
|
|
||||||
os.Setenv(name, val)
|
|
||||||
} else {
|
|
||||||
os.Unsetenv(name)
|
|
||||||
}
|
|
||||||
t.Cleanup(func() {
|
|
||||||
if oldOK {
|
|
||||||
os.Setenv(name, oldVal)
|
|
||||||
} else {
|
|
||||||
os.Unsetenv(name)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
//go:build go1.17
|
|
||||||
// +build go1.17
|
|
||||||
|
|
||||||
package testutil
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Setenv sets an environment variable to a temporary value for the
|
|
||||||
// duration of the test.
|
|
||||||
//
|
|
||||||
// This shim can be removed once support for Go <1.17 is dropped.
|
|
||||||
func Setenv(t *testing.T, name, val string) {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
t.Setenv(name, val)
|
|
||||||
}
|
|
||||||
@@ -1,77 +1,68 @@
|
|||||||
package viper
|
package viper
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"context"
|
||||||
|
|
||||||
jww "github.com/spf13/jwalterweatherman"
|
slog "github.com/sagikazarmark/slog-shim"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Logger is a unified interface for various logging use cases and practices, including:
|
// Logger is a unified interface for various logging use cases and practices, including:
|
||||||
// - leveled logging
|
// - leveled logging
|
||||||
// - structured logging
|
// - structured logging
|
||||||
|
//
|
||||||
|
// Deprecated: use `log/slog` instead.
|
||||||
type Logger interface {
|
type Logger interface {
|
||||||
// Trace logs a Trace event.
|
// Trace logs a Trace event.
|
||||||
//
|
//
|
||||||
// Even more fine-grained information than Debug events.
|
// Even more fine-grained information than Debug events.
|
||||||
// Loggers not supporting this level should fall back to Debug.
|
// Loggers not supporting this level should fall back to Debug.
|
||||||
Trace(msg string, keyvals ...interface{})
|
Trace(msg string, keyvals ...any)
|
||||||
|
|
||||||
// Debug logs a Debug event.
|
// Debug logs a Debug event.
|
||||||
//
|
//
|
||||||
// A verbose series of information events.
|
// A verbose series of information events.
|
||||||
// They are useful when debugging the system.
|
// They are useful when debugging the system.
|
||||||
Debug(msg string, keyvals ...interface{})
|
Debug(msg string, keyvals ...any)
|
||||||
|
|
||||||
// Info logs an Info event.
|
// Info logs an Info event.
|
||||||
//
|
//
|
||||||
// General information about what's happening inside the system.
|
// General information about what's happening inside the system.
|
||||||
Info(msg string, keyvals ...interface{})
|
Info(msg string, keyvals ...any)
|
||||||
|
|
||||||
// Warn logs a Warn(ing) event.
|
// Warn logs a Warn(ing) event.
|
||||||
//
|
//
|
||||||
// Non-critical events that should be looked at.
|
// Non-critical events that should be looked at.
|
||||||
Warn(msg string, keyvals ...interface{})
|
Warn(msg string, keyvals ...any)
|
||||||
|
|
||||||
// Error logs an Error event.
|
// Error logs an Error event.
|
||||||
//
|
//
|
||||||
// Critical events that require immediate attention.
|
// Critical events that require immediate attention.
|
||||||
// Loggers commonly provide Fatal and Panic levels above Error level,
|
// Loggers commonly provide Fatal and Panic levels above Error level,
|
||||||
// but exiting and panicing is out of scope for a logging library.
|
// but exiting and panicking is out of scope for a logging library.
|
||||||
Error(msg string, keyvals ...interface{})
|
Error(msg string, keyvals ...any)
|
||||||
}
|
}
|
||||||
|
|
||||||
type jwwLogger struct{}
|
// WithLogger sets a custom logger.
|
||||||
|
func WithLogger(l *slog.Logger) Option {
|
||||||
func (jwwLogger) Trace(msg string, keyvals ...interface{}) {
|
return optionFunc(func(v *Viper) {
|
||||||
jww.TRACE.Printf(jwwLogMessage(msg, keyvals...))
|
v.logger = l
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (jwwLogger) Debug(msg string, keyvals ...interface{}) {
|
type discardHandler struct{}
|
||||||
jww.DEBUG.Printf(jwwLogMessage(msg, keyvals...))
|
|
||||||
|
func (n *discardHandler) Enabled(_ context.Context, _ slog.Level) bool {
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func (jwwLogger) Info(msg string, keyvals ...interface{}) {
|
func (n *discardHandler) Handle(_ context.Context, _ slog.Record) error {
|
||||||
jww.INFO.Printf(jwwLogMessage(msg, keyvals...))
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (jwwLogger) Warn(msg string, keyvals ...interface{}) {
|
func (n *discardHandler) WithAttrs(_ []slog.Attr) slog.Handler {
|
||||||
jww.WARN.Printf(jwwLogMessage(msg, keyvals...))
|
return n
|
||||||
}
|
}
|
||||||
|
|
||||||
func (jwwLogger) Error(msg string, keyvals ...interface{}) {
|
func (n *discardHandler) WithGroup(_ string) slog.Handler {
|
||||||
jww.ERROR.Printf(jwwLogMessage(msg, keyvals...))
|
return n
|
||||||
}
|
|
||||||
|
|
||||||
func jwwLogMessage(msg string, keyvals ...interface{}) string {
|
|
||||||
out := msg
|
|
||||||
|
|
||||||
if len(keyvals) > 0 && len(keyvals)%2 == 1 {
|
|
||||||
keyvals = append(keyvals, nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 0; i <= len(keyvals)-2; i += 2 {
|
|
||||||
out = fmt.Sprintf("%s %v=%v", out, keyvals[i], keyvals[i+1])
|
|
||||||
}
|
|
||||||
|
|
||||||
return out
|
|
||||||
}
|
}
|
||||||
|
|||||||
+22
-26
@@ -1,7 +1,6 @@
|
|||||||
package viper
|
package viper
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
@@ -46,11 +45,11 @@ func TestNestedOverrides(t *testing.T) {
|
|||||||
deepCheckValue(assert, v, overrideLayer, []string{"tom", "size"}, 4)
|
deepCheckValue(assert, v, overrideLayer, []string{"tom", "size"}, 4)
|
||||||
|
|
||||||
// Case 4: key:value overridden by a map
|
// Case 4: key:value overridden by a map
|
||||||
v = overrideDefault(assert, "tom.size", 4, "tom", map[string]interface{}{"age": 10}) // "tom.size" is first given "4" as default value, then "tom" is overridden by map{"age":10}
|
v = overrideDefault(assert, "tom.size", 4, "tom", map[string]any{"age": 10}) // "tom.size" is first given "4" as default value, then "tom" is overridden by map{"age":10}
|
||||||
assert.Equal(4, v.Get("tom.size")) // "tom.size" should still be reachable
|
assert.Equal(4, v.Get("tom.size")) // "tom.size" should still be reachable
|
||||||
assert.Equal(10, v.Get("tom.age")) // new value should be there
|
assert.Equal(10, v.Get("tom.age")) // new value should be there
|
||||||
deepCheckValue(assert, v, overrideLayer, []string{"tom", "age"}, 10) // new value should be there
|
deepCheckValue(assert, v, overrideLayer, []string{"tom", "age"}, 10) // new value should be there
|
||||||
v = override(assert, "tom.size", 4, "tom", map[string]interface{}{"age": 10})
|
v = override(assert, "tom.size", 4, "tom", map[string]any{"age": 10})
|
||||||
assert.Nil(v.Get("tom.size"))
|
assert.Nil(v.Get("tom.size"))
|
||||||
assert.Equal(10, v.Get("tom.age"))
|
assert.Equal(10, v.Get("tom.age"))
|
||||||
deepCheckValue(assert, v, overrideLayer, []string{"tom", "age"}, 10)
|
deepCheckValue(assert, v, overrideLayer, []string{"tom", "age"}, 10)
|
||||||
@@ -75,11 +74,11 @@ func TestNestedOverrides(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func overrideDefault(assert *assert.Assertions, firstPath string, firstValue interface{}, secondPath string, secondValue interface{}) *Viper {
|
func overrideDefault(assert *assert.Assertions, firstPath string, firstValue any, secondPath string, secondValue any) *Viper {
|
||||||
return overrideFromLayer(defaultLayer, assert, firstPath, firstValue, secondPath, secondValue)
|
return overrideFromLayer(defaultLayer, assert, firstPath, firstValue, secondPath, secondValue)
|
||||||
}
|
}
|
||||||
|
|
||||||
func override(assert *assert.Assertions, firstPath string, firstValue interface{}, secondPath string, secondValue interface{}) *Viper {
|
func override(assert *assert.Assertions, firstPath string, firstValue any, secondPath string, secondValue any) *Viper {
|
||||||
return overrideFromLayer(overrideLayer, assert, firstPath, firstValue, secondPath, secondValue)
|
return overrideFromLayer(overrideLayer, assert, firstPath, firstValue, secondPath, secondValue)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,11 +93,11 @@ func override(assert *assert.Assertions, firstPath string, firstValue interface{
|
|||||||
//
|
//
|
||||||
// After each assignment, the value is checked, retrieved both by its full path
|
// After each assignment, the value is checked, retrieved both by its full path
|
||||||
// and by its key sequence (successive maps).
|
// and by its key sequence (successive maps).
|
||||||
func overrideFromLayer(l layer, assert *assert.Assertions, firstPath string, firstValue interface{}, secondPath string, secondValue interface{}) *Viper {
|
func overrideFromLayer(l layer, assert *assert.Assertions, firstPath string, firstValue any, secondPath string, secondValue any) *Viper {
|
||||||
v := New()
|
v := New()
|
||||||
firstKeys := strings.Split(firstPath, v.keyDelim)
|
firstKeys := strings.Split(firstPath, v.keyDelim)
|
||||||
if assert == nil ||
|
if assert == nil ||
|
||||||
len(firstKeys) == 0 || len(firstKeys[0]) == 0 {
|
len(firstKeys) == 0 || firstKeys[0] == "" {
|
||||||
return v
|
return v
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,7 +115,7 @@ func overrideFromLayer(l layer, assert *assert.Assertions, firstPath string, fir
|
|||||||
|
|
||||||
// Override and check new value
|
// Override and check new value
|
||||||
secondKeys := strings.Split(secondPath, v.keyDelim)
|
secondKeys := strings.Split(secondPath, v.keyDelim)
|
||||||
if len(secondKeys) == 0 || len(secondKeys[0]) == 0 {
|
if len(secondKeys) == 0 || secondKeys[0] == "" {
|
||||||
return v
|
return v
|
||||||
}
|
}
|
||||||
v.Set(secondPath, secondValue)
|
v.Set(secondPath, secondValue)
|
||||||
@@ -127,15 +126,15 @@ func overrideFromLayer(l layer, assert *assert.Assertions, firstPath string, fir
|
|||||||
}
|
}
|
||||||
|
|
||||||
// deepCheckValue checks that all given keys correspond to a valid path in the
|
// deepCheckValue checks that all given keys correspond to a valid path in the
|
||||||
// configuration map of the given layer, and that the final value equals the one given
|
// configuration map of the given layer, and that the final value equals the one given.
|
||||||
func deepCheckValue(assert *assert.Assertions, v *Viper, l layer, keys []string, value interface{}) {
|
func deepCheckValue(assert *assert.Assertions, v *Viper, l layer, keys []string, value any) {
|
||||||
if assert == nil || v == nil ||
|
if assert == nil || v == nil ||
|
||||||
len(keys) == 0 || len(keys[0]) == 0 {
|
len(keys) == 0 || keys[0] == "" {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// init
|
// init
|
||||||
var val interface{}
|
var val any
|
||||||
var ms string
|
var ms string
|
||||||
switch l {
|
switch l {
|
||||||
case defaultLayer:
|
case defaultLayer:
|
||||||
@@ -147,28 +146,25 @@ func deepCheckValue(assert *assert.Assertions, v *Viper, l layer, keys []string,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// loop through map
|
// loop through map
|
||||||
var m map[string]interface{}
|
var m map[string]any
|
||||||
err := false
|
|
||||||
for _, k := range keys {
|
for _, k := range keys {
|
||||||
if val == nil {
|
if val == nil {
|
||||||
assert.Fail(fmt.Sprintf("%s is not a map[string]interface{}", ms))
|
assert.Failf("%s is not a map[string]any", ms)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// deep scan of the map to get the final value
|
// deep scan of the map to get the final value
|
||||||
switch val.(type) {
|
switch val := val.(type) {
|
||||||
case map[interface{}]interface{}:
|
case map[any]any:
|
||||||
m = cast.ToStringMap(val)
|
m = cast.ToStringMap(val)
|
||||||
case map[string]interface{}:
|
case map[string]any:
|
||||||
m = val.(map[string]interface{})
|
m = val
|
||||||
default:
|
default:
|
||||||
assert.Fail(fmt.Sprintf("%s is not a map[string]interface{}", ms))
|
assert.Failf("%s is not a map[string]any", ms)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ms = ms + "[\"" + k + "\"]"
|
ms = ms + "[\"" + k + "\"]"
|
||||||
val = m[k]
|
val = m[k]
|
||||||
}
|
}
|
||||||
if !err {
|
assert.Equal(value, val)
|
||||||
assert.Equal(value, val)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+14
-8
@@ -10,6 +10,7 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
crypt "github.com/sagikazarmark/crypt/config"
|
crypt "github.com/sagikazarmark/crypt/config"
|
||||||
|
|
||||||
@@ -75,6 +76,7 @@ func getConfigManager(rp viper.RemoteProvider) (crypt.ConfigManager, error) {
|
|||||||
var cm crypt.ConfigManager
|
var cm crypt.ConfigManager
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
|
endpoints := strings.Split(rp.Endpoint(), ";")
|
||||||
if rp.SecretKeyring() != "" {
|
if rp.SecretKeyring() != "" {
|
||||||
var kr *os.File
|
var kr *os.File
|
||||||
kr, err = os.Open(rp.SecretKeyring())
|
kr, err = os.Open(rp.SecretKeyring())
|
||||||
@@ -84,24 +86,28 @@ func getConfigManager(rp viper.RemoteProvider) (crypt.ConfigManager, error) {
|
|||||||
defer kr.Close()
|
defer kr.Close()
|
||||||
switch rp.Provider() {
|
switch rp.Provider() {
|
||||||
case "etcd":
|
case "etcd":
|
||||||
cm, err = crypt.NewEtcdConfigManager([]string{rp.Endpoint()}, kr)
|
cm, err = crypt.NewEtcdConfigManager(endpoints, kr)
|
||||||
case "etcd3":
|
case "etcd3":
|
||||||
cm, err = crypt.NewEtcdV3ConfigManager([]string{rp.Endpoint()}, kr)
|
cm, err = crypt.NewEtcdV3ConfigManager(endpoints, kr)
|
||||||
case "firestore":
|
case "firestore":
|
||||||
cm, err = crypt.NewFirestoreConfigManager([]string{rp.Endpoint()}, kr)
|
cm, err = crypt.NewFirestoreConfigManager(endpoints, kr)
|
||||||
|
case "nats":
|
||||||
|
cm, err = crypt.NewNatsConfigManager(endpoints, kr)
|
||||||
default:
|
default:
|
||||||
cm, err = crypt.NewConsulConfigManager([]string{rp.Endpoint()}, kr)
|
cm, err = crypt.NewConsulConfigManager(endpoints, kr)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
switch rp.Provider() {
|
switch rp.Provider() {
|
||||||
case "etcd":
|
case "etcd":
|
||||||
cm, err = crypt.NewStandardEtcdConfigManager([]string{rp.Endpoint()})
|
cm, err = crypt.NewStandardEtcdConfigManager(endpoints)
|
||||||
case "etcd3":
|
case "etcd3":
|
||||||
cm, err = crypt.NewStandardEtcdV3ConfigManager([]string{rp.Endpoint()})
|
cm, err = crypt.NewStandardEtcdV3ConfigManager(endpoints)
|
||||||
case "firestore":
|
case "firestore":
|
||||||
cm, err = crypt.NewStandardFirestoreConfigManager([]string{rp.Endpoint()})
|
cm, err = crypt.NewStandardFirestoreConfigManager(endpoints)
|
||||||
|
case "nats":
|
||||||
|
cm, err = crypt.NewStandardNatsConfigManager(endpoints)
|
||||||
default:
|
default:
|
||||||
cm, err = crypt.NewStandardConsulConfigManager([]string{rp.Endpoint()})
|
cm, err = crypt.NewStandardConsulConfigManager(endpoints)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"unicode"
|
"unicode"
|
||||||
|
|
||||||
|
slog "github.com/sagikazarmark/slog-shim"
|
||||||
"github.com/spf13/cast"
|
"github.com/spf13/cast"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -31,13 +32,18 @@ func (pe ConfigParseError) Error() string {
|
|||||||
return fmt.Sprintf("While parsing config: %s", pe.err.Error())
|
return fmt.Sprintf("While parsing config: %s", pe.err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Unwrap returns the wrapped error.
|
||||||
|
func (pe ConfigParseError) Unwrap() error {
|
||||||
|
return pe.err
|
||||||
|
}
|
||||||
|
|
||||||
// toCaseInsensitiveValue checks if the value is a map;
|
// toCaseInsensitiveValue checks if the value is a map;
|
||||||
// if so, create a copy and lower-case the keys recursively.
|
// if so, create a copy and lower-case the keys recursively.
|
||||||
func toCaseInsensitiveValue(value interface{}) interface{} {
|
func toCaseInsensitiveValue(value any) any {
|
||||||
switch v := value.(type) {
|
switch v := value.(type) {
|
||||||
case map[interface{}]interface{}:
|
case map[any]any:
|
||||||
value = copyAndInsensitiviseMap(cast.ToStringMap(v))
|
value = copyAndInsensitiviseMap(cast.ToStringMap(v))
|
||||||
case map[string]interface{}:
|
case map[string]any:
|
||||||
value = copyAndInsensitiviseMap(v)
|
value = copyAndInsensitiviseMap(v)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,15 +52,15 @@ func toCaseInsensitiveValue(value interface{}) interface{} {
|
|||||||
|
|
||||||
// copyAndInsensitiviseMap behaves like insensitiviseMap, but creates a copy of
|
// copyAndInsensitiviseMap behaves like insensitiviseMap, but creates a copy of
|
||||||
// any map it makes case insensitive.
|
// any map it makes case insensitive.
|
||||||
func copyAndInsensitiviseMap(m map[string]interface{}) map[string]interface{} {
|
func copyAndInsensitiviseMap(m map[string]any) map[string]any {
|
||||||
nm := make(map[string]interface{})
|
nm := make(map[string]any)
|
||||||
|
|
||||||
for key, val := range m {
|
for key, val := range m {
|
||||||
lkey := strings.ToLower(key)
|
lkey := strings.ToLower(key)
|
||||||
switch v := val.(type) {
|
switch v := val.(type) {
|
||||||
case map[interface{}]interface{}:
|
case map[any]any:
|
||||||
nm[lkey] = copyAndInsensitiviseMap(cast.ToStringMap(v))
|
nm[lkey] = copyAndInsensitiviseMap(cast.ToStringMap(v))
|
||||||
case map[string]interface{}:
|
case map[string]any:
|
||||||
nm[lkey] = copyAndInsensitiviseMap(v)
|
nm[lkey] = copyAndInsensitiviseMap(v)
|
||||||
default:
|
default:
|
||||||
nm[lkey] = v
|
nm[lkey] = v
|
||||||
@@ -64,18 +70,25 @@ func copyAndInsensitiviseMap(m map[string]interface{}) map[string]interface{} {
|
|||||||
return nm
|
return nm
|
||||||
}
|
}
|
||||||
|
|
||||||
func insensitiviseMap(m map[string]interface{}) {
|
func insensitiviseVal(val any) any {
|
||||||
for key, val := range m {
|
switch v := val.(type) {
|
||||||
switch val.(type) {
|
case map[any]any:
|
||||||
case map[interface{}]interface{}:
|
// nested map: cast and recursively insensitivise
|
||||||
// nested map: cast and recursively insensitivise
|
val = cast.ToStringMap(val)
|
||||||
val = cast.ToStringMap(val)
|
insensitiviseMap(val.(map[string]any))
|
||||||
insensitiviseMap(val.(map[string]interface{}))
|
case map[string]any:
|
||||||
case map[string]interface{}:
|
// nested map: recursively insensitivise
|
||||||
// nested map: recursively insensitivise
|
insensitiviseMap(v)
|
||||||
insensitiviseMap(val.(map[string]interface{}))
|
case []any:
|
||||||
}
|
// nested array: recursively insensitivise
|
||||||
|
insensitiveArray(v)
|
||||||
|
}
|
||||||
|
return val
|
||||||
|
}
|
||||||
|
|
||||||
|
func insensitiviseMap(m map[string]any) {
|
||||||
|
for key, val := range m {
|
||||||
|
val = insensitiviseVal(val)
|
||||||
lower := strings.ToLower(key)
|
lower := strings.ToLower(key)
|
||||||
if key != lower {
|
if key != lower {
|
||||||
// remove old key (not lower-cased)
|
// remove old key (not lower-cased)
|
||||||
@@ -86,7 +99,13 @@ func insensitiviseMap(m map[string]interface{}) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func absPathify(logger Logger, inPath string) string {
|
func insensitiveArray(a []any) {
|
||||||
|
for i, val := range a {
|
||||||
|
a[i] = insensitiviseVal(val)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func absPathify(logger *slog.Logger, inPath string) string {
|
||||||
logger.Info("trying to resolve absolute path", "path", inPath)
|
logger.Info("trying to resolve absolute path", "path", inPath)
|
||||||
|
|
||||||
if inPath == "$HOME" || strings.HasPrefix(inPath, "$HOME"+string(os.PathSeparator)) {
|
if inPath == "$HOME" || strings.HasPrefix(inPath, "$HOME"+string(os.PathSeparator)) {
|
||||||
@@ -137,7 +156,7 @@ func safeMul(a, b uint) uint {
|
|||||||
return c
|
return c
|
||||||
}
|
}
|
||||||
|
|
||||||
// parseSizeInBytes converts strings like 1GB or 12 mb into an unsigned integer number of bytes
|
// parseSizeInBytes converts strings like 1GB or 12 mb into an unsigned integer number of bytes.
|
||||||
func parseSizeInBytes(sizeStr string) uint {
|
func parseSizeInBytes(sizeStr string) uint {
|
||||||
sizeStr = strings.TrimSpace(sizeStr)
|
sizeStr = strings.TrimSpace(sizeStr)
|
||||||
lastChar := len(sizeStr) - 1
|
lastChar := len(sizeStr) - 1
|
||||||
@@ -179,22 +198,22 @@ func parseSizeInBytes(sizeStr string) uint {
|
|||||||
// In case intermediate keys do not exist, or map to a non-map value,
|
// In case intermediate keys do not exist, or map to a non-map value,
|
||||||
// a new map is created and inserted, and the search continues from there:
|
// a new map is created and inserted, and the search continues from there:
|
||||||
// the initial map "m" may be modified!
|
// the initial map "m" may be modified!
|
||||||
func deepSearch(m map[string]interface{}, path []string) map[string]interface{} {
|
func deepSearch(m map[string]any, path []string) map[string]any {
|
||||||
for _, k := range path {
|
for _, k := range path {
|
||||||
m2, ok := m[k]
|
m2, ok := m[k]
|
||||||
if !ok {
|
if !ok {
|
||||||
// intermediate key does not exist
|
// intermediate key does not exist
|
||||||
// => create it and continue from there
|
// => create it and continue from there
|
||||||
m3 := make(map[string]interface{})
|
m3 := make(map[string]any)
|
||||||
m[k] = m3
|
m[k] = m3
|
||||||
m = m3
|
m = m3
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
m3, ok := m2.(map[string]interface{})
|
m3, ok := m2.(map[string]any)
|
||||||
if !ok {
|
if !ok {
|
||||||
// intermediate key is a value
|
// intermediate key is a value
|
||||||
// => replace with a new map
|
// => replace with a new map
|
||||||
m3 = make(map[string]interface{})
|
m3 = make(map[string]any)
|
||||||
m[k] = m3
|
m[k] = m3
|
||||||
}
|
}
|
||||||
// continue search from here
|
// continue search from here
|
||||||
|
|||||||
+18
-27
@@ -13,24 +13,24 @@ package viper
|
|||||||
import (
|
import (
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"reflect"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/spf13/viper/internal/testutil"
|
slog "github.com/sagikazarmark/slog-shim"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestCopyAndInsensitiviseMap(t *testing.T) {
|
func TestCopyAndInsensitiviseMap(t *testing.T) {
|
||||||
var (
|
var (
|
||||||
given = map[string]interface{}{
|
given = map[string]any{
|
||||||
"Foo": 32,
|
"Foo": 32,
|
||||||
"Bar": map[interface{}]interface{}{
|
"Bar": map[any]any{
|
||||||
"ABc": "A",
|
"ABc": "A",
|
||||||
"cDE": "B",
|
"cDE": "B",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
expected = map[string]interface{}{
|
expected = map[string]any{
|
||||||
"foo": 32,
|
"foo": 32,
|
||||||
"bar": map[string]interface{}{
|
"bar": map[string]any{
|
||||||
"abc": "A",
|
"abc": "A",
|
||||||
"cde": "B",
|
"cde": "B",
|
||||||
},
|
},
|
||||||
@@ -39,22 +39,15 @@ func TestCopyAndInsensitiviseMap(t *testing.T) {
|
|||||||
|
|
||||||
got := copyAndInsensitiviseMap(given)
|
got := copyAndInsensitiviseMap(given)
|
||||||
|
|
||||||
if !reflect.DeepEqual(got, expected) {
|
assert.Equal(t, expected, got)
|
||||||
t.Fatalf("Got %q\nexpected\n%q", got, expected)
|
_, ok := given["foo"]
|
||||||
}
|
assert.False(t, ok)
|
||||||
|
_, ok = given["bar"]
|
||||||
|
assert.False(t, ok)
|
||||||
|
|
||||||
if _, ok := given["foo"]; ok {
|
m := given["Bar"].(map[any]any)
|
||||||
t.Fatal("Input map changed")
|
_, ok = m["ABc"]
|
||||||
}
|
assert.True(t, ok)
|
||||||
|
|
||||||
if _, ok := given["bar"]; ok {
|
|
||||||
t.Fatal("Input map changed")
|
|
||||||
}
|
|
||||||
|
|
||||||
m := given["Bar"].(map[interface{}]interface{})
|
|
||||||
if _, ok := m["ABc"]; !ok {
|
|
||||||
t.Fatal("Input map changed")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAbsPathify(t *testing.T) {
|
func TestAbsPathify(t *testing.T) {
|
||||||
@@ -64,8 +57,8 @@ func TestAbsPathify(t *testing.T) {
|
|||||||
homer := filepath.Join(home, "homer")
|
homer := filepath.Join(home, "homer")
|
||||||
wd, _ := os.Getwd()
|
wd, _ := os.Getwd()
|
||||||
|
|
||||||
testutil.Setenv(t, "HOMER_ABSOLUTE_PATH", homer)
|
t.Setenv("HOMER_ABSOLUTE_PATH", homer)
|
||||||
testutil.Setenv(t, "VAR_WITH_RELATIVE_PATH", "relative")
|
t.Setenv("VAR_WITH_RELATIVE_PATH", "relative")
|
||||||
|
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
input string
|
input string
|
||||||
@@ -87,9 +80,7 @@ func TestAbsPathify(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
got := absPathify(jwwLogger{}, test.input)
|
got := absPathify(slog.Default(), test.input)
|
||||||
if got != test.output {
|
assert.Equal(t, test.output, got)
|
||||||
t.Errorf("Got %v\nexpected\n%q", got, test.output)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,32 +0,0 @@
|
|||||||
//go:build go1.16 && finder
|
|
||||||
// +build go1.16,finder
|
|
||||||
|
|
||||||
package viper
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/spf13/afero"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Search all configPaths for any config file.
|
|
||||||
// Returns the first path that exists (and is a config file).
|
|
||||||
func (v *Viper) findConfigFile() (string, error) {
|
|
||||||
finder := finder{
|
|
||||||
paths: v.configPaths,
|
|
||||||
fileNames: []string{v.configName},
|
|
||||||
extensions: SupportedExts,
|
|
||||||
withoutExtension: v.configType != "",
|
|
||||||
}
|
|
||||||
|
|
||||||
file, err := finder.Find(afero.NewIOFS(v.fs))
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
if file == "" {
|
|
||||||
return "", ConfigFileNotFoundError{v.configName, fmt.Sprintf("%s", v.configPaths)}
|
|
||||||
}
|
|
||||||
|
|
||||||
return file, nil
|
|
||||||
}
|
|
||||||
+514
-419
File diff suppressed because it is too large
Load Diff
@@ -1,56 +0,0 @@
|
|||||||
//go:build viper_yaml2
|
|
||||||
// +build viper_yaml2
|
|
||||||
|
|
||||||
package viper
|
|
||||||
|
|
||||||
var yamlExample = []byte(`Hacker: true
|
|
||||||
name: steve
|
|
||||||
hobbies:
|
|
||||||
- skateboarding
|
|
||||||
- snowboarding
|
|
||||||
- go
|
|
||||||
clothing:
|
|
||||||
jacket: leather
|
|
||||||
trousers: denim
|
|
||||||
pants:
|
|
||||||
size: large
|
|
||||||
age: 35
|
|
||||||
eyes : brown
|
|
||||||
beard: true
|
|
||||||
`)
|
|
||||||
|
|
||||||
var yamlWriteExpected = []byte(`age: 35
|
|
||||||
beard: true
|
|
||||||
clothing:
|
|
||||||
jacket: leather
|
|
||||||
pants:
|
|
||||||
size: large
|
|
||||||
trousers: denim
|
|
||||||
eyes: brown
|
|
||||||
hacker: true
|
|
||||||
hobbies:
|
|
||||||
- skateboarding
|
|
||||||
- snowboarding
|
|
||||||
- go
|
|
||||||
name: steve
|
|
||||||
`)
|
|
||||||
|
|
||||||
var yamlExampleWithDot = []byte(`Hacker: true
|
|
||||||
name: steve
|
|
||||||
hobbies:
|
|
||||||
- skateboarding
|
|
||||||
- snowboarding
|
|
||||||
- go
|
|
||||||
clothing:
|
|
||||||
jacket: leather
|
|
||||||
trousers: denim
|
|
||||||
pants:
|
|
||||||
size: large
|
|
||||||
age: 35
|
|
||||||
eyes : brown
|
|
||||||
beard: true
|
|
||||||
emails:
|
|
||||||
steve@hacker.com:
|
|
||||||
created: 01/02/03
|
|
||||||
active: true
|
|
||||||
`)
|
|
||||||
@@ -1,6 +1,3 @@
|
|||||||
//go:build !viper_yaml2
|
|
||||||
// +build !viper_yaml2
|
|
||||||
|
|
||||||
package viper
|
package viper
|
||||||
|
|
||||||
var yamlExample = []byte(`Hacker: true
|
var yamlExample = []byte(`Hacker: true
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
//go:build !js
|
|
||||||
// +build !js
|
|
||||||
|
|
||||||
package viper
|
|
||||||
|
|
||||||
import "github.com/fsnotify/fsnotify"
|
|
||||||
|
|
||||||
type watcher = fsnotify.Watcher
|
|
||||||
|
|
||||||
func newWatcher() (*watcher, error) {
|
|
||||||
return fsnotify.NewWatcher()
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
// +build js,wasm
|
|
||||||
|
|
||||||
package viper
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
|
|
||||||
"github.com/fsnotify/fsnotify"
|
|
||||||
)
|
|
||||||
|
|
||||||
type watcher struct {
|
|
||||||
Events chan fsnotify.Event
|
|
||||||
Errors chan error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (*watcher) Close() error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (*watcher) Add(name string) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (*watcher) Remove(name string) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func newWatcher() (*watcher, error) {
|
|
||||||
return &watcher{}, errors.New("fsnotify is not supported on WASM")
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user