-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(goctl): update api handler comment during generation
- Loading branch information
Showing
3 changed files
with
70 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
package gogen | ||
|
||
import ( | ||
"bytes" | ||
"fmt" | ||
"go/ast" | ||
"go/format" | ||
"go/parser" | ||
"go/token" | ||
"os" | ||
) | ||
|
||
func updateHandlerComments(filename string, handlerName string, comments []string) error { | ||
// Parse the code file | ||
fset := token.NewFileSet() | ||
f, err := parser.ParseFile(fset, filename, nil, parser.ParseComments) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
// Find the UserSelfHandler function | ||
var fn *ast.FuncDecl | ||
for i := range f.Decls { | ||
if fd, ok := f.Decls[i].(*ast.FuncDecl); ok && fd.Name.Name == handlerName { | ||
fn = fd | ||
break | ||
} | ||
} | ||
if fn == nil { | ||
return fmt.Errorf("handler %s not found", handlerName) | ||
} | ||
|
||
// Update the function's comments | ||
var list []*ast.Comment | ||
for i, comment := range comments { | ||
if i == 0 { | ||
list = append(list, &ast.Comment{Slash: fn.Pos() - 1, Text: comment}) | ||
} else { | ||
list = append(list, &ast.Comment{Text: comment}) | ||
} | ||
} | ||
if fn.Doc == nil { | ||
fn.Doc = &ast.CommentGroup{} | ||
} | ||
fn.Doc.List = list | ||
|
||
// Format and write the updated code to file | ||
var buf bytes.Buffer | ||
if err := format.Node(&buf, fset, f); err != nil { | ||
return err | ||
} | ||
if err := os.WriteFile(filename, buf.Bytes(), 0644); err != nil { | ||
return err | ||
} | ||
|
||
return nil | ||
} |