Skip to content

Commit 9d4cfc8

Browse files
committed
Sanitise program name when using in shell function name
Fixes #49
1 parent 66bd208 commit 9d4cfc8

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

src/HookFactory.php

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ function %%function_name%% {
6464
__ltrim_colon_completions "$cur";
6565
};
6666
67-
complete -F %%function_name%% %%program_name%%;
67+
complete -F %%function_name%% "%%program_name%%";
6868
END
6969

7070
// ZSH Hook
@@ -94,7 +94,7 @@ function %%function_name%% {
9494
compadd -- $RESULT
9595
};
9696
97-
compdef %%function_name%% %%program_name%%;
97+
compdef %%function_name%% "%%program_name%%";
9898
END
9999
);
100100

@@ -161,11 +161,24 @@ protected function generateFunctionName($programPath, $programName)
161161
{
162162
return sprintf(
163163
'_%s_%s_complete',
164-
basename($programName),
164+
$this->sanitiseForFunctionName(basename($programName)),
165165
substr(md5($programPath), 0, 16)
166166
);
167167
}
168168

169+
170+
/**
171+
* Make a string safe for use as a shell function name
172+
*
173+
* @param string $name
174+
* @return string
175+
*/
176+
protected function sanitiseForFunctionName($name)
177+
{
178+
$name = str_replace('-', '_', $name);
179+
return preg_replace('/[^A-Za-z0-9_]+/', '', $name);
180+
}
181+
169182
/**
170183
* Strip '#' style comments from a string
171184
*

tests/Stecman/Component/Symfony/Console/BashCompletion/HookFactoryTest.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ public function generateHookDataProvider()
4949
array('/path/to/myprogram', null, true),
5050
array('/path/to/myprogram', 'myprogram', false),
5151
array('/path/to/myprogram', 'myprogram', true),
52+
array('/path/to/my-program', 'my-program', false)
5253
);
5354
}
5455

0 commit comments

Comments
 (0)