diff --git a/.gitignore b/.gitignore index 9839280..56a1c24 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ build/ dist/ colout.egg-info/ +.eggs/ diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..bd53a0b --- /dev/null +++ b/.travis.yml @@ -0,0 +1,15 @@ +language: python +python: + - "2.7" + - "3.3" + - "3.4" + - "3.5" + - "3.6" + - "3.7-dev" + - "pypy" + - "pypy3" +install: + - pip install . +script: + - colout --help + - echo heyoo | colout hey yellow diff --git a/README.md b/README.md index 7688266..cce451b 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,13 @@ colout(1) -- Color Up Arbitrary Command Output ============================================== -## SYNOPSIS +## Synopsis `colout` [-h] [-r RESOURCE] `colout` [-g] [-c] [-l min,max] [-a] [-t] [-T DIR] [-P DIR] [-d COLORMAP] [-s] [-e CHAR] [-E CHAR] [--debug] PATTERN [COLOR(S) [STYLE(S)]] -## DESCRIPTION +## Description `colout` read lines of text stream on the standard input and output characters matching a given regular expression *PATTERN* in given *COLOR* and *STYLE*. @@ -54,8 +54,8 @@ Before interpreting the matched string as a number, colout will remove any character not supposed to be used to write down numbers. This permits to apply this special color on a large group, while interpreting only its numerical part. -If the python3-pygments library is installed, you can use the name of a -syntax-coloring "lexer" as a color (for example: "Cpp", "ruby", "xml+django", etc.). +You can use the name of a syntax-coloring ["lexer"](http://pygments.org/docs/lexers/) +as a color (for example: "Cpp", "ruby", "xml+django", etc.). If GIMP palettes files (\*.gpl) are available, you can also use their names as a colormap (see the `-P` switch below). @@ -68,8 +68,7 @@ When not specified, a *COLOR* defaults to _red_ and a *STYLE* defaults to _bold_ `colout` comes with some predefined themes to rapidly color well-known outputs (see the `-t` switch below). -If the python3-pygments library is available, `colout` can be used as an interface -to it (see also the `-s` switch below). +`colout` can be used as an interface to pygments (see also the `--source` switch below). To have a list of all colors, styles, special colormaps, themes, palettes and lexers, use the `-r` switch (see below). @@ -77,37 +76,28 @@ use the `-r` switch (see below). `colout` is released under the GNU Public License v3. -## INSTALLATION +## Installation - sudo python3 setup.py install +The reccomended method is using [pipsi](https://github.com/mitsuhiko/pipsi) +``` +pipsi install colout +``` -and then soft link `/usr/local/bin/colout` to your colout.py under your installation -directory, which is usually something like +Another method is to use pip to install the package for the local user: - /usr/local/lib/python3/dist-packages/colout-0.1-py3.egg/colout/colout.py +``` +pip install --user colout +``` +There is also a PPA for Ubuntu 16.04 (Xenial)/18.04 (Bionic) -## OTHER INSTALLATION METHOD +``` +sudo add-apt-repository ppa:csaba-kertesz/random +sudo apt-get update +sudo apt-get/aptitude install colout +``` -Pypi (the Python Package Index) - - sudo pip install colout - -or - - sudo easy_install colout - -Ubuntu PPA for 16.04 (Xenial)/18.04 (Bionic) - - sudo add-apt-repository ppa:csaba-kertesz/random - sudo apt-get update - sudo apt-get/aptitude install colout - -Gentoo - - sudo emerge colout - -## OPTIONS +## Options * `-h`, `--help`: Show a help message and exit @@ -164,7 +154,7 @@ Gentoo Debug mode: print what's going on internally, if you want to check what features are available. -## REGULAR EXPRESSIONS +## Regular expressions A regular expression (or _regex_) is a pattern that describes a set of strings that matches it. @@ -174,15 +164,7 @@ that matches it. special characters that would be recognize by your shell. -## DEPENDENCIES - -Recommended packages: - -* `pygments` for the source code syntax coloring -* `babel` for a locale-aware number parsing - - -## LIMITATIONS +## Limitations Don't use nested groups or colout will duplicate the corresponding input text with each matching colors. @@ -192,7 +174,7 @@ Using a default colormap that is incompatible with the special colormap's mode Color pairs ("foreground.background") work in 8-colors mode for simple coloring, but may fail with `--colormap`. -## EXAMPLES +## Examples ### Simple diff --git a/bin/colout b/bin/colout deleted file mode 100644 index 7702d17..0000000 --- a/bin/colout +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/bash -# Copyright (c) 2013 Martin Ueding - -# Small launcher script for the main module. - -# Licence: GPL 3 - -set -e -set -u - -python3 -m colout.colout "$@" diff --git a/colout/colout.py b/colout/colout.py index 29ca071..3cfaa61 100755 --- a/colout/colout.py +++ b/colout/colout.py @@ -20,6 +20,7 @@ import logging import argparse import importlib import functools +import babel.numbers as bn # set the SIGPIPE handler to kill the program instead of # ending in a write error when a broken pipe occurs @@ -42,6 +43,8 @@ context["styles"] = { "reverse": 7, "conceal": 8 } +error_codes = {"UnknownColor": 1, "DuplicatedPalette": 2, "MixedModes": 3, "UnknownLexer": 4} + # Available color names in 8-colors mode. eight_colors = ["black","red","green","yellow","blue","magenta","cyan","white"] # Given in that order, the ASCII code is the index. @@ -290,35 +293,31 @@ def load_lexers(): global context # load available pygments lexers lexers = [] + global get_lexer_by_name + from pygments.lexers import get_lexer_by_name + + global highlight + from pygments import highlight + + global Terminal256Formatter + from pygments.formatters import Terminal256Formatter + + global TerminalFormatter + from pygments.formatters import TerminalFormatter + + from pygments.lexers import get_all_lexers try: - global get_lexer_by_name - from pygments.lexers import get_lexer_by_name + for lexer in get_all_lexers(): + try: + lexers.append(lexer[1][0]) + except IndexError: + logging.warning("cannot load lexer: %s" % lexer[1][0]) + pass + except: + logging.warning("error while executing the pygment module, syntax coloring is not available") - global highlight - from pygments import highlight - - global Terminal256Formatter - from pygments.formatters import Terminal256Formatter - - global TerminalFormatter - from pygments.formatters import TerminalFormatter - - from pygments.lexers import get_all_lexers - except ImportError: - logging.warning("the pygments module has not been found, syntax coloring is not available") - else: - try: - for lexer in get_all_lexers(): - try: - lexers.append(lexer[1][0]) - except IndexError: - logging.warning("cannot load lexer: %s" % lexer[1][0]) - pass - except: - logging.warning("error while executing the pygment module, syntax coloring is not available") - - lexers.sort() - logging.debug("loaded %i lexers: %s" % (len(lexers), ", ".join(lexers))) + lexers.sort() + logging.debug("loaded %i lexers: %s" % (len(lexers), ", ".join(lexers))) context["lexers"] = lexers @@ -409,23 +408,11 @@ def color_scale( name, text ): nb = "".join([i for i in filter(allowed.__contains__, text)]) # interpret as decimal - # First, try with the babel module, if available - # if not, use python itself, - # if thoses fails, try to `eval` the string - # (this allow strings like "1/2+0.9*2") f = None try: - # babel is a specialized module - import babel.numbers as bn - try: - f = float(bn.parse_decimal(nb)) - except bn.NumberFormatError: - pass - except ImportError: - try: - f = float(nb) - except ValueError: - pass + f = float(bn.parse_decimal(nb)) + except bn.NumberFormatError: + pass if f is not None: # normalize with scale if it's a number f = (f - context["scale"][0]) / (context["scale"][1]-context["scale"][0]) @@ -830,11 +817,6 @@ def _args_parse(argv, usage=""): help="A regular expression") pygments_warn=" You can use a language name to activate syntax coloring (see `-r all` for a list)." - try: - import pygments - except ImportError: - pygments_warn=" (WARNING: python3-pygments is not available, \ - install it if you want to be able to use syntax coloring)" parser.add_argument("color", metavar="COLOR", type=str, nargs='?', default="red", @@ -854,12 +836,6 @@ def _args_parse(argv, usage=""): (cycle the colors at each match)") babel_warn=" (numbers will be parsed according to your locale)" - try: - # babel is a specialized module - import babel.numbers - except ImportError: - babel_warn=" (WARNING: python3-babel is not available, install it \ - if you want to be able to parse numbers according to your locale)" parser.add_argument("-l", "--scale", metavar="SCALE", help="When using the 'scale' colormap, parse matches as decimal numbers \ @@ -927,10 +903,8 @@ def write_all( as_all, stream_in, stream_out, function, *args ): map_write( stream_in, stream_out, function, *args ) -if __name__ == "__main__": - - error_codes = {"UnknownColor":1, "DuplicatedPalette":2, "MixedModes":3} - +def main(): + global context usage = "A regular expression based formatter that color up an arbitrary text stream." ##################### @@ -1075,7 +1049,9 @@ if __name__ == "__main__": # if pygments elif as_source: logging.debug("asked for lexer: %s" % pattern.lower()) - assert(pattern.lower() in context["lexers"]) + if pattern.lower() not in context["lexers"]: + logging.error("Lexer %r is not available. Run with \"--resources all\" to see the options.") + sys.exit(error_codes["UnknownLexer"]) lexer = get_lexer_by_name(pattern.lower()) # Python => 256 colors, python => 8 colors ask_256 = pattern[0].isupper() @@ -1108,3 +1084,6 @@ if __name__ == "__main__": + " Check the following 'color:mode' pairs: %s." % e ) sys.exit( error_codes["MixedModes"] ) + +if __name__ == "__main__": + main() diff --git a/setup.py b/setup.py index 33e99b4..9457291 100644 --- a/setup.py +++ b/setup.py @@ -9,17 +9,36 @@ except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': - os.system('python3 setup.py sdist upload') + os.system('python setup.py bdist_wheel --universal upload') sys.exit() packages = ['colout'] -requires = ['argparse; python_version < "2.7"', 'pygments', 'babel'] +requires = ['pygments', 'babel'] + +setup_requires = ['setuptools_scm'] + +classifiers = """ +Environment :: Console +License :: OSI Approved :: GNU General Public License v3 (GPLv3) +Programming Language :: Python :: 2 +Programming Language :: Python :: 2.7 +Programming Language :: Python :: 3 +Programming Language :: Python :: 3.3 +Programming Language :: Python :: 3.4 +Programming Language :: Python :: 3.5 +Programming Language :: Python :: 3.6 +Programming Language :: Python :: 3.7 +""".strip().split('\n') setup( name='colout', - version='0.6', + use_scm_version=True, + classifiers=classifiers, description='Color Up Arbitrary Command Output.', + entry_points={ + 'console_scripts': ['colout=colout.colout:main'], + }, long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(), author='nojhan', author_email='nojhan@nojhan.net', @@ -27,7 +46,8 @@ setup( packages=packages, package_data={'': ['LICENSE', 'README.md']}, package_dir={'colout': 'colout'}, - scripts=['bin/colout'], + python_requires='>=2.7,!=3.0.*,!=3.1.*,!=3.2.*', + setup_requires=setup_requires, include_package_data=True, install_requires=requires, license='GPLv3',