-
Notifications
You must be signed in to change notification settings - Fork 0
381 lines (319 loc) · 15.9 KB
/
sync-from-java.yml
File metadata and controls
381 lines (319 loc) · 15.9 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
name: Sync to Java Repo with Python-to-Java Translation
on:
push:
branches:
- main
paths:
- 'sync_folder/**'
workflow_dispatch:
jobs:
sync:
runs-on: ubuntu-latest
steps:
- name: Checkout Python Repo
uses: actions/checkout@v4
with:
path: python-repo
- name: Checkout Java Repo
uses: actions/checkout@v4
with:
repository: SikandarEjaz/RepoSyncTestJava
token: ${{ secrets.SYNC_TOKEN }}
path: java-repo
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Create Python-to-Java Translator using AST
run: |
cat > translator.py << 'TRANSLATOR_EOF'
import ast
import sys
class PythonToJavaTranslator(ast.NodeVisitor):
def __init__(self):
self.indent_level = 0
self.output = []
self.current_class = None
self.class_fields = set()
self.in_method = False
self.constructor_params = []
def get_indent(self):
return " " * self.indent_level
def visit_ClassDef(self, node):
self.current_class = node.name
# Check for inheritance
parent_class = ""
if node.bases:
base_name = node.bases[0]
if isinstance(base_name, ast.Name) and base_name.id != "object":
parent_class = f" extends {base_name.id}"
self.output.append(f"public class {node.name}{parent_class} {{")
self.indent_level += 1
# First pass: collect fields from __init__
for item in node.body:
if isinstance(item, ast.FunctionDef) and item.name == "__init__":
self.collect_fields(item)
# Add field declarations
if self.class_fields:
for field in sorted(self.class_fields):
self.output.append(f"{self.get_indent()}private String {field};")
self.output.append("")
# Visit all methods
for item in node.body:
self.visit(item)
self.indent_level -= 1
self.output.append("}")
self.output.append("")
def collect_fields(self, node):
"""Collect field names from __init__ method"""
for stmt in node.body:
if isinstance(stmt, ast.Assign):
for target in stmt.targets:
if isinstance(target, ast.Attribute):
if isinstance(target.value, ast.Name) and target.value.id == "self":
self.class_fields.add(target.attr)
def visit_FunctionDef(self, node):
self.in_method = True
method_name = node.name
# Get parameters (skip 'self')
params = [arg.arg for arg in node.args.args if arg.arg != "self"]
if method_name == "__init__":
# Constructor
self.constructor_params = params
params_str = ", ".join([f"String {p}" for p in params])
self.output.append(f"{self.get_indent()}public {self.current_class}({params_str}) {{")
self.indent_level += 1
# Visit body
for stmt in node.body:
self.visit(stmt)
self.indent_level -= 1
self.output.append(f"{self.get_indent()}}}")
self.output.append("")
else:
# Regular method
params_str = ", ".join([f"String {p}" for p in params])
# Determine return type
return_type = self.get_return_type(node)
self.output.append(f"{self.get_indent()}public {return_type} {method_name}({params_str}) {{")
self.indent_level += 1
# Visit body
for stmt in node.body:
self.visit(stmt)
self.indent_level -= 1
self.output.append(f"{self.get_indent()}}}")
self.output.append("")
self.in_method = False
def get_return_type(self, func_node):
"""Determine return type from function body"""
for stmt in ast.walk(func_node):
if isinstance(stmt, ast.Return):
if stmt.value:
if isinstance(stmt.value, ast.Constant):
if isinstance(stmt.value.value, bool):
return "boolean"
elif isinstance(stmt.value.value, int):
return "int"
elif isinstance(stmt.value.value, str):
return "String"
elif isinstance(stmt.value, ast.Name):
if stmt.value.id in ["True", "False"]:
return "boolean"
return "String"
return "void"
def visit_Assign(self, node):
"""Handle assignments"""
if not self.in_method:
return
for target in node.targets:
if isinstance(target, ast.Attribute):
# self.field = value
if isinstance(target.value, ast.Name) and target.value.id == "self":
field_name = target.attr
value = self.convert_expr(node.value)
self.output.append(f"{self.get_indent()}this.{field_name} = {value};")
elif isinstance(target, ast.Name):
# Local variable
var_name = target.id
value = self.convert_expr(node.value)
self.output.append(f"{self.get_indent()}String {var_name} = {value};")
def visit_Return(self, node):
"""Handle return statements"""
if node.value:
value = self.convert_expr(node.value)
self.output.append(f"{self.get_indent()}return {value};")
else:
self.output.append(f"{self.get_indent()}return;")
def visit_If(self, node):
"""Handle if statements"""
condition = self.convert_expr(node.test)
self.output.append(f"{self.get_indent()}if ({condition}) {{")
self.indent_level += 1
for stmt in node.body:
self.visit(stmt)
self.indent_level -= 1
self.output.append(f"{self.get_indent()}}}")
# Handle else
if node.orelse:
self.output.append(f"{self.get_indent()}else {{")
self.indent_level += 1
for stmt in node.orelse:
self.visit(stmt)
self.indent_level -= 1
self.output.append(f"{self.get_indent()}}}")
def visit_Expr(self, node):
"""Handle expression statements (like print calls)"""
if isinstance(node.value, ast.Call):
if isinstance(node.value.func, ast.Name) and node.value.func.id == "print":
# Handle print
args = [self.convert_expr(arg) for arg in node.value.args]
args_str = " + ".join(args)
self.output.append(f"{self.get_indent()}System.out.println({args_str});")
def convert_expr(self, expr):
"""Convert Python expression to Java"""
if isinstance(expr, ast.Constant):
value = expr.value
if isinstance(value, bool):
return "true" if value else "false"
elif isinstance(value, str):
return f'"{value}"'
else:
return str(value)
elif isinstance(expr, ast.Name):
name = expr.id
if name in ["True", "False"]:
return name.lower()
return name
elif isinstance(expr, ast.Attribute):
if isinstance(expr.value, ast.Name) and expr.value.id == "self":
return f"this.{expr.attr}"
return f"{self.convert_expr(expr.value)}.{expr.attr}"
elif isinstance(expr, ast.BinOp):
left = self.convert_expr(expr.left)
right = self.convert_expr(expr.right)
op = self.convert_op(expr.op)
return f"{left} {op} {right}"
elif isinstance(expr, ast.Compare):
left = self.convert_expr(expr.left)
comparators = [self.convert_expr(c) for c in expr.comparators]
ops = [self.convert_compare_op(op) for op in expr.ops]
result = left
for op, comp in zip(ops, comparators):
result += f" {op} {comp}"
return result
elif isinstance(expr, ast.JoinedStr):
# f-string
parts = []
for value in expr.values:
if isinstance(value, ast.Constant):
parts.append(f'"{value.value}"')
elif isinstance(value, ast.FormattedValue):
parts.append(self.convert_expr(value.value))
return " + ".join(parts)
elif isinstance(expr, ast.Call):
# Method call
if isinstance(expr.func, ast.Attribute):
obj = self.convert_expr(expr.func.value)
method = expr.func.attr
args = [self.convert_expr(arg) for arg in expr.args]
args_str = ", ".join(args)
return f"{obj}.{method}({args_str})"
return "null"
def convert_op(self, op):
"""Convert binary operators"""
op_map = {
ast.Add: "+",
ast.Sub: "-",
ast.Mult: "*",
ast.Div: "/",
ast.Mod: "%",
}
return op_map.get(type(op), "+")
def convert_compare_op(self, op):
"""Convert comparison operators"""
op_map = {
ast.Eq: "==",
ast.NotEq: "!=",
ast.Lt: "<",
ast.LtE: "<=",
ast.Gt: ">",
ast.GtE: ">=",
}
return op_map.get(type(op), "==")
def get_java_code(self):
return "\n".join(self.output)
def translate_python_to_java(python_file_path):
with open(python_file_path, 'r', encoding='utf-8') as f:
python_code = f.read()
tree = ast.parse(python_code)
translator = PythonToJavaTranslator()
translator.visit(tree)
return translator.get_java_code()
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python translator.py <input_python_file> <output_java_file>")
sys.exit(1)
input_file = sys.argv[1]
output_file = sys.argv[2]
try:
java_code = translate_python_to_java(input_file)
with open(output_file, 'w', encoding='utf-8') as f:
f.write(java_code)
print(f"Successfully translated {input_file} to {output_file}")
print(f"\nGenerated Java code preview:")
print("-" * 50)
print(java_code[:800])
print("-" * 50)
except Exception as e:
print(f"Translation error: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
TRANSLATOR_EOF
- name: Translate Python files to Java
run: |
mkdir -p java-repo/synced-from-python
# Find all Python files in sync_folder
find python-repo/sync_folder -name "*.py" -type f | while read python_file; do
# Skip __pycache__ and __init__ files
if [[ "$python_file" == *"__pycache__"* ]] || [[ "$python_file" == *"__init__.py" ]]; then
echo "Skipping: $python_file"
continue
fi
# Get relative path and convert to Java filename
rel_path=$(realpath --relative-to=python-repo/sync_folder "$python_file")
java_file="java-repo/synced-from-python/${rel_path%.py}.java"
# Create directory if needed
mkdir -p "$(dirname "$java_file")"
# Translate
echo "========================================="
echo "Translating: $python_file"
echo " to: $java_file"
echo "========================================="
if python translator.py "$python_file" "$java_file"; then
echo "Translation successful"
echo "File size: $(wc -c < "$java_file") bytes"
ls -lh "$java_file"
else
echo "Translation failed for $python_file"
fi
echo ""
done
# Show what was created
echo "=== Contents of synced-from-python ==="
find java-repo/synced-from-python -type f -exec echo "File: {}" \; -exec head -20 {} \; -exec echo "---" \;
- name: Commit and Push to Java Repo
run: |
cd java-repo
git config user.name "GitHub Action"
git config user.email "action@github.com"
git add .
# Check if there are changes
if git diff --staged --quiet; then
echo "No changes to commit"
else
echo "Changes detected, committing..."
git status
git commit -m "Sync from Python repo with translation [automated]"
git push
echo "Changes pushed successfully"
fi