Skip to content
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

Add a python based wizard #21

Open
wants to merge 2 commits into
base: master
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 setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
entry_points={
'console_scripts': [
'wyriwyd-test=wyriwyd.__main__:main',
'wyriwydzard-new=wyriwyd.__main__:main_wizard',
],
},
install_requires=requirements,
Expand Down
44 changes: 44 additions & 0 deletions tests/test_interactive.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import os
import sys
import pytest
from contextlib import contextmanager
from wyriwyd.interactive import make_doc_from_session
from io import StringIO


@contextmanager
def replace_streams(instream=None, outstream=None, errstream=None):
inorig = sys.stdin
outorig = sys.stdout
errorig = sys.stderr
if instream:
sys.stdin = instream
if outstream:
sys.stdout = outstream
if errstream:
sys.stderr = errstream
yield
sys.stdin = inorig
sys.stdout = outorig
sys.stderr = errorig

def test_make_doc_from_session(tmpdir):
cmds = ["export MY_VARIABLE='hello world'",
"cd {}".format(str(tmpdir)),
"pwd",
"echo MY_VARIABLE = $MY_VARIABLE",
"pushd ../ && \ \n pwd && \ \n popd",
"exit"]
instream = StringIO("\n".join(cmds))
outstream = StringIO()
with replace_streams(instream=instream, outstream=outstream):
make_doc_from_session(str(tmpdir / "dummy.md"), append=True)
# print(outstream.getvalue())
lines = (tmpdir / "dummy.md").read()
# print(lines)
expect = ["", "", "", str(tmpdir) + "\n"]
expect += ["MY_VARIABLE = hello world\n"]
expect += ["> > {0} {1}\n{0}\n{1}\n".format(os.path.dirname(str(tmpdir)), str(tmpdir))]
expect += [""]
assert outstream.getvalue() == "$ ".join(expect)
# assert False
20 changes: 20 additions & 0 deletions wyriwyd/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from .parser import parse_file
from .checker import check_commands
from .interactive import make_doc_from_session

import logging
logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -36,3 +37,22 @@ def main(args=None):
for error in errors:
print(highlight(error, DiffLexer(), Terminal256Formatter()))
return 1


def prepare_parser_wizard():
from argparse import ArgumentParser
parser = ArgumentParser(description=__doc__)
parser.add_argument("-o", "--outfile", default=None,
help="The path to the output markdown documentation")
parser.add_argument("-a", "--append", default=False, action="store_true",
help="Append to existing documentation, rather than overwrite it")
parser.add_argument("-s", "--skip-blank-output", default=False, action="store_true",
help="""If a command prints no output, don't add a blank \
output section to the documentation""")
return parser


def main_wizard(args=None):
args = prepare_parser_wizard().parse_args(args=args)
make_doc_from_session(**vars(args))
return 0
70 changes: 70 additions & 0 deletions wyriwyd/interactive.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
from six.moves import input
from .executor import ShellExecutor


COMMAND_BLOCK = """\
```bash
{cmd}
```
"""


OUTPUT_BLOCK = """\
```output
{output}
```
"""


class InteractiveSession():
def __init__(self, filename, append=False):
self.file = None
self.mode = "a" if append else "w"
if filename:
self.filename = filename
else:
self.filename = input("Output file name (.md):")

def __enter__(self):
self.file = open(self.filename, self.mode)
self.file.__enter__()
return self

def __exit__(self, cls, value, traceback):
self.file.__exit__(cls, value, traceback)

def __iter__(self):
lines = []
ps1 = "$ "
ps2 = "> "
prompt = ps1
while True:
try:
cmd = input(prompt).strip()
except EOFError:
break
if not cmd or cmd == "exit":
break
lines.append(cmd)
prompt = ps2
if cmd[-1] != '\\':
yield "\n".join(lines)
lines = []
prompt = ps1

def store_command(self, cmd):
self.file.write(COMMAND_BLOCK.format(cmd=cmd))

def store_output(self, out):
self.file.write(OUTPUT_BLOCK.format(output=out))


def make_doc_from_session(outfile, append=False, skip_blank_output=True):
with InteractiveSession(outfile, append) as session, ShellExecutor() as executor:
for cmd in session:
session.store_command(cmd)
output = executor.run_command(cmd)
output = "\n".join(output)
if output or not skip_blank_output:
print(output)
session.store_output(output)