1use 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
29fn 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#[derive(Debug, Parser)]
44pub struct Command {
45 #[clap(short = 'r', long)]
49 pub raw: bool,
50 #[clap(long, default_value_t = 1500)]
52 pub max_length: usize,
53 #[clap(long, default_value = "\n\n")]
55 pub split_pattern: String,
56 #[clap(long, default_value_t = 5, allow_negative_numbers = true)]
58 pub max_suggestions: isize,
59 #[clap(long, value_enum, default_value_t = FileType::default(), ignore_case = true)]
63 pub r#type: FileType,
64 #[arg(conflicts_with_all(["text", "data"]), value_parser = parse_filename)]
66 pub filenames: Vec<PathBuf>,
67 #[command(flatten, next_help_heading = "Request options")]
69 pub request: CliRequest,
70}
71
72#[derive(Clone, Debug, Default, ValueEnum)]
74#[non_exhaustive]
75pub enum FileType {
76 #[default]
78 Auto,
79 Raw,
81 Markdown,
83 Html,
85 Typst,
87}
88
89fn 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 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 if self.filenames.is_empty() {
117 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 let requests = request.split(self.max_length, self.split_pattern.as_str());
131
132 if self.raw {
133 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 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 for filename in self.filenames.iter() {
163 let mut file_type = self.r#type.clone();
164
165 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 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#[derive(Args, Clone, Debug, Default, PartialEq, Eq, Hash)]
251#[non_exhaustive]
252pub struct CliRequest {
253 #[clap(short = 't', long, conflicts_with = "data", allow_hyphen_values(true))]
257 pub text: Option<String>,
258 #[clap(short = 'd', long, conflicts_with = "text")]
283 pub data: Option<CliData>,
284 #[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 #[cfg_attr(
303 feature = "cli",
304 clap(short = 'u', long, requires = "api_key", env = "LANGUAGETOOL_USERNAME")
305 )]
306 pub username: Option<String>,
307 #[cfg_attr(
309 feature = "cli",
310 clap(short = 'k', long, requires = "username", env = "LANGUAGETOOL_API_KEY")
311 )]
312 pub api_key: Option<String>,
313 #[cfg_attr(feature = "cli", clap(long))]
316 pub dicts: Option<Vec<String>>,
317 #[cfg_attr(feature = "cli", clap(long))]
320 pub mother_tongue: Option<String>,
321 #[cfg_attr(feature = "cli", clap(long, conflicts_with = "language"))]
331 pub preferred_variants: Option<Vec<String>>,
332 #[cfg_attr(feature = "cli", clap(long))]
334 pub enabled_rules: Option<Vec<String>>,
335 #[cfg_attr(feature = "cli", clap(long))]
337 pub disabled_rules: Option<Vec<String>>,
338 #[cfg_attr(feature = "cli", clap(long))]
340 pub enabled_categories: Option<Vec<String>>,
341 #[cfg_attr(feature = "cli", clap(long))]
343 pub disabled_categories: Option<Vec<String>>,
344 #[cfg_attr(feature = "cli", clap(long))]
347 pub enabled_only: bool,
348 #[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#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq, Hash)]
380#[non_exhaustive]
381pub struct CliData {
382 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#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, Hash)]
400#[non_exhaustive]
401#[serde(rename_all = "camelCase")]
402pub struct CliDataAnnotation {
403 #[serde(skip_serializing_if = "Option::is_none")]
407 pub text: Option<String>,
408 #[serde(skip_serializing_if = "Option::is_none")]
412 pub markup: Option<String>,
413 #[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}