package com.ruyi.cache.test3;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;
public class SimpleQoderCliExecutor {
public static String generateUserProspectSaveExample(String workingDirectory) {
try {
String command = "qodercli --print --output-format=json -p \"介绍一下项目结构\"";
//String command = "where qodercli && echo --- && qodercli --version";
System.out.println("⏳ 开始执行命令(可能需要10-30秒): " + command);
System.out.println("📂 工作目录: " + workingDirectory);
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", command);
pb.directory(new File(workingDirectory));
pb.environment().putAll(System.getenv());
pb.redirectErrorStream(true); // 合并错误流
pb.environment().put("FORCE_COLOR", "0");
pb.environment().put("NODE_OPTIONS", "--no-warnings");
Process process = pb.start();
// 📥 实时读取输出(关键!必须在 waitFor 前开始读)
StringBuilder output = new StringBuilder();
Thread readerThread = new Thread(() -> {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream(), "GBK"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println("📤 实时输出: " + line); // 立即看到进展
output.append(line).append("\n");
}
} catch (Exception e) {
e.printStackTrace();
}
});
readerThread.start();
// ⏱️ 设置足够长的超时(比如 120 秒)
boolean finished = process.waitFor(120, TimeUnit.SECONDS);
if (!finished) {
process.destroyForcibly();
throw new RuntimeException("❌ 命令执行超时(超过120秒)");
}
// 等待读取线程完成
readerThread.join(5000); // 最多再等5秒收尾
int exitCode = process.exitValue();
System.out.println("✅ 命令执行完成,退出码: " + exitCode);
if (exitCode != 0) {
throw new RuntimeException("❌ 命令执行失败,退出码: " + exitCode);
}
return output.toString().trim();
} catch (Exception e) {
throw new RuntimeException("💥 执行命令时发生错误: " + e.getMessage(), e);
}
}
public static void main(String[] args) {
try {
String workingDirectory = "E:\\wuzu\\mall";
String result = generateUserProspectSaveExample(workingDirectory);
System.out.println("\n✅ 最终结果:");
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
通过代码从未得到结果