bcode_tui 0.0.1-alpha.0

Terminal user interface for bcode
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
//! Bounded external theme discovery.

use std::collections::BTreeMap;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};

use super::definition::{MAX_THEME_FILE_BYTES, ThemeCatalog, ThemeError, parse_theme_definition};

/// Maximum candidate theme files discovered in one refresh.
pub const MAX_DISCOVERED_THEME_FILES: usize = 256;
/// Maximum aggregate theme bytes read in one refresh.
pub const MAX_DISCOVERED_THEME_BYTES: usize = 4 * 1024 * 1024;

/// Origin and precedence class for a discovered theme.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ThemeSourceKind {
    /// User configuration directory.
    User,
    /// Repository-local `.bcode/themes` directory.
    Project,
    /// Explicit authorized file/directory from configuration.
    Explicit,
}

/// One safe theme discovery root.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ThemeDiscoveryRoot {
    /// Root path or exact file path.
    pub path: PathBuf,
    /// Root precedence class.
    pub kind: ThemeSourceKind,
}

impl ThemeDiscoveryRoot {
    /// Create a discovery root.
    #[must_use]
    pub fn new(path: impl Into<PathBuf>, kind: ThemeSourceKind) -> Self {
        Self {
            path: path.into(),
            kind,
        }
    }
}

/// Bounded diagnostic from one ignored external theme candidate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ThemeDiscoveryDiagnostic {
    /// Candidate path.
    pub path: PathBuf,
    /// Secret-safe failure description.
    pub message: String,
}

/// Accepted origin for one external theme definition.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ThemeExternalSource {
    /// Canonical accepted source path.
    pub path: PathBuf,
    /// Discovery precedence class that accepted the source.
    pub kind: ThemeSourceKind,
}

/// Result of one deterministic theme discovery pass.
#[derive(Debug, Clone)]
pub struct DiscoveredThemes {
    /// Bundled and valid external definitions in final precedence order.
    pub catalog: ThemeCatalog,
    /// Accepted external source keyed by final stable theme id.
    pub sources: BTreeMap<String, ThemeExternalSource>,
    /// Invalid or unsafe candidates that were skipped.
    pub diagnostics: Vec<ThemeDiscoveryDiagnostic>,
}

/// Discover the default user/project roots plus configured explicit roots.
///
/// Root order is bundled, user, project, explicit. Later valid definitions
/// replace earlier definitions with the same stable id.
#[must_use]
pub fn default_theme_roots(
    user_config_dir: &Path,
    project_root: &Path,
    explicit: &[PathBuf],
) -> Vec<ThemeDiscoveryRoot> {
    let mut roots = vec![
        ThemeDiscoveryRoot::new(user_config_dir.join("themes"), ThemeSourceKind::User),
        ThemeDiscoveryRoot::new(
            project_root.join(".bcode").join("themes"),
            ThemeSourceKind::Project,
        ),
    ];
    roots.extend(
        explicit
            .iter()
            .cloned()
            .map(|path| ThemeDiscoveryRoot::new(path, ThemeSourceKind::Explicit)),
    );
    roots
}

/// Stable bounded signature of the current authorized theme inputs.
///
/// Missing roots are represented explicitly. Directory roots are shallow and
/// include only direct `.toml` candidates, matching discovery semantics. This
/// routine performs only the same bounded, confined reads as discovery and
/// never parses or mutates theme files.
#[must_use]
pub fn theme_input_signature(roots: &[ThemeDiscoveryRoot]) -> u64 {
    let mut hasher = DefaultHasher::new();
    let mut candidates = Vec::new();
    let mut diagnostics = Vec::new();
    for root in roots {
        root.kind.hash(&mut hasher);
        root.path.hash(&mut hasher);
        root.path.exists().hash(&mut hasher);
        collect_root_candidates(root, &mut candidates, &mut diagnostics);
    }
    candidates.sort_by(|left, right| {
        left.kind
            .cmp(&right.kind)
            .then_with(|| left.path.cmp(&right.path))
    });
    candidates.truncate(MAX_DISCOVERED_THEME_FILES);
    let mut aggregate_bytes = 0_usize;
    for candidate in candidates {
        candidate.kind.hash(&mut hasher);
        candidate.path.hash(&mut hasher);
        let Ok(bytes) = std::fs::read(&candidate.path) else {
            continue;
        };
        if bytes.len() > MAX_THEME_FILE_BYTES
            || aggregate_bytes.saturating_add(bytes.len()) > MAX_DISCOVERED_THEME_BYTES
        {
            continue;
        }
        aggregate_bytes = aggregate_bytes.saturating_add(bytes.len());
        bytes.hash(&mut hasher);
    }
    for diagnostic in diagnostics {
        diagnostic.path.hash(&mut hasher);
        diagnostic.message.hash(&mut hasher);
    }
    hasher.finish()
}

/// Discover valid theme definitions from confined roots.
///
/// Missing roots are ignored. Candidate files must be regular `.toml` files.
/// Directory roots are shallow by design: every accepted candidate must remain
/// directly under the canonicalized authorized root. Symlinked candidates are
/// accepted only when their canonical target remains under that root.
///
/// # Errors
///
/// Returns an error only when embedded bundled themes are invalid. External
/// damage is represented by bounded diagnostics so one malformed custom theme
/// cannot prevent use of the remaining catalog.
pub fn discover_themes(roots: &[ThemeDiscoveryRoot]) -> Result<DiscoveredThemes, ThemeError> {
    let mut catalog = ThemeCatalog::bundled()?;
    let mut sources = BTreeMap::new();
    let mut diagnostics = Vec::new();
    let mut candidates = Vec::new();
    for root in roots {
        collect_root_candidates(root, &mut candidates, &mut diagnostics);
    }
    candidates.sort_by(|left, right| {
        left.kind
            .cmp(&right.kind)
            .then_with(|| left.path.cmp(&right.path))
    });
    if candidates.len() > MAX_DISCOVERED_THEME_FILES {
        diagnostics.push(ThemeDiscoveryDiagnostic {
            path: PathBuf::new(),
            message: format!(
                "theme candidate limit exceeded; only the first {MAX_DISCOVERED_THEME_FILES} candidates were inspected"
            ),
        });
        candidates.truncate(MAX_DISCOVERED_THEME_FILES);
    }

    let mut aggregate_bytes = 0_usize;
    for candidate in candidates {
        let metadata = match std::fs::metadata(&candidate.path) {
            Ok(metadata) => metadata,
            Err(error) => {
                push_diagnostic(
                    &mut diagnostics,
                    &candidate.path,
                    format!("metadata: {error}"),
                );
                continue;
            }
        };
        let Ok(file_bytes) = usize::try_from(metadata.len()) else {
            push_diagnostic(
                &mut diagnostics,
                &candidate.path,
                "file size is unsupported",
            );
            continue;
        };
        if file_bytes > MAX_THEME_FILE_BYTES {
            push_diagnostic(
                &mut diagnostics,
                &candidate.path,
                format!("file exceeds the {MAX_THEME_FILE_BYTES}-byte limit"),
            );
            continue;
        }
        if aggregate_bytes.saturating_add(file_bytes) > MAX_DISCOVERED_THEME_BYTES {
            push_diagnostic(
                &mut diagnostics,
                &candidate.path,
                format!("aggregate theme byte limit {MAX_DISCOVERED_THEME_BYTES} reached"),
            );
            break;
        }
        aggregate_bytes = aggregate_bytes.saturating_add(file_bytes);
        let text = match std::fs::read_to_string(&candidate.path) {
            Ok(text) => text,
            Err(error) => {
                push_diagnostic(&mut diagnostics, &candidate.path, format!("read: {error}"));
                continue;
            }
        };
        match parse_theme_definition(candidate.path.display().to_string(), &text) {
            Ok(definition) => {
                let id = definition.id().to_owned();
                catalog.insert(definition);
                sources.insert(
                    id,
                    ThemeExternalSource {
                        path: candidate.path,
                        kind: candidate.kind,
                    },
                );
            }
            Err(error) => push_diagnostic(&mut diagnostics, &candidate.path, error.to_string()),
        }
    }
    Ok(DiscoveredThemes {
        catalog,
        sources,
        diagnostics,
    })
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct Candidate {
    path: PathBuf,
    kind: ThemeSourceKind,
}

fn collect_root_candidates(
    root: &ThemeDiscoveryRoot,
    candidates: &mut Vec<Candidate>,
    diagnostics: &mut Vec<ThemeDiscoveryDiagnostic>,
) {
    if !root.path.exists() {
        return;
    }
    let canonical_root = match std::fs::canonicalize(&root.path) {
        Ok(path) => path,
        Err(error) => {
            push_diagnostic(diagnostics, &root.path, format!("root: {error}"));
            return;
        }
    };
    if canonical_root.is_file() {
        push_candidate(
            &root.path,
            canonical_root.parent().unwrap_or_else(|| Path::new("/")),
            root.kind,
            candidates,
            diagnostics,
        );
        return;
    }
    if !canonical_root.is_dir() {
        push_diagnostic(diagnostics, &root.path, "root is not a file or directory");
        return;
    }
    let entries = match std::fs::read_dir(&canonical_root) {
        Ok(entries) => entries,
        Err(error) => {
            push_diagnostic(diagnostics, &root.path, format!("directory: {error}"));
            return;
        }
    };
    let mut paths = entries
        .filter_map(Result::ok)
        .map(|entry| entry.path())
        .collect::<Vec<_>>();
    paths.sort();
    for path in paths {
        push_candidate(&path, &canonical_root, root.kind, candidates, diagnostics);
    }
}

fn push_candidate(
    path: &Path,
    canonical_root: &Path,
    kind: ThemeSourceKind,
    candidates: &mut Vec<Candidate>,
    diagnostics: &mut Vec<ThemeDiscoveryDiagnostic>,
) {
    if path.extension().and_then(std::ffi::OsStr::to_str) != Some("toml") {
        return;
    }
    let canonical = match std::fs::canonicalize(path) {
        Ok(canonical) => canonical,
        Err(error) => {
            push_diagnostic(diagnostics, path, format!("candidate: {error}"));
            return;
        }
    };
    if !canonical.starts_with(canonical_root) {
        push_diagnostic(diagnostics, path, "candidate escapes its authorized root");
        return;
    }
    if !canonical.is_file() {
        push_diagnostic(diagnostics, path, "candidate is not a regular file");
        return;
    }
    candidates.push(Candidate {
        path: canonical,
        kind,
    });
}

fn push_diagnostic(
    diagnostics: &mut Vec<ThemeDiscoveryDiagnostic>,
    path: &Path,
    message: impl Into<String>,
) {
    if diagnostics.len() < MAX_DISCOVERED_THEME_FILES {
        diagnostics.push(ThemeDiscoveryDiagnostic {
            path: path.to_path_buf(),
            message: message.into(),
        });
    }
}

#[cfg(test)]
mod tests {
    use std::fs;

    use bmux_tui::style::Color;
    use tempfile::tempdir;

    use super::{ThemeDiscoveryRoot, ThemeSourceKind, default_theme_roots, discover_themes};
    use crate::theme::definition::ThemeSelection;

    fn theme(id: &str, accent: &str) -> String {
        format!("schema_version = 1\nid = \"{id}\"\n[palette]\naccent = \"{accent}\"\n")
    }

    #[test]
    fn theme_input_signature_changes_for_file_revision_and_disappearance() {
        let temp = tempdir().expect("tempdir");
        let path = temp.path().join("live.toml");
        fs::write(&path, theme("live", "#112233")).expect("theme");
        let roots = [ThemeDiscoveryRoot::new(
            temp.path(),
            ThemeSourceKind::Explicit,
        )];
        let initial = super::theme_input_signature(&roots);

        fs::write(&path, theme("live", "#445566")).expect("revision");
        let revised = super::theme_input_signature(&roots);
        fs::remove_file(path).expect("remove theme");
        let missing = super::theme_input_signature(&roots);

        assert_ne!(initial, revised);
        assert_ne!(revised, missing);
    }

    #[test]
    fn default_roots_have_expected_precedence() {
        let roots = default_theme_roots(
            std::path::Path::new("/user/bcode"),
            std::path::Path::new("/project"),
            &[std::path::PathBuf::from("/explicit")],
        );
        assert_eq!(roots[0].kind, ThemeSourceKind::User);
        assert_eq!(roots[1].kind, ThemeSourceKind::Project);
        assert_eq!(roots[2].kind, ThemeSourceKind::Explicit);
        assert_eq!(
            roots[1].path,
            std::path::Path::new("/project/.bcode/themes")
        );
    }

    #[test]
    fn later_valid_sources_override_and_invalid_files_are_diagnostics() {
        let temp = tempdir().expect("tempdir");
        let user = temp.path().join("user");
        let project = temp.path().join("project");
        fs::create_dir_all(&user).expect("user dir");
        fs::create_dir_all(&project).expect("project dir");
        fs::write(user.join("same.toml"), theme("same", "#112233")).expect("user theme");
        fs::write(project.join("same.toml"), theme("same", "#445566")).expect("project theme");
        fs::write(project.join("bad.toml"), "not = [valid").expect("bad theme");

        let discovered = discover_themes(&[
            ThemeDiscoveryRoot::new(&user, ThemeSourceKind::User),
            ThemeDiscoveryRoot::new(&project, ThemeSourceKind::Project),
        ])
        .expect("discovery succeeds");
        let resolved = discovered
            .catalog
            .resolve(&ThemeSelection::new("same"))
            .expect("same resolves");

        assert_eq!(resolved.color("accent"), Some(Color::Rgb(68, 85, 102)));
        assert_eq!(discovered.diagnostics.len(), 1);
        assert!(
            discovered.sources["same"]
                .path
                .parent()
                .is_some_and(|parent| parent.ends_with("project"))
        );
        assert_eq!(discovered.sources["same"].kind, ThemeSourceKind::Project);
    }

    #[cfg(unix)]
    #[test]
    fn symlink_escape_is_rejected() {
        use std::os::unix::fs::symlink;

        let temp = tempdir().expect("tempdir");
        let root = temp.path().join("root");
        fs::create_dir_all(&root).expect("root");
        let outside = temp.path().join("outside.toml");
        fs::write(&outside, theme("outside", "#112233")).expect("outside");
        symlink(&outside, root.join("escape.toml")).expect("symlink");

        let discovered =
            discover_themes(&[ThemeDiscoveryRoot::new(&root, ThemeSourceKind::Explicit)])
                .expect("discovery succeeds");

        assert_eq!(discovered.diagnostics.len(), 1);
        assert!(
            discovered
                .catalog
                .resolve(&ThemeSelection::new("outside"))
                .is_err()
        );
    }
}