1
0

alias.py 2.4 KB

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