import yaml from "js-yaml" ; import { Result } from "./base" ; export interface Writer { write ( data ) : void ; } export enum PrintFormat { YAML = "yaml" , JSON = "json" } export interface PrintOptions { format : PrintFormat ; writer : Writer ; } type Printer < T > = ( writer : Writer , data : T ) => void ; type PrinterMap < T > = { [ key in PrintFormat ] : Printer < T > ; } ; function stringifyYAML ( data ) { return yaml . dump ( data , { noRefs : true } ) ; } function stringifyJSON ( data ) { return JSON . stringify ( data , null , "  " ) ; } const printers = { [ PrintFormat . YAML ] ( writer , data ) { writer . write ( stringifyYAML ( data ) ) ; } , [ PrintFormat . JSON ] ( writer , data ) { writer . write ( stringifyJSON ( data ) ) ; } } ; const arrPrinters = { [ PrintFormat . YAML ] ( writer , data ) { for ( const item of data ) { writer . write ( "---\n" + stringifyYAML ( item ) ) ; } } , [ PrintFormat . JSON ] ( writer , data ) { const list = { apiVersion : "v1" , kind : "List" , items : data } ; writer . write ( stringifyJSON ( list ) ) ; } } ; param result param options export function print ( result , { format , writer } ) { const data = result . manifests . map ( ( manifest ) => manifest . data ) ; if ( ! data . length ) return ; if ( data . length > 1 ) { arrPrinters [ format ] ( writer , data ) ; } else { printers [ format ] ( writer , data [ 0 ] ) ; } }