Commits

Tom Davies committed 4f8e7ee

clean up param handling

  • Participants
  • Parent commits f24b3b7
  • Branches fix-param-handling

Comments (0)

Files changed (1)

src/main/java/com/atlassian/utils/process/ExternalProcessImpl.java

      * @param handler the process handler to manage the execution of this process
      */
     public ExternalProcessImpl(ExecutorService executorService, List<String> command, ProcessHandler handler) {
-        this.command = command;
+        this.command = escapeParameters(command);
         setHandler(handler);
 
         this.executorService = executorService;
     public void setTimeout(long timeout) {
         setIdleTimeout(timeout);
     }
+
+
+    public List<String> escapeParameters(List<String> commandArgs) {
+        for (int i = 0; i < commandArgs.size(); ++i) {
+            commandArgs.set(i, escapeArg(commandArgs.get(i)));
+        }
+        return commandArgs;
+    }
+
+    /**
+     * On windows we need to ensure that we escape any double quotes in the argument, (but not any already escaped quotes)
+     * @param arg
+     * @return
+     */
+    private String escapeArg(String arg) {
+        String escapedArg = arg;
+        if (isWindows() && arg.contains("\"")) {
+            boolean escapeNextChar = false;
+            StringBuilder sb = new StringBuilder("\"");
+            for (char c : arg.toCharArray()) {
+                if (escapeNextChar) {
+                    escapeNextChar = false;
+                } else if (c == '"') {
+                    sb.append('\\');
+                } else if (c == '\\') {
+                    escapeNextChar = true;
+                }
+                sb.append(c);
+            }
+            if (escapeNextChar) {
+                sb.append('\\'); // string ended with unmatched escape character, add another escape char.
+            }
+            sb.append('\"');
+            escapedArg = sb.toString();
+        }
+        return escapedArg;
+    }
 }