1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
|
#!/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] [--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. --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 math
import os
import re
import sys
SOURCE_EXT = {
# mainframe and legacy business languages
'.cbl', '.cob', '.cobol', '.cpy', '.pli', '.pl1', '.jcl', '.proc', '.rpg', '.rpgle', '.sqlrpgle', '.clle', '.nat', '.ada', '.adb', '.ads',
'.asm', '.bms', '.map', '.pas', '.dpr', '.prg', '.f', '.for', '.f90', '.f77',
# general purpose
'.java', '.kt', '.scala', '.groovy', '.cs', '.vb', '.vbs', '.bas', '.cls', '.frm', '.fs', '.c', '.h', '.cc', '.cpp', '.cxx', '.hpp', '.m', '.mm',
'.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', '.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',
'__pycache__', '.venv', 'venv', '.tox', '.gradle', '.idea', 'coverage', 'fixtures', 'testdata', 'test-data', 'generated',
}
TEST_DIRS = {'test', 'tests', '__tests__', 'spec', 'specs'}
MAX_FILES = 25
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 # files; a tiny estate also fits in one shard (MAX_LOC lines)
MAX_BYTES = 5_000_000
# Estimated agents per 1,000 lines for each depth: code that is mostly plumbing, and very dense business logic. Taken from
# simulated runs (T-SQL procedures, C utilities) and, for the low end of standard, from a 30,000-line estate.
AGENTS_PER_KLOC = {'Standard': (15, 55), 'Thorough': (20, 190)}
SMALL_SHARD = {'Standard': 40, 'Thorough': 125} # a short dense file needs more per line: 10 + lines / 5, up to this
LENS_AGENTS = {'Standard': (15, 100), 'Thorough': (20, 250)} # a tiny estate, about 1,000 lines
LENS_MIN_TOP = {'Standard': 100, 'Thorough': 150}
TOKENS_PER_AGENT = 16_000
def too_broad(path):
"""The filesystem root, the home directory or one of its parents, or a top-level system directory: never a system's code."""
real = os.path.realpath(path)
home = os.path.realpath(os.path.expanduser('~'))
parts = [p for p in real.split(os.sep) if p]
return real == os.sep or len(parts) < 2 or home == real or home.startswith(real + os.sep)
def source_dir(workspace, system):
"""The code is legacy/<system>: a copy, or a symlink to where it really lives."""
return os.path.join(workspace, 'legacy', system)
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
with open(path, 'rb') as handle:
data = handle.read()
except OSError:
return None
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)
def matcher(pattern):
"""A glob matches a name or a path (or its file name); a plain name such as `jetty-util` also matches what lies beneath it."""
plain_name = not any(ch in pattern for ch in '*?[')
wanted = pattern.strip('/')
def match(text):
if fnmatch.fnmatch(text, pattern) or fnmatch.fnmatch(os.path.basename(text), pattern):
return True
if plain_name:
padded = '/' + text.strip('/') + '/'
return padded.startswith('/' + wanted + '/') or ('/' + wanted + '/') in padded
return False
return match
def contained(source, rel):
"""True when `rel` under the source directory really resolves inside it (no `..`, no symlink out)."""
root = os.path.realpath(source)
real = os.path.realpath(os.path.join(source, rel))
return real == root or real.startswith(root + os.sep)
def relative_to_source(path, source, system):
"""A topology `file` may be absolute, workspace-relative or source-relative: return it source-relative."""
path = path.replace('\\', '/')
if os.path.isabs(path):
rel = os.path.relpath(path, source).replace(os.sep, '/')
return None if rel.startswith('..') else rel
for prefix in (f'legacy/{system}/', os.path.normpath(source).replace(os.sep, '/') + '/'):
if path.startswith(prefix):
return path[len(prefix):]
return path
def shared_locations(modules, source):
"""Locations several map modules share, or that are directories: modules without files of their own cannot be sharded."""
seen, shared = {}, []
for module in modules:
for rel in module['files']:
seen.setdefault(rel, []).append(module['name'])
for rel, owners in seen.items():
if len(owners) > 1 or os.path.isdir(os.path.join(source, rel)):
shared.append((rel, len(owners)))
return shared
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):
kind = node.get('kind')
if kind == 'domain':
domain = node.get('name') or node.get('id', '')
if kind == 'module' and node.get('file'):
rel = relative_to_source(str(node['file']), source, system)
if rel and not contained(source, rel):
escaped.append(rel)
elif rel:
name = str(node.get('name') or node.get('id'))
if name in names:
name = str(node.get('id') or name) # names can repeat across domains; ids are unique
names.add(name)
modules.append({'name': name, 'domain': domain, 'files': [rel], 'loc': node.get('loc') or None})
for child in node.get('children', []):
walk(child, domain)
walk(topology['root'], '')
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
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:
counter[module['domain']] = counter.get(module['domain'], 0) + 1
current = pool[module['domain']] = {
'name': f"{module['domain'] or 'misc'}:small-{counter[module['domain']]}",
'domain': module['domain'], 'files': [], 'loc': 0,
}
shards.append(current)
current['files'] += module['files']
current['loc'] += module['loc']
else:
shards.append(module)
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 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):
if d in SKIP_DIRS or (d.startswith('.') and d not in ('.',)):
skipped['vendored or generated'] += 1
elif d.lower() in TEST_DIRS and not include_all:
skipped['tests'] += 1
else:
kept.append(d)
dirs[:] = kept
for name in sorted(files):
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:
unread.append(rel)
continue
by_dir.setdefault(os.path.dirname(rel), []).append((rel, lines))
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()}
shards, total = [], 0
for directory in sorted(by_dir):
entries = by_dir[directory]
total += len(entries)
chunk, chunk_loc, part = [], 0, 1
label = directory or '.'
for rel, lines in entries + [(None, 0)]:
if rel is None or (chunk and (len(chunk) >= MAX_FILES or chunk_loc + lines > MAX_LOC)):
if chunk:
shards.append({'name': label if part == 1 else f'{label}#{part}', 'domain': directory,
'files': [f for f, _ in chunk], 'loc': chunk_loc or None})
part += 1
chunk, chunk_loc = [], 0
if rel is not None:
chunk.append((rel, lines))
chunk_loc += lines
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 estimate(sizes, tiny):
"""One line with the agents and tokens each depth is expected to need, from the number of lines in each shard."""
def rounded(n):
return math.ceil(n / 10) * 10
parts = []
for depth in AGENTS_PER_KLOC:
if tiny:
low, top = LENS_AGENTS[depth][0], max(LENS_MIN_TOP[depth], LENS_AGENTS[depth][1] * sum(sizes) / 1000)
else:
low = AGENTS_PER_KLOC[depth][0] * sum(sizes) / 1000
top = sum(max(AGENTS_PER_KLOC[depth][1] * n / 1000, min(SMALL_SHARD[depth], 10 + n / 5)) for n in sizes)
low, top = max(rounded(low), 20), max(rounded(top), 30)
parts.append(f'{depth} {low} to {top} agents (about {low * TOKENS_PER_AGENT / 1e6:.1f}M to {top * TOKENS_PER_AGENT / 1e6:.1f}M tokens)')
return 'estimate: ' + '; '.join(parts) + ', from mostly plumbing to very dense business logic'
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):
args = [a for a in argv[1:] if not a.startswith('--')]
flags = [a for a in argv[1:] if a.startswith('--')]
workspace = '.'
if '--workspace' in 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] [--unmapped]', file=sys.stderr)
return 2
system, pattern = args[0], (args[1] if len(args) > 1 else '')
source = source_dir(workspace, system)
print(f'source: {source}')
if os.path.isdir(source) and too_broad(source):
print(f'{source} is too broad to be one system (the filesystem root, your home directory or a top-level directory). '
'Point --source at the directory that holds the code.', file=sys.stderr)
return 1
if not os.path.isdir(source):
print(f'No code at {source}. Run preflight first (with --source <path> if the code lives elsewhere).', file=sys.stderr)
return 1
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, 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 = from_tree(by_dir, pattern)
mapped = None
origin = f'{files} source files (tree)'
else:
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 = 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 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)
# The map's sizes can be missing or out of date, so the files are counted.
print(estimate([s['loc'] if 'lines' in s else sum(count_lines(os.path.join(source, f)) or 0 for f in s['files']) or s['loc'] or 0 for s in shards], tiny))
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
if __name__ == '__main__':
sys.exit(main(sys.argv))
|