3 Commits
Author SHA1 Message Date
Anya Tokugawa c92531a257 docs: document TUI picker, vi, !cmd, $cmd, and pending server API proposals
Test and release pages-cli / linux (push) Successful in 48s
Test and release pages-cli / macos (push) Skipped
2026-11-30 23:25:12 +09:00
Anya Tokugawa 7176b2c47b feat(shell): add vi projection, !cmd local execution, and $cmd stream/file projection 2026-11-30 23:24:46 +09:00
Anya Tokugawa 9a0ebd874f feat(shell): upgrade Ctrl+P / pick to fzf-like interactive TUI 2026-11-30 23:21:40 +09:00
4 changed files with 915 additions and 31 deletions

No files matched your search

+5 -2
View File
@@ -154,16 +154,19 @@ OSの言語からは推測しません。最初に名前付きプロファイル
| `get ADDRESS LOCAL` | 正本をファイルへ安全保存(`--resume` / `--max-bytes` / `--timeout`、既存ファイルは上書きしない) |
| `mget REMOTE LOCAL_DIR` | リモートPath/glob(`-r` / `--dry-run` / `--resume`)で一括ダウンロード。既存ファイルは上書きしない |
| `edit ADDRESS` | `$EDITOR`で編集。未存在Pathは確認後に新規作成。Wikiはauthoring Markdown、他のテキストは原文 |
| `vi ADDRESS` | ローカルの `vi` を明示起動して編集・CAS保存(未存在時は `$EDITOR` へフォールバック) |
| `put LOCAL ADDRESS --base REVISION_UUID` | 明示した基点RevisionとのCASで更新 |
| `mput LOCAL... REMOTE_PREFIX` | ローカルファイル/globから新規Pageを一括作成(`-r` / `--strip-ext` / `--dry-run`、既存Pathは412で停止) |
| `recover [PATH]` | 退避された原稿の一覧表示・再開・破棄(`--list` / `--edit` / `--discard`) |
| `search QUERY` | 権限付きの検索候補 |
| `pick [QUERY]`(シェル内 `Ctrl+P`) | 対話シェルでのファジー検索選択・入力補完・操作 |
| `pick [QUERY]`(シェル内 `Ctrl+P`) | 対話シェルでのインラインfzf風TUIファジー検索選択・フォルダ展開(`TERM=dumb` 等では行選択へフォールバック) |
| `!COMMAND` / `!cd DIR`(シェル内) | シェルを使わず(`shell=False` で)ローカルコマンドを実行、`!cd` でローカル作業ディレクトリを移動 |
| `$[--stream\|--file] CMD WIKI_PATH`(シェル内) | Wiki上のファイルをローカルアプリへ射影して開く(`vlc`/`mpv` 等はループバックRangeプロキシでストリーミング、その他は読取専用一時ファイル。ローカルファイルは `local:PATH`) |
| `open ADDRESS` | ブラウザで閲覧。ブラウザ側ログインを使用 |
| `status` / `logout` | 接続状態表示/セッション失効 |
`pages --help`、`pages configure --help`、`pages edit --help`、`pages shell --help` で引数を確認できます。
コマンド名・サブコマンド・引用文字・途中カーソル位置に対応したTab補完、`Ctrl+P`(または `pick`)によるファジー検索選択、上下キーの履歴に対応しています。履歴は既定でプロセス内のみ保持し、`pages shell --history` を明示指定した場合だけ秘密情報を除外して `0600` ファイルへ保存します。
コマンド名・サブコマンド・引用文字・途中カーソル位置・`$CMD` の引数に対応したTab補完、`Ctrl+P`(または `pick`)によるfzf風TUIファジー検索選択(文字入力でリアルタイム絞込、`↑/↓`/`Ctrl+J/K`/`Ctrl+N/P` で移動、`Tab` でフォルダ展開、`Enter` で確定、`Esc`/`Ctrl+C` で取消)、上下キーの履歴に対応しています。履歴は既定でプロセス内のみ保持し、`pages shell --history` を明示指定した場合だけ秘密情報を除外して `0600` ファイルへ保存します。
### 言語を指定して編集する
+8 -1
View File
@@ -18,7 +18,9 @@ OIDC入口はサーバーv0.3.0以降。OIDCで認証した利用者への追加
設定の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` を使い、サーバー側認可の範囲のみ候補表示する。
対話シェルの履歴は既定でプロセス内のみに保持する。`pages shell --history` を明示指定した場合のみ、`history/PROFILE.history`(ディレクトリ `0700`、ファイル `0600`、シンボリックリンク拒否)へ保存し、`login` や `Bearer`/`password`/`pw_api_` 等を含む行は保存・読込時に除外する。`Ctrl+P`/`pick` のファジー検索はTTY環境でPOSIX `termios`/`tty` によるインラインTUI(非TTY・`TERM=dumb`時は行選択フォールバック)を提供し、サーバー側の `GET /_/api/v1/search/suggest` と `GET /_/api/v1/path-picker` を使ってサーバー側認可の範囲のみ候補表示する。
対話シェル内の `!CMD`(`!cd` 含む)は `shell=False` でローカル実行し、Bearerトークンや設定秘密情報を追加しない。`$CMD`(`--stream` / `--file`)はWiki上の正本をローカルアプリへ読み取り専用射影する。メディアプレイヤー等(`vlc`/`mpv`/`ffplay` 等、または `--stream` 明示)に対しては、`127.0.0.1` のみに束縛した一時ループバックHTTPプロキシを起動し、推測不能なワンタイムランダムパスへ中継する(子プロセス引数・環境変数へBearerを出さず、`GET`/`HEAD`/`Range` のみを `NoRedirect`・CLI TLSポリシー付きで中継し、子プロセス終了時に即座に待受を閉じる)。ローカルファイル必須のアプリ(または `--file` 明示)に対しては、`0700` 一時ディレクトリ内へ全体SHA-256検証済みの `0400` 読み取り専用一時ファイルを展開し、終了時(例外・異常終了を含む)に必ず削除する。`vi ADDRESS` はローカルの `vi` バイナリ(未存在時は `$EDITOR`)を `shell=False` で起動し、`edit` と同じCAS保存・復旧契約を共有する。
## アドレスと編集
@@ -77,3 +79,8 @@ Viewer面(`/...`)や非正規Projection面(`/v/raw/...`)と分離され
一括転送(`mget` / `mput`)はローカルとリモートのglob対象を明示分離し、1回あたり最大500ファイル・200フォルダを上限とする。`mget` は末尾セグメントのglob(または `--recursive`)でリモートを走査し、`..` や制御文字、シンボリックリンク、宛先ディレクトリ外への出力を拒否し、0700ディレクトリ・0600ファイル・no-clobberで保存する。`mput` はシンボリックリンク・バイナリ・1 MiB超過・重複宛先を送信前に拒否し、各ファイルを `PUT /_/api/v1/pages/path:...`(`If-None-Match: *`)で新規作成のみ行い、既存Pageを無断上書きしない(`--dry-run` で事前確認可)。
CLIの単体・実バイナリ試験は合成データのみを使用する。サーバー側の権限・CAS・OIDC署名検証とGoのHTTP結合テストはPagesWikiリポジトリで管理する。新規Page作成および `mput` には `PUT /_/api/v1/pages/path:...` に対応したサーバーが必要。Windowsの資格情報保護とロック移植、バイナリ大容量アップロードAPIは後続タスク。
### サーバー連携待ちの提案API(設計相談中)
- **アカウント・セッション照会(`whois` / `w` / `last`)**: 既存 `auth_sessions` / `principals` を読み取り専用で返すJSON API(`GET /_/api/v1/auth/whoami`、`GET /_/api/v1/auth/sessions`、`GET /_/api/v1/auth/sessions/history`)をサーバー側と調整中。`token_hash` 等の秘密値は返さず、旧サーバー(`404`/`405`/`501`)への自動フォールバックは行わない。
- **明示的空フォルダ/予約エンティティ(`mkdir` 案3)**: 仮想フォルダ(Page存在に付随する接頭辞)とは別に、全クライアントで共有・永続化できる空フォルダ作成・削除・`path-picker` 統合API(例: `PUT /_/api/v1/folders/path:...` + `If-None-Match: *`、`DELETE /_/api/v1/folders/path:...`)をサーバー側と調整中。
+630 -28
View File
@@ -16,19 +16,28 @@ import getpass
import glob
import hashlib
from html.parser import HTMLParser
from http import server as http_server
import json
import os
from pathlib import Path
import posixpath
import re
import secrets
import select
import shlex
import shutil
import ssl
import stat
import subprocess
import sys
import tempfile
import threading
import time
try:
import termios
import tty
except ImportError:
termios = tty = None
import unicodedata
import urllib.error
import urllib.parse as url
@@ -794,9 +803,9 @@ def private_dir(path):
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:
def run_editor(file, *, command=None):
cmd = list(command) if command is not None else shlex.split(os.environ.get('EDITOR', 'vi'))
if not cmd or subprocess.run(cmd + [str(file)], check=False).returncode:
raise Failure('Editor exited unsuccessfully.')
@@ -947,7 +956,7 @@ def confirm_create(addr, status):
return answer.strip().lower() in ('y', 'yes')
def editor(client, addr, mode):
def editor(client, addr, mode, *, editor_command=None):
creating = False
state = None
try:
@@ -983,7 +992,7 @@ def editor(client, addr, mode):
ctx = {'creating': creating, 'addr': addr, 'state': state, 'lang': lang, 'markdown': markdown}
success = False
try:
run_editor(file)
run_editor(file, command=editor_command)
text = file.read_text(encoding='utf-8')
if text == initial:
print('Unchanged; page was not created.' if creating else 'Unchanged.')
@@ -1635,10 +1644,10 @@ def execute(client, profile, words):
return tasks(client,profile,words[1:])
parser = argparse.ArgumentParser(prog='pages')
sub = parser.add_subparsers(dest='command', required=True)
for command in ('ls', 'cd', 'cat', 'view', 'edit', 'open'):
for command in ('ls', 'cd', 'cat', 'view', 'edit', 'vi', 'open'):
p = sub.add_parser(command)
p.add_argument('path', nargs='?', default='.')
if command == 'edit':
if command in ('edit', 'vi'):
p.add_argument('--format', choices=['auto', 'raw', 'markdown'], default='auto')
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')
elif command == 'cat':
@@ -1716,8 +1725,16 @@ def execute(client, profile, words):
elif cmd == 'open':
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':
elif cmd in ('edit', 'vi'):
editing = Client(client.base, client.token, language(args.lang), insecure=client.insecure) if args.lang else client
if cmd == 'vi':
vi_bin = shutil.which('vi')
if vi_bin:
editor(editing, addr, args.format, editor_command=[vi_bin])
else:
print('vi not found on PATH; falling back to $EDITOR.', file=sys.stderr)
editor(editing, addr, args.format)
else:
editor(editing, addr, args.format)
elif cmd == 'put':
local_path = Path(args.local)
@@ -1767,7 +1784,7 @@ def execute(client, profile, words):
SHELL_COMMANDS = (
'cat', 'cd', 'contacts', 'edit', 'exit', 'get', 'help', 'logout',
'ls', 'mget', 'mput', 'open', 'pick', 'put', 'pwd', 'quit',
'recover', 'search', 'status', 'task', 'view',
'recover', 'search', 'status', 'task', 'vi', 'view',
)
SHELL_SUBCOMMANDS = {
'task': ('add', 'done', 'from-mail', 'list', 'preferences', 'project-add', 'projects', 'reopen', 'report', 'retry', 'show', 'start', 'status', 'stop', 'update'),
@@ -1841,7 +1858,30 @@ def _format_shell_token(candidate, quote_char, *, is_dir=False):
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:
if current.startswith(('!', '$')):
return []
return [prefix_str + cmd for cmd in SHELL_COMMANDS if cmd.startswith(current)]
if completed and completed[0].startswith('!'):
return []
if completed and completed[0].startswith('$'):
if completed[0] == '$':
# Still reading optional launcher flags or the local command name itself.
tokens_after = completed[1:]
idx = 0
has_app = False
while idx < len(tokens_after):
tok = tokens_after[idx]
if tok in ('--stream', '--file'):
idx += 1
elif tok in ('--max-bytes', '--timeout'):
idx += 2
elif tok.startswith(('--max-bytes=', '--timeout=')):
idx += 1
else:
has_app = True
break
if not has_app or idx > len(tokens_after):
return []
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('-'):
@@ -1909,25 +1949,40 @@ def _fuzzy_score(query, text):
return None
def _gather_pick_candidates(client, cwd, query=''):
def _gather_pick_candidates(client, cwd, query='', *, cache=None):
merged = {}
if query.strip():
q = query.strip()
if q:
suggest_cache = cache.setdefault('suggest', {}) if cache is not None else None
if suggest_cache is not None and q in suggest_cache:
suggest_rows = suggest_cache[q]
else:
try:
for item in client.json('/_/api/v1/search/suggest?' + url.urlencode({'q': query.strip()})).get('items', []):
suggest_rows = client.json('/_/api/v1/search/suggest?' + url.urlencode({'q': q})).get('items', [])
except Failure:
suggest_rows = []
if suggest_cache is not None:
suggest_cache[q] = suggest_rows
for item in suggest_rows:
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
list_cache = cache.setdefault('listing', {}) if cache is not None else None
if list_cache is not None and cwd in list_cache:
list_rows = list_cache[cwd]
else:
try:
for item in client.listing(cwd).get('entries', []):
list_rows = client.listing(cwd).get('entries', [])
except Failure:
list_rows = []
if list_cache is not None:
list_cache[cwd] = list_rows
for item in list_rows:
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']
@@ -1935,16 +1990,188 @@ def _gather_pick_candidates(client, cwd, query=''):
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]]
limit = 50 if cache is not None else 20
return [row[2] for row in scored[:limit]]
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', '/')
def _char_width(ch):
if unicodedata.combining(ch):
return 0
return 2 if unicodedata.east_asian_width(ch) in ('F', 'W') else 1
def _truncate_display(text, max_cols):
cleaned = safe_text(text).replace('\n', ' ').replace('\t', ' ')
if max_cols <= 0:
return ''
out = []
cols = 0
for idx, ch in enumerate(cleaned):
w = _char_width(ch)
if cols + w > max_cols:
while out and cols + 1 > max_cols:
cols -= _char_width(out.pop())
if cols + 1 <= max_cols:
out.append('…')
return ''.join(out)
out.append(ch)
cols += w
if idx + 1 < len(cleaned) and cols == max_cols and _char_width(cleaned[idx + 1]) > 0:
while out and cols + 1 > max_cols:
cols -= _char_width(out.pop())
if cols + 1 <= max_cols:
out.append('…')
return ''.join(out)
return ''.join(out)
def _read_tui_key(fd):
b = os.read(fd, 1)
if not b:
return 'CANCEL'
ch = b[0]
if ch == 0x1b:
if not select.select([fd], [], [], 0.03)[0]:
return 'ESC'
nxt = os.read(fd, 1)
if nxt in (b'[', b'O'):
seq = nxt
while len(seq) < 8 and select.select([fd], [], [], 0.03)[0]:
part = os.read(fd, 1)
seq += part
if part[:1].isalpha() or part == b'~':
break
if seq in (b'[A', b'OA'):
return 'UP'
if seq in (b'[B', b'OB'):
return 'DOWN'
if seq == b'[5~':
return 'PGUP'
if seq == b'[6~':
return 'PGDN'
return 'NOOP'
return 'NOOP'
if ch in (0x0d, 0x0a):
return 'ENTER'
if ch in (0x7f, 0x08):
return 'BACKSPACE'
if ch in (0x03, 0x04):
return 'CANCEL'
if ch in (0x10, 0x0b):
return 'UP'
if ch in (0x0e,):
return 'DOWN'
if ch == 0x15:
return 'CLEAR'
if ch == 0x09:
return 'TAB'
if ch < 0x20:
return 'NOOP'
if ch >= 0x80:
needed = 1 if (ch & 0xe0) == 0xc0 else 2 if (ch & 0xf0) == 0xe0 else 3 if (ch & 0xf8) == 0xf0 else 0
buf = bytearray([ch])
for _ in range(needed):
if select.select([fd], [], [], 0.03)[0]:
buf.extend(os.read(fd, 1))
text = buf.decode('utf-8', errors='ignore')
if not text or any(unicodedata.category(c).startswith('C') for c in text):
return 'NOOP'
return ('CHAR', text)
return ('CHAR', chr(ch))
def _run_tui_picker(client, cwd, initial_query='', *, key_reader=None, out=None, term_size=None):
cur_cwd = cwd
query = initial_query
selected = 0
top = 0
cache = {}
stream = out or sys.stdout
while True:
size = term_size() if term_size is not None else shutil.get_terminal_size((80, 24))
cols = max(24, size.columns)
rows = max(8, size.lines)
items = _gather_pick_candidates(client, cur_cwd, query, cache=cache)
if items:
selected = max(0, min(selected, len(items) - 1))
else:
selected = 0
top = 0
height = max(4, rows - 5)
if selected < top:
top = selected
elif selected >= top + height:
top = selected - height + 1
max_w = cols - 1
lines = [
_truncate_display(f'pages fuzzy pick cwd: {cur_cwd} [Enter: select | Tab: folder | Esc: cancel]', max_w),
_truncate_display(f'> {query}', max_w),
_truncate_display(f' {len(items)} matches', max_w),
]
if not items:
lines.append(_truncate_display(' (no matching pages)', max_w))
else:
for idx in range(top, min(len(items), top + height)):
item = items[idx]
suffix = '/' if item['kind'] == 'folder' and not item['path'].endswith('/') else ''
label = f" {item['label']}" if item['label'] and item['label'] != item['path'] else ''
row_text = _truncate_display(f"{'>' if idx == selected else ' '} {item['path']}{suffix}{label} [{item['kind']}]", max_w)
if idx == selected:
lines.append('\x1b[7m' + row_text + '\x1b[0m')
else:
lines.append(row_text)
stream.write('\x1b[H\x1b[J' + '\r\n'.join(lines))
stream.flush()
key = key_reader()
if isinstance(key, tuple) and key[0] == 'CHAR':
query += key[1]
selected = 0
top = 0
elif key == 'BACKSPACE':
if query:
query = query[:-1]
selected = 0
top = 0
elif key == 'CLEAR':
query = ''
selected = 0
top = 0
elif key == 'UP' and items:
selected = max(0, selected - 1)
elif key == 'DOWN' and items:
selected = min(len(items) - 1, selected + 1)
elif key == 'PGUP' and items:
selected = max(0, selected - height)
elif key == 'PGDN' and items:
selected = min(len(items) - 1, selected + height)
elif key == 'TAB' and items and items[selected]['kind'] == 'folder':
cur_cwd = items[selected]['path']
query = ''
selected = 0
top = 0
elif key == 'ENTER':
return items[selected]['path'] if items else None
elif key in ('ESC', 'CANCEL'):
return None
def _tui_fuzzy_pick(client, cwd, initial_query=''):
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
sys.stdout.write('\x1b[?1049h\x1b[?25l')
sys.stdout.flush()
try:
tty.setraw(fd)
return _run_tui_picker(client, cwd, initial_query, key_reader=lambda: _read_tui_key(fd), out=sys.stdout)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
sys.stdout.write('\x1b[?25h\x1b[?1049l')
sys.stdout.flush()
def _line_fuzzy_pick(client, cwd, initial_query='', *, allow_retry=False):
query = initial_query.strip()
first = True
chosen = None
while True:
if not first or not query:
try:
@@ -1958,7 +2185,7 @@ def fuzzy_pick(client, profile, initial_query='', initial_line=''):
items = _gather_pick_candidates(client, cwd, query)
if not items:
print('No matching pages.')
if initial_query and not initial_line:
if initial_query and not allow_retry:
return None
query = ''
continue
@@ -1974,11 +2201,28 @@ def fuzzy_pick(client, profile, initial_query='', initial_line=''):
if sel.isdigit():
num = int(sel)
if 1 <= num <= len(items):
chosen = items[num - 1]['path']
break
return items[num - 1]['path']
print('Selection out of range.')
continue
query = sel
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', '/')
use_tui = (
termios is not None and tty is not None
and sys.stdin.isatty() and sys.stdout.isatty()
and os.environ.get('TERM', '').lower() not in ('', 'dumb')
)
chosen = (
_tui_fuzzy_pick(client, cwd, initial_query)
if use_tui else
_line_fuzzy_pick(client, cwd, initial_query, allow_retry=bool(initial_line))
)
if not chosen:
return None
if initial_line:
return initial_line + shlex.quote(chosen)
try:
@@ -2050,10 +2294,359 @@ def _save_shell_history(readline_mod, path):
tmp.unlink()
STREAM_PROJECT_APPS = frozenset({
'vlc', 'cvlc', 'mpv', 'ffplay', 'mplayer', 'totem', 'celluloid', 'iina', 'smplayer',
})
def run_local_command(cmdline):
body = cmdline.lstrip()[1:].strip()
if not body:
print('Usage: !COMMAND [ARGS...] (or !cd DIR)')
return
argv = shlex.split(body)
if not argv:
print('Usage: !COMMAND [ARGS...] (or !cd DIR)')
return
if argv[0] == 'cd':
if len(argv) > 2:
raise Failure('Usage: !cd [DIR]')
target = os.path.expanduser(argv[1] if len(argv) == 2 else '~')
os.chdir(target)
print(safe_text(os.getcwd()))
return
try:
subprocess.run(argv, check=False)
except FileNotFoundError:
raise Failure('Local command not found: ' + argv[0]) from None
def _project_raw_route(client, addr):
query = '' if client.lang == 'auto' else '?' + url.urlencode({'lang': client.lang})
return '/v/raw/' + url.quote(addr, safe='/:') + query
def _project_filename(addr, headers=None):
name = ''
if headers is not None:
disp = headers.get('Content-Disposition') or ''
m_cd = re.search(r'filename="([^"]+)"', disp)
if m_cd:
name = m_cd.group(1)
if not name and addr.startswith('path:'):
name = posixpath.basename(addr[5:].rstrip('/'))
if not name:
name = addr.split(':', 1)[-1]
name = safe_text(name).replace('\n', '').replace('\t', '')
name = posixpath.basename(name.replace('\\', '/')).strip()
if not name or name in ('.', '..'):
return 'document'
return name
def _parse_project_line(cmdline):
body = cmdline.lstrip()[1:].strip()
if not body:
raise Failure('Usage: $[--stream|--file] COMMAND ARGS...')
tokens = shlex.split(body)
mode = 'auto'
max_bytes = DEFAULT_DOWNLOAD_LIMIT
timeout = DEFAULT_DEADLINE
idx = 0
while idx < len(tokens):
tok = tokens[idx]
if tok == '--stream':
mode = 'stream'
idx += 1
elif tok == '--file':
mode = 'file'
idx += 1
elif tok == '--max-bytes':
if idx + 1 >= len(tokens):
raise Failure('--max-bytes requires a positive integer.')
try:
max_bytes = int(tokens[idx + 1])
except ValueError:
raise Failure('--max-bytes requires a positive integer.') from None
idx += 2
elif tok.startswith('--max-bytes='):
try:
max_bytes = int(tok.split('=', 1)[1])
except ValueError:
raise Failure('--max-bytes requires a positive integer.') from None
idx += 1
elif tok == '--timeout':
if idx + 1 >= len(tokens):
raise Failure('--timeout requires a positive integer.')
try:
timeout = int(tokens[idx + 1])
except ValueError:
raise Failure('--timeout requires a positive integer.') from None
idx += 2
elif tok.startswith('--timeout='):
try:
timeout = int(tok.split('=', 1)[1])
except ValueError:
raise Failure('--timeout requires a positive integer.') from None
idx += 1
elif tok == '--':
idx += 1
break
else:
break
if max_bytes <= 0 or timeout <= 0:
raise Failure('Download limit and timeout must be positive.')
cmd_argv = tokens[idx:]
if not cmd_argv:
raise Failure('Usage: $[--stream|--file] COMMAND ARGS...')
return mode, max_bytes, timeout, cmd_argv
def _resolve_project_args(client, cwd, args):
cwd_names = None
resolved = []
targets = []
for arg in args:
if arg.startswith('local:'):
resolved.append(('literal', arg[6:]))
elif arg.startswith(('path:', 'uuid:', 'rev:')) or arg.startswith('/'):
targets.append(len(resolved))
resolved.append(('wiki', address(arg, cwd)))
elif arg.startswith('-') or '://' in arg or arg in ('.', '..'):
resolved.append(('literal', arg))
else:
if cwd_names is None:
try:
entries = client.listing(cwd).get('entries', [])
except Failure:
entries = []
cwd_names = {item.get('name', '') for item in entries if item.get('name')}
head = arg.split('/', 1)[0]
if head in cwd_names:
targets.append(len(resolved))
resolved.append(('wiki', address(arg, cwd)))
else:
resolved.append(('literal', arg))
if not targets:
raise Failure('Specify at least one Wiki path or address to project (prefix local files with local:).')
return resolved
class _LoopbackRawProxy:
def __init__(self, client):
self.client = client
self.routes = {}
self.server = None
self.thread = None
self.port = 0
def register(self, addr, filename):
token = secrets.token_urlsafe(24)
self.routes[token] = addr
return f'http://127.0.0.1:{self.port}/{token}/{url.quote(filename, safe="")}'
def __enter__(self):
proxy = self
class ProxyHandler(http_server.BaseHTTPRequestHandler):
protocol_version = 'HTTP/1.1'
def log_message(self, format, *args):
return
def _relay(self, method):
if method not in ('GET', 'HEAD'):
self.send_response(405)
self.send_header('Allow', 'GET, HEAD')
self.send_header('Content-Length', '0')
self.send_header('Connection', 'close')
self.end_headers()
self.close_connection = True
return
parts = url.urlsplit(self.path).path.lstrip('/').split('/', 1)
token = parts[0] if parts else ''
addr = None
for candidate_tok, candidate_addr in proxy.routes.items():
if secrets.compare_digest(token, candidate_tok):
addr = candidate_addr
break
if addr is None:
self.send_response(404)
self.send_header('Content-Length', '0')
self.send_header('Connection', 'close')
self.end_headers()
self.close_connection = True
return
req_headers = {'User-Agent': 'pages-cli/' + VERSION}
if proxy.client.token:
req_headers['Authorization'] = 'Bearer ' + proxy.client.token
for hdr in ('Range', 'If-Range'):
val = self.headers.get(hdr)
if val:
req_headers[hdr] = val
upstream_url = proxy.client.base + _project_raw_route(proxy.client, addr)
req = http.Request(upstream_url, None, req_headers, method=method)
try:
resp = proxy.client.opener.open(req, timeout=DEFAULT_TIMEOUT)
except urllib.error.HTTPError as err:
status = err.code
if status in (301, 302, 303, 307, 308):
status = 502
self.send_response(status)
for hdr in ('Content-Type', 'Content-Length', 'Content-Range', 'Accept-Ranges', 'ETag'):
val = err.headers.get(hdr) if err.headers else None
if val:
self.send_header(hdr, val)
self.send_header('Cache-Control', 'private, no-store')
self.send_header('Connection', 'close')
self.end_headers()
self.close_connection = True
err.close()
return
except (OSError, urllib.error.URLError):
self.send_response(502)
self.send_header('Content-Length', '0')
self.send_header('Connection', 'close')
self.end_headers()
self.close_connection = True
return
try:
self.send_response(resp.status)
for hdr in ('Content-Type', 'Content-Length', 'Content-Range', 'Accept-Ranges', 'ETag', 'Last-Modified'):
val = resp.headers.get(hdr)
if val:
self.send_header(hdr, val)
self.send_header('Cache-Control', 'private, no-store')
self.send_header('Connection', 'close')
self.end_headers()
self.close_connection = True
if method == 'GET':
while True:
chunk = resp.read(CHUNK_SIZE)
if not chunk:
break
self.wfile.write(chunk)
self.wfile.flush()
except (BrokenPipeError, ConnectionResetError):
pass
finally:
resp.close()
def do_GET(self):
self._relay('GET')
def do_HEAD(self):
self._relay('HEAD')
def do_POST(self):
self._relay('POST')
def do_PUT(self):
self._relay('PUT')
def do_DELETE(self):
self._relay('DELETE')
class LoopbackServer(http_server.ThreadingHTTPServer):
daemon_threads = True
allow_reuse_address = True
self.server = LoopbackServer(('127.0.0.1', 0), ProxyHandler)
self.port = self.server.server_port
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
self.thread.start()
return self
def __exit__(self, exc_type, exc, tb):
if self.server is not None:
self.server.shutdown()
self.server.server_close()
def run_project_command(client, cwd, cmdline, *, runner=subprocess.run):
mode, max_bytes, timeout, cmd_argv = _parse_project_line(cmdline)
resolved = _resolve_project_args(client, cwd, cmd_argv[1:])
app_name = os.path.basename(cmd_argv[0]).lower()
if mode == 'auto':
mode = 'stream' if app_name in STREAM_PROJECT_APPS else 'file'
if mode == 'stream':
meta = []
for kind, val in resolved:
if kind == 'wiki':
preflight_headers = []
client.stream_request(
_project_raw_route(client, val), method='HEAD', limit=None,
on_headers=lambda st, hdrs, box=preflight_headers: box.append(hdrs),
)
hdrs = preflight_headers[0] if preflight_headers else None
meta.append((val, _project_filename(val, hdrs)))
with _LoopbackRawProxy(client) as proxy:
final_argv = [cmd_argv[0]]
meta_iter = iter(meta)
for kind, val in resolved:
if kind == 'wiki':
addr, fname = next(meta_iter)
final_argv.append(proxy.register(addr, fname))
else:
final_argv.append(val)
try:
runner(final_argv, check=False)
except FileNotFoundError:
raise Failure('Local command not found: ' + cmd_argv[0]) from None
return
directory = Path(tempfile.mkdtemp(prefix='pageswiki-open-'))
created_files = []
try:
os.chmod(directory, 0o700)
used_names = set()
final_argv = [cmd_argv[0]]
for kind, val in resolved:
if kind != 'wiki':
final_argv.append(val)
continue
fname = _project_filename(val)
if fname in used_names:
fname = f'{len(used_names) + 1}-{fname}'
used_names.add(fname)
dest = directory / fname
client.download(val, str(dest), limit=max_bytes, deadline_seconds=timeout)
os.chmod(dest, 0o400)
created_files.append(dest)
final_argv.append(str(dest))
try:
runner(final_argv, check=False)
except FileNotFoundError:
raise Failure('Local command not found: ' + cmd_argv[0]) from None
finally:
for fpath in created_files:
if fpath.exists() and not fpath.is_symlink():
try:
os.chmod(fpath, 0o600)
except OSError:
pass
try:
fpath.unlink()
except OSError:
pass
if directory.exists():
for leftover in directory.iterdir():
if not leftover.is_symlink() and leftover.is_file():
try:
os.chmod(leftover, 0o600)
leftover.unlink()
except OSError:
pass
try:
directory.rmdir()
except OSError:
pass
def shell(client, profile, *, persist_history=False, history_root=None):
import readline
print(safe_text('pages · ' + client.base + ' · ' + profile.data.get('username', '') + ' · ' + client.lang))
print('Type help for commands, Tab to complete, Ctrl+P (or pick) for fuzzy search.')
print('Type help for commands, !cmd for local shell, $cmd for local app projection, Ctrl+P for fuzzy TUI.')
# History remains in memory unless --history is explicitly opted in; login/password commands are not supported here.
readline.set_history_length(200)
hist_path = None
@@ -2116,11 +2709,20 @@ def shell(client, profile, *, persist_history=False, history_root=None):
if inserted:
pre_input_text[0] = inserted
continue
stripped_line = line.lstrip()
if stripped_line.startswith('!'):
run_local_command(stripped_line)
continue
if stripped_line.startswith('$'):
if profile.data.get('expires', 0) <= time.time():
raise Failure('Session expired; log in again.')
run_project_command(client, profile.data.get('cwd', '/'), stripped_line)
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.')
print('Commands: ' + ', '.join(SHELL_COMMANDS) + '. Local: !CMD (!cd), App project: $[--stream|--file] CMD WIKI_PATH. Keys: Tab=complete, Ctrl+P=fuzzy TUI.')
continue
if words[0] == 'pick':
inserted = fuzzy_pick(client, profile, initial_query=' '.join(words[1:]))
+272
View File
@@ -1436,6 +1436,278 @@ class RemoteTests(unittest.TestCase):
with self.assertRaisesRegex(Failure, '0600'):
m['_load_shell_history'](FakeReadline(), hist_file)
def test_fuzzy_pick_tui_navigation_caching_and_fallback(self):
# Full-width display truncation avoids terminal line wrapping on CJK text.
self.assertEqual(m['_truncate_display']('日本語タイトル', 7), '日本語…')
self.assertEqual(m['_truncate_display']('日本語タイトル', 6), '日本…')
self.assertEqual(m['_truncate_display']('abc\x1bdef', 10), 'abcdef')
client = Client('https://example.test', 'token')
suggest_calls = []
listing_calls = []
def fake_json(route, **kwargs):
suggest_calls.append(route)
if 'q=guide' in route:
return {'items': [
{'path': '/docs/guide', 'label': 'User Guide', 'kind': 'page'},
{'path': '/docs/guideline', 'label': 'Guideline', 'kind': 'page'},
]}
return {'items': []}
def fake_listing(path, prefix=''):
listing_calls.append(path)
if path == '/':
return {'entries': [
{'name': 'docs', 'path': '/docs', 'kind': 'folder'},
{'name': 'readme', 'path': '/readme', 'kind': 'file'},
]}
if path == '/docs':
return {'entries': [
{'name': 'intro', 'path': '/docs/intro', 'kind': 'file'},
]}
return {'entries': []}
with patch.object(client, 'json', side_effect=fake_json), \
patch.object(client, 'listing', side_effect=fake_listing):
# Type 'g', 'u', backspace -> 'g', clear, Tab into /docs, then Enter on /docs/intro.
keys = iter([
('CHAR', 'g'), ('CHAR', 'u'), 'BACKSPACE', 'CLEAR',
'ENTER',
])
out = io.StringIO()
res = m['_run_tui_picker'](
client, '/', '', key_reader=lambda: next(keys),
out=out, term_size=lambda: os.terminal_size((80, 12)),
)
self.assertEqual(res, '/docs')
rendered = out.getvalue()
self.assertIn('\x1b[H\x1b[J', rendered)
self.assertIn('\x1b[7m>', rendered)
# Drill down into /docs folder with Tab, then navigate Down/Up without duplicate HTTP calls.
suggest_calls.clear()
listing_calls.clear()
keys2 = iter([
'TAB', 'DOWN', 'UP', 'ENTER',
])
res2 = m['_run_tui_picker'](
client, '/', '', key_reader=lambda: next(keys2),
out=io.StringIO(), term_size=lambda: os.terminal_size((80, 12)),
)
self.assertEqual(res2, '/docs/intro')
self.assertEqual(listing_calls, ['/', '/docs'])
self.assertEqual(suggest_calls, [])
# Multi-step typing and ESC cancel returns None and uses query cache.
suggest_calls.clear()
keys3 = iter([
('CHAR', 'g'), ('CHAR', 'u'), ('CHAR', 'i'), ('CHAR', 'd'), ('CHAR', 'e'),
'DOWN', 'UP', 'ESC',
])
res3 = m['_run_tui_picker'](
client, '/', '', key_reader=lambda: next(keys3),
out=io.StringIO(), term_size=lambda: os.terminal_size((80, 12)),
)
self.assertIsNone(res3)
self.assertEqual(len([c for c in suggest_calls if c.endswith('q=guide')]), 1)
# TERM=dumb falls back to _line_fuzzy_pick even when both stdin and stdout are TTYs.
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(m['sys'], 'stdout', fake_tty), \
patch.dict(os.environ, {'TERM': 'dumb'}), \
patch.dict(m['fuzzy_pick'].__globals__, {'_line_fuzzy_pick': lambda *a, **kw: '/docs/intro', '_tui_fuzzy_pick': lambda *a, **kw: self.fail('should not invoke TUI on TERM=dumb')}):
self.assertEqual(m['fuzzy_pick'](client, profile, initial_line='cat '), 'cat /docs/intro')
def test_vi_local_commands_and_project_stream_or_file(self):
client = Client('https://example.test', 'secret-tok')
profile = type('P', (), {'name': 'test', 'data': {'cwd': '/', 'expires': time.time() + 600}})()
# 1. vi resolves local vi (falling back to $EDITOR) and commits via CAS; completions work for vi/$cmd/!cmd.
snapshot_state = {
'object_uuid': '00000000-0000-0000-0000-000000000001',
'lang': 'en', 'head_revision_uuid': 'rev-1', 'etag': '"rev-1"',
'content_type': 'text/plain', 'body': 'before\n', 'markdown': 'before\n',
}
runs = []
def fake_sub_run(cmd, check=False, **kwargs):
runs.append(cmd)
if cmd and cmd[0] in ('/usr/bin/vi', 'nano'):
Path(cmd[-1]).write_text('after\n', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch.object(client, 'snapshot', return_value=snapshot_state), \
patch.object(client, 'save', return_value={'revision_uuid': 'rev-2'}) as save_mock, \
patch.object(m['shutil'], 'which', return_value='/usr/bin/vi'), \
patch.object(m['subprocess'], 'run', side_effect=fake_sub_run), \
patch.dict(os.environ, {'EDITOR': 'nano'}), \
contextlib.redirect_stdout(io.StringIO()):
m['execute'](client, profile, ['vi', '/note'])
self.assertEqual(runs[0][0], '/usr/bin/vi')
save_mock.assert_called_once()
runs.clear()
with patch.object(client, 'snapshot', return_value=snapshot_state), \
patch.object(client, 'save', return_value={'revision_uuid': 'rev-2'}), \
patch.object(m['shutil'], 'which', return_value=None), \
patch.object(m['subprocess'], 'run', side_effect=fake_sub_run), \
patch.dict(os.environ, {'EDITOR': 'nano'}), \
contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()) as err:
m['execute'](client, profile, ['vi', '/note'])
self.assertEqual(runs[0][0], 'nano')
self.assertIn('falling back to $EDITOR', err.getvalue())
with patch.object(client, 'listing', return_value={'entries': [{'name': 'guide', 'path': '/guide', 'kind': 'file'}]}):
self.assertEqual(m['shell_completions'](client, '/', 'vi g'), ['vi guide'])
self.assertEqual(m['shell_completions'](client, '/', '$vlc g'), ['$vlc guide'])
self.assertEqual(m['shell_completions'](client, '/', '$ --stream '), [])
self.assertEqual(m['shell_completions'](client, '/', '!ls g'), [])
self.assertIn('vi', m['shell_completions'](client, '/', 'v'))
# 2. !cmd runs locally with shell=False and !cd changes local working directory.
orig_cwd = os.getcwd()
with tempfile.TemporaryDirectory() as local_tmp:
real_tmp = os.path.realpath(local_tmp)
try:
with contextlib.redirect_stdout(io.StringIO()) as out:
m['run_local_command']('!cd ' + m['shlex'].quote(real_tmp))
self.assertEqual(os.path.realpath(os.getcwd()), real_tmp)
self.assertEqual(out.getvalue().strip(), real_tmp)
finally:
os.chdir(orig_cwd)
runs.clear()
with patch.object(m['subprocess'], 'run', side_effect=fake_sub_run):
m['run_local_command']('!echo hello world')
self.assertEqual(runs[-1], ['echo', 'hello', 'world'])
with self.assertRaisesRegex(Failure, 'Local command not found'):
m['run_local_command']('!definitely-missing-pages-binary-xyz')
# 3. $cmd stream mode (loopback HTTP Range proxy) and file mode (verified 0400 temp file).
import urllib.error as url_error
import urllib.request as url_request
media_bytes = b'0123456789ABCDEF' * 1024
media_sha = hashlib.sha256(media_bytes).hexdigest()
doc_bytes = b'{"title": "hello"}\n'
doc_sha = hashlib.sha256(doc_bytes).hexdigest()
upstream_auths = []
class RawHandler(BaseHTTPRequestHandler):
protocol_version = 'HTTP/1.1'
def log_message(self, format, *args): return
def _serve(self, head_only=False):
upstream_auths.append(self.headers.get('Authorization'))
path_only = m['url'].urlsplit(self.path).path
if path_only == '/v/raw/path:/movies/clip.mp4':
payload, ctype, sha, etag = media_bytes, 'video/mp4', media_sha, '"m1"'
elif path_only == '/v/raw/path:/data/doc.json':
payload, ctype, sha, etag = doc_bytes, 'application/json', doc_sha, '"d1"'
else:
self.send_response(404); self.send_header('Content-Length', '0'); self.end_headers(); return
rng = self.headers.get('Range')
if rng == 'bytes=2-5':
part = payload[2:6]
self.send_response(206)
self.send_header('Content-Type', ctype)
self.send_header('Content-Range', f'bytes 2-5/{len(payload)}')
self.send_header('Content-Length', str(len(part)))
self.send_header('ETag', etag)
self.send_header('X-PagesWiki-Document-SHA256', sha)
self.end_headers()
if not head_only:
self.wfile.write(part)
return
self.send_response(200)
self.send_header('Content-Type', ctype)
self.send_header('Accept-Ranges', 'bytes')
self.send_header('Content-Length', str(len(payload)))
self.send_header('ETag', etag)
self.send_header('X-PagesWiki-Document-SHA256', sha)
self.end_headers()
if not head_only:
self.wfile.write(payload)
def do_GET(self): self._serve(False)
def do_HEAD(self): self._serve(True)
class Server(ThreadingHTTPServer):
daemon_threads = True
srv = Server(('127.0.0.1', 0), RawHandler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
try:
srv_client = Client(f'http://127.0.0.1:{srv.server_port}', 'secret-tok')
# Stream mode with vlc auto-detection and Range request through loopback proxy.
seen_argv = []
def stream_child(argv, check=False):
seen_argv.extend(argv)
target_url = argv[-1]
self.assertTrue(target_url.startswith('http://127.0.0.1:'))
self.assertTrue(target_url.endswith('/clip.mp4'))
self.assertNotIn('secret-tok', ' '.join(argv))
with url_request.urlopen(target_url, timeout=5) as r:
self.assertEqual(r.status, 200)
self.assertEqual(r.read(), media_bytes)
req = url_request.Request(target_url, headers={'Range': 'bytes=2-5'})
with url_request.urlopen(req, timeout=5) as r:
self.assertEqual(r.status, 206)
self.assertEqual(r.read(), media_bytes[2:6])
bad_url = target_url.rsplit('/', 2)[0] + '/wrong-token/clip.mp4'
with self.assertRaises(url_error.HTTPError) as ctx:
url_request.urlopen(bad_url, timeout=5)
self.assertEqual(ctx.exception.code, 404)
ctx.exception.close()
post_req = url_request.Request(target_url, data=b'x', method='POST')
with self.assertRaises(url_error.HTTPError) as ctx2:
url_request.urlopen(post_req, timeout=5)
self.assertEqual(ctx2.exception.code, 405)
ctx2.exception.close()
with patch.object(srv_client, 'listing', return_value={'entries': [{'name': 'movies', 'path': '/movies', 'kind': 'folder'}]}):
m['run_project_command'](srv_client, '/', '$vlc movies/clip.mp4', runner=stream_child)
self.assertEqual(seen_argv[0], 'vlc')
self.assertTrue(all(a == 'Bearer secret-tok' for a in upstream_auths))
# Proxy closes immediately on child exit.
with self.assertRaises(url_error.URLError):
url_request.urlopen(seen_argv[-1], timeout=2)
# File mode for jq (read-only 0400 temp file, cleaned up afterward) and explicit --file on vlc.
observed_paths = []
def file_child(argv, check=False):
observed_paths.append(list(argv))
fpath = Path(argv[2])
self.assertTrue(fpath.exists())
self.assertEqual(fpath.name, 'doc.json')
self.assertEqual(stat.S_IMODE(fpath.parent.stat().st_mode), 0o700)
self.assertEqual(stat.S_IMODE(fpath.stat().st_mode), 0o400)
self.assertEqual(fpath.read_bytes(), doc_bytes)
raise RuntimeError('simulated child error')
with patch.object(srv_client, 'listing', return_value={'entries': [{'name': 'data', 'path': '/data', 'kind': 'folder'}]}):
with self.assertRaisesRegex(RuntimeError, 'simulated child error'):
m['run_project_command'](srv_client, '/', '$jq .title /data/doc.json local:/tmp/keep.json', runner=file_child)
self.assertEqual(observed_paths[0][:2], ['jq', '.title'])
# Temporary file and directory are removed even when the child fails.
temp_file = Path(observed_paths[0][2])
self.assertEqual(observed_paths[0][3], '/tmp/keep.json')
self.assertFalse(temp_file.exists())
self.assertFalse(temp_file.parent.exists())
# Explicit --file overrides STREAM_PROJECT_APPS (vlc receives a verified local file instead of HTTP URL).
explicit_file_argv = []
def explicit_file_child(argv, check=False):
explicit_file_argv.extend(argv)
self.assertTrue(Path(argv[1]).name == 'clip.mp4')
self.assertEqual(Path(argv[1]).read_bytes(), media_bytes)
m['run_project_command'](srv_client, '/', '$ --file vlc /movies/clip.mp4', runner=explicit_file_child)
self.assertEqual(explicit_file_argv[0], 'vlc')
self.assertFalse(Path(explicit_file_argv[1]).exists())
finally:
srv.shutdown()
srv.server_close()
def oidc_integration():
fixture=json.load(sys.stdin)