rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
self.SendToRietveld('/%d/close' % self.issue, body, ctype)
self.SendToRietveld('/%d/close' % self.issue, payload=body, content_type=ctype)
def CloseIssue(self): """Closes the Rietveld issue for this changelist.""" data = [("description", self.description),] ctype, body = upload.EncodeMultipartFormData(data, []) self.SendToRietveld('/%d/close' % self.issue, body, ctype)
self.SendToRietveld('/%d/description' % self.issue, body, ctype)
self.SendToRietveld('/%d/description' % self.issue, payload=body, content_type=ctype)
def UpdateRietveldDescription(self): """Sets the description for an issue on Rietveld.""" data = [("description", self.description),] ctype, body = upload.EncodeMultipartFormData(data, []) self.SendToRietveld('/%d/description' % self.issue, body, ctype)
def SendToRietveld(self, request_path, payload=None, content_type="application/octet-stream", timeout=None):
def SendToRietveld(self, request_path, timeout=None, **kwargs):
def SendToRietveld(self, request_path, payload=None, content_type="application/octet-stream", timeout=None): """Send a POST/GET to Rietveld. Returns the response body.""" if not self.rietveld: ErrorExit(CODEREVIEW_SETTINGS_FILE_NOT_FOUND) def GetUserCredentials(): """Prompts the user for a username and password.""" em...
return rpc_server.Send(request_path, payload, content_type, timeout)
return rpc_server.Send(request_path, timeout=timeout, **kwargs)
def GetUserCredentials(): """Prompts the user for a username and password.""" email = upload.GetEmail('Email (login for uploading to %s)' % self.rietveld) password = getpass.getpass('Password for %s: ' % email) return email, password
match = re.search(r'revision (\d+).', out)
last_line = out.splitlines()[-1] match = re.search(r'(\d+)', out)
def commit_svn(repo): """Commits the changes and returns the new revision number.""" to_add = [] to_remove = [] for status, filepath in scm.SVN.CaptureStatus(repo): if status[0] == '?': to_add.append(filepath) elif status[0] == '!': to_remove.append(filepath) if to_add: check_call(['svn', 'add', '--no-auto-props', '-q'...
description = m.group(2)
def __init__(self, commit=None, upstream_branch=None): self.commit = commit self.verbose = None self.default_presubmit = None self.may_prompt = None
elif options.issue:
elif options.issue and options.patchset is None:
def TryChange(argv, file_list, swallow_exception, prog=None): """ Args: argv: Arguments and options. file_list: Default value to pass to --file. swallow_exception: Whether we raise or swallow exceptions. """ # Parse argv parser = optparse.OptionParser(usage=USAGE, version=__version__, prog=prog) parser.add_option("-v",...
if len(args) == 1 and args[0] == 'help':
if len(args) == 2 and args[1] == 'help':
def WebKitRevision(options, opt, value, parser): if not hasattr(options, 'sub_rep'): options.sub_rep = [] if parser.rargs and not parser.rargs[0].startswith('-'): options.sub_rep.append('third_party/WebKit@%s' % parser.rargs.pop(0)) else: options.sub_rep.append('third_party/WebKit')
if not len(ref) == 1: raise Exception('Failed to find one reference to %s. %s' % ( url.module_name, ref))
if not ref: raise gclient_utils.Error('Failed to find one reference to %s. %s' % ( url.module_name, ref))
def LateOverride(self, url): """Resolves the parsed url from url.
raise Exception('Couldn\'t find %s in %s, referenced by %s' % (
raise gclient_utils.Error( 'Couldn\'t find %s in %s, referenced by %s' % (
def LateOverride(self, url): """Resolves the parsed url from url.
'deps_hooks', '_file_list'):
'deps_hooks', '_file_list', 'processed', 'hooks_ran'):
def __str__(self): out = [] for i in ('name', 'url', 'safesync_url', 'custom_deps', 'custom_vars', 'deps_hooks', '_file_list'): # 'deps_file' if self.__dict__[i]: out.append('%s: %s' % (i, self.__dict__[i]))
['config', 'branch.%s.merge' % branch], error_ok=True)[0].strip()
['config', 'branch.%s.merge' % branch], in_directory=cwd, error_ok=True)[0].strip()
def FetchUpstreamTuple(cwd): """Returns a tuple containg remote and remote ref, e.g. 'origin', 'refs/heads/master' """ remote = '.' branch = GIT.GetBranch(cwd) upstream_branch = None upstream_branch = GIT.Capture( ['config', 'branch.%s.merge' % branch], error_ok=True)[0].strip() if upstream_branch: remote = GIT.Capture...
error_ok=True)[0].strip()
in_directory=cwd, error_ok=True)[0].strip()
def FetchUpstreamTuple(cwd): """Returns a tuple containg remote and remote ref, e.g. 'origin', 'refs/heads/master' """ remote = '.' branch = GIT.GetBranch(cwd) upstream_branch = None upstream_branch = GIT.Capture( ['config', 'branch.%s.merge' % branch], error_ok=True)[0].strip() if upstream_branch: remote = GIT.Capture...
if not upstream_branch: GIT.Capture(['branch', '-r'])[0].split().count('origin/master') remote = 'origin' upstream_branch = 'refs/heads/master'
def FetchUpstreamTuple(cwd): """Returns a tuple containg remote and remote ref, e.g. 'origin', 'refs/heads/master' """ remote = '.' branch = GIT.GetBranch(cwd) upstream_branch = None upstream_branch = GIT.Capture( ['config', 'branch.%s.merge' % branch], error_ok=True)[0].strip() if upstream_branch: remote = GIT.Capture...
def __init__(self, test_case, verbose=False, revision=None):
def __init__(self, verbose=False, revision=None):
def __init__(self, test_case, verbose=False, revision=None): self.verbose = verbose self.revision = revision self.manually_grab_svn_rev = True self.deps_os = None self.force = False self.reset = False self.nohooks = False self.stdout = gclient_scm.sys.stdout
return self.OptionsObject(self, *args, **kwargs)
return self.OptionsObject(*args, **kwargs)
def Options(self, *args, **kwargs): return self.OptionsObject(self, *args, **kwargs)
logging.warning('Sending by HTTP')
logging.info('Sending by HTTP')
def _SendChangeHTTP(options): """Send a change to the try server using the HTTP protocol.""" if not options.host: raise NoTryServerAccess('Please use the --host option to specify the try ' 'server host to connect to.') if not options.port: raise NoTryServerAccess('Please use the --port option to specify the try ' 'serv...
logging.warning('Sending by SVN')
logging.info('Sending by SVN')
def _SendChangeSVN(options): """Send a change to the try server by committing a diff file on a subversion server.""" if not options.svn_repo: raise NoTryServerAccess('Please use the --svn_repo option to specify the' ' try server svn repository to connect to.') values = _ParseSendChangeOptions(options) description = ''...
log = "" pos = 0 for line in svn_log: if (pos > 2): log += line.replace('-','').replace('\r','') else: pos = pos + 1 return log
return ''.join([l.replace('\r','') for l in svn_log[3:-1]])
def getRevisionLog(url, revision): """Takes an svn url and gets the associated revision.""" command = 'svn log ' + url + " -r"+str(revision) svn_log = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.readlines() log = "" pos = 0 for line in svn_log: if (pos > 2): log += line....
out.write("TBR=" + author)
out.write("\nTBR=" + author)
def main(options, args): revision = options.revert or options.merge # Initialize some variables used below. They can be overwritten by # the drover.properties file. BASE_URL = "svn://svn.chromium.org/chrome" TRUNK_URL = BASE_URL + "/trunk/src" BRANCH_URL = BASE_URL + "/branches/$branch/src" SKIP_CHECK_WORKING = True P...
parser.add_option('-j', '--jobs', default=8, type='int',
parser.add_option('-j', '--jobs', default=1, type='int',
def Main(argv): """Doesn't parse the arguments here, just find the right subcommand to execute.""" try: # Do it late so all commands are listed. CMDhelp.usage = ('\n\nCommands are:\n' + '\n'.join([ ' %-10s %s' % (fn[3:], Command(fn[3:]).__doc__.split('\n')[0].strip()) for fn in dir(sys.modules[__name__]) if fn.startsw...
for filename in os.listdir(unicode(GetInfoDir())): file_path = os.path.join(unicode(GetInfoDir()), filename) if os.path.isfile(file_path) and filename != CODEREVIEW_SETTINGS_FILE: shutil.move(file_path, GetChangesDir())
def main(argv=None): if argv is None: argv = sys.argv if len(argv) == 1: Help() return 0; try: # Create the directories where we store information about changelists if it # doesn't exist. if not os.path.exists(GetInfoDir()): os.mkdir(GetInfoDir()) if not os.path.exists(GetChangesDir()): os.mkdir(GetChangesDir()) # Fo...
help="Update rietveld issue try job status")
help="Update rietveld issue try job status. This is " "optional if --issue is used, In that case, the " "latest patchset will be used.")
def TryChange(argv, file_list, swallow_exception, prog=None): """ Args: argv: Arguments and options. file_list: Default value to pass to --file. swallow_exception: Whether we raise or swallow exceptions. """ # Parse argv parser = optparse.OptionParser(usage=USAGE, version=__version__, prog=prog) parser.add_option("-v",...
group.add_option("--rietveld_url", help="The code review url.")
group.add_option("-R", "--rietveld_url", default="codereview.appspot.com", metavar="URL", help="The root code review url. Default:%default")
def TryChange(argv, file_list, swallow_exception, prog=None): """ Args: argv: Arguments and options. file_list: Default value to pass to --file. swallow_exception: Whether we raise or swallow exceptions. """ # Parse argv parser = optparse.OptionParser(usage=USAGE, version=__version__, prog=prog) parser.add_option("-v",...
api_url = 'http://%s/api/%d' % (options.rietveld_url, options.issue)
api_url = '%s/api/%d' % (options.rietveld_url, options.issue) logging.debug(api_url)
def TryChange(argv, file_list, swallow_exception, prog=None): """ Args: argv: Arguments and options. file_list: Default value to pass to --file. swallow_exception: Whether we raise or swallow exceptions. """ # Parse argv parser = optparse.OptionParser(usage=USAGE, version=__version__, prog=prog) parser.add_option("-v",...
diff_url = ('http://%s/download/issue%d_%d.diff' % (options.rietveld_url, options.issue, contents['patchsets'][-1]))
options.patchset = contents['patchsets'][-1] diff_url = ('%s/download/issue%d_%d.diff' % (options.rietveld_url, options.issue, options.patchset))
def TryChange(argv, file_list, swallow_exception, prog=None): """ Args: argv: Arguments and options. file_list: Default value to pass to --file. swallow_exception: Whether we raise or swallow exceptions. """ # Parse argv parser = optparse.OptionParser(usage=USAGE, version=__version__, prog=prog) parser.add_option("-v",...
if options.tests: values['tests'] = ','.join(options.tests)
if options.testfilter: values['testfilter'] = ','.join(options.testfilter)
def _ParseSendChangeOptions(options): """Parse common options passed to _SendChangeHTTP and _SendChangeSVN.""" values = {} if options.email: values['email'] = options.email values['user'] = options.user values['name'] = options.name if options.bot: values['bot'] = ','.join(options.bot) if options.revision: values['revi...
group.add_option("-t", "--tests", action="append", help=optparse.SUPPRESS_HELP)
group.add_option("-t", "--testfilter", action="append", help="Add a gtest_filter to a test. Use multiple times to " "specify filters for different tests. (i.e. " "--testfilter base_unittests:ThreadTest.* " "--testfilter ui_tests) If you specify any testfilters " "the test results will not be reported in rietveld and " ...
def TryChange(argv, file_list, swallow_exception, prog=None): """ Args: argv: Arguments and options. file_list: Default value to pass to --file. swallow_exception: Whether we raise or swallow exceptions. """ # Parse argv parser = optparse.OptionParser(usage=USAGE, version=__version__, prog=prog) parser.add_option("-v",...
def _GetAuthToken(self, email, password):
def _GetAuthToken(self, host, email, password):
def _GetAuthToken(self, email, password): """Uses ClientLogin to authenticate the user, returning an auth token.
if self.host.endswith(".google.com"):
if host.endswith(".google.com"):
def _GetAuthToken(self, email, password): """Uses ClientLogin to authenticate the user, returning an auth token.
auth_token = self._GetAuthToken(credentials[0], credentials[1])
auth_token = self._GetAuthToken(host, credentials[0], credentials[1])
def _Authenticate(self, host): """Authenticates the user.
args = ['cat', svn_path]
args = ['svn', 'cat', svn_path]
def GetCachedFile(filename, max_age=60*60*24*3, use_root=False): """Retrieves a file from the repository and caches it in GetCacheDir() for max_age seconds. use_root: If False, look up the arborescence for the first match, otherwise go directory to the root repository. Note: The cache will be inconsistent if the same...
def BackquoteAsInteger(cmd, cwd=None): """Like Backquote, but returns either an int or None."""
def ConvertToInteger(input): """Convert a string to integer, but returns either an int or None."""
def BackquoteAsInteger(cmd, cwd=None): """Like Backquote, but returns either an int or None.""" try: return int(Backquote(cmd, cwd)) except ValueError: return None
return int(Backquote(cmd, cwd)) except ValueError:
return int(input) except TypeError, ValueError:
def BackquoteAsInteger(cmd, cwd=None): """Like Backquote, but returns either an int or None.""" try: return int(Backquote(cmd, cwd)) except ValueError: return None
issue = BackquoteAsInteger(['git', 'cl', 'status', '--field=id']) patchset = BackquoteAsInteger(['git', 'cl', 'status', '--field=patch'])
cl = git_cl.Changelist() issue = ConvertToInteger(cl.GetIssue()) patchset = ConvertToInteger(cl.GetPatchset())
def __init__(self, commit=None, upstream_branch=None): self.commit = commit self.verbose = None self.default_presubmit = None self.may_prompt = None
if (os.path.exists(working)):
if (os.path.exists(working)) and not options.local:
def main(options, args): revision = options.revert or options.merge # Initialize some variables used below. They can be overwritten by # the drover.properties file. BASE_URL = "svn://svn.chromium.org/chrome" TRUNK_URL = BASE_URL + "/trunk/src" BRANCH_URL = BASE_URL + "/branches/$branch/src" SKIP_CHECK_WORKING = True P...
os.makedirs(working) os.chdir(working)
if not options.local: os.makedirs(working) os.chdir(working)
def main(options, args): revision = options.revert or options.merge # Initialize some variables used below. They can be overwritten by # the drover.properties file. BASE_URL = "svn://svn.chromium.org/chrome" TRUNK_URL = BASE_URL + "/trunk/src" BRANCH_URL = BASE_URL + "/branches/$branch/src" SKIP_CHECK_WORKING = True P...
branch_url = BRANCH_URL.replace("$branch", options.branch) checkoutRevision(url, revision, branch_url)
if not options.local: branch_url = BRANCH_URL.replace("$branch", options.branch) checkoutRevision(url, revision, branch_url)
def main(options, args): revision = options.revert or options.merge # Initialize some variables used below. They can be overwritten by # the drover.properties file. BASE_URL = "svn://svn.chromium.org/chrome" TRUNK_URL = BASE_URL + "/trunk/src" BRANCH_URL = BASE_URL + "/branches/$branch/src" SKIP_CHECK_WORKING = True P...
if options.merge and not options.branch: option_parser.error("--merge requires a --branch")
if options.merge and not options.branch and not options.local: option_parser.error("--merge requires either --branch or --local")
def main(options, args): revision = options.revert or options.merge # Initialize some variables used below. They can be overwritten by # the drover.properties file. BASE_URL = "svn://svn.chromium.org/chrome" TRUNK_URL = BASE_URL + "/trunk/src" BRANCH_URL = BASE_URL + "/branches/$branch/src" SKIP_CHECK_WORKING = True P...
class FakeRepos(object):
class FakeReposBase(object):
def commit_git(repo): """Commits the changes and returns the new hash.""" check_call(['git', 'add', '-A', '-f'], cwd=repo) check_call(['git', 'commit', '-q', '--message', 'foo'], cwd=repo) rev = Popen(['git', 'show-ref', '--head', 'HEAD'], cwd=repo).communicate()[0].split(' ', 1)[0] logging.debug('At revision %s' % rev...
And types of dependencies: Relative urls, Full urls, both svn and git."""
And types of dependencies: Relative urls, Full urls, both svn and git. populateSvn() and populateGit() need to be implemented by the subclass. """
def commit_git(repo): """Commits the changes and returns the new hash.""" check_call(['git', 'add', '-A', '-f'], cwd=repo) check_call(['git', 'commit', '-q', '--message', 'foo'], cwd=repo) rev = Popen(['git', 'show-ref', '--head', 'HEAD'], cwd=repo).communicate()[0].split(' ', 1)[0] logging.debug('At revision %s' % rev...
def setUpGIT(self): """Creates git repositories and start the servers.""" if self.gitdaemon: return True self.setUp() if sys.platform == 'win32': return False for repo in ['repo_%d' % r for r in range(1, 5)]: check_call(['git', 'init', '-q', join(self.git_root, repo)]) self.git_hashes[repo] = [None]
def populateGit(self):
def setUpGIT(self): """Creates git repositories and start the servers.""" if self.gitdaemon: return True self.setUp() if sys.platform == 'win32': return False for repo in ['repo_%d' % r for r in range(1, 5)]: check_call(['git', 'init', '-q', join(self.git_root, repo)]) self.git_hashes[repo] = [None]
cmd = ['git', 'daemon', '--export-all', '--base-path=' + self.repos_dir] if self.HOST == '127.0.0.1': cmd.append('--listen=127.0.0.1') logging.debug(cmd) self.gitdaemon = Popen(cmd, cwd=self.repos_dir) return True def _commit_svn(self, tree): self._genTree(self.svn_root, tree) commit_svn(self.svn_root) if self.svn_rev...
def setUpGIT(self): """Creates git repositories and start the servers.""" if self.gitdaemon: return True self.setUp() if sys.platform == 'win32': return False for repo in ['repo_%d' % r for r in range(1, 5)]: check_call(['git', 'init', '-q', join(self.git_root, repo)]) self.git_hashes[repo] = [None]
FakeReposTestBase.FAKE_REPOS = FakeRepos()
FakeReposTestBase.FAKE_REPOS = self.FAKE_REPOS_CLASS()
def __init__(self, *args, **kwargs): unittest.TestCase.__init__(self, *args, **kwargs) if not FakeReposTestBase.FAKE_REPOS: FakeReposTestBase.FAKE_REPOS = FakeRepos()
def CMDcommit(change_list, args):
def CMDcommit(change_info, args):
def CMDcommit(change_list, args): """Commits the changelist to the repository.""" if not change_info.GetFiles(): print "Nothing to commit, changelist is empty." return 1 if not OptionallyDoPresubmitChecks(change_info, True, args): return 1 # We face a problem with svn here: Let's say change 'bleh' modifies # svn:ignor...
option_parser.add_option("", "--verbose", action="store_true", default=False,
option_parser.add_option("-v", "--verbose", action="count", default=0,
def Main(argv): """Parse command line arguments and dispatch command.""" option_parser = optparse.OptionParser(usage=DEFAULT_USAGE_TEXT, version=__version__) option_parser.disable_interspersed_args() option_parser.add_option("", "--force", action="store_true", default=False, help=("(update/sync only) force update even...
if options.verbose:
if options.verbose > 1:
def Main(argv): """Parse command line arguments and dispatch command.""" option_parser = optparse.OptionParser(usage=DEFAULT_USAGE_TEXT, version=__version__) option_parser.disable_interspersed_args() option_parser.add_option("", "--force", action="store_true", default=False, help=("(update/sync only) force update even...
command = ['diff', '-p', '--no-prefix', branch + "..." + branch_head]
command = ['diff', '-p', '--no-prefix', '--no-ext-diff', branch + "..." + branch_head]
def GenerateDiff(cwd, branch=None, branch_head='HEAD', full_move=False, files=None): """Diffs against the upstream branch or optionally another branch.
def Popen(*args, **kwargs):
def Popen(args, **kwargs):
def Popen(*args, **kwargs): """Calls subprocess.Popen() with hacks to work around certain behaviors. Ensure English outpout for svn and make it work reliably on Windows. """ copied = False if not 'env' in kwargs: copied = True kwargs = kwargs.copy() # It's easier to parse the stdout if it is always in English. kwargs[...
copied = False
logging.debug(u'%s, cwd=%s' % (u' '.join(args), kwargs.get('cwd', '')))
def Popen(*args, **kwargs): """Calls subprocess.Popen() with hacks to work around certain behaviors. Ensure English outpout for svn and make it work reliably on Windows. """ copied = False if not 'env' in kwargs: copied = True kwargs = kwargs.copy() # It's easier to parse the stdout if it is always in English. kwargs[...
copied = True kwargs = kwargs.copy()
def Popen(*args, **kwargs): """Calls subprocess.Popen() with hacks to work around certain behaviors. Ensure English outpout for svn and make it work reliably on Windows. """ copied = False if not 'env' in kwargs: copied = True kwargs = kwargs.copy() # It's easier to parse the stdout if it is always in English. kwargs[...
if not copied: kwargs = kwargs.copy()
def Popen(*args, **kwargs): """Calls subprocess.Popen() with hacks to work around certain behaviors. Ensure English outpout for svn and make it work reliably on Windows. """ copied = False if not 'env' in kwargs: copied = True kwargs = kwargs.copy() # It's easier to parse the stdout if it is always in English. kwargs[...
return subprocess.Popen(*args, **kwargs)
return subprocess.Popen(args, **kwargs)
def Popen(*args, **kwargs): """Calls subprocess.Popen() with hacks to work around certain behaviors. Ensure English outpout for svn and make it work reliably on Windows. """ copied = False if not 'env' in kwargs: copied = True kwargs = kwargs.copy() # It's easier to parse the stdout if it is always in English. kwargs[...
logging.debug('%s, cwd=%s' % (str(command), str(cwd)))
def CheckCall(command, cwd=None, print_error=True): """Similar subprocess.check_call() but redirects stdout and returns (stdout, stderr). Works on python 2.4 """ logging.debug('%s, cwd=%s' % (str(command), str(cwd))) try: stderr = None if not print_error: stderr = subprocess.PIPE process = Popen(command, cwd=cwd, stdo...
logging.debug(args)
def CheckCallAndFilter(args, stdout=None, filter_fn=None, print_stdout=None, call_filter_on_first_line=False, **kwargs): """Runs a command and calls back a filter function if needed. Accepts all subprocess.Popen() parameters plus: print_stdout: If True, the command's stdout is forwarded to stdout. filter_fn: A functio...
help="Print info level logs (default).")
help="Print info level logs.")
def _GetOpener(self): """Returns an OpenerDirector that supports cookies and ignores redirects.
if len(out) > 1:
status, _ = out[0].split(' ', 1) if len(out) > 1 and status == "A":
def GetBaseFile(self, filename): # "hg status" and "hg cat" both take a path relative to the current subdir # rather than to the repo root, but "hg diff" has given us the full path # to the repo root. base_content = "" new_content = None is_binary = False oldrelpath = relpath = self._GetRelPath(filename) # "hg status -...
else: status, _ = out[0].split(' ', 1)
def GetBaseFile(self, filename): # "hg status" and "hg cat" both take a path relative to the current subdir # rather than to the repo root, but "hg diff" has given us the full path # to the repo root. base_content = "" new_content = None is_binary = False oldrelpath = relpath = self._GetRelPath(filename) # "hg status -...
subversion_config = os.path.expanduser("~/.subversion/config")
if os.name == 'nt': subversion_config = os.environ.get("APPDATA") + "\\Subversion\\config" else: subversion_config = os.path.expanduser("~/.subversion/config")
def LoadSubversionAutoProperties(): """Returns the content of [auto-props] section of Subversion's config file as a dictionary. Returns: A dictionary whose key-value pair corresponds the [auto-props] section's key-value pair. In following cases, returns empty dictionary: - config file doesn't exist, or - 'enable-auto-...
r".*\.c", r".*\.cc", r".*\.cpp", r".*\.h", r".*\.m", r".*\.mm", r".*\.inl", r".*\.asm", r".*\.hxx", r".*\.hpp",
r".*\.c$", r".*\.cc$", r".*\.cpp$", r".*\.h$", r".*\.m$", r".*\.mm$", r".*\.inl$", r".*\.asm$", r".*\.hxx$", r".*\.hpp$",
def __init__(self, *args, **kwargs): raise NotImplementedException() # TODO(joi) Implement.
r".*\.js", r".*\.py", r".*\.sh", r".*\.rb", r".*\.pl", r".*\.pm",
r".*\.js$", r".*\.py$", r".*\.sh$", r".*\.rb$", r".*\.pl$", r".*\.pm$",
def __init__(self, *args, **kwargs): raise NotImplementedException() # TODO(joi) Implement.
r"(^|.*[\\\/])[^.]+$",
r"(^|.*?[\\\/])[^.]+$",
def __init__(self, *args, **kwargs): raise NotImplementedException() # TODO(joi) Implement.
r".*\.java", r".*\.mk", r".*\.am",
r".*\.java$", r".*\.mk$", r".*\.am$",
def __init__(self, *args, **kwargs): raise NotImplementedException() # TODO(joi) Implement.
chromium_utils.RemoveDirectory(args[2])
gclient_utils.RemoveDirectory(args[2])
def CaptureMatchingLines(line): match = compiled_pattern.search(line) if match: file_list.append(match.group(1)) if line.startswith('svn: '): failure.append(line)
cl = git_cl.Changelist() issue = cl.GetIssue() patchset = cl.GetPatchset()
issue = BackquoteAsInteger(['git', 'cl', 'status', '--field=id']) patchset = BackquoteAsInteger(['git', 'cl', 'status', '--field=patch'])
def __init__(self, commit=None, upstream_branch=None): self.commit = commit self.verbose = None self.default_presubmit = None self.may_prompt = None
description = cl.GetDescription()
description = Backquote(['git', 'cl', 'status', '--field=desc'])
def __init__(self, commit=None, upstream_branch=None): self.commit = commit self.verbose = None self.default_presubmit = None self.may_prompt = None
def addKill(): """Add kill() method to subprocess.Popen for python <2.6""" if getattr(subprocess.Popen, 'kill', None): return if sys.platform.startswith('win'): def kill_win(process): import win32process return win32process.TerminateProcess(process._handle, -1) subprocess.kill = kill_win else: def kill_nix(process): im...
class GClientSmokeBase(unittest.TestCase): ROOT_DIR = os.path.join(TRIAL_DIR, 'smoke') def setUp(self): self.env = os.environ.copy() self.env['DEPOT_TOOLS_UPDATE'] = '0' self.root_dir = os.path.join(self.ROOT_DIR, self.id()) rmtree(self.root_dir) if not os.path.exists(self.ROOT_DIR): os.mkdir(self.ROOT_DIR) os.mkd...
def addKill(): """Add kill() method to subprocess.Popen for python <2.6""" if getattr(subprocess.Popen, 'kill', None): return if sys.platform.startswith('win'): def kill_win(process): import win32process return win32process.TerminateProcess(process._handle, -1) subprocess.kill = kill_win else: def kill_nix(process): im...
def rmtree(path): """Delete a directory.""" if os.path.exists(path): shutil.rmtree(path)
class GClientSmoke(GClientSmokeBase): def testCommands(self): """This test is to make sure no new command was added.""" result = self.gclient(['help']) self.assertEquals(3189, len(result[0])) self.assertEquals(0, len(result[1])) self.assertEquals(0, result[2]) def testNotConfigured(self): res = ("", "Error: client not...
def rmtree(path): """Delete a directory.""" if os.path.exists(path): shutil.rmtree(path)
def write(path, content): f = open(path, 'wb') f.write(content) f.close()
class GClientSmokeSync(GClientSmokeBase): """sync is the most important command. Hence test it more.""" def testSyncSvn(self): """Test pure gclient svn checkout, example of Chromium checkout""" self.gclient(['config', self.svn_base + 'trunk/src/']) results = self.gclient(['sync']) self.assertEquals(0, results[2]) resul...
def write(path, content): f = open(path, 'wb') f.write(content) f.close()
class FakeRepos(object): def __init__(self, trial_dir, leak, local_only): self.trial_dir = trial_dir self.repos_dir = os.path.join(self.trial_dir, 'repos') self.leak = leak self.local_only = local_only self.svnserve = [] self.gitdaemon = [] addKill() rmtree(self.trial_dir) os.mkdir(self.trial_dir) os.mkdir(self.repos_d...
class GClientSmokeRevert(GClientSmokeBase): """revert is the second most important command. Hence test it more.""" def setUp(self): GClientSmokeBase.setUp(self) self.gclient(['config', self.URL_BASE])
def write(path, content): f = open(path, 'wb') f.write(content) f.close()
self.setUpSVN() self.setUpGIT()
GClientSmokeBase.setUp(self) self.gclient(['config', self.URL_BASE])
def setUp(self): self.setUpSVN() self.setUpGIT()
def tearDown(self): for i in self.svnserve: i.kill() for i in self.gitdaemon: i.kill() if not self.leak: rmtree(self.trial_dir) def setUpSVN(self): """Creates subversion repositories and start the servers.""" assert not self.svnserve join = os.path.join root = join(self.repos_dir, 'svn') rmtree(root) subprocess.check_...
def tearDown(self): for i in self.svnserve: i.kill() for i in self.gitdaemon: i.kill() if not self.leak: rmtree(self.trial_dir)
fake = FakeRepos(os.path.dirname(os.path.abspath(__file__)), False)
fake = FakeRepos(TRIAL_DIR, SHOULD_LEAK, True)
def setUpGIT(self): """Creates git repositories and start the servers.""" assert not self.gitdaemon join = os.path.join root = join(self.repos_dir, 'git') rmtree(root) os.mkdir(root) # Repo 1 repo = join(root, 'repo_1') subprocess.check_call(['git', 'init', '-q', repo]) write(join(repo, 'DEPS'), """
sys.stdin.readline()
unittest.main()
def setUpGIT(self): """Creates git repositories and start the servers.""" assert not self.gitdaemon join = os.path.join root = join(self.repos_dir, 'git') rmtree(root) os.mkdir(root) # Repo 1 repo = join(root, 'repo_1') subprocess.check_call(['git', 'init', '-q', repo]) write(join(repo, 'DEPS'), """
for _ in range(10):
i = 0 while True: i += 1
def RunAndGetFileList(verbose, args, cwd, file_list, stdout=None): """Runs svn checkout, update, or status, output to stdout.
'FindGclientRoot', 'GetNamedNodeText', 'GetNodeNamedAttributeText', 'IsUsingGit', 'PathDifference', 'ParseXML', 'PrintableObject', 'RemoveDirectory', 'SplitUrlRevision', 'SubprocessCall', 'SubprocessCallAndFilter', 'errno', 'logging', 'os', 're', 'stat', 'subprocess', 'sys', 'time', 'xml',
'FindFileUpwards', 'FindGclientRoot', 'GetGClientRootAndEntries', 'GetNamedNodeText', 'GetNodeNamedAttributeText', 'IsUsingGit', 'PathDifference', 'ParseXML', 'PrintableObject', 'RemoveDirectory', 'SplitUrlRevision', 'SubprocessCall', 'SubprocessCallAndFilter', 'errno', 'logging', 'os', 're', 'stat', 'subprocess', 'sys...
def testMembersChanged(self): members = [ 'CheckCall', 'CheckCallError', 'Error', 'FileRead', 'FileWrite', 'FindGclientRoot', 'GetNamedNodeText', 'GetNodeNamedAttributeText', 'IsUsingGit', 'PathDifference', 'ParseXML', 'PrintableObject', 'RemoveDirectory', 'SplitUrlRevision', 'SubprocessCall', 'SubprocessCallAndFilter'...
group.add_option("--webkit", action="append_const", const="third_party/WebKit", dest="sub_rep", help="Shorthand for -s third_party/WebKit")
try: group.add_option("--webkit", action="append_const", const="third_party/WebKit", dest="sub_rep", help="Shorthand for -s third_party/WebKit") except optparse.OptionError: pass
def TryChange(argv, file_list, swallow_exception, prog=None): """ Args: argv: Arguments and options. file_list: Default value to pass to --file. swallow_exception: Whether we raise or swallow exceptions. """ # Parse argv parser = optparse.OptionParser(usage=USAGE, version=__version__, prog=prog) parser.add_option("-v",...
result[0:2] = '{ \''
result = '{ \'' + result[2:]
def _SaveEntries(self, entries): """Creates a .gclient_entries file to record the list of unique checkouts.
if self._options.snapshot: url = entries.pop(name)
def GetURLAndRev(name, original_url): if not original_url: return None url, _ = gclient_utils.SplitUrlRevision(original_url) scm = gclient_scm.CreateSCM(original_url, self.root_dir(), name) return '%s@%s' % (url, scm.revinfo(self._options, [], None))
command.extend(['--revision', str(revision)])
command.extend(['--revision', str(revision).strip()])
def update(self, options, args, file_list): """Runs svn to update or transparently checkout the working copy.
command.extend(['--revision', str(options.revision)])
command.extend(['--revision', str(options.revision).strip()])
def updatesingle(self, options, args, file_list): checkout_path = os.path.join(self._root_dir, self.relpath) filename = args.pop() if scm.SVN.AssertVersion("1.5")[0]: if not os.path.exists(os.path.join(checkout_path, '.svn')): # Create an empty checkout and then update the one file we want. Future # operations will on...
if input_api.re.match(closed, status):
if input_api.re.match(closed, status, input_api.re.IGNORECASE):
def CheckTreeIsOpen(input_api, output_api, url, closed): """Checks that an url's content doesn't match a regexp that would mean that the tree is closed.""" if not input_api.is_committing: return [] try: connection = input_api.urllib2.urlopen(url) status = connection.read() connection.close() if input_api.re.match(close...
if command in ('update', 'revert') and sys.stdout.isatty():
if (command in ('update', 'revert') and sys.stdout.isatty() and not self._options.verbose):
def RunOnDeps(self, command, args): """Runs a command on each dependency in a client and its dependencies.
data = "Index: %s\n" % filename
data = "Index: %s\n" % filename.replace(os.sep, '/')
def _DiffItemInternal(filename, info, bogus_dir, full_move=False, revision=None): """Grabs the diff data.""" command = ["diff", "--config-dir", bogus_dir, filename] if revision: command.extend(['--revision', revision]) data = None if SVN.IsMovedInfo(info): if full_move: if info.get("Node Kind") == "directory": # Things...
sp = subprocess.Popen(cmd, cwd=cwd, stdout=stdout) output = sp.communicate()[0]
logging.debug(cmd) try: sp = subprocess.Popen(cmd, cwd=cwd, stdout=stdout) output = sp.communicate()[0] except OSError: raise gclient_utils.Error("git command '%s' failed to run." % ' '.join(cmd) + "\nCheck that you have git installed.")
def _Run(self, args, cwd=None, checkrc=True, redirect_stdout=True): # TODO(maruel): Merge with Capture? if cwd is None: cwd = self.checkout_path stdout=None if redirect_stdout: stdout=subprocess.PIPE if cwd == None: cwd = self.checkout_path cmd = [self.COMMAND] cmd.extend(args) sp = subprocess.Popen(cmd, cwd=cwd, stdou...
print "Argument%s \"%s\" not understood" % (plural, " ".join(args[1:]))
print >> sys.stderr, ( 'Argument%s \"%s\" not understood' % (plural, ' '.join(args[1:])))
def TryChange(argv, file_list, swallow_exception, prog=None, extra_epilog=None): """ Args: argv: Arguments and options. file_list: Default value to pass to --file. swallow_exception: Whether we raise or swallow exceptions. """ # Parse argv parser = optparse.OptionParser(usage=USAGE, version=__version__, prog=prog) epil...
print e
print >> sys.stderr, e return 1 except gclient_utils.Error, e: print >> sys.stderr, e
def TryChange(argv, file_list, swallow_exception, prog=None, extra_epilog=None): """ Args: argv: Arguments and options. file_list: Default value to pass to --file. swallow_exception: Whether we raise or swallow exceptions. """ # Parse argv parser = optparse.OptionParser(usage=USAGE, version=__version__, prog=prog) epil...
if not argv: argv = ['help'] command = Command(argv[0])
def main(argv): try: GetRepositoryRoot() except gclient_utils.Error: print('To use gcl, you need to be in a subversion checkout.') return 1 # Create the directories where we store information about changelists if it # doesn't exist. if not os.path.exists(GetInfoDir()): os.mkdir(GetInfoDir()) if not os.path.exists(GetC...
root = os.path.abspath(self.gclient_root)
def ReadRootFile(self, filename): if not self.options.root: filepath = os.path.join(self.checkout_root, filename) if os.path.isfile(filepath): logging.info('Found %s at %s' % (filename, self.checkout_root)) return gclient_util.FileRead(filepath) return None root = os.path.abspath(self.gclient_root) cur = os.path.abspat...
ErrorExit("Changelist file %s is corrupt" % info_file)
ErrorExit( ('Changelist file %s is corrupt.\n' 'Either run "gcl delete %s" or manually edit the file') % ( info_file, changename))
def Load(changename, local_root, fail_on_not_found, update_status): """Gets information about a changelist.
for item in files:
for item in files[:]:
def Load(changename, local_root, fail_on_not_found, update_status): """Gets information about a changelist.
@need_change def CMDdelete(change_info):
def CMDdelete(args):
def CMDdescription(change_info): """Prints the description of the specified change to stdout.""" print change_info.description return 0
change_info.Delete()
if not len(args) == 1: ErrorExit('You need to pass a change list name') os.remove(GetChangelistInfoFile(args[0]))
def CMDdelete(change_info): """Deletes a changelist.""" change_info.Delete() return 0
self._Run(['prune'], redirect_stdout=False) self._Run(['fsck'], redirect_stdout=False) self._Run(['gc'], redirect_stdout=False)
def cleanup(self, options, args, file_list): """Cleanup working copy.""" __pychecker__ = 'unusednames=options,args,file_list' self._Run(['prune'], redirect_stdout=False) self._Run(['fsck'], redirect_stdout=False) self._Run(['gc'], redirect_stdout=False)
if rev_type == "branch": remote_output, remote_err = scm.GIT.Capture( ['fetch'] + verbose + ['origin', revision], self.checkout_path, print_error=False) else: remote_output, remote_err = scm.GIT.Capture(
remote_output, remote_err = scm.GIT.Capture(
def update(self, options, args, file_list): """Runs git to update or transparently checkout the working copy.
"Returns a human-readable hierarchical reference to a Dependency."
def hierarchy(self): "Returns a human-readable hierarchical reference to a Dependency." out = '%s(%s)' % (self.name, self.url) i = self.parent while i and i.name: out = '%s(%s) -> %s' % (i.name, i.url, out) i = i.parent return out
print('To use gcl, you need to be in a subversion checkout.')
print >> sys.stderr, 'To use gcl, you need to be in a subversion checkout.'
def main(argv): if not argv: argv = ['help'] command = Command(argv[0]) # Help can be run from anywhere. if command == CMDhelp: return command(argv[1:]) try: GetRepositoryRoot() except gclient_utils.Error: print('To use gcl, you need to be in a subversion checkout.') return 1 # Create the directories where we store i...
print('Got an exception') print(str(e))
print >> sys.stderr, 'Got an exception' print >> sys.stderr, str(e) return 1 except urllib2.HTTPError, e: if e.code != 500: raise print >> sys.stderr, ( 'AppEngine is misbehaving and returned HTTP %d, again. Keep faith ' 'and retry or visit go/isgaeup.\n%s') % (e.code, e.reason) return 1
def main(argv): if not argv: argv = ['help'] command = Command(argv[0]) # Help can be run from anywhere. if command == CMDhelp: return command(argv[1:]) try: GetRepositoryRoot() except gclient_utils.Error: print('To use gcl, you need to be in a subversion checkout.') return 1 # Create the directories where we store i...
checkouts.append(GuessVCS(options, os.getcwd()))
path = os.getcwd() if options.upstream_branch: path += '@' + options.upstream_branch checkouts.append(GuessVCS(options, path))
def TryChange(argv, file_list, swallow_exception, prog=None, extra_epilog=None): """ Args: argv: Arguments and options. file_list: Default value to pass to --file. swallow_exception: Whether we raise or swallow exceptions. """ # Parse argv parser = optparse.OptionParser(usage=USAGE, version=__version__, prog=prog) epil...
SendStack(repr(last_value), ''.join(traceback.format_tb(last_tb)))
SendStack(last_value, ''.join(traceback.format_tb(last_tb)))
def CheckForException(): """Runs at exit. Look if there was an exception active.""" last_value = getattr(sys, 'last_value', None) if last_value and not isinstance(last_value, KeyboardInterrupt): last_tb = getattr(sys, 'last_traceback', None) if last_tb: SendStack(repr(last_value), ''.join(traceback.format_tb(last_tb)))...