Something went wrong. Try again.
Command line interface for accessing the Open Web Index shards and slices.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384"""Output Writer - Unified output handling for all CLI commands.
Supports multiple output formats:- TABLE: Rich tables for human-readable output (default)- JSON: Single JSON array- JSONL: JSON Lines for streaming/piping- Future: AVRO via plugins"""from enum import Enumfrom typing import Iterator, List, Dict, Any, Optional, Unionimport jsonimport sys
from rich.console import Consolefrom rich.table import Table
class OutputFormat(str, Enum): """Supported output formats.""" TABLE = "table" # Rich tables (default, human-readable) JSON = "json" # Single JSON array JSONL = "jsonl" # JSON Lines (streaming) # Future formats via plugins # AVRO = "avro" # PARQUET = "parquet"
class OutputWriter: """ Unified output handler for all commands. Handles output format, destination (file or stdout), and streaming. Commands use this to ensure consistent output behavior. Usage: writer = OutputWriter(ctx) writer.write_records(datasets) # Iterator of dicts writer.close() """ def __init__(self, ctx: "CLIContext"): """ Initialize output writer from CLI context. """ self.ctx = ctx self.format = OutputFormat(ctx.output_format) self.console = ctx.console self._file = None # Parse field customization from context self.show_fields = [] self.hide_fields = [] if getattr(ctx, 'fields', None): for f in ctx.fields.split(','): f = f.strip() if f.startswith('+'): self.show_fields.append(f[1:].lower()) elif f.startswith('-'): self.hide_fields.append(f[1:].lower()) else: self.show_fields.append(f.lower()) # Open output file if specified if ctx.output_file: self._file = open(ctx.output_file, 'w', encoding='utf-8') def _is_field_visible(self, field_name: str, default_visible: bool = True) -> bool: """Check if field should be shown based on customization.""" field_name = field_name.lower() if field_name in self.hide_fields: return False if field_name in self.show_fields: return True return default_visible
def write_records( self, records: Union[Iterator[Dict[str, Any]], List[Dict[str, Any]]], title: Optional[str] = None, columns: Optional[List[str]] = None, ): """ Write records to output in the configured format. Args: records: Iterator or list of dictionaries to output title: Optional title for table output columns: Optional column order (auto-detected if None) """ # Convert iterator to list if needed for non-streaming formats if self.format == OutputFormat.JSONL: self._write_jsonl(records) elif self.format == OutputFormat.JSON: self._write_json(list(records) if not isinstance(records, list) else records) elif self.format == OutputFormat.TABLE: # Filter columns if customized if columns is None and records: # Get all keys but filter all_keys = list(records[0].keys()) if isinstance(records, list) else [] columns = [k for k in all_keys if self._is_field_visible(k)] self._write_table( list(records) if not isinstance(records, list) else records, title=title, columns=columns ) def write_message(self, message: str, style: Optional[str] = None): """Write a simple message (only in non-JSON modes).""" if self.format == OutputFormat.TABLE: if style: self.console.print(message, style=style) else: self.console.print(message) def _write_jsonl(self, records: Iterator[Dict[str, Any]]): """Write records as JSON Lines (streaming).""" for record in records: line = json.dumps(record, ensure_ascii=False, default=str) self._write_line(line) def _write_json(self, records: List[Dict[str, Any]]): """Write records as single JSON array.""" output = json.dumps(records, indent=2, ensure_ascii=False, default=str) self._write_line(output) def _write_table( self, records: List[Dict[str, Any]], title: Optional[str] = None, columns: Optional[List[str]] = None, ): """Write records as Rich table.""" if not records: self.console.print("[dim]No results[/dim]") return # Auto-detect columns from first record if not specified if columns is None: columns = list(records[0].keys()) # Create table table = Table(title=title, show_header=True, header_style="bold") for col in columns: table.add_column(col) # Add rows for record in records: row = [str(record.get(col, "")) for col in columns] table.add_row(*row) # Output if not self.ctx.no_display: self.console.print(table) def write_datasets( self, datasets, display_format: str = "short", show_summary: bool = True, ): """ Write datasets in the specified display format. Args: datasets: List of Dataset objects display_format: 'short' (compact), 'wide' (table), or 'markdown' show_summary: Whether to show summary at end """ if not datasets: self.console.print("[dim]No datasets found[/dim]") return if display_format == "short": self._write_datasets_short(datasets) elif display_format == "wide": self._write_datasets_wide(datasets) elif display_format == "full": self._write_datasets_full(datasets) elif display_format == "markdown": self._write_datasets_markdown(datasets) else: self._write_datasets_short(datasets) if show_summary: total_size = sum(ds.metadata.get('totalSize', 0) or 0 for ds in datasets) total_files = sum(ds.metadata.get('fileCount', 0) or 0 for ds in datasets) total_objects = sum(ds.metadata.get('objectCount', 0) or 0 for ds in datasets) self.console.print( f"\n[bold]Summary:[/bold] {len(datasets)} datasets, {total_size/1e9:.1f} GB, " f"{total_files:,} files, {total_objects:,} objects" ) def _write_datasets_short(self, datasets): """ Compact single-line format: 📦 ID TITLE <DATE;COLL;DC> n=COUNT SIZE [ACCESS] Grep-friendly (no emojis/colors if not terminal). """ for d in datasets: ds_id = d.metadata.get("internalID", "N/A") or "N/A" title = d.metadata.get("title", "Untitled") or "Untitled" # Dates start_date = d.metadata.get("startDate", None) end_date = d.metadata.get("endDate", None) start = str(start_date)[:10] if start_date else "?" end = str(end_date)[:10] if end_date else start date_range = start if start == end else f"{start}→{end}" # Location dc = getattr(d, 'dataCenter', None) or "?" zone = getattr(d, 'zone', None) or d.metadata.get("zone", "?") or "?" coll = d.metadata.get("collectionName", "?") or "?" # Stats obj_count = d.metadata.get("objectCount", 0) or 0 total_size = d.metadata.get("totalSize", 0) or 0 size_gib = float(total_size) / (1024**3) access = getattr(d, 'access', None) or d.metadata.get("access", "?") # Single line format - includes Zone line = f"[bold cyan]📦\t{ds_id}[/]\t[bold]{title}[/]\t[dim]{date_range}\t{coll}\t{dc}\t{zone}\t[/]\t#={int(obj_count):,}\t{size_gib:.2f}GiB\t{access}" self.console.print(line)
def _write_datasets_wide(self, datasets): """ Rich Panel format with detailed metadata. Uses indented key-value pairs for better readability. """ from rich.panel import Panel from rich.text import Text from rich.box import ROUNDED for d in datasets: md = d.metadata content = Text() # Helper for fields def add_field(key, value, indent=0, style="dim", field_id=None): fid = field_id or key.lower() if self._is_field_visible(fid) and value: prefix = " " * indent content.append(f"{prefix}{key}: ", style="bold " + style) content.append(str(value) + "\n", style=style)
# Core Info add_field("Title", md.get("title"), style="cyan") add_field("ID", md.get("internalID")) # Detailed sections add_field("Path", d.path, indent=1) add_field("Dates", f"{md.get('startDate')} - {md.get('endDate')}", indent=1) add_field("Size", f"{md.get('totalSize', 0)/1e9:.2f} GB ({md.get('fileCount', 0)} files, {md.get('objectCount', 0)} objects)", indent=1) # Collection/Location add_field("Collection", md.get("collectionName"), indent=1) add_field("DataCenter", getattr(d, 'dataCenter', None), indent=1) add_field("Zone", getattr(d, 'zone', None) or md.get("zone"), indent=1) add_field("Access", getattr(d, 'access', None) or md.get("access"), indent=1) # Descriptions if self._is_field_visible("descriptions"): descriptions = md.get("descriptions", []) if isinstance(descriptions, str): descriptions = [descriptions] if descriptions: content.append(" Descriptions:\n", style="bold") for desc in descriptions[:3]: # Show first 3 if isinstance(desc, dict): txt = desc.get("description", "") dtype = desc.get("type", "") content.append(f" - [{dtype}] {txt[:100]}{'...' if len(txt)>100 else ''}\n") else: content.append(f" - {str(desc)[:100]}\n") # Creators if self._is_field_visible("creators"): creators = md.get("creators", []) if isinstance(creators, str): creators = [creators] if creators: names = [] for c in creators: if isinstance(c, dict): names.append(c.get("name", str(c))) else: names.append(str(c)) add_field("Creators", ", ".join(names), indent=1, field_id="creators")
# Render panel self.console.print(Panel( content, title=f"[bold]{md.get('title')}[/] ({md.get('internalID')})", expand=True, border_style="blue", box=ROUNDED )) def _write_datasets_full(self, datasets): """Show ALL metadata in a pager.""" import yaml # Collect all data all_output = [] for d in datasets: # Combine object attrs + metadata try: # Try explicit to_dict first if hasattr(d.metadata, 'to_dict'): data = d.metadata.to_dict() # Try internal dict storage elif hasattr(d.metadata, '_metadata'): data = dict(d.metadata._metadata) # Try direct iteration (if dict-like) else: data = dict(d.metadata) except Exception: # Fallback if metadata is opaque data = {"error": "Could not serialize metadata", "raw": str(d.metadata)} # Add implicit fields data['_path'] = str(d.path) data['_access'] = getattr(d, 'access', None) data['_dataCenter'] = getattr(d, 'dataCenter', None) # Format as YAML block try: yaml_str = yaml.dump(data, sort_keys=False, default_flow_style=False, allow_unicode=True) except Exception as e: yaml_str = f"Error dumping YAML: {e}\n{data}" all_output.append(f"---\n# Dataset: {data.get('title', 'Unknown')}\n{yaml_str}") # Page it if all_output: with self.console.pager(): self.console.print("\n".join(all_output)) else: self.console.print("[dim]No datasets to display[/dim]") def _write_datasets_markdown(self, datasets): """Markdown table format.""" headers = ["ID", "Title", "Collection", "DC", "Dates", "Size", "Files", "Objects"] self.console.print("| " + " | ".join(headers) + " |") self.console.print("|" + "|".join(["---"] * len(headers)) + "|") for d in datasets: ds_id = (d.metadata.get('internalID', '') or "")[:12] title = (d.metadata.get('title', '') or "")[:30] coll = d.metadata.get('collectionName', '') or "" dc = getattr(d, 'dataCenter', '') or "" start = str(d.metadata.startDate)[:10] if d.metadata.startDate else "?" size = f"{d.metadata.get('totalSize', 0) / 1e9:.1f}G" files = d.metadata.get('fileCount', 0) or 0 objects = d.metadata.get('objectCount', 0) or 0 row = [ds_id, title, coll, dc, start, size, str(files), str(objects)] self.console.print("| " + " | ".join(row) + " |") def _write_line(self, line: str): """Write a line to file or stdout.""" if self._file: self._file.write(line + '\n') elif not self.ctx.no_display: # Write to stdout for piping sys.stdout.write(line + '\n') sys.stdout.flush() def close(self): """Close output file if opened.""" if self._file: self._file.close() self._file = None def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() return False