Skip to content

Commit

Permalink
GH-79: Handle special characters in shell scripts better
Browse files Browse the repository at this point in the history
- Handle \r \n and \t in shell scripts.
- Handle % in batch scripts.

Fixes GH-79.
  • Loading branch information
ascopes authored Mar 7, 2024
1 parent 313d79c commit 87968f4
Showing 1 changed file with 28 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@
*
* <p>Losely based on Python's {@code shlex} module.
*
* <p>This is far from perfect but should work in the majority of use cases
* to ensure scripts do not interpret special characters in paths in strange
* and unexpected ways.
*
* @author Ashley Scopes
*/
public final class Shlex {
Expand Down Expand Up @@ -65,10 +69,22 @@ private static void quoteShellArg(StringBuilder sb, String arg) {
sb.append('\'');
for (var i = 0; i < arg.length(); ++i) {
var c = arg.charAt(i);
if (c == '\'') {
sb.append("'\"'\"'");
} else {
sb.append(c);
switch (c) {
case '\'':
sb.append("'\"'\"'");
break;
case '\n':
sb.append("'$'\\n''");
break;
case '\r':
sb.append("'$'\\r''");
break;
case '\t':
sb.append("'$'\\t''");
break;
default:
sb.append(c);
break;
}
}
sb.append('\'');
Expand All @@ -83,6 +99,10 @@ private static void quoteBatchArg(StringBuilder sb, String arg) {
for (var i = 0; i < arg.length(); ++i) {
var c = arg.charAt(i);
switch (c) {
case '%':
sb.append("%%");
break;

case '\\':
case '"':
case '\'':
Expand All @@ -95,9 +115,11 @@ private static void quoteBatchArg(StringBuilder sb, String arg) {
case '>':
case '|':
sb.append('^');
// Fall through...
default:
sb.append(c);
break;
}

sb.append(c);
}
}

Expand Down

0 comments on commit 87968f4

Please sign in to comment.