use unilang::data::{ ErrorCode, ErrorData };
use unilang::semantic::VerifiedCommand;
use unilang::types::Value;
#[ derive( Debug, Clone, Copy, PartialEq ) ]
pub enum OutputFormat
{
Text,
Json,
}
#[ derive( Debug ) ]
pub struct OutputOptions
{
pub verbosity : u8,
pub format : OutputFormat,
}
impl OutputOptions
{
#[ inline ]
pub fn from_cmd( cmd : &VerifiedCommand ) -> Result< Self, ErrorData >
{
let verbosity = match cmd.arguments.get( "verbosity" )
{
Some( Value::Integer( n ) ) => u8::try_from( *n ).unwrap_or( 1 ),
_ => 1,
};
let format = match cmd.arguments.get( "format" )
{
Some( Value::String( s ) ) =>
{
match s.as_str()
{
"text" => OutputFormat::Text,
"json" => OutputFormat::Json,
other =>
{
return Err( ErrorData::new(
ErrorCode::ArgumentTypeMismatch,
format!( "unknown format '{other}': expected text or json" ),
) );
}
}
}
_ => OutputFormat::Text,
};
Ok( OutputOptions { verbosity, format } )
}
}
#[ inline ]
#[ must_use ]
pub fn json_escape( s : &str ) -> String
{
let mut out = String::with_capacity( s.len() );
for ch in s.chars()
{
match ch
{
'"' => out.push_str( "\\\"" ),
'\\' => out.push_str( "\\\\" ),
'\n' => out.push_str( "\\n" ),
'\r' => out.push_str( "\\r" ),
'\t' => out.push_str( "\\t" ),
c => out.push( c ),
}
}
out
}