feat: opt-in OIDC browser open, atomic page creation, and conflict recovery
- Default pages login --oidc to not auto-open a browser and replace --no-browser with --with-open-browser - Add atomic new Path/Page creation (PUT /_/api/v1/pages/path:... with If-None-Match: *) in pages edit with confirmation and und warning - Add interactive 409/412 conflict resolution and pages recover (--list, --edit, --discard) - Update tests, docs (README.md, DISTRIBUTION.md, docs/client-contract.md, docs/neomutt.md), and macOS CI unittest list
This commit is contained in:
1 parent
bee03094f3
commit
9b685b72da
9 files changed
+907
-75
No files matched your search
@@ -92,26 +92,30 @@ class Client:
|
||||
handlers.append(http.HTTPSHandler(context=context))
|
||||
self.opener = http.build_opener(*handlers)
|
||||
|
||||
def request(self, route, method='GET', data=None, form=None, limit=4 << 20, etag=None, content_type=None):
|
||||
def request(self, route, method='GET', data=None, form=None, limit=4 << 20, etag=None, content_type=None, headers=None, expect_status=None):
|
||||
if not route.startswith('/') or route.startswith('//'):
|
||||
raise Failure('Invalid API route.')
|
||||
headers = {'Accept': 'application/json', 'User-Agent': 'pages-cli/' + VERSION}
|
||||
req_headers = {'Accept': 'application/json', 'User-Agent': 'pages-cli/' + VERSION}
|
||||
if headers:
|
||||
req_headers.update(headers)
|
||||
if etag is not None:
|
||||
headers['If-Match'] = etag
|
||||
req_headers['If-Match'] = etag
|
||||
if self.token:
|
||||
headers['Authorization'] = 'Bearer ' + self.token
|
||||
req_headers['Authorization'] = 'Bearer ' + self.token
|
||||
body = None
|
||||
if data is not None:
|
||||
body = data if isinstance(data, bytes) else json.dumps(data, ensure_ascii=False).encode()
|
||||
headers['Content-Type'] = content_type or 'application/json'
|
||||
req_headers['Content-Type'] = content_type or 'application/json'
|
||||
if form is not None:
|
||||
body = url.urlencode(form).encode()
|
||||
headers['Content-Type'] = 'application/x-www-form-urlencoded'
|
||||
req_headers['Content-Type'] = 'application/x-www-form-urlencoded'
|
||||
if body is not None and len(body) > 2 << 20:
|
||||
raise Failure('Request exceeds the 2 MiB client limit.')
|
||||
req = http.Request(self.base + route, body, headers, method=method)
|
||||
req = http.Request(self.base + route, body, req_headers, method=method)
|
||||
try:
|
||||
with self.opener.open(req, timeout=20) as response:
|
||||
if expect_status is not None and response.status != expect_status:
|
||||
raise Failure('Unexpected HTTP status (%d).' % response.status, response.status)
|
||||
raw = response.read(limit + 1)
|
||||
if len(raw) > limit:
|
||||
raise Failure('Response exceeds client limit; use the browser for large files.')
|
||||
@@ -127,7 +131,8 @@ class Client:
|
||||
payload = {}
|
||||
messages = {303: 'Login redirect refused; log in again.', 401: 'Session expired or authentication required.', 403: 'Access denied.',
|
||||
404: 'Not found or not readable.', 409: 'Conflict: remote revision changed.',
|
||||
412: 'Conflict: remote item changed; reload before saving.', 422: 'Invalid fields; check dates, project and required settings.'}
|
||||
412: 'Conflict: remote item changed; reload before saving.', 422: 'Invalid fields; check dates, project and required settings.',
|
||||
428: 'Precondition required by server.'}
|
||||
raise Failure(messages.get(e.code, 'HTTP request failed (%d); redirects are not followed.' % e.code), e.code, payload) from None
|
||||
except (urllib.error.URLError, TimeoutError, OSError):
|
||||
raise Failure('Connection/TLS failure; no automatic write retry was attempted.') from None
|
||||
@@ -166,7 +171,7 @@ class Client:
|
||||
self.token = token
|
||||
return time.time() + duration
|
||||
|
||||
def login_oidc(self, no_browser=False, expected_username='', *, remember=False, sleep=time.sleep, clock=time.monotonic):
|
||||
def login_oidc(self, open_browser=False, expected_username='', *, remember=False, sleep=time.sleep, clock=time.monotonic):
|
||||
verifier = secrets.token_urlsafe(32)
|
||||
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
|
||||
try:
|
||||
@@ -192,7 +197,7 @@ class Client:
|
||||
print(self.base + route)
|
||||
print('Confirmation code:', code)
|
||||
print('Waiting for approval (up to 5 minutes). Ctrl+C cancels locally.', flush=True)
|
||||
if not no_browser:
|
||||
if open_browser:
|
||||
try: webbrowser.open(self.base + route, new=2)
|
||||
except (webbrowser.Error, OSError): pass # URL remains usable on another device.
|
||||
while clock() + interval < deadline:
|
||||
@@ -281,6 +286,45 @@ class Client:
|
||||
'base_revision_uuid': state['head_revision_uuid'],
|
||||
'editor_principal_uuid': state['principal_uuid'], 'message': 'Remote CLI edit'})
|
||||
|
||||
def create_page(self, addr, text, markdown=False, *, lang=None, content_type=None, filename='', message='Remote CLI create'):
|
||||
if not addr.startswith('path:') or addr == 'path:/':
|
||||
raise Failure('New page creation requires a non-root Path.')
|
||||
if len(text.encode('utf-8')) > 1 << 20:
|
||||
raise Failure('Text edit exceeds the 1 MiB client limit.')
|
||||
chosen = self.lang if lang is None else language(lang)
|
||||
target_lang = 'und' if chosen == 'auto' else chosen
|
||||
if markdown:
|
||||
ctype = 'text/html; charset=utf-8'
|
||||
body_text = self.json('/_/api/v1/render/markdown', method='POST', data={
|
||||
'markdown': text, 'authoring': True, 'projection': False})['html']
|
||||
else:
|
||||
ctype = content_type or 'text/plain; charset=utf-8'
|
||||
body_text = text
|
||||
payload = body_text.encode('utf-8')
|
||||
extra = {'If-None-Match': '*', 'Content-Language': target_lang}
|
||||
if message:
|
||||
extra['X-PagesWiki-Commit-Message'] = url.quote(message, safe='-_.,~')
|
||||
if filename:
|
||||
extra['X-PagesWiki-Filename'] = url.quote(filename, safe='-_.,~')
|
||||
route = '/_/api/v1/pages/' + url.quote(addr, safe='/:')
|
||||
try:
|
||||
_, resp_headers = self.request(route, method='PUT', data=payload, content_type=ctype, headers=extra, expect_status=201)
|
||||
except Failure as e:
|
||||
if e.status in (404, 405, 501):
|
||||
raise Failure('Atomic page creation (PUT /_/api/v1/pages/path:...) is unavailable on this server. Update the server to a version supporting this endpoint.', e.status, e.payload) from None
|
||||
if e.status == 412:
|
||||
raise Failure('Conflict: a page already exists at this Path; reload with pages edit.', 412, e.payload) from None
|
||||
if e.status == 428:
|
||||
raise Failure('Server requires a create precondition (If-None-Match: *).', 428, e.payload) from None
|
||||
raise
|
||||
object_uuid = resp_headers.get('X-PagesWiki-Object-UUID', '').strip()
|
||||
revision_uuid = resp_headers.get('X-PagesWiki-Revision-UUID', '').strip()
|
||||
doc_hash = resp_headers.get('X-PagesWiki-Document-SHA256', '').strip()
|
||||
saved_lang = resp_headers.get('Content-Language', target_lang).strip() or target_lang
|
||||
if not object_uuid or not revision_uuid or not re.fullmatch(r'[0-9a-f]{64}', doc_hash):
|
||||
raise Failure('Invalid page creation response; missing document identity headers.')
|
||||
return {'status': 'created', 'path': addr[5:], 'object_uuid': object_uuid, 'revision_uuid': revision_uuid, 'document_hash': doc_hash, 'lang': saved_lang}
|
||||
|
||||
|
||||
def private_file(path):
|
||||
info = path.lstat()
|
||||
@@ -420,47 +464,336 @@ def configure(words, root=None):
|
||||
print('Default profile:', data['default_profile'])
|
||||
|
||||
|
||||
def private_dir(path):
|
||||
info = path.lstat()
|
||||
if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
|
||||
raise Failure('Recovery directory must be owned by you with mode 0700; symlinks are not accepted.')
|
||||
|
||||
|
||||
def run_editor(file):
|
||||
command = shlex.split(os.environ.get('EDITOR', 'vi'))
|
||||
if not command or subprocess.run(command + [str(file)], check=False).returncode:
|
||||
raise Failure('Editor exited unsuccessfully.')
|
||||
|
||||
|
||||
def conflict_buffer(local, remote, head_rev=''):
|
||||
l = local if (not local or local.endswith('\n')) else local + '\n'
|
||||
r = remote if (not remote or remote.endswith('\n')) else remote + '\n'
|
||||
label = 'remote (rev: ' + head_rev + ')' if head_rev else 'remote'
|
||||
return '<<<<<<< local\n' + l + '=======\n' + r + '>>>>>>> ' + label + '\n'
|
||||
|
||||
|
||||
def has_conflict_markers(text):
|
||||
return any(line.startswith('<<<<<<< ') or line == '=======' or line.startswith('>>>>>>> ') for line in text.splitlines())
|
||||
|
||||
|
||||
def choose_conflict_action(kind, has_remote=True):
|
||||
if not sys.stdin.isatty():
|
||||
return 'k'
|
||||
if kind == 'update':
|
||||
prompt = 'Conflict detected. [e]dit with markers, [f]orce-save local on new head, [k]eep local draft and exit [e/f/K]: '
|
||||
allowed = ('e', 'f', 'k')
|
||||
elif has_remote:
|
||||
prompt = 'Path already exists. [e]dit with existing page, [p]ick another path, [k]eep local draft and exit [e/p/K]: '
|
||||
allowed = ('e', 'p', 'k')
|
||||
else:
|
||||
prompt = 'Path already exists (not readable). [p]ick another path, [k]eep local draft and exit [p/K]: '
|
||||
allowed = ('p', 'k')
|
||||
try:
|
||||
choice = input(prompt).strip().lower()
|
||||
except EOFError:
|
||||
return 'k'
|
||||
return choice if choice in allowed else 'k'
|
||||
|
||||
|
||||
def prompt_new_path(cwd='/'):
|
||||
if not sys.stdin.isatty():
|
||||
return None
|
||||
try:
|
||||
raw = input('New Path (blank to keep draft and exit): ').strip()
|
||||
except EOFError:
|
||||
return None
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
addr = address(raw, cwd)
|
||||
except Failure as e:
|
||||
print(safe_text(str(e)), file=sys.stderr)
|
||||
return None
|
||||
if not addr.startswith('path:') or addr == 'path:/':
|
||||
print('Enter a non-root Path.', file=sys.stderr)
|
||||
return None
|
||||
return addr
|
||||
|
||||
|
||||
def write_recovery(directory, client, ctx):
|
||||
metadata = directory / 'recovery.json'
|
||||
metadata.touch(mode=0o600)
|
||||
if ctx['creating']:
|
||||
recovery = {'origin': client.base, 'mode': 'create', 'address': ctx['addr'],
|
||||
'lang': ctx['lang'], 'format': 'markdown' if ctx['markdown'] else 'raw'}
|
||||
else:
|
||||
recovery = {'origin': client.base, 'address': 'uuid:' + ctx['state']['object_uuid'],
|
||||
'base_revision_uuid': ctx['state']['head_revision_uuid'],
|
||||
'source_revision_uuid': ctx['state'].get('source_revision_uuid', ''),
|
||||
'lang': ctx['state']['lang'], 'format': 'markdown' if ctx['markdown'] else 'raw'}
|
||||
metadata.write_text(json.dumps(recovery))
|
||||
|
||||
|
||||
def commit_edit(client, file, text, ctx, cwd='/'):
|
||||
while True:
|
||||
if ctx['creating']:
|
||||
try:
|
||||
result = client.create_page(ctx['addr'], text, ctx['markdown'], lang=ctx['lang'])
|
||||
except Failure as error:
|
||||
if error.status != 412:
|
||||
raise
|
||||
try:
|
||||
latest = client.snapshot(ctx['addr'], lang=ctx['lang'])
|
||||
except Failure:
|
||||
latest = None
|
||||
remote = ''
|
||||
if latest is not None:
|
||||
remote = latest['markdown'] if ctx['markdown'] else latest['body']
|
||||
print(safe_text(''.join(difflib.unified_diff(remote.splitlines(True), text.splitlines(True), fromfile='remote', tofile='local'))))
|
||||
action = choose_conflict_action('create', has_remote=latest is not None)
|
||||
if action == 'p':
|
||||
new_addr = prompt_new_path(cwd)
|
||||
if not new_addr:
|
||||
raise
|
||||
ctx['addr'] = new_addr
|
||||
continue
|
||||
if action == 'e' and latest is not None:
|
||||
ctx['creating'] = False
|
||||
ctx['state'] = latest
|
||||
ctx['lang'] = latest['lang']
|
||||
file.write_text(conflict_buffer(text, remote, latest.get('head_revision_uuid', '')), encoding='utf-8')
|
||||
run_editor(file)
|
||||
text = file.read_text(encoding='utf-8')
|
||||
if has_conflict_markers(text):
|
||||
print('Conflict markers remain; remove them before saving.', file=sys.stderr)
|
||||
raise Failure('Conflict markers remain in edited document.', 409) from None
|
||||
continue
|
||||
raise
|
||||
print('Created page:', safe_text(result['path']))
|
||||
print('Object UUID:', safe_text(result['object_uuid']))
|
||||
print('Saved revision:', safe_text(result['revision_uuid']))
|
||||
return result
|
||||
try:
|
||||
result = client.save(ctx['state'], text, ctx['markdown'])
|
||||
except Failure as error:
|
||||
if error.status != 409:
|
||||
raise
|
||||
latest = client.snapshot('uuid:' + ctx['state']['object_uuid'], lang=ctx['state']['lang'])
|
||||
remote = latest['markdown'] if ctx['markdown'] else latest['body']
|
||||
print(safe_text(''.join(difflib.unified_diff(remote.splitlines(True), text.splitlines(True), fromfile='remote', tofile='local'))))
|
||||
action = choose_conflict_action('update', has_remote=True)
|
||||
if action == 'k':
|
||||
raise
|
||||
ctx['state'] = latest
|
||||
if action == 'f':
|
||||
continue
|
||||
if action == 'e':
|
||||
file.write_text(conflict_buffer(text, remote, latest.get('head_revision_uuid', '')), encoding='utf-8')
|
||||
run_editor(file)
|
||||
text = file.read_text(encoding='utf-8')
|
||||
if has_conflict_markers(text):
|
||||
print('Conflict markers remain; remove them before saving.', file=sys.stderr)
|
||||
raise Failure('Conflict markers remain in edited document.', 409) from None
|
||||
continue
|
||||
raise
|
||||
print('Saved revision:', safe_text(result['revision_uuid']))
|
||||
return result
|
||||
|
||||
|
||||
def confirm_create(addr, status):
|
||||
if not sys.stdin.isatty():
|
||||
if status == 404:
|
||||
raise Failure('Not found or not readable (interactive confirmation is required to create a new page).', 404)
|
||||
raise Failure('Access denied.', 403)
|
||||
path = safe_text(addr[5:])
|
||||
if status == 404:
|
||||
prompt = f'Path {path} does not exist. Create a new page? [y/N]: '
|
||||
else:
|
||||
prompt = f'Cannot read {path} (access denied). If you have create-only permission, attempt to create a new page? [y/N]: '
|
||||
try:
|
||||
answer = input(prompt)
|
||||
except EOFError:
|
||||
return False
|
||||
return answer.strip().lower() in ('y', 'yes')
|
||||
|
||||
|
||||
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']
|
||||
creating = False
|
||||
state = None
|
||||
try:
|
||||
state = client.snapshot(addr)
|
||||
except Failure as error:
|
||||
if error.status in (404, 403) and addr.startswith('path:') and addr != 'path:/':
|
||||
if not confirm_create(addr, error.status):
|
||||
print('Aborted.')
|
||||
return
|
||||
creating = True
|
||||
if client.lang == 'auto':
|
||||
lang = 'und'
|
||||
print("WARNING: Creating a new page with language 'und' (profile language is 'auto'). Use --lang TAG to specify an explicit language.", file=sys.stderr)
|
||||
else:
|
||||
lang = client.lang
|
||||
print('Creating new page:', safe_text(addr[5:]))
|
||||
print('Editing language:', safe_text(lang))
|
||||
markdown = mode in ('auto', 'markdown')
|
||||
initial = ''
|
||||
else:
|
||||
raise
|
||||
if not creating:
|
||||
lang = state['lang']
|
||||
print('Editing language:', safe_text(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-'))
|
||||
file = directory / ('document.md' if markdown else 'document.txt')
|
||||
file.touch(mode=0o600)
|
||||
file.write_text(initial, encoding='utf-8')
|
||||
ctx = {'creating': creating, 'addr': addr, 'state': state, 'lang': lang, 'markdown': markdown}
|
||||
success = False
|
||||
try:
|
||||
command = shlex.split(os.environ.get('EDITOR', 'vi'))
|
||||
if not command or subprocess.run(command + [str(file)], check=False).returncode:
|
||||
raise Failure('Editor exited unsuccessfully.')
|
||||
run_editor(file)
|
||||
text = file.read_text(encoding='utf-8')
|
||||
if text == initial:
|
||||
print('Unchanged.')
|
||||
print('Unchanged; page was not created.' if creating else 'Unchanged.')
|
||||
else:
|
||||
try:
|
||||
result = client.save(state, text, markdown)
|
||||
except Failure as error:
|
||||
if error.status == 409:
|
||||
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
|
||||
print('Saved revision:', safe_text(result['revision_uuid']))
|
||||
commit_edit(client, file, text, ctx)
|
||||
success = True
|
||||
finally:
|
||||
if success:
|
||||
file.unlink()
|
||||
directory.rmdir()
|
||||
else:
|
||||
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'], 'source_revision_uuid': state.get('source_revision_uuid', ''),
|
||||
'lang': state['lang'], 'format': 'markdown' if markdown else 'raw'}))
|
||||
write_recovery(directory, client, ctx)
|
||||
print('Local edit retained:', safe_text(file), file=sys.stderr)
|
||||
print('Recover later with: pages recover', safe_text(file), file=sys.stderr)
|
||||
|
||||
|
||||
def resolve_recovery(target):
|
||||
p = Path(target)
|
||||
if p.is_symlink():
|
||||
raise Failure('Recovery path must not be a symlink.')
|
||||
if p.is_dir():
|
||||
directory = p
|
||||
elif p.name in ('recovery.json', 'document.md', 'document.txt'):
|
||||
directory = p.parent
|
||||
else:
|
||||
raise Failure('Specify a pageswiki-edit recovery directory, recovery.json, or retained document file.')
|
||||
if not directory.exists() or directory.is_symlink():
|
||||
raise Failure('Recovery directory not found or invalid.')
|
||||
private_dir(directory)
|
||||
meta_path = directory / 'recovery.json'
|
||||
if not meta_path.exists() and not meta_path.is_symlink():
|
||||
raise Failure('Missing recovery.json metadata.')
|
||||
private_file(meta_path)
|
||||
try:
|
||||
data = json.loads(meta_path.read_text(encoding='utf-8'))
|
||||
except (ValueError, UnicodeError) as e:
|
||||
raise Failure('Corrupt recovery.json metadata.') from e
|
||||
if not isinstance(data, dict):
|
||||
raise Failure('Corrupt recovery.json metadata.')
|
||||
req_origin = data.get('origin')
|
||||
addr = data.get('address')
|
||||
lang = data.get('lang')
|
||||
fmt = data.get('format')
|
||||
rec_mode = data.get('mode', 'update')
|
||||
if (not isinstance(req_origin, str) or not req_origin
|
||||
or not isinstance(addr, str) or not addr
|
||||
or not isinstance(lang, str) or not lang
|
||||
or fmt not in ('markdown', 'raw')
|
||||
or rec_mode not in ('update', 'create')):
|
||||
raise Failure('Invalid recovery.json metadata.')
|
||||
doc_path = directory / ('document.md' if fmt == 'markdown' else 'document.txt')
|
||||
if not doc_path.exists() and not doc_path.is_symlink():
|
||||
raise Failure('Missing retained document file.')
|
||||
private_file(doc_path)
|
||||
return directory, meta_path, doc_path, data
|
||||
|
||||
|
||||
def list_recoveries(temp_root=None):
|
||||
root = Path(temp_root or tempfile.gettempdir())
|
||||
found = []
|
||||
for entry in sorted(root.glob('pageswiki-edit-*')):
|
||||
try:
|
||||
directory, _, doc_path, data = resolve_recovery(entry)
|
||||
found.append((directory, doc_path, data, doc_path.stat().st_mtime))
|
||||
except (Failure, OSError, ValueError):
|
||||
continue
|
||||
return found
|
||||
|
||||
|
||||
def cleanup_recovery(directory, meta_path, doc_path):
|
||||
for p in (doc_path, meta_path):
|
||||
if p.exists():
|
||||
p.unlink()
|
||||
if directory.exists() and not any(directory.iterdir()):
|
||||
directory.rmdir()
|
||||
|
||||
|
||||
def recover(client, profile, target=None, *, edit_first=False, discard=False, list_only=False, temp_root=None):
|
||||
if list_only or (target is None and not discard):
|
||||
items = list_recoveries(temp_root)
|
||||
if not items:
|
||||
print('No local recovery drafts found.')
|
||||
return
|
||||
for directory, _, data, mtime in items:
|
||||
stamp = time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(mtime))
|
||||
print(safe_text('\t'.join((str(directory), data.get('mode', 'update'), data['address'], data['lang'], data['origin'], stamp))))
|
||||
return
|
||||
if target is None:
|
||||
raise Failure('Specify a recovery path or use --list.')
|
||||
directory, meta_path, doc_path, meta = resolve_recovery(target)
|
||||
if discard:
|
||||
if not directory.name.startswith('pageswiki-edit-'):
|
||||
raise Failure('Refusing to discard outside a pageswiki-edit-* directory.')
|
||||
cleanup_recovery(directory, meta_path, doc_path)
|
||||
print('Discarded recovery draft:', safe_text(directory))
|
||||
return
|
||||
if meta['origin'] != client.base:
|
||||
raise Failure('Recovery draft belongs to a different server origin (%s); switch profile before recovering.' % safe_text(meta['origin']))
|
||||
rec_mode = meta.get('mode', 'update')
|
||||
markdown = meta['format'] == 'markdown'
|
||||
lang = language(meta['lang'])
|
||||
addr = meta['address']
|
||||
if edit_first:
|
||||
run_editor(doc_path)
|
||||
text = doc_path.read_text(encoding='utf-8')
|
||||
if has_conflict_markers(text):
|
||||
raise Failure('Conflict markers remain in draft; run with --edit to resolve them.', 409)
|
||||
if rec_mode == 'create':
|
||||
if not text:
|
||||
raise Failure('Recovery draft is empty; edit with --edit or remove with --discard.')
|
||||
ctx = {'creating': True, 'addr': addr, 'state': None, 'lang': lang, 'markdown': markdown}
|
||||
else:
|
||||
state = client.snapshot(addr, lang=lang)
|
||||
expected_base = meta.get('base_revision_uuid', '')
|
||||
if state['head_revision_uuid'] != expected_base:
|
||||
remote = state['markdown'] if markdown else state['body']
|
||||
print(safe_text(''.join(difflib.unified_diff(remote.splitlines(True), text.splitlines(True), fromfile='remote', tofile='local'))))
|
||||
action = choose_conflict_action('update', has_remote=True)
|
||||
if action == 'k':
|
||||
raise Failure('Conflict: remote revision changed since draft was saved.', 409)
|
||||
if action == 'e':
|
||||
doc_path.write_text(conflict_buffer(text, remote, state.get('head_revision_uuid', '')), encoding='utf-8')
|
||||
run_editor(doc_path)
|
||||
text = doc_path.read_text(encoding='utf-8')
|
||||
if has_conflict_markers(text):
|
||||
raise Failure('Conflict markers remain in edited document.', 409)
|
||||
ctx = {'creating': False, 'addr': addr, 'state': state, 'lang': state['lang'], 'markdown': markdown}
|
||||
cwd = profile.data.get('cwd', '/') if profile else '/'
|
||||
try:
|
||||
commit_edit(client, doc_path, text, ctx, cwd=cwd)
|
||||
except BaseException:
|
||||
write_recovery(directory, client, ctx)
|
||||
raise
|
||||
cleanup_recovery(directory, meta_path, doc_path)
|
||||
|
||||
|
||||
TASK_API = '/_/api/v1/extension/organizer.tasks/'
|
||||
@@ -733,15 +1066,22 @@ 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.add_argument('--lang', help='auto edits the visible language (or creates as und with warning); an explicit tag selects or creates 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')
|
||||
p = sub.add_parser('recover', help='List, resume, or discard retained local edit drafts')
|
||||
p.add_argument('target', nargs='?', help='Recovery directory, recovery.json, or retained document file')
|
||||
p.add_argument('--list', action='store_true', dest='list_only', help='List retained local drafts')
|
||||
p.add_argument('--edit', action='store_true', dest='edit_first', help='Open the draft in $EDITOR before saving')
|
||||
p.add_argument('--discard', action='store_true', help='Delete the retained draft without saving')
|
||||
p = sub.add_parser('search'); p.add_argument('query')
|
||||
sub.add_parser('pwd'); sub.add_parser('logout'); sub.add_parser('status')
|
||||
args = parser.parse_args(words)
|
||||
cwd = profile.data.get('cwd', '/')
|
||||
cmd = args.command
|
||||
if cmd == 'recover':
|
||||
recover(client, profile, args.target, edit_first=args.edit_first, discard=args.discard, list_only=args.list_only); return
|
||||
if cmd == 'logout':
|
||||
client.json('/_/auth/logout', method='POST')
|
||||
profile.data.pop('token', None); profile.data.pop('expires', None); profile.save()
|
||||
@@ -841,7 +1181,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, task, contacts. Use pages COMMAND --help.')
|
||||
parser = argparse.ArgumentParser(prog='pages', description=__doc__, epilog='Commands: configure, login, logout, status, shell, ls, cd, pwd, cat, view, get, put, edit, recover, search, open, task, contacts. Use pages COMMAND --help.')
|
||||
parser.add_argument('--version', action='version', version='pages-cli ' + VERSION)
|
||||
parser.add_argument('--profile', help='Use another configured connection for this invocation')
|
||||
parser.add_argument('--lang', help='auto or an exact language tag for this invocation')
|
||||
@@ -858,10 +1198,10 @@ def main(argv=None):
|
||||
if args.command == 'login':
|
||||
login = argparse.ArgumentParser(prog='pages login', description='Log into the configured connection. Password and TOTP are prompted privately.')
|
||||
login.add_argument('--oidc', action='store_true', help='Authenticate and approve in a browser; no local password required')
|
||||
login.add_argument('--no-browser', action='store_true', help='Print the browser login URL without opening it (requires --oidc)')
|
||||
login.add_argument('--with-open-browser', action='store_true', help='Open the browser login URL automatically (requires --oidc)')
|
||||
login.add_argument('--remember', action='store_true', help='Keep this trusted device signed in for up to 30 days, subject to server policy')
|
||||
login_args = login.parse_args(args.args)
|
||||
if login_args.no_browser and not login_args.oidc: login.error('--no-browser requires --oidc')
|
||||
if login_args.with_open_browser and not login_args.oidc: login.error('--with-open-browser requires --oidc')
|
||||
elif '--help' in args.args:
|
||||
execute(None, None, [args.command] + args.args); return
|
||||
with contextlib.ExitStack() as stack:
|
||||
@@ -881,7 +1221,7 @@ def main(argv=None):
|
||||
if profile.data.get('token') and profile.data.get('expires',0)>time.time(): raise Failure('Log out this profile before replacing its active session.')
|
||||
client = Client(spec['origin'], lang=lang, insecure=args.insecure)
|
||||
if login_args.oidc:
|
||||
expires, username = client.login_oidc(login_args.no_browser, spec.get('username', ''), remember=login_args.remember)
|
||||
expires, username = client.login_oidc(login_args.with_open_browser, spec.get('username', ''), remember=login_args.remember)
|
||||
else:
|
||||
username = spec['username']
|
||||
expires = client.login(username, getpass.getpass('Password: '), remember=login_args.remember)
|
||||
|
||||
Reference in new issue
Block a user