| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2023, Ondrej Zvara ([email protected]) |
| 4 |
# Based on code: |
| 5 |
# Copyright (c) 2021, Lennert Mertens ([email protected]) |
| 6 |
# Copyright (c) 2021, Werner Dijkerman ([email protected]) |
| 7 |
# Copyright (c) 2015, Werner Dijkerman ([email protected]) |
| 8 |
# Copyright (c) 2019, Guillaume Martinez ([email protected]) |
| 9 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 10 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 11 |
from __future__ import annotations |
| 12 |
|
| 13 |
DOCUMENTATION = r""" |
| 14 |
module: gitlab_merge_request |
| 15 |
short_description: Create, update, or delete GitLab merge requests |
| 16 |
version_added: 7.1.0 |
| 17 |
description: |
| 18 |
- Creates a merge request if it does not exist. |
| 19 |
- When a single merge request does exist, it is updated if the provided parameters are different. |
| 20 |
- When a single merge request does exist and O(state=absent), the merge request is deleted. |
| 21 |
- When multiple merge requests are detected, the task fails. |
| 22 |
- Existing merge requests are matched based on O(title), O(source_branch), O(target_branch), and O(state_filter) filters. |
| 23 |
author: |
| 24 |
- zvaraondrej (@zvaraondrej) |
| 25 |
requirements: |
| 26 |
- python-gitlab >= 2.3.0 |
| 27 |
extends_documentation_fragment: |
| 28 |
- community.general._auth_basic |
| 29 |
- community.general._gitlab |
| 30 |
- community.general._attributes |
| 31 |
|
| 32 |
attributes: |
| 33 |
check_mode: |
| 34 |
support: full |
| 35 |
diff_mode: |
| 36 |
support: none |
| 37 |
|
| 38 |
options: |
| 39 |
state: |
| 40 |
description: |
| 41 |
- Create or delete merge request. |
| 42 |
default: present |
| 43 |
type: str |
| 44 |
choices: ["present", "absent"] |
| 45 |
project: |
| 46 |
description: |
| 47 |
- The path or name of the project. |
| 48 |
required: true |
| 49 |
type: str |
| 50 |
source_branch: |
| 51 |
description: |
| 52 |
- Merge request's source branch. |
| 53 |
- Ignored while updating existing merge request. |
| 54 |
required: true |
| 55 |
type: str |
| 56 |
target_branch: |
| 57 |
description: |
| 58 |
- Merge request's target branch. |
| 59 |
required: true |
| 60 |
type: str |
| 61 |
title: |
| 62 |
description: |
| 63 |
- A title for the merge request. |
| 64 |
type: str |
| 65 |
required: true |
| 66 |
description: |
| 67 |
description: |
| 68 |
- A description for the merge request. |
| 69 |
- Gets overridden by a content of file specified at O(description_path), if found. |
| 70 |
type: str |
| 71 |
description_path: |
| 72 |
description: |
| 73 |
- A path of file containing merge request's description. |
| 74 |
- Accepts MarkDown formatted files. |
| 75 |
type: path |
| 76 |
labels: |
| 77 |
description: |
| 78 |
- Comma separated list of label names. |
| 79 |
type: str |
| 80 |
default: "" |
| 81 |
remove_source_branch: |
| 82 |
description: |
| 83 |
- Flag indicating if a merge request should remove the source branch when merging. |
| 84 |
type: bool |
| 85 |
default: false |
| 86 |
state_filter: |
| 87 |
description: |
| 88 |
- Filter specifying state of merge requests while searching. |
| 89 |
type: str |
| 90 |
choices: ["opened", "closed", "locked", "merged"] |
| 91 |
default: opened |
| 92 |
assignee_ids: |
| 93 |
description: |
| 94 |
- Comma separated list of assignees usernames omitting V(@) character. |
| 95 |
- Set to empty string to unassign all assignees. |
| 96 |
type: str |
| 97 |
reviewer_ids: |
| 98 |
description: |
| 99 |
- Comma separated list of reviewers usernames omitting V(@) character. |
| 100 |
- Set to empty string to unassign all reviewers. |
| 101 |
type: str |
| 102 |
""" |
| 103 |
|
| 104 |
|
| 105 |
EXAMPLES = r""" |
| 106 |
- name: Create Merge Request from branch1 to branch2 |
| 107 |
community.general.gitlab_merge_request: |
| 108 |
api_url: https://gitlab.com |
| 109 |
api_token: secret_access_token |
| 110 |
project: "group1/project1" |
| 111 |
source_branch: branch1 |
| 112 |
target_branch: branch2 |
| 113 |
title: "Ansible demo MR" |
| 114 |
description: "Demo MR description" |
| 115 |
labels: "Ansible,Demo" |
| 116 |
state_filter: "opened" |
| 117 |
remove_source_branch: true |
| 118 |
state: present |
| 119 |
|
| 120 |
- name: Delete Merge Request from branch1 to branch2 |
| 121 |
community.general.gitlab_merge_request: |
| 122 |
api_url: https://gitlab.com |
| 123 |
api_token: secret_access_token |
| 124 |
project: "group1/project1" |
| 125 |
source_branch: branch1 |
| 126 |
target_branch: branch2 |
| 127 |
title: "Ansible demo MR" |
| 128 |
state_filter: "opened" |
| 129 |
state: absent |
| 130 |
""" |
| 131 |
|
| 132 |
RETURN = r""" |
| 133 |
msg: |
| 134 |
description: Success or failure message. |
| 135 |
returned: always |
| 136 |
type: str |
| 137 |
sample: "Success" |
| 138 |
|
| 139 |
mr: |
| 140 |
description: API object. |
| 141 |
returned: success |
| 142 |
type: dict |
| 143 |
""" |
| 144 |
|
| 145 |
from ansible.module_utils.api import basic_auth_argument_spec |
| 146 |
from ansible.module_utils.basic import AnsibleModule |
| 147 |
from ansible.module_utils.common.text.converters import to_text |
| 148 |
|
| 149 |
from ansible_collections.community.general.plugins.module_utils._gitlab import ( |
| 150 |
auth_argument_spec, |
| 151 |
find_project, |
| 152 |
gitlab, |
| 153 |
gitlab_authentication, |
| 154 |
) |
| 155 |
from ansible_collections.community.general.plugins.module_utils._version import LooseVersion |
| 156 |
|
| 157 |
|
| 158 |
class GitlabMergeRequest: |
| 159 |
def __init__(self, module, project, gitlab_instance): |
| 160 |
self._gitlab = gitlab_instance |
| 161 |
self._module = module |
| 162 |
self.project = project |
| 163 |
|
| 164 |
""" |
| 165 |
@param branch Name of the branch |
| 166 |
""" |
| 167 |
|
| 168 |
def get_branch(self, branch): |
| 169 |
try: |
| 170 |
return self.project.branches.get(branch) |
| 171 |
except gitlab.exceptions.GitlabGetError as e: |
| 172 |
self._module.fail_json(msg=f"Failed to get the branch: {e}") |
| 173 |
|
| 174 |
""" |
| 175 |
@param title Title of the Merge Request |
| 176 |
@param source_branch Merge Request's source branch |
| 177 |
@param target_branch Merge Request's target branch |
| 178 |
@param state_filter Merge Request's state to filter on |
| 179 |
""" |
| 180 |
|
| 181 |
def get_mr(self, title, source_branch, target_branch, state_filter): |
| 182 |
mrs = [] |
| 183 |
try: |
| 184 |
mrs = self.project.mergerequests.list( |
| 185 |
search=title, source_branch=source_branch, target_branch=target_branch, state=state_filter |
| 186 |
) |
| 187 |
except gitlab.exceptions.GitlabGetError as e: |
| 188 |
self._module.fail_json(msg=f"Failed to list the Merge Request: {e}") |
| 189 |
|
| 190 |
if len(mrs) > 1: |
| 191 |
self._module.fail_json(msg="Multiple Merge Requests matched search criteria.") |
| 192 |
if len(mrs) == 1: |
| 193 |
try: |
| 194 |
return self.project.mergerequests.get(id=mrs[0].iid) |
| 195 |
except gitlab.exceptions.GitlabGetError as e: |
| 196 |
self._module.fail_json(msg=f"Failed to get the Merge Request: {e}") |
| 197 |
|
| 198 |
""" |
| 199 |
@param username Name of the user |
| 200 |
""" |
| 201 |
|
| 202 |
def get_user(self, username): |
| 203 |
users = [] |
| 204 |
try: |
| 205 |
users = [user for user in self.project.users.list(username=username, all=True) if user.username == username] |
| 206 |
except gitlab.exceptions.GitlabGetError as e: |
| 207 |
self._module.fail_json(msg=f"Failed to list the users: {e}") |
| 208 |
|
| 209 |
if len(users) > 1: |
| 210 |
self._module.fail_json(msg="Multiple Users matched search criteria.") |
| 211 |
elif len(users) < 1: |
| 212 |
self._module.fail_json(msg="No User matched search criteria.") |
| 213 |
else: |
| 214 |
return users[0] |
| 215 |
|
| 216 |
""" |
| 217 |
@param users List of usernames |
| 218 |
""" |
| 219 |
|
| 220 |
def get_user_ids(self, users): |
| 221 |
return [self.get_user(user).id for user in users] |
| 222 |
|
| 223 |
""" |
| 224 |
@param options Options of the Merge Request |
| 225 |
""" |
| 226 |
|
| 227 |
def create_mr(self, options): |
| 228 |
if self._module.check_mode: |
| 229 |
self._module.exit_json(changed=True, msg=f"Successfully created the Merge Request {options['title']}") |
| 230 |
|
| 231 |
try: |
| 232 |
return self.project.mergerequests.create(options) |
| 233 |
except gitlab.exceptions.GitlabCreateError as e: |
| 234 |
self._module.fail_json(msg=f"Failed to create Merge Request: {e}") |
| 235 |
|
| 236 |
""" |
| 237 |
@param mr Merge Request object to delete |
| 238 |
""" |
| 239 |
|
| 240 |
def delete_mr(self, mr): |
| 241 |
if self._module.check_mode: |
| 242 |
self._module.exit_json(changed=True, msg=f"Successfully deleted the Merge Request {mr['title']}") |
| 243 |
|
| 244 |
try: |
| 245 |
return mr.delete() |
| 246 |
except gitlab.exceptions.GitlabDeleteError as e: |
| 247 |
self._module.fail_json(msg=f"Failed to delete Merge Request: {e}") |
| 248 |
|
| 249 |
""" |
| 250 |
@param mr Merge Request object to update |
| 251 |
""" |
| 252 |
|
| 253 |
def update_mr(self, mr, options): |
| 254 |
if self._module.check_mode: |
| 255 |
self._module.exit_json(changed=True, msg=f"Successfully updated the Merge Request {mr['title']}") |
| 256 |
|
| 257 |
try: |
| 258 |
return self.project.mergerequests.update(mr.iid, options) |
| 259 |
except gitlab.exceptions.GitlabUpdateError as e: |
| 260 |
self._module.fail_json(msg=f"Failed to update Merge Request: {e}") |
| 261 |
|
| 262 |
""" |
| 263 |
@param mr Merge Request object to evaluate |
| 264 |
@param options New options to update MR with |
| 265 |
""" |
| 266 |
|
| 267 |
def mr_has_changed(self, mr, options): |
| 268 |
for key, value in options.items(): |
| 269 |
if value is not None: |
| 270 |
# see https://gitlab.com/gitlab-org/gitlab-foss/-/issues/27355 |
| 271 |
if key == "remove_source_branch": |
| 272 |
key = "force_remove_source_branch" |
| 273 |
|
| 274 |
if key == "assignee_ids": |
| 275 |
if value != sorted([user["id"] for user in mr.assignees]): |
| 276 |
return True |
| 277 |
|
| 278 |
elif key == "reviewer_ids": |
| 279 |
if value != sorted([user["id"] for user in mr.reviewers]): |
| 280 |
return True |
| 281 |
|
| 282 |
elif key == "labels": |
| 283 |
if value != sorted(getattr(mr, key)): |
| 284 |
return True |
| 285 |
|
| 286 |
elif getattr(mr, key) != value: |
| 287 |
return True |
| 288 |
|
| 289 |
return False |
| 290 |
|
| 291 |
|
| 292 |
def main(): |
| 293 |
argument_spec = basic_auth_argument_spec() |
| 294 |
argument_spec.update(auth_argument_spec()) |
| 295 |
argument_spec.update( |
| 296 |
project=dict(type="str", required=True), |
| 297 |
source_branch=dict(type="str", required=True), |
| 298 |
target_branch=dict(type="str", required=True), |
| 299 |
title=dict(type="str", required=True), |
| 300 |
description=dict(type="str"), |
| 301 |
labels=dict(type="str", default=""), |
| 302 |
description_path=dict(type="path"), |
| 303 |
remove_source_branch=dict(type="bool", default=False), |
| 304 |
state_filter=dict(type="str", default="opened", choices=["opened", "closed", "locked", "merged"]), |
| 305 |
assignee_ids=dict(type="str"), |
| 306 |
reviewer_ids=dict(type="str"), |
| 307 |
state=dict(type="str", default="present", choices=["absent", "present"]), |
| 308 |
) |
| 309 |
|
| 310 |
module = AnsibleModule( |
| 311 |
argument_spec=argument_spec, |
| 312 |
mutually_exclusive=[ |
| 313 |
["api_username", "api_token"], |
| 314 |
["api_username", "api_oauth_token"], |
| 315 |
["api_username", "api_job_token"], |
| 316 |
["api_token", "api_oauth_token"], |
| 317 |
["api_token", "api_job_token"], |
| 318 |
["description", "description_path"], |
| 319 |
], |
| 320 |
required_together=[ |
| 321 |
["api_username", "api_password"], |
| 322 |
], |
| 323 |
required_one_of=[["api_username", "api_token", "api_oauth_token", "api_job_token"]], |
| 324 |
required_if=[ |
| 325 |
["state", "present", ["source_branch", "target_branch", "title"], True], |
| 326 |
["state", "absent", ["source_branch", "target_branch", "title"], True], |
| 327 |
], |
| 328 |
supports_check_mode=True, |
| 329 |
) |
| 330 |
|
| 331 |
# check prerequisites and connect to gitlab server |
| 332 |
gitlab_instance = gitlab_authentication(module) |
| 333 |
|
| 334 |
project = module.params["project"] |
| 335 |
source_branch = module.params["source_branch"] |
| 336 |
target_branch = module.params["target_branch"] |
| 337 |
title = module.params["title"] |
| 338 |
description = module.params["description"] |
| 339 |
labels = module.params["labels"] |
| 340 |
description_path = module.params["description_path"] |
| 341 |
remove_source_branch = module.params["remove_source_branch"] |
| 342 |
state_filter = module.params["state_filter"] |
| 343 |
assignee_ids = module.params["assignee_ids"] |
| 344 |
reviewer_ids = module.params["reviewer_ids"] |
| 345 |
state = module.params["state"] |
| 346 |
|
| 347 |
gitlab_version = gitlab.__version__ |
| 348 |
if LooseVersion(gitlab_version) < LooseVersion("2.3.0"): |
| 349 |
module.fail_json( |
| 350 |
msg=f"community.general.gitlab_merge_request requires python-gitlab Python module >= 2.3.0 (installed version: [{gitlab_version}])." |
| 351 |
" Please upgrade python-gitlab to version 2.3.0 or above." |
| 352 |
) |
| 353 |
|
| 354 |
this_project = find_project(gitlab_instance, project) |
| 355 |
if this_project is None: |
| 356 |
module.fail_json(msg=f"Failed to get the project: {project}") |
| 357 |
|
| 358 |
this_gitlab = GitlabMergeRequest(module=module, project=this_project, gitlab_instance=gitlab_instance) |
| 359 |
|
| 360 |
r_source_branch = this_gitlab.get_branch(source_branch) |
| 361 |
if not r_source_branch: |
| 362 |
module.fail_json(msg=f"Source branch {r_source_branch} not exist.") |
| 363 |
|
| 364 |
r_target_branch = this_gitlab.get_branch(target_branch) |
| 365 |
if not r_target_branch: |
| 366 |
module.fail_json(msg=f"Destination branch {r_target_branch} not exist.") |
| 367 |
|
| 368 |
this_mr = this_gitlab.get_mr(title, source_branch, target_branch, state_filter) |
| 369 |
|
| 370 |
if state == "present": |
| 371 |
if description_path: |
| 372 |
try: |
| 373 |
with open(description_path, "rb") as f: |
| 374 |
description = to_text(f.read(), errors="surrogate_or_strict") |
| 375 |
except OSError as e: |
| 376 |
module.fail_json(msg=f"Cannot open {description_path}: {e}") |
| 377 |
|
| 378 |
# sorting necessary in order to properly detect changes, as we don't want to get false positive |
| 379 |
# results due to differences in ids ordering; see `mr_has_changed()` |
| 380 |
assignee_ids = sorted(this_gitlab.get_user_ids(assignee_ids.split(","))) if assignee_ids else [] |
| 381 |
reviewer_ids = sorted(this_gitlab.get_user_ids(reviewer_ids.split(","))) if reviewer_ids else [] |
| 382 |
labels = sorted(labels.split(",")) if labels else [] |
| 383 |
|
| 384 |
options = { |
| 385 |
"target_branch": target_branch, |
| 386 |
"title": title, |
| 387 |
"description": description, |
| 388 |
"labels": labels, |
| 389 |
"remove_source_branch": remove_source_branch, |
| 390 |
"reviewer_ids": reviewer_ids, |
| 391 |
"assignee_ids": assignee_ids, |
| 392 |
} |
| 393 |
|
| 394 |
if not this_mr: |
| 395 |
options["source_branch"] = source_branch |
| 396 |
|
| 397 |
mr = this_gitlab.create_mr(options) |
| 398 |
module.exit_json( |
| 399 |
changed=True, |
| 400 |
msg=f"Created the Merge Request {title} from branch {source_branch} to branch {target_branch}.", |
| 401 |
mr=mr.asdict(), |
| 402 |
) |
| 403 |
else: |
| 404 |
if this_gitlab.mr_has_changed(this_mr, options): |
| 405 |
mr = this_gitlab.update_mr(this_mr, options) |
| 406 |
module.exit_json( |
| 407 |
changed=True, |
| 408 |
msg=f"Merge Request {title} from branch {source_branch} to branch {target_branch} updated.", |
| 409 |
mr=mr, |
| 410 |
) |
| 411 |
else: |
| 412 |
module.exit_json( |
| 413 |
changed=False, |
| 414 |
msg=f"Merge Request {title} from branch {source_branch} to branch {target_branch} already exist", |
| 415 |
mr=this_mr.asdict(), |
| 416 |
) |
| 417 |
elif this_mr and state == "absent": |
| 418 |
mr = this_gitlab.delete_mr(this_mr) |
| 419 |
module.exit_json( |
| 420 |
changed=True, |
| 421 |
msg=f"Merge Request {title} from branch {source_branch} to branch {target_branch} deleted.", |
| 422 |
mr=mr, |
| 423 |
) |
| 424 |
else: |
| 425 |
module.exit_json(changed=False, msg="No changes are needed.", mr=this_mr.asdict()) |
| 426 |
|
| 427 |
|
| 428 |
if __name__ == "__main__": |
| 429 |
main() |