Compare commits

...

35 Commits

Author SHA1 Message Date
c67e4daf7e Update Rust crate zip to v2.2.0 (#34)
All checks were successful
continuous-integration/drone/push Build is passing
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [zip](https://github.com/zip-rs/zip2) | dependencies | minor | `2.1.6` -> `2.2.0` |

---

### Release Notes

<details>
<summary>zip-rs/zip2 (zip)</summary>

### [`v2.2.0`](https://github.com/zip-rs/zip2/blob/HEAD/CHANGELOG.md#220---2024-08-11)

[Compare Source](https://github.com/zip-rs/zip2/compare/v2.1.6...v2.2.0)

##### <!-- 0 -->🚀 Features

-   Expose `ZipArchive::central_directory_start` ([#&#8203;232](https://github.com/zip-rs/zip2/pull/232))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzOC43Ny43IiwidXBkYXRlZEluVmVyIjoiMzguNzcuNyIsInRhcmdldEJyYW5jaCI6Im1hc3RlciIsImxhYmVscyI6W119-->

Reviewed-on: pierre/GrammalecteClient#34
Co-authored-by: Pierre HUBERT <pierre@noreply.localhost>
Co-committed-by: Pierre HUBERT <pierre@noreply.localhost>
2024-09-17 09:30:17 +00:00
386f7009d7 Update Rust crate tokio to v1.40.0
All checks were successful
continuous-integration/drone/push Build is passing
2024-09-13 00:48:21 +00:00
ed315214b4 Update Rust crate serde_json to v1.0.128
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-09-13 00:31:31 +00:00
e7f5de3c73 Update Rust crate reqwest to v0.12.7
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-09-12 00:31:47 +00:00
c634cb16cc Update Rust crate serde to v1.0.206 (#26)
All checks were successful
continuous-integration/drone/push Build is passing
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [serde](https://serde.rs) ([source](https://github.com/serde-rs/serde)) | dependencies | patch | `1.0.205` -> `1.0.206` |

---

### Release Notes

<details>
<summary>serde-rs/serde (serde)</summary>

### [`v1.0.206`](https://github.com/serde-rs/serde/releases/tag/v1.0.206)

[Compare Source](https://github.com/serde-rs/serde/compare/v1.0.205...v1.0.206)

-   Improve support for `flatten` attribute inside of enums ([#&#8203;2567](https://github.com/serde-rs/serde/issues/2567), thanks [@&#8203;Mingun](https://github.com/Mingun))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzOC4yNS4wIiwidXBkYXRlZEluVmVyIjoiMzguMjUuMCIsInRhcmdldEJyYW5jaCI6Im1hc3RlciIsImxhYmVscyI6W119-->

Reviewed-on: pierre/GrammalecteClient#26
Co-authored-by: Pierre HUBERT <pierre@noreply.localhost>
Co-committed-by: Pierre HUBERT <pierre@noreply.localhost>
2024-08-22 07:12:01 +00:00
b26445a5f2 Update Rust crate tokio to v1.39.3
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-08-18 00:29:18 +00:00
2784089e9f Update Rust crate serde_json to v1.0.125
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-08-15 15:17:30 +00:00
938fb1297e Update Rust crate serde_json to v1.0.124
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-08-12 00:08:24 +00:00
a6e502b864 Update Rust crate serde to v1.0.205
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-08-09 00:09:51 +00:00
5634f9615b Update Rust crate serde_json to v1.0.122
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-08-02 00:08:32 +00:00
16b44e002c Update Rust crate zip to v2.1.6
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-08-01 00:08:21 +00:00
c6386d8cc5 Update Rust crate serde_json to v1.0.121
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-07-29 00:08:31 +00:00
1687a1c09f Update Rust crate tokio to v1.39.2
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-07-28 00:08:24 +00:00
ca59eb2849 Update Rust crate env_logger to v0.11.5
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-07-26 00:09:10 +00:00
a8a1cac9ac Update Rust crate zip to v2.1.5
All checks were successful
continuous-integration/drone/push Build is passing
2024-07-25 00:31:14 +00:00
ae41e25869 Update Rust crate thiserror to v1.0.63
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-07-25 00:08:03 +00:00
99a7f7e297 Update Rust crate zip to v2.1.4 (#15)
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: pierre/GrammalecteClient#15
2024-07-24 13:23:34 +00:00
8c514bfd7b Update Rust crate thiserror to v1.0.62 (#13)
All checks were successful
continuous-integration/drone/push Build is passing
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [thiserror](https://github.com/dtolnay/thiserror) | dependencies | patch | `1.0.61` -> `1.0.62` |

---

### Release Notes

<details>
<summary>dtolnay/thiserror (thiserror)</summary>

### [`v1.0.62`](https://github.com/dtolnay/thiserror/releases/tag/1.0.62)

[Compare Source](https://github.com/dtolnay/thiserror/compare/1.0.61...1.0.62)

-   Support referring to nested tuple struct fields inside `#[error("…", …)]` attribute ([#&#8203;309](https://github.com/dtolnay/thiserror/issues/309))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzNy40MjkuMCIsInVwZGF0ZWRJblZlciI6IjM3LjQyOS4wIiwidGFyZ2V0QnJhbmNoIjoibWFzdGVyIiwibGFiZWxzIjpbXX0=-->

Reviewed-on: pierre/GrammalecteClient#13
Co-authored-by: Pierre HUBERT <pierre@noreply.localhost>
Co-committed-by: Pierre HUBERT <pierre@noreply.localhost>
2024-07-24 13:23:25 +00:00
5d3de56c35 Update Rust crate tokio to v1.39.1
All checks were successful
continuous-integration/drone/push Build is passing
2024-07-24 00:37:40 +00:00
c104e74ce2 Update Rust crate env_logger to v0.11.4
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-07-24 00:08:04 +00:00
2df7944058 Update Rust crate zip to v2.1.4
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2024-07-20 00:08:53 +00:00
cf14fd1a6b Update Rust crate tokio to v1.38.1
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-07-17 00:08:43 +00:00
5476cd0613 Update Rust crate serde to v1.0.204
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-07-07 00:21:50 +00:00
81463fa438 Update Rust crate serde_json to v1.0.120
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-07-02 00:21:27 +00:00
06277cff8b Update Rust crate serde_json to v1.0.119
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-07-01 00:06:56 +00:00
f5212213f0 Update Rust crate log to v0.4.22
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-06-29 00:15:48 +00:00
387f283ce5 Update Rust crate serde_json to v1.0.118
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-06-26 00:14:55 +00:00
e305dc6582 Update Rust crate reqwest to v0.12.5
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-06-18 00:15:35 +00:00
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: pierre/GrammalecteClient#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: pierre/GrammalecteClient#1
2024-06-14 16:48:30 +00:00
Gwen Lg
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
Gwen Lg
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
Gwen Lg
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
Gwen Lg
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
Gwen Lg
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
6 changed files with 1169 additions and 561 deletions

1540
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,12 +1,12 @@
[package]
name = "grammalecte_client"
version = "0.1.4"
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"]
@ -14,17 +14,18 @@ categories = ["text-processing"]
[dependencies]
serde_json = "1.0.96"
reqwest = { version = "0.11.18", features = ["json"] }
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"
env_logger = "0.11.3"
tokio = { version = "1.28.1", features = ["full"] }

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

@ -36,10 +36,11 @@
//! 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")]
pub mod server;
@ -302,6 +303,28 @@ pub struct SuggestResult {
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
pub struct GrammalecteClient {
base_url: String,
@ -335,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(),
@ -344,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
}
@ -353,7 +376,7 @@ 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);
@ -361,7 +384,7 @@ impl GrammalecteClient {
.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);
@ -371,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,
@ -13,29 +52,31 @@ pub struct EmbeddedServer {
impl EmbeddedServer {
/// Start embedded Grammalecte server on a random free port
pub fn start() -> Result<Self, Box<dyn Error>> {
Self::start_listen_on_port(get_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, Box<dyn Error>> {
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)?;
}
}
@ -48,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,
@ -78,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) {
@ -93,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 })
}
}
}
}
}