languagetool_rust/api/check/requests.rs
1//! Structures for `check` requests.
2
3use super::{serialize_option_vec_string, Data};
4use std::{borrow::Cow, mem, ops::Deref};
5
6#[cfg(feature = "cli")]
7use clap::ValueEnum;
8use lifetime::IntoStatic;
9use serde::{Serialize, Serializer};
10
11use crate::error::{Error, Result};
12
13/// Possible levels for additional rules.
14///
15/// Currently, `Level::Picky` adds additional rules
16/// with respect to `Level::Default`.
17#[derive(Clone, Default, Debug, PartialEq, Eq, Serialize, Hash)]
18#[cfg_attr(feature = "cli", derive(ValueEnum))]
19#[serde(rename_all = "lowercase")]
20#[non_exhaustive]
21pub enum Level {
22 /// Default level.
23 #[default]
24 Default,
25 /// Picky level.
26 Picky,
27}
28
29impl Level {
30 /// Return `true` if current level is the default one.
31 ///
32 /// # Examples
33 ///
34 /// ```
35 /// # use languagetool_rust::api::check::Level;
36 ///
37 /// let level: Level = Default::default();
38 ///
39 /// assert!(level.is_default());
40 /// ```
41 #[must_use]
42 pub fn is_default(&self) -> bool {
43 *self == Level::default()
44 }
45}
46
47/// Split a string into as few fragments as possible, where each fragment
48/// contains (if possible) a maximum of `n` characters. Pattern str `pat` is
49/// used for splitting.
50///
51/// # Examples
52///
53/// ```
54/// # use languagetool_rust::api::check::split_len;
55/// let s = "I have so many friends.
56/// They are very funny.
57/// I think I am very lucky to have them.
58/// One day, I will write them a poem.
59/// But, in the meantime, I write code.
60/// ";
61///
62/// let split = split_len(&s, 40, "\n");
63///
64/// assert_eq!(split.join(""), s);
65/// assert_eq!(
66/// split,
67/// vec![
68/// "I have so many friends.\n",
69/// "They are very funny.\n",
70/// "I think I am very lucky to have them.\n",
71/// "One day, I will write them a poem.\n",
72/// "But, in the meantime, I write code.\n"
73/// ]
74/// );
75///
76/// let split = split_len(&s, 80, "\n");
77///
78/// assert_eq!(
79/// split,
80/// vec![
81/// "I have so many friends.\nThey are very funny.\n",
82/// "I think I am very lucky to have them.\nOne day, I will write them a poem.\n",
83/// "But, in the meantime, I write code.\n"
84/// ]
85/// );
86///
87/// let s = "I have so many friends.
88/// They are very funny.
89/// I think I am very lucky to have them.
90///
91/// One day, I will write them a poem.
92/// But, in the meantime, I write code.
93/// ";
94///
95/// let split = split_len(&s, 80, "\n\n");
96///
97/// println!("{:?}", split);
98///
99/// assert_eq!(
100/// split,
101/// vec![
102/// "I have so many friends.\nThey are very funny.\nI think I am very lucky to have \
103/// them.\n\n",
104/// "One day, I will write them a poem.\nBut, in the meantime, I write code.\n"
105/// ]
106/// );
107/// ```
108#[must_use]
109pub fn split_len<'source>(s: &'source str, n: usize, pat: &str) -> Vec<&'source str> {
110 let mut vec: Vec<&'source str> = Vec::with_capacity(s.len() / n);
111 let mut splits = s.split_inclusive(pat);
112
113 let mut start = 0;
114 let mut i = 0;
115
116 if let Some(split) = splits.next() {
117 vec.push(split);
118 } else {
119 return Vec::new();
120 }
121
122 for split in splits {
123 let new_len = vec[i].len() + split.len();
124 if new_len < n {
125 vec[i] = &s[start..start + new_len];
126 } else {
127 vec.push(split);
128 start += vec[i].len();
129 i += 1;
130 }
131 }
132
133 vec
134}
135
136/// Default value for [`Request::language`].
137pub const DEFAULT_LANGUAGE: &str = "auto";
138
139/// Custom serialization for [`Request::language`].
140fn serialize_language<S>(lang: &str, s: S) -> std::result::Result<S::Ok, S::Error>
141where
142 S: Serializer,
143{
144 s.serialize_str(if lang.is_empty() {
145 DEFAULT_LANGUAGE
146 } else {
147 lang
148 })
149}
150
151/// LanguageTool POST check request.
152///
153/// The main feature - check a text with LanguageTool for possible style and
154/// grammar issues.
155///
156/// The structure below tries to follow as closely as possible the JSON API
157/// described [here](https://languagetool.org/http-api/swagger-ui/#!/default/post_check).
158#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Hash, IntoStatic)]
159#[serde(rename_all = "camelCase")]
160#[non_exhaustive]
161pub struct Request<'source> {
162 /// The text to be checked. This or 'data' is required.
163 #[serde(skip_serializing_if = "Option::is_none")]
164 pub text: Option<Cow<'source, str>>,
165 /// The text to be checked, given as a JSON document that specifies what's
166 /// text and what's markup. This or 'text' is required.
167 ///
168 /// Markup will be ignored when looking for errors. Example text:
169 /// ```html
170 /// A <b>test</b>
171 /// ```
172 /// JSON for the example text:
173 /// ```json
174 /// {"annotation":[
175 /// {"text": "A "},
176 /// {"markup": "<b>"},
177 /// {"text": "test"},
178 /// {"markup": "</b>"}
179 /// ]}
180 /// ```
181 /// If you have markup that should be interpreted as whitespace, like `<p>`
182 /// in HTML, you can have it interpreted like this:
183 ///
184 /// ```json
185 /// {"markup": "<p>", "interpretAs": "\n\n"}
186 /// ```
187 /// The 'data' feature is not limited to HTML or XML, it can be used for any
188 /// kind of markup. Entities will need to be expanded in this input.
189 #[serde(skip_serializing_if = "Option::is_none")]
190 pub data: Option<Data<'source>>,
191 /// A language code like `en-US`, `de-DE`, `fr`, or `auto` to guess the
192 /// language automatically (see `preferredVariants` below).
193 ///
194 /// For languages with variants (English, German, Portuguese) spell checking
195 /// will only be activated when you specify the variant, e.g. `en-GB`
196 /// instead of just `en`.
197 #[serde(serialize_with = "serialize_language")]
198 pub language: String,
199 /// Set to get Premium API access: Your username/email as used to log in at
200 /// languagetool.org.
201 #[serde(skip_serializing_if = "Option::is_none")]
202 pub username: Option<String>,
203 /// Set to get Premium API access: your API key (see <https://languagetool.org/editor/settings/api>).
204 #[serde(skip_serializing_if = "Option::is_none")]
205 pub api_key: Option<String>,
206 /// Comma-separated list of dictionaries to include words from; uses special
207 /// default dictionary if this is unset.
208 #[serde(serialize_with = "serialize_option_vec_string")]
209 pub dicts: Option<Vec<String>>,
210 /// A language code of the user's native language, enabling false friends
211 /// checks for some language pairs.
212 #[serde(skip_serializing_if = "Option::is_none")]
213 pub mother_tongue: Option<String>,
214 /// Comma-separated list of preferred language variants.
215 ///
216 /// The language detector used with `language=auto` can detect e.g. English,
217 /// but it cannot decide whether British English or American English is
218 /// used. Thus this parameter can be used to specify the preferred variants
219 /// like `en-GB` and `de-AT`. Only available with `language=auto`. You
220 /// should set variants for at least German and English, as otherwise the
221 /// spell checking will not work for those, as no spelling dictionary can be
222 /// selected for just `en` or `de`.
223 #[serde(serialize_with = "serialize_option_vec_string")]
224 pub preferred_variants: Option<Vec<String>>,
225 /// IDs of rules to be enabled, comma-separated.
226 #[serde(serialize_with = "serialize_option_vec_string")]
227 pub enabled_rules: Option<Vec<String>>,
228 /// IDs of rules to be disabled, comma-separated.
229 #[serde(serialize_with = "serialize_option_vec_string")]
230 pub disabled_rules: Option<Vec<String>>,
231 /// IDs of categories to be enabled, comma-separated.
232 #[serde(serialize_with = "serialize_option_vec_string")]
233 pub enabled_categories: Option<Vec<String>>,
234 /// IDs of categories to be disabled, comma-separated.
235 #[serde(serialize_with = "serialize_option_vec_string")]
236 pub disabled_categories: Option<Vec<String>>,
237 /// If true, only the rules and categories whose IDs are specified with
238 /// `enabledRules` or `enabledCategories` are enabled.
239 #[serde(skip_serializing_if = "std::ops::Not::not")]
240 pub enabled_only: bool,
241 /// If set to `picky`, additional rules will be activated, i.e. rules that
242 /// you might only find useful when checking formal text.
243 #[serde(skip_serializing_if = "Level::is_default")]
244 pub level: Level,
245}
246
247impl<'source> Request<'source> {
248 /// Create a new empty request with language set to `"auto"`.
249 #[must_use]
250 pub fn new() -> Self {
251 Self {
252 language: "auto".to_string(),
253 ..Default::default()
254 }
255 }
256
257 /// Set the text to be checked and remove potential data field.
258 #[must_use]
259 pub fn with_text<T: Into<Cow<'source, str>>>(mut self, text: T) -> Self {
260 self.text = Some(text.into());
261 self.data = None;
262 self
263 }
264
265 /// Set the data to be checked and remove potential text field.
266 #[must_use]
267 pub fn with_data(mut self, data: Data<'source>) -> Self {
268 self.data = Some(data);
269 self.text = None;
270 self
271 }
272
273 /// Set the data (obtained from string) to be checked and remove potential
274 /// text field
275 pub fn with_data_str(self, data: &str) -> serde_json::Result<Self> {
276 serde_json::from_str(data).map(|data| self.with_data(data))
277 }
278
279 /// Set the language of the text / data.
280 #[must_use]
281 pub fn with_language(mut self, language: String) -> Self {
282 self.language = language;
283 self
284 }
285
286 /// Return the text within the request.
287 ///
288 /// # Errors
289 ///
290 /// If both `self.text` and `self.data` are [`None`].
291 /// If any data annotation does not contain text or markup.
292 pub fn try_get_text(&self) -> Result<Cow<'source, str>> {
293 if let Some(ref text) = self.text {
294 Ok(text.clone())
295 } else if let Some(ref data) = self.data {
296 match data.annotation.len() {
297 0 => Ok(Default::default()),
298 1 => data.annotation[0].try_get_text(),
299 _ => {
300 let mut text = String::new();
301
302 for da in data.annotation.iter() {
303 text.push_str(da.try_get_text()?.deref());
304 }
305
306 Ok(Cow::Owned(text))
307 },
308 }
309 } else {
310 Err(Error::InvalidRequest(
311 "missing either text or data field".to_string(),
312 ))
313 }
314 }
315
316 /// Return a copy of the text within the request.
317 /// Call [`Request::try_get_text`] but panic on error.
318 ///
319 /// # Panics
320 ///
321 /// If both `self.text` and `self.data` are [`None`].
322 /// If any data annotation does not contain text or markup.
323 #[must_use]
324 pub fn get_text(&self) -> Cow<'source, str> {
325 self.try_get_text().unwrap()
326 }
327
328 /// Split this request into multiple, using [`split_len`] function to split
329 /// text.
330 ///
331 /// # Errors
332 ///
333 /// If `self.text` is [`None`] and `self.data` is [`None`].
334 pub fn try_split(mut self, n: usize, pat: &str) -> Result<Vec<Self>> {
335 // DATA ANNOTATIONS
336 if let Some(data) = mem::take(&mut self.data) {
337 return Ok(data
338 .split(n, pat)
339 .into_iter()
340 .map(|d| self.clone().with_data(d))
341 .collect());
342 }
343
344 // TEXT
345 let text = mem::take(&mut self.text)
346 .ok_or_else(|| Error::InvalidRequest("missing text or data field".to_string()))?;
347 let string: &str = match &text {
348 Cow::Owned(s) => s.as_str(),
349 Cow::Borrowed(s) => s,
350 };
351
352 Ok(split_len(string, n, pat)
353 .iter()
354 .map(|text_fragment| {
355 self.clone()
356 .with_text(Cow::Owned(text_fragment.to_string()))
357 })
358 .collect())
359 }
360
361 /// Split this request into multiple, using [`split_len`] function to split
362 /// text.
363 /// Call [`Request::try_split`] but panic on error.
364 ///
365 /// # Panics
366 ///
367 /// If `self.text` is none.
368 #[must_use]
369 pub fn split(self, n: usize, pat: &str) -> Vec<Self> {
370 self.try_split(n, pat).unwrap()
371 }
372}
373
374#[cfg(test)]
375mod tests {
376 use crate::api::check::DataAnnotation;
377
378 use super::*;
379
380 #[test]
381 fn test_with_text() {
382 let req = Request::default().with_text("hello");
383
384 assert_eq!(req.text.unwrap(), "hello");
385 assert!(req.data.is_none());
386 }
387
388 #[test]
389 fn test_with_data() {
390 let req =
391 Request::default().with_data([DataAnnotation::new_text("hello")].into_iter().collect());
392
393 assert_eq!(
394 req.data.unwrap().annotation[0],
395 DataAnnotation::new_text("hello")
396 );
397 }
398
399 #[test]
400 fn test_with_data_str() {
401 let req = Request::default()
402 .with_data_str("{\"annotation\":[{\"text\": \"hello\"}]}")
403 .unwrap();
404 assert_eq!(
405 req.data.unwrap().annotation[0],
406 DataAnnotation::new_text("hello")
407 );
408
409 // Not a data annotation
410 assert!(Request::default().with_data_str("hello").is_err());
411 }
412
413 #[test]
414 fn test_with_language() {
415 assert_eq!(
416 Request::default().with_language("en-US".into()).language,
417 "en-US".to_string()
418 );
419 }
420}