-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjira.py
199 lines (165 loc) · 6.85 KB
/
jira.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
#!python3
# -*- coding: utf-8 -*-
import datetime
import json
import os
import sys
from argparse import ArgumentParser
from base64 import b64encode
from urllib import request
from urllib.error import HTTPError
from subprocess import check_call
from typing import Any, Optional, Dict
def _fail(msg: str) -> None:
print(f"::error::{msg}" if os.environ.get("CI") else msg)
sys.exit(1)
def _get_status_code(req: request.Request) -> int:
try:
return request.urlopen(req).status
except HTTPError as e:
return e.status
def _get_json(req: request.Request) -> Any:
try:
response = request.urlopen(req)
except HTTPError:
return None
else:
return json.loads(response.read())
def _assert_ok_status(req: request.Request) -> None:
status = _get_status_code(req)
if 200 <= status < 300:
return
_fail(f"request `{req.full_url}` failed with status code {status}")
class Jira:
def __init__(self, base_url: str, username: str, password: str) -> None:
self.base_url = base_url
self.username = username
self.password = password
def add_attachment(self, issue: str, path: str) -> None:
check_call([
"curl",
"--user", f"{self.username}:{self.password}",
"--request", "POST",
"--header", "X-Atlassian-Token: nocheck", # disable XSRF check
"--form", f"file=@{os.path.abspath(path)}",
f"{self.base_url}/rest/api/2/issue/{issue}/attachments",
])
def add_comments(self, comments_file: str) -> None:
with open(comments_file, mode='r') as cf:
comments = json.load(cf)
for issue, comment in comments.items():
if isinstance(comment, dict):
attachments = comment.get('attachments', [])
comment = comment.get('comment', '')
else:
attachments = []
for attachment in attachments:
self.add_attachment(issue, attachment)
self.add_comment(issue, comment)
def add_comment(self, issue: str, comment: str) -> None:
_assert_ok_status(
self._request(
f"issue/{issue}/comment",
headers={"Content-Type": "application/json"},
data=json.dumps({"body": comment}).encode(),
)
)
def get_issue(self, issue: str) -> Any:
return _get_json(self._request(f"issue/{issue}"))
def get_version(self, project: str, version: str) -> Any:
versions = _get_json(self._request(f"project/{project}/versions"))
if versions:
for version_data in versions:
if version_data.get("name") == version:
return version_data
def release_version(self, project: str, version: str) -> None:
version_data = self.get_version(project, version)
if version_data is None:
_fail(f"version {version} in project {project} does not exist")
_assert_ok_status(
self._request(
f"version/{version_data['id']}",
method="PUT",
headers={"Content-Type": "application/json"},
data=json.dumps({
"released": True,
"releaseDate": datetime.date.today().strftime("%Y-%m-%d")
}).encode()
)
)
def close_issue(self, issue: str) -> None:
transitions = _get_json(self._request(f"issue/{issue}/transitions"))
if transitions is None:
_fail(f"could not fetch available transitions")
close_transition = next((t for t in transitions.get("transitions", []) if t.get("to", {}).get("name") == "Geschlossen"), None)
if close_transition is None:
_fail(f"issue {issue} does not have a close transition")
_assert_ok_status(
self._request(
f"issue/{issue}/transitions",
method="POST",
headers={"Content-Type": "application/json"},
data=json.dumps({
"fields": {"resolution": {"name": "Done"}},
"transition": {"id": close_transition["id"]},
}).encode()
)
)
def _request(
self,
path: str,
method: Optional[str] = None,
headers: Optional[Dict[str, str]] = None,
data: Optional[bytes] = None
) -> request.Request:
login = f"{self.username}:{self.password}"
return request.Request(
f"{self.base_url}/rest/api/2/{path}",
method=method,
headers={
"Authorization": "Basic " + b64encode(login.encode()).decode(),
**(headers or {})
},
data=data
)
if __name__ == "__main__":
parser = ArgumentParser("JIRA")
parser.add_argument("--base-url", required=True)
parser.add_argument("--username", required=True)
parser.add_argument("--password", required=True)
subparsers = parser.add_subparsers(required=True)
add_comment_parser = subparsers.add_parser("add-comment")
add_comment_parser.set_defaults(func=Jira.add_comment)
add_comment_parser.add_argument("--issue", required=True)
add_comment_parser.add_argument("--comment", required=True)
add_attachments = subparsers.add_parser("add-attachment")
add_attachments.set_defaults(func=Jira.add_attachment)
add_attachments.add_argument("--issue", required=True)
add_attachments.add_argument("--path", required=True)
add_comments_parser = subparsers.add_parser("add-comments")
add_comments_parser.set_defaults(func=Jira.add_comments)
add_comments_parser.add_argument("--comments-file", required=True)
get_issue_parser = subparsers.add_parser("get-issue")
get_issue_parser.set_defaults(func=Jira.get_issue)
get_issue_parser.add_argument("--issue", required=True)
get_version_parser = subparsers.add_parser("get-version")
get_version_parser.set_defaults(func=Jira.get_version)
get_version_parser.add_argument("--project", required=True)
get_version_parser.add_argument("--version", required=True)
release_version_parser = subparsers.add_parser("release-version")
release_version_parser.set_defaults(func=Jira.release_version)
release_version_parser.add_argument("--project", required=True)
release_version_parser.add_argument("--version", required=True)
close_issue_parser = subparsers.add_parser("close-issue")
close_issue_parser.set_defaults(func=Jira.close_issue)
close_issue_parser.add_argument("--issue", required=True)
args = parser.parse_args().__dict__
jira = Jira(
base_url=args.pop("base_url"),
username=args.pop("username"),
password=args.pop("password"),
)
func = args.pop("func")
result = func(jira, **args)
if result is not None:
print(json.dumps(result, indent=2))