1
0
mirror of https://github.com/kellyjonbrazil/jc.git synced 2025-06-17 00:07:37 +02:00
Files
jc/jc/parsers/hash.py

109 lines
2.2 KiB
Python

"""jc - JSON CLI output utility `hash` command output parser
Usage (cli):
$ hash | jc --hash
Usage (module):
import jc.parsers.hash
result = jc.parsers.hash.parse(hash_command_output)
Compatibility:
'linux', 'darwin', 'cygwin', 'aix', 'freebsd'
Examples:
$ hash | jc --hash -p
[
{
"hits": 2,
"command": "/bin/cat"
},
{
"hits": 1,
"command": "/bin/ls"
}
]
"""
import jc.utils
import jc.parsers.universal
class info():
version = '1.0'
description = '`hash` command parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
# compatible options: linux, darwin, cygwin, win32, aix, freebsd
compatible = ['linux', 'darwin', 'cygwin', 'aix', 'freebsd']
__version__ = info.version
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (List of Dictionaries) raw structured data to process
Returns:
List of Dictionaries. Structured data with the following schema:
[
{
"command": string,
"hits": integer
}
]
"""
for entry in proc_data:
# change to int
int_list = ['hits']
for key in int_list:
if key in entry:
try:
key_int = int(entry[key])
entry[key] = key_int
except (ValueError):
entry[key] = None
return proc_data
def parse(data, raw=False, quiet=False):
"""
Main text parsing function
Parameters:
data: (string) text data to parse
raw: (boolean) output preprocessed JSON if True
quiet: (boolean) suppress warning messages if True
Returns:
List of Dictionaries. Raw or processed structured data.
"""
if not quiet:
jc.utils.compatibility(__name__, info.compatible)
cleandata = data.splitlines()
raw_output = []
if jc.utils.has_data(data):
cleandata[0] = cleandata[0].lower()
raw_output = jc.parsers.universal.simple_table_parse(cleandata)
if raw:
return raw_output
else:
return process(raw_output)