hyperlane-cli 23.0.0

A command-line tool for Hyperlane framework.
Documentation
use super::*;

/// Executes unified `crate-cli` formatting first (Markdown, YAML, JSON/JSONC, TOML, plain text, derives, `cargo fmt`), then applies Hyperlane-specific attribute formatting.
///
/// # Arguments
///
/// - `&Path` - Workspace root directory, `Cargo.toml` manifest path, or single file path.
/// - `bool` - When `true`, verifies formatting without writing files.
///
/// # Returns
///
/// - `io::Result<HyperlaneFmtReport>` - Aggregated formatting report or error.
pub async fn execute_fmt(target_root: &Path, check: bool) -> io::Result<HyperlaneFmtReport> {
    let is_non_manifest_file: bool = target_root.is_file()
        && target_root.file_name().and_then(OsStr::to_str) != Some(FMT_CARGO_TOML);
    let text_report: UnifiedFmtReport = if is_non_manifest_file {
        format_workspace_text_files(target_root, check)?
    } else {
        execute_unified_fmt(target_root, check).await?
    };
    let workspace_dir: PathBuf = if target_root.is_file() {
        target_root
            .parent()
            .map(Path::to_path_buf)
            .unwrap_or_else(|| PathBuf::from("."))
    } else {
        target_root.to_path_buf()
    };
    let has_manifest: bool = workspace_dir.join(FMT_CARGO_TOML).exists();
    if has_manifest && !is_non_manifest_file {
        run_workspace_cargo_fmt(&workspace_dir, check).await?;
    }
    let (rust_scanned, rust_changed): (usize, Vec<String>) =
        format_hyperlane_attributes_in_workspace(target_root, check)?;
    let rust_formatted: usize = rust_changed.len();
    if !check && has_manifest && !is_non_manifest_file && rust_formatted > 0 {
        run_workspace_cargo_fmt(&workspace_dir, false).await?;
    }
    let mut changed_files: Vec<String> = text_report.get_changed_files().clone();
    changed_files.extend(rust_changed);
    Ok(HyperlaneFmtReport::new(
        text_report.get_files_scanned(),
        text_report.get_files_formatted(),
        rust_scanned,
        rust_formatted,
        check,
        changed_files,
    ))
}

/// Normalizes single-line Hyperlane attribute macros (`#[route(...)]`, `#[methods(...)]`, `#[hyperlane::...(...)]`, etc.) in a Rust source string.
///
/// # Arguments
///
/// - `&str` - Raw Rust source code.
///
/// # Returns
///
/// - `(String, usize)` - Tuple of `(formatted_source, normalized_attribute_count)`.
#[must_use]
pub fn format_hyperlane_attributes_in_source(source: &str) -> (String, usize) {
    let mut scratch: String = String::new();
    format_hyperlane_attributes_with_scratch(source, &mut scratch)
}

/// Normalizes single-line Hyperlane attributes in `source` while reusing `scratch` across lines.
///
/// # Arguments
///
/// - `&str` - Raw Rust source code.
/// - `&mut String` - Reusable scratch buffer for normalizing candidate attribute lines.
///
/// # Returns
///
/// - `(String, usize)` - Tuple of `(formatted_source, normalized_attribute_count)`.
fn format_hyperlane_attributes_with_scratch(source: &str, scratch: &mut String) -> (String, usize) {
    let has_crlf: bool = source.contains(FMT_CRLF);
    let mut hits: usize = 0;
    if !has_crlf {
        let mut out: Option<String> = None;
        let mut offset: usize = 0;
        for raw_line in source.split_inclusive('\n') {
            let (line, has_nl): (&str, bool) = match raw_line.strip_suffix('\n') {
                Some(stripped) => (stripped, true),
                None => (raw_line, false),
            };
            if format_hyperlane_attr_line_into(line, scratch) {
                hits += 1;
                let dst: &mut String = out.get_or_insert_with(|| {
                    let mut buf: String = String::with_capacity(source.len());
                    buf.push_str(&source[..offset]);
                    buf
                });
                dst.push_str(scratch.as_str());
                if has_nl {
                    dst.push('\n');
                }
            } else if let Some(dst) = out.as_mut() {
                dst.push_str(raw_line);
            }
            offset += raw_line.len();
        }
        return (out.unwrap_or_else(|| source.to_owned()), hits);
    }
    let mut out: String = String::with_capacity(source.len());
    let ends_with_newline: bool = source.ends_with('\n');
    let mut first: bool = true;
    for line in source.lines() {
        if !first {
            out.push('\n');
        }
        first = false;
        if format_hyperlane_attr_line_into(line, scratch) {
            hits += 1;
            out.push_str(scratch.as_str());
        } else {
            out.push_str(line);
        }
    }
    if ends_with_newline && !first {
        out.push('\n');
    }
    (out, hits)
}

/// Checks whether `source` requires any Hyperlane attribute or CRLF normalization without allocating output.
///
/// # Arguments
///
/// - `&str` - Raw Rust source code.
/// - `&mut String` - Reusable scratch buffer for normalizing candidate attribute lines.
///
/// # Returns
///
/// - `bool` - `true` if formatting `source` would change its contents.
fn source_needs_hyperlane_attr_format(source: &str, scratch: &mut String) -> bool {
    if source.contains(FMT_CRLF) {
        return true;
    }
    for raw_line in source.split_inclusive('\n') {
        let line: &str = raw_line.strip_suffix('\n').unwrap_or(raw_line);
        if format_hyperlane_attr_line_into(line, scratch) {
            return true;
        }
    }
    false
}

/// Formats Hyperlane attributes across all `.rs` files under `root` (or a single `.rs` file).
///
/// # Arguments
///
/// - `&Path` - Root directory or individual `.rs` file path.
/// - `bool` - When `true`, returns an error if any file needs formatting without modifying disk.
///
/// # Returns
///
/// - `io::Result<(usize, Vec<String>)>` - Tuple of `(scanned_count, changed_file_paths)`.
pub fn format_hyperlane_attributes_in_workspace(
    root: &Path,
    check: bool,
) -> io::Result<(usize, Vec<String>)> {
    let mut files: Vec<PathBuf> = Vec::new();
    collect_rs_files(root, true, &mut files)?;
    files.sort();
    let scanned: usize = files.len();
    let mut changed: Vec<String> = Vec::new();
    let mut read_buf: String = String::new();
    let mut scratch: String = String::new();
    for file_path in files {
        read_buf.clear();
        let _: usize = File::open(&file_path)?.read_to_string(&mut read_buf)?;
        if check {
            if source_needs_hyperlane_attr_format(&read_buf, &mut scratch) {
                changed.push(file_path.display().to_string());
            }
        } else if source_needs_hyperlane_attr_format(&read_buf, &mut scratch) {
            let (formatted, _): (String, usize) =
                format_hyperlane_attributes_with_scratch(&read_buf, &mut scratch);
            if formatted != read_buf {
                changed.push(file_path.display().to_string());
                fs::write(&file_path, formatted)?;
            }
        }
    }
    if check && !changed.is_empty() {
        return Err(io::Error::other(format!(
            "{ERR_HYPERLANE_ATTR_CHECK_FAILED}: {}",
            changed.join(", ")
        )));
    }
    Ok((scanned, changed))
}

/// Runs `cargo fmt --all` (or `--all -- --check`) inside `workspace_dir`.
///
/// # Arguments
///
/// - `&Path` - Workspace directory containing `Cargo.toml`.
/// - `bool` - Whether to pass `--check`.
///
/// # Returns
///
/// - `io::Result<()>` - Execution status.
async fn run_workspace_cargo_fmt(workspace_dir: &Path, check: bool) -> io::Result<()> {
    let mut cmd: Command = Command::new(FMT_BIN_CARGO);
    cmd.current_dir(workspace_dir)
        .arg(FMT_ARG_FMT)
        .arg(FMT_ARG_ALL);
    if check {
        cmd.arg(FMT_ARG_DOUBLE_DASH).arg(FMT_ARG_CHECK);
    }
    cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
    let output: Output = cmd.output().await?;
    if !output.status.success() {
        let stderr: String = String::from_utf8_lossy(&output.stderr).trim().to_string();
        return Err(io::Error::other(format!(
            "{ERR_CARGO_FMT_FAILED}: {stderr}"
        )));
    }
    Ok(())
}

/// Recursively collects `.rs` files under `path` while skipping generated directories.
///
/// # Arguments
///
/// - `&Path` - Directory or file path to traverse.
/// - `bool` - Whether `path` is the top-level target.
/// - `&mut Vec<PathBuf>` - Output vector of Rust source paths.
///
/// # Returns
///
/// - `io::Result<()>` - Traversal result.
fn collect_rs_files(path: &Path, is_root: bool, out: &mut Vec<PathBuf>) -> io::Result<()> {
    if path.is_file() {
        if path.extension().and_then(OsStr::to_str) == Some(FMT_EXT_RS) {
            out.push(path.to_path_buf());
        }
        return Ok(());
    }
    if !path.is_dir() {
        return Ok(());
    }
    if !is_root
        && let Some(name) = path.file_name().and_then(OsStr::to_str)
        && FMT_SKIP_DIRS.contains(&name)
    {
        return Ok(());
    }
    for entry_res in fs::read_dir(path)? {
        let entry: DirEntry = entry_res?;
        let file_type: FileType = entry.file_type()?;
        let child: PathBuf = entry.path();
        let is_dir: bool = if file_type.is_symlink() {
            child.is_dir()
        } else {
            file_type.is_dir()
        };
        if is_dir {
            if let Some(name) = entry.file_name().to_str()
                && FMT_SKIP_DIRS.contains(&name)
            {
                continue;
            }
            collect_rs_files(&child, false, out)?;
        } else if child.extension().and_then(OsStr::to_str) == Some(FMT_EXT_RS) {
            out.push(child);
        }
    }
    Ok(())
}

/// Normalizes a single-line Hyperlane attribute into `scratch` if `line` matches `#[<hyperlane_attr>(...)]` and changed.
///
/// # Arguments
///
/// - `&str` - Single source line.
/// - `&mut String` - Reusable scratch buffer populated with the normalized line when `true` is returned.
///
/// # Returns
///
/// - `bool` - `true` when `line` is a recognized single-line Hyperlane attribute whose normalized text differs from `line`.
fn format_hyperlane_attr_line_into(line: &str, scratch: &mut String) -> bool {
    let trimmed_start: &str = line.trim_start();
    if !trimmed_start.starts_with("#[") {
        return false;
    }
    let trimmed: &str = trimmed_start.trim_end();
    if !trimmed.ends_with(']') {
        return false;
    }
    let body: &str = &trimmed[2..trimmed.len() - 1];
    if !body.ends_with(')') {
        return false;
    }
    let Some(open_paren) = body.find('(') else {
        return false;
    };
    let raw_path: &str = body[..open_paren].trim();
    let attr_ident: &str = raw_path.rsplit("::").next().unwrap_or(raw_path).trim();
    if HYPERLANE_ATTR_NAMES.binary_search(&attr_ident).is_err() {
        return false;
    }
    let indent_len: usize = line.len() - trimmed_start.len();
    let indent: &str = &line[..indent_len];
    let raw_args: &str = &body[open_paren + 1..body.len() - 1];
    scratch.clear();
    scratch.reserve(line.len());
    scratch.push_str(indent);
    scratch.push_str("#[");
    scratch.push_str(raw_path);
    scratch.push('(');
    normalize_attr_arg_list_into(raw_args, scratch);
    scratch.push_str(")]");
    scratch.as_str() != line
}

/// Normalizes spacing around commas and outer parentheses in a single-line attribute argument list directly into `out`.
///
/// # Arguments
///
/// - `&str` - Raw argument slice inside `(...)`.
/// - `&mut String` - Destination string receiving the normalized argument list.
fn normalize_attr_arg_list_into(raw: &str, out: &mut String) {
    let trimmed: &str = raw.trim();
    if trimmed.is_empty() {
        return;
    }
    let mut part_start: usize = 0;
    let mut emitted: usize = 0;
    let mut in_string: bool = false;
    let mut escaped: bool = false;
    let mut depth: usize = 0;
    for (idx, ch) in trimmed.char_indices() {
        if in_string {
            if escaped {
                escaped = false;
            } else if ch == '\\' {
                escaped = true;
            } else if ch == '"' {
                in_string = false;
            }
            continue;
        }
        match ch {
            '"' => {
                in_string = true;
            }
            '(' | '[' | '{' => {
                depth += 1;
            }
            ')' | ']' | '}' => {
                depth = depth.saturating_sub(1);
            }
            ',' if depth == 0 => {
                let piece: &str = trimmed[part_start..idx].trim();
                if !piece.is_empty() {
                    if emitted > 0 {
                        out.push_str(", ");
                    }
                    out.push_str(piece);
                    emitted += 1;
                }
                part_start = idx + 1;
            }
            _ => {}
        }
    }
    let tail: &str = trimmed[part_start..].trim();
    if !tail.is_empty() {
        if emitted > 0 {
            out.push_str(", ");
        }
        out.push_str(tail);
    }
}