In this section
- TRUSS 47 render · cosmic / tools/explore/bigbang/rules/TRUSS-47.py lines 1–700
TRUSS 47
A Python module in the rules folder of Cosmic that cleans name (`clean_name`) and groups steps (`group_steps`) (units: mm², MVA, MW), using haversine and Vincenty.
rendercosmic / tools/explore/bigbang/rules/TRUSS-47.py · lines 1–700 of 790 · Not reached from any entry point (candidate for review) · pattern main_functions (shared by 3 files)
- What it does
- It draws its content. Defines 30 functions or classes, including words, clean_name, ext_of, defined_functions, call_counts. Uses libraries re. Side effects: changes the web page (DOM); makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Inputs & outputs
- In: form fields (user input). Out: SVG drawing. Coordinate systems named: WGS84 / EPSG:4326, Web Mercator / EPSG:3857.
- What it achieves
- It joins list (`join_list`) and is built from the words step (`words`) and the ext of helper (`ext_of`). TRUSS-47 rule set (Big Bang tournament player): STRUCTURE strategy.
- Why it matters
- No other file in the estate was found to import it.
- Application
- cosmic · tools/explore/bigbang/rules · Python module
- Uses
- re
- Used by
- none found
- Produces
- words, clean_name, ext_of, defined_functions, call_counts, entry_order, phrase_for, join_list, structure, code_terms, main_functions, q
- Defines here
- words, clean_name, ext_of, defined_functions, call_counts, entry_order, phrase_for, join_list, structure, code_terms, main_functions, q, clause, group_steps, _old_group_steps, nwords, folder_phrase, translate, workflow_parts, css_parts, page_parts, config_keys, pad_parts, context_sentence, function_roles
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/bigbang/rules/TRUSS-47.py:1-700 · blob 51438344c1a66f9a294f5a82538e18d587acb43b · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network, process, storage · domain stage: unknown · users: none · canonical: unreached_review
"""TRUSS-47 rule set (Big Bang tournament player): STRUCTURE strategy.
Translates a file from what its code does structurally: entry point, verb-led function names in call
order, inputs (files read, fetch targets, form fields), outputs (files written, page, canvas, SVG, map,
downloads) and side effects. Aim: "It reads X, computes Y and draws Z."
Deterministic, stdlib only. Never invents: every identifier quoted in backticks is one of the file's own
defined names (also in the evidence); data file names are given in plain lower case only when they occur
literally in the source; capitalised words come only from the title or the stock list.
"""
import re
NAME = "TRUSS-47"
STRATEGY = "Structure: entry point, verb-led functions in call order, inputs read, outputs drawn or written."
# ------------------------------------------------------------------ verb table
# identifier verb -> (third-person verb, bucket). Bucket orders the sentence: in -> work -> out.
VERB = {
'fetch': ('fetches', 'in'), 'load': ('loads', 'in'), 'read': ('reads', 'in'), 'get': ('gets', 'in'),
'parse': ('parses', 'in'), 'import': ('imports', 'in'), 'scan': ('scans', 'in'), 'collect': ('collects', 'in'),
'download': ('downloads', 'in'), 'extract': ('extracts', 'in'), 'decode': ('decodes', 'in'),
'compute': ('computes', 'work'), 'calc': ('calculates', 'work'), 'calculate': ('calculates', 'work'),
'estimate': ('estimates', 'work'), 'derive': ('derives', 'work'), 'solve': ('solves', 'work'),
'build': ('builds', 'work'), 'make': ('makes', 'work'), 'create': ('creates', 'work'),
'generate': ('generates', 'work'), 'normalise': ('normalises', 'work'), 'normalize': ('normalizes', 'work'),
'convert': ('converts', 'work'), 'transform': ('transforms', 'work'), 'merge': ('merges', 'work'),
'filter': ('filters', 'work'), 'sort': ('sorts', 'work'), 'group': ('groups', 'work'), 'rank': ('ranks', 'work'),
'score': ('scores', 'work'), 'match': ('matches', 'work'), 'find': ('finds', 'work'), 'resolve': ('resolves', 'work'),
'validate': ('validates', 'work'), 'check': ('checks', 'work'), 'verify': ('verifies', 'work'),
'classify': ('classifies', 'work'), 'detect': ('detects', 'work'), 'measure': ('measures', 'work'),
'clamp': ('clamps', 'work'), 'round': ('rounds', 'work'), 'summarise': ('summarises', 'work'),
'summarize': ('summarizes', 'work'), 'count': ('counts', 'work'), 'index': ('indexes', 'work'),
'split': ('splits', 'work'), 'project': ('projects', 'work'), 'interpolate': ('interpolates', 'work'),
'simulate': ('simulates', 'work'), 'apply': ('applies', 'work'), 'aggregate': ('aggregates', 'work'),
'hash': ('hashes', 'work'), 'encode': ('encodes', 'work'), 'compare': ('compares', 'work'),
'size': ('sizes', 'work'), 'layout': ('lays out', 'work'), 'place': ('places', 'work'), 'route': ('routes', 'work'),
'select': ('selects', 'work'), 'pick': ('picks', 'work'), 'choose': ('chooses', 'work'), 'plan': ('plans', 'work'),
'format': ('formats', 'out'), 'render': ('draws', 'out'), 'draw': ('draws', 'out'), 'paint': ('paints', 'out'),
'plot': ('plots', 'out'), 'show': ('shows', 'out'), 'display': ('shows', 'out'), 'update': ('updates', 'out'),
'refresh': ('refreshes', 'out'), 'write': ('writes', 'out'), 'save': ('saves', 'out'), 'export': ('exports', 'out'),
'emit': ('emits', 'out'), 'print': ('prints', 'out'), 'publish': ('publishes', 'out'), 'report': ('reports', 'out'),
'toggle': ('toggles', 'out'), 'highlight': ('highlights', 'out'), 'describe': ('describes', 'out'),
'label': ('labels', 'out'), 'set': ('sets', 'out'), 'add': ('adds', 'out'), 'append': ('appends', 'out'),
'insert': ('inserts', 'out'), 'remove': ('removes', 'out'), 'clear': ('clears', 'out'), 'reset': ('resets', 'out'),
'open': ('opens', 'out'), 'close': ('closes', 'out'), 'animate': ('animates', 'out'), 'zoom': ('zooms', 'out'),
'install': ('installs', 'out'), 'mount': ('mounts', 'out'), 'attach': ('attaches', 'out'), 'bind': ('binds', 'out'),
'init': ('sets up', 'out'), 'setup': ('sets up', 'out'), 'register': ('registers', 'out'), 'run': ('runs', 'work'),
'test': ('tests', 'work'), 'assert': ('asserts', 'work'), 'expect': ('checks', 'work'),
}
WEAK = {'get', 'set', 'add', 'run', 'make', 'open', 'close', 'show', 'init', 'setup', 'test', 'assert', 'expect',
'remove', 'clear', 'reset', 'mount', 'bind', 'attach', 'register', 'install'}
STOP_OBJ = {'the', 'a', 'an', 'of', 'to', 'for', 'and', 'or', 'by', 'from', 'with', 'in', 'on', 'at', 'is', 'it'}
# ------------------------------------------------------------------ structural detectors
CANVAS = re.compile(r"getContext\(\s*['\"](?:2d|webgl2?|webgpu)|\.(?:fillRect|strokeRect|arc|lineTo|fillText)\(")
SVG = re.compile(r"createElementNS\([^)]*svg|<svg[\s>]|d3\.select")
MAP = re.compile(r"maplibregl\.|mapboxgl\.|\bL\.map\(|new\s+ol\.Map|addLayer\(")
DOM_WRITE = re.compile(r"\.innerHTML\s*=|\.textContent\s*=|appendChild\(|insertAdjacentHTML|\.replaceChildren\(|\.append\(")
DOM_EVENT = re.compile(r"addEventListener\(\s*['\"](\w+)")
FORM_READ = re.compile(r"getElementById\(\s*['\"]([\w\-]+)['\"]\s*\)\s*\.value(?:AsNumber)?|"
r"querySelector\(\s*['\"]#([\w\-]+)['\"]\s*\)\s*\.value")
FETCH = re.compile(r"fetch\(\s*[`'\"]([^`'\"$]+)[`'\"]")
NODE_READ = re.compile(r"read(?:File|FileSync|JSON|Json)\w*\(\s*[^,)]*?['\"`]([^'\"`$]+\.\w{2,7})['\"`]")
NODE_WRITE = re.compile(r"write(?:File|FileSync|JSON|Json)\w*\(\s*[^,)]*?['\"`]([^'\"`$]+\.\w{2,7})['\"`]")
NODE_WRITE_ANY = re.compile(r"\bwrite(?:File|FileSync)\(|createWriteStream\(")
LOADER_CALL = re.compile(r"(?<![\w.])(?:load|read)\w*\(\s*['\"]([^'\"{}$]+\.\w{2,7})['\"]")
PY_OPEN = re.compile(r"open\(\s*[^,)]*?['\"]([^'\"{}]+\.\w{2,7})['\"]\s*(?:,\s*['\"]([rwab+]+)['\"])?")
PY_WRITE_ANY = re.compile(r"\.write_text\(|\.to_csv\(|\.to_parquet\(|json\.dump\(|open\([^)]*['\"][wa]b?['\"]")
PY_READ_ANY = re.compile(r"\.read_text\(|pd\.read_\w+\(|json\.load\(|csv\.(?:reader|DictReader)\(")
PY_HTTP = re.compile(r"requests\.(?:get|post)\(|urlopen\(|httpx\.")
ARGPARSE = re.compile(r"add_argument\(\s*['\"](--?[\w\-]+)")
PY_MAIN = re.compile(r"if\s+__name__\s*==\s*['\"]__main__['\"]")
STORAGE = re.compile(r"localStorage\.(?:get|set)Item|sessionStorage\.")
DOWNLOAD = re.compile(r"new\s+Blob\(|\.download\s*=|URL\.createObjectURL")
PRINTS = re.compile(r"console\.(?:log|table)\(|\bprint\(")
SUBPROC = re.compile(r"subprocess\.\w+\(|execSync\(|spawnSync?\(|child_process")
DATA_EXT = r'(?:json|geojson|csv|parquet|txt|tsv|xml|kml|pmtiles|topojson|ya?ml|md|html)'
def words(name):
n = re.sub(r'([a-z0-9])([A-Z])', r'\1 \2', name)
n = re.sub(r'([A-Z]+)([A-Z][a-z])', r'\1 \2', n)
return [w.lower() for w in re.split(r'[\s_\-.$]+', n) if w]
def clean_name(s):
"""A data file name safe to print lower case: basename, letters/digits/._- only, no capitals."""
b = s.rstrip('/').split('/')[-1].split('?')[0]
if not re.fullmatch(r'[a-z0-9][a-z0-9._\-]*\.' + DATA_EXT, b):
return ''
if re.search(r'\d{6,}', b) or len(b) > 40:
return ''
return b
def ext_of(path):
return path.rsplit('.', 1)[-1].lower() if '.' in path.rsplit('/', 1)[-1] else ''
# ------------------------------------------------------------------ function analysis
def defined_functions(src, lang, defines):
"""[(name, body)] for defined names in source order, body = text up to the next definition."""
names = [d for d in defines if re.fullmatch(r'[A-Za-z_$][\w$]*', d)]
if not names or not src:
return []
pos = []
for n in names:
if lang == 'py':
rx = r'^\s*(?:async\s+)?(?:def|class)\s+' + re.escape(n) + r'\b'
else:
rx = (r'(?:function\s*\*?\s*' + re.escape(n) + r'\s*\(|(?:const|let|var)\s+' + re.escape(n) +
r'\s*=|class\s+' + re.escape(n) + r'\b|^\s*(?:async\s+)?' + re.escape(n) + r'\s*\([^)]*\)\s*\{)')
m = re.search(rx, src, re.M)
if m:
pos.append((m.start(), n))
pos.sort()
out = []
for k, (p, n) in enumerate(pos):
end = pos[k + 1][0] if k + 1 < len(pos) else len(src)
out.append((n, src[p:end]))
return out
def call_counts(src, names):
c = {}
for n in names:
c[n] = max(0, len(re.findall(r'(?<![\w$.])' + re.escape(n) + r'\s*\(', src)) - 1)
return c
def entry_order(src, lang, funcs):
"""Names of defined functions in the order the entry point calls them (main / __main__ / DOMContentLoaded /
top-level calls), or [] when no entry point is visible."""
names = [n for n, _ in funcs]
body = ''
bodies = dict(funcs)
if lang == 'py':
m = PY_MAIN.search(src)
if 'main' in bodies:
body = bodies['main']
elif m:
body = src[m.end():]
else:
if 'main' in bodies:
body = bodies['main']
elif 'init' in bodies:
body = bodies['init']
else:
# top-level statements: drop function bodies by removing text of each function
top = src
for _, b in funcs:
top = top.replace(b, '\n')
body = top
order = []
for m in re.finditer(r'(?<![\w$.])([A-Za-z_$][\w$]*)\s*\(', body):
n = m.group(1)
if n in names and n not in order and n not in ('main',):
order.append(n)
return order
def phrase_for(name, title_words):
"""('computes', 'layout', 'work') for computeLayout, or None."""
ws = words(name)
if len(ws) < 2:
return None
v = ws[0]
if v in ('on', 'handle') and len(ws) >= 2:
obj = [w for w in ws[1:] if w not in STOP_OBJ]
return ('handles', ' '.join(obj) + (' events' if obj and obj[-1] not in ('click', 'change', 'input') else ''),
'out') if obj else None
if v in ('is', 'has', 'can', 'should'):
obj = [w for w in ws[1:] if w not in STOP_OBJ]
return ('checks for', ' '.join(obj), 'work') if obj else None
if v not in VERB:
return None
verb, bucket = VERB[v]
obj = [w for w in ws[1:] if w not in STOP_OBJ]
if not obj or len(obj) > 5:
return None
if any(len(w) == 1 for w in obj):
return None
return (verb, ' '.join(obj), bucket)
# ------------------------------------------------------------------ sentence assembly
def join_list(xs):
xs = [x for x in xs if x]
if not xs:
return ''
if len(xs) == 1:
return xs[0]
return ', '.join(xs[:-1]) + ' and ' + xs[-1]
def structure(rec, src):
path = rec.get('path', '')
e = ext_of(path)
lang = 'py' if e == 'py' else 'js' if e in ('js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx', 'html', 'htm') else e
defines = [d for d in rec.get('defines') or [] if isinstance(d, str)]
src = src or ''
s = {'lang': lang, 'inputs': [], 'outputs': [], 'steps': [], 'entry': '', 'effects': []}
title_words = set(words(rec.get('title', '')))
# ---- inputs
reads = []
for rx in (FETCH, NODE_READ):
for m in rx.finditer(src):
n = clean_name(m.group(1))
if n and n not in reads:
reads.append(n)
for m in LOADER_CALL.finditer(src):
n = clean_name(m.group(1))
if n and n not in reads:
reads.append(n)
if lang == 'py':
for m in PY_OPEN.finditer(src):
n = clean_name(m.group(1))
mode = m.group(2) or 'r'
if n and 'r' in mode and n not in reads:
reads.append(n)
writes = []
for m in NODE_WRITE.finditer(src):
n = clean_name(m.group(1))
if n and n not in writes:
writes.append(n)
if lang == 'py':
for m in PY_OPEN.finditer(src):
n = clean_name(m.group(1))
if n and m.group(2) and re.search(r'[wa]', m.group(2)) and n not in writes:
writes.append(n)
reads = [r for r in reads if r not in writes]
if reads:
s['inputs'].append('reads ' + join_list([q(r) for r in reads[:3]]) + (' and %d more files' % (len(reads) - 3) if len(reads) > 3 else ''))
elif FETCH.search(src) or re.search(r'\bfetch\(', src):
s['inputs'].append('fetches data over the network' if re.search(r"fetch\(\s*[`'\"]https?:", src) else 'fetches its data files')
elif lang == 'py' and PY_READ_ANY.search(src):
s['inputs'].append('reads data files')
elif lang == 'js' and re.search(r'\breadFile(?:Sync)?\(', src):
s['inputs'].append('reads files')
if lang == 'py' and PY_HTTP.search(src) and not any('fetch' in x for x in s['inputs']):
s['inputs'].append('fetches data over the web')
forms = []
for m in FORM_READ.finditer(src):
w = ' '.join(words(m.group(1) or m.group(2)))
if w and w not in forms and len(w) < 30:
forms.append(w)
if forms:
s['inputs'].append('takes ' + join_list(forms[:3]) + ' from the form')
args = []
for m in ARGPARSE.finditer(src):
a = m.group(1).lstrip('-')
if a and a not in args and a != 'h':
args.append(a)
if STORAGE.search(src):
s['effects'].append('remembers settings in the browser')
# ---- outputs
if CANVAS.search(src):
s['outputs'].append('draws on a canvas')
if SVG.search(src):
s['outputs'].append('draws vector graphics')
if MAP.search(src):
s['outputs'].append('draws map layers')
if DOM_WRITE.search(src) and lang == 'js':
s['outputs'].append('updates the page')
if writes:
s['outputs'].append('writes ' + join_list([q(w) for w in writes[:3]]))
elif (lang == 'py' and PY_WRITE_ANY.search(src)) or (lang == 'js' and NODE_WRITE_ANY.search(src)):
s['outputs'].append('writes its results to files')
if DOWNLOAD.search(src):
s['outputs'].append('offers a download')
if not s['outputs'] and PRINTS.search(src) and lang in ('py', 'js') and rec.get('kind') != 'page':
s['outputs'].append('prints a report')
if SUBPROC.search(src):
s['effects'].append('runs other commands')
# ---- entry
evs = []
for m in DOM_EVENT.finditer(src):
if m.group(1) not in evs:
evs.append(m.group(1))
if lang == 'py' and (PY_MAIN.search(src) or ARGPARSE.search(src)):
s['entry'] = 'command line'
elif evs:
s['entry'] = 'events'
s['events'] = evs
s['args'] = args
# ---- steps from verb-led defined names, entry order first, then most-called
funcs = defined_functions(src, lang, defines)
names = [n for n, _ in funcs] or defines
order = entry_order(src, lang, funcs) if funcs else []
counts = call_counts(src, names)
ranked = order + sorted([n for n in names if n not in order], key=lambda n: (-counts.get(n, 0), names.index(n)))
steps, seen_obj, seen_verb = [], set(), {}
for n in ranked:
if n.startswith('_') and lang == 'py' and len(steps) >= 2:
continue
p = phrase_for(n.lstrip('_$'), title_words)
if not p:
continue
verb, obj, bucket = p
if obj in seen_obj:
continue
v0 = words(n.lstrip('_$'))[0]
if v0 in WEAK and len(obj.split()) < 2:
continue
seen_obj.add(obj)
steps.append({'name': n, 'verb': verb, 'obj': obj, 'bucket': bucket, 'entry': n in order})
s['steps'] = steps
s['n_funcs'] = len(names)
return s
UNIT_SRC = re.compile(r'(?<![\w.])(\d+(?:\.\d+)?)\s?(kV|kVA|MVA|MVAr|kW|MW|GW|kWh|MWh|GWh|TWh|Hz|mm²|mm2)\b')
STD_SRC = re.compile(r'\b(?:IEC|BS|EN|IEEE|ENA|IET)\s?\d{3,5}(?:-\d+)*\b|\bG(?:59|83|98|99|100)\b|\bEPSG:\d{4,5}\b')
METHODS = ['haversine', 'vincenty', 'newton-raphson', 'gauss-seidel', 'pagerank', 'dijkstra', 'kruskal',
'bradley-terry', 'louvain', 'least squares', 'kalman', 'fourier', 'monte carlo', 'bisection',
'interpolation', 'bilinear', 'douglas-peucker', 'delaunay', 'voronoi', 'convex hull', 'k-means', 'sha-256',
'sha256', 'crc32', 'base64', 'web mercator', 'mercator', 'helmert', 'voltage drop', 'power factor',
'derating', 'thermal resistance', 'short-circuit', 'fault level', 'load flow', 'power flow', 'impedance',
'reactance', 'capacitance', 'irradiance', 'lcoe', 'npv', 'discount rate', 'regression', 'percentile',
'median', 'standard deviation', 'cosine similarity', 'jaccard', 'levenshtein', 'breadth-first',
'depth-first', 'topological sort', 'quadtree', 'geohash', 'ray casting', 'point in polygon', 'fft', 'elo',
'per-unit', 'skin effect', 'mppt', 'levelised cost', 'label propagation', 'trilinear',
'transverse mercator', 'ostn15', 'wgs84', 'i2r', 'r-tree', 'rtree', 'bfs', 'hilbert curve', 'raycast',
'kmeans', 'trilinear']
def code_terms(src, budget_mixed=2):
"""Units with numbers, bare units, standards and named methods that occur in the code. Mixed-case units
(kV, kW) are capped by budget_mixed, and kVA/kWh are never used, so the text does not read as identifiers."""
code = re.sub(r'(?m)^\s*(?://|#|\*).*$', ' ', src)
std, meth, upper, mixed, bare = [], [], [], [], []
for m in STD_SRC.finditer(src):
if m.group(0) not in std:
std.append(m.group(0))
low = code.lower()
for w in METHODS:
if re.search(r'(?<![\w])' + re.escape(w) + r'(?![\w])', low) and \
not any(w.replace('-', '') in o.replace('-', '') or o.replace('-', '') in w.replace('-', '') for o in meth):
meth.append(w)
seen = set()
for m in UNIT_SRC.finditer(code):
u = m.group(2)
if u in ('kVA', 'kWh', 'mm2'):
continue
t = m.group(1) + ' ' + u
k = t.replace(' ', '').lower()
if k in seen:
continue
seen.add(k)
(mixed if re.match(r'[a-z]', u) else upper).append(t)
have_units = {x.split()[-1] for x in upper + mixed}
for u in ('MW', 'GW', 'MWh', 'GWh', 'TWh', 'MVA', 'Hz'):
if u not in have_units and re.search(r'(?<![\w])' + u + r'(?![\w])', code):
bare.append(u)
out = std[:2] + meth[:2] + upper[:2] + mixed[:budget_mixed] + bare[:2]
return out[:4]
def main_functions(rec):
out = []
for d in rec.get('defines') or []:
if not isinstance(d, str) or d.startswith('_') or d.startswith('test') or d in ('main', '__init__') or len(d) < 3:
continue
if d not in out:
out.append(d)
return out[:6]
def q(name):
return '`%s`' % name.replace('`', '')
def clause(group):
v = group[0]['verb']
return '%s %s (%s)' % (v, join_list([g['obj'] for g in group]), ', '.join(q(g['name']) for g in group))
def group_steps(steps):
return [[st] for st in steps]
def _old_group_steps(steps):
by, order = {}, []
for st in steps:
if st['verb'] not in by:
by[st['verb']] = []
order.append(st['verb'])
if len(by[st['verb']]) < 1:
by[st['verb']].append(st)
return [by[v] for v in order]
def nwords(s):
return len(s.split())
def folder_phrase(rec):
"""Plain words of the nearest meaningful folder, e.g. 'cable geometry visualiser', or ''."""
for f in reversed(rec.get('folder_hierarchy') or []):
if re.search(r'\d{6,}', f) or f.startswith('.') or f.lower() in ('src', 'lib', 'js', 'scripts', 'tools', 'tests',
'test', 'releases', 'workflows', 'mod', 'engine',
'public', 'assets', 'static', 'docs'):
continue
ws = [w for w in re.split(r'[-_\s]+', f.lower()) if w and not re.fullmatch(r'v?\d+', w)]
if 1 <= len(ws) <= 5 and all(re.fullmatch(r'[a-z][a-z0-9]*', w) for w in ws):
return ' '.join(ws)
return ''
return ''
def translate(file_record, source_text):
rec = file_record or {}
title = (rec.get('title') or '').strip()
if nwords(title) > 8:
title = ' '.join(title.split()[:8])
kind = rec.get('kind') or ''
src = source_text or ''
s = structure(rec, src)
mf = main_functions(rec)
rank = {'in': 0, 'work': 1, 'out': 2}
steps = s['steps']
# main functions first (coverage), then entry order
prio = sorted(steps, key=lambda st: (0 if st['name'] in mf else 1, 0 if st['entry'] else 1))
chosen = sorted(prio[:6], key=lambda st: rank[st['bucket']])
groups = group_steps(chosen)
# ---- synopsis: inputs, steps (budget), outputs, effect
lead = 'From the command line, it ' if s['entry'] == 'command line' and kind != 'test' else 'It '
head = s['inputs'][:1]
tail = s['outputs'][:2] + s['effects'][:1]
used, body = [], []
budget = 38 - nwords(lead) - sum(nwords(x) for x in head + tail[:1])
for g in groups:
c = clause(g)
if nwords(c) <= budget - sum(nwords(b) for b in body):
body.append(c)
used.extend(x['name'] for x in g)
if len(body) >= 3:
break
parts = head + body
for t in tail:
if nwords(lead) + sum(nwords(x) for x in parts + [t]) <= 39:
parts.append(t)
if kind == 'workflow' or (kind == 'configuration' and re.search(r'(?m)^jobs:', src)):
parts = workflow_parts(src, rec) or parts
if kind == 'style sheet':
parts = css_parts(src) or parts
if not parts and kind == 'page':
parts = page_parts(src)
fp = folder_phrase(rec)
if not parts:
defs = [d for d in mf if d not in used][:3]
if defs:
parts = [role_phrase(src, s['lang'], defs, 'provides ')]
used.extend(defs)
else:
keys = config_keys(src, rec)
parts = ['sets %s' % join_list([q(k) for k in keys])] if keys else \
[('holds settings for the %s folder' % fp if fp else 'holds settings read by other files')
if kind == 'configuration' or ext_of(rec.get('path', '')) in ('json', 'yml', 'yaml', 'toml')
else ('holds top-level code for the %s folder' % fp if fp else 'holds top-level code')]
for extra in pad_parts(src, rec, s, parts):
if nwords(lead + join_list(parts)) >= 14:
break
if nwords(lead + join_list(parts + [extra])) <= 40:
parts.append(extra)
synopsis = lead + join_list(parts) + '.'
if nwords(synopsis) < 12 and fp and not any(fp in p for p in parts):
synopsis = synopsis[:-1] + ', for the %s folder.' % fp
# ---- achieves: remaining main functions, entry, terms
ach = []
rest = [st for st in steps if st['name'] in mf and st['name'] not in used]
if rest:
gs = group_steps(rest[:3])
ach.append('It also ' + join_list([clause(g) for g in gs]) + '.')
used.extend(x['name'] for g in gs for x in g)
left = [d for d in mf if d not in used and q(d) not in synopsis]
if left:
ach.extend(role_sentences(src, s['lang'], left))
if s['entry'] == 'events' and s['events']:
starts = any(e in ('DOMContentLoaded', 'load') for e in s['events'])
ev = [e for e in s['events'] if re.fullmatch(r'[a-z]+', e) and e != 'load'][:3]
if ev:
ach.append('It reacts to %s events in the browser%s.' % (join_list(ev), ', starting when the page loads'
if starts else ''))
elif starts:
ach.append('It starts when the page loads.')
if s['entry'] == 'command line' and s['args']:
opts = [a for a in s['args'] if re.fullmatch(r'[a-z0-9][a-z0-9\-]*', a)][:3]
if opts:
ach.append('It accepts %s.' % join_list(['`--%s`' % a for a in opts]))
ctxs = context_sentence(rec, title)
mixed_ctx = len(re.findall(r'(?<![\w`])[a-z]+[A-Z]\w*', ctxs))
terms = code_terms(src, max(0, 2 - mixed_ctx))
if terms:
ach.append('Its code refers to %s.' % join_list(terms))
if not ach or nwords(' '.join(ach)) < 6:
if s['outputs'] and fp:
ach.append('Its result: it %s for the %s folder.' % (join_list(s['outputs'][:2]), fp))
elif fp:
ach.append('It serves the %s folder.' % fp)
ctx = ctxs
if ctx and nwords(' '.join(ach)) < 45:
ach.append(ctx)
achieves = ' '.join(ach)
if achieves.rstrip('.').lower() == synopsis.rstrip('.').lower() or not achieves:
achieves = 'It is a %s in the %s folder.' % (kind or 'file', fp or 'top')
return {'title': title, 'synopsis': synopsis, 'achieves': achieves}
TRIG = {'push': 'on push', 'pull_request': 'on pull requests', 'schedule': 'on a schedule',
'workflow_dispatch': 'by hand', 'workflow_run': 'after another workflow', 'release': 'on release'}
def workflow_parts(src, rec):
on = []
m = re.search(r'(?ms)^on:\s*(.*?)(?=^\S)', src + '\nzz:')
blk = m.group(1) if m else ''
first = re.search(r'(?m)^on:\s*(\S.*)$', src)
blk += ' ' + (first.group(1) if first else '')
for k, v in TRIG.items():
if re.search(r'(?<![\w])' + k + r'(?![\w])', blk) and v not in on:
on.append(v)
runs = []
for m in re.finditer(r'(?:python3?|node|bash|sh|pwsh)\s+((?:[\w.\-]+/)*[\w.\-]+\.(?:py|mjs|js|sh|ps1))', src):
if m.group(1) not in runs:
runs.append(m.group(1))
names = [d for d in rec.get('defines') or [] if isinstance(d, str)][:1]
parts = []
if names and names[0] in src:
parts.append('runs the workflow job %s' % q(names[0]))
elif on:
parts.append('runs automated jobs')
if on:
parts[-1] += ' ' + join_list(on[:3]) if parts else ''
if runs:
parts.append('calls %s' % join_list([q(r) for r in runs[:3]]))
if re.search(r'git (?:commit|push)', src):
parts.append('commits the results back')
if re.search(r'actions/upload-pages-artifact|deploy-pages|gh-pages', src):
parts.append('publishes the site')
if re.search(r'actions/upload-artifact', src):
parts.append('uploads build artifacts')
return parts
def css_parts(src):
sel = len(re.findall(r'\{', src))
media = len(re.findall(r'@media', src))
var = len(set(re.findall(r'(--[\w\-]+)\s*:', src)))
kf = len(re.findall(r'@keyframes', src))
parts = []
if sel:
parts.append('styles %d rule blocks' % sel)
if var:
parts.append('sets %d colour and size variables' % var)
if media:
parts.append('adapts the layout at %d screen widths' % media)
if kf:
parts.append('defines %d animations' % kf)
return parts
def page_parts(src):
parts = []
n_a = len(re.findall(r'<a\s[^>]*href', src, re.I))
n_sec = len(re.findall(r'<(?:section|article)\b', src, re.I))
n_scr = re.findall(r'<script[^>]*src=["\']([^"\']+)["\']', src, re.I)
if n_scr:
loc = [x.split('/')[-1] for x in n_scr if re.fullmatch(r'[\w.\-/]+', x) and not x.startswith('http')]
if loc:
parts.append('loads %s' % join_list([q(x) for x in loc[:3]]))
if n_sec:
parts.append('lays out %d sections' % n_sec)
if n_a:
parts.append('links to %d pages' % n_a)
if re.search(r'<form\b|<input\b', src, re.I):
parts.append('offers a form')
return parts
def config_keys(src, rec):
e = ext_of(rec.get('path', ''))
keys = []
if e in ('yml', 'yaml', 'toml'):
for m in re.finditer(r'(?m)^\[?([A-Za-z_][\w\-]*)\]?\s*[:=\]]', src):
if m.group(1) not in keys:
keys.append(m.group(1))
elif e == 'json':
for m in re.finditer(r'(?m)^\s{0,4}"([A-Za-z_][\w\-]*)"\s*:', src):
if m.group(1) not in keys:
keys.append(m.group(1))
elif e == 'ps1':
for m in re.finditer(r'(?im)^\s*function\s+([A-Za-z][\w\-]*)', src):
if m.group(1) not in keys:
keys.append(m.group(1))
return keys[:4]
IMPORT_JS = re.compile(r"""(?:import\s[^'"]*?from\s*|import\s*\(\s*|require\(\s*)['"]([^'"]+)['"]""")
IMPORT_PY = re.compile(r'(?m)^\s*(?:from\s+([\w.]+)\s+import|import\s+([\w.]+))')
EXPORT_JS = re.compile(r'(?m)^export\s+(?:default\s+)?(?:async\s+)?(?:function\*?|const|let|class)\s+([A-Za-z_$][\w$]*)')
def pad_parts(src, rec, s, parts):
"""Extra structural facts to reach a full sentence: what it exports, what it imports, size."""
out = []
have = ' '.join(parts)
mf = main_functions(rec)
ex = [m.group(1) for m in EXPORT_JS.finditer(src) if '`%s`' % m.group(1) not in have and m.group(1) not in mf]
if ex:
out.append('exports %s' % join_list([q(x) for x in ex[:3]]))
imps = []
if s['lang'] == 'py':
for m in IMPORT_PY.finditer(src):
n = m.group(1) or m.group(2)
if n and n not in imps and n.split('.')[0] not in ('os', 'sys', 're', 'json', '__future__', 'typing'):
imps.append(n)
else:
for m in IMPORT_JS.finditer(src):
n = m.group(1)
if n not in imps and re.fullmatch(r'[\w.@/:\-]+', n):
imps.append(n)
if imps:
out.append('builds on %s' % join_list([q(x) for x in imps[:2]]))
n = rec.get('lines') or src.count('\n') + 1
if n:
out.append('runs to %d lines' % n)
return out
STATUSY = re.compile(r'\b(candidate|not composed|not published|no production|retired|deprecated|superseded|'
r'unreviewed|quarantined|example only|copied|placeholder|todo|draft)\b|\b20\d{6,}\b|'
r'\b[0-9a-f]{10,}\b|https?://|`|\$\{|\.(?:mjs|cjs|py|js)\b', re.I)
IDENTY = re.compile(r'(?<![\w`])(?:[a-z]+[A-Z]\w+|[a-z]+_\w+)')
def context_sentence(rec, title):
"""The README or context sentence (nearest folder first) richest in content words, 8-24 words, clean."""
ctx = rec.get('ctx') or {}
cands = list(ctx.get('readme') or [])[:12]
cands += re.split(r'(?<=[.!?])\s+', rec.get('context') or '')
best, bs = '', 0
for k, c in enumerate(cands):
c = c.strip()
n = nwords(c)
if not (6 <= n <= 28) or not re.match(r'[A-Z]', c) or STATUSY.search(c) or IDENTY.search(c) or '"' in c or '|' in c:
continue
if re.search(r'\b(\w+) \1\b|\s\*\s|…|:', c):
continue
if title and nwords(title) >= 2 and title.lower() in c.lower():
continue
w = {x.lower() for x in re.findall(r'[A-Za-z][A-Za-z\-]{3,}', c)}
sc = min(len(w), 6) * 10 - k
if sc > bs:
best, bs = c, sc
if not best:
return ''
best = best.rstrip()
if best[-1] not in '.!?':
best += '.'
return best
ROLE_RX = [
('class definition', None),
('canvas drawing', re.compile(r'\.(?:fillRect|strokeRect|lineTo|moveTo|arc|fillText|stroke|fill|drawImage)\(')),
('vector drawing', re.compile(r'createElementNS|<svg|<path|<line|<circle|<polyline')),
('page update', re.compile(r'innerHTML|textContent|appendChild|replaceChildren|classList|\.style\.|setAttribute')),
('data loading', re.compile(r'\bfetch\(|readFile|json\.load|\bopen\(|read_text|read_csv|urlopen')),
('file output', re.compile(r'writeFile|json\.dump|write_text|to_csv|\.write\(')),
('event wiring', re.compile(r'addEventListener|\.on\w*\s*=')),
('hash calculation', re.compile(r'createHash|hashlib|crypto\.subtle|sha256', re.I)),
('geometry maths', re.compile(r'Math\.(?:sin|cos|atan2|hypot|tan|asin|acos)|math\.(?:sin|cos|atan2|hypot|radians)')),
('numeric calculation', re.compile(r'Math\.\w+|math\.\w+|\*\*|[\w)]\s*[*/]\s*[\w(]')),
('number formatting', re.compile(r'toFixed|toLocaleString|padStart|:\.\d+f|format\(')),
('input check', re.compile(r'throw new \w*Error|\braise\b|\bassert\b|return false')),
('text processing', re.compile(r'\.replace\(|\.split\(|re\.sub|\.match\(|\.trim\(|\.strip\(')),
('list building', re.compile(r'\.map\(|\.filter\(|\.push\(|\.append\(|\breturn \[|\bfor\b')),
('object lookup', re.compile(r'\breturn\b')),
]
def function_roles(src, lang, names):
"""name -> short two-word role read from the function's own body (first matching pattern)."""
if not names or not src:
return {}
funcs = dict(function_bodies(src, lang, list(names)))
out = {}
for n in names:
b = funcs.get(n, '')
if not b:
continue
b = b[:3000]