Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions atomic-cli/src/commands/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,11 @@ pub fn resolve_identity_for_server(

if let Some(ref identity_name) = server.identity {
// Server profile specifies an identity — use it.
log::debug!(
"Authenticating as '{}' (bound to server profile {})",
identity_name,
server.url.as_deref().unwrap_or("<no url>")
);
store.load_by_name(identity_name).map_err(|e| {
CliError::Internal(anyhow::anyhow!(
"Identity '{}' specified by server profile not found: {}",
Expand All @@ -189,7 +194,13 @@ pub fn resolve_identity_for_server(
})
} else {
// Fall back to global default identity.
store
//
// Worth logging loudly: the fallback is silent on the wire, so when
// the default identity is not the one registered with this server the
// only symptom is a 401 from the far end that names no identity at
// all. Saying which identity was chosen, and that it was a fallback,
// is the difference between a one-line fix and a blind hunt.
let identity = store
.get_default()
.map_err(|e| {
CliError::Internal(anyhow::anyhow!("Failed to load default identity: {}", e))
Expand All @@ -199,7 +210,14 @@ pub fn resolve_identity_for_server(
"No default identity set. Create one first:\n \
atomic identity new <name> --email <email> --set-default"
))
})
})?;
log::debug!(
"Server profile {} declares no identity; falling back to the default identity '{}'. \
Bind one with 'atomic server set-identity <profile> <identity>'.",
server.url.as_deref().unwrap_or("<no url>"),
identity.name
);
Ok(identity)
}
}

Expand Down
43 changes: 42 additions & 1 deletion atomic-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -865,9 +865,50 @@ enum Commands {

// Main Entry Point

/// The log filter `--verbose` turns on.
///
/// Scoped to the Atomic crates on purpose: a bare `debug` also unleashes
/// `reqwest`/`hyper` wire logging, which buries the one line the user wanted.
///
/// `atomic` is a prefix match, so it covers this binary (whose module paths
/// are `atomic::…`, after the `[[bin]]` name rather than the `atomic-cli`
/// package) along with every `atomic_*` library crate. `atomic_core` is pegged
/// back to `info`: its per-vertex graph logging is far below the level anyone
/// reaching for `--verbose` is asking about.
const VERBOSE_FILTER: &str = "atomic=debug,atomic_core=info";

/// Detect the global `--verbose` flag straight from `argv`.
///
/// Logging has to be live before clap runs, because argument parsing itself
/// can fail and we want the debug trail for that too. `--verbose` is a global
/// flag, so its position is unconstrained — scanning argv is both simpler and
/// more faithful than trying to parse twice.
fn verbose_requested() -> bool {
std::env::args_os().any(|a| a == "-v" || a == "--verbose")
}

/// Install the logger, honouring `--verbose`.
///
/// Every command advertises `-v, --verbose Emit extra diagnostic output`, but
/// the flag was parsed into a field nothing ever read: logging was initialised
/// before parsing and only `RUST_LOG` could raise the level. The debug lines
/// that explain *which identity a request authenticated as* already existed —
/// they were simply unreachable through the documented flag, which turned an
/// identity misconfiguration into an opaque server-side 401.
///
/// `RUST_LOG` still wins when set, so existing workflows are untouched.
fn init_logging() {
let default = if verbose_requested() {
VERBOSE_FILTER
} else {
"warn"
};
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or(default)).init();
}

fn main() {
// Initialize logging
env_logger::init();
init_logging();

// Dynamic shell completion. When invoked in completion mode (the `COMPLETE`
// env var is set by the installed shell hook), this emits candidates —
Expand Down
21 changes: 21 additions & 0 deletions atomic-cli/src/output/progress.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,24 @@ pub fn suspend<R>(mp: &MultiProgress, f: impl FnOnce() -> R) -> R {

// Progress Bar Completion

/// Write a completion message directly to stderr when the progress bar is
/// hidden.
///
/// `indicatif` defaults to a stderr draw target that suppresses itself when
/// stderr is not a terminal. That is the right call for the *animation* — a
/// spinner in a log file is noise — but `finish_with_message` goes through the
/// same draw target, so the final outcome line disappeared along with it. A
/// piped `atomic view switch` printed nothing at all: no confirmation, and no
/// "N conflicts detected" warning either.
///
/// So when the bar is hidden, emit the message ourselves. Plain text, no ANSI:
/// the consumer is a pipe, a CI log, or an agent.
fn emit_if_hidden(pb: &ProgressBar, prefix: &str, message: &str) {
if pb.is_hidden() {
eprintln!("{} {}", prefix, message);
}
}

/// Finish a progress bar with a success message.
///
/// This clears the progress bar and displays a success message in green.
Expand All @@ -236,6 +254,7 @@ pub fn suspend<R>(mp: &MultiProgress, f: impl FnOnce() -> R) -> R {
pub fn finish_success(pb: &ProgressBar, message: &str) {
pb.set_style(success_style());
pb.finish_with_message(message.to_string());
emit_if_hidden(pb, "✓", message);
}

/// Finish a progress bar with a warning message.
Expand All @@ -249,6 +268,7 @@ pub fn finish_success(pb: &ProgressBar, message: &str) {
pub fn finish_warning(pb: &ProgressBar, message: &str) {
pb.set_style(warning_style());
pb.finish_with_message(message.to_string());
emit_if_hidden(pb, "⚠", message);
}

/// Finish and completely clear a progress bar from the terminal.
Expand Down Expand Up @@ -283,6 +303,7 @@ pub fn finish_and_clear(pb: &ProgressBar) {
pub fn finish_error(pb: &ProgressBar, message: &str) {
pb.set_style(error_style());
pb.finish_with_message(message.to_string());
emit_if_hidden(pb, "✗", message);
}

// Progress Styles
Expand Down
72 changes: 70 additions & 2 deletions atomic-remote/src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,31 @@ use crate::storage_types::{
UpdateProjectRequest, UpdateWorkspaceRequest, WorkspaceInfo,
};

/// How much of an undeserializable response body to quote in the error.
///
/// Deliberately generous. The previous 200 bytes routinely cut off before the
/// offending field, leaving an error that named a problem the reader could not
/// see; the full body is available at debug level regardless.
const BODY_PREVIEW_BYTES: usize = 2000;

/// Truncate `s` to at most `max` bytes without splitting a UTF-8 character.
///
/// Slicing a `String` at an arbitrary byte offset panics when the index lands
/// inside a multi-byte character, so the naive `&body[..200]` this replaces
/// could take down the CLI on any error body containing non-ASCII text — an
/// accented name or a smart quote in a server message was enough. Walk back to
/// a character boundary instead.
fn preview(s: &str, max: usize) -> String {
if s.len() <= max {
return s.to_string();
}
let mut end = max;
while end > 0 && !s.is_char_boundary(end) {
end -= 1;
}
format!("{}… ({} bytes total)", &s[..end], s.len())
}

/// HTTP client for atomic-storage management operations.
///
/// Handles authentication, URL construction, and API response unwrapping.
Expand Down Expand Up @@ -198,11 +223,13 @@ impl StorageClient {
}

let api_resp: ApiResponse<T> = serde_json::from_str(&body).map_err(|e| {
let preview_len = body.len().min(200);
// The whole body goes to the log; the error message carries a
// bounded preview so a large payload cannot flood the terminal.
log::debug!("Undeserializable response body: {}", body);
RemoteError::other(format!(
"invalid response JSON: {} (body: {})",
e,
&body[..preview_len]
preview(&body, BODY_PREVIEW_BYTES)
))
})?;

Expand Down Expand Up @@ -410,4 +437,45 @@ mod tests {
let err = client.parse_error_body(502, "Bad Gateway");
assert!(err.to_string().contains("502"));
}

#[test]
fn preview_returns_short_input_verbatim() {
assert_eq!(preview("short", BODY_PREVIEW_BYTES), "short");
}

#[test]
fn preview_truncates_long_input_and_reports_full_length() {
let body = "a".repeat(BODY_PREVIEW_BYTES + 500);
let out = preview(&body, BODY_PREVIEW_BYTES);
assert!(out.starts_with(&"a".repeat(BODY_PREVIEW_BYTES)));
assert!(out.contains(&format!("({} bytes total)", body.len())));
}

/// The predecessor of `preview` sliced with `&body[..200]`, which panics
/// when the cut lands inside a multi-byte character. A server message
/// containing an accented name or a smart quote was enough to abort the
/// CLI while it was in the middle of reporting a different error.
///
/// Every offset across a multi-byte boundary must be safe.
#[test]
fn preview_never_splits_a_utf8_character() {
// "é" is two bytes, "→" three, "🔒" four — so every truncation length
// walks through the middle of some character.
let body = "é→🔒".repeat(200);
for max in 0..64 {
let out = preview(&body, max);
assert!(
out.len() <= body.len() + 32,
"preview should not grow the input"
);
}
}

#[test]
fn preview_handles_multibyte_at_exact_limit() {
// Limit falls exactly between the two bytes of "é".
let body = "aé".repeat(10);
let out = preview(&body, 2);
assert!(out.starts_with('a'), "got {out:?}");
}
}
Loading