Skip to content

Commit

Permalink
Escaping special regex chars
Browse files Browse the repository at this point in the history
  • Loading branch information
Reinier Cruz committed Aug 8, 2024
1 parent 22ce984 commit 69ae50a
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion src/panels/TcpDumpPanel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,14 @@ const tcpDumpCommandBase = "tcpdump --snapshot-length=0 -vvv";
const captureDir = "/tmp";
const captureFilePrefix = "vscodenodecap_";
const captureFileBasePath = `${captureDir}/${captureFilePrefix}`;
const captureFilePathRegex = `${captureFileBasePath.replace(/\//g, "\\$&")}(.*)\\.cap`; // Matches the part of the filename after the prefix
const captureFileBasePathEscaped = escapeRegExp(captureFileBasePath);
const captureFilePathRegex = `${captureFileBasePathEscaped}(.*)\\.cap`; // Matches the part of the filename after the prefix

// Escape all regex meta characters to ensure sanitation and '/' for later use in regex pattern
function escapeRegExp(input: string): string {
return input.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&"); //Escapes by adding '\' to every matched string $&
}
//Reference for regex syntax chars: https://262.ecma-international.org/13.0/index.html#prod-SyntaxCharacter

function getPodName(node: NodeName) {
return `debug-${node}`;
Expand Down Expand Up @@ -53,6 +60,20 @@ function getCaptureFromFilePath(filePath: string): string | null {
return fileMatch && fileMatch[1];
}

// Test function to verify escaping
function testEscapeRegExp() {
const testString = "/tmp/vscodenodecap_*+?^${}()|[]\\";
const expectedEscapedString = "\\/tmp\\/vscodenodecap_\\*\\+\\?\\^\\$\\{\\}\\(\\)\\|\\[\\]\\\\";

const actualEscapedString = escapeRegExp(testString);
console.assert(
actualEscapedString === expectedEscapedString,
`Expected ${expectedEscapedString}, but got ${actualEscapedString}`,
);
}

testEscapeRegExp();

export class TcpDumpPanel extends BasePanel<"tcpDump"> {
constructor(extensionUri: Uri) {
super(extensionUri, "tcpDump", {
Expand Down

0 comments on commit 69ae50a

Please sign in to comment.