Skip to content

Commit

Permalink
Test applying new formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
tgross35 committed Nov 23, 2023
1 parent f342249 commit 8c6f016
Show file tree
Hide file tree
Showing 17 changed files with 197 additions and 313 deletions.
25 changes: 14 additions & 11 deletions zspell-cli/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@ include!("src/cli/mod.rs");

fn build_shell_completion(cmd: &mut Command, outdir: &path::PathBuf) -> Result<(), Error> {
// Generate shell completion scripts for our
for shell in [
Shell::Bash,
Shell::Elvish,
Shell::Fish,
Shell::PowerShell,
Shell::Zsh,
] {
for shell in
[
Shell::Bash,
Shell::Elvish,
Shell::Fish,
Shell::PowerShell,
Shell::Zsh,
]
{
let path = generate_to(
shell, cmd, // We need to specify what generator to use
"zspell", // We need to specify the bin name manually
Expand Down Expand Up @@ -49,10 +51,11 @@ fn build_man_pages(cmd: Command, outdir: &Path) -> Result<(), Error> {

fn main() -> Result<(), Error> {
// Output directory will be a cargo-generated random directory
let outdir = match env::var_os("OUT_DIR") {
Some(outdir) => std::path::PathBuf::from(outdir),
None => return Ok(()),
};
let outdir =
match env::var_os("OUT_DIR") {
Some(outdir) => std::path::PathBuf::from(outdir),
None => return Ok(()),
};

let profile = std::env::var("PROFILE").unwrap();

Expand Down
58 changes: 31 additions & 27 deletions zspell-cli/src/download.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,9 +105,9 @@ async fn retrieve_urls(lang: &str, client: &Client) -> anyhow::Result<DownloadIn
.context("error while sending request")?
.text()
.await
.map(|txt| {
serde_json::from_str(&txt).context("error understanding server response at root")
})??;
.map(
|txt| serde_json::from_str(&txt).context("error understanding server response at root")
)??;

// Get the URL of the directory to download
let dir_url = root_json
Expand All @@ -128,9 +128,9 @@ async fn retrieve_urls(lang: &str, client: &Client) -> anyhow::Result<DownloadIn
.context("error while sending request")?
.text()
.await
.map(|txt| {
serde_json::from_str(&txt).context("error understanding server response at dir")
})??;
.map(
|txt| serde_json::from_str(&txt).context("error understanding server response at dir")
)??;

let dir_listing = &dir_json
.as_array()
Expand Down Expand Up @@ -258,12 +258,13 @@ async fn download_dict(

let urls = retrieve_urls(lang, &client).await?;

let fnames = DownloadInfo {
affix: format!("{lang}.aff"),
dictionary: format!("{lang}.dic"),
license: format!("{lang}.license"),
lang: String::default(),
};
let fnames =
DownloadInfo {
affix: format!("{lang}.aff"),
dictionary: format!("{lang}.dic"),
license: format!("{lang}.license"),
lang: String::default(),
};

// We control these strings, unwrap should be safe
// Want to split "sha$some_sha_hex$some_url" into (some_sha_hex, some_url)
Expand Down Expand Up @@ -451,21 +452,24 @@ mod test_mocks {
.replace(r"{{ROOT_URL}}", &TEST_SERVER.base_url())
);

let de_at_aff = make_resp!(
"/main/dictionaries/de-AT/index.aff",
"text/plain",
CONTENT_AFF
);
let de_at_dic = make_resp!(
"/main/dictionaries/de-AT/index.dic",
"text/plain",
CONTENT_DIC
);
let de_at_lic = make_resp!(
"/main/dictionaries/de-AT/license",
"text/plain",
CONTENT_LIC
);
let de_at_aff =
make_resp!(
"/main/dictionaries/de-AT/index.aff",
"text/plain",
CONTENT_AFF
);
let de_at_dic =
make_resp!(
"/main/dictionaries/de-AT/index.dic",
"text/plain",
CONTENT_DIC
);
let de_at_lic =
make_resp!(
"/main/dictionaries/de-AT/license",
"text/plain",
CONTENT_LIC
);

TestMocks {
dict_listing,
Expand Down
27 changes: 14 additions & 13 deletions zspell-cli/src/spelling/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,19 +36,20 @@ pub fn spellcheck_cli(cli: &Cli) -> ExitCode {
};

let load_start = Instant::now();
let dict = match create_dict_from_path(dict_path) {
Ok(v) => v,
Err(e) => {
match e {
Error::Io(e) => eprintln!("IO error: {e}"),
Error::Parse(e) => eprintln!("Error parsing: {e}"),
Error::Build(e) => eprintln!("Error building: {e}"),
Error::Regex(e) => eprintln!("Regex error: {e}"),
_ => unreachable!(),
};
return ExitCode::FAILURE;
}
};
let dict =
match create_dict_from_path(dict_path) {
Ok(v) => v,
Err(e) => {
match e {
Error::Io(e) => eprintln!("IO error: {e}"),
Error::Parse(e) => eprintln!("Error parsing: {e}"),
Error::Build(e) => eprintln!("Error building: {e}"),
Error::Regex(e) => eprintln!("Regex error: {e}"),
_ => unreachable!(),

Check warning on line 48 in zspell-cli/src/spelling/mod.rs

View check run for this annotation

Codecov / codecov/patch

zspell-cli/src/spelling/mod.rs#L39-L48

Added lines #L39 - L48 were not covered by tests
};
return ExitCode::FAILURE;

Check warning on line 50 in zspell-cli/src/spelling/mod.rs

View check run for this annotation

Codecov / codecov/patch

zspell-cli/src/spelling/mod.rs#L50

Added line #L50 was not covered by tests
}
};
let load_time = load_start.elapsed().as_secs_f32();
let wc = dict.wordlist().inner().len() + dict.wordlist_nosuggest().inner().len();
eprintln!("loaded {wc} words in {load_time:.2}s. started session");
Expand Down
5 changes: 0 additions & 5 deletions zspell/src/affix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,11 +249,6 @@ impl ParsedCfg {
}

/// Create a `Config` object from a string version of an affix file
///
/// # Errors
///
/// Returns an error if there is a problem parsing, or if the file is
/// invalid
#[inline]
pub fn load_from_str(s: &str) -> Result<Self, Error> {
Self::from_parsed(affix_from_str(s)?)
Expand Down
55 changes: 19 additions & 36 deletions zspell/src/affix/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,41 +25,34 @@ const SEPARATORS: [char; 3] = ['\r', '\n', '#'];
const LINE_TERMINATORS: [char; 2] = ['\r', '\n'];

/// The result of parsing something
///
/// - `Ok(None)`: nothing found but no errors
/// - `Ok(Some(node, residual))`: matched with result stored to `node`,
/// `residual` contains the rest of the non-matched string
/// - `Err(e)`: error while parsing
type ParseResult<'a> = Result<Option<(AffixNode, &'a str, u32)>, ParseError>;

lazy_static! {
static ref RE_AFX_RULE_HEADER: Regex = Regex::new(
r"(?x)
static ref RE_AFX_RULE_HEADER: Regex =
Regex::new(
r"(?x)
^(?P<flag>\S+)\s+
(?P<xprod>\w+)\s+
(?P<num>\d+)$"
)
.unwrap();
static ref RE_AFX_RULE_BODY: Regex = Regex::new(
r"(?x)
)
.unwrap();
static ref RE_AFX_RULE_BODY: Regex =
Regex::new(
r"(?x)
^(?P<flag>\S+)\s+
(?P<strip_chars>\S+)\s+
(?P<affix>\S+)\s+
(?P<condition>\S+)
(?:$|\s+(?P<morph>.+)$)"
)
.unwrap();
)
.unwrap();
}

/*
Parser Helpers
*/

/// Split a line by key
///
/// - `None`: key not found
/// - `Some((match, residual))`: `match` is the matched string, `residual` is
/// the leftover
#[inline]
#[allow(clippy::option_if_let_else)]
fn line_splitter<'a>(s: &'a str, key: &str) -> Option<(&'a str, &'a str)> {
Expand All @@ -75,18 +68,16 @@ fn line_splitter<'a>(s: &'a str, key: &str) -> Option<(&'a str, &'a str)> {
};

// Parse to newline
let (work, residual) = match s.find(to_find) {
Some(i) => (&s[key.len()..i], &s[i..]),
None => (&s[key.len()..], ""),
};
let (work, residual) =
match s.find(to_find) {
Some(i) => (&s[key.len()..i], &s[i..]),
None => (&s[key.len()..], ""),
};

Some((work.trim(), residual))
}

/// Parse anything from a given key to the end of a line
///
/// Accepts a string to search, a key to search for, and a function to convert
/// the result type if found
#[inline]
fn line_key_parser<'a, F>(s: &'a str, key: &str, f: F) -> ParseResult<'a>
where
Expand All @@ -113,9 +104,6 @@ fn bool_parser<'a>(s: &'a str, key: &str, afx: AffixNode) -> ParseResult<'a> {
}

/// Parse simple strings
///
/// Accepts a string to search, a key to search for, and a function (enum
/// variant)
fn string_parser<'a, F>(s: &'a str, key: &str, f: F) -> ParseResult<'a>
where
F: FnOnce(String) -> AffixNode,
Expand All @@ -124,9 +112,6 @@ where
}

/// Parse single-character flags
///
/// Accepts a string to search, a key to search for, and a function (enum
/// variant)
fn flag_parser<'a, F>(s: &'a str, key: &str, f: F) -> ParseResult<'a>
where
F: FnOnce(String) -> AffixNode,
Expand Down Expand Up @@ -229,9 +214,9 @@ where
match line_splitter(residual, key) {
Some((content, resid)) => {
residual = resid;
let line_groups = RE_AFX_RULE_BODY.captures(content).ok_or_else(|| {
ParseError::new_nocol(ParseErrorKind::AffixBody, content, nlines)
})?;
let line_groups = RE_AFX_RULE_BODY.captures(content).ok_or_else(
|| ParseError::new_nocol(ParseErrorKind::AffixBody, content, nlines)
)?;

let line_flag = line_groups.name("flag").unwrap().as_str();
if line_flag != flag {
Expand Down Expand Up @@ -383,9 +368,7 @@ fn parse_morph_alias(s: &str) -> ParseResult {

fn parse_neighbor_keys(s: &str) -> ParseResult {
line_key_parser(s, "KEY", |s| {
Ok(AffixNode::NeighborKeys(
s.split('|').map(ToOwned::to_owned).collect(),
))
Ok(AffixNode::NeighborKeys(s.split('|').map(ToOwned::to_owned).collect()))
})
}
fn parse_try_characters(s: &str) -> ParseResult {
Expand Down
4 changes: 0 additions & 4 deletions zspell/src/affix/rule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,6 @@ use crate::morph::MorphInfo;
use crate::Error;

/// A simple prefix or suffix rule
///
/// This struct represents a prefix or suffix option that may be applied to any
/// base word. It contains multiple possible rule definitions that describe how
/// to apply the rule.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ParsedRuleGroup {
/// Character identifier for this specific affix, usually any uppercase
Expand Down
9 changes: 2 additions & 7 deletions zspell/src/affix/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,7 @@ impl FlagType {
if flag.len() != 2 || flag.chars().any(|c| !c.is_ascii()) {
Err(ParseErrorKind::FlagParse(Self::Long))
} else {
Ok(u32::from(u16::from_ne_bytes(
flag[0..=1].as_bytes().try_into().unwrap(),
)))
Ok(u32::from(u16::from_ne_bytes(flag[0..=1].as_bytes().try_into().unwrap())))

Check warning on line 121 in zspell/src/affix/types.rs

View check run for this annotation

Codecov / codecov/patch

zspell/src/affix/types.rs#L121

Added line #L121 was not covered by tests
}
}

Expand All @@ -146,10 +144,7 @@ impl FlagType {
if chars.iter().any(|ch| !ch.is_ascii()) {
Err(ParseErrorKind::FlagParse(Self::Long))
} else {
Ok(u32::from(u16::from_ne_bytes([
chars[0] as u8,
chars[1] as u8,
])))
Ok(u32::from(u16::from_ne_bytes([chars[0] as u8, chars[1] as u8])))

Check warning on line 147 in zspell/src/affix/types.rs

View check run for this annotation

Codecov / codecov/patch

zspell/src/affix/types.rs#L147

Added line #L147 was not covered by tests
}
}

Expand Down
Loading

0 comments on commit 8c6f016

Please sign in to comment.