github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/hack/plugins/formatter_order.go (about)

     1  package plugins
     2  
     3  import (
     4  	"strings"
     5  
     6  	"github.com/vektah/gqlparser/v2/ast"
     7  )
     8  
     9  // QueryTypeName missing godoc
    10  const QueryTypeName = "Query"
    11  
    12  // MutationTypeName missing godoc
    13  const MutationTypeName = "Mutation"
    14  
    15  // OrderedDefinitionList missing godoc
    16  type OrderedDefinitionList []ast.Definition
    17  
    18  // Len missing godoc
    19  func (d OrderedDefinitionList) Len() int {
    20  	return len(d)
    21  }
    22  
    23  // Swap missing godoc
    24  func (d OrderedDefinitionList) Swap(i, j int) {
    25  	d[i], d[j] = d[j], d[i]
    26  }
    27  
    28  // Less missing godoc
    29  func (d OrderedDefinitionList) Less(i, j int) bool {
    30  	first := d[i]
    31  	second := d[j]
    32  
    33  	typeComparison := d.typeMapping(first.Kind) - d.typeMapping(second.Kind)
    34  	if typeComparison < 0 {
    35  		return true
    36  	} else if typeComparison > 0 {
    37  		return false
    38  	}
    39  
    40  	if first.Kind == ast.Object {
    41  		// query and mutations should be at the end of the file
    42  		if first.Name == MutationTypeName {
    43  			return false
    44  		}
    45  		if second.Name == MutationTypeName {
    46  			return true
    47  		}
    48  		if first.Name == QueryTypeName {
    49  			return false
    50  		}
    51  		if second.Name == QueryTypeName {
    52  			return true
    53  		}
    54  	}
    55  	return strings.Compare(first.Name, second.Name) < 0
    56  }
    57  
    58  func (d OrderedDefinitionList) typeMapping(kind ast.DefinitionKind) int {
    59  	switch kind {
    60  	case ast.Scalar:
    61  		return 1
    62  	case ast.Enum:
    63  		return 2
    64  	case ast.Interface:
    65  		return 3
    66  	case ast.Union:
    67  		return 4
    68  	case ast.InputObject:
    69  		return 5
    70  	case ast.Object:
    71  		return 6
    72  	default:
    73  		return 0
    74  	}
    75  }