From 2c176a7f149d312c6435dc2b632a31e4f1dc8af2 Mon Sep 17 00:00:00 2001 From: WindSoilder Date: Thu, 14 Sep 2023 21:10:15 +0800 Subject: [PATCH] Ps: add `cwd` column on linux and macos (#10347) # Description Close: #7484 Just found that I want `cwd` column on linux/macos as well.. --- crates/nu-command/src/system/ps.rs | 5 +++++ crates/nu-system/src/linux.rs | 8 ++++++++ crates/nu-system/src/macos.rs | 16 +++++++++++++++- 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/crates/nu-command/src/system/ps.rs b/crates/nu-command/src/system/ps.rs index c87f72e05..5ed83cd82 100644 --- a/crates/nu-command/src/system/ps.rs +++ b/crates/nu-command/src/system/ps.rs @@ -143,6 +143,7 @@ fn run_ps(engine_state: &EngineState, call: &Call) -> Result Result, pub curr_status: Option, pub interval: Duration, + pub cwd: PathBuf, } pub fn collect_proc(interval: Duration, _with_thread: bool) -> Vec { @@ -98,6 +100,7 @@ pub fn collect_proc(interval: Duration, _with_thread: bool) -> Vec info!("failed to retrieve info for pid={curr_proc_pid}, process probably died between snapshots"); continue; }; + let cwd = curr_proc.cwd().unwrap_or_default(); let curr_io = curr_proc.io().ok(); let curr_stat = curr_proc.stat().ok(); @@ -117,6 +120,7 @@ pub fn collect_proc(interval: Duration, _with_thread: bool) -> Vec prev_stat, curr_status, interval, + cwd, }; ret.push(proc); @@ -165,6 +169,10 @@ impl ProcessInfo { } } + pub fn cwd(&self) -> String { + self.cwd.display().to_string() + } + /// Get the status of the process pub fn status(&self) -> String { if let Ok(p) = self.curr_proc.stat() { diff --git a/crates/nu-system/src/macos.rs b/crates/nu-system/src/macos.rs index ab19b78bd..0842f42fe 100644 --- a/crates/nu-system/src/macos.rs +++ b/crates/nu-system/src/macos.rs @@ -142,6 +142,7 @@ pub struct PathInfo { pub root: PathBuf, pub cmd: Vec, pub env: Vec, + pub cwd: PathBuf, } #[cfg_attr(tarpaulin, skip)] @@ -213,12 +214,17 @@ fn get_path_info(pid: i32, mut size: size_t) -> Option { } start = cp; let mut env = Vec::new(); + let mut cwd = PathBuf::default(); while cp < ptr.add(size) { if *cp == 0 { if cp == start { break; } - env.push(get_unchecked_str(cp, start)); + let env_str = get_unchecked_str(cp, start); + if let Some(pwd) = env_str.strip_prefix("PWD=") { + cwd = PathBuf::from(pwd) + } + env.push(env_str); start = cp.offset(1); } cp = cp.offset(1); @@ -238,6 +244,7 @@ fn get_path_info(pid: i32, mut size: size_t) -> Option { root, cmd, env, + cwd, }) } else { None @@ -394,6 +401,13 @@ impl ProcessInfo { pub fn virtual_size(&self) -> u64 { self.curr_task.ptinfo.pti_virtual_size } + + pub fn cwd(&self) -> String { + self.curr_path + .as_ref() + .map(|cur_path| cur_path.cwd.display().to_string()) + .unwrap_or_else(|| "".to_string()) + } } /// The Macos kernel returns process times in mach ticks rather than nanoseconds. To get times in