forked from dathere/qsv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcount.rs
77 lines (65 loc) · 1.92 KB
/
count.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
static USAGE: &str = "
Prints a count of the number of records in the CSV data.
Note that the count will not include the header row (unless --no-headers is
given).
Usage:
qsv count [options] [<input>]
qsv count --help
count options:
-H, --human-readable Comma separate row count.
Common options:
-h, --help Display this message
-n, --no-headers When set, the first row will be included in
the count.
-d, --delimiter <arg> The field delimiter for reading CSV data.
Must be a single character. (default: ,)
";
use log::{debug, info};
use serde::Deserialize;
use crate::{
config::{Config, Delimiter},
util, CliResult,
};
#[derive(Deserialize)]
struct Args {
arg_input: Option<String>,
flag_human_readable: bool,
flag_no_headers: bool,
flag_delimiter: Option<Delimiter>,
}
pub fn run(argv: &[&str]) -> CliResult<()> {
let args: Args = util::get_args(USAGE, argv)?;
let conf = Config::new(&args.arg_input)
.checkutf8(false)
.delimiter(args.flag_delimiter)
.no_headers(args.flag_no_headers);
debug!(
"input: {:?}, no_header: {}, delimiter: {:?}",
(args.arg_input).clone().unwrap(),
&args.flag_no_headers,
&args.flag_delimiter
);
let count = if let Some(idx) = conf.indexed().unwrap_or_else(|_| {
info!("index is stale...");
None
}) {
info!("index used");
idx.count()
} else {
info!(r#"counting "manually"..."#);
let mut rdr = conf.reader()?;
let mut count = 0u64;
let mut record = csv::ByteRecord::new();
while rdr.read_byte_record(&mut record)? {
count += 1;
}
count
};
if args.flag_human_readable {
use thousands::Separable;
println!("{}", count.separate_with_commas());
} else {
println!("{count}");
}
Ok(())
}