patchwork_csv_utils 0.1.9-arm64-darwin → 0.1.11-arm64-darwin

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 781d1b794c50e77e2ead8bd507a691b60ff3b3a0799a4036e20784fe88f98751
4
- data.tar.gz: 138220cbbb20024c1dcdc2f838f8d5bad68890af98ebbe8899ce5cddb78f1b73
3
+ metadata.gz: fb79f50a40c0b1913d133b410abe0133fb685d6de113b8fc61e56d6c75ebf179
4
+ data.tar.gz: 20c06b94ca3a083d599cfeff94118a3dc71aeac42df42cdcfe746153b74fbacf
5
5
  SHA512:
6
- metadata.gz: 2fc9c026fa19c4eb42bed410c6faf1089b1bfc0aff9bb1121d90736f0fbefceffb5047556a5f4d7bad4c42da76bfd07220d5ada669bc90fa21000ab34a687f22
7
- data.tar.gz: 38b7b4b7812d387a61897403e6c54ff3a0538fabd1da498a722203e73441436eb0f028bc0644a88bce88738ebe5b442cfed9ae58138fb1fc84dbaca2cb519841
6
+ metadata.gz: 4f1a7b75c34fd0c38925fd23e709dc466ea46e7210d008f50320a37cab561d47c5d0213b014dacdddbe453b60e09fc79a00b8c993f0d3f3b00f81cffdefa9e68
7
+ data.tar.gz: 29429c06f1546fdff0cebb07e7e7ba6d3ed2a684f759bb34e4313d47fe3899edf0904d22c1170d952a7b6dd522f5594491350f5084ba7e237f439891da91b6f1
data/Gemfile.lock CHANGED
@@ -1,7 +1,7 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- patchwork_csv_utils (0.1.9)
4
+ patchwork_csv_utils (0.1.11)
5
5
 
6
6
  GEM
7
7
  remote: https://rubygems.org/
data/README.md CHANGED
@@ -13,9 +13,9 @@ gem install patchwork_csv_utils
13
13
 
14
14
  ```irb
15
15
  require 'csv_utils'
16
- CsvUtils.dedup('file1.csv', 'file2.csv', 'output.csv')
17
- CsvUtils.to_csv('file1.xls', 'output_file1.csv', ['request_ids_to_skip']])
18
- CsvUtils.transform_csv('file1.xls', 'output_file1.csv', ['request_ids_to_skip']])
16
+ CsvUtils.dedup('file1.csv', 'file2.csv', 'output.csv', ['mandatory_headers'])
17
+ CsvUtils.to_csv('file1.xls', 'output_file1.csv', ['request_ids_to_skip'], ['mandatory_headers'])
18
+ CsvUtils.transform_csv('file1.xls', 'output_file1.csv', ['request_ids_to_skip'], ['mandatory_headers'])
19
19
  ```
20
20
 
21
21
  ## Release
@@ -8,8 +8,8 @@ pub mod utils;
8
8
  #[magnus::init]
9
9
  fn init() -> Result<(), magnus::Error> {
10
10
  let module = define_module("CsvUtils")?;
11
- module.define_singleton_method("dedup", function!(dedup, 3))?;
12
- module.define_singleton_method("to_csv", function!(to_csv, 3))?;
13
- module.define_singleton_method("transform_csv", function!(transform_csv, 3))?;
11
+ module.define_singleton_method("dedup", function!(dedup, 4))?;
12
+ module.define_singleton_method("to_csv", function!(to_csv, 4))?;
13
+ module.define_singleton_method("transform_csv", function!(transform_csv, 4))?;
14
14
  Ok(())
15
15
  }
@@ -2,26 +2,35 @@ use std::collections::HashMap;
2
2
  use std::fs::File;
3
3
 
4
4
  use chrono::{NaiveDate, NaiveDateTime, NaiveTime, Utc};
5
- use csv::{StringRecord, Writer};
5
+ use csv::{Reader, StringRecord, Writer};
6
6
  use magnus::{Error, RArray, Ruby};
7
7
 
8
- use crate::utils::{FileExtension, magnus_err, missing_header, to_datetime_error};
8
+ use crate::utils::{FileExtension, magnus_err, missing_header, to_datetime_error, check_mandatory_headers, create_header_map, missing_value, headers_as_byte_record};
9
9
 
10
- pub fn transform_csv(ruby: &Ruby, csv_path: String, target_path: String, exclusions: RArray) -> magnus::error::Result<()> {
10
+ pub fn transform_csv(ruby: &Ruby, csv_path: String,
11
+ target_path: String, exclusions: RArray,
12
+ mandatory_headers: RArray,) -> magnus::error::Result<()> {
11
13
  if !csv_path.has_extension(&["csv"]) {
12
- return Err(magnus::Error::new(ruby.exception_standard_error(), "csv_path must be a csv file".to_string()));
14
+ return Err(Error::new(ruby.exception_standard_error(), "csv_path must be a csv file".to_string()));
13
15
  }
14
16
 
15
17
  let exclusions = RArray::to_vec(exclusions)?;
18
+ let mandatory_headers: Vec<String> = RArray::to_vec(mandatory_headers)?;
16
19
 
17
20
  let csv_file = File::open(csv_path).map_err(|e| magnus_err(ruby, e, "csv_path"))?;
18
- let mut csv: csv::Reader<File> = csv::Reader::from_reader(csv_file);
21
+ let mut csv: Reader<File> = Reader::from_reader(csv_file);
19
22
  let mut wtr = Writer::from_path(target_path).map_err(|e| magnus_err(ruby, e, "target_path"))?;
20
- let headers = csv.headers().map_err(|e| magnus_err(ruby, e, "csv_path headers"))?;
21
- let header_map: HashMap<String, usize> = headers.iter().enumerate().map(|(i, h)| (h.to_string(), i)).collect();
23
+ let headers = csv.headers().map_err(|e| magnus_err(ruby, e, "csv_path headers"))?.clone();
24
+ let headers_list : Vec<String> = headers.iter().map(|h| h.to_string()).collect();
25
+
26
+ if let Some(value) =
27
+ check_mandatory_headers(ruby, &headers_list, &mandatory_headers, "csv") { return value; }
28
+
29
+ let header_map: HashMap<String, usize> = create_header_map(&headers);
22
30
  let inverse_header_map: HashMap<usize, String> = headers.iter().enumerate().map(|(i, h)| (i, h.to_string())).collect();
23
31
 
24
- wtr.write_byte_record(headers.as_byte_record()).map_err(|e| magnus_err(ruby, e, "write_byte_record"))?;
32
+ let csv_headers = headers_as_byte_record(mandatory_headers.clone());
33
+ wtr.write_byte_record(&csv_headers).map_err(|e| magnus_err(ruby, e, "write_byte_record"))?;
25
34
 
26
35
  let request_id = header_map.get("Request Id").ok_or(missing_header(ruby, "Request Id"))?;
27
36
  let date = header_map.get("Date").ok_or(missing_header(ruby, "Date"))?;
@@ -39,22 +48,29 @@ pub fn transform_csv(ruby: &Ruby, csv_path: String, target_path: String, exclusi
39
48
 
40
49
  let mut date_value = Utc::now().naive_utc();
41
50
 
42
- let record = record.iter().enumerate().map(|(i, c)| {
43
- let c = c.trim_end();
51
+ let mut columns = vec![];
52
+ for (i, column) in mandatory_headers.iter().enumerate() {
53
+ let column_index = header_map.get(column).ok_or(missing_header(ruby, column))?;
54
+ let column_value = record.get(*column_index).ok_or(missing_value(ruby, column))?;
55
+ let column_value = column_value.trim_end();
56
+
44
57
  if i == *date {
45
- let current = string_to_datetime(c).ok_or(to_datetime_error(ruby, c, ri, "Date"))?;
58
+ let current = string_to_datetime(column_value).ok_or(to_datetime_error(ruby, column_value, ri, "Date"))?;
46
59
  date_value = current;
47
- Ok(current.to_string())
60
+ columns.push(current.to_string());
48
61
  } else if i == *start || i == *end || i == *actual_start || i == *actual_end {
49
- if c.is_empty() { return Ok(c.to_string()); }
50
- let column_name = get_column_name(&inverse_header_map, &i);
51
- process_datetime(ruby, ri, date_value, c, &column_name)
62
+ if column_value.is_empty() {
63
+ columns.push(column_value.to_string());
64
+ } else {
65
+ let column_name = get_column_name(&inverse_header_map, &i);
66
+ let current = process_datetime(ruby, ri, date_value, column_value, &column_name)?;
67
+ columns.push(current);
68
+ }
52
69
  } else {
53
- Ok(c.to_string())
70
+ columns.push(column_value.to_string());
54
71
  }
55
- }).collect::<Result<StringRecord, magnus::Error>>()?;
56
-
57
- let record = record.into_iter().map(|r| r.trim_end()).collect::<StringRecord>();
72
+ }
73
+ let record = columns.into_iter().collect::<StringRecord>();
58
74
  wtr.write_byte_record(record.as_byte_record()).map_err(|e| magnus_err(ruby, e, "write_byte_record"))?;
59
75
  }
60
76
 
@@ -1,54 +1,51 @@
1
1
  use std::fs::File;
2
2
 
3
- use csv::{StringRecord, Writer};
4
- use magnus::Ruby;
3
+ use csv::{Reader, StringRecord, Writer};
4
+ use magnus::{RArray, Ruby};
5
5
 
6
- use crate::utils::{FileExtension, magnus_err};
6
+ use crate::utils::{FileExtension, magnus_err, check_mandatory_headers, create_header_map, missing_header, missing_value, headers_as_byte_record};
7
7
 
8
- pub fn dedup(ruby: &Ruby, previous_csv_path: String, new_csv_path: String, target_path: String) -> magnus::error::Result<()> {
9
- if !previous_csv_path.has_extension(&["csv"]) {
10
- return Err(magnus::Error::new(ruby.exception_standard_error(), "previous_csv_path must be a csv file".to_string()));
11
- }
12
- if !new_csv_path.has_extension(&["csv"]) {
13
- return Err(magnus::Error::new(ruby.exception_standard_error(), "new_csv_path must be a csv file".to_string()));
14
- }
8
+ pub fn dedup(ruby: &Ruby, previous_csv_path: String,
9
+ new_csv_path: String,
10
+ target_path: String,
11
+ mandatory_headers: RArray,
12
+ ) -> magnus::error::Result<()> {
13
+ if let Some(value) =
14
+ check_file_extension(ruby, &previous_csv_path, "previous_csv_path") { return value; }
15
+
16
+ if let Some(value) =
17
+ check_file_extension(ruby, &new_csv_path, "new_csv_path") { return value; }
15
18
 
16
19
  let csv1 = File::open(previous_csv_path).map_err(|e| magnus_err(ruby, e, "previous_csv_path"))?;
17
20
  let csv2 = File::open(new_csv_path).map_err(|e| magnus_err(ruby, e, "new_csv_path"))?;
18
21
 
22
+ let mandatory_headers: Vec<String> = RArray::to_vec(mandatory_headers)?;
23
+
19
24
  let mut previous_csv: csv::Reader<File> = csv::Reader::from_reader(csv1);
20
25
  let mut new_csv: csv::Reader<File> = csv::Reader::from_reader(csv2);
21
26
 
22
27
  let mut wtr = Writer::from_path(target_path).map_err(|e| magnus_err(ruby, e, "target_path"))?;
23
28
 
24
- let previous_headers = previous_csv.headers().map_err(|e| magnus_err(ruby, e, "previous_csv_path headers"))?;
25
- let new_headers = new_csv.headers().map_err(|e| magnus_err(ruby, e, "new_csv_path headers"))?;
29
+ let previous_headers = previous_csv.headers().map_err(|e| magnus_err(ruby, e, "previous_csv"))?.clone();
30
+ let previous_headers_list : Vec<String> = previous_headers.iter().map(|h| h.to_string()).collect();
31
+ let new_headers = new_csv.headers().map_err(|e| magnus_err(ruby, e, "new_csv"))?.clone();
32
+ let new_headers_list : Vec<String> = new_headers.iter().map(|h| h.to_string()).collect();
26
33
 
27
- if previous_headers != new_headers {
28
- return Err(magnus::Error::new(ruby.exception_standard_error(), "headers of both csv files must be the same".to_string()));
29
- }
30
34
 
31
- wtr.write_byte_record(previous_headers.as_byte_record()).map_err(|e| magnus_err(ruby, e, "write_byte_record"))?;
35
+ if let Some(value) =
36
+ check_mandatory_headers(ruby, &previous_headers_list, &mandatory_headers, "previous_csv") { return value; }
32
37
 
33
- let mut previous_records = vec![];
34
- for previous_record in previous_csv.records() {
35
- let previous_record = previous_record.map_err(|e| magnus_err(ruby, e, "previous_record"))?;
38
+ if let Some(value) =
39
+ check_mandatory_headers(ruby, &new_headers_list, &mandatory_headers, "new_csv") { return value; }
36
40
 
37
- if has_empty_row_skip(&previous_record) { continue; }
38
- if has_empty_first_col_skip_row(&previous_record) { continue; }
41
+ let csv_headers = headers_as_byte_record(mandatory_headers.clone());
42
+ wtr.write_byte_record(&csv_headers).map_err(|e| magnus_err(ruby, e, "write_byte_record"))?;
39
43
 
40
- let previous_record = previous_record.into_iter().map(|r| r.trim_end()).collect::<StringRecord>();
41
- previous_records.push(previous_record)
42
- }
43
-
44
- for new_record in new_csv.records() {
45
- let new_record = new_record.map_err(|e| magnus_err(ruby, e, "new_record"))?;
44
+ let previous_mandatory_records = get_records(ruby, &mut previous_csv, &previous_headers, &mandatory_headers)?;
45
+ let new_mandatory_records = get_records(ruby, &mut new_csv, &new_headers, &mandatory_headers)?;
46
46
 
47
- if has_empty_row_skip(&new_record) { continue; }
48
- if has_empty_first_col_skip_row(&new_record) { continue; }
49
-
50
- let new_record = new_record.into_iter().map(|r| r.trim_end()).collect::<StringRecord>();
51
- if !previous_records.contains(&new_record) {
47
+ for new_record in new_mandatory_records {
48
+ if !previous_mandatory_records.contains(&new_record) {
52
49
  wtr.write_byte_record(new_record.as_byte_record()).map_err(|e| magnus_err(ruby, e, "write_byte_record"))?;
53
50
  }
54
51
  }
@@ -58,6 +55,34 @@ pub fn dedup(ruby: &Ruby, previous_csv_path: String, new_csv_path: String, targe
58
55
  Ok(())
59
56
  }
60
57
 
58
+ fn get_records(ruby: &Ruby, csv: &mut Reader<File>, csv_headers: &StringRecord, headers: &Vec<String>) -> magnus::error::Result<Vec<StringRecord>> {
59
+ let header_map = create_header_map(&csv_headers);
60
+ let mut records = vec![];
61
+ for record in csv.records() {
62
+ let record = record.map_err(|e| magnus_err(ruby, e, "record error"))?;
63
+
64
+ if has_empty_row_skip(&record) { continue; }
65
+ if has_empty_first_col_skip_row(&record) { continue; }
66
+
67
+ let mut columns = vec![];
68
+ for column in headers.iter() {
69
+ let column_index = header_map.get(column).ok_or(missing_header(ruby, column))?;
70
+ let column_value = record.get(*column_index).ok_or(missing_value(ruby, column))?;
71
+ columns.push(column_value.trim_end());
72
+ }
73
+ let columns = columns.into_iter().collect::<StringRecord>();
74
+ records.push(columns);
75
+ }
76
+ Ok(records)
77
+ }
78
+
79
+ fn check_file_extension(ruby: &Ruby, csv_path: &String, message: &str) -> Option<magnus::error::Result<()>> {
80
+ if !csv_path.has_extension(&["csv"]) {
81
+ return Some(Err(magnus::Error::new(ruby.exception_standard_error(), format!("{} must be a csv file", message))));
82
+ }
83
+ None
84
+ }
85
+
61
86
  fn has_empty_first_col_skip_row(previous_record: &StringRecord) -> bool {
62
87
  previous_record[0].is_empty()
63
88
  }
@@ -1,6 +1,8 @@
1
+ use std::collections::HashMap;
1
2
  use std::error::Error;
2
3
  use std::ffi::OsStr;
3
4
  use std::path::Path;
5
+ use ::csv::{ByteRecord, StringRecord};
4
6
  use magnus::Ruby;
5
7
 
6
8
  pub mod csv;
@@ -11,6 +13,15 @@ fn missing_header(ruby: &Ruby, header: &str) -> magnus::Error {
11
13
  magnus::Error::new(ruby.exception_standard_error(), format!("Missing '{}' header", header))
12
14
  }
13
15
 
16
+ fn missing_value(ruby: &Ruby, header: &str) -> magnus::Error {
17
+ magnus::Error::new(ruby.exception_standard_error(), format!("Missing value for '{}' header", header))
18
+ }
19
+
20
+ fn headers_as_byte_record(headers: Vec<String>) -> ByteRecord {
21
+ let string_record = headers.into_iter().collect::<StringRecord>();
22
+ string_record.as_byte_record().clone()
23
+ }
24
+
14
25
  fn magnus_err<E: Error>(ruby: &Ruby, e: E, msg: &str) -> magnus::Error {
15
26
  magnus::Error::new(ruby.exception_standard_error(), format!("{}: {}", msg, e.to_string()))
16
27
  }
@@ -19,6 +30,28 @@ fn to_datetime_error(ruby: &Ruby, value: &str, row: usize, col: &str) -> magnus:
19
30
  magnus::Error::new(ruby.exception_standard_error(), format!("Could not parse datetime '{}', row: {}, col: {}", value, row, col))
20
31
  }
21
32
 
33
+ fn check_mandatory_headers(ruby: &Ruby, headers: &Vec<String>, mandatory_headers: &Vec<String>, message: &str) -> Option<magnus::error::Result<()>> {
34
+ let csv_mandatory_headers = filter_headers(headers, mandatory_headers);
35
+
36
+ if csv_mandatory_headers.is_empty() {
37
+ return Some(Err(magnus::Error::new(ruby.exception_standard_error(), format!("{} has no mandatory headers", message))));
38
+ }
39
+
40
+ if &csv_mandatory_headers != mandatory_headers {
41
+ let missing_headers = mandatory_headers.into_iter().filter(|h| !csv_mandatory_headers.contains(h)).map(|v| v.to_string()).collect::<Vec<String>>();
42
+ return Some(Err(magnus::Error::new(ruby.exception_standard_error(), format!("{} is missing mandatory headers: {}", message, missing_headers.join(", ")))));
43
+ }
44
+ None
45
+ }
46
+
47
+ fn filter_headers(csv_headers: &Vec<String>, expected_headers: &Vec<String>) -> Vec<String> {
48
+ csv_headers.iter().map(|v| v.to_string()).filter(|h| expected_headers.contains(h)).collect::<Vec<String>>()
49
+ }
50
+
51
+ fn create_header_map(headers: &StringRecord) -> HashMap<String, usize> {
52
+ headers.iter().enumerate().map(|(i, h)| (h.to_string(), i)).collect()
53
+ }
54
+
22
55
  pub trait FileExtension {
23
56
  fn has_extension<S: AsRef<str>>(&self, extensions: &[S]) -> bool;
24
57
  }
@@ -6,14 +6,19 @@ use calamine::{Data, open_workbook, Range, Reader, Xls};
6
6
  use chrono::{NaiveDateTime, Utc};
7
7
  use magnus::{RArray, Ruby};
8
8
 
9
- use crate::utils::{FileExtension, magnus_err, missing_header, to_datetime_error};
9
+ use crate::utils::{FileExtension, magnus_err, missing_header, to_datetime_error, check_mandatory_headers, missing_value};
10
10
 
11
- pub fn to_csv(ruby: &Ruby, xls_path: String, target_path: String, exclusions: RArray) -> magnus::error::Result<()> {
11
+ pub fn to_csv(ruby: &Ruby, xls_path: String,
12
+ target_path: String,
13
+ exclusions: RArray,
14
+ mandatory_headers: RArray
15
+ ) -> magnus::error::Result<()> {
12
16
  if !xls_path.has_extension(&["xls"]) {
13
17
  return Err(magnus::Error::new(ruby.exception_standard_error(), "xls_path must be an xls file".to_string()));
14
18
  }
15
19
 
16
20
  let exclusions = RArray::to_vec(exclusions)?;
21
+ let mandatory_headers: Vec<String> = RArray::to_vec(mandatory_headers)?;
17
22
 
18
23
  let mut workbook: Xls<_> = open_workbook(xls_path.clone()).map_err(|e| magnus_err(ruby, e, format!("could not open xls: {}", xls_path).as_str()))?;
19
24
  let range = workbook.worksheet_range_at(0)
@@ -21,14 +26,20 @@ pub fn to_csv(ruby: &Ruby, xls_path: String, target_path: String, exclusions: RA
21
26
  .and_then(|r| r.map_err(|e| magnus_err(ruby, e, "could not read worksheet range")))?;
22
27
 
23
28
  let headers = range.headers().ok_or(magnus::Error::new(ruby.exception_standard_error(), "no headers found in xls".to_string()))?;
29
+ let headers_list : Vec<String> = headers.iter().map(|h| h.to_string()).collect();
30
+
31
+ if let Some(value) =
32
+ check_mandatory_headers(ruby, &headers_list, &mandatory_headers, "csv") { return value; }
33
+
24
34
  let header_map: HashMap<String, usize> = headers.iter().enumerate().map(|(i, h)| (h.to_string(), i)).collect();
25
35
  let csv_out_file = File::create(target_path.clone()).map_err(|e| magnus_err(ruby, e, format!("could not create csv file: {}", target_path).as_str()))?;
26
36
  let mut dest = BufWriter::new(csv_out_file);
27
37
 
28
- write_csv(ruby, &mut dest, &range, header_map, exclusions)
38
+ write_csv(ruby, &mut dest, &range, header_map, exclusions, mandatory_headers)
29
39
  }
30
40
 
31
- fn write_csv<W: Write>(ruby: &Ruby, dest: &mut W, range: &Range<Data>, header_map: HashMap<String, usize>, exclusions: Vec<String>) -> magnus::error::Result<()> {
41
+ fn write_csv<W: Write>(ruby: &Ruby, dest: &mut W, range: &Range<Data>,
42
+ header_map: HashMap<String, usize>, exclusions: Vec<String>, mandatory_headers: Vec<String>) -> magnus::error::Result<()> {
32
43
  let n = range.get_size().1 - 1;
33
44
 
34
45
  let request_id = header_map.get("Request Id").ok_or(missing_header(ruby, "Request Id"))?;
@@ -48,7 +59,11 @@ fn write_csv<W: Write>(ruby: &Ruby, dest: &mut W, range: &Range<Data>, header_ma
48
59
  return Err(magnus::Error::new(ruby.exception_standard_error(), format!("Date value is not present in row: {}", ri)));
49
60
  }
50
61
 
51
- for (i, c) in r.iter().enumerate() {
62
+ for (i, c) in mandatory_headers.iter().enumerate() {
63
+
64
+ let column_index = header_map.get(c).ok_or(missing_header(ruby, c))?;
65
+ let c = r.get(*column_index).ok_or(missing_value(ruby, c))?;
66
+
52
67
  match *c {
53
68
  Data::Empty => Ok(()),
54
69
  Data::String(ref s) | Data::DateTimeIso(ref s) | Data::DurationIso(ref s) => {
Binary file
Binary file
Binary file
Binary file
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module CsvUtils
4
- VERSION = '0.1.9'
4
+ VERSION = '0.1.11'
5
5
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: patchwork_csv_utils
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.9
4
+ version: 0.1.11
5
5
  platform: arm64-darwin
6
6
  authors:
7
7
  - kingsley.hendrickse
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2024-08-08 00:00:00.000000000 Z
11
+ date: 2024-09-03 00:00:00.000000000 Z
12
12
  dependencies: []
13
13
  description: Deduplication of CSV files and XLS to CSV conversion.
14
14
  email: