use std::panic::AssertUnwindSafe;
use std::path::{Path, PathBuf};
use mds::effective_parent;
use miette::Result;
use crate::build::{ensure_existing_mds_file, load_config, read_stdin, resolve_input};
use crate::output::{
catch_compile, collect_mds_files_detailed, render_unified_diff, safe_path, stdout_failure,
walked_pin, write_stdout, Panicked, RootPaths, StdoutOutcome, WriteTarget,
};
use crate::write::{
read_stamped, replace_if_unchanged, replace_owing_sync, DirectorySyncs, Durability, Renamed,
Rewritten, Synced,
};
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 {
crate::output::ewriteln!("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() {
let canonical =
crate::input::resolve_directory_argument(&input).map_err(miette::Error::from)?;
return run_fmt_directory(&input, &canonical, flags);
}
ensure_existing_mds_file(&input).map_err(miette::Error::from)?;
run_fmt_file(&input, flags)
}
fn read_source_file(path: &Path, pin: Option<mds::EntryPin>) -> Result<String> {
crate::lint::read_source_file(path, pin).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 = read_stdin()?;
let result = format_source_named(&source, None, STDIN_DISPLAY_LABEL)?;
if diff {
let rendered = render_unified_diff(&source, &result.formatted, STDIN_DISPLAY_LABEL);
write_stdout(rendered.as_bytes()).into_batch_result()?;
} else if !check {
write_stdout(result.formatted.as_bytes()).into_batch_result()?;
}
if check && result.changed {
if !quiet {
crate::output::ewriteln!("Would reformat: {STDIN_DISPLAY_LABEL}");
}
crate::output::exit(1);
}
Ok(())
}
fn run_fmt_file(path: &Path, flags: FmtFlags) -> Result<()> {
let FmtFlags { check, diff, quiet } = flags;
let source = read_source_file(path, None)?;
let base_dir = Some(effective_parent(path));
let file_name = safe_path(path);
let result = format_source_named(&source, base_dir, &file_name)?;
if diff && result.changed {
let rendered = render_unified_diff(&source, &result.formatted, &file_name);
write_stdout(rendered.as_bytes()).into_batch_result()?;
}
let read_only = check || diff;
if !read_only {
if result.changed {
let read = read_stamped(&WriteTarget::as_typed(path.to_path_buf()), &source)?;
match replace_if_unchanged(read, &result.formatted, Durability::Fsync)? {
Rewritten::Done => {
if !quiet {
crate::output::ewriteln!("Formatted: {}", crate::output::safe_path(path));
}
}
Rewritten::NotSynced(e) => return Err(e.into()),
}
} else if !quiet {
crate::output::ewriteln!("Unchanged: {}", crate::output::safe_path(path));
}
return Ok(());
}
if check {
if result.changed {
if !quiet {
crate::output::ewriteln!("Would reformat: {}", crate::output::safe_path(path));
}
crate::output::exit(1);
}
if !quiet {
crate::output::ewriteln!("Unchanged: {}", crate::output::safe_path(path));
}
}
Ok(())
}
enum FileOutcome {
Formatted(Renamed),
Unchanged,
WouldChange,
NoChange,
Failed,
}
fn format_one_file(
root: &Path,
file: &Path,
pin: Result<mds::EntryPin>,
flags: FmtFlags,
) -> FileOutcome {
let FmtFlags { check, diff, .. } = flags;
let file_name = safe_path(file);
let source = match pin.and_then(|pin| read_source_file(file, Some(pin))) {
Ok(s) => s,
Err(e) => {
crate::output::eprint_file_failure(e);
return FileOutcome::Failed;
}
};
let base_dir = Some(effective_parent(file));
let formatted = catch_compile(
file,
AssertUnwindSafe(|| format_source_named(&source, base_dir, &file_name)),
);
let result = match formatted {
Ok(Ok(r)) => r,
Ok(Err(e)) => {
crate::output::eprint_file_failure(e);
return FileOutcome::Failed;
}
Err(Panicked) => return FileOutcome::Failed,
};
if diff && result.changed {
let rendered = render_unified_diff(&source, &result.formatted, &file_name);
match write_stdout(rendered.as_bytes()) {
StdoutOutcome::Written | StdoutOutcome::Closed => {}
StdoutOutcome::Failed(e) => {
crate::output::eprint_io_failure(stdout_failure(&e));
return FileOutcome::Failed;
}
StdoutOutcome::FailedAgain => 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 {
let target = WriteTarget::walked_below(RootPaths::as_typed(root), file);
match read_stamped(&target, &source)
.and_then(|read| replace_owing_sync(read, &result.formatted))
{
Ok(renamed) => FileOutcome::Formatted(renamed),
Err(e) => {
crate::output::eprint_io_failure(e);
FileOutcome::Failed
}
}
}
}
fn run_fmt_directory(dir: &Path, canonical_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 {
crate::output::ewriteln!(
"{} .mds file(s) found but all are under default-excluded directories \
(hidden dirs, node_modules); nothing was formatted",
walk.excluded_by_default
);
crate::output::exit(1);
}
crate::output::ewriteln!(
"no .mds files found in {}; nothing was formatted",
crate::output::safe_path(dir)
);
crate::output::exit(1);
}
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;
let mut syncs = DirectorySyncs::new(files.iter().map(PathBuf::as_path));
for (place, file) in files.iter().enumerate() {
let pin = walked_pin(&walk, file, dir, canonical_dir).map_err(miette::Error::from);
let landed = match format_one_file(dir, file, pin, flags) {
FileOutcome::Formatted(renamed) => {
changed_count += 1;
syncs.landed(place, renamed, file.as_path())
}
FileOutcome::WouldChange => {
changed_count += 1;
None
}
FileOutcome::Unchanged | FileOutcome::NoChange => {
unchanged_count += 1;
None
}
FileOutcome::Failed => {
fail_count += 1;
None
}
};
for synced in landed.into_iter().flatten() {
show_synced(synced, flags.quiet);
}
for synced in syncs.past(place).into_iter().flatten() {
show_synced(synced, flags.quiet);
}
}
if read_only {
if !flags.quiet || fail_count > 0 {
crate::output::ewriteln!(
"{changed_count} would reformat, {unchanged_count} unchanged, {fail_count} failed"
);
}
} else if !flags.quiet || fail_count > 0 {
crate::output::ewriteln!(
"{changed_count} formatted, {unchanged_count} unchanged, {fail_count} failed"
);
}
if fail_count > 0 || (flags.check && changed_count > 0) {
crate::output::exit(1);
}
Ok(())
}
fn show_synced(synced: Synced<&Path>, quiet: bool) {
match synced {
Synced::Durable(file) => {
if !quiet {
crate::output::ewriteln!("Formatted: {}", crate::output::safe_path(file));
}
}
Synced::NotSynced(_, e) => crate::output::eprint_io_failure(e),
}
}
#[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'));
}
#[cfg(unix)]
#[test]
fn a_directory_run_syncs_each_directory_once() {
use crate::write::sync_probe::directory_syncs;
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
let src = root.join("src");
std::fs::create_dir_all(src.join("sub")).unwrap();
let files = ["a.mds", "b.mds", "sub/c.mds", "z.mds"].map(|file| src.join(file));
let unformatted = || {
for file in &files {
std::fs::write(file, "Alpha\r\n").unwrap();
}
};
let flags = FmtFlags {
check: false,
diff: false,
quiet: true,
};
unformatted();
let before = directory_syncs();
run_fmt_directory(&src, &src, flags).unwrap();
assert_eq!(
directory_syncs() - before,
2,
"one sync for src and one for src/sub"
);
for file in &files {
assert_eq!(
std::fs::read_to_string(file).unwrap(),
"Alpha\n",
"{file:?}"
);
}
unformatted();
let before = directory_syncs();
for file in &files {
run_fmt_file(file, flags).unwrap();
}
assert_eq!(
directory_syncs() - before,
files.len(),
"control: a file argument's rewrite syncs its directory itself"
);
}
}