Skip to content

Commit 34b1814

Browse files
refactor: logger and docs (#13)
1 parent fce22d6 commit 34b1814

File tree

9 files changed

+148
-41
lines changed

9 files changed

+148
-41
lines changed

CONTRIBUTING.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ git --version
1717
go version
1818
```
1919

20+
Also make sure to install the tools required for development by running `make generate`.
21+
2022
## Setting up
2123

2224
Clone this repository with git.
@@ -41,6 +43,12 @@ To run the tests run:
4143
make test
4244
```
4345

46+
If writing unit tests, use the mocks generated by [GoMock](https://github.com/golang/mock) by running `make generate`.
47+
48+
If writing `pact` or integration tests, use the test implementations in [./internal/util/testutil](./internal/util/testutil).
49+
50+
If you've changed any of the interfaces you may need to re-run `make generate` to generate the mocks again.
51+
4452
## Code ownership
4553

4654
For current ownership assignments, see: [CODEOWNERS](./.github/CODEOWNERS).

README.md

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,69 @@
11
# code-client-go
22

33
A library that exposes scanning capabilities for Snyk Code that can be used in the [Snyk CLI](https://github.com/snyk/cli) as well as Snyk IDE plugins using the [Snyk Language Server](https://github.com/snyk/snyk-ls).
4+
5+
## Installation
6+
7+
```shell script
8+
$ go get github.com/snyk/code-client-go
9+
```
10+
11+
## Usage
12+
13+
### HTTP Client
14+
15+
Use the HTTP client to make HTTP requests with configured retriable codes and authorisation headers for Snyk Rest APIs.
16+
17+
```go
18+
engine := workflow.NewDefaultWorkFlowEngine()
19+
httpClient := http.NewHTTPClient(engine, engine.GetNetworkAccess().GetHttpClient, codeInstrumentor, codeErrorReporter)
20+
```
21+
22+
The HTTP client exposes a `DoCall` function.
23+
24+
25+
### Snyk Code Client
26+
27+
Use the Snyk Code Client to make calls to the DeepCode API using the `httpClient` HTTP client created above.
28+
29+
30+
```go
31+
engine := workflow.NewDefaultWorkFlowEngine()
32+
snykCode := deepcode.NewSnykCodeClient(engine, httpClient, testutil.NewTestInstrumentor())
33+
```
34+
35+
The Snyk Code Client exposes the following functions:
36+
- `GetFilters`
37+
- `CreateBundle`
38+
- `ExtendBundle`
39+
40+
### Bundle Manager
41+
42+
Use the Bundle Manager to create bundles using the `snykCode` Snyk Code Client created above and then to extend it by uploading more files to it.
43+
44+
```go
45+
bundleManager := bundle.NewBundleManager(snykCode, testutil.NewTestInstrumentor(), testutil.NewTestCodeInstrumentor())
46+
```
47+
48+
The Bundle Manager exposes the following functions:
49+
- `Create`
50+
- `Upload`
51+
52+
### Code Scanner
53+
54+
Use the Code Scanner to trigger a scan for a Snyk Code workspace using the Bundle Manager created above:
55+
56+
```go
57+
codeScanner := codeclient.NewCodeScanner(
58+
bundleManager,
59+
testutil.NewTestInstrumentor(),
60+
testutil.NewTestCodeInstrumentor(),
61+
testutils.NewTestAnalytics(),
62+
)
63+
```
64+
65+
The Code Scanner exposes a `UploadAndAnalyze` function.
66+
67+
### Observability
68+
69+
Under [./observability](./observability) we have defined some observability interfaces which allows consumers of the library to inject their own observability implementations as long as they follow the defined interfaces.

bundle/bundle.go

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,13 @@ package bundle
1818

1919
import (
2020
"context"
21-
22-
"github.com/rs/zerolog/log"
21+
"github.com/rs/zerolog"
2322

2423
"github.com/snyk/code-client-go/deepcode"
2524
"github.com/snyk/code-client-go/observability"
2625
)
2726

28-
//go:generate mockgen -destination=mocks/deepCodeBundle.go -source=deepCodeBundle.go -package mocks
27+
//go:generate mockgen -destination=mocks/bundle.go -source=bundle.go -package mocks
2928
type Bundle interface {
3029
UploadBatch(ctx context.Context, host string, batch *Batch) error
3130
GetBundleHash() string
@@ -39,6 +38,7 @@ type deepCodeBundle struct {
3938
SnykCode deepcode.SnykCodeClient
4039
instrumentor observability.Instrumentor
4140
errorReporter observability.ErrorReporter
41+
logger *zerolog.Logger
4242
requestId string
4343
rootPath string
4444
files map[string]deepcode.BundleFile
@@ -48,11 +48,23 @@ type deepCodeBundle struct {
4848
limitToFiles []string
4949
}
5050

51-
func NewBundle(snykCode deepcode.SnykCodeClient, instrumentor observability.Instrumentor, errorReporter observability.ErrorReporter, bundleHash string, requestId string, rootPath string, files map[string]deepcode.BundleFile, limitToFiles []string, missingFiles []string) *deepCodeBundle {
51+
func NewBundle(
52+
snykCode deepcode.SnykCodeClient,
53+
instrumentor observability.Instrumentor,
54+
errorReporter observability.ErrorReporter,
55+
logger *zerolog.Logger,
56+
bundleHash string,
57+
requestId string,
58+
rootPath string,
59+
files map[string]deepcode.BundleFile,
60+
limitToFiles []string,
61+
missingFiles []string,
62+
) *deepCodeBundle {
5263
return &deepCodeBundle{
5364
SnykCode: snykCode,
5465
instrumentor: instrumentor,
5566
errorReporter: errorReporter,
67+
logger: logger,
5668
bundleHash: bundleHash,
5769
requestId: requestId,
5870
rootPath: rootPath,
@@ -96,7 +108,7 @@ func (b *deepCodeBundle) extendBundle(ctx context.Context, host string, uploadBa
96108
var err error
97109
if uploadBatch.hasContent() {
98110
b.bundleHash, b.missingFiles, err = b.SnykCode.ExtendBundle(ctx, host, b.bundleHash, uploadBatch.documents, []string{})
99-
log.Debug().Str("requestId", b.requestId).Interface("MissingFiles", b.missingFiles).Msg("extended deepCodeBundle on backend")
111+
b.logger.Debug().Str("requestId", b.requestId).Interface("MissingFiles", b.missingFiles).Msg("extended deepCodeBundle on backend")
100112
}
101113

102114
return err

bundle/bundle_manager.go

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,12 @@ package bundle
1818

1919
import (
2020
"context"
21+
"github.com/rs/zerolog"
22+
"github.com/snyk/go-application-framework/pkg/workflow"
2123
"os"
2224
"path/filepath"
2325

2426
"github.com/puzpuzpuz/xsync"
25-
"github.com/rs/zerolog/log"
26-
2727
"github.com/snyk/code-client-go/deepcode"
2828
"github.com/snyk/code-client-go/internal/util"
2929
"github.com/snyk/code-client-go/observability"
@@ -34,6 +34,7 @@ type bundleManager struct {
3434
SnykCode deepcode.SnykCodeClient
3535
instrumentor observability.Instrumentor
3636
errorReporter observability.ErrorReporter
37+
logger *zerolog.Logger
3738
supportedExtensions *xsync.MapOf[string, bool]
3839
supportedConfigFiles *xsync.MapOf[string, bool]
3940
}
@@ -56,11 +57,17 @@ type BundleManager interface {
5657
) (Bundle, error)
5758
}
5859

59-
func NewBundleManager(SnykCode deepcode.SnykCodeClient, instrumentor observability.Instrumentor, errorReporter observability.ErrorReporter) *bundleManager {
60+
func NewBundleManager(
61+
engine workflow.Engine,
62+
SnykCode deepcode.SnykCodeClient,
63+
instrumentor observability.Instrumentor,
64+
errorReporter observability.ErrorReporter,
65+
) *bundleManager {
6066
return &bundleManager{
6167
SnykCode: SnykCode,
6268
instrumentor: instrumentor,
6369
errorReporter: errorReporter,
70+
logger: engine.GetLogger(),
6471
supportedExtensions: xsync.NewMapOf[bool](),
6572
supportedConfigFiles: xsync.NewMapOf[bool](),
6673
}
@@ -96,7 +103,7 @@ func (b *bundleManager) Create(ctx context.Context,
96103
var fileContent []byte
97104
fileContent, err = os.ReadFile(absoluteFilePath)
98105
if err != nil {
99-
log.Error().Err(err).Str("filePath", absoluteFilePath).Msg("could not load content of file")
106+
b.logger.Error().Err(err).Str("filePath", absoluteFilePath).Msg("could not load content of file")
100107
continue
101108
}
102109

@@ -133,6 +140,7 @@ func (b *bundleManager) Create(ctx context.Context,
133140
b.SnykCode,
134141
b.instrumentor,
135142
b.errorReporter,
143+
b.logger,
136144
bundleHash,
137145
requestId,
138146
rootPath,
@@ -193,10 +201,10 @@ func (b *bundleManager) groupInBatches(
193201
file := files[filePath]
194202
var fileContent = []byte(file.Content)
195203
if batch.canFitFile(filePath, fileContent) {
196-
log.Trace().Str("path", filePath).Int("size", len(fileContent)).Msgf("added to deepCodeBundle #%v", len(batches))
204+
b.logger.Trace().Str("path", filePath).Int("size", len(fileContent)).Msgf("added to deepCodeBundle #%v", len(batches))
197205
batch.documents[filePath] = file
198206
} else {
199-
log.Trace().Str("path", filePath).Int("size", len(fileContent)).Msgf("created new deepCodeBundle - %v bundles in this upload so far", len(batches))
207+
b.logger.Trace().Str("path", filePath).Int("size", len(fileContent)).Msgf("created new deepCodeBundle - %v bundles in this upload so far", len(batches))
200208
newUploadBatch := NewBatch(map[string]deepcode.BundleFile{})
201209
newUploadBatch.documents[filePath] = file
202210
batches = append(batches, newUploadBatch)
@@ -210,7 +218,7 @@ func (b *bundleManager) IsSupported(ctx context.Context, host string, file strin
210218
if b.supportedExtensions.Size() == 0 && b.supportedConfigFiles.Size() == 0 {
211219
filters, err := b.SnykCode.GetFilters(ctx, host)
212220
if err != nil {
213-
log.Error().Err(err).Msg("could not get filters")
221+
b.logger.Error().Err(err).Msg("could not get filters")
214222
return false, err
215223
}
216224

bundle/bundle_manager_test.go

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -19,20 +19,22 @@ package bundle_test
1919
import (
2020
"bytes"
2121
"context"
22-
deepcode2 "github.com/snyk/code-client-go/deepcode"
23-
mocks2 "github.com/snyk/code-client-go/deepcode/mocks"
22+
"github.com/rs/zerolog"
2423
"os"
2524
"path/filepath"
2625
"strings"
2726
"testing"
2827

2928
"github.com/golang/mock/gomock"
30-
"github.com/snyk/code-client-go/observability/mocks"
29+
"github.com/snyk/go-application-framework/pkg/workflow"
3130
"github.com/stretchr/testify/assert"
3231
"github.com/stretchr/testify/require"
3332

3433
"github.com/snyk/code-client-go/bundle"
34+
deepcode2 "github.com/snyk/code-client-go/deepcode"
35+
mocks2 "github.com/snyk/code-client-go/deepcode/mocks"
3536
"github.com/snyk/code-client-go/internal/util"
37+
"github.com/snyk/code-client-go/observability/mocks"
3638
)
3739

3840
func Test_Create(t *testing.T) {
@@ -60,7 +62,7 @@ func Test_Create(t *testing.T) {
6062
err := os.WriteFile(file, []byte(data), 0600)
6163
require.NoError(t, err)
6264

63-
var bundleManager = bundle.NewBundleManager(mockSnykCodeClient, mockInstrumentor, mockErrorReporter)
65+
var bundleManager = bundle.NewBundleManager(workflow.NewDefaultWorkFlowEngine(), mockSnykCodeClient, mockInstrumentor, mockErrorReporter)
6466
bundle, err := bundleManager.Create(context.Background(),
6567
"testHost",
6668
"testRequestId",
@@ -93,7 +95,7 @@ func Test_Create(t *testing.T) {
9395
err := os.WriteFile(file, []byte(data), 0600)
9496
require.NoError(t, err)
9597

96-
var bundleManager = bundle.NewBundleManager(mockSnykCodeClient, mockInstrumentor, mockErrorReporter)
98+
var bundleManager = bundle.NewBundleManager(workflow.NewDefaultWorkFlowEngine(), mockSnykCodeClient, mockInstrumentor, mockErrorReporter)
9799
bundle, err := bundleManager.Create(context.Background(),
98100
"testHost",
99101
"testRequestId",
@@ -131,7 +133,7 @@ func Test_Create(t *testing.T) {
131133
)
132134
require.NoError(t, err)
133135

134-
var bundleManager = bundle.NewBundleManager(mockSnykCodeClient, mockInstrumentor, mockErrorReporter)
136+
var bundleManager = bundle.NewBundleManager(workflow.NewDefaultWorkFlowEngine(), mockSnykCodeClient, mockInstrumentor, mockErrorReporter)
135137
bundle, err := bundleManager.Create(context.Background(),
136138
"testHost",
137139
"testRequestId",
@@ -168,7 +170,7 @@ func Test_Create(t *testing.T) {
168170
},
169171
)
170172
require.NoError(t, err)
171-
var bundleManager = bundle.NewBundleManager(mockSnykCodeClient, mockInstrumentor, mockErrorReporter)
173+
var bundleManager = bundle.NewBundleManager(workflow.NewDefaultWorkFlowEngine(), mockSnykCodeClient, mockInstrumentor, mockErrorReporter)
172174
bundle, err := bundleManager.Create(context.Background(),
173175
"testHost",
174176
"testRequestId",
@@ -202,7 +204,7 @@ func Test_Create(t *testing.T) {
202204
err := os.WriteFile(file, []byte("some content so the file won't be skipped"), 0600)
203205
assert.Nil(t, err)
204206

205-
var bundleManager = bundle.NewBundleManager(mockSnykCodeClient, mockInstrumentor, mockErrorReporter)
207+
var bundleManager = bundle.NewBundleManager(workflow.NewDefaultWorkFlowEngine(), mockSnykCodeClient, mockInstrumentor, mockErrorReporter)
206208
bundle, err := bundleManager.Create(context.Background(),
207209
"testHost",
208210
"testRequestId",
@@ -251,7 +253,7 @@ func Test_Create(t *testing.T) {
251253
require.NoError(t, err)
252254
}
253255

254-
var bundleManager = bundle.NewBundleManager(mockSnykCodeClient, mockInstrumentor, mockErrorReporter)
256+
var bundleManager = bundle.NewBundleManager(workflow.NewDefaultWorkFlowEngine(), mockSnykCodeClient, mockInstrumentor, mockErrorReporter)
255257
bundle, err := bundleManager.Create(context.Background(),
256258
"testHost",
257259
"testRequestId",
@@ -271,6 +273,8 @@ func Test_Upload(t *testing.T) {
271273
_ = os.RemoveAll(temporaryDir)
272274
})
273275

276+
logger := zerolog.Nop()
277+
274278
t.Run("adds files to deepCodeBundle", func(t *testing.T) {
275279
ctrl := gomock.NewController(t)
276280
mockSpan := mocks.NewMockSpan(ctrl)
@@ -282,14 +286,14 @@ func Test_Upload(t *testing.T) {
282286
mockInstrumentor.EXPECT().Finish(gomock.Any()).Times(2)
283287
mockErrorReporter := mocks.NewMockErrorReporter(ctrl)
284288

285-
var bundleManager = bundle.NewBundleManager(mockSnykCodeClient, mockInstrumentor, mockErrorReporter)
289+
var bundleManager = bundle.NewBundleManager(workflow.NewDefaultWorkFlowEngine(), mockSnykCodeClient, mockInstrumentor, mockErrorReporter)
286290
documentURI, bundleFile := createTempFileInDir(t, "bundleDoc.java", 10, temporaryDir)
287291
bundleFileMap := map[string]deepcode2.BundleFile{}
288292
bundleFileMap[documentURI] = bundleFile
289293

290294
_, err := bundleManager.Upload(context.Background(),
291295
"testHost",
292-
bundle.NewBundle(mockSnykCodeClient, mockInstrumentor, mockErrorReporter, "bundleHash", "testRequestId", "", bundleFileMap, []string{}, []string{documentURI}),
296+
bundle.NewBundle(mockSnykCodeClient, mockInstrumentor, mockErrorReporter, &logger, "bundleHash", "testRequestId", "", bundleFileMap, []string{}, []string{documentURI}),
293297
bundleFileMap)
294298
assert.NoError(t, err)
295299
})
@@ -305,7 +309,7 @@ func Test_Upload(t *testing.T) {
305309
mockInstrumentor.EXPECT().StartSpan(gomock.Any(), gomock.Any()).Return(mockSpan).Times(2)
306310
mockInstrumentor.EXPECT().Finish(gomock.Any()).Times(2)
307311
mockErrorReporter := mocks.NewMockErrorReporter(ctrl)
308-
var bundleManager = bundle.NewBundleManager(mockSnykCodeClient, mockInstrumentor, mockErrorReporter)
312+
var bundleManager = bundle.NewBundleManager(workflow.NewDefaultWorkFlowEngine(), mockSnykCodeClient, mockInstrumentor, mockErrorReporter)
309313

310314
bundleFileMap := map[string]deepcode2.BundleFile{}
311315
var missingFiles []string
@@ -327,7 +331,7 @@ func Test_Upload(t *testing.T) {
327331

328332
_, err := bundleManager.Upload(context.Background(),
329333
"testHost",
330-
bundle.NewBundle(mockSnykCodeClient, mockInstrumentor, mockErrorReporter, "bundleHash", "testRequestId", "", bundleFileMap, []string{}, missingFiles),
334+
bundle.NewBundle(mockSnykCodeClient, mockInstrumentor, mockErrorReporter, &logger, "bundleHash", "testRequestId", "", bundleFileMap, []string{}, missingFiles),
331335
bundleFileMap)
332336
assert.Nil(t, err)
333337
})
@@ -349,7 +353,7 @@ func Test_IsSupported_Extensions(t *testing.T) {
349353
}, nil)
350354
mockInstrumentor := mocks.NewMockInstrumentor(ctrl)
351355
mockErrorReporter := mocks.NewMockErrorReporter(ctrl)
352-
bundler := bundle.NewBundleManager(mockSnykCodeClient, mockInstrumentor, mockErrorReporter)
356+
bundler := bundle.NewBundleManager(workflow.NewDefaultWorkFlowEngine(), mockSnykCodeClient, mockInstrumentor, mockErrorReporter)
353357

354358
t.Run("should return true for supported languages", func(t *testing.T) {
355359
supported, _ := bundler.IsSupported(context.Background(), "testHost", "C:\\some\\path\\Test.java")
@@ -388,7 +392,7 @@ func Test_IsSupported_ConfigFiles(t *testing.T) {
388392
}, nil)
389393
mockInstrumentor := mocks.NewMockInstrumentor(ctrl)
390394
mockErrorReporter := mocks.NewMockErrorReporter(ctrl)
391-
bundler := bundle.NewBundleManager(mockSnykCodeClient, mockInstrumentor, mockErrorReporter)
395+
bundler := bundle.NewBundleManager(workflow.NewDefaultWorkFlowEngine(), mockSnykCodeClient, mockInstrumentor, mockErrorReporter)
392396
dir, _ := os.Getwd()
393397

394398
t.Run("should return true for supported config files", func(t *testing.T) {

0 commit comments

Comments
 (0)