summaryrefslogtreecommitdiffstats
path: root/src/utils/process.rs
blob: a9c11a375e0b99fbd5495c1bbf73ef825525200c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
use std::collections::{HashMap, HashSet};
use sysinfo::{Pid, Process, ProcessExt, SystemExt};

// Return value of `extract_args(args: &[String]) -> ProcessArgs<T>` function which is
// passed to `calling_process_cmdline()`.
#[derive(Debug, PartialEq)]
pub enum ProcessArgs<T> {
    // A result has been successfully extracted from args.
    Args(T),
    // The extraction has failed.
    ArgError,
    // The process does not match, others may be inspected.
    OtherProcess,
}

pub fn git_blame_filename_extension() -> Option<String> {
    calling_process_cmdline(blame::guess_git_blame_filename_extension)
}

mod blame {
    use super::*;

    // Skip all arguments starting with '-' from `args_it`. Also skip all arguments listed in
    // `skip_this_plus_parameter` plus their respective next argument.
    // Keep all arguments once a '--' is encountered.
    // (Note that some arguments work with and without '=': '--foo' 'bar' / '--foo=bar')
    fn skip_uninteresting_args<'a, 'b, ArgsI, SkipI>(
        mut args_it: ArgsI,
        skip_this_plus_parameter: SkipI,
    ) -> Vec<&'a str>
    where
        ArgsI: Iterator<Item = &'a str>,
        SkipI: Iterator<Item = &'b str>,
    {
        let arg_follows_space: HashSet<&'b str> = skip_this_plus_parameter.into_iter().collect();

        let mut result = Vec::new();
        loop {
            match args_it.next() {
                None => break result,
                Some("--") => {
                    result.extend(args_it);
                    break result;
                }
                Some(arg) if arg_follows_space.contains(arg) => {
                    let _skip_parameter = args_it.next();
                }
                Some(arg) if !arg.starts_with('-') => {
                    result.push(arg);
                }
                Some(_) => { /* skip: --these -and --also=this */ }
            }
        }
    }

    pub fn guess_git_blame_filename_extension(args: &[String]) -> ProcessArgs<String> {
        {
            let mut it = args.iter();
            match (it.next(), it.next()) {
                // git blame or git -C/-c etc. and then (maybe) blame
                (Some(git), Some(blame))
                    if git.contains("git") && (blame == "blame" || blame.starts_with('-')) => {}
                _ => return ProcessArgs::OtherProcess,
            }
        }

        let args = args.iter().skip(2).map(|s| s.as_str());

        // See git(1) and git-blame(1). Some arguments separate their parameter with space or '=', e.g.
        // --date 2015 or --date=2015.
        let git_blame_options_with_parameter =
            "-C -c -L --since --ignore-rev --ignore-revs-file --contents --reverse --date";

        match skip_uninteresting_args(args, git_blame_options_with_parameter.split(' '))
            .last()
            .and_then(|&s| s.split('.').last())
            .map(str::to_owned)
        {
            Some(ext) => ProcessArgs::Args(ext),
            None => ProcessArgs::ArgError,
        }
    }
} // mod blame

fn calling_process_cmdline<F, T>(extract_args: F) -> Option<T>
where
    F: Fn(&[String]) -> ProcessArgs<T>,
{
    let mut info = sysinfo::System::new();
    let my_pid = std::process::id() as Pid;

    // 1) Try the parent process. If delta is set as the pager in git, then git is the parent process.
    let parent = parent_process(&mut info, my_pid)?;

    match extract_args(parent.cmd()) {
        ProcessArgs::Args(ext) => return Some(ext),
        ProcessArgs::ArgError => return None,

        // 2) The parent process was something else, this can happen if git output is piped into delta, e.g.
        // `git blame foo.txt | delta`. When the shell sets up the pipe it creates the two processes, the pids
        // are usually consecutive, so check if the process with `my_pid - 1` matches.
        ProcessArgs::OtherProcess => {
            let sibling = naive_sibling_process(&mut info, my_pid);
            if let Some(proc) = sibling {
                if let ProcessArgs::Args(ext) = extract_args(proc.cmd()) {
                    return Some(ext);
                }
            }
            // else try the fallback
        }
    }

    /*
    3) Neither parent nor direct sibling were a match.
    The most likely case is that the input program of the pipe wrote all its data and exited before delta
    started, so no command line can be parsed. Same if the data was piped from an input file.

    There might also be intermediary scripts in between or piped input with a gap in pids or (rarely)
    randomized pids, so check all processes for the closest match in the process tree.

    100 /usr/bin/some-terminal-emulator
    124  \_ -shell
    301  |   \_ /usr/bin/git blame src/main.rs
    302  |       \_ wraps_delta.sh
    303  |           \_ delta
    304  |               \_ less --RAW-CONTROL-CHARS --quit-if-one-screen
    125  \_ -shell
    800  |   \_ /usr/bin/git blame src/main.rs
    200  |   \_ delta
    400  |       \_ less --RAW-CONTROL-CHARS --quit-if-one-screen
    126  \_ -shell
    501  |   \_ /bin/sh /wrapper/for/git blame src/main.rs
    555  |   |   \_ /usr/bin/git blame src/main.rs
    502  |   \_ delta
    567  |       \_ less --RAW-CONTROL-CHARS --quit-if-one-screen

    */
    find_sibling_process(&mut info, my_pid, extract_args)
}

fn parent_process(info: &mut sysinfo::System, my_pid: Pid) -> Option<&Process> {
    info.refresh_process(my_pid).then(|| ())?;

    let parent_pid = info.process(my_pid)?.parent()?;
    info.refresh_process(parent_pid).then(|| ())?;
    info.process(parent_pid)
}

fn naive_sibling_process(info: &mut sysinfo::System, my_pid: Pid) -> Option<&Process> {
    let sibling_pid = my_pid - 1;
    info.refresh_process(sibling_pid).then(|| ())?;
    info.process(sibling_pid)
}

// Walk up the process tree, calling `f` with the pid and the distance to `starting_pid`.
// Prerequisite: `info.refresh_processes()` has been called.
fn iter_parents<F>(info: &sysinfo::System, starting_pid: Pid, f: F)
where
    F: FnMut(Pid, usize),
{
    fn inner_iter_parents<F>(info: &sysinfo::System, pid: Pid, mut f: F, distance: usize)
    where
        F: FnMut(Pid, usize),
    {
        if let Some(proc) = info.process(pid) {
            if let Some(pid) = proc.parent() {
                f(pid, distance);
                inner_iter_parents(info, pid, f, distance + 1)
            }
        }
    }
    inner_iter_parents(info, starting_pid, f, 1)
}

fn find_sibling_process<F, T>(info: &mut sysinfo::System, my_pid: Pid, extract_args: F) -> Option<T>
where
    F: Fn(&[String]) -> ProcessArgs<T>,
{
    info.refresh_processes();

    let this_start_time = info.process(my_pid)?.start_time();

    /*

    $ start_blame_of.sh src/main.rs | delta

    \_ /usr/bin/some-terminal-emulator
    |   \_ common_git_and_delta_ancestor
    |       \_ /bin/sh /opt/git/start_blame_of.sh src/main.rs
    |       |   \_ /bin/sh /opt/some/wrapper git blame src/main.rs
    |       |       \_ /usr/bin/git blame src/main.rs
    |       \_ /bin/sh /opt/some/wrapper delta
    |           \_ delta

    Walk up the process tree of delta and of every matching other process, counting the steps
    along the way.
    Find the common ancestor processes, calculate the distance, and select the one with the shortest.

    */

    let mut pid_distances = HashMap::<Pid, usize>::new();
    let mut collect_parent_pids = |pid, distance| {
        pid_distances.insert(pid, distance);
    };

    iter_parents(info, my_pid, &mut collect_parent_pids);

    let process_start_time_difference_less_than_3s = |a, b| (a as i64 - b as i64).abs() < 3;

    let cmdline_of_closest_matching_process = info
        .processes()
        .iter()
        .filter(|(_, proc)| {
            process_start_time_difference_less_than_3s(this_start_time, proc