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
9 changes: 8 additions & 1 deletion src/cortex-cli/src/logs_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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<()> {
Expand Down Expand Up @@ -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
Expand Down
49 changes: 49 additions & 0 deletions src/cortex-cli/tests/logs_clear.rs
Original file line number Diff line number Diff line change
@@ -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");
}