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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
use std::path::{Path, PathBuf,};
use std::error::Error;
use clap::{App, Arg, ArgGroup, };

pub fn app() -> App<'static, 'static> {
    App::new("rjoin")
        .author(crate_authors!())
        .version(crate_version!())
        .about("joins lines of two files with identical join fields.")
        .arg(Arg::with_name("show_left")
                 .short("l")
                 .long("show-left")
                 .help("print the unmatched lines from the left file"))
        .arg(Arg::with_name("show_right")
                 .short("r")
                 .long("show-right")
                 .help("print the unmatched lines from the right file"))
        .arg(Arg::with_name("show_both")
                 .short("b")
                 .long("show-both")
                 .help("print the matched lines"))
        .group(ArgGroup::with_name("show_any")
                        .args(&["show_left", "show_right", "show_both"])
                        .multiple(true))
        .arg(Arg::with_name("header")
                 .long("header")
                 .help("treat the first line in each file as field headers, print them without trying to pair them"))
        .arg(Arg::with_name("key")
                 .short("k")
                 .long("key")
                 .conflicts_with_all(&["left_key", "right_key"])
                 .takes_value(true)
                 .min_values(1)
                 .value_delimiter(",")
                 .value_name("FIELDS")
                 .help("equivalent to '--left-key=FIELDS --right-key=FIELDS'"))
        .arg(Arg::with_name("left_key")
                 .long("left-key")
                 .requires("right_key")
                 .takes_value(true)
                 .min_values(1)
                 .value_delimiter(",")
                 .value_name("FIELDS")
                 .help("join on these comma-separated fields in the left file")
                 .long_help(
"join on these comma-separated fields in the left file. The index 
starts with one and must not contain duplicates. The default is 1."))
        .arg(Arg::with_name("right_key")
                 .long("right-key")
                 .requires("left_key")
                 .takes_value(true)
                 .min_values(1)
                 .value_delimiter(",")
                 .value_name("FIELDS")
                 .help("join on these comma-separated fields in the right file")
                 .long_help(
"join on these comma-separated fields in the right file. The index 
starts with one and must not contain duplicates. The default is 1."))
        .arg(Arg::with_name("delimiter")
                 .long("delimiter")
                 .short("d")
                 .takes_value(true)
                 .value_name("CHAR")
                 .conflicts_with("in_delimiter")
                 .help("equivalent to '--in-delimiter=CHAR --out-delimiter=CHAR'"))
        .arg(Arg::with_name("in_delimiter")
                 .long("in-delimiter")
                 .takes_value(true)
                 .value_name("CHAR")
                 .requires("out_delimiter")
                 .conflicts_with_all(&["in_left_delimiter", "in_right_delimiter"])
                 .help("equivalent to '--in-left-delimiter=CHAR --in-right-delimiter=CHAR'"))
        .arg(Arg::with_name("out_delimiter")
                 .long("out-delimiter")
                 .takes_value(true)
                 .value_name("CHAR")
                 .requires("in_delimiter")
                 .help("use CHAR as output field delimiter")
                 .long_help(
"use CHAR as output field delimiter. It must be 1 byte long in utf-8."))
        .arg(Arg::with_name("in_left_delimiter")
                 .long("in-left-delimiter")
                 .takes_value(true)
                 .value_name("CHAR")
                 .requires_all(&["in_right_delimiter", "out_delimiter"])
                 .help("use CHAR as input field delimiter for the left file")
                 .long_help(
"use CHAR as input field delimiter for left file. It must be 1 byte long in utf-8."))
        .arg(Arg::with_name("in_right_delimiter")
                 .long("in-right-delimiter")
                 .takes_value(true)
                 .value_name("CHAR")
                 .requires("in_left_delimiter")
                 .help("use CHAR as input field delimiter for the right file")
                 .long_help(
"use CHAR as input field delimiter for the right file. It must be 1 byte long in utf-8."))
        .arg(Arg::with_name("terminator")
                 .long("terminator")
                 .short("t")
                 .takes_value(true)
                 .value_name("CHAR")
                 .conflicts_with("in_terminator")
                 .help("equivalent to '--in-terminator=CHAR --out-terminator=CHAR'"))
        .arg(Arg::with_name("in_terminator")
                 .long("in-terminator")
                 .takes_value(true)
                 .value_name("CHAR")
                 .requires("out_terminator")
                 .conflicts_with_all(&["in_left_terminator", "in_right_terminator"])
                 .help("equivalent to '--in-left-terminator=CHAR --in-right-terminator=CHAR'"))
        .arg(Arg::with_name("out_terminator")
                 .long("out-terminator")
                 .takes_value(true)
                 .value_name("CHAR")
                 .requires("in_terminator")
                 .help("use CHAR as output record terminator")
                 .long_help(
"use CHAR as output record terminator. It must be 1 byte long in utf-8."))
        .arg(Arg::with_name("in_left_terminator")
                 .long("in-left-terminator")
                 .takes_value(true)
                 .value_name("CHAR")
                 .requires_all(&["in_right_terminator", "out_terminator"])
                 .help("use CHAR as input record terminator for the left file")
                 .long_help(
"use CHAR as input record terminator for left file. It must be 1 byte long in utf-8."))
        .arg(Arg::with_name("in_right_terminator")
                 .long("in-right-terminator")
                 .takes_value(true)
                 .value_name("CHAR")
                 .requires("in_left_terminator")
                 .help("use CHAR as input record terminator for the right file")
                 .long_help(
"use CHAR as input record terminator for right file. It must be 1 byte long in utf-8."))
        .arg(Arg::with_name("LEFT_FILE")
                 .help("the left input file")
                 .required(true)
                 .index(1))
        .arg(Arg::with_name("RIGHT_FILE")
                 .help("the right input file")
                 .required(true)
                 .index(2))
}

pub struct Args {
    left_path: PathBuf,
    right_path: PathBuf,
    show_left: bool,
    show_right: bool,
    show_both: bool,
    left_key: Vec<usize>,
    right_key: Vec<usize>,
    in_left_delimiter: u8,
    in_right_delimiter: u8,
    out_delimiter: u8,
    in_left_terminator: u8,
    in_right_terminator: u8,
    out_terminator: u8,
    header: bool,
}

impl Args {
    pub fn parse() -> Result<Args, Box<Error>> {
        let matches = app().get_matches();

        let left_path = matches.value_of("LEFT_FILE").ok_or("expected LEFT_FILE")?;
        let right_path = matches.value_of("RIGHT_FILE").ok_or("expected RIGHT_FILE")?;

        let show_left = matches.is_present("show_left");
        let show_right = matches.is_present("show_right");
        let show_both = !matches.is_present("show_any") || matches.is_present("show_both");

        let header = matches.is_present("header");

        let key: Vec<usize> = match matches.values_of("key").map(|it| it.collect::<Vec<_>>()) {
            Some(v) => validate_key(v, "")?,
            None => vec![0],
        };
        let left_key: Vec<usize> = match matches.values_of("left_key")
                                                .map(|it| it.collect::<Vec<_>>()) {
            Some(v) => validate_key(v, "left ")?,
            None => key.clone(),
        };
        let right_key: Vec<usize> = match matches.values_of("right_key")
                                                 .map(|it| it.collect::<Vec<_>>()) {
            Some(v) => validate_key(v, "right ")?,
            None => key.clone(),
        };

        if left_key.len() != right_key.len() {
            return Err("the left key and the right key parameters have different lenght".into());
        }

        let delimiter = match matches.value_of("delimiter")
                                     .map(|s| s.as_bytes()) {
            Some(b) => {
                if b.len() > 1 {
                    return Err("the field delimiter must be 1 byte long in utf8".into());
                }
                b[0]
            }
            None => b','
        };
        let in_delimiter = match matches.value_of("in_delimiter")
                                        .map(|s| s.as_bytes()) {
            Some(b) => {
                if b.len() > 1 {
                    return Err("the input field delimiter must be 1 byte long in utf8".into());
                }
                b[0]
            }
            None => delimiter
        };
        let out_delimiter = match matches.value_of("out_delimiter")
                                         .map(|s| s.as_bytes()) {
            Some(b) => {
                if b.len() > 1 {
                    return Err("the output field delimiter must be 1 byte long in utf8".into());
                }
                b[0]
            }
            None => delimiter
        };
        let in_left_delimiter = match matches.value_of("in_left_delimiter")
                                             .map(|s| s.as_bytes()) {
            Some(b) => {
                if b.len() > 1 {
                    return Err("the left input field delimiter must be 1 byte long in utf8".into());
                }
                b[0]
            }
            None => in_delimiter
        };
        let in_right_delimiter = match matches.value_of("in_right_delimiter")
                                             .map(|s| s.as_bytes()) {
            Some(b) => {
                if b.len() > 1 {
                    return Err("the right input field delimiter must be 1 byte long in utf8".into());
                }
                b[0]
            }
            None => in_delimiter
        };

        let terminator = match matches.value_of("terminator")
                                   .map(|s| s.as_bytes()) {
            Some(b) => {
                if b.len() > 1 {
                    return Err("the record terminator must be 1 byte long in utf8".into());
                }
                b[0]
            }
            None => b'\n'
        };
        let in_terminator = match matches.value_of("in_terminator")
                                      .map(|s| s.as_bytes()) {
            Some(b) => {
                if b.len() > 1 {
                    return Err("the input record terminator must be 1 byte long in utf8".into());
                }
                b[0]
            }
            None => terminator
        };
        let out_terminator = match matches.value_of("out_terminator")
                                       .map(|s| s.as_bytes()) {
            Some(b) => {
                if b.len() > 1 {
                    return Err("the output record terminator must be 1 byte long in utf8".into());
                }
                b[0]
            }
            None => terminator
        };
        let in_left_terminator = match matches.value_of("in_left_terminator")
                                           .map(|s| s.as_bytes()) {
            Some(b) => {
                if b.len() > 1 {
                    return Err("the left input record terminator must be 1 byte long in \
                    utf8".into());
                }
                b[0]
            }
            None => in_terminator
        };
        let in_right_terminator = match matches.value_of("in_right_terminator")
                                            .map(|s| s.as_bytes()) {
            Some(b) => {
                if b.len() > 1 {
                    return Err("the right input record terminator must be 1 byte long in \
                    utf8".into());
                }
                b[0]
            }
            None => in_terminator
        };


        let args = Args { 
            left_path: left_path.into(),
            right_path: right_path.into(),
            show_left: show_left,
            show_right: show_right,
            show_both: show_both,
            left_key: left_key,
            right_key: right_key,
            in_left_delimiter: in_left_delimiter,
            in_right_delimiter: in_right_delimiter,
            out_delimiter: out_delimiter,
            in_left_terminator: in_left_terminator,
            in_right_terminator: in_right_terminator,
            out_terminator: out_terminator,
            header: header,
        };
        Ok(args)
    }
    pub fn left_path(&self) -> &Path {
        &self.left_path
    }
    pub fn right_path(&self) -> &Path {
        &self.right_path
    }
    pub fn show_left(&self) -> bool {
        self.show_left
    }
    pub fn show_right(&self) -> bool {
        self.show_right
    }
    pub fn show_both(&self) -> bool {
        self.show_both
    }
    pub fn left_key(&self) -> &[usize] {
        &self.left_key
    }
    pub fn right_key(&self) -> &[usize] {
        &self.right_key
    }
    pub fn in_left_delimiter(&self) -> u8 {
        self.in_left_delimiter
    }
    pub fn in_right_delimiter(&self) -> u8 {
        self.in_right_delimiter
    }
    pub fn out_delimiter(&self) -> u8 {
        self.out_delimiter
    }
    pub fn in_left_terminator(&self) -> u8 {
        self.in_left_terminator
    }
    pub fn in_right_terminator(&self) -> u8 {
        self.in_right_terminator
    }
    pub fn out_terminator(&self) -> u8 {
        self.out_terminator
    }
    pub fn header(&self) -> bool {
        self.header
    }
}

        
fn validate_key(k: Vec<&str>, which: &str) -> Result<Vec<usize>, Box<Error>> {
    let out = Ok(k)
        .map(|v| v.iter().map(|s| s.parse::<usize>())
                         .collect::<Vec<_>>())
        .and_then(|v| {
            let mut out: Vec<usize> = Vec::with_capacity(v.len());
            for (x, r) in v.iter().enumerate() {
                match *r {
                    Ok(i) => out.push(i),
                    Err(_) => return Err(format!("could not parse the {}key parameter at \
                                                  the position {}", which, x + 1).into()),
                }
            }
            Ok(out)
        })
        .and_then(|mut v| {
            if v.iter().any(|&i| i < 1) {
                return Err("the key fields must use 1-based numbering".into());
            }
            for i in v.iter_mut() {
               *i -= 1;
            }
            Ok(v)
        });
    out
}