Debian Codegraph @

src/utils/process.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
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, Process, ProcessRefreshKind, ProcessesToUpdate, UpdateKind};
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) -> Vec<String>;
283 fn parent(&self) -> Option<DeltaPid>;
284 fn pid(&self) -> DeltaPid;
285 fn start_time(&self) -> u64;
286 }
287
•288 impl ProcActions for Process {
289 fn cmd(&self) -> Vec<String> {
290 Process::cmd(self)
291 .iter()
292 .map(|arg| arg.to_string_lossy().into_owned())
293 .collect()
294 }
295 fn parent(&self) -> Option<DeltaPid> {
•296 Process::parent(self).map(|p| p.as_u32())
297 }
298 fn pid(&self) -> DeltaPid {
•299 Process::pid(self).as_u32()
300 }
301 fn start_time(&self) -> u64 {
•302 Process::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.refresh_processes_specifics(
409 ProcessesToUpdate::Some(&[Pid::from_u32(pid)]),
410 true,
411 ProcessRefreshKind::nothing().with_cmd(UpdateKind::Always),
412 ) > 0
413 }
414 fn process(&self, pid: DeltaPid) -> Option<&Self::Out> {
415 self.info.process(Pid::from_u32(pid))
416 }
417 fn processes(&self) -> &HashMap<Pid, Self::Out> {
418 self.info.processes()
419 }
420 fn refresh_processes(&mut self) {
•421 self.info.refresh_processes_specifics(
422 ProcessesToUpdate::All,
423 true,
424 ProcessRefreshKind::nothing().with_cmd(UpdateKind::Always),
425 );
426 }
427 }
428
429 fn calling_process_cmdline<P, F, T>(mut info: P, extract_args: F) -> Option<T>
430 where
431 P: ProcessInterface,
432 F: Fn(&[String]) -> ProcessArgs<T>,
433 {
434 #[cfg(test)]
435 {
436 if let Some(args) = tests::FakeParentArgs::get() {
437 match extract_args(&args) {
438 ProcessArgs::Args(result) => return Some(result),
439 _ => return None,
440 }
441 }
442 }
443
444 let my_pid = info.my_pid();
445
446 // 1) Try the parent process(es). If delta is set as the pager in git, then git is the parent process.
447 // If delta is started by a script check the parent's parent as well.
448 let mut current_pid = my_pid;
449 'parent_iter: for depth in [1, 2, 3] {
450 let parent = match info.parent_process(current_pid) {
451 None => {
452 break 'parent_iter;
453 }
454 Some(parent) => parent,
455 };
456 let parent_pid = parent.pid();
457
•458 match extract_args(&parent.cmd()) {
459 ProcessArgs::Args(result) => return Some(result),
460 ProcessArgs::ArgError => return None,
461
462 // 2) The 1st parent process was something else, this can happen if git output is piped into delta, e.g.
463 // `git blame foo.txt | delta`. When the shell sets up the pipe it creates the two processes, the pids
464 // are usually consecutive, so naively check if the process with `my_pid - 1` matches.
465 ProcessArgs::OtherProcess if depth == 1 => {
466 let sibling = info.naive_sibling_process(current_pid);
467 if let Some(proc) = sibling {
•468 if let ProcessArgs::Args(result) = extract_args(&proc.cmd()) {
469 return Some(result);
470 }
471 }
472 }
473 // This check is not done for the parent's parent etc.
474 ProcessArgs::OtherProcess => {}
475 }
476 current_pid = parent_pid;
477 }
478
479 /*
480 3) Neither parent(s) nor the direct sibling were a match.
481 The most likely case is that the input program of the pipe wrote all its data and exited before delta
482 started, so no command line can be parsed. Same if the data was piped from an input file.
483
484 There might also be intermediary scripts in between or piped input with a gap in pids or (rarely)
485 randomized pids, so check processes for the closest match in the process tree.
486 The size of this process tree can be reduced by only refreshing selected processes.
487
488 100 /usr/bin/some-terminal-emulator
489 124 \_ -shell
490 301 | \_ /usr/bin/git blame src/main.rs
491 302 | \_ wraps_delta.sh
492 303 | \_ delta
493 304 | \_ less --RAW-CONTROL-CHARS --quit-if-one-screen
494 125 \_ -shell
495 800 | \_ /usr/bin/git blame src/main.rs
496 200 | \_ delta
497 400 | \_ less --RAW-CONTROL-CHARS --quit-if-one-screen
498 126 \_ -shell
499 501 | \_ /bin/sh /wrapper/for/git blame src/main.rs
500 555 | | \_ /usr/bin/git blame src/main.rs
501 502 | \_ delta
502 567 | \_ less --RAW-CONTROL-CHARS --quit-if-one-screen
503
504 */
505
506 // Also `add` because `A_has_pid101 | delta_has_pid102`, but if A is a wrapper which then calls
507 // git (no `exec`), then the final pid of the git process might be 103 or greater.
508 let pid_range = my_pid.saturating_sub(10)..my_pid.saturating_add(10);
509 for p in pid_range {
510 // Processes which were not refreshed do not exist for sysinfo, so by selectively
511 // letting it know about processes the `find_sibling..` function will only
512 // consider these.
513 if info.process(p).is_none() {
514 info.refresh_process(p);
515 }
516 }
517
518 match info.find_sibling_in_refreshed_processes(my_pid, &extract_args) {
519 None => {
520 #[cfg(not(target_os = "linux"))]
521 let full_scan = true;
522
523 // The full scan is expensive on Linux and rarely successful, so disable it by default.
524 #[cfg(target_os = "linux")]
525 let full_scan = std::env::var("DELTA_CALLING_PROCESS_QUERY_ALL")
526 .is_ok_and(|v| !["0", "false", "no"].iter().any(|&n| n == v));
527
528 if full_scan {
529 info.refresh_processes();
530 info.find_sibling_in_refreshed_processes(my_pid, &extract_args)
531 } else {
532 None
533 }
534 }
535 some => some,
536 }
537 }
538
539 // Walk up the process tree, calling `f` with the pid and the distance to `starting_pid`.
540 // Prerequisite: `info.refresh_processes()` has been called.
541 fn iter_parents<P, F>(info: &P, starting_pid: DeltaPid, f: F)
542 where
543 P: ProcessInterface,
544 F: FnMut(DeltaPid, usize),
545 {
546 fn inner_iter_parents<P, F>(info: &P, pid: DeltaPid, mut f: F, distance: usize)
547 where
548 P: ProcessInterface,
549 F: FnMut(u32, usize),
550 {
551 // Probably bad input, not a tree:
552 if distance > 2000 {
553 return;
554 }
555 if let Some(proc) = info.process(pid) {
556 if let Some(pid) = proc.parent() {
557 f(pid, distance);
558 inner_iter_parents(info, pid, f, distance + 1)
559 }
560 }
561 }
562 inner_iter_parents(info, starting_pid, f, 1)
563 }
564
565 #[cfg(test)]
566 pub mod tests {
567
568 use super::*;
569
570 use itertools::Itertools;
571 use std::cell::RefCell;
572 use std::rc::Rc;
573
574 thread_local! {
575 static FAKE_ARGS: RefCell<TlsState<Vec<String>>> = const { RefCell::new(TlsState::None) };
576 }
577
578 #[derive(Debug, PartialEq)]
579 enum TlsState<T> {
580 Once(T),
581 Scope(T),
582 With(usize, Rc<Vec<T>>),
583 None,
584 Invalid,
585 ErrorAlreadyHandled,
586 }
587
588 // When calling `FakeParentArgs::get()`, it can return `Some(values)` which were set earlier
589 // during in the #[test]. Otherwise returns None.
590 // This value can be valid once: `FakeParentArgs::once(val)`, for the entire scope:
591 // `FakeParentArgs::for_scope(val)`, or can be different values every time `get()` is called:
592 // `FakeParentArgs::with([val1, val2, val3])`.
593 // It is an error if `once` or `with` values remain unused, or are overused.
594 // Note: The values are stored per-thread, so the expectation is that no thread boundaries are
595 // crossed.
596 pub struct FakeParentArgs {}
597 impl FakeParentArgs {
598 pub fn once(args: &str) -> Self {
599 Self::new(args, TlsState::Once, "once")
600 }
601 pub fn for_scope(args: &str) -> Self {
602 Self::new(args, TlsState::Scope, "for_scope")
603 }
604 fn new<F>(args: &str, initial: F, from_: &str) -> Self
605 where
606 F: Fn(Vec<String>) -> TlsState<Vec<String>>,
607 {
608 let string_vec = args.split(' ').map(str::to_owned).collect();
609 if FAKE_ARGS.with(|a| a.replace(initial(string_vec))) != TlsState::None {
610 Self::error(from_);
611 }
612 FakeParentArgs {}
613 }
614 pub fn with(args: &[&str]) -> Self {
615 let with = TlsState::With(
616 0,
617 Rc::new(
618 args.iter()
619 .map(|a| a.split(' ').map(str::to_owned).collect())
620 .collect(),
621 ),
622 );
623 if FAKE_ARGS.with(|a| a.replace(with)) != TlsState::None || args.is_empty() {
624 Self::error("with creation");
625 }
626 FakeParentArgs {}
627 }
628 pub fn get() -> Option<Vec<String>> {
629 FAKE_ARGS.with(|a| {
630 let old_value = a.replace_with(|old_value| match old_value {
631 TlsState::Once(_) => TlsState::Invalid,
632 TlsState::Scope(args) => TlsState::Scope(args.clone()),
633 TlsState::With(n, args) => TlsState::With(*n + 1, Rc::clone(args)),
634 TlsState::None => TlsState::None,
635 TlsState::Invalid => TlsState::Invalid,
636 TlsState::ErrorAlreadyHandled => TlsState::ErrorAlreadyHandled,
637 });
638
639 match old_value {
640 TlsState::Once(args) | TlsState::Scope(args) => Some(args),
641 TlsState::With(n, args) if n < args.len() => Some(args[n].clone()),
642 TlsState::None => None,
643 TlsState::Invalid | TlsState::With(_, _) | TlsState::ErrorAlreadyHandled => {
644 Self::error("get");
645 None
646 }
647 }
648 })
649 }
650 pub fn are_set() -> bool {
651 FAKE_ARGS.with(|a| {
652 *a.borrow() != TlsState::None && *a.borrow() != TlsState::ErrorAlreadyHandled
653 })
654 }
655 fn error(where_: &str) {
656 FAKE_ARGS.with(|a| {
657 let old_value = a.replace(TlsState::ErrorAlreadyHandled);
658
659 match old_value {
660 TlsState::ErrorAlreadyHandled => (),
661 _ => {
662 panic!(
663 "test logic error (in {}): wrong FakeParentArgs scope?",
664 where_
665 );
666 }
667 }
668 });
669 }
670 }
671 impl Drop for FakeParentArgs {
672 fn drop(&mut self) {
673 // Clears an Invalid state and tests if a Once or With value has been used.
674 FAKE_ARGS.with(|a| {
675 let old_value = a.replace(TlsState::None);
676 match old_value {
677 TlsState::With(n, args) => {
678 if n != args.len() {
679 Self::error("drop with")
680 }
681 }
682 TlsState::Once(_) | TlsState::None => Self::error("drop"),
683 TlsState::Scope(_) | TlsState::Invalid | TlsState::ErrorAlreadyHandled => {}
684 }
685 });
686 }
687 }
688
689 #[derive(Debug, Default)]
690 struct FakeProc {
691 #[allow(dead_code)]
692 pid: DeltaPid,
693 start_time: u64,
694 cmd: Vec<String>,
695 ppid: Option<DeltaPid>,
696 }
697 impl FakeProc {
698 fn new(pid: DeltaPid, start_time: u64, cmd: Vec<String>, ppid: Option<DeltaPid>) -> Self {
699 FakeProc {
700 pid,
701 start_time,
702 cmd,
703 ppid,
704 }
705 }
706 }
707
708 impl ProcActions for FakeProc {
•709 fn cmd(&self) -> Vec<String> {
710 self.cmd.clone()
711 }
712 fn parent(&self) -> Option<DeltaPid> {
713 self.ppid
714 }
715 fn pid(&self) -> DeltaPid {
716 self.pid
717 }
718 fn start_time(&self) -> u64 {
719 self.start_time
720 }
721 }
722
723 #[derive(Debug, Default)]
724 struct MockProcInfo {
725 delta_pid: DeltaPid,
726 info: HashMap<Pid, FakeProc>,
727 }
728 impl MockProcInfo {
729 fn with(processes: &[(DeltaPid, u64, &str, Option<DeltaPid>)]) -> Self {
730 MockProcInfo {
731 delta_pid: processes.last().map(|p| p.0).unwrap_or(1),
732 info: processes
733 .iter()
734 .map(|(pid, start_time, cmd, ppid)| {
735 let cmd_vec = cmd.split(' ').map(str::to_owned).collect();
736 (
737 Pid::from_u32(*pid),
738 FakeProc::new(*pid, *start_time, cmd_vec, *ppid),
739 )
740 })
741 .collect(),
742 }
743 }
744 }
745
746 impl ProcessInterface for MockProcInfo {
747 type Out = FakeProc;
748
749 fn my_pid(&self) -> DeltaPid {
750 self.delta_pid
751 }
752 fn process(&self, pid: DeltaPid) -> Option<&Self::Out> {
753 self.info.get(&Pid::from_u32(pid))
754 }
755 fn processes(&self) -> &HashMap<Pid, Self::Out> {
756 &self.info
757 }
758 fn refresh_processes(&mut self) {}
759 fn refresh_process(&mut self, _pid: DeltaPid) -> bool {
760 true
761 }
762 }
763
764 fn set(arg1: &[&str]) -> HashSet<String> {
765 arg1.iter().map(|&s| s.to_owned()).collect()
766 }
767
768 #[test]
769 fn test_process_testing() {
770 {
771 let _args = FakeParentArgs::once("git blame hello");
772 assert_eq!(
773 calling_process_cmdline(ProcInfo::new(), describe_calling_process),
774 Some(CallingProcess::GitBlame(CommandLine {
775 long_options: [].into(),
776 short_options: [].into(),
777 last_arg: Some("hello".into())
778 }))
779 );
780 }
781 {
782 let _args = FakeParentArgs::once("git blame world.txt");
783 assert_eq!(
784 calling_process_cmdline(ProcInfo::new(), describe_calling_process),
785 Some(CallingProcess::GitBlame(CommandLine {
786 long_options: [].into(),
787 short_options: [].into(),
788 last_arg: Some("world.txt".into())
789 }))
790 );
791 }
792 {
793 let _args = FakeParentArgs::for_scope("git blame hello world.txt");
794 assert_eq!(
795 calling_process_cmdline(ProcInfo::new(), describe_calling_process),
796 Some(CallingProcess::GitBlame(CommandLine {
797 long_options: [].into(),
798 short_options: [].into(),
799 last_arg: Some("world.txt".into())
800 }))
801 );
802 }
803 }
804
805 #[test]
806 #[should_panic(expected = "test logic error (in get): wrong FakeParentArgs scope?")]
807 fn test_process_testing_assert() {
808 let _args = FakeParentArgs::once("git blame do.not.panic");
809 assert_eq!(
810 calling_process_cmdline(ProcInfo::new(), describe_calling_process),
811 Some(CallingProcess::GitBlame(CommandLine {
812 long_options: [].into(),
813 short_options: [].into(),
814 last_arg: Some("do.not.panic".into())
815 }))
816 );
817 calling_process_cmdline(ProcInfo::new(), describe_calling_process);
818 }
819
820 #[test]
821 #[should_panic(expected = "test logic error (in drop): wrong FakeParentArgs scope?")]
822 fn test_process_testing_assert_once_never_used() {
823 let _args = FakeParentArgs::once("never used");
824 }
825
826 #[test]
827 #[should_panic(expected = "test logic error (in once): wrong FakeParentArgs scope?")]
828 fn test_process_testing_assert_for_scope_never_used() {
829 let _args = FakeParentArgs::for_scope(&"never used");
830 let _args = FakeParentArgs::once(&"never used");
831 }
832
833 #[test]
834 #[should_panic(expected = "test logic error (in for_scope): wrong FakeParentArgs scope?")]
835 fn test_process_testing_assert_once_never_used2() {
836 let _args = FakeParentArgs::once(&"never used");
837 let _args = FakeParentArgs::for_scope(&"never used");
838 }
839
840 #[test]
841 fn test_process_testing_scope_can_remain_unused() {
842 let _args = FakeParentArgs::for_scope("never used");
843 }
844
845 #[test]
846 fn test_process_testing_n_times() {
847 let _args = FakeParentArgs::with(&["git blame once", "git blame twice"]);
848 assert_eq!(
849 calling_process_cmdline(ProcInfo::new(), describe_calling_process),
850 Some(CallingProcess::GitBlame(CommandLine {
851 long_options: [].into(),
852 short_options: [].into(),
853 last_arg: Some("once".into())
854 }))
855 );
856
857 assert_eq!(
858 calling_process_cmdline(ProcInfo::new(), describe_calling_process),
859 Some(CallingProcess::GitBlame(CommandLine {
860 long_options: [].into(),
861 short_options: [].into(),
862 last_arg: Some("twice".into())
863 }))
864 );
865 }
866
867 #[test]
868 #[should_panic(expected = "test logic error (in drop with): wrong FakeParentArgs scope?")]
869 fn test_process_testing_n_times_unused() {
870 let _args = FakeParentArgs::with(&["git blame once", "git blame twice"]);
871 }
872
873 #[test]
874 #[should_panic(expected = "test logic error (in drop with): wrong FakeParentArgs scope?")]
875 fn test_process_testing_n_times_underused() {
876 let _args = FakeParentArgs::with(&["git blame once", "git blame twice"]);
877 assert_eq!(
878 calling_process_cmdline(ProcInfo::new(), describe_calling_process),
879 Some(CallingProcess::GitBlame(CommandLine {
880 long_options: [].into(),
881 short_options: [].into(),
882 last_arg: Some("once".into())
883 }))
884 );
885 }
886
887 #[test]
888 #[should_panic(expected = "test logic error (in get): wrong FakeParentArgs scope?")]
889 fn test_process_testing_n_times_overused() {
890 let _args = FakeParentArgs::with(&["git blame once"]);
891 assert_eq!(
892 calling_process_cmdline(ProcInfo::new(), describe_calling_process),
893 Some(CallingProcess::GitBlame(CommandLine {
894 long_options: [].into(),
895 short_options: [].into(),
896 last_arg: Some("once".into())
897 }))
898 );
899 calling_process_cmdline(ProcInfo::new(), describe_calling_process);
900 }
901
902 #[test]
903 fn test_describe_calling_process_blame() {
904 let no_processes = MockProcInfo::with(&[]);
905 assert_eq!(
906 calling_process_cmdline(no_processes, describe_calling_process),
907 None
908 );
909
910 let two_trees = MockProcInfo::with(&[
911 (2, 100, "-shell", None),
912 (3, 100, "git blame src/main.rs", Some(2)),
913 (4, 100, "call_delta.sh", None),
914 (5, 100, "delta", Some(4)),
915 ]);
916 assert_eq!(
917 calling_process_cmdline(two_trees, describe_calling_process),
918 None
919 );
920
921 let no_options_command_line = CommandLine {
922 long_options: [].into(),
923 short_options: [].into(),
924 last_arg: Some("hello.txt".to_string()),
925 };
926 let parent = MockProcInfo::with(&[
927 (2, 100, "-shell", None),
928 (3, 100, "git blame hello.txt", Some(2)),
929 (4, 100, "delta", Some(3)),
930 ]);
931 assert_eq!(
932 calling_process_cmdline(parent, describe_calling_process),
933 Some(CallingProcess::GitBlame(no_options_command_line.clone()))
934 );
935
936 let parent = MockProcInfo::with(&[
937 (2, 100, "-shell", None),
938 (3, 100, "git blame -- hello.txt", Some(2)),
939 (4, 100, "delta", Some(3)),
940 ]);
941 assert_eq!(
942 calling_process_cmdline(parent, describe_calling_process),
943 Some(CallingProcess::GitBlame(no_options_command_line.clone()))
944 );
945
946 let parent = MockProcInfo::with(&[
947 (2, 100, "-shell", None),
948 (3, 100, "git blame -- --not.an.argument", Some(2)),
949 (4, 100, "delta", Some(3)),
950 ]);
951 assert_eq!(
952 calling_process_cmdline(parent, describe_calling_process),
953 Some(CallingProcess::GitBlame(CommandLine {
954 long_options: [].into(),
955 short_options: [].into(),
956 last_arg: Some("--not.an.argument".to_string()),
957 }))
958 );
959
960 let parent = MockProcInfo::with(&[
961 (2, 100, "-shell", None),
962 (3, 100, "git blame --help.txt", Some(2)),
963 (4, 100, "delta", Some(3)),
964 ]);
965 assert_eq!(
966 calling_process_cmdline(parent, describe_calling_process),
967 Some(CallingProcess::GitBlame(CommandLine {
968 long_options: ["--help.txt".into()].into(),
969 short_options: [].into(),
970 last_arg: None,
971 }))
972 );
973
974 let parent = MockProcInfo::with(&[
975 (2, 100, "-shell", None),
976 (3, 100, "git blame --", Some(2)),
977 (4, 100, "delta", Some(3)),
978 ]);
979 assert_eq!(
980 calling_process_cmdline(parent, describe_calling_process),
981 Some(CallingProcess::GitBlame(CommandLine {
982 long_options: [].into(),
983 short_options: [].into(),
984 last_arg: None,
985 }))
986 );
987
988 let parent = MockProcInfo::with(&[
989 (2, 100, "-shell", None),
990 (3, 100, "Git.exe blame hello.txt", Some(2)),
991 (4, 100, "delta", Some(3)),
992 ]);
993 assert_eq!(
994 calling_process_cmdline(parent, describe_calling_process),
995 Some(CallingProcess::GitBlame(no_options_command_line.clone()))
996 );
997
998 let git_blame_command =
999 "git -c a=b blame -fnb --incremental -t --color-by-age -M --since=3.weeks --contents annotation.txt -C -C2 hello.txt";
1000
1001 // here -C2 is parsed as -C and -2. It doesn't really matters because we only use last_arg from options
1002 // to determine the file type.
1003 let expected_result = Some(CallingProcess::GitBlame(CommandLine {
1004 long_options: set(&["--incremental", "--color-by-age", "--since", "--contents"]),
1005 short_options: set(&["-f", "-n", "-b", "-t", "-M", "-C", "-2"]),
1006 last_arg: Some("hello.txt".to_string()),
1007 }));
1008
1009 let parent = MockProcInfo::with(&[
1010 (2, 100, "-shell", None),
1011 (3, 100, git_blame_command, Some(2)),
1012 (4, 100, "delta", Some(3)),
1013 ]);
1014 assert_eq!(
1015 calling_process_cmdline(parent, describe_calling_process),
1016 expected_result
1017 );
1018
1019 let grandparent = MockProcInfo::with(&[
1020 (2, 100, "-shell", None),
1021 (3, 100, git_blame_command, Some(2)),
1022 (4, 100, "call_delta.sh", Some(3)),
1023 (5, 100, "delta", Some(4)),
1024 ]);
1025 assert_eq!(
1026 calling_process_cmdline(grandparent, describe_calling_process),
1027 expected_result
1028 );
1029
1030 let sibling = MockProcInfo::with(&[
1031 (2, 100, "-xterm", None),
1032 (3, 100, "-shell", Some(2)),
1033 (4, 100, "git blame src/main.rs", Some(3)),
1034 (5, 100, "delta", Some(3)),
1035 ]);
1036 assert_eq!(
1037 calling_process_cmdline(sibling, describe_calling_process),
1038 Some(CallingProcess::GitBlame(CommandLine {
1039 long_options: [].into(),
1040 short_options: [].into(),
1041 last_arg: Some("src/main.rs".into())
1042 }))
1043 );
1044
1045 let indirect_sibling = MockProcInfo::with(&[
1046 (2, 100, "-xterm", None),
1047 (3, 100, "-shell", Some(2)),
1048 (4, 100, "Git.exe blame --correct src/main.abc", Some(3)),
1049 (
1050 10,
1051 100,
1052 "Git.exe blame --ignored-child src/main.def",
1053 Some(4),
1054 ),
1055 (5, 100, "delta.sh", Some(3)),
1056 (20, 100, "delta", Some(5)),
1057 ]);
1058 assert_eq!(
1059 calling_process_cmdline(indirect_sibling, describe_calling_process),
1060 Some(CallingProcess::GitBlame(CommandLine {
1061 long_options: set(&["--correct"]),
1062 short_options: [].into(),
1063 last_arg: Some("src/main.abc".into())
1064 }))
1065 );
1066
1067 let indirect_sibling2 = MockProcInfo::with(&[
1068 (2, 100, "-xterm", None),
1069 (3, 100, "-shell", Some(2)),
1070 (4, 100, "git wrap src/main.abc", Some(3)),
1071 (10, 100, "git blame src/main.def", Some(4)),
1072 (5, 100, "delta.sh", Some(3)),
1073 (20, 100, "delta", Some(5)),
1074 ]);
1075 assert_eq!(
1076 calling_process_cmdline(indirect_sibling2, describe_calling_process),
1077 Some(CallingProcess::GitBlame(CommandLine {
1078 long_options: [].into(),
1079 short_options: [].into(),
1080 last_arg: Some("src/main.def".into())
1081 }))
1082 );
1083
1084 // 3 blame processes, 2 with matching start times, pick the one with lower
1085 // distance but larger start time difference.
1086 let indirect_sibling_start_times = MockProcInfo::with(&[
1087 (2, 100, "-xterm", None),
1088 (3, 100, "-shell", Some(2)),
1089 (4, 109, "git wrap src/main.abc", Some(3)),
1090 (10, 109, "git blame src/main.def", Some(4)),
1091 (20, 100, "git wrap1 src/main.abc", Some(3)),
1092 (21, 100, "git wrap2 src/main.def", Some(20)),
1093 (22, 101, "git blame src/main.not", Some(21)),
1094 (23, 102, "git blame src/main.this", Some(20)),
1095 (5, 100, "delta.sh", Some(3)),
1096 (20, 100, "delta", Some(5)),
1097 ]);
1098 assert_eq!(
1099 calling_process_cmdline(indirect_sibling_start_times, describe_calling_process),
1100 Some(CallingProcess::GitBlame(CommandLine {
1101 long_options: [].into(),
1102 short_options: [].into(),
1103 last_arg: Some("src/main.this".into())
1104 }))
1105 );
1106 }
1107
1108 #[test]
1109 fn test_describe_calling_process_grep() {
1110 let no_processes = MockProcInfo::with(&[]);
1111 assert_eq!(
1112 calling_process_cmdline(no_processes, describe_calling_process),
1113 None
1114 );
1115
1116 let empty_command_line = CommandLine {
1117 long_options: [].into(),
1118 short_options: [].into(),
1119 last_arg: Some("hello.txt".to_string()),
1120 };
1121 let parent = MockProcInfo::with(&[
1122 (2, 100, "-shell", None),
1123 (3, 100, "git grep pattern hello.txt", Some(2)),
1124 (4, 100, "delta", Some(3)),
1125 ]);
1126 assert_eq!(
1127 calling_process_cmdline(parent, describe_calling_process),
1128 Some(CallingProcess::GitGrep(empty_command_line.clone()))
1129 );
1130
1131 let parent = MockProcInfo::with(&[
1132 (2, 100, "-shell", None),
1133 (3, 100, "Git.exe grep pattern hello.txt", Some(2)),
1134 (4, 100, "delta", Some(3)),
1135 ]);
1136 assert_eq!(
1137 calling_process_cmdline(parent, describe_calling_process),
1138 Some(CallingProcess::GitGrep(empty_command_line))
1139 );
1140
1141 for grep_command in &[
1142 "/usr/local/bin/rg pattern hello.txt",
1143 "RG.exe pattern hello.txt",
1144 "/usr/local/bin/ack pattern hello.txt",
1145 "ack.exe pattern hello.txt",
1146 ] {
1147 let parent = MockProcInfo::with(&[
1148 (2, 100, "-shell", None),
1149 (3, 100, grep_command, Some(2)),
1150 (4, 100, "delta", Some(3)),
1151 ]);
1152 assert_eq!(
1153 calling_process_cmdline(parent, describe_calling_process),
1154 Some(CallingProcess::OtherGrep)
1155 );
1156 }
1157
1158 let git_grep_command =
1159 "git grep -ab --function-context -n --show-function -W --foo=val pattern hello.txt";
1160
1161 let expected_result = Some(CallingProcess::GitGrep(CommandLine {
1162 long_options: set(&["--function-context", "--show-function", "--foo"]),
1163 short_options: set(&["-a", "-b", "-n", "-W"]),
1164 last_arg: Some("hello.txt".to_string()),
1165 }));
1166
1167 let parent = MockProcInfo::with(&[
1168 (2, 100, "-shell", None),
1169 (3, 100, git_grep_command, Some(2)),
1170 (4, 100, "delta", Some(3)),
1171 ]);
1172 assert_eq!(
1173 calling_process_cmdline(parent, describe_calling_process),
1174 expected_result
1175 );
1176
1177 let grandparent = MockProcInfo::with(&[
1178 (2, 100, "-shell", None),
1179 (3, 100, git_grep_command, Some(2)),
1180 (4, 100, "call_delta.sh", Some(3)),
1181 (5, 100, "delta", Some(4)),
1182 ]);
1183 assert_eq!(
1184 calling_process_cmdline(grandparent, describe_calling_process),
1185 expected_result
1186 );
1187 }
1188
1189 #[test]
1190 fn test_describe_calling_process_git_show() {
1191 for (command, expected_extension) in [
1192 (
1193 "/usr/local/bin/git show --abbrev-commit -w 775c3b84:./src/hello.rs",
1194 "hello.rs",
1195 ),
1196 (
1197 "/usr/local/bin/git show --abbrev-commit -w HEAD~1:Makefile",
1198 "Makefile",
1199 ),
1200 (
1201 "git -c x.y=z show --abbrev-commit -w 775c3b84:./src/hello.bye.R",
1202 "hello.bye.R",
1203 ),
1204 ] {
1205 let parent = MockProcInfo::with(&[
1206 (2, 100, "-shell", None),
1207 (3, 100, command, Some(2)),
1208 (4, 100, "delta", Some(3)),
1209 ]);
1210 if let Some(CallingProcess::GitShow(cmd_line, filename)) =
1211 calling_process_cmdline(parent, describe_calling_process)
1212 {
1213 assert_eq!(cmd_line.long_options, set(&["--abbrev-commit"]));
1214 assert_eq!(cmd_line.short_options, set(&["-w"]));
1215 assert_eq!(filename, Some(expected_extension.to_string()));
1216 } else {
1217 unreachable!();
1218 }
1219 }
1220 }
1221
1222 #[test]
1223 fn test_process_calling_cmdline() {
1224 // GitHub runs CI tests for arm under qemu where sysinfo can not find the parent process.
1225 if std::env::vars().any(|(key, _)| key == "CROSS_RUNNER" || key == "QEMU_LD_PREFIX") {
1226 return;
1227 }
1228
1229 let mut info = ProcInfo::new();
1230 info.refresh_processes();
1231 let mut ppid_distance = Vec::new();
1232
1233 iter_parents(&info, std::process::id(), |pid, distance| {
1234 ppid_distance.push(pid as i32);
1235 ppid_distance.push(distance as i32)
1236 });
1237
1238 assert!(ppid_distance[1] == 1);
1239
1240 fn find_calling_process(args: &[String], want: &[&str]) -> ProcessArgs<()> {
1241 if args.iter().any(|have| want.iter().any(|want| want == have)) {
1242 ProcessArgs::Args(())
1243 } else {
1244 ProcessArgs::ArgError
1245 }
1246 }
1247
1248 // Tests that caller is something like "cargo test" or "cargo tarpaulin"
1249 let find_test = |args: &[String]| find_calling_process(args, &["t", "test", "tarpaulin"]);
1250 assert_eq!(calling_process_cmdline(info, find_test), Some(()));
1251
1252 let nonsense = ppid_distance
1253 .iter()
1254 .map(|i| i.to_string())
1255 .join("Y40ii4RihK6lHiK4BDsGSx");
1256
1257 let find_nothing = |args: &[String]| find_calling_process(args, &[&nonsense]);
1258 assert_eq!(calling_process_cmdline(ProcInfo::new(), find_nothing), None);
1259 }
1260 }