From 7afb1e9d111f206b42859dd3e294ba69d0b6c163 Mon Sep 17 00:00:00 2001 From: quobix Date: Tue, 6 Feb 2024 22:03:53 -0500 Subject: [PATCH] Addressed #159 Cleaned up all interesting static checks. All that is left is cosmetics. Signed-off-by: quobix --- datamodel/high/base/schema.go | 18 ++--- datamodel/high/v2/path_item_test.go | 9 +-- datamodel/high/v3/components.go | 3 +- datamodel/high/v3/oauth_flow_test.go | 1 + datamodel/high/v3/path_item.go | 39 +++++---- datamodel/high/v3/path_item_test.go | 5 +- datamodel/low/base/example_test.go | 1 + datamodel/low/base/license_test.go | 1 + datamodel/low/base/schema.go | 34 ++++---- datamodel/low/base/schema_proxy_test.go | 1 + datamodel/low/base/schema_test.go | 8 +- datamodel/low/extraction_functions.go | 9 ++- datamodel/low/extraction_functions_test.go | 16 +--- datamodel/low/model_builder.go | 1 - datamodel/low/model_builder_test.go | 1 - datamodel/low/v2/path_item.go | 7 -- datamodel/low/v3/path_item.go | 8 -- datamodel/low/v3/response_test.go | 1 + document_test.go | 5 -- index/extract_refs.go | 10 +-- index/map_index_nodes.go | 22 +++--- index/rolodex.go | 1 - index/rolodex_file_loader.go | 4 - index/rolodex_file_loader_test.go | 8 +- index/rolodex_test.go | 2 +- index/search_rolodex.go | 2 +- index/search_rolodex_test.go | 2 + index/utility_methods_test.go | 12 --- renderer/mock_generator.go | 4 +- renderer/mock_generator_test.go | 28 +++---- renderer/schema_renderer.go | 9 +-- utils/type_check.go | 4 +- what-changed/model/comparison_functions.go | 7 +- what-changed/model/components.go | 27 +++---- what-changed/model/path_item.go | 92 +++++++++------------- what-changed/model/paths.go | 12 +-- what-changed/model/schema.go | 6 +- what-changed/model/schema_test.go | 2 +- what-changed/model/tags_test.go | 37 +++++---- 39 files changed, 180 insertions(+), 279 deletions(-) diff --git a/datamodel/high/base/schema.go b/datamodel/high/base/schema.go index 56bf3e46..dd79d827 100644 --- a/datamodel/high/base/schema.go +++ b/datamodel/high/base/schema.go @@ -347,11 +347,9 @@ func NewSchema(schema *base.Schema) *Schema { } j := 0 for j < totalSchemas { - select { - case r := <-bChan: - j++ - (*items)[r.idx] = r.s - } + r := <-bChan + j++ + (*items)[r.idx] = r.s } doneChan <- true } @@ -440,12 +438,10 @@ func NewSchema(schema *base.Schema) *Schema { if children > 0 { allDone: for { - select { - case <-polyCompletedChan: - completeChildren++ - if children == completeChildren { - break allDone - } + <-polyCompletedChan + completeChildren++ + if children == completeChildren { + break allDone } } } diff --git a/datamodel/high/v2/path_item_test.go b/datamodel/high/v2/path_item_test.go index a7fa8ebb..be79c360 100644 --- a/datamodel/high/v2/path_item_test.go +++ b/datamodel/high/v2/path_item_test.go @@ -9,7 +9,6 @@ import ( "github.com/pb33f/libopenapi/datamodel/low" lowV2 "github.com/pb33f/libopenapi/datamodel/low/v2" - v2 "github.com/pb33f/libopenapi/datamodel/low/v2" "github.com/pb33f/libopenapi/index" "github.com/pb33f/libopenapi/orderedmap" "github.com/stretchr/testify/assert" @@ -37,7 +36,7 @@ options: _ = yaml.Unmarshal([]byte(yml), &idxNode) idx := index.NewSpecIndex(&idxNode) - var n v2.PathItem + var n lowV2.PathItem _ = low.BuildModel(&idxNode, &n) _ = n.Build(context.Background(), nil, idxNode.Content[0], idx) @@ -85,10 +84,10 @@ func TestPathItem_GetOperations_LowWithUnsetOperations(t *testing.T) { func TestPathItem_NewPathItem_WithParameters(t *testing.T) { pi := NewPathItem(&lowV2.PathItem{ - Parameters: low.NodeReference[[]low.ValueReference[*v2.Parameter]]{ - Value: []low.ValueReference[*v2.Parameter]{ + Parameters: low.NodeReference[[]low.ValueReference[*lowV2.Parameter]]{ + Value: []low.ValueReference[*lowV2.Parameter]{ { - Value: &v2.Parameter{}, + Value: &lowV2.Parameter{}, }, }, ValueNode: &yaml.Node{}, diff --git a/datamodel/high/v3/components.go b/datamodel/high/v3/components.go index db155b0b..d7796efe 100644 --- a/datamodel/high/v3/components.go +++ b/datamodel/high/v3/components.go @@ -129,8 +129,7 @@ func buildComponent[IN any, OUT any](inMap *orderedmap.Map[lowmodel.KeyReference func buildSchema(inMap *orderedmap.Map[lowmodel.KeyReference[string], lowmodel.ValueReference[*base.SchemaProxy]], outMap *orderedmap.Map[string, *highbase.SchemaProxy]) { translateFunc := func(pair orderedmap.Pair[lowmodel.KeyReference[string], lowmodel.ValueReference[*base.SchemaProxy]]) (componentResult[*highbase.SchemaProxy], error) { value := pair.Value() - var sch *highbase.SchemaProxy - sch = highbase.NewSchemaProxy(&lowmodel.NodeReference[*base.SchemaProxy]{ + sch := highbase.NewSchemaProxy(&lowmodel.NodeReference[*base.SchemaProxy]{ Value: value.Value, ValueNode: value.ValueNode, }) diff --git a/datamodel/high/v3/oauth_flow_test.go b/datamodel/high/v3/oauth_flow_test.go index ea112ba4..f0305283 100644 --- a/datamodel/high/v3/oauth_flow_test.go +++ b/datamodel/high/v3/oauth_flow_test.go @@ -26,6 +26,7 @@ func TestOAuthFlow_MarshalYAML(t *testing.T) { } rend, _ := oflow.Render() + assert.NotNil(t, rend) desired := `authorizationUrl: https://pb33f.io tokenUrl: https://pb33f.io/token diff --git a/datamodel/high/v3/path_item.go b/datamodel/high/v3/path_item.go index df8b4df9..dedc005a 100644 --- a/datamodel/high/v3/path_item.go +++ b/datamodel/high/v3/path_item.go @@ -95,27 +95,26 @@ func NewPathItem(pathItem *lowV3.PathItem) *PathItem { complete := false opCount := 0 for !complete { - select { - case opRes := <-opChan: - switch opRes.method { - case get: - pi.Get = opRes.op - case put: - pi.Put = opRes.op - case post: - pi.Post = opRes.op - case del: - pi.Delete = opRes.op - case options: - pi.Options = opRes.op - case head: - pi.Head = opRes.op - case patch: - pi.Patch = opRes.op - case trace: - pi.Trace = opRes.op - } + opRes := <-opChan + switch opRes.method { + case get: + pi.Get = opRes.op + case put: + pi.Put = opRes.op + case post: + pi.Post = opRes.op + case del: + pi.Delete = opRes.op + case options: + pi.Options = opRes.op + case head: + pi.Head = opRes.op + case patch: + pi.Patch = opRes.op + case trace: + pi.Trace = opRes.op } + opCount++ if opCount == 8 { complete = true diff --git a/datamodel/high/v3/path_item_test.go b/datamodel/high/v3/path_item_test.go index 36619ba9..06986b63 100644 --- a/datamodel/high/v3/path_item_test.go +++ b/datamodel/high/v3/path_item_test.go @@ -10,7 +10,6 @@ import ( "github.com/pb33f/libopenapi/datamodel/low" lowV3 "github.com/pb33f/libopenapi/datamodel/low/v3" - v3 "github.com/pb33f/libopenapi/datamodel/low/v3" "github.com/pb33f/libopenapi/index" "github.com/pb33f/libopenapi/orderedmap" "github.com/stretchr/testify/assert" @@ -29,7 +28,7 @@ func TestPathItem(t *testing.T) { _ = yaml.Unmarshal([]byte(yml), &idxNode) idx := index.NewSpecIndex(&idxNode) - var n v3.PathItem + var n lowV3.PathItem _ = low.BuildModel(&idxNode, &n) _ = n.Build(context.Background(), nil, idxNode.Content[0], idx) @@ -63,7 +62,7 @@ trace: _ = yaml.Unmarshal([]byte(yml), &idxNode) idx := index.NewSpecIndex(&idxNode) - var n v3.PathItem + var n lowV3.PathItem _ = low.BuildModel(&idxNode, &n) _ = n.Build(context.Background(), nil, idxNode.Content[0], idx) diff --git a/datamodel/low/base/example_test.go b/datamodel/low/base/example_test.go index d7ba2e1c..4858650f 100644 --- a/datamodel/low/base/example_test.go +++ b/datamodel/low/base/example_test.go @@ -62,6 +62,7 @@ x-cake: hot` var example string err = n.Value.Value.Decode(&example) + require.NoError(t, err) assert.Equal(t, "a string example", example) var xCake string diff --git a/datamodel/low/base/license_test.go b/datamodel/low/base/license_test.go index 173825ba..d91747e1 100644 --- a/datamodel/low/base/license_test.go +++ b/datamodel/low/base/license_test.go @@ -70,6 +70,7 @@ description: the ranch` // create low level objects var lDoc License err := low.BuildModel(lNode.Content[0], &lDoc) + assert.NoError(t, err) err = lDoc.Build(context.Background(), nil, lNode.Content[0], nil) diff --git a/datamodel/low/base/schema.go b/datamodel/low/base/schema.go index 9fdcd084..2d58fc03 100644 --- a/datamodel/low/base/schema.go +++ b/datamodel/low/base/schema.go @@ -1134,15 +1134,13 @@ func buildSchema(ctx context.Context, schemas chan schemaProxyBuildResult, label // this only runs once, however to keep things consistent, it makes sense to use the same async method // that arrays will use. go build(foundCtx, labelNode, valueNode, refNode, -1, syncChan, isRef, refLocation) - select { - case r := <-syncChan: - schemas <- schemaProxyBuildResult{ - k: low.KeyReference[string]{ - KeyNode: labelNode, - Value: labelNode.Value, - }, - v: *r.res, - } + r := <-syncChan + schemas <- schemaProxyBuildResult{ + k: low.KeyReference[string]{ + KeyNode: labelNode, + Value: labelNode.Value, + }, + v: *r.res, } } else if utils.IsNodeArray(valueNode) { refBuilds := 0 @@ -1171,11 +1169,9 @@ func buildSchema(ctx context.Context, schemas chan schemaProxyBuildResult, label completedBuilds := 0 for completedBuilds < refBuilds { - select { - case res := <-syncChan: - completedBuilds++ - results[res.idx] = res.res - } + res := <-syncChan + completedBuilds++ + results[res.idx] = res.res } for _, r := range results { @@ -1225,14 +1221,14 @@ func ExtractSchema(ctx context.Context, root *yaml.Node, idx *index.SpecIndex) ( if schNode != nil { h := false if h, _, refLocation = utils.IsNodeRefValue(schNode); h { - ref, foundIdx, _, nCtx := low.LocateRefNodeWithContext(ctx, schNode, idx) + ref, _, _, nCtx := low.LocateRefNodeWithContext(ctx, schNode, idx) if ref != nil { refNode = schNode schNode = ref - if foundIdx != nil { - // TODO: check on this - // idx = foundIdx - } + //if foundIdx != nil { + // TODO: check on this + // idx = foundIdx + //} ctx = nCtx } else { v := schNode.Content[1].Value diff --git a/datamodel/low/base/schema_proxy_test.go b/datamodel/low/base/schema_proxy_test.go index 698d38e7..aaf0549f 100644 --- a/datamodel/low/base/schema_proxy_test.go +++ b/datamodel/low/base/schema_proxy_test.go @@ -150,6 +150,7 @@ properties: // do it again, but with no index err = schC.Build(context.Background(), nil, idxNodeA.Content[0], nil) + assert.NoError(t, err) origin = schC.GetSchemaReferenceLocation() assert.Nil(t, origin) } diff --git a/datamodel/low/base/schema_test.go b/datamodel/low/base/schema_test.go index 3f9090d0..b3f2ee94 100644 --- a/datamodel/low/base/schema_test.go +++ b/datamodel/low/base/schema_test.go @@ -1876,11 +1876,9 @@ func TestBuildSchema_BadNodeTypes(t *testing.T) { var err error go func() { for { - select { - case e := <-eChan: - err = e - doneChan <- true - } + e := <-eChan + err = e + doneChan <- true } }() diff --git a/datamodel/low/extraction_functions.go b/datamodel/low/extraction_functions.go index 376e4da4..1a38e149 100644 --- a/datamodel/low/extraction_functions.go +++ b/datamodel/low/extraction_functions.go @@ -599,6 +599,11 @@ type mappingResult[T any] struct { v ValueReference[T] } +type buildInput struct { + label *yaml.Node + value *yaml.Node +} + // ExtractMapExtensions will extract a map of KeyReference and ValueReference from a root yaml.Node. The 'label' is // used to locate the node to be extracted from the root node supplied. Supply a bit to decide if extensions should // be included or not. required in some use cases. @@ -655,10 +660,6 @@ func ExtractMapExtensions[PT Buildable[N], N any]( if valueNode != nil { valueMap := orderedmap.New[KeyReference[string], ValueReference[PT]]() - type buildInput struct { - label *yaml.Node - value *yaml.Node - } in := make(chan buildInput) out := make(chan mappingResult[PT]) done := make(chan struct{}) diff --git a/datamodel/low/extraction_functions_test.go b/datamodel/low/extraction_functions_test.go index 16d63100..6a03a698 100644 --- a/datamodel/low/extraction_functions_test.go +++ b/datamodel/low/extraction_functions_test.go @@ -331,14 +331,6 @@ func TestExtractObject_DoubleRef_Circular_Direct_Fail(t *testing.T) { assert.Error(t, err) } -type test_borked struct { - DontWork int -} - -func (t test_borked) Build(_ context.Context, _, root *yaml.Node, idx *index.SpecIndex) error { - return fmt.Errorf("I am always going to fail, every thing") -} - type test_noGood struct { DontWork int } @@ -1898,11 +1890,11 @@ func TestLocateRefNode_DoARealLookup(t *testing.T) { func TestLocateRefEndNoRef_NoName(t *testing.T) { r := &yaml.Node{Content: []*yaml.Node{{Kind: yaml.ScalarNode, Value: "$ref"}, {Kind: yaml.ScalarNode, Value: ""}}} - n, i, e, c := LocateRefEnd(nil, r, nil, 0) + n, i, e, c := LocateRefEnd(context.TODO(), r, nil, 0) assert.Nil(t, n) assert.Nil(t, i) assert.Error(t, e) - assert.Nil(t, c) + assert.NotNil(t, c) } func TestLocateRefEndNoRef(t *testing.T) { @@ -1916,11 +1908,11 @@ func TestLocateRefEndNoRef(t *testing.T) { func TestLocateRefEnd_TooDeep(t *testing.T) { r := &yaml.Node{Content: []*yaml.Node{{Kind: yaml.ScalarNode, Value: "$ref"}, {Kind: yaml.ScalarNode, Value: ""}}} - n, i, e, c := LocateRefEnd(nil, r, nil, 100) + n, i, e, c := LocateRefEnd(context.TODO(), r, nil, 100) assert.Nil(t, n) assert.Nil(t, i) assert.Error(t, e) - assert.Nil(t, c) + assert.NotNil(t, c) } func TestLocateRefEnd_Loop(t *testing.T) { diff --git a/datamodel/low/model_builder.go b/datamodel/low/model_builder.go index 4e74a61d..c81ca6e4 100644 --- a/datamodel/low/model_builder.go +++ b/datamodel/low/model_builder.go @@ -448,7 +448,6 @@ func SetField(field *reflect.Value, valueNode *yaml.Node, keyNode *yaml.Node) { // we want to ignore everything else, each model handles its own complex types. break } - return } // BuildModelAsync is a convenience function for calling BuildModel from a goroutine, requires a sync.WaitGroup diff --git a/datamodel/low/model_builder_test.go b/datamodel/low/model_builder_test.go index cd4ef19b..54916470 100644 --- a/datamodel/low/model_builder_test.go +++ b/datamodel/low/model_builder_test.go @@ -365,7 +365,6 @@ func TestHandleSlicesOfBools(t *testing.T) { func TestSetField_Ignore(t *testing.T) { type Complex struct { - name string } type internal struct { Thing *Complex diff --git a/datamodel/low/v2/path_item.go b/datamodel/low/v2/path_item.go index 0bc287a0..edd3e59c 100644 --- a/datamodel/low/v2/path_item.go +++ b/datamodel/low/v2/path_item.go @@ -105,19 +105,12 @@ func (p *PathItem) Build(ctx context.Context, _, root *yaml.Node, idx *index.Spe // the only thing we now care about is handling operations, filter out anything that's not a verb. switch currentNode.Value { case GetLabel: - break case PostLabel: - break case PutLabel: - break case PatchLabel: - break case DeleteLabel: - break case HeadLabel: - break case OptionsLabel: - break default: continue // ignore everything else. } diff --git a/datamodel/low/v3/path_item.go b/datamodel/low/v3/path_item.go index 4d8457ba..bee97128 100644 --- a/datamodel/low/v3/path_item.go +++ b/datamodel/low/v3/path_item.go @@ -177,21 +177,13 @@ func (p *PathItem) Build(ctx context.Context, keyNode, root *yaml.Node, idx *ind // the only thing we now care about is handling operations, filter out anything that's not a verb. switch currentNode.Value { case GetLabel: - break case PostLabel: - break case PutLabel: - break case PatchLabel: - break case DeleteLabel: - break case HeadLabel: - break case OptionsLabel: - break case TraceLabel: - break default: continue // ignore everything else. } diff --git a/datamodel/low/v3/response_test.go b/datamodel/low/v3/response_test.go index 1fced164..8c67b3d8 100644 --- a/datamodel/low/v3/response_test.go +++ b/datamodel/low/v3/response_test.go @@ -96,6 +96,7 @@ x-shoes: old` assert.NoError(t, err) err = n.Build(context.Background(), nil, idxNode.Content[0], idx) + assert.NoError(t, err) // check hash assert.Equal(t, "3da5051dcd82a06f8e4c7698cdec03550ae1988ee54d96d4c4a90a5c8f9d7b2b", diff --git a/document_test.go b/document_test.go index bc3e5237..329579a6 100644 --- a/document_test.go +++ b/document_test.go @@ -957,11 +957,6 @@ func BenchmarkReferenceOrigin(b *testing.B) { items := mediaType.A.Schema() origin := items.ParentProxy.GetReferenceOrigin() - if origin == nil { - // fmt.Println("nil origin") - } else { - // fmt.Println(origin.AbsoluteLocation) - } assert.NotNil(b, origin) assert.True(b, strings.HasSuffix(origin.AbsoluteLocation, "test_specs/burgershop.openapi.yaml")) } diff --git a/index/extract_refs.go b/index/extract_refs.go index bcae9dc9..aa0e20d9 100644 --- a/index/extract_refs.go +++ b/index/extract_refs.go @@ -9,7 +9,6 @@ import ( "net/url" "os" "path/filepath" - "regexp" "strings" "github.com/pb33f/libopenapi/utils" @@ -17,8 +16,6 @@ import ( "gopkg.in/yaml.v3" ) -var windowsDriveDetector = regexp.MustCompile(`^([a-zA-Z]:)`) - // ExtractRefs will return a deduplicated slice of references for every unique ref found in the document. // The total number of refs, will generally be much higher, you can extract those from GetRawReferenceCount() func (index *SpecIndex) ExtractRefs(node, parent *yaml.Node, seenPath []string, level int, poly bool, pName string) []*Reference { @@ -108,7 +105,7 @@ func (index *SpecIndex) ExtractRefs(node, parent *yaml.Node, seenPath []string, skip = true break } - // look for any extension in the path that begins with 'x-' + // look for any extension in the path and ignore it if strings.HasPrefix(p, "x-") { skip = true break @@ -638,9 +635,8 @@ func (index *SpecIndex) ExtractComponentsFromRefs(refs []*Reference) []*Referenc } var refsToCheck []*Reference - for _, ref := range refs { - refsToCheck = append(refsToCheck, ref) - } + refsToCheck = append(refsToCheck, refs...) + mappedRefsInSequence := make([]*ReferenceMapped, len(refsToCheck)) for r := range refsToCheck { diff --git a/index/map_index_nodes.go b/index/map_index_nodes.go index cdf62607..596aeeaa 100644 --- a/index/map_index_nodes.go +++ b/index/map_index_nodes.go @@ -49,18 +49,18 @@ func (index *SpecIndex) MapNodes(rootNode *yaml.Node) { cruising := make(chan bool) nodeChan := make(chan *nodeMap) go func(nodeChan chan *nodeMap) { - for { - select { - case node, ok := <-nodeChan: - if !ok { - cruising <- true - return - } - if index.nodeMap[node.line] == nil { - index.nodeMap[node.line] = make(map[int]*yaml.Node) - } - index.nodeMap[node.line][node.column] = node.node + done := false + for !done { + node, ok := <-nodeChan + if !ok { + done = true + cruising <- true + return } + if index.nodeMap[node.line] == nil { + index.nodeMap[node.line] = make(map[int]*yaml.Node) + } + index.nodeMap[node.line][node.column] = node.node } }(nodeChan) go enjoyALuxuryCruise(rootNode, nodeChan, true) diff --git a/index/rolodex.go b/index/rolodex.go index 42df2ad2..01ed9b81 100644 --- a/index/rolodex.go +++ b/index/rolodex.go @@ -72,7 +72,6 @@ type Rolodex struct { infiniteCircularReferences []*CircularReferenceResult ignoredCircularReferences []*CircularReferenceResult logger *slog.Logger - rolodex *Rolodex } // NewRolodex creates a new rolodex with the provided index configuration. diff --git a/index/rolodex_file_loader.go b/index/rolodex_file_loader.go index 0953f44e..3ded3e5e 100644 --- a/index/rolodex_file_loader.go +++ b/index/rolodex_file_loader.go @@ -12,7 +12,6 @@ import ( "path/filepath" "slices" "strings" - "sync" "time" "github.com/pb33f/libopenapi/datamodel" @@ -29,11 +28,9 @@ type LocalFS struct { Files syncmap.Map extractedFiles map[string]RolodexFile logger *slog.Logger - fileLock sync.Mutex readingErrors []error rolodex *Rolodex processingFiles syncmap.Map - fileListeners int } // GetFiles returns the files that have been indexed. A map of RolodexFile objects keyed by the full path of the file. @@ -416,7 +413,6 @@ func (l *LocalFS) extractFile(p string) (*LocalFile, error) { // if reading without a directory FS, error out on any error, do not continue. if fileError != nil { - readingErrors = append(readingErrors, fileError) return nil, fileError } diff --git a/index/rolodex_file_loader_test.go b/index/rolodex_file_loader_test.go index f121e0e3..116a3919 100644 --- a/index/rolodex_file_loader_test.go +++ b/index/rolodex_file_loader_test.go @@ -313,8 +313,6 @@ func TestRecursiveLocalFile_MultipleRequests(t *testing.T) { run := func(i int) { fox, fErr := rolo.Open("fox.yaml") assert.NoError(t, fErr) - if fox == nil { - } assert.NotNil(t, fox) c <- fox } @@ -325,9 +323,7 @@ func TestRecursiveLocalFile_MultipleRequests(t *testing.T) { completed := 0 for completed < 10 { - select { - case <-c: - completed++ - } + <-c + completed++ } } diff --git a/index/rolodex_test.go b/index/rolodex_test.go index 18d43517..e07febb0 100644 --- a/index/rolodex_test.go +++ b/index/rolodex_test.go @@ -673,7 +673,7 @@ components: first = strings.ReplaceAll(strings.ReplaceAll(first, "$2", secondFile.Name()), "\\", "\\\\") second = strings.ReplaceAll(strings.ReplaceAll(second, "$3", thirdFile.Name()), "\\", "\\\\") third = strings.ReplaceAll(strings.ReplaceAll(third, "$4", filepath.Base(fourthFile.Name())), "\\", "\\\\") - third = strings.ReplaceAll(strings.ReplaceAll(first, "$1", filepath.Base(firstFile.Name())), "\\", "\\\\") + fourth = strings.ReplaceAll(strings.ReplaceAll(first, "$1", filepath.Base(firstFile.Name())), "\\", "\\\\") firstFile.WriteString(first) secondFile.WriteString(second) diff --git a/index/search_rolodex.go b/index/search_rolodex.go index 9178f27a..c18d3320 100644 --- a/index/search_rolodex.go +++ b/index/search_rolodex.go @@ -20,7 +20,7 @@ func (r *Rolodex) FindNodeOrigin(node *yaml.Node) *NodeOrigin { } d <- true } - for i, _ := range r.indexes { + for i := range r.indexes { go findNode(i, node) } searched := 0 diff --git a/index/search_rolodex_test.go b/index/search_rolodex_test.go index dde76103..313ab626 100644 --- a/index/search_rolodex_test.go +++ b/index/search_rolodex_test.go @@ -41,6 +41,7 @@ func TestRolodex_FindNodeOrigin(t *testing.T) { rolo.SetRootNode(node) err = rolo.IndexTheRolodex() + assert.NoError(t, err) rolo.Resolve() assert.Len(t, rolo.indexes, 4) @@ -109,6 +110,7 @@ func TestRolodex_FindNodeOrigin_ModifyLookup(t *testing.T) { rolo.SetRootNode(node) err = rolo.IndexTheRolodex() + assert.NoError(t, err) rolo.Resolve() assert.Len(t, rolo.indexes, 4) diff --git a/index/utility_methods_test.go b/index/utility_methods_test.go index 41dd87c2..d61a8021 100644 --- a/index/utility_methods_test.go +++ b/index/utility_methods_test.go @@ -113,8 +113,6 @@ func Test_extractRequiredReferenceProperties_abs3(t *testing.T) { assert.Len(t, props, 1) if runtime.GOOS != "windows" { assert.Equal(t, "cakes", props["/big/fat/oh/pillow.yaml"][0]) - } else { - // assert.Equal(t, "cakes", props["C:\\big\\fat\\oh\\pillow.yaml"][0]) drive could be anything } assert.NotNil(t, data) } @@ -131,8 +129,6 @@ func Test_extractRequiredReferenceProperties_rel_full(t *testing.T) { assert.Len(t, props, 1) if runtime.GOOS != "windows" { assert.Equal(t, "cakes", props["/chalky/milky/camel.yaml#/a/nice/picture/of/cake"][0]) - } else { - //assert.Equal(t, "cakes", props["C:\\chalky\\milky\\camel.yaml#/a/nice/picture/of/cake"][0]) } assert.NotNil(t, data) } @@ -149,9 +145,6 @@ func Test_extractRequiredReferenceProperties_rel(t *testing.T) { assert.Len(t, props, 1) if runtime.GOOS != "windows" { assert.Equal(t, "cakes", props["/oh/camel.yaml#/rum/cake"][0]) - } else { - //cwd, _ := os.Getwd() - //assert.Equal(t, "cakes", props[filepath.Dir(cwd)+"\\oh\\camel.yaml#/rum/cake"][0]) } assert.NotNil(t, data) } @@ -168,9 +161,6 @@ func Test_extractRequiredReferenceProperties_abs2(t *testing.T) { assert.Len(t, props, 1) if runtime.GOOS != "windows" { assert.Equal(t, "cakes", props["/oh/my/camel.yaml#/rum/cake"][0]) - } else { - //cwd, _ := os.Getwd() - //assert.Equal(t, "cakes", props[filepath.Dir(cwd)+"\\oh\\my\\camel.yaml#/rum/cake"][0]) } assert.NotNil(t, data) } @@ -257,8 +247,6 @@ func Test_extractRequiredReferenceProperties_nocomponent_http2(t *testing.T) { assert.Len(t, props, 1) if runtime.GOOS != "windows" { assert.Equal(t, "cakes", props["/go-to-bed.com/no/more/cake.yaml"][0]) - } else { - //assert.Equal(t, "cakes", props["C:\\go-to-bed.com\\no\\more\\cake.yaml"][0]) } assert.NotNil(t, data) } diff --git a/renderer/mock_generator.go b/renderer/mock_generator.go index 32bebf94..ad560acf 100644 --- a/renderer/mock_generator.go +++ b/renderer/mock_generator.go @@ -177,9 +177,7 @@ func (mg *MockGenerator) GenerateMock(mock any, name string) ([]byte, error) { // render the schema as our last hope. renderMap := mg.renderer.RenderSchema(schemaValue) - if renderMap != nil { - return mg.renderMock(renderMap), nil - } + return mg.renderMock(renderMap), nil } return nil, nil } diff --git a/renderer/mock_generator_test.go b/renderer/mock_generator_test.go index 9519773c..c67d0383 100644 --- a/renderer/mock_generator_test.go +++ b/renderer/mock_generator_test.go @@ -6,29 +6,27 @@ package renderer import ( "context" "encoding/json" - "strings" - "testing" - "github.com/pb33f/libopenapi/datamodel/high/base" - highbase "github.com/pb33f/libopenapi/datamodel/high/base" "github.com/pb33f/libopenapi/datamodel/low" lowbase "github.com/pb33f/libopenapi/datamodel/low/base" "github.com/pb33f/libopenapi/orderedmap" "github.com/pb33f/libopenapi/utils" "github.com/stretchr/testify/assert" "gopkg.in/yaml.v3" + "strings" + "testing" ) type fakeMockable struct { - Schema *highbase.SchemaProxy + Schema *base.SchemaProxy Example any - Examples *orderedmap.Map[string, *highbase.Example] + Examples *orderedmap.Map[string, *base.Example] } type fakeMockableButWithASchemaNotAProxy struct { - Schema *highbase.Schema + Schema *base.Schema Example any - Examples *orderedmap.Map[string, *highbase.Example] + Examples *orderedmap.Map[string, *base.Example] } var simpleFakeMockSchema = `type: string @@ -52,11 +50,11 @@ func createFakeMock(mock string, values map[string]any, example any) *fakeMockab lowRef := low.NodeReference[*lowbase.SchemaProxy]{ Value: &lowProxy, } - highSchema := highbase.NewSchemaProxy(&lowRef) - examples := orderedmap.New[string, *highbase.Example]() + highSchema := base.NewSchemaProxy(&lowRef) + examples := orderedmap.New[string, *base.Example]() for k, v := range values { - examples.Set(k, &highbase.Example{ + examples.Set(k, &base.Example{ Value: utils.CreateYamlNode(v), }) } @@ -75,11 +73,11 @@ func createFakeMockWithoutProxy(mock string, values map[string]any, example any) lowRef := low.NodeReference[*lowbase.SchemaProxy]{ Value: &lowProxy, } - highSchema := highbase.NewSchemaProxy(&lowRef) - examples := orderedmap.New[string, *highbase.Example]() + highSchema := base.NewSchemaProxy(&lowRef) + examples := orderedmap.New[string, *base.Example]() for k, v := range values { - examples.Set(k, &highbase.Example{ + examples.Set(k, &base.Example{ Value: utils.CreateYamlNode(v), }) } @@ -104,7 +102,6 @@ func TestMockGenerator_GenerateJSONMock_NoObject(t *testing.T) { mg := NewMockGenerator(JSON) var isNil any - isNil = nil mock, err := mg.GenerateMock(isNil, "") assert.NoError(t, err) @@ -113,7 +110,6 @@ func TestMockGenerator_GenerateJSONMock_NoObject(t *testing.T) { func TestMockGenerator_GenerateJSONMock_BadObject(t *testing.T) { type NotMockable struct { - pizza string } mg := NewMockGenerator(JSON) diff --git a/renderer/schema_renderer.go b/renderer/schema_renderer.go index 5f801e26..c0c4d350 100644 --- a/renderer/schema_renderer.go +++ b/renderer/schema_renderer.go @@ -86,7 +86,7 @@ func (wr *SchemaRenderer) RenderSchema(schema *base.Schema) any { // dive into the schema and render it structure := make(map[string]any) wr.DiveIntoSchema(schema, rootType, structure, 0) - return structure[rootType].(any) + return structure[rootType] } // DisableRequiredCheck will disable the required check when rendering a schema. This means that all properties @@ -171,12 +171,11 @@ func (wr *SchemaRenderer) DiveIntoSchema(schema *base.Schema, key string, struct case uuidType: structure[key] = wr.PseudoUUID() case byteType: - structure[key] = fmt.Sprintf("%x", wr.RandomWord(minLength, maxLength, 0)) + structure[key] = wr.RandomWord(minLength, maxLength, 0) case passwordType: - structure[key] = fmt.Sprintf("%s", wr.RandomWord(minLength, maxLength, 0)) + structure[key] = wr.RandomWord(minLength, maxLength, 0) case binaryType: - structure[key] = fmt.Sprintf("%s", - base64.StdEncoding.EncodeToString([]byte(wr.RandomWord(minLength, maxLength, 0)))) + structure[key] = base64.StdEncoding.EncodeToString([]byte(wr.RandomWord(minLength, maxLength, 0))) default: // if there is a pattern supplied, then try and generate a string from it. if schema.Pattern != "" { diff --git a/utils/type_check.go b/utils/type_check.go index aceee4bb..9cb962f8 100644 --- a/utils/type_check.go +++ b/utils/type_check.go @@ -17,10 +17,10 @@ func AreValuesCorrectlyTyped(valType string, values interface{}) map[string]stri results := make(map[string]string) for _, v := range arr { - switch v.(type) { + switch v := v.(type) { case string: if valType != "string" { - results[v.(string)] = fmt.Sprintf("enum value '%v' is a "+ + results[v] = fmt.Sprintf("enum value '%v' is a "+ "string, but it's defined as a '%v'", v, valType) } case int64: diff --git a/what-changed/model/comparison_functions.go b/what-changed/model/comparison_functions.go index cde10b9b..a83ead2f 100644 --- a/what-changed/model/comparison_functions.go +++ b/what-changed/model/comparison_functions.go @@ -340,10 +340,9 @@ func CheckMapForChangesWithComp[T any, R any](expLeft, expRight *orderedmap.Map[ // wait for all done signals. completed := 0 for completed < count { - select { - case <-doneChan: - completed++ - } + <-doneChan + completed++ + } return expChanges } diff --git a/what-changed/model/components.go b/what-changed/model/components.go index 125138fb..2ce2ee1c 100644 --- a/what-changed/model/components.go +++ b/what-changed/model/components.go @@ -184,22 +184,17 @@ func CompareComponents(l, r any) *ComponentsChanges { completedComponents := 0 for completedComponents < comparisons { - select { - case res := <-doneChan: - switch res.prop { - case v3.SchemasLabel: - completedComponents++ - cc.SchemaChanges = res.result.(map[string]*SchemaChanges) - break - case v3.SecuritySchemesLabel: - completedComponents++ - cc.SecuritySchemeChanges = res.result.(map[string]*SecuritySchemeChanges) - break - case v3.ResponsesLabel, v3.ParametersLabel, v3.ExamplesLabel, v3.RequestBodiesLabel, v3.HeadersLabel, - v3.LinksLabel, v3.CallbacksLabel: - completedComponents++ - break - } + res := <-doneChan + switch res.prop { + case v3.SchemasLabel: + completedComponents++ + cc.SchemaChanges = res.result.(map[string]*SchemaChanges) + case v3.SecuritySchemesLabel: + completedComponents++ + cc.SecuritySchemeChanges = res.result.(map[string]*SecuritySchemeChanges) + case v3.ResponsesLabel, v3.ParametersLabel, v3.ExamplesLabel, v3.RequestBodiesLabel, v3.HeadersLabel, + v3.LinksLabel, v3.CallbacksLabel: + completedComponents++ } } } diff --git a/what-changed/model/path_item.go b/what-changed/model/path_item.go index 8f2b0c1a..d5952f27 100644 --- a/what-changed/model/path_item.go +++ b/what-changed/model/path_item.go @@ -351,33 +351,25 @@ func compareSwaggerPathItem(lPath, rPath *v2.PathItem, changes *[]*Change, pc *P // collect up operations changes. completedOperations := 0 for completedOperations < totalOps { - select { - case n := <-opChan: - switch n.label { - case v3.GetLabel: - pc.GetChanges = n.changes - break - case v3.PutLabel: - pc.PutChanges = n.changes - break - case v3.PostLabel: - pc.PostChanges = n.changes - break - case v3.DeleteLabel: - pc.DeleteChanges = n.changes - break - case v3.OptionsLabel: - pc.OptionsChanges = n.changes - break - case v2.HeadLabel: - pc.HeadChanges = n.changes - break - case v2.PatchLabel: - pc.PatchChanges = n.changes - break - } - completedOperations++ + n := <-opChan + switch n.label { + case v3.GetLabel: + pc.GetChanges = n.changes + case v3.PutLabel: + pc.PutChanges = n.changes + case v3.PostLabel: + pc.PostChanges = n.changes + case v3.DeleteLabel: + pc.DeleteChanges = n.changes + case v3.OptionsLabel: + pc.OptionsChanges = n.changes + case v2.HeadLabel: + pc.HeadChanges = n.changes + case v2.PatchLabel: + pc.PatchChanges = n.changes } + completedOperations++ + } pc.ExtensionChanges = CompareExtensions(lPath.Extensions, rPath.Extensions) return props @@ -613,36 +605,26 @@ func compareOpenAPIPathItem(lPath, rPath *v3.PathItem, changes *[]*Change, pc *P // collect up operations changes. completedOperations := 0 for completedOperations < totalOps { - select { - case n := <-opChan: - switch n.label { - case v3.GetLabel: - pc.GetChanges = n.changes - break - case v3.PutLabel: - pc.PutChanges = n.changes - break - case v3.PostLabel: - pc.PostChanges = n.changes - break - case v3.DeleteLabel: - pc.DeleteChanges = n.changes - break - case v3.OptionsLabel: - pc.OptionsChanges = n.changes - break - case v3.HeadLabel: - pc.HeadChanges = n.changes - break - case v3.PatchLabel: - pc.PatchChanges = n.changes - break - case v3.TraceLabel: - pc.TraceChanges = n.changes - break - } - completedOperations++ + n := <-opChan + switch n.label { + case v3.GetLabel: + pc.GetChanges = n.changes + case v3.PutLabel: + pc.PutChanges = n.changes + case v3.PostLabel: + pc.PostChanges = n.changes + case v3.DeleteLabel: + pc.DeleteChanges = n.changes + case v3.OptionsLabel: + pc.OptionsChanges = n.changes + case v3.HeadLabel: + pc.HeadChanges = n.changes + case v3.PatchLabel: + pc.PatchChanges = n.changes + case v3.TraceLabel: + pc.TraceChanges = n.changes } + completedOperations++ } pc.ExtensionChanges = CompareExtensions(lPath.Extensions, rPath.Extensions) } diff --git a/what-changed/model/paths.go b/what-changed/model/paths.go index 517fe297..6095495e 100644 --- a/what-changed/model/paths.go +++ b/what-changed/model/paths.go @@ -122,10 +122,8 @@ func ComparePaths(l, r any) *PathsChanges { // wait for the things to be done. completedChecks := 0 for completedChecks < pathsChecked { - select { - case <-doneChan: - completedChecks++ - } + <-doneChan + completedChecks++ } if len(pathChanges) > 0 { pc.PathItemsChanges = pathChanges @@ -197,10 +195,8 @@ func ComparePaths(l, r any) *PathsChanges { // wait for the things to be done. completedChecks := 0 for completedChecks < pathsChecked { - select { - case <-doneChan: - completedChecks++ - } + <-doneChan + completedChecks++ } if len(pathChanges) > 0 { pc.PathItemsChanges = pathChanges diff --git a/what-changed/model/schema.go b/what-changed/model/schema.go index 18e9f600..0c481deb 100644 --- a/what-changed/model/schema.go +++ b/what-changed/model/schema.go @@ -415,10 +415,8 @@ func CompareSchemas(l, r *base.SchemaProxy) *SchemaChanges { totalChecks := totalProperties + depsTotal + patternsTotal + 3 completedChecks := 0 for completedChecks < totalChecks { - select { - case <-doneChan: - completedChecks++ - } + <-doneChan + completedChecks++ } } // done diff --git a/what-changed/model/schema_test.go b/what-changed/model/schema_test.go index 5737b61b..4c00ac93 100644 --- a/what-changed/model/schema_test.go +++ b/what-changed/model/schema_test.go @@ -175,7 +175,7 @@ func test_BuildDocv2(l, r string) (*v2.Swagger, *v2.Swagger) { var err error var leftDoc, rightDoc *v2.Swagger - leftDoc, err = v2.CreateDocumentFromConfig(leftInfo, datamodel.NewDocumentConfiguration()) + leftDoc, _ = v2.CreateDocumentFromConfig(leftInfo, datamodel.NewDocumentConfiguration()) rightDoc, err = v2.CreateDocumentFromConfig(rightInfo, datamodel.NewDocumentConfiguration()) uErr := utils.UnwrapErrors(err) diff --git a/what-changed/model/tags_test.go b/what-changed/model/tags_test.go index b7162aac..c84cebfd 100644 --- a/what-changed/model/tags_test.go +++ b/what-changed/model/tags_test.go @@ -33,8 +33,8 @@ tags: // create document (which will create our correct tags low level structures) lInfo, _ := datamodel.ExtractSpecInfo([]byte(left)) rInfo, _ := datamodel.ExtractSpecInfo([]byte(right)) - lDoc, _ := lowv3.CreateDocument(lInfo) - rDoc, _ := lowv3.CreateDocument(rInfo) + lDoc, _ := lowv3.CreateDocumentFromConfig(lInfo, datamodel.NewDocumentConfiguration()) + rDoc, _ := lowv3.CreateDocumentFromConfig(rInfo, datamodel.NewDocumentConfiguration()) // compare. changes := CompareTags(lDoc.Tags.Value, rDoc.Tags.Value) @@ -78,8 +78,8 @@ tags: // create document (which will create our correct tags low level structures) lInfo, _ := datamodel.ExtractSpecInfo([]byte(left)) rInfo, _ := datamodel.ExtractSpecInfo([]byte(right)) - lDoc, _ := lowv3.CreateDocument(lInfo) - rDoc, _ := lowv3.CreateDocument(rInfo) + lDoc, _ := lowv3.CreateDocumentFromConfig(lInfo, datamodel.NewDocumentConfiguration()) + rDoc, _ := lowv3.CreateDocumentFromConfig(rInfo, datamodel.NewDocumentConfiguration()) // compare. changes := CompareTags(lDoc.Tags.Value, rDoc.Tags.Value) @@ -112,8 +112,8 @@ tags: // create document (which will create our correct tags low level structures) lInfo, _ := datamodel.ExtractSpecInfo([]byte(left)) rInfo, _ := datamodel.ExtractSpecInfo([]byte(right)) - lDoc, _ := lowv3.CreateDocument(lInfo) - rDoc, _ := lowv3.CreateDocument(rInfo) + lDoc, _ := lowv3.CreateDocumentFromConfig(lInfo, datamodel.NewDocumentConfiguration()) + rDoc, _ := lowv3.CreateDocumentFromConfig(rInfo, datamodel.NewDocumentConfiguration()) // compare. changes := CompareTags(lDoc.Tags.Value, rDoc.Tags.Value) @@ -149,8 +149,8 @@ tags: // create document (which will create our correct tags low level structures) lInfo, _ := datamodel.ExtractSpecInfo([]byte(left)) rInfo, _ := datamodel.ExtractSpecInfo([]byte(right)) - lDoc, _ := lowv3.CreateDocument(lInfo) - rDoc, _ := lowv3.CreateDocument(rInfo) + lDoc, _ := lowv3.CreateDocumentFromConfig(lInfo, datamodel.NewDocumentConfiguration()) + rDoc, _ := lowv3.CreateDocumentFromConfig(rInfo, datamodel.NewDocumentConfiguration()) // compare. changes := CompareTags(lDoc.Tags.Value, rDoc.Tags.Value) @@ -183,8 +183,8 @@ tags: // create document (which will create our correct tags low level structures) lInfo, _ := datamodel.ExtractSpecInfo([]byte(left)) rInfo, _ := datamodel.ExtractSpecInfo([]byte(right)) - lDoc, _ := lowv3.CreateDocument(lInfo) - rDoc, _ := lowv3.CreateDocument(rInfo) + lDoc, _ := lowv3.CreateDocumentFromConfig(lInfo, datamodel.NewDocumentConfiguration()) + rDoc, _ := lowv3.CreateDocumentFromConfig(rInfo, datamodel.NewDocumentConfiguration()) // compare. changes := CompareTags(lDoc.Tags.Value, rDoc.Tags.Value) @@ -216,9 +216,8 @@ tags: // create document (which will create our correct tags low level structures) lInfo, _ := datamodel.ExtractSpecInfo([]byte(left)) rInfo, _ := datamodel.ExtractSpecInfo([]byte(right)) - lDoc, _ := lowv3.CreateDocument(lInfo) - rDoc, _ := lowv3.CreateDocument(rInfo) - + lDoc, _ := lowv3.CreateDocumentFromConfig(lInfo, datamodel.NewDocumentConfiguration()) + rDoc, _ := lowv3.CreateDocumentFromConfig(rInfo, datamodel.NewDocumentConfiguration()) // compare. changes := CompareTags(lDoc.Tags.Value, rDoc.Tags.Value) @@ -257,8 +256,8 @@ tags: // create document (which will create our correct tags low level structures) lInfo, _ := datamodel.ExtractSpecInfo([]byte(left)) rInfo, _ := datamodel.ExtractSpecInfo([]byte(right)) - lDoc, _ := lowv3.CreateDocument(lInfo) - rDoc, _ := lowv3.CreateDocument(rInfo) + lDoc, _ := lowv3.CreateDocumentFromConfig(lInfo, datamodel.NewDocumentConfiguration()) + rDoc, _ := lowv3.CreateDocumentFromConfig(rInfo, datamodel.NewDocumentConfiguration()) // compare. changes := CompareTags(lDoc.Tags.Value, rDoc.Tags.Value) @@ -284,8 +283,8 @@ tags: // create document (which will create our correct tags low level structures) lInfo, _ := datamodel.ExtractSpecInfo([]byte(left)) rInfo, _ := datamodel.ExtractSpecInfo([]byte(right)) - lDoc, _ := lowv3.CreateDocument(lInfo) - rDoc, _ := lowv3.CreateDocument(rInfo) + lDoc, _ := lowv3.CreateDocumentFromConfig(lInfo, datamodel.NewDocumentConfiguration()) + rDoc, _ := lowv3.CreateDocumentFromConfig(rInfo, datamodel.NewDocumentConfiguration()) // compare. changes := CompareTags(lDoc.Tags.Value, rDoc.Tags.Value) @@ -313,8 +312,8 @@ tags: // create document (which will create our correct tags low level structures) lInfo, _ := datamodel.ExtractSpecInfo([]byte(left)) rInfo, _ := datamodel.ExtractSpecInfo([]byte(right)) - lDoc, _ := lowv3.CreateDocument(lInfo) - rDoc, _ := lowv3.CreateDocument(rInfo) + lDoc, _ := lowv3.CreateDocumentFromConfig(lInfo, datamodel.NewDocumentConfiguration()) + rDoc, _ := lowv3.CreateDocumentFromConfig(rInfo, datamodel.NewDocumentConfiguration()) // compare. changes := CompareTags(rDoc.Tags.Value, lDoc.Tags.Value)