Commit 9a2f37ea authored by maruel@chromium.org's avatar maruel@chromium.org

Remove trychange.RunCommand and replace it by gclient_utils.CheckCall.

TEST=unit tests

Review URL: http://codereview.chromium.org/502078

git-svn-id: svn://svn.chromium.org/chrome/trunk/tools/depot_tools@35052 0039d316-1c4b-4281-b951-d872f2087c98
parent 461843e2
...@@ -25,6 +25,30 @@ import xml.dom.minidom ...@@ -25,6 +25,30 @@ import xml.dom.minidom
import xml.parsers.expat import xml.parsers.expat
class CheckCallError(OSError):
"""CheckCall() returned non-0."""
def __init__(self, command, cwd, retcode, stdout):
OSError.__init__(self, command, cwd, retcode, stdout)
self.command = command
self.cwd = cwd
self.retcode = retcode
self.stdout = stdout
def CheckCall(command, cwd=None):
"""Like subprocess.check_call() but returns stdout.
Works on python 2.4
"""
process = subprocess.Popen(command, cwd=cwd,
shell=sys.platform.startswith('win'),
stdout=subprocess.PIPE)
output = process.communicate()[0]
if process.retcode:
raise CheckCallError(command, cwd, process.retcode, output)
return output
def SplitUrlRevision(url): def SplitUrlRevision(url):
"""Splits url and returns a two-tuple: url, rev""" """Splits url and returns a two-tuple: url, rev"""
if url.startswith('ssh:'): if url.startswith('ssh:'):
......
...@@ -9,6 +9,55 @@ import StringIO ...@@ -9,6 +9,55 @@ import StringIO
import gclient_utils import gclient_utils
from super_mox import SuperMoxTestBase from super_mox import SuperMoxTestBase
class GclientUtilsUnittest(SuperMoxTestBase):
"""General gclient_utils.py tests."""
def testMembersChanged(self):
members = [
'CheckCall', 'CheckCallError', 'Error', 'FileRead', 'FileWrite',
'FullUrlFromRelative', 'FullUrlFromRelative2', 'GetNamedNodeText',
'GetNodeNamedAttributeText', 'IsUsingGit', 'ParseXML',
'PrintableObject', 'RemoveDirectory', 'SplitUrlRevision',
'SubprocessCall', 'SubprocessCallAndFilter', 'errno', 'os', 're',
'stat', 'subprocess', 'sys', 'time', 'xml',
]
# If this test fails, you should add the relevant test.
self.compareMembers(gclient_utils, members)
class CheckCallTestCase(SuperMoxTestBase):
def testCheckCallSuccess(self):
command = ['boo', 'foo', 'bar']
process = self.mox.CreateMockAnything()
process.retcode = 0
gclient_utils.subprocess.Popen(
command, cwd=None,
stdout=gclient_utils.subprocess.PIPE,
shell=gclient_utils.sys.platform.startswith('win')).AndReturn(process)
process.communicate().AndReturn(['bleh'])
self.mox.ReplayAll()
gclient_utils.CheckCall(command)
def testCheckCallFailure(self):
command = ['boo', 'foo', 'bar']
process = self.mox.CreateMockAnything()
process.retcode = 42
gclient_utils.subprocess.Popen(
command, cwd=None,
stdout=gclient_utils.subprocess.PIPE,
shell=gclient_utils.sys.platform.startswith('win')).AndReturn(process)
process.communicate().AndReturn(['bleh'])
self.mox.ReplayAll()
try:
gclient_utils.CheckCall(command)
self.fail()
except gclient_utils.CheckCallError, e:
self.assertEqual(e.command, command)
self.assertEqual(e.cwd, None)
self.assertEqual(e.retcode, 42)
self.assertEqual(e.stdout, 'bleh')
class SubprocessCallAndFilterTestCase(SuperMoxTestBase): class SubprocessCallAndFilterTestCase(SuperMoxTestBase):
def testSubprocessCallAndFilter(self): def testSubprocessCallAndFilter(self):
command = ['boo', 'foo', 'bar'] command = ['boo', 'foo', 'bar']
......
...@@ -24,8 +24,8 @@ class TryChangeUnittest(TryChangeTestsBase): ...@@ -24,8 +24,8 @@ class TryChangeUnittest(TryChangeTestsBase):
'EscapeDot', 'GIT', 'GetSourceRoot', 'EscapeDot', 'GIT', 'GetSourceRoot',
'GetTryServerSettings', 'GuessVCS', 'GetTryServerSettings', 'GuessVCS',
'HELP_STRING', 'InvalidScript', 'NoTryServerAccess', 'PathDifference', 'HELP_STRING', 'InvalidScript', 'NoTryServerAccess', 'PathDifference',
'RunCommand', 'SCM', 'SVN', 'TryChange', 'USAGE', 'breakpad', 'SCM', 'SVN', 'TryChange', 'USAGE', 'breakpad',
'datetime', 'gcl', 'getpass', 'logging', 'datetime', 'gcl', 'gclient_utils', 'getpass', 'logging',
'optparse', 'os', 'presubmit_support', 'scm', 'shutil', 'socket', 'optparse', 'os', 'presubmit_support', 'scm', 'shutil', 'socket',
'subprocess', 'sys', 'tempfile', 'upload', 'urllib', 'subprocess', 'sys', 'tempfile', 'upload', 'urllib',
] ]
......
...@@ -22,6 +22,7 @@ import urllib ...@@ -22,6 +22,7 @@ import urllib
import breakpad import breakpad
import gcl import gcl
import gclient_utils
import scm import scm
import presubmit_support import presubmit_support
import upload import upload
...@@ -118,13 +119,6 @@ def EscapeDot(name): ...@@ -118,13 +119,6 @@ def EscapeDot(name):
return name.replace('.', '-') return name.replace('.', '-')
def RunCommand(command):
output, retcode = gcl.RunShellWithReturnCode(command)
if retcode:
raise NoTryServerAccess(' '.join(command) + '\nOuput:\n' + output)
return output
class SCM(object): class SCM(object):
"""Simplistic base class to implement one function: ProcessOptions.""" """Simplistic base class to implement one function: ProcessOptions."""
def __init__(self, options): def __init__(self, options):
...@@ -302,48 +296,47 @@ def _SendChangeSVN(options): ...@@ -302,48 +296,47 @@ def _SendChangeSVN(options):
# Do an empty checkout. # Do an empty checkout.
temp_dir = tempfile.mkdtemp() temp_dir = tempfile.mkdtemp()
temp_file = tempfile.NamedTemporaryFile() temp_file = tempfile.NamedTemporaryFile()
temp_file_name = temp_file.name
try: try:
# Don't use '--non-interactive', since we want it to prompt for
# crendentials if necessary.
command = ['svn', 'checkout', '--depth', 'empty', '-q',
options.svn_repo, temp_dir]
if options.email:
command += ['--username', options.email]
# Don't use RunCommand() since svn may prompt for information.
use_shell = sys.platform.startswith("win")
subprocess.Popen(command, shell=use_shell).communicate()
# TODO(maruel): Use a subdirectory per user?
current_time = str(datetime.datetime.now()).replace(':', '.')
file_name = (EscapeDot(options.user) + '.' + EscapeDot(options.name) +
'.%s.diff' % current_time)
full_path = os.path.join(temp_dir, file_name)
full_url = options.svn_repo + '/' + file_name
file_found = False
try: try:
RunCommand(['svn', 'ls', full_url]) command = ['svn', 'checkout', '--depth', 'empty', '-q',
file_found = True options.svn_repo, temp_dir]
except NoTryServerAccess: if options.email:
pass command += ['--username', options.email]
if file_found: gclient_utils.CheckCall(command)
# The file already exists in the repo. Note that commiting a file is a
# no-op if the file's content (the diff) is not modified. This is why the # TODO(maruel): Use a subdirectory per user?
# file name contains the date and time. current_time = str(datetime.datetime.now()).replace(':', '.')
RunCommand(['svn', 'update', full_path]) file_name = (EscapeDot(options.user) + '.' + EscapeDot(options.name) +
f = open(full_path, 'wb') '.%s.diff' % current_time)
f.write(options.diff) full_path = os.path.join(temp_dir, file_name)
f.close() full_url = options.svn_repo + '/' + file_name
else: file_found = False
# Add the file to the repo try:
f = open(full_path, 'wb') gclient_utils.CheckCall(['svn', 'ls', full_url])
f.write(options.diff) file_found = True
f.close() except gclient_utils.CheckCallError:
RunCommand(["svn", "add", full_path]) pass
temp_file.write(description) if file_found:
temp_file.flush() # The file already exists in the repo. Note that commiting a file is a
RunCommand(["svn", "commit", full_path, '--file', # no-op if the file's content (the diff) is not modified. This is why
temp_file_name]) # the file name contains the date and time.
gclient_utils.CheckCall(['svn', 'update', full_path])
f = open(full_path, 'wb')
f.write(options.diff)
f.close()
else:
# Add the file to the repo
f = open(full_path, 'wb')
f.write(options.diff)
f.close()
gclient_utils.CheckCall(["svn", "add", full_path])
temp_file.write(description)
temp_file.flush()
gclient_utils.CheckCall(["svn", "commit", full_path, '--file',
temp_file.name])
except gclient_utils.CheckCallError, e:
raise NoTryServerAccess(' '.join(e.command) + '\nOuput:\n' +
e.stdout)
finally: finally:
temp_file.close() temp_file.close()
shutil.rmtree(temp_dir, True) shutil.rmtree(temp_dir, True)
...@@ -371,8 +364,10 @@ def GuessVCS(options): ...@@ -371,8 +364,10 @@ def GuessVCS(options):
# Git has a command to test if you're in a git tree. # Git has a command to test if you're in a git tree.
# Try running it, but don't die if we don't have git installed. # Try running it, but don't die if we don't have git installed.
try: try:
out, returncode = gcl.RunShellWithReturnCode(["git", "rev-parse", out, returncode = subprocess.Popen(
"--is-inside-work-tree"]) ["git", "rev-parse", "--is-inside-work-tree"],
shell=sys.platform.startswith('win'),
stdout=subprocess.PIPE).communicate()[0]
if returncode == 0: if returncode == 0:
logging.info("Guessed VCS = Git") logging.info("Guessed VCS = Git")
return GIT(options) return GIT(options)
...@@ -520,7 +515,7 @@ def TryChange(argv, ...@@ -520,7 +515,7 @@ def TryChange(argv,
if options.url: if options.url:
options.diff = urllib.urlopen(options.url).read() options.diff = urllib.urlopen(options.url).read()
elif options.diff: elif options.diff:
options.diff = gcl.gclient_utils.FileRead(options.diff, 'rb') options.diff = gclient_utils.FileRead(options.diff, 'rb')
# Process the VCS in any case at least to retrieve the email address. # Process the VCS in any case at least to retrieve the email address.
try: try:
options.scm = GuessVCS(options) options.scm = GuessVCS(options)
......
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