Files
rengine/shared/utils/cidr.py
T
Yogesh OjhaandClaude Opus 5 2cb8d73280 style: strip explanatory comments across the codebase
The comment rule in CLAUDE.md is one line maximum, never narration: no
multi-line blocks, no module-header explainers, no sentences that explain or
justify the code to the reader. The tree had drifted a long way from it, and
most of the drift is mine.

Removed:
  232  lines of multi-line comment blocks
  203  single-line comments that argued instead of stating
  154  comments joined by so/because/otherwise/rather-than
  143  narrating comments in the frontend
  112  test docstrings (the test name already says what it asserts)
   25  test module docstrings and 25 decorative section dividers

Collapsed:
  324  multi-line docstrings to one factual line
  271  one-line docstrings that had a justifying clause bolted on

Kept: functional directives, section dividers, short field labels, alembic
revision headers, and the eight FastAPI route docstrings that render in /docs.
Where a fact was load-bearing it is in CLAUDE.md, which is where it belongs.

284 python tests and 34 frontend tests pass, ruff and ruff-format clean across
ten packages, svelte-check 0 errors, prettier and eslint clean, app.main imports.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013dKUV96WkQQETZBMoAG98C
2026-09-11 14:11:23 +05:30

57 lines
1.6 KiB
Python

"""Stdlib CIDR/IP math for seed expansion (no external binary — pure arithmetic)."""
from __future__ import annotations
import ipaddress
IPNetwork = ipaddress.IPv4Network | ipaddress.IPv6Network
DEFAULT_MAX_HOSTS = 4096
def parse_network(cidr: str) -> IPNetwork | None:
"""Parse a CIDR (or bare IP) into a network, host bits zeroed."""
try:
return ipaddress.ip_network(cidr.strip(), strict=False)
except ValueError:
return None
def _usable_count(net: IPNetwork) -> int:
total = net.num_addresses
if net.version == 4 and net.prefixlen < 31 and total > 2: # noqa: PLR2004
return total - 2
return total
def expand_network(
cidr: str,
*,
max_hosts: int = DEFAULT_MAX_HOSTS,
skip_private: bool = False,
) -> tuple[list[str], bool]:
"""Expand a CIDR to host IPs, capped at max_hosts by even-stride sampling."""
net = parse_network(cidr)
if net is None:
return [], False
total = net.num_addresses
skip_edges = net.version == 4 and net.prefixlen < 31 and total > 2 # noqa: PLR2004
start = 1 if skip_edges else 0
end = total - 1 if skip_edges else total
usable = max(end - start, 0)
if usable == 0:
return [str(net.network_address)], False
truncated = usable > max_hosts
stride = (usable // max_hosts) or 1 if truncated else 1
ips: list[str] = []
idx = start
while idx < end and len(ips) < max_hosts:
addr = net[idx]
if not (skip_private and addr.is_private):
ips.append(str(addr))
idx += stride
return ips, truncated