1pub(crate) fn print_savings(original: usize, sent: usize) {
2 let footer = crate::core::protocol::format_savings(original, sent);
3 if !footer.is_empty() {
4 println!("{footer}");
5 }
6}
7
8#[cfg(unix)]
10pub(crate) fn filter_daemon_output(text: &str) -> String {
11 if crate::core::protocol::savings_footer_visible() {
12 return text.to_string();
13 }
14 text.lines()
15 .filter(|l| {
16 let t = l.trim();
17 !(t.starts_with('[')
18 && t.contains("tok")
19 && t.ends_with(']')
20 && (t.contains("tok saved") || t.contains("lean-ctx:") || t.contains("vs native")))
21 })
22 .collect::<Vec<_>>()
23 .join("\n")
24}
25
26pub fn load_shell_history_pub() -> Vec<String> {
27 load_shell_history()
28}
29
30pub(crate) fn load_shell_history() -> Vec<String> {
31 let shell = std::env::var("SHELL").unwrap_or_default();
32 let Some(home) = dirs::home_dir() else {
33 return Vec::new();
34 };
35
36 let history_file = if shell.contains("zsh") {
37 home.join(".zsh_history")
38 } else if shell.contains("fish") {
39 home.join(".local/share/fish/fish_history")
40 } else if cfg!(windows) && shell.is_empty() {
41 home.join("AppData")
42 .join("Roaming")
43 .join("Microsoft")
44 .join("Windows")
45 .join("PowerShell")
46 .join("PSReadLine")
47 .join("ConsoleHost_history.txt")
48 } else {
49 home.join(".bash_history")
50 };
51
52 match std::fs::read(&history_file) {
56 Ok(bytes) => String::from_utf8_lossy(&bytes)
57 .lines()
58 .filter_map(|l| {
59 let trimmed = l.trim();
60 if trimmed.starts_with(':') {
61 trimmed
62 .split(';')
63 .nth(1)
64 .map(std::string::ToString::to_string)
65 } else {
66 Some(trimmed.to_string())
67 }
68 })
69 .filter(|l| !l.is_empty())
70 .collect(),
71 Err(_) => Vec::new(),
72 }
73}
74
75pub(crate) fn daemon_fallback_hint() {
76 use std::sync::Once;
77 static HINT: Once = Once::new();
78 HINT.call_once(|| {
79 if crate::core::protocol::meta_visible() {
80 eprintln!("\x1b[2;33mhint: daemon not running — stats tracked locally (lean-ctx serve -d for full tracking)\x1b[0m");
81 }
82 });
83}
84
85pub(crate) fn format_tokens_cli(tokens: u64) -> String {
86 if tokens >= 1_000_000_000_000 {
87 format!("{:.2}T", tokens as f64 / 1_000_000_000_000.0)
88 } else if tokens >= 1_000_000_000 {
89 format!("{:.2}B", tokens as f64 / 1_000_000_000.0)
91 } else if tokens >= 1_000_000 {
92 format!("{:.1}M", tokens as f64 / 1_000_000.0)
93 } else if tokens >= 1_000 {
94 format!("{:.1}K", tokens as f64 / 1_000.0)
95 } else {
96 format!("{tokens}")
97 }
98}
99
100pub(crate) fn detect_project_root(args: &[String]) -> String {
101 let mut it = args.iter().peekable();
102 while let Some(a) = it.next() {
103 if let Some(v) = a.strip_prefix("--root=")
104 && !v.trim().is_empty()
105 {
106 return normalize_explicit_root(v);
107 }
108 if let Some(v) = a.strip_prefix("--project-root=")
109 && !v.trim().is_empty()
110 {
111 return normalize_explicit_root(v);
112 }
113 if (a == "--root" || a == "--project-root")
114 && let Some(v) = it.peek()
115 && !v.starts_with("--")
116 && !v.trim().is_empty()
117 {
118 return normalize_explicit_root(v);
119 }
120 }
121 if let Ok(root) = std::env::var("LEAN_CTX_PROJECT_ROOT")
122 && !root.trim().is_empty()
123 {
124 return normalize_explicit_root(&root);
125 }
126 let cwd = std::env::current_dir()
127 .ok()
128 .map_or_else(|| ".".to_string(), |p| p.to_string_lossy().to_string());
129 promote_to_git_root(&cwd)
130}
131
132fn normalize_explicit_root(path: &str) -> String {
133 let expanded = expand_home(path.trim());
134 crate::core::index_paths::normalize_project_root(&expanded)
135}
136
137fn expand_home(path: &str) -> String {
138 if path == "~" {
139 return dirs::home_dir().map_or_else(
140 || path.to_string(),
141 |home| home.to_string_lossy().to_string(),
142 );
143 }
144 if let Some(rest) = path.strip_prefix("~/") {
145 return dirs::home_dir().map_or_else(
146 || path.to_string(),
147 |home| home.join(rest).to_string_lossy().to_string(),
148 );
149 }
150 path.to_string()
151}
152
153pub(crate) fn promote_to_git_root(path: &str) -> String {
154 let mut p = std::path::Path::new(path);
155 loop {
156 if p.join(".git").exists() {
157 return p.to_string_lossy().to_string();
158 }
159 match p.parent() {
160 Some(parent) => p = parent,
161 None => return path.to_string(),
162 }
163 }
164}
165
166#[cfg(test)]
167mod tests {
168 use super::{detect_project_root, format_tokens_cli, normalize_explicit_root};
169
170 #[test]
171 fn format_tokens_cli_scales_through_billions() {
172 assert_eq!(format_tokens_cli(742), "742");
173 assert_eq!(format_tokens_cli(2_500), "2.5K");
174 assert_eq!(format_tokens_cli(3_400_000), "3.4M");
175 assert_eq!(format_tokens_cli(1_310_000_000), "1.31B");
177 assert_eq!(format_tokens_cli(1_500_000_000_000), "1.50T");
178 }
179
180 #[test]
181 fn explicit_root_is_not_promoted_to_parent_git_root() {
182 let args = vec![
183 "build".to_string(),
184 "--root".to_string(),
185 "/home/example/travail".to_string(),
186 ];
187
188 assert_eq!(detect_project_root(&args), "/home/example/travail");
189 }
190
191 #[test]
192 fn explicit_root_expands_home_prefix() {
193 let Some(home) = dirs::home_dir() else {
194 return;
195 };
196
197 assert_eq!(
198 normalize_explicit_root("~/travail"),
199 home.join("travail").to_string_lossy().to_string()
200 );
201 }
202}