feat(shell): add quote/cursor-aware completion, Ctrl+P fuzzy picker, and opt-in history
Test and release pages-cli / linux (push) Successful in 48s
Test and release pages-cli / macos (push) Skipped

- Add quote-aware, mid-cursor, and command/subcommand-aware Tab completion in shell
- Add Ctrl+P keybinding and pick command for interactive fuzzy search via search/suggest and path-picker
- Add explicit opt-in persistent shell history (pages shell --history) stored in 0700/0600 files with secret-line filtering
- Add unit tests and update README.md and docs/client-contract.md
This commit is contained in:
Anya Tokugawa committed 2026-11-30 22:36:45 +09:00
1 parent a1956dcc6a
commit 44be7c6382
4 files changed
+488 -32

No files matched your search

+371 -30
View File
@@ -1764,45 +1764,382 @@ def execute(client, profile, words):
else: print(text, end='')
def shell(client, profile):
SHELL_COMMANDS = (
'cat', 'cd', 'contacts', 'edit', 'exit', 'get', 'help', 'logout',
'ls', 'mget', 'mput', 'open', 'pick', 'put', 'pwd', 'quit',
'recover', 'search', 'status', 'task', 'view',
)
SHELL_SUBCOMMANDS = {
'task': ('add', 'done', 'from-mail', 'list', 'preferences', 'project-add', 'projects', 'reopen', 'report', 'retry', 'show', 'start', 'status', 'stop', 'update'),
'tasks': ('add', 'done', 'from-mail', 'list', 'preferences', 'project-add', 'projects', 'reopen', 'report', 'retry', 'show', 'start', 'status', 'stop', 'update'),
'contacts': ('export', 'import', 'list', 'query'),
'contact': ('export', 'import', 'list', 'query'),
}
def _split_shell_context(before_cursor):
tokens = []
buf = []
in_token = False
token_start = len(before_cursor)
quote = ''
escape = False
for idx, ch in enumerate(before_cursor):
if escape:
buf.append(ch)
escape = False
continue
if quote == "'":
if ch == "'":
quote = ''
else:
buf.append(ch)
continue
if quote == '"':
if ch == '"':
quote = ''
elif ch == '\\':
escape = True
else:
buf.append(ch)
continue
if ch in (' ', '\t', '\n'):
if in_token:
tokens.append(''.join(buf))
buf = []
in_token = False
token_start = idx + 1
continue
if not in_token:
in_token = True
token_start = idx
if ch == '\\':
escape = True
elif ch in ("'", '"'):
quote = ch
else:
buf.append(ch)
if not in_token:
token_start = len(before_cursor)
return before_cursor[:token_start], tokens, ''.join(buf), quote
def _format_shell_token(candidate, quote_char, *, is_dir=False):
if quote_char == '"':
escaped = candidate.replace('\\', '\\\\').replace('"', '\\"')
return '"' + escaped + ('' if is_dir else '"')
if quote_char == "'":
if "'" in candidate:
return shlex.quote(candidate)
return "'" + candidate + ('' if is_dir else "'")
quoted = shlex.quote(candidate)
if is_dir and quoted == candidate:
return candidate
return quoted
def shell_completions(client, cwd, before_cursor, *, temp_root=None):
prefix_str, completed, current, quote_char = _split_shell_context(before_cursor)
if not completed and not quote_char:
return [prefix_str + cmd for cmd in SHELL_COMMANDS if cmd.startswith(current)]
if len(completed) == 1 and completed[0] in SHELL_SUBCOMMANDS and not quote_char:
return [prefix_str + sub for sub in SHELL_SUBCOMMANDS[completed[0]] if sub.startswith(current)]
if completed and completed[0] == 'recover' and not current.startswith('-'):
out = []
for directory, _, _, _ in list_recoveries(temp_root):
dstr = str(directory)
if dstr.startswith(current):
out.append(prefix_str + _format_shell_token(dstr, quote_char, is_dir=True))
return out
if current.startswith('-'):
return []
if current.startswith(('uuid:', 'rev:')):
return []
addr_prefix = 'path:' if current.startswith('path:') else ''
raw = current.removeprefix('path:')
try:
p = semantic(raw or '.', cwd)
except Failure:
return []
if not raw:
parent, prefix = cwd, ''
elif raw.endswith('/'):
parent, prefix = p, ''
else:
parent, prefix = posixpath.dirname(p), posixpath.basename(p)
try:
entries = client.listing(parent, prefix).get('entries', [])
except Failure:
return []
out = []
for item in entries:
ipath = item.get('path', '')
if not isinstance(ipath, str) or not ipath or any(unicodedata.category(c).startswith('C') for c in ipath):
continue
is_dir = item.get('kind') == 'folder'
cand = ipath if raw.startswith('/') else posixpath.relpath(ipath, cwd)
cand = addr_prefix + cand + ('/' if is_dir else '')
out.append(prefix_str + _format_shell_token(cand, quote_char, is_dir=is_dir))
return out
def _fuzzy_score(query, text):
q = query.strip().lower()
if not q:
return 0
t = text.lower()
pos = t.find(q)
if pos != -1:
return 1000 - pos - len(t)
qi = 0
score = 0
prev = -2
for ti, ch in enumerate(t):
if ch == q[qi]:
if ti == prev + 1:
score += 12
elif ti == 0 or t[ti - 1] in '/_- .':
score += 8
else:
score += 1
prev = ti
qi += 1
if qi == len(q):
return score - len(t) // 4
return None
def _gather_pick_candidates(client, cwd, query=''):
merged = {}
if query.strip():
try:
for item in client.json('/_/api/v1/search/suggest?' + url.urlencode({'q': query.strip()})).get('items', []):
p = item.get('path', '')
if not isinstance(p, str) or not p.startswith('/') or any(unicodedata.category(c).startswith('C') for c in p):
continue
merged[p] = {'path': p, 'label': safe_text(item.get('label', '')), 'kind': item.get('kind', 'page')}
except Failure:
pass
try:
for item in client.listing(cwd).get('entries', []):
p = item.get('path', '')
if not isinstance(p, str) or not p.startswith('/') or any(unicodedata.category(c).startswith('C') for c in p):
continue
merged.setdefault(p, {'path': p, 'label': safe_text(item.get('name', '')), 'kind': item.get('kind', 'file')})
except Failure:
pass
scored = []
for entry in merged.values():
haystack = entry['path'] + ' ' + entry['label']
sc = _fuzzy_score(query, haystack)
if sc is not None:
scored.append((sc, entry['path'], entry))
scored.sort(key=lambda row: (-row[0], row[1]))
return [row[2] for row in scored[:20]]
def fuzzy_pick(client, profile, initial_query='', initial_line=''):
if not sys.stdin.isatty():
raise Failure('Interactive picker requires a TTY.')
cwd = profile.data.get('cwd', '/')
query = initial_query.strip()
first = True
chosen = None
while True:
if not first or not query:
try:
typed = input('Fuzzy search (blank to cancel): ').strip()
except EOFError:
return None
if not typed:
return None
query = typed
first = False
items = _gather_pick_candidates(client, cwd, query)
if not items:
print('No matching pages.')
if initial_query and not initial_line:
return None
query = ''
continue
for idx, item in enumerate(items, 1):
label = f" {item['label']}" if item['label'] and item['label'] != item['path'] else ''
print(safe_text(f"{idx:2d}) {item['path']}{label} [{item['kind']}]"))
try:
sel = input(f'Select [1-{len(items)}] (or new query / blank to cancel): ').strip()
except EOFError:
return None
if not sel or sel.lower() == 'q':
return None
if sel.isdigit():
num = int(sel)
if 1 <= num <= len(items):
chosen = items[num - 1]['path']
break
print('Selection out of range.')
continue
query = sel
if initial_line:
return initial_line + shlex.quote(chosen)
try:
act = input(f'Action for {safe_text(chosen)}: [c]d / [e]dit / [v]iew / [p]rint / [i]nsert / [Q]uit: ').strip().lower()
except EOFError:
return None
if act == 'c':
execute(client, profile, ['cd', chosen])
elif act == 'e':
execute(client, profile, ['edit', chosen])
elif act == 'v':
execute(client, profile, ['view', chosen])
elif act == 'p':
print(safe_text(chosen))
elif act == 'i':
return shlex.quote(chosen) + ' '
return None
def _safe_history_line(line):
if not isinstance(line, str):
return False
stripped = line.strip()
if not stripped or any(unicodedata.category(c).startswith('C') for c in stripped):
return False
low = stripped.lower()
if low == 'login' or low.startswith('login '):
return False
for marker in ('authorization', 'bearer', 'password', 'totp', 'pw_api_', 'challenge_token', 'device_code', 'code_verifier'):
if marker in low:
return False
return True
def _shell_history_path(profile, root=None):
hist_dir = config_root(root) / 'history'
hist_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
private_dir(hist_dir)
return hist_dir / (profile_name(profile.name) + '.history')
def _load_shell_history(readline_mod, path):
if path.exists() or path.is_symlink():
private_file(path)
for line in path.read_text(encoding='utf-8').splitlines():
if _safe_history_line(line):
readline_mod.add_history(line)
def _save_shell_history(readline_mod, path):
count = readline_mod.get_current_history_length()
start = max(1, count - 199)
lines = []
for idx in range(start, count + 1):
item = readline_mod.get_history_item(idx)
if _safe_history_line(item):
lines.append(item.strip())
tmp = path.parent / ('.hist-' + secrets.token_hex(8) + '.tmp')
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
try:
with os.fdopen(fd, 'w', encoding='utf-8') as out:
if lines:
out.write('\n'.join(lines) + '\n')
out.flush()
os.fsync(out.fileno())
os.replace(tmp, path)
finally:
if tmp.exists() or tmp.is_symlink():
tmp.unlink()
def shell(client, profile, *, persist_history=False, history_root=None):
import readline
print(safe_text('pages · ' + client.base + ' · ' + profile.data.get('username', '') + ' · ' + client.lang))
# History remains in memory, never on disk; login/password commands are not supported here.
print('Type help for commands, Tab to complete, Ctrl+P (or pick) for fuzzy search.')
# History remains in memory unless --history is explicitly opted in; login/password commands are not supported here.
readline.set_history_length(200)
readline.set_completer_delims(' \t\n')
hist_path = None
if persist_history:
hist_path = _shell_history_path(profile, history_root)
_load_shell_history(readline, hist_path)
readline.set_completer_delims('\n')
matches = []
def complete(text, index):
if index == 0:
matches.clear()
try:
p = semantic(text, profile.data.get('cwd', '/'))
parent = p if text.endswith('/') else posixpath.dirname(p)
prefix = '' if text.endswith('/') else posixpath.basename(p)
for item in client.listing(parent, prefix)['entries']:
if any(unicodedata.category(c).startswith('C') for c in item['path']):
continue
candidate = item['path'] + ('/' if item['kind'] == 'folder' else '')
if not text.startswith('/'): candidate = posixpath.relpath(candidate, profile.data.get('cwd', '/')) + ('/' if item['kind'] == 'folder' else '')
matches.append(shlex.quote(candidate))
except Failure:
pass
buf = readline.get_line_buffer()
end = readline.get_endidx()
before = buf[:end] if end else text
matches.extend(shell_completions(client, profile.data.get('cwd', '/'), before))
return matches[index] if index < len(matches) else None
readline.set_completer(complete)
readline.parse_and_bind('tab: complete')
while True:
if hasattr(readline, 'set_completion_display_matches_hook'):
def display_matches(substitution, match_list, longest_match_length):
print()
short = [_split_shell_context(m)[2] or m for m in match_list]
print(' '.join(safe_text(s) for s in short))
sys.stdout.write('pages[' + profile.name + ']:' + safe_text(profile.data.get('cwd', '/')) + '> ' + readline.get_line_buffer())
sys.stdout.flush()
readline.set_completion_display_matches_hook(display_matches)
if 'libedit' in (getattr(readline, '__doc__', '') or ''):
readline.parse_and_bind('bind ^I rl_complete')
try:
line = input('pages[' + profile.name + ']:' + safe_text(profile.data.get('cwd', '/')) + '> ')
words = shlex.split(line)
if not words: continue
if words[0] in ('exit', 'quit'): break
if words[0] == 'login': raise Failure('Exit shell and use the login command.')
if words[0] != 'logout' and profile.data.get('expires', 0) <= time.time(): raise Failure('Session expired; log in again.')
execute(client, profile, words)
if words[0] == 'logout': break
except (Failure, ValueError, OSError) as e: print(safe_text(str(e)), file=sys.stderr)
except SystemExit: pass
except KeyboardInterrupt: print()
except EOFError: break
readline.parse_and_bind('bind "^P" "\\x01\\x1f\\x05\\n"')
except Exception:
pass
else:
readline.parse_and_bind('tab: complete')
try:
readline.parse_and_bind(r'"\C-p": "\C-a\x1f\C-e\n"')
except Exception:
pass
pre_input_text = [None]
if hasattr(readline, 'set_pre_input_hook'):
def pre_hook():
if pre_input_text[0]:
readline.insert_text(pre_input_text[0])
readline.redisplay()
pre_input_text[0] = None
readline.set_pre_input_hook(pre_hook)
try:
while True:
try:
line = input('pages[' + profile.name + ']:' + safe_text(profile.data.get('cwd', '/')) + '> ')
if line.startswith('\x1f'):
buf = line[1:]
prefix_str, completed, current, _ = _split_shell_context(buf)
if completed:
init_line = prefix_str
init_query = current
else:
init_line = ''
init_query = buf.strip()
inserted = fuzzy_pick(client, profile, initial_query=init_query, initial_line=init_line)
if inserted:
pre_input_text[0] = inserted
continue
words = shlex.split(line)
if not words: continue
if words[0] in ('exit', 'quit'): break
if words[0] == 'help':
print('Commands: ' + ', '.join(SHELL_COMMANDS) + '. Keys: Tab=complete, Ctrl+P=fuzzy pick.')
continue
if words[0] == 'pick':
inserted = fuzzy_pick(client, profile, initial_query=' '.join(words[1:]))
if inserted:
pre_input_text[0] = inserted
continue
if words[0] == 'login': raise Failure('Exit shell and use the login command.')
if words[0] != 'logout' and profile.data.get('expires', 0) <= time.time(): raise Failure('Session expired; log in again.')
execute(client, profile, words)
if words[0] == 'logout': break
except (Failure, ValueError, OSError) as e: print(safe_text(str(e)), file=sys.stderr)
except SystemExit: pass
except KeyboardInterrupt: print()
except EOFError: break
finally:
if hasattr(readline, 'set_pre_input_hook'):
readline.set_pre_input_hook(None)
if persist_history and hist_path is not None:
_save_shell_history(readline, hist_path)
def main(argv=None):
@@ -1827,6 +2164,10 @@ def main(argv=None):
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.with_open_browser and not login_args.oidc: login.error('--with-open-browser requires --oidc')
elif args.command == 'shell':
shell_parser = argparse.ArgumentParser(prog='pages shell', description='Start an interactive PagesWiki shell.')
shell_parser.add_argument('--history', action='store_true', help='Opt in to saving sanitized non-secret shell history privately')
shell_args = shell_parser.parse_args(args.args)
elif '--help' in args.args:
execute(None, None, [args.command] + args.args); return
with contextlib.ExitStack() as stack:
@@ -1874,7 +2215,7 @@ def main(argv=None):
raise Failure('Session and configured identity differ. Log out before reconnecting.')
if args.command not in ('logout', 'status') and profile.data.get('expires', 0) <= time.time(): raise Failure('Session expired; log out and log in again.')
client = Client(profile.data['origin'], profile.data['token'], lang, insecure=args.insecure)
if args.command == 'shell': shell(client, profile)
if args.command == 'shell': shell(client, profile, persist_history=shell_args.history)
else: execute(client, profile, [args.command] + args.args)