diff --git a/Cargo.lock b/Cargo.lock index 36cf8804aac..7d15ced84f8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -257,6 +257,7 @@ dependencies = [ "cargo-test-macro", "cargo-test-support", "cargo-util", + "cargo-util-schemas", "clap", "color-print", "crates-io", @@ -297,7 +298,6 @@ dependencies = [ "semver", "serde", "serde-untagged", - "serde-value", "serde_ignored", "serde_json", "sha1", @@ -314,7 +314,6 @@ dependencies = [ "tracing-subscriber", "unicase", "unicode-width", - "unicode-xid", "url", "walkdir", "windows-sys 0.52.0", @@ -436,6 +435,20 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "cargo-util-schemas" +version = "0.1.0" +dependencies = [ + "anyhow", + "semver", + "serde", + "serde-untagged", + "serde-value", + "toml", + "unicode-xid", + "url", +] + [[package]] name = "cargo_metadata" version = "0.18.1" @@ -2821,6 +2834,7 @@ version = "0.0.0" dependencies = [ "cargo", "cargo-util", + "cargo-util-schemas", "proptest", "varisat", ] diff --git a/Cargo.toml b/Cargo.toml index 317a0df0e1f..f91661a5ce6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,6 +30,7 @@ cargo-platform = { path = "crates/cargo-platform", version = "0.1.4" } cargo-test-macro = { path = "crates/cargo-test-macro" } cargo-test-support = { path = "crates/cargo-test-support" } cargo-util = { version = "0.2.6", path = "crates/cargo-util" } +cargo-util-schemas = { version = "0.1.0", path = "crates/cargo-util-schemas" } cargo_metadata = "0.18.1" clap = "4.4.10" color-print = "0.3.5" @@ -144,6 +145,7 @@ base64.workspace = true bytesize.workspace = true cargo-credential.workspace = true cargo-platform.workspace = true +cargo-util-schemas.workspace = true cargo-util.workspace = true clap = { workspace = true, features = ["wrap_help"] } color-print.workspace = true @@ -183,7 +185,6 @@ rustfix.workspace = true semver.workspace = true serde = { workspace = true, features = ["derive"] } serde-untagged.workspace = true -serde-value.workspace = true serde_ignored.workspace = true serde_json = { workspace = true, features = ["raw_value"] } sha1.workspace = true @@ -199,7 +200,6 @@ tracing.workspace = true tracing-subscriber.workspace = true unicase.workspace = true unicode-width.workspace = true -unicode-xid.workspace = true url.workspace = true walkdir.workspace = true diff --git a/crates/cargo-util-schemas/Cargo.toml b/crates/cargo-util-schemas/Cargo.toml new file mode 100644 index 00000000000..24d1801ff4f --- /dev/null +++ b/crates/cargo-util-schemas/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "cargo-util-schemas" +version = "0.1.0" +rust-version.workspace = true +edition.workspace = true +license.workspace = true +homepage = "https://github.com/rust-lang/cargo" +repository = "https://github.com/rust-lang/cargo" +description = "Deserialization schemas for Cargo" + +[dependencies] +anyhow.workspace = true +semver.workspace = true +serde = { workspace = true, features = ["derive"] } +serde-untagged.workspace = true +serde-value.workspace = true +toml.workspace = true +unicode-xid.workspace = true +url.workspace = true + +[lints] +workspace = true diff --git a/crates/cargo-util-schemas/LICENSE-APACHE b/crates/cargo-util-schemas/LICENSE-APACHE new file mode 120000 index 00000000000..1cd601d0a3a --- /dev/null +++ b/crates/cargo-util-schemas/LICENSE-APACHE @@ -0,0 +1 @@ +../../LICENSE-APACHE \ No newline at end of file diff --git a/crates/cargo-util-schemas/LICENSE-MIT b/crates/cargo-util-schemas/LICENSE-MIT new file mode 120000 index 00000000000..b2cfbdc7b0b --- /dev/null +++ b/crates/cargo-util-schemas/LICENSE-MIT @@ -0,0 +1 @@ +../../LICENSE-MIT \ No newline at end of file diff --git a/src/cargo/util_schemas/core/mod.rs b/crates/cargo-util-schemas/src/core/mod.rs similarity index 70% rename from src/cargo/util_schemas/core/mod.rs rename to crates/cargo-util-schemas/src/core/mod.rs index 2001a6bc7ee..aad6d1488f3 100644 --- a/src/cargo/util_schemas/core/mod.rs +++ b/crates/cargo-util-schemas/src/core/mod.rs @@ -1,6 +1,8 @@ mod package_id_spec; +mod partial_version; mod source_kind; pub use package_id_spec::PackageIdSpec; +pub use partial_version::PartialVersion; pub use source_kind::GitReference; pub use source_kind::SourceKind; diff --git a/src/cargo/util_schemas/core/package_id_spec.rs b/crates/cargo-util-schemas/src/core/package_id_spec.rs similarity index 98% rename from src/cargo/util_schemas/core/package_id_spec.rs rename to crates/cargo-util-schemas/src/core/package_id_spec.rs index 015bfa928d7..e0a706750af 100644 --- a/src/cargo/util_schemas/core/package_id_spec.rs +++ b/crates/cargo-util-schemas/src/core/package_id_spec.rs @@ -6,10 +6,10 @@ use semver::Version; use serde::{de, ser}; use url::Url; -use crate::util_schemas::core::GitReference; -use crate::util_schemas::core::SourceKind; -use crate::util_schemas::manifest::PackageName; -use crate::util_semver::PartialVersion; +use crate::core::GitReference; +use crate::core::PartialVersion; +use crate::core::SourceKind; +use crate::manifest::PackageName; /// Some or all of the data required to identify a package: /// @@ -59,7 +59,7 @@ impl PackageIdSpec { /// Some examples of valid strings /// /// ``` - /// use cargo::core::PackageIdSpec; + /// use cargo_util_schemas::core::PackageIdSpec; /// /// let specs = vec![ /// "https://crates.io/foo", @@ -280,7 +280,7 @@ impl<'de> de::Deserialize<'de> for PackageIdSpec { #[cfg(test)] mod tests { use super::PackageIdSpec; - use crate::util_schemas::core::{GitReference, SourceKind}; + use crate::core::{GitReference, SourceKind}; use url::Url; #[test] diff --git a/src/cargo/util_semver.rs b/crates/cargo-util-schemas/src/core/partial_version.rs similarity index 90% rename from src/cargo/util_semver.rs rename to crates/cargo-util-schemas/src/core/partial_version.rs index a84c9ee582e..9670bd87764 100644 --- a/src/cargo/util_semver.rs +++ b/crates/cargo-util-schemas/src/core/partial_version.rs @@ -1,32 +1,8 @@ use std::fmt::{self, Display}; -use semver::{Comparator, Op, Version, VersionReq}; +use semver::{Comparator, Version, VersionReq}; use serde_untagged::UntaggedEnumVisitor; -pub trait VersionExt { - fn is_prerelease(&self) -> bool; - - fn to_exact_req(&self) -> VersionReq; -} - -impl VersionExt for Version { - fn is_prerelease(&self) -> bool { - !self.pre.is_empty() - } - - fn to_exact_req(&self) -> VersionReq { - VersionReq { - comparators: vec![Comparator { - op: Op::Exact, - major: self.major, - minor: Some(self.minor), - patch: Some(self.patch), - pre: self.pre.clone(), - }], - } - } -} - #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Debug)] pub struct PartialVersion { pub major: u64, diff --git a/src/cargo/util_schemas/core/source_kind.rs b/crates/cargo-util-schemas/src/core/source_kind.rs similarity index 100% rename from src/cargo/util_schemas/core/source_kind.rs rename to crates/cargo-util-schemas/src/core/source_kind.rs diff --git a/src/cargo/util_schemas/mod.rs b/crates/cargo-util-schemas/src/lib.rs similarity index 100% rename from src/cargo/util_schemas/mod.rs rename to crates/cargo-util-schemas/src/lib.rs diff --git a/src/cargo/util_schemas/manifest.rs b/crates/cargo-util-schemas/src/manifest.rs similarity index 99% rename from src/cargo/util_schemas/manifest.rs rename to crates/cargo-util-schemas/src/manifest.rs index 390658b0e46..eb6d4ea4852 100644 --- a/src/cargo/util_schemas/manifest.rs +++ b/crates/cargo-util-schemas/src/manifest.rs @@ -16,9 +16,9 @@ use serde::ser; use serde::{Deserialize, Serialize}; use serde_untagged::UntaggedEnumVisitor; -use crate::util_schemas::core::PackageIdSpec; -use crate::util_schemas::restricted_names; -use crate::util_semver::PartialVersion; +use crate::core::PackageIdSpec; +use crate::core::PartialVersion; +use crate::restricted_names; /// This type is used to deserialize `Cargo.toml` files. #[derive(Debug, Deserialize, Serialize)] diff --git a/src/cargo/util_schemas/restricted_names.rs b/crates/cargo-util-schemas/src/restricted_names.rs similarity index 100% rename from src/cargo/util_schemas/restricted_names.rs rename to crates/cargo-util-schemas/src/restricted_names.rs diff --git a/crates/resolver-tests/Cargo.toml b/crates/resolver-tests/Cargo.toml index 947c445698e..11d5b5d0d83 100644 --- a/crates/resolver-tests/Cargo.toml +++ b/crates/resolver-tests/Cargo.toml @@ -7,6 +7,7 @@ publish = false [dependencies] cargo.workspace = true +cargo-util-schemas.workspace = true cargo-util.workspace = true proptest.workspace = true varisat.workspace = true diff --git a/crates/resolver-tests/src/lib.rs b/crates/resolver-tests/src/lib.rs index 2df7a36bb09..00d64894ef5 100644 --- a/crates/resolver-tests/src/lib.rs +++ b/crates/resolver-tests/src/lib.rs @@ -19,7 +19,7 @@ use cargo::core::{GitReference, SourceId}; use cargo::sources::source::QueryKind; use cargo::sources::IndexSummary; use cargo::util::{CargoResult, Config, IntoUrl}; -use cargo::util_schemas::manifest::RustVersion; +use cargo_util_schemas::manifest::RustVersion; use proptest::collection::{btree_map, vec}; use proptest::prelude::*; diff --git a/crates/xtask-bump-check/src/xtask.rs b/crates/xtask-bump-check/src/xtask.rs index db82fff632f..49393680aa9 100644 --- a/crates/xtask-bump-check/src/xtask.rs +++ b/crates/xtask-bump-check/src/xtask.rs @@ -168,6 +168,7 @@ fn bump_check(args: &clap::ArgMatches, config: &cargo::util::Config) -> CargoRes let mut cmd = ProcessBuilder::new("cargo"); cmd.arg("semver-checks") .arg("check-release") + .args(&["--exclude", "cargo-util-schemas"]) // FIXME: Remove once 1.76 is stable .arg("--workspace"); config.shell().status("Running", &cmd)?; cmd.exec()?; @@ -177,6 +178,7 @@ fn bump_check(args: &clap::ArgMatches, config: &cargo::util::Config) -> CargoRes cmd.arg("semver-checks") .arg("--workspace") .args(&["--exclude", "rustfix"]) // FIXME: Remove once 1.76 is stable + .args(&["--exclude", "cargo-util-schemas"]) // FIXME: Remove once 1.76 is stable .arg("--baseline-rev") .arg(referenced_commit.id().to_string()); for krate in crates_not_check_against_channels { diff --git a/publish.py b/publish.py index 114d7dbbd59..f84d360dad3 100755 --- a/publish.py +++ b/publish.py @@ -25,6 +25,7 @@ 'crates/cargo-platform', 'crates/cargo-util', 'crates/crates-io', + 'crates/cargo-util-schemas', '.', ] diff --git a/src/bin/cargo/commands/install.rs b/src/bin/cargo/commands/install.rs index b3d379c41be..c391c844bc5 100644 --- a/src/bin/cargo/commands/install.rs +++ b/src/bin/cargo/commands/install.rs @@ -6,7 +6,7 @@ use anyhow::format_err; use cargo::core::{GitReference, SourceId, Workspace}; use cargo::ops; use cargo::util::IntoUrl; -use cargo::util_semver::VersionExt; +use cargo::util::VersionExt; use cargo::CargoResult; use itertools::Itertools; use semver::VersionReq; diff --git a/src/bin/cargo/main.rs b/src/bin/cargo/main.rs index 14a4206d659..8cf745f91c8 100644 --- a/src/bin/cargo/main.rs +++ b/src/bin/cargo/main.rs @@ -4,8 +4,8 @@ use cargo::util::network::http::http_handle; use cargo::util::network::http::needs_custom_http_transport; use cargo::util::CliError; use cargo::util::{self, closest_msg, command_prelude, CargoResult, CliResult, Config}; -use cargo::util_schemas::manifest::StringOrVec; use cargo_util::{ProcessBuilder, ProcessError}; +use cargo_util_schemas::manifest::StringOrVec; use std::collections::BTreeMap; use std::env; use std::ffi::OsStr; diff --git a/src/cargo/core/compiler/mod.rs b/src/cargo/core/compiler/mod.rs index 170b59b265b..2c3a5c1d883 100644 --- a/src/cargo/core/compiler/mod.rs +++ b/src/cargo/core/compiler/mod.rs @@ -94,9 +94,9 @@ use crate::util::errors::{CargoResult, VerboseError}; use crate::util::interning::InternedString; use crate::util::machine_message::{self, Message}; use crate::util::{add_path_args, internal, iter_join_onto, profile}; -use crate::util_schemas::manifest::TomlDebugInfo; -use crate::util_schemas::manifest::TomlTrimPaths; use cargo_util::{paths, ProcessBuilder, ProcessError}; +use cargo_util_schemas::manifest::TomlDebugInfo; +use cargo_util_schemas::manifest::TomlTrimPaths; use rustfix::diagnostics::Applicability; const RUSTDOC_CRATE_VERSION_FLAG: &str = "--crate-version"; diff --git a/src/cargo/core/manifest.rs b/src/cargo/core/manifest.rs index 0468caa9627..ac0bb44f929 100644 --- a/src/cargo/core/manifest.rs +++ b/src/cargo/core/manifest.rs @@ -6,6 +6,8 @@ use std::rc::Rc; use std::sync::Arc; use anyhow::Context as _; +use cargo_util_schemas::manifest::RustVersion; +use cargo_util_schemas::manifest::{TomlManifest, TomlProfiles}; use semver::Version; use serde::ser; use serde::Serialize; @@ -19,8 +21,6 @@ use crate::core::{Edition, Feature, Features, WorkspaceConfig}; use crate::util::errors::*; use crate::util::interning::InternedString; use crate::util::{short_hash, Config, Filesystem}; -use crate::util_schemas::manifest::RustVersion; -use crate::util_schemas::manifest::{TomlManifest, TomlProfiles}; pub enum EitherManifest { Real(Manifest), diff --git a/src/cargo/core/mod.rs b/src/cargo/core/mod.rs index f3b3142fa73..bdc9b2f4fe6 100644 --- a/src/cargo/core/mod.rs +++ b/src/cargo/core/mod.rs @@ -14,7 +14,7 @@ pub use self::workspace::{ find_workspace_root, resolve_relative_path, MaybePackage, Workspace, WorkspaceConfig, WorkspaceRootConfig, }; -pub use crate::util_schemas::core::{GitReference, PackageIdSpec, SourceKind}; +pub use cargo_util_schemas::core::{GitReference, PackageIdSpec, SourceKind}; pub mod compiler; pub mod dependency; diff --git a/src/cargo/core/package.rs b/src/cargo/core/package.rs index 08254488283..a7713eca1de 100644 --- a/src/cargo/core/package.rs +++ b/src/cargo/core/package.rs @@ -10,6 +10,7 @@ use std::time::{Duration, Instant}; use anyhow::Context; use bytesize::ByteSize; +use cargo_util_schemas::manifest::RustVersion; use curl::easy::Easy; use curl::multi::{EasyHandle, Multi}; use lazycell::LazyCell; @@ -33,7 +34,6 @@ use crate::util::network::retry::{Retry, RetryResult}; use crate::util::network::sleep::SleepTracker; use crate::util::toml::prepare_for_publish; use crate::util::{self, internal, Config, Progress, ProgressStyle}; -use crate::util_schemas::manifest::RustVersion; pub const MANIFEST_PREAMBLE: &str = "\ # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO diff --git a/src/cargo/core/profiles.rs b/src/cargo/core/profiles.rs index 4d2a23f5060..090e2183bcd 100644 --- a/src/cargo/core/profiles.rs +++ b/src/cargo/core/profiles.rs @@ -31,12 +31,12 @@ use crate::core::{ use crate::util::interning::InternedString; use crate::util::toml::validate_profile; use crate::util::{closest_msg, config, CargoResult, Config}; -use crate::util_schemas::manifest::TomlTrimPaths; -use crate::util_schemas::manifest::TomlTrimPathsValue; -use crate::util_schemas::manifest::{ +use anyhow::{bail, Context as _}; +use cargo_util_schemas::manifest::TomlTrimPaths; +use cargo_util_schemas::manifest::TomlTrimPathsValue; +use cargo_util_schemas::manifest::{ ProfilePackageSpec, StringOrBool, TomlDebugInfo, TomlProfile, TomlProfiles, }; -use anyhow::{bail, Context as _}; use std::collections::{BTreeMap, HashMap, HashSet}; use std::hash::Hash; use std::{cmp, fmt, hash}; diff --git a/src/cargo/core/resolver/errors.rs b/src/cargo/core/resolver/errors.rs index f3e72c51bb1..4ecce02b5f0 100644 --- a/src/cargo/core/resolver/errors.rs +++ b/src/cargo/core/resolver/errors.rs @@ -4,8 +4,7 @@ use std::task::Poll; use crate::core::{Dependency, PackageId, Registry, Summary}; use crate::sources::source::QueryKind; use crate::util::edit_distance::edit_distance; -use crate::util::{Config, OptVersionReq}; -use crate::util_semver::VersionExt; +use crate::util::{Config, OptVersionReq, VersionExt}; use anyhow::Error; use super::context::Context; diff --git a/src/cargo/core/resolver/version_prefs.rs b/src/cargo/core/resolver/version_prefs.rs index 1e4eacb591f..e84d24ba066 100644 --- a/src/cargo/core/resolver/version_prefs.rs +++ b/src/cargo/core/resolver/version_prefs.rs @@ -4,9 +4,10 @@ use std::cmp::Ordering; use std::collections::{HashMap, HashSet}; +use cargo_util_schemas::manifest::RustVersion; + use crate::core::{Dependency, PackageId, Summary}; use crate::util::interning::InternedString; -use crate::util_schemas::manifest::RustVersion; /// A collection of preferences for particular package versions. /// diff --git a/src/cargo/core/summary.rs b/src/cargo/core/summary.rs index 2137d633250..5f73362cf33 100644 --- a/src/cargo/core/summary.rs +++ b/src/cargo/core/summary.rs @@ -1,9 +1,9 @@ use crate::core::{Dependency, PackageId, SourceId}; use crate::util::interning::InternedString; use crate::util::CargoResult; -use crate::util_schemas::manifest::FeatureName; -use crate::util_schemas::manifest::RustVersion; use anyhow::bail; +use cargo_util_schemas::manifest::FeatureName; +use cargo_util_schemas::manifest::RustVersion; use semver::Version; use std::collections::{BTreeMap, HashMap, HashSet}; use std::fmt; diff --git a/src/cargo/core/workspace.rs b/src/cargo/core/workspace.rs index b933c61731d..6bb8188dc3a 100644 --- a/src/cargo/core/workspace.rs +++ b/src/cargo/core/workspace.rs @@ -26,10 +26,10 @@ use crate::util::errors::{CargoResult, ManifestError}; use crate::util::interning::InternedString; use crate::util::toml::{read_manifest, InheritableFields}; use crate::util::{config::ConfigRelativePath, Config, Filesystem, IntoUrl}; -use crate::util_schemas::manifest::RustVersion; -use crate::util_schemas::manifest::{TomlDependency, TomlProfiles}; use cargo_util::paths; use cargo_util::paths::normalize_path; +use cargo_util_schemas::manifest::RustVersion; +use cargo_util_schemas::manifest::{TomlDependency, TomlProfiles}; use pathdiff::diff_paths; /// The core abstraction in Cargo for working with a workspace of crates. diff --git a/src/cargo/lib.rs b/src/cargo/lib.rs index 6d7468ca3b0..9419ce5e31a 100644 --- a/src/cargo/lib.rs +++ b/src/cargo/lib.rs @@ -62,6 +62,9 @@ //! - [`cargo-util`](https://crates.io/crates/cargo-util) //! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/cargo_util)): //! This contains general utility code that is shared between cargo and the testsuite +//! - [`cargo-util-schemas`](https://crates.io/crates/cargo-util-schemas) +//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/cargo_util-schemas)): +//! This contains the serde schemas for cargo //! - [`crates-io`](https://crates.io/crates/crates-io) //! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/crates_io)): //! This contains code for accessing the crates.io API. @@ -98,7 +101,7 @@ //! Files that interact with cargo include //! //! - Package -//! - `Cargo.toml`: User-written project manifest, loaded with [`util_schemas::manifest::TomlManifest`] and then +//! - `Cargo.toml`: User-written project manifest, loaded with [`util::toml::read_manifest`] and then //! translated to [`core::manifest::Manifest`] which maybe stored in a [`core::Package`]. //! - This is editable with [`util::toml_mut::manifest::LocalManifest`] //! - `Cargo.lock`: Generally loaded with [`ops::resolve_ws`] or a variant of it into a [`core::resolver::Resolve`] @@ -152,8 +155,6 @@ pub mod core; pub mod ops; pub mod sources; pub mod util; -pub mod util_schemas; -pub mod util_semver; mod version; pub fn exit_with_error(err: CliError, shell: &mut Shell) -> ! { diff --git a/src/cargo/ops/cargo_add/crate_spec.rs b/src/cargo/ops/cargo_add/crate_spec.rs index 65c58314f65..d8825456c4a 100644 --- a/src/cargo/ops/cargo_add/crate_spec.rs +++ b/src/cargo/ops/cargo_add/crate_spec.rs @@ -4,8 +4,8 @@ use anyhow::Context as _; use super::Dependency; use crate::util::toml_mut::dependency::RegistrySource; -use crate::util_schemas::manifest::PackageName; use crate::CargoResult; +use cargo_util_schemas::manifest::PackageName; /// User-specified crate /// diff --git a/src/cargo/ops/cargo_add/mod.rs b/src/cargo/ops/cargo_add/mod.rs index 9be290b4818..8409df7324b 100644 --- a/src/cargo/ops/cargo_add/mod.rs +++ b/src/cargo/ops/cargo_add/mod.rs @@ -11,6 +11,7 @@ use std::str::FromStr; use anyhow::Context as _; use cargo_util::paths; +use cargo_util_schemas::manifest::RustVersion; use indexmap::IndexSet; use itertools::Itertools; use toml_edit::Item as TomlItem; @@ -35,7 +36,6 @@ use crate::util::toml_mut::dependency::WorkspaceSource; use crate::util::toml_mut::is_sorted; use crate::util::toml_mut::manifest::DepTable; use crate::util::toml_mut::manifest::LocalManifest; -use crate::util_schemas::manifest::RustVersion; use crate::CargoResult; use crate::Config; use crate_spec::CrateSpec; diff --git a/src/cargo/ops/cargo_new.rs b/src/cargo/ops/cargo_new.rs index 57c7e268e3a..f126a5f469a 100644 --- a/src/cargo/ops/cargo_new.rs +++ b/src/cargo/ops/cargo_new.rs @@ -4,9 +4,9 @@ use crate::util::important_paths::find_root_manifest_for_wd; use crate::util::toml_mut::is_sorted; use crate::util::{existing_vcs_repo, FossilRepo, GitRepo, HgRepo, PijulRepo}; use crate::util::{restricted_names, Config}; -use crate::util_schemas::manifest::PackageName; use anyhow::{anyhow, Context}; use cargo_util::paths::{self, write_atomic}; +use cargo_util_schemas::manifest::PackageName; use serde::de; use serde::Deserialize; use std::collections::BTreeMap; diff --git a/src/cargo/ops/resolve.rs b/src/cargo/ops/resolve.rs index 5421d05724b..b00dc15004e 100644 --- a/src/cargo/ops/resolve.rs +++ b/src/cargo/ops/resolve.rs @@ -72,8 +72,8 @@ use crate::sources::PathSource; use crate::util::cache_lock::CacheLockMode; use crate::util::errors::CargoResult; use crate::util::{profile, CanonicalUrl}; -use crate::util_schemas::manifest::RustVersion; use anyhow::Context as _; +use cargo_util_schemas::manifest::RustVersion; use std::collections::{HashMap, HashSet}; use tracing::{debug, trace}; diff --git a/src/cargo/sources/git/mod.rs b/src/cargo/sources/git/mod.rs index 4c01016c249..0b2cb9908e1 100644 --- a/src/cargo/sources/git/mod.rs +++ b/src/cargo/sources/git/mod.rs @@ -8,7 +8,7 @@ //! [CVE-2022-46176]: https://blog.rust-lang.org/2023/01/10/cve-2022-46176.html pub use self::source::GitSource; -pub use self::utils::{fetch, GitCheckout, GitDatabase, GitRemote}; +pub use self::utils::{fetch, resolve_ref, GitCheckout, GitDatabase, GitRemote}; mod known_hosts; mod oxide; mod source; diff --git a/src/cargo/sources/git/utils.rs b/src/cargo/sources/git/utils.rs index 74690d30c7b..7ce43d9bd1f 100644 --- a/src/cargo/sources/git/utils.rs +++ b/src/cargo/sources/git/utils.rs @@ -123,7 +123,7 @@ impl GitRemote { let resolved_commit_hash = match locked_rev { Some(rev) => db.contains(rev).then_some(rev), - None => reference.resolve(&db.repo).ok(), + None => resolve_ref(reference, &db.repo).ok(), }; if let Some(rev) = resolved_commit_hash { return Ok((db, rev)); @@ -148,7 +148,7 @@ impl GitRemote { .with_context(|| format!("failed to clone into: {}", into.display()))?; let rev = match locked_rev { Some(rev) => rev, - None => reference.resolve(&repo)?, + None => resolve_ref(reference, &repo)?, }; Ok(( @@ -207,56 +207,54 @@ impl GitDatabase { self.repo.revparse_single(&oid.to_string()).is_ok() } - /// [`GitReference::resolve`]s this reference with this database. + /// [`resolve_ref`]s this reference with this database. pub fn resolve(&self, r: &GitReference) -> CargoResult { - r.resolve(&self.repo) + resolve_ref(r, &self.repo) } } -impl GitReference { - /// Resolves self to an object ID with objects the `repo` currently has. - pub fn resolve(&self, repo: &git2::Repository) -> CargoResult { - let id = match self { - // Note that we resolve the named tag here in sync with where it's - // fetched into via `fetch` below. - GitReference::Tag(s) => (|| -> CargoResult { - let refname = format!("refs/remotes/origin/tags/{}", s); - let id = repo.refname_to_id(&refname)?; - let obj = repo.find_object(id, None)?; - let obj = obj.peel(ObjectType::Commit)?; - Ok(obj.id()) - })() - .with_context(|| format!("failed to find tag `{}`", s))?, - - // Resolve the remote name since that's all we're configuring in - // `fetch` below. - GitReference::Branch(s) => { - let name = format!("origin/{}", s); - let b = repo - .find_branch(&name, git2::BranchType::Remote) - .with_context(|| format!("failed to find branch `{}`", s))?; - b.get() - .target() - .ok_or_else(|| anyhow::format_err!("branch `{}` did not have a target", s))? - } +/// Resolves [`GitReference`] to an object ID with objects the `repo` currently has. +pub fn resolve_ref(gitref: &GitReference, repo: &git2::Repository) -> CargoResult { + let id = match gitref { + // Note that we resolve the named tag here in sync with where it's + // fetched into via `fetch` below. + GitReference::Tag(s) => (|| -> CargoResult { + let refname = format!("refs/remotes/origin/tags/{}", s); + let id = repo.refname_to_id(&refname)?; + let obj = repo.find_object(id, None)?; + let obj = obj.peel(ObjectType::Commit)?; + Ok(obj.id()) + })() + .with_context(|| format!("failed to find tag `{}`", s))?, + + // Resolve the remote name since that's all we're configuring in + // `fetch` below. + GitReference::Branch(s) => { + let name = format!("origin/{}", s); + let b = repo + .find_branch(&name, git2::BranchType::Remote) + .with_context(|| format!("failed to find branch `{}`", s))?; + b.get() + .target() + .ok_or_else(|| anyhow::format_err!("branch `{}` did not have a target", s))? + } - // We'll be using the HEAD commit - GitReference::DefaultBranch => { - let head_id = repo.refname_to_id("refs/remotes/origin/HEAD")?; - let head = repo.find_object(head_id, None)?; - head.peel(ObjectType::Commit)?.id() - } + // We'll be using the HEAD commit + GitReference::DefaultBranch => { + let head_id = repo.refname_to_id("refs/remotes/origin/HEAD")?; + let head = repo.find_object(head_id, None)?; + head.peel(ObjectType::Commit)?.id() + } - GitReference::Rev(s) => { - let obj = repo.revparse_single(s)?; - match obj.as_tag() { - Some(tag) => tag.target_id(), - None => obj.id(), - } + GitReference::Rev(s) => { + let obj = repo.revparse_single(s)?; + match obj.as_tag() { + Some(tag) => tag.target_id(), + None => obj.id(), } - }; - Ok(id) - } + } + }; + Ok(id) } impl<'a> GitCheckout<'a> { @@ -1404,7 +1402,7 @@ fn github_fast_path( return Ok(FastPathRev::Indeterminate); } - let local_object = reference.resolve(repo).ok(); + let local_object = resolve_ref(reference, repo).ok(); let github_branch_name = match reference { GitReference::Branch(branch) => branch, diff --git a/src/cargo/sources/registry/index.rs b/src/cargo/sources/registry/index.rs index aed8fc813b5..65da727d78a 100644 --- a/src/cargo/sources/registry/index.rs +++ b/src/cargo/sources/registry/index.rs @@ -93,9 +93,9 @@ use crate::util::cache_lock::CacheLockMode; use crate::util::interning::InternedString; use crate::util::IntoUrl; use crate::util::{internal, CargoResult, Config, Filesystem, OptVersionReq}; -use crate::util_schemas::manifest::RustVersion; use anyhow::bail; use cargo_util::{paths, registry::make_dep_path}; +use cargo_util_schemas::manifest::RustVersion; use semver::Version; use serde::Deserialize; use std::borrow::Cow; diff --git a/src/cargo/sources/registry/remote.rs b/src/cargo/sources/registry/remote.rs index 841ee3683d9..34df41ffa9b 100644 --- a/src/cargo/sources/registry/remote.rs +++ b/src/cargo/sources/registry/remote.rs @@ -4,6 +4,7 @@ use crate::core::global_cache_tracker; use crate::core::{GitReference, PackageId, SourceId}; use crate::sources::git; use crate::sources::git::fetch::RemoteKind; +use crate::sources::git::resolve_ref; use crate::sources::registry::download; use crate::sources::registry::MaybeLock; use crate::sources::registry::{LoadResponse, RegistryConfig, RegistryData}; @@ -149,7 +150,7 @@ impl<'cfg> RemoteRegistry<'cfg> { fn head(&self) -> CargoResult { if self.head.get().is_none() { let repo = self.repo()?; - let oid = self.index_git_ref.resolve(repo)?; + let oid = resolve_ref(&self.index_git_ref, repo)?; self.head.set(Some(oid)); } Ok(self.head.get().unwrap()) diff --git a/src/cargo/util/command_prelude.rs b/src/cargo/util/command_prelude.rs index 24c8c098dde..b0584fb6378 100644 --- a/src/cargo/util/command_prelude.rs +++ b/src/cargo/util/command_prelude.rs @@ -11,12 +11,12 @@ use crate::util::{ print_available_benches, print_available_binaries, print_available_examples, print_available_packages, print_available_tests, }; -use crate::util_schemas::manifest::ProfileName; -use crate::util_schemas::manifest::RegistryName; -use crate::util_schemas::manifest::StringOrVec; use crate::CargoResult; use anyhow::bail; use cargo_util::paths; +use cargo_util_schemas::manifest::ProfileName; +use cargo_util_schemas::manifest::RegistryName; +use cargo_util_schemas::manifest::StringOrVec; use clap::builder::UnknownArgumentValueParser; use std::ffi::{OsStr, OsString}; use std::path::Path; diff --git a/src/cargo/util/config/mod.rs b/src/cargo/util/config/mod.rs index 1c1b949a783..2362aa7e73b 100644 --- a/src/cargo/util/config/mod.rs +++ b/src/cargo/util/config/mod.rs @@ -80,10 +80,10 @@ use crate::util::network::http::http_handle; use crate::util::try_canonicalize; use crate::util::{internal, CanonicalUrl}; use crate::util::{Filesystem, IntoUrl, IntoUrlWithBase, Rustc}; -use crate::util_schemas::manifest::RegistryName; use anyhow::{anyhow, bail, format_err, Context as _}; use cargo_credential::Secret; use cargo_util::paths; +use cargo_util_schemas::manifest::RegistryName; use curl::easy::Easy; use lazycell::LazyCell; use serde::de::IntoDeserializer as _; diff --git a/src/cargo/util/mod.rs b/src/cargo/util/mod.rs index e5ecd077fd7..12d8e6afdd7 100644 --- a/src/cargo/util/mod.rs +++ b/src/cargo/util/mod.rs @@ -22,7 +22,7 @@ pub use self::lockserver::{LockServer, LockServerClient, LockServerStarted}; pub use self::progress::{Progress, ProgressStyle}; pub use self::queue::Queue; pub use self::rustc::Rustc; -pub use self::semver_ext::OptVersionReq; +pub use self::semver_ext::{OptVersionReq, VersionExt}; pub use self::vcs::{existing_vcs_repo, FossilRepo, GitRepo, HgRepo, PijulRepo}; pub use self::workspace::{ add_path_args, path_args, print_available_benches, print_available_binaries, diff --git a/src/cargo/util/semver_ext.rs b/src/cargo/util/semver_ext.rs index 854fab6c8a2..fed957ef7d9 100644 --- a/src/cargo/util/semver_ext.rs +++ b/src/cargo/util/semver_ext.rs @@ -1,8 +1,30 @@ use std::fmt::{self, Display}; -use semver::{Op, Version, VersionReq}; +use semver::{Comparator, Op, Version, VersionReq}; -use crate::util_semver::VersionExt as _; +pub trait VersionExt { + fn is_prerelease(&self) -> bool; + + fn to_exact_req(&self) -> VersionReq; +} + +impl VersionExt for Version { + fn is_prerelease(&self) -> bool { + !self.pre.is_empty() + } + + fn to_exact_req(&self) -> VersionReq { + VersionReq { + comparators: vec![Comparator { + op: Op::Exact, + major: self.major, + minor: Some(self.minor), + patch: Some(self.patch), + pre: self.pre.clone(), + }], + } + } +} #[derive(PartialEq, Eq, Hash, Clone, Debug)] pub enum OptVersionReq { diff --git a/src/cargo/util/toml/embedded.rs b/src/cargo/util/toml/embedded.rs index cad7abc38fa..fdd73ed9060 100644 --- a/src/cargo/util/toml/embedded.rs +++ b/src/cargo/util/toml/embedded.rs @@ -1,7 +1,8 @@ use anyhow::Context as _; +use cargo_util_schemas::manifest::PackageName; + use crate::util::restricted_names; -use crate::util_schemas::manifest::PackageName; use crate::CargoResult; use crate::Config; diff --git a/src/cargo/util/toml/mod.rs b/src/cargo/util/toml/mod.rs index 8affc69a44b..39b0e6e7faf 100644 --- a/src/cargo/util/toml/mod.rs +++ b/src/cargo/util/toml/mod.rs @@ -7,6 +7,8 @@ use std::str::{self, FromStr}; use anyhow::{anyhow, bail, Context as _}; use cargo_platform::Platform; use cargo_util::paths; +use cargo_util_schemas::manifest; +use cargo_util_schemas::manifest::RustVersion; use itertools::Itertools; use lazycell::LazyCell; use tracing::{debug, trace}; @@ -24,8 +26,6 @@ use crate::sources::{CRATES_IO_INDEX, CRATES_IO_REGISTRY}; use crate::util::errors::{CargoResult, ManifestError}; use crate::util::interning::InternedString; use crate::util::{self, config::ConfigRelativePath, Config, IntoUrl, OptVersionReq}; -use crate::util_schemas::manifest; -use crate::util_schemas::manifest::RustVersion; mod embedded; mod targets; diff --git a/src/cargo/util/toml/targets.rs b/src/cargo/util/toml/targets.rs index 7d0f1891e15..d004a76dc61 100644 --- a/src/cargo/util/toml/targets.rs +++ b/src/cargo/util/toml/targets.rs @@ -14,18 +14,18 @@ use std::collections::HashSet; use std::fs::{self, DirEntry}; use std::path::{Path, PathBuf}; +use anyhow::Context as _; +use cargo_util_schemas::manifest::{ + PathValue, StringOrBool, StringOrVec, TomlBenchTarget, TomlBinTarget, TomlExampleTarget, + TomlLibTarget, TomlManifest, TomlTarget, TomlTestTarget, +}; + use crate::core::compiler::rustdoc::RustdocScrapeExamples; use crate::core::compiler::CrateType; use crate::core::{Edition, Feature, Features, Target}; use crate::util::errors::CargoResult; use crate::util::restricted_names; use crate::util::toml::warn_on_deprecated; -use crate::util_schemas::manifest::{ - PathValue, StringOrBool, StringOrVec, TomlBenchTarget, TomlBinTarget, TomlExampleTarget, - TomlLibTarget, TomlManifest, TomlTarget, TomlTestTarget, -}; - -use anyhow::Context as _; const DEFAULT_TEST_DIR_NAME: &'static str = "tests"; const DEFAULT_BENCH_DIR_NAME: &'static str = "benches"; diff --git a/tests/testsuite/config.rs b/tests/testsuite/config.rs index bcd1260205a..7912c58be9c 100644 --- a/tests/testsuite/config.rs +++ b/tests/testsuite/config.rs @@ -2,12 +2,12 @@ use cargo::core::{PackageIdSpec, Shell}; use cargo::util::config::{self, Config, Definition, JobsConfig, SslVersionConfig, StringList}; -use cargo::util_schemas::manifest::TomlTrimPaths; -use cargo::util_schemas::manifest::TomlTrimPathsValue; -use cargo::util_schemas::manifest::{self as cargo_toml, TomlDebugInfo, VecStringOrBool as VSOB}; use cargo::CargoResult; use cargo_test_support::compare; use cargo_test_support::{panic_error, paths, project, symlink_supported, t}; +use cargo_util_schemas::manifest::TomlTrimPaths; +use cargo_util_schemas::manifest::TomlTrimPathsValue; +use cargo_util_schemas::manifest::{self as cargo_toml, TomlDebugInfo, VecStringOrBool as VSOB}; use serde::Deserialize; use std::borrow::Borrow; use std::collections::{BTreeMap, HashMap}; diff --git a/tests/testsuite/profile_config.rs b/tests/testsuite/profile_config.rs index f8a9ae744b3..a96d6b0849d 100644 --- a/tests/testsuite/profile_config.rs +++ b/tests/testsuite/profile_config.rs @@ -1,9 +1,9 @@ //! Tests for profiles defined in config files. -use cargo::util_schemas::manifest::TomlDebugInfo; use cargo_test_support::paths::CargoPathExt; use cargo_test_support::registry::Package; use cargo_test_support::{basic_lib_manifest, paths, project}; +use cargo_util_schemas::manifest::TomlDebugInfo; // TODO: this should be remove once -Zprofile-rustflags is stabilized #[cargo_test]