import { migrateString } from "@kosko/migrate" ; import fs from "fs-extra" ; import getStdin from "get-stdin" ; import { join , resolve } from "path" ; import { Command , RootArguments } from "../cli/command" ; import Debug from "../cli/debug" ; import { print } from "../cli/print" ; const debug = Debug . extend ( "migrate" ) ; function concatFiles ( arr ) { if ( ! arr . length ) return "" ; let output = "" ; for ( const s of arr ) { if ( ! s . startsWith ( "---" ) ) output += "---\n" ; output += s + "\n" ; } return output ; } function readFileString ( path ) { debug ( "Reading file" , path ) ; return fs . readFile ( path , "utf8" ) ; } async function readFilesInDir ( dir ) { debug ( "Reading directory" , dir ) ; const files = await fs . readdir ( dir ) ; const contents = await Promise . all ( files . map ( ( file ) => readFileString ( join ( dir , file ) ) ) ) ; return concatFiles ( contents ) ; } function readFiles ( cwd , files ) { return Promise . all ( files . map ( async ( file ) => { if ( file === "-" ) { debug ( "Reading from stdin" ) ; return getStdin ( ) ; } const path = resolve ( cwd , file ) ; const stats = await fs . stat ( path ) ; return stats . isDirectory ( ) ? readFilesInDir ( path ) : readFileString ( path ) ; } ) ) ; } function toArray < T > ( input ) { return Array . isArray ( input ) ? input : [ input ] ; } export interface MigrateArguments extends RootArguments { filename : any ; } export const migrateCmd = { command : "migrate" , describe : "Migrate YAML into components" , builder ( argv ) { return ( argv . option ( "filename" , { type : "string" , describe : "File, directory to migrate" , required : true , alias : "f" } ) . example ( "$0 migrate -f path/to/file" , "Read from the path" ) . example ( "$0 migrate -f -" , "Read from stdin" ) ) ; } , async handler ( args ) { const file = concatFiles ( await readFiles ( args . cwd , toArray ( args . filename ) ) ) ; const content = await migrateString ( file ) ; await print ( content ) ; } } ;