Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Escape tilde more gracefully #16583

Merged
merged 2 commits into from
Oct 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ public final class ShellEscaper extends Escaper {
.or(CharMatcher.inRange('a', 'z')) // that would also accept non-ASCII digits and
.or(CharMatcher.inRange('A', 'Z')) // letters.
.precomputed();
private static final CharMatcher SAFECHAR_MATCHER_WITH_TILDE =
SAFECHAR_MATCHER.or(CharMatcher.is('~')).precomputed();

/**
* Escapes a string by adding strong (single) quotes around it if necessary.
Expand Down Expand Up @@ -98,9 +100,13 @@ public String escape(String unescaped) {
// gets treated as a separate argument.
return "''";
} else {
return SAFECHAR_MATCHER.matchesAllOf(s)
? s
: "'" + STRONGQUOTE_ESCAPER.escape(s) + "'";
if (SAFECHAR_MATCHER.matchesAllOf(s)) {
return s;
}
if (SAFECHAR_MATCHER_WITH_TILDE.matchesAllOf(s) && s.charAt(0) != '~') {
return s;
}
return "'" + STRONGQUOTE_ESCAPER.escape(s) + "'";
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ public void shellEscape() throws Exception {
assertThat(escapeString("\\'foo\\'")).isEqualTo("'\\'\\''foo\\'\\'''");
assertThat(escapeString("${filename%.c}.o")).isEqualTo("'${filename%.c}.o'");
assertThat(escapeString("<html!>")).isEqualTo("'<html!>'");
assertThat(escapeString("~not_home")).isEqualTo("'~not_home'");
assertThat(escapeString("external/protobuf~3.19.6/src/google"))
.isEqualTo("external/protobuf~3.19.6/src/google");
assertThat(escapeString("external/~install_dev_dependencies~foo/pkg"))
.isEqualTo("external/~install_dev_dependencies~foo/pkg");
}

@Test
Expand Down