Skip to content
Open
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
16 changes: 7 additions & 9 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,17 +149,15 @@ pub fn load() -> Result<Config> {
}

pub fn save_file(path: &Path, config: &Config) -> Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let parent = path.parent().unwrap_or_else(|| Path::new("."));
fs::create_dir_all(parent)?;

let json = serde_json::to_string_pretty(config)?;
let temp_path = path.with_extension("tmp");
let mut file = fs::File::create(&temp_path)?;
file.write_all(json.as_bytes())?;
file.write_all(b"\n")?;
file.sync_all()?;
fs::rename(&temp_path, path)?;
let mut tmp = tempfile::NamedTempFile::new_in(parent)?;
tmp.write_all(json.as_bytes())?;
tmp.write_all(b"\n")?;
tmp.as_file().sync_all()?;
tmp.persist(path)?;

Ok(())
}
Expand Down
2 changes: 1 addition & 1 deletion src/functions/pull.rs
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ pub async fn run(base: BaseArgs, args: PullArgs) -> Result<()> {
);
}
};
match resolve_project_names(&winners, projects) {
match resolve_project_names(&materializable, projects) {
Ok(names) => names,
Err(err) => {
spinner.finish_and_clear();
Expand Down
29 changes: 3 additions & 26 deletions src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ use crate::experiments::api::create_experiment;
use crate::http::ApiClient;
use crate::projects::api::{create_project, list_projects, Project};
use crate::ui::{animations_enabled, fuzzy_select, is_quiet};
use crate::utils::parse_duration_to_seconds;

const STATE_SCHEMA_VERSION: u32 = 1;
const DEFAULT_PULL_LIMIT: usize = 100;
Expand Down Expand Up @@ -2603,30 +2604,6 @@ fn build_root_spans_query(
parts.join(" | ")
}

fn parse_duration_to_seconds(input: &str) -> Result<u64> {
let trimmed = input.trim();
if trimmed.is_empty() {
bail!("duration cannot be empty");
}
if let Ok(seconds) = trimmed.parse::<u64>() {
return Ok(seconds);
}

let (num_str, unit) = trimmed.split_at(trimmed.len().saturating_sub(1));
let value: u64 = num_str
.trim()
.parse()
.with_context(|| format!("invalid duration '{input}'"))?;
let multiplier = match unit.to_ascii_lowercase().as_str() {
"s" => 1,
"m" => 60,
"h" => 60 * 60,
"d" => 60 * 60 * 24,
_ => bail!("invalid duration '{input}'. expected suffix s/m/h/d"),
};
Ok(value.saturating_mul(multiplier))
}

fn build_time_filter_clause(window: &str, extra_filter: Option<&str>) -> Result<String> {
let seconds = parse_duration_to_seconds(window)?;
let time_clause = format!("created >= NOW() - INTERVAL {seconds} SECOND");
Expand Down Expand Up @@ -4107,7 +4084,7 @@ fn collect_seen_roots_until_offset(
let file =
File::open(path).with_context(|| format!("failed to open {}", path.display()))?;
let reader = BufReader::new(file);
for (line_index, line) in reader.lines().enumerate() {
for line in reader.lines() {
if global_line_index >= line_offset {
break 'files;
}
Expand All @@ -4117,7 +4094,7 @@ fn collect_seen_roots_until_offset(
format!(
"invalid JSON in {} at line {} while rebuilding trace resume state",
path.display(),
line_index + 1
global_line_index + 1
)
})?;
if let Some(root_id) = row_root_span_id(&row) {
Expand Down
65 changes: 29 additions & 36 deletions src/traces.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ use crate::args::BaseArgs;
use crate::auth::{self, login};
use crate::http::ApiClient;
use crate::ui::{fuzzy_select, is_interactive, with_spinner};
use crate::utils::parse_duration_to_seconds;

const MAX_TRACE_SPANS: usize = 5000;
const MAX_BTQL_PAGE_LIMIT: usize = 1000;
Expand Down Expand Up @@ -1028,6 +1029,7 @@ async fn run_logs_command(base: BaseArgs, client: ApiClient, args: LogsArgs) ->
&object_ref_arg,
next_cursor.as_deref(),
profile_flag,
args.limit,
),
});
println!("{}", serde_json::to_string_pretty(&payload)?);
Expand Down Expand Up @@ -1191,6 +1193,7 @@ async fn run_trace_command(base: BaseArgs, client: ApiClient, args: TraceArgs) -
&trace_id,
next_cursor.as_deref(),
profile_flag,
args.limit,
),
});
println!("{}", serde_json::to_string_pretty(&payload)?);
Expand Down Expand Up @@ -4844,16 +4847,22 @@ fn logs_hints(
object_ref: &str,
next_cursor: Option<&str>,
profile: Option<&str>,
limit: usize,
) -> Vec<String> {
let mut hints = vec![
"Rows are truncated by preview_length; fetch a single span for full content.".to_string(),
"Use --json to get machine-readable envelopes for agent workflows.".to_string(),
"Write large responses to a file to preserve full output context.".to_string(),
];
let limit_suffix = if limit != 50 {
format!(" --limit {limit}")
} else {
String::new()
};
if has_more {
if let Some(cursor) = next_cursor {
hints.push(format!(
"Next page: bt view logs{} --object-ref {object_ref} --cursor {cursor}",
"Next page: bt view logs{} --object-ref {object_ref} --cursor {cursor}{limit_suffix}",
profile_flag_suffix(profile)
));
} else {
Expand All @@ -4871,6 +4880,7 @@ fn trace_hints(
trace_id: &str,
next_cursor: Option<&str>,
profile: Option<&str>,
limit: usize,
) -> Vec<String> {
let mut hints = vec![
format!(
Expand All @@ -4879,10 +4889,15 @@ fn trace_hints(
),
"Write output to a file for long traces.".to_string(),
];
let limit_suffix = if limit != 50 {
format!(" --limit {limit}")
} else {
String::new()
};
if has_more {
if let Some(cursor) = next_cursor {
hints.push(format!(
"Next page: bt view trace{} --object-ref {object_ref} --trace-id {trace_id} --cursor {cursor}",
"Next page: bt view trace{} --object-ref {object_ref} --trace-id {trace_id} --cursor {cursor}{limit_suffix}",
profile_flag_suffix(profile)
));
} else {
Expand Down Expand Up @@ -4934,9 +4949,14 @@ fn print_logs_text(
}
println!("\nTruncated fields use preview_length={preview_length}.");
if let Some(cursor) = next_cursor {
let limit_suffix = if limit != 50 {
format!(" --limit {limit}")
} else {
String::new()
};
println!("next_cursor: {cursor}");
println!(
"next: bt view logs{} --object-ref {object_ref} --cursor {cursor} --non-interactive",
"next: bt view logs{} --object-ref {object_ref} --cursor {cursor} --non-interactive{limit_suffix}",
profile_flag_suffix(profile)
);
} else {
Expand Down Expand Up @@ -4980,9 +5000,14 @@ fn print_trace_text(
object_ref
);
if let Some(cursor) = next_cursor {
let limit_suffix = if limit != 50 {
format!(" --limit {limit}")
} else {
String::new()
};
println!("next_cursor: {cursor}");
println!(
"next: bt view trace{} --object-ref {} --trace-id {} --cursor {} --non-interactive",
"next: bt view trace{} --object-ref {} --trace-id {} --cursor {} --non-interactive{limit_suffix}",
profile_flag_suffix(profile),
object_ref,
trace_id,
Expand All @@ -5006,30 +5031,6 @@ fn print_span_text(item: Option<&Map<String, Value>>) {
}
}

fn parse_duration_to_seconds(input: &str) -> Result<u64> {
let trimmed = input.trim();
if trimmed.is_empty() {
bail!("duration cannot be empty");
}
if let Ok(seconds) = trimmed.parse::<u64>() {
return Ok(seconds);
}

let (num_str, unit) = trimmed.split_at(trimmed.len().saturating_sub(1));
let value: u64 = num_str
.trim()
.parse()
.with_context(|| format!("invalid duration '{input}'"))?;
let multiplier = match unit.to_ascii_lowercase().as_str() {
"s" => 1,
"m" => 60,
"h" => 60 * 60,
"d" => 60 * 60 * 24,
_ => bail!("invalid duration '{input}'. expected suffix s/m/h/d"),
};
Ok(value.saturating_mul(multiplier))
}

fn build_base_filter_clause(
since: Option<&str>,
window: &str,
Expand Down Expand Up @@ -6155,14 +6156,6 @@ mod tests {
}
}

#[test]
fn parse_duration_to_seconds_supports_units() {
assert_eq!(parse_duration_to_seconds("90").expect("seconds"), 90);
assert_eq!(parse_duration_to_seconds("15m").expect("minutes"), 900);
assert_eq!(parse_duration_to_seconds("2h").expect("hours"), 7_200);
assert_eq!(parse_duration_to_seconds("1d").expect("days"), 86_400);
}

#[test]
fn build_base_filter_clause_uses_window_or_since() {
let from_window = build_base_filter_clause(None, "1h", Some("metadata.model IS NOT NULL"))
Expand Down
50 changes: 50 additions & 0 deletions src/utils/duration.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
use anyhow::{bail, Context, Result};

pub fn parse_duration_to_seconds(input: &str) -> Result<u64> {
let trimmed = input.trim();
if trimmed.is_empty() {
bail!("duration cannot be empty");
}
if let Ok(seconds) = trimmed.parse::<u64>() {
return Ok(seconds);
}

let suffix = trimmed.chars().last().filter(|ch| ch.is_ascii_alphabetic());
let (num_str, unit) = match suffix {
Some(unit) => (&trimmed[..trimmed.len() - unit.len_utf8()], unit),
None => (trimmed, 's'),
};
let value: u64 = num_str
.trim()
.parse()
.with_context(|| format!("invalid duration '{input}'"))?;
let multiplier = match unit.to_ascii_lowercase() {
's' => 1,
'm' => 60,
'h' => 60 * 60,
'd' => 60 * 60 * 24,
_ => bail!("invalid duration '{input}'. expected suffix s/m/h/d"),
};
Ok(value.saturating_mul(multiplier))
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn supports_units() {
assert_eq!(parse_duration_to_seconds("90").expect("seconds"), 90);
assert_eq!(parse_duration_to_seconds("15m").expect("minutes"), 900);
assert_eq!(parse_duration_to_seconds("2h").expect("hours"), 7_200);
assert_eq!(parse_duration_to_seconds("1d").expect("days"), 86_400);
}

#[test]
fn rejects_non_ascii_suffix_without_panicking() {
for input in ["1–", "1é", "1🙂"] {
let err = parse_duration_to_seconds(input).expect_err("invalid unicode suffix");
assert!(err.to_string().contains("invalid duration"));
}
}
}
2 changes: 2 additions & 0 deletions src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
mod duration;
mod fs_atomic;
mod git;
mod plurals;

pub use duration::parse_duration_to_seconds;
pub use fs_atomic::write_text_atomic;
pub use git::GitRepo;
pub use plurals::pluralize;
Loading