Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(86)

Side by Side Diff: git_cl.py

Issue 1835963003: Gerrit git cl: stop creating a shadow branch. (Closed) Base URL: https://chromium.googlesource.com/chromium/tools/depot_tools.git@H150
Patch Set: +fix Created 4 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « no previous file | tests/git_cl_test.py » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 #!/usr/bin/env python 1 #!/usr/bin/env python
2 # Copyright (c) 2012 The Chromium Authors. All rights reserved. 2 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be 3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file. 4 # found in the LICENSE file.
5 5
6 # Copyright (C) 2008 Evan Martin <martine@danga.com> 6 # Copyright (C) 2008 Evan Martin <martine@danga.com>
7 7
8 """A git-command for integrating reviews on Rietveld and Gerrit.""" 8 """A git-command for integrating reviews on Rietveld and Gerrit."""
9 9
10 from distutils.version import LooseVersion 10 from distutils.version import LooseVersion
(...skipping 2500 matching lines...) Expand 10 before | Expand all | Expand 10 after
2511 # whitespace. This code is not doing this, but it clearly won't decrease 2511 # whitespace. This code is not doing this, but it clearly won't decrease
2512 # entropy. 2512 # entropy.
2513 lines.append(message) 2513 lines.append(message)
2514 change_hash = RunCommand(['git', 'hash-object', '-t', 'commit', '--stdin'], 2514 change_hash = RunCommand(['git', 'hash-object', '-t', 'commit', '--stdin'],
2515 stdin='\n'.join(lines)) 2515 stdin='\n'.join(lines))
2516 return 'I%s' % change_hash.strip() 2516 return 'I%s' % change_hash.strip()
2517 2517
2518 2518
2519 def GerritUpload(options, args, cl, change): 2519 def GerritUpload(options, args, cl, change):
2520 """upload the current branch to gerrit.""" 2520 """upload the current branch to gerrit."""
2521 # TODO(tandrii): refactor this to be a method of _GerritChangelistImpl,
2522 # to avoid private members accessors below.
2523
2521 # We assume the remote called "origin" is the one we want. 2524 # We assume the remote called "origin" is the one we want.
2522 # It is probably not worthwhile to support different workflows. 2525 # It is probably not worthwhile to support different workflows.
2523 gerrit_remote = 'origin' 2526 gerrit_remote = 'origin'
2524 2527
2525 remote, remote_branch = cl.GetRemoteBranch() 2528 remote, remote_branch = cl.GetRemoteBranch()
2526 branch = GetTargetRef(remote, remote_branch, options.target_branch, 2529 branch = GetTargetRef(remote, remote_branch, options.target_branch,
2527 pending_prefix='') 2530 pending_prefix='')
2528 2531
2529 change_desc = ChangeDescription(
2530 options.message or CreateDescriptionFromLog(args))
2531 if not change_desc.description:
2532 print "\nDescription is empty. Aborting..."
2533 return 1
2534
2535 if options.title: 2532 if options.title:
2536 print "\nPatch titles (-t) are not supported in Gerrit. Aborting..." 2533 print "\nPatch titles (-t) are not supported in Gerrit. Aborting..."
2537 return 1 2534 return 1
2538 2535
2539 if options.squash: 2536 if options.squash:
2540 # Try to get the message from a previous upload. 2537 if cl.GetIssue():
2541 shadow_branch = 'refs/heads/git_cl_uploads/' + cl.GetBranch() 2538 # Try to get the message from a previous upload.
2542 message = RunGitSilent(['show', '--format=%B', '-s', shadow_branch]) 2539 message = cl.GetDescription()
2543 if not message: 2540 if not message:
2541 DieWithError(
2542 'failed to fetch description from current Gerrit issue %d\n'
2543 '%s' % (cl.GetIssue(), cl.GetIssueURL()))
2544 change_id = cl._codereview_impl._GetChangeDetail([])['change_id']
2545 footer_change_ids = git_footers.get_footer_change_id(message)
2546 if footer_change_ids != [change_id]:
2547 while footer_change_ids:
2548 # There is already a valid footer but with different or several ids.
2549 # Doing this automatically is non-trivial as we don't want to loose
2550 # existing other footers, yet we want to append just 1 desired
2551 # Change-Id. That's non-trival, so just create new footer, but let
2552 # user verify the new description.
2553 message = '%s\n\nChange-Id: %s' % (message, change_id)
2554 print((
2555 'WARNING: issue %s has Change-Id footer(s):\n'
2556 ' %s\n'
2557 'but issue has Change-Id %s, according to Gerrit.\n'
2558 'Please, check the proposed correction to the description,\n'
2559 'and edit it if necessary but keep the "Change-Id: %s" footer\n'
2560 ) % (cl.GetIssue(), '\n '.join(footer_change_ids), change_id,
2561 change_id, cl.GetIssueUrl()))
2562 ask_for_data('Press enter to edit now, Ctrl+C to abort')
2563 if options.force:
Bernhard Bauer 2016/03/29 13:27:38 Why do we do this only if force is _set_?
tandrii(chromium) 2016/03/29 14:46:32 good catch, missing "not".
2564 change_desc = ChangeDescription(message)
2565 change_desc.prompt()
2566 message = change_desc.description
2567 if not message:
2568 DieWithError("Description is empty. Aborting...")
2569 footer_change_ids = git_footers.get_footer_change_id(message)
2570 if footer_change_ids == [change_id] or not footer_change_ids:
2571 break
2572 continue
Bernhard Bauer 2016/03/29 13:27:38 This is the last statement in the body of a while
tandrii(chromium) 2016/03/29 14:46:32 Yep, but I thought reading is easier that way.
2573 if not footer_change_ids:
2574 message = git_footers.add_footer_change_id(message, change_id)
2575 print('WARNING: appended missing Change-Id to issue description')
2576 # Sanity check of this code - we should end up with proper message footer.
2577 assert [change_id] == git_footers.get_footer_change_id(message)
2578 change_desc = ChangeDescription(message)
2579 else:
2580 change_desc = ChangeDescription(
2581 options.message or CreateDescriptionFromLog(args))
2544 if not options.force: 2582 if not options.force:
2545 change_desc.prompt() 2583 change_desc.prompt()
2546 if not change_desc.description: 2584 if not change_desc.description:
2547 print "Description is empty; aborting." 2585 DieWithError("Description is empty. Aborting...")
2548 return 1
2549 message = change_desc.description 2586 message = change_desc.description
2550 change_ids = git_footers.get_footer_change_id(message) 2587 change_ids = git_footers.get_footer_change_id(message)
2551 if len(change_ids) > 1: 2588 if len(change_ids) > 1:
2552 DieWithError('too many Change-Id footers in %s branch' % shadow_branch) 2589 DieWithError('too many Change-Id footers, at most 1 allowed.')
2553 if not change_ids: 2590 if not change_ids:
2591 # Generate the Change-Id automatically.
2554 message = git_footers.add_footer_change_id( 2592 message = git_footers.add_footer_change_id(
2555 message, GenerateGerritChangeId(message)) 2593 message, GenerateGerritChangeId(message))
2556 change_desc.set_description(message) 2594 change_desc.set_description(message)
2557 change_ids = git_footers.get_footer_change_id(message) 2595 change_ids = git_footers.get_footer_change_id(message)
2558 assert len(change_ids) == 1 2596 assert len(change_ids) == 1
2559
2560 change_id = change_ids[0] 2597 change_id = change_ids[0]
2561 2598
2562 remote, upstream_branch = cl.FetchUpstreamTuple(cl.GetBranch()) 2599 remote, upstream_branch = cl.FetchUpstreamTuple(cl.GetBranch())
2563 if remote is '.': 2600 if remote is '.':
2564 # If our upstream branch is local, we base our squashed commit on its 2601 # If our upstream branch is local, we base our squashed commit on its
2565 # squashed version. 2602 # squashed version.
2566 parent = ('refs/heads/git_cl_uploads/' + 2603 upstream_branch_name = scm.GIT.ShortBranchName(upstream_branch)
2567 scm.GIT.ShortBranchName(upstream_branch)) 2604 # Check the squashed hash of the parent.
2568 2605 parent = RunGit(['config',
2569 # Verify that the upstream branch has been uploaded too, otherwise Gerrit 2606 'branch.%s.gerritsquashhash' % upstream_branch_name],
2570 # will create additional CLs when uploading. 2607 error_ok=True).strip()
2571 if (RunGitSilent(['rev-parse', upstream_branch + ':']) != 2608 # Verify that the upstream branch has been uploaded too, otherwise
2572 RunGitSilent(['rev-parse', parent + ':'])): 2609 # Gerrit will create additional CLs when uploading.
2573 print 'Upload upstream branch ' + upstream_branch + ' first.' 2610 if not parent or (RunGitSilent(['rev-parse', upstream_branch + ':']) !=
2574 return 1 2611 RunGitSilent(['rev-parse', parent + ':'])):
2612 # TODO(tandrii): remove "old depot_tools" part on April 12, 2016.
2613 DieWithError(
2614 'Upload upstream branch %s first.\n'
2615 'Note: maybe you\'ve uploaded it with --no-squash or with an old\n'
2616 ' version of depot_tools. If so, then re-upload it with:\n'
2617 ' git cl upload --squash\n' % upstream_branch_name)
2575 else: 2618 else:
2576 parent = cl.GetCommonAncestorWithUpstream() 2619 parent = cl.GetCommonAncestorWithUpstream()
2577 2620
2578 tree = RunGit(['rev-parse', 'HEAD:']).strip() 2621 tree = RunGit(['rev-parse', 'HEAD:']).strip()
2579 ref_to_push = RunGit(['commit-tree', tree, '-p', parent, 2622 ref_to_push = RunGit(['commit-tree', tree, '-p', parent,
2580 '-m', message]).strip() 2623 '-m', message]).strip()
2581 else: 2624 else:
2625 change_desc = ChangeDescription(
2626 options.message or CreateDescriptionFromLog(args))
2627 if not change_desc.description:
2628 DieWithError("Description is empty. Aborting...")
2629
2582 if not git_footers.get_footer_change_id(change_desc.description): 2630 if not git_footers.get_footer_change_id(change_desc.description):
2583 DownloadGerritHook(False) 2631 DownloadGerritHook(False)
2584 change_desc.set_description(AddChangeIdToCommitMessage(options, args)) 2632 change_desc.set_description(AddChangeIdToCommitMessage(options, args))
2585 ref_to_push = 'HEAD' 2633 ref_to_push = 'HEAD'
2586 parent = '%s/%s' % (gerrit_remote, branch) 2634 parent = '%s/%s' % (gerrit_remote, branch)
2587 change_id = git_footers.get_footer_change_id(change_desc.description)[0] 2635 change_id = git_footers.get_footer_change_id(change_desc.description)[0]
2588 2636
2637 assert change_desc
2589 commits = RunGitSilent(['rev-list', '%s..%s' % (parent, 2638 commits = RunGitSilent(['rev-list', '%s..%s' % (parent,
2590 ref_to_push)]).splitlines() 2639 ref_to_push)]).splitlines()
2591 if len(commits) > 1: 2640 if len(commits) > 1:
2592 print('WARNING: This will upload %d commits. Run the following command ' 2641 print('WARNING: This will upload %d commits. Run the following command '
2593 'to see which commits will be uploaded: ' % len(commits)) 2642 'to see which commits will be uploaded: ' % len(commits))
2594 print('git log %s..%s' % (parent, ref_to_push)) 2643 print('git log %s..%s' % (parent, ref_to_push))
2595 print('You can also use `git squash-branch` to squash these into a single ' 2644 print('You can also use `git squash-branch` to squash these into a single '
2596 'commit.') 2645 'commit.')
2597 ask_for_data('About to upload; enter to confirm.') 2646 ask_for_data('About to upload; enter to confirm.')
2598 2647
(...skipping 26 matching lines...) Expand all
2625 if options.squash: 2674 if options.squash:
2626 regex = re.compile(r'remote:\s+https?://[\w\-\.\/]*/(\d+)\s.*') 2675 regex = re.compile(r'remote:\s+https?://[\w\-\.\/]*/(\d+)\s.*')
2627 change_numbers = [m.group(1) 2676 change_numbers = [m.group(1)
2628 for m in map(regex.match, push_stdout.splitlines()) 2677 for m in map(regex.match, push_stdout.splitlines())
2629 if m] 2678 if m]
2630 if len(change_numbers) != 1: 2679 if len(change_numbers) != 1:
2631 DieWithError( 2680 DieWithError(
2632 ('Created|Updated %d issues on Gerrit, but only 1 expected.\n' 2681 ('Created|Updated %d issues on Gerrit, but only 1 expected.\n'
2633 'Change-Id: %s') % (len(change_numbers), change_id)) 2682 'Change-Id: %s') % (len(change_numbers), change_id))
2634 cl.SetIssue(change_numbers[0]) 2683 cl.SetIssue(change_numbers[0])
2635 head = RunGit(['rev-parse', 'HEAD']).strip() 2684 RunGit(['config', 'branch.%s.gerritsquashhash' % cl.GetBranch(),
2636 RunGit(['update-ref', '-m', 'Uploaded ' + head, shadow_branch, ref_to_push]) 2685 ref_to_push])
2637 return 0 2686 return 0
2638 2687
2639 2688
2640 def GetTargetRef(remote, remote_branch, target_branch, pending_prefix): 2689 def GetTargetRef(remote, remote_branch, target_branch, pending_prefix):
2641 """Computes the remote branch ref to use for the CL. 2690 """Computes the remote branch ref to use for the CL.
2642 2691
2643 Args: 2692 Args:
2644 remote (str): The git remote for the CL. 2693 remote (str): The git remote for the CL.
2645 remote_branch (str): The git remote branch for the CL. 2694 remote_branch (str): The git remote branch for the CL.
2646 target_branch (str): The target branch specified by the user. 2695 target_branch (str): The target branch specified by the user.
(...skipping 270 matching lines...) Expand 10 before | Expand all | Expand 10 after
2917 auth.add_auth_options(parser) 2966 auth.add_auth_options(parser)
2918 (options, args) = parser.parse_args(args) 2967 (options, args) = parser.parse_args(args)
2919 auth_config = auth.extract_auth_config_from_options(options) 2968 auth_config = auth.extract_auth_config_from_options(options)
2920 2969
2921 if git_common.is_dirty_git_tree('upload'): 2970 if git_common.is_dirty_git_tree('upload'):
2922 return 1 2971 return 1
2923 2972
2924 options.reviewers = cleanup_list(options.reviewers) 2973 options.reviewers = cleanup_list(options.reviewers)
2925 options.cc = cleanup_list(options.cc) 2974 options.cc = cleanup_list(options.cc)
2926 2975
2976 # For sanity of test expectations, do this otherwise lazy-loading *now*.
2977 settings.GetIsGerrit()
2978
2927 cl = Changelist(auth_config=auth_config) 2979 cl = Changelist(auth_config=auth_config)
2928 if args: 2980 if args:
2929 # TODO(ukai): is it ok for gerrit case? 2981 # TODO(ukai): is it ok for gerrit case?
2930 base_branch = args[0] 2982 base_branch = args[0]
2931 else: 2983 else:
2932 if cl.GetBranch() is None: 2984 if cl.GetBranch() is None:
2933 DieWithError('Can\'t upload from detached HEAD state. Get on a branch!') 2985 DieWithError('Can\'t upload from detached HEAD state. Get on a branch!')
2934 2986
2935 # Default to diffing against common ancestor of upstream branch 2987 # Default to diffing against common ancestor of upstream branch
2936 base_branch = cl.GetCommonAncestorWithUpstream() 2988 base_branch = cl.GetCommonAncestorWithUpstream()
(...skipping 1389 matching lines...) Expand 10 before | Expand all | Expand 10 after
4326 if __name__ == '__main__': 4378 if __name__ == '__main__':
4327 # These affect sys.stdout so do it outside of main() to simplify mocks in 4379 # These affect sys.stdout so do it outside of main() to simplify mocks in
4328 # unit testing. 4380 # unit testing.
4329 fix_encoding.fix_encoding() 4381 fix_encoding.fix_encoding()
4330 colorama.init() 4382 colorama.init()
4331 try: 4383 try:
4332 sys.exit(main(sys.argv[1:])) 4384 sys.exit(main(sys.argv[1:]))
4333 except KeyboardInterrupt: 4385 except KeyboardInterrupt:
4334 sys.stderr.write('interrupted\n') 4386 sys.stderr.write('interrupted\n')
4335 sys.exit(1) 4387 sys.exit(1)
OLDNEW
« no previous file with comments | « no previous file | tests/git_cl_test.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698