In this section
- Build render · cosmic / tools/explore/build.py lines 1401–2100
Build
A Python command-line tool in the explore folder of Cosmic that maps dictionary and build graph, using EPSG:27700 and EPSG:4326, and uses data from the GridAtlas, ventus-grid-engine and SatNav repositories.
rendercosmic / tools/explore/build.py · lines 1401–2100 of 3776 (continued from section 1080) · Entry point · pattern clean_comment (shared by 2 files)
- What it does
- It maps dictionary, build graph, words and solar. Defines 114 functions or classes, including words_of, git, ext, slug, load_leaks. Uses libraries argparse, collections, datetime, fnmatch, html. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain terms in the code: solar, 132kV, 33kV, 11kV, 11kV/400V, 400V. README: "`build.py` is the method"
- Inputs & outputs
- In: data source: gridatlas data; data source: ventus-grid-engine data; data source: satnav data; data source: solar-electrical-topology-analysis-engine-text-based data; JSON file dictionary.json; JSON file build_graph.json; Parquet file code.parquet; Parquet file words.parquet. Out: Parquet file; JSON file; interactive map; SVG drawing. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326, Web Mercator / EPSG:3857, ETRS89 / EPSG:4258. Voltage levels named: 132kV, 33kV, 11kV, 11kV/400V, 400V.
- Downstream impact
- Used directly by 3 files: Cadastre 27 (cosmic); Ship (cosmic); Test Build (cosmic). Reached from 1 other entry point, including Test Ship (cosmic).
- What it achieves
- It loads leaks (`load_leaks`), loads essays (`load_essays`) and cleans key (`clean_key`). The README says: `build.py` is the method. Its code works with 132 kV, 33 kV and 11 kV. It writes `words/index.html`.
- Why it matters
- Imported by Cadastre 27. Run by Ship. Checked by Test Build.
- Application
- cosmic · tools/explore · Python CLI
- Uses
- Describe (import), Agentdocs (import), GridAtlas — Index Page (estate URL), SatNav — Scope Page (estate URL), Solar Electrical Topology Analysis Engine Text Based — Index Page (estate URL), argparse, collections, datetime, fnmatch, html, json, os, posixpath
- Used by
- imported by Cadastre 27 (sys.path import), run by Ship (script call), imported by Test Build (import)
- Produces
- words_of, git, ext, slug, load_leaks, humanise, kind_of, name_words, stamp_note, title_parts, title_of, repo_title
- Defines here
- refs_of, comment_spans, in_spans, Resolver, __init__, lookup, url, resolve_url, resolve_path, resolve_python, mod_in, discover, resolve_script, glob, edges_of, gate, effects_of, stage_of, role_of, family_of, assign_patterns, package_entries
- 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/build.py:1401-2100 · blob a82b6f8252f926b3e24b5469dc1f3b7b2ead6a33 · GitHub at these lines
- State
- achieves: readme · context: readme_derived · stage: output · effects: dom, filesystem, network, process, storage · domain stage: unknown · users: none · canonical: unknown
if m:
v = py_path_expr(m.group(1), env, path)
if v and v[0] == 'path':
d = posixpath.normpath(v[1]) if v[1] else ''
d = '' if d == '.' else d
if not d.startswith('..') and not d.startswith('/') and d not in dirs:
dirs.append(d)
return dirs
def refs_of(path, lines):
"""Every reference this file makes, as (kind, spec, extra). Read over the whole file."""
e = ext(path)
out = []
text = '\n'.join(lines)
low = text.lower()
if e == 'py':
out += _python_refs(lines)
if 'subprocess' in low or 'sys.executable' in low or 'os.system' in low or 'python' in low:
out += [('script-call', s, ()) for s in PY_SUB.findall(text)]
out += [('script-call', s, ()) for s in CMD.findall(text)]
if (e == 'py' and ('subprocess' in low or 'os.system' in low)) or \
(e in JSX and ('child_process' in low or 'spawnsync' in low or 'execfile' in low)):
# a file that starts processes and names a script path in a string: that script is run by it
out += [('script-call', 'string:' + s, ()) for s in STR_PATH.findall(text)
if ('/' in s or e == 'py') and (e != 'py' or s.endswith(('.py', '.sh')))] # Python runs .py/.sh
if e in JSX:
if 'import' in low or 'export' in low:
out += [('import', s, ()) for s in JS_STATIC.findall(text)]
out += [('dynamic-import', s, ()) for s in JS_DYN.findall(text)]
if 'require(' in low:
out += [('require', s, ()) for s in JS_REQ.findall(text)]
if 'child_process' in low or 'exec' in low or 'spawn' in low:
out += [('script-call', s, ()) for s in CMD.findall(text)]
if 'import.meta' in low:
out += [('url-import-meta', s, ()) for s in JS_URL.findall(text)]
if 'worker' in low or 'importscripts' in low:
out += [('worker', s, ()) for s in JS_WORK.findall(text)]
if '.src' in low:
out += [('script-src', s, ()) for s in JS_SRCSET.findall(text)]
if 'fetch(' in low:
out += [('fetch', s, ()) for s in JS_FETCH.findall(text)]
if 'location' in low or 'window.open' in low:
out += [('link', s, ()) for s in JS_NAV.findall(text)]
if e in ('html', 'htm', 'vue', 'svelte'):
for m in HTML_TAG.finditer(text):
tag, a = m.group(1).lower(), _attrs(m.group(2))
if tag == 'script' and a.get('src'):
out.append(('script-src', a['src'], ()))
elif tag == 'link' and a.get('href'):
rel = (a.get('rel') or '').lower()
if 'stylesheet' in rel or a['href'].split('?')[0].lower().endswith('.css'):
out.append(('stylesheet', a['href'], ()))
elif any(r in rel for r in ('modulepreload', 'preload', 'prefetch')):
out.append(('modulepreload', a['href'], ()))
elif tag in ('iframe', 'frame') and a.get('src'):
out.append(('iframe', a['src'], ()))
elif tag in ('a', 'area') and a.get('href'):
out.append(('link', a['href'], ()))
for m in HTML_IMAPS.finditer(text):
try:
im = json.loads(m.group(1))
except ValueError:
continue
vals = list((im.get('imports') or {}).values())
for sc in (im.get('scopes') or {}).values():
if isinstance(sc, dict):
vals += list(sc.values())
out += [('import-map', v, ()) for v in vals if isinstance(v, str)]
out += [('link', s, ()) for s in HTML_REFRESH.findall(text)]
if e in ('css', 'html', 'htm') and '@import' in low:
out += [('stylesheet', s, ()) for s in CSS_IMPORT.findall(text)]
workflow = path.startswith('.github/workflows/') and e in ('yml', 'yaml')
if workflow or e in ('sh', 'ps1', 'bat') or (e in ('yml', 'yaml') and path.startswith('.github/')):
kind = 'workflow-run' if path.startswith('.github/') else 'script-call'
wds = WF_WD.findall(text) if workflow else []
# Variables: HERE=$(dirname "$0") style folders mean the script's own folder; NAME: path.mjs / NAME=path.py
# values are substituted where a command runs "$NAME".
here_vars = set(SH_HERE.findall(text))
env = dict(SH_ENV.findall(text))
for line in lines:
if len(line) > 600:
continue
cds = CD_RX.findall(line)
specs = CMD.findall(line) + CMD_EXEC.findall(line)
specs += [env[a or b] for a, b in CMD_VAR.findall(line) if (a or b) in env]
for s in specs:
m = re.match(r'^\$\{?(\w+)\}?/(.+)$', s) or re.match(r'^\$\(dirname\s+"?\$(?:0|\{?BASH_SOURCE(?:\[0\])?\}?)"?\)/(.+)$', s)
if m and (m.lastindex == 1 or m.group(1) in here_vars):
s = 'filedir:' + m.group(m.lastindex)
out.append((kind, s, tuple(cds + wds)))
for s in CMD_MOD.findall(line):
if s not in ('pytest', 'unittest', 'py_compile'):
out.append((kind, 'python-module:' + s, tuple(cds + wds)))
for m in TEST_RUN.finditer(line):
if not re.search(r'\b(?:install|uninstall)\b', line[:m.start()]): # pip install pytest is not a run
out.append((kind, 'discover:%s:%s' % (m.group(1).split()[0], m.group(2).strip()), tuple(cds + wds)))
if kind == 'workflow-run':
out += [(kind, s, ()) for s in WF_USES.findall(text)]
seen, res = set(), []
for r in out:
if r[:2] not in seen and 0 < len(r[1]) < 300:
seen.add(r[:2])
res.append(r)
return res
COMMENT_RX = {
'c': re.compile(r'/\*[\s\S]*?\*/|(?<![:\w\'"`\\/])//[^\n]*'),
'html': re.compile(r'<!--[\s\S]*?-->'),
'py': re.compile(r'(?:^|(?<=\s))#[^\n]*|"""[\s\S]*?"""|\'\'\'[\s\S]*?\'\'\''),
'hash': re.compile(r'(?:^|(?<=\s))#[^\n]*'),
}
def comment_spans(path, text):
"""Sorted (start, end) character spans of comments (and Python docstrings / triple-quoted strings)."""
e = ext(path)
rxs = []
if e in JSX or e == 'css':
rxs.append(COMMENT_RX['c'])
if e in ('html', 'htm', 'vue', 'svelte'):
rxs.append(COMMENT_RX['html'])
if e == 'py':
rxs.append(COMMENT_RX['py'])
if e in ('sh', 'yml', 'yaml', 'toml', 'r', 'rb', 'ps1'):
rxs.append(COMMENT_RX['hash'])
spans = []
for rx in rxs:
spans += [m.span() for m in rx.finditer(text)]
return sorted(spans)
def in_spans(spans, pos):
import bisect
k = bisect.bisect_right(spans, (pos, float('inf'))) - 1
return k >= 0 and spans[k][0] <= pos < spans[k][1]
class Resolver:
"""Resolves references to estate files (any repository) by path, estate URL, directory index, timestamp
family (older version -> kept newest member) and duplicate blob (path -> the copy kept elsewhere)."""
def __init__(self, files, metas):
self.files = files
self.by_path = {(f['repo'], f['path']): i for i, f in enumerate(files)}
self.fam = {}
for i, f in enumerate(files):
if STAMP.search(f['path']):
self.fam[(f['repo'], STAMP.sub('#', f['path']))] = i
self.dups = {}
for r, m in metas.items():
for p, tgt in (m.get('dups') or {}).items():
self.dups[(r, p)] = tgt
self.listing = collections.defaultdict(list)
for i, f in enumerate(files):
self.listing[f['repo']].append((f['path'], i))
self.repos = {r.lower(): r for r in metas}
# cosmic is served on its own domain (Pages custom domain, set in repo settings; no CNAME file in the repo)
self.hosts = {'globalgrid2050.com': 'globalgrid2050', 'www.globalgrid2050.com': 'globalgrid2050', 'code.globalgrid2050.com': 'cosmic'}
for r, m in metas.items():
if m.get('cname'):
self.hosts[m['cname'].lower()] = r
self.hosts['www.' + m['cname'].lower()] = r
self.hosts = {h: r for h, r in self.hosts.items() if r in metas}
self.pages_root = {}
for r in metas:
self.pages_root[r] = 'docs' if (r, 'index.html') not in self.by_path and (r, 'docs/index.html') in self.by_path else ''
hosts = '|'.join(re.escape(h) for h in sorted(self.hosts, key=len, reverse=True))
self.url_rx = re.compile(r'''https?://(?:ventusltd\.github\.io/|raw\.githubusercontent\.com/ventusltd/|'''
r'''cdn\.jsdelivr\.net/gh/ventusltd/|github\.com/ventusltd/''' +
((r'|(?:%s)(?=[/\'"`\s)<]|$)' % hosts) if hosts else '') +
r''')[^\s'"`)<>\]\\{}$|*]*''', re.I)
def lookup(self, repo, p, depth=0):
"""(index, via) for repository path p (no leading slash; '' or a trailing slash means a folder)."""
folder = p == '' or p.endswith('/')
p = posixpath.normpath(p) if p not in ('', '/') else ''
p = '' if p == '.' else p
if p.startswith('..') or p.startswith('/'):
return None
cands = [] if folder else [p, p + '.js', p + '.mjs', p + '.ts', p + '/index.js']
for c in cands:
if (repo, c) in self.by_path:
return self.by_path[(repo, c)], ''
for c in ([p + '/index.html', p + '/index.htm'] if p else ['index.html', 'index.htm']):
if (repo, c) in self.by_path:
return self.by_path[(repo, c)], 'index'
for c in cands[:3]:
if STAMP.search(c) and (repo, STAMP.sub('#', c)) in self.fam:
return self.fam[(repo, STAMP.sub('#', c))], 'family'
if depth < 3:
for c in cands[:1]:
if (repo, c) in self.dups:
r2, p2 = self.dups[(repo, c)]
hit = self.lookup(r2, p2, depth + 1)
if hit:
return hit[0], '+'.join(x for x in ('duplicate', hit[1]) if x)
return None
def url(self, u):
"""(repo, path) for an absolute URL into the estate, or None."""
try:
s = urllib.parse.urlsplit(u.strip())
except ValueError:
return None
host = (s.hostname or '').lower()
parts = [urllib.parse.unquote(x) for x in s.path.split('/')]
trail = s.path.endswith('/')
parts = [x for x in parts if x]
repo, rest = None, None
if host == 'ventusltd.github.io' and parts:
repo, rest = self.repos.get(parts[0].lower()), parts[1:]
elif host in self.hosts:
repo, rest = self.hosts[host], parts
elif host == 'raw.githubusercontent.com' and len(parts) >= 3 and parts[0].lower() == 'ventusltd':
repo = self.repos.get(parts[1].lower())
rest = parts[5:] if parts[2] == 'refs' and len(parts) > 4 and parts[3] in ('heads', 'tags') else parts[3:]
elif host == 'cdn.jsdelivr.net' and len(parts) >= 3 and parts[0] == 'gh' and parts[1].lower() == 'ventusltd':
repo, rest = self.repos.get(parts[2].split('@')[0].lower()), parts[3:]
elif host in ('github.com', 'www.github.com') and len(parts) >= 5 and parts[0].lower() == 'ventusltd' \
and parts[2] in ('blob', 'raw'):
repo, rest = self.repos.get(parts[1].lower()), parts[4:]
trail = False
if not rest:
return None
if not repo:
return None
return repo, '/'.join(rest) + ('/' if trail and rest else '')
def resolve_url(self, u):
t = self.url(u)
if not t:
return None
repo, p = t
hit = self.lookup(repo, p)
if not hit and self.pages_root.get(repo):
hit = self.lookup(repo, posixpath.join(self.pages_root[repo], p) + ('/' if p.endswith('/') else ''))
if hit:
return hit[0], '+'.join(x for x in ('url', hit[1]) if x)
return None
def resolve_path(self, f, spec, kind):
"""A path or URL written in file f -> (index, via) or None."""
spec = spec.strip()
if not spec or spec.startswith(('#', 'data:', 'mailto:', 'javascript:', 'tel:')):
return None
if re.match(r'^(?:https?:)?//', spec, re.I):
return self.resolve_url('https:' + spec if spec.startswith('//') else spec)
if re.match(r'^[a-z][a-z0-9+.-]*:', spec, re.I) or '${' in spec or '{{' in spec:
return None
path_part = urllib.parse.unquote(spec.split('#')[0].split('?')[0])
if not path_part:
return None
repo = f['repo']
if path_part.startswith('/'):
segs = path_part.lstrip('/').split('/', 1)
if repo in self.hosts.values():
cands = [(repo, path_part.lstrip('/'))]
elif segs[0].lower() == repo.lower():
cands = [(repo, segs[1] if len(segs) > 1 else '')]
elif segs[0].lower() in self.repos:
cands = [(self.repos[segs[0].lower()], segs[1] if len(segs) > 1 else '')]
else:
cands = [(repo, path_part.lstrip('/'))]
for r, p in cands:
hit = self.lookup(r, p + ('/' if path_part.endswith('/') and p else ''))
if hit:
return hit
return None
if not path_part.startswith('.'):
bare_is_package = kind in ('import', 'require', 'dynamic-import') and ext(f['path']) not in ('html', 'htm')
if bare_is_package:
return None
base = posixpath.dirname(f['path'])
trail = '/' if path_part.endswith('/') else ''
hit = self.lookup(repo, posixpath.join(base, path_part) + trail)
if hit:
return hit
doc_relative = kind in ('script-src', 'stylesheet', 'modulepreload', 'iframe', 'link', 'fetch', 'worker', 'import-map')
root = self.pages_root.get(repo, '')
if doc_relative and base != root:
hit = self.lookup(repo, posixpath.join(root, path_part) + trail)
if hit:
return hit[0], '+'.join(x for x in ('pages-root', hit[1]) if x)
return None
def resolve_python(self, f, spec, names, syspath):
"""Python module spec (dots + dotted name) and imported names -> list of (index, via, kind)."""
out = []
dots = len(spec) - len(spec.lstrip('.'))
mod = spec.lstrip('.').replace('.', '/')
repo = f['repo']
base = posixpath.dirname(f['path'])
for _ in range(max(0, dots - 1)):
base = posixpath.dirname(base)
def mod_in(d, m):
for c in ([posixpath.join(d, m + '.py'), posixpath.join(d, m, '__init__.py')] if m else
[posixpath.join(d, '__init__.py')]):
c = posixpath.normpath(c)
if (repo, c) in self.by_path:
return self.by_path[(repo, c)]
if STAMP.search(c) and (repo, STAMP.sub('#', c)) in self.fam:
return self.fam[(repo, STAMP.sub('#', c))]
return None
roots = [(base, '')] if dots else [(base, ''), ('', '')] + [(d, 'sys-path') for d in syspath]
kind = 'python-relative' if dots else 'import'
for d, how in roots:
found = []
pkg = posixpath.join(d, mod) if mod else d
for n in names: # from pkg import submodule
j = mod_in(pkg, n)
if j is not None:
found.append(j)
j = mod_in(d, mod) if mod else None
if j is not None:
found.append(j)
if not found and not mod and dots:
j = mod_in(d, '')
if j is not None:
found.append(j)
if found:
return [(j, '', how or kind) for j in found]
return out
def discover(self, f, spec, bases):
"""Files a test runner collects: [(index, via)]. Paths given on the command line narrow the search; with
none, the repository root (or the cd / working-directory folder) is searched."""
_, tool, args = spec.split(':', 2)
toks = args.split()
repo = f['repo']
if tool == 'unittest':
if 'discover' in toks:
d, pat = '.', 'test*.py'
for k, v in zip(toks, toks[1:]):
if k in ('-s', '--start-directory'):
d = v
elif k in ('-p', '--pattern'):
pat = v
rules, paths = [lambda n, pat=pat.strip('\'"'): fnmatch.fnmatch(n, pat)], [d]
else:
mods = [t for t in toks if not t.startswith('-')]
if not mods:
rules, paths = [lambda n: fnmatch.fnmatch(n, 'test*.py')], ['.']
else:
out = []
for m in mods:
p = m if m.endswith('.py') else m.replace('.', '/') + '.py'
hit = self.resolve_script(f, p, bases)
if hit:
out.append((hit[0], 'discover'))
return out
elif tool == 'py_compile': # python -m py_compile a.py b.py: those files, checked by the workflow
out = []
for t in toks:
hit = self.resolve_script(f, t, bases) if t.endswith('.py') else None
if hit:
out.append((hit[0], 'discover'))
return out
elif tool == 'pytest':
rules = [lambda n: fnmatch.fnmatch(n, 'test_*.py') or fnmatch.fnmatch(n, '*_test.py') or n == 'conftest.py']
skip = False
paths = []
for t in toks:
if skip:
skip = False
continue
if t in ('-k', '-m', '-p', '-c', '-o', '--rootdir', '--maxfail', '--tb', '--junitxml', '--cov', '-n'):
skip = True
continue
if not t.startswith('-') and '=' not in t and not t.startswith(('"', "'")):
paths.append(t.split('::')[0])
paths = paths or ['.']
else: # node --test
rules = [lambda n: re.match(r'^(?:test|.*[.\-_]test|test[\-_].*)\.[cm]?js$', n) is not None]
paths = [t.strip('\'"') for t in toks if not t.startswith('-')] or ['.']
out = []
for b in ([''] + list(bases)):
for p in paths:
p = posixpath.normpath(posixpath.join(b, p))
if p.startswith('..'):
continue
p = '' if p == '.' else p
for path, i in self.listing[repo]:
if path == p or (any(c in p for c in '*?[') and fnmatch.fnmatch(path, p)):
out.append((i, 'discover'))
elif (not p or path.startswith(p + '/')) and (
any(r(path.rsplit('/', 1)[-1]) for r in rules) or
(tool == 'node' and re.search(r'(?:^|/)test/[^/]*\.[cm]?js$', path[len(p):].lstrip('/')))):
out.append((i, 'discover'))
if out:
break
return out
def resolve_script(self, f, spec, bases):
"""A script path in a command line -> (index, via) or None. Repository root first (workflows and most
commands run there), then the folders named by cd / working-directory, then the file's own folder."""
repo = f['repo']
if spec.startswith('python-module:'):
m = spec.split(':', 1)[1].replace('.', '/')
for c in (m + '.py', m + '/__main__.py', m + '/__init__.py'):
if (repo, c) in self.by_path:
return self.by_path[(repo, c)], 'root'
return None
if spec.startswith('filedir:'):
p = posixpath.normpath(posixpath.join(posixpath.dirname(f['path']), spec[8:]))
hit = self.lookup(repo, p) if not p.startswith('..') else None
return (hit[0], 'shell-dir') if hit and not hit[1] else None
string = spec.startswith('string:')
if string:
spec = spec[7:]
if '$' in spec or '{' in spec:
return None
spec = spec.strip('\'"')
if '*' in spec: # a glob such as tools/*/proof.mjs: every estate file it matches (first hit returned here)
hits = self.glob(f, spec, bases)
return hits[0] if hits else None
if spec.startswith('/'):
return None
tries = [('', 'root')] + [(b, 'root') for b in bases] + [(posixpath.dirname(f['path']), '')]
if string:
tries = [(b, 'string' if not v else v + '+string') for b, v in tries]
for b, via in tries:
p = posixpath.normpath(posixpath.join(b, spec))
if p.startswith('..'):
continue
if (repo, p) in self.by_path:
return self.by_path[(repo, p)], via
if STAMP.search(p) and (repo, STAMP.sub('#', p)) in self.fam:
return self.fam[(repo, STAMP.sub('#', p))], '+'.join(x for x in (via, 'family') if x)
return None
def glob(self, f, spec, bases):
for b in [''] + list(bases) + [posixpath.dirname(f['path'])]:
pat = posixpath.normpath(posixpath.join(b, spec))
hits = [(i, 'glob') for path, i in self.listing[f['repo']] if fnmatch.fnmatchcase(path, pat)]
if hits:
return hits
return []
def edges_of(self, i):
"""[(target, kind, via)] for file i, and its unresolved external specs."""
f = self.files[i]
out, ext_specs, used = [], [], set()
url_out = {} # index in out -> the absolute URL it was written as
for kind, spec, extra in f['refs']:
if kind in ('import', 'python-relative') and f['path'].endswith('.py'):
hits = self.resolve_python(f, spec, extra, f.get('syspath', []))
for j, via, k in hits:
out.append((j, k, via))
if not hits:
ext_specs.append(spec)
continue
if kind in ('script-call', 'workflow-run') and spec.startswith('discover:'):
out += [(j, kind, via) for j, via in self.discover(f, spec, extra)]
continue
if kind in ('script-call', 'workflow-run') and '*' in spec and '$' not in spec:
out += [(j, kind, via) for j, via in self.glob(f, spec.strip('\'"'), extra)]
continue
if kind in ('script-call', 'workflow-run'):
if kind == 'workflow-run' and spec.startswith('./') and not re.search(r'\.\w+$', spec):
hit = None
for c in ('action.yml', 'action.yaml'):
hit = hit or self.resolve_script(f, posixpath.join(spec, c), ())
else:
hit = self.resolve_script(f, spec, extra)
if hit:
out.append((hit[0], kind, hit[1]))
continue
hit = self.resolve_path(f, spec, kind)
if re.match(r'^(?:https?:)?//', spec, re.I):
used.add(spec.rstrip('.,;:'))
if hit:
if re.match(r'^https?://', spec, re.I):
url_out[len(out)] = spec.rstrip('.,;:')
out.append((hit[0], kind, hit[1]))
elif kind in EXT_KINDS:
ext_specs.append(spec)
if 'http' in f['low']:
spans = None
in_code = {} # url -> True if any occurrence lies outside comments
for m in self.url_rx.finditer(f['text']):
u = m.group(0).rstrip('.,;:')
if f['text'][m.end():m.end() + 1] in ('$', '{'):
continue
if spans is None:
spans = comment_spans(f['path'], f['text'])
in_code[u] = in_code.get(u, False) or not in_spans(spans, m.start())
# contextual references written as URLs that occur only in comments become mentions
for n, spec in url_out.items():
if in_code.get(spec) is False:
out[n] = (out[n][0], 'comment-url', out[n][2])
for u, code in in_code.items():
if u in used:
continue
hit = self.resolve_url(u)
if hit:
out.append((hit[0], 'estate-url' if code else 'comment-url', hit[1]))
return [(j, k, v) for j, k, v in out if j != i], ext_specs
# ---------------------------------------------------------------- function: effects, stage, role, pattern, entry
EFFECTS = {
'dom': re.compile(r'\bdocument\.|\bwindow\.|\.innerHTML\b|getElementById|querySelector|createElement\(|appendChild\(|'
r'\.getContext\(|\bd3\.select|\bL\.map\(|maplibregl\.|new\s+THREE\.|<canvas|<svg\b'),
'network': re.compile(r'\bfetch\(|XMLHttpRequest|\baxios\b|new\s+WebSocket|EventSource\(|\brequests\.(?:get|post|put|Session)|'
r'urllib\.request|urlopen\(|http\.client|\baiohttp\b|\bhttpx\b|(?:^|\s)curl\s|(?:^|\s)wget\s|sendBeacon'),
'storage': re.compile(r'localStorage|sessionStorage|indexedDB|\bduckdb\b|\bsqlite3\b|\.parquet\b|caches\.open|document\.cookie'),
'filesystem': re.compile(r'(?<![\w.])open\(|\bos\.(?:remove|unlink|makedirs|mkdir|rename|walk|listdir)\b|\bshutil\.|\bpathlib\b|'
r'readFileSync|writeFileSync|\breadFile\(|\bwriteFile\(|require\([\'"](?:node:)?fs[\'"]\)|'
r'from\s+[\'"](?:node:)?fs(?:/promises)?[\'"]|json\.(?:dump|load)\(|\.to_csv\(|read_csv\(|np\.(?:save|load)\('),
'process': re.compile(r'\bsubprocess\b|os\.system\(|child_process|process\.exit\(|sys\.exit\(|\bspawn\(|\bexecSync\(|Popen\('),
}
WRITES = re.compile(r'(?<![\w.])open\([^)\n]*[\'"][wax]b?\+?[\'"]|writeFileSync|\bwriteFile\(|json\.dump\(|\.to_csv\(|'
r'\.to_parquet\(|\.write_text\(|\.write_bytes\(|\bCOPY\b[^\n]*\bTO\b|np\.save\(|savefig\(')
READS = re.compile(r'(?<![\w.])open\(|readFileSync|\breadFile\(|json\.load\(|read_csv\(|read_parquet|pd\.read_|np\.load\(|'
r'\.read_text\(|\bfetch\(|XMLHttpRequest|urlopen\(|requests\.get')
DRAW = re.compile(r'\.getContext\(|<canvas|<svg\b|\.fillRect\(|\.stroke\(|\.fill\(|drawArrays|drawElements|'
r'\.beginPath\(|\bmatplotlib\b|\bplt\.|\.innerHTML\b|createElement\(|addLayer\(|maplibregl\.|\bL\.map\(')
EVENTS = re.compile(r'addEventListener\(|\bon(?:click|change|input|key\w+|mouse\w+|pointer\w+|touch\w+|submit)\b|'
r'history\.pushState|hashchange|popstate|\brouter\b|\bnavigate\(')
DOMAIN = [
('geodesy', set('haversine bearing bearings geodesy geodesic geodetic latlon latlng lat lng lon longitude latitude coord '
'coords coordinate coordinates projection utm wgs84 osgb bng easting northing distance distances geohash '
'mercator vincenty azimuth geojson km elevation terrain lidar polygon geodesic'.split())),
('electrical', set('voltage volt volts kv ampacity amps amp cable cables conductor derating impedance resistance reactance '
'ohm ohms transformer busbar fault earthing kva mva inverter sld substation switchgear feeder '
'vdrop electrical current watts phase harmonic rating'.split())),
('energy-data', set('generation prices price market markets repd elexon bmrs tariff demand interconnector interconnectors '
'carbon intensity mwh capacity dno tso neso ukpn ssen datacentre auction fuelinst wind solar '
'register pipeline'.split())),
]
# Cheap substring gates (on lower-case text) before each costly expression: same results, much faster.
GATES = {
'dom': ('document.', 'window.', 'innerhtml', 'getelementbyid', 'queryselector', 'createelement', 'appendchild',
'getcontext', 'd3.select', 'l.map(', 'maplibregl', 'three', '<canvas', '<svg'),
'network': ('fetch(', 'xmlhttprequest', 'axios', 'websocket', 'eventsource', 'requests.', 'urllib', 'urlopen',
'http.client', 'aiohttp', 'httpx', 'curl', 'wget', 'sendbeacon'),
'storage': ('localstorage', 'sessionstorage', 'indexeddb', 'duckdb', 'sqlite3', '.parquet', 'caches.open', 'document.cookie'),
'filesystem': ('open(', 'os.', 'shutil', 'pathlib', 'readfile', 'writefile', 'fs', 'json.dump', 'json.load', 'to_csv',
'read_csv', 'np.save', 'np.load'),
'process': ('subprocess', 'os.system', 'child_process', 'process.exit', 'sys.exit', 'spawn(', 'execsync', 'popen('),
'writes': ('open(', 'writefile', 'json.dump', 'to_csv', 'to_parquet', 'write_text', 'write_bytes', 'copy', 'np.save', 'savefig'),
'reads': ('open(', 'readfile', 'json.load', 'read_csv', 'read_parquet', 'pd.read_', 'np.load', 'read_text', 'fetch(',
'xmlhttprequest', 'urlopen', 'requests.get'),
'draw': ('getcontext', '<canvas', '<svg', 'fillrect', '.stroke(', '.fill(', 'drawarrays', 'drawelements', 'beginpath',
'matplotlib', 'plt.', 'innerhtml', 'createelement', 'addlayer', 'maplibregl', 'l.map('),
'events': ('addeventlistener', 'onclick', 'onchange', 'oninput', 'onkey', 'onmouse', 'onpointer', 'ontouch', 'onsubmit',
'pushstate', 'hashchange', 'popstate', 'router', 'navigate('),
}
def gate(f, key):
low = f['low']
return any(t in low for t in (GATES[key] if isinstance(key, str) else key))
GENERIC_NAMES = set('main init setup render update run test get set handler constructor start draw resize onload tostring '
'apply build create load parse fetch reset clear close open show hide toggle format process handle '
'helper wrapper default index value values items element elements status error errors config '
'options callback listener refresh redraw remove append insert select filter search compute '
'calculate validate normalize normalise convert transform write read save print debug log '
'escape escapehtml sleep delay noop'.split())
def effects_of(f):
e = ext(f['path'])
text = f['text']
eff = {k for k, rx in EFFECTS.items() if gate(f, k) and rx.search(text)}
if e in ('html', 'htm', 'css', 'vue', 'svelte'):
eff.add('dom')
if e in ('sh', 'ps1', 'bat') or f['path'].startswith('.github/workflows/'):
eff.add('process')
f['effects'] = sorted(eff)
f['writes'] = gate(f, 'writes') and bool(WRITES.search(text))
f['reads'] = (gate(f, 'reads') and bool(READS.search(text))) or bool(eff & {'network', 'storage'})
f['draw_n'] = (len(DRAW.findall(text)) if gate(f, 'draw') else 0) + (5 if e in ('html', 'htm', 'css') else 0)
f['event_n'] = len(EVENTS.findall(text)) if gate(f, 'events') else 0
f['entry_main'] = bool(re.search(r'''if\s+__name__\s*==\s*['"]__main__['"]''', text)) or \
bool(f['lines'] and f['lines'][0].startswith('#!'))
def stage_of(f):
"""The documented stage rule (module docstring)."""
if 'dom' in f['effects'] or f['draw_n'] or f['writes']:
return 'output'
if f['reads'] or set(f['effects']) & {'network', 'storage', 'filesystem'}:
return 'ingest'
if not f['effects'] and f['defs'] and any(k != 'workflow' for n, k, i in f['defs']):
return 'transform'
return 'unknown'
def role_of(f):
"""The documented role rule (module docstring): first match wins."""
path = f['path']
e = ext(path)
name = path.rsplit('/', 1)[-1].lower()
pw = set(words_of(path))
kind = f.get('kind') or kind_of(path, f['lines'])
if kind == 'test' or pw & {'test', 'tests', 'spec', 'specs', 'smoke'}:
return 'test'
if kind == 'workflow' or path.startswith('.github/') or e in ('sh', 'ps1', 'bat') or pw & {'ci', 'workflow', 'workflows', 'deploy', 'release'}:
return 'automation'
if e in ('toml', 'yml', 'yaml') or re.match(r'(config|settings|manifest)\b', name):
return 'docs-config'
stem_words = name_words(name)
folder_words = name_words(path.rsplit('/', 1)[0]) if '/' in path else []
def_words = set()
for n, k, i in f['defs']:
def_words.update(words_of(n))
vw = []
for v in f.get('vedic') or []:
vw += words_of(' '.join(str(v.get(x) or '') for x in ('periodic_category', 'estate_group', 'discipline')))
best, best_s = None, 1
for role, kws in DOMAIN:
s = sum(1 for w in def_words if w in kws) + 2 * sum(1 for w in set(stem_words) if w in kws) + \
sum(1 for w in set(folder_words[-1:]) if w in kws) + 2 * sum(1 for w in set(vw) if w in kws)
if s > best_s:
best, best_s = role, s
if best:
return best
if kind in ('page', 'style sheet'):
return 'render'
if 'dom' in f['effects'] or f['draw_n']:
return 'interaction' if f['event_n'] > f['draw_n'] else 'render'
if 'storage' in f['effects'] or f['writes']:
return 'storage'
if f['reads'] or 'network' in f['effects'] or \
any(re.match(r'(fetch|load|parse|read|decode)', n, re.I) for n, k, i in f['defs']):
return 'ingest'
if not f['effects'] and f['defs']:
return 'transform'
return 'other'
def family_of(name):
fam = re.sub(r'(?:[_\-]?[vV]?\d+)+$', '', name)
return fam if len(fam) >= 5 and fam.lower().replace('_', '') not in GENERIC_NAMES else ''
def assign_patterns(files, leaks):
holders = collections.defaultdict(set)
for i, f in enumerate(files):
for n, k, ln in f['defs']:
if k in ('function', 'class'):
fam = family_of(n)
if fam:
holders[fam].add(i)
for i, f in enumerate(files):
best = None
for fam in {family_of(n) for n, k, ln in f['defs'] if k in ('function', 'class')}:
c = len(holders.get(fam, ()))
if fam and 2 <= c <= 100 and not leaks(fam):
key = (c, -len(fam), fam)
if best is None or key < best[0]:
best = (key, fam)
f['pattern'] = best[1] if best else ''
f['pattern_n'] = best[0][0] if best else 0
def package_entries(metas, by_path):
"""Files named as main, bin or exports, or run by a script command, in any package.json."""
out = set()
for repo, meta in metas.items():
for ppath, pkg in meta['packages'].items():
if not isinstance(pkg, dict):
continue
base = posixpath.dirname(ppath)
targets = []
for key in ('main', 'module', 'browser', 'bin', 'exports'):
v = pkg.get(key)
stack = [v]
while stack:
x = stack.pop()
if isinstance(x, str):
targets.append(x)
elif isinstance(x, dict):
stack += list(x.values())
elif isinstance(x, list):
stack += x
scripts = pkg.get('scripts')
if isinstance(scripts, dict): # npm scripts: "build": "node scripts/build.mjs"
for cmd in scripts.values():
if isinstance(cmd, str):
targets += [s for s in CMD.findall(cmd) + CMD_EXEC.findall(cmd) if '$' not in s]
for t in targets:
p = posixpath.normpath(posixpath.join(base, t))
for c in (p, p + '.js', p + '/index.js'):
if (repo, c) in by_path:
out.add(by_path[(repo, c)])
break
return out
# ---------------------------------------------------------------- synopsis (evidence only)
# Known hosts -> plain names. A URL to an unknown host counts only where it is fetched, and then by host name.
HOSTS = [
(r'raw\.githubusercontent\.com/ventusltd/([\w.-]+)', lambda m: '%s data' % m.group(1)),