blob: 19c1a2130610138ed01cdc18bc875c901bc77c1b [file] [log] [blame]
Stuart McCulloch39cc9ac2012-07-16 13:43:38 +00001package aQute.bnd.osgi;
Stuart McCullochbb014372012-06-07 21:57:32 +00002
3import java.io.*;
4
5import aQute.libg.command.*;
6
7public class CommandResource extends WriteResource {
Stuart McCulloch2286f232012-06-15 13:27:53 +00008 final long lastModified;
9 final Builder domain;
10 final String command;
Stuart McCullochb215bfd2012-09-06 18:28:06 +000011 final File wd;
Stuart McCulloch2286f232012-06-15 13:27:53 +000012
Stuart McCullochb215bfd2012-09-06 18:28:06 +000013 public CommandResource(String command, Builder domain, long lastModified, File wd) {
Stuart McCullochbb014372012-06-07 21:57:32 +000014 this.lastModified = lastModified;
15 this.domain = domain;
16 this.command = command;
Stuart McCullochb215bfd2012-09-06 18:28:06 +000017 this.wd = wd;
Stuart McCullochbb014372012-06-07 21:57:32 +000018 }
19
20 @Override
21 public void write(OutputStream out) throws IOException, Exception {
22 StringBuilder errors = new StringBuilder();
23 StringBuilder stdout = new StringBuilder();
Stuart McCullochbb014372012-06-07 21:57:32 +000024 domain.trace("executing command %s", command);
Stuart McCulloch2286f232012-06-15 13:27:53 +000025 Command cmd = new Command("sh");
Stuart McCullochb215bfd2012-09-06 18:28:06 +000026 cmd.setCwd(wd);
Stuart McCullochbb014372012-06-07 21:57:32 +000027 cmd.inherit();
28 String oldpath = cmd.var("PATH");
Stuart McCulloch2286f232012-06-15 13:27:53 +000029
Stuart McCullochbb014372012-06-07 21:57:32 +000030 String path = domain.getProperty("-PATH");
31 if (path != null) {
Stuart McCulloch2286f232012-06-15 13:27:53 +000032 path = path.replaceAll("\\s*,\\s*", File.pathSeparator);
Stuart McCullochbb014372012-06-07 21:57:32 +000033 path = path.replaceAll("\\$\\{@\\}", oldpath);
34 cmd.var("PATH", path);
35 domain.trace("PATH: %s", path);
36 }
Stuart McCullochd4826102012-06-26 16:34:24 +000037 OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
Stuart McCulloch2286f232012-06-15 13:27:53 +000038 int result = cmd.execute(command, stdout, errors);
Stuart McCullochbb014372012-06-07 21:57:32 +000039 osw.append(stdout);
40 osw.flush();
Stuart McCulloch2286f232012-06-15 13:27:53 +000041 if (result != 0) {
Stuart McCullochec47fe72012-09-19 12:56:05 +000042 throw new Exception("executing command failed" + command + "\n"+ stdout + "\n" + errors);
Stuart McCullochbb014372012-06-07 21:57:32 +000043 }
Stuart McCullochbb014372012-06-07 21:57:32 +000044 }
45
46 @Override
47 public long lastModified() {
48 return lastModified;
49 }
50
51}