Callable object storing the details of one alias. Instances are registered as magic functions to allow use of aliases.
| 122 | |
| 123 | |
| 124 | class Alias: |
| 125 | """Callable object storing the details of one alias. |
| 126 | |
| 127 | Instances are registered as magic functions to allow use of aliases. |
| 128 | """ |
| 129 | |
| 130 | # Prepare blacklist |
| 131 | blacklist = {'cd','popd','pushd','dhist','alias','unalias'} |
| 132 | |
| 133 | def __init__(self, shell, name, cmd): |
| 134 | self.shell = shell |
| 135 | self.name = name |
| 136 | self.cmd = cmd |
| 137 | self.__doc__ = "Alias for `!{}`".format(cmd) |
| 138 | self.nargs = self.validate() |
| 139 | |
| 140 | def validate(self): |
| 141 | """Validate the alias, and return the number of arguments.""" |
| 142 | if self.name in self.blacklist: |
| 143 | raise InvalidAliasError("The name %s can't be aliased " |
| 144 | "because it is a keyword or builtin." % self.name) |
| 145 | try: |
| 146 | caller = self.shell.magics_manager.magics['line'][self.name] |
| 147 | except KeyError: |
| 148 | pass |
| 149 | else: |
| 150 | if not isinstance(caller, Alias): |
| 151 | raise InvalidAliasError("The name %s can't be aliased " |
| 152 | "because it is another magic command." % self.name) |
| 153 | |
| 154 | if not (isinstance(self.cmd, str)): |
| 155 | raise InvalidAliasError("An alias command must be a string, " |
| 156 | "got: %r" % self.cmd) |
| 157 | |
| 158 | nargs = self.cmd.count('%s') - self.cmd.count('%%s') |
| 159 | |
| 160 | if (nargs > 0) and (self.cmd.find('%l') >= 0): |
| 161 | raise InvalidAliasError('The %s and %l specifiers are mutually ' |
| 162 | 'exclusive in alias definitions.') |
| 163 | |
| 164 | return nargs |
| 165 | |
| 166 | def __repr__(self): |
| 167 | return "<alias {} for {!r}>".format(self.name, self.cmd) |
| 168 | |
| 169 | def __call__(self, rest=''): |
| 170 | cmd = self.cmd |
| 171 | nargs = self.nargs |
| 172 | # Expand the %l special to be the user's input line |
| 173 | if cmd.find('%l') >= 0: |
| 174 | cmd = cmd.replace('%l', rest) |
| 175 | rest = '' |
| 176 | |
| 177 | if nargs==0: |
| 178 | if cmd.find('%%s') >= 1: |
| 179 | cmd = cmd.replace('%%s', '%s') |
| 180 | # Simple, argument-less aliases |
| 181 | cmd = '%s %s' % (cmd, rest) |
no outgoing calls
no test coverage detected
searching dependent graphs…