System Aliases

To date there are well over 100 aliases manually added to the shell.

These aliases depend on the operating system used as Linux OSes will default to a bash system shell, and Windows will have dosbatch or powershell shells.

Overview

This module utilizes _ip, the global InteractiveShell instance, and fills the user_ns with aliases that are available in a typical system shell.

Unfortunately, the exact definition of what a system shell is, what language it responds to, and it’s ability to receive and pass along input and output in pipelines will vary greatly.

As a result, the module needs to test the user’s OS, what shell they’re using and what executables are available on the PATH.

On Unix platforms, it is assumed that the user is using a bash shell.

However on Windows, it is possible that the user has a shell that runs dosbatch, powershell, or bash.

As a result, the environment variable COMSPEC will be checked, and if present, that value is used.

Attributes

ipInteractiveShell

A global object representing the active IPython session. Contains varying packages as well as the current global namespace. Doesn’t need to be defined in advance during an interactive session.

Parameters

%lCommand-line argument.

The remainder of the user’s input. Commonly referred to in the Jupyter documentation as the remaining ‘cell’. You can use the %l specifier in an %alias definition to represent the whole line when the alias is called.

%sCommand line argument

A required positional parameter can be given to the alias.

Variable Expansion in Aliases

%alias
%unalias

Note that we quote when in the configuration file but when running %alias interactively the syntax.

%alias alias_name cmd

Doesn’t require quoting.

Aliases expand Python variables just like system calls using ! or !! do: all expressions prefixed with $ get expanded. For details of the semantic rules, see PEP 215 as this is the library used by IPython for variable expansion.

Meaning that it behaves similarly to the parameter $* in typical POSIX shells.

See also

IPython.core.alias

Module where the alias functionality for IPython is defined and the basic implementation scaffolded.

Linux Aliases

Aliases that have either:

  • Only been tested on Linux

  • Only natively exist on Linux

  • Clobber an existing Windows command

    • cmd has a few overlapping commands like find.

    • powershell intentionally has many aliases that match busybox aliases, with commands like ls and curl already mapped to pwsh builtins.

Packages such as ConEmu or Cmder allow a large number of GNU/Linux built-ins to exist on Windows, and as a result, the list may not be comprehensive and it may be that a reasonable portion of these aliases can be successfully executed from a shell such as Cygwin, MSys2, MinGW, Git on Windows or the Windows Subsystem for Linux.

Whitespace in Aliases

In order to make new subcommands in a way similar to how git allows one to come up with aliases, I first tried using whitespace in the alias.

(‘git last’, ‘git log -1 HEAD %l’)

However that simply registers the word git as an alias and then sends git last to the underlying shell, which it may or may not recognize.

Therefore I tried using a hyphen to separate the words, but the python interpreter uses hyphens as well as whitespace to separate keywords, and as a result, would split the alias in the middle of the command.

API Docs

validate_alias(alias)[source][source]

Ensure that the aliases are of the right form and correct type.

Ensures that %s and %l arguments aren’t mixed. Check attributes and formatting of Alias string. Verifies alias through the name and cmd attributes.

Parameters

alias (Alias) – alias to verify.

Return nargs

the validated alias

Rtype nargs

Alias

Raises

InvalidAliasError – On invalid aliases

class Alias(alias)[source][source]

After a sufficient amount of time, the definition of an alias needed to be built on, and a new alias class was defined in this module.

It is initialized with a mapping of ‘name’ to ‘cmds’.

class CommonAliases(dict=None)[source][source]

A dictionary mapping aliases to system commands, this class implements most of the functionality in the module.

git()[source][source]

100+ git aliases.

Aliases of note.

  • gcls: git clone [url]

    • This uses the %s argument to indicate it requires 1 and only 1 argument as git clone does

  • Note this is in contrast to gcl, or git clone, as that can have additional options specified

  • gcim: git commit –message [message]

    • Also uses %s

Unless otherwise noted every alias uses %l to allow the user to specify any relevant options or flags on the command line as necessary.

Returns user_aliases

A list of tuples The format of IPython aliases got taken it’s logical conclusion and probably pushed a little further than that.

Autogenerated Documentation

As a product of running %rehashx the alias magic is unusable.

Therefore, we try to properly map aliases as dictionaries.

This implies adding enough dunders to the CommonAliases class constructed here that it appropriately follows the mapping protocol as specified in the Python Language Reference.

As stated in the language reference under Common Sequence Operations.:

Concatenating immutable sequences always results in a new object. This means that building up a sequence by repeated concatenation will have a quadratic runtime cost in the total sequence length. To get a linear runtime cost, you must switch to one of the alternatives below:

  • If concatenating tuple objects, extend a list instead.

validate_alias(alias) → Optional[Any][source][source]
class Alias(name: AnyStr, cmd: AnyStr, **kwargs: Optional[Dict])[source][source]

Bases: collections.UserDict

Callable object storing the details of one alias.

Reasonably this is the object that should be the UserDict. CommonAliases makes more sense as a list of dicts.

Instances are registered as magic functions to allow use of aliases.

blacklist : method

Previously a class attribute, the blacklist is now a property of an Alias.

__init__(name: AnyStr, cmd: AnyStr, **kwargs: Optional[Dict])[source][source]

Validate the alias, and return the number of arguments.

property shell[source][source]
property blacklist[source][source]

Override the super classes blacklist. The reset magic no longer works.

We change prompt_toolkit properties and don’t reset them with that magic, so it expects the interface to continue existing.

class CommonAliases(user_aliases=None, **kwargs)[source][source]

Bases: collections.UserDict

Aliases that are usable on any major platform.

Aliases are added by calling the update() method which will add aliases to the attribute dict_aliases.

In addition, note that the definition for updating indicates that the class updates aliases and will add other instances.

shell = None[source]
__init__(user_aliases=None, **kwargs)[source][source]

OS Agnostic aliases.

Parameters

user_aliases (list of ('alias', 'system command') tuples) – User aliases to add the user’s namespace.

property alias_manager[source][source]

The ‘alias_manager’ attribute of InteractiveShell.

define_alias(name, cmd)[source][source]

Define a new alias.

Examples

In [54]: pkg?
Repr: <alias pkg for 'pkg'>
In [55]: aliases + ('pkg', 'pkg list-a')
In [56]: pkg?
Repr: <alias pkg for 'pkg list-a'>
is_alias(name)[source][source]

Return bool verifying if a name is defined in ‘dict_aliases.keys()’.

soft_define_alias(name, cmd)[source][source]

Define a new alias and don’t raise an error on an invalid alias.

undefine_alias(name)[source][source]

Override to raise AliasError not ValueError.

We’re not subclassing AliasManager here but still attempting to match it’s interface.

update(other, **kwargs)[source][source]

Update the mapping of aliases to system commands.

Ensure that this is properly defined as this can be critical for speed.

If a TypeError is raised by doing so then attempt to pass the alias along to the shell’s AliasManager with soft_define_alias.

Parameters
  • kwargs (dict) – Any keyword arguments to pass to the superclass.

  • other – Other object to update instance dict with.

keys()[source][source]
len()[source][source]
tuple_to_dict(list_of_tuples)[source][source]
unalias(alias)[source][source]

Remove an alias.

user_shell()[source][source]

Determine the user’s shell. Checks SHELL and COMSPEC.

python_exes()[source][source]

Python executables like pydoc get executed in a subprocess currently.

I want to do a check for if pydoc and apropos are in the aliases.

Todo

os.environ => env

git()[source][source]
ls_patch()[source][source]
class LinuxAliases(dict_aliases=None, *args, **kwargs)[source][source]

Bases: default_profile.startup.system_aliases.CommonAliases

Add Linux specific aliases.

__init__(dict_aliases=None, *args, **kwargs)[source][source]
busybox()[source][source]

Commands that are available on any Unix-ish system.

Returns

dict_aliases – User aliases to add the user’s namespace.

Return type

list of (‘alias’, ‘system command’) tuples

thirdparty()[source][source]

Contrasted to busybox, these require external installation.

As a result it’ll be of value to check that they’re even in the namespace.

class WindowsAliases(dict_aliases: Optional[Dict] = None, *args, **kwargs)[source][source]

Bases: default_profile.startup.system_aliases.CommonAliases

Aggregated Window aliases. Provides simplified system calls for NT.

Implements aliases specific to cmd or powershell.

Notes

Would it be useful to subclass reprlib.Repr here?

__init__(dict_aliases: Optional[Dict] = None, *args, **kwargs)[source][source]
cmd_aliases()[source][source]

Aliases for the cmd shell.

Todo

Cmd, COPYCMD and IPython

Need to consider how to handle env vars. Still working out how IPython’s logic for Window’s shells works, but that’ll determine how SHELL and COMSPEC are handled.

Note

Windows environment variables

However it’ll also take some consideration to figure out how to handle env vars like COPYCMD. Should we build them into the aliases we have here because that’ll affect _ip.dict_aliases.mv?

Also note DIRCMD for dir.

powershell_aliases()[source][source]

Aliases for Windows OSes using powershell.

Has only been tested on Windows 10 in a heavily configured environment.

Niceties such as Git for Windows, ag-silversearcher, ripgrep, ConEmu and others have been added.

The minimum number of assumptions possible have been made; however, note that this section is still under development and frequently changes.

generate_aliases() → Union[None, default_profile.startup.system_aliases.LinuxAliases, default_profile.startup.system_aliases.WindowsAliases][source][source]

Define aliases in case the user needs to redefine

Parameters

aliases (list of tuple) – Aliases to rerun. Can be easily generated from generate_aliases

Returns

Return type

None

Raises

traitlets.config.application.ApplicationError – Raises an ApplicationError if get_ipython returns an object that doesn’t have an attribute ‘alias_manager’.