Skip to content

Commit fdb7bd7

Browse files
authored
Merge pull request #7936 from Its-Just-Nans/fix-doc-hashs
fix docs test
2 parents 6736e5f + 2c3e55a commit fdb7bd7

File tree

4 files changed

+179
-15
lines changed

4 files changed

+179
-15
lines changed

src/bin/uudoc.rs

Lines changed: 55 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,8 @@ fn gen_manpage<T: Args>(
8484
} else {
8585
validation::setup_localization_or_exit(utility);
8686
let mut cmd = util_map.get(utility).unwrap().1();
87+
cmd.set_bin_name(utility.clone());
88+
let mut cmd = cmd.display_name(utility);
8789
if let Some(zip) = tldr {
8890
if let Ok(examples) = write_zip_examples(zip, utility, false) {
8991
cmd = cmd.after_help(examples);
@@ -274,12 +276,15 @@ fn main() -> io::Result<()> {
274276

275277
println!("Writing to utils");
276278
for (&name, (_, command)) in utils {
277-
if name == "[" {
278-
continue;
279-
}
280-
let p = format!("docs/src/utils/{name}.md");
279+
let (utils_name, usage_name, command) = match name {
280+
"[" => {
281+
continue;
282+
}
283+
n => (n, n, command),
284+
};
285+
let p = format!("docs/src/utils/{usage_name}.md");
281286

282-
let fluent = File::open(format!("src/uu/{name}/locales/en-US.ftl"))
287+
let fluent = File::open(format!("src/uu/{utils_name}/locales/en-US.ftl"))
283288
.and_then(|mut f: File| {
284289
let mut s = String::new();
285290
f.read_to_string(&mut s)?;
@@ -291,28 +296,51 @@ fn main() -> io::Result<()> {
291296
MDWriter {
292297
w: Box::new(f),
293298
command: command(),
294-
name,
299+
name: usage_name,
295300
tldr_zip: &mut tldr_zip,
296301
utils_per_platform: &utils_per_platform,
297302
fluent,
303+
fluent_key: utils_name.to_string(),
298304
}
299305
.markdown()?;
300306
println!("Wrote to '{p}'");
301307
} else {
302308
println!("Error writing to {p}");
303309
}
304-
writeln!(summary, "* [{name}](utils/{name}.md)")?;
310+
writeln!(summary, "* [{usage_name}](utils/{usage_name}.md)")?;
305311
}
306312
Ok(())
307313
}
308314

315+
fn fix_usage(name: &str, usage: String) -> String {
316+
match name {
317+
"test" => {
318+
// replace to [ but not the first two line
319+
usage
320+
.lines()
321+
.enumerate()
322+
.map(|(i, l)| {
323+
if i > 1 {
324+
l.replace("test", "[")
325+
} else {
326+
l.to_string()
327+
}
328+
})
329+
.collect::<Vec<_>>()
330+
.join("\n")
331+
}
332+
_ => usage,
333+
}
334+
}
335+
309336
struct MDWriter<'a, 'b> {
310337
w: Box<dyn Write>,
311338
command: Command,
312339
name: &'a str,
313340
tldr_zip: &'b mut Option<ZipArchive<File>>,
314341
utils_per_platform: &'b HashMap<&'b str, Vec<String>>,
315342
fluent: Option<String>,
343+
fluent_key: String,
316344
}
317345

318346
impl MDWriter<'_, '_> {
@@ -343,9 +371,20 @@ impl MDWriter<'_, '_> {
343371
if id.name == key {
344372
// Simple text extraction - just concatenate text elements
345373
let mut result = String::new();
374+
use fluent_syntax::ast::{
375+
Expression, InlineExpression,
376+
PatternElement::{Placeable, TextElement},
377+
};
346378
for element in elements {
347-
if let fluent_syntax::ast::PatternElement::TextElement { value } = element {
348-
result.push_str(&value);
379+
if let TextElement { ref value } = element {
380+
result.push_str(value);
381+
}
382+
if let Placeable {
383+
expression:
384+
Expression::Inline(InlineExpression::StringLiteral { ref value }),
385+
} = element
386+
{
387+
result.push_str(value);
349388
}
350389
}
351390
return Some(result);
@@ -403,7 +442,8 @@ impl MDWriter<'_, '_> {
403442
/// # Errors
404443
/// Returns an error if the writer fails.
405444
fn usage(&mut self) -> io::Result<()> {
406-
if let Some(usage) = self.extract_fluent_value(&format!("{}-usage", self.name)) {
445+
if let Some(usage) = self.extract_fluent_value(&format!("{}-usage", self.fluent_key)) {
446+
let usage = fix_usage(self.name, usage);
407447
writeln!(self.w, "\n```")?;
408448
writeln!(self.w, "{usage}")?;
409449
writeln!(self.w, "```")
@@ -415,7 +455,7 @@ impl MDWriter<'_, '_> {
415455
/// # Errors
416456
/// Returns an error if the writer fails.
417457
fn about(&mut self) -> io::Result<()> {
418-
if let Some(about) = self.extract_fluent_value(&format!("{}-about", self.name)) {
458+
if let Some(about) = self.extract_fluent_value(&format!("{}-about", self.fluent_key)) {
419459
writeln!(self.w, "{about}")
420460
} else {
421461
Ok(())
@@ -425,7 +465,9 @@ impl MDWriter<'_, '_> {
425465
/// # Errors
426466
/// Returns an error if the writer fails.
427467
fn after_help(&mut self) -> io::Result<()> {
428-
if let Some(after_help) = self.extract_fluent_value(&format!("{}-after-help", self.name)) {
468+
if let Some(after_help) =
469+
self.extract_fluent_value(&format!("{}-after-help", self.fluent_key))
470+
{
429471
writeln!(self.w, "\n\n{after_help}")
430472
} else {
431473
Ok(())
@@ -498,7 +540,7 @@ impl MDWriter<'_, '_> {
498540
writeln!(self.w, "</dt>")?;
499541
let help_text = arg.get_help().unwrap_or_default().to_string();
500542
// Try to resolve Fluent key if it looks like one, otherwise use as-is
501-
let resolved_help = if help_text.starts_with(&format!("{}-help-", self.name)) {
543+
let resolved_help = if help_text.starts_with(&format!("{}-help-", self.fluent_key)) {
502544
self.extract_fluent_value(&help_text).unwrap_or(help_text)
503545
} else {
504546
help_text

src/uu/test/locales/en-US.ftl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ test-usage = test EXPRESSION
33
test
44
{"[ EXPRESSION ]"}
55
{"[ ]"}
6-
{"[ OPTION ]"}
6+
{"[ OPTION"}
77
test-after-help = Exit with the status determined by EXPRESSION.
88
99
An omitted EXPRESSION defaults to false.

src/uu/test/locales/fr-FR.ftl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ test-usage = test EXPRESSION
33
test
44
{"[ EXPRESSION ]"}
55
{"[ ]"}
6-
{"[ OPTION ]"}
6+
{"[ OPTION"}
77
test-after-help = Quitter avec le statut déterminé par EXPRESSION.
88
99
Une EXPRESSION omise vaut false par défaut.

tests/test_uudoc.rs

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
//! Tests on the `uudoc` binary.
2+
//!
3+
//! To run the uudoc
4+
//! ```
5+
//! cargo run --bin uudoc --features uudoc
6+
//! ```
7+
//!
8+
//! To run the tests
9+
//! ```
10+
//! cargo test --features uudoc
11+
//! ```
12+
#![cfg(feature = "uudoc")]
13+
14+
use std::env;
15+
pub const TESTS_BINARY: &str = env!("CARGO_BIN_EXE_uudoc");
16+
17+
// Set the environment variable for any tests
18+
19+
// Use the ctor attribute to run this function before any tests
20+
#[ctor::ctor]
21+
fn init() {
22+
// No need for unsafe here
23+
unsafe {
24+
std::env::set_var("UUTESTS_BINARY_PATH", TESTS_BINARY);
25+
}
26+
// Print for debugging
27+
eprintln!("Setting UUTESTS_BINARY_PATH={TESTS_BINARY}");
28+
}
29+
30+
/// Run the `uudoc` command and return the output as a vector of strings.
31+
/// # Errors
32+
/// If the command fails to execute or if the output cannot be converted to UTF-8, an `io::Error` is returned.
33+
fn run_write_doc() -> Vec<String> {
34+
use std::process::Command;
35+
use uutests::util::TestScenario;
36+
37+
let scenario = TestScenario::new("");
38+
let output = Command::new(&scenario.bin_path).output().unwrap();
39+
assert!(
40+
output.status.success(),
41+
"uudoc command failed: {}",
42+
String::from_utf8_lossy(&output.stderr)
43+
);
44+
45+
String::from_utf8(output.stdout)
46+
.unwrap()
47+
.lines()
48+
.map(String::from)
49+
.filter(|line| line.starts_with("Wrote"))
50+
.collect::<Vec<String>>()
51+
}
52+
53+
fn get_doc_file_from_output(output: &str) -> (String, String) {
54+
let correct_path_test = output
55+
.strip_prefix("Wrote to '")
56+
.unwrap()
57+
.strip_suffix("'")
58+
.unwrap()
59+
.to_string();
60+
let content = std::fs::read_to_string(&correct_path_test);
61+
let content = match content {
62+
Ok(content) => content,
63+
Err(e) => {
64+
panic!(
65+
"Failed to read file {}: {} from {:?}",
66+
correct_path_test,
67+
e,
68+
env::current_dir()
69+
);
70+
}
71+
};
72+
(correct_path_test, content)
73+
}
74+
75+
#[test]
76+
fn uudoc_check_test() {
77+
let pages = run_write_doc();
78+
// assert wrote to the correct file
79+
let path_test = pages.iter().find(|line| line.contains("test.md")).unwrap();
80+
let (correct_path, content) = get_doc_file_from_output(path_test);
81+
82+
// open the file
83+
assert!(
84+
content.contains(
85+
"```
86+
test EXPRESSION
87+
test
88+
[ EXPRESSION ]
89+
[ ]
90+
[ OPTION
91+
```
92+
",
93+
),
94+
"{correct_path} does not contains the required text"
95+
);
96+
}
97+
98+
#[test]
99+
fn uudoc_check_sums() {
100+
let pages = run_write_doc();
101+
let sums = [
102+
"md5sum",
103+
"sha1sum",
104+
"sha224sum",
105+
"sha256sum",
106+
"sha384sum",
107+
"sha512sum",
108+
"b2sum",
109+
];
110+
for one_sum in sums {
111+
let output_path = pages
112+
.iter()
113+
.find(|one_line| one_line.contains(one_sum))
114+
.unwrap();
115+
let (correct_path, content) = get_doc_file_from_output(output_path);
116+
let formatted = format!("```\n{one_sum} [OPTIONS] [FILE]...\n```");
117+
assert!(
118+
content.contains(&formatted),
119+
"Content of {correct_path} does not contain the expected format: {formatted}",
120+
);
121+
}
122+
}

0 commit comments

Comments
 (0)