Potential NameError in copy_file() exception handler
Priority: Medium Component: fs.py Type: Bug
Description
In the copy_file() function, if the os.open() call for the output file fails, the variable fout will be uninitialized, causing a NameError when the finally block tries to close it.
Location
curateipsum/fs.py:182-198
Current Code
defcopy_file(src,dst):try:fin=os.open(src,READ_FLAGS)fstat=os.fstat(fin)fout=os.open(dst,WRITE_FLAGS,fstat.st_mode)# Could fail hereforxiniter(lambda:os.read(fin,BUFFER_SIZE),b""):os.write(fout,x)finally:try:os.close(fout)# NameError if fout wasn't createdexcept(OSError,UnboundLocalError):pass
Problem
If line 187 fails, fout is never assigned, leading to UnboundLocalError in the finally block (which is caught but indicates poor code structure).
Medium - Code works but is fragile and harder to maintain.
# Potential NameError in copy_file() exception handler
**Priority:** Medium
**Component:** fs.py
**Type:** Bug
## Description
In the `copy_file()` function, if the `os.open()` call for the output file fails, the variable `fout` will be uninitialized, causing a `NameError` when the finally block tries to close it.
## Location
`curateipsum/fs.py:182-198`
## Current Code
```python
def copy_file(src, dst):
try:
fin = os.open(src, READ_FLAGS)
fstat = os.fstat(fin)
fout = os.open(dst, WRITE_FLAGS, fstat.st_mode) # Could fail here
for x in iter(lambda: os.read(fin, BUFFER_SIZE), b""):
os.write(fout, x)
finally:
try:
os.close(fout) # NameError if fout wasn't created
except (OSError, UnboundLocalError):
pass
```
## Problem
If line 187 fails, `fout` is never assigned, leading to `UnboundLocalError` in the finally block (which is caught but indicates poor code structure).
## Proposed Solution
```python
def copy_file(src, dst):
fin = None
fout = None
try:
fin = os.open(src, READ_FLAGS)
fstat = os.fstat(fin)
fout = os.open(dst, WRITE_FLAGS, fstat.st_mode)
for x in iter(lambda: os.read(fin, BUFFER_SIZE), b""):
os.write(fout, x)
finally:
if fout is not None:
try:
os.close(fout)
except OSError:
pass
if fin is not None:
try:
os.close(fin)
except OSError:
pass
```
## Impact
**Medium** - Code works but is fragile and harder to maintain.
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.
Potential NameError in copy_file() exception handler
Priority: Medium
Component: fs.py
Type: Bug
Description
In the
copy_file()function, if theos.open()call for the output file fails, the variablefoutwill be uninitialized, causing aNameErrorwhen the finally block tries to close it.Location
curateipsum/fs.py:182-198Current Code
Problem
If line 187 fails,
foutis never assigned, leading toUnboundLocalErrorin the finally block (which is caught but indicates poor code structure).Proposed Solution
Impact
Medium - Code works but is fragile and harder to maintain.