1use std::collections::HashMap;
8use std::path::{Path, PathBuf};
9use std::process::Command;
10
11#[derive(Debug, Clone, PartialEq, Eq)]
13pub enum Reference {
14 File {
15 path: String,
16 lines: Option<(u32, u32)>,
17 },
18 Symbol {
19 path: String,
20 symbol: String,
21 },
22 Test {
23 path: String,
24 name: String,
25 },
26 Commit(String),
27 Node(String),
28 Url(String),
29}
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum RefState {
34 Valid,
35 Invalid,
36 Unpublished,
38}
39
40fn path_ok(path: &str) -> bool {
42 !path.is_empty()
43 && path.len() <= 300
44 && !path.starts_with('/')
45 && !path.contains('\\')
46 && !path.chars().any(|c| c.is_whitespace() || c.is_control())
47 && path
48 .split('/')
49 .all(|s| !s.is_empty() && s != "." && s != "..")
50}
51
52impl Reference {
53 pub fn to_contract(&self) -> String {
55 match self {
56 Self::File { path, lines: None } => format!("file:{path}"),
57 Self::File {
58 path,
59 lines: Some((a, b)),
60 } if a == b => format!("file:{path}#L{a}"),
61 Self::File {
62 path,
63 lines: Some((a, b)),
64 } => format!("file:{path}#L{a}-{b}"),
65 Self::Symbol { path, symbol } => format!("sym:{path}::{symbol}"),
66 Self::Test { path, name } => format!("test:{path}::{name}"),
67 Self::Commit(sha) => format!("commit:{sha}"),
68 Self::Node(id) => format!("node:{id}"),
69 Self::Url(url) => url.clone(),
70 }
71 }
72}
73
74fn symbol_ok(symbol: &str) -> bool {
75 symbol.len() <= 200
76 && symbol.split("::").flat_map(|s| s.split('.')).all(|seg| {
77 let mut chars = seg.chars();
78 chars
79 .next()
80 .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
81 && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
82 })
83}
84
85fn test_name_ok(name: &str) -> bool {
86 (1..=200).contains(&name.len())
87 && name.chars().all(|c| {
88 c.is_ascii_alphanumeric() || matches!(c, '_' | ':' | '.' | '-' | '[' | ']' | ' ')
89 })
90}
91
92fn url_ok(url: &str) -> bool {
93 let Some(rest) = url.strip_prefix("https://") else {
94 return false;
95 };
96 let host_port = rest.split(['/', '?', '#']).next().unwrap_or_default();
97 let host = host_port.rsplit_once(':').map_or(host_port, |(h, _)| h);
98 url.len() <= 500
99 && !host.is_empty()
100 && !host_port.contains('@')
101 && !host.starts_with('[')
102 && host.parse::<std::net::Ipv4Addr>().is_err()
103 && host.contains('.')
104 && url.chars().all(|c| c.is_ascii_graphic())
105}
106
107pub fn parse(raw: &str) -> Option<Reference> {
109 if raw.starts_with("https://") {
110 return url_ok(raw).then(|| Reference::Url(raw.to_string()));
111 }
112 let (kind, rest) = raw.split_once(':')?;
113 match kind {
114 "file" => {
115 let (path, lines) = match rest.split_once("#L") {
116 Some((path, range)) => {
117 let (a, b) = range.split_once('-').unwrap_or((range, range));
118 let (a, b): (u32, u32) = (a.parse().ok()?, b.parse().ok()?);
119 if a == 0 || a > b {
120 return None;
121 }
122 (path, Some((a, b)))
123 }
124 None => (rest, None),
125 };
126 path_ok(path).then(|| Reference::File {
127 path: path.to_string(),
128 lines,
129 })
130 }
131 "sym" => {
132 let colons = rest.find("::");
136 let (path, symbol) = match (rest.find('#'), colons) {
137 (Some(h), Some(c)) if h < c => rest.split_once('#')?,
138 (Some(_), None) => rest.split_once('#')?,
139 _ => rest.split_once("::")?,
140 };
141 (path_ok(path) && symbol_ok(symbol)).then(|| Reference::Symbol {
142 path: path.to_string(),
143 symbol: symbol.to_string(),
144 })
145 }
146 "test" => {
147 let (path, name) = rest.split_once("::")?;
148 (path_ok(path) && test_name_ok(name)).then(|| Reference::Test {
149 path: path.to_string(),
150 name: name.to_string(),
151 })
152 }
153 "commit" => ((7..=40).contains(&rest.len())
154 && rest
155 .bytes()
156 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
157 .then(|| Reference::Commit(rest.to_string())),
158 "node" => {
159 let id = rest.strip_prefix("n_")?;
160 (id.len() == 26
161 && id
162 .bytes()
163 .all(|b| b.is_ascii_lowercase() || (b'2'..=b'7').contains(&b)))
164 .then(|| Reference::Node(rest.to_string()))
165 }
166 _ => None,
167 }
168}
169
170pub struct Checkout {
175 root: PathBuf,
176 blobs: HashMap<String, Option<Vec<u8>>>,
177 commits: HashMap<String, RefState>,
178 head: Option<String>,
179 head_read: bool,
180 contained: HashMap<String, bool>,
182 pub nodes: std::collections::HashSet<String>,
184}
185
186impl Checkout {
187 pub fn new(root: &Path) -> Self {
188 Self {
189 root: root.to_path_buf(),
190 blobs: HashMap::new(),
191 commits: HashMap::new(),
192 head: None,
193 head_read: false,
194 contained: HashMap::new(),
195 nodes: Default::default(),
196 }
197 }
198
199 pub fn head_contains(&mut self, sha: &str) -> bool {
203 if !(7..=64).contains(&sha.len()) || !sha.bytes().all(|b| b.is_ascii_hexdigit()) {
204 return false;
205 }
206 if let Some(known) = self.contained.get(sha) {
207 return *known;
208 }
209 let known = self
210 .git(&["merge-base", "--is-ancestor", sha, "HEAD"])
211 .is_some();
212 self.contained.insert(sha.to_string(), known);
213 known
214 }
215
216 fn git(&self, args: &[&str]) -> Option<Vec<u8>> {
217 let out = Command::new("git")
218 .arg("-C")
219 .arg(&self.root)
220 .args(args)
221 .env("GIT_TERMINAL_PROMPT", "0")
222 .output()
223 .ok()?;
224 out.status.success().then_some(out.stdout)
225 }
226
227 pub fn blob_bytes(&mut self, path: &str) -> Option<&[u8]> {
229 if !self.blobs.contains_key(path) {
230 let content = self.git(&["cat-file", "-p", &format!("HEAD:{path}")]);
231 self.blobs.insert(path.to_string(), content);
232 }
233 self.blobs.get(path).and_then(Option::as_deref)
234 }
235
236 fn blob(&mut self, path: &str) -> Option<String> {
237 self.blob_bytes(path)
238 .map(|b| String::from_utf8_lossy(b).into_owned())
239 }
240
241 pub fn symbol_span(&mut self, path: &str, symbol: &str) -> Option<Vec<u8>> {
244 let symbol = symbol.replace("::", ".");
245 let leaf = symbol.rsplit('.').next().unwrap_or(&symbol).to_string();
246 let content = self.blob_bytes(path)?;
247 lean_ctx::core::knowledge::anchors::anchored(content, path, Some(&leaf)).map(<[u8]>::to_vec)
248 }
249
250 pub fn head(&mut self) -> Option<String> {
252 if !self.head_read {
253 self.head = self
254 .git(&["rev-parse", "HEAD"])
255 .map(|b| String::from_utf8_lossy(&b).trim().to_string())
256 .filter(|s| matches!(s.len(), 40 | 64));
257 self.head_read = true;
258 }
259 self.head.clone()
260 }
261
262 fn commit(&mut self, sha: &str) -> RefState {
263 if let Some(state) = self.commits.get(sha) {
264 return *state;
265 }
266 let state = if self
267 .git(&["cat-file", "-e", &format!("{sha}^{{commit}}")])
268 .is_none()
269 {
270 RefState::Invalid
271 } else if self
272 .git(&["branch", "-r", "--contains", sha])
273 .is_some_and(|out| !out.trim_ascii().is_empty())
274 {
275 RefState::Valid
276 } else {
277 RefState::Unpublished
278 };
279 self.commits.insert(sha.to_string(), state);
280 state
281 }
282
283 pub fn check(&mut self, reference: &Reference) -> RefState {
285 let ok = |b: bool| {
286 if b {
287 RefState::Valid
288 } else {
289 RefState::Invalid
290 }
291 };
292 match reference {
293 Reference::File { path, lines } => {
294 let Some(content) = self.blob(path) else {
295 return RefState::Invalid;
296 };
297 ok(lines.is_none_or(|(_, b)| b as usize <= content.lines().count()))
298 }
299 Reference::Symbol { path, symbol } => {
300 let path = path.clone();
301 ok(self.symbol_span(&path, symbol).is_some())
302 }
303 Reference::Test { path, name } => {
304 let leaf = name.rsplit("::").next().unwrap_or(name);
305 ok(self.blob(path).is_some_and(|c| c.contains(leaf)))
306 }
307 Reference::Commit(sha) => self.commit(sha),
308 Reference::Node(id) => ok(self.nodes.contains(id)),
309 Reference::Url(_) => RefState::Valid,
310 }
311 }
312}
313
314#[cfg(test)]
315mod tests {
316 use super::*;
317
318 #[test]
319 fn grammar() {
320 for good in [
321 "file:rust/src/lib.rs",
322 "file:rust/src/lib.rs#L3-9",
323 "file:README.md#L1",
324 "sym:rust/src/core/cloud/outbox.rs#Outbox::push",
325 "test:rust/src/a.rs::tests::name",
326 "commit:4a551fc452",
327 "node:n_abcdefghijklmnopqrstuvwxyz",
328 "https://docs.rs/blake3/latest/blake3/",
329 ] {
330 assert!(parse(good).is_some(), "{good}");
331 }
332 for bad in [
333 "file:/etc/passwd",
334 "file:../x.rs",
335 "file:a/./b.rs",
336 "file:a.rs#L0",
337 "file:a.rs#L9-3",
338 "sym:a.rs#1bad",
339 "commit:XYZ1234",
340 "commit:abc",
341 "node:n_short",
342 "http://example.com",
343 "https://127.0.0.1/x",
344 "https://user@example.com/x",
345 "https://localhost/x",
346 "ftp:x",
347 "plain text",
348 ] {
349 assert!(parse(bad).is_none(), "{bad}");
350 }
351 }
352
353 #[test]
356 fn contract_anchor_refs() {
357 let path = std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../.."))
358 .join("crates/lean-ctx-protocol/tests/fixtures/cloud-v2/vectors/anchor.vectors.json");
359 let v: serde_json::Value =
360 serde_json::from_slice(&std::fs::read(path).expect("vectors")).expect("json");
361 for case in v["ref"].as_array().expect("ref cases") {
362 let input = case["input"].as_str().expect("input");
363 let out = &case["output"];
364 match parse(input) {
365 None => assert_eq!(out["valid"], false, "{input}"),
366 Some(r) => {
367 assert_eq!(out["valid"], true, "{input}");
368 assert_eq!(r.to_contract(), input);
369 match r {
370 Reference::File { path, .. } => assert_eq!(out["path"], path.as_str()),
371 Reference::Symbol { path, symbol } => {
372 assert_eq!(out["path"], path.as_str());
373 assert_eq!(out["symbol"], symbol.as_str());
374 }
375 other => panic!("{input}: {other:?}"),
376 }
377 }
378 }
379 }
380 assert_eq!(
381 parse("sym:src/lib.rs#Client::send").map(|r| r.to_contract()),
382 Some("sym:src/lib.rs::Client::send".to_string())
383 );
384 }
385}