Dough Git

clove/code4dyslexia

src/main.rs

back to src

// src/main.rs

mod adapter_protocol;

mod config;

mod discovery;

mod ecmascript_source;

mod go_source;

mod json_source;

mod language;

mod lua_source;

mod python_source;

mod rust_source;

mod terminal;

use std::env;
use std::ffi::{OsStr, OsString};
use std::fs;
use std::io::{self, IsTerminal, Write};
use std::path::Path;
use std::process::ExitCode;

use jpcl::{Object, StringifyOptions, Value};
use tempfile::NamedTempFile;

use crate::config::ConfigStore;
use crate::discovery::Discovery;
use crate::language::Diagnostic;
use crate::terminal::{Terminal, Tone};

const USAGE: &str = "Usage:
  c4d check [PATH ...]
  c4d format [PATH ...]
  c4d format --check [PATH ...]
  c4d config show [PATH] [--language LANGUAGE]
  c4d version";

#[derive(Clone, Copy, PartialEq, Eq)]
enum Mode {
    Check,
    DryRun,
    Write,
}

fn report(path: &Path, source: &str, issues: &[Diagnostic], terminal: &Terminal) {
    let mut line = 1;
    let mut line_start = 0;
    let mut breaks = source.match_indices('\n').peekable();

    for issue in issues {
        while let Some(&(offset, _)) = breaks.peek() {
            if offset >= issue.offset {
                break;
            }

            breaks.next();
            line += 1;
            line_start = offset + 1;
        }

        let column = source[line_start..issue.offset].chars().count() + 1;
        let tone = if matches!(issue.rule, "syntax" | "runtime") {
            Tone::Error
        } else {
            Tone::Notice
        };
        let rule = terminal.paint(tone, issue.rule);
        println!(
            "{}:{line}:{column} {} — {}",
            path.display(),
            rule,
            issue.message,
        );
    }
}

fn replace_source(path: &Path, original: &str, formatted: &str) -> io::Result<()> {
    let initial = path.symlink_metadata()?;

    if !initial.is_file() {
        return Err(io::Error::other("source is no longer a regular file"));
    }

    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;

        if initial.nlink() > 1 {
            return Err(io::Error::other("source has multiple hard links"));
        }
    }

    let directory = path.parent().expect("absolute file path");
    let mut temporary = NamedTempFile::new_in(directory)?;
    temporary.write_all(formatted.as_bytes())?;
    temporary.as_file().set_permissions(initial.permissions())?;
    temporary.as_file().sync_all()?;

    let current = path.symlink_metadata()?;

    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;

        if (current.dev(), current.ino(), current.nlink())
        != (initial.dev(), initial.ino(), initial.nlink())
        {
            return Err(io::Error::other("source changed during formatting"));
        }
    }

    if !current.is_file()
    || current.permissions() != initial.permissions()
    || fs::read(path)? != original.as_bytes()
    {
        return Err(io::Error::other("source changed during formatting"));
    }

    temporary.persist(path)?;
    Ok(())
}

fn inspect(
    path: &Path,
    shown: &Path,
    cwd: &Path,
    config: &mut ConfigStore,
    mode: Mode,
) -> Result<Option<(u8, Terminal)>, String> {
    let language = language::detect(path).expect("discovered language");
    let bytes = fs::read(path).map_err(|error| error.to_string())?;
    let source = match std::str::from_utf8(&bytes) {
        Ok(source) if !bytes.contains(&0) => source,
        _ => {
            eprintln!("{}: skipped (binary or non-UTF-8 file)", shown.display());
            return Ok(None);
        }
    };

    let project = config.project(path.parent().expect("absolute file path"))?;
    let relative_path = project
    .as_deref()
    .and_then(|root| path.strip_prefix(root).ok())
    .or_else(|| path.strip_prefix(cwd).ok())
    .unwrap_or_else(|| Path::new(path.file_name().expect("discovered filename")));
    let header_path = relative_path
    .iter()
    .map(|part| {
        part.to_string_lossy()
        .replace('\\', "\\\\")
        .replace('\r', "\\r")
        .replace('\n', "\\n")
        })
    .collect::<Vec<_>>()
    .join("/");

    if (language.generated_header)(source, &header_path) {
        eprintln!("{}: skipped (generated header)", shown.display());
        return Ok(None);
    }

    let settings = config.settings(project.as_deref(), Some(language.id));
    let terminal = settings.theme().stdout();
    let analysis = match (language.analyze)(source, &header_path, settings, mode == Mode::Check) {
        Ok(result) => result,
        Err(issue) => {
            report(shown, source, &[issue], &terminal);
            return Ok(Some((2, terminal)));
        }
    };

    let status = match mode {
        Mode::Check if !analysis.issues.is_empty() => {
            report(shown, source, &analysis.issues, &terminal);
            1
        }
        Mode::DryRun if analysis.formatted != source => {
            println!(
                "{}: {}",
                shown.display(),
                terminal.paint(Tone::Notice, "would format")
            );
            1
        }
        Mode::Write if analysis.formatted != source => {
            replace_source(path, source, &analysis.formatted).map_err(|error| error.to_string())?;
            println!(
                "{}: {}",
                shown.display(),
                terminal.paint(Tone::Success, "formatted")
            );
            0
        }
        _ => 0,
    };
    Ok(Some((status, terminal)))
}

fn show_config(arguments: &[OsString], discovery: &Discovery) -> Result<u8, String> {
    let mut iter = arguments.iter();
    let mut language = None;
    let mut input = None;

    while let Some(argument) = iter.next() {
        if argument == "--language" && language.is_none() {
            language = iter.next().and_then(|value| value.to_str());

            if !language.is_some_and(config::language_id) {
                return Err("expected a lowercase language identifier after --language".into());
            }
        } else if !argument.to_string_lossy().starts_with('-') && input.is_none() {
            input = Some(Path::new(argument));
        } else {
            return Err(format!(
                "unexpected argument {}",
                argument.to_string_lossy()
            ));
        }
    }

    let Some(path) = discovery.explicit(input.unwrap_or(Path::new(".")))? else {
        return Ok(2);
    };
    let directory = if path.is_dir() {
        &path
    } else {
        path.parent().unwrap_or(&path)
    };
    let home = env::home_dir();

    if let Some(home) = &home {
        config::initialize_global(home)?;
    }

    let mut config = ConfigStore::load(home.as_deref())?;
    let project = config.project(directory)?;
    let root = project.as_deref();
    let effective = config.settings(root, language);
    let mut document = effective.document();
    let mut origins = String::from("\n~~ Setting origins\n");
    effective.write_origins(&mut origins, "");

    if language.is_none() {
        let mut overrides = Object::new();
        let mut ids = config.override_languages(root);
        ids.extend(
            language::LANGUAGES
            .iter()
            .map(|language| language.id.to_owned()),
        );

        for id in ids {
            let effective = config.settings(root, Some(&id));
            overrides.insert(&id, Value::Object(effective.document()));
            effective.write_origins(&mut origins, &format!("overrides.{id}."));
        }

        document.insert("overrides", Value::Object(overrides));
    }

    print!(
        "{}{origins}",
        jpcl::stringify(&document, &StringifyOptions::default())
    );
    Ok(0)
}

fn run(arguments: Vec<OsString>) -> Result<u8, String> {
    let command = arguments.first().and_then(|arg| arg.to_str());

    if matches!(command, Some("-h" | "--help")) {
        println!("{USAGE}");
        return Ok(0);
    }

    if matches!(command, Some("version" | "-V" | "--version")) {
        println!("c4d {}", env!("CARGO_PKG_VERSION"));
        return Ok(0);
    }

    let working_directory = env::current_dir().map_err(|error| error.to_string())?;
    let mut discovery = Discovery::new(working_directory.clone());

    if command == Some("config") && arguments.get(1) == Some(&OsString::from("show")) {
        return show_config(&arguments[2..], &discovery);
    }

    let mut mode = match command {
        Some("check") => Mode::Check,
        Some("format") => Mode::Write,
        _ => return Err(USAGE.into()),
    };
    let mut positional_only = false;
    let mut inputs = Vec::new();

    for argument in &arguments[1..] {
        if !positional_only && argument == "--" {
            positional_only = true;
        } else if !positional_only && argument == "--check" && mode == Mode::Write {
            mode = Mode::DryRun;
        } else if !positional_only && argument.to_string_lossy().starts_with('-') {
            return Err(format!(
                "unexpected argument {}",
                argument.to_string_lossy()
            ));
        } else {
            inputs.push(argument.as_os_str());
        }
    }

    if inputs.is_empty() {
        inputs.push(OsStr::new("."));
    }

    let mut config = ConfigStore::load(env::home_dir().as_deref())?;
    let mut status = 0;
    let mut scanned = 0;
    let mut summary_terminal = None;

    for input in inputs {
        let path = match discovery.explicit(Path::new(input)) {
            Ok(Some(path)) => path,
            Ok(None) => continue,
            Err(error) => {
                eprintln!("{error}");
                status = 2;
                continue;
            }
        };
        let directory = if path.is_dir() {
            &path
        } else {
            path.parent().unwrap_or(&path)
        };
        // The nearest config is still resolved per file to support nested projects.
        let project = match config.project(directory) {
            Ok(project) => project,
            Err(error) => {
                eprintln!("{error}");
                status = 2;
                continue;
            }
        };
        let result = discovery.scan(&path, project.as_deref(), |path| {
            let shown = path.strip_prefix(&working_directory).unwrap_or(path);

            match inspect(path, shown, &working_directory, &mut config, mode) {
                Ok(Some((result, terminal))) => {
                    status = status.max(result);
                    scanned += 1;
                    summary_terminal.get_or_insert(terminal);
                }
                Ok(None) => {}
                Err(error) => {
                    eprintln!("{}: {error}", shown.display());
                    status = 2;
                }
            }
            });

        if let Err(error) = result {
            eprintln!("{error}");
            status = 2;
        }
    }

    if status == 0 && io::stdout().is_terminal() {
        if let Some(terminal) = summary_terminal {
            let label = match mode {
                Mode::Check => "No issues found",
                Mode::DryRun => "Formatting is up to date",
                Mode::Write => "Formatting complete",
            };
            let noun = if scanned == 1 { "file" } else { "files" };
            println!(
                "{} ({scanned} {noun} checked).",
                terminal.paint(Tone::Success, label)
            );
        } else {
            println!("No supported source files to check.");
        }
    }

    Ok(status)
}

fn main() -> ExitCode {
    match run(env::args_os().skip(1).collect()) {
        Ok(status) => ExitCode::from(status),
        Err(error) => {
            eprintln!("{error}");
            ExitCode::from(2)
        }
    }
}