Skip to content

Commit 747d3ba

Browse files
author
Greyforge Admin
committed
Show initial lines before following logs
1 parent 7954d02 commit 747d3ba

2 files changed

Lines changed: 64 additions & 0 deletions

File tree

src/cortex-cli/src/logs_cmd.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,27 @@ impl LogsCli {
222222
println!("Following log file: {}", log_file.display());
223223
println!("Press Ctrl+C to stop.\n");
224224

225+
let content = std::fs::read_to_string(log_file)?;
226+
let lines: Vec<&str> = content.lines().collect();
227+
let filtered_lines: Vec<&str> = if let Some(ref level) = self.level {
228+
let level_upper = level.to_uppercase();
229+
lines
230+
.iter()
231+
.filter(|line| line.to_uppercase().contains(&level_upper))
232+
.copied()
233+
.collect()
234+
} else {
235+
lines
236+
};
237+
let start = if filtered_lines.len() > self.lines {
238+
filtered_lines.len() - self.lines
239+
} else {
240+
0
241+
};
242+
for line in &filtered_lines[start..] {
243+
println!("{}", line);
244+
}
245+
225246
let file = std::fs::File::open(log_file)?;
226247
let mut reader = BufReader::new(file);
227248

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
use std::fs;
2+
use std::io::Read;
3+
use std::process::{Command, Stdio};
4+
use std::thread;
5+
use std::time::Duration;
6+
7+
use tempfile::tempdir;
8+
9+
#[test]
10+
fn logs_follow_prints_requested_initial_lines() {
11+
let home = tempdir().unwrap();
12+
let cache = tempdir().unwrap();
13+
let logs_dir = cache.path().join("cortex").join("logs");
14+
fs::create_dir_all(&logs_dir).unwrap();
15+
fs::write(logs_dir.join("cortex.log"), "one\ntwo\nthree\nfour\n").unwrap();
16+
17+
let mut child = Command::new(env!("CARGO_BIN_EXE_Cortex"))
18+
.args(["logs", "--follow", "--lines", "2"])
19+
.env("HOME", home.path())
20+
.env("XDG_CACHE_HOME", cache.path())
21+
.env_remove("CORTEX_HOME")
22+
.stdout(Stdio::piped())
23+
.stderr(Stdio::piped())
24+
.spawn()
25+
.unwrap();
26+
27+
thread::sleep(Duration::from_millis(250));
28+
let _ = child.kill();
29+
30+
let mut stdout = String::new();
31+
child
32+
.stdout
33+
.take()
34+
.unwrap()
35+
.read_to_string(&mut stdout)
36+
.unwrap();
37+
let _ = child.wait();
38+
39+
assert!(!stdout.contains("\none\n"), "output:\n{stdout}");
40+
assert!(!stdout.contains("\ntwo\n"), "output:\n{stdout}");
41+
assert!(stdout.contains("\nthree\n"), "output:\n{stdout}");
42+
assert!(stdout.contains("\nfour\n"), "output:\n{stdout}");
43+
}

0 commit comments

Comments
 (0)