|
| 1 | +// Copyright 2025 MongoDB Inc |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package filter |
| 16 | + |
| 17 | +import ( |
| 18 | + "log" |
| 19 | + "maps" |
| 20 | + "strings" |
| 21 | + |
| 22 | + "github.com/getkin/kin-openapi/openapi3" |
| 23 | +) |
| 24 | + |
| 25 | +// SchemasFilter removes unused #/components/schemas/. |
| 26 | +type SchemasFilter struct { |
| 27 | + oas *openapi3.T |
| 28 | +} |
| 29 | + |
| 30 | +func (*SchemasFilter) ValidateMetadata() error { |
| 31 | + return nil |
| 32 | +} |
| 33 | + |
| 34 | +func (f *SchemasFilter) Apply() error { |
| 35 | + if f.oas.Paths == nil { |
| 36 | + return nil |
| 37 | + } |
| 38 | + |
| 39 | + for { |
| 40 | + oasSpecAsBytes, err := f.oas.MarshalJSON() |
| 41 | + if err != nil { |
| 42 | + return err |
| 43 | + } |
| 44 | + |
| 45 | + spec := string(oasSpecAsBytes) |
| 46 | + schemasToDelete := make([]string, 0) |
| 47 | + for k := range f.oas.Components.Schemas { |
| 48 | + ref := "#/components/schemas/" + k |
| 49 | + if !strings.Contains(spec, ref) { |
| 50 | + schemasToDelete = append(schemasToDelete, k) |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + if len(schemasToDelete) == 0 { |
| 55 | + return nil |
| 56 | + } |
| 57 | + |
| 58 | + for _, schemaToDelete := range schemasToDelete { |
| 59 | + log.Printf("Deleting unused schema: %q", schemaToDelete) |
| 60 | + maps.DeleteFunc(f.oas.Components.Schemas, func(k string, _ *openapi3.SchemaRef) bool { |
| 61 | + return k == schemaToDelete |
| 62 | + }) |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments