Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion fixit/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
__version__,
bases,
coin,
color,
convert,
dates,
dice,
Expand Down Expand Up @@ -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,
Expand All @@ -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:
Expand Down Expand Up @@ -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


Expand Down
48 changes: 48 additions & 0 deletions fixit/color.py
Original file line number Diff line number Diff line change
@@ -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")
36 changes: 36 additions & 0 deletions tests/test_color.py
Original file line number Diff line number Diff line change
@@ -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")
Loading