1use std::path::Path;
44
45use crate::manifest::{Line, MANIFEST};
46
47pub const PACK_FILE: &str = crate::names::PACK_FILE;
51
52#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct Source {
55 pub label: String,
57 pub url: String,
59 pub rev: Option<String>,
61}
62
63fn looks_like_path(body: &str) -> bool {
77 let b = body.as_bytes();
78 let drive = b.len() >= 3
80 && b[0].is_ascii_alphabetic()
81 && b[1] == b':'
82 && (b[2] == b'\\' || b[2] == b'/');
83 body.starts_with('/') || drive
85 || body.starts_with(r"\\") || std::path::Path::new(body).exists() }
88
89pub fn parse_source(spec: &str) -> Result<Source, String> {
99 if spec.is_empty() {
100 return Err("empty source".into());
101 }
102 let slash = spec.rfind(['/', '\\']).map(|i| i as isize).unwrap_or(-1);
103 let (body, rev) = match spec.rfind('@') {
104 Some(at) if (at as isize) > slash => (&spec[..at], Some(spec[at + 1..].to_string())),
105 _ => (spec, None),
106 };
107 if rev.as_deref().is_some_and(str::is_empty) {
108 return Err(format!("{spec}: a revision was named but is empty"));
109 }
110 let url = if let Some(rest) = body.strip_prefix("github:") {
111 if rest.split('/').count() != 2 || rest.split('/').any(str::is_empty) {
112 return Err(format!("{spec}: github: wants owner/repo"));
113 }
114 format!("https://github.com/{rest}.git")
115 } else if let Some(rest) = body.strip_prefix("forgejo:") {
116 if rest.split('/').count() != 3 || rest.split('/').any(str::is_empty) {
119 return Err(format!("{spec}: forgejo: wants host/owner/repo"));
120 }
121 format!("https://{rest}.git")
122 } else if body.contains("://") || body.contains('@') || looks_like_path(body) {
123 body.to_string()
124 } else {
125 return Err(format!(
126 "{spec}: not a git URL — use github:owner/repo, \
127 forgejo:host/owner/repo, or a full URL"
128 ));
129 };
130 Ok(Source {
131 label: body.to_string(),
132 url,
133 rev,
134 })
135}
136
137pub fn resolve(source: &Source) -> Result<String, String> {
139 let rev = source.rev.as_deref().unwrap_or("HEAD");
140 let out = crate::git::stdout(&["ls-remote", &source.url, rev]).ok_or_else(|| {
141 format!(
142 "{}: cannot reach the remote, or {rev} names nothing",
143 source.label
144 )
145 })?;
146 let refs = named_refs(&out);
155 let mut ids: Vec<&str> = refs.iter().map(|(id, _)| id.as_str()).collect();
156 ids.sort_unstable();
157 ids.dedup();
158 match ids.as_slice() {
159 [] => Err(format!(
160 "{}: {rev} names nothing on that remote",
161 source.label
162 )),
163 [one] => Ok((*one).to_string()),
164 _ => {
165 let listed = refs
166 .iter()
167 .map(|(id, name)| format!("{name} @ {}", &id[..7.min(id.len())]))
168 .collect::<Vec<_>>()
169 .join(", ");
170 Err(format!(
171 "{}: {rev} is ambiguous — it names {} different commits on \
172 that remote ({listed}); name a commit id instead",
173 source.label,
174 ids.len()
175 ))
176 }
177 }
178}
179
180fn named_refs(out: &str) -> Vec<(String, String)> {
190 out.lines()
191 .filter_map(|l| {
192 let mut it = l.split_whitespace();
193 let id = it.next()?;
194 let name = it.next().unwrap_or("");
195 (!name.ends_with("^{}")).then(|| (id.to_string(), name.to_string()))
196 })
197 .collect()
198}
199
200pub fn fetch(source: &Source, id: &str, into: &Path) -> Result<String, String> {
208 let dir = into.to_string_lossy().into_owned();
209 let ok = |args: &[&str]| crate::git::succeeds_in(into, args);
210 std::fs::create_dir_all(into).map_err(|e| format!("cannot create {dir}: {e}"))?;
211 if !ok(&["init", "-q"]) {
212 return Err(format!("cannot init a scratch repository at {dir}"));
213 }
214 let rev = source.rev.as_deref().unwrap_or("HEAD");
215 if !ok(&["fetch", "-q", "--depth", "1", &source.url, rev]) {
216 return Err(format!("{}: fetching {rev} failed", source.label));
217 }
218 let got = crate::git::stdout_in(into, &["rev-parse", "FETCH_HEAD"])
219 .ok_or_else(|| format!("{}: nothing was fetched", source.label))?;
220 if got != id {
221 return Err(format!(
222 "{}: {rev} moved while we were reading it ({id} → {got}) — \
223 nothing was written; run the same command again",
224 source.label
225 ));
226 }
227 [PACK_FILE, crate::names::old::PACK_FILE]
228 .iter()
229 .find_map(|file| crate::git::stdout_in(into, &["show", &format!("FETCH_HEAD:{file}")]))
230 .ok_or_else(|| {
231 format!(
232 "{}: has no {PACK_FILE} (or {}) at {}",
233 source.label,
234 crate::names::old::PACK_FILE,
235 &id[..7.min(id.len())]
236 )
237 })
238}
239
240pub fn rows(text: &str) -> Result<Vec<String>, String> {
252 let source_rows: Vec<&str> = text
255 .lines()
256 .map(str::trim)
257 .filter(|l| !l.is_empty() && !l.starts_with('#'))
258 .collect();
259 let parsed = crate::manifest::parse_lines(text);
260 if parsed.len() != source_rows.len() {
261 return Err(format!("{PACK_FILE}: cannot be read as {MANIFEST} syntax"));
262 }
263 if source_rows.is_empty() {
264 return Err(format!("{PACK_FILE}: declares no checks"));
265 }
266 let mut out = Vec::with_capacity(source_rows.len());
267 for (line, parsed) in source_rows.iter().zip(&parsed) {
268 match parsed {
269 Line::Usable(_) => out.push((*line).to_string()),
270 Line::Broken { why, .. } => {
271 return Err(format!("{PACK_FILE}: `{line}` — {why}"));
272 }
273 Line::Tool(_) | Line::Policy { .. } | Line::Tree(_) => {
279 return Err(format!(
280 "{PACK_FILE}: `{line}` — a pack may declare checks only, \
281 not tool pins, policy or tree gates"
282 ));
283 }
284 }
285 }
286 Ok(out)
287}
288
289fn start_marker(label: &str) -> String {
297 format!("{} {label}", crate::names::PACK_START)
298}
299fn end_marker(label: &str) -> String {
300 format!("{} {label}", crate::names::PACK_END)
301}
302fn old_start_marker(label: &str) -> String {
304 format!("{} {label}", crate::names::old::PACK_START)
305}
306fn old_end_marker(label: &str) -> String {
307 format!("{} {label}", crate::names::old::PACK_END)
308}
309
310pub fn block(label: &str, id: &str, rows: &[String]) -> String {
311 let mut out = format!("{} {id}\n", start_marker(label));
312 for r in rows {
313 out.push_str(r);
314 out.push('\n');
315 }
316 out.push_str(&end_marker(label));
317 out.push('\n');
318 out
319}
320
321#[derive(Debug, PartialEq, Eq)]
323enum Span {
324 Absent,
326 Found { start: usize, end: usize },
328 Unpaired { marker: String, line: usize },
331}
332
333fn line_of(text: &str, at: usize) -> usize {
334 text[..at].matches('\n').count() + 1
335}
336
337fn block_range(manifest: &str, start: &str, end: &str) -> Span {
338 match (manifest.find(start), manifest.find(end)) {
339 (Some(s), Some(e)) if e > s => {
340 let mut tail = e + end.len();
341 if manifest[tail..].starts_with('\n') {
342 tail += 1;
343 }
344 Span::Found {
345 start: s,
346 end: tail,
347 }
348 }
349 (None, None) => Span::Absent,
350 (Some(s), None) => Span::Unpaired {
351 marker: start.to_string(),
352 line: line_of(manifest, s),
353 },
354 (_, Some(e)) => Span::Unpaired {
356 marker: end.to_string(),
357 line: line_of(manifest, e),
358 },
359 }
360}
361
362pub fn splice(
373 manifest: &str,
374 label: &str,
375 id: &str,
376 rows: &[String],
377) -> Result<(String, Option<String>), String> {
378 use crate::names::{old, PACK_STEM};
379 let new = block_range(manifest, &start_marker(label), &end_marker(label));
380 let old_span = block_range(manifest, &old_start_marker(label), &old_end_marker(label));
381 let lone: Vec<String> = [&new, &old_span]
382 .into_iter()
383 .filter_map(|s| match s {
384 Span::Unpaired { marker, line } => Some(format!("`{marker}` at line {line}")),
385 Span::Absent | Span::Found { .. } => None,
386 })
387 .collect();
388 if !lone.is_empty() {
389 let (verb, what) = if lone.len() == 1 {
390 ("has", "that line")
391 } else {
392 ("have", "those lines")
393 };
394 return Err(format!(
395 "{MANIFEST}: {} {verb} no partner; delete {what}, then run `{} add {label}` again",
396 lone.join(" and "),
397 crate::names::BIN
398 ));
399 }
400 let fresh = block(label, id, rows);
401 match (new, old_span) {
402 (Span::Found { start: s, end: e }, Span::Found { start: os, end: oe }) => {
403 if s < oe && os < e {
404 return Err(format!(
405 "{MANIFEST}: the `{PACK_STEM}` and `{}` blocks for {label} overlap; \
406 separate them by hand, then run `{} add {label}` again",
407 old::PACK_STEM,
408 crate::names::BIN
409 ));
410 }
411 let mut out = manifest.to_string();
413 let mut cuts = [(s, e, fresh.as_str()), (os, oe, "")];
414 cuts.sort_by_key(|c| std::cmp::Reverse(c.0));
415 for (from, to, with) in cuts {
416 out.replace_range(from..to, with);
417 }
418 Ok((
419 out,
420 Some(format!(
421 "{MANIFEST}: has both `{PACK_STEM}` and `{}` blocks for \
422 {label} — the `{}` one was removed",
423 old::PACK_STEM,
424 old::PACK_STEM
425 )),
426 ))
427 }
428 (Span::Found { start: s, end: e }, Span::Absent)
429 | (Span::Absent, Span::Found { start: s, end: e }) => {
430 Ok((format!("{}{fresh}{}", &manifest[..s], &manifest[e..]), None))
431 }
432 (Span::Unpaired { .. }, _) | (_, Span::Unpaired { .. }) => {
433 unreachable!("a lone marker returned the unpaired error above")
434 }
435 (Span::Absent, Span::Absent) => {
436 let mut out = manifest.to_string();
437 if !out.is_empty() && !out.ends_with('\n') {
438 out.push('\n');
439 }
440 if !out.is_empty() {
441 out.push('\n');
442 }
443 out.push_str(&fresh);
444 Ok((out, None))
445 }
446 }
447}
448
449#[cfg(test)]
450mod tests {
451 use super::*;
452
453 #[test]
457 fn a_peeled_tag_line_is_not_a_second_ref() {
458 let out = "fdfa39b\trefs/tags/v1\n2127b95\trefs/tags/v1^{}\n";
459 let refs = named_refs(out);
460 assert_eq!(refs.len(), 1, "{refs:?}");
461 assert_eq!(
462 refs[0].0, "fdfa39b",
463 "the TAG object, which is what FETCH_HEAD records"
464 );
465 }
466
467 #[test]
468 fn shorthands_and_urls_become_git_urls() {
469 let s = parse_source("github:acme/rust-strict").unwrap();
470 assert_eq!(s.url, "https://github.com/acme/rust-strict.git");
471 assert_eq!(s.label, "github:acme/rust-strict");
472 assert_eq!(s.rev, None);
473
474 let s = parse_source("forgejo:git.example.org/acme/packs@v2").unwrap();
475 assert_eq!(s.url, "https://git.example.org/acme/packs.git");
476 assert_eq!(s.rev.as_deref(), Some("v2"));
477 }
478
479 #[test]
483 fn an_ssh_url_keeps_its_userinfo() {
484 let s = parse_source("git@github.com:acme/repo.git").unwrap();
485 assert_eq!(s.url, "git@github.com:acme/repo.git");
486 assert_eq!(s.rev, None);
487
488 let s = parse_source("git@github.com:acme/repo.git@v1").unwrap();
489 assert_eq!(s.url, "git@github.com:acme/repo.git");
490 assert_eq!(s.rev.as_deref(), Some("v1"));
491 }
492
493 #[test]
503 fn an_absolute_path_is_a_source_on_any_platform() {
504 for p in ["/tmp/pack", r"C:\Users\me\pack", r"\\server\share\pack"] {
505 let s = parse_source(p).unwrap_or_else(|e| panic!("{p:?} should be a source: {e}"));
506 assert_eq!(s.url, p);
507 assert_eq!(s.rev, None, "{p:?} has no revision");
508 }
509 }
510
511 #[test]
514 fn a_windows_path_with_an_at_sign_is_not_split_on_it() {
515 let s = parse_source(r"C:\Users\me\a@b\pack").unwrap();
516 assert_eq!(s.url, r"C:\Users\me\a@b\pack");
517 assert_eq!(s.rev, None);
518 let s = parse_source(r"C:\Users\me\a@b\pack@v1").unwrap();
519 assert_eq!(s.url, r"C:\Users\me\a@b\pack");
520 assert_eq!(s.rev.as_deref(), Some("v1"));
521 }
522
523 #[test]
524 fn a_source_that_is_not_a_url_is_refused() {
525 for bad in ["", "acme/rust-strict", "github:acme", "github:acme/repo/x"] {
526 assert!(parse_source(bad).is_err(), "{bad:?} should be refused");
527 }
528 assert!(parse_source("github:acme/repo@").is_err(), "empty revision");
529 }
530
531 #[test]
532 fn rows_are_taken_verbatim() {
533 let text = "# a comment\n\npre-commit terraform-fmt Dockerfile block terraform-fmt\n";
534 assert_eq!(
535 rows(text).unwrap(),
536 vec!["pre-commit terraform-fmt Dockerfile block terraform-fmt"]
537 );
538 }
539
540 #[test]
549 fn a_pack_may_not_carry_valid_policy_or_pins() {
550 for bad in [
551 "set largeFileBlock 4000\n",
552 "severity secrets warn\n",
553 "skip secrets\n",
554 "tool terraform-fmt 2.12\n",
555 ] {
556 let text = format!("pre-commit ok * block true\n{bad}");
557 let err = rows(&text).unwrap_err();
558 assert!(err.contains("checks only"), "{bad:?} gave: {err}");
559 }
560 }
561
562 #[test]
565 fn a_policy_line_the_parser_rejects_is_still_refused() {
566 let text = "pre-commit ok * block true\nset greengate.fix true\n";
567 let err = rows(text).unwrap_err();
568 assert!(err.contains("not a policy-settable key"), "{err}");
569 }
570
571 #[test]
572 fn a_pack_is_refused_whole_on_one_bad_row() {
573 let text = "pre-commit fine * block true\nnonsense\n";
574 assert!(rows(text).is_err());
575 assert!(rows("# nothing but a comment\n").is_err(), "empty pack");
576 }
577
578 #[test]
579 fn splice_appends_then_replaces_in_place() {
580 let rows0 = vec!["pre-commit a * block true".to_string()];
581 let base = "pre-commit mine * block true\n";
582
583 let once = splice(base, "github:acme/p", "abc1234", &rows0).unwrap().0;
584 assert!(once.starts_with(base), "existing lines are kept: {once:?}");
585 assert!(once.contains("# greengate:pack:start github:acme/p abc1234"));
586
587 let rows1 = vec!["pre-commit b * block true".to_string()];
590 let twice = splice(&once, "github:acme/p", "def5678", &rows1).unwrap().0;
591 assert_eq!(
592 twice.matches("greengate:pack:start github:acme/p").count(),
593 1
594 );
595 assert!(twice.contains("def5678"));
596 assert!(!twice.contains("abc1234"));
597 assert!(!twice.contains("pre-commit a *"), "old rows are gone");
598 assert!(
599 twice.contains("pre-commit mine"),
600 "unrelated lines survive"
601 );
602 }
603
604 #[test]
605 fn an_unpaired_marker_is_reported_not_guessed() {
606 let rows0 = vec!["pre-commit a * block true".to_string()];
607 let half = "# greengate:pack:start github:acme/p abc1234\n";
608 assert!(splice(half, "github:acme/p", "x", &rows0).is_err());
609 let old_half = "# amont:pack:start github:acme/p abc1234\n";
610 assert!(splice(old_half, "github:acme/p", "x", &rows0).is_err());
611 let inverted =
612 "# greengate:pack:end github:acme/p\n# greengate:pack:start github:acme/p x\n";
613 assert!(splice(inverted, "github:acme/p", "y", &rows0).is_err());
614 }
615
616 #[test]
618 fn mixed_start_and_end_spellings_are_unpaired() {
619 let rows0 = vec!["pre-commit a * block true".to_string()];
620 let mixed = "# greengate:pack:start github:acme/p x\n# amont:pack:end github:acme/p\n";
621 let err = splice(mixed, "github:acme/p", "y", &rows0).unwrap_err();
622 assert!(
623 err.contains("greengate:pack") && err.contains("amont:pack"),
624 "{err}"
625 );
626 }
627
628 #[test]
632 fn an_old_marker_block_is_replaced_in_place_under_new_markers() {
633 let rows0 = vec!["pre-commit b * block true".to_string()];
634 let old = "pre-commit mine * block true\n\n# amont:pack:start github:acme/p abc1234\n\
635 pre-commit a * block true\n# amont:pack:end github:acme/p\n\
636 pre-commit after * block true\n";
637 let (out, warning) = splice(old, "github:acme/p", "def5678", &rows0).unwrap();
638 assert_eq!(warning, None);
639 assert!(!out.contains("amont:pack"), "{out}");
640 assert_eq!(out.matches("greengate:pack:start").count(), 1, "{out}");
641 assert!(!out.contains("pre-commit a *"), "old row replaced: {out}");
642 let at = |n: &str| out.find(n).unwrap();
643 assert!(
644 at("mine") < at("def5678") && at("def5678") < at("after"),
645 "in place: {out}"
646 );
647 }
648
649 #[test]
652 fn both_spellings_of_one_label_leave_one_block_and_a_warning() {
653 let rows0 = vec!["pre-commit b * block true".to_string()];
654 for order in 0..2 {
655 let oldb = "# amont:pack:start github:acme/p 1111111\n\
656 pre-commit a * block true\n# amont:pack:end github:acme/p\n";
657 let newb = "# greengate:pack:start github:acme/p 2222222\n\
658 pre-commit c * block true\n# greengate:pack:end github:acme/p\n";
659 let both = if order == 0 {
660 format!("{oldb}\n{newb}")
661 } else {
662 format!("{newb}\n{oldb}")
663 };
664 let (out, warning) = splice(&both, "github:acme/p", "3333333", &rows0).unwrap();
665 assert!(
666 warning.is_some_and(|w| w.contains("amont:pack")),
667 "order {order}"
668 );
669 assert!(!out.contains("amont:pack"), "{out}");
670 assert_eq!(out.matches("greengate:pack:start").count(), 1, "{out}");
671 assert_eq!(out.matches("greengate:pack:end").count(), 1, "{out}");
672 assert!(
673 out.contains("3333333") && !out.contains("1111111") && !out.contains("2222222")
674 );
675 let parsed = crate::manifest::parse_lines(&out);
676 assert_eq!(parsed.len(), 1, "{out}");
677 assert!(matches!(parsed[0], Line::Usable(_)), "{out}");
678 }
679 }
680
681 #[test]
684 fn overlapping_old_and_new_blocks_are_refused() {
685 let rows0 = vec!["pre-commit b * block true".to_string()];
686 let nested = "# greengate:pack:start github:acme/p 1\n\
687 # amont:pack:start github:acme/p 2\n\
688 pre-commit a * block true\n\
689 # amont:pack:end github:acme/p\n\
690 # greengate:pack:end github:acme/p\n";
691 let err = splice(nested, "github:acme/p", "3", &rows0).unwrap_err();
692 assert!(err.contains("overlap"), "{err}");
693 assert!(err.contains("greengate add github:acme/p"), "{err}");
694 }
695
696 #[test]
698 fn the_unpaired_error_names_the_marker_line_and_fix() {
699 let rows0 = vec!["pre-commit a * block true".to_string()];
700 let text = "pre-commit mine * block true\n# amont:pack:start github:acme/p 1\n";
701 let err = splice(text, "github:acme/p", "2", &rows0).unwrap_err();
702 assert!(
703 err.contains("`# amont:pack:start github:acme/p` at line 2 has no partner"),
704 "{err}"
705 );
706 assert!(
707 err.contains("delete that line, then run `greengate add github:acme/p` again"),
708 "{err}"
709 );
710 }
711
712 #[test]
714 fn packs_from_different_sources_do_not_collide() {
715 let a = vec!["pre-commit a * block true".to_string()];
716 let b = vec!["pre-commit b * block true".to_string()];
717 let one = splice("", "github:x/a", "1111111", &a).unwrap().0;
718 let two = splice(&one, "github:x/b", "2222222", &b).unwrap().0;
719 let three = splice(&two, "github:x/a", "3333333", &a).unwrap().0;
720 assert!(three.contains("2222222"), "the other pack is untouched");
721 assert!(three.contains("3333333"));
722 assert!(!three.contains("1111111"));
723 }
724}