diff --git a/v1/printer_options.go b/v1/printer_options.go index 384f1f9..9c18255 100644 --- a/v1/printer_options.go +++ b/v1/printer_options.go @@ -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 diff --git a/v1/v1_tests.go b/v1/v1_tests.go index ba298da..80868fa 100644 --- a/v1/v1_tests.go +++ b/v1/v1_tests.go @@ -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 >")) + }) + }) }) })