|
50 | 50 |
|
51 | 51 |
|
52 | 52 | --- Return running processes as a list with { pid, name } tables. |
| 53 | +--- |
| 54 | +---@return {pid: integer, name: string}[] |
53 | 55 | function M.get_processes() |
54 | 56 | local is_windows = vim.fn.has('win32') == 1 |
55 | 57 | local separator = is_windows and ',' or ' \\+' |
|
95 | 97 |
|
96 | 98 |
|
97 | 99 | --- Show a prompt to select a process pid |
98 | | -function M.pick_process() |
| 100 | +--- Requires `ps ah` on Linux/Mac and `tasklist /nh /fo csv` on windows. |
| 101 | +-- |
| 102 | +--- Takes an optional `opts` table with the following options: |
| 103 | +--- |
| 104 | +--- - filter string|fun: A lua pattern or function to filter the processes. |
| 105 | +--- If a function the parameter is a table with |
| 106 | +--- {pid: integer, name: string} |
| 107 | +--- and it must return a boolean. |
| 108 | +--- Matches are included. |
| 109 | +--- |
| 110 | +--- <pre> |
| 111 | +--- require("dap.utils").pick_process({ filter = "sway" }) |
| 112 | +--- </pre> |
| 113 | +--- |
| 114 | +--- <pre> |
| 115 | +--- require("dap.utils").pick_process({ |
| 116 | +--- filter = function(proc) return vim.endswith(proc.name, "sway") end |
| 117 | +--- }) |
| 118 | +--- </pre> |
| 119 | +--- |
| 120 | +---@param opts? {filter: string|(fun(proc: {pid: integer, name: string}): boolean)} |
| 121 | +function M.pick_process(opts) |
| 122 | + opts = opts or {} |
99 | 123 | local label_fn = function(proc) |
100 | 124 | return string.format("id=%d name=%s", proc.pid, proc.name) |
101 | 125 | end |
| 126 | + local procs = M.get_processes() |
| 127 | + if opts.filter then |
| 128 | + local filter |
| 129 | + if type(opts.filter) == "string" then |
| 130 | + filter = function(proc) |
| 131 | + return proc.name:find(opts.filter) |
| 132 | + end |
| 133 | + elseif type(opts.filter) == "function" then |
| 134 | + filter = function(proc) |
| 135 | + return opts.filter(proc) |
| 136 | + end |
| 137 | + else |
| 138 | + error("opts.filter must be a string or a function") |
| 139 | + end |
| 140 | + procs = vim.tbl_filter(filter, procs) |
| 141 | + end |
102 | 142 | local co = coroutine.running() |
103 | 143 | if co then |
104 | 144 | return coroutine.create(function() |
105 | | - local procs = M.get_processes() |
106 | 145 | require('dap.ui').pick_one(procs, "Select process", label_fn, function(choice) |
107 | 146 | coroutine.resume(co, choice and choice.pid or nil) |
108 | 147 | end) |
109 | 148 | end) |
110 | 149 | else |
111 | | - local procs = M.get_processes() |
112 | 150 | local result = require('dap.ui').pick_one_sync(procs, "Select process", label_fn) |
113 | 151 | return result and result.pid or nil |
114 | 152 | end |
|
0 commit comments