Skip to content

Instantly share code, notes, and snippets.

@Kuanlin-Chen
Last active November 1, 2022 02:52
Show Gist options
  • Save Kuanlin-Chen/92635ccc132297461558563872ed370a to your computer and use it in GitHub Desktop.
Save Kuanlin-Chen/92635ccc132297461558563872ed370a to your computer and use it in GitHub Desktop.
Cherry-pick changes from commit list remotely.
import sys
from pygerrit2 import GerritRestAPI, HTTPBasicAuth
import base64
import json
from urllib2 import HTTPError
auth = HTTPBasicAuth('username','passwd')
rest = GerritRestAPI(url='http://gerrit.xxxxxx.com:8080', auth=auth)
class Gerrit:
subject = None
commit_id = None
change_id = None
change_num = None
target_branch = None
new_data = None
def __init__(self, target_branch):
self.target_branch = target_branch
def get_info_by_commit(self, commit_id):
self.commit_id = commit_id
info = rest.get("/changes/?q=commit:{}".format(commit_id))
self.subject = info[0]['subject']
self.change_id = info[0]['change_id']
self.change_num = info[0]['_number']
def revert(self):
headers = {'content-type': 'application/json'}
query = "/changes/" + str(self.change_num) + "/revert"
my_data = {"message": "{}".format("Revert "+str(self.subject))}
return rest.post(query, data=json.dumps(my_data), timeout=30, headers=headers)
def cherrypick(self):
headers = {'content-disposition': 'attachment', 'content-type': 'application/json'}
query = "/changes/" + str(self.change_num) + "/revisions/current/cherrypick"
message = """{}
Change-Id: {}
(cherry picked from commit {})""".format(self.subject, self.change_id, self.commit_id)
my_data = {"message": "{}".format(message), "destination": "{}".format(self.target_branch)}
self.new_data = rest.post(query, data=json.dumps(my_data), timeout=30, headers=headers)
def review(self):
headers = {'content-disposition': 'attachment', 'content-type': 'application/json'}
new_change = self.new_data['_number']
query = "/changes/" + str(new_change) + "/revisions/current/review"
my_data = { "labels": {"Code-Review": "+2", "Verified": "+1"} }
rest.post(query, data=json.dumps(my_data), timeout=30, headers=headers)
def submit(self):
headers = {'content-disposition': 'attachment', 'content-type': 'application/json'}
new_change = self.new_data['_number']
query = "/changes/" + str(new_change) + "/submit"
my_data = {}
rest.post(query, data=json.dumps(my_data), timeout=30, headers=headers)
####################
def main(orig_args):
target_branch = 'master'
commit_list = ['commit-id', 'commit-id', 'commit-id']
gerrit = Gerrit(target_branch)
for commit in commit_list:
print "Commit-Id: {}".format(commit)
gerrit.get_info_by_commit(commit)
try:
gerrit.cherrypick()
gerrit.review()
gerrit.submit()
except HTTPError as err:
print(err)
if __name__ == '__main__':
main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment