Skip to content

Add mechanism for prefixing all cells with a prompt mechanism when transformed to TS #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions runbook/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
__version__ = "0.3.3"
from .add_prompt_preprocessor import AddPromptPreprocessor
55 changes: 55 additions & 0 deletions runbook/add_prompt_preprocessor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import base64

from nbconvert.preprocessors import Preprocessor


class AddPromptPreprocessor(Preprocessor):
"""Add Prompt Preprocessor for Typescript"""

has_import_added = False
# TODO don't re-import a bazillion times
import_statement = """
import { decodeBase64 } from "https://deno.land/[email protected]/encoding/base64.ts";
import { setTheme, printHighlight } from 'npm:@speed-highlight/core/terminal'

await setTheme('default')
const syntaxPrint = async (code: string) => {
return await printHighlight(code, 'ts')
}

"""

def prompt_str(self, base64Code):
return (
f"""
var _promptToRun = `{base64Code}`;
await syntaxPrint(new TextDecoder().decode(decodeBase64(_promptToRun)))
console.log("")
console.log("")
console.log("%cReady to run the above code?", "color: red;")
var _promptResult = prompt("Choose (y/n):");
"""
+ """
if(!_promptResult.match(/y/i)) {
throw Error("You rejected progress")
}
console.log("")
"""
)

def preprocess_cell(self, cell, resources, index):
if "source" in cell and cell.cell_type == "code":
if type(cell.source) is str:
s = [cell.source]
else:
s = cell.source

base64code = base64.b64encode("".join(s).encode("utf-8")).decode("utf-8")
s.insert(0, self.prompt_str(base64code))

if not self.has_import_added:
s.insert(0, self.import_statement)
self.has_import_added = True

cell.source = s
return cell, resources
31 changes: 24 additions & 7 deletions runbook/cli/commands/convert.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import tempfile
from os import path

import click
import nbformat
from runbook.add_prompt_preprocessor import AddPromptPreprocessor
from runbook.cli.completions import EditableNotebook
from runbook.cli.validators import validate_runbook_file_path

Expand All @@ -15,15 +18,29 @@
"output",
type=click.Path(exists=False, file_okay=True, writable=True),
)
@click.option(
"-i",
"--insert-prompts",
default=False,
help="Insert prompt statements at start of each cell",
)
@click.pass_context
def convert(ctx, filename, output):
def convert(ctx, filename, output, insert_prompts):
"""Convert an existing runbook to different format"""
# Must override argv because it's used in launch instance and there isn't a way
# to pass via argument in ExtensionApp.lauch_instance
# TODO:
argv = [path.abspath(filename), "--output", output]
# Lazily loaded for performance
from jupytext.cli import jupytext as jupytext_main

jupytext_main(args=argv)
# TODO: insert post run hooks here
with tempfile.NamedTemporaryFile(suffix=".ipynb") as fp:
content = nbformat.reads(open(filename).read(), as_version=4)
if content.metadata.get("kernelspec").get("name") == "deno":
(nb, _resources) = AddPromptPreprocessor().preprocess(content, {})
else:
nb = content
with tempfile.NamedTemporaryFile(suffix=".ipynb") as fp:
nbformat.write(nb, fp.name)
argv = [path.abspath(fp.name), "--output", output]
# Lazily loaded for performance
from jupytext.cli import jupytext as jupytext_main

print(f"Running jupytext {argv}")
jupytext_main(args=argv)