use std::io::Write as _;
use std::path::{Path, PathBuf};
use mds::{effective_parent, FileSystem};
use miette::Result;
use crate::build::{ensure_existing_mds_file, load_config, read_stdin, resolve_input};
use crate::output::{atomic_write_file, collect_mds_files_detailed, render_unified_diff};
pub(crate) struct FmtArgs {
pub(crate) input: Option<PathBuf>,
pub(crate) check: bool,
pub(crate) diff: bool,
pub(crate) quiet: bool,
}
#[derive(Clone, Copy)]
struct FmtFlags {
check: bool,
diff: bool,
quiet: bool,
}
pub(crate) fn run_fmt(args: FmtArgs) -> Result<()> {
let FmtArgs {
input,
check,
diff,
quiet,
} = args;
let (input, auto_detected) = resolve_input(input, "fmt")?;
if auto_detected && !quiet {
eprintln!("Formatting {}", crate::output::safe_path(&input));
}
let flags = FmtFlags { check, diff, quiet };
if input == Path::new("-") {
return run_fmt_stdin(flags);
}
if input.is_dir() {
if input
.symlink_metadata()
.map(|m| m.file_type().is_symlink())
.unwrap_or(false)
{
return Err(miette::miette!(
"directory argument must not be a symlink: {}",
input.display()
));
}
return run_fmt_directory(&input, flags);
}
ensure_existing_mds_file(&input).map_err(miette::Error::from)?;
run_fmt_file(&input, flags)
}
fn read_source_file(path: &Path) -> Result<String> {
let canonical = mds::NativeFs::check_symlink(path).map_err(miette::Error::from)?;
let path_str = canonical
.to_str()
.ok_or_else(|| miette::miette!("path is not valid UTF-8: {}", path.display()))?;
let fs = mds::NativeFs::new();
let _ = fs.set_root(&effective_parent(&canonical).display().to_string());
fs.read(path_str).map_err(miette::Error::from)
}
struct FmtResult {
formatted: String,
changed: bool,
}
fn format_source_named(
source: &str,
base_dir: Option<&Path>,
file_name: &str,
) -> Result<FmtResult> {
let formatted =
mds::format_str_named(source, base_dir, file_name).map_err(miette::Error::from)?;
let changed = formatted != source;
Ok(FmtResult { formatted, changed })
}
fn run_fmt_stdin(flags: FmtFlags) -> Result<()> {
use crate::output::STDIN_DISPLAY_LABEL;
let FmtFlags { check, diff, quiet } = flags;
let (source, cwd) = read_stdin()?;
let result = format_source_named(&source, Some(&cwd), STDIN_DISPLAY_LABEL)?;
if diff {
print_diff(&render_unified_diff(
&source,
&result.formatted,
STDIN_DISPLAY_LABEL,
))?;
} else if !check {
write_stdout(&result.formatted)?;
}
if check && result.changed {
if !quiet {
eprintln!("Would reformat: {STDIN_DISPLAY_LABEL}");
}
std::process::exit(1);
}
Ok(())
}
fn run_fmt_file(path: &Path, flags: FmtFlags) -> Result<()> {
let FmtFlags { check, diff, quiet } = flags;
let source = read_source_file(path)?;
let base_dir = Some(effective_parent(path));
let file_name = path.display().to_string();
let result = format_source_named(&source, base_dir, &file_name)?;
if diff && result.changed {
let label = crate::output::safe_path(path);
print_diff(&render_unified_diff(&source, &result.formatted, &label))?;
}
let read_only = check || diff;
if !read_only {
if result.changed {
atomic_write_file(path, &result.formatted)?;
if !quiet {
eprintln!("Formatted: {}", crate::output::safe_path(path));
}
} else if !quiet {
eprintln!("Unchanged: {}", crate::output::safe_path(path));
}
return Ok(());
}
if check {
if result.changed {
if !quiet {
eprintln!("Would reformat: {}", crate::output::safe_path(path));
}
std::process::exit(1);
}
if !quiet {
eprintln!("Unchanged: {}", crate::output::safe_path(path));
}
}
Ok(())
}
enum FileOutcome {
Formatted,
Unchanged,
WouldChange,
NoChange,
Failed,
}
fn format_one_file(file: &Path, flags: FmtFlags) -> FileOutcome {
let FmtFlags { check, diff, quiet } = flags;
let file_name = file.display().to_string();
let source = match read_source_file(file) {
Ok(s) => s,
Err(e) => {
crate::output::eprint_error(e);
return FileOutcome::Failed;
}
};
let base_dir = Some(effective_parent(file));
let result = match format_source_named(&source, base_dir, &file_name) {
Ok(r) => r,
Err(e) => {
crate::output::eprint_error(e);
return FileOutcome::Failed;
}
};
if diff && result.changed {
let label = file_name.clone();
if let Err(e) = print_diff(&render_unified_diff(&source, &result.formatted, &label)) {
crate::output::eprint_error(e);
return FileOutcome::Failed;
}
}
let read_only = check || diff;
if read_only {
if result.changed {
FileOutcome::WouldChange
} else {
FileOutcome::NoChange
}
} else if !result.changed {
FileOutcome::Unchanged
} else {
match atomic_write_file(file, &result.formatted) {
Ok(()) => {
if !quiet {
eprintln!("Formatted: {}", crate::output::safe_path(file));
}
FileOutcome::Formatted
}
Err(e) => {
crate::output::eprint_error(e);
FileOutcome::Failed
}
}
}
}
fn run_fmt_directory(dir: &Path, flags: FmtFlags) -> Result<()> {
const MAX_DEPTH: usize = 64;
let _ = load_config(dir)?;
let walk = collect_mds_files_detailed(dir, MAX_DEPTH, None);
let files = walk.files;
if files.is_empty() {
if walk.excluded_by_default > 0 {
eprintln!(
"{} .mds file(s) found but all are under default-excluded directories \
(hidden dirs, node_modules); nothing was formatted",
walk.excluded_by_default
);
std::process::exit(1);
}
if !flags.quiet {
eprintln!("No .mds files found in {}", crate::output::safe_path(dir));
}
return Ok(());
}
let read_only = flags.check || flags.diff;
let mut changed_count: usize = 0;
let mut unchanged_count: usize = 0;
let mut fail_count: usize = 0;
for file in &files {
match format_one_file(file, flags) {
FileOutcome::Formatted | FileOutcome::WouldChange => changed_count += 1,
FileOutcome::Unchanged | FileOutcome::NoChange => unchanged_count += 1,
FileOutcome::Failed => fail_count += 1,
}
}
if read_only {
if !flags.quiet || fail_count > 0 {
eprintln!(
"{changed_count} would reformat, {unchanged_count} unchanged, {fail_count} failed"
);
}
} else if !flags.quiet || fail_count > 0 {
eprintln!("{changed_count} formatted, {unchanged_count} unchanged, {fail_count} failed");
}
if fail_count > 0 || (flags.check && changed_count > 0) {
std::process::exit(1);
}
Ok(())
}
fn write_stdout(s: &str) -> Result<()> {
let mut stdout = std::io::stdout();
if let Err(e) = stdout.write_all(s.as_bytes()) {
if e.kind() == std::io::ErrorKind::BrokenPipe {
return Ok(());
}
return Err(miette::miette!("cannot write to stdout: {e}"));
}
if let Err(e) = stdout.flush() {
if e.kind() != std::io::ErrorKind::BrokenPipe {
return Err(miette::miette!("cannot flush stdout: {e}"));
}
}
Ok(())
}
fn print_diff(rendered: &str) -> Result<()> {
if rendered.is_empty() {
return Ok(());
}
write_stdout(rendered)
}
#[cfg(test)]
mod tests {
use super::*;
use mds::MdsError;
#[test]
fn ensure_existing_mds_file_accepts_existing_mds() {
let dir = tempfile::tempdir().unwrap();
let p = dir.path().join("foo.mds");
std::fs::write(&p, "").unwrap();
assert!(
ensure_existing_mds_file(&p).is_ok(),
"existing .mds file must pass"
);
}
#[test]
fn ensure_existing_mds_file_rejects_non_mds_extension() {
let dir = tempfile::tempdir().unwrap();
let p = dir.path().join("foo.txt");
std::fs::write(&p, "").unwrap();
let err = ensure_existing_mds_file(&p).expect_err("existing .txt file must be rejected");
assert!(
matches!(err, MdsError::NotMdsFile { .. }),
"error must be NotMdsFile for existing .txt; got: {err:?}"
);
}
#[test]
fn ensure_existing_mds_file_rejects_missing_path() {
let dir = tempfile::tempdir().unwrap();
let p = dir.path().join("nonexistent.mds");
let err = ensure_existing_mds_file(&p).expect_err("nonexistent file must be rejected");
assert!(
matches!(err, MdsError::FileNotFound { .. }),
"error must be FileNotFound for missing path; got: {err:?}"
);
}
#[test]
fn ensure_existing_mds_file_missing_non_mds_reports_not_found() {
let dir = tempfile::tempdir().unwrap();
let p = dir.path().join("nonexistent.txt");
let err = ensure_existing_mds_file(&p).expect_err("nonexistent .txt file must be rejected");
assert!(
matches!(err, MdsError::FileNotFound { .. }),
"must be FileNotFound (not NotMdsFile) for non-existent path; got: {err:?}"
);
}
#[test]
fn format_source_detects_no_change() {
let result = format_source_named("Hello!\n", None, "<source>").unwrap();
assert!(!result.changed);
assert_eq!(result.formatted, "Hello!\n");
}
#[test]
fn format_source_detects_change() {
let result =
format_source_named("Hello!\r\n\r\n\r\n\r\nBye.\r\n", None, "<source>").unwrap();
assert!(result.changed);
assert!(!result.formatted.contains('\r'));
}
}