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.
- cli/__init__.py +1 -0
- cli/cli.py +248 -0
- cli/core.py +553 -0
- cli/model.py +63 -0
- cli/provider.py +40 -0
- cli/providers/__init__.py +5 -0
- cli/providers/github.py +106 -0
- cli/providers/gitlab.py +73 -0
- cli/providers/interfaces.py +24 -0
- cli/providers/jira_cloud.py +122 -0
- cli/providers/openproject.py +673 -0
- cli/renderer.py +81 -0
- open_quality_cli-0.1.0.dist-info/METADATA +168 -0
- open_quality_cli-0.1.0.dist-info/RECORD +19 -0
- open_quality_cli-0.1.0.dist-info/WHEEL +5 -0
- open_quality_cli-0.1.0.dist-info/entry_points.txt +2 -0
- open_quality_cli-0.1.0.dist-info/licenses/LICENSE +674 -0
- open_quality_cli-0.1.0.dist-info/licenses/NOTICE +6 -0
- open_quality_cli-0.1.0.dist-info/top_level.txt +1 -0
cli/providers/github.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""GitHub enforcement provider for development-stage policies."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from urllib.error import HTTPError
|
|
9
|
+
from urllib.parse import quote
|
|
10
|
+
from urllib.request import Request, urlopen
|
|
11
|
+
|
|
12
|
+
import yaml
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class GitHubConfig:
|
|
16
|
+
name: str
|
|
17
|
+
owner: str
|
|
18
|
+
repository: str
|
|
19
|
+
visibility: str = "private"
|
|
20
|
+
members_file: str = ""
|
|
21
|
+
base_url: str = "https://api.github.com"
|
|
22
|
+
|
|
23
|
+
def token(self) -> str:
|
|
24
|
+
token = os.getenv("GITHUB_TOKEN")
|
|
25
|
+
if not token:
|
|
26
|
+
raise ValueError("environment variable GITHUB_TOKEN is empty")
|
|
27
|
+
return token
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def load_config(path: str | Path | dict, role: str = "") -> GitHubConfig:
|
|
31
|
+
try:
|
|
32
|
+
raw = (path if isinstance(path, dict) else yaml.safe_load(Path(path).read_text())) or {}
|
|
33
|
+
config = raw.get("config") or {}
|
|
34
|
+
if raw.get("provider") != "github":
|
|
35
|
+
raise ValueError("provider must be github")
|
|
36
|
+
if set(raw) - {"provider", "config", "description"}:
|
|
37
|
+
raise ValueError("target has an unknown field")
|
|
38
|
+
allowed = {"owner", "repository", "visibility", "membersFile", "members", "baseURL"}
|
|
39
|
+
if set(config) - allowed:
|
|
40
|
+
raise ValueError("GitHub config has an unknown field")
|
|
41
|
+
required = ["owner", "repository"]
|
|
42
|
+
if any(not isinstance(config.get(key), str) or not config[key] for key in required):
|
|
43
|
+
raise ValueError("owner and repository are required")
|
|
44
|
+
visibility = config.get("visibility", "private")
|
|
45
|
+
if visibility not in {"public", "private"}:
|
|
46
|
+
raise ValueError("visibility must be public or private")
|
|
47
|
+
return GitHubConfig(role or raw["provider"], config["owner"], config["repository"], visibility, config.get("membersFile", ""), config.get("baseURL", "https://api.github.com"))
|
|
48
|
+
except Exception as error:
|
|
49
|
+
raise ValueError(f"target {path}: {error}") from error
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True)
|
|
53
|
+
class GitHubMember:
|
|
54
|
+
role: str
|
|
55
|
+
username: str
|
|
56
|
+
permission: str
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def load_members(path: str | Path | dict) -> list[GitHubMember]:
|
|
60
|
+
try:
|
|
61
|
+
raw = (path if isinstance(path, dict) else yaml.safe_load(Path(path).read_text())) or {}
|
|
62
|
+
if raw.get("provider") != "github" or set(raw) - {"provider", "members"}:
|
|
63
|
+
raise ValueError("must contain only provider: github and members")
|
|
64
|
+
members = []
|
|
65
|
+
for item in raw.get("members", []):
|
|
66
|
+
if set(item) - {"role", "usernames", "permission"}:
|
|
67
|
+
raise ValueError("member contains an unknown field")
|
|
68
|
+
role, usernames, permission = item.get("role"), item.get("usernames"), item.get("permission")
|
|
69
|
+
if not isinstance(role, str) or not isinstance(usernames, list) or permission not in {"pull", "push", "triage", "maintain", "admin"}:
|
|
70
|
+
raise ValueError("member requires role, usernames and a valid permission")
|
|
71
|
+
members.extend(GitHubMember(role, username, permission) for username in usernames if isinstance(username, str) and username)
|
|
72
|
+
return members
|
|
73
|
+
except Exception as error:
|
|
74
|
+
raise ValueError(f"members {path}: {error}") from error
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class GitHubClient:
|
|
78
|
+
def __init__(self, config: GitHubConfig, token: str): self.config, self.token = config, token
|
|
79
|
+
def request(self, method: str, path: str, body: dict | None = None) -> dict:
|
|
80
|
+
request = Request(self.config.base_url.rstrip("/") + path, method=method, data=json.dumps(body).encode() if body is not None else None, headers={"Accept": "application/vnd.github+json", "Authorization": f"Bearer {self.token}", "X-GitHub-Api-Version": "2022-11-28", "Content-Type": "application/json"})
|
|
81
|
+
try:
|
|
82
|
+
with urlopen(request, timeout=30) as response:
|
|
83
|
+
return json.load(response) if response.length != 0 else {}
|
|
84
|
+
except HTTPError as error:
|
|
85
|
+
raise ValueError(f"GitHub returned {error.code}: {error.read().decode()}") from error
|
|
86
|
+
@property
|
|
87
|
+
def repository_path(self) -> str: return f"/repos/{quote(self.config.owner)}/{quote(self.config.repository)}"
|
|
88
|
+
def ensure_repository(self) -> dict:
|
|
89
|
+
try:
|
|
90
|
+
return self.request("GET", self.repository_path)
|
|
91
|
+
except ValueError as error:
|
|
92
|
+
if "404" not in str(error):
|
|
93
|
+
raise
|
|
94
|
+
account = self.request("GET", "/user")
|
|
95
|
+
payload = {"name": self.config.repository, "private": self.config.visibility == "private"}
|
|
96
|
+
if account.get("login", "").casefold() == self.config.owner.casefold():
|
|
97
|
+
return self.request("POST", "/user/repos", payload)
|
|
98
|
+
return self.request("POST", f"/orgs/{quote(self.config.owner)}/repos", payload)
|
|
99
|
+
def invite_member(self, member: GitHubMember) -> None:
|
|
100
|
+
self.request("PUT", f"{self.repository_path}/collaborators/{quote(member.username)}", {"permission": member.permission})
|
|
101
|
+
def apply(config: GitHubConfig, members: list[GitHubMember] | None = None) -> int:
|
|
102
|
+
client = GitHubClient(config, config.token())
|
|
103
|
+
client.ensure_repository()
|
|
104
|
+
for member in members or []:
|
|
105
|
+
client.invite_member(member)
|
|
106
|
+
return 1
|
cli/providers/gitlab.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""GitLab provider for development-stage policies."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from urllib.error import HTTPError
|
|
9
|
+
from urllib.parse import quote
|
|
10
|
+
from urllib.request import Request, urlopen
|
|
11
|
+
|
|
12
|
+
import yaml
|
|
13
|
+
|
|
14
|
+
ACCESS_LEVELS = {"guest": 10, "reporter": 20, "developer": 30, "maintainer": 40}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class GitLabConfig:
|
|
19
|
+
name: str; base_url: str; project: str
|
|
20
|
+
def token(self) -> str:
|
|
21
|
+
token = os.getenv("GITLAB_TOKEN")
|
|
22
|
+
if not token: raise ValueError("environment variable GITLAB_TOKEN is empty")
|
|
23
|
+
return token
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class GitLabMember:
|
|
28
|
+
role: str; username: str; access_level: str
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def load_config(source: str | Path | dict, role: str = "") -> GitLabConfig:
|
|
32
|
+
try:
|
|
33
|
+
raw = (source if isinstance(source, dict) else yaml.safe_load(Path(source).read_text())) or {}; cfg = raw.get("config") or {}
|
|
34
|
+
if raw.get("provider") != "gitlab": raise ValueError("provider must be gitlab")
|
|
35
|
+
if set(raw) - {"provider", "config", "description"}: raise ValueError("target has an unknown field")
|
|
36
|
+
if set(cfg) - {"baseURL", "project", "members"}: raise ValueError("GitLab config has an unknown field")
|
|
37
|
+
if any(not cfg.get(key) for key in ("baseURL", "project")): raise ValueError("baseURL and project are required")
|
|
38
|
+
return GitLabConfig(role or raw["provider"], cfg["baseURL"], cfg["project"])
|
|
39
|
+
except Exception as error: raise ValueError(f"target {source}: {error}") from error
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def load_members(raw: dict) -> list[GitLabMember]:
|
|
43
|
+
members = []
|
|
44
|
+
for item in raw.get("members", []):
|
|
45
|
+
if set(item) - {"role", "usernames", "accessLevel"}: raise ValueError("GitLab member contains an unknown field")
|
|
46
|
+
role, usernames, access = item.get("role"), item.get("usernames"), item.get("accessLevel")
|
|
47
|
+
if not isinstance(role, str) or not isinstance(usernames, list) or access not in ACCESS_LEVELS: raise ValueError("GitLab member requires role, usernames and accessLevel")
|
|
48
|
+
if not all(isinstance(username, str) and username for username in usernames): raise ValueError("GitLab usernames must be non-empty strings")
|
|
49
|
+
members.extend(GitLabMember(role, username, access) for username in usernames)
|
|
50
|
+
return members
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class GitLabClient:
|
|
54
|
+
def __init__(self, config: GitLabConfig, token: str): self.config, self.token = config, token
|
|
55
|
+
def request(self, method: str, path: str, body: dict | None = None) -> dict | list:
|
|
56
|
+
request = Request(self.config.base_url.rstrip("/") + path, method=method, data=json.dumps(body).encode() if body is not None else None, headers={"PRIVATE-TOKEN": self.token, "Content-Type": "application/json"})
|
|
57
|
+
try:
|
|
58
|
+
with urlopen(request, timeout=30) as response:
|
|
59
|
+
payload = response.read(); return json.loads(payload) if payload else {}
|
|
60
|
+
except HTTPError as error: raise ValueError(f"GitLab returned {error.code}: {error.read().decode()}") from error
|
|
61
|
+
@property
|
|
62
|
+
def project_path(self) -> str: return "/projects/" + quote(self.config.project, safe="")
|
|
63
|
+
def project(self) -> dict: return self.request("GET", self.project_path) # type: ignore[return-value]
|
|
64
|
+
def invite_member(self, project_id: int, member: GitLabMember) -> None:
|
|
65
|
+
users = self.request("GET", f"/users?username={quote(member.username)}")
|
|
66
|
+
if not isinstance(users, list) or not users: raise ValueError(f"GitLab user not found: {member.username}")
|
|
67
|
+
self.request("POST", f"/projects/{project_id}/members", {"user_id": users[0]["id"], "access_level": ACCESS_LEVELS[member.access_level]})
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def apply(config: GitLabConfig, members: list[GitLabMember]) -> int:
|
|
71
|
+
client = GitLabClient(config, config.token()); project = client.project()
|
|
72
|
+
for member in members: client.invite_member(project["id"], member)
|
|
73
|
+
return 1
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Provider contracts shared by every external-system adapter."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Protocol, Sequence
|
|
7
|
+
|
|
8
|
+
from ..model import Bundle
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ProviderAdapter(Protocol):
|
|
12
|
+
"""Plans and materializes a quality bundle in an external provider."""
|
|
13
|
+
|
|
14
|
+
name: str
|
|
15
|
+
|
|
16
|
+
def plan(self, bundle: Bundle, state: object) -> Sequence[object]: ...
|
|
17
|
+
|
|
18
|
+
def apply(self, operations: Sequence[object], state: object) -> object: ...
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class TargetLoader(Protocol):
|
|
22
|
+
"""Loads provider-specific target configuration from a YAML document."""
|
|
23
|
+
|
|
24
|
+
def load(self, path: str | Path) -> object: ...
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Jira Cloud provider using the Jira REST API v3."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import base64
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
from dataclasses import asdict, dataclass, field
|
|
9
|
+
from datetime import UTC, datetime
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, Callable
|
|
12
|
+
from urllib.error import HTTPError
|
|
13
|
+
from urllib.parse import quote
|
|
14
|
+
from urllib.request import Request, urlopen
|
|
15
|
+
|
|
16
|
+
import yaml
|
|
17
|
+
|
|
18
|
+
from ..model import Bundle, Resource
|
|
19
|
+
from .openproject import ExternalResource, Operation
|
|
20
|
+
from ..core import quality_requirements
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class JiraConfig:
|
|
25
|
+
provider: str; name: str; base_url: str; project_key: str; template_key: str; issue_type: str; members_file: str = ""; columns: list[str] = field(default_factory=list)
|
|
26
|
+
def credentials(self) -> tuple[str, str]:
|
|
27
|
+
email, token = os.getenv("JIRA_EMAIL"), os.getenv("JIRA_API_TOKEN")
|
|
28
|
+
if not email or not token: raise ValueError("JIRA_EMAIL and JIRA_API_TOKEN are required for apply")
|
|
29
|
+
return email, token
|
|
30
|
+
|
|
31
|
+
def load_config(path: str | Path | dict, role: str = "") -> JiraConfig:
|
|
32
|
+
raw = (path if isinstance(path, dict) else yaml.safe_load(Path(path).read_text())) or {}; cfg = raw.get("config") or {}
|
|
33
|
+
try:
|
|
34
|
+
if raw.get("provider") != "jira-cloud": raise ValueError("provider must be jira-cloud")
|
|
35
|
+
if set(raw) - {"provider", "config", "description"}: raise ValueError("provider has an unknown field")
|
|
36
|
+
if set(cfg) - {"baseURL", "projectKey", "projectTemplateKey", "issueTypeName", "membersFile", "members", "kanban"}: raise ValueError("Jira config has an unknown field")
|
|
37
|
+
required = ["baseURL", "projectKey"]
|
|
38
|
+
if any(not cfg.get(key) for key in required): raise ValueError("baseURL and projectKey are required")
|
|
39
|
+
kanban = cfg.get("kanban") or {}; columns = kanban.get("columns", [])
|
|
40
|
+
if not isinstance(columns, list) or not all(isinstance(x, str) and x for x in columns): raise ValueError("kanban.columns must be a list of strings")
|
|
41
|
+
return JiraConfig("jira-cloud", role or raw["provider"], cfg["baseURL"], cfg["projectKey"], cfg.get("projectTemplateKey", "com.pyxis.greenhopper.jira:gh-kanban-template"), cfg.get("issueTypeName", "Task"), cfg.get("membersFile", ""), columns)
|
|
42
|
+
except Exception as error: raise ValueError(f"target {path}: {error}") from error
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class JiraMember: role: str; email: str; jira_role: str
|
|
46
|
+
def load_members(path: str | Path | dict) -> list[JiraMember]:
|
|
47
|
+
raw = (path if isinstance(path, dict) else yaml.safe_load(Path(path).read_text())) or {}
|
|
48
|
+
if raw.get("provider") != "jira-cloud": raise ValueError("members provider must be jira-cloud")
|
|
49
|
+
result=[]
|
|
50
|
+
for item in raw.get("members", []):
|
|
51
|
+
for email in item.get("emails", []): result.append(JiraMember(item["role"], email, item["jiraProjectRole"]))
|
|
52
|
+
return result
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class JiraState:
|
|
56
|
+
version: int; provider: str; target: str; resources: dict[str, ExternalResource] = field(default_factory=dict)
|
|
57
|
+
def load_state(path: str | Path, target: str) -> JiraState:
|
|
58
|
+
p=Path(path)
|
|
59
|
+
if not p.exists(): return JiraState(1,"jira-cloud",target)
|
|
60
|
+
raw=json.loads(p.read_text())
|
|
61
|
+
if raw.get("provider") != "jira-cloud" or raw.get("target") != target: raise ValueError("state belongs to another provider or target")
|
|
62
|
+
return JiraState(raw.get("version",1),raw["provider"],raw["target"],{k:ExternalResource(**v) for k,v in raw.get("resources",{}).items()})
|
|
63
|
+
def save_state(path: str | Path, state: JiraState) -> None:
|
|
64
|
+
p=Path(path); p.parent.mkdir(mode=0o700, parents=True,exist_ok=True); temporary=p.with_name(p.name+".tmp"); temporary.write_text(json.dumps({"version":state.version,"provider":state.provider,"target":state.target,"resources":{k:asdict(v) for k,v in state.resources.items()}},indent=2)+"\n"); temporary.replace(p)
|
|
65
|
+
|
|
66
|
+
def _op(state:JiraState,rid:str,kind:str,subject:str,parent:str="",data:dict[str,str]|None=None)->Operation:
|
|
67
|
+
data=data or {}; digest=hashlib.sha256(json.dumps([kind,subject,parent,data],sort_keys=True).encode()).hexdigest(); action="no-op" if rid in state.resources and state.resources[rid].hash==digest else "update" if rid in state.resources else "create"; return Operation(action,rid,kind,subject,"",parent,digest,data)
|
|
68
|
+
def plan(bundle:Bundle,state:JiraState,config:JiraConfig,members:list[JiraMember])->list[Operation]:
|
|
69
|
+
assert bundle.project; workflow=bundle.workflows[bundle.project.spec["workflow"]]; ops=[_op(state,bundle.project.id,"Project",bundle.project.name,data={"key":config.project_key})]
|
|
70
|
+
if workflow.spec["stages"]:
|
|
71
|
+
ops.append(_op(state,"kanban:"+bundle.project.id,"KanbanBoard",bundle.project.name,bundle.project.id,{"key":config.project_key,"columns":json.dumps(config.columns)}))
|
|
72
|
+
ops += [_op(state,"member:"+m.email,"ProjectMember",m.email,bundle.project.id,{"email":m.email,"role":m.jira_role}) for m in members]
|
|
73
|
+
for rid in quality_requirements(bundle.project): ops.append(_op(state,rid,"QualityRequirement",bundle.requirements[rid].name,bundle.project.id))
|
|
74
|
+
for rid in workflow.spec["stages"]: ops.append(_op(state,rid,"Stage",bundle.stages[rid].name,bundle.project.id))
|
|
75
|
+
return ops
|
|
76
|
+
|
|
77
|
+
class JiraClient:
|
|
78
|
+
def __init__(self,c:JiraConfig,email:str,token:str): self.c=c; self.auth="Basic "+base64.b64encode(f"{email}:{token}".encode()).decode()
|
|
79
|
+
def req(self,method:str,path:str,body:dict|None=None)->dict:
|
|
80
|
+
q=Request(self.c.base_url.rstrip("/")+path,method=method,data=json.dumps(body).encode() if body else None,headers={"Authorization":self.auth,"Accept":"application/json","Content-Type":"application/json"})
|
|
81
|
+
try:
|
|
82
|
+
with urlopen(q,timeout=30) as r: return json.load(r) if r.readable() and r.length != 0 else {}
|
|
83
|
+
except HTTPError as e: raise ValueError(f"Jira returned {e.code} {e.reason}: {e.read().decode()}") from e
|
|
84
|
+
def project(self,key:str)->dict|None:
|
|
85
|
+
try:return self.req("GET","/rest/api/3/project/"+quote(key))
|
|
86
|
+
except ValueError as e:
|
|
87
|
+
if "404" in str(e): return None
|
|
88
|
+
raise
|
|
89
|
+
def invite(self,email:str)->str:
|
|
90
|
+
try: return self.req("POST","/rest/api/3/user",{"emailAddress":email,"products":["jira-software"]})["accountId"]
|
|
91
|
+
except ValueError as e:
|
|
92
|
+
if "already" not in str(e).lower(): raise
|
|
93
|
+
users=self.req("GET","/rest/api/3/user/assignable/search?project="+quote(self.c.project_key)+"&query="+quote(email)); return next(u["accountId"] for u in users if u.get("emailAddress","").lower()==email.lower())
|
|
94
|
+
def ensure_kanban_board(self,name:str)->tuple[int,str]:
|
|
95
|
+
boards=self.req("GET","/rest/agile/1.0/board?projectKeyOrId="+quote(self.c.project_key)+"&name="+quote(name))
|
|
96
|
+
for board in boards.get("values",[]):
|
|
97
|
+
if board.get("name")==name:
|
|
98
|
+
return int(board["id"]),board.get("self",f"/rest/agile/1.0/board/{board['id']}").replace(self.c.base_url,"")
|
|
99
|
+
filter_result=self.req("POST","/rest/api/3/filter",{"name":f"Open Quality: {name}","jql":f"project = {self.c.project_key} ORDER BY Rank ASC"})
|
|
100
|
+
board=self.req("POST","/rest/agile/1.0/board",{"name":name,"type":"kanban","filterId":int(filter_result["id"]),"location":{"type":"project","projectKeyOrId":self.c.project_key}})
|
|
101
|
+
return int(board["id"]),board.get("self",f"/rest/agile/1.0/board/{board['id']}").replace(self.c.base_url,"")
|
|
102
|
+
|
|
103
|
+
def apply(ops:list[Operation],state:JiraState,client:JiraClient,config:JiraConfig,checkpoint:Callable[[JiraState],None]|None=None)->JiraState:
|
|
104
|
+
for op in ops:
|
|
105
|
+
if op.action=="no-op": continue
|
|
106
|
+
try:
|
|
107
|
+
if op.kind=="Project":
|
|
108
|
+
current=client.project(config.project_key); result=current or client.req("POST","/rest/api/3/project",{"key":config.project_key,"name":op.subject,"projectTypeKey":"software","projectTemplateKey":config.template_key,"leadAccountId":client.req("GET","/rest/api/3/myself")["accountId"]}); eid=int(result["id"]); href="/rest/api/3/project/"+config.project_key
|
|
109
|
+
elif op.kind=="KanbanBoard": eid,href=client.ensure_kanban_board(op.subject)
|
|
110
|
+
elif op.kind=="ProjectMember":
|
|
111
|
+
aid=client.invite(op.data["email"]); roles=client.req("GET",f"/rest/api/3/project/{config.project_key}/role"); url=roles.get(op.data["role"])
|
|
112
|
+
if not url:
|
|
113
|
+
expected=op.data["role"].casefold().rstrip("s")
|
|
114
|
+
url=next((href for name,href in roles.items() if name.casefold().rstrip("s")==expected),None)
|
|
115
|
+
if not url: raise ValueError(f"Jira project role not found: {op.data['role']}; available: {', '.join(roles)}")
|
|
116
|
+
client.req("POST",url.replace(config.base_url,""),{"user":[aid]}); eid=0; href=url
|
|
117
|
+
else:
|
|
118
|
+
issue=client.req("POST","/rest/api/3/issue",{"fields":{"project":{"key":config.project_key},"summary":op.subject,"issuetype":{"name":config.issue_type}}}); eid=int(issue["id"]); href="/rest/api/3/issue/"+issue["id"]
|
|
119
|
+
state.resources[op.resource_id]=ExternalResource(op.resource_id,op.kind,eid,href,op.hash,datetime.now(UTC).isoformat())
|
|
120
|
+
if checkpoint: checkpoint(state)
|
|
121
|
+
except ValueError as e: raise ValueError(f"{op.action} {op.kind} {op.subject!r}: {e}") from e
|
|
122
|
+
return state
|