win-dev-doctor 0.2.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.
@@ -0,0 +1,3 @@
1
+ """win-dev-doctor: Fast, modular CLI doctor for Windows developers."""
2
+
3
+ __version__ = "0.2.0"
@@ -0,0 +1,6 @@
1
+ """Allow running via `python -m win_dev_doctor`."""
2
+
3
+ from win_dev_doctor.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
@@ -0,0 +1,5 @@
1
+ """Modular diagnostic checks for Windows developers.
2
+
3
+ Each file in this package defines one or more `BaseCheck` subclasses that are
4
+ automatically discovered by `win_dev_doctor.registry`.
5
+ """
@@ -0,0 +1,149 @@
1
+ """Discover, measure, and safely clean Windows developer package caches."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ from win_dev_doctor.models import BaseCheck, CheckResult, Status
11
+
12
+
13
+ @dataclass(slots=True)
14
+ class CacheTarget:
15
+ """A known developer cache directory."""
16
+
17
+ id: str
18
+ name: str
19
+ path: Path
20
+ size_bytes: int = 0
21
+
22
+
23
+ def format_bytes(num_bytes: int) -> str:
24
+ """Format byte count into human-readable units."""
25
+ value = float(num_bytes)
26
+ for unit in ("B", "KB", "MB", "GB", "TB"):
27
+ if value < 1024.0 or unit == "TB":
28
+ return f"{value:.1f} {unit}" if unit != "B" else f"{int(value)} B"
29
+ value /= 1024.0
30
+ return f"{num_bytes} B"
31
+
32
+
33
+ def directory_size(path: Path) -> int:
34
+ """Fast, symlink-safe recursive directory size calculation."""
35
+ total = 0
36
+ stack: list[Path] = [path]
37
+ while stack:
38
+ current = stack.pop()
39
+ try:
40
+ with os.scandir(current) as it:
41
+ for entry in it:
42
+ try:
43
+ if entry.is_symlink():
44
+ continue
45
+ if entry.is_file(follow_symlinks=False):
46
+ total += entry.stat(follow_symlinks=False).st_size
47
+ elif entry.is_dir(follow_symlinks=False):
48
+ stack.append(Path(entry.path))
49
+ except OSError:
50
+ continue
51
+ except OSError:
52
+ continue
53
+ return total
54
+
55
+
56
+ def _candidate_cache_dirs() -> list[tuple[str, str, Path]]:
57
+ home = Path.home()
58
+ local_app = Path(os.environ.get("LOCALAPPDATA", home / "AppData" / "Local"))
59
+ roaming_app = Path(os.environ.get("APPDATA", home / "AppData" / "Roaming"))
60
+
61
+ return [
62
+ ("pip", "pip cache", local_app / "pip" / "Cache"),
63
+ ("uv", "uv cache", local_app / "uv" / "cache"),
64
+ ("npm", "npm cache", local_app / "npm-cache"),
65
+ ("npm-roaming", "npm cache (Roaming)", roaming_app / "npm-cache"),
66
+ ("pnpm", "pnpm store", local_app / "pnpm" / "store"),
67
+ ("yarn", "Yarn cache", local_app / "Yarn" / "Cache"),
68
+ ("cargo", "Cargo registry cache", home / ".cargo" / "registry" / "cache"),
69
+ ("ruff", "Ruff cache", local_app / "ruff"),
70
+ ("mypy", "mypy cache", home / ".mypy_cache"),
71
+ ("nuget", "NuGet HTTP cache", local_app / "NuGet" / "v3-cache"),
72
+ ("gradle", "Gradle cache", home / ".gradle" / "caches"),
73
+ ]
74
+
75
+
76
+ def scan_caches(candidates: list[tuple[str, str, Path]] | None = None) -> list[CacheTarget]:
77
+ """Scan existing developer cache directories and calculate their sizes."""
78
+ targets: list[CacheTarget] = []
79
+ seen_paths: set[str] = set()
80
+
81
+ for cache_id, name, path in candidates or _candidate_cache_dirs():
82
+ norm = os.path.normcase(os.path.normpath(str(path)))
83
+ if norm in seen_paths or not path.exists() or not path.is_dir():
84
+ continue
85
+ seen_paths.add(norm)
86
+ size = directory_size(path)
87
+ if size > 0:
88
+ targets.append(CacheTarget(id=cache_id, name=name, path=path, size_bytes=size))
89
+
90
+ targets.sort(key=lambda t: t.size_bytes, reverse=True)
91
+ return targets
92
+
93
+
94
+ def clean_cache_dir(path: Path) -> tuple[int, int]:
95
+ """Delete contents of a cache directory safely.
96
+
97
+ Returns `(reclaimed_bytes, failed_items)`.
98
+ """
99
+ if not path.exists() or not path.is_dir():
100
+ return (0, 0)
101
+
102
+ before = directory_size(path)
103
+ failed = 0
104
+
105
+ for child in list(path.iterdir()):
106
+ try:
107
+ if child.is_symlink() or child.is_file():
108
+ child.unlink(missing_ok=True)
109
+ elif child.is_dir():
110
+ shutil.rmtree(child)
111
+ except OSError:
112
+ failed += 1
113
+
114
+ after = directory_size(path)
115
+ reclaimed = max(0, before - after)
116
+ return (reclaimed, failed)
117
+
118
+
119
+ class DevCachesCheck(BaseCheck):
120
+ id = "caches"
121
+ name = "Developer Caches"
122
+ category = "disk"
123
+ description = "Measure reclaimable space in pip, uv, npm, pnpm, cargo, gradle, and ruff caches."
124
+ order = 70
125
+
126
+ def run(self) -> CheckResult:
127
+ caches = scan_caches()
128
+ if not caches:
129
+ return CheckResult(
130
+ check_id=self.id,
131
+ name=self.name,
132
+ category=self.category,
133
+ status=Status.OK,
134
+ summary="No large developer caches found",
135
+ )
136
+
137
+ total = sum(c.size_bytes for c in caches)
138
+ details = [f"{c.name} ({c.id}): {format_bytes(c.size_bytes)} — {c.path}" for c in caches[:6]]
139
+ # Warn if caches exceed 2 GB
140
+ status = Status.WARN if total >= 2 * 1024**3 else Status.INFO
141
+ return CheckResult(
142
+ check_id=self.id,
143
+ name=self.name,
144
+ category=self.category,
145
+ status=status,
146
+ summary=f"{format_bytes(total)} across {len(caches)} cache folder(s)",
147
+ details=details,
148
+ fix_hint="Run `wdd clean --dry-run` to preview or `wdd clean` to reclaim space.",
149
+ )
@@ -0,0 +1,133 @@
1
+ """Check whether common dev folders are excluded from Windows Defender scans."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import subprocess
7
+ from pathlib import Path
8
+
9
+ from win_dev_doctor.models import BaseCheck, CheckResult, Status
10
+
11
+ # Folders under the user's home where dev work usually lives.
12
+ _DEV_FOLDER_NAMES = (
13
+ "source",
14
+ "repos",
15
+ "dev",
16
+ "projects",
17
+ "code",
18
+ "src",
19
+ ".cargo",
20
+ ".rustup",
21
+ )
22
+
23
+ _PS_COMMAND = "Get-MpPreference | Select-Object -ExpandProperty ExclusionPath"
24
+ def _classify_failure(stderr: str) -> str:
25
+ text = stderr.lower()
26
+ if "0x800106ba" in text:
27
+ return "Defender service isn't running (another antivirus may be active)"
28
+ if "must be an administrator" in text:
29
+ return "Run as Administrator to read Defender exclusions"
30
+ if "not recognized" in text or "cannot find" in text:
31
+ return "Defender PowerShell module not available"
32
+ return "Could not read Defender exclusions"
33
+
34
+ def _read_exclusions() -> tuple[list[str] | None, str]:
35
+ """Return (paths, reason). paths is None if they cannot be read."""
36
+ try:
37
+ proc = subprocess.run(
38
+ ["powershell", "-NoProfile", "-NonInteractive", "-Command", _PS_COMMAND],
39
+ capture_output=True,
40
+ text=True,
41
+ timeout=20,
42
+ check=False,
43
+ )
44
+ except (OSError, subprocess.TimeoutExpired):
45
+ return None, "PowerShell not found or timed out"
46
+ if proc.returncode != 0:
47
+ return None, _classify_failure(proc.stderr or proc.stdout)
48
+ lines = [line.strip() for line in proc.stdout.splitlines() if line.strip()]
49
+ # Without admin rights Defender answers with an "N/A: Must be an
50
+ # administrator..." placeholder instead of the real list.
51
+ if any(line.upper().startswith("N/A") for line in lines):
52
+ return None, "Run as Administrator to read Defender exclusions"
53
+ return lines, ""
54
+
55
+
56
+ def _dev_folders() -> list[Path]:
57
+ """Common dev folders that actually exist under the user's home."""
58
+ home = Path.home()
59
+ return [home / name for name in _DEV_FOLDER_NAMES if (home / name).is_dir()]
60
+
61
+
62
+ def _norm(path: str | Path) -> str:
63
+ return os.path.normcase(os.path.normpath(str(path)))
64
+
65
+
66
+ def _is_excluded(folder: Path, exclusions: list[str]) -> bool:
67
+ """True if the folder, or one of its parents, is on the exclusion list."""
68
+ target = _norm(folder)
69
+ for exclusion in exclusions:
70
+ base = _norm(exclusion).rstrip(os.sep) + os.sep
71
+ if target + os.sep == base or target.startswith(base):
72
+ return True
73
+ return False
74
+
75
+
76
+ class DefenderExclusionsCheck(BaseCheck):
77
+ id = "defender"
78
+ name = "Defender Exclusions"
79
+ category = "performance"
80
+ description = "Check whether dev folders have Windows Defender exclusions."
81
+ order = 80
82
+
83
+ def run(self) -> CheckResult:
84
+ exclusions, reason = _read_exclusions()
85
+ if exclusions is None:
86
+ return CheckResult(
87
+ check_id=self.id,
88
+ name=self.name,
89
+ category=self.category,
90
+ status=Status.INFO,
91
+ summary=reason,
92
+ details=[
93
+ "Reading the list needs an Administrator PowerShell, and "
94
+ "Windows Defender must be the active antivirus."
95
+ ],
96
+ )
97
+
98
+ folders = _dev_folders()
99
+ if not folders:
100
+ return CheckResult(
101
+ check_id=self.id,
102
+ name=self.name,
103
+ category=self.category,
104
+ status=Status.INFO,
105
+ summary="No common dev folders found",
106
+ )
107
+
108
+ missing = [f for f in folders if not _is_excluded(f, exclusions)]
109
+ if not missing:
110
+ return CheckResult(
111
+ check_id=self.id,
112
+ name=self.name,
113
+ category=self.category,
114
+ status=Status.OK,
115
+ summary=f"All {len(folders)} dev folders are excluded from Defender",
116
+ )
117
+
118
+ commands = "; ".join(f'Add-MpPreference -ExclusionPath "{f}"' for f in missing)
119
+ return CheckResult(
120
+ check_id=self.id,
121
+ name=self.name,
122
+ category=self.category,
123
+ status=Status.WARN,
124
+ summary=(
125
+ f"{len(missing)} of {len(folders)} dev folders "
126
+ "are not excluded from Defender"
127
+ ),
128
+ details=[str(f) for f in missing],
129
+ fix_hint=(
130
+ f"Run in Admin PowerShell: {commands}. "
131
+ "Exclusions reduce malware scanning, so only add folders you trust."
132
+ ),
133
+ )
@@ -0,0 +1,88 @@
1
+ """Detect common Windows developer toolchain binaries and versions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ import subprocess
7
+
8
+ from win_dev_doctor.models import BaseCheck, CheckResult, Status
9
+
10
+ TOOL_SPECS: tuple[tuple[str, list[str]], ...] = (
11
+ ("git", ["git", "--version"]),
12
+ ("python", ["python", "--version"]),
13
+ ("uv", ["uv", "--version"]),
14
+ ("node", ["node", "--version"]),
15
+ ("npm", ["npm", "--version"]),
16
+ ("rustc", ["rustc", "--version"]),
17
+ ("go", ["go", "version"]),
18
+ ("docker", ["docker", "--version"]),
19
+ ("winget", ["winget", "--version"]),
20
+ ("pwsh", ["pwsh", "--version"]),
21
+ )
22
+
23
+
24
+ def _probe_tool(binary: str, cmd: list[str]) -> str | None:
25
+ resolved = shutil.which(binary)
26
+ if not resolved:
27
+ return None
28
+ # Ignore the Microsoft Store redirect stub for python
29
+ if binary == "python" and "windowsapps" in resolved.lower():
30
+ return None
31
+ try:
32
+ proc = subprocess.run(
33
+ cmd,
34
+ capture_output=True,
35
+ text=True,
36
+ timeout=3,
37
+ check=False,
38
+ )
39
+ output = (proc.stdout or proc.stderr or "").strip()
40
+ if proc.returncode == 0 and output:
41
+ return output.splitlines()[0].strip()
42
+ except (OSError, subprocess.SubprocessError):
43
+ return None
44
+ return None
45
+
46
+
47
+ class DevToolsCheck(BaseCheck):
48
+ id = "tools"
49
+ name = "Developer Toolchain"
50
+ category = "toolchain"
51
+ description = "Detect installed CLI tools (git, python, uv, node, rustc, go, docker, winget)."
52
+ order = 30
53
+
54
+ def run(self) -> CheckResult:
55
+ found: list[str] = []
56
+ missing_core: list[str] = []
57
+ core_tools = {"git", "python", "uv", "node"}
58
+
59
+ for name, cmd in TOOL_SPECS:
60
+ version = _probe_tool(name, cmd)
61
+ if version:
62
+ found.append(f"{name}: {version}")
63
+ elif name in core_tools:
64
+ missing_core.append(name)
65
+
66
+ if not found:
67
+ return CheckResult(
68
+ check_id=self.id,
69
+ name=self.name,
70
+ category=self.category,
71
+ status=Status.FAIL,
72
+ summary="No standard developer tools found in PATH",
73
+ fix_hint="Install tools via `winget install Git.Git astral-sh.uv OpenJS.NodeJS.LTS`.",
74
+ )
75
+
76
+ status = Status.OK if not missing_core else Status.INFO
77
+ summary = f"{len(found)}/{len(TOOL_SPECS)} tools detected"
78
+ if missing_core:
79
+ summary += f" (not in PATH: {', '.join(missing_core)})"
80
+
81
+ return CheckResult(
82
+ check_id=self.id,
83
+ name=self.name,
84
+ category=self.category,
85
+ status=status,
86
+ summary=summary,
87
+ details=found,
88
+ )
@@ -0,0 +1,75 @@
1
+ """Check Windows developer environment variables for common pitfalls."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from pathlib import Path
7
+
8
+ from win_dev_doctor.models import BaseCheck, CheckResult, Status
9
+
10
+
11
+ def inspect_dev_env(environ: dict[str, str] | None = None) -> tuple[list[str], list[str]]:
12
+ """Inspect environment variables for broken temp dirs and Python/proxy conflicts.
13
+
14
+ Returns `(warnings, info_notes)`.
15
+ """
16
+ env = os.environ if environ is None else environ
17
+ warnings: list[str] = []
18
+ notes: list[str] = []
19
+
20
+ for var in ("TEMP", "TMP"):
21
+ val = env.get(var, "").strip()
22
+ if not val:
23
+ warnings.append(f"{var} is unset")
24
+ elif not Path(val).is_dir():
25
+ warnings.append(f"{var} points to missing directory: {val}")
26
+
27
+ for py_var in ("PYTHONHOME", "PYTHONPATH"):
28
+ val = env.get(py_var, "").strip()
29
+ if val:
30
+ warnings.append(
31
+ f"{py_var} is set globally ({val}) — can break isolated virtualenvs/uv"
32
+ )
33
+
34
+ proxy_vars = [
35
+ k for k in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY") if env.get(k, "").strip()
36
+ ]
37
+ if proxy_vars:
38
+ notes.append("Proxy env vars active: " + ", ".join(proxy_vars))
39
+
40
+ return warnings, notes
41
+
42
+
43
+ class DevEnvVarsCheck(BaseCheck):
44
+ id = "env"
45
+ name = "Dev Env Variables"
46
+ category = "environment"
47
+ description = "Check TEMP/TMP validity, global PYTHONHOME/PYTHONPATH leaks, and proxy variables."
48
+ order = 15
49
+
50
+ def run(self) -> CheckResult:
51
+ warnings, notes = inspect_dev_env()
52
+ if warnings:
53
+ return CheckResult(
54
+ check_id=self.id,
55
+ name=self.name,
56
+ category=self.category,
57
+ status=Status.WARN,
58
+ summary=f"{len(warnings)} environment variable issue(s) found",
59
+ details=warnings + notes,
60
+ fix_hint=(
61
+ "Fix missing TEMP/TMP folders and avoid setting PYTHONHOME/PYTHONPATH globally."
62
+ ),
63
+ )
64
+
65
+ summary = "TEMP/TMP valid; no global Python env leaks"
66
+ if notes:
67
+ summary += f" ({notes[0]})"
68
+ return CheckResult(
69
+ check_id=self.id,
70
+ name=self.name,
71
+ category=self.category,
72
+ status=Status.OK,
73
+ summary=summary,
74
+ details=notes,
75
+ )
@@ -0,0 +1,85 @@
1
+ """Check Windows-critical Git configuration settings."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ import subprocess
7
+
8
+ from win_dev_doctor.models import BaseCheck, CheckResult, Status
9
+
10
+
11
+ def _git_config_get(key: str) -> str | None:
12
+ try:
13
+ proc = subprocess.run(
14
+ ["git", "config", "--global", "--get", key],
15
+ capture_output=True,
16
+ text=True,
17
+ timeout=3,
18
+ check=False,
19
+ )
20
+ if proc.returncode == 0:
21
+ return proc.stdout.strip()
22
+ except (OSError, subprocess.SubprocessError):
23
+ return None
24
+ return None
25
+
26
+
27
+ class GitConfigCheck(BaseCheck):
28
+ id = "git"
29
+ name = "Git Windows Config"
30
+ category = "toolchain"
31
+ description = "Verify Git identity, core.longpaths, and line-ending (core.autocrlf) settings."
32
+ order = 40
33
+
34
+ def run(self) -> CheckResult:
35
+ if not shutil.which("git"):
36
+ return CheckResult(
37
+ check_id=self.id,
38
+ name=self.name,
39
+ category=self.category,
40
+ status=Status.INFO,
41
+ summary="git is not in PATH (skipped)",
42
+ fix_hint="Install Git via `winget install Git.Git`.",
43
+ )
44
+
45
+ warnings: list[str] = []
46
+ hints: list[str] = []
47
+
48
+ user_name = _git_config_get("user.name")
49
+ user_email = _git_config_get("user.email")
50
+ longpaths = _git_config_get("core.longpaths")
51
+ autocrlf = _git_config_get("core.autocrlf")
52
+
53
+ if not user_name or not user_email:
54
+ warnings.append("Global git user.name or user.email is not set")
55
+ hints.append(
56
+ 'git config --global user.name "Your Name" '
57
+ '&& git config --global user.email "you@example.com"'
58
+ )
59
+
60
+ if (longpaths or "").lower() != "true":
61
+ warnings.append(f"core.longpaths is `{longpaths or 'unset'}` (recommended: true on Windows)")
62
+ hints.append("git config --global core.longpaths true")
63
+
64
+ if autocrlf is None:
65
+ warnings.append("core.autocrlf is unset (can cause CRLF/LF diff noise across Windows/Linux)")
66
+ hints.append("git config --global core.autocrlf true")
67
+
68
+ if not warnings:
69
+ return CheckResult(
70
+ check_id=self.id,
71
+ name=self.name,
72
+ category=self.category,
73
+ status=Status.OK,
74
+ summary=f"Git configured for Windows ({user_name}, autocrlf={autocrlf}, longpaths=true)",
75
+ )
76
+
77
+ return CheckResult(
78
+ check_id=self.id,
79
+ name=self.name,
80
+ category=self.category,
81
+ status=Status.WARN,
82
+ summary=f"{len(warnings)} Git Windows setting(s) need attention",
83
+ details=warnings,
84
+ fix_hint=" ; ".join(hints),
85
+ )
@@ -0,0 +1,61 @@
1
+ """Check whether Windows Long Paths (>260 chars) are enabled in the registry."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ from win_dev_doctor.models import BaseCheck, CheckResult, Status
8
+
9
+
10
+ def is_long_paths_enabled() -> bool | None:
11
+ """Return True/False from HKLM registry, or None if unavailable."""
12
+ if sys.platform != "win32":
13
+ return None
14
+ try:
15
+ import winreg
16
+
17
+ key_path = r"SYSTEM\CurrentControlSet\Control\FileSystem"
18
+ with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_path) as key:
19
+ value, _ = winreg.QueryValueEx(key, "LongPathsEnabled")
20
+ return bool(value == 1)
21
+ except OSError:
22
+ return None
23
+
24
+
25
+ class LongPathsCheck(BaseCheck):
26
+ id = "long-paths"
27
+ name = "Windows Long Paths"
28
+ category = "windows"
29
+ description = "Verify Win32 LongPathsEnabled registry setting (prevents MAX_PATH 260-char errors)."
30
+ order = 20
31
+
32
+ def run(self) -> CheckResult:
33
+ enabled = is_long_paths_enabled()
34
+ if enabled is None:
35
+ return CheckResult(
36
+ check_id=self.id,
37
+ name=self.name,
38
+ category=self.category,
39
+ status=Status.INFO,
40
+ summary="Registry key unavailable (non-Windows or restricted access)",
41
+ )
42
+ if enabled:
43
+ return CheckResult(
44
+ check_id=self.id,
45
+ name=self.name,
46
+ category=self.category,
47
+ status=Status.OK,
48
+ summary="Long paths (>260 chars) are enabled",
49
+ )
50
+ return CheckResult(
51
+ check_id=self.id,
52
+ name=self.name,
53
+ category=self.category,
54
+ status=Status.WARN,
55
+ summary="Long paths are DISABLED (can break node_modules, cargo, pip, git)",
56
+ fix_hint=(
57
+ 'Run in Admin PowerShell: Set-ItemProperty '
58
+ '-Path "HKLM:\\SYSTEM\\CurrentControlSet\\Control\\FileSystem" '
59
+ '-Name "LongPathsEnabled" -Value 1'
60
+ ),
61
+ )