lib/addoninfo.cpp: When loading a JSON addon, test 'script' key. (#5797)

In case a user accidentally uses a wrong JSON file (e.g. naming.json,
which is the config file for namingng.py), the code could give a
confusing exception. This happens when the key 'script' is not defined
as a string.

This is solved by testing the key for existence and type. In case
'script' is not a key or refers to a type other than a string, a clear
error is given, stating for example: 'Loading naming.json failed. script
must be set to a string value.'

The message is kept in line with other messages. Maybe it can be
clarified further, e.g. 'Loading naming.json failed. A key "script" must
be set with a string value referring to a Python script.' - in which
case the errors relating to other keys may also be clarified.
This commit is contained in:
thingsconnected 2023-12-25 05:49:17 +01:00 committed by GitHub
parent a7baf88d4f
commit 403e7f1f7d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 0 deletions

View File

@ -87,6 +87,11 @@ static std::string parseAddonInfo(AddonInfo& addoninfo, const picojson::value &j
return "";
}
if (!obj.count("script") || !obj["script"].is<std::string>())
{
return "Loading " + fileName + " failed. script must be set to a string value.";
}
return addoninfo.getAddonInfo(obj["script"].get<std::string>(), exename);
}

View File

@ -278,6 +278,22 @@ extern const char* f()
assert stderr == '{}:4:12: warning: strerror is MT-unsafe [threadsafety-unsafe-call]\n'.format(test_file)
def test_addon_invalidjson(tmpdir):
addon_file = os.path.join(tmpdir, 'invalid.json')
with open(addon_file, 'wt') as f:
f.write("""
{
"Script": "addons/something.py"
}
""")
args = ['--addon={}'.format(addon_file), '--enable=all', 'nonexistent.cpp']
exitcode, stdout, stderr = cppcheck(args)
assert exitcode != 0
assert stdout == 'Loading {} failed. script must be set to a string value.\n'.format(addon_file)
def test_addon_naming(tmpdir):
# the addon does nothing without a config
addon_file = os.path.join(tmpdir, 'naming1.json')