Skip to main content

clm_rust_core/layer0/
fs_utils.rs

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