csvsc 2.2.1

Build processing chains for CSV files
Documentation
use regex::Regex;

use crate::add::colspec::ColSpec;

/// A simple interface for building and adding new columns.
///
/// You'll always start from a column name `with_name` and then decide if you
/// want to build the new column's value from previous columns or from a
/// specific one using a regex.
///
/// ## Example
///
/// ```
/// use csvsc::prelude::*;
///
/// Column::with_name("full name").from_all_previous().definition("{name} {last name}");
/// ```
pub struct Column {
    colname: String,
}

impl Column {
    /// Start your new column with a name
    pub fn with_name(name: &str) -> Column {
        Column {
            colname: name.into(),
        }
    }

    /// Build the new column's value from the values of existing columns so far
    pub fn from_all_previous(self) -> MixColumn {
        MixColumn {
            colname: self.colname,
        }
    }

    /// Build the new column's value from a single column and a regex that you'll
    /// use to extract some values.
    ///
    /// This is very useful for adding data contained in the csv file's name
    /// that is contained in the `_source` column (automatically added).
    ///
    /// ## Example
    ///
    /// ```
    /// use csvsc::prelude::*;
    ///
    /// Column::with_name("year")
    ///     .from_column("_source")
    ///     .with_regex("report_([0-9]{4}).csv").unwrap()
    ///     .definition("$1");
    /// ```
    pub fn from_column(self, name: &str) -> IncompleteRegexColumn {
        IncompleteRegexColumn {
            colname: self.colname,
            source: name.into(),
        }
    }
}

pub struct MixColumn {
    colname: String,
}

pub struct IncompleteRegexColumn {
    colname: String,
    source: String,
}

pub struct RegexColumn {
    colname: String,
    source: String,
    regex: Regex,
}

impl MixColumn {
    pub fn definition(self, def: &str) -> ColSpec {
        ColSpec::Mix {
            colname: self.colname,
            coldef: def.into(),
        }
    }
}

impl IncompleteRegexColumn {
    pub fn with_regex(self, regex: &str) -> Result<RegexColumn, regex::Error> {
        Ok(RegexColumn {
            colname: self.colname,
            source: self.source,
            regex: Regex::new(regex)?,
        })
    }
}

impl RegexColumn {
    pub fn definition(self, def: &str) -> ColSpec {
        ColSpec::Regex {
            source: self.source,
            colname: self.colname,
            regex: self.regex,
            coldef: def.into(),
        }
    }
}