Coverage for netbox_interface_name_rules / family / previous.py: 100.00%

16 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-16 10:13 +0000

1# SPDX-License-Identifier: Apache-2.0 

2# Copyright (C) 2025 Marcin Zieba <marcinpsk@gmail.com> 

3"""The names a module's templates had before a move, rebuilt without a database write. 

4 

5A reapply after a move recognises an interface by the names its template had in the previous state: 

6the raw template name resolved there, and the output of the rule that state selected, built from 

7its template variables. Everything here evaluates values read before the save. 

8""" 

9 

10from collections.abc import Mapping 

11from dataclasses import dataclass 

12 

13from .installed import device_interface_families 

14from .targets import intended_family_names 

15from .template_names import ResolvedTemplateName 

16 

17 

18@dataclass(frozen=True, slots=True) 

19class PreviousForms: 

20 """What rebuilds the names a module's interfaces had in the previous state. 

21 

22 *rule* is the rule the previous state selects, or None when no rule matched there. *variables* 

23 are the previous template variables, and *templates* maps each interface template's primary key 

24 to the name it resolved to in the previous state. 

25 """ 

26 

27 rule: object | None 

28 variables: Mapping[str, str] 

29 templates: Mapping[int, ResolvedTemplateName] 

30 

31 

32def _names_given_by(previous_forms) -> frozenset[str]: 

33 """Return every name the previous rule gave the module's templates, other than a raw name.""" 

34 return frozenset( 

35 name 

36 for template in previous_forms.templates.values() 

37 if template.channel_id is None 

38 for name in intended_family_names( 

39 previous_forms.rule, previous_forms.variables, template.resolved, template.resolved 

40 ) 

41 if name != template.resolved 

42 ) 

43 

44 

45def names_the_previous_rule_gave(previous_forms, interfaces) -> tuple[str, ...]: 

46 """Return the name of each of *interfaces* that the previous rule gave, in interface order. 

47 

48 *previous_forms* must hold a rule. A template the rule could not evaluate kept its raw name. A 

49 channel that a simple rule renamed in lockstep with its parent follows the parent. 

50 """ 

51 given = _names_given_by(previous_forms) 

52 names = [] 

53 for interface, channels in device_interface_families(interfaces): 

54 parent_named = interface.name in given 

55 names.extend(row.name for row in (interface, *channels) if parent_named or row.name in given) 

56 return tuple(names)