pax_global_header 0000666 0000000 0000000 00000000064 14270441700 0014511 g ustar 00root root 0000000 0000000 52 comment=bbde59525fde41729d93796610295894156bae9a
wasabi-0.10.1/ 0000775 0000000 0000000 00000000000 14270441700 0013036 5 ustar 00root root 0000000 0000000 wasabi-0.10.1/.flake8 0000664 0000000 0000000 00000000135 14270441700 0014210 0 ustar 00root root 0000000 0000000 [flake8]
ignore = E203, E266, E501, E731, W503
max-line-length = 80
select = B,C,E,F,W,T4,B9
wasabi-0.10.1/.gitignore 0000664 0000000 0000000 00000002451 14270441700 0015030 0 ustar 00root root 0000000 0000000 .vscode/
tmp/
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
wasabi-0.10.1/LICENSE 0000664 0000000 0000000 00000002067 14270441700 0014050 0 ustar 00root root 0000000 0000000 The MIT License (MIT)
Copyright (C) 2018 Ines Montani
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
wasabi-0.10.1/MANIFEST.in 0000664 0000000 0000000 00000000020 14270441700 0014564 0 ustar 00root root 0000000 0000000 include LICENSE
wasabi-0.10.1/README.md 0000664 0000000 0000000 00000066627 14270441700 0014336 0 ustar 00root root 0000000 0000000 # wasabi: A lightweight console printing and formatting toolkit
Over the years, I've written countless implementations of coloring and
formatting utilities to output messages in our libraries like
[spaCy](https://spacy.io), [Thinc](https://github.com/explosion/thinc) and
[Prodigy](https://prodi.gy). While there are many other great open-source
options, I've always ended up wanting something slightly different or slightly
custom.
This package is still a work in progress and aims to bundle those utilities in a
standardised way so they can be shared across our other projects. It's super
lightweight, has zero dependencies and works across Python 2 and 3.
[](https://dev.azure.com/explosion-ai/public/_build?definitionId=1)
[](https://pypi.python.org/pypi/wasabi)
[](https://anaconda.org/conda-forge/wasabi)
[](https://github.com/ines/wasabi)
[](https://github.com/ambv/black)
## π¬ FAQ
### Are you going to add more features?
Yes, there's still a few of helpers and features to port over. However, the new
features will be heavily biased by what we (think we) need. I always appreciate
pull requests to improve the existing functionality β but I want to keep this
library as simple, lightweight and specific as possible.
### Can I use this for my projects?
Sure, if you like it, feel free to adopt it! Just keep in mind that the package
is very specific and not intended to be a full-featured and fully customisable
formatting library. If that's what you're looking for, you might want to try
other packages β for example, [`colored`](https://pypi.org/project/colored/),
[`crayons`](https://github.com/kennethreitz/crayons),
[`colorful`](https://github.com/timofurrer/colorful),
[`tabulate`](https://bitbucket.org/astanin/python-tabulate),
[`console`](https://github.com/mixmastamyk/console) or
[`py-term`](https://github.com/gravmatt/py-term), to name a few.
### Why `wasabi`?
I was looking for a short and descriptive name, but everything was already
taken. So I ended up naming this package after one of my rats, Wasabi. π
## βοΈ Installation
```bash
pip install wasabi
```
## π API
### function `msg`
An instance of `Printer`, initialized with the default config. Useful as a quick
shortcut if you don't need to customize initialization.
```python
from wasabi import msg
msg.good("Success!")
```
### class `Printer`
#### method `Printer.__init__`
```python
from wasabi import Printer
msg = Printer()
```
| Argument | Type | Description | Default |
| ----------------- | --------- | ------------------------------------------------------------- | ------------- |
| `pretty` | bool | Pretty-print output with colors and icons. | `True` |
| `no_print` | bool | Don't actually print, just return. | `False` |
| `colors` | dict | Add or overwrite color values, names mapped to `0`-`256`. | `None` |
| `icons` | dict | Add or overwrite icon. Name mapped to unicode. | `None` |
| `line_max` | int | Maximum line length (for divider). | `80` |
| `animation` | str | Steps of loading animation for `Printer.loading`. | `"β β Ήβ Έβ Όβ ΄β ¦β §β β "` |
| `animation_ascii` | str | Alternative animation for ASCII terminals. | `"\|/-\\"` |
| `hide_animation` | bool | Don't display animation, e.g. for logs. | `False` |
| `ignore_warnings` | bool | Don't output messages of type `MESSAGE.WARN`. | `False` |
| `env_prefix` | str | Prefix for environment variables, e.g. `WASABI_LOG_FRIENDLY`. | `"WASABI"` |
| `timestamp` | bool | Add timestamp before output. | `False` |
| **RETURNS** | `Printer` | The initialized printer. | - |
#### method `Printer.text`
```python
msg = Printer()
msg.text("Hello world!")
```
| Argument | Type | Description | Default |
| ---------- | -------------- | ---------------------------------------------------------------------------------------------------------------------- | ------- |
| `title` | str | The main text to print. | `""` |
| `text` | str | Optional additional text to print. | `""` |
| `color` | Β unicode / int | Color name or value. | `None` |
| `icon` | str | Name of icon to add. | `None` |
| `show` | bool | Whether to print or not. Can be used to only output messages under certain condition, e.g. if `--verbose` flag is set. | `True` |
| `spaced` | bool | Whether to add newlines around the output. | `False` |
| `no_print` | bool | Don't actually print, just return. Overwrites global setting. | `False` |
| `exits` | int | If set, perform a system exit with the given code after printing. | `None` |
#### method `Printer.good`, `Printer.fail`, `Printer.warn`, `Printer.info`
Print special formatted messages.
```python
msg = Printer()
msg.good("Success")
msg.fail("Error")
msg.warn("Warning")
msg.info("Info")
```
| Argument | Type | Description | Default |
| -------- | ---- | ---------------------------------------------------------------------------------------------------------------------- | ------- |
| `title` | str | The main text to print. | `""` |
| `text` | str | Optional additional text to print. | `""` |
| `show` | bool | Whether to print or not. Can be used to only output messages under certain condition, e.g. if `--verbose` flag is set. | `True` |
| `exits` | int | If set, perform a system exit with the given code after printing. | `None` |
#### method `Printer.divider`
Print a formatted divider.
```python
msg = Printer()
msg.divider("Heading")
```
| Argument | Type | Description | Default |
| -------- | ---- | ---------------------------------------------------------------------------------------------------------------------- | ------- |
| `text` | str | Headline text. If empty, only the line is printed. | `""` |
| `char` | str | Single line character to repeat. | `"="` |
| `show` | bool | Whether to print or not. Can be used to only output messages under certain condition, e.g. if `--verbose` flag is set. | `True` |
| `icon` | str | Optional icon to use with title. | `None` |
#### contextmanager `Printer.loading`
```python
msg = Printer()
with msg.loading("Loading..."):
# Do something here that takes longer
time.sleep(10)
msg.good("Successfully loaded something!")
```
| Argument | Type | Description | Default |
| -------- | ---- | ---------------------------------- | ----------------- |
| `text` | str | The text to display while loading. | `"Loading..."` |
#### method `Printer.table`, `Printer.row`
See [Tables](#tables).
#### property `Printer.counts`
Get the counts of how often the special printers were fired, e.g.
`MESSAGES.GOOD`. Can be used to print an overview like "X warnings"
```python
msg = Printer()
msg.good("Success")
msg.fail("Error")
msg.warn("Error")
print(msg.counts)
# Counter({'good': 1, 'fail': 2, 'warn': 0, 'info': 0})
```
| Argument | Type | Description |
| ----------- | --------- | ---------------------------------------------------- |
| **RETURNS** | `Counter` | The counts for the individual special message types. |
### Tables
#### function `table`
Lightweight helper to format tabular data.
```python
from wasabi import table
data = [("a1", "a2", "a3"), ("b1", "b2", "b3")]
header = ("Column 1", "Column 2", "Column 3")
widths = (8, 9, 10)
aligns = ("r", "c", "l")
formatted = table(data, header=header, divider=True, widths=widths, aligns=aligns)
```
```
Column 1 Column 2 Column 3
-------- --------- ----------
a1 a2 a3
b1 b2 b3
```
| Argument | Type | Description | Default |
| ----------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | -------- |
| `data` | iterable / dict | The data to render. Either a list of lists (one per row) or a dict for two-column tables. | |
| `header` | iterable | Optional header columns. | `None` |
| `footer` | iterable | Optional footer columns. | `None` |
| `divider` | bool | Show a divider line between header/footer and body. | `False` |
| `widths` | iterable / `"auto"` | Column widths in order. If `"auto"`, widths will be calculated automatically based on the largest value. | `"auto"` |
| `max_col` | int | Maximum column width. | `30` |
| `spacing` | int | Number of spaces between columns. | `3` |
| `aligns` | iterable / unicode | Columns alignments in order. `"l"` (left, default), `"r"` (right) or `"c"` (center). If If a string, value is used for all columns. | `None` |
| `multiline` | bool | If a cell value is a list of a tuple, render it on multiple lines, with one value per line. | `False` |
| `env_prefix` | unicode | Prefix for environment variables, e.g. WASABI_LOG_FRIENDLY. | `"WASABI"` |
| `color_values` | dict | Add or overwrite color values, name mapped to value. | `None` |
| `fg_colors` | iterable | Foreground colors, one per column. None can be specified for individual columns to retain the default background color. | `None` |
| `bg_colors` | iterable | Background colors, one per column. None can be specified for individual columns to retain the default background color. | `None` |
| **RETURNS** | str | The formatted table. | |
#### function `row`
```python
from wasabi import row
data = ("a1", "a2", "a3")
formatted = row(data)
```
```
a1 a2 a3
```
| Argument | Type | Description | Default |
| ----------- | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
| `data` | iterable | The individual columns to format. | |
| `widths` | list / int / `"auto"` | Column widths, either one integer for all columns or an iterable of values. If "auto", widths will be calculated automatically based on the largest value. | `"auto"` |
| `spacing` | int | Number of spaces between columns. | `3` |
| `aligns` | list | Columns alignments in order. `"l"` (left), `"r"` (right) or `"c"` (center). | `None` |
| `env_prefix` | unicode | Prefix for environment variables, e.g. WASABI_LOG_FRIENDLY. | `"WASABI"` |
| `fg_colors` | list | Foreground colors for the columns, in order. None can be specified for individual columns to retain the default foreground color. | `None` |
| `bg_colors` | list | Background colors for the columns, in order. None can be specified for individual columns to retain the default background color. | `None` |
| **RETURNS** | str | The formatted row. | |
### class `TracebackPrinter`
Helper to output custom formatted tracebacks and error messages. Currently used
in [Thinc](https://github.com/explosion/thinc).
#### method `TracebackPrinter.__init__`
Initialize a traceback printer.
```python
from wasabi import TracebackPrinter
tb = TracebackPrinter(tb_base="thinc", tb_exclude=("check.py",))
```
| Argument | Type | Description | Default |
| ----------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------- |
| `color_error` | str / int | Color name or code for errors (passed to `color` helper). | `"red"` |
| `color_tb` | str / int | Color name or code for traceback headline (passed to `color` helper). | `"blue"` |
| `color_highlight` | str / int | Color name or code for highlighted text (passed to `color` helper). | `"yellow"` |
| `indent` | int | Number of spaces to use for indentation. | `2` |
| `tb_base` | str | Name of directory to use to show relative paths. For example, `"thinc"` will look for the last occurence of `"/thinc/"` in a path and only show path to the right of it. | `None` |
| `tb_exclude` | tuple | List of filenames to exclude from traceback. | `tuple()` |
| **RETURNS** | `TracebackPrinter` | The traceback printer. | |
#### method `TracebackPrinter.__call__`
Output custom formatted tracebacks and errors.
```python
from wasabi import TracebackPrinter
import traceback
tb = TracebackPrinter(tb_base="thinc", tb_exclude=("check.py",))
error = tb("Some error", "Error description", highlight="kwargs", tb=traceback.extract_stack())
raise ValueError(error)
```
```
Some error
Some error description
Traceback:
ββ [61] in .env/lib/python3.6/site-packages/pluggy/manager.py
ββββ _multicall [187] in .env/lib/python3.6/site-packages/pluggy/callers.py
ββββββ pytest_fixture_setup [969] in .env/lib/python3.6/site-packages/_pytest/fixtures.py
>>> result = call_fixture_func(fixturefunc, request, kwargs)
```
| Argument | Type | Description | Default |
| ----------- | -------- | ------------------------------------------------------------------------------------------ | ------- |
| `title` | str | The message title. | |
| `*texts` | str | Optional texts to print (one per line). | |
| `highlight` | str | Optional sequence to highlight in the traceback, e.g. the bad value that caused the error. | `False` |
| `tb` | iterable | The traceback, e.g. generated by `traceback.extract_stack()`. | `None` |
| **RETURNS** | str | The formatted traceback. Can be printed or raised by custom exception. | |
### class `MarkdownRenderer`
Helper to create Markdown-formatted content. Will store the blocks added to the Markdown document in order.
```python
from wasabi import MarkdownRenderer
md = MarkdownRenderer()
md.add(md.title(1, "Hello world"))
md.add("This is a paragraph")
print(md.text)
```
### method `MarkdownRenderer.__init__`
Initialize a Markdown renderer.
```python
from wasabi import MarkdownRenderer
md = MarkdownRenderer()
```
| Argument | Type | Description | Default |
| ----------- | ------------------ | ------------------------------ | ------- |
| `no_emoji` | bool | Don't include emoji in titles. | `False` |
| **RETURNS** | `MarkdownRenderer` | The renderer. |
### method `MarkdownRenderer.add`
Add a block to the Markdown document.
```python
from wasabi import MarkdownRenderer
md = MarkdownRenderer()
md.add("This is a paragraph")
```
| Argument | Type | Description | Default |
| -------- | ---- | ------------------- | ------- |
| `text` | str | The content to add. | |
### property `MarkdownRenderer.text`
The rendered Markdown document.
```python
md = MarkdownRenderer()
md.add("This is a paragraph")
print(md.text)
```
| Argument | Type | Description | Default |
| ----------- | ---- | -------------------------------- | ------- |
| **RETURNS** | str | The document as a single string. | |
### method `MarkdownRenderer.table`
Create a Markdown-formatted table.
```python
md = MarkdownRenderer()
table = md.table([("a", "b"), ("c", "d")], ["Column 1", "Column 2"])
md.add(table)
```
```markdown
| Column 1 | Column 2 |
| --- | --- |
| a | b |
| c | d |
```
| Argument | Type | Description | Default |
| ----------- | ----------------------- | ------------------------------------------------------------------------------------ | ------- |
| `data` | Iterable[Iterable[str]] | The body, one iterable per row, containig an interable of column contents. | |
| `header` | Iterable[str] | The column names. | |
| `aligns` | Iterable[str] | Columns alignments in order. `"l"` (left, default), `"r"` (right) or `"c"` (center). | `None` |
| **RETURNS** | str | The table. | |
### method `MarkdownRenderer.title`
Create a Markdown-formatted heading.
```python
md = MarkdownRenderer()
md.add(md.title(1, "Hello world"))
md.add(md.title(2, "Subheading", "π"))
```
```markdown
# Hello world
## π Subheading
```
| Argument | Type | Description | Default |
| ----------- | ---- | -------------------------------------- | ------- |
| `level` | int | The heading level, e.g. `3` for `###`. | |
| `text` | str | The heading text. | |
| `emoji` | str | Optional emoji to show before heading. | `None` |
| **RETURNS** | str | The rendered title. | |
### method `MarkdownRenderer.list`
Create a Markdown-formatted non-nested list.
```python
md = MarkdownRenderer()
md.add(md.list(["item", "other item"]))
md.add(md.list(["first item", "second item"], numbered=True))
```
```markdown
- item
- other item
1. first item
2. second item
```
| Argument | Type | Description | Default |
| ----------- | ------------- | ------------------------------- | ------- |
| `items` | Iterable[str] | The list items. | |
| `numbered` | bool | Whether to use a numbered list. | `False` |
| **RETURNS** | str | The rendered list. | |
### method `MarkdownRenderer.link`
Create a Markdown-formatted link.
```python
md = MarkdownRenderer()
md.add(md.link("Google", "https://google.com"))
```
```markdown
[Google](https://google.com)
```
| Argument | Type | Description | Default |
| ----------- | ---- | ------------------ | ------- |
| `text` | str | The link text. | |
| `url` | str | The link URL. | |
| **RETURNS** | str | The rendered link. | |
### method `MarkdownRenderer.code_block`
Create a Markdown-formatted code block.
```python
md = MarkdownRenderer()
md.add(md.code_block("import spacy", "python"))
```
````markdown
```python
import spacy
```
````
| Argument | Type | Description | Default |
| ----------- | ---- | ------------------------ | ------- |
| `text` | str | The code text. | |
| `lang` | str | Optional code language. | `""` |
| **RETURNS** | str | The rendered code block. | |
### method `MarkdownRenderer.code`, `MarkdownRenderer.bold`, `MarkdownRenderer.italic`
Create a Markdown-formatted text.
```python
md = MarkdownRenderer()
md.add(md.code("import spacy"))
md.add(md.bold("Hello!"))
md.add(md.italic("Emphasis"))
```
```markdown
`import spacy`
**Hello!**
_Emphasis_
```
### Utilities
#### function `color`
```python
from wasabi import color
formatted = color("This is a text", fg="white", bg="green", bold=True)
```
| Argument | Type | Description | Default |
| ----------- | --------- | --------------------------------------------- | ------- |
| `text` | str | The text to be formatted. | - |
| `fg` | str / int | Foreground color. String name or `0` - `256`. | `None` |
| `bg` | str / int | Background color. String name or `0` - `256`. | `None` |
| `bold` | bool | Format the text in bold. | `False` |
| `underline` | bool | Format the text by underlining. | `False` |
| **RETURNS** | str | The formatted string. | |
#### function `wrap`
```python
from wasabi import wrap
wrapped = wrap("Hello world, this is a text.", indent=2)
```
| Argument | Type | Description | Default |
| ----------- | ---- | ------------------------------------------ | ------- |
| `text` | str | The text to wrap. | - |
| `wrap_max` | int | Maximum line width, including indentation. | `80` |
| `indent` | int | Number of spaces used for indentation. | `4` |
| **RETURNS** | str | The wrapped text with line breaks. | |
#### function `diff_strings`
```python
from wasabi import diff_strings
diff = diff_strings("hello world!", "helloo world")
```
| Argument | Type | Description | Default |
| ----------- | --------- | ---------------------------------------------------------------------------- | ------------------ |
| `a` | str | The first string to diff. |
| `b` | str | The second string to diff. |
| `fg` | str / int | Foreground color. String name or `0` - `256`. | `"black"` |
| `bg` | tuple | Background colors as `(insert, delete)` tuple of string name or `0` - `256`. | `("green", "red")` |
| **RETURNS** | str | The formatted diff. | |
### Environment variables
Wasabi also respects the following environment variables. The prefix can be
customised on the `Printer` via the `env_prefix` argument. For example, setting
`env_prefix="SPACY"` will expect the environment variable `SPACY_LOG_FRIENDLY`.
| Name | Description |
| ---------------------- | ------------------------------------------------------ |
| `ANSI_COLORS_DISABLED` | Disable colors. |
| `WASABI_LOG_FRIENDLY` | Make output nicer for logs (no colors, no animations). |
| `WASABI_NO_PRETTY` | Disable pretty printing, e.g. colors and icons. |
## π Run tests
Fork or clone the repo, make sure you have `pytest` installed and then run it on
the package directory. The tests are located in
[`/wasabi/tests`](/wasabi/tests).
```bash
pip install pytest
cd wasabi
python -m pytest wasabi
```
wasabi-0.10.1/azure-pipelines.yml 0000664 0000000 0000000 00000004601 14270441700 0016676 0 ustar 00root root 0000000 0000000 trigger:
batch: true
branches:
include:
- '*'
jobs:
- job: 'Test'
strategy:
matrix:
Python27Linux:
imageName: 'ubuntu-20.04'
python.version: '2.7'
Python27LinuxASCII:
imageName: 'ubuntu-20.04'
python.version: '2.7'
LANG: 'en_US.ascii'
LC_ALL: 'en_US.ascii'
Python27LinuxASCIIPython:
imageName: 'ubuntu-20.04'
python.version: '2.7'
PYTHONIOENCODING: 'ascii'
Python27Windows:
imageName: 'windows-2019'
python.version: '2.7'
Python27Mac:
imageName: 'macOS-10.15'
python.version: '2.7'
Python36Linux:
imageName: 'ubuntu-20.04'
python.version: '3.6'
Python36Windows:
imageName: 'windows-2019'
python.version: '3.6'
Python36Mac:
imageName: 'macOS-10.15'
python.version: '3.6'
Python37Linux:
imageName: 'ubuntu-20.04'
python.version: '3.7'
Python37Windows:
imageName: 'windows-2019'
python.version: '3.7'
Python37Mac:
imageName: 'macOS-10.15'
python.version: '3.7'
Python38Linux:
imageName: 'ubuntu-20.04'
python.version: '3.8'
Python38Windows:
imageName: 'windows-2019'
python.version: '3.8'
Python38Mac:
imageName: 'macOS-10.15'
python.version: '3.8'
Python39Linux:
imageName: 'ubuntu-20.04'
python.version: '3.9'
Python39Windows:
imageName: 'windows-2019'
python.version: '3.9'
Python39Mac:
imageName: 'macOS-10.15'
python.version: '3.9'
Python310Linux:
imageName: 'ubuntu-20.04'
python.version: '3.10'
Python310Windows:
imageName: 'windows-2019'
python.version: '3.10'
maxParallel: 4
pool:
vmImage: $(imageName)
steps:
- task: UsePythonVersion@0
inputs:
versionSpec: '$(python.version)'
architecture: 'x64'
- script: python -m pip install --upgrade pip
displayName: 'Install dependencies'
- script: |
python -c "import locale; print('Preferred encoding:', locale.getpreferredencoding())"
python -c "import sys; print('stdout encoding:', sys.stdout.encoding)"
env
pip install pytest
python -m pytest -s wasabi
displayName: 'Run tests'
- script: python setup.py sdist
displayName: 'Test sdist'
wasabi-0.10.1/requirements.txt 0000664 0000000 0000000 00000000007 14270441700 0016317 0 ustar 00root root 0000000 0000000 pytest
wasabi-0.10.1/setup.py 0000664 0000000 0000000 00000002065 14270441700 0014553 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
from __future__ import unicode_literals
import os
import io
from setuptools import setup, find_packages
def setup_package():
package_name = "wasabi"
root = os.path.abspath(os.path.dirname(__file__))
# Read in package meta from about.py
about_path = os.path.join(root, package_name, "about.py")
with io.open(about_path, encoding="utf8") as f:
about = {}
exec(f.read(), about)
# Get readme
readme_path = os.path.join(root, "README.md")
with io.open(readme_path, encoding="utf8") as f:
readme = f.read()
setup(
name=package_name,
description=about["__summary__"],
long_description=readme,
long_description_content_type="text/markdown",
author=about["__author__"],
author_email=about["__email__"],
url=about["__uri__"],
version=about["__version__"],
license=about["__license__"],
packages=find_packages(),
install_requires=[],
zip_safe=True,
)
if __name__ == "__main__":
setup_package()
wasabi-0.10.1/wasabi/ 0000775 0000000 0000000 00000000000 14270441700 0014304 5 ustar 00root root 0000000 0000000 wasabi-0.10.1/wasabi/__init__.py 0000664 0000000 0000000 00000000626 14270441700 0016421 0 ustar 00root root 0000000 0000000 # coding: utf8
from __future__ import unicode_literals
from .printer import Printer # noqa
from .tables import table, row # noqa
from .traceback_printer import TracebackPrinter # noqa
from .markdown import MarkdownRenderer # noqa
from .util import color, wrap, get_raw_input, format_repr, diff_strings # noqa
from .util import MESSAGES # noqa
from .about import __version__ # noqa
msg = Printer()
wasabi-0.10.1/wasabi/about.py 0000664 0000000 0000000 00000000336 14270441700 0015772 0 ustar 00root root 0000000 0000000 __title__ = "wasabi"
__version__ = "0.10.1"
__summary__ = "A lightweight console printing and formatting toolkit"
__uri__ = "https://ines.io"
__author__ = "Ines Montani"
__email__ = "ines@explosion.ai"
__license__ = "MIT"
wasabi-0.10.1/wasabi/markdown.py 0000664 0000000 0000000 00000006546 14270441700 0016513 0 ustar 00root root 0000000 0000000 # coding: utf8
from __future__ import unicode_literals, print_function
class MarkdownRenderer:
"""Simple helper for generating raw Markdown."""
def __init__(self, no_emoji=False):
"""Initialize the renderer.
no_emoji (bool): Don't show emoji in titles etc.
"""
self.data = []
self.no_emoji = no_emoji
@property
def text(self):
"""RETURNS (str): The Markdown document."""
return "\n\n".join(self.data)
def add(self, content):
"""Add a string to the Markdown document.
content (str): Add content to the document.
"""
self.data.append(content)
def table(self, data, header, aligns=None):
"""Create a Markdown table.
data (Iterable[Iterable[str]]): The body, one iterable per row,
containig an interable of column contents.
header (Iterable[str]): The column names.
RETURNS (str): The rendered table.
"""
if aligns is None:
aligns = ["l"] * len(header)
if len(aligns) != len(header):
err = "Invalid aligns: {} (header length: {})".format(aligns, len(header))
raise ValueError(err)
get_divider = lambda a: ":---:" if a == "c" else "---:" if a == "r" else "---"
head = "| {} |".format(" | ".join(header))
divider = "| {} |".format(
" | ".join(get_divider(aligns[i]) for i in range(len(header)))
)
body = "\n".join("| {} |".format(" | ".join(row)) for row in data)
return "{}\n{}\n{}".format(head, divider, body)
def title(self, level, text, emoji=None):
"""Create a Markdown heading.
level (int): The heading level, e.g. 3 for ###
text (str): The heading text.
emoji (str): Optional emoji to show before heading text, if enabled.
RETURNS (str): The rendered title.
"""
prefix = "{} ".format(emoji) if emoji and not self.no_emoji else ""
return "{} {}{}".format("#" * level, prefix, text)
def list(self, items, numbered=False):
"""Create a non-nested list.
items (Iterable[str]): The list items.
numbered (bool): Whether to use a numbered list.
RETURNS (str): The rendered list.
"""
content = []
for i, item in enumerate(items):
if numbered:
content.append("{}. {}".format(i + 1, item))
else:
content.append("- {}".format(item))
return "\n".join(content)
def link(self, text, url):
"""Create a Markdown link.
text (str): The link text.
url (str): The link URL.
RETURNS (str): The rendered link.
"""
return "[{}]({})".format(text, url)
def code_block(self, text, lang=""):
"""Create a Markdown code block.
text (str): The code text.
lang (str): Optional code language.
RETURNS (str): The rendered code block.
"""
return "```{}\n{}\n```".format(lang, text)
def code(self, text):
"""Create Markdown inline code."""
return self._wrap(text, "`")
def bold(self, text):
"""Create bold text."""
return self._wrap(text, "**")
def italic(self, text):
"""Create italic text."""
return self._wrap(text, "_")
def _wrap(self, text, marker):
return "{}{}{}".format(marker, text, marker)
wasabi-0.10.1/wasabi/printer.py 0000664 0000000 0000000 00000021632 14270441700 0016345 0 ustar 00root root 0000000 0000000 # coding: utf8
from __future__ import unicode_literals, print_function
import datetime
from collections import Counter
from contextlib import contextmanager
from multiprocessing import Process
import itertools
import sys
import time
import os
import traceback
from .tables import table, row
from .util import wrap, supports_ansi, can_render, locale_escape
from .util import MESSAGES, COLORS, ICONS
from .util import color as _color
class Printer(object):
def __init__(
self,
pretty=True,
no_print=False,
colors=None,
icons=None,
line_max=80,
animation="β β Ήβ Έβ Όβ ΄β ¦β §β β ",
animation_ascii="|/-\\",
hide_animation=False,
ignore_warnings=False,
env_prefix="WASABI",
timestamp=False,
):
"""Initialize the command-line printer.
pretty (bool): Pretty-print output (colors, icons).
no_print (bool): Don't actually print, just return.
colors (dict): Add or overwrite color values, name mapped to value.
icons (dict): Add or overwrite icons. Name mapped to unicode icon.
line_max (int): Maximum line length (for divider).
animation (unicode): Steps of loading animation for loading() method.
animation_ascii (unicode): Alternative animation for ASCII terminals.
hide_animation (bool): Don't display animation, e.g. for logs.
ignore_warnings (bool): Do not output messages of type MESSAGE.WARN.
env_prefix (unicode): Prefix for environment variables, e.g.
WASABI_LOG_FRIENDLY.
timestamp (bool): Print a timestamp (default False).
RETURNS (Printer): The initialized printer.
"""
env_log_friendly = os.getenv("{}_LOG_FRIENDLY".format(env_prefix), False)
env_no_pretty = os.getenv("{}_NO_PRETTY".format(env_prefix), False)
self._counts = Counter()
self.pretty = pretty and not env_no_pretty
self.no_print = no_print
self.show_color = supports_ansi() and not env_log_friendly
self.hide_animation = hide_animation or env_log_friendly
self.ignore_warnings = ignore_warnings
self.line_max = line_max
self.colors = dict(COLORS)
self.icons = dict(ICONS)
self.timestamp = timestamp
if colors:
self.colors.update(colors)
if icons:
self.icons.update(icons)
self.anim = animation if can_render(animation) else animation_ascii
@property
def counts(self):
"""Get the counts of how often the special printers were fired,
e.g. MESSAGES.GOOD. Can be used to print an overview like "X warnings".
"""
return self._counts
def good(self, title="", text="", show=True, spaced=False, exits=None):
"""Print a success message."""
return self._get_msg(
title, text, style=MESSAGES.GOOD, show=show, spaced=spaced, exits=exits
)
def fail(self, title="", text="", show=True, spaced=False, exits=None):
"""Print an error message."""
return self._get_msg(
title, text, style=MESSAGES.FAIL, show=show, spaced=spaced, exits=exits
)
def warn(self, title="", text="", show=True, spaced=False, exits=None):
"""Print a warning message."""
return self._get_msg(
title, text, style=MESSAGES.WARN, show=show, spaced=spaced, exits=exits
)
def info(self, title="", text="", show=True, spaced=False, exits=None):
"""Print an informational message."""
return self._get_msg(
title, text, style=MESSAGES.INFO, show=show, spaced=spaced, exits=exits
)
def text(
self,
title="",
text="",
color=None,
bg_color=None,
icon=None,
spaced=False,
show=True,
no_print=False,
exits=None,
):
"""Print a message.
title (unicode): The main text to print.
text (unicode): Optional additional text to print.
color (unicode / int): Foreground color.
bg_color (unicode / int): Background color.
icon (unicode): Name of icon to add.
spaced (unicode): Whether to add newlines around the output.
show (bool): Whether to print or not. Can be used to only output
messages under certain condition, e.g. if --verbose flag is set.
no_print (bool): Don't actually print, just return.
exits (int): Perform a system exit.
"""
if not show:
return
if self.pretty:
color = self.colors.get(color, color)
bg_color = self.colors.get(bg_color, bg_color)
icon = self.icons.get(icon)
if icon:
title = locale_escape("{} {}".format(icon, title)).strip()
if self.show_color:
title = _color(title, fg=color, bg=bg_color)
title = wrap(title, indent=0)
if text:
title = "{}\n{}".format(title, wrap(text, indent=0))
if self.timestamp:
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
title = "{}\t{}".format(now, title)
if exits is not None or spaced:
title = "\n{}\n".format(title)
if not self.no_print and not no_print:
print(title)
if exits is not None:
sys.stdout.flush()
sys.stderr.flush()
if self.no_print or no_print and exits != 0:
try:
raise RuntimeError(title.strip())
except Exception as e:
# Remove wasabi from the traceback and re-raise
tb = "\n".join(traceback.format_stack()[:-3])
raise SystemExit("{}\n{}".format(tb, e))
sys.exit(exits)
if self.no_print or no_print:
return title
def divider(self, text="", char="=", show=True, icon=None):
"""Print a divider with a headline:
============================ Headline here ===========================
text (unicode): Headline text. If empty, only the line is printed.
char (unicode): Line character to repeat, e.g. =.
show (bool): Whether to print or not.
icon (unicode): Optional icon to display with title.
"""
if not show:
return
if len(char) != 1:
raise ValueError(
"Divider chars need to be one character long. "
"Received: {}".format(char)
)
if self.pretty:
icon = self.icons.get(icon)
if icon:
text = locale_escape("{} {}".format(icon, text)).strip()
deco = char * (int(round((self.line_max - len(text))) / 2) - 2)
text = " {} ".format(text) if text else ""
text = _color(
"\n{deco}{text}{deco}".format(deco=deco, text=text), bold=True
)
if len(text) < self.line_max:
text = text + char * (self.line_max - len(text))
if self.no_print:
return text
print(text)
def table(self, data, **kwargs):
"""Print data as a table.
data (iterable / dict): The data to render. Either a list of lists
(one per row) or a dict for two-column tables.
kwargs: Table settings. See tables.table for details.
"""
title = kwargs.pop("title", None)
text = table(data, **kwargs)
if title:
self.divider(title)
if self.no_print:
return text
print(text)
def row(self, data, **kwargs):
"""Print a table row.
data (iterable): The individual columns to format.
kwargs: Row settings. See tables.row for details.
"""
text = row(data, **kwargs)
if self.no_print:
return text
print(text)
@contextmanager
def loading(self, text="Loading..."):
if self.no_print:
yield
elif self.hide_animation:
print(text)
yield
else:
sys.stdout.flush()
t = Process(target=self._spinner, args=(text,))
t.start()
try:
yield
except Exception as e:
# Handle exception inside the with block
t.terminate()
sys.stdout.write("\n")
raise (e)
t.terminate()
sys.stdout.write("\r\x1b[2K") # erase line
sys.stdout.flush()
def _spinner(self, text="Loading..."):
for char in itertools.cycle(self.anim):
sys.stdout.write("\r{} {}".format(char, text))
sys.stdout.flush()
time.sleep(0.1)
def _get_msg(self, title, text, style=None, show=None, spaced=False, exits=None):
if self.ignore_warnings and style == MESSAGES.WARN:
show = False
self._counts[style] += 1
return self.text(
title, text, color=style, icon=style, show=show, spaced=spaced, exits=exits
)
wasabi-0.10.1/wasabi/tables.py 0000664 0000000 0000000 00000013335 14270441700 0016135 0 ustar 00root root 0000000 0000000 # coding: utf8
from __future__ import unicode_literals, print_function
import os
from .util import COLORS
from .util import color as _color
from .util import supports_ansi, to_string, zip_longest, basestring_
ALIGN_MAP = {"l": "<", "r": ">", "c": "^"}
def table(
data,
header=None,
footer=None,
divider=False,
widths="auto",
max_col=30,
spacing=3,
aligns=None,
multiline=False,
env_prefix="WASABI",
color_values=None,
fg_colors=None,
bg_colors=None,
):
"""Format tabular data.
data (iterable / dict): The data to render. Either a list of lists (one per
row) or a dict for two-column tables.
header (iterable): The header columns.
footer (iterable): The footer columns.
divider (bool): Show a divider line between header/footer and body.
widths (iterable or 'auto'): Column widths in order. If "auto", widths
will be calculated automatically based on the largest value.
max_col (int): Maximum column width.
spacing (int): Spacing between columns, in spaces.
aligns (iterable / unicode): Column alignments in order. 'l' (left,
default), 'r' (right) or 'c' (center). If a string, value is used
for all columns.
multiline (bool): If a cell value is a list of a tuple, render it on
multiple lines, with one value per line.
env_prefix (unicode): Prefix for environment variables, e.g.
WASABI_LOG_FRIENDLY.
color_values (dict): Add or overwrite color values, name mapped to value.
fg_colors (iterable): Foreground colors, one per column. None can be specified
for individual columns to retain the default foreground color.
bg_colors (iterable): Background colors, one per column. None can be specified
for individual columns to retain the default background color.
RETURNS (unicode): The formatted table.
"""
if fg_colors is not None or bg_colors is not None:
colors = dict(COLORS)
if color_values is not None:
colors.update(color_values)
if fg_colors is not None:
fg_colors = [colors.get(fg_color, fg_color) for fg_color in fg_colors]
if bg_colors is not None:
bg_colors = [colors.get(bg_color, bg_color) for bg_color in bg_colors]
if isinstance(data, dict):
data = list(data.items())
if multiline:
zipped_data = []
for i, item in enumerate(data):
vals = [v if isinstance(v, (list, tuple)) else [v] for v in item]
zipped_data.extend(list(zip_longest(*vals, fillvalue="")))
if i < len(data) - 1:
zipped_data.append(["" for i in item])
data = zipped_data
if widths == "auto":
widths = _get_max_widths(data, header, footer, max_col)
settings = {
"widths": widths,
"spacing": spacing,
"aligns": aligns,
"env_prefix": env_prefix,
"fg_colors": fg_colors,
"bg_colors": bg_colors,
}
divider_row = row(["-" * width for width in widths], **settings)
rows = []
if header:
rows.append(row(header, **settings))
if divider:
rows.append(divider_row)
for i, item in enumerate(data):
rows.append(row(item, **settings))
if footer:
if divider:
rows.append(divider_row)
rows.append(row(footer, **settings))
return "\n{}\n".format("\n".join(rows))
def row(
data,
widths="auto",
spacing=3,
aligns=None,
env_prefix="WASABI",
fg_colors=None,
bg_colors=None,
):
"""Format data as a table row.
data (iterable): The individual columns to format.
widths (list, int or 'auto'): Column widths, either one integer for all
columns or an iterable of values. If "auto", widths will be calculated
automatically based on the largest value.
spacing (int): Spacing between columns, in spaces.
aligns (list / unicode): Column alignments in order. 'l' (left,
default), 'r' (right) or 'c' (center). If a string, value is used
for all columns.
env_prefix (unicode): Prefix for environment variables, e.g.
WASABI_LOG_FRIENDLY.
fg_colors (list): Foreground colors for the columns, in order. None can be
specified for individual columns to retain the default foreground color.
bg_colors (list): Background colors for the columns, in order. None can be
specified for individual columns to retain the default background color.
RETURNS (unicode): The formatted row.
"""
env_log_friendly = os.getenv("{}_LOG_FRIENDLY".format(env_prefix), False)
show_colors = (
supports_ansi()
and not env_log_friendly
and (fg_colors is not None or bg_colors is not None)
)
cols = []
if isinstance(aligns, basestring_): # single align value
aligns = [aligns for _ in data]
if not hasattr(widths, "__iter__") and widths != "auto": # single number
widths = [widths for _ in range(len(data))]
for i, col in enumerate(data):
align = ALIGN_MAP.get(aligns[i] if aligns and i < len(aligns) else "l")
col_width = len(col) if widths == "auto" else widths[i]
tpl = "{:%s%d}" % (align, col_width)
col = tpl.format(to_string(col))
if show_colors:
fg = fg_colors[i] if fg_colors is not None else None
bg = bg_colors[i] if bg_colors is not None else None
col = _color(col, fg=fg, bg=bg)
cols.append(col)
return (" " * spacing).join(cols)
def _get_max_widths(data, header, footer, max_col):
all_data = list(data)
if header:
all_data.append(header)
if footer:
all_data.append(footer)
widths = [[len(to_string(col)) for col in item] for item in all_data]
return [min(max(w), max_col) for w in list(zip(*widths))]
wasabi-0.10.1/wasabi/tests/ 0000775 0000000 0000000 00000000000 14270441700 0015446 5 ustar 00root root 0000000 0000000 wasabi-0.10.1/wasabi/tests/__init__.py 0000664 0000000 0000000 00000000000 14270441700 0017545 0 ustar 00root root 0000000 0000000 wasabi-0.10.1/wasabi/tests/test_markdown.py 0000664 0000000 0000000 00000002334 14270441700 0020703 0 ustar 00root root 0000000 0000000 # coding: utf8
from __future__ import unicode_literals, print_function
from wasabi.markdown import MarkdownRenderer
import pytest
def test_markdown():
md = MarkdownRenderer()
md.add(md.title(1, "Title"))
md.add("Paragraph with {}".format(md.bold("bold")))
md.add(md.list(["foo", "bar"]))
md.add(md.table([("a", "b"), ("c", "d")], ["foo", "bar"]))
md.add(md.code_block('import spacy\n\nnlp = spacy.blank("en")', "python"))
md.add(md.list(["first", "second"], numbered=True))
expected = """# Title\n\nParagraph with **bold**\n\n- foo\n- bar\n\n| foo | bar |\n| --- | --- |\n| a | b |\n| c | d |\n\n```python\nimport spacy\n\nnlp = spacy.blank("en")\n```\n\n1. first\n2. second"""
assert md.text == expected
def test_markdown_table_aligns():
md = MarkdownRenderer()
md.add(md.table([("a", "b", "c")], ["foo", "bar", "baz"], aligns=("c", "r", "l")))
expected = """| foo | bar | baz |\n| :---: | ---: | --- |\n| a | b | c |"""
assert md.text == expected
with pytest.raises(ValueError):
md.table([("a", "b", "c")], ["foo", "bar", "baz"], aligns=("c", "r"))
with pytest.raises(ValueError):
md.table([("a", "b", "c")], ["foo", "bar", "baz"], aligns=("c", "r", "l", "l"))
wasabi-0.10.1/wasabi/tests/test_printer.py 0000664 0000000 0000000 00000016402 14270441700 0020545 0 ustar 00root root 0000000 0000000 # coding: utf8
from __future__ import unicode_literals, print_function
import re
import pytest
import time
import os
from wasabi.printer import Printer
from wasabi.util import MESSAGES, NO_UTF8, supports_ansi
SUPPORTS_ANSI = supports_ansi()
def test_printer():
p = Printer(no_print=True)
text = "This is a test."
good = p.good(text)
fail = p.fail(text)
warn = p.warn(text)
info = p.info(text)
assert p.text(text) == text
if SUPPORTS_ANSI and not NO_UTF8:
assert good == "\x1b[38;5;2m\u2714 {}\x1b[0m".format(text)
assert fail == "\x1b[38;5;1m\u2718 {}\x1b[0m".format(text)
assert warn == "\x1b[38;5;3m\u26a0 {}\x1b[0m".format(text)
assert info == "\x1b[38;5;4m\u2139 {}\x1b[0m".format(text)
if SUPPORTS_ANSI and NO_UTF8:
assert good == "\x1b[38;5;2m[+] {}\x1b[0m".format(text)
assert fail == "\x1b[38;5;1m[x] {}\x1b[0m".format(text)
assert warn == "\x1b[38;5;3m[!] {}\x1b[0m".format(text)
assert info == "\x1b[38;5;4m[i] {}\x1b[0m".format(text)
if not SUPPORTS_ANSI and not NO_UTF8:
assert good == "\u2714 {}".format(text)
assert fail == "\u2718 {}".format(text)
assert warn == "\u26a0 {}".format(text)
assert info == "\u2139 {}".format(text)
if not SUPPORTS_ANSI and NO_UTF8:
assert good == "[+] {}".format(text)
assert fail == "[x] {}".format(text)
assert warn == "[!] {}".format(text)
assert info == "[i] {}".format(text)
def test_printer_print():
p = Printer()
text = "This is a test."
p.good(text)
p.fail(text)
p.info(text)
p.text(text)
def test_printer_print_timestamp():
p = Printer(no_print=True, timestamp=True)
result = p.info("Hello world")
matches = re.match("^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}", result)
assert matches
def test_printer_no_pretty():
p = Printer(no_print=True, pretty=False)
text = "This is a test."
assert p.good(text) == text
assert p.fail(text) == text
assert p.warn(text) == text
assert p.info(text) == text
assert p.text(text) == text
def test_printer_custom():
colors = {"yellow": 220, "purple": 99}
icons = {"warn": "\u26a0\ufe0f", "question": "?"}
p = Printer(no_print=True, colors=colors, icons=icons)
text = "This is a test."
purple_question = p.text(text, color="purple", icon="question")
warning = p.warn(text)
if SUPPORTS_ANSI and not NO_UTF8:
assert purple_question == "\x1b[38;5;99m? {}\x1b[0m".format(text)
assert warning == "\x1b[38;5;3m\u26a0\ufe0f {}\x1b[0m".format(text)
if SUPPORTS_ANSI and NO_UTF8:
assert purple_question == "\x1b[38;5;99m? {}\x1b[0m".format(text)
assert warning == "\x1b[38;5;3m?? {}\x1b[0m".format(text)
if not SUPPORTS_ANSI and not NO_UTF8:
assert purple_question == "? {}".format(text)
assert warning == "\u26a0\ufe0f {}".format(text)
if not SUPPORTS_ANSI and NO_UTF8:
assert purple_question == "? {}".format(text)
assert warning == "?? {}".format(text)
def test_color_as_int():
p = Printer(no_print=True)
text = "This is a text."
result = p.text(text, color=220)
if SUPPORTS_ANSI:
assert result == "\x1b[38;5;220mThis is a text.\x1b[0m"
else:
assert result == "This is a text."
def test_bg_color():
p = Printer(no_print=True)
text = "This is a text."
result = p.text(text, bg_color="red")
print(result)
if SUPPORTS_ANSI:
assert result == "\x1b[48;5;1mThis is a text.\x1b[0m"
else:
assert result == "This is a text."
def test_bg_color_as_int():
p = Printer(no_print=True)
text = "This is a text."
result = p.text(text, bg_color=220)
print(result)
if SUPPORTS_ANSI:
assert result == "\x1b[48;5;220mThis is a text.\x1b[0m"
else:
assert result == "This is a text."
def test_color_and_bc_color():
p = Printer(no_print=True)
text = "This is a text."
result = p.text(text, color="green", bg_color="yellow")
print(result)
if SUPPORTS_ANSI:
assert result == "\x1b[38;5;2;48;5;3mThis is a text.\x1b[0m"
else:
assert result == "This is a text."
def test_printer_counts():
p = Printer()
text = "This is a test."
for i in range(2):
p.good(text)
for i in range(1):
p.fail(text)
for i in range(4):
p.warn(text)
assert p.counts[MESSAGES.GOOD] == 2
assert p.counts[MESSAGES.FAIL] == 1
assert p.counts[MESSAGES.WARN] == 4
def test_printer_spaced():
p = Printer(no_print=True, pretty=False)
text = "This is a test."
assert p.good(text) == text
assert p.good(text, spaced=True) == "\n{}\n".format(text)
def test_printer_divider():
p = Printer(line_max=20, no_print=True)
p.divider() == "\x1b[1m\n================\x1b[0m"
p.divider("test") == "\x1b[1m\n====== test ======\x1b[0m"
p.divider("test", char="*") == "\x1b[1m\n****** test ******\x1b[0m"
assert (
p.divider("This is a very long text, it is very long")
== "\x1b[1m\n This is a very long text, it is very long \x1b[0m"
)
with pytest.raises(ValueError):
p.divider("test", char="~.")
@pytest.mark.parametrize("hide_animation", [False, True])
def test_printer_loading(hide_animation):
p = Printer(hide_animation=hide_animation)
print("\n")
with p.loading("Loading..."):
time.sleep(1)
p.good("Success!")
with p.loading("Something else..."):
time.sleep(2)
p.good("Yo!")
with p.loading("Loading..."):
time.sleep(1)
p.good("Success!")
def test_printer_loading_raises_exception():
def loading_with_exception():
p = Printer()
print("\n")
with p.loading():
raise Exception("This is an error.")
with pytest.raises(Exception):
loading_with_exception()
def test_printer_loading_no_print():
p = Printer(no_print=True)
with p.loading("Loading..."):
time.sleep(1)
p.good("Success!")
def test_printer_log_friendly():
text = "This is a test."
ENV_LOG_FRIENDLY = "WASABI_LOG_FRIENDLY"
os.environ[ENV_LOG_FRIENDLY] = "True"
p = Printer(no_print=True)
assert p.good(text) in ("\u2714 This is a test.", "[+] This is a test.")
del os.environ[ENV_LOG_FRIENDLY]
def test_printer_log_friendly_prefix():
text = "This is a test."
ENV_LOG_FRIENDLY = "CUSTOM_LOG_FRIENDLY"
os.environ[ENV_LOG_FRIENDLY] = "True"
p = Printer(no_print=True, env_prefix="CUSTOM")
assert p.good(text) in ("\u2714 This is a test.", "[+] This is a test.")
print(p.good(text))
del os.environ[ENV_LOG_FRIENDLY]
@pytest.mark.skip(reason="Now seems to raise TypeError: readonly attribute?")
def test_printer_none_encoding(monkeypatch):
"""Test that printer works even if sys.stdout.encoding is set to None. This
previously caused a very confusing error."""
monkeypatch.setattr("sys.stdout.encoding", None)
p = Printer() # noqa: F841
def test_printer_no_print_raise_on_exit():
"""Test that the printer raises if a non-zero exit code is provided, even
if no_print is set to True."""
err = "This is an error."
p = Printer(no_print=True, pretty=False)
with pytest.raises(SystemExit) as e:
p.fail(err, exits=True)
assert str(e.value).strip()[-len(err) :] == err
wasabi-0.10.1/wasabi/tests/test_tables.py 0000664 0000000 0000000 00000042237 14270441700 0020341 0 ustar 00root root 0000000 0000000 # coding: utf8
from __future__ import unicode_literals, print_function
import os
import pytest
from wasabi.tables import table, row
from wasabi.util import supports_ansi
SUPPORTS_ANSI = supports_ansi()
@pytest.fixture()
def data():
return [("Hello", "World", "12344342"), ("This is a test", "World", "1234")]
@pytest.fixture()
def header():
return ["COL A", "COL B", "COL 3"]
@pytest.fixture()
def footer():
return ["", "", "2030203.00"]
@pytest.fixture()
def fg_colors():
return ["", "yellow", "87"]
@pytest.fixture()
def bg_colors():
return ["green", "23", ""]
def test_table_default(data):
result = table(data)
assert (
result
== "\nHello World 12344342\nThis is a test World 1234 \n"
)
def test_table_header(data, header):
result = table(data, header=header)
assert (
result
== "\nCOL A COL B COL 3 \nHello World 12344342\nThis is a test World 1234 \n"
)
def test_table_header_footer_divider(data, header, footer):
result = table(data, header=header, footer=footer, divider=True)
assert (
result
== "\nCOL A COL B COL 3 \n-------------- ----- ----------\nHello World 12344342 \nThis is a test World 1234 \n-------------- ----- ----------\n 2030203.00\n"
)
def test_table_aligns(data):
result = table(data, aligns=("r", "c", "l"))
assert (
result
== "\n Hello World 12344342\nThis is a test World 1234 \n"
)
def test_table_aligns_single(data):
result = table(data, aligns="r")
assert (
result
== "\n Hello World 12344342\nThis is a test World 1234\n"
)
def test_table_widths():
data = [("a", "bb", "ccc"), ("d", "ee", "fff")]
widths = (5, 2, 10)
result = table(data, widths=widths)
assert result == "\na bb ccc \nd ee fff \n"
def test_row_single_widths():
data = ("a", "bb", "ccc")
result = row(data, widths=10)
assert result == "a bb ccc "
def test_table_multiline(header):
data = [
("hello", ["foo", "bar", "baz"], "world"),
("hello", "world", ["world 1", "world 2"]),
]
result = table(data, header=header, divider=True, multiline=True)
assert (
result
== "\nCOL A COL B COL 3 \n----- ----- -------\nhello foo world \n bar \n baz \n \nhello world world 1\n world 2\n"
)
def test_row_fg_colors(fg_colors):
result = row(("Hello", "World", "12344342"), fg_colors=fg_colors)
if SUPPORTS_ANSI:
assert (
result == "Hello \x1b[38;5;3mWorld\x1b[0m \x1b[38;5;87m12344342\x1b[0m"
)
else:
assert result == "Hello World 12344342"
def test_row_bg_colors(bg_colors):
result = row(("Hello", "World", "12344342"), bg_colors=bg_colors)
if SUPPORTS_ANSI:
assert (
result == "\x1b[48;5;2mHello\x1b[0m \x1b[48;5;23mWorld\x1b[0m 12344342"
)
else:
assert result == "Hello World 12344342"
def test_row_fg_colors_and_bg_colors(fg_colors, bg_colors):
result = row(
("Hello", "World", "12344342"), fg_colors=fg_colors, bg_colors=bg_colors
)
if SUPPORTS_ANSI:
assert (
result
== "\x1b[48;5;2mHello\x1b[0m \x1b[38;5;3;48;5;23mWorld\x1b[0m \x1b[38;5;87m12344342\x1b[0m"
)
else:
assert result == "Hello World 12344342"
def test_row_fg_colors_and_bg_colors_log_friendly(fg_colors, bg_colors):
ENV_LOG_FRIENDLY = "WASABI_LOG_FRIENDLY"
os.environ[ENV_LOG_FRIENDLY] = "True"
result = row(
("Hello", "World", "12344342"), fg_colors=fg_colors, bg_colors=bg_colors
)
assert result == "Hello World 12344342"
del os.environ[ENV_LOG_FRIENDLY]
def test_row_fg_colors_and_bg_colors_log_friendly_prefix(fg_colors, bg_colors):
ENV_LOG_FRIENDLY = "CUSTOM_LOG_FRIENDLY"
os.environ[ENV_LOG_FRIENDLY] = "True"
result = row(
("Hello", "World", "12344342"),
fg_colors=fg_colors,
bg_colors=bg_colors,
env_prefix="CUSTOM",
)
assert result == "Hello World 12344342"
del os.environ[ENV_LOG_FRIENDLY]
def test_row_fg_colors_and_bg_colors_supports_ansi_false(fg_colors, bg_colors):
os.environ["ANSI_COLORS_DISABLED"] = "True"
result = row(
("Hello", "World", "12344342"), fg_colors=fg_colors, bg_colors=bg_colors
)
assert result == "Hello World 12344342"
del os.environ["ANSI_COLORS_DISABLED"]
def test_colors_whole_table_with_automatic_widths(
data, header, footer, fg_colors, bg_colors
):
result = table(
data,
header=header,
footer=footer,
divider=True,
fg_colors=fg_colors,
bg_colors=bg_colors,
)
if SUPPORTS_ANSI:
assert (
result
== "\n\x1b[48;5;2mCOL A \x1b[0m \x1b[38;5;3;48;5;23mCOL B\x1b[0m \x1b[38;5;87mCOL 3 \x1b[0m\n\x1b[48;5;2m--------------\x1b[0m \x1b[38;5;3;48;5;23m-----\x1b[0m \x1b[38;5;87m----------\x1b[0m\n\x1b[48;5;2mHello \x1b[0m \x1b[38;5;3;48;5;23mWorld\x1b[0m \x1b[38;5;87m12344342 \x1b[0m\n\x1b[48;5;2mThis is a test\x1b[0m \x1b[38;5;3;48;5;23mWorld\x1b[0m \x1b[38;5;87m1234 \x1b[0m\n\x1b[48;5;2m--------------\x1b[0m \x1b[38;5;3;48;5;23m-----\x1b[0m \x1b[38;5;87m----------\x1b[0m\n\x1b[48;5;2m \x1b[0m \x1b[38;5;3;48;5;23m \x1b[0m \x1b[38;5;87m2030203.00\x1b[0m\n"
)
else:
assert (
result
== "\nCOL A COL B COL 3 \n-------------- ----- ----------\nHello World 12344342 \nThis is a test World 1234 \n-------------- ----- ----------\n 2030203.00\n"
)
def test_colors_whole_table_only_fg_colors(data, header, footer, fg_colors):
result = table(
data,
header=header,
footer=footer,
divider=True,
fg_colors=fg_colors,
)
if SUPPORTS_ANSI:
assert (
result
== "\nCOL A \x1b[38;5;3mCOL B\x1b[0m \x1b[38;5;87mCOL 3 \x1b[0m\n-------------- \x1b[38;5;3m-----\x1b[0m \x1b[38;5;87m----------\x1b[0m\nHello \x1b[38;5;3mWorld\x1b[0m \x1b[38;5;87m12344342 \x1b[0m\nThis is a test \x1b[38;5;3mWorld\x1b[0m \x1b[38;5;87m1234 \x1b[0m\n-------------- \x1b[38;5;3m-----\x1b[0m \x1b[38;5;87m----------\x1b[0m\n \x1b[38;5;3m \x1b[0m \x1b[38;5;87m2030203.00\x1b[0m\n"
)
else:
assert (
result
== "\nCOL A COL B COL 3 \n-------------- ----- ----------\nHello World 12344342 \nThis is a test World 1234 \n-------------- ----- ----------\n 2030203.00\n"
)
def test_colors_whole_table_only_bg_colors(data, header, footer, bg_colors):
result = table(
data,
header=header,
footer=footer,
divider=True,
bg_colors=bg_colors,
)
if SUPPORTS_ANSI:
assert (
result
== "\n\x1b[48;5;2mCOL A \x1b[0m \x1b[48;5;23mCOL B\x1b[0m COL 3 \n\x1b[48;5;2m--------------\x1b[0m \x1b[48;5;23m-----\x1b[0m ----------\n\x1b[48;5;2mHello \x1b[0m \x1b[48;5;23mWorld\x1b[0m 12344342 \n\x1b[48;5;2mThis is a test\x1b[0m \x1b[48;5;23mWorld\x1b[0m 1234 \n\x1b[48;5;2m--------------\x1b[0m \x1b[48;5;23m-----\x1b[0m ----------\n\x1b[48;5;2m \x1b[0m \x1b[48;5;23m \x1b[0m 2030203.00\n"
)
else:
assert (
result
== "\nCOL A COL B COL 3 \n-------------- ----- ----------\nHello World 12344342 \nThis is a test World 1234 \n-------------- ----- ----------\n 2030203.00\n"
)
def test_colors_whole_table_with_supplied_spacing(
data, header, footer, fg_colors, bg_colors
):
result = table(
data,
header=header,
footer=footer,
divider=True,
fg_colors=fg_colors,
bg_colors=bg_colors,
spacing=5,
)
if SUPPORTS_ANSI:
assert (
result
== "\n\x1b[48;5;2mCOL A \x1b[0m \x1b[38;5;3;48;5;23mCOL B\x1b[0m \x1b[38;5;87mCOL 3 \x1b[0m\n\x1b[48;5;2m--------------\x1b[0m \x1b[38;5;3;48;5;23m-----\x1b[0m \x1b[38;5;87m----------\x1b[0m\n\x1b[48;5;2mHello \x1b[0m \x1b[38;5;3;48;5;23mWorld\x1b[0m \x1b[38;5;87m12344342 \x1b[0m\n\x1b[48;5;2mThis is a test\x1b[0m \x1b[38;5;3;48;5;23mWorld\x1b[0m \x1b[38;5;87m1234 \x1b[0m\n\x1b[48;5;2m--------------\x1b[0m \x1b[38;5;3;48;5;23m-----\x1b[0m \x1b[38;5;87m----------\x1b[0m\n\x1b[48;5;2m \x1b[0m \x1b[38;5;3;48;5;23m \x1b[0m \x1b[38;5;87m2030203.00\x1b[0m\n"
)
else:
assert (
result
== "\nCOL A COL B COL 3 \n-------------- ----- ----------\nHello World 12344342 \nThis is a test World 1234 \n-------------- ----- ----------\n 2030203.00\n"
)
def test_colors_whole_table_with_supplied_widths(
data, header, footer, fg_colors, bg_colors
):
result = table(
data,
header=header,
footer=footer,
divider=True,
fg_colors=fg_colors,
bg_colors=bg_colors,
widths=(5, 2, 10),
)
if SUPPORTS_ANSI:
assert (
result
== "\n\x1b[48;5;2mCOL A\x1b[0m \x1b[38;5;3;48;5;23mCOL B\x1b[0m \x1b[38;5;87mCOL 3 \x1b[0m\n\x1b[48;5;2m-----\x1b[0m \x1b[38;5;3;48;5;23m--\x1b[0m \x1b[38;5;87m----------\x1b[0m\n\x1b[48;5;2mHello\x1b[0m \x1b[38;5;3;48;5;23mWorld\x1b[0m \x1b[38;5;87m12344342 \x1b[0m\n\x1b[48;5;2mThis is a test\x1b[0m \x1b[38;5;3;48;5;23mWorld\x1b[0m \x1b[38;5;87m1234 \x1b[0m\n\x1b[48;5;2m-----\x1b[0m \x1b[38;5;3;48;5;23m--\x1b[0m \x1b[38;5;87m----------\x1b[0m\n\x1b[48;5;2m \x1b[0m \x1b[38;5;3;48;5;23m \x1b[0m \x1b[38;5;87m2030203.00\x1b[0m\n"
)
else:
assert (
result
== "\nCOL A COL B COL 3 \n----- -- ----------\nHello World 12344342 \nThis is a test World 1234 \n----- -- ----------\n 2030203.00\n"
)
def test_colors_whole_table_with_single_alignment(
data, header, footer, fg_colors, bg_colors
):
result = table(
data,
header=header,
footer=footer,
divider=True,
fg_colors=fg_colors,
bg_colors=bg_colors,
aligns="r",
)
if SUPPORTS_ANSI:
assert (
result
== "\n\x1b[48;5;2m COL A\x1b[0m \x1b[38;5;3;48;5;23mCOL B\x1b[0m \x1b[38;5;87m COL 3\x1b[0m\n\x1b[48;5;2m--------------\x1b[0m \x1b[38;5;3;48;5;23m-----\x1b[0m \x1b[38;5;87m----------\x1b[0m\n\x1b[48;5;2m Hello\x1b[0m \x1b[38;5;3;48;5;23mWorld\x1b[0m \x1b[38;5;87m 12344342\x1b[0m\n\x1b[48;5;2mThis is a test\x1b[0m \x1b[38;5;3;48;5;23mWorld\x1b[0m \x1b[38;5;87m 1234\x1b[0m\n\x1b[48;5;2m--------------\x1b[0m \x1b[38;5;3;48;5;23m-----\x1b[0m \x1b[38;5;87m----------\x1b[0m\n\x1b[48;5;2m \x1b[0m \x1b[38;5;3;48;5;23m \x1b[0m \x1b[38;5;87m2030203.00\x1b[0m\n"
)
else:
assert (
result
== "\n COL A COL B COL 3\n-------------- ----- ----------\n Hello World 12344342\nThis is a test World 1234\n-------------- ----- ----------\n 2030203.00\n"
)
def test_colors_whole_table_with_multiple_alignment(
data, header, footer, fg_colors, bg_colors
):
result = table(
data,
header=header,
footer=footer,
divider=True,
fg_colors=fg_colors,
bg_colors=bg_colors,
aligns=("c", "r", "l"),
)
if SUPPORTS_ANSI:
assert (
result
== "\n\x1b[48;5;2m COL A \x1b[0m \x1b[38;5;3;48;5;23mCOL B\x1b[0m \x1b[38;5;87mCOL 3 \x1b[0m\n\x1b[48;5;2m--------------\x1b[0m \x1b[38;5;3;48;5;23m-----\x1b[0m \x1b[38;5;87m----------\x1b[0m\n\x1b[48;5;2m Hello \x1b[0m \x1b[38;5;3;48;5;23mWorld\x1b[0m \x1b[38;5;87m12344342 \x1b[0m\n\x1b[48;5;2mThis is a test\x1b[0m \x1b[38;5;3;48;5;23mWorld\x1b[0m \x1b[38;5;87m1234 \x1b[0m\n\x1b[48;5;2m--------------\x1b[0m \x1b[38;5;3;48;5;23m-----\x1b[0m \x1b[38;5;87m----------\x1b[0m\n\x1b[48;5;2m \x1b[0m \x1b[38;5;3;48;5;23m \x1b[0m \x1b[38;5;87m2030203.00\x1b[0m\n"
)
else:
assert (
result
== "\n COL A COL B COL 3 \n-------------- ----- ----------\n Hello World 12344342 \nThis is a test World 1234 \n-------------- ----- ----------\n 2030203.00\n"
)
def test_colors_whole_table_with_multiline(data, header, footer, fg_colors, bg_colors):
result = table(
data=((["Charles", "Quinton", "Murphy"], "my", "brother"), ("1", "2", "3")),
fg_colors=fg_colors,
bg_colors=bg_colors,
multiline=True,
)
if SUPPORTS_ANSI:
assert (
result
== "\n\x1b[48;5;2mCharles\x1b[0m \x1b[38;5;3;48;5;23mmy\x1b[0m \x1b[38;5;87mbrother\x1b[0m\n\x1b[48;5;2mQuinton\x1b[0m \x1b[38;5;3;48;5;23m \x1b[0m \x1b[38;5;87m \x1b[0m\n\x1b[48;5;2mMurphy \x1b[0m \x1b[38;5;3;48;5;23m \x1b[0m \x1b[38;5;87m \x1b[0m\n\x1b[48;5;2m \x1b[0m \x1b[38;5;3;48;5;23m \x1b[0m \x1b[38;5;87m \x1b[0m\n\x1b[48;5;2m1 \x1b[0m \x1b[38;5;3;48;5;23m2 \x1b[0m \x1b[38;5;87m3 \x1b[0m\n"
)
else:
assert (
result
== "\nCharles my brother\nQuinton \nMurphy \n \n1 2 3 \n"
)
def test_colors_whole_table_log_friendly(data, header, footer, fg_colors, bg_colors):
ENV_LOG_FRIENDLY = "WASABI_LOG_FRIENDLY"
os.environ[ENV_LOG_FRIENDLY] = "True"
result = table(
data,
header=header,
footer=footer,
divider=True,
fg_colors=fg_colors,
bg_colors=bg_colors,
)
assert (
result
== "\nCOL A COL B COL 3 \n-------------- ----- ----------\nHello World 12344342 \nThis is a test World 1234 \n-------------- ----- ----------\n 2030203.00\n"
)
del os.environ[ENV_LOG_FRIENDLY]
def test_colors_whole_table_log_friendly_prefix(
data, header, footer, fg_colors, bg_colors
):
ENV_LOG_FRIENDLY = "CUSTOM_LOG_FRIENDLY"
os.environ[ENV_LOG_FRIENDLY] = "True"
result = table(
data,
header=header,
footer=footer,
divider=True,
fg_colors=fg_colors,
bg_colors=bg_colors,
env_prefix="CUSTOM",
)
assert (
result
== "\nCOL A COL B COL 3 \n-------------- ----- ----------\nHello World 12344342 \nThis is a test World 1234 \n-------------- ----- ----------\n 2030203.00\n"
)
del os.environ[ENV_LOG_FRIENDLY]
def test_colors_whole_table_supports_ansi_false(
data, header, footer, fg_colors, bg_colors
):
os.environ["ANSI_COLORS_DISABLED"] = "True"
result = table(
data,
header=header,
footer=footer,
divider=True,
fg_colors=fg_colors,
bg_colors=bg_colors,
)
assert (
result
== "\nCOL A COL B COL 3 \n-------------- ----- ----------\nHello World 12344342 \nThis is a test World 1234 \n-------------- ----- ----------\n 2030203.00\n"
)
del os.environ["ANSI_COLORS_DISABLED"]
def test_colors_whole_table_color_values(data, header, footer, fg_colors, bg_colors):
result = table(
data,
header=header,
footer=footer,
divider=True,
fg_colors=fg_colors,
bg_colors=bg_colors,
color_values={"yellow": 11},
)
if SUPPORTS_ANSI:
assert (
result
== "\n\x1b[48;5;2mCOL A \x1b[0m \x1b[38;5;11;48;5;23mCOL B\x1b[0m \x1b[38;5;87mCOL 3 \x1b[0m\n\x1b[48;5;2m--------------\x1b[0m \x1b[38;5;11;48;5;23m-----\x1b[0m \x1b[38;5;87m----------\x1b[0m\n\x1b[48;5;2mHello \x1b[0m \x1b[38;5;11;48;5;23mWorld\x1b[0m \x1b[38;5;87m12344342 \x1b[0m\n\x1b[48;5;2mThis is a test\x1b[0m \x1b[38;5;11;48;5;23mWorld\x1b[0m \x1b[38;5;87m1234 \x1b[0m\n\x1b[48;5;2m--------------\x1b[0m \x1b[38;5;11;48;5;23m-----\x1b[0m \x1b[38;5;87m----------\x1b[0m\n\x1b[48;5;2m \x1b[0m \x1b[38;5;11;48;5;23m \x1b[0m \x1b[38;5;87m2030203.00\x1b[0m\n"
)
else:
assert (
result
== "\nCOL A COL B COL 3 \n-------------- ----- ----------\nHello World 12344342 \nThis is a test World 1234 \n-------------- ----- ----------\n 2030203.00\n"
)
wasabi-0.10.1/wasabi/tests/test_traceback.py 0000664 0000000 0000000 00000003234 14270441700 0021000 0 ustar 00root root 0000000 0000000 # coding: utf8
from __future__ import unicode_literals, print_function
import pytest
import traceback
from wasabi.traceback_printer import TracebackPrinter
@pytest.fixture
def tb():
return traceback.extract_stack()
def test_traceback_printer(tb):
tbp = TracebackPrinter(tb_base="wasabi")
msg = tbp("Hello world", "This is a test", tb=tb)
print(msg)
def test_traceback_printer_highlight(tb):
tbp = TracebackPrinter(tb_base="wasabi")
msg = tbp("Hello world", "This is a test", tb=tb, highlight="kwargs")
print(msg)
def test_traceback_printer_custom_colors(tb):
tbp = TracebackPrinter(
tb_base="wasabi", color_error="blue", color_highlight="green", color_tb="yellow"
)
msg = tbp("Hello world", "This is a test", tb=tb, highlight="kwargs")
print(msg)
def test_traceback_printer_only_title(tb):
tbp = TracebackPrinter(tb_base="wasabi")
msg = tbp("Hello world", tb=tb)
print(msg)
def test_traceback_dot_relative_path_tb_base(tb):
tbp = TracebackPrinter(tb_base=".")
msg = tbp("Hello world", tb=tb)
print(msg)
def test_traceback_tb_base_none(tb):
tbp = TracebackPrinter()
msg = tbp("Hello world", tb=tb)
print(msg)
def test_traceback_printer_no_tb():
tbp = TracebackPrinter(tb_base="wasabi")
msg = tbp("Hello world", "This is a test")
print(msg)
def test_traceback_printer_custom_tb_range():
tbp = TracebackPrinter(tb_range_start=-10, tb_range_end=-3)
msg = tbp("Hello world", "This is a test")
print(msg)
def test_traceback_printer_custom_tb_range_start():
tbp = TracebackPrinter(tb_range_start=-1)
msg = tbp("Hello world", "This is a test")
print(msg)
wasabi-0.10.1/wasabi/tests/test_util.py 0000664 0000000 0000000 00000004734 14270441700 0020044 0 ustar 00root root 0000000 0000000 # coding: utf8
from __future__ import unicode_literals, print_function
import pytest
from wasabi.util import color, wrap, locale_escape, format_repr, diff_strings
def test_color():
assert color("test", fg="green") == "\x1b[38;5;2mtest\x1b[0m"
assert color("test", fg=4) == "\x1b[38;5;4mtest\x1b[0m"
assert color("test", bold=True) == "\x1b[1mtest\x1b[0m"
assert color("test", fg="red", underline=True) == "\x1b[4;38;5;1mtest\x1b[0m"
assert (
color("test", fg=7, bg="red", bold=True) == "\x1b[1;38;5;7;48;5;1mtest\x1b[0m"
)
def test_wrap():
text = "Hello world, this is a test."
assert wrap(text, indent=0) == text
assert wrap(text, indent=4) == " Hello world, this is a test."
assert wrap(text, wrap_max=10, indent=0) == "Hello\nworld,\nthis is a\ntest."
assert (
wrap(text, wrap_max=5, indent=2)
== " Hello\n world,\n this\n is\n a\n test."
)
def test_format_repr():
obj = {"hello": "world", "test": 123}
formatted = format_repr(obj)
assert formatted.replace("u'", "'") in [
"{'hello': 'world', 'test': 123}",
"{'test': 123, 'hello': 'world'}",
]
formatted = format_repr(obj, max_len=10)
assert formatted.replace("u'", "'") in [
"{'hel ... 123}",
"{'tes ... rld'}",
"{'te ... rld'}",
]
formatted = format_repr(obj, max_len=10, ellipsis="[...]")
assert formatted.replace("u'", "'") in [
"{'hel [...] 123}",
"{'tes [...] rld'}",
"{'te [...] rld'}",
]
@pytest.mark.parametrize(
"text,non_ascii",
[
("abc", ["abc"]),
("\u2714 abc", ["? abc"]),
("π»", ["??", "?"]), # On Python 3 windows, this becomes "?" instead of "??"
],
)
def test_locale_escape(text, non_ascii):
result = locale_escape(text)
assert result == text or result in non_ascii
print(result)
def test_diff_strings():
a = "hello\nworld\nwide\nweb"
b = "yo\nwide\nworld\nweb"
expected = "\x1b[38;5;16;48;5;2myo\x1b[0m\n\x1b[38;5;16;48;5;2mwide\x1b[0m\n\x1b[38;5;16;48;5;1mhello\x1b[0m\nworld\n\x1b[38;5;16;48;5;1mwide\x1b[0m\nweb"
assert diff_strings(a, b) == expected
def test_diff_strings_with_symbols():
a = "hello\nworld\nwide\nweb"
b = "yo\nwide\nworld\nweb"
expected = "\x1b[38;5;16;48;5;2m+ yo\x1b[0m\n\x1b[38;5;16;48;5;2m+ wide\x1b[0m\n\x1b[38;5;16;48;5;1m- hello\x1b[0m\nworld\n\x1b[38;5;16;48;5;1m- wide\x1b[0m\nweb"
assert diff_strings(a, b, add_symbols=True) == expected
wasabi-0.10.1/wasabi/traceback_printer.py 0000664 0000000 0000000 00000011531 14270441700 0020341 0 ustar 00root root 0000000 0000000 # coding: utf8
from __future__ import unicode_literals, print_function
import os
from .util import color, supports_ansi, NO_UTF8
LINE_EDGE = "ββ" if not NO_UTF8 else "|_"
LINE_FORK = "ββ" if not NO_UTF8 else "|__"
LINE_PATH = "ββ" if not NO_UTF8 else "__"
class TracebackPrinter(object):
def __init__(
self,
color_error="red",
color_tb="blue",
color_highlight="yellow",
indent=2,
tb_base=None,
tb_exclude=tuple(),
tb_range_start=-5,
tb_range_end=-2,
):
"""Initialize a traceback printer.
color_error (unicode / int): Color name or code for errors.
color_tb (unicode / int): Color name or code for traceback headline.
color_highlight (unicode / int): Color name or code for highlights.
indent (int): Indentation in spaces.
tb_base (unicode): Name of directory to use to show relative paths. For
example, "thinc" will look for the last occurence of "/thinc/" in
a path and only show path to the right of it.
tb_exclude (tuple): List of filenames to exclude from traceback.
tb_range_start (int): The starting index from a traceback to include.
tb_range_end (int): The final index from a traceback to include. If None
the traceback will continue until the last record.
RETURNS (TracebackPrinter): The traceback printer.
"""
self.color_error = color_error
self.color_tb = color_tb
self.color_highlight = color_highlight
self.indent = " " * indent
if tb_base == ".":
tb_base = "{}{}".format(os.getcwd(), os.path.sep)
elif tb_base is not None:
tb_base = "/{}/".format(tb_base)
self.tb_base = tb_base
self.tb_exclude = tuple(tb_exclude)
self.tb_range_start = tb_range_start
self.tb_range_end = tb_range_end
self.supports_ansi = supports_ansi()
def __call__(self, title, *texts, **settings):
"""Output custom formatted tracebacks and errors.
title (unicode): The message title.
*texts (unicode): The texts to print (one per line).
highlight (unicode): Optional sequence to highlight in the traceback,
e.g. the bad value that caused the error.
tb (iterable): The traceback, e.g. generated by traceback.extract_stack().
RETURNS (unicode): The formatted traceback. Can be printed or raised
by custom exception.
"""
highlight = settings.get("highlight", False)
tb = settings.get("tb", None)
if self.supports_ansi: # use first line as title
title = color(title, fg=self.color_error, bold=True)
info = "\n" + "\n".join([self.indent + text for text in texts]) if texts else ""
tb = self._get_traceback(tb, highlight) if tb else ""
msg = "\n\n{}{}{}{}\n".format(self.indent, title, info, tb)
return msg
def _get_traceback(self, tb, highlight):
# Exclude certain file names from traceback
tb = [record for record in tb if not record[0].endswith(self.tb_exclude)]
tb_range = (
tb[self.tb_range_start : self.tb_range_end]
if self.tb_range_end is not None
else tb[self.tb_range_start :]
)
tb_list = [
self._format_traceback(path, line, fn, text, i, len(tb_range), highlight)
for i, (path, line, fn, text) in enumerate(tb_range)
]
tb_data = "\n".join(tb_list).strip()
title = "Traceback:"
if self.supports_ansi:
title = color(title, fg=self.color_tb, bold=True)
return "\n\n{indent}{title}\n{indent}{tb}".format(
title=title, tb=tb_data, indent=self.indent
)
def _format_traceback(self, path, line, fn, text, i, count, highlight):
template = "{base_indent}{indent} {fn} in {path}:{line}{text}"
indent = (LINE_EDGE if i == count - 1 else LINE_FORK) + LINE_PATH * i
if self.tb_base and self.tb_base in path:
path = path.rsplit(self.tb_base, 1)[1]
text = self._format_user_error(text, i, highlight) if i == count - 1 else ""
if self.supports_ansi:
fn = color(fn, bold=True)
path = color(path, underline=True)
return template.format(
base_indent=self.indent,
line=line,
indent=indent,
text=text,
fn=fn,
path=path,
)
def _format_user_error(self, text, i, highlight):
spacing = " " * i + " >>>"
if self.supports_ansi:
spacing = color(spacing, fg=self.color_error)
if highlight and self.supports_ansi:
formatted_highlight = color(highlight, fg=self.color_highlight)
text = text.replace(highlight, formatted_highlight)
return "\n{} {} {}".format(self.indent, spacing, text)
wasabi-0.10.1/wasabi/util.py 0000664 0000000 0000000 00000016046 14270441700 0015642 0 ustar 00root root 0000000 0000000 # coding: utf8
from __future__ import unicode_literals, print_function
import os
import sys
import textwrap
import difflib
import itertools
STDOUT_ENCODING = sys.stdout.encoding if hasattr(sys.stdout, "encoding") else None
ENCODING = STDOUT_ENCODING or "ascii"
NO_UTF8 = ENCODING.lower() not in ("utf8", "utf-8")
# Environment variables
ENV_ANSI_DISABLED = "ANSI_COLORS_DISABLED" # no colors
class MESSAGES(object):
GOOD = "good"
FAIL = "fail"
WARN = "warn"
INFO = "info"
COLORS = {
MESSAGES.GOOD: 2,
MESSAGES.FAIL: 1,
MESSAGES.WARN: 3,
MESSAGES.INFO: 4,
"red": 1,
"green": 2,
"yellow": 3,
"blue": 4,
"pink": 5,
"cyan": 6,
"white": 7,
"grey": 8,
"black": 16,
}
ICONS = {
MESSAGES.GOOD: "\u2714" if not NO_UTF8 else "[+]",
MESSAGES.FAIL: "\u2718" if not NO_UTF8 else "[x]",
MESSAGES.WARN: "\u26a0" if not NO_UTF8 else "[!]",
MESSAGES.INFO: "\u2139" if not NO_UTF8 else "[i]",
}
INSERT_SYMBOL = "+"
DELETE_SYMBOL = "-"
# Python 2 compatibility
IS_PYTHON_2 = sys.version_info[0] == 2
if IS_PYTHON_2:
basestring_ = basestring # noqa: F821
input_ = raw_input # noqa: F821
zip_longest = itertools.izip_longest # noqa: F821
else:
basestring_ = str
input_ = input
zip_longest = itertools.zip_longest
def color(text, fg=None, bg=None, bold=False, underline=False):
"""Color text by applying ANSI escape sequence.
text (unicode): The text to be formatted.
fg (unicode / int): Foreground color. String name or 0 - 256 (see COLORS).
bg (unicode / int): Background color. String name or 0 - 256 (see COLORS).
bold (bool): Format text in bold.
underline (bool): Underline text.
RETURNS (unicode): The formatted text.
"""
fg = COLORS.get(fg, fg)
bg = COLORS.get(bg, bg)
if not any([fg, bg, bold]):
return text
styles = []
if bold:
styles.append("1")
if underline:
styles.append("4")
if fg:
styles.append("38;5;{}".format(fg))
if bg:
styles.append("48;5;{}".format(bg))
return "\x1b[{}m{}\x1b[0m".format(";".join(styles), text)
def wrap(text, wrap_max=80, indent=4):
"""Wrap text at given width using textwrap module.
text (unicode): The text to wrap.
wrap_max (int): Maximum line width, including indentation. Defaults to 80.
indent (int): Number of spaces used for indentation. Defaults to 4.
RETURNS (unicode): The wrapped text with line breaks.
"""
indent = indent * " "
wrap_width = wrap_max - len(indent)
text = to_string(text)
return textwrap.fill(
text,
width=wrap_width,
initial_indent=indent,
subsequent_indent=indent,
break_long_words=False,
break_on_hyphens=False,
)
def format_repr(obj, max_len=50, ellipsis="..."):
"""Wrapper around `repr()` to print shortened and formatted string version.
obj: The object to represent.
max_len (int): Maximum string length. Longer strings will be cut in the
middle so only the beginning and end is displayed, separated by ellipsis.
ellipsis (unicode): Ellipsis character(s), e.g. "...".
RETURNS (unicode): The formatted representation.
"""
string = repr(obj)
if len(string) >= max_len:
half = int(max_len / 2)
return "{} {} {}".format(string[:half], ellipsis, string[-half:])
else:
return string
def diff_strings(a, b, fg="black", bg=("green", "red"), add_symbols=False):
"""Compare two strings and return a colored diff with red/green background
for deletion and insertions.
a (unicode): The first string to diff.
b (unicode): The second string to diff.
fg (unicode / int): Foreground color. String name or 0 - 256 (see COLORS).
bg (tuple): Background colors as (insert, delete) tuple of string name or
0 - 256 (see COLORS).
add_symbols (bool): Whether to add symbols before the diff lines. Uses '+'
for inserts and '-' for deletions. Default is False.
RETURNS (unicode): The formatted diff.
"""
a = a.split("\n")
b = b.split("\n")
output = []
matcher = difflib.SequenceMatcher(None, a, b)
for opcode, a0, a1, b0, b1 in matcher.get_opcodes():
if opcode == "equal":
for item in a[a0:a1]:
output.append(item)
if opcode == "insert" or opcode == "replace":
for item in b[b0:b1]:
item = "{} {}".format(INSERT_SYMBOL, item) if add_symbols else item
output.append(color(item, fg=fg, bg=bg[0]))
if opcode == "delete" or opcode == "replace":
for item in a[a0:a1]:
item = "{} {}".format(DELETE_SYMBOL, item) if add_symbols else item
output.append(color(item, fg=fg, bg=bg[1]))
return "\n".join(output)
def get_raw_input(description, default=False, indent=4):
"""Get user input from the command line via raw_input / input.
description (unicode): Text to display before prompt.
default (unicode or False/None): Default value to display with prompt.
indent (int): Indentation in spaces.
RETURNS (unicode): User input.
"""
additional = " (default: {})".format(default) if default else ""
prompt = wrap("{}{}: ".format(description, additional), indent=indent)
user_input = input_(prompt)
return user_input
def locale_escape(string, errors="replace"):
"""Mangle non-supported characters, for savages with ASCII terminals.
string (unicode): The string to escape.
errors (unicode): The str.encode errors setting. Defaults to `"replace"`.
RETURNS (unicode): The escaped string.
"""
string = to_string(string)
string = string.encode(ENCODING, errors).decode("utf8")
return string
def can_render(string):
"""Check if terminal can render unicode characters, e.g. special loading
icons. Can be used to display fallbacks for ASCII terminals.
string (unicode): The string to render.
RETURNS (bool): Whether the terminal can render the text.
"""
try:
string.encode(ENCODING)
return True
except UnicodeEncodeError:
return False
def supports_ansi():
"""Returns True if the running system's terminal supports ANSI escape
sequences for color, formatting etc. and False otherwise. Inspired by
Django's solution β hacky, but an okay approximation.
RETURNS (bool): Whether the terminal supports ANSI colors.
"""
if os.getenv(ENV_ANSI_DISABLED):
return False
# See: https://stackoverflow.com/q/7445658/6400719
supported_platform = sys.platform != "Pocket PC" and (
sys.platform != "win32" or "ANSICON" in os.environ
)
if not supported_platform:
return False
return True
def to_string(text):
"""Minimal compat helper to make sure text is unicode. Mostly used to
convert Paths and other Python objects.
text: The text/object to be converted.
RETURNS (unicode): The converted string.
"""
if not isinstance(text, basestring_):
if IS_PYTHON_2:
text = str(text).decode("utf8")
else:
text = str(text)
return text