-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcsharp.py
More file actions
212 lines (176 loc) · 6.55 KB
/
Copy pathcsharp.py
File metadata and controls
212 lines (176 loc) · 6.55 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
"""C# library extraction logic."""
import re
import xml.etree.ElementTree as ET
from typing import Literal
from .base import BaseExtractor
class CSharpExtractor(BaseExtractor):
"""Extract libraries from C# code and dependency files."""
# C# using statement pattern
USING_PATTERN = re.compile(r"^\s*using\s+([\w.]+)\s*;", re.MULTILINE)
# Package manager files
PACKAGE_FILES = [
"*.csproj",
"packages.config",
"paket.dependencies",
"Directory.Build.props",
"Directory.Packages.props",
]
# .NET Standard library namespaces (common ones)
STDLIB = {
"System",
"Microsoft.CSharp",
"Microsoft.VisualBasic",
"System.Collections",
"System.ComponentModel",
"System.Configuration",
"System.Data",
"System.Diagnostics",
"System.Drawing",
"System.Globalization",
"System.IO",
"System.Linq",
"System.Net",
"System.Reflection",
"System.Resources",
"System.Runtime",
"System.Security",
"System.Text",
"System.Threading",
"System.Timers",
"System.Web",
"System.Xml",
}
@staticmethod
def extract_imports(code: str) -> set[str]:
"""Extract C# using statements from code."""
imports = set()
for match in CSharpExtractor.USING_PATTERN.finditer(code):
namespace = match.group(1)
# Get the base namespace (first part before .)
base_namespace = namespace.split(".")[0]
imports.add(base_namespace)
return imports
@staticmethod
def parse_csproj(content: str) -> dict[str, str | None]:
"""Parse .csproj file and extract PackageReference entries."""
packages = {}
try:
# Parse XML
root = ET.fromstring(content)
# Find all PackageReference elements
# Handle both old and new csproj formats
for package_ref in root.findall(".//PackageReference"):
# Get package name from Include attribute
package_name = package_ref.get("Include")
if not package_name:
continue
# Get version from Version attribute or child element
version = package_ref.get("Version")
if not version:
version_elem = package_ref.find("Version")
if version_elem is not None and version_elem.text:
version = version_elem.text
packages[package_name] = version
except ET.ParseError:
# If XML parsing fails, try regex fallback
pattern = re.compile(
r'<PackageReference\s+Include="([^"]+)"(?:\s+Version="([^"]+)")?'
)
for match in pattern.finditer(content):
package_name = match.group(1)
version = match.group(2)
packages[package_name] = version
return packages
@staticmethod
def parse_packages_config(content: str) -> dict[str, str | None]:
"""Parse packages.config file and extract package entries."""
packages = {}
try:
root = ET.fromstring(content)
# Find all package elements
for package in root.findall(".//package"):
package_id = package.get("id")
version = package.get("version")
if package_id:
packages[package_id] = version
except ET.ParseError:
# Regex fallback
pattern = re.compile(r'<package\s+id="([^"]+)"(?:\s+version="([^"]+)")?')
for match in pattern.finditer(content):
package_id = match.group(1)
version = match.group(2)
packages[package_id] = version
return packages
@staticmethod
def parse_paket_dependencies(content: str) -> dict[str, str | None]:
"""Parse paket.dependencies file."""
packages = {}
for line in content.split("\n"):
line = line.strip()
# Skip comments and empty lines
if not line or line.startswith("//") or line.startswith("#"):
continue
# Match: nuget PackageName version
match = re.match(r"nuget\s+(\S+)(?:\s+(.+))?", line, re.IGNORECASE)
if match:
package_name = match.group(1)
version = match.group(2).strip() if match.group(2) else None
packages[package_name] = version
return packages
@staticmethod
def is_stdlib(module: str) -> bool:
"""Check if a module is part of the .NET standard library."""
return module in CSharpExtractor.STDLIB or module.startswith(
("System", "Microsoft")
)
@staticmethod
def extract_install_commands(text: str) -> list[tuple[str, str, list[str]]]:
"""
Extract C#/.NET installation commands from PR body or commit messages.
Currently C# dependencies are typically managed through .csproj or NuGet,
so this returns an empty list. This method exists for consistency.
Returns:
List of tuples: (package_manager, command, [packages])
"""
return []
@classmethod
def extract_from_file(
cls,
filename: str,
content: str,
) -> tuple[Literal["code", "dependency"] | None, dict[str, str | None]]:
"""
Extract libraries from a C# file based on its type.
Returns:
Tuple of (file_type, libraries) where file_type is "code", "dependency", or None.
"""
filename_lower = filename.lower()
# Check for package manager files
if filename_lower.endswith(".csproj"):
return (
"dependency",
cls.parse_csproj(
content=content,
),
)
elif filename_lower == "packages.config":
return (
"dependency",
cls.parse_packages_config(
content=content,
),
)
elif filename_lower == "paket.dependencies":
return (
"dependency",
cls.parse_paket_dependencies(
content=content,
),
)
# Check for C# code files
elif filename.endswith(".cs"):
imports = cls.extract_imports(
code=content,
)
return ("code", {lib: None for lib in imports})
return (None, {})