diff options
| author | Claude <noreply@anthropic.com> | 2026-11-30 20:49:13 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-11-30 20:49:13 +0000 |
| commit | 761a93d46638340c9df6a73b46aa3c9826a2213d (patch) | |
| tree | 7c69b5213ecd70f4528640801b8b5290aa205d6f /plugins/code-modernization/scripts | |
| parent | 0fbfda5a91f4adc311daca25acc99132f40f0b6e (diff) | |
code-modernization: one rule per decision and smaller shards in rule extraction
Remove the rules-per-line target, cut tree shards to about 1,000 lines, and
report files and rules that were dropped without notice. Version 1.2.0.
Diffstat (limited to 'plugins/code-modernization/scripts')
4 files changed, 380 insertions, 29 deletions
diff --git a/plugins/code-modernization/scripts/make_shards.py b/plugins/code-modernization/scripts/make_shards.py index 175d6980..1365d9bc 100644 --- a/plugins/code-modernization/scripts/make_shards.py +++ b/plugins/code-modernization/scripts/make_shards.py @@ -1,17 +1,20 @@ #!/usr/bin/env python3 """Split a system's source into shards for per-module rule extraction. - python3 make_shards.py <system> [module-pattern] [--workspace DIR] [--all] + python3 make_shards.py <system> [module-pattern] [--workspace DIR] [--all] [--unmapped] The source directory is legacy/<system> (a copy, or a symlink to where the code lives). With analysis/<system>/topology.json, one shard per map module (small modules of a domain merged); without it, one shard per directory of source -files. The list is written to analysis/<system>/extract-rules.modules.json as -[{"name", "domain", "files": [relative to the source dir], "loc"}], the form the -extract-rules workflow takes. Standard library only. +files. --unmapped adds shards for the source files the map has no module for. The list is written to analysis/<system>/extract-rules.modules.json as +[{"name", "domain", "files": [relative to the source dir], "loc", "lines"?}], the form the +extract-rules workflow takes. A long file is cut into several shards, each with "lines": [first, last]. Standard library only. """ +import codecs +import collections import fnmatch import json import os +import re import sys SOURCE_EXT = { @@ -23,7 +26,15 @@ SOURCE_EXT = { '.go', '.rs', '.py', '.rb', '.php', '.pl', '.pm', '.js', '.jsx', '.ts', '.tsx', '.swift', '.lua', '.tcl', '.erl', '.ex', '.exs', '.clj', '.hs', '.ml', '.r', '.sh', '.bat', '.ps1', # web and data - '.asp', '.aspx', '.ascx', '.cshtml', '.jsp', '.jspx', '.sql', '.pks', '.pkb', '.plsql', '.tf', + '.asp', '.aspx', '.ascx', '.cshtml', '.jsp', '.jspx', '.tf', + # database code: procedures, packages, triggers, views, embedded SQL + '.sql', '.pks', '.pkb', '.plsql', '.pls', '.pck', '.pkg', '.spc', '.bdy', '.tps', '.tpb', '.prc', '.fnc', '.trg', '.vw', '.sp', '.udf', + '.ddl', '.tsql', '.psql', '.pgsql', '.db2', '.pc', '.pco', '.sqc', '.sqb', +} +# Documents, media, build output and project files: not worth reporting as left out. +NOT_CODE_EXT = { + '.sln', '.csproj', '.resx', '.md', '.rst', '.pdf', '.doc', '.docx', '.log', '.lock', '.png', '.jpg', '.jpeg', '.gif', '.svg', '.ico', '.bmp', + '.woff', '.woff2', '.ttf', '.eot', '.css', '.zip', '.gz', '.tar', '.jar', '.class', '.dll', '.exe', '.o', '.so', '.pyc', } SKIP_DIRS = { '.git', '.svn', '.hg', 'node_modules', 'vendor', 'third_party', 'thirdparty', 'dist', 'build', 'target', 'bin', 'obj', 'out', @@ -31,9 +42,11 @@ SKIP_DIRS = { } TEST_DIRS = {'test', 'tests', '__tests__', 'spec', 'specs'} MAX_FILES = 25 -MAX_LOC = 5000 +MAX_LOC = 1000 # one extractor writes all of a shard's rules in one answer and leaves detail out of a long one +SPLIT_LOC = 1500 # a file longer than this is cut into line ranges of about MAX_LOC lines +CUT_WINDOW = 100 # how far a cut may move to land between two blocks of code SMALL = 300 -TINY_ESTATE = 30 +TINY_ESTATE = 30 # files; a tiny estate also fits in one shard (MAX_LOC lines) MAX_BYTES = 5_000_000 @@ -50,7 +63,8 @@ def source_dir(workspace, system): return os.path.join(workspace, 'legacy', system) -def count_lines(path): +def read_source(path): + """The file's bytes, with UTF-16 converted to UTF-8, or None when it is unreadable, binary or too large.""" try: if os.path.getsize(path) > MAX_BYTES: return None @@ -58,7 +72,14 @@ def count_lines(path): data = handle.read() except OSError: return None - if b'\x00' in data[:4096]: + if data[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE): # text, though every other byte is zero + data = data.decode('utf-16', errors='replace').encode('utf-8') + return None if b'\x00' in data[:4096] else data + + +def count_lines(path): + data = read_source(path) + if data is None: return None return data.count(b'\n') + (1 if data and not data.endswith(b'\n') else 0) @@ -111,6 +132,7 @@ def shared_locations(modules, source): def from_topology(topology, source, system, pattern): + """Shards, the number of modules in them, map files outside the source directory, and every file the map makes a module.""" modules, names, escaped = [], set(), [] def walk(node, domain): @@ -131,16 +153,19 @@ def from_topology(topology, source, system, pattern): walk(child, domain) walk(topology['root'], '') - total = len(modules) + mapped = {os.path.normpath(f).replace(os.sep, '/') for m in modules for f in m['files']} unusable = shared_locations(modules, source) if unusable: raise ValueError('%d map module(s) share a location or name a directory instead of a file (first: %s)' % (len(unusable), unusable[0][0])) if pattern: match = matcher(pattern) modules = [m for m in modules if match(m['name']) or any(match(f) for f in m['files'])] - # merge small modules of the same domain; never split one + # merge small modules of the same domain shards, pool, counter = [], {}, {} for module in modules: + real = count_lines(os.path.join(source, module['files'][0])) + if real and module['loc'] and module['loc'] < SMALL <= real: + module['loc'] = real # the map's size is out of date if module['loc'] and module['loc'] < SMALL: current = pool.get(module['domain']) if current is None or current['loc'] >= SMALL or len(current['files']) >= MAX_FILES: @@ -154,11 +179,23 @@ def from_topology(topology, source, system, pattern): current['loc'] += module['loc'] else: shards.append(module) - return shards, len(modules), escaped, total + return shards, len(modules), escaped, mapped + +def extension_label(name): + """A file's extension for a note. File names are untrusted, so anything unusual is reported without its text.""" + ext = os.path.splitext(name)[1].lower() + return ext if re.fullmatch(r'\.[a-z0-9_]{1,10}', ext) else ('with an unusual extension' if ext else 'with no extension') -def from_tree(source, pattern, include_all): - by_dir, skipped = {}, {'vendored or generated': 0, 'tests': 0, 'unreadable or binary': 0, 'symbolic links': 0} + +def most_common(counter): + return ', '.join(f'{n} {label}' for label, n in counter.most_common(20)) + (f', and {len(counter) - 20} more types' if len(counter) > 20 else '') + + +def scan_tree(source, include_all): + """Source files by directory as (path, lines), counts of what was left out, files that could not be read, and files of unknown type.""" + by_dir, skipped = {}, {'vendored or generated': 0, 'tests': 0, 'symbolic links': 0} + unread, unknown = [], [] for root, dirs, files in os.walk(source): kept = [] for d in sorted(dirs): @@ -170,19 +207,25 @@ def from_tree(source, pattern, include_all): kept.append(d) dirs[:] = kept for name in sorted(files): - if os.path.splitext(name)[1].lower() not in SOURCE_EXT or name.endswith('.min.js'): - continue + ext = os.path.splitext(name)[1].lower() path = os.path.join(root, name) + rel = os.path.relpath(path, source).replace(os.sep, '/') + if ext not in SOURCE_EXT or name.endswith('.min.js'): + if ext not in SOURCE_EXT and ext not in NOT_CODE_EXT and not name.startswith('.'): + unknown.append(rel) + continue if os.path.islink(path): skipped['symbolic links'] += 1 # a link can point outside the source directory continue lines = count_lines(path) if lines is None: - skipped['unreadable or binary'] += 1 + unread.append(rel) continue - rel = os.path.relpath(path, source).replace(os.sep, '/') by_dir.setdefault(os.path.dirname(rel), []).append((rel, lines)) - whole = sum(len(fs) for fs in by_dir.values()) + return by_dir, skipped, unread, unknown + + +def from_tree(by_dir, pattern): if pattern: match = matcher(pattern) by_dir = {d: [f for f in fs if match(f[0])] for d, fs in by_dir.items()} @@ -202,7 +245,40 @@ def from_tree(source, pattern, include_all): if rel is not None: chunk.append((rel, lines)) chunk_loc += lines - return shards, total, skipped, whole + return shards, total + + +def line_ranges(lines): + """Cut a long file into [first, last] ranges of about equal length. + + Each cut moves up to CUT_WINDOW lines to start on the least indented line after a blank one.""" + parts = -(-len(lines) // MAX_LOC) + starts = [0] + for part in range(1, parts): + aim = part * len(lines) // parts + near = [i for i in range(aim - CUT_WINDOW, aim + CUT_WINDOW + 1) if lines[i].strip()] or [aim] + starts.append(min(near, key=lambda i: (bool(lines[i - 1].strip()), len(lines[i]) - len(lines[i].lstrip()), abs(i - aim)))) + return [[first + 1, last] for first, last in zip(starts, starts[1:] + [len(lines)])] + + +def split_long_files(shards, source): + out = [] + for shard in shards: + data = read_source(os.path.join(source, shard['files'][0])) if len(shard['files']) == 1 else None + lines = data.split(b'\n') if data else [] + if lines and not lines[-1]: + lines.pop() + if len(lines) <= SPLIT_LOC: + out.append(shard) + continue + for first, last in line_ranges(lines): + out.append({**shard, 'name': f"{shard['name']}:{first}-{last}", 'loc': last - first + 1, 'lines': [first, last]}) + return out + + +def quoted(names): + """Up to five file names for a note, quoted and shortened.""" + return ', '.join(json.dumps(name[-80:]) + extra for name, extra in names[:5]) def main(argv): @@ -213,7 +289,7 @@ def main(argv): workspace = argv[argv.index('--workspace') + 1] args = [a for a in args if a != workspace] if not args: - print('usage: make_shards.py <system> [module-pattern] [--workspace DIR] [--all]', file=sys.stderr) + print('usage: make_shards.py <system> [module-pattern] [--workspace DIR] [--all] [--unmapped]', file=sys.stderr) return 2 system, pattern = args[0], (args[1] if len(args) > 1 else '') source = source_dir(workspace, system) @@ -228,40 +304,75 @@ def main(argv): out = os.path.join(workspace, 'analysis', system, 'extract-rules.modules.json') topo_path = os.path.join(workspace, 'analysis', system, 'topology.json') notes = [] + by_dir, skipped, unread, unknown = scan_tree(source, '--all' in flags) + tree = [entry for entries in by_dir.values() for entry in entries] + mapped, unmapped_note = None, None if os.path.isfile(topo_path): try: with open(topo_path, encoding='utf-8') as handle: topology = json.load(handle) - shards, modules, escaped, whole = from_topology(topology, source, system, pattern) + shards, modules, escaped, mapped = from_topology(topology, source, system, pattern) origin = f'{modules} map modules' if escaped: notes.append(f'{len(escaped)} map file(s) resolve outside the source directory and were left out (first: {escaped[0]})') missing = [f for s in shards for f in s['files'] if not os.path.exists(os.path.join(source, f))] if missing: notes.append(f'{len(missing)} file(s) named by the map do not exist under the source directory (first: {missing[0]})') + match = matcher(pattern) if pattern else None + unmapped = sorted(((rel, n) for rel, n in tree if rel not in mapped and (not match or match(rel))), key=lambda e: (-e[1], e[0])) + if unmapped and '--unmapped' in flags: + left = {d: [e for e in entries if e[0] not in mapped] for d, entries in by_dir.items()} + shards += from_tree(left, pattern)[0] + origin += f' and {len(unmapped)} unmapped file(s)' + elif unmapped: + kinds = collections.Counter(extension_label(rel) for rel, _ in unmapped) + unmapped_note = (f'{len(unmapped)} source file(s) ({sum(n for _, n in unmapped)} lines: {most_common(kinds)}) are not modules in the map, ' + 'so no rules will be mined from them. Re-run with --unmapped to include them. ' + f'Largest: {quoted([(rel, f" ({n} lines)") for rel, n in unmapped])}') except (ValueError, KeyError, OSError) as error: print(f'note: the map cannot be sharded by module ({error}); reading the directory tree instead.') - shards, files, skipped, whole = from_tree(source, pattern, '--all' in flags) + shards, files = from_tree(by_dir, pattern) + mapped = None origin = f'{files} source files (tree)' else: - shards, files, skipped, whole = from_tree(source, pattern, '--all' in flags) + shards, files = from_tree(by_dir, pattern) origin = f'{files} source files (no topology.json: read from the directory tree)' + if mapped is None: + mapped = set() left_out = ', '.join(f'{n} {k}' for k, n in skipped.items() if n) if left_out: notes.append(f'left out: {left_out}') + match = matcher(pattern) if pattern else None + unread_left = [rel for rel in unread if rel not in mapped and (not match or match(rel))] + if unread_left: + notes.append(f'{len(unread_left)} source file(s) were left out because they are binary, unreadable or over 5 MB: {quoted([(rel, "") for rel in unread_left])}') + unknown = [rel for rel in unknown if rel not in mapped and (not match or match(rel))] + if unknown: + notes.append(f'{len(unknown)} file(s) were left out because their extension is not a known source type ' + f'({most_common(collections.Counter(extension_label(rel) for rel in unknown))}). Add any that hold logic to the shard list by hand.') if not shards: + for note in notes + ([unmapped_note] if unmapped_note else []): + print(f'note: {note}', file=sys.stderr) print('0 shards: the pattern matched nothing, or no source files were found. Nothing was written.', file=sys.stderr) return 1 + shards = split_long_files(shards, source) + cut = collections.Counter(s['files'][0] for s in shards if 'lines' in s) + if cut: + notes.append(f'{len(cut)} long file(s) were cut into {sum(cut.values())} shards. Remove any that hold only data or generated code ' + f'from the shard list. Largest: {quoted([(rel, f" ({n} shards)") for rel, n in cut.most_common()])}') os.makedirs(os.path.dirname(out), exist_ok=True) tmp = out + '.tmp' with open(tmp, 'w', encoding='utf-8') as handle: json.dump(shards, handle, indent=1) os.replace(tmp, out) - file_count = sum(len(s['files']) for s in shards) + file_count = len({f for s in shards for f in s['files']}) loc = sum(s['loc'] or 0 for s in shards) - print(f'{len(shards)} shards from {origin}, {file_count} files, {loc} lines -> {os.path.relpath(out, workspace)}') - if whole < TINY_ESTATE: - print(f'tiny estate: the system has fewer than {TINY_ESTATE} source files, so sharding adds little (run the workflow in lens mode).') + print(f'{len(shards)} shards from {origin}, {file_count} files in all, {loc} lines -> {os.path.relpath(out, workspace)}') + tiny = max(len(mapped), len(tree)) < TINY_ESTATE and max(loc, sum(n for _, n in tree)) <= MAX_LOC and not unread + if unmapped_note and not tiny: # lens mode reads every file + notes.append(unmapped_note) + if tiny: + print(f'tiny estate: the system has fewer than {TINY_ESTATE} source files and at most {MAX_LOC} lines, so sharding adds little (run the workflow in lens mode).') for note in notes: print(f'note: {note}') return 0 diff --git a/plugins/code-modernization/scripts/render_rules.py b/plugins/code-modernization/scripts/render_rules.py index fa609332..6f04e0c1 100644 --- a/plugins/code-modernization/scripts/render_rules.py +++ b/plugins/code-modernization/scripts/render_rules.py @@ -72,7 +72,7 @@ def render_rule(number, rule): out.append(f"**Parameters:** {block(rule['parameters'])}") cases = rule.get('edgeCases') or [] if cases: - out.append('**Edge cases handled:** ' + '; '.join(one_line(c, 200) for c in cases)) + out.append('**Edge cases handled:** ' + '; '.join(one_line(c, 1000) for c in cases)) if rule.get('suspectedDefect'): out.append(f"**Suspected defect:** {block(rule['suspectedDefect'])}") confidence = one_line(rule.get('confidence'), 10) diff --git a/plugins/code-modernization/scripts/tests/test_extract_workflow.py b/plugins/code-modernization/scripts/tests/test_extract_workflow.py new file mode 100644 index 00000000..063a5749 --- /dev/null +++ b/plugins/code-modernization/scripts/tests/test_extract_workflow.py @@ -0,0 +1,131 @@ +"""Runs workflows/extract-rules.js under node with scripted agents in place of the model.""" +import json +import os +import shutil +import subprocess +import unittest + +PLUGIN = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +WORKFLOW = os.path.join(PLUGIN, 'workflows', 'extract-rules.js') + +# Extractors return the next entry of `extracts`. Referees confirm unless `verdicts` has the cited source. +# P0 judges agree unless `notP0` has the cited source. +HARNESS = r""" +const fs = require('fs') +const spec = JSON.parse(fs.readFileSync(0, 'utf8')) +const source = fs.readFileSync(process.argv[1], 'utf8').replace('export const meta', 'const meta') +const cited = prompt => /Citation[^\n]*<<<UNTRUSTED\n([^\n]*)/.exec(prompt)[1] +let next = 0 +const prompts = [] +const agent = async (prompt, o) => { + if (o.phase === 'Extract') prompts.push(prompt) + if (o.phase === 'Extract') return { rules: spec.extracts[next++] || [], coveredAreas: [] } + if (o.phase === 'Verify') return cited(prompt) in (spec.verdicts || {}) ? spec.verdicts[cited(prompt)] : { verdict: 'confirmed', reason: 'ok' } + if (o.phase === 'P0 panel') return { p0Justified: !(spec.notP0 || []).includes(cited(prompt)), faithful: true, reason: 'r' } + if (o.phase === 'Consolidate') return { groups: [] } + return { dataObjects: [] } +} +const parallel = thunks => Promise.all(thunks.map(t => t())) +const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor +new AsyncFunction('args', 'agent', 'parallel', 'log', 'budget', source)(spec.args, agent, parallel, () => {}, { total: 0, remaining: () => Infinity }) + .then(result => console.log(JSON.stringify({ ...result, prompts }))) +""" + + +def rule(name, source, priority='P1'): + return {'name': name, 'category': 'Validation', 'priority': priority, 'source': source, 'plainEnglish': 'x', + 'given': 'g', 'when': 'w', 'then': 't', 'confidence': 'High'} + + +def extract(extracts, modules=1, **spec): + if isinstance(modules, int): + modules = [{'name': f'm{i}', 'files': ['a.sql']} for i in range(modules)] + args = {'system': 's', 'modules': modules} + done = subprocess.run(['node', '-e', HARNESS, WORKFLOW], input=json.dumps({'args': args, 'extracts': extracts, **spec}), + capture_output=True, text=True, encoding='utf-8') + if done.returncode: + raise AssertionError(done.stderr) + return json.loads(done.stdout) + + +def sources(result): + return [r['source'] for r in result['confirmedRules']] + + +@unittest.skipUnless(shutil.which('node'), 'needs node') +class AgentCapTests(unittest.TestCase): + def test_dense_shards_that_do_not_fit_are_left_for_a_follow_up_run(self): + result = extract([[rule(f'R{m}-{i}', f'a.sql:{i + 1}') for i in range(120)] for m in range(30)], modules=30) + self.assertLessEqual(result['stats']['agents'], 1000) + self.assertEqual(result['unverifiedRules'], []) + self.assertEqual(len(result['confirmedRules']), 120 * (30 - len(result['rerunModules']))) + + def test_typical_shards_all_fit(self): + result = extract([[rule(f'R{m}-{i}', f'a.sql:{i + 1}') for i in range(8)] for m in range(70)], modules=70) + self.assertEqual((len(result['confirmedRules']), result['rerunModules']), (560, [])) + + +@unittest.skipUnless(shutil.which('node'), 'needs node') +class DuplicateTests(unittest.TestCase): + def test_the_same_name_at_different_lines_is_two_rules(self): + result = extract([[rule('Validate amount', 'a.sql:10-20'), rule('Validate amount', 'a.sql:500-510')]]) + self.assertEqual(sources(result), ['a.sql:10-20', 'a.sql:500-510']) + + def test_the_same_name_at_overlapping_lines_is_one_rule(self): + result = extract([[rule('Validate amount', 'a.sql:10-20')], [rule('validate-amount', 'a.sql:15'), rule('Validate amount', 'a.sql')]], modules=2) + self.assertEqual(sources(result), ['a.sql:10-20']) + + def test_comparison_signs_and_non_latin_names_tell_rules_apart(self): + names = ['Fee when amount > 100', 'Fee when amount < 100', 'Fee when amount ≥ 100', 'Fee when amount ≤ 100', 'Status = A', 'Status != A', '金額の検証', '手数料の計算', 'Проверка суммы'] + result = extract([[rule(n, 'a.sql:1-50') for n in names]]) + self.assertEqual([r['name'] for r in result['confirmedRules']], names) + + def test_a_citation_corrected_onto_an_existing_rule_is_a_duplicate(self): + moved = {'verdict': 'wrong-citation', 'reason': 'r', 'correctedSource': 'a.sql:500-510'} + result = extract([[rule('Cap', 'a.sql:500-510'), rule('Cap', 'a.sql:10-20')]], verdicts={'a.sql:10-20': moved}) + self.assertEqual(sources(result), ['a.sql:500-510']) + self.assertEqual(len(result['rejectedRules']), 1) + + def test_a_citation_corrected_within_its_file_is_kept(self): + moved = {'verdict': 'wrong-citation', 'reason': 'r', 'correctedSource': 'a.sql:12-30'} + result = extract([[rule('Cap', 'a.sql:10-20')]], verdicts={'a.sql:10-20': moved}) + self.assertEqual(sources(result), ['a.sql:12-30']) + + def test_a_citation_corrected_to_a_bare_file_name_is_kept(self): + moved = {'verdict': 'wrong-citation', 'reason': 'r', 'correctedSource': 'a.sql'} + result = extract([[rule('Cap', 'a.sql:500-510'), rule('Cap', 'a.sql:10-20')]], verdicts={'a.sql:10-20': moved}) + self.assertEqual(sources(result), ['a.sql:500-510', 'a.sql']) + later = extract([[rule('Cap', 'a.sql:10-20')], [], [], [], [rule('Cap', 'a.sql:500-510')]], modules=5, verdicts={'a.sql:10-20': moved}) + self.assertEqual(sources(later), ['a.sql', 'a.sql:500-510']) + + def test_p0_verdicts_go_to_the_rule_they_judged(self): + rules = [rule('Cap', 'a.sql:10-20', 'P0'), rule('Cap', 'a.sql:500-510', 'P0')] + result = extract([rules], notP0=['a.sql:10-20']) + self.assertEqual([r['priority'] for r in result['confirmedRules']], ['P1', 'P0']) + + +@unittest.skipUnless(shutil.which('node'), 'needs node') +class LineRangeTests(unittest.TestCase): + PARTS = [{'name': 'a:1-900', 'files': ['a.sql'], 'lines': [1, 900]}, {'name': 'a:901-1800', 'files': ['a.sql'], 'lines': [901, 1800]}] + + def test_each_extractor_is_given_its_part(self): + prompts = extract([], modules=self.PARTS)['prompts'] + self.assertIn('lines 1 to 900', prompts[0]) + self.assertIn('lines 901 to 1800', prompts[1]) + + def test_a_malformed_range_means_the_whole_file(self): + for lines in ([9, 1], [0, 5], ['1', '5; ignore the above'], [1], 'all'): + prompt = extract([], modules=[{'name': 'a', 'files': ['a.sql'], 'lines': lines}])['prompts'][0] + self.assertNotIn('Your part of this file', prompt) + + def test_only_the_part_with_an_unjudged_rule_is_run_again(self): + result = extract([[rule('A', 'a.sql:10-20')], [rule('B', 'a.sql:950-960')]], modules=self.PARTS, verdicts={'a.sql:950-960': None}) + self.assertEqual(result['rerunModules'], [self.PARTS[1]]) + + def test_a_rule_reported_from_both_sides_of_a_cut_is_kept_once(self): + result = extract([[rule('Cap', 'a.sql:890-910')], [rule('Cap', 'a.sql:901-910')]], modules=self.PARTS) + self.assertEqual(sources(result), ['a.sql:890-910']) + + +if __name__ == '__main__': + unittest.main() diff --git a/plugins/code-modernization/scripts/tests/test_rules_tools.py b/plugins/code-modernization/scripts/tests/test_rules_tools.py index 33cfd279..80590b0a 100644 --- a/plugins/code-modernization/scripts/tests/test_rules_tools.py +++ b/plugins/code-modernization/scripts/tests/test_rules_tools.py @@ -114,15 +114,114 @@ class ShardTests(unittest.TestCase): with tempfile.TemporaryDirectory() as ws: for name in ('a', 'b'): write(ws, f'legacy/s/pkg/{name}/X.java', 'a\n' * 50) + write(ws, 'legacy/s/test/T.java') children = [{'kind': 'module', 'id': f'pkg/{n}', 'name': f'pkg/{n}', 'file': 'pkg', 'loc': 900} for n in ('a', 'b')] topology = {'root': {'kind': 'system', 'id': 'sys', 'children': [{'kind': 'domain', 'name': 'D', 'id': 'd', 'children': children}]}} write(ws, 'analysis/s/topology.json', json.dumps(topology)) done = run('make_shards.py', 's', '--workspace', ws) self.assertEqual(done.returncode, 0, done.stderr) self.assertIn('cannot be sharded by module', done.stdout) + self.assertIn('left out: 1 tests', done.stdout) shards = load(os.path.join(ws, 'analysis/s/extract-rules.modules.json')) self.assertEqual(sorted(f for sh in shards for f in sh['files']), ['pkg/a/X.java', 'pkg/b/X.java']) + def test_database_code_is_sharded_and_unknown_extensions_are_counted(self): + with tempfile.TemporaryDirectory() as ws: + for name in ('a.prc', 'b.PLS', 'c.trg', 'd.fnc', 'e.pc', 'f.tsql'): + write(ws, f'legacy/s/db/{name}', 'a\n' * 5) + for name in ('r1.xyz', 'r2.xyz', 'MEMBER', 'README.md', 'x.a b;c'): + write(ws, f'legacy/s/db/{name}') + done = run('make_shards.py', 's', '--workspace', ws) + self.assertEqual(done.returncode, 0, done.stderr) + shards = load(os.path.join(ws, 'analysis/s/extract-rules.modules.json')) + self.assertEqual(len(shards[0]['files']), 6) + note = [line for line in done.stdout.splitlines() if 'not a known source type' in line][0] + for part in ('2 .xyz', '1 with no extension', '1 with an unusual extension'): + self.assertIn(part, note) + self.assertNotIn('.md', note) + self.assertNotIn('a b;c', done.stdout) + + def test_unknown_extensions_are_named_when_nothing_is_sharded(self): + with tempfile.TemporaryDirectory() as ws: + write(ws, 'legacy/s/a.xyz') + done = run('make_shards.py', 's', '--workspace', ws) + self.assertEqual(done.returncode, 1) + self.assertIn('1 .xyz', done.stderr) + + def test_utf16_source_is_text_and_binary_is_not(self): + with tempfile.TemporaryDirectory() as ws: + os.makedirs(os.path.join(ws, 'legacy/s')) + for name, data in (('le.sql', b'\xff\xfe' + 'SELECT 1\r\nGO\r\n'.encode('utf-16-le')), + ('be.sql', b'\xfe\xff' + 'SELECT 1\nGO'.encode('utf-16-be')), + ('blob.sql', b'ab\x00\x01cd')): + with open(os.path.join(ws, 'legacy/s', name), 'wb') as handle: + handle.write(data) + done = run('make_shards.py', 's', '--workspace', ws) + shards = load(os.path.join(ws, 'analysis/s/extract-rules.modules.json')) + self.assertEqual((shards[0]['files'], shards[0]['loc']), (['be.sql', 'le.sql'], 4)) + self.assertIn('binary, unreadable or over 5 MB: "blob.sql"', done.stdout) + self.assertNotIn('tiny estate', done.stdout) + + def test_a_few_very_large_files_are_not_a_tiny_estate(self): + with tempfile.TemporaryDirectory() as ws: + write(ws, 'legacy/small/a.sql', 'a\n' * 200) + self.assertIn('tiny estate', run('make_shards.py', 'small', '--workspace', ws).stdout) + for i in range(4): + write(ws, f'legacy/big/p{i}.sql', 'a\n' * 4000) + self.assertNotIn('tiny estate', run('make_shards.py', 'big', '--workspace', ws).stdout) + self.assertNotIn('tiny estate', run('make_shards.py', 'big', 'p0*', '--workspace', ws).stdout) + + def test_source_files_the_map_leaves_out_are_reported(self): + with tempfile.TemporaryDirectory() as ws: + write(ws, 'legacy/s/A.cs', 'a\n' * 400) + write(ws, 'legacy/s/db/big.sql', 'a\n' * 900) + write(ws, 'legacy/s/db/q.xyz') + write(ws, 'legacy/s/db/job.sql', 'a\n' * 100) + topology = {'root': {'kind': 'system', 'id': 'sys', 'children': [ + {'kind': 'module', 'id': 'A', 'name': 'A', 'file': './A.cs', 'loc': 400}, + {'kind': 'job', 'id': 'J', 'name': 'J', 'file': 'db/job.sql', 'loc': 100}]}} + write(ws, 'analysis/s/topology.json', json.dumps(topology)) + done = run('make_shards.py', 's', '--workspace', ws) + self.assertIn('2 source file(s) (1000 lines: 2 .sql) are not modules in the map', done.stdout) + self.assertIn('not a known source type (1 .xyz)', done.stdout) + self.assertIn('"db/big.sql" (900 lines)', done.stdout) + self.assertNotIn('not modules in the map', run('make_shards.py', 's', 'A*', '--workspace', ws).stdout) + self.assertNotIn('not modules in the map', run('make_shards.py', 's', '--unmapped', '--workspace', ws).stdout) + shards = load(os.path.join(ws, 'analysis/s/extract-rules.modules.json')) + self.assertEqual(sorted(f for s in shards for f in s['files']), ['./A.cs', 'db/big.sql', 'db/job.sql']) + + def test_a_long_file_is_cut_between_blocks_into_ranges_that_cover_it(self): + block = 'IF x\nBEGIN\n' + ' SET y\n' * 37 + 'END\n\n' # 41 lines + with tempfile.TemporaryDirectory() as ws: + write(ws, 'legacy/s/long.sql', block * 100) + write(ws, 'legacy/s/no_blank_lines.sql', 'a\n' * 1600) + write(ws, 'legacy/s/short.sql', 'a\n' * 1400) + done = run('make_shards.py', 's', '--workspace', ws) + self.assertIn('3 files in all, 7100 lines', done.stdout) + self.assertIn('2 long file(s) were cut into 7 shards', done.stdout) + self.assertIn('"long.sql" (5 shards)', done.stdout) + shards = load(os.path.join(ws, 'analysis/s/extract-rules.modules.json')) + for name, total, parts in (('long.sql', 4100, 5), ('no_blank_lines.sql', 1600, 2)): + ranges = [s['lines'] for s in shards if s['files'] == [name]] + self.assertEqual(len(ranges), parts) + self.assertEqual([first for first, _ in ranges], [1] + [last + 1 for _, last in ranges[:-1]]) + self.assertEqual(ranges[-1][1], total) + self.assertTrue(all(s['lines'][0] % 41 == 1 for s in shards if s['files'] == ['long.sql'])) + self.assertNotIn('lines', [s for s in shards if s['files'] == ['short.sql']][0]) + self.assertEqual(len({s['name'] for s in shards}), len(shards)) + + def test_a_long_map_module_is_cut_too(self): + with tempfile.TemporaryDirectory() as ws: + write(ws, 'legacy/s/A.cbl', 'a\n' * 2500) + write(ws, 'legacy/s/B.cbl', 'a\n' * 10) + topology = {'root': {'kind': 'system', 'id': 'sys', 'children': [ + {'kind': 'module', 'id': 'A', 'name': 'A', 'file': 'A.cbl', 'loc': 100}, # an out-of-date size + {'kind': 'module', 'id': 'B', 'name': 'B', 'file': 'B.cbl', 'loc': 10}]}} + write(ws, 'analysis/s/topology.json', json.dumps(topology)) + self.assertEqual(run('make_shards.py', 's', '--workspace', ws).returncode, 0) + shards = load(os.path.join(ws, 'analysis/s/extract-rules.modules.json')) + self.assertEqual([s.get('lines') for s in shards], [[1, 833], [834, 1666], [1667, 2500], None]) + def test_missing_source_says_what_to_do(self): with tempfile.TemporaryDirectory() as ws: done = run('make_shards.py', 'nope', '--workspace', ws) @@ -187,6 +286,16 @@ class RenderTests(unittest.TestCase): self.assertIn('**Also cited:** b.c:3-4', text) self.assertNotIn('\n# fake heading', text) + def test_a_long_edge_case_keeps_its_ending(self): + case = 'when the account is overdue ' * 10 + 'the fee is 12.5% capped at 400.00' + result = {'confirmedRules': [{'name': 'Fee', 'category': 'Calculation', 'priority': 'P1', 'source': 'a.sql:1-2', 'plainEnglish': 'x', + 'given': 'g', 'when': 'w', 'then': 't', 'confidence': 'High', 'edgeCases': [case]}]} + with tempfile.TemporaryDirectory() as ws: + write(ws, 'analysis/s/rules_result.json', json.dumps(result)) + self.assertEqual(run('render_rules.py', 's', '--workspace', ws).returncode, 0) + with open(os.path.join(ws, 'analysis/s/BUSINESS_RULES.md'), encoding='utf-8') as handle: + self.assertIn('capped at 400.00', handle.read()) + def test_unreadable_result_is_an_error(self): with tempfile.TemporaryDirectory() as ws: self.assertEqual(run('render_rules.py', 's', '--workspace', ws).returncode, 1) |
