2a91e2b083
Pure move: cli definition, per-group handlers (session, bulk, bench, events, galaxy, smoke, batch) and shared output/parse/connect helpers now live in their own modules. No behaviour or CLI surface change; --help of all 33 commands is byte-identical, clippy clean, tests unchanged. Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
250 lines
8.3 KiB
Rust
250 lines
8.3 KiB
Rust
//! Argument and value parsing helpers (typed values, RFC3339 timestamps, credentials).
|
|
|
|
use std::env;
|
|
|
|
use zb_mom_ww_mxgateway_client::{Error, MxValue};
|
|
|
|
use crate::cli::*;
|
|
|
|
/// Resolves the `authenticate-user` credential from `--password`, falling back to
|
|
/// the environment variable named by `--password-env` (default
|
|
/// `MXGATEWAY_VERIFY_PASSWORD`).
|
|
///
|
|
/// An empty value from either source counts as missing (CLI-45): the CLI fails
|
|
/// fast with a usage error rather than sending a fabricated empty credential to
|
|
/// the wire. The error names the flag and the variable only — never the value,
|
|
/// which is never echoed to stdout/stderr or embedded in an error message.
|
|
pub(crate) fn resolve_verify_user_password(
|
|
password: Option<String>,
|
|
password_env: &str,
|
|
) -> Result<String, Error> {
|
|
password
|
|
.filter(|value| !value.is_empty())
|
|
.or_else(|| {
|
|
env::var(password_env)
|
|
.ok()
|
|
.filter(|value| !value.is_empty())
|
|
})
|
|
.ok_or_else(|| Error::InvalidArgument {
|
|
name: "password".to_owned(),
|
|
detail: format!("supply --password or set the environment variable `{password_env}`"),
|
|
})
|
|
}
|
|
|
|
pub(crate) fn parse_value(value_type: CliValueType, value: &str) -> Result<MxValue, Error> {
|
|
let parsed = match value_type {
|
|
CliValueType::Bool => MxValue::bool(parse_cli_value(value)?),
|
|
CliValueType::Int32 => MxValue::int32(parse_cli_value(value)?),
|
|
CliValueType::Int64 => MxValue::int64(parse_cli_value(value)?),
|
|
CliValueType::Float => MxValue::float(parse_cli_value(value)?),
|
|
CliValueType::Double => MxValue::double(parse_cli_value(value)?),
|
|
CliValueType::String => MxValue::string(value),
|
|
};
|
|
Ok(parsed)
|
|
}
|
|
|
|
/// Pairs each parsed item handle with its parsed MxValue (proto form) so a
|
|
/// single helper can build the four bulk-write families without each branch
|
|
/// repeating the length check and per-value parsing.
|
|
pub(crate) fn build_write_bulk_entries(
|
|
item_handles: &[i32],
|
|
value_type: CliValueType,
|
|
values: &[String],
|
|
) -> Result<
|
|
Vec<(
|
|
i32,
|
|
zb_mom_ww_mxgateway_client::generated::mxaccess_gateway::v1::MxValue,
|
|
)>,
|
|
Error,
|
|
> {
|
|
if item_handles.len() != values.len() {
|
|
return Err(Error::InvalidArgument {
|
|
name: "values".to_owned(),
|
|
detail: format!(
|
|
"item-handles count ({}) does not match values count ({})",
|
|
item_handles.len(),
|
|
values.len()
|
|
),
|
|
});
|
|
}
|
|
item_handles
|
|
.iter()
|
|
.zip(values.iter())
|
|
.map(|(handle, value)| {
|
|
parse_value(value_type, value).map(|wrapper| (*handle, wrapper.into_proto()))
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// Parse a small but practically-complete subset of RFC3339:
|
|
/// `YYYY-MM-DDTHH:MM:SS[.fffffffff][Z|+HH:MM|-HH:MM]`. Returns the
|
|
/// corresponding `prost_types::Timestamp` (Unix seconds + nanoseconds).
|
|
pub(crate) fn parse_rfc3339_timestamp(input: &str) -> Result<prost_types::Timestamp, Error> {
|
|
fn invalid(detail: impl Into<String>) -> Error {
|
|
Error::InvalidArgument {
|
|
name: "last-seen-deploy-time".to_owned(),
|
|
detail: detail.into(),
|
|
}
|
|
}
|
|
|
|
let bytes = input.as_bytes();
|
|
if bytes.len() < 20 || (bytes[10] != b'T' && bytes[10] != b't') {
|
|
return Err(invalid(format!(
|
|
"expected RFC3339 timestamp like 2026-04-28T15:30:00Z, got {input:?}"
|
|
)));
|
|
}
|
|
|
|
let read_u32 = |start: usize, len: usize| -> Result<u32, Error> {
|
|
std::str::from_utf8(&bytes[start..start + len])
|
|
.ok()
|
|
.and_then(|slice| slice.parse::<u32>().ok())
|
|
.ok_or_else(|| invalid(format!("non-numeric digits at byte {start}")))
|
|
};
|
|
|
|
let year = read_u32(0, 4)? as i32;
|
|
if bytes[4] != b'-' {
|
|
return Err(invalid("expected '-' after year"));
|
|
}
|
|
let month = read_u32(5, 2)?;
|
|
if bytes[7] != b'-' {
|
|
return Err(invalid("expected '-' after month"));
|
|
}
|
|
let day = read_u32(8, 2)?;
|
|
let hour = read_u32(11, 2)?;
|
|
if bytes[13] != b':' {
|
|
return Err(invalid("expected ':' after hour"));
|
|
}
|
|
let minute = read_u32(14, 2)?;
|
|
if bytes[16] != b':' {
|
|
return Err(invalid("expected ':' after minute"));
|
|
}
|
|
let second = read_u32(17, 2)?;
|
|
|
|
let mut cursor = 19usize;
|
|
let mut nanos: u32 = 0;
|
|
if cursor < bytes.len() && bytes[cursor] == b'.' {
|
|
cursor += 1;
|
|
let frac_start = cursor;
|
|
while cursor < bytes.len() && bytes[cursor].is_ascii_digit() {
|
|
cursor += 1;
|
|
}
|
|
let frac_len = cursor - frac_start;
|
|
if frac_len == 0 {
|
|
return Err(invalid("expected fractional digits after '.'"));
|
|
}
|
|
let take = frac_len.min(9);
|
|
let frac = std::str::from_utf8(&bytes[frac_start..frac_start + take])
|
|
.ok()
|
|
.and_then(|slice| slice.parse::<u32>().ok())
|
|
.ok_or_else(|| invalid("invalid fractional digits"))?;
|
|
nanos = frac * 10u32.pow(9u32.saturating_sub(take as u32));
|
|
}
|
|
|
|
let mut offset_seconds: i64 = 0;
|
|
if cursor >= bytes.len() {
|
|
return Err(invalid("missing timezone designator (Z or +HH:MM)"));
|
|
}
|
|
match bytes[cursor] {
|
|
b'Z' | b'z' => cursor += 1,
|
|
sign @ (b'+' | b'-') => {
|
|
cursor += 1;
|
|
if cursor + 5 > bytes.len() {
|
|
return Err(invalid("offset must be ±HH:MM"));
|
|
}
|
|
let oh = std::str::from_utf8(&bytes[cursor..cursor + 2])
|
|
.ok()
|
|
.and_then(|slice| slice.parse::<i64>().ok())
|
|
.ok_or_else(|| invalid("invalid offset hour"))?;
|
|
if bytes[cursor + 2] != b':' {
|
|
return Err(invalid("offset must contain ':' between HH and MM"));
|
|
}
|
|
let om = std::str::from_utf8(&bytes[cursor + 3..cursor + 5])
|
|
.ok()
|
|
.and_then(|slice| slice.parse::<i64>().ok())
|
|
.ok_or_else(|| invalid("invalid offset minute"))?;
|
|
cursor += 5;
|
|
let signed = if sign == b'-' { -1 } else { 1 };
|
|
offset_seconds = signed * (oh * 3600 + om * 60);
|
|
}
|
|
other => {
|
|
return Err(invalid(format!(
|
|
"unexpected timezone designator byte {other:?}"
|
|
)));
|
|
}
|
|
}
|
|
if cursor != bytes.len() {
|
|
return Err(invalid("trailing characters after timezone"));
|
|
}
|
|
|
|
let unix = ymdhms_to_unix(year, month, day, hour, minute, second)?;
|
|
let seconds = unix - offset_seconds;
|
|
|
|
Ok(prost_types::Timestamp {
|
|
seconds,
|
|
nanos: nanos as i32,
|
|
})
|
|
}
|
|
|
|
pub(crate) fn ymdhms_to_unix(
|
|
year: i32,
|
|
month: u32,
|
|
day: u32,
|
|
hour: u32,
|
|
minute: u32,
|
|
second: u32,
|
|
) -> Result<i64, Error> {
|
|
if !(1..=12).contains(&month) || day < 1 || hour > 23 || minute > 59 || second > 60 {
|
|
return Err(Error::InvalidArgument {
|
|
name: "last-seen-deploy-time".to_owned(),
|
|
detail: "calendar component out of range".to_owned(),
|
|
});
|
|
}
|
|
fn is_leap(year: i32) -> bool {
|
|
(year % 4 == 0 && year % 100 != 0) || year % 400 == 0
|
|
}
|
|
const DAYS: [u32; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
let mut max = DAYS[(month - 1) as usize];
|
|
if month == 2 && is_leap(year) {
|
|
max = 29;
|
|
}
|
|
if day > max {
|
|
return Err(Error::InvalidArgument {
|
|
name: "last-seen-deploy-time".to_owned(),
|
|
detail: format!("day {day} out of range for month {month}/{year}"),
|
|
});
|
|
}
|
|
|
|
// Days from 1970-01-01 to year-month-day.
|
|
let mut total_days: i64 = 0;
|
|
if year >= 1970 {
|
|
for y in 1970..year {
|
|
total_days += if is_leap(y) { 366 } else { 365 };
|
|
}
|
|
} else {
|
|
for y in year..1970 {
|
|
total_days -= if is_leap(y) { 366 } else { 365 };
|
|
}
|
|
}
|
|
for m in 1..month {
|
|
let mut dim = DAYS[(m - 1) as usize];
|
|
if m == 2 && is_leap(year) {
|
|
dim = 29;
|
|
}
|
|
total_days += dim as i64;
|
|
}
|
|
total_days += (day - 1) as i64;
|
|
|
|
Ok(total_days * 86_400 + hour as i64 * 3600 + minute as i64 * 60 + second as i64)
|
|
}
|
|
|
|
pub(crate) fn parse_cli_value<T>(value: &str) -> Result<T, Error>
|
|
where
|
|
T: std::str::FromStr,
|
|
T::Err: std::fmt::Display,
|
|
{
|
|
value.parse::<T>().map_err(|source| Error::InvalidArgument {
|
|
name: "value".to_owned(),
|
|
detail: source.to_string(),
|
|
})
|
|
}
|