feat: json importer

This commit is contained in:
abelith committed 2026-08-21 15:48:02 +05:00
1 parent 69af7eaee3
commit c41d13bb77
3 files changed
+40

No files matched your search

+33
View File
@@ -4,16 +4,20 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"github.com/abelith/spellbook/internal/adapters/exporter" "github.com/abelith/spellbook/internal/adapters/exporter"
"github.com/abelith/spellbook/internal/adapters/importer"
"github.com/abelith/spellbook/internal/models" "github.com/abelith/spellbook/internal/models"
"io" "io"
) )
func init() { func init() {
exporter.Register("jsonl", &JsonlExporter{}) exporter.Register("jsonl", &JsonlExporter{})
importer.Register("jsonl", &JsonlImporter{})
} }
type JsonlExporter struct{} type JsonlExporter struct{}
type JsonlImporter struct{}
func (je *JsonlExporter) Export(ctx context.Context, ch <-chan models.Spell, w io.Writer) error { func (je *JsonlExporter) Export(ctx context.Context, ch <-chan models.Spell, w io.Writer) error {
encoder := json.NewEncoder(w) encoder := json.NewEncoder(w)
@@ -32,3 +36,32 @@ func (je *JsonlExporter) Export(ctx context.Context, ch <-chan models.Spell, w i
} }
} }
} }
func (ji JsonlImporter) Import(ctx context.Context, r io.Reader) (<-chan models.Spell, <-chan error, error) {
ch := make(chan models.Spell, 1)
errCh := make(chan error, 1)
dec := json.NewDecoder(r)
go func() {
defer close(ch)
defer close(errCh)
for dec.More() {
var spell models.Spell
if err := dec.Decode(&spell); err != nil {
errCh <- err
return
}
select {
case <-ctx.Done():
errCh <- ctx.Err()
return
case ch <- spell:
}
}
}()
return ch, errCh, nil
}
+5
View File
@@ -100,12 +100,17 @@ func (a *Application) ImportSpells(
name string, name string,
r io.Reader, r io.Reader,
) error { ) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
ch, errCh, err := importer.Import(ctx, name, r) ch, errCh, err := importer.Import(ctx, name, r)
if err != nil { if err != nil {
cancel()
return err return err
} }
if err := a.spellCmd.Import(ctx, ch); err != nil { if err := a.spellCmd.Import(ctx, ch); err != nil {
cancel()
return err return err
} }
+2
View File
@@ -14,6 +14,8 @@ var reservedCommands = map[string]struct{}{
"help": {}, "help": {},
"completion": {}, "completion": {},
"search": {}, "search": {},
"export": {},
"import": {},
} }
func NewAddCommand(app Application) *cobra.Command { func NewAddCommand(app Application) *cobra.Command {