import sys
from itertools import chain
class MarkDown:
def __init__(self) -> None:
self.user_input = ""
self.formatted = []
self.commands = ["!help", "!done"]
self.help = [
"Available formatters: plain bold italic header link inline-code ordered-list unordered-list new-line",
"Special commands: !help !done",
]
self.formatters = {
"plain": self.plain,
"bold": self.bold,
"italic": self.italic,
"header": self.header,
"link": self.link,
"inline-code": self.inline,
"ordered-list": self.list,
"unordered-list": self.list,
"new-line": self.new_line,
}
def handle_user_input(self) -> None:
while "!done" not in (user_input := input("- Choose a formatter: ")):
self.user_input = user_input
if self.user_input not in chain(self.commands, self.formatters):
print("Unknown formatting type or command. Please try again")
continue
elif self.user_input == self.commands[0]:
print(*self.help, sep="\n")
elif self.user_input in self.formatters:
self.handle_formatters_call()
self.save_file()
self.exit_program()
def print_formatters(self) -> None:
print(*self.formatted, sep="")
def handle_formatters_call(self) -> None:
self.formatters[self.user_input]()
self.print_formatters()
def plain(self) -> None:
self.formatted.append(input("- Text: "))
def bold(self) -> None:
string_formatted = f"**{input('- Text: ')}**"
self.formatted.append(string_formatted)
def italic(self) -> None:
string_formatted = f"*{input('- Text: ')}*"
self.formatted.append(string_formatted)
def header(self) -> None:
header_level = "#" * int(input("- Level: "))
string_formatted = f"{header_level} {input('- Text: ')}\n"
self.formatted.append(string_formatted)
def link(self) -> None:
label = input("- Label: ")
url = input("- URL: ")
string_formatted = f"[{label}]({url})"
self.formatted.append(string_formatted)
def inline(self) -> None:
string_formatted = f"`{input('- Text: ')}`"
self.formatted.append(string_formatted)
def list(self) -> None:
while True:
try:
rows = int(input("- Number of rows: "))
if rows < 1:
raise ValueError
except ValueError:
print("The number of rows should be greater than zero")
continue
is_ordered = self.user_input == "ordered-list"
for n in range(rows):
number = n + 1
text = f"{input(f'- Row #{number}: ')}"
string_formatted = (
f"{number}. {text}\n" if is_ordered else f"* {text}\n"
)
self.formatted.append(string_formatted)
break
def new_line(self) -> None:
self.formatted.append("\n")
def save_file(self):
with open("output.md", "w") as file:
file.writelines(self.formatted)
@staticmethod
def exit_program() -> None:
sys.exit()
if __name__ == "__main__":
md = MarkDown()
md.handle_user_input()
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
from behave import __version__
from behave.configuration import Configuration, ConfigError
from behave.parser import ParserError
from behave.runner import Runner
from behave.runner_util import print_undefined_step_snippets, \
InvalidFileLocationError, InvalidFilenameError, FileNotFoundError
from behave.textutil import text as _text
import sys
TAG_HELP = """
Scenarios inherit tags declared on the Feature level. The simplest
TAG_EXPRESSION is simply a tag::
--tags @dev
You may even leave off the "@" - behave doesn't mind.
When a tag in a tag expression starts with a ~, this represents boolean NOT::
--tags [email protected]
A tag expression can have several tags separated by a comma, which represents
logical OR::
--tags @dev,@wip
The --tags option can be specified several times, and this represents logical
AND, for instance this represents the boolean expression
"(@foo or not @bar) and @zap"::
--tags @foo,[email protected] --tags @zap.
Beware that if you want to use several negative tags to exclude several tags
you have to use logical AND::
--tags [email protected] --tags [email protected]
""".strip()
# TODO
# Positive tags can be given a threshold to limit the number of occurrences.
# Which can be practical if you are practicing Kanban or CONWIP. This will fail
# if there are more than 3 occurrences of the @qa tag:
#
# --tags @qa:3
# """.strip()
def main(args=None):
config = Configuration(args)
if config.version:
print("behave " + __version__)
return 0
if config.tags_help:
print(TAG_HELP)
return 0
if config.lang_list:
from behave.i18n import languages
iso_codes = languages.keys()
iso_codes.sort()
print("Languages available:")
for iso_code in iso_codes:
native = languages[iso_code]['native'][0]
name = languages[iso_code]['name'][0]
print(u'%s: %s / %s' % (iso_code, native, name))
return 0
if config.lang_help:
from behave.i18n import languages
if config.lang_help not in languages:
print('%s is not a recognised language: try --lang-list' % \
config.lang_help)
return 1
trans = languages[config.lang_help]
print(u"Translations for %s / %s" % (trans['name'][0],
trans['native'][0]))
for kw in trans:
if kw in 'name native'.split():
continue
print(u'%16s: %s' % (kw.title().replace('_', ' '),
u', '.join(w for w in trans[kw] if w != '*')))
return 0
if not config.format:
config.format = [ config.default_format ]
elif config.format and "format" in config.defaults:
# -- CASE: Formatter are specified in behave configuration file.
# Check if formatter are provided on command-line, too.
if len(config.format) == len(config.defaults["format"]):
# -- NO FORMATTER on command-line: Add default formatter.
config.format.append(config.default_format)
if 'help' in config.format:
print_formatters("Available formatters:")
return 0
if len(config.outputs) > len(config.format):
print('CONFIG-ERROR: More outfiles (%d) than formatters (%d).' % \
(len(config.outputs), len(config.format)))
return 1
failed = True
runner = Runner(config)
try:
failed = runner.run()
except ParserError as e:
print(u"ParseError: %s" % e)
except ConfigError as e:
print(u"ConfigError: %s" % e)
except FileNotFoundError as e:
print(u"FileNotFoundError: %s" % e)
except InvalidFileLocationError as e:
print(u"InvalidFileLocationError: %s" % e)
except InvalidFilenameError as e:
print(u"InvalidFilenameError: %s" % e)
except Exception as e:
# -- DIAGNOSTICS:
text = _text(e)
print(u"Exception %s: %s" % (e.__class__.__name__, text))
raise
if config.show_snippets and runner.undefined_steps:
print_undefined_step_snippets(runner.undefined_steps,
colored=config.color)
return_code = 0
if failed:
return_code = 1
return return_code
def print_formatters(title=None, stream=None):
"""
Prints the list of available formatters and their description.
:param title: Optional title (as string).
:param stream: Optional, output stream to use (default: sys.stdout).
"""
from behave.formatter._registry import format_items
from behave.textutil import compute_words_maxsize, text as _text
from operator import itemgetter
if stream is None:
stream = sys.stdout
if title:
stream.write(u"%s\n" % title)
format_items = sorted(format_items(resolved=True), key=itemgetter(0))
format_names = [item[0] for item in format_items]
column_size = compute_words_maxsize(format_names)
schema = u" %-"+ _text(column_size) +"s %s\n"
for name, formatter_class in format_items:
formatter_description = getattr(formatter_class, "description", "")
stream.write(schema % (name, formatter_description))
if __name__ == '__main__':
# -- EXAMPLE: main("--version")
sys.exit(main())