common

package
v0.12.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 2, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Overview

Package common provides shared interfaces, types, and utilities for the Charta graph system.

This package defines the core abstractions that enable Charta's plugin architecture:

  • Grapher: The main interface that all graph types must implement
  • Graph: Shared configuration structure for all graph types
  • Plugin registration via the Plugins slice

Architecture

Charta uses a plugin-based architecture where each graph type (simple, minmax, compare, cumul, heatmap) registers itself during initialization. The common package provides:

  • Interface definitions for consistent graph behavior
  • Shared configuration parsing and management
  • File loading utilities for text, JSON, and YAML formats
  • Common printing helpers for titles, legends, and labels

Graph Types

All graph types implement the Grapher interface, which is composed of several smaller interfaces for specific functionality:

  • GraphBuilder: Factory method for creating new instances
  • GraphNamer: Returns the graph type name for CLI subcommands
  • GraphParser: Adds CLI arguments to the argument parser
  • GraphPrinter: Renders the graph to the terminal
  • GraphHelper: Displays help files for different input formats
  • GraphLoader: Processes input data from various sources

Usage

Graph plugins register themselves in their init() functions:

func init() {
    common.Plugins = append(common.Plugins, &Graph{Name: "mygraph"})
}

The main application then iterates through Plugins to set up CLI subcommands and dispatch to the appropriate handler.

Package common provides shared interfaces, types, and utilities for the Charta graph system. This file contains helper functions for the Graph type.

Package common - loader.go provides file loading and input processing utilities.

This file contains functions for:

  • Reading and parsing input from stdin, text files, and structured files
  • Processing lines of input data (values and configuration)
  • Loading JSON and YAML configuration files

Package common - parser.go provides command-line argument parsing utilities.

This file contains functions for:

  • Registering CLI arguments with the argparse library
  • Managing argument options and their default values
  • Converting string values to typed fields

Argument Types

The parser supports several argument types:

Options Registry

Arguments are registered in a global options map (opts) which allows dynamic field assignment via OptToField. This enables configuration from both CLI arguments and file-based settings.

Package common - printer.go provides common printing utilities for graphs.

This file contains functions for rendering graph elements to the terminal:

  • Title printing with centering and styling
  • Legend printing with formatting
  • Base Print implementation for common elements

Index

Constants

This section is empty.

Variables

View Source
var Plugins []Grapher

Plugins is the global registry of available graph type plugins. Each graph type registers itself here during package initialization. The main application iterates through this slice to set up CLI subcommands.

Functions

func AddChoiceArg added in v0.2.0

func AddChoiceArg(p *argparse.Parser, f *string, short, long, help, group, def string, choices []any, parsers []*argparse.Parser)

AddChoiceArg adds a string argument with a limited set of valid choices. The argument is registered in the options map for later retrieval.

Parameters:

  • p: Argument parser to add the argument to
  • f: Pointer to string field to store the value
  • short: Short flag name (e.g., "c")
  • long: Long flag name (e.g., "color")
  • help: Help text for the argument
  • group: Group name for organizing arguments
  • def: Default value
  • choices: List of valid choices
  • parsers: List of parsers to bind this argument to

func AddChoicesArg added in v0.3.0

func AddChoicesArg(p *argparse.Parser, f *[]string, short, long, help, group string, choices []any, parsers []*argparse.Parser)

AddChoiceArg adds a string array argument with a limited set of valid choices. The argument is registered in the options map for later retrieval.

Parameters:

  • p: Argument parser to add the argument to
  • f: Pointer to string field to store the value
  • short: Short flag name (e.g., "c")
  • long: Long flag name (e.g., "color")
  • help: Help text for the argument
  • group: Group name for organizing arguments
  • choices: List of valid choices
  • parsers: List of parsers to bind this argument to

func AddFileArg added in v0.2.0

func AddFileArg(p *argparse.Parser, f *string, short, long, help, group string, file_ext []string, parsers []*argparse.Parser)

AddFileArg adds a file argument to the argument parser with support for stdin and various file extensions. Stores the filename in Graph for later processing.

Parameters:

  • p: Argument parser to add the argument to
  • cg: Graph to store the filename
  • short: Short flag name (e.g., "f")
  • long: Long flag name (e.g., "file")
  • help: Help text for the argument
  • group: Group name for organizing arguments
  • file_ext: List of supported file extensions (without dots)

func AddFlagArg added in v0.3.0

func AddFlagArg(p *argparse.Parser, f *bool, short, long, help, group string, parsers []*argparse.Parser)

AddFlagArg adds a bool argument to the argument parser with default value handling. The argument is registered in the options map for later retrieval.

Parameters:

  • p: Argument parser to add the argument to
  • f: Pointer to string field to store the value
  • short: Short flag name (e.g., "l")
  • long: Long flag name (e.g., "label")
  • help: Help text for the argument
  • group: Group name for organizing arguments
  • parsers: List of parsers to bind this argument to

func AddHelpArg added in v0.2.0

func AddHelpArg(p *argparse.Parser, g GraphHelper, short, long, help, group string, choices []any)

AddHelpArg adds a help argument that displays help content for specific file types.

Parameters:

  • p: Argument parser to add the argument to
  • g: Graph implementation that provides help content
  • short: Short flag name (e.g., "H")
  • long: Long flag name (e.g., "help_for_file")
  • help: Help text for the argument
  • group: Group name for organizing arguments
  • choices: List of valid file type choices

func AddInParsers added in v0.3.0

func AddInParsers(k string, p *argparse.Parser)

AddInParsers registers a parser under a named category. This allows arguments to be bound to specific parser groups, enabling conditional argument availability based on graph type.

Parameters:

  • k: Category key (e.g., "generic", "minmax", "color", "label")
  • p: Parser to register under this category

func AddIntArg added in v0.2.0

func AddIntArg(p *argparse.Parser, f *int, short, long, help, group, def string, parsers []*argparse.Parser)

AddIntArg adds an integer argument to the argument parser with default value handling. The argument is registered in the options map for later retrieval.

Parameters:

  • p: Argument parser to add the argument to
  • f: Pointer to int field to store the value
  • short: Short flag name (e.g., "w")
  • long: Long flag name (e.g., "width")
  • help: Help text for the argument
  • group: Group name for organizing arguments
  • def: Default value as string
  • parsers: List of parsers to bind this argument to

func AddIntOpt added in v0.2.0

func AddIntOpt(f *int, long string, def int)

AddIntOpt registers an integer option in the options map without adding it to a parser. Used for options that need to be accessible via OptToField.

Parameters:

  • f: Pointer to int field to store the value
  • long: Option name
  • def: Default value

func AddStringArg added in v0.2.0

func AddStringArg(p *argparse.Parser, f *string, short, long, help, group, def string, parsers []*argparse.Parser)

AddStringArg adds a string argument to the argument parser with default value handling. The argument is registered in the options map for later retrieval.

Parameters:

  • p: Argument parser to add the argument to
  • f: Pointer to string field to store the value
  • short: Short flag name (e.g., "l")
  • long: Long flag name (e.g., "label")
  • help: Help text for the argument
  • group: Group name for organizing arguments
  • def: Default value
  • parsers: List of parsers to bind this argument to

func AddStringOpt added in v0.2.0

func AddStringOpt(f *string, long string, def string, choices []interface{})

AddStringOpt registers a string option in the options map without adding it to a parser. Used for options that need to be accessible via OptToField.

Parameters:

  • f: Pointer to string field to store the value
  • long: Option name
  • def: Default value
  • choices: Valid choices (if applicable)

func AddStringsArg added in v0.3.0

func AddStringsArg(p *argparse.Parser, f *[]string, short, long, help, group string, parsers []*argparse.Parser)

AddStringsArg adds a string argument to the argument parser with default value handling. The argument is registered in the options map for later retrieval.

Parameters:

  • p: Argument parser to add the argument to
  • f: Pointer to string field to store the value
  • short: Short flag name (e.g., "l")
  • long: Long flag name (e.g., "label")
  • help: Help text for the argument
  • group: Group name for organizing arguments
  • parsers: List of parsers to bind this argument to

func ObjFromFile added in v0.4.0

func ObjFromFile(filename string, fileExt string, obj any) error

ObjFromFile reads and parses a file into a generic structure based on the file extension. This is a common implementation used by all graph types for structured file parsing. Supports JSON (.json) and YAML (.yaml, .yml) formats.

Parameters:

  • filename: Path to the file to read
  • fileExt: File extension to determine parsing method
  • obj: Pointer to the structure to unmarshal into

Returns:

  • error: Any error encountered during file reading or parsing

func OptToField added in v0.2.0

func OptToField(k, v string) (find bool)

OptToField assigns a value to a registered option field by name. Performs type-safe conversion based on the option's type. Optimized with fast type switching and early returns.

For integer options, if the value cannot be parsed as an integer, the function returns false without modifying the field. Default values are only applied by the argparse Action handlers, not by OptToField.

Parameters:

  • k: Option name
  • v: Value to assign as string

Returns:

  • find: true if the option was found and assigned successfully

func ParseLine added in v0.5.0

func ParseLine(g any, line string) (printed bool)

ParseLine processes a single line of input data for any graph type with optimized string handling. It handles three types of input with minimal string allocations:

  1. Special commands: "new" resets values, "new=graph" resets display state
  2. Configuration: "key=value" pairs update graph settings
  3. Numeric values: Single values for SingleValuer, space-separated pairs for MultiValuer

The function uses efficient string parsing to minimize memory allocations and improve performance for large input files.

Parameters:

Returns:

  • printed: true if the graph was rendered as a result of this line

Example input lines:

"42.5"           - Single numeric value
"10.5 20.3"      - Value pair for compare graphs
"width=80"       - Configuration setting
"new"            - Reset values for new data series
"new=graph"      - Reset display state for new graph

func ProcessFile added in v0.2.0

func ProcessFile(g Grapher, filename string) error

ProcessFile determines the file type and delegates to the appropriate processing method. Supports text files (.txt, .text), JSON (.json), and YAML (.yaml, .yml) formats. Uses optimized file extension matching to avoid repeated filepath.Ext calls.

Parameters:

  • g: Graph implementation to process the file
  • filename: Path to the file to process

Returns:

  • error: Any error encountered during file processing

func ProcessStdin added in v0.5.0

func ProcessStdin(g Grapher)

ProcessStdin reads and processes graph data from standard input. This is the primary method for streaming data to graphs in real-time.

The function reads lines from stdin until EOF, processing each line through ScanFile which handles parsing and graph updates.

Parameters:

  • g: Graph implementation to receive the data

Example usage:

echo -e "10\n20\n30" | charta simple

func ProcessTextFile added in v0.5.0

func ProcessTextFile(g Grapher, f string) error

ProcessTextFile reads and processes a plain text file containing graph data. Each line in the file is processed as either a configuration setting or a value.

The file format supports:

  • Numeric values (one per line)
  • Configuration settings (key=value format)
  • Comments (lines starting with #)
  • Empty lines (ignored)

Parameters:

  • g: Graph implementation to process the file
  • f: Path to the text file

Returns:

  • error: Any error encountered during file opening or processing

func ScanFile added in v0.2.0

func ScanFile(g Grapher, f io.Reader) error

ScanFile reads and processes lines from an io.Reader, parsing each line through the provided Graph implementation. It skips empty lines and comments (lines starting with #), and ensures the graph is printed at least once.

Parameters:

  • g: Grapher implementation to process the lines
  • f: io.Reader to read lines from

Returns:

  • error: Any error encountered during scanning

Types

type Graph

type Graph struct {
	File          string              // Input file path or "stdin" for standard input
	GroupBy       int                 // Number of values to group together before printing
	Min           int                 // Minimum scale value (0 for auto-scale)
	Max           int                 // Maximum scale value (0 for auto-scale)
	Width         int                 // Graph width in characters (default: 100)
	Label         string              // Label text displayed before each graph line
	Color         string              // Override color name (e.g., "red", "green", "blue")
	LabelColor    string              // Color for the label text
	Warning       int                 // Threshold for warning color (yellow)
	Alert         int                 // Threshold for alert color (red)
	ActiveGraph   Grapher             // Currently active graph plugin instance
	Title         string              // Graph title displayed at the top
	TitleColor    string              // Color for the title text
	Legend        string              // Legend text for multi-segment graphs
	TitlePrinted  bool                // Flag to prevent duplicate title printing
	LegendPrinted bool                // Flag to prevent duplicate legend printing
	GroupType     string              // Grouping aggregation type: "avg" or "sum"
	Condensed     bool                // Use Braille characters for condensed display
	FormatterName string              // Name of the formatter plugin to use
	Formatter     formatter.Formatter // Formatter
}

Graph holds shared configuration and state for all graph types. It provides common functionality like argument parsing and plugin management.

Graph types embed this struct to inherit common configuration fields and can override or extend behavior as needed. The ActiveGraph field points to the currently selected graph implementation.

Configuration Fields

Scale and dimensions:

  • Min, Max: Define the value range for the graph scale
  • Width: Graph width in terminal characters
  • GroupBy: Number of values to aggregate before printing
  • GroupType: Aggregation method ("avg" or "sum")

Labels and titles:

  • Label: Per-line label displayed before the graph bar
  • LabelColor: Color for the label text
  • Title: Graph title displayed once at the top
  • TitleColor: Color for the title text
  • Legend: Legend text for multi-color graphs

Colors and thresholds:

  • Color: Override color for the graph bar
  • Warning: Threshold value for yellow/warning color
  • Alert: Threshold value for red/alert color

Display options:

  • Condensed: Use Braille characters for compact display
  • NoAnsi: Disable ANSI escape codes for plain text output
  • Formatter: Name of the formatter plugin to use

func (Graph) AddArg

func (g Graph) AddArg(k, v string) (find bool)

AddArg processes a key-value configuration argument for the base Graph type. Delegates to OptToField to update the appropriate configuration field.

This method is typically overridden by specific graph types to handle graph-specific arguments before falling back to common arguments.

Parameters:

  • k: Argument key/name (e.g., "width", "min", "max", "color")
  • v: Argument value as a string

Returns:

  • find: true if the argument was recognized and processed

func (*Graph) AddToParse

func (g *Graph) AddToParse(p *argparse.Parser) *argparse.Parser

AddToParse registers all common graph arguments with the argument parser. This method is called for each graph type to add shared configuration options.

The arguments are organized into groups:

  • "Graph appearance": title, width, min, max, legend, groupby, grouptype, condensed
  • "Values appearance": color, label, label_color
  • "Alert or Warning threshold": warning, alert
  • "Input and Output": file, formatter

Parameters:

  • p: The argument parser to add arguments to

Returns:

  • The parser for method chaining

func (*Graph) GetName added in v0.2.0

func (g *Graph) GetName() string

GetName implements GraphNamer for the base Graph type. Returns "common" as the identifier for the base graph type.

func (*Graph) InitVal added in v0.5.0

func (g *Graph) InitVal()

InitVal resets the display state flags for the graph. This is called when processing "new=graph" command to allow the title and legend to be printed again for a new graph section.

Resets:

  • TitlePrinted: Allows title to be printed again
  • LegendPrinted: Allows legend to be printed again

func (*Graph) InitValues added in v0.5.0

func (g *Graph) InitValues()

InitValues is the default implementation that does nothing. Graph types override this to reset their value storage for a new data series.

func (*Graph) New added in v0.2.0

func (g *Graph) New(common *Graph) Grapher

New implements GraphBuilder for the base Graph type. Returns the Graph itself as it serves as a base implementation. Graph-specific types override this to return their own instances.

func (*Graph) Print

func (g *Graph) Print(newLine bool)

Print is the base implementation of [GraphPrinter.Print] for the Graph type. It renders the title and legend, which are common to all graph types.

Specific graph types (simple, minmax, compare, cumul, heatmap) override this method to add their own visualization after calling the base title and legend printing.

Parameters:

  • newLine: If true, ends output with newline; if false, ends with carriage return (The base implementation ignores this parameter as it only prints title/legend)

func (Graph) PrintHelpFile added in v0.2.0

func (g Graph) PrintHelpFile(t string)

PrintHelpFile is a placeholder implementation for printing help files. Individual graph types should override this method to provide specific help content. This default implementation prints a message indicating the function is not implemented.

Parameters:

  • t: The type of help file to print (e.g., "txt", "json", "yaml", "stdin")

func (*Graph) PrintLegend added in v0.2.0

func (g *Graph) PrintLegend()

PrintLegend renders the graph legend below the title. The legend is displayed in italic style with white text color.

The legend is only printed once per graph; subsequent calls are no-ops until [InitVal] is called to reset the LegendPrinted flag.

This base implementation prints a simple text legend. Graph types like cumul and heatmap override this to display color-coded legends with multiple segments.

func (*Graph) PrintTitle added in v0.2.0

func (g *Graph) PrintTitle(w int)

PrintTitle renders the graph title centered at the top of the graph. The title is displayed in bold italic style with the configured TitleColor.

The title is only printed once per graph; subsequent calls are no-ops until [InitVal] is called to reset the TitlePrinted flag.

Parameters:

  • w: Available width for centering (typically graph width + margins)

The title uses the formatter plugin specified in Graph.Formatter (default: "ansi") with Bold and Italic styles applied.

func (*Graph) ProcessStructuredFile added in v0.2.0

func (g *Graph) ProcessStructuredFile(f, ext string) error

ProcessStructuredFile is the default implementation for the base Graph type. It prints an error message indicating that the specific graph type should override this method to handle structured file formats.

Graph types like simple, minmax, compare, cumul, and heatmap each provide their own implementation with type-specific FileStruct definitions.

Parameters:

  • f: Path to the file
  • ext: File extension (.json, .yaml, or .yml)

Returns:

  • error: Always returns nil (error is printed to stdout)

type GraphBuilder added in v0.5.0

type GraphBuilder interface {
	// New creates a new graph instance linked to the provided common configuration.
	// Returns nil if the provided Graph is nil.
	New(g *Graph) Grapher
}

GraphBuilder defines the factory method for creating new graph instances. Each graph type implements this to return a properly initialized instance linked to the provided common Graph configuration.

type GraphHelper added in v0.5.0

type GraphHelper interface {
	// PrintHelpFile displays the help file for the specified input format.
	// Valid format types are: "txt", "json", "yaml", "stdin"
	PrintHelpFile(t string)
}

GraphHelper provides help file display functionality.

type GraphLoader added in v0.5.0

type GraphLoader interface {
	// InitValues resets the graph's value storage for a new data series.
	// Called when processing "new" command in input.
	InitValues()

	// InitVal resets the graph's display state (title/legend printed flags).
	// Called when processing "new=graph" command in input.
	InitVal()

	// AddArg processes a key-value configuration argument.
	// Returns true if the argument was recognized and processed.
	AddArg(key, value string) (found bool)

	// ProcessStructuredFile loads and processes a JSON or YAML file.
	// The ext parameter specifies the file extension for format detection.
	ProcessStructuredFile(filename, ext string) error
}

GraphLoader handles input data processing from various sources.

type GraphNamer added in v0.5.0

type GraphNamer interface {
	// GetName returns the graph type name (e.g., "simple", "minmax", "compare").
	// This name is used as the CLI subcommand name.
	GetName() string
}

GraphNamer provides the graph type identifier used for CLI subcommands.

type GraphParser added in v0.5.0

type GraphParser interface {
	// AddToParse registers the graph's specific command-line arguments with the parser.
	// Returns the subcommand parser for further customization.
	AddToParse(parser *argparse.Parser) *argparse.Parser
}

GraphParser handles command-line argument registration for graph-specific options.

type GraphPrinter added in v0.5.0

type GraphPrinter interface {
	// Print renders the graph to stdout.
	// If newline is true, ends with a newline; otherwise ends with carriage return
	// for in-place updates (useful for streaming data).
	Print(newline bool)

	// PrintTitle renders the graph title if configured and not already printed.
	// The width parameter specifies the available width for centering.
	PrintTitle(w int)

	// PrintLegend renders the graph legend if configured and not already printed.
	// Used primarily by cumul and heatmap graphs to show color mappings.
	PrintLegend()
}

GraphPrinter handles all output rendering for the graph.

type Grapher added in v0.5.0

Grapher defines the complete interface that all graph types must implement. It composes several smaller interfaces to provide a consistent API for:

Implementations should embed a Graph struct to inherit common configuration and provide graph-specific fields and methods.

type MultiValuer added in v0.6.0

type MultiValuer interface {
	// AddValues processes a pair of numeric values for comparison.
	// Returns true if the graph was printed as a result of these values.
	AddValues(value, value2 float64) (printed bool)
}

MultiValuer is implemented by graph types that process pairs of numeric values. Used by the compare graph type for dual-value comparisons.

type SingleValuer added in v0.5.0

type SingleValuer interface {
	// AddValue processes a single numeric value.
	// Returns true if the graph was printed as a result of this value
	// (e.g., when GroupBy threshold is reached).
	AddValue(value float64) (printed bool)
}

SingleValuer is implemented by graph types that process single numeric values. Used by simple, minmax, cumul, and heatmap graphs.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL