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