Code Reference

guacamole.core

The essence of guacamole.

This module defines the three essential core classes: Ingredient, Bowl, Context. All of those have stable APIs.

class guacamole.core.Ingredient[source]

Part of guacamole.

Ingredients are a mechanism for inserting functionality into Guacamole. The sequence of calls to ingredient methods is as follows:

The added method is where an ingredient can advertise itself to other ingredients that it explicitly collaborates with.

The preparse method is where ingredients can have a peek at the command line arguments. This can serve to optimize further actions. Essentially guacamole allows applications to parse arguments twice and limit the actions needed to do that correctly to the essential minimum required.

The early initialization method can be used to do additional initialization. It can take advantage of the fact that the whole command line arguments are now known and may have been analyzed further by the preparse method.

The parse method is where applications are expected to fully understand command line arguments. This method can abort subsequent execution if arguments are wrong in in some way. After parsing command line arguments the application should be ready for execution.

The late initialization method mimics the early initialization method but is called after parsing all of the command line arguments. Again, it can be used to prepare addiotional resources necessary for a given application.

The dispatch method is where applications execute the bulk of their actions. Dispatching is typically done with one of the standard ingredients which will locate the appropriate method to call into the application.

Depending on the outcome of the dispatch (if an exception is raised or not) one of dispatch_succeeded()`() or dispatch_failed() is called.

This is the last method called on all ingredients.

Each of those methods is called with a context argument (Context:). A context is a free-for-all environment where ingredients can pass data around. There is no name-spacing. Ingredients should advertise what they do with the context and what to expect.

added(context)[source]

Ingredient method called before anything else.

build_early_parser(context)[source]

Ingredient method called to build the early parser.

build_parser(context)[source]

Ingredient method called to build the full parser.

dispatch(context)[source]

Ingredient method for dispatching (execution).

Note

The first ingredient that implements this method and returns something other than None will stop command dispatch!

dispatch_failed(context)[source]

Ingredient method called when dispatching fails.

dispatch_succeeded(context)[source]

Ingredient method called when dispatching is correct.

early_init(context)[source]

Ingredient method for early initialization.

late_init(context)[source]

Ingredient method for late initialization.

parse(context)[source]

Ingredient method called to parse command line arguments.

preparse(context)[source]

Ingredient method called to pre-parse command line aruments.

shutdown(context)[source]

Ingredient method called after all other methods.

class guacamole.core.Context[source]

Context for making guacamole with ingredients.

A context object is created and maintained throughout the life-cycle of an executing tool. A context is passed as argument to all ingredient methods.

Since context has no fixed API anything can be stored and loaded. Particular ingredients document how they use the context object.

class guacamole.core.Bowl(ingredients)[source]

A vessel for preparing guacamole out of ingredients.

Note

Each Bowl is single-use. If you eat it you need to get another one as this one is dirty and cannot be reused.

add_spice(spice)[source]

Add a single spice the bowl.

eat(argv=None)[source]

Eat the guacamole.

Parameters:argv – Command line arguments or None. None means that sys.argv is used
Returns:Whatever is returned by the first ingredient that agrees to perform the command dispatch.

The eat method is called to run the application, as if it was invoked from command line directly.

has_spice(spice)[source]

Check if a given spice is being used.

This method can be used to construct checks if an optional ingredient feature should be enabled or not. Spices are simply strings that describe optional features.

guacamole.recipes

APIs for guacamole add-on developers.

This module contains the public APIs for add-on developers. Add-ons (or plug-ins) for guacamole are called ingredients. The Ingredient class contains a description of available add-on methods.

Ingredients are somewhat similar to Django middleware as they can influence the execution of an application across its life-cycle. All of core guacamole features are implemented as ingredients. Developers are encouraged to read core ingredients to understand how to formulate their own design.

Ingredient APIs are public. They will be maintained for backwards compatibility. Since Guacamole doesn’t automatically enable any third-party ingredients, application developers that wish to use them need to use the guacamole.core module to create their own guacamole out of available ingredients. Ingredient developers are recommended in documenting how to use each ingredient this way.

In addition this module contains the public APIs for creating custom mixes of guacamole. A custom mix begins with a Bowl with any number of Ingredient objects added.

If you are familiar with the Command class you should know that they are using the recipe system internally. They refer to pre-made recipes that put particular ingredients into the bowl for a ready dish.

If you wish to build a custom experience on top of guacamole, please provide a new recipe class. Recipes are how applications should interact with any guacamole mixtures.

class guacamole.recipes.Recipe[source]

Mechanism to use ingredients to dispatch and invoke commands.

get_ingredients()[source]

Get a list of ingredients for making guacamole.

Returns:A list of initialized ingredients.
Raises:RecipeError – If the recipe is wrong. This is a developer error. Do not handle this exception. Consult the error message to understand what the problem is and correct the recipe instead.
main(argv=None, exit=True)[source]

Shortcut to prepare a bowl of guacamole and eat it.

Parameters:
  • argv – Command line arguments or None. None means that sys.argv is used
  • exit – Raise SystemExit after finishing execution
Returns:

Whatever is returned by the eating the guacamole.

Raises:

Whatever is raised by eating the guacamole.

Note

This method always either raises and exception or returns an object. The way it behaves depends on the value of the exit argument.

This method can be used to quickly take a recipe, prepare the guacamole and eat it. It is named main as it is applicable as the main method of an application.

The exit argument controls if main returns normally or raises SystemExit. By default it will raise SystemExit (it will either wrap the return value with SystemExit or re-raise the SystemExit exception again). If SystemExit is raised but exit is False the argument to SystemExit is unwrapped and returned instead.

prepare()[source]

Prepare a bowl with the ingredients specified by this recipe.

Returns:A new Bowl instance with all the ingredients prepared.
exception guacamole.recipes.RecipeError[source]

Exception raised when the recipe for guacamole is incorrect.

This exception is only used when a set of ingredients is ordered correctly or has some missing elements. Each time this exception is raised it is accompanied by a detailed message that should help you to resolve the problem.

Note

This exception should not be handled, it is a developer error.

guacamole.recipes.cmd

Recipe for using guacamole to run commands.

This module contains sock recipes for guacamole. Stock recipes allow application developers to use use simple-to-understand design patterns to get predictable runtime behiavior.

Currently, guacamole ships with two such recipes, for creating simple commands and for creating hierarhical command groups. They are captured by the Command and Group classes respectively.

class guacamole.recipes.cmd.Command[source]

A single-purpose command.

Single purpose commands are the most commonly known tools in command line environments. Tools such as ls, mkdir or vim all fall in this class. A command is essentially a named action that can be invoked from the terminal emulator or other command line environment specific to a given operating system.

To create a new command simply create a custom class and override the invoked() method. Put all of your custom code there. If you want to interact with command line arguments then please also override the register_arguments() method.

Have a look at example applications for details of how to do this. You can use them as a starting point for your own application as they are licensed very liberally.

get_app_id()[source]

Get the identifier of the application.

Note

Application identifier is looked up using the app_id attribute.

The syntax of a valid command identifier is REVERSE-DNS-NAME:ID. For example, "com.example.product:command". This identifier must not contain characters that are hostile to the file systems. It’s best to stick to ASCII characters and digits.

On Mac OS X this will be used as a directory name rooted in ~/Library/Preferences/. On Linux and other freedesktop.org-based systems this will be used as directory name rooted in $XDG_CONFIG_HOME and $XDG_CACHE_HOME. On Windows it will be used as a directory name rooted in the per-user AppData folder.

Note

If this method returns None then logging and configuration services are disabled. It is strongly recommended to implement this method and return a correct value as it enhances application behavior.

get_app_name()[source]

Get the name of the application.

Note

Application name is looked up using the app_name attribute.

Application name differs from executable name. The executable might be called my-app or myapp while the application might be called My Application.

get_app_vendor()[source]

Get the name of the application vendor.

The name should be a human readable name, like "Joe Developer" or "Big Corporation Ltd."

Note

Application vendor name is looked up using the app_vendor attribute.

get_cmd_description()[source]

Get the leading, multi-line description of this command.

Returns:self.description, if defined
Returns:A substring of the class docstring between the first line (which is discarded) and the string @EPILOG@, if present, or the end of the docstring, if any
Returns:None, otherwise

The description string will be displayed after the usage string but before any of the detailed argument descriptions.

Please consider following good practice by keeping the description line short enough not to require scrolling but useful enough to provide additional information that cannot be inferred from the name of the command or other arguments. Stating the purpose of the command is highly recommended.

get_cmd_epilog()[source]

Get the trailing, multi-line description of this command.

Returns:self.epilog, if defined
Returns:A substring of the class docstring between the string @EPILOG and the end of the docstring, if defined
Returns:None, otherwise

The epilog is similar to the description string but it is instead printed after the section containing detailed descriptions of all of the command line arguments.

Please consider following good practice by providing additional details about how the command can be used, perhaps an example or a reference to means of finding additional documentation.

get_cmd_help()[source]

Get the single-line help of this command.

Returns:self.help, if defined
Returns:The first line of the docstring, without the trailing dot, if present.
Returns:None, otherwise
get_cmd_name()[source]

Get the name of the application executable.

Note

If this method returns None then the executable name is guessed from sys.argv[0].

get_cmd_spices()[source]

Get a list of spices requested by this command.

Feature flags are a mechanism that allows application developers to control ingredients (switch them on or off) as well as to control how some ingredients behave.

Returns:self.spices, if defined. This should be a set of strings. Each string represents as single flag. Ingredients should document the set of flags they understand and use.
Returns:An empty set otherwise

Some flags have a generic meaning, you can scope a flag to a given ingredient using the name: prefix where the name is the name of the ingredient.

get_cmd_usage()[source]

Get the usage string associated with this command.

Returns:self.usage, if defined
Returns:None, otherwise

The usage string typically contains the list of available, abbreviated options, mandatory arguments and other arguments. Its purpose is to quickly inform the user on the basic syntax used by the command.

It is perfectly fine not to customize this method as the default is to compute an appropriate usage string out of all the arguments. Consider implementing this method in a customized way if your command has highly complicated syntax and you want to provide an alternative, more terse usage string instead.

get_cmd_version()[source]

Get the version reported by this executable.

Note

If this method returns None then the --version option is disabled.

get_gettext_domain()[source]

Get the gettext translation domain associated with this command.

The value returned will be used to select translations to global calls to gettext() and ngettext() everywhere in python.

Note

If this method returns None then all i18n services are disabled.

get_locale_dir()[source]

Get the path of the gettext translation catalogs for this command.

This value is used to bind the domain returned by get_gettext_domain() to a specific directory.

Note

If this method returns None then standard, system-wide locations are used (on compatibles systems). In practical terms, on Windows, you may need to use it to have access to localization data.

get_sub_commands()[source]

Get a list of sub-commands of this command.

Returns:self.sub_commands, if defined. This is a sequence of pairs (name, cls) where name is the name of the sub command and cls is a command class (not an object). The name can be None if the command has a version of get_cmd_name() that returns an useful value.
Returns:An empty tuple otherwise

Applications can create hierarchical commands by defining the sub_commands attribute. Many developers are familiar with nested commands, for example git commit is a sub-command of the git command. All commands can be nested this way.

invoked(context)[source]

Callback called when the command gets invoked.

Parameters:context – The guacamole context object.
Returns:The return value is returned by the executable. It should be an integer between 0 and 255. Other values are will likely won’t work at all.

The context argument can be used to access command line arguments and other information that guacamole provides.

main(argv=None, exit=True)[source]

Shortcut for running a command.

See guacamole.recipes.Recipe.main() for details.

register_arguments(parser)[source]

Callback called to register command-specific arguments.

Parameters:parser – Argument parser (from argparse) specific to this command.
class guacamole.recipes.cmd.CommandRecipe(command)[source]

A recipe for using commands.

get_ingredients()[source]

Get a list of ingredients for guacamole.

guacamole.ingredients

Package with ingredients bundled with guacamole.

guacamole.ingredients.cmdtree

Ingredient for arranging commands into a tree structure.

class guacamole.ingredients.cmdtree.CommandTreeBuilder(command)[source]

Ingredient for arranging commands into a tree of instances.

Since commands and sub-commands are specified as classes there has to be an ingredient that instantiates them and resolves all the naming ambiguities. Here it is.

This component acts early, in its added() method.

added(context)[source]

Ingredient method called before anything else.

Here this method just builds the full command tree and stores it inside the context as the cmd_tree attribute. The structure of the tree is explained by the build_cmd_tree() function.

class guacamole.ingredients.cmdtree.CommandTreeDispatcher[source]

Ingredient for dispatching commands hierarchically.

This ingredient builds on the CommandTreeBuilder ingredient. It implements the dispatch() method that recurses from the top (root) of the command tree down to the appropriate leaf, calling the invoke() method of each command.

The process stops on the first command that returns a value other than None, raises an exception or until a leaf command is reached. THe ability to return early allows commands to perform some sanity checks or short- circuit execution that is hard to express using standard parser APIs.

Lastly, a command can return a generator, this is treated as a sign that the generator implements a context-manager-like API. In this case the generator is called exactly twice and can be used to manage resources during the lifetime of all sub-commands.

dispatch(context)[source]

Dispatch execution to the invoke() method of selected commands.

class guacamole.ingredients.cmdtree.cmd_tree_node(cmd_name, cmd_obj, children)

A named tuple for representing the hierarchy of commands.

children

Alias for field number 2

cmd_name

Alias for field number 0

cmd_obj

Alias for field number 1

guacamole.ingredients.argparse

Ingredients for using arparse for parsing command line arguments.

This module contains two ingredients. The main one is the ParserIngredient. It is responsible for handling all of the command line parsing and command argument registration. It is a part of the recipe for the command class. Note that command dispatch is not handled by this ingredient (see CommandTreeIngredient).

The second ingredient is AutocompleteIngredient which relies on the third-party argcomplete module to add support for automatic command line completion to supported shells (bash).

class guacamole.ingredients.argparse.AutocompleteIngredient[source]

Ingredient for adding shell auto-completion.

Warning

This component is not widely tested due to difficulty of providing actual integration. It might be totally broken.

Note

To effectively get tab completion you need to have the argcomplete package installed. In addition, a per-command initialization command has to be created and sourced by the shell. Look at argcomplete documentation for details.

parse(context)[source]

Optionally trigger argument completion in the invoking shell.

This method is called to see if bash argument completion is requested and to honor the request, if needed. This causes the process to exit (early) without giving other ingredients a chance to initialize or shut down.

Due to the way argcomple works, no other ingredient can print() anything to stdout prior to this point.

class guacamole.ingredients.argparse.ParserIngredient[source]

Ingredient for using argparse to parse command line arguments.

This ingredient uses the following Ingredient methods:

  • build_early_parser()
  • preparse()
  • build_parser()
  • parse()

The main parser is constructed in, unsurprisingly, the build_parser() method and stored in the context as parser. Other ingredients can be added after the ParserIngredient and can extend the available arguments (on the root parser) by using standard argparse APIs such as parser.add_argument() or parser.add_argument_group(). This parser is used to handle all of command line in the parse() method.

While most users won’t concern themselves with this design decision, there is also a second parser, called the early parser, that is used to pre-parse the command line arguments. This can be used as a way to optimize subsequent actions as, perhaps, knowing which commands are going to be invoked there will be no need to instantiate and prepare all of the commands in the command tree.

Currently this feature is not used. To take advantage of this knowledge you can look at the context.early_args object which contains the result of parsing the command line with the early parser. The early parser is a simple parser consisting of --help, --version (if applicable) and rest. The rest argument can be used as a hint as to what is coming next (e.g. if it matches a name of a command we know to exist)

After parsing is done the results of parsing the command line are stored in the context.args attribute. This is commonly accessed by individual commands from their invoke() methods.

build_early_parser(context)[source]

Create the early argument parser.

This method creates the early argparse argument parser. The early parser doesn’t know about any of the sub-commands so it can be used much earlier during the start-up process (before commands are loaded and initialized).

build_parser(context)[source]

Create the final argument parser.

This method creates the non-early (full) argparse argument parser. Unlike the early counterpart it is expected to have knowledge of the full command tree.

This method relies on context.cmd_tree and produces context.parser. Other ingredients can interact with the parser up until parse() is called.

parse(context)[source]

Parse command line arguments.

This method relies on context.argv and context.early_parser and produces context.args. Note that .argv is modified by preparse() so it actually has _less_ things in it.

The context.args object is the return value from argparse. It is the dict/object like namespace object.

preparse(context)[source]

Parse a portion of command line arguments with the early parser.

This method relies on context.argv and context.early_parser and produces context.early_args.

The context.early_args object is the return value from argparse. It is the dict/object like namespace object.

guacamole.ingredients.crash

Ingredient for reacting to application crashes.

class guacamole.ingredients.crash.VerboseCrashHandler[source]

Ingredient for reacting to crashes with a traceback.

You can add this ingredient into your recipe to react to application crashes. It will simply print the exception, as stored in context.exc_type, context.exc_value and context.traceback and raise SystemExit(1).

dispatch_failed(context)[source]

Print the unhandled exception and exit the application.

guacamole.ingredients.ansi

Ingredients for using ANSI command sequences.

class guacamole.ingredients.ansi.ANSI[source]

Numerous ANSI constants.

See also

Original specification in the Standard ECMA 48, page 61 (75th page of the PDF).

Wikipedia article about ANSI escape code.

cmd_erase_display
Command for erasing the whole display
cmd_erase_line
Command for erasing the current line
cmd_sgr_reset_all:
Command for resetting all SGR attributes
sgr_reset_all:
SGR code for resetting all attributes
sgr_bold:

Causes text to be rendered with bold face font or, alternatively, to be rendered with bright color variant. This code is widely supported on Linux. It is not supported on Windows.

sgr_bright:
Alternate spelling of :attr:`sgr_bold`.
sgr_faint:
SGR code that activates faint color subset
srg_dim:
Alternate spelling of ``sgr_faint``
srg_italic:
SGR code that activates italic font face
sgr_underline:
SGR code that activates underline mode
sgr_blink_slow:
SGR code that activates slow blinking of characters
sgr_blink_fast:
SGR code that activates fast blinking of characters
sgr_reverse:
SGR code that activates reverse-video mode
sgr_double_underline:
SGR code that activates double-underline mode
static cmd_sgr(sgr_list)[source]

Get a SGR (Set Graphics Rendition) code.

static sgr_bg_indexed(i)[source]

Get SGR (Set Graphics Rendition) background indexed color.

static sgr_bg_rgb(r, g, b)[source]

Get SGR (Set Graphics Rendition) background RGB color.

static sgr_fg_indexed(i)[source]

Get SGR (Set Graphics Rendition) foreground indexed color.

static sgr_fg_rgb(r, g, b)[source]

Get SGR (Set Graphics Rendition) foreground RGB color.

class guacamole.ingredients.ansi.ANSIFormatter(enabled=None)[source]

Formatter for ANSI Set Graphics Rendition codes.

An instance of this class is inserted into the context object as ansi. Using the fact that ANSIFormatter is callable one can easily add ANSI control sequences for foreground and background color as well as text attributes.

aprint(*values, **kwargs)

ANSI formatting-aware print().

This method is a version of print() (function) that understands additional ansi control parameters.

Parameters:
  • value – The values to print, same as with print()
  • sep – Separator between values, same as with print()
  • end – Terminator of the line, same as with print()
  • file – File to print to, same as with print()
  • flush – Flag that controls stream flush behavior, same as with print()
  • fg – Foreground color, same as with __call__().
  • bg – Background color, same as with __call__().
  • style – Text style, same as with __call__().
  • reset – Flag that controls if ANSI attributes are reset at the end, same as with __call__().
  • sgr – Additonal (custom) Set Graphics Rendition directives, same as with __call__().

Note

This implementation only works on Python 3

cmd(cmd, *args)[source]

Get an ANSI control sequence, if the formatter is enabled.

is_enabled

Flag indicating if text style is enabled.

This property is useful to let applications customize their behavior if they know color support is desired and enabled.

class guacamole.ingredients.ansi.ANSIIngredient(enable=None)[source]

Ingredient for colorizing output.

added(context)[source]

Ingredient method called before anything else.

guacamole.ingredients.ansi.ansi_cmd(cmd, *args)[source]

Get ANSI command code by name.

guacamole.ingredients.ansi.ansi_sgr(text, fg=None, bg=None, style=None, reset=True, **sgr)[source]

Apply desired SGR commands to given text.

Parameters:
  • text – Text or anything convertible to text
  • fg – (optional) Foreground color. Choose one of black, red, green, yellow, blue, magenta cyan or white. Note that the bright SGR impacts effective color in most implementations.
guacamole.ingredients.ansi.get_intensity(r, g, b)[source]

Get the gray level intensity of the given rgb triplet.

guacamole.ingredients.ansi.get_visible_color(color)[source]

Get the visible counter-color.