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

[types] add ipaddr and ipnet types #1946

Merged
merged 4 commits into from
Jul 2, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions visidata/features/type_ipaddr.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
"""
Column types and utility commands related to IP addresses.
"""
import ipaddress

from visidata import vd
from visidata.sheets import Column, TableSheet


def isSupernet(cell, network, isNull):
"""Is `cell` a supernet of `network`?

Treat nulls as false, and perform conversions to IP network objects only
if necessary.
"""
if isNull(cell):
return False
if not isinstance(cell, ipaddress._BaseNetwork):
try:
cell = ipaddress.ip_network(str(cell).strip())
except ValueError:
return False
return cell.supernet_of(network)


@Column.api
def selectSupernets(col, ip):
"""Select rows based on network containment

Given an IP address (e.g. 10.0.0.0) or network (e.g. 10.0.0.0/8) as input,
select rows whose network address space completely contains the input network.
"""
if not ip:
return

sheet = col.sheet
network = ipaddress.ip_network(ip.strip())
isNull = sheet.isNullFunc()

vd.status(f'selecting rows where {col.name} is a supernet of "{str(network)}"')
sheet.select(
[
row
for row in sheet.rows
if isSupernet(col.getTypedValue(row), network, isNull)
]
)


TableSheet.addCommand(
None,
"type-ipaddr",
"cursorCol.type=ipaddress.ip_address",
"set type of current column to IP address",
)
TableSheet.addCommand(
None,
"type-ipnet",
"cursorCol.type=ipaddress.ip_network",
"set type of current column to IP network",
)
TableSheet.addCommand(
None,
"select-supernets",
'cursorCol.selectSupernets(input("ip or cidr block: "))',
"select rows where the CIDR block value includes the input address space",
)

vd.addGlobals({"ipaddress": ipaddress})