1use std::ffi::OsStr;
5use std::fmt;
6use std::path::{Path, PathBuf};
7use std::sync::Mutex;
8use std::sync::atomic::{AtomicUsize, Ordering};
9
10use cuno_core::{CunoError, Env, ExitClass};
11use cuno_manifest::{Fmt, FmtStyle, Lang};
12use cuno_toolchain::Runner;
13
14pub struct ClangFormat<'a> {
16 pub program: &'a Path,
18 pub style: &'a Path,
20 pub env: &'a Env,
22 pub jobs: usize,
24}
25
26#[derive(Debug)]
28pub struct FormatError {
29 pub file: PathBuf,
31 pub reason: String,
33}
34
35impl fmt::Display for FormatError {
36 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37 write!(
38 f,
39 "could not format {}: {}",
40 self.file.display(),
41 self.reason
42 )
43 }
44}
45
46impl std::error::Error for FormatError {}
47
48impl CunoError for FormatError {
49 fn exit_class(&self) -> ExitClass {
50 ExitClass::Failure
51 }
52}
53
54#[derive(Debug)]
57pub struct StyleRefused {
58 pub reason: String,
60}
61
62impl fmt::Display for StyleRefused {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 write!(
65 f,
66 "clang-format refuses the configuration from [fmt] in Cuno.toml: {}",
67 self.reason
68 )
69 }
70}
71
72impl std::error::Error for StyleRefused {}
73
74impl CunoError for StyleRefused {
75 fn exit_class(&self) -> ExitClass {
76 ExitClass::Setup
77 }
78
79 fn help(&self) -> Option<String> {
80 Some("correct [fmt.clang-format] in Cuno.toml".to_owned())
81 }
82}
83
84pub fn check_style(tool: &ClangFormat<'_>, runner: &dyn Runner) -> Result<(), StyleRefused> {
88 let style = format!("--style=file:{}", tool.style.display());
89 let args: [&OsStr; 2] = ["--dump-config".as_ref(), style.as_ref()];
90 let output = runner
91 .run(tool.program, &args, tool.env)
92 .map_err(|e| StyleRefused {
93 reason: e.to_string(),
94 })?;
95 if output.success {
96 return Ok(());
97 }
98 let said = String::from_utf8_lossy(&output.stderr);
99 let shown = tool.style.display().to_string();
100 let reason = said
101 .lines()
102 .find(|line| line.contains("error:"))
103 .unwrap_or(said.trim())
104 .replace(&format!("{shown}:"), "line ")
105 .replace(&shown, "the configuration");
106 Err(StyleRefused { reason })
107}
108
109#[derive(Debug, Default)]
113pub struct Formatted {
114 pub changed: Vec<PathBuf>,
116 pub failed: Vec<FormatError>,
118}
119
120pub fn format(
126 files: &[PathBuf],
127 tool: &ClangFormat<'_>,
128 check: bool,
129 runner: &(dyn Runner + Sync),
130) -> Formatted {
131 let next = AtomicUsize::new(0);
132 let results: Mutex<Vec<(usize, Result<bool, FormatError>)>> = Mutex::new(Vec::new());
133 std::thread::scope(|scope| {
134 for _ in 0..tool.jobs.clamp(1, files.len().max(1)) {
135 scope.spawn(|| {
136 loop {
137 let i = next.fetch_add(1, Ordering::SeqCst);
138 let Some(file) = files.get(i) else { break };
139 let result = format_one(file, tool, check, runner);
140 results.lock().unwrap().push((i, result));
141 }
142 });
143 }
144 });
145 let mut results = results.into_inner().unwrap();
146 results.sort_by_key(|(i, _)| *i);
147 let mut formatted = Formatted::default();
148 for (i, result) in results {
149 match result {
150 Ok(true) => formatted.changed.push(files[i].clone()),
151 Ok(false) => {}
152 Err(e) => formatted.failed.push(e),
153 }
154 }
155 formatted
156}
157
158fn format_one(
160 file: &Path,
161 tool: &ClangFormat<'_>,
162 check: bool,
163 runner: &(dyn Runner + Sync),
164) -> Result<bool, FormatError> {
165 let failed = |reason: String| FormatError {
166 file: file.to_owned(),
167 reason,
168 };
169 let held = std::fs::read(file).map_err(|e| failed(e.to_string()))?;
170 let style = format!("--style=file:{}", tool.style.display());
171 let args: [&OsStr; 2] = [style.as_ref(), file.as_os_str()];
172 let output = runner
173 .run(tool.program, &args, tool.env)
174 .map_err(|e| failed(e.to_string()))?;
175 if !output.success {
176 let said = String::from_utf8_lossy(&output.stderr).trim().to_owned();
177 return Err(failed(if said.is_empty() {
178 "clang-format failed and said nothing".to_owned()
179 } else {
180 said
181 }));
182 }
183 if output.stdout == held {
184 return Ok(false);
185 }
186 if output.stdout.is_empty() {
189 return Err(failed("clang-format printed nothing for it".to_owned()));
190 }
191 if !check {
192 replace(file, &held, &output.stdout).map_err(failed)?;
193 }
194 Ok(true)
195}
196
197fn replace(file: &Path, held: &[u8], content: &[u8]) -> Result<(), String> {
202 let mut beside = file.as_os_str().to_owned();
203 beside.push(format!(".cuno-fmt-{}", std::process::id()));
204 let beside = PathBuf::from(beside);
205 std::fs::write(&beside, content).map_err(|e| e.to_string())?;
206 let now = std::fs::read(file).map_err(|e| e.to_string());
207 let result = match now {
208 Ok(now) if now != held => {
209 Err("it changed while it was being formatted; run cuno fmt again".to_owned())
210 }
211 Ok(_) => std::fs::rename(&beside, file).map_err(|e| e.to_string()),
212 Err(e) => Err(e),
213 };
214 if result.is_err() {
215 let _ = std::fs::remove_file(&beside);
216 }
217 result
218}
219
220pub const FILE: &str = ".clang-format";
222
223pub const MARKER: &str =
227 "# Generated by cuno from [fmt] in Cuno.toml, and overwritten: edit Cuno.toml instead.";
228
229pub fn clang_format_config(fmt: &Fmt, lang: Lang) -> String {
235 let mut keys: Vec<(&str, String)> = Vec::new();
236 match fmt.style {
237 FmtStyle::Cuno => {
238 keys.push(("BasedOnStyle", "LLVM".to_owned()));
239 keys.push(("IndentWidth", "4".to_owned()));
240 keys.push(("ColumnLimit", "100".to_owned()));
241 keys.push(("BreakBeforeBraces", "Attach".to_owned()));
242 let pointers = match lang {
243 Lang::C => "Right",
244 Lang::Cxx => "Left",
245 };
246 keys.push(("PointerAlignment", pointers.to_owned()));
247 keys.push(("DerivePointerAlignment", "false".to_owned()));
248 keys.push(("SortIncludes", "CaseSensitive".to_owned()));
249 keys.push(("IncludeBlocks", "Preserve".to_owned()));
251 }
252 other => keys.push(("BasedOnStyle", based_on(other).to_owned())),
253 }
254 if let Some(width) = fmt.indent_width {
255 set(&mut keys, "IndentWidth", width.to_string());
256 }
257 if let Some(limit) = fmt.column_limit {
258 set(&mut keys, "ColumnLimit", limit.to_string());
259 }
260 if let Some(tabs) = fmt.use_tabs {
261 set(
262 &mut keys,
263 "UseTab",
264 if tabs { "ForIndentation" } else { "Never" }.to_owned(),
265 );
266 if tabs {
269 let width = match fmt.clang_format.get("IndentWidth") {
270 Some(toml::Value::Integer(width)) => width.to_string(),
271 _ => fmt
272 .indent_width
273 .unwrap_or_else(|| style_indent(fmt.style))
274 .to_string(),
275 };
276 set(&mut keys, "TabWidth", width);
277 }
278 }
279 keys.retain(|(k, _)| !fmt.clang_format.contains_key(*k));
280 let mut text = format!("{MARKER}\n");
281 for (key, value) in keys {
282 text.push_str(&format!("{key}: {value}\n"));
283 }
284 for (key, value) in &fmt.clang_format {
285 text.push_str(&format!("{key}: {}\n", flow(value)));
286 }
287 text
288}
289
290fn set(keys: &mut Vec<(&str, String)>, key: &'static str, value: String) {
292 keys.retain(|(k, _)| *k != key);
293 keys.push((key, value));
294}
295
296fn style_indent(style: FmtStyle) -> u32 {
298 match style {
299 FmtStyle::Cuno | FmtStyle::Microsoft | FmtStyle::Webkit => 4,
300 FmtStyle::Llvm
301 | FmtStyle::Google
302 | FmtStyle::Mozilla
303 | FmtStyle::Chromium
304 | FmtStyle::Gnu => 2,
305 }
306}
307
308fn based_on(style: FmtStyle) -> &'static str {
310 match style {
312 FmtStyle::Cuno | FmtStyle::Llvm => "LLVM",
313 FmtStyle::Google => "Google",
314 FmtStyle::Microsoft => "Microsoft",
315 FmtStyle::Mozilla => "Mozilla",
316 FmtStyle::Webkit => "WebKit",
317 FmtStyle::Chromium => "Chromium",
318 FmtStyle::Gnu => "GNU",
319 }
320}
321
322fn flow(value: &toml::Value) -> String {
324 match value {
325 toml::Value::String(s) => format!("'{}'", s.replace('\'', "''")),
326 toml::Value::Integer(i) => i.to_string(),
327 toml::Value::Float(f) => f.to_string(),
328 toml::Value::Boolean(b) => b.to_string(),
329 toml::Value::Datetime(d) => format!("'{d}'"),
330 toml::Value::Array(items) => {
331 let items: Vec<String> = items.iter().map(flow).collect();
332 format!("[{}]", items.join(", "))
333 }
334 toml::Value::Table(table) => {
335 let entries: Vec<String> = table
336 .iter()
337 .map(|(k, v)| format!("{k}: {}", flow(v)))
338 .collect();
339 format!("{{{}}}", entries.join(", "))
340 }
341 }
342}
343
344#[cfg(test)]
345mod tests {
346 use super::*;
347
348 fn fmt(extra: &str) -> Fmt {
349 let toml = format!("[package]\nname = \"app\"\nversion = \"0.1.0\"\n{extra}");
350 let root = std::path::Path::new("/p");
351 cuno_manifest::parse_manifest(&toml, &root.join("Cuno.toml"), root)
352 .unwrap()
353 .value
354 .fmt
355 }
356
357 struct Fake<'a> {
360 answer: &'a (dyn Fn(&Path) -> Option<Vec<u8>> + Sync),
361 during: &'a (dyn Fn(&Path) + Sync),
362 }
363
364 impl Runner for Fake<'_> {
365 fn run(
366 &self,
367 _program: &Path,
368 args: &[&OsStr],
369 _env: &Env,
370 ) -> std::io::Result<cuno_toolchain::Output> {
371 let file = Path::new(args[1]);
372 (self.during)(file);
373 Ok(match (self.answer)(file) {
374 Some(stdout) => cuno_toolchain::Output {
375 success: true,
376 stdout,
377 stderr: Vec::new(),
378 },
379 None => cuno_toolchain::Output {
380 success: false,
381 stdout: Vec::new(),
382 stderr: b"boom".to_vec(),
383 },
384 })
385 }
386 }
387
388 fn run_fake(files: &[PathBuf], fake: &Fake<'_>, check: bool) -> Formatted {
389 let env = Env::from_pairs([], cuno_core::NameCase::Insensitive);
390 let tool = ClangFormat {
391 program: Path::new("clang-format"),
392 style: Path::new("style"),
393 env: &env,
394 jobs: 4,
395 };
396 format(files, &tool, check, fake)
397 }
398
399 #[test]
406 fn failures_are_collected_and_the_rest_formatted() {
407 let dir = tempfile::tempdir().unwrap();
408 let files: Vec<PathBuf> = ["a.c", "bad1.c", "b.c", "bad2.c", "same.c"]
409 .iter()
410 .map(|n| dir.path().join(n))
411 .collect();
412 for f in &files {
413 std::fs::write(f, "x\n").unwrap();
414 }
415 let answer = |f: &Path| {
416 let name = f.file_name().unwrap().to_str().unwrap();
417 match name {
418 n if n.starts_with("bad") => None,
419 "same.c" => Some(b"x\n".to_vec()),
420 _ => Some(b"y\n".to_vec()),
421 }
422 };
423 let nothing = |_: &Path| {};
424 let fake = Fake {
425 answer: &answer,
426 during: ¬hing,
427 };
428 let checked = run_fake(&files, &fake, true);
429 assert_eq!(checked.changed, [files[0].clone(), files[2].clone()]);
430 assert_eq!(std::fs::read_to_string(&files[0]).unwrap(), "x\n");
431 let done = run_fake(&files, &fake, false);
432 assert_eq!(done.changed, [files[0].clone(), files[2].clone()]);
433 assert_eq!(
434 done.failed
435 .iter()
436 .map(|e| e.file.clone())
437 .collect::<Vec<_>>(),
438 [files[1].clone(), files[3].clone()]
439 );
440 assert_eq!(std::fs::read_to_string(&files[0]).unwrap(), "y\n");
441 assert_eq!(std::fs::read_to_string(&files[1]).unwrap(), "x\n");
442 let left: Vec<_> = std::fs::read_dir(dir.path()).unwrap().collect();
443 assert_eq!(left.len(), files.len(), "no file left beside");
444 }
445
446 #[test]
452 fn a_source_is_never_lost() {
453 let dir = tempfile::tempdir().unwrap();
454 let file = dir.path().join("a.c");
455 std::fs::write(&file, "int x;\n").unwrap();
456 let empty = |_: &Path| Some(Vec::new());
457 let nothing = |_: &Path| {};
458 let done = run_fake(
459 std::slice::from_ref(&file),
460 &Fake {
461 answer: &empty,
462 during: ¬hing,
463 },
464 false,
465 );
466 assert_eq!(done.failed.len(), 1);
467 assert_eq!(std::fs::read_to_string(&file).unwrap(), "int x;\n");
468
469 let tidy = |_: &Path| Some(b"int x;\n".to_vec());
470 let edit = |f: &Path| std::fs::write(f, "int x; // mine\n").unwrap();
471 let done = run_fake(
472 std::slice::from_ref(&file),
473 &Fake {
474 answer: &tidy,
475 during: &edit,
476 },
477 false,
478 );
479 assert!(
480 done.failed[0].reason.contains("changed while"),
481 "{:?}",
482 done.failed
483 );
484 assert_eq!(std::fs::read_to_string(&file).unwrap(), "int x; // mine\n");
485 }
486
487 fn lines(text: &str) -> Vec<&str> {
488 text.lines().filter(|l| !l.starts_with('#')).collect()
489 }
490
491 #[test]
498 fn the_cuno_style_is_the_spec_s() {
499 let cxx = clang_format_config(&fmt(""), Lang::Cxx);
500 assert_eq!(
501 lines(&cxx),
502 [
503 "BasedOnStyle: LLVM",
504 "IndentWidth: 4",
505 "ColumnLimit: 100",
506 "BreakBeforeBraces: Attach",
507 "PointerAlignment: Left",
508 "DerivePointerAlignment: false",
509 "SortIncludes: CaseSensitive",
510 "IncludeBlocks: Preserve",
511 ]
512 );
513 let c = clang_format_config(&fmt(""), Lang::C);
514 assert!(lines(&c).contains(&"PointerAlignment: Right"), "{c}");
515 assert!(cxx.starts_with("# Generated by cuno"), "{cxx}");
516 }
517
518 #[test]
522 fn a_named_style_is_clang_format_s() {
523 for (style, name) in [
524 ("llvm", "LLVM"),
525 ("google", "Google"),
526 ("microsoft", "Microsoft"),
527 ("mozilla", "Mozilla"),
528 ("webkit", "WebKit"),
529 ("chromium", "Chromium"),
530 ("gnu", "GNU"),
531 ] {
532 let text =
533 clang_format_config(&fmt(&format!("[fmt]\nstyle = \"{style}\"\n")), Lang::Cxx);
534 assert_eq!(
535 lines(&text),
536 [format!("BasedOnStyle: {name}").as_str()],
537 "{style}"
538 );
539 }
540 }
541
542 #[test]
548 fn written_keys_replace_the_style_s() {
549 let text = clang_format_config(
550 &fmt("[fmt]\nindent-width = 3\ncolumn-limit = 90\nuse-tabs = true\n"),
551 Lang::Cxx,
552 );
553 let l = lines(&text);
554 for key in [
555 "IndentWidth: 3",
556 "ColumnLimit: 90",
557 "UseTab: ForIndentation",
558 "TabWidth: 3",
559 ] {
560 assert_eq!(l.iter().filter(|x| **x == key).count(), 1, "{key}: {text}");
561 }
562 assert!(!text.contains("IndentWidth: 4"), "{text}");
563 let spaces = clang_format_config(
564 &fmt("[fmt]\nstyle = \"google\"\nuse-tabs = false\n"),
565 Lang::Cxx,
566 );
567 assert_eq!(lines(&spaces), ["BasedOnStyle: Google", "UseTab: Never"]);
568 }
569
570 #[test]
577 fn a_tab_is_one_level_wide() {
578 for (style, width) in [("webkit", "4"), ("google", "2"), ("microsoft", "4")] {
579 let text = clang_format_config(
580 &fmt(&format!("[fmt]\nstyle = \"{style}\"\nuse-tabs = true\n")),
581 Lang::Cxx,
582 );
583 assert!(
584 lines(&text).contains(&format!("TabWidth: {width}").as_str()),
585 "{text}"
586 );
587 }
588 let text = clang_format_config(
589 &fmt("[fmt]\nuse-tabs = true\n[fmt.clang-format]\nIndentWidth = 2\n"),
590 Lang::Cxx,
591 );
592 assert!(lines(&text).contains(&"TabWidth: 2"), "{text}");
593 }
594
595 #[test]
602 fn the_escape_hatch_replaces_cuno_s_keys() {
603 let text = clang_format_config(
604 &fmt(
605 "[fmt.clang-format]\nPointerAlignment = \"Right\"\nIndentCaseLabels = true\n\
606 BraceWrapping = { AfterFunction = true }\nMacros = [\"A=x\", \"it's\"]\n",
607 ),
608 Lang::Cxx,
609 );
610 let l = lines(&text);
611 assert_eq!(
612 l.iter()
613 .filter(|x| x.starts_with("PointerAlignment"))
614 .count(),
615 1
616 );
617 assert!(l.contains(&"PointerAlignment: 'Right'"), "{text}");
618 assert!(l.contains(&"IndentCaseLabels: true"), "{text}");
619 assert!(
620 l.contains(&"BraceWrapping: {AfterFunction: true}"),
621 "{text}"
622 );
623 assert!(l.contains(&"Macros: ['A=x', 'it''s']"), "{text}");
624 }
625}