package acceptance;

import com.google.common.base.Throwables;
import com.google.common.io.Resources;
import io.digdag.cli.Main;
import io.digdag.core.Version;
import org.junit.Assert;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

import static io.digdag.core.Version.buildVersion;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;

class TestUtils
{
    static CommandStatus main(String... args)
    {
        return main(buildVersion(), args);
    }

    static CommandStatus main(Version localVersion, String... args)
    {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final ByteArrayOutputStream err = new ByteArrayOutputStream();
        final int code;
        try {
            code = new Main(localVersion, new PrintStream(out), new PrintStream(err)).cli(args);
        }
        catch (RuntimeException e) {
            e.printStackTrace();
            Assert.fail();
            throw e;
        }
        return CommandStatus.of(code, out.toByteArray(), err.toByteArray());
    }

    static void copyResource(String resource, Path dest) throws IOException
    {
        try (InputStream input = Resources.getResource(resource).openStream()) {
            Files.copy(input, dest, REPLACE_EXISTING);
        }
    }

    static void fakeHome(String home, Action a) throws Exception
    {
        String orig = System.setProperty("user.home", home);
        try {
            Files.createDirectories(Paths.get(home).resolve(".config").resolve("digdag"));
            a.run();
        }
        finally {
            System.setProperty("user.home", orig);
        }
    }
}

@@ -293,32 +293,77 @@
 io.PrintStream;%0A
+import java.io.UnsupportedEncodingException;%0A
 import java.nio.
@@ -432,49 +432,8 @@
 ths;
-%0Aimport java.nio.file.StandardCopyOption;
 %0A%0Aim
@@ -911,33 +911,33 @@
 de;%0A        try 
-%7B
+(
 %0A            cod
@@ -937,37 +937,30 @@
     
-code = new Main(localVersion,
+    PrintStream outp =
  new
@@ -979,31 +979,162 @@
 (out
-)
 , 
-new PrintStream(err)
+true, %22UTF-8%22);%0A                PrintStream errp = new PrintStream(err, true, %22UTF-8%22);%0A        ) %7B%0A            code = new Main(localVersion, outp, errp
 ).cl
@@ -1184,16 +1184,47 @@
 ception 
+%7C UnsupportedEncodingException 
 e) %7B%0A   
@@ -1298,17 +1298,39 @@
   throw 
-e
+Throwables.propagate(e)
 ;%0A      
@@ -1473,16 +1473,28 @@
 th dest)
+%0A           
  throws 
@@ -1711,16 +1711,28 @@
 ction a)
+%0A           
  throws 

fix findbugs warning