open-quality-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,673 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import os
6
+ from dataclasses import asdict, dataclass, field
7
+ from datetime import UTC, datetime
8
+ from pathlib import Path
9
+ from typing import Any, Callable
10
+ from urllib.error import HTTPError
11
+ from urllib.parse import quote
12
+ from urllib.request import Request, urlopen
13
+
14
+ import yaml
15
+
16
+ from ..model import Bundle, Resource
17
+ from ..core import quality_requirements
18
+
19
+
20
+ REGISTERED_PROVIDERS = {"openproject"}
21
+
22
+
23
+ @dataclass
24
+ class TargetConfig:
25
+ provider: str
26
+ name: str
27
+ base_url: str
28
+ project: str = ""
29
+ type_href: str = ""
30
+ notify: bool = False
31
+ description: str = ""
32
+ members_file: str = ""
33
+ kanban_columns: list[str] = field(default_factory=list)
34
+
35
+ def validate(self) -> None:
36
+ if self.provider not in REGISTERED_PROVIDERS:
37
+ raise ValueError(
38
+ f"unsupported provider {self.provider!r}; registered providers: "
39
+ + ", ".join(sorted(REGISTERED_PROVIDERS))
40
+ )
41
+ if not all([self.name, self.base_url, self.type_href]):
42
+ raise ValueError(
43
+ "name, baseURL and workPackageTypeHref are required"
44
+ )
45
+ if not self.type_href.startswith("/api/v3/types/"):
46
+ raise ValueError("workPackageTypeHref must be an OpenProject API type href")
47
+
48
+ def token(self) -> str:
49
+ if not (token := os.getenv("OPENPROJECT_TOKEN")):
50
+ raise ValueError("environment variable OPENPROJECT_TOKEN is empty")
51
+ return token
52
+
53
+
54
+ def load_config(path: str | Path | dict[str, Any], role: str = "") -> TargetConfig:
55
+ try:
56
+ raw = path if isinstance(path, dict) else yaml.safe_load(Path(path).read_text())
57
+ unknown = set(raw) - {"provider", "config", "description"}
58
+ if unknown:
59
+ raise ValueError(f"unknown field {sorted(unknown)[0]!r}")
60
+ provider_config = raw.get("config") or {}
61
+ if not isinstance(provider_config, dict):
62
+ raise ValueError("config must be a mapping")
63
+ if raw.get("provider") == "openproject":
64
+ unknown = set(provider_config) - {
65
+ "baseURL", "workPackageTypeHref", "notify", "membersFile", "members", "kanban"
66
+ }
67
+ if unknown:
68
+ raise ValueError(
69
+ f"OpenProject config contains unknown field {sorted(unknown)[0]!r}"
70
+ )
71
+ kanban = provider_config.get("kanban") or {}
72
+ if not isinstance(kanban, dict) or set(kanban) - {"columns"}:
73
+ raise ValueError("OpenProject kanban must contain only columns")
74
+ columns = kanban.get("columns", [])
75
+ if not isinstance(columns, list) or not all(isinstance(column, str) and column for column in columns):
76
+ raise ValueError("OpenProject kanban.columns must be a list of non-empty strings")
77
+ config = TargetConfig(
78
+ raw.get("provider", ""),
79
+ role or raw.get("provider", ""),
80
+ provider_config.get("baseURL", ""),
81
+ "",
82
+ provider_config.get("workPackageTypeHref", ""),
83
+ provider_config.get("notify", False),
84
+ raw.get("description", ""),
85
+ provider_config.get("membersFile", ""),
86
+ columns,
87
+ )
88
+ config.validate()
89
+ return config
90
+ except Exception as error:
91
+ raise ValueError(f"target {path}: {error}") from error
92
+
93
+
94
+ @dataclass(frozen=True)
95
+ class ProjectMember:
96
+ role: str
97
+ email: str
98
+ openproject_role: str
99
+
100
+
101
+ def load_members(path: str | Path | dict) -> list[ProjectMember]:
102
+ try:
103
+ raw = (path if isinstance(path, dict) else yaml.safe_load(Path(path).read_text())) or {}
104
+ if raw.get("provider") != "openproject" or set(raw) - {"provider", "members"}:
105
+ raise ValueError("must contain only provider: openproject and members")
106
+ members: list[ProjectMember] = []
107
+ for entry in raw.get("members", []):
108
+ if set(entry) - {"role", "emails", "openProjectRole"}:
109
+ raise ValueError("member contains an unknown field")
110
+ role, emails, op_role = (
111
+ entry.get("role"),
112
+ entry.get("emails"),
113
+ entry.get("openProjectRole"),
114
+ )
115
+ if not isinstance(role, str) or not isinstance(op_role, str) or not isinstance(emails, list):
116
+ raise ValueError("member requires role, emails and openProjectRole")
117
+ members.extend(ProjectMember(role, email, op_role) for email in emails if isinstance(email, str))
118
+ return members
119
+ except Exception as error:
120
+ raise ValueError(f"members {path}: {error}") from error
121
+
122
+
123
+ @dataclass
124
+ class ExternalResource:
125
+ resourceId: str
126
+ kind: str
127
+ externalId: int
128
+ href: str
129
+ hash: str
130
+ appliedAt: str
131
+
132
+
133
+ @dataclass
134
+ class ProviderState:
135
+ version: int
136
+ provider: str
137
+ target: str
138
+ resources: dict[str, ExternalResource] = field(default_factory=dict)
139
+
140
+
141
+ def new_state(target: str) -> ProviderState:
142
+ return ProviderState(1, "openproject", target)
143
+
144
+
145
+ def load_state(path: str | Path, target: str) -> ProviderState:
146
+ path = Path(path)
147
+ if not path.exists():
148
+ return new_state(target)
149
+ raw = json.loads(path.read_text())
150
+ if raw.get("provider") != "openproject" or raw.get("target") != target:
151
+ raise ValueError(
152
+ f"state belongs to provider {raw.get('provider')!r} target {raw.get('target')!r}"
153
+ )
154
+ return ProviderState(
155
+ raw.get("version", 1),
156
+ raw["provider"],
157
+ raw["target"],
158
+ {
159
+ key: ExternalResource(**value)
160
+ for key, value in raw.get("resources", {}).items()
161
+ },
162
+ )
163
+
164
+
165
+ def save_state(path: str | Path, state: ProviderState) -> None:
166
+ path = Path(path)
167
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
168
+ temporary = path.with_name(path.name + ".tmp")
169
+ temporary.write_text(
170
+ json.dumps(
171
+ {
172
+ "version": state.version,
173
+ "provider": state.provider,
174
+ "target": state.target,
175
+ "resources": {
176
+ key: asdict(value) for key, value in state.resources.items()
177
+ },
178
+ },
179
+ indent=2,
180
+ )
181
+ + "\n"
182
+ )
183
+ temporary.replace(path)
184
+
185
+
186
+ @dataclass
187
+ class Operation:
188
+ action: str
189
+ resource_id: str
190
+ kind: str
191
+ subject: str
192
+ description: str
193
+ parent: str
194
+ hash: str
195
+ data: dict[str, str] = field(default_factory=dict)
196
+
197
+
198
+ def _description(resource: Resource, kind: str) -> str:
199
+ if kind == "Project":
200
+ return f"**Open Quality resource:** `{resource.id}`\n\n{resource.metadata.get('description', '')}"
201
+ lines = [f"**Open Quality resource:** `{resource.id}`"]
202
+ if kind == "QualityRequirement":
203
+ lines += [
204
+ resource.spec.get("statement", ""),
205
+ "",
206
+ f"- Priority: {resource.spec.get('priority', '')}",
207
+ ]
208
+ elif kind == "Stage":
209
+ if resource.spec.get("description"):
210
+ lines += ["", resource.spec["description"]]
211
+ if resource.spec.get("dependsOn"):
212
+ lines += [
213
+ "",
214
+ "- Depends on: `" + "`, `".join(resource.spec["dependsOn"]) + "`",
215
+ ]
216
+ else:
217
+ lines += [
218
+ "",
219
+ "All rules must pass:",
220
+ *[
221
+ f"- `{rule.get('metric')} {rule.get('operator')} {rule.get('value')}`"
222
+ for rule in resource.spec.get("rules", [])
223
+ ],
224
+ f"- Failure action: `{resource.spec.get('failure', {}).get('action', '')}`",
225
+ ]
226
+ return "\n".join(lines)
227
+
228
+
229
+ def plan(
230
+ bundle: Bundle, state: ProviderState, config: TargetConfig, members: list[ProjectMember] | None = None
231
+ ) -> list[Operation]:
232
+ assert bundle.project
233
+ workflow = bundle.workflows[bundle.project.spec["workflow"]]
234
+ items: list[tuple[Resource, str, str, str]] = [
235
+ (bundle.project, "Project", bundle.project.name, "")
236
+ ]
237
+ items += [
238
+ (
239
+ bundle.requirements[item],
240
+ "QualityRequirement",
241
+ bundle.requirements[item].name,
242
+ bundle.project.id,
243
+ )
244
+ for item in quality_requirements(bundle.project)
245
+ ]
246
+ items += [
247
+ (
248
+ bundle.stages[item],
249
+ "Stage",
250
+ bundle.stages[item].name,
251
+ bundle.project.id,
252
+ )
253
+ for item in workflow.spec["stages"]
254
+ ]
255
+ operations = []
256
+ for resource, kind, subject, parent in items:
257
+ description = _description(resource, kind)
258
+ digest = hashlib.sha256(
259
+ "\0".join([kind, subject, description, parent]).encode()
260
+ ).hexdigest()
261
+ action = (
262
+ "no-op"
263
+ if resource.id in state.resources
264
+ and state.resources[resource.id].hash == digest
265
+ else "update" if resource.id in state.resources else "create"
266
+ )
267
+ operations.append(
268
+ Operation(action, resource.id, kind, subject, description, parent, digest)
269
+ )
270
+ members = members or []
271
+ stages = {stage_id: bundle.stages[stage_id] for stage_id in workflow.spec["stages"]}
272
+ bootstrap: list[Operation] = []
273
+ if stages:
274
+ _append_operation(
275
+ bootstrap, state, f"kanban:{bundle.project.id}", "KanbanBoard",
276
+ bundle.project.name, "Kanban board for the development workflow", bundle.project.id,
277
+ {"projectIdentifier": bundle.project.id, "columns": json.dumps(config.kanban_columns)},
278
+ )
279
+ for member in members:
280
+ _append_operation(
281
+ bootstrap, state, f"member:{member.email}", "ProjectMember", member.email,
282
+ f"{member.role} → {member.openproject_role}", bundle.project.id,
283
+ {"email": member.email, "role": member.openproject_role},
284
+ )
285
+ # Project infrastructure must exist before the workflow work packages.
286
+ operations[1:1] = bootstrap
287
+ for stage in stages.values():
288
+ if stage.spec.get("reviewScope") != "code":
289
+ continue
290
+ policy_id = stage.spec.get("approvalPolicy")
291
+ if not policy_id:
292
+ raise ValueError(f"code review stage {stage.id!r} requires approvalPolicy")
293
+ policy = bundle.approval_policies[policy_id]
294
+ reviewer_roles = set(policy.spec["approvers"])
295
+ for member in members:
296
+ if member.role in reviewer_roles:
297
+ _append_operation(
298
+ operations, state, f"code-reviewer:{stage.id}:{member.email}", "CodeReviewer",
299
+ member.email, f"Code reviewer for {stage.name}", stage.id,
300
+ {"email": member.email},
301
+ )
302
+ return operations
303
+
304
+
305
+ def _append_operation(
306
+ operations: list[Operation], state: ProviderState, resource_id: str, kind: str,
307
+ subject: str, description: str, parent: str, data: dict[str, str] | None = None,
308
+ ) -> None:
309
+ digest = hashlib.sha256("\0".join([kind, subject, description, parent, json.dumps(data or {}, sort_keys=True)]).encode()).hexdigest()
310
+ action = "no-op" if resource_id in state.resources and state.resources[resource_id].hash == digest else "update" if resource_id in state.resources else "create"
311
+ operations.append(Operation(action, resource_id, kind, subject, description, parent, digest, data or {}))
312
+
313
+
314
+ class OpenProjectClient:
315
+ def __init__(self, config: TargetConfig, token: str):
316
+ self.config, self.token = config, token
317
+
318
+ def _request(
319
+ self, method: str, path: str, payload: dict[str, Any] | None = None
320
+ ) -> dict[str, Any]:
321
+ url = (
322
+ path
323
+ if path.startswith("http")
324
+ else self.config.base_url.rstrip("/") + "/" + path.lstrip("/")
325
+ )
326
+ request = Request(
327
+ url,
328
+ method=method,
329
+ data=json.dumps(payload).encode() if payload else None,
330
+ headers={
331
+ "Authorization": "Bearer " + self.token,
332
+ "Accept": "application/hal+json",
333
+ "Content-Type": "application/json",
334
+ },
335
+ )
336
+ try:
337
+ with urlopen(request, timeout=30) as response:
338
+ return json.load(response)
339
+ except HTTPError as error:
340
+ body = error.read().decode()
341
+ try:
342
+ response = json.loads(body)
343
+ message = response.get("message", body)
344
+ details = response.get("_embedded", {}).get("details")
345
+ if details:
346
+ message += ": " + json.dumps(details, ensure_ascii=False)
347
+ elif response.get("_embedded"):
348
+ message += ": " + json.dumps(
349
+ response["_embedded"], ensure_ascii=False
350
+ )
351
+ except json.JSONDecodeError:
352
+ message = body or "no response body"
353
+ raise ValueError(
354
+ f"OpenProject returned {error.code} {error.reason}: {message}"
355
+ ) from error
356
+
357
+ def find_project(self, identifier: str) -> tuple[int, str] | None:
358
+ try:
359
+ result = self._request("GET", f"/api/v3/projects/{quote(identifier, safe='')}")
360
+ except ValueError as error:
361
+ if " 404 " in str(error):
362
+ return None
363
+ raise
364
+ href = result.get("_links", {}).get("self", {}).get("href", "")
365
+ if not result.get("id") or not href:
366
+ raise ValueError("OpenProject project response is missing id or self link")
367
+ return result["id"], href
368
+
369
+ def _collection(self, path: str) -> list[dict[str, Any]]:
370
+ return self._request("GET", path).get("_embedded", {}).get("elements", [])
371
+
372
+ def _user_href(self, email: str) -> str:
373
+ # OpenProject 17 exposes email in User resources but does not support it
374
+ # as an API v3 filter. Match the returned user records exactly instead.
375
+ users = [
376
+ user
377
+ for user in self._collection("/api/v3/users?pageSize=1000")
378
+ if user.get("email", "").casefold() == email.casefold()
379
+ ]
380
+ if not users:
381
+ # An invited account needs only an email address. OpenProject sends
382
+ # the activation invitation and returns the newly created user.
383
+ created = self._request(
384
+ "POST", "/api/v3/users", {"email": email, "status": "invited"}
385
+ )
386
+ href = created.get("_links", {}).get("self", {}).get("href")
387
+ if not href:
388
+ raise ValueError(
389
+ f"OpenProject invitation response is missing self link for {email!r}"
390
+ )
391
+ return href
392
+ if len(users) != 1:
393
+ raise ValueError(f"multiple OpenProject users found for email {email!r}")
394
+ href = users[0].get("_links", {}).get("self", {}).get("href")
395
+ if not href:
396
+ raise ValueError(f"OpenProject user response is missing self link for {email!r}")
397
+ return href
398
+
399
+ def _role_href(self, name: str) -> str:
400
+ for role in self._collection("/api/v3/roles?pageSize=1000"):
401
+ if role.get("name") == name:
402
+ return role["_links"]["self"]["href"]
403
+ raise ValueError(f"OpenProject role not found: {name!r}")
404
+
405
+ def _kanban_columns(self, columns: list[str]) -> list[dict[str, Any]]:
406
+ statuses = {status.get("name"): status for status in self._collection("/api/v3/statuses")}
407
+ missing = [column for column in columns if column not in statuses]
408
+ if missing:
409
+ raise ValueError("OpenProject Kanban status not found: " + ", ".join(repr(column) for column in missing))
410
+ return [statuses[column] for column in columns]
411
+
412
+ def _set_kanban_columns(
413
+ self, board: dict[str, Any], columns: list[str]
414
+ ) -> dict[str, Any]:
415
+ if not columns:
416
+ return board
417
+ statuses = self._kanban_columns(columns)
418
+ configured = []
419
+ for index, status in enumerate(statuses, start=1):
420
+ configured.append(
421
+ {
422
+ "_type": "GridWidget",
423
+ "identifier": "work_package_query",
424
+ "startRow": 1,
425
+ "endRow": 2,
426
+ "startColumn": index,
427
+ "endColumn": index + 1,
428
+ "options": {
429
+ "filters": [
430
+ {
431
+ "status_id": {
432
+ "operator": "=",
433
+ "values": [str(status["id"])],
434
+ }
435
+ }
436
+ ]
437
+ },
438
+ }
439
+ )
440
+ payload = {
441
+ "name": board.get("name", ""),
442
+ "options": {"type": "action", "attribute": "status"},
443
+ "rowCount": 2,
444
+ "columnCount": len(configured) + 1,
445
+ "widgets": configured,
446
+ "_links": {"scope": board.get("_links", {}).get("scope", {})},
447
+ }
448
+ href = board["_links"]["self"]["href"]
449
+ # Grid updates retain widgets that are not explicitly removed. Clear the
450
+ # existing lists first so the requested columns cannot overlap them.
451
+ clear_payload = {
452
+ "name": board.get("name", ""),
453
+ "options": {"type": "action", "attribute": "status"},
454
+ "rowCount": 1,
455
+ "columnCount": 1,
456
+ "widgets": [],
457
+ "_links": {"scope": board.get("_links", {}).get("scope", {})},
458
+ }
459
+ self._request("PATCH", href, clear_payload)
460
+ return self._request("PATCH", href, payload)
461
+
462
+ def create_kanban_board(
463
+ self, project_identifier: str, name: str, columns: list[str]
464
+ ) -> tuple[int, str]:
465
+ payload = {
466
+ "name": name,
467
+ "_links": {"scope": {"href": f"/projects/{project_identifier}/boards"}},
468
+ "options": {"type": "action", "attribute": "status"},
469
+ }
470
+ if columns:
471
+ statuses = self._kanban_columns(columns)
472
+ payload["rowCount"] = 2
473
+ payload["columnCount"] = len(statuses) + 1
474
+ payload["widgets"] = [
475
+ {
476
+ "_type": "GridWidget",
477
+ "identifier": "work_package_query",
478
+ "startRow": 1,
479
+ "endRow": 2,
480
+ "startColumn": index,
481
+ "endColumn": index + 1,
482
+ "options": {"filters": [{"status_id": {"operator": "=", "values": [str(status["id"])]}}]},
483
+ }
484
+ for index, status in enumerate(statuses, start=1)
485
+ ]
486
+ form = self._request("POST", "/api/v3/grids/form", payload)
487
+ write_payload = form.get("_embedded", {}).get("payload", payload)
488
+ result = self._request("POST", "/api/v3/grids", write_payload)
489
+ href = result.get("_links", {}).get("self", {}).get("href", "")
490
+ if not result.get("id") or not href:
491
+ raise ValueError("OpenProject Kanban board response is missing id or self link")
492
+ result = self._request("GET", href)
493
+ result = self._set_kanban_columns(result, columns)
494
+ href = result.get("_links", {}).get("self", {}).get("href", "")
495
+ if not result.get("id") or not href:
496
+ raise ValueError("OpenProject Kanban board response is missing id or self link")
497
+ return result["id"], href
498
+
499
+ def update_kanban_board(self, href: str, columns: list[str]) -> tuple[int, str]:
500
+ result = self._set_kanban_columns(self._request("GET", href), columns)
501
+ return result["id"], result["_links"]["self"]["href"]
502
+
503
+ def update_project(self, href: str, name: str) -> tuple[int, str]:
504
+ current = self._request("GET", href)
505
+ result = self._request(
506
+ "PATCH", href, {"name": name, "lockVersion": current.get("lockVersion", 0)}
507
+ )
508
+ return result["id"], result["_links"]["self"]["href"]
509
+
510
+ def add_member(self, project_href: str, email: str, role: str) -> tuple[int, str]:
511
+ result = self._request("POST", "/api/v3/memberships", {
512
+ "_links": {
513
+ "project": {"href": project_href},
514
+ "principal": {"href": self._user_href(email)},
515
+ "roles": [{"href": self._role_href(role)}],
516
+ },
517
+ "_meta": {"sendNotifications": False},
518
+ })
519
+ return result["id"], result["_links"]["self"]["href"]
520
+
521
+ def add_code_reviewer(self, work_package_href: str, email: str) -> tuple[int, str]:
522
+ user_href = self._user_href(email)
523
+ self._request("POST", work_package_href + "/watchers", {"user": {"href": user_href}})
524
+ return int(user_href.rsplit("/", 1)[-1]), user_href
525
+
526
+ def create(self, input: Operation, parent_href: str, project_href: str = "") -> tuple[int, str]:
527
+ if input.kind == "Project":
528
+ result = self._request(
529
+ "POST",
530
+ "/api/v3/projects",
531
+ {"identifier": input.resource_id, "name": input.subject},
532
+ )
533
+ return result["id"], result["_links"]["self"]["href"]
534
+ project_id = project_href.rsplit("/", 1)[-1]
535
+ return self._write(
536
+ "POST",
537
+ f"/api/v3/projects/{quote(project_id, safe='')}/work_packages?notify={str(self.config.notify).lower()}",
538
+ input,
539
+ parent_href,
540
+ project_href=project_href,
541
+ )
542
+
543
+ def update(self, href: str, input: Operation, parent_href: str) -> tuple[int, str]:
544
+ current = self._request("GET", href)
545
+ return self._write(
546
+ "PATCH",
547
+ href + f"?notify={str(self.config.notify).lower()}",
548
+ input,
549
+ parent_href,
550
+ current.get("lockVersion", 0),
551
+ )
552
+
553
+ def _write(
554
+ self,
555
+ method: str,
556
+ path: str,
557
+ operation: Operation,
558
+ parent: str,
559
+ lock: int | None = None,
560
+ project_href: str = "",
561
+ ) -> tuple[int, str]:
562
+ links: dict[str, Any] = {"type": {"href": self.config.type_href}}
563
+ if project_href:
564
+ links["project"] = {"href": project_href}
565
+ if parent:
566
+ links["parent"] = {"href": parent}
567
+ body: dict[str, Any] = {
568
+ "subject": operation.subject,
569
+ "description": {"format": "markdown", "raw": operation.description},
570
+ "_links": links,
571
+ }
572
+ if lock is not None:
573
+ body["lockVersion"] = lock
574
+ result = self._request(method, path, body)
575
+ href = result.get("_links", {}).get("self", {}).get("href", "")
576
+ if not result.get("id") or not href:
577
+ raise ValueError("OpenProject response is missing id or self link")
578
+ return result["id"], href
579
+
580
+
581
+ def apply(
582
+ operations: list[Operation], state: ProviderState, client: OpenProjectClient,
583
+ checkpoint: Callable[[ProviderState], None] | None = None,
584
+ ) -> ProviderState:
585
+ for operation in operations:
586
+ if operation.action == "no-op":
587
+ continue
588
+ parent = state.resources.get(operation.parent)
589
+ if operation.parent and not parent:
590
+ raise ValueError(
591
+ f"parent resource {operation.parent!r} has not been materialized"
592
+ )
593
+ project = state.resources.get(
594
+ next((item.resource_id for item in operations if item.kind == "Project"), "")
595
+ )
596
+ try:
597
+ if operation.kind == "KanbanBoard":
598
+ if not parent:
599
+ raise ValueError("Kanban board requires an OpenProject project")
600
+ columns = json.loads(operation.data["columns"])
601
+ external_id, href = (
602
+ client.update_kanban_board(
603
+ state.resources[operation.resource_id].href, columns
604
+ )
605
+ if operation.action == "update"
606
+ else client.create_kanban_board(
607
+ operation.data["projectIdentifier"], operation.subject, columns
608
+ )
609
+ )
610
+ elif operation.kind == "ProjectMember":
611
+ if not parent:
612
+ raise ValueError("project member requires an OpenProject project")
613
+ external_id, href = client.add_member(
614
+ parent.href, operation.data["email"], operation.data["role"]
615
+ )
616
+ elif operation.kind == "CodeReviewer":
617
+ if not parent:
618
+ raise ValueError("code reviewer requires a code-review work package")
619
+ external_id, href = client.add_code_reviewer(parent.href, operation.data["email"])
620
+ elif operation.kind == "Project" and operation.action == "update":
621
+ external_id, href = client.update_project(
622
+ state.resources[operation.resource_id].href, operation.subject
623
+ )
624
+ else:
625
+ external_id, href = (
626
+ client.update(
627
+ state.resources[operation.resource_id].href,
628
+ operation,
629
+ parent.href if parent and parent.kind != "Project" else "",
630
+ )
631
+ if operation.action == "update"
632
+ else client.create(
633
+ operation,
634
+ parent.href if parent and parent.kind != "Project" else "",
635
+ project.href if project else "",
636
+ )
637
+ )
638
+ except ValueError as error:
639
+ raise ValueError(
640
+ f"{operation.action} {operation.kind} {operation.subject!r}: {error}"
641
+ ) from error
642
+ state.resources[operation.resource_id] = ExternalResource(
643
+ operation.resource_id,
644
+ operation.kind,
645
+ external_id,
646
+ href,
647
+ operation.hash,
648
+ datetime.now(UTC).isoformat(),
649
+ )
650
+ if checkpoint:
651
+ checkpoint(state)
652
+ return state
653
+
654
+
655
+ class OpenProjectProvider:
656
+ """OpenProject implementation of the provider adapter contract."""
657
+
658
+ name = "openproject"
659
+
660
+ def __init__(self, config: TargetConfig, token: str):
661
+ self.config = config
662
+ self.client = OpenProjectClient(config, token)
663
+
664
+ def plan(
665
+ self, bundle: Bundle, state: ProviderState, members: list[ProjectMember]
666
+ ) -> list[Operation]:
667
+ return plan(bundle, state, self.config, members)
668
+
669
+ def apply(
670
+ self, operations: list[Operation], state: ProviderState,
671
+ checkpoint: Callable[[ProviderState], None] | None = None,
672
+ ) -> ProviderState:
673
+ return apply(operations, state, self.client, checkpoint)