ecformat 0.1.1

command line tool to keep files correct in respect of your EditorConfig
Documentation
// SPDX-FileCopyrightText: Contributors to ecformat project <https://codeberg.org/BaumiCoder/ecformat>
//
// SPDX-License-Identifier: BlueOak-1.0.0

use anyhow::Result;
use log::error;
use snafu::ensure;

pub mod cli;

mod editorconfig;

mod files;

#[cfg(test)]
pub(crate) mod test_utils;

use cli::{CommandArgs, LibCommands};

pub use crate::editorconfig::errors;

/// Execute one of the CLI lib commands.
/// (The other CLI commands are not supported by the lib crate.)
/// See also [`check`] and [`fix`].
pub fn execute(cmd: &LibCommands) -> Result<()> {
    match cmd {
        LibCommands::Check(args) => check(args),
        LibCommands::Fix(args) => fix(args),
    }
}

/// Execute the check command.
/// The error in the Result is a [`errors::CheckErrorList`]
/// if the check found violations against your EditorConfig.
/// Use a downcast method to check if it is the case and access the errors list.
pub fn check(args: &CommandArgs) -> Result<()> {
    let mut errors = Vec::new();

    for entry in files::get_target_files(&args.targets()?, &args.ignore_args)? {
        let path = entry?;
        if let Err(e) = editorconfig::check_file(&path, &args.editorconfig_args) {
            let check_error = errors::CheckSnafu {
                path,
                error_type: e.downcast::<editorconfig::errors::CheckErrorType>()?,
            }
            .build();

            error!("{check_error}");
            errors.push(check_error);
        }
    }
    ensure!(
        errors.is_empty(),
        editorconfig::errors::CheckErrorListSnafu { errors }
    );
    Ok(())
}

/// Execute the fix command.
pub fn fix(args: &CommandArgs) -> Result<()> {
    for entry in files::get_target_files(&args.targets()?, &args.ignore_args)? {
        editorconfig::fix_file(&entry?, &args.editorconfig_args)?
    }

    Ok(())
}