Create a readerValue for values that can implement the io.Reader interface

This commit is contained in:
Elara 2023-09-30 16:59:10 -07:00
parent 6272e5e044
commit 029dfab35f
2 changed files with 25 additions and 15 deletions

View File

@ -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)

View File

@ -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
}