diff --git a/fixit/cli.py b/fixit/cli.py index 254c493..215d3d9 100644 --- a/fixit/cli.py +++ b/fixit/cli.py @@ -13,6 +13,7 @@ __version__, bases, coin, + color, convert, dates, dice, @@ -219,6 +220,23 @@ def run_morse(args: argparse.Namespace) -> None: except ValueError as exc: raise ValueError(str(exc)) from exc + +def run_color(args: argparse.Namespace) -> None: + """Convert colors between RGB, HSV, HSL and hex.""" + if args.action == "hex2rgb": + + print(*color.hex_to_rgb(args.values[0])) + return + + r, g, b = (int(v) for v in args.values) + if args.action == "rgb2hex": + print(color.rgb_to_hex(r, g, b)) + elif args.action == "rgb2hsv": + print(*color.rgb_to_hsv(r, g, b)) + elif args.action == "rgb2hsl": + print(*color.rgb_to_hsl(r, g, b)) + + COMMAND_TABLE = { "wc": run_wc, "convert": run_convert, @@ -243,7 +261,7 @@ def run_morse(args: argparse.Namespace) -> None: "days-until": run_days_until, "age": run_age, "morse": run_morse, - + "color": run_color, } def finite_float(value: str) -> float: @@ -387,6 +405,10 @@ def build_parser() -> argparse.ArgumentParser: morse_parser.add_argument("text", help="text or Morse code to process") morse_parser.add_argument("--decode", action="store_true", help="decode Morse code to text") + col = sub.add_parser("color", help="convert colors between RGB, HSV, HSL and hex") + col.add_argument("action", choices=["rgb2hsv", "rgb2hsl", "rgb2hex", "hex2rgb"]) + col.add_argument("values", nargs="+", help="three RGB numbers (0-255), or one hex color") + return parser diff --git a/fixit/color.py b/fixit/color.py new file mode 100644 index 0000000..2054eea --- /dev/null +++ b/fixit/color.py @@ -0,0 +1,48 @@ +"""Color conversions between RGB, HSV, HSL and hex.""" + +import colorsys + + +def check_rgb(r, g, b): + """Raise ValueError if any RGB value is outside 0-255.""" + for value in (r, g, b): + if not 0 <= value <= 255: + raise ValueError("Error: RGB values must be between 0 and 255") + + +def rgb_to_hsv(r, g, b): + """Convert RGB (0-255) to (H degrees, S percent, V percent).""" + check_rgb(r, g, b) + h, s, v = colorsys.rgb_to_hsv(r / 255, g / 255, b / 255) + return round(h * 360), round(s * 100), round(v * 100) + + +def rgb_to_hsl(r, g, b): + """Convert RGB (0-255) to (H degrees, S percent, L percent).""" + check_rgb(r, g, b) + h, l, s = colorsys.rgb_to_hls(r / 255, g / 255, b / 255) # H, L, S order + return round(h * 360), round(s * 100), round(l * 100) + + +def rgb_to_hex(r, g, b): + """Convert RGB (0-255) to an uppercase '#RRGGBB' string.""" + check_rgb(r, g, b) + return f"#{r:02X}{g:02X}{b:02X}" + + +def hex_to_rgb(value): + """ + Convert a 3- or 6-letter hex color, with or without '#', to RGB. + A 6-letter hex color is in the form #FFFFFF while a 3-letter + is like #FA0, with the understanding that each letter is doubled, + like becoming #FFAA00. This is a CSS convention. + """ + value = value.lstrip("#") + if len(value) == 3: + value = "".join(ch * 2 for ch in value) + if len(value) != 6: + raise ValueError("Error: hex color must have 3 or 6 digits") + try: + return int(value[0:2], 16), int(value[2:4], 16), int(value[4:6], 16) + except ValueError: + raise ValueError("Error: invalid hex digits") diff --git a/tests/test_color.py b/tests/test_color.py new file mode 100644 index 0000000..09a411b --- /dev/null +++ b/tests/test_color.py @@ -0,0 +1,36 @@ +import pytest + +from fixit import color + + +def test_rgb_to_hsv(): + assert color.rgb_to_hsv(255, 0, 0) == (0, 100, 100) + + +def test_rgb_to_hsl(): + assert color.rgb_to_hsl(255, 0, 0) == (0, 100, 50) + + +def test_rgb_to_hex(): + assert color.rgb_to_hex(255, 255, 255) == "#FFFFFF" + + +def test_hex_to_rgb(): + assert color.hex_to_rgb("FFFFFF") == (255, 255, 255) + assert color.hex_to_rgb("#F00") == (255, 0, 0) + + +def test_round_trip(): + assert color.rgb_to_hex(*color.hex_to_rgb("#1A2B3C")) == "#1A2B3C" + + +def test_rgb_out_of_range(): + with pytest.raises(ValueError): + color.rgb_to_hex(256, 0, 0) + + +def test_bad_hex(): + with pytest.raises(ValueError): + color.hex_to_rgb("#12") + with pytest.raises(ValueError): + color.hex_to_rgb("GGGGGG") \ No newline at end of file