mago_cli/commands/
format.rs1use clap::Parser;
2
3use mago_interner::ThreadedInterner;
4use mago_service::config::Configuration;
5use mago_service::formatter::FormatterService;
6use mago_service::source::SourceService;
7
8use crate::utils::bail;
9
10#[derive(Parser, Debug)]
11#[command(
12 name = "format",
13 aliases = ["fmt"],
14 about = "Format source files",
15 long_about = r#"
16Format source files.
17
18This command will format source files according to the rules defined in the configuration file.
19"#
20)]
21pub struct FormatCommand {
22 #[arg(long, short = 'w', help = "The width of the printed source code", value_name = "WIDTH")]
23 pub print_width: Option<usize>,
24 #[arg(long, short = 'd', help = "Run the command without writing any changes to disk")]
25 pub dry_run: bool,
26}
27
28pub async fn execute(command: FormatCommand, mut configuration: Configuration) -> i32 {
29 let interner = ThreadedInterner::new();
30
31 let source_service = SourceService::new(interner.clone(), configuration.source);
32 let source_manager = source_service.load().await.unwrap_or_else(bail);
33
34 if let Some(width) = command.print_width {
35 configuration.format.print_width = Some(width);
36 }
37
38 let service = FormatterService::new(configuration.format, interner.clone(), source_manager.clone());
39
40 let changed = service.run(command.dry_run).await.unwrap_or_else(bail);
41
42 if changed == 0 {
43 mago_feedback::info!("All source files are already formatted");
44
45 return 0;
46 }
47
48 if command.dry_run {
49 mago_feedback::info!("Found {} source files that need formatting", changed);
50
51 1
52 } else {
53 mago_feedback::info!("Formatted {} source files successfully", changed);
54
55 0
56 }
57}