Compare commits

...

14 Commits

Author SHA1 Message Date
150097f77a Release v0.2.0 (#6)
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
Reviewed-on: #6
2024-06-14 17:00:16 +00:00
d33202816f Configure Renovate (#1)
All checks were successful
continuous-integration/drone/push Build is passing
Welcome to [Renovate](https://github.com/renovatebot/renovate)! This is an onboarding PR to help you understand and configure settings before regular Pull Requests begin.

🚦 To activate Renovate, merge this Pull Request. To disable Renovate, simply close this Pull Request unmerged.

---
### Detected Package Files

 * `Cargo.toml` (cargo)

### What to Expect

With your current configuration, Renovate will create 8 Pull Requests:

<details>
<summary>Update Rust crate log to v0.4.21</summary>

  - Schedule: ["at any time"]
  - Branch name: `renovate/log-0.x-lockfile`
  - Merge into: `master`
  - Upgrade [log](https://github.com/rust-lang/log) to `0.4.21`

</details>

<details>
<summary>Update Rust crate mktemp to v0.5.1</summary>

  - Schedule: ["at any time"]
  - Branch name: `renovate/mktemp-0.x-lockfile`
  - Merge into: `master`
  - Upgrade [mktemp](https://github.com/samgiles/rs-mktemp) to `0.5.1`

</details>

<details>
<summary>Update Rust crate serde to v1.0.203</summary>

  - Schedule: ["at any time"]
  - Branch name: `renovate/serde-1.x-lockfile`
  - Merge into: `master`
  - Upgrade [serde](https://github.com/serde-rs/serde) to `1.0.203`

</details>

<details>
<summary>Update Rust crate serde_json to v1.0.117</summary>

  - Schedule: ["at any time"]
  - Branch name: `renovate/serde_json-1.x-lockfile`
  - Merge into: `master`
  - Upgrade [serde_json](https://github.com/serde-rs/json) to `1.0.117`

</details>

<details>
<summary>Update Rust crate env_logger to 0.11.0</summary>

  - Schedule: ["at any time"]
  - Branch name: `renovate/env_logger-0.x`
  - Merge into: `master`
  - Upgrade [env_logger](https://github.com/rust-cli/env_logger) to `0.11.0`

</details>

<details>
<summary>Update Rust crate reqwest to 0.12.0</summary>

  - Schedule: ["at any time"]
  - Branch name: `renovate/reqwest-0.x`
  - Merge into: `master`
  - Upgrade [reqwest](https://github.com/seanmonstar/reqwest) to `0.12.0`

</details>

<details>
<summary>Update Rust crate tokio to v1.38.0</summary>

  - Schedule: ["at any time"]
  - Branch name: `renovate/tokio-1.x-lockfile`
  - Merge into: `master`
  - Upgrade [tokio](https://github.com/tokio-rs/tokio) to `1.38.0`

</details>

<details>
<summary>Update Rust crate zip to v2</summary>

  - Schedule: ["at any time"]
  - Branch name: `renovate/zip-2.x`
  - Merge into: `master`
  - Upgrade [zip](https://github.com/zip-rs/zip2) to `2.0.0`

</details>

<br />

🚸 Branch creation will be limited to maximum 2 per hour, so it doesn't swamp any CI resources or overwhelm the project. See docs for `prhourlylimit` for details.

---

 Got questions? Check out Renovate's [Docs](https://docs.renovatebot.com/), particularly the Getting Started section.
If you need any further assistance then you can also [request help here](https://github.com/renovatebot/renovate/discussions).

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).

<!--renovate-config-hash:94693a990c975907e7f13da3309b9d56ba02b3983519b41786edf5cf031e457c-->

Reviewed-on: #1
2024-06-14 16:48:30 +00:00
b0543aaba9 add err output when server failed to start
All checks were successful
continuous-integration/drone/push Build is passing
2024-06-14 16:46:39 +00:00
597a681801 check if server correctly start
in same time than the port was opened.
Rename function into `wait_for_server` according.
2024-06-14 16:46:39 +00:00
74ff8463ba fix grammalecte archive with python files
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
- update bottle.py dependency to v0.12.25
- fix test of python version in grammalecte-server.py
2024-06-14 14:12:16 +02:00
1ad5dfbe78 improve error management with thiserror use
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
- add thiserror dependency
- use distinct Error enum in lib and server
2024-06-14 12:05:45 +02:00
0d43729a02 update dependencies in Cargo.toml
update: zip, reqwest and env_logger
fix fmt in Cargo.toml
2024-06-14 12:05:05 +02:00
2dd1e5907a Enable CI (#2)
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #2
2024-06-14 06:43:14 +00:00
b09034d6fb Bump Grammalecte version 2023-05-23 14:50:44 +02:00
757692e054 Expose server 2023-05-23 14:46:45 +02:00
7f8a37ce01 Update dependencies 2023-05-23 14:41:19 +02:00
707821ca23 Update metadata 2022-12-20 10:18:19 +01:00
162a5e9af8 Bump version 2022-12-20 10:15:33 +01:00
991dc71c79 Fix bad structure interface 2022-12-20 10:14:57 +01:00
8 changed files with 1209 additions and 564 deletions

14
.drone.yml Normal file
View File

@ -0,0 +1,14 @@
---
kind: pipeline
type: docker
name: default
steps:
- name: cargo_check
image: rust
commands:
- rustup component add clippy
- cargo clippy -- -D warnings
- cargo test --all-features

1536
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,28 +1,31 @@
[package]
name = "grammalecte_client"
version = "0.1.2"
version = "0.1.5"
edition = "2021"
authors = ["Pierre Hubert <pierre.git@communiquons.org>"]
description = "Grammalecte HTTP client"
license = "MIT"
repository = "https://gitea.communiquons.org/pierre/GrammalecteClient"
keywords = ["grammalecte", "spell-check"]
keywords = ["grammalecte", "spell-check", "spellcheck"]
readme = "README.md"
categories = ["text-processing"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
serde_json = "1.0.89"
reqwest = { version = "0.11.13", features = ["json"] }
serde = { version = "1.0.151", features = ["derive"] }
serde_json = "1.0.96"
reqwest = { version = "0.12.4", features = ["json"] }
serde = { version = "1.0.163", features = ["derive"] }
log = "0.4.17"
zip = { version = "0.6.3", optional = true }
zip = { version = "2.1.3", optional = true }
mktemp = { version = "0.5.0", optional = true }
rand = { version = "0.8.5", optional = true }
port_scanner = {version = "0.1.5", optional = true}
port_scanner = { version = "0.1.5", optional = true }
thiserror = "1.0.61"
[features]
embedded-server = ["zip", "mktemp", "rand", "port_scanner"]
[dev-dependencies]
env_logger = "0.10.0"
tokio = { version = "1.23.0", features = ["full"] }
env_logger = "0.11.3"
tokio = { version = "1.28.1", features = ["full"] }

View File

@ -1,4 +1,7 @@
# Grammalecte client
This crate is an Open Source [Grammalecte](https://grammalecte.net/) client, writtent in Rust.
[![Crate](https://img.shields.io/crates/v/grammalecte_client.svg)](https://crates.io/crates/grammalecte_client)
[![Documentation](https://docs.rs/grammalecte_client/badge.svg)](https://docs.rs/grammalecte_client/)
Please have a look at this crate documentation to learn more.
This crate is an Open Source [Grammalecte](https://grammalecte.net/) client, written in Rust.
Please have a look at this [crate documentation](https://docs.rs/grammalecte_client/latest/grammalecte_client/) to learn more.

9
renovate.json Normal file
View File

@ -0,0 +1,9 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"packageRules": [
{
"matchUpdateTypes": ["major", "minor", "patch"],
"automerge": true
}
]
}

Binary file not shown.

View File

@ -10,7 +10,7 @@
//! temporary web server that will act as Grammalecte backend, instead
//! of targetting an existing instance:
//!
//! ```rust,no_run
//! ```rust,ignore
//! use grammalecte_client::GrammalecteClient;
//!
//! let msg = "Les ange sont inssuportables!";
@ -24,7 +24,9 @@
//!
//! ## Suggestion
//! You can also ask Grammalecte to give you valid alternatives words:
//! ```rust,no_run
//! ```rust,ignore
//! use grammalecte_client::GrammalecteClient;
//!
//! let res = GrammalecteClient::start_server()
//! .unwrap()
//! .suggest("bonjou")
@ -34,13 +36,14 @@
//! println!("RESULT = {:#?}", res);
//! ```
use thiserror::Error;
#[cfg(feature = "embedded-server")]
use crate::server::EmbeddedServer;
use std::collections::HashMap;
use std::error::Error;
#[cfg(feature = "embedded-server")]
mod server;
pub mod server;
/// Spell check options
#[derive(Hash, Debug, Eq, PartialEq)]
@ -296,7 +299,30 @@ pub struct SpellingError {
/// Response to a suggestion request
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SuggestResult {
suggestions: Vec<String>,
/// Suggestions returned by Grammalecte
pub suggestions: Vec<String>,
}
#[derive(Debug, Error)]
pub enum Error {
#[cfg(feature = "embedded-server")]
#[error("Grammalecte-server failed to start")]
ServerStartFailed(#[from] server::Error),
#[error("Failed to Serialize Option in Json")]
OptionJsonSerialization(#[source] serde_json::Error),
#[error("Failed to send request `check with option`")]
RequestSendCheckWithOptions(#[source] reqwest::Error),
#[error("Failed to send request `suggest`")]
RequestSendSuggest(#[source] reqwest::Error),
#[error("Failed to Deserialize Check result")]
CheckResultDeserialize(#[source] reqwest::Error),
#[error("Failed to Deserialize Suggest result")]
SuggestDeserialize(#[source] reqwest::Error),
}
/// The Grammalecte client itself
@ -332,7 +358,7 @@ impl GrammalecteClient {
///
/// Python 3.7 or higher must is required at runtime
#[cfg(feature = "embedded-server")]
pub fn start_server() -> Result<Self, Box<dyn Error>> {
pub fn start_server() -> Result<Self, Error> {
let server = EmbeddedServer::start()?;
Ok(Self {
base_url: server.base_url(),
@ -341,7 +367,7 @@ impl GrammalecteClient {
}
/// Run spell check on text
pub async fn spell_check(&self, text: &str) -> Result<CheckResult, Box<dyn Error>> {
pub async fn spell_check(&self, text: &str) -> Result<CheckResult, Error> {
self.spell_check_with_options(text, &HashMap::new()).await
}
@ -350,15 +376,15 @@ impl GrammalecteClient {
&self,
text: &str,
options: &HashMap<GramOpt, bool>,
) -> Result<CheckResult, Box<dyn Error>> {
) -> Result<CheckResult, Error> {
let url = format!("{}/gc_text/fr", self.base_url);
log::debug!("Will use URL {} for spell check", url);
let options = options
.into_iter()
.iter()
.map(|t| (t.0.id(), t.1))
.collect::<HashMap<_, _>>();
let options = serde_json::to_string(&options)?;
let options = serde_json::to_string(&options).map_err(Error::OptionJsonSerialization)?;
let mut params = HashMap::new();
params.insert("text", text);
@ -368,28 +394,32 @@ impl GrammalecteClient {
.post(url)
.form(&params)
.send()
.await?
.await
.map_err(Error::RequestSendCheckWithOptions)?
.json::<CheckResult>()
.await?;
.await
.map_err(Error::CheckResultDeserialize)?;
Ok(result)
}
/// Ask for word suggestion
pub async fn suggest(&self, token: &str) -> Result<SuggestResult, Box<dyn Error>> {
pub async fn suggest(&self, token: &str) -> Result<SuggestResult, Error> {
let url = format!("{}/suggest/fr", self.base_url);
log::debug!("Will use URL {} for word suggestion", url);
let mut params = HashMap::new();
params.insert("token", token);
Ok(reqwest::Client::new()
reqwest::Client::new()
.post(&url)
.form(&params)
.send()
.await?
.await
.map_err(Error::RequestSendSuggest)?
.json()
.await?)
.await
.map_err(Error::SuggestDeserialize)
}
}

View File

@ -1,9 +1,48 @@
use crate::server::utils::{get_free_port, wait_for_port};
use crate::server::utils::{get_free_port, wait_for_server};
use mktemp::Temp;
use std::error::Error;
use std::io::{Cursor, Read};
use std::process::{Child, Stdio};
use zip::ZipArchive;
use std::io::{self, Cursor, Read};
use std::process::{Child, ExitStatus, Stdio};
use thiserror::Error;
use zip::{result::ZipError, ZipArchive};
#[derive(Debug, Error)]
pub enum Error {
#[error("Grammalecte-server failed to launch process")]
StartServerProcess(#[source] io::Error),
#[error("Get an available port failed")]
GetFreePort(#[source] io::Error),
#[error("Server exit with `{status}`")]
ServerExitWithStatus { status: ExitStatus },
#[error("Server exit with `{status}` :\n{msg}")]
ServerExitWithError { status: ExitStatus, msg: String },
#[error("Error append during check grammalecte-server status")]
ServerCheckStatus(#[source] io::Error),
#[error("Port {port} did not open in time!")]
WaitPortOpen { port: u16 },
#[error("Create temporary directory failed")]
CreateTempDir(#[source] io::Error),
#[error("Zip archive loading failed")]
ZipArchiveLoading(#[source] ZipError),
#[error("Access file by index failed")]
ZipFileIndex(#[source] ZipError),
#[error("Create directory for files from zip")]
CreateDirectoryForZipFile(#[source] io::Error),
#[error("Read file from zip archive")]
ZipFileReadToEnd(#[source] io::Error),
#[error("Write file from archive on disk")]
WriteFile(#[source] io::Error),
}
pub struct EmbeddedServer {
_srv_dir: Temp,
@ -12,30 +51,35 @@ pub struct EmbeddedServer {
}
impl EmbeddedServer {
/// Start embedded Grammalecte server
pub fn start() -> Result<Self, Box<dyn Error>> {
/// Start embedded Grammalecte server on a random free port
pub fn start() -> Result<Self, Error> {
Self::start_listen_on_port(get_free_port())
}
/// Start embedded Grammalecte server on a given port
pub fn start_listen_on_port(port: u16) -> Result<Self, Error> {
log::info!("Will start server");
// First, unpack server
let dest = mktemp::Temp::new_dir()?;
let dest = mktemp::Temp::new_dir().map_err(Error::CreateTempDir)?;
let cursor = Cursor::new(include_bytes!("GrammalecteDist.zip"));
let mut zip = ZipArchive::new(cursor)?;
let mut zip = ZipArchive::new(cursor).map_err(Error::ZipArchiveLoading)?;
for i in 0..zip.len() {
let mut file = zip.by_index(i)?;
let mut file = zip.by_index(i).map_err(Error::ZipFileIndex)?;
if file.is_dir() {
log::debug!("Create directory: {}", file.name());
std::fs::create_dir_all(dest.join(file.name()))?;
std::fs::create_dir_all(dest.join(file.name()))
.map_err(Error::CreateDirectoryForZipFile)?;
} else {
log::debug!("Decompress file: {}", file.name());
let mut buff = Vec::with_capacity(file.size() as usize);
file.read_to_end(&mut buff)?;
file.read_to_end(&mut buff)
.map_err(Error::ZipFileReadToEnd)?;
std::fs::write(dest.join(file.name()), buff)?;
std::fs::write(dest.join(file.name()), buff).map_err(Error::WriteFile)?;
}
}
// Get a free port
let port = get_free_port()?;
log::info!("Will start to listen on port {}", port);
let server_file = dest
@ -45,15 +89,16 @@ impl EmbeddedServer {
log::info!("Will execute file {}", server_file);
// Start server
let child = std::process::Command::new("/usr/bin/python3")
let mut child = std::process::Command::new("/usr/bin/python3")
.arg(server_file)
.arg("-p")
.arg(port.to_string())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()?;
.stderr(Stdio::piped())
.spawn()
.map_err(Error::StartServerProcess)?;
wait_for_port(port)?;
wait_for_server(&mut child, port)?;
Ok(Self {
_srv_dir: dest,
@ -75,11 +120,14 @@ impl Drop for EmbeddedServer {
}
mod utils {
use std::io::ErrorKind;
use super::Error;
use std::fmt::Write;
use std::io::{BufRead, BufReader};
use std::process::Child;
use std::time::Duration;
/// Get a free port
pub fn get_free_port() -> std::io::Result<u16> {
pub fn get_free_port() -> u16 {
let mut port = 0;
while !(2000..=64000).contains(&port) {
@ -90,20 +138,42 @@ mod utils {
port += 1;
}
Ok(port)
port
}
pub fn wait_for_port(port: u16) -> std::io::Result<()> {
pub fn wait_for_server(child: &mut Child, port: u16) -> Result<(), Error> {
for _ in 0..50 {
check_server(child)?;
if port_scanner::scan_port(port) {
return Ok(());
}
std::thread::sleep(Duration::from_millis(100));
}
Err(std::io::Error::new(
ErrorKind::Other,
format!("Port {} did not open in time!", port),
))?
Err(Error::WaitPortOpen { port })
}
fn check_server(child: &mut Child) -> Result<(), Error> {
match child.try_wait().map_err(Error::ServerCheckStatus)? {
None => Ok(()), // Continue
Some(status) => {
if let Some(err) = child.stderr.take() {
let mut msg = format!("grammalecte-server exit with `{status}`");
writeln!(&mut msg, " :").unwrap();
let err = BufReader::new(err);
err.lines().for_each(|line| match line {
Ok(line) => {
writeln!(&mut msg, "\t{}", line).unwrap();
}
Err(err) => {
writeln!(&mut msg, "__{err:?}").unwrap();
}
});
Err(Error::ServerExitWithError { status, msg })
} else {
Err(Error::ServerExitWithStatus { status })
}
}
}
}
}