Skip to main content

hyperlane_cli/fmt/
fn.rs

1use super::*;
2
3/// Executes unified `crate-cli` formatting first (Markdown, YAML, JSON/JSONC, TOML, plain text, derives, `cargo fmt`), then applies Hyperlane-specific attribute formatting.
4///
5/// # Arguments
6///
7/// - `&Path` - Workspace root directory, `Cargo.toml` manifest path, or single file path.
8/// - `bool` - When `true`, verifies formatting without writing files.
9///
10/// # Returns
11///
12/// - `io::Result<HyperlaneFmtReport>` - Aggregated formatting report or error.
13pub async fn execute_fmt(target_root: &Path, check: bool) -> io::Result<HyperlaneFmtReport> {
14    let is_non_manifest_file: bool = target_root.is_file()
15        && target_root.file_name().and_then(OsStr::to_str) != Some(FMT_CARGO_TOML);
16    let text_report: UnifiedFmtReport = if is_non_manifest_file {
17        format_workspace_text_files(target_root, check)?
18    } else {
19        execute_unified_fmt(target_root, check).await?
20    };
21    let workspace_dir: PathBuf = if target_root.is_file() {
22        target_root
23            .parent()
24            .map(Path::to_path_buf)
25            .unwrap_or_else(|| PathBuf::from("."))
26    } else {
27        target_root.to_path_buf()
28    };
29    let has_manifest: bool = workspace_dir.join(FMT_CARGO_TOML).exists();
30    if has_manifest && !is_non_manifest_file {
31        run_workspace_cargo_fmt(&workspace_dir, check).await?;
32    }
33    let (rust_scanned, rust_changed): (usize, Vec<String>) =
34        format_hyperlane_attributes_in_workspace(target_root, check)?;
35    let rust_formatted: usize = rust_changed.len();
36    if !check && has_manifest && !is_non_manifest_file && rust_formatted > 0 {
37        run_workspace_cargo_fmt(&workspace_dir, false).await?;
38    }
39    let mut changed_files: Vec<String> = text_report.get_changed_files().clone();
40    changed_files.extend(rust_changed);
41    Ok(HyperlaneFmtReport::new(
42        text_report.get_files_scanned(),
43        text_report.get_files_formatted(),
44        rust_scanned,
45        rust_formatted,
46        check,
47        changed_files,
48    ))
49}
50
51/// Normalizes single-line Hyperlane attribute macros (`#[route(...)]`, `#[methods(...)]`, `#[hyperlane::...(...)]`, etc.) in a Rust source string.
52///
53/// # Arguments
54///
55/// - `&str` - Raw Rust source code.
56///
57/// # Returns
58///
59/// - `(String, usize)` - Tuple of `(formatted_source, normalized_attribute_count)`.
60#[must_use]
61pub fn format_hyperlane_attributes_in_source(source: &str) -> (String, usize) {
62    let mut out: String = String::with_capacity(source.len());
63    let mut hits: usize = 0;
64    let ends_with_newline: bool = source.ends_with('\n');
65    let lines: Vec<&str> = source.lines().collect();
66    for (idx, line) in lines.iter().enumerate() {
67        let formatted_line: String = match format_hyperlane_attr_line(line) {
68            Some(next) if next != *line => {
69                hits += 1;
70                next
71            }
72            _ => (*line).to_string(),
73        };
74        out.push_str(&formatted_line);
75        if idx + 1 < lines.len() || ends_with_newline {
76            out.push('\n');
77        }
78    }
79    (out, hits)
80}
81
82/// Formats Hyperlane attributes across all `.rs` files under `root` (or a single `.rs` file).
83///
84/// # Arguments
85///
86/// - `&Path` - Root directory or individual `.rs` file path.
87/// - `bool` - When `true`, returns an error if any file needs formatting without modifying disk.
88///
89/// # Returns
90///
91/// - `io::Result<(usize, Vec<String>)>` - Tuple of `(scanned_count, changed_file_paths)`.
92pub fn format_hyperlane_attributes_in_workspace(
93    root: &Path,
94    check: bool,
95) -> io::Result<(usize, Vec<String>)> {
96    let mut files: Vec<PathBuf> = Vec::new();
97    collect_rs_files(root, true, &mut files)?;
98    files.sort();
99    let scanned: usize = files.len();
100    let mut changed: Vec<String> = Vec::new();
101    for file_path in files {
102        let original: String = fs::read_to_string(&file_path)?;
103        let (formatted, _): (String, usize) = format_hyperlane_attributes_in_source(&original);
104        if formatted != original {
105            changed.push(file_path.display().to_string());
106            if !check {
107                fs::write(&file_path, formatted)?;
108            }
109        }
110    }
111    if check && !changed.is_empty() {
112        return Err(io::Error::other(format!(
113            "{ERR_HYPERLANE_ATTR_CHECK_FAILED}: {}",
114            changed.join(", ")
115        )));
116    }
117    Ok((scanned, changed))
118}
119
120/// Runs `cargo fmt --all` (or `--all -- --check`) inside `workspace_dir`.
121///
122/// # Arguments
123///
124/// - `&Path` - Workspace directory containing `Cargo.toml`.
125/// - `bool` - Whether to pass `--check`.
126///
127/// # Returns
128///
129/// - `io::Result<()>` - Execution status.
130async fn run_workspace_cargo_fmt(workspace_dir: &Path, check: bool) -> io::Result<()> {
131    let mut cmd: Command = Command::new(FMT_BIN_CARGO);
132    cmd.current_dir(workspace_dir)
133        .arg(FMT_ARG_FMT)
134        .arg(FMT_ARG_ALL);
135    if check {
136        cmd.arg(FMT_ARG_DOUBLE_DASH).arg(FMT_ARG_CHECK);
137    }
138    cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
139    let output: Output = cmd.output().await?;
140    if !output.status.success() {
141        let stderr: String = String::from_utf8_lossy(&output.stderr).trim().to_string();
142        return Err(io::Error::other(format!(
143            "{ERR_CARGO_FMT_FAILED}: {stderr}"
144        )));
145    }
146    Ok(())
147}
148
149/// Recursively collects `.rs` files under `path` while skipping generated directories.
150///
151/// # Arguments
152///
153/// - `&Path` - Directory or file path to traverse.
154/// - `bool` - Whether `path` is the top-level target.
155/// - `&mut Vec<PathBuf>` - Output vector of Rust source paths.
156///
157/// # Returns
158///
159/// - `io::Result<()>` - Traversal result.
160fn collect_rs_files(path: &Path, is_root: bool, out: &mut Vec<PathBuf>) -> io::Result<()> {
161    if path.is_file() {
162        if path.extension().and_then(OsStr::to_str) == Some(FMT_EXT_RS) {
163            out.push(path.to_path_buf());
164        }
165        return Ok(());
166    }
167    if !path.is_dir() {
168        return Ok(());
169    }
170    if !is_root
171        && let Some(name) = path.file_name().and_then(OsStr::to_str)
172        && FMT_SKIP_DIRS.contains(&name)
173    {
174        return Ok(());
175    }
176    for entry_res in fs::read_dir(path)? {
177        let entry: DirEntry = entry_res?;
178        let child: PathBuf = entry.path();
179        if child.is_dir() {
180            collect_rs_files(&child, false, out)?;
181        } else if child.extension().and_then(OsStr::to_str) == Some(FMT_EXT_RS) {
182            out.push(child);
183        }
184    }
185    Ok(())
186}
187
188/// Normalizes a single-line Hyperlane attribute if `line` matches `#[<hyperlane_attr>(...)]`.
189///
190/// # Arguments
191///
192/// - `&str` - Single source line.
193///
194/// # Returns
195///
196/// - `Option<String>` - Normalized line when it is a recognized single-line Hyperlane attribute.
197fn format_hyperlane_attr_line(line: &str) -> Option<String> {
198    let trimmed_start: &str = line.trim_start();
199    let indent_len: usize = line.len() - trimmed_start.len();
200    let indent: &str = &line[..indent_len];
201    let trimmed: &str = trimmed_start.trim_end();
202    if !trimmed.starts_with("#[") || !trimmed.ends_with(']') {
203        return None;
204    }
205    let body: &str = &trimmed[2..trimmed.len() - 1];
206    let open_paren: usize = body.find('(')?;
207    if !body.ends_with(')') {
208        return None;
209    }
210    let raw_path: &str = body[..open_paren].trim();
211    let attr_ident: &str = raw_path.rsplit("::").next().unwrap_or(raw_path).trim();
212    if !HYPERLANE_ATTR_NAMES.contains(&attr_ident) {
213        return None;
214    }
215    let raw_args: &str = &body[open_paren + 1..body.len() - 1];
216    let norm_args: String = normalize_attr_arg_list(raw_args);
217    Some(format!("{indent}#[{raw_path}({norm_args})]"))
218}
219
220/// Normalizes spacing around commas and outer parentheses in a single-line attribute argument list while preserving string literals verbatim.
221///
222/// # Arguments
223///
224/// - `&str` - Raw argument slice inside `(...)`.
225///
226/// # Returns
227///
228/// - `String` - Normalized argument list.
229fn normalize_attr_arg_list(raw: &str) -> String {
230    let trimmed: &str = raw.trim();
231    if trimmed.is_empty() {
232        return String::new();
233    }
234    let mut parts: Vec<String> = Vec::new();
235    let mut cur: String = String::new();
236    let mut in_string: bool = false;
237    let mut escaped: bool = false;
238    let mut depth: usize = 0;
239    for ch in trimmed.chars() {
240        if in_string {
241            cur.push(ch);
242            if escaped {
243                escaped = false;
244            } else if ch == '\\' {
245                escaped = true;
246            } else if ch == '"' {
247                in_string = false;
248            }
249            continue;
250        }
251        match ch {
252            '"' => {
253                in_string = true;
254                cur.push(ch);
255            }
256            '(' | '[' | '{' => {
257                depth += 1;
258                cur.push(ch);
259            }
260            ')' | ']' | '}' => {
261                depth = depth.saturating_sub(1);
262                cur.push(ch);
263            }
264            ',' if depth == 0 => {
265                let piece: String = cur.trim().to_string();
266                if !piece.is_empty() {
267                    parts.push(piece);
268                }
269                cur.clear();
270            }
271            _ => cur.push(ch),
272        }
273    }
274    let tail: String = cur.trim().to_string();
275    if !tail.is_empty() {
276        parts.push(tail);
277    }
278    parts.join(", ")
279}