-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_retype.py
More file actions
285 lines (236 loc) · 11 KB
/
main_retype.py
File metadata and controls
285 lines (236 loc) · 11 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
import json
import os
from methods import init_session
from methods import recursively_convert_parameter_for_event
RESUME_FILE = "retype_resume.json"
VALID_TYPES = ("STRING", "INTEGER", "FLOAT", "BOOLEAN", "TIMESTAMP")
def parameter_in_tree(parameter_list, parameter_name):
"""True if parameter_name appears anywhere in the parameter tree."""
for param in parameter_list:
if param["name"] == parameter_name:
return True
if parameter_in_tree(param.get("children", []), parameter_name):
return True
return False
def remove_parameter_from_tree(parameter_list, parameter_name):
"""Return a new parameter list with all occurrences of parameter_name pruned."""
new_list = []
for param in parameter_list:
if param["name"] == parameter_name:
continue
new_param = dict(param)
if "children" in new_param:
new_param["children"] = remove_parameter_from_tree(new_param["children"], parameter_name)
new_list.append(new_param)
return new_list
def save_resume(state):
with open(RESUME_FILE, "w") as f:
json.dump(state, f, indent=2)
def load_resume():
if not os.path.exists(RESUME_FILE):
return None
with open(RESUME_FILE, "r") as f:
return json.load(f)
def clear_resume():
if os.path.exists(RESUME_FILE):
os.remove(RESUME_FILE)
# ---------------------------- init + confirm ----------------------------
rh, settings, src_project, _ = init_session(validate_src=True, validate_target=False)
org_id = settings["srcOrgId"]
project_id = settings["srcProjectId"]
environment_id = settings["srcEnvId"]
project_name = src_project.get("name", "Unknown Project")
print(" CHANGE A PARAMETER'S TYPE (admin operation) ")
print("-------------------------------------------------")
print(f"Here's a link to the project {project_name}:")
print(f"https://cloud.unity.com/home/organizations/{org_id}/projects/{project_id}/environments/{environment_id}")
input("If this is correct, press enter to continue... If not, terminate the script and change the settings.json file.")
# ---------------------------- resume detection ----------------------------
resume = load_resume()
if resume:
if (resume["org_id"] != org_id
or resume["project_id"] != project_id
or resume["environment_id"] != environment_id):
print("-------------------------------------------------")
print("A resume file exists but it targets a different environment than settings.json:")
print(f" resume: org={resume['org_id']} project={resume['project_id']} env={resume['environment_id']}")
print(f" settings: org={org_id} project={project_id} env={environment_id}")
print("Refusing to continue. Fix settings.json to match the resume file, or delete the resume file.")
exit(1)
print("-------------------------------------------------")
print(f"Resume file found:")
print(f" parameter: {resume['parameter_name']}")
print(f" new type: {resume['new_type']}")
print(f" phase: {resume['phase']}")
print(f" events known: {len(resume['affected_events'])}")
answer = input("Resume? [y/N]: ").strip().lower()
if answer != "y":
print("Not resuming. Delete retype_resume.json manually if you want to start fresh.")
exit(0)
parameter_name = resume["parameter_name"]
new_type = resume["new_type"]
affected_events = resume["affected_events"]
phase = resume["phase"]
else:
# --------------- pick parameter and target type ---------------
print("-------------------------------------------------")
print("Fetching parameters...")
all_params = rh.get_parameters(org_id, project_id, environment_id)
if not all_params:
print("No parameters returned. Token may be expired (cookie 'token' at https://cloud.unity.com/).")
exit(1)
selectable = [p for p in all_params if p["type"] not in ("OBJECT", "ARRAY")]
for i, p in enumerate(selectable):
print(f"{i} - {p['name']} ({p['type']})")
idx = input("Select parameter number: ").strip()
if not idx.isdigit() or int(idx) < 0 or int(idx) >= len(selectable):
print("Invalid index. Exiting.")
exit(1)
chosen = selectable[int(idx)]
parameter_name = chosen["name"]
old_type = chosen["type"]
print(f"New type options: {', '.join(VALID_TYPES)}")
new_type = input("New type: ").strip().upper()
if new_type not in VALID_TYPES:
print(f"Invalid type: {new_type}")
exit(1)
if new_type == old_type:
print(f"Parameter '{parameter_name}' is already {old_type}. Nothing to do.")
exit(0)
print("-------------------------------------------------")
print(f"Will retype '{parameter_name}': {old_type} -> {new_type}")
print("This is an admin operation. If the parameter is attached to any events the script")
print("will unlink it from each event, retype it, then re-link it. Progress is checkpointed")
print(f"to {RESUME_FILE} after every step so an interruption can be resumed.")
confirm = input(f"Press enter to continue THERE WILL BE NO FURTHER CONFIRMATIONS:").strip()
if confirm != parameter_name:
print("Mismatch. Exiting. ")
exit(1)
affected_events = []
phase = "start"
def persist():
save_resume({
"parameter_name": parameter_name,
"new_type": new_type,
"org_id": org_id,
"project_id": project_id,
"environment_id": environment_id,
"phase": phase,
"affected_events": affected_events,
})
def parameter_now_has_type(target_type):
"""Re-fetch the parameter and check its current type. Returns None on fetch failure."""
fetched = rh.get_parameter_by_id(org_id, project_id, environment_id, parameter_name)
if not fetched:
return None
return fetched.get("type") == target_type
# ---------------------------- attempt direct retype ----------------------------
if phase == "start":
print(f"\nAttempting direct retype of '{parameter_name}' -> {new_type}...")
result = rh.change_parameter_type(org_id, project_id, environment_id, parameter_name, new_type)
verdict = parameter_now_has_type(new_type)
if verdict is None:
print("Could not re-fetch the parameter to verify the retype. Aborting before any destructive action.")
exit(1)
if verdict:
print(f"SUCCESS: parameter '{parameter_name}' is now {new_type}.")
clear_resume()
exit(0)
print("Direct retype did not take effect — the parameter is likely attached to one or more events.")
print("Discovering affected events...")
schemas = rh.get_schemas(org_id, project_id, environment_id)
if not schemas:
print("Failed to fetch schemas. Aborting.")
exit(1)
for summary in schemas:
full = rh.get_schema_by_id(org_id, project_id, environment_id, summary["name"])
if not full:
continue
if parameter_in_tree(full.get("parameters", []), parameter_name):
print(f" - '{full['name']}' contains '{parameter_name}'")
affected_events.append({
"event_name": full["name"],
"description": full.get("description", ""),
"is_enabled": full.get("isEnabled", True),
"original_parameters": full["parameters"],
"unlinked": False,
"relinked": False,
})
if not affected_events:
print(f"No events were found containing '{parameter_name}', but the retype still failed.")
print("Manual investigation required (likely a permission or validation problem).")
exit(1)
phase = "discovered"
persist()
print(f"\n{len(affected_events)} affected event(s) saved to {RESUME_FILE}.")
# ---------------------------- unlink phase ----------------------------
if phase == "discovered":
print(f"\nUnlinking '{parameter_name}' from {len(affected_events)} event(s)...")
for entry in affected_events:
if entry["unlinked"]:
continue
pruned = remove_parameter_from_tree(entry["original_parameters"], parameter_name)
resp = rh.update_schema(
org_id, project_id, environment_id,
entry["event_name"], entry["description"], pruned, entry["is_enabled"],
)
if not resp:
print(f" FAILED to unlink from '{entry['event_name']}'. Aborting; resume file kept.")
persist()
exit(1)
entry["unlinked"] = True
persist()
print(f" unlinked from '{entry['event_name']}'")
phase = "unlinked"
persist()
# ---------------------------- second retype attempt ----------------------------
if phase == "unlinked":
print(f"\nRetrying retype of '{parameter_name}' -> {new_type}...")
rh.change_parameter_type(org_id, project_id, environment_id, parameter_name, new_type)
verdict = parameter_now_has_type(new_type)
if verdict is None:
print("Could not re-fetch the parameter to verify the retype. Resume file kept.")
exit(1)
if not verdict:
print("Retype still did not take effect after unlinking. Resume file kept.")
print("Investigate manually. Re-running this script will resume from the 'unlinked' phase")
print("and will NOT restore the parameter to events until the retype succeeds —")
print("if you need to abandon the retype, restore the events from the resume file by hand.")
exit(1)
phase = "retyped"
persist()
print(f" retype OK")
# ---------------------------- relink phase ----------------------------
if phase == "retyped":
print(f"\nRe-linking '{parameter_name}' to {len(affected_events)} event(s)...")
failures = []
for entry in affected_events:
if entry["relinked"]:
continue
# original_parameters carries the pre-retype type fields. Convert to the
# POST/PUT shape ({name, isRequired, children}) so the embedded type info
# cannot disagree with the parameter resource's new type.
clean = [recursively_convert_parameter_for_event(p) for p in entry["original_parameters"]]
resp = rh.update_schema(
org_id, project_id, environment_id,
entry["event_name"], entry["description"], clean, entry["is_enabled"],
)
if not resp:
print(f" FAILED to re-link to '{entry['event_name']}'")
failures.append(entry["event_name"])
persist()
continue
entry["relinked"] = True
persist()
print(f" re-linked to '{entry['event_name']}'")
if failures:
print(f"\nPartial success: '{parameter_name}' is now {new_type}, but {len(failures)} event(s) could not be re-linked:")
for name in failures:
print(f" - {name}")
print("Resume file kept. Re-run the script to retry just the failed re-links.")
exit(1)
phase = "relinked"
persist()
# ---------------------------- done ----------------------------
print(f"\nSUCCESS: '{parameter_name}' retyped to {new_type} and re-linked to {len(affected_events)} event(s).")
clear_resume()