Skip to content

Commit e26b598

Browse files
committed
refining --only-code-output
1 parent 4c9fed6 commit e26b598

6 files changed

Lines changed: 42 additions & 13 deletions

File tree

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@
33

44
## v0.7.0 (dev)
55

6+
* Added `--only-code-output` option, which writes code output in JSON Lines
7+
format to stdout as soon as it is available, and does not create a document.
8+
This is intended for use with Codebraid Preview, so that document previews
9+
can be updated during code execution.
10+
611
* Added command-line option `--no-execute` that disables code execution and
712
only uses available cached output.
813

README.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,22 @@ needed in Markdown documents, this can be accomplished by piping the output of
216216

217217
* `--no-execute` — Disables code execution. Only use available cached output.
218218

219+
* `--only-code-output`={format} — Write code output in JSON Lines format to
220+
stdout as soon as it is available, and do not create a document.
221+
222+
This is intended for use with Codebraid Preview, so that document previews
223+
can be updated during code execution. Currently, the only supported format
224+
is `codebraid_preview`. One JSON data object followed by a newline is
225+
written to stdout for each code chunk. In some cases, the data for a chunk
226+
will be resent later if the data relevant for a chunk changes (for example,
227+
if code execution fails after the first chunk runs, but in such a way that
228+
an error message needs to be attached to the first chunk). Data for a chunk
229+
is sent as soon as it is available from code processing, from cache, or from
230+
code execution (as soon as the chunk completes, typically before the session
231+
completes). Additional JSON data may be sent to provide tracking of code
232+
execution progress or information such as metadata. The JSON data provided
233+
for format `codebraid_preview` may change between minor versions.
234+
219235

220236
## Caching
221237

codebraid/cmdline.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212

1313

1414
import argparse
15-
import codecs
1615
import io
1716
import pathlib
1817
import sys
@@ -128,7 +127,7 @@ def print_help(self):
128127

129128
def pandoc(args):
130129
# Stay consistent with Pandoc's requirement of UTF-8
131-
sys.stdin = codecs.getreader('utf_8_sig')(sys.stdin.buffer, 'strict')
130+
sys.stdin = io.TextIOWrapper(sys.stdin.buffer, encoding='utf_8_sig')
132131

133132
other_pandoc_args = []
134133
if vars(args).get('--defaults') is not None:

codebraid/converters/pandoc.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -344,9 +344,12 @@ def __init__(self,
344344
def attr_hash(self):
345345
attr_list = []
346346
attr_list.append('{')
347-
attr_list.append(f'#{self.node_id}')
347+
if self.node_id:
348+
attr_list.append(f'#{self.node_id}')
348349
attr_list.extend(f'.{c}' for c in self.node_classes)
349-
attr_list.extend('"{0}"="{1}"'.format(k.replace('"', '\\"'), v.replace('"', '\\"')) for k, v in self.node_kvpairs)
350+
for k, v in self.node_kvpairs:
351+
v = v.replace('\\', '\\\\').replace('"', '\\"')
352+
attr_list.extend(f'{k}="{v}"')
350353
attr_list.append('}')
351354
attr_str = ' '.join(attr_list)
352355
hasher = hashlib.sha1()
@@ -760,7 +763,7 @@ def _as_markdown_attr(self,
760763
def _as_markdown_inline_code(self, text: str, *, id=None, classes=None, keyval=None, raw=None, protect_start=True):
761764
md_list = []
762765
if protect_start:
763-
md_list.append('[]{.codebraid-protect-inline-start}')
766+
md_list.append('[]{.codebraid-protect-inline=true}')
764767
delim = '`'
765768
while delim in text:
766769
delim += '`'

codebraid/progress.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import collections
1616
import datetime
1717
import json
18+
import sys
1819
import time
1920
import textwrap
2021
from typing import Callable, Deque, Dict, Iterable, List, Optional
@@ -328,14 +329,16 @@ def _print_live_output(self, output: str, *, stream: str, fmter: Optional[Callab
328329

329330

330331
def _print_code_output(self, code_collection: CodeCollection, *, chunk: CodeChunk, check_first_chunk=False):
331-
type = code_collection.type
332-
lang = chunk.options.get('placeholder_lang', chunk.options['lang'] or '')
333-
name = code_collection.name or ''
334332
data = {
335-
'command': 'output',
336-
'key': f'{type}>{lang}>{name}',
333+
'message_type': 'output',
334+
'origin': chunk.origin_name or '',
335+
'code_collection': {
336+
'type': code_collection.type,
337+
'lang': chunk.options.get('placeholder_lang', chunk.options['lang'] or ''),
338+
'name': code_collection.name or '',
339+
},
337340
'inline': chunk.inline,
338-
'index': f'{chunk.index+1}/{len(code_collection.code_chunks)}',
341+
'number': f'{chunk.index+1}/{len(code_collection.code_chunks)}',
339342
'attr_hash': chunk.attr_hash,
340343
'code_hash': chunk.code_hash,
341344
'output': chunk.only_code_output(self._only_code_output),
@@ -346,7 +349,10 @@ def _print_code_output(self, code_collection: CodeCollection, *, chunk: CodeChun
346349
return
347350
elif chunk.index == 0:
348351
self._only_code_output_first_chunk_cache[code_collection.key] = data
349-
print(json.dumps(data), flush=True)
352+
# All data I/O must be UTF-8, following Pandoc
353+
sys.stdout.buffer.write(json.dumps(data).encode('utf8'))
354+
sys.stdout.buffer.write(b'\n')
355+
sys.stdout.buffer.flush()
350356

351357

352358
def _update_message_count(self, code_collection: CodeCollection):

codebraid/version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
# -*- coding: utf-8 -*-
22

33
from .fmtversion import get_version_plus_info
4-
__version__, __version_info__ = get_version_plus_info(0, 7, 0, 'dev', 3)
4+
__version__, __version_info__ = get_version_plus_info(0, 7, 0, 'dev', 4)

0 commit comments

Comments
 (0)