refactor: add shared library facade
This commit is contained in:
parent
4c29830891
commit
b54c03744b
|
|
@ -21,6 +21,10 @@ The temporary command-line entry point accepts one file, directory, or supported
|
|||
ZIP-based path and prints a summary per document. Its interface will be replaced
|
||||
by the planned Clap-based detector binary during Milestone 1.
|
||||
|
||||
Reusable consumers should call the library facade: `load_config`,
|
||||
`analyze_source`, `plan_replacements`, and `read_inputs`. Replacement planning is
|
||||
pure and shares the exact resolved configuration used by analysis.
|
||||
|
||||
The implementation is being restructured into a reusable library plus detector,
|
||||
formatter, and LSP binaries. See [tasks.md](tasks.md) for the ordered backlog and
|
||||
[AGENTS.md](AGENTS.md) for the design and contribution rules.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,56 @@
|
|||
//! Typed configuration consumed by the shared library.
|
||||
|
||||
/// One configured Unicode-to-ASCII replacement.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ReplacementRule {
|
||||
/// Stable identifier used by diagnostics and overrides.
|
||||
pub id: &'static str,
|
||||
/// Unicode character to replace.
|
||||
pub source: char,
|
||||
/// ASCII replacement text.
|
||||
pub replacement: &'static str,
|
||||
}
|
||||
|
||||
/// Resolved John Slop configuration.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Config {
|
||||
/// Enabled replacement rules in deterministic matching order.
|
||||
pub replacements: Vec<ReplacementRule>,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// Load the replacement defaults embedded in this build.
|
||||
///
|
||||
/// Layered TOML sources will replace this constructor during Milestone 2.
|
||||
pub fn embedded() -> Self {
|
||||
const HYPHENS: &[(char, &str)] = &[
|
||||
('\u{2010}', "hyphen"),
|
||||
('\u{2011}', "non-breaking-hyphen"),
|
||||
('\u{2012}', "figure-dash"),
|
||||
('\u{2013}', "en-dash"),
|
||||
('\u{2014}', "em-dash"),
|
||||
('\u{2015}', "horizontal-bar"),
|
||||
('\u{2212}', "minus-sign"),
|
||||
('\u{fe58}', "small-em-dash"),
|
||||
('\u{fe63}', "small-hyphen-minus"),
|
||||
('\u{ff0d}', "fullwidth-hyphen-minus"),
|
||||
];
|
||||
|
||||
Self {
|
||||
replacements: HYPHENS
|
||||
.iter()
|
||||
.map(|(source, id)| ReplacementRule {
|
||||
id,
|
||||
source: *source,
|
||||
replacement: "-",
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Self::embedded()
|
||||
}
|
||||
}
|
||||
|
|
@ -1,13 +1,20 @@
|
|||
//! All detection function & modules
|
||||
//!
|
||||
#[cfg(test)]
|
||||
use regex::{Regex, RegexBuilder};
|
||||
#[cfg(test)]
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use crate::model::{Analysis, Category, Confidence, Finding, RuleId, TextEdit};
|
||||
use crate::{
|
||||
config::Config,
|
||||
model::{Analysis, Category, Confidence, Finding, RuleId},
|
||||
replacement,
|
||||
};
|
||||
|
||||
/// A tiny “search‑engine” that knows a *set* of Unicode code‑points.
|
||||
/// It returns the **byte** offset of every match (so the positions are
|
||||
/// deterministic even if you run the search in parallel).
|
||||
#[cfg(test)]
|
||||
static HYPHEN_REGEX: LazyLock<Regex> = LazyLock::new(|| {
|
||||
// All the Unicode characters that look like a hyphen.
|
||||
// (U+002D, U+2010, U+2011, U+2012, U+2013, U+2014, U+2015, …)
|
||||
|
|
@ -20,6 +27,7 @@ static HYPHEN_REGEX: LazyLock<Regex> = LazyLock::new(|| {
|
|||
|
||||
/// Find *all* occurrences of the characters in `re` inside `text`.
|
||||
/// Returns a vector of `(byte_start, byte_end, matched_char)` tuples.
|
||||
#[cfg(test)]
|
||||
fn find_all(re: &Regex, text: &str) -> Vec<(usize, usize, char)> {
|
||||
re.find_iter(text)
|
||||
.map(|m| (m.start(), m.end(), text[m.range()].chars().next().unwrap()))
|
||||
|
|
@ -27,22 +35,18 @@ fn find_all(re: &Regex, text: &str) -> Vec<(usize, usize, char)> {
|
|||
}
|
||||
|
||||
/// Analyze text using the proof-of-concept Unicode punctuation rule.
|
||||
pub fn analyze(source: &str) -> Analysis {
|
||||
let findings = find_all(&HYPHEN_REGEX, source)
|
||||
pub fn analyze(config: &Config, source: &str) -> Analysis {
|
||||
let findings = replacement::plan(config, source)
|
||||
.into_iter()
|
||||
.filter(|(_, _, character)| *character != '-')
|
||||
.map(|(start, end, character)| Finding {
|
||||
.map(|edit| Finding {
|
||||
rule_id: RuleId::from_static("typography-non-ascii-hyphen"),
|
||||
category: Category::Typography,
|
||||
message: format!("non-ASCII hyphen-like character U+{:04X}", character as u32),
|
||||
message: "configured non-ASCII character has an ASCII replacement".to_owned(),
|
||||
help: Some("Review the punctuation or replace it with an ASCII hyphen.".to_owned()),
|
||||
byte_span: start..end,
|
||||
matched_text: character.to_string(),
|
||||
byte_span: edit.byte_span.clone(),
|
||||
matched_text: source[edit.byte_span.clone()].to_owned(),
|
||||
weight: 10.0,
|
||||
fix: Some(TextEdit {
|
||||
byte_span: start..end,
|
||||
replacement: "-".to_owned(),
|
||||
}),
|
||||
fix: Some(edit),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let score = u8::try_from(findings.len().saturating_mul(10)).unwrap_or(u8::MAX);
|
||||
|
|
@ -93,7 +97,7 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn analysis_returns_explainable_findings_and_ignores_ascii_hyphens() {
|
||||
let analysis = analyze("ordinary-word and suspicious—dash");
|
||||
let analysis = analyze(&Config::embedded(), "ordinary-word and suspicious—dash");
|
||||
|
||||
assert_eq!(analysis.findings.len(), 1);
|
||||
assert_eq!(
|
||||
|
|
|
|||
|
|
@ -0,0 +1,55 @@
|
|||
//! Shared analysis library for John Slop's command-line, formatter, and LSP
|
||||
//! adapters.
|
||||
|
||||
#![warn(missing_docs)]
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
mod config;
|
||||
mod detector;
|
||||
mod model;
|
||||
mod reader;
|
||||
mod replacement;
|
||||
|
||||
pub use config::{Config, ReplacementRule};
|
||||
pub use model::{Analysis, Category, Confidence, Finding, RuleId, SourceId, TextEdit};
|
||||
pub use reader::{FileContent, FileDescriptorIterator};
|
||||
|
||||
/// Load the configuration embedded in this build.
|
||||
///
|
||||
/// User and named configuration layers are introduced in Milestone 2 without
|
||||
/// changing consumers of this facade.
|
||||
pub fn load_config() -> Config {
|
||||
Config::embedded()
|
||||
}
|
||||
|
||||
/// Analyze a UTF-8 source snapshot with the resolved configuration.
|
||||
pub fn analyze_source(config: &Config, source: &str) -> Analysis {
|
||||
detector::analyze(config, source)
|
||||
}
|
||||
|
||||
/// Plan safe ASCII replacements without modifying the source.
|
||||
pub fn plan_replacements(config: &Config, source: &str) -> Vec<TextEdit> {
|
||||
replacement::plan(config, source)
|
||||
}
|
||||
|
||||
/// Read documents from a file, directory, or supported ZIP-based container.
|
||||
pub fn read_inputs(path: &Path) -> miette::Result<FileDescriptorIterator> {
|
||||
reader::universal_read(path)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn facade_uses_one_configuration_for_analysis_and_edits() {
|
||||
let config = load_config();
|
||||
let source = "review—this";
|
||||
let analysis = analyze_source(&config, source);
|
||||
let edits = plan_replacements(&config, source);
|
||||
|
||||
assert_eq!(analysis.findings.len(), 1);
|
||||
assert_eq!(analysis.findings[0].fix.as_ref(), edits.first());
|
||||
}
|
||||
}
|
||||
11
src/main.rs
11
src/main.rs
|
|
@ -5,21 +5,18 @@
|
|||
|
||||
use std::{env, path::Path};
|
||||
|
||||
use john_slop::{analyze_source, load_config, read_inputs};
|
||||
use miette::{Result, miette};
|
||||
|
||||
mod detector;
|
||||
mod errors;
|
||||
mod model;
|
||||
mod reader;
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let path = env::args_os()
|
||||
.nth(1)
|
||||
.ok_or_else(|| miette!("usage: john_slop <path>"))?;
|
||||
|
||||
for document in reader::universal_read(Path::new(&path))? {
|
||||
let config = load_config();
|
||||
for document in read_inputs(Path::new(&path))? {
|
||||
let document = document?;
|
||||
let analysis = detector::analyze(&document.content);
|
||||
let analysis = analyze_source(&config, &document.content);
|
||||
println!(
|
||||
"{}: confidence {}, {} finding(s)",
|
||||
document.path.display(),
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ mod tests;
|
|||
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{Read, Write},
|
||||
io::Read,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
|
|
@ -240,7 +240,10 @@ pub fn read_zip(zip_path: &Path) -> Result<Vec<FileContent>> {
|
|||
/// let path = Path::new("example.txt");
|
||||
/// replace_in_file(path, "foo", "bar")?;
|
||||
/// ```
|
||||
#[cfg(test)]
|
||||
pub fn replace_in_file(path: &Path, target: &str, replacement: &str) -> Result<()> {
|
||||
use std::io::Write;
|
||||
|
||||
let content = read_file(path)?;
|
||||
let new_content = content.replace(target, replacement);
|
||||
let mut file = File::create(path)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,34 @@
|
|||
//! Pure planning of configured text replacements.
|
||||
|
||||
use crate::{Config, TextEdit};
|
||||
|
||||
/// Plan deterministic non-overlapping edits without modifying the source.
|
||||
pub fn plan(config: &Config, source: &str) -> Vec<TextEdit> {
|
||||
source
|
||||
.char_indices()
|
||||
.filter_map(|(start, character)| {
|
||||
let rule = config
|
||||
.replacements
|
||||
.iter()
|
||||
.find(|rule| rule.source == character)?;
|
||||
Some(TextEdit {
|
||||
byte_span: start..start + character.len_utf8(),
|
||||
replacement: rule.replacement.to_owned(),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn plans_only_configured_non_ascii_characters() {
|
||||
let edits = plan(&Config::embedded(), "plain-word—fixed");
|
||||
|
||||
assert_eq!(edits.len(), 1);
|
||||
assert_eq!(edits[0].byte_span, 10..13);
|
||||
assert_eq!(edits[0].replacement, "-");
|
||||
}
|
||||
}
|
||||
2
tasks.md
2
tasks.md
|
|
@ -45,7 +45,7 @@ are written down, and a clean baseline passes all quality gates.
|
|||
|
||||
## Milestone 1 — Library-first restructure
|
||||
|
||||
- [ ] Add `src/lib.rs` and expose a small facade for loading config, analyzing a
|
||||
- [x] Add `src/lib.rs` and expose a small facade for loading config, analyzing a
|
||||
source, planning replacements, and reading inputs.
|
||||
- [x] Replace demo functions and ad hoc errors in `main.rs` with typed domain
|
||||
values (`SourceId`, `Finding`, `Analysis`, `Confidence`, `TextEdit`).
|
||||
|
|
|
|||
Loading…
Reference in New Issue