aboutsummaryrefslogtreecommitdiffstats
path: root/crates/client/src/command/client.rs
blob: 42e72e213cd5cb43a97eb49c922ff8e43af8abb0 (plain) (blame)
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
use std::fs::{self};
use std::path::{Path, PathBuf};

use clap::Subcommand;
use eyre::{Result, WrapErr};

use tracing_subscriber::filter::EnvFilter;

use crate::atuin_client::settings::Settings;

fn cleanup_old_logs(log_dir: &Path, prefix: &str, retention_days: u64) {
    let cutoff = std::time::SystemTime::now()
        - std::time::Duration::from_secs(retention_days * 24 * 60 * 60);

    let Ok(entries) = fs::read_dir(log_dir) else {
        return;
    };

    for entry in entries.flatten() {
        let path = entry.path();
        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
            continue;
        };

        // Match files like "search.log.2024-02-23" or "daemon.log.2024-02-23"
        if !name.starts_with(prefix) || name == prefix {
            continue;
        }

        if let Ok(metadata) = entry.metadata()
            && let Ok(modified) = metadata.modified()
            && modified < cutoff
        {
            drop(fs::remove_file(&path));
        }
    }
}

mod config;
mod default_config;
mod history;
mod info;
mod stats;
mod store;
mod sync;
mod wrapped;

#[derive(Subcommand, Debug)]
#[command(infer_subcommands = true)]
pub(crate) enum Cmd {
    /// Manipulate shell history
    #[command(subcommand)]
    History(history::Cmd),

    #[command(subcommand)]
    /// Request a sync or view sync status
    Sync(sync::Cmd),

    /// Manage the atuin data store
    #[command(subcommand)]
    Store(store::Cmd),

    /// Information about dotfiles locations and ENV vars
    #[command()]
    Info,

    /// Calculate statistics for your history
    Stats(stats::Cmd),

    #[command()]
    /// Display a recap of your last year's history
    Wrapped { year: Option<i32> },

    /// Print the default atuin configuration (config.toml)
    #[command()]
    DefaultConfig,

    #[command(subcommand)]
    /// Manage your configuration
    Config(config::Cmd),
}

impl Cmd {
    pub(crate) fn run(self) -> Result<()> {
        let mut runtime = tokio::runtime::Builder::new_current_thread();

        let runtime = runtime.enable_all().build().unwrap();

        let res = {
            let settings = Settings::new().wrap_err("could not load client settings")?;

            runtime.block_on(self.run_inner(settings))
        };

        runtime.shutdown_timeout(std::time::Duration::from_millis(50));

        res
    }

    async fn run_inner(self, mut settings: Settings) -> Result<()> {
        // ATUIN_LOG env var overrides config file level settings
        let env_log_set = std::env::var("ATUIN_LOG").is_ok();

        // Base filter from env var (or empty if not set)
        let base_filter =
            EnvFilter::from_env("ATUIN_LOG").add_directive("sqlx_sqlite::regexp=off".parse()?);

        tracing::trace!(command = ?self, "client command");

        // Skip initializing any databases for history
        // This is a pretty hot path, as it runs before and after every single command the user
        // runs
        match self {
            Self::History(history) => return history.run(&settings).await,
            Self::Config(config) => return config.run(&settings).await,
            _ => {}
        }

        match self {
            Self::Stats(stats) => stats.run(&db, &settings).await,
            Self::Wrapped { year } => wrapped::run(year, &db, &settings).await,

            Self::Sync(sync) => sync.run(settings, &db, sqlite_store).await,

            Self::Store(store) => store.run(&settings, &db, sqlite_store).await,

            Self::Info => info::run(&settings),

            Self::DefaultConfig => {
                default_config::run();
                Ok(())
            }

            Self::History(_) | Self::Config(_) => {
                unreachable!()
            }
        }
    }
}