#!/usr/bin/env python3
# coding=utf-8
#
# Copyright 2016 Ville Rantanen
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see .
#
"""Color by ${X} notation."""
__author__ = "Ville Rantanen "
__version__ = "0.1"
import sys, os, argparse, re
from argparse import ArgumentParser
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
import ansicodes as ansi
def setup_options():
""" Create command line options """
usage = (
"""
Color notation renderer in ANSI codes
Special syntaxes:
* Colors: insert string ${X}, where X values in the table below.
"""
+ ansi.demo()
)
parser = ArgumentParser(
description=usage,
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__author__,
)
parser.add_argument("-v", "--version", action="version", version=__version__)
parser.add_argument(
"--no-color",
"-n",
action="store_false",
dest="color",
default=True,
help="Disable color.",
)
parser.add_argument(
"-z",
action="store_true",
dest="zero",
default=False,
help="Reset coloring at the end of each line.",
)
parser.add_argument(
"-Z",
action="store_false",
dest="zero_final",
default=True,
help="Disable reset of colors at the end of file.",
)
parser.add_argument("filename", type=str, help="File to show, - for stdin")
opts = parser.parse_args()
return opts
bc = ansi.code()
opts = setup_options()
if opts.filename == "-":
f = sys.stdin
else:
f = open(opts.filename, "r")
for row in f:
if not row:
continue
if type(row) == bytes:
row = row.decode("utf-8")
row = row.rstrip("\n\r ")
if opts.color:
colored = bc.color_string(row)
else:
colored = bc.nocolor_string(row)
sys.stdout.write(colored)
if opts.zero and opts.color:
sys.stdout.write(bc.Z)
sys.stdout.write("\n")
if opts.zero_final and opts.color:
sys.stdout.write(bc.Z)