| 1 |
use std::collections::{HashMap, HashSet}; |
| 2 |
use std::path::Path; |
| 3 |
use std::sync::atomic::AtomicUsize; |
| 4 |
use std::sync::{Arc, Condvar, Mutex, MutexGuard}; |
| 5 |
|
| 6 |
use lazy_static::lazy_static; |
| 7 |
use sysinfo::{Pid, PidExt, Process, ProcessExt, ProcessRefreshKind, SystemExt}; |
| 8 |
|
| 9 |
use crate::utils::DELTA_ATOMIC_ORDERING; |
| 10 |
|
| 11 |
pub type DeltaPid = u32; |
| 12 |
|
| 13 |
#[derive(Clone, Debug, PartialEq, Eq)] |
| 14 |
pub enum CallingProcess { |
| 15 |
GitDiff(CommandLine), |
| 16 |
GitShow(CommandLine, Option<String>), // element 2 is filename |
| 17 |
GitLog(CommandLine), |
| 18 |
GitReflog(CommandLine), |
| 19 |
GitBlame(CommandLine), |
| 20 |
GitGrep(CommandLine), |
| 21 |
OtherGrep, // rg, grep, ag, ack, etc |
| 22 |
None, // no matching process could be found |
| 23 |
Pending, // calling process is currently being determined |
| 24 |
} |
| 25 |
|
| 26 |
// The information where the calling process info comes from *should* be inside |
| 27 |
// `CallingProcess`, but that is handed out (within a MutexGuard) to callers. |
| 28 |
// To keep the interface simple, store it here: |
| 29 |
static CALLER_INFO_SOURCE: AtomicUsize = AtomicUsize::new(CALLER_GUESSED); |
| 30 |
const CALLER_GUESSED: usize = 1; |
| 31 |
const CALLER_KNOWN: usize = 2; |
| 32 |
|
| 33 |
impl CallingProcess { |
| 34 |
pub fn paths_in_input_are_relative_to_cwd(&self) -> bool { |
| 35 |
match self { |
| 36 |
CallingProcess::GitDiff(cmd) if cmd.long_options.contains("--relative") => true, |
| 37 |
CallingProcess::GitShow(cmd, _) if cmd.long_options.contains("--relative") => true, |
| 38 |
CallingProcess::GitLog(cmd) if cmd.long_options.contains("--relative") => true, |
| 39 |
CallingProcess::GitBlame(_) |
| 40 |
| CallingProcess::GitGrep(_) |
| 41 |
| CallingProcess::OtherGrep => true, |
| 42 |
_ => false, |
| 43 |
} |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
#[derive(Clone, Debug, PartialEq, Eq)] |
| 48 |
pub struct CommandLine { |
| 49 |
pub long_options: HashSet<String>, |
| 50 |
pub short_options: HashSet<String>, |
| 51 |
pub last_arg: Option<String>, |
| 52 |
} |
| 53 |
|
| 54 |
lazy_static! { |
| 55 |
static ref CALLER: Arc<(Mutex<CallingProcess>, Condvar)> = |
| 56 |
Arc::new((Mutex::new(CallingProcess::Pending), Condvar::new())); |
| 57 |
} |
| 58 |
|
| 59 |
// delta was called by this process (or called by something which called delta and it), |
| 60 |
// try looking up this information in the process tree. |
| 61 |
pub fn start_determining_calling_process_in_thread() { |
| 62 |
// The handle is neither kept nor returned nor joined but dropped, so the main |
| 63 |
// thread can exit early if it does not need to know its parent process. |
| 64 |
std::thread::Builder::new() |
| 65 |
.name("find_calling_process".into()) |
| 66 |
.spawn(move || { |
| 67 |
let calling_process = determine_calling_process(); |
| 68 |
|
| 69 |
let (caller_mutex, determine_done) = &**CALLER; |
| 70 |
|
| 71 |
let mut caller = caller_mutex.lock().unwrap(); |
| 72 |
|
| 73 |
if CALLER_INFO_SOURCE.load(DELTA_ATOMIC_ORDERING) <= CALLER_GUESSED { |
| 74 |
*caller = calling_process; |
| 75 |
} |
| 76 |
|
| 77 |
determine_done.notify_all(); |
| 78 |
}) |
| 79 |
.unwrap(); |
| 80 |
} |
| 81 |
|
| 82 |
// delta starts the process, so it is known. |
| 83 |
pub fn set_calling_process(args: &[String]) { |
| 84 |
if let ProcessArgs::Args(result) = describe_calling_process(args) { |
| 85 |
let (caller_mutex, determine_done) = &**CALLER; |
| 86 |
|
| 87 |
let mut caller = caller_mutex.lock().unwrap(); |
| 88 |
*caller = result; |
| 89 |
CALLER_INFO_SOURCE.store(CALLER_KNOWN, DELTA_ATOMIC_ORDERING); |
| 90 |
determine_done.notify_all(); |
| 91 |
} |
| 92 |
} |
| 93 |
|
| 94 |
#[cfg(not(test))] |
| 95 |
pub fn calling_process() -> MutexGuard<'static, CallingProcess> { |
| 96 |
let (caller_mutex, determine_done) = &**CALLER; |
| 97 |
|
| 98 |
determine_done |
| 99 |
.wait_while(caller_mutex.lock().unwrap(), |caller| { |
| 100 |
*caller == CallingProcess::Pending |
| 101 |
}) |
| 102 |
.unwrap() |
| 103 |
} |
| 104 |
|
| 105 |
// The return value is duck-typed to work in place of a MutexGuard when testing. |
| 106 |
#[cfg(test)] |
| 107 |
pub fn calling_process() -> Box<CallingProcess> { |
| 108 |
type _UnusedImport = MutexGuard<'static, i8>; |
| 109 |
|
| 110 |
if crate::utils::process::tests::FakeParentArgs::are_set() { |
| 111 |
// If the (thread-local) FakeParentArgs are set, then the following command returns |
| 112 |
// these, so the cached global real ones can not be used. |
| 113 |
Box::new(determine_calling_process()) |
| 114 |
} else { |
| 115 |
let (caller_mutex, _) = &**CALLER; |
| 116 |
|
| 117 |
let mut caller = caller_mutex.lock().unwrap(); |
| 118 |
if *caller == CallingProcess::Pending { |
| 119 |
*caller = determine_calling_process(); |
| 120 |
} |
| 121 |
|
| 122 |
Box::new(caller.clone()) |
| 123 |
} |
| 124 |
} |
| 125 |
|
| 126 |
fn determine_calling_process() -> CallingProcess { |
| 127 |
calling_process_cmdline(ProcInfo::new(), describe_calling_process) |
| 128 |
.unwrap_or(CallingProcess::None) |
| 129 |
} |
| 130 |
|
| 131 |
// Return value of `extract_args(args: &[String]) -> ProcessArgs<T>` function which is |
| 132 |
// passed to `calling_process_cmdline()`. |
| 133 |
#[derive(Debug, PartialEq, Eq)] |
| 134 |
pub enum ProcessArgs<T> { |
| 135 |
// A result has been successfully extracted from args. |
| 136 |
Args(T), |
| 137 |
// The extraction has failed. |
| 138 |
ArgError, |
| 139 |
// The process does not match, others may be inspected. |
| 140 |
OtherProcess, |
| 141 |
} |
| 142 |
|
| 143 |
pub fn describe_calling_process(args: &[String]) -> ProcessArgs<CallingProcess> { |
| 144 |
let mut args = args.iter().map(|s| s.as_str()); |
| 145 |
|
| 146 |
fn is_any_of<'a, I>(cmd: Option<&str>, others: I) -> bool |
| 147 |
where |
| 148 |
I: IntoIterator<Item = &'a str>, |
| 149 |
{ |
| 150 |
cmd.map(|cmd| others.into_iter().any(|o| o.eq_ignore_ascii_case(cmd))) |
| 151 |
.unwrap_or(false) |
| 152 |
} |
| 153 |
|
| 154 |
match args.next() { |
| 155 |
Some(command) => match Path::new(command).file_stem() { |
| 156 |
Some(s) if s.to_str().map(is_git_binary).unwrap_or(false) => { |
| 157 |
let mut args = args.skip_while(|s| { |
| 158 |
*s != "diff" |
| 159 |
&& *s != "show" |
| 160 |
&& *s != "log" |
| 161 |
&& *s != "reflog" |
| 162 |
&& *s != "grep" |
| 163 |
&& *s != "blame" |
| 164 |
}); |
| 165 |
match args.next() { |
| 166 |
Some("diff") => { |
| 167 |
ProcessArgs::Args(CallingProcess::GitDiff(parse_command_line(args))) |
| 168 |
} |
| 169 |
Some("show") => { |
| 170 |
let command_line = parse_command_line(args); |
| 171 |
let filename = if let Some(last_arg) = &command_line.last_arg { |
| 172 |
match last_arg.split_once(':') { |
| 173 |
Some((_, filename)) => Path::new(filename) |
| 174 |
.file_name() |
| 175 |
.map(|f| f.to_string_lossy().to_string()), |
| 176 |
None => None, |
| 177 |
} |
| 178 |
} else { |
| 179 |
None |
| 180 |
}; |
| 181 |
ProcessArgs::Args(CallingProcess::GitShow(command_line, filename)) |
| 182 |
} |
| 183 |
Some("log") => { |
| 184 |
ProcessArgs::Args(CallingProcess::GitLog(parse_command_line(args))) |
| 185 |
} |
| 186 |
Some("reflog") => { |
| 187 |
ProcessArgs::Args(CallingProcess::GitReflog(parse_command_line(args))) |
| 188 |
} |
| 189 |
Some("grep") => { |
| 190 |
ProcessArgs::Args(CallingProcess::GitGrep(parse_command_line(args))) |
| 191 |
} |
| 192 |
Some("blame") => { |
| 193 |
ProcessArgs::Args(CallingProcess::GitBlame(parse_command_line(args))) |
| 194 |
} |
| 195 |
_ => { |
| 196 |
// It's git, but not a subcommand that we parse. Don't |
| 197 |
// look at any more processes. |
| 198 |
ProcessArgs::ArgError |
| 199 |
} |
| 200 |
} |
| 201 |
} |
| 202 |
// TODO: parse_style_sections is failing to parse ANSI escape sequences emitted by |
| 203 |
// grep (BSD and GNU), ag, pt. See #794 |
| 204 |
Some(s) if is_any_of(s.to_str(), ["rg", "ack", "sift"]) => { |
| 205 |
ProcessArgs::Args(CallingProcess::OtherGrep) |
| 206 |
} |
| 207 |
Some(_) => { |
| 208 |
// It's not git, and it's not another grep tool. Keep |
| 209 |
// looking at other processes. |
| 210 |
ProcessArgs::OtherProcess |
| 211 |
} |
| 212 |
_ => { |
| 213 |
// Could not parse file stem (not expected); keep looking at |
| 214 |
// other processes. |
| 215 |
ProcessArgs::OtherProcess |
| 216 |
} |
| 217 |
}, |
| 218 |
_ => { |
| 219 |
// Empty arguments (not expected); keep looking. |
| 220 |
ProcessArgs::OtherProcess |
| 221 |
} |
| 222 |
} |
| 223 |
} |
| 224 |
|
| 225 |
fn is_git_binary(git: &str) -> bool { |
| 226 |
// Ignore case, for e.g. NTFS or APFS file systems |
| 227 |
Path::new(git) |
| 228 |
.file_stem() |
| 229 |
.and_then(|os_str| os_str.to_str()) |
| 230 |
.map(|s| s.eq_ignore_ascii_case("git")) |
| 231 |
.unwrap_or(false) |
| 232 |
} |
| 233 |
|
| 234 |
// Given `--aa val -bc -d val e f -- ...` return |
| 235 |
// ({"--aa"}, {"-b", "-c", "-d"}) |
| 236 |
fn parse_command_line<'a>(args: impl Iterator<Item = &'a str>) -> CommandLine { |
| 237 |
let mut long_options = HashSet::new(); |
| 238 |
let mut short_options = HashSet::new(); |
| 239 |
let mut last_arg = None; |
| 240 |
let mut after_double_dash = false; |
| 241 |
|
| 242 |
for s in args { |
| 243 |
if after_double_dash { |
| 244 |
last_arg = Some(s); |
| 245 |
} else if s == "--" { |
| 246 |
after_double_dash = true; |
| 247 |
} else if s.starts_with("--") { |
| 248 |
long_options.insert(s.split('=').next().unwrap().to_owned()); |
| 249 |
} else if let Some(suffix) = s.strip_prefix('-') { |
| 250 |
short_options.extend(suffix.chars().map(|c| format!("-{c}"))); |
| 251 |
} else { |
| 252 |
last_arg = Some(s); |
| 253 |
} |
| 254 |
} |
| 255 |
|
| 256 |
CommandLine { |
| 257 |
long_options, |
| 258 |
short_options, |
| 259 |
last_arg: last_arg.map(|s| s.to_string()), |
| 260 |
} |
| 261 |
} |
| 262 |
|
| 263 |
struct ProcInfo { |
| 264 |
info: sysinfo::System, |
| 265 |
} |
| 266 |
impl ProcInfo { |
| 267 |
fn new() -> Self { |
| 268 |
// On Linux sysinfo optimizes for repeated process queries and keeps per-process |
| 269 |
// /proc file descriptors open. This caching is not needed here, so |
| 270 |
// set this to zero (this does nothing on other platforms). |
| 271 |
// Also, there is currently a kernel bug which slows down syscalls when threads are |
| 272 |
// involved (here: the ctrlc handler) and a lot of files are kept open. |
| 273 |
sysinfo::set_open_files_limit(0); |
| 274 |
|
| 275 |
ProcInfo { |
| 276 |
info: sysinfo::System::new(), |
| 277 |
} |
| 278 |
} |
| 279 |
} |
| 280 |
|
| 281 |
trait ProcActions { |
| 282 |
fn cmd(&self) -> &[String]; |
| 283 |
fn parent(&self) -> Option<DeltaPid>; |
| 284 |
fn pid(&self) -> DeltaPid; |
| 285 |
fn start_time(&self) -> u64; |
| 286 |
} |
| 287 |
|
| 288 |
impl<T> ProcActions for T |
| 289 |
where |
| 290 |
T: ProcessExt, |
| 291 |
{ |
| 292 |
fn cmd(&self) -> &[String] { |
| 293 |
ProcessExt::cmd(self) |
| 294 |
} |
| 295 |
fn parent(&self) -> Option<DeltaPid> { |
| 296 |
ProcessExt::parent(self).map(|p| p.as_u32()) |
| 297 |
} |
| 298 |
fn pid(&self) -> DeltaPid { |
| 299 |
ProcessExt::pid(self).as_u32() |
| 300 |
} |
| 301 |
fn start_time(&self) -> u64 { |
| 302 |
ProcessExt::start_time(self) |
| 303 |
} |
| 304 |
} |
| 305 |
|
| 306 |
trait ProcessInterface { |
| 307 |
type Out: ProcActions; |
| 308 |
|
| 309 |
fn my_pid(&self) -> DeltaPid; |
| 310 |
|
| 311 |
fn process(&self, pid: DeltaPid) -> Option<&Self::Out>; |
| 312 |
fn processes(&self) -> &HashMap<Pid, Self::Out>; |
| 313 |
|
| 314 |
fn refresh_process(&mut self, pid: DeltaPid) -> bool; |
| 315 |
fn refresh_processes(&mut self); |
| 316 |
|
| 317 |
fn parent_process(&mut self, pid: DeltaPid) -> Option<&Self::Out> { |
| 318 |
self.refresh_process(pid).then_some(())?; |
| 319 |
let parent_pid = self.process(pid)?.parent()?; |
| 320 |
self.refresh_process(parent_pid).then_some(())?; |
| 321 |
self.process(parent_pid) |
| 322 |
} |
| 323 |
fn naive_sibling_process(&mut self, pid: DeltaPid) -> Option<&Self::Out> { |
| 324 |
let sibling_pid = pid - 1; |
| 325 |
self.refresh_process(sibling_pid).then_some(())?; |
| 326 |
self.process(sibling_pid) |
| 327 |
} |
| 328 |
fn find_sibling_in_refreshed_processes<F, T>( |
| 329 |
&mut self, |
| 330 |
pid: DeltaPid, |
| 331 |
extract_args: &F, |
| 332 |
) -> Option<T> |
| 333 |
where |
| 334 |
F: Fn(&[String]) -> ProcessArgs<T>, |
| 335 |
Self: Sized, |
| 336 |
{ |
| 337 |
/* |
| 338 |
|
| 339 |
$ start_blame_of.sh src/main.rs | delta |
| 340 |
|
| 341 |
\_ /usr/bin/some-terminal-emulator |
| 342 |
| \_ common_git_and_delta_ancestor |
| 343 |
| \_ /bin/sh /opt/git/start_blame_of.sh src/main.rs |
| 344 |
| | \_ /bin/sh /opt/some/wrapper git blame src/main.rs |
| 345 |
| | \_ /usr/bin/git blame src/main.rs |
| 346 |
| \_ /bin/sh /opt/some/wrapper delta |
| 347 |
| \_ delta |
| 348 |
|
| 349 |
Walk up the process tree of delta and of every matching other process, counting the steps |
| 350 |
along the way. |
| 351 |
Find the common ancestor processes, calculate the distance, and select the one with the shortest. |
| 352 |
|
| 353 |
*/ |
| 354 |
|
| 355 |
let this_start_time = self.process(pid)?.start_time(); |
| 356 |
|
| 357 |
let mut pid_distances = HashMap::<DeltaPid, usize>::new(); |
| 358 |
let mut collect_parent_pids = |pid, distance| { |
| 359 |
pid_distances.insert(pid, distance); |
| 360 |
}; |
| 361 |
|
| 362 |
iter_parents(self, pid, &mut collect_parent_pids); |
| 363 |
|
| 364 |
let process_start_time_difference_less_than_3s = |a, b| (a as i64 - b as i64).abs() < 3; |
| 365 |
|
| 366 |
let cmdline_of_closest_matching_process = self |
| 367 |
.processes() |
| 368 |
.iter() |
| 369 |
.filter(|(_, proc)| { |
| 370 |
process_start_time_difference_less_than_3s(this_start_time, proc.start_time()) |
| 371 |
}) |
| 372 |
.filter_map(|(&pid, proc)| match extract_args(proc.cmd()) { |
| 373 |
ProcessArgs::Args(args) => { |
| 374 |
let mut length_of_process_chain = usize::MAX; |
| 375 |
|
| 376 |
let mut sum_distance = |pid, distance| { |
| 377 |
if length_of_process_chain == usize::MAX { |
| 378 |
if let Some(distance_to_first_common_parent) = pid_distances.get(&pid) { |
| 379 |
length_of_process_chain = |
| 380 |
distance_to_first_common_parent + distance; |
| 381 |
} |
| 382 |
} |
| 383 |
}; |
| 384 |
iter_parents(self, pid.as_u32(), &mut sum_distance); |
| 385 |
|
| 386 |
if length_of_process_chain == usize::MAX { |
| 387 |
None |
| 388 |
} else { |
| 389 |
Some((length_of_process_chain, args)) |
| 390 |
} |
| 391 |
} |
| 392 |
_ => None, |
| 393 |
}) |
| 394 |
.min_by_key(|(distance, _)| *distance) |
| 395 |
.map(|(_, result)| result); |
| 396 |
|
| 397 |
cmdline_of_closest_matching_process |
| 398 |
} |
| 399 |
} |
| 400 |
|
| 401 |
impl ProcessInterface for ProcInfo { |
| 402 |
type Out = Process; |
| 403 |
|
| 404 |
fn my_pid(&self) -> DeltaPid { |
| 405 |
std::process::id() |
| 406 |
} |
| 407 |
fn refresh_process(&mut self, pid: DeltaPid) -> bool { |
| 408 |
self.info |
| 409 |
.refresh_process_specifics(Pid::from_u32(pid), ProcessRefreshKind::new()) |
| 410 |
} |
| 411 |
fn process(&self, pid: DeltaPid) -> Option<&Self::Out> { |
| 412 |
self.info.process(Pid::from_u32(pid)) |
| 413 |
} |
| 414 |
fn processes(&self) -> &HashMap<Pid, Self::Out> { |
| 415 |
self.info.processes() |
| 416 |
} |
| 417 |
fn refresh_processes(&mut self) { |
| 418 |
self.info |
| 419 |
.refresh_processes_specifics(ProcessRefreshKind::new()) |
| 420 |
} |
| 421 |
} |
| 422 |
|
| 423 |
fn calling_process_cmdline<P, F, T>(mut info: P, extract_args: F) -> Option<T> |
| 424 |
where |
| 425 |
P: ProcessInterface, |
| 426 |
F: Fn(&[String]) -> ProcessArgs<T>, |
| 427 |
{ |
| 428 |
#[cfg(test)] |
| 429 |
{ |
| 430 |
if let Some(args) = tests::FakeParentArgs::get() { |
| 431 |
match extract_args(&args) { |
| 432 |
ProcessArgs::Args(result) => return Some(result), |
| 433 |
_ => return None, |
| 434 |
} |
| 435 |
} |
| 436 |
} |
| 437 |
|
| 438 |
let my_pid = info.my_pid(); |
| 439 |
|
| 440 |
// 1) Try the parent process(es). If delta is set as the pager in git, then git is the parent process. |
| 441 |
// If delta is started by a script check the parent's parent as well. |
| 442 |
let mut current_pid = my_pid; |
| 443 |
'parent_iter: for depth in [1, 2, 3] { |
| 444 |
let parent = match info.parent_process(current_pid) { |
| 445 |
None => { |
| 446 |
break 'parent_iter; |
| 447 |
} |
| 448 |
Some(parent) => parent, |
| 449 |
}; |
| 450 |
let parent_pid = parent.pid(); |
| 451 |
|
| 452 |
match extract_args(parent.cmd()) { |
| 453 |
ProcessArgs::Args(result) => return Some(result), |
| 454 |
ProcessArgs::ArgError => return None, |
| 455 |
|
| 456 |
// 2) The 1st parent process was something else, this can happen if git output is piped into delta, e.g. |
| 457 |
// `git blame foo.txt | delta`. When the shell sets up the pipe it creates the two processes, the pids |
| 458 |
// are usually consecutive, so naively check if the process with `my_pid - 1` matches. |
| 459 |
ProcessArgs::OtherProcess if depth == 1 => { |
| 460 |
let sibling = info.naive_sibling_process(current_pid); |
| 461 |
if let Some(proc) = sibling { |
| 462 |
if let ProcessArgs::Args(result) = extract_args(proc.cmd()) { |
| 463 |
return Some(result); |
| 464 |
} |
| 465 |
} |
| 466 |
} |
| 467 |
// This check is not done for the parent's parent etc. |
| 468 |
ProcessArgs::OtherProcess => {} |
| 469 |
} |
| 470 |
current_pid = parent_pid; |
| 471 |
} |
| 472 |
|
| 473 |
/* |
| 474 |
3) Neither parent(s) nor the direct sibling were a match. |
| 475 |
The most likely case is that the input program of the pipe wrote all its data and exited before delta |
| 476 |
started, so no command line can be parsed. Same if the data was piped from an input file. |
| 477 |
|
| 478 |
There might also be intermediary scripts in between or piped input with a gap in pids or (rarely) |
| 479 |
randomized pids, so check processes for the closest match in the process tree. |
| 480 |
The size of this process tree can be reduced by only refreshing selected processes. |
| 481 |
|
| 482 |
100 /usr/bin/some-terminal-emulator |
| 483 |
124 \_ -shell |
| 484 |
301 | \_ /usr/bin/git blame src/main.rs |
| 485 |
302 | \_ wraps_delta.sh |
| 486 |
303 | \_ delta |
| 487 |
304 | \_ less --RAW-CONTROL-CHARS --quit-if-one-screen |
| 488 |
125 \_ -shell |
| 489 |
800 | \_ /usr/bin/git blame src/main.rs |
| 490 |
200 | \_ delta |
| 491 |
400 | \_ less --RAW-CONTROL-CHARS --quit-if-one-screen |
| 492 |
126 \_ -shell |
| 493 |
501 | \_ /bin/sh /wrapper/for/git blame src/main.rs |
| 494 |
555 | | \_ /usr/bin/git blame src/main.rs |
| 495 |
502 | \_ delta |
| 496 |
567 | \_ less --RAW-CONTROL-CHARS --quit-if-one-screen |
| 497 |
|
| 498 |
*/ |
| 499 |
|
| 500 |
// Also `add` because `A_has_pid101 | delta_has_pid102`, but if A is a wrapper which then calls |
| 501 |
// git (no `exec`), then the final pid of the git process might be 103 or greater. |
| 502 |
let pid_range = my_pid.saturating_sub(10)..my_pid.saturating_add(10); |
| 503 |
for p in pid_range { |
| 504 |
// Processes which were not refreshed do not exist for sysinfo, so by selectively |
| 505 |
// letting it know about processes the `find_sibling..` function will only |
| 506 |
// consider these. |
| 507 |
if info.process(p).is_none() { |
| 508 |
info.refresh_process(p); |
| 509 |
} |
| 510 |
} |
| 511 |
|
| 512 |
match info.find_sibling_in_refreshed_processes(my_pid, &extract_args) { |
| 513 |
None => { |
| 514 |
#[cfg(not(target_os = "linux"))] |
| 515 |
let full_scan = true; |
| 516 |
|
| 517 |
// The full scan is expensive on Linux and rarely successful, so disable it by default. |
| 518 |
#[cfg(target_os = "linux")] |
| 519 |
let full_scan = std::env::var("DELTA_CALLING_PROCESS_QUERY_ALL") |
| 520 |
.is_ok_and(|v| !["0", "false", "no"].iter().any(|&n| n == v)); |
| 521 |
|
| 522 |
if full_scan { |
| 523 |
info.refresh_processes(); |
| 524 |
info.find_sibling_in_refreshed_processes(my_pid, &extract_args) |
| 525 |
} else { |
| 526 |
None |
| 527 |
} |
| 528 |
} |
| 529 |
some => some, |
| 530 |
} |
| 531 |
} |
| 532 |
|
| 533 |
// Walk up the process tree, calling `f` with the pid and the distance to `starting_pid`. |
| 534 |
// Prerequisite: `info.refresh_processes()` has been called. |
| 535 |
fn iter_parents<P, F>(info: &P, starting_pid: DeltaPid, f: F) |
| 536 |
where |
| 537 |
P: ProcessInterface, |
| 538 |
F: FnMut(DeltaPid, usize), |
| 539 |
{ |
| 540 |
fn inner_iter_parents<P, F>(info: &P, pid: DeltaPid, mut f: F, distance: usize) |
| 541 |
where |
| 542 |
P: ProcessInterface, |
| 543 |
F: FnMut(u32, usize), |
| 544 |
{ |
| 545 |
// Probably bad input, not a tree: |
| 546 |
if distance > 2000 { |
| 547 |
return; |
| 548 |
} |
| 549 |
if let Some(proc) = info.process(pid) { |
| 550 |
if let Some(pid) = proc.parent() { |
| 551 |
f(pid, distance); |
| 552 |
inner_iter_parents(info, pid, f, distance + 1) |
| 553 |
} |
| 554 |
} |
| 555 |
} |
| 556 |
inner_iter_parents(info, starting_pid, f, 1) |
| 557 |
} |
| 558 |
|
| 559 |
#[cfg(test)] |
| 560 |
pub mod tests { |
| 561 |
|
| 562 |
use super::*; |
| 563 |
|
| 564 |
use itertools::Itertools; |
| 565 |
use std::cell::RefCell; |
| 566 |
use std::rc::Rc; |
| 567 |
|
| 568 |
thread_local! { |
| 569 |
static FAKE_ARGS: RefCell<TlsState<Vec<String>>> = const { RefCell::new(TlsState::None) }; |
| 570 |
} |
| 571 |
|
| 572 |
#[derive(Debug, PartialEq)] |
| 573 |
enum TlsState<T> { |
| 574 |
Once(T), |
| 575 |
Scope(T), |
| 576 |
With(usize, Rc<Vec<T>>), |
| 577 |
None, |
| 578 |
Invalid, |
| 579 |
ErrorAlreadyHandled, |
| 580 |
} |
| 581 |
|
| 582 |
// When calling `FakeParentArgs::get()`, it can return `Some(values)` which were set earlier |
| 583 |
// during in the #[test]. Otherwise returns None. |
| 584 |
// This value can be valid once: `FakeParentArgs::once(val)`, for the entire scope: |
| 585 |
// `FakeParentArgs::for_scope(val)`, or can be different values every time `get()` is called: |
| 586 |
// `FakeParentArgs::with([val1, val2, val3])`. |
| 587 |
// It is an error if `once` or `with` values remain unused, or are overused. |
| 588 |
// Note: The values are stored per-thread, so the expectation is that no thread boundaries are |
| 589 |
// crossed. |
| 590 |
pub struct FakeParentArgs {} |
| 591 |
impl FakeParentArgs { |
| 592 |
pub fn once(args: &str) -> Self { |
| 593 |
Self::new(args, TlsState::Once, "once") |
| 594 |
} |
| 595 |
pub fn for_scope(args: &str) -> Self { |
| 596 |
Self::new(args, TlsState::Scope, "for_scope") |
| 597 |
} |
| 598 |
fn new<F>(args: &str, initial: F, from_: &str) -> Self |
| 599 |
where |
| 600 |
F: Fn(Vec<String>) -> TlsState<Vec<String>>, |
| 601 |
{ |
| 602 |
let string_vec = args.split(' ').map(str::to_owned).collect(); |
| 603 |
if FAKE_ARGS.with(|a| a.replace(initial(string_vec))) != TlsState::None { |
| 604 |
Self::error(from_); |
| 605 |
} |
| 606 |
FakeParentArgs {} |
| 607 |
} |
| 608 |
pub fn with(args: &[&str]) -> Self { |
| 609 |
let with = TlsState::With( |
| 610 |
0, |
| 611 |
Rc::new( |
| 612 |
args.iter() |
| 613 |
.map(|a| a.split(' ').map(str::to_owned).collect()) |
| 614 |
.collect(), |
| 615 |
), |
| 616 |
); |
| 617 |
if FAKE_ARGS.with(|a| a.replace(with)) != TlsState::None || args.is_empty() { |
| 618 |
Self::error("with creation"); |
| 619 |
} |
| 620 |
FakeParentArgs {} |
| 621 |
} |
| 622 |
pub fn get() -> Option<Vec<String>> { |
| 623 |
FAKE_ARGS.with(|a| { |
| 624 |
let old_value = a.replace_with(|old_value| match old_value { |
| 625 |
TlsState::Once(_) => TlsState::Invalid, |
| 626 |
TlsState::Scope(args) => TlsState::Scope(args.clone()), |
| 627 |
TlsState::With(n, args) => TlsState::With(*n + 1, Rc::clone(args)), |
| 628 |
TlsState::None => TlsState::None, |
| 629 |
TlsState::Invalid => TlsState::Invalid, |
| 630 |
TlsState::ErrorAlreadyHandled => TlsState::ErrorAlreadyHandled, |
| 631 |
}); |
| 632 |
|
| 633 |
match old_value { |
| 634 |
TlsState::Once(args) | TlsState::Scope(args) => Some(args), |
| 635 |
TlsState::With(n, args) if n < args.len() => Some(args[n].clone()), |
| 636 |
TlsState::None => None, |
| 637 |
TlsState::Invalid | TlsState::With(_, _) | TlsState::ErrorAlreadyHandled => { |
| 638 |
Self::error("get"); |
| 639 |
None |
| 640 |
} |
| 641 |
} |
| 642 |
}) |
| 643 |
} |
| 644 |
pub fn are_set() -> bool { |
| 645 |
FAKE_ARGS.with(|a| { |
| 646 |
*a.borrow() != TlsState::None && *a.borrow() != TlsState::ErrorAlreadyHandled |
| 647 |
}) |
| 648 |
} |
| 649 |
fn error(where_: &str) { |
| 650 |
FAKE_ARGS.with(|a| { |
| 651 |
let old_value = a.replace(TlsState::ErrorAlreadyHandled); |
| 652 |
|
| 653 |
match old_value { |
| 654 |
TlsState::ErrorAlreadyHandled => (), |
| 655 |
_ => { |
| 656 |
panic!( |
| 657 |
"test logic error (in {}): wrong FakeParentArgs scope?", |
| 658 |
where_ |
| 659 |
); |
| 660 |
} |
| 661 |
} |
| 662 |
}); |
| 663 |
} |
| 664 |
} |
| 665 |
impl Drop for FakeParentArgs { |
| 666 |
fn drop(&mut self) { |
| 667 |
// Clears an Invalid state and tests if a Once or With value has been used. |
| 668 |
FAKE_ARGS.with(|a| { |
| 669 |
let old_value = a.replace(TlsState::None); |
| 670 |
match old_value { |
| 671 |
TlsState::With(n, args) => { |
| 672 |
if n != args.len() { |
| 673 |
Self::error("drop with") |
| 674 |
} |
| 675 |
} |
| 676 |
TlsState::Once(_) | TlsState::None => Self::error("drop"), |
| 677 |
TlsState::Scope(_) | TlsState::Invalid | TlsState::ErrorAlreadyHandled => {} |
| 678 |
} |
| 679 |
}); |
| 680 |
} |
| 681 |
} |
| 682 |
|
| 683 |
#[derive(Debug, Default)] |
| 684 |
struct FakeProc { |
| 685 |
#[allow(dead_code)] |
| 686 |
pid: DeltaPid, |
| 687 |
start_time: u64, |
| 688 |
cmd: Vec<String>, |
| 689 |
ppid: Option<DeltaPid>, |
| 690 |
} |
| 691 |
impl FakeProc { |
| 692 |
fn new(pid: DeltaPid, start_time: u64, cmd: Vec<String>, ppid: Option<DeltaPid>) -> Self { |
| 693 |
FakeProc { |
| 694 |
pid, |
| 695 |
start_time, |
| 696 |
cmd, |
| 697 |
ppid, |
| 698 |
} |
| 699 |
} |
| 700 |
} |
| 701 |
|
| 702 |
impl ProcActions for FakeProc { |
| 703 |
fn cmd(&self) -> &[String] { |
| 704 |
&self.cmd |
| 705 |
} |
| 706 |
fn parent(&self) -> Option<DeltaPid> { |
| 707 |
self.ppid |
| 708 |
} |
| 709 |
fn pid(&self) -> DeltaPid { |
| 710 |
self.pid |
| 711 |
} |
| 712 |
fn start_time(&self) -> u64 { |
| 713 |
self.start_time |
| 714 |
} |
| 715 |
} |
| 716 |
|
| 717 |
#[derive(Debug, Default)] |
| 718 |
struct MockProcInfo { |
| 719 |
delta_pid: DeltaPid, |
| 720 |
info: HashMap<Pid, FakeProc>, |
| 721 |
} |
| 722 |
impl MockProcInfo { |
| 723 |
fn with(processes: &[(DeltaPid, u64, &str, Option<DeltaPid>)]) -> Self { |
| 724 |
MockProcInfo { |
| 725 |
delta_pid: processes.last().map(|p| p.0).unwrap_or(1), |
| 726 |
info: processes |
| 727 |
.iter() |
| 728 |
.map(|(pid, start_time, cmd, ppid)| { |
| 729 |
let cmd_vec = cmd.split(' ').map(str::to_owned).collect(); |
| 730 |
( |
| 731 |
Pid::from_u32(*pid), |
| 732 |
FakeProc::new(*pid, *start_time, cmd_vec, *ppid), |
| 733 |
) |
| 734 |
}) |
| 735 |
.collect(), |
| 736 |
} |
| 737 |
} |
| 738 |
} |
| 739 |
|
| 740 |
impl ProcessInterface for MockProcInfo { |
| 741 |
type Out = FakeProc; |
| 742 |
|
| 743 |
fn my_pid(&self) -> DeltaPid { |
| 744 |
self.delta_pid |
| 745 |
} |
| 746 |
fn process(&self, pid: DeltaPid) -> Option<&Self::Out> { |
| 747 |
self.info.get(&Pid::from_u32(pid)) |
| 748 |
} |
| 749 |
fn processes(&self) -> &HashMap<Pid, Self::Out> { |
| 750 |
&self.info |
| 751 |
} |
| 752 |
fn refresh_processes(&mut self) {} |
| 753 |
fn refresh_process(&mut self, _pid: DeltaPid) -> bool { |
| 754 |
true |
| 755 |
} |
| 756 |
} |
| 757 |
|
| 758 |
fn set(arg1: &[&str]) -> HashSet<String> { |
| 759 |
arg1.iter().map(|&s| s.to_owned()).collect() |
| 760 |
} |
| 761 |
|
| 762 |
#[test] |
| 763 |
fn test_process_testing() { |
| 764 |
{ |
| 765 |
let _args = FakeParentArgs::once("git blame hello"); |
| 766 |
assert_eq!( |
| 767 |
calling_process_cmdline(ProcInfo::new(), describe_calling_process), |
| 768 |
Some(CallingProcess::GitBlame(CommandLine { |
| 769 |
long_options: [].into(), |
| 770 |
short_options: [].into(), |
| 771 |
last_arg: Some("hello".into()) |
| 772 |
})) |
| 773 |
); |
| 774 |
} |
| 775 |
{ |
| 776 |
let _args = FakeParentArgs::once("git blame world.txt"); |
| 777 |
assert_eq!( |
| 778 |
calling_process_cmdline(ProcInfo::new(), describe_calling_process), |
| 779 |
Some(CallingProcess::GitBlame(CommandLine { |
| 780 |
long_options: [].into(), |
| 781 |
short_options: [].into(), |
| 782 |
last_arg: Some("world.txt".into()) |
| 783 |
})) |
| 784 |
); |
| 785 |
} |
| 786 |
{ |
| 787 |
let _args = FakeParentArgs::for_scope("git blame hello world.txt"); |
| 788 |
assert_eq!( |
| 789 |
calling_process_cmdline(ProcInfo::new(), describe_calling_process), |
| 790 |
Some(CallingProcess::GitBlame(CommandLine { |
| 791 |
long_options: [].into(), |
| 792 |
short_options: [].into(), |
| 793 |
last_arg: Some("world.txt".into()) |
| 794 |
})) |
| 795 |
); |
| 796 |
} |
| 797 |
} |
| 798 |
|
| 799 |
#[test] |
| 800 |
#[should_panic(expected = "test logic error (in get): wrong FakeParentArgs scope?")] |
| 801 |
fn test_process_testing_assert() { |
| 802 |
let _args = FakeParentArgs::once("git blame do.not.panic"); |
| 803 |
assert_eq!( |
| 804 |
calling_process_cmdline(ProcInfo::new(), describe_calling_process), |
| 805 |
Some(CallingProcess::GitBlame(CommandLine { |
| 806 |
long_options: [].into(), |
| 807 |
short_options: [].into(), |
| 808 |
last_arg: Some("do.not.panic".into()) |
| 809 |
})) |
| 810 |
); |
| 811 |
calling_process_cmdline(ProcInfo::new(), describe_calling_process); |
| 812 |
} |
| 813 |
|
| 814 |
#[test] |
| 815 |
#[should_panic(expected = "test logic error (in drop): wrong FakeParentArgs scope?")] |
| 816 |
fn test_process_testing_assert_once_never_used() { |
| 817 |
let _args = FakeParentArgs::once("never used"); |
| 818 |
} |
| 819 |
|
| 820 |
#[test] |
| 821 |
#[should_panic(expected = "test logic error (in once): wrong FakeParentArgs scope?")] |
| 822 |
fn test_process_testing_assert_for_scope_never_used() { |
| 823 |
let _args = FakeParentArgs::for_scope(&"never used"); |
| 824 |
let _args = FakeParentArgs::once(&"never used"); |
| 825 |
} |
| 826 |
|
| 827 |
#[test] |
| 828 |
#[should_panic(expected = "test logic error (in for_scope): wrong FakeParentArgs scope?")] |
| 829 |
fn test_process_testing_assert_once_never_used2() { |
| 830 |
let _args = FakeParentArgs::once(&"never used"); |
| 831 |
let _args = FakeParentArgs::for_scope(&"never used"); |
| 832 |
} |
| 833 |
|
| 834 |
#[test] |
| 835 |
fn test_process_testing_scope_can_remain_unused() { |
| 836 |
let _args = FakeParentArgs::for_scope("never used"); |
| 837 |
} |
| 838 |
|
| 839 |
#[test] |
| 840 |
fn test_process_testing_n_times() { |
| 841 |
let _args = FakeParentArgs::with(&["git blame once", "git blame twice"]); |
| 842 |
assert_eq!( |
| 843 |
calling_process_cmdline(ProcInfo::new(), describe_calling_process), |
| 844 |
Some(CallingProcess::GitBlame(CommandLine { |
| 845 |
long_options: [].into(), |
| 846 |
short_options: [].into(), |
| 847 |
last_arg: Some("once".into()) |
| 848 |
})) |
| 849 |
); |
| 850 |
|
| 851 |
assert_eq!( |
| 852 |
calling_process_cmdline(ProcInfo::new(), describe_calling_process), |
| 853 |
Some(CallingProcess::GitBlame(CommandLine { |
| 854 |
long_options: [].into(), |
| 855 |
short_options: [].into(), |
| 856 |
last_arg: Some("twice".into()) |
| 857 |
})) |
| 858 |
); |
| 859 |
} |
| 860 |
|
| 861 |
#[test] |
| 862 |
#[should_panic(expected = "test logic error (in drop with): wrong FakeParentArgs scope?")] |
| 863 |
fn test_process_testing_n_times_unused() { |
| 864 |
let _args = FakeParentArgs::with(&["git blame once", "git blame twice"]); |
| 865 |
} |
| 866 |
|
| 867 |
#[test] |
| 868 |
#[should_panic(expected = "test logic error (in drop with): wrong FakeParentArgs scope?")] |
| 869 |
fn test_process_testing_n_times_underused() { |
| 870 |
let _args = FakeParentArgs::with(&["git blame once", "git blame twice"]); |
| 871 |
assert_eq!( |
| 872 |
calling_process_cmdline(ProcInfo::new(), describe_calling_process), |
| 873 |
Some(CallingProcess::GitBlame(CommandLine { |
| 874 |
long_options: [].into(), |
| 875 |
short_options: [].into(), |
| 876 |
last_arg: Some("once".into()) |
| 877 |
})) |
| 878 |
); |
| 879 |
} |
| 880 |
|
| 881 |
#[test] |
| 882 |
#[should_panic(expected = "test logic error (in get): wrong FakeParentArgs scope?")] |
| 883 |
fn test_process_testing_n_times_overused() { |
| 884 |
let _args = FakeParentArgs::with(&["git blame once"]); |
| 885 |
assert_eq!( |
| 886 |
calling_process_cmdline(ProcInfo::new(), describe_calling_process), |
| 887 |
Some(CallingProcess::GitBlame(CommandLine { |
| 888 |
long_options: [].into(), |
| 889 |
short_options: [].into(), |
| 890 |
last_arg: Some("once".into()) |
| 891 |
})) |
| 892 |
); |
| 893 |
calling_process_cmdline(ProcInfo::new(), describe_calling_process); |
| 894 |
} |
| 895 |
|
| 896 |
#[test] |
| 897 |
fn test_describe_calling_process_blame() { |
| 898 |
let no_processes = MockProcInfo::with(&[]); |
| 899 |
assert_eq!( |
| 900 |
calling_process_cmdline(no_processes, describe_calling_process), |
| 901 |
None |
| 902 |
); |
| 903 |
|
| 904 |
let two_trees = MockProcInfo::with(&[ |
| 905 |
(2, 100, "-shell", None), |
| 906 |
(3, 100, "git blame src/main.rs", Some(2)), |
| 907 |
(4, 100, "call_delta.sh", None), |
| 908 |
(5, 100, "delta", Some(4)), |
| 909 |
]); |
| 910 |
assert_eq!( |
| 911 |
calling_process_cmdline(two_trees, describe_calling_process), |
| 912 |
None |
| 913 |
); |
| 914 |
|
| 915 |
let no_options_command_line = CommandLine { |
| 916 |
long_options: [].into(), |
| 917 |
short_options: [].into(), |
| 918 |
last_arg: Some("hello.txt".to_string()), |
| 919 |
}; |
| 920 |
let parent = MockProcInfo::with(&[ |
| 921 |
(2, 100, "-shell", None), |
| 922 |
(3, 100, "git blame hello.txt", Some(2)), |
| 923 |
(4, 100, "delta", Some(3)), |
| 924 |
]); |
| 925 |
assert_eq!( |
| 926 |
calling_process_cmdline(parent, describe_calling_process), |
| 927 |
Some(CallingProcess::GitBlame(no_options_command_line.clone())) |
| 928 |
); |
| 929 |
|
| 930 |
let parent = MockProcInfo::with(&[ |
| 931 |
(2, 100, "-shell", None), |
| 932 |
(3, 100, "git blame -- hello.txt", Some(2)), |
| 933 |
(4, 100, "delta", Some(3)), |
| 934 |
]); |
| 935 |
assert_eq!( |
| 936 |
calling_process_cmdline(parent, describe_calling_process), |
| 937 |
Some(CallingProcess::GitBlame(no_options_command_line.clone())) |
| 938 |
); |
| 939 |
|
| 940 |
let parent = MockProcInfo::with(&[ |
| 941 |
(2, 100, "-shell", None), |
| 942 |
(3, 100, "git blame -- --not.an.argument", Some(2)), |
| 943 |
(4, 100, "delta", Some(3)), |
| 944 |
]); |
| 945 |
assert_eq!( |
| 946 |
calling_process_cmdline(parent, describe_calling_process), |
| 947 |
Some(CallingProcess::GitBlame(CommandLine { |
| 948 |
long_options: [].into(), |
| 949 |
short_options: [].into(), |
| 950 |
last_arg: Some("--not.an.argument".to_string()), |
| 951 |
})) |
| 952 |
); |
| 953 |
|
| 954 |
let parent = MockProcInfo::with(&[ |
| 955 |
(2, 100, "-shell", None), |
| 956 |
(3, 100, "git blame --help.txt", Some(2)), |
| 957 |
(4, 100, "delta", Some(3)), |
| 958 |
]); |
| 959 |
assert_eq!( |
| 960 |
calling_process_cmdline(parent, describe_calling_process), |
| 961 |
Some(CallingProcess::GitBlame(CommandLine { |
| 962 |
long_options: ["--help.txt".into()].into(), |
| 963 |
short_options: [].into(), |
| 964 |
last_arg: None, |
| 965 |
})) |
| 966 |
); |
| 967 |
|
| 968 |
let parent = MockProcInfo::with(&[ |
| 969 |
(2, 100, "-shell", None), |
| 970 |
(3, 100, "git blame --", Some(2)), |
| 971 |
(4, 100, "delta", Some(3)), |
| 972 |
]); |
| 973 |
assert_eq!( |
| 974 |
calling_process_cmdline(parent, describe_calling_process), |
| 975 |
Some(CallingProcess::GitBlame(CommandLine { |
| 976 |
long_options: [].into(), |
| 977 |
short_options: [].into(), |
| 978 |
last_arg: None, |
| 979 |
})) |
| 980 |
); |
| 981 |
|
| 982 |
let parent = MockProcInfo::with(&[ |
| 983 |
(2, 100, "-shell", None), |
| 984 |
(3, 100, "Git.exe blame hello.txt", Some(2)), |
| 985 |
(4, 100, "delta", Some(3)), |
| 986 |
]); |
| 987 |
assert_eq!( |
| 988 |
calling_process_cmdline(parent, describe_calling_process), |
| 989 |
Some(CallingProcess::GitBlame(no_options_command_line.clone())) |
| 990 |
); |
| 991 |
|
| 992 |
let git_blame_command = |
| 993 |
"git -c a=b blame -fnb --incremental -t --color-by-age -M --since=3.weeks --contents annotation.txt -C -C2 hello.txt"; |
| 994 |
|
| 995 |
// here -C2 is parsed as -C and -2. It doesn't really matters because we only use last_arg from options |
| 996 |
// to determine the file type. |
| 997 |
let expected_result = Some(CallingProcess::GitBlame(CommandLine { |
| 998 |
long_options: set(&["--incremental", "--color-by-age", "--since", "--contents"]), |
| 999 |
short_options: set(&["-f", "-n", "-b", "-t", "-M", "-C", "-2"]), |
| 1000 |
last_arg: Some("hello.txt".to_string()), |
| 1001 |
})); |
| 1002 |
|
| 1003 |
let parent = MockProcInfo::with(&[ |
| 1004 |
(2, 100, "-shell", None), |
| 1005 |
(3, 100, git_blame_command, Some(2)), |
| 1006 |
(4, 100, "delta", Some(3)), |
| 1007 |
]); |
| 1008 |
assert_eq!( |
| 1009 |
calling_process_cmdline(parent, describe_calling_process), |
| 1010 |
expected_result |
| 1011 |
); |
| 1012 |
|
| 1013 |
let grandparent = MockProcInfo::with(&[ |
| 1014 |
(2, 100, "-shell", None), |
| 1015 |
(3, 100, git_blame_command, Some(2)), |
| 1016 |
(4, 100, "call_delta.sh", Some(3)), |
| 1017 |
(5, 100, "delta", Some(4)), |
| 1018 |
]); |
| 1019 |
assert_eq!( |
| 1020 |
calling_process_cmdline(grandparent, describe_calling_process), |
| 1021 |
expected_result |
| 1022 |
); |
| 1023 |
|
| 1024 |
let sibling = MockProcInfo::with(&[ |
| 1025 |
(2, 100, "-xterm", None), |
| 1026 |
(3, 100, "-shell", Some(2)), |
| 1027 |
(4, 100, "git blame src/main.rs", Some(3)), |
| 1028 |
(5, 100, "delta", Some(3)), |
| 1029 |
]); |
| 1030 |
assert_eq!( |
| 1031 |
calling_process_cmdline(sibling, describe_calling_process), |
| 1032 |
Some(CallingProcess::GitBlame(CommandLine { |
| 1033 |
long_options: [].into(), |
| 1034 |
short_options: [].into(), |
| 1035 |
last_arg: Some("src/main.rs".into()) |
| 1036 |
})) |
| 1037 |
); |
| 1038 |
|
| 1039 |
let indirect_sibling = MockProcInfo::with(&[ |
| 1040 |
(2, 100, "-xterm", None), |
| 1041 |
(3, 100, "-shell", Some(2)), |
| 1042 |
(4, 100, "Git.exe blame --correct src/main.abc", Some(3)), |
| 1043 |
( |
| 1044 |
10, |
| 1045 |
100, |
| 1046 |
"Git.exe blame --ignored-child src/main.def", |
| 1047 |
Some(4), |
| 1048 |
), |
| 1049 |
(5, 100, "delta.sh", Some(3)), |
| 1050 |
(20, 100, "delta", Some(5)), |
| 1051 |
]); |
| 1052 |
assert_eq!( |
| 1053 |
calling_process_cmdline(indirect_sibling, describe_calling_process), |
| 1054 |
Some(CallingProcess::GitBlame(CommandLine { |
| 1055 |
long_options: set(&["--correct"]), |
| 1056 |
short_options: [].into(), |
| 1057 |
last_arg: Some("src/main.abc".into()) |
| 1058 |
})) |
| 1059 |
); |
| 1060 |
|
| 1061 |
let indirect_sibling2 = MockProcInfo::with(&[ |
| 1062 |
(2, 100, "-xterm", None), |
| 1063 |
(3, 100, "-shell", Some(2)), |
| 1064 |
(4, 100, "git wrap src/main.abc", Some(3)), |
| 1065 |
(10, 100, "git blame src/main.def", Some(4)), |
| 1066 |
(5, 100, "delta.sh", Some(3)), |
| 1067 |
(20, 100, "delta", Some(5)), |
| 1068 |
]); |
| 1069 |
assert_eq!( |
| 1070 |
calling_process_cmdline(indirect_sibling2, describe_calling_process), |
| 1071 |
Some(CallingProcess::GitBlame(CommandLine { |
| 1072 |
long_options: [].into(), |
| 1073 |
short_options: [].into(), |
| 1074 |
last_arg: Some("src/main.def".into()) |
| 1075 |
})) |
| 1076 |
); |
| 1077 |
|
| 1078 |
// 3 blame processes, 2 with matching start times, pick the one with lower |
| 1079 |
// distance but larger start time difference. |
| 1080 |
let indirect_sibling_start_times = MockProcInfo::with(&[ |
| 1081 |
(2, 100, "-xterm", None), |
| 1082 |
(3, 100, "-shell", Some(2)), |
| 1083 |
(4, 109, "git wrap src/main.abc", Some(3)), |
| 1084 |
(10, 109, "git blame src/main.def", Some(4)), |
| 1085 |
(20, 100, "git wrap1 src/main.abc", Some(3)), |
| 1086 |
(21, 100, "git wrap2 src/main.def", Some(20)), |
| 1087 |
(22, 101, "git blame src/main.not", Some(21)), |
| 1088 |
(23, 102, "git blame src/main.this", Some(20)), |
| 1089 |
(5, 100, "delta.sh", Some(3)), |
| 1090 |
(20, 100, "delta", Some(5)), |
| 1091 |
]); |
| 1092 |
assert_eq!( |
| 1093 |
calling_process_cmdline(indirect_sibling_start_times, describe_calling_process), |
| 1094 |
Some(CallingProcess::GitBlame(CommandLine { |
| 1095 |
long_options: [].into(), |
| 1096 |
short_options: [].into(), |
| 1097 |
last_arg: Some("src/main.this".into()) |
| 1098 |
})) |
| 1099 |
); |
| 1100 |
} |
| 1101 |
|
| 1102 |
#[test] |
| 1103 |
fn test_describe_calling_process_grep() { |
| 1104 |
let no_processes = MockProcInfo::with(&[]); |
| 1105 |
assert_eq!( |
| 1106 |
calling_process_cmdline(no_processes, describe_calling_process), |
| 1107 |
None |
| 1108 |
); |
| 1109 |
|
| 1110 |
let empty_command_line = CommandLine { |
| 1111 |
long_options: [].into(), |
| 1112 |
short_options: [].into(), |
| 1113 |
last_arg: Some("hello.txt".to_string()), |
| 1114 |
}; |
| 1115 |
let parent = MockProcInfo::with(&[ |
| 1116 |
(2, 100, "-shell", None), |
| 1117 |
(3, 100, "git grep pattern hello.txt", Some(2)), |
| 1118 |
(4, 100, "delta", Some(3)), |
| 1119 |
]); |
| 1120 |
assert_eq!( |
| 1121 |
calling_process_cmdline(parent, describe_calling_process), |
| 1122 |
Some(CallingProcess::GitGrep(empty_command_line.clone())) |
| 1123 |
); |
| 1124 |
|
| 1125 |
let parent = MockProcInfo::with(&[ |
| 1126 |
(2, 100, "-shell", None), |
| 1127 |
(3, 100, "Git.exe grep pattern hello.txt", Some(2)), |
| 1128 |
(4, 100, "delta", Some(3)), |
| 1129 |
]); |
| 1130 |
assert_eq!( |
| 1131 |
calling_process_cmdline(parent, describe_calling_process), |
| 1132 |
Some(CallingProcess::GitGrep(empty_command_line)) |
| 1133 |
); |
| 1134 |
|
| 1135 |
for grep_command in &[ |
| 1136 |
"/usr/local/bin/rg pattern hello.txt", |
| 1137 |
"RG.exe pattern hello.txt", |
| 1138 |
"/usr/local/bin/ack pattern hello.txt", |
| 1139 |
"ack.exe pattern hello.txt", |
| 1140 |
] { |
| 1141 |
let parent = MockProcInfo::with(&[ |
| 1142 |
(2, 100, "-shell", None), |
| 1143 |
(3, 100, grep_command, Some(2)), |
| 1144 |
(4, 100, "delta", Some(3)), |
| 1145 |
]); |
| 1146 |
assert_eq!( |
| 1147 |
calling_process_cmdline(parent, describe_calling_process), |
| 1148 |
Some(CallingProcess::OtherGrep) |
| 1149 |
); |
| 1150 |
} |
| 1151 |
|
| 1152 |
let git_grep_command = |
| 1153 |
"git grep -ab --function-context -n --show-function -W --foo=val pattern hello.txt"; |
| 1154 |
|
| 1155 |
let expected_result = Some(CallingProcess::GitGrep(CommandLine { |
| 1156 |
long_options: set(&["--function-context", "--show-function", "--foo"]), |
| 1157 |
short_options: set(&["-a", "-b", "-n", "-W"]), |
| 1158 |
last_arg: Some("hello.txt".to_string()), |
| 1159 |
})); |
| 1160 |
|
| 1161 |
let parent = MockProcInfo::with(&[ |
| 1162 |
(2, 100, "-shell", None), |
| 1163 |
(3, 100, git_grep_command, Some(2)), |
| 1164 |
(4, 100, "delta", Some(3)), |
| 1165 |
]); |
| 1166 |
assert_eq!( |
| 1167 |
calling_process_cmdline(parent, describe_calling_process), |
| 1168 |
expected_result |
| 1169 |
); |
| 1170 |
|
| 1171 |
let grandparent = MockProcInfo::with(&[ |
| 1172 |
(2, 100, "-shell", None), |
| 1173 |
(3, 100, git_grep_command, Some(2)), |
| 1174 |
(4, 100, "call_delta.sh", Some(3)), |
| 1175 |
(5, 100, "delta", Some(4)), |
| 1176 |
]); |
| 1177 |
assert_eq!( |
| 1178 |
calling_process_cmdline(grandparent, describe_calling_process), |
| 1179 |
expected_result |
| 1180 |
); |
| 1181 |
} |
| 1182 |
|
| 1183 |
#[test] |
| 1184 |
fn test_describe_calling_process_git_show() { |
| 1185 |
for (command, expected_extension) in [ |
| 1186 |
( |
| 1187 |
"/usr/local/bin/git show --abbrev-commit -w 775c3b84:./src/hello.rs", |
| 1188 |
"hello.rs", |
| 1189 |
), |
| 1190 |
( |
| 1191 |
"/usr/local/bin/git show --abbrev-commit -w HEAD~1:Makefile", |
| 1192 |
"Makefile", |
| 1193 |
), |
| 1194 |
( |
| 1195 |
"git -c x.y=z show --abbrev-commit -w 775c3b84:./src/hello.bye.R", |
| 1196 |
"hello.bye.R", |
| 1197 |
), |
| 1198 |
] { |
| 1199 |
let parent = MockProcInfo::with(&[ |
| 1200 |
(2, 100, "-shell", None), |
| 1201 |
(3, 100, command, Some(2)), |
| 1202 |
(4, 100, "delta", Some(3)), |
| 1203 |
]); |
| 1204 |
if let Some(CallingProcess::GitShow(cmd_line, filename)) = |
| 1205 |
calling_process_cmdline(parent, describe_calling_process) |
| 1206 |
{ |
| 1207 |
assert_eq!(cmd_line.long_options, set(&["--abbrev-commit"])); |
| 1208 |
assert_eq!(cmd_line.short_options, set(&["-w"])); |
| 1209 |
assert_eq!(filename, Some(expected_extension.to_string())); |
| 1210 |
} else { |
| 1211 |
unreachable!(); |
| 1212 |
} |
| 1213 |
} |
| 1214 |
} |
| 1215 |
|
| 1216 |
#[test] |
| 1217 |
fn test_process_calling_cmdline() { |
| 1218 |
// GitHub runs CI tests for arm under qemu where sysinfo can not find the parent process. |
| 1219 |
if std::env::vars().any(|(key, _)| key == "CROSS_RUNNER" || key == "QEMU_LD_PREFIX") { |
| 1220 |
return; |
| 1221 |
} |
| 1222 |
|
| 1223 |
let mut info = ProcInfo::new(); |
| 1224 |
info.refresh_processes(); |
| 1225 |
let mut ppid_distance = Vec::new(); |
| 1226 |
|
| 1227 |
iter_parents(&info, std::process::id(), |pid, distance| { |
| 1228 |
ppid_distance.push(pid as i32); |
| 1229 |
ppid_distance.push(distance as i32) |
| 1230 |
}); |
| 1231 |
|
| 1232 |
assert!(ppid_distance[1] == 1); |
| 1233 |
|
| 1234 |
fn find_calling_process(args: &[String], want: &[&str]) -> ProcessArgs<()> { |
| 1235 |
if args.iter().any(|have| want.iter().any(|want| want == have)) { |
| 1236 |
ProcessArgs::Args(()) |
| 1237 |
} else { |
| 1238 |
ProcessArgs::ArgError |
| 1239 |
} |
| 1240 |
} |
| 1241 |
|
| 1242 |
// Tests that caller is something like "cargo test" or "cargo tarpaulin" |
| 1243 |
let find_test = |args: &[String]| find_calling_process(args, &["t", "test", "tarpaulin"]); |
| 1244 |
assert_eq!(calling_process_cmdline(info, find_test), Some(())); |
| 1245 |
|
| 1246 |
let nonsense = ppid_distance |
| 1247 |
.iter() |
| 1248 |
.map(|i| i.to_string()) |
| 1249 |
.join("Y40ii4RihK6lHiK4BDsGSx"); |
| 1250 |
|
| 1251 |
let find_nothing = |args: &[String]| find_calling_process(args, &[&nonsense]); |
| 1252 |
assert_eq!(calling_process_cmdline(ProcInfo::new(), find_nothing), None); |
| 1253 |
} |
| 1254 |
} |