github.com/daixiang0/gci@v0.13.0/pkg/format/format.go (about)

     1  package format
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/daixiang0/gci/pkg/config"
     7  	"github.com/daixiang0/gci/pkg/log"
     8  	"github.com/daixiang0/gci/pkg/parse"
     9  	"github.com/daixiang0/gci/pkg/section"
    10  	"github.com/daixiang0/gci/pkg/specificity"
    11  )
    12  
    13  type Block struct {
    14  	Start, End int
    15  }
    16  
    17  type resultMap map[string][]*Block
    18  
    19  func Format(data []*parse.GciImports, cfg *config.Config) (resultMap, error) {
    20  	result := make(resultMap, len(cfg.Sections))
    21  	for _, d := range data {
    22  		// determine match specificity for every available section
    23  		var bestSection section.Section
    24  		var bestSectionSpecificity specificity.MatchSpecificity = specificity.MisMatch{}
    25  		for _, section := range cfg.Sections {
    26  			sectionSpecificity := section.MatchSpecificity(d)
    27  			if sectionSpecificity.IsMoreSpecific(specificity.MisMatch{}) && sectionSpecificity.Equal(bestSectionSpecificity) {
    28  				// specificity is identical
    29  				// return nil, section.EqualSpecificityMatchError{}
    30  				return nil, nil
    31  			}
    32  			if sectionSpecificity.IsMoreSpecific(bestSectionSpecificity) {
    33  				// better match found
    34  				bestSectionSpecificity = sectionSpecificity
    35  				bestSection = section
    36  			}
    37  		}
    38  		if bestSection == nil {
    39  			return nil, section.NoMatchingSectionForImportError{Imports: d}
    40  		}
    41  		log.L().Debug(fmt.Sprintf("Matched import %v to section %s", d, bestSection))
    42  		result[bestSection.String()] = append(result[bestSection.String()], &Block{d.Start, d.End})
    43  	}
    44  
    45  	return result, nil
    46  }