1from distutils.errors import DistutilsOptionError 2 3from setuptools.extern.six.moves import map 4 5from setuptools.command.setopt import edit_config, option_base, config_file 6 7 8def shquote(arg): 9 """Quote an argument for later parsing by shlex.split()""" 10 for c in '"', "'", "\\", "#": 11 if c in arg: 12 return repr(arg) 13 if arg.split() != [arg]: 14 return repr(arg) 15 return arg 16 17 18class alias(option_base): 19 """Define a shortcut that invokes one or more commands""" 20 21 description = "define a shortcut to invoke one or more commands" 22 command_consumes_arguments = True 23 24 user_options = [ 25 ('remove', 'r', 'remove (unset) the alias'), 26 ] + option_base.user_options 27 28 boolean_options = option_base.boolean_options + ['remove'] 29 30 def initialize_options(self): 31 option_base.initialize_options(self) 32 self.args = None 33 self.remove = None 34 35 def finalize_options(self): 36 option_base.finalize_options(self) 37 if self.remove and len(self.args) != 1: 38 raise DistutilsOptionError( 39 "Must specify exactly one argument (the alias name) when " 40 "using --remove" 41 ) 42 43 def run(self): 44 aliases = self.distribution.get_option_dict('aliases') 45 46 if not self.args: 47 print("Command Aliases") 48 print("---------------") 49 for alias in aliases: 50 print("setup.py alias", format_alias(alias, aliases)) 51 return 52 53 elif len(self.args) == 1: 54 alias, = self.args 55 if self.remove: 56 command = None 57 elif alias in aliases: 58 print("setup.py alias", format_alias(alias, aliases)) 59 return 60 else: 61 print("No alias definition found for %r" % alias) 62 return 63 else: 64 alias = self.args[0] 65 command = ' '.join(map(shquote, self.args[1:])) 66 67 edit_config(self.filename, {'aliases': {alias: command}}, self.dry_run) 68 69 70def format_alias(name, aliases): 71 source, command = aliases[name] 72 if source == config_file('global'): 73 source = '--global-config ' 74 elif source == config_file('user'): 75 source = '--user-config ' 76 elif source == config_file('local'): 77 source = '' 78 else: 79 source = '--filename=%r' % source 80 return source + name + ' ' + command 81