use std::collections::BTreeSet;
use std::io::{IsTerminal, Read, Write};
use clap::{ArgGroup, CommandFactory, Parser, Subcommand};
use clap_complete::Shell;
use dialoguer::{Confirm, Editor, Input, Password, Select};
use serde_json::{Map, Value};
use servicenow_cli::api::{ApiError, DisplayValue, ListOptions, ServiceNowClient};
use servicenow_cli::attachment;
use servicenow_cli::catalog::{self, CatalogItem};
use servicenow_cli::commands::{
INCIDENT_HUMAN_FIELDS, INCIDENT_LIST_FIELDS, build_body, parse_fields, print_record,
print_records, print_records_or, record_sys_id,
};
use servicenow_cli::config::{
AuthType, Config, ProfileConfig, active_profile_name, config_path, delete_stored_credential,
init_document, profile_defaults, profile_summaries, remove_profile, save_profile, use_profile,
};
use servicenow_cli::credentials::{self, StoredCredential};
use servicenow_cli::incident;
use servicenow_cli::metadata::{self, ReferenceKind};
use servicenow_cli::output::{self, OutputConfig, OutputFormat, exit_code, print_error};
use servicenow_cli::record;
use servicenow_cli::{out, outln};
#[derive(Parser)]
#[command(
name = "servicenow",
version,
about = "Fast, safe, human-friendly ServiceNow operations from the terminal",
arg_required_else_help = true,
after_help = "Get started:\n servicenow init Configure and sign in\n servicenow doctor Check configuration and instance access\n servicenow incidents mine See what needs your attention\n servicenow schema --command 'incidents list'\n Inspect one command for automation"
)]
struct Cli {
#[arg(long, env = "SERVICENOW_INSTANCE")]
instance: Option<String>,
#[arg(long, env = "SERVICENOW_USERNAME")]
username: Option<String>,
#[arg(long, env = "SERVICENOW_PROFILE", global = true)]
profile: Option<String>,
#[arg(short, long, global = true, default_value = "auto")]
output: String,
#[arg(long, global = true, hide = true)]
json: bool,
#[arg(long, global = true)]
quiet: bool,
#[arg(
short,
long,
global = true,
env = "SERVICENOW_VERBOSE",
conflicts_with = "quiet"
)]
verbose: bool,
#[arg(long, global = true)]
no_color: bool,
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
#[command(alias = "setup")]
Init {
#[arg(value_name = "PROFILE", hide = true)]
legacy_profile: Option<String>,
#[arg(long)]
instance: Option<String>,
#[arg(long, value_enum)]
method: Option<AuthType>,
#[arg(long)]
username: Option<String>,
#[arg(long)]
client_id: Option<String>,
#[arg(long)]
scope: Option<String>,
#[arg(long)]
redirect_uri: Option<String>,
#[arg(long)]
secret_stdin: bool,
#[arg(long)]
insecure_storage: bool,
#[arg(long)]
no_browser: bool,
#[arg(long)]
read_only: bool,
},
#[command(subcommand)]
Auth(AuthCommand),
#[command(subcommand, visible_alias = "profiles")]
Profile(ProfileCommand),
Tui {
#[arg(default_value = "incident")]
table: String,
#[arg(short, long)]
query: Option<String>,
#[arg(long, default_value = "25", value_parser = parse_tui_page_size)]
page_size: usize,
},
#[command(subcommand, visible_alias = "incident")]
Incidents(IncidentsCommand),
#[command(subcommand, visible_alias = "attachment")]
Attachments(AttachmentsCommand),
#[command(subcommand, visible_alias = "cat")]
Catalog(CatalogCommand),
#[command(subcommand, visible_alias = "table")]
Tables(TablesCommand),
#[command(subcommand)]
Config(ConfigCommand),
Doctor {
#[arg(long)]
offline: bool,
},
Schema {
table: Option<String>,
#[arg(long, conflicts_with = "table")]
command: Option<String>,
#[arg(long)]
refresh: bool,
},
Choices {
table: String,
field: String,
#[arg(long)]
refresh: bool,
},
Resolve {
#[arg(value_enum)]
kind: ReferenceKind,
value: String,
},
Completions {
shell: Shell,
},
}
#[derive(Subcommand)]
enum AuthCommand {
Login {
#[arg(value_name = "PROFILE", hide = true)]
legacy_profile: Option<String>,
#[arg(long)]
instance: Option<String>,
#[arg(long, value_enum)]
method: Option<AuthType>,
#[arg(long)]
username: Option<String>,
#[arg(long)]
client_id: Option<String>,
#[arg(long)]
scope: Option<String>,
#[arg(long)]
redirect_uri: Option<String>,
#[arg(long)]
secret_stdin: bool,
#[arg(long)]
insecure_storage: bool,
#[arg(long)]
no_browser: bool,
#[arg(long)]
read_only: bool,
},
Logout {
#[arg(value_name = "PROFILE", hide = true)]
legacy_profile: Option<String>,
},
Status {
#[arg(long)]
offline: bool,
},
}
#[derive(Subcommand)]
enum ProfileCommand {
List,
Use { name: String },
Remove {
name: String,
#[arg(long)]
yes: bool,
},
}
#[derive(Subcommand)]
enum IncidentsCommand {
List {
#[arg(short, long)]
query: Option<String>,
#[arg(long)]
active: bool,
#[arg(short = 'n', long, default_value = "50")]
limit: usize,
#[arg(long, default_value = "0")]
offset: usize,
#[arg(long)]
all: bool,
#[arg(long)]
fields: Option<String>,
#[arg(long, value_enum)]
display_value: Option<DisplayValue>,
},
Mine {
#[arg(short, long)]
query: Option<String>,
#[arg(short = 'n', long, default_value = "50")]
limit: usize,
#[arg(long)]
all: bool,
#[arg(long, value_enum)]
display_value: Option<DisplayValue>,
},
Show {
identifier: String,
#[arg(long)]
fields: Option<String>,
#[arg(long, value_enum, default_value = "all")]
display_value: DisplayValue,
},
Create {
#[arg(short, long)]
short_description: String,
#[arg(short, long)]
description: Option<String>,
#[arg(long)]
category: Option<String>,
#[arg(long)]
impact: Option<String>,
#[arg(long)]
urgency: Option<String>,
#[arg(long)]
assignment_group: Option<String>,
#[arg(long)]
assignee: Option<String>,
#[arg(long = "field")]
fields: Vec<String>,
},
Update {
identifier: String,
#[arg(long)]
short_description: Option<String>,
#[arg(long)]
description: Option<String>,
#[arg(long)]
state: Option<String>,
#[arg(long)]
assignee: Option<String>,
#[arg(long)]
work_notes: Option<String>,
#[arg(long = "field")]
fields: Vec<String>,
},
#[command(group(
ArgGroup::new("resolution_notes")
.required(true)
.multiple(false)
.args(["notes", "notes_file"])
))]
Resolve {
identifier: String,
#[arg(long)]
code: String,
#[arg(long)]
notes: Option<String>,
#[arg(long, value_name = "PATH")]
notes_file: Option<std::path::PathBuf>,
#[arg(long)]
state: Option<String>,
#[arg(long = "field")]
fields: Vec<String>,
#[arg(long)]
refresh: bool,
#[arg(long)]
dry_run: bool,
},
Edit {
identifier: String,
#[arg(long)]
file: Option<std::path::PathBuf>,
#[arg(long)]
dry_run: bool,
#[arg(long)]
yes: bool,
},
Note {
identifier: String,
text: Option<String>,
#[arg(long)]
file: Option<std::path::PathBuf>,
#[arg(long)]
dry_run: bool,
},
Assign {
identifier: String,
#[arg(long = "to")]
assignee: Option<String>,
#[arg(long)]
group: Option<String>,
#[arg(long)]
dry_run: bool,
},
Open {
identifier: String,
#[arg(long)]
print: bool,
},
Watch {
identifier: String,
#[arg(long, default_value = "5")]
interval: u64,
#[arg(long)]
count: Option<usize>,
#[arg(long)]
fields: Option<String>,
},
}
#[derive(Subcommand)]
enum AttachmentsCommand {
List {
table: String,
record: String,
#[arg(short = 'n', long, default_value = "100")]
limit: usize,
#[arg(long)]
all: bool,
},
Upload {
table: String,
record: String,
file: std::path::PathBuf,
#[arg(long)]
name: Option<String>,
#[arg(long)]
content_type: Option<String>,
#[arg(long)]
dry_run: bool,
},
Download {
attachment: String,
destination: Option<std::path::PathBuf>,
#[arg(long)]
force: bool,
},
Delete {
attachment: String,
#[arg(long)]
yes: bool,
#[arg(long)]
dry_run: bool,
},
}
#[derive(Subcommand)]
enum CatalogCommand {
Search {
text: Option<String>,
#[arg(short = 'n', long, default_value = "20")]
limit: usize,
#[arg(long, default_value = "0")]
offset: usize,
},
Show {
item: String,
},
#[command(
after_help = "The instance accepts invalid choices, references to the wrong table, and unknown\nvariable names without complaint, so the CLI validates every value first.\nSensitive values belong in --vars-file, not --var. --vars-file - reads them from\nstandard input, which then cannot answer the confirmation prompt: add --yes."
)]
Order {
item: String,
#[arg(long = "var", value_name = "NAME=VALUE")]
vars: Vec<String>,
#[arg(long, value_name = "PATH")]
vars_file: Option<std::path::PathBuf>,
#[arg(long, default_value = "1")]
quantity: u32,
#[arg(long)]
requested_for: Option<String>,
#[arg(long)]
allow_unknown_vars: bool,
#[arg(long)]
allow_unverified_formats: bool,
#[arg(long)]
checkout: bool,
#[arg(long)]
dry_run: bool,
#[arg(long)]
yes: bool,
},
#[command(subcommand)]
Cart(CatalogCartCommand),
#[command(subcommand, visible_alias = "request")]
Requests(CatalogRequestsCommand),
}
#[derive(Subcommand)]
enum CatalogCartCommand {
#[command(
after_help = "Reading the cart makes the instance create an empty one when you have none."
)]
Show,
#[command(
after_help = "The cart is submitted as it is when the instance receives the request, so\nitems added in the portal after the confirmation are ordered too."
)]
Submit {
#[arg(long)]
yes: bool,
},
Remove {
cart_item_id: String,
#[arg(long)]
yes: bool,
},
Clear {
#[arg(long)]
yes: bool,
},
}
#[derive(Subcommand)]
enum CatalogRequestsCommand {
Mine {
#[arg(short = 'n', long, default_value = "20")]
limit: usize,
#[arg(long)]
open: bool,
#[arg(long, value_enum)]
display_value: Option<DisplayValue>,
},
Vars {
identifier: String,
#[arg(long)]
include_empty: bool,
},
}
#[derive(Subcommand)]
enum TablesCommand {
List {
table: String,
#[arg(short, long)]
query: Option<String>,
#[arg(long)]
fields: Option<String>,
#[arg(short = 'n', long, default_value = "50")]
limit: usize,
#[arg(long, default_value = "0")]
offset: usize,
#[arg(long)]
all: bool,
#[arg(long, value_enum, default_value = "false")]
display_value: DisplayValue,
},
Get {
table: String,
sys_id: String,
#[arg(long)]
fields: Option<String>,
#[arg(long, value_enum, default_value = "all")]
display_value: DisplayValue,
},
Create {
table: String,
#[arg(long)]
data: Option<String>,
#[arg(long = "field")]
fields: Vec<String>,
},
Update {
table: String,
sys_id: String,
#[arg(long)]
data: Option<String>,
#[arg(long = "field")]
fields: Vec<String>,
},
Delete {
table: String,
sys_id: String,
#[arg(long)]
yes: bool,
},
}
#[derive(Subcommand)]
enum ConfigCommand {
Show,
Init,
Path,
}
fn parse_tui_page_size(value: &str) -> Result<usize, String> {
let page_size = value
.parse::<usize>()
.map_err(|_| "page size must be a whole number".to_string())?;
if (5..=200).contains(&page_size) {
Ok(page_size)
} else {
Err("page size must be between 5 and 200".into())
}
}
fn machine_readable_errors(output: &str, json_alias: bool) -> bool {
match output {
"json" | "jsonl" | "ndjson" | "yaml" | "yml" | "csv" => true,
"text" | "table" => false,
_ => json_alias || !std::io::stdout().is_terminal(),
}
}
fn raw_output_flags(args: &[std::ffi::OsString]) -> (String, bool) {
let mut output = String::from("auto");
let mut json_alias = false;
let mut iter = args.iter().skip(1).map(|arg| arg.to_string_lossy());
while let Some(arg) = iter.next() {
if arg == "--" {
break;
} else if arg == "--json" {
json_alias = true;
} else if arg == "--output" || arg == "-o" {
if let Some(value) = iter.next() {
output = value.into_owned();
}
} else if let Some(value) = arg.strip_prefix("--output=") {
output = value.to_string();
} else if let Some(value) = arg.strip_prefix("-o") {
output = value.strip_prefix('=').unwrap_or(value).to_string();
}
}
(output, json_alias)
}
#[tokio::main]
async fn main() {
let args: Vec<std::ffi::OsString> = std::env::args_os().collect();
let cli = match Cli::try_parse_from(&args) {
Ok(cli) => cli,
Err(error) => {
let (output, json_alias) = raw_output_flags(&args);
if !error.use_stderr() || !machine_readable_errors(&output, json_alias) {
error.exit();
}
let parse_error = ApiError::InvalidInput(error.to_string().trim_end().to_string());
print_error(&parse_error, true);
std::process::exit(exit_code(&parse_error));
}
};
let machine_errors = machine_readable_errors(&cli.output, cli.json);
if let Err(error) = run(cli).await {
print_error(&error, machine_errors);
std::process::exit(exit_code(&error));
}
}
async fn run(cli: Cli) -> Result<(), ApiError> {
let output = OutputConfig::new(&cli.output, cli.json, cli.quiet, cli.no_color)?;
let verbose = cli.verbose;
let profile_override = cli.profile.clone();
match cli.command {
Command::Init {
legacy_profile,
instance,
method,
username,
client_id,
scope,
redirect_uri,
secret_stdin,
insecure_storage,
no_browser,
read_only,
} => {
let profile = selected_profile(profile_override.as_deref(), legacy_profile)?
.unwrap_or_else(|| "default".into());
let authenticated = run_auth_login(
&output,
profile,
instance,
method,
username,
client_id,
scope,
redirect_uri,
secret_stdin,
insecure_storage,
no_browser,
read_only,
verbose,
)
.await?;
if authenticated && !output.json {
outln!("\nNext\n servicenow doctor\n servicenow incidents mine");
}
return Ok(());
}
Command::Auth(AuthCommand::Login {
legacy_profile,
instance,
method,
username,
client_id,
scope,
redirect_uri,
secret_stdin,
insecure_storage,
no_browser,
read_only,
}) => {
let profile = selected_profile(profile_override.as_deref(), legacy_profile)?
.unwrap_or_else(|| "default".into());
run_auth_login(
&output,
profile,
instance,
method,
username,
client_id,
scope,
redirect_uri,
secret_stdin,
insecure_storage,
no_browser,
read_only,
verbose,
)
.await?;
return Ok(());
}
Command::Auth(AuthCommand::Logout { legacy_profile }) => {
let profile = match selected_profile(profile_override.as_deref(), legacy_profile)? {
Some(profile) => profile,
None => active_profile_name()?,
};
let removed = delete_stored_credential(&profile)?;
let value = serde_json::json!({
"profile": profile,
"loggedOut": removed,
});
if output.json {
output.value(&value);
} else if removed {
outln!("Logged out of profile {profile}.");
} else {
outln!("Profile {profile} had no stored credential.");
}
return Ok(());
}
Command::Profile(ProfileCommand::List) => {
let profiles = profile_summaries()?;
if output.json {
output.value(&serde_json::json!({"result": profiles}));
} else {
let records = profiles
.into_iter()
.map(serde_json::to_value)
.collect::<Result<Vec<_>, _>>()
.map_err(|error| ApiError::Other(error.to_string()))?;
print_records_or(
&records,
None,
output.color,
"No profiles yet. Start here: `servicenow init`.",
);
}
return Ok(());
}
Command::Profile(ProfileCommand::Use { name }) => {
use_profile(&name)?;
if output.json {
output.value(&serde_json::json!({"activeProfile": name}));
} else {
outln!("Now using profile {name}.");
}
return Ok(());
}
Command::Profile(ProfileCommand::Remove { name, yes }) => {
confirm_destructive(
yes,
format!("Remove profile '{name}' and its stored credential?"),
"profile removal cancelled; use --yes for non-interactive removal",
)?;
let credential_removed = delete_stored_credential(&name)?;
let removed = remove_profile(&name)?;
if !removed && !credential_removed {
return Err(ApiError::NotFound(format!("config profile '{name}'")));
}
if output.json {
output.value(&serde_json::json!({"removed": true, "profile": name}));
} else {
outln!("Removed profile {name}.");
}
return Ok(());
}
Command::Schema {
table: None,
command,
..
} => {
let root = Cli::command();
let schema = if let Some(path) = command {
let selected = find_command(&root, &path)?;
command_document(selected, Some(&path))
} else {
command_document(&root, None)
};
output.value(&schema);
return Ok(());
}
Command::Completions { shell } => {
let mut command = Cli::command();
clap_complete::generate(shell, &mut command, "servicenow", &mut output::Stdout);
return Ok(());
}
Command::Tui {
table,
query,
page_size,
} => {
if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() {
return Err(ApiError::InvalidInput(
"the TUI requires an interactive terminal on stdin and stdout".into(),
));
}
return run_tui_command(
&output,
cli.instance,
cli.username,
cli.profile,
table,
query,
page_size,
verbose,
)
.await;
}
Command::Config(ConfigCommand::Init) => {
if output.json {
output.value(&init_document());
} else {
let document = init_document();
outln!(
"Config path: {}",
document["configPath"].as_str().unwrap_or("")
);
outln!(
"\n{}",
toml::to_string_pretty(&document["example"])
.unwrap_or_else(|_| "[default]\ninstance = \"dev12345\"".into())
);
outln!("Next: {}", document["initCommand"].as_str().unwrap_or(""));
}
return Ok(());
}
Command::Config(ConfigCommand::Path) => {
if output.json {
output.value(&serde_json::json!({ "configPath": config_path() }));
} else {
outln!("{}", config_path().display());
}
return Ok(());
}
Command::Auth(AuthCommand::Status { offline: true }) => {
let config = Config::load(cli.instance, cli.username, cli.profile)?;
render_offline_auth_status(&config, &output);
return Ok(());
}
Command::Doctor { offline: true } => {
let config = Config::load(cli.instance, cli.username, cli.profile)?;
render_offline_doctor(&config, &output);
return Ok(());
}
_ => {}
}
let mut config = Config::load(cli.instance, cli.username, cli.profile)?;
if servicenow_cli::auth::refresh_if_needed(&mut config).await? {
output.message("OAuth access token refreshed.");
}
if matches!(cli.command, Command::Config(ConfigCommand::Show)) {
let masked = if matches!(config.auth_type, AuthType::Browser) {
"****".into()
} else {
mask_secret(&config.secret)
};
let value = serde_json::json!({
"configPath": config_path(),
"profile": config.profile,
"instance": config.instance,
"username": config.username,
"authType": config.auth_type.as_str(),
"secretMasked": masked,
"readOnly": config.read_only,
});
if output.json {
output.value(&value);
} else {
print_record(&value, output.color);
}
return Ok(());
}
let client = ServiceNowClient::new_with_user_token(
&config.instance,
config.username.as_deref(),
&config.secret,
config.auth_type,
config.browser_user_token.as_deref(),
)?;
let command_result = match cli.command {
Command::Tui { .. } => unreachable!("TUI commands return before shared client setup"),
Command::Incidents(command) => run_incidents(command, &client, &config, &output).await,
Command::Attachments(command) => run_attachments(command, &client, &config, &output).await,
Command::Catalog(command) => run_catalog(command, &client, &config, &output).await,
Command::Tables(command) => run_tables(command, &client, &config, &output).await,
Command::Schema {
table: Some(table),
refresh,
..
} => run_table_schema(&table, refresh, &client, &config, &output).await,
Command::Choices {
table,
field,
refresh,
} => run_choices(&table, &field, refresh, &client, &config, &output).await,
Command::Resolve { kind, value } => metadata::resolve_reference(&client, kind, &value)
.await
.map(|record| emit_record(&output, record)),
Command::Doctor { offline: false } => run_doctor(&client, &config, &output).await,
Command::Auth(AuthCommand::Status { offline: false }) => {
run_auth_status(&client, &config, &output).await
}
Command::Doctor { offline: true }
| Command::Init { .. }
| Command::Auth(_)
| Command::Profile(_)
| Command::Config(_)
| Command::Schema { .. }
| Command::Completions { .. } => {
unreachable!()
}
};
if command_result.is_ok()
&& let Some(cookie) = client.refreshed_browser_cookie()
&& let Err(error) = config.persist_browser_cookie(&cookie)
{
eprintln!(
"warning: the command succeeded, but the refreshed browser session could not be saved ({error}); run `servicenow auth login` if later commands fail"
);
}
command_result
}
#[allow(clippy::too_many_arguments)]
async fn run_tui_command(
output: &OutputConfig,
instance_arg: Option<String>,
username_arg: Option<String>,
profile_arg: Option<String>,
table: String,
query: Option<String>,
page_size: usize,
verbose: bool,
) -> Result<(), ApiError> {
let options = servicenow_cli::tui::TuiOptions {
table,
query,
page_size,
color: output.color,
};
options.validate()?;
let requested_profile = profile_arg.unwrap_or(active_profile_name()?);
loop {
let mut config = match Config::load(
instance_arg.clone(),
username_arg.clone(),
Some(requested_profile.clone()),
) {
Ok(config) => config,
Err(error) if tui_login_recoverable(&error) => {
let saved = profile_defaults(&requested_profile)?;
let instance_hint = instance_arg
.as_deref()
.or_else(|| saved.as_ref().map(|profile| profile.instance.as_str()));
let login_instance = saved.is_none().then(|| instance_arg.clone()).flatten();
let reason = tui_connection_reason(&error);
if !request_tui_login(
output,
&requested_profile,
instance_hint,
login_instance,
username_arg.clone(),
&reason,
verbose,
)
.await?
{
return Ok(());
}
continue;
}
Err(error) => return Err(error),
};
if let Err(error) = servicenow_cli::auth::refresh_if_needed(&mut config).await {
if !tui_login_recoverable(&error) {
return Err(error);
}
let reason = tui_connection_reason(&error);
let login_instance = profile_defaults(&config.profile)?
.is_none()
.then(|| config.instance.clone());
if !request_tui_login(
output,
&config.profile,
Some(&config.instance),
login_instance,
config.username.clone(),
&reason,
verbose,
)
.await?
{
return Ok(());
}
continue;
}
let client = ServiceNowClient::new_with_user_token(
&config.instance,
config.username.as_deref(),
&config.secret,
config.auth_type,
config.browser_user_token.as_deref(),
)?;
let tui_exit = servicenow_cli::tui::run(&client, &config, options.clone()).await?;
match tui_exit {
servicenow_cli::tui::TuiExit::Quit => {
if let Some(cookie) = client.refreshed_browser_cookie() {
config.persist_browser_cookie(&cookie)?;
}
return Ok(());
}
servicenow_cli::tui::TuiExit::Authenticate => {
let login_instance = profile_defaults(&config.profile)?
.is_none()
.then(|| config.instance.clone());
if !request_tui_login(
output,
&config.profile,
Some(&config.instance),
login_instance,
config.username.clone(),
"ServiceNow rejected the current session. Sign in again to continue where you left off.",
verbose,
)
.await?
{
return Ok(());
}
}
}
}
}
#[allow(clippy::too_many_arguments)]
async fn request_tui_login(
output: &OutputConfig,
profile: &str,
instance_hint: Option<&str>,
login_instance: Option<String>,
username: Option<String>,
reason: &str,
verbose: bool,
) -> Result<bool, ApiError> {
if servicenow_cli::tui::request_authentication(profile, instance_hint, reason, output.color)?
== servicenow_cli::tui::TuiExit::Quit
{
return Ok(false);
}
let auth_output = OutputConfig {
json: false,
quiet: false,
format: OutputFormat::Text,
color: output.color,
};
run_auth_login(
&auth_output,
profile.to_string(),
login_instance,
None,
username,
None,
None,
None,
false,
false,
false,
false,
verbose,
)
.await
}
fn tui_login_recoverable(error: &ApiError) -> bool {
if matches!(error, ApiError::Auth(_)) {
return true;
}
let message = error.to_string();
matches!(error, ApiError::InvalidInput(_) | ApiError::NotFound(_))
&& [
"No ServiceNow instance configured",
"No username configured",
"No password configured",
"No browser session configured",
"No access token configured",
"config profile '",
"OAuth profile is missing client_id",
]
.iter()
.any(|marker| message.contains(marker))
}
fn tui_connection_reason(error: &ApiError) -> String {
let message = error.to_string();
if message.contains("No ServiceNow instance configured") {
"No ServiceNow instance is connected to this profile yet.".into()
} else if message.contains("config profile '") {
"This profile has not been connected yet.".into()
} else if message.contains("No username configured")
|| message.contains("No password configured")
|| message.contains("No browser session configured")
|| message.contains("No access token configured")
{
"This profile does not have a usable credential yet.".into()
} else {
message
}
}
async fn run_table_schema(
table: &str,
refresh: bool,
client: &ServiceNowClient,
config: &Config,
output: &OutputConfig,
) -> Result<(), ApiError> {
let metadata = if refresh {
metadata::sync_table(client, &config.profile, table).await?
} else if let Some(metadata) = metadata::load(&config.profile, table)? {
metadata
} else {
output.message("No cached metadata found; fetching it from the instance.");
metadata::sync_table(client, &config.profile, table).await?
};
if output.json {
output.value(&serde_json::json!({"result": metadata}));
} else {
outln!(
"{} {} fields {} choice fields\n",
output.heading(&metadata.table),
metadata.fields.len(),
metadata.choices.len()
);
let records = metadata::metadata_as_records(&metadata);
let fields = [
"field".into(),
"label".into(),
"type".into(),
"reference".into(),
"mandatory".into(),
"read_only".into(),
"choices".into(),
];
print_records(&records, Some(&fields), output.color);
}
Ok(())
}
async fn run_choices(
table: &str,
field: &str,
refresh: bool,
client: &ServiceNowClient,
config: &Config,
output: &OutputConfig,
) -> Result<(), ApiError> {
let metadata = if refresh {
metadata::sync_table(client, &config.profile, table).await?
} else if let Some(metadata) = metadata::load(&config.profile, table)? {
metadata
} else {
metadata::sync_table(client, &config.profile, table).await?
};
if metadata.field(field).is_none() {
return Err(ApiError::NotFound(format!("field {table}.{field}")));
}
let choices = metadata.choices.get(field).cloned().unwrap_or_default();
if output.json {
output.value(&serde_json::json!({
"table": table,
"field": field,
"result": choices,
}));
} else if choices.is_empty() {
outln!("No configured choices for {table}.{field}.");
} else {
let records = choices
.into_iter()
.map(serde_json::to_value)
.collect::<Result<Vec<_>, _>>()
.map_err(|error| ApiError::Other(error.to_string()))?;
print_records(
&records,
Some(&["value".into(), "label".into(), "sequence".into()]),
output.color,
);
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn run_auth_login(
output: &OutputConfig,
profile: String,
instance: Option<String>,
method: Option<AuthType>,
username: Option<String>,
client_id: Option<String>,
scope: Option<String>,
redirect_uri: Option<String>,
secret_stdin: bool,
insecure_storage: bool,
no_browser: bool,
read_only: bool,
verbose: bool,
) -> Result<bool, ApiError> {
servicenow_cli::config::validate_profile_name(&profile)?;
if output.format == OutputFormat::Text && std::io::stdin().is_terminal() {
output.message(&format!(
"{}\n Secure sign-in, tailored to your instance.",
output.heading("Connect to ServiceNow")
));
}
let saved = if instance.is_none() {
profile_defaults(&profile)?
} else {
None
};
let resumed = saved.is_some();
let instance = required_prompt(
instance.or_else(|| saved.as_ref().map(|value| value.instance.clone())),
"ServiceNow instance",
)?;
let method = method.or(saved
.as_ref()
.and_then(|value| value.auth_type.as_deref())
.map(str::parse)
.transpose()?);
let username = username.or_else(|| saved.as_ref().and_then(|value| value.username.clone()));
let client_id = client_id.or_else(|| saved.as_ref().and_then(|value| value.client_id.clone()));
let scope = scope
.or_else(|| saved.as_ref().and_then(|value| value.oauth_scope.clone()))
.unwrap_or_else(|| "useraccount".into());
let redirect_uri = redirect_uri
.or_else(|| saved.as_ref().and_then(|value| value.redirect_uri.clone()))
.unwrap_or_else(|| "http://127.0.0.1:8484/callback".into());
let read_only = read_only
|| saved
.as_ref()
.and_then(|value| value.read_only)
.unwrap_or(false);
if resumed {
output.success(&format!("Resuming profile '{profile}'"));
}
let method = resolve_auth_method(output, &instance, method, client_id.as_deref()).await?;
let mut username = username;
if matches!(method, AuthType::Basic) {
username = Some(required_prompt(username, "Username")?);
}
let configured_client_id = if matches!(method, AuthType::OAuth) {
if client_id
.as_deref()
.is_none_or(|value| value.trim().is_empty())
{
print_oauth_admin_request(output, &redirect_uri);
if std::io::stdin().is_terminal() {
let ready = Confirm::new()
.with_prompt("Do you have the client ID ready?")
.default(true)
.interact()
.map_err(|error| {
ApiError::Other(format!("failed to confirm OAuth readiness: {error}"))
})?;
if !ready {
save_oauth_draft(&profile, &instance, &scope, &redirect_uri, read_only)?;
let resume_command = format!("servicenow auth login {profile}");
if output.json {
output.value(&serde_json::json!({
"profile": profile,
"instance": instance,
"authType": "oauth",
"authenticated": false,
"status": "awaiting-client-id",
"resumeCommand": resume_command,
}));
} else {
output.success("Setup saved—no credential was stored");
outln!(
"\nWhen your administrator sends the client ID, continue with:\n {resume_command} --client-id YOUR_CLIENT_ID"
);
}
return Ok(false);
}
}
}
Some(required_prompt(client_id, "OAuth client ID")?)
} else {
None
};
let file_storage = if matches!(method, AuthType::Browser) {
None
} else {
Some(choose_credential_storage(insecure_storage)?)
};
let mut credential = match method {
AuthType::Basic => StoredCredential::Basic {
password: read_login_secret(secret_stdin, "Password", false)?,
},
AuthType::Browser => {
if secret_stdin {
return Err(ApiError::InvalidInput(
"browser sign-in cannot be read from stdin; remove --secret-stdin".into(),
));
}
if !no_browser {
output.message("\nOpening a private browser window for ServiceNow…");
output.message(
"Complete your normal SSO sign-in there. This CLI never receives your identity-provider password.",
);
}
let spinner = if verbose {
output.message(
"Verbose browser diagnostics enabled; secrets, URLs, and page content are redacted.",
);
None
} else {
OnboardingSpinner::start(
output,
"Waiting for ServiceNow to complete the secure browser handoff",
)
};
let credential = if verbose {
let started = std::time::Instant::now();
servicenow_cli::browser::browser_login_with_progress(
&instance,
!no_browser,
|progress| {
eprintln!(
"[+{:>6.1}s] browser: {}",
started.elapsed().as_secs_f64(),
progress.message()
);
},
)
.await
} else {
servicenow_cli::browser::browser_login(&instance, !no_browser).await
};
drop(spinner);
credential?
}
AuthType::Bearer => StoredCredential::Bearer {
access_token: read_login_secret(secret_stdin, "Access token", false)?,
},
AuthType::OAuth => {
let id = configured_client_id
.as_deref()
.expect("OAuth client ID was collected before reading credentials");
let client_secret = read_login_secret(
secret_stdin,
"OAuth client secret (optional; press Enter to skip)",
true,
)?;
servicenow_cli::auth::oauth_login(
&instance,
id,
(!client_secret.is_empty()).then_some(client_secret),
Some(&scope),
&redirect_uri,
!no_browser,
)
.await?
}
};
let browser_user_token = match &credential {
StoredCredential::Browser { user_token, .. } => Some(user_token.as_str()),
_ => None,
};
let client = ServiceNowClient::new_with_user_token(
&instance,
username.as_deref(),
credential.secret(),
method,
browser_user_token,
)?;
let users = match client
.list_records(
"sys_user",
&ListOptions {
query: Some("sys_id=javascript:gs.getUserID()".into()),
fields: Some(vec!["sys_id".into(), "user_name".into(), "name".into()]),
limit: 1,
..ListOptions::default()
},
)
.await
{
Ok(users) => users,
Err(error) if matches!(method, AuthType::Basic) && matches!(error, ApiError::Auth(_)) => {
return Err(enrich_basic_auth_error(&instance, error).await);
}
Err(error) => return Err(error),
};
let mut browser_identity = None;
if let Some(user) = users.first() {
username = field_text(user, "user_name").or(username);
if matches!(method, AuthType::Browser) {
let name = field_text(user, "name");
browser_identity = match (name.as_deref(), username.as_deref()) {
(Some(name), Some(username)) if name != username => {
Some(format!("{name} ({username})"))
}
(Some(name), _) => Some(name.into()),
(_, Some(username)) => Some(username.into()),
_ => None,
};
}
}
if matches!(method, AuthType::Browser) {
let identity = browser_identity.unwrap_or_else(|| "your ServiceNow account".into());
if output.format == OutputFormat::Text {
output.success(&format!("Browser sign-in complete as {identity}"));
}
if let Some(cookie) = client.refreshed_browser_cookie()
&& let StoredCredential::Browser {
cookie: stored_cookie,
..
} = &mut credential
{
*stored_cookie = cookie;
}
}
let file_storage = match file_storage {
Some(file_storage) => file_storage,
None => choose_credential_storage(insecure_storage)?,
};
let mut profile_config = ProfileConfig::default();
profile_config.instance = Some(instance);
profile_config.username = username.clone();
profile_config.auth_type = Some(method.as_str().into());
profile_config.read_only = Some(read_only);
profile_config.credential_store = Some(if file_storage { "file" } else { "keyring" }.into());
profile_config.credential = file_storage.then_some(credential.clone());
profile_config.client_id = configured_client_id;
profile_config.oauth_scope = matches!(method, AuthType::OAuth).then_some(scope);
profile_config.redirect_uri = matches!(method, AuthType::OAuth).then_some(redirect_uri);
if !file_storage {
credentials::store(&profile, &credential)?;
}
if let Err(error) = save_profile(&profile, profile_config, true) {
if !file_storage {
let _ = credentials::delete(&profile);
}
return Err(error);
}
let result = serde_json::json!({
"profile": profile,
"instance": client.site_url(),
"username": username,
"authType": method.as_str(),
"readOnly": read_only,
"credentialStore": if file_storage { "config-file" } else { "os-keychain" },
"authenticated": true,
});
if output.json {
output.value(&result);
} else {
output.success("Connected to ServiceNow");
outln!("\n{}", output.heading("Connection"));
outln!(
" Profile {}",
result["profile"].as_str().unwrap_or("")
);
outln!(
" Instance {}",
result["instance"].as_str().unwrap_or("")
);
outln!(
" User {}",
result["username"].as_str().unwrap_or("")
);
outln!(
" Auth {}",
result["authType"].as_str().unwrap_or("")
);
outln!(
" Safety {}",
if read_only {
"read-only"
} else {
"writes enabled"
}
);
outln!(
" Credentials {}",
if file_storage {
"config file (plaintext, mode 0600)"
} else {
"OS keychain"
}
);
}
Ok(true)
}
fn print_oauth_admin_request(output: &OutputConfig, redirect_uri: &str) {
let heading = output.heading("ServiceNow OAuth app required");
output.message(&format!(
"\n{heading}\n\nAsk your ServiceNow administrator:\n\n Please create an OAuth API endpoint for external clients under\n System OAuth → Application Registry for the ServiceNow CLI, and\n register this redirect URI:\n\n {redirect_uri}\n\n Then send me the client ID.\n\nMicrosoft Entra remains the browser sign-in; the OAuth app itself is\nconfigured in ServiceNow."
));
}
async fn enrich_basic_auth_error(instance: &str, error: ApiError) -> ApiError {
let ApiError::Auth(message) = error else {
return error;
};
match servicenow_cli::auth::discover_login_provider(instance).await {
Ok(servicenow_cli::auth::LoginProvider::MicrosoftEntra) => ApiError::Auth(format!(
"Basic authentication was rejected, and this instance appears to use Microsoft Entra SSO. Federated accounts usually do not have a usable ServiceNow password. Use browser sign-in instead; it needs no OAuth application or administrator setup. ServiceNow response: {message}"
)),
Ok(servicenow_cli::auth::LoginProvider::ExternalSso(host)) => {
let provider = host
.map(|host| format!(" through {host}"))
.unwrap_or_default();
ApiError::Auth(format!(
"Basic authentication was rejected, and this instance appears to use external SSO{provider}. Federated accounts usually do not have a usable ServiceNow password. Use browser sign-in instead; it needs no OAuth application or administrator setup. ServiceNow response: {message}"
))
}
_ => ApiError::Auth(message),
}
}
fn save_oauth_draft(
profile: &str,
instance: &str,
scope: &str,
redirect_uri: &str,
read_only: bool,
) -> Result<(), ApiError> {
let mut draft = ProfileConfig::default();
draft.instance = Some(instance.into());
draft.auth_type = Some("oauth".into());
draft.read_only = Some(read_only);
draft.oauth_scope = Some(scope.into());
draft.redirect_uri = Some(redirect_uri.into());
save_profile(profile, draft, true)
}
async fn resolve_auth_method(
output: &OutputConfig,
instance: &str,
explicit: Option<AuthType>,
client_id: Option<&str>,
) -> Result<AuthType, ApiError> {
if let Some(method) = explicit {
return Ok(method);
}
if client_id.is_some_and(|value| !value.trim().is_empty()) {
return Ok(AuthType::OAuth);
}
let spinner = OnboardingSpinner::start(output, "Checking how this instance signs users in");
if spinner.is_none() {
output.message("Checking how this instance signs users in…");
}
let discovery = servicenow_cli::auth::discover_login_provider(instance).await;
drop(spinner);
match discovery {
Ok(servicenow_cli::auth::LoginProvider::MicrosoftEntra) => {
output.success("Microsoft Entra SSO detected");
output.message(
"Sign in through your browser—no ServiceNow password or OAuth application is required.",
);
Ok(AuthType::Browser)
}
Ok(servicenow_cli::auth::LoginProvider::ExternalSso(host)) => {
let provider = host
.as_deref()
.map(|host| format!("External SSO detected ({host})"))
.unwrap_or_else(|| "External SSO detected".into());
output.success(&provider);
output.message(
"Sign in through your browser—no identity-provider password is entered into this CLI.",
);
Ok(AuthType::Browser)
}
Ok(servicenow_cli::auth::LoginProvider::Undetermined)
if std::io::stdin().is_terminal() =>
{
output.message(
"No SSO redirect was detected. A ServiceNow login page does not prove that your account has a local password.",
);
select_auth_method()
}
Ok(servicenow_cli::auth::LoginProvider::Undetermined) => Err(ApiError::InvalidInput(
"the instance did not expose a definitive login method; pass --method browser, basic, oauth, or bearer"
.into(),
)),
Err(error) if std::io::stdin().is_terminal() => {
output.message(&format!(
"Could not identify the login method automatically ({error})."
));
select_auth_method()
}
Err(error) => Err(ApiError::InvalidInput(format!(
"could not auto-detect the authentication method ({error}); pass --method browser, basic, oauth, or bearer"
))),
}
}
struct OnboardingSpinner {
running: std::sync::Arc<std::sync::atomic::AtomicBool>,
handle: Option<std::thread::JoinHandle<()>>,
}
impl OnboardingSpinner {
fn start(output: &OutputConfig, message: &str) -> Option<Self> {
if output.quiet || output.format != OutputFormat::Text || !std::io::stderr().is_terminal() {
return None;
}
let running = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
let thread_running = running.clone();
let message = message.to_string();
let handle = std::thread::spawn(move || {
let frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
let mut frame = 0;
while thread_running.load(std::sync::atomic::Ordering::Relaxed) {
eprint!("\r{} {message}", frames[frame % frames.len()]);
let _ = std::io::stderr().flush();
frame += 1;
std::thread::sleep(std::time::Duration::from_millis(80));
}
});
Some(Self {
running,
handle: Some(handle),
})
}
}
impl Drop for OnboardingSpinner {
fn drop(&mut self) {
self.running
.store(false, std::sync::atomic::Ordering::Relaxed);
if let Some(handle) = self.handle.take() {
let _ = handle.join();
}
eprint!("\r{:width$}\r", "", width = 72);
let _ = std::io::stderr().flush();
}
}
fn select_auth_method() -> Result<AuthType, ApiError> {
let options = [
"Browser sign-in (SSO, no administrator setup)",
"Managed OAuth application",
"ServiceNow username and password",
"Access token",
];
let selected = Select::new()
.with_prompt("How do you sign in?")
.items(options)
.default(0)
.interact()
.map_err(|error| ApiError::Other(format!("failed to choose authentication: {error}")))?;
Ok(match selected {
0 => AuthType::Browser,
1 => AuthType::OAuth,
2 => AuthType::Basic,
_ => AuthType::Bearer,
})
}
fn choose_credential_storage(insecure_storage: bool) -> Result<bool, ApiError> {
if insecure_storage {
eprintln!(
"warning: the credential will be stored in plaintext in {} (protected with mode 0600 on Unix)",
config_path().display()
);
return Ok(true);
}
match credentials::available() {
Ok(()) => Ok(false),
Err(error) => {
eprintln!(
"warning: {error}; storing the credential in plaintext in {} (protected with mode 0600 on Unix)",
config_path().display()
);
Ok(true)
}
}
}
fn required_prompt(value: Option<String>, prompt: &str) -> Result<String, ApiError> {
if let Some(value) = value.filter(|value| !value.trim().is_empty()) {
return Ok(value.trim().into());
}
if !std::io::stdin().is_terminal() {
return Err(ApiError::InvalidInput(format!(
"{prompt} is required in non-interactive mode"
)));
}
Input::<String>::new()
.with_prompt(prompt)
.interact_text()
.map_err(|error| ApiError::Other(format!("failed to read {prompt}: {error}")))
.and_then(|value| {
(!value.trim().is_empty())
.then(|| value.trim().into())
.ok_or_else(|| ApiError::InvalidInput(format!("{prompt} cannot be empty")))
})
}
fn read_login_secret(
from_stdin: bool,
prompt: &str,
allow_empty: bool,
) -> Result<String, ApiError> {
let value = if from_stdin {
let mut value = String::new();
std::io::stdin()
.read_to_string(&mut value)
.map_err(|error| ApiError::Other(format!("failed to read secret: {error}")))?;
value.trim_end_matches(['\r', '\n']).to_string()
} else {
if !std::io::stdin().is_terminal() {
return Err(ApiError::InvalidInput(format!(
"{prompt} requires --secret-stdin in non-interactive mode"
)));
}
Password::new()
.with_prompt(prompt)
.allow_empty_password(allow_empty)
.interact()
.map_err(|error| ApiError::Other(format!("failed to read {prompt}: {error}")))?
};
if value.is_empty() && !allow_empty {
Err(ApiError::InvalidInput(format!("{prompt} cannot be empty")))
} else {
Ok(value)
}
}
fn credential_detail(config: &Config) -> &'static str {
match config.credential_store() {
"config-file" => "config file (plaintext, mode 0600)",
"os-keychain" => "OS keychain",
"environment" => "environment variable",
"legacy-config" => "legacy plaintext config field",
_ => "unknown",
}
}
fn confirm_destructive(yes: bool, prompt: String, cancelled_message: &str) -> Result<(), ApiError> {
let confirmed = yes
|| (std::io::stdin().is_terminal()
&& Confirm::new()
.with_prompt(prompt)
.default(false)
.interact()
.map_err(|error| ApiError::Other(format!("failed to confirm: {error}")))?);
if confirmed {
Ok(())
} else {
Err(ApiError::InvalidInput(cancelled_message.into()))
}
}
fn selected_profile(
profile_override: Option<&str>,
legacy_profile: Option<String>,
) -> Result<Option<String>, ApiError> {
match (profile_override, legacy_profile) {
(Some(_), Some(_)) => Err(ApiError::InvalidInput(
"provide the profile with --profile or the legacy positional argument, not both".into(),
)),
(Some(profile), None) => Ok(Some(profile.into())),
(None, legacy_profile) => Ok(legacy_profile),
}
}
fn render_offline_auth_status(config: &Config, output: &OutputConfig) {
let value = serde_json::json!({
"profile": config.profile,
"status": "configured",
"verified": false,
"instance": config.instance,
"authType": config.auth_type.as_str(),
"credentialStore": config.credential_store(),
});
if output.json {
output.value(&value);
} else {
outln!(
"Profile: {}\nStatus: configured (network not checked)\nAuthentication: {}\nCredentials: {}",
config.profile,
config.auth_type.as_str(),
credential_detail(config)
);
}
}
fn render_offline_doctor(config: &Config, output: &OutputConfig) {
let checks = serde_json::json!([
{"name": "configuration", "ok": true, "detail": config.instance},
{"name": "credentials", "ok": true, "detail": credential_detail(config)},
{"name": "authentication", "skipped": true, "detail": "network check skipped"},
{"name": "table_api", "skipped": true, "detail": "network check skipped"},
{"name": "write_safety", "ok": true, "detail": if config.read_only { "read-only mode enabled" } else { "write operations enabled" }}
]);
if output.json {
output.value(&serde_json::json!({
"ok": true,
"offline": true,
"verified": false,
"checks": checks
}));
} else {
outln!("ServiceNow connection (offline)\n");
for check in checks.as_array().expect("checks are an array") {
let marker = if check["skipped"].as_bool().unwrap_or(false) {
"–"
} else {
"✓"
};
outln!(
" {marker} {:<16} {}",
check["name"].as_str().unwrap_or("check"),
check["detail"].as_str().unwrap_or("")
);
}
}
}
async fn run_auth_status(
client: &ServiceNowClient,
config: &Config,
output: &OutputConfig,
) -> Result<(), ApiError> {
let users = client
.list_records(
"sys_user",
&ListOptions {
query: Some("sys_id=javascript:gs.getUserID()".into()),
fields: Some(vec!["sys_id".into(), "user_name".into(), "name".into()]),
limit: 1,
..ListOptions::default()
},
)
.await?;
let user = users.first().ok_or_else(|| {
ApiError::Other("authentication succeeded, but the current user was not returned".into())
})?;
let username = field_text(user, "user_name")
.or_else(|| field_text(user, "name"))
.unwrap_or_else(|| "unknown".into());
let value = serde_json::json!({
"profile": config.profile,
"status": "ok",
"verified": true,
"identity": username,
"instance": config.instance,
"authType": config.auth_type.as_str(),
"credentialStore": config.credential_store(),
});
if output.json {
output.value(&value);
} else {
outln!(
"Authenticated as {} ({}, {})",
value["identity"].as_str().unwrap_or("unknown"),
config.auth_type.as_str(),
credential_detail(config)
);
}
Ok(())
}
async fn run_doctor(
client: &ServiceNowClient,
config: &Config,
output: &OutputConfig,
) -> Result<(), ApiError> {
let users = client
.list_records(
"sys_user",
&ListOptions {
query: Some("sys_id=javascript:gs.getUserID()".into()),
fields: Some(vec![
"sys_id".into(),
"user_name".into(),
"name".into(),
"active".into(),
]),
limit: 1,
..ListOptions::default()
},
)
.await?;
let user = users.first().ok_or_else(|| {
ApiError::Other("authentication succeeded, but the current user was not returned".into())
})?;
let username = field_text(user, "user_name").unwrap_or_else(|| "unknown".into());
client
.list_records(
"incident",
&ListOptions {
fields: Some(vec!["sys_id".into(), "number".into()]),
limit: 1,
..ListOptions::default()
},
)
.await?;
let credential_detail = credential_detail(config);
let checks = serde_json::json!([
{"name": "configuration", "ok": true, "detail": config.instance},
{"name": "authentication", "ok": true, "detail": username},
{"name": "credentials", "ok": true, "detail": credential_detail},
{"name": "table_api", "ok": true, "detail": "incident table is readable"},
{
"name": "write_safety",
"ok": true,
"detail": if config.read_only { "read-only mode enabled" } else { "write operations enabled" }
}
]);
let result = serde_json::json!({
"ok": true,
"instance": client.site_url(),
"checks": checks,
});
if output.json {
output.value(&result);
} else {
outln!("ServiceNow connection\n");
for check in result["checks"].as_array().expect("checks are an array") {
outln!(
" ✓ {:<16} {}",
check["name"].as_str().unwrap_or("check"),
check["detail"].as_str().unwrap_or("")
);
}
outln!("\nReady.");
}
Ok(())
}
async fn run_incidents(
command: IncidentsCommand,
client: &ServiceNowClient,
config: &Config,
output: &OutputConfig,
) -> Result<(), ApiError> {
match command {
IncidentsCommand::List {
query,
active,
limit,
offset,
all,
fields,
display_value,
} => {
let query = combine_query(active.then_some("active=true"), query.as_deref());
let custom_fields = fields.is_some();
let fields = parse_fields(fields.as_deref()).or_else(|| {
Some(
INCIDENT_LIST_FIELDS
.iter()
.map(|field| (*field).into())
.collect(),
)
});
let records = client
.list_records(
"incident",
&ListOptions {
query,
fields: fields.clone(),
limit,
offset,
all,
display_value: display_value.unwrap_or_else(|| {
if output.format == OutputFormat::Text {
DisplayValue::True
} else {
DisplayValue::False
}
}),
},
)
.await?;
let human_fields: Vec<String> = INCIDENT_HUMAN_FIELDS
.iter()
.map(|field| (*field).into())
.collect();
let visible_fields = if custom_fields {
fields.as_deref()
} else {
Some(human_fields.as_slice())
};
emit_records_or(
output,
records,
visible_fields,
"No incidents matched. Try broadening --query or removing --active.",
);
}
IncidentsCommand::Mine {
query,
limit,
all,
display_value,
} => {
let query = combine_query(
Some("assigned_to=javascript:gs.getUserID()"),
query.as_deref(),
);
let fields: Vec<String> = INCIDENT_LIST_FIELDS
.iter()
.map(|field| (*field).into())
.collect();
let records = client
.list_records(
"incident",
&ListOptions {
query,
fields: Some(fields.clone()),
limit,
all,
display_value: display_value.unwrap_or_else(|| {
if output.format == OutputFormat::Text {
DisplayValue::True
} else {
DisplayValue::False
}
}),
..ListOptions::default()
},
)
.await?;
let human_fields: Vec<String> = INCIDENT_HUMAN_FIELDS
.iter()
.map(|field| (*field).into())
.collect();
emit_records_or(
output,
records,
Some(&human_fields),
"Nothing is assigned to you. You’re clear for now. Explore with `servicenow incidents list --active`.",
);
}
IncidentsCommand::Show {
identifier,
fields,
display_value,
} => {
let fields = parse_fields(fields.as_deref());
let record =
resolve_incident(client, &identifier, fields.clone(), display_value).await?;
emit_record(output, record);
}
IncidentsCommand::Create {
short_description,
description,
category,
impact,
urgency,
assignment_group,
assignee,
fields,
} => {
config.require_writable()?;
let mut body = build_body(None, &fields)?;
insert(&mut body, "short_description", Some(short_description));
insert(&mut body, "description", description);
insert(&mut body, "category", category);
insert(&mut body, "impact", impact);
insert(&mut body, "urgency", urgency);
insert(
&mut body,
"assignment_group",
resolve_reference_id(client, ReferenceKind::Group, assignment_group).await?,
);
insert(
&mut body,
"assigned_to",
resolve_reference_id(client, ReferenceKind::User, assignee).await?,
);
let record = client.create_record("incident", &body).await?;
output.success("Incident created.");
emit_record(output, record);
}
IncidentsCommand::Update {
identifier,
short_description,
description,
state,
assignee,
work_notes,
fields,
} => {
config.require_writable()?;
let mut body = build_body(None, &fields)?;
insert(&mut body, "short_description", short_description);
insert(&mut body, "description", description);
insert(&mut body, "state", state);
insert(
&mut body,
"assigned_to",
resolve_reference_id(client, ReferenceKind::User, assignee).await?,
);
insert(&mut body, "work_notes", work_notes);
if body.is_empty() {
return Err(ApiError::InvalidInput(
"at least one field must be supplied".into(),
));
}
let existing = resolve_incident(
client,
&identifier,
Some(vec!["sys_id".into()]),
DisplayValue::False,
)
.await?;
let sys_id = record_sys_id(&existing)?.to_string();
let record = client.update_record("incident", &sys_id, &body).await?;
output.success("Incident updated.");
emit_record(output, record);
}
IncidentsCommand::Resolve {
identifier,
code,
notes,
notes_file,
state,
fields,
refresh,
dry_run,
} => {
let notes = match (notes, notes_file) {
(Some(notes), None) => notes,
(None, Some(path)) => read_file_or_stdin(&path, "resolution notes")?,
(Some(_), Some(_)) => unreachable!("clap rejects conflicting note inputs"),
(None, None) => {
return Err(ApiError::InvalidInput(
"resolution notes are required; provide --notes or --notes-file".into(),
));
}
};
incident::require_resolution_input(&code, ¬es)?;
let mut body = build_body(None, &fields)?;
for reserved in ["state", "close_code", "close_notes"] {
if body.contains_key(reserved) {
return Err(ApiError::InvalidInput(format!(
"--field {reserved}=... conflicts with the dedicated resolution option"
)));
}
}
if !dry_run {
config.require_writable()?;
}
let metadata = if refresh {
metadata::sync_table(client, &config.profile, "incident").await?
} else if let Some(metadata) = metadata::load(&config.profile, "incident")? {
metadata
} else {
metadata::sync_table(client, &config.profile, "incident").await?
};
let resolution = incident::resolution_body(&metadata, &code, notes, state.as_deref())?;
let resolved_state = resolution["state"]
.as_str()
.expect("resolution state is a string")
.to_string();
body.extend(resolution);
let existing = resolve_incident(
client,
&identifier,
Some(vec!["sys_id".into(), "number".into(), "state".into()]),
DisplayValue::All,
)
.await?;
incident::require_resolvable(&existing, &resolved_state, &metadata)?;
if dry_run {
emit_mutation_plan(output, "resolve", &identifier, &body);
return Ok(());
}
let record = client
.update_record("incident", record_sys_id(&existing)?, &body)
.await?;
output.success(&format!("Resolved {identifier}."));
emit_record(output, record);
}
IncidentsCommand::Edit {
identifier,
file,
dry_run,
yes,
} => {
let existing = resolve_incident(client, &identifier, None, DisplayValue::All).await?;
let sys_id = record_sys_id(&existing)?.to_string();
let original = incident::edit_document(
&existing,
metadata::load(&config.profile, "incident")?.as_ref(),
)?;
let edited = match file {
Some(path) => read_file_or_stdin(&path, "edited incident")?,
None if std::io::stdin().is_terminal() => Editor::new()
.extension(".yaml")
.edit(&original)
.map_err(|error| ApiError::Other(format!("failed to open editor: {error}")))?
.ok_or_else(|| ApiError::InvalidInput("incident edit cancelled".into()))?,
None => {
return Err(ApiError::InvalidInput(
"an interactive terminal or --file is required for incident edit".into(),
));
}
};
let body = incident::changed_fields(&existing, incident::parse_edit_document(&edited)?);
if body.is_empty() {
if output.json {
output.value(&serde_json::json!({
"changed": false,
"incident": identifier,
"changes": {},
}));
} else {
outln!("No changes to apply.");
}
return Ok(());
}
if dry_run {
emit_mutation_plan(output, "update", &identifier, &body);
return Ok(());
}
config.require_writable()?;
if !yes {
if !std::io::stdin().is_terminal() {
return Err(ApiError::InvalidInput(
"confirmation requires an interactive terminal; rerun with --yes".into(),
));
}
let diff = incident::unified_diff(&original, &edited);
if !diff.is_empty() {
eprintln!("{diff}");
}
let confirmed = Confirm::new()
.with_prompt(format!(
"Apply {} changed field(s) to {identifier}?",
body.len()
))
.default(false)
.interact()
.map_err(|error| {
ApiError::Other(format!("failed to confirm update: {error}"))
})?;
if !confirmed {
return Err(ApiError::InvalidInput("incident edit cancelled".into()));
}
}
let record = client.update_record("incident", &sys_id, &body).await?;
output.success(&format!("Updated {identifier} ({} field(s)).", body.len()));
emit_record(output, record);
}
IncidentsCommand::Note {
identifier,
text,
file,
dry_run,
} => {
let note = match (text, file) {
(Some(_), Some(_)) => {
return Err(ApiError::InvalidInput(
"provide work note text or --file, not both".into(),
));
}
(Some(text), None) => text,
(None, Some(path)) => read_file_or_stdin(&path, "work note")?,
(None, None) => {
return Err(ApiError::InvalidInput(
"work note text or --file is required".into(),
));
}
};
let body = incident::work_note_body(note)?;
let existing = resolve_incident(
client,
&identifier,
Some(vec!["sys_id".into()]),
DisplayValue::False,
)
.await?;
if dry_run {
emit_mutation_plan(output, "append_work_note", &identifier, &body);
return Ok(());
}
config.require_writable()?;
let record = client
.update_record("incident", record_sys_id(&existing)?, &body)
.await?;
output.success(&format!("Added a work note to {identifier}."));
emit_record(output, record);
}
IncidentsCommand::Assign {
identifier,
assignee,
group,
dry_run,
} => {
incident::require_assignment(assignee.as_deref(), group.as_deref())?;
let mut body = Map::new();
insert(
&mut body,
"assigned_to",
resolve_reference_id(client, ReferenceKind::User, assignee).await?,
);
insert(
&mut body,
"assignment_group",
resolve_reference_id(client, ReferenceKind::Group, group).await?,
);
let existing = resolve_incident(
client,
&identifier,
Some(vec!["sys_id".into()]),
DisplayValue::False,
)
.await?;
if dry_run {
emit_mutation_plan(output, "assign", &identifier, &body);
return Ok(());
}
config.require_writable()?;
let record = client
.update_record("incident", record_sys_id(&existing)?, &body)
.await?;
output.success(&format!("Assigned {identifier}."));
emit_record(output, record);
}
IncidentsCommand::Open { identifier, print } => {
let existing = resolve_incident(
client,
&identifier,
Some(vec!["sys_id".into(), "number".into()]),
DisplayValue::False,
)
.await?;
let url = client.record_url("incident", record_sys_id(&existing)?);
if output.json {
output.value(&serde_json::json!({
"incident": field_text(&existing, "number").unwrap_or(identifier),
"url": url,
}));
} else if print || !std::io::stdout().is_terminal() {
outln!("{url}");
} else {
open::that(&url).map_err(|error| {
ApiError::Other(format!("failed to open ServiceNow in a browser: {error}"))
})?;
output.success("Opened incident in ServiceNow.");
}
}
IncidentsCommand::Watch {
identifier,
interval,
count,
fields,
} => {
if interval == 0 {
return Err(ApiError::InvalidInput(
"--interval must be greater than zero".into(),
));
}
if count == Some(0) {
return Err(ApiError::InvalidInput(
"--count must be greater than zero".into(),
));
}
if output.format == OutputFormat::Csv {
return Err(ApiError::InvalidInput(
"incident watch is a stream; use table, json, jsonl, or yaml output".into(),
));
}
let fields = parse_fields(fields.as_deref()).unwrap_or_else(|| {
[
"sys_id",
"number",
"short_description",
"state",
"priority",
"assigned_to",
"assignment_group",
"sys_updated_on",
]
.into_iter()
.map(str::to_string)
.collect()
});
let mut previous =
resolve_incident(client, &identifier, Some(fields.clone()), DisplayValue::All)
.await?;
let sys_id = record_sys_id(&previous)?.to_string();
emit_watch_event(output, &identifier, 0, &[], Some(&previous));
let mut polls = 0usize;
loop {
if count.is_some_and(|limit| polls >= limit) {
break;
}
tokio::select! {
_ = tokio::signal::ctrl_c() => {
output.message("Watch stopped.");
break;
}
_ = tokio::time::sleep(std::time::Duration::from_secs(interval)) => {}
}
polls += 1;
let current = client
.get_record("incident", &sys_id, Some(&fields), DisplayValue::All)
.await?;
let changes = incident::change_records(&previous, ¤t);
if !changes.is_empty() {
emit_watch_event(output, &identifier, polls, &changes, None);
}
previous = current;
}
}
}
Ok(())
}
async fn resolve_reference_id(
client: &ServiceNowClient,
kind: ReferenceKind,
value: Option<String>,
) -> Result<Option<String>, ApiError> {
let Some(value) = value else {
return Ok(None);
};
let record = metadata::resolve_reference(client, kind, &value).await?;
Ok(Some(record_sys_id(&record)?.to_string()))
}
const RITM_LIST_FIELDS: &[&str] = &[
"number",
"cat_item",
"stage",
"state",
"quantity",
"requested_for",
"request",
"sys_created_on",
"sys_id",
];
async fn run_catalog(
command: CatalogCommand,
client: &ServiceNowClient,
config: &Config,
output: &OutputConfig,
) -> Result<(), ApiError> {
match command {
CatalogCommand::Search {
text,
limit,
offset,
} => {
let items = client
.search_catalog_items(text.as_deref(), limit, offset)
.await?;
let rows: Vec<Value> = items.iter().map(catalog_search_row).collect();
let fields: Vec<String> = ["name", "kind", "short_description", "sys_id"]
.into_iter()
.map(str::to_string)
.collect();
emit_records_or(output, rows, Some(&fields), "No catalog items found.");
}
CatalogCommand::Show { item } => {
let item = resolve_catalog_item(client, &item, true).await?;
emit_catalog_item(output, &item, client.site_url());
}
CatalogCommand::Order {
item,
vars,
vars_file,
quantity,
requested_for,
allow_unknown_vars,
allow_unverified_formats,
checkout,
dry_run,
yes,
} => {
if checkout && requested_for.is_some() {
return Err(ApiError::InvalidInput(
"--checkout cannot order for someone else: the instance ignores --requested-for for items added to a cart, so the request would be raised for you; order without --checkout".into(),
));
}
let file_values = match vars_file {
Some(path) => {
catalog::parse_vars_document(&read_file_or_stdin(&path, "catalog variables")?)?
}
None => Default::default(),
};
let command_line = vars
.iter()
.map(|assignment| catalog::parse_var_assignment(assignment))
.collect::<Result<Vec<_>, _>>()?;
let inputs = catalog::merge_inputs(file_values, command_line);
let item = resolve_catalog_item(client, &item, false).await?;
item.ensure_orderable(client.site_url())?;
let requested_for =
resolve_reference_id(client, ReferenceKind::User, requested_for).await?;
let unverified_formats = if allow_unverified_formats {
catalog::UnverifiedFormats::Allow
} else if dry_run {
catalog::UnverifiedFormats::Preview
} else {
catalog::UnverifiedFormats::Refuse
};
let plan = catalog::prepare_order(
client,
&item,
&inputs,
&catalog::OrderOptions {
quantity,
requested_for,
allow_unknown_vars,
unverified_formats,
},
)
.await?;
for warning in &plan.warnings {
output.message(&format!("warning: {warning}"));
}
if item.has_client_logic {
output.message(
"warning: this item has catalog UI policies or client scripts that the CLI does not run",
);
}
if !item.custom_widgets.is_empty() {
output.message(&format!(
"warning: this item has custom widgets the CLI cannot show or fill ({}); if the order is rejected or incomplete, use the portal",
item.custom_widgets.join(", ")
));
}
let mut plan_json = plan.plan_json();
if checkout {
if !dry_run {
config.require_writable()?;
}
ensure_cart_empty(client).await?;
plan_json["checkout"] = Value::Bool(true);
}
let through_cart = if checkout { " through your cart" } else { "" };
if dry_run {
emit_plan(
output,
&format!(
"order \"{}\" (quantity {}){through_cart}",
plan.item_name, plan.quantity
),
&plan_json,
"variables",
);
return Ok(());
}
config.require_writable()?;
if !yes && !output.json {
outln!(
"Order \"{}\" (quantity {}){through_cart}\n",
plan.item_name,
plan.quantity
);
print_record(&plan_json["variables"], output.color);
}
confirm_destructive(
yes,
format!(
"Submit order for \"{}\" ({} variable(s))?",
plan.item_name,
plan.variables.len()
),
"order cancelled; rerun with --yes to submit without prompting",
)?;
let scrubber = plan.error_scrubber();
let scrub = scrubber
.as_ref()
.map(|scrub| scrub as &dyn Fn(&str) -> String);
if checkout {
let added = client
.add_catalog_item_to_cart(&plan.item_sys_id, &plan.request_body(), scrub)
.await?;
let request = submit_added_item(client, &plan.item_sys_id, &added, scrub).await?;
emit_order_result(client, output, &plan.item_name, request, OrderSource::Cart)
.await?;
} else {
let request = client
.order_catalog_item(&plan.item_sys_id, &plan.request_body(), scrub)
.await?;
emit_order_result(
client,
output,
&plan.item_name,
request,
OrderSource::OrderNow,
)
.await?;
}
}
CatalogCommand::Cart(command) => run_catalog_cart(command, client, config, output).await?,
CatalogCommand::Requests(CatalogRequestsCommand::Mine {
limit,
open,
display_value,
}) => {
let mut query =
"requested_for=javascript:gs.getUserID()^ORopened_by=javascript:gs.getUserID()"
.to_string();
if open {
query.push_str("^active=true");
}
query.push_str("^ORDERBYDESCsys_created_on");
let records = client
.list_records(
"sc_req_item",
&ListOptions {
query: Some(query),
fields: Some(
RITM_LIST_FIELDS
.iter()
.map(|field| (*field).into())
.collect(),
),
limit,
display_value: display_value.unwrap_or_else(|| {
if output.format == OutputFormat::Text {
DisplayValue::True
} else {
DisplayValue::False
}
}),
..ListOptions::default()
},
)
.await?;
let human_fields: Vec<String> =
["number", "cat_item", "stage", "state", "sys_created_on"]
.into_iter()
.map(str::to_string)
.collect();
emit_records_or(
output,
records,
Some(&human_fields),
"No requested items found.",
);
}
CatalogCommand::Requests(CatalogRequestsCommand::Vars {
identifier,
include_empty,
}) => {
let ritm = resolve_requested_item(client, &identifier).await?;
let ritm_sys_id = record_sys_id(&ritm)?.to_string();
let item_sys_id = ritm
.get("cat_item")
.and_then(|cell| cell.get("value").or(Some(cell)))
.and_then(Value::as_str)
.filter(|value| !value.is_empty())
.ok_or_else(|| {
ApiError::InvalidInput(format!(
"{identifier} has no catalog item, so its variables cannot be listed"
))
})?
.to_string();
let item = CatalogItem::from_api(&client.get_catalog_item(&item_sys_id).await?)?;
let names = catalog::readable_variable_names(&item);
let variables = if names.is_empty() {
Vec::new()
} else {
let fields: Vec<String> = names
.iter()
.map(|name| format!("variables.{name}"))
.collect();
let record = client
.get_record(
"sc_req_item",
&ritm_sys_id,
Some(&fields),
DisplayValue::All,
)
.await?;
catalog::ritm_variables(&item, &record)
};
emit_ritm_variables(output, &identifier, &variables, include_empty);
}
}
Ok(())
}
fn catalog_search_row(item: &Value) -> Value {
let class = item
.get("sys_class_name")
.and_then(Value::as_str)
.unwrap_or_default();
serde_json::json!({
"sys_id": item.get("sys_id").cloned().unwrap_or(Value::Null),
"name": item.get("name").cloned().unwrap_or(Value::Null),
"short_description": item.get("short_description").cloned().unwrap_or(Value::Null),
"class": class,
"kind": catalog::kind_label(class),
"orderable": catalog::is_orderable_class(class),
"category": item.get("category").and_then(|category| category.get("title")).cloned().unwrap_or(Value::Null),
})
}
async fn resolve_catalog_item(
client: &ServiceNowClient,
identifier: &str,
allow_search: bool,
) -> Result<CatalogItem, ApiError> {
let identifier = identifier.trim();
if servicenow_cli::api::validate_sys_id(identifier).is_ok() {
return CatalogItem::from_api(
&client
.get_catalog_item(&identifier.to_ascii_lowercase())
.await?,
);
}
const PAGE: usize = 100;
const MAX_RESULTS: usize = 1000;
let mut hits = Vec::new();
loop {
let page = client
.search_catalog_items(Some(identifier), PAGE, hits.len())
.await?;
let full = page.len() == PAGE;
hits.extend(page);
if !full {
break;
}
if hits.len() >= MAX_RESULTS {
return Err(ApiError::Conflict(format!(
"more than {MAX_RESULTS} catalog items match \"{identifier}\", so the name cannot be checked for uniqueness; use the sys_id"
)));
}
}
let exact: Vec<&Value> = hits
.iter()
.filter(|hit| {
hit.get("name")
.and_then(Value::as_str)
.is_some_and(|name| name.eq_ignore_ascii_case(identifier))
})
.collect();
let candidates = |items: &[&Value]| {
items
.iter()
.take(10)
.map(|item| {
format!(
"{} ({}, {})",
item.get("name").and_then(Value::as_str).unwrap_or("?"),
catalog::kind_label(
item.get("sys_class_name")
.and_then(Value::as_str)
.unwrap_or_default()
),
item.get("sys_id").and_then(Value::as_str).unwrap_or("?"),
)
})
.collect::<Vec<_>>()
.join("\n ")
};
let chosen = match exact.as_slice() {
[item] => *item,
[] if allow_search && hits.len() == 1 => &hits[0],
[] if hits.is_empty() => {
return Err(ApiError::NotFound(format!(
"no catalog item matches \"{identifier}\""
)));
}
[] => {
let all: Vec<&Value> = hits.iter().collect();
let hint = if allow_search {
"use a more specific name or the sys_id"
} else {
"orders need the exact item name or sys_id"
};
return Err(ApiError::NotFound(format!(
"no catalog item is named \"{identifier}\"; {hint}. Matches:\n {}",
candidates(&all)
)));
}
several => {
return Err(ApiError::Conflict(format!(
"{} catalog items are named \"{identifier}\"; use the sys_id:\n {}",
several.len(),
candidates(several)
)));
}
};
let sys_id = chosen
.get("sys_id")
.and_then(Value::as_str)
.ok_or_else(|| ApiError::Other("catalog search result omitted sys_id".into()))?;
CatalogItem::from_api(&client.get_catalog_item(sys_id).await?)
}
fn emit_catalog_item(output: &OutputConfig, item: &CatalogItem, site_url: &str) {
let item = &item.redacted();
let portal_url = item.portal_url(site_url);
let orderable = item.ensure_orderable(site_url);
if output.json {
let mut value = serde_json::to_value(item).expect("catalog item is serializable");
value["kind"] = catalog::kind_label(&item.class).into();
value["orderable"] = orderable.is_ok().into();
value["portal_url"] = portal_url.into();
output.value(&serde_json::json!({ "result": value }));
return;
}
outln!("{}", output.heading(&item.name));
if !item.short_description.is_empty() {
outln!("{}", item.short_description);
}
outln!(
"{} ({}) {}\n{}\n",
catalog::kind_label(&item.class),
item.class,
item.sys_id,
portal_url
);
if let Err(reason) = &orderable {
outln!("Not orderable from the CLI: {reason}\n");
}
if item.instance_orderable == Some(false) {
outln!("Note: {}.\n", catalog::INSTANCE_UNORDERABLE);
}
if item.has_client_logic {
outln!(
"Note: this item has client-side logic (UI policies or client scripts) the CLI does not run.\n"
);
}
let empty_sets: Vec<&str> = item
.variables
.iter()
.filter(|variable| {
variable.kind == catalog::VariableKind::MultiRowSet && !variable.mandatory
})
.map(|variable| variable.name.as_str())
.collect();
if orderable.is_ok() && !empty_sets.is_empty() {
outln!(
"Note: the CLI cannot fill multi-row variable sets; these optional ones are left empty when ordering: {}.\n",
empty_sets.join(", ")
);
}
if !item.custom_widgets.is_empty() {
outln!(
"Note: this item has custom widgets the CLI cannot show or fill: {}.\n",
item.custom_widgets.join(", ")
);
}
let rows: Vec<Value> = item
.variables
.iter()
.map(|variable| {
let options = if !variable.choices.is_empty() {
variable
.choices
.iter()
.map(|choice| choice.value.as_str())
.collect::<Vec<_>>()
.join(", ")
} else if let Some(table) = &variable.reference_table {
format!("→ {table}")
} else {
String::new()
};
serde_json::json!({
"name": variable.name,
"label": variable.label,
"type": variable.type_name,
"required": if variable.mandatory { "yes" } else { "" },
"default": variable.default_value.clone().unwrap_or_default(),
"options": options,
})
})
.collect();
let fields: Vec<String> = ["name", "label", "type", "required", "default", "options"]
.into_iter()
.map(str::to_string)
.collect();
print_records_or(
&rows,
Some(&fields),
output.color,
"This item has no variables.",
);
}
async fn run_catalog_cart(
command: CatalogCartCommand,
client: &ServiceNowClient,
config: &Config,
output: &OutputConfig,
) -> Result<(), ApiError> {
match command {
CatalogCartCommand::Show => {
let cart = catalog::Cart::from_api(&client.get_cart().await?)?;
if output.json {
output.value(&cart.to_json());
} else if cart.items.is_empty() {
outln!("Your cart is empty.");
} else {
outln!(
"Cart {} ({} item(s)) {}\n",
cart.cart_id,
cart.items.len(),
client.record_url("sc_cart", &cart.cart_id)
);
print_cart_items(&cart, output);
}
}
CatalogCartCommand::Submit { yes } => {
config.require_writable()?;
let cart = catalog::Cart::from_api(&client.get_cart().await?)?;
if cart.items.is_empty() {
return Err(ApiError::InvalidInput(
"your cart is empty, so there is nothing to submit".into(),
));
}
for item in &cart.items {
if item.can_order == Some(false) {
output.message(&format!(
"warning: the instance reports that \"{}\" cannot be ordered as it is; it may refuse the cart",
item.name
));
}
}
if !yes && !output.json {
print_cart_items(&cart, output);
outln!();
}
confirm_destructive(
yes,
format!("Order the {} item(s) in your cart?", cart.items.len()),
"cart submission cancelled; rerun with --yes to submit without prompting",
)?;
let withhold = |_: &str| WITHHELD_FOR_CART.to_string();
let scrub = if cart_may_hold_secrets(client, &cart).await {
Some(&withhold as &dyn Fn(&str) -> String)
} else {
None
};
ensure_cart_unchanged(client, &cart).await?;
let request = client.submit_cart(scrub).await?;
emit_order_result(
client,
output,
&cart.item_names(),
request,
OrderSource::Cart,
)
.await?;
}
CatalogCartCommand::Remove { cart_item_id, yes } => {
config.require_writable()?;
let cart_item_id = cart_item_id.trim().to_ascii_lowercase();
servicenow_cli::api::validate_sys_id(&cart_item_id)?;
let cart = catalog::Cart::from_api(&client.get_cart().await?)?;
let item = cart.item(&cart_item_id).ok_or_else(|| {
ApiError::NotFound(format!(
"cart item {cart_item_id} is not in your cart; `servicenow catalog cart show` lists what is"
))
})?;
confirm_destructive(
yes,
format!("Remove \"{}\" from your cart?", item.name),
"cart item removal cancelled; rerun with --yes to remove without prompting",
)?;
client.remove_cart_item(&cart_item_id).await?;
if output.json {
output.value(&serde_json::json!({
"removed": true,
"cart_id": cart.cart_id,
"cart_item_id": cart_item_id,
"item_name": item.name,
}));
} else {
outln!("Removed \"{}\" from your cart.", item.name);
}
}
CatalogCartCommand::Clear { yes } => {
config.require_writable()?;
let cart = catalog::Cart::from_api(&client.get_cart().await?)?;
if !cart.items.is_empty() {
confirm_destructive(
yes,
format!("Remove all {} item(s) from your cart?", cart.items.len()),
"cart clearing cancelled; rerun with --yes to clear without prompting",
)?;
ensure_cart_unchanged(client, &cart).await?;
client.empty_cart(&cart.cart_id).await?;
}
if output.json {
output.value(&serde_json::json!({
"cleared": true,
"cart_id": cart.cart_id,
"items_removed": cart.items.len(),
}));
} else if cart.items.is_empty() {
outln!("Your cart is already empty.");
} else {
outln!("Removed {} item(s) from your cart.", cart.items.len());
}
}
}
Ok(())
}
fn print_cart_items(cart: &catalog::Cart, output: &OutputConfig) {
let rows: Vec<Value> = cart
.items
.iter()
.map(|item| {
serde_json::json!({
"item_name": item.name,
"quantity": item.details.get("quantity").cloned().unwrap_or(Value::Null),
"cart_item_id": item.cart_item_id,
})
})
.collect();
let fields: Vec<String> = ["item_name", "quantity", "cart_item_id"]
.into_iter()
.map(str::to_string)
.collect();
print_records_or(&rows, Some(&fields), output.color, "Your cart is empty.");
}
const WITHHELD_FOR_CART: &str = "error message withheld: your cart may hold sensitive values the CLI cannot see, so the message could quote one; open the cart in the portal to see why";
async fn cart_may_hold_secrets(client: &ServiceNowClient, cart: &catalog::Cart) -> bool {
let mut ids = BTreeSet::new();
for item in &cart.items {
match &item.catalog_item_id {
Some(id) => {
ids.insert(id.clone());
}
None => return true,
}
}
for id in ids {
let sensitive = match client.get_catalog_item(&id).await {
Ok(value) => catalog::CatalogItem::from_api(&value).map_or(true, |item| {
item.variables.iter().any(|variable| {
variable.is_sensitive() || variable.kind == catalog::VariableKind::MultiRowSet
})
}),
Err(_) => true,
};
if sensitive {
return true;
}
}
false
}
async fn ensure_cart_empty(client: &ServiceNowClient) -> Result<(), ApiError> {
let cart = catalog::Cart::from_api(&client.get_cart().await?)?;
if cart.items.is_empty() {
return Ok(());
}
Err(ApiError::Conflict(format!(
"your cart already holds {} item(s) ({}), and --checkout submits the whole cart, so they would be ordered too; review it with `servicenow catalog cart show`, then order it with `servicenow catalog cart submit` or empty it with `servicenow catalog cart clear`",
cart.items.len(),
cart.item_names()
)))
}
async fn submit_added_item(
client: &ServiceNowClient,
item_sys_id: &str,
added: &Value,
scrub: Option<&dyn Fn(&str) -> String>,
) -> Result<Value, ApiError> {
let cart = catalog::Cart::from_api(added).map_err(|error| {
ApiError::Other(format!(
"the item was added to your cart, but the answer could not be read ({error}); nothing was ordered, so check `servicenow catalog cart show` before retrying"
))
})?;
let left_in_cart = |reason: String| ApiError::NotOrdered {
message: format!(
"{reason}; nothing was ordered, and the item is still in your cart {} ({})",
cart.cart_id,
client.record_url("sc_cart", &cart.cart_id)
),
cart_id: cart.cart_id.clone(),
};
if cart.items.is_empty() {
return Err(ApiError::Other(format!(
"the instance accepted the item for cart {} but listed no items in it; {}",
cart.cart_id,
servicenow_cli::api::MAY_HAVE_ADDED_TO_CART
)));
}
if let [only] = cart.items.as_slice()
&& only
.catalog_item_id
.as_deref()
.is_some_and(|id| !id.eq_ignore_ascii_case(item_sys_id))
{
return Err(left_in_cart(format!(
"your cart changed while the item was added and now holds \"{}\" instead, so it was not submitted",
only.name
)));
}
if cart.items.len() != 1 {
return Err(left_in_cart(format!(
"your cart changed while the item was added and now holds {} item(s) ({}), so it was not submitted",
cart.items.len(),
cart.item_names()
)));
}
match client.submit_cart(scrub).await {
Ok(request) => Ok(request),
Err(error @ (ApiError::Other(_) | ApiError::Api { status: 500.., .. })) => Err(error),
Err(error) => {
let added_id = &cart.items[0].cart_item_id;
let still_there = match client.get_cart().await {
Ok(answer) => {
catalog::Cart::from_api(&answer).is_ok_and(|now| now.item(added_id).is_some())
}
Err(_) => false,
};
if still_there {
Err(left_in_cart(format!(
"the item was added to your cart, but submitting the cart failed ({error})"
)))
} else {
Err(ApiError::Other(format!(
"submitting the cart failed ({error}), and the added item is no longer in your cart, so it may have been ordered or removed elsewhere; check `servicenow catalog requests mine` and `servicenow catalog cart show` before ordering again"
)))
}
}
}
}
async fn ensure_cart_unchanged(
client: &ServiceNowClient,
confirmed: &catalog::Cart,
) -> Result<(), ApiError> {
let now = catalog::Cart::from_api(&client.get_cart().await?)?;
if now.fingerprint() != confirmed.fingerprint() {
return Err(ApiError::Conflict(format!(
"your cart changed after it was read (it now holds {} item(s): {}); nothing was changed, so review it with `servicenow catalog cart show` and run the command again",
now.items.len(),
if now.items.is_empty() {
"none".to_string()
} else {
now.item_names()
}
)));
}
Ok(())
}
#[derive(Clone, Copy)]
enum OrderSource {
OrderNow,
Cart,
}
async fn emit_order_result(
client: &ServiceNowClient,
output: &OutputConfig,
item_name: &str,
request: Value,
source: OrderSource,
) -> Result<(), ApiError> {
let (request_id, request_label) = match catalog::OrderOutcome::classify(&request) {
catalog::OrderOutcome::Request { sys_id, number } => {
let label = number.unwrap_or_else(|| format!("request {sys_id}"));
(sys_id, label)
}
catalog::OrderOutcome::CartOnly { cart_id } => {
let cart_url = client.record_url("sc_cart", &cart_id);
let message = match source {
OrderSource::OrderNow => format!(
"the instance accepted the order but created no request; the item was left in cart {cart_id} ({cart_url}) instead, and the instance may also have put a copy in your portal cart. This usually means the instance needs a separate checkout step (`servicenow catalog order --checkout` orders through the cart), or the item cannot be ordered through the API. Nothing was ordered."
),
OrderSource::Cart => {
return Err(ApiError::Other(format!(
"the instance answered the cart submission with cart {cart_id} ({cart_url}) instead of a request, so it is unclear whether anything was ordered; check `servicenow catalog requests mine` and `servicenow catalog cart show` before submitting again"
)));
}
};
return Err(ApiError::NotOrdered { message, cart_id });
}
catalog::OrderOutcome::Unrecognized { keys, number } => {
let fields = if keys.is_empty() {
"no fields".to_string()
} else {
format!("fields: {}", keys.join(", "))
};
let named = number
.map(|number| format!(", though it named request {number}"))
.unwrap_or_default();
return Err(ApiError::Other(format!(
"the instance answered the order with neither a request id nor a cart ({fields}){named}; {}",
servicenow_cli::api::MAY_HAVE_ORDERED
)));
}
};
let requested_items = match client
.list_records(
"sc_req_item",
&ListOptions {
query: Some(format!("request={request_id}")),
fields: Some(
RITM_LIST_FIELDS
.iter()
.map(|field| (*field).into())
.collect(),
),
limit: 100,
display_value: DisplayValue::False,
..ListOptions::default()
},
)
.await
{
Ok(items) => Some(items),
Err(error) => {
output.message(&format!(
"warning: the order was placed, but its requested items could not be read ({error}); do not reorder, check `servicenow catalog requests mine`"
));
None
}
};
let numbers: Vec<&str> = requested_items
.iter()
.flatten()
.filter_map(|item| item.get("number").and_then(Value::as_str))
.collect();
if numbers.is_empty() {
output.success(&format!("Ordered {item_name}: {request_label}"));
if requested_items.is_some() {
output.message("No requested items were found for this request yet; check `servicenow catalog requests mine`.");
}
} else {
output.success(&format!(
"Ordered {item_name}: {request_label} / {}",
numbers.join(", ")
));
}
if output.json {
output.value(&serde_json::json!({
"request": request,
"requestedItems": requested_items,
}));
} else {
outln!(
"{request_label} {}",
client.record_url("sc_request", &request_id)
);
for item in requested_items.iter().flatten() {
if let (Some(number), Some(sys_id)) = (
item.get("number").and_then(Value::as_str),
item.get("sys_id").and_then(Value::as_str),
) {
outln!("{number} {}", client.record_url("sc_req_item", sys_id));
}
}
}
Ok(())
}
async fn resolve_requested_item(
client: &ServiceNowClient,
identifier: &str,
) -> Result<Value, ApiError> {
let identifier = identifier.trim();
let fields: Vec<String> = ["sys_id", "number", "cat_item", "sys_created_on"]
.into_iter()
.map(str::to_string)
.collect();
if servicenow_cli::api::validate_sys_id(identifier).is_ok() {
return client
.get_record("sc_req_item", identifier, Some(&fields), DisplayValue::All)
.await;
}
if identifier.is_empty() || !identifier.bytes().all(|byte| byte.is_ascii_alphanumeric()) {
return Err(ApiError::InvalidInput(format!(
"invalid requested item '{identifier}'; give a RITM number or sys_id"
)));
}
let records = client
.list_records(
"sc_req_item",
&ListOptions {
query: Some(format!("number={identifier}")),
fields: Some(fields),
limit: 10,
display_value: DisplayValue::All,
..ListOptions::default()
},
)
.await?;
match records.as_slice() {
[] => Err(ApiError::NotFound(format!("requested item {identifier}"))),
[record] => Ok(record.clone()),
several => Err(ApiError::Conflict(format!(
"{} requested items are numbered {identifier}; use the sys_id:\n {}",
several.len(),
several
.iter()
.map(|record| {
let cell = |field: &str| {
record
.get(field)
.and_then(|cell| cell.get("display_value").or(Some(cell)))
.and_then(Value::as_str)
.unwrap_or("?")
.to_string()
};
let sys_id = record_sys_id(record).unwrap_or("?");
format!(
"{sys_id} ({}, created {})",
cell("cat_item"),
cell("sys_created_on")
)
})
.collect::<Vec<_>>()
.join("\n ")
))),
}
}
fn emit_ritm_variables(
output: &OutputConfig,
identifier: &str,
variables: &[catalog::RitmVariable],
include_empty: bool,
) {
let shown: Vec<&catalog::RitmVariable> = variables
.iter()
.filter(|variable| {
include_empty || !variable.value.is_empty() || (output.json && variable.has_default)
})
.collect();
let withheld: Vec<&str> = shown
.iter()
.filter(|variable| variable.sensitive)
.map(|variable| variable.name.as_str())
.collect();
if output.json {
if !withheld.is_empty() {
output.message(&format!(
"Omitted sensitive variable(s) {}; supply them yourself with --vars-file.",
withheld.join(", ")
));
}
let read_only: Vec<&str> = shown
.iter()
.filter(|variable| variable.read_only && !variable.sensitive)
.map(|variable| variable.name.as_str())
.collect();
if !read_only.is_empty() {
output.message(&format!(
"Omitted read-only variable(s) {}, which the form fills itself; see them with --output text.",
read_only.join(", ")
));
}
let reusable: Vec<&&catalog::RitmVariable> = shown
.iter()
.filter(|variable| !variable.sensitive && !variable.read_only)
.collect();
let unplaced: Vec<&str> = reusable
.iter()
.filter(|variable| variable.order_value.is_none())
.map(|variable| variable.name.as_str())
.collect();
if !unplaced.is_empty() {
output.message(&format!(
"Omitted variable(s) {}: the instance returned them without a value in your time zone; see them with --output text.",
unplaced.join(", ")
));
}
let values: Map<String, Value> = reusable
.iter()
.filter_map(|variable| {
let value = variable.order_value.clone()?;
Some((variable.name.clone(), Value::String(value)))
})
.collect();
output.value(&Value::Object(values));
return;
}
let rows: Vec<Value> = shown
.iter()
.map(|variable| {
let display = if variable.sensitive {
servicenow_cli::sensitive::REDACTED.to_string()
} else {
variable.display_value.clone()
};
serde_json::json!({
"name": variable.name,
"label": variable.label,
"value": display,
})
})
.collect();
let fields: Vec<String> = ["name", "label", "value"]
.into_iter()
.map(str::to_string)
.collect();
print_records_or(
&rows,
Some(&fields),
output.color,
&format!("{identifier} has no variable values."),
);
}
fn read_file_or_stdin(path: &std::path::Path, label: &str) -> Result<String, ApiError> {
if path == std::path::Path::new("-") {
let mut value = String::new();
std::io::stdin()
.read_to_string(&mut value)
.map_err(|error| {
ApiError::Other(format!("failed to read {label} from stdin: {error}"))
})?;
Ok(value)
} else {
std::fs::read_to_string(path).map_err(|error| {
ApiError::Other(format!(
"failed to read {label} from {}: {error}",
path.display()
))
})
}
}
fn emit_mutation_plan(
output: &OutputConfig,
operation: &str,
identifier: &str,
body: &Map<String, Value>,
) {
let plan = serde_json::json!({
"dryRun": true,
"operation": operation,
"table": "incident",
"incident": identifier,
"changes": body,
});
emit_plan(
output,
&format!("{operation} {identifier}"),
&plan,
"changes",
);
}
fn emit_plan(output: &OutputConfig, summary: &str, plan: &Value, detail_key: &str) {
if output.json {
output.value(plan);
} else {
outln!("Dry run: {summary}\n");
print_record(&plan[detail_key], output.color);
}
}
fn emit_watch_event(
output: &OutputConfig,
identifier: &str,
poll: usize,
changes: &[Value],
initial: Option<&Value>,
) {
let event = serde_json::json!({
"event": if initial.is_some() { "snapshot" } else { "change" },
"incident": identifier,
"poll": poll,
"changes": changes,
"record": initial,
});
match output.format {
OutputFormat::Json | OutputFormat::JsonLines => outln!(
"{}",
serde_json::to_string(&event).expect("watch event is serializable")
),
OutputFormat::Yaml => out!(
"---\n{}",
serde_saphyr::to_string(&event).expect("watch event is serializable")
),
OutputFormat::Text => {
if let Some(record) = initial {
outln!("Watching {identifier}. Press Ctrl-C to stop.\n");
print_record(record, output.color);
} else {
outln!("\n{} changed", output.heading(identifier));
print_records(
changes,
Some(&["field".into(), "before".into(), "after".into()]),
output.color,
);
}
}
OutputFormat::Csv => unreachable!("CSV watch output is rejected before polling"),
}
}
async fn run_attachments(
command: AttachmentsCommand,
client: &ServiceNowClient,
config: &Config,
output: &OutputConfig,
) -> Result<(), ApiError> {
match command {
AttachmentsCommand::List {
table,
record: identifier,
limit,
all,
} => {
let record = record::resolve(
client,
&table,
&identifier,
Some(vec!["sys_id".into(), "number".into()]),
DisplayValue::False,
)
.await?;
let sys_id = record_sys_id(&record)?;
let attachments = client.list_attachments(&table, sys_id, limit, all).await?;
emit_attachments(output, attachments)?;
}
AttachmentsCommand::Upload {
table,
record: identifier,
file,
name,
content_type,
dry_run,
} => {
if !dry_run {
config.require_writable()?;
}
let metadata = std::fs::metadata(&file).map_err(|error| {
ApiError::InvalidInput(format!(
"cannot read attachment {}: {error}",
file.display()
))
})?;
if !metadata.is_file() {
return Err(ApiError::InvalidInput(format!(
"attachment source is not a regular file: {}",
file.display()
)));
}
std::fs::File::open(&file).map_err(|error| {
ApiError::InvalidInput(format!(
"cannot open attachment {}: {error}",
file.display()
))
})?;
let file_name = attachment::upload_file_name(&file, name.as_deref())?;
let content_type = attachment::content_type(&file, content_type.as_deref())?;
let record = record::resolve(
client,
&table,
&identifier,
Some(vec!["sys_id".into(), "number".into()]),
DisplayValue::False,
)
.await?;
let table_sys_id = record_sys_id(&record)?;
if dry_run {
let plan = serde_json::json!({
"dryRun": true,
"operation": "upload_attachment",
"table": table,
"record": identifier,
"tableSysId": table_sys_id,
"file": file,
"fileName": file_name,
"contentType": content_type,
"sizeBytes": metadata.len(),
});
if output.json {
output.value(&plan);
} else {
outln!("Dry run: upload {file_name} to {table}/{identifier}\n");
print_record(&plan, output.color);
}
return Ok(());
}
let uploaded = client
.upload_attachment_file(&table, table_sys_id, &file_name, &content_type, &file)
.await?;
output.success(&format!(
"Uploaded {file_name} ({}) to {table}/{identifier}.",
uploaded
.size_bytes
.as_deref()
.map(attachment::human_size)
.unwrap_or_else(|| "n/a".into())
));
emit_attachment(output, uploaded)?;
}
AttachmentsCommand::Download {
attachment: identifier,
destination,
force,
} => {
let sys_id = record::attachment_sys_id(client.site_url(), &identifier)?;
let metadata = client.get_attachment(&sys_id).await?;
let file_name = metadata.file_name.as_deref().ok_or_else(|| {
ApiError::Other("ServiceNow attachment response omitted file_name".into())
})?;
let destination = attachment::destination_path(destination.as_deref(), file_name)?;
if destination == std::path::Path::new("-") {
let bytes = client
.download_attachment(&sys_id, &mut output::Stdout)
.await?;
output.message(&format!(
"Downloaded {file_name} ({}) to stdout.",
attachment::human_size(&bytes.to_string())
));
return Ok(());
}
if destination.exists() && !force {
return Err(ApiError::Conflict(format!(
"{} already exists; use --force to replace it",
destination.display()
)));
}
let parent = destination
.parent()
.filter(|path| !path.as_os_str().is_empty())
.unwrap_or_else(|| std::path::Path::new("."));
if !parent.is_dir() {
return Err(ApiError::InvalidInput(format!(
"destination directory does not exist: {}",
parent.display()
)));
}
let mut temporary = tempfile::NamedTempFile::new_in(parent).map_err(|error| {
ApiError::Other(format!(
"failed to create a temporary download in {}: {error}",
parent.display()
))
})?;
let bytes = client.download_attachment(&sys_id, &mut temporary).await?;
temporary.as_file().sync_all().map_err(|error| {
ApiError::Other(format!("failed to sync downloaded attachment: {error}"))
})?;
if force {
temporary.persist(&destination).map_err(|error| {
ApiError::Other(format!(
"failed to save attachment to {}: {}",
destination.display(),
error.error
))
})?;
} else {
temporary.persist_noclobber(&destination).map_err(|error| {
ApiError::Conflict(format!(
"could not save {} without replacing a file: {}",
destination.display(),
error.error
))
})?;
}
let result = serde_json::json!({
"downloaded": true,
"attachment": sys_id,
"fileName": metadata.file_name,
"contentType": metadata.content_type,
"path": destination,
"sizeBytes": bytes,
});
output.success(&format!(
"Downloaded {} ({}) to {}.",
result["fileName"].as_str().unwrap_or("attachment"),
attachment::human_size(&bytes.to_string()),
destination.display()
));
if output.json {
output.value(&result);
} else {
outln!("{}", destination.display());
}
}
AttachmentsCommand::Delete {
attachment: identifier,
yes,
dry_run,
} => {
if !dry_run {
config.require_writable()?;
}
let sys_id = record::attachment_sys_id(client.site_url(), &identifier)?;
let metadata = client.get_attachment(&sys_id).await?;
if dry_run {
let plan = serde_json::json!({
"dryRun": true,
"operation": "delete_attachment",
"attachment": sys_id,
"fileName": metadata.file_name,
"table": metadata.table_name,
"tableSysId": metadata.table_sys_id,
"sizeBytes": metadata.size_bytes,
});
if output.json {
output.value(&plan);
} else {
outln!(
"Dry run: permanently delete {}\n",
metadata.file_name.as_deref().unwrap_or("n/a")
);
print_record(&plan, output.color);
}
return Ok(());
}
confirm_destructive(
yes,
format!(
"Permanently delete '{}' ({})?",
metadata.file_name.as_deref().unwrap_or("n/a"),
metadata
.size_bytes
.as_deref()
.map(attachment::human_size)
.unwrap_or_else(|| "n/a".into())
),
"attachment deletion cancelled; use --yes for non-interactive deletion",
)?;
client.delete_attachment(&sys_id).await?;
let result = serde_json::json!({
"deleted": true,
"attachment": sys_id,
"fileName": metadata.file_name,
"table": metadata.table_name,
"tableSysId": metadata.table_sys_id,
});
output.success(&format!(
"Deleted attachment {}.",
result["fileName"].as_str().unwrap_or("attachment")
));
if output.json {
output.value(&result);
} else {
outln!(
"Deleted {}.",
result["fileName"].as_str().unwrap_or("attachment")
);
}
}
}
Ok(())
}
fn emit_attachments(
output: &OutputConfig,
attachments: Vec<servicenow_cli::api::AttachmentMetadata>,
) -> Result<(), ApiError> {
let mut records = attachments
.into_iter()
.map(serde_json::to_value)
.collect::<Result<Vec<_>, _>>()
.map_err(|error| {
ApiError::Other(format!("failed to encode attachment metadata: {error}"))
})?;
if output.json {
emit_records(output, records, None);
} else {
for record in &mut records {
if let Some(object) = record.as_object_mut() {
let size = object
.get("size_bytes")
.and_then(Value::as_str)
.map(attachment::human_size)
.unwrap_or_else(|| "n/a".into());
object.insert("size".into(), Value::String(size));
render_missing_attachment_fields_as_na(object);
}
}
let fields = [
"file_name".into(),
"content_type".into(),
"size".into(),
"sys_created_by".into(),
"sys_created_on".into(),
"sys_id".into(),
];
print_records(&records, Some(&fields), output.color);
}
Ok(())
}
fn emit_attachment(
output: &OutputConfig,
attachment: servicenow_cli::api::AttachmentMetadata,
) -> Result<(), ApiError> {
let mut record = serde_json::to_value(attachment).map_err(|error| {
ApiError::Other(format!("failed to encode attachment metadata: {error}"))
})?;
if !output.json
&& let Some(object) = record.as_object_mut()
{
render_missing_attachment_fields_as_na(object);
}
emit_record(output, record);
Ok(())
}
fn render_missing_attachment_fields_as_na(object: &mut serde_json::Map<String, Value>) {
for value in object.values_mut() {
if value.is_null() {
*value = Value::String("n/a".into());
}
}
}
async fn run_tables(
command: TablesCommand,
client: &ServiceNowClient,
config: &Config,
output: &OutputConfig,
) -> Result<(), ApiError> {
match command {
TablesCommand::List {
table,
query,
fields,
limit,
offset,
all,
display_value,
} => {
let fields = parse_fields(fields.as_deref());
let records = client
.list_records(
&table,
&ListOptions {
query,
fields: fields.clone(),
limit,
offset,
all,
display_value,
},
)
.await?;
emit_records(output, records, fields.as_deref());
}
TablesCommand::Get {
table,
sys_id,
fields,
display_value,
} => {
let fields = parse_fields(fields.as_deref());
let record = client
.get_record(&table, &sys_id, fields.as_deref(), display_value)
.await?;
emit_record(output, record);
}
TablesCommand::Create {
table,
data,
fields,
} => {
config.require_writable()?;
let body = build_body(data.as_deref(), &fields)?;
let record = client.create_record(&table, &body).await?;
output.message("Record created.");
emit_record(output, record);
}
TablesCommand::Update {
table,
sys_id,
data,
fields,
} => {
config.require_writable()?;
let body = build_body(data.as_deref(), &fields)?;
let record = client.update_record(&table, &sys_id, &body).await?;
output.message("Record updated.");
emit_record(output, record);
}
TablesCommand::Delete { table, sys_id, yes } => {
config.require_writable()?;
confirm_destructive(
yes,
format!("Permanently delete {table}/{sys_id}?"),
"table record deletion cancelled; use --yes for non-interactive deletion",
)?;
client.delete_record(&table, &sys_id).await?;
let result = serde_json::json!({
"deleted": true,
"table": table,
"sys_id": sys_id,
});
if output.json {
output.value(&result);
} else {
outln!("Deleted {table}/{sys_id}.");
}
}
}
Ok(())
}
async fn resolve_incident(
client: &ServiceNowClient,
identifier: &str,
fields: Option<Vec<String>>,
display_value: DisplayValue,
) -> Result<Value, ApiError> {
record::resolve(client, "incident", identifier, fields, display_value).await
}
fn emit_records(output: &OutputConfig, records: Vec<Value>, fields: Option<&[String]>) {
emit_records_or(output, records, fields, "No records found.");
}
fn emit_records_or(
output: &OutputConfig,
records: Vec<Value>,
fields: Option<&[String]>,
empty_message: &str,
) {
if output.json {
output.value(&serde_json::json!({
"count": records.len(),
"result": records,
}));
} else {
print_records_or(&records, fields, output.color, empty_message);
}
}
fn emit_record(output: &OutputConfig, record: Value) {
if output.json {
output.value(&serde_json::json!({ "result": record }));
} else {
print_record(&record, output.color);
}
}
fn combine_query(first: Option<&str>, second: Option<&str>) -> Option<String> {
match (
first.filter(|value| !value.is_empty()),
second.filter(|value| !value.is_empty()),
) {
(Some(first), Some(second)) => Some(format!("{first}^{second}")),
(Some(value), None) | (None, Some(value)) => Some(value.to_string()),
(None, None) => None,
}
}
fn insert(body: &mut Map<String, Value>, name: &str, value: Option<String>) {
if let Some(value) = value {
body.insert(name.into(), Value::String(value));
}
}
fn field_text(record: &Value, field: &str) -> Option<String> {
let value = record.get(field)?;
match value {
Value::String(value) => Some(value.clone()),
Value::Bool(value) => Some(value.to_string()),
Value::Number(value) => Some(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),
_ => None,
}
}
fn mask_secret(secret: &str) -> String {
if secret.chars().count() <= 4 {
"****".into()
} else {
let suffix: String = secret
.chars()
.rev()
.take(4)
.collect::<String>()
.chars()
.rev()
.collect();
format!("***{suffix}")
}
}
fn command_document(command: &clap::Command, selected_path: Option<&str>) -> Value {
let path = selected_path.unwrap_or(command.get_name());
let mut schema = command_schema(command, path);
let object = schema
.as_object_mut()
.expect("command schema is always an object");
object.insert("schemaVersion".into(), Value::String("1.0".into()));
object.insert(
"outputContract".into(),
serde_json::json!({
"default": "human table on a terminal; JSON when piped",
"listEnvelope": {"count": "integer", "result": "array"},
"recordEnvelope": {"result": "object"},
"errorEnvelope": {"error": {
"kind": "string", "message": "string", "remediation": "string|null",
"cart": "{sys_id: string}, only with kind not_ordered"
}},
"streams": {"stdout": "data", "stderr": "status and errors"},
"exitCodes": {
"0": "success", "1": "unexpected", "2": "invalid_input", "3": "auth or permission",
"4": "not_found", "5": "api_error", "6": "rate_limit", "7": "conflict",
"8": "not_ordered"
}
}),
);
schema
}
fn find_command<'a>(root: &'a clap::Command, path: &str) -> Result<&'a clap::Command, ApiError> {
let mut command = root;
let mut parts = path.split_whitespace().peekable();
if parts.peek().is_none() {
return Err(ApiError::InvalidInput("--command cannot be empty".into()));
}
if parts.peek().copied() == Some(root.get_name()) {
parts.next();
}
for part in parts {
command = command.find_subcommand(part).ok_or_else(|| {
ApiError::NotFound(format!(
"command '{path}'; inspect available commands with `servicenow schema`"
))
})?;
}
Ok(command)
}
fn command_schema(command: &clap::Command, path: &str) -> Value {
let args: Vec<Value> = command
.get_arguments()
.filter(|arg| arg.get_id() != "help" && arg.get_id() != "version")
.map(|arg| {
let range = arg.get_num_args();
let takes_value = !matches!(
arg.get_action(),
clap::ArgAction::SetTrue | clap::ArgAction::SetFalse | clap::ArgAction::Count
);
let minimum = range
.map(|range| range.min_values())
.unwrap_or(usize::from(takes_value && arg.is_required_set()));
let max_values = range
.and_then(|range| {
(range.max_values() != usize::MAX).then_some(range.max_values())
})
.or(takes_value.then_some(1));
let possible_values: Vec<String> = arg
.get_possible_values()
.into_iter()
.map(|value| value.get_name().to_string())
.collect();
let default_values: Vec<String> = arg
.get_default_values()
.iter()
.map(|value| value.to_string_lossy().into_owned())
.collect();
serde_json::json!({
"id": arg.get_id().as_str(),
"long": arg.get_long(),
"short": arg.get_short().map(|value| value.to_string()),
"required": arg.is_required_set(),
"help": arg.get_help().map(|value| value.to_string()),
"type": argument_type(arg, &possible_values),
"action": argument_action(arg.get_action()),
"valueCardinality": {
"minimum": minimum,
"maximum": max_values,
},
"defaultValues": default_values,
"possibleValues": possible_values,
"repeatable": matches!(arg.get_action(), clap::ArgAction::Append | clap::ArgAction::Count),
"global": arg.is_global_set(),
"environment": arg.get_env().map(|value| value.to_string_lossy().into_owned()),
"valueHint": format!("{:?}", arg.get_value_hint()).to_lowercase(),
"dynamicDefault": argument_dynamic_default(path, arg.get_id().as_str()),
})
})
.collect();
let commands: Vec<Value> = command
.get_subcommands()
.map(|subcommand| {
let subcommand_path = format!("{path} {}", subcommand.get_name());
command_schema(subcommand, &subcommand_path)
})
.collect();
serde_json::json!({
"name": command.get_name(),
"path": path,
"about": command.get_about().map(|value| value.to_string()),
"arguments": args,
"argumentGroups": command_argument_groups(path),
"commands": commands,
"behavior": command_behavior(path),
})
}
fn command_argument_groups(path: &str) -> Vec<Value> {
if path.ends_with("incidents resolve") {
vec![serde_json::json!({
"id": "resolution_notes",
"arguments": ["notes", "notes_file"],
"required": true,
"multiple": false,
})]
} else {
Vec::new()
}
}
fn argument_dynamic_default(path: &str, argument: &str) -> Option<&'static str> {
if argument == "display_value" {
return Some("display values for text output; raw values for machine output");
}
if path.ends_with("incidents resolve") && argument == "state" {
return Some(
"the configured Resolved choice; standard value 6 when choices are unavailable",
);
}
if path.ends_with("init") || path.ends_with("auth login") {
return match argument {
"instance" => Some("saved profile value when resuming; otherwise prompted"),
"method" => Some(
"saved profile value when resuming; otherwise detected from the instance login route",
),
"scope" => Some("saved profile value when resuming; otherwise useraccount"),
"redirect_uri" => {
Some("saved profile value when resuming; otherwise http://127.0.0.1:8484/callback")
}
_ => None,
};
}
None
}
fn argument_type(arg: &clap::Arg, possible_values: &[String]) -> &'static str {
match arg.get_action() {
clap::ArgAction::SetTrue | clap::ArgAction::SetFalse => "boolean",
clap::ArgAction::Count => "integer",
_ if !possible_values.is_empty() => "enum",
_ if matches!(
arg.get_id().as_str(),
"limit" | "offset" | "interval" | "count"
) =>
{
"integer"
}
_ => "string",
}
}
fn argument_action(action: &clap::ArgAction) -> &'static str {
match action {
clap::ArgAction::Set => "set",
clap::ArgAction::Append => "append",
clap::ArgAction::SetTrue => "set_true",
clap::ArgAction::SetFalse => "set_false",
clap::ArgAction::Count => "count",
clap::ArgAction::Help => "help",
clap::ArgAction::HelpShort => "help_short",
clap::ArgAction::HelpLong => "help_long",
clap::ArgAction::Version => "version",
_ => "other",
}
}
fn command_behavior(path: &str) -> Value {
let remote_mutations = [
"tui",
"incidents create",
"incidents update",
"incidents resolve",
"incidents edit",
"incidents note",
"incidents assign",
"attachments upload",
"attachments delete",
"tables create",
"tables update",
"tables delete",
"catalog order",
"catalog cart submit",
"catalog cart remove",
"catalog cart clear",
];
let local_mutations = [
"init",
"auth login",
"auth logout",
"profile use",
"profile remove",
"attachments download",
];
let mutation = remote_mutations.iter().any(|suffix| path.ends_with(suffix))
|| local_mutations.iter().any(|suffix| path.ends_with(suffix));
let remote_mutation = remote_mutations.iter().any(|suffix| path.ends_with(suffix));
let local_mutation = local_mutations.iter().any(|suffix| path.ends_with(suffix));
let side_effect = if path.ends_with("init") || path.ends_with("auth login") {
"local_and_remote"
} else if remote_mutation {
"remote"
} else if local_mutation {
"local"
} else {
"none"
};
let network_access = if path == "servicenow"
|| path == "auth"
|| path == "schema"
|| path == "doctor"
|| path.ends_with(" auth")
|| path.ends_with(" schema")
|| path.ends_with("auth status")
{
"conditional"
} else if path == "profile"
|| path == "config"
|| path.ends_with(" profile")
|| path.ends_with(" config")
|| path.ends_with("completions")
|| path.ends_with("profile list")
|| path.ends_with("profile use")
|| path.ends_with("profile remove")
|| path.ends_with("auth logout")
|| path.ends_with("config show")
|| path.ends_with("config init")
|| path.ends_with("config path")
{
"none"
} else {
"required"
};
let destructive = path.ends_with("attachments delete")
|| path.ends_with("tables delete")
|| path.ends_with("catalog cart remove")
|| path.ends_with("catalog cart clear")
|| path.ends_with("profile remove");
let requires_confirmation = destructive
|| path.ends_with("incidents edit")
|| path.ends_with("catalog order")
|| path.ends_with("catalog cart submit")
|| path.ends_with("tui");
let supports_dry_run = [
"catalog order",
"incidents resolve",
"incidents edit",
"incidents note",
"incidents assign",
"attachments upload",
"attachments delete",
]
.iter()
.any(|suffix| path.ends_with(suffix));
serde_json::json!({
"sideEffect": side_effect,
"networkAccess": network_access,
"mutation": mutation,
"destructive": destructive,
"requiresConfirmation": requires_confirmation,
"supportsDryRun": supports_dry_run,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn raw_flags(args: &[&str]) -> (String, bool) {
let args: Vec<std::ffi::OsString> = std::iter::once("servicenow")
.chain(args.iter().copied())
.map(Into::into)
.collect();
raw_output_flags(&args)
}
#[test]
fn raw_output_flags_recognize_every_spelling_clap_accepts() {
for spelling in [
&["--output", "yaml"][..],
&["--output=yaml"],
&["-o", "yaml"],
&["-oyaml"],
&["-o=yaml"],
] {
assert_eq!(raw_flags(spelling), ("yaml".into(), false), "{spelling:?}");
}
assert_eq!(raw_flags(&["--json", "bogus"]), ("auto".into(), true));
assert_eq!(raw_flags(&["bogus"]), ("auto".into(), false));
}
#[test]
fn raw_output_flags_ignore_positional_values_after_the_separator() {
assert_eq!(
raw_flags(&["-o", "text", "tables", "get", "--", "-ojson", "--json"]),
("text".into(), false)
);
}
#[test]
fn explicit_formats_decide_error_rendering_regardless_of_the_json_alias() {
assert!(machine_readable_errors("csv", false));
assert!(!machine_readable_errors("text", true));
assert!(!machine_readable_errors("table", true));
assert!(machine_readable_errors("auto", true));
}
#[test]
fn tui_recovers_only_connection_and_authentication_failures() {
assert!(tui_login_recoverable(&ApiError::InvalidInput(
"No ServiceNow instance configured. Run `servicenow init`.".into()
)));
assert!(tui_login_recoverable(&ApiError::NotFound(
"config profile 'work'. Available: none defined".into()
)));
assert!(tui_login_recoverable(&ApiError::Auth(
"browser session expired".into()
)));
assert!(!tui_login_recoverable(&ApiError::InvalidInput(
"invalid table name".into()
)));
assert!(!tui_login_recoverable(&ApiError::RateLimit));
}
#[test]
fn tui_connection_copy_removes_dead_end_command_instructions() {
let reason = tui_connection_reason(&ApiError::InvalidInput(
"No access token configured. Run `servicenow init`.".into(),
));
assert_eq!(
reason,
"This profile does not have a usable credential yet."
);
assert!(!reason.contains("servicenow init"));
}
}