8000 style: fix code formatting and linting issues · loonghao/pypi-query-mcp-server@f2b92ff · GitHub
[go: up one dir, main page]

Skip to content

Commit f2b92ff

Browse files
committed
style: fix code formatting and linting issues
- Fix whitespace in docstrings and blank lines - Remove unused variables in tests - Rename unused loop variables to follow conventions - All ruff checks now pass Signed-off-by: Hal <hal.long@outlook.com>
1 parent 6b14ff6 commit f2b92ff

File tree

6 files changed

+194
-203
lines changed

6 files changed

+194
-203
lines changed

examples/dependency_analysis_demo.py

Lines changed: 34 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
async def analyze_pyside2_dependencies():
1818
"""Analyze PySide2 dependencies for Python 3.10."""
1919
print("🔍 Analyzing PySide2 dependencies for Python 3.10...")
20-
20+
2121
try:
2222
result = await resolve_package_dependencies(
2323
package_name="PySide2",
@@ -26,23 +26,23 @@ async def analyze_pyside2_dependencies():
2626
include_dev=False,
2727
max_depth=3
2828
)
29-
29+
3030
print(f"✅ Successfully resolved dependencies for {result['package_name']}")
31-
print(f"📊 Summary:")
31+
print("📊 Summary:")
3232
summary = result['summary']
3333 print(f" - Total packages: {summary['total_packages']}")
3434
print(f" - Runtime dependencies: {summary['total_runtime_dependencies']}")
3535
print(f" - Max depth: {summary['max_depth']}")
36-
37-
print(f"\n📦 Package list:")
36+
37+
print("\n📦 Package list:")
3838
for i, pkg in enumerate(summary['package_list'][:10], 1): # Show first 10
3939
print(f" {i}. {pkg}")
40-
40+
4141
if len(summary['package_list']) > 10:
4242
print(f" ... and {len(summary['package_list']) - 10} more packages")
43-
43+
4444
return result
45-
45+
4646
except Exception as e:
4747
print(f"❌ Error analyzing dependencies: {e}")
4848
return None
@@ -51,9 +51,9 @@ async def analyze_pyside2_dependencies():
5151
async def download_pyside2_packages():
5252
"""Download PySide2 and its dependencies."""
5353
print("\n📥 Downloading PySide2 and dependencies...")
54-
54+
5555
download_dir = Path("./pyside2_downloads")
56-
56+
5757
try:
5858
result = await download_package_with_dependencies(
5959
package_name="PySide2",
@@ -65,24 +65,24 @@ async def download_pyside2_packages():
6565
verify_checksums=True,
6666
max_depth=2 # Limit depth for demo
6767
)
68-
69-
print(f"✅ Download completed!")
70-
print(f"📊 Download Summary:")
68+
69+
print("✅ Download completed!")
70+
print("📊 Download Summary:")
7171
summary = result['summary']
7272
print(f" - Total packages: {summary['total_packages']}")
7373
print(f" - Successful downloads: {summary['successful_downloads']}")
7474
print(f" - Failed downloads: {summary['failed_downloads']}")
7575
print(f" - Total size: {summary['total_downloaded_size']:,} bytes")
7676
print(f" - Success rate: {summary['success_rate']:.1f}%")
7777
print(f" - Download directory: {summary['download_directory']}")
78-
78+
7979
if result['failed_downloads']:
80-
print(f"\n⚠️ Failed downloads:")
80+
print("\n⚠️ Failed downloads:")
8181
for failure in result['failed_downloads']:
8282
print(f" - {failure['package']}: {failure['error']}")
83-
83+
8484
return result
85-
85+
8686
except Exception as e:
8787
print(f"❌ Error downloading packages: {e}")
8888
return None
@@ -91,7 +91,7 @@ async def download_pyside2_packages():
9191
async def analyze_small_package():
9292
"""Analyze a smaller package for demonstration."""
9393
print("\n🔍 Analyzing 'click' package dependencies...")
94-
94+
9595
try:
9696
result = await resolve_package_dependencies(
9797
package_name="click",
@@ -100,26 +100,26 @@ async def analyze_small_package():
100100
include_dev=False,
101101
max_depth=5
102102
)
103-
103+
104104
print(f"✅ Successfully resolved dependencies for {result['package_name']}")
105-
105+
106106
# Show detailed dependency tree
107-
print(f"\n🌳 Dependency Tree:")
107+
print("\n🌳 Dependency Tree:")
108108
dependency_tree = result['dependency_tree']
109-
110-
for pkg_name, pkg_info in dependency_tree.items():
109+
110+
for _pkg_name, pkg_info in dependency_tree.items():
111111
indent = " " * pkg_info['depth']
112112
print(f"{indent}- {pkg_info['name']} ({pkg_info['version']})")
113-
113+
114114
runtime_deps = pkg_info['dependencies']['runtime']
115115
if runtime_deps:
116116
for dep in runtime_deps[:3]: # Show first 3 dependencies
117117
print(f"{indent} └─ {dep}")
118118
if len(runtime_deps) > 3:
119119
print(f"{indent} └─ ... and {len(runtime_deps) - 3} more")
120-
120+
121121
return result
122-
122+
123123
except Exception as e:
124124
print(f"❌ Error analyzing dependencies: {e}")
125125
return None
@@ -129,26 +129,26 @@ async def main():
129129
"""Main demonstration function."""
130130
print("🚀 PyPI Query MCP Server - Dependency Analysis Demo")
131131
print("=" * 60)
132-
132+
133133
# Analyze a small package first
134134
click_result = await analyze_small_package()
135-
135+
136136
# Analyze PySide2 dependencies
137137
pyside2_result = await analyze_pyside2_dependencies()
138-
138+
139139
# Optionally download packages (commented out to avoid large downloads in demo)
140140
# download_result = await download_pyside2_packages()
141-
141+
142142
print("\n" + "=" * 60)
143143
print("✨ Demo completed!")
144-
144+
145145
if click_result:
146-
print(f"📝 Click analysis saved to: click_dependencies.json")
146+
print("📝 Click analysis saved to: click_dependencies.json")
147147
with open("click_dependencies.json", "w") as f:
148148
json.dump(click_result, f, indent=2)
149-
149+
150150
if pyside2_result:
151-
print(f"📝 PySide2 analysis saved to: pyside2_dependencies.json")
151+
print("📝 PySide2 analysis saved to: pyside2_dependencies.json")
152152
with open("pyside2_dependencies.json", "w") as f:
153153
json.dump(pyside2_result, f, indent=2)
154154

pypi_query_mcp/core/dependency_parser.py

Lines changed: 47 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,86 +1,86 @@
11
"""Dependency parsing utilities for PyPI packages."""
22

3+
import logging
34
import re
4-
from typing import Any, Dict, List, Optional, Set, Tuple
5+
from typing import Any
6+
57
from packaging.requirements import Requirement
6-
from packaging.specifiers import SpecifierSet
78
from packaging.version import Version
8-
import logging
99

1010
logger = logging.getLogger(__name__)
1111

1212

1313
class DependencyParser:
1414
"""Parser for Python package dependencies."""
15-
15+
1616
def __init__(self):
17-
self.parsed_cache: Dict[str, List[Requirement]] = {}
18-
19-
def parse_requirements(self, requires_dist: List[str]) -> List[Requirement]:
17+
self.parsed_cache: dict[str, list[Requirement]] = {}
18+
19+
def parse_requirements(self, requires_dist: list[str]) -> list[Requirement]:
2020
"""Parse requirements from requires_dist list.
21-
21+
2222
Args:
2323
requires_dist: List of requirement strings from PyPI metadata
24-
24+
2525
Returns:
2626
List of parsed Requirement objects
2727
"""
2828
requirements = []
29-
29+
3030
for req_str in requires_dist or []:
3131
if not req_str or not req_str.strip():
3232
continue
33-
33+
3434
try:
3535
req = Requirement(req_str)
3636
requirements.append(req)
3737
except Exception as e:
3838
logger.warning(f"Failed to parse requirement '{req_str}': {e}")
3939
continue
40-
40+
4141
return requirements
42-
42+
4343
def filter_requirements_by_python_version(
44-
self,
45-
requirements: List[Requirement],
44+
self,
45+
requirements: list[Requirement],
4646
python_version: str
47-
) -> List[Requirement]:
47+
) -> list[Requirement]:
4848
"""Filter requirements based on Python version.
49-
49+
5050
Args:
5151
requirements: List of Requirement objects
5252
python_version: Target Python version (e.g., "3.10")
53-
53+
5454
Returns:
5555
Filtered list of requirements applicable to the Python version
5656
"""
5757
filtered = []
58-
58+
5959
try:
6060
target_version = Version(python_version)
6161
except Exception as e:
6262
logger.warning(f"Invalid Python version '{python_version}': {e}")
6363
return requirements
64-
64+
6565
for req in requirements:
6666
if self._is_requirement_applicable(req, target_version):
6767
filtered.append(req)
68-
68+
6969
return filtered
70-
70+
7171
def _is_requirement_applicable(self, req: Requirement, python_version: Version) -> bool:
7272
"""Check if a requirement is applicable for the given Python version.
73-
73+
7474
Args:
7575
req: Requirement object
7676
python_version: Target Python version
77-
77+
7878
Returns:
7979
True if requirement applies to the Python version
8080
"""
8181
if not req.marker:
8282
return True
83-
83+
8484
# Create environment for marker evaluation
8585
env = {
8686
'python_version': str(python_version),
@@ -90,22 +90,22 @@ def _is_requirement_applicable(self, req: Requirement, python_version: Version)
9090
'implementation_name': 'cpython',
9191
'implementation_version': str(python_version),
9292
}
93-
93+
9494
try:
9595
return req.marker.evaluate(env)
9696
except Exception as e:
9797
logger.warning(f"Failed to evaluate marker for {req}: {e}")
9898
return True # Include by default if evaluation fails
99-
99+
100100
def categorize_dependencies(
101-
self,
102-
requirements: List[Requirement]
103-
) -> Dict[str, List[Requirement]]:
101+
self,
102+
requirements: list[Requirement]
103+
) -> dict[str, list[Requirement]]:
104104
"""Categorize dependencies into runtime, development, and optional groups.
105-
105+
106106
Args:
107107
requirements: List of Requirement objects
108-
108+
109109
Returns:
110110
Dictionary with categorized dependencies
111111
"""
@@ -115,15 +115,15 @@ def categorize_dependencies(
115115
'optional': {},
116116
'extras': {}
117117
}
118-
118+
119119
for req in requirements:
120120
if not req.marker:
121121
# No marker means it's a runtime dependency
122122
categories['runtime'].append(req)
123123
continue
124-
124+
125125
marker_str = str(req.marker)
126-
126+
127127
# Check for extra dependencies
128128
if 'extra ==' in marker_str:
129129
extra_match = re.search(r'extra\s*==\s*["\']([^"\']+)["\']', marker_str)
@@ -133,45 +133,45 @@ def categorize_dependencies(
133133
categories['extras'][extra_name] = []
134134
categories['extras'][extra_name].append(req)
135135
continue
136-
136+
137137
# Check for development dependencies
138138
if any(keyword in marker_str.lower() for keyword in ['dev', 'test', 'lint', 'doc']):
139139
categories['development'].append(req)
140140
else:
141141
categories['runtime'].append(req)
142-
142+
143143
return categories
144-
145-
def extract_package_names(self, requirements: List[Requirement]) -> Set[str]:
144+
145+
def extract_package_names(self, requirements: list[Requirement]) -> set[str]:
146146
"""Extract package names from requirements.
147-
147+
148148
Args:
149149
requirements: List of Requirement objects
150-
150+
151151
Returns:
152152
Set of package names
153153
"""
154154
return {req.name.lower() for req in requirements}
155-
156-
def get_version_constraints(self, req: Requirement) -> Dict[str, Any]:
155+
156+
def get_version_constraints(self, req: Requirement) -> dict[str, Any]:
157157
"""Get version constraints from a requirement.
158-
158+
159159
Args:
160160
req: Requirement object
161-
161+
162162
Returns:
163163
Dictionary with version constraint information
164164
"""
165165
if not req.specifier:
166166
return {'constraints': [], 'allows_any': True}
167-
167+
168168
constraints = []
169169
for spec in req.specifier:
170170
constraints.append({
171171
'operator': spec.operator,
172172
'version': str(spec.version)
173173
})
174-
174+
175175
return {
176176
'constraints': constraints,
177177
'allows_any': len(constraints) == 0,

0 commit comments

Comments
 (0)
0