From 7c57805fb2f32f8380f2071c6845fdbc29a46e08 Mon Sep 17 00:00:00 2001 From: Timothy DeHerrera Date: Sun, 13 Oct 2024 18:04:16 -0600 Subject: [PATCH] style: add a .rustfmt.toml enforces a slightly more opinionate style that should help keep the code a bit more consistent. --- .rustfmt.toml | 21 ++++++++++++ crates/atom/src/core.rs | 9 +++-- crates/atom/src/id/mod.rs | 9 +++-- crates/atom/src/lib.rs | 7 ++-- crates/atom/src/manifest.rs | 14 +++++--- crates/atom/src/manifest/depends.rs | 1 + crates/atom/src/publish/error.rs | 12 ++++--- crates/atom/src/publish/git/inner.rs | 50 ++++++++++++--------------- crates/atom/src/publish/git/mod.rs | 51 ++++++++++++++++------------ crates/atom/src/publish/git/test.rs | 22 +++++++----- crates/atom/src/publish/mod.rs | 13 ++++--- crates/atom/src/store/git.rs | 43 +++++++++++++++-------- crates/atom/src/store/git/test.rs | 14 +++----- crates/atom/src/uri/mod.rs | 42 +++++++++++------------ crates/config/src/lib.rs | 16 ++++----- crates/nixec/src/main.rs | 13 ++++--- dev/env/rust-toolchain.toml | 2 +- dev/env/shell.nix | 1 + src/cli/commands/init.rs | 7 ++-- src/cli/commands/mod.rs | 6 ++-- src/cli/commands/publish/git/mod.rs | 24 ++++++------- src/cli/commands/publish/mod.rs | 23 +++++++------ src/cli/logging.rs | 14 ++++---- src/cli/mod.rs | 6 ++-- src/cli/store.rs | 3 +- src/main.rs | 3 +- treefmt.toml | 1 - 27 files changed, 239 insertions(+), 188 deletions(-) create mode 100644 .rustfmt.toml diff --git a/.rustfmt.toml b/.rustfmt.toml new file mode 100644 index 0000000..f03246b --- /dev/null +++ b/.rustfmt.toml @@ -0,0 +1,21 @@ +edition = "2021" +newline_style = "unix" +use_field_init_shorthand = true +use_try_shorthand = true + +unstable_features = true + +comment_width = 100 +condense_wildcard_suffixes = true +error_on_line_overflow = true +format_code_in_doc_comments = true +format_macro_bodies = true +format_macro_matchers = true +format_strings = true +group_imports = "StdExternalCrate" +imports_granularity = "Module" +match_block_trailing_comma = true +normalize_doc_attributes = true +reorder_impl_items = true +style_edition = "2024" +wrap_comments = true diff --git a/crates/atom/src/core.rs b/crates/atom/src/core.rs index 76ab353..86011a6 100644 --- a/crates/atom/src/core.rs +++ b/crates/atom/src/core.rs @@ -1,10 +1,11 @@ -use std::{borrow::Cow, path::Path}; - -use super::id::Id; +use std::borrow::Cow; +use std::path::Path; use semver::Version; use serde::{Deserialize, Serialize}; +use super::id::Id; + #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] /// Represents the deserialized form of an Atom, directly constructed from the TOML manifest. /// @@ -69,9 +70,11 @@ impl AtomPaths { pub fn lock(&self) -> &Path { self.lock.as_ref() } + pub fn spec(&self) -> &Path { self.spec.as_ref() } + pub fn content(&self) -> &Path { self.content.as_ref() } diff --git a/crates/atom/src/id/mod.rs b/crates/atom/src/id/mod.rs index b105e16..93808d7 100644 --- a/crates/atom/src/id/mod.rs +++ b/crates/atom/src/id/mod.rs @@ -6,12 +6,12 @@ #[cfg(test)] mod tests; -use serde::{Deserialize, Serialize, Serializer}; - use std::borrow::Borrow; use std::fmt; use std::ops::Deref; use std::str::FromStr; + +use serde::{Deserialize, Serialize, Serializer}; use thiserror::Error; use unic_ucd_category::GeneralCategory; @@ -80,6 +80,7 @@ impl Serialize for AtomId { impl Deref for AtomHash<'_, T> { type Target = [u8; 32]; + fn deref(&self) -> &Self::Target { &self.hash } @@ -124,6 +125,7 @@ where let root = src.calculate_root()?; Ok(AtomId { root, id }) } + /// The root field, which serves as a derived key for the blake-3 hash used to /// identify the Atom in backend implementations. pub fn root(&self) -> &R { @@ -158,6 +160,7 @@ impl Id { Ok(()) } + pub(super) fn is_invalid_start(c: char) -> bool { matches!( GeneralCategory::of(c), @@ -166,6 +169,7 @@ impl Id { || c == '-' || !Id::is_valid_char(c) } + pub(super) fn is_valid_char(c: char) -> bool { matches!( GeneralCategory::of(c), @@ -183,6 +187,7 @@ impl Id { impl Deref for Id { type Target = String; + fn deref(&self) -> &Self::Target { &self.0 } diff --git a/crates/atom/src/lib.rs b/crates/atom/src/lib.rs index 8503791..a2a0352 100644 --- a/crates/atom/src/lib.rs +++ b/crates/atom/src/lib.rs @@ -36,11 +36,10 @@ pub mod publish; pub mod store; pub mod uri; pub use core::Atom; -pub use id::AtomId; -pub use id::CalculateRoot; -pub use manifest::Manifest; - use std::sync::LazyLock; + +pub use id::{AtomId, CalculateRoot}; +pub use manifest::Manifest; const TOML: &str = "toml"; const BASE32: base32::Alphabet = base32::Alphabet::Rfc4648HexLower { padding: false }; static ATOM_EXT: LazyLock = LazyLock::new(|| format!("@.{}", crate::TOML)); diff --git a/crates/atom/src/manifest.rs b/crates/atom/src/manifest.rs index 86f34c5..a463005 100644 --- a/crates/atom/src/manifest.rs +++ b/crates/atom/src/manifest.rs @@ -1,12 +1,17 @@ //! # Atom Manifest //! //! Provides the core types for working with an Atom's manifest format. -use crate::Atom; -use serde::{Deserialize, Serialize}; +mod depends; + +use std::collections::HashMap; use std::str::FromStr; + +use serde::{Deserialize, Serialize}; use thiserror::Error; -use toml_edit::de; -use toml_edit::DocumentMut; +use toml_edit::{DocumentMut, de}; + +use crate::Atom; +use crate::id::Id; /// Errors which occur during manifest (de)serialization. #[derive(Error, Debug)] @@ -53,6 +58,7 @@ impl Manifest { impl FromStr for Manifest { type Err = de::Error; + fn from_str(s: &str) -> Result { de::from_str(s) } diff --git a/crates/atom/src/manifest/depends.rs b/crates/atom/src/manifest/depends.rs index 6815820..def8983 100644 --- a/crates/atom/src/manifest/depends.rs +++ b/crates/atom/src/manifest/depends.rs @@ -36,6 +36,7 @@ impl AtomSrc { _ => None, } } + pub(crate) fn path(self) -> Option { match self { AtomSrc::Path(path) => Some(path), diff --git a/crates/atom/src/publish/error.rs b/crates/atom/src/publish/error.rs index 3e28780..ce52ce0 100644 --- a/crates/atom/src/publish/error.rs +++ b/crates/atom/src/publish/error.rs @@ -15,9 +15,11 @@ pub enum PublishError { #[cfg(feature = "git")] pub mod git { //! # Git Publishing Errors - use crate::store::git::Root; - use gix::object; use std::path::PathBuf; + + use gix::object; + + use crate::store::git::Root; /// An error representing a failure during publishing to a Git Ekala store. #[derive(thiserror::Error, Debug)] pub enum Error { @@ -103,13 +105,13 @@ pub mod git { remote_root = %**remote, suggest = Error::INCONSISTENT_ROOT_SUGGESTION ); - } + }, Error::Invalid(e, path) => { tracing::warn!(message = %self, path = %path.display(), message = format!("\n{}", e)); - } + }, Error::NotAnAtom(path) => { tracing::warn!(message = %self, path = %path.display()); - } + }, Error::Failed => (), _ => tracing::warn!(message = %self), } diff --git a/crates/atom/src/publish/git/inner.rs b/crates/atom/src/publish/git/inner.rs index d3b6bf3..5149448 100644 --- a/crates/atom/src/publish/git/inner.rs +++ b/crates/atom/src/publish/git/inner.rs @@ -1,29 +1,22 @@ -use super::{ - super::{ATOM_FORMAT_VERSION, ATOM_MANIFEST, EMPTY_SIG}, - AtomContext, AtomRef, GitContext, GitResult, RefKind, -}; -use crate::{ - core::AtomPaths, - publish::{error::git::Error, ATOM_ORIGIN}, - store::git, - Atom, AtomId, Manifest, -}; - -use gix::{ - actor::Signature, - diff::object::Commit as AtomCommit, - object::tree::Entry, - objs::{tree::Entry as AtomEntry, WriteTo}, - worktree::object::Tree as AtomTree, - ObjectId, Reference, -}; -use std::{ - io::{self, Read}, - os::unix::ffi::OsStrExt, - path::Path, -}; - -use std::path::PathBuf; +use std::io::{self, Read}; +use std::os::unix::ffi::OsStrExt; +use std::path::{Path, PathBuf}; + +use gix::actor::Signature; +use gix::diff::object::Commit as AtomCommit; +use gix::object::tree::Entry; +use gix::objs::WriteTo; +use gix::objs::tree::Entry as AtomEntry; +use gix::worktree::object::Tree as AtomTree; +use gix::{ObjectId, Reference}; + +use super::super::{ATOM_FORMAT_VERSION, ATOM_MANIFEST, EMPTY_SIG}; +use super::{AtomContext, AtomRef, GitContext, GitResult, RefKind}; +use crate::core::AtomPaths; +use crate::publish::ATOM_ORIGIN; +use crate::publish::error::git::Error; +use crate::store::git; +use crate::{Atom, AtomId, Manifest}; impl<'a> GitContext<'a> { /// Method to verify the manifest of an entry pub(super) fn verify_manifest(&self, obj: &Object, path: &Path) -> GitResult { @@ -149,13 +142,13 @@ impl<'a> AtomContext<'a> { false } } + /// Method to write the atom tree object pub(super) fn write_atom_tree( &self, entries: &AtomEntries, ) -> GitResult> { - use Err as Skipped; - use Ok as Wrote; + use {Err as Skipped, Ok as Wrote}; let mut entries: Vec<_> = entries.iter().map(atom_entry).collect(); @@ -320,6 +313,7 @@ impl CommittedAtom { pub fn commit(&self) -> &AtomCommit { &self.commit } + #[must_use] /// Returns a reference to the tip of this [`CommittedAtom`]. pub fn tip(&self) -> &ObjectId { diff --git a/crates/atom/src/publish/git/mod.rs b/crates/atom/src/publish/git/mod.rs index e1aa263..a554e98 100644 --- a/crates/atom/src/publish/git/mod.rs +++ b/crates/atom/src/publish/git/mod.rs @@ -15,19 +15,19 @@ mod test; mod inner; -use super::{error::git::Error, Content, PublishOutcome, Record}; -use crate::{ - core::AtomPaths, - store::{git::Root, NormalizeStorePath}, - Atom, AtomId, -}; - -use gix::Commit; -use gix::{ObjectId, Repository, Tree}; use std::cell::RefCell; use std::path::{Path, PathBuf}; + +use gix::{Commit, ObjectId, Repository, Tree}; use tokio::task::JoinSet; +use super::error::git::Error; +use super::{Content, PublishOutcome, Record}; +use crate::core::AtomPaths; +use crate::store::NormalizeStorePath; +use crate::store::git::Root; +use crate::{Atom, AtomId}; + type GitAtomId = AtomId; /// The Outcome of an Atom publish attempt to a Git store. pub type GitOutcome = PublishOutcome; @@ -198,7 +198,7 @@ impl<'a> StateValidator for GitPublisher<'a> { return Err(Error::Duplicates); } atoms.insert(atom.id, path); - } + }, Err(e) => e.warn(), } } @@ -228,21 +228,25 @@ impl GitContent { pub fn spec(&self) -> &gix::refs::Reference { &self.spec } + /// Return a reference to the Atom src Git ref. #[must_use] pub fn origin(&self) -> &gix::refs::Reference { &self.origin } + /// Return a reference to the Atom content ref. #[must_use] pub fn content(&self) -> &gix::refs::Reference { &self.content } + /// Return a reference to the path to the Atom. #[must_use] pub fn path(&self) -> &PathBuf { &self.path } + /// Return a reference to the atom ref prefix. #[must_use] pub fn ref_prefix(&self) -> &String { @@ -250,9 +254,10 @@ impl GitContent { } } +use std::collections::HashMap; + use super::Publish; use crate::id::Id; -use std::collections::HashMap; impl<'a> super::private::Sealed for GitContext<'a> {} @@ -261,12 +266,15 @@ impl<'a> Publish for GitContext<'a> { /// Publishes atoms. /// - /// This function processes a collection of paths, each representing an atom to be published. The publishing - /// process includes path normalization, existence checks, and actual publishing attempts. + /// This function processes a collection of paths, each representing an atom to be published. + /// The publishing process includes path normalization, existence checks, and actual + /// publishing attempts. /// /// # Path Normalization - /// - First attempts to interpret each path as relative to the caller's current location inside the repository. - /// - If normalization fails (e.g., in a bare repository), falls back to treating the path as already relative to the repo root. + /// - First attempts to interpret each path as relative to the caller's current location inside + /// the repository. + /// - If normalization fails (e.g., in a bare repository), falls back to treating the path as + /// already relative to the repo root. /// - The normalized path is used to search the Git history, not the file system. /// /// # Publishing Process @@ -285,8 +293,8 @@ impl<'a> Publish for GitContext<'a> { /// /// # Return Value /// Returns a vector of results types (`Vec, Self::Error>>`), where the - /// outter result represents whether an atom has failed, and the inner result determines whether an - /// atom was safely skipped, e.g. because it already exists.. + /// outter result represents whether an atom has failed, and the inner result determines whether + /// an atom was safely skipped, e.g. because it already exists.. fn publish(&self, paths: C) -> Vec> where C: IntoIterator, @@ -306,8 +314,7 @@ impl<'a> Publish for GitContext<'a> { } fn publish_atom>(&self, path: P) -> GitResult { - use Err as Skipped; - use Ok as Published; + use {Err as Skipped, Ok as Published}; let atom = AtomContext::set(path.as_ref(), self)?; @@ -385,13 +392,13 @@ impl<'a> GitContext<'a> { if !output.is_empty() { tracing::info!(output = %String::from_utf8_lossy(&output)); } - } + }, Ok(Err(e)) => { errors.push(e); - } + }, Err(e) => { errors.push(Error::JoinFailed(e)); - } + }, } } } diff --git a/crates/atom/src/publish/git/test.rs b/crates/atom/src/publish/git/test.rs index a9fb0c5..feb584f 100644 --- a/crates/atom/src/publish/git/test.rs +++ b/crates/atom/src/publish/git/test.rs @@ -1,13 +1,14 @@ -use std::{io::Write, os::unix::fs::MetadataExt, str::FromStr}; +use std::io::Write; +use std::os::unix::fs::MetadataExt; +use std::str::FromStr; use anyhow::Context; -use gix::{prelude::ReferenceExt, ObjectId}; +use gix::ObjectId; +use gix::prelude::ReferenceExt; use tempfile::{Builder, NamedTempFile}; -use crate::{ - publish::{Content, Publish, Record}, - store::git, -}; +use crate::publish::{Content, Publish, Record}; +use crate::store::git; trait MockAtom { fn mock( @@ -25,11 +26,13 @@ impl MockAtom for gix::Repository { version: &str, description: &str, ) -> Result<(NamedTempFile, ObjectId), anyhow::Error> { - use crate::{Atom, Manifest}; - use gix::objs::{tree::Entry, tree::EntryMode, Tree}; + use gix::objs::Tree; + use gix::objs::tree::{Entry, EntryMode}; use semver::Version; use toml_edit::ser; + use crate::{Atom, Manifest}; + let work_dir = self.work_dir().context("No workdir")?; let mut atom_file = Builder::new() .suffix(crate::ATOM_EXT.as_str()) @@ -40,6 +43,9 @@ impl MockAtom for gix::Repository { version: Version::from_str(version)?, description: (!description.is_empty()).then_some(description.into()), }, + deps: None, + srcs: None, + pins: None, }; let buf = ser::to_string_pretty(&manifest)?; diff --git a/crates/atom/src/publish/mod.rs b/crates/atom/src/publish/mod.rs index 1504e16..7c289a0 100644 --- a/crates/atom/src/publish/mod.rs +++ b/crates/atom/src/publish/mod.rs @@ -7,12 +7,14 @@ pub mod error; #[cfg(feature = "git")] pub mod git; -use crate::{id::Id, AtomId}; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; #[cfg(feature = "git")] use git::GitContent; -use std::collections::HashMap; -use std::path::{Path, PathBuf}; + +use crate::AtomId; +use crate::id::Id; /// The results of Atom publishing, for reporting to the user. pub struct Record { @@ -112,8 +114,8 @@ pub trait Publish: private::Sealed { /// This function takes a single path and publishes the Atom located there, if possible. /// /// # Return Value - /// - An outcome is either the record ([`Record`]) of the successfully - /// publish Atom or the [`crate::AtomId`] if it was safely skipped. + /// - An outcome is either the record ([`Record`]) of the successfully publish Atom or the + /// [`crate::AtomId`] if it was safely skipped. /// /// - The function will return an error ([`Self::Error`]) if the Atom could not be published for /// any reason, e.g. invalid manifests. @@ -125,6 +127,7 @@ impl Record { pub fn id(&self) -> &AtomId { &self.id } + /// Return a reference to the [`Content`] of the record. pub fn content(&self) -> &Content { &self.content diff --git a/crates/atom/src/store/git.rs b/crates/atom/src/store/git.rs index 9fcac3c..50156eb 100644 --- a/crates/atom/src/store/git.rs +++ b/crates/atom/src/store/git.rs @@ -8,17 +8,17 @@ #[cfg(test)] pub(crate) mod test; -use crate::id::CalculateRoot; +use std::sync::OnceLock; use bstr::BStr; -use gix::{ - discover::upwards::Options, - sec::{trust::Mapping, Trust}, - Commit, ObjectId, ThreadSafeRepository, -}; -use std::sync::OnceLock; +use gix::discover::upwards::Options; +use gix::sec::Trust; +use gix::sec::trust::Mapping; +use gix::{Commit, ObjectId, ThreadSafeRepository}; use thiserror::Error as ThisError; +use crate::id::CalculateRoot; + /// An error encountered during initialization or other git store operations. #[derive(ThisError, Debug)] pub enum Error { @@ -95,7 +95,7 @@ pub fn repo() -> Result, Box { error = Some(e); None - } + }, }); if let Some(e) = error { Err(e) @@ -152,6 +152,7 @@ pub fn default_remote() -> &'static str { use std::ops::Deref; impl Deref for Root { type Target = ObjectId; + fn deref(&self) -> &Self::Target { &self.0 } @@ -159,6 +160,7 @@ impl Deref for Root { impl<'a> CalculateRoot for Commit<'a> { type Error = Error; + fn calculate_root(&self) -> Result { use gix::traverse::commit::simple::{CommitTimeOrder, Sorting}; // FIXME: we rely on a custom crate patch to search the commit graph @@ -187,15 +189,19 @@ impl<'a> CalculateRoot for Commit<'a> { } } -use super::{NormalizeStorePath, QueryStore}; -use gix::Repository; use std::path::{Path, PathBuf}; +use gix::Repository; + +use super::{NormalizeStorePath, QueryStore}; + impl NormalizeStorePath for Repository { type Error = Error; + fn normalize>(&self, path: P) -> Result { - use path_clean::PathClean; use std::fs; + + use path_clean::PathClean; let path = path.as_ref(); let rel_repo_root = self.work_dir().ok_or(Error::NoWorkDir)?; @@ -248,6 +254,7 @@ trait EkalaRemote { impl<'repo> EkalaRemote for gix::Remote<'repo> { type Error = Error; + fn try_symbol(&self) -> Result<&str, Self::Error> { use gix::remote::Name; self.name() @@ -265,6 +272,7 @@ const V1_ROOT: &str = "refs/tags/ekala/root/v1"; use super::Init; impl<'repo> Init for gix::Remote<'repo> { type Error = Error; + /// Determines if this remote is a valid Ekala store by pulling HEAD and the root /// tag, ensuring the latter is actually the root of HEAD, returning the root. fn ekala_root(&self) -> Result { @@ -293,6 +301,7 @@ impl<'repo> Init for gix::Remote<'repo> { } })? } + /// Sync with the given remote and get the most up to date HEAD according to it. fn sync(&self) -> Result { self.get_ref("HEAD") @@ -300,9 +309,10 @@ impl<'repo> Init for gix::Remote<'repo> { /// Initialize the repository by calculating the root, according to the latest HEAD. fn ekala_init(&self) -> Result<(), Error> { - use crate::CalculateRoot; use gix::refs::transaction::PreviousValue; + use crate::CalculateRoot; + let name = self.try_symbol()?; let head = self.sync()?; let repo = self.repo(); @@ -349,6 +359,7 @@ fn setup_line_renderer( impl<'repo> super::QueryStore for gix::Remote<'repo> { type Error = Error; + /// returns the git object ids for the given references fn get_refs( &self, @@ -357,12 +368,14 @@ impl<'repo> super::QueryStore for gix::Remote<'repo> { where Spec: AsRef, { - use gix::progress::tree::Root; - use gix::remote::ref_map::Options; - use gix::remote::{fetch::Tags, Direction}; use std::collections::HashSet; use std::sync::atomic::AtomicBool; + use gix::progress::tree::Root; + use gix::remote::Direction; + use gix::remote::fetch::Tags; + use gix::remote::ref_map::Options; + let tree = Root::new(); let sync_progress = tree.add_child("sync"); let init_progress = tree.add_child("init"); diff --git a/crates/atom/src/store/git/test.rs b/crates/atom/src/store/git/test.rs index 911f130..c655f14 100644 --- a/crates/atom/src/store/git/test.rs +++ b/crates/atom/src/store/git/test.rs @@ -1,6 +1,7 @@ -use super::*; use tempfile::TempDir; +use super::*; + pub(crate) fn init_repo_and_remote() -> Result<(TempDir, TempDir), anyhow::Error> { use gix::actor::SignatureRef; use gix::config::{File, Source}; @@ -18,14 +19,9 @@ pub(crate) fn init_repo_and_remote() -> Result<(TempDir, TempDir), anyhow::Error repo.empty_tree().id(), no_parents.clone(), )?; - remote.commit_as( - sig, - sig, - "HEAD", - "2nd", - repo.empty_tree().id(), - vec![init.detach()], - )?; + remote.commit_as(sig, sig, "HEAD", "2nd", repo.empty_tree().id(), vec![ + init.detach(), + ])?; let config_file = repo.git_dir().join("config"); let mut config = File::from_path_no_includes(config_file.clone(), Source::Local)?; diff --git a/crates/atom/src/uri/mod.rs b/crates/atom/src/uri/mod.rs index 10be22b..bf3ce66 100644 --- a/crates/atom/src/uri/mod.rs +++ b/crates/atom/src/uri/mod.rs @@ -16,18 +16,17 @@ #[cfg(test)] mod tests; +use std::collections::HashMap; use std::ops::Deref; use std::str::FromStr; +use gix_url::Url; +use semver::VersionReq; use serde::{Deserialize, Serialize}; +use thiserror::Error; use super::id::Id; use crate::id::Error; -use gix_url::Url; - -use semver::VersionReq; -use std::collections::HashMap; -use thiserror::Error; #[derive(Debug)] struct Aliases(&'static HashMap<&'static str, &'static str>); @@ -75,14 +74,12 @@ struct AtomRef<'a> { version: Option<&'a str>, } -use nom::{ - branch::alt, - bytes::complete::{tag, take_until}, - character::complete::digit1, - combinator::{all_consuming, map, not, opt, peek, rest, verify}, - sequence::{separated_pair, tuple}, - IResult, ParseTo, -}; +use nom::branch::alt; +use nom::bytes::complete::{tag, take_until}; +use nom::character::complete::digit1; +use nom::combinator::{all_consuming, map, not, opt, peek, rest, verify}; +use nom::sequence::{separated_pair, tuple}; +use nom::{IResult, ParseTo}; fn parse(input: &str) -> Ref { let (rest, url) = match url(input) { @@ -120,7 +117,7 @@ fn parse_alias(input: &str) -> (&str, Option<&str>) { )), map(rest, |a| (a, "", ())), )), - |(a, _, _)| a, + |(a, ..)| a, ), // not an scp url |a| { @@ -154,7 +151,7 @@ fn ssh_host(input: &str) -> IResult<&str, (&str, &str)> { Some((_, port_str, second_colon)) => { let full_host = &input[..(host.len() + colon.len() + port_str.len())]; Ok((rest, (full_host, second_colon))) - } + }, None => Ok((rest, (host, colon))), } } @@ -186,11 +183,7 @@ fn parse_url(url: &str) -> IResult<&str, UrlPrefix> { } fn not_empty(input: &str) -> Option<&str> { - if input.is_empty() { - None - } else { - Some(input) - } + if input.is_empty() { None } else { Some(input) } } fn empty_none<'a>((rest, opt): (&'a str, Option<&'a str>)) -> (&'a str, Option<&'a str>) { @@ -272,7 +265,7 @@ impl Aliases { Some((s, rest)) => { let res = self.get_alias(s)?; Cow::Owned(format!("{res}/{rest}")) - } + }, None => Cow::Borrowed(res), }; @@ -282,6 +275,7 @@ impl Aliases { impl Deref for Aliases { type Target = HashMap<&'static str, &'static str>; + fn deref(&self) -> &Self::Target { self.0 } @@ -434,6 +428,7 @@ impl<'a> AtomRef<'a> { impl<'a> TryFrom> for Uri { type Error = UriError; + fn try_from(refs: Ref<'a>) -> Result { let Ref { url, atom } = refs; @@ -449,6 +444,7 @@ impl<'a> TryFrom> for Uri { impl<'a> TryFrom> for Url { type Error = UriError; + fn try_from(refs: UrlRef<'a>) -> Result { match refs.to_url() { Some(url) => Ok(url), @@ -459,6 +455,7 @@ impl<'a> TryFrom> for Url { impl FromStr for Uri { type Err = UriError; + fn from_str(s: &str) -> Result { let r = Ref::from(s); Uri::try_from(r) @@ -467,6 +464,7 @@ impl FromStr for Uri { impl<'a> TryFrom<&'a str> for Uri { type Error = UriError; + fn try_from(s: &'a str) -> Result { s.parse() } @@ -494,11 +492,13 @@ impl Uri { pub fn url(&self) -> Option<&Url> { self.url.as_ref() } + #[must_use] /// Returns the Atom identifier parsed from the URI. pub fn id(&self) -> &Id { &self.id } + #[must_use] /// Returns the Atom version parsed from the URI. pub fn version(&self) -> Option<&VersionReq> { diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index fb6f2a5..716d2f7 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -1,15 +1,12 @@ -#[cfg(feature = "git")] -use gix::ThreadSafeRepository; +use std::collections::HashMap; +use std::sync::LazyLock; use etcetera::BaseStrategy; +use figment::providers::{Env, Format, Toml}; +use figment::{Figment, Metadata, Provider}; +#[cfg(feature = "git")] +use gix::ThreadSafeRepository; use serde::{Deserialize, Serialize}; -use std::collections::HashMap; - -use figment::{ - providers::{Env, Format, Toml}, - Figment, Metadata, Provider, -}; -use std::sync::LazyLock; /// Provide a lazyily instantiated static reference to /// a config object parsed from canonical locations @@ -83,6 +80,7 @@ impl Provider for Config { fn metadata(&self) -> figment::Metadata { Metadata::named("Eka CLI Config") } + fn data( &self, ) -> Result, figment::Error> { diff --git a/crates/nixec/src/main.rs b/crates/nixec/src/main.rs index 94ad2e8..6ff60da 100644 --- a/crates/nixec/src/main.rs +++ b/crates/nixec/src/main.rs @@ -1,10 +1,9 @@ -use birdcage::{process::Command, Birdcage, Exception, Sandbox}; -use std::process::ExitCode; -use std::{ - env, fs, - path::{Path, PathBuf}, - process::Command as UnsafeCommand, -}; +use std::path::{Path, PathBuf}; +use std::process::{Command as UnsafeCommand, ExitCode}; +use std::{env, fs}; + +use birdcage::process::Command; +use birdcage::{Birdcage, Exception, Sandbox}; use thiserror::Error; #[derive(Error, Debug)] diff --git a/dev/env/rust-toolchain.toml b/dev/env/rust-toolchain.toml index 7a28393..7d10897 100644 --- a/dev/env/rust-toolchain.toml +++ b/dev/env/rust-toolchain.toml @@ -1,4 +1,4 @@ [toolchain] channel = "1.81.0" -components = ["clippy", "rust-analyzer", "rust-src", "rustfmt"] +components = ["clippy", "rust-analyzer", "rust-src"] targets = ["x86_64-unknown-linux-musl"] diff --git a/dev/env/shell.nix b/dev/env/shell.nix index 592ece6..6ff3b50 100644 --- a/dev/env/shell.nix +++ b/dev/env/shell.nix @@ -11,6 +11,7 @@ pkgs.mkShell.override { stdenv = pkgs.clangStdenv; } { shfmt taplo nodePackages.prettier + atom.fenix.default.rustfmt toolchain mold cargo-insta diff --git a/src/cli/commands/init.rs b/src/cli/commands/init.rs index 315a91e..0120820 100644 --- a/src/cli/commands/init.rs +++ b/src/cli/commands/init.rs @@ -1,6 +1,7 @@ -use crate::cli::store::Detected; use clap::Parser; +use crate::cli::store::Detected; + #[derive(Parser, Debug)] pub struct Args { #[command(flatten)] @@ -31,8 +32,8 @@ pub(super) fn run(store: Detected, args: Args) -> Result<(), anyhow::Error> { .find_remote(args.git.remote.as_str()) .map_err(Box::new)?; remote.ekala_init()? - } - _ => {} + }, + _ => {}, } Ok(()) } diff --git a/src/cli/commands/mod.rs b/src/cli/commands/mod.rs index 19a85c2..84d0118 100644 --- a/src/cli/commands/mod.rs +++ b/src/cli/commands/mod.rs @@ -1,11 +1,11 @@ mod init; mod publish; +use clap::Subcommand; + use super::Args; use crate::cli::store; -use clap::Subcommand; - #[derive(Subcommand)] pub(super) enum Commands { /// Package and publish atoms to the atom store. @@ -33,7 +33,7 @@ pub async fn run(args: Args) -> anyhow::Result<()> { match args.command { Commands::Publish(args) => { publish::run(store.await?, args).await?; - } + }, Commands::Init(args) => init::run(store.await?, args)?, } diff --git a/src/cli/commands/publish/git/mod.rs b/src/cli/commands/publish/git/mod.rs index 1fc3e7b..a85fd85 100644 --- a/src/cli/commands/publish/git/mod.rs +++ b/src/cli/commands/publish/git/mod.rs @@ -1,18 +1,14 @@ -use super::PublishArgs; - -use atom::{ - publish::{ - error::git::Error, - git::{GitOutcome, GitResult}, - }, - store::git, -}; -use clap::Parser; use std::collections::HashSet; use std::path::PathBuf; +use atom::publish::error::git::Error; +use atom::publish::git::{GitOutcome, GitResult}; +use atom::store::git; +use clap::Parser; use gix::ThreadSafeRepository; +use super::PublishArgs; + #[derive(Parser, Debug)] #[command(next_help_heading = "Git Options")] pub(super) struct GitArgs { @@ -38,11 +34,11 @@ pub(super) async fn run( repo: &ThreadSafeRepository, args: PublishArgs, ) -> GitResult<(Vec>, Vec)> { - use atom::{ - publish::{git::GitPublisher, Builder, Publish}, - store::NormalizeStorePath, - }; use std::path::Path; + + use atom::publish::git::GitPublisher; + use atom::publish::{Builder, Publish}; + use atom::store::NormalizeStorePath; let repo = repo.to_thread_local(); let GitArgs { remote, spec } = args.store.git; diff --git a/src/cli/commands/publish/mod.rs b/src/cli/commands/publish/mod.rs index fa8e28c..a306574 100644 --- a/src/cli/commands/publish/mod.rs +++ b/src/cli/commands/publish/mod.rs @@ -1,11 +1,13 @@ #[cfg(feature = "git")] mod git; -use crate::cli::store::Detected; +use std::path::PathBuf; -use atom::publish::{self, error::PublishError}; +use atom::publish::error::PublishError; +use atom::publish::{self}; use clap::Parser; -use std::path::PathBuf; + +use crate::cli::store::Detected; #[derive(Parser, Debug)] #[command(arg_required_else_help = true)] @@ -35,9 +37,8 @@ pub(super) async fn run(store: Detected, args: PublishArgs) -> Result { - use atom::publish::{error, Content}; - use Err as Skipped; - use Ok as Published; + use atom::publish::{Content, error}; + use {Err as Skipped, Ok as Published}; let (results, mut errors) = git::run(repo, args).await?; for res in results { @@ -51,15 +52,15 @@ pub(super) async fn run(store: Detected, args: PublishArgs) -> Result { stats.skipped += 1; tracing::info!(atom.id = %id, "Skipping existing atom") - } + }, Err(e) => { stats.failed += 1; errors.push(e) - } + }, } } @@ -72,8 +73,8 @@ pub(super) async fn run(store: Detected, args: PublishArgs) -> Result {} + }, + _ => {}, } Ok(stats) diff --git a/src/cli/logging.rs b/src/cli/logging.rs index d092610..f8ae94f 100644 --- a/src/cli/logging.rs +++ b/src/cli/logging.rs @@ -1,12 +1,13 @@ -use super::{Args, LogArgs}; +use std::str::FromStr; use clap::Parser; -use std::str::FromStr; use tracing_error::ErrorLayer; use tracing_subscriber::filter::{EnvFilter, LevelFilter}; -use tracing_subscriber::fmt; -use tracing_subscriber::Layer; -use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; +use tracing_subscriber::layer::SubscriberExt; +use tracing_subscriber::util::SubscriberInitExt; +use tracing_subscriber::{Layer, fmt}; + +use super::{Args, LogArgs}; fn get_log_level(args: LogArgs) -> LevelFilter { if args.quiet { @@ -74,8 +75,7 @@ pub mod ansi { #[macro_export] macro_rules! fatal { ($error:expr) => {{ - use $crate::cli::logging::ansi; - use $crate::cli::logging::ANSI; + use $crate::cli::logging::{ANSI, ansi}; let ansi = ANSI.load(std::sync::atomic::Ordering::SeqCst); tracing::error!( fatal = true, diff --git a/src/cli/mod.rs b/src/cli/mod.rs index e19273b..747bf6a 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -3,11 +3,11 @@ mod commands; pub mod logging; mod store; -pub use commands::run; -pub use logging::init_global_subscriber; +use std::path::PathBuf; use clap::Parser; -use std::path::PathBuf; +pub use commands::run; +pub use logging::init_global_subscriber; #[derive(Parser)] #[command(author, version, about, long_about = None)] diff --git a/src/cli/store.rs b/src/cli/store.rs index 8fb9810..b7ea544 100644 --- a/src/cli/store.rs +++ b/src/cli/store.rs @@ -1,9 +1,8 @@ #[cfg(feature = "git")] use atom::store::git; -use thiserror::Error; - #[cfg(feature = "git")] use gix::ThreadSafeRepository; +use thiserror::Error; #[non_exhaustive] #[derive(Clone, Debug)] diff --git a/src/main.rs b/src/main.rs index f1e9bb1..a148698 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,7 @@ +use std::process::ExitCode; + use clap::Parser; use eka::cli::{self, Args}; -use std::process::ExitCode; #[tokio::main] async fn main() -> ExitCode { diff --git a/treefmt.toml b/treefmt.toml index 30b2111..ce3c41f 100644 --- a/treefmt.toml +++ b/treefmt.toml @@ -26,4 +26,3 @@ options = ["--write"] command = "rustfmt" excludes = [] includes = ["*.rs"] -options = ["--edition", "2021"]