aic-utils 2.0.4__tar.gz → 2.0.5__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aic_utils
3
- Version: 2.0.4
3
+ Version: 2.0.5
4
4
  Summary: AIC API wrapper and GitLab integration framework for pipeline management
5
5
  Home-page: https://github.com/dylandoyle11/aic_utils
6
6
  Author: Dylan D
@@ -8,7 +8,7 @@ from .gitlab_init import GitLabRepositoryInitializer
8
8
  from .dataset_converter import DatasetConverter
9
9
  from .slack_logger import SlackLogger
10
10
 
11
- __version__ = '2.0.4'
11
+ __version__ = '2.0.5'
12
12
  __author__ = 'Dylan D'
13
13
 
14
14
  __all__ = [
@@ -555,12 +555,22 @@ class GitLabManager:
555
555
  commit_msg_prefix=f"Sync code for pipeline '{pipeline_name}'",
556
556
  )
557
557
 
558
- def push_to_git(self):
558
+ def push_to_git(self, prune: bool = False):
559
559
  """
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).
560
+ Push pipeline JSON and code to GitLab using batched commits API (≤50
561
+ file writes per commit) with content-hash change detection so unchanged
562
+ files produce no commit.
563
+
564
+ Args:
565
+ prune: when True, also delete `config/<name>.json` and `code/<name>/...`
566
+ for any pipeline not in `self.aic.pipeline_configs`. **Refuses
567
+ to run unless the AIC instance was loaded with the FULL workspace**
568
+ (`pipelines=['*']` or equivalent), to avoid deleting files for
569
+ pipelines that just happened to not be loaded into this session.
570
+
571
+ Change detection: respects `self.use_hash_comparison` (constructor flag,
572
+ default True). Compares git blob SHAs from a single tree-list call vs
573
+ locally-computed git blob SHAs of new content. No per-file fetches.
564
574
  """
565
575
  if self._branch == self.default_branch:
566
576
  force_push = input('⚠️ WARNING: You are attempting to overwrite the Production branch with existing AIC code. Proceed? (y/n)')
@@ -577,11 +587,22 @@ class GitLabManager:
577
587
  f"Allowed hotfix prefixes: {self._hotfix_prefixes}\n"
578
588
  )
579
589
 
590
+ # Safety gate for prune BEFORE we do any work
591
+ if prune:
592
+ loaded = len(self.aic.pipeline_configs)
593
+ total_in_ws = len(self.aic.pipelines)
594
+ if loaded < total_in_ws:
595
+ raise RuntimeError(
596
+ f"❌ prune=True requires the FULL workspace to be loaded "
597
+ f"(pipelines=['*'] in your AIC(...) call). "
598
+ f"Currently {loaded}/{total_in_ws} pipelines loaded; pruning "
599
+ f"now would delete files for the {total_in_ws - loaded} unloaded pipelines."
600
+ )
601
+
580
602
  self.ensure_branch_exists(branch_name=self._branch, ref=self._branch)
581
603
 
582
604
  # Build the full list of (file_path, content) pairs for this push.
583
605
  all_pairs = []
584
- results = []
585
606
  per_pipeline_pairs = {}
586
607
  for cfg in self.aic.pipeline_configs:
587
608
  name = cfg['name']
@@ -592,49 +613,101 @@ class GitLabManager:
592
613
  per_pipeline_pairs[name] = pairs
593
614
  all_pairs.extend(pairs)
594
615
 
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
599
-
600
- # Pre-fetch existing files on branch so we can choose create vs update.
616
+ # Pre-fetch existing tree (path → blob SHA) for change detection + create/update decisions
601
617
  try:
602
- existing = set(self._list_all_paths(self._branch))
618
+ existing_shas = self._list_blob_shas(self._branch)
603
619
  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
620
+ print(f"⚠️ Could not list existing tree on '{self._branch}' ({e}); proceeding without change detection.")
621
+ existing_shas = None
606
622
 
607
623
  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)
624
+ per_pipeline_status = {name: 'Skipped' for name in per_pipeline_pairs}
625
+ per_pipeline_changed_files = {name: 0 for name in per_pipeline_pairs}
626
+ skipped_unchanged = 0
627
+ for cfg in self.aic.pipeline_configs:
628
+ name = cfg['name']
629
+ for path, content in per_pipeline_pairs[name]:
630
+ if existing_shas is not None:
631
+ old_sha = existing_shas.get(path)
632
+ if self.use_hash_comparison and old_sha is not None:
633
+ new_sha = self._git_blob_sha(content)
634
+ if old_sha == new_sha:
635
+ skipped_unchanged += 1
636
+ continue
637
+ action_type = "update" if old_sha is not None else "create"
638
+ else:
639
+ action_type = "update" # _commit_batched_actions auto-flips on 400
640
+ actions.append({"action": action_type, "file_path": path, "content": content})
641
+ per_pipeline_status[name] = 'Success'
642
+ per_pipeline_changed_files[name] += 1
643
+
644
+ # Compute prune deletions if requested
645
+ prune_deletes = []
646
+ if prune:
647
+ allowed = {cfg['name'] for cfg in self.aic.pipeline_configs}
648
+ paths_for_check = existing_shas.keys() if existing_shas is not None else self._list_all_paths(self._branch)
649
+ for path in paths_for_check:
650
+ if path.startswith('config/') and path.endswith('.json'):
651
+ pname = path[len('config/'):-len('.json')]
652
+ if pname not in allowed:
653
+ prune_deletes.append(path)
654
+ elif path.startswith('code/'):
655
+ parts = path[len('code/'):].split('/', 1)
656
+ if parts and parts[0] not in allowed:
657
+ prune_deletes.append(path)
658
+
659
+ n_changed = len(actions)
623
660
  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:
661
+
662
+ if skipped_unchanged:
663
+ print(f"Change detection: {skipped_unchanged} unchanged file(s) skipped (hash match).")
664
+
665
+ if n_changed == 0 and not prune_deletes:
666
+ print(f"✓ No changes to push to '{self._branch}'.")
667
+ results = [(name, 'Skipped', 'No change') for name in per_pipeline_pairs]
668
+ subj, body = self._format_push_summary(self._branch, results)
669
+ self._send_email(subj, body, testing=False)
670
+ return
671
+
672
+ if n_changed > 0:
673
+ msg_prefix = f"Sync {n_pipelines} pipeline(s) ({n_changed} changed file(s)) from AIC workspace '{self.aic.workspace}'"
674
+ print(f"Pushing {n_changed} changed file(s) across {n_pipelines} pipeline(s) to '{self._branch}' in batches of 50...")
675
+ try:
676
+ self._commit_batched_actions(
677
+ actions=actions,
678
+ branch=self._branch,
679
+ commit_msg_prefix=msg_prefix,
680
+ )
681
+ except Exception as e:
682
+ print(f"❌ Batched push failed: {e}")
683
+ for name in per_pipeline_pairs:
684
+ per_pipeline_status[name] = 'Failure'
685
+ results = [(name, 'Failure', str(e)[:160]) for name in per_pipeline_pairs]
686
+ subj, body = self._format_push_summary(self._branch, results)
687
+ self._send_email(subj, body, testing=False)
688
+ return
689
+
690
+ if prune_deletes:
691
+ print(f"Prune: deleting {len(prune_deletes)} obsolete file(s) for pipelines not in current workspace state...")
627
692
  self._commit_batched_actions(
628
- actions=actions,
693
+ actions=[{"action":"delete","file_path":p} for p in prune_deletes],
629
694
  branch=self._branch,
630
- commit_msg_prefix=msg_prefix,
695
+ commit_msg_prefix=f"Prune {len(prune_deletes)} obsolete file(s) from workspace '{self.aic.workspace}'",
631
696
  )
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]))
697
+
698
+ # Build per-pipeline results for email
699
+ results = []
700
+ for name in per_pipeline_pairs:
701
+ st = per_pipeline_status[name]
702
+ if st == 'Success':
703
+ msg = f"{per_pipeline_changed_files[name]} changed file(s)"
704
+ elif st == 'Skipped':
705
+ msg = 'No change'
706
+ else:
707
+ msg = 'Failed'
708
+ results.append((name, st, msg))
709
+ if prune_deletes:
710
+ results.append(('(prune)', 'Success', f"{len(prune_deletes)} file(s) deleted"))
638
711
 
639
712
  subj, body = self._format_push_summary(self._branch, results)
640
713
  self._send_email(subj, body, testing=False)
@@ -922,15 +995,17 @@ class GitLabManager:
922
995
  f"(status {resp.status_code}): {resp.text}"
923
996
  )
924
997
 
925
- def _list_all_paths(self, branch: str) -> list:
998
+ def _list_blob_shas(self, branch: str) -> dict:
926
999
  """
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.
1000
+ Return {path: blob_sha} for every blob on `branch`. The blob_sha is
1001
+ Git's content-addressed SHA-1 (matches `git hash-object`), enabling
1002
+ change detection by computing the same hash locally on candidate
1003
+ new content and comparing.
929
1004
  """
930
1005
  proj = self.project_path.replace('/', '%2F')
931
1006
  page = 1
932
1007
  per_page = 100
933
- all_paths = []
1008
+ out = {}
934
1009
  while True:
935
1010
  resp = requests.get(
936
1011
  f"{self.gitlab_base}/projects/{proj}/repository/tree",
@@ -939,18 +1014,32 @@ class GitLabManager:
939
1014
  timeout=30,
940
1015
  )
941
1016
  if resp.status_code == 404:
942
- return all_paths
1017
+ return out
943
1018
  resp.raise_for_status()
944
1019
  items = resp.json()
945
1020
  if not items:
946
1021
  break
947
1022
  for it in items:
948
1023
  if it.get('type') == 'blob':
949
- all_paths.append(it['path'])
1024
+ out[it['path']] = it.get('id')
950
1025
  if len(items) < per_page:
951
1026
  break
952
1027
  page += 1
953
- return all_paths
1028
+ return out
1029
+
1030
+ def _list_all_paths(self, branch: str) -> list:
1031
+ """Return every blob path on `branch`. Backed by `_list_blob_shas`."""
1032
+ return list(self._list_blob_shas(branch).keys())
1033
+
1034
+ @staticmethod
1035
+ def _git_blob_sha(content) -> str:
1036
+ """
1037
+ Compute Git's blob SHA-1 for a file content (matches `git hash-object`).
1038
+ Used by `push_to_git` to detect unchanged files without a per-file fetch.
1039
+ """
1040
+ data = content.encode('utf-8') if isinstance(content, str) else content
1041
+ header = f"blob {len(data)}\0".encode('utf-8')
1042
+ return hashlib.sha1(header + data).hexdigest()
954
1043
 
955
1044
  def list_all_blobs(self, subpath: str) -> list[str]:
956
1045
  """
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aic_utils
3
- Version: 2.0.4
3
+ Version: 2.0.5
4
4
  Summary: AIC API wrapper and GitLab integration framework for pipeline management
5
5
  Home-page: https://github.com/dylandoyle11/aic_utils
6
6
  Author: Dylan D
@@ -7,7 +7,7 @@ with open('README.md', 'r', encoding='utf-8') as fh:
7
7
 
8
8
  setup(
9
9
  name='aic_utils',
10
- version='2.0.4',
10
+ version='2.0.5',
11
11
  packages=find_packages(),
12
12
  install_requires=[
13
13
  'requests>=2.25.0',
File without changes
File without changes
File without changes