ctb_formats_wfscan/
wfscan.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Port of wfparser and wfscan Perl programs.
21//!
22//! Note that wfscan isn't itself a format; these are utilities for working
23//! with other formats.
24
25#[allow(
26    unused_imports,
27    clippy::wildcard_imports,
28    reason = "Standard workspace crate prelude"
29)]
30pub(crate) use ctb_utilities::*;
31
32pub mod cli;
33
34use regex::Regex;
35use std::path::Path;
36
37/// Returns the fixture data from the wfscan/fixtures folder.
38#[cfg(test)]
39pub fn get_wfscan_data(key: &str) -> Option<Vec<u8>> {
40    ctb_utilities::load_manifest_fixture(env!("CARGO_MANIFEST_DIR"), key)
41}
42
43/// Parses the binary data of a file using the same logic as the original
44/// `wfparser.pl` program.
45pub fn wfparse(data: &[u8]) -> Result<Vec<u8>> {
46    let decoded = ctb_formats_perl::unicode::perl_utf8_decode(data)?;
47
48    let re_open = Regex::new(r"<\w+>")?;
49    let mut s = re_open.replace_all(&decoded, " ").into_owned();
50
51    let re_close = Regex::new(r"<\\\W+>")?;
52    s = re_close.replace_all(&s, " ").into_owned();
53
54    let re_start_c = Regex::new(r"^C")?;
55    s = re_start_c.replace_all(&s, " ").into_owned();
56
57    s = s.replace('\u{FFFD}', " ");
58    s.push('\n');
59
60    Ok(s.into_bytes())
61}
62
63/// Reads a file from disk and parses it using `wfparse`.
64pub fn wfparse_file<P: AsRef<Path>>(path: P) -> Result<Vec<u8>> {
65    let data = std::fs::read(path)?;
66    wfparse(&data)
67}
68
69/// Scans the binary data of a file using the same logic as the original
70/// `wfscan.pl` program.
71pub fn wfscan(data: &[u8]) -> Result<Vec<u8>> {
72    let mut s: String = data.iter().map(|&b| char::from(b)).collect();
73
74    s = s.replace('\n', " ");
75
76    let re_open = Regex::new(r"<[a-zA-Z0-9_]+>")?;
77    s = re_open.replace_all(&s, " ").into_owned();
78
79    let re_close = Regex::new(r"<\\[^a-zA-Z0-9_]+>")?;
80    s = re_close.replace_all(&s, " ").into_owned();
81
82    let re_non_word = Regex::new(r"[^a-zA-Z0-9_]")?;
83    s = re_non_word.replace_all(&s, " ").into_owned();
84
85    let re_spaces = Regex::new(r" +")?;
86    s = re_spaces.replace_all(&s, " ").into_owned();
87
88    s = s.to_ascii_lowercase();
89
90    s = s.replace(" ,", ",");
91    s.push('\n');
92
93    Ok(s.into_bytes())
94}
95
96/// Reads a file from disk and scans it using `wfscan`.
97pub fn wfscan_file<P: AsRef<Path>>(path: P) -> Result<Vec<u8>> {
98    let data = std::fs::read(path)?;
99    wfscan(&data)
100}
101
102#[cfg(test)]
103#[allow(
104    clippy::panic,
105    clippy::expect_used,
106    clippy::unwrap_used,
107    clippy::unwrap_in_result,
108    clippy::panic_in_result_fn,
109    clippy::indexing_slicing,
110    clippy::arithmetic_side_effects,
111    reason = "Standard repository test boilerplate"
112)]
113mod tests {
114    use super::*;
115
116    #[crate::ctb_test]
117    fn test_wfparser_wfscan_fixtures() {
118        let input_data = get_wfscan_data("fixtures/Sample with patterns.pan")
119            .expect("input fixture not found");
120        let parser_expected = get_wfscan_data(
121            "fixtures/Sample_with_patterns.pan.parser.expected",
122        )
123        .expect("parser expected fixture not found");
124        let scanner_expected = get_wfscan_data(
125            "fixtures/Sample_with_patterns.pan.scanner.expected",
126        )
127        .expect("scanner expected fixture not found");
128
129        let parser_actual = wfparse(&input_data).expect("wfparse failed");
130        let scanner_actual = wfscan(&input_data).expect("wfscan failed");
131
132        assert_eq!(parser_actual, parser_expected);
133        assert_eq!(scanner_actual, scanner_expected);
134    }
135}