finalizeGoSource processes Go source entirely in memory without file I/O
(path string, content []byte)
| 127 | |
| 128 | // finalizeGoSource processes Go source entirely in memory without file I/O |
| 129 | func finalizeGoSource(path string, content []byte) ([]byte, error) { |
| 130 | // Parse the content |
| 131 | fset := token.NewFileSet() |
| 132 | file, err := parser.ParseFile(fset, path, content, parser.ParseComments) |
| 133 | if err != nil { |
| 134 | var buf bytes.Buffer |
| 135 | scanner.PrintError(&buf, err) |
| 136 | return nil, fmt.Errorf("%s\n========\nContent:\n%s", buf.String(), content) |
| 137 | } |
| 138 | |
| 139 | // Clean unused imports using optimized single-pass detection |
| 140 | impMap := buildImportMap(file) |
| 141 | detectUsedImports(file, impMap) |
| 142 | removeUnusedImports(fset, file, impMap) |
| 143 | ast.SortImports(fset, file) |
| 144 | |
| 145 | // Format the AST back to bytes |
| 146 | var formatted bytes.Buffer |
| 147 | if err := format.Node(&formatted, fset, file); err != nil { |
| 148 | return nil, err |
| 149 | } |
| 150 | |
| 151 | // Apply goimports formatting |
| 152 | opt := imports.Options{ |
| 153 | Comments: true, |
| 154 | FormatOnly: true, |
| 155 | } |
| 156 | result, err := imports.Process(path, formatted.Bytes(), &opt) |
| 157 | if err != nil { |
| 158 | return nil, err |
| 159 | } |
| 160 | |
| 161 | return result, nil |
| 162 | } |
no test coverage detected