summaryrefslogtreecommitdiffstats
path: root/bin/domain/imag-todo/src/lib.rs
blob: b2007b49bdc157e50b7ab7050467d51d74866b4e (plain)
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

#![forbid(unsafe_code)]

#![deny(
    non_camel_case_types,
    non_snake_case,
    path_statements,
    trivial_numeric_casts,
    unstable_features,
    unused_allocation,
    unused_import_braces,
    unused_imports,
    unused_must_use,
    unused_mut,
    unused_qualifications,
    while_true,
)]

extern crate clap;
extern crate toml;
extern crate toml_query;
extern crate chrono;
extern crate filters;
extern crate kairos;
#[macro_use] extern crate log;
#[macro_use] extern crate failure;
extern crate resiter;
extern crate handlebars;
extern crate prettytable;

#[cfg(feature = "import-taskwarrior")]
extern crate task_hookrs;

#[cfg(feature = "import-taskwarrior")]
extern crate uuid;

#[cfg(feature = "import-taskwarrior")]
extern crate libimagentrytag;

#[cfg(feature = "import-taskwarrior")]
extern crate libimagentrylink;

extern crate libimagrt;
extern crate libimagstore;
extern crate libimagerror;
extern crate libimagentryedit;
extern crate libimagtodo;
extern crate libimagutil;
extern crate libimagentryview;
extern crate libimaginteraction;

use std::ops::Deref;
use std::io::Write;
use std::result::Result as RResult;
use std::str::FromStr;

use clap::ArgMatches;
use chrono::NaiveDateTime;
use failure::Error;
use failure::Fallible as Result;
use failure::err_msg;
use clap::App;
use resiter::AndThen;
use resiter::IterInnerOkOrElse;
use prettytable::Table;
use prettytable::Cell;
use prettytable::Row;

use libimagentryedit::edit::Edit;
use libimagentryview::viewer::Viewer;
use libimagrt::application::ImagApplication;
use libimagrt::runtime::Runtime;
use libimagstore::iter::get::*;
use libimagstore::store::Entry;
use libimagstore::store::FileLockEntry;
use libimagtodo::entry::Todo;
use libimagtodo::priority::Priority;
use libimagtodo::status::Status;
use libimagtodo::store::TodoStore;

mod ui;
mod import;
mod util;

/// Marker enum for implementing ImagApplication on
///
/// This is used by binaries crates to execute business logic
/// or to build a CLI completion.
pub enum ImagTodo {}
impl ImagApplication for ImagTodo {
    fn run(rt: Runtime) -> Result<()> {
        match rt.cli().subcommand_name() {
            Some("create")      => create(&rt),
            Some("show")        => show(&rt),
            Some("mark")           => mark(&rt),
            Some("pending") | None => list_todos(&rt, &StatusMatcher::new().is(Status::Pending), false),
            Some("list")           => list(&rt),
            Some("import")         => import::import(&rt),
            Some(other)         => {
                debug!("Unknown command");
                if rt.handle_unknown_subcommand("imag-todo", other, rt.cli())?.success() {
                    Ok(())
                } else {
                    Err(err_msg("Failed to handle unknown subcommand"))
                }
            }
        } // end match scmd
    }

    fn build_cli<'a>(app: App<'a, 'a>) -> App<'a, 'a> {
        ui::build_ui(app)
    }

    fn name() -> &'static str {
        env!("CARGO_PKG_NAME")
    }

    fn description() -> &'static str {
        "Interface with taskwarrior"
    }

    fn version() -> &'static str {
        env!("CARGO_PKG_VERSION")
    }
}

/// A black- and whitelist for matching statuses of todo entries
///
/// The blacklist is checked first, followed by the whitelist.
/// In case the whitelist is empty, the StatusMatcher works with a
/// blacklist-only approach.
#[derive(Debug, Default)]
pub struct StatusMatcher {
    is: Vec<Status>,
    is_not: Vec<Status>,
}

impl StatusMatcher {
    pub fn new() -> Self {
        StatusMatcher { ..Default::default() }
    }

    pub fn is(mut self, s: Status) -> Self {
        self.add_is(s);
        self
    }

    pub fn add_is(&mut self, s: Status) {
        self.is.push(s);
    }

    #[allow(clippy::wrong_self_convention)]
    pub fn is_not(mut self, s: Status) -> Self {
        self.add_is_not(s);
        self
    }

    pub fn add_is_not(&mut self, s: Status) {
        self.is_not.push(s);
    }

    pub fn matches(&self, todo: Status) -> bool {
        if self.is_not.iter().any(|t| *t == todo) {
            // On blacklist
            false
        } else {
            // No whitelist or on whitelist
            // or
            // Not on blacklist, but whitelist exists and not on it either
            self.is.is_empty() || self.is.iter().any(|t| *t == todo)
        }
    }
}

fn create(rt: &Runtime) -> Result<()> {
    debug!("Creating todo");
    let scmd = rt.cli().subcommand().1.unwrap(); // safe by clap

    let scheduled: Option<NaiveDateTime> = get_datetime_arg(&scmd, "create-scheduled")?;
    let hidden: Option<NaiveDateTime>    = get_datetime_arg(&scmd, "create-hidden")?;
    let due: Option<NaiveDateTime>       = get_datetime_arg(&scmd, "create-due")?;
    let prio: Option<Priority>           = scmd.value_of("create-prio").map(prio_from_str).transpose()?;
    let status: Status                   = scmd.value_of("create-status").map(Status::from_str).unwrap()?;
    let edit                             = scmd.is_present("create-edit");
    let text                             = scmd.value_of("text").unwrap();

    trace!("Creating todo with these variables:");
    trace!("scheduled = {:?}", scheduled);
    trace!("hidden    = {:?}", hidden);
    trace!("due       = {:?}", due);
    trace!("prio      = {:?}", prio);
    trace!("status    = {:?}", status);
    trace!("edit      = {}", edit);
    trace!("text      = {:?}", text);

    let mut entry = rt.store().create_todo(status, scheduled, hidden, due, prio, true)?;
    debug!("Created: todo {}", entry.get_uuid()?);

    debug!("Setting content");
    *entry.get_content_mut() = text.to_string();

    if edit {
        debug!("Editing content");
        entry.edit_content(&rt)?;
    }

    rt.report_touched(entry.get_location())
}

fn mark(rt: &Runtime) -> Result<()> {
    fn mark_todos_as(rt: &Runtime, status: Status) -> Result<()> {
        rt.ids::<crate::ui::PathProvider>()?
            .ok_or_else(|| err_msg("No ids supplied"))?
            .into_iter()
            .map(Ok)
            .into_get_iter(rt.store())
            .map_inner_ok_or_else(|| err_msg("Did not find one entry"))
            .and_then_ok(|e| rt.report_touched(e.get_location()).map(|_| e))
            .and_then_ok(|mut e| e.set_status(status.clone()))
            .collect()
    }

    let scmd = rt.cli().subcommand().1.unwrap();
    match scmd.subcommand_name() {
        Some("done")    => mark_todos_as(rt, Status::Done),
        Some("deleted") => mark_todos_as(rt, Status::Deleted),
        Some("pending") => mark_todos_as(rt, Status::Pending),
        Some(other)     => Err(format_err!("Unknown mark type selected: {}", other)),
        None            => Err(format_err!("No mark type selected, doing nothing!")),
    }
}

/// Generic todo listing function
///
/// Supports filtering of todos by status using the passed in StatusMatcher
fn list_todos(rt: &Runtime, matcher: &StatusMatcher, show_hidden: bool) -> Result<()> {
    use filters::failable::filter::FailableFilter;
    debug!("Listing todos with status filter {:?}", matcher);

    struct TodoViewer {
        details: bool,
    }
    impl Viewer for TodoViewer {
        fn view_entry<W>(&self, entry: &Entry, sink: &mut W) -> RResult<(), libimagentryview::error::Error>
            where W: Write
        {
            use libimagentryview::error::Error as E;

            if !entry.is_todo().map_err(E::from)? {
                return Err(format_err!("Not a Todo: {}", entry.get_location())).map_err(E::from);
            }

            let uuid     = entry.get_uuid().map_err(E::from)?;
            let status   = entry.get_status().map_err(E::from)?;
            let status   = status.as_str();
            let first_line = entry.get_content()
                .lines()
                .next()
                .unwrap_or("<empty description>");

            if !self.details {
                writeln!(sink, "{uuid} - {status} : {first_line}",
                         uuid = uuid,
                         status = status,
                         first_line = first_line)
            } else {
                let sched    = util::get_dt_str(entry.get_scheduled(), "Not scheduled")?;
                let hidden   = util::get_dt_str(entry.get_hidden(), "Not hidden")?;
                let due      = util::get_dt_str(entry.get_due(), "No due")?;
                let priority = entry.get_priority().map_err(E::from)?.map(|p| p.as_str().to_string())
                    .unwrap_or_else(|| "No prio".to_string());

                writeln!(sink, "{uuid} - {status} - {sched} - {hidden} - {due} - {prio}: {first_line}",
                         uuid = uuid,
                         status = status,
                         sched = sched,
                         hidden = hidden,
                         due = due,
                         prio = priority,
                         first_line = first_line)
            }
            .map_err(libimagentryview::error::Error::from)
        }
    }

    fn process<'a, I>(rt: &Runtime, matcher: &StatusMatcher, show_hidden: bool, iter: I) -> Result<()>
        where I: Iterator<Item = Result<FileLockEntry<'a>>> + Sized
    {
        let viewer = TodoViewer { details: false };

        let now = {
            let now = chrono::offset::Local::now();
            NaiveDateTime::new(now.date().naive_local(), now.time())
        };

        let filter_hidden = |todo: &FileLockEntry<'_>| -> Result<bool> {
            Ok(todo.get_hidden()?.map(|hid| hid > now).unwrap_or(true))
        };

        iter
            .filter_map(|r| {
                match r.and_then(|e| e.get_status().map(|s| (s, e))) {
                    Err(e) => Some(Err(e)),
                    Ok((st, e)) => if matcher.matches(st) {
                        Some(Ok(e))
                    } else {
                        None
                    }
                }
            })
            .and_then_ok(|entry| {
                if !rt.output_is_pipe() && (show_hidden || filter_hidden.filter(&entry)?) {
                    if let Err(e) = viewer.view_entry(&entry, &mut rt.stdout()) {
                        use libimagentryview::error::Error;
                        match e {
                            Error::Other(e) => return Err(e),
                            Error::Io(e)    => if e.kind() != std::io::ErrorKind::BrokenPipe {
                                return Err(failure::Error::from(e))
                            },
                        }
                    }
                }

                rt.report_touched(entry.get_location())
            })
            .collect()
    };

    if rt.ids_from_stdin() {
        let iter = rt.ids::<crate::ui::PathProvider>()?
            .ok_or_else(|| err_msg("No ids supplied"))?
            .into_iter()
            .map(Ok)
            .into_get_iter(rt.store())
            .map_inner_ok_or_else(|| err_msg("Did not find one entry"));

        process(&rt, matcher, show_hidden, iter)
    } else {
        let iter = rt.store().get_todos()?
            .into_get_iter()
            .map_inner_ok_or_else(|| err_msg("Did not find one entry"));

        process(&rt, matcher, show_hidden, iter)
    }
}

/// Generic todo items list function
///
/// This sets up filtes based on the command line and prints out a list of todos
fn list(rt: &Runtime) -> Result<()> {
    debug!("Listing todo");
    let scmd      = rt.cli().subcommand().1;
    let table     = scmd.map(|s| s.is_present("list-table")).unwrap_or(true);
    let hidden    = scmd.map(|s| s.is_present("list-hidden")).unwrap_or(false);
    let done      = scmd.map(|s| s.is_present("list-done")).unwrap_or(false);
    let nopending = scmd.map(|s| s.is_present("list-nopending")).unwrap_or(true);

    trace!("table     = {}", table);
    trace!("hidden    = {}", hidden);
    trace!("done      = {}", done);
    trace!("nopending = {}", nopending);

    let mut matcher = StatusMatcher::new();
    if !done { matcher.add_is_not(Status::Done); }
    if nopending { matcher.add_is_not(Status::Pending); }

    // TODO: Support printing as ASCII table
    list_todos(rt, &matcher, hidden)
}

fn show(rt: &Runtime) -> Result<()> {
    let scmd        = rt.cli().subcommand_matches("show").unwrap();
    let show_format = util::get_todo_print_format("todo.show_format", rt, &scmd)?;
    let out         = rt.stdout();
    let mut outlock = out.lock();

    fn show_with_table<'a, I>(rt: &Runtime, iter: I) -> Result<()>
        where I: Iterator<Item = FileLockEntry<'a>>
    {
        const HEADER: &[&str] = &[
            "uuid",
            "status",
            "sched",
            "hidden",
            "due",
            "priority",
            "text",
        ];

        let mut table = {
            let mut t = Table::new();
            let header = HEADER.iter().map(|s| Cell::new(s)).collect::<Vec<Cell>>();
            t.set_titles(Row::from(header));
            t
        };

        iter.map(|entry| {
            use libimagentryview::error::Error as E;

            let uuid     = entry.get_uuid().map_err(E::from)?.to_hyphenated().to_string();
            let status   = entry.get_status().map_err(E::from)?;
            let status   = status.as_str().to_string();
            let sched    = util::get_dt_str(entry.get_scheduled(), "Not scheduled")?;
            let hidden   = util::get_dt_str(entry.get_hidden(), "Not hidden")?;
            let due      = util::get_dt_str(entry.get_due(), "No due")?;
            let priority = entry.get_priority().map_err(E::from)?.map(|p| p.as_str().to_string()).unwrap_or_else(|| "No prio".to_string());

            let text     = entry.get_content().to_owned();

            let v = [
                uuid,
                status,
                sched,
                hidden,
                due,
                priority,
                text,
            ];
            table.add_row(v.iter().map(|s| Cell::new(s)).collect());

            Ok(entry)
        })
        .and_then_ok(|e| rt.report_touched(e.get_location()).map_err(Error::from).map(|_| e))
        .collect::<Result<Vec<_>>>()?;

        table.print(&mut rt.stdout())
            .map(|_| ())
            .map_err(Error::from)
    }

    let iter = rt
        .ids::<crate::ui::PathProvider>()?
        .ok_or_else(|| err_msg("No ids supplied"))?
        .into_iter()
        .map(Ok)
        .into_get_iter(rt.store())
        .map_inner_ok_or_else(|| err_msg("Did not find one entry"))
        .and_then_ok(|e| rt.report_touched(e.get_location()).map(|_| e))
        .collect::<Result<Vec<_>>>()?
        .into_iter();

    if scmd.is_present("show-no-table") {
        iter.enumerate()
            .map(|(i, elem)| {
                let data = util::build_data_object_for_handlebars(i, elem.deref())?;
                let s = show_format.render("format", &data)?;
                writeln!(outlock, "{}", s).map_err(Error::from)
            })
            .collect()
    } else {
        show_with_table(rt, iter)
    }
}

//
// utility functions
//

fn get_datetime_arg(scmd: &ArgMatches, argname: &'static str) -> Result<Option<NaiveDateTime>> {
    use kairos::timetype::TimeType;
    use kairos::parser;

    match scmd.value_of(argname) {
        None => Ok(None),
        Some(v) => match parser::parse(v)? {
            parser::Parsed::TimeType(TimeType::Moment(moment)) => Ok(Some(moment)),
            parser::Parsed::TimeType(other) => {
                Err(format_err!("You did not pass a date, but a {}", other.name()))
            },
            parser::Parsed::Iterator(_) => {
                Err(format_err!("Argument {} results in a list of dates, but we need a single date.", v))
            }
        }
    }
}

fn prio_from_str<S: AsRef<str>>(s: S) -> Result<Priority> {
    match s.as_ref() {
        "h" => Ok(Priority::High),
        "m" => Ok(Priority::Medium),
        "l" => Ok(Priority::Low),
        other => Err(format_err!("Unsupported Priority: '{}'", other)),
    }
}