Terminal Formatting Utilities Feature Documentation

Overview

The nokill/formatting.py module provides consistent, rich-formatted console output for the NoKill K9s plugin. It centralizes color codes, layout logic, and fallbacks for environments without the Rich library. This ensures all sections, metrics, notes, and tables render clearly in both interactive and plain terminals.

By abstracting styling and printing concerns, the module streamlines report rendering across views. Users see colored headers, status chips, KPI summaries, and tables without repeating boilerplate formatting code.

Module Structure

⚙️ Configuration & Initialization

  • _RICH_AVAILABLE

    • Flag set to True if the Rich library imports succeed.
    • Fallback path sets it to False when Rich is unavailable.
  • _CONSOLE

    • Cached rich.console.Console instance or None.
    • Initialized on first use by _get_console().

🖥️ Rich Console Setup

_rich_enabled() -> bool

Checks if Rich formatting is enabled.

_get_console() -> Console

Creates and configures a shared Rich Console for K9s pager output.

  • force_terminal: Always treat output as a terminal
  • color_system: Standard ANSI colors
  • markup: Enable inline markup tags
  • Honors NO_COLOR environment variable

🎨 Styling Utilities

These functions apply ANSI and Rich-specific styles.

colorize(text: str, color_code: str) -> str

Wraps text in ANSI color codes.

style_bool(value: bool, true_color: str = GREEN, false_color: str = RESET, true_text: str = "YES", false_text: str = "NO") -> str

Formats a boolean as colored "YES"/"NO" strings.

status_chip(text: str, level: str = "info") -> str

Creates a colored label using Rich markup for statuses.

  • Levels: ok, warn, error, info, neutral

now_label() -> str

Returns the current local timestamp in YYYY-MM-DD HH:MM:SS format.

📋 Printing Functions

These methods render sections, KPIs, notes, and tables with Rich or fallback output.

Prints a boxed panel header with Rich or plain text.

  • Rich: Displays title in cyan and subtitle inside a rounded panel.
  • Fallback: Prints title and, if provided, subtitle on the next line.

Renders key metrics in a single row.

  • Rich: Uses a simple table without headers.
  • Fallback: Joins pairs with “ | ”.

Outputs a contextual note line.

  • Levels map to colored prefixes: INFO, WARN, ERROR.
  • Rich: Emits a colored prefix and message.
  • Fallback: Prints [LEVEL] message.

Displays a table with optional per-row styles.

  • Rich: Uses heavy borders and wraps overflow.
  • Fallback: Uses tabulate with a simple format.

Backward-compatible alias for print_rich_table.

Function Reference

Function Description Key Parameters
_rich_enabled Check if Rich is available –
_get_console Initialize or retrieve shared Rich Console –
colorize Wrap text with ANSI escape codes text, color_code
style_bool Format booleans as colored "YES"/"NO" value, true_color, false_color, true_text, false_text
status_chip Create a Rich-styled status label text, level
now_label Generate a compact timestamp label –
print_header Render a section header title, subtitle
print_kpis Print key performance indicators row kpi_pairs
print_note Display a contextual note line text, level
print_rich_table Show table with Rich or fallback formatting columns, rows, row_styles
print_table Alias for print_rich_table headers, data

Usage Patterns

  • When Rich is installed, all output uses rich panels, tables, and markup.
  • When Rich is unavailable or NO_COLOR is set, the module falls back to plain prints and ANSI codes.
  • Use status_chip to highlight critical values inside tables.
  • Use style_bool to embed colored "YES"/"NO" labels inline.
from nokill.formatting import print_header, print_kpis, status_chip

print_header("Cluster Report", "Updated 2023-09-01 12:00:00")
print_kpis([("Nodes", "5"), ("Disrupting", "2")])
label = status_chip("ERROR", "error")
print(f"Overall Status: {label}")

Dependencies

  • rich (optional): Provides advanced console styling.
  • tabulate: Renders fallback tables.
  • datetime, os, sys, typing: Standard library modules.

Testing Considerations

The tests/test_formatting.py suite verifies:

  • Fallback path when _RICH_AVAILABLE is False and _CONSOLE is None.
  • Plain output contains titles, subtitles, KPI pairs, and note prefixes.
  • status_chip generates markup tags around text when Rich is enabled.

Key Constants

Constant Value Description
RESET "\033[0m" ANSI reset code
BOLD "\033[1m" ANSI bold code
RED "\033[31m" ANSI red code
GREEN "\033[32m" ANSI green code
YELLOW "\033[33m" ANSI yellow code
BLUE "\033[34m" ANSI blue code
CYAN "\033[36m" ANSI cyan code
MAGENTA "\033[35m" ANSI magenta code

This documentation covers all core utilities in nokill/formatting.py. It explains how the module configures styling, integrates with Rich, and falls back cleanly when needed.