use std::collections::BTreeMap;
use std::fs;
use std::io::{self, IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::time::Duration;
use clap::{Parser as ClapParser, Subcommand};
use import_lint::{CheckedEntry, ExportInfo, FileModuleInfo, Provenance, extract_file};
use import_lint_cli::lsp::{self, LspOptions};
use import_lint_cli::output::{OutputFormat, RenderedDiagnostic};
use import_lint_cli::overlay::Overlays;
use import_lint_cli::report::{ReportOptions, build_report};
use import_lint_cli::runner::RunnerOptions;
use import_lint_cli::setup;
use import_lint_cli::source_type::{SUPPORTED_EXTENSIONS_MESSAGE, source_type_for_path};
use import_lint_cli::watch::{CycleOutcome, WatchSession, WatchSessionOptions, watch_loop};
use oxc_allocator::Allocator;
use oxc_parser::Parser as OxcParser;
use oxc_str::CompactStr;
use serde::Serialize;
mod init;
#[derive(ClapParser, Debug)]
#[command(name = "import-lint", version, about, long_about = None)]
struct Cli {
#[command(subcommand)]
command: Option<Command>,
paths: Vec<PathBuf>,
#[arg(long)]
config: Option<PathBuf>,
#[arg(long, value_enum, default_value_t = OutputFormat::Pretty)]
format: OutputFormat,
#[arg(long)]
threads: Option<usize>,
#[arg(long)]
tsconfig: Option<PathBuf>,
#[arg(long)]
report_unresolved: bool,
#[arg(long)]
quiet: bool,
#[arg(long)]
watch: bool,
#[arg(
long,
value_name = "INTERVAL_MS",
num_args = 0..=1,
default_missing_value = "500"
)]
watch_poll: Option<u64>,
}
#[derive(Subcommand, Debug)]
enum Command {
Inspect {
file: PathBuf,
},
Graph {
paths: Vec<PathBuf>,
#[arg(long)]
tsconfig: Option<PathBuf>,
},
Lsp,
Init {
#[arg(long)]
force: bool,
},
}
fn main() -> ExitCode {
let cli = Cli::parse();
match cli.command {
Some(Command::Inspect { file }) => inspect(&file),
Some(Command::Graph { paths, tsconfig }) => graph(paths, tsconfig),
Some(Command::Lsp) => lsp_command(),
Some(Command::Init { force }) => init_command(force),
None if cli.watch || cli.watch_poll.is_some() => watch_command(cli),
None => lint(cli),
}
}
fn lint(cli: Cli) -> ExitCode {
let cwd = match std::env::current_dir() {
Ok(dir) => dir,
Err(err) => {
eprintln!("import-lint: cannot determine current directory: {err}");
return ExitCode::from(2);
}
};
let loaded = match setup::load_config(cli.config.as_deref(), &cwd) {
Ok(loaded) => loaded,
Err(err) => {
eprintln!("import-lint: {err}");
return ExitCode::from(2);
}
};
let config = loaded.config;
let project_root = loaded.project_root;
let roots = setup::compute_roots(&cli.paths, &config, &project_root);
let tsconfig = setup::compute_tsconfig(cli.tsconfig.as_deref(), &config, &project_root);
let self_reference_mode = setup::compute_self_reference_mode(&config);
if let Some(threads) = cli.threads {
let _ = rayon::ThreadPoolBuilder::new()
.num_threads(threads)
.build_global();
}
let runner_options = RunnerOptions {
roots,
project_root: project_root.clone(),
tsconfig,
self_reference_mode,
exclude: config.exclude.clone(),
};
let module_graph = import_lint_cli::run(&runner_options);
let report = build_report(
&module_graph,
&config,
&project_root,
&ReportOptions {
report_unresolved: cli.report_unresolved,
quiet: cli.quiet,
},
&Overlays::default(),
);
let stdout = io::stdout();
let colors = cli.format == OutputFormat::Pretty && stdout.is_terminal();
let mut handle = stdout.lock();
let linted_files: Vec<PathBuf> = module_graph.lint_targets.iter().cloned().collect();
let render_result = cli.format.render(
&mut handle,
&report.diagnostics,
&cwd,
colors,
&linted_files,
);
if let Err(err) = render_result.and_then(|()| handle.flush()) {
eprintln!("import-lint: failed to write output: {err}");
return ExitCode::from(2);
}
if report.has_error {
ExitCode::from(1)
} else {
ExitCode::SUCCESS
}
}
fn watch_command(cli: Cli) -> ExitCode {
let cwd = match std::env::current_dir() {
Ok(dir) => dir,
Err(err) => {
eprintln!("import-lint: cannot determine current directory: {err}");
return ExitCode::from(2);
}
};
if let Some(threads) = cli.threads {
let _ = rayon::ThreadPoolBuilder::new()
.num_threads(threads)
.build_global();
}
let format = cli.format;
let poll_interval = cli.watch_poll.map(Duration::from_millis);
let session_options = WatchSessionOptions {
cli_paths: cli.paths.clone(),
explicit_config: cli.config.clone(),
cli_tsconfig: cli.tsconfig.clone(),
report_unresolved: cli.report_unresolved,
quiet: cli.quiet,
cwd: cwd.clone(),
};
let mut session = match WatchSession::new(session_options) {
Ok(session) => session,
Err(err) => {
eprintln!("import-lint: {err}");
return ExitCode::from(2);
}
};
let tty = io::stdout().is_terminal();
render_watch_state(session.last_diagnostics(), None, format, &cwd, tty);
let shutdown = Arc::new(AtomicBool::new(false));
let debounce = Duration::from_millis(100);
let result = watch_loop(
&mut session,
debounce,
poll_interval,
&shutdown,
|outcome| {
render_watch_cycle(outcome, format, &cwd, tty);
},
);
if let Err(err) = result {
eprintln!("import-lint: watch mode failed to start: {err}");
return ExitCode::from(2);
}
ExitCode::SUCCESS
}
fn lsp_command() -> ExitCode {
match lsp::run_stdio(LspOptions::default()) {
Ok(()) => ExitCode::SUCCESS,
Err(err) => {
eprintln!("import-lint: lsp server failed: {err}");
ExitCode::from(2)
}
}
}
fn init_command(force: bool) -> ExitCode {
let cwd = match std::env::current_dir() {
Ok(dir) => dir,
Err(err) => {
eprintln!("import-lint: cannot determine current directory: {err}");
return ExitCode::from(2);
}
};
match init::run_init(&cwd, force) {
Ok(()) => ExitCode::SUCCESS,
Err(err) => {
eprintln!("import-lint: {err}");
ExitCode::from(2)
}
}
}
fn render_watch_cycle(outcome: &CycleOutcome, format: OutputFormat, cwd: &Path, tty: bool) {
let status = watch_status_line(outcome);
render_watch_state(
&outcome.diagnostics,
Some((&outcome.linted_files, &status)),
format,
cwd,
tty,
);
}
fn watch_status_line(outcome: &CycleOutcome) -> String {
let error_count = outcome
.diagnostics
.iter()
.filter(|d| d.severity == import_lint_cli::output::OutputSeverity::Error)
.count();
let warning_count = outcome.diagnostics.len() - error_count;
let millis = outcome.duration.as_millis();
let tail = format!(
"rechecked {} file{} in {millis} ms (watching, Ctrl-C to exit)",
outcome.rechecked_files,
if outcome.rechecked_files == 1 {
""
} else {
"s"
}
);
if outcome.has_error || warning_count > 0 {
let total = outcome.diagnostics.len();
format!(
"\u{2716} {total} problem{} ({error_count} error{}, {warning_count} warning{}) \u{2014} {tail}",
if total == 1 { "" } else { "s" },
if error_count == 1 { "" } else { "s" },
if warning_count == 1 { "" } else { "s" },
)
} else {
format!("\u{2713} no problems \u{2014} {tail}")
}
}
fn render_watch_state(
diagnostics: &[RenderedDiagnostic],
status: Option<(&[PathBuf], &str)>,
format: OutputFormat,
cwd: &Path,
tty: bool,
) {
let colors = tty && format == OutputFormat::Pretty;
let clear = tty && format == OutputFormat::Pretty && status.is_some();
let linted_files: &[PathBuf] = status.map(|(files, _)| files).unwrap_or(&[]);
let stdout = io::stdout();
let mut handle = stdout.lock();
if clear {
let _ = write!(handle, "\x1b[2J\x1b[H");
}
let _ = format.render(&mut handle, diagnostics, cwd, colors, linted_files);
if let Some((_, status_line)) = status {
let styled = if colors {
format!("\x1b[1m{status_line}\x1b[0m")
} else {
status_line.to_string()
};
let _ = writeln!(handle, "{styled}");
}
let _ = handle.flush();
}
fn inspect(file: &Path) -> ExitCode {
let Some(source_type) = source_type_for_path(file) else {
eprintln!(
"import-lint: {}: unrecognized file extension ({SUPPORTED_EXTENSIONS_MESSAGE})",
file.display()
);
return ExitCode::from(2);
};
let source_text = match fs::read_to_string(file) {
Ok(text) => text,
Err(err) => {
eprintln!("import-lint: cannot read {}: {err}", file.display());
return ExitCode::from(2);
}
};
let preflight_allocator = Allocator::default();
let preflight = OxcParser::new(&preflight_allocator, &source_text, source_type).parse();
if preflight.panicked || preflight.diagnostics.has_errors() {
eprintln!("import-lint: failed to parse {}:", file.display());
for diagnostic in preflight.diagnostics.errors() {
eprintln!(" {diagnostic}");
}
return ExitCode::from(2);
}
let allocator = Allocator::default();
let info = extract_file(file, &source_text, source_type, &allocator);
match serde_json::to_string_pretty(&InspectOutput::from(&info)) {
Ok(json) => {
println!("{json}");
ExitCode::SUCCESS
}
Err(err) => {
eprintln!("import-lint: failed to serialize extraction output: {err}");
ExitCode::from(2)
}
}
}
#[derive(Serialize)]
struct InspectOutput<'a> {
path: &'a Path,
checked_entries: &'a [CheckedEntry],
export_table: BTreeMap<&'a str, &'a ExportInfo>,
star_exports: &'a [CompactStr],
ambient_modules: &'a [CompactStr],
specifiers: &'a [CompactStr],
}
impl<'a> From<&'a FileModuleInfo> for InspectOutput<'a> {
fn from(info: &'a FileModuleInfo) -> Self {
Self {
path: &info.path,
checked_entries: &info.checked_entries,
export_table: info
.export_table
.iter()
.map(|(k, v)| (k.as_str(), v))
.collect(),
star_exports: &info.star_exports,
ambient_modules: &info.ambient_modules,
specifiers: &info.specifiers,
}
}
}
fn graph(paths: Vec<PathBuf>, tsconfig: Option<PathBuf>) -> ExitCode {
let roots = if paths.is_empty() {
vec![PathBuf::from(".")]
} else {
paths
};
let project_root = match std::env::current_dir() {
Ok(dir) => dir,
Err(err) => {
eprintln!("import-lint: cannot determine current directory: {err}");
return ExitCode::from(2);
}
};
let tsconfig = tsconfig.or_else(|| RunnerOptions::default_tsconfig(&project_root));
let options = RunnerOptions {
roots,
project_root,
tsconfig,
self_reference_mode: import_lint::SelfReferenceMode::default(),
exclude: Vec::new(),
};
let module_graph = import_lint_cli::run(&options);
match serde_json::to_string_pretty(&GraphOutput::from(&module_graph)) {
Ok(json) => {
println!("{json}");
ExitCode::SUCCESS
}
Err(err) => {
eprintln!("import-lint: failed to serialize graph output: {err}");
ExitCode::from(2)
}
}
}
#[derive(Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum ResolutionOutput {
Internal { path: String },
External,
Unresolved,
}
impl From<&Provenance> for ResolutionOutput {
fn from(provenance: &Provenance) -> Self {
match provenance {
Provenance::Internal(path) => ResolutionOutput::Internal {
path: path.to_string_lossy().into_owned(),
},
Provenance::External => ResolutionOutput::External,
Provenance::Unresolved => ResolutionOutput::Unresolved,
}
}
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct FileOutput {
lint_target: bool,
resolutions: BTreeMap<String, ResolutionOutput>,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Summary {
files: usize,
lint_targets: usize,
internal: usize,
external: usize,
unresolved: usize,
}
#[derive(Serialize)]
struct GraphOutput {
files: BTreeMap<String, FileOutput>,
summary: Summary,
}
impl From<&import_lint::ModuleGraph> for GraphOutput {
fn from(graph: &import_lint::ModuleGraph) -> Self {
let mut files = BTreeMap::new();
let mut internal = 0;
let mut external = 0;
let mut unresolved = 0;
for (path, file) in &graph.files {
let mut resolutions = BTreeMap::new();
for specifier in &file.specifiers {
if let Some(provenance) = graph.resolution(path, specifier) {
resolutions.insert(specifier.to_string(), ResolutionOutput::from(provenance));
match provenance {
Provenance::Internal(_) => internal += 1,
Provenance::External => external += 1,
Provenance::Unresolved => unresolved += 1,
}
}
}
files.insert(
path.to_string_lossy().into_owned(),
FileOutput {
lint_target: graph.lint_targets.contains(path),
resolutions,
},
);
}
GraphOutput {
summary: Summary {
files: graph.files.len(),
lint_targets: graph.lint_targets.len(),
internal,
external,
unresolved,
},
files,
}
}
}