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 scratch: String = String::new();
63    format_hyperlane_attributes_with_scratch(source, &mut scratch)
64}
65
66/// Normalizes single-line Hyperlane attributes in `source` while reusing `scratch` across lines.
67///
68/// # Arguments
69///
70/// - `&str` - Raw Rust source code.
71/// - `&mut String` - Reusable scratch buffer for normalizing candidate attribute lines.
72///
73/// # Returns
74///
75/// - `(String, usize)` - Tuple of `(formatted_source, normalized_attribute_count)`.
76fn format_hyperlane_attributes_with_scratch(source: &str, scratch: &mut String) -> (String, usize) {
77    let has_crlf: bool = source.contains(FMT_CRLF);
78    let mut hits: usize = 0;
79    if !has_crlf {
80        let mut out: Option<String> = None;
81        let mut offset: usize = 0;
82        for raw_line in source.split_inclusive('\n') {
83            let (line, has_nl): (&str, bool) = match raw_line.strip_suffix('\n') {
84                Some(stripped) => (stripped, true),
85                None => (raw_line, false),
86            };
87            if format_hyperlane_attr_line_into(line, scratch) {
88                hits += 1;
89                let dst: &mut String = out.get_or_insert_with(|| {
90                    let mut buf: String = String::with_capacity(source.len());
91                    buf.push_str(&source[..offset]);
92                    buf
93                });
94                dst.push_str(scratch.as_str());
95                if has_nl {
96                    dst.push('\n');
97                }
98            } else if let Some(dst) = out.as_mut() {
99                dst.push_str(raw_line);
100            }
101            offset += raw_line.len();
102        }
103        return (out.unwrap_or_else(|| source.to_owned()), hits);
104    }
105    let mut out: String = String::with_capacity(source.len());
106    let ends_with_newline: bool = source.ends_with('\n');
107    let mut first: bool = true;
108    for line in source.lines() {
109        if !first {
110            out.push('\n');
111        }
112        first = false;
113        if format_hyperlane_attr_line_into(line, scratch) {
114            hits += 1;
115            out.push_str(scratch.as_str());
116        } else {
117            out.push_str(line);
118        }
119    }
120    if ends_with_newline && !first {
121        out.push('\n');
122    }
123    (out, hits)
124}
125
126/// Checks whether `source` requires any Hyperlane attribute or CRLF normalization without allocating output.
127///
128/// # Arguments
129///
130/// - `&str` - Raw Rust source code.
131/// - `&mut String` - Reusable scratch buffer for normalizing candidate attribute lines.
132///
133/// # Returns
134///
135/// - `bool` - `true` if formatting `source` would change its contents.
136fn source_needs_hyperlane_attr_format(source: &str, scratch: &mut String) -> bool {
137    if source.contains(FMT_CRLF) {
138        return true;
139    }
140    for raw_line in source.split_inclusive('\n') {
141        let line: &str = raw_line.strip_suffix('\n').unwrap_or(raw_line);
142        if format_hyperlane_attr_line_into(line, scratch) {
143            return true;
144        }
145    }
146    false
147}
148
149/// Formats Hyperlane attributes across all `.rs` files under `root` (or a single `.rs` file).
150///
151/// # Arguments
152///
153/// - `&Path` - Root directory or individual `.rs` file path.
154/// - `bool` - When `true`, returns an error if any file needs formatting without modifying disk.
155///
156/// # Returns
157///
158/// - `io::Result<(usize, Vec<String>)>` - Tuple of `(scanned_count, changed_file_paths)`.
159pub fn format_hyperlane_attributes_in_workspace(
160    root: &Path,
161    check: bool,
162) -> io::Result<(usize, Vec<String>)> {
163    let mut files: Vec<PathBuf> = Vec::new();
164    collect_rs_files(root, true, &mut files)?;
165    files.sort();
166    let scanned: usize = files.len();
167    let mut changed: Vec<String> = Vec::new();
168    let mut read_buf: String = String::new();
169    let mut scratch: String = String::new();
170    for file_path in files {
171        read_buf.clear();
172        let _: usize = File::open(&file_path)?.read_to_string(&mut read_buf)?;
173        if check {
174            if source_needs_hyperlane_attr_format(&read_buf, &mut scratch) {
175                changed.push(file_path.display().to_string());
176            }
177        } else if source_needs_hyperlane_attr_format(&read_buf, &mut scratch) {
178            let (formatted, _): (String, usize) =
179                format_hyperlane_attributes_with_scratch(&read_buf, &mut scratch);
180            if formatted != read_buf {
181                changed.push(file_path.display().to_string());
182                fs::write(&file_path, formatted)?;
183            }
184        }
185    }
186    if check && !changed.is_empty() {
187        return Err(io::Error::other(format!(
188            "{ERR_HYPERLANE_ATTR_CHECK_FAILED}: {}",
189            changed.join(", ")
190        )));
191    }
192    Ok((scanned, changed))
193}
194
195/// Runs `cargo fmt --all` (or `--all -- --check`) inside `workspace_dir`.
196///
197/// # Arguments
198///
199/// - `&Path` - Workspace directory containing `Cargo.toml`.
200/// - `bool` - Whether to pass `--check`.
201///
202/// # Returns
203///
204/// - `io::Result<()>` - Execution status.
205async fn run_workspace_cargo_fmt(workspace_dir: &Path, check: bool) -> io::Result<()> {
206    let mut cmd: Command = Command::new(FMT_BIN_CARGO);
207    cmd.current_dir(workspace_dir)
208        .arg(FMT_ARG_FMT)
209        .arg(FMT_ARG_ALL);
210    if check {
211        cmd.arg(FMT_ARG_DOUBLE_DASH).arg(FMT_ARG_CHECK);
212    }
213    cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
214    let output: Output = cmd.output().await?;
215    if !output.status.success() {
216        let stderr: String = String::from_utf8_lossy(&output.stderr).trim().to_string();
217        return Err(io::Error::other(format!(
218            "{ERR_CARGO_FMT_FAILED}: {stderr}"
219        )));
220    }
221    Ok(())
222}
223
224/// Recursively collects `.rs` files under `path` while skipping generated directories.
225///
226/// # Arguments
227///
228/// - `&Path` - Directory or file path to traverse.
229/// - `bool` - Whether `path` is the top-level target.
230/// - `&mut Vec<PathBuf>` - Output vector of Rust source paths.
231///
232/// # Returns
233///
234/// - `io::Result<()>` - Traversal result.
235fn collect_rs_files(path: &Path, is_root: bool, out: &mut Vec<PathBuf>) -> io::Result<()> {
236    if path.is_file() {
237        if path.extension().and_then(OsStr::to_str) == Some(FMT_EXT_RS) {
238            out.push(path.to_path_buf());
239        }
240        return Ok(());
241    }
242    if !path.is_dir() {
243        return Ok(());
244    }
245    if !is_root
246        && let Some(name) = path.file_name().and_then(OsStr::to_str)
247        && FMT_SKIP_DIRS.contains(&name)
248    {
249        return Ok(());
250    }
251    for entry_res in fs::read_dir(path)? {
252        let entry: DirEntry = entry_res?;
253        let file_type: FileType = entry.file_type()?;
254        let child: PathBuf = entry.path();
255        let is_dir: bool = if file_type.is_symlink() {
256            child.is_dir()
257        } else {
258            file_type.is_dir()
259        };
260        if is_dir {
261            if let Some(name) = entry.file_name().to_str()
262                && FMT_SKIP_DIRS.contains(&name)
263            {
264                continue;
265            }
266            collect_rs_files(&child, false, out)?;
267        } else if child.extension().and_then(OsStr::to_str) == Some(FMT_EXT_RS) {
268            out.push(child);
269        }
270    }
271    Ok(())
272}
273
274/// Normalizes a single-line Hyperlane attribute into `scratch` if `line` matches `#[<hyperlane_attr>(...)]` and changed.
275///
276/// # Arguments
277///
278/// - `&str` - Single source line.
279/// - `&mut String` - Reusable scratch buffer populated with the normalized line when `true` is returned.
280///
281/// # Returns
282///
283/// - `bool` - `true` when `line` is a recognized single-line Hyperlane attribute whose normalized text differs from `line`.
284fn format_hyperlane_attr_line_into(line: &str, scratch: &mut String) -> bool {
285    let trimmed_start: &str = line.trim_start();
286    if !trimmed_start.starts_with("#[") {
287        return false;
288    }
289    let trimmed: &str = trimmed_start.trim_end();
290    if !trimmed.ends_with(']') {
291        return false;
292    }
293    let body: &str = &trimmed[2..trimmed.len() - 1];
294    if !body.ends_with(')') {
295        return false;
296    }
297    let Some(open_paren) = body.find('(') else {
298        return false;
299    };
300    let raw_path: &str = body[..open_paren].trim();
301    let attr_ident: &str = raw_path.rsplit("::").next().unwrap_or(raw_path).trim();
302    if HYPERLANE_ATTR_NAMES.binary_search(&attr_ident).is_err() {
303        return false;
304    }
305    let indent_len: usize = line.len() - trimmed_start.len();
306    let indent: &str = &line[..indent_len];
307    let raw_args: &str = &body[open_paren + 1..body.len() - 1];
308    scratch.clear();
309    scratch.reserve(line.len());
310    scratch.push_str(indent);
311    scratch.push_str("#[");
312    scratch.push_str(raw_path);
313    scratch.push('(');
314    normalize_attr_arg_list_into(raw_args, scratch);
315    scratch.push_str(")]");
316    scratch.as_str() != line
317}
318
319/// Normalizes spacing around commas and outer parentheses in a single-line attribute argument list directly into `out`.
320///
321/// # Arguments
322///
323/// - `&str` - Raw argument slice inside `(...)`.
324/// - `&mut String` - Destination string receiving the normalized argument list.
325fn normalize_attr_arg_list_into(raw: &str, out: &mut String) {
326    let trimmed: &str = raw.trim();
327    if trimmed.is_empty() {
328        return;
329    }
330    let mut part_start: usize = 0;
331    let mut emitted: usize = 0;
332    let mut in_string: bool = false;
333    let mut escaped: bool = false;
334    let mut depth: usize = 0;
335    for (idx, ch) in trimmed.char_indices() {
336        if in_string {
337            if escaped {
338                escaped = false;
339            } else if ch == '\\' {
340                escaped = true;
341            } else if ch == '"' {
342                in_string = false;
343            }
344            continue;
345        }
346        match ch {
347            '"' => {
348                in_string = true;
349            }
350            '(' | '[' | '{' => {
351                depth += 1;
352            }
353            ')' | ']' | '}' => {
354                depth = depth.saturating_sub(1);
355            }
356            ',' if depth == 0 => {
357                let piece: &str = trimmed[part_start..idx].trim();
358                if !piece.is_empty() {
359                    if emitted > 0 {
360                        out.push_str(", ");
361                    }
362                    out.push_str(piece);
363                    emitted += 1;
364                }
365                part_start = idx + 1;
366            }
367            _ => {}
368        }
369    }
370    let tail: &str = trimmed[part_start..].trim();
371    if !tail.is_empty() {
372        if emitted > 0 {
373            out.push_str(", ");
374        }
375        out.push_str(tail);
376    }
377}