Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
refactor(core): use a macro and document the methods (#2655)
Elijah Potter862a9b17f199
diff --git a/harper-core/src/weirpack/error.rs b/harper-core/src/weirpack/error.rsnew file mode 100644index 000000000..79878e8e0--- /dev/null+++ b/harper-core/src/weirpack/error.rs@@ -0,0 +1,23 @@+use thiserror::Error;++#[derive(Debug, Error)]+pub enum Error {+ #[error("IO error: {0}")]+ Io(#[from] std::io::Error),+ #[error("Zip error: {0}")]+ Zip(#[from] zip::result::ZipError),+ #[error("JSON error: {0}")]+ Json(#[from] serde_json::Error),+ #[error("Weir error: {0}")]+ Weir(#[from] crate::weir::Error),+ #[error("Missing manifest file '{0}'.")]+ MissingManifest(&'static str),+ #[error("Manifest field '{0}' is missing.")]+ MissingManifestField(&'static str),+ #[error("Manifest field '{0}' must be a string.")]+ InvalidManifestFieldType(&'static str),+ #[error("Duplicate manifest file '{0}'.")]+ DuplicateManifest(&'static str),+ #[error("Invalid rule filename '{0}'.")]+ InvalidRuleFileName(String),+}diff --git a/harper-core/src/weirpack/manifest.rs b/harper-core/src/weirpack/manifest.rsindex 54f4559e5..e69cfe56c 100644--- a/harper-core/src/weirpack/manifest.rs+++ b/harper-core/src/weirpack/manifest.rs@@ -1,82 +1,78 @@use std::io::{Read, Write};use hashbrown::HashMap;+use paste::paste;use serde_json::Value;-use super::WeirpackError;+use super::Error;#[derive(Debug, Clone, Default)]pub struct WeirpackManifest {data: HashMap<String, Value>,}+macro_rules! gen_fns {+ ($field:ident) => {+ paste! {+ #[doc = concat!("Get the ", stringify!($field), " field from the manifest.")]+ pub fn $field(&self) -> Result<&str, Error>{+ self.required_str(stringify!($field))+ }++ #[doc = concat!("Set the ", stringify!($field), " field in the manifest.")]+ pub fn [< set_ $field >](&mut self, value: impl Into<String>) {+ self.set_field(stringify!($field), Value::String(value.into()));+ }+ }+ };+}+impl WeirpackManifest {+ /// Create a new, empty manifest.+ /// Note that an empty manifest is an invalid manifest.pub fn new() -> Self {Self::default()}- pub fn from_reader(reader: impl Read) -> Result<Self, WeirpackError> {+ /// Load a manifest from some bytes.+ pub fn from_reader(reader: impl Read) -> Result<Self, Error> {let data: HashMap<String, Value> = serde_json::from_reader(reader)?;let manifest = Self { data };manifest.validate_required()?;Ok(manifest)}- pub fn write_to(&self, writer: impl Write) -> Result<(), WeirpackError> {+ /// Write a manifest to some bytes.+ pub fn write_to(&self, writer: impl Write) -> Result<(), Error> {self.validate_required()?;serde_json::to_writer_pretty(writer, &self.data)?;Ok(())}+ /// Get an arbitrary field from the manifest.pub fn get_field(&self, key: &str) -> Option<&Value> {self.data.get(key)}+ /// Set an arbitrary field from the manifest.pub fn set_field(&mut self, key: impl Into<String>, value: Value) {self.data.insert(key.into(), value);}- pub fn author(&self) -> Result<&str, WeirpackError> {- self.required_str("author")- }-- pub fn set_author(&mut self, value: impl Into<String>) {- self.set_field("author", Value::String(value.into()));- }-- pub fn version(&self) -> Result<&str, WeirpackError> {- self.required_str("version")- }-- pub fn set_version(&mut self, value: impl Into<String>) {- self.set_field("version", Value::String(value.into()));- }-- pub fn description(&self) -> Result<&str, WeirpackError> {- self.required_str("description")- }-- pub fn set_description(&mut self, value: impl Into<String>) {- self.set_field("description", Value::String(value.into()));- }-- pub fn license(&self) -> Result<&str, WeirpackError> {- self.required_str("license")- }-- pub fn set_license(&mut self, value: impl Into<String>) {- self.set_field("license", Value::String(value.into()));- }+ gen_fns!(author);+ gen_fns!(version);+ gen_fns!(description);+ gen_fns!(license);- fn required_str(&self, key: &'static str) -> Result<&str, WeirpackError> {+ fn required_str(&self, key: &'static str) -> Result<&str, Error> {match self.data.get(key) {Some(Value::String(value)) => Ok(value),- Some(_) => Err(WeirpackError::InvalidManifestFieldType(key)),- None => Err(WeirpackError::MissingManifestField(key)),+ Some(_) => Err(Error::InvalidManifestFieldType(key)),+ None => Err(Error::MissingManifestField(key)),}}- fn validate_required(&self) -> Result<(), WeirpackError> {+ fn validate_required(&self) -> Result<(), Error> {self.author()?;self.version()?;self.description()?;diff --git a/harper-core/src/weirpack/mod.rs b/harper-core/src/weirpack/mod.rsindex 74466282d..2876e9246 100644--- a/harper-core/src/weirpack/mod.rs+++ b/harper-core/src/weirpack/mod.rs@@ -2,39 +2,20 @@ use std::io::{Read, Write};use std::path::Path;use hashbrown::HashMap;-use thiserror::Error;use zip::write::FileOptions;use zip::{CompressionMethod, ZipArchive, ZipWriter};use crate::linting::LintGroup;use crate::weir::{TestResult, WeirLinter};+mod error;mod manifest;+pub use error::Error;pub use manifest::WeirpackManifest;-#[derive(Debug, Error)]-pub enum WeirpackError {- #[error("IO error: {0}")]- Io(#[from] std::io::Error),- #[error("Zip error: {0}")]- Zip(#[from] zip::result::ZipError),- #[error("JSON error: {0}")]- Json(#[from] serde_json::Error),- #[error("Weir error: {0}")]- Weir(#[from] crate::weir::Error),- #[error("Missing manifest file '{0}'.")]- MissingManifest(&'static str),- #[error("Manifest field '{0}' is missing.")]- MissingManifestField(&'static str),- #[error("Manifest field '{0}' must be a string.")]- InvalidManifestFieldType(&'static str),- #[error("Duplicate manifest file '{0}'.")]- DuplicateManifest(&'static str),- #[error("Invalid rule filename '{0}'.")]- InvalidRuleFileName(String),-}-+/// A Weirpack, which carries within itself one or more rules to be used for grammar checking.+/// These rules are written in Weir.#[derive(Debug, Clone, Default)]pub struct Weirpack {pub rules: HashMap<String, String>,@@ -42,6 +23,7 @@ pub struct Weirpack {}impl Weirpack {+ /// Create an empty Weirpack.pub fn new(manifest: WeirpackManifest) -> Self {Self {rules: HashMap::new(),@@ -49,15 +31,18 @@ impl Weirpack {}}+ /// Add a rule to this Weirpack. Does not compile to test the rule.pub fn add_rule(&mut self, name: impl Into<String>, rule: impl Into<String>) -> Option<String> {self.rules.insert(name.into(), rule.into())}+ /// Remove a rule from this Weirpack.pub fn remove_rule(&mut self, name: &str) -> Option<String> {self.rules.remove(name)}- pub fn run_tests(&self) -> Result<HashMap<String, Vec<TestResult>>, WeirpackError> {+ /// Run all the tests within all the Weir rules in this Weirpack.+ pub fn run_tests(&self) -> Result<HashMap<String, Vec<TestResult>>, Error> {let mut failures = HashMap::new();for (name, rule) in &self.rules {@@ -71,7 +56,9 @@ impl Weirpack {Ok(failures)}- pub fn to_lint_group(&self) -> Result<LintGroup, WeirpackError> {+ /// Parse and optimize the Weir rules in the pack, converting the set into a single [`LintGroup`].+ /// Does not run tests.+ pub fn to_lint_group(&self) -> Result<LintGroup, Error> {let mut group = LintGroup::default();for (name, rule) in &self.rules {@@ -83,19 +70,22 @@ impl Weirpack {Ok(group)}- pub fn from_reader(mut reader: impl Read) -> Result<Self, WeirpackError> {+ /// Load a Weirpack from bytes.+ pub fn from_reader(mut reader: impl Read) -> Result<Self, Error> {let mut bytes = Vec::new();reader.read_to_end(&mut bytes)?;Self::from_bytes(&bytes)}- pub fn write_to(&self, mut writer: impl Write) -> Result<(), WeirpackError> {+ /// Write the Weirpack to bytes.+ pub fn write_to(&self, mut writer: impl Write) -> Result<(), Error> {let bytes = self.to_bytes()?;writer.write_all(&bytes)?;Ok(())}- pub fn from_bytes(bytes: &[u8]) -> Result<Self, WeirpackError> {+ /// Load a Weirpack from bytes.+ pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {let cursor = std::io::Cursor::new(bytes);let mut archive = ZipArchive::new(cursor)?;@@ -111,7 +101,7 @@ impl Weirpack {let name = file.name().to_string();if name == "manifest.json" {if manifest.is_some() {- return Err(WeirpackError::DuplicateManifest("manifest.json"));+ return Err(Error::DuplicateManifest("manifest.json"));}let manifest_data = WeirpackManifest::from_reader(&mut file)?;manifest = Some(manifest_data);@@ -126,23 +116,24 @@ impl Weirpack {let file_name = path.file_name().and_then(|segment| segment.to_str())- .ok_or_else(|| WeirpackError::InvalidRuleFileName(name.clone()))?;+ .ok_or_else(|| Error::InvalidRuleFileName(name.clone()))?;let rule_name = Path::new(file_name).file_stem().and_then(|stem| stem.to_str())- .ok_or_else(|| WeirpackError::InvalidRuleFileName(name.clone()))?;+ .ok_or_else(|| Error::InvalidRuleFileName(name.clone()))?;let mut contents = String::new();file.read_to_string(&mut contents)?;rules.insert(rule_name.to_string(), contents);}- let manifest = manifest.ok_or(WeirpackError::MissingManifest("manifest.json"))?;+ let manifest = manifest.ok_or(Error::MissingManifest("manifest.json"))?;Ok(Self { rules, manifest })}- pub fn to_bytes(&self) -> Result<Vec<u8>, WeirpackError> {+ /// Write a Weirpack into bytes.+ pub fn to_bytes(&self) -> Result<Vec<u8>, Error> {let mut zip = ZipWriter::new(std::io::Cursor::new(Vec::new()));let options = FileOptions::<()>::default().compression_method(CompressionMethod::Deflated);