github.com/google/yamlfmt@v0.12.2-0.20240514121411-7f77800e2681/formatter.go (about)

     1  // Copyright 2024 Google LLC
     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 yamlfmt
    16  
    17  import "fmt"
    18  
    19  type Formatter interface {
    20  	Type() string
    21  	Format(yamlContent []byte) ([]byte, error)
    22  	ConfigMap() (map[string]any, error)
    23  }
    24  
    25  type Factory interface {
    26  	Type() string
    27  	NewFormatter(config map[string]interface{}) (Formatter, error)
    28  }
    29  
    30  type Registry struct {
    31  	registry    map[string]Factory
    32  	defaultType string
    33  }
    34  
    35  func NewFormatterRegistry(defaultFactory Factory) *Registry {
    36  	return &Registry{
    37  		registry: map[string]Factory{
    38  			defaultFactory.Type(): defaultFactory,
    39  		},
    40  		defaultType: defaultFactory.Type(),
    41  	}
    42  }
    43  
    44  func (r *Registry) Add(f Factory) {
    45  	r.registry[f.Type()] = f
    46  }
    47  
    48  func (r *Registry) GetFactory(fType string) (Factory, error) {
    49  	factory, ok := r.registry[fType]
    50  	if !ok {
    51  		return nil, fmt.Errorf("no formatter registered with type \"%s\"", fType)
    52  	}
    53  	return factory, nil
    54  }
    55  
    56  func (r *Registry) GetDefaultFactory() (Factory, error) {
    57  	factory, ok := r.registry[r.defaultType]
    58  	if !ok {
    59  		return nil, fmt.Errorf("no default formatter registered for type \"%s\"", r.defaultType)
    60  	}
    61  	return factory, nil
    62  }