use enclose_strings::SimpleExtract;
use spreadsheet_to_json::{Column, DateTimeMode, Format, Identifier, KeySegment};
use std::sync::Arc;
#[derive(Debug, Clone, Copy, PartialEq)]
enum CaptureType {
Int,
Str,
}
const ANONYMOUS_CAPTURE: &str = "*";
struct SourcePattern {
prefix: String,
capture_name: String,
capture_type: CaptureType,
}
fn parse_source_pattern(source: &str) -> Option<SourcePattern> {
let lower = source.to_lowercase();
if let Some(prefix) = lower.strip_suffix('*') {
if !prefix.is_empty() {
return Some(SourcePattern { prefix: prefix.to_string(), capture_name: ANONYMOUS_CAPTURE.to_string(), capture_type: CaptureType::Str });
}
}
if lower.ends_with(']') {
if let Some(open) = lower.find('[') {
if open == 0 {
return None; }
let name = lower.extract_from_brackets()?;
let (capture_name, capture_type) = if name.is_empty() {
(ANONYMOUS_CAPTURE.to_string(), CaptureType::Str) } else {
(name, CaptureType::Int)
};
return Some(SourcePattern { prefix: lower[..open].to_string(), capture_name, capture_type });
}
}
if lower.ends_with('}') {
if let Some(open) = lower.find('{') {
let name = lower.extract_from_braces().filter(|n| !n.is_empty())?;
return Some(SourcePattern { prefix: lower[..open].to_string(), capture_name: name, capture_type: CaptureType::Str });
}
}
None
}
enum TargetToken {
Literal(String),
ArrayOpen(String),
Braces(Vec<String>),
}
fn parse_target_tokens(target: &str) -> Option<Vec<TargetToken>> {
target.split('.').map(parse_target_segment).collect()
}
fn parse_target_segment(segment: &str) -> Option<TargetToken> {
if let Some(name) = segment.strip_suffix("[]") {
if !name.is_empty() {
return Some(TargetToken::ArrayOpen(name.to_string()));
}
}
if segment.starts_with('{') {
return parse_brace_groups(segment).map(TargetToken::Braces);
}
if !segment.is_empty() {
return Some(TargetToken::Literal(segment.to_string()));
}
None
}
fn parse_brace_groups(mut segment: &str) -> Option<Vec<String>> {
let mut groups = Vec::new();
while !segment.is_empty() {
if !segment.starts_with('{') {
return None;
}
let content = segment.extract_from_braces().filter(|c| !c.is_empty())?;
let consumed = content.len() + 2; if consumed > segment.len() {
return None;
}
segment = &segment[consumed..];
groups.push(content);
}
if groups.is_empty() { None } else { Some(groups) }
}
fn build_key_segment(tokens: &[TargetToken], capture_name: &str, capture_id: &Identifier) -> Option<KeySegment> {
let (first, rest) = tokens.split_first()?;
match first {
TargetToken::Literal(name) => {
let next = build_key_segment(rest, capture_name, capture_id)?;
Some(KeySegment::Object(Arc::from(name.as_str()), Arc::new(next)))
}
TargetToken::ArrayOpen(name) => {
if rest.is_empty() {
return Some(KeySegment::PlainArray(Arc::from(name.as_str())));
}
let (TargetToken::Braces(names), rest2) = rest.split_first()? else { return None };
if !rest2.is_empty() {
return None; }
build_array_with_braces(name, names, capture_name, capture_id)
}
TargetToken::Braces(names) => {
if !rest.is_empty() {
return None; }
let [name] = names.as_slice() else { return None };
(name == capture_name).then(|| KeySegment::Simple(Arc::from(capture_id.to_string().as_str())))
}
}
}
fn build_array_with_braces(container: &str, names: &[String], capture_name: &str, capture_id: &Identifier) -> Option<KeySegment> {
let (first, rest) = names.split_first()?;
if first != capture_name {
return None;
}
let chain = build_inner_object_chain(rest, capture_name, capture_id)?;
Some(KeySegment::Array(Arc::from(container), capture_id.clone(), Arc::from(first.as_str()), Arc::new(chain)))
}
fn build_inner_object_chain(names: &[String], capture_name: &str, capture_id: &Identifier) -> Option<KeySegment> {
let (name, rest) = names.split_first()?;
if name == capture_name {
let next = build_inner_object_chain(rest, capture_name, capture_id)?;
Some(KeySegment::InnerObject(capture_id.clone(), Arc::from(name.as_str()), Arc::new(next)))
} else if rest.is_empty() {
Some(KeySegment::Simple(Arc::from(name.as_str())))
} else {
None }
}
pub fn expand_pattern_entry(source: &str, target: &str, format: &Format, natural_keys: &[String]) -> Option<Vec<Column>> {
let pattern = parse_source_pattern(source)?;
let tokens = parse_target_tokens(target)?;
let placeholder_id = Identifier::from_string("__validate__");
build_key_segment(&tokens, &pattern.capture_name, &placeholder_id)?;
let columns: Vec<Column> = natural_keys
.iter()
.filter_map(|natural_key| {
let remainder = natural_key.strip_prefix(pattern.prefix.as_str())?;
if remainder.is_empty() {
return None;
}
let capture_id = match pattern.capture_type {
CaptureType::Int => Identifier::from_int_str(remainder),
CaptureType::Str => Identifier::from_string(remainder),
};
let key_segment = build_key_segment(&tokens, &pattern.capture_name, &capture_id)
.expect("already validated the same template above");
let mut col = Column::from_source_key_with_format(natural_key, None, format.clone(), None, DateTimeMode::Full, false);
col.key = Some(key_segment);
Some(col)
})
.collect();
Some(columns)
}
pub fn resolve_suppression_key(identifier: &str, natural_keys: &[String]) -> Option<String> {
if let Some(found) = natural_keys.iter().find(|k| k.eq_ignore_ascii_case(identifier)) {
return Some(found.clone());
}
let digits = identifier.strip_prefix(['c', 'C']).unwrap_or(identifier);
let num: usize = digits.parse().ok()?;
let idx = num.checked_sub(1)?;
natural_keys.get(idx).cloned()
}
pub fn build_suppression_column(natural_key: &str) -> Column {
let mut col = Column::from_source_key_with_format(natural_key, None, Format::Auto, None, DateTimeMode::Full, false);
col.key = Some(KeySegment::Excluded);
col
}
#[cfg(test)]
mod tests {
use super::*;
fn keys(cols: &[Column]) -> Vec<String> {
cols.iter().map(|c| c.source_key_name()).collect()
}
#[test]
fn test_plain_array_pattern_matches_any_suffix_regardless_of_bracket_type() {
let natural_keys = vec!["file_1".to_string(), "file_2".to_string(), "file_a".to_string(), "other".to_string()];
let cols = expand_pattern_entry("file_[n]", "files[]", &Format::Auto, &natural_keys).unwrap();
assert_eq!(keys(&cols), vec!["file_1".to_string(), "file_2".to_string(), "file_a".to_string()]);
for col in &cols {
assert!(matches!(&col.key, Some(KeySegment::PlainArray(name)) if &**name == "files"));
}
}
#[test]
fn test_glob_star_shorthand_is_equivalent_to_an_anonymous_bracket_capture() {
let natural_keys = vec!["download_1".to_string(), "download_2".to_string(), "other".to_string()];
let cols = expand_pattern_entry("download_*", "downloads[]", &Format::Auto, &natural_keys).unwrap();
assert_eq!(keys(&cols), vec!["download_1".to_string(), "download_2".to_string()]);
for col in &cols {
assert!(matches!(&col.key, Some(KeySegment::PlainArray(name)) if &**name == "downloads"));
}
}
#[test]
fn test_empty_brackets_shorthand_is_equivalent_to_an_anonymous_bracket_capture() {
let natural_keys = vec!["download_1".to_string(), "download_2".to_string(), "other".to_string()];
let cols = expand_pattern_entry("download_[]", "downloads[]", &Format::Auto, &natural_keys).unwrap();
assert_eq!(keys(&cols), vec!["download_1".to_string(), "download_2".to_string()]);
for col in &cols {
assert!(matches!(&col.key, Some(KeySegment::PlainArray(name)) if &**name == "downloads"));
}
}
#[test]
fn test_bare_star_or_empty_brackets_with_no_prefix_at_all_is_rejected() {
assert!(parse_source_pattern("*").is_none());
assert!(parse_source_pattern("[]").is_none());
}
#[test]
fn test_object_pattern_uses_captured_value_as_the_key() {
let natural_keys = vec!["sales_north_west".to_string(), "sales_south_east".to_string()];
let cols = expand_pattern_entry("sales_{region}", "sales.{region}", &Format::Float, &natural_keys).unwrap();
assert_eq!(cols.len(), 2);
let seg = cols[0].key.as_ref().unwrap();
match seg {
KeySegment::Object(key, next) => {
assert_eq!(&**key, "sales");
assert!(matches!(&**next, KeySegment::Simple(k) if &**k == "north_west"));
}
other => panic!("expected Object, got {other:?}"),
}
}
#[test]
fn test_array_inner_object_pattern_types_the_capture_as_integer() {
let natural_keys = vec!["sales_2024".to_string(), "sales_2025".to_string()];
let cols = expand_pattern_entry("sales_[year]", "sales[].{year}{amount}", &Format::Float, &natural_keys).unwrap();
assert_eq!(cols.len(), 2);
let seg = cols[0].key.as_ref().unwrap();
match seg {
KeySegment::Array(container, id, key_field, next) => {
assert_eq!(&**container, "sales");
assert_eq!(*id, Identifier::Integer(2024));
assert_eq!(&**key_field, "year");
assert!(matches!(&**next, KeySegment::Simple(k) if &**k == "amount"));
}
other => panic!("expected Array, got {other:?}"),
}
}
#[test]
fn test_non_pattern_source_returns_none() {
assert!(expand_pattern_entry("weight", "weight_kg", &Format::Float, &["weight".to_string()]).is_none());
}
#[test]
fn test_prefix_matching_is_case_insensitive() {
let natural_keys = vec!["file_1".to_string()];
let cols = expand_pattern_entry("FILE_[n]", "files[]", &Format::Auto, &natural_keys).unwrap();
assert_eq!(cols.len(), 1);
}
#[test]
fn test_resolve_suppression_matches_natural_key_case_insensitively() {
let natural_keys = vec!["id".to_string(), "colour".to_string(), "title".to_string()];
assert_eq!(resolve_suppression_key("colour", &natural_keys), Some("colour".to_string()));
assert_eq!(resolve_suppression_key("COLOUR", &natural_keys), Some("colour".to_string()));
assert_eq!(resolve_suppression_key("nope", &natural_keys), None);
}
#[test]
fn test_resolve_suppression_matches_a1_letter_directly_in_a1_mode() {
let natural_keys = vec!["a".to_string(), "b".to_string(), "c".to_string(), "d".to_string()];
assert_eq!(resolve_suppression_key("d", &natural_keys), Some("d".to_string()));
assert_eq!(resolve_suppression_key("D", &natural_keys), Some("d".to_string()));
}
#[test]
fn test_resolve_suppression_falls_back_to_a_plain_number_for_r1c1_mode() {
let natural_keys = vec!["c01".to_string(), "c02".to_string(), "c03".to_string(), "c04".to_string()];
assert_eq!(resolve_suppression_key("4", &natural_keys), Some("c04".to_string()));
assert_eq!(resolve_suppression_key("c4", &natural_keys), Some("c04".to_string()));
assert_eq!(resolve_suppression_key("c04", &natural_keys), Some("c04".to_string()));
assert_eq!(resolve_suppression_key("c004", &natural_keys), Some("c04".to_string()));
}
#[test]
fn test_resolve_suppression_number_fallback_out_of_range_is_none() {
let natural_keys = vec!["c01".to_string(), "c02".to_string()];
assert_eq!(resolve_suppression_key("0", &natural_keys), None);
assert_eq!(resolve_suppression_key("9", &natural_keys), None);
}
}