-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitfleet.py
More file actions
executable file
·1352 lines (1120 loc) · 44.9 KB
/
gitfleet.py
File metadata and controls
executable file
·1352 lines (1120 loc) · 44.9 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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import enum
import os
import sys
import shlex
import shutil
import subprocess
import re
import argparse
from argparse import RawTextHelpFormatter
import json
import logging
import concurrent.futures
from typing import Dict, Any, Optional, Tuple
import time
import urllib.request
import urllib.parse
import urllib.error
import zipfile
import tarfile
__version__ = 'v1.2.1'
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
logger = logging.getLogger("gitfleet")
class RevisionType(enum.Enum):
"""Git revision type enumeration"""
SHA1 = enum.auto()
TAGS = enum.auto()
HEADS = enum.auto()
UNKNOWN = enum.auto()
class GitError(Exception):
"""Exception for Git operations"""
pass
class ConfigError(Exception):
"""Exception for configuration issues"""
pass
class ReleaseError(Exception):
"""Exception for GitHub release operations"""
pass
class GitRunner:
"""Handles Git command execution and operations"""
# Constants
REVISION_PATTERN = (
r"(?:(?P<tags>refs/tags/)|(?P<heads>refs/heads/))(?P<refs_target>[\S]+)"
)
DEFAULT_CLONE_DEPTH = "1"
GIT_CONFIG_OPTIONS = "-c advice.detachedHead=false"
@staticmethod
def run_command(cmd: str, cwd: Optional[str] = None, dry_run: bool = False) -> str:
"""Execute a Git command
Args:
cmd: Command to execute
cwd: Working directory
dry_run: If True, only log the command without executing
Returns:
Command output as string
Raises:
GitError: If command execution fails
"""
if dry_run:
logger.info(f"[DRY RUN] Would execute: {cmd}")
return ""
logger.debug(f"Executing: {cmd}")
try:
start_time = time.time()
result = (
subprocess.check_output(shlex.split(cmd), cwd=cwd)
.decode("utf-8")
.rstrip()
)
duration = time.time() - start_time
logger.debug(f"Command completed in {duration:.2f}s")
return result
except subprocess.CalledProcessError as e:
raise GitError(f"Git command failed with code {e.returncode}: {cmd}")
@staticmethod
def detect_revision_type(revision: str) -> Tuple[RevisionType, Optional[str]]:
"""Detect the type of revision
Args:
revision: Git revision string
Returns:
Tuple of (RevisionType, reference target if applicable)
"""
revision_match = re.match(GitRunner.REVISION_PATTERN, revision)
if not revision_match:
return RevisionType.SHA1, None
refs_target = revision_match.groupdict().get("refs_target", "")
if revision_match.groupdict().get("tags") is not None:
return RevisionType.TAGS, refs_target
elif revision_match.groupdict().get("heads") is not None:
return RevisionType.HEADS, refs_target
else:
return RevisionType.UNKNOWN, refs_target
@staticmethod
def is_shallow_repository(path: str, dry_run: bool = False) -> bool:
"""Check if the repository is shallow cloned
Args:
path: Repository path
dry_run: If True, assume not shallow in dry run mode
Returns:
True if repository is shallow cloned
"""
if dry_run:
return False
try:
result = GitRunner.run_command(
"git rev-parse --is-shallow-repository", cwd=path
)
return result.lower() == "true"
except GitError:
return False
@staticmethod
def build_clone_options(
repository: Dict[str, Any],
force_shallow_clone: bool,
revision_type: RevisionType,
refs_target: Optional[str],
) -> str:
"""Build Git clone options
Args:
repository: Repository configuration
force_shallow_clone: Force shallow clone
revision_type: Type of revision
refs_target: Reference target (branch or tag name)
Returns:
String with Git clone options
"""
options = [GitRunner.GIT_CONFIG_OPTIONS]
# Determine if shallow clone should be used
can_shallow_clone = (
force_shallow_clone or repository.get("shallow-clone", False)
) and revision_type in (RevisionType.HEADS, RevisionType.TAGS)
if can_shallow_clone and refs_target:
options.extend(["--depth", GitRunner.DEFAULT_CLONE_DEPTH])
options.extend(["-b", refs_target, "--single-branch"])
if repository.get("clone-submodule", False):
options.append("--recurse-submodule")
if can_shallow_clone:
options.append("--shallow-submodule")
return " ".join(options)
class Repository:
"""Represents a Git repository with operations"""
def __init__(
self,
config: Dict[str, Any],
working_dir: str,
force_shallow_clone: bool = False,
dry_run: bool = False,
):
"""Initialize repository
Args:
config: Repository configuration
working_dir: Base directory for relative paths
force_shallow_clone: Force shallow clone
dry_run: If True, don't execute commands
"""
self.config = config
self.working_dir = working_dir
self.force_shallow_clone = force_shallow_clone
self.dry_run = dry_run
self.setup_paths()
self.revision_type, self.refs_target = GitRunner.detect_revision_type(
self.config["revision"]
)
def setup_paths(self):
"""Setup repository paths"""
self.source_url = self.config["src"]
repo_name = os.path.basename(self.source_url.rstrip("/"))
if repo_name.endswith(".git"):
repo_name = repo_name[:-4]
self.name = repo_name
# Resolve destination path
dest = self.config["dest"].rstrip("/")
if not os.path.isabs(dest):
self.dest_path = os.path.abspath(os.path.join(self.working_dir, dest))
else:
self.dest_path = dest
def exists(self) -> bool:
"""Check if repository directory exists
Returns:
True if repository exists
"""
return os.path.exists(self.dest_path) and os.path.isdir(self.dest_path)
def ensure_parent_directory(self):
"""Ensure parent directory exists"""
if not self.dry_run:
try:
os.makedirs(os.path.dirname(self.dest_path), exist_ok=True)
except OSError as e:
raise GitError(f"Failed to create directory for {self.name}: {e}")
def check_revision_match(self) -> bool:
"""Check if current revision matches the configured one
Returns:
True if revisions match
"""
if self.dry_run:
return False
try:
current_sha1 = GitRunner.run_command(
"git rev-parse HEAD", cwd=self.dest_path
)
if self.revision_type == RevisionType.SHA1:
return current_sha1.startswith(self.config["revision"])
elif self.revision_type == RevisionType.TAGS:
target_sha1 = GitRunner.run_command(
f"git rev-list -n 1 {self.config['revision']}", cwd=self.dest_path
)
return current_sha1 == target_sha1
elif self.revision_type == RevisionType.HEADS:
target_sha1 = GitRunner.run_command(
f"git ls-remote origin {self.config['revision']}",
cwd=self.dest_path,
).split()[0]
return current_sha1 == target_sha1
return False
except GitError:
return False
def clone(self):
"""Clone repository"""
clone_options = GitRunner.build_clone_options(
self.config, self.force_shallow_clone, self.revision_type, self.refs_target
)
cmd = f"git clone {clone_options} {self.source_url} {self.dest_path}"
logger.info(f"Cloning {self.name} into {self.dest_path}")
GitRunner.run_command(cmd, dry_run=self.dry_run)
# Initialize submodule if needed
if self.config.get("clone-submodule", False):
logger.info(f"Initializing submodule for {self.name}")
GitRunner.run_command(
"git submodule init", cwd=self.dest_path, dry_run=self.dry_run
)
GitRunner.run_command(
"git submodule update", cwd=self.dest_path, dry_run=self.dry_run
)
def update(self):
"""Update repository to specified revision"""
current_dir = os.getcwd()
try:
if not self.dry_run:
os.chdir(self.dest_path)
# Fetch updates
GitRunner.run_command("git fetch", cwd=self.dest_path, dry_run=self.dry_run)
# Check working directory status
is_dirty = False
if not self.dry_run:
is_dirty = bool(
GitRunner.run_command("git status -suno", cwd=self.dest_path)
)
if is_dirty:
logger.warning(f"{self.name}: Working directory is not clean")
# Update based on revision type
if self.revision_type == RevisionType.SHA1:
self._update_sha1(is_dirty)
elif self.revision_type == RevisionType.TAGS:
self._update_tag(is_dirty)
elif self.revision_type == RevisionType.HEADS:
self._update_branch(is_dirty)
else:
raise GitError(f"Invalid revision type for {self.name}")
# Update submodule if needed
if self.config.get("clone-submodule", False):
GitRunner.run_command(
"git submodule update --recursive",
cwd=self.dest_path,
dry_run=self.dry_run,
)
finally:
if not self.dry_run:
os.chdir(current_dir)
def _update_sha1(self, is_dirty: bool):
"""Update repository to specific SHA1 commit"""
needs_update = True
if not self.dry_run:
current_sha1 = GitRunner.run_command(
"git rev-parse HEAD", cwd=self.dest_path
)
if current_sha1.startswith(self.config["revision"]):
logger.info(
f"{self.name}: Already at revision {self.config['revision']}"
)
needs_update = False
if needs_update:
GitRunner.run_command(
f"git checkout {self.config['revision']}",
cwd=self.dest_path,
dry_run=self.dry_run,
)
logger.info(f"{self.name}: Checked out revision {self.config['revision']}")
def _update_tag(self, is_dirty: bool):
"""Update repository to specific tag"""
needs_update = True
if not self.dry_run:
current_sha1 = GitRunner.run_command(
"git rev-parse HEAD", cwd=self.dest_path
)
target_sha1 = GitRunner.run_command(
f"git rev-list -n 1 {self.config['revision']}", cwd=self.dest_path
)
if current_sha1 == target_sha1:
logger.info(f"{self.name}: Already at tag {self.config['revision']}")
needs_update = False
if needs_update:
target_sha1 = GitRunner.run_command(
f"git rev-list -n 1 {self.config['revision']}",
cwd=self.dest_path,
dry_run=self.dry_run,
)
GitRunner.run_command(
f"git checkout {target_sha1}", cwd=self.dest_path, dry_run=self.dry_run
)
logger.info(f"{self.name}: Checked out tag {self.config['revision']}")
def _update_branch(self, is_dirty: bool):
"""Update repository to latest branch commit"""
needs_update = True
branch = self.refs_target
if not self.dry_run:
current_sha1 = GitRunner.run_command(
"git rev-parse HEAD", cwd=self.dest_path
)
target_sha1 = GitRunner.run_command(
f"git ls-remote origin {self.config['revision']}", cwd=self.dest_path
).split()[0]
if current_sha1 == target_sha1:
logger.info(f"{self.name}: Already at latest commit of {branch}")
needs_update = False
if needs_update:
GitRunner.run_command(
f"git checkout {branch}", cwd=self.dest_path, dry_run=self.dry_run
)
# Pull only if working directory is clean
if not is_dirty:
GitRunner.run_command(
f"git pull origin {branch}",
cwd=self.dest_path,
dry_run=self.dry_run,
)
logger.info(f"{self.name}: Updated to latest commit of {branch}")
else:
logger.warning(
f"{self.name}: Skipping git pull - working directory is not clean"
)
def process_subfleet(self):
"""Process nested fleet file if specified"""
if not self.config.get("clone-subfleet", False):
return
# Look for fleet config files in the root of the repository
try:
subfleet_path = FleetManager.find_fleet_config_file(self.dest_path)
logger.info(f"Processing nested fleet file: {subfleet_path}")
fleet_manager = FleetManager(
self.dest_path, # Use the repository path as the base directory
self.force_shallow_clone,
dry_run=self.dry_run,
)
fleet_manager.process()
except ConfigError as e:
if self.dry_run:
logger.info(
f"[DRY RUN] Would process nested fleet file in {self.dest_path}"
)
else:
logger.warning(f"Failed to process nested fleet file: {e}")
except GitError as e:
logger.warning(f"Failed to process nested fleet file: {e}")
def get_current_sha1(self) -> str:
"""Get current commit SHA1
Returns:
Current commit SHA1
"""
if self.dry_run:
return "dry-run-sha1"
try:
return GitRunner.run_command("git rev-parse HEAD", cwd=self.dest_path)
except GitError as e:
logger.warning(f"Failed to get current SHA1 for {self.name}: {e}")
return ""
def perform_copy_operations(self):
"""Perform selective file/directory copy operations as specified in the 'copy' config."""
copy_list = self.config.get("copy")
if not copy_list:
return
for entry in copy_list:
repo_path = entry.get("repoPath")
dest_path = entry.get("dest")
if not repo_path or not dest_path:
logger.warning(f"copy entry missing required fields: {entry}")
continue
abs_repo_path = os.path.join(self.dest_path, repo_path)
# If dest_path is not absolute, resolve relative to working_dir
if not os.path.isabs(dest_path):
abs_dest_path = os.path.abspath(
os.path.join(self.working_dir, dest_path)
)
else:
abs_dest_path = dest_path
if self.dry_run:
logger.info(f"[DRY RUN] Would copy {abs_repo_path} to {abs_dest_path}")
continue
if not os.path.exists(abs_repo_path):
logger.warning(f"Source path does not exist: {abs_repo_path}")
continue
try:
if os.path.isdir(abs_repo_path):
if os.path.exists(abs_dest_path):
if os.path.isdir(abs_dest_path):
shutil.rmtree(abs_dest_path)
else:
os.remove(abs_dest_path)
shutil.copytree(abs_repo_path, abs_dest_path)
else:
os.makedirs(os.path.dirname(abs_dest_path), exist_ok=True)
shutil.copy2(abs_repo_path, abs_dest_path)
logger.info(f"Copied {abs_repo_path} to {abs_dest_path}")
except Exception as e:
logger.error(f"Failed to copy {abs_repo_path} to {abs_dest_path}: {e}")
def sync(self) -> bool:
"""Synchronize repository
Returns:
True if successful
"""
logger.info(f"Processing repository: {self.name} from {self.source_url}")
try:
self.ensure_parent_directory()
should_be_shallow = self.force_shallow_clone or self.config.get(
"shallow-clone", False
)
requires_clean_clone = False
# Check if repository exists and if state matches requirements
if self.exists():
current_is_shallow = GitRunner.is_shallow_repository(
self.dest_path, self.dry_run
)
revision_matches = self.check_revision_match()
if should_be_shallow != current_is_shallow or not revision_matches:
logger.info(
f"{self.name}: Repository state mismatch - performing clean clone"
)
if not self.dry_run:
shutil.rmtree(self.dest_path)
requires_clean_clone = True
else:
requires_clean_clone = True
# Clone or update repository
if requires_clean_clone:
self.clone()
else:
self.update()
# Process nested fleet if needed
self.process_subfleet()
# Perform selective copy if specified
self.perform_copy_operations()
return True
except GitError as e:
logger.error(f"Failed to sync repository {self.name}: {e}")
return False
class ReleaseAsset:
"""Represents a GitHub release asset with download operations"""
def __init__(
self,
config: Dict[str, Any],
working_dir: str,
dry_run: bool = False,
):
"""Initialize release asset
Args:
config: Asset configuration
working_dir: Base directory for relative paths
dry_run: If True, don't execute commands
"""
self.config = config
self.working_dir = working_dir
self.dry_run = dry_run
self.setup_paths()
def setup_paths(self):
"""Setup asset paths"""
self.name = self.config["name"]
# Resolve destination path (dest is required)
dest = self.config["dest"]
if not os.path.isabs(dest):
self.dest_path = os.path.abspath(os.path.join(self.working_dir, dest))
else:
self.dest_path = dest
self.file_path = os.path.join(self.dest_path, self.name)
def ensure_dest_directory(self):
"""Ensure destination directory exists"""
if not self.dry_run:
try:
os.makedirs(self.dest_path, exist_ok=True)
except OSError as e:
raise ReleaseError(f"Failed to create directory {self.dest_path}: {e}")
def download(self, download_url: str) -> bool:
"""Download asset from URL
Args:
download_url: URL to download from
Returns:
True if successful
"""
logger.info(f"Downloading {self.name} to {self.dest_path}")
if self.dry_run:
logger.info(f"[DRY RUN] Would download {download_url} to {self.file_path}")
return True
try:
self.ensure_dest_directory()
# Download with progress
with urllib.request.urlopen(download_url) as response:
total_size = int(response.headers.get("Content-Length", 0))
with open(self.file_path, "wb") as f:
downloaded = 0
chunk_size = 8192
while True:
chunk = response.read(chunk_size)
if not chunk:
break
f.write(chunk)
downloaded += len(chunk)
if total_size > 0:
progress = (downloaded / total_size) * 100
logger.debug(
f"Downloaded {downloaded}/{total_size} bytes ({progress:.1f}%)"
)
logger.info(f"Successfully downloaded {self.name}")
return True
except Exception as e:
logger.error(f"Failed to download {self.name}: {e}")
return False
def extract(self) -> bool:
"""Extract archive if specified
Returns:
True if successful or no extraction needed
"""
if not self.config.get("extract", True):
return True
if self.dry_run:
logger.info(f"[DRY RUN] Would extract {self.file_path}")
return True
if not os.path.exists(self.file_path):
logger.error(f"Cannot extract - file not found: {self.file_path}")
return False
try:
if self.name.endswith(".zip"):
logger.info(f"Extracting ZIP: {self.name}")
with zipfile.ZipFile(self.file_path, "r") as zip_file:
zip_file.extractall(self.dest_path)
elif self.name.endswith((".tar.gz", ".tgz")):
logger.info(f"Extracting TAR.GZ: {self.name}")
with tarfile.open(self.file_path, "r:gz") as tar_file:
tar_file.extractall(self.dest_path)
elif self.name.endswith(".tar"):
logger.info(f"Extracting TAR: {self.name}")
with tarfile.open(self.file_path, "r") as tar_file:
tar_file.extractall(self.dest_path)
else:
logger.info(f"No extraction needed for {self.name}")
return True
logger.info(f"Successfully extracted {self.name}")
return True
except (zipfile.BadZipFile, tarfile.TarError, IOError) as e:
logger.error(f"Failed to extract {self.name}: {e}")
return False
class Release:
"""Represents a GitHub release with asset operations"""
def __init__(
self,
config: Dict[str, Any],
working_dir: str,
dry_run: bool = False,
):
"""Initialize release
Args:
config: Release configuration
working_dir: Base directory for relative paths
dry_run: If True, don't execute commands
"""
self.config = config
self.working_dir = working_dir
self.dry_run = dry_run
self.setup_release_info()
self.setup_assets()
def setup_release_info(self):
"""Setup release information"""
self.url = self.config["url"]
self.tag = self.config["tag"]
# Parse GitHub URL to get owner and repo
if self.url.startswith("https://github.com/"):
parts = self.url.replace("https://github.com/", "").strip("/").split("/")
if len(parts) >= 2:
self.owner = parts[0]
self.repo = parts[1]
self.name = f"{self.owner}/{self.repo}"
else:
raise ReleaseError(f"Invalid GitHub URL format: {self.url}")
else:
raise ReleaseError(f"Only GitHub URLs are supported: {self.url}")
def setup_assets(self):
"""Setup asset objects"""
self.assets = []
for asset_config in self.config.get("assets", []):
self.assets.append(
ReleaseAsset(asset_config, self.working_dir, self.dry_run)
)
def fetch_release_info(self) -> Dict[str, Any]:
"""Fetch release information from GitHub API
Returns:
Release information dictionary
Raises:
ReleaseError: If API request fails
"""
api_url = f"https://api.github.com/repos/{self.owner}/{self.repo}/releases/tags/{self.tag}"
if self.dry_run:
logger.info(f"[DRY RUN] Would fetch release info from {api_url}")
return {"assets": []}
try:
logger.debug(f"Fetching release info from {api_url}")
with urllib.request.urlopen(api_url) as response:
data = json.loads(response.read().decode("utf-8"))
return data
except (urllib.error.URLError, json.JSONDecodeError) as e:
raise ReleaseError(
f"Failed to fetch release info for {self.name} tag {self.tag}: {e}"
)
def find_asset_download_url(
self, asset_name: str, release_data: Dict[str, Any]
) -> Optional[str]:
"""Find download URL for asset
Args:
asset_name: Name of asset to find
release_data: Release data from GitHub API
Returns:
Download URL if found, None otherwise
"""
for asset in release_data.get("assets", []):
if asset.get("name") == asset_name:
return asset.get("browser_download_url")
return None
def sync(self) -> bool:
"""Synchronize release assets
Returns:
True if successful
"""
logger.info(f"Processing release: {self.name} tag {self.tag}")
try:
# Fetch release information
release_data = self.fetch_release_info()
# Process each asset
success_count = 0
for asset in self.assets:
download_url = self.find_asset_download_url(asset.name, release_data)
if not download_url:
logger.error(f"Asset not found in release: {asset.name}")
continue
# Download and extract asset
if asset.download(download_url) and asset.extract():
success_count += 1
else:
logger.error(f"Failed to process asset: {asset.name}")
total_assets = len(self.assets)
logger.info(
f"Processed {success_count}/{total_assets} assets for {self.name}"
)
return success_count == total_assets
except ReleaseError as e:
logger.error(f"Failed to sync release {self.name}: {e}")
return False
class ConfigLoader:
"""Handles loading and validating configuration files"""
@staticmethod
def load_config(file_path: str) -> Dict[str, Any]:
"""Load configuration from file
Args:
file_path: Path to configuration file
Returns:
Dictionary with parsed configuration
Raises:
ConfigError: If configuration is invalid
"""
if not os.path.exists(file_path):
raise ConfigError(f"Configuration file not found: {file_path}")
file_ext = os.path.splitext(file_path)[1].lower()
try:
with open(file_path, "r") as f:
if file_ext == ".json":
config = json.load(f)
elif file_ext in (".yaml", ".yml"):
try:
import yaml
except ImportError:
raise ConfigError(
"YAML support requires the 'pyyaml' package. "
"Install it with: pip install pyyaml"
)
config = yaml.safe_load(f)
else:
raise ConfigError(f"Unsupported configuration format: {file_ext}")
except json.JSONDecodeError as e:
raise ConfigError(f"Failed to parse JSON configuration file: {e}")
except ImportError:
# Re-raise ImportError from yaml import
raise
except IOError as e:
raise ConfigError(f"Failed to read configuration file: {e}")
except yaml.YAMLError as e:
raise ConfigError(f"Failed to parse YAML configuration file: {e}")
# Validate configuration
ConfigLoader.validate_config(config)
return config
@staticmethod
def validate_config(config: Dict[str, Any]):
"""Validate configuration structure
Args:
config: Configuration dictionary
Raises:
ConfigError: If configuration is invalid
"""
if not isinstance(config, dict):
raise ConfigError("Configuration must be a dictionary")
# Validate repositories section
if "repositories" in config:
if not isinstance(config["repositories"], list):
raise ConfigError("'repositories' must be a list")
for idx, repo in enumerate(config["repositories"]):
if not isinstance(repo, dict):
raise ConfigError(f"Repository #{idx} must be a dictionary")
# Check required fields
for field in ["src", "dest", "revision"]:
if field not in repo:
raise ConfigError(
f"Repository #{idx} missing required field: {field}"
)
# Validate that clone-submodule is boolean if present
if "clone-submodule" in repo and not isinstance(
repo["clone-submodule"], bool
):
raise ConfigError(
f"Repository #{idx}: 'clone-submodule' must be a boolean value"
)
if "clone-subfleet" in repo and not isinstance(
repo["clone-subfleet"], bool
):
raise ConfigError(
f"Repository #{idx}: 'clone-subfleet' must be a boolean value"
)
if "shallow-clone" in repo and not isinstance(
repo["shallow-clone"], bool
):
raise ConfigError(
f"Repository #{idx}: 'shallow-clone' must be a boolean value"
)
# Validate that copy is a list if present
if (
"copy" in repo
and repo["copy"] is not None
and not isinstance(repo["copy"], list)
):
raise ConfigError(
f"Repository #{idx}: 'copy' must be a list if present"
)
# Validate releases section
if "releases" in config:
if not isinstance(config["releases"], list):
raise ConfigError("'releases' must be a list")
for idx, release in enumerate(config["releases"]):
if not isinstance(release, dict):
raise ConfigError(f"Release #{idx} must be a dictionary")
# Check required fields
for field in ["url", "tag", "assets"]:
if field not in release:
raise ConfigError(
f"Release #{idx} missing required field: {field}"
)
# Validate assets
if not isinstance(release["assets"], list):
raise ConfigError(f"Release #{idx}: 'assets' must be a list")
for asset_idx, asset in enumerate(release["assets"]):
if not isinstance(asset, dict):
raise ConfigError(
f"Release #{idx} asset #{asset_idx} must be a dictionary"
)
# Check required fields for assets
for field in ["name", "dest"]:
if field not in asset:
raise ConfigError(
f"Release #{idx} asset #{asset_idx} missing required field: '{field}'"
)
# Ensure at least one of repositories or releases exists
if "repositories" not in config and "releases" not in config:
raise ConfigError(
"Configuration must contain 'repositories' or 'releases' section"
)
@staticmethod
def save_config(config: Dict[str, Any], file_path: str):
"""Save configuration to file
Args:
config: Configuration dictionary
file_path: Path to save configuration file
Raises:
ConfigError: If configuration cannot be saved
"""
file_ext = os.path.splitext(file_path)[1].lower()
try:
with open(file_path, "w") as f:
if file_ext == ".json":
json.dump(config, f, indent=4)
elif file_ext in (".yaml", ".yml"):
try:
import yaml
except ImportError:
raise ConfigError(
"YAML support requires the 'pyyaml' package. "
"Install it with: pip install pyyaml"
)
yaml.dump(config, f, default_flow_style=False)
else:
raise ConfigError(f"Unsupported configuration format: {file_ext}")
except IOError as e:
raise ConfigError(f"Failed to write configuration file: {e}")
class FleetManager:
"""Manages the entire fleet of repositories"""
FLEET_CONFIG_NAMES = ["gitfleet.yaml", "gitfleet.yml", "gitfleet.json"]
SUPPORTED_SCHEMA_VERSIONS = ["v1"]