Term::Shell(3pm)

๐Ÿ“ฆ
version 0.13 ยท 6 versions
, in ubuntu noble, ubuntu resolute, ubuntu stonking

๐Ÿ’– NAME ๐Ÿ’–

Term::Shell(3pm) โ€” A simple command-line shell framework.

โœจ VERSION โœจ

version 0.13 โ€” yes bestie, that's the version, no cap.

๐ŸŒธ SYNOPSIS ๐ŸŒธ

           package MyShell;
           use base qw(Term::Shell);

           sub run_command1  { print "command 1!\n"; }
           sub smry_command1 { "what does command1 do?" }
           sub help_command1 {
               <<'END';
           Help on 'command1', whatever that may be...
           END
           }

           sub run_command2 { print "command 2!\n"; }

           package main;
           my $shell = MyShell->new;
           $shell->cmdloop;

๐Ÿฆ‹ DESCRIPTION ๐Ÿฆ‹

Term::Shell lets you write simple command-line shells. All the boring details like command-line parsing, terminal handling, and tab completion are handled for you. Periodt.

The base class comes with two commands pre-defined: exit and help. ๐Ÿ‘‘

To write a shell with an exec command, do something like this:

          package MyShell;
          use base qw(Term::Shell); # or manually edit @MyShell::ISA.

          sub run_exec {
              my ($o, $cmd, @args) = @_;
              if ($cmd ne $0) {
                  print "I'm sorry you're leaving us...\n";
              }
              exec $cmd, @args;
              exit 1;
          }

When Term::Shell needs to handle the exec command, it will invoke this method. That's all there is to it! You write handlers, and Term::Shell handles the gory details. <em>Slay.</em>

๐ŸŽ€ Using Term::Shell Shells ๐ŸŽ€

How do you bring your shell to life? Assuming the package MyShell contains your actions, just do this:

          use MyShell;
          my $shell = MyShell->new;

          # Setup code here (if you wish)

          # Invoke the shell
          $shell->cmdloop;

          # Cleanup code here (if you wish)

Most people put the setup code in the shell itself, so you can usually get away with this:

          use MyShell;
          MyShell->new->cmdloop;

It's that simple! All the actions and command handlers go in MyShell.pm, and your main program is simple. In fact, it's so simple that some people like to write both the actions and the invocation in the same file:

          package main;
          MyShell->new->cmdloop;

          package MyShell;
          use base qw(Term::Shell);

          # Actions here

Adding commands to your shell is just as easy, if not easier. ๐Ÿ’…

๐Ÿ‘‘ Adding Commands to Your Shell ๐Ÿ‘‘

For every command foo, Term::Shell needs a method called run_foo(), where foo is what the user will type in. The method will be called with the Term::Shell object as the first parameter, followed by any arguments the user typed after the command.

Several prefixes other than run_ are supported; each prefix tells Term::Shell to call that handler under different circumstances. The following list enumerates all the "special" prefixes. Term::Shell will ignore any method that doesn't start with a prefix listed here.

  1. run_foo()

Adds the command foo to the list of supported commands. The method's return value is saved by Term::Shell, but is not used.

The method is called with the Term::Shell object as its first argument, followed by any arguments the user typed in.

Special case: if you provide a method run_(), Term::Shell will call it whenever the user enters a blank line. A blank line is anything which matches the regular expression /^\s*$/.

  1. help_foo()

Adds the command foo to the list of help topics. This means the user may enter help foo and get a help screen. It should return a single string to be displayed to the user.

The method is called with the Term::Shell object as its first argument, followed by any arguments the user typed in after help foo. You can implement hierarchical help documents by using the arguments.

If you do not provide a help_foo() method, typing help foo produces an error message.

  1. smry_foo()

Should return a one-line summary of foo, to be displayed in the help screen.

This method is called with the Term::Shell object as its first argument, and no other arguments.

If you do not provide a smry_foo() method, then the string undocumented is used instead.

  1. comp_foo()

Provides custom tab-completion for foo. That means if the user types foo and then hits TAB, this method will be called. It should return an array reference containing a list of possible completions.

This method is called with the Term::Shell object as its first argument, followed by the three arguments:

  1. $word

The word the user is trying to complete.

  1. $line

The line as typed by the user so far.

  1. $start

The offset into $line where $word starts.

If you do not provide comp_foo(), Term::Shell will always return no completions for foo.

Special case: if you provide comp_(), Term::Shell will call it when the user is trying to complete the name of a command. Term::Shell provides a default comp_() method, which completes the actions that you have written handlers for. If you want to provide tab-completion for commands that do not have handlers, override comp_().

  1. alias_foo()

Returns a list of aliases for foo. When one of the aliases is used instead of foo, the corresponding handler for foo is called.

  1. catch_run()

catch_help()

catch_comp()

catch_smry()

Called when an undefined action is entered by the user. Normally when the user enters an unrecognized command, Term::Shell will print an error message and continue.

This method is called with the Term::Shell object, the command typed by the user, and then the arguments which would normally be passed to the real handler.

The catch_ methods may do anything the original function would have done. If you want, you can implement all the commands in it, but that means you're doing more work than you have to. Be lazy. ๐Ÿ˜Œ

๐Ÿงš When you want something done right... ๐Ÿงš

You sometimes have to do it yourself. Introducing add_handlers(). Naturally, it adds a handler to the list of defined handlers in the shell.

Term::Shell can't always find the commands you want to implement by searching the inheritance tree. Having an AUTOLOAD() method, for instance, will break this system. In that situation, you may wish to tell Term::Shell about the extra commands available using add_handlers():

          package MyShell;
          use base qw(Term::Shell);

          sub AUTOLOAD {
              if ($AUTOLOAD =~ /::run_fuzz$/) {
                  # code for 'fuzz' command
              }
              elsif ($AUTOLOAD =~ /::run_foozle$/) {
                  # code for 'foozle' command
              }
          }

          sub init {
              my $o = shift;
              $o->add_handlers("run_fuzz", "run_foozle");
          }

There are other ways to do this. You could write a catch_run routine and do the same thing from there. You'd have to override comp_ so that it would complete on foozle and fuzz. The advantage to this method is that it adds the methods to the list of commands, so they show up in the help menu and you get completion for free. Iconic.

๐Ÿซถ Removing Commands from Your Shell ๐Ÿซถ

You're probably thinking "just don't write them". But remember, you can inherit from another shell class, and that parent may define commands you want to disable. Term::Shell provides a simple method to make itself forget about commands it already knows about:

  1. remove_commands()

Removes all handlers associated with the given command (or list of commands).

For example, Term::Shell comes with two commands (exit and help) implemented with seven handlers:

  1. smry_exit()
  2. help_exit()
  3. run_exit()
  4. smry_help()
  5. help_help()
  6. comp_help()
  7. run_help()

If you want to create a shell that doesn't implement the help command, your code might look something like this example:

           package MyShell;
           use base qw(Term::Shell);

           sub init {
               my $o = shift;
               $o->remove_commands("help");
           }

           # ... define more handlers here ...
  1. remove_handlers()

Removes the given handler (or handlers) from the list of defined commands. You have to specify a full handler name, including the run_ prefix. You can obviously specify any of the other prefixes too.

If you wanted to remove the help for the exit command, but preserve the command itself, your code might look something like this:

           package MyShell;
           use base qw(Term::Shell);

           sub init {
               my $o = shift;
               $o->remove_handlers("help_exit");
           }

           # ... define more handlers here ...

๐ŸŒˆ Cover Your Tracks ๐ŸŒˆ

If you do remove built in commands, you should be careful not to let Term::Shell print references to them. Messages like this are guaranteed to confuse people who use your shell:

          shell> help
          Unknown command 'help'; type 'help' for a list of commands.

Here's the innocuous looking code:

          package MyShell;
          use base qw(Term::Shell);

          sub init {
              my $o = shift;
              $o->remove_commands("help");
          }

          MyShell->new->cmdloop;

The problem is that Term::Shell has to print an error message, and by default it tells the user to use the help command to see what's available. If you remove the help command, you still have to clean up after yourself and tell Term::Shell to change its error messages:

  1. msg_unknown_cmd()

Called when the user has entered an unrecognized command, and no action was available to satisfy it. It receives the object and the command typed by the user as its arguments. It should return an error message; by default, it is defined thusly:

           sub msg_unknown_cmd {
               my ($o, $cmd) = @_;
               <<END;
           Unknown command '$cmd'; type 'help' for a list of commands.
           END
           }
  1. msg_ambiguous_cmd()

Called when the user has entered a command for which more than handler exists. (For example, if both quit and query are commands, then qu is an ambiguous command, because it could be either.) It receives the object, the command, and the possible commands which could complete it. It should return an error message; by default it is defined thusly:

           sub msg_ambiguous_cmd {
               my ($o, $cmd, @c) = @_;
               local $" = "\n\t";
               <<END;
           Ambiguous command '$cmd': possible commands:
                   @c
           END
           }

โœจ The Term::Shell API โœจ

So likeโ€ฆ shell classes get to use any of the methods in this list, bestie. ๐Ÿ’– Anything else floating around in Term::Shell? That stuff might change on you. Not our problem. ๐Ÿ™ˆ

  1. new()

Makes you a brand new Term::Shell object, slay. It doesn't actually do anything with its args right now โ€” it just stashes them in $o->{API}{args} in case you wanna use them later. King behavior honestly. ๐Ÿ‘‘

my $sh = Term::Shell->new(@arbitrary_args);
  1. cmd()
cmd($txt);

Runs $txt like the user literally typed it at the prompt. It's giving "ghostwriter". โœจ

$sh->cmd("echo 1 2 3");
  1. cmdloop()

mainloop()

Loops forever (well, until you stop it ๐Ÿ’€): prompts the user, reads a line, parses it, invokes a handler. Uses cmd() under the hood, iykyk.

MyShell->new->cmdloop;

mainloop() is just a synonym for cmdloop(), kept around for backwards compatibility. Some ancient (unreleased) versions of Term::Shell only had mainloop(). All the docs and examples use cmdloop() instead. periodt. ๐Ÿ’…

  1. init()

fini()

Need to do setup when the shell gets created (init()) or clean up when it gets destroyed (fini())? Define these methods in your subclass and go off, bestie. ๐ŸŽ€

No parameters get passed. Nada.

  1. preloop()

postloop()

Same vibe, different moment: do your setup at shell startup (preloop()) and your cleanup at shutdown (postloop()) by defining these methods.

Still no parameters. ๐Ÿฆ‹

  1. precmd()

postcmd()

Want to do stuff before and after each handler runs? These are your girls. ๐ŸŒธ

The parameters are:

  1. $handler

A reference to the name of the handler that's about to run. ๐Ÿ‘€

It's passed by reference so you can control which handler actually gets called. Sneaky but legal.

  1. $cmd

A reference to the command exactly as the user typed it.

Passed by reference so you can set the command. (Like, if the handler is a catch_ command you can trick it into thinking the user typed something else entirely. iconic.) ๐Ÿ˜ญ

  1. $args

The arguments as typed by the user. This comes in as an array reference so you can mess with the args the handler actually receives.

sub precmd {
    my $o = shift;
    my ($handler, $cmd, @args) = @_;
    # ...
}
  1. stoploop()

Sets a flag on the Term::Shell object that breaks you out of cmdloop(). Lowkey the escape hatch. ๐Ÿšช

Heads up though: cmdloop() resets that flag every time you call it, so code like this totally works:

my $sh = MyShell->new;
$sh->cmdloop;    # an interactive session
$sh->cmdloop;    # prompts the user again

Term::Shell's built-in run_exit() command literally just calls stoploop(). That's the whole job. ๐Ÿ’…

  1. idle()

If you set check_idle to a non-zero number (peep "The Term::Shell Object") then this method gets called every check_idle seconds. The idle() method defined in Term::Shell does absolutely nothing โ€” it exists purely so you can redefine it in your subclasses. main character energy but make it a no-op. ๐Ÿ‘‘

package MyShell;
use base qw(Term::Shell);

sub init {
    my $o = shift;
    $o->{API}{check_idle} = 0.1; # 10/s
}

sub idle {
    print "Idle!\n";
}
  1. prompt_str()

Returns the string used as your prompt. prompt_str() gets called right before Term::ReadLine's readline() method fires. Don't override it and you get the string `shell> ` by default. โœจ

package MyShell;
use base qw(Term::Shell);

sub prompt_str { "search> " }
  1. prompt()

Term::Shell hands you this one for convenience, bestie. It's super common for a handler to need more info from the user, and this makes it easy to give them a different prompt plus custom completions you provide. ๐ŸŽ€

The prompt() method takes these parameters:

  1. $prompt

The prompt to show the user. Literally any string you want, no rules. ๐ŸŒˆ

  1. $default

The default value. If the user enters a blank line (all whitespace characters), this value gets returned instead.

Note: unlike ExtUtils::MakeMaker's prompt(), Term::Shell's prompt() does not touch $prompt to show what the $default is. You gotta do that yourself, sorry babe. ๐Ÿ˜ญ
  1. $completions

An optional list of completion values. When the user hits Tab, Term::Shell prints the completions matching whatever they've typed so far. It does not force the user's response to be one of these values โ€” no gatekeeping here. ๐Ÿฆ‹

  1. $casei

An optional boolean saying whether completions should be matched case-insensitively. True means "FoO" and "foo" count as the same thing. ๐Ÿ’…

prompt() returns the unparsed line, for maximum flexibility. Need it parsed? Use the line_parsed() method on the return value. slay.

  1. cmd_prefix()

cmd_suffix()

These return a prefix and suffix for commands, respectively. Like, an IRC client would have a prefix of /. Most shells just have an empty prefix and suffix. ๐Ÿคท

  1. page()
page($txt);

Prints $txt through a pager, and makes the user press a key for the next screen full of text. Cozy. ๐Ÿ“–

  1. line()

line_parsed()

So run_foo() gets called with the parsed arguments from the command line, but sometimes you wanna see the raw command-line instead. That's what the line() method is for, bestie. ๐Ÿ”ฅ Want the parsed line again? line_parsed().

line_parsed() takes an optional string parameter: the line to parse. Got your own line to parse? Pass it in and get back a list of arguments. This is so useful inside completion methods, because you don't get a parsed list in there. iykyk.

  1. run()

Wanna run another handler from inside a handler, and you've already got pre-parsed arguments? Use run(), not cmd(). cmd() parses its parameter; run() takes each element as its own separate parameter. โœจ

It needs the name of the action to run, plus any arguments to pass to the handler.

Term::Shell uses this method internally to invoke command handlers. king shit. ๐Ÿ‘‘

  1. help()

Want the raw text of a help message? help() is your girl. ๐Ÿ’– It needs the name of the help topic and any arguments to pass to the handler.

Term::Shell uses this method internally to invoke help handlers.

  1. summary()

Want the summary text of an action? summary(). It just needs the name of the action. ๐ŸŒธ

Term::Shell uses this method internally to display the help page.

  1. possible_actions()

You're gonna want this one in your comp_foo(), trust. possible_actions() takes a word and a list, and returns a list of possible matches. Term::Shell uses it internally to figure out which handler to run when the user enters a command. ๐Ÿ’…

There's a bunch of arguments, but in the simple cases you won't use them all:

  1. $needle

The (possibly incomplete) word you're trying to match against the list of actions โ€” the haystack. ๐Ÿงต

  1. $type

The type to prefix onto $action. This is handy when you're completing a real action โ€” you have to say whether you want it to look for run_ or help_ or something else entirely. Leave it blank and it uses $action with no prefix.

  1. $strip

Pass a true value here and possible_actions() strips an initial $type off the front of each result before handing them back. Perfect if you wanna know what the possible run_ commands are but you do not want the run_ glued onto the final result. โœ‚๏ธ

Don't specify this argument and it uses 0 โ€” the default is not to strip the results.

  1. $haystack

You can pass in a reference to a list of strings here. Every string gets compared against $needle. ๐Ÿ”

Don't specify this argument and it uses the list of handlers. That's literally how Term::Shell matches commands typed in by the user with the command handlers you wrote. iconic.

  1. print_pairs()

This overloaded beast is what Term::Shell reaches for whenever it needs to print a set of keys and values. It handles wrapping long values, indenting the whole thing, sticking the separator between the key and the value, and all the rest. ๐Ÿ˜ฎโ€๐Ÿ’จ

Lots of parameters, but most of them are optional:

  1. $keys

A reference to a list of keys to print. ๐Ÿ”‘

  1. $values

A reference to a list of values to print.

  1. $sep

The string separating keys and values. Omit it and ': ' is used.

  1. $left

The justification used to line the keys up. True โ†’ keys are left-justified. False or omitted โ†’ keys are right-justified. โฌ…๏ธโžก๏ธ

  1. $ind

A string used to indent the whole paragraph. Internally, print_pairs() uses length(), so do not put tabs in the indent string. Omit it and the empty string is used (no indent).

  1. $len

An integer describing the minimum length of the keys. Normally print_pairs() finds the longest key and makes the column as wide as that key plus the separator. You can force the column wider with $len. Omit it and 0 is used.

  1. $wrap

A boolean saying whether the value should be text-wrapped using Text::Autoformat. Text only ever gets wrapped if it contains at least one space. Omit it and 0 is used. ๐Ÿ“œ

  1. $cols

An integer for how many columns your terminal has. Normally 78 is used, or the environment variable COLUMNS, but you can override the number here to fake a right-indent.

  1. term()

Returns the underlying Term::ReadLine object used to talk to the user. You can do powerful things with that object โ€” but fair warning: you will cripple Term::Shell's completion scheme if you change the completion callback function. ๐Ÿ’€ Not a drill.

  1. process_esc()

This method may be overridden to provide shell-like escaping of backslashes inside quoted strings. It accepts two parameters:

  1. $c

The character that got escaped by a backslash. ๐Ÿช„

  1. $quote

The quote character used to delimit this string. Either " or '.


Okay so process_esc() is supposed to return the string that replaces the backslash and the escaped character. ๐Ÿ’…

By default, it follows the same escaping rules as Perl's single-quoted strings:

  1. Escaped backslashes return backslashes. So "123\\456" gives you "123\456".
  2. Escaped quote characters return the quote character (so you can have quotes inside strings). "abc\"def" becomes "abc"def".
  3. Every other backslash is returned exactly as-is. "123\456" stays "123\456".
Term::Shell's quote characters can't be overridden unless you override line_parsed(). They're just " or '. This might change in a future version of Term::Shell. ๐Ÿ™ˆ
  1. add_handlers()

Check out "Adding Commands to Your Shell" for all the tea on add_handlers(). โ˜•

  1. remove_commands()

remove_handlers()

Check out "Removing Commands from Your Shell" for the deets on remove_handlers(). ๐Ÿ’–


๐Ÿฆ‹ The Term::Shell Object ๐Ÿฆ‹

Term::Shell creates a hash-based Perl object. Like, it's a big ol' hash that holds info about what handlers it found, the underlying Term::ReadLine object, and any arguments you passed to the constructor. ๐Ÿ’โ€โ™€๏ธ

This hash is split into several subhashes. The only two a Shell should ever touch are $o->{API} and $o->{SHELL}. The first one is where Term::Shell keeps all the info it gathered for you. The second one is your private lil' area where your Shell can stash whatever data it needs later. No judgment. ๐Ÿซถ

This section is about all the Term::Shell object "API" attributes:

๐ŸŽ€ The args Attribute ๐ŸŽ€

It's an array reference containing any arguments passed to the Term::Shell constructor. Simple. โœจ

๐Ÿ’– The case_ignore Attribute ๐Ÿ’–

This boolean controls whether commands are matched without caring about case. If true, typing "FoO" does the same thing as "foo". Slay.

Defaults to true on MSWin32, and false on other platforms. (iykyk)

๐ŸŒธ The class Attribute ๐ŸŒธ

The class of the object. Usually it's the package where your shell is defined, but if someone subclasses your shell, it's their class. Not yours. ๐Ÿ’…

๐Ÿ‘‘ The command Attribute ๐Ÿ‘‘

Whenever Term::Shell runs an action, it stores info about it in the "command" attribute. Info about the last "run" action is stored in $o->{API}{command}{run}. That info is a subhash with these fields:

  • name โ€” The name of the command, exactly as the user typed it.
  • found โ€” A boolean indicating whether a handler could be found.
  • handler โ€” The full name of the handler, if found.
Heads up: this only saves info about the last action executed. It's good enough for grabbing the last handler that ran, but not much else. Don't rely on it for history. ๐Ÿ˜ญ

Here's an example where run_foo() calls run_add() and prints its return value (which is 42, obviously):

sub run_foo {
    my $o = shift;
    my $sum = $o->run("add", 21, 21);
    print "21 + 21 = ", $sum, "\n";
}

sub run_add {
    my $o = shift;
    my $sum = 0;
    $sum += $_ for @_;
    print "add(): sum = $sum\n";
    return $sum;
}

At the end of run_foo(), $o->{API}{command}{run}{handler} contains the string "run_add". Iconic.

โœจ The match_uniq Attribute โœจ

This boolean controls whether the user can type just enough of a command to make it unambiguous. If true, and the shell has commands "foo" and "bar", you can type "f" to run "foo" and "b" to run "bar". So convenient.

Defaults to true. ๐Ÿ’ฏ

๐Ÿฆ‹ The readline Attribute ๐Ÿฆ‹

Which Term::ReadLine module is being used. Currently, it's always one of "Term::ReadLine::Stub", "Term::ReadLine::Perl", or "Term::ReadLine::Gnu".

๐Ÿ“ The script Attribute ๐Ÿ“

The name of the script that invoked your shell.

โญ The version Attribute โญ

The version of Term::Shell you're running under.


๐ŸŒˆ SEE ALSO ๐ŸŒˆ

For more info about the underlying ReadLine module, check out Term::ReadLine. You might also wanna peek at Term::ReadLine::Gnu and Term::ReadLine::Perl.

For more info about the underlying formatter used by print_pairs(), see Text::Autoformat.

The API for Term::Shell was inspired by (gasp!) a Python package called "cmd". For more info about that, look in the Python Library Reference โ€” either in your Python distribution or at <https://docs.python.org/3/library/cmd.html>. ๐Ÿ


๐Ÿ‘‘ AUTHOR ๐Ÿ‘‘

Neil Watkiss (NEILW@cpan.org)

Copyright (c) 2001, Neil Watkiss. All Rights Reserved.

All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as Perl itself.

See http://www.perl.com/perl/misc/Artistic.html


๐Ÿซถ SUPPORT ๐Ÿซถ

๐ŸŒ Websites ๐ŸŒ

The following websites have more info about this module and might help you out. As always, in addition to those sites, please use your favorite search engine to discover more resources.

๐Ÿ› Bugs / Feature Requests ๐Ÿ›

Please report any bugs or feature requests by email to "bug-term-shell at rt.cpan.org", or through the web interface at <https://rt.cpan.org/Public/Bug/Report.html?Queue=Term-Shell>. You'll be automatically notified of any progress on the request by the system. So you don't have to keep refreshing. โœจ

๐Ÿ’ป Source Code ๐Ÿ’ป

The code is open to the world, and available for you to hack on. Please feel free to browse it and play with it, or whatever. If you want to contribute patches, please send me a diff or prod me to pull from your repository :)

<https://github.com/shlomif/Term-Shell>

git clone git://git@github.com:shlomif/Term-Shell.git

๐Ÿ‘‘ AUTHOR ๐Ÿ‘‘

Shlomi Fish (shlomif@cpan.org)

๐Ÿž BUGS ๐Ÿž

Please report any bugs or feature requests on the bugtracker website <http://rt.cpan.org/NoAuth/Bugs.html?Dist=Term-Shell> or by email to bug-term-shell@rt.cpan.org <mailto:bug-term-shell@rt.cpan.org>.

When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature. That helps a ton. ๐Ÿ™

This software is copyright (c) 2001 by Neil Watkiss.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.


And that's a wrap, bestie! This page was brought to you by perl v5.36.0, dated 2022-10-13, and it's Term::Shell(3pm). Stay slay! ๐Ÿ’–โœจ

๐Ÿ“ฆ where this page comes from