Skip to content

Commit

Permalink
Source ~/.shellrc automatically if it exists (#173)
Browse files Browse the repository at this point in the history
* Source ~/.shellrc automatically if it exists
* Implement --norc option to skip sourcing .shellrc

Fixes #95.
  • Loading branch information
certik authored Sep 30, 2024
1 parent 90d3346 commit d555365
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions crates/shell/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ struct Options {
#[clap(long)]
interact: bool,

/// Do not source ~/.shellrc on startup
#[clap(long)]
norc: bool,

#[clap(short, long)]
debug: bool,
}
Expand All @@ -34,7 +38,7 @@ fn init_state() -> ShellState {
ShellState::new(env_vars, &cwd, commands::get_commands())
}

async fn interactive(state: Option<ShellState>) -> miette::Result<()> {
async fn interactive(state: Option<ShellState>, norc: bool) -> miette::Result<()> {
let config = Config::builder()
.history_ignore_space(true)
.completion_type(CompletionType::List)
Expand All @@ -53,6 +57,8 @@ async fn interactive(state: Option<ShellState>) -> miette::Result<()> {
let mut state = state.unwrap_or_else(init_state);

let home = dirs::home_dir().ok_or(miette::miette!("Couldn't get home directory"))?;

// Load .shell_history
let history_file: PathBuf = [home.as_path(), Path::new(".shell_history")]
.iter()
.collect();
Expand All @@ -62,6 +68,16 @@ async fn interactive(state: Option<ShellState>) -> miette::Result<()> {
.context("Failed to read the command history")?;
}

// Load ~/.shellrc
let shellrc_file: PathBuf = [home.as_path(), Path::new(".shellrc")].iter().collect();
if !norc && Path::new(shellrc_file.as_path()).exists() {
let line = "source '".to_owned() + shellrc_file.to_str().unwrap() + "'";
let prev_exit_code = execute(&line, &mut state)
.await
.context("Failed to source ~/.shellrc")?;
state.set_last_command_exit_code(prev_exit_code);
}

let mut _prev_exit_code = 0;
loop {
// Reset cancellation flag
Expand Down Expand Up @@ -156,10 +172,10 @@ async fn main() -> miette::Result<()> {
}
execute(&script_text, &mut state).await?;
if options.interact {
interactive(Some(state)).await?;
interactive(Some(state), options.norc).await?;
}
} else {
interactive(None).await?;
interactive(None, options.norc).await?;
}

Ok(())
Expand Down

0 comments on commit d555365

Please sign in to comment.