Skip to content

Commit

Permalink
feat: support o.OverrideOutputFormat(format)
Browse files Browse the repository at this point in the history
this new method creates a copy of the existing
printers.PrinterOptions in order to override
the given output without changing the original
printers.PrinterOptions.
  • Loading branch information
davidalpert committed Aug 4, 2024
1 parent ca2d5ba commit 17370f9
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
23 changes: 23 additions & 0 deletions v1/printer_options.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,29 @@ func (o *PrinterOptions) WithStreams(s IOStreams) *PrinterOptions {
return o
}

// OverrideOutputFormat returns a copy of the PrinterOptions with an overridden OutputFormat
func (o *PrinterOptions) OverrideOutputFormat(output string) *PrinterOptions {
o2 := PrinterOptions{
OutputFormat: output,
IOStreams: o.IOStreams,
}
if o.DefaultOutputFormat != nil {
o2.DefaultOutputFormat = StringPointer(*o.DefaultOutputFormat)
}
if o.TableCaption != nil {
o2.TableCaption = StringPointer(*o.TableCaption)
}
if o.TablePopulateFN != nil {
fn := *o.TablePopulateFN
o2.TablePopulateFN = &fn
}
if o.ItemsSelector != nil {
sel := *o.ItemsSelector
o2.ItemsSelector = &sel
}
return &o2
}

// WithDefaultOutput sets a default output format if one is not provided through a flag value
func (o *PrinterOptions) WithDefaultOutput(output string) *PrinterOptions {
o.DefaultOutputFormat = &output
Expand Down
43 changes: 43 additions & 0 deletions v1/v1_tests.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,5 +196,48 @@ var _ = Describe("go-printers", func() {
Ω(outBuf.String()).Should(Equal("stringed< the answer to the question is 42 >"))
})
})

Describe("overriding the output format", func() {
BeforeEach(func() {
o.OutputFormat = "json"
o.WithDefaultOutput("yaml")
})

It("without an override", func() {
testData := TestDataWithStringer{
TestData: TestData{
IntField: 42,
StringField: "the answer to the question",
},
}

// write via custom helpers
err := o.WriteOutput(testData)
Ω(err).Should(BeNil())

// read from the test buffer
Ω(outBuf.String()).Should(Equal(`{
"IntField": 42,
"StringField": "the answer to the question"
}
`))
})

It("with an override", func() {
testData := TestDataWithStringer{
TestData: TestData{
IntField: 42,
StringField: "the answer to the question",
},
}

// write via custom helpers
err := o.OverrideOutputFormat("text").WriteOutput(testData)
Ω(err).Should(BeNil())

// read from the test buffer
Ω(outBuf.String()).Should(Equal("stringed< the answer to the question is 42 >"))
})
})
})
})

0 comments on commit 17370f9

Please sign in to comment.