tokf 0.2.33

Config-driven CLI tool that compresses command output before it reaches an LLM context
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
use std::path::{Path, PathBuf};

use serde::Serialize;

use tokf::config;
use tokf::tracking;

/// Write-access status for a path that tokf needs to write to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
enum WriteAccess {
    /// Path exists and is writable by the current process.
    Writable,
    /// Path exists but is not writable.
    ReadOnly,
    /// Path does not exist; its nearest existing ancestor is writable (will be auto-created).
    WillCreate,
    /// Path does not exist and its nearest existing ancestor is not writable.
    ParentReadOnly,
    /// Neither the path nor any ancestor could be found or checked.
    Unavailable,
}

impl WriteAccess {
    const fn label(self) -> &'static str {
        match self {
            Self::Writable => "writable",
            Self::ReadOnly => "read-only!",
            Self::WillCreate => "will be created",
            Self::ParentReadOnly => "dir not writable!",
            Self::Unavailable => "unavailable",
        }
    }
}

/// Returns `true` if the current process can write to `path`.
/// For directories, briefly creates and removes a probe file to test access accurately.
///
/// Uses `create_new(true)` to avoid following a pre-existing symlink (TOCTOU mitigation).
/// A PID-suffixed probe name with up to 5 attempts handles the rare case where a previous
/// probe file with the same name already exists, avoiding false negatives.
fn is_writable(path: &Path) -> bool {
    if path.is_file() {
        std::fs::OpenOptions::new().write(true).open(path).is_ok()
    } else if path.is_dir() {
        let pid = std::process::id();
        for attempt in 0..5u32 {
            let probe = path.join(format!(".tokf_write_check_{pid}_{attempt}"));
            match std::fs::OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(&probe)
            {
                Ok(_) => {
                    let _ = std::fs::remove_file(&probe);
                    return true;
                }
                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
                Err(_) => return false,
            }
        }
        false
    } else {
        false
    }
}

/// Determine write-access status for `path`, walking up to the nearest existing ancestor
/// when the path itself does not exist.
fn check_write_access(path: &Path) -> WriteAccess {
    if path.exists() {
        return if is_writable(path) {
            WriteAccess::Writable
        } else {
            WriteAccess::ReadOnly
        };
    }
    let mut ancestor = path.parent();
    while let Some(a) = ancestor {
        if a.exists() {
            return if is_writable(a) {
                WriteAccess::WillCreate
            } else {
                WriteAccess::ParentReadOnly
            };
        }
        ancestor = a.parent();
    }
    WriteAccess::Unavailable
}

#[derive(Serialize)]
struct SearchDir {
    scope: &'static str,
    path: String,
    exists: bool,
    /// `Some(access)` when the directory exists; `None` when it does not.
    access: Option<WriteAccess>,
}

#[derive(Serialize)]
struct TrackingDb {
    env_override: Option<String>,
    path: Option<String>,
    exists: bool,
    access: Option<WriteAccess>,
}

#[derive(Serialize)]
struct CacheInfo {
    path: Option<String>,
    exists: bool,
    access: Option<WriteAccess>,
}

#[derive(Serialize)]
struct FilterCounts {
    local: usize,
    user: usize,
    builtin: usize,
    total: usize,
}

#[derive(Serialize)]
struct ConfigFileEntry {
    scope: &'static str,
    path: String,
    exists: bool,
}

#[derive(Serialize)]
struct InfoOutput {
    version: String,
    /// `TOKF_HOME` env var value when set; affects all user-level paths.
    home_override: Option<String>,
    search_dirs: Vec<SearchDir>,
    tracking_db: TrackingDb,
    cache: CacheInfo,
    config_files: Vec<ConfigFileEntry>,
    filters: Option<FilterCounts>,
}

pub fn cmd_info(json: bool) -> i32 {
    let search_dirs = config::default_search_dirs();
    let info = collect_info(&search_dirs);

    if json {
        crate::output::print_json(&info);
    } else {
        print_human(&info);
    }
    0
}

fn collect_search_dirs(search_dirs: &[PathBuf]) -> Vec<SearchDir> {
    let mut dirs: Vec<SearchDir> = search_dirs
        .iter()
        .enumerate()
        .map(|(i, dir)| SearchDir {
            scope: if i == 0 { "local" } else { "user" },
            path: dir.display().to_string(),
            exists: dir.exists(),
            access: dir.exists().then(|| {
                if is_writable(dir) {
                    WriteAccess::Writable
                } else {
                    WriteAccess::ReadOnly
                }
            }),
        })
        .collect();
    dirs.push(SearchDir {
        scope: "built-in",
        path: "<embedded>".to_string(),
        exists: true,
        access: None,
    });
    dirs
}

fn collect_filter_counts(search_dirs: &[PathBuf]) -> Option<FilterCounts> {
    match config::discover_all_filters(search_dirs) {
        Ok(f) => {
            let local = f.iter().filter(|fi| fi.priority == 0).count();
            let user = f
                .iter()
                .filter(|fi| fi.priority > 0 && fi.priority < u8::MAX)
                .count();
            let builtin = f.iter().filter(|fi| fi.priority == u8::MAX).count();
            Some(FilterCounts {
                local,
                user,
                builtin,
                total: f.len(),
            })
        }
        Err(e) => {
            eprintln!("[tokf] error discovering filters: {e:#}");
            None
        }
    }
}

fn collect_info(search_dirs: &[PathBuf]) -> InfoOutput {
    let dirs = collect_search_dirs(search_dirs);

    // Normalise to None when empty/whitespace-only, matching paths::resolve_user_path() behaviour.
    let home_override = std::env::var("TOKF_HOME")
        .ok()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty());
    let env_override = tokf::paths::db_path_override().map(|p| p.display().to_string());
    let db_path = tracking::db_path();
    let db_exists = db_path.as_ref().is_some_and(|p| p.exists());
    let db_access = db_path.as_ref().map(|p| check_write_access(p));
    let tracking_db = TrackingDb {
        env_override,
        path: db_path.map(|p| p.display().to_string()),
        exists: db_exists,
        access: db_access,
    };

    let cache_path = config::cache::cache_path(search_dirs);
    let cache_exists = cache_path.as_ref().is_some_and(|p| p.exists());
    let cache_access = cache_path.as_ref().map(|p| check_write_access(p));
    let cache = CacheInfo {
        path: cache_path.map(|p| p.display().to_string()),
        exists: cache_exists,
        access: cache_access,
    };

    let config_files = collect_config_files();

    InfoOutput {
        version: env!("CARGO_PKG_VERSION").to_string(),
        home_override,
        search_dirs: dirs,
        tracking_db,
        cache,
        config_files,
        filters: collect_filter_counts(search_dirs),
    }
}

fn collect_config_files() -> Vec<ConfigFileEntry> {
    let user_dir = tokf::paths::user_dir();
    let cwd = std::env::current_dir().unwrap_or_default();
    let project_root = tokf::history::project_root_for(&cwd);
    let local_dir = project_root.join(".tokf");

    let mut entries = Vec::new();

    // Global config files
    let global_files = ["config.toml", "auth.toml", "machine.toml", "rewrites.toml"];
    for file in &global_files {
        let path = user_dir.as_ref().map(|d| d.join(file));
        let exists = path.as_ref().is_some_and(|p| p.exists());
        entries.push(ConfigFileEntry {
            scope: "global",
            path: path.map_or_else(|| "(unavailable)".to_string(), |p| p.display().to_string()),
            exists,
        });
    }

    // Local config files
    let local_files = ["config.toml", "rewrites.toml"];
    for file in &local_files {
        let path = local_dir.join(file);
        let exists = path.exists();
        entries.push(ConfigFileEntry {
            scope: "local",
            path: path.display().to_string(),
            exists,
        });
    }

    entries
}

fn print_human(info: &InfoOutput) {
    println!("tokf {}", info.version);
    match &info.home_override {
        Some(p) => println!("TOKF_HOME: {p}"),
        None => println!("TOKF_HOME: (not set)"),
    }

    println!("\nfilter search directories:");
    for dir in &info.search_dirs {
        if dir.scope == "built-in" {
            println!("  [{}] {} (always available)", dir.scope, dir.path);
        } else {
            let status = if dir.exists {
                match dir.access {
                    Some(WriteAccess::Writable) => "exists, writable",
                    Some(WriteAccess::ReadOnly) => "exists, read-only!",
                    _ => "exists",
                }
            } else {
                "not found"
            };
            println!("  [{}] {} ({status})", dir.scope, dir.path);
        }
    }

    println!("\ntracking database:");
    match &info.tracking_db.env_override {
        Some(p) => println!("  TOKF_DB_PATH: {p}"),
        None => println!("  TOKF_DB_PATH: (not set)"),
    }
    match &info.tracking_db.path {
        Some(p) => {
            let status = info
                .tracking_db
                .access
                .map_or("unknown", WriteAccess::label);
            println!("  path: {p} ({status})");
        }
        None => println!("  path: (could not determine)"),
    }

    println!("\nfilter cache:");
    match &info.cache.path {
        Some(p) => {
            let status = info.cache.access.map_or("unknown", WriteAccess::label);
            println!("  path: {p} ({status})");
        }
        None => println!("  path: (could not determine)"),
    }

    println!("\nconfig files:");
    for entry in &info.config_files {
        let status = if entry.exists { "exists" } else { "not found" };
        println!("  [{}] {} ({status})", entry.scope, entry.path);
    }

    if let Some(f) = &info.filters {
        println!("\nfilters:");
        println!("  local:    {}", f.local);
        println!("  user:     {}", f.user);
        println!("  built-in: {}", f.builtin);
        println!("  total:    {}", f.total);
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use tempfile::TempDir;

    use super::*;

    #[test]
    fn is_writable_true_for_writable_file() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, b"hello").unwrap();
        assert!(is_writable(&file));
    }

    #[cfg(unix)]
    #[test]
    fn is_writable_false_for_readonly_file() {
        use std::os::unix::fs::PermissionsExt;
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("ro.txt");
        std::fs::write(&file, b"hello").unwrap();
        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o444)).unwrap();
        assert!(!is_writable(&file));
        // Restore so TempDir cleanup can remove the file.
        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o644)).unwrap();
    }

    #[test]
    fn is_writable_true_for_writable_dir() {
        let dir = TempDir::new().unwrap();
        assert!(is_writable(dir.path()));
    }

    #[cfg(unix)]
    #[test]
    fn is_writable_false_for_readonly_dir() {
        use std::os::unix::fs::PermissionsExt;
        let tmp = TempDir::new().unwrap();
        let ro_dir = tmp.path().join("ro_dir");
        std::fs::create_dir(&ro_dir).unwrap();
        std::fs::set_permissions(&ro_dir, std::fs::Permissions::from_mode(0o555)).unwrap();
        assert!(!is_writable(&ro_dir));
        // Restore so cleanup works.
        std::fs::set_permissions(&ro_dir, std::fs::Permissions::from_mode(0o755)).unwrap();
    }

    #[test]
    fn check_write_access_writable_for_existing_writable_file() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.db");
        std::fs::write(&file, b"").unwrap();
        assert_eq!(check_write_access(&file), WriteAccess::Writable);
    }

    #[cfg(unix)]
    #[test]
    fn check_write_access_read_only_for_readonly_file() {
        use std::os::unix::fs::PermissionsExt;
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("ro.db");
        std::fs::write(&file, b"").unwrap();
        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o444)).unwrap();
        assert_eq!(check_write_access(&file), WriteAccess::ReadOnly);
        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o644)).unwrap();
    }

    #[test]
    fn check_write_access_will_create_for_nonexistent_in_writable_dir() {
        let dir = TempDir::new().unwrap();
        // Path doesn't exist but its grandparent (the temp dir) is writable.
        let nonexistent = dir.path().join("subdir").join("new.db");
        assert_eq!(check_write_access(&nonexistent), WriteAccess::WillCreate);
    }

    #[cfg(unix)]
    #[test]
    fn check_write_access_parent_read_only_when_dir_not_writable() {
        use std::os::unix::fs::PermissionsExt;
        let tmp = TempDir::new().unwrap();
        let ro_dir = tmp.path().join("ro");
        std::fs::create_dir(&ro_dir).unwrap();
        std::fs::set_permissions(&ro_dir, std::fs::Permissions::from_mode(0o555)).unwrap();
        let nested = ro_dir.join("new.db");
        assert_eq!(check_write_access(&nested), WriteAccess::ParentReadOnly);
        std::fs::set_permissions(&ro_dir, std::fs::Permissions::from_mode(0o755)).unwrap();
    }
}