Debian Codegraph @

cylc/flow/scripts/diff.py

raw
1 #!/usr/bin/env python3
2
3 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
4 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
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 """cylc diff [OPTIONS] ARGS
20
21 Compare two workflow configurations and display any differences.
22
23 Differencing is done after parsing the flow.cylc files so it takes
24 account of default values that are not explicitly defined, it disregards
25 the order of configuration items, and it sees any include-file content
26 after inlining has occurred.
27
28 Files in the workflow bin directory and other sub-directories of the
29 run directory are not currently differenced.
30 """
31
32 import sys
33 from typing import TYPE_CHECKING
34
35 from cylc.flow.id_cli import parse_id
36 from cylc.flow.option_parsers import (
37 WORKFLOW_ID_OR_PATH_ARG_DOC,
38 CylcOptionParser as COP,
39 icp_option,
40 )
41 from cylc.flow.config import WorkflowConfig
42 from cylc.flow.templatevars import get_template_vars
43 from cylc.flow.terminal import cli_function
44
45 if TYPE_CHECKING:
46 from optparse import Values
47
48
49 n_oone = 0
50 n_otwo = 0
51 n_diff = 0
52
53
54 def diffdict(one, two, oone, otwo, diff):
55 global n_oone, n_otwo, n_diff
56 # Recursively difference two dictionaries in which any element
57 # may be another dictionary, keeping items that appear only
58 # in one or the other, and items that appear in both but differ.
59 for key in one:
60 if key not in two:
61 oone[key] = one[key]
62 n_oone += 1
63 elif one[key] != two[key]:
64 if isinstance(one[key], dict):
65 for item in oone, otwo, diff:
66 if key not in item:
67 item[key] = {}
68 diffdict(one[key], two[key], oone[key], otwo[key], diff[key])
69 else:
70 diff[key] = (one[key], two[key])
71 n_diff += 1
72
73 for key in two:
74 if key not in one:
75 otwo[key] = two[key]
76 n_otwo += 1
77
78
79 def prdict(dct, arrow='<', section='', level=0, diff=False, nested=False):
80 """Recursively print, in pseudo 'diff' format, the contents of
81 one of the three dictionaries populated by the diffdict() function
82 above (any element may itself be a dictionary).
83 """
84
85 if section != '':
86 prfx = section + ' '
87 else:
88 prfx = ''
89
90 if section == '':
91 sctn = '(top)'
92 else:
93 sctn = section
94
95 foo = False
96
97 for key in dct:
98 if isinstance(dct[key], dict):
99 lvl = level + 1
100 if nested:
101 pre = prfx + '\n' + ' ' * lvl
102 else:
103 pre = prfx
104 prdict(dct[key], arrow,
105 pre + '[' * lvl + str(key) + ']' * lvl, lvl,
106 diff, nested)
107 else:
108 if not foo:
109 if nested:
110 print(' ', sctn)
111 else:
112 print('\n ', sctn)
113 foo = True
114
115 if diff:
116 print(' < ', key, '=', dct[key][0])
117 print(' > ', key, '=', dct[key][1])
118 else:
119 print(' ' + arrow + ' ', key, '=', dct[key])
120
121
122 def get_option_parser() -> COP:
123 parser = COP(
124 __doc__,
125 jset=True,
126 argdoc=[
127 (f'WORKFLOW_{n}', WORKFLOW_ID_OR_PATH_ARG_DOC[1])
128 for n in (1, 2)
129 ]
130 )
131
132 parser.add_option(
133 "-n", "--nested",
134 help="print flow.cylc section headings in nested form.",
135 action="store_true", default=False, dest="nested"
136 )
137
138 parser.add_option(icp_option)
139
140 return parser
141
142
143 @cli_function(get_option_parser)
144 def main(parser: COP, options: 'Values', workflow_id1: str, workflow_id2: str):
145 workflow_id_1, _, workflow_file_1_ = parse_id(
146 workflow_id1,
147 src=True,
148 constraint='workflows',
149 )
150 workflow_id_2, _, workflow_file_2_ = parse_id(
151 workflow_id2,
152 src=True,
153 constraint='workflows',
154 )
155 if workflow_file_1_ == workflow_file_2_:
156 parser.error("You can't diff a single workflow.")
157 print(f"Parsing {workflow_id_1} ({workflow_file_1_})")
158 template_vars = get_template_vars(options)
159 config1 = WorkflowConfig(
160 workflow_id_1, workflow_file_1_, options, template_vars
161 ).cfg
162 print(f"Parsing {workflow_id_2} ({workflow_file_2_})")
163 config2 = WorkflowConfig(
164 workflow_id_2, workflow_file_2_, options, template_vars
165 ).cfg
166
167 if config1 == config2:
168 print(
169 f"Workflow definitions {workflow_id_1} and {workflow_id_2} are "
170 f"identical"
171 )
172 sys.exit(0)
173
174 print(f"Workflow definitions {workflow_id_1} and {workflow_id_2} differ")
175
176 workflow1_only = {} # type: ignore
177 workflow2_only = {} # type: ignore
178 diff_1_2 = {} # type: ignore
179 # TODO: this whole file could do wih refactoring at some point
180
181 diffdict(config1, config2, workflow1_only, workflow2_only, diff_1_2)
182
183 if n_oone > 0:
184 print(f'\n{n_oone} items only in {workflow_id_1} (<)')
185 prdict(workflow1_only, '<', nested=options.nested)
186
187 if n_otwo > 0:
188 print(f'\n{n_otwo} items only in {workflow_id_2} (>)')
189 prdict(workflow2_only, '>', nested=options.nested)
190
191 if n_diff > 0:
192 print(f'\n{n_diff} common items differ {workflow_id_1}(<) '
193 f'{workflow_id_2}(>)')
194 prdict(diff_1_2, '', diff=True, nested=options.nested)