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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
pub mod group;
pub mod split;

mod internal;

pub use crate::utils::group::group;
pub use crate::utils::split::split;

pub use crate::utils::internal::Reduction;
use crate::utils::internal::*;

use derive_new::new;
use getset::Getters;
use nu_errors::ShellError;
use nu_protocol::{UntaggedValue, Value};
use nu_source::Tag;

#[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Getters, Clone, new)]
pub struct Model {
    pub labels: Labels,
    pub ranges: (Range, Range),

    pub data: Value,
    pub percentages: Value,
}

#[allow(clippy::type_complexity)]
pub struct Operation<'a> {
    pub grouper: Option<Box<dyn Fn(usize, &Value) -> Result<String, ShellError> + Send>>,
    pub splitter: Option<Box<dyn Fn(usize, &Value) -> Result<String, ShellError> + Send>>,
    pub format: &'a Option<Box<dyn Fn(&Value, String) -> Result<String, ShellError>>>,
    pub eval: &'a Option<Box<dyn Fn(usize, &Value) -> Result<Value, ShellError> + Send>>,
    pub reduction: &'a Reduction,
}

pub fn report(
    values: &Value,
    options: Operation,
    tag: impl Into<Tag>,
) -> Result<Model, ShellError> {
    let tag = tag.into();

    let grouped = group(values, &options.grouper, &tag)?;
    let splitted = split(&grouped, &options.splitter, &tag)?;

    let x = grouped
        .row_entries()
        .map(|(key, _)| key.clone())
        .collect::<Vec<_>>();

    let x = sort_columns(&x, options.format)?;

    let mut y = splitted
        .row_entries()
        .map(|(key, _)| key.clone())
        .collect::<Vec<_>>();

    y.sort();

    let planes = Labels { x, y };

    let sorted = sort(&planes, &splitted, &tag)?;

    let evaluated = evaluate(
        &sorted,
        if options.eval.is_some() {
            options.eval
        } else {
            &None
        },
        &tag,
    )?;

    let group_labels = planes.grouping_total();

    let reduced = reduce(&evaluated, options.reduction, &tag)?;

    let maxima = max(&reduced, &tag)?;

    let percents = percentages(&maxima, &reduced, &tag)?;

    Ok(Model {
        labels: planes,
        ranges: (
            Range {
                start: UntaggedValue::int(0).into_untagged_value(),
                end: group_labels,
            },
            Range {
                start: UntaggedValue::int(0).into_untagged_value(),
                end: maxima,
            },
        ),
        data: reduced,
        percentages: percents,
    })
}

pub mod helpers {
    use nu_errors::ShellError;
    use nu_protocol::{row, Value};
    use nu_source::{Tag, TaggedItem};
    use nu_test_support::value::{date, int, string, table};
    use nu_value_ext::ValueExt;

    pub fn committers() -> Vec<Value> {
        vec![
            row! {
                   "date".into() => date("2019-07-23"),
                   "name".into() =>       string("AR"),
                "country".into() =>       string("EC"),
              "chickens".into() =>             int(10)
            },
            row! {
                   "date".into() => date("2019-07-23"),
                   "name".into() =>       string("JT"),
                "country".into() =>       string("NZ"),
               "chickens".into() =>             int(5)
            },
            row! {
                   "date".into() => date("2019-10-10"),
                   "name".into() =>       string("YK"),
                "country".into() =>       string("US"),
               "chickens".into() =>             int(6)
            },
            row! {
                   "date".into() => date("2019-09-24"),
                   "name".into() =>       string("AR"),
                "country".into() =>       string("EC"),
               "chickens".into() =>            int(20)
            },
            row! {
                   "date".into() => date("2019-10-10"),
                   "name".into() =>       string("JT"),
                "country".into() =>       string("NZ"),
               "chickens".into() =>            int(15)
            },
            row! {
                   "date".into() => date("2019-09-24"),
                   "name".into() =>       string("YK"),
                "country".into() =>       string("US"),
               "chickens".into() =>             int(4)
            },
            row! {
                   "date".into() => date("2019-10-10"),
                   "name".into() =>       string("AR"),
                "country".into() =>       string("EC"),
               "chickens".into() =>            int(30)
            },
            row! {
                   "date".into() => date("2019-09-24"),
                   "name".into() =>       string("JT"),
                "country".into() =>       string("NZ"),
              "chickens".into() =>             int(10)
            },
            row! {
                   "date".into() => date("2019-07-23"),
                   "name".into() =>       string("YK"),
                "country".into() =>       string("US"),
               "chickens".into() =>             int(2)
            },
        ]
    }

    pub fn committers_grouped_by_date() -> Value {
        let sample = table(&committers());

        let grouper = Box::new(move |_, row: &Value| {
            let key = String::from("date").tagged_unknown();
            let group_key = row
                .get_data_by_key(key.borrow_spanned())
                .expect("get key failed");

            group_key.format("%Y-%m-%d")
        });

        crate::utils::group(&sample, &Some(grouper), Tag::unknown())
            .expect("failed to create group")
    }

    pub fn date_formatter(
        fmt: String,
    ) -> Box<dyn Fn(&Value, String) -> Result<String, ShellError>> {
        Box::new(move |date: &Value, _: String| {
            let fmt = fmt.clone();
            date.format(&fmt)
        })
    }
}

#[cfg(test)]
mod tests {
    use super::helpers::{committers, date_formatter};
    use super::{report, Labels, Model, Operation, Range, Reduction};
    use nu_errors::ShellError;
    use nu_protocol::Value;
    use nu_source::{Tag, TaggedItem};
    use nu_test_support::value::{decimal_from_float, int, table};
    use nu_value_ext::ValueExt;

    pub fn assert_without_checking_percentages(report_a: Model, report_b: Model) {
        assert_eq!(report_a.labels.x, report_b.labels.x);
        assert_eq!(report_a.labels.y, report_b.labels.y);
        assert_eq!(report_a.ranges, report_b.ranges);
        assert_eq!(report_a.data, report_b.data);
    }

    #[test]
    fn prepares_report_using_counting_value() {
        let committers = table(&committers());

        let by_date = Box::new(move |_, row: &Value| {
            let key = String::from("date").tagged_unknown();
            let key = row.get_data_by_key(key.borrow_spanned()).unwrap();

            let callback = date_formatter("%Y-%m-%d".to_string());
            callback(&key, "nothing".to_string())
        });

        let by_country = Box::new(move |_, row: &Value| {
            let key = String::from("country").tagged_unknown();
            let key = row.get_data_by_key(key.borrow_spanned()).unwrap();
            nu_value_ext::as_string(&key)
        });

        let options = Operation {
            grouper: Some(by_date),
            splitter: Some(by_country),
            format: &None,
            eval: /* value to be used for accumulation */ &Some(Box::new(move |_, value: &Value| {
                let chickens_key = String::from("chickens").tagged_unknown();

                value
                    .get_data_by_key(chickens_key.borrow_spanned())
                    .ok_or_else(|| {
                        ShellError::labeled_error(
                            "unknown column",
                            "unknown column",
                            chickens_key.span(),
                        )
                    })
            })),
            reduction: &Reduction::Count
        };

        assert_without_checking_percentages(
            report(&committers, options, Tag::unknown()).unwrap(),
            Model {
                labels: Labels {
                    x: vec![
                        String::from("2019-07-23"),
                        String::from("2019-09-24"),
                        String::from("2019-10-10"),
                    ],
                    y: vec![String::from("EC"), String::from("NZ"), String::from("US")],
                },
                ranges: (
                    Range {
                        start: int(0),
                        end: int(3),
                    },
                    Range {
                        start: int(0),
                        end: int(30),
                    },
                ),
                data: table(&[
                    table(&[int(10), int(20), int(30)]),
                    table(&[int(5), int(10), int(15)]),
                    table(&[int(2), int(4), int(6)]),
                ]),
                percentages: table(&[
                    table(&[
                        decimal_from_float(33.33),
                        decimal_from_float(66.66),
                        decimal_from_float(99.99),
                    ]),
                    table(&[
                        decimal_from_float(16.66),
                        decimal_from_float(33.33),
                        decimal_from_float(49.99),
                    ]),
                    table(&[
                        decimal_from_float(6.66),
                        decimal_from_float(13.33),
                        decimal_from_float(19.99),
                    ]),
                ]),
            },
        );
    }
}