gitoriaLog in with ident

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit8f1d45428f1d4542tracker#40: superseded collections — a TMDB collection timeline whose titles are all in one curated timeline is hidden (supersededBy; kept: own page + editor finder), set by the collection seed when it makes one and by the curated build (lifted when the cover is gone); partly covered ones join that franchise; no second widget (First Contact: only Star Trek — Prime); gate franchiseseed 26/0, browser 365/0, kinds 32/0, franchises 53/0, check-theme 0; real copy 24 supersededmre8f1d4542/tools/let-audit.py

13.0 KB

  1. #!/usr/bin/env python3
  2. """tools/let-audit.py [--fix] [--list] <file.hl …> — mission 028 (code order rule 1: `let` ONLY for a variable that is reassigned).
  3. Counts every `let NAME = …` and decides whether it may be a plain declaration (`NAME = …`); --fix rewrites those in place,
  4. --list prints every kept one with its reason. A `let` STAYS when:
  5. reassigned NAME is written again in its function (a nested closure included), or appended to (`NAME[] = v`)
  6. loop it is declared inside a loop body (a plain declaration there is "Cannot reassign" on the 2nd pass) or a for head
  7. shadow the same name is a member / import of the file (or of a component's `parent`), a parameter or name of an
  8. enclosing function, or is read somewhere else as a free name (a plain `NAME = …` would then REBIND that outer binding instead of declaring one)
  9. block NAME is used outside the block it is declared in, or before it (the browser target emits a bare declaration as a
  10. block-scoped JS `let`, a `let` as a function-scoped `var`)
  11. root a file-root `let` of a component (a View member; left alone) or one written anywhere else in the file
  12. form destructuring or no initializer
  13. Tokens: `//` comments; '…' and "…" strings (a backslash masks the next character); no regexes, no backtick strings in code.
  14. """
  15. import os, re, sys
  16. KEYWORDS_BLOCK = {'if', 'switch', 'catch', 'with'}
  17. KEYWORDS_LOOP = {'for', 'while'}
  18. IMPLICIT = {'session', 'params', 'route', 'req', 'res', 'server', 'title', 'head', 'query', 'state', 'kids', 'page', 'emit',
  19. 'refresh', 'this', 'super', 'styles', 'View', 'console'}
  20. def tokenize(src):
  21. toks = [] # (kind, text, start)
  22. i, n = 0, len(src)
  23. while i < n:
  24. c = src[i]
  25. if c in ' \t\r\n':
  26. i += 1
  27. elif src.startswith('//', i):
  28. j = src.find('\n', i)
  29. i = n if j < 0 else j
  30. elif c in '\'"':
  31. j = i + 1
  32. while j < n and src[j] != c:
  33. j += 2 if src[j] == '\\' else 1
  34. toks.append(('str', src[i:j + 1], i))
  35. i = j + 1
  36. elif c.isalpha() or c in '_#@$' or ord(c) > 127:
  37. j = i
  38. while j < n and (src[j].isalnum() or src[j] in '_#@$' or ord(src[j]) > 127):
  39. j += 1
  40. toks.append(('id', src[i:j], i))
  41. i = j
  42. elif c.isdigit():
  43. m = re.match(r'\d+(\.\d+)?([eE][+-]?\d+)?', src[i:])
  44. toks.append(('num', m.group(0), i))
  45. i += len(m.group(0))
  46. else:
  47. for op in ('===', '!==', '=>', '==', '!=', '<=', '>=', '&&', '||', '??', '++', '--', '+=', '-=', '*=', '/=', '<>', '?.', '...'):
  48. if src.startswith(op, i):
  49. toks.append(('op', op, i))
  50. i += len(op)
  51. break
  52. else:
  53. toks.append(('op', c, i))
  54. i += 1
  55. return toks
  56. OBJ_BEFORE = {'=', '(', ',', '[', ':', '?', '||', '&&', '??', '!', '+', '-', '<>', '==', '!=', '===', '!==', '<', '>', '<=', '>=', '...'}
  57. class Frame:
  58. def __init__(self, kind, start, parent, params=()):
  59. self.kind, self.start, self.end, self.parent, self.params = kind, start, None, parent, set(params)
  60. def func(self):
  61. f = self
  62. while f.kind not in ('func', 'root'):
  63. f = f.parent
  64. return f
  65. def rootsOf(path):
  66. return analyse(path, True, want_roots=True)
  67. def analyse(path, is_component, want_roots=False):
  68. src = open(path, encoding='utf-8').read()
  69. toks = tokenize(src)
  70. root = Frame('root', -1, None)
  71. root.end = len(toks)
  72. frames = [root]
  73. stack = [root]
  74. match = {}
  75. popen = []
  76. frame_of = [None] * len(toks) # the innermost brace frame of each token
  77. paren_kind = [None] * len(toks) # 'forhead' when inside a for(...) head
  78. forheads = []
  79. param_toks = set()
  80. for k, (kind, text, _) in enumerate(toks):
  81. top = stack[-1]
  82. frame_of[k] = top
  83. if forheads:
  84. paren_kind[k] = 'forhead'
  85. if kind != 'op':
  86. continue
  87. if text in '([':
  88. popen.append(k)
  89. if text == '(' and k > 0 and toks[k - 1][1] == 'for':
  90. forheads.append(k)
  91. elif text in ')]':
  92. o = popen.pop()
  93. match[k] = o
  94. match[o] = k
  95. if forheads and forheads[-1] == o:
  96. forheads.pop()
  97. elif text == '{':
  98. prev = toks[k - 1] if k > 0 else ('op', '', 0)
  99. fkind, params = 'block', ()
  100. if prev[1] == '=>':
  101. fkind = 'func'
  102. b = k - 2
  103. if toks[b][1] == ')':
  104. params = [t[1] for t in toks[match[b] + 1:b] if t[0] == 'id']
  105. param_toks.update(j for j in range(match[b] + 1, b) if toks[j][0] == 'id')
  106. elif toks[b][0] == 'id':
  107. params = [toks[b][1]]
  108. param_toks.add(b)
  109. elif prev[1] == ')':
  110. o = match[k - 1]
  111. before = toks[o - 1] if o > 0 else ('op', '', 0)
  112. if before[0] == 'id' and before[1] in KEYWORDS_LOOP:
  113. fkind = 'loop'
  114. elif before[0] == 'id' and before[1] in KEYWORDS_BLOCK:
  115. fkind = 'block'
  116. elif before[0] == 'id':
  117. fkind = 'func'
  118. params = [t[1] for t in toks[o + 1:k - 1] if t[0] == 'id']
  119. param_toks.update(j for j in range(o + 1, k - 1) if toks[j][0] == 'id')
  120. else:
  121. fkind = 'obj'
  122. elif prev[0] == 'id' and prev[1] in ('else', 'try', 'finally'):
  123. fkind = 'block'
  124. elif prev[0] == 'id' and prev[1] == 'do':
  125. fkind = 'loop'
  126. elif prev[0] in ('id', 'str'):
  127. fkind = 'elem'
  128. elif prev[0] == 'op' and (prev[1] in OBJ_BEFORE or prev[1] == '') or (prev[0] == 'id' and prev[1] == 'return'):
  129. fkind = 'obj'
  130. f = Frame(fkind, k, top, params)
  131. frames.append(f)
  132. stack.append(f)
  133. elif text == '}':
  134. f = stack.pop()
  135. f.end = k
  136. frame_of[k] = f.parent
  137. # every identifier occurrence: (k, name, role) role = let | assign | append | param | read | key
  138. occ = {}
  139. roots = set()
  140. for k, (kind, text, _) in enumerate(toks):
  141. if kind != 'id':
  142. continue
  143. prev = toks[k - 1][1] if k > 0 else ''
  144. nxt = toks[k + 1][1] if k + 1 < len(toks) else ''
  145. fr = frame_of[k]
  146. if prev in ('.', '?.'):
  147. continue
  148. if k in param_toks:
  149. role = 'param'
  150. elif prev == 'let':
  151. role = 'let'
  152. elif prev == '(' and k > 1 and toks[k - 2][1] == 'for' and nxt in ('of', 'in'):
  153. role = 'forvar'
  154. elif fr.kind in ('obj', 'elem') and nxt == '=':
  155. role = 'key'
  156. elif nxt in ('=', '++', '--', '+=', '-=', '*=', '/=') or prev in ('++', '--'):
  157. role = 'assign'
  158. elif nxt == '[' and k + 3 < len(toks) and toks[k + 2][1] == ']' and toks[k + 3][1] == '=':
  159. role = 'append'
  160. else:
  161. role = 'read'
  162. occ.setdefault(text, []).append((k, role))
  163. # file-root members: written at the root (outside every function), static, imported, root methods
  164. if fr.func() is root and role in ('let', 'assign'):
  165. roots.add(text)
  166. if prev == 'static' or prev == 'import':
  167. roots.add(text)
  168. if nxt == '(' and fr is root and prev not in ('new',):
  169. c = match.get(k + 1)
  170. if c is not None and c + 1 < len(toks) and toks[c + 1][1] == '{':
  171. roots.add(text)
  172. # a component's `parent '<file>'`: the parent's members are this one's too (main.hl's header members in every page)
  173. for k, (kind, text, _) in enumerate(toks):
  174. if text == 'parent' and kind == 'id' and k + 1 < len(toks) and toks[k + 1][0] == 'str' and frame_of[k] is root:
  175. ppath = os.path.normpath(os.path.join(os.path.dirname(path), toks[k + 1][1][1:-1]))
  176. if os.path.exists(ppath):
  177. roots |= rootsOf(ppath)
  178. # imports `import { a, b } from` / `import X from`
  179. for k, (kind, text, _) in enumerate(toks):
  180. if text == 'import' and k + 1 < len(toks):
  181. j = k + 1
  182. if toks[j][1] == '{':
  183. while toks[j][1] != '}':
  184. if toks[j][0] == 'id':
  185. roots.add(toks[j][1])
  186. j += 1
  187. elif toks[j][0] == 'id':
  188. roots.add(toks[j][1])
  189. if want_roots:
  190. return roots
  191. def inside(k, f):
  192. return f.start < k < f.end if f.kind != 'root' else True
  193. def chain(f):
  194. out = []
  195. while f is not None:
  196. out.append(f)
  197. f = f.parent
  198. return out
  199. def declares(g, name):
  200. # does function g itself bind `name` (param, let, or a plain write at its own level that is not a root member)?
  201. if name in g.params:
  202. return True
  203. for (k, role) in occ.get(name, []):
  204. if role in ('let', 'assign', 'forvar') and frame_of[k].func() is g:
  205. return True
  206. return False
  207. results = []
  208. for k, (kind, text, start) in enumerate(toks):
  209. if text != 'let' or kind != 'id':
  210. continue
  211. if k + 2 >= len(toks) or toks[k + 1][0] != 'id' or toks[k + 2][1] != '=':
  212. results.append((k, toks[k + 1][1] if k + 1 < len(toks) else '?', 'form'))
  213. continue
  214. name = toks[k + 1][1]
  215. fr = frame_of[k]
  216. F = fr.func()
  217. if paren_kind[k] == 'forhead':
  218. results.append((k, name, 'loop'))
  219. continue
  220. # loop between the let and its function?
  221. g, loop = fr, False
  222. while g is not F:
  223. if g.kind == 'loop':
  224. loop = True
  225. g = g.parent
  226. others = [(j, r) for (j, r) in occ[name] if j != k + 1 and inside(j, F)]
  227. reassigned = any(r in ('assign', 'append', 'let', 'forvar') for (j, r) in others)
  228. others = [(j, r) for (j, r) in others if r not in ('key', 'param')]
  229. if F is root:
  230. elsewhere = [(j, r) for (j, r) in occ[name] if j != k + 1 and r in ('assign', 'append', 'let', 'forvar')]
  231. if loop:
  232. results.append((k, name, 'loop'))
  233. elif elsewhere or is_component:
  234. results.append((k, name, 'reassigned' if elsewhere else 'root'))
  235. else:
  236. results.append((k, name, 'ok'))
  237. continue
  238. if reassigned:
  239. results.append((k, name, 'reassigned'))
  240. continue
  241. if loop:
  242. results.append((k, name, 'loop'))
  243. continue
  244. # shadow: a member/import, an implicit member, a param of F or an enclosing function, a name an enclosing function binds,
  245. # a nested function's parameter of the same name, or a FREE read anywhere outside F
  246. bad = name in roots or name in IMPLICIT or name in F.params
  247. for g in chain(F.parent):
  248. if g.kind == 'func' and declares(g, name):
  249. bad = True
  250. for f2 in frames:
  251. if f2.kind == 'func' and f2 is not F and inside(f2.start, F) and name in f2.params:
  252. bad = True
  253. if not bad:
  254. for (j, r) in occ[name]:
  255. if inside(j, F) or r in ('key', 'param'):
  256. continue
  257. if not any(g.kind == 'func' and declares(g, name) for g in chain(frame_of[j].func())):
  258. bad = True
  259. break
  260. if bad:
  261. results.append((k, name, 'shadow'))
  262. continue
  263. # block: every use inside the declaration's own block, after it
  264. blk = fr
  265. if any(not (j > k and (blk is F or inside(j, blk))) for (j, r) in others):
  266. results.append((k, name, 'block'))
  267. continue
  268. results.append((k, name, 'ok'))
  269. return src, toks, results
  270. def main():
  271. args = sys.argv[1:]
  272. fix = '--fix' in args
  273. lst = '--list' in args
  274. files = [a for a in args if not a.startswith('--')]
  275. total = {}
  276. for path in files:
  277. is_component = '/components/' in '/' + path
  278. src, toks, results = analyse(path, is_component)
  279. counts = {}
  280. for (k, name, why) in results:
  281. counts[why] = counts.get(why, 0) + 1
  282. total[why] = total.get(why, 0) + 1
  283. if lst and why != 'ok':
  284. line = src.count('\n', 0, toks[k][2]) + 1
  285. print(f'{path}:{line}: keep let {name} ({why})')
  286. n = len(results)
  287. print(f'{path}: let={n} ' + ' '.join(f'{w}={c}' for w, c in sorted(counts.items())))
  288. if fix:
  289. out = src
  290. for (k, name, why) in sorted(results, key=lambda r: -toks[r[0]][2]):
  291. if why == 'ok':
  292. s = toks[k][2]
  293. e = toks[k + 1][2]
  294. out = out[:s] + out[e:]
  295. if out != src:
  296. open(path, 'w', encoding='utf-8').write(out)
  297. n = sum(total.values())
  298. print(f'TOTAL let={n} ' + ' '.join(f'{w}={c}' for w, c in sorted(total.items())))
  299. if __name__ == '__main__':
  300. main()

Branches

Latest commits

  • 8f1d4542tracker#40: superseded collections — a TMDB collection timeline whose titles are all in one curated timeline is hidden (supersededBy; kept: own page + editor finder), set by the collection seed when it makes one and by the curated build (lifted when the cover is gone); partly covered ones join that franchise; no second widget (First Contact: only Star Trek — Prime); gate franchiseseed 26/0, browser 365/0, kinds 32/0, franchises 53/0, check-theme 0; real copy 24 supersededmre
  • 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