pyconflict 2.0.0__py3-none-any.whl

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.
Files changed (35) hide show
  1. pyconflict/__init__.py +3 -0
  2. pyconflict/__main__.py +6 -0
  3. pyconflict/application/__init__.py +1 -0
  4. pyconflict/application/exceptions.py +27 -0
  5. pyconflict/application/use_cases/__init__.py +1 -0
  6. pyconflict/application/use_cases/check_add_package.py +113 -0
  7. pyconflict/application/use_cases/check_environment.py +97 -0
  8. pyconflict/application/use_cases/get_latest_stable.py +62 -0
  9. pyconflict/application/use_cases/team_check.py +114 -0
  10. pyconflict/domain/__init__.py +1 -0
  11. pyconflict/domain/entities.py +122 -0
  12. pyconflict/domain/exceptions.py +23 -0
  13. pyconflict/domain/repositories.py +140 -0
  14. pyconflict/domain/services/__init__.py +1 -0
  15. pyconflict/domain/services/conflict_detector.py +124 -0
  16. pyconflict/domain/services/suggestion_generator.py +101 -0
  17. pyconflict/domain/services/version_resolver.py +86 -0
  18. pyconflict/infrastructure/__init__.py +1 -0
  19. pyconflict/infrastructure/exceptions.py +25 -0
  20. pyconflict/infrastructure/repositories/__init__.py +1 -0
  21. pyconflict/infrastructure/repositories/cloud_cache_repository.py +51 -0
  22. pyconflict/infrastructure/repositories/disk_cache_repository.py +154 -0
  23. pyconflict/infrastructure/repositories/pip_environment_repository.py +75 -0
  24. pyconflict/infrastructure/repositories/pypi_repository.py +277 -0
  25. pyconflict/presentation/__init__.py +1 -0
  26. pyconflict/presentation/cli/__init__.py +1 -0
  27. pyconflict/presentation/cli/commands.py +487 -0
  28. pyconflict/presentation/cli/di.py +124 -0
  29. pyconflict/presentation/cli/formatters.py +132 -0
  30. pyconflict-2.0.0.dist-info/LICENSE +21 -0
  31. pyconflict-2.0.0.dist-info/METADATA +498 -0
  32. pyconflict-2.0.0.dist-info/RECORD +35 -0
  33. pyconflict-2.0.0.dist-info/WHEEL +5 -0
  34. pyconflict-2.0.0.dist-info/entry_points.txt +2 -0
  35. pyconflict-2.0.0.dist-info/top_level.txt +1 -0
pyconflict/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """PyConflict - Python Dependency Conflict Checker."""
2
+
3
+ __version__ = "2.0.0"
pyconflict/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Run the PyConflict CLI with ``python -m pyconflict``."""
2
+
3
+ from pyconflict.presentation.cli.commands import app
4
+
5
+ if __name__ == "__main__":
6
+ app()
@@ -0,0 +1 @@
1
+ """Application layer - Use cases and business workflows."""
@@ -0,0 +1,27 @@
1
+ """Application-level exceptions."""
2
+
3
+
4
+ class ApplicationException(Exception):
5
+ """Base exception for application errors."""
6
+
7
+ pass
8
+
9
+
10
+ class PackageNotFoundError(ApplicationException):
11
+ """Package not found in repository."""
12
+
13
+ def __init__(self, package_name: str, message: str = "") -> None:
14
+ self.package_name = package_name
15
+ super().__init__(message or f"Package not found: {package_name}")
16
+
17
+
18
+ class EnvironmentError(ApplicationException):
19
+ """Cannot read environment."""
20
+
21
+ pass
22
+
23
+
24
+ class RepositoryError(ApplicationException):
25
+ """Repository operation failed."""
26
+
27
+ pass
@@ -0,0 +1 @@
1
+ """Use cases - Application business workflows."""
@@ -0,0 +1,113 @@
1
+ """Use case for checking if a package can be added safely."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import List, Optional
5
+
6
+ from pyconflict.domain.entities import Conflict, Environment, Package
7
+ from pyconflict.domain.repositories import IEnvironmentRepository, IPackageRepository
8
+ from pyconflict.domain.services.conflict_detector import ConflictDetector
9
+ from pyconflict.domain.services.suggestion_generator import SuggestionGenerator
10
+
11
+
12
+ @dataclass
13
+ class CheckAddPackageRequest:
14
+ """Request to check if a package can be added."""
15
+
16
+ package_name: str
17
+ version: Optional[str] = None
18
+
19
+
20
+ @dataclass
21
+ class CheckAddPackageResponse:
22
+ """Response from checking a package."""
23
+
24
+ safe_to_add: bool
25
+ package: Package
26
+ conflicts: List[Conflict]
27
+ suggestions: List[str]
28
+ caveats: List[str]
29
+
30
+
31
+ class CheckAddPackageUseCase:
32
+ """Use case: Check if adding a package will cause conflicts.
33
+
34
+ This is the core use case of PyConflict - answering the question:
35
+ "Will adding this package break my environment?"
36
+ """
37
+
38
+ def __init__(
39
+ self,
40
+ package_repo: IPackageRepository,
41
+ env_repo: IEnvironmentRepository,
42
+ conflict_detector: ConflictDetector,
43
+ suggestion_generator: SuggestionGenerator,
44
+ ) -> None:
45
+ """Initialize the use case.
46
+
47
+ Args:
48
+ package_repo: Repository for fetching package metadata
49
+ env_repo: Repository for reading environment state
50
+ conflict_detector: Service for detecting conflicts
51
+ suggestion_generator: Service for generating suggestions
52
+ """
53
+ self._package_repo = package_repo
54
+ self._env_repo = env_repo
55
+ self._conflict_detector = conflict_detector
56
+ self._suggestion_generator = suggestion_generator
57
+
58
+ def execute(self, request: CheckAddPackageRequest) -> CheckAddPackageResponse:
59
+ """Execute the use case.
60
+
61
+ Args:
62
+ request: The request parameters
63
+
64
+ Returns:
65
+ Response with conflict analysis
66
+ """
67
+ # 1. Get current environment state
68
+ environment = self._get_environment()
69
+
70
+ # 2. Fetch target package metadata
71
+ package = self._package_repo.get_package(request.package_name, request.version)
72
+
73
+ # 3. Detect conflicts using domain logic
74
+ conflicts = self._conflict_detector.detect_conflicts(package, environment)
75
+
76
+ # 4. Generate suggestions if conflicts found
77
+ suggestions = []
78
+ if conflicts:
79
+ suggestions = self._suggestion_generator.generate(package, conflicts, environment)
80
+
81
+ # 5. Describe checks that are not part of the current analysis.
82
+ caveats = self._get_caveats()
83
+
84
+ return CheckAddPackageResponse(
85
+ safe_to_add=len(conflicts) == 0,
86
+ package=package,
87
+ conflicts=conflicts,
88
+ suggestions=suggestions,
89
+ caveats=caveats,
90
+ )
91
+
92
+ def _get_environment(self) -> Environment:
93
+ """Get the current environment state.
94
+
95
+ Returns:
96
+ Environment entity
97
+ """
98
+ return Environment(
99
+ packages=self._env_repo.get_installed_packages(),
100
+ python_version=self._env_repo.get_python_version(),
101
+ platform=self._env_repo.get_platform(),
102
+ )
103
+
104
+ def _get_caveats(self) -> List[str]:
105
+ """List limitations of this check.
106
+
107
+ Returns:
108
+ List of caveats/warnings about what wasn't checked
109
+ """
110
+ return [
111
+ "Only direct dependencies checked (not transitive)",
112
+ "Optional extras not included",
113
+ ]
@@ -0,0 +1,97 @@
1
+ """Use case for validating the current Python environment."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Dict, List
5
+
6
+ from packaging.requirements import InvalidRequirement, Requirement
7
+ from packaging.utils import canonicalize_name
8
+ from packaging.version import Version
9
+
10
+ from pyconflict.domain.entities import (
11
+ Conflict,
12
+ ConflictSeverity,
13
+ InstalledDistribution,
14
+ )
15
+ from pyconflict.domain.repositories import IEnvironmentRepository
16
+
17
+
18
+ @dataclass
19
+ class CheckEnvironmentResponse:
20
+ """Result of checking installed distribution requirements."""
21
+
22
+ conflicts: List[Conflict]
23
+ analysis_errors: List[Dict[str, str]]
24
+ packages_count: int
25
+
26
+ @property
27
+ def exit_code(self) -> int:
28
+ """Return the CLI status for this result."""
29
+ if self.analysis_errors:
30
+ return 5
31
+ return 1 if self.conflicts else 0
32
+
33
+
34
+ class CheckEnvironmentUseCase:
35
+ """Check installed distributions for missing or incompatible requirements."""
36
+
37
+ def __init__(self, environment_repository: IEnvironmentRepository) -> None:
38
+ self._environment_repository = environment_repository
39
+
40
+ def execute(self) -> CheckEnvironmentResponse:
41
+ distributions = self._environment_repository.get_installed_distributions()
42
+ installed = {str(canonicalize_name(item.name)): item.version for item in distributions}
43
+ conflicts: List[Conflict] = []
44
+ analysis_errors: List[Dict[str, str]] = []
45
+
46
+ for distribution in distributions:
47
+ self._check_distribution(
48
+ distribution,
49
+ installed,
50
+ conflicts,
51
+ analysis_errors,
52
+ )
53
+
54
+ return CheckEnvironmentResponse(
55
+ conflicts=conflicts,
56
+ analysis_errors=analysis_errors,
57
+ packages_count=len(distributions),
58
+ )
59
+
60
+ @staticmethod
61
+ def _check_distribution(
62
+ distribution: InstalledDistribution,
63
+ installed: Dict[str, Version],
64
+ conflicts: List[Conflict],
65
+ analysis_errors: List[Dict[str, str]],
66
+ ) -> None:
67
+ for raw_requirement in distribution.requirements:
68
+ try:
69
+ requirement = Requirement(raw_requirement)
70
+ if requirement.marker and not requirement.marker.evaluate():
71
+ continue
72
+ except (InvalidRequirement, ValueError, TypeError) as error:
73
+ analysis_errors.append(
74
+ {
75
+ "package": distribution.name,
76
+ "requirement": raw_requirement,
77
+ "error": str(error),
78
+ }
79
+ )
80
+ continue
81
+
82
+ installed_version = installed.get(canonicalize_name(requirement.name))
83
+ if installed_version is not None and requirement.specifier.contains(
84
+ installed_version, prereleases=True
85
+ ):
86
+ continue
87
+
88
+ conflicts.append(
89
+ Conflict(
90
+ dependency_name=requirement.name,
91
+ required_by=f"{distribution.name}=={distribution.version}",
92
+ required_constraint=requirement.specifier,
93
+ installed_version=installed_version,
94
+ conflicting_package=None,
95
+ severity=ConflictSeverity.ERROR,
96
+ )
97
+ )
@@ -0,0 +1,62 @@
1
+ """Use case for getting the latest stable version of a package."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Optional
5
+
6
+ from packaging.version import Version
7
+
8
+ from pyconflict.domain.repositories import IPackageRepository
9
+
10
+
11
+ @dataclass
12
+ class GetLatestStableRequest:
13
+ """Request to get latest stable version."""
14
+
15
+ package_name: str
16
+ python_version: Optional[str] = None # e.g., "3.8"
17
+
18
+
19
+ @dataclass
20
+ class GetLatestStableResponse:
21
+ """Response with latest stable version."""
22
+
23
+ package_name: str
24
+ version: Version
25
+ is_filtered_by_python: bool
26
+
27
+
28
+ class GetLatestStableUseCase:
29
+ """Use case: Get the latest stable version of a package.
30
+
31
+ Returns the latest non-prerelease version, optionally filtered
32
+ by Python version compatibility.
33
+ """
34
+
35
+ def __init__(self, package_repo: IPackageRepository) -> None:
36
+ """Initialize the use case.
37
+
38
+ Args:
39
+ package_repo: Repository for fetching package metadata
40
+ """
41
+ self._package_repo = package_repo
42
+
43
+ def execute(self, request: GetLatestStableRequest) -> GetLatestStableResponse:
44
+ """Execute the use case.
45
+
46
+ Args:
47
+ request: The request parameters
48
+
49
+ Returns:
50
+ Response with latest stable version
51
+ """
52
+ python_version = None
53
+ if request.python_version:
54
+ python_version = Version(request.python_version)
55
+
56
+ version = self._package_repo.get_latest_stable(request.package_name, python_version)
57
+
58
+ return GetLatestStableResponse(
59
+ package_name=request.package_name,
60
+ version=version,
61
+ is_filtered_by_python=python_version is not None,
62
+ )
@@ -0,0 +1,114 @@
1
+ """Application workflow for comparing an environment with a team baseline."""
2
+
3
+ from typing import Dict, List, Optional
4
+
5
+ from packaging.utils import canonicalize_name
6
+ from packaging.version import InvalidVersion, Version
7
+
8
+ from pyconflict.domain.repositories import ICacheRepository, IEnvironmentRepository
9
+
10
+
11
+ class TeamCheckResult:
12
+ """Comparison between installed packages and a saved team baseline."""
13
+
14
+ def __init__(self, workspace_id: str, drift: List[Dict[str, Optional[str]]]) -> None:
15
+ self.workspace_id = workspace_id
16
+ self.drift = drift
17
+ self.matches_standard = not drift
18
+ self.packages_count = 0
19
+
20
+
21
+ class TeamCheckUseCase:
22
+ """Read or save an explicitly selected team package baseline.
23
+
24
+ The check only reads the baseline. It does not upload a developer's
25
+ environment unless ``save_current_as_standard`` is explicitly called.
26
+ """
27
+
28
+ STANDARD_KEY = "team:standard_environment"
29
+
30
+ def __init__(
31
+ self,
32
+ environment_repository: IEnvironmentRepository,
33
+ cache_repository: ICacheRepository,
34
+ workspace_id: str,
35
+ ) -> None:
36
+ if not workspace_id.strip():
37
+ raise ValueError("workspace_id must not be empty")
38
+ self.environment_repository = environment_repository
39
+ self.cache_repository = cache_repository
40
+ self.workspace_id = workspace_id
41
+
42
+ def execute(self) -> TeamCheckResult:
43
+ """Compare installed packages with the saved team standard."""
44
+ baseline = self.cache_repository.get(self.STANDARD_KEY)
45
+ if baseline is None:
46
+ raise RuntimeError("No team baseline exists. Run team-check --set-standard first.")
47
+
48
+ installed_versions = {
49
+ str(canonicalize_name(name)): str(version)
50
+ for name, version in self.environment_repository.get_installed_packages().items()
51
+ }
52
+ normalized_baseline = self._normalize_baseline(baseline)
53
+ drift: List[Dict[str, Optional[str]]] = []
54
+
55
+ for package, expected in normalized_baseline.items():
56
+ actual = installed_versions.get(package)
57
+ if actual is None:
58
+ drift.append(
59
+ {
60
+ "package": package,
61
+ "installed_version": None,
62
+ "standard_version": expected,
63
+ "status": "missing",
64
+ }
65
+ )
66
+ elif actual != expected:
67
+ drift.append(
68
+ {
69
+ "package": package,
70
+ "installed_version": actual,
71
+ "standard_version": expected,
72
+ "status": "different",
73
+ }
74
+ )
75
+
76
+ for package, actual in installed_versions.items():
77
+ if package not in normalized_baseline:
78
+ drift.append(
79
+ {
80
+ "package": package,
81
+ "installed_version": actual,
82
+ "standard_version": None,
83
+ "status": "extra",
84
+ }
85
+ )
86
+
87
+ result = TeamCheckResult(self.workspace_id, drift)
88
+ result.packages_count = len(installed_versions)
89
+ return result
90
+
91
+ def save_current_as_standard(self, ttl: int = 30 * 24 * 60 * 60) -> Dict[str, str]:
92
+ """Save the current environment as the team baseline on explicit request."""
93
+ if ttl <= 0:
94
+ raise ValueError("ttl must be greater than zero")
95
+ standard = {
96
+ str(canonicalize_name(name)): str(version)
97
+ for name, version in self.environment_repository.get_installed_packages().items()
98
+ }
99
+ self.cache_repository.set(self.STANDARD_KEY, standard, ttl)
100
+ return standard
101
+
102
+ @staticmethod
103
+ def _normalize_baseline(value: object) -> Dict[str, str]:
104
+ if not isinstance(value, dict):
105
+ raise ValueError("The saved team baseline must be a package-to-version object")
106
+ normalized: Dict[str, str] = {}
107
+ for name, version in value.items():
108
+ if not isinstance(name, str) or not isinstance(version, str):
109
+ raise ValueError("Team baseline package names and versions must be strings")
110
+ try:
111
+ normalized[str(canonicalize_name(name))] = str(Version(version))
112
+ except InvalidVersion as error:
113
+ raise ValueError(f"Invalid version for {name}: {version}") from error
114
+ return normalized
@@ -0,0 +1 @@
1
+ """Domain layer - Core business logic and entities."""
@@ -0,0 +1,122 @@
1
+ """Domain entities - Immutable business objects."""
2
+
3
+ from dataclasses import dataclass, field
4
+ from enum import Enum
5
+ from typing import Dict, List, Optional, Set
6
+
7
+ from packaging.specifiers import SpecifierSet
8
+ from packaging.version import Version
9
+
10
+
11
+ class ConflictSeverity(Enum):
12
+ """Severity level of a conflict."""
13
+
14
+ ERROR = "error"
15
+ WARNING = "warning"
16
+ INFO = "info"
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Dependency:
21
+ """A dependency with version constraint.
22
+
23
+ Represents a single dependency requirement, including version constraints,
24
+ platform markers, and extras.
25
+ """
26
+
27
+ name: str
28
+ specifier: SpecifierSet
29
+ markers: Optional[str] = None # PEP 508 markers (e.g., "python_version >= '3.8'")
30
+ extras: Set[str] = field(default_factory=set)
31
+
32
+ def __str__(self) -> str:
33
+ """String representation matching PEP 508 format."""
34
+ parts = [self.name]
35
+
36
+ if self.extras:
37
+ parts.append(f"[{','.join(sorted(self.extras))}]")
38
+
39
+ if self.specifier:
40
+ parts.append(str(self.specifier))
41
+
42
+ if self.markers:
43
+ parts.append(f"; {self.markers}")
44
+
45
+ return "".join(parts)
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class Package:
50
+ """Immutable package entity.
51
+
52
+ Represents a Python package with its metadata and dependencies.
53
+ """
54
+
55
+ name: str
56
+ version: Version
57
+ requires_python: Optional[str] = None
58
+ dependencies: List[Dependency] = field(default_factory=list)
59
+
60
+ def __str__(self) -> str:
61
+ """String representation."""
62
+ return f"{self.name}=={self.version}"
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class Conflict:
67
+ """Represents a dependency conflict.
68
+
69
+ A conflict occurs when a package requires a version of a dependency
70
+ that is incompatible with what's installed or required by another package.
71
+ """
72
+
73
+ dependency_name: str
74
+ required_by: str # Package that requires this dependency
75
+ required_constraint: SpecifierSet
76
+ installed_version: Optional[Version]
77
+ conflicting_package: Optional[str] # Package that conflicts with this requirement
78
+ severity: ConflictSeverity
79
+
80
+ def __str__(self) -> str:
81
+ """Human-readable description of the conflict."""
82
+ lines = [
83
+ f"Conflict in '{self.dependency_name}':",
84
+ f" Required by: {self.required_by} ({self.required_constraint})",
85
+ ]
86
+
87
+ if self.installed_version:
88
+ lines.append(f" Installed: {self.installed_version}")
89
+
90
+ if self.conflicting_package:
91
+ lines.append(f" Conflicts with: {self.conflicting_package}")
92
+
93
+ return "\n".join(lines)
94
+
95
+
96
+ @dataclass(frozen=True)
97
+ class Environment:
98
+ """Current Python environment state.
99
+
100
+ Represents the current state of installed packages and Python version.
101
+ """
102
+
103
+ packages: Dict[str, Version] # package_name -> version
104
+ python_version: Version
105
+ platform: str # sys.platform value
106
+
107
+ def has_package(self, name: str) -> bool:
108
+ """Check if a package is installed."""
109
+ return name.lower() in self.packages
110
+
111
+ def get_version(self, name: str) -> Optional[Version]:
112
+ """Get installed version of a package."""
113
+ return self.packages.get(name.lower())
114
+
115
+
116
+ @dataclass(frozen=True)
117
+ class InstalledDistribution:
118
+ """Installed distribution metadata needed for environment validation."""
119
+
120
+ name: str
121
+ version: Version
122
+ requirements: List[str] = field(default_factory=list)
@@ -0,0 +1,23 @@
1
+ """Domain-level exceptions."""
2
+
3
+
4
+ class DomainException(Exception):
5
+ """Base exception for domain errors."""
6
+
7
+ pass
8
+
9
+
10
+ class InvalidVersionError(DomainException):
11
+ """Invalid version string."""
12
+
13
+ def __init__(self, version: str, message: str = "") -> None:
14
+ self.version = version
15
+ super().__init__(message or f"Invalid version: {version}")
16
+
17
+
18
+ class IncompatibleConstraintError(DomainException):
19
+ """Constraint cannot be satisfied."""
20
+
21
+ def __init__(self, constraint: str, message: str = "") -> None:
22
+ self.constraint = constraint
23
+ super().__init__(message or f"Incompatible constraint: {constraint}")