redhat-developer / alizer

⛔️ DEPRECATED - Application analyzer toolkit, use https://github.com/devfile/alizer instead
Apache License 2.0
12 stars 17 forks source link

Replace MustCompile with Compile for non-hardcoded regexes #238

Closed thepetk closed 1 year ago

thepetk commented 1 year ago

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.

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.