libimagviewcmd/
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#![forbid(unsafe_code)]
21
22#![deny(
23    non_camel_case_types,
24    non_snake_case,
25    path_statements,
26    trivial_numeric_casts,
27    unstable_features,
28    unused_allocation,
29    unused_import_braces,
30    unused_imports,
31    unused_must_use,
32    unused_mut,
33    unused_qualifications,
34    while_true,
35)]
36
37extern crate clap;
38#[macro_use] extern crate log;
39extern crate handlebars;
40extern crate tempfile;
41extern crate toml;
42extern crate toml_query;
43#[macro_use] extern crate failure;
44extern crate resiter;
45
46extern crate libimagentryview;
47extern crate libimagerror;
48extern crate libimagrt;
49extern crate libimagstore;
50extern crate libimagutil;
51
52use std::str::FromStr;
53use std::collections::BTreeMap;
54use std::io::Write;
55use std::process::Command;
56
57use handlebars::Handlebars;
58use toml_query::read::TomlValueReadTypeExt;
59use failure::err_msg;
60use failure::Fallible as Result;
61use resiter::AndThen;
62use resiter::IterInnerOkOrElse;
63use clap::App;
64
65use libimagrt::runtime::Runtime;
66use libimagrt::application::ImagApplication;
67use libimagentryview::builtin::stdout::StdoutViewer;
68use libimagentryview::builtin::md::MarkdownViewer;
69use libimagentryview::viewer::Viewer;
70use libimagstore::iter::get::StoreIdGetIteratorExtension;
71use libimagstore::store::FileLockEntry;
72
73mod ui;
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 ImagView {}
80impl ImagApplication for ImagView {
81    fn run(rt: Runtime) -> Result<()> {
82        let view_header  = rt.cli().is_present("view-header");
83        let hide_content = rt.cli().is_present("not-view-content");
84        let entries      = rt
85            .ids::<::ui::PathProvider>()?
86            .ok_or_else(|| err_msg("No ids supplied"))?
87            .into_iter()
88            .map(Ok)
89            .into_get_iter(rt.store())
90            .map_inner_ok_or_else(|| err_msg("Entry not found, please report this as a bug"));
91
92        if rt.cli().is_present("in") {
93            let files = entries
94                .and_then_ok(|entry| {
95                    let tmpfile = create_tempfile_for(&entry, view_header, hide_content)?;
96                    rt.report_touched(entry.get_location())?;
97                    Ok(tmpfile)
98                })
99                .collect::<Result<Vec<_>>>()?;
100
101            let mut command = {
102                let viewer = rt
103                    .cli()
104                    .value_of("in")
105                    .ok_or_else(|| err_msg("No viewer given"))?;
106
107                let config = rt
108                    .config()
109                    .ok_or_else(|| err_msg("No configuration, cannot continue"))?;
110
111                let query = format!("view.viewers.{}", viewer);
112
113                let viewer_template = config
114                    .read_string(&query)?
115                    .ok_or_else(|| format_err!("Cannot find '{}' in config", query))?;
116
117                let mut handlebars = Handlebars::new();
118                handlebars.register_escape_fn(::handlebars::no_escape);
119
120                handlebars.register_template_string("template", viewer_template)?;
121
122                let mut data = BTreeMap::new();
123
124                let file_paths = files
125                    .iter()
126                    .map(|&(_, ref path)| path.clone())
127                    .collect::<Vec<String>>()
128                    .join(" ");
129
130                data.insert("entries", file_paths);
131
132                let call = handlebars .render("template", &data)?;
133                let mut elems = call.split_whitespace();
134                let command_string = elems.next().ok_or_else(|| err_msg("No command"))?;
135                let mut cmd = Command::new(command_string);
136
137                for arg in elems {
138                    cmd.arg(arg);
139                }
140
141                cmd
142            };
143
144            debug!("Calling: {:?}", command);
145
146            if !command
147                .status()?
148                .success()
149            {
150                return Err(err_msg("Failed to execute command"))
151            }
152
153            drop(files);
154            Ok(())
155        } else {
156            let out         = rt.stdout();
157            let mut outlock = out.lock();
158
159            let basesep = if rt.cli().occurrences_of("seperator") != 0 { // checker for default value
160                rt.cli().value_of("seperator").map(String::from)
161            } else {
162                None
163            };
164
165            let mut sep_width = 80; // base width, automatically overridden by wrap width
166
167            // Helper to build the seperator with a base string `sep` and a `width`
168            let build_seperator = |sep: String, width: usize| -> String {
169                sep.repeat(width / sep.len())
170            };
171
172            if rt.cli().is_present("compile-md") {
173                let viewer    = MarkdownViewer::new(&rt);
174                let seperator = basesep.map(|s| build_seperator(s, sep_width));
175
176                let mut i = 0; // poor mans enumerate()
177
178                entries.and_then_ok(|entry| {
179                    if i != 0 {
180                        if let Some(s) = seperator.as_ref() {
181                            writeln!(outlock, "{}", s)?;
182                        }
183                    }
184
185                    viewer.view_entry(&entry, &mut outlock)?;
186
187                    i += 1;
188                    rt.report_touched(entry.get_location())
189                })
190                .collect()
191            } else {
192                let mut viewer = StdoutViewer::new(view_header, !hide_content);
193
194                if rt.cli().occurrences_of("autowrap") != 0 {
195                    let width = rt.cli().value_of("autowrap").unwrap(); // ensured by clap
196                    let width = usize::from_str(width).map_err(|_| {
197                        format_err!("Failed to parse argument to number: autowrap = {:?}",
198                               rt.cli().value_of("autowrap").map(String::from))
199                    })?;
200
201                    // Copying this value over, so that the seperator has the right len as well
202                    sep_width = width;
203
204                    viewer.wrap_at(width);
205                }
206
207                let seperator = basesep.map(|s| build_seperator(s, sep_width));
208                let mut i = 0; // poor mans enumerate()
209                entries.and_then_ok(|entry| {
210                    if i != 0 {
211                        if let Some(s) = seperator.as_ref() {
212                            writeln!(outlock, "{}", s)?;
213                        }
214                    }
215
216                    viewer.view_entry(&entry, &mut outlock)?;
217
218                    i += 1;
219                    rt.report_touched(entry.get_location())
220                })
221                .collect()
222            }
223        }
224    }
225
226    fn build_cli<'a>(app: App<'a, 'a>) -> App<'a, 'a> {
227        ui::build_ui(app)
228    }
229
230    fn name() -> &'static str {
231        env!("CARGO_PKG_NAME")
232    }
233
234    fn description() -> &'static str {
235        "View entries (readonly)"
236    }
237
238    fn version() -> &'static str {
239        env!("CARGO_PKG_VERSION")
240    }
241}
242
243fn create_tempfile_for<'a>(entry: &FileLockEntry<'a>, view_header: bool, hide_content: bool)
244    -> Result<(tempfile::NamedTempFile, String)>
245{
246    let mut tmpfile = tempfile::NamedTempFile::new()?;
247
248    if view_header {
249        let hdr = toml::ser::to_string_pretty(entry.get_header())?;
250        let _ = tmpfile.write(format!("---\n{}---\n", hdr).as_bytes())?;
251    }
252
253    if !hide_content {
254        let _ = tmpfile.write(entry.get_content().as_bytes())?;
255    }
256
257    let file_path = tmpfile
258        .path()
259        .to_str()
260        .map(String::from)
261        .ok_or_else(|| err_msg("Cannot build path"))?;
262
263    Ok((tmpfile, file_path))
264}
265