Skip to content

Commit d555365

Browse files
authored
Source ~/.shellrc automatically if it exists (#173)
* Source ~/.shellrc automatically if it exists * Implement --norc option to skip sourcing .shellrc Fixes #95.
1 parent 90d3346 commit d555365

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

crates/shell/src/main.rs

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,10 @@ struct Options {
2424
#[clap(long)]
2525
interact: bool,
2626

27+
/// Do not source ~/.shellrc on startup
28+
#[clap(long)]
29+
norc: bool,
30+
2731
#[clap(short, long)]
2832
debug: bool,
2933
}
@@ -34,7 +38,7 @@ fn init_state() -> ShellState {
3438
ShellState::new(env_vars, &cwd, commands::get_commands())
3539
}
3640

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

5559
let home = dirs::home_dir().ok_or(miette::miette!("Couldn't get home directory"))?;
60+
61+
// Load .shell_history
5662
let history_file: PathBuf = [home.as_path(), Path::new(".shell_history")]
5763
.iter()
5864
.collect();
@@ -62,6 +68,16 @@ async fn interactive(state: Option<ShellState>) -> miette::Result<()> {
6268
.context("Failed to read the command history")?;
6369
}
6470

71+
// Load ~/.shellrc
72+
let shellrc_file: PathBuf = [home.as_path(), Path::new(".shellrc")].iter().collect();
73+
if !norc && Path::new(shellrc_file.as_path()).exists() {
74+
let line = "source '".to_owned() + shellrc_file.to_str().unwrap() + "'";
75+
let prev_exit_code = execute(&line, &mut state)
76+
.await
77+
.context("Failed to source ~/.shellrc")?;
78+
state.set_last_command_exit_code(prev_exit_code);
79+
}
80+
6581
let mut _prev_exit_code = 0;
6682
loop {
6783
// Reset cancellation flag
@@ -156,10 +172,10 @@ async fn main() -> miette::Result<()> {
156172
}
157173
execute(&script_text, &mut state).await?;
158174
if options.interact {
159-
interactive(Some(state)).await?;
175+
interactive(Some(state), options.norc).await?;
160176
}
161177
} else {
162-
interactive(None).await?;
178+
interactive(None, options.norc).await?;
163179
}
164180

165181
Ok(())

0 commit comments

Comments
 (0)