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 package builtins
import ( import (
"io"
"strings"
"github.com/PuerkitoBio/goquery" "github.com/PuerkitoBio/goquery"
"go.starlark.net/starlark" "go.starlark.net/starlark"
"go.starlark.net/starlarkstruct" "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) { func htmlParse(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var val starlark.Value var r readerValue
err := starlark.UnpackArgs("html.selection.find", args, kwargs, "from", &val) err := starlark.UnpackArgs("html.selection.find", args, kwargs, "from", &r)
if err != nil { if err != nil {
return nil, err 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() defer r.Close()
doc, err := goquery.NewDocumentFromReader(r) doc, err := goquery.NewDocumentFromReader(r)

View File

@ -3,7 +3,9 @@ package builtins
import ( import (
"bufio" "bufio"
"encoding/json" "encoding/json"
"errors"
"io" "io"
"strings"
"github.com/vmihailenco/msgpack/v5" "github.com/vmihailenco/msgpack/v5"
"go.elara.ws/lure-updater/internal/convert" "go.elara.ws/lure-updater/internal/convert"
@ -213,3 +215,24 @@ func (sr starlarkReader) Close() error {
} }
return nil 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
}