Skip to content

Commit 78f0df9

Browse files
author
=
committed
feat(app): create first release for app v1.0.0
1 parent e26c87c commit 78f0df9

File tree

8 files changed

+1041
-1
lines changed

8 files changed

+1041
-1
lines changed

.gitignore

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,4 +36,11 @@ build/
3636
.vscode/
3737

3838
### Mac OS ###
39-
.DS_Store
39+
.DS_Store
40+
41+
dependency-reduced-pom.xml
42+
python-envs.properties
43+
.venvs/
44+
.venv/
45+
venvs/
46+
venv/

pom.xml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@
2727
</dependencies>
2828

2929
<build>
30+
<finalName>${project.artifactId}</finalName>
31+
3032
<plugins>
3133

3234
<plugin>
Lines changed: 311 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,311 @@
1+
package com.alexdevzz.pythonrunner;
2+
3+
import com.alexdevzz.pythonrunner.cli.CommandLineArgs;
4+
import com.alexdevzz.pythonrunner.core.ExecutionResult;
5+
import com.alexdevzz.pythonrunner.core.PythonRunner;
6+
import com.alexdevzz.pythonrunner.core.PythonService;
7+
8+
import java.io.IOException;
9+
import java.io.File;
10+
import java.nio.file.Files;
11+
import java.nio.file.Path;
12+
import java.nio.file.Paths;
13+
import java.util.Arrays;
14+
import java.util.Map;
15+
16+
public class Main {
17+
18+
private static final String APP_NAME = "Java Python Executor";
19+
private static final String VERSION = "1.0.0";
20+
21+
/**
22+
* Entrada de la aplicación (Main)
23+
* @param args
24+
*/
25+
public static void main(String[] args) {
26+
27+
System.out.println(APP_NAME + " v" + VERSION + "\n");
28+
29+
CommandLineArgs cli = CommandLineArgs.parse(args);
30+
31+
// mostrar la ayuda
32+
if (cli.isHelpRequested() || (args.length == 0 && !cli.hasScript())) {
33+
printHelp();
34+
System.exit(0);
35+
}
36+
37+
// mostrar la lista de entornos virtuales
38+
if (cli.isListEnvs()) {
39+
listEnvironments();
40+
System.exit(0);
41+
}
42+
43+
// crear entorno virtual de python
44+
if (cli.isCreateEnv()) {
45+
createEnvironment(cli);
46+
System.exit(0);
47+
}
48+
49+
if (cli.hasScript()) {
50+
executeScript(cli);
51+
} else {
52+
System.err.println("Error: No se especificó script Python a ejecutar.");
53+
printUsage();
54+
System.exit(1);
55+
}
56+
}
57+
58+
59+
60+
/**
61+
* Imprimir el resultado del script
62+
* @param result Resultado de ejecución
63+
*/
64+
private static void printResult(ExecutionResult result) {
65+
System.out.println("\n" + "═".repeat(60));
66+
System.out.println("📊 RESULTADO DE EJECUCIÓN");
67+
System.out.println("═".repeat(60));
68+
69+
System.out.println("✅ Código de salida: " + result.getExitCode());
70+
System.out.println("📈 Estado: " + (result.isSuccess() ? "ÉXITO" : "FALLÓ"));
71+
72+
if (!result.getOutput().isEmpty()) {
73+
System.out.println("\n📤 SALIDA DEL SCRIPT:");
74+
System.out.println("-".repeat(40));
75+
result.getOutput().forEach(line -> {
76+
if (line.startsWith("ERROR") || line.startsWith("Error") ||
77+
line.contains("Traceback")) {
78+
System.err.println(line);
79+
} else {
80+
System.out.println(line);
81+
}
82+
});
83+
}
84+
85+
if (!result.getErrors().isEmpty()) {
86+
System.out.println("\n❌ ERRORES DEL SISTEMA:");
87+
System.out.println("-".repeat(40));
88+
result.getErrors().forEach(System.err::println);
89+
}
90+
91+
System.out.println("═".repeat(60));
92+
}
93+
94+
/**
95+
* Verifica si el archivo cumple con todas las condiciones para ser ejecutado
96+
* @param filePath Ruta del archivo
97+
* @return True si el archivo es válido
98+
*/
99+
private static boolean isReadyToRun(String filePath) {
100+
if (filePath == null || filePath.trim().isEmpty()) {
101+
System.err.println("The path file cannot be empty or null");
102+
return false;
103+
}
104+
105+
Path path = Paths.get(filePath);
106+
107+
// verify is file exist
108+
if (!Files.exists(path)) {
109+
System.out.println("File not found: " + filePath);
110+
return false;
111+
}
112+
113+
// verify if it is a regular file (not directory)
114+
if (!Files.isRegularFile(path)) {
115+
System.out.println("The path file is not regular path (maybe directory path): " + filePath);
116+
return false;
117+
}
118+
119+
// verify read permissions
120+
if (!Files.isReadable(path)) {
121+
System.out.println("Do not have read permissions: " + filePath);
122+
return false;
123+
}
124+
125+
// verify .py extension
126+
String fileName = path.getFileName().toString();
127+
if (!fileName.endsWith(".py")) {
128+
return false;
129+
}
130+
131+
// verify if the file is not empty (optional)
132+
try {
133+
if (Files.size(path) == 0) {
134+
System.out.println("WANING: File is empty: " + filePath);
135+
// not return false, only warning
136+
}
137+
} catch (IOException e) {
138+
System.err.println("Error to verify file size: " + e.getMessage());
139+
}
140+
141+
return true;
142+
}
143+
144+
145+
/**
146+
* Imprimir ayuda
147+
*/
148+
private static void printHelp() {
149+
System.out.println("📚 " + APP_NAME + " - Ejecutor de scripts Python desde Java\n");
150+
printUsage();
151+
152+
System.out.println("\n📋 OPCIONES DISPONIBLES:");
153+
System.out.println(" script.py Script Python a ejecutar (obligatorio para ejecución)");
154+
System.out.println(" [arg1 arg2 ...] Argumentos para el script Python");
155+
System.out.println(" -v, --venv RUTA Usar entorno virtual en la RUTA especificada");
156+
System.out.println(" -l, --list-envs Listar entornos virtuales configurados");
157+
System.out.println(" -c, --create-env NOMBRE Crear nuevo entorno virtual");
158+
System.out.println(" --python VERS Versión de Python (ej: 3, 3.9)");
159+
System.out.println(" --install PKG... Instalar paquetes al crear entorno");
160+
System.out.println(" -h, --help Mostrar esta ayuda");
161+
162+
System.out.println("\n🔧 SEPARADOR DE ARGUMENTOS:");
163+
System.out.println(" -- Separa argumentos de Java de los de Python");
164+
System.out.println(" Ej: app.jar script.py --venv myenv -- arg1 arg2");
165+
166+
System.out.println("\n💡 EJEMPLOS DE USO:");
167+
System.out.println(" Ejecutar script sin entorno virtual:");
168+
System.out.println(" java -jar app.jar \"C:\\scripts\\mi_script.py\" \"param1\" \"param2\"");
169+
System.out.println("");
170+
System.out.println(" Ejecutar script con entorno virtual:");
171+
System.out.println(" java -jar app.jar \"C:\\scripts\\horoscope.py\" \"aries\" --venv \"C:\\venvs\\horoscope_venv\"");
172+
System.out.println("");
173+
System.out.println(" Crear entorno virtual con paquetes:");
174+
System.out.println(" java -jar app.jar --create-env data-science --python 3.9 --install numpy pandas matplotlib");
175+
System.out.println("");
176+
System.out.println(" Listar entornos:");
177+
System.out.println(" java -jar app.jar --list-envs");
178+
}
179+
180+
/**
181+
* Imprimir el uso
182+
*/
183+
private static void printUsage() {
184+
System.out.println("📖 USO:");
185+
System.out.println(" java -jar java-python-executor.jar [OPCIONES] script.py [ARG_PYTHON...]");
186+
System.out.println("");
187+
System.out.println(" Ejemplo básico:");
188+
System.out.println(" java -jar app.jar script.py arg1 arg2");
189+
System.out.println("");
190+
System.out.println(" Con entorno virtual:");
191+
System.out.println(" java -jar app.jar script.py arg1 --venv /ruta/venv arg2");
192+
}
193+
194+
/**
195+
* Listar entornos virtuales guardados
196+
*/
197+
private static void listEnvironments() {
198+
System.out.println("📋 ENTORNOS VIRTUALES CONFIGURADOS\n");
199+
200+
PythonService service = new PythonService();
201+
Map<String, String> envs = service.listVenvs();
202+
203+
if (envs.isEmpty()) {
204+
System.out.println("No hay entornos configurados.");
205+
System.out.println("Usa: java -jar app.jar --create-env <nombre>");
206+
return;
207+
}
208+
209+
System.out.printf("%-20s %-40s %s%n", "Nombre", "Ruta", "Estado");
210+
System.out.println("-".repeat(70));
211+
212+
envs.forEach((name, path) -> {
213+
boolean valid = service.validateVenv(name);
214+
String status = valid ? "✅ VÁLIDO" : "❌ NO VÁLIDO";
215+
System.out.printf("%-20s %-40s %s%n", name, path, status);
216+
});
217+
}
218+
219+
/**
220+
* Crear entorno virtual
221+
* @param cli Objeto del tipo {@code CommandLineArgs}
222+
*/
223+
private static void createEnvironment(CommandLineArgs cli) {
224+
if (cli.getEnvName() == null) {
225+
System.err.println("Error: Debes especificar un nombre para el entorno.");
226+
System.out.println("Uso: --create-env <nombre> [--python <version>] [--install pkg1 pkg2]");
227+
System.exit(1);
228+
}
229+
230+
System.out.println("🛠️ CREANDO ENTORNO VIRTUAL: " + cli.getEnvName() + "\n");
231+
232+
PythonService service = new PythonService();
233+
234+
String pythonVersion = cli.getPythonVersion() != null ?
235+
cli.getPythonVersion() : "3";
236+
237+
String[] packages = cli.getPackages().toArray(new String[0]);
238+
239+
ExecutionResult result = service.setupVenv(
240+
cli.getEnvName(),
241+
"venvs", // Directorio base relativo
242+
pythonVersion,
243+
packages
244+
);
245+
246+
printResult(result);
247+
248+
if (result.isSuccess()) {
249+
System.out.println("\n🎉 Entorno creado exitosamente!");
250+
System.out.println("Para usarlo:");
251+
System.out.println(" java -jar app.jar script.py --venv venvs/" + cli.getEnvName());
252+
}
253+
}
254+
255+
/**
256+
* Ejecutar el script de python
257+
* @param cli Objeto del tipo {@code CommandLineArgs}
258+
*/
259+
private static void executeScript(CommandLineArgs cli) {
260+
System.out.println("╔══════════════════════════════════════════════════════╗");
261+
System.out.println("║ EJECUTANDO SCRIPT PYTHON ║");
262+
System.out.println("╚══════════════════════════════════════════════════════╝\n");
263+
264+
File scriptFile = new File(cli.getScriptPath());
265+
266+
if (!scriptFile.exists()) {
267+
System.err.println("❌ Error: Script no encontrado: " + cli.getScriptPath());
268+
System.exit(1);
269+
}
270+
271+
if (!scriptFile.getName().endsWith(".py")) {
272+
System.err.println("⚠️ Advertencia: El archivo no parece ser un script Python (.py)");
273+
}
274+
275+
// Mostrar información de la ejecución
276+
System.out.println("📄 Script: " + scriptFile.getAbsolutePath());
277+
System.out.println("📂 Directorio: " + scriptFile.getParent());
278+
System.out.println("🔧 Argumentos para Python: " + cli.getScriptArgs());
279+
280+
PythonRunner runner = new PythonRunner();
281+
282+
try {
283+
ExecutionResult result;
284+
285+
if (cli.hasVenv()) {
286+
System.out.println("🐍 Entorno virtual: " + cli.getVenvPath());
287+
result = runner.runPythonScriptWithVenv(
288+
cli.getVenvPath(),
289+
scriptFile.getAbsolutePath(),
290+
cli.getScriptArgs()
291+
);
292+
} else {
293+
System.out.println("🐍 Usando Python del sistema");
294+
result = runner.runPythonScript(
295+
scriptFile.getAbsolutePath(),
296+
cli.getScriptArgs()
297+
);
298+
}
299+
300+
printResult(result);
301+
302+
// Código de salida apropiado
303+
System.exit(result.getExitCode());
304+
305+
} catch (Exception e) {
306+
System.err.println("💥 Error crítico: " + e.getMessage());
307+
e.printStackTrace();
308+
System.exit(1);
309+
}
310+
}
311+
}

0 commit comments

Comments
 (0)