Skip to content

Commit

Permalink
Escape regex directory path
Browse files Browse the repository at this point in the history
  • Loading branch information
stacey-gammon committed Feb 24, 2021
1 parent 3ac3e3d commit 279956d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
12 changes: 11 additions & 1 deletion packages/kbn-docs-utils/src/api_docs/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,22 @@ it('test getServiceForPath', () => {
getServiceForPath('src/plugins/embed/public/file.ts', 'src/plugins/embed')
).toBeUndefined();
expect(
getServiceForPath('src/plugins/embed/server/another_service/file.ts', 'src/plugins/embed')
getServiceForPath('/src/plugins/embed/server/another_service/index', '/src/plugins/embed')
).toBe('another_service');
expect(getServiceForPath('src/plugins/embed/server/no_ending', 'src/plugins/embed')).toBe(
undefined
);
expect(
getServiceForPath('src/plugins/embed/server/routes/public/foo/index.ts', 'src/plugins/embed')
).toBe('routes');
expect(getServiceForPath('src/plugins/embed/server/f.ts', 'src/plugins/embed')).toBeUndefined();

expect(
getServiceForPath(
'/var/lib/jenkins/workspace/elastic+kibana+pipeline-pull-request/kibana/packages/kbn-docs-utils/src/api_docs/tests/__fixtures__/src/plugin_a/public/foo/index',
'/var/lib/jenkins/workspace/elastic+kibana+pipeline-pull-request/kibana/packages/kbn-docs-utils/src/api_docs/tests/__fixtures__/src/plugin_a'
)
).toBe('foo');
});

it('test removeBrokenLinks', () => {
Expand Down
11 changes: 8 additions & 3 deletions packages/kbn-docs-utils/src/api_docs/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ export function groupPluginApi(declarations: ApiDeclaration[]): ScopeApi {
return scope;
}

function escapeRegExp(regexp: string) {
return regexp.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

/**
* If the file is at the top level, returns undefined, otherwise returns the
* name of the first nested folder in the plugin. For example a path of
Expand All @@ -60,9 +64,10 @@ export function groupPluginApi(declarations: ApiDeclaration[]): ScopeApi {
* @param path
*/
export function getServiceForPath(path: string, pluginDirectory: string): string | undefined {
const publicMatchGroups = path.match(`${pluginDirectory}\/public\/([^\/]*)\/`);
const serverMatchGroups = path.match(`${pluginDirectory}\/server\/([^\/]*)\/`);
const commonMatchGroups = path.match(`${pluginDirectory}\/common\/([^\/]*)\/`);
const dir = escapeRegExp(pluginDirectory);
const publicMatchGroups = path.match(`${dir}\/public\/([^\/]*)\/`);
const serverMatchGroups = path.match(`${dir}\/server\/([^\/]*)\/`);
const commonMatchGroups = path.match(`${dir}\/common\/([^\/]*)\/`);

if (publicMatchGroups && publicMatchGroups.length > 1) {
return publicMatchGroups[1];
Expand Down

0 comments on commit 279956d

Please sign in to comment.