1use serde::{Deserialize, Serialize};
6use std::ffi::OsStr;
7use std::fs::OpenOptions;
8use std::io::{BufRead, BufReader, Write};
9use std::path::{Path, PathBuf};
10
11pub fn default_path() -> Option<PathBuf> {
19 path_from(
20 std::env::var_os("BLYTE_USAGE_LOG").as_deref(),
21 std::env::var_os("XDG_STATE_HOME").as_deref(),
22 std::env::var_os("HOME").as_deref(),
23 )
24}
25
26pub fn path_from(
28 log: Option<&OsStr>,
29 xdg: Option<&OsStr>,
30 home: Option<&OsStr>,
31) -> Option<PathBuf> {
32 if let Some(log) = log.filter(|s| !s.is_empty()) {
33 if log == "off" {
34 return None;
35 }
36 return Some(PathBuf::from(log));
37 }
38 if let Some(xdg) = xdg.filter(|s| !s.is_empty()) {
39 return Some(Path::new(xdg).join("blyte").join("usage.jsonl"));
40 }
41 if let Some(home) = home.filter(|s| !s.is_empty()) {
42 return Some(
43 Path::new(home)
44 .join(".local")
45 .join("state")
46 .join("blyte")
47 .join("usage.jsonl"),
48 );
49 }
50 None
51}
52
53pub fn session_from(blyte: Option<String>, claude: Option<String>) -> Option<String> {
57 blyte
58 .filter(|s| !s.trim().is_empty())
59 .or_else(|| claude.filter(|s| !s.trim().is_empty()))
60}
61
62#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
64pub struct Entry {
65 pub ts: u64,
66 pub repo: String,
67 #[serde(default, skip_serializing_if = "Option::is_none")]
68 pub session: Option<String>,
69 #[serde(default, skip_serializing_if = "Option::is_none")]
70 pub dispatch: Option<String>,
71 pub research: bool,
72 pub model: String,
73 pub outcome: String,
74 pub turns: u32,
75 pub input: u64,
76 pub cached: u64,
77 pub output: u64,
78 pub thinking: u64,
79 #[serde(default)]
80 pub cost_usd: Option<f64>,
81}
82
83pub fn repo_of(root: &Path) -> String {
85 let mut prefix = PathBuf::new();
86 let mut found = false;
87 for component in root.components() {
88 if component.as_os_str() == ".wt" {
89 found = true;
90 break;
91 }
92 prefix.push(component);
93 }
94 if found {
95 prefix.to_string_lossy().into_owned()
96 } else {
97 root.to_string_lossy().into_owned()
98 }
99}
100
101pub fn append(path: &Path, entry: &Entry) -> std::io::Result<()> {
105 if let Some(parent) = path.parent() {
106 if !parent.as_os_str().is_empty() {
107 std::fs::create_dir_all(parent)?;
108 }
109 }
110 let mut file = OpenOptions::new().create(true).append(true).open(path)?;
111 let mut line = serde_json::to_vec(entry)
112 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
113 line.push(b'\n');
114 file.write_all(&line)?;
115 Ok(())
116}
117
118pub fn read(path: &Path) -> Vec<Entry> {
122 let Ok(file) = std::fs::File::open(path) else {
123 return Vec::new();
124 };
125 let reader = BufReader::new(file);
126 let mut entries = Vec::new();
127 for line in reader.lines() {
128 let Ok(line) = line else {
129 continue;
130 };
131 let trimmed = line.trim();
132 if trimmed.is_empty() {
133 continue;
134 }
135 if let Ok(entry) = serde_json::from_str::<Entry>(trimmed) {
136 entries.push(entry);
137 }
138 }
139 entries
140}
141
142#[cfg(test)]
143pub(crate) static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
144
145#[cfg(test)]
146mod tests {
147 use super::*;
148 use std::ffi::OsStr;
149
150 #[test]
151 fn test_path_from() {
152 assert_eq!(
154 path_from(
155 Some(OsStr::new("/x/u.jsonl")),
156 Some(OsStr::new("/xdg")),
157 Some(OsStr::new("/home")),
158 ),
159 Some(PathBuf::from("/x/u.jsonl"))
160 );
161
162 assert_eq!(
164 path_from(
165 Some(OsStr::new("off")),
166 Some(OsStr::new("/xdg")),
167 Some(OsStr::new("/home")),
168 ),
169 None
170 );
171
172 assert_eq!(
174 path_from(None, Some(OsStr::new("/xdg")), Some(OsStr::new("/home"))),
175 Some(PathBuf::from("/xdg/blyte/usage.jsonl"))
176 );
177
178 assert_eq!(
180 path_from(None, None, Some(OsStr::new("/home"))),
181 Some(PathBuf::from("/home/.local/state/blyte/usage.jsonl"))
182 );
183
184 assert_eq!(
186 path_from(
187 Some(OsStr::new("")),
188 Some(OsStr::new("")),
189 Some(OsStr::new("/home")),
190 ),
191 Some(PathBuf::from("/home/.local/state/blyte/usage.jsonl"))
192 );
193 assert_eq!(
194 path_from(
195 Some(OsStr::new("")),
196 Some(OsStr::new("/xdg")),
197 Some(OsStr::new("")),
198 ),
199 Some(PathBuf::from("/xdg/blyte/usage.jsonl"))
200 );
201 assert_eq!(
202 path_from(
203 Some(OsStr::new("")),
204 Some(OsStr::new("")),
205 Some(OsStr::new("")),
206 ),
207 None
208 );
209
210 assert_eq!(path_from(None, None, None), None);
212 }
213
214 #[test]
215 fn test_repo_of() {
216 assert_eq!(repo_of(Path::new("/r/.wt/T1")), "/r");
217 assert_eq!(repo_of(Path::new("/r")), "/r");
218 assert_eq!(repo_of(Path::new("/r/.wtx/a")), "/r/.wtx/a");
219 }
220
221 #[test]
222 fn test_append_twice_and_read() {
223 let tmp = tempfile::tempdir().unwrap();
224 let log_path = tmp.path().join("parent").join("sub").join("usage.jsonl");
225
226 let entry1 = Entry {
227 ts: 1700000000,
228 repo: "/repo/one".into(),
229 session: Some("sess-1".into()),
230 dispatch: Some("disp-1".into()),
231 research: false,
232 model: "claude-3-7-sonnet".into(),
233 outcome: "verified".into(),
234 turns: 3,
235 input: 1000,
236 cached: 200,
237 output: 300,
238 thinking: 50,
239 cost_usd: Some(0.015),
240 };
241
242 let entry2 = Entry {
243 ts: 1700000010,
244 repo: "/repo/two".into(),
245 session: None,
246 dispatch: None,
247 research: true,
248 model: "gemini-3.8-flash".into(),
249 outcome: "budgetexhausted".into(),
250 turns: 15,
251 input: 5000,
252 cached: 1000,
253 output: 800,
254 thinking: 0,
255 cost_usd: None,
256 };
257
258 append(&log_path, &entry1).expect("first append should succeed");
259
260 {
262 let mut f = OpenOptions::new()
263 .append(true)
264 .open(&log_path)
265 .expect("open log file to inject garbage");
266 f.write_all(b"not valid json here at all\n")
267 .expect("write garbage");
268 }
269
270 append(&log_path, &entry2).expect("second append should succeed");
271
272 let entries = read(&log_path);
273 assert_eq!(entries.len(), 2);
274 assert_eq!(entries[0], entry1);
275 assert_eq!(entries[1], entry2);
276 }
277
278 #[test]
279 fn test_session_none_serialization() {
280 let entry = Entry {
281 ts: 1700000000,
282 repo: "/r".into(),
283 session: None,
284 dispatch: None,
285 research: false,
286 model: "m".into(),
287 outcome: "verified".into(),
288 turns: 1,
289 input: 10,
290 cached: 0,
291 output: 5,
292 thinking: 0,
293 cost_usd: None,
294 };
295
296 let json_str = serde_json::to_string(&entry).unwrap();
297 assert!(
298 !json_str.contains("\"session\""),
299 "session key must be omitted when None"
300 );
301 assert!(
302 !json_str.contains("\"dispatch\""),
303 "dispatch key must be omitted when None"
304 );
305
306 let parsed: Entry = serde_json::from_str(&json_str).unwrap();
307 assert_eq!(parsed, entry);
308 }
309
310 #[test]
311 fn test_session_from() {
312 assert_eq!(
313 session_from(Some("b".into()), Some("c".into())),
314 Some("b".into())
315 );
316 assert_eq!(session_from(None, Some("c".into())), Some("c".into()));
317 assert_eq!(
318 session_from(Some("".into()), Some("c".into())),
319 Some("c".into())
320 );
321 assert_eq!(session_from(Some(" ".into()), None), None);
322 assert_eq!(session_from(None, None), None);
323 }
324
325 #[test]
326 fn the_ledger_is_off_under_cargo_test() {
327 let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
328 assert_eq!(default_path(), None);
329 }
330}