Skip to content

Commit

Permalink
refactor: rewrite formatImportSpecs to eliminate dupe
Browse files Browse the repository at this point in the history
  • Loading branch information
haunt98 committed Nov 26, 2022
1 parent c8a2bac commit 2e435dd
Showing 1 changed file with 21 additions and 53 deletions.
74 changes: 21 additions & 53 deletions internal/imports/formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,39 +287,8 @@ func (ft *Formatter) formatImportSpecs(
) ([]ast.Spec, error) {
result := make([]ast.Spec, 0, len(importSpecs))

if stdImportSpecs, ok := groupedImportSpecs[stdImport]; ok && len(stdImportSpecs) != 0 {
for _, importSpec := range stdImportSpecs {
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 {
result = append(result, &ast.ImportSpec{
Path: &ast.BasicLit{
Value: "",
Kind: token.STRING,
},
})
}

for _, importSpec := range thirdPartImportSpecs {
result = append(result, &ast.ImportSpec{
Path: &ast.BasicLit{
Value: importSpec.Path.Value,
Kind: token.IMPORT,
},
})
}
}

if ft.companyPrefix != "" {
if companyImportSpecs, ok := groupedImportSpecs[companyImport]; ok && len(companyImportSpecs) != 0 {
appendToResultFn := func(groupImportType string) {
if specs, ok := groupedImportSpecs[groupImportType]; ok && len(specs) != 0 {
if len(result) != 0 {
result = append(result, &ast.ImportSpec{
Path: &ast.BasicLit{
Expand All @@ -329,36 +298,23 @@ func (ft *Formatter) formatImportSpecs(
})
}

for _, importSpec := range companyImportSpecs {
for _, spec := range specs {
result = append(result, &ast.ImportSpec{
Path: &ast.BasicLit{
Value: importSpec.Path.Value,
Value: ft.importNameAndPath(spec),
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(stdImport)
appendToResultFn(thirdPartyImport)
if ft.companyPrefix != "" {
appendToResultFn(companyImport)
}
appendToResultFn(localImport)

return result, nil
}
Expand Down Expand Up @@ -420,3 +376,15 @@ func (ft *Formatter) moduleName(path string) (string, error) {

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
}

0 comments on commit 2e435dd

Please sign in to comment.