1 use std::fs;
2 use std::io;
3 use std::path::{Path, PathBuf};
4 
5 use csv_index::RandomAccessSimple;
6 
7 use CliResult;
8 use config::{Config, Delimiter};
9 use util;
10 
11 static USAGE: &'static str = "
12 Creates an index of the given CSV data, which can make other operations like
13 slicing, splitting and gathering statistics much faster.
14 
15 Note that this does not accept CSV data on stdin. You must give a file
16 path. The index is created at 'path/to/input.csv.idx'. The index will be
17 automatically used by commands that can benefit from it. If the original CSV
18 data changes after the index is made, commands that try to use it will result
19 in an error (you have to regenerate the index before it can be used again).
20 
21 Usage:
22     xsv index [options] <input>
23     xsv index --help
24 
25 index options:
26     -o, --output <file>    Write index to <file> instead of <input>.idx.
27                            Generally, this is not currently useful because
28                            the only way to use an index is if it is specially
29                            named <input>.idx.
30 
31 Common options:
32     -h, --help             Display this message
33     -d, --delimiter <arg>  The field delimiter for reading CSV data.
34                            Must be a single character. (default: ,)
35 ";
36 
37 #[derive(Deserialize)]
38 struct Args {
39     arg_input: String,
40     flag_output: Option<String>,
41     flag_delimiter: Option<Delimiter>,
42 }
43 
run(argv: &[&str]) -> CliResult<()>44 pub fn run(argv: &[&str]) -> CliResult<()> {
45     let args: Args = util::get_args(USAGE, argv)?;
46 
47     let pidx = match args.flag_output {
48         None => util::idx_path(&Path::new(&args.arg_input)),
49         Some(p) => PathBuf::from(&p),
50     };
51 
52     let rconfig = Config::new(&Some(args.arg_input))
53                          .delimiter(args.flag_delimiter);
54     let mut rdr = rconfig.reader_file()?;
55     let mut wtr = io::BufWriter::new(fs::File::create(&pidx)?);
56     RandomAccessSimple::create(&mut rdr, &mut wtr)?;
57     Ok(())
58 }
59