Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor the registry system #235

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 82 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ reqwest = { version = "0.11", features = ["rustls-tls-native-roots"], default-fe
semver = { version = "1", features = ["serde"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
serde_with = "3.7"
tar = "0.4"
thiserror = "1.0.49"
tokio = { version = "^1.26", features = ["fs", "rt", "macros", "process", "io-std", "tracing"] }
Expand Down
95 changes: 95 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
// Copyright 2023 Helsing GmbH
//
// 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
//
// http://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 miette::{miette, Context, IntoDiagnostic};
use serde::{Deserialize, Serialize};
use std::{io::ErrorKind, path::PathBuf};
use tokio::fs;

use crate::{
errors::{DeserializationError, FileExistsError, ReadError, SerializationError, WriteError},
registry::RegistryTable,
ManagedFile,
};

/// Filename of the config file
pub const CONFIG_FILE: &str = "config.toml";

/// Configuration file for the buffrs cli
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Config {
/// A mapping from registry name to their corresponding uri
pub registry: Option<RegistryTable>,
}

impl Config {
fn location() -> PathBuf {
PathBuf::from("./.buffrs/").join(CONFIG_FILE)
}

/// Checks if the credentials exists
pub async fn exists() -> miette::Result<bool> {
fs::try_exists(Self::location())
.await
.into_diagnostic()
.wrap_err(FileExistsError(CONFIG_FILE))
}

/// Reads the credentials from the file system
pub async fn read() -> miette::Result<Option<Self>> {
// if the file does not exist, we don't need to treat it as an error.
match fs::read_to_string(Self::location()).await {
Ok(contents) => {
let raw = toml::from_str(&contents)
.into_diagnostic()
.wrap_err(DeserializationError(ManagedFile::Configuration))?;

Ok(Some(raw))
}
Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
Err(error) => Err(error)
.into_diagnostic()
.wrap_err(ReadError(CONFIG_FILE)),
}
}

/// Writes the credentials to the file system
pub async fn write(&self) -> miette::Result<()> {
let location = Self::location();

if let Some(parent) = location.parent() {
// if directory already exists, error is returned but that is fine
fs::create_dir(parent).await.ok();
}

fs::write(
location,
toml::to_string(&self)
.into_diagnostic()
.wrap_err(SerializationError(ManagedFile::Configuration))?
.into_bytes(),
)
.await
.into_diagnostic()
.wrap_err(WriteError(CONFIG_FILE))
}

/// Loads the config from the file system, returning an error if it doesnt exist
pub async fn load() -> miette::Result<Self> {
Self::read()
.await
.transpose()
.ok_or(miette!("missing configuration file"))?
}
}
16 changes: 8 additions & 8 deletions src/credentials.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use tokio::fs;

use crate::{
errors::{DeserializationError, FileExistsError, ReadError, SerializationError, WriteError},
registry::RegistryUri,
registry::Registry,
ManagedFile,
};

Expand All @@ -31,8 +31,8 @@ pub const CREDENTIALS_FILE: &str = "credentials.toml";
/// This type represents a snapshot of the read credential store.
#[derive(Debug, Default, Clone)]
pub struct Credentials {
/// A mapping from registry URIs to their corresponding tokens
pub registry_tokens: HashMap<RegistryUri, String>,
/// A mapping from registry to their corresponding tokens
pub tokens: HashMap<Registry, String>,
}

impl Credentials {
Expand Down Expand Up @@ -108,7 +108,7 @@ struct RawCredentialCollection {
/// Credentials for a single registry. Serialization type.
#[derive(Serialize, Deserialize)]
struct RawRegistryCredentials {
uri: RegistryUri,
registry: Registry,
token: String,
}

Expand All @@ -117,21 +117,21 @@ impl From<RawCredentialCollection> for Credentials {
let credentials = value
.credentials
.into_iter()
.map(|it| (it.uri, it.token))
.map(|it| (it.registry, it.token))
.collect();

Self {
registry_tokens: credentials,
tokens: credentials,
}
}
}

impl From<Credentials> for RawCredentialCollection {
fn from(value: Credentials) -> Self {
let credentials = value
.registry_tokens
.tokens
.into_iter()
.map(|(uri, token)| RawRegistryCredentials { uri, token })
.map(|(registry, token)| RawRegistryCredentials { registry, token })
.collect();

Self { credentials }
Expand Down
5 changes: 5 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ use thiserror::Error;
pub mod cache;
/// CLI command implementations
pub mod command;
/// Configuration for the CLI
pub mod config;
/// Credential management
pub mod credentials;
/// Common error types
Expand Down Expand Up @@ -63,18 +65,21 @@ fn home() -> Result<PathBuf, HomeError> {

#[derive(Debug)]
pub(crate) enum ManagedFile {
Configuration,
Credentials,
Manifest,
Lock,
}

impl ManagedFile {
fn name(&self) -> &str {
use config::CONFIG_FILE;
use credentials::CREDENTIALS_FILE;
use lock::LOCKFILE;
use manifest::MANIFEST_FILE;

match self {
ManagedFile::Configuration => CONFIG_FILE,
ManagedFile::Manifest => MANIFEST_FILE,
ManagedFile::Lock => LOCKFILE,
ManagedFile::Credentials => CREDENTIALS_FILE,
Expand Down
Loading
Loading