Skip to content

Commit

Permalink
fix shell escape
Browse files Browse the repository at this point in the history
  • Loading branch information
slorber committed May 26, 2022
1 parent aac5f29 commit 1f574b6
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 17 deletions.
12 changes: 6 additions & 6 deletions packages/docusaurus-utils/src/__tests__/shellUtils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ import {escapeShellArg} from '../shellUtils';

describe('shellUtils', () => {
it('escapeShellArg', () => {
expect(escapeShellArg('hello')).toBe('hello');
expect(escapeShellArg('*')).toBe('"*"');
expect(escapeShellArg('hello world')).toBe('"hello world"');
expect(escapeShellArg("'hello'")).toBe('"\'hello\'"');
expect(escapeShellArg('$(pwd)')).toBe('"$(pwd)"');
expect(escapeShellArg('hello$(pwd)')).toBe('"hello$(pwd)"');
expect(escapeShellArg('hello')).toBe("'hello'");
expect(escapeShellArg('*')).toBe("'*'");
expect(escapeShellArg('hello world')).toBe("'hello world'");
expect(escapeShellArg("'hello'")).toBe("\\''hello'\\'");
expect(escapeShellArg('$(pwd)')).toBe("'$(pwd)'");
expect(escapeShellArg('hello$(pwd)')).toBe("'hello$(pwd)'");
});
});
16 changes: 5 additions & 11 deletions packages/docusaurus-utils/src/shellUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,9 @@
// Even shelljs recommends execa for security / escaping:
// https://github.com/shelljs/shelljs/wiki/Security-guidelines

const NO_ESCAPE_REGEXP = /^[\w.-]+$/;
const DOUBLE_QUOTES_REGEXP = /"/g;

// Inspired from Execa escaping function
// https://github.com/sindresorhus/execa/blob/main/lib/command.js#L12
export function escapeShellArg(arg: string): string {
if (NO_ESCAPE_REGEXP.test(arg)) {
return arg;
}

return `"${arg.replace(DOUBLE_QUOTES_REGEXP, '\\"')}"`;
// Inspired by https://github.com/xxorax/node-shell-escape/blob/master/shell-escape.js
export function escapeShellArg(s: string): string {
let res = `'${s.replace(/'/g, "'\\''")}'`;
res = res.replace(/^(?:'')+/g, '').replace(/\\'''/g, "\\'");
return res;
}

0 comments on commit 1f574b6

Please sign in to comment.