@typeroll/mcp-server 0.45.168 → 0.45.170
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +2 -1
- package/dist/bundled-content.js +26 -13
- package/dist/server.js +4 -0
- package/dist/tools/apps.js +33 -0
- package/dist/tools/fonts.js +1 -1
- package/dist/tools/forms.js +4 -3
- package/dist/tools/media.js +2 -2
- package/dist/tools/migration.js +1 -1
- package/dist/tools/pages.js +4 -0
- package/dist/tools/preview.js +4 -0
- package/dist/tools/settings.js +1 -1
- package/dist/tools/styles.js +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/workspace.d.ts +1 -1
- package/dist/workspace.js +17 -8
- package/package.json +1 -1
- package/skills/tr-brand.md +1 -1
- package/skills/tr-migrate-astro.md +4 -13
- package/skills/tr-migrate-multisite.md +10 -31
- package/skills/tr-migrate-wp.md +73 -384
- package/skills/tr-responsive.md +14 -0
- package/workspace-templates/scripts/README.md +18 -0
- package/workspace-templates/scripts/typeroll/browser.cjs +6 -1
- package/workspace-templates/scripts/typeroll/call.py +5 -2
- package/workspace-templates/scripts/typeroll/css_report.py +45 -0
- package/workspace-templates/scripts/typeroll/inventory.py +264 -0
- package/workspace-templates/scripts/typeroll/media_fit.py +112 -0
- package/workspace-templates/scripts/typeroll/migration.py +254 -0
- package/workspace-templates/scripts/typeroll/page_part.cjs +34 -0
- package/workspace-templates/scripts/typeroll/page_source.py +148 -0
- package/workspace-templates/scripts/typeroll/pages.py +156 -0
- package/workspace-templates/scripts/typeroll/read_pages.cjs +169 -0
- package/workspace-templates/scripts/typeroll/shoot_hosted.cjs +13 -6
- package/workspace-templates/scripts/typeroll/trlib.py +45 -7
- package/workspace-templates/scripts/typeroll/verify_migration.cjs +47 -0
- package/workspace-templates/scripts/typeroll/verify_migration.py +274 -0
- package/workspace-templates/scripts/typeroll/write_pages.py +542 -0
- package/workspace-templates/skills/typeroll-migrate-sources.md +36 -0
- package/workspace-templates/skills/typeroll-migrate.md +109 -0
- package/workspace-templates/workflows/design.md +1 -1
- package/workspace-templates/workflows/migration.md +12 -5
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""Migration steps and their saved results. Read-only towards the CMS.
|
|
2
|
+
|
|
3
|
+
migration.py status what is done and what comes next
|
|
4
|
+
migration.py approve model "NAME" record the owner's approval of the content model
|
|
5
|
+
migration.py approve prototype "NAME" record the owner's approval of the prototype pages
|
|
6
|
+
migration.py handover read the launch report and write the last result
|
|
7
|
+
|
|
8
|
+
Every step saves qa/migration/<step>.json. A step refuses to start until the
|
|
9
|
+
step before it has a result that passed, and an approval is void when what was
|
|
10
|
+
approved changes. Page text and HTML stay in the ignored sources/private/.
|
|
11
|
+
"""
|
|
12
|
+
import argparse
|
|
13
|
+
import datetime
|
|
14
|
+
import hashlib
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
import tempfile
|
|
19
|
+
|
|
20
|
+
STEPS = ('inventory', 'model', 'prototype', 'import', 'compare', 'handover')
|
|
21
|
+
APPROVED = ('model', 'prototype')
|
|
22
|
+
NEXT = {
|
|
23
|
+
'inventory': 'python3 scripts/typeroll/inventory.py https://old-site.example',
|
|
24
|
+
'model': 'python3 scripts/typeroll/pages.py next until every page has an answer (pages.py start makes the worksheet once), then: migration.py approve model "OWNER"',
|
|
25
|
+
'prototype': 'make one page of every kind, python3 scripts/typeroll/write_pages.py prototype PATH ... --apply, let the owner see it, then: migration.py approve prototype "OWNER"',
|
|
26
|
+
'import': 'make the other pages, then: python3 scripts/typeroll/write_pages.py all --apply',
|
|
27
|
+
'compare': 'look at every new page (pages.py checked), then: python3 scripts/typeroll/verify_migration.py https://test-address.example',
|
|
28
|
+
'handover': 'python3 scripts/typeroll/migration.py handover',
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class StepError(RuntimeError):
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def root():
|
|
37
|
+
for directory in (Path.cwd(), *Path.cwd().parents):
|
|
38
|
+
if (directory / 'typeroll.json').is_file():
|
|
39
|
+
return directory
|
|
40
|
+
raise StepError('Run from a workspace containing typeroll.json')
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def folder():
|
|
44
|
+
return root() / 'qa' / 'migration'
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def private():
|
|
48
|
+
return root() / 'sources' / 'private' / 'migration'
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def write_json(path, value):
|
|
52
|
+
"""Whole file or nothing: an interrupted run never leaves half a result."""
|
|
53
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
54
|
+
handle, name = tempfile.mkstemp(dir=path.parent, prefix='.' + path.name)
|
|
55
|
+
with os.fdopen(handle, 'w', encoding='utf8') as file:
|
|
56
|
+
json.dump(value, file, ensure_ascii=False, indent=2, sort_keys=True)
|
|
57
|
+
file.write('\n')
|
|
58
|
+
os.replace(name, path)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def read_json(path, default=None):
|
|
62
|
+
if not path.is_file():
|
|
63
|
+
return default
|
|
64
|
+
try:
|
|
65
|
+
return json.loads(path.read_text('utf8'))
|
|
66
|
+
except ValueError:
|
|
67
|
+
raise StepError(f'{path.name} is not valid JSON; restore it before continuing') from None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def digest(value):
|
|
71
|
+
return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True).encode()).hexdigest()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def result(step):
|
|
75
|
+
return read_json(folder() / f'{step}.json')
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def save(step, ok, **data):
|
|
79
|
+
"""Save a step's result, tied to the results of the steps it was built on."""
|
|
80
|
+
before = STEPS[:STEPS.index(step)]
|
|
81
|
+
write_json(folder() / f'{step}.json', {
|
|
82
|
+
'step': step, 'ok': bool(ok), 'finished_at': datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds'),
|
|
83
|
+
'built_on': {name: subject(name) for name in before if result(name)}, **data})
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def subject(step):
|
|
87
|
+
"""What a later step depends on. A new date alone changes nothing."""
|
|
88
|
+
value = result(step) or {}
|
|
89
|
+
return digest({key: item for key, item in value.items() if key not in ('finished_at', 'approval', 'built_on')})
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def approval_error(step):
|
|
93
|
+
approval = (result(step) or {}).get('approval') or {}
|
|
94
|
+
if not approval.get('by'):
|
|
95
|
+
return f'The {step} is not approved by the owner yet'
|
|
96
|
+
if approval.get('subject') != subject(step):
|
|
97
|
+
return f'The {step} changed after it was approved; ask the owner again'
|
|
98
|
+
return None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def problem(step):
|
|
102
|
+
"""Why this step does not count as done, or None."""
|
|
103
|
+
value = result(step)
|
|
104
|
+
if not value:
|
|
105
|
+
return f'{step} has no saved result'
|
|
106
|
+
if not value.get('ok'):
|
|
107
|
+
return f'{step} did not pass'
|
|
108
|
+
for name, stamp in (value.get('built_on') or {}).items():
|
|
109
|
+
if stamp != subject(name):
|
|
110
|
+
return f'{step} is older than the current {name}; run it again'
|
|
111
|
+
return approval_error(step) if step in APPROVED else None
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def require(step):
|
|
115
|
+
"""Every step before this one must be done."""
|
|
116
|
+
for name in STEPS[:STEPS.index(step)]:
|
|
117
|
+
reason = problem(name)
|
|
118
|
+
if reason:
|
|
119
|
+
raise StepError(f'Not ready for {step}: {reason}. Next: {NEXT[name]}')
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def approve(step, by):
|
|
123
|
+
if step not in APPROVED:
|
|
124
|
+
raise StepError('Only the model and the prototype are approved')
|
|
125
|
+
if not by.strip():
|
|
126
|
+
raise StepError('Write the name of the owner who approved it')
|
|
127
|
+
value = result(step)
|
|
128
|
+
if not value or not value.get('ok'):
|
|
129
|
+
raise StepError(f'{step} has no result that passed yet')
|
|
130
|
+
if step == 'model':
|
|
131
|
+
problems = model_problems(value)
|
|
132
|
+
if problems:
|
|
133
|
+
raise StepError('The model cannot be approved yet: ' + '; '.join(problems))
|
|
134
|
+
# A step built on something that has changed cannot be approved either.
|
|
135
|
+
for name, stamp in (value.get('built_on') or {}).items():
|
|
136
|
+
if stamp != subject(name):
|
|
137
|
+
raise StepError(f'{step} is older than the current {name}; run it again')
|
|
138
|
+
value['approval'] = {'by': by.strip(), 'at': datetime.date.today().isoformat(), 'subject': subject(step)}
|
|
139
|
+
write_json(folder() / f'{step}.json', value)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
# Every page has these already (PAGE_BUILTIN_FIELDS in Typeroll); a content type cannot add them.
|
|
143
|
+
PAGE_FIELDS = {
|
|
144
|
+
'id', 'title', 'slug', 'path', 'parent', 'sort_order', 'template', 'content_type', 'fields', 'body', 'blocks',
|
|
145
|
+
'content_mode', 'html_content', 'status', 'breadcrumb_label', 'seo_title', 'append_seo_suffix', 'footer_spacing', 'seo_description', 'og_title', 'og_description', 'og_image',
|
|
146
|
+
'seo_image_alt', 'canonical_url', 'noindex', 'nofollow', 'alternates', 'lastmod_override', 'json_ld', 'kind', 'schema_type',
|
|
147
|
+
'service', 'author', 'language', 'image_sizes_default', 'old_wp_url', 'ai_generated', 'date_published',
|
|
148
|
+
'date_updated', 'publish_at', 'unpublish_at', 'custom_css', 'own_page',
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def model_problems(model):
|
|
153
|
+
"""What the model still lacks before the owner can be asked. Checks, no opinions about content."""
|
|
154
|
+
found, pages = [], model.get('pages') or {}
|
|
155
|
+
entries = {entry['content_type']: entry for entry in model.get('types') or []}
|
|
156
|
+
if not pages:
|
|
157
|
+
found.append('it lists no pages')
|
|
158
|
+
without = sum(1 for page in pages.values() if not page.get('type'))
|
|
159
|
+
if without:
|
|
160
|
+
found.append(f'{without} pages have no answer; run pages.py next')
|
|
161
|
+
for path, page in pages.items():
|
|
162
|
+
if page['type'] not in (None, 'page', 'skip', 'ask', *entries):
|
|
163
|
+
found.append(f"{path} has the unknown type {page['type']}")
|
|
164
|
+
if page['type'] and not page['saw'].strip():
|
|
165
|
+
found.append(f'{path} has an answer but nothing says what was seen')
|
|
166
|
+
if page['type'] == 'ask':
|
|
167
|
+
found.append(f"ask the owner about {path}: {page['saw']}, then note their answer")
|
|
168
|
+
if page['type'] == 'skip' and not page.get('to'):
|
|
169
|
+
found.append(f'{path} is skipped without saying where its address goes; note it again with --to')
|
|
170
|
+
for name, entry in entries.items():
|
|
171
|
+
own = [page for page in pages.values() if page['type'] == name]
|
|
172
|
+
fields = [field.get('name') for field in entry.get('fields') or []]
|
|
173
|
+
if len(fields) != len(set(fields)):
|
|
174
|
+
found.append(f'{name} has two fields with one name')
|
|
175
|
+
found += [f'{name}: {field} is already a field of every page; remove it, or use another name' for field in fields if field in PAGE_FIELDS]
|
|
176
|
+
if own and entry.get('own_pages', True):
|
|
177
|
+
if len(own) >= 3 and not entry.get('template') and not str(entry.get('why') or '').strip():
|
|
178
|
+
found.append(f'{name} has {len(own)} pages and no template; add one, or write why')
|
|
179
|
+
if not entry.get('route_template'):
|
|
180
|
+
found.append(f'{name} has no route_template; set one, or own_pages to false for records without pages')
|
|
181
|
+
found += [f"{name}: {field['name']} points at records, so it needs ref_content_type" for field in entry.get('fields') or []
|
|
182
|
+
if field.get('type') in ('page_ref', 'page_ref_list') and field.get('ref_content_type') not in entries]
|
|
183
|
+
return found
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def status():
|
|
187
|
+
rows = []
|
|
188
|
+
for step in STEPS:
|
|
189
|
+
reason = problem(step)
|
|
190
|
+
rows.append({'step': step, 'done': reason is None, **({'why': reason, 'next': NEXT[step]} if reason else {})})
|
|
191
|
+
if reason:
|
|
192
|
+
break
|
|
193
|
+
return rows
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def version_warning():
|
|
197
|
+
"""Say so when these files are older than the Typeroll they talk to."""
|
|
198
|
+
import trlib
|
|
199
|
+
ours = (read_json(root() / 'typeroll.lock.json') or {}).get('generator_version')
|
|
200
|
+
if not os.environ.get('TYPEROLL_API_KEY'):
|
|
201
|
+
return 'Versions were not compared: TYPEROLL_API_KEY is not set'
|
|
202
|
+
theirs = trlib.server_version()
|
|
203
|
+
number = lambda value: [int(part) for part in str(value).split('.')[:3] if part.isdigit()]
|
|
204
|
+
if ours and theirs and number(ours) < number(theirs):
|
|
205
|
+
return f'These files are from {ours}, Typeroll is {theirs}. Run: npx @typeroll/mcp-server@{theirs} init . --update'
|
|
206
|
+
return None if ours and theirs else 'The version of these files or of Typeroll is unknown'
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def handover():
|
|
210
|
+
import trlib
|
|
211
|
+
require('handover')
|
|
212
|
+
report = trlib.call('get_migration_launch_report')
|
|
213
|
+
imported, compared = result('import'), result('compare')
|
|
214
|
+
failed_media = imported.get('failed_media') or []
|
|
215
|
+
ok = bool(report.get('launch_ready')) and not failed_media
|
|
216
|
+
save('handover', ok, launch_ready=bool(report.get('launch_ready')), issues=report.get('issues') or [],
|
|
217
|
+
warnings=report.get('warnings') or [], pages=imported.get('counts') or {}, failed_media=failed_media,
|
|
218
|
+
compare=compared.get('summary') or {})
|
|
219
|
+
lines = ['# Handover', '', f"Launch ready: {'yes' if ok else 'no'}", '', '## Stops launch', '',
|
|
220
|
+
*([f"- {item['id']}: {item['detail']}" for item in report.get('issues') or []] or ['- nothing']),
|
|
221
|
+
*[f'- media not copied: {url}' for url in failed_media], '', '## Worth fixing', '',
|
|
222
|
+
*([f"- {item['id']}: {item['detail']}" for item in report.get('warnings') or []] or ['- nothing']), '',
|
|
223
|
+
'This report publishes nothing and changes no DNS. Both need the owner\'s approval.', '']
|
|
224
|
+
(folder() / 'handover.md').write_text('\n'.join(lines), 'utf8')
|
|
225
|
+
return ok
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def main():
|
|
229
|
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
230
|
+
commands = parser.add_subparsers(dest='command', required=True)
|
|
231
|
+
commands.add_parser('status')
|
|
232
|
+
commands.add_parser('handover')
|
|
233
|
+
approval = commands.add_parser('approve')
|
|
234
|
+
approval.add_argument('step', choices=APPROVED)
|
|
235
|
+
approval.add_argument('by')
|
|
236
|
+
args = parser.parse_args()
|
|
237
|
+
if args.command == 'approve':
|
|
238
|
+
approve(args.step, args.by)
|
|
239
|
+
if args.command == 'handover':
|
|
240
|
+
ok = handover()
|
|
241
|
+
print('See qa/migration/handover.md')
|
|
242
|
+
return 0 if ok else 1
|
|
243
|
+
print(json.dumps(status(), ensure_ascii=False, indent=2))
|
|
244
|
+
warning = version_warning() if args.command == 'status' else None
|
|
245
|
+
if warning:
|
|
246
|
+
print(warning)
|
|
247
|
+
return 0
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
if __name__ == '__main__':
|
|
251
|
+
try:
|
|
252
|
+
raise SystemExit(main())
|
|
253
|
+
except StepError as error:
|
|
254
|
+
raise SystemExit(str(error))
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Hand out exact parts of saved pages. Somebody else chose the parts; no network.
|
|
2
|
+
// Usage: node page_part.cjs PLAN.json ({folder, result, pages:[{key, parts:[selector]}]})
|
|
3
|
+
const qa = require('./browser.cjs');
|
|
4
|
+
const fs = require('node:fs/promises');
|
|
5
|
+
const path = require('node:path');
|
|
6
|
+
|
|
7
|
+
function part(selector) {
|
|
8
|
+
for (const el of document.querySelectorAll('[data-tr-hidden]')) el.hidden = true;
|
|
9
|
+
let hits;
|
|
10
|
+
try { hits = [...document.querySelectorAll(selector)]; } catch { return { error: 'is not a selector' }; }
|
|
11
|
+
if (hits.length !== 1) return { error: `fits ${hits.length} places; it must fit one` };
|
|
12
|
+
const el = hits[0], image = el.matches('img') ? el : el.querySelector('img'), link = el.matches('a[href]') ? el : el.querySelector('a[href]');
|
|
13
|
+
return { html: el.innerHTML, text: el.innerText.replace(/[ \t]+/g, ' ').replace(/ *\n */g, '\n').trim(),
|
|
14
|
+
image: image?.getAttribute('src') || el.getAttribute('data-tr-bg') || '', alt: image?.getAttribute('alt') || '', link: link?.getAttribute('href') || '' };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
async function main() {
|
|
18
|
+
const plan = JSON.parse(await fs.readFile(process.argv[2], 'utf8'));
|
|
19
|
+
const browser = await qa.chromium.launch(), result = {};
|
|
20
|
+
try {
|
|
21
|
+
const context = await browser.newContext({ serviceWorkers: 'block', javaScriptEnabled: false });
|
|
22
|
+
await context.route('**/*', route => route.abort());
|
|
23
|
+
const page = await context.newPage();
|
|
24
|
+
for (const item of plan.pages) {
|
|
25
|
+
const saved = JSON.parse(await fs.readFile(path.join(plan.folder, `${item.key}.json`), 'utf8'));
|
|
26
|
+
await page.setContent(`<!doctype html><body>${saved.html}</body>`, { waitUntil: 'domcontentloaded' });
|
|
27
|
+
result[item.key] = {};
|
|
28
|
+
for (const selector of item.parts) result[item.key][selector] = await page.evaluate(part, selector);
|
|
29
|
+
}
|
|
30
|
+
} finally { await browser.close(); }
|
|
31
|
+
await fs.writeFile(plan.result, JSON.stringify(result));
|
|
32
|
+
}
|
|
33
|
+
if (require.main === module) main().catch(qa.fail);
|
|
34
|
+
module.exports = { part };
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""A saved page of the old site, for the agent that moves it.
|
|
2
|
+
|
|
3
|
+
page_source.py PATH pictures, texts in order, links and videos
|
|
4
|
+
page_source.py PATH "SELECTOR" one part exactly: its text and clean HTML
|
|
5
|
+
|
|
6
|
+
The selector of a text is printed after it. It can be used in a page file
|
|
7
|
+
({"copy": "SELECTOR"}), so that long text is copied and never typed again.
|
|
8
|
+
"""
|
|
9
|
+
import argparse
|
|
10
|
+
import html
|
|
11
|
+
from html.parser import HTMLParser
|
|
12
|
+
import json
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
import re
|
|
15
|
+
import subprocess
|
|
16
|
+
import migration
|
|
17
|
+
from inventory import page_key, seen
|
|
18
|
+
|
|
19
|
+
KEEP = {'p', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'blockquote', 'strong', 'em', 'a', 'br', 'hr', 'sup', 'sub', 'u', 's',
|
|
20
|
+
'code', 'pre', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th', 'caption'}
|
|
21
|
+
RENAME = {'b': 'strong', 'i': 'em', 'h1': 'h2', 'del': 's', 'strike': 's'}
|
|
22
|
+
# Says nothing about the text; its content is kept.
|
|
23
|
+
WRAPPERS = {'div', 'section', 'article', 'span', 'main', 'font', 'center', 'small', 'mark', 'time', 'abbr', 'cite', 'q'}
|
|
24
|
+
VOID = {'br', 'hr', 'img', 'source', 'wbr', 'input'}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Clean(HTMLParser):
|
|
28
|
+
"""Running text without classes and scripts. Anything else is named and refused, never dropped."""
|
|
29
|
+
|
|
30
|
+
def __init__(self, link):
|
|
31
|
+
super().__init__(convert_charrefs=True)
|
|
32
|
+
self.link, self.out, self.other, self.hidden = link, [], set(), 0
|
|
33
|
+
|
|
34
|
+
def handle_starttag(self, tag, attrs):
|
|
35
|
+
data = {key: value or '' for key, value in attrs}
|
|
36
|
+
if self.hidden or 'data-tr-hidden' in data:
|
|
37
|
+
self.hidden += tag not in VOID
|
|
38
|
+
return
|
|
39
|
+
tag = RENAME.get(tag, tag)
|
|
40
|
+
if 'data-tr-bg' in data or 'data-tr-video' in data:
|
|
41
|
+
self.other.add('a background picture' if 'data-tr-bg' in data else 'a video')
|
|
42
|
+
if tag in KEEP:
|
|
43
|
+
extra = ''
|
|
44
|
+
if tag == 'a' and data.get('href'):
|
|
45
|
+
extra = f' href="{html.escape(self.link(data["href"]), quote=True)}"' + (' target="_blank" rel="noopener"' if data.get('target') == '_blank' else '')
|
|
46
|
+
if tag in ('td', 'th'):
|
|
47
|
+
extra = ''.join(f' {key}="{int(data[key])}"' for key in ('colspan', 'rowspan') if data.get(key, '').isdigit())
|
|
48
|
+
self.out.append(f'<{tag}{extra}>')
|
|
49
|
+
elif tag == 'wbr':
|
|
50
|
+
return
|
|
51
|
+
elif tag not in WRAPPERS:
|
|
52
|
+
self.other.add(f'<{tag}>')
|
|
53
|
+
elif tag != 'span':
|
|
54
|
+
self.out.append(' ')
|
|
55
|
+
|
|
56
|
+
def handle_endtag(self, tag):
|
|
57
|
+
if self.hidden:
|
|
58
|
+
self.hidden -= tag not in VOID
|
|
59
|
+
return
|
|
60
|
+
tag = RENAME.get(tag, tag)
|
|
61
|
+
if tag in KEEP and tag not in VOID:
|
|
62
|
+
self.out.append(f'</{tag}>')
|
|
63
|
+
|
|
64
|
+
def handle_data(self, text):
|
|
65
|
+
if not self.hidden:
|
|
66
|
+
self.out.append(html.escape(re.sub(r'[ \t\r\n]+', ' ', text), quote=False))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def clean(source, link=lambda url: url):
|
|
70
|
+
"""(html, what is in it besides running text)"""
|
|
71
|
+
parser = Clean(link)
|
|
72
|
+
parser.feed(source)
|
|
73
|
+
parser.close()
|
|
74
|
+
text = re.sub(r'<p>(?:\s|\xa0|<br>)*</p>', '', re.sub(r' {2,}', ' ', ''.join(parser.out))).strip()
|
|
75
|
+
if text and not re.match(r'<(?:p|h[2-6]|ul|ol|blockquote|pre|table|hr)\b', text):
|
|
76
|
+
text = f'<p>{text}</p>'
|
|
77
|
+
return text, sorted(parser.other)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def parts(wanted):
|
|
81
|
+
"""{url: {selector: part}} for {url: selectors}."""
|
|
82
|
+
work = [{'key': page_key(url), 'parts': sorted(selectors)} for url, selectors in wanted.items() if selectors]
|
|
83
|
+
if not work:
|
|
84
|
+
return {}
|
|
85
|
+
plan, answer = migration.private() / 'part-plan.json', migration.private() / 'parts.json'
|
|
86
|
+
answer.unlink(missing_ok=True)
|
|
87
|
+
migration.write_json(plan, {'folder': str(migration.private() / 'pages'), 'result': str(answer), 'pages': work})
|
|
88
|
+
run = subprocess.run(['node', str(Path(__file__).with_name('page_part.cjs')), str(plan)], check=False)
|
|
89
|
+
found = migration.read_json(answer)
|
|
90
|
+
if run.returncode or found is None:
|
|
91
|
+
raise migration.StepError('The saved pages could not be opened. Install Playwright (scripts/README.md) and run again')
|
|
92
|
+
return {url: found.get(page_key(url), {}) for url in wanted}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def url_of(path):
|
|
96
|
+
row = next((row for row in (migration.result('inventory') or {}).get('urls', []) if row['path'] == path and row.get('read')), None)
|
|
97
|
+
if not row:
|
|
98
|
+
raise migration.StepError(f'{path} is not a page of the inventory')
|
|
99
|
+
return row['url']
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def pictures(full):
|
|
103
|
+
folder = migration.private() / 'screens'
|
|
104
|
+
return [str((folder / name).relative_to(migration.root())) for name in full.get('screens') or [] if (folder / name).is_file()]
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def describe(path):
|
|
108
|
+
full = seen(url_of(path))
|
|
109
|
+
def field(entry):
|
|
110
|
+
if isinstance(entry, str): # pages read by an older version
|
|
111
|
+
return entry
|
|
112
|
+
return f"{entry.get('label') or entry['name']} ({entry['type']}{', required' if entry.get('required') else ''}" + \
|
|
113
|
+
(f": {' | '.join(entry['choices'])}" if entry.get('choices') else '') + ')'
|
|
114
|
+
|
|
115
|
+
def line(item):
|
|
116
|
+
shown = item.get('text') or item.get('alt') or item.get('src') or '; '.join(field(entry) for entry in item.get('fields') or [])
|
|
117
|
+
if item['kind'] == 'image' and item.get('alt'):
|
|
118
|
+
shown += f" ({item['src']})"
|
|
119
|
+
extra = (f" -> {item['href']}" if item.get('href') else '') + (f"; choices: {' | '.join(item['choices'])}" if item.get('choices') else '')
|
|
120
|
+
links = ''.join(f"\n {link}" for link in item.get('links') or [])
|
|
121
|
+
return f"{item['kind']}: {shown}{extra} [{item['at']}]{links}"
|
|
122
|
+
lines = [line(item) for item in full['outline']]
|
|
123
|
+
return {'path': path, 'url': full['url'], 'look_at': pictures(full), 'title': full['title'], 'description': full['description'], 'share_image': full['share_image'],
|
|
124
|
+
'published': full['published'], 'noindex': full['noindex'], 'videos': full['videos'], 'shows': lines}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def main():
|
|
128
|
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
129
|
+
parser.add_argument('path')
|
|
130
|
+
parser.add_argument('selector', nargs='?')
|
|
131
|
+
args = parser.parse_args()
|
|
132
|
+
if not args.selector:
|
|
133
|
+
print(json.dumps(describe(args.path), ensure_ascii=False, indent=2))
|
|
134
|
+
return 0
|
|
135
|
+
url = url_of(args.path)
|
|
136
|
+
found = parts({url: {args.selector}})[url][args.selector]
|
|
137
|
+
if found.get('error'):
|
|
138
|
+
raise migration.StepError(f'The selector {found["error"]}')
|
|
139
|
+
text, other = clean(found['html'])
|
|
140
|
+
print(json.dumps({'text': found['text'], 'html': text, 'also_holds': other, 'image': found['image'], 'alt': found['alt'], 'link': found['link']}, ensure_ascii=False, indent=2))
|
|
141
|
+
return 0
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
if __name__ == '__main__':
|
|
145
|
+
try:
|
|
146
|
+
raise SystemExit(main())
|
|
147
|
+
except migration.StepError as error:
|
|
148
|
+
raise SystemExit(str(error))
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""The migrating agent's worksheet: one line of judgement for every page.
|
|
2
|
+
|
|
3
|
+
pages.py start make the worksheet from the inventory
|
|
4
|
+
pages.py next a page without an answer, with its pictures
|
|
5
|
+
pages.py note PATH TYPE "what you saw" your answer [--template ID] [--to PATH|gone]
|
|
6
|
+
pages.py type NAME "Singular" "Plural" add a content type [--no-pages]
|
|
7
|
+
pages.py checked PATH "what you compared" after you looked at the new page
|
|
8
|
+
pages.py left what is not done yet
|
|
9
|
+
|
|
10
|
+
TYPE is a content type you added, "page" (one of a kind), "skip" (not moved:
|
|
11
|
+
say why, and where its address goes with --to /new/path/ or --to gone) or
|
|
12
|
+
"ask" (only the owner can decide: write the question). A record without its
|
|
13
|
+
own page also needs --to. The script proposes nothing. Open the pictures and
|
|
14
|
+
decide. Answers are saved in qa/migration/model.json.
|
|
15
|
+
"""
|
|
16
|
+
import argparse
|
|
17
|
+
import json
|
|
18
|
+
import migration
|
|
19
|
+
import page_source
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def load():
|
|
23
|
+
model = migration.result('model')
|
|
24
|
+
if not model:
|
|
25
|
+
raise migration.StepError('No worksheet yet. Run pages.py start')
|
|
26
|
+
return model
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def store(model):
|
|
30
|
+
migration.write_json(migration.folder() / 'model.json', model)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def start():
|
|
34
|
+
migration.require('model')
|
|
35
|
+
old = migration.result('model') or {}
|
|
36
|
+
pages = {row['path']: (old.get('pages') or {}).get(row['path']) or {'type': None, 'template': None, 'saw': ''}
|
|
37
|
+
for row in migration.result('inventory')['urls'] if row.get('read')}
|
|
38
|
+
# Answers are kept when the inventory is read again.
|
|
39
|
+
migration.save('model', True, types=old.get('types') or [], pages=pages)
|
|
40
|
+
return len(pages)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def open_pages(model):
|
|
44
|
+
return sorted(path for path, page in model['pages'].items() if not page['type'])
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def following(model):
|
|
48
|
+
left = open_pages(model)
|
|
49
|
+
return {**page_source.describe(left[0]), 'left': len(left)} if left else None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def note(model, path, value, saw, template='', to=''):
|
|
53
|
+
names = [entry['content_type'] for entry in model['types']]
|
|
54
|
+
if value not in ('page', 'skip', 'ask', *names):
|
|
55
|
+
raise migration.StepError(f'{value} is not a content type yet. Add it first: pages.py type {value} "Singular" "Plural"')
|
|
56
|
+
if path not in model['pages']:
|
|
57
|
+
raise migration.StepError(f'{path} is not a page of the inventory')
|
|
58
|
+
if len(saw.split()) < 3:
|
|
59
|
+
raise migration.StepError('Say in a few words what the page shows, or why it is not moved')
|
|
60
|
+
without_page = value == 'skip' or any(entry['content_type'] == value and not entry.get('own_pages', True) for entry in model['types'])
|
|
61
|
+
if without_page and not to:
|
|
62
|
+
raise migration.StepError('Say where the old address goes: --to /new/path/, or --to gone if nothing replaces it')
|
|
63
|
+
if to and to != 'gone' and not (to.startswith('/') and to.endswith('/')):
|
|
64
|
+
raise migration.StepError('--to takes an address on the new site such as /kontakt/, or gone')
|
|
65
|
+
entry = model['pages'][path]
|
|
66
|
+
entry.update(type=value, saw=saw.strip(), template=template or None)
|
|
67
|
+
# Only a real target is stored, so noting a page again with the same answer leaves the approved model as it was.
|
|
68
|
+
if to:
|
|
69
|
+
entry['to'] = to
|
|
70
|
+
else:
|
|
71
|
+
entry.pop('to', None)
|
|
72
|
+
store(model)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def add_type(model, name, singular, plural, own_pages=True):
|
|
76
|
+
if name in ('page', 'skip', 'ask', *(entry['content_type'] for entry in model['types'])):
|
|
77
|
+
raise migration.StepError(f'{name} exists already')
|
|
78
|
+
model['types'].append({'content_type': name, 'label_singular': singular, 'label_plural': plural, 'own_pages': own_pages,
|
|
79
|
+
'route_template': f'/{name.replace("_", "-")}/{{slug}}/' if own_pages else '', 'template': name if own_pages else None, 'why': '', 'fields': []})
|
|
80
|
+
store(model)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def check(path, compared):
|
|
84
|
+
"""The agent's own look at the new page. Void when the page file changes."""
|
|
85
|
+
import write_pages
|
|
86
|
+
file = write_pages.file_of(path)
|
|
87
|
+
if file is None:
|
|
88
|
+
raise migration.StepError(f'{path} has no page file yet')
|
|
89
|
+
if len(compared.split()) < 3:
|
|
90
|
+
raise migration.StepError('Say in a few words what you compared and what you found')
|
|
91
|
+
checked = migration.read_json(migration.folder() / 'checked.json', {})
|
|
92
|
+
checked[path] = {'compared': compared.strip(), 'page': migration.digest(file)}
|
|
93
|
+
migration.write_json(migration.folder() / 'checked.json', checked)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def left(model):
|
|
97
|
+
import write_pages
|
|
98
|
+
files, checked = write_pages.files(), migration.read_json(migration.folder() / 'checked.json', {})
|
|
99
|
+
moved = [path for path, page in sorted(model['pages'].items()) if page['type'] not in (None, 'skip', 'ask')]
|
|
100
|
+
return {'without_answer': open_pages(model), 'for_the_owner': {path: page['saw'] for path, page in sorted(model['pages'].items()) if page['type'] == 'ask'},
|
|
101
|
+
'without_page_file': [path for path in moved if path not in files],
|
|
102
|
+
'not_checked': [path for path in moved if path in files and (checked.get(path) or {}).get('page') != migration.digest(files[path])]}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def main():
|
|
106
|
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
107
|
+
commands = parser.add_subparsers(dest='command', required=True)
|
|
108
|
+
for name in ('start', 'next', 'left'):
|
|
109
|
+
commands.add_parser(name)
|
|
110
|
+
one = commands.add_parser('note')
|
|
111
|
+
for name in ('path', 'type', 'saw'):
|
|
112
|
+
one.add_argument(name)
|
|
113
|
+
one.add_argument('--template', default='')
|
|
114
|
+
one.add_argument('--to', default='', help='Where the old address goes when the page is skipped: /new/path/ or gone')
|
|
115
|
+
one = commands.add_parser('type')
|
|
116
|
+
for name in ('name', 'singular', 'plural'):
|
|
117
|
+
one.add_argument(name)
|
|
118
|
+
one.add_argument('--no-pages', action='store_true', help='Records that are only shown in lists')
|
|
119
|
+
one = commands.add_parser('checked')
|
|
120
|
+
one.add_argument('path')
|
|
121
|
+
one.add_argument('compared')
|
|
122
|
+
args = parser.parse_args()
|
|
123
|
+
if args.command == 'start':
|
|
124
|
+
print(f'{start()} pages to look at. Next: pages.py next')
|
|
125
|
+
return 0
|
|
126
|
+
model = load()
|
|
127
|
+
if args.command == 'note':
|
|
128
|
+
note(model, args.path, args.type, args.saw, args.template, args.to)
|
|
129
|
+
print(f'{len(open_pages(model))} pages left')
|
|
130
|
+
elif args.command == 'type':
|
|
131
|
+
add_type(model, args.name, args.singular, args.plural, not args.no_pages)
|
|
132
|
+
print('Set its fields, route_template and template in qa/migration/model.json')
|
|
133
|
+
elif args.command == 'checked':
|
|
134
|
+
check(args.path, args.compared)
|
|
135
|
+
elif args.command == 'left':
|
|
136
|
+
print(json.dumps(left(model), ensure_ascii=False, indent=2))
|
|
137
|
+
else:
|
|
138
|
+
item = following(model)
|
|
139
|
+
if item:
|
|
140
|
+
print(json.dumps(item, ensure_ascii=False, indent=2))
|
|
141
|
+
return 0
|
|
142
|
+
problems = migration.model_problems(model)
|
|
143
|
+
print('Every page has an answer.')
|
|
144
|
+
if problems:
|
|
145
|
+
print('Fix these before the owner is asked:\n- ' + '\n- '.join(problems))
|
|
146
|
+
else:
|
|
147
|
+
print('Next: show the owner the types, the pages of each and your questions (pages.py left), '
|
|
148
|
+
'then record their approval: migration.py approve model "OWNER"')
|
|
149
|
+
return 0
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
if __name__ == '__main__':
|
|
153
|
+
try:
|
|
154
|
+
raise SystemExit(main())
|
|
155
|
+
except migration.StepError as error:
|
|
156
|
+
raise SystemExit(str(error))
|