Fix potential NameError in copy_file exception handler

Initialize file descriptors to None before opening to prevent
UnboundLocalError in the finally block if file opening fails.

Changes:
- Initialize fin = None and fout = None at function start
- Check if descriptors are not None before closing
- Remove UnboundLocalError from exception handling (no longer needed)

This improves code quality by eliminating the need to catch an error
that indicates a logic bug. The existing tests verify correct behavior.

Fixes #6
This commit is contained in:
2026-02-03 22:20:52 -08:00
parent 7c59bbc90b
commit 5dc9235992

View File

@@ -181,6 +181,8 @@ BUFFER_SIZE = 128 * 1024
def copy_file(src, dst):
""" Copy file from src to dst. Faster than shutil.copy. """
fin = None
fout = None
try:
fin = os.open(src, READ_FLAGS)
fstat = os.fstat(fin)
@@ -188,14 +190,16 @@ def copy_file(src, dst):
for x in iter(lambda: os.read(fin, BUFFER_SIZE), b""):
os.write(fout, x)
finally:
try:
os.close(fout)
except (OSError, UnboundLocalError):
pass
try:
os.close(fin)
except (OSError, UnboundLocalError):
pass
if fout is not None:
try:
os.close(fout)
except OSError:
pass
if fin is not None:
try:
os.close(fin)
except OSError:
pass
def copy_direntry(entry: Union[os.DirEntry, PseudoDirEntry], dst_path):