From e859ef136caea55cad86b7098d0b3f97da50fcc1 Mon Sep 17 00:00:00 2001 From: Matthew Rich Date: Wed, 17 Apr 2024 16:49:41 -0700 Subject: [PATCH] add io filter --- internal/iofilter/filter.go | 32 ++++++++++++++++++++ internal/iofilter/filter_test.go | 22 ++++++++++++++ internal/resource/schemas/package.jsonschema | 2 +- 3 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 internal/iofilter/filter.go create mode 100644 internal/iofilter/filter_test.go diff --git a/internal/iofilter/filter.go b/internal/iofilter/filter.go new file mode 100644 index 0000000..4316bb5 --- /dev/null +++ b/internal/iofilter/filter.go @@ -0,0 +1,32 @@ +// Copyright 2024 Matthew Rich . All rights reserved. + +package iofilter + +import ( + "io" + "log/slog" +) + +type ReadFilter func([]byte, int, error) (int, error) + +type Reader struct { + input io.Reader + filter ReadFilter +} + +func NewReader(reader io.Reader, filter ReadFilter) *Reader { + return &Reader{ + input: reader, + filter: filter, + } +} + +func (r *Reader) Read(p []byte) (n int, err error) { + n, err = r.input.Read(p) + if r.filter != nil { + return r.filter(p, n, err) + } else { + slog.Warn("iofilter.Reader.Read() - nil filter") + } + return n, err +} diff --git a/internal/iofilter/filter_test.go b/internal/iofilter/filter_test.go new file mode 100644 index 0000000..f1cf307 --- /dev/null +++ b/internal/iofilter/filter_test.go @@ -0,0 +1,22 @@ +// Copyright 2024 Matthew Rich . All rights reserved. + +package iofilter + +import ( + "github.com/stretchr/testify/assert" + "testing" + "strings" +) + +func TestNewReader(t *testing.T) { + buffer := make([]byte, 20) + reader := NewReader(strings.NewReader("testdata"), func(p []byte, in int, e error) (int, error) { + copy(p, []byte("foo")) + return 3, nil + }) + assert.NotNil(t, reader) + sz, e := reader.Read(buffer) + assert.Nil(t, e) + assert.Equal(t, 3, sz) + assert.Equal(t, "foo", string(buffer[:3])) +} diff --git a/internal/resource/schemas/package.jsonschema b/internal/resource/schemas/package.jsonschema index 72e0628..32ae8b6 100644 --- a/internal/resource/schemas/package.jsonschema +++ b/internal/resource/schemas/package.jsonschema @@ -12,7 +12,7 @@ "required": { "description": "version requirement", "type": "string", - "pattern": "^([><~=][=]?[a-zA-Z0-9+.-_]+|)$" + "pattern": "^(([><~]*=){0,1}[-_a-zA-Z0-9+.]+|)$" }, "version": { "type": "string"