| // 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, HashSet}, |
| sync::Arc, |
| }; |
| |
| use crate::Package; |
| |
| /// A database of packages known to `qg`. |
| #[derive(Debug)] |
| pub struct Registry { |
| /// Mapping of package slug to package. Slugs are globally unique. |
| packages: HashMap<String, Arc<Package>>, |
| |
| /// Mapping of package name to packages. The same package can come form |
| /// multiple providers. |
| packages_by_name: HashMap<String, Vec<Arc<Package>>>, |
| |
| /// All known package providers by name. |
| /// TODO(frolv): Make this a map storing provider metadata. |
| providers: HashSet<String>, |
| } |
| |
| impl Registry { |
| /// Initializes an empty package registry. |
| #[must_use] |
| pub fn new() -> Self { |
| Self { |
| packages: HashMap::new(), |
| packages_by_name: HashMap::new(), |
| providers: HashSet::new(), |
| } |
| } |
| |
| /// Returns an iterator over all known packages grouped by package name. |
| pub fn packages_by_name(&self) -> impl Iterator<Item = (&str, Vec<&Package>)> { |
| self.packages_by_name |
| .iter() |
| .map(|(k, v)| (k.as_str(), v.iter().map(Arc::as_ref).collect())) |
| } |
| |
| pub(crate) fn add_provider(&mut self, name: &str) -> bool { |
| self.providers.insert(name.to_owned()) |
| } |
| |
| pub(crate) fn add_package(&mut self, package: Package) -> bool { |
| if !self.providers.contains(package.provider()) { |
| return false; |
| } |
| |
| let package = Arc::new(package); |
| self.packages |
| .insert(package.canonical_slug(), package.clone()); |
| |
| self.packages_by_name |
| .entry(package.name().into()) |
| .or_default() |
| .push(package); |
| |
| true |
| } |
| } |
| |
| impl Default for Registry { |
| fn default() -> Self { |
| Self::new() |
| } |
| } |