From ba137391d3b79a73fc0826955d6c793ace354e34 Mon Sep 17 00:00:00 2001 From: Joachim Klein Date: Fri, 8 Jun 2018 17:10:47 +0200 Subject: [PATCH] PrismCL: Tweak quoting of command-line arguments in log output Handle special cases when quoting the command-line arguments to the log: * Empty argument * Argument containing a single-quote character (') --- prism/src/prism/PrismCL.java | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/prism/src/prism/PrismCL.java b/prism/src/prism/PrismCL.java index 1158e04e..9f30eb72 100644 --- a/prism/src/prism/PrismCL.java +++ b/prism/src/prism/PrismCL.java @@ -2104,15 +2104,37 @@ public class PrismCL implements PrismModelListener for (i = 0; i < args.length; i++) { s = args[i]; // If necessary add quotes so can be pasted back into a shell - // (where "necessary" means contains any non-safe characters) - if (s.matches(".*[^_a-zA-Z0-9\\./\\-=].*")) { - s = "'" + s + "'"; - } + s = shellQuoteSingleIfNecessary(s); mainLog.print(" " + s); } mainLog.println(); } + /** + * For a command-line argument, returns a quoted version + * with single quotes if it contains unsafe characters. + * Otherwise, just returns the unquoted argument. + */ + public static String shellQuoteSingleIfNecessary(String arg) + { + if (arg.isEmpty()) { + // empty argument needs to be quoted + return "''"; + } + + // If necessary add quotes so can be pasted back into a shell + // (where "necessary" means contains any non-safe characters) + if (arg.matches(".*[^_a-zA-Z0-9\\./\\-=].*")) { + // argument needs quoting, so we surround with single quotes, + // which neutralises all characters except ' + // for that we have to have special handling, replacing ' by '\'' + // (close quote, escaped-', open quote again) + arg = arg.replace("'", "'\\''"); + arg = "'" + arg + "'"; + } + return arg; + } + // do some processing of the options private void processOptions() throws PrismException