Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
qexat committed Apr 14, 2024
0 parents commit 51ec4f6
Show file tree
Hide file tree
Showing 7 changed files with 416 additions and 0 deletions.
132 changes: 132 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
# 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/
pip-wheel-metadata/
share/python-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
*.py,cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# 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

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# 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/

# Custom
\#*
9 changes: 9 additions & 0 deletions 3rdparty/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
MIT License

Copyright (c) Sindre Sorhus <[email protected]> (<https://sindresorhus.com>)

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.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Qexat

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.
21 changes: 21 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
[project]
name = "anstrip"
description = "anstrip is a minimal library to strip ANSI sequences from strings."
version = "0.1.0-1"
readme = "README.md"
keywords = ["ansi", "escape sequence", "SGR", "ECMA", "strip"]
requires-python = ">=3.10"

[project.license]
file = "LICENSE"

[[project.authors]]
name = "Qexat"
email = "[email protected]"

[project.urls]
source = "https://github.com/qexat/anstrip"

[build-system]
requires = ["setuptools"]
build-backend = "setuptools.build_meta"
119 changes: 119 additions & 0 deletions src/anstrip/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
"""
anstrip is a minimal library to strip ANSI sequences from strings.
It provides:
- the regex pattern used by the functions of anstrip
- `strip`, a function to remove all the escape sequences from a string
- `auto_strip`, a function that is similar to `strip`, except that it only removes if the output is a TTY
- `printed_length`, a function that returns the length of the string as seen on the screen
"""

import collections.abc
import functools
import re
import sys
import typing

__all__ = [
"PATTERN",
"strip",
"auto_strip",
"auto_print",
"printed_length",
]

_P = typing.ParamSpec("_P")

# Based on <https://github.com/chalk/ansi-regex/blob/main/index.js>
# The license of `ansi-regex` can be found in the `3rdparty` directory
PATTERN = re.compile(
r"[\u001B\u009B][\[\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\d\/#&.:=?%@~_]+)*|[a-zA-Z\d]+(?:;[-a-zA-Z\d\/#&.:=?%@~_]*)*)?\u0007)|(?:(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))"
)


def strip(string: str) -> str:
"""
Strip ANSI sequences from a given string.
>>> anstrip.strip("Nothing out of the \\x1b[94mblue\\x1b[39m...")
'Nothing out of the blue...'
>>> anstrip.strip("\\x1b[1;31mBOLD, AND RED!\\x1b[22;39m")
'BOLD, AND RED!' # well not anymore
>>> anstrip.strip("A party? I'm \\x1b[Bdown for that!")
"A party? I'm down for that!"
>>> anstrip.strip("Hello, mundane world.")
'Hello, mundane world.'
>>> anstrip.strip("")
''
"""

return re.sub(PATTERN, "", string)


# The docstring is provided by the overloads (in the stubs)
def auto_strip(
string_or_function: str | collections.abc.Callable[_P, str] | None = None,
/,
*,
output: typing.TextIO | None = None,
) -> (
str
| collections.abc.Callable[_P, str]
| collections.abc.Callable[
[collections.abc.Callable[_P, str]], collections.abc.Callable[_P, str]
]
):
if output is None:
output = sys.stdout

if isinstance(string_or_function, str):
return string_or_function if output.isatty() else strip(string_or_function)

def decorator(
function: collections.abc.Callable[_P, str],
) -> collections.abc.Callable[_P, str]:
@functools.wraps(function)
def inner(*args: _P.args, **kwargs: _P.kwargs) -> str:
return strip(function(*args, **kwargs))

if output.isatty():
return function
return inner

if string_or_function is not None:
return decorator(string_or_function)
return decorator


def auto_print(
*values: object,
sep: str | None = None,
end: str | None = None,
file: typing.TextIO | None = None,
flush: bool = False,
) -> None:
"""
Similar to the built-in function `print`, but ANSI escape sequences are
automatically stripped if `file` is not a TTY.
"""

def str_and_auto_strip(value: object) -> str:
return typing.cast(str, auto_strip(str(value), output=file))

print(*map(str_and_auto_strip, values), sep=sep, end=end, file=file, flush=flush)


def printed_length(string: str) -> int:
"""
Return the length of the string without counting characters that are not
actually visible (ANSI sequences).
>>> ansi.printed_length("Nothing out of the \\x1b[94mblue\\x1b[39m...")
26
>>> ansi.printed_length("Hello, mundane world.")
21
>>> ansi.printed_length("")
0
"""

return len(strip(string))
Loading

0 comments on commit 51ec4f6

Please sign in to comment.