-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconverter.py
More file actions
193 lines (176 loc) · 7.14 KB
/
converter.py
File metadata and controls
193 lines (176 loc) · 7.14 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
import re
from typing import List, Dict, Optional, Tuple
# Basic type maps
JAVA_TO_TS = {
'long': 'number', 'Long': 'number',
'int': 'number', 'Integer': 'number',
'short': 'number', 'Short': 'number',
'double': 'number', 'Double': 'number',
'float': 'number', 'Float': 'number',
'BigDecimal': 'number',
'boolean': 'boolean', 'Boolean': 'boolean',
'String': 'string', 'char': 'string', 'Character': 'string',
'LocalDate': 'string', 'LocalDateTime': 'string', 'Date': 'string', 'Instant': 'string',
'Object': 'any'
}
CSHARP_TO_TS = {
'int': 'number', 'long': 'number', 'short': 'number',
'double': 'number', 'float': 'number', 'decimal': 'number',
'bool': 'boolean', 'string': 'string', 'DateTime': 'string',
'object': 'any'
}
# patterns
CLASS_REGEX = re.compile(r'\b(public\s+)?(class|record|interface)\s+(\w+)\s*(?:\<[^>]*\>)?\s*(?:extends|implements)?[^\\{]*\{', re.MULTILINE)
FIELD_REGEX = re.compile(r'(?P<annotations>(?:@\w+(?:\([^)]*\))?\s*)*)(?P<modifiers>(?:public|private|protected|static|final|\s)*)\s*(?P<type>[A-Za-z0-9_<>\[\]\.? ,]+)\s+(?P<name>[A-Za-z0-9_]+)\s*(?:=.+)?;', re.MULTILINE)
CS_FIELD_REGEX = re.compile(r'(?P<attributes>(?:\[[^\]]+\]\s*)*)(?P<modifiers>(?:public|private|protected|static|readonly|\s)*)\s*(?P<type>[A-Za-z0-9_<>\[\]\.? ,]+)\s+(?P<name>[A-Za-z0-9_]+)\s*(?:\{[^\}]*\})?', re.MULTILINE)
GENERIC_LIST_REGEX = re.compile(r'(?:List|ArrayList|IList|IEnumerable|ICollection|Set|HashSet|Collection)\s*<\s*([^>]+)\s*>')
ARRAY_REGEX = re.compile(r'([A-Za-z0-9_\.]+)\s*\[\s*\]')
NOTNULL_ANNOTATIONS = {'NotNull', 'NonNull', 'NotBlank', 'NotEmpty', 'Required'}
def detect_language(text: str) -> str:
# crude detection
if re.search(r'\bnamespace\b', text) or re.search(r'\busing\s+System', text) or re.search(r'\bpublic\s+class\s+\w+\s*\{', text) and re.search(r'\{ get; set; \}', text):
return 'csharp'
return 'java'
def extract_classes(text: str) -> List[Tuple[str, str]]:
# returns list of (class_name, body_text)
classes = []
for m in CLASS_REGEX.finditer(text):
name = m.group(3)
start = m.end()
# find matching brace
depth = 1
i = start
while i < len(text) and depth > 0:
if text[i] == '{':
depth += 1
elif text[i] == '}':
depth -= 1
i += 1
body = text[start:i-1]
classes.append((name, body))
return classes
def parse_fields_java(class_body: str) -> List[Dict]:
fields = []
for m in FIELD_REGEX.finditer(class_body):
annotations = m.group('annotations').strip()
t = m.group('type').strip()
name = m.group('name').strip()
fields.append({'name': name, 'type': t, 'annotations': annotations})
# also try properties with getters/setters? skipping for brevity
return fields
def parse_fields_csharp(class_body: str) -> List[Dict]:
fields = []
for m in CS_FIELD_REGEX.finditer(class_body):
attrs = m.group('attributes').strip()
t = m.group('type').strip()
name = m.group('name').strip()
fields.append({'name': name, 'type': t, 'annotations': attrs})
return fields
def map_type(ts_type: str) -> str:
# fallback mapper invoked for nested items if it's already TS
return ts_type
def java_type_to_ts(t: str) -> str:
t = t.strip()
# arrays
ar = ARRAY_REGEX.match(t)
if ar:
inner = ar.group(1).strip()
return f"{java_type_to_ts(inner)}[]"
# generics list
gl = GENERIC_LIST_REGEX.search(t)
if gl:
inner = gl.group(1).strip()
return f"{java_type_to_ts(inner)}[]"
# Map<K,V>
if t.startswith('Map') or t.startswith('HashMap') or t.startswith('LinkedHashMap'):
inner = re.search(r'<\s*([^,>]+)\s*,\s*([^>]+)\s*>', t)
if inner:
k, v = inner.group(1).strip(), inner.group(2).strip()
return f"Record<{java_type_to_ts(k)}, {java_type_to_ts(v)}>"
return "Record<string, any>"
# simple mapping
base = re.split(r'[<\[\]\s,]', t)[0]
if base in JAVA_TO_TS:
return JAVA_TO_TS[base]
# enum/other class -> keep name
return base
def csharp_type_to_ts(t: str) -> str:
t = t.strip()
# arrays
ar = ARRAY_REGEX.match(t)
if ar:
inner = ar.group(1).strip()
return f"{csharp_type_to_ts(inner)}[]"
# generics like List<T> or Dictionary<K,V>
gl = GENERIC_LIST_REGEX.search(t)
if gl:
inner = gl.group(1).strip()
return f"{csharp_type_to_ts(inner)}[]"
if t.startswith('Dictionary') or t.startswith('IDictionary'):
inner = re.search(r'<\s*([^,>]+)\s*,\s*([^>]+)\s*>', t)
if inner:
k, v = inner.group(1).strip(), inner.group(2).strip()
return f"Record<{csharp_type_to_ts(k)}, {csharp_type_to_ts(v)}>"
return "Record<string, any>"
base = re.split(r'[<\[\]\s,]', t)[0]
if base in CSHARP_TO_TS:
return CSHARP_TO_TS[base]
return base
def is_required(field: Dict, language: str) -> bool:
anns = field.get('annotations') or ''
# if explicit notnull-like annotation
for ann in NOTNULL_ANNOTATIONS:
if re.search(r'@?' + re.escape(ann) + r'\b', anns):
return True
# Java primitive types (int, long, boolean) are required
if language == 'java':
t = field['type'].strip()
if re.match(r'^(int|long|short|double|float|boolean|char)\b', t):
return True
# wrapper classes are nullable unless annotated
return False
else:
# C# value types (int, long, bool, double, decimal, DateTime) are non-nullable unless suffixed with ?
t = field['type'].strip()
if t.endswith('?'):
return False
base = re.split(r'[<\[\]\s,]', t)[0]
if base in CSHARP_TO_TS:
return True
return False
def ts_safe_name(name: str) -> str:
return name # adapt if needed
def convert_class(name: str, body: str, language: str) -> str:
if language == 'java':
fields = parse_fields_java(body)
type_conv = java_type_to_ts
else:
fields = parse_fields_csharp(body)
type_conv = csharp_type_to_ts
lines = [f"export interface {name} {{"]
for f in fields:
raw_type = f['type']
ts_type = type_conv(raw_type)
required = is_required(f, language)
prop = ts_safe_name(f['name'])
opt = '' if required else '?'
lines.append(f" {prop}{opt}: {ts_type};")
lines.append("}")
return "\n".join(lines)
def convert_text_to_ts(text: str, prefer_interface: bool = True, use_ollama: bool = False) -> str:
language = detect_language(text)
classes = extract_classes(text)
out = []
if not classes:
# no classes found: fallback -- attempt to parse fields from top-level
if language == 'java':
fields = parse_fields_java(text)
cls = "RootDto"
body = "\n".join([f for f in fields])
out.append(convert_class(cls, text, language))
else:
out.append("// No classes detected")
return "\n\n".join(out)
for name, body in classes:
out.append(convert_class(name, body, language))
return "\n\n".join(out)