alias.py 2.3 KB

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