annet 0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of annet might be problematic. Click here for more details.

Files changed (113) hide show
  1. annet/__init__.py +61 -0
  2. annet/annet.py +25 -0
  3. annet/annlib/__init__.py +7 -0
  4. annet/annlib/command.py +49 -0
  5. annet/annlib/diff.py +158 -0
  6. annet/annlib/errors.py +8 -0
  7. annet/annlib/filter_acl.py +196 -0
  8. annet/annlib/jsontools.py +89 -0
  9. annet/annlib/lib.py +495 -0
  10. annet/annlib/netdev/__init__.py +0 -0
  11. annet/annlib/netdev/db.py +62 -0
  12. annet/annlib/netdev/devdb/__init__.py +28 -0
  13. annet/annlib/netdev/devdb/data/devdb.json +137 -0
  14. annet/annlib/netdev/views/__init__.py +0 -0
  15. annet/annlib/netdev/views/dump.py +121 -0
  16. annet/annlib/netdev/views/hardware.py +112 -0
  17. annet/annlib/output.py +246 -0
  18. annet/annlib/patching.py +533 -0
  19. annet/annlib/rbparser/__init__.py +0 -0
  20. annet/annlib/rbparser/acl.py +120 -0
  21. annet/annlib/rbparser/deploying.py +55 -0
  22. annet/annlib/rbparser/ordering.py +52 -0
  23. annet/annlib/rbparser/platform.py +51 -0
  24. annet/annlib/rbparser/syntax.py +115 -0
  25. annet/annlib/rulebook/__init__.py +0 -0
  26. annet/annlib/rulebook/common.py +350 -0
  27. annet/annlib/tabparser.py +648 -0
  28. annet/annlib/types.py +35 -0
  29. annet/api/__init__.py +807 -0
  30. annet/argparse.py +415 -0
  31. annet/cli.py +192 -0
  32. annet/cli_args.py +493 -0
  33. annet/configs/context.yml +18 -0
  34. annet/configs/logging.yaml +39 -0
  35. annet/connectors.py +64 -0
  36. annet/deploy.py +441 -0
  37. annet/diff.py +85 -0
  38. annet/executor.py +551 -0
  39. annet/filtering.py +40 -0
  40. annet/gen.py +828 -0
  41. annet/generators/__init__.py +987 -0
  42. annet/generators/common/__init__.py +0 -0
  43. annet/generators/common/initial.py +33 -0
  44. annet/hardware.py +45 -0
  45. annet/implicit.py +139 -0
  46. annet/lib.py +128 -0
  47. annet/output.py +170 -0
  48. annet/parallel.py +448 -0
  49. annet/patching.py +25 -0
  50. annet/reference.py +148 -0
  51. annet/rulebook/__init__.py +114 -0
  52. annet/rulebook/arista/__init__.py +0 -0
  53. annet/rulebook/arista/iface.py +16 -0
  54. annet/rulebook/aruba/__init__.py +16 -0
  55. annet/rulebook/aruba/ap_env.py +146 -0
  56. annet/rulebook/aruba/misc.py +8 -0
  57. annet/rulebook/cisco/__init__.py +0 -0
  58. annet/rulebook/cisco/iface.py +68 -0
  59. annet/rulebook/cisco/misc.py +57 -0
  60. annet/rulebook/cisco/vlandb.py +90 -0
  61. annet/rulebook/common.py +19 -0
  62. annet/rulebook/deploying.py +87 -0
  63. annet/rulebook/huawei/__init__.py +0 -0
  64. annet/rulebook/huawei/aaa.py +75 -0
  65. annet/rulebook/huawei/bgp.py +97 -0
  66. annet/rulebook/huawei/iface.py +33 -0
  67. annet/rulebook/huawei/misc.py +337 -0
  68. annet/rulebook/huawei/vlandb.py +115 -0
  69. annet/rulebook/juniper/__init__.py +107 -0
  70. annet/rulebook/nexus/__init__.py +0 -0
  71. annet/rulebook/nexus/iface.py +92 -0
  72. annet/rulebook/patching.py +143 -0
  73. annet/rulebook/ribbon/__init__.py +12 -0
  74. annet/rulebook/texts/arista.deploy +20 -0
  75. annet/rulebook/texts/arista.order +125 -0
  76. annet/rulebook/texts/arista.rul +59 -0
  77. annet/rulebook/texts/aruba.deploy +20 -0
  78. annet/rulebook/texts/aruba.order +83 -0
  79. annet/rulebook/texts/aruba.rul +87 -0
  80. annet/rulebook/texts/cisco.deploy +27 -0
  81. annet/rulebook/texts/cisco.order +82 -0
  82. annet/rulebook/texts/cisco.rul +105 -0
  83. annet/rulebook/texts/huawei.deploy +188 -0
  84. annet/rulebook/texts/huawei.order +388 -0
  85. annet/rulebook/texts/huawei.rul +471 -0
  86. annet/rulebook/texts/juniper.rul +120 -0
  87. annet/rulebook/texts/nexus.deploy +24 -0
  88. annet/rulebook/texts/nexus.order +85 -0
  89. annet/rulebook/texts/nexus.rul +83 -0
  90. annet/rulebook/texts/nokia.rul +31 -0
  91. annet/rulebook/texts/pc.order +5 -0
  92. annet/rulebook/texts/pc.rul +9 -0
  93. annet/rulebook/texts/ribbon.deploy +22 -0
  94. annet/rulebook/texts/ribbon.rul +77 -0
  95. annet/rulebook/texts/routeros.order +38 -0
  96. annet/rulebook/texts/routeros.rul +45 -0
  97. annet/storage.py +121 -0
  98. annet/tabparser.py +36 -0
  99. annet/text_term_format.py +95 -0
  100. annet/tracing.py +170 -0
  101. annet/types.py +223 -0
  102. annet-0.1.dist-info/AUTHORS +21 -0
  103. annet-0.1.dist-info/LICENSE +21 -0
  104. annet-0.1.dist-info/METADATA +24 -0
  105. annet-0.1.dist-info/RECORD +113 -0
  106. annet-0.1.dist-info/WHEEL +5 -0
  107. annet-0.1.dist-info/entry_points.txt +6 -0
  108. annet-0.1.dist-info/top_level.txt +3 -0
  109. annet_generators/__init__.py +0 -0
  110. annet_generators/example/__init__.py +12 -0
  111. annet_generators/example/lldp.py +52 -0
  112. annet_nbexport/__init__.py +220 -0
  113. annet_nbexport/main.py +46 -0
annet/deploy.py ADDED
@@ -0,0 +1,441 @@
1
+ # pylint: disable=unused-argument
2
+
3
+
4
+ import abc
5
+ import re
6
+ from collections import namedtuple
7
+ from contextlib import contextmanager
8
+ from typing import Dict, List, Optional, Type
9
+
10
+ from contextlog import get_logger
11
+
12
+ from annet import text_term_format
13
+ from annet.cli_args import DeployOptions
14
+ from annet.connectors import Connector
15
+ from annet.output import TextArgs
16
+ from annet.storage import Device
17
+
18
+
19
+ NCURSES_SIZE_T = 2 ** 15 - 1
20
+
21
+
22
+ _DeployResultBase = namedtuple("_DeployResultBase", ("hostnames", "results", "durations", "original_states"))
23
+
24
+
25
+ class DeployResult(_DeployResultBase): # noqa: E302
26
+ def add_results(self, results: Dict[str, Optional[Exception]]) -> None:
27
+ for hostname, result in results.items():
28
+ self.hostnames.append(hostname)
29
+ self.results[hostname] = result
30
+ self.durations[hostname] = 0.0
31
+ self.original_states[hostname] = None
32
+
33
+
34
+ class _FetcherConnector(Connector["Fetcher"]):
35
+ name = "Fetcher"
36
+ ep_name = "deploy_fetcher"
37
+
38
+ def _get_default(self) -> Type["Fetcher"]:
39
+ return StubFetcher
40
+
41
+
42
+ class _DriverConnector(Connector["DeployDriver"]):
43
+ name = "DeployDriver"
44
+ ep_name = "deploy_driver"
45
+
46
+ def _get_default(self) -> Type["DeployDriver"]:
47
+ return StubDeployDriver
48
+
49
+
50
+ fetcher_connector = _FetcherConnector()
51
+ driver_connector = _DriverConnector()
52
+
53
+
54
+ class Fetcher(abc.ABC):
55
+ @abc.abstractmethod
56
+ def fetch_packages(self, devices: List[Device],
57
+ processes: int = 1, max_slots: int = 0):
58
+ pass
59
+
60
+ @abc.abstractmethod
61
+ def fetch(self, devices: List[Device],
62
+ files_to_download: Dict[str, List[str]] = None,
63
+ processes: int = 1, max_slots: int = 0):
64
+ pass
65
+
66
+
67
+ class StubFetcher(Fetcher):
68
+ def fetch_packages(self, devices: List[Device],
69
+ processes: int = 1, max_slots: int = 0):
70
+ raise NotImplementedError()
71
+
72
+ def fetch(self, devices: List[Device],
73
+ files_to_download: Dict[str, List[str]] = None,
74
+ processes: int = 1, max_slots: int = 0):
75
+ raise NotImplementedError()
76
+
77
+
78
+ class DeployDriver(abc.ABC):
79
+ @abc.abstractmethod
80
+ async def bulk_deploy(self, deploy_cmds: dict, args: DeployOptions) -> DeployResult:
81
+ pass
82
+
83
+ @abc.abstractmethod
84
+ def apply_deploy_rulebook(self, hw, cmd_paths, do_finalize=True, do_commit=True):
85
+ pass
86
+
87
+ @abc.abstractmethod
88
+ def build_configuration_cmdlist(self, hw, do_finalize=True, do_commit=True):
89
+ pass
90
+
91
+ @abc.abstractmethod
92
+ def build_exit_cmdlist(self, hw):
93
+ pass
94
+
95
+
96
+ class StubDeployDriver(DeployDriver):
97
+ async def bulk_deploy(self, deploy_cmds: dict, args: DeployOptions) -> DeployResult:
98
+ NotImplementedError()
99
+
100
+ def apply_deploy_rulebook(self, hw, cmd_paths, do_finalize=True, do_commit=True):
101
+ NotImplementedError()
102
+
103
+ def build_configuration_cmdlist(self, hw, do_finalize=True, do_commit=True):
104
+ NotImplementedError()
105
+
106
+ def build_exit_cmdlist(self, hw):
107
+ raise NotImplementedError()
108
+
109
+
110
+ # ===
111
+ def scrub_config(text, breed):
112
+ return text
113
+
114
+
115
+ def show_bulk_report(hostnames, results, durations, log_dir):
116
+ pass
117
+
118
+
119
+ class AskConfirm:
120
+ CUT_WARN_MSG = "WARNING: the text was cut because of curses limits."
121
+
122
+ def __init__(self, text: str, text_type="diff", alternative_text: str = "",
123
+ alternative_text_type: str = "diff", allow_force_yes: bool = False):
124
+ self.text = [text, text_type]
125
+ self.alternative_text = [alternative_text, alternative_text_type]
126
+ self.color_to_curses: Dict[Optional[str], int] = {}
127
+ self.lines: Dict[int, List[TextArgs]] = {}
128
+ self.rows = None
129
+ self.cols = None
130
+ self.top = 0
131
+ self.left = 0
132
+ self.pad = None
133
+ self.screen = None
134
+ self.found_pos = {}
135
+ self.curses_lines = None
136
+ self.debug_prompt = TextArgs("")
137
+ self.page_position = TextArgs("")
138
+ s_force = "/f" if allow_force_yes else ""
139
+ self.prompt = [
140
+ TextArgs("Execute these commands? [Y%s/q] (/ - search, a - patch/cmds)" % s_force, "blue", offset=0),
141
+ self.page_position,
142
+ self.debug_prompt]
143
+
144
+ def _parse_text(self):
145
+ txt = self.text[0]
146
+ txt_split = txt.splitlines()
147
+ # curses pad, который тут используется, имеет ограничение на количество линий
148
+ if (len(txt_split) + 1) >= NCURSES_SIZE_T: # +1 для того чтобы курсор можно было переместить на пустую строку
149
+ del txt_split[NCURSES_SIZE_T - 3:]
150
+ txt_split.insert(0, self.CUT_WARN_MSG)
151
+ txt_split.append(self.CUT_WARN_MSG)
152
+ txt = "\n".join(txt_split)
153
+ self.rows = len(txt_split)
154
+ self.cols = max(len(line) for line in txt_split)
155
+ res = text_term_format.curses_format(txt, self.text[1])
156
+ self.lines = res
157
+
158
+ def _update_search_pos(self, expr):
159
+ self.found_pos = {}
160
+ if not expr:
161
+ return
162
+ try:
163
+ expr = re.compile(expr)
164
+ except Exception:
165
+ return None
166
+ lines = self.text[0].splitlines()
167
+ for (line_no, line) in enumerate(lines):
168
+ for match in re.finditer(expr, line):
169
+ if line_no not in self.found_pos:
170
+ self.found_pos[line_no] = []
171
+ self.found_pos[line_no].append(TextArgs(match.group(0), "highlight", match.start()))
172
+
173
+ def _init_colors(self):
174
+ self.color_to_curses = init_colors()
175
+
176
+ def _init_pad(self):
177
+ import curses
178
+
179
+ with self._store_xy():
180
+ self.pad = curses.newpad(self.rows + 1, self.cols)
181
+ self.pad.keypad(True) # accept arrow keys
182
+ self._render_to_pad(self.lines)
183
+
184
+ def _render_to_pad(self, lines: dict):
185
+ """
186
+ Рендерим данный на pad
187
+ :param lines: словарь проиндексированный по номерам линий
188
+ :return:
189
+ """
190
+ with self._store_xy():
191
+ for line_no, line_data in sorted(lines.items()):
192
+ line_pos_calc = 0
193
+ for line_part in line_data:
194
+ if line_part.offset is not None:
195
+ line_pos = line_part.offset
196
+ else:
197
+ line_pos = line_pos_calc
198
+ if line_part.color:
199
+ self.pad.addstr(line_no, line_pos, line_part.text, self.color_to_curses[line_part.color])
200
+ else:
201
+ self.pad.addstr(line_no, line_pos, line_part.text)
202
+ line_pos_calc += len(line_part.text)
203
+
204
+ def _add_prompt(self):
205
+ for prompt_part in self.prompt:
206
+ if not prompt_part:
207
+ continue
208
+ if prompt_part.offset is None:
209
+ offset = 0
210
+ else:
211
+ offset = prompt_part.offset
212
+ self.screen.addstr(self.curses_lines - 1, offset, prompt_part.text, self.color_to_curses[prompt_part.color])
213
+
214
+ def _clear_prompt(self):
215
+ with self._store_xy():
216
+ self.screen.move(self.curses_lines - 1, 0)
217
+ self.screen.clrtoeol()
218
+
219
+ def show(self):
220
+ self._add_prompt()
221
+ self.screen.refresh()
222
+ size = self.screen.getmaxyx()
223
+ self.pad.refresh(self.top, self.left, 0, 0, size[0] - 2, size[1] - 2)
224
+
225
+ @contextmanager
226
+ def _store_xy(self):
227
+ if self.pad is not None:
228
+ current_y, current_x = self.pad.getyx()
229
+ yield current_y, current_x
230
+ max_y, max_x = self.pad.getmaxyx()
231
+ current_y = min(max_y - 1, current_y)
232
+ current_x = min(max_x - 1, current_x)
233
+
234
+ self.pad.move(current_y, current_x)
235
+ else:
236
+ yield
237
+
238
+ def search_next(self, prev=False):
239
+ to = None
240
+ current_y, current_x = self.pad.getyx()
241
+ if prev:
242
+ for line_index in sorted(self.found_pos, reverse=True):
243
+ for text_args in self.found_pos[line_index]:
244
+ if line_index > current_y:
245
+ continue
246
+
247
+ if line_index < current_y or line_index == current_y and text_args.offset < current_x:
248
+ to = line_index, text_args.offset
249
+ break
250
+ if to:
251
+ break
252
+ else:
253
+ for line_index in sorted([i for i in self.found_pos if i >= current_y]):
254
+ for text_args in self.found_pos[line_index]:
255
+ if line_index > current_y or line_index == current_y and text_args.offset > current_x:
256
+ to = line_index, text_args.offset
257
+ break
258
+ if to:
259
+ break
260
+ if to:
261
+ return to[0] - current_y, to[1] - current_x
262
+ else:
263
+ return 0, 0
264
+
265
+ def _search_prompt(self):
266
+ import curses
267
+
268
+ search_prompt = [TextArgs("Search: ", "green_bold", offset=0)]
269
+ current_prompt = self.prompt
270
+ self.prompt = search_prompt
271
+ with self._store_xy():
272
+ self._clear_prompt()
273
+ self.show()
274
+ curses.echo()
275
+ expr = self.screen.getstr().decode()
276
+ curses.noecho()
277
+ self._update_search_pos(expr)
278
+ self._parse_text()
279
+ self._init_pad()
280
+ # срендерем поверх pad слой с подстветкой
281
+ self._render_to_pad(self.found_pos)
282
+ y_offset, x_offset = self.search_next()
283
+ self.prompt = current_prompt
284
+ return y_offset, x_offset
285
+
286
+ def _do_commands(self):
287
+ import curses
288
+
289
+ while True:
290
+ self._clear_prompt()
291
+ try:
292
+ ch = self.pad.getch()
293
+ except KeyboardInterrupt:
294
+ return "n"
295
+ max_y, max_x = self.screen.getmaxyx()
296
+ _, pad_max_x = self.pad.getmaxyx()
297
+ max_y -= 2 # prompt
298
+ y_offset = 0
299
+ x_offset = 0
300
+ margin = 0
301
+ y_delta = 0
302
+ x_delta = 0
303
+
304
+ y, x = self.pad.getyx()
305
+ if ch == ord("q"):
306
+ return "exit"
307
+ elif ch in [ord("y"), ord("Y")]:
308
+ return "y"
309
+ elif ch in [ord("f"), ord("F")]:
310
+ return "force-yes"
311
+ elif ch == ord("a"):
312
+ if self.alternative_text:
313
+ self.text, self.alternative_text = self.alternative_text, self.text
314
+ self.screen.clear()
315
+ self._parse_text()
316
+ self._init_pad()
317
+ elif ch == ord("d"):
318
+ if self.debug_prompt.text == "":
319
+ self.debug_prompt.text = "init"
320
+ else:
321
+ self.debug_prompt.text = ""
322
+ elif ch == ord("n"):
323
+ y_offset, x_offset = self.search_next()
324
+ margin = 10
325
+ elif ch == ord("N"):
326
+ y_offset, x_offset = self.search_next(prev=True)
327
+ margin = 10
328
+ elif ch == ord("/"):
329
+ y_offset, x_offset = self._search_prompt()
330
+ margin = 10
331
+ elif ch == curses.KEY_UP:
332
+ y_offset = -1
333
+ elif ch == curses.KEY_PPAGE:
334
+ y_offset = -10
335
+ elif ch == curses.KEY_HOME:
336
+ y_offset = -len(self.lines)
337
+ elif ch == curses.KEY_DOWN:
338
+ y_offset = 1
339
+ elif ch == curses.KEY_NPAGE:
340
+ y_offset = 10
341
+ elif ch == curses.KEY_END:
342
+ y_offset = len(self.lines)
343
+ elif ch == curses.KEY_LEFT:
344
+ x_offset = -1
345
+ elif ch == curses.KEY_RIGHT:
346
+ x_offset = 1
347
+
348
+ if y_offset or x_offset:
349
+ y = max(0, y + y_offset)
350
+ y = min(self.rows, y)
351
+ x = max(0, x + x_offset)
352
+ x = min(self.cols, x)
353
+
354
+ y_delta = y - (self.top + max_y - margin)
355
+ if y_delta > 0:
356
+ self.top += y_delta
357
+ elif (y - margin) < self.top:
358
+ self.top = y
359
+
360
+ self.top = min(self.top, len(self.lines) - max_y)
361
+
362
+ x_delta = x - (self.left + max_x)
363
+ if x_delta > 0:
364
+ self.left += x_delta
365
+ elif x < self.left:
366
+ self.left = x
367
+
368
+ x = min(x, pad_max_x - 1)
369
+ self.pad.move(y, x)
370
+
371
+ if self.debug_prompt.text != "":
372
+ debug_line = "y=%s x=%s, x_delta=%s y_delta=%s top=%s, max_y=%s max_x=%s lines=%s" % \
373
+ (y, x, x_delta, y_delta, self.top, max_y, max_x, len(self.lines))
374
+ self.debug_prompt.text = debug_line
375
+ self.debug_prompt.color = "green_bold"
376
+ self.debug_prompt.offset = max_x - len(debug_line) - 1
377
+
378
+ if self.debug_prompt.text == "":
379
+ self.page_position.color = "highlight"
380
+ self.page_position.text = "line %s/%s" % (y, len(self.lines))
381
+ self.page_position.offset = max_x - len(self.page_position.text) - 1
382
+
383
+ self.show()
384
+
385
+ def loop(self):
386
+ import curses
387
+
388
+ res = None
389
+ old_cursor = None
390
+ try:
391
+ self.screen = curses.initscr()
392
+ self.screen.leaveok(True)
393
+ self.curses_lines = curses.LINES # pylint: disable=maybe-no-member
394
+ curses.start_color()
395
+ curses.noecho() # no echo key input
396
+ curses.cbreak() # input with no-enter keyed
397
+ try:
398
+ old_cursor = curses.curs_set(2)
399
+ except Exception:
400
+ pass
401
+ self._init_colors()
402
+ self._parse_text()
403
+ self._init_pad()
404
+ self.pad.move(0, 0)
405
+ self.show()
406
+ res = self._do_commands()
407
+ except Exception as err:
408
+ get_logger().exception("%s", err)
409
+ finally:
410
+ if old_cursor is not None:
411
+ curses.curs_set(old_cursor)
412
+ curses.nocbreak()
413
+ curses.echo()
414
+ curses.endwin()
415
+ return res
416
+
417
+
418
+ def init_colors():
419
+ import curses
420
+
421
+ curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
422
+ curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK)
423
+ curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK)
424
+ curses.init_pair(4, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
425
+ curses.init_pair(5, curses.COLOR_YELLOW, curses.COLOR_BLACK)
426
+ curses.init_pair(6, curses.COLOR_BLUE, curses.COLOR_WHITE)
427
+ curses.init_pair(7, curses.COLOR_RED, curses.COLOR_WHITE)
428
+ curses.init_pair(8, curses.COLOR_BLACK, curses.COLOR_WHITE)
429
+ curses.init_pair(9, curses.COLOR_CYAN, curses.COLOR_BLUE)
430
+ return {
431
+ "green": curses.color_pair(1),
432
+ "green_bold": curses.color_pair(1) | curses.A_BOLD,
433
+ "cyan": curses.color_pair(2),
434
+ "red": curses.color_pair(3),
435
+ "magenta": curses.color_pair(4),
436
+ "yellow": curses.color_pair(5),
437
+ "blue": curses.color_pair(6),
438
+ "highlight": curses.color_pair(7),
439
+ None: curses.color_pair(8),
440
+ "cyan_blue": curses.color_pair(9),
441
+ }
annet/diff.py ADDED
@@ -0,0 +1,85 @@
1
+ import re
2
+ from itertools import groupby
3
+ from typing import Generator, List, Mapping, Tuple, Union
4
+
5
+ from annet.annlib.diff import ( # pylint: disable=unused-import
6
+ colorize_line,
7
+ diff_cmp,
8
+ diff_ops,
9
+ gen_pre_as_diff,
10
+ resort_diff,
11
+ )
12
+ from annet.annlib.output import format_file_diff
13
+
14
+ from annet import patching
15
+ from annet.cli_args import ShowDiffOptions
16
+ from annet.output import output_driver_connector
17
+ from annet.storage import Device
18
+ from annet.tabparser import make_formatter
19
+ from annet.types import Diff, PCDiff
20
+
21
+
22
+ # NOCDEV-1720
23
+
24
+
25
+ def gen_sort_diff(
26
+ diffs: Mapping[Device, Union[Diff, PCDiff]], args: ShowDiffOptions
27
+ ) -> Generator[Tuple[str, Generator[str, None, None], bool], None, None]:
28
+ """
29
+ Возвращает осортированный дифф, совместимый с write_output
30
+ :param diffs: Маппинг устройства в дифф
31
+ :param args: Параметры коммандной строки
32
+ """
33
+ # NOCDEV-2201 non-null --dest implies --no-collapse
34
+ if args.no_collapse or args.dest:
35
+ devices_to_diff = {(dev,): diff for dev, diff in diffs.items()}
36
+ else:
37
+ non_pc_diffs = {dev: diff for dev, diff in diffs.items() if not isinstance(diff, PCDiff)}
38
+ devices_to_diff = collapse_diffs(non_pc_diffs)
39
+ devices_to_diff.update({(dev,): diff for dev, diff in diffs.items() if isinstance(diff, PCDiff)})
40
+ for devices, diff_obj in devices_to_diff.items():
41
+ if not diff_obj:
42
+ continue
43
+ if isinstance(diff_obj, PCDiff):
44
+ for diff_file in diff_obj.diff_files:
45
+ diff_text = (
46
+ "\n".join(diff_file.diff_lines)
47
+ if args.no_color
48
+ else "\n".join(format_file_diff(diff_file.diff_lines))
49
+ )
50
+ yield diff_file.label, diff_text, False
51
+ else:
52
+ output_driver = output_driver_connector.get()
53
+ dest_name = ", ".join([output_driver.cfg_file_names(dev)[0] for dev in devices])
54
+ pd = patching.make_pre(resort_diff(diff_obj))
55
+ yield dest_name, gen_pre_as_diff(pd, args.show_rules, args.indent, args.no_color), False
56
+
57
+
58
+ def _transform_text_diff_for_collapsing(text_diff) -> List[str]:
59
+ for line_no, line in enumerate(text_diff):
60
+ text_diff[line_no] = re.sub(r"(snmp-agent .+) cipher \S+ (.+)", r"\1 cipher ENCRYPTED \2", line)
61
+ return text_diff
62
+
63
+
64
+ def _make_text_diff(device: Device, diff: Diff) -> List[str]:
65
+ formatter = make_formatter(device.hw)
66
+ res = formatter.diff(diff)
67
+ return res
68
+
69
+
70
+ def collapse_diffs(diffs: Mapping[Device, Diff]) -> Mapping[Tuple[Device, ...], Diff]:
71
+ """
72
+ Группировка диффов.
73
+ :param diffs:
74
+ :return: дикт аналогичный типу Diff, но с несколькими dev в ключе.
75
+ Нужно учесть что дифы сверяются в отформатированном виде
76
+ """
77
+ diffs_with_test = {dev: [diff, _transform_text_diff_for_collapsing(_make_text_diff(dev, diff))] for dev, diff in
78
+ diffs.items()}
79
+ res = {}
80
+ for _, collapsed_diff_iter in groupby(sorted(diffs_with_test.items(), key=lambda x: (x[0].hw.vendor, x[1][1])),
81
+ key=lambda x: x[1][1]):
82
+ collapsed_diff = list(collapsed_diff_iter)
83
+ res[tuple(x[0] for x in collapsed_diff)] = collapsed_diff[0][1][0]
84
+
85
+ return res