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

Add quetz upload command #429

Merged
merged 3 commits into from
Dec 19, 2023
Merged
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
68 changes: 68 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use tracing_subscriber::{
prelude::*,
EnvFilter,
};
use url::Url;

use rattler_build::{
build::run_build,
Expand All @@ -36,6 +37,7 @@ use rattler_build::{

mod console_utils;
mod rebuild;
mod upload;

use crate::console_utils::{IndicatifWriter, TracingFormatter};

Expand All @@ -49,6 +51,9 @@ enum SubCommands {

/// Rebuild a package
Rebuild(RebuildOpts),

/// Upload a package
Upload(UploadOpts),
}

#[derive(Parser)]
Expand Down Expand Up @@ -163,6 +168,42 @@ struct RebuildOpts {
common: CommonOpts,
}

#[derive(Parser)]
struct UploadOpts {
/// The package file to upload
#[clap(short, long)]
package_file: PathBuf,

/// The server type
#[clap(subcommand)]
server_type: ServerType,

#[clap(flatten)]
common: CommonOpts,
}

#[derive(Clone, Debug, PartialEq, Parser)]
enum ServerType {
Quetz(QuetzOpts),
}

#[derive(Clone, Debug, PartialEq, Parser)]
/// Options for uploading to a Quetz server
/// Authentication is used from the keychain / auth-file
struct QuetzOpts {
/// The URL to your Quetz server
#[arg(short, long, env = "QUETZ_SERVER_URL")]
url: Url,

/// The URL to your channel
#[arg(short, long, env = "QUETZ_CHANNEL")]
channel: String,

/// The quetz API key, if none is provided, the token is read from the keychain / auth-file
#[arg(short, long, env = "QUETZ_API_KEY")]
api_key: Option<String>,
}

#[tokio::main]
async fn main() -> miette::Result<()> {
let args = App::parse();
Expand All @@ -183,6 +224,7 @@ async fn main() -> miette::Result<()> {
SubCommands::Build(args) => run_build_from_args(args, multi_progress).await,
SubCommands::Test(args) => run_test_from_args(args).await,
SubCommands::Rebuild(args) => rebuild_from_args(args).await,
SubCommands::Upload(args) => upload_from_args(args).await,
}
}

Expand Down Expand Up @@ -498,6 +540,32 @@ async fn rebuild_from_args(args: RebuildOpts) -> miette::Result<()> {
Ok(())
}

async fn upload_from_args(args: UploadOpts) -> miette::Result<()> {
if ArchiveType::try_from(&args.package_file).is_none() {
return Err(miette::miette!(
"The file {} does not appear to be a conda package.",
args.package_file.to_string_lossy()
));
}

let store = get_auth_store(args.common.auth_file);

match args.server_type {
ServerType::Quetz(quetz_opts) => {
upload::upload_package_to_quetz(
&store,
quetz_opts.api_key,
args.package_file,
quetz_opts.url,
quetz_opts.channel,
)
.await?;
}
}

Ok(())
}

/// Constructs a default [`EnvFilter`] that is used when the user did not specify a custom RUST_LOG.
pub fn get_default_env_filter(
verbose: clap_verbosity_flag::LevelFilter,
Expand Down
72 changes: 72 additions & 0 deletions src/upload.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
use std::path::PathBuf;

use miette::IntoDiagnostic;
use rattler_networking::{redact_known_secrets_from_error, Authentication, AuthenticationStorage};
use reqwest::Method;
use sha2::Digest;
use tracing::info;
use url::Url;

pub async fn upload_package_to_quetz(
storage: &AuthenticationStorage,
api_key: Option<String>,
package_file: PathBuf,
url: Url,
channel: String,
) -> miette::Result<()> {
let token = match api_key {
Some(api_key) => api_key,
None => match storage.get_by_url(url.clone()) {
Ok((_, Some(Authentication::CondaToken(token)))) => token,
Ok((_, Some(_))) => {
return Err(miette::miette!("A Conda token is required for authentication with quetz.
Authentication information found in the keychain / auth file, but it was not a Conda token"));
}
Ok((_, None)) => {
return Err(miette::miette!(
"No quetz api key was given and none was found in the keychain / auth file"
));
}
Err(e) => {
return Err(miette::miette!(
"Failed to get authentication information form keychain: {e}"
));
}
},
};

let client = reqwest::Client::builder()
.no_gzip()
.build()
.expect("failed to create client");

let upload_url = url
.join(&format!(
"api/channels/{}/upload/{}",
channel,
package_file.file_name().unwrap().to_string_lossy()
))
.into_diagnostic()?;

let bytes = tokio::fs::read(package_file).await.into_diagnostic()?;
let upload_hash = sha2::Sha256::digest(&bytes);

let req = client
.request(Method::POST, upload_url)
.query(&[("force", "false"), ("sha256", &hex::encode(upload_hash))])
.body(bytes)
.header("X-API-Key", token)
.send()
.await
.map_err(redact_known_secrets_from_error)
.into_diagnostic()
.map_err(|e| miette::miette!("Sending package to Quetz server failed: {e}"))?;

req.error_for_status_ref()
.map_err(redact_known_secrets_from_error)
.into_diagnostic()
.map_err(|e| miette::miette!("Quetz server responded with error: {e}"))?;

info!("Package was successfully uploaded to Quetz server");
Ok(())
}