Enable CLI language-aware editing and reuse OIDC authentication

This commit is contained in:
Anya Tokugawa committed 2026-11-01 21:31:04 +09:00
1 parent f188e7eac1
commit fd8d0f20d1
3 files changed
+154 -30

No files matched your search

+45 -16
View File
@@ -71,7 +71,7 @@ class NoRedirect(http.HTTPRedirectHandler):
class Client:
def __init__(self, base, token='', lang='und'):
def __init__(self, base, token='', lang='auto'):
self.base, self.token, self.lang = origin(base), token, lang
self.opener = http.build_opener(NoRedirect())
@@ -200,24 +200,45 @@ class Client:
return self.json('/_/api/v1/path-picker?' + url.urlencode({'path': path, 'mode': 'children', 'prefix': prefix}))
def raw(self, addr, method='GET'):
raw, headers = self.request('/v/raw/' + url.quote(addr, safe='/:') + '?' + url.urlencode({'lang': self.lang}), method=method, limit=64 << 20)
query = '' if self.lang == 'auto' else '?' + url.urlencode({'lang': self.lang})
raw, headers = self.request('/v/raw/' + url.quote(addr, safe='/:') + query, method=method, limit=64 << 20)
digest = headers.get('X-PagesWiki-Document-SHA256')
if method == 'GET' and (not digest or hashlib.sha256(raw).hexdigest() != digest):
raise Failure('Document SHA-256 mismatch.')
return raw, headers
def snapshot(self, addr):
def snapshot(self, addr, lang=None):
if addr.startswith('rev:'):
raise Failure('Revision addresses are immutable; edit a path: or uuid: address.')
_, headers = self.raw(addr, 'HEAD')
ident = headers.get('X-PagesWiki-Object-UUID')
if not ident:
raise Failure('Missing Object UUID metadata.')
state = self.json('/_/api/v1/editor/state?' + url.urlencode({'uuid': ident, 'lang': self.lang}))
target = self.lang if lang is None else lang
visible = headers.get('X-PagesWiki-Revision-UUID', '')
def load(language, **extra):
return self.json('/_/api/v1/editor/state?' + url.urlencode({'uuid': ident, 'lang': language, **extra}))
if target == 'auto':
# Resolve the viewer's language, then obtain that exact language's
# current head. Never save against a head from a different language.
target = load('und', revision=visible, metadata=1)['lang'] if visible else 'und'
state = load(target)
if not state.get('editable') or not state.get('principal_uuid'):
raise Failure('Not an authenticated editable text document; use the browser.')
if not state.get('head_revision_uuid') or not state.get('content_type'):
raise Failure('No saved revision in this exact language; creation/translation is not supported yet.')
if not state.get('head_revision_uuid'):
# An empty CAS base asserts absence of this language. Seed from the
# visible source without changing it or pretending it is the base.
if visible:
source = load(state['lang'], revision=visible)
if not source.get('editable') or source.get('principal_uuid') != state['principal_uuid']:
raise Failure('Cannot fork this document or the editing account changed.')
for key in ('body', 'markdown', 'content_type', 'filename'):
state[key] = source[key]
state['source_revision_uuid'] = visible
state['source_language'] = source['lang']
state['new_language'] = True
if not state.get('content_type'):
raise Failure('Missing document format; use the browser.')
state['object_uuid'] = ident
return state
@@ -229,7 +250,7 @@ class Client:
raise Failure('Markdown authoring is supported only for HTML Wiki documents.')
text = self.json('/_/api/v1/render/markdown', method='POST', data={
'markdown': text, 'authoring': True, 'projection': False})['html']
if text == state['body']:
if state['head_revision_uuid'] and text == state['body']:
return {'status': 'unchanged', 'revision_uuid': state['head_revision_uuid']}
return self.json('/_/api/v1/revisions/save', method='POST', data={
'object_uuid': state['object_uuid'], 'body': text, 'lang': state['lang'],
@@ -294,7 +315,7 @@ def profile_name(name):
def language(value):
if not isinstance(value, str) or not re.fullmatch(r'[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*', value):
raise Failure('Use a language tag such as und, ja or en-US; the server validates the exact tag.')
raise Failure('Use auto or a language tag such as und, ja or en-US; the server validates the exact tag.')
return value
@@ -325,7 +346,7 @@ class Configuration(PrivateJSON):
raise Failure('Profiles accept only origin, username and lang; never store a password here.')
if not isinstance(spec.get('username', ''), str) or any(unicodedata.category(c).startswith('C') for c in spec.get('username', '')):
raise Failure('Invalid configured username.')
normalized[name] = dict(spec, origin=origin(spec.get('origin', '')), lang=language(spec.get('lang', 'und')))
normalized[name] = dict(spec, origin=origin(spec.get('origin', '')), lang=language(spec.get('lang', 'auto')))
if profiles and default not in profiles: raise Failure('Default profile does not exist.')
return {'version': 1, 'default_profile': default, 'profiles': normalized}
@@ -347,7 +368,7 @@ def configure(words, root=None):
print(json.dumps(data, ensure_ascii=False, indent=2)); return
if args.action == 'list':
for name, spec in data['profiles'].items():
print(safe_text(('★ ' if name == data['default_profile'] else ' ') + name + ' ' + spec['origin'] + ' ' + spec.get('username', '') + ' [' + spec.get('lang', 'und') + ']'))
print(safe_text(('★ ' if name == data['default_profile'] else ' ') + name + ' ' + spec['origin'] + ' ' + spec.get('username', '') + ' [' + spec.get('lang', 'auto') + ']'))
if not data['profiles']: print('No connections. Use: pages configure --origin https://wiki.example --username NAME')
return
if args.action == 'use':
@@ -356,7 +377,7 @@ def configure(words, root=None):
data['default_profile'] = name
else:
name = profile_name(args.profile or data['default_profile'])
spec = dict(data['profiles'].get(name, {'lang': 'und'}))
spec = dict(data['profiles'].get(name, {'lang': 'auto'}))
if args.origin is not None: spec['origin'] = origin(args.origin)
if args.username is not None: spec['username'] = args.username.strip()
if args.lang is not None: spec['lang'] = language(args.lang)
@@ -378,6 +399,9 @@ def configure(words, root=None):
def editor(client, addr, mode):
state = client.snapshot(addr)
print('Editing language:', safe_text(state['lang']))
if state.get('new_language'):
print('Creating a new language revision; source remains unchanged:', safe_text(state.get('source_language', '(empty)')))
markdown = mode == 'markdown' or (mode == 'auto' and state['content_type'].startswith('text/html'))
initial = state['markdown'] if markdown else state['body']
directory = Path(tempfile.mkdtemp(prefix='pageswiki-edit-'))
@@ -397,7 +421,7 @@ def editor(client, addr, mode):
result = client.save(state, text, markdown)
except Failure as error:
if error.status == 409:
latest = client.snapshot('uuid:' + state['object_uuid'])
latest = client.snapshot('uuid:' + state['object_uuid'], lang=state['lang'])
remote = latest['markdown'] if markdown else latest['body']
print(safe_text(''.join(difflib.unified_diff(remote.splitlines(True), text.splitlines(True), fromfile='remote', tofile='local'))))
raise
@@ -411,7 +435,8 @@ def editor(client, addr, mode):
metadata = directory / 'recovery.json'
metadata.touch(mode=0o600)
metadata.write_text(json.dumps({'origin': client.base, 'address': 'uuid:' + state['object_uuid'],
'base_revision_uuid': state['head_revision_uuid'], 'lang': state['lang'], 'format': 'markdown' if markdown else 'raw'}))
'base_revision_uuid': state['head_revision_uuid'], 'source_revision_uuid': state.get('source_revision_uuid', ''),
'lang': state['lang'], 'format': 'markdown' if markdown else 'raw'}))
print('Local edit retained:', safe_text(file), file=sys.stderr)
@@ -423,6 +448,7 @@ def execute(client, profile, words):
p.add_argument('path', nargs='?', default='.')
if command == 'edit':
p.add_argument('--format', choices=['auto', 'raw', 'markdown'], default='auto')
p.add_argument('--lang', help='auto edits the visible language; an explicit tag can create a language revision')
p = sub.add_parser('get'); p.add_argument('path'); p.add_argument('local')
p = sub.add_parser('put'); p.add_argument('local'); p.add_argument('path'); p.add_argument('--base', required=True)
p.add_argument('--format', choices=['raw', 'markdown'], default='raw')
@@ -462,9 +488,12 @@ def execute(client, profile, words):
route = addr[5:] if addr.startswith('path:') else '/o/' + addr if addr.startswith('uuid:') else '/r/view/' + addr[4:]
webbrowser.open(client.base + url.quote(route, safe='/:'), new=2)
elif cmd == 'edit':
editor(client, addr, args.format)
editing = Client(client.base, client.token, language(args.lang)) if args.lang else client
editor(editing, addr, args.format)
elif cmd == 'put':
state = client.snapshot(addr)
if not state['head_revision_uuid']:
raise Failure('No revision in the target language; use edit --lang to create a language revision.')
if state['head_revision_uuid'] != args.base: raise Failure('Conflict: supplied base is not the current language head.', 409)
text = Path(args.local).read_text(encoding='utf-8')
print('Revision:', safe_text(client.save(state, text, args.format == 'markdown')['revision_uuid']))
@@ -529,7 +558,7 @@ def shell(client, profile):
def main(argv=None):
parser = argparse.ArgumentParser(prog='pages', description=__doc__, epilog='Commands: configure, login, logout, status, shell, ls, cd, pwd, cat, view, get, put, edit, search, open. Use pages COMMAND --help.')
parser.add_argument('--profile', help='Use another configured connection for this invocation')
parser.add_argument('--lang', help='Override the configured exact language for this invocation')
parser.add_argument('--lang', help='auto or an exact language tag for this invocation')
parser.add_argument('command', nargs='?', default='shell')
parser.add_argument('args', nargs=argparse.REMAINDER)
args = parser.parse_args(argv)
@@ -553,7 +582,7 @@ def main(argv=None):
spec = settings['profiles'].get(name)
if spec is None:
raise Failure('No connection configured. Run: pages configure --origin https://HOST --username NAME')
lang = language(args.lang or spec.get('lang', 'und'))
lang = language(args.lang or spec.get('lang', 'auto'))
# Hold the profile lock before releasing the configuration lock.
profile = stack.enter_context(Profile(name).locked())
if args.command == 'login':