Skip to content

Commit

Permalink
Set Consul-K8s-Version header on Consul API calls (#434)
Browse files Browse the repository at this point in the history
* Upgrade to latest consul api package
* Create common consul package that implements NewClient(). This
  function returns a Consul client that will set the header
  "Consul-K8s-Version" to the current consul-k8s version on all calls to
  Consul.
* Swap to using this new constructor everywhere.
* Add a linter that ensures we use our NewClient() function everywhere
  in the future.
  • Loading branch information
lkysow authored Feb 8, 2021
1 parent 864dae8 commit 431bc8b
Show file tree
Hide file tree
Showing 15 changed files with 252 additions and 22 deletions.
10 changes: 5 additions & 5 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,12 @@ jobs:
fi
- run: go vet ./...

# lint consul tests
lint-consul-retry:
linters:
executor: go
steps:
- checkout
- run: go get -u github.com/hashicorp/lint-consul-retry && lint-consul-retry
- run: go run hack/lint-api-new-client/main.go

test:
executor: go
Expand Down Expand Up @@ -150,15 +150,15 @@ workflows:
test-and-build:
jobs:
- go-fmt-and-vet
- lint-consul-retry
- linters
- test:
requires:
- go-fmt-and-vet
- lint-consul-retry
- linters
- test_enterprise:
requires:
- go-fmt-and-vet
- lint-consul-retry
- linters
- build-distro:
OS: "darwin freebsd linux windows"
ARCH: "386"
Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ FEATURES:

IMPROVEMENTS:
* CRDs: give a more descriptive error when a config entry already exists in Consul. [[GH-420](https://github.com/hashicorp/consul-k8s/pull/420)]
* Set `User-Agent: consul-k8s/<version>` header on calls to Consul where `<version>` is the current
version of `consul-k8s`. [[GH-434](https://github.com/hashicorp/consul-k8s/pull/434)]

## 0.23.0 (January 22, 2021)

Expand Down
3 changes: 2 additions & 1 deletion connect-inject/health_check_resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"sync"
"time"

"github.com/hashicorp/consul-k8s/consul"
"github.com/hashicorp/consul/api"
"github.com/hashicorp/go-hclog"
"golang.org/x/net/context"
Expand Down Expand Up @@ -278,7 +279,7 @@ func (h *HealthCheckResource) getConsulClient(pod *corev1.Pod) (*api.Client, err
if pod.Annotations[annotationConsulNamespace] != "" {
localConfig.Namespace = pod.Annotations[annotationConsulNamespace]
}
localClient, err := api.NewClient(localConfig)
localClient, err := consul.NewClient(localConfig)
if err != nil {
h.Log.Error("unable to get Consul API Client", "addr", newAddr, "err", err)
return nil, err
Expand Down
19 changes: 19 additions & 0 deletions consul/consul.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package consul

import (
"fmt"

"github.com/hashicorp/consul-k8s/version"
capi "github.com/hashicorp/consul/api"
)

// NewClient returns a Consul API client. It adds a required User-Agent
// header that describes the version of consul-k8s making the call.
func NewClient(config *capi.Config) (*capi.Client, error) {
client, err := capi.NewClient(config)
if err != nil {
return nil, err
}
client.AddHeader("User-Agent", fmt.Sprintf("consul-k8s/%s", version.GetHumanVersion()))
return client, nil
}
45 changes: 45 additions & 0 deletions consul/consul_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package consul

import (
"fmt"
"net/http"
"net/http/httptest"
"testing"

"github.com/hashicorp/consul-k8s/version"
capi "github.com/hashicorp/consul/api"
"github.com/stretchr/testify/require"
)

func TestNewClient(t *testing.T) {
type APICall struct {
Method string
Path string
UserAgentHeader string
}

var consulAPICalls []APICall
consulServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Record all the API calls made.
consulAPICalls = append(consulAPICalls, APICall{
Method: r.Method,
Path: r.URL.Path,
UserAgentHeader: r.UserAgent(),
})
fmt.Fprintln(w, "\"leader\"")
}))
defer consulServer.Close()

client, err := NewClient(&capi.Config{Address: consulServer.URL})
require.NoError(t, err)
leader, err := client.Status().Leader()
require.NoError(t, err)
require.Equal(t, "leader", leader)

require.Len(t, consulAPICalls, 1)
require.Equal(t, APICall{
Method: "GET",
Path: "/v1/status/leader",
UserAgentHeader: fmt.Sprintf("consul-k8s/%s", version.GetHumanVersion()),
}, consulAPICalls[0])
}
18 changes: 10 additions & 8 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,40 +1,42 @@
module github.com/hashicorp/consul-k8s

require (
github.com/armon/go-metrics v0.3.4 // indirect
github.com/armon/go-metrics v0.3.6 // indirect
github.com/cenkalti/backoff v2.1.1+incompatible
github.com/deckarep/golang-set v1.7.1
github.com/digitalocean/godo v1.10.0 // indirect
github.com/fatih/color v1.10.0 // indirect
github.com/go-logr/logr v0.1.0
github.com/google/go-cmp v0.4.0
github.com/google/go-querystring v1.0.0 // indirect
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510
github.com/hashicorp/consul/api v1.4.1-0.20201007080954-aa0f5ff839c5
github.com/hashicorp/consul/sdk v0.6.0
github.com/hashicorp/consul/api v1.4.1-0.20210203205937-0d1301c408a3
github.com/hashicorp/consul/sdk v0.7.0
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/go-discover v0.0.0-20200812215701-c4b85f6ed31f
github.com/hashicorp/go-hclog v0.12.0
github.com/hashicorp/go-immutable-radix v1.2.0 // indirect
github.com/hashicorp/go-hclog v0.15.0
github.com/hashicorp/go-immutable-radix v1.3.0 // indirect
github.com/hashicorp/go-msgpack v0.5.5 // indirect
github.com/hashicorp/go-multierror v1.1.0
github.com/hashicorp/go-sockaddr v1.0.2 // indirect
github.com/hashicorp/go-uuid v1.0.2 // indirect
github.com/hashicorp/serf v0.9.3
github.com/hashicorp/serf v0.9.5
github.com/joyent/triton-go v1.7.1-0.20200416154420-6801d15b779f // indirect
github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect
github.com/kr/text v0.1.0
github.com/mattbaird/jsonpatch v0.0.0-20171005235357-81af80346b1a
github.com/mitchellh/cli v1.1.0
github.com/mitchellh/go-homedir v1.1.0
github.com/mitchellh/go-testing-interface v1.14.0 // indirect
github.com/mitchellh/mapstructure v1.3.3 // indirect
github.com/mitchellh/mapstructure v1.4.1 // indirect
github.com/radovskyb/watcher v1.0.2
github.com/stretchr/testify v1.5.1
go.opencensus.io v0.22.0 // indirect
go.uber.org/zap v1.10.0
golang.org/x/net v0.0.0-20200625001655-4c5254603344
golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6 // indirect
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208 // indirect
golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae // indirect
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c // indirect
golang.org/x/time v0.0.0-20200416051211-89c76fbcd5d1 // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
gomodules.xyz/jsonpatch/v2 v2.0.1
Expand Down
22 changes: 22 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5
github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY=
github.com/armon/go-metrics v0.3.4 h1:Xqf+7f2Vhl9tsqDYmXhnXInUdcrtgpRNpIA15/uldSc=
github.com/armon/go-metrics v0.3.4/go.mod h1:4O98XIr/9W0sxpJ8UaYkvjk10Iff7SnFrb4QAOwNTFc=
github.com/armon/go-metrics v0.3.6 h1:x/tmtOF9cDBoXH7XoAGOz2qqm1DknFD1590XmD/DUJ8=
github.com/armon/go-metrics v0.3.6/go.mod h1:4O98XIr/9W0sxpJ8UaYkvjk10Iff7SnFrb4QAOwNTFc=
github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
github.com/armon/go-radix v1.0.0 h1:F4z6KzEeeQIMeLFa97iZU6vupzoecKdU5TX24SNppXI=
github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
Expand Down Expand Up @@ -132,6 +134,8 @@ github.com/evanphx/json-patch v4.9.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLi
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/fatih/color v1.9.0 h1:8xPHl4/q1VyqGIPif1F+1V3Y3lSmrq01EabUW3CoW5s=
github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU=
github.com/fatih/color v1.10.0 h1:s36xzo75JdqLaaWoiEHk767eHiwo0598uUxyfiPkDsg=
github.com/fatih/color v1.10.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM=
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=
Expand Down Expand Up @@ -254,20 +258,30 @@ github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t
github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY=
github.com/hashicorp/consul/api v1.4.1-0.20201007080954-aa0f5ff839c5 h1:mHgaDaPdf0z3UG3G2UpCINFMRKhzi1DLNoOp6sIQWnU=
github.com/hashicorp/consul/api v1.4.1-0.20201007080954-aa0f5ff839c5/go.mod h1:1NSuaUUkFaJzMasbfq/11wKYWSR67Xn6r2DXKhuDNFg=
github.com/hashicorp/consul/api v1.4.1-0.20210203205937-0d1301c408a3 h1:tpdztuA6xykU8LH3SeAxefJ4nab0K4KbE8Fu/F9C/ZI=
github.com/hashicorp/consul/api v1.4.1-0.20210203205937-0d1301c408a3/go.mod h1:sDjTOq0yUyv5G4h+BqSea7Fn6BU+XbolEz1952UB+mk=
github.com/hashicorp/consul/sdk v0.4.1-0.20201006182405-a2a8e9c7839a h1:yclqizoDCodLeiAUg1Siaodz3hvIBxzH8A2GnjY74EU=
github.com/hashicorp/consul/sdk v0.4.1-0.20201006182405-a2a8e9c7839a/go.mod h1:fY08Y9z5SvJqevyZNy6WWPXiG3KwBPAvlcdx16zZ0fM=
github.com/hashicorp/consul/sdk v0.7.0 h1:H6R9d008jDcHPQPAqPNuydAshJ4v5/8URdFnUvK/+sc=
github.com/hashicorp/consul/sdk v0.7.0/go.mod h1:fY08Y9z5SvJqevyZNy6WWPXiG3KwBPAvlcdx16zZ0fM=
github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=
github.com/hashicorp/go-cleanhttp v0.5.1 h1:dH3aiDG9Jvb5r5+bYHsikaOUIpcM0xvgMXVoDkXMzJM=
github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=
github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ=
github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48=
github.com/hashicorp/go-discover v0.0.0-20200812215701-c4b85f6ed31f h1:7WFMVeuJQp6BkzuTv9O52pzwtEFVUJubKYN+zez8eTI=
github.com/hashicorp/go-discover v0.0.0-20200812215701-c4b85f6ed31f/go.mod h1:D4eo8/CN92vm9/9UDG+ldX1/fMFa4kpl8qzyTolus8o=
github.com/hashicorp/go-hclog v0.12.0 h1:d4QkX8FRTYaKaCZBoXYY8zJX2BXjWxurN/GA2tkrmZM=
github.com/hashicorp/go-hclog v0.12.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ=
github.com/hashicorp/go-hclog v0.15.0 h1:qMuK0wxsoW4D0ddCCYwPSTm4KQv1X1ke3WmPWZ0Mvsk=
github.com/hashicorp/go-hclog v0.15.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ=
github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60=
github.com/hashicorp/go-immutable-radix v1.2.0 h1:l6UW37iCXwZkZoAbEYnptSHVE/cQ5bOTPYG5W3vf9+8=
github.com/hashicorp/go-immutable-radix v1.2.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60=
github.com/hashicorp/go-immutable-radix v1.3.0 h1:8exGP7ego3OmkfksihtSouGMZ+hQrhxx+FVELeXpVPE=
github.com/hashicorp/go-immutable-radix v1.3.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60=
github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM=
github.com/hashicorp/go-msgpack v0.5.5 h1:i9R9JSrqIz0QVLz3sz+i3YJdT7TTSLcfLLzJi9aZTuI=
github.com/hashicorp/go-msgpack v0.5.5/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM=
Expand Down Expand Up @@ -297,6 +311,8 @@ github.com/hashicorp/memberlist v0.2.2 h1:5+RffWKwqJ71YPu9mWsF7ZOscZmwfasdA8kbdC
github.com/hashicorp/memberlist v0.2.2/go.mod h1:MS2lj3INKhZjWNqd3N0m3J+Jxf3DAOnAH9VT3Sh9MUE=
github.com/hashicorp/serf v0.9.3 h1:AVF6JDQQens6nMHT9OGERBvK0f8rPrAGILnsKLr6lzM=
github.com/hashicorp/serf v0.9.3/go.mod h1:UWDWwZeL5cuWDJdl0C6wrvrUwEqtQ4ZKBKKENpqIUyk=
github.com/hashicorp/serf v0.9.5 h1:EBWvyu9tcRszt3Bxp3KNssBMP1KuHWyO51lz9+786iM=
github.com/hashicorp/serf v0.9.5/go.mod h1:UWDWwZeL5cuWDJdl0C6wrvrUwEqtQ4ZKBKKENpqIUyk=
github.com/hashicorp/vic v1.5.1-0.20190403131502-bbfe86ec9443 h1:O/pT5C1Q3mVXMyuqg7yuAWUg/jMZR1/0QTzTRdNR6Uw=
github.com/hashicorp/vic v1.5.1-0.20190403131502-bbfe86ec9443/go.mod h1:bEpDU35nTu0ey1EXjwNwPjI9xErAsoOCmcMb9GKvyxo=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
Expand Down Expand Up @@ -354,6 +370,8 @@ github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaO
github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-colorable v0.1.6 h1:6Su7aK7lXmJ/U79bYtBjLNaha4Fs1Rg9plHpcH+vvnE=
github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-colorable v0.1.8 h1:c1ghPdyEDarC70ftn0y+A/Ee++9zz8ljHG1b13eJ0s8=
github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
Expand Down Expand Up @@ -381,6 +399,8 @@ github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:F
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.3.3 h1:SzB1nHZ2Xi+17FP0zVQBHIZqvwRN9408fJO8h+eeNA8=
github.com/mitchellh/mapstructure v1.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/mitchellh/mapstructure v1.4.1 h1:CpVNEelQCZBooIPDn+AR3NpivK/TIKU8bDxdASFVQag=
github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
Expand Down Expand Up @@ -616,6 +636,8 @@ golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae h1:Ih9Yo4hSPImZOpfGuA4bR/ORKTAbhZo2AbWNRCnevdo=
golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c h1:VwygUrnw9jn88c4u8GD3rZQbqrP/tgas88tPUbBxQrk=
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.0.0-20160726164857-2910a502d2bf/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
Expand Down
132 changes: 132 additions & 0 deletions hack/lint-api-new-client/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
// Parses golang code looking for github.com/hashicorp/consul/api.NewClient()
// being used in non-test code. If it finds this, it will error.
// The purpose of this lint is that we actually want to use our internal
// github.com/hashicorp/consul-k8s/consul.NewClient() function because that
// adds the consul-k8s version as a header.
package main

import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"path/filepath"
"strings"
)

var (
broken = make(map[string]bool, 0) // Stored in a map for deduplication
exitCode = 0
fset = token.NewFileSet()
consulApiPackage = "github.com/hashicorp/consul/api"
)

func main() {
dir, err := os.Getwd()
if err != nil {
os.Stderr.WriteString(fmt.Sprintf("failed to get cwd: %v", err))
os.Exit(1)
}
err = walkDir(dir)
if err != nil {
os.Stderr.WriteString(err.Error())
os.Exit(1)
}
if len(broken) > 0 {
exitCode = 1
os.Stderr.WriteString("Found code using github.com/hashicorp/consul/api.NewClient()\ninstead of github.com/hashicorp/consul-k8s/consul.NewClient()\nin the following files:\n")
for filePath := range broken {
os.Stderr.WriteString(fmt.Sprintf("- %s\n", filePath))
}
}
os.Exit(exitCode)
}

type visitor struct {
path string
alias string
}

func (v visitor) Visit(n ast.Node) ast.Visitor {
switch node := n.(type) {
case *ast.CallExpr:
function, ok := node.Fun.(*ast.SelectorExpr)
if !ok {
break
}
pkg, ok := function.X.(*ast.Ident)
if !ok {
break
}
if !(pkg.Name == v.alias && function.Sel.Name == "NewClient") {
break
}
broken[v.path] = true
}
return v
}

// imports returns true if file imports pkg and the name of the alias
// used to import.
func imports(file *ast.File, pkgName string) (bool, string) {
var specs []ast.Spec

for _, decl := range file.Decls {
if general, ok := decl.(*ast.GenDecl); ok {
specs = append(specs, general.Specs...)
}
}
for _, spec := range specs {
pkg, ok := spec.(*ast.ImportSpec)
if !ok {
continue
}
path := pkg.Path.Value
// path may have leading/trailing quotes.
path = strings.Trim(path, "\"")
if path == pkgName {
alias := filepath.Base(pkgName)
if pkg.Name != nil {
alias = pkg.Name.Name
}
return true, alias
}
}
return false, ""
}

func walkDir(path string) error {
return filepath.Walk(path, visitFile)
}

func visitFile(path string, f os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("failed to visit '%s', %v", path, err)
}

// consul/consul.go is where we have our re-implementation of NewClient()
// which under the hood calls api.NewClient() so we need to discard that
// path.
if isNonTestFile(path, f) && !strings.Contains(path, "consul/consul.go") {
tree, err := parser.ParseFile(fset, path, nil, parser.ParseComments)
if err != nil {
return err
}

// Only process files importing github.com/hashicorp/consul/api.
importsAPI, alias := imports(tree, consulApiPackage)
if importsAPI {
v := visitor{
path: path,
alias: alias,
}
ast.Walk(v, tree)
}
}
return nil
}

func isNonTestFile(path string, f os.FileInfo) bool {
return !f.IsDir() && !strings.Contains(path, "test") && filepath.Ext(path) == ".go"
}
Loading

0 comments on commit 431bc8b

Please sign in to comment.