use std::collections::BTreeSet;
use std::io::{IsTerminal, Write};
use serde_json::Value;
use crate::api::ApiError;
pub struct Stdout;
impl Write for Stdout {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
std::io::stdout()
.write(buf)
.or_else(|error| stdout_failed(error))
}
fn flush(&mut self) -> std::io::Result<()> {
std::io::stdout()
.flush()
.or_else(|error| stdout_failed(error))
}
}
fn stdout_failed(error: std::io::Error) -> ! {
if error.kind() == std::io::ErrorKind::BrokenPipe {
std::process::exit(0);
}
eprintln!("servicenow: failed to write to stdout: {error}");
std::process::exit(exit_codes::GENERAL);
}
#[macro_export]
macro_rules! out {
($($arg:tt)*) => {{
use ::std::io::Write as _;
let _ = ::std::write!($crate::output::Stdout, $($arg)*);
}};
}
#[macro_export]
macro_rules! outln {
($($arg:tt)*) => {{
use ::std::io::Write as _;
let _ = ::std::writeln!($crate::output::Stdout, $($arg)*);
}};
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OutputFormat {
Text,
Json,
JsonLines,
Yaml,
Csv,
}
#[derive(Clone, Copy, Debug)]
pub struct OutputConfig {
pub json: bool,
pub quiet: bool,
pub format: OutputFormat,
pub color: bool,
}
impl OutputConfig {
pub fn new(
output: &str,
json_alias: bool,
quiet: bool,
no_color: bool,
) -> Result<Self, ApiError> {
let format = match output {
"auto" if json_alias || !std::io::stdout().is_terminal() => OutputFormat::Json,
"auto" | "text" | "table" => OutputFormat::Text,
"json" => OutputFormat::Json,
"jsonl" | "ndjson" => OutputFormat::JsonLines,
"yaml" | "yml" => OutputFormat::Yaml,
"csv" => OutputFormat::Csv,
other => {
return Err(ApiError::InvalidInput(format!(
"invalid output format '{other}'; expected auto, table, text, json, jsonl, yaml, or csv"
)));
}
};
let interactive = format == OutputFormat::Text && std::io::stdout().is_terminal();
let color = interactive && !no_color && std::env::var_os("NO_COLOR").is_none();
Ok(Self {
json: format != OutputFormat::Text,
quiet,
format,
color,
})
}
pub fn value(&self, value: &Value) {
match self.format {
OutputFormat::Text | OutputFormat::Json => crate::outln!(
"{}",
serde_json::to_string_pretty(value).expect("JSON serialization cannot fail")
),
OutputFormat::JsonLines => print_json_lines(value),
OutputFormat::Yaml => crate::out!(
"{}",
serde_saphyr::to_string(value).expect("YAML serialization cannot fail")
),
OutputFormat::Csv => print_csv(value),
}
}
pub fn message(&self, message: &str) {
if !self.quiet {
eprintln!("{message}");
}
}
pub fn success(&self, message: &str) {
if self.quiet {
return;
}
if self.color {
eprintln!("\x1b[32m✓\x1b[0m {message}");
} else {
eprintln!("✓ {message}");
}
}
pub fn heading(&self, value: &str) -> String {
if self.color {
format!("\x1b[1;36m{value}\x1b[0m")
} else {
value.into()
}
}
}
fn print_json_lines(value: &Value) {
if let Some(records) = value.get("result").and_then(Value::as_array) {
for record in records {
crate::outln!(
"{}",
serde_json::to_string(record).expect("JSON serialization cannot fail")
);
}
} else {
crate::outln!(
"{}",
serde_json::to_string(value).expect("JSON serialization cannot fail")
);
}
}
fn print_csv(value: &Value) {
let owned;
let records = if let Some(records) = value.get("result").and_then(Value::as_array) {
records.as_slice()
} else if let Some(record) = value.get("result") {
owned = vec![record.clone()];
owned.as_slice()
} else {
owned = vec![value.clone()];
owned.as_slice()
};
if records.is_empty() {
return;
}
let headers: Vec<String> = records
.iter()
.filter_map(Value::as_object)
.flat_map(|record| record.keys().cloned())
.collect::<BTreeSet<_>>()
.into_iter()
.collect();
let mut writer = csv::Writer::from_writer(Stdout);
writer
.write_record(&headers)
.expect("Stdout handles write failures itself");
for record in records {
let row = headers
.iter()
.map(|header| record.get(header).map(csv_cell).unwrap_or_default());
writer
.write_record(row)
.expect("Stdout handles write failures itself");
}
writer
.flush()
.expect("Stdout handles write failures itself");
}
fn csv_cell(value: &Value) -> String {
match value {
Value::Null => String::new(),
Value::String(value) => value.clone(),
Value::Bool(value) => value.to_string(),
Value::Number(value) => value.to_string(),
Value::Object(value) => value
.get("display_value")
.and_then(Value::as_str)
.or_else(|| value.get("value").and_then(Value::as_str))
.map(str::to_string)
.unwrap_or_else(|| serde_json::to_string(value).unwrap_or_default()),
Value::Array(_) => serde_json::to_string(value).unwrap_or_default(),
}
}
pub mod exit_codes {
pub const GENERAL: i32 = 1;
pub const INPUT: i32 = 2;
pub const AUTH: i32 = 3;
pub const NOT_FOUND: i32 = 4;
pub const API: i32 = 5;
pub const RATE_LIMIT: i32 = 6;
pub const CONFLICT: i32 = 7;
pub const NOT_ORDERED: i32 = 8;
}
pub fn error_kind(error: &ApiError) -> &'static str {
match error {
ApiError::InvalidInput(_) => "invalid_input",
ApiError::Auth(_) => "auth",
ApiError::Permission(_) => "permission",
ApiError::NotFound(_) => "not_found",
ApiError::Conflict(_) => "conflict",
ApiError::NotOrdered { .. } => "not_ordered",
ApiError::RateLimit => "rate_limit",
ApiError::Api { .. } => "api_error",
ApiError::Http(_) | ApiError::Other(_) => "unexpected_error",
}
}
pub fn exit_code(error: &ApiError) -> i32 {
match error {
ApiError::InvalidInput(_) => exit_codes::INPUT,
ApiError::Auth(_) | ApiError::Permission(_) => exit_codes::AUTH,
ApiError::NotFound(_) => exit_codes::NOT_FOUND,
ApiError::Conflict(_) => exit_codes::CONFLICT,
ApiError::NotOrdered { .. } => exit_codes::NOT_ORDERED,
ApiError::RateLimit => exit_codes::RATE_LIMIT,
ApiError::Api { .. } => exit_codes::API,
ApiError::Http(_) | ApiError::Other(_) => exit_codes::GENERAL,
}
}
pub fn print_error(error: &ApiError, machine_readable: bool) {
let remediation = error_remediation(error);
if machine_readable {
let mut body = serde_json::json!({
"kind": error_kind(error),
"message": error.to_string(),
"remediation": remediation,
});
if let ApiError::NotOrdered { cart_id, .. } = error {
body["cart"] = serde_json::json!({ "sys_id": cart_id });
}
eprintln!("{}", serde_json::json!({ "error": body }));
} else {
eprintln!("error: {error}");
if let Some(remediation) = remediation {
eprintln!("\nTry: {remediation}");
}
}
}
fn error_remediation(error: &ApiError) -> Option<&'static str> {
let message = error.to_string();
if message.contains("No ServiceNow instance configured")
|| message.contains("No username configured")
|| message.contains("No credential configured")
|| message.contains("No password configured")
|| message.contains("No browser session configured")
|| message.contains("No access token configured")
{
Some("run `servicenow init` to connect an instance securely")
} else if matches!(error, ApiError::Auth(_))
&& message.contains("appears to use")
&& message.contains("SSO")
{
Some("retry with `servicenow init --method browser`; no OAuth application is required")
} else {
match error {
ApiError::Auth(_) if message.contains("browser session") => {
Some("run `servicenow auth login --method browser` to sign in again")
}
ApiError::Auth(_) => Some("run `servicenow auth login` to refresh your credentials"),
ApiError::Permission(_) => Some(
"your credentials work, but this account lacks the role or ACL the operation needs; ask a ServiceNow administrator, or use an account that has it",
),
ApiError::NotOrdered { .. } => Some(
"see what your cart holds with `servicenow catalog cart show`, then order it with `servicenow catalog cart submit` or empty it with `servicenow catalog cart clear`; do not retry the order, because every attempt adds another cart item; if the portal shows a cart of its own, submit the item from one cart only, since each submitted copy is a separate order",
),
ApiError::RateLimit => Some("wait briefly, then retry the command"),
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn output_aliases_are_stable() {
assert_eq!(
OutputConfig::new("table", false, false, true)
.unwrap()
.format,
OutputFormat::Text
);
assert_eq!(
OutputConfig::new("ndjson", false, false, true)
.unwrap()
.format,
OutputFormat::JsonLines
);
assert!(OutputConfig::new("xml", false, false, true).is_err());
}
#[test]
fn expired_browser_sessions_have_a_specific_safe_recovery() {
let error = ApiError::Auth(
"browser session expired or was rejected: User is not authenticated".into(),
);
assert_eq!(
error_remediation(&error),
Some("run `servicenow auth login --method browser` to sign in again")
);
}
}