Skip to content

Commit

Permalink
feat: imports grouping
Browse files Browse the repository at this point in the history
  • Loading branch information
MilkeeyCat committed Jan 3, 2025
1 parent e54517e commit 2fd5972
Showing 1 changed file with 29 additions and 7 deletions.
36 changes: 29 additions & 7 deletions cmd/templ/imports/process.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,21 +104,33 @@ func Process(t parser.TemplateFile) (parser.TemplateFile, error) {
if err := eg.Wait(); err != nil {
return t, err
}

// Delete all the existing imports.
// Delete unused imports.
for _, imp := range firstGoNodeInTemplate.Imports {
name, path, err := getImportDetails(imp)
if err != nil {
return t, err
if !containsImport(updatedImports, imp) {
name, path, err := getImportDetails(imp)
if err != nil {
return t, err
}
astutil.DeleteNamedImport(fset, firstGoNodeInTemplate, name, path)
}
astutil.DeleteNamedImport(fset, firstGoNodeInTemplate, name, path)
}
// Add imports, if there are any to add.
for _, imp := range updatedImports {
name, path, err := getImportDetails(imp)
if !containsImport(firstGoNodeInTemplate.Imports, imp) {
name, path, err := getImportDetails(imp)
if err != nil {
return t, err
}
astutil.AddNamedImport(fset, firstGoNodeInTemplate, name, path)
}
}
// Edge case: reinsert the import to use import syntax without parentheses.
if len(firstGoNodeInTemplate.Imports) == 1 {
name, path, err := getImportDetails(firstGoNodeInTemplate.Imports[0])
if err != nil {
return t, err
}
astutil.DeleteNamedImport(fset, firstGoNodeInTemplate, name, path)
astutil.AddNamedImport(fset, firstGoNodeInTemplate, name, path)
}
// Write out the Go code with the imports.
Expand Down Expand Up @@ -150,3 +162,13 @@ func getImportDetails(imp *ast.ImportSpec) (name, importPath string, err error)
}
return name, importPath, nil
}

func containsImport(imports []*ast.ImportSpec, spec *ast.ImportSpec) bool {
for _, imp := range imports {
if imp.Path.Value == spec.Path.Value {
return true
}
}

return false
}

0 comments on commit 2fd5972

Please sign in to comment.