1#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use anyhow::{Context, Result, ensure};
30use ctb_storage_minimal::global_graph_layout::{
31 FORMAT_REGION_END, FORMAT_REGION_START, SHORT_DC_REGION_END,
32 SHORT_DC_REGION_START, UNICODE_REGION_END, dc_to_gid, format_to_gid,
33 get_block_name_for_id, gid_to_short,
34};
35
36#[derive(clap::Args, Debug, Clone, PartialEq, Eq, Default)]
38#[command(
39 name = "short-dc",
40 after_help = "Examples:\n $ ctoolbox short-dc 296\n 1114408\n\n $ ctoolbox short-dc f80\n 2228304\n\n $ ctoolbox short-dc -i 296"
41)]
42pub struct ShortDcArgs {
43 pub id: String,
45
46 #[arg(short = 'i', long = "info")]
48 pub info: bool,
49}
50
51#[derive(clap::Args, Debug, Clone, PartialEq, Eq, Default)]
53#[command(
54 name = "gid",
55 after_help = "Examples:\n $ ctoolbox gid --s 1114408\n dc:296\n\n $ ctoolbox gid -i 1114408"
56)]
57pub struct GidArgs {
58 pub id: String,
60
61 #[arg(short = 's', long = "short", alias = "s")]
63 pub short: bool,
64
65 #[arg(short = 'i', long = "info")]
67 pub info: bool,
68}
69
70fn parse_number_literal(s: &str) -> Result<u128> {
71 let trimmed = s.trim();
72 if let Some(hex_str) = trimmed
73 .strip_prefix("0x")
74 .or_else(|| trimmed.strip_prefix("0X"))
75 {
76 u128::from_str_radix(hex_str, 16)
77 .with_context(|| format!("Invalid hex literal: {trimmed}"))
78 } else {
79 trimmed
80 .parse::<u128>()
81 .with_context(|| format!("Invalid integer literal: {trimmed}"))
82 }
83}
84
85pub fn parse_graph_or_short_id(input: &str) -> Result<u128> {
87 let trimmed = input.trim();
88 if let Some(rest) = trimmed
89 .strip_prefix("dc:")
90 .or_else(|| trimmed.strip_prefix("dc/"))
91 {
92 let short_id = parse_number_literal(rest)?;
93 let dc_u64 = u64::try_from(short_id)
94 .context("Dc ID exceeds 64-bit addressable range")?;
95 Ok(dc_to_gid(dc_u64))
96 } else if let Some(rest) = trimmed
97 .strip_prefix("fmt:")
98 .or_else(|| trimmed.strip_prefix("fmt/"))
99 {
100 let short_id = parse_number_literal(rest)?;
101 let fmt_u64 = u64::try_from(short_id)
102 .context("Format ID exceeds 64-bit addressable range")?;
103 Ok(format_to_gid(fmt_u64))
104 } else if let Some(rest) = trimmed
105 .strip_prefix("uni:")
106 .or_else(|| trimmed.strip_prefix("uni/"))
107 .or_else(|| trimmed.strip_prefix("U+"))
108 .or_else(|| trimmed.strip_prefix("u+"))
109 {
110 let cp =
111 if rest.chars().all(|c| c.is_ascii_hexdigit()) && rest.len() <= 6 {
112 u128::from_str_radix(rest, 16)?
113 } else {
114 parse_number_literal(rest)?
115 };
116 ensure!(
117 cp <= UNICODE_REGION_END,
118 "Unicode code point exceeds 0x10FFFF maximum: {cp}"
119 );
120 Ok(cp)
121 } else if let Some(rest) = trimmed
122 .strip_prefix("gid:")
123 .or_else(|| trimmed.strip_prefix("gid/"))
124 {
125 parse_number_literal(rest)
126 } else {
127 parse_number_literal(trimmed)
128 }
129}
130
131pub fn describe_gid_metadata(gid: u128) -> Result<String> {
133 if gid <= UNICODE_REGION_END {
134 let cp = u32::try_from(gid).context("Invalid Unicode code point")?;
135 let desc =
136 ctb_formats_unicode::character_description::describe_codepoint(cp);
137 Ok(format!("{gid}\n{desc}\n"))
138 } else if (SHORT_DC_REGION_START..=SHORT_DC_REGION_END).contains(&gid) {
139 let dc_id = u32::try_from(gid.saturating_sub(SHORT_DC_REGION_START))
140 .context("Invalid Dc ID range")?;
141 let desc = crate::character_description::describe_dc(dc_id)?;
142 Ok(format!("{desc}\n"))
143 } else if (FORMAT_REGION_START..=FORMAT_REGION_END).contains(&gid) {
144 let fmt_id = usize::try_from(gid.saturating_sub(FORMAT_REGION_START))
145 .context("Invalid Format ID range")?;
146 let desc = ctb_formats_utilities::describe_format(fmt_id)?;
147 Ok(format!("{desc}\n"))
148 } else {
149 let block = match get_block_name_for_id(gid) {
150 Ok(name) => name,
151 Err(_) => "Reserved".to_string(),
152 };
153 Ok(format!("{gid}\nBlock: {block}\n"))
154 }
155}
156
157pub fn execute_cli_short_dc(args: &ShortDcArgs) -> Result<String> {
159 let shorthand =
160 ctb_storage_minimal::shorthand::DcShorthand::parse(&args.id)?;
161 let gid = shorthand.to_global_id()?;
162
163 if args.info {
164 describe_gid_metadata(gid)
165 } else {
166 Ok(format!("{gid}\n"))
167 }
168}
169
170pub fn execute_cli_gid(args: &GidArgs) -> Result<String> {
172 let gid = parse_graph_or_short_id(&args.id)?;
173
174 if args.info {
175 describe_gid_metadata(gid)
176 } else {
177 let short = gid_to_short(gid);
178 Ok(format!("{short}\n"))
179 }
180}
181
182#[derive(clap::Args, Debug, Clone, PartialEq, Eq, Default)]
184#[command(
185 name = "explain-ctbnodes",
186 after_help = "Examples:\n $ ctoolbox explain-ctbnodes assets/data/graph/85899_34592.ctbnodes\n $ ctoolbox explain-ctbnodes assets/data/graph/85900_04692.ctbnodes -o explained.ctbnodes"
187)]
188pub struct ExplainCtbnodesArgs {
189 pub file: std::path::PathBuf,
191
192 #[arg(short = 'o', long = "output")]
194 pub output: Option<std::path::PathBuf>,
195
196 #[arg(long = "graph-dir")]
198 pub graph_dir: Option<std::path::PathBuf>,
199}
200
201pub fn execute_cli_explain_ctbnodes<F>(
204 args: &ExplainCtbnodesArgs,
205 read_file_or_stdin: F,
206) -> Result<Option<Vec<u8>>>
207where
208 F: FnOnce(&std::path::Path) -> Result<Vec<u8>>,
209{
210 let rendered = if args.file == std::path::Path::new("-") {
211 let raw = read_file_or_stdin(&args.file)?;
212 let content = String::from_utf8(raw)
213 .context("Standard input for explain-ctbnodes is not valid UTF-8")?;
214 ctb_formats_dcdata::graph_ledger::explain_ctbnodes_str(
215 &content,
216 "<stdin>",
217 args.graph_dir.as_deref(),
218 )?
219 } else {
220 ctb_formats_dcdata::graph_ledger::explain_ctbnodes_file(
221 &args.file,
222 args.graph_dir.as_deref(),
223 )?
224 };
225
226 if let Some(out_path) = &args.output
227 && out_path != std::path::Path::new("-")
228 {
229 if let Some(parent) = out_path.parent()
230 && !parent.as_os_str().is_empty()
231 {
232 std::fs::create_dir_all(parent).with_context(|| {
233 format!("Failed to create directory {}", parent.display())
234 })?;
235 }
236 std::fs::write(out_path, rendered.as_bytes()).with_context(|| {
237 format!("Failed to write {}", out_path.display())
238 })?;
239 return Ok(None);
240 }
241
242 Ok(Some(rendered.into_bytes()))
243}
244
245#[cfg(test)]
246#[allow(
247 clippy::panic,
248 clippy::expect_used,
249 clippy::unwrap_used,
250 clippy::unwrap_in_result,
251 clippy::panic_in_result_fn,
252 clippy::indexing_slicing,
253 clippy::arithmetic_side_effects,
254 reason = "Standard repository test boilerplate"
255)]
256mod tests {
257 use super::*;
258
259 #[crate::ctb_test]
260 fn test_short_dc_execution() {
261 let out = execute_cli_short_dc(&ShortDcArgs {
262 id: "296".to_string(),
263 info: false,
264 })
265 .expect("short-dc 296");
266 assert_eq!(out, "1114408\n");
267
268 let out_info = execute_cli_short_dc(&ShortDcArgs {
269 id: "296".to_string(),
270 info: true,
271 })
272 .expect("short-dc -i 296");
273 assert!(
274 out_info.starts_with(
275 "1114408\nNext number is a Dc-equivalent reference"
276 )
277 );
278 assert!(out_info.contains("Type: !Cx (Control: Dc special)"));
279 assert!(out_info.contains("Syntax: :~ [number]"));
280
281 let out_308 = execute_cli_short_dc(&ShortDcArgs {
282 id: "308".to_string(),
283 info: false,
284 })
285 .expect("short-dc 308");
286 assert_eq!(out_308, "1114420\n");
287
288 let out_308_info = execute_cli_short_dc(&ShortDcArgs {
289 id: "308".to_string(),
290 info: true,
291 })
292 .expect("short-dc -i 308");
293 assert!(
294 out_308_info.starts_with(
295 "1114420\nNext number is a long (global graph) Dc"
296 )
297 );
298 let out_fmt = execute_cli_short_dc(&ShortDcArgs {
300 id: "f80".to_string(),
301 info: false,
302 })
303 .expect("short-dc f80");
304 assert_eq!(out_fmt, "2228304\n");
305
306 let out_fmt_info = execute_cli_short_dc(&ShortDcArgs {
307 id: "f80".to_string(),
308 info: true,
309 })
310 .expect("short-dc -i f80");
311 assert!(
312 out_fmt_info.starts_with("2228304\nString\n\nCategory: semantic")
313 );
314
315 let out_uni = execute_cli_short_dc(&ShortDcArgs {
317 id: "u12a".to_string(),
318 info: false,
319 })
320 .expect("short-dc u12a");
321 assert_eq!(out_uni, "298\n");
322
323 let out_uni_info = execute_cli_short_dc(&ShortDcArgs {
324 id: "u12a".to_string(),
325 info: true,
326 })
327 .expect("short-dc -i u12a");
328 assert!(out_uni_info.contains("LATIN CAPITAL LETTER I WITH MACRON"));
329
330 let out_long = execute_cli_short_dc(&ShortDcArgs {
332 id: "l1114408".to_string(),
333 info: false,
334 })
335 .expect("short-dc l1114408");
336 assert_eq!(out_long, "1114408\n");
337
338 execute_cli_short_dc(&ShortDcArgs {
340 id: "dc:296".to_string(),
341 info: false,
342 })
343 .unwrap_err();
344
345 execute_cli_short_dc(&ShortDcArgs {
346 id: "0x128".to_string(),
347 info: false,
348 })
349 .unwrap_err();
350
351 execute_cli_short_dc(&ShortDcArgs {
353 id: "L42".to_string(),
354 info: false,
355 })
356 .unwrap_err();
357
358 execute_cli_short_dc(&ShortDcArgs {
360 id: "F80".to_string(),
361 info: false,
362 })
363 .unwrap_err();
364 }
365
366 #[crate::ctb_test]
367 fn test_gid_execution() {
368 let out_dc = execute_cli_gid(&GidArgs {
370 id: "1114408".to_string(),
371 short: true,
372 info: false,
373 })
374 .expect("gid --s 1114408");
375 assert_eq!(out_dc, "dc:296\n");
376
377 let out_fmt = execute_cli_gid(&GidArgs {
378 id: "2228304".to_string(),
379 short: true,
380 info: false,
381 })
382 .expect("gid --s 2228304");
383 assert_eq!(out_fmt, "fmt:80\n");
384
385 let out_uni = execute_cli_gid(&GidArgs {
386 id: "1234".to_string(),
387 short: true,
388 info: false,
389 })
390 .expect("gid --s 1234");
391 assert_eq!(out_uni, "uni:1234\n");
392
393 let out_other = execute_cli_gid(&GidArgs {
394 id: "23234234".to_string(),
395 short: true,
396 info: false,
397 })
398 .expect("gid --s 23234234");
399 assert_eq!(out_other, "gid:23234234\n");
400
401 let out_dc_info = execute_cli_gid(&GidArgs {
403 id: "1114408".to_string(),
404 short: false,
405 info: true,
406 })
407 .expect("gid -i 1114408");
408 assert!(
409 out_dc_info.starts_with(
410 "1114408\nNext number is a Dc-equivalent reference"
411 )
412 );
413
414 let out_fmt_info = execute_cli_gid(&GidArgs {
415 id: "2228304".to_string(),
416 short: false,
417 info: true,
418 })
419 .expect("gid -i 2228304");
420 assert!(out_fmt_info.starts_with("2228304\nString"));
421
422 let out_uni_info = execute_cli_gid(&GidArgs {
423 id: "65".to_string(),
424 short: false,
425 info: true,
426 })
427 .expect("gid -i 65");
428 assert!(out_uni_info.contains("LATIN CAPITAL LETTER A"));
429 }
430
431 #[crate::ctb_test]
432 fn test_gid_command() {
433 let cmd_gid_short = GidArgs {
434 id: "1114408".to_string(),
435 short: true,
436 info: false,
437 };
438 let res_gid_short =
439 execute_cli_gid(&cmd_gid_short).expect("Run gid --s");
440 assert_eq!(res_gid_short, "dc:296\n");
441
442 let cmd_gid_info = GidArgs {
443 id: "1114408".to_string(),
444 short: false,
445 info: true,
446 };
447 let res_gid_info = execute_cli_gid(&cmd_gid_info).expect("Run gid -i");
448 assert!(
449 res_gid_info.starts_with(
450 "1114408\nNext number is a Dc-equivalent reference"
451 )
452 );
453 }
454
455 #[crate::ctb_test]
456 fn test_explain_ctbnodes_cli_execution() {
457 let sample = "l8589934592: u68 u69 # @created_ns:1700000000000000000\n\
458 l8589934593: 584 296 574\n\
459 l8589934594: 610 l8589934593 l8589934592\n";
460 let out_bytes = execute_cli_explain_ctbnodes(
461 &ExplainCtbnodesArgs {
462 file: std::path::PathBuf::from("-"),
463 output: None,
464 graph_dir: None,
465 },
466 |_| Ok(sample.as_bytes().to_vec()),
467 )
468 .expect("explain-ctbnodes on stdin must succeed")
469 .expect("stdout bytes");
470 let text = String::from_utf8(out_bytes).unwrap();
471 let lines: Vec<&str> = text.lines().collect();
472 assert_eq!(lines.len(), 3);
473 assert_eq!(
474 lines[0],
475 "l8589934592: u68 u69 # @created_ns:1700000000000000000 \"hi\""
476 );
477 assert!(lines[1].contains("Has a (") && lines[1].contains("Programmatic identifier)"));
478 assert!(
479 lines[2].contains("Has value (Has a (")
480 && lines[2].contains("Programmatic identifier), \"hi\")")
481 );
482 }
483}