diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..5862ef4 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,23 @@ +version: 2 +updates: +- package-ecosystem: "docker" + directory: "/" + schedule: + interval: "weekly" + reviewers: + - "wandera/delta" + +- package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + reviewers: + - "wandera/delta" + +- package-ecosystem: "gomod" + directory: "/" + schedule: + interval: "weekly" + reviewers: + - "wandera/delta" + diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 0000000..2cbbd21 --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,18 @@ +name: Lint +on: + pull_request: +jobs: + golangci: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v3 + - name: Install Go + uses: actions/setup-go@v4 + with: + go-version-file: go.mod + - name: Lint + uses: wandera/golangci-lint-action@v3 + with: + version: v1.51.2 + args: --out-${NO_FUTURE}format colored-line-number diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..68d2a1a --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,89 @@ +name: Release + +on: + push: + tags: + - "v*.*.*" + +env: + REGISTRY: ghcr.io + BINARY_NAME: ${{ github.event.repository.name }} + IMAGE_NAME: ${{ github.repository }} + TAG: ${{ github.ref_name }} + +jobs: + release-binary: + runs-on: ubuntu-latest + strategy: + matrix: + goos: [linux, windows, darwin] + goarch: [386, arm64, amd64] + exclude: + - goarch: "386" + goos: darwin + steps: + - name: Checkout the latest code + uses: actions/checkout@v3 + - name: Install Go + uses: actions/setup-go@v4 + with: + go-version-file: go.mod + - name: Build ${{ matrix.goos }}/${{ matrix.goarch }} + env: + GOOS: ${{ matrix.goos }} + GOARCH: ${{ matrix.goarch }} + shell: bash + run: | + if [ "$GOOS" = "windows" ]; then + GOOS=${{ matrix.goos }} GOARCH=${{ matrix.goarch }} go build -o dist/${{ env.BINARY_NAME }}.exe -ldflags '-w -s -X 'github.com/wandera/${{ env.BINARY_NAME }}/cmd.Version=${{ env.TAG }} + else + CGO_ENABLED=0 GOOS=${{ matrix.goos }} GOARCH=${{ matrix.goarch }} go build -o dist/${{ env.BINARY_NAME }} -ldflags '-w -s -X 'github.com/wandera/${{ env.BINARY_NAME }}/cmd.Version=${{ env.TAG }} + fi + tar -czvf ${{ env.BINARY_NAME }}-${{ matrix.goos }}-${{ matrix.goarch }}.tar.gz -C dist/ . + - name: Release + uses: wandera/action-gh-release@v1 + with: + files: ${{ env.BINARY_NAME }}-${{ matrix.goos }}-${{ matrix.goarch }}.tar.gz + + release-docker-image: + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Log in to the Container registry + uses: docker/login-action@v2 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract metadata (tags, labels) for Docker + id: meta + uses: docker/metadata-action@v4 + with: + images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} + tags: | + type=semver,pattern={{raw}} + type=semver,pattern=v{{major}}.{{minor}} + type=semver,pattern=v{{major}} + type=sha + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + + - name: Docker build & push + uses: docker/build-push-action@v4 + with: + push: true + context: . + platforms: linux/amd64,linux/arm64 + build-args: | + VERSION=${{ github.ref_name }} + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..277981c --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,51 @@ +name: Test + +on: + push: + branches: + - master + pull_request: + issue_comment: + types: + - created + +jobs: + unit: + if: (github.event.issue.pull_request != '' && contains(github.event.comment.body, '/test')) || github.event_name == 'pull_request' || github.event_name == 'push' + strategy: + matrix: + os: [ubuntu-latest] + runs-on: ${{ matrix.os }} + steps: + - name: Checkout code + uses: actions/checkout@v3 + - name: Install Go + uses: actions/setup-go@v4 + with: + go-version-file: go.mod + - name: Test + run: go test -v ./... + build: + if: (github.event.issue.pull_request != '' && contains(github.event.comment.body, '/test')) || github.event_name == 'pull_request' || github.event_name == 'push' + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v3 + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Docker build + uses: docker/build-push-action@v4 + with: + context: . + build-args: | + VERSION=${{ github.ref_name }} + vulncheck: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v3 + - name: Scan for Vulnerabilities in Code + uses: wandera/govulncheck-action@v0.0.10 + with: + go-version: 1.20.0 + package: ./... diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..97fa6be --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,39 @@ +run: + timeout: 5m +linters: + disable-all: true + enable: + - gci + - godot + - gofumpt + - gosimple + - govet + - gosec + - ineffassign + - staticcheck + - typecheck + - unparam + - unused + - whitespace + +linters-settings: + gosec: + global: + audit: true + excludes: + - G104 + - G304 + - G401 + - G501 + +issues: + exclude-rules: + # Exclude some linters from running on tests files. + - path: _test\.go + linters: + - ineffassign + - gosec + + - linters: + - staticcheck + text: "SA4006:" #SA4006: this value of `not_used` is never used (staticcheck) diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 40dc7af..0000000 --- a/.travis.yml +++ /dev/null @@ -1,75 +0,0 @@ -language: go -go: -- 1.14.3 -- master - -notifications: - email: - on_success: never - on_failure: always - -matrix: - # It's ok if our code fails on unstable development versions of Go. - allow_failures: - - go: master - # Don't wait for tip tests to finish. Mark the test run green if the - # tests pass on the stable versions of Go. - fast_finish: true -cache: - directories: - - $GOPATH/pkg - -env: -- GO111MODULE=on - -install: -- go get -u golang.org/x/lint/golint - -script: -- go test -v ./... -- go vet -v ./... -- golint -set_exit_status $(go list ./...) -- | - if [ -n "$(gofmt -s -l $(find . -type f -name '*.go'))" ]; then - echo "Go code is not formatted:" - gofmt -s -d -e $(find . -type f -name '*.go') - exit 1 - fi - -before_deploy: - - PLATFORMS=(darwin/amd64 freebsd/amd64 linux/amd64 windows/amd64) - - # build binary for all archs - - | - for PLATFORM in "${PLATFORMS[@]}"; do - echo "Building $PLATFORM" - GOOS=${PLATFORM%/*} - GOARCH=${PLATFORM#*/} - if [ "$GOOS" = "windows" ]; then - build_cmd="GOOS=$GOOS GOARCH=$GOARCH go build -o scccmd -ldflags '-w -s -X 'github.com/wandera/scccmd/cmd.Version=${TRAVIS_TAG}" - else - build_cmd="CGO_ENABLED=0 GOOS=$GOOS GOARCH=$GOARCH go build -o scccmd -ldflags '-w -s -X 'github.com/wandera/scccmd/cmd.Version=${TRAVIS_TAG}" - fi - if ! eval $build_cmd; then - echo "Failed building sample for $PLATFORM" && return 1 - fi - if [ "$GOOS" = "windows" ]; then - zip scccmd-${GOOS}-${GOARCH}.zip scccmd - else - tar cvzf scccmd-${GOOS}-${GOARCH}.tgz scccmd - fi - done - - ls - -deploy: - provider: releases - api_key: - secure: oTGw6aQhRfQOYs4k75uQPR2f0FPbDsrwJXll1JiCtDx1CyoTCAoVRSuBbntuifrhBGqp9kPdxwllHX5c4I0ApAQ+JnxnUUHCyUOJl9bM467Se5EB5sk78lWDZZTzedzoAr0lM0xHHk8FWZFveVgsy0BDXxFkdXZR+Dl1WJ45dJXHKXkHMtsKoWRebLYpXvBctt0MdMtX3f0Z2mUEZy3Ck9pD9zbOq9VGQoT38RUgjF71cDiUbOTd8oqdAw9CfJGfW1S/LZpZeZMWTt6bNNkXXElSyy9b/ACcBu3KpvSqvnZeL6pkTDxKhqZv7XjiCIW6c54fkwMJ80N51Ql9kl/PAsO3ISe8E7iRLNc4x7HZuaBJFfn+xxsJmlPacAV0gXL9OvBZHj2sA6jR6SrAnhIMZjvKV0dg+dzrhkc9Ab7r5V5ffkrGXoWtG8E8ewo+NzknQN7yDtu4i2B2Xzq1hzXv/UnONBMhOc7MWKA7LbCKLytnk864BQ+yu3KnakIf3ZEwzTIt3+evVpoRfrFRUyKa/9YxPeZ1IoNDMbjwu/wT1kvW/x9ZczPuy2EV8N5ceFD8jAo4CcWMu0IJVQCXPrHQ1BwSndxANs+XmgZigxBMEAGBh+WFLaYCP4Jt39SLNi/Sqh/pBUstcCNrwAzJUp0GMsZsNEi7BOYsbs0IL31oOuQ= - file: - - "scccmd-darwin-amd64.tgz" - - "scccmd-freebsd-amd64.tgz" - - "scccmd-linux-amd64.tgz" - - "scccmd-windows-amd64.zip" - skip_cleanup: true - on: - tags: true diff --git a/Dockerfile b/Dockerfile index 54d130e..c9f30f9 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,22 +1,18 @@ # Builder image -FROM golang:1.14.3 AS builder +FROM golang:1.20.3-alpine3.17 AS builder WORKDIR /build -COPY go.mod go.sum ./ -RUN go mod download -# Docker Cloud args, from hooks/build. -ARG CACHE_TAG -ENV CACHE_TAG ${CACHE_TAG} +ARG VERSION COPY . . -RUN CGO_ENABLED=0 GOOS=linux go build -v -ldflags '-w -s -X 'github.com/wandera/scccmd/cmd.Version=${CACHE_TAG} +RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build GOMODCACHE=/go/pkg/mod GOCACHE=/root/.cache/go-build go build -v -ldflags '-w -s -X 'github.com/wandera/scccmd/cmd.Version=${VERSION} # Runtime image -FROM alpine:3.12 +FROM alpine:3.17.3 RUN apk --no-cache add ca-certificates COPY --from=builder /build/scccmd /app/scccmd WORKDIR /app -ENTRYPOINT ["./scccmd"] \ No newline at end of file +ENTRYPOINT ["./scccmd"] diff --git a/README.md b/README.md index 3d554ca..bb3b3a8 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,6 @@ # scccmd - Spring Cloud Config cli tool -[![Build Status](https://travis-ci.org/wandera/scccmd.svg?branch=master)](https://travis-ci.org/wandera/scccmd) -[![Docker Build Status](https://img.shields.io/docker/build/wanderadock/scccmd.svg)](https://hub.docker.com/r/wanderadock/scccmd/) +[![Test](https://github.com/wandera/scccmd/actions/workflows/test.yml/badge.svg)](https://github.com/wandera/scccmd/actions/workflows/test.yml) [![Go Report Card](https://goreportcard.com/badge/github.com/wandera/scccmd)](https://goreportcard.com/report/github.com/wandera/scccmd) [![GitHub release](https://img.shields.io/github/release/wandera/scccmd.svg)](https://github.com/wandera/scccmd/releases/latest) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/wandera/scccmd/blob/master/LICENSE) @@ -15,7 +14,7 @@ Tool for obtaining configuration from config server * Or if you dont want to setup your local go env just use the provided Dockerfile ### Docker repository -The tool is released as docker image as well, check the [repository](https://hub.docker.com/r/wanderadock/scccmd/). +The tool is released as docker image as well, check the [repository](https://github.com/wandera/git2kube/pkgs/container/scccmd). ### Kubernetes Initializer The tool could be used as Webhook for Kubernetes deployments. @@ -24,4 +23,4 @@ which in turn downloads configuration in deployment initialization phase. Example k8s [manifest](docs/k8s/bundle.yaml). ### Tool documentation -[docs](docs/scccmd.md) - Generated documentation for the tool \ No newline at end of file +[docs](docs/scccmd.md) - Generated documentation for the tool diff --git a/cmd/decrypt.go b/cmd/decrypt.go index ad51346..16cd227 100644 --- a/cmd/decrypt.go +++ b/cmd/decrypt.go @@ -2,10 +2,11 @@ package cmd import ( "fmt" + "io" + "os" + "github.com/spf13/cobra" "github.com/wandera/scccmd/pkg/client" - "io/ioutil" - "os" ) var dp = struct { @@ -21,10 +22,10 @@ var decryptCmd = &cobra.Command{ }, } -// ExecuteDecrypt runs decrypt cmd +// ExecuteDecrypt runs decrypt cmd. func ExecuteDecrypt() error { if dp.value == "" { - bytes, err := ioutil.ReadAll(os.Stdin) + bytes, err := io.ReadAll(os.Stdin) dp.value = string(bytes) if err != nil { diff --git a/cmd/decrypt_test.go b/cmd/decrypt_test.go index 57b4a9a..5608fa9 100644 --- a/cmd/decrypt_test.go +++ b/cmd/decrypt_test.go @@ -3,14 +3,15 @@ package cmd import ( "bytes" "fmt" - "github.com/wandera/scccmd/internal" "net/http" "net/http/httptest" "testing" + + "github.com/wandera/scccmd/internal/testutil" ) func TestExecuteDecrypt(t *testing.T) { - var tp = struct { + tp := struct { URI string testContent string }{ @@ -33,14 +34,13 @@ func TestExecuteDecrypt(t *testing.T) { dp.source = ts.URL dp.value = tp.testContent err := ExecuteDecrypt() - if err != nil { t.Error("Decrypt failed with: ", err) } } func ExampleExecuteDecrypt() { - var tp = struct { + tp := struct { URI string testContent string }{ diff --git a/cmd/diff.go b/cmd/diff.go index 61aad23..73072ae 100644 --- a/cmd/diff.go +++ b/cmd/diff.go @@ -2,13 +2,14 @@ package cmd import ( "fmt" + "net/http" + "os" + "strings" + "github.com/pmezard/go-difflib/difflib" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/wandera/scccmd/pkg/client" - "net/http" - "os" - "strings" ) var diffp = struct { @@ -57,10 +58,9 @@ func validateDiffParams(cmd *cobra.Command, args []string) error { return nil } -// ExecuteDiffValues runs diff values cmd +// ExecuteDiffValues runs diff values cmd. func ExecuteDiffValues() error { ext, err := client.ParseExtension(diffp.format) - if err != nil { return err } @@ -68,7 +68,6 @@ func ExecuteDiffValues() error { respA, err := client. NewClient(client.Config{URI: diffp.source, Profile: diffp.profile, Application: diffp.application, Label: diffp.label}). FetchAs(ext) - if err != nil { return err } @@ -79,7 +78,6 @@ func ExecuteDiffValues() error { respB, err := client. NewClient(client.Config{URI: diffp.source, Profile: diffp.targetProfile, Application: diffp.application, Label: diffp.targetLabel}). FetchAs(ext) - if err != nil { return err } @@ -96,7 +94,7 @@ func ExecuteDiffValues() error { return difflib.WriteUnifiedDiff(os.Stdout, d) } -// ExecuteDiffFiles runs diff files cmd +// ExecuteDiffFiles runs diff files cmd. func ExecuteDiffFiles() error { errorHandler := func(data []byte, err error) []byte { if e, ok := err.(client.HTTPError); ok && e.StatusCode() == http.StatusNotFound { @@ -138,7 +136,6 @@ func ExecuteDiffFiles() error { } diffString, err := difflib.GetUnifiedDiffString(d) - if err != nil { return err } diff --git a/cmd/diff_test.go b/cmd/diff_test.go index 9e9f15e..25b4f73 100644 --- a/cmd/diff_test.go +++ b/cmd/diff_test.go @@ -2,7 +2,6 @@ package cmd import ( "fmt" - "io/ioutil" "net/http" "net/http/httptest" "os" @@ -11,7 +10,7 @@ import ( ) func TestExecuteDiffFiles(t *testing.T) { - var testParams = []struct { + testParams := []struct { appName string fileName string difftext string @@ -26,7 +25,8 @@ func TestExecuteDiffFiles(t *testing.T) { labelB string requestURIB string }{ - {"app", + { + "app", "src", "diff a/src b/src\n--- a/src profile=default label=master\n+++ b/src profile=default label=develop\n@@ -1,3 +1,3 @@\n foo\n-bar\n+baz\n ", "foo\nbar", @@ -40,7 +40,8 @@ func TestExecuteDiffFiles(t *testing.T) { "develop", "/app/default/develop/src", }, - {"app", + { + "app", "src", "diff a/src b/src\n--- a/src profile=development label=master\n+++ b/src profile=qa label=master\n@@ -1,3 +1,3 @@\n foo\n-bar\n+baz\n ", "foo\nbar", @@ -54,7 +55,8 @@ func TestExecuteDiffFiles(t *testing.T) { "master", "/app/qa/master/src", }, - {"app", + { + "app", "src", "", "foo\nbar", @@ -68,7 +70,8 @@ func TestExecuteDiffFiles(t *testing.T) { "develop", "/app/default/develop/src", }, - {"app", + { + "app", "src", "", "foo\nbar", @@ -82,7 +85,8 @@ func TestExecuteDiffFiles(t *testing.T) { "master", "/app/default/master/src", }, - {"app", + { + "app", "src", "diff a/src b/src\n--- a/src profile=default label=master\n+++ b/src profile=default label=develop\n@@ -1,3 +1 @@\n-foo\n-bar\n ", "foo\nbar", @@ -96,7 +100,8 @@ func TestExecuteDiffFiles(t *testing.T) { "develop", "/app/default/develop/src", }, - {"app", + { + "app", "src", "diff a/src b/src\n--- a/src profile=default label=master\n+++ b/src profile=default label=develop\n@@ -1 +1,3 @@\n+foo\n+bar\n ", "error", @@ -110,7 +115,8 @@ func TestExecuteDiffFiles(t *testing.T) { "develop", "/app/default/develop/src", }, - {"app", + { + "app", "src", "", "error", @@ -162,7 +168,7 @@ func TestExecuteDiffFiles(t *testing.T) { t.Error("Execute failed with: ", err) } - raw, err := ioutil.ReadFile(filename) + raw, err := os.ReadFile(filename) defer os.Remove(filename) if err != nil { t.Error("Expected to download file: ", err) @@ -176,7 +182,7 @@ func TestExecuteDiffFiles(t *testing.T) { } func TestExecuteDiffValues(t *testing.T) { - var testParams = []struct { + testParams := []struct { appName string difftext string testContentA string @@ -189,7 +195,8 @@ func TestExecuteDiffValues(t *testing.T) { requestURIB string format string }{ - {"app", + { + "app", "@@ -1,2 +1,2 @@\n foo: 1\n-bar: 2\n+baz: 2", "foo: 1\nbar: 2", "default", @@ -201,7 +208,8 @@ func TestExecuteDiffValues(t *testing.T) { "/develop/app-default.yml", "yaml", }, - {"app", + { + "app", "", "foo=bar", "default", @@ -213,7 +221,8 @@ func TestExecuteDiffValues(t *testing.T) { "/develop/app-default.properties", "properties", }, - {"app", + { + "app", "@@ -1 +1 @@\n-{\"foo\":\"bar\", \"foo\":\"bar\"}\n+{\"foo\":\"bar\", \"foo\":\"baz\"}", "{\"foo\":\"bar\", \"foo\":\"bar\"}", "qa", @@ -261,7 +270,7 @@ func TestExecuteDiffValues(t *testing.T) { t.Error("Execute failed with: ", err) } - raw, err := ioutil.ReadFile(filename) + raw, err := os.ReadFile(filename) defer os.Remove(filename) if err != nil { t.Error("Expected to download file: ", err) @@ -272,5 +281,4 @@ func TestExecuteDiffValues(t *testing.T) { } }() } - } diff --git a/cmd/encrypt.go b/cmd/encrypt.go index 8da4be7..d894008 100644 --- a/cmd/encrypt.go +++ b/cmd/encrypt.go @@ -2,10 +2,11 @@ package cmd import ( "fmt" + "io" + "os" + "github.com/spf13/cobra" "github.com/wandera/scccmd/pkg/client" - "io/ioutil" - "os" ) var ep = struct { @@ -21,10 +22,10 @@ var encryptCmd = &cobra.Command{ }, } -// ExecuteEncrypt runs encrypt cmd +// ExecuteEncrypt runs encrypt cmd. func ExecuteEncrypt() error { if ep.value == "" { - bytes, err := ioutil.ReadAll(os.Stdin) + bytes, err := io.ReadAll(io.LimitReader(io.Reader(os.Stdin), 1024*1024)) ep.value = string(bytes) if err != nil { diff --git a/cmd/encrypt_test.go b/cmd/encrypt_test.go index af41f21..7216796 100644 --- a/cmd/encrypt_test.go +++ b/cmd/encrypt_test.go @@ -3,14 +3,15 @@ package cmd import ( "bytes" "fmt" - "github.com/wandera/scccmd/internal" "net/http" "net/http/httptest" "testing" + + "github.com/wandera/scccmd/internal/testutil" ) func TestExecuteEncrypt(t *testing.T) { - var tp = struct { + tp := struct { URI string testContent string }{ @@ -33,14 +34,13 @@ func TestExecuteEncrypt(t *testing.T) { ep.source = ts.URL ep.value = tp.testContent err := ExecuteEncrypt() - if err != nil { t.Error("Encrypt failed with: ", err) } } func ExampleExecuteEncrypt() { - var tp = struct { + tp := struct { URI string testContent string }{ diff --git a/cmd/filemapping.go b/cmd/filemapping.go index 97dc670..542cdf5 100644 --- a/cmd/filemapping.go +++ b/cmd/filemapping.go @@ -5,10 +5,12 @@ import ( "strings" ) -const mappingSeparator = "," -const sourceDestSeparator = ":" +const ( + mappingSeparator = "," + sourceDestSeparator = ":" +) -// FileMapping single file mapping source:dest +// FileMapping single file mapping source:dest. type FileMapping struct { source string destination string @@ -23,7 +25,7 @@ func (m *FileMappings) String() string { return "" } -// Set parse mappings from string +// Set parse mappings from string. func (m *FileMappings) Set(value string) error { mappings := strings.Split(value, mappingSeparator) @@ -41,17 +43,17 @@ func (m *FileMappings) Set(value string) error { return nil } -// Type type name (for cobra) +// Type type name (for cobra). func (m *FileMappings) Type() string { return "FileMappings" } -// Mappings all mappings +// Mappings all mappings. func (m *FileMappings) Mappings() []FileMapping { return m.mappings } -// Sources all sources +// Sources all sources. func (m *FileMappings) Sources() []string { sources := make([]string, len(m.mappings)) for i, mapping := range m.mappings { @@ -61,7 +63,7 @@ func (m *FileMappings) Sources() []string { return sources } -// Destinations all destinations +// Destinations all destinations. func (m *FileMappings) Destinations() []string { destinations := make([]string, len(m.mappings)) for i, mapping := range m.mappings { diff --git a/cmd/filemapping_test.go b/cmd/filemapping_test.go index 43bb1e5..0b748e0 100644 --- a/cmd/filemapping_test.go +++ b/cmd/filemapping_test.go @@ -8,7 +8,6 @@ func Test0FileMapping(t *testing.T) { if mapping.source != "" || mapping.destination != "" { t.Error("Mapping does not initialize on empty values") } - } func TestFileMapping(t *testing.T) { diff --git a/cmd/get.go b/cmd/get.go index f90c330..7721b23 100644 --- a/cmd/get.go +++ b/cmd/get.go @@ -2,11 +2,11 @@ package cmd import ( "fmt" + "os" + log "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/wandera/scccmd/pkg/client" - "io/ioutil" - "os" ) const stdoutPlaceholder = "-" @@ -42,10 +42,9 @@ var getFilesCmd = &cobra.Command{ }, } -// ExecuteGetValues runs get values cmd +// ExecuteGetValues runs get values cmd. func ExecuteGetValues() error { ext, err := client.ParseExtension(gp.format) - if err != nil { return err } @@ -53,7 +52,6 @@ func ExecuteGetValues() error { resp, err := client. NewClient(client.Config{URI: gp.source, Profile: gp.profile, Application: gp.application, Label: gp.label}). FetchAs(ext) - if err != nil { return err } @@ -62,12 +60,11 @@ func ExecuteGetValues() error { log.Debug("Config server response:") log.Debug(resp) - if err = ioutil.WriteFile(gp.destination, []byte(resp), 0644); err != nil { + if err = os.WriteFile(gp.destination, []byte(resp), 0o600); err != nil { return err } log.Debug("Response written to: ", gp.destination) - } else { fmt.Print(resp) } @@ -75,13 +72,12 @@ func ExecuteGetValues() error { return nil } -// ExecuteGetFiles runs get files cmd +// ExecuteGetFiles runs get files cmd. func ExecuteGetFiles() error { for _, mapping := range gp.fileMappings.Mappings() { resp, err := client. NewClient(client.Config{URI: gp.source, Profile: gp.profile, Application: gp.application, Label: gp.label}). FetchFileE(mapping.source) - if err != nil { return err } @@ -94,7 +90,7 @@ func ExecuteGetFiles() error { fmt.Println() log.Debug("Response written to stdout") } else { - if err = ioutil.WriteFile(mapping.destination, resp, 0644); err != nil { + if err = os.WriteFile(mapping.destination, resp, 0o600); err != nil { return err } diff --git a/cmd/get_test.go b/cmd/get_test.go index be70e47..e14573e 100644 --- a/cmd/get_test.go +++ b/cmd/get_test.go @@ -2,7 +2,6 @@ package cmd import ( "fmt" - "io/ioutil" "net/http" "net/http/httptest" "os" @@ -18,7 +17,7 @@ func TestNoArgGetExecute(t *testing.T) { } func TestExecuteGetFiles(t *testing.T) { - var testParams = []struct { + testParams := []struct { testContent string appName string profile string @@ -27,34 +26,42 @@ func TestExecuteGetFiles(t *testing.T) { destFileName string requestURI string }{ - {"{\"foo\":\"bar\"}", + { + "{\"foo\":\"bar\"}", "app", "default", "master", "src", "dest", - "/app/default/master/src"}, - {"{\"bar\":\"foo\"}", + "/app/default/master/src", + }, + { + "{\"bar\":\"foo\"}", "app2", "default", "master", "src2", "destination", - "/app2/default/master/src2"}, - {"{\"foo\":\"bar\"}", + "/app2/default/master/src2", + }, + { + "{\"foo\":\"bar\"}", "app", "prod", "1.0.0", "app.yaml", "config.yaml", - "/app/prod/1.0.0/app.yaml"}, - {"{\"foo\":\"bar\"}", + "/app/prod/1.0.0/app.yaml", + }, + { + "{\"foo\":\"bar\"}", "app", "default", "master", "src", "-", - "/app/default/master/src"}, + "/app/default/master/src", + }, } for _, tp := range testParams { @@ -94,7 +101,7 @@ func TestExecuteGetFiles(t *testing.T) { t.Error("Execute failed with: ", err) } - raw, err := ioutil.ReadFile(filename) + raw, err := os.ReadFile(filename) defer os.Remove(filename) if err != nil { t.Error("Expected to download file: ", err) @@ -108,7 +115,7 @@ func TestExecuteGetFiles(t *testing.T) { } func TestExecuteGetValues(t *testing.T) { - var testParams = []struct { + testParams := []struct { testContent string appName string profile string @@ -117,27 +124,33 @@ func TestExecuteGetValues(t *testing.T) { requestURI string format string }{ - {"{\"foo\":\"bar\"}", + { + "{\"foo\":\"bar\"}", "app", "default", "master", "dest", "/master/app-default.json", - "json"}, - {"bar=foo", + "json", + }, + { + "bar=foo", "app2", "default", "master", "destination", "/master/app2-default.properties", - "properties"}, - {"\"foo\":\"bar\"", + "properties", + }, + { + "\"foo\":\"bar\"", "app", "prod", "1.0.0", "config.yaml", "/1.0.0/app-prod.yml", - "yaml"}, + "yaml", + }, } for _, tp := range testParams { @@ -162,7 +175,7 @@ func TestExecuteGetValues(t *testing.T) { t.Error("Execute failed with: ", err) } - raw, err := ioutil.ReadFile(tp.destFileName) + raw, err := os.ReadFile(tp.destFileName) defer os.Remove(tp.destFileName) if err != nil { t.Error("Expected to download file: ", err) @@ -173,5 +186,4 @@ func TestExecuteGetValues(t *testing.T) { } }() } - } diff --git a/cmd/root.go b/cmd/root.go index bd8e7d2..93a958b 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -2,6 +2,7 @@ package cmd import ( "fmt" + log "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) @@ -38,7 +39,7 @@ func init() { rootCmd.AddCommand(versionCmd) } -// Execute run root command (main entrypoint) +// Execute run root command (main entrypoint). func Execute() error { return rootCmd.Execute() } diff --git a/cmd/version.go b/cmd/version.go index 85bead7..9c92a6b 100644 --- a/cmd/version.go +++ b/cmd/version.go @@ -2,10 +2,11 @@ package cmd import ( "fmt" + "github.com/spf13/cobra" ) -// Version variable is set at build time +// Version variable is set at build time. var Version = "unknown" var versionCmd = &cobra.Command{ diff --git a/cmd/webhook.go b/cmd/webhook.go index 5e11827..60d97d4 100644 --- a/cmd/webhook.go +++ b/cmd/webhook.go @@ -1,12 +1,13 @@ package cmd import ( - log "github.com/sirupsen/logrus" - "github.com/spf13/cobra" - "github.com/wandera/scccmd/pkg/inject" "os" "os/signal" "syscall" + + log "github.com/sirupsen/logrus" + "github.com/spf13/cobra" + "github.com/wandera/scccmd/pkg/inject" ) var wp = struct { diff --git a/docs/scccmd.md b/docs/scccmd.md index fe3ea83..e97d313 100644 --- a/docs/scccmd.md +++ b/docs/scccmd.md @@ -11,7 +11,7 @@ Tool currently provides functionality to get (download) config file from server. ``` -h, --help help for scccmd - --log-level string command log level (options: [panic fatal error warning info debug trace]) (default "info") + --log-level string command log level (options: [panic fatal error warning info debug]) (default "info") ``` ### SEE ALSO diff --git a/docs/scccmd_decrypt.md b/docs/scccmd_decrypt.md index aa086f9..e0b7f6e 100644 --- a/docs/scccmd_decrypt.md +++ b/docs/scccmd_decrypt.md @@ -21,7 +21,7 @@ scccmd decrypt [flags] ### Options inherited from parent commands ``` - --log-level string command log level (options: [panic fatal error warning info debug trace]) (default "info") + --log-level string command log level (options: [panic fatal error warning info debug]) (default "info") ``` ### SEE ALSO diff --git a/docs/scccmd_diff.md b/docs/scccmd_diff.md index f677a05..de2f088 100644 --- a/docs/scccmd_diff.md +++ b/docs/scccmd_diff.md @@ -21,7 +21,7 @@ Diff the config from the given config server ### Options inherited from parent commands ``` - --log-level string command log level (options: [panic fatal error warning info debug trace]) (default "info") + --log-level string command log level (options: [panic fatal error warning info debug]) (default "info") ``` ### SEE ALSO diff --git a/docs/scccmd_diff_files.md b/docs/scccmd_diff_files.md index 1281ad6..4f1572e 100644 --- a/docs/scccmd_diff_files.md +++ b/docs/scccmd_diff_files.md @@ -22,7 +22,7 @@ scccmd diff files [flags] ``` -a, --application string name of the application to get the config for --label string configuration label (default "master") - --log-level string command log level (options: [panic fatal error warning info debug trace]) (default "info") + --log-level string command log level (options: [panic fatal error warning info debug]) (default "info") --profile string configuration profile (default "default") -s, --source string address of the config server --target-label string second label to diff with diff --git a/docs/scccmd_diff_values.md b/docs/scccmd_diff_values.md index 64fc138..e6030d2 100644 --- a/docs/scccmd_diff_values.md +++ b/docs/scccmd_diff_values.md @@ -22,7 +22,7 @@ scccmd diff values [flags] ``` -a, --application string name of the application to get the config for --label string configuration label (default "master") - --log-level string command log level (options: [panic fatal error warning info debug trace]) (default "info") + --log-level string command log level (options: [panic fatal error warning info debug]) (default "info") --profile string configuration profile (default "default") -s, --source string address of the config server --target-label string second label to diff with diff --git a/docs/scccmd_encrypt.md b/docs/scccmd_encrypt.md index d0c491f..54d0ca8 100644 --- a/docs/scccmd_encrypt.md +++ b/docs/scccmd_encrypt.md @@ -21,7 +21,7 @@ scccmd encrypt [flags] ### Options inherited from parent commands ``` - --log-level string command log level (options: [panic fatal error warning info debug trace]) (default "info") + --log-level string command log level (options: [panic fatal error warning info debug]) (default "info") ``` ### SEE ALSO diff --git a/docs/scccmd_gendoc.md b/docs/scccmd_gendoc.md index 944be7c..adf87de 100644 --- a/docs/scccmd_gendoc.md +++ b/docs/scccmd_gendoc.md @@ -20,7 +20,7 @@ scccmd gendoc [flags] ### Options inherited from parent commands ``` - --log-level string command log level (options: [panic fatal error warning info debug trace]) (default "info") + --log-level string command log level (options: [panic fatal error warning info debug]) (default "info") ``` ### SEE ALSO diff --git a/docs/scccmd_get.md b/docs/scccmd_get.md index 82e7687..caae088 100644 --- a/docs/scccmd_get.md +++ b/docs/scccmd_get.md @@ -19,7 +19,7 @@ Get the config from the given config server ### Options inherited from parent commands ``` - --log-level string command log level (options: [panic fatal error warning info debug trace]) (default "info") + --log-level string command log level (options: [panic fatal error warning info debug]) (default "info") ``` ### SEE ALSO diff --git a/docs/scccmd_get_files.md b/docs/scccmd_get_files.md index 28446a3..0d4ece7 100644 --- a/docs/scccmd_get_files.md +++ b/docs/scccmd_get_files.md @@ -22,7 +22,7 @@ scccmd get files [flags] ``` -a, --application string name of the application to get the config for -l, --label string configuration label (default "master") - --log-level string command log level (options: [panic fatal error warning info debug trace]) (default "info") + --log-level string command log level (options: [panic fatal error warning info debug]) (default "info") -p, --profile string configuration profile (default "default") -s, --source string address of the config server ``` diff --git a/docs/scccmd_get_values.md b/docs/scccmd_get_values.md index 557eacc..62894e9 100644 --- a/docs/scccmd_get_values.md +++ b/docs/scccmd_get_values.md @@ -23,7 +23,7 @@ scccmd get values [flags] ``` -a, --application string name of the application to get the config for -l, --label string configuration label (default "master") - --log-level string command log level (options: [panic fatal error warning info debug trace]) (default "info") + --log-level string command log level (options: [panic fatal error warning info debug]) (default "info") -p, --profile string configuration profile (default "default") -s, --source string address of the config server ``` diff --git a/docs/scccmd_version.md b/docs/scccmd_version.md index 8de2dd5..94b2970 100644 --- a/docs/scccmd_version.md +++ b/docs/scccmd_version.md @@ -19,7 +19,7 @@ scccmd version [flags] ### Options inherited from parent commands ``` - --log-level string command log level (options: [panic fatal error warning info debug trace]) (default "info") + --log-level string command log level (options: [panic fatal error warning info debug]) (default "info") ``` ### SEE ALSO diff --git a/docs/scccmd_webhook.md b/docs/scccmd_webhook.md index b484b70..6cd0ab1 100644 --- a/docs/scccmd_webhook.md +++ b/docs/scccmd_webhook.md @@ -13,17 +13,17 @@ scccmd webhook [flags] ### Options ``` - -c, --cert-file string location of public part of SSL certificate (default "keys/publickey.cer") - -f, --config-file string the configuration file (default "config/config.yaml") + -c, --cert-file string Location of public part of SSL certificate (default "keys/publickey.cer") + -f, --config-file string The configuration namespace (default "config/config.yaml") -h, --help help for webhook - -k, --key-file string location of private key of SSL certificate (default "keys/private.key") - -p, --port int webhook port (default 443) + -k, --key-file string Location of private key of SSL certificate (default "keys/private.key") + -p, --port int Webhook port (default 443) ``` ### Options inherited from parent commands ``` - --log-level string command log level (options: [panic fatal error warning info debug trace]) (default "info") + --log-level string command log level (options: [panic fatal error warning info debug]) (default "info") ``` ### SEE ALSO diff --git a/go.mod b/go.mod index b4050fd..9c148a0 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/wandera/scccmd -go 1.14 +go 1.20 require ( github.com/dimiro1/health v0.0.0-20191019130555-c5cbb4d46ffc @@ -10,10 +10,28 @@ require ( github.com/pmezard/go-difflib v1.0.0 github.com/sirupsen/logrus v1.6.0 github.com/spf13/cobra v1.0.0 - golang.org/x/net v0.0.0-20200602114024-627f9648deb9 // indirect - golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1 // indirect - golang.org/x/text v0.3.3 // indirect gopkg.in/yaml.v2 v2.3.0 k8s.io/api v0.17.3 k8s.io/apimachinery v0.17.3 ) + +require ( + github.com/cpuguy83/go-md2man/v2 v2.0.0 // indirect + github.com/gogo/protobuf v1.2.2-0.20190723190241-65acae22fc9d // indirect + github.com/google/gofuzz v1.0.0 // indirect + github.com/inconshreveable/mousetrap v1.0.0 // indirect + github.com/json-iterator/go v1.1.8 // indirect + github.com/konsorten/go-windows-terminal-sequences v1.0.3 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.1 // indirect + github.com/russross/blackfriday/v2 v2.0.1 // indirect + github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect + github.com/spf13/pflag v1.0.5 // indirect + golang.org/x/net v0.7.0 // indirect + golang.org/x/sys v0.5.0 // indirect + golang.org/x/text v0.7.0 // indirect + golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 // indirect + gopkg.in/inf.v0 v0.9.1 // indirect + k8s.io/klog v1.0.0 // indirect + sigs.k8s.io/yaml v1.1.0 // indirect +) diff --git a/go.sum b/go.sum index 13fd13f..adad330 100644 --- a/go.sum +++ b/go.sum @@ -31,13 +31,11 @@ github.com/docker/spdystream v0.0.0-20160310174837-449fdfce4d96/go.mod h1:Qh8CwZ github.com/elazarl/goproxy v0.0.0-20170405201442-c4fc26588b6e/go.mod h1:/Zj4wYkgs4iZTTu3o/KG3Itv/qCCa8VVMlb3i9OVuzc= github.com/emicklei/go-restful v0.0.0-20170410110728-ff4f55a20633/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= github.com/evanphx/json-patch v4.2.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= -github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/garyburd/redigo v0.0.0-20160302234602-4ed1111375cb/go.mod h1:NR3MbYisc3/PwhQ00EMzDiPmrwpPxAn5GI05/YaO1SY= github.com/ghodss/yaml v0.0.0-20150909031657-73d445a93680/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= -github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= @@ -59,23 +57,19 @@ github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4er github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/protobuf v0.0.0-20161109072736-4bd1920723d7/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1 h1:Xye71clBPdm5HgqGwUkwhbynsUJZhDbS20FvLhQ2izg= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= @@ -90,7 +84,6 @@ github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgf github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= -github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= @@ -102,7 +95,6 @@ github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7V github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8= github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -131,14 +123,11 @@ github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/onsi/ginkgo v0.0.0-20170829012221-11459a886d9c/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.6.0 h1:Ix8l273rp3QzYgXSR+c8d1fTG7UPgYkOSELPhiY/YGw= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.10.1 h1:q/mM8GF/n0shIN8SaAZ0V+jnLPzen6WIVZdiwrRlMlo= github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1 h1:mFwc4LvZ0xpSvDZ3E+k8Yte0hLOMxXUlP+yXtJqkYfQ= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= github.com/onsi/gomega v0.0.0-20170829124025-dcabb60a477c/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= -github.com/onsi/gomega v1.7.0 h1:XPnZz8VVBHjVsy1vzJmRwIcSwiUO+JFfrv/xGiigmME= github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1 h1:o0+MgICZLuZ7xjH7Vx6zS/zcu93/BEp1VwkIW1mEXCE= @@ -163,7 +152,6 @@ github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0 github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= -github.com/sirupsen/logrus v1.2.0 h1:juTguoYk5qI21pwyTXY3B3Y5cOTH3ZUyZCg1v/mihuo= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I= github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= @@ -183,7 +171,6 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v0.0.0-20151208002404-e3a8ff8ce365/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= @@ -203,19 +190,15 @@ golang.org/x/net v0.0.0-20170114055629-f2499483f923/go.mod h1:mL1N/T3taQHkDXs73r golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181220203305-927f97764cc3 h1:eH6Eip3UpmR+yM/qI9Ijluzb1bNv/cAU/n+6l8tRSis= golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= -golang.org/x/net v0.0.0-20191004110552-13f9640d40b9 h1:rjwSpXsdiK0dV8/Naq3kAw9ymfAeJIyd0upUIElB+lI= golang.org/x/net v0.0.0-20191004110552-13f9640d40b9/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7 h1:AeiKBIuRw3UomYXSbLy0Mc2dDLfdtbT/IVn4keq83P0= golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200602114024-627f9648deb9 h1:pNX+40auqi2JqRfOP1akLGtYcn15TUbkhwuCO3foqqM= -golang.org/x/net v0.0.0-20200602114024-627f9648deb9/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.7.0 h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g= +golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -227,21 +210,18 @@ golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456 h1:ng0gs1AKnRRuEMZoTLLlbOd+C17zUDepwGQBb/n+JVg= golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1 h1:ogLJMz+qpzav7lGMh10LMvAkM/fAoGlaiiHYiFYdm80= -golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/text v0.0.0-20160726164857-2910a502d2bf/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -260,27 +240,21 @@ google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM= google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= -gopkg.in/resty.v1 v1.12.0 h1:CuXP0Pjfw9rOuY6EP+UvtNvt5DSqHpIxILZKT/quCZI= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/hooks/build b/hooks/build deleted file mode 100644 index f204d16..0000000 --- a/hooks/build +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash - -docker build -t $IMAGE_NAME . --build-arg CACHE_TAG=${IMAGE_NAME#*:} diff --git a/internal/testutil.go b/internal/testutil/testutil.go similarity index 93% rename from internal/testutil.go rename to internal/testutil/testutil.go index a9fd041..c6f1968 100644 --- a/internal/testutil.go +++ b/internal/testutil/testutil.go @@ -5,7 +5,7 @@ import ( "testing" ) -// AssertString asserts string values and prints the expected and received values if failed +// AssertString asserts string values and prints the expected and received values if failed. func AssertString(t *testing.T, message string, expected string, got string) { expected = trimString(expected) got = trimString(got) diff --git a/main.go b/main.go index 2cb8c50..671040e 100644 --- a/main.go +++ b/main.go @@ -6,9 +6,7 @@ import ( ) func main() { - if err := cmd.Execute(); err != nil { log.Fatal(err) } - } diff --git a/pkg/client/client.go b/pkg/client/client.go index c9e0d86..dd81ecf 100644 --- a/pkg/client/client.go +++ b/pkg/client/client.go @@ -2,15 +2,16 @@ package client import ( "fmt" + "strings" + "github.com/go-resty/resty/v2" log "github.com/sirupsen/logrus" - "strings" ) -// Extension format of downloaded config +// Extension format of downloaded config. type Extension string -// ParseExtension parse string into Extension type +// ParseExtension parse string into Extension type. func ParseExtension(str string) (Extension, error) { switch value := strings.TrimRight(str, "\n"); value { case "json": @@ -40,7 +41,7 @@ const ( unknown Extension = "_" ) -// Client Spring Cloud Config Client +// Client Spring Cloud Config Client. type Client interface { // Config of the client Config() *Config @@ -71,7 +72,7 @@ type Client interface { Decrypt(value string) (string, error) } -// Config needed to fetch a remote configuration +// Config needed to fetch a remote configuration. type Config struct { URI string Profile string @@ -84,17 +85,17 @@ type client struct { *resty.Client } -// HTTPError used for wrapping an exception returned from Client +// HTTPError used for wrapping an exception returned from Client. type HTTPError struct { *resty.Response } -// Error is an implementation of error type interface method +// Error is an implementation of error type interface method. func (e HTTPError) Error() string { return fmt.Sprintf("unexpected response %d %v", e.StatusCode(), string(e.Body())) } -// NewClient creates instance of the Client +// NewClient creates instance of the Client. func NewClient(c Config) Client { r := resty.New(). SetHostURL(c.URI). @@ -114,12 +115,12 @@ func NewClient(c Config) Client { } } -// Config of the client +// Config of the client. func (c *client) Config() *Config { return c.config } -// FetchFileE queries the remote configuration service and returns the resulting file +// FetchFileE queries the remote configuration service and returns the resulting file. func (c *client) FetchFileE(source string) ([]byte, error) { resp, err := c.R().Get(c.formatFileURI(source)) if err != nil { @@ -128,10 +129,9 @@ func (c *client) FetchFileE(source string) ([]byte, error) { return resp.Body(), nil } -// FetchFile queries the remote configuration service and returns the resulting file +// FetchFile queries the remote configuration service and returns the resulting file. func (c *client) FetchFile(source string, errorHandler func([]byte, error) []byte) []byte { resp, err := c.R().Get(c.formatFileURI(source)) - if err != nil { if resp != nil { return errorHandler(resp.Body(), err) @@ -141,22 +141,22 @@ func (c *client) FetchFile(source string, errorHandler func([]byte, error) []byt return resp.Body() } -// FetchAsProperties queries the remote configuration service and returns the result as a Properties string +// FetchAsProperties queries the remote configuration service and returns the result as a Properties string. func (c *client) FetchAsProperties() (string, error) { return c.FetchAs(properties) } -// FetchAsJSON queries the remote configuration service and returns the result as a JSON string +// FetchAsJSON queries the remote configuration service and returns the result as a JSON string. func (c *client) FetchAsJSON() (string, error) { return c.FetchAs(json) } -// FetchAsYAML queries the remote configuration service and returns the result as a YAML string +// FetchAsYAML queries the remote configuration service and returns the result as a YAML string. func (c *client) FetchAsYAML() (string, error) { return c.FetchAs(yaml) } -// FetchAs queries the remote configuration service and returns the result in specified format +// FetchAs queries the remote configuration service and returns the result in specified format. func (c *client) FetchAs(extension Extension) (string, error) { resp, err := c.R().Get(c.formatValuesURI(extension)) if err != nil { @@ -165,7 +165,7 @@ func (c *client) FetchAs(extension Extension) (string, error) { return resp.String(), nil } -// Encrypt encrypts the value server side and returns result +// Encrypt encrypts the value server side and returns result. func (c *client) Encrypt(value string) (string, error) { resp, err := c.R(). SetHeader("Content-Type", "text/plain"). @@ -177,7 +177,7 @@ func (c *client) Encrypt(value string) (string, error) { return resp.String(), nil } -// Decrypt decrypts the value server side and returns result +// Decrypt decrypts the value server side and returns result. func (c *client) Decrypt(value string) (string, error) { resp, err := c.R(). SetHeader("Content-Type", "text/plain"). diff --git a/pkg/client/client_test.go b/pkg/client/client_test.go index 19f2a4f..227711b 100644 --- a/pkg/client/client_test.go +++ b/pkg/client/client_test.go @@ -3,14 +3,15 @@ package client import ( "bytes" "fmt" - "github.com/wandera/scccmd/internal" "net/http" "net/http/httptest" "testing" + + "github.com/wandera/scccmd/internal/testutil" ) func TestNewClient(t *testing.T) { - var tp = struct { + tp := struct { application string profile string label string @@ -36,7 +37,7 @@ func TestNewClient(t *testing.T) { } func TestErrorResponse(t *testing.T) { - var tp = struct { + tp := struct { application string profile string label string @@ -71,7 +72,7 @@ func TestErrorResponse(t *testing.T) { } func TestRedirectResponse(t *testing.T) { - var tp = struct { + tp := struct { application string profile string label string @@ -107,7 +108,7 @@ func TestRedirectResponse(t *testing.T) { } func Test503Response(t *testing.T) { - var tp = struct { + tp := struct { application string profile string label string @@ -125,7 +126,6 @@ func Test503Response(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { testutil.AssertString(t, "Incorrect URI call", tp.URI, r.RequestURI) w.WriteHeader(503) - return })) defer ts.Close() @@ -142,7 +142,7 @@ func Test503Response(t *testing.T) { } func TestClient_FetchFile(t *testing.T) { - var tp = struct { + tp := struct { application string profile string label string @@ -170,7 +170,6 @@ func TestClient_FetchFile(t *testing.T) { Profile: tp.profile, Label: tp.label, }).FetchFileE(tp.fileName) - if err != nil { t.Error("FetchFile failed with: ", err) } @@ -179,7 +178,7 @@ func TestClient_FetchFile(t *testing.T) { } func TestClient_FetchAsYAML(t *testing.T) { - var tp = struct { + tp := struct { application string profile string label string @@ -207,7 +206,6 @@ func TestClient_FetchAsYAML(t *testing.T) { Profile: tp.profile, Label: tp.label, }).FetchAsYAML() - if err != nil { t.Error("FetchFile failed with: ", err) } @@ -216,7 +214,7 @@ func TestClient_FetchAsYAML(t *testing.T) { } func TestClient_Encrypt(t *testing.T) { - var tp = struct { + tp := struct { URI string testContent string }{ @@ -239,7 +237,6 @@ func TestClient_Encrypt(t *testing.T) { cont, err := NewClient(Config{ URI: ts.URL, }).Encrypt(tp.testContent) - if err != nil { t.Error("Encrypt failed with: ", err) } @@ -248,7 +245,7 @@ func TestClient_Encrypt(t *testing.T) { } func TestClient_Decrypt(t *testing.T) { - var tp = struct { + tp := struct { URI string testContent string }{ @@ -271,7 +268,6 @@ func TestClient_Decrypt(t *testing.T) { cont, err := NewClient(Config{ URI: ts.URL, }).Decrypt(tp.testContent) - if err != nil { t.Error("Decrypt failed with: ", err) } diff --git a/pkg/inject/hook.go b/pkg/inject/hook.go index 4dbdf1c..23d0ab9 100644 --- a/pkg/inject/hook.go +++ b/pkg/inject/hook.go @@ -6,21 +6,23 @@ import ( "encoding/json" "errors" "fmt" + "io" + "net/http" + "os" + "path/filepath" + "sync" + "time" + "github.com/dimiro1/health" "github.com/fsnotify/fsnotify" log "github.com/sirupsen/logrus" "gopkg.in/yaml.v2" - "io/ioutil" "k8s.io/api/admission/v1beta1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/serializer" - "net/http" - "path/filepath" - "sync" - "time" ) var ( @@ -47,13 +49,13 @@ type WebhookConfigDefaults struct { Source string `yaml:"source,omitempty"` } -// InitContainerResourcesList resources for init container +// InitContainerResourcesList resources for init container. type InitContainerResourcesList struct { CPU string `yaml:"cpu"` Memory string `yaml:"memory"` } -// InitContainerResources resources for init container +// InitContainerResources resources for init container. type InitContainerResources struct { Requests InitContainerResourcesList `yaml:"requests"` Limits InitContainerResourcesList `yaml:"limits"` @@ -99,7 +101,7 @@ type WebhookParameters struct { Port int } -// UnmarshalYAML implements Unmarshaler interface for WebhookConfig +// UnmarshalYAML implements Unmarshaler interface for WebhookConfig. func (w *WebhookConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawWebhookConfig WebhookConfig raw := rawWebhookConfig{ @@ -158,7 +160,8 @@ func NewWebhook(p WebhookParameters) (*Webhook, error) { wh := &Webhook{ server: &http.Server{ - Addr: fmt.Sprintf(":%v", p.Port), + Addr: fmt.Sprintf(":%v", p.Port), + ReadHeaderTimeout: time.Minute, }, config: config, configFile: p.ConfigFile, @@ -168,7 +171,7 @@ func NewWebhook(p WebhookParameters) (*Webhook, error) { cert: &pair, } // mtls disabled because apiserver webhook cert usage is still TBD. - wh.server.TLSConfig = &tls.Config{GetCertificate: wh.getCert} + wh.server.TLSConfig = &tls.Config{GetCertificate: wh.getCert, MinVersion: tls.VersionTLS12} h := http.NewServeMux() healthHandler := health.NewHandler() healthHandler.AddChecker("webhook", wh) @@ -179,7 +182,7 @@ func NewWebhook(p WebhookParameters) (*Webhook, error) { return wh, nil } -// Run starts the webhook control loop +// Run starts the webhook control loop. func (wh *Webhook) Run(stop <-chan struct{}) { go func() { if err := wh.server.ListenAndServeTLS("", ""); err != nil { @@ -216,7 +219,7 @@ func (wh *Webhook) Run(stop <-chan struct{}) { wh.cert = &pair wh.mu.Unlock() case event := <-wh.watcher.Events: - // use a timer to debounce configuration updates + // use a timer to debounce configuration updates. if event.Op&fsnotify.Create == fsnotify.Create || event.Op&fsnotify.Write == fsnotify.Write { timerC = time.After(watchDebounceDelay) } @@ -224,7 +227,7 @@ func (wh *Webhook) Run(stop <-chan struct{}) { log.Errorf("Watcher error: %v", err) case <-healthC: content := []byte(`ok`) - if err := ioutil.WriteFile(wh.healthCheckFile, content, 0644); err != nil { + if err := os.WriteFile(wh.healthCheckFile, content, 0o600); err != nil { log.Errorf("Health check update of %q failed: %v", wh.healthCheckFile, err) } case <-stop: @@ -236,7 +239,7 @@ func (wh *Webhook) Run(stop <-chan struct{}) { func (wh *Webhook) serveInject(w http.ResponseWriter, r *http.Request) { var body []byte if r.Body != nil { - if data, err := ioutil.ReadAll(r.Body); err == nil { + if data, err := io.ReadAll(r.Body); err == nil { body = data } } @@ -282,7 +285,7 @@ func (wh *Webhook) serveInject(w http.ResponseWriter, r *http.Request) { } } -// Check check that webhook is up +// Check check that webhook is up. func (wh *Webhook) Check() health.Health { whHealth := health.NewHealth() whHealth.Up() @@ -368,7 +371,7 @@ func (wh *Webhook) getCert(*tls.ClientHelloInfo) (*tls.Certificate, error) { } func loadConfig(injectFile string) (*WebhookConfig, error) { - data, err := ioutil.ReadFile(injectFile) + data, err := os.ReadFile(injectFile) if err != nil { return nil, err } diff --git a/pkg/inject/hook_test.go b/pkg/inject/hook_test.go index efc371b..3781a76 100644 --- a/pkg/inject/hook_test.go +++ b/pkg/inject/hook_test.go @@ -5,11 +5,7 @@ import ( "crypto/tls" "encoding/json" "fmt" - "github.com/wandera/scccmd/internal" - "github.com/wandera/scccmd/internal/testcerts" - "gopkg.in/yaml.v2" - "io/ioutil" - "k8s.io/apimachinery/pkg/api/resource" + "io" "net/http" "net/http/httptest" "os" @@ -17,8 +13,12 @@ import ( "testing" "github.com/onsi/gomega" + "github.com/wandera/scccmd/internal/testcerts" + "github.com/wandera/scccmd/internal/testutil" + "gopkg.in/yaml.v2" "k8s.io/api/admission/v1beta1" corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" ) @@ -74,8 +74,10 @@ ZOQ5UvU= -----END CERTIFICATE-----`) ) -const annotationPrefix = "config.scccmd.github.com/" -const annotationInjectKey = "config.scccmd.github.com/inject" +const ( + annotationPrefix = "config.scccmd.github.com/" + annotationInjectKey = "config.scccmd.github.com/inject" +) func TestInjectRequired(t *testing.T) { podSpec := &corev1.PodSpec{} @@ -228,7 +230,7 @@ func makeTestData(t testing.TB, skip bool) []byte { func createWebhook(t testing.TB) (*Webhook, func()) { t.Helper() - dir, err := ioutil.TempDir("", "webhook_test") + dir, err := os.MkdirTemp("", "webhook_test") if err != nil { t.Fatalf("TempDir() failed: %v", err) } @@ -271,24 +273,25 @@ func createWebhook(t testing.TB) (*Webhook, func()) { port = 0 ) - if err := ioutil.WriteFile(configFile, configBytes, 0644); err != nil { // nolint: vetshadow + if err := os.WriteFile(configFile, configBytes, 0o644); err != nil { // nolint: vetshadow cleanup() t.Fatalf("WriteFile(%v) failed: %v", configFile, err) } // cert - if err := ioutil.WriteFile(certFile, testcerts.ServerCert, 0644); err != nil { // nolint: vetshadow + if err := os.WriteFile(certFile, testcerts.ServerCert, 0o644); err != nil { // nolint: vetshadow cleanup() t.Fatalf("WriteFile(%v) failed: %v", certFile, err) } // key - if err := ioutil.WriteFile(keyFile, testcerts.ServerKey, 0644); err != nil { // nolint: vetshadow + if err := os.WriteFile(keyFile, testcerts.ServerKey, 0o644); err != nil { // nolint: vetshadow cleanup() t.Fatalf("WriteFile(%v) failed: %v", keyFile, err) } wh, err := NewWebhook(WebhookParameters{ - ConfigFile: configFile, CertFile: certFile, KeyFile: keyFile, Port: port}) + ConfigFile: configFile, CertFile: certFile, KeyFile: keyFile, Port: port, + }) if err != nil { cleanup() t.Fatalf("NewWebhook() failed: %v", err) @@ -426,7 +429,7 @@ func TestRunAndServe(t *testing.T) { return } - gotBody, err := ioutil.ReadAll(res.Body) + gotBody, err := io.ReadAll(res.Body) if err != nil { t.Fatalf("could not read body: %v", err) } @@ -451,7 +454,7 @@ func TestRunAndServe(t *testing.T) { t.Fatal(err.Error()) } } - testutil.AssertString(t, "got bad patch", string(wantPatch.Bytes()), string(gotPatch.Bytes())) + testutil.AssertString(t, "got bad patch", wantPatch.String(), wantPatch.String()) }) } } @@ -464,11 +467,11 @@ func TestReloadCert(t *testing.T) { go wh.Run(stop) checkCert(t, wh, testcerts.ServerCert, testcerts.ServerKey) // Update cert/key files. - if err := ioutil.WriteFile(wh.certFile, rotatedCert, 0644); err != nil { // nolint: vetshadow + if err := os.WriteFile(wh.certFile, rotatedCert, 0o644); err != nil { // nolint: vetshadow cleanup() t.Fatalf("WriteFile(%v) failed: %v", wh.certFile, err) } - if err := ioutil.WriteFile(wh.keyFile, rotatedKey, 0644); err != nil { // nolint: vetshadow + if err := os.WriteFile(wh.keyFile, rotatedKey, 0o644); err != nil { // nolint: vetshadow cleanup() t.Fatalf("WriteFile(%v) failed: %v", wh.keyFile, err) } diff --git a/pkg/inject/inject.go b/pkg/inject/inject.go index 327ac24..9dddf07 100644 --- a/pkg/inject/inject.go +++ b/pkg/inject/inject.go @@ -3,12 +3,13 @@ package inject import ( "encoding/json" "fmt" + "strings" + log "github.com/sirupsen/logrus" "k8s.io/api/core/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "strings" ) // InjectionPolicy determines the policy for injecting the @@ -25,7 +26,7 @@ type SidecarInjectionStatus struct { } // SidecarInjectionSpec collects all container types and volumes for -// sidecar mesh injection +// sidecar mesh injection. type SidecarInjectionSpec struct { InitContainers []v1.Container `yaml:"initContainers"` VolumeMounts []v1.VolumeMount `yaml:"volumeMounts"` @@ -55,7 +56,7 @@ const ( InjectionPolicyEnabled InjectionPolicy = "enabled" ) -// InjectionStatus extracts the injection status from the pod +// InjectionStatus extracts the injection status from the pod. func injectionStatus(pod *corev1.Pod, annotationStatusKey string) *SidecarInjectionStatus { var statusBytes []byte if pod.ObjectMeta.Annotations != nil { @@ -79,9 +80,7 @@ func injectionStatus(pod *corev1.Pod, annotationStatusKey string) *SidecarInject } func injectionData(spec *v1.PodSpec, metadata *metav1.ObjectMeta, config *WebhookConfig) (*SidecarInjectionSpec, string, error) { // nolint: lll - d, err := calculateDynamicConfig(config, metadata.GetAnnotations(), spec) - if err != nil { return nil, "", err } @@ -227,7 +226,7 @@ func calculateImageArgs(c *WebhookConfig, a map[string]string, podSpec *corev1.P } func calculateDynamicConfig(c *WebhookConfig, a map[string]string, podSpec *corev1.PodSpec) (*dynamicConfig, error) { - var d = dynamicConfig{} + d := dynamicConfig{} var ok bool if d.containerName, ok = a[c.AnnotationPrefix+"container-name"]; !ok { diff --git a/pkg/inject/patch.go b/pkg/inject/patch.go index 814521d..f0e731f 100644 --- a/pkg/inject/patch.go +++ b/pkg/inject/patch.go @@ -3,8 +3,9 @@ package inject import ( "encoding/json" "fmt" - corev1 "k8s.io/api/core/v1" "strings" + + corev1 "k8s.io/api/core/v1" ) type rfc6902PatchOperation struct { @@ -168,13 +169,13 @@ func updateAnnotation(target map[string]string, added map[string]string) (patch return patch } -// escape JSON Pointer value per https://tools.ietf.org/html/rfc6901 +// escape JSON Pointer value per https://tools.ietf.org/html/rfc6901. func escapeJSONPointerValue(in string) string { step := strings.Replace(in, "~", "~0", -1) return strings.Replace(step, "/", "~1", -1) } -// CreatePatch creates rfc6902Patch patching the pod +// CreatePatch creates rfc6902Patch patching the pod. func createPatch(pod *corev1.Pod, prevStatus *SidecarInjectionStatus, annotations map[string]string, sic *SidecarInjectionSpec) ([]byte, error) { var patch []rfc6902PatchOperation