summaryrefslogtreecommitdiffstats
path: root/atuin/src/command/client/doctor.rs
blob: 6602c04f379611a603c6cccab1a065a4ff1b913a (plain)
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
use std::process::Command;
use std::{collections::HashMap, path::PathBuf};

use atuin_client::settings::Settings;
use colored::Colorize;
use eyre::Result;
use serde::{Deserialize, Serialize};

use sysinfo::{get_current_pid, Disks, System};

#[derive(Debug, Serialize, Deserialize)]
struct ShellInfo {
    pub name: String,

    // Detect some shell plugins that the user has installed.
    // I'm just going to start with preexec/blesh
    pub plugins: Vec<String>,
}

impl ShellInfo {
    // HACK ALERT!
    // Many of the env vars we need to detect are not exported :(
    // So, we're going to run `env` in a subshell and parse the output
    // There's a chance this won't work, so it should not be fatal.
    //
    // Every shell we support handles `shell -c 'command'`
    fn env_exists(shell: &str, var: &str) -> bool {
        let mut cmd = Command::new(shell)
            .args(["-ic", format!("echo ${var}").as_str()])
            .output()
            .map_or(String::new(), |v| {
                let out = v.stdout;
                String::from_utf8(out).unwrap_or_default()
            });

        cmd.retain(|c| !c.is_whitespace());

        !cmd.is_empty()
    }

    pub fn plugins(shell: &str) -> Vec<String> {
        // consider a different detection approach if there are plugins
        // that don't set env vars

        let map = HashMap::from([
            ("ATUIN_SESSION", "atuin"),
            ("BLE_ATTACHED", "blesh"),
            ("bash_preexec_imported", "bash-preexec"),
        ]);

        map.into_iter()
            .filter_map(|(env, plugin)| {
                if ShellInfo::env_exists(shell, env) {
                    return Some(plugin.to_string());
                }

                None
            })
            .collect()
    }

    pub fn new() -> Self {
        let sys = System::new_all();

        let process = sys
            .process(get_current_pid().expect("Failed to get current PID"))
            .expect("Process with current pid does not exist");

        let parent = sys
            .process(process.parent().expect("Atuin running with no parent!"))
            .expect("Process with parent pid does not exist");

        let shell = parent.name().trim().to_lowercase();
        let shell = shell.strip_prefix('-').unwrap_or(&shell);
        let name = shell.to_string();

        let plugins = ShellInfo::plugins(name.as_str());

        Self { name, plugins }
    }
}

#[derive(Debug, Serialize, Deserialize)]
struct DiskInfo {
    pub name: String,
    pub filesystem: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct SystemInfo {
    pub os: String,

    pub arch: String,

    pub version: String,
    pub disks: Vec<DiskInfo>,
}

impl SystemInfo {
    pub fn new() -> Self {
        let disks = Disks::new_with_refreshed_list();
        let disks = disks
            .list()
            .iter()
            .map(|d| DiskInfo {
                name: d.name().to_os_string().into_string().unwrap(),
                filesystem: d.file_system().to_os_string().into_string().unwrap(),
            })
            .collect();

        Self {
            os: System::name().unwrap_or_else(|| "unknown".to_string()),
            arch: System::cpu_arch().unwrap_or_else(|| "unknown".to_string()),
            version: System::os_version().unwrap_or_else(|| "unknown".to_string()),
            disks,
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
struct SyncInfo {
    /// Whether the main Atuin sync server is in use
    /// I'm just calling it Atuin Cloud for lack of a better name atm
    pub cloud: bool,
    pub records: bool,
    pub auto_sync: bool,

    pub last_sync: String,
}

impl SyncInfo {
    pub fn new(settings: &Settings) -> Self {
        Self {
            cloud: settings.sync_address == "https://api.atuin.sh",
            auto_sync: settings.auto_sync,
            records: settings.sync.records,
            last_sync: Settings::last_sync().map_or("no last sync".to_string(), |v| v.to_string()),
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
struct AtuinInfo {
    pub version: String,

    /// Whether the main Atuin sync server is in use
    /// I'm just calling it Atuin Cloud for lack of a better name atm
    pub sync: Option<SyncInfo>,
}

impl AtuinInfo {
    pub fn new(settings: &Settings) -> Self {
        let session_path = settings.session_path.as_str();
        let logged_in = PathBuf::from(session_path).exists();

        let sync = if logged_in {
            Some(SyncInfo::new(settings))
        } else {
            None
        };

        Self {
            version: crate::VERSION.to_string(),
            sync,
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
struct DoctorDump {
    pub atuin: AtuinInfo,
    pub shell: ShellInfo,
    pub system: SystemInfo,
}

impl DoctorDump {
    pub fn new(settings: &Settings) -> Self {
        Self {
            atuin: AtuinInfo::new(settings),
            shell: ShellInfo::new(),
            system: SystemInfo::new(),
        }
    }
}

pub fn run(settings: &Settings) -> Result<()> {
    println!("{}", "Atuin Doctor".bold());
    println!("Checking for diagnostics");
    println!("Please include the output below with any bug reports or issues\n");

    let dump = DoctorDump::new(settings);

    let dump = serde_yaml::to_string(&dump)?;
    println!("{dump}");

    Ok(())
}