libimagheadercmd/
lib.rs

1//
2// imag - the personal information management suite for the commandline
3// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
4//
5// This library is free software; you can redistribute it and/or
6// modify it under the terms of the GNU Lesser General Public
7// License as published by the Free Software Foundation; version
8// 2.1 of the License.
9//
10// This library is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13// Lesser General Public License for more details.
14//
15// You should have received a copy of the GNU Lesser General Public
16// License along with this library; if not, write to the Free Software
17// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
18//
19
20#![deny(
21    non_camel_case_types,
22    non_snake_case,
23    path_statements,
24    trivial_numeric_casts,
25    unstable_features,
26    unused_allocation,
27    unused_import_braces,
28    unused_imports,
29    unused_must_use,
30    unused_mut,
31    unused_qualifications,
32    while_true,
33)]
34
35extern crate clap;
36#[macro_use] extern crate log;
37#[macro_use] extern crate failure;
38extern crate toml;
39extern crate toml_query;
40extern crate filters;
41extern crate resiter;
42
43extern crate libimagentryedit;
44extern crate libimagerror;
45extern crate libimagrt;
46extern crate libimagstore;
47extern crate libimagutil;
48
49use std::io::Write;
50use std::str::FromStr;
51use std::string::ToString;
52
53use clap::{App, ArgMatches};
54use filters::filter::Filter;
55use toml::Value;
56use failure::Error;
57use failure::Fallible as Result;
58use failure::err_msg;
59use resiter::FilterMap;
60use resiter::AndThen;
61use resiter::IterInnerOkOrElse;
62
63use libimagrt::runtime::Runtime;
64use libimagrt::application::ImagApplication;
65use libimagstore::iter::get::StoreIdGetIteratorExtension;
66use libimagstore::store::FileLockEntry;
67
68use toml_query::read::TomlValueReadExt;
69use toml_query::read::TomlValueReadTypeExt;
70
71mod ui;
72
73const EPS_CMP: f64 = 1e-10;
74
75/// Marker enum for implementing ImagApplication on
76///
77/// This is used by binaries crates to execute business logic
78/// or to build a CLI completion.
79pub enum ImagHeader {}
80impl ImagApplication for ImagHeader {
81    fn run(rt: Runtime) -> Result<()> {
82        let list_output_with_ids     = rt.cli().is_present("list-id");
83        let list_output_with_ids_fmt = rt.cli().value_of("list-id-format");
84
85        trace!("list_output_with_ids     = {:?}", list_output_with_ids );
86        trace!("list_output_with_ids_fmt = {:?}", list_output_with_ids_fmt);
87
88        let iter = rt
89            .ids::<crate::ui::PathProvider>()?
90            .ok_or_else(|| err_msg("No ids supplied"))?
91            .into_iter()
92            .map(Ok)
93            .into_get_iter(rt.store())
94            .map_inner_ok_or_else(|| err_msg("Did not find one entry"));
95
96        match rt.cli().subcommand() {
97            ("read", Some(mtch))   => read(&rt, mtch, iter),
98            ("has", Some(mtch))    => has(&rt, mtch, iter),
99            ("hasnt", Some(mtch))  => hasnt(&rt, mtch, iter),
100            ("int", Some(mtch))    => int(&rt, mtch, iter),
101            ("float", Some(mtch))  => float(&rt, mtch, iter),
102            ("string", Some(mtch)) => string(&rt, mtch, iter),
103            ("bool", Some(mtch))   => boolean(&rt, mtch, iter),
104            (other, _mtchs) => {
105                debug!("Unknown command");
106                if rt.handle_unknown_subcommand("imag-header", other, rt.cli())
107                    .map_err(Error::from)?
108                    .success()
109                {
110                    Ok(())
111                } else {
112                    Err(format_err!("Subcommand failed"))
113                }
114            },
115        }
116    }
117
118    fn build_cli<'a>(app: App<'a, 'a>) -> App<'a, 'a> {
119        ui::build_ui(app)
120    }
121
122    fn name() -> &'static str {
123        env!("CARGO_PKG_NAME")
124    }
125
126    fn description() -> &'static str {
127        "Plumbing tool for reading/writing structured data in entries"
128    }
129
130    fn version() -> &'static str {
131        env!("CARGO_PKG_VERSION")
132    }
133}
134
135fn read<'a, 'e, I>(rt: &Runtime, mtch: &ArgMatches<'a>, iter: I) -> Result<()>
136    where I: Iterator<Item = Result<FileLockEntry<'e>>>
137{
138    debug!("Processing headers: reading value");
139    let header_path = get_header_path(mtch, "header-value-path");
140    let mut output = rt.stdout();
141    trace!("Got output: {:?}", output);
142
143    iter.and_then_ok(|entry| {
144        trace!("Processing headers: working on {:?}", entry.get_location());
145        entry.get_header()
146            .read(header_path)?
147            .ok_or_else(|| format_err!("Value not present for entry {} at {}", entry.get_location(), header_path))
148            .and_then(|value| {
149                trace!("Processing headers: Got value {:?}", value);
150
151                let string_representation = match value {
152                    Value::String(s)  => Some(s.to_owned()),
153                    Value::Integer(i) => Some(i.to_string()),
154                    Value::Float(f)   => Some(f.to_string()),
155                    Value::Boolean(b) => Some(b.to_string()),
156                    _ => None,
157                };
158
159                if let Some(repr) = string_representation {
160                    writeln!(output, "{}", repr)?;
161                } else {
162                    writeln!(output, "{}", value)?;
163                }
164                Ok(())
165            })
166    })
167    .collect::<Result<()>>()
168}
169
170fn has<'a, 'e, I>(rt: &Runtime, mtch: &ArgMatches<'a>, iter: I) -> Result<()>
171    where I: Iterator<Item = Result<FileLockEntry<'e>>>
172{
173    debug!("Processing headers: has value");
174    let header_path = get_header_path(mtch, "header-value-path");
175    let mut output = rt.stdout();
176
177    iter.and_then_ok(|entry| {
178        trace!("Processing headers: working on {:?}", entry.get_location());
179        if entry.get_header().read(header_path)?.is_some() {
180            if !rt.output_is_pipe() {
181                writeln!(output, "{}", entry.get_location())?;
182            }
183            rt.report_touched(entry.get_location())
184        } else {
185            Ok(())
186        }
187    })
188    .collect::<Result<()>>()
189}
190
191fn hasnt<'a, 'e, I>(rt: &Runtime, mtch: &ArgMatches<'a>, iter: I) -> Result<()>
192    where I: Iterator<Item = Result<FileLockEntry<'e>>>
193{
194    debug!("Processing headers: hasnt value");
195    let header_path = get_header_path(mtch, "header-value-path");
196    let mut output = rt.stdout();
197
198    iter.and_then_ok(|entry| {
199        trace!("Processing headers: working on {:?}", entry.get_location());
200        if entry.get_header().read(header_path)?.is_some() {
201            Ok(())
202        } else {
203            if !rt.output_is_pipe() {
204                writeln!(output, "{}", entry.get_location())?;
205            }
206            rt.report_touched(entry.get_location())
207        }
208    })
209    .collect()
210}
211
212macro_rules! implement_compare {
213    { $mtch: ident, $path: expr, $t: ty, $compare: expr } => {{
214        trace!("Getting value at {}, comparing as {}", $path, stringify!($t));
215        if let Some(cmp) = $mtch.value_of($path).map(FromStr::from_str) {
216            let cmp : $t = cmp.unwrap(); // safe by clap
217            trace!("Getting value at {} = {}", $path, cmp);
218            $compare(cmp)
219        } else {
220            true
221        }
222    }}
223}
224
225fn int<'a, 'e, I>(rt: &Runtime, mtch: &ArgMatches<'a>, iter: I) -> Result<()>
226    where I: Iterator<Item = Result<FileLockEntry<'e>>>
227{
228    debug!("Processing headers: int value");
229    let header_path = get_header_path(mtch, "header-value-path");
230
231    let filter = ::filters::ops::bool::Bool::new(true)
232        .and(|i: &i64| -> bool {
233            implement_compare!(mtch, "header-int-eq", i64, |cmp| *i == cmp)
234        })
235        .and(|i: &i64| -> bool {
236            implement_compare!(mtch, "header-int-neq", i64, |cmp| *i != cmp)
237        })
238        .and(|i: &i64| -> bool {
239            implement_compare!(mtch, "header-int-lt", i64, |cmp| *i < cmp)
240        })
241        .and(|i: &i64| -> bool {
242            implement_compare!(mtch, "header-int-gt", i64, |cmp| *i > cmp)
243        })
244        .and(|i: &i64| -> bool {
245            implement_compare!(mtch, "header-int-lte", i64, |cmp| *i <= cmp)
246        })
247        .and(|i: &i64| -> bool {
248            implement_compare!(mtch, "header-int-gte", i64, |cmp| *i >= cmp)
249        });
250
251    iter.and_then_ok(|entry| {
252        if let Some(hdr) = entry.get_header().read_int(header_path)?  {
253            Ok((filter.filter(&hdr), entry))
254        } else {
255            Ok((false, entry))
256        }
257    })
258    .filter_map_ok(|(b, e)| if b { Some(e) } else { None })
259    .and_then_ok(|entry| rt.report_touched(entry.get_location()))
260    .collect()
261}
262
263fn float<'a, 'e, I>(rt: &Runtime, mtch: &ArgMatches<'a>, iter: I) -> Result<()>
264    where I: Iterator<Item = Result<FileLockEntry<'e>>>
265{
266    debug!("Processing headers: float value");
267    let header_path = get_header_path(mtch, "header-value-path");
268
269    let filter = ::filters::ops::bool::Bool::new(true)
270        .and(|i: &f64| -> bool {
271            implement_compare!(mtch, "header-float-eq", f64, |cmp: f64| (*i - cmp).abs() < EPS_CMP)
272        })
273        .and(|i: &f64| -> bool {
274            implement_compare!(mtch, "header-float-neq", f64, |cmp: f64| (*i - cmp).abs() > EPS_CMP)
275        })
276        .and(|i: &f64| -> bool {
277            implement_compare!(mtch, "header-float-lt", f64, |cmp| *i < cmp)
278        })
279        .and(|i: &f64| -> bool {
280            implement_compare!(mtch, "header-float-gt", f64, |cmp| *i > cmp)
281        })
282        .and(|i: &f64| -> bool {
283            implement_compare!(mtch, "header-float-lte", f64, |cmp| *i <= cmp)
284        })
285        .and(|i: &f64| -> bool {
286            implement_compare!(mtch, "header-float-gte", f64, |cmp| *i >= cmp)
287        });
288
289    iter.and_then_ok(|entry| {
290        if let Some(hdr) = entry.get_header().read_float(header_path)? {
291            Ok((filter.filter(&hdr), entry))
292        } else {
293            Ok((false, entry))
294        }
295    })
296    .filter_map_ok(|(b, e)| if b { Some(e) } else { None })
297    .and_then_ok(|entry| rt.report_touched(entry.get_location()))
298    .collect()
299}
300
301fn string<'a, 'e, I>(rt: &Runtime, mtch: &ArgMatches<'a>, iter: I) -> Result<()>
302    where I: Iterator<Item = Result<FileLockEntry<'e>>>
303{
304    debug!("Processing headers: string value");
305    let header_path = get_header_path(mtch, "header-value-path");
306
307    let filter = ::filters::ops::bool::Bool::new(true)
308        .and(|i: &String| -> bool {
309            implement_compare!(mtch, "header-string-eq", String, |cmp| *i == cmp)
310        })
311        .and(|i: &String| -> bool {
312            implement_compare!(mtch, "header-string-neq", String, |cmp| *i != cmp)
313        });
314
315    iter.and_then_ok(|entry| {
316        if let Some(hdr) = entry.get_header().read_string(header_path)?  {
317            Ok((filter.filter(&hdr), entry))
318        } else {
319            Ok((false, entry))
320        }
321    })
322    .filter_map_ok(|(b, e)| if b { Some(e) } else { None })
323    .and_then_ok(|entry| rt.report_touched(entry.get_location()))
324    .collect()
325}
326
327fn boolean<'a, 'e, I>(rt: &Runtime, mtch: &ArgMatches<'a>, iter: I) -> Result<()>
328    where I: Iterator<Item = Result<FileLockEntry<'e>>>
329{
330    debug!("Processing headers: bool value");
331    let header_path = get_header_path(mtch, "header-value-path");
332
333    let filter = ::filters::ops::bool::Bool::new(true)
334        .and(|i: &bool| -> bool { *i })
335        .and(|i: &bool| -> bool { *i });
336
337    iter.and_then_ok(|entry| {
338        if let Some(hdr) = entry.get_header().read_bool(header_path)?  {
339            Ok((filter.filter(&hdr), entry))
340        } else {
341            Ok((false, entry))
342        }
343    })
344    .filter_map_ok(|(b, e)| if b { Some(e) } else { None })
345    .and_then_ok(|entry| rt.report_touched(entry.get_location()))
346    .collect()
347}
348
349
350
351// helpers
352//
353fn get_header_path<'a>(mtch: &'a ArgMatches<'a>, path: &'static str) -> &'a str {
354    let header_path = mtch.value_of(path).unwrap(); // safe by clap
355    debug!("Processing headers: header path = {}", header_path);
356    header_path
357}
358