Skip to content

Commit

Permalink
Handle no-search-hits properly
Browse files Browse the repository at this point in the history
Before this change, if there were no search hits, we just listed all
running processes.

With this change in place, we print an informative message to stderr
when this happens.

Fixes #117.
  • Loading branch information
walles committed Oct 29, 2023
1 parent 7c018d8 commit 2259495
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
18 changes: 15 additions & 3 deletions px/px_tree.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,26 @@
from . import px_process
from . import px_terminal

import sys

from typing import Set, List, Optional, Iterable


def tree(search: str) -> None:
"""Print a process tree"""
for line in _generate_tree(px_process.get_all(), search):
print_me = _generate_tree(px_process.get_all(), search)
if not print_me:
print(f"No processes found matching <{search}>", file=sys.stderr)
return

for line in print_me:
print(line)


def _generate_tree(processes: List[px_process.PxProcess], search: str) -> List[str]:
if not processes:
return []

# Only print subtrees needed for showing all search hits and their children.
#
# We do that by starting at the search hits and walking up the tree from all
Expand All @@ -24,6 +34,7 @@ def _generate_tree(processes: List[px_process.PxProcess], search: str) -> List[s

_mark_children(process, show_pids)

# Walk up the tree from this process, marking each process for display
if process and process.parent:
process = process.parent
while process:
Expand All @@ -34,8 +45,9 @@ def _generate_tree(processes: List[px_process.PxProcess], search: str) -> List[s
break
process = process.parent

if not processes:
return []
# Search found nothing
if not show_pids:
return []

lines = []
coalescer = Coalescer(0)
Expand Down
31 changes: 31 additions & 0 deletions tests/px_tree_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,37 @@ def test_search():
) == ["root(1)", f" {px_terminal.bold('find-me')}(2)"]


def test_no_search():
assert px_tree._generate_tree(
resolve(
[
testutils.create_process(pid=1, ppid=0, commandline="root"),
testutils.create_process(pid=2, ppid=1, commandline="find-me"),
testutils.create_process(pid=3, ppid=1, commandline="uninteresting"),
]
),
"",
) == ["root(1)", " find-me(2)", " uninteresting(3)"]


def test_search_no_matches():
assert (
px_tree._generate_tree(
resolve(
[
testutils.create_process(pid=1, ppid=0, commandline="root"),
testutils.create_process(pid=2, ppid=1, commandline="find-me"),
testutils.create_process(
pid=3, ppid=1, commandline="uninteresting"
),
]
),
"not-there",
)
== []
)


def test_coalesce_no_search():
assert px_tree._generate_tree(
resolve(
Expand Down

0 comments on commit 2259495

Please sign in to comment.