001 package org.fusesource.hawtjni.maven; 002 003 import java.io.File; 004 import java.util.List; 005 import java.util.regex.Pattern; 006 007 import org.apache.maven.plugin.logging.Log; 008 import org.codehaus.plexus.util.cli.CommandLineException; 009 import org.codehaus.plexus.util.cli.CommandLineUtils; 010 import org.codehaus.plexus.util.cli.Commandline; 011 import org.codehaus.plexus.util.cli.StreamConsumer; 012 import org.codehaus.plexus.util.cli.CommandLineUtils.StringStreamConsumer; 013 014 public class CLI { 015 016 public static final boolean IS_WINDOWS = isWindows(); 017 018 static private boolean isWindows() { 019 String name = System.getProperty("os.name").toLowerCase().trim(); 020 return name.startsWith("win"); 021 } 022 023 public boolean verbose; 024 public Log log; 025 026 027 public void setExecutable(File path) { 028 if( IS_WINDOWS ) { 029 return; 030 } 031 try { 032 // These are Java 1.6 Methods.. 033 if( !path.canExecute() ) { 034 path.setExecutable(true); 035 } 036 } catch (NoSuchMethodError e1) { 037 // Do it the old fasioned way... 038 try { 039 system(path.getParentFile(), new String[] { "chmod", "a+x", path.getCanonicalPath() }); 040 } catch (Throwable e2) { 041 } 042 } 043 } 044 045 public int system(File wd, String[] command) throws CommandLineException { 046 return system(wd, command, null); 047 } 048 049 public int system(File wd, String[] command, List<String> args) throws CommandLineException { 050 Commandline cli = new Commandline(); 051 cli.setWorkingDirectory(wd); 052 for (String c : command) { 053 cli.createArg().setValue(c); 054 } 055 if( args!=null ) { 056 for (String arg : args) { 057 cli.createArg().setValue(arg); 058 } 059 } 060 log.info("executing: "+cli); 061 062 StreamConsumer consumer = new StreamConsumer() { 063 public void consumeLine(String line) { 064 log.info(line); 065 } 066 }; 067 if( !verbose ) { 068 consumer = new StringStreamConsumer(); 069 } 070 int rc = CommandLineUtils.executeCommandLine(cli, null, consumer, consumer); 071 if( rc!=0 ) { 072 if( !verbose ) { 073 // We only display output if the command fails.. 074 String output = ((StringStreamConsumer)consumer).getOutput(); 075 if( output.length()>0 ) { 076 String nl = System.getProperty( "line.separator"); 077 String[] lines = output.split(Pattern.quote(nl)); 078 for (String line : lines) { 079 log.info(line); 080 } 081 } 082 } 083 log.info("rc: "+rc); 084 } else { 085 if( !verbose ) { 086 String output = ((StringStreamConsumer)consumer).getOutput(); 087 if( output.length()>0 ) { 088 String nl = System.getProperty( "line.separator"); 089 String[] lines = output.split(Pattern.quote(nl)); 090 for (String line : lines) { 091 log.debug(line); 092 } 093 } 094 } 095 log.debug("rc: "+rc); 096 } 097 return rc; 098 } 099 100 }