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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
extern crate chrono;
extern crate clap;
extern crate two_timer;

use crate::configure::Configuration;
use crate::log::{parse_line, Filter, Item, LogController, LogLine};
use crate::util::{
    common_search_or_filter_arguments, display_events, display_notes, fatal, remainder, some_nws,
    warn,
};
use chrono::{Duration, Local};
use clap::{App, Arg, ArgMatches, SubCommand};
use std::fs::{copy, remove_file, File};
use std::io::{BufReader, BufWriter, Read, Write};
use std::path::PathBuf;
use std::str::FromStr;
use two_timer::parse;

fn after_help() -> &'static str {
    "\
If you are interrupted in the middle of the task you may want to add a timestamp to \
the log and delay tagging the task until a quieter moment:
    
    job a talking to Captain Distraction

When you are done with this interruption you can return to your prior task, but now you \
need to categorize the interruption. You can `job edit` to add the missing tags, but the \
tag subcommand makes this a little easier. With `job tag --empty --last --add overhead --add communication` or \
perhaps `job t -el -a o -a c` you're back on your way.

All prefixes of 'tag', so 't' and 'ta', are aliases of the subcommand.
"
}

const BUFFER_SIZE: usize = 16 * 1024;

pub fn cli(mast: App<'static, 'static>, display_order: usize) -> App<'static, 'static> {
    mast.subcommand(common_search_or_filter_arguments(
        SubCommand::with_name("tag")
            .aliases(&["t", "ta"])
            .about("Modifies the tags for specified events/notes")
            .after_help(after_help())
            .arg(
                Arg::with_name("period")
                    .help("description of time period of interest")
                    .long_help(
                        "Words describing the period of interest. E.g., 'last week' or '2016-10-2'.",
                    )
                    .value_name("word")
                    .default_value("today")
                    .multiple(true)
            )
            .display_order(display_order),
            None,
    ).arg(
        Arg::with_name("last")
        .long("last")
        .short("l")
        .conflicts_with("first")
        .help("Applies changes only to the last line found")
    ).arg(
        Arg::with_name("first")
        .long("first")
        .short("f")
        .conflicts_with("last")
        .help("Applies changes only to the first line found")
    ).arg(
        Arg::with_name("clear")
        .long("clear")
        .short("c")
        .conflicts_with("remove")
        .help("Removes all existing tags")
    ).arg(
        Arg::with_name("add")
        .long("add")
        .short("a")
        .visible_alias("add-tag")
        .validator(|v| if some_nws(&v) {Ok(())} else {Err(format!("tag {:?} needs some non-whitespace character", v))})
        .multiple(true)
        .number_of_values(1)
        .help("Adds tag")
        .value_name("tag")
    ).arg(
        Arg::with_name("remove")
        .long("remove")
        .short("r")
        .conflicts_with("clear")
        .visible_alias("remove-tag")
        .validator(|v| if some_nws(&v) {Ok(())} else {Err(format!("tag {:?} needs some non-whitespace character", v))})
        .multiple(true)
        .number_of_values(1)
        .help("Removes tag, if present")
        .value_name("tag")
    )
)
}

pub fn run(directory: Option<&str>, matches: &ArgMatches) {
    let conf = Configuration::read(None, directory);
    let mut to_add = if let Some(values) = matches.values_of("add") {
        values.collect::<Vec<_>>()
    } else {
        vec![]
    };
    to_add.sort_unstable();
    to_add.dedup();
    let mut to_remove = if let Some(values) = matches.values_of("remove") {
        values.collect::<Vec<_>>()
    } else {
        vec![]
    };
    to_remove.sort_unstable();
    to_remove.dedup();
    let clear = matches.is_present("clear");
    // some sanity checking
    if clear {
        if matches.is_present("no-tags") {
            warn(
                "there is no point in --clear if you are seeking only items that are --empty",
                &conf,
            );
            if to_add.is_empty() {
                fatal("no tag changes specified: you must --add a tag if you are seeking only items that are --empty", &conf);
            }
        }
    } else {
        let mut common = vec![];
        let filtered_to_add = to_add
            .iter()
            .filter(|s| {
                if to_remove.contains(s) {
                    common.push(**s);
                    false
                } else {
                    true
                }
            })
            .map(|s| *s)
            .collect::<Vec<_>>();
        let filtered_to_remove = to_remove
            .iter()
            .filter(|s| !common.contains(s))
            .map(|s| *s)
            .collect::<Vec<_>>();
        if !common.is_empty() {
            to_add = filtered_to_add;
            to_remove = filtered_to_remove;
            warn(
                format!(
                    "the following tags are to be both added and removed: {}",
                    common.join(", ")
                ),
                &conf,
            );
        }
        if to_add.is_empty() && to_remove.is_empty() {
            fatal(
                "no tag changes specified: you must --clear tags, --add a tag, or --remove a tag",
                &conf,
            );
        }
    }
    let phrase = remainder("period", matches);
    if let Ok((start, end, _)) = parse(&phrase, conf.two_timer_config()) {
        let mut reader = LogController::new(None, &conf).expect("could not read log");
        let now = Local::now().naive_local();
        if let Some(time) = reader.first_timestamp() {
            // narrow the range in to just the dates from the beginning of the log to the present
            // so that we don't have spurious vacation times
            let start = if time > start {
                time.date().and_hms(0, 0, 0)
            } else {
                start
            };
            let time = now.date().and_hms(0, 0, 0) + Duration::days(1);
            let end = if end > time { time } else { end };

            let filter = Filter::new(matches);
            let notes_only = matches.is_present("notes");
            let mut items = reader
                .tagable_items_in_range(&start, &end)
                .into_iter()
                .filter(|i| match i {
                    Item::Note(n, _) => {
                        if notes_only {
                            filter.matches(n)
                        } else {
                            false
                        }
                    }
                    Item::Event(e, _) => {
                        if notes_only {
                            false
                        } else {
                            filter.matches(e)
                        }
                    }
                    _ => false,
                })
                .collect::<Vec<_>>();
            if items.is_empty() {
                fatal(
                    format!("no {} found", if notes_only { "note" } else { "event" }),
                    &conf,
                );
            } else if matches.is_present("last") {
                items = vec![items.remove(items.len() - 1)];
            }
            let mut changed = false;
            items = items
                .into_iter()
                .map(|i| match &i {
                    Item::Note(n, offset) => {
                        let mut tags = vec![];
                        if clear {
                            changed = changed || !n.tags.is_empty();
                        } else {
                            for s in &n.tags {
                                if to_remove.contains(&s.as_str()) {
                                    changed = true;
                                } else {
                                    tags.push(s.clone());
                                }
                            }
                        }
                        for s in &to_add {
                            let s = s.to_string();
                            if !tags.contains(&s) {
                                changed = true;
                                tags.push(s);
                            }
                        }
                        let mut n = n.clone();
                        n.tags = tags;
                        Item::Note(n, *offset)
                    }
                    Item::Event(e, offset) => {
                        let mut tags = vec![];
                        if clear {
                            changed = changed || !e.tags.is_empty();
                        } else {
                            for s in &e.tags {
                                if to_remove.contains(&s.as_str()) {
                                    changed = true;
                                } else {
                                    tags.push(s.clone());
                                }
                            }
                        }
                        for s in &to_add {
                            let s = s.to_string();
                            if !tags.contains(&s) {
                                changed = true;
                                tags.push(s);
                            }
                        }
                        let mut e = e.clone();
                        e.tags = tags;
                        Item::Event(e, *offset)
                    }
                    _ => unreachable!(),
                })
                .collect();
            if changed {
                // create a copy of the log with the desired changes and replace the current log
                // this could be more efficient; maybe some day it will be
                let mut modified_copy = BufWriter::new(modified_copy(&conf));
                let mut buf_reader = BufReader::new(log_file(&conf));
                let byte_offset = reader
                    .larry
                    .offset(items[0].offset())
                    .expect("could not obtain line offset of first item")
                    as usize;
                let mut bytes_written: usize = 0;
                // fill up the log copy up to the offset without parsing bytes
                while bytes_written < byte_offset {
                    let delta = byte_offset - bytes_written;
                    let mut buffer: Vec<u8> = if delta < BUFFER_SIZE {
                        vec![0; delta]
                    } else {
                        vec![0; BUFFER_SIZE]
                    };
                    buf_reader
                        .read_exact(&mut buffer)
                        .expect("could not read from log file");
                    bytes_written += buffer.len();
                    modified_copy
                        .write_all(&buffer)
                        .expect("could not write to validation file");
                }
                // now add the changes and any other lines
                let mut item_offset = 0;
                for line_offset in items[0].offset()..reader.larry.len() {
                    if item_offset == items.len() || items[item_offset].offset() != line_offset {
                        modified_copy
                            .write(
                                reader
                                    .larry
                                    .get(line_offset)
                                    .expect("could not obtain log line")
                                    .as_bytes(),
                            )
                            .expect("could not write log line to log copy");
                    } else {
                        let line = match &items[item_offset] {
                            Item::Event(e, _) => e.to_line(),
                            Item::Note(n, _) => n.to_line(),
                            _ => unreachable!(),
                        };
                        modified_copy
                            .write(line.as_bytes())
                            .expect("could not write log line to log copy");
                        modified_copy
                            .write("\n".as_bytes())
                            .expect("could not add newline to log copy");
                        item_offset += 1;
                    }
                }
                modified_copy
                    .flush()
                    .expect("could not flush log copy buffer");
                copy(copy_path(&conf), log_path(&conf))
                    .expect("could not replace old log with new");
                remove_file(copy_path(&conf)).expect("could not remove log copy");
                // now display the items
                if notes_only {
                    let notes = items
                        .iter()
                        .map(|i| match i {
                            Item::Note(n, _) => n.clone(),
                            _ => unreachable!(),
                        })
                        .collect::<Vec<_>>();
                    display_notes(notes, &start, &end, &conf);
                } else {
                    // we need to create events *with end times*
                    let events = items
                        .iter()
                        .map(|i| match i {
                            Item::Event(e, offset) => {
                                let mut e = e.clone();
                                // look for end time
                                for i in offset + 1..reader.larry.len() {
                                    let i = parse_line(
                                        &reader.larry.get(i).expect("larry failed us"),
                                        0,
                                    );
                                    match &i {
                                        Item::Event(_, _) | Item::Done(_, _) => {
                                            e.end = Some(i.time().unwrap().0.clone())
                                        }
                                        _ => (),
                                    }
                                    if e.end.is_some() {
                                        break;
                                    }
                                }
                                e
                            }
                            _ => unreachable!(),
                        })
                        .collect::<Vec<_>>();
                    display_events(events, &start, &end, &conf);
                }
            } else {
                warn("no change", &conf);
            }
        } else {
            if matches.is_present("notes") {
                warn("no note found", &conf)
            } else {
                warn("no event found", &conf)
            }
        }
    } else {
        fatal(
            format!("could not parse '{}' as a time expression", phrase),
            &conf,
        )
    }
}

fn copy_path(conf: &Configuration) -> PathBuf {
    let mut p = PathBuf::from_str(conf.directory().unwrap())
        .expect("could not obtain JobLog base directory");
    p.push("log.copy");
    p
}

fn modified_copy(conf: &Configuration) -> File {
    File::create(copy_path(conf)).expect("could not produce file into which to write changes")
}

fn log_path(conf: &Configuration) -> PathBuf {
    let mut p = PathBuf::from_str(conf.directory().unwrap())
        .expect("could not obtain JobLog base directory");
    p.push("log");
    p
}

fn log_file(conf: &Configuration) -> File {
    File::open(log_path(conf)).expect("could not produce log file")
}