feat: release v1.1.2 - hardened IP sorting with ipaddress and config sort defaults

This commit is contained in:
soda64 committed 2026-10-03 22:18:10 +02:00
1 parent 62710d8bb7
commit 191b1d8a1d
12 files changed
+88 -21

No files matched your search

+2
View File
@@ -20,6 +20,8 @@ defaults:
ssh_user: "lain" ssh_user: "lain"
ssh_port: 22 ssh_port: 22
conflict_policy: "runtime_over_static" conflict_policy: "runtime_over_static"
sort_by: "name" # Default sorting: "name" or "ip"
sort_reverse: false # Set true to reverse sorting by default
destinations: destinations:
# In --sync mode, destinations define where unified inventories are written. # In --sync mode, destinations define where unified inventories are written.
@@ -30,3 +30,7 @@
- Preserved host order in all 6 exporters (Ansible YAML, JSON, Linux-Connector, Generic YAML, XML, INI). - Preserved host order in all 6 exporters (Ansible YAML, JSON, Linux-Connector, Generic YAML, XML, INI).
- Added destination override flags for --sync mode (--ansible-dest, --lc-dest, -o). - Added destination override flags for --sync mode (--ansible-dest, --lc-dest, -o).
- Added ~ expansion support for config destinations and CLI paths. - Added ~ expansion support for config destinations and CLI paths.
- Release v1.1.2:
- Hardened IP sorting with Python standard `ipaddress` module for 32-bit/128-bit numerical sorting.
- Handled CIDR prefixes (`/24`) and port numbers (`:22`) cleanly in IP sort key.
- Added configuration file support for `sort_by` and `sort_reverse` under `defaults:`.
+1 -1
View File
@@ -1,6 +1,6 @@
"""Universal homelab and fleet inventory collector and deduplicator.""" """Universal homelab and fleet inventory collector and deduplicator."""
__version__ = "1.1.1" __version__ = "1.1.2"
_yaml_warning_emitted = False _yaml_warning_emitted = False
+6 -3
View File
@@ -120,12 +120,13 @@ def build_parser() -> argparse.ArgumentParser:
"--sort", "--sort-by", "--sort", "--sort-by",
dest="sort_by", dest="sort_by",
choices=["name", "ip"], choices=["name", "ip"],
default="name", default=None,
help="Sort hosts by 'name' or 'ip' (default: name)." help="Sort hosts by 'name' or 'ip' (default: name, or config default)."
) )
parser.add_argument( parser.add_argument(
"-r", "--reverse", "-r", "--reverse",
action="store_true", action="store_true",
default=None,
help="Reverse the sort order." help="Reverse the sort order."
) )
parser.add_argument( parser.add_argument(
@@ -228,7 +229,9 @@ def main(argv: Optional[List[str]] = None) -> int:
) )
# 4c. Sort inventory by name or IP # 4c. Sort inventory by name or IP
inv = inv.sort(sort_by=args.sort_by, reverse=args.reverse) sort_by = args.sort_by or app_config.sort_by or "name"
sort_reverse = args.reverse if args.reverse is not None else app_config.sort_reverse
inv = inv.sort(sort_by=sort_by, reverse=sort_reverse)
# 5. Inspection / Dry-run Mode # 5. Inspection / Dry-run Mode
if args.dry_run: if args.dry_run:
+6
View File
@@ -31,6 +31,8 @@ class AppConfig:
output_linux_connector: Optional[Path] = None output_linux_connector: Optional[Path] = None
output_yaml: Optional[Path] = None output_yaml: Optional[Path] = None
output_xml: Optional[Path] = None output_xml: Optional[Path] = None
sort_by: str = "name"
sort_reverse: bool = False
class ConfigLoader: class ConfigLoader:
"""Loads configuration with environment variable interpolation.""" """Loads configuration with environment variable interpolation."""
@@ -197,6 +199,10 @@ class ConfigLoader:
config.default_ssh_user = defaults.get("ssh_user", config.default_ssh_user) config.default_ssh_user = defaults.get("ssh_user", config.default_ssh_user)
config.default_ssh_port = int(defaults.get("ssh_port", config.default_ssh_port)) config.default_ssh_port = int(defaults.get("ssh_port", config.default_ssh_port))
config.conflict_policy = defaults.get("conflict_policy", config.conflict_policy) config.conflict_policy = defaults.get("conflict_policy", config.conflict_policy)
if "sort_by" in defaults:
config.sort_by = str(defaults["sort_by"])
if "sort_reverse" in defaults:
config.sort_reverse = bool(defaults["sort_reverse"])
# Parse destinations # Parse destinations
destinations = data.get("destinations", {}) destinations = data.get("destinations", {})
+12 -6
View File
@@ -1,3 +1,4 @@
import ipaddress
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Dict, List, Optional, Any from typing import Dict, List, Optional, Any
@@ -63,14 +64,19 @@ class InventoryData:
def ip_sort_key(ip: str): def ip_sort_key(ip: str):
clean_ip = (ip or "").strip() clean_ip = (ip or "").strip()
if not clean_ip: if not clean_ip:
return (1, ()) return (2, 0, "")
# Strip single port if present e.g. 192.168.1.1:22
if ":" in clean_ip and not clean_ip.startswith("[") and clean_ip.count(":") == 1:
clean_ip = clean_ip.split(":")[0]
# Strip CIDR prefix if present e.g. 192.168.1.1/24
if "/" in clean_ip:
clean_ip = clean_ip.split("/")[0]
try: try:
parts = tuple(int(p) for p in clean_ip.split(".")) addr = ipaddress.ip_address(clean_ip)
if len(parts) == 4: return (0, addr.version, int(addr))
return (0, parts)
except Exception: except Exception:
pass return (1, 0, clean_ip.lower())
return (2, clean_ip)
def record_key(host: HostRecord): def record_key(host: HostRecord):
if sort_by.lower() == "ip": if sort_by.lower() == "ip":
+1 -1
View File
@@ -1,4 +1,4 @@
.TH INVENTORY-COLLECTOR 1 "October 2026" "inventory-collector 1.1.1" "User Commands" .TH INVENTORY-COLLECTOR 1 "October 2026" "inventory-collector 1.1.2" "User Commands"
.SH NAME .SH NAME
inventory-collector \- Universal homelab and fleet inventory collector and deduplicator inventory-collector \- Universal homelab and fleet inventory collector and deduplicator
.SH SYNOPSIS .SH SYNOPSIS
+1 -2
View File
@@ -296,8 +296,7 @@ class PackageBuilder:
], ],
check=True, check=True,
) )
# Find created .rpm and copy to dist/ rpms = [r for r in rpms_dir.glob(f"**/*{self.version}*.rpm") if not r.name.endswith(".src.rpm")]
rpms = list(rpms_dir.glob("**/*.rpm"))
if rpms: if rpms:
for rpm in rpms: for rpm in rpms:
shutil.copy2(str(rpm), str(self.output_dir / rpm.name)) shutil.copy2(str(rpm), str(self.output_dir / rpm.name))
+6 -1
View File
@@ -1,5 +1,5 @@
Name: inventory-collector Name: inventory-collector
Version: 1.1.1 Version: 1.1.2
Release: 1%{?dist} Release: 1%{?dist}
Summary: Universal homelab and fleet inventory collector and deduplicator Summary: Universal homelab and fleet inventory collector and deduplicator
@@ -66,6 +66,11 @@ fi
%doc %{_datadir}/doc/inventory-collector %doc %{_datadir}/doc/inventory-collector
%changelog %changelog
* Sat Oct 03 2026 Mateusz Stomski <zbytatencyjny@gmail.com> - 1.1.2-1
- Use Python standard ipaddress module for robust numerical 32-bit/128-bit IP sorting.
- Handle CIDR notation (/24) and port numbers (:22) gracefully in IP sorting.
- Support default sort configuration (sort_by, sort_reverse) in config.yaml.
* Sat Oct 03 2026 Mateusz Stomski <zbytatencyjny@gmail.com> - 1.1.1-1 * Sat Oct 03 2026 Mateusz Stomski <zbytatencyjny@gmail.com> - 1.1.1-1
- Add host sorting by name and IP (--sort {name,ip}, -r/--reverse). - Add host sorting by name and IP (--sort {name,ip}, -r/--reverse).
- Add destination override flags in --sync mode (--ansible-dest, --lc-dest, -o). - Add destination override flags in --sync mode (--ansible-dest, --lc-dest, -o).
+17
View File
@@ -63,5 +63,22 @@ destinations:
finally: finally:
env_file.unlink() env_file.unlink()
def test_load_config_sort_defaults(self):
content = """
defaults:
sort_by: "ip"
sort_reverse: true
"""
with NamedTemporaryFile("w+", suffix=".yaml", delete=False) as f:
f.write(content)
cfg_path = Path(f.name)
try:
config = ConfigLoader.load(cfg_path)
self.assertEqual(config.sort_by, "ip")
self.assertTrue(config.sort_reverse)
finally:
cfg_path.unlink()
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+25
View File
@@ -100,5 +100,30 @@ class TestDeduplicationEngine(unittest.TestCase):
rev_inv = inv.sort(sort_by="ip", reverse=True) rev_inv = inv.sort(sort_by="ip", reverse=True)
self.assertEqual(list(rev_inv.hosts.keys()), ["host-no-ip", "host-101", "host-20", "host-2"]) self.assertEqual(list(rev_inv.hosts.keys()), ["host-no-ip", "host-101", "host-20", "host-2"])
def test_inventory_sort_by_ip_robustness(self):
from inventory_collector.models import InventoryData
inv = InventoryData()
inv.add_host(HostRecord(name="node0", ansible_host="192.168.0.101"))
inv.add_host(HostRecord(name="node0-cidr", ansible_host="192.168.0.2/24"))
inv.add_host(HostRecord(name="node0-port", ansible_host="192.168.0.101:2222"))
inv.add_host(HostRecord(name="alma-crash", ansible_host="192.168.5.51"))
inv.add_host(HostRecord(name="rhcsa-111", ansible_host="192.168.5.111"))
inv.add_host(HostRecord(name="ipv6-host", ansible_host="fe80::1"))
inv.add_host(HostRecord(name="named-host", ansible_host="nas.wired.intra"))
inv.add_host(HostRecord(name="empty-host", ansible_host=""))
sorted_inv = inv.sort(sort_by="ip")
expected_order = [
"node0-cidr", # 192.168.0.2
"node0", # 192.168.0.101
"node0-port", # 192.168.0.101:2222 (tie broken by name)
"alma-crash", # 192.168.5.51 (51 < 111)
"rhcsa-111", # 192.168.5.111
"ipv6-host", # fe80::1 (IPv6 after IPv4)
"named-host", # nas.wired.intra (hostname after IP)
"empty-host", # "" (empty IP at end)
]
self.assertEqual(list(sorted_inv.hosts.keys()), expected_order)
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+7 -7
View File
@@ -33,13 +33,13 @@ class TestPackaging(unittest.TestCase):
def test_get_version(self): def test_get_version(self):
version = get_version(self.source_root) version = get_version(self.source_root)
self.assertEqual(version, "1.1.1") self.assertEqual(version, "1.1.2")
def test_build_tarball(self): def test_build_tarball(self):
builder = PackageBuilder( builder = PackageBuilder(
source_root=self.source_root, source_root=self.source_root,
output_dir=self.output_dir, output_dir=self.output_dir,
version="1.1.1", version="1.1.2",
) )
tar_path = builder.build_tarball() tar_path = builder.build_tarball()
self.assertTrue(tar_path.exists()) self.assertTrue(tar_path.exists())
@@ -48,16 +48,16 @@ class TestPackaging(unittest.TestCase):
# Verify tar contents # Verify tar contents
with tarfile.open(str(tar_path), "r:gz") as tar: with tarfile.open(str(tar_path), "r:gz") as tar:
names = tar.getnames() names = tar.getnames()
self.assertIn("inventory-collector-1.1.1/bin/inventory-collector", names) self.assertIn("inventory-collector-1.1.2/bin/inventory-collector", names)
self.assertIn("inventory-collector-1.1.1/inventory_collector/__init__.py", names) self.assertIn("inventory-collector-1.1.2/inventory_collector/__init__.py", names)
self.assertIn("inventory-collector-1.1.1/install.sh", names) self.assertIn("inventory-collector-1.1.2/install.sh", names)
self.assertIn("inventory-collector-1.1.1/packaging/install.sh", names) self.assertIn("inventory-collector-1.1.2/packaging/install.sh", names)
def test_build_deb(self): def test_build_deb(self):
builder = PackageBuilder( builder = PackageBuilder(
source_root=self.source_root, source_root=self.source_root,
output_dir=self.output_dir, output_dir=self.output_dir,
version="1.1.1", version="1.1.2",
) )
deb_path = builder.build_deb() deb_path = builder.build_deb()
self.assertTrue(deb_path.exists()) self.assertTrue(deb_path.exists())