Skip to content

Commit 5badd96

Browse files
author
Greyforge Admin
committed
Filter logs clear to log files
1 parent 7954d02 commit 5badd96

2 files changed

Lines changed: 57 additions & 1 deletion

File tree

src/cortex-cli/src/logs_cmd.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
use anyhow::Result;
1010
use clap::Parser;
1111
use serde::Serialize;
12-
use std::path::PathBuf;
12+
use std::path::{Path, PathBuf};
1313

1414
/// Logs CLI command.
1515
#[derive(Debug, Parser)]
@@ -81,6 +81,12 @@ fn format_size(bytes: u64) -> String {
8181
}
8282
}
8383

84+
fn is_log_file(path: &Path) -> bool {
85+
path.file_name()
86+
.and_then(|n| n.to_str())
87+
.is_some_and(|name| name.ends_with(".log") || name.ends_with(".txt"))
88+
}
89+
8490
impl LogsCli {
8591
/// Run the logs command.
8692
pub async fn run(self) -> Result<()> {
@@ -329,6 +335,7 @@ impl LogsCli {
329335
for entry in entries.flatten() {
330336
let path = entry.path();
331337
if path.is_file()
338+
&& is_log_file(&path)
332339
&& let Ok(meta) = entry.metadata()
333340
&& let Ok(modified) = meta.modified()
334341
&& modified < cutoff_time

src/cortex-cli/tests/logs_clear.rs

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
use std::fs;
2+
use std::process::Command;
3+
4+
use tempfile::tempdir;
5+
6+
fn combined_output(output: &std::process::Output) -> String {
7+
format!(
8+
"{}{}",
9+
String::from_utf8_lossy(&output.stdout),
10+
String::from_utf8_lossy(&output.stderr)
11+
)
12+
}
13+
14+
#[test]
15+
fn logs_clear_removes_only_log_files() {
16+
let home = tempdir().unwrap();
17+
let cache = tempdir().unwrap();
18+
let logs_dir = cache.path().join("cortex").join("logs");
19+
fs::create_dir_all(&logs_dir).unwrap();
20+
21+
let log_file = logs_dir.join("cortex.log");
22+
let txt_file = logs_dir.join("debug.txt");
23+
let json_file = logs_dir.join("notes.json");
24+
let bin_file = logs_dir.join("snapshot.bin");
25+
26+
fs::write(&log_file, "log\n").unwrap();
27+
fs::write(&txt_file, "debug\n").unwrap();
28+
fs::write(&json_file, "{}\n").unwrap();
29+
fs::write(&bin_file, "binary\n").unwrap();
30+
31+
let output = Command::new(env!("CARGO_BIN_EXE_Cortex"))
32+
.args(["logs", "--clear", "--keep-days", "0"])
33+
.env("HOME", home.path())
34+
.env("XDG_CACHE_HOME", cache.path())
35+
.env_remove("CORTEX_HOME")
36+
.output()
37+
.unwrap();
38+
39+
assert!(
40+
output.status.success(),
41+
"logs --clear failed:\n{}",
42+
combined_output(&output)
43+
);
44+
45+
assert!(!log_file.exists(), "expected .log file to be cleared");
46+
assert!(!txt_file.exists(), "expected .txt file to be cleared");
47+
assert!(json_file.exists(), "expected non-log .json file to remain");
48+
assert!(bin_file.exists(), "expected non-log .bin file to remain");
49+
}

0 commit comments

Comments
 (0)