feat(shell): add vi projection, !cmd local execution, and $cmd stream/file projection

This commit is contained in:
Anya Tokugawa committed 2026-11-30 23:24:46 +09:00
1 parent 9a0ebd874f
commit 7176b2c47b
2 files changed
+588 -12

No files matched your search

+401 -12
View File
@@ -803,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.')
@@ -956,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:
@@ -992,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.')
@@ -1644,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':
@@ -1725,9 +1725,17 @@ 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
editor(editing, addr, args.format)
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)
if local_path.exists() and local_path.stat().st_size > 1 << 20:
@@ -1776,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'),
@@ -1850,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('-'):
@@ -2263,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
@@ -2329,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:]))