Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: added automatic shell detection #66

Merged
merged 4 commits into from
Dec 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@
ln -s $out/bin/comma $out/bin/,
'';
};
checkInputs = [ pkgs.rustPackages.clippy ];
doCheck = true;
cargoTestCommands = x:
x ++ [
''cargo clippy --all --all-features --tests -- \
-D warnings || true''
];
};
in
utils.lib.eachDefaultSystem
Expand Down
4 changes: 2 additions & 2 deletions src/index.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{
os::unix::prelude::CommandExt,
path::PathBuf,
path::{Path, PathBuf},
process::Command,
time::{Duration, SystemTime},
};
Expand Down Expand Up @@ -37,7 +37,7 @@ fn get_database_file() -> PathBuf {
}

/// Test whether the database is more than 30 days old
fn is_database_old(database_file: &std::path::PathBuf) -> bool {
fn is_database_old(database_file: &Path) -> bool {
let Ok(metadata) = database_file.metadata() else {
return false;
};
Expand Down
18 changes: 14 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
mod index;
mod shell;
use std::{
env,
io::Write,
os::unix::prelude::CommandExt,
process::{Command, ExitCode, Stdio},
process::{self, Command, ExitCode, Stdio},
};

use clap::crate_version;
Expand Down Expand Up @@ -35,7 +36,13 @@ fn pick(picker: &str, derivations: &[&str]) -> Option<String> {
)
}

fn run_command_or_open_shell(use_channel: bool, choice: &str, command: &str, trail: &[String], nixpkgs_flake: &str) {
fn run_command_or_open_shell(
use_channel: bool,
choice: &str,
command: &str,
trail: &[String],
nixpkgs_flake: &str,
) {
let mut run_cmd = Command::new("nix");

run_cmd.args([
Expand All @@ -52,7 +59,9 @@ fn run_command_or_open_shell(use_channel: bool, choice: &str, command: &str, tra

if !command.is_empty() {
run_cmd.args(["--command", command]);
run_cmd.args(trail);
if !trail.is_empty() {
run_cmd.args(trail);
}
};

run_cmd.exec();
Expand Down Expand Up @@ -132,7 +141,8 @@ fn main() -> ExitCode {
.args(["-f", "<nixpkgs>", "-iA", choice.rsplit('.').last().unwrap()])
.exec();
} else if args.shell {
run_command_or_open_shell(use_channel, &choice, "", &[String::new()], &args.nixpkgs_flake);
let shell_cmd = shell::select_shell_from_pid(process::id()).unwrap_or("bash".into());
run_command_or_open_shell(use_channel, &choice, &shell_cmd, &[], &args.nixpkgs_flake);
} else {
run_command_or_open_shell(use_channel, &choice, command, trail, &args.nixpkgs_flake);
}
Expand Down
63 changes: 63 additions & 0 deletions src/shell.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
use std::{error::Error, fs};

type ResultDyn<T> = Result<T, Box<dyn Error>>;

const KNOWN_SHELLS: &[&str] = &[
"ash", //
"bash", //
heinwol marked this conversation as resolved.
Show resolved Hide resolved
"elvish", //
"fish", //
"nu", //
"pwsh", //
"tcsh", //
"zsh", //
];

fn get_process_status_field(pid: u32, field: &str) -> ResultDyn<String> {
let status_bytes =
fs::read(format!("/proc/{pid:?}/status")).map_err(|_| format!("no such pid: {pid:?}"))?;
let status_str = String::from_utf8(status_bytes)?;
let status_str = status_str
.split('\n')
.find(|&x| x.starts_with(field))
.ok_or_else(|| format!("error parsing /proc/{pid:?}/status"))?;
let field_contents = status_str
.strip_prefix(&format!("{field}:"))
.ok_or_else(|| "bad parsing".to_string())?
.trim()
.to_owned();
Ok(field_contents)
}

fn get_parent_pid(pid: u32) -> ResultDyn<u32> {
Ok(get_process_status_field(pid, "PPid")?.parse::<u32>()?)
}

fn get_process_name(pid: u32) -> ResultDyn<String> {
get_process_status_field(pid, "Name")
}

fn get_all_parents_pid(pid: u32) -> ResultDyn<Vec<u32>> {
let mut res = Vec::<u32>::new();
let mut pid = pid;
loop {
match get_parent_pid(pid) {
Ok(parent_id) if parent_id != 0 => {
res.push(parent_id);
pid = parent_id;
}
Ok(_) => return Ok(res),
Err(e) => return Err(e),
}
}
}

pub fn select_shell_from_pid(pid: u32) -> ResultDyn<String> {
let parents = get_all_parents_pid(pid)?;
let parents_names: Result<Vec<_>, _> =
parents.iter().map(|&pid| get_process_name(pid)).collect();
let shell = parents_names?
.into_iter()
.find(|x| KNOWN_SHELLS.contains(&x.as_str()));
shell.ok_or("no shell found".into())
}