aic-utils 2.0.3__tar.gz → 2.0.4__tar.gz
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.
- {aic_utils-2.0.3 → aic_utils-2.0.4}/PKG-INFO +1 -1
- {aic_utils-2.0.3 → aic_utils-2.0.4}/aic_utils/__init__.py +1 -1
- {aic_utils-2.0.3 → aic_utils-2.0.4}/aic_utils/gitlabmanager.py +202 -84
- {aic_utils-2.0.3 → aic_utils-2.0.4}/aic_utils.egg-info/PKG-INFO +1 -1
- {aic_utils-2.0.3 → aic_utils-2.0.4}/setup.py +1 -1
- {aic_utils-2.0.3 → aic_utils-2.0.4}/README.md +0 -0
- {aic_utils-2.0.3 → aic_utils-2.0.4}/aic_utils/aic.py +0 -0
- {aic_utils-2.0.3 → aic_utils-2.0.4}/aic_utils/dataset_converter.py +0 -0
- {aic_utils-2.0.3 → aic_utils-2.0.4}/aic_utils/gitlab_init.py +0 -0
- {aic_utils-2.0.3 → aic_utils-2.0.4}/aic_utils/slack_logger.py +0 -0
- {aic_utils-2.0.3 → aic_utils-2.0.4}/aic_utils.egg-info/SOURCES.txt +0 -0
- {aic_utils-2.0.3 → aic_utils-2.0.4}/aic_utils.egg-info/dependency_links.txt +0 -0
- {aic_utils-2.0.3 → aic_utils-2.0.4}/aic_utils.egg-info/requires.txt +0 -0
- {aic_utils-2.0.3 → aic_utils-2.0.4}/aic_utils.egg-info/top_level.txt +0 -0
- {aic_utils-2.0.3 → aic_utils-2.0.4}/setup.cfg +0 -0
|
@@ -479,13 +479,13 @@ class GitLabManager:
|
|
|
479
479
|
"""
|
|
480
480
|
return subject, body
|
|
481
481
|
|
|
482
|
-
def
|
|
482
|
+
def _collect_code_actions(self, pipeline_name: str, job_config: dict) -> list:
|
|
483
483
|
"""
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
484
|
+
Walk `job_config` and produce a list of (file_path, content) tuples for
|
|
485
|
+
every PYSPARK script, SQL query, and triple-quoted SQL block extracted
|
|
486
|
+
from PYSPARK scripts. No I/O — caller batches the writes.
|
|
487
487
|
"""
|
|
488
|
-
|
|
488
|
+
out = []
|
|
489
489
|
|
|
490
490
|
def _find_all_tasks(obj):
|
|
491
491
|
if isinstance(obj, dict):
|
|
@@ -501,7 +501,6 @@ class GitLabManager:
|
|
|
501
501
|
for task in _find_all_tasks(job_config):
|
|
502
502
|
if not isinstance(task, dict):
|
|
503
503
|
continue
|
|
504
|
-
|
|
505
504
|
task_type = task.get("type", "").upper()
|
|
506
505
|
if task_type not in ("PYSPARK", "SQL"):
|
|
507
506
|
continue
|
|
@@ -514,44 +513,60 @@ class GitLabManager:
|
|
|
514
513
|
script = cfg.get("script")
|
|
515
514
|
if not script:
|
|
516
515
|
continue
|
|
517
|
-
|
|
518
|
-
# Push the full PySpark script
|
|
519
|
-
py_filename = f"{base_folder}/{task_id}.py"
|
|
520
|
-
self._push_file(proj, py_filename, script, branch=self._branch)
|
|
521
|
-
|
|
522
|
-
# Extract triple-quoted SQL blocks
|
|
516
|
+
out.append((f"{base_folder}/{task_id}.py", script))
|
|
523
517
|
pattern = re.compile(r"'''(.*?)'''|\"\"\"(.*?)\"\"\"", re.DOTALL)
|
|
524
|
-
|
|
525
|
-
for idx, m in enumerate(matches, start=1):
|
|
518
|
+
for idx, m in enumerate(pattern.findall(script), start=1):
|
|
526
519
|
sql_block = m[0] if m[0] else m[1]
|
|
527
520
|
stripped = sql_block.strip()
|
|
528
521
|
first_word = stripped.split(None, 1)[0].lower() if stripped else ""
|
|
529
|
-
if first_word
|
|
522
|
+
if first_word in {
|
|
530
523
|
"select", "insert", "update", "delete",
|
|
531
524
|
"with", "create", "drop", "alter", "merge"
|
|
532
525
|
}:
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
self._push_file(proj, sql_filename, stripped, branch=self._branch)
|
|
536
|
-
|
|
537
|
-
else: # task_type == "SQL"
|
|
526
|
+
out.append((f"{base_folder}/{task_id}_{idx}.sql", stripped))
|
|
527
|
+
else: # SQL
|
|
538
528
|
sql_text = cfg.get("query") or cfg.get("script") or cfg.get("sql")
|
|
539
529
|
if not sql_text:
|
|
540
530
|
continue
|
|
541
|
-
|
|
542
|
-
|
|
531
|
+
out.append((f"{base_folder}/{task_id}.sql", sql_text.strip()))
|
|
532
|
+
|
|
533
|
+
return out
|
|
534
|
+
|
|
535
|
+
def _extract_and_push_code(self, pipeline_name: str, job_config: dict):
|
|
536
|
+
"""
|
|
537
|
+
Backward-compatible wrapper: collect code actions and push them via the
|
|
538
|
+
batched commits API. Kept so external callers continue to work.
|
|
539
|
+
"""
|
|
540
|
+
actions_pairs = self._collect_code_actions(pipeline_name, job_config)
|
|
541
|
+
if not actions_pairs:
|
|
542
|
+
return
|
|
543
|
+
existing = set(self._list_all_paths(self._branch))
|
|
544
|
+
actions = [
|
|
545
|
+
{
|
|
546
|
+
"action": "update" if path in existing else "create",
|
|
547
|
+
"file_path": path,
|
|
548
|
+
"content": content,
|
|
549
|
+
}
|
|
550
|
+
for path, content in actions_pairs
|
|
551
|
+
]
|
|
552
|
+
self._commit_batched_actions(
|
|
553
|
+
actions=actions,
|
|
554
|
+
branch=self._branch,
|
|
555
|
+
commit_msg_prefix=f"Sync code for pipeline '{pipeline_name}'",
|
|
556
|
+
)
|
|
543
557
|
|
|
544
558
|
def push_to_git(self):
|
|
545
559
|
"""
|
|
546
|
-
Push pipeline JSON and code to GitLab
|
|
560
|
+
Push pipeline JSON and code to GitLab using the GitLab Commits API to
|
|
561
|
+
batch up to 50 file writes per commit (vs the previous one-commit-per-file
|
|
562
|
+
behavior, which produced hundreds of commits per push and choked GitLab's
|
|
563
|
+
merge-base computation on large workspaces).
|
|
547
564
|
"""
|
|
548
|
-
|
|
549
565
|
if self._branch == self.default_branch:
|
|
550
566
|
force_push = input('⚠️ WARNING: You are attempting to overwrite the Production branch with existing AIC code. Proceed? (y/n)')
|
|
551
567
|
if force_push.lower() != 'y':
|
|
552
568
|
raise ValueError('Production Push refused. Exiting.')
|
|
553
|
-
|
|
554
|
-
# Guard: only allow pushes on configured branches or hotfix prefixes
|
|
569
|
+
|
|
555
570
|
if (
|
|
556
571
|
self._branch not in self._allowed_push
|
|
557
572
|
and not any(self._branch.startswith(pref) for pref in self._hotfix_prefixes)
|
|
@@ -562,35 +577,65 @@ class GitLabManager:
|
|
|
562
577
|
f"Allowed hotfix prefixes: {self._hotfix_prefixes}\n"
|
|
563
578
|
)
|
|
564
579
|
|
|
565
|
-
# Ensure branch exists
|
|
566
580
|
self.ensure_branch_exists(branch_name=self._branch, ref=self._branch)
|
|
567
|
-
proj = self.project_path.replace('/', '%2F')
|
|
568
|
-
results = []
|
|
569
581
|
|
|
570
|
-
#
|
|
582
|
+
# Build the full list of (file_path, content) pairs for this push.
|
|
583
|
+
all_pairs = []
|
|
584
|
+
results = []
|
|
585
|
+
per_pipeline_pairs = {}
|
|
571
586
|
for cfg in self.aic.pipeline_configs:
|
|
572
|
-
name
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
587
|
+
name = cfg['name']
|
|
588
|
+
pairs = [
|
|
589
|
+
(f"config/{name}.json", json.dumps(cfg['jobConfig'], indent=2)),
|
|
590
|
+
]
|
|
591
|
+
pairs.extend(self._collect_code_actions(name, cfg['jobConfig']))
|
|
592
|
+
per_pipeline_pairs[name] = pairs
|
|
593
|
+
all_pairs.extend(pairs)
|
|
594
|
+
|
|
595
|
+
if not all_pairs:
|
|
596
|
+
print("No pipeline content to push.")
|
|
597
|
+
self._send_email(*self._format_push_summary(self._branch, []), testing=False)
|
|
598
|
+
return
|
|
581
599
|
|
|
582
|
-
#
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
600
|
+
# Pre-fetch existing files on branch so we can choose create vs update.
|
|
601
|
+
try:
|
|
602
|
+
existing = set(self._list_all_paths(self._branch))
|
|
603
|
+
except Exception as e:
|
|
604
|
+
print(f"⚠️ Could not list existing tree on '{self._branch}' ({e}); falling back to create-or-update probe.")
|
|
605
|
+
existing = None
|
|
606
|
+
|
|
607
|
+
actions = []
|
|
608
|
+
for path, content in all_pairs:
|
|
609
|
+
if existing is None:
|
|
610
|
+
# Conservative default: try update; GitLab will reject create-on-existing
|
|
611
|
+
# but accept update on an existing file. If that errors per-batch, we
|
|
612
|
+
# retry that batch with action=create. Done in _commit_batched_actions.
|
|
613
|
+
action_type = "update"
|
|
614
|
+
else:
|
|
615
|
+
action_type = "update" if path in existing else "create"
|
|
616
|
+
actions.append({
|
|
617
|
+
"action": action_type,
|
|
618
|
+
"file_path": path,
|
|
619
|
+
"content": content,
|
|
620
|
+
})
|
|
621
|
+
|
|
622
|
+
n_files = len(actions)
|
|
623
|
+
n_pipelines = len(self.aic.pipeline_configs)
|
|
624
|
+
msg_prefix = f"Sync {n_pipelines} pipeline(s) ({n_files} files) from AIC workspace '{self.aic.workspace}'"
|
|
625
|
+
print(f"Pushing {n_files} files across {n_pipelines} pipeline(s) to '{self._branch}' in batches of 50...")
|
|
626
|
+
try:
|
|
627
|
+
self._commit_batched_actions(
|
|
628
|
+
actions=actions,
|
|
629
|
+
branch=self._branch,
|
|
630
|
+
commit_msg_prefix=msg_prefix,
|
|
631
|
+
)
|
|
632
|
+
for name in per_pipeline_pairs:
|
|
633
|
+
results.append((name, 'Success', f"{len(per_pipeline_pairs[name])} files"))
|
|
634
|
+
except Exception as e:
|
|
635
|
+
print(f"❌ Batched push failed: {e}")
|
|
636
|
+
for name in per_pipeline_pairs:
|
|
637
|
+
results.append((name, 'Failure', str(e)[:160]))
|
|
592
638
|
|
|
593
|
-
# Summary email
|
|
594
639
|
subj, body = self._format_push_summary(self._branch, results)
|
|
595
640
|
self._send_email(subj, body, testing=False)
|
|
596
641
|
|
|
@@ -805,48 +850,107 @@ class GitLabManager:
|
|
|
805
850
|
commit_msg_prefix: str
|
|
806
851
|
):
|
|
807
852
|
"""
|
|
808
|
-
Batch-delete multiple files in a single (or multiple) commit(s)
|
|
809
|
-
|
|
810
|
-
- paths_to_delete: list of file paths (e.g. "config/FOO.json" or "code/PL_XYZ/foo.sql").
|
|
811
|
-
- branch: the GitLab branch to apply the deletion on (e.g. "release/test5").
|
|
812
|
-
- commit_msg_prefix: a prefix for the commit message; each batch appends "(batch N of M)".
|
|
813
|
-
|
|
814
|
-
Splits into batches of 50 files each if needed.
|
|
853
|
+
Batch-delete multiple files in a single (or multiple) commit(s).
|
|
854
|
+
Thin wrapper around `_commit_batched_actions` for backward compat.
|
|
815
855
|
"""
|
|
816
856
|
if not paths_to_delete:
|
|
817
857
|
return
|
|
858
|
+
actions = [{"action": "delete", "file_path": p} for p in paths_to_delete]
|
|
859
|
+
self._commit_batched_actions(
|
|
860
|
+
actions=actions,
|
|
861
|
+
branch=branch,
|
|
862
|
+
commit_msg_prefix=commit_msg_prefix,
|
|
863
|
+
)
|
|
864
|
+
|
|
865
|
+
def _commit_batched_actions(
|
|
866
|
+
self,
|
|
867
|
+
actions: list,
|
|
868
|
+
branch: str,
|
|
869
|
+
commit_msg_prefix: str,
|
|
870
|
+
batch_size: int = 50,
|
|
871
|
+
):
|
|
872
|
+
"""
|
|
873
|
+
Generic batcher for the GitLab Commits API. Splits `actions` into chunks
|
|
874
|
+
of `batch_size` and POSTs each as a single commit. Each action is a dict
|
|
875
|
+
like {"action": "create"|"update"|"delete", "file_path": "...", "content": "..."}.
|
|
876
|
+
|
|
877
|
+
On 400 errors (typically "file already exists" or "doesn't exist"), retries the
|
|
878
|
+
batch once with the action flipped between create/update to handle drift between
|
|
879
|
+
the cached tree and reality.
|
|
880
|
+
"""
|
|
881
|
+
if not actions:
|
|
882
|
+
return
|
|
818
883
|
|
|
819
884
|
proj = self.project_path.replace('/', '%2F')
|
|
820
|
-
|
|
821
|
-
total = len(paths_to_delete)
|
|
822
|
-
num_batches = (total + BATCH_SIZE - 1) // BATCH_SIZE
|
|
885
|
+
url = f"{self.gitlab_base}/projects/{proj}/repository/commits"
|
|
823
886
|
|
|
887
|
+
total = len(actions)
|
|
888
|
+
num_batches = (total + batch_size - 1) // batch_size
|
|
824
889
|
for batch_idx in range(num_batches):
|
|
825
|
-
|
|
826
|
-
end = min(start + BATCH_SIZE, total)
|
|
827
|
-
batch_paths = paths_to_delete[start:end]
|
|
828
|
-
|
|
829
|
-
actions = []
|
|
830
|
-
for fpath in batch_paths:
|
|
831
|
-
actions.append({
|
|
832
|
-
"action": "delete",
|
|
833
|
-
"file_path": fpath
|
|
834
|
-
})
|
|
835
|
-
|
|
836
|
-
commit_message = f"{commit_msg_prefix} (batch {batch_idx+1} of {num_batches})"
|
|
890
|
+
chunk = actions[batch_idx * batch_size : (batch_idx + 1) * batch_size]
|
|
837
891
|
payload = {
|
|
838
|
-
"branch":
|
|
839
|
-
"commit_message":
|
|
840
|
-
"actions":
|
|
892
|
+
"branch": branch,
|
|
893
|
+
"commit_message": f"{commit_msg_prefix} (batch {batch_idx + 1} of {num_batches})",
|
|
894
|
+
"actions": chunk,
|
|
841
895
|
}
|
|
896
|
+
resp = requests.post(url, headers=self.headers, json=payload, timeout=60)
|
|
897
|
+
if resp.status_code in (200, 201):
|
|
898
|
+
print(f"Committed batch {batch_idx + 1}/{num_batches} ({len(chunk)} files) on '{branch}'")
|
|
899
|
+
continue
|
|
842
900
|
|
|
843
|
-
|
|
844
|
-
resp
|
|
845
|
-
|
|
901
|
+
# Retry create<->update flip on 400 errors
|
|
902
|
+
if resp.status_code == 400:
|
|
903
|
+
flipped = []
|
|
904
|
+
for a in chunk:
|
|
905
|
+
if a.get("action") == "update":
|
|
906
|
+
flipped.append({**a, "action": "create"})
|
|
907
|
+
elif a.get("action") == "create":
|
|
908
|
+
flipped.append({**a, "action": "update"})
|
|
909
|
+
else:
|
|
910
|
+
flipped.append(a)
|
|
911
|
+
payload["actions"] = flipped
|
|
912
|
+
resp2 = requests.post(url, headers=self.headers, json=payload, timeout=60)
|
|
913
|
+
if resp2.status_code in (200, 201):
|
|
914
|
+
print(f"Committed batch {batch_idx + 1}/{num_batches} ({len(chunk)} files) on '{branch}' [flipped]")
|
|
915
|
+
continue
|
|
846
916
|
raise RuntimeError(
|
|
847
|
-
f"Failed
|
|
848
|
-
f"(status {
|
|
917
|
+
f"Failed batch {batch_idx + 1}/{num_batches} on '{branch}' even after create/update flip "
|
|
918
|
+
f"(status {resp2.status_code}): {resp2.text}"
|
|
849
919
|
)
|
|
920
|
+
raise RuntimeError(
|
|
921
|
+
f"Failed batch {batch_idx + 1}/{num_batches} on '{branch}' "
|
|
922
|
+
f"(status {resp.status_code}): {resp.text}"
|
|
923
|
+
)
|
|
924
|
+
|
|
925
|
+
def _list_all_paths(self, branch: str) -> list:
|
|
926
|
+
"""
|
|
927
|
+
Return every blob path in the repository on `branch`. Used by `push_to_git`
|
|
928
|
+
to choose between create and update actions. Empty list if branch missing.
|
|
929
|
+
"""
|
|
930
|
+
proj = self.project_path.replace('/', '%2F')
|
|
931
|
+
page = 1
|
|
932
|
+
per_page = 100
|
|
933
|
+
all_paths = []
|
|
934
|
+
while True:
|
|
935
|
+
resp = requests.get(
|
|
936
|
+
f"{self.gitlab_base}/projects/{proj}/repository/tree",
|
|
937
|
+
headers={'PRIVATE-TOKEN': self.gitlab_token},
|
|
938
|
+
params={'ref': branch, 'recursive': True, 'per_page': per_page, 'page': page},
|
|
939
|
+
timeout=30,
|
|
940
|
+
)
|
|
941
|
+
if resp.status_code == 404:
|
|
942
|
+
return all_paths
|
|
943
|
+
resp.raise_for_status()
|
|
944
|
+
items = resp.json()
|
|
945
|
+
if not items:
|
|
946
|
+
break
|
|
947
|
+
for it in items:
|
|
948
|
+
if it.get('type') == 'blob':
|
|
949
|
+
all_paths.append(it['path'])
|
|
950
|
+
if len(items) < per_page:
|
|
951
|
+
break
|
|
952
|
+
page += 1
|
|
953
|
+
return all_paths
|
|
850
954
|
|
|
851
955
|
def list_all_blobs(self, subpath: str) -> list[str]:
|
|
852
956
|
"""
|
|
@@ -1000,10 +1104,23 @@ class GitLabManager:
|
|
|
1000
1104
|
print(f"✅ Hotfix branch '{slug}' ready; only pipelines: {sorted(allowed)}")
|
|
1001
1105
|
|
|
1002
1106
|
|
|
1003
|
-
def create_merge_request(
|
|
1107
|
+
def create_merge_request(
|
|
1108
|
+
self,
|
|
1109
|
+
title: str,
|
|
1110
|
+
description: str,
|
|
1111
|
+
target_branch: str = None,
|
|
1112
|
+
assignee_ids: list = None,
|
|
1113
|
+
squash: bool = True,
|
|
1114
|
+
):
|
|
1004
1115
|
"""
|
|
1005
1116
|
Create a GitLab merge request from the current branch into target_branch.
|
|
1006
|
-
|
|
1117
|
+
|
|
1118
|
+
- target_branch: if omitted, auto-determined from the source branch prefix.
|
|
1119
|
+
- squash: when True (default), the MR is configured to squash commits on
|
|
1120
|
+
merge. AIC pushes generate hundreds of small "Sync ..." commits per
|
|
1121
|
+
batch; squashing collapses them into one tidy commit on the target
|
|
1122
|
+
branch and avoids long "preparing" stalls in GitLab's merge-base
|
|
1123
|
+
computation. Set to False to preserve full commit history.
|
|
1007
1124
|
"""
|
|
1008
1125
|
original_branch = self._branch
|
|
1009
1126
|
# Auto-determine target branch if not provided
|
|
@@ -1024,14 +1141,15 @@ class GitLabManager:
|
|
|
1024
1141
|
'source_branch': self._branch,
|
|
1025
1142
|
'target_branch': target_branch,
|
|
1026
1143
|
'title': title,
|
|
1027
|
-
'description': description
|
|
1144
|
+
'description': description,
|
|
1145
|
+
'squash': squash,
|
|
1028
1146
|
}
|
|
1029
1147
|
if assignee_ids:
|
|
1030
1148
|
payload['assignee_ids'] = assignee_ids
|
|
1031
1149
|
response = requests.post(url, headers=self.headers, json=payload)
|
|
1032
1150
|
response.raise_for_status()
|
|
1033
1151
|
mr = response.json()
|
|
1034
|
-
print(f"✅ Created MR !{mr['iid']} from {self._branch} → {target_branch}")
|
|
1152
|
+
print(f"✅ Created MR !{mr['iid']} from {self._branch} → {target_branch} (squash={squash})")
|
|
1035
1153
|
self._set_branch(original_branch)
|
|
1036
1154
|
print(f'Checked out {original_branch}')
|
|
1037
1155
|
# return mr
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|