Skip to main content

languagetool_rust/cli/
check.rs

1//! Check text using LanguageTool server.
2//!
3//! The input can be one of the following:
4//!
5//! - raw text, if `--text TEXT` is provided;
6//! - annotated data, if `--data TEXT` is provided;
7//! - text from file(s), if `[FILE(S)]...` are provided.
8//! - raw text through `stdin`, if nothing else is provided.
9use std::{borrow::Cow, io, io::Write, path::PathBuf};
10
11use clap::{Args, Parser, ValueEnum};
12use is_terminal::IsTerminal;
13use serde::{Deserialize, Serialize};
14use termcolor::{StandardStream, WriteColor};
15
16use crate::{
17    api::{
18        check::{
19            self, parse_language_code, Data, DataAnnotation, Level, Request, DEFAULT_LANGUAGE,
20        },
21        server::ServerClient,
22    },
23    error::{Error, Result},
24    parsers::{html::parse_html, markdown::parse_markdown, typst::parse_typst},
25};
26
27use super::ExecuteSubcommand;
28
29/// Parse a string slice into a [`PathBuf`], and error if the file does not
30/// exist.
31fn parse_filename(s: &str) -> Result<PathBuf> {
32    let path_buf = PathBuf::from(s);
33
34    if path_buf.is_file() {
35        Ok(path_buf)
36    } else {
37        Err(Error::InvalidFilename(s.to_string()))
38    }
39}
40
41/// Command to check a text with LanguageTool for possible style and grammar
42/// issues.
43#[derive(Debug, Parser)]
44pub struct Command {
45    /// If present, raw JSON output will be printed instead of annotated text.
46    /// This has no effect if `--data` is used, because it is never
47    /// annotated.
48    #[clap(short = 'r', long)]
49    pub raw: bool,
50    /// Sets the maximum number of characters before splitting.
51    #[clap(long, default_value_t = 1500)]
52    pub max_length: usize,
53    /// If text is too long, will split on this pattern.
54    #[clap(long, default_value = "\n\n")]
55    pub split_pattern: String,
56    /// Max. number of suggestions kept. If negative, all suggestions are kept.
57    #[clap(long, default_value_t = 5, allow_negative_numbers = true)]
58    pub max_suggestions: isize,
59    /// Specify the files type to use the correct parser.
60    ///
61    /// If set to auto, the type is guessed from the filename extension.
62    #[clap(long, value_enum, default_value_t = FileType::default(), ignore_case = true)]
63    pub r#type: FileType,
64    /// Optional filenames from which input is read.
65    #[arg(conflicts_with_all(["text", "data"]), value_parser = parse_filename)]
66    pub filenames: Vec<PathBuf>,
67    /// Inner [`Request`].
68    #[command(flatten, next_help_heading = "Request options")]
69    pub request: CliRequest,
70}
71
72/// Support file types.
73#[derive(Clone, Debug, Default, ValueEnum)]
74#[non_exhaustive]
75pub enum FileType {
76    /// Auto.
77    #[default]
78    Auto,
79    /// Raw text.
80    Raw,
81    /// Markdown.
82    Markdown,
83    /// HTML.
84    Html,
85    /// Typst.
86    Typst,
87}
88
89/// Read lines from standard input and write to buffer string.
90///
91/// Standard output is used when waiting for user to input text.
92fn read_from_stdin(buffer: &mut String) -> Result<()> {
93    if io::stdin().is_terminal() {
94        #[cfg(windows)]
95        log::info!("Reading from STDIN, press [CTRL+Z] when you're done.");
96
97        #[cfg(unix)]
98        log::info!("Reading from STDIN, press [CTRL+D] when you're done.");
99    }
100    let stdin = std::io::stdin();
101
102    while stdin.read_line(buffer)? > 0 {}
103    Ok(())
104}
105
106impl ExecuteSubcommand for Command {
107    /// Executes the `check` subcommand.
108    async fn execute(self, mut stdout: StandardStream, server_client: ServerClient) -> Result<()> {
109        let mut request: check::Request = self.request.into();
110        #[cfg(feature = "annotate")]
111        let color = stdout.supports_color();
112
113        let server_client = server_client.with_max_suggestions(self.max_suggestions);
114
115        // ANNOTATED DATA, RAW TEXT, STDIN
116        if self.filenames.is_empty() {
117            // Fallback to `stdin` if nothing else is provided
118            if request.text.is_none() && request.data.is_none() {
119                let mut text = String::new();
120                read_from_stdin(&mut text)?;
121                request = request.with_text(Cow::Owned(text));
122            }
123
124            if let Some(ref text) = request.text {
125                if text.is_empty() {
126                    log::warn!("No input text was provided, skipping.");
127                    return Ok(());
128                }
129                // Split text into multiple parts to be checked
130                let requests = request.split(self.max_length, self.split_pattern.as_str());
131
132                if self.raw {
133                    // RAW JSON output does not carry 'context' information
134                    let response = server_client
135                        .check_multiple_and_join_without_context(requests)
136                        .await?;
137                    writeln!(&mut stdout, "{}", serde_json::to_string_pretty(&response)?)?;
138                } else {
139                    let response_with_context =
140                        server_client.check_multiple_and_join(requests).await?;
141
142                    writeln!(
143                        &mut stdout,
144                        "{}",
145                        &response_with_context.annotate(
146                            response_with_context.text.as_ref(),
147                            None,
148                            color
149                        )
150                    )?;
151                }
152            } else {
153                // Handle annotated data
154                let response = server_client.check(&request).await?;
155                writeln!(&mut stdout, "{}", serde_json::to_string_pretty(&response)?)?;
156            };
157
158            return Ok(());
159        }
160
161        // FILES
162        for filename in self.filenames.iter() {
163            let mut file_type = self.r#type.clone();
164
165            // If file type is "Auto", guess file type from extension
166            if matches!(self.r#type, FileType::Auto) {
167                file_type = match PathBuf::from(filename).extension().and_then(|e| e.to_str()) {
168                    Some(ext) => {
169                        match ext {
170                            "typ" => FileType::Typst,
171                            "md" | "markdown" | "mdown" | "mdwn" | "mkd" | "mkdn" | "mdx" => {
172                                FileType::Markdown
173                            },
174
175                            "html" | "htm" => FileType::Html,
176                            _ => {
177                                log::debug!("Unknown file type: {ext}.");
178                                FileType::Raw
179                            },
180                        }
181                    },
182                    None => {
183                        log::debug!("No extension found for file: {filename:?}.");
184                        FileType::Raw
185                    },
186                };
187            };
188
189            let file_content = std::fs::read_to_string(filename)?;
190
191            let (response, text): (check::Response, String) = match &file_type {
192                FileType::Auto => unreachable!(),
193                FileType::Raw => {
194                    let requests = (request.clone().with_text(&file_content))
195                        .split(self.max_length, self.split_pattern.as_str());
196
197                    if requests.is_empty() {
198                        log::info!("Skipping empty file: {filename:?}.");
199                        continue;
200                    }
201                    // TODO: see if we can keep the ResponseWithContext and use this for better
202                    // annotation, or if it doesn't change anything become into() preserves
203                    // all the important information.
204
205                    let response = server_client.check_multiple_and_join(requests).await?;
206                    (response.into(), file_content)
207                },
208                FileType::Typst | FileType::Markdown | FileType::Html => {
209                    let data = match file_type {
210                        FileType::Typst => parse_typst(&file_content),
211                        FileType::Html => parse_html(&file_content),
212                        FileType::Markdown => parse_markdown(&file_content),
213                        _ => unreachable!(),
214                    };
215                    let requests = (request.clone().with_data(data))
216                        .split(self.max_length, self.split_pattern.as_str());
217                    let response = server_client
218                        .check_multiple_and_join_without_context(requests)
219                        .await?;
220                    (response, file_content)
221                },
222            };
223
224            if self.raw {
225                writeln!(&mut stdout, "{}", serde_json::to_string_pretty(&response)?)?;
226            } else {
227                writeln!(
228                    &mut stdout,
229                    "{}",
230                    &response.annotate(&text, filename.to_str(), color)
231                )?;
232            }
233        }
234
235        Ok(())
236    }
237}
238
239// NOTE: The below structs are copied from `../api/check.rs` to avoid lifetime
240// issues with `clap` TODO: Remove these once this upstream issue is resolved: <https://github.com/clap-rs/clap/issues/5773>
241// -------------------------------------------------------------------------------------------------
242
243/// LanguageTool POST check request.
244///
245/// The main feature - check a text with LanguageTool for possible style and
246/// grammar issues.
247///
248/// The structure below tries to follow as closely as possible the JSON API
249/// described [here](https://languagetool.org/http-api/swagger-ui/#!/default/post_check).
250#[derive(Args, Clone, Debug, Default, PartialEq, Eq, Hash)]
251#[non_exhaustive]
252pub struct CliRequest {
253    /// The text to be checked. This, `data`, or `[FILENAMES...]` cannot be
254    /// passed simultaneously. If nothing is specified, input will be read from
255    /// `stdin`
256    #[clap(short = 't', long, conflicts_with = "data", allow_hyphen_values(true))]
257    pub text: Option<String>,
258    /// The text to be checked, given as a JSON document that specifies what's
259    /// text and what's markup. This or 'text' is required.
260    ///
261    /// Markup will be ignored when looking for errors. Example text:
262    /// ```html
263    /// A <b>test</b>
264    /// ```
265    /// JSON for the example text:
266    /// ```json
267    /// {"annotation":[
268    ///  {"text": "A "},
269    ///  {"markup": "<b>"},
270    ///  {"text": "test"},
271    ///  {"markup": "</b>"}
272    /// ]}
273    /// ```
274    /// If you have markup that should be interpreted as whitespace, like `<p>`
275    /// in HTML, you can have it interpreted like this:
276    ///
277    /// ```json
278    /// {"markup": "<p>", "interpretAs": "\n\n"}
279    /// ```
280    /// The 'data' feature is not limited to HTML or XML, it can be used for any
281    /// kind of markup. Entities will need to be expanded in this input.
282    #[clap(short = 'd', long, conflicts_with = "text")]
283    pub data: Option<CliData>,
284    /// A language code like `en-US`, `de-DE`, `fr`, or `auto` to guess the
285    /// language automatically (see `preferredVariants` below).
286    ///
287    /// For languages with variants (English, German, Portuguese) spell checking
288    /// will only be activated when you specify the variant, e.g. `en-GB`
289    /// instead of just `en`.
290    #[cfg_attr(
291        feature = "cli",
292        clap(
293            short = 'l',
294            long,
295            default_value = DEFAULT_LANGUAGE,
296            value_parser = parse_language_code
297        )
298    )]
299    pub language: String,
300    /// Set to get Premium API access: Your username/email as used to log in at
301    /// languagetool.org.
302    #[cfg_attr(
303        feature = "cli",
304        clap(short = 'u', long, requires = "api_key", env = "LANGUAGETOOL_USERNAME")
305    )]
306    pub username: Option<String>,
307    /// Set to get Premium API access: your API key (see <https://languagetool.org/editor/settings/api>).
308    #[cfg_attr(
309        feature = "cli",
310        clap(short = 'k', long, requires = "username", env = "LANGUAGETOOL_API_KEY")
311    )]
312    pub api_key: Option<String>,
313    /// Comma-separated list of dictionaries to include words from; uses special
314    /// default dictionary if this is unset.
315    #[cfg_attr(feature = "cli", clap(long))]
316    pub dicts: Option<Vec<String>>,
317    /// A language code of the user's native language, enabling false friends
318    /// checks for some language pairs.
319    #[cfg_attr(feature = "cli", clap(long))]
320    pub mother_tongue: Option<String>,
321    /// Comma-separated list of preferred language variants.
322    ///
323    /// The language detector used with `language=auto` can detect e.g. English,
324    /// but it cannot decide whether British English or American English is
325    /// used. Thus this parameter can be used to specify the preferred variants
326    /// like `en-GB` and `de-AT`. Only available with `language=auto`. You
327    /// should set variants for at least German and English, as otherwise the
328    /// spell checking will not work for those, as no spelling dictionary can be
329    /// selected for just `en` or `de`.
330    #[cfg_attr(feature = "cli", clap(long, conflicts_with = "language"))]
331    pub preferred_variants: Option<Vec<String>>,
332    /// IDs of rules to be enabled, comma-separated.
333    #[cfg_attr(feature = "cli", clap(long))]
334    pub enabled_rules: Option<Vec<String>>,
335    /// IDs of rules to be disabled, comma-separated.
336    #[cfg_attr(feature = "cli", clap(long))]
337    pub disabled_rules: Option<Vec<String>>,
338    /// IDs of categories to be enabled, comma-separated.
339    #[cfg_attr(feature = "cli", clap(long))]
340    pub enabled_categories: Option<Vec<String>>,
341    /// IDs of categories to be disabled, comma-separated.
342    #[cfg_attr(feature = "cli", clap(long))]
343    pub disabled_categories: Option<Vec<String>>,
344    /// If true, only the rules and categories whose IDs are specified with
345    /// `enabledRules` or `enabledCategories` are enabled.
346    #[cfg_attr(feature = "cli", clap(long))]
347    pub enabled_only: bool,
348    /// If set to `picky`, additional rules will be activated, i.e. rules that
349    /// you might only find useful when checking formal text.
350    #[cfg_attr(
351        feature = "cli",
352        clap(long, default_value = "default", ignore_case = true, value_enum)
353    )]
354    pub level: Level,
355}
356
357impl From<CliRequest> for Request<'_> {
358    fn from(val: CliRequest) -> Self {
359        Request {
360            text: val.text.map(Cow::Owned),
361            data: val.data.map(Into::into),
362            language: val.language,
363            username: val.username,
364            api_key: val.api_key,
365            dicts: val.dicts,
366            mother_tongue: val.mother_tongue,
367            preferred_variants: val.preferred_variants,
368            enabled_rules: val.enabled_rules,
369            disabled_rules: val.disabled_rules,
370            enabled_categories: val.enabled_categories,
371            disabled_categories: val.disabled_categories,
372            enabled_only: val.enabled_only,
373            level: val.level,
374        }
375    }
376}
377
378/// Alternative text to be checked.
379#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq, Hash)]
380#[non_exhaustive]
381pub struct CliData {
382    /// Vector of markup text, see [`DataAnnotation`].
383    pub annotation: Vec<CliDataAnnotation>,
384}
385
386impl From<CliData> for Data<'_> {
387    fn from(val: CliData) -> Self {
388        Data {
389            annotation: val
390                .annotation
391                .into_iter()
392                .map(|a| a.into())
393                .collect::<Vec<DataAnnotation>>(),
394        }
395    }
396}
397
398/// A portion of text to be checked.
399#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, Hash)]
400#[non_exhaustive]
401#[serde(rename_all = "camelCase")]
402pub struct CliDataAnnotation {
403    /// Text that should be treated as normal text.
404    ///
405    /// This or `markup` is required.
406    #[serde(skip_serializing_if = "Option::is_none")]
407    pub text: Option<String>,
408    /// Text that should be treated as markup.
409    ///
410    /// This or `text` is required.
411    #[serde(skip_serializing_if = "Option::is_none")]
412    pub markup: Option<String>,
413    /// If set, the markup will be interpreted as this.
414    #[serde(skip_serializing_if = "Option::is_none")]
415    pub interpret_as: Option<String>,
416}
417
418impl From<CliDataAnnotation> for DataAnnotation<'_> {
419    fn from(val: CliDataAnnotation) -> Self {
420        DataAnnotation {
421            text: val.text.map(Cow::Owned),
422            markup: val.markup.map(Cow::Owned),
423            interpret_as: val.interpret_as.map(Cow::Owned),
424        }
425    }
426}
427
428impl std::str::FromStr for CliData {
429    type Err = Error;
430
431    fn from_str(s: &str) -> Result<Self> {
432        let v: Self = serde_json::from_str(s)?;
433        Ok(v)
434    }
435}
436
437#[cfg(test)]
438mod test {
439    use super::*;
440
441    #[test]
442    fn test_read_from_stdin() {
443        let handle = std::thread::spawn(|| {
444            let mut buffer = String::new();
445            read_from_stdin(&mut buffer).unwrap();
446            buffer
447        });
448
449        std::thread::sleep(std::time::Duration::from_millis(100));
450
451        if std::io::stdin().is_terminal() {
452            assert!(!handle.is_finished());
453        } else {
454            assert!(handle.is_finished());
455        }
456    }
457}