Skip to content

Commit

Permalink
Collect ANSI sequences (#105)
Browse files Browse the repository at this point in the history
  • Loading branch information
anders-kiaer authored Sep 30, 2019
1 parent 3eda23e commit 86a9289
Show file tree
Hide file tree
Showing 8 changed files with 76 additions and 57 deletions.
32 changes: 16 additions & 16 deletions webviz_config/_build_webviz.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from ._config_parser import ParserError
from ._write_script import write_script
from .themes import installed_themes

from .utils import terminal_colors

BUILD_FILENAME = "webviz_app.py"
STATIC_FOLDER = os.path.join(os.path.dirname(__file__), "static")
Expand Down Expand Up @@ -39,10 +39,10 @@ def build_webviz(args):
try:
if args.portable:
print(
"\033[1m\033[94m"
f"{terminal_colors.BLUE}{terminal_colors.BOLD}"
"Saving requested data to build folder "
"such that the webviz instance is portable."
"\033[0m"
f"{terminal_colors.END}"
)

write_script(
Expand All @@ -63,9 +63,9 @@ def build_webviz(args):
os.remove(os.path.join(build_directory, "copy_data.py"))

print(
"\033[1m\033[94m"
f"{terminal_colors.GREEN}{terminal_colors.BOLD}"
"Finished data extraction. All output saved."
"\033[0m"
f"{terminal_colors.END}"
)

non_default_assets = write_script(
Expand All @@ -87,9 +87,9 @@ def build_webviz(args):
def run_webviz(args, build_directory):

print(
" \n\033[92m"
f"{terminal_colors.YELLOW}"
" Starting up your webviz application. Please wait..."
" \033[0m\n"
f"{terminal_colors.END}"
)

app_process = subprocess.Popen( # nosec
Expand All @@ -108,24 +108,24 @@ def run_webviz(args, build_directory):
args, build_directory, "webviz_template.py.jinja2", BUILD_FILENAME
)
print(
"\033[1m\033[94m"
f"{terminal_colors.BLUE}{terminal_colors.BOLD}"
"Rebuilt webviz dash app from configuration file"
"\033[0m"
f"{terminal_colors.END}"
)

except (ParserError, YAMLError) as e:
print(
f"{e} \033[91m Fix the error and save the "
"configuration file in order to trigger a new "
"rebuild. \033[0m"
f"{e} {terminal_colors.RED}{terminal_colors.BOLD}"
"Fix the error and save the configuration file in "
" order to trigger a new rebuild."
f"{terminal_colors.END}"
)

except Exception as e:
app_process.kill()
print(
"\033[91m"
"Unexpected error. Killing the webviz dash "
"application process."
"\033[0m"
f"{terminal_colors.RED}{terminal_colors.BOLD}"
"Unexpected error. Killing the webviz dash application process."
f"{terminal_colors.END}"
)
raise e
6 changes: 4 additions & 2 deletions webviz_config/_certificate.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import rsa

from .utils import terminal_colors


NAME = x509.Name(
[
Expand Down Expand Up @@ -120,7 +122,7 @@ def create_ca(args):
).upper()

print(
f"""\n\033[1m\033[94m
f"""\n{terminal_colors.BLUE}{terminal_colors.BOLD}
Created CA key and certificate files (both saved in {directory}).
Keep the key file ({CA_KEY_FILENAME}) private. The certificate file
({CA_CRT_FILENAME}) is not sensitive, and you can import it in
Expand All @@ -141,7 +143,7 @@ def create_ca(args):
When done, you do not have to rerun "webviz certificate" or do this procedure
before the certificate expiry date has passed. The certificate is only valid
for localhost and {DNS_NAME}."""
for localhost and {DNS_NAME}.{terminal_colors.END}"""
)


Expand Down
63 changes: 33 additions & 30 deletions webviz_config/_config_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from . import containers as standard_containers
from .containers import WebvizContainer
from .utils import terminal_colors

SPECIAL_ARGS = ["self", "app", "container_settings", "_call_signature", "_imports"]

Expand Down Expand Up @@ -54,49 +55,51 @@ def _call_signature(
for arg in required_args:
if arg not in SPECIAL_ARGS and arg not in kwargs:
raise ParserError(
"\033[91m"
f"{terminal_colors.RED}{terminal_colors.BOLD}"
f"The container `{container_name}` requires "
f"the argument `{arg}` in your configuration "
"file."
"\033[0m"
f"{terminal_colors.END}"
)

for arg in list(kwargs):
if arg in SPECIAL_ARGS:
raise ParserError(
"\033[91m" f"Container argument `{arg}` not allowed." "\033[0m"
f"{terminal_colors.RED}{terminal_colors.BOLD}"
f"Container argument `{arg}` not allowed."
f"{terminal_colors.END}"
)

if arg == "contact_person":
if not isinstance(kwargs["contact_person"], dict):
raise ParserError(
"\033[91m"
f"{terminal_colors.RED}{terminal_colors.BOLD}"
f"The contact information provided for "
f"container `{container_name}` is "
f"not a dictionary. "
"\033[0m"
f"{terminal_colors.END}"
)
elif any(
key not in ["name", "phone", "email"]
for key in kwargs["contact_person"]
):
raise ParserError(
"\033[91m"
f"{terminal_colors.RED}{terminal_colors.BOLD}"
f"Unrecognized contact information key "
f"given to container `{container_name}`."
f'Should be "name", "phone" and/or "email".'
"\033[0m"
f"{terminal_colors.END}"
)
else:
contact_person = kwargs.pop("contact_person")

elif arg not in argspec.args:
raise ParserError(
"\033[91m"
f"{terminal_colors.RED}{terminal_colors.BOLD}"
"Unrecognized argument. The container "
f"`{container_name}` does not take an "
f"argument `{arg}`."
"\033[0m"
f"{terminal_colors.END}"
)

if arg in argspec.annotations:
Expand All @@ -107,13 +110,13 @@ def _call_signature(

if not isinstance(kwargs[arg], expected_type):
raise ParserError(
"\033[91m"
f"{terminal_colors.RED}{terminal_colors.BOLD}"
f"The value provided for argument `{arg}` "
f"given to container `{container_name}` is "
f"of type `{type(kwargs[arg]).__name__}`. "
f"Expected type "
f"`{argspec.annotations[arg].__name__}`."
"\033[0m"
f"{terminal_colors.END}"
)

special_args = ""
Expand Down Expand Up @@ -151,9 +154,9 @@ def __init__(self, yaml_file):
f"line {e.problem_mark.line + 1}."
)

raise type(e)(f"{e}. \033[91m{extra_info}\033[0m").with_traceback(
sys.exc_info()[2]
)
raise type(e)(
f"{e}. {terminal_colors.RED}{terminal_colors.BOLD}{extra_info}{terminal_colors.END}"
).with_traceback(sys.exc_info()[2])

self._config_folder = pathlib.Path(yaml_file).parent
self._page_ids = []
Expand Down Expand Up @@ -193,37 +196,37 @@ def clean_configuration(self):

if "pages" not in self.configuration:
raise ParserError(
"\033[91m"
f"{terminal_colors.RED}{terminal_colors.BOLD}"
"The configuration file does not have "
"information regarding which pages to create."
"\033[0m"
f"{terminal_colors.END}"
)
elif not isinstance(self.configuration["pages"], list):
raise ParserError(
"\033[91m"
f"{terminal_colors.RED}{terminal_colors.BOLD}"
"The configuration input belonging to the "
"`pages` keyword should be a list."
"\033[0m"
f"{terminal_colors.END}"
)

for page_number, page in enumerate(self.configuration["pages"]):

if "title" not in page:
raise ParserError(
"\033[91m"
f"{terminal_colors.RED}{terminal_colors.BOLD}"
f"Page number {page_number + 1} does "
"not have the title specified."
"\033[0m"
f"{terminal_colors.END}"
)

if "id" not in page:
page["id"] = self._generate_page_id(page["title"])
elif page["id"] in self._page_ids:
raise ParserError(
"\033[91m"
f"{terminal_colors.RED}{terminal_colors.BOLD}"
"You have more than one page "
"with the same `id`."
"\033[0m"
f"{terminal_colors.END}"
)

self._page_ids.append(page["id"])
Expand All @@ -232,21 +235,21 @@ def clean_configuration(self):
page["content"] = []
elif not isinstance(page["content"], list):
raise ParserError(
"\033[91m"
f"{terminal_colors.RED}{terminal_colors.BOLD}"
"The content of page number "
f"{page_number + 1} should be a list."
"\033[0m"
f"{terminal_colors.END}"
)

containers = [e for e in page["content"] if isinstance(e, dict)]

for container in containers:
if "container" not in container:
raise ParserError(
"\033[91m"
f"{terminal_colors.RED}{terminal_colors.BOLD}"
"Argument `container`, stating name of "
"the container to include, is required."
"\033[0m"
f"{terminal_colors.END}"
)

kwargs = {**container}
Expand All @@ -255,12 +258,12 @@ def clean_configuration(self):
if "." not in container_name:
if container_name not in ConfigParser.STANDARD_CONTAINERS:
raise ParserError(
"\033[91m"
f"{terminal_colors.RED}{terminal_colors.BOLD}"
"You have included an container with "
f"name `{container_name}` in your "
"configuration file. This is not a "
"standard container."
"\033[0m"
f"{terminal_colors.END}"
)
else:
self.configuration["_imports"].add(
Expand Down Expand Up @@ -289,10 +292,10 @@ def clean_configuration(self):

if container_name not in _get_webviz_containers(module):
raise ParserError(
"\033[91m"
f"{terminal_colors.RED}{terminal_colors.BOLD}"
f"Module `{module}` does not have a "
f"container named `{container_name}`"
"\033[0m"
f"{terminal_colors.END}"
)
else:
self.configuration["_imports"].add(module_name)
Expand Down
5 changes: 3 additions & 2 deletions webviz_config/_localhost_open_browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import webbrowser

from ._is_reload_process import is_reload_process
from .utils import terminal_colors


class LocalhostOpenBrowser:
Expand Down Expand Up @@ -65,10 +66,10 @@ def _open_new_tab(self):
"""

print(
" \n\033[92m"
f"{terminal_colors.GREEN}{terminal_colors.BOLD}"
" Opening the application in your default browser.\n"
" Press CTRL+C in this terminal window to stop the application."
" \033[0m\n"
f"{terminal_colors.END}"
)

webbrowser.open_new_tab(self._login_link)
Empty file added webviz_config/utils/__init__.py
Empty file.
8 changes: 8 additions & 0 deletions webviz_config/utils/terminal_colors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
BLUE = "\x1b[5;37;44m"
GREEN = "\x1b[5;37;42m"
PURPLE = "\x1b[0;37;45m"
RED = "\x1b[5;37;41m"
YELLOW = "\x1b[2;30;43m"

BOLD = "\x1b[1m"
END = "\x1b[0m"
6 changes: 4 additions & 2 deletions webviz_config/webviz_assets.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

import flask

from .utils import terminal_colors


class WebvizAssets:
"""Dash applications by default host static resources from a folder called
Expand Down Expand Up @@ -77,15 +79,15 @@ def make_portable(self, asset_folder):
new_filename = os.path.join(asset_folder, assigned_id)

print(
"\033[94m" f"Copying over {filename} to {new_filename}" "\033[0m",
f"{terminal_colors.PURPLE} Copying over {filename} {terminal_colors.END}",
end="",
flush=True,
)

shutil.copyfile(filename, os.path.join(asset_folder, assigned_id))

print(
f" \033[92m\033[1m[\u2713] Copied ({counter + 1}/{len(self._assets)})\033[0m"
f"{terminal_colors.PURPLE}{terminal_colors.BOLD} [\u2713] Copied ({counter + 1}/{len(self._assets)}){terminal_colors.END}"
)

def _generate_id(self, filename):
Expand Down
13 changes: 8 additions & 5 deletions webviz_config/webviz_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@
import hashlib
import inspect
import pathlib
import pandas as pd
from collections import defaultdict

import pandas as pd

from .utils import terminal_colors


class WebvizStorage:
def __init__(self):
Expand Down Expand Up @@ -156,9 +159,9 @@ def build_store(self):
kwargs = dict(argtuples)

print(
"\033[94m"
f"Running {WebvizStorage.string(func, kwargs)}"
"\033[0m",
f"{terminal_colors.PURPLE}"
f" Running {WebvizStorage.string(func, kwargs)}"
f"{terminal_colors.END}",
end="",
flush=True,
)
Expand All @@ -175,7 +178,7 @@ def build_store(self):

counter += 1
print(
f" \033[92m\033[1m[\u2713] Saved ({counter}/{total_calls})\033[0m"
f"{terminal_colors.PURPLE}{terminal_colors.BOLD}[\u2713] Saved ({counter}/{total_calls}){terminal_colors.END}"
)


Expand Down

0 comments on commit 86a9289

Please sign in to comment.