1pub mod check;
16mod parse;
17#[cfg(test)]
18mod tests;
19
20use std::collections::HashMap;
21use std::path::{Path, PathBuf};
22use std::sync::{Arc, Mutex};
23
24pub use check::{OtherFiles, Violation, evaluate_change, evaluate_change_with};
25pub use parse::{NewRecord, id_from_slug, parse_decision, render_record, scaffold};
26
27pub const DECISIONS_DIR: &str = ".leanctx/decisions";
29pub const SUFFIX_HEADER: &str = "--- Decisions in scope ---";
31const MAX_SUFFIX_DECISIONS: usize = 8;
33const MAX_SUFFIX_LINE_CHARS: usize = 200;
35const MAX_DECISION_FILES: usize = 512;
37pub const MAX_DECISION_BYTES: u64 = 64 * 1024;
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
41pub enum Status {
42 Active,
43 Superseded,
44 Revoked,
45}
46
47impl Status {
48 pub fn as_str(self) -> &'static str {
49 match self {
50 Self::Active => "active",
51 Self::Superseded => "superseded",
52 Self::Revoked => "revoked",
53 }
54 }
55}
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum CheckKind {
59 ForbidPath,
60 ForbidRegex,
61 RequireRegex,
62}
63
64impl CheckKind {
65 pub fn as_str(self) -> &'static str {
66 match self {
67 Self::ForbidPath => "forbid_path",
68 Self::ForbidRegex => "forbid_regex",
69 Self::RequireRegex => "require_regex",
70 }
71 }
72}
73
74#[derive(Debug, Clone)]
76pub struct Check {
77 pub kind: CheckKind,
78 pub paths: Vec<String>,
79 globs: Vec<glob::Pattern>,
80 pub pattern: Option<String>,
81 regex: Option<regex::Regex>,
82 pub message: Option<String>,
83}
84
85#[derive(Debug, Clone)]
87pub struct Decision {
88 pub id: String,
89 pub title: String,
90 pub statement: String,
91 pub rationale: String,
92 pub status: Status,
93 pub supersedes: Vec<String>,
94 pub decided_by: String,
95 pub decided_at: String,
96 pub source_kind: Option<String>,
97 pub source_ref: Option<String>,
98 pub repos: Vec<String>,
99 pub paths: Vec<String>,
100 path_globs: Vec<glob::Pattern>,
101 pub symbols: Vec<String>,
102 pub checks: Vec<Check>,
103 pub evidence: Option<RecordEvidence>,
105 pub file: String,
107}
108
109#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct RecordEvidence {
115 pub commit: String,
117 pub quote: String,
119 pub trust: String,
121}
122
123#[derive(Debug, Clone, Default)]
125pub struct DecisionSet {
126 pub decisions: Vec<Decision>,
127 pub errors: Vec<String>,
129 repo_names: Vec<String>,
131 root: Option<PathBuf>,
133}
134
135fn match_options() -> glob::MatchOptions {
136 glob::MatchOptions {
137 case_sensitive: true,
138 require_literal_separator: true,
139 require_literal_leading_dot: false,
140 }
141}
142
143impl Check {
144 pub fn covers(&self, decision: &Decision, rel_path: &str) -> bool {
146 if self.globs.is_empty() {
147 decision.covers_path(rel_path)
148 } else {
149 let opts = match_options();
150 self.globs.iter().any(|g| g.matches_with(rel_path, opts))
151 }
152 }
153
154 pub fn regex(&self) -> Option<®ex::Regex> {
155 self.regex.as_ref()
156 }
157}
158
159impl Decision {
160 pub fn is_repo_wide(&self) -> bool {
162 self.paths.is_empty() && self.symbols.is_empty()
163 }
164
165 pub fn covers_path(&self, rel_path: &str) -> bool {
168 if self.is_repo_wide() {
169 return true;
170 }
171 let opts = match_options();
172 self.path_globs
173 .iter()
174 .any(|g| g.matches_with(rel_path, opts))
175 }
176
177 pub fn covers_symbol(&self, symbol: &str) -> bool {
179 self.symbols.iter().any(|s| symbol_matches(s, symbol))
180 }
181
182 pub fn one_line(&self) -> String {
184 let line = self
185 .statement
186 .lines()
187 .map(str::trim)
188 .find(|l| !l.is_empty())
189 .unwrap_or_default();
190 truncate_chars(line, MAX_SUFFIX_LINE_CHARS)
191 }
192}
193
194fn symbol_matches(a: &str, b: &str) -> bool {
197 let (a, b) = (a.trim(), b.trim());
198 if a.is_empty() || b.is_empty() {
199 return false;
200 }
201 if a == b {
202 return true;
203 }
204 let last = |s: &str| s.rsplit("::").next().unwrap_or(s).to_string();
205 (!a.contains("::") || !b.contains("::")) && last(a) == last(b)
206}
207
208fn truncate_chars(s: &str, max: usize) -> String {
209 if s.chars().count() <= max {
210 return s.to_string();
211 }
212 let cut: String = s.chars().take(max.saturating_sub(1)).collect();
213 format!("{cut}…")
214}
215
216impl DecisionSet {
217 pub fn active(&self) -> impl Iterator<Item = &Decision> {
220 let superseded: Vec<&str> = self
221 .decisions
222 .iter()
223 .filter(|d| d.status == Status::Active)
224 .flat_map(|d| d.supersedes.iter().map(String::as_str))
225 .collect();
226 self.decisions
227 .iter()
228 .filter(move |d| d.status == Status::Active && !superseded.contains(&d.id.as_str()))
229 }
230
231 pub fn effective_status(&self, d: &Decision) -> Status {
234 if d.status == Status::Active && self.active().all(|a| a.id != d.id) {
235 Status::Superseded
236 } else {
237 d.status
238 }
239 }
240
241 pub fn get(&self, id: &str) -> Option<&Decision> {
242 self.decisions.iter().find(|d| d.id == id)
243 }
244
245 pub fn repo_matches(&self, d: &Decision) -> bool {
247 d.repos.is_empty()
248 || d.repos
249 .iter()
250 .any(|r| self.repo_names.iter().any(|n| n == &r.to_lowercase()))
251 }
252
253 pub fn for_path(&self, rel_path: &str) -> Vec<&Decision> {
255 self.active()
256 .filter(|d| self.repo_matches(d) && d.covers_path(rel_path))
257 .collect()
258 }
259
260 pub fn for_symbol(&self, symbol: &str) -> Vec<&Decision> {
262 self.active()
263 .filter(|d| self.repo_matches(d) && d.covers_symbol(symbol))
264 .collect()
265 }
266
267 pub fn is_empty(&self) -> bool {
268 self.decisions.is_empty() && self.errors.is_empty()
269 }
270}
271
272type Signature = Vec<(String, u64, u128)>;
275
276static CACHE: Mutex<Option<HashMap<PathBuf, (Signature, Arc<DecisionSet>)>>> = Mutex::new(None);
277
278pub(crate) const MAX_CACHED_ROOTS: usize = 16;
281
282#[derive(Debug, Clone, PartialEq, Eq)]
284pub struct RecordEntry {
285 pub path: PathBuf,
287 pub rel: String,
289 pub regular: bool,
292}
293
294pub fn list_records(root: &Path) -> Result<Option<Vec<RecordEntry>>, String> {
302 let dir = root.join(DECISIONS_DIR);
303 let meta = match std::fs::symlink_metadata(&dir) {
304 Ok(m) => m,
305 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
306 Err(e) => return Err(format!("{DECISIONS_DIR}: {e}")),
307 };
308 if !meta.is_dir() {
309 return Err(format!(
310 "{DECISIONS_DIR} is not a directory inside the project"
311 ));
312 }
313 let real_root =
315 std::fs::canonicalize(root).map_err(|e| format!("project root {}: {e}", root.display()))?;
316 let real = std::fs::canonicalize(&dir).map_err(|e| format!("{DECISIONS_DIR}: {e}"))?;
317 let expected = DECISIONS_DIR
319 .split('/')
320 .fold(real_root, |p, part| p.join(part));
321 if real != expected {
322 return Err(format!("{DECISIONS_DIR} leads outside the project"));
323 }
324 let mut entries: Vec<RecordEntry> = std::fs::read_dir(&dir)
325 .map_err(|e| format!("{DECISIONS_DIR}: {e}"))?
326 .filter_map(Result::ok)
327 .filter(|e| {
328 Path::new(&e.file_name())
329 .extension()
330 .is_some_and(|x| x == "toml")
331 })
332 .map(|e| {
333 let name = e.file_name().to_string_lossy().into_owned();
334 let regular = e.file_type().is_ok_and(|t| t.is_file());
336 RecordEntry {
337 path: dir.join(e.file_name()),
338 rel: format!("{DECISIONS_DIR}/{name}"),
339 regular,
340 }
341 })
342 .collect();
343 entries.sort_by(|a, b| a.path.cmp(&b.path));
344 Ok(Some(entries))
345}
346
347pub fn read_record(file: &Path) -> Result<String, &'static str> {
351 use std::io::Read;
352 let mut options = std::fs::OpenOptions::new();
353 options.read(true);
354 #[cfg(unix)]
355 {
356 use std::os::unix::fs::OpenOptionsExt;
357 options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC);
358 }
359 #[cfg(not(unix))]
360 {
361 if std::fs::symlink_metadata(file).is_ok_and(|m| !m.file_type().is_file()) {
362 return Err("not a regular file");
363 }
364 }
365 let handle = options.open(file).map_err(|e| {
366 #[cfg(unix)]
367 {
368 if e.raw_os_error() == Some(libc::ELOOP) {
369 return "not a regular file";
370 }
371 }
372 let _ = e;
373 "unreadable"
374 })?;
375 let meta = handle.metadata().map_err(|_| "unreadable")?;
376 if !meta.is_file() {
377 return Err("not a regular file");
378 }
379 if meta.len() > MAX_DECISION_BYTES {
380 return Err("larger than 64 KiB");
381 }
382 let mut bytes = Vec::new();
383 handle
384 .take(MAX_DECISION_BYTES + 1)
385 .read_to_end(&mut bytes)
386 .map_err(|_| "unreadable")?;
387 if bytes.len() as u64 > MAX_DECISION_BYTES {
388 return Err("larger than 64 KiB");
389 }
390 String::from_utf8(bytes).map_err(|_| "not UTF-8 text")
391}
392
393fn signature(entries: &[RecordEntry]) -> Signature {
394 entries
395 .iter()
396 .map(|e| {
397 let p = &e.path;
398 let meta = std::fs::symlink_metadata(p).ok();
399 let len = meta.as_ref().map_or(0, std::fs::Metadata::len);
400 let mtime = meta
401 .and_then(|m| m.modified().ok())
402 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
403 .map_or(0, |d| d.as_nanos());
404 (p.to_string_lossy().into_owned(), len, mtime)
405 })
406 .collect()
407}
408
409pub fn load(root: &Path) -> Arc<DecisionSet> {
414 let files = match list_records(root) {
415 Ok(Some(entries)) if !entries.is_empty() => entries,
416 Ok(_) => return Arc::new(DecisionSet::default()),
417 Err(e) => {
418 return Arc::new(from_records(
419 root,
420 vec![(DECISIONS_DIR.to_string(), Err(e))],
421 ));
422 }
423 };
424 let sig = signature(&files);
425 {
426 let guard = CACHE
427 .lock()
428 .unwrap_or_else(std::sync::PoisonError::into_inner);
429 if let Some((cached_sig, set)) = guard.as_ref().and_then(|c| c.get(root))
430 && *cached_sig == sig
431 {
432 return Arc::clone(set);
433 }
434 }
435 let set = Arc::new(load_uncached(root, &files));
436 let mut guard = CACHE
437 .lock()
438 .unwrap_or_else(std::sync::PoisonError::into_inner);
439 let cache = guard.get_or_insert_with(HashMap::new);
440 if !cache.contains_key(root) && cache.len() >= MAX_CACHED_ROOTS {
441 cache.clear();
442 }
443 cache.insert(root.to_path_buf(), (sig, Arc::clone(&set)));
444 set
445}
446
447#[cfg(test)]
448pub(crate) fn cached_roots() -> usize {
449 CACHE
450 .lock()
451 .unwrap_or_else(std::sync::PoisonError::into_inner)
452 .as_ref()
453 .map_or(0, HashMap::len)
454}
455
456fn load_uncached(root: &Path, files: &[RecordEntry]) -> DecisionSet {
457 let records: Vec<(String, Result<String, String>)> = files
458 .iter()
459 .take(MAX_DECISION_FILES + 1)
460 .map(|entry| {
461 let text = if entry.regular {
462 read_record(&entry.path).map_err(str::to_string)
463 } else {
464 Err("not a regular file (symlinks are not followed)".to_string())
465 };
466 (entry.rel.clone(), text)
467 })
468 .collect();
469 let mut set = from_records(root, records);
470 set.root = Some(root.to_path_buf());
471 set
472}
473
474pub fn from_records(
479 repo_root: &Path,
480 records: Vec<(String, Result<String, String>)>,
481) -> DecisionSet {
482 let mut set = DecisionSet {
483 repo_names: repo_names(repo_root),
484 ..DecisionSet::default()
485 };
486 if records.len() > MAX_DECISION_FILES {
487 set.errors.push(format!(
488 "{DECISIONS_DIR}: more than the limit of {MAX_DECISION_FILES} record files; none loaded"
489 ));
490 return set;
491 }
492 for (rel, text) in records {
493 let stem = Path::new(&rel)
494 .file_stem()
495 .map(|s| s.to_string_lossy().into_owned())
496 .unwrap_or_default();
497 let text = match text {
498 Ok(t) if t.len() as u64 > MAX_DECISION_BYTES => {
499 set.errors.push(format!(
500 "{rel}: {} bytes, more than the limit of {MAX_DECISION_BYTES}",
501 t.len()
502 ));
503 continue;
504 }
505 Ok(t) => t,
506 Err(e) => {
507 set.errors.push(format!("{rel}: {e}"));
508 continue;
509 }
510 };
511 match parse_decision(&text, &stem, &rel) {
512 Ok(d) if set.decisions.iter().any(|o| o.id == d.id) => {
513 set.errors.push(format!("{rel}: duplicate id `{}`", d.id));
514 }
515 Ok(d) => set.decisions.push(d),
516 Err(e) => set.errors.push(format!("{rel}: {e}")),
517 }
518 }
519 set.decisions.sort_by(|a, b| a.id.cmp(&b.id));
520 set.errors.sort();
521 set
522}
523
524fn repo_names(root: &Path) -> Vec<String> {
527 let mut names = Vec::new();
528 if let Some(name) = root.file_name() {
529 names.push(name.to_string_lossy().to_lowercase());
530 }
531 if let Some(url) = origin_url(root) {
532 let base = url
533 .trim_end_matches('/')
534 .rsplit(['/', ':'])
535 .next()
536 .unwrap_or_default()
537 .trim_end_matches(".git")
538 .to_lowercase();
539 if !base.is_empty() && !names.contains(&base) {
540 names.push(base);
541 }
542 }
543 names
544}
545
546fn git_common_dir(root: &Path) -> Option<PathBuf> {
547 let dot_git = root.join(".git");
548 if dot_git.is_dir() {
549 return Some(dot_git);
550 }
551 let text = std::fs::read_to_string(&dot_git).ok()?;
552 let gitdir = PathBuf::from(text.trim().strip_prefix("gitdir:")?.trim());
553 let gitdir = if gitdir.is_absolute() {
554 gitdir
555 } else {
556 root.join(gitdir)
557 };
558 match std::fs::read_to_string(gitdir.join("commondir")) {
559 Ok(common) => {
560 let common = PathBuf::from(common.trim());
561 Some(if common.is_absolute() {
562 common
563 } else {
564 gitdir.join(common)
565 })
566 }
567 Err(_) => Some(gitdir),
568 }
569}
570
571fn origin_url(root: &Path) -> Option<String> {
572 let config = std::fs::read_to_string(git_common_dir(root)?.join("config")).ok()?;
573 let mut in_origin = false;
574 for line in config.lines() {
575 let line = line.trim();
576 if line.starts_with('[') {
577 in_origin = line == "[remote \"origin\"]";
578 } else if in_origin
579 && let Some((key, value)) = line.split_once('=')
580 && key.trim() == "url"
581 {
582 return Some(value.trim().to_string());
583 }
584 }
585 None
586}
587
588pub fn find_root(path: &Path) -> Option<PathBuf> {
591 let start = if path.is_dir() { path } else { path.parent()? };
592 for dir in start.ancestors() {
593 if dir.join(DECISIONS_DIR).is_dir() {
594 return Some(dir.to_path_buf());
595 }
596 if dir.join(".git").exists() {
597 return None;
598 }
599 }
600 None
601}
602
603pub fn relative_path(root: &Path, path: &Path) -> Option<String> {
605 let abs = if path.is_absolute() {
606 path.to_path_buf()
607 } else {
608 root.join(path)
609 };
610 let rel: PathBuf = if let Ok(rel) = abs.strip_prefix(root) {
611 rel.to_path_buf()
612 } else {
613 let canon_root = root.canonicalize().ok()?;
616 let canon = abs.canonicalize().ok().or_else(|| {
617 let parent = abs.parent()?.canonicalize().ok()?;
618 Some(parent.join(abs.file_name()?))
619 })?;
620 canon.strip_prefix(&canon_root).ok()?.to_path_buf()
621 };
622 let s = rel.to_string_lossy().replace('\\', "/");
623 (!s.is_empty()).then_some(s)
624}
625
626pub fn render_lines(decisions: &[&Decision]) -> String {
630 let mut out = String::new();
631 for d in decisions.iter().take(MAX_SUFFIX_DECISIONS) {
632 let line = format!("{}: {} — {}", d.id, d.title.trim(), d.one_line());
633 out.push_str(&truncate_chars(&line, MAX_SUFFIX_LINE_CHARS * 2));
634 out.push('\n');
635 }
636 if decisions.len() > MAX_SUFFIX_DECISIONS {
637 out.push_str(&format!(
638 "(+{} more: lean-ctx decisions list)\n",
639 decisions.len() - MAX_SUFFIX_DECISIONS
640 ));
641 }
642 out
643}
644
645pub fn suffix_for_paths(set: &DecisionSet, rel_paths: &[&str]) -> String {
648 let mut hits: Vec<&Decision> = Vec::new();
649 for p in rel_paths {
650 for d in set.for_path(p) {
651 if !hits.iter().any(|h| h.id == d.id) {
652 hits.push(d);
653 }
654 }
655 }
656 if hits.is_empty() {
657 return String::new();
658 }
659 hits.sort_by(|a, b| a.id.cmp(&b.id));
660 format!("\n\n{SUFFIX_HEADER}\n{}", render_lines(&hits))
661 .trim_end()
662 .to_string()
663}
664
665pub fn suffix_for_file(file: &Path) -> String {
668 let Some(root) = find_root(file) else {
669 return String::new();
670 };
671 let Some(rel) = relative_path(&root, file) else {
672 return String::new();
673 };
674 suffix_for_paths(&load(&root), &[rel.as_str()])
675}
676
677pub fn suffix_for_read(file: &str) -> String {
681 if crate::core::policy::runtime::is_active() {
682 return String::new();
683 }
684 suffix_for_file(Path::new(file))
685}
686
687pub fn suffix_for_root_paths(root: &Path, rel_paths: &[&str]) -> String {
689 if !root.join(DECISIONS_DIR).is_dir() || rel_paths.is_empty() {
690 return String::new();
691 }
692 suffix_for_paths(&load(root), rel_paths)
693}
694
695const MAX_COMPOSE_PATHS: usize = 64;
697
698pub fn suffix_for_compose(root: &Path, text: &str) -> String {
701 if crate::core::policy::runtime::is_active() || !root.join(DECISIONS_DIR).is_dir() {
702 return String::new();
703 }
704 let paths = paths_named_in(root, text);
705 suffix_for_root_paths(root, &paths)
706}
707
708pub fn paths_named_in<'a>(root: &Path, text: &'a str) -> Vec<&'a str> {
711 let mut paths: Vec<&str> = Vec::new();
712 for line in text.lines() {
713 let line = line.trim_start();
714 let candidate = match line.strip_prefix("File: ") {
715 Some(rest) => rest.split([' ', '(']).next().unwrap_or_default(),
716 None => match line.split_once(':') {
717 Some((p, rest)) if rest.starts_with(|c: char| c.is_ascii_digit()) => p,
718 _ => continue,
719 },
720 };
721 if candidate.is_empty()
722 || candidate.contains(char::is_whitespace)
723 || paths.contains(&candidate)
724 || !root.join(candidate).is_file()
725 {
726 continue;
727 }
728 paths.push(candidate);
729 if paths.len() >= MAX_COMPOSE_PATHS {
730 break;
731 }
732 }
733 paths
734}
735
736pub fn describe(set: &DecisionSet, d: &Decision) -> String {
738 let mut out = format!(
739 "{} [{}] {}\n statement: {}\n",
740 d.id,
741 set.effective_status(d).as_str(),
742 d.title.trim(),
743 d.statement.trim()
744 );
745 if !d.rationale.trim().is_empty() {
746 out.push_str(&format!(" rationale: {}\n", d.rationale.trim()));
747 }
748 out.push_str(&format!(
749 " decided: {} by {}\n",
750 d.decided_at, d.decided_by
751 ));
752 if let (Some(kind), Some(r)) = (&d.source_kind, &d.source_ref) {
753 out.push_str(&format!(" source: {kind} {r}\n"));
754 }
755 if let Some(ev) = &d.evidence {
756 out.push_str(&format!(
757 " evidence ({}): {} \"{}\"\n",
758 ev.trust,
759 &ev.commit[..ev.commit.len().min(12)],
760 ev.quote
761 ));
762 }
763 if !d.supersedes.is_empty() {
764 out.push_str(&format!(" supersedes: {}\n", d.supersedes.join(", ")));
765 }
766 let scope = |v: &[String]| {
767 if v.is_empty() {
768 "*".to_string()
769 } else {
770 v.join(", ")
771 }
772 };
773 out.push_str(&format!(
774 " scope: repos={} paths={} symbols={}\n",
775 scope(&d.repos),
776 scope(&d.paths),
777 if d.symbols.is_empty() {
778 "-".to_string()
779 } else {
780 d.symbols.join(", ")
781 }
782 ));
783 for (i, c) in d.checks.iter().enumerate() {
784 out.push_str(&format!(
785 " check[{i}]: {} paths={}{}\n",
786 c.kind.as_str(),
787 scope(&c.paths),
788 c.pattern
789 .as_deref()
790 .map(|p| format!(" pattern={p}"))
791 .unwrap_or_default()
792 ));
793 }
794 out.push_str(&format!(" file: {}\n", d.file));
795 out.split('\n')
797 .map(terminal_safe)
798 .collect::<Vec<_>>()
799 .join("\n")
800}
801
802pub fn terminal_safe(s: &str) -> String {
805 s.chars()
806 .map(|c| {
807 if c.is_control()
808 || matches!(
809 c,
810 '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}'
811 )
812 {
813 '?'
814 } else {
815 c
816 }
817 })
818 .collect()
819}
820
821pub fn query_text(project_root: &Path, path: Option<&str>, symbol: Option<&str>) -> String {
825 let root = find_root(project_root).unwrap_or_else(|| project_root.to_path_buf());
826 let set = load(&root);
827 if set.is_empty() {
828 return format!(
829 "No decisions in this project ({DECISIONS_DIR}/*.toml). Create one: lean-ctx decisions new <slug>"
830 );
831 }
832 let (label, hits): (String, Vec<&Decision>) = match (path, symbol) {
833 (Some(p), _) => {
834 let rel = relative_path(&root, Path::new(p))
835 .unwrap_or_else(|| p.trim_start_matches("./").to_string());
836 let hits = set.for_path(&rel);
837 (format!("in scope of {rel}"), hits)
838 }
839 (None, Some(s)) => (format!("naming symbol {s}"), set.for_symbol(s)),
840 (None, None) => ("all".to_string(), set.decisions.iter().collect()),
841 };
842 let mut out = format!("Decisions {label}: {}\n", hits.len());
843 for d in hits {
844 out.push_str(&describe(&set, d));
845 }
846 if !set.errors.is_empty() {
847 out.push_str("Invalid records (not applied):\n");
848 for e in &set.errors {
849 out.push_str(&format!(" {}\n", terminal_safe(e)));
851 }
852 }
853 out.trim_end().to_string()
854}