refactor: rewrite formatImportSpecs to eliminate dupe

main
sudo pacman -Syu 2022-11-27 00:57:52 +07:00
parent c8a2bac5f1
commit 2e435dd37b
No known key found for this signature in database
GPG Key ID: D6CB5C6C567C47B0
1 changed files with 21 additions and 53 deletions

View File

@ -287,18 +287,8 @@ func (ft *Formatter) formatImportSpecs(
) ([]ast.Spec, error) { ) ([]ast.Spec, error) {
result := make([]ast.Spec, 0, len(importSpecs)) result := make([]ast.Spec, 0, len(importSpecs))
if stdImportSpecs, ok := groupedImportSpecs[stdImport]; ok && len(stdImportSpecs) != 0 { appendToResultFn := func(groupImportType string) {
for _, importSpec := range stdImportSpecs { if specs, ok := groupedImportSpecs[groupImportType]; ok && len(specs) != 0 {
result = append(result, &ast.ImportSpec{
Path: &ast.BasicLit{
Value: importSpec.Path.Value,
Kind: token.IMPORT,
},
})
}
}
if thirdPartImportSpecs, ok := groupedImportSpecs[thirdPartyImport]; ok && len(thirdPartImportSpecs) != 0 {
if len(result) != 0 { if len(result) != 0 {
result = append(result, &ast.ImportSpec{ result = append(result, &ast.ImportSpec{
Path: &ast.BasicLit{ Path: &ast.BasicLit{
@ -308,57 +298,23 @@ func (ft *Formatter) formatImportSpecs(
}) })
} }
for _, importSpec := range thirdPartImportSpecs { for _, spec := range specs {
result = append(result, &ast.ImportSpec{ result = append(result, &ast.ImportSpec{
Path: &ast.BasicLit{ Path: &ast.BasicLit{
Value: importSpec.Path.Value, Value: ft.importNameAndPath(spec),
Kind: token.IMPORT, Kind: token.IMPORT,
}, },
}) })
} }
} }
}
appendToResultFn(stdImport)
appendToResultFn(thirdPartyImport)
if ft.companyPrefix != "" { if ft.companyPrefix != "" {
if companyImportSpecs, ok := groupedImportSpecs[companyImport]; ok && len(companyImportSpecs) != 0 { appendToResultFn(companyImport)
if len(result) != 0 {
result = append(result, &ast.ImportSpec{
Path: &ast.BasicLit{
Value: "",
Kind: token.STRING,
},
})
}
for _, importSpec := range companyImportSpecs {
result = append(result, &ast.ImportSpec{
Path: &ast.BasicLit{
Value: importSpec.Path.Value,
Kind: token.IMPORT,
},
})
}
}
}
if localImportSpecs, ok := groupedImportSpecs[localImport]; ok && len(localImportSpecs) != 0 {
if len(result) != 0 {
result = append(result, &ast.ImportSpec{
Path: &ast.BasicLit{
Value: "",
Kind: token.STRING,
},
})
}
for _, importSpec := range localImportSpecs {
result = append(result, &ast.ImportSpec{
Path: &ast.BasicLit{
Value: importSpec.Path.Value,
Kind: token.IMPORT,
},
})
}
} }
appendToResultFn(localImport)
return result, nil return result, nil
} }
@ -420,3 +376,15 @@ func (ft *Formatter) moduleName(path string) (string, error) {
return result, nil return result, nil
} }
func (ft *Formatter) importNameAndPath(importSpec *ast.ImportSpec) string {
if importSpec == nil {
return ""
}
if importSpec.Name != nil {
return importSpec.Name.String() + " " + importSpec.Path.Value
}
return importSpec.Path.Value
}