MooseX::App(3)
π MooseX::App(3) β user-contributed Perl documentation
okay bestie, buckle up: this is the MooseX::App(3) page, and it is literally about writing user-friendly command line apps with even less suffering. No cap. π
πΈ NAME
MooseX::App β write user-friendly command line apps with even less suffering π
β¨ SYNOPSIS
First, in your base class:
package MyApp;
use MooseX::App qw(Color);
option 'global_option' => (
is => 'rw',
isa => 'Bool',
documentation => q[Enable this to do fancy stuff],
); # Global option
has 'private' => (
is => 'rw',
); # not exposed
Write multiple command classes (if you have only a single command class you should use MooseX::App::Simple instead). Packages in the namespace may be deeply nested.
package MyApp::SomeCommand;
use MooseX::App::Command; # important (also imports Moose)
extends qw(MyApp); # optional, only if you want to use global options from base class
# Positional parameter
parameter 'some_parameter' => (
is => 'rw',
isa => 'Str',
required => 1,
documentation => q[Some parameter that you need to supply],
);
option 'some_option' => (
is => 'rw',
isa => 'Int',
required => 1,
documentation => q[Very important option!],
); # Option
sub run {
my ($self) = @_;
# Do something
}
And then you need a simple wrapper script (called eg. myapp):
#!/usr/bin/env perl
use MyApp;
MyApp->new_with_command->run;
On the command line:
bash$ myapp help
usage:
myapp <command> [long options...]
myapp help
global options:
--global_option Enable this to do fancy stuff [Flag]
--help --usage -? Prints this usage information. [Flag]
available commands:
some_command Description of some command
another_command Description of another command
help Prints this usage information
or
bash$ myapp some_command --help
usage:
myapp some_command <SOME_PARAMETER> [long options...]
myapp help
myapp some_command --help
parameters:
some_parameter Some parameter that you need to supply [Required]
options:
--global_option Enable this to do fancy stuff [Flag]
--some_option Very important option! [Int,Required]
--help --usage -? Prints this usage information. [Flag]
π DESCRIPTION
MooseX-App is a highly customisable helper for writing user-friendly command line applications without having to worry about most of the annoying things usually involved. Just take any existing Moose class, add a single line (use MooseX-App qw(PluginA PluginB ...);) and create one class for each command in an underlying namespace. Options and positional parameters can be defined as simple Moose accessors using the option and parameter keywords respectively.
MooseX-App will then:
- Find, load and initialise the command classes (see
MooseX::App::Simplefor single class/command applications) - Create automated help and documentation from modules POD as well as attributes metadata and type constraints
- Read, encode and validate the command line options and positional parameters entered by the user from
@ARGVand%ENV(and possibly prompt the user for additional parameters seeMooseX::App::Plugin::Term) - Provide helpful error messages if user input cannot be validated (either missing or wrong attributes or Moose type constraints not satisfied) or if the user requests help.
Commandline options are defined using the 'option' keyword which accepts the same attributes as Moose' 'has' keyword.
option 'some_option' => (
is => 'rw',
isa => 'Str',
);
This is equivalent to:
has 'some_option' => (
is => 'rw',
isa => 'Str',
traits => ['AppOption'], # Load extra metaclass
cmd_type => 'option', # Set attribute type
);
Single letter options are treated as flags and may be combined with each other. However such options must have a Boolean type constraint.
option 'verbose' => (
is => 'rw',
isa => 'Bool',
cmd_flag => 'v',
);
Positional parameters are defined with the 'parameter' keyword:
parameter 'some_option' => (
is => 'rw',
isa => 'Str',
);
This is equivalent to:
has 'some_option' => (
is => 'rw',
isa => 'Str',
traits => ['AppOption'],
cmd_type => 'parameter',
);
All keywords are imported by Moosex::App (in the app base class) and MooseX::App::Command (in the command class) or MooseX::App::Simple (single class application).
Furthermore, all options and parameters can also be supplied via %ENV:
option 'some_option' => (
is => 'rw',
isa => 'Str',
cmd_env => 'SOME_OPTION', # sets the env key
);
Moose type constraints help MooseX::App to construct helpful error messages and parse @ARGV in a meaningful way. The following type constraints are supported:
- ArrayRef: Specify multiple values (
'--opt value1 --opt value2', also seeapp_permuteandcmd_split) - HashRef: Specify multiple key value pairs (
'--opt key=value --opt key2=value2', also seeapp_permute) - Enum: Display all possibilities
- Bool: Flags that do not require values
- Int, Num: Used for proper error messages
Read the Tutorial for getting started with a simple MooseX::App command line application.
π¦ METHODS
π«Ά new_with_command
my $myapp_command = MyApp->new_with_command();
This constructor reads the command line arguments and tries to create a command class instance. If it fails it returns a MooseX::App::Message::Envelope object holding an error message.
You can pass a hash of default/fallback params to new_with_command:
my $obj = MyApp->new_with_command(%default);
Optionally you can pass a custom ARGV to this constructor:
my $obj = MyApp->new_with_command( ARGV => \@myARGV );
However, if you do so you must take care of proper @ARGV encoding yourself.
π«Ά initialize_command_class
my $obj = MyApp->initialize_command_class($command_name,%default);
Helper method to instantiate the command class for the given command.
π GLOBAL OPTIONS
These options may be used to alter the default behaviour of MooseX-App.
π app_base
app_base 'my_script'; # Defaults to $0
Usually MooseX::App will take the name of the calling wrapper script to construct the program name in various help messages. This name can be changed via the app_base function.
π app_fuzzy
app_fuzzy 1; # default
OR
app_fuzzy 0;
Enables fuzzy matching of commands and attributes. Is turned on by default.
π app_strict
app_strict 0; # default
OR
app_strict 1;
If strict is enabled the program will terminate with an error message if superfluous/unknown positional parameters are supplied. If disabled all extra parameters will be copied to the extra_argv attribute. Unknown options (with leading dashes) will always yield an error message.
The command_strict config in the command classes allows one to set this option individually for each command in the respective command class.
π app_prefer_commandline
app_prefer_commandline 0; # default
or
app_prefer_commandline 1;
Specifies if parameters/options supplied via @ARGV,%ENV should take precedence over arguments passed directly to new_with_command.
π app_namespace
app_namespace 'MyApp::Commands', 'YourApp::MoreCommands';
OR
app_namespace();
Usually MooseX::App will take the package name of the base class as the namespace for commands. This namespace can be changed and you can add multiple extra namespaces.
If app_namespace is called with no arguments then autoloading of command classes will be disabled entirely.
π app_exclude
app_exclude 'MyApp::Commands::Roles','MyApp::Commands::Utils';
A sub namespace included via app_namespace (or the default behaviour) can be excluded using app_exclude.
π app_command_name
app_command_name {
my ($package_short,$package_full) = @_;
# munge package name;
return $command_name;
};
This coderef can be used to control how autoloaded package names should be translated to command names. If this command returns nothing the respective command class will be skipped and not loaded.
π app_command_register
app_command_register
do => 'MyApp::Commands::DoSomething',
undo => 'MyApp::Commands::UndoSomething';
This keyword can be used to register additional commands. Especially useful in conjunction with app_namespace and disabled autoloading.
π app_description
app_description qq[Description text];
Set the app description text. If not set this information will be taken from the Pod DESCRIPTION or OVERVIEW sections. (see command_description to set usage per command)
π app_usage
app_usage qq[myapp --option ...];
Set a custom usage text. If not set this will be taken from the Pod SYNOPSIS or USAGE section. If both sections are not available, the usage information will be autogenerated. (see command_usage to set usage per command)
π app_permute
app_permute 0; # default
OR
app_permute 1;
Allows one to specify multiple values with one key. So instead of writing "--list element1 --list element2 --list element3" one might write "--list element1 element2 element3" for ArrayRef elements. HashRef elements may be expressed as "--hash key=value key2=value2".
π GLOBAL ATTRIBUTES
All MooseX::App classes will have two extra attributes.
π extra_argv
Carries all parameters from @ARGV that were not consumed (only if app_strict is turned off, otherwise superfluous parameters will raise an exception).
π help_flag
Help flag that is set when help was requested.
π ATTRIBUTE OPTIONS
Options and parameters accept extra attributes for customisation:
cmd_tagsβ Extra tags (as used by the help)cmd_flagβ Override option/parameter namecmd_aliasesβ Additional option/parameter name aliasescmd_splitβ Split values into ArrayRefs on this token or RegExcmd_positionβ Specify option/parameter order in helpcmd_envβ Read options/parameters from%ENVcmd_countβ Value of option equals to number of occurrences in@ARGVcmd_negateβ Adds an option to negate boolean flags
Refer to MooseX::App::Meta::Role::Attribute::Option for detailed documentation.
π METADATA π
okay so MooseX::App is lowkey a little detective π β it snoops through your class metadata and your POD to build commands and to make actually helpful error/usage messages. these bits of info are what it uses, and bestie, you should provide them if you can:
- π¦ Package names
- β required options for Moose attributes
- π documentation options for Moose attributes
- 𧬠Moose type constraints (
Bool,ArrayRef,HashRef,Int,Num, andEnum) - π documentation set via
app_description,app_usage,command_short_description,command_long_descriptionandcommand_usage - π POD (
NAME,ABSTRACT,DESCRIPTION,USAGE,SYNOPSIS,OVERVIEW,COPYRIGHT,LICENSE,COPYRIGHT AND LICENSE,AUTHORandAUTHORSsections) - π·οΈ the Dist::Zilla
ABSTRACTtag if you donβt have POD yet
π§© PLUGINS π§©
so MooseX-App can be customised with plugins, and loading them is literally just passing a list of plugin names after the use MooseX-App statement. β οΈ Attention: order sometimes matters β yes, like a group chat where the wrong person speaks first and suddenly itβs chaos.
use MooseX::App qw(PluginA PluginB);
Currently the following plugins ship with MooseX::App:
- π
MooseX::App::Plugin::BashCompletionβ adds a command that generates a bash completion script for your application. see third partyMooseX::App::Plugin::ZshCompletionfor Z shell completion. - πΈ
MooseX::App::Plugin::Colorβ colorful output for your MooseX::App applications. - βοΈ
MooseX::App::Plugin::Configβ config files for MooseX::App applications. - π
MooseX::App::Plugin::ConfigHomeβ tries to find config files in the userβs home directory. - π¬
MooseX::App::Plugin::Termβ prompts the user for options and parameters that werenβt provided via options or params. the prompt offers basic editing capabilities and non-persistent history. - π€
MooseX::App::Plugin::Typoβ handles typos in command names and gives suggestions. - π·οΈ
MooseX::App::Plugin::Versionβ adds a command to display the version and license of your application. - π
MooseX::App::Plugin::Manβ displays the full manpage of the application and its commands. - π
MooseX::App::Plugin::MutexGroupβ allows for mutually exclusive options. - π
MooseX::App::Plugin::Dependsβ adds dependent options.
Refer to Writing MooseX-App Plugins for documentation on how to create your own plugins. π οΈβ¨
π§ͺ DEVELOPMENT π§ͺ
bestie, please make sure to invoke your script with APP_DEVELOPER=1 ser during development. π this comes with a starup penalty but performs additional checks for detecting wrong attribute/type constraint combinations, name clashes, β¦ yeah, itβs the βturn on the extra safety railsβ mode.
ngl, the starup typo is in the original and itβs giving βdeveloper mode has no time for spellcheckβ π but the point is: extra checks, slightly slower start.
π CAVEATS & KNOWN BUGS π
Startup time may be an issue β especially if you load many plugins. π if you donβt require plugin functionality and the ability for fine-grained customisation (or Moose itself, for that matter), then you should probably use MooX::Options or MooX::Cmd.
In some cases β especially when using non-standard class inheritance β you may end up with command classes that are missing the help attribute. π« in that case you need to include the following line in your base class or command classes:
with qw(MooseX::App::Role::Common);
When manually registering command classes (e.g. via app_command_register) in multiple base classes with different sets of plugins (and honestly, why would you ever want to do that? π), then meta attributes may lack some attribute metaclasses. in that case you need to load the missing attribute traits explicitly:
option 'argument' => (
depends => 'otherargument',
trait => ['MooseX::App::Plugin::Depends::Meta::Attribute'], # load trait
);
π SEE ALSO π
Read the Tutorial for getting started with a simple MooseX::App command line application. π£
For alternatives you can check out:
MooseX::App::CmdMooseX::GetoptMooX::OptionsMooX::CmdApp::Cmd
π«Ά SUPPORT π«Ά
Please report any bugs or feature requests via https://github.com/maros/MooseX-App/issues/new. I will be notified, and then youβll automatically be notified of progress on your report as I make changes. π¬β¨
π AUTHOR π
MaroΕ‘ KollΓ‘r
CPAN ID: MAROS
maros [at] k-1.com
http://www.k-1.com
π CONTRIBUTORS π
Special thanks to all contributors. π
In no particular order: Andrew Jones, George Hartzell, Steve Nolte, Michael G, Thomas Klausner, Yanick Champoux, Edward Baudrez, David Golden, J.R. Mash, Thilo Fester, Gregor Herrmann, Sergey Romanov, Sawyer X, Roman F., Hunter McMillen, Maik Hentsche, Alexander Stoddard, Marc Logghe, Tina MΓΌller, Lisa Hare, Jose Luis Martinez, Frank Schreiner, Bernhard M. Wiedemann, Petr Pisar, William Barker.
You are more than welcome to contribute to MooseX-App. π«Ά please have a look at the https://github.com/maros/MooseX-App/issues?q=is%3Aissue+is%3Aopen+label%3AWishlist list of open wishlist issues for ideas. β¨
π COPYRIGHT π
MooseX::App is Copyright (c) 2012-23 MaroΕ‘ KollΓ‘r.
This library is free software and may be distributed under the same terms as perl itself. the full text of the licence can be found in the LICENCE file included with this module. π
and thatβs the whole vibe, bestie β this page is from perl v5.42.0, dated 2024-08-09, and itβs serving MooseX::App(3) realness. slay responsibly. π
β¨
π¦ where this page comes from
- opensuse-leap 16.0: perl-MooseX-App 1.430.1-bp160.1.10 Β· Artistic-1.0 OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms