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

fix: ensure completion script uses valid function name #2388

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
5 changes: 4 additions & 1 deletion lib/completion.ts
Expand Up @@ -349,7 +349,10 @@ export class Completion implements CompletionInstance {
let script = this.zshShell
? templates.completionZshTemplate
: templates.completionShTemplate;
const name = this.shim.path.basename($0);
let name = this.shim.path.basename($0);
// Santize `name` to make sure it is a valid bash function name by
// replacing any characters that are not alphanumeric or underscore with an underscore
name = name.replace(/[^A-Za-z0-9_]/g, '_');

// add ./ to applications not yet installed as bin.
if ($0.match(/\.js$/)) $0 = `./${$0}`;
Expand Down
8 changes: 8 additions & 0 deletions test/completion.cjs
Expand Up @@ -608,6 +608,14 @@ describe('Completion', () => {
r.logs[0].should.match(/ndm flintlock >>/);
});

it('santizes scriptName ($0) for use in a bash function', () => {
const r = checkUsage(
() => yargs([]).scriptName('1 test ing').showCompletionScript()
);

r.logs[0].should.match(/_1_test_ing/);
});

it('if $0 has a .js extension, a ./ prefix is added', () => {
const r = checkUsage(() => yargs([]).showCompletionScript(), ['test.js']);

Expand Down