blob: 767dc98895bf69cc8176ab8f03936d6fecbdce83 [file] [log] [blame]
/*=============================================================================#
# Copyright (c) 2020 Stephan Wahlbrink and others.
#
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License 2.0 which is available at
# https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
# which is available at https://www.apache.org/licenses/LICENSE-2.0.
#
# SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
#
# Contributors:
# Stephan Wahlbrink <sw@wahlbrink.eu> - initial API and implementation
#=============================================================================*/
package org.eclipse.statet.jcommons.runtime;
import java.util.List;
import java.util.regex.Pattern;
import org.eclipse.statet.jcommons.lang.NonNullByDefault;
@NonNullByDefault
public class ProcessUtils {
private static final Pattern DOUBLE_QUOTE_PATTERN= Pattern.compile("\"", Pattern.LITERAL); //$NON-NLS-1$
private static final String DOUBLE_QUOTE_REPLACEMENT= "\\\\\""; //$NON-NLS-1$
/**
* Creates an UI presentation (compatible with most shells) of the specified command.
*
* @param command the program and arguments (e.g. from {@link ProcessBuilder#command()})
*
* @return the command line string
*/
public static String generateCommandLine(final List<String> command) {
if (command.isEmpty()) {
return ""; //$NON-NLS-1$
}
final StringBuilder sb= new StringBuilder();
for (final String arg : command) {
final String escaped= DOUBLE_QUOTE_PATTERN
.matcher(arg)
.replaceAll(DOUBLE_QUOTE_REPLACEMENT);
if (escaped.indexOf(' ') >= 0) {
sb.append('\"');
sb.append(escaped);
sb.append('\"');
}
else {
sb.append(escaped);
}
sb.append(' ');
}
return sb.substring(0, sb.length() - 1);
}
private ProcessUtils() {
}
}