Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/IPython/core/alias.py: 38%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""
2System command aliases.
4Authors:
6* Fernando Perez
7* Brian Granger
8"""
9from __future__ import annotations
11#-----------------------------------------------------------------------------
12# Copyright (C) 2008-2011 The IPython Development Team
13#
14# Distributed under the terms of the BSD License.
15#
16# The full license is in the file COPYING.txt, distributed with this software.
17#-----------------------------------------------------------------------------
19#-----------------------------------------------------------------------------
20# Imports
21#-----------------------------------------------------------------------------
23import os
24import re
25import sys
27from traitlets.config.configurable import Configurable
28from .error import UsageError
30from traitlets import List, Instance
33#-----------------------------------------------------------------------------
34# Utilities
35#-----------------------------------------------------------------------------
37# This is used as the pattern for calls to split_user_input.
38shell_line_split = re.compile(r'^(\s*)()(\S+)(.*$)')
40def default_aliases() -> list[tuple[str, str]]:
41 """Return list of shell aliases to auto-define.
42 """
43 # Note: the aliases defined here should be safe to use on a kernel
44 # regardless of what frontend it is attached to. Frontends that use a
45 # kernel in-process can define additional aliases that will only work in
46 # their case. For example, things like 'less' or 'clear' that manipulate
47 # the terminal should NOT be declared here, as they will only work if the
48 # kernel is running inside a true terminal, and not over the network.
50 if os.name == 'posix':
51 default_aliases = [('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
52 ('mv', 'mv'), ('rm', 'rm'), ('cp', 'cp'),
53 ('cat', 'cat'),
54 ]
55 # Useful set of ls aliases. The GNU and BSD options are a little
56 # different, so we make aliases that provide as similar as possible
57 # behavior in ipython, by passing the right flags for each platform
58 if sys.platform.startswith('linux'):
59 ls_aliases = [('ls', 'ls -F --color'),
60 # long ls
61 ('ll', 'ls -F -o --color'),
62 # ls normal files only
63 ('lf', 'ls -F -o --color %l | grep ^-'),
64 # ls symbolic links
65 ('lk', 'ls -F -o --color %l | grep ^l'),
66 # directories or links to directories,
67 ('ldir', 'ls -F -o --color %l | grep /$'),
68 # things which are executable
69 ('lx', 'ls -F -o --color %l | grep ^-..x'),
70 ]
71 elif sys.platform.startswith('openbsd') or sys.platform.startswith('netbsd'):
72 # OpenBSD, NetBSD. The ls implementation on these platforms do not support
73 # the -G switch and lack the ability to use colorized output.
74 ls_aliases = [('ls', 'ls -F'),
75 # long ls
76 ('ll', 'ls -F -l'),
77 # ls normal files only
78 ('lf', 'ls -F -l %l | grep ^-'),
79 # ls symbolic links
80 ('lk', 'ls -F -l %l | grep ^l'),
81 # directories or links to directories,
82 ('ldir', 'ls -F -l %l | grep /$'),
83 # things which are executable
84 ('lx', 'ls -F -l %l | grep ^-..x'),
85 ]
86 else:
87 # BSD, OSX, etc.
88 ls_aliases = [('ls', 'ls -F -G'),
89 # long ls
90 ('ll', 'ls -F -l -G'),
91 # ls normal files only
92 ('lf', 'ls -F -l -G %l | grep ^-'),
93 # ls symbolic links
94 ('lk', 'ls -F -l -G %l | grep ^l'),
95 # directories or links to directories,
96 ('ldir', 'ls -F -G -l %l | grep /$'),
97 # things which are executable
98 ('lx', 'ls -F -l -G %l | grep ^-..x'),
99 ]
100 default_aliases = default_aliases + ls_aliases
101 elif os.name in ['nt', 'dos']:
102 default_aliases = [('ls', 'dir /on'),
103 ('ddir', 'dir /ad /on'), ('ldir', 'dir /ad /on'),
104 ('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
105 ('echo', 'echo'), ('ren', 'ren'), ('copy', 'copy'),
106 ]
107 else:
108 default_aliases = []
110 return default_aliases
113class AliasError(Exception):
114 pass
117class InvalidAliasError(AliasError):
118 pass
121class Alias:
122 """Callable object storing the details of one alias.
124 Instances are registered as magic functions to allow use of aliases.
125 """
127 # Prepare blacklist
128 blacklist = {'cd','popd','pushd','dhist','alias','unalias'}
130 def __init__(self, shell, name, cmd):
131 self.shell = shell
132 self.name = name
133 self.cmd = cmd
134 self.__doc__ = f"Alias for `!{cmd}`"
135 self.nargs = self.validate()
137 def validate(self):
138 """Validate the alias, and return the number of arguments."""
139 if self.name in self.blacklist:
140 raise InvalidAliasError("The name %s can't be aliased "
141 "because it is a keyword or builtin." % self.name)
142 try:
143 caller = self.shell.magics_manager.magics['line'][self.name]
144 except KeyError:
145 pass
146 else:
147 if not isinstance(caller, Alias):
148 raise InvalidAliasError("The name %s can't be aliased "
149 "because it is another magic command." % self.name)
151 if not (isinstance(self.cmd, str)):
152 raise InvalidAliasError("An alias command must be a string, "
153 "got: %r" % self.cmd)
155 nargs = self.cmd.count('%s') - self.cmd.count('%%s')
157 if (nargs > 0) and (self.cmd.find('%l') >= 0):
158 raise InvalidAliasError('The %s and %l specifiers are mutually '
159 'exclusive in alias definitions.')
161 return nargs
163 def __repr__(self):
164 return f"<alias {self.name} for {self.cmd!r}>"
166 def __call__(self, rest=''):
167 cmd = self.cmd
168 nargs = self.nargs
169 # Expand the %l special to be the user's input line
170 if cmd.find('%l') >= 0:
171 cmd = cmd.replace('%l', rest)
172 rest = ''
174 if nargs==0:
175 if cmd.find('%%s') >= 1:
176 cmd = cmd.replace('%%s', '%s')
177 # Simple, argument-less aliases
178 cmd = '{} {}'.format(cmd, rest)
179 else:
180 # Handle aliases with positional arguments
181 args = rest.split(None, nargs)
182 if len(args) < nargs:
183 raise UsageError('Alias <%s> requires %s arguments, %s given.' %
184 (self.name, nargs, len(args)))
185 cmd = '{} {}'.format(cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
187 self.shell.system(cmd)
189#-----------------------------------------------------------------------------
190# Main AliasManager class
191#-----------------------------------------------------------------------------
193class AliasManager(Configurable):
194 default_aliases: List = List(default_aliases()).tag(config=True)
195 user_aliases: List = List(default_value=[]).tag(config=True)
196 shell = Instance(
197 "IPython.core.interactiveshell.InteractiveShellABC", allow_none=True
198 )
200 def __init__(self, shell=None, **kwargs):
201 super().__init__(shell=shell, **kwargs)
202 # For convenient access
203 if self.shell is not None:
204 self.linemagics = self.shell.magics_manager.magics["line"]
205 self.init_aliases()
207 def init_aliases(self):
208 # Load default & user aliases
209 for name, cmd in self.default_aliases + self.user_aliases:
210 if (
211 cmd.startswith("ls ")
212 and self.shell is not None
213 and self.shell.colors == "nocolor"
214 ):
215 cmd = cmd.replace(" --color", "")
216 self.soft_define_alias(name, cmd)
218 @property
219 def aliases(self) -> list:
220 return [(n, func.cmd) for (n, func) in self.linemagics.items()
221 if isinstance(func, Alias)]
223 def soft_define_alias(self, name, cmd):
224 """Define an alias, but don't raise on an AliasError."""
225 try:
226 self.define_alias(name, cmd)
227 except AliasError as e:
228 from logging import error
229 error("Invalid alias: %s" % e)
231 def define_alias(self, name, cmd):
232 """Define a new alias after validating it.
234 This will raise an :exc:`AliasError` if there are validation
235 problems.
236 """
237 caller = Alias(shell=self.shell, name=name, cmd=cmd)
238 self.shell.magics_manager.register_function(caller, magic_kind='line',
239 magic_name=name)
241 def get_alias(self, name):
242 """Return an alias, or None if no alias by that name exists."""
243 aname = self.linemagics.get(name, None)
244 return aname if isinstance(aname, Alias) else None
246 def is_alias(self, name):
247 """Return whether or not a given name has been defined as an alias"""
248 return self.get_alias(name) is not None
250 def undefine_alias(self, name):
251 if self.is_alias(name):
252 del self.linemagics[name]
253 else:
254 raise ValueError('%s is not an alias' % name)
256 def clear_aliases(self):
257 for name, _ in self.aliases:
258 self.undefine_alias(name)
260 def retrieve_alias(self, name):
261 """Retrieve the command to which an alias expands."""
262 caller = self.get_alias(name)
263 if caller:
264 return caller.cmd
265 else:
266 raise ValueError('%s is not an alias' % name)