Skip to content

Commit

Permalink
feat: ✨ non working nushell PR
Browse files Browse the repository at this point in the history
Mostly recreating the PR mentionned in:
LGUG2Z#25
  • Loading branch information
melMass committed Feb 1, 2024
1 parent e7b0b1f commit f8f5493
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 34 deletions.
77 changes: 50 additions & 27 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ mod whkdrc;
lazy_static! {
static ref WHKDRC: Whkdrc = {
// config file defaults to `~/.config/whkdrc`, or `<WHKD_CONFIG_HOME>/whkdrc`
let mut home = std::env::var("WHKD_CONFIG_HOME").map_or_else(
let mut home = std::env::var("WHKD_CONFIG_HOME").map_or_else(
|_| dirs::home_dir().expect("no home directory found").join(".config"),
|home_path| {
let home = PathBuf::from(&home_path);
Expand All @@ -36,13 +36,15 @@ lazy_static! {
home
} else {
panic!(
"$Env:WHKD_CONFIG_HOME is set to '{home_path}', which is not a valid directory",
"$Env:WHKD_CONFIG_HOME is set to '{home_path}', which is not a valid directory"
);
}
},
}
);
home.push("whkdrc");
Whkdrc::load(&home).unwrap_or_else(|_| panic!("could not load whkdrc from {home:?}"))
Whkdrc::load(&home).unwrap_or_else(|e|
panic!("could not load whkdrc from {home:?} ({e:?})")
)
};
static ref SESSION_STDIN: Mutex<Option<ChildStdin>> = Mutex::new(None);
}
Expand All @@ -59,18 +61,22 @@ impl HkmData {
pub fn register(&self, hkm: &mut HotkeyManager<()>, shell: Shell) -> Result<()> {
let cmd = self.command.clone();

if let Err(error) = hkm.register(self.vkey, self.mod_keys.as_slice(), move || {
if let Some(session_stdin) = SESSION_STDIN.lock().as_mut() {
if matches!(shell, Shell::Pwsh | Shell::Powershell) {
println!("{cmd}");
}
if
let Err(error) = hkm.register(self.vkey, self.mod_keys.as_slice(), move || {
if let Some(session_stdin) = SESSION_STDIN.lock().as_mut() {
if matches!(shell, Shell::Pwsh | Shell::Powershell) {
println!("{cmd}");
}

writeln!(session_stdin, "{cmd}").expect("failed to execute command");
}
}) {
writeln!(session_stdin, "{cmd}").expect("failed to execute command");
}
})
{
eprintln!(
"Unable to bind '{:?} + {}' to '{}' (error: {error}), ignoring this binding and continuing...",
self.mod_keys, self.vkey, self.command
self.mod_keys,
self.vkey,
self.command
);
}

Expand Down Expand Up @@ -113,9 +119,10 @@ fn main() -> Result<()> {
let whkdrc = cli.config.map_or_else(
|| WHKDRC.clone(),
|config| {
Whkdrc::load(&config)
.unwrap_or_else(|_| panic!("could not load whkdrc from {config:?}"))
},
Whkdrc::load(&config).unwrap_or_else(|_|
panic!("could not load whkdrc from {config:?}")
)
}
);

let shell_binary = whkdrc.shell.to_string();
Expand All @@ -127,8 +134,7 @@ fn main() -> Result<()> {
.args(["-Command", "-"])
.spawn()?;

let mut stdin = process
.stdin
let mut stdin = process.stdin
.take()
.ok_or_else(|| eyre!("could not take stdin from powershell session"))?;

Expand All @@ -143,13 +149,27 @@ fn main() -> Result<()> {
.args(["-"])
.spawn()?;

let mut stdin = process
.stdin
let mut stdin = process.stdin
.take()
.ok_or_else(|| eyre!("could not take stdin from cmd session"))?;

writeln!(stdin, "prompt $S")?;

let mut session_stdin = SESSION_STDIN.lock();
*session_stdin = Option::from(stdin);
}
Shell::Nushell => {
let mut process = Command::new(&shell_binary)
.stdin(Stdio::piped())
.args(["--stdin", "-n"])
.spawn()?;

let stdin = process.stdin
.take()
.ok_or_else(|| eyre!("could not take stdin from nushell session"))?;

// writeln!(stdin, "$wshell = New-Object -ComObject wscript.shell")?;

let mut session_stdin = SESSION_STDIN.lock();
*session_stdin = Option::from(stdin);
}
Expand All @@ -162,10 +182,7 @@ fn main() -> Result<()> {
for (keys, app_bindings) in &whkdrc.app_bindings {
for binding in app_bindings {
let data = HkmData::try_from(binding)?;
mapped
.entry(keys.join("+"))
.or_insert_with(Vec::new)
.push(data);
mapped.entry(keys.join("+")).or_insert_with(Vec::new).push(data);
}
}

Expand All @@ -182,12 +199,18 @@ fn main() -> Result<()> {
match active_win_pos_rs::get_active_window() {
Ok(window) => {
if window.app_name == *proc {
if matches!(whkdrc.shell, Shell::Pwsh | Shell::Powershell) {
if
matches!(
whkdrc.shell,
Shell::Pwsh | Shell::Nushell | Shell::Powershell
)
{
println!("{cmd}");
}

writeln!(session_stdin, "{cmd}")
.expect("failed to execute command");
writeln!(session_stdin, "{cmd}").expect(
"failed to execute command"
);
}
}
Err(error) => {
Expand Down
16 changes: 9 additions & 7 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub fn parser() -> impl Parser<char, Whkdrc, Error = Simple<char>> {

let shell = just(".shell")
.padded()
.ignore_then(choice((just("pwsh"), just("powershell"), just("cmd"))))
.ignore_then(choice((just("pwsh"), just("nu"), just("powershell"), just("cmd"))))
.repeated()
.exactly(1)
.collect::<String>()
Expand All @@ -37,7 +37,8 @@ pub fn parser() -> impl Parser<char, Whkdrc, Error = Simple<char>> {
.map(|c| c.0)
.collect::<String>();

let process_name = text::ident()
let process_name = text
::ident()
.padded()
.repeated()
.at_least(1)
Expand Down Expand Up @@ -79,7 +80,7 @@ pub fn parser() -> impl Parser<char, Whkdrc, Error = Simple<char>> {
.padded()
.padded_by(comment.repeated())
.repeated()
.at_least(0),
.at_least(0)
)
.then(
binding
Expand All @@ -91,7 +92,7 @@ pub fn parser() -> impl Parser<char, Whkdrc, Error = Simple<char>> {
.padded()
.padded_by(comment.repeated())
.repeated()
.at_least(1),
.at_least(1)
)
.map(|((shell, app_bindings), bindings)| Whkdrc {
shell,
Expand Down Expand Up @@ -127,7 +128,8 @@ alt + h : echo "Hello""#;

#[test]
fn test_parse() {
let src = r#"
let src =
r#"
.shell cmd
# Specify different behaviour depending on the app
Expand Down Expand Up @@ -169,7 +171,7 @@ alt + 1 : komorebic focus-workspace 0 # digits are fine in the hotkeys section
keys: vec![String::from("alt"), String::from("n")],
command: String::from(r#"echo "hello chrome""#),
process_name: Option::from("Google Chrome".to_string()),
},
}
],
)],
bindings: vec![
Expand Down Expand Up @@ -197,7 +199,7 @@ alt + 1 : komorebic focus-workspace 0 # digits are fine in the hotkeys section
keys: vec![String::from("alt"), String::from("1")],
command: String::from("komorebic focus-workspace 0"),
process_name: None,
},
}
],
};

Expand Down
3 changes: 3 additions & 0 deletions src/whkdrc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ pub enum Shell {
Cmd,
Powershell,
Pwsh,
Nushell,
}

#[allow(clippy::fallible_impl_from)]
Expand All @@ -28,6 +29,7 @@ impl From<String> for Shell {
"pwsh" => Self::Pwsh,
"powershell" => Self::Powershell,
"cmd" => Self::Cmd,
"nu" => Self::Nushell,
_ => panic!("unsupported shell"),
}
}
Expand All @@ -39,6 +41,7 @@ impl Display for Shell {
Self::Cmd => write!(f, "cmd"),
Self::Powershell => write!(f, "powershell"),
Self::Pwsh => write!(f, "pwsh"),
Self::Nushell => write!(f, "nu"),
}
}
}
Expand Down

0 comments on commit f8f5493

Please sign in to comment.