Skip to content

Commit efbcbbc

Browse files
committed
Improve error handling and path validation
Updated compression level validation to use a fallback max level if the zstandard constant is unavailable. Added checks to ensure paths are not None before file operations in the extract_archive function, improving robustness and preventing potential errors.
1 parent 320ed0a commit efbcbbc

File tree

1 file changed

+22
-9
lines changed

1 file changed

+22
-9
lines changed

src/tzst/core.py

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -175,10 +175,17 @@ def __init__(
175175
)
176176

177177
# Validate compression level
178-
if not 1 <= compression_level <= zstd.ZstdCompressor.max_level():
178+
try:
179+
# Try to get max_level from a constant in the zstandard module
180+
max_level = zstd.MAX_COMPRESSION_LEVEL
181+
except AttributeError:
182+
# Fallback to a hardcoded default if the constant is not found
183+
max_level = 22 # Common max level for zstd
184+
185+
if not 1 <= compression_level <= max_level:
179186
raise ValueError(
180187
f"Invalid compression level '{compression_level}'. "
181-
f"Must be between 1 and {zstd.ZstdCompressor.max_level()}."
188+
f"Must be between 1 and {max_level}."
182189
)
183190

184191
# Check for unsupported modes immediately
@@ -806,8 +813,10 @@ def extract_archive(
806813

807814
fileobj = archive.extractfile(member)
808815
if fileobj:
809-
with open(target_path, "wb") as f:
810-
f.write(fileobj.read())
816+
# Ensure target_path is not None before opening
817+
if target_path:
818+
with open(target_path, "wb") as f:
819+
f.write(fileobj.read())
811820
else:
812821
# Extract with full directory structure
813822
if members:
@@ -836,10 +845,14 @@ def extract_archive(
836845
break
837846

838847
# For AUTO_RENAME, we need to adjust the member path
839-
if actual_resolution in (
840-
ConflictResolution.AUTO_RENAME,
841-
ConflictResolution.AUTO_RENAME_ALL,
842-
):
848+
if (
849+
actual_resolution
850+
in (
851+
ConflictResolution.AUTO_RENAME,
852+
ConflictResolution.AUTO_RENAME_ALL,
853+
)
854+
and final_path
855+
): # Ensure final_path is not None
843856
# Create parent directories for renamed file
844857
final_path.parent.mkdir(parents=True, exist_ok=True)
845858
# Extract to temporary location, then move
@@ -907,7 +920,7 @@ def extract_archive(
907920
):
908921
target_path.unlink() # Remove existing file
909922

910-
if target_path:
923+
if target_path: # Ensure target_path is not None
911924
temp_file.rename(target_path)
912925
finally:
913926
# Clean up temp directory

0 commit comments

Comments
 (0)