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

+3 -2
View File
@@ -158,11 +158,12 @@ OSの言語からは推測しません。最初に名前付きプロファイル
| `mput LOCAL... REMOTE_PREFIX` | ローカルファイル/globから新規Pageを一括作成(`-r` / `--strip-ext` / `--dry-run`、既存Pathは412で停止) | | `mput LOCAL... REMOTE_PREFIX` | ローカルファイル/globから新規Pageを一括作成(`-r` / `--strip-ext` / `--dry-run`、既存Pathは412で停止) |
| `recover [PATH]` | 退避された原稿の一覧表示・再開・破棄(`--list` / `--edit` / `--discard`) | | `recover [PATH]` | 退避された原稿の一覧表示・再開・破棄(`--list` / `--edit` / `--discard`) |
| `search QUERY` | 権限付きの検索候補 | | `search QUERY` | 権限付きの検索候補 |
| `pick [QUERY]`(シェル内 `Ctrl+P`) | 対話シェルでのファジー検索選択・入力補完・操作 |
| `open ADDRESS` | ブラウザで閲覧。ブラウザ側ログインを使用 | | `open ADDRESS` | ブラウザで閲覧。ブラウザ側ログインを使用 |
| `status` / `logout` | 接続状態表示/セッション失効 | | `status` / `logout` | 接続状態表示/セッション失効 |
`pages --help`、`pages configure --help`、`pages edit --help` で引数を確認できます。 `pages --help`、`pages configure --help`、`pages edit --help`、`pages shell --help` で引数を確認できます。
Tab補完、上下キーのプロセス内履歴に対応。複雑な引用位置の補完、Ctrl+Pのfuzzy UIは後続です。 コマンド名・サブコマンド・引用文字・途中カーソル位置に対応したTab補完、`Ctrl+P`(または `pick`)によるファジー検索選択、上下キーの履歴に対応しています。履歴は既定でプロセス内のみ保持し、`pages shell --history` を明示指定した場合だけ秘密情報を除外して `0600` ファイルへ保存します。
### 言語を指定して編集する ### 言語を指定して編集する
+2
View File
@@ -18,6 +18,8 @@ OIDC入口はサーバーv0.3.0以降。OIDCで認証した利用者への追加
設定のorigin・usernameと保存セッションの対応を検査する。ログイン中の接続先変更はlogoutを先に行う。logoutはサーバーの失効に失敗した場合、成功と報告せず資格情報を残す。パスワード・TOTP・Bearerを引数、URL、履歴、設定表示へ含めない。セッションファイルは平文なので、同じOSユーザーやrootからは保護できない。OS keyringは未対応。 設定のorigin・usernameと保存セッションの対応を検査する。ログイン中の接続先変更はlogoutを先に行う。logoutはサーバーの失効に失敗した場合、成功と報告せず資格情報を残す。パスワード・TOTP・Bearerを引数、URL、履歴、設定表示へ含めない。セッションファイルは平文なので、同じOSユーザーやrootからは保護できない。OS keyringは未対応。
対話シェルの履歴は既定でプロセス内のみに保持する。`pages shell --history` を明示指定した場合のみ、`history/PROFILE.history`(ディレクトリ `0700`、ファイル `0600`、シンボリックリンク拒否)へ保存し、`login` や `Bearer`/`password`/`pw_api_` 等を含む行は保存・読込時に除外する。`Ctrl+P`/`pick` のファジー検索もサーバー側の `GET /_/api/v1/search/suggest` と `GET /_/api/v1/path-picker` を使い、サーバー側認可の範囲のみ候補表示する。
## アドレスと編集 ## アドレスと編集
Pathは到達経路、UUIDはPageの識別子、Revisionは履歴。正本は `/v/raw/path:/...`、`uuid:`、`rev:` で取得する。Wiki正本はHTMLで、編集用Markdownはauthoring射影。children等の展開結果を保存せず、HTMLの保護フェンスを既存変換APIで往復する。 Pathは到達経路、UUIDはPageの識別子、Revisionは履歴。正本は `/v/raw/path:/...`、`uuid:`、`rev:` で取得する。Wiki正本はHTMLで、編集用Markdownはauthoring射影。children等の展開結果を保存せず、HTMLの保護フェンスを既存変換APIで往復する。
+371 -30
View File
@@ -1764,45 +1764,382 @@ def execute(client, profile, words):
else: print(text, end='') 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 import readline
print(safe_text('pages · ' + client.base + ' · ' + profile.data.get('username', '') + ' · ' + client.lang)) 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_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 = [] matches = []
def complete(text, index): def complete(text, index):
if index == 0: if index == 0:
matches.clear() matches.clear()
try: buf = readline.get_line_buffer()
p = semantic(text, profile.data.get('cwd', '/')) end = readline.get_endidx()
parent = p if text.endswith('/') else posixpath.dirname(p) before = buf[:end] if end else text
prefix = '' if text.endswith('/') else posixpath.basename(p) matches.extend(shell_completions(client, profile.data.get('cwd', '/'), before))
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
return matches[index] if index < len(matches) else None return matches[index] if index < len(matches) else None
readline.set_completer(complete) readline.set_completer(complete)
readline.parse_and_bind('tab: complete') if hasattr(readline, 'set_completion_display_matches_hook'):
while True: 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: try:
line = input('pages[' + profile.name + ']:' + safe_text(profile.data.get('cwd', '/')) + '> ') readline.parse_and_bind('bind "^P" "\\x01\\x1f\\x05\\n"')
words = shlex.split(line) except Exception:
if not words: continue pass
if words[0] in ('exit', 'quit'): break else:
if words[0] == 'login': raise Failure('Exit shell and use the login command.') readline.parse_and_bind('tab: complete')
if words[0] != 'logout' and profile.data.get('expires', 0) <= time.time(): raise Failure('Session expired; log in again.') try:
execute(client, profile, words) readline.parse_and_bind(r'"\C-p": "\C-a\x1f\C-e\n"')
if words[0] == 'logout': break except Exception:
except (Failure, ValueError, OSError) as e: print(safe_text(str(e)), file=sys.stderr) pass
except SystemExit: pass pre_input_text = [None]
except KeyboardInterrupt: print() if hasattr(readline, 'set_pre_input_hook'):
except EOFError: break 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): 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.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) 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') 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: elif '--help' in args.args:
execute(None, None, [args.command] + args.args); return execute(None, None, [args.command] + args.args); return
with contextlib.ExitStack() as stack: with contextlib.ExitStack() as stack:
@@ -1874,7 +2215,7 @@ def main(argv=None):
raise Failure('Session and configured identity differ. Log out before reconnecting.') 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.') 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) 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) else: execute(client, profile, [args.command] + args.args)
+112
View File
@@ -1324,6 +1324,118 @@ class RemoteTests(unittest.TestCase):
m['execute'](client, profile, ['mput', str(big_file), '/wiki', '--lang', 'ja']) m['execute'](client, profile, ['mput', str(big_file), '/wiki', '--lang', 'ja'])
create_mock.assert_not_called() create_mock.assert_not_called()
def test_shell_completions_quotes_mid_cursor_and_commands(self):
client = Client('https://example.test', 'token')
def fake_listing(path, prefix=''):
data = {
'/': [
{'name': 'my folder', 'path': '/my folder', 'kind': 'folder'},
{'name': 'my doc', 'path': '/my doc', 'kind': 'file'},
{'name': 'docs', 'path': '/docs', 'kind': 'folder'},
{'name': 'bad\x1bctrl', 'path': '/bad\x1bctrl', 'kind': 'file'},
],
'/docs': [
{'name': 'guide', 'path': '/docs/guide', 'kind': 'file'},
{'name': 'sub dir', 'path': '/docs/sub dir', 'kind': 'folder'},
],
}
entries = [e for e in data.get(path, []) if e['name'].startswith(prefix)]
return {'entries': entries}
with patch.object(client, 'listing', side_effect=fake_listing):
self.assertEqual(m['shell_completions'](client, '/', 'ed'), ['edit'])
self.assertEqual(m['shell_completions'](client, '/', 'm'), ['mget', 'mput'])
self.assertEqual(m['shell_completions'](client, '/', 'task pr'), ['task preferences', 'task project-add', 'task projects'])
self.assertEqual(m['shell_completions'](client, '/', 'cd "my fol'), ['cd "my folder/'])
self.assertEqual(m['shell_completions'](client, '/', "edit 'my d"), ["edit 'my doc'"])
unquoted = m['shell_completions'](client, '/', 'cat my')
self.assertEqual(unquoted, ["cat 'my folder/'", "cat 'my doc'"])
self.assertEqual(m['shell_completions'](client, '/', 'edit docs/gu'), ['edit docs/guide'])
self.assertEqual(m['shell_completions'](client, '/docs', 'ls sub'), ["ls 'sub dir/'"])
self.assertEqual(m['shell_completions'](client, '/', 'edit --l'), [])
self.assertEqual(m['shell_completions'](client, '/', 'cat uuid:123'), [])
def test_fuzzy_pick_ctrl_p_and_opt_in_history(self):
client = Client('https://example.test', 'token')
suggest_items = [
{'path': '/docs/guide', 'label': 'User Guide', 'kind': 'page'},
{'path': '/notes/design', 'label': 'Architecture', 'kind': 'page'},
{'path': '/evil\x07path', 'label': 'Evil', 'kind': 'page'},
]
listing_items = [
{'name': 'local-note', 'path': '/local-note', 'kind': 'file'},
]
def fake_json(route, **kwargs):
self.assertTrue(route.startswith('/_/api/v1/search/suggest?'))
return {'items': suggest_items}
with patch.object(client, 'json', side_effect=fake_json), \
patch.object(client, 'listing', return_value={'entries': listing_items}):
cands = m['_gather_pick_candidates'](client, '/', 'dg')
paths = [c['path'] for c in cands]
self.assertEqual(paths[0], '/docs/guide')
self.assertNotIn('/evil\x07path', paths)
profile = type('P', (), {'name': 'test', 'data': {'cwd': '/', 'expires': time.time() + 600}})()
fake_tty = type('TTY', (), {'isatty': lambda self: True})()
with patch.object(m['sys'], 'stdin', fake_tty), \
patch.object(client, 'json', return_value={'items': suggest_items}), \
patch.object(client, 'listing', return_value={'entries': listing_items}):
with patch('builtins.input', side_effect=['1']), contextlib.redirect_stdout(io.StringIO()):
res = m['fuzzy_pick'](client, profile, initial_query='dg', initial_line='edit ')
self.assertEqual(res, 'edit /docs/guide')
with patch('builtins.input', side_effect=['dg', '1', 'c']), \
patch.dict(m['fuzzy_pick'].__globals__, {'execute': lambda c, p, w: p.data.__setitem__('cwd', w[1])}), \
contextlib.redirect_stdout(io.StringIO()):
res2 = m['fuzzy_pick'](client, profile)
self.assertIsNone(res2)
self.assertEqual(profile.data['cwd'], '/docs/guide')
with patch.object(m['sys'], 'stdin', io.StringIO('')):
with self.assertRaisesRegex(Failure, 'requires a TTY'):
m['fuzzy_pick'](client, profile)
class FakeReadline:
def __init__(self, items=None):
self.items = list(items or [])
self.delims = ''
def set_history_length(self, n): pass
def set_completer_delims(self, d): self.delims = d
def set_completer(self, fn): pass
def parse_and_bind(self, s): pass
def set_completion_display_matches_hook(self, fn): pass
def set_pre_input_hook(self, fn): pass
def get_current_history_length(self): return len(self.items)
def get_history_item(self, i): return self.items[i - 1]
def add_history(self, s): self.items.append(s)
with tempfile.TemporaryDirectory() as root:
fake_rl = FakeReadline()
with patch.dict('sys.modules', {'readline': fake_rl}), \
patch('builtins.input', side_effect=['pwd', 'exit']), \
contextlib.redirect_stdout(io.StringIO()):
m['shell'](client, profile, persist_history=False, history_root=root)
self.assertFalse((Path(root) / 'pages-cli/history').exists())
fake_rl2 = FakeReadline(['ls /docs', 'login', 'cat /a Bearer secret', 'pwd', 'edit pw_api_123'])
with patch.dict('sys.modules', {'readline': fake_rl2}), \
patch('builtins.input', side_effect=['\x1fedit dg', 'exit']), \
patch.dict(m['shell'].__globals__, {'fuzzy_pick': lambda c, p, initial_query='', initial_line='': initial_line + '/docs/guide'}), \
contextlib.redirect_stdout(io.StringIO()):
m['shell'](client, profile, persist_history=True, history_root=root)
hist_file = Path(root) / 'pages-cli/history/test.history'
self.assertTrue(hist_file.exists())
self.assertEqual(stat.S_IMODE(hist_file.parent.stat().st_mode), 0o700)
self.assertEqual(stat.S_IMODE(hist_file.stat().st_mode), 0o600)
saved_lines = hist_file.read_text(encoding='utf-8').splitlines()
self.assertEqual(saved_lines, ['ls /docs', 'pwd'])
loader_rl = FakeReadline()
m['_load_shell_history'](loader_rl, hist_file)
self.assertEqual(loader_rl.items, ['ls /docs', 'pwd'])
hist_file.chmod(0o644)
with self.assertRaisesRegex(Failure, '0600'):
m['_load_shell_history'](FakeReadline(), hist_file)
def oidc_integration(): def oidc_integration():
fixture=json.load(sys.stdin) fixture=json.load(sys.stdin)