Commit ae3586b5 authored by Edward Lesmes's avatar Edward Lesmes Committed by LUCI CQ

depot_tools: Use gclient_utils.AskForData instead of raw_input.

gclient_utils.AskForData will use raw_input on Python 2 and input on Python 3.

Bug: 1063976
Change-Id: I93c059c4e4454d01787716b5a0a2641ad5253f53
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/2116370
Commit-Queue: Edward Lesmes <ehmaldonado@chromium.org>
Reviewed-by: 's avatarAnthony Polito <apolito@google.com>
Auto-Submit: Edward Lesmes <ehmaldonado@chromium.org>
parent 10d9c49f
......@@ -26,10 +26,7 @@ $VerifiedPlatform linux-mips64 linux-mips64le linux-mipsle
'''
# Timeout for a test to be executed.
TEST_TIMEOUT_S = 180 # 3m
# Tests take longer on Windows.
if sys.platform.startswith('win'):
TEST_TIMEOUT_S = 330 # 5m 30s
TEST_TIMEOUT_S = 330 # 5m 30s
......
......@@ -1081,11 +1081,7 @@ class GitWrapper(SCMWrapper):
raise gclient_utils.Error("Background task requires input. Rerun "
"gclient with --jobs=1 so that\n"
"interaction is possible.")
try:
return raw_input(prompt)
except KeyboardInterrupt:
# Hide the exception.
sys.exit(1)
return gclient_utils.AskForData(prompt)
def _AttemptRebase(self, upstream, files, options, newbase=None,
......
......@@ -158,6 +158,17 @@ class PrintableObject(object):
return output
def AskForData(message):
# Use this so that it can be mocked in tests on Python 2 and 3.
try:
if sys.version_info.major == 2:
return raw_input(message)
return input(message)
except KeyboardInterrupt:
# Hide the exception.
sys.exit(1)
def FileRead(filename, mode='rbU'):
# Always decodes output to a Unicode string.
# On Python 3 newlines are converted to '\n' by default and 'U' is deprecated.
......
......@@ -233,21 +233,6 @@ def datetime_now():
return datetime.datetime.now()
def _raw_input(message):
# Use this so that it can be mocked in tests on Python 2 and 3.
if sys.version_info.major == 2:
return raw_input(message)
return input(message)
def ask_for_data(prompt):
try:
return _raw_input(prompt)
except KeyboardInterrupt:
# Hide the exception.
sys.exit(1)
def confirm_or_exit(prefix='', action='confirm'):
"""Asks user to press enter to continue or press Ctrl+C to abort."""
if not prefix or prefix.endswith('\n'):
......@@ -258,18 +243,19 @@ def confirm_or_exit(prefix='', action='confirm'):
mid = 'press'
else:
mid = ' press'
ask_for_data('%s%s Enter to %s, or Ctrl+C to abort' % (prefix, mid, action))
gclient_utils.AskForData(
'%s%s Enter to %s, or Ctrl+C to abort' % (prefix, mid, action))
def ask_for_explicit_yes(prompt):
"""Returns whether user typed 'y' or 'yes' to confirm the given prompt."""
result = ask_for_data(prompt + ' [Yes/No]: ').lower()
result = gclient_utils.AskForData(prompt + ' [Yes/No]: ').lower()
while True:
if 'yes'.startswith(result):
return True
if 'no'.startswith(result):
return False
result = ask_for_data('Please, type yes or no: ').lower()
result = gclient_utils.AskForData('Please, type yes or no: ').lower()
def _git_branch_config_key(branch, key):
......@@ -1495,7 +1481,8 @@ class Changelist(object):
['show', '-s', '--format=%s', 'HEAD']).strip()
if options.force:
return title
return ask_for_data('Title for patchset [%s]: ' % title) or title
user_title = gclient_utils.AskForData('Title for patchset [%s]: ' % title)
return user_title or title
def CMDUpload(self, options, git_diff_args, orig_args):
"""Uploads a change to codereview."""
......@@ -3614,7 +3601,7 @@ def CMDarchive(parser, args):
current_branch)
return 1
elif not options.force:
answer = ask_for_data('\nProceed with deletion (Y/n)? ').lower()
answer = gclient_utils.AskForData('\nProceed with deletion (Y/n)? ').lower()
if answer not in ('y', ''):
print('Aborted.')
return 1
......@@ -5267,7 +5254,7 @@ def CMDcheckout(parser, args):
print('Multiple branches match issue %s:' % target_issue)
for i in range(len(branches)):
print('%d: %s' % (i, branches[i]))
which = ask_for_data('Choose by index: ')
which = gclient_utils.AskForData('Choose by index: ')
try:
RunGit(['checkout', branches[int(which)]])
except (IndexError, ValueError):
......
......@@ -17,6 +17,7 @@ import sys
import tempfile
import git_common
import gclient_utils
if sys.version_info.major == 2:
import cPickle
......@@ -70,12 +71,6 @@ else:
mk_symlink = os.symlink
def _raw_input(message):
# Use this so that it can be mocked in tests on Python 2 and 3.
if sys.version_info.major == 2:
return raw_input(message)
return input(message)
class _Drover(object):
def __init__(self, branch, revision, parent_repo, dry_run, verbose):
......@@ -192,7 +187,7 @@ class _Drover(object):
result = ''
while result not in ('y', 'n'):
try:
result = _raw_input('%s Continue (y/n)? ' % message)
result = gclient_utils.AskForData('%s Continue (y/n)? ' % message)
except EOFError:
result = 'n'
return result == 'y'
......
......@@ -14,6 +14,7 @@ from __future__ import print_function
import argparse
import sys
import gclient_utils
from git_common import current_branch, branches, upstream, run, hash_one
import metrics
......@@ -53,7 +54,7 @@ def main(args):
if r:
print(prompt + r)
else:
r = raw_input(prompt).strip() or '0'
r = gclient_utils.AskForData(prompt).strip() or '0'
if not r.isdigit() or (0 > int(r) > high):
print("Invalid choice.")
else:
......
......@@ -42,6 +42,7 @@ import re
import auth
import fix_encoding
import gclient_utils
import gerrit_util
......@@ -153,7 +154,7 @@ def get_week_of(date):
def get_yes_or_no(msg):
while True:
response = raw_input(msg + ' yes/no [no] ')
response = gclient_utils.AskForData(msg + ' yes/no [no] ')
if response == 'y' or response == 'yes':
return True
elif not response or response == 'n' or response == 'no':
......
......@@ -12,6 +12,9 @@ import owners as owners_module
import random
import gclient_utils
def first(iterable):
for element in iterable:
return element
......@@ -126,7 +129,7 @@ class OwnersFinder(object):
self.list_owners(self.owners_queue)
break
elif inp == 'p' or inp == 'pick':
self.pick_owner(raw_input('Pick an owner: '))
self.pick_owner(gclient_utils.AskForData('Pick an owner: '))
break
elif inp.startswith('p ') or inp.startswith('pick '):
self.pick_owner(inp.split(' ', 2)[1].strip())
......@@ -373,5 +376,5 @@ class OwnersFinder(object):
def input_command(self, owner):
self.writeln('Add ' + self.bold_name(owner) + ' as your reviewer? ')
return raw_input(
return gclient_utils.AskForData(
'[yes/no/Defer/pick/files/owners/quit/restart]: ').lower()
......@@ -233,7 +233,7 @@ def SplitCl(description_file, comment_file, changelist, cmd_upload, dry_run,
' infra-dev@chromium.org to ensure that this won\'t break anything.'
' The infra team reserves the right to cancel your jobs if they are'
' overloading the CQ.' % num_cls)
answer = raw_input('Proceed? (y/n):')
answer = gclient_utils.AskForData('Proceed? (y/n):')
if answer.lower() != 'y':
return 0
......
......@@ -1218,7 +1218,7 @@ class TestGitCl(unittest.TestCase):
mock.patch(
'git_cl.GenerateGerritChangeId', return_value=change_id).start()
mock.patch(
'git_cl.ask_for_data',
'gclient_utils.AskForData',
lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
self.mockGit.config['gerrit.host'] = 'true'
......@@ -1854,7 +1854,7 @@ class TestGitCl(unittest.TestCase):
def _test_gerrit_ensure_authenticated_common(self, auth):
mock.patch(
'git_cl.ask_for_data',
'gclient_utils.AskForData',
lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
CookiesAuthenticatorMockFactory(hosts_with_creds=auth)).start()
......@@ -2253,7 +2253,7 @@ class TestGitCl(unittest.TestCase):
'git_cl.gclient_utils.rm_file_or_tree',
lambda path: self._mocked_call(['rm_file_or_tree', path])).start()
mock.patch(
'git_cl.ask_for_data',
'gclient_utils.AskForData',
lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
return git_cl.Changelist(issue=123)
......@@ -2405,7 +2405,7 @@ class TestGitCl(unittest.TestCase):
# git cl also checks for existence other files not relevant to this test.
return None
mock.patch(
'git_cl.ask_for_data',
'gclient_utils.AskForData',
lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
mock.patch('os.path.exists', exists_mock).start()
......
......@@ -18,6 +18,7 @@ else:
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import gclient_utils
import git_drover
......@@ -39,7 +40,7 @@ class GitDroverTest(unittest.TestCase):
os.path.join(self._parent_repo, '.git', 'info', 'refs'), 'w') as f:
f.write('refs')
mock.patch('tempfile.mkdtemp', self._mkdtemp).start()
mock.patch('git_drover._raw_input', self._get_input).start()
mock.patch('gclient_utils.AskForData', self._get_input).start()
mock.patch('subprocess.check_call', self._check_call).start()
mock.patch('subprocess.check_output', self._check_call).start()
self.real_popen = subprocess.Popen
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment