blob: dbad62852931a5445f096533517dfb82191b169d [file] [log] [blame]
// Copyright 2022 The Pigweed Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
use std::{collections::HashMap, sync::Arc};
use crate::target::{Provider, Target};
/// A database of packages known to `qg`.
#[derive(Debug)]
pub struct Registry {
/// Mapping of package slug to package. Slugs are globally unique.
targets: HashMap<String, Arc<Target>>,
/// All known package providers by name.
providers: HashMap<String, Provider>,
}
impl Registry {
/// Initializes an empty package registry.
#[must_use]
pub fn new() -> Self {
Self {
targets: HashMap::new(),
providers: HashMap::new(),
}
}
/// Returns the number of registered targets.
#[must_use]
pub fn target_count(&self) -> usize {
self.targets.len()
}
/// Returns an iterator over all known targets, in arbitrary order.
pub fn targets(&self) -> impl Iterator<Item = (&str, &Target)> {
self.targets
.iter()
.map(|(k, v)| (k.as_str(), Arc::as_ref(v)))
}
pub(crate) fn add_provider(&mut self, provider: Provider) -> bool {
self.providers
.insert(provider.name.clone(), provider)
.is_none()
}
pub(crate) fn add_target(&mut self, package: Target) -> bool {
let Some(provider) = self.providers.get(package.provider()) else {
return false;
};
let slug = if provider.global {
package.name().to_string()
} else {
format!("{}:{}", provider.name, package.name())
};
let target = Arc::new(package);
self.targets.insert(slug, target);
true
}
}
impl Default for Registry {
fn default() -> Self {
Self::new()
}
}