Skip to content
This repository has been archived by the owner on Oct 10, 2023. It is now read-only.

Replace MustCompile with Compile for non-hardcoded regexes #238

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,10 @@ func (e ExpressDetector) DoPortsDetection(component *model.Component, ctx *conte

func getPortGroup(content string, matchIndexes []int, portPlaceholder string) string {
contentBeforeMatch := content[0:matchIndexes[0]]
re := regexp.MustCompile(`(let|const|var)\s+` + portPlaceholder + `\s*=\s*([^;]*)`)
re, err := regexp.Compile(`(let|const|var)\s+` + portPlaceholder + `\s*=\s*([^;]*)`)
if err != nil {
return ""
}
return utils.FindPotentialPortGroup(re, contentBeforeMatch, 2)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,10 @@ func getPortFromScript(root string, getScript packageScriptFunc, regexes []strin
}

for _, regex := range regexes {
re := regexp.MustCompile(regex)
re, err := regexp.Compile(regex)
if err != nil {
continue
}
port := utils.FindPortSubmatch(re, getScript(packageJson), 1)
if port != -1 {
return port
Expand Down
6 changes: 5 additions & 1 deletion go/test/apis/component_recognizer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,10 @@ func TestComponentDetectionOnAngular(t *testing.T) {
isComponentsInProject(t, "angularjs", 1, "typescript", "angularjs")
}

func TestComponentDetectionOnExpress(t *testing.T) {
isComponentsInProject(t, "expressjs", 1, "javascript", "expressjs")
}

func TestComponentDetectionOnNextJs(t *testing.T) {
isComponentsInProject(t, "nextjs-app", 1, "typescript", "nextjs-app")
}
Expand Down Expand Up @@ -178,7 +182,7 @@ func updateContent(filePath string, data []byte) error {

func TestComponentDetectionMultiProjects(t *testing.T) {
components := getComponentsFromProject(t, "")
nComps := 32
nComps := 33
if len(components) != nComps {
t.Errorf("Expected " + strconv.Itoa(nComps) + " components but found " + strconv.Itoa(len(components)))
}
Expand Down
65 changes: 65 additions & 0 deletions resources/projects/expressjs/config.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* Copyright 2020 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

export interface Config {
/**
* A list of forwarding-proxies. Each key is a route to match,
* below the prefix that the proxy plugin is mounted on. It must
* start with a '/'.
*/
proxy?: {
[key: string]:
| string
| {
/**
* Target of the proxy. Url string to be parsed with the url module.
*/
target: string;
/**
* Object with extra headers to be added to target requests.
*/
headers?: Partial<{
/** @visibility secret */
Authorization: string;
/** @visibility secret */
authorization: string;
/** @visibility secret */
'X-Api-Key': string;
/** @visibility secret */
'x-api-key': string;
[key: string]: string;
}>;
/**
* Changes the origin of the host header to the target URL. Default: true.
*/
changeOrigin?: boolean;
/**
* Rewrite target's url path. Object-keys will be used as RegExp to match paths.
* If pathRewrite is not specified, it is set to a single rewrite that removes the entire prefix and route.
*/
pathRewrite?: { [regexp: string]: string };
/**
* Limit the forwarded HTTP methods, for example allowedMethods: ['GET'] to enforce read-only access.
*/
allowedMethods?: string[];
/**
* Limit the forwarded HTTP methods. By default, only the headers that are considered safe for CORS
* and headers that are set by the proxy will be forwarded.
*/
allowedHeaders?: string[];
};
};
}
56 changes: 56 additions & 0 deletions resources/projects/expressjs/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
{
"name": "expressjs",
"description": "test resources",
"version": "0.2.40-next.2",
"main": "src/index.ts",
"types": "src/index.ts",
"license": "Apache-2.0",
"publishConfig": {
"access": "public",
"main": "dist/index.cjs.js",
"types": "dist/index.d.ts",
"alphaTypes": "dist/index.alpha.d.ts"
},
"backstage": {
"role": "backend-plugin"
},
"homepage": "https://backstage.io",
"repository": {
"type": "git",
"url": "https://github.com/backstage/backstage",
"directory": "plugins/proxy-backend"
},
"keywords": [
"backstage"
],
"dependencies": {
"@backstage/backend-common": "workspace:^",
"@backstage/backend-plugin-api": "workspace:^",
"@backstage/config": "workspace:^",
"@types/express": "^4.17.6",
"express": "^4.17.1",
"express-promise-router": "^4.1.0",
"http-proxy-middleware": "^2.0.0",
"morgan": "^1.10.0",
"uuid": "^8.0.0",
"winston": "^3.2.1",
"yaml": "^2.0.0",
"yn": "^4.0.0",
"yup": "^0.32.9"
},
"devDependencies": {
"@backstage/cli": "workspace:^",
"@types/http-proxy-middleware": "^0.19.3",
"@types/supertest": "^2.0.8",
"@types/uuid": "^8.0.0",
"@types/yup": "^0.29.13",
"msw": "^1.0.0",
"supertest": "^6.1.3"
},
"files": [
"dist",
"config.d.ts",
"alpha"
],
"configSchema": "config.d.ts"
}
24 changes: 24 additions & 0 deletions resources/projects/expressjs/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* Copyright 2020 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
* A Backstage backend plugin that helps you set up proxy endpoints in the backend
*
* @packageDocumentation
*/

export * from './service';
export { proxyPlugin } from './plugin';
57 changes: 57 additions & 0 deletions resources/projects/expressjs/src/plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Copyright 2023 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { loggerToWinstonLogger } from '@backstage/backend-common';
import {
createBackendPlugin,
coreServices,
} from '@backstage/backend-plugin-api';
import { createRouter } from './service/router';

/**
* The proxy backend plugin.
*
* @alpha
*/
export const proxyPlugin = createBackendPlugin(
(options?: {
skipInvalidProxies?: boolean;
reviveConsumedRequestBodies?: boolean;
}) => ({
pluginId: 'proxy',
register(env) {
env.registerInit({
deps: {
config: coreServices.config,
discovery: coreServices.discovery,
logger: coreServices.logger,
httpRouter: coreServices.httpRouter,
},
async init({ config, discovery, logger, httpRouter }) {
httpRouter.use(
await createRouter({
config,
discovery,
logger: loggerToWinstonLogger(logger),
skipInvalidProxies: options?.skipInvalidProxies,
reviveConsumedRequestBodies: options?.reviveConsumedRequestBodies,
}),
);
},
});
},
}),
);
33 changes: 33 additions & 0 deletions resources/projects/expressjs/src/run.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* Copyright 2020 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { getRootLogger } from '@backstage/backend-common';
import yn from 'yn';
import { startStandaloneServer } from './service/standaloneServer';

const port = process.env.PLUGIN_PORT ? Number(process.env.PLUGIN_PORT) : 7007;
const enableCors = yn(process.env.PLUGIN_CORS, { default: false });
const logger = getRootLogger();

startStandaloneServer({ port, enableCors, logger }).catch(err => {
logger.error(err);
process.exit(1);
});

process.on('SIGINT', () => {
logger.info('CTRL+C pressed; exiting.');
process.exit(0);
});
18 changes: 18 additions & 0 deletions resources/projects/expressjs/src/service/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
* Copyright 2020 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

export type { RouterOptions } from './router';
export { createRouter } from './router';
Loading