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

Targeted improvements to job managements #38

Merged
merged 2 commits into from
May 31, 2024
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
5 changes: 4 additions & 1 deletion parser/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,10 @@ impl Display for Pipeline {
if self.bang {
write!(f, "!")?;
}
for command in &self.seq {
for (i, command) in self.seq.iter().enumerate() {
if i > 0 {
write!(f, " |")?;
}
write!(f, "{}", command)?;
}

Expand Down
2 changes: 1 addition & 1 deletion shell/src/builtins/jobs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ impl BuiltinCommand for JobsCommand {
return error::unimp("jobs with job specs");
}

for job in &context.shell.jobs.background_jobs {
for job in &context.shell.jobs.jobs {
writeln!(context.stdout(), "{job}")?;
}

Expand Down
39 changes: 32 additions & 7 deletions shell/src/completion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ use std::{
path::{Path, PathBuf},
};

use crate::{env, error, namedoptions, patterns, users, variables::ShellValueLiteral, Shell};
use crate::{
env, error, jobs, namedoptions, patterns, traps, users, variables::ShellValueLiteral, Shell,
};

#[derive(Clone, Debug, ValueEnum)]
pub enum CompleteAction {
Expand Down Expand Up @@ -229,8 +231,11 @@ impl CompletionSpec {
candidates.append(&mut file_completions);
}
CompleteAction::Disabled => {
// For now, no builtins are disabled.
tracing::debug!("UNIMPLEMENTED: complete -A disabled");
for (name, registration) in &shell.builtins {
if registration.disabled {
candidates.push(name.to_owned());
}
}
}
CompleteAction::Enabled => {
for (name, registration) in &shell.builtins {
Expand Down Expand Up @@ -268,13 +273,23 @@ impl CompletionSpec {
candidates.push(name.to_string_lossy().to_string());
}
}
CompleteAction::Job => tracing::debug!("UNIMPLEMENTED: complete -A job"),
CompleteAction::Job => {
for job in &shell.jobs.jobs {
candidates.push(job.get_command_name().to_owned());
}
}
CompleteAction::Keyword => {
for keyword in shell.get_keywords() {
candidates.push(keyword.clone());
}
}
CompleteAction::Running => tracing::debug!("UNIMPLEMENTED: complete -A running"),
CompleteAction::Running => {
for job in &shell.jobs.jobs {
if matches!(job.state, jobs::JobState::Running) {
candidates.push(job.get_command_name().to_owned());
}
}
}
CompleteAction::Service => tracing::debug!("UNIMPLEMENTED: complete -A service"),
CompleteAction::SetOpt => {
for (name, _) in namedoptions::SET_O_OPTIONS.iter() {
Expand All @@ -286,8 +301,18 @@ impl CompletionSpec {
candidates.push((*name).to_owned());
}
}
CompleteAction::Signal => tracing::debug!("UNIMPLEMENTED: complete -A signal"),
CompleteAction::Stopped => tracing::debug!("UNIMPLEMENTED: complete -A stopped"),
CompleteAction::Signal => {
for signal in traps::TrapSignal::all_values() {
candidates.push(signal.to_string());
}
}
CompleteAction::Stopped => {
for job in &shell.jobs.jobs {
if matches!(job.state, jobs::JobState::Stopped) {
candidates.push(job.get_command_name().to_owned());
}
}
}
CompleteAction::User => {
let mut names = users::get_all_users()?;
candidates.append(&mut names);
Expand Down
3 changes: 3 additions & 0 deletions shell/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@ pub enum Error {

#[error("invalid signal")]
InvalidSignal,

#[error("system error: {0}")]
ErrnoError(#[from] nix::errno::Errno),
}

pub(crate) fn unimp<T>(msg: &'static str) -> Result<T, Error> {
Expand Down
126 changes: 85 additions & 41 deletions shell/src/interp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,28 +140,17 @@ impl Execute for ast::CompoundList {
let run_async = matches!(sep, ast::SeparatorOperator::Async);

if run_async {
let background_job = tokio::spawn(execute_ao_list_async(
shell.clone(),
params.clone(),
ao_list.clone(),
));
// TODO: Reenable launching in child process?
// let job = spawn_ao_list_in_child(ao_list, shell, params).await?;

// TODO: Find pids
let job = shell.jobs.add(jobs::Job::new(
VecDeque::from([background_job]),
vec![],
ao_list.to_string(),
jobs::JobState::Running,
));
let job_id = job.id;
let job_annotation = job.get_annotation();
let job_pid = job
.get_pid()?
.map_or_else(|| String::from("<pid unknown>"), |pid| pid.to_string());
let job = spawn_ao_list_in_task(ao_list, shell, params);
let job_formatted = job.to_pid_style_string();

if shell.options.interactive {
writeln!(shell.stderr(), "[{job_id}]{job_annotation}\t{job_pid}")?;
writeln!(shell.stderr(), "{job_formatted}")?;
}

result = ExecutionResult::success();
} else {
result = ao_list.execute(shell, params).await?;
}
Expand All @@ -182,15 +171,82 @@ impl Execute for ast::CompoundList {
}
}

async fn execute_ao_list_async(
mut shell: Shell,
params: ExecutionParameters,
ao_list: ast::AndOrList,
) -> Result<ExecutionResult, error::Error> {
let background_job = ao_list.execute(&mut shell, &params).await?;
Ok(background_job)
fn spawn_ao_list_in_task<'a>(
ao_list: &ast::AndOrList,
shell: &'a mut Shell,
params: &ExecutionParameters,
) -> &'a jobs::Job {
// Clone the inputs.
let mut cloned_shell = shell.clone();
let cloned_params = params.clone();
let cloned_ao_list = ao_list.clone();

// Mark the child shell as not interactive; we don't want it messing with the terminal too much.
cloned_shell.options.interactive = false;

let join_handle = tokio::spawn(async move {
cloned_ao_list
.execute(&mut cloned_shell, &cloned_params)
.await
});

let job = shell.jobs.add_as_current(jobs::Job::new(
VecDeque::from([join_handle]),
vec![],
ao_list.to_string(),
jobs::JobState::Running,
));

job
}

// async fn spawn_ao_list_in_child<'a>(
// ao_list: &ast::AndOrList,
// shell: &'a mut Shell,
// params: &ExecutionParameters,
// ) -> Result<&'a jobs::Job, error::Error> {
// let fork_result = unsafe { nix::unistd::fork() }?;

// #[allow(clippy::cast_lossless)]
// #[allow(clippy::cast_sign_loss)]
// match fork_result {
// nix::unistd::ForkResult::Parent { child } => {
// let join_handle = tokio::spawn(async move {
// let wait_status = nix::sys::wait::waitid(
// nix::sys::wait::Id::Pid(child),
// nix::sys::wait::WaitPidFlag::WEXITED,
// )?;

// #[allow(clippy::cast_possible_truncation)]
// if let nix::sys::wait::WaitStatus::Exited(_, code) = wait_status {
// Ok(ExecutionResult::new(code as u8))
// } else {
// Ok(ExecutionResult::new(1))
// }
// });

// let job = shell.jobs.add_as_current(jobs::Job::new(
// VecDeque::from([join_handle]),
// vec![child.as_raw() as u32],
// ao_list.to_string(),
// jobs::JobState::Running,
// ));

// Ok(job)
// }
// nix::unistd::ForkResult::Child => {
// if nix::unistd::setpgid(nix::unistd::Pid::from_raw(0), nix::unistd::Pid::from_raw(0))
// .is_err()
// {
// std::process::exit(1);
// }

// let result = ao_list.execute(shell, params).await?;
// std::process::exit(result.exit_code as i32);
// }
// }
// }

#[async_trait::async_trait]
impl Execute for ast::AndOrList {
async fn execute(
Expand Down Expand Up @@ -356,37 +412,25 @@ impl Execute for ast::Pipeline {
}

if !stopped.is_empty() {
let job = shell.jobs.add(jobs::Job::new(
let job = shell.jobs.add_as_current(jobs::Job::new(
stopped,
pids,
self.to_string(),
jobs::JobState::Stopped,
));
let job_id = job.id;
let job_state = job.state.clone();

let annotation = if job.is_current() {
"+"
} else if job.is_prev() {
"-"
} else {
""
};
let formatted = job.to_string();

// N.B. We use the '\r' to overwrite any ^Z output.
writeln!(
shell.stderr(),
"\r[{job_id}]{annotation:3}{:24}{}",
job_state.to_string(),
self
)?;
writeln!(shell.stderr(), "\r{formatted}")?;
}

if self.bang {
result.exit_code = if result.exit_code == 0 { 1 } else { 0 };
}

shell.last_exit_status = result.exit_code;

Ok(result)
}
}
Expand Down
Loading
Loading