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
2 changes: 1 addition & 1 deletion cmd/gf/internal/cmd/geninit/geninit_ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ func (r *ASTReplacer) ReplaceInFile(ctx context.Context, filePath string) error
}

// Write back to file without formatting.
// Formatting will be handled by utils.GoFmt after all replacements are done.
// Formatting will be handled by formatGoFiles after all replacements are done.
var buf bytes.Buffer
if err := printer.Fprint(&buf, r.fset, file); err != nil {
return err
Expand Down
38 changes: 35 additions & 3 deletions cmd/gf/internal/cmd/geninit/geninit_generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ package geninit
import (
"context"
"fmt"
"go/format"
"path/filepath"

"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/text/gstr"

"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
"github.com/gogf/gf/cmd/gf/v2/internal/utility/utils"
)

// generateProject copies the template to the destination and performs cleanup
Expand Down Expand Up @@ -82,8 +82,10 @@ func generateProject(ctx context.Context, srcPath, name, oldModule, newModule st
}
}

// 6. Format the generated Go files
utils.GoFmt(dstPath)
// 6. Format the generated Go files using go/format (not imports.Process)
// Note: We use formatGoFiles instead of utils.GoFmt because imports.Process
// may incorrectly "fix" local import paths by replacing them with cached module paths.
formatGoFiles(dstPath)

mlog.Print("Project generated successfully!")
return nil
Expand Down Expand Up @@ -112,3 +114,33 @@ func upgradeDependencies(ctx context.Context, projectDir string) error {
mlog.Print("Dependencies upgraded successfully!")
return nil
}

// formatGoFiles formats all Go files in the directory using go/format.
// Unlike imports.Process, this only formats code without modifying imports,
// which prevents incorrect "fixing" of local import paths.
func formatGoFiles(dir string) {
files, err := findGoFiles(dir)
if err != nil {
mlog.Printf("Failed to find Go files for formatting: %v", err)
return
}

for _, file := range files {
content := gfile.GetContents(file)
if content == "" {
continue
}

formatted, err := format.Source([]byte(content))
if err != nil {
mlog.Debugf("Failed to format %s: %v", file, err)
continue
}

if string(formatted) != content {
if err := gfile.PutContents(file, string(formatted)); err != nil {
mlog.Debugf("Failed to write formatted file %s: %v", file, err)
}
}
}
}
Loading