Skip to content
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
83 changes: 82 additions & 1 deletion cmd/internal/migrations/v3/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -364,17 +364,98 @@ func MigrateTrustedProxyConfig(cmd *cobra.Command, cwd string, _, _ *semver.Vers
// in Fiber v3. It renames Prefork and Network fields and adapts them to the new
// listener configuration fields.
func MigrateConfigListenerFields(cmd *cobra.Command, cwd string, _, _ *semver.Version) error {
var disableStartup string
var enablePrint string

err := internal.ChangeFileContent(cwd, func(content string) string {
replacer := strings.NewReplacer(
"Prefork:", "EnablePrefork:",
"Network:", "ListenerNetwork:",
)
return replacer.Replace(content)
content = replacer.Replace(content)

reStartup := regexp.MustCompile(`(?m)^\s*DisableStartupMessage:\s*([^,]+),?\n`)
content = reStartup.ReplaceAllStringFunc(content, func(s string) string {
if disableStartup == "" {
sub := reStartup.FindStringSubmatch(s)
if len(sub) > 1 {
disableStartup = strings.TrimSpace(sub[1])
}
}
return ""
})

rePrint := regexp.MustCompile(`(?m)^\s*EnablePrintRoutes:\s*([^,]+),?\n`)
content = rePrint.ReplaceAllStringFunc(content, func(s string) string {
if enablePrint == "" {
sub := rePrint.FindStringSubmatch(s)
if len(sub) > 1 {
enablePrint = strings.TrimSpace(sub[1])
}
}
return ""
})

return content
})
if err != nil {
return fmt.Errorf("failed to migrate listener related config fields: %w", err)
}

err = internal.ChangeFileContent(cwd, func(content string) string {
if disableStartup == "" && enablePrint == "" {
return content
}

reWithCfg := regexp.MustCompile(`\.Listen\(([^,]+),\s*fiber.ListenConfig\{([^}]*)\}\)`)
content = reWithCfg.ReplaceAllStringFunc(content, func(s string) string {
sub := reWithCfg.FindStringSubmatch(s)
addr := sub[1]
Comment on lines +412 to +413
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Accessing slice elements from FindStringSubmatch without checking the slice length can lead to a panic if the regex matches but fails to capture the expected groups. It's safer to check the length of sub before accessing its elements.

sub := reWithCfg.FindStringSubmatch(s)
if len(sub) < 3 {
	return s
}
addr := sub[1]

cfg := strings.TrimSpace(sub[2])

if disableStartup != "" && !strings.Contains(cfg, "DisableStartupMessage:") {
if len(cfg) > 0 && !strings.HasSuffix(cfg, ",") {
cfg += ","
}
cfg += " DisableStartupMessage: " + disableStartup + ","
}
if enablePrint != "" && !strings.Contains(cfg, "EnablePrintRoutes:") {
if len(cfg) > 0 && !strings.HasSuffix(cfg, ",") {
cfg += ","
}
cfg += " EnablePrintRoutes: " + enablePrint + ","
}

cfg = strings.TrimSuffix(cfg, ",")
return fmt.Sprintf(".Listen(%s, fiber.ListenConfig{%s})", addr, cfg)
})

rePlain := regexp.MustCompile(`\.Listen\(([^,\n)]+)\)`)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This regular expression can be made more specific to only match .Listen calls with a single argument. By ensuring no other arguments follow the address (\s*\)), you can then remove the strings.Contains check on lines 435-437, which makes the migration logic more robust.

rePlain := regexp.MustCompile(`\.Listen\(([^,\n)]+)\s*\)`)

content = rePlain.ReplaceAllStringFunc(content, func(s string) string {
if strings.Contains(s, "fiber.ListenConfig") {
return s
}
Comment on lines +435 to +437
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Following the suggested change to the regular expression on line 433, this check is no longer necessary and can be removed.


addr := rePlain.FindStringSubmatch(s)[1]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

It's important to check the length of the submatch slice before accessing elements to prevent a potential panic. This is especially true after removing the guard clause that was previously on lines 435-437.

sub := rePlain.FindStringSubmatch(s)
if len(sub) < 2 {
	return s
}
addr := sub[1]

fields := ""
if disableStartup != "" {
fields += "DisableStartupMessage: " + disableStartup + ", "
}
if enablePrint != "" {
fields += "EnablePrintRoutes: " + enablePrint + ", "
}
fields = strings.TrimSpace(fields)
fields = strings.TrimSuffix(fields, ",")

return fmt.Sprintf(".Listen(%s, fiber.ListenConfig{%s})", addr, fields)
})

return content
})
if err != nil {
return fmt.Errorf("failed to migrate listener related listen calls: %w", err)
}

cmd.Println("Migrating listener related config fields")
return nil
}
Expand Down
67 changes: 61 additions & 6 deletions cmd/internal/migrations/v3/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -479,23 +479,78 @@ func Test_MigrateConfigListenerFields(t *testing.T) {
require.NoError(t, err)
defer func() { require.NoError(t, os.RemoveAll(dir)) }()

file := writeTempFile(t, dir, `package main
file1 := filepath.Join(dir, "app.go")
require.NoError(t, os.WriteFile(file1, []byte(`package main
import "github.com/gofiber/fiber/v2"
func main() {
app := fiber.New(fiber.Config{
func newApp() *fiber.App {
return fiber.New(fiber.Config{
Prefork: true,
Network: "tcp",
DisableStartupMessage: true,
EnablePrintRoutes: true,
})
_ = app
}`)
}`), 0o600))

file2 := filepath.Join(dir, "main.go")
require.NoError(t, os.WriteFile(file2, []byte(`package main
func main() {
app := newApp()
app.Listen(":3000")
}`), 0o600))

var buf bytes.Buffer
cmd := newCmd(&buf)
require.NoError(t, v3.MigrateConfigListenerFields(cmd, dir, nil, nil))

content := readFile(t, file)
content := readFile(t, file1)
assert.Contains(t, content, "EnablePrefork: true")
assert.Contains(t, content, "ListenerNetwork: \"tcp\"")
assert.NotContains(t, content, "DisableStartupMessage")
assert.NotContains(t, content, "EnablePrintRoutes")
content2 := readFile(t, file2)
assert.Contains(t, content2, "fiber.ListenConfig{")
assert.Contains(t, content2, "DisableStartupMessage: true")
assert.Contains(t, content2, "EnablePrintRoutes: true")
assert.Contains(t, buf.String(), "Migrating listener related config fields")
}

func Test_MigrateConfigListenerFields_ExistingListenConfig(t *testing.T) {
t.Parallel()

dir, err := os.MkdirTemp("", "mconf2")
require.NoError(t, err)
defer func() { require.NoError(t, os.RemoveAll(dir)) }()

file1 := filepath.Join(dir, "app.go")
require.NoError(t, os.WriteFile(file1, []byte(`package main
import "github.com/gofiber/fiber/v2"
func newApp() *fiber.App {
return fiber.New(fiber.Config{
DisableStartupMessage: true,
EnablePrintRoutes: true,
})
}`), 0o600))

file2 := filepath.Join(dir, "main.go")
require.NoError(t, os.WriteFile(file2, []byte(`package main
import "github.com/gofiber/fiber/v2"
func main() {
app := newApp()
app.Listen(":3000", fiber.ListenConfig{EnablePrefork: true})
}`), 0o600))

var buf bytes.Buffer
cmd := newCmd(&buf)
require.NoError(t, v3.MigrateConfigListenerFields(cmd, dir, nil, nil))

content1 := readFile(t, file1)
assert.NotContains(t, content1, "DisableStartupMessage")
assert.NotContains(t, content1, "EnablePrintRoutes")

content2 := readFile(t, file2)
assert.Contains(t, content2, "EnablePrefork: true")
assert.Contains(t, content2, "DisableStartupMessage: true")
assert.Contains(t, content2, "EnablePrintRoutes: true")
assert.Contains(t, buf.String(), "Migrating listener related config fields")
}

Expand Down
Loading