Skip to main content

blaze_keys/
shell.rs

1use crate::{SHELL, Shell, is_nushell, yml::LeaderKeys};
2use anyhow::Result;
3use log::debug;
4
5pub mod nu_hook;
6pub mod zsh_hook;
7
8pub fn print_leader_state(leaders: &Option<&Vec<LeaderKeys>>) {
9    println!("{}", leaders_to_state(leaders));
10}
11
12pub fn leaders_to_state(leaders: &Option<&Vec<LeaderKeys>>) -> String {
13    leaders.map_or_else(
14        || "none".to_string(),
15        |l| {
16            let mut out = vec![];
17
18            for leader in l {
19                out.push(format!(
20                    "{}_e{}_a{}",
21                    leader.sanitized_name(),
22                    leader.exec_mode,
23                    leader.abbr_mode,
24                ));
25            }
26
27            out.sort();
28            out.join("|")
29        },
30    )
31}
32
33/// Checks if the leader key state from the env is up to date. Returs an error if not.
34pub fn check_leaders(leaders: &Option<&Vec<LeaderKeys>>) -> Result<()> {
35    let var = std::env::var("BLZ_LEADER_STATE");
36    debug!("Check leader keys: {leaders:?}");
37    debug!("BLZ_LEADER_STATE = {var:?}");
38
39    let shell = *SHELL.lock().unwrap();
40
41    let (which, _or) = match shell {
42        Shell::Zsh => (".zshrc", ", or run 'source ~/.zshrc'"),
43        Shell::Nu => ("nu config", ""),
44    };
45
46    match var {
47        Ok(it) => {
48            if it != leaders_to_state(leaders) {
49                // nushell doesn't make it so easy to refresh the environment, so we'll allow an
50                // override to quiet this message.
51                if is_nushell() && std::env::var("BLZ_STFU").is_ok_and(|it| it != "false") {
52                    return Ok(());
53                }
54
55                anyhow::bail!(match shell {
56                    Shell::Zsh =>
57                        "The '.zshrc' needs to be sourced since the leader keys have changed since BLZ was last initialised. \nPlease run 'source ~/.zshrc'.",
58                    Shell::Nu =>
59                        "The nu session needs to be updated since the BLZ leader keys have changed. This requires opening a new shell with a new environment; sourcing the config and 'exec nu' won't work, but you can open a new terminal tab. \nTip: Use '$env.BLZ_STFU = true' in the current session to quiet this message.",
60                })
61            } else {
62                Ok(())
63            }
64        }
65        Err(_) => {
66            anyhow::bail!(
67                "The 'BLZ_LEADER_STATE' should have been set in the {which}. Please open a new shell{_or}."
68            )
69        }
70    }
71}