I’m trying to create and merge a gitlab mr
using python script, the mr
was created without any error, but I got an error message while trying to merge it "422, {"message":"Branch cannot be merged"}"
, how can i get more details about the error? Is there any issue with my script? Thanks
The functions used to create and merge it:
def create_merge_request(token, project_id, source_branch, target_branch, title, description):
"""Créer une Merge Request sur GitLab."""
url = f"{GITLAB_HOST_HTTPS}/api/v4/projects/{project_id}/merge_requests"
headers = {"PRIVATE-TOKEN": token}
data = {
"source_branch": source_branch,
"target_branch": target_branch,
"title": title,
"description": description,
"merge_when_pipeline_succeeds": False, # Désactiver la fusion conditionnelle
"remove_source_branch": True, # Supprimer la branche source après fusion
"squash": True # Ne pas écraser les commits
}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 201:
mr_data = response.json()
print(f"Merge Request créée avec succès : {mr_data.get('web_url')}")
return mr_data # Retourne les détails de la MR
else:
print(f"Erreur lors de la création de la Merge Request : {response.json()}")
return None
def merge_mr(token, project_id, merge_request_iid):
"""Fusionner une Merge Request via l'API GitLab."""
url = f"{GITLAB_HOST_HTTPS}/api/v4/projects/{project_id}/merge_requests/{merge_request_iid}/merge"
headers = {"PRIVATE-TOKEN": token}
print(f"URL utilisée pour le merge : {url}")
response = requests.put(url, headers=headers) #, json=data
if response.status_code == 200:
print("Merge Request mergée avec succès.")
return response.json()
elif response.status_code == 405:
print("Erreur 405 : Méthode non autorisée. Vérifiez la méthode HTTP (PUT).")
else:
print(f"Erreur lors de la Merge : {response.status_code}, {response.text}")
return None
def create_and_merge_mr(token, project_id, source_branch, target_branch, title, description):
"""Créer une MR et la merger immédiatement si possible."""
# Étape 1 : Créer la MR
mr_data = create_merge_request(token, project_id, source_branch, target_branch, title, description)
if not mr_data:
print("Échec de la création de la Merge Request.")
return
# Étape 2 : Récupérer l'ID interne de la MR (iid)
merge_request_iid = mr_data.get('iid')
if not merge_request_iid:
print("Impossible de récupérer l'ID interne de la Merge Request.")
return
# Étape 3 : Fusionner la MR
merge_result = merge_mr(token, project_id, merge_request_iid)
if merge_result:
print("MR mergée avec succès.")
else:
print("Échec de la merge de la MR.")
def main():
parser = ArgumentParser()
parser.add_argument("--client_group_name", help="Nom du groupe client à filtrer", default=None)
parser.add_argument("--yaml_file", help="Chemin du fichier YAML pour les topics", default="nature-topics.yaml")
parser.add_argument("--gitlab_token", help="GitLab token for authentication", required=True)
parser.add_argument("--nature", help="Nature of the environment (e.g., dev, qa)", required=True)
args = parser.parse_args()
#1.
#2.
#3.
#4.
# 9. merge la MR
# git_merge_branches(local_repo_path, new_branch, branch)
create_and_merge_mr(
args.gitlab_token,
project_id,
new_branch,
branch,
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"
)
if __name__ == "__main__":
main()