package org.sugarj.cleardep.xattr;

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

import org.sugarj.common.CommandExecution;
import org.sugarj.common.path.Path;

public class XattrCommandStrategy implements XattrStrategy {

  CommandExecution exec = new CommandExecution(true);
  
  @Override
  public void setXattr(Path p, String key, String value) throws IOException {
    try {
      exec.execute("xattr", "-w", Xattr.PREFIX + ":" + key, value, p.getAbsolutePath());
    } catch (CommandExecution.ExecutionError e) {
      throw new IOException(e);
    }
  }
  
  @Override
  public void removeXattr(Path p, String key) throws IOException {
    try {
      exec.execute("xattr", "-d", Xattr.PREFIX + ":" + key, p.getAbsolutePath());
    } catch (CommandExecution.ExecutionError e) {
      throw new IOException(e);
    }
  }

  @Override
  public String getXattr(Path p, String key) throws IOException {
    try {
      String[][] out = exec.execute("xattr", "-p", Xattr.PREFIX + ":" + key, p.getAbsolutePath());
      if (out[0].length > 0)
        return out[0][0];
      return null;
    } catch (CommandExecution.ExecutionError e) {
      return null;
    }
  }

  @Override
  public Map<String, String> getAllXattr(Path p) throws IOException {
    try {
      String[][] out = exec.execute("xattr", "-l", p.getAbsolutePath());
      
      Map<String, String> attrs = new HashMap<>();
      for (String line : out[0]) {
        int split = line.indexOf(": ");
        String key = line.substring(0, split);
        String val = line.substring(split + ": ".length());
        attrs.put(key, val);
      }
      return attrs;
    } catch (CommandExecution.ExecutionError e) {
      return null;
    }
  }

}

@@ -131,32 +131,20 @@
 .common.
-CommandExecution
+Exec
 ;%0Aimport
@@ -242,52 +242,28 @@
 %0A%0A  
-CommandExecution exec = new CommandExecution
+Exec exec = new Exec
 (tru
@@ -376,35 +376,32 @@
 %0A      exec.exec
-ute
 (%22xattr%22, %22-w%22, 
@@ -468,32 +468,20 @@
  catch (
-CommandExecution
+Exec
 .Executi
@@ -634,35 +634,32 @@
 %0A      exec.exec
-ute
 (%22xattr%22, %22-d%22, 
@@ -719,32 +719,20 @@
  catch (
-CommandExecution
+Exec
 .Executi
@@ -877,34 +877,44 @@
 try %7B%0A      
-String%5B%5D%5B%5D
+Exec.ExecutionResult
  out = exec.
@@ -909,35 +909,32 @@
  out = exec.exec
-ute
 (%22xattr%22, %22-p%22, 
@@ -991,105 +991,48 @@
     
-if (out%5B0%5D.length %3E 0)%0A        return out%5B0%5D%5B0%5D;%0A      return null;%0A    %7D catch (CommandExecution
+return out.outMsgs%5B0%5D;%0A    %7D catch (Exec
 .Exe
@@ -1180,18 +1180,28 @@
     
-String%5B%5D%5B%5D
+Exec.ExecutionResult
  out
@@ -1212,19 +1212,16 @@
 xec.exec
-ute
 (%22xattr%22
@@ -1336,19 +1336,24 @@
 ne : out
-%5B0%5D
+.outMsgs
 ) %7B%0A    
@@ -1569,24 +1569,12 @@
 ch (
-CommandExecution
+Exec
 .Exe

improve CommandExecution