7
7
from sys import stderr
8
8
from threading import Thread
9
9
from time import sleep
10
- from typing import Dict , IO , List , Tuple
10
+ from typing import Dict , IO , List , Optional , Tuple
11
11
12
12
13
13
class Checksum ():
@@ -44,21 +44,26 @@ def __init__(self, path: str, threshold: int = 200) -> None:
44
44
self .filesize = self ._path .stat ().st_size
45
45
self .threshold = threshold
46
46
47
- def _progress (self , file : IO ) -> None :
47
+ def _progress (self , file : IO ) -> Optional [ Thread ] :
48
48
def _p (file : IO ) -> None :
49
49
while not file .closed :
50
50
print (f"{ int (file .tell () / self .filesize * 100 )} %" , end = "\r " , file = stderr )
51
51
sleep (0.2 )
52
52
print (" " , end = "\r " , file = stderr ) # clear the progress display
53
+ thread = None
53
54
if self .filesize > self .threshold * 1024 * 1024 :
54
- Thread (target = _p , args = (file ,)).start ()
55
+ thread = Thread (target = _p , args = (file ,))
56
+ thread .start ()
57
+ return thread
55
58
56
59
def _hashlib_compute (self , name : str ) -> str :
57
60
result = hashlib .new (name )
58
61
with self ._path .open ("rb" ) as lines :
59
- self ._progress (lines )
62
+ thread = self ._progress (lines )
60
63
for line in lines :
61
64
result .update (line )
65
+ if thread :
66
+ thread .join ()
62
67
return result .hexdigest ()
63
68
64
69
def _zlib_compute (self , name : str ) -> str :
@@ -69,9 +74,11 @@ def _zlib_compute(self, name: str) -> str:
69
74
result = 0
70
75
update = zlib .crc32
71
76
with self ._path .open ("rb" ) as lines :
72
- self ._progress (lines )
77
+ thread = self ._progress (lines )
73
78
for line in lines :
74
79
result = update (line , result )
80
+ if thread :
81
+ thread .join ()
75
82
return hex (result )[2 :].zfill (8 )
76
83
77
84
def compute (self , algorithm : str ) -> str :
0 commit comments