Format formats swag comments in contents. It uses fileName to report errors that happen during parsing of contents.
(fileName string, contents []byte)
| 49 | // Format formats swag comments in contents. It uses fileName to report errors |
| 50 | // that happen during parsing of contents. |
| 51 | func (f *Formatter) Format(fileName string, contents []byte) ([]byte, error) { |
| 52 | fileSet := token.NewFileSet() |
| 53 | ast, err := goparser.ParseFile(fileSet, fileName, contents, goparser.ParseComments) |
| 54 | if err != nil { |
| 55 | return nil, err |
| 56 | } |
| 57 | |
| 58 | // Formatting changes are described as an edit list of byte range |
| 59 | // replacements. We make these content-level edits directly rather than |
| 60 | // changing the AST nodes and writing those out (via [go/printer] or |
| 61 | // [go/format]) so that we only change the formatting of Swag attribute |
| 62 | // comments. This won't touch the formatting of any other comments, or of |
| 63 | // functions, etc. |
| 64 | maxEdits := 0 |
| 65 | for _, comment := range ast.Comments { |
| 66 | maxEdits += len(comment.List) |
| 67 | } |
| 68 | edits := make(edits, 0, maxEdits) |
| 69 | |
| 70 | for _, comment := range ast.Comments { |
| 71 | formatFuncDoc(fileSet, comment.List, &edits) |
| 72 | } |
| 73 | formatted, err := imports.Process(fileName, edits.apply(contents), nil) |
| 74 | if err != nil { |
| 75 | return nil, err |
| 76 | } |
| 77 | return formatted, nil |
| 78 | } |
| 79 | |
| 80 | type edit struct { |
| 81 | begin int |