import { readFile , stat } from 'fs' ; import { Arguments , ParsedOptions , CodedError , Util } from '@kui-shell/core' ; export interface FStat { viewer : string ; filepath : string ; fullpath : string ; isDirectory : boolean ; isExecutable ? : boolean ; size : number ; data ? : string ; } export interface FStatOptions extends ParsedOptions { 'enoent-ok' : boolean ; 'with-data' : boolean ; } function readData ( fullpath ) { return new Promise ( ( resolve , reject ) => { readFile ( fullpath , ( err , data ) => { if ( err ) { reject ( err ) ; } else { resolve ( data . toString ( ) ) ; } } ) ; } ) ; } /**
 * Kui command for fs.stat
 *
 */ export const fstat = ( { argvNoOptions , parsedOptions } ) => { const filepath = argvNoOptions [ 1 ] ; const viewer = 'open' ; const fullpath = Util . expandHomeDir ( filepath ) ; const prettyFullPath = fullpath . replace ( new RegExp ( `^${ process . env . HOME }` ) , '~' ) ; return new Promise < FStat > ( ( resolve , reject ) => { const handleError = ( err ) => { if ( err . code === 'ENOENT' ) { if ( parsedOptions [ 'enoent-ok' ] ) { resolve ( { viewer , filepath , fullpath : prettyFullPath , isDirectory : false , size : 0 , data : '' } ) ; } const error = new Error ( err . message ) ; error . stack = err . stack ; error . code = 404 ; reject ( error ) ; } else { reject ( err ) ; } } ; stat ( fullpath , async ( err , stats ) => { if ( err ) { handleError ( err ) ; } else { resolve ( { viewer , filepath , fullpath : prettyFullPath , isDirectory : stats . isDirectory ( ) , size : stats . size , data : ! stats . isDirectory ( ) && parsedOptions [ 'with-data' ] && ! filepath . endsWith ( '.gz' ) && stats . size < 10 * 1024 * 1024 ? await readData ( fullpath ) : '' } ) ; } } ) ; } ) ; } ;