Skip to content

Commit afdba1f

Browse files
andreyneringdnaeon
authored andcommitted
feat: add WithEncodeOption to tweak yaml marshalling
1 parent da150ef commit afdba1f

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

pkg/cassette/cassette.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -396,6 +396,9 @@ type Cassette struct {
396396
IsNew bool `yaml:"-"`
397397

398398
nextInteractionId int `yaml:"-"`
399+
400+
// EncodeOptions is an optional list of YAML encoder options.
401+
EncodeOptions []yaml.EncodeOption `yaml:"-"`
399402
}
400403

401404
// New creates a new empty cassette
@@ -502,10 +505,12 @@ func (c *Cassette) SaveWithFS(fs FS) error {
502505
c.Interactions = interactions
503506

504507
// Marshal to YAML and save interactions
505-
data, err := yaml.Marshal(c)
506-
if err != nil {
508+
var buff bytes.Buffer
509+
enc := yaml.NewEncoder(&buff, c.EncodeOptions...)
510+
if err := enc.Encode(c); err != nil {
507511
return err
508512
}
513+
data := buff.Bytes()
509514

510515
// Honor the YAML structure specification
511516
// http://www.yaml.org/spec/1.2/spec.html#id2760395

pkg/recorder/recorder.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import (
3535
"net/http/httputil"
3636
"time"
3737

38+
"github.com/goccy/go-yaml"
3839
"gopkg.in/dnaeon/go-vcr.v4/pkg/cassette"
3940
)
4041

@@ -209,6 +210,8 @@ type Recorder struct {
209210

210211
// fs specifies custom filesystem ([cassette.FS]) implementation.
211212
fs cassette.FS
213+
214+
encodeOptions []yaml.EncodeOption
212215
}
213216

214217
// Option is a function which configures the [Recorder].
@@ -313,6 +316,15 @@ func WithFS(fs cassette.FS) Option {
313316
return opt
314317
}
315318

319+
// WithEncodeOptions is an [Option], which configures the [Recorder] to use
320+
// custom YAML encoder options. This allows customization of the YAML encoding
321+
// process, such as setting string literal style, etc.
322+
func WithEncodeOptions(encodeOptions ...yaml.EncodeOption) Option {
323+
return func(r *Recorder) {
324+
r.encodeOptions = encodeOptions
325+
}
326+
}
327+
316328
// New creates a new [Recorder] and configures it using the provided options.
317329
func New(cassetteName string, opts ...Option) (*Recorder, error) {
318330
r := &Recorder{
@@ -340,6 +352,7 @@ func New(cassetteName string, opts ...Option) (*Recorder, error) {
340352
r.cassette = c
341353
r.cassette.Matcher = r.matcher
342354
r.cassette.ReplayableInteractions = r.replayableInteractions
355+
r.cassette.EncodeOptions = r.encodeOptions
343356

344357
return r, nil
345358
}

0 commit comments

Comments
 (0)