Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(systemextensionsctl): add functionality #597

Open
wants to merge 14 commits into
base: dev
Choose a base branch
from
Open
165 changes: 165 additions & 0 deletions jc/parsers/systemextensionsctl.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
"""jc - JSON Convert `systemextensionsctl list` command output parser

Usage:

$ systemextensionsctl list | jc --systemextensionsctl

Compatibility:

macOS

Example:

$ systemextensionsctl list | jc --systemextensionsctl -p
{
"total_extensions": 1,
"sections": [
{
"category": "com.apple.system_extension.network_extension",
"description": "Go to 'System Settings > General > Login Items & Extensions > Network Extensions' to modify these system extension(s)",
"entries": [
{
"enabled": "*",
"active": "*",
georgettica marked this conversation as resolved.
Show resolved Hide resolved
"teamID": "XXX",
"bundleID": "YYY",
"version": "QQQ",
"name": "ZZZ",
"state": "activated enabled"
georgettica marked this conversation as resolved.
Show resolved Hide resolved
}
]
},

]
}

"""

import jc.utils
import jc.parsers.universal
import re

class info():
version = '1.0'
description = '`systemextensionsctl list` command parser'
author = 'Ron Green'
author_email = '[email protected]'
compatible = ['darwin']
georgettica marked this conversation as resolved.
Show resolved Hide resolved
magic_commands = ['systemextensionsctl list']
def parse(data, raw=False, quiet=False):
"""
Parses the output of `systemextensionsctl list` command.

Parameters:

data: (string) Text data to parse

Returns:

Dictionary with parsed data
"""
jc.utils.compatibility(__name__, info.compatible, quiet)
if jc.utils.has_data(data):

lines = data.strip().splitlines()
total_extensions = None
sections = []
section = None
headers = None

line_iter = iter(lines)
for line in line_iter:
line = line.strip('\n')
if line.endswith('extension(s)'):
# Extract total_extensions
match = re.match(r'(\d+)\s+extension\(s\)', line)
if match:
total_extensions = int(match.group(1))
elif line.startswith('--- '):
# Only process sections if total_extensions > 0
if total_extensions is not None and total_extensions > 0:
category_line = line
# Extract category and description
category_and_desc = line[4:]
# Category is up to the first '('
if '(' in category_and_desc and ')' in category_and_desc:
category = category_and_desc.split('(')[0].strip()
description = category_and_desc[category_and_desc.find('(')+1:category_and_desc.rfind(')')].strip()
else:
category = category_and_desc.strip()
description = ''
section = {
'category': category,
'description': description,
'entries': []
}
sections.append(section)
try:
# Read the header line
headers_line = next(line_iter).strip()
# Check if headers_line contains expected headers
expected_headers = ['enabled', 'active', 'teamID', 'bundleID (version)', 'name', '[state]']
actual_headers = [h.strip().lower() for h in headers_line.split('\t')]
if not all(header.lower() in actual_headers for header in expected_headers):
# Headers do not match expected format
headers = None
continue
headers = headers_line.split('\t')
headers = [h.strip() for h in headers]
except StopIteration:
# No more lines; headers not found
headers = None
continue
else:
# If total_extensions is 0 or not set, skip processing sections
continue
else:
# Data line
if not line.strip():
continue
if not section or not headers:
# No section defined or headers missing; skip the line
continue
fields = line.split('\t')
# Pad fields with empty strings if needed
if len(fields) < len(headers):
fields = fields + ['']*(len(headers) - len(fields))
entry = {}
for h, f in zip(headers, fields):
entry[h] = f.strip()
# Optionally parse the 'bundleID (version)' field
if 'bundleID (version)' in entry:
bundleID_version = entry['bundleID (version)']
match = re.match(r'(.+)\s+\((.+)\)', bundleID_version)
if match:
bundleID = match.group(1).strip()
version = match.group(2).strip()
entry['bundleID'] = bundleID
entry['version'] = version
else:
entry['bundleID'] = bundleID_version.strip()
entry['version'] = ''
del entry['bundleID (version)']
# Optionally parse the '[state]' field
if '[state]' in entry:
state = entry['[state]']
if state.startswith('[') and state.endswith(']'):
state_content = state[1:-1]
entry['state'] = state_content.strip()
else:
entry['state'] = state.strip()
del entry['[state]']
# Add entry to the current section
section['entries'].append(entry)

# Finalize the result
if total_extensions is not None:
result = {
'total_extensions': total_extensions,
'sections': sections
}
return result
else:
return {}
else:
return {}
4 changes: 4 additions & 0 deletions tests/fixtures/generic/systemextensionsctl-no-extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"total_extensions": 0,
"sections": []
}
2 changes: 2 additions & 0 deletions tests/fixtures/generic/systemextensionsctl-no-extensions.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
0 extension(s)
--- com.apple.system_extension.network_extension (No extensions found)
20 changes: 20 additions & 0 deletions tests/fixtures/generic/systemextensionsctl.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"total_extensions": 1,
"sections": [
{
"category": "com.apple.system_extension.network_extension",
"description": "Go to 'System Settings > General > Login Items & Extensions > Network Extensions' to modify these system extension(s)",
"entries": [
{
"enabled": "*",
"active": "*",
"teamID": "XXX",
"bundleID": "YYY",
"version": "QQQ",
"name": "ZZZ",
"state": "activated enabled"
}
]
}
]
}
4 changes: 4 additions & 0 deletions tests/fixtures/generic/systemextensionsctl.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
1 extension(s)
--- com.apple.system_extension.network_extension (Go to 'System Settings > General > Login Items & Extensions > Network Extensions' to modify these system extension(s))
enabled active teamID bundleID (version) name [state]
* * XXX YYY (QQQ) ZZZ [activated enabled]
82 changes: 82 additions & 0 deletions tests/test_systemextensionsctl.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import os
import json
import unittest
import jc.parsers.systemextensionsctl

THIS_DIR = os.path.dirname(os.path.abspath(__file__))


class MyTests(unittest.TestCase):

# Input data from fixtures
with open(os.path.join(THIS_DIR, os.pardir, 'tests/fixtures/generic/systemextensionsctl.out'), 'r', encoding='utf-8') as f:
systemextensionsctl_output = f.read()

with open(os.path.join(THIS_DIR, os.pardir, 'tests/fixtures/generic/systemextensionsctl-no-extensions.out'), 'r', encoding='utf-8') as f:
systemextensionsctl_no_extensions_output = f.read()

# Expected output data from fixtures
with open(os.path.join(THIS_DIR, os.pardir, 'tests/fixtures/generic/systemextensionsctl.json'), 'r', encoding='utf-8') as f:
systemextensionsctl_expected = json.loads(f.read())

with open(os.path.join(THIS_DIR, os.pardir, 'tests/fixtures/generic/systemextensionsctl-no-extensions.json'), 'r', encoding='utf-8') as f:
systemextensionsctl_no_extensions_expected = json.loads(f.read())

def test_systemextensionsctl(self):
"""
Test 'systemextensionsctl list' with placeholder data
"""
self.assertEqual(
jc.parsers.systemextensionsctl.parse(
self.systemextensionsctl_output, quiet=True),
self.systemextensionsctl_expected
)

def test_systemextensionsctl_empty(self):
"""
Test 'systemextensionsctl list' with empty input
"""
self.assertEqual(
jc.parsers.systemextensionsctl.parse(
'', quiet=True),
{}
)

def test_systemextensionsctl_no_extensions(self):
"""
Test 'systemextensionsctl list' with no extensions
"""
self.assertEqual(
jc.parsers.systemextensionsctl.parse(
self.systemextensionsctl_no_extensions_output, quiet=True),
self.systemextensionsctl_no_extensions_expected
)

def test_systemextensionsctl_nodata(self):
"""
Test 'systemextensionsctl list' with no data
"""
self.assertEqual(jc.parsers.systemextensionsctl.parse('', quiet=True), {})

def test_systemextensionsctl_incorrect_format(self):
"""
Test 'systemextensionsctl list' with incorrect format
"""
incorrect_data = 'This is not the correct format.'
self.assertEqual(
jc.parsers.systemextensionsctl.parse(incorrect_data, quiet=True), {}
)

def test_systemextensionsctl_trailing_newline(self):
"""
Test 'systemextensionsctl list' with trailing newline
"""
cmd_output = self.systemextensionsctl_output + '\n'
self.assertEqual(
jc.parsers.systemextensionsctl.parse(cmd_output, quiet=True),
self.systemextensionsctl_expected
)


if __name__ == '__main__':
unittest.main()
Loading