questions.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. """Functions to collect user input.
  2. """
  3. from milc import cli, format_ansi
  4. def yesno(prompt, *args, default=None, **kwargs):
  5. """Displays prompt to the user and gets a yes or no response.
  6. Returns True for a yes and False for a no.
  7. If you add `--yes` and `--no` arguments to your program the user can answer questions by passing command line flags.
  8. @add_argument('-y', '--yes', action='store_true', arg_only=True, help='Answer yes to all questions.')
  9. @add_argument('-n', '--no', action='store_true', arg_only=True, help='Answer no to all questions.')
  10. Arguments:
  11. prompt
  12. The prompt to present to the user. Can include ANSI and format strings like milc's `cli.echo()`.
  13. default
  14. Whether to default to a Yes or No when the user presses enter.
  15. None- force the user to enter Y or N
  16. True- Default to yes
  17. False- Default to no
  18. """
  19. if not args and kwargs:
  20. args = kwargs
  21. if 'no' in cli.args and cli.args.no:
  22. return False
  23. if 'yes' in cli.args and cli.args.yes:
  24. return True
  25. if default is not None:
  26. if default:
  27. prompt = prompt + ' [Y/n] '
  28. else:
  29. prompt = prompt + ' [y/N] '
  30. while True:
  31. cli.echo('')
  32. answer = input(format_ansi(prompt % args))
  33. cli.echo('')
  34. if not answer and prompt is not None:
  35. return default
  36. elif answer.lower() in ['y', 'yes']:
  37. return True
  38. elif answer.lower() in ['n', 'no']:
  39. return False
  40. def question(prompt, *args, default=None, confirm=False, answer_type=str, validate=None, **kwargs):
  41. """Prompt the user to answer a question with a free-form input.
  42. Arguments:
  43. prompt
  44. The prompt to present to the user. Can include ANSI and format strings like milc's `cli.echo()`.
  45. default
  46. The value to return when the user doesn't enter any value. Use None to prompt until they enter a value.
  47. confirm
  48. Present the user with a confirmation dialog before accepting their answer.
  49. answer_type
  50. Specify a type function for the answer. Will re-prompt the user if the function raises any errors. Common choices here include int, float, and decimal.Decimal.
  51. validate
  52. This is an optional function that can be used to validate the answer. It should return True or False and have the following signature:
  53. def function_name(answer, *args, **kwargs):
  54. """
  55. if not args and kwargs:
  56. args = kwargs
  57. if default is not None:
  58. prompt = '%s [%s] ' % (prompt, default)
  59. while True:
  60. cli.echo('')
  61. answer = input(format_ansi(prompt % args))
  62. cli.echo('')
  63. if answer:
  64. if validate is not None and not validate(answer, *args, **kwargs):
  65. continue
  66. elif confirm:
  67. if yesno('Is the answer "%s" correct?', answer, default=True):
  68. try:
  69. return answer_type(answer)
  70. except Exception as e:
  71. cli.log.error('Could not convert answer (%s) to type %s: %s', answer, answer_type.__name__, str(e))
  72. else:
  73. try:
  74. return answer_type(answer)
  75. except Exception as e:
  76. cli.log.error('Could not convert answer (%s) to type %s: %s', answer, answer_type.__name__, str(e))
  77. elif default is not None:
  78. return default
  79. def choice(heading, options, *args, default=None, confirm=False, prompt='Please enter your choice: ', **kwargs):
  80. """Present the user with a list of options and let them pick one.
  81. Users can enter either the number or the text of their choice.
  82. This will return the value of the item they choose, not the numerical index.
  83. Arguments:
  84. heading
  85. The text to place above the list of options.
  86. options
  87. A sequence of items to choose from.
  88. default
  89. The index of the item to return when the user doesn't enter any value. Use None to prompt until they enter a value.
  90. confirm
  91. Present the user with a confirmation dialog before accepting their answer.
  92. prompt
  93. The prompt to present to the user. Can include ANSI and format strings like milc's `cli.echo()`.
  94. """
  95. if not args and kwargs:
  96. args = kwargs
  97. if prompt and default:
  98. prompt = prompt + ' [%s] ' % (default + 1,)
  99. while True:
  100. # Prompt for an answer.
  101. cli.echo('')
  102. cli.echo(heading % args)
  103. cli.echo('')
  104. for i, option in enumerate(options, 1):
  105. cli.echo('\t{fg_cyan}%d.{fg_reset} %s', i, option)
  106. cli.echo('')
  107. answer = input(format_ansi(prompt))
  108. cli.echo('')
  109. # If the user types in one of the options exactly use that
  110. if answer in options:
  111. return answer
  112. # Massage the answer into a valid integer
  113. if answer == '' and default:
  114. answer = default
  115. else:
  116. try:
  117. answer = int(answer) - 1
  118. except Exception:
  119. # Normally we would log the exception here, but in the interest of clean UI we do not.
  120. cli.log.error('Invalid choice: %s', answer + 1)
  121. continue
  122. # Validate the answer
  123. if answer >= len(options) or answer < 0:
  124. cli.log.error('Invalid choice: %s', answer + 1)
  125. continue
  126. if confirm and not yesno('Is the answer "%s" correct?', answer + 1, default=True):
  127. continue
  128. # Return the answer they chose.
  129. return options[answer]