Skip to content

Commit b5d4af7

Browse files
author
Kazuki Suzuki Przyborowski
committed
Update pycatfile.py
1 parent c46e921 commit b5d4af7

1 file changed

Lines changed: 146 additions & 6 deletions

File tree

pycatfile.py

Lines changed: 146 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,8 @@ def _is_printable(ch):
346346
__use_ini_name__ = "catfile.ini"
347347
__use_json_file__ = False
348348
__use_json_name__ = "catfile.json"
349+
if(__use_ini_file__ and __use_json_name__):
350+
__use_json_name__ = False
349351
if('PYCATFILE_CONFIG_FILE' in os.environ and os.path.exists(os.environ['PYCATFILE_CONFIG_FILE']) and __use_env_file__):
350352
scriptconf = os.environ['PYCATFILE_CONFIG_FILE']
351353
else:
@@ -356,6 +358,10 @@ def _is_printable(ch):
356358
scriptconf = ""
357359
if os.path.exists(scriptconf):
358360
__config_file__ = scriptconf
361+
elif(__use_ini_file__ and not __use_json_file__):
362+
__config_file__ = os.path.join(os.path.dirname(os.path.realpath(__file__)), __use_ini_name__)
363+
elif(not __use_ini_file__ and __use_json_file__):
364+
__config_file__ = os.path.join(os.path.dirname(os.path.realpath(__file__)), __use_json_name__)
359365
else:
360366
__config_file__ = os.path.join(os.path.dirname(os.path.realpath(__file__)), __use_ini_name__)
361367
if __use_ini_file__ and os.path.exists(__config_file__):
@@ -372,19 +378,153 @@ def decode_unicode_escape(value):
372378
__use_inmemfile__ = config.getboolean('config', 'inmemfile')
373379
# Loop through all sections
374380
for section in config.sections():
381+
if section == "config":
382+
continue
383+
375384
required_keys = [
376-
"len", "hex", "ver", "name",
385+
"len", "hex", "ver", "name",
377386
"magic", "delimiter", "extension",
378387
"newstyle", "advancedlist", "altinode"
379388
]
380-
if section != "config" and all(key in config[section] for key in required_keys):
381-
delim = decode_unicode_escape(config.get(section, 'delimiter'))
382-
if(not is_only_nonprintable(delim)):
383-
delim = "\x00" * len("\x00")
384-
__file_format_multi_dict__.update( { decode_unicode_escape(config.get(section, 'magic')): {'format_name': decode_unicode_escape(config.get(section, 'name')), 'format_magic': decode_unicode_escape(config.get(section, 'magic')), 'format_len': config.getint(section, 'len'), 'format_hex': config.get(section, 'hex'), 'format_delimiter': delim, 'format_ver': config.get(section, 'ver'), 'new_style': config.getboolean(section, 'newstyle'), 'use_advanced_list': config.getboolean(section, 'advancedlist'), 'use_alt_inode': config.getboolean(section, 'altinode'), 'format_extension': decode_unicode_escape(config.get(section, 'extension')) } } )
389+
390+
# Py2+Py3 compatible key presence check
391+
has_all_required = all(config.has_option(section, key) for key in required_keys)
392+
if not has_all_required:
393+
continue
394+
395+
delim = decode_unicode_escape(config.get(section, 'delimiter'))
396+
if (not is_only_nonprintable(delim)):
397+
delim = "\x00" * len("\x00")
398+
399+
__file_format_multi_dict__.update({
400+
decode_unicode_escape(config.get(section, 'magic')): {
401+
'format_name': decode_unicode_escape(config.get(section, 'name')),
402+
'format_magic': decode_unicode_escape(config.get(section, 'magic')),
403+
'format_len': config.getint(section, 'len'),
404+
'format_hex': config.get(section, 'hex'),
405+
'format_delimiter': delim,
406+
'format_ver': config.get(section, 'ver'),
407+
'new_style': config.getboolean(section, 'newstyle'),
408+
'use_advanced_list': config.getboolean(section, 'advancedlist'),
409+
'use_alt_inode': config.getboolean(section, 'altinode'),
410+
'format_extension': decode_unicode_escape(config.get(section, 'extension')),
411+
}
412+
})
385413
if not __file_format_multi_dict__ and not __include_defaults__:
386414
__include_defaults__ = True
415+
elif __use_json_file__ and os.path.exists(__config_file__):
416+
# Prefer ujson/simplejson if available (you already have this import block above)
417+
with open(__config_file__, 'rb') as f:
418+
raw = f.read()
419+
420+
# Ensure we get a unicode string for json.loads on both Py2 and Py3
421+
if sys.version_info[0] < 3:
422+
text = raw.decode('utf-8') # Py2 bytes -> unicode
423+
else:
424+
text = raw if isinstance(raw, str) else raw.decode('utf-8')
425+
426+
cfg = json.loads(text)
427+
428+
# --- helpers: coerce + decode like your INI path ---
429+
def decode_unicode_escape(value):
430+
if sys.version_info[0] < 3: # Python 2
431+
if isinstance(value, unicode): # noqa: F821 (Py2 only)
432+
return value.encode('utf-8').decode('unicode_escape')
433+
elif isinstance(value, str):
434+
return value.decode('unicode_escape')
435+
else:
436+
return value
437+
else: # Python 3
438+
if isinstance(value, str):
439+
return bytes(value, 'UTF-8').decode('unicode_escape')
440+
else:
441+
return value
442+
443+
def _to_bool(v):
444+
# handle true/false, 1/0, and "true"/"false"/"1"/"0"
445+
if isinstance(v, bool):
446+
return v
447+
if isinstance(v, (int, float)):
448+
return bool(v)
449+
if isinstance(v, (str,)):
450+
lv = v.strip().lower()
451+
if lv in ('true', 'yes', '1'):
452+
return True
453+
if lv in ('false', 'no', '0'):
454+
return False
455+
return bool(v)
456+
457+
def _to_int(v, default=0):
458+
try:
459+
return int(v)
460+
except Exception:
461+
return default
462+
463+
def _get(section_dict, key, default=None):
464+
return section_dict.get(key, default)
465+
466+
# --- read global config (like INI's [config]) ---
467+
cfg_config = cfg.get('config', {}) or {}
468+
__file_format_default__ = decode_unicode_escape(_get(cfg_config, 'default', ''))
469+
__program_name__ = decode_unicode_escape(_get(cfg_config, 'proname', ''))
470+
__include_defaults__ = _to_bool(_get(cfg_config, 'includedef', False))
471+
__use_inmemfile__ = _to_bool(_get(cfg_config, 'inmemfile', False))
472+
473+
# --- iterate format sections (everything except "config") ---
474+
required_keys = [
475+
"len", "hex", "ver", "name",
476+
"magic", "delimiter", "extension",
477+
"newstyle", "advancedlist", "altinode"
478+
]
479+
480+
for section_name, section in cfg.items():
481+
if section_name == 'config' or not isinstance(section, dict):
482+
continue
483+
484+
# check required keys present
485+
if not all(k in section for k in required_keys):
486+
continue
487+
488+
# pull + coerce values
489+
magic = decode_unicode_escape(_get(section, 'magic', ''))
490+
name = decode_unicode_escape(_get(section, 'name', ''))
491+
fmt_len = _to_int(_get(section, 'len', 0))
492+
fmt_hex = decode_unicode_escape(_get(section, 'hex', ''))
493+
fmt_ver = decode_unicode_escape(_get(section, 'ver', ''))
494+
delim = decode_unicode_escape(_get(section, 'delimiter', ''))
495+
new_style = _to_bool(_get(section, 'newstyle', False))
496+
adv_list = _to_bool(_get(section, 'advancedlist', False))
497+
alt_inode = _to_bool(_get(section, 'altinode', False))
498+
extension = decode_unicode_escape(_get(section, 'extension', ''))
499+
500+
# keep your delimiter validation semantics
501+
if not is_only_nonprintable(delim):
502+
delim = "\x00" * len("\x00") # same as your INI branch
503+
504+
__file_format_multi_dict__.update({
505+
magic: {
506+
'format_name': name,
507+
'format_magic': magic,
508+
'format_len': fmt_len,
509+
'format_hex': fmt_hex,
510+
'format_delimiter': delim,
511+
'format_ver': fmt_ver,
512+
'new_style': new_style,
513+
'use_advanced_list': adv_list,
514+
'use_alt_inode': alt_inode,
515+
'format_extension': extension,
516+
}
517+
})
518+
519+
# mirror your INI logic
520+
if not __file_format_multi_dict__ and not __include_defaults__:
521+
__include_defaults__ = True
387522
elif __use_ini_file__ and not os.path.exists(__config_file__):
523+
__use_ini_file__ = False
524+
__use_json_file__ = False
525+
__include_defaults__ = True
526+
elif __use_json_file__ and not os.path.exists(__config_file__):
527+
__use_json_file__ = False
388528
__use_ini_file__ = False
389529
__include_defaults__ = True
390530
if not __use_ini_file__ and not __include_defaults__:

0 commit comments

Comments
 (0)