forked from viamrobotics/rdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync_jira_release.py
More file actions
303 lines (243 loc) · 9.56 KB
/
sync_jira_release.py
File metadata and controls
303 lines (243 loc) · 9.56 KB
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#!/usr/bin/env python3
"""
GitHub to Jira Release Sync
Syncs a specific release from viamrobotics/rdk to Jira RSDK project
Usage:
python sync_jira_release.py 0.42.0
Environment Variables Required:
GITHUB_TOKEN - GitHub personal access token
JIRA_BASE_URL - Your Jira instance URL (e.g., https://your-domain.atlassian.net)
JIRA_EMAIL - Your Jira email address
JIRA_API_TOKEN - Jira API token
"""
import os
import re
import sys
import requests
# Configuration
GITHUB_REPO = "viamrobotics/rdk"
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
JIRA_BASE_URL = os.getenv("JIRA_BASE_URL")
JIRA_EMAIL = os.getenv("JIRA_EMAIL")
JIRA_API_TOKEN = os.getenv("JIRA_API_TOKEN")
JIRA_PROJECT_KEY = "RSDK"
# Validate environment variables
if not all([GITHUB_TOKEN, JIRA_BASE_URL, JIRA_EMAIL, JIRA_API_TOKEN]):
print("❌ Missing required environment variables!")
print(" Required: GITHUB_TOKEN, JIRA_BASE_URL, JIRA_EMAIL, JIRA_API_TOKEN")
sys.exit(1)
# Jira auth
jira_auth = (JIRA_EMAIL, JIRA_API_TOKEN)
# GitHub headers
github_headers = {
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {GITHUB_TOKEN}",
"X-GitHub-Api-Version": "2022-11-28"
}
def validate_version(version):
"""Validate that the input is a valid version string (e.g., 0.42.0 or v0.42.0)"""
if re.fullmatch(r'v?\d+\.\d+\.\d+', version):
return version
return None
def verify_release_exists(version):
"""Verify release exists on GitHub"""
tag = version if version.startswith('v') else f'v{version}'
url = f"https://api.github.com/repos/{GITHUB_REPO}/releases/tags/{tag}"
response = requests.get(url, headers=github_headers)
if response.status_code == 200:
return response.json(), tag
else:
raise Exception(f"Release {tag} not found on {GITHUB_REPO}")
def get_tickets_from_release_notes(tag):
"""
Get Jira tickets directly from GitHub release notes/description
Much simpler than comparing commits between releases
"""
url = f"https://api.github.com/repos/{GITHUB_REPO}/releases/tags/{tag}"
response = requests.get(url, headers=github_headers)
if response.status_code != 200:
raise Exception(f"Could not fetch release notes for {tag}")
release_data = response.json()
# Get the release description/body
body = release_data.get('body', '')
if not body:
print(f"⚠️ Warning: Release {tag} has no description/notes")
return []
# Extract all RSDK-XXX ticket IDs from the release notes
pattern = f"{JIRA_PROJECT_KEY}-\\d+"
tickets = list(set(re.findall(pattern, body, re.IGNORECASE)))
return tickets
def create_jira_version(github_version):
"""Create version in Jira RSDK project with format 'rdk {version}'"""
# Format as "rdk {version}"
jira_version_name = f"rdk {github_version}"
url = f"{JIRA_BASE_URL}/rest/api/3/version"
payload = {
"name": jira_version_name,
"project": JIRA_PROJECT_KEY,
"released": False,
"description": f"Release {github_version} from {GITHUB_REPO}"
}
response = requests.post(
url,
auth=jira_auth,
headers={"Content-Type": "application/json"},
json=payload
)
if response.status_code == 201:
return response.json()
elif response.status_code == 400:
# Version exists, fetch it
search_url = f"{JIRA_BASE_URL}/rest/api/3/project/{JIRA_PROJECT_KEY}/versions"
versions = requests.get(search_url, auth=jira_auth).json()
return next((v for v in versions if v["name"] == jira_version_name), None)
else:
raise Exception(f"Failed to create version: {response.text}")
def get_ticket_status(ticket_key):
"""Get current status of ticket"""
url = f"{JIRA_BASE_URL}/rest/api/3/issue/{ticket_key}"
params = {"fields": "status"}
response = requests.get(url, auth=jira_auth, params=params)
if response.status_code == 200:
return response.json()["fields"]["status"]["name"]
return None
def set_fix_version(ticket_key, version_id):
"""Set fix version on a ticket without transitioning it."""
update_url = f"{JIRA_BASE_URL}/rest/api/3/issue/{ticket_key}"
update_payload = {
"fields": {
"fixVersions": [{"id": version_id}]
}
}
response = requests.put(
update_url,
auth=jira_auth,
headers={"Content-Type": "application/json"},
json=update_payload
)
if response.status_code != 204:
print(f"⚠️ Failed to set fix version for {ticket_key}")
return False
return True
def set_fix_version_and_close(ticket_key, version_id):
"""
Step 1: Set fix version while in "Awaiting Release"
Step 2: Transition ticket to Closed
"""
# Step 1: Set fix version first
update_url = f"{JIRA_BASE_URL}/rest/api/3/issue/{ticket_key}"
update_payload = {
"fields": {
"fixVersions": [{"id": version_id}]
}
}
response = requests.put(
update_url,
auth=jira_auth,
headers={"Content-Type": "application/json"},
json=update_payload
)
if response.status_code != 204:
print(f"⚠️ Failed to set fix version for {ticket_key}")
return False
# Step 2: Get available transitions
transitions_url = f"{JIRA_BASE_URL}/rest/api/3/issue/{ticket_key}/transitions"
response = requests.get(transitions_url, auth=jira_auth)
transitions = response.json().get("transitions", [])
close_transition = next(
(t for t in transitions if t.get("to", {}).get("name", "").lower() == "closed"),
None
)
if not close_transition:
available = [f"{t['name']} → {t.get('to', {}).get('name', '?')}" for t in transitions]
print(f"⚠️ No transition to 'Closed' status for {ticket_key}. Available: {available}")
return False
# Step 3: Transition to Closed with Resolution "Done"
payload = {
"transition": {"id": close_transition["id"]},
"fields": {
"resolution": {"name": "Done"}
}
}
response = requests.post(
transitions_url,
auth=jira_auth,
headers={"Content-Type": "application/json"},
json=payload
)
return response.status_code == 204
def main(version_input):
"""Main workflow triggered by user prompt"""
# 1. Validate version input
version = validate_version(version_input)
if not version:
print(f"❌ Invalid version format: {version_input}")
print(" Expected format: 0.42.0 or v0.42.0")
return
print(f"🔍 Version: {version}")
# 2. Verify release exists on GitHub
print(f"🔍 Checking GitHub for release...")
try:
release_data, tag = verify_release_exists(version)
print(f"✅ Found release {tag} on GitHub")
print(f" Published: {release_data['published_at'][:10]}")
print(f" Author: {release_data['author']['login']}\n")
except Exception as e:
print(f"❌ {e}")
return
# 3. Create Jira version
print(f"📦 Creating Jira version: rdk {version}")
jira_version = create_jira_version(version)
if not jira_version:
print(f"❌ Failed to create Jira version")
return
version_id = jira_version["id"]
print(f"✅ Jira version: {jira_version['name']} (ID: {version_id})\n")
# 4. Extract Jira tickets from release notes
print(f"🔍 Extracting Jira tickets from release notes...")
ticket_keys = get_tickets_from_release_notes(tag)
print(f"📋 Found {len(ticket_keys)} unique tickets:")
print(f" {', '.join(ticket_keys) if ticket_keys else 'None'}\n")
if not ticket_keys:
print("⚠️ No Jira tickets found in this release")
return
# 5. Process tickets in "Awaiting Release"
print(f"🔄 Processing tickets...\n")
closed_count = 0
skipped_count = 0
tagged_count = 0
for ticket_key in ticket_keys:
status = get_ticket_status(ticket_key)
if status == "Awaiting Release":
print(f" {ticket_key}: {status} → Setting fix version & closing...")
if set_fix_version_and_close(ticket_key, version_id):
print(f" ✅ {ticket_key} closed with fix version rdk {version}")
closed_count += 1
else:
print(f" ❌ Failed to close {ticket_key}")
elif status == "Closed":
print(f" {ticket_key}: {status} → Tagging fix version...")
if set_fix_version(ticket_key, version_id):
print(f" ✅ {ticket_key} tagged with fix version rdk {version}")
tagged_count += 1
else:
print(f" ❌ Failed to tag fix version for {ticket_key}")
else:
print(f" ⏭️ {ticket_key}: {status} (skipped)")
skipped_count += 1
# 6. Summary
print(f"\n{'='*60}")
print(f"🎉 Release sync complete!")
print(f" Version: rdk {version}")
print(f" Tickets closed: {closed_count}")
print(f" Tickets tagged (already closed): {tagged_count}")
print(f" Tickets skipped: {skipped_count}")
print(f" Total tickets: {len(ticket_keys)}")
print(f" Release page: {JIRA_BASE_URL}/projects/{JIRA_PROJECT_KEY}/versions/{version_id}/tab/release-report-all-issues")
print(f"{'='*60}")
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python sync_jira_release.py <version>")
print(" e.g. python sync_jira_release.py 0.42.0")
sys.exit(1)
main(sys.argv[1])