-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlist.go
71 lines (62 loc) · 1.52 KB
/
list.go
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
//go:build windows
// +build windows
package winproc
// List returns a list of running processes. Collection options can be
// provided to filter the list and collect additional process information.
// Options will be evaluated in order.
//
// If a filter relies on process information gathered by one or more
// collector options, those options must be included before the filter.
func List(options ...CollectionOption) ([]Process, error) {
// Collect all processes from the system
procs, err := scan()
if err != nil {
return nil, err
}
// Form a collection
col := Collection{
Procs: procs,
Excluded: make([]bool, len(procs)),
}
// Apply each collection option in order
for i := 0; i < len(options); i++ {
opt := options[i]
// Merge adjacent options when possible.
//
// This can improve efficiency by combining several options that work
// more efficiently as a batch.
for i+1 < len(options) {
mergable, ok := opt.(MergableCollectionOption)
if !ok {
break
}
merged, ok := mergable.Merge(options[i+1])
if !ok {
break
}
opt = merged
i++
}
opt.Apply(&col)
}
// Count the number of matches
total := 0
for i := range col.Excluded {
if !col.Excluded[i] {
total++
}
}
// If all procs matched just return the original slice
if len(col.Procs) == total {
return col.Procs, nil
}
// Return the matches
matched := make([]Process, 0, total)
for i := range col.Procs {
if col.Excluded[i] {
continue
}
matched = append(matched, col.Procs[i])
}
return matched, nil
}