Skip to content

Commit

Permalink
feat: add Source function
Browse files Browse the repository at this point in the history
  • Loading branch information
ldez committed Dec 23, 2024
1 parent 0a02424 commit a62ac9f
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions gofmt/golangci.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ import (
"github.com/golangci/gofmt/gofmt/internal/diff"
)

type Options struct {
NeedSimplify bool
RewriteRules []RewriteRule
}

var parserModeMu sync.RWMutex

type RewriteRule struct {
Expand Down Expand Up @@ -73,6 +78,32 @@ func RunRewrite(filename string, needSimplify bool, rewriteRules []RewriteRule)
return diff.Diff(oldName, src, newName, res), nil
}

func Source(filename string, src []byte, opts Options) ([]byte, error) {
fset := token.NewFileSet()

parserModeMu.Lock()
initParserMode()
parserModeMu.Unlock()

file, sourceAdj, indentAdj, err := parse(fset, filename, src, false)
if err != nil {
return nil, err
}

file, err = rewriteFileContent(fset, file, opts.RewriteRules)
if err != nil {
return nil, err
}

ast.SortImports(fset, file)

if opts.NeedSimplify {
simplify(file)
}

return format(fset, file, sourceAdj, indentAdj, src, printer.Config{Mode: printerMode, Tabwidth: tabWidth})
}

func rewriteFileContent(fset *token.FileSet, file *ast.File, rewriteRules []RewriteRule) (*ast.File, error) {
for _, rewriteRule := range rewriteRules {
pattern, err := parseExpression(rewriteRule.Pattern, "pattern")
Expand Down

0 comments on commit a62ac9f

Please sign in to comment.