feat(shell): add vi projection, !cmd local execution, and $cmd stream/file projection
This commit is contained in:
1 parent
9a0ebd874f
commit
7176b2c47b
2 files changed
+588
-12
No files matched your search
+187
@@ -1521,6 +1521,193 @@ class RemoteTests(unittest.TestCase):
|
||||
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)
|
||||
|
||||
Reference in new issue
Block a user