tracker
All repositories: gitoria
13.0 KB
#!/usr/bin/env python3"""tools/let-audit.py [--fix] [--list] <file.hl …> — mission 028 (code order rule 1: `let` ONLY for a variable that is reassigned).Counts every `let NAME = …` and decides whether it may be a plain declaration (`NAME = …`); --fix rewrites those in place,--list prints every kept one with its reason. A `let` STAYS when:reassigned NAME is written again in its function (a nested closure included), or appended to (`NAME[] = v`)loop it is declared inside a loop body (a plain declaration there is "Cannot reassign" on the 2nd pass) or a for headshadow the same name is a member / import of the file (or of a component's `parent`), a parameter or name of anenclosing function, or is read somewhere else as a free name (a plain `NAME = …` would then REBIND that outer binding instead of declaring one)block NAME is used outside the block it is declared in, or before it (the browser target emits a bare declaration as ablock-scoped JS `let`, a `let` as a function-scoped `var`)root a file-root `let` of a component (a View member; left alone) or one written anywhere else in the fileform destructuring or no initializerTokens: `//` comments; '…' and "…" strings (a backslash masks the next character); no regexes, no backtick strings in code."""import os, re, sysKEYWORDS_BLOCK = {'if', 'switch', 'catch', 'with'}KEYWORDS_LOOP = {'for', 'while'}IMPLICIT = {'session', 'params', 'route', 'req', 'res', 'server', 'title', 'head', 'query', 'state', 'kids', 'page', 'emit','refresh', 'this', 'super', 'styles', 'View', 'console'}def tokenize(src):toks = [] # (kind, text, start)i, n = 0, len(src)while i < n:c = src[i]if c in ' \t\r\n':i += 1elif src.startswith('//', i):j = src.find('\n', i)i = n if j < 0 else jelif c in '\'"':j = i + 1while j < n and src[j] != c:j += 2 if src[j] == '\\' else 1toks.append(('str', src[i:j + 1], i))i = j + 1elif c.isalpha() or c in '_#@$' or ord(c) > 127:j = iwhile j < n and (src[j].isalnum() or src[j] in '_#@$' or ord(src[j]) > 127):j += 1toks.append(('id', src[i:j], i))i = jelif c.isdigit():m = re.match(r'\d+(\.\d+)?([eE][+-]?\d+)?', src[i:])toks.append(('num', m.group(0), i))i += len(m.group(0))else:for op in ('===', '!==', '=>', '==', '!=', '<=', '>=', '&&', '||', '??', '++', '--', '+=', '-=', '*=', '/=', '<>', '?.', '...'):if src.startswith(op, i):toks.append(('op', op, i))i += len(op)breakelse:toks.append(('op', c, i))i += 1return toksOBJ_BEFORE = {'=', '(', ',', '[', ':', '?', '||', '&&', '??', '!', '+', '-', '<>', '==', '!=', '===', '!==', '<', '>', '<=', '>=', '...'}class Frame:def __init__(self, kind, start, parent, params=()):self.kind, self.start, self.end, self.parent, self.params = kind, start, None, parent, set(params)def func(self):f = selfwhile f.kind not in ('func', 'root'):f = f.parentreturn fdef rootsOf(path):return analyse(path, True, want_roots=True)def analyse(path, is_component, want_roots=False):src = open(path, encoding='utf-8').read()toks = tokenize(src)root = Frame('root', -1, None)root.end = len(toks)frames = [root]stack = [root]match = {}popen = []frame_of = [None] * len(toks) # the innermost brace frame of each tokenparen_kind = [None] * len(toks) # 'forhead' when inside a for(...) headforheads = []param_toks = set()for k, (kind, text, _) in enumerate(toks):top = stack[-1]frame_of[k] = topif forheads:paren_kind[k] = 'forhead'if kind != 'op':continueif text in '([':popen.append(k)if text == '(' and k > 0 and toks[k - 1][1] == 'for':forheads.append(k)elif text in ')]':o = popen.pop()match[k] = omatch[o] = kif forheads and forheads[-1] == o:forheads.pop()elif text == '{':prev = toks[k - 1] if k > 0 else ('op', '', 0)fkind, params = 'block', ()if prev[1] == '=>':fkind = 'func'b = k - 2if toks[b][1] == ')':params = [t[1] for t in toks[match[b] + 1:b] if t[0] == 'id']param_toks.update(j for j in range(match[b] + 1, b) if toks[j][0] == 'id')elif toks[b][0] == 'id':params = [toks[b][1]]param_toks.add(b)elif prev[1] == ')':o = match[k - 1]before = toks[o - 1] if o > 0 else ('op', '', 0)if before[0] == 'id' and before[1] in KEYWORDS_LOOP:fkind = 'loop'elif before[0] == 'id' and before[1] in KEYWORDS_BLOCK:fkind = 'block'elif before[0] == 'id':fkind = 'func'params = [t[1] for t in toks[o + 1:k - 1] if t[0] == 'id']param_toks.update(j for j in range(o + 1, k - 1) if toks[j][0] == 'id')else:fkind = 'obj'elif prev[0] == 'id' and prev[1] in ('else', 'try', 'finally'):fkind = 'block'elif prev[0] == 'id' and prev[1] == 'do':fkind = 'loop'elif prev[0] in ('id', 'str'):fkind = 'elem'elif prev[0] == 'op' and (prev[1] in OBJ_BEFORE or prev[1] == '') or (prev[0] == 'id' and prev[1] == 'return'):fkind = 'obj'f = Frame(fkind, k, top, params)frames.append(f)stack.append(f)elif text == '}':f = stack.pop()f.end = kframe_of[k] = f.parent# every identifier occurrence: (k, name, role) role = let | assign | append | param | read | keyocc = {}roots = set()for k, (kind, text, _) in enumerate(toks):if kind != 'id':continueprev = toks[k - 1][1] if k > 0 else ''nxt = toks[k + 1][1] if k + 1 < len(toks) else ''fr = frame_of[k]if prev in ('.', '?.'):continueif k in param_toks:role = 'param'elif prev == 'let':role = 'let'elif prev == '(' and k > 1 and toks[k - 2][1] == 'for' and nxt in ('of', 'in'):role = 'forvar'elif fr.kind in ('obj', 'elem') and nxt == '=':role = 'key'elif nxt in ('=', '++', '--', '+=', '-=', '*=', '/=') or prev in ('++', '--'):role = 'assign'elif nxt == '[' and k + 3 < len(toks) and toks[k + 2][1] == ']' and toks[k + 3][1] == '=':role = 'append'else:role = 'read'occ.setdefault(text, []).append((k, role))# file-root members: written at the root (outside every function), static, imported, root methodsif fr.func() is root and role in ('let', 'assign'):roots.add(text)if prev == 'static' or prev == 'import':roots.add(text)if nxt == '(' and fr is root and prev not in ('new',):c = match.get(k + 1)if c is not None and c + 1 < len(toks) and toks[c + 1][1] == '{':roots.add(text)# a component's `parent '<file>'`: the parent's members are this one's too (main.hl's header members in every page)for k, (kind, text, _) in enumerate(toks):if text == 'parent' and kind == 'id' and k + 1 < len(toks) and toks[k + 1][0] == 'str' and frame_of[k] is root:ppath = os.path.normpath(os.path.join(os.path.dirname(path), toks[k + 1][1][1:-1]))if os.path.exists(ppath):roots |= rootsOf(ppath)# imports `import { a, b } from` / `import X from`for k, (kind, text, _) in enumerate(toks):if text == 'import' and k + 1 < len(toks):j = k + 1if toks[j][1] == '{':while toks[j][1] != '}':if toks[j][0] == 'id':roots.add(toks[j][1])j += 1elif toks[j][0] == 'id':roots.add(toks[j][1])if want_roots:return rootsdef inside(k, f):return f.start < k < f.end if f.kind != 'root' else Truedef chain(f):out = []while f is not None:out.append(f)f = f.parentreturn outdef declares(g, name):# does function g itself bind `name` (param, let, or a plain write at its own level that is not a root member)?if name in g.params:return Truefor (k, role) in occ.get(name, []):if role in ('let', 'assign', 'forvar') and frame_of[k].func() is g:return Truereturn Falseresults = []for k, (kind, text, start) in enumerate(toks):if text != 'let' or kind != 'id':continueif k + 2 >= len(toks) or toks[k + 1][0] != 'id' or toks[k + 2][1] != '=':results.append((k, toks[k + 1][1] if k + 1 < len(toks) else '?', 'form'))continuename = toks[k + 1][1]fr = frame_of[k]F = fr.func()if paren_kind[k] == 'forhead':results.append((k, name, 'loop'))continue# loop between the let and its function?g, loop = fr, Falsewhile g is not F:if g.kind == 'loop':loop = Trueg = g.parentothers = [(j, r) for (j, r) in occ[name] if j != k + 1 and inside(j, F)]reassigned = any(r in ('assign', 'append', 'let', 'forvar') for (j, r) in others)others = [(j, r) for (j, r) in others if r not in ('key', 'param')]if F is root:elsewhere = [(j, r) for (j, r) in occ[name] if j != k + 1 and r in ('assign', 'append', 'let', 'forvar')]if loop:results.append((k, name, 'loop'))elif elsewhere or is_component:results.append((k, name, 'reassigned' if elsewhere else 'root'))else:results.append((k, name, 'ok'))continueif reassigned:results.append((k, name, 'reassigned'))continueif loop:results.append((k, name, 'loop'))continue# shadow: a member/import, an implicit member, a param of F or an enclosing function, a name an enclosing function binds,# a nested function's parameter of the same name, or a FREE read anywhere outside Fbad = name in roots or name in IMPLICIT or name in F.paramsfor g in chain(F.parent):if g.kind == 'func' and declares(g, name):bad = Truefor f2 in frames:if f2.kind == 'func' and f2 is not F and inside(f2.start, F) and name in f2.params:bad = Trueif not bad:for (j, r) in occ[name]:if inside(j, F) or r in ('key', 'param'):continueif not any(g.kind == 'func' and declares(g, name) for g in chain(frame_of[j].func())):bad = Truebreakif bad:results.append((k, name, 'shadow'))continue# block: every use inside the declaration's own block, after itblk = frif any(not (j > k and (blk is F or inside(j, blk))) for (j, r) in others):results.append((k, name, 'block'))continueresults.append((k, name, 'ok'))return src, toks, resultsdef main():args = sys.argv[1:]fix = '--fix' in argslst = '--list' in argsfiles = [a for a in args if not a.startswith('--')]total = {}for path in files:is_component = '/components/' in '/' + pathsrc, toks, results = analyse(path, is_component)counts = {}for (k, name, why) in results:counts[why] = counts.get(why, 0) + 1total[why] = total.get(why, 0) + 1if lst and why != 'ok':line = src.count('\n', 0, toks[k][2]) + 1print(f'{path}:{line}: keep let {name} ({why})')n = len(results)print(f'{path}: let={n} ' + ' '.join(f'{w}={c}' for w, c in sorted(counts.items())))if fix:out = srcfor (k, name, why) in sorted(results, key=lambda r: -toks[r[0]][2]):if why == 'ok':s = toks[k][2]e = toks[k + 1][2]out = out[:s] + out[e:]if out != src:open(path, 'w', encoding='utf-8').write(out)n = sum(total.values())print(f'TOTAL let={n} ' + ' '.join(f'{w}={c}' for w, c in sorted(total.items())))if __name__ == '__main__':main()
Branches
- mainmain branch
Latest commits
- 7d4b293dtracker#40: "Franchises" in the main menu (desktop header after People, phone sidebar) → /franchises, marked on franchise and timeline pages; gates 365/0, 32/0, 53/0, 24/0, check-theme 0mre
- 93dfb0batracker#40 (mission 034): the curated franchises — data/franchises.json (17 franchises, 31 timelines, 285 TMDB titles, movies + series, in-universe/release order, 12 TMDB collections attached); lib/franchiseseed.hl + jobs.hl franchiseSeedTick (last start job, imports missing titles via details.hl importWithCredits = the search's Add, one per step paced, then one build; franchiseseed.db: editor changes win, the creator's same-name franchise adopted / timeline left alone, 404 remembered, resumable, idempotent); timeline heads 'N titles · in-universe order' (orderKind) and wrap on a phone; series pages show the widget; new gate tests/franchiseseed.mjs (5th in deploy.sh), the others run with TRACKER_FRANCHISE_SEED=0; gates 365/0, 32/0, 52/0, 24/0, check-theme 0; real copy 196 imported, 0 failed, 7 min, restart unchanged=31mre
- 96ba683adeploy.sh: a gate without a 'passed,' line (check-theme) no longer ends the scriptmre
- eb3b9205tracker: report 031mre
- 9b5d2e89tracker mission 031: README (What it does, Test: four gates + the #32 checks, Files: theme/, new pages), STATUS (real copy, A/B load, how to repeat, open points), LOGmre
- 39950e4ctracker#32 (mission 031): the WorldAPI theme (theme/ vendored verbatim from layouts.worldapi.org 85b5654; styles.hl inherits it: accent green-dark, type colours 1-6; own base/header rules, row lines, genre-pill and inverted-button frames removed, the season foldable keeps its line; check-theme 21 -> 0, 4th deploy gate; main actions class primary) and the #32 header (theme AppHeader/MainMenu/UserMenu/Sidebar/ContentFirst: desktop brand, search, Series|Shows|Movies|Genres|People, user icon with Unwatched..Settings, Logout; signed out the ident selector, phone the iD icon dropdown; phone menu in the sidebar overlay; marked entry by :has); /find -> /search/<q>, /genres, /people(/<letter>), /settings; main { ContentFirst { slot } } works around the hl:web one-line slot bug; gates 365/0, 32/0, 52/0, check-theme 0mre
- a386dc92tracker: reports 029 + 030mre
- 71e0fd7dtracker missions 029 + 030: README (What it does, Files, gate count), STATUS (real-copy numbers, how to repeat, open points), LOGmre
- d36ea6eatracker#34 + #35 (mission 030): Follow directly under the poster, as wide as the poster (show.hl, styles.hl); the status pill next to a series' title — TVmaze's status (new tvmazeStatus, stored by the sync's TVmaze merge) else TMDB's, TVmaze Ended + TMDB Canceled = Canceled, inverted (filled, dark text, no border), green running / yellow pending / red canceled / muted ended (shows.hl statusOf); the daily delta asks TVmaze's status of an unfollowed series TVmaze's change list names (dailysync.hl syncRunStep, sync.hl syncTvmazeStatus); the status backfill after the details repair (backfill.hl, jobs.hl statusTick; resumable, 550 ms per TVmaze request); gates 354/0, 32/0, 52/0mre
- 7d7d4487tracker#33 (mission 029): reduced titles — every title TMDB's details never went through this app (no detailsAt, no tmdbSync) is incomplete (shows.hl isIncomplete; the old tracker's migrated rows passed #26's test: 5,697 non-adult on the live copy, 691 series without seasons); the repair job does the visibly reduced first (shows.hl missingParts), the page completes one on open; a title TMDB has no poster for (The Remaining) shows the placeholder; tools/count-incomplete.hl; gate fixtures stand for synced titles (tmdbSync), tests/seed-reduced.hl + #33 checks; gates 347/0, 32/0, 52/0mre
- 661c2592tracker: report 028mre
- 27c916fatracker mission 028: README ("Code order", the new file map), STATUS (counts before/after, tests, how to repeat, open), LOGmre
- d924f398tracker mission 028: comments name the new files (sync.hl, dailysync.hl, backfill.hl, credits.hl, jobs.hl, images.hl …); tools/ref-params.py + tools/lambda-audit.py also scan lib/ (they globbed the root only), lambda-audit counts a plain `x = p` alias like `let x = p`mre
- 2e89b968tracker mission 028 (code order) 5/5 let: `let` only where a variable is reassigned — 667 never-reassigned lets became plain declarations (project.hl, lib/, components/, tools/, tests/); kept: 264 in loop bodies (a plain declaration there is 'Cannot reassign' on the 2nd pass), 234 reassigned, 27 whose name is also a member/outer/free name (a plain write would rebind it); tools/let-audit.py decides and fixes (README 'Code order'); tests/realdata-m028.{sh,mjs} = the page-output diff on a real copy; gates 342/0, 32/0, 52/0, real-copy pages identicalmre
- 54796ff2tracker mission 028 (code order) 4/5 thin faces + last copies: the show page's check/follow faces call lib/watches.hl toggleWatched / toggleSeasonWatched (seasonAllWatched moved there) and lib/follows.hl toggleFollowed; both logins (header selector face, /login/callback) share lib/users.hl userOfCode; todayStr/listOf copies in components and the export readers copied into tools/migrate.hl + tools/old-short-ids.hl now once (lib/util.hl, lib/export.hl); gates 342/0, 32/0, 52/0; old-short-ids output byte-identical, migrate output identicalmre
- 06b078e3tracker mission 028 (code order) 3/5 project.hl is the map: config, routes, wiring and a feature → file index (914 → 258 lines); the background jobs (daily sync run, backfills, details repair, credits job, merge, short ids, collection seed) moved unchanged into lib/jobs.hl (a class: their state is reassigned every step, a static cannot be; one instance made after the server), the login callback into lib/users.hl, poster/photo serving into lib/images.hl, the /shows/<slug> rule into lib/shows.hl showsMovedPath; route handlers are thin wrappers; gates 342/0, 32/0, 52/0, real-copy pages identicalmre
- 94716fd2tracker mission 028 (code order) 2/5 util + topics: lib/util.hl holds envOr, storageDir, postersDir, profilesDir, newId, hexDigits, todayStr, dateOr, textOr, hasId, listOr, firstOf, sortDesc once (were copied into up to 5 files); tmdbsync.hl split into tmdb.hl (TMDB/TVmaze requests), sync.hl (one title's sync), sync-helpers.hl, backfill.hl; details.hl split into details.hl, credits.hl, credits-helpers.hl (isIncomplete to shows.hl); search-helpers.hl (words, query, ranking, slugs); collections.hl (the TMDB collection seed, out of franchises.hl); deltasync.hl renamed dailysync.hl; no behaviour change: gates 342/0, 32/0, 52/0, real-copy pages identicalmre
- 186079b0tracker mission 028 (code order) 1/5 move: every root .hl except project.hl into lib/ (styles.hl into components/), import paths only; gates 342/0, 32/0, 52/0; real-copy pages identicalmre
- 4f47f181tracker: report 027mre
- dc1d4be4tracker mission 027: Hybriel master 06617221 vendored (plugin allocator fixes 3a781359 + 413f60e4); real copy RSS through first-start jobs + 400 loads flat ~2.55 GB (190aa11d 2.3 -> 5.6 GB), page times <= 1.1x; gates 342/0, 32/0, 52/0mre