Skip to content

Commit

Permalink
enable cargo-fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
Byron committed Jul 29, 2023
1 parent 0d89352 commit 365f9dc
Show file tree
Hide file tree
Showing 18 changed files with 253 additions and 254 deletions.
14 changes: 6 additions & 8 deletions examples/sparse_http_reqwest.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crates_index::{SparseIndex};
use crates_index::SparseIndex;

///
/// **important**:<br>
Expand All @@ -18,18 +18,18 @@ fn main() {
print_crate(&mut index);
}

fn print_crate(index: &mut SparseIndex){
fn print_crate(index: &mut SparseIndex) {
match index.crate_from_cache(CRATE_TO_FETCH) {
Ok(krate) => {
println!("{:?}", krate.highest_normal_version().unwrap().version());
}
Err(_err) => {
println!("could not find crate {}",CRATE_TO_FETCH)
println!("could not find crate {}", CRATE_TO_FETCH)
}
}
}

fn update(index: &mut SparseIndex){
fn update(index: &mut SparseIndex) {
let req = index.make_cache_request(CRATE_TO_FETCH).unwrap().body(()).unwrap();

let (parts, _) = req.into_parts();
Expand All @@ -41,9 +41,7 @@ fn update(index: &mut SparseIndex){

let res = client.execute(req).unwrap();

let mut builder = http::Response::builder()
.status(res.status())
.version(res.version());
let mut builder = http::Response::builder().status(res.status()).version(res.version());

builder
.headers_mut()
Expand All @@ -54,4 +52,4 @@ fn update(index: &mut SparseIndex){
let res = builder.body(body.to_vec()).unwrap();

index.parse_cache_response(CRATE_TO_FETCH, res, true).unwrap();
}
}
13 changes: 7 additions & 6 deletions examples/sparse_http_ureq.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crates_index::SparseIndex;
use std::io;
use crates_index::{SparseIndex};

///
/// **important**:<br>
Expand All @@ -19,27 +19,28 @@ fn main() {
print_crate(&mut index);
}

fn print_crate(index: &mut SparseIndex){
fn print_crate(index: &mut SparseIndex) {
match index.crate_from_cache(CRATE_TO_FETCH) {
Ok(krate) => {
println!("{:?}", krate.highest_normal_version().unwrap().version());
}
Err(_err) => {
println!("could not find crate {}",CRATE_TO_FETCH)
println!("could not find crate {}", CRATE_TO_FETCH)
}
}
}

fn update(index: &mut SparseIndex){
fn update(index: &mut SparseIndex) {
let request: ureq::Request = index.make_cache_request(CRATE_TO_FETCH).unwrap().into();

let response: http::Response<String> = request
.call()
.map_err(|_e| io::Error::new(io::ErrorKind::InvalidInput, "connection error")).unwrap()
.map_err(|_e| io::Error::new(io::ErrorKind::InvalidInput, "connection error"))
.unwrap()
.into();

let (parts, body) = response.into_parts();
let response = http::Response::from_parts(parts, body.into_bytes());

index.parse_cache_response(CRATE_TO_FETCH, response, true).unwrap();
}
}
10 changes: 7 additions & 3 deletions examples/update_and_get_latest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,16 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut index = crates_index::GitIndex::new_cargo_default()?;
println!("Updating index…");
index.update()?;

let limit = 10;
println!("The most recent {limit} changes:\n");
for change in index.changes()?.take(limit) {
let change = change?;
println!("{name} changed in {commit}", name = change.crate_name(), commit = change.commit_hex());
println!(
"{name} changed in {commit}",
name = change.crate_name(),
commit = change.commit_hex()
);
}
Ok(())
}
}
3 changes: 2 additions & 1 deletion rustfmt.toml
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
disable_all_formatting = true
max_width = 120
disable_all_formatting = false
2 changes: 1 addition & 1 deletion src/config.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use serde_derive::Deserialize;
use crate::dirs::crate_prefix;
use serde_derive::Deserialize;

/// Global configuration of an index, reflecting the [contents of config.json](https://doc.rust-lang.org/cargo/reference/registries.html#index-format).
#[derive(Clone, Debug, Deserialize)]
Expand Down
11 changes: 8 additions & 3 deletions src/dedupe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ impl DedupeContext {
if let Some(has_feats) = self.features.get(&features_to_dedupe) {
*features = Arc::clone(&has_feats.map);
} else {
if self.features.len() > 16384 { // keeps peak memory low (must clear, remove is leaving tombstones)
if self.features.len() > 16384 {
// keeps peak memory low (must clear, remove is leaving tombstones)
self.features.clear();
}
self.features.insert(features_to_dedupe);
Expand All @@ -36,7 +37,8 @@ impl DedupeContext {
if let Some(has_deps) = self.deps.get(&*deps) {
*deps = Arc::clone(has_deps);
} else {
if self.deps.len() > 16384 { // keeps peak memory low (must clear, remove is leaving tombstones)
if self.deps.len() > 16384 {
// keeps peak memory low (must clear, remove is leaving tombstones)
self.deps.clear();
}
self.deps.insert(Arc::clone(deps));
Expand All @@ -52,7 +54,10 @@ pub struct HashableHashMap<K: PartialEq + Hash + Eq, V: PartialEq + Hash + Eq> {
}

impl<K: PartialEq + Hash + Eq, V: PartialEq + Hash + Eq> Hash for HashableHashMap<K, V> {
fn hash<H>(&self, hasher: &mut H) where H: Hasher {
fn hash<H>(&self, hasher: &mut H)
where
H: Hasher,
{
hasher.write_u64(self.hash);
}
}
Expand Down
53 changes: 27 additions & 26 deletions src/dirs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,30 @@ pub(crate) fn crate_prefix(accumulator: &mut String, crate_name: &str, separator
3 => {
accumulator.push('3');
accumulator.push(separator);
accumulator.extend(crate_name.as_bytes().get(0..1)?.iter().map(|c| c.to_ascii_lowercase() as char));
accumulator.extend(
crate_name
.as_bytes()
.get(0..1)?
.iter()
.map(|c| c.to_ascii_lowercase() as char),
);
}
_ => {
accumulator.extend(crate_name.as_bytes().get(0..2)?.iter().map(|c| c.to_ascii_lowercase() as char));
accumulator.extend(
crate_name
.as_bytes()
.get(0..2)?
.iter()
.map(|c| c.to_ascii_lowercase() as char),
);
accumulator.push(separator);
accumulator.extend(crate_name.as_bytes().get(2..4)?.iter().map(|c| c.to_ascii_lowercase() as char));
accumulator.extend(
crate_name
.as_bytes()
.get(2..4)?
.iter()
.map(|c| c.to_ascii_lowercase() as char),
);
}
};
Some(())
Expand All @@ -52,7 +70,6 @@ pub(crate) fn crate_name_to_relative_path(crate_name: &str, separator: Option<ch
Some(rel_path)
}


/// Converts a full url, eg https://github.com/rust-lang/crates.io-index, into
/// the root directory name where cargo itself will fetch it on disk
fn url_to_local_dir(url: &str) -> Result<(String, String), Error> {
Expand Down Expand Up @@ -174,51 +191,35 @@ mod test {
use crate::sparse::URL;
assert_eq!(
super::url_to_local_dir(URL).unwrap(),
(
"index.crates.io-6f17d22bba15001f".to_owned(),
URL.to_owned(),
)
("index.crates.io-6f17d22bba15001f".to_owned(), URL.to_owned(),)
);

// I've confirmed this also works with a custom registry, unfortunately
// that one includes a secret key as part of the url which would allow
// anyone to publish to the registry, so uhh...here's a fake one instead
assert_eq!(
super::url_to_local_dir(
"https://dl.cloudsmith.io/aBcW1234aBcW1234/embark/rust/cargo/index.git"
)
.unwrap(),
super::url_to_local_dir("https://dl.cloudsmith.io/aBcW1234aBcW1234/embark/rust/cargo/index.git").unwrap(),
(
"dl.cloudsmith.io-ff79e51ddd2b38fd".to_owned(),
"https://dl.cloudsmith.io/aBcW1234aBcW1234/embark/rust/cargo/index.git".to_owned()
)
);
}

#[test]
#[cfg(feature = "git")]
fn git_url_matches_cargo() {
use crate::git::URL;
assert_eq!(
crate::dirs::url_to_local_dir(URL).unwrap(),
(
"github.com-1ecc6299db9ec823".to_owned(),
URL.to_owned()
)
("github.com-1ecc6299db9ec823".to_owned(), URL.to_owned())
);

// Ensure we actually strip off the irrelevant parts of a url, note that
// the .git suffix is not part of the canonical url, but *is* used when hashing
assert_eq!(
crate::dirs::url_to_local_dir(&format!(
"registry+{}.git?one=1&two=2#fragment",
URL
))
.unwrap(),
(
"github.com-c786010fb7ef2e6e".to_owned(),
URL.to_owned()
)
crate::dirs::url_to_local_dir(&format!("registry+{}.git?one=1&two=2#fragment", URL)).unwrap(),
("github.com-c786010fb7ef2e6e".to_owned(), URL.to_owned())
);
}
}
8 changes: 3 additions & 5 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
pub use serde_json::Error as SerdeJsonError;
use std::{io};
use std::io;
use std::path::PathBuf;
pub use toml::de::Error as TomlDeError;

Expand All @@ -12,7 +12,7 @@ pub enum Error {
Git(#[from] GixError),
#[error("{0}")]
Url(String),
#[error("Could not obtain the most recent head commit in repo at {}. Tried {}, had {} available", repo_path.display(), refs_tried.join(", "), refs_available.join(", "))]
#[error("Could not obtain the most recent head commit in repo at {}. Tried {}, had {} available", repo_path.display(), refs_tried.join(", "), refs_available.join(", "))]
MissingHead {
/// The references we tried to get commits for.
refs_tried: &'static [&'static str],
Expand Down Expand Up @@ -49,9 +49,7 @@ pub enum GixError {
#[error(transparent)]
IntoObjectKind(#[from] gix::object::try_into::Error),
#[error("The '{}' file is missing at the root of the tree of the crates index", path.display())]
PathMissing {
path: std::path::PathBuf
},
PathMissing { path: std::path::PathBuf },
#[error(transparent)]
LockAcquire(#[from] gix::lock::acquire::Error),
#[error(transparent)]
Expand Down
43 changes: 31 additions & 12 deletions src/git/changes.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::git::{Change, fetch_remote};
use crate::error::GixError;
use crate::git::{fetch_remote, Change};
use crate::Error;
use crate::GitIndex;
use gix::bstr::ByteSlice;
Expand All @@ -9,7 +9,6 @@ use std::time::{Duration, SystemTime};

const INDEX_GIT_ARCHIVE_URL: &str = "https://github.com/rust-lang/crates.io-index-archive";


/// An iterator over individual changes, see [`GitIndex::changes`] for more.
pub struct Changes<'repo> {
repo: &'repo gix::Repository,
Expand All @@ -30,7 +29,15 @@ impl<'repo> Iterator for Changes<'repo> {
};
let parent_tree = parent.tree().ok()?;
let time = SystemTime::UNIX_EPOCH + Duration::from_secs(self.current.time().ok()?.seconds.max(0) as _);
Self::tree_additions(&self.repo, &mut self.out, time, &self.current.id(), &self.current_tree, &parent_tree).ok()?;
Self::tree_additions(
&self.repo,
&mut self.out,
time,
&self.current.id(),
&self.current_tree,
&parent_tree,
)
.ok()?;
self.current_tree = parent_tree;
self.current = parent;
}
Expand All @@ -40,7 +47,11 @@ impl<'repo> Iterator for Changes<'repo> {

impl<'repo> Changes<'repo> {
pub(crate) fn new(index: &'repo GitIndex) -> Result<Self, GixError> {
let current = index.repo.find_object(index.head_commit)?.peel_to_kind(gix::object::Kind::Commit)?.into_commit();
let current = index
.repo
.find_object(index.head_commit)?
.peel_to_kind(gix::object::Kind::Commit)?
.into_commit();
let current_tree = current.tree()?;

Ok(Self {
Expand All @@ -52,7 +63,13 @@ impl<'repo> Changes<'repo> {
}

fn get_parent(&self) -> Result<Option<gix::Commit<'repo>>, GixError> {
match self.current.parent_ids().next().map(|id| id.try_object()).transpose()?.flatten()
match self
.current
.parent_ids()
.next()
.map(|id| id.try_object())
.transpose()?
.flatten()
{
Some(obj) => Ok(Some(obj.try_into_commit()?)),
None => {
Expand Down Expand Up @@ -96,13 +113,12 @@ impl<'repo> Changes<'repo> {
// Recurse only into crate subdirs, and they all happen to be 1 or 2 letters long
let is_crates_subdir = name.len() <= 2 && name.iter().copied().all(valid_crate_name_char);
let old_obj = if is_crates_subdir {
old.bisect_entry(name, true)
.map(|entry| entry.attach(repo))
old.bisect_entry(name, true).map(|entry| entry.attach(repo))
} else {
None
}
.map(|o| o.object())
.transpose()?;
.map(|o| o.object())
.transpose()?;
let old_tree = match old_obj.and_then(|o| o.try_into_tree().ok()) {
Some(t) => t,
None => repo.empty_tree(),
Expand Down Expand Up @@ -130,7 +146,10 @@ fn valid_crate_name_char(c: u8) -> bool {
}

fn oid_and_branch_from_commit_message(msg: &str) -> Option<(gix::ObjectId, &str)> {
let hash_start = msg.split_once("Previous HEAD was ")?.1.trim_start_matches(|c: char| !c.is_ascii_hexdigit());
let hash_start = msg
.split_once("Previous HEAD was ")?
.1
.trim_start_matches(|c: char| !c.is_ascii_hexdigit());
let (hash_str, rest) = hash_start.split_once(|c: char| !c.is_ascii_hexdigit())?;
let hash = gix::ObjectId::from_hex(hash_str.as_bytes()).ok()?;
let snapshot_start = rest.find("snapshot-")?;
Expand All @@ -141,7 +160,7 @@ fn oid_and_branch_from_commit_message(msg: &str) -> Option<(gix::ObjectId, &str)

#[cfg(test)]
pub(crate) mod test {
use super::{oid_and_branch_from_commit_message};
use super::oid_and_branch_from_commit_message;

#[test]
fn changes_parse_split_message() {
Expand All @@ -153,7 +172,7 @@ More information about this change can be found [online] and on [this issue].
[online]: https://internals.rust-lang.org/t/cargos-crate-index-upcoming-squash-into-one-commit/8440
[this issue]: https://github.com/rust-lang/crates-io-cargo-teams/issues/47",
)
.unwrap();
.unwrap();
assert_eq!("4181c62812c70fafb2b56cbbd66c31056671b445", id.to_string());
assert_eq!("snapshot-2021-07-02", branch);
}
Expand Down
5 changes: 1 addition & 4 deletions src/git/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,7 @@ fn read_cargo_config<T>(
) -> Result<Option<T>, Error> {
use std::borrow::Cow;

if let Some(mut path) = root
.map(PathBuf::from)
.or_else(|| std::env::current_dir().ok())
{
if let Some(mut path) = root.map(PathBuf::from).or_else(|| std::env::current_dir().ok()) {
loop {
path.push(".cargo/config.toml");
if let Some(toml) = try_read_toml(&path)? {
Expand Down
Loading

0 comments on commit 365f9dc

Please sign in to comment.