From 029dfab35f99889bc2559ca02b7cce500c185c26 Mon Sep 17 00:00:00 2001 From: Elara Musayelyan Date: Sat, 30 Sep 2023 16:59:10 -0700 Subject: [PATCH] Create a readerValue for values that can implement the io.Reader interface --- internal/builtins/html.go | 17 ++--------------- internal/builtins/reader.go | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+), 15 deletions(-) diff --git a/internal/builtins/html.go b/internal/builtins/html.go index efcfaea..47e8db3 100644 --- a/internal/builtins/html.go +++ b/internal/builtins/html.go @@ -1,9 +1,6 @@ package builtins import ( - "io" - "strings" - "github.com/PuerkitoBio/goquery" "go.starlark.net/starlark" "go.starlark.net/starlarkstruct" @@ -24,21 +21,11 @@ var htmlModule = &starlarkstruct.Module{ } func htmlParse(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { - var val starlark.Value - err := starlark.UnpackArgs("html.selection.find", args, kwargs, "from", &val) + var r readerValue + err := starlark.UnpackArgs("html.selection.find", args, kwargs, "from", &r) if err != nil { return nil, err } - - var r io.ReadCloser - switch val := val.(type) { - case starlark.String: - r = io.NopCloser(strings.NewReader(string(val))) - case starlark.Bytes: - r = io.NopCloser(strings.NewReader(string(val))) - case starlarkReader: - r = val - } defer r.Close() doc, err := goquery.NewDocumentFromReader(r) diff --git a/internal/builtins/reader.go b/internal/builtins/reader.go index e07ccf5..b72602f 100644 --- a/internal/builtins/reader.go +++ b/internal/builtins/reader.go @@ -3,7 +3,9 @@ package builtins import ( "bufio" "encoding/json" + "errors" "io" + "strings" "github.com/vmihailenco/msgpack/v5" "go.elara.ws/lure-updater/internal/convert" @@ -213,3 +215,24 @@ func (sr starlarkReader) Close() error { } return nil } + +type readerValue struct { + io.ReadCloser +} + +func (rv *readerValue) Unpack(v starlark.Value) error { + switch val := v.(type) { + case starlark.String: + rv.ReadCloser = io.NopCloser(strings.NewReader(string(val))) + case starlark.Bytes: + rv.ReadCloser = io.NopCloser(strings.NewReader(string(val))) + case starlarkReader: + rv.ReadCloser = val + } + + if rv.ReadCloser == nil { + return errors.New("invalid type for reader") + } + + return nil +}