Skip to main content

clm_rust_core/
fs_utils.rs

1use std::fs;
2use std::path::{Path, PathBuf};
3use std::io::{self, Read};
4
5// Explicit SHA-256 computation for legacy/specific SHA-256 contracts.
6pub fn compute_sha256_hex(content: &[u8]) -> String {
7    use sha2::{Digest, Sha256};
8    let mut hasher = Sha256::new();
9    hasher.update(content);
10    format!("{:x}", hasher.finalize())
11}
12
13pub fn compute_content_hash(input: &str) -> String {
14    if input == "-" {
15        let mut buffer = Vec::new();
16        let mut stdin = io::stdin();
17        let _ = stdin.read_to_end(&mut buffer);
18        crate::hash::raw_hash_bytes(&buffer)
19    } else if let Ok(metadata) = fs::metadata(input) {
20        if metadata.is_file()
21            && let Ok(data) = fs::read(input) {
22                return crate::hash::raw_hash_bytes(&data);
23            }
24        crate::hash::raw_hash_bytes(input.as_bytes())
25    } else {
26        crate::hash::raw_hash_bytes(input.as_bytes())
27    }
28}
29
30pub fn compute_stripped_file_hash(path: &Path) -> io::Result<String> {
31    let content = fs::read_to_string(path)?;
32    // Emulate bash's $(cat file) which strips trailing newlines (\n and \r)
33    let trimmed = content.trim_end_matches(['\n', '\r']);
34    Ok(crate::hash::raw_hash_bytes(trimmed.as_bytes()))
35}
36
37pub fn get_file_handle(raw_path: &str, clm_root: Option<&str>) -> String {
38    // 1. Resolve absolute path
39    let path = Path::new(raw_path);
40    let abs_path = if path.is_absolute() {
41        path.to_path_buf()
42    } else if let Ok(curr) = std::env::current_dir() {
43        curr.join(path)
44    } else {
45        path.to_path_buf()
46    };
47
48    // 2. Canonicalize path representation (resolve parent dirs/dots, but keep as String)
49    // We do clean normalization manually to avoid issues with non-existent paths.
50    let mut components = Vec::new();
51    for component in abs_path.components() {
52        match component {
53            std::path::Component::Prefix(prefix) => {
54                // Windows prefix (e.g. C:) -> map to lowercase /c/
55                let prefix_str = prefix.as_os_str().to_string_lossy().to_string();
56                if prefix_str.len() >= 2 && prefix_str.ends_with(':') {
57                    let drive = prefix_str[0..1].to_lowercase();
58                    components.push(format!("/{}", drive));
59                } else {
60                    components.push(prefix_str);
61                }
62            }
63            std::path::Component::RootDir => {
64                // Root is implicit if components start with /
65            }
66            std::path::Component::CurDir => {}
67            std::path::Component::ParentDir => {
68                components.pop();
69            }
70            std::path::Component::Normal(val) => {
71                components.push(val.to_string_lossy().to_string());
72            }
73        }
74    }
75
76    let mut norm_abs = components.join("/");
77    if !norm_abs.starts_with('/') {
78        norm_abs = format!("/{}", norm_abs);
79    }
80    // Remove duplicate slashes
81    while norm_abs.contains("//") {
82        norm_abs = norm_abs.replace("//", "/");
83    }
84    if norm_abs.len() > 1 && norm_abs.ends_with('/') {
85        norm_abs.pop();
86    }
87
88    // Normalize CLM_ROOT
89    let root_path = clm_root.map(PathBuf::from).unwrap_or_else(|| {
90        std::env::var("CLM_ROOT")
91            .map(PathBuf::from)
92            .unwrap_or_else(|_| PathBuf::from("."))
93    });
94    
95    let abs_root = if root_path.is_absolute() {
96        root_path
97    } else if let Ok(curr) = std::env::current_dir() {
98        curr.join(root_path)
99    } else {
100        root_path
101    };
102
103    let mut root_components = Vec::new();
104    for component in abs_root.components() {
105        match component {
106            std::path::Component::Prefix(prefix) => {
107                let prefix_str = prefix.as_os_str().to_string_lossy().to_string();
108                if prefix_str.len() >= 2 && prefix_str.ends_with(':') {
109                    let drive = prefix_str[0..1].to_lowercase();
110                    root_components.push(format!("/{}", drive));
111                } else {
112                    root_components.push(prefix_str);
113                }
114            }
115            std::path::Component::RootDir => {}
116            std::path::Component::CurDir => {}
117            std::path::Component::ParentDir => {
118                root_components.pop();
119            }
120            std::path::Component::Normal(val) => {
121                root_components.push(val.to_string_lossy().to_string());
122            }
123        }
124    }
125    let mut norm_root = root_components.join("/");
126    if !norm_root.starts_with('/') {
127        norm_root = format!("/{}", norm_root);
128    }
129    while norm_root.contains("//") {
130        norm_root = norm_root.replace("//", "/");
131    }
132    if norm_root.len() > 1 && norm_root.ends_with('/') {
133        norm_root.pop();
134    }
135
136    // Check if norm_abs is under norm_root
137    let rel_path = if norm_abs == norm_root {
138        ".".to_string()
139    } else if norm_abs.starts_with(&format!("{}/", norm_root)) {
140        norm_abs[norm_root.len() + 1..].to_string()
141    } else {
142        // Fallback to filename
143        path.file_name()
144            .map(|f| f.to_string_lossy().to_string())
145            .unwrap_or_default()
146    };
147
148    format!("file:{}", rel_path)
149}
150
151/// Stamps a canonical `g_time` coordinate under an explicit algorithm and timestamp.
152pub fn compute_g_time_at(algorithm: &str, timestamp: &str, locale: &str) -> Result<String, String> {
153    let algo = algorithm.trim().trim_end_matches(':').to_lowercase();
154    if !crate::hash::list_algorithms()
155        .iter()
156        .any(|registered| registered.trim_end_matches(':') == algo)
157    {
158        return Err(format!("Unsupported g_time hash algorithm: {algo}"));
159    }
160    if locale.contains('|') {
161        return Err("g_time locale cannot contain the pipe delimiter".to_string());
162    }
163
164    let parsed = match chrono::DateTime::parse_from_rfc3339(timestamp) {
165        Ok(parsed) => parsed,
166        Err(original_error) => {
167            if timestamp.len() < 5 {
168                return Err(format!("Invalid g_time timestamp: {original_error}"));
169            }
170            let offset_start = timestamp.len() - 5;
171            let offset = &timestamp[offset_start..];
172            if (offset.starts_with('+') || offset.starts_with('-'))
173                && offset[1..].chars().all(|ch| ch.is_ascii_digit())
174            {
175                let normalized = format!("{}{}:{}", &timestamp[..offset_start], &offset[..3], &offset[3..]);
176                chrono::DateTime::parse_from_rfc3339(&normalized)
177                    .map_err(|error| format!("Invalid g_time timestamp: {error}"))?
178            } else {
179                return Err(format!("Invalid g_time timestamp: {original_error}"));
180            }
181        }
182    };
183    let canonical_timestamp = parsed.to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
184    Ok(format!("{algo}|{canonical_timestamp}|{locale}"))
185}
186
187/// Stamps a `g_time` coordinate under an explicit algorithm.
188///
189/// The algorithm is a parameter so the label always matches the function that produced the
190/// digest. Grammar: `algorithm|timestamp|locale` (charter ยง3.1.1).
191pub fn compute_g_time_for(algorithm: &str) -> String {
192    let now = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
193    let tz_name = if let Ok(link) = std::fs::read_link("/etc/localtime") {
194        if let Some(pos) = link.to_string_lossy().find("/zoneinfo/") {
195            link.to_string_lossy()[pos + 10..].to_string()
196        } else {
197            "UTC".to_string()
198        }
199    } else {
200        "UTC".to_string()
201    };
202    compute_g_time_at(algorithm, &now, &tz_name).expect("registered writer algorithm and timestamp")
203}
204
205/// Stamps a `g_time` coordinate under the runtime's resolved active hash policy.
206pub fn compute_g_time() -> String {
207    compute_g_time_for(crate::hash::config().active_algorithm)
208}
209
210pub fn get_clm_root() -> PathBuf {
211    let raw = std::env::var("CLM_ROOT").unwrap_or_else(|_| ".".into());
212    normalize_windows_path(Path::new(&raw))
213}
214
215pub fn get_data_dir(clm_root: &str, pillar: &str) -> PathBuf {
216    let zero_fs = crate::utils::is_zero_fs();
217    if zero_fs {
218        let tmp = std::env::var("TMPDIR").unwrap_or_else(|_| std::env::temp_dir().to_string_lossy().to_string());
219        PathBuf::from(tmp).join("data").join(pillar)
220    } else {
221        Path::new(clm_root).join("data").join(pillar)
222    }
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    #[test]
230    fn test_sha256() {
231        assert_eq!(
232            compute_sha256_hex(b"hello"),
233            "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
234        );
235    }
236}
237
238pub fn get_bash_command() -> String {
239    if cfg!(target_os = "windows") {
240        if let Ok(bash_env) = std::env::var("BASH")
241            && Path::new(&bash_env).exists() {
242                return bash_env;
243            }
244        let git_bash = "C:\\Program Files\\Git\\bin\\bash.exe";
245        if Path::new(git_bash).exists() {
246            return git_bash.to_string();
247        }
248    }
249    "bash".to_string()
250}
251
252pub fn normalize_windows_path(p: &Path) -> PathBuf {
253    if cfg!(target_os = "windows") {
254        let s = p.to_string_lossy().to_string();
255        if s.starts_with('/') && s.len() >= 3 && s.chars().nth(2) == Some('/') {
256            let drive = s.chars().nth(1).unwrap().to_uppercase().to_string();
257            let rest = &s[2..];
258            return PathBuf::from(format!("{}:{}", drive, rest));
259        } else if s.starts_with('/') && s.len() == 2 {
260            let drive = s.chars().nth(1).unwrap().to_uppercase().to_string();
261            return PathBuf::from(format!("{}:\\", drive));
262        }
263    }
264    p.to_path_buf()
265}