🏡 index : ~doyle/gitlab-cargo-shim.git

author Jordan Doyle <jordan@doyle.la> 2022-03-12 17:22:26.0 +00:00:00
committer Jordan Doyle <jordan@doyle.la> 2022-03-12 17:22:26.0 +00:00:00
commit
6f6a60e29bee2af14768ec4e00b376d790167bcd [patch]
tree
0660a17e66ac8968fa4228497efb148f8375c2f0
parent
e57bc3cc9788eec12c300acb7cb86ae158d448cd
download
6f6a60e29bee2af14768ec4e00b376d790167bcd.tar.gz

#[deny(clippy::pedanic)]



Diff

 Cargo.lock                          |  2 +-
 Cargo.toml                          |  2 +-
 src/git_command_handlers/fetch.rs   |  4 ++--
 src/git_command_handlers/ls_refs.rs |  2 +-
 src/main.rs                         | 21 +++++++++++----------
 src/metadata.rs                     | 12 +++++++-----
 src/protocol/high_level.rs          |  2 +-
 src/protocol/low_level.rs           | 10 +++++-----
 src/protocol/packet_line.rs         |  2 +-
 src/providers/gitlab.rs             |  9 ++++++---
 src/util.rs                         |  2 ++
 11 files changed, 38 insertions(+), 30 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock
index fec55db..9b7c4d7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -510,7 +510,7 @@ dependencies = [
]

[[package]]
name = "git-server"
name = "gitlab-cargo-shim"
version = "0.1.0"
dependencies = [
 "anyhow",
diff --git a/Cargo.toml b/Cargo.toml
index 8352f2d..8535e83 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,5 +1,5 @@
[package]
name = "git-server"
name = "gitlab-cargo-shim"
version = "0.1.0"
edition = "2021"

diff --git a/src/git_command_handlers/fetch.rs b/src/git_command_handlers/fetch.rs
index d157996..583ec5c 100644
--- a/src/git_command_handlers/fetch.rs
+++ b/src/git_command_handlers/fetch.rs
@@ -13,8 +13,8 @@ pub fn handle<U: UserProvider + PackageProvider + Send + Sync + 'static>(
    handle: &mut Handler<U>,
    session: &mut Session,
    channel: ChannelId,
    metadata: Vec<Bytes>,
    packfile_entries: Vec<PackFileEntry>,
    metadata: &[Bytes],
    packfile_entries: &[PackFileEntry],
) -> Result<(), anyhow::Error> {
    // the client sending us `done` in the metadata means they know there's no negotiation
    // required for which commits we need to send, they just want us to send whatever we
diff --git a/src/git_command_handlers/ls_refs.rs b/src/git_command_handlers/ls_refs.rs
index 19da2de..4b77740 100644
--- a/src/git_command_handlers/ls_refs.rs
+++ b/src/git_command_handlers/ls_refs.rs
@@ -16,7 +16,7 @@ pub fn handle<U: UserProvider + PackageProvider + Send + Sync + 'static>(
    handle: &mut Handler<U>,
    session: &mut Session,
    channel: ChannelId,
    _metadata: Vec<Bytes>,
    _metadata: &[Bytes],
    commit_hash: &HashOutput,
) -> Result<(), anyhow::Error> {
    let commit_hash = hex::encode(&commit_hash);
diff --git a/src/main.rs b/src/main.rs
index 66472ff..83e315f 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,3 +1,6 @@
#![deny(clippy::pedantic)]
#![allow(clippy::missing_errors_doc)]

pub mod git_command_handlers;
pub mod metadata;
pub mod protocol;
@@ -6,6 +9,7 @@ pub mod util;

use crate::metadata::CargoIndexCrateMetadata;
use crate::protocol::low_level::{HashOutput, PackFileEntry};
use crate::providers::Group;
use crate::util::get_crate_folder;
use crate::{
    protocol::{
@@ -27,7 +31,6 @@ use thrussh::{
use thrussh_keys::key::PublicKey;
use tokio_util::{codec::Decoder, codec::Encoder as CodecEncoder};
use tracing::error;
use crate::providers::Group;

const AGENT: &str = concat!(
    "agent=",
@@ -56,7 +59,7 @@ async fn main() -> anyhow::Result<()> {
        "127.0.0.1:2210",
        Server {
            gitlab,
            metadata_cache: Arc::new(Default::default()),
            metadata_cache: MetadataCache::default(),
        },
    )
    .await?;
@@ -221,7 +224,7 @@ impl<U: UserProvider + PackageProvider + Send + Sync + 'static> Handler<U> {
                // parses the `cargo metadata` stored in the release, which
                // should be stored under `metadata.json`.
                let meta = self
                    .fetch_metadata(&crate_path, &checksum, &crate_name, &version)
                    .fetch_metadata(crate_path, checksum, crate_name, version)
                    .await?;

                buffer.extend_from_slice(&serde_json::to_vec(&*meta).unwrap());
@@ -229,7 +232,7 @@ impl<U: UserProvider + PackageProvider + Send + Sync + 'static> Handler<U> {
            }

            packfile.insert(
                get_crate_folder(&crate_name),
                get_crate_folder(crate_name),
                crate_name.to_string(),
                buffer.split().freeze(),
            )?;
@@ -320,7 +323,7 @@ impl<'a, U: UserProvider + PackageProvider + Send + Sync + 'static> thrussh::ser
                            &mut self,
                            &mut session,
                            channel,
                            frame.metadata,
                            &frame.metadata,
                            &commit_hash,
                        )?;
                    }
@@ -329,8 +332,8 @@ impl<'a, U: UserProvider + PackageProvider + Send + Sync + 'static> thrussh::ser
                            &mut self,
                            &mut session,
                            channel,
                            frame.metadata,
                            packfile_entries.clone(),
                            &frame.metadata,
                            &packfile_entries,
                        )?;
                    }
                    v => {
@@ -416,9 +419,7 @@ impl<'a, U: UserProvider + PackageProvider + Send + Sync + 'static> thrussh::ser
            // given to `git-upload-pack`)
            if let Some(group) = args.next().filter(|v| v.as_str() != "/") {
                let user = self.user()?;
                let group = group
                    .trim_start_matches('/')
                    .trim_end_matches('/');
                let group = group.trim_start_matches('/').trim_end_matches('/');

                match self.gitlab.clone().fetch_group(group, user).await {
                    Ok(v) => self.group = Some(v),
diff --git a/src/metadata.rs b/src/metadata.rs
index 9b35137..a359e56 100644
--- a/src/metadata.rs
+++ b/src/metadata.rs
@@ -1,10 +1,13 @@
#![allow(clippy::module_name_repetitions)]

use cargo_metadata::Package;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Transforms metadata from `cargo metadata` to the standard one-line JSON used in cargo registries.
///
/// https://github.com/rust-lang/cargo/blob/3bc0e6d83f7f5da0161ce445f8864b0b639776a9/src/cargo/ops/registry.rs#L183
/// <https://github.com/rust-lang/cargo/blob/3bc0e6d83f7f5da0161ce445f8864b0b639776a9/src/cargo/ops/registry.rs#L183>
#[must_use]
pub fn transform(
    metadata: cargo_metadata::Metadata,
    crate_name: &str,
@@ -29,10 +32,9 @@ pub fn transform(
                default_features: v.uses_default_features,
                target: v.target.map(|v| v.to_string()),
                kind: v.kind.to_string(),
                registry: Some(
                    v.registry
                        .unwrap_or("https://github.com/rust-lang/crates.io-index.git".to_string()),
                ),
                registry: Some(v.registry.unwrap_or_else(|| {
                    "https://github.com/rust-lang/crates.io-index.git".to_string()
                })),
                package: v.rename,
            })
            .collect(),
diff --git a/src/protocol/high_level.rs b/src/protocol/high_level.rs
index 3f699df..68be1ed 100644
--- a/src/protocol/high_level.rs
+++ b/src/protocol/high_level.rs
@@ -75,7 +75,7 @@ impl GitRepository {
        Ok(())
    }

    /// Finalises this `GitRepository` by writing a commit to the packfile_entries,
    /// Finalises this `GitRepository` by writing a commit to the `packfile_entries`,
    /// all the files currently in the `tree`, returning all the packfile entries
    /// and also the commit hash so it can be referred to by `ls-ref`s.
    pub fn commit(
diff --git a/src/protocol/low_level.rs b/src/protocol/low_level.rs
index 8e9eb38..c38b5e9 100644
--- a/src/protocol/low_level.rs
+++ b/src/protocol/low_level.rs
@@ -11,13 +11,13 @@ pub type HashOutput = [u8; 20];
// which is sort of used to make sure you're getting the start of the
// packfile correctly. This is followed by a 4-byte packfile version
// number and then a 4-byte number of entries in that file.
pub struct PackFile {
    entries: Vec<PackFileEntry>,
pub struct PackFile<'a> {
    entries: &'a [PackFileEntry],
}

impl PackFile {
impl<'a> PackFile<'a> {
    #[must_use]
    pub fn new(entries: Vec<PackFileEntry>) -> Self {
    pub fn new(entries: &'a [PackFileEntry]) -> Self {
        Self { entries }
    }

@@ -41,7 +41,7 @@ impl PackFile {
        buf.put_u32(self.entries.len().try_into()?); // number of entries in the packfile

        // body
        for entry in &self.entries {
        for entry in self.entries {
            entry.encode_to(&mut buf)?;
        }

diff --git a/src/protocol/packet_line.rs b/src/protocol/packet_line.rs
index 81f98ee..e469001 100644
--- a/src/protocol/packet_line.rs
+++ b/src/protocol/packet_line.rs
@@ -8,7 +8,7 @@ pub enum PktLine<'a> {
    Data(&'a [u8]),
    /// Similar to a data packet, but used during packfile sending to indicate this
    /// packet is a block of data by appending a byte containing the u8 `1`.
    SidebandData(PackFile),
    SidebandData(PackFile<'a>),
    /// Similar to a data packet, but used during packfile sending to indicate this
    /// packet is a status message by appending a byte containing the u8 `2`.
    SidebandMsg(&'a [u8]),
diff --git a/src/providers/gitlab.rs b/src/providers/gitlab.rs
index 0019dbe..850e405 100644
--- a/src/providers/gitlab.rs
+++ b/src/providers/gitlab.rs
@@ -1,3 +1,5 @@
#![allow(clippy::module_name_repetitions)]

use crate::providers::{Group, Release, User};
use async_trait::async_trait;
use futures::{stream::FuturesUnordered, StreamExt, TryStreamExt};
@@ -185,6 +187,7 @@ impl super::PackageProvider for Gitlab {
                        package_files
                            .into_iter()
                            .filter_map(|package_file| {
                                #[allow(clippy::case_sensitive_file_extension_comparisons)]
                                if package_file.file_name.ends_with(".crate") {
                                    if package_file.file_name
                                        == format!("{}-{}.crate", release.name, release.version)
@@ -215,7 +218,7 @@ impl super::PackageProvider for Gitlab {
                            })
                            .collect(),
                    ))
                }))
                }));
            }
        }

@@ -260,8 +263,7 @@ async fn handle_error(resp: reqwest::Response) -> Result<reqwest::Response, anyh
        Err(anyhow::Error::msg(
            resp.message
                .or(resp.error)
                .map(Cow::Owned)
                .unwrap_or_else(|| Cow::Borrowed("unknown error")),
                .map_or_else(|| Cow::Borrowed("unknown error"), Cow::Owned)
        ))
    }
}
@@ -294,6 +296,7 @@ pub struct GitlabCratePath {
}

impl GitlabCratePath {
    #[must_use]
    pub fn metadata_uri(&self, version: &str) -> String {
        format!(
            "/projects/{}/packages/generic/{}/{version}/metadata.json",
diff --git a/src/util.rs b/src/util.rs
index f4324a8..422e38d 100644
--- a/src/util.rs
+++ b/src/util.rs
@@ -1,3 +1,4 @@
#[must_use]
pub fn format_fingerprint(fingerprint: &str) -> String {
    format!("SHA256:{}", fingerprint)
}
@@ -6,6 +7,7 @@ pub fn format_fingerprint(fingerprint: &str) -> String {
/// 1, 2 or 3 respectively as per the cargo spec. Anything else we'll build out a normal tree for
/// using the frist four characters of the crate name, 2 for the first directory and the other 2
/// for the second.
#[must_use]
pub fn get_crate_folder(crate_name: &str) -> Vec<String> {
    let mut folders = Vec::new();