Implement job id command

This cmomit also modifies run_external and job_unfreeze because the
engine_state stores the id of the current job in the
current_thread_job field, so its usages are accessed differently now.
This commit is contained in:
cosineblast 2025-03-05 00:42:31 -03:00
parent 7c160725ed
commit bffa9d3278
7 changed files with 77 additions and 13 deletions

View File

@ -451,6 +451,7 @@ pub fn add_shell_command_context(mut engine_state: EngineState) -> EngineState {
JobSpawn, JobSpawn,
JobList, JobList,
JobKill, JobKill,
JobId,
Job, Job,
}; };

View File

@ -0,0 +1,54 @@
use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct JobId;
impl Command for JobId {
fn name(&self) -> &str {
"job id"
}
fn description(&self) -> &str {
"Get id of current job."
}
fn extra_description(&self) -> &str {
"This command returns the job id for the current background job.
The special id 0 indicates that this command was not called from a background job thread, and
was instead spawned by main nushell execution thread."
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("job id")
.category(Category::Experimental)
.input_output_types(vec![(Type::Nothing, Type::Int)])
}
fn search_terms(&self) -> Vec<&str> {
vec!["self", "this", "my-id", "this-id"]
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
if let Some((id, _)) = &engine_state.thread_job_entry {
Ok(Value::int(id.get() as i64, head).into_pipeline_data())
} else {
Ok(Value::int(0, head).into_pipeline_data())
}
}
fn examples(&self) -> Vec<Example> {
vec![Example {
example: "job id",
description: "Get id of current job",
result: None,
}]
}
}

View File

@ -69,8 +69,11 @@ impl Command for JobSpawn {
let id = { let id = {
let thread_job = ThreadJob::new(job_signals); let thread_job = ThreadJob::new(job_signals);
job_state.current_thread_job = Some(thread_job.clone()); let id = jobs.add_job(Job::Thread(thread_job.clone()));
jobs.add_job(Job::Thread(thread_job))
job_state.thread_job_entry = Some((id, thread_job));
id
}; };
let result = thread::Builder::new() let result = thread::Builder::new()

View File

@ -115,7 +115,7 @@ fn unfreeze_job(
Job::Frozen(FrozenJob { unfreeze: handle }) => { Job::Frozen(FrozenJob { unfreeze: handle }) => {
let pid = handle.pid(); let pid = handle.pid();
if let Some(thread_job) = &state.current_thread_job { if let Some(thread_job) = &state.current_thread_job() {
if !thread_job.try_add_pid(pid) { if !thread_job.try_add_pid(pid) {
kill_by_pid(pid.into()).map_err(|err| { kill_by_pid(pid.into()).map_err(|err| {
ShellError::Io(IoError::new_internal( ShellError::Io(IoError::new_internal(
@ -133,7 +133,7 @@ fn unfreeze_job(
.then(|| state.pipeline_externals_state.clone()), .then(|| state.pipeline_externals_state.clone()),
); );
if let Some(thread_job) = &state.current_thread_job { if let Some(thread_job) = &state.current_thread_job() {
thread_job.remove_pid(pid); thread_job.remove_pid(pid);
} }

View File

@ -1,5 +1,6 @@
mod is_admin; mod is_admin;
mod job; mod job;
mod job_id;
mod job_kill; mod job_kill;
mod job_list; mod job_list;
mod job_spawn; mod job_spawn;
@ -9,9 +10,9 @@ mod job_unfreeze;
pub use is_admin::IsAdmin; pub use is_admin::IsAdmin;
pub use job::Job; pub use job::Job;
pub use job_id::JobId;
pub use job_kill::JobKill; pub use job_kill::JobKill;
pub use job_list::JobList; pub use job_list::JobList;
pub use job_spawn::JobSpawn; pub use job_spawn::JobSpawn;
#[cfg(all(unix, feature = "os"))] #[cfg(all(unix, feature = "os"))]

View File

@ -279,7 +279,7 @@ impl Command for External {
) )
})?; })?;
if let Some(thread_job) = &engine_state.current_thread_job { if let Some(thread_job) = engine_state.current_thread_job() {
if !thread_job.try_add_pid(child.pid()) { if !thread_job.try_add_pid(child.pid()) {
kill_by_pid(child.pid().into()).map_err(|err| { kill_by_pid(child.pid().into()).map_err(|err| {
ShellError::Io(IoError::new_internal( ShellError::Io(IoError::new_internal(
@ -312,8 +312,8 @@ impl Command for External {
} }
let jobs = engine_state.jobs.clone(); let jobs = engine_state.jobs.clone();
let this_job = engine_state.current_thread_job.clone();
let is_interactive = engine_state.is_interactive; let is_interactive = engine_state.is_interactive;
let this_job = engine_state.current_thread_job().cloned();
let child_pid = child.pid(); let child_pid = child.pid();
// Wrap the output into a `PipelineData::ByteStream`. // Wrap the output into a `PipelineData::ByteStream`.

View File

@ -8,9 +8,9 @@ use crate::{
}, },
eval_const::create_nu_constant, eval_const::create_nu_constant,
shell_error::io::IoError, shell_error::io::IoError,
BlockId, Category, Config, DeclId, FileId, GetSpan, Handlers, HistoryConfig, Module, ModuleId, BlockId, Category, Config, DeclId, FileId, GetSpan, Handlers, HistoryConfig, JobId, Module,
OverlayId, ShellError, SignalAction, Signals, Signature, Span, SpanId, Type, Value, VarId, ModuleId, OverlayId, ShellError, SignalAction, Signals, Signature, Span, SpanId, Type, Value,
VirtualPathId, VarId, VirtualPathId,
}; };
use fancy_regex::Regex; use fancy_regex::Regex;
use lru::LruCache; use lru::LruCache;
@ -117,7 +117,7 @@ pub struct EngineState {
pub jobs: Arc<Mutex<Jobs>>, pub jobs: Arc<Mutex<Jobs>>,
// The job being executed with this engine state, or None if main thread // The job being executed with this engine state, or None if main thread
pub current_thread_job: Option<ThreadJob>, pub thread_job_entry: Option<(JobId, ThreadJob)>,
// When there are background jobs running, the interactive behavior of `exit` changes depending on // When there are background jobs running, the interactive behavior of `exit` changes depending on
// the value of this flag: // the value of this flag:
@ -196,7 +196,7 @@ impl EngineState {
is_debugging: IsDebugging::new(false), is_debugging: IsDebugging::new(false),
debugger: Arc::new(Mutex::new(Box::new(NoopDebugger))), debugger: Arc::new(Mutex::new(Box::new(NoopDebugger))),
jobs: Arc::new(Mutex::new(Jobs::default())), jobs: Arc::new(Mutex::new(Jobs::default())),
current_thread_job: None, thread_job_entry: None,
exit_warning_given: Arc::new(AtomicBool::new(false)), exit_warning_given: Arc::new(AtomicBool::new(false)),
} }
} }
@ -1080,7 +1080,12 @@ impl EngineState {
// Determines whether the current state is being held by a background job // Determines whether the current state is being held by a background job
pub fn is_background_job(&self) -> bool { pub fn is_background_job(&self) -> bool {
self.current_thread_job.is_some() self.thread_job_entry.is_some()
}
// Gets the thread job entry
pub fn current_thread_job(&self) -> Option<&ThreadJob> {
self.thread_job_entry.as_ref().map(|(_, job)| job)
} }
} }