package com.github.blindpirate.gogradle.util;


import com.google.common.collect.Lists;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class ProcessUtils {
    public static class ProcessResult {
        private int code;
        private String stdout;
        private String stderr;

        public int getCode() {
            return code;
        }

        public String getStdout() {
            return stdout;
        }

        public String getStderr() {
            return stderr;
        }

        public ProcessResult(Process process) throws InterruptedException {
            code = process.waitFor();
            stdout = IOUtils.toString(process.getInputStream());
            stderr = IOUtils.toString(process.getErrorStream());
        }
    }

    public static ProcessResult run(List<String> args, Map<String, String> envs)
            throws IOException, InterruptedException {
        ProcessBuilder pb = new ProcessBuilder().command(args);
        pb.environment().putAll(envs);
        Process process = pb.start();
        return new ProcessResult(process);
    }


    public static ProcessResult runProcessWithCurrentClasspath(Class mainClass,
                                                               List<String> args,
                                                               Map<String, String> envs) {
        String currentClasspath = System.getProperty("java.class.path");

        List<String> cmds = Lists.newArrayList("java", "-cp", currentClasspath, mainClass.getName());
        cmds.addAll(args);
        try {
            return run(cmds, envs);
        } catch (IOException | InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }
}

@@ -82,16 +82,37 @@
 Lists;%0A%0A
+import java.io.File;%0A
 import j
@@ -131,16 +131,16 @@
 eption;%0A
-
 import j
@@ -890,16 +890,18 @@
 g%3E envs)
+ %7B
 %0A       
@@ -905,55 +905,169 @@
     
-    throws IOException, InterruptedException %7B%0A
+return run(args, envs, null);%0A    %7D%0A%0A    public static ProcessResult run(List%3CString%3E args, Map%3CString, String%3E envs, File workingDirectory) %7B%0A        try %7B%0A    
     
@@ -1134,16 +1134,20 @@
         
+    
 pb.envir
@@ -1165,24 +1165,134 @@
 tAll(envs);%0A
+            if (workingDirectory != null) %7B%0A                pb.directory(workingDirectory);%0A            %7D%0A    
         Proc
@@ -1321,24 +1321,28 @@
 ();%0A        
+   
+ 
 return new P
@@ -1360,24 +1360,147 @@
 t(process);%0A
+        %7D catch (IOException %7C InterruptedException e) %7B%0A            throw ExceptionHandler.uncheckException(e);%0A        %7D%0A
     %7D%0A%0A%0A    
@@ -1951,34 +1951,16 @@
 (args);%0A
-        try %7B%0A    
         
@@ -1987,123 +1987,8 @@
 s);%0A
-        %7D catch (IOException %7C InterruptedException e) %7B%0A            throw new IllegalStateException(e);%0A        %7D%0A
     

support changing work directory of process