package fr.monlouyan.bakefile; import java.io.IOException; public class CommandExecutor { private boolean debug; private boolean needsUpdate = false; // Pour tracker si quelque chose doit être mis à jour private boolean isCircular = false; // Pour tracker si un cycle a été détecté public CommandExecutor(boolean debug, boolean isCircular) { this.debug = debug; this.isCircular = isCircular; } public void execute(Rule rule) { if (rule.getCommands().isEmpty()) { System.out.println("bake: Nothing to be done for '" + rule.getName() + "'."); return; } // On vérifie d'abord si cette règle a besoin d'être mise à jour boolean ruleNeedsUpdate = rule.needsUpdate(); if (ruleNeedsUpdate) { needsUpdate = true; // Au moins une règle doit être mise à jour } for (String command : rule.getCommands()) { if (isCircular){ System.out.println(command); } // Mais on n'exécute que si nécessaire if (ruleNeedsUpdate) { try { if(!isCircular){ System.out.println(command); } if (debug) System.out.println("Debug: Executing " + command); ProcessBuilder pb = new ProcessBuilder("sh", "-c", command); Process process = pb.start(); // Lire et afficher la sortie standard (stdout) new Thread(() -> { try (var reader = new java.io.BufferedReader(new java.io.InputStreamReader(process.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } }).start(); // Lire et afficher la sortie d'erreur (stderr) new Thread(() -> { try (var reader = new java.io.BufferedReader(new java.io.InputStreamReader(process.getErrorStream()))) { String line; while ((line = reader.readLine()) != null) { System.err.println(line); } } catch (IOException e) { e.printStackTrace(); } }).start(); // Attendre la fin du processus int exitCode = process.waitFor(); if (exitCode != 0) { System.err.println("bake: *** [" + rule.getName() + "] Error " + exitCode); System.exit(exitCode); } } catch (IOException | InterruptedException e) { e.printStackTrace(); System.exit(1); } } } // On affiche "up to date" seulement après avoir traité TOUTES les règles // et seulement si AUCUNE règle n'avait besoin d'être mise à jour if (rule.getName().equals(BakefileParser.getFirstTarget()) && !needsUpdate) { System.out.println("bake: `" + rule.getName() + "' is up to date."); } } }