forked from dathere/qsv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrename.rs
63 lines (49 loc) · 1.8 KB
/
rename.rs
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
use crate::config::{Config, Delimiter};
use crate::serde::Deserialize;
use crate::util;
use crate::CliResult;
static USAGE: &str = "
Rename the columns of CSV data efficiently.
This command lets you rename the columns in CSV data. You must specify
all of the headers, and separate them by a comma.
Change the name of the columns:
$ qsv rename id,name,title
Use column names that contains commas and conflict with the separator:
$ qsv rename '\"Date - Opening\",\"Date - Actual Closing\"'
Usage:
qsv rename [options] [--] <headers> [<input>]
qsv rename --help
Common options:
-h, --help Display this message
-o, --output <file> Write output to <file> instead of stdout.
-d, --delimiter <arg> The field delimiter for reading CSV data.
Must be a single character. (default: ,)
";
#[derive(Deserialize)]
struct Args {
arg_input: Option<String>,
arg_headers: String,
flag_output: Option<String>,
flag_delimiter: Option<Delimiter>,
}
pub fn run(argv: &[&str]) -> CliResult<()> {
let args: Args = util::get_args(USAGE, argv)?;
let rconfig = Config::new(&args.arg_input).delimiter(args.flag_delimiter);
let mut rdr = rconfig.reader()?;
let mut wtr = Config::new(&args.flag_output).writer()?;
let headers = rdr.byte_headers()?;
let mut new_rdr = csv::Reader::from_reader(args.arg_headers.as_bytes());
let new_headers = new_rdr.byte_headers()?;
if headers.len() != new_headers.len() {
return fail!("The length of the CSV headers is different from the provided one.");
}
if !rconfig.no_headers {
wtr.write_record(new_headers)?;
}
let mut record = csv::ByteRecord::new();
while rdr.read_byte_record(&mut record)? {
wtr.write_record(&record)?;
}
wtr.flush()?;
Ok(())
}