debian-forge-composer/internal/distroregistry/distroregistry.go
Ondřej Budai dd4db353e2 distro: move Registry to its own distroregistry package
My goal is to add a method to distroregistry to return Registry with
all supported distributions. This way, all supported distributions
would be defined only on one place.

To achieve this, the Registry must live outside the distro package
because the distro implementation depends on it and this would create
a circular dependency unsupported by Go.

Signed-off-by: Ondřej Budai <ondrej@budai.cz>
2021-03-12 08:29:30 +01:00

60 lines
1.2 KiB
Go

package distroregistry
import (
"errors"
"fmt"
"sort"
"github.com/osbuild/osbuild-composer/internal/distro"
)
type Registry struct {
distros map[string]distro.Distro
}
func New(distros ...distro.Distro) (*Registry, error) {
reg := &Registry{
distros: make(map[string]distro.Distro),
}
for _, d := range distros {
name := d.Name()
if _, exists := reg.distros[name]; exists {
return nil, fmt.Errorf("New: passed two distros with the same name: %s", d.Name())
}
reg.distros[name] = d
}
return reg, nil
}
func (r *Registry) GetDistro(name string) distro.Distro {
d, ok := r.distros[name]
if !ok {
return nil
}
return d
}
// List returns the names of all distros in a Registry, sorted alphabetically.
func (r *Registry) List() []string {
list := []string{}
for _, d := range r.distros {
list = append(list, d.Name())
}
sort.Strings(list)
return list
}
func (r *Registry) FromHost() (distro.Distro, bool, bool, error) {
name, beta, isStream, err := distro.GetHostDistroName()
if err != nil {
return nil, false, false, err
}
d := r.GetDistro(name)
if d == nil {
return nil, false, false, errors.New("unknown distro: " + name)
}
return d, beta, isStream, nil
}