package shop.alien.util.common;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 命令行工具类
 *
 * @author ssk
 * @version 1.0
 * @date 2025/6/11 9:30
 */
@Slf4j
public class CommendUtil {

    public static void main(String[] args) {
        String commendInfo = getCommendInfo("C:\\Users\\PC\\Desktop\\GitCommitVersion.bat");
        String[] split = commendInfo.split(",");
        String lastLine = split[split.length - 1];
        System.out.println(lastLine);
    }

    public static String getCommendInfo(String commendContent) {
        try {
            StringBuilder stringBuilder = new StringBuilder();
            ProcessBuilder processBuilder = new ProcessBuilder(commendContent);
            Process process = processBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line).append(",");
            }
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                StringBuilder errorMessage = new StringBuilder();
                String errorLine;
                while ((errorLine = errorReader.readLine()) != null) {
                    errorMessage.append(errorLine).append(",");
                }
                throw new IOException("命令执行失败，退出码: " + exitCode + ", 错误信息: " + errorMessage);
            }
            return stringBuilder.toString().trim();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
