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
//
// 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;
#[macro_use] extern crate is_match;
#[macro_use] extern crate log;
extern crate toml;
extern crate toml_query;
extern crate itertools;
extern crate failure;
extern crate textwrap;
extern crate resiter;

extern crate libimaglog;
extern crate libimagrt;
extern crate libimagstore;
extern crate libimagerror;
extern crate libimagdiary;

use std::io::Write;
use std::io::Cursor;
use std::str::FromStr;

use failure::Error;
use failure::err_msg;
use failure::Fallible as Result;
use resiter::Map;
use resiter::AndThen;
use resiter::IterInnerOkOrElse;
use resiter::Filter;

use libimagrt::application::ImagApplication;
use libimagrt::runtime::Runtime;
use libimagdiary::diary::Diary;
use libimagdiary::diaryid::DiaryId;
use libimaglog::log::Log;
use libimagstore::iter::get::StoreIdGetIteratorExtension;
use libimagstore::store::FileLockEntry;

use clap::App;

mod ui;

use toml::Value;
use itertools::Itertools;

/// Marker enum for implementing ImagApplication on
///
/// This is used by binaries crates to execute business logic
/// or to build a CLI completion.
pub enum ImagLog {}
impl ImagApplication for ImagLog {
    fn run(rt: Runtime) -> Result<()> {
        if let Some(scmd) = rt.cli().subcommand_name() {
            match scmd {
                "show" => show(&rt),
                other  => {
                    debug!("Unknown command");
                    if rt.handle_unknown_subcommand("imag-bookmark", other, rt.cli())?.success() {
                        Ok(())
                    } else {
                        Err(err_msg("Failed to handle unknown subcommand"))
                    }
                },
            }
        } else {
            let text       = get_log_text(&rt);
            let diary_name = match rt.cli().value_of("diaryname").map(String::from) {
                Some(s) => s,
                None => get_diary_name(&rt)?,
            };

            debug!("Writing to '{}': {}", diary_name, text);

            rt.store()
                .new_entry_now(&diary_name)
                .and_then(|mut fle| {
                    fle.make_log_entry()?;
                    *fle.get_content_mut() = text;
                    Ok(fle)
                })
                .and_then(|fle| rt.report_touched(fle.get_location()).map_err(Error::from))
        }
    }

    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 {
        "Overlay to imag-diary to 'log' single lines of text"
    }

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

fn show(rt: &Runtime) -> Result<()> {
    use std::borrow::Cow;

    use libimagdiary::iter::DiaryEntryIterator;
    use libimagdiary::entry::DiaryEntry;

    let scmd = rt.cli().subcommand_matches("show").unwrap(); // safed by main()
    let iters : Vec<DiaryEntryIterator> = match scmd.values_of("show-name") {
        Some(values) => values
            .map(|diary_name| Diary::entries(rt.store(), diary_name))
            .collect::<Result<Vec<DiaryEntryIterator>>>(),

        None => if scmd.is_present("show-all") {
            debug!("Showing for all diaries");
            let iter = rt.store()
                .diary_names()?
                .map(|diary_name| {
                    let diary_name = diary_name?;
                    debug!("Getting entries for Diary: {}", diary_name);
                    let entries = Diary::entries(rt.store(), &diary_name)?;
                    let diary_name = Cow::from(diary_name);
                    Ok((entries, diary_name))
                })
                .collect::<Result<Vec<(DiaryEntryIterator, Cow<str>)>>>()?;

            let iter = iter.into_iter()
                .unique_by(|tpl| tpl.1.clone())
                .map(|tpl| tpl.0)
                .collect::<Vec<DiaryEntryIterator>>();

            Ok(iter)
        } else {
            // showing default logs
            get_diary_name(rt).and_then(|dname| Diary::entries(rt.store(), &dname)).map(|e| vec![e])
        }
    }?;

    let mut do_wrap = if scmd.is_present("show-wrap") {
        Some(80)
    } else {
        None
    };
    let do_remove_newlines = scmd.is_present("show-skipnewlines");

    if let Some(wrap_value) = scmd.value_of("show-wrap") {
        do_wrap = Some(usize::from_str(wrap_value).map_err(Error::from)?);
    }

    let mut output = rt.stdout();

    let v = iters.into_iter()
        .flatten()
        .into_get_iter(rt.store())
        .map_inner_ok_or_else(|| err_msg("Did not find one entry"))
        .and_then_ok(|e| e.is_log().map(|b| (b, e)))
        .filter_ok(|tpl| tpl.0)
        .map_ok(|tpl| tpl.1)
        .and_then_ok(|entry| entry.diary_id().map(|did| (did.get_date_representation(), did, entry)))
        .collect::<Result<Vec<_>>>()?;

    v.into_iter()
        .sorted_by_key(|tpl| tpl.0)
        .map(|tpl| (tpl.1, tpl.2))
        .inspect(|tpl| debug!("Found entry: {:?}", tpl.1))
        .map(|(id, entry)| {
            if let Some(wrap_limit) = do_wrap {
                // assume a capacity here:
                // diaryname + year + month + day + hour + minute + delimiters + whitespace
                // 10 + 4 + 2 + 2 + 2 + 2 + 6 + 4 = 32
                // plus text, which we assume to be 120 characters... lets allocate 256 bytes.
                let mut buffer = Cursor::new(Vec::with_capacity(256));
                do_write_to(&mut buffer, id, &entry, do_remove_newlines)?;
                let buffer = String::from_utf8(buffer.into_inner())?;

                // now lets wrap
                ::textwrap::wrap(&buffer, wrap_limit)
                    .iter()
                    .map(|line| writeln!(&mut output, "{}", line).map_err(Error::from))
                    .collect::<Result<Vec<_>>>()?;
            } else {
                do_write_to(&mut output, id, &entry, do_remove_newlines)?;
            }

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

fn get_diary_name(rt: &Runtime) -> Result<String> {
    use toml_query::read::TomlValueReadExt;
    use toml_query::read::TomlValueReadTypeExt;

    let cfg = rt
        .config()
        .ok_or_else(|| err_msg("Configuration not present, cannot continue"))?;

    let current_log = cfg
        .read_string("log.default")?
        .ok_or_else(|| err_msg("Configuration missing: 'log.default'"))?;

    if cfg
        .read("log.logs")?
        .ok_or_else(|| err_msg("Configuration missing: 'log.logs'"))?
        .as_array()
        .ok_or_else(|| err_msg("Configuration 'log.logs' is not an Array"))?
        .iter()
        .map(|e| if !is_match!(e, &Value::String(_)) {
            Err(err_msg("Configuration 'log.logs' is not an Array<String>!"))
        } else {
            Ok(e)
        })
        .map_ok(|value| value.as_str().unwrap())
        .map_ok(String::from)
        .collect::<Result<Vec<_>>>()?
        .iter()
        .find(|log| *log == &current_log)
        .is_none()
    {
        Err(err_msg("'log.logs' does not contain 'log.default'"))
    } else {
        Ok(current_log)
    }
}

fn get_log_text(rt: &Runtime) -> String {
    rt.cli()
        .values_of("text")
        .unwrap() // safe by clap
        .enumerate()
        .fold(String::with_capacity(500), |mut acc, (n, e)| {
            if n != 0 {
                acc.push_str(" ");
            }
            acc.push_str(e);
            acc
        })
}

fn do_write_to<'a>(sink: &mut dyn Write, id: DiaryId, entry: &FileLockEntry<'a>, do_remove_newlines: bool) -> Result<()> {
    let text = if do_remove_newlines {
        entry.get_content().trim_end().replace("\n", "")
    } else {
        entry.get_content().trim_end().to_string()
    };

    writeln!(sink,
            "{dname: >10} - {y: >4}-{m:0>2}-{d:0>2}T{H:0>2}:{M:0>2} - {text}",
             dname = id.diary_name(),
             y = id.year(),
             m = id.month(),
             d = id.day(),
             H = id.hour(),
             M = id.minute(),
             text = text)
        .map_err(Error::from)
}