1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
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(),
        }
    }
}