workspacer_cli/
format_imports.rs

1// ---------------- [ File: workspacer-cli/src/format_imports.rs ]
2crate::ix!();
3
4/// Subcommand data for `ws format imports --crate <crate_name> [--workspace <dir>] [--skip-git-check]`
5#[derive(Debug, StructOpt)]
6pub struct FormatImportsCommand {
7    /// The name of the crate to format
8    #[structopt(long = "crate")]
9    crate_name: String,
10
11    /// If provided, we use this directory as the workspace root instead of the current dir
12    #[structopt(long = "workspace")]
13    workspace_path: Option<PathBuf>,
14
15    /// Skip checking for a clean Git state if true
16    #[structopt(long = "skip-git-check")]
17    skip_git_check: bool,
18}
19
20impl FormatImportsCommand {
21    pub async fn run(&self) -> Result<(), WorkspaceError> {
22        let crate_name_owned = self.crate_name.clone();
23        let skip_flag = self.skip_git_check;
24        let ws_path = self.workspace_path.clone();
25
26        // Use our standard helper that loads a workspace + optional crate name
27        run_with_workspace_and_crate_name(
28            ws_path,
29            skip_flag,
30            crate_name_owned,
31            move |ws, the_crate_name| {
32                Box::pin(async move {
33                    // 1) Look up the crate handle
34                    let arc_crate = ws
35                        .find_crate_by_name(the_crate_name)
36                        .await
37                        .ok_or_else(|| {
38                            error!("No crate named '{}' found in workspace", the_crate_name);
39                            CrateError::CrateNotFoundInWorkspace {
40                                crate_name: the_crate_name.to_owned(),
41                            }
42                        })?;
43
44                    // 2) Lock and call sort_and_format_imports() on that crate
45                    let mut handle = arc_crate.lock().await.clone();
46                    handle
47                        .sort_and_format_imports()
48                        .await
49                        .map_err(|e| {
50                            error!(
51                                "Failed to format imports for crate='{}': {:?}",
52                                the_crate_name, e
53                            );
54                            WorkspaceError::CrateError(e)
55                        })?;
56
57                    info!("Successfully formatted imports for crate='{}'!", the_crate_name);
58                    Ok(())
59                })
60            },
61        )
62        .await
63    }
64}