refactor: initialization

This commit is contained in:
iff 2024-12-07 17:50:38 +01:00
parent b6b4afc226
commit 89be82307b
3 changed files with 75 additions and 62 deletions

View file

@ -1,22 +1,20 @@
use crate::shell::initialization; use crate::shell::{initialization, Init};
use colored::Colorize; use colored::Colorize;
pub enum Status { pub enum Status {
Continue, Continue,
Exit, // version, help, etc. Exit, // version, help, etc.
Error, Error,
} }
// returns true if should exit
pub fn handle_args() -> Status { pub fn handle_args() -> Status {
use Status::*; use Status::*;
let args = std::env::args().collect::<Vec<String>>(); let args = std::env::args().collect::<Vec<String>>();
if args.len() <= 1 { if args.len() <= 1 {
return Continue; return Continue;
} }
let mut auto_aliasing = String::new(); let mut init = Init::new();
let mut shell = String::new();
let mut cnf = true;
let mut index = 1; let mut index = 1;
while index < args.len() { while index < args.len() {
match args[index].as_str() { match args[index].as_str() {
@ -31,35 +29,36 @@ pub fn handle_args() -> Status {
"-a" | "--alias" => { "-a" | "--alias" => {
if args.len() > index + 1 { if args.len() > index + 1 {
if args[index + 1].starts_with('-') { if args[index + 1].starts_with('-') {
auto_aliasing = String::from("f"); init.alias = String::from("f");
} else { } else {
auto_aliasing = args[index + 1].clone(); init.alias = args[index + 1].clone();
index += 1; index += 1;
} }
} else { } else {
auto_aliasing = String::from("f"); init.alias = String::from("f");
} }
init.auto_alias = true;
index += 1; index += 1;
} }
"--noncf" => { "--noncf" => {
cnf = false; init.cnf = false;
index += 1 index += 1
} }
_ => { _ => {
shell = args[index].clone(); init.shell = args[index].clone();
index += 1 index += 1
} }
} }
} }
if shell.is_empty() { if init.shell.is_empty() {
eprintln!("{}", t!("no-shell")); eprintln!("{}", t!("no-shell"));
return Error; return Error;
} }
let binary_path = &args[0]; init.binary_path = args[0].clone();
initialization(&shell, binary_path, &auto_aliasing, cnf); initialization(&mut init);
Exit Exit
} }

View file

@ -60,10 +60,10 @@ fn main() -> Result<(), std::io::Error> {
}; };
data.expand_command(); data.expand_command();
use shell::Mode; use shell::Mode::*;
match data.mode { match data.mode {
Mode::Suggestion => modes::suggestion(&mut data), Suggestion => modes::suggestion(&mut data),
Mode::Cnf => modes::cnf(&mut data), Cnf => modes::cnf(&mut data),
} }
Ok(()) Ok(())

View file

@ -15,6 +15,25 @@ pub enum Mode {
Suggestion, Suggestion,
Cnf, Cnf,
} }
pub struct Init {
pub shell: String,
pub binary_path: String,
pub alias: String,
pub auto_alias: bool,
pub cnf: bool,
}
impl Init {
pub fn new() -> Init {
Init {
shell: String::from(""),
binary_path: String::from(""),
alias: String::from("f"),
auto_alias: false,
cnf: true,
}
}
}
pub struct Data { pub struct Data {
pub shell: String, pub shell: String,
@ -29,13 +48,6 @@ pub struct Data {
pub mode: Mode, pub mode: Mode,
} }
pub struct Init {
pub shell: String,
pub binary_path: String,
pub auto_alias: String,
pub cnf: bool,
}
impl Data { impl Data {
pub fn init() -> Data { pub fn init() -> Data {
let shell = get_shell(); let shell = get_shell();
@ -307,44 +319,46 @@ pub fn expand_alias_multiline(map: &HashMap<String, String>, command: &str) -> O
} }
} }
pub fn initialization(shell: &str, binary_path: &str, auto_alias: &str, cnf: bool) { pub fn initialization(init: &mut Init) {
let last_command; let last_command;
let alias; let shell_alias;
let alias = &init.alias;
let auto_alias = init.auto_alias;
let cnf = init.cnf;
let binary_path = &init.binary_path;
match shell { match init.shell.as_str() {
"bash" => { "bash" => {
last_command = "$(history 2)"; last_command = "$(history 2)";
alias = "$(alias)" shell_alias = "$(alias)"
} }
"zsh" => { "zsh" => {
last_command = "$(fc -ln -1)"; last_command = "$(fc -ln -1)";
alias = "$(alias)" shell_alias = "$(alias)"
} }
"fish" => { "fish" => {
last_command = "$(history | head -n 1)"; last_command = "$(history | head -n 1)";
alias = "$(alias)"; shell_alias = "$(alias)";
} }
"nu" | "nush" | "nushell" => { "nu" | "nush" | "nushell" => {
last_command = "(history | last).command"; last_command = "(history | last).command";
alias = "\"\""; shell_alias = "\"\"";
init.shell = "nu".to_string();
} }
"pwsh" | "powershell" => { "pwsh" | "powershell" => {
last_command = "Get-History | Select-Object -Last 1 | ForEach-Object {$_.CommandLine}"; last_command = "Get-History | Select-Object -Last 1 | ForEach-Object {$_.CommandLine}";
alias = ";"; shell_alias = ";";
init.shell = "pwsh".to_string();
} }
_ => { _ => {
println!("Unknown shell: {}", shell); println!("Unknown shell: {}", init.shell);
return; return;
} }
} }
if shell == "nu" || shell == "nush" || shell == "nushell" { let shell = &init.shell;
let pr_alias = if auto_alias.is_empty() {
"f"
} else {
auto_alias
};
if init.shell == "nu" {
let init = format!( let init = format!(
r#" r#"
def --env {} [] {{ def --env {} [] {{
@ -352,20 +366,20 @@ def --env {} [] {{
cd $dir cd $dir
}} }}
"#, "#,
pr_alias, last_command, binary_path init.alias, last_command, init.binary_path
); );
println!("{}", init); println!("{}", init);
return; return;
} }
let mut init = match shell { let mut initialize = match shell.as_str() {
"bash" | "zsh" | "fish" => format!( "bash" | "zsh" | "fish" => format!(
"\ "\
eval $(_PR_LAST_COMMAND=\"{}\" \ eval $(_PR_LAST_COMMAND=\"{}\" \
_PR_ALIAS=\"{}\" \ _PR_ALIAS=\"{}\" \
_PR_SHELL=\"{}\" \ _PR_SHELL=\"{}\" \
\"{}\")", \"{}\")",
last_command, alias, shell, binary_path last_command, shell_alias, shell, binary_path
), ),
"pwsh" | "powershell" => format!( "pwsh" | "powershell" => format!(
r#"& {{ r#"& {{
@ -397,30 +411,30 @@ def --env {} [] {{
return; return;
} }
}; };
if auto_alias.is_empty() { if !auto_alias {
println!("{}", init); println!("{}", initialize);
return; return;
} }
match shell { match shell.as_str() {
"bash" | "zsh" => { "bash" | "zsh" => {
init = format!(r#"alias {}='{}'"#, auto_alias, init); initialize = format!(r#"alias {}='{}'"#, alias, initialize);
} }
"fish" => { "fish" => {
init = format!( initialize = format!(
r#" r#"
function {} -d "Terminal command correction" function {} -d "Terminal command correction"
eval $({}) eval $({})
end end
"#, "#,
auto_alias, init alias, initialize
); );
} }
"pwsh" | "powershell" => { "pwsh" => {
init = format!( initialize = format!(
"function {} {{\n{}", "function {} {{\n{}",
auto_alias, alias,
init.split_once("\n").unwrap().1, initialize.split_once("\n").unwrap().1,
); );
} }
_ => { _ => {
@ -430,9 +444,9 @@ end
} }
if cnf { if cnf {
match shell { match shell.as_str() {
"bash" => { "bash" => {
init = format!( initialize = format!(
r#" r#"
command_not_found_handle() {{ command_not_found_handle() {{
eval $(_PR_LAST_COMMAND="_ $@" _PR_SHELL="{}" _PR_MODE="cnf" "{}") eval $(_PR_LAST_COMMAND="_ $@" _PR_SHELL="{}" _PR_MODE="cnf" "{}")
@ -440,11 +454,11 @@ command_not_found_handle() {{
{} {}
"#, "#,
shell, binary_path, init shell, binary_path, initialize
); );
} }
"zsh" => { "zsh" => {
init = format!( initialize = format!(
r#" r#"
command_not_found_handler() {{ command_not_found_handler() {{
eval $(_PR_LAST_COMMAND="$@" _PR_SHELL="{}" _PR_MODE="cnf" "{}") eval $(_PR_LAST_COMMAND="$@" _PR_SHELL="{}" _PR_MODE="cnf" "{}")
@ -452,11 +466,11 @@ command_not_found_handler() {{
{} {}
"#, "#,
shell, binary_path, init shell, binary_path, initialize
); );
} }
"fish" => { "fish" => {
init = format!( initialize = format!(
r#" r#"
function fish_command_not_found --on-event fish_command_not_found function fish_command_not_found --on-event fish_command_not_found
eval $(_PR_LAST_COMMAND="$argv" _PR_SHELL="{}" _PR_MODE="cnf" "{}") eval $(_PR_LAST_COMMAND="$argv" _PR_SHELL="{}" _PR_MODE="cnf" "{}")
@ -464,11 +478,11 @@ end
{} {}
"#, "#,
shell, binary_path, init shell, binary_path, initialize
); );
} }
"pwsh" | "powershell" => { "pwsh" => {
init = format!( initialize = format!(
r#"{} r#"{}
$ExecutionContext.InvokeCommand.CommandNotFoundAction = $ExecutionContext.InvokeCommand.CommandNotFoundAction =
{{ {{
@ -488,7 +502,7 @@ $ExecutionContext.InvokeCommand.CommandNotFoundAction =
$eventArgs.StopSearch = $True; $eventArgs.StopSearch = $True;
}} }}
"#, "#,
init, auto_alias initialize, alias
) )
} }
_ => { _ => {
@ -498,7 +512,7 @@ $ExecutionContext.InvokeCommand.CommandNotFoundAction =
} }
} }
println!("{}", init); println!("{}", initialize);
} }
pub fn get_shell() -> String { pub fn get_shell() -> String {