自动化需要获取到所有的gerrit 用户,也就是username,查询 Gerrit的REST API并没有这样的Endpoint.
最终实现方法:先获取所有用户id,再根据id查询username。
这里需要注意:返回的json格式是有 XSSI 保护前缀的,所以需要先移除。
import requests
from requests.auth import HTTPBasicAuth
import json
def get_user_info(gerrit_url, username, password, account_id):
url = f"{gerrit_url}/a/accounts/{account_id}"
headers = {"Content-Type": "application/json"}
response = requests.get(url, auth=HTTPBasicAuth(username, password), headers=headers)
if response.status_code == 200:
try:
json_text = response.text.lstrip(")]}'")
user_info = json.loads(json_text)
return user_info.get("username")
except json.JSONDecodeError:
print(f"Error decoding JSON for user ID {account_id}")
print("Response JSON:", response.text)
else:
print(f"Failed to retrieve user info for ID {account_id}. Status code: {response.status_code}, Response: {response.text}")
def list_users(username, password, gerrit_url):
url = f"{gerrit_url}/a/accounts/?q=is:active"
headers = {"Content-Type": "application/json"}
response = requests.get(url, auth=HTTPBasicAuth(username, password), headers=headers)
users_list = []
if response.status_code == 200:
try:
json_text = response.text.lstrip(")]}'")
users_data = json.loads(json_text)
for user in users_data:
account_id = user.get('_account_id')
account_username = get_user_info(gerrit_url, username, password, account_id)
users_list.append(account_username)
except json.JSONDecodeError:
print("Empty response or invalid JSON.")
else:
print(f"Error: {response.status_code} - {response.text}")
return users_list