import Debug from 'debug' ; import { basename , dirname } from 'path' ; import { Capabilities , i18n , MultiModalResponse , Arguments , Registrar , KResponse , ParsedOptions , Util } from '@kui-shell/core' ; import File from './File' ; import { contentTypeOf } from './open' ; import { fslice } from '../vfs/delegates' ; const strings = i18n ( 'plugin-bash-like' ) ; const debug = Debug ( 'plugins/bash-like/cmds/head' ) ; export interface HeadOptions extends ParsedOptions { n : number ; c : number ; } export function showResponseAsMMR ( filepath , data ) { const suffix = filepath . substring ( filepath . lastIndexOf ( '.' ) + 1 ) ; const enclosingDirectory = dirname ( filepath ) ; const packageName = enclosingDirectory === '.' ? undefined : enclosingDirectory ; const mode = { mode : 'view' , label : strings ( 'View' ) , contentType : contentTypeOf ( suffix ) , content : data } ; const response = { apiVersion : 'kui-shell/v1' , kind : 'File' , metadata : { name : basename ( filepath ) , namespace : packageName } , modes : [ mode ] , spec : { filepath , size : 0 , fullpath : Util . absolute ( Util . expandHomeDir ( filepath ) ) } } ; return response ; } async function head ( args ) { const { argvNoOptions , parsedOptions } = args ; const filepath = argvNoOptions [ argvNoOptions . indexOf ( 'head' ) + 1 ] ; debug ( 'head' , filepath ) ; if ( typeof filepath === 'number' && filepath < 0 ) { const newarg = `-n ${ filepath * - 1 }` ; return args . REPL . qexec ( args . command . replace ( filepath , newarg ) ) ; } else if ( typeof filepath === 'undefined' ) { throw new Error ( 'Missing input file' ) ; } try { const data = await fslice ( filepath , 0 , parsedOptions . c || parsedOptions . n || 10 , parsedOptions . c ? 'bytes' : 'lines' ) ; if ( Capabilities . isHeadless ( ) && ! Capabilities . inProxy ( ) ) { return data ; } else { return showResponseAsMMR ( filepath , data ) ; } } catch ( err ) { throw new Error ( `head: ${ err . message }` ) ; } } /**
 * Register command handlers
 *
 */ export default ( registrar ) => { registrar . listen ( '/head' , head , { requiresLocal : true } ) ; } ;