Skip to content

Commit

Permalink
Upload colorpattern 1.1
Browse files Browse the repository at this point in the history
  • Loading branch information
croketillo committed Nov 9, 2023
0 parents commit ecdd804
Show file tree
Hide file tree
Showing 10 changed files with 256 additions and 0 deletions.
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
build/
colorpattern.egg-info/

.env/
env/
env
2 changes: 2 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
include README.md
recursive-include colorpattern *.py
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# ColorPattern

ColorPattern is a Python module designed for enhancing text output in the console by applying color to specific patterns. It offers a flexible way to define patterns and apply different text colors, background colors, styles, and underlines to matching text in the output.

## Installation

You can install ColorPattern using pip:

```pip install colorpattern ```


## USAGE

```python
from colorpattern import SetPattern, start_color

# Define color patterns
pattern1 = SetPattern(r'\d+', color='green', back='black', style='bright', underline=True)
pattern2 = SetPattern(r'error', color='red', back='yellow', style='dim', underline=False)
pattern3 = SetPattern(r'pattern', back='blue', style='reset_all', underline=True)

# Initialize color for patterns
start_color([pattern1, pattern2, pattern3])

# Your code with colorized output
print("123 error 456 pattern")
```

## Patterns

- `pattern`: Regular expression pattern to match in the text.
- `color`: Text color (e.g., 'green', 'red', 'yellow').
- `back`: Background color (e.g., 'black', 'blue', 'white').
- `style`: Text style (e.g., 'bright', 'dim', 'reset_all').
- `underline`: Set to `True` for underlining matched text.

## License

This project is licensed under the GNU-GLP,3 License - see the LICENSE file for details.
47 changes: 47 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
ColorPattern
============

ColorPattern is a Python module designed for enhancing text output in
the console by applying color to specific patterns. It offers a flexible
way to define patterns and apply different text colors, background
colors, styles, and underlines to matching text in the output.

Installation
------------

You can install ColorPattern using pip:

``pip install colorpattern``

USAGE
-----

.. code:: python
from colorpattern import SetPattern, start_color
# Define color patterns
pattern1 = SetPattern(r'\d+', color='green', back='black', style='bright', underline=True)
pattern2 = SetPattern(r'error', color='red', back='yellow', style='dim', underline=False)
pattern3 = SetPattern(r'pattern', back='blue', style='reset_all', underline=True)
# Initialize color for patterns
start_color([pattern1, pattern2, pattern3])
# Your code with colorized output
print("123 error 456 pattern")
Patterns
--------

- ``pattern``: Regular expression pattern to match in the text.
- ``color``: Text color (e.g., ‘green’, ‘red’, ‘yellow’).
- ``back``: Background color (e.g., ‘black’, ‘blue’, ‘white’).
- ``style``: Text style (e.g., ‘bright’, ‘dim’, ‘reset_all’).
- ``underline``: Set to ``True`` for underlining matched text.

License
-------

This project is licensed under the GNU-GLP,3 License - see the LICENSE
file for details.
Empty file added colorpattern/__init__.py
Empty file.
36 changes: 36 additions & 0 deletions colorpattern/colorpattern.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import re
from colorama import Fore, Style, Back
import builtins


class SetPattern:
def __init__(self, pattern, color=None, back=None, style=None, underline=False):
self.pattern = re.compile(pattern)
self.color = color if color is not None else Fore.RESET
self.back = back if back is not None else Back.RESET
self.style = style if style is not None else Style.RESET_ALL
self.underline = underline

def colorize_text(self, text):
if self.underline:
return self.pattern.sub(lambda match: f"{self.style}{self.color}{self.back}\033[4m{match.group()}\033[0m{Style.RESET_ALL}", text)
else:
return self.pattern.sub(lambda match: f"{self.style}{self.color}{self.back}{match.group()}{Style.RESET_ALL}", text)


# Función que inicializa el coloreado
def start_color(patterns):
def custom_print(*args, **kwargs):
# Convertir los argumentos de print a una cadena
text = " ".join(map(str, args))

# Aplicar el coloreado
for pattern in patterns:
text = pattern.colorize_text(text)

# Imprimir el texto coloreado
original_print(text, **kwargs)

# Remplazar la función print por nuestra versión personalizada
original_print = builtins.print
builtins.print = custom_print
Binary file added dist/colorpattern-1.1-py3-none-any.whl
Binary file not shown.
Binary file added dist/colorpattern-1.1.tar.gz
Binary file not shown.
114 changes: 114 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import json
from os import path
from setuptools import setup, find_packages
from sys import version_info

CURR_PATH = "{}{}".format(path.abspath(path.dirname(__file__)), '/')




def path_format(file_path=None, file_name=None, is_abspath=False,
ignore_raises=False):
"""
Get path joined checking before if path and filepath exist,
if not, raise an Exception
if ignore_raise it's enabled, then file_path must include '/' at end lane
"""
path_formatted = "{}{}".format(file_path, file_name)
if ignore_raises:
return path_formatted
if file_path is None or not path.exists(file_path):
raise IOError("Path '{}' doesn't exists".format(file_path))
if file_name is None or not path.exists(path_formatted):
raise IOError(
"File '{}{}' doesn't exists".format(file_path, file_name))
if is_abspath:
return path.abspath(path.join(file_path, file_name))
else:
return path.join(file_path, file_name)


def read_file(is_json=False, file_path=None, encoding='utf-8',
is_encoding=True, ignore_raises=False):
"""Returns file object from file_path,
compatible with all py versiones
optionals:
can be use to return dict from json path
can modify encoding used to obtain file
"""
text = None
try:
if file_path is None:
raise Exception("File path received it's None")
if version_info.major >= 3:
if not is_encoding:
encoding = None
with open(file_path, encoding=encoding) as buff:
text = buff.read()
if version_info.major <= 2:
with open(file_path) as buff:
if is_encoding:
text = buff.read().decode(encoding)
else:
text = buff.read()
if is_json:
return json.loads(text)
except Exception as err:
if not ignore_raises:
raise Exception(err)
return text


def read(file_name=None, is_encoding=True, ignore_raises=False):
"""Read file"""
if file_name is None:
raise Exception("File name not provided")
if ignore_raises:
try:
return read_file(
is_encoding=is_encoding,
file_path=path_format(
file_path=CURR_PATH,
file_name=file_name,
ignore_raises=ignore_raises))
except Exception:
# TODO: not silence like this,
# must be on setup.cfg, README path
return 'NOTFOUND'
return read_file(is_encoding=is_encoding,
file_path=path_format(
file_path=CURR_PATH,
file_name=file_name,
ignore_raises=ignore_raises))

setup(
name='colorpattern',
version='1.1',
author='croketillo',
author_email='[email protected]',
packages=find_packages(),
install_requires=[
'colorama',
],
description='Effortless console text colorization based on user-defined patterns in Python."',
long_description=read("README.rst"),
url='https://github.com/croketillo/colorpattern',
classifiers=[
'Environment :: Console', # Proyecto diseñado para ejecutarse en la consola
'Intended Audience :: Developers', # Audiencia a la que se dirige el proyecto
'Programming Language :: Python :: 3', # Indica que el proyecto es compatible con Python 3
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Topic :: Terminals', # Relacionado con la manipulación de terminales y consolas
'Topic :: Software Development :: Libraries :: Python Modules', # Relacionado con desarrollo de software
'Topic :: Utilities', # Utilidades generales
],
keywords='color pattern console',
entry_points={
'console_scripts': [
'colorpattern = colorpattern.colorpattern:main',
],
},
)
12 changes: 12 additions & 0 deletions test/colorpattern_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from colorpattern.colorpattern import *


pattern1 = SetPattern(r'\d+',color=Fore.GREEN)
pattern2 = SetPattern(r'Colorpattern',color=Fore.LIGHTRED_EX, underline=True)
pattern3 = SetPattern(r'Croketillo',color=Fore.RED,back=Back.LIGHTYELLOW_EX, style=Style.BRIGHT)
email = SetPattern(r'\b[A-Za-z0.9._%+-]+@[A-Za-z0.9.-]+\.[A-Z|a-z]{2,7}\b', color=Fore.LIGHTCYAN_EX)

start_color([pattern1,pattern2,pattern3, email])

print('2133 Colorpattern 432423')
print('By Croketillo - [email protected]')

0 comments on commit ecdd804

Please sign in to comment.