Skip to content

Offline, privacy-first grammar checker. Fast, open-source, Rust-powered

refactor(cli): refactor `Input` and adjacent code (#2412)

Steve Kurch4123b44fbcc8
diff --git a/Cargo.lock b/Cargo.lock
index f0ec6fbfd..c82db9fcd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1910,6 +1910,18 @@ dependencies = [
"syn",
]
+[[package]]
+name = "enum_dispatch"
+version = "0.3.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa18ce2bc66555b3218614519ac839ddb759a7d6720732f979ef8d13be147ecd"
+dependencies = [
+ "once_cell",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
[[package]]
name = "enumset"
version = "1.1.10"
@@ -2695,6 +2707,7 @@ dependencies = [
"ariadne",
"clap",
"dirs 6.0.0",
+ "enum_dispatch",
"harper-asciidoc",
"harper-comments",
"harper-core",
@@ -2709,6 +2722,7 @@ dependencies = [
"serde",
"serde_json",
"strum",
+ "strum_macros",
]
[[package]]
diff --git a/harper-cli/Cargo.toml b/harper-cli/Cargo.toml
index 4da07c05b..2c5191e28 100644
--- a/harper-cli/Cargo.toml
+++ b/harper-cli/Cargo.toml
@@ -23,7 +23,9 @@ rayon = "1.11.0"
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.148"
strum = "0.27.2"
+strum_macros = "0.27.2"
harper-ink = { version = "1.0.0", path = "../harper-ink" }
+enum_dispatch = "0.3.13"
[features]
default = []
diff --git a/harper-cli/src/input.rs b/harper-cli/src/input.rs
index 0b0614857..46ec1dc24 100644
--- a/harper-cli/src/input.rs
+++ b/harper-cli/src/input.rs
@@ -1,90 +1,60 @@
-use std::{borrow::Cow, io::Read, path::PathBuf};
+use std::borrow::Cow;
-use harper_core::spell::Dictionary;
-use harper_core::{
- Document,
- parsers::{MarkdownOptions, PlainEnglish},
-};
+use enum_dispatch::enum_dispatch;
+use strum_macros::EnumTryAs;
-/// Represents an input/source passed via the command line. For example, this can be a file, or
-/// text passed via the command line directly.
-#[derive(Clone, Debug)]
-pub(super) enum Input {
- /// File (path) input.
- File(PathBuf),
- /// Directory (path) input.
- Dir(PathBuf),
- /// Direct text input, via the command line.
- Text(String),
- /// Standard input (stdin).
- Stdin(String),
-}
-impl Input {
- /// Loads the contained file/string into a conventional format. Returns a `Result` containing
- /// a tuple of a `Document` and its corresponding source text as a string.
- pub(super) fn load(
- &self,
- batch_mode: bool,
- markdown_options: MarkdownOptions,
- dictionary: &impl Dictionary,
- ) -> anyhow::Result<(Option<Document>, String)> {
- match self {
- Input::File(file) => super::load_file(
- file,
- Some(&self.get_identifier()),
- batch_mode,
- markdown_options,
- dictionary,
- ),
- Input::Dir(dir) => Ok((None, dir.display().to_string())),
- Input::Text(s) => Ok((Some(Document::new(s, &PlainEnglish, dictionary)), s.clone())),
- Input::Stdin(s) => Ok((Some(Document::new(s, &PlainEnglish, dictionary)), s.clone())),
- }
- }
+pub mod single_input;
+use single_input::SingleInput;
+pub mod multi_input;
+use multi_input::MultiInput;
+
+/// The general trait implemented by all input types.
+#[enum_dispatch]
+pub(crate) trait InputTrait {
/// Gets a human-readable identifier for the input. For example, this can be a filename, or
/// simply the string `"<input>"`.
- #[must_use]
- pub(super) fn get_identifier(&'_ self) -> Cow<'_, str> {
- match self {
- Input::File(file) => file
- .file_name()
- .map_or(Cow::from("<file>"), |file_name| file_name.to_string_lossy()),
- Input::Dir(dir) => dir
- .file_name()
- .map_or(Cow::from("<dir>"), |dir_name| dir_name.to_string_lossy()),
- Input::Text(_) => Cow::from("<text>"),
- Input::Stdin(_) => Cow::from("<stdin>"),
- }
- }
+ fn get_identifier(&self) -> Cow<'_, str>;
+}
- /// Tries to construct an `Input` by reading standard input. This will fail if the standard
- /// input cannot be read.
- pub(super) fn try_from_stdin() -> anyhow::Result<Self> {
- let mut buf = String::new();
- std::io::stdin().lock().read_to_string(&mut buf)?;
- Ok(Self::Stdin(buf))
- }
+/// Represents an input/source passed via the command line. For example, this can be a file,
+/// a directory, or text passed via the command line directly.
+#[enum_dispatch(InputTrait)]
+#[derive(Clone, EnumTryAs)]
+pub(crate) enum AnyInput {
+ /// An input of a single source. For instance, a specific file, or input from standard input.
+ Single(SingleInput),
+ /// An input of multiple sources. For instance, a path to a directory.
+ Multi(MultiInput),
}
+
// This allows this type to be directly used with clap as an argument.
// https://docs.rs/clap/latest/clap/macro.value_parser.html
-impl From<String> for Input {
- /// Converts the given string into an `Input`. `Input` is automatically set to the correct variant
- /// depending on whether `input_string` is a valid file path or not.
+impl From<String> for AnyInput {
+ /// Converts the given string into an `Input` by trying to detect the input type.
fn from(input_string: String) -> Self {
- if let Ok(metadata) = std::fs::metadata(&input_string)
- && metadata.is_file()
- {
- // Input is a valid file path.
- Self::File(input_string.into())
- } else if let Ok(metadata) = std::fs::metadata(&input_string)
- && metadata.is_dir()
- {
- // Input is a valid directory path.
- Self::Dir(input_string.into())
+ if let Ok(multi_input) = MultiInput::try_parse_string(&input_string) {
+ Self::Multi(multi_input)
} else {
- // Input is not a valid file path, we assume it's intended to be a string.
- Self::Text(input_string)
+ Self::Single(SingleInput::parse_string(&input_string))
}
}
}
+
+// This allows this type to be directly used with clap as an argument.
+// It can be used in place of AnyInput if the command should only accept single-inputs
+// (e.g. a file).
+impl From<String> for SingleInput {
+ fn from(input_string: String) -> Self {
+ SingleInput::parse_string(&input_string)
+ }
+}
+
+// This allows this type to be directly used with clap as an argument.
+// It can be used in place of AnyInput if the command should only accept multi-inputs,
+// (e.g. directories).
+impl From<String> for MultiInput {
+ fn from(input_string: String) -> Self {
+ MultiInput::try_parse_string(&input_string).unwrap()
+ }
+}
diff --git a/harper-cli/src/input/multi_input.rs b/harper-cli/src/input/multi_input.rs
new file mode 100644
index 000000000..add9e83f3
--- /dev/null
+++ b/harper-cli/src/input/multi_input.rs
@@ -0,0 +1,77 @@
+use std::{borrow::Cow, path::PathBuf};
+
+use enum_dispatch::enum_dispatch;
+use strum_macros::EnumTryAs;
+
+use crate::input::single_input::{FileInput, SingleInput};
+
+use super::InputTrait;
+
+#[enum_dispatch]
+pub(crate) trait MultiInputTrait: InputTrait {
+ /// Get an iterator of [`SingleInput`] from this `MultiInput`.
+ ///
+ /// For instance, if this is a directory input, the returned inputs might correspond to the
+ /// files inside that directory.
+ #[allow(dead_code)]
+ fn iter_inputs(&self) -> anyhow::Result<impl Iterator<Item = SingleInput>>;
+}
+
+#[derive(Clone, EnumTryAs)]
+#[enum_dispatch(MultiInputTrait, InputTrait)]
+pub(crate) enum MultiInput {
+ /// A directory.
+ Dir(DirInput),
+}
+impl MultiInput {
+ /// Try to parse a `MultiInput` from the provided string. This might fail if the provided
+ /// string cannot be parsed as a supported `MultiInput`.
+ pub(crate) fn try_parse_string(input_string: &str) -> anyhow::Result<Self> {
+ let metadata = std::fs::metadata(input_string);
+ if metadata?.is_dir() {
+ // Input is a valid directory path.
+ Ok(Self::Dir(DirInput {
+ path: input_string.into(),
+ }))
+ } else {
+ anyhow::bail!(
+ "Unsupported input '{}' for {}",
+ input_string,
+ std::any::type_name::<Self>()
+ )
+ }
+ }
+}
+
+/// A directory.
+#[derive(Clone)]
+pub(crate) struct DirInput {
+ /// The path pointing to the directory.
+ path: PathBuf,
+}
+impl DirInput {
+ /// An iterator of the files inside the directory, as [`FileInput`].
+ pub(crate) fn iter_files(&self) -> anyhow::Result<impl Iterator<Item = FileInput>> {
+ Ok(std::fs::read_dir(&self.path)?.filter_map(|dir_entry| {
+ if let Ok(dir_entry) = dir_entry
+ && let Ok(file) = FileInput::try_from_path(&dir_entry.path())
+ {
+ Some(file)
+ } else {
+ None
+ }
+ }))
+ }
+}
+impl MultiInputTrait for DirInput {
+ fn iter_inputs(&self) -> anyhow::Result<impl Iterator<Item = SingleInput>> {
+ Ok(self.iter_files()?.map(|file| file.into()))
+ }
+}
+impl InputTrait for DirInput {
+ fn get_identifier(&self) -> Cow<'_, str> {
+ self.path
+ .file_name()
+ .map_or(Cow::from("<dir>"), |dir_name| dir_name.to_string_lossy())
+ }
+}
diff --git a/harper-cli/src/input/single_input.rs b/harper-cli/src/input/single_input.rs
new file mode 100644
index 000000000..d4f12ad3b
--- /dev/null
+++ b/harper-cli/src/input/single_input.rs
@@ -0,0 +1,192 @@
+use std::path::Path;
+use std::{borrow::Cow, io::Read, path::PathBuf};
+
+use enum_dispatch::enum_dispatch;
+use strum_macros::EnumTryAs;
+
+use harper_asciidoc::AsciidocParser;
+use harper_comments::CommentParser;
+use harper_core::parsers::{Markdown, OrgMode, Parser};
+use harper_core::spell::Dictionary;
+use harper_core::{
+ Document,
+ parsers::{MarkdownOptions, PlainEnglish},
+};
+use harper_ink::InkParser;
+use harper_literate_haskell::LiterateHaskellParser;
+use harper_python::PythonParser;
+
+use super::InputTrait;
+
+/// An input of a single source. This would not include a directory for instance, which may have
+/// multiple (file) sources.
+#[enum_dispatch]
+pub(crate) trait SingleInputTrait: InputTrait {
+ /// Loads the contained file/string into a conventional format. Returns a `Result` containing
+ /// a tuple of a `Document` and its corresponding source text as a string.
+ fn load(
+ &self,
+ markdown_options: MarkdownOptions,
+ dictionary: &dyn Dictionary,
+ ) -> anyhow::Result<(Document, Cow<'_, str>)> {
+ let text = self.get_content()?;
+ let parser = self.get_parser(markdown_options);
+ Ok((Document::new(&text, &parser, &dictionary), text))
+ }
+
+ /// The parser that should be used to parse this input.
+ fn get_parser(&self, _markdown_options: MarkdownOptions) -> Box<dyn Parser> {
+ Box::new(PlainEnglish)
+ }
+
+ /// Get/load the raw content of this input.
+ fn get_content(&self) -> anyhow::Result<Cow<'_, str>>;
+}
+
+#[derive(Clone, EnumTryAs)]
+#[enum_dispatch(SingleInputTrait, InputTrait)]
+pub(crate) enum SingleInput {
+ /// Read from a file.
+ File(FileInput),
+ /// Direct text input via the command line.
+ Text(TextInput),
+ /// Read from standard input.
+ Stdin(StdinInput),
+}
+impl SingleInput {
+ /// Parse a string into a [`SingleInput`], trying to automatically detect the input
+ /// type based on its contents.
+ ///
+ /// For instance, an `input_string` that corresponds to a valid filepath will be parsed as
+ /// a [`SingleInput::File`].
+ pub(crate) fn parse_string(input_string: &str) -> Self {
+ if let Ok(file) = FileInput::try_from_path(Path::new(input_string)) {
+ // Input is a valid filepath.
+ Self::File(file)
+ } else {
+ // Input is not a valid filepath, we assume it's intended to be a string.
+ Self::Text(TextInput {
+ text: input_string.to_owned(),
+ })
+ }
+ }
+}
+
+pub trait SingleInputOptionExt {
+ /// Returns the contained [`Some`] value if some, otherwise returns [`SingleInput::Stdin`].
+ fn unwrap_or_read_from_stdin(self) -> SingleInput;
+}
+impl SingleInputOptionExt for Option<SingleInput> {
+ fn unwrap_or_read_from_stdin(self) -> SingleInput {
+ self.unwrap_or_else(|| StdinInput.into())
+ }
+}
+
+/// File (path) input.
+#[derive(Clone)]
+pub(crate) struct FileInput {
+ path: PathBuf,
+}
+impl FileInput {
+ /// The path of the file.
+ pub(crate) fn path(&self) -> &PathBuf {
+ &self.path
+ }
+
+ /// Try to create a `FileInput` from the given path. If the path does not point to a valid
+ /// file, this will fail.
+ pub(crate) fn try_from_path(path: &Path) -> anyhow::Result<Self> {
+ let metadata = std::fs::metadata(path);
+ if metadata?.is_file() {
+ Ok(Self::from_path_unchecked(path))
+ } else {
+ anyhow::bail!(
+ "Failed to parse '{}' as {}",
+ path.to_string_lossy(),
+ std::any::type_name::<Self>()
+ )
+ }
+ }
+
+ /// Create a file input from the given path, without checking if that path points to a valid
+ /// file.
+ pub(crate) fn from_path_unchecked(path: &Path) -> Self {
+ Self {
+ path: path.to_owned(),
+ }
+ }
+}
+impl SingleInputTrait for FileInput {
+ /// Read content from the file.
+ fn get_content(&self) -> anyhow::Result<Cow<'_, str>> {
+ Ok(std::fs::read_to_string(&self.path)?.into())
+ }
+
+ /// Detect the parser that should be used for the given file.
+ fn get_parser(&self, _markdown_options: MarkdownOptions) -> Box<dyn Parser> {
+ match self.path.extension().map(|ext| ext.to_str().unwrap()) {
+ Some("md") | Some("markdown") => Box::new(Markdown::default()),
+ Some("ink") => Box::new(InkParser::default()),
+ Some("lhs") => Box::new(LiterateHaskellParser::new_markdown(
+ MarkdownOptions::default(),
+ )),
+ Some("org") => Box::new(OrgMode),
+ Some("typ") => Box::new(harper_typst::Typst),
+ Some("py") | Some("pyi") => Box::new(PythonParser::default()),
+ Some("adoc") | Some("asciidoc") => Box::new(AsciidocParser::default()),
+ Some("txt") => Box::new(PlainEnglish),
+ _ => {
+ if let Some(comment_parser) =
+ CommentParser::new_from_filename(&self.path, _markdown_options)
+ {
+ Box::new(comment_parser)
+ } else {
+ eprintln!(
+ "{}: Warning: Could not detect language ID; falling back to PlainEnglish parser.",
+ self.get_identifier()
+ );
+ Box::new(PlainEnglish)
+ }
+ }
+ }
+ }
+}
+impl InputTrait for FileInput {
+ fn get_identifier(&self) -> Cow<'_, str> {
+ self.path
+ .file_name()
+ .map_or(Cow::from("<file>"), |file_name| file_name.to_string_lossy())
+ }
+}
+
+/// Direct text input via the command line.
+#[derive(Clone)]
+pub(crate) struct TextInput {
+ text: String,
+}
+impl SingleInputTrait for TextInput {
+ fn get_content(&self) -> anyhow::Result<Cow<'_, str>> {
+ Ok(Cow::from(&self.text))
+ }
+}
+impl InputTrait for TextInput {
+ fn get_identifier(&self) -> Cow<'_, str> {
+ Cow::from("<text>")
+ }
+}
+
+/// Standard input (stdin).
+#[derive(Clone)]
+pub(crate) struct StdinInput;
+impl SingleInputTrait for StdinInput {
+ fn get_content(&self) -> anyhow::Result<Cow<'_, str>> {
+ let mut buf = String::new();
+ std::io::stdin().lock().read_to_string(&mut buf)?;
+ Ok(Cow::from(buf))
+ }
+}
+impl InputTrait for StdinInput {
+ fn get_identifier(&self) -> Cow<'_, str> {
+ Cow::from("<stdin>")
+ }
+}
diff --git a/harper-cli/src/lint.rs b/harper-cli/src/lint.rs
index 8576a4551..556e8d065 100644
--- a/harper-cli/src/lint.rs
+++ b/harper-cli/src/lint.rs
@@ -1,3 +1,4 @@
+use std::borrow::Cow;
use std::collections::BTreeMap;
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
@@ -14,7 +15,11 @@ use harper_core::{
{Dialect, DictWordMetadata, Document, Token, TokenKind, remove_overlaps_map},
};
-use crate::input::Input;
+use crate::input::{
+ AnyInput, InputTrait,
+ multi_input::MultiInput,
+ single_input::{SingleInput, SingleInputTrait, StdinInput},
+};
/// Sync version of harper-ls/src/dictionary_io@load_dict
fn load_dict(path: &Path) -> anyhow::Result<MutableDictionary> {
@@ -43,10 +48,10 @@ fn file_dict_name(path: &Path) -> PathBuf {
rewritten.into()
}
-pub struct LintOptions<'a> {
+pub struct LintOptions {
pub count: bool,
- pub ignore: &'a Option<Vec<String>>,
- pub only: &'a Option<Vec<String>>,
+ pub ignore: Option<Vec<String>>,
+ pub only: Option<Vec<String>>,
pub dialect: Dialect,
}
enum ReportStyle {
@@ -56,20 +61,16 @@ enum ReportStyle {
struct InputInfo<'a> {
parent_input_id: &'a str,
- input: Input,
+ input: &'a AnyInput,
}
struct InputJob {
batch_mode: bool,
parent_input_id: String,
- input: Input,
-}
-
-trait InputPath {
- fn format_path(&self) -> String;
+ input: AnyInput,
}
-impl InputPath for InputInfo<'_> {
+impl InputInfo<'_> {
fn format_path(&self) -> String {
let child = self.input.get_identifier();
if self.parent_input_id.is_empty() {
@@ -83,33 +84,29 @@ impl InputPath for InputInfo<'_> {
pub fn lint(
markdown_options: MarkdownOptions,
curated_dictionary: Arc<dyn Dictionary>,
- inputs: Vec<Input>,
- lint_options: LintOptions,
+ mut inputs: Vec<AnyInput>,
+ mut lint_options: LintOptions,
user_dict_path: PathBuf,
// TODO workspace_dict_path?
file_dict_path: PathBuf,
) -> anyhow::Result<()> {
let LintOptions {
count,
- ignore,
- only,
+ ref mut ignore,
+ ref mut only,
dialect,
} = lint_options;
// Zero or more inputs, default to stdin if not provided
- let all_user_inputs = if inputs.is_empty() {
- vec![Input::try_from_stdin().unwrap()]
- } else {
- inputs
- };
+ if inputs.is_empty() {
+ inputs.push(SingleInput::from(StdinInput).into());
+ }
// Filter out any rules from ignore/only lists that don't exist in the current config
// Uses a cached config to avoid expensive linter initialization
let config = LintGroupConfig::new_curated();
- let mut ignore = ignore.clone();
- let mut only = only.clone();
- if let Some(ref mut only) = only {
+ if let Some(only) = only {
only.retain(|rule| {
if !config.has_rule(rule) {
eprintln!("Warning: Cannot enable unknown rule '{}'.", rule);
@@ -119,7 +116,7 @@ pub fn lint(
});
}
- if let Some(ref mut ignore) = ignore {
+ if let Some(ignore) = ignore {
ignore.retain(|rule| {
if !config.has_rule(rule) {
eprintln!("Warning: Cannot disable unknown rule '{}'.", rule);
@@ -158,37 +155,26 @@ pub fn lint(
};
let mut input_jobs = Vec::new();
- for user_input in all_user_inputs {
- let (batch_mode, maybe_dir) = match &user_input {
- Input::Dir(dir) => (true, std::fs::read_dir(dir).ok()),
- _ => (false, None),
- };
-
- let parent_input_id = if batch_mode {
- user_input.get_identifier().to_string()
- } else {
- String::new()
- };
-
- if let Some(dir) = maybe_dir {
- let mut entries: Vec<_> = dir
- .filter_map(Result::ok)
- .filter(|entry| entry.file_type().map(|ft| !ft.is_dir()).unwrap_or(false))
- .collect();
+ for user_input in inputs {
+ if let Some(dir_input) = user_input
+ .try_as_multi_ref()
+ .and_then(MultiInput::try_as_dir_ref)
+ {
+ let mut file_entries: Vec<_> = dir_input.iter_files()?.collect();
- entries.sort_by_key(|entry| entry.file_name());
+ file_entries.sort_by(|a, b| a.path().file_name().cmp(&b.path().file_name()));
- for entry in entries {
+ for entry in file_entries.into_iter().map(SingleInput::from) {
input_jobs.push(InputJob {
- batch_mode,
- parent_input_id: parent_input_id.clone(),
- input: Input::File(entry.path()),
+ batch_mode: true,
+ parent_input_id: user_input.get_identifier().to_string(),
+ input: entry.into(),
});
}
} else {
input_jobs.push(InputJob {
- batch_mode,
- parent_input_id,
+ batch_mode: false,
+ parent_input_id: String::new(),
input: user_input.clone(),
});
}
@@ -201,27 +187,20 @@ pub fn lint(
parent_input_id,
input,
} = job;
- let parent_id_ref = parent_input_id.as_str();
-
lint_one_input(
// Common properties of harper-cli
markdown_options,
&curated_plus_user_dict,
// Passed from the user for the `lint` subcommand
&report_mode,
- LintOptions {
- count,
- ignore: &ignore,
- only: &only,
- dialect,
- },
+ &lint_options,
&file_dict_path,
// Are we linting multiple inputs inside a directory?
batch_mode,
// The current input to be linted
InputInfo {
- parent_input_id: parent_id_ref,
- input,
+ parent_input_id: parent_input_id.as_str(),
+ input: &input,
},
)
};
@@ -269,7 +248,7 @@ type SpelloCount = HashMap<String, usize>;
struct FullInputInfo<'a> {
input: InputInfo<'a>,
doc: Document,
- source: String,
+ source: Cow<'a, str>,
}
fn lint_one_input(
@@ -278,7 +257,7 @@ fn lint_one_input(
curated_plus_user_dict: &MergedDictionary,
report_mode: &ReportStyle,
// Options passed from the user specific to the `lint` subcommand
- lint_options: LintOptions,
+ lint_options: &LintOptions,
file_dict_path: &Path,
// Are we linting multiple inputs?
batch_mode: bool,
@@ -302,31 +281,28 @@ fn lint_one_input(
let mut lint_kind_rule_pairs: HashMap<(LintKind, String), usize> = HashMap::new();
let mut spellos: HashMap<String, usize> = HashMap::new();
- // Create a new merged dictionary for this input.
- let mut merged_dictionary = curated_plus_user_dict.clone();
-
- // If processing a file, try to load its per-file dictionary
- if let Input::File(ref file) = current.input {
- let dict_path = file_dict_path.join(file_dict_name(file));
- if let Ok(file_dictionary) = load_dict(&dict_path) {
- merged_dictionary.add_dictionary(Arc::new(file_dictionary));
- println!(
- "{}: Note: Using per-file dictionary: {}",
- current.format_path(),
- dict_path.display()
- );
+ if let Some(single_input) = current.input.try_as_single_ref() {
+ // Create a new merged dictionary for this input.
+ let mut merged_dictionary = curated_plus_user_dict.clone();
+
+ // If processing a file, try to load its per-file dictionary
+ if let Some(file) = single_input.try_as_file_ref() {
+ let dict_path = file_dict_path.join(file_dict_name(file.path()));
+ if let Ok(file_dictionary) = load_dict(&dict_path) {
+ merged_dictionary.add_dictionary(Arc::new(file_dictionary));
+ println!(
+ "{}: Note: Using per-file dictionary: {}",
+ current.format_path(),
+ dict_path.display()
+ );
+ }
}
- }
- match current
- .input
- .load(batch_mode, markdown_options, &merged_dictionary)
- {
- Err(err) => eprintln!("{}", err),
- Ok((maybe_doc, source)) => {
- if let Some(doc) = maybe_doc {
+ match single_input.load(markdown_options, &merged_dictionary) {
+ Err(err) => eprintln!("{}", err),
+ Ok((doc, source)) => {
// Create the Lint Group from which we will lint this input, using the combined dictionary and the specified dialect
- let mut lint_group = LintGroup::new_curated(merged_dictionary.into(), dialect);
+ let mut lint_group = LintGroup::new_curated(merged_dictionary.into(), *dialect);
// Turn specified rules on or off
configure_lint_group(&mut lint_group, only, ignore);
diff --git a/harper-cli/src/main.rs b/harper-cli/src/main.rs
index 81ae7cf13..c68d24a91 100644
--- a/harper-cli/src/main.rs
+++ b/harper-cli/src/main.rs
@@ -5,7 +5,7 @@ use hashbrown::HashMap;
use std::collections::BTreeMap;
use std::fs::File;
use std::io::BufReader;
-use std::path::{Path, PathBuf};
+use std::path::PathBuf;
// use std::sync::Arc;
use std::fs;
@@ -13,25 +13,23 @@ use anyhow::anyhow;
use ariadne::{Color, Label, Report, ReportKind, Source};
use clap::Parser;
use dirs::{config_dir, data_local_dir};
-use harper_asciidoc::AsciidocParser;
-use harper_comments::CommentParser;
use harper_core::linting::LintGroup;
-use harper_core::parsers::{Markdown, MarkdownOptions, OrgMode, PlainEnglish};
+use harper_core::parsers::MarkdownOptions;
use harper_core::{
- CharStringExt, Dialect, DictWordMetadata, Document, OrthFlags, Span, TokenKind, TokenStringExt,
+ CharStringExt, Dialect, DictWordMetadata, OrthFlags, Span, TokenKind, TokenStringExt,
};
-use harper_ink::InkParser;
-use harper_literate_haskell::LiterateHaskellParser;
#[cfg(feature = "training")]
use harper_pos_utils::{BrillChunker, BrillTagger, BurnChunkerCpu};
-use harper_python::PythonParser;
use harper_stats::Stats;
use serde::Serialize;
use serde_json::Value;
mod input;
-use input::Input;
+use input::{
+ AnyInput, InputTrait,
+ single_input::{SingleInput, SingleInputOptionExt, SingleInputTrait},
+};
mod annotate_tokens;
use annotate_tokens::{Annotation, AnnotationType};
@@ -41,14 +39,14 @@ use crate::lint::lint;
use lint::LintOptions;
/// A debugging tool for the Harper grammar checker.
-#[derive(Debug, Parser)]
+#[derive(Parser)]
#[command(version, about)]
enum Args {
/// Lint provided documents.
Lint {
/// The text or file you wish to grammar check. If not provided, it will be read from
/// standard input.
- inputs: Vec<Input>,
+ inputs: Vec<AnyInput>,
/// Whether to merely print out the number of errors encountered,
/// without further details.
#[arg(short, long)]
@@ -75,13 +73,13 @@ enum Args {
Parse {
/// The text or file you wish to parse. If not provided, it will be read from standard
/// input.
- input: Option<Input>,
+ input: Option<SingleInput>,
},
/// Parse a provided document and show the spans of the detected tokens.
Spans {
/// The file or text for which you wish to display the spans. If not provided, it will be
/// read from standard input.
- input: Option<Input>,
+ input: Option<SingleInput>,
/// Include newlines in the output
#[arg(short, long)]
include_newlines: bool,
@@ -90,7 +88,7 @@ enum Args {
AnnotateTokens {
/// The text or file you wish to parse. If not provided, it will be read from standard
/// input.
- input: Option<Input>,
+ input: Option<SingleInput>,
/// How the tokens should be annotated.
#[arg(short, long, value_enum, default_value_t = AnnotationType::Upos)]
annotation_type: AnnotationType,
@@ -113,7 +111,7 @@ enum Args {
/// Print a list of all the words in a document, sorted by frequency.
MineWords {
/// The document to mine words from.
- file: PathBuf,
+ input: Option<SingleInput>,
},
#[cfg(feature = "training")]
TrainBrillTagger {
@@ -185,7 +183,7 @@ enum Args {
/// Emit a list of each noun phrase contained within the input
NominalPhrases {
/// The text or file to analyze. If not provided, it will be read from standard input.
- input: Option<Input>,
+ input: Option<SingleInput>,
},
}
@@ -211,8 +209,8 @@ fn main() -> anyhow::Result<()> {
inputs,
LintOptions {
count,
- ignore: &ignore,
- only: &only,
+ ignore,
+ only,
dialect,
},
user_dict_path,
@@ -222,11 +220,10 @@ fn main() -> anyhow::Result<()> {
}
Args::Parse { input } => {
// Try to read from standard input if `input` was not provided.
- let input = input.unwrap_or_else(|| Input::try_from_stdin().unwrap());
+ let input = input.unwrap_or_read_from_stdin();
// Load the file/text.
- let (doc, _) = input.load(false, markdown_options, &curated_dictionary)?;
- let doc = doc.expect("Failed to load document");
+ let (doc, _) = input.load(markdown_options, &curated_dictionary)?;
for token in doc.tokens() {
let json = serde_json::to_string(&token)?;
@@ -240,11 +237,10 @@ fn main() -> anyhow::Result<()> {
include_newlines,
} => {
// Try to read from standard input if `input` was not provided.
- let input = input.unwrap_or_else(|| Input::try_from_stdin().unwrap());
+ let input = input.unwrap_or_read_from_stdin();
// Load the file/text.
- let (doc, source) = input.load(false, markdown_options, &curated_dictionary)?;
- let doc = doc.expect("Failed to load document");
+ let (doc, source) = input.load(markdown_options, &curated_dictionary)?;
let primary_color = Color::Blue;
let secondary_color = Color::Magenta;
@@ -290,11 +286,10 @@ fn main() -> anyhow::Result<()> {
annotation_type,
} => {
// Try to read from standard input if `input` was not provided.
- let input = input.unwrap_or_else(|| Input::try_from_stdin().unwrap());
+ let input = input.unwrap_or_read_from_stdin();
// Load the file/text.
- let (doc, source) = input.load(false, markdown_options, &curated_dictionary)?;
- let doc = doc.expect("Failed to load document");
+ let (doc, source) = input.load(markdown_options, &curated_dictionary)?;
let input_identifier = input.get_identifier();
@@ -465,15 +460,9 @@ fn main() -> anyhow::Result<()> {
Ok(())
}
- Args::MineWords { file } => {
- let (doc, _source) = load_file(
- &file,
- None,
- false,
- MarkdownOptions::default(),
- &curated_dictionary,
- )?;
- let doc = doc.expect("Failed to load document");
+ Args::MineWords { input } => {
+ let input = input.unwrap_or_read_from_stdin();
+ let (doc, _source) = input.load(MarkdownOptions::default(), &curated_dictionary)?;
let mut words = HashMap::new();
@@ -869,14 +858,10 @@ fn main() -> anyhow::Result<()> {
}
Args::NominalPhrases { input } => {
// Get input from either file or direct text
- let input = match input {
- Some(Input::File(path)) => std::fs::read_to_string(path)?,
- Some(Input::Dir(_)) => anyhow::bail!("Directory input is not supported"),
- Some(Input::Text(text)) | Some(Input::Stdin(text)) => text,
- None => std::io::read_to_string(std::io::stdin())?,
- };
+ let (doc, _) = input
+ .unwrap_or_read_from_stdin()
+ .load(MarkdownOptions::default(), &curated_dictionary)?;
- let doc = Document::new_markdown_default_curated(&input);
let phrases: Vec<_> = doc
.iter_nominal_phrases()
.map(|toks| {
@@ -925,57 +910,6 @@ fn main() -> anyhow::Result<()> {
}
}
-fn load_file(
- file: &Path,
- input_identifier: Option<&str>,
- batch_mode: bool,
- markdown_options: MarkdownOptions,
- dictionary: &impl Dictionary,
-) -> anyhow::Result<(Option<Document>, String)> {
- let source = std::fs::read_to_string(file)?;
-
- let parser: Box<dyn harper_core::parsers::Parser> = match file
- .extension()
- .map(|v| v.to_str().unwrap())
- {
- Some("md") | Some("markdown") => Box::new(Markdown::default()),
- Some("ink") => Box::new(InkParser::default()),
-
- Some("lhs") => Box::new(LiterateHaskellParser::new_markdown(
- MarkdownOptions::default(),
- )),
- Some("org") => Box::new(OrgMode),
- Some("typ") => Box::new(harper_typst::Typst),
- Some("py") | Some("pyi") => Box::new(PythonParser::default()),
- Some("adoc") | Some("asciidoc") => Box::new(AsciidocParser::default()),
- Some("txt") => Box::new(PlainEnglish),
- _ => {
- if let Some(comment_parser) = CommentParser::new_from_filename(file, markdown_options) {
- Box::new(comment_parser)
- } else {
- eprintln!(
- "{}Warning: Could not detect language ID; {}",
- input_identifier
- .map(|id| format!("{}: ", id))
- .unwrap_or_default(),
- if batch_mode {
- "skipping file."
- } else {
- "falling back to PlainEnglish parser."
- }
- );
- if batch_mode {
- return Ok((None, source));
- } else {
- Box::new(PlainEnglish)
- }
- }
- }
- };
-
- Ok((Some(Document::new(&source, &parser, dictionary)), source))
-}
-
/// Split a dictionary line into its word and annotation segments
fn line_to_parts(line: &str) -> (String, String) {
if let Some((word, annot)) = line.split_once('/') {
diff --git a/harper-core/src/spell/dictionary.rs b/harper-core/src/spell/dictionary.rs
index 3c74f530b..f06a8f92b 100644
--- a/harper-core/src/spell/dictionary.rs
+++ b/harper-core/src/spell/dictionary.rs
@@ -8,7 +8,7 @@ use crate::DictWordMetadata;
/// An in-memory database that contains everything necessary to parse and analyze English text.
///
/// See also: [`super::FstDictionary`] and [`super::MutableDictionary`].
-#[blanket(derive(Arc))]
+#[blanket(derive(Arc, Ref))]
pub trait Dictionary: Send + Sync {
/// Check if the dictionary contains any capitalization of a given word.
fn contains_word(&self, word: &[char]) -> bool;