pyGHDL.cli.dom

A terminal application to exercise pyGHDL.dom.

It parses VHDL source files with libghdl, translates the result to the document object model and writes each document as VHDL code, which makes it the quickest way to see what the model makes of a given file. Installed as ghdl-dom by setup.py.

Classes


Classes

class pyGHDL.cli.dom.Application(**kwargs)[source]

The pyghdl-dom application.

It owns a Design, adds the requested source files to it, and dispatches the sub-command the user asked for.

Inheritance

Inheritance diagram of Application

HEADLINE: ClassVar[str] = 'pyGHDL.dom - Test Application'

Headline of the application, printed by _PrintHeadline().

DUNDER_MODULE = <module 'pyGHDL' from '/home/runner/work/ghdl/ghdl/pyGHDL/__init__.py'>

Module declaring the application’s dunder variables, e.g. __version__, read by TerminalApplication._PrintVersion() and the exception printers. Default: None, i.e. none declared.

__init__()[source]

Initializes the application.

property Platform

Read-only property to access the platform the application runs on (__PLATFORM).

Returns:

The platform’s name, as platform.system() reports it.

Run()[source]

Parse the command line and run the requested sub-command.

HandleDefault(_)[source]

Handle an invocation with no sub-command by printing the help page.

Parameters:

_ – The parsed arguments, unused.

HandleHelp(args)[source]

Handle the help sub-command: print the help page of a command, or the overview.

Parameters:

args – The parsed arguments, carrying the optional command name.

HandleVersion(args)[source]

Handle the version sub-command: print the headline, copyright, license, authors and version.

Parameters:

args – The parsed arguments, unused.

HandlePretty(args)[source]

Handle the pretty sub-command: translate the selected sources and write each document as VHDL code.

A file is translated on its own; a directory is scanned, and each subdirectory is reported as a library of that name. The documents aren’t added to the design, nor analyzed. Each document is written by VHDLWriter: its design units with their context items, in source order. The time libghdl spent parsing and the time the translation took are reported per file.

A file, that can’t be translated or written, is reported as an error; the remaining files are written. The application exits with an error, if an error was reported.

Parameters:

args – The parsed arguments, carrying the selected files, directory, default library, VHDL version and tab size.

writeFile(filename, indent)[source]

Translate a source file into a document and write the document as VHDL code.

An error is reported, if the file can’t be translated or the document can’t be written.

Parameters:
  • filename (Path) – The source file to translate.

  • indent (int) – The indentation level of the timing messages.

Return type:

None

_mainParser

The main argument parser of the application.

_formatter

Help page formatter class used by every parser.

_subParser

The sub-parser action the sub-commands are registered at.

_subParsers

Sub-command name to its argument parser.

property BaseIndent: int

Property to access the base indentation level of written messages (_baseIndent).

The assigned level is added to every message’s own indentation.

Returns:

Base indentation level.

Configure(*, verbose=False, debug=False, silent=False, quiet=False, writeToStdOut=True)

Configure the verbosity of the application, usually from the command line switches.

The resulting LogLevel is the minimum severity a message needs to be written: Severity.Debug in debug mode, Severity.Verbose in verbose mode, Severity.Silent in silent mode, Severity.Quiet in quiet mode, otherwise Severity.Normal. Debug mode implies verbose mode.

Parameters:
  • verbose (bool) – Optional, write verbose messages. Default: False.

  • debug (bool) – Optional, write debug messages, implying verbose messages. Default: False.

  • silent (bool) – Optional, reduce the messages to warnings and higher severities. Default: False.

  • quiet (bool) – Optional, reduce the messages to errors and always visible messages. Default: False.

  • writeToStdOut (bool) – Optional, write to STDOUT. Default: True.

Return type:

None

property CriticalWarningCount: int

Read-only property to access the number of counted critical warnings.

Returns:

Number of critical warnings.

property Debug: bool

Check if debug messages are enabled.

Returns:

True, if debug messages are written.

property ErrorCount: int

Read-only property to access the number of counted errors.

Returns:

Number of errors.

Exit(returnCode=0)

Exit the terminal application by uninitializing color support and returning an Exit code.

Parameters:

returnCode (int) – Optional, return code for application exit.

Return type:

NoReturn

ExitOnPreviousCriticalWarnings(includeErrors=True)

Exit application if error or critical warnings have been printed.

Parameters:

includeErrors (bool) – Optional, if True, count previous errors as well as critical warnings.

Return type:

None

ExitOnPreviousErrors()

Exit application if errors have been printed.

Return type:

None

ExitOnPreviousWarnings(includeCriticalWarnings=True, includeErrors=True)

Exit application if error or (critical) warnings have been printed.

Parameters:
  • includeCriticalWarnings (bool) – Optional, if True, count previous critical warnings as well as warnings.

  • includeErrors (bool) – Optional, if True, count previous errors as well.

Return type:

None

FATAL_EXIT_CODE = 255

Return code for fatal exits.

FOREGROUND = {'BLUE': '\x1b[94m', 'CYAN': '\x1b[96m', 'DARK_BLUE': '\x1b[34m', 'DARK_CYAN': '\x1b[36m', 'DARK_GRAY': '\x1b[90m', 'DARK_GREEN': '\x1b[32m', 'DARK_RED': '\x1b[31m', 'DARK_YELLOW': '\x1b[33m', 'ERROR': '\x1b[91m', 'GRAY': '\x1b[37m', 'GREEN': '\x1b[92m', 'HEADLINE': '\x1b[95m', 'MAGENTA': '\x1b[95m', 'NOCOLOR': '\x1b[39m', 'RED': '\x1b[91m', 'WARNING': '\x1b[93m', 'WHITE': '\x1b[97m', 'YELLOW': '\x1b[93m'}

Terminal colors

FatalExit(returnCode=0)

Exit the terminal application by uninitializing color support and returning a fatal Exit code.

Parameters:

returnCode (int) – Optional, return code for application exit.

Return type:

NoReturn

classmethod GetMethodsWithAttributes(predicate=None)

Return the class’ methods that carry at least one matching attribute.

Parameters:

predicate (type[TAttr] | Iterable[type[TAttr]] | None) – Optional, an attribute class, an iterable of attribute classes, or None to accept every attribute.

Return type:

dict[Callable[..., Any], tuple[Attribute, ...]]

Returns:

Dictionary of methods and the matching attributes attached to them.

Raises:
  • ValueError – If an element of parameter ‘predicate’ is not a sub-class of Attribute.

  • ValueError – If parameter ‘predicate’ is neither an attribute class nor an iterable of those.

static GetTerminalSize()

Returns the terminal size as tuple (width, height) for Windows, macOS (Darwin), Linux, cygwin (Windows), MinGW32/64 (Windows).

Return type:

tuple[int, int]

Returns:

A tuple containing width and height of the terminal’s size in characters.

Raises:

PlatformNotSupportedError – When a platform is not yet supported.

property Height: int

Read-only property to access the terminal’s height.

Returns:

The terminal window’s height in characters.

INDENT = '  '

Indentation. Default: "  " (2 spaces)

InitializeColors()

Initialize the terminal for color support by :gh:`colorama <tartley/colorama>`.

Return type:

bool

Returns:

True, if ‘colorama’ package could be imported and initialized.

property Lines: list[Line]

Read-only property to access the list of printed lines (messages).

Returns:

List of lines.

property LogLevel: Severity

Property to access the minimal severity level a message needs to be written (_writeLevel).

Assigning a level replaces what Configure() computed from the verbosity switches.

Returns:

The current minimal severity level.

MISSING_DEPENDENCY_EXIT_CODE = 242

Return code (242), if an optional dependency is missing; the value lives on the exception - see PrintMissingDependencyError().

property MainParser: ArgumentParser

Read-only property to access the main argument parser (_mainParser).

Returns:

The main argument parser.

NOT_IMPLEMENTED_EXCEPTION_EXIT_CODE = 240

Return code, if unimplemented methods or code sections were called.

PrintException(ex)

Prints an exception of type Exception and its traceback.

If the exception as a nested action, the cause is printed as well.

If DUNDER_MODULE defines __issue_tracker_url__, the output ends with an invitation to report the bug at that URL.

Parameters:

ex (Exception) – The exception to print.

Return type:

NoReturn

PrintExceptionBase(ex)

Prints an exception of type ExceptionBase and its traceback.

If the exception as a nested action, the cause is printed as well.

If DUNDER_MODULE defines __issue_tracker_url__, the output ends with an invitation to report the bug at that URL.

Parameters:

ex (Exception) – The exception to print.

Return type:

NoReturn

PrintMissingDependencyError(ex)

Print a missing optional dependency and the command lines installing it.

Unlike the other printers, this one does not report a bug: there is no traceback, and no invitation to open an issue, because nothing is wrong with the program - a package it can use is not installed. The message names the missing package and every installation option the exception carries (InstallCommands).

Attention

A dependency missing while a module is imported raises before an application object exists, so this method cannot report that case. An application that wants to survive it catches the exception around its own imports and prints the commands directly:

from pyTooling.Exceptions import MissingDependencyError

try:
  from myPackage.Plotting import Plot
except MissingDependencyError as ex:
  print(f"{ex}\n" + "\n".join(f"  {command}" for command in ex.InstallCommands))
  raise SystemExit(MissingDependencyError.EXIT_CODE) from ex
Parameters:

ex (MissingDependencyError) – The exception to print.

Return type:

NoReturn

Returns:

Never - the method exits the application with MISSING_DEPENDENCY_EXIT_CODE.

See also

PrintException()

→ Print an unhandled exception and its traceback.

PrintNotImplementedError()

→ Print a call to an unimplemented function or abstract method.

PrintNotImplementedError(ex)

Prints a not-implemented exception of type NotImplementedError.

If DUNDER_MODULE defines __issue_tracker_url__, the output ends with an invitation to report the bug at that URL.

Parameters:

ex (NotImplementedError) – The exception to print.

Return type:

NoReturn

property Quiet: bool

Check if quiet mode is enabled.

Returns:

True, if quiet mode is enabled.

property Silent: bool

Check if silent mode is enabled.

Returns:

True, if silent mode is enabled.

property SubParsers: dict[str, ArgumentParser]

Read-only property to access the sub-parsers (_subParser).

Returns:

Dictionary of command names and their sub-parsers.

TryWriteLine(line)

Check if a line object of a certain severity would be written.

Parameters:

line – Line object to check.

Return type:

bool

Returns:

True, if line would be written.

UNHANDLED_EXCEPTION_EXIT_CODE = 241

Return code, if an unhandled exception reached the topmost exception handler.

UninitializeColors()

Uninitialize the terminal for color support by :gh:`colorama <tartley/colorama>`.

Return type:

bool

Returns:

True, if ‘colorama’ package could be imported and uninitialized.

property Verbose: bool

Check if verbose messages are enabled.

Returns:

True, if verbose messages are written.

property WarningCount: int

Read-only property to access the number of counted warnings.

Returns:

Number of warnings.

property Width: int

Read-only property to access the terminal’s width.

Returns:

The terminal window’s width in characters.

WriteCritical(message, *, indent=0, appendLinebreak=True)

Write a critical message.

Depending on internal settings and rules, a message might be skipped.

Parameters:
  • message (str) – Message to write.

  • indent (int) – Optional, indentation level of the message.

  • appendLinebreak (bool) – Optional, append a linebreak after the message. Default: True

Return type:

bool

Returns:

True, if message was actually written.

WriteCriticalNote(message, *, indent=0, appendLinebreak=True)

Write a critical note.

Depending on internal settings and rules, a note might be skipped.

Parameters:
  • message (str) – Message to write.

  • indent (int) – Optional, indentation level of the note.

  • appendLinebreak (bool) – Optional, append a linebreak after the note. Default: True

Return type:

bool

Returns:

True, if note was actually written.

WriteDebug(message, *, indent=0, appendLinebreak=True)

Write a debug message.

Depending on internal settings and rules, a message might be skipped.

Parameters:
  • message (str) – Message to write.

  • indent (int) – Optional, indentation level of the message.

  • appendLinebreak (bool) – Optional, append a linebreak after the message. Default: True

Return type:

bool

Returns:

True, if message was actually written.

WriteDryRun(message, *, indent=0, appendLinebreak=True)

Write a dry-run message message.

Depending on internal settings and rules, a message might be skipped.

Parameters:
  • message (str) – Message to write.

  • indent (int) – Optional, indentation level of the message.

  • appendLinebreak (bool) – Optional, append a linebreak after the message. Default: True

Return type:

bool

Returns:

True, if message was actually written.

WriteError(message, *, indent=0, appendLinebreak=True)

Write an error message.

Depending on internal settings and rules, a message might be skipped.

Parameters:
  • message (str) – Message to write.

  • indent (int) – Optional, indentation level of the message.

  • appendLinebreak (bool) – Optional, append a linebreak after the message. Default: True

Return type:

bool

Returns:

True, if message was actually written.

WriteErrorNote(message, *, indent=0, appendLinebreak=True)

Write a note belonging to an error, which is where the advice for fixing it goes.

Depending on internal settings and rules, a note might be skipped.

Parameters:
  • message (str) – Message to write.

  • indent (int) – Optional, indentation level of the note.

  • appendLinebreak (bool) – Optional, append a linebreak after the note. Default: True

Return type:

bool

Returns:

True, if note was actually written.

WriteFatal(message, *, indent=0, appendLinebreak=True, exitCode=0, immediateExit=True)

Write a fatal message and exit.

Depending on internal settings and rules, a message might be skipped.

Parameters:
  • message (str) – Message to write.

  • indent (int) – Optional, indentation level of the message.

  • appendLinebreak (bool) – Optional, append a linebreak after the message. Default: True

  • exitCode (int) – Optional, exit application with this exit code. Default: 0
    If 0, use FATAL_EXIT_CODE as exit code.

  • immediateExit (bool) – Optional, exit application immediately. Default: True

Return type:

bool

Returns:

True, if message was actually written.

WriteInfo(message, *, indent=0, appendLinebreak=True)

Write an info message.

Depending on internal settings and rules, a message might be skipped.

Parameters:
  • message (str) – Message to write.

  • indent (int) – Optional, indentation level of the message.

  • appendLinebreak (bool) – Optional, append a linebreak after the message. Default: True

Return type:

bool

Returns:

True, if message was actually written.

WriteLine(line)

Print a formatted line to the underlying terminal/console offered by the operating system.

The message is indented by INDENT repeated Line.Indent times. The indentation is applied to the message, not to the whole line, so the severity markers stay in one column.

Parameters:

line (Line) – Line object to indent, format and print.

Return type:

bool

Returns:

True, if line was actually written.

WriteLineToStdErr(message, end='\n')

Low-level method for writing to STDERR.

Parameters:
  • message (str) – Message to write to STDERR.

  • end (str) – Optional, use newline character. Default: \n.

Return type:

int

Returns:

Number of written characters.

WriteLineToStdOut(message, end='\n')

Low-level method for writing to STDOUT.

Parameters:
  • message (str) – Message to write to STDOUT.

  • end (str) – Optional, use newline character. Default: \n.

Return type:

int

Returns:

Number of written characters.

WriteNormal(message, *, indent=0, appendLinebreak=True)

Write a normal message.

Depending on internal settings and rules, a message might be skipped.

Parameters:
  • message (str) – Message to write.

  • indent (int) – Optional, indentation level of the message.

  • appendLinebreak (bool) – Optional, append a linebreak after the message. Default: True

Return type:

bool

Returns:

True, if message was actually written.

WriteQuiet(message, *, indent=0, appendLinebreak=True)

Write an always visible message.

This message is even visible in quiet mode.

Depending on internal settings and rules, a message might be skipped.

Parameters:
  • message (str) – Message to write.

  • indent (int) – Optional, indentation level of the message.

  • appendLinebreak (bool) – Optional, append a linebreak after the message. Default: True

Return type:

bool

Returns:

True, if message was actually written.

WriteToStdErr(message)

Low-level method for writing to STDERR.

Parameters:

message (str) – Message to write to STDERR.

Return type:

int

Returns:

Number of written characters.

WriteToStdOut(message)

Low-level method for writing to STDOUT.

Parameters:

message (str) – Message to write to STDOUT.

Return type:

int

Returns:

Number of written characters.

WriteVerbose(message, *, indent=0, appendLinebreak=True)

Write a verbose message.

Depending on internal settings and rules, a message might be skipped.

Parameters:
  • message (str) – Message to write.

  • indent (int) – Optional, indentation level of the message.

  • appendLinebreak (bool) – Optional, append a linebreak after the message. Default: True

Return type:

bool

Returns:

True, if message was actually written.

WriteWarning(message, *, indent=0, appendLinebreak=True)

Write a warning message.

Depending on internal settings and rules, a message might be skipped.

Parameters:
  • message (str) – Message to write.

  • indent (int) – Optional, indentation level of the message.

  • appendLinebreak (bool) – Optional, append a linebreak after the message. Default: True

Return type:

bool

Returns:

True, if message was actually written.

WriteWarningNote(message, *, indent=0, appendLinebreak=True)

Write a warning note.

Depending on internal settings and rules, a note might be skipped.

Parameters:
  • message (str) – Message to write.

  • indent (int) – Optional, indentation level of the note.

  • appendLinebreak (bool) – Optional, append a linebreak after the note. Default: True

Return type:

bool

Returns:

True, if note was actually written.

_EnabledAutoComplete()

Register the main parser with argcomplete for shell completion.

The package is optional: when it isn’t installed, completion is silently unavailable.

Return type:

None

_GetLatestVersion(packageName, timeout=1)

Query PyPI for the latest released version of a package.

Every error - an unreachable index, a timeout, an unknown package - is answered with None, because a version check must not fail the application it is printing the version of.

Parameters:
  • packageName (str) – Name of the package on PyPI.

  • timeout (int) – Optional, timeout in seconds for the request. Default: 1.

Return type:

str | None

Returns:

The latest version as a string, or None, if it couldn’t be determined.

_LOG_LEVEL_ROUTING__: dict[Severity, tuple[Callable[[str, str], int]]]

Message routing rules.

_LOG_MESSAGE_FORMAT__: ClassVar[dict[Severity, str]] = {Severity.Debug: '{DARK_GRAY}{message}{NOCOLOR}', Severity.Verbose: '{GRAY}{message}{NOCOLOR}', Severity.DryRun: '{DARK_CYAN}[DRY] {message}{NOCOLOR}', Severity.Normal: '{WHITE}{message}{NOCOLOR}', Severity.Info: '{WHITE}{message}{NOCOLOR}', Severity.WarningNote: '{DARK_YELLOW}            > {message}{NOCOLOR}', Severity.Warning: '{YELLOW}[WARNING]   {message}{NOCOLOR}', Severity.CriticalNote: '{DARK_YELLOW}            > {message}{NOCOLOR}', Severity.Critical: '{DARK_YELLOW}[CRITICAL]  {message}{NOCOLOR}', Severity.Quiet: '{WHITE}{message}{NOCOLOR}', Severity.ErrorNote: '{DARK_RED}            > {message}{NOCOLOR}', Severity.Error: '{RED}[ERROR]     {message}{NOCOLOR}', Severity.Fatal: '{DARK_RED}[FATAL]     {message}{NOCOLOR}', Severity.ExceptionNote: '{DARK_RED}            > {message}{NOCOLOR}', Severity.Exception: '{RED}[EXCEPTION] {message}{NOCOLOR}'}

Message formatting rules.

_ParseArguments()

Parse the command line arguments and route them to the selected handler method.

Return type:

None

_PrintHeadline(width=80)

Helper method to print the program headline.

Parameters:

width (int) – Optional, number of characters for horizontal lines.

Return type:

None

Generated output

=========================
    centered headline
=========================
_PrintHelp(command=None)

Helper method to print the command line parser’s help page, or the help page of one sub-command.

Attention

This method writes through the Write*** methods of TerminalApplication, which this mixin-class does not provide, so the application class has to derive from both.

Parameters:

command (str | None) – Optional, the sub-command to print the help page for. If None, the main parser’s help page is printed. Default: None.

Raises:

UnfulfilledExpectationError – If the application class doesn’t also derive from TerminalApplication.

Return type:

None

_PrintVersion(packageName=None, versionCheckTimeout=1)

Helper method to print the version information.

The author(s), email, copyright, version and URLs are read from the dunder variables of the module the class constant DUNDER_MODULE refers to. If it is None, every dunder variable counts as missing.

Parameters:
  • packageName (str | None) – Optional, name of the package on PyPI. If given, the latest released version is queried and reported as an available update. Default: None.

  • versionCheckTimeout (int) – Optional, timeout in seconds for the PyPI request. Default: 1.

Raises:

TypeError – If parameter ‘packageName’ is not of type str.
A module with dunder variables is set as class constant DUNDER_MODULE.

Return type:

None

Example usage

import myPackage

class Application(TerminalApplication):
  HEADLINE =      "My Application"
  DUNDER_MODULE = myPackage

  def HandleVersion(self, _: Namespace) -> None:
    self._PrintHeadline()
    self._PrintVersion("myPackage")
_RouteToHandler(args)

Call the handler method the parsed arguments select.

The handler is stored as an unbound function, so it is called with the application object as first parameter.

Parameters:

args (Namespace) – The parsed command line arguments.

Return type:

None

__annotate_func__()

The type of the None singleton.

__getstate__()

Return the object’s state for pickling, collecting every slot of the class hierarchy.

Return type:

dict[str, Any]

Returns:

Dictionary of slot names and their values.

Raises:

ExtendedTypeError – If a slot was never assigned, so it has no value to serialize.

__new__(**kwargs)
__setstate__(state)

Restore the object’s state from unpickling, requiring exactly the slots of the class hierarchy.

Parameters:

state (dict[str, Any]) – Dictionary of slot names and their values.

Raises:

ExtendedTypeError – If the given state misses a slot or carries an unexpected one.

Return type:

None

_baseIndent: int

Indentation level added to every message’s own indentation.

_criticalWarningCount: int

Number of critical warnings written so far.

_debug: bool

True, if debug messages are written.

_errorCount: int

Number of errors written so far.

_height

Terminal height in characters

_lines: list[Line]

Every message written so far, in the order it was written.

_quiet: bool

True, if only errors and quiet messages are written.

_silent: bool

True, if no messages are written at all.

_stderr

STDERR

_stdin

STDIN

_stdout

STDOUT

_verbose: bool

True, if verbose messages are written.

_warningCount: int

Number of warnings written so far.

_width

Terminal width in characters

_writeLevel: Severity

Minimal severity a message needs to be written.

_writeToStdOut: bool

True, if messages are written to STDOUT instead of STDERR.