-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathversionguard.py
More file actions
996 lines (833 loc) · 35.8 KB
/
versionguard.py
File metadata and controls
996 lines (833 loc) · 35.8 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
#!/usr/bin/env python3
"""
VersionGuard - Pre-Validate Version Compatibility Before Implementation
Pre-validates version compatibility across frontend/backend dependencies
before implementation to prevent hours wasted on version incompatibilities.
Problem Solved:
During IRIS's BCH Mobile development session, 2 hours were wasted on
Socket.IO v4/v5 incompatibility. The frontend used v4 client but the
backend had v5 server - they're not compatible. This tool catches such
issues BEFORE implementation begins.
Author: ATLAS (Team Brain)
For: Logan Smith / Metaphy LLC
Version: 1.0
Date: January 24, 2026
License: MIT
Requested by: IRIS (Tool Request #18)
"""
import json
import re
import logging
from dataclasses import dataclass, field
from typing import List, Dict, Optional, Any, Tuple, Set
from enum import Enum
from pathlib import Path
from collections import defaultdict
__version__ = "1.0.0"
__author__ = "ATLAS (Team Brain)"
class CompatibilityStatus(Enum):
"""Version compatibility status."""
COMPATIBLE = "compatible"
WARNING = "warning"
INCOMPATIBLE = "incompatible"
UNKNOWN = "unknown"
class Severity(Enum):
"""Issue severity."""
INFO = "info"
WARNING = "warning"
ERROR = "error"
CRITICAL = "critical"
@dataclass
class SemanticVersion:
"""
Represents a semantic version (major.minor.patch).
Supports comparison operations and version range checking.
"""
major: int
minor: int
patch: int
prerelease: str = ""
build: str = ""
raw: str = ""
@classmethod
def parse(cls, version_str: str) -> Optional['SemanticVersion']:
"""
Parse a version string into SemanticVersion.
Handles formats like:
- 1.0.0
- 1.0
- 1
- ^1.0.0, ~1.0.0 (range prefixes stripped)
- 1.0.0-alpha, 1.0.0-rc.1 (prerelease)
- 1.0.0+build (build metadata)
"""
if not version_str:
return None
raw = version_str
# Strip common prefixes
version_str = version_str.strip()
version_str = re.sub(r'^[=^~<>]*\s*', '', version_str)
version_str = re.sub(r'^v', '', version_str, flags=re.IGNORECASE)
# Extract build metadata
build = ""
if '+' in version_str:
version_str, build = version_str.split('+', 1)
# Extract prerelease
prerelease = ""
if '-' in version_str:
parts = version_str.split('-', 1)
version_str = parts[0]
prerelease = parts[1] if len(parts) > 1 else ""
# Parse version numbers
try:
parts = version_str.split('.')
major = int(parts[0]) if len(parts) > 0 else 0
minor = int(parts[1]) if len(parts) > 1 else 0
patch = int(parts[2]) if len(parts) > 2 else 0
return cls(
major=major,
minor=minor,
patch=patch,
prerelease=prerelease,
build=build,
raw=raw
)
except (ValueError, IndexError):
return None
def __str__(self) -> str:
"""String representation."""
result = f"{self.major}.{self.minor}.{self.patch}"
if self.prerelease:
result += f"-{self.prerelease}"
if self.build:
result += f"+{self.build}"
return result
def __lt__(self, other: 'SemanticVersion') -> bool:
"""Less than comparison."""
return (self.major, self.minor, self.patch) < (other.major, other.minor, other.patch)
def __le__(self, other: 'SemanticVersion') -> bool:
"""Less than or equal comparison."""
return (self.major, self.minor, self.patch) <= (other.major, other.minor, other.patch)
def __gt__(self, other: 'SemanticVersion') -> bool:
"""Greater than comparison."""
return (self.major, self.minor, self.patch) > (other.major, other.minor, other.patch)
def __ge__(self, other: 'SemanticVersion') -> bool:
"""Greater than or equal comparison."""
return (self.major, self.minor, self.patch) >= (other.major, other.minor, other.patch)
def __eq__(self, other: object) -> bool:
"""Equality comparison."""
if not isinstance(other, SemanticVersion):
return False
return (self.major, self.minor, self.patch) == (other.major, other.minor, other.patch)
def is_major_compatible(self, other: 'SemanticVersion') -> bool:
"""Check if same major version."""
return self.major == other.major
def is_minor_compatible(self, other: 'SemanticVersion') -> bool:
"""Check if same major and minor version."""
return self.major == other.major and self.minor == other.minor
@dataclass
class Dependency:
"""Represents a package dependency."""
name: str
version: Optional[SemanticVersion]
version_spec: str # Original version specification
source: str # "frontend", "backend", "shared"
file_path: str
def to_dict(self) -> Dict:
"""Convert to dictionary."""
return {
"name": self.name,
"version": str(self.version) if self.version else None,
"version_spec": self.version_spec,
"source": self.source,
"file_path": self.file_path
}
@dataclass
class CompatibilityIssue:
"""Represents a compatibility issue."""
package: str
frontend_version: Optional[SemanticVersion]
backend_version: Optional[SemanticVersion]
status: CompatibilityStatus
severity: Severity
message: str
recommendation: str
details: List[str] = field(default_factory=list)
def to_dict(self) -> Dict:
"""Convert to dictionary."""
return {
"package": self.package,
"frontend_version": str(self.frontend_version) if self.frontend_version else None,
"backend_version": str(self.backend_version) if self.backend_version else None,
"status": self.status.value,
"severity": self.severity.value,
"message": self.message,
"recommendation": self.recommendation,
"details": self.details
}
@dataclass
class CompatibilityReport:
"""Full compatibility analysis report."""
status: CompatibilityStatus
frontend_deps: List[Dependency]
backend_deps: List[Dependency]
issues: List[CompatibilityIssue]
recommendations: List[str]
summary: str
def to_dict(self) -> Dict:
"""Convert to dictionary."""
return {
"status": self.status.value,
"frontend_dep_count": len(self.frontend_deps),
"backend_dep_count": len(self.backend_deps),
"issue_count": len(self.issues),
"issues": [i.to_dict() for i in self.issues],
"recommendations": self.recommendations,
"summary": self.summary
}
class CompatibilityMatrix:
"""
Built-in compatibility rules for common packages.
Contains known compatibility issues between package versions.
"""
# Known compatibility rules
# Format: package_name -> list of rules
RULES = {
# Socket.IO - major version must match between client and server
"socket.io": {
"type": "client_server",
"client_packages": ["socket.io-client"],
"server_packages": ["socket.io", "python-socketio"],
"rule": "major_must_match",
"message": "Socket.IO client v{client} requires server v{server} with matching major version",
"recommendation": "Update both client and server to the same major version"
},
"socket.io-client": {
"type": "client_server",
"related_to": "socket.io",
"rule": "major_must_match",
"message": "Socket.IO client v{client} is incompatible with server v{server}",
"recommendation": "Use socket.io-client v4 with socket.io v4, or v5 with v5"
},
"python-socketio": {
"type": "client_server",
"related_to": "socket.io-client",
"rule": "major_must_match",
"mapping": {
"5": "4-5", # python-socketio 5.x works with socket.io 4.x-5.x
"4": "3-4" # python-socketio 4.x works with socket.io 3.x-4.x
},
"message": "python-socketio v{backend} compatibility with socket.io-client v{frontend}",
"recommendation": "Check python-socketio documentation for client compatibility"
},
# React / ReactDOM - versions must match
"react": {
"type": "version_match",
"must_match": ["react-dom"],
"rule": "exact_match",
"message": "React v{v1} must match React-DOM v{v2}",
"recommendation": "Install matching versions: npm install react@{target} react-dom@{target}"
},
"react-dom": {
"type": "version_match",
"must_match": ["react"],
"rule": "exact_match",
"message": "React-DOM v{v1} must match React v{v2}",
"recommendation": "Install matching versions: npm install react@{target} react-dom@{target}"
},
# TypeScript / @types compatibility
"typescript": {
"type": "minimum_version",
"notes": "TypeScript versions have varying @types compatibility",
"message": "TypeScript v{version} detected",
"recommendation": "Ensure @types packages are compatible with TypeScript version"
},
# Node.js version requirements
"node": {
"type": "runtime",
"message": "Node.js v{version} required",
"recommendation": "Check all packages support your Node.js version"
},
# Python version requirements
"python": {
"type": "runtime",
"message": "Python v{version} required",
"recommendation": "Check all packages support your Python version"
},
# Flask / Werkzeug compatibility
"flask": {
"type": "dependency_version",
"depends_on": {
"werkzeug": {
"2.0": ">=2.0",
"1.0": ">=0.15,<2.0"
}
},
"message": "Flask v{v1} requires Werkzeug v{v2}",
"recommendation": "Update Werkzeug to compatible version"
},
# FastAPI / Starlette compatibility
"fastapi": {
"type": "dependency_version",
"depends_on": {
"starlette": {
"0.100": ">=0.27.0",
"0.90": ">=0.25.0"
}
},
"message": "FastAPI v{v1} may have Starlette compatibility issues",
"recommendation": "Check FastAPI release notes for Starlette version requirements"
},
# Webpack version
"webpack": {
"type": "major_version",
"breaking_changes": {
"5": "Webpack 5 has different configuration than v4",
"4": "Webpack 4 uses different loaders than v5"
},
"message": "Webpack v{version} detected - verify loader compatibility",
"recommendation": "Check webpack-cli and loader versions match webpack major version"
},
# SQLAlchemy 1.x vs 2.x
"sqlalchemy": {
"type": "major_version",
"breaking_changes": {
"2": "SQLAlchemy 2.0 has significantly different API than 1.x",
"1": "SQLAlchemy 1.x API - consider migration to 2.0"
},
"message": "SQLAlchemy v{version} - check for API compatibility",
"recommendation": "If mixing 1.x and 2.x code, use sqlalchemy.future for forward compatibility"
},
# Pydantic 1.x vs 2.x
"pydantic": {
"type": "major_version",
"breaking_changes": {
"2": "Pydantic 2.0 has breaking changes from 1.x",
"1": "Pydantic 1.x - consider migration path to 2.0"
},
"message": "Pydantic v{version} - major API changes between versions",
"recommendation": "Use pydantic.v1 namespace for 1.x compatibility in 2.0"
}
}
@classmethod
def get_rule(cls, package_name: str) -> Optional[Dict]:
"""Get compatibility rule for a package."""
return cls.RULES.get(package_name.lower())
@classmethod
def get_related_packages(cls, package_name: str) -> List[str]:
"""Get packages related to this one for compatibility checking."""
rule = cls.get_rule(package_name)
if not rule:
return []
related = []
if rule.get("type") == "version_match":
related.extend(rule.get("must_match", []))
if rule.get("type") == "client_server":
related.extend(rule.get("client_packages", []))
related.extend(rule.get("server_packages", []))
if "related_to" in rule:
related.append(rule["related_to"])
return related
class DependencyParser:
"""Parses dependency files to extract versions."""
@staticmethod
def parse_package_json(file_path: Path) -> List[Dependency]:
"""Parse package.json for dependencies."""
deps = []
try:
with open(file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
except (json.JSONDecodeError, FileNotFoundError) as e:
logging.warning(f"Failed to parse {file_path}: {e}")
return deps
# Parse dependencies
for dep_type in ['dependencies', 'devDependencies', 'peerDependencies']:
if dep_type in data:
for name, version_spec in data[dep_type].items():
version = SemanticVersion.parse(version_spec)
deps.append(Dependency(
name=name,
version=version,
version_spec=version_spec,
source="frontend",
file_path=str(file_path)
))
return deps
@staticmethod
def parse_requirements_txt(file_path: Path) -> List[Dependency]:
"""Parse requirements.txt for dependencies."""
deps = []
try:
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
except FileNotFoundError:
logging.warning(f"File not found: {file_path}")
return deps
for line in lines:
line = line.strip()
# Skip comments and empty lines
if not line or line.startswith('#') or line.startswith('-'):
continue
# Parse package==version, package>=version, etc.
match = re.match(r'^([a-zA-Z0-9_-]+)\s*([<>=!~]+)?\s*([\d.a-zA-Z-]*)?', line)
if match:
name = match.group(1)
operator = match.group(2) or ""
version_str = match.group(3) or ""
version = SemanticVersion.parse(version_str) if version_str else None
deps.append(Dependency(
name=name,
version=version,
version_spec=f"{operator}{version_str}" if version_str else "",
source="backend",
file_path=str(file_path)
))
return deps
@staticmethod
def parse_pyproject_toml(file_path: Path) -> List[Dependency]:
"""Parse pyproject.toml for dependencies (simplified parser)."""
deps = []
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
except FileNotFoundError:
logging.warning(f"File not found: {file_path}")
return deps
# Simple parsing for dependencies section
in_dependencies = False
for line in content.split('\n'):
line = line.strip()
if line.startswith('[') and 'dependencies' in line.lower():
in_dependencies = True
continue
elif line.startswith('['):
in_dependencies = False
continue
if in_dependencies and '=' in line:
# Parse "package = version" or 'package = "version"'
match = re.match(r'^([a-zA-Z0-9_-]+)\s*=\s*["\']?([^"\']+)["\']?', line)
if match:
name = match.group(1)
version_spec = match.group(2).strip()
version = SemanticVersion.parse(version_spec)
deps.append(Dependency(
name=name,
version=version,
version_spec=version_spec,
source="backend",
file_path=str(file_path)
))
return deps
class VersionGuard:
"""
Main class for version compatibility validation.
Pre-validates version compatibility across frontend/backend dependencies
to prevent implementation issues.
"""
def __init__(self, project_root: Optional[Path] = None):
"""
Initialize VersionGuard.
Args:
project_root: Optional project root directory
"""
self.project_root = project_root or Path.cwd()
self.parser = DependencyParser()
self.matrix = CompatibilityMatrix()
self.frontend_deps: List[Dependency] = []
self.backend_deps: List[Dependency] = []
self.issues: List[CompatibilityIssue] = []
self.logger = logging.getLogger(__name__)
def scan_project(self, root: Optional[Path] = None) -> Tuple[List[Dependency], List[Dependency]]:
"""
Scan a project directory for dependency files.
Args:
root: Project root (defaults to current directory)
Returns:
Tuple of (frontend_deps, backend_deps)
"""
root = root or self.project_root
self.frontend_deps = []
self.backend_deps = []
# Scan for package.json files
for package_json in root.rglob('package.json'):
# Skip node_modules
if 'node_modules' in str(package_json):
continue
deps = self.parser.parse_package_json(package_json)
self.frontend_deps.extend(deps)
# Scan for requirements.txt files
for req_txt in root.rglob('requirements*.txt'):
deps = self.parser.parse_requirements_txt(req_txt)
self.backend_deps.extend(deps)
# Scan for pyproject.toml files
for pyproject in root.rglob('pyproject.toml'):
deps = self.parser.parse_pyproject_toml(pyproject)
self.backend_deps.extend(deps)
return self.frontend_deps, self.backend_deps
def check_compatibility(
self,
frontend_deps: Optional[List[Dependency]] = None,
backend_deps: Optional[List[Dependency]] = None
) -> List[CompatibilityIssue]:
"""
Check compatibility between frontend and backend dependencies.
Args:
frontend_deps: Frontend dependencies (or use scanned deps)
backend_deps: Backend dependencies (or use scanned deps)
Returns:
List of compatibility issues
"""
frontend_deps = frontend_deps or self.frontend_deps
backend_deps = backend_deps or self.backend_deps
self.issues = []
# Build lookup dictionaries
frontend_map = {d.name.lower(): d for d in frontend_deps}
backend_map = {d.name.lower(): d for d in backend_deps}
all_deps = {**frontend_map, **backend_map}
# Check each package against compatibility rules
checked = set()
for dep in frontend_deps + backend_deps:
pkg_name = dep.name.lower()
if pkg_name in checked:
continue
checked.add(pkg_name)
rule = self.matrix.get_rule(pkg_name)
if not rule:
continue
# Check based on rule type
if rule.get("type") == "client_server":
self._check_client_server_compatibility(
pkg_name, rule, frontend_map, backend_map
)
elif rule.get("type") == "version_match":
self._check_version_match(pkg_name, rule, all_deps)
elif rule.get("type") == "major_version":
self._check_major_version(pkg_name, rule, all_deps.get(pkg_name))
return self.issues
def _check_client_server_compatibility(
self,
pkg_name: str,
rule: Dict,
frontend_map: Dict,
backend_map: Dict
) -> None:
"""Check client/server version compatibility."""
# Get client packages (frontend)
client_pkgs = rule.get("client_packages", [])
server_pkgs = rule.get("server_packages", [])
# Also check the package itself
if pkg_name in frontend_map:
client_pkgs.append(pkg_name)
if pkg_name in backend_map:
server_pkgs.append(pkg_name)
# Find matching client and server
client_dep = None
server_dep = None
for client_name in client_pkgs:
if client_name.lower() in frontend_map:
client_dep = frontend_map[client_name.lower()]
break
for server_name in server_pkgs:
if server_name.lower() in backend_map:
server_dep = backend_map[server_name.lower()]
break
# Also check frontend for server packages (e.g., monorepo)
if server_name.lower() in frontend_map:
server_dep = frontend_map[server_name.lower()]
break
if client_dep and server_dep and client_dep.version and server_dep.version:
# Check major version match
if rule.get("rule") == "major_must_match":
if client_dep.version.major != server_dep.version.major:
msg = rule.get("message", "Version mismatch").format(
client=client_dep.version,
server=server_dep.version
)
self.issues.append(CompatibilityIssue(
package=pkg_name,
frontend_version=client_dep.version,
backend_version=server_dep.version,
status=CompatibilityStatus.INCOMPATIBLE,
severity=Severity.CRITICAL,
message=msg,
recommendation=rule.get("recommendation", "Update to matching versions"),
details=[
f"Client ({client_dep.name}): v{client_dep.version}",
f"Server ({server_dep.name}): v{server_dep.version}",
f"Rule: Major versions must match"
]
))
def _check_version_match(self, pkg_name: str, rule: Dict, all_deps: Dict) -> None:
"""Check that related packages have matching versions."""
must_match = rule.get("must_match", [])
pkg_dep = all_deps.get(pkg_name.lower())
if not pkg_dep or not pkg_dep.version:
return
for match_name in must_match:
match_dep = all_deps.get(match_name.lower())
if not match_dep or not match_dep.version:
continue
if pkg_dep.version != match_dep.version:
msg = rule.get("message", "Version mismatch").format(
v1=pkg_dep.version,
v2=match_dep.version
)
# Check if it's just minor mismatch (warning) or major (error)
if pkg_dep.version.major != match_dep.version.major:
severity = Severity.CRITICAL
status = CompatibilityStatus.INCOMPATIBLE
else:
severity = Severity.WARNING
status = CompatibilityStatus.WARNING
self.issues.append(CompatibilityIssue(
package=pkg_name,
frontend_version=pkg_dep.version,
backend_version=match_dep.version,
status=status,
severity=severity,
message=msg,
recommendation=rule.get("recommendation", "Install matching versions"),
details=[
f"{pkg_dep.name}: v{pkg_dep.version}",
f"{match_dep.name}: v{match_dep.version}"
]
))
def _check_major_version(self, pkg_name: str, rule: Dict, dep: Optional[Dependency]) -> None:
"""Check for major version warnings."""
if not dep or not dep.version:
return
breaking_changes = rule.get("breaking_changes", {})
major_str = str(dep.version.major)
if major_str in breaking_changes:
msg = rule.get("message", "Version note").format(version=dep.version)
self.issues.append(CompatibilityIssue(
package=pkg_name,
frontend_version=dep.version if dep.source == "frontend" else None,
backend_version=dep.version if dep.source == "backend" else None,
status=CompatibilityStatus.WARNING,
severity=Severity.WARNING,
message=msg,
recommendation=rule.get("recommendation", "Check documentation"),
details=[breaking_changes[major_str]]
))
def generate_report(self) -> CompatibilityReport:
"""Generate a full compatibility report."""
# Determine overall status
if any(i.status == CompatibilityStatus.INCOMPATIBLE for i in self.issues):
overall_status = CompatibilityStatus.INCOMPATIBLE
elif any(i.status == CompatibilityStatus.WARNING for i in self.issues):
overall_status = CompatibilityStatus.WARNING
elif self.frontend_deps or self.backend_deps:
overall_status = CompatibilityStatus.COMPATIBLE
else:
overall_status = CompatibilityStatus.UNKNOWN
# Generate recommendations
recommendations = []
for issue in self.issues:
if issue.recommendation and issue.recommendation not in recommendations:
recommendations.append(issue.recommendation)
# Generate summary
critical_count = sum(1 for i in self.issues if i.severity == Severity.CRITICAL)
warning_count = sum(1 for i in self.issues if i.severity == Severity.WARNING)
if overall_status == CompatibilityStatus.INCOMPATIBLE:
summary = f"INCOMPATIBLE: {critical_count} critical issues found that will cause runtime errors"
elif overall_status == CompatibilityStatus.WARNING:
summary = f"WARNING: {warning_count} potential issues found - review recommended"
elif overall_status == CompatibilityStatus.COMPATIBLE:
summary = f"COMPATIBLE: No compatibility issues detected ({len(self.frontend_deps)} frontend, {len(self.backend_deps)} backend deps)"
else:
summary = "UNKNOWN: Could not determine compatibility (no dependencies found)"
return CompatibilityReport(
status=overall_status,
frontend_deps=self.frontend_deps,
backend_deps=self.backend_deps,
issues=self.issues,
recommendations=recommendations,
summary=summary
)
def format_report(self, report: Optional[CompatibilityReport] = None) -> str:
"""Format report as text."""
report = report or self.generate_report()
lines = [
"=" * 70,
"VERSIONGUARD COMPATIBILITY REPORT",
"=" * 70,
"",
f"Status: {report.status.value.upper()}",
"",
"SUMMARY",
"-" * 40,
report.summary,
"",
"DEPENDENCIES SCANNED",
"-" * 40,
f"Frontend packages: {len(report.frontend_deps)}",
f"Backend packages: {len(report.backend_deps)}",
]
if report.issues:
lines.extend([
"",
"ISSUES FOUND",
"-" * 40,
])
for i, issue in enumerate(report.issues, 1):
status_icon = {
CompatibilityStatus.INCOMPATIBLE: "[X]",
CompatibilityStatus.WARNING: "[!]",
CompatibilityStatus.COMPATIBLE: "[OK]",
CompatibilityStatus.UNKNOWN: "[?]"
}.get(issue.status, "[?]")
lines.append(f"\n{i}. {status_icon} {issue.package.upper()}")
lines.append(f" Status: {issue.status.value.upper()}")
lines.append(f" Severity: {issue.severity.value.upper()}")
lines.append(f" Message: {issue.message}")
if issue.details:
for detail in issue.details:
lines.append(f" - {detail}")
lines.append(f" Recommendation: {issue.recommendation}")
else:
lines.extend([
"",
"NO ISSUES FOUND",
"-" * 40,
"All scanned dependencies appear compatible.",
])
if report.recommendations:
lines.extend([
"",
"RECOMMENDATIONS",
"-" * 40,
])
for rec in report.recommendations:
lines.append(f"- {rec}")
lines.extend([
"",
"=" * 70,
])
return "\n".join(lines)
def export_json(self, filepath: Path) -> None:
"""Export report to JSON file."""
report = self.generate_report()
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(report.to_dict(), f, indent=2, ensure_ascii=False)
self.logger.info(f"Report exported to {filepath}")
def main():
"""CLI entry point."""
import argparse
parser = argparse.ArgumentParser(
description="VersionGuard - Pre-validate version compatibility"
)
subparsers = parser.add_subparsers(dest="command", help="Commands")
# Scan command
scan_parser = subparsers.add_parser("scan", help="Scan project for dependencies")
scan_parser.add_argument("path", nargs="?", default=".", help="Project directory")
scan_parser.add_argument("--output", "-o", help="Output report file")
scan_parser.add_argument("--json", action="store_true", help="Output as JSON")
# Check command
check_parser = subparsers.add_parser("check", help="Check specific package versions")
check_parser.add_argument("--frontend", "-f", help="Frontend package@version")
check_parser.add_argument("--backend", "-b", help="Backend package@version")
# Demo command
demo_parser = subparsers.add_parser("demo", help="Run demonstration")
# Version command
parser.add_argument("--version", "-v", action="version", version=f"VersionGuard {__version__}")
args = parser.parse_args()
if args.command == "scan":
project_path = Path(args.path)
guard = VersionGuard(project_path)
print(f"Scanning {project_path.absolute()}...")
guard.scan_project()
guard.check_compatibility()
report = guard.generate_report()
if args.json:
if args.output:
guard.export_json(Path(args.output))
print(f"Report saved to {args.output}")
else:
print(json.dumps(report.to_dict(), indent=2))
else:
formatted = guard.format_report(report)
print(formatted)
if args.output:
with open(args.output, 'w') as f:
f.write(formatted)
print(f"\nReport saved to {args.output}")
elif args.command == "demo":
print("Running VersionGuard Demo...")
print("=" * 70)
guard = VersionGuard()
# Create mock dependencies to demonstrate
print("\nScenario: Socket.IO Version Mismatch")
print("-" * 70)
print("Frontend: socket.io-client@4.7.2")
print("Backend: python-socketio@5.8.0 (Socket.IO v5)")
# Manually add demo dependencies
guard.frontend_deps = [
Dependency(
name="socket.io-client",
version=SemanticVersion.parse("4.7.2"),
version_spec="^4.7.2",
source="frontend",
file_path="package.json"
)
]
guard.backend_deps = [
Dependency(
name="python-socketio",
version=SemanticVersion.parse("5.8.0"),
version_spec=">=5.8.0",
source="backend",
file_path="requirements.txt"
)
]
# For this demo, manually create the issue
guard.issues = [
CompatibilityIssue(
package="socket.io",
frontend_version=SemanticVersion.parse("4.7.2"),
backend_version=SemanticVersion.parse("5.8.0"),
status=CompatibilityStatus.INCOMPATIBLE,
severity=Severity.CRITICAL,
message="Socket.IO client v4.7.2 is incompatible with server v5.8.0",
recommendation="Use socket.io-client v4 with python-socketio v4, or upgrade both to v5",
details=[
"Client (socket.io-client): v4.7.2 (Socket.IO v4 protocol)",
"Server (python-socketio): v5.8.0 (Socket.IO v5 protocol)",
"Rule: Major versions must match for protocol compatibility"
]
)
]
print("\n" + guard.format_report())
print("\n" + "=" * 70)
print("This is the EXACT issue that cost IRIS 2 hours during BCH Mobile dev!")
print("VersionGuard would have caught this BEFORE implementation started.")
print("=" * 70)
elif args.command == "check":
if not args.frontend and not args.backend:
print("Specify at least one package with --frontend or --backend")
return
guard = VersionGuard()
if args.frontend:
name, version = args.frontend.split("@") if "@" in args.frontend else (args.frontend, "")
guard.frontend_deps.append(Dependency(
name=name,
version=SemanticVersion.parse(version),
version_spec=version,
source="frontend",
file_path="cli"
))
if args.backend:
name, version = args.backend.split("@") if "@" in args.backend else (args.backend, "")
guard.backend_deps.append(Dependency(
name=name,
version=SemanticVersion.parse(version),
version_spec=version,
source="backend",
file_path="cli"
))
guard.check_compatibility()
print(guard.format_report())
else:
parser.print_help()
if __name__ == "__main__":
main()