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

Conversation

thepetk
Copy link
Collaborator

@thepetk thepetk commented Jun 18, 2023

What does this PR do?

There are two cases that we are compiling a regex with regexp.MustCompile and a dynamic string:

One, for express js port detection

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

Second, for nodejs_detector.getPortFromScript() func:

for _, regex := range regexes {
	re := regexp.MustCompile(regex)
	port := utils.FindPortSubmatch(re, getScript(packageJson), 1)
	if port != -1 {
		return port
	}
}

As MustCompile action for error is panic this PR replaces those two functions with Compile and handles any error case accordingly.

A test resource is added along with the TestComponentDetectionOnExpress test, ensuring that a failure with regexp.Compile will be handled and the code will not panic.

Which issue(s) does this PR fix

fixes #220

PR acceptance criteria

Testing and documentation do not need to be complete in order for this PR to be approved. We just need to ensure tracking issues are opened.

  • Unit/Functional tests

  • Documentation

How to test changes / Special notes to the reviewer

The repo that this issue was first seen was the one mentioned inside the issue: https://github.com/backstage/backstage.

thepetk added 5 commits June 14, 2023 15:32
Signed-off-by: thepetk <thepetk@gmail.com>
Signed-off-by: thepetk <thepetk@gmail.com>
Signed-off-by: thepetk <thepetk@gmail.com>
Signed-off-by: thepetk <thepetk@gmail.com>
Signed-off-by: thepetk <thepetk@gmail.com>
@thepetk thepetk requested a review from mike-hoang June 18, 2023 20:22
@thepetk thepetk self-assigned this Jun 18, 2023
thepetk added 2 commits June 18, 2023 21:25
Signed-off-by: thepetk <thepetk@gmail.com>
Signed-off-by: thepetk <thepetk@gmail.com>
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Regular expressions in port detection might panic
2 participants