histdb-rs 2.0.1

Better history management for zsh. Based on ideas from [https://github.com/larkery/zsh-histdb](https://github.com/larkery/zsh-histdb).
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
use crate::{
    config,
    run,
    run::{
        Display,
        TableDisplay,
    },
    store::Filter,
};
use directories::ProjectDirs;
use log::error;
use regex::Regex;
use std::path::PathBuf;
use structopt::{
    clap::AppSettings::{
        ColoredHelp,
        GlobalVersion,
        NextLineHelp,
        VersionlessSubcommands,
    },
    StructOpt,
};
use thiserror::Error;

macro_rules! into_str {
    ($x:expr) => {{
        structopt::lazy_static::lazy_static! {
            static ref DATA: String = $x.to_string();
        }
        DATA.as_str()
    }};
}

#[derive(Error, Debug)]
pub enum Error {
    #[error("can not get base directories")]
    BaseDirectory,

    #[error("can not get project dirs")]
    ProjectDirs,
}

fn get_default_or_fail<T>(func: fn() -> Result<T, Error>) -> T {
    match func() {
        Ok(s) => s,
        Err(e) => {
            error!("{}", e);
            std::process::exit(1);
        }
    }
}

fn project_dir() -> Result<ProjectDirs, Error> {
    ProjectDirs::from("com", "histdb-rs", "histdb-rs").ok_or(Error::ProjectDirs)
}

fn default_data_dir() -> Result<String, Error> {
    let project_dir = project_dir()?;
    let data_dir = project_dir.data_dir();

    Ok(data_dir.to_string_lossy().to_string())
}

fn default_cache_path() -> Result<String, Error> {
    let project_dir = project_dir()?;
    let cache_path = project_dir.cache_dir().join("server");

    Ok(cache_path.to_string_lossy().to_string())
}

fn default_histdb_sqlite_path() -> Result<String, Error> {
    let base_dirs = directories::BaseDirs::new().ok_or(Error::BaseDirectory)?;

    let home = base_dirs.home_dir();
    let file_path = home.join(".histdb").join("zsh-history.db");

    Ok(file_path.to_string_lossy().to_string())
}

fn default_zsh_histfile_path() -> Result<String, Error> {
    let base_dirs = directories::BaseDirs::new().ok_or(Error::BaseDirectory)?;

    let home = base_dirs.home_dir();
    let file_path = home.join(".histfile");

    Ok(file_path.to_string_lossy().to_string())
}

fn default_socket_path() -> Result<String, Error> {
    let project_dir = project_dir();

    let fallback_path = PathBuf::from("/tmp/histdb-rs/");

    let socket_path = project_dir?
        .runtime_dir()
        .unwrap_or(&fallback_path)
        .join("server_socket");

    Ok(socket_path.to_string_lossy().to_string())
}

fn default_config_path() -> Result<String, Error> {
    let project_dir = project_dir();

    let socket_path = project_dir?.config_dir().join("config.toml");

    Ok(socket_path.to_string_lossy().to_string())
}

#[derive(StructOpt, Debug)]
struct ZSHAddHistory {
    #[structopt(flatten)]
    socket_path: Socket,

    /// Command to add to history
    #[structopt(index = 1)]
    command: String,
}

#[derive(StructOpt, Debug)]
struct Server {
    /// Path to the cachefile used to store entries between restarts
    #[structopt(short, long, default_value = into_str!(get_default_or_fail(default_cache_path)))]
    cache_path: PathBuf,

    #[structopt(flatten)]
    data_dir: DataDir,

    #[structopt(flatten)]
    socket_path: Socket,
}

#[derive(StructOpt, Debug)]
enum Import {
    #[cfg(feature = "histdb-import")]
    /// Import entries from existing histdb sqlite file
    Histdb(ImportHistdb),

    /// Import entries from existing zsh histfile
    Histfile(ImportHistfile),
}

#[derive(StructOpt, Debug)]
struct ImportHistdb {
    #[structopt(flatten)]
    data_dir: DataDir,

    /// Path to the existing histdb sqlite file
    #[structopt(short, long, default_value = into_str!(get_default_or_fail(default_histdb_sqlite_path)))]
    import_file: PathBuf,
}

#[derive(StructOpt, Debug)]
struct ImportHistfile {
    #[structopt(flatten)]
    data_dir: DataDir,

    /// Path to the existing zsh histfile file
    #[structopt(short, long, default_value = into_str!(get_default_or_fail(default_zsh_histfile_path)))]
    import_file: PathBuf,
}

#[derive(StructOpt, Debug)]
struct Socket {
    /// Path to the socket for communication with the server
    #[structopt(short, long, env = "HISTDBRS_SOCKET_PATH", default_value = into_str!(get_default_or_fail(default_socket_path)))]
    socket_path: PathBuf,
}

#[derive(StructOpt, Debug)]
struct Config {
    /// Path to the socket for communication with the server
    #[structopt(long, env = "HISTDBRS_CONFIG_PATH", default_value = into_str!(get_default_or_fail(default_config_path)))]
    config_path: PathBuf,
}

#[derive(StructOpt, Debug)]
struct DataDir {
    /// Path to folder in which to store the history files
    #[structopt(
        short,
        long,
        default_value = into_str!(get_default_or_fail(default_data_dir))
    )]
    data_dir: PathBuf,
}

#[allow(clippy::struct_excessive_bools)]
#[derive(StructOpt, Debug)]
struct DefaultArgs {
    #[structopt(flatten)]
    data_dir: DataDir,

    /// How many entries to print
    #[structopt(short, long, default_value = "25")]
    entries_count: usize,

    /// Only print entries beginning with the given command
    #[structopt(short, long)]
    command: Option<String>,

    /// Only print entries containing the given regex
    #[structopt(short = "t", long = "text")]
    command_text: Option<Regex>,

    /// Only print entries that have been executed in the current directory
    #[structopt(short, long = "in", conflicts_with = "folder")]
    in_current: bool,

    /// Only print entries that have been executed in the given directory
    #[structopt(short, long, conflicts_with = "in_current")]
    folder: Option<PathBuf>,

    /// Exclude subdirectories when filtering by folder
    #[structopt(long)]
    no_subdirs: bool,

    /// Filter by given hostname
    #[structopt(long, conflicts_with = "all_hosts")]
    hostname: Option<String>,

    /// Filter by given session
    #[structopt(long)]
    session: Option<Regex>,

    /// Print all hosts
    #[structopt(long, conflicts_with = "hostname")]
    all_hosts: bool,

    /// Disable fancy formatting
    #[structopt(long)]
    disable_formatting: bool,

    /// Print host column
    #[structopt(long)]
    show_host: bool,

    /// Print returncode of command
    #[structopt(long)]
    show_status: bool,

    /// Show how long the command ran
    #[structopt(long)]
    show_duration: bool,

    /// Show directory in which the command was run
    #[structopt(long)]
    show_pwd: bool,

    /// Show session id for command
    #[structopt(long)]
    show_session: bool,

    /// Disable printing of header
    #[structopt(long)]
    hide_header: bool,

    /// Filter out failed commands (return code not 0)
    #[structopt(long)]
    filter_failed: bool,

    /// Find commands with the given return code
    #[structopt(long)]
    find_status: Option<u16>,

    #[structopt(flatten)]
    config: Config,
}

#[derive(StructOpt, Debug)]
enum SubCommand {
    /// Add new command for current session
    #[structopt(name = "zshaddhistory")]
    ZSHAddHistory(ZSHAddHistory),

    /// Start the server
    #[structopt(name = "server")]
    Server(Server),

    /// Stop the server
    #[structopt(name = "stop")]
    Stop(Socket),

    /// Disable history recording for current session
    #[structopt(name = "disable")]
    Disable(Socket),

    /// Enable history recording for current session
    #[structopt(name = "enable")]
    Enable(Socket),

    /// Finish command for current session
    #[structopt(name = "precmd")]
    PreCmd(Socket),

    /// Get new session id
    #[structopt(name = "session_id")]
    SessionID,

    /// Import entries from existing histdb sqlite or zsh histfile
    #[structopt(name = "import")]
    Import(Import),

    /// Print out shell functions needed by histdb and set current session id
    #[structopt(name = "init")]
    Init,

    /// Run benchmark against server
    #[structopt(name = "bench")]
    Bench(Socket),
}

#[derive(StructOpt, Debug)]
#[structopt(
    global_settings = &[ColoredHelp, VersionlessSubcommands, NextLineHelp, GlobalVersion]
)]
pub struct Opt {
    #[structopt(flatten)]
    default_args: DefaultArgs,

    #[structopt(subcommand)]
    sub_command: Option<SubCommand>,
}

impl Opt {
    pub fn run(self) -> Result<(), run::Error> {
        let sub_command = self.sub_command;
        let in_current = self.default_args.in_current;
        let folder = self.default_args.folder;
        let all_hosts = self.default_args.all_hosts;
        let hostname = self.default_args.hostname;
        let data_dir = self.default_args.data_dir.data_dir;
        let entries_count = self.default_args.entries_count;
        let command = self.default_args.command;
        let session_filter = self.default_args.session;
        let no_subdirs = self.default_args.no_subdirs;
        let command_text = self.default_args.command_text;
        let filter_failed = self.default_args.filter_failed;
        let find_status = self.default_args.find_status;
        let config = config::Config::open(self.default_args.config.config_path)
            .map_err(run::Error::ReadConfig)?;

        let format = !self.default_args.disable_formatting;
        let duration = Display::should_show(self.default_args.show_duration);
        let header = Display::should_hide(self.default_args.hide_header);
        let host = Display::should_show(self.default_args.show_host);
        let pwd = Display::should_show(self.default_args.show_pwd);
        let session = Display::should_show(self.default_args.show_session);
        let status = Display::should_show(self.default_args.show_status);

        if std::env::var_os("RUST_LOG").is_none() {
            std::env::set_var("RUST_LOG", config.log_level.as_str());
        }
        pretty_env_logger::init();

        sub_command.map_or_else(
            || {
                let filter = Filter::default()
                    .directory(folder, in_current, no_subdirs)?
                    .hostname(hostname, all_hosts)?
                    .count(entries_count)
                    .command(command, command_text)
                    .session(session_filter)
                    .filter_failed(filter_failed)
                    .find_status(find_status);

                let display = TableDisplay {
                    format,

                    duration,
                    header,
                    host,
                    pwd,
                    session,
                    status,
                };

                run::default(&filter, &display, data_dir)
            },
            |sub_command| match sub_command {
                SubCommand::ZSHAddHistory(o) => {
                    run::zsh_add_history(&config, o.command, o.socket_path.socket_path)
                }
                SubCommand::Server(o) => {
                    run::server(o.cache_path, o.socket_path.socket_path, o.data_dir.data_dir)
                }
                SubCommand::Stop(o) => run::stop(o.socket_path),
                SubCommand::Disable(o) => run::disable(o.socket_path),
                SubCommand::Enable(o) => run::enable(o.socket_path),
                SubCommand::PreCmd(o) => run::precmd(o.socket_path),
                SubCommand::SessionID => {
                    run::session_id();
                    Ok(())
                }
                SubCommand::Import(s) => match s {
                    #[cfg(feature = "histdb-import")]
                    Import::Histdb(o) => run::import::histdb(&o.import_file, o.data_dir.data_dir)
                        .map_err(run::Error::Import),
                    Import::Histfile(o) => {
                        run::import::histfile(&o.import_file, o.data_dir.data_dir)
                            .map_err(run::Error::Import)
                    }
                },
                SubCommand::Init => {
                    run::init();
                    Ok(())
                }
                SubCommand::Bench(s) => run::bench(s.socket_path),
            },
        )
    }
}