Skip to main content

trusty_code/workstreams/
path.rs

1//! Storage-path derivation for the workstream store (DOC-48 §3.1).
2//!
3//! Why: the spec pins the filename shape (`workstreams-{project_slug}-{hash}.json`)
4//! to the daemon's OWN [`ProjectBinding`] — never a caller-supplied label —
5//! so two daemons bound to the same project always agree on one file, and
6//! two different projects (even same-named checkouts) never collide.
7//! What: [`store_filename`] derives the filesystem-safe slug + a truncated
8//! SHA-256 fingerprint of the canonical root from a [`ProjectBinding`];
9//! [`store_path`] joins it under a data directory; [`default_data_dir`]
10//! resolves `~/.trusty-code` (mirrors trusty-mpm's `~/.trusty-mpm`
11//! precedent, `crates/trusty-mpm/src/core/paths.rs`).
12//! Test: `path_tests`.
13
14use std::path::{Path, PathBuf};
15
16use sha2::{Digest, Sha256};
17
18use crate::binding::ProjectBinding;
19
20/// Number of hex characters kept from the SHA-256 digest (§3.1: "truncated
21/// to 8 chars").
22const HASH_LEN: usize = 8;
23
24/// Fixed filename used when the daemon is projectless (`ProjectBinding::None`).
25///
26/// Why: DOC-48 §2.3/§3.1 only specify the filename shape for a BOUND
27/// project; a projectless daemon has no path to slug or hash. Rather than
28/// fabricate a fake root, this ticket resolves the ambiguity with one fixed,
29/// documented filename — a projectless daemon has at most one workstream
30/// store regardless of which directory `tcode serve` happened to start in.
31const PROJECTLESS_FILENAME: &str = "workstreams-projectless.json";
32
33/// Resolve `~/.trusty-code`, the trusty-code data directory.
34///
35/// Why: mirrors `trusty-mpm`'s `~/.trusty-mpm` precedent
36/// (`crates/trusty-mpm/src/core/paths.rs`) rather than inventing a new
37/// resolution convention.
38/// What: `dirs::home_dir()/.trusty-code`, falling back to a relative
39/// `.trusty-code` if the home directory cannot be resolved (never panics).
40/// Test: `path_tests::default_data_dir_is_dot_trusty_code`.
41pub fn default_data_dir() -> PathBuf {
42    dirs::home_dir()
43        .unwrap_or_else(|| PathBuf::from("."))
44        .join(".trusty-code")
45}
46
47/// Turn an arbitrary string into a filesystem-safe, lowercase, hyphenated
48/// slug.
49///
50/// Why: a project's directory basename may contain characters unsafe for a
51/// filename component (spaces, underscores, mixed case); the slug must be
52/// stable and readable.
53/// What: keeps ASCII alphanumerics (lowercased), collapses any run of other
54/// characters into a single `-`, and trims leading/trailing `-`. An
55/// all-non-alphanumeric input slugs to `"project"` rather than an empty
56/// string.
57/// Test: `path_tests::slugify_*`.
58fn slugify(raw: &str) -> String {
59    let mut slug = String::with_capacity(raw.len());
60    let mut last_was_dash = false;
61    for ch in raw.chars() {
62        if ch.is_ascii_alphanumeric() {
63            slug.push(ch.to_ascii_lowercase());
64            last_was_dash = false;
65        } else if !last_was_dash && !slug.is_empty() {
66            slug.push('-');
67            last_was_dash = true;
68        }
69    }
70    while slug.ends_with('-') {
71        slug.pop();
72    }
73    if slug.is_empty() {
74        "project".to_string()
75    } else {
76        slug
77    }
78}
79
80/// Deterministic 8-hex-char fingerprint of a project root path.
81///
82/// Why: disambiguates multiple checkouts that share a directory basename
83/// (§3.1: "to handle multiple checkouts of the same project").
84/// What: SHA-256 of the path's platform string, truncated to
85/// [`HASH_LEN`] lowercase hex characters. Deterministic for a given path,
86/// unlike a per-process `RandomState`-seeded hasher.
87/// Test: `path_tests::project_hash_is_deterministic`,
88/// `path_tests::project_hash_differs_for_different_paths`.
89fn project_hash(root: &Path) -> String {
90    let mut hasher = Sha256::new();
91    hasher.update(root.to_string_lossy().as_bytes());
92    let digest = hasher.finalize();
93    let mut hex = String::with_capacity(digest.len() * 2);
94    for byte in digest {
95        hex.push_str(&format!("{byte:02x}"));
96    }
97    hex.truncate(HASH_LEN);
98    hex
99}
100
101/// Derive the workstream store's filename from a daemon's project binding
102/// (DOC-48 §3.1).
103///
104/// Why: the ONE place the filename shape is assembled, so the store and any
105/// future inspection tooling can never disagree on it.
106/// What: for a bound project, `workstreams-{slug}-{hash}.json` where `slug`
107/// comes from the root's basename and `hash` fingerprints the full root
108/// path (§3.1). For [`ProjectBinding::None`], the fixed
109/// [`PROJECTLESS_FILENAME`] (see its docs for why).
110/// Test: `path_tests::store_filename_for_bound_project`,
111/// `path_tests::store_filename_for_projectless`.
112pub fn store_filename(binding: &ProjectBinding) -> String {
113    match binding.root() {
114        Some(root) => {
115            let basename = root
116                .file_name()
117                .map(|n| n.to_string_lossy().to_string())
118                .unwrap_or_else(|| root.display().to_string());
119            let slug = slugify(&basename);
120            let hash = project_hash(root);
121            format!("workstreams-{slug}-{hash}.json")
122        }
123        None => PROJECTLESS_FILENAME.to_string(),
124    }
125}
126
127/// Join [`store_filename`] under a data directory to get the full store path.
128///
129/// Why: the single entry point `WorkstreamStore::load_for_binding` (and any
130/// future daemon boot code) calls to resolve where the store file lives.
131/// What: `data_dir.join(store_filename(binding))`.
132/// Test: `path_tests::store_path_joins_data_dir_and_filename`.
133pub fn store_path(data_dir: &Path, binding: &ProjectBinding) -> PathBuf {
134    data_dir.join(store_filename(binding))
135}
136
137#[cfg(test)]
138#[path = "path_tests.rs"]
139mod path_tests;