body
stringlengths 26
98.2k
| body_hash
int64 -9,222,864,604,528,158,000
9,221,803,474B
| docstring
stringlengths 1
16.8k
| path
stringlengths 5
230
| name
stringlengths 1
96
| repository_name
stringlengths 7
89
| lang
stringclasses 1
value | body_without_docstring
stringlengths 20
98.2k
|
|---|---|---|---|---|---|---|---|
@subcommand.usage('[upstream branch to apply against]')
def CMDdcommit(parser, args):
'Commits the current changelist via git-svn.'
if (not settings.GetIsGitSvn()):
if git_footers.get_footer_svn_id():
message = "This repository appears to be a git-svn mirror, but no\nupstream SVN master is set. You probably need to run 'git auto-svn' once."
else:
message = "This doesn't appear to be an SVN repository.\nIf your project has a true, writeable git repository, you probably want to run\n'git cl land' instead.\nIf your project has a git mirror of an upstream SVN master, you probably need\nto run 'git svn init'.\n\nUsing the wrong command might cause your commit to appear to succeed, and the\nreview to be closed, without actually landing upstream. If you choose to\nproceed, please verify that the commit lands upstream as expected."
print(message)
ask_for_data('[Press enter to dcommit or ctrl-C to quit]')
print('WARNING: chrome infrastructure is migrating SVN repos to Git.\nPlease let us know of this project you are committing to: http://crbug.com/600451')
return SendUpstream(parser, args, 'dcommit')
| 5,863,675,845,697,642,000
|
Commits the current changelist via git-svn.
|
git_cl.py
|
CMDdcommit
|
wuyong2k/chromium_depot_tool
|
python
|
@subcommand.usage('[upstream branch to apply against]')
def CMDdcommit(parser, args):
if (not settings.GetIsGitSvn()):
if git_footers.get_footer_svn_id():
message = "This repository appears to be a git-svn mirror, but no\nupstream SVN master is set. You probably need to run 'git auto-svn' once."
else:
message = "This doesn't appear to be an SVN repository.\nIf your project has a true, writeable git repository, you probably want to run\n'git cl land' instead.\nIf your project has a git mirror of an upstream SVN master, you probably need\nto run 'git svn init'.\n\nUsing the wrong command might cause your commit to appear to succeed, and the\nreview to be closed, without actually landing upstream. If you choose to\nproceed, please verify that the commit lands upstream as expected."
print(message)
ask_for_data('[Press enter to dcommit or ctrl-C to quit]')
print('WARNING: chrome infrastructure is migrating SVN repos to Git.\nPlease let us know of this project you are committing to: http://crbug.com/600451')
return SendUpstream(parser, args, 'dcommit')
|
@subcommand.usage('[upstream branch to apply against]')
def CMDland(parser, args):
'Commits the current changelist via git.'
if (settings.GetIsGitSvn() or git_footers.get_footer_svn_id()):
print('This appears to be an SVN repository.')
print("Are you sure you didn't mean 'git cl dcommit'?")
print('(Ignore if this is the first commit after migrating from svn->git)')
ask_for_data('[Press enter to push or ctrl-C to quit]')
return SendUpstream(parser, args, 'land')
| -2,676,884,157,090,033,700
|
Commits the current changelist via git.
|
git_cl.py
|
CMDland
|
wuyong2k/chromium_depot_tool
|
python
|
@subcommand.usage('[upstream branch to apply against]')
def CMDland(parser, args):
if (settings.GetIsGitSvn() or git_footers.get_footer_svn_id()):
print('This appears to be an SVN repository.')
print("Are you sure you didn't mean 'git cl dcommit'?")
print('(Ignore if this is the first commit after migrating from svn->git)')
ask_for_data('[Press enter to push or ctrl-C to quit]')
return SendUpstream(parser, args, 'land')
|
@subcommand.usage('<patch url or issue id or issue url>')
def CMDpatch(parser, args):
'Patches in a code review.'
parser.add_option('-b', dest='newbranch', help='create a new branch off trunk for the patch')
parser.add_option('-f', '--force', action='store_true', help='with -b, clobber any existing branch')
parser.add_option('-d', '--directory', action='store', metavar='DIR', help='Change to the directory DIR immediately, before doing anything else. Rietveld only.')
parser.add_option('--reject', action='store_true', help='failed patches spew .rej files rather than attempting a 3-way merge. Rietveld only.')
parser.add_option('-n', '--no-commit', action='store_true', dest='nocommit', help="don't commit after patch applies. Rietveld only.")
group = optparse.OptionGroup(parser, 'Options for continuing work on the current issue uploaded from a different clone (e.g. different machine). Must be used independently from the other options. No issue number should be specified, and the branch must have an issue number associated with it')
group.add_option('--reapply', action='store_true', dest='reapply', help='Reset the branch and reapply the issue.\nCAUTION: This will undo any local changes in this branch')
group.add_option('--pull', action='store_true', dest='pull', help='Performs a pull before reapplying.')
parser.add_option_group(group)
auth.add_auth_options(parser)
_add_codereview_select_options(parser)
(options, args) = parser.parse_args(args)
_process_codereview_select_options(parser, options)
auth_config = auth.extract_auth_config_from_options(options)
if options.reapply:
if options.newbranch:
parser.error('--reapply works on the current branch only')
if (len(args) > 0):
parser.error('--reapply implies no additional arguments')
cl = Changelist(auth_config=auth_config, codereview=options.forced_codereview)
if (not cl.GetIssue()):
parser.error('current branch must have an associated issue')
upstream = cl.GetUpstreamBranch()
if (upstream == None):
parser.error('No upstream branch specified. Cannot reset branch')
RunGit(['reset', '--hard', upstream])
if options.pull:
RunGit(['pull'])
return cl.CMDPatchIssue(cl.GetIssue(), options.reject, options.nocommit, options.directory)
if ((len(args) != 1) or (not args[0])):
parser.error('Must specify issue number or url')
if git_common.is_dirty_git_tree('patch'):
return 1
if options.newbranch:
if options.force:
RunGit(['branch', '-D', options.newbranch], stderr=subprocess2.PIPE, error_ok=True)
RunGit(['new-branch', options.newbranch])
cl = Changelist(auth_config=auth_config, codereview=options.forced_codereview)
if cl.IsGerrit():
if options.reject:
parser.error('--reject is not supported with Gerrit codereview.')
if options.nocommit:
parser.error('--nocommit is not supported with Gerrit codereview.')
if options.directory:
parser.error('--directory is not supported with Gerrit codereview.')
return cl.CMDPatchIssue(args[0], options.reject, options.nocommit, options.directory)
| 7,364,788,965,587,228,000
|
Patches in a code review.
|
git_cl.py
|
CMDpatch
|
wuyong2k/chromium_depot_tool
|
python
|
@subcommand.usage('<patch url or issue id or issue url>')
def CMDpatch(parser, args):
parser.add_option('-b', dest='newbranch', help='create a new branch off trunk for the patch')
parser.add_option('-f', '--force', action='store_true', help='with -b, clobber any existing branch')
parser.add_option('-d', '--directory', action='store', metavar='DIR', help='Change to the directory DIR immediately, before doing anything else. Rietveld only.')
parser.add_option('--reject', action='store_true', help='failed patches spew .rej files rather than attempting a 3-way merge. Rietveld only.')
parser.add_option('-n', '--no-commit', action='store_true', dest='nocommit', help="don't commit after patch applies. Rietveld only.")
group = optparse.OptionGroup(parser, 'Options for continuing work on the current issue uploaded from a different clone (e.g. different machine). Must be used independently from the other options. No issue number should be specified, and the branch must have an issue number associated with it')
group.add_option('--reapply', action='store_true', dest='reapply', help='Reset the branch and reapply the issue.\nCAUTION: This will undo any local changes in this branch')
group.add_option('--pull', action='store_true', dest='pull', help='Performs a pull before reapplying.')
parser.add_option_group(group)
auth.add_auth_options(parser)
_add_codereview_select_options(parser)
(options, args) = parser.parse_args(args)
_process_codereview_select_options(parser, options)
auth_config = auth.extract_auth_config_from_options(options)
if options.reapply:
if options.newbranch:
parser.error('--reapply works on the current branch only')
if (len(args) > 0):
parser.error('--reapply implies no additional arguments')
cl = Changelist(auth_config=auth_config, codereview=options.forced_codereview)
if (not cl.GetIssue()):
parser.error('current branch must have an associated issue')
upstream = cl.GetUpstreamBranch()
if (upstream == None):
parser.error('No upstream branch specified. Cannot reset branch')
RunGit(['reset', '--hard', upstream])
if options.pull:
RunGit(['pull'])
return cl.CMDPatchIssue(cl.GetIssue(), options.reject, options.nocommit, options.directory)
if ((len(args) != 1) or (not args[0])):
parser.error('Must specify issue number or url')
if git_common.is_dirty_git_tree('patch'):
return 1
if options.newbranch:
if options.force:
RunGit(['branch', '-D', options.newbranch], stderr=subprocess2.PIPE, error_ok=True)
RunGit(['new-branch', options.newbranch])
cl = Changelist(auth_config=auth_config, codereview=options.forced_codereview)
if cl.IsGerrit():
if options.reject:
parser.error('--reject is not supported with Gerrit codereview.')
if options.nocommit:
parser.error('--nocommit is not supported with Gerrit codereview.')
if options.directory:
parser.error('--directory is not supported with Gerrit codereview.')
return cl.CMDPatchIssue(args[0], options.reject, options.nocommit, options.directory)
|
def CMDrebase(parser, args):
'Rebases current branch on top of svn repo.'
return RunGitWithCode((['svn', 'rebase'] + args))[1]
| 5,346,108,559,491,527,000
|
Rebases current branch on top of svn repo.
|
git_cl.py
|
CMDrebase
|
wuyong2k/chromium_depot_tool
|
python
|
def CMDrebase(parser, args):
return RunGitWithCode((['svn', 'rebase'] + args))[1]
|
def GetTreeStatus(url=None):
"Fetches the tree status and returns either 'open', 'closed',\n 'unknown' or 'unset'."
url = (url or settings.GetTreeStatusUrl(error_ok=True))
if url:
status = urllib2.urlopen(url).read().lower()
if ((status.find('closed') != (- 1)) or (status == '0')):
return 'closed'
elif ((status.find('open') != (- 1)) or (status == '1')):
return 'open'
return 'unknown'
return 'unset'
| 722,695,825,156,314,800
|
Fetches the tree status and returns either 'open', 'closed',
'unknown' or 'unset'.
|
git_cl.py
|
GetTreeStatus
|
wuyong2k/chromium_depot_tool
|
python
|
def GetTreeStatus(url=None):
"Fetches the tree status and returns either 'open', 'closed',\n 'unknown' or 'unset'."
url = (url or settings.GetTreeStatusUrl(error_ok=True))
if url:
status = urllib2.urlopen(url).read().lower()
if ((status.find('closed') != (- 1)) or (status == '0')):
return 'closed'
elif ((status.find('open') != (- 1)) or (status == '1')):
return 'open'
return 'unknown'
return 'unset'
|
def GetTreeStatusReason():
'Fetches the tree status from a json url and returns the message\n with the reason for the tree to be opened or closed.'
url = settings.GetTreeStatusUrl()
json_url = urlparse.urljoin(url, '/current?format=json')
connection = urllib2.urlopen(json_url)
status = json.loads(connection.read())
connection.close()
return status['message']
| 331,425,300,037,896,640
|
Fetches the tree status from a json url and returns the message
with the reason for the tree to be opened or closed.
|
git_cl.py
|
GetTreeStatusReason
|
wuyong2k/chromium_depot_tool
|
python
|
def GetTreeStatusReason():
'Fetches the tree status from a json url and returns the message\n with the reason for the tree to be opened or closed.'
url = settings.GetTreeStatusUrl()
json_url = urlparse.urljoin(url, '/current?format=json')
connection = urllib2.urlopen(json_url)
status = json.loads(connection.read())
connection.close()
return status['message']
|
def GetBuilderMaster(bot_list):
'For a given builder, fetch the master from AE if available.'
map_url = 'https://builders-map.appspot.com/'
try:
master_map = json.load(urllib2.urlopen(map_url))
except urllib2.URLError as e:
return (None, ('Failed to fetch builder-to-master map from %s. Error: %s.' % (map_url, e)))
except ValueError as e:
return (None, ('Invalid json string from %s. Error: %s.' % (map_url, e)))
if (not master_map):
return (None, 'Failed to build master map.')
result_master = ''
for bot in bot_list:
builder = bot.split(':', 1)[0]
master_list = master_map.get(builder, [])
if (not master_list):
return (None, ('No matching master for builder %s.' % builder))
elif (len(master_list) > 1):
return (None, ('The builder name %s exists in multiple masters %s.' % (builder, master_list)))
else:
cur_master = master_list[0]
if (not result_master):
result_master = cur_master
elif (result_master != cur_master):
return (None, 'The builders do not belong to the same master.')
return (result_master, None)
| 8,976,772,511,821,153,000
|
For a given builder, fetch the master from AE if available.
|
git_cl.py
|
GetBuilderMaster
|
wuyong2k/chromium_depot_tool
|
python
|
def GetBuilderMaster(bot_list):
map_url = 'https://builders-map.appspot.com/'
try:
master_map = json.load(urllib2.urlopen(map_url))
except urllib2.URLError as e:
return (None, ('Failed to fetch builder-to-master map from %s. Error: %s.' % (map_url, e)))
except ValueError as e:
return (None, ('Invalid json string from %s. Error: %s.' % (map_url, e)))
if (not master_map):
return (None, 'Failed to build master map.')
result_master =
for bot in bot_list:
builder = bot.split(':', 1)[0]
master_list = master_map.get(builder, [])
if (not master_list):
return (None, ('No matching master for builder %s.' % builder))
elif (len(master_list) > 1):
return (None, ('The builder name %s exists in multiple masters %s.' % (builder, master_list)))
else:
cur_master = master_list[0]
if (not result_master):
result_master = cur_master
elif (result_master != cur_master):
return (None, 'The builders do not belong to the same master.')
return (result_master, None)
|
def CMDtree(parser, args):
'Shows the status of the tree.'
(_, args) = parser.parse_args(args)
status = GetTreeStatus()
if ('unset' == status):
print('You must configure your tree status URL by running "git cl config".')
return 2
print(('The tree is %s' % status))
print()
print(GetTreeStatusReason())
if (status != 'open'):
return 1
return 0
| 3,916,277,630,828,864,500
|
Shows the status of the tree.
|
git_cl.py
|
CMDtree
|
wuyong2k/chromium_depot_tool
|
python
|
def CMDtree(parser, args):
(_, args) = parser.parse_args(args)
status = GetTreeStatus()
if ('unset' == status):
print('You must configure your tree status URL by running "git cl config".')
return 2
print(('The tree is %s' % status))
print()
print(GetTreeStatusReason())
if (status != 'open'):
return 1
return 0
|
def CMDtry(parser, args):
'Triggers try jobs through BuildBucket.'
group = optparse.OptionGroup(parser, 'Try job options')
group.add_option('-b', '--bot', action='append', help="IMPORTANT: specify ONE builder per --bot flag. Use it multiple times to specify multiple builders. ex: '-b win_rel -b win_layout'. See the try server waterfall for the builders name and the tests available.")
group.add_option('-m', '--master', default='', help='Specify a try master where to run the tries.')
group.add_option('--luci', action='store_true')
group.add_option('-r', '--revision', help='Revision to use for the try job; default: the revision will be determined by the try server; see its waterfall for more info')
group.add_option('-c', '--clobber', action='store_true', default=False, help="Force a clobber before building; e.g. don't do an incremental build")
group.add_option('--project', help='Override which project to use. Projects are defined server-side to define what default bot set to use')
group.add_option('-p', '--property', dest='properties', action='append', default=[], help='Specify generic properties in the form -p key1=value1 -p key2=value2 etc (buildbucket only). The value will be treated as json if decodable, or as string otherwise.')
group.add_option('-n', '--name', help='Try job name; default to current branch name')
group.add_option('--use-rietveld', action='store_true', default=False, help='Use Rietveld to trigger try jobs.')
group.add_option('--buildbucket-host', default='cr-buildbucket.appspot.com', help='Host of buildbucket. The default host is %default.')
parser.add_option_group(group)
auth.add_auth_options(parser)
(options, args) = parser.parse_args(args)
auth_config = auth.extract_auth_config_from_options(options)
if (options.use_rietveld and options.properties):
parser.error('Properties can only be specified with buildbucket')
bad_params = [x for x in options.properties if ('=' not in x)]
if bad_params:
parser.error(('Got properties with missing "=": %s' % bad_params))
if args:
parser.error(('Unknown arguments: %s' % args))
cl = Changelist(auth_config=auth_config)
if (not cl.GetIssue()):
parser.error('Need to upload first')
if cl.IsGerrit():
parser.error('Not yet supported for Gerrit (http://crbug.com/599931).\nIf your project has Commit Queue, dry run is a workaround:\n git cl set-commit --dry-run')
props = cl.GetIssueProperties()
if props.get('closed'):
parser.error('Cannot send tryjobs for a closed CL')
if props.get('private'):
parser.error('Cannot use trybots with private issue')
if (not options.name):
options.name = cl.GetBranch()
if (options.bot and (not options.master)):
(options.master, err_msg) = GetBuilderMaster(options.bot)
if err_msg:
parser.error(('Tryserver master cannot be found because: %s\nPlease manually specify the tryserver master, e.g. "-m tryserver.chromium.linux".' % err_msg))
def GetMasterMap():
if (not options.bot):
change = cl.GetChange(cl.GetCommonAncestorWithUpstream(), None)
masters = presubmit_support.DoGetTryMasters(change, change.LocalPaths(), settings.GetRoot(), None, None, options.verbose, sys.stdout)
if masters:
return masters
options.bot = presubmit_support.DoGetTrySlaves(change, change.LocalPaths(), settings.GetRoot(), None, None, options.verbose, sys.stdout)
if (not options.bot):
cq_cfg = os.path.join(change.RepositoryRoot(), 'infra', 'config', 'cq.cfg')
if os.path.exists(cq_cfg):
masters = {}
cq_masters = commit_queue.get_master_builder_map(cq_cfg, include_experimental=False, include_triggered=False)
for (master, builders) in cq_masters.iteritems():
for builder in builders:
masters.setdefault(master, {})[builder] = ['defaulttests']
if masters:
print(('Loaded default bots from CQ config (%s)' % cq_cfg))
return masters
else:
print(('CQ config exists (%s) but has no try bots listed' % cq_cfg))
if (not options.bot):
parser.error('No default try builder to try, use --bot')
builders_and_tests = {}
old_style = filter((lambda x: isinstance(x, basestring)), options.bot)
new_style = filter((lambda x: isinstance(x, tuple)), options.bot)
for bot in old_style:
if (':' in bot):
parser.error('Specifying testfilter is no longer supported')
elif (',' in bot):
parser.error('Specify one bot per --bot flag')
else:
builders_and_tests.setdefault(bot, [])
for (bot, tests) in new_style:
builders_and_tests.setdefault(bot, []).extend(tests)
return {options.master: builders_and_tests}
masters = GetMasterMap()
for builders in masters.itervalues():
if any((('triggered' in b) for b in builders)):
print(('ERROR You are trying to send a job to a triggered bot. This type of bot requires an\ninitial job from a parent (usually a builder). Instead send your job to the parent.\nBot list: %s' % builders), file=sys.stderr)
return 1
patchset = cl.GetMostRecentPatchset()
if (patchset and (patchset != cl.GetPatchset())):
print(('\nWARNING Mismatch between local config and server. Did a previous upload fail?\ngit-cl try always uses latest patchset from rietveld. Continuing using\npatchset %s.\n' % patchset))
if options.luci:
trigger_luci_job(cl, masters, options)
elif (not options.use_rietveld):
try:
trigger_try_jobs(auth_config, cl, options, masters, 'git_cl_try')
except BuildbucketResponseException as ex:
print(('ERROR: %s' % ex))
return 1
except Exception as e:
stacktrace = (''.join(traceback.format_stack()) + traceback.format_exc())
print(('ERROR: Exception when trying to trigger tryjobs: %s\n%s' % (e, stacktrace)))
return 1
else:
try:
cl.RpcServer().trigger_distributed_try_jobs(cl.GetIssue(), patchset, options.name, options.clobber, options.revision, masters)
except urllib2.HTTPError as e:
if (e.code == 404):
print('404 from rietveld; did you mean to use "git try" instead of "git cl try"?')
return 1
print('Tried jobs on:')
for (master, builders) in sorted(masters.iteritems()):
if master:
print(('Master: %s' % master))
length = max((len(builder) for builder in builders))
for builder in sorted(builders):
print((' %*s: %s' % (length, builder, ','.join(builders[builder]))))
return 0
| -4,868,945,639,271,806,000
|
Triggers try jobs through BuildBucket.
|
git_cl.py
|
CMDtry
|
wuyong2k/chromium_depot_tool
|
python
|
def CMDtry(parser, args):
group = optparse.OptionGroup(parser, 'Try job options')
group.add_option('-b', '--bot', action='append', help="IMPORTANT: specify ONE builder per --bot flag. Use it multiple times to specify multiple builders. ex: '-b win_rel -b win_layout'. See the try server waterfall for the builders name and the tests available.")
group.add_option('-m', '--master', default=, help='Specify a try master where to run the tries.')
group.add_option('--luci', action='store_true')
group.add_option('-r', '--revision', help='Revision to use for the try job; default: the revision will be determined by the try server; see its waterfall for more info')
group.add_option('-c', '--clobber', action='store_true', default=False, help="Force a clobber before building; e.g. don't do an incremental build")
group.add_option('--project', help='Override which project to use. Projects are defined server-side to define what default bot set to use')
group.add_option('-p', '--property', dest='properties', action='append', default=[], help='Specify generic properties in the form -p key1=value1 -p key2=value2 etc (buildbucket only). The value will be treated as json if decodable, or as string otherwise.')
group.add_option('-n', '--name', help='Try job name; default to current branch name')
group.add_option('--use-rietveld', action='store_true', default=False, help='Use Rietveld to trigger try jobs.')
group.add_option('--buildbucket-host', default='cr-buildbucket.appspot.com', help='Host of buildbucket. The default host is %default.')
parser.add_option_group(group)
auth.add_auth_options(parser)
(options, args) = parser.parse_args(args)
auth_config = auth.extract_auth_config_from_options(options)
if (options.use_rietveld and options.properties):
parser.error('Properties can only be specified with buildbucket')
bad_params = [x for x in options.properties if ('=' not in x)]
if bad_params:
parser.error(('Got properties with missing "=": %s' % bad_params))
if args:
parser.error(('Unknown arguments: %s' % args))
cl = Changelist(auth_config=auth_config)
if (not cl.GetIssue()):
parser.error('Need to upload first')
if cl.IsGerrit():
parser.error('Not yet supported for Gerrit (http://crbug.com/599931).\nIf your project has Commit Queue, dry run is a workaround:\n git cl set-commit --dry-run')
props = cl.GetIssueProperties()
if props.get('closed'):
parser.error('Cannot send tryjobs for a closed CL')
if props.get('private'):
parser.error('Cannot use trybots with private issue')
if (not options.name):
options.name = cl.GetBranch()
if (options.bot and (not options.master)):
(options.master, err_msg) = GetBuilderMaster(options.bot)
if err_msg:
parser.error(('Tryserver master cannot be found because: %s\nPlease manually specify the tryserver master, e.g. "-m tryserver.chromium.linux".' % err_msg))
def GetMasterMap():
if (not options.bot):
change = cl.GetChange(cl.GetCommonAncestorWithUpstream(), None)
masters = presubmit_support.DoGetTryMasters(change, change.LocalPaths(), settings.GetRoot(), None, None, options.verbose, sys.stdout)
if masters:
return masters
options.bot = presubmit_support.DoGetTrySlaves(change, change.LocalPaths(), settings.GetRoot(), None, None, options.verbose, sys.stdout)
if (not options.bot):
cq_cfg = os.path.join(change.RepositoryRoot(), 'infra', 'config', 'cq.cfg')
if os.path.exists(cq_cfg):
masters = {}
cq_masters = commit_queue.get_master_builder_map(cq_cfg, include_experimental=False, include_triggered=False)
for (master, builders) in cq_masters.iteritems():
for builder in builders:
masters.setdefault(master, {})[builder] = ['defaulttests']
if masters:
print(('Loaded default bots from CQ config (%s)' % cq_cfg))
return masters
else:
print(('CQ config exists (%s) but has no try bots listed' % cq_cfg))
if (not options.bot):
parser.error('No default try builder to try, use --bot')
builders_and_tests = {}
old_style = filter((lambda x: isinstance(x, basestring)), options.bot)
new_style = filter((lambda x: isinstance(x, tuple)), options.bot)
for bot in old_style:
if (':' in bot):
parser.error('Specifying testfilter is no longer supported')
elif (',' in bot):
parser.error('Specify one bot per --bot flag')
else:
builders_and_tests.setdefault(bot, [])
for (bot, tests) in new_style:
builders_and_tests.setdefault(bot, []).extend(tests)
return {options.master: builders_and_tests}
masters = GetMasterMap()
for builders in masters.itervalues():
if any((('triggered' in b) for b in builders)):
print(('ERROR You are trying to send a job to a triggered bot. This type of bot requires an\ninitial job from a parent (usually a builder). Instead send your job to the parent.\nBot list: %s' % builders), file=sys.stderr)
return 1
patchset = cl.GetMostRecentPatchset()
if (patchset and (patchset != cl.GetPatchset())):
print(('\nWARNING Mismatch between local config and server. Did a previous upload fail?\ngit-cl try always uses latest patchset from rietveld. Continuing using\npatchset %s.\n' % patchset))
if options.luci:
trigger_luci_job(cl, masters, options)
elif (not options.use_rietveld):
try:
trigger_try_jobs(auth_config, cl, options, masters, 'git_cl_try')
except BuildbucketResponseException as ex:
print(('ERROR: %s' % ex))
return 1
except Exception as e:
stacktrace = (.join(traceback.format_stack()) + traceback.format_exc())
print(('ERROR: Exception when trying to trigger tryjobs: %s\n%s' % (e, stacktrace)))
return 1
else:
try:
cl.RpcServer().trigger_distributed_try_jobs(cl.GetIssue(), patchset, options.name, options.clobber, options.revision, masters)
except urllib2.HTTPError as e:
if (e.code == 404):
print('404 from rietveld; did you mean to use "git try" instead of "git cl try"?')
return 1
print('Tried jobs on:')
for (master, builders) in sorted(masters.iteritems()):
if master:
print(('Master: %s' % master))
length = max((len(builder) for builder in builders))
for builder in sorted(builders):
print((' %*s: %s' % (length, builder, ','.join(builders[builder]))))
return 0
|
@subcommand.usage('[new upstream branch]')
def CMDupstream(parser, args):
'Prints or sets the name of the upstream branch, if any.'
(_, args) = parser.parse_args(args)
if (len(args) > 1):
parser.error(('Unrecognized args: %s' % ' '.join(args)))
cl = Changelist()
if args:
branch = cl.GetBranch()
RunGit(['branch', '--set-upstream', branch, args[0]])
cl = Changelist()
print(('Upstream branch set to %s' % (cl.GetUpstreamBranch(),)))
git_common.remove_merge_base(branch)
else:
print(cl.GetUpstreamBranch())
return 0
| 6,015,972,814,959,564,000
|
Prints or sets the name of the upstream branch, if any.
|
git_cl.py
|
CMDupstream
|
wuyong2k/chromium_depot_tool
|
python
|
@subcommand.usage('[new upstream branch]')
def CMDupstream(parser, args):
(_, args) = parser.parse_args(args)
if (len(args) > 1):
parser.error(('Unrecognized args: %s' % ' '.join(args)))
cl = Changelist()
if args:
branch = cl.GetBranch()
RunGit(['branch', '--set-upstream', branch, args[0]])
cl = Changelist()
print(('Upstream branch set to %s' % (cl.GetUpstreamBranch(),)))
git_common.remove_merge_base(branch)
else:
print(cl.GetUpstreamBranch())
return 0
|
def CMDweb(parser, args):
'Opens the current CL in the web browser.'
(_, args) = parser.parse_args(args)
if args:
parser.error(('Unrecognized args: %s' % ' '.join(args)))
issue_url = Changelist().GetIssueURL()
if (not issue_url):
print('ERROR No issue to open', file=sys.stderr)
return 1
webbrowser.open(issue_url)
return 0
| -2,022,026,822,592,401,400
|
Opens the current CL in the web browser.
|
git_cl.py
|
CMDweb
|
wuyong2k/chromium_depot_tool
|
python
|
def CMDweb(parser, args):
(_, args) = parser.parse_args(args)
if args:
parser.error(('Unrecognized args: %s' % ' '.join(args)))
issue_url = Changelist().GetIssueURL()
if (not issue_url):
print('ERROR No issue to open', file=sys.stderr)
return 1
webbrowser.open(issue_url)
return 0
|
def CMDset_commit(parser, args):
'Sets the commit bit to trigger the Commit Queue.'
parser.add_option('-d', '--dry-run', action='store_true', help='trigger in dry run mode')
parser.add_option('-c', '--clear', action='store_true', help='stop CQ run, if any')
auth.add_auth_options(parser)
(options, args) = parser.parse_args(args)
auth_config = auth.extract_auth_config_from_options(options)
if args:
parser.error(('Unrecognized args: %s' % ' '.join(args)))
if (options.dry_run and options.clear):
parser.error('Make up your mind: both --dry-run and --clear not allowed')
cl = Changelist(auth_config=auth_config)
if options.clear:
state = _CQState.CLEAR
elif options.dry_run:
state = _CQState.DRY_RUN
else:
state = _CQState.COMMIT
if (not cl.GetIssue()):
parser.error('Must upload the issue first')
cl.SetCQState(state)
return 0
| -7,858,453,068,095,442,000
|
Sets the commit bit to trigger the Commit Queue.
|
git_cl.py
|
CMDset_commit
|
wuyong2k/chromium_depot_tool
|
python
|
def CMDset_commit(parser, args):
parser.add_option('-d', '--dry-run', action='store_true', help='trigger in dry run mode')
parser.add_option('-c', '--clear', action='store_true', help='stop CQ run, if any')
auth.add_auth_options(parser)
(options, args) = parser.parse_args(args)
auth_config = auth.extract_auth_config_from_options(options)
if args:
parser.error(('Unrecognized args: %s' % ' '.join(args)))
if (options.dry_run and options.clear):
parser.error('Make up your mind: both --dry-run and --clear not allowed')
cl = Changelist(auth_config=auth_config)
if options.clear:
state = _CQState.CLEAR
elif options.dry_run:
state = _CQState.DRY_RUN
else:
state = _CQState.COMMIT
if (not cl.GetIssue()):
parser.error('Must upload the issue first')
cl.SetCQState(state)
return 0
|
def CMDset_close(parser, args):
'Closes the issue.'
auth.add_auth_options(parser)
(options, args) = parser.parse_args(args)
auth_config = auth.extract_auth_config_from_options(options)
if args:
parser.error(('Unrecognized args: %s' % ' '.join(args)))
cl = Changelist(auth_config=auth_config)
cl.GetDescription()
cl.CloseIssue()
return 0
| 1,098,923,931,220,576,800
|
Closes the issue.
|
git_cl.py
|
CMDset_close
|
wuyong2k/chromium_depot_tool
|
python
|
def CMDset_close(parser, args):
auth.add_auth_options(parser)
(options, args) = parser.parse_args(args)
auth_config = auth.extract_auth_config_from_options(options)
if args:
parser.error(('Unrecognized args: %s' % ' '.join(args)))
cl = Changelist(auth_config=auth_config)
cl.GetDescription()
cl.CloseIssue()
return 0
|
def CMDdiff(parser, args):
'Shows differences between local tree and last upload.'
auth.add_auth_options(parser)
(options, args) = parser.parse_args(args)
auth_config = auth.extract_auth_config_from_options(options)
if args:
parser.error(('Unrecognized args: %s' % ' '.join(args)))
if git_common.is_dirty_git_tree('diff'):
return 1
cl = Changelist(auth_config=auth_config)
issue = cl.GetIssue()
branch = cl.GetBranch()
if (not issue):
DieWithError(('No issue found for current branch (%s)' % branch))
TMP_BRANCH = 'git-cl-diff'
base_branch = cl.GetCommonAncestorWithUpstream()
RunGit(['checkout', '-q', '-b', TMP_BRANCH, base_branch])
cl.ClearBranch()
try:
rtn = cl.CMDPatchIssue(issue, reject=False, nocommit=False, directory=None)
if (rtn != 0):
RunGit(['reset', '--hard'])
return rtn
subprocess2.check_call(['git', 'diff', TMP_BRANCH, branch, '--'])
finally:
RunGit(['checkout', '-q', branch])
RunGit(['branch', '-D', TMP_BRANCH])
return 0
| 4,786,604,619,235,999,000
|
Shows differences between local tree and last upload.
|
git_cl.py
|
CMDdiff
|
wuyong2k/chromium_depot_tool
|
python
|
def CMDdiff(parser, args):
auth.add_auth_options(parser)
(options, args) = parser.parse_args(args)
auth_config = auth.extract_auth_config_from_options(options)
if args:
parser.error(('Unrecognized args: %s' % ' '.join(args)))
if git_common.is_dirty_git_tree('diff'):
return 1
cl = Changelist(auth_config=auth_config)
issue = cl.GetIssue()
branch = cl.GetBranch()
if (not issue):
DieWithError(('No issue found for current branch (%s)' % branch))
TMP_BRANCH = 'git-cl-diff'
base_branch = cl.GetCommonAncestorWithUpstream()
RunGit(['checkout', '-q', '-b', TMP_BRANCH, base_branch])
cl.ClearBranch()
try:
rtn = cl.CMDPatchIssue(issue, reject=False, nocommit=False, directory=None)
if (rtn != 0):
RunGit(['reset', '--hard'])
return rtn
subprocess2.check_call(['git', 'diff', TMP_BRANCH, branch, '--'])
finally:
RunGit(['checkout', '-q', branch])
RunGit(['branch', '-D', TMP_BRANCH])
return 0
|
def CMDowners(parser, args):
'Interactively find the owners for reviewing.'
parser.add_option('--no-color', action='store_true', help='Use this option to disable color output')
auth.add_auth_options(parser)
(options, args) = parser.parse_args(args)
auth_config = auth.extract_auth_config_from_options(options)
author = (RunGit(['config', 'user.email']).strip() or None)
cl = Changelist(auth_config=auth_config)
if args:
if (len(args) > 1):
parser.error('Unknown args')
base_branch = args[0]
else:
base_branch = cl.GetCommonAncestorWithUpstream()
change = cl.GetChange(base_branch, None)
return owners_finder.OwnersFinder([f.LocalPath() for f in cl.GetChange(base_branch, None).AffectedFiles()], change.RepositoryRoot(), author, fopen=file, os_path=os.path, glob=glob.glob, disable_color=options.no_color).run()
| -8,540,179,567,444,445,000
|
Interactively find the owners for reviewing.
|
git_cl.py
|
CMDowners
|
wuyong2k/chromium_depot_tool
|
python
|
def CMDowners(parser, args):
parser.add_option('--no-color', action='store_true', help='Use this option to disable color output')
auth.add_auth_options(parser)
(options, args) = parser.parse_args(args)
auth_config = auth.extract_auth_config_from_options(options)
author = (RunGit(['config', 'user.email']).strip() or None)
cl = Changelist(auth_config=auth_config)
if args:
if (len(args) > 1):
parser.error('Unknown args')
base_branch = args[0]
else:
base_branch = cl.GetCommonAncestorWithUpstream()
change = cl.GetChange(base_branch, None)
return owners_finder.OwnersFinder([f.LocalPath() for f in cl.GetChange(base_branch, None).AffectedFiles()], change.RepositoryRoot(), author, fopen=file, os_path=os.path, glob=glob.glob, disable_color=options.no_color).run()
|
def BuildGitDiffCmd(diff_type, upstream_commit, args):
'Generates a diff command.'
diff_cmd = ['diff', '--no-ext-diff', '--no-prefix', diff_type, upstream_commit, '--']
if args:
for arg in args:
if (os.path.isdir(arg) or os.path.isfile(arg)):
diff_cmd.append(arg)
else:
DieWithError(('Argument "%s" is not a file or a directory' % arg))
return diff_cmd
| 5,490,146,766,828,878,000
|
Generates a diff command.
|
git_cl.py
|
BuildGitDiffCmd
|
wuyong2k/chromium_depot_tool
|
python
|
def BuildGitDiffCmd(diff_type, upstream_commit, args):
diff_cmd = ['diff', '--no-ext-diff', '--no-prefix', diff_type, upstream_commit, '--']
if args:
for arg in args:
if (os.path.isdir(arg) or os.path.isfile(arg)):
diff_cmd.append(arg)
else:
DieWithError(('Argument "%s" is not a file or a directory' % arg))
return diff_cmd
|
def MatchingFileType(file_name, extensions):
'Returns true if the file name ends with one of the given extensions.'
return bool([ext for ext in extensions if file_name.lower().endswith(ext)])
| 3,653,199,087,222,800,000
|
Returns true if the file name ends with one of the given extensions.
|
git_cl.py
|
MatchingFileType
|
wuyong2k/chromium_depot_tool
|
python
|
def MatchingFileType(file_name, extensions):
return bool([ext for ext in extensions if file_name.lower().endswith(ext)])
|
@subcommand.usage('[files or directories to diff]')
def CMDformat(parser, args):
'Runs auto-formatting tools (clang-format etc.) on the diff.'
CLANG_EXTS = ['.cc', '.cpp', '.h', '.mm', '.proto', '.java']
GN_EXTS = ['.gn', '.gni', '.typemap']
parser.add_option('--full', action='store_true', help='Reformat the full content of all touched files')
parser.add_option('--dry-run', action='store_true', help="Don't modify any file on disk.")
parser.add_option('--python', action='store_true', help='Format python code with yapf (experimental).')
parser.add_option('--diff', action='store_true', help='Print diff to stdout rather than modifying files.')
(opts, args) = parser.parse_args(args)
rel_base_path = settings.GetRelativeRoot()
if rel_base_path:
os.chdir(rel_base_path)
upstream_commit = None
cl = Changelist()
upstream_branch = cl.GetUpstreamBranch()
if upstream_branch:
upstream_commit = RunGit(['merge-base', 'HEAD', upstream_branch])
upstream_commit = upstream_commit.strip()
if (not upstream_commit):
DieWithError('Could not find base commit for this branch. Are you in detached state?')
changed_files_cmd = BuildGitDiffCmd('--name-only', upstream_commit, args)
diff_output = RunGit(changed_files_cmd)
diff_files = diff_output.splitlines()
diff_files = [x for x in diff_files if os.path.isfile(x)]
clang_diff_files = [x for x in diff_files if MatchingFileType(x, CLANG_EXTS)]
python_diff_files = [x for x in diff_files if MatchingFileType(x, ['.py'])]
dart_diff_files = [x for x in diff_files if MatchingFileType(x, ['.dart'])]
gn_diff_files = [x for x in diff_files if MatchingFileType(x, GN_EXTS)]
top_dir = os.path.normpath(RunGit(['rev-parse', '--show-toplevel']).rstrip('\n'))
return_value = 0
if clang_diff_files:
try:
clang_format_tool = clang_format.FindClangFormatToolInChromiumTree()
except clang_format.NotFoundError as e:
DieWithError(e)
if opts.full:
cmd = [clang_format_tool]
if ((not opts.dry_run) and (not opts.diff)):
cmd.append('-i')
stdout = RunCommand((cmd + clang_diff_files), cwd=top_dir)
if opts.diff:
sys.stdout.write(stdout)
else:
env = os.environ.copy()
env['PATH'] = str(os.path.dirname(clang_format_tool))
try:
script = clang_format.FindClangFormatScriptInChromiumTree('clang-format-diff.py')
except clang_format.NotFoundError as e:
DieWithError(e)
cmd = [sys.executable, script, '-p0']
if ((not opts.dry_run) and (not opts.diff)):
cmd.append('-i')
diff_cmd = BuildGitDiffCmd('-U0', upstream_commit, clang_diff_files)
diff_output = RunGit(diff_cmd)
stdout = RunCommand(cmd, stdin=diff_output, cwd=top_dir, env=env)
if opts.diff:
sys.stdout.write(stdout)
if (opts.dry_run and (len(stdout) > 0)):
return_value = 2
if opts.python:
yapf_tool = gclient_utils.FindExecutable('yapf')
if (yapf_tool is None):
DieWithError('yapf not found in PATH')
if opts.full:
if python_diff_files:
cmd = [yapf_tool]
if ((not opts.dry_run) and (not opts.diff)):
cmd.append('-i')
stdout = RunCommand((cmd + python_diff_files), cwd=top_dir)
if opts.diff:
sys.stdout.write(stdout)
else:
DieWithError('--python currently only works with --full')
if dart_diff_files:
try:
command = [dart_format.FindDartFmtToolInChromiumTree()]
if ((not opts.dry_run) and (not opts.diff)):
command.append('-w')
command.extend(dart_diff_files)
stdout = RunCommand(command, cwd=top_dir)
if (opts.dry_run and stdout):
return_value = 2
except dart_format.NotFoundError as e:
print('Warning: Unable to check Dart code formatting. Dart SDK not found in this checkout. Files in other languages are still formatted.')
if gn_diff_files:
cmd = ['gn', 'format']
if ((not opts.dry_run) and (not opts.diff)):
cmd.append('--in-place')
for gn_diff_file in gn_diff_files:
stdout = RunCommand((cmd + [gn_diff_file]), shell=(sys.platform == 'win32'), cwd=top_dir)
if opts.diff:
sys.stdout.write(stdout)
return return_value
| -8,500,997,385,933,100,000
|
Runs auto-formatting tools (clang-format etc.) on the diff.
|
git_cl.py
|
CMDformat
|
wuyong2k/chromium_depot_tool
|
python
|
@subcommand.usage('[files or directories to diff]')
def CMDformat(parser, args):
CLANG_EXTS = ['.cc', '.cpp', '.h', '.mm', '.proto', '.java']
GN_EXTS = ['.gn', '.gni', '.typemap']
parser.add_option('--full', action='store_true', help='Reformat the full content of all touched files')
parser.add_option('--dry-run', action='store_true', help="Don't modify any file on disk.")
parser.add_option('--python', action='store_true', help='Format python code with yapf (experimental).')
parser.add_option('--diff', action='store_true', help='Print diff to stdout rather than modifying files.')
(opts, args) = parser.parse_args(args)
rel_base_path = settings.GetRelativeRoot()
if rel_base_path:
os.chdir(rel_base_path)
upstream_commit = None
cl = Changelist()
upstream_branch = cl.GetUpstreamBranch()
if upstream_branch:
upstream_commit = RunGit(['merge-base', 'HEAD', upstream_branch])
upstream_commit = upstream_commit.strip()
if (not upstream_commit):
DieWithError('Could not find base commit for this branch. Are you in detached state?')
changed_files_cmd = BuildGitDiffCmd('--name-only', upstream_commit, args)
diff_output = RunGit(changed_files_cmd)
diff_files = diff_output.splitlines()
diff_files = [x for x in diff_files if os.path.isfile(x)]
clang_diff_files = [x for x in diff_files if MatchingFileType(x, CLANG_EXTS)]
python_diff_files = [x for x in diff_files if MatchingFileType(x, ['.py'])]
dart_diff_files = [x for x in diff_files if MatchingFileType(x, ['.dart'])]
gn_diff_files = [x for x in diff_files if MatchingFileType(x, GN_EXTS)]
top_dir = os.path.normpath(RunGit(['rev-parse', '--show-toplevel']).rstrip('\n'))
return_value = 0
if clang_diff_files:
try:
clang_format_tool = clang_format.FindClangFormatToolInChromiumTree()
except clang_format.NotFoundError as e:
DieWithError(e)
if opts.full:
cmd = [clang_format_tool]
if ((not opts.dry_run) and (not opts.diff)):
cmd.append('-i')
stdout = RunCommand((cmd + clang_diff_files), cwd=top_dir)
if opts.diff:
sys.stdout.write(stdout)
else:
env = os.environ.copy()
env['PATH'] = str(os.path.dirname(clang_format_tool))
try:
script = clang_format.FindClangFormatScriptInChromiumTree('clang-format-diff.py')
except clang_format.NotFoundError as e:
DieWithError(e)
cmd = [sys.executable, script, '-p0']
if ((not opts.dry_run) and (not opts.diff)):
cmd.append('-i')
diff_cmd = BuildGitDiffCmd('-U0', upstream_commit, clang_diff_files)
diff_output = RunGit(diff_cmd)
stdout = RunCommand(cmd, stdin=diff_output, cwd=top_dir, env=env)
if opts.diff:
sys.stdout.write(stdout)
if (opts.dry_run and (len(stdout) > 0)):
return_value = 2
if opts.python:
yapf_tool = gclient_utils.FindExecutable('yapf')
if (yapf_tool is None):
DieWithError('yapf not found in PATH')
if opts.full:
if python_diff_files:
cmd = [yapf_tool]
if ((not opts.dry_run) and (not opts.diff)):
cmd.append('-i')
stdout = RunCommand((cmd + python_diff_files), cwd=top_dir)
if opts.diff:
sys.stdout.write(stdout)
else:
DieWithError('--python currently only works with --full')
if dart_diff_files:
try:
command = [dart_format.FindDartFmtToolInChromiumTree()]
if ((not opts.dry_run) and (not opts.diff)):
command.append('-w')
command.extend(dart_diff_files)
stdout = RunCommand(command, cwd=top_dir)
if (opts.dry_run and stdout):
return_value = 2
except dart_format.NotFoundError as e:
print('Warning: Unable to check Dart code formatting. Dart SDK not found in this checkout. Files in other languages are still formatted.')
if gn_diff_files:
cmd = ['gn', 'format']
if ((not opts.dry_run) and (not opts.diff)):
cmd.append('--in-place')
for gn_diff_file in gn_diff_files:
stdout = RunCommand((cmd + [gn_diff_file]), shell=(sys.platform == 'win32'), cwd=top_dir)
if opts.diff:
sys.stdout.write(stdout)
return return_value
|
@subcommand.usage('<codereview url or issue id>')
def CMDcheckout(parser, args):
'Checks out a branch associated with a given Rietveld or Gerrit issue.'
(_, args) = parser.parse_args(args)
if (len(args) != 1):
parser.print_help()
return 1
issue_arg = ParseIssueNumberArgument(args[0])
if (not issue_arg.valid):
parser.print_help()
return 1
target_issue = str(issue_arg.issue)
def find_issues(issueprefix):
output = RunGit(['config', '--local', '--get-regexp', ('branch\\..*\\.%s' % issueprefix)], error_ok=True)
for (key, issue) in [x.split() for x in output.splitlines()]:
if (issue == target_issue):
(yield re.sub(('branch\\.(.*)\\.%s' % issueprefix), '\\1', key))
branches = []
for cls in _CODEREVIEW_IMPLEMENTATIONS.values():
branches.extend(find_issues(cls.IssueSettingSuffix()))
if (len(branches) == 0):
print(('No branch found for issue %s.' % target_issue))
return 1
if (len(branches) == 1):
RunGit(['checkout', branches[0]])
else:
print(('Multiple branches match issue %s:' % target_issue))
for i in range(len(branches)):
print(('%d: %s' % (i, branches[i])))
which = raw_input('Choose by index: ')
try:
RunGit(['checkout', branches[int(which)]])
except (IndexError, ValueError):
print('Invalid selection, not checking out any branch.')
return 1
return 0
| 2,895,987,222,502,879,700
|
Checks out a branch associated with a given Rietveld or Gerrit issue.
|
git_cl.py
|
CMDcheckout
|
wuyong2k/chromium_depot_tool
|
python
|
@subcommand.usage('<codereview url or issue id>')
def CMDcheckout(parser, args):
(_, args) = parser.parse_args(args)
if (len(args) != 1):
parser.print_help()
return 1
issue_arg = ParseIssueNumberArgument(args[0])
if (not issue_arg.valid):
parser.print_help()
return 1
target_issue = str(issue_arg.issue)
def find_issues(issueprefix):
output = RunGit(['config', '--local', '--get-regexp', ('branch\\..*\\.%s' % issueprefix)], error_ok=True)
for (key, issue) in [x.split() for x in output.splitlines()]:
if (issue == target_issue):
(yield re.sub(('branch\\.(.*)\\.%s' % issueprefix), '\\1', key))
branches = []
for cls in _CODEREVIEW_IMPLEMENTATIONS.values():
branches.extend(find_issues(cls.IssueSettingSuffix()))
if (len(branches) == 0):
print(('No branch found for issue %s.' % target_issue))
return 1
if (len(branches) == 1):
RunGit(['checkout', branches[0]])
else:
print(('Multiple branches match issue %s:' % target_issue))
for i in range(len(branches)):
print(('%d: %s' % (i, branches[i])))
which = raw_input('Choose by index: ')
try:
RunGit(['checkout', branches[int(which)]])
except (IndexError, ValueError):
print('Invalid selection, not checking out any branch.')
return 1
return 0
|
def pop(title, f, color=None, **kwargs):
'Pop matching builds from `builds` dict and print them.'
if ((not options.color) or (color is None)):
colorize = str
else:
colorize = (lambda x: ('%s%s%s' % (color, x, Fore.RESET)))
result = []
for b in builds.values():
if all(((b.get(k) == v) for (k, v) in kwargs.iteritems())):
builds.pop(b['id'])
result.append(b)
if result:
print(colorize(title))
for b in sorted(result, key=sort_key):
print(' ', colorize('\t'.join(map(str, f(b)))))
| -6,675,543,092,929,439,000
|
Pop matching builds from `builds` dict and print them.
|
git_cl.py
|
pop
|
wuyong2k/chromium_depot_tool
|
python
|
def pop(title, f, color=None, **kwargs):
if ((not options.color) or (color is None)):
colorize = str
else:
colorize = (lambda x: ('%s%s%s' % (color, x, Fore.RESET)))
result = []
for b in builds.values():
if all(((b.get(k) == v) for (k, v) in kwargs.iteritems())):
builds.pop(b['id'])
result.append(b)
if result:
print(colorize(title))
for b in sorted(result, key=sort_key):
print(' ', colorize('\t'.join(map(str, f(b)))))
|
def LazyUpdateIfNeeded(self):
'Updates the settings from a codereview.settings file, if available.'
if (not self.updated):
autoupdate = RunGit(['config', 'rietveld.autoupdate'], error_ok=True).strip().lower()
cr_settings_file = FindCodereviewSettingsFile()
if ((autoupdate != 'false') and cr_settings_file):
LoadCodereviewSettingsFromFile(cr_settings_file)
self.updated = True
| -3,136,644,429,528,896,000
|
Updates the settings from a codereview.settings file, if available.
|
git_cl.py
|
LazyUpdateIfNeeded
|
wuyong2k/chromium_depot_tool
|
python
|
def LazyUpdateIfNeeded(self):
if (not self.updated):
autoupdate = RunGit(['config', 'rietveld.autoupdate'], error_ok=True).strip().lower()
cr_settings_file = FindCodereviewSettingsFile()
if ((autoupdate != 'false') and cr_settings_file):
LoadCodereviewSettingsFromFile(cr_settings_file)
self.updated = True
|
def GetGitMirror(self, remote='origin'):
'If this checkout is from a local git mirror, return a Mirror object.'
local_url = RunGit(['config', '--get', ('remote.%s.url' % remote)]).strip()
if (not os.path.isdir(local_url)):
return None
git_cache.Mirror.SetCachePath(os.path.dirname(local_url))
remote_url = git_cache.Mirror.CacheDirToUrl(local_url)
mirror = git_cache.Mirror(remote_url, print_func=(lambda *args: None))
if mirror.exists():
return mirror
return None
| -2,647,150,121,721,829,000
|
If this checkout is from a local git mirror, return a Mirror object.
|
git_cl.py
|
GetGitMirror
|
wuyong2k/chromium_depot_tool
|
python
|
def GetGitMirror(self, remote='origin'):
local_url = RunGit(['config', '--get', ('remote.%s.url' % remote)]).strip()
if (not os.path.isdir(local_url)):
return None
git_cache.Mirror.SetCachePath(os.path.dirname(local_url))
remote_url = git_cache.Mirror.CacheDirToUrl(local_url)
mirror = git_cache.Mirror(remote_url, print_func=(lambda *args: None))
if mirror.exists():
return mirror
return None
|
def GetIsGitSvn(self):
"Return true if this repo looks like it's using git-svn."
if (self.is_git_svn is None):
if self.GetPendingRefPrefix():
self.is_git_svn = False
else:
self.is_git_svn = (RunGitWithCode(['config', '--local', '--get-regexp', '^svn-remote\\.'])[0] == 0)
return self.is_git_svn
| -7,692,615,956,078,929,000
|
Return true if this repo looks like it's using git-svn.
|
git_cl.py
|
GetIsGitSvn
|
wuyong2k/chromium_depot_tool
|
python
|
def GetIsGitSvn(self):
if (self.is_git_svn is None):
if self.GetPendingRefPrefix():
self.is_git_svn = False
else:
self.is_git_svn = (RunGitWithCode(['config', '--local', '--get-regexp', '^svn-remote\\.'])[0] == 0)
return self.is_git_svn
|
def GetIsSkipDependencyUpload(self, branch_name):
'Returns true if specified branch should skip dep uploads.'
return self._GetBranchConfig(branch_name, 'skip-deps-uploads', error_ok=True)
| 2,428,893,246,341,684,000
|
Returns true if specified branch should skip dep uploads.
|
git_cl.py
|
GetIsSkipDependencyUpload
|
wuyong2k/chromium_depot_tool
|
python
|
def GetIsSkipDependencyUpload(self, branch_name):
return self._GetBranchConfig(branch_name, 'skip-deps-uploads', error_ok=True)
|
def GetIsGerrit(self):
'Return true if this repo is assosiated with gerrit code review system.'
if (self.is_gerrit is None):
self.is_gerrit = self._GetConfig('gerrit.host', error_ok=True)
return self.is_gerrit
| 2,969,505,047,769,960,000
|
Return true if this repo is assosiated with gerrit code review system.
|
git_cl.py
|
GetIsGerrit
|
wuyong2k/chromium_depot_tool
|
python
|
def GetIsGerrit(self):
if (self.is_gerrit is None):
self.is_gerrit = self._GetConfig('gerrit.host', error_ok=True)
return self.is_gerrit
|
def GetSquashGerritUploads(self):
'Return true if uploads to Gerrit should be squashed by default.'
if (self.squash_gerrit_uploads is None):
self.squash_gerrit_uploads = self.GetSquashGerritUploadsOverride()
if (self.squash_gerrit_uploads is None):
self.squash_gerrit_uploads = (not (RunGit(['config', '--bool', 'gerrit.squash-uploads'], error_ok=True).strip() == 'false'))
return self.squash_gerrit_uploads
| 6,245,361,291,211,359,000
|
Return true if uploads to Gerrit should be squashed by default.
|
git_cl.py
|
GetSquashGerritUploads
|
wuyong2k/chromium_depot_tool
|
python
|
def GetSquashGerritUploads(self):
if (self.squash_gerrit_uploads is None):
self.squash_gerrit_uploads = self.GetSquashGerritUploadsOverride()
if (self.squash_gerrit_uploads is None):
self.squash_gerrit_uploads = (not (RunGit(['config', '--bool', 'gerrit.squash-uploads'], error_ok=True).strip() == 'false'))
return self.squash_gerrit_uploads
|
def GetSquashGerritUploadsOverride(self):
'Return True or False if codereview.settings should be overridden.\n\n Returns None if no override has been defined.\n '
result = RunGit(['config', '--bool', 'gerrit.override-squash-uploads'], error_ok=True).strip()
if (result == 'true'):
return True
if (result == 'false'):
return False
return None
| 6,591,214,156,574,674,000
|
Return True or False if codereview.settings should be overridden.
Returns None if no override has been defined.
|
git_cl.py
|
GetSquashGerritUploadsOverride
|
wuyong2k/chromium_depot_tool
|
python
|
def GetSquashGerritUploadsOverride(self):
'Return True or False if codereview.settings should be overridden.\n\n Returns None if no override has been defined.\n '
result = RunGit(['config', '--bool', 'gerrit.override-squash-uploads'], error_ok=True).strip()
if (result == 'true'):
return True
if (result == 'false'):
return False
return None
|
def GetGerritSkipEnsureAuthenticated(self):
'Return True if EnsureAuthenticated should not be done for Gerrit\n uploads.'
if (self.gerrit_skip_ensure_authenticated is None):
self.gerrit_skip_ensure_authenticated = (RunGit(['config', '--bool', 'gerrit.skip-ensure-authenticated'], error_ok=True).strip() == 'true')
return self.gerrit_skip_ensure_authenticated
| -5,341,155,329,583,082,000
|
Return True if EnsureAuthenticated should not be done for Gerrit
uploads.
|
git_cl.py
|
GetGerritSkipEnsureAuthenticated
|
wuyong2k/chromium_depot_tool
|
python
|
def GetGerritSkipEnsureAuthenticated(self):
'Return True if EnsureAuthenticated should not be done for Gerrit\n uploads.'
if (self.gerrit_skip_ensure_authenticated is None):
self.gerrit_skip_ensure_authenticated = (RunGit(['config', '--bool', 'gerrit.skip-ensure-authenticated'], error_ok=True).strip() == 'true')
return self.gerrit_skip_ensure_authenticated
|
def GetGitEditor(self):
'Return the editor specified in the git config, or None if none is.'
if (self.git_editor is None):
self.git_editor = self._GetConfig('core.editor', error_ok=True)
return (self.git_editor or None)
| -3,534,564,734,461,231,600
|
Return the editor specified in the git config, or None if none is.
|
git_cl.py
|
GetGitEditor
|
wuyong2k/chromium_depot_tool
|
python
|
def GetGitEditor(self):
if (self.git_editor is None):
self.git_editor = self._GetConfig('core.editor', error_ok=True)
return (self.git_editor or None)
|
def __init__(self, branchref=None, issue=None, codereview=None, **kwargs):
"Create a new ChangeList instance.\n\n If issue is given, the codereview must be given too.\n\n If `codereview` is given, it must be 'rietveld' or 'gerrit'.\n Otherwise, it's decided based on current configuration of the local branch,\n with default being 'rietveld' for backwards compatibility.\n See _load_codereview_impl for more details.\n\n **kwargs will be passed directly to codereview implementation.\n "
global settings
if (not settings):
settings = Settings()
if issue:
assert codereview, 'codereview must be known, if issue is known'
self.branchref = branchref
if self.branchref:
assert branchref.startswith('refs/heads/')
self.branch = ShortBranchName(self.branchref)
else:
self.branch = None
self.upstream_branch = None
self.lookedup_issue = False
self.issue = (issue or None)
self.has_description = False
self.description = None
self.lookedup_patchset = False
self.patchset = None
self.cc = None
self.watchers = ()
self._remote = None
self._codereview_impl = None
self._codereview = None
self._load_codereview_impl(codereview, **kwargs)
assert self._codereview_impl
assert (self._codereview in _CODEREVIEW_IMPLEMENTATIONS)
| -1,281,385,223,439,482,000
|
Create a new ChangeList instance.
If issue is given, the codereview must be given too.
If `codereview` is given, it must be 'rietveld' or 'gerrit'.
Otherwise, it's decided based on current configuration of the local branch,
with default being 'rietveld' for backwards compatibility.
See _load_codereview_impl for more details.
**kwargs will be passed directly to codereview implementation.
|
git_cl.py
|
__init__
|
wuyong2k/chromium_depot_tool
|
python
|
def __init__(self, branchref=None, issue=None, codereview=None, **kwargs):
"Create a new ChangeList instance.\n\n If issue is given, the codereview must be given too.\n\n If `codereview` is given, it must be 'rietveld' or 'gerrit'.\n Otherwise, it's decided based on current configuration of the local branch,\n with default being 'rietveld' for backwards compatibility.\n See _load_codereview_impl for more details.\n\n **kwargs will be passed directly to codereview implementation.\n "
global settings
if (not settings):
settings = Settings()
if issue:
assert codereview, 'codereview must be known, if issue is known'
self.branchref = branchref
if self.branchref:
assert branchref.startswith('refs/heads/')
self.branch = ShortBranchName(self.branchref)
else:
self.branch = None
self.upstream_branch = None
self.lookedup_issue = False
self.issue = (issue or None)
self.has_description = False
self.description = None
self.lookedup_patchset = False
self.patchset = None
self.cc = None
self.watchers = ()
self._remote = None
self._codereview_impl = None
self._codereview = None
self._load_codereview_impl(codereview, **kwargs)
assert self._codereview_impl
assert (self._codereview in _CODEREVIEW_IMPLEMENTATIONS)
|
def GetCCList(self):
"Return the users cc'd on this CL.\n\n Return is a string suitable for passing to gcl with the --cc flag.\n "
if (self.cc is None):
base_cc = settings.GetDefaultCCList()
more_cc = ','.join(self.watchers)
self.cc = (','.join(filter(None, (base_cc, more_cc))) or '')
return self.cc
| -1,000,866,675,075,656,300
|
Return the users cc'd on this CL.
Return is a string suitable for passing to gcl with the --cc flag.
|
git_cl.py
|
GetCCList
|
wuyong2k/chromium_depot_tool
|
python
|
def GetCCList(self):
"Return the users cc'd on this CL.\n\n Return is a string suitable for passing to gcl with the --cc flag.\n "
if (self.cc is None):
base_cc = settings.GetDefaultCCList()
more_cc = ','.join(self.watchers)
self.cc = (','.join(filter(None, (base_cc, more_cc))) or )
return self.cc
|
def GetCCListWithoutDefault(self):
"Return the users cc'd on this CL excluding default ones."
if (self.cc is None):
self.cc = ','.join(self.watchers)
return self.cc
| -4,830,934,428,076,575,000
|
Return the users cc'd on this CL excluding default ones.
|
git_cl.py
|
GetCCListWithoutDefault
|
wuyong2k/chromium_depot_tool
|
python
|
def GetCCListWithoutDefault(self):
if (self.cc is None):
self.cc = ','.join(self.watchers)
return self.cc
|
def SetWatchers(self, watchers):
"Set the list of email addresses that should be cc'd based on the changed\n files in this CL.\n "
self.watchers = watchers
| -8,987,320,363,241,563,000
|
Set the list of email addresses that should be cc'd based on the changed
files in this CL.
|
git_cl.py
|
SetWatchers
|
wuyong2k/chromium_depot_tool
|
python
|
def SetWatchers(self, watchers):
"Set the list of email addresses that should be cc'd based on the changed\n files in this CL.\n "
self.watchers = watchers
|
def GetBranch(self):
"Returns the short branch name, e.g. 'master'."
if (not self.branch):
branchref = GetCurrentBranchRef()
if (not branchref):
return None
self.branchref = branchref
self.branch = ShortBranchName(self.branchref)
return self.branch
| 3,819,321,995,054,192,600
|
Returns the short branch name, e.g. 'master'.
|
git_cl.py
|
GetBranch
|
wuyong2k/chromium_depot_tool
|
python
|
def GetBranch(self):
if (not self.branch):
branchref = GetCurrentBranchRef()
if (not branchref):
return None
self.branchref = branchref
self.branch = ShortBranchName(self.branchref)
return self.branch
|
def GetBranchRef(self):
"Returns the full branch name, e.g. 'refs/heads/master'."
self.GetBranch()
return self.branchref
| -7,243,469,493,687,418,000
|
Returns the full branch name, e.g. 'refs/heads/master'.
|
git_cl.py
|
GetBranchRef
|
wuyong2k/chromium_depot_tool
|
python
|
def GetBranchRef(self):
self.GetBranch()
return self.branchref
|
def ClearBranch(self):
'Clears cached branch data of this object.'
self.branch = self.branchref = None
| -3,159,752,250,145,031,700
|
Clears cached branch data of this object.
|
git_cl.py
|
ClearBranch
|
wuyong2k/chromium_depot_tool
|
python
|
def ClearBranch(self):
self.branch = self.branchref = None
|
@staticmethod
def FetchUpstreamTuple(branch):
"Returns a tuple containing remote and remote ref,\n e.g. 'origin', 'refs/heads/master'\n "
remote = '.'
upstream_branch = RunGit(['config', ('branch.%s.merge' % branch)], error_ok=True).strip()
if upstream_branch:
remote = RunGit(['config', ('branch.%s.remote' % branch)]).strip()
else:
upstream_branch = RunGit(['config', 'rietveld.upstream-branch'], error_ok=True).strip()
if upstream_branch:
remote = RunGit(['config', 'rietveld.upstream-remote']).strip()
elif settings.GetIsGitSvn():
upstream_branch = settings.GetSVNBranch()
else:
remote_branches = RunGit(['branch', '-r']).split()
if ('origin/master' in remote_branches):
remote = 'origin'
upstream_branch = 'refs/heads/master'
elif ('origin/trunk' in remote_branches):
remote = 'origin'
upstream_branch = 'refs/heads/trunk'
else:
DieWithError('Unable to determine default branch to diff against.\nEither pass complete "git diff"-style arguments, like\n git cl upload origin/master\nor verify this branch is set up to track another \n(via the --track argument to "git checkout -b ...").')
return (remote, upstream_branch)
| 3,438,684,381,524,826,600
|
Returns a tuple containing remote and remote ref,
e.g. 'origin', 'refs/heads/master'
|
git_cl.py
|
FetchUpstreamTuple
|
wuyong2k/chromium_depot_tool
|
python
|
@staticmethod
def FetchUpstreamTuple(branch):
"Returns a tuple containing remote and remote ref,\n e.g. 'origin', 'refs/heads/master'\n "
remote = '.'
upstream_branch = RunGit(['config', ('branch.%s.merge' % branch)], error_ok=True).strip()
if upstream_branch:
remote = RunGit(['config', ('branch.%s.remote' % branch)]).strip()
else:
upstream_branch = RunGit(['config', 'rietveld.upstream-branch'], error_ok=True).strip()
if upstream_branch:
remote = RunGit(['config', 'rietveld.upstream-remote']).strip()
elif settings.GetIsGitSvn():
upstream_branch = settings.GetSVNBranch()
else:
remote_branches = RunGit(['branch', '-r']).split()
if ('origin/master' in remote_branches):
remote = 'origin'
upstream_branch = 'refs/heads/master'
elif ('origin/trunk' in remote_branches):
remote = 'origin'
upstream_branch = 'refs/heads/trunk'
else:
DieWithError('Unable to determine default branch to diff against.\nEither pass complete "git diff"-style arguments, like\n git cl upload origin/master\nor verify this branch is set up to track another \n(via the --track argument to "git checkout -b ...").')
return (remote, upstream_branch)
|
def GitSanityChecks(self, upstream_git_obj):
'Checks git repo status and ensures diff is from local commits.'
if (upstream_git_obj is None):
if (self.GetBranch() is None):
print('ERROR: unable to determine current branch (detached HEAD?)', file=sys.stderr)
else:
print('ERROR: no upstream branch', file=sys.stderr)
return False
upstream_sha = RunGit(['rev-parse', '--verify', upstream_git_obj]).strip()
common_ancestor = RunGit(['merge-base', upstream_sha, 'HEAD']).strip()
if (upstream_sha != common_ancestor):
print(('ERROR: %s is not in the current branch. You may need to rebase your tracking branch' % upstream_sha), file=sys.stderr)
return False
commits_in_diff = RunGit(['rev-list', ('^%s' % upstream_sha), 'HEAD']).splitlines()
(code, remote_branch) = RunGitWithCode(['config', 'gitcl.remotebranch'])
remote_branch = remote_branch.strip()
if (code != 0):
(_, remote_branch) = self.GetRemoteBranch()
commits_in_remote = RunGit(['rev-list', ('^%s' % upstream_sha), remote_branch]).splitlines()
common_commits = (set(commits_in_diff) & set(commits_in_remote))
if common_commits:
print(('ERROR: Your diff contains %d commits already in %s.\nRun "git log --oneline %s..HEAD" to get a list of commits in the diff. If you are using a custom git flow, you can override the reference used for this check with "git config gitcl.remotebranch <git-ref>".' % (len(common_commits), remote_branch, upstream_git_obj)), file=sys.stderr)
return False
return True
| 4,551,052,420,264,305,700
|
Checks git repo status and ensures diff is from local commits.
|
git_cl.py
|
GitSanityChecks
|
wuyong2k/chromium_depot_tool
|
python
|
def GitSanityChecks(self, upstream_git_obj):
if (upstream_git_obj is None):
if (self.GetBranch() is None):
print('ERROR: unable to determine current branch (detached HEAD?)', file=sys.stderr)
else:
print('ERROR: no upstream branch', file=sys.stderr)
return False
upstream_sha = RunGit(['rev-parse', '--verify', upstream_git_obj]).strip()
common_ancestor = RunGit(['merge-base', upstream_sha, 'HEAD']).strip()
if (upstream_sha != common_ancestor):
print(('ERROR: %s is not in the current branch. You may need to rebase your tracking branch' % upstream_sha), file=sys.stderr)
return False
commits_in_diff = RunGit(['rev-list', ('^%s' % upstream_sha), 'HEAD']).splitlines()
(code, remote_branch) = RunGitWithCode(['config', 'gitcl.remotebranch'])
remote_branch = remote_branch.strip()
if (code != 0):
(_, remote_branch) = self.GetRemoteBranch()
commits_in_remote = RunGit(['rev-list', ('^%s' % upstream_sha), remote_branch]).splitlines()
common_commits = (set(commits_in_diff) & set(commits_in_remote))
if common_commits:
print(('ERROR: Your diff contains %d commits already in %s.\nRun "git log --oneline %s..HEAD" to get a list of commits in the diff. If you are using a custom git flow, you can override the reference used for this check with "git config gitcl.remotebranch <git-ref>".' % (len(common_commits), remote_branch, upstream_git_obj)), file=sys.stderr)
return False
return True
|
def GetGitBaseUrlFromConfig(self):
'Return the configured base URL from branch.<branchname>.baseurl.\n\n Returns None if it is not set.\n '
return RunGit(['config', ('branch.%s.base-url' % self.GetBranch())], error_ok=True).strip()
| -7,890,018,859,449,928,000
|
Return the configured base URL from branch.<branchname>.baseurl.
Returns None if it is not set.
|
git_cl.py
|
GetGitBaseUrlFromConfig
|
wuyong2k/chromium_depot_tool
|
python
|
def GetGitBaseUrlFromConfig(self):
'Return the configured base URL from branch.<branchname>.baseurl.\n\n Returns None if it is not set.\n '
return RunGit(['config', ('branch.%s.base-url' % self.GetBranch())], error_ok=True).strip()
|
def GetGitSvnRemoteUrl(self):
'Return the configured git-svn remote URL parsed from git svn info.\n\n Returns None if it is not set.\n '
data = RunGit(['svn', 'info'], cwd=settings.GetRoot())
if data:
keys = dict((line.split(': ', 1) for line in data.splitlines() if (': ' in line)))
return keys.get('URL', None)
return None
| -5,987,009,470,614,354,000
|
Return the configured git-svn remote URL parsed from git svn info.
Returns None if it is not set.
|
git_cl.py
|
GetGitSvnRemoteUrl
|
wuyong2k/chromium_depot_tool
|
python
|
def GetGitSvnRemoteUrl(self):
'Return the configured git-svn remote URL parsed from git svn info.\n\n Returns None if it is not set.\n '
data = RunGit(['svn', 'info'], cwd=settings.GetRoot())
if data:
keys = dict((line.split(': ', 1) for line in data.splitlines() if (': ' in line)))
return keys.get('URL', None)
return None
|
def GetRemoteUrl(self):
"Return the configured remote URL, e.g. 'git://example.org/foo.git/'.\n\n Returns None if there is no remote.\n "
(remote, _) = self.GetRemoteBranch()
url = RunGit(['config', ('remote.%s.url' % remote)], error_ok=True).strip()
if os.path.isdir(url):
url = RunGit(['config', ('remote.%s.url' % remote)], error_ok=True, cwd=url).strip()
return url
| -6,965,647,758,296,576,000
|
Return the configured remote URL, e.g. 'git://example.org/foo.git/'.
Returns None if there is no remote.
|
git_cl.py
|
GetRemoteUrl
|
wuyong2k/chromium_depot_tool
|
python
|
def GetRemoteUrl(self):
"Return the configured remote URL, e.g. 'git://example.org/foo.git/'.\n\n Returns None if there is no remote.\n "
(remote, _) = self.GetRemoteBranch()
url = RunGit(['config', ('remote.%s.url' % remote)], error_ok=True).strip()
if os.path.isdir(url):
url = RunGit(['config', ('remote.%s.url' % remote)], error_ok=True, cwd=url).strip()
return url
|
def GetIssue(self):
'Returns the issue number as a int or None if not set.'
if ((self.issue is None) and (not self.lookedup_issue)):
issue = RunGit(['config', self._codereview_impl.IssueSetting(self.GetBranch())], error_ok=True).strip()
self.issue = ((int(issue) or None) if issue else None)
self.lookedup_issue = True
return self.issue
| -2,721,788,952,252,530,700
|
Returns the issue number as a int or None if not set.
|
git_cl.py
|
GetIssue
|
wuyong2k/chromium_depot_tool
|
python
|
def GetIssue(self):
if ((self.issue is None) and (not self.lookedup_issue)):
issue = RunGit(['config', self._codereview_impl.IssueSetting(self.GetBranch())], error_ok=True).strip()
self.issue = ((int(issue) or None) if issue else None)
self.lookedup_issue = True
return self.issue
|
def GetIssueURL(self):
'Get the URL for a particular issue.'
issue = self.GetIssue()
if (not issue):
return None
return ('%s/%s' % (self._codereview_impl.GetCodereviewServer(), issue))
| 5,451,291,022,107,055,000
|
Get the URL for a particular issue.
|
git_cl.py
|
GetIssueURL
|
wuyong2k/chromium_depot_tool
|
python
|
def GetIssueURL(self):
issue = self.GetIssue()
if (not issue):
return None
return ('%s/%s' % (self._codereview_impl.GetCodereviewServer(), issue))
|
def GetPatchset(self):
'Returns the patchset number as a int or None if not set.'
if ((self.patchset is None) and (not self.lookedup_patchset)):
patchset = RunGit(['config', self._codereview_impl.PatchsetSetting()], error_ok=True).strip()
self.patchset = ((int(patchset) or None) if patchset else None)
self.lookedup_patchset = True
return self.patchset
| 8,813,032,372,331,586,000
|
Returns the patchset number as a int or None if not set.
|
git_cl.py
|
GetPatchset
|
wuyong2k/chromium_depot_tool
|
python
|
def GetPatchset(self):
if ((self.patchset is None) and (not self.lookedup_patchset)):
patchset = RunGit(['config', self._codereview_impl.PatchsetSetting()], error_ok=True).strip()
self.patchset = ((int(patchset) or None) if patchset else None)
self.lookedup_patchset = True
return self.patchset
|
def SetPatchset(self, patchset):
"Set this branch's patchset. If patchset=0, clears the patchset."
patchset_setting = self._codereview_impl.PatchsetSetting()
if patchset:
RunGit(['config', patchset_setting, str(patchset)])
self.patchset = patchset
else:
RunGit(['config', '--unset', patchset_setting], stderr=subprocess2.PIPE, error_ok=True)
self.patchset = None
| 707,502,986,647,797,200
|
Set this branch's patchset. If patchset=0, clears the patchset.
|
git_cl.py
|
SetPatchset
|
wuyong2k/chromium_depot_tool
|
python
|
def SetPatchset(self, patchset):
patchset_setting = self._codereview_impl.PatchsetSetting()
if patchset:
RunGit(['config', patchset_setting, str(patchset)])
self.patchset = patchset
else:
RunGit(['config', '--unset', patchset_setting], stderr=subprocess2.PIPE, error_ok=True)
self.patchset = None
|
def SetIssue(self, issue=None):
"Set this branch's issue. If issue isn't given, clears the issue."
issue_setting = self._codereview_impl.IssueSetting(self.GetBranch())
codereview_setting = self._codereview_impl.GetCodereviewServerSetting()
if issue:
self.issue = issue
RunGit(['config', issue_setting, str(issue)])
codereview_server = self._codereview_impl.GetCodereviewServer()
if codereview_server:
RunGit(['config', codereview_setting, codereview_server])
else:
config_settings = [issue_setting, self._codereview_impl.PatchsetSetting()]
for prop in (['last-upload-hash'] + self._codereview_impl._PostUnsetIssueProperties()):
config_settings.append(('branch.%s.%s' % (self.GetBranch(), prop)))
for setting in config_settings:
RunGit(['config', '--unset', setting], error_ok=True)
self.issue = None
self.patchset = None
| 3,311,791,937,509,908,000
|
Set this branch's issue. If issue isn't given, clears the issue.
|
git_cl.py
|
SetIssue
|
wuyong2k/chromium_depot_tool
|
python
|
def SetIssue(self, issue=None):
issue_setting = self._codereview_impl.IssueSetting(self.GetBranch())
codereview_setting = self._codereview_impl.GetCodereviewServerSetting()
if issue:
self.issue = issue
RunGit(['config', issue_setting, str(issue)])
codereview_server = self._codereview_impl.GetCodereviewServer()
if codereview_server:
RunGit(['config', codereview_setting, codereview_server])
else:
config_settings = [issue_setting, self._codereview_impl.PatchsetSetting()]
for prop in (['last-upload-hash'] + self._codereview_impl._PostUnsetIssueProperties()):
config_settings.append(('branch.%s.%s' % (self.GetBranch(), prop)))
for setting in config_settings:
RunGit(['config', '--unset', setting], error_ok=True)
self.issue = None
self.patchset = None
|
def RunHook(self, committing, may_prompt, verbose, change):
'Calls sys.exit() if the hook fails; returns a HookResults otherwise.'
try:
return presubmit_support.DoPresubmitChecks(change, committing, verbose=verbose, output_stream=sys.stdout, input_stream=sys.stdin, default_presubmit=None, may_prompt=may_prompt, rietveld_obj=self._codereview_impl.GetRieveldObjForPresubmit(), gerrit_obj=self._codereview_impl.GetGerritObjForPresubmit())
except presubmit_support.PresubmitFailure as e:
DieWithError(('%s\nMaybe your depot_tools is out of date?\nIf all fails, contact maruel@' % e))
| 165,045,495,008,101,700
|
Calls sys.exit() if the hook fails; returns a HookResults otherwise.
|
git_cl.py
|
RunHook
|
wuyong2k/chromium_depot_tool
|
python
|
def RunHook(self, committing, may_prompt, verbose, change):
try:
return presubmit_support.DoPresubmitChecks(change, committing, verbose=verbose, output_stream=sys.stdout, input_stream=sys.stdin, default_presubmit=None, may_prompt=may_prompt, rietveld_obj=self._codereview_impl.GetRieveldObjForPresubmit(), gerrit_obj=self._codereview_impl.GetGerritObjForPresubmit())
except presubmit_support.PresubmitFailure as e:
DieWithError(('%s\nMaybe your depot_tools is out of date?\nIf all fails, contact maruel@' % e))
|
def CMDPatchIssue(self, issue_arg, reject, nocommit, directory):
'Fetches and applies the issue patch from codereview to local branch.'
if (isinstance(issue_arg, (int, long)) or issue_arg.isdigit()):
parsed_issue_arg = _ParsedIssueNumberArgument(int(issue_arg))
else:
parsed_issue_arg = self._codereview_impl.ParseIssueURL(urlparse.urlparse(issue_arg))
if ((not parsed_issue_arg) or (not parsed_issue_arg.valid)):
DieWithError(('Failed to parse issue argument "%s". Must be an issue number or a valid URL.' % issue_arg))
return self._codereview_impl.CMDPatchWithParsedIssue(parsed_issue_arg, reject, nocommit, directory)
| 4,974,629,712,309,087,000
|
Fetches and applies the issue patch from codereview to local branch.
|
git_cl.py
|
CMDPatchIssue
|
wuyong2k/chromium_depot_tool
|
python
|
def CMDPatchIssue(self, issue_arg, reject, nocommit, directory):
if (isinstance(issue_arg, (int, long)) or issue_arg.isdigit()):
parsed_issue_arg = _ParsedIssueNumberArgument(int(issue_arg))
else:
parsed_issue_arg = self._codereview_impl.ParseIssueURL(urlparse.urlparse(issue_arg))
if ((not parsed_issue_arg) or (not parsed_issue_arg.valid)):
DieWithError(('Failed to parse issue argument "%s". Must be an issue number or a valid URL.' % issue_arg))
return self._codereview_impl.CMDPatchWithParsedIssue(parsed_issue_arg, reject, nocommit, directory)
|
def CMDUpload(self, options, git_diff_args, orig_args):
'Uploads a change to codereview.'
if git_diff_args:
base_branch = git_diff_args[0]
else:
if (self.GetBranch() is None):
DieWithError("Can't upload from detached HEAD state. Get on a branch!")
base_branch = self.GetCommonAncestorWithUpstream()
git_diff_args = [base_branch, 'HEAD']
self._codereview_impl.EnsureAuthenticated(force=options.force)
change = self.GetChange(base_branch, None)
watchlist = watchlists.Watchlists(change.RepositoryRoot())
files = [f.LocalPath() for f in change.AffectedFiles()]
if (not options.bypass_watchlists):
self.SetWatchers(watchlist.GetWatchersForPaths(files))
if (not options.bypass_hooks):
if (options.reviewers or options.tbr_owners):
change_description = ChangeDescription(change.FullDescriptionText())
change_description.update_reviewers(options.reviewers, options.tbr_owners, change)
change.SetDescriptionText(change_description.description)
hook_results = self.RunHook(committing=False, may_prompt=(not options.force), verbose=options.verbose, change=change)
if (not hook_results.should_continue()):
return 1
if ((not options.reviewers) and hook_results.reviewers):
options.reviewers = hook_results.reviewers.split(',')
if self.GetIssue():
latest_patchset = self.GetMostRecentPatchset()
local_patchset = self.GetPatchset()
if (latest_patchset and local_patchset and (local_patchset != latest_patchset)):
print(('The last upload made from this repository was patchset #%d but the most recent patchset on the server is #%d.' % (local_patchset, latest_patchset)))
print("Uploading will still work, but if you've uploaded to this issue from another machine or branch the patch you're uploading now might not include those changes.")
ask_for_data('About to upload; enter to confirm.')
print_stats(options.similarity, options.find_copies, git_diff_args)
ret = self.CMDUploadChange(options, git_diff_args, change)
if (not ret):
git_set_branch_value('last-upload-hash', RunGit(['rev-parse', 'HEAD']).strip())
if settings.GetRunPostUploadHook():
presubmit_support.DoPostUploadExecuter(change, self, settings.GetRoot(), options.verbose, sys.stdout)
if options.dependencies:
print()
print('--dependencies has been specified.')
print('All dependent local branches will be re-uploaded.')
print()
orig_args.remove('--dependencies')
ret = upload_branch_deps(self, orig_args)
return ret
| -7,557,256,267,665,093,000
|
Uploads a change to codereview.
|
git_cl.py
|
CMDUpload
|
wuyong2k/chromium_depot_tool
|
python
|
def CMDUpload(self, options, git_diff_args, orig_args):
if git_diff_args:
base_branch = git_diff_args[0]
else:
if (self.GetBranch() is None):
DieWithError("Can't upload from detached HEAD state. Get on a branch!")
base_branch = self.GetCommonAncestorWithUpstream()
git_diff_args = [base_branch, 'HEAD']
self._codereview_impl.EnsureAuthenticated(force=options.force)
change = self.GetChange(base_branch, None)
watchlist = watchlists.Watchlists(change.RepositoryRoot())
files = [f.LocalPath() for f in change.AffectedFiles()]
if (not options.bypass_watchlists):
self.SetWatchers(watchlist.GetWatchersForPaths(files))
if (not options.bypass_hooks):
if (options.reviewers or options.tbr_owners):
change_description = ChangeDescription(change.FullDescriptionText())
change_description.update_reviewers(options.reviewers, options.tbr_owners, change)
change.SetDescriptionText(change_description.description)
hook_results = self.RunHook(committing=False, may_prompt=(not options.force), verbose=options.verbose, change=change)
if (not hook_results.should_continue()):
return 1
if ((not options.reviewers) and hook_results.reviewers):
options.reviewers = hook_results.reviewers.split(',')
if self.GetIssue():
latest_patchset = self.GetMostRecentPatchset()
local_patchset = self.GetPatchset()
if (latest_patchset and local_patchset and (local_patchset != latest_patchset)):
print(('The last upload made from this repository was patchset #%d but the most recent patchset on the server is #%d.' % (local_patchset, latest_patchset)))
print("Uploading will still work, but if you've uploaded to this issue from another machine or branch the patch you're uploading now might not include those changes.")
ask_for_data('About to upload; enter to confirm.')
print_stats(options.similarity, options.find_copies, git_diff_args)
ret = self.CMDUploadChange(options, git_diff_args, change)
if (not ret):
git_set_branch_value('last-upload-hash', RunGit(['rev-parse', 'HEAD']).strip())
if settings.GetRunPostUploadHook():
presubmit_support.DoPostUploadExecuter(change, self, settings.GetRoot(), options.verbose, sys.stdout)
if options.dependencies:
print()
print('--dependencies has been specified.')
print('All dependent local branches will be re-uploaded.')
print()
orig_args.remove('--dependencies')
ret = upload_branch_deps(self, orig_args)
return ret
|
def SetCQState(self, new_state):
'Update the CQ state for latest patchset.\n\n Issue must have been already uploaded and known.\n '
assert (new_state in _CQState.ALL_STATES)
assert self.GetIssue()
return self._codereview_impl.SetCQState(new_state)
| 4,467,814,156,745,606,000
|
Update the CQ state for latest patchset.
Issue must have been already uploaded and known.
|
git_cl.py
|
SetCQState
|
wuyong2k/chromium_depot_tool
|
python
|
def SetCQState(self, new_state):
'Update the CQ state for latest patchset.\n\n Issue must have been already uploaded and known.\n '
assert (new_state in _CQState.ALL_STATES)
assert self.GetIssue()
return self._codereview_impl.SetCQState(new_state)
|
def GetStatus(self):
"Apply a rough heuristic to give a simple summary of an issue's review\n or CQ status, assuming adherence to a common workflow.\n\n Returns None if no issue for this branch, or specific string keywords.\n "
raise NotImplementedError()
| 6,329,365,881,695,162,000
|
Apply a rough heuristic to give a simple summary of an issue's review
or CQ status, assuming adherence to a common workflow.
Returns None if no issue for this branch, or specific string keywords.
|
git_cl.py
|
GetStatus
|
wuyong2k/chromium_depot_tool
|
python
|
def GetStatus(self):
"Apply a rough heuristic to give a simple summary of an issue's review\n or CQ status, assuming adherence to a common workflow.\n\n Returns None if no issue for this branch, or specific string keywords.\n "
raise NotImplementedError()
|
def GetCodereviewServer(self):
'Returns server URL without end slash, like "https://codereview.com".'
raise NotImplementedError()
| -6,283,354,262,252,491,000
|
Returns server URL without end slash, like "https://codereview.com".
|
git_cl.py
|
GetCodereviewServer
|
wuyong2k/chromium_depot_tool
|
python
|
def GetCodereviewServer(self):
raise NotImplementedError()
|
def FetchDescription(self):
'Fetches and returns description from the codereview server.'
raise NotImplementedError()
| 683,693,468,192,395,600
|
Fetches and returns description from the codereview server.
|
git_cl.py
|
FetchDescription
|
wuyong2k/chromium_depot_tool
|
python
|
def FetchDescription(self):
raise NotImplementedError()
|
def GetCodereviewServerSetting(self):
'Returns git config setting for the codereview server.'
raise NotImplementedError()
| -8,951,700,844,428,134,000
|
Returns git config setting for the codereview server.
|
git_cl.py
|
GetCodereviewServerSetting
|
wuyong2k/chromium_depot_tool
|
python
|
def GetCodereviewServerSetting(self):
raise NotImplementedError()
|
@classmethod
def IssueSettingSuffix(cls):
'Returns name of git config setting which stores issue number for a given\n branch.'
raise NotImplementedError()
| -7,071,520,134,023,710,000
|
Returns name of git config setting which stores issue number for a given
branch.
|
git_cl.py
|
IssueSettingSuffix
|
wuyong2k/chromium_depot_tool
|
python
|
@classmethod
def IssueSettingSuffix(cls):
'Returns name of git config setting which stores issue number for a given\n branch.'
raise NotImplementedError()
|
def PatchsetSetting(self):
'Returns name of git config setting which stores issue number.'
raise NotImplementedError()
| -4,430,877,442,446,300,000
|
Returns name of git config setting which stores issue number.
|
git_cl.py
|
PatchsetSetting
|
wuyong2k/chromium_depot_tool
|
python
|
def PatchsetSetting(self):
raise NotImplementedError()
|
def _PostUnsetIssueProperties(self):
'Which branch-specific properties to erase when unsettin issue.'
raise NotImplementedError()
| 4,685,999,962,814,047,000
|
Which branch-specific properties to erase when unsettin issue.
|
git_cl.py
|
_PostUnsetIssueProperties
|
wuyong2k/chromium_depot_tool
|
python
|
def _PostUnsetIssueProperties(self):
raise NotImplementedError()
|
def UpdateDescriptionRemote(self, description):
'Update the description on codereview site.'
raise NotImplementedError()
| -7,340,033,275,796,108,000
|
Update the description on codereview site.
|
git_cl.py
|
UpdateDescriptionRemote
|
wuyong2k/chromium_depot_tool
|
python
|
def UpdateDescriptionRemote(self, description):
raise NotImplementedError()
|
def CloseIssue(self):
'Closes the issue.'
raise NotImplementedError()
| -8,431,182,191,379,887,000
|
Closes the issue.
|
git_cl.py
|
CloseIssue
|
wuyong2k/chromium_depot_tool
|
python
|
def CloseIssue(self):
raise NotImplementedError()
|
def GetApprovingReviewers(self):
'Returns a list of reviewers approving the change.\n\n Note: not necessarily committers.\n '
raise NotImplementedError()
| 2,777,351,221,320,171,000
|
Returns a list of reviewers approving the change.
Note: not necessarily committers.
|
git_cl.py
|
GetApprovingReviewers
|
wuyong2k/chromium_depot_tool
|
python
|
def GetApprovingReviewers(self):
'Returns a list of reviewers approving the change.\n\n Note: not necessarily committers.\n '
raise NotImplementedError()
|
def GetMostRecentPatchset(self):
'Returns the most recent patchset number from the codereview site.'
raise NotImplementedError()
| -69,695,029,279,877,080
|
Returns the most recent patchset number from the codereview site.
|
git_cl.py
|
GetMostRecentPatchset
|
wuyong2k/chromium_depot_tool
|
python
|
def GetMostRecentPatchset(self):
raise NotImplementedError()
|
def CMDPatchWithParsedIssue(self, parsed_issue_arg, reject, nocommit, directory):
'Fetches and applies the issue.\n\n Arguments:\n parsed_issue_arg: instance of _ParsedIssueNumberArgument.\n reject: if True, reject the failed patch instead of switching to 3-way\n merge. Rietveld only.\n nocommit: do not commit the patch, thus leave the tree dirty. Rietveld\n only.\n directory: switch to directory before applying the patch. Rietveld only.\n '
raise NotImplementedError()
| 1,090,445,375,256,550,700
|
Fetches and applies the issue.
Arguments:
parsed_issue_arg: instance of _ParsedIssueNumberArgument.
reject: if True, reject the failed patch instead of switching to 3-way
merge. Rietveld only.
nocommit: do not commit the patch, thus leave the tree dirty. Rietveld
only.
directory: switch to directory before applying the patch. Rietveld only.
|
git_cl.py
|
CMDPatchWithParsedIssue
|
wuyong2k/chromium_depot_tool
|
python
|
def CMDPatchWithParsedIssue(self, parsed_issue_arg, reject, nocommit, directory):
'Fetches and applies the issue.\n\n Arguments:\n parsed_issue_arg: instance of _ParsedIssueNumberArgument.\n reject: if True, reject the failed patch instead of switching to 3-way\n merge. Rietveld only.\n nocommit: do not commit the patch, thus leave the tree dirty. Rietveld\n only.\n directory: switch to directory before applying the patch. Rietveld only.\n '
raise NotImplementedError()
|
@staticmethod
def ParseIssueURL(parsed_url):
'Parses url and returns instance of _ParsedIssueNumberArgument or None if\n failed.'
raise NotImplementedError()
| 3,797,609,221,604,850,000
|
Parses url and returns instance of _ParsedIssueNumberArgument or None if
failed.
|
git_cl.py
|
ParseIssueURL
|
wuyong2k/chromium_depot_tool
|
python
|
@staticmethod
def ParseIssueURL(parsed_url):
'Parses url and returns instance of _ParsedIssueNumberArgument or None if\n failed.'
raise NotImplementedError()
|
def EnsureAuthenticated(self, force):
'Best effort check that user is authenticated with codereview server.\n\n Arguments:\n force: whether to skip confirmation questions.\n '
raise NotImplementedError()
| -8,503,028,676,478,826,000
|
Best effort check that user is authenticated with codereview server.
Arguments:
force: whether to skip confirmation questions.
|
git_cl.py
|
EnsureAuthenticated
|
wuyong2k/chromium_depot_tool
|
python
|
def EnsureAuthenticated(self, force):
'Best effort check that user is authenticated with codereview server.\n\n Arguments:\n force: whether to skip confirmation questions.\n '
raise NotImplementedError()
|
def CMDUploadChange(self, options, args, change):
'Uploads a change to codereview.'
raise NotImplementedError()
| 8,035,336,178,282,116,000
|
Uploads a change to codereview.
|
git_cl.py
|
CMDUploadChange
|
wuyong2k/chromium_depot_tool
|
python
|
def CMDUploadChange(self, options, args, change):
raise NotImplementedError()
|
def SetCQState(self, new_state):
'Update the CQ state for latest patchset.\n\n Issue must have been already uploaded and known.\n '
raise NotImplementedError()
| -6,356,504,941,651,309,000
|
Update the CQ state for latest patchset.
Issue must have been already uploaded and known.
|
git_cl.py
|
SetCQState
|
wuyong2k/chromium_depot_tool
|
python
|
def SetCQState(self, new_state):
'Update the CQ state for latest patchset.\n\n Issue must have been already uploaded and known.\n '
raise NotImplementedError()
|
def EnsureAuthenticated(self, force):
'Best effort check that user is authenticated with Rietveld server.'
if self._auth_config.use_oauth2:
authenticator = auth.get_authenticator_for_host(self.GetCodereviewServer(), self._auth_config)
if (not authenticator.has_cached_credentials()):
raise auth.LoginRequiredError(self.GetCodereviewServer())
| 8,550,876,920,952,164,000
|
Best effort check that user is authenticated with Rietveld server.
|
git_cl.py
|
EnsureAuthenticated
|
wuyong2k/chromium_depot_tool
|
python
|
def EnsureAuthenticated(self, force):
if self._auth_config.use_oauth2:
authenticator = auth.get_authenticator_for_host(self.GetCodereviewServer(), self._auth_config)
if (not authenticator.has_cached_credentials()):
raise auth.LoginRequiredError(self.GetCodereviewServer())
|
def GetStatus(self):
"Apply a rough heuristic to give a simple summary of an issue's review\n or CQ status, assuming adherence to a common workflow.\n\n Returns None if no issue for this branch, or one of the following keywords:\n * 'error' - error from review tool (including deleted issues)\n * 'unsent' - not sent for review\n * 'waiting' - waiting for review\n * 'reply' - waiting for owner to reply to review\n * 'lgtm' - LGTM from at least one approved reviewer\n * 'commit' - in the commit queue\n * 'closed' - closed\n "
if (not self.GetIssue()):
return None
try:
props = self.GetIssueProperties()
except urllib2.HTTPError:
return 'error'
if props.get('closed'):
return 'closed'
if (props.get('commit') and (not props.get('cq_dry_run', False))):
return 'commit'
try:
reviewers = self.GetApprovingReviewers()
except urllib2.HTTPError:
return 'error'
if reviewers:
return 'lgtm'
messages = (props.get('messages') or [])
while (messages and (messages[(- 1)]['sender'] == COMMIT_BOT_EMAIL)):
if ('Dry run:' in messages[(- 1)]['text']):
messages.pop()
elif ('The CQ bit was unchecked' in messages[(- 1)]['text']):
messages.pop()
else:
break
if (not messages):
return 'unsent'
if (messages[(- 1)]['sender'] != props.get('owner_email')):
return 'reply'
return 'waiting'
| -6,504,038,583,646,839,000
|
Apply a rough heuristic to give a simple summary of an issue's review
or CQ status, assuming adherence to a common workflow.
Returns None if no issue for this branch, or one of the following keywords:
* 'error' - error from review tool (including deleted issues)
* 'unsent' - not sent for review
* 'waiting' - waiting for review
* 'reply' - waiting for owner to reply to review
* 'lgtm' - LGTM from at least one approved reviewer
* 'commit' - in the commit queue
* 'closed' - closed
|
git_cl.py
|
GetStatus
|
wuyong2k/chromium_depot_tool
|
python
|
def GetStatus(self):
"Apply a rough heuristic to give a simple summary of an issue's review\n or CQ status, assuming adherence to a common workflow.\n\n Returns None if no issue for this branch, or one of the following keywords:\n * 'error' - error from review tool (including deleted issues)\n * 'unsent' - not sent for review\n * 'waiting' - waiting for review\n * 'reply' - waiting for owner to reply to review\n * 'lgtm' - LGTM from at least one approved reviewer\n * 'commit' - in the commit queue\n * 'closed' - closed\n "
if (not self.GetIssue()):
return None
try:
props = self.GetIssueProperties()
except urllib2.HTTPError:
return 'error'
if props.get('closed'):
return 'closed'
if (props.get('commit') and (not props.get('cq_dry_run', False))):
return 'commit'
try:
reviewers = self.GetApprovingReviewers()
except urllib2.HTTPError:
return 'error'
if reviewers:
return 'lgtm'
messages = (props.get('messages') or [])
while (messages and (messages[(- 1)]['sender'] == COMMIT_BOT_EMAIL)):
if ('Dry run:' in messages[(- 1)]['text']):
messages.pop()
elif ('The CQ bit was unchecked' in messages[(- 1)]['text']):
messages.pop()
else:
break
if (not messages):
return 'unsent'
if (messages[(- 1)]['sender'] != props.get('owner_email')):
return 'reply'
return 'waiting'
|
def SetFlag(self, flag, value):
'Patchset must match.'
if (not self.GetPatchset()):
DieWithError('The patchset needs to match. Send another patchset.')
try:
return self.RpcServer().set_flag(self.GetIssue(), self.GetPatchset(), flag, value)
except urllib2.HTTPError as e:
if (e.code == 404):
DieWithError(("The issue %s doesn't exist." % self.GetIssue()))
if (e.code == 403):
DieWithError(("Access denied to issue %s. Maybe the patchset %s doesn't match?" % (self.GetIssue(), self.GetPatchset())))
raise
| -2,922,904,480,073,585,700
|
Patchset must match.
|
git_cl.py
|
SetFlag
|
wuyong2k/chromium_depot_tool
|
python
|
def SetFlag(self, flag, value):
if (not self.GetPatchset()):
DieWithError('The patchset needs to match. Send another patchset.')
try:
return self.RpcServer().set_flag(self.GetIssue(), self.GetPatchset(), flag, value)
except urllib2.HTTPError as e:
if (e.code == 404):
DieWithError(("The issue %s doesn't exist." % self.GetIssue()))
if (e.code == 403):
DieWithError(("Access denied to issue %s. Maybe the patchset %s doesn't match?" % (self.GetIssue(), self.GetPatchset())))
raise
|
def RpcServer(self):
"Returns an upload.RpcServer() to access this review's rietveld instance.\n "
if (not self._rpc_server):
self._rpc_server = rietveld.CachingRietveld(self.GetCodereviewServer(), (self._auth_config or auth.make_auth_config()))
return self._rpc_server
| -5,865,990,408,082,371,000
|
Returns an upload.RpcServer() to access this review's rietveld instance.
|
git_cl.py
|
RpcServer
|
wuyong2k/chromium_depot_tool
|
python
|
def RpcServer(self):
"\n "
if (not self._rpc_server):
self._rpc_server = rietveld.CachingRietveld(self.GetCodereviewServer(), (self._auth_config or auth.make_auth_config()))
return self._rpc_server
|
def PatchsetSetting(self):
"Return the git setting that stores this change's most recent patchset."
return ('branch.%s.rietveldpatchset' % self.GetBranch())
| -8,972,197,271,422,346,000
|
Return the git setting that stores this change's most recent patchset.
|
git_cl.py
|
PatchsetSetting
|
wuyong2k/chromium_depot_tool
|
python
|
def PatchsetSetting(self):
return ('branch.%s.rietveldpatchset' % self.GetBranch())
|
def GetCodereviewServerSetting(self):
"Returns the git setting that stores this change's rietveld server."
branch = self.GetBranch()
if branch:
return ('branch.%s.rietveldserver' % branch)
return None
| -4,057,608,187,407,304,700
|
Returns the git setting that stores this change's rietveld server.
|
git_cl.py
|
GetCodereviewServerSetting
|
wuyong2k/chromium_depot_tool
|
python
|
def GetCodereviewServerSetting(self):
branch = self.GetBranch()
if branch:
return ('branch.%s.rietveldserver' % branch)
return None
|
def _PostUnsetIssueProperties(self):
'Which branch-specific properties to erase when unsetting issue.'
return ['rietveldserver']
| 6,426,913,963,738,132,000
|
Which branch-specific properties to erase when unsetting issue.
|
git_cl.py
|
_PostUnsetIssueProperties
|
wuyong2k/chromium_depot_tool
|
python
|
def _PostUnsetIssueProperties(self):
return ['rietveldserver']
|
def CMDUploadChange(self, options, args, change):
'Upload the patch to Rietveld.'
upload_args = ['--assume_yes']
upload_args.extend(['--server', self.GetCodereviewServer()])
upload_args.extend(auth.auth_config_to_command_options(self._auth_config))
if options.emulate_svn_auto_props:
upload_args.append('--emulate_svn_auto_props')
change_desc = None
if (options.email is not None):
upload_args.extend(['--email', options.email])
if self.GetIssue():
if options.title:
upload_args.extend(['--title', options.title])
if options.message:
upload_args.extend(['--message', options.message])
upload_args.extend(['--issue', str(self.GetIssue())])
print(('This branch is associated with issue %s. Adding patch to that issue.' % self.GetIssue()))
else:
if options.title:
upload_args.extend(['--title', options.title])
message = (options.title or options.message or CreateDescriptionFromLog(args))
change_desc = ChangeDescription(message)
if (options.reviewers or options.tbr_owners):
change_desc.update_reviewers(options.reviewers, options.tbr_owners, change)
if (not options.force):
change_desc.prompt()
if (not change_desc.description):
print('Description is empty; aborting.')
return 1
upload_args.extend(['--message', change_desc.description])
if change_desc.get_reviewers():
upload_args.append(('--reviewers=%s' % ','.join(change_desc.get_reviewers())))
if options.send_mail:
if (not change_desc.get_reviewers()):
DieWithError('Must specify reviewers to send email.')
upload_args.append('--send_mail')
if options.private:
logging.warn('rietveld.cc is ignored since private flag is specified. You need to review and add them manually if necessary.')
cc = self.GetCCListWithoutDefault()
else:
cc = self.GetCCList()
cc = ','.join(filter(None, (cc, ','.join(options.cc))))
if cc:
upload_args.extend(['--cc', cc])
if (options.private or (settings.GetDefaultPrivateFlag() == 'True')):
upload_args.append('--private')
upload_args.extend(['--git_similarity', str(options.similarity)])
if (not options.find_copies):
upload_args.extend(['--git_no_find_copies'])
remote_url = self.GetGitBaseUrlFromConfig()
if (not remote_url):
if settings.GetIsGitSvn():
remote_url = self.GetGitSvnRemoteUrl()
elif (self.GetRemoteUrl() and ('/' in self.GetUpstreamBranch())):
remote_url = ('%s@%s' % (self.GetRemoteUrl(), self.GetUpstreamBranch().split('/')[(- 1)]))
if remote_url:
upload_args.extend(['--base_url', remote_url])
(remote, remote_branch) = self.GetRemoteBranch()
target_ref = GetTargetRef(remote, remote_branch, options.target_branch, settings.GetPendingRefPrefix())
if target_ref:
upload_args.extend(['--target_ref', target_ref])
(remote, upstream_branch) = self.FetchUpstreamTuple(self.GetBranch())
upstream_branch = ShortBranchName(upstream_branch)
if (remote is '.'):
local_branch = upstream_branch
if settings.GetIsSkipDependencyUpload(local_branch):
print()
print(('Skipping dependency patchset upload because git config branch.%s.skip-deps-uploads is set to True.' % local_branch))
print()
else:
auth_config = auth.extract_auth_config_from_options(options)
branch_cl = Changelist(branchref=('refs/heads/' + local_branch), auth_config=auth_config)
branch_cl_issue_url = branch_cl.GetIssueURL()
branch_cl_issue = branch_cl.GetIssue()
branch_cl_patchset = branch_cl.GetPatchset()
if (branch_cl_issue_url and branch_cl_issue and branch_cl_patchset):
upload_args.extend(['--depends_on_patchset', ('%s:%s' % (branch_cl_issue, branch_cl_patchset))])
print(('\nThe current branch (%s) is tracking a local branch (%s) with an associated CL.\nAdding %s/#ps%s as a dependency patchset.\n\n' % (self.GetBranch(), local_branch, branch_cl_issue_url, branch_cl_patchset)))
project = settings.GetProject()
if project:
upload_args.extend(['--project', project])
if options.cq_dry_run:
upload_args.extend(['--cq_dry_run'])
try:
upload_args = ((['upload'] + upload_args) + args)
logging.info('upload.RealMain(%s)', upload_args)
(issue, patchset) = upload.RealMain(upload_args)
issue = int(issue)
patchset = int(patchset)
except KeyboardInterrupt:
sys.exit(1)
except:
if change_desc:
backup_path = os.path.expanduser(DESCRIPTION_BACKUP_FILE)
print(('\nGot exception while uploading -- saving description to %s\n' % backup_path))
backup_file = open(backup_path, 'w')
backup_file.write(change_desc.description)
backup_file.close()
raise
if (not self.GetIssue()):
self.SetIssue(issue)
self.SetPatchset(patchset)
if options.use_commit_queue:
self.SetCQState(_CQState.COMMIT)
return 0
| 4,221,466,073,041,626,600
|
Upload the patch to Rietveld.
|
git_cl.py
|
CMDUploadChange
|
wuyong2k/chromium_depot_tool
|
python
|
def CMDUploadChange(self, options, args, change):
upload_args = ['--assume_yes']
upload_args.extend(['--server', self.GetCodereviewServer()])
upload_args.extend(auth.auth_config_to_command_options(self._auth_config))
if options.emulate_svn_auto_props:
upload_args.append('--emulate_svn_auto_props')
change_desc = None
if (options.email is not None):
upload_args.extend(['--email', options.email])
if self.GetIssue():
if options.title:
upload_args.extend(['--title', options.title])
if options.message:
upload_args.extend(['--message', options.message])
upload_args.extend(['--issue', str(self.GetIssue())])
print(('This branch is associated with issue %s. Adding patch to that issue.' % self.GetIssue()))
else:
if options.title:
upload_args.extend(['--title', options.title])
message = (options.title or options.message or CreateDescriptionFromLog(args))
change_desc = ChangeDescription(message)
if (options.reviewers or options.tbr_owners):
change_desc.update_reviewers(options.reviewers, options.tbr_owners, change)
if (not options.force):
change_desc.prompt()
if (not change_desc.description):
print('Description is empty; aborting.')
return 1
upload_args.extend(['--message', change_desc.description])
if change_desc.get_reviewers():
upload_args.append(('--reviewers=%s' % ','.join(change_desc.get_reviewers())))
if options.send_mail:
if (not change_desc.get_reviewers()):
DieWithError('Must specify reviewers to send email.')
upload_args.append('--send_mail')
if options.private:
logging.warn('rietveld.cc is ignored since private flag is specified. You need to review and add them manually if necessary.')
cc = self.GetCCListWithoutDefault()
else:
cc = self.GetCCList()
cc = ','.join(filter(None, (cc, ','.join(options.cc))))
if cc:
upload_args.extend(['--cc', cc])
if (options.private or (settings.GetDefaultPrivateFlag() == 'True')):
upload_args.append('--private')
upload_args.extend(['--git_similarity', str(options.similarity)])
if (not options.find_copies):
upload_args.extend(['--git_no_find_copies'])
remote_url = self.GetGitBaseUrlFromConfig()
if (not remote_url):
if settings.GetIsGitSvn():
remote_url = self.GetGitSvnRemoteUrl()
elif (self.GetRemoteUrl() and ('/' in self.GetUpstreamBranch())):
remote_url = ('%s@%s' % (self.GetRemoteUrl(), self.GetUpstreamBranch().split('/')[(- 1)]))
if remote_url:
upload_args.extend(['--base_url', remote_url])
(remote, remote_branch) = self.GetRemoteBranch()
target_ref = GetTargetRef(remote, remote_branch, options.target_branch, settings.GetPendingRefPrefix())
if target_ref:
upload_args.extend(['--target_ref', target_ref])
(remote, upstream_branch) = self.FetchUpstreamTuple(self.GetBranch())
upstream_branch = ShortBranchName(upstream_branch)
if (remote is '.'):
local_branch = upstream_branch
if settings.GetIsSkipDependencyUpload(local_branch):
print()
print(('Skipping dependency patchset upload because git config branch.%s.skip-deps-uploads is set to True.' % local_branch))
print()
else:
auth_config = auth.extract_auth_config_from_options(options)
branch_cl = Changelist(branchref=('refs/heads/' + local_branch), auth_config=auth_config)
branch_cl_issue_url = branch_cl.GetIssueURL()
branch_cl_issue = branch_cl.GetIssue()
branch_cl_patchset = branch_cl.GetPatchset()
if (branch_cl_issue_url and branch_cl_issue and branch_cl_patchset):
upload_args.extend(['--depends_on_patchset', ('%s:%s' % (branch_cl_issue, branch_cl_patchset))])
print(('\nThe current branch (%s) is tracking a local branch (%s) with an associated CL.\nAdding %s/#ps%s as a dependency patchset.\n\n' % (self.GetBranch(), local_branch, branch_cl_issue_url, branch_cl_patchset)))
project = settings.GetProject()
if project:
upload_args.extend(['--project', project])
if options.cq_dry_run:
upload_args.extend(['--cq_dry_run'])
try:
upload_args = ((['upload'] + upload_args) + args)
logging.info('upload.RealMain(%s)', upload_args)
(issue, patchset) = upload.RealMain(upload_args)
issue = int(issue)
patchset = int(patchset)
except KeyboardInterrupt:
sys.exit(1)
except:
if change_desc:
backup_path = os.path.expanduser(DESCRIPTION_BACKUP_FILE)
print(('\nGot exception while uploading -- saving description to %s\n' % backup_path))
backup_file = open(backup_path, 'w')
backup_file.write(change_desc.description)
backup_file.close()
raise
if (not self.GetIssue()):
self.SetIssue(issue)
self.SetPatchset(patchset)
if options.use_commit_queue:
self.SetCQState(_CQState.COMMIT)
return 0
|
def _GetGitHost(self):
'Returns git host to be used when uploading change to Gerrit.'
return urlparse.urlparse(self.GetRemoteUrl()).netloc
| -2,931,209,852,958,704,000
|
Returns git host to be used when uploading change to Gerrit.
|
git_cl.py
|
_GetGitHost
|
wuyong2k/chromium_depot_tool
|
python
|
def _GetGitHost(self):
return urlparse.urlparse(self.GetRemoteUrl()).netloc
|
def EnsureAuthenticated(self, force):
'Best effort check that user is authenticated with Gerrit server.'
if settings.GetGerritSkipEnsureAuthenticated():
return
if gerrit_util.GceAuthenticator.is_gce():
return
self.GetCodereviewServer()
git_host = self._GetGitHost()
assert (self._gerrit_server and self._gerrit_host)
cookie_auth = gerrit_util.CookiesAuthenticator()
gerrit_auth = cookie_auth.get_auth_header(self._gerrit_host)
git_auth = cookie_auth.get_auth_header(git_host)
if (gerrit_auth and git_auth):
if (gerrit_auth == git_auth):
return
print(('WARNING: you have different credentials for Gerrit and git hosts.\n Check your %s or %s file for credentials of hosts:\n %s\n %s\n %s' % (cookie_auth.get_gitcookies_path(), cookie_auth.get_netrc_path(), git_host, self._gerrit_host, cookie_auth.get_new_password_message(git_host))))
if (not force):
ask_for_data('If you know what you are doing, press Enter to continue, Ctrl+C to abort.')
return
else:
missing = ([] if gerrit_auth else (([self._gerrit_host] + []) if git_auth else [git_host]))
DieWithError(('Credentials for the following hosts are required:\n %s\nThese are read from %s (or legacy %s)\n%s' % ('\n '.join(missing), cookie_auth.get_gitcookies_path(), cookie_auth.get_netrc_path(), cookie_auth.get_new_password_message(git_host))))
| 2,260,168,958,560,955,000
|
Best effort check that user is authenticated with Gerrit server.
|
git_cl.py
|
EnsureAuthenticated
|
wuyong2k/chromium_depot_tool
|
python
|
def EnsureAuthenticated(self, force):
if settings.GetGerritSkipEnsureAuthenticated():
return
if gerrit_util.GceAuthenticator.is_gce():
return
self.GetCodereviewServer()
git_host = self._GetGitHost()
assert (self._gerrit_server and self._gerrit_host)
cookie_auth = gerrit_util.CookiesAuthenticator()
gerrit_auth = cookie_auth.get_auth_header(self._gerrit_host)
git_auth = cookie_auth.get_auth_header(git_host)
if (gerrit_auth and git_auth):
if (gerrit_auth == git_auth):
return
print(('WARNING: you have different credentials for Gerrit and git hosts.\n Check your %s or %s file for credentials of hosts:\n %s\n %s\n %s' % (cookie_auth.get_gitcookies_path(), cookie_auth.get_netrc_path(), git_host, self._gerrit_host, cookie_auth.get_new_password_message(git_host))))
if (not force):
ask_for_data('If you know what you are doing, press Enter to continue, Ctrl+C to abort.')
return
else:
missing = ([] if gerrit_auth else (([self._gerrit_host] + []) if git_auth else [git_host]))
DieWithError(('Credentials for the following hosts are required:\n %s\nThese are read from %s (or legacy %s)\n%s' % ('\n '.join(missing), cookie_auth.get_gitcookies_path(), cookie_auth.get_netrc_path(), cookie_auth.get_new_password_message(git_host))))
|
def PatchsetSetting(self):
"Return the git setting that stores this change's most recent patchset."
return ('branch.%s.gerritpatchset' % self.GetBranch())
| 5,591,027,276,532,097,000
|
Return the git setting that stores this change's most recent patchset.
|
git_cl.py
|
PatchsetSetting
|
wuyong2k/chromium_depot_tool
|
python
|
def PatchsetSetting(self):
return ('branch.%s.gerritpatchset' % self.GetBranch())
|
def GetCodereviewServerSetting(self):
"Returns the git setting that stores this change's Gerrit server."
branch = self.GetBranch()
if branch:
return ('branch.%s.gerritserver' % branch)
return None
| 6,454,964,620,202,646,000
|
Returns the git setting that stores this change's Gerrit server.
|
git_cl.py
|
GetCodereviewServerSetting
|
wuyong2k/chromium_depot_tool
|
python
|
def GetCodereviewServerSetting(self):
branch = self.GetBranch()
if branch:
return ('branch.%s.gerritserver' % branch)
return None
|
def _PostUnsetIssueProperties(self):
'Which branch-specific properties to erase when unsetting issue.'
return ['gerritserver', 'gerritsquashhash']
| -7,306,721,975,579,348,000
|
Which branch-specific properties to erase when unsetting issue.
|
git_cl.py
|
_PostUnsetIssueProperties
|
wuyong2k/chromium_depot_tool
|
python
|
def _PostUnsetIssueProperties(self):
return ['gerritserver', 'gerritsquashhash']
|
def GetStatus(self):
"Apply a rough heuristic to give a simple summary of an issue's review\n or CQ status, assuming adherence to a common workflow.\n\n Returns None if no issue for this branch, or one of the following keywords:\n * 'error' - error from review tool (including deleted issues)\n * 'unsent' - no reviewers added\n * 'waiting' - waiting for review\n * 'reply' - waiting for owner to reply to review\n * 'not lgtm' - Code-Review -2 from at least one approved reviewer\n * 'lgtm' - Code-Review +2 from at least one approved reviewer\n * 'commit' - in the commit queue\n * 'closed' - abandoned\n "
if (not self.GetIssue()):
return None
try:
data = self._GetChangeDetail(['DETAILED_LABELS', 'CURRENT_REVISION'])
except httplib.HTTPException:
return 'error'
if (data['status'] in ('ABANDONED', 'MERGED')):
return 'closed'
cq_label = data['labels'].get('Commit-Queue', {})
if cq_label:
vote_value = cq_label.get('value', '0')
vote_text = cq_label.get('values', {}).get(vote_value, '')
if (vote_text.lower() == 'commit'):
return 'commit'
lgtm_label = data['labels'].get('Code-Review', {})
if lgtm_label:
if ('rejected' in lgtm_label):
return 'not lgtm'
if ('approved' in lgtm_label):
return 'lgtm'
if (not data.get('reviewers', {}).get('REVIEWER', [])):
return 'unsent'
messages = data.get('messages', [])
if messages:
owner = data['owner'].get('_account_id')
last_message_author = messages[(- 1)].get('author', {}).get('_account_id')
if (owner != last_message_author):
return 'reply'
return 'waiting'
| 3,784,288,564,603,652,000
|
Apply a rough heuristic to give a simple summary of an issue's review
or CQ status, assuming adherence to a common workflow.
Returns None if no issue for this branch, or one of the following keywords:
* 'error' - error from review tool (including deleted issues)
* 'unsent' - no reviewers added
* 'waiting' - waiting for review
* 'reply' - waiting for owner to reply to review
* 'not lgtm' - Code-Review -2 from at least one approved reviewer
* 'lgtm' - Code-Review +2 from at least one approved reviewer
* 'commit' - in the commit queue
* 'closed' - abandoned
|
git_cl.py
|
GetStatus
|
wuyong2k/chromium_depot_tool
|
python
|
def GetStatus(self):
"Apply a rough heuristic to give a simple summary of an issue's review\n or CQ status, assuming adherence to a common workflow.\n\n Returns None if no issue for this branch, or one of the following keywords:\n * 'error' - error from review tool (including deleted issues)\n * 'unsent' - no reviewers added\n * 'waiting' - waiting for review\n * 'reply' - waiting for owner to reply to review\n * 'not lgtm' - Code-Review -2 from at least one approved reviewer\n * 'lgtm' - Code-Review +2 from at least one approved reviewer\n * 'commit' - in the commit queue\n * 'closed' - abandoned\n "
if (not self.GetIssue()):
return None
try:
data = self._GetChangeDetail(['DETAILED_LABELS', 'CURRENT_REVISION'])
except httplib.HTTPException:
return 'error'
if (data['status'] in ('ABANDONED', 'MERGED')):
return 'closed'
cq_label = data['labels'].get('Commit-Queue', {})
if cq_label:
vote_value = cq_label.get('value', '0')
vote_text = cq_label.get('values', {}).get(vote_value, )
if (vote_text.lower() == 'commit'):
return 'commit'
lgtm_label = data['labels'].get('Code-Review', {})
if lgtm_label:
if ('rejected' in lgtm_label):
return 'not lgtm'
if ('approved' in lgtm_label):
return 'lgtm'
if (not data.get('reviewers', {}).get('REVIEWER', [])):
return 'unsent'
messages = data.get('messages', [])
if messages:
owner = data['owner'].get('_account_id')
last_message_author = messages[(- 1)].get('author', {}).get('_account_id')
if (owner != last_message_author):
return 'reply'
return 'waiting'
|
def GetApprovingReviewers(self):
'Returns a list of reviewers approving the change.\n\n Note: not necessarily committers.\n '
raise NotImplementedError()
| 2,777,351,221,320,171,000
|
Returns a list of reviewers approving the change.
Note: not necessarily committers.
|
git_cl.py
|
GetApprovingReviewers
|
wuyong2k/chromium_depot_tool
|
python
|
def GetApprovingReviewers(self):
'Returns a list of reviewers approving the change.\n\n Note: not necessarily committers.\n '
raise NotImplementedError()
|
def CMDUploadChange(self, options, args, change):
'Upload the current branch to Gerrit.'
if (options.squash and options.no_squash):
DieWithError('Can only use one of --squash or --no-squash')
if ((not options.squash) and (not options.no_squash)):
options.squash = settings.GetSquashGerritUploads()
elif options.no_squash:
options.squash = False
gerrit_remote = 'origin'
(remote, remote_branch) = self.GetRemoteBranch()
branch = GetTargetRef(remote, remote_branch, options.target_branch, pending_prefix='')
if options.squash:
self._GerritCommitMsgHookCheck(offer_removal=(not options.force))
if (not self.GetIssue()):
message = RunGitSilent(['show', '--format=%B', '-s', ('refs/heads/git_cl_uploads/%s' % self.GetBranch())])
if message:
change_ids = git_footers.get_footer_change_id(message.strip())
if (change_ids and (len(change_ids) == 1)):
details = self._GetChangeDetail(issue=change_ids[0])
if details:
print(('WARNING: found old upload in branch git_cl_uploads/%s corresponding to issue %s' % (self.GetBranch(), details['_number'])))
self.SetIssue(details['_number'])
if (not self.GetIssue()):
DieWithError(('\nFound old upload in branch git_cl_uploads/%s, but failed to find corresponding Gerrit issue.\nIf you know the issue number, set it manually first:\n git cl issue 123456\nIf you intended to upload this CL as new issue, just delete or rename the old upload branch:\n git rename-branch git_cl_uploads/%s old_upload-%s\nAfter that, please run git cl upload again.' % tuple(([self.GetBranch()] * 3))))
if self.GetIssue():
message = self.GetDescription()
if (not message):
DieWithError(('failed to fetch description from current Gerrit issue %d\n%s' % (self.GetIssue(), self.GetIssueURL())))
change_id = self._GetChangeDetail()['change_id']
while True:
footer_change_ids = git_footers.get_footer_change_id(message)
if (footer_change_ids == [change_id]):
break
if (not footer_change_ids):
message = git_footers.add_footer_change_id(message, change_id)
print('WARNING: appended missing Change-Id to issue description')
continue
message = ('%s\n\nChange-Id: %s' % (message, change_id))
print(('WARNING: issue %s has Change-Id footer(s):\n %s\nbut issue has Change-Id %s, according to Gerrit.\nPlease, check the proposed correction to the description, and edit it if necessary but keep the "Change-Id: %s" footer\n' % (self.GetIssue(), '\n '.join(footer_change_ids), change_id, change_id)))
ask_for_data('Press enter to edit now, Ctrl+C to abort')
if (not options.force):
change_desc = ChangeDescription(message)
change_desc.prompt()
message = change_desc.description
if (not message):
DieWithError('Description is empty. Aborting...')
assert ([change_id] == git_footers.get_footer_change_id(message))
change_desc = ChangeDescription(message)
else:
change_desc = ChangeDescription((options.message or CreateDescriptionFromLog(args)))
if (not options.force):
change_desc.prompt()
if (not change_desc.description):
DieWithError('Description is empty. Aborting...')
message = change_desc.description
change_ids = git_footers.get_footer_change_id(message)
if (len(change_ids) > 1):
DieWithError('too many Change-Id footers, at most 1 allowed.')
if (not change_ids):
message = git_footers.add_footer_change_id(message, GenerateGerritChangeId(message))
change_desc.set_description(message)
change_ids = git_footers.get_footer_change_id(message)
assert (len(change_ids) == 1)
change_id = change_ids[0]
(remote, upstream_branch) = self.FetchUpstreamTuple(self.GetBranch())
if (remote is '.'):
upstream_branch_name = scm.GIT.ShortBranchName(upstream_branch)
parent = RunGit(['config', ('branch.%s.gerritsquashhash' % upstream_branch_name)], error_ok=True).strip()
if ((not parent) or (RunGitSilent(['rev-parse', (upstream_branch + ':')]) != RunGitSilent(['rev-parse', (parent + ':')]))):
DieWithError(("Upload upstream branch %s first.\nNote: maybe you've uploaded it with --no-squash or with an old version of depot_tools. If so, then re-upload it with:\n git cl upload --squash\n" % upstream_branch_name))
else:
parent = self.GetCommonAncestorWithUpstream()
tree = RunGit(['rev-parse', 'HEAD:']).strip()
ref_to_push = RunGit(['commit-tree', tree, '-p', parent, '-m', message]).strip()
else:
change_desc = ChangeDescription((options.message or CreateDescriptionFromLog(args)))
if (not change_desc.description):
DieWithError('Description is empty. Aborting...')
if (not git_footers.get_footer_change_id(change_desc.description)):
DownloadGerritHook(False)
change_desc.set_description(self._AddChangeIdToCommitMessage(options, args))
ref_to_push = 'HEAD'
parent = ('%s/%s' % (gerrit_remote, branch))
change_id = git_footers.get_footer_change_id(change_desc.description)[0]
assert change_desc
commits = RunGitSilent(['rev-list', ('%s..%s' % (parent, ref_to_push))]).splitlines()
if (len(commits) > 1):
print(('WARNING: This will upload %d commits. Run the following command to see which commits will be uploaded: ' % len(commits)))
print(('git log %s..%s' % (parent, ref_to_push)))
print('You can also use `git squash-branch` to squash these into a single commit.')
ask_for_data('About to upload; enter to confirm.')
if (options.reviewers or options.tbr_owners):
change_desc.update_reviewers(options.reviewers, options.tbr_owners, change)
refspec_opts = []
if options.title:
if ('_' in options.title):
print('WARNING: underscores in title will be converted to spaces.')
refspec_opts.append(('m=' + options.title.replace(' ', '_')))
if options.send_mail:
if (not change_desc.get_reviewers()):
DieWithError('Must specify reviewers to send email.')
refspec_opts.append('notify=ALL')
else:
refspec_opts.append('notify=NONE')
cc = self.GetCCList().split(',')
if options.cc:
cc.extend(options.cc)
cc = filter(None, cc)
if cc:
refspec_opts.extend((('cc=' + email.strip()) for email in cc))
if change_desc.get_reviewers():
refspec_opts.extend((('r=' + email.strip()) for email in change_desc.get_reviewers()))
refspec_suffix = ''
if refspec_opts:
refspec_suffix = ('%' + ','.join(refspec_opts))
assert (' ' not in refspec_suffix), ('spaces not allowed in refspec: "%s"' % refspec_suffix)
refspec = ('%s:refs/for/%s%s' % (ref_to_push, branch, refspec_suffix))
push_stdout = gclient_utils.CheckCallAndFilter(['git', 'push', gerrit_remote, refspec], print_stdout=True, filter_fn=(lambda _: sys.stdout.flush()))
if options.squash:
regex = re.compile('remote:\\s+https?://[\\w\\-\\.\\/]*/(\\d+)\\s.*')
change_numbers = [m.group(1) for m in map(regex.match, push_stdout.splitlines()) if m]
if (len(change_numbers) != 1):
DieWithError(('Created|Updated %d issues on Gerrit, but only 1 expected.\nChange-Id: %s' % (len(change_numbers), change_id)))
self.SetIssue(change_numbers[0])
RunGit(['config', ('branch.%s.gerritsquashhash' % self.GetBranch()), ref_to_push])
return 0
| 6,165,878,012,663,440,000
|
Upload the current branch to Gerrit.
|
git_cl.py
|
CMDUploadChange
|
wuyong2k/chromium_depot_tool
|
python
|
def CMDUploadChange(self, options, args, change):
if (options.squash and options.no_squash):
DieWithError('Can only use one of --squash or --no-squash')
if ((not options.squash) and (not options.no_squash)):
options.squash = settings.GetSquashGerritUploads()
elif options.no_squash:
options.squash = False
gerrit_remote = 'origin'
(remote, remote_branch) = self.GetRemoteBranch()
branch = GetTargetRef(remote, remote_branch, options.target_branch, pending_prefix=)
if options.squash:
self._GerritCommitMsgHookCheck(offer_removal=(not options.force))
if (not self.GetIssue()):
message = RunGitSilent(['show', '--format=%B', '-s', ('refs/heads/git_cl_uploads/%s' % self.GetBranch())])
if message:
change_ids = git_footers.get_footer_change_id(message.strip())
if (change_ids and (len(change_ids) == 1)):
details = self._GetChangeDetail(issue=change_ids[0])
if details:
print(('WARNING: found old upload in branch git_cl_uploads/%s corresponding to issue %s' % (self.GetBranch(), details['_number'])))
self.SetIssue(details['_number'])
if (not self.GetIssue()):
DieWithError(('\nFound old upload in branch git_cl_uploads/%s, but failed to find corresponding Gerrit issue.\nIf you know the issue number, set it manually first:\n git cl issue 123456\nIf you intended to upload this CL as new issue, just delete or rename the old upload branch:\n git rename-branch git_cl_uploads/%s old_upload-%s\nAfter that, please run git cl upload again.' % tuple(([self.GetBranch()] * 3))))
if self.GetIssue():
message = self.GetDescription()
if (not message):
DieWithError(('failed to fetch description from current Gerrit issue %d\n%s' % (self.GetIssue(), self.GetIssueURL())))
change_id = self._GetChangeDetail()['change_id']
while True:
footer_change_ids = git_footers.get_footer_change_id(message)
if (footer_change_ids == [change_id]):
break
if (not footer_change_ids):
message = git_footers.add_footer_change_id(message, change_id)
print('WARNING: appended missing Change-Id to issue description')
continue
message = ('%s\n\nChange-Id: %s' % (message, change_id))
print(('WARNING: issue %s has Change-Id footer(s):\n %s\nbut issue has Change-Id %s, according to Gerrit.\nPlease, check the proposed correction to the description, and edit it if necessary but keep the "Change-Id: %s" footer\n' % (self.GetIssue(), '\n '.join(footer_change_ids), change_id, change_id)))
ask_for_data('Press enter to edit now, Ctrl+C to abort')
if (not options.force):
change_desc = ChangeDescription(message)
change_desc.prompt()
message = change_desc.description
if (not message):
DieWithError('Description is empty. Aborting...')
assert ([change_id] == git_footers.get_footer_change_id(message))
change_desc = ChangeDescription(message)
else:
change_desc = ChangeDescription((options.message or CreateDescriptionFromLog(args)))
if (not options.force):
change_desc.prompt()
if (not change_desc.description):
DieWithError('Description is empty. Aborting...')
message = change_desc.description
change_ids = git_footers.get_footer_change_id(message)
if (len(change_ids) > 1):
DieWithError('too many Change-Id footers, at most 1 allowed.')
if (not change_ids):
message = git_footers.add_footer_change_id(message, GenerateGerritChangeId(message))
change_desc.set_description(message)
change_ids = git_footers.get_footer_change_id(message)
assert (len(change_ids) == 1)
change_id = change_ids[0]
(remote, upstream_branch) = self.FetchUpstreamTuple(self.GetBranch())
if (remote is '.'):
upstream_branch_name = scm.GIT.ShortBranchName(upstream_branch)
parent = RunGit(['config', ('branch.%s.gerritsquashhash' % upstream_branch_name)], error_ok=True).strip()
if ((not parent) or (RunGitSilent(['rev-parse', (upstream_branch + ':')]) != RunGitSilent(['rev-parse', (parent + ':')]))):
DieWithError(("Upload upstream branch %s first.\nNote: maybe you've uploaded it with --no-squash or with an old version of depot_tools. If so, then re-upload it with:\n git cl upload --squash\n" % upstream_branch_name))
else:
parent = self.GetCommonAncestorWithUpstream()
tree = RunGit(['rev-parse', 'HEAD:']).strip()
ref_to_push = RunGit(['commit-tree', tree, '-p', parent, '-m', message]).strip()
else:
change_desc = ChangeDescription((options.message or CreateDescriptionFromLog(args)))
if (not change_desc.description):
DieWithError('Description is empty. Aborting...')
if (not git_footers.get_footer_change_id(change_desc.description)):
DownloadGerritHook(False)
change_desc.set_description(self._AddChangeIdToCommitMessage(options, args))
ref_to_push = 'HEAD'
parent = ('%s/%s' % (gerrit_remote, branch))
change_id = git_footers.get_footer_change_id(change_desc.description)[0]
assert change_desc
commits = RunGitSilent(['rev-list', ('%s..%s' % (parent, ref_to_push))]).splitlines()
if (len(commits) > 1):
print(('WARNING: This will upload %d commits. Run the following command to see which commits will be uploaded: ' % len(commits)))
print(('git log %s..%s' % (parent, ref_to_push)))
print('You can also use `git squash-branch` to squash these into a single commit.')
ask_for_data('About to upload; enter to confirm.')
if (options.reviewers or options.tbr_owners):
change_desc.update_reviewers(options.reviewers, options.tbr_owners, change)
refspec_opts = []
if options.title:
if ('_' in options.title):
print('WARNING: underscores in title will be converted to spaces.')
refspec_opts.append(('m=' + options.title.replace(' ', '_')))
if options.send_mail:
if (not change_desc.get_reviewers()):
DieWithError('Must specify reviewers to send email.')
refspec_opts.append('notify=ALL')
else:
refspec_opts.append('notify=NONE')
cc = self.GetCCList().split(',')
if options.cc:
cc.extend(options.cc)
cc = filter(None, cc)
if cc:
refspec_opts.extend((('cc=' + email.strip()) for email in cc))
if change_desc.get_reviewers():
refspec_opts.extend((('r=' + email.strip()) for email in change_desc.get_reviewers()))
refspec_suffix =
if refspec_opts:
refspec_suffix = ('%' + ','.join(refspec_opts))
assert (' ' not in refspec_suffix), ('spaces not allowed in refspec: "%s"' % refspec_suffix)
refspec = ('%s:refs/for/%s%s' % (ref_to_push, branch, refspec_suffix))
push_stdout = gclient_utils.CheckCallAndFilter(['git', 'push', gerrit_remote, refspec], print_stdout=True, filter_fn=(lambda _: sys.stdout.flush()))
if options.squash:
regex = re.compile('remote:\\s+https?://[\\w\\-\\.\\/]*/(\\d+)\\s.*')
change_numbers = [m.group(1) for m in map(regex.match, push_stdout.splitlines()) if m]
if (len(change_numbers) != 1):
DieWithError(('Created|Updated %d issues on Gerrit, but only 1 expected.\nChange-Id: %s' % (len(change_numbers), change_id)))
self.SetIssue(change_numbers[0])
RunGit(['config', ('branch.%s.gerritsquashhash' % self.GetBranch()), ref_to_push])
return 0
|
def _AddChangeIdToCommitMessage(self, options, args):
'Re-commits using the current message, assumes the commit hook is in\n place.\n '
log_desc = (options.message or CreateDescriptionFromLog(args))
git_command = ['commit', '--amend', '-m', log_desc]
RunGit(git_command)
new_log_desc = CreateDescriptionFromLog(args)
if git_footers.get_footer_change_id(new_log_desc):
print('git-cl: Added Change-Id to commit message.')
return new_log_desc
else:
DieWithError('ERROR: Gerrit commit-msg hook not installed.')
| -2,375,211,046,930,508,000
|
Re-commits using the current message, assumes the commit hook is in
place.
|
git_cl.py
|
_AddChangeIdToCommitMessage
|
wuyong2k/chromium_depot_tool
|
python
|
def _AddChangeIdToCommitMessage(self, options, args):
'Re-commits using the current message, assumes the commit hook is in\n place.\n '
log_desc = (options.message or CreateDescriptionFromLog(args))
git_command = ['commit', '--amend', '-m', log_desc]
RunGit(git_command)
new_log_desc = CreateDescriptionFromLog(args)
if git_footers.get_footer_change_id(new_log_desc):
print('git-cl: Added Change-Id to commit message.')
return new_log_desc
else:
DieWithError('ERROR: Gerrit commit-msg hook not installed.')
|
def SetCQState(self, new_state):
'Sets the Commit-Queue label assuming canonical CQ config for Gerrit.'
vote_map = {_CQState.NONE: 0, _CQState.DRY_RUN: 1, _CQState.COMMIT: 2}
gerrit_util.SetReview(self._GetGerritHost(), self.GetIssue(), labels={'Commit-Queue': vote_map[new_state]})
| -7,298,066,659,973,490,000
|
Sets the Commit-Queue label assuming canonical CQ config for Gerrit.
|
git_cl.py
|
SetCQState
|
wuyong2k/chromium_depot_tool
|
python
|
def SetCQState(self, new_state):
vote_map = {_CQState.NONE: 0, _CQState.DRY_RUN: 1, _CQState.COMMIT: 2}
gerrit_util.SetReview(self._GetGerritHost(), self.GetIssue(), labels={'Commit-Queue': vote_map[new_state]})
|
def update_reviewers(self, reviewers, add_owners_tbr=False, change=None):
'Rewrites the R=/TBR= line(s) as a single line each.'
assert isinstance(reviewers, list), reviewers
if ((not reviewers) and (not add_owners_tbr)):
return
reviewers = reviewers[:]
regexp = re.compile(self.R_LINE)
matches = [regexp.match(line) for line in self._description_lines]
new_desc = [l for (i, l) in enumerate(self._description_lines) if (not matches[i])]
self.set_description(new_desc)
r_names = []
tbr_names = []
for match in matches:
if (not match):
continue
people = cleanup_list([match.group(2).strip()])
if (match.group(1) == 'TBR'):
tbr_names.extend(people)
else:
r_names.extend(people)
for name in r_names:
if (name not in reviewers):
reviewers.append(name)
if add_owners_tbr:
owners_db = owners.Database(change.RepositoryRoot(), fopen=file, os_path=os.path, glob=glob.glob)
all_reviewers = set((tbr_names + reviewers))
missing_files = owners_db.files_not_covered_by(change.LocalPaths(), all_reviewers)
tbr_names.extend(owners_db.reviewers_for(missing_files, change.author_email))
new_r_line = (('R=' + ', '.join(reviewers)) if reviewers else None)
new_tbr_line = (('TBR=' + ', '.join(tbr_names)) if tbr_names else None)
line_loc = next((i for (i, match) in enumerate(matches) if match), (- 1))
if (0 <= line_loc < len(self._description_lines)):
if new_tbr_line:
self._description_lines.insert(line_loc, new_tbr_line)
if new_r_line:
self._description_lines.insert(line_loc, new_r_line)
else:
if new_r_line:
self.append_footer(new_r_line)
if new_tbr_line:
self.append_footer(new_tbr_line)
| -3,866,714,032,062,314,500
|
Rewrites the R=/TBR= line(s) as a single line each.
|
git_cl.py
|
update_reviewers
|
wuyong2k/chromium_depot_tool
|
python
|
def update_reviewers(self, reviewers, add_owners_tbr=False, change=None):
assert isinstance(reviewers, list), reviewers
if ((not reviewers) and (not add_owners_tbr)):
return
reviewers = reviewers[:]
regexp = re.compile(self.R_LINE)
matches = [regexp.match(line) for line in self._description_lines]
new_desc = [l for (i, l) in enumerate(self._description_lines) if (not matches[i])]
self.set_description(new_desc)
r_names = []
tbr_names = []
for match in matches:
if (not match):
continue
people = cleanup_list([match.group(2).strip()])
if (match.group(1) == 'TBR'):
tbr_names.extend(people)
else:
r_names.extend(people)
for name in r_names:
if (name not in reviewers):
reviewers.append(name)
if add_owners_tbr:
owners_db = owners.Database(change.RepositoryRoot(), fopen=file, os_path=os.path, glob=glob.glob)
all_reviewers = set((tbr_names + reviewers))
missing_files = owners_db.files_not_covered_by(change.LocalPaths(), all_reviewers)
tbr_names.extend(owners_db.reviewers_for(missing_files, change.author_email))
new_r_line = (('R=' + ', '.join(reviewers)) if reviewers else None)
new_tbr_line = (('TBR=' + ', '.join(tbr_names)) if tbr_names else None)
line_loc = next((i for (i, match) in enumerate(matches) if match), (- 1))
if (0 <= line_loc < len(self._description_lines)):
if new_tbr_line:
self._description_lines.insert(line_loc, new_tbr_line)
if new_r_line:
self._description_lines.insert(line_loc, new_r_line)
else:
if new_r_line:
self.append_footer(new_r_line)
if new_tbr_line:
self.append_footer(new_tbr_line)
|
def prompt(self):
'Asks the user to update the description.'
self.set_description((['# Enter a description of the change.', '# This will be displayed on the codereview site.', '# The first line will also be used as the subject of the review.', '#--------------------This line is 72 characters long--------------------'] + self._description_lines))
regexp = re.compile(self.BUG_LINE)
if (not any((regexp.match(line) for line in self._description_lines))):
self.append_footer(('BUG=%s' % settings.GetBugPrefix()))
content = gclient_utils.RunEditor(self.description, True, git_editor=settings.GetGitEditor())
if (not content):
DieWithError('Running editor failed')
lines = content.splitlines()
clean_lines = [line.rstrip() for line in lines if (not line.startswith('#'))]
if (not clean_lines):
DieWithError('No CL description, aborting')
self.set_description(clean_lines)
| 6,837,271,194,655,891,000
|
Asks the user to update the description.
|
git_cl.py
|
prompt
|
wuyong2k/chromium_depot_tool
|
python
|
def prompt(self):
self.set_description((['# Enter a description of the change.', '# This will be displayed on the codereview site.', '# The first line will also be used as the subject of the review.', '#--------------------This line is 72 characters long--------------------'] + self._description_lines))
regexp = re.compile(self.BUG_LINE)
if (not any((regexp.match(line) for line in self._description_lines))):
self.append_footer(('BUG=%s' % settings.GetBugPrefix()))
content = gclient_utils.RunEditor(self.description, True, git_editor=settings.GetGitEditor())
if (not content):
DieWithError('Running editor failed')
lines = content.splitlines()
clean_lines = [line.rstrip() for line in lines if (not line.startswith('#'))]
if (not clean_lines):
DieWithError('No CL description, aborting')
self.set_description(clean_lines)
|
def append_footer(self, line):
'Adds a footer line to the description.\n\n Differentiates legacy "KEY=xxx" footers (used to be called tags) and\n Gerrit\'s footers in the form of "Footer-Key: footer any value" and ensures\n that Gerrit footers are always at the end.\n '
parsed_footer_line = git_footers.parse_footer(line)
if parsed_footer_line:
self.set_description(git_footers.add_footer(self.description, key=parsed_footer_line[0], value=parsed_footer_line[1]))
return
if (not self._description_lines):
self._description_lines.append(line)
return
(top_lines, gerrit_footers, _) = git_footers.split_footers(self.description)
if gerrit_footers:
assert (top_lines and (top_lines[(- 1)] == ''))
(top_lines, separator) = (top_lines[:(- 1)], top_lines[(- 1):])
else:
separator = []
prev_line = (top_lines[(- 1)] if top_lines else '')
if ((not presubmit_support.Change.TAG_LINE_RE.match(prev_line)) or (not presubmit_support.Change.TAG_LINE_RE.match(line))):
top_lines.append('')
top_lines.append(line)
self._description_lines = ((top_lines + separator) + gerrit_footers)
| -4,948,696,434,904,024,000
|
Adds a footer line to the description.
Differentiates legacy "KEY=xxx" footers (used to be called tags) and
Gerrit's footers in the form of "Footer-Key: footer any value" and ensures
that Gerrit footers are always at the end.
|
git_cl.py
|
append_footer
|
wuyong2k/chromium_depot_tool
|
python
|
def append_footer(self, line):
'Adds a footer line to the description.\n\n Differentiates legacy "KEY=xxx" footers (used to be called tags) and\n Gerrit\'s footers in the form of "Footer-Key: footer any value" and ensures\n that Gerrit footers are always at the end.\n '
parsed_footer_line = git_footers.parse_footer(line)
if parsed_footer_line:
self.set_description(git_footers.add_footer(self.description, key=parsed_footer_line[0], value=parsed_footer_line[1]))
return
if (not self._description_lines):
self._description_lines.append(line)
return
(top_lines, gerrit_footers, _) = git_footers.split_footers(self.description)
if gerrit_footers:
assert (top_lines and (top_lines[(- 1)] == ))
(top_lines, separator) = (top_lines[:(- 1)], top_lines[(- 1):])
else:
separator = []
prev_line = (top_lines[(- 1)] if top_lines else )
if ((not presubmit_support.Change.TAG_LINE_RE.match(prev_line)) or (not presubmit_support.Change.TAG_LINE_RE.match(line))):
top_lines.append()
top_lines.append(line)
self._description_lines = ((top_lines + separator) + gerrit_footers)
|
def get_reviewers(self):
'Retrieves the list of reviewers.'
matches = [re.match(self.R_LINE, line) for line in self._description_lines]
reviewers = [match.group(2).strip() for match in matches if match]
return cleanup_list(reviewers)
| 1,088,958,793,655,500,300
|
Retrieves the list of reviewers.
|
git_cl.py
|
get_reviewers
|
wuyong2k/chromium_depot_tool
|
python
|
def get_reviewers(self):
matches = [re.match(self.R_LINE, line) for line in self._description_lines]
reviewers = [match.group(2).strip() for match in matches if match]
return cleanup_list(reviewers)
|
def patch_tpool_proxy():
"eventlet.tpool.Proxy doesn't work with old-style class in __str__()\n or __repr__() calls. See bug #962840 for details.\n We perform a monkey patch to replace those two instance methods.\n "
def str_method(self):
return str(self._obj)
def repr_method(self):
return repr(self._obj)
tpool.Proxy.__str__ = str_method
tpool.Proxy.__repr__ = repr_method
| -8,502,220,070,496,038,000
|
eventlet.tpool.Proxy doesn't work with old-style class in __str__()
or __repr__() calls. See bug #962840 for details.
We perform a monkey patch to replace those two instance methods.
|
nova/virt/libvirt/driver.py
|
patch_tpool_proxy
|
srajag/nova
|
python
|
def patch_tpool_proxy():
"eventlet.tpool.Proxy doesn't work with old-style class in __str__()\n or __repr__() calls. See bug #962840 for details.\n We perform a monkey patch to replace those two instance methods.\n "
def str_method(self):
return str(self._obj)
def repr_method(self):
return repr(self._obj)
tpool.Proxy.__str__ = str_method
tpool.Proxy.__repr__ = repr_method
|
def _set_cache_mode(self, conf):
'Set cache mode on LibvirtConfigGuestDisk object.'
try:
source_type = conf.source_type
driver_cache = conf.driver_cache
except AttributeError:
return
cache_mode = self.disk_cachemodes.get(source_type, driver_cache)
conf.driver_cache = cache_mode
| 5,531,731,997,377,213,000
|
Set cache mode on LibvirtConfigGuestDisk object.
|
nova/virt/libvirt/driver.py
|
_set_cache_mode
|
srajag/nova
|
python
|
def _set_cache_mode(self, conf):
try:
source_type = conf.source_type
driver_cache = conf.driver_cache
except AttributeError:
return
cache_mode = self.disk_cachemodes.get(source_type, driver_cache)
conf.driver_cache = cache_mode
|
def _native_thread(self):
"Receives async events coming in from libvirtd.\n\n This is a native thread which runs the default\n libvirt event loop implementation. This processes\n any incoming async events from libvirtd and queues\n them for later dispatch. This thread is only\n permitted to use libvirt python APIs, and the\n driver.queue_event method. In particular any use\n of logging is forbidden, since it will confuse\n eventlet's greenthread integration\n "
while True:
libvirt.virEventRunDefaultImpl()
| 7,655,609,895,301,288,000
|
Receives async events coming in from libvirtd.
This is a native thread which runs the default
libvirt event loop implementation. This processes
any incoming async events from libvirtd and queues
them for later dispatch. This thread is only
permitted to use libvirt python APIs, and the
driver.queue_event method. In particular any use
of logging is forbidden, since it will confuse
eventlet's greenthread integration
|
nova/virt/libvirt/driver.py
|
_native_thread
|
srajag/nova
|
python
|
def _native_thread(self):
"Receives async events coming in from libvirtd.\n\n This is a native thread which runs the default\n libvirt event loop implementation. This processes\n any incoming async events from libvirtd and queues\n them for later dispatch. This thread is only\n permitted to use libvirt python APIs, and the\n driver.queue_event method. In particular any use\n of logging is forbidden, since it will confuse\n eventlet's greenthread integration\n "
while True:
libvirt.virEventRunDefaultImpl()
|
def _dispatch_thread(self):
'Dispatches async events coming in from libvirtd.\n\n This is a green thread which waits for events to\n arrive from the libvirt event loop thread. This\n then dispatches the events to the compute manager.\n '
while True:
self._dispatch_events()
| 6,173,909,251,682,045,000
|
Dispatches async events coming in from libvirtd.
This is a green thread which waits for events to
arrive from the libvirt event loop thread. This
then dispatches the events to the compute manager.
|
nova/virt/libvirt/driver.py
|
_dispatch_thread
|
srajag/nova
|
python
|
def _dispatch_thread(self):
'Dispatches async events coming in from libvirtd.\n\n This is a green thread which waits for events to\n arrive from the libvirt event loop thread. This\n then dispatches the events to the compute manager.\n '
while True:
self._dispatch_events()
|
@staticmethod
def _event_lifecycle_callback(conn, dom, event, detail, opaque):
'Receives lifecycle events from libvirt.\n\n NB: this method is executing in a native thread, not\n an eventlet coroutine. It can only invoke other libvirt\n APIs, or use self.queue_event(). Any use of logging APIs\n in particular is forbidden.\n '
self = opaque
uuid = dom.UUIDString()
transition = None
if (event == libvirt.VIR_DOMAIN_EVENT_STOPPED):
transition = virtevent.EVENT_LIFECYCLE_STOPPED
elif (event == libvirt.VIR_DOMAIN_EVENT_STARTED):
transition = virtevent.EVENT_LIFECYCLE_STARTED
elif (event == libvirt.VIR_DOMAIN_EVENT_SUSPENDED):
transition = virtevent.EVENT_LIFECYCLE_PAUSED
elif (event == libvirt.VIR_DOMAIN_EVENT_RESUMED):
transition = virtevent.EVENT_LIFECYCLE_RESUMED
if (transition is not None):
self._queue_event(virtevent.LifecycleEvent(uuid, transition))
| 9,154,323,491,274,748,000
|
Receives lifecycle events from libvirt.
NB: this method is executing in a native thread, not
an eventlet coroutine. It can only invoke other libvirt
APIs, or use self.queue_event(). Any use of logging APIs
in particular is forbidden.
|
nova/virt/libvirt/driver.py
|
_event_lifecycle_callback
|
srajag/nova
|
python
|
@staticmethod
def _event_lifecycle_callback(conn, dom, event, detail, opaque):
'Receives lifecycle events from libvirt.\n\n NB: this method is executing in a native thread, not\n an eventlet coroutine. It can only invoke other libvirt\n APIs, or use self.queue_event(). Any use of logging APIs\n in particular is forbidden.\n '
self = opaque
uuid = dom.UUIDString()
transition = None
if (event == libvirt.VIR_DOMAIN_EVENT_STOPPED):
transition = virtevent.EVENT_LIFECYCLE_STOPPED
elif (event == libvirt.VIR_DOMAIN_EVENT_STARTED):
transition = virtevent.EVENT_LIFECYCLE_STARTED
elif (event == libvirt.VIR_DOMAIN_EVENT_SUSPENDED):
transition = virtevent.EVENT_LIFECYCLE_PAUSED
elif (event == libvirt.VIR_DOMAIN_EVENT_RESUMED):
transition = virtevent.EVENT_LIFECYCLE_RESUMED
if (transition is not None):
self._queue_event(virtevent.LifecycleEvent(uuid, transition))
|
def _queue_event(self, event):
'Puts an event on the queue for dispatch.\n\n This method is called by the native event thread to\n put events on the queue for later dispatch by the\n green thread. Any use of logging APIs is forbidden.\n '
if (self._event_queue is None):
return
self._event_queue.put(event)
c = ' '.encode()
self._event_notify_send.write(c)
self._event_notify_send.flush()
| 5,110,817,474,055,161,000
|
Puts an event on the queue for dispatch.
This method is called by the native event thread to
put events on the queue for later dispatch by the
green thread. Any use of logging APIs is forbidden.
|
nova/virt/libvirt/driver.py
|
_queue_event
|
srajag/nova
|
python
|
def _queue_event(self, event):
'Puts an event on the queue for dispatch.\n\n This method is called by the native event thread to\n put events on the queue for later dispatch by the\n green thread. Any use of logging APIs is forbidden.\n '
if (self._event_queue is None):
return
self._event_queue.put(event)
c = ' '.encode()
self._event_notify_send.write(c)
self._event_notify_send.flush()
|
def _dispatch_events(self):
'Wait for & dispatch events from native thread\n\n Blocks until native thread indicates some events\n are ready. Then dispatches all queued events.\n '
try:
_c = self._event_notify_recv.read(1)
assert _c
except ValueError:
return
last_close_event = None
while (not self._event_queue.empty()):
try:
event = self._event_queue.get(block=False)
if isinstance(event, virtevent.LifecycleEvent):
self.emit_event(event)
elif (('conn' in event) and ('reason' in event)):
last_close_event = event
except native_Queue.Empty:
pass
if (last_close_event is None):
return
conn = last_close_event['conn']
with self._wrapped_conn_lock:
if (conn == self._wrapped_conn):
reason = last_close_event['reason']
_error = (_('Connection to libvirt lost: %s') % reason)
LOG.warn(_error)
self._wrapped_conn = None
self._set_host_enabled(False, disable_reason=_error)
| -360,219,353,666,080,640
|
Wait for & dispatch events from native thread
Blocks until native thread indicates some events
are ready. Then dispatches all queued events.
|
nova/virt/libvirt/driver.py
|
_dispatch_events
|
srajag/nova
|
python
|
def _dispatch_events(self):
'Wait for & dispatch events from native thread\n\n Blocks until native thread indicates some events\n are ready. Then dispatches all queued events.\n '
try:
_c = self._event_notify_recv.read(1)
assert _c
except ValueError:
return
last_close_event = None
while (not self._event_queue.empty()):
try:
event = self._event_queue.get(block=False)
if isinstance(event, virtevent.LifecycleEvent):
self.emit_event(event)
elif (('conn' in event) and ('reason' in event)):
last_close_event = event
except native_Queue.Empty:
pass
if (last_close_event is None):
return
conn = last_close_event['conn']
with self._wrapped_conn_lock:
if (conn == self._wrapped_conn):
reason = last_close_event['reason']
_error = (_('Connection to libvirt lost: %s') % reason)
LOG.warn(_error)
self._wrapped_conn = None
self._set_host_enabled(False, disable_reason=_error)
|
def _init_events_pipe(self):
'Create a self-pipe for the native thread to synchronize on.\n\n This code is taken from the eventlet tpool module, under terms\n of the Apache License v2.0.\n '
self._event_queue = native_Queue.Queue()
try:
(rpipe, wpipe) = os.pipe()
self._event_notify_send = greenio.GreenPipe(wpipe, 'wb', 0)
self._event_notify_recv = greenio.GreenPipe(rpipe, 'rb', 0)
except (ImportError, NotImplementedError):
sock = eventlet_util.__original_socket__(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', 0))
sock.listen(50)
csock = eventlet_util.__original_socket__(socket.AF_INET, socket.SOCK_STREAM)
csock.connect(('localhost', sock.getsockname()[1]))
(nsock, addr) = sock.accept()
self._event_notify_send = nsock.makefile('wb', 0)
gsock = greenio.GreenSocket(csock)
self._event_notify_recv = gsock.makefile('rb', 0)
| -7,875,527,013,368,604,000
|
Create a self-pipe for the native thread to synchronize on.
This code is taken from the eventlet tpool module, under terms
of the Apache License v2.0.
|
nova/virt/libvirt/driver.py
|
_init_events_pipe
|
srajag/nova
|
python
|
def _init_events_pipe(self):
'Create a self-pipe for the native thread to synchronize on.\n\n This code is taken from the eventlet tpool module, under terms\n of the Apache License v2.0.\n '
self._event_queue = native_Queue.Queue()
try:
(rpipe, wpipe) = os.pipe()
self._event_notify_send = greenio.GreenPipe(wpipe, 'wb', 0)
self._event_notify_recv = greenio.GreenPipe(rpipe, 'rb', 0)
except (ImportError, NotImplementedError):
sock = eventlet_util.__original_socket__(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', 0))
sock.listen(50)
csock = eventlet_util.__original_socket__(socket.AF_INET, socket.SOCK_STREAM)
csock.connect(('localhost', sock.getsockname()[1]))
(nsock, addr) = sock.accept()
self._event_notify_send = nsock.makefile('wb', 0)
gsock = greenio.GreenSocket(csock)
self._event_notify_recv = gsock.makefile('rb', 0)
|
def _init_events(self):
'Initializes the libvirt events subsystem.\n\n This requires running a native thread to provide the\n libvirt event loop integration. This forwards events\n to a green thread which does the actual dispatching.\n '
self._init_events_pipe()
LOG.debug('Starting native event thread')
event_thread = native_threading.Thread(target=self._native_thread)
event_thread.setDaemon(True)
event_thread.start()
LOG.debug('Starting green dispatch thread')
eventlet.spawn(self._dispatch_thread)
| 1,019,574,824,169,468,700
|
Initializes the libvirt events subsystem.
This requires running a native thread to provide the
libvirt event loop integration. This forwards events
to a green thread which does the actual dispatching.
|
nova/virt/libvirt/driver.py
|
_init_events
|
srajag/nova
|
python
|
def _init_events(self):
'Initializes the libvirt events subsystem.\n\n This requires running a native thread to provide the\n libvirt event loop integration. This forwards events\n to a green thread which does the actual dispatching.\n '
self._init_events_pipe()
LOG.debug('Starting native event thread')
event_thread = native_threading.Thread(target=self._native_thread)
event_thread.setDaemon(True)
event_thread.start()
LOG.debug('Starting green dispatch thread')
eventlet.spawn(self._dispatch_thread)
|
def _do_quality_warnings(self):
'Warn about untested driver configurations.\n\n This will log a warning message about untested driver or host arch\n configurations to indicate to administrators that the quality is\n unknown. Currently, only qemu or kvm on intel 32- or 64-bit systems\n is tested upstream.\n '
caps = self._get_host_capabilities()
arch = caps.host.cpu.arch
if ((CONF.libvirt.virt_type not in ('qemu', 'kvm')) or (arch not in ('i686', 'x86_64'))):
LOG.warn(_LW('The libvirt driver is not tested on %(type)s/%(arch)s by the OpenStack project and thus its quality can not be ensured. For more information, see: https://wiki.openstack.org/wiki/HypervisorSupportMatrix'), {'type': CONF.libvirt.virt_type, 'arch': arch})
| 920,347,697,261,030,000
|
Warn about untested driver configurations.
This will log a warning message about untested driver or host arch
configurations to indicate to administrators that the quality is
unknown. Currently, only qemu or kvm on intel 32- or 64-bit systems
is tested upstream.
|
nova/virt/libvirt/driver.py
|
_do_quality_warnings
|
srajag/nova
|
python
|
def _do_quality_warnings(self):
'Warn about untested driver configurations.\n\n This will log a warning message about untested driver or host arch\n configurations to indicate to administrators that the quality is\n unknown. Currently, only qemu or kvm on intel 32- or 64-bit systems\n is tested upstream.\n '
caps = self._get_host_capabilities()
arch = caps.host.cpu.arch
if ((CONF.libvirt.virt_type not in ('qemu', 'kvm')) or (arch not in ('i686', 'x86_64'))):
LOG.warn(_LW('The libvirt driver is not tested on %(type)s/%(arch)s by the OpenStack project and thus its quality can not be ensured. For more information, see: https://wiki.openstack.org/wiki/HypervisorSupportMatrix'), {'type': CONF.libvirt.virt_type, 'arch': arch})
|
def instance_exists(self, instance):
'Efficient override of base instance_exists method.'
try:
self._lookup_by_name(instance.name)
return True
except exception.NovaException:
return False
| 4,235,376,044,896,723,500
|
Efficient override of base instance_exists method.
|
nova/virt/libvirt/driver.py
|
instance_exists
|
srajag/nova
|
python
|
def instance_exists(self, instance):
try:
self._lookup_by_name(instance.name)
return True
except exception.NovaException:
return False
|
def _list_instance_domains(self, only_running=True, only_guests=True):
'Get a list of libvirt.Domain objects for nova instances\n\n :param only_running: True to only return running instances\n :param only_guests: True to filter out any host domain (eg Dom-0)\n\n Query libvirt to a get a list of all libvirt.Domain objects\n that correspond to nova instances. If the only_running parameter\n is true this list will only include active domains, otherwise\n inactive domains will be included too. If the only_guests parameter\n is true the list will have any "host" domain (aka Xen Domain-0)\n filtered out.\n\n :returns: list of libvirt.Domain objects\n '
if (not self._skip_list_all_domains):
try:
alldoms = self._list_instance_domains_fast(only_running)
except (libvirt.libvirtError, AttributeError) as ex:
LOG.info(_LI('Unable to use bulk domain list APIs, falling back to slow code path: %(ex)s'), {'ex': ex})
self._skip_list_all_domains = True
if self._skip_list_all_domains:
alldoms = self._list_instance_domains_slow(only_running)
doms = []
for dom in alldoms:
if (only_guests and (dom.ID() == 0)):
continue
doms.append(dom)
return doms
| -8,610,953,524,653,425,000
|
Get a list of libvirt.Domain objects for nova instances
:param only_running: True to only return running instances
:param only_guests: True to filter out any host domain (eg Dom-0)
Query libvirt to a get a list of all libvirt.Domain objects
that correspond to nova instances. If the only_running parameter
is true this list will only include active domains, otherwise
inactive domains will be included too. If the only_guests parameter
is true the list will have any "host" domain (aka Xen Domain-0)
filtered out.
:returns: list of libvirt.Domain objects
|
nova/virt/libvirt/driver.py
|
_list_instance_domains
|
srajag/nova
|
python
|
def _list_instance_domains(self, only_running=True, only_guests=True):
'Get a list of libvirt.Domain objects for nova instances\n\n :param only_running: True to only return running instances\n :param only_guests: True to filter out any host domain (eg Dom-0)\n\n Query libvirt to a get a list of all libvirt.Domain objects\n that correspond to nova instances. If the only_running parameter\n is true this list will only include active domains, otherwise\n inactive domains will be included too. If the only_guests parameter\n is true the list will have any "host" domain (aka Xen Domain-0)\n filtered out.\n\n :returns: list of libvirt.Domain objects\n '
if (not self._skip_list_all_domains):
try:
alldoms = self._list_instance_domains_fast(only_running)
except (libvirt.libvirtError, AttributeError) as ex:
LOG.info(_LI('Unable to use bulk domain list APIs, falling back to slow code path: %(ex)s'), {'ex': ex})
self._skip_list_all_domains = True
if self._skip_list_all_domains:
alldoms = self._list_instance_domains_slow(only_running)
doms = []
for dom in alldoms:
if (only_guests and (dom.ID() == 0)):
continue
doms.append(dom)
return doms
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.