unlatch 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- unlatch/__init__.py +14 -0
- unlatch/__main__.py +82 -0
- unlatch/assets/unlatch.ico +0 -0
- unlatch/assets/unlatch.svg +8 -0
- unlatch/cli.py +136 -0
- unlatch/commands.py +162 -0
- unlatch/core/__init__.py +1 -0
- unlatch/core/actions.py +137 -0
- unlatch/core/finder.py +107 -0
- unlatch/core/handle_table.py +156 -0
- unlatch/core/instances.py +70 -0
- unlatch/core/matching.py +137 -0
- unlatch/core/watchdog.py +152 -0
- unlatch/engine.py +50 -0
- unlatch/exceptions.py +23 -0
- unlatch/gui/__init__.py +1 -0
- unlatch/gui/app.py +112 -0
- unlatch/gui/instance.py +125 -0
- unlatch/gui/prompts.py +37 -0
- unlatch/gui/scanner.py +93 -0
- unlatch/gui/window.py +700 -0
- unlatch/models.py +129 -0
- unlatch/native/__init__.py +1 -0
- unlatch/native/elevation.py +47 -0
- unlatch/native/handles.py +237 -0
- unlatch/native/modules.py +116 -0
- unlatch/native/processes.py +72 -0
- unlatch/native/shell.py +106 -0
- unlatch/native/win32.py +195 -0
- unlatch/output.py +82 -0
- unlatch/py.typed +0 -0
- unlatch/targets.py +40 -0
- unlatch-0.1.0.dist-info/METADATA +137 -0
- unlatch-0.1.0.dist-info/RECORD +37 -0
- unlatch-0.1.0.dist-info/WHEEL +4 -0
- unlatch-0.1.0.dist-info/entry_points.txt +6 -0
- unlatch-0.1.0.dist-info/licenses/LICENSE +21 -0
unlatch/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Unlatch: find and free whatever is holding a file or folder on Windows."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
VERSION = version("unlatch")
|
|
9
|
+
except PackageNotFoundError: # Running from a source tree without metadata
|
|
10
|
+
VERSION = "0.0.0+unknown"
|
|
11
|
+
|
|
12
|
+
APP_NAME = "Unlatch"
|
|
13
|
+
|
|
14
|
+
__all__ = ["APP_NAME", "VERSION"]
|
unlatch/__main__.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Entry points for the ``unlatch`` and ``unlatch-gui`` commands."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import sys
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
from importlib.resources import files
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from unlatch.cli import CommandLine
|
|
12
|
+
from unlatch.commands import EXIT_ERROR, CommandRunner, Services, Shell
|
|
13
|
+
from unlatch.engine import Engine
|
|
14
|
+
from unlatch.exceptions import AppError
|
|
15
|
+
from unlatch.targets import TargetResolver
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger("unlatch")
|
|
18
|
+
|
|
19
|
+
EXIT_INTERRUPTED = 130
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Application:
|
|
23
|
+
"""Command-line application."""
|
|
24
|
+
|
|
25
|
+
def __init__(self, services: Services | None = None) -> None:
|
|
26
|
+
self._services = services or self.default_services()
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
def main(cls) -> None:
|
|
30
|
+
"""Run ``unlatch`` with the process arguments and exit."""
|
|
31
|
+
sys.exit(cls().run(sys.argv[1:]))
|
|
32
|
+
|
|
33
|
+
@classmethod
|
|
34
|
+
def gui_main(cls) -> None:
|
|
35
|
+
"""Run ``unlatch-gui``: open the window on any paths given."""
|
|
36
|
+
sys.exit(cls().run(["gui", *sys.argv[1:]]))
|
|
37
|
+
|
|
38
|
+
def run(self, argv: Sequence[str]) -> int:
|
|
39
|
+
"""Parse, execute, and return the exit code."""
|
|
40
|
+
settings = CommandLine().parse(argv)
|
|
41
|
+
logging.basicConfig(
|
|
42
|
+
level=settings.log_level,
|
|
43
|
+
format="%(levelname)s %(name)s: %(message)s",
|
|
44
|
+
stream=sys.stderr,
|
|
45
|
+
)
|
|
46
|
+
runner = CommandRunner(self._services, sys.stdout)
|
|
47
|
+
try:
|
|
48
|
+
return runner.run(settings)
|
|
49
|
+
except AppError as err:
|
|
50
|
+
logger.error("%s", err) # noqa: TRY400 - expected errors need no trace
|
|
51
|
+
return EXIT_ERROR
|
|
52
|
+
except KeyboardInterrupt:
|
|
53
|
+
return EXIT_INTERRUPTED
|
|
54
|
+
|
|
55
|
+
@staticmethod
|
|
56
|
+
def icon_path() -> Path:
|
|
57
|
+
"""Location of the packaged Windows icon."""
|
|
58
|
+
return Path(str(files("unlatch") / "assets" / "unlatch.ico"))
|
|
59
|
+
|
|
60
|
+
@classmethod
|
|
61
|
+
def default_services(cls) -> Services:
|
|
62
|
+
"""Services backed by the real Windows implementations."""
|
|
63
|
+
|
|
64
|
+
def shell() -> Shell:
|
|
65
|
+
"""Create the registry integration (Windows only)."""
|
|
66
|
+
from unlatch.native.shell import ShellIntegration # noqa: PLC0415
|
|
67
|
+
|
|
68
|
+
return ShellIntegration(icon=cls.icon_path())
|
|
69
|
+
|
|
70
|
+
def gui(paths: Sequence[str]) -> int:
|
|
71
|
+
"""Open the window."""
|
|
72
|
+
from unlatch.gui.app import GuiApplication # noqa: PLC0415
|
|
73
|
+
|
|
74
|
+
return GuiApplication.launch(paths)
|
|
75
|
+
|
|
76
|
+
return Services(
|
|
77
|
+
engine=Engine.create, resolver=TargetResolver(), shell=shell, gui=gui
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
if __name__ == "__main__":
|
|
82
|
+
Application.main()
|
|
Binary file
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
|
|
2
|
+
<title>Unlatch</title>
|
|
3
|
+
<rect x="4" y="4" width="56" height="56" rx="13" fill="#1B2A4A"/>
|
|
4
|
+
<path d="M23 31 V20.5 a9 9 0 0 1 18 0 V24" fill="none" stroke="#EEF2F8" stroke-width="5" stroke-linecap="round"/>
|
|
5
|
+
<rect x="15" y="30" width="34" height="24" rx="5" fill="#F2B33D"/>
|
|
6
|
+
<circle cx="32" cy="39.5" r="3.8" fill="#1B2A4A"/>
|
|
7
|
+
<path d="M30.4 41 h3.2 l1 7 h-5.2 z" fill="#1B2A4A"/>
|
|
8
|
+
</svg>
|
unlatch/cli.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""Command-line parsing into typed settings."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from enum import StrEnum
|
|
9
|
+
|
|
10
|
+
from unlatch import APP_NAME, VERSION
|
|
11
|
+
|
|
12
|
+
LOG_LEVELS = ("DEBUG", "INFO", "WARNING", "ERROR")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Command(StrEnum):
|
|
16
|
+
"""Top-level subcommands."""
|
|
17
|
+
|
|
18
|
+
SCAN = "scan"
|
|
19
|
+
CHECK = "check"
|
|
20
|
+
KILL = "kill"
|
|
21
|
+
RELEASE = "release"
|
|
22
|
+
GUI = "gui"
|
|
23
|
+
SHELL = "shell"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ShellAction(StrEnum):
|
|
27
|
+
"""Explorer integration actions."""
|
|
28
|
+
|
|
29
|
+
INSTALL = "install"
|
|
30
|
+
UNINSTALL = "uninstall"
|
|
31
|
+
STATUS = "status"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True, slots=True)
|
|
35
|
+
class Settings:
|
|
36
|
+
"""Everything one invocation asked for."""
|
|
37
|
+
|
|
38
|
+
command: Command
|
|
39
|
+
paths: tuple[str, ...] = ()
|
|
40
|
+
as_json: bool = False
|
|
41
|
+
assume_yes: bool = False
|
|
42
|
+
shell_action: ShellAction | None = None
|
|
43
|
+
log_level: str = "WARNING"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class CommandLine:
|
|
47
|
+
"""Parser for the ``unlatch`` command."""
|
|
48
|
+
|
|
49
|
+
def __init__(self) -> None:
|
|
50
|
+
self._parser = self._build_parser()
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def parser(self) -> argparse.ArgumentParser:
|
|
54
|
+
"""The underlying parser (for help text)."""
|
|
55
|
+
return self._parser
|
|
56
|
+
|
|
57
|
+
def parse(self, argv: Sequence[str]) -> Settings:
|
|
58
|
+
"""Parse arguments; no arguments at all opens the GUI."""
|
|
59
|
+
args = self._parser.parse_args(list(argv) or ["gui"])
|
|
60
|
+
command = Command(args.command)
|
|
61
|
+
shell_action = getattr(args, "action", None)
|
|
62
|
+
return Settings(
|
|
63
|
+
command=command,
|
|
64
|
+
paths=tuple(getattr(args, "paths", ()) or ()),
|
|
65
|
+
as_json=bool(getattr(args, "json", False)),
|
|
66
|
+
assume_yes=bool(getattr(args, "yes", False)),
|
|
67
|
+
shell_action=ShellAction(shell_action) if shell_action else None,
|
|
68
|
+
log_level=str(args.log_level),
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
@staticmethod
|
|
72
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
73
|
+
"""Define the subcommands and their arguments."""
|
|
74
|
+
parser = argparse.ArgumentParser(
|
|
75
|
+
prog="unlatch",
|
|
76
|
+
description=f"{APP_NAME}: find and free whatever is holding a file "
|
|
77
|
+
"or folder on Windows.",
|
|
78
|
+
)
|
|
79
|
+
parser.add_argument(
|
|
80
|
+
"--version", action="version", version=f"%(prog)s {VERSION}"
|
|
81
|
+
)
|
|
82
|
+
parser.add_argument(
|
|
83
|
+
"--log-level",
|
|
84
|
+
choices=LOG_LEVELS,
|
|
85
|
+
default="WARNING",
|
|
86
|
+
type=str.upper,
|
|
87
|
+
help="diagnostic detail on stderr (default: %(default)s)",
|
|
88
|
+
)
|
|
89
|
+
commands = parser.add_subparsers(
|
|
90
|
+
dest="command", required=True, metavar="COMMAND"
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
scan = commands.add_parser(Command.SCAN, help="list what holds the paths")
|
|
94
|
+
CommandLine._add_paths(scan)
|
|
95
|
+
scan.add_argument("--json", action="store_true", help="print JSON")
|
|
96
|
+
|
|
97
|
+
check = commands.add_parser(
|
|
98
|
+
Command.CHECK,
|
|
99
|
+
help="exit 0 if the paths are free, 3 if something holds them",
|
|
100
|
+
)
|
|
101
|
+
CommandLine._add_paths(check)
|
|
102
|
+
|
|
103
|
+
kill = commands.add_parser(
|
|
104
|
+
Command.KILL, help="end every process holding the paths"
|
|
105
|
+
)
|
|
106
|
+
CommandLine._add_paths(kill)
|
|
107
|
+
CommandLine._add_yes(kill)
|
|
108
|
+
|
|
109
|
+
release = commands.add_parser(
|
|
110
|
+
Command.RELEASE,
|
|
111
|
+
help="close the open handles on the paths without ending processes "
|
|
112
|
+
"(advanced: the program may misbehave)",
|
|
113
|
+
)
|
|
114
|
+
CommandLine._add_paths(release)
|
|
115
|
+
CommandLine._add_yes(release)
|
|
116
|
+
|
|
117
|
+
gui = commands.add_parser(Command.GUI, help="open the window (the default)")
|
|
118
|
+
gui.add_argument("paths", nargs="*", metavar="PATH", help="file or folder")
|
|
119
|
+
|
|
120
|
+
shell = commands.add_parser(
|
|
121
|
+
Command.SHELL, help="manage the Explorer menu entry"
|
|
122
|
+
)
|
|
123
|
+
shell.add_argument("action", choices=[action.value for action in ShellAction])
|
|
124
|
+
return parser
|
|
125
|
+
|
|
126
|
+
@staticmethod
|
|
127
|
+
def _add_paths(parser: argparse.ArgumentParser) -> None:
|
|
128
|
+
"""Add the required path arguments."""
|
|
129
|
+
parser.add_argument("paths", nargs="+", metavar="PATH", help="file or folder")
|
|
130
|
+
|
|
131
|
+
@staticmethod
|
|
132
|
+
def _add_yes(parser: argparse.ArgumentParser) -> None:
|
|
133
|
+
"""Add the confirmation bypass flag."""
|
|
134
|
+
parser.add_argument(
|
|
135
|
+
"-y", "--yes", action="store_true", help="do not ask for confirmation"
|
|
136
|
+
)
|
unlatch/commands.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""Run CLI commands against the engine."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from collections.abc import Callable, Sequence
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Protocol, TextIO
|
|
9
|
+
|
|
10
|
+
from unlatch.cli import Command, Settings, ShellAction
|
|
11
|
+
from unlatch.core.actions import ActionSummary
|
|
12
|
+
from unlatch.core.matching import TargetSpec
|
|
13
|
+
from unlatch.engine import Engine
|
|
14
|
+
from unlatch.exceptions import AppError
|
|
15
|
+
from unlatch.models import ScanReport
|
|
16
|
+
from unlatch.output import ReportFormatter
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
EXIT_OK = 0
|
|
21
|
+
EXIT_ERROR = 1
|
|
22
|
+
EXIT_HELD = 3
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Shell(Protocol):
|
|
26
|
+
"""Explorer integration operations."""
|
|
27
|
+
|
|
28
|
+
def install(self) -> None:
|
|
29
|
+
"""Add the menu entry."""
|
|
30
|
+
...
|
|
31
|
+
|
|
32
|
+
def uninstall(self) -> None:
|
|
33
|
+
"""Remove the menu entry."""
|
|
34
|
+
...
|
|
35
|
+
|
|
36
|
+
def is_installed(self) -> bool:
|
|
37
|
+
"""True when the entry is present."""
|
|
38
|
+
...
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Resolver(Protocol):
|
|
42
|
+
"""Turns raw paths into targets."""
|
|
43
|
+
|
|
44
|
+
def resolve(self, paths: Sequence[str]) -> list[TargetSpec]:
|
|
45
|
+
"""Resolve and validate paths."""
|
|
46
|
+
...
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True, slots=True)
|
|
50
|
+
class Services:
|
|
51
|
+
"""Factories for everything a command may need, so tests can swap them."""
|
|
52
|
+
|
|
53
|
+
engine: Callable[[], Engine]
|
|
54
|
+
resolver: Resolver
|
|
55
|
+
shell: Callable[[], Shell]
|
|
56
|
+
gui: Callable[[Sequence[str]], int]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class CommandRunner:
|
|
60
|
+
"""Execute parsed settings and return a process exit code."""
|
|
61
|
+
|
|
62
|
+
def __init__(
|
|
63
|
+
self,
|
|
64
|
+
services: Services,
|
|
65
|
+
out: TextIO,
|
|
66
|
+
prompt: Callable[[str], str] = input,
|
|
67
|
+
) -> None:
|
|
68
|
+
self._services = services
|
|
69
|
+
self._out = out
|
|
70
|
+
self._prompt = prompt
|
|
71
|
+
|
|
72
|
+
def run(self, settings: Settings) -> int:
|
|
73
|
+
"""Dispatch to the handler for the command."""
|
|
74
|
+
match settings.command:
|
|
75
|
+
case Command.GUI:
|
|
76
|
+
return self._services.gui(settings.paths)
|
|
77
|
+
case Command.SHELL:
|
|
78
|
+
return self._shell(settings.shell_action or ShellAction.STATUS)
|
|
79
|
+
case Command.SCAN:
|
|
80
|
+
return self._scan(settings)
|
|
81
|
+
case Command.CHECK:
|
|
82
|
+
return self._check(settings)
|
|
83
|
+
case Command.KILL | Command.RELEASE:
|
|
84
|
+
return self._free(settings)
|
|
85
|
+
|
|
86
|
+
def _scan(self, settings: Settings) -> int:
|
|
87
|
+
"""Print the report."""
|
|
88
|
+
report = self._report(self._services.engine(), settings.paths)
|
|
89
|
+
formatter = ReportFormatter.json if settings.as_json else ReportFormatter.text
|
|
90
|
+
self._out.write(formatter(report))
|
|
91
|
+
return EXIT_OK
|
|
92
|
+
|
|
93
|
+
def _check(self, settings: Settings) -> int:
|
|
94
|
+
"""Print the headline and signal through the exit code."""
|
|
95
|
+
report = self._report(self._services.engine(), settings.paths)
|
|
96
|
+
self._out.write(ReportFormatter.headline(report) + "\n")
|
|
97
|
+
return EXIT_OK if report.is_free else EXIT_HELD
|
|
98
|
+
|
|
99
|
+
def _free(self, settings: Settings) -> int:
|
|
100
|
+
"""End processes or release handles, then verify the paths are free."""
|
|
101
|
+
engine = self._services.engine()
|
|
102
|
+
report = self._report(engine, settings.paths)
|
|
103
|
+
killing = settings.command is Command.KILL
|
|
104
|
+
candidates = [p for p in report.processes if killing or p.handle_holds]
|
|
105
|
+
if not candidates:
|
|
106
|
+
self._out.write(ReportFormatter.text(report))
|
|
107
|
+
return EXIT_OK if report.is_free else EXIT_ERROR
|
|
108
|
+
self._out.write(ReportFormatter.text(report))
|
|
109
|
+
noun = "process" if len(candidates) == 1 else "processes"
|
|
110
|
+
pronoun = "it" if len(candidates) == 1 else "them"
|
|
111
|
+
question = (
|
|
112
|
+
f"End {len(candidates)} {noun}? Unsaved work in {pronoun} will be lost."
|
|
113
|
+
if killing
|
|
114
|
+
else f"Close the open handles in {len(candidates)} {noun}? "
|
|
115
|
+
"They may misbehave or crash."
|
|
116
|
+
)
|
|
117
|
+
if not settings.assume_yes and not self._confirm(question):
|
|
118
|
+
self._out.write("Nothing was changed.\n")
|
|
119
|
+
return EXIT_ERROR
|
|
120
|
+
if killing:
|
|
121
|
+
summary = engine.actions.end_all(candidates)
|
|
122
|
+
else:
|
|
123
|
+
summary = ActionSummary()
|
|
124
|
+
for process in candidates:
|
|
125
|
+
result = engine.actions.release_all(process)
|
|
126
|
+
summary.succeeded.extend(result.succeeded)
|
|
127
|
+
summary.failed.extend(result.failed)
|
|
128
|
+
verb = "Ended" if killing else "Released"
|
|
129
|
+
self._out.write(ReportFormatter.action_text(verb, summary))
|
|
130
|
+
after = engine.finder.scan(self._services.resolver.resolve(settings.paths))
|
|
131
|
+
self._out.write(ReportFormatter.headline(after) + "\n")
|
|
132
|
+
return EXIT_OK if summary.ok and after.is_free else EXIT_ERROR
|
|
133
|
+
|
|
134
|
+
def _shell(self, action: ShellAction) -> int:
|
|
135
|
+
"""Install, uninstall, or report the Explorer menu entry."""
|
|
136
|
+
shell = self._services.shell()
|
|
137
|
+
if action is ShellAction.INSTALL:
|
|
138
|
+
shell.install()
|
|
139
|
+
self._out.write("Added 'What's holding this?' to the Explorer menu.\n")
|
|
140
|
+
elif action is ShellAction.UNINSTALL:
|
|
141
|
+
shell.uninstall()
|
|
142
|
+
self._out.write("Removed the Explorer menu entry.\n")
|
|
143
|
+
else:
|
|
144
|
+
state = "installed" if shell.is_installed() else "not installed"
|
|
145
|
+
self._out.write(f"Explorer menu entry: {state}\n")
|
|
146
|
+
return EXIT_OK
|
|
147
|
+
|
|
148
|
+
def _report(self, engine: Engine, paths: Sequence[str]) -> ScanReport:
|
|
149
|
+
"""Resolve the paths and scan them."""
|
|
150
|
+
return engine.finder.scan(self._services.resolver.resolve(paths))
|
|
151
|
+
|
|
152
|
+
def _confirm(self, question: str) -> bool:
|
|
153
|
+
"""Ask a yes/no question; a closed stdin counts as an error.
|
|
154
|
+
|
|
155
|
+
Raises:
|
|
156
|
+
AppError: There is no interactive input to answer the question.
|
|
157
|
+
"""
|
|
158
|
+
try:
|
|
159
|
+
answer = self._prompt(f"{question} [y/N] ")
|
|
160
|
+
except EOFError as err:
|
|
161
|
+
raise AppError("Confirmation is required; pass --yes to proceed") from err
|
|
162
|
+
return answer.strip().casefold() in {"y", "yes"}
|
unlatch/core/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Pure, platform-independent scan logic."""
|
unlatch/core/actions.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""Verified actions that free a held path: end a process or release a handle."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from collections.abc import Iterable
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Protocol
|
|
9
|
+
|
|
10
|
+
from unlatch.core.matching import WindowsPath
|
|
11
|
+
from unlatch.exceptions import ActionError, StaleTargetError
|
|
12
|
+
from unlatch.models import Hold, HoldingProcess, HoldKind, ProcessIdentity
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ProcessControl(Protocol):
|
|
18
|
+
"""Inspect and terminate processes."""
|
|
19
|
+
|
|
20
|
+
def current_identity(self, pid: int) -> ProcessIdentity | None:
|
|
21
|
+
"""Return the identity of the process now using ``pid``, or None."""
|
|
22
|
+
...
|
|
23
|
+
|
|
24
|
+
def terminate(self, pid: int) -> None:
|
|
25
|
+
"""Terminate a process and wait briefly for it to exit."""
|
|
26
|
+
...
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class HandleControl(Protocol):
|
|
30
|
+
"""Inspect and close handles in other processes."""
|
|
31
|
+
|
|
32
|
+
def resolve(self, pid: int, handle: int) -> str | None:
|
|
33
|
+
"""Return the path a handle names now, or None if it names no file."""
|
|
34
|
+
...
|
|
35
|
+
|
|
36
|
+
def close(self, pid: int, handle: int) -> None:
|
|
37
|
+
"""Close a handle inside another process."""
|
|
38
|
+
...
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(slots=True)
|
|
42
|
+
class ActionSummary:
|
|
43
|
+
"""Outcome of an action applied to several processes."""
|
|
44
|
+
|
|
45
|
+
succeeded: list[HoldingProcess] = field(default_factory=list)
|
|
46
|
+
failed: list[tuple[HoldingProcess, str]] = field(default_factory=list)
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def ok(self) -> bool:
|
|
50
|
+
"""True when every action succeeded."""
|
|
51
|
+
return not self.failed
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class LockActions:
|
|
55
|
+
"""End processes and release handles, refusing anything that changed."""
|
|
56
|
+
|
|
57
|
+
def __init__(self, processes: ProcessControl, handles: HandleControl) -> None:
|
|
58
|
+
self._processes = processes
|
|
59
|
+
self._handles = handles
|
|
60
|
+
|
|
61
|
+
def end_process(self, process: HoldingProcess) -> None:
|
|
62
|
+
"""Terminate the process, if it is still the one that was scanned.
|
|
63
|
+
|
|
64
|
+
Raises:
|
|
65
|
+
StaleTargetError: The process exited or its PID was reused.
|
|
66
|
+
ActionError: Windows refused to terminate it.
|
|
67
|
+
"""
|
|
68
|
+
self._verify(process.identity)
|
|
69
|
+
logger.info("Ending process %s (PID %d)", process.name, process.pid)
|
|
70
|
+
self._processes.terminate(process.pid)
|
|
71
|
+
|
|
72
|
+
def end_all(self, processes: Iterable[HoldingProcess]) -> ActionSummary:
|
|
73
|
+
"""End every process, collecting failures instead of stopping."""
|
|
74
|
+
summary = ActionSummary()
|
|
75
|
+
for process in processes:
|
|
76
|
+
try:
|
|
77
|
+
self.end_process(process)
|
|
78
|
+
except ActionError as err:
|
|
79
|
+
summary.failed.append((process, str(err)))
|
|
80
|
+
else:
|
|
81
|
+
summary.succeeded.append(process)
|
|
82
|
+
return summary
|
|
83
|
+
|
|
84
|
+
def release(self, process: HoldingProcess, hold: Hold) -> None:
|
|
85
|
+
"""Close one open handle, if it still names the scanned path.
|
|
86
|
+
|
|
87
|
+
Raises:
|
|
88
|
+
ActionError: The hold is not a handle, or Windows refused.
|
|
89
|
+
StaleTargetError: The process or the handle changed since the scan.
|
|
90
|
+
"""
|
|
91
|
+
if hold.kind is not HoldKind.HANDLE or hold.handle is None:
|
|
92
|
+
raise ActionError(f"Only open handles can be released: {hold.path}")
|
|
93
|
+
self._verify(process.identity)
|
|
94
|
+
current = self._handles.resolve(process.pid, hold.handle)
|
|
95
|
+
if current is None or WindowsPath.key(current) != WindowsPath.key(hold.path):
|
|
96
|
+
raise StaleTargetError(
|
|
97
|
+
f"Handle {hold.handle:#x} in {process.name} no longer names "
|
|
98
|
+
f"{hold.path}; refresh and try again"
|
|
99
|
+
)
|
|
100
|
+
logger.info(
|
|
101
|
+
"Releasing handle %#x on %s in %s (PID %d)",
|
|
102
|
+
hold.handle,
|
|
103
|
+
hold.path,
|
|
104
|
+
process.name,
|
|
105
|
+
process.pid,
|
|
106
|
+
)
|
|
107
|
+
self._handles.close(process.pid, hold.handle)
|
|
108
|
+
|
|
109
|
+
def release_all(self, process: HoldingProcess) -> ActionSummary:
|
|
110
|
+
"""Release every handle the process holds on the targets."""
|
|
111
|
+
summary = ActionSummary()
|
|
112
|
+
errors = []
|
|
113
|
+
for hold in process.handle_holds:
|
|
114
|
+
try:
|
|
115
|
+
self.release(process, hold)
|
|
116
|
+
except ActionError as err:
|
|
117
|
+
errors.append(str(err))
|
|
118
|
+
if errors:
|
|
119
|
+
summary.failed.append((process, "; ".join(errors)))
|
|
120
|
+
else:
|
|
121
|
+
summary.succeeded.append(process)
|
|
122
|
+
return summary
|
|
123
|
+
|
|
124
|
+
def _verify(self, scanned: ProcessIdentity) -> None:
|
|
125
|
+
"""Refuse to act when the PID now belongs to a different process."""
|
|
126
|
+
current = self._processes.current_identity(scanned.pid)
|
|
127
|
+
if current is None:
|
|
128
|
+
raise StaleTargetError(
|
|
129
|
+
f"{scanned.name} (PID {scanned.pid}) is no longer running"
|
|
130
|
+
)
|
|
131
|
+
same_name = current.name.casefold() == scanned.name.casefold()
|
|
132
|
+
same_start = scanned.created is None or current.created == scanned.created
|
|
133
|
+
if not (same_name and same_start):
|
|
134
|
+
raise StaleTargetError(
|
|
135
|
+
f"PID {scanned.pid} now belongs to a different process "
|
|
136
|
+
f"({current.name}); refresh and try again"
|
|
137
|
+
)
|
unlatch/core/finder.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Combine hold sources into one scan report."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import time
|
|
7
|
+
from collections.abc import Callable, Iterable, Sequence
|
|
8
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from typing import Protocol
|
|
11
|
+
|
|
12
|
+
from unlatch.core.matching import TargetMatcher, TargetSpec
|
|
13
|
+
from unlatch.models import Hold, HoldingProcess, ProcessIdentity, ScanReport
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(slots=True)
|
|
19
|
+
class SourceResult:
|
|
20
|
+
"""Holds found by one source, keyed by PID."""
|
|
21
|
+
|
|
22
|
+
holds: dict[int, list[Hold]] = field(default_factory=dict)
|
|
23
|
+
inaccessible: set[int] = field(default_factory=set)
|
|
24
|
+
warnings: list[str] = field(default_factory=list)
|
|
25
|
+
|
|
26
|
+
def add(self, pid: int, hold: Hold) -> None:
|
|
27
|
+
"""Record one hold for a process."""
|
|
28
|
+
self.holds.setdefault(pid, []).append(hold)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class HoldSource(Protocol):
|
|
32
|
+
"""Something that can find holds on the targets, such as open handles."""
|
|
33
|
+
|
|
34
|
+
name: str
|
|
35
|
+
|
|
36
|
+
def collect(self, matcher: TargetMatcher, exclude: frozenset[int]) -> SourceResult:
|
|
37
|
+
"""Find holds on the matcher's targets, skipping excluded PIDs."""
|
|
38
|
+
...
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class ProcessDirectory(Protocol):
|
|
42
|
+
"""Looks up facts about processes."""
|
|
43
|
+
|
|
44
|
+
def identify(self, pid: int) -> ProcessIdentity:
|
|
45
|
+
"""Return the identity of a running process."""
|
|
46
|
+
...
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class LockFinder:
|
|
50
|
+
"""Scan every source and group the holds by process."""
|
|
51
|
+
|
|
52
|
+
def __init__(
|
|
53
|
+
self,
|
|
54
|
+
sources: Sequence[HoldSource],
|
|
55
|
+
processes: ProcessDirectory,
|
|
56
|
+
*,
|
|
57
|
+
elevated: Callable[[], bool],
|
|
58
|
+
exclude: Iterable[int] = (),
|
|
59
|
+
clock: Callable[[], float] = time.perf_counter,
|
|
60
|
+
) -> None:
|
|
61
|
+
self._sources = tuple(sources)
|
|
62
|
+
self._processes = processes
|
|
63
|
+
self._elevated = elevated
|
|
64
|
+
self._exclude = frozenset(exclude)
|
|
65
|
+
self._clock = clock
|
|
66
|
+
|
|
67
|
+
def scan(self, specs: Sequence[TargetSpec]) -> ScanReport:
|
|
68
|
+
"""Find every visible process that holds any of the targets."""
|
|
69
|
+
started = self._clock()
|
|
70
|
+
matcher = TargetMatcher(specs)
|
|
71
|
+
holds: dict[int, set[Hold]] = {}
|
|
72
|
+
inaccessible: set[int] = set()
|
|
73
|
+
warnings: list[str] = []
|
|
74
|
+
with ThreadPoolExecutor(
|
|
75
|
+
max(len(self._sources), 1), thread_name_prefix="unlatch-source"
|
|
76
|
+
) as pool:
|
|
77
|
+
results = list(
|
|
78
|
+
pool.map(lambda s: s.collect(matcher, self._exclude), self._sources)
|
|
79
|
+
)
|
|
80
|
+
for result in results:
|
|
81
|
+
for pid, found in result.holds.items():
|
|
82
|
+
if pid not in self._exclude:
|
|
83
|
+
holds.setdefault(pid, set()).update(found)
|
|
84
|
+
inaccessible.update(result.inaccessible)
|
|
85
|
+
warnings.extend(result.warnings)
|
|
86
|
+
processes = sorted(
|
|
87
|
+
(
|
|
88
|
+
HoldingProcess(self._processes.identify(pid), tuple(sorted(found)))
|
|
89
|
+
for pid, found in holds.items()
|
|
90
|
+
),
|
|
91
|
+
key=lambda process: (process.name.casefold(), process.pid),
|
|
92
|
+
)
|
|
93
|
+
report = ScanReport(
|
|
94
|
+
targets=matcher.targets,
|
|
95
|
+
processes=tuple(processes),
|
|
96
|
+
elevated=self._elevated(),
|
|
97
|
+
inaccessible=len(inaccessible - holds.keys() - self._exclude),
|
|
98
|
+
duration=self._clock() - started,
|
|
99
|
+
warnings=tuple(dict.fromkeys(warnings)),
|
|
100
|
+
)
|
|
101
|
+
logger.info(
|
|
102
|
+
"Scan found %d holds in %d processes in %.3f s",
|
|
103
|
+
report.hold_count,
|
|
104
|
+
len(report.processes),
|
|
105
|
+
report.duration,
|
|
106
|
+
)
|
|
107
|
+
return report
|