Skip to content

fix(cli): stop leaking a file handle in create-settings-file - #365

Open
Eljees wants to merge 1 commit into
protectai:mainfrom
Eljees:fix/create-settings-file-handle-226
Open

fix(cli): stop leaking a file handle in create-settings-file#365
Eljees wants to merge 1 commit into
protectai:mainfrom
Eljees:fix/create-settings-file-handle-226

Conversation

@Eljees

@Eljees Eljees commented Jul 28, 2026

Copy link
Copy Markdown

Fixes #226

create_settings used open() as an existence check and never closed the handle — that is the CodeQL
finding at cli.py:177:

try:
    open(settings_path, encoding="utf-8")
    if force:
        ...
except FileNotFoundError:
    ...

Replaced with an explicit os.path.exists() check, so no handle is opened for the check at all, and the
write path exists once instead of twice. Behaviour is unchanged: without --force an existing file is kept
and the warning is logged; with --force, or when the file does not exist, the default settings are written.
The redundant settings_file.close() calls inside the with blocks went away with the duplication.

Test

tests/test_cli.py (new): invoking the command against an existing file without --force leaves the file
untouched — this is the branch the fix rewrote.

PYTHONPATH=/src python -m pytest tests/test_cli.py -q   ->  1 passed

One thing I could not cover, and why

I wanted to also assert that the file is written when it does not exist, but that path is currently broken
on main, independently of this PR:

$ python -c "from modelscan.settings import SettingsUtils; SettingsUtils.get_default_settings_as_toml()"
TypeError: Keys must be strings

DEFAULT_SETTINGS["middlewares"]["modelscan.middlewares.FormatViaExtensionMiddleware"]["formats"] is keyed by
SupportedModelFormats.*, which are Property instances, and tomlkit.dumps() only accepts string keys — so
modelscan create-settings-file fails for everyone right now (tomlkit 0.13, within the >=0.12.3,<0.14.0 pin).
That is a separate bug from this one; happy to open an issue for it, or send a fix if you tell me which shape
you prefer — string keys in DEFAULT_SETTINGS, or a conversion at serialisation time so the in-memory lookups
keep working.

AI-assisted (LLM used for drafting); the change, the test run and the reproduction above are mine.

The existence check opened the settings file and never closed it (CodeQL: file is opened but not closed). Use os.path.exists instead and keep a single write path.

Signed-off-by: Eljees <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CodeQL Finding: File is not always closed- file: cli.py

1 participant