Skip to content

Commit

Permalink
Add colors support (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
evilmarty authored Jul 30, 2024
1 parent 48ed176 commit c943285
Showing 1 changed file with 54 additions and 2 deletions.
56 changes: 54 additions & 2 deletions src/safaribookmarks/cli.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,46 @@
from io import UnsupportedOperation
import os
from typing import IO, List, Optional
from .safaribookmarks import SafariBookmarks, SafariBookmarkItem

DEFAULT_LIST_FORMAT = "{icon} {title: <50} {id: <38}{url}"
SIMPLE_FORMAT = "{icon} {title: <50} {url}"
DEFAULT_LIST_FORMAT = (
"{grey}{icon}{reset} {title: <50} {dark_grey}{id: <38}{cyan}{url}{reset}"
)
SIMPLE_FORMAT = "{grey}{icon}{reset} {title: <50} {cyan}{url}{reset}"
ICON_FIRST_LEAF = "┌"
ICON_MIDDLE_LEAF = "├"
ICON_LAST_LEAF = "└"
ICON_SINGLE_LEAF = "─"
ICON_LIST_CONTAINER = "│"

# Source: https://github.com/termcolor/termcolor/blob/main/src/termcolor/termcolor.py
COLORS: dict[str, int] = {
"reset": 0,
"black": 30,
"grey": 30,
"red": 31,
"green": 32,
"yellow": 33,
"blue": 34,
"magenta": 35,
"cyan": 36,
"light_grey": 37,
"dark_grey": 90,
"light_red": 91,
"light_green": 92,
"light_yellow": 93,
"light_blue": 94,
"light_magenta": 95,
"light_cyan": 96,
"white": 97,
}


class CLI:
def __init__(self, path: str, out: IO) -> None:
self.bookmarks = SafariBookmarks.open(path)
self.output = out
self.colors = generate_colors(out)

@property
def path(self) -> str:
Expand Down Expand Up @@ -42,6 +69,7 @@ def _render_item(
):
self.output.write(
f"{format}\n".format(
**self.colors,
icon=icon,
depth=depth,
title=item.title.replace("\n", ""),
Expand Down Expand Up @@ -161,3 +189,27 @@ def empty(self, path: List[str]):
raise ValueError("Target is not a list")
target.empty()
self._save()


def generate_colors(output: IO) -> dict[str, str]:
if supports_colors(output):
return {name: "\033[%dm" % code for name, code in COLORS.items()}
else:
return {name: "" for name in COLORS.keys()}


def supports_colors(tty: IO) -> bool:
if "ANSI_COLORS_DISABLED" in os.environ:
return False
if "NO_COLOR" in os.environ:
return False
if "FORCE_COLOR" in os.environ:
return True
if os.environ.get("TERM") == "dumb":
return False
if not hasattr(tty, "fileno"):
return False
try:
return os.isatty(tty.fileno())
except UnsupportedOperation:
return tty.isatty()

0 comments on commit c943285

Please sign in to comment.