-
Notifications
You must be signed in to change notification settings - Fork 0
/
checkdisk.py
141 lines (111 loc) · 4.47 KB
/
checkdisk.py
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
import logging
import os
import re
import subprocess
import sys
from argparse import ArgumentParser, Namespace
from locale import getpreferredencoding
from pathlib import Path
from typing import List, NamedTuple
from rich.console import Console
from rich.panel import Panel
from rich.prompt import Confirm
class Line(NamedTuple):
text: bytes
end: bytes
class BinaryLineBuffer:
cp = re.compile(rb"([^\r\n]*)(\r\n|\r|\n)")
def __init__(self):
# rewrite using deque[bytes]
self.buffer = bytearray()
def append(self, data: bytes) -> None:
self.buffer.extend(data)
def get(self, full=False) -> List[Line]:
matches = list(self.cp.finditer(self.buffer))
if not matches:
return []
if not full and matches[-1].end() == len(self.buffer) and matches[-1].group(2) == b"\r":
# keep last match since a \n might still follow
out = [Line._make(m.groups()) for m in matches[:-1]]
if len(matches) >= 2:
del self.buffer[: matches[-2].end()]
return out
else:
out = [Line._make(m.groups()) for m in matches]
if full and matches[-1].end() != len(self.buffer):
out.append(Line(self.buffer[matches[-1].end() :], b""))
self.buffer.clear()
else:
del self.buffer[: matches[-1].end()]
return out
def _print_line(cout, cerr, textb: bytes, endb: bytes, encoding: str) -> None:
assert b"\n" not in textb, textb
text = textb.decode(encoding)
end = endb.decode("ascii")
if end == "\r":
cerr.print(text, end="\r")
else: # \n or \r\n
cout.print(text, end="\n")
def check_disks(drives: List[str]) -> None:
cout = Console(soft_wrap=True, markup=False)
cerr = Console(soft_wrap=True, stderr=True, markup=False)
for i, drive in enumerate(drives, 1):
if not re.match("^[a-zA-Z]:$", drive):
msg = f"Invalid drive letter: {drive}"
raise ValueError(msg)
cout.print(Panel(drive))
cmd = ["chkdsk", drive, "/V"]
stderr = Path("chkdsk.stderr")
encoding = getpreferredencoding()
try:
with stderr.open("ab") as fw:
with subprocess.Popen(cmd, bufsize=0, stdout=subprocess.PIPE, stderr=fw) as proc:
assert proc.stdout is not None # for mypy
lb = BinaryLineBuffer()
while True:
chunk = proc.stdout.read(1024)
if not chunk:
for textb, endb in lb.get(full=True):
_print_line(cout, cerr, textb, endb, encoding)
break
lb.append(chunk)
for textb, endb in lb.get():
_print_line(cout, cerr, textb, endb, encoding)
assert proc.returncode in (0, 3), proc.returncode
if proc.returncode != 0:
logging.error("Checking `%s` returned %s", drive, proc.returncode)
assert not stderr.read_bytes()
except Exception:
logging.exception("Running chkdsk on %s failed", drive)
if i < len(drives) and args.ask_continue:
if not Confirm.ask("Continue with next drive?"):
break
def main(args: Namespace) -> None:
if args.select is None:
drives = []
if not hasattr(os, "listdrives"): # Python 3.12+
from genutility.win.device import get_logical_drives
listdrives = get_logical_drives
else:
listdrives = os.listdrives
for drive in listdrives():
drive = drive.rstrip("\\")
if drive not in args.ignore:
drives.append(drive)
check_disks(drives)
else:
check_disks(args.select)
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument("--ask-continue", action="store_true", help="Ask to continue after every checked drive")
parser.add_argument("--ignore", nargs="+", default=(), help="Drives not to scan, only used if --select is not")
parser.add_argument(
"--select", nargs="+", help="Select drive letters to scan, eg. `C: D:`. If not used all drives are scanned."
)
args = parser.parse_args()
logging.basicConfig(level=logging.INFO)
try:
main(args)
except KeyboardInterrupt:
print("", file=sys.stderr)
logging.warning("Interrupted.")