use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::Arc;
mod manifest;
pub mod typed;
#[cfg(any(test, feature = "test-util"))]
pub(crate) use manifest::EcosystemManifest;
pub use manifest::ParsedManifest;
#[cfg(feature = "lsp-responses")]
pub use typed::{HoverDecoration, HoverDecorator, code_actions, hover};
pub use typed::{TypedEcosystem, diagnostics};
use crate::{
Registry,
lsp_helpers::EcosystemFormatter,
position::Range,
registry::Metadata,
selection::{InvalidStabilityOccurrence, SelectionContext},
};
#[doc(hidden)]
pub mod private {
pub trait Sealed {}
}
pub type BoxFuture<'a, T> = Pin<Box<dyn std::future::Future<Output = T> + Send + 'a>>;
pub async fn parse_manifest_blocking(
ecosystem: &Arc<dyn Ecosystem>,
content: &str,
uri: &url::Url,
) -> crate::error::Result<Box<dyn ParsedManifest>> {
let ecosystem = Arc::clone(ecosystem);
let owned_content = content.to_owned();
let owned_uri = uri.clone();
let handle = tokio::runtime::Handle::current();
tokio::task::spawn_blocking(move || {
handle.block_on(ecosystem.parse_manifest(&owned_content, &owned_uri))
})
.await
.map_err(|e| crate::error::DepsError::parse_error(format!("manifest at {uri:?}"), &e))?
}
pub fn parse_manifest_now(
ecosystem: &Arc<dyn Ecosystem>,
content: &str,
uri: &url::Url,
) -> Option<Box<dyn ParsedManifest>> {
tokio::runtime::Handle::try_current().ok()?;
Arc::clone(ecosystem).parse_manifest_sync(content, uri)
}
macro_rules! ecosystem_ids {
( $( $(#[$vmeta:meta])* $variant:ident => $id:literal ),+ $(,)? ) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum EcosystemId {
$( $(#[$vmeta])* $variant, )+
}
impl EcosystemId {
pub const ALL: &'static [Self] = &[ $( Self::$variant ),+ ];
#[must_use]
pub const fn id(self) -> &'static str {
match self {
$( Self::$variant => $id, )+
}
}
}
impl std::str::FromStr for EcosystemId {
type Err = crate::error::DepsError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
$( $id => Ok(Self::$variant), )+
_ => Err(crate::error::DepsError::UnsupportedEcosystem(s.to_string())),
}
}
}
};
}
ecosystem_ids! {
Cargo => "cargo",
Npm => "npm",
Pypi => "pypi",
Go => "go",
Bundler => "bundler",
Dart => "dart",
Maven => "maven",
Composer => "composer",
Gradle => "gradle",
Swift => "swift",
NuGet => "nuget",
Deno => "deno",
GithubActions => "github-actions",
GitlabCi => "gitlab-ci",
PreCommit => "pre-commit",
}
impl EcosystemId {
#[must_use]
pub const fn osv_ecosystem(self) -> Option<crate::osv::OsvEcosystem> {
use crate::osv::OsvEcosystem;
match self {
Self::Cargo => Some(OsvEcosystem::CratesIo),
Self::Npm | Self::Deno => Some(OsvEcosystem::Npm),
Self::Pypi => Some(OsvEcosystem::PyPI),
Self::Go => Some(OsvEcosystem::Go),
Self::Bundler => Some(OsvEcosystem::RubyGems),
Self::Dart => Some(OsvEcosystem::Pub),
Self::Maven | Self::Gradle => Some(OsvEcosystem::Maven),
Self::Composer => Some(OsvEcosystem::Packagist),
Self::Swift => Some(OsvEcosystem::SwiftURL),
Self::NuGet => Some(OsvEcosystem::NuGet),
Self::GithubActions => Some(OsvEcosystem::GitHubActions),
Self::GitlabCi => None,
Self::PreCommit => None,
}
}
}
impl std::fmt::Display for EcosystemId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.id())
}
}
pub trait RegistryOccurrence {
fn range(&self) -> Range;
fn declaration_key(&self) -> &str;
}
#[derive(Clone, crate::redact_debug::RedactingDebug)]
pub struct BlockedRegistryOccurrence {
#[raw]
pub range: Range,
#[raw]
pub block: crate::net_policy::BlockedHost,
#[redact(url)]
pub raw_value: String,
#[redact(key)]
pub declaration_key: String,
}
impl RegistryOccurrence for BlockedRegistryOccurrence {
fn range(&self) -> Range {
self.range
}
fn declaration_key(&self) -> &str {
&self.declaration_key
}
}
#[derive(Clone, PartialEq, Eq, crate::redact_debug::RedactingDebug)]
pub struct BlockedSourceClass {
#[raw]
pub block: crate::net_policy::BlockedHost,
#[redact(url)]
pub raw_value: String,
#[redact(key)]
pub declaration_key: String,
}
impl BlockedSourceClass {
#[must_use]
pub fn into_occurrence(self, range: Range) -> BlockedRegistryOccurrence {
BlockedRegistryOccurrence {
range,
block: self.block,
raw_value: self.raw_value,
declaration_key: self.declaration_key,
}
}
}
#[derive(Clone, crate::redact_debug::RedactingDebug)]
pub struct RejectedRegistryOccurrence {
#[raw]
pub range: Range,
#[raw]
pub reason: crate::net_policy::RegistryRejectionReason,
#[redact(url)]
pub raw_value: String,
#[redact(key)]
pub declaration_key: String,
}
impl RegistryOccurrence for RejectedRegistryOccurrence {
fn range(&self) -> Range {
self.range
}
fn declaration_key(&self) -> &str {
&self.declaration_key
}
}
#[derive(Clone, PartialEq, Eq, crate::redact_debug::RedactingDebug)]
pub struct RejectedSourceClass {
#[raw]
pub reason: crate::net_policy::RegistryRejectionReason,
#[redact(url)]
pub raw_value: String,
#[redact(key)]
pub declaration_key: String,
}
impl RejectedSourceClass {
#[must_use]
pub fn into_occurrence(self, range: Range) -> RejectedRegistryOccurrence {
RejectedRegistryOccurrence {
range,
reason: self.reason,
raw_value: self.raw_value,
declaration_key: self.declaration_key,
}
}
}
pub trait ParseResult: Send + Sync {
fn dependencies(&self) -> Vec<&dyn Dependency>;
fn workspace_root(&self) -> Option<&std::path::Path>;
fn uri(&self) -> &url::Url;
fn blocked_registries(&self) -> Vec<BlockedRegistryOccurrence> {
Vec::new()
}
fn selection_context(&self) -> SelectionContext {
SelectionContext::none()
}
fn invalid_minimum_stability(&self) -> Option<InvalidStabilityOccurrence> {
None
}
fn rejected_registries(&self) -> Vec<RejectedRegistryOccurrence> {
Vec::new()
}
fn dependency_truncation(&self) -> Option<crate::DependencyTruncation> {
None
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DependencyKind {
Normal,
Development,
Build,
Peer,
Optional,
}
#[must_use]
pub const fn normal_kind<T: ?Sized>(_dependency: &T) -> Option<DependencyKind> {
Some(DependencyKind::Normal)
}
pub trait Dependency: Send + Sync {
fn name(&self) -> &crate::PackageName;
fn native_cooldown(&self) -> Option<&crate::native_cooldown::NativeCooldown> {
None
}
fn kind(&self) -> Option<crate::DependencyKind> {
None
}
fn name_range(&self) -> Range;
fn version_requirement(&self) -> Option<&crate::VersionReq>;
fn version_range(&self) -> Option<Range>;
fn source(&self) -> crate::parser::DependencySource;
fn features(&self) -> &[String] {
&[]
}
fn features_range(&self) -> Option<Range> {
None
}
fn markers(&self) -> Option<&str> {
None
}
fn markers_range(&self) -> Option<Range> {
None
}
fn version_literal(&self) -> Option<&str> {
None
}
fn name_range_is_synthetic(&self) -> bool {
false
}
fn lock_scope(&self) -> crate::LockScope {
crate::LockScope::Project
}
}
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct EcosystemConfig {
pub show_up_to_date_hints: bool,
pub up_to_date_text: String,
pub needs_update_text: String,
pub loading_text: String,
pub show_loading_hints: bool,
pub network: crate::NetworkMode,
}
impl Default for EcosystemConfig {
fn default() -> Self {
Self::new()
}
}
impl EcosystemConfig {
#[must_use]
pub fn new() -> Self {
Self {
show_up_to_date_hints: true,
up_to_date_text: "✅".to_string(),
needs_update_text: "❌ {}".to_string(),
loading_text: "⏳".to_string(),
show_loading_hints: true,
network: crate::NetworkMode::Online,
}
}
#[must_use]
pub const fn with_show_up_to_date_hints(mut self, show_up_to_date_hints: bool) -> Self {
self.show_up_to_date_hints = show_up_to_date_hints;
self
}
#[must_use]
pub fn with_up_to_date_text(mut self, up_to_date_text: impl Into<String>) -> Self {
self.up_to_date_text = up_to_date_text.into();
self
}
#[must_use]
pub fn with_needs_update_text(mut self, needs_update_text: impl Into<String>) -> Self {
self.needs_update_text = needs_update_text.into();
self
}
#[must_use]
pub fn with_loading_text(mut self, loading_text: impl Into<String>) -> Self {
self.loading_text = loading_text.into();
self
}
#[must_use]
pub const fn with_show_loading_hints(mut self, show_loading_hints: bool) -> Self {
self.show_loading_hints = show_loading_hints;
self
}
#[must_use]
pub const fn with_network(mut self, network: crate::NetworkMode) -> Self {
self.network = network;
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WatchedConfigEffect {
RewritesRequirements,
ChangesRouting,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ConfigReach {
Subtree,
OwnerDirectory,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum OwnerReach {
Subtree,
OwnerDirectory,
AllDocuments,
}
impl From<ConfigReach> for OwnerReach {
fn from(reach: ConfigReach) -> Self {
match reach {
ConfigReach::Subtree => Self::Subtree,
ConfigReach::OwnerDirectory => Self::OwnerDirectory,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UserHome {
raw: PathBuf,
canonical: Option<PathBuf>,
}
impl UserHome {
#[must_use]
pub const fn new(raw: PathBuf) -> Self {
Self {
raw,
canonical: None,
}
}
#[must_use]
pub fn resolve(raw: PathBuf) -> Self {
let canonical = std::fs::canonicalize(&raw).ok();
Self { raw, canonical }
}
#[must_use]
pub fn current() -> Option<&'static Self> {
static HOME: std::sync::OnceLock<Option<UserHome>> = std::sync::OnceLock::new();
HOME.get_or_init(|| absolute_home(std::env::home_dir()).map(Self::resolve))
.as_ref()
}
#[must_use]
pub fn path(&self) -> &Path {
&self.raw
}
#[must_use]
pub fn is(&self, dir: &Path) -> bool {
self.raw == dir || self.canonical.as_deref() == Some(dir)
}
}
fn absolute_home(home: Option<PathBuf>) -> Option<PathBuf> {
home.filter(|home| home.is_absolute())
}
#[cfg(test)]
mod home_tests {
use super::absolute_home;
use std::path::PathBuf;
#[test]
fn a_relative_home_is_no_home() {
assert_eq!(absolute_home(Some(PathBuf::from("relative/home"))), None);
assert_eq!(absolute_home(Some(PathBuf::new())), None);
assert_eq!(absolute_home(None), None);
let absolute = std::env::temp_dir();
assert_eq!(absolute_home(Some(absolute.clone())), Some(absolute));
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ConfigOwner {
dir: PathBuf,
reach: OwnerReach,
}
impl ConfigOwner {
#[must_use]
pub fn new(dir: PathBuf, reach: impl Into<OwnerReach>) -> Self {
Self {
dir,
reach: reach.into(),
}
}
#[must_use]
pub fn dir(&self) -> &Path {
&self.dir
}
#[must_use]
pub const fn reach(&self) -> OwnerReach {
self.reach
}
#[must_use]
pub fn covers(&self, manifest: &Path) -> bool {
let Some(manifest_dir) = manifest.parent() else {
return false;
};
match self.reach {
OwnerReach::Subtree => {
crate::fs_probe::config_ancestors(manifest_dir).any(|dir| dir == self.dir)
}
OwnerReach::OwnerDirectory => manifest_dir == self.dir,
OwnerReach::AllDocuments => true,
}
}
#[must_use]
pub fn for_user_home(self, home: Option<&UserHome>) -> Self {
if home.is_some_and(|home| home.is(&self.dir)) {
Self {
reach: OwnerReach::AllDocuments,
..self
}
} else {
self
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WatchedConfig {
path_suffix: &'static str,
effect: WatchedConfigEffect,
reach: ConfigReach,
}
const fn assert_plain_relative_suffix(suffix: &str) {
let mut rest = suffix.as_bytes();
assert!(!rest.is_empty(), "watched config suffix is empty");
assert!(
!matches!(rest, [b'/', ..]),
"watched config suffix is absolute"
);
let mut component_len = 0usize;
let mut component_dots = 0usize;
while let [byte, tail @ ..] = rest {
rest = tail;
if *byte == b'/' {
assert!(
!(component_len == 2 && component_dots == 2),
"watched config suffix contains `..`"
);
component_len = 0;
component_dots = 0;
continue;
}
assert!(
!matches!(*byte, b'*' | b'?' | b'[' | b'\\'),
"watched config suffix contains a glob or separator character"
);
component_len += 1;
if *byte == b'.' {
component_dots += 1;
}
}
assert!(
!(component_len == 2 && component_dots == 2),
"watched config suffix contains `..`"
);
}
impl WatchedConfig {
#[must_use]
pub const fn new(
path_suffix: &'static str,
effect: WatchedConfigEffect,
reach: ConfigReach,
) -> Self {
assert_plain_relative_suffix(path_suffix);
Self {
path_suffix,
effect,
reach,
}
}
#[must_use]
pub const fn reach(&self) -> ConfigReach {
self.reach
}
#[must_use]
pub fn owner_dir<'a>(&self, changed: &'a Path) -> Option<&'a Path> {
if !self.matches(changed) {
return None;
}
changed
.ancestors()
.nth(Path::new(self.path_suffix).components().count())
}
#[must_use]
pub const fn path_suffix(&self) -> &'static str {
self.path_suffix
}
#[must_use]
pub const fn effect(&self) -> WatchedConfigEffect {
self.effect
}
#[must_use]
pub fn matches(&self, path: &Path) -> bool {
path.ends_with(self.path_suffix)
}
#[must_use]
pub fn glob_pattern(&self) -> String {
format!("**/{}", self.path_suffix)
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LicenseSource {
#[default]
RegistryDeclaredSpdx,
FetchedDeclaredSpdx,
DetectedSpdx,
PomFreeText,
}
impl LicenseSource {
#[must_use]
pub const fn requires_dedicated_fetch(self) -> bool {
match self {
Self::RegistryDeclaredSpdx => false,
Self::FetchedDeclaredSpdx | Self::DetectedSpdx | Self::PomFreeText => true,
}
}
}
pub trait EcosystemBase: Send + Sync + private::Sealed {
fn ecosystem_id(&self) -> EcosystemId;
fn display_name(&self) -> &'static str;
fn manifest_filenames(&self) -> &[&'static str];
fn manifest_extensions(&self) -> &[&'static str] {
&[]
}
fn manifest_patterns(&self) -> &[&'static str] {
&[]
}
fn manifest_directory_patterns(&self) -> &[(&'static str, &'static str)] {
&[]
}
fn lockfile_filenames(&self) -> &[&'static str] {
&[]
}
fn watched_configs(&self) -> &[WatchedConfig] {
&[]
}
fn registry(&self) -> Arc<dyn Registry>;
fn lockfile_provider(&self) -> Option<Arc<dyn crate::lockfile::LockFileProvider>> {
None
}
fn refresh_events(&self) -> Option<crate::RefreshEvents> {
None
}
fn fallback_completion_prefix<'a>(
&self,
_content: &'a str,
_position: crate::position::Position,
) -> Option<&'a str> {
None
}
fn completion_insert_text(&self, metadata: &dyn Metadata) -> Option<String>;
fn fallback_completion_is_bare(
&self,
_content: &str,
_position: crate::position::Position,
) -> bool {
false
}
fn fallback_bare_insert_text(&self, metadata: &dyn Metadata) -> Option<String> {
Some(metadata.name().as_str().to_string())
}
fn package_search_is_incomplete(&self) -> bool {
false
}
fn fetch_license<'a>(
&'a self,
_name: &'a crate::PackageName,
_version: &'a crate::ConcreteVersion,
) -> BoxFuture<'a, Vec<String>> {
Box::pin(std::future::ready(Vec::new()))
}
fn license_source(&self) -> LicenseSource {
LicenseSource::RegistryDeclaredSpdx
}
#[cfg(feature = "lsp-responses")]
fn pin_all_to_sha_noun(&self) -> crate::lsp_helpers::PinNoun {
crate::lsp_helpers::PinNoun {
singular: "ref",
plural: "refs",
}
}
}
pub trait Ecosystem: EcosystemBase + typed::BlanketOnly {
fn formatter(&self) -> &dyn EcosystemFormatter;
fn parse_manifest<'a>(
self: Arc<Self>,
content: &'a str,
uri: &'a url::Url,
) -> BoxFuture<'a, crate::error::Result<Box<dyn ParsedManifest>>>;
fn parse_manifest_sync(
self: Arc<Self>,
content: &str,
uri: &url::Url,
) -> Option<Box<dyn ParsedManifest>>;
#[cfg(any(test, feature = "test-util"))]
#[cfg_attr(docsrs, doc(cfg(feature = "test-util")))]
fn probe_non_public_route(
&self,
name: crate::PackageName,
source: crate::parser::DependencySource,
) -> crate::osv::NonPublicRoute;
#[cfg(any(test, feature = "test-util"))]
#[cfg_attr(docsrs, doc(cfg(feature = "test-util")))]
fn probe_route_non_public_routes(
&self,
name: crate::PackageName,
) -> Vec<crate::osv::NonPublicRoute>;
}
impl dyn Ecosystem + '_ {
#[must_use]
pub fn id(&self) -> &'static str {
self.ecosystem_id().id()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "lsp-responses")]
use crate::completion::Completions;
use std::assert_matches;
#[cfg(feature = "lsp-responses")]
use tower_lsp_server::ls_types::Position;
fn owner(dir: &str, reach: ConfigReach) -> ConfigOwner {
ConfigOwner::new(PathBuf::from(dir), reach)
}
#[test]
fn test_config_owner_subtree_covers_owner_dir_and_descendants_only() {
let owner = owner("/work", ConfigReach::Subtree);
assert!(owner.covers(Path::new("/work/package.json")));
assert!(owner.covers(Path::new("/work/pkg/deep/package.json")));
assert!(!owner.covers(Path::new("/work2/package.json")));
assert!(!owner.covers(Path::new("/other/work/package.json")));
assert!(!owner.covers(Path::new("/package.json")));
}
#[test]
fn test_config_owner_subtree_respects_ancestor_depth_cap() {
let owner = owner("/r", ConfigReach::Subtree);
let within: PathBuf =
std::iter::repeat_n("d", crate::fs_probe::MAX_CONFIG_ANCESTOR_DEPTH - 1)
.fold(PathBuf::from("/r"), |p, c| p.join(c))
.join("package.json");
assert!(owner.covers(&within));
let beyond = within.parent().unwrap().join("d").join("package.json");
assert!(!owner.covers(&beyond));
}
#[test]
fn test_config_owner_owner_directory_covers_only_the_directory_itself() {
let owner = owner("/work", ConfigReach::OwnerDirectory);
assert!(owner.covers(Path::new("/work/Package.swift")));
assert!(!owner.covers(Path::new("/work/other/Package.swift")));
assert!(!owner.covers(Path::new("/Package.swift")));
}
#[test]
fn test_config_owner_rootless_manifest_is_not_covered() {
assert!(!owner("/", ConfigReach::Subtree).covers(Path::new("")));
}
#[test]
fn test_watched_config_owner_dir_strips_every_suffix_component() {
const NPMRC: WatchedConfig = WatchedConfig::new(
".npmrc",
WatchedConfigEffect::ChangesRouting,
ConfigReach::Subtree,
);
assert_eq!(
NPMRC.owner_dir(Path::new("/a/b/.npmrc")),
Some(Path::new("/a/b"))
);
assert_eq!(NPMRC.owner_dir(Path::new("/a/b/x.npmrc")), None);
assert_eq!(NPMRC.reach(), ConfigReach::Subtree);
}
#[test]
fn test_ecosystem_id_roundtrip() {
const ALL: &[EcosystemId] = &[
EcosystemId::Cargo,
EcosystemId::Npm,
EcosystemId::Pypi,
EcosystemId::Go,
EcosystemId::Bundler,
EcosystemId::Dart,
EcosystemId::Maven,
EcosystemId::Composer,
EcosystemId::Gradle,
EcosystemId::Swift,
EcosystemId::NuGet,
EcosystemId::Deno,
EcosystemId::GithubActions,
EcosystemId::GitlabCi,
EcosystemId::PreCommit,
];
for id in ALL {
let parsed: EcosystemId = id.id().parse().unwrap();
assert_eq!(parsed, *id);
assert_eq!(id.to_string(), id.id());
}
}
#[test]
fn test_osv_ecosystem_mapping_pinned() {
let expected: &[(EcosystemId, &str)] = &[
(EcosystemId::Cargo, "crates.io"),
(EcosystemId::Npm, "npm"),
(EcosystemId::Pypi, "PyPI"),
(EcosystemId::Go, "Go"),
(EcosystemId::Bundler, "RubyGems"),
(EcosystemId::Dart, "Pub"),
(EcosystemId::Maven, "Maven"),
(EcosystemId::Composer, "Packagist"),
(EcosystemId::Gradle, "Maven"),
(EcosystemId::Swift, "SwiftURL"),
(EcosystemId::NuGet, "NuGet"),
(EcosystemId::Deno, "npm"),
(EcosystemId::GithubActions, "GitHub Actions"),
];
for (id, expected_str) in expected {
assert_eq!(
id.osv_ecosystem().map(crate::osv::OsvEcosystem::as_str),
Some(*expected_str),
"unexpected OSV ecosystem string for {id:?}"
);
}
assert_eq!(EcosystemId::GitlabCi.osv_ecosystem(), None);
assert_eq!(EcosystemId::PreCommit.osv_ecosystem(), None);
}
#[test]
fn test_ecosystem_id_from_str_unknown() {
let err = "unknown".parse::<EcosystemId>().unwrap_err();
assert_matches!(err, crate::error::DepsError::UnsupportedEcosystem(s) if s == "unknown");
}
#[test]
fn test_ecosystem_config_default() {
let config = EcosystemConfig::default();
assert!(config.show_up_to_date_hints);
assert_eq!(config.up_to_date_text, "✅");
assert_eq!(config.needs_update_text, "❌ {}");
}
#[test]
fn test_ecosystem_config_custom() {
let config = EcosystemConfig {
show_up_to_date_hints: false,
up_to_date_text: "OK".to_string(),
needs_update_text: "Update to {}".to_string(),
loading_text: "Loading...".to_string(),
show_loading_hints: false,
network: crate::NetworkMode::Online,
};
assert!(!config.show_up_to_date_hints);
assert_eq!(config.up_to_date_text, "OK");
assert_eq!(config.needs_update_text, "Update to {}");
}
#[test]
fn test_dependency_default_features() {
struct MockDep;
impl Dependency for MockDep {
fn name(&self) -> &crate::PackageName {
static NAME: std::sync::LazyLock<crate::PackageName> =
std::sync::LazyLock::new(|| crate::PackageName::new("test"));
&NAME
}
fn name_range(&self) -> Range {
Range::default()
}
fn version_requirement(&self) -> Option<&crate::VersionReq> {
None
}
fn version_range(&self) -> Option<Range> {
None
}
fn source(&self) -> crate::parser::DependencySource {
crate::parser::DependencySource::Registry
}
}
let dep = MockDep;
assert_eq!(dep.features(), &[] as &[String]);
}
struct StubEcosystem {
calling_thread: std::thread::ThreadId,
should_panic: bool,
dep_count: usize,
}
impl private::Sealed for StubEcosystem {}
impl EcosystemBase for StubEcosystem {
fn ecosystem_id(&self) -> EcosystemId {
EcosystemId::Cargo
}
fn display_name(&self) -> &'static str {
"Stub"
}
fn manifest_filenames(&self) -> &[&'static str] {
&[]
}
fn registry(&self) -> Arc<dyn crate::Registry> {
unimplemented!()
}
fn completion_insert_text(&self, _metadata: &dyn crate::Metadata) -> Option<String> {
unimplemented!()
}
}
impl TypedEcosystem for StubEcosystem {
type Parsed = crate::test_util::StubParseResult;
type Formatter = crate::test_util::StubFormatter;
fn own_formatter(&self) -> &Self::Formatter {
&crate::test_util::StubFormatter::DEFAULT
}
fn parse<'a>(
&'a self,
_content: &'a str,
uri: &'a url::Url,
) -> BoxFuture<'a, crate::error::Result<Self::Parsed>> {
Box::pin(async move {
assert!(!self.should_panic, "boom");
assert_ne!(
std::thread::current().id(),
self.calling_thread,
"parse must run on the blocking pool, not the calling thread"
);
Ok(crate::test_util::StubParseResult::new(
uri.clone(),
self.dep_count,
))
})
}
}
#[cfg(feature = "lsp-responses")]
#[tokio::test]
async fn test_generate_completions_default_dispatch_stamps_origin_per_context() {
use crate::completion::CompletionOrigin;
use crate::typed_boundary::{ParsedView, TypedParseResult};
struct OriginMockDep {
name: Range,
version: Range,
features: Range,
}
crate::impl_unprobed_dependency!(OriginMockDep);
impl Dependency for OriginMockDep {
fn name(&self) -> &crate::PackageName {
static NAME: std::sync::LazyLock<crate::PackageName> =
std::sync::LazyLock::new(|| crate::PackageName::new("demo"));
&NAME
}
fn name_range(&self) -> Range {
self.name
}
fn version_requirement(&self) -> Option<&crate::VersionReq> {
static REQ: std::sync::LazyLock<crate::VersionReq> =
std::sync::LazyLock::new(|| crate::VersionReq::new("1.0"));
Some(&REQ)
}
fn version_range(&self) -> Option<Range> {
Some(self.version)
}
fn source(&self) -> crate::parser::DependencySource {
crate::parser::DependencySource::Registry
}
fn features_range(&self) -> Option<Range> {
Some(self.features)
}
}
struct OriginMockParseResult {
deps: [OriginMockDep; 1],
uri: url::Url,
}
impl ParseResult for OriginMockParseResult {
fn dependencies(&self) -> Vec<&dyn Dependency> {
vec![&self.deps[0]]
}
fn workspace_root(&self) -> Option<&std::path::Path> {
None
}
fn uri(&self) -> &url::Url {
&self.uri
}
}
impl TypedParseResult for OriginMockParseResult {
type Dep = OriginMockDep;
fn own_dependencies(&self) -> &[OriginMockDep] {
&self.deps
}
}
struct OriginMockEcosystem;
impl private::Sealed for OriginMockEcosystem {}
impl EcosystemBase for OriginMockEcosystem {
fn ecosystem_id(&self) -> EcosystemId {
EcosystemId::Cargo
}
fn display_name(&self) -> &'static str {
"origin-mock"
}
fn manifest_filenames(&self) -> &[&'static str] {
&[]
}
fn registry(&self) -> Arc<dyn crate::Registry> {
unimplemented!()
}
fn completion_insert_text(&self, _metadata: &dyn crate::Metadata) -> Option<String> {
unimplemented!()
}
}
impl TypedEcosystem for OriginMockEcosystem {
type Parsed = OriginMockParseResult;
type Formatter = crate::test_util::StubFormatter<OriginMockDep>;
fn own_formatter(&self) -> &Self::Formatter {
const FORMATTER: crate::test_util::StubFormatter<OriginMockDep> =
crate::test_util::StubFormatter::new().for_dependency();
&FORMATTER
}
fn parse<'a>(
&'a self,
_content: &'a str,
_uri: &'a url::Url,
) -> BoxFuture<'a, crate::error::Result<Self::Parsed>> {
Box::pin(async move { unimplemented!() })
}
fn complete_version<'a>(
&'a self,
_request: crate::completion::CompletionRequest<'a, Self::Parsed>,
_package_name: crate::PackageName,
_prefix: String,
) -> BoxFuture<'a, Completions> {
Box::pin(std::future::ready(Completions::new(vec![])))
}
}
let content = "demo\n1.0\nderive\n";
let dep = OriginMockDep {
name: Range::new(
crate::position::Position::new(0, 0),
crate::position::Position::new(0, 4),
),
version: Range::new(
crate::position::Position::new(1, 0),
crate::position::Position::new(1, 3),
),
features: Range::new(
crate::position::Position::new(2, 0),
crate::position::Position::new(2, 6),
),
};
let parse_result = OriginMockParseResult {
deps: [dep],
uri: crate::test_util::test_uri("/test/manifest.toml"),
};
let eco = OriginMockEcosystem;
let freshness = crate::FreshnessSettings::default();
let _: &dyn crate::lsp_helpers::EcosystemFormatter = eco.own_formatter();
for (position, expected) in [
(Position::new(0, 2), CompletionOrigin::PackageName),
(Position::new(1, 1), CompletionOrigin::Version),
(Position::new(2, 3), CompletionOrigin::Feature),
(Position::new(3, 0), CompletionOrigin::Unresolved),
] {
let result = eco
.completions(ParsedView::new(&parse_result), position, content, freshness)
.await;
assert_eq!(
result.origin, expected,
"position {position:?} expected origin {expected:?}, got {:?}",
result.origin
);
}
}
#[tokio::test]
async fn test_parse_manifest_blocking_runs_parse_off_calling_thread() {
let ecosystem: Arc<dyn Ecosystem> = Arc::new(StubEcosystem {
calling_thread: std::thread::current().id(),
should_panic: false,
dep_count: 0,
});
let uri = crate::test_util::test_uri("/test/manifest.toml");
let parsed = parse_manifest_blocking(&ecosystem, "content", &uri)
.await
.unwrap();
assert_eq!(parsed.uri(), &uri);
}
#[test]
fn test_refresh_events_defaults_to_none() {
let ecosystem = StubEcosystem {
calling_thread: std::thread::current().id(),
should_panic: false,
dep_count: 0,
};
assert!(ecosystem.refresh_events().is_none());
}
#[test]
fn test_parse_depends_on_defaults_to_reparsing_every_document() {
let ecosystem = StubEcosystem {
calling_thread: std::thread::current().id(),
should_panic: false,
dep_count: 0,
};
let parsed = crate::test_util::StubParseResult::new(
crate::test_util::test_uri("/test/manifest.toml"),
0,
);
assert!(ecosystem.depends_on(
crate::typed_boundary::ParsedView::new(&parsed),
&crate::ParseInputKey::minted_by(crate::EcosystemId::Cargo, "any")
));
}
#[tokio::test]
async fn test_parse_manifest_blocking_caps_dependencies_over_the_ceiling() {
let ecosystem: Arc<dyn Ecosystem> = Arc::new(StubEcosystem {
calling_thread: std::thread::current().id(),
should_panic: false,
dep_count: crate::dependency_cap::MAX_DEPENDENCIES_PER_DOCUMENT + 1,
});
let uri = crate::test_util::test_uri("/test/manifest.toml");
let parsed = parse_manifest_blocking(&ecosystem, "content", &uri)
.await
.unwrap();
assert_eq!(
parsed.dependencies().len(),
crate::dependency_cap::MAX_DEPENDENCIES_PER_DOCUMENT
);
assert_eq!(
parsed.dependency_truncation(),
Some(crate::DependencyTruncation {
kept: crate::dependency_cap::MAX_DEPENDENCIES_PER_DOCUMENT,
total: crate::dependency_cap::MAX_DEPENDENCIES_PER_DOCUMENT + 1,
})
);
}
#[tokio::test]
async fn test_parse_manifest_blocking_panic_becomes_parse_error() {
let ecosystem: Arc<dyn Ecosystem> = Arc::new(StubEcosystem {
calling_thread: std::thread::current().id(),
should_panic: true,
dep_count: 0,
});
let uri = crate::test_util::test_uri("/test/manifest.toml");
let Err(err) = parse_manifest_blocking(&ecosystem, "content", &uri).await else {
panic!("expected parse_manifest_blocking to return an error");
};
match err {
crate::error::DepsError::ParseError {
file_type, source, ..
} => {
assert!(file_type.contains("manifest at"));
assert!(
source.to_string().contains("boom"),
"panic message should be preserved in the error source, got: {source}"
);
}
other => panic!("Expected ParseError, got: {other:?}"),
}
}
#[tokio::test]
async fn test_parse_manifest_now_caps_dependencies_over_the_ceiling() {
let foreign_thread = std::thread::spawn(|| std::thread::current().id())
.join()
.unwrap();
let ecosystem: Arc<dyn Ecosystem> = Arc::new(StubEcosystem {
calling_thread: foreign_thread,
should_panic: false,
dep_count: crate::dependency_cap::MAX_DEPENDENCIES_PER_DOCUMENT + 1,
});
let uri = crate::test_util::test_uri("/test/manifest.toml");
let parsed = parse_manifest_now(&ecosystem, "content", &uri)
.expect("an immediately-ready parse must resolve on the first poll");
assert_eq!(
parsed.dependencies().len(),
crate::dependency_cap::MAX_DEPENDENCIES_PER_DOCUMENT
);
assert_eq!(
parsed.dependency_truncation(),
Some(crate::DependencyTruncation {
kept: crate::dependency_cap::MAX_DEPENDENCIES_PER_DOCUMENT,
total: crate::dependency_cap::MAX_DEPENDENCIES_PER_DOCUMENT + 1,
})
);
}
#[tokio::test]
async fn test_parse_manifest_now_returns_none_for_a_pending_future() {
struct PendingEcosystem;
impl private::Sealed for PendingEcosystem {}
impl EcosystemBase for PendingEcosystem {
fn ecosystem_id(&self) -> EcosystemId {
EcosystemId::Composer
}
fn display_name(&self) -> &'static str {
"pending-stub"
}
fn manifest_filenames(&self) -> &[&'static str] {
&[]
}
fn registry(&self) -> Arc<dyn crate::Registry> {
unimplemented!()
}
fn completion_insert_text(&self, _metadata: &dyn crate::Metadata) -> Option<String> {
unimplemented!()
}
}
impl TypedEcosystem for PendingEcosystem {
type Parsed = crate::test_util::StubParseResult;
type Formatter = crate::test_util::StubFormatter;
fn own_formatter(&self) -> &Self::Formatter {
&crate::test_util::StubFormatter::DEFAULT
}
fn parse<'a>(
&'a self,
_content: &'a str,
_uri: &'a url::Url,
) -> BoxFuture<'a, crate::error::Result<Self::Parsed>> {
Box::pin(std::future::pending())
}
}
let ecosystem: Arc<dyn Ecosystem> = Arc::new(PendingEcosystem);
let uri = crate::test_util::test_uri("/test/manifest.toml");
assert!(parse_manifest_now(&ecosystem, "content", &uri).is_none());
}
#[test]
fn test_parse_manifest_now_returns_none_outside_a_tokio_runtime() {
let ecosystem: Arc<dyn Ecosystem> = Arc::new(StubEcosystem {
calling_thread: std::thread::current().id(),
should_panic: false,
dep_count: 0,
});
let uri = crate::test_util::test_uri("/test/manifest.toml");
assert!(
tokio::runtime::Handle::try_current().is_err(),
"this test must run with no ambient tokio runtime for the assertion below to mean \
anything"
);
assert!(parse_manifest_now(&ecosystem, "content", &uri).is_none());
}
crate::debug_redaction_conformance!(
test_blocked_registry_occurrence_debug_redacts_credentials,
2,
BlockedRegistryOccurrence {
range: Range::default(),
block: crate::net_policy::BlockedHost::floor(crate::net_policy::HostClass::Loopback)
.unwrap(),
raw_value: crate::conformance::CREDENTIAL_PROBE_URL.to_string(),
declaration_key: crate::conformance::CREDENTIAL_PROBE_KEY.to_string(),
},
);
crate::debug_redaction_conformance!(
test_blocked_source_class_debug_redacts_credentials,
2,
BlockedSourceClass {
block: crate::net_policy::BlockedHost::floor(crate::net_policy::HostClass::Loopback)
.unwrap(),
raw_value: crate::conformance::CREDENTIAL_PROBE_URL.to_string(),
declaration_key: crate::conformance::CREDENTIAL_PROBE_KEY.to_string(),
},
);
}