From 5badd96919881c6ead43b2f250f94257fec709e0 Mon Sep 17 00:00:00 2001 From: Greyforge Admin Date: Wed, 20 May 2026 00:28:17 -0400 Subject: [PATCH] Filter logs clear to log files --- src/cortex-cli/src/logs_cmd.rs | 9 +++++- src/cortex-cli/tests/logs_clear.rs | 49 ++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 src/cortex-cli/tests/logs_clear.rs diff --git a/src/cortex-cli/src/logs_cmd.rs b/src/cortex-cli/src/logs_cmd.rs index f525efc3c..8b470b8f6 100644 --- a/src/cortex-cli/src/logs_cmd.rs +++ b/src/cortex-cli/src/logs_cmd.rs @@ -9,7 +9,7 @@ use anyhow::Result; use clap::Parser; use serde::Serialize; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; /// Logs CLI command. #[derive(Debug, Parser)] @@ -81,6 +81,12 @@ fn format_size(bytes: u64) -> String { } } +fn is_log_file(path: &Path) -> bool { + path.file_name() + .and_then(|n| n.to_str()) + .is_some_and(|name| name.ends_with(".log") || name.ends_with(".txt")) +} + impl LogsCli { /// Run the logs command. pub async fn run(self) -> Result<()> { @@ -329,6 +335,7 @@ impl LogsCli { for entry in entries.flatten() { let path = entry.path(); if path.is_file() + && is_log_file(&path) && let Ok(meta) = entry.metadata() && let Ok(modified) = meta.modified() && modified < cutoff_time diff --git a/src/cortex-cli/tests/logs_clear.rs b/src/cortex-cli/tests/logs_clear.rs new file mode 100644 index 000000000..12d49aa2a --- /dev/null +++ b/src/cortex-cli/tests/logs_clear.rs @@ -0,0 +1,49 @@ +use std::fs; +use std::process::Command; + +use tempfile::tempdir; + +fn combined_output(output: &std::process::Output) -> String { + format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ) +} + +#[test] +fn logs_clear_removes_only_log_files() { + let home = tempdir().unwrap(); + let cache = tempdir().unwrap(); + let logs_dir = cache.path().join("cortex").join("logs"); + fs::create_dir_all(&logs_dir).unwrap(); + + let log_file = logs_dir.join("cortex.log"); + let txt_file = logs_dir.join("debug.txt"); + let json_file = logs_dir.join("notes.json"); + let bin_file = logs_dir.join("snapshot.bin"); + + fs::write(&log_file, "log\n").unwrap(); + fs::write(&txt_file, "debug\n").unwrap(); + fs::write(&json_file, "{}\n").unwrap(); + fs::write(&bin_file, "binary\n").unwrap(); + + let output = Command::new(env!("CARGO_BIN_EXE_Cortex")) + .args(["logs", "--clear", "--keep-days", "0"]) + .env("HOME", home.path()) + .env("XDG_CACHE_HOME", cache.path()) + .env_remove("CORTEX_HOME") + .output() + .unwrap(); + + assert!( + output.status.success(), + "logs --clear failed:\n{}", + combined_output(&output) + ); + + assert!(!log_file.exists(), "expected .log file to be cleared"); + assert!(!txt_file.exists(), "expected .txt file to be cleared"); + assert!(json_file.exists(), "expected non-log .json file to remain"); + assert!(bin_file.exists(), "expected non-log .bin file to remain"); +}