Coverage for src/birdplan/bird_config/util.py: 100%

17 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-07-25 07:38 +0000

1# 

2# SPDX-License-Identifier: GPL-3.0-or-later 

3# 

4# Copyright (c) 2019-2025, AllWorldIT 

5# 

6# This program is free software: you can redistribute it and/or modify 

7# it under the terms of the GNU General Public License as published by 

8# the Free Software Foundation, either version 3 of the License, or 

9# (at your option) any later version. 

10# 

11# This program is distributed in the hope that it will be useful, 

12# but WITHOUT ANY WARRANTY; without even the implied warranty of 

13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

14# GNU General Public License for more details. 

15# 

16# You should have received a copy of the GNU General Public License 

17# along with this program. If not, see <http://www.gnu.org/licenses/>. 

18 

19"""Bird configuration utility functions.""" 

20 

21import ipaddress 

22 

23__all__ = ["network_count", "sanitize_community", "sanitize_community_list"] 

24 

25 

26def sanitize_community(community: str) -> str: 

27 """Sanitize a string representation of a large community.""" 

28 # Split on : 

29 community_components = community.split(":") 

30 # Re-join using , and add brackets 

31 return f"({','.join(community_components)})" 

32 

33 

34def sanitize_community_list(communities: list[str]) -> list[str]: 

35 """Sanitize a list of communities.""" 

36 return [sanitize_community(community) for community in sorted(communities)] 

37 

38 

39def network_count(ip_networks: list[str]) -> int: 

40 """Get the number of ISP networks within a list of IP networks.""" 

41 

42 # Loop with the networks we got 

43 count = 0 

44 for prefix_raw in ip_networks: 

45 # Split off possible network size constraints 

46 prefix = prefix_raw.split("{", 1)[0] 

47 # Grab network object 

48 ipnetwork = ipaddress.ip_network(prefix) 

49 # Check which IP version this is 

50 if ipnetwork.version == 4: # noqa: SIM108,PLR2004 

51 # Count how many /24's there are in the ipnetwork 

52 prefix_count = ipnetwork.num_addresses >> 8 

53 else: 

54 # Count approximate number of /48's there are in the ipnetwork 

55 prefix_count = ipnetwork.num_addresses >> 80 

56 # Add to counter 

57 count += prefix_count 

58 

59 return count