Rename plugin cache file ⇒ plugin registry file (#12634)

# Description
So far this seems like the winner of my poll on what the name should be.
I'll take this off draft once the poll expires, if this is indeed the
winner.
This commit is contained in:
Devyn Cairns 2024-04-24 15:40:39 -07:00 committed by GitHub
parent 9996e4a1f8
commit 25cbcb511d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
22 changed files with 165 additions and 159 deletions

View File

@ -6,7 +6,7 @@ use nu_protocol::{
report_error, HistoryFileFormat, PipelineData, report_error, HistoryFileFormat, PipelineData,
}; };
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
use nu_protocol::{ParseError, PluginCacheFile, Spanned}; use nu_protocol::{ParseError, PluginRegistryFile, Spanned};
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
use nu_utils::utils::perf; use nu_utils::utils::perf;
use std::path::PathBuf; use std::path::PathBuf;
@ -51,7 +51,7 @@ pub fn read_plugin_file(
} }
let mut start_time = std::time::Instant::now(); let mut start_time = std::time::Instant::now();
// Reading signatures from plugin cache file // Reading signatures from plugin registry file
// The plugin.msgpackz file stores the parsed signature collected from each registered plugin // The plugin.msgpackz file stores the parsed signature collected from each registered plugin
add_plugin_file(engine_state, plugin_file.clone(), storage_path); add_plugin_file(engine_state, plugin_file.clone(), storage_path);
perf( perf(
@ -89,7 +89,7 @@ pub fn read_plugin_file(
engine_state, engine_state,
&ShellError::GenericError { &ShellError::GenericError {
error: format!( error: format!(
"Error while opening plugin cache file: {}", "Error while opening plugin registry file: {}",
plugin_path.display() plugin_path.display()
), ),
msg: "plugin path defined here".into(), msg: "plugin path defined here".into(),
@ -113,15 +113,15 @@ pub fn read_plugin_file(
} }
// Read the contents of the plugin file // Read the contents of the plugin file
let contents = match PluginCacheFile::read_from(&mut file, span) { let contents = match PluginRegistryFile::read_from(&mut file, span) {
Ok(contents) => contents, Ok(contents) => contents,
Err(err) => { Err(err) => {
log::warn!("Failed to read plugin cache file: {err:?}"); log::warn!("Failed to read plugin registry file: {err:?}");
report_error_new( report_error_new(
engine_state, engine_state,
&ShellError::GenericError { &ShellError::GenericError {
error: format!( error: format!(
"Error while reading plugin cache file: {}", "Error while reading plugin registry file: {}",
plugin_path.display() plugin_path.display()
), ),
msg: "plugin path defined here".into(), msg: "plugin path defined here".into(),
@ -265,8 +265,8 @@ pub(crate) fn get_history_path(storage_path: &str, mode: HistoryFileFormat) -> O
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
pub fn migrate_old_plugin_file(engine_state: &EngineState, storage_path: &str) -> bool { pub fn migrate_old_plugin_file(engine_state: &EngineState, storage_path: &str) -> bool {
use nu_protocol::{ use nu_protocol::{
report_error_new, PluginCacheItem, PluginCacheItemData, PluginExample, PluginIdentity, report_error_new, PluginExample, PluginIdentity, PluginRegistryItem,
PluginSignature, ShellError, PluginRegistryItemData, PluginSignature, ShellError,
}; };
use std::collections::BTreeMap; use std::collections::BTreeMap;
@ -318,7 +318,7 @@ pub fn migrate_old_plugin_file(engine_state: &EngineState, storage_path: &str) -
} }
// Now that the plugin commands are loaded, we just have to generate the file // Now that the plugin commands are loaded, we just have to generate the file
let mut contents = PluginCacheFile::new(); let mut contents = PluginRegistryFile::new();
let mut groups = BTreeMap::<PluginIdentity, Vec<PluginSignature>>::new(); let mut groups = BTreeMap::<PluginIdentity, Vec<PluginSignature>>::new();
@ -339,11 +339,11 @@ pub fn migrate_old_plugin_file(engine_state: &EngineState, storage_path: &str) -
} }
for (identity, commands) in groups { for (identity, commands) in groups {
contents.upsert_plugin(PluginCacheItem { contents.upsert_plugin(PluginRegistryItem {
name: identity.name().to_owned(), name: identity.name().to_owned(),
filename: identity.filename().to_owned(), filename: identity.filename().to_owned(),
shell: identity.shell().map(|p| p.to_owned()), shell: identity.shell().map(|p| p.to_owned()),
data: PluginCacheItemData::Valid { commands }, data: PluginRegistryItemData::Valid { commands },
}); });
} }

View File

@ -2,7 +2,7 @@ use std::sync::Arc;
use nu_engine::{command_prelude::*, current_dir}; use nu_engine::{command_prelude::*, current_dir};
use nu_plugin::{GetPlugin, PersistentPlugin}; use nu_plugin::{GetPlugin, PersistentPlugin};
use nu_protocol::{PluginCacheItem, PluginGcConfig, PluginIdentity, RegisteredPlugin}; use nu_protocol::{PluginGcConfig, PluginIdentity, PluginRegistryItem, RegisteredPlugin};
use crate::util::{get_plugin_dirs, modify_plugin_file}; use crate::util::{get_plugin_dirs, modify_plugin_file};
@ -21,7 +21,7 @@ impl Command for PluginAdd {
.named( .named(
"plugin-config", "plugin-config",
SyntaxShape::Filepath, SyntaxShape::Filepath,
"Use a plugin cache file other than the one set in `$nu.plugin-path`", "Use a plugin registry file other than the one set in `$nu.plugin-path`",
None, None,
) )
.named( .named(
@ -39,7 +39,7 @@ impl Command for PluginAdd {
} }
fn usage(&self) -> &str { fn usage(&self) -> &str {
"Add a plugin to the plugin cache file." "Add a plugin to the plugin registry file."
} }
fn extra_usage(&self) -> &str { fn extra_usage(&self) -> &str {
@ -47,8 +47,8 @@ impl Command for PluginAdd {
This does not load the plugin commands into the scope - see `register` for that. This does not load the plugin commands into the scope - see `register` for that.
Instead, it runs the plugin to get its command signatures, and then edits the Instead, it runs the plugin to get its command signatures, and then edits the
plugin cache file (by default, `$nu.plugin-path`). The changes will be plugin registry file (by default, `$nu.plugin-path`). The changes will be
apparent the next time `nu` is next launched with that plugin cache file. apparent the next time `nu` is next launched with that plugin registry file.
"# "#
.trim() .trim()
} }
@ -66,7 +66,7 @@ apparent the next time `nu` is next launched with that plugin cache file.
}, },
Example { Example {
example: "plugin add --plugin-config polars.msgpackz nu_plugin_polars", example: "plugin add --plugin-config polars.msgpackz nu_plugin_polars",
description: "Run the `nu_plugin_polars` plugin from the current directory or $env.NU_PLUGIN_DIRS, and install its signatures to the \"polars.msgpackz\" plugin cache file.", description: "Run the `nu_plugin_polars` plugin from the current directory or $env.NU_PLUGIN_DIRS, and install its signatures to the \"polars.msgpackz\" plugin registry file.",
result: None, result: None,
}, },
] ]
@ -122,7 +122,7 @@ apparent the next time `nu` is next launched with that plugin cache file.
modify_plugin_file(engine_state, stack, call.head, custom_path, |contents| { modify_plugin_file(engine_state, stack, call.head, custom_path, |contents| {
// Update the file with the received signatures // Update the file with the received signatures
let item = PluginCacheItem::new(plugin.identity(), commands); let item = PluginRegistryItem::new(plugin.identity(), commands);
contents.upsert_plugin(item); contents.upsert_plugin(item);
Ok(()) Ok(())
})?; })?;

View File

@ -60,8 +60,9 @@ impl Command for PluginCommand {
Example { Example {
example: "plugin use inc", example: "plugin use inc",
description: " description: "
Load (or reload) the `inc` plugin from the plugin cache file and put its commands in scope. Load (or reload) the `inc` plugin from the plugin registry file and put its
The plugin must already be in the cache file at parse time. commands in scope. The plugin must already be in the registry file at parse
time.
" "
.trim(), .trim(),
result: None, result: None,

View File

@ -17,7 +17,7 @@ impl Command for PluginRm {
.named( .named(
"plugin-config", "plugin-config",
SyntaxShape::Filepath, SyntaxShape::Filepath,
"Use a plugin cache file other than the one set in `$nu.plugin-path`", "Use a plugin registry file other than the one set in `$nu.plugin-path`",
None, None,
) )
.switch( .switch(
@ -34,15 +34,15 @@ impl Command for PluginRm {
} }
fn usage(&self) -> &str { fn usage(&self) -> &str {
"Remove a plugin from the plugin cache file." "Remove a plugin from the plugin registry file."
} }
fn extra_usage(&self) -> &str { fn extra_usage(&self) -> &str {
r#" r#"
This does not remove the plugin commands from the current scope or from `plugin This does not remove the plugin commands from the current scope or from `plugin
list` in the current shell. It instead removes the plugin from the plugin list` in the current shell. It instead removes the plugin from the plugin
cache file (by default, `$nu.plugin-path`). The changes will be apparent the registry file (by default, `$nu.plugin-path`). The changes will be apparent the
next time `nu` is launched with that plugin cache file. next time `nu` is launched with that plugin registry file.
This can be useful for removing an invalid plugin signature, if it can't be This can be useful for removing an invalid plugin signature, if it can't be
fixed with `plugin add`. fixed with `plugin add`.
@ -68,7 +68,7 @@ fixed with `plugin add`.
}, },
Example { Example {
example: "plugin rm --plugin-config polars.msgpackz polars", example: "plugin rm --plugin-config polars.msgpackz polars",
description: "Remove the installed signatures for the `polars` plugin from the \"polars.msgpackz\" plugin cache file.", description: "Remove the installed signatures for the `polars` plugin from the \"polars.msgpackz\" plugin registry file.",
result: None, result: None,
}, },
] ]
@ -100,7 +100,7 @@ fixed with `plugin add`.
} else { } else {
Err(ShellError::GenericError { Err(ShellError::GenericError {
error: format!("Failed to remove the `{}` plugin", name.item), error: format!("Failed to remove the `{}` plugin", name.item),
msg: "couldn't find a plugin with this name in the cache file".into(), msg: "couldn't find a plugin with this name in the registry file".into(),
span: Some(name.span), span: Some(name.span),
help: None, help: None,
inner: vec![], inner: vec![],

View File

@ -9,7 +9,7 @@ impl Command for PluginUse {
} }
fn usage(&self) -> &str { fn usage(&self) -> &str {
"Load a plugin from the plugin cache file into scope." "Load a plugin from the plugin registry file into scope."
} }
fn signature(&self) -> nu_protocol::Signature { fn signature(&self) -> nu_protocol::Signature {
@ -18,7 +18,7 @@ impl Command for PluginUse {
.named( .named(
"plugin-config", "plugin-config",
SyntaxShape::Filepath, SyntaxShape::Filepath,
"Use a plugin cache file other than the one set in `$nu.plugin-path`", "Use a plugin registry file other than the one set in `$nu.plugin-path`",
None, None,
) )
.required( .required(
@ -34,13 +34,13 @@ impl Command for PluginUse {
This command is a parser keyword. For details, check: This command is a parser keyword. For details, check:
https://www.nushell.sh/book/thinking_in_nu.html https://www.nushell.sh/book/thinking_in_nu.html
The plugin definition must be available in the plugin cache file at parse time. The plugin definition must be available in the plugin registry file at parse
Run `plugin add` first in the REPL to do this, or from a script consider time. Run `plugin add` first in the REPL to do this, or from a script consider
preparing a plugin cache file and passing `--plugin-config`, or using the preparing a plugin registry file and passing `--plugin-config`, or using the
`--plugin` option to `nu` instead. `--plugin` option to `nu` instead.
If the plugin was already loaded, this will reload the latest definition from If the plugin was already loaded, this will reload the latest definition from
the cache file into scope. the registry file into scope.
Note that even if the plugin filename is specified, it will only be loaded if Note that even if the plugin filename is specified, it will only be loaded if
it was already previously registered with `plugin add`. it was already previously registered with `plugin add`.
@ -80,7 +80,7 @@ it was already previously registered with `plugin add`.
}, },
Example { Example {
description: description:
"Load the commands for the `query` plugin from a custom plugin cache file", "Load the commands for the `query` plugin from a custom plugin registry file",
example: r#"plugin use --plugin-config local-plugins.msgpackz query"#, example: r#"plugin use --plugin-config local-plugins.msgpackz query"#,
result: None, result: None,
}, },

View File

@ -4,25 +4,25 @@ use std::{
}; };
use nu_engine::{command_prelude::*, current_dir}; use nu_engine::{command_prelude::*, current_dir};
use nu_protocol::{engine::StateWorkingSet, PluginCacheFile}; use nu_protocol::{engine::StateWorkingSet, PluginRegistryFile};
pub(crate) fn modify_plugin_file( pub(crate) fn modify_plugin_file(
engine_state: &EngineState, engine_state: &EngineState,
stack: &mut Stack, stack: &mut Stack,
span: Span, span: Span,
custom_path: Option<Spanned<String>>, custom_path: Option<Spanned<String>>,
operate: impl FnOnce(&mut PluginCacheFile) -> Result<(), ShellError>, operate: impl FnOnce(&mut PluginRegistryFile) -> Result<(), ShellError>,
) -> Result<(), ShellError> { ) -> Result<(), ShellError> {
let cwd = current_dir(engine_state, stack)?; let cwd = current_dir(engine_state, stack)?;
let plugin_cache_file_path = if let Some(ref custom_path) = custom_path { let plugin_registry_file_path = if let Some(ref custom_path) = custom_path {
nu_path::expand_path_with(&custom_path.item, cwd, true) nu_path::expand_path_with(&custom_path.item, cwd, true)
} else { } else {
engine_state engine_state
.plugin_path .plugin_path
.clone() .clone()
.ok_or_else(|| ShellError::GenericError { .ok_or_else(|| ShellError::GenericError {
error: "Plugin cache file not set".into(), error: "Plugin registry file not set".into(),
msg: "pass --plugin-config explicitly here".into(), msg: "pass --plugin-config explicitly here".into(),
span: Some(span), span: Some(span),
help: Some("you may be running `nu` with --no-config-file".into()), help: Some("you may be running `nu` with --no-config-file".into()),
@ -31,13 +31,13 @@ pub(crate) fn modify_plugin_file(
}; };
// Try to read the plugin file if it exists // Try to read the plugin file if it exists
let mut contents = if fs::metadata(&plugin_cache_file_path).is_ok_and(|m| m.len() > 0) { let mut contents = if fs::metadata(&plugin_registry_file_path).is_ok_and(|m| m.len() > 0) {
PluginCacheFile::read_from( PluginRegistryFile::read_from(
File::open(&plugin_cache_file_path).err_span(span)?, File::open(&plugin_registry_file_path).err_span(span)?,
Some(span), Some(span),
)? )?
} else { } else {
PluginCacheFile::default() PluginRegistryFile::default()
}; };
// Do the operation // Do the operation
@ -45,7 +45,7 @@ pub(crate) fn modify_plugin_file(
// Save the modified file on success // Save the modified file on success
contents.write_to( contents.write_to(
File::create(&plugin_cache_file_path).err_span(span)?, File::create(&plugin_registry_file_path).err_span(span)?,
Some(span), Some(span),
)?; )?;

View File

@ -3557,7 +3557,7 @@ pub fn parse_where(working_set: &mut StateWorkingSet, lite_command: &LiteCommand
pub fn parse_register(working_set: &mut StateWorkingSet, lite_command: &LiteCommand) -> Pipeline { pub fn parse_register(working_set: &mut StateWorkingSet, lite_command: &LiteCommand) -> Pipeline {
use nu_plugin::{get_signature, PluginDeclaration}; use nu_plugin::{get_signature, PluginDeclaration};
use nu_protocol::{ use nu_protocol::{
engine::Stack, ErrSpan, ParseWarning, PluginCacheItem, PluginIdentity, PluginSignature, engine::Stack, ErrSpan, ParseWarning, PluginIdentity, PluginRegistryItem, PluginSignature,
RegisteredPlugin, RegisteredPlugin,
}; };
@ -3742,8 +3742,10 @@ pub fn parse_register(working_set: &mut StateWorkingSet, lite_command: &LiteComm
if let Ok(ref signatures) = signatures { if let Ok(ref signatures) = signatures {
// Add the loaded plugin to the delta // Add the loaded plugin to the delta
working_set working_set.update_plugin_registry(PluginRegistryItem::new(
.update_plugin_cache(PluginCacheItem::new(&identity, signatures.clone())); &identity,
signatures.clone(),
));
} }
signatures signatures
@ -3776,7 +3778,7 @@ pub fn parse_register(working_set: &mut StateWorkingSet, lite_command: &LiteComm
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
pub fn parse_plugin_use(working_set: &mut StateWorkingSet, call: Box<Call>) -> Pipeline { pub fn parse_plugin_use(working_set: &mut StateWorkingSet, call: Box<Call>) -> Pipeline {
use nu_protocol::{FromValue, PluginCacheFile}; use nu_protocol::{FromValue, PluginRegistryFile};
let cwd = working_set.get_cwd(); let cwd = working_set.get_cwd();
@ -3827,8 +3829,8 @@ pub fn parse_plugin_use(working_set: &mut StateWorkingSet, call: Box<Call>) -> P
.plugin_path .plugin_path
.as_ref() .as_ref()
.ok_or_else(|| ParseError::LabeledErrorWithHelp { .ok_or_else(|| ParseError::LabeledErrorWithHelp {
error: "Plugin cache file not set".into(), error: "Plugin registry file not set".into(),
label: "can't load plugin without cache file".into(), label: "can't load plugin without registry file".into(),
span: call.head, span: call.head,
help: help:
"pass --plugin-config to `plugin use` when $nu.plugin-path is not set" "pass --plugin-config to `plugin use` when $nu.plugin-path is not set"
@ -3840,14 +3842,14 @@ pub fn parse_plugin_use(working_set: &mut StateWorkingSet, call: Box<Call>) -> P
let file = plugin_config_path.open(working_set).map_err(|err| { let file = plugin_config_path.open(working_set).map_err(|err| {
ParseError::LabeledError( ParseError::LabeledError(
"Plugin cache file can't be opened".into(), "Plugin registry file can't be opened".into(),
err.to_string(), err.to_string(),
plugin_config.as_ref().map(|p| p.span).unwrap_or(call.head), plugin_config.as_ref().map(|p| p.span).unwrap_or(call.head),
) )
})?; })?;
// The file is now open, so we just have to parse the contents and find the plugin // The file is now open, so we just have to parse the contents and find the plugin
let contents = PluginCacheFile::read_from(file, Some(call.head)) let contents = PluginRegistryFile::read_from(file, Some(call.head))
.map_err(|err| err.wrap(working_set, call.head))?; .map_err(|err| err.wrap(working_set, call.head))?;
let plugin_item = contents let plugin_item = contents
@ -3861,7 +3863,7 @@ pub fn parse_plugin_use(working_set: &mut StateWorkingSet, call: Box<Call>) -> P
})?; })?;
// Now add the signatures to the working set // Now add the signatures to the working set
nu_plugin::load_plugin_cache_item(working_set, plugin_item, Some(call.head)) nu_plugin::load_plugin_registry_item(working_set, plugin_item, Some(call.head))
.map_err(|err| err.wrap(working_set, call.head))?; .map_err(|err| err.wrap(working_set, call.head))?;
Ok(()) Ok(())

View File

@ -78,8 +78,8 @@ pub use serializers::{json::JsonSerializer, msgpack::MsgPackSerializer};
// Used by other nu crates. // Used by other nu crates.
#[doc(hidden)] #[doc(hidden)]
pub use plugin::{ pub use plugin::{
add_plugin_to_working_set, create_plugin_signature, get_signature, load_plugin_cache_item, add_plugin_to_working_set, create_plugin_signature, get_signature, load_plugin_file,
load_plugin_file, serve_plugin_io, EngineInterfaceManager, GetPlugin, Interface, load_plugin_registry_item, serve_plugin_io, EngineInterfaceManager, GetPlugin, Interface,
InterfaceManager, PersistentPlugin, PluginDeclaration, PluginExecutionCommandContext, InterfaceManager, PersistentPlugin, PluginDeclaration, PluginExecutionCommandContext,
PluginExecutionContext, PluginInterface, PluginInterfaceManager, PluginSource, PluginExecutionContext, PluginInterface, PluginInterfaceManager, PluginSource,
ServePluginError, ServePluginError,

View File

@ -24,8 +24,8 @@ use std::{
use nu_engine::documentation::get_flags_section; use nu_engine::documentation::get_flags_section;
use nu_protocol::{ use nu_protocol::{
ast::Operator, engine::StateWorkingSet, report_error_new, CustomValue, IntoSpanned, ast::Operator, engine::StateWorkingSet, report_error_new, CustomValue, IntoSpanned,
LabeledError, PipelineData, PluginCacheFile, PluginCacheItem, PluginCacheItemData, LabeledError, PipelineData, PluginIdentity, PluginRegistryFile, PluginRegistryItem,
PluginIdentity, PluginSignature, RegisteredPlugin, ShellError, Span, Spanned, Value, PluginRegistryItemData, PluginSignature, RegisteredPlugin, ShellError, Span, Spanned, Value,
}; };
use thiserror::Error; use thiserror::Error;
@ -925,12 +925,12 @@ pub fn get_plugin_encoding(
#[doc(hidden)] #[doc(hidden)]
pub fn load_plugin_file( pub fn load_plugin_file(
working_set: &mut StateWorkingSet, working_set: &mut StateWorkingSet,
plugin_cache_file: &PluginCacheFile, plugin_registry_file: &PluginRegistryFile,
span: Option<Span>, span: Option<Span>,
) { ) {
for plugin in &plugin_cache_file.plugins { for plugin in &plugin_registry_file.plugins {
// Any errors encountered should just be logged. // Any errors encountered should just be logged.
if let Err(err) = load_plugin_cache_item(working_set, plugin, span) { if let Err(err) = load_plugin_registry_item(working_set, plugin, span) {
report_error_new(working_set.permanent_state, &err) report_error_new(working_set.permanent_state, &err)
} }
} }
@ -938,15 +938,15 @@ pub fn load_plugin_file(
/// Load a definition from the plugin file into the engine state /// Load a definition from the plugin file into the engine state
#[doc(hidden)] #[doc(hidden)]
pub fn load_plugin_cache_item( pub fn load_plugin_registry_item(
working_set: &mut StateWorkingSet, working_set: &mut StateWorkingSet,
plugin: &PluginCacheItem, plugin: &PluginRegistryItem,
span: Option<Span>, span: Option<Span>,
) -> Result<Arc<PersistentPlugin>, ShellError> { ) -> Result<Arc<PersistentPlugin>, ShellError> {
let identity = let identity =
PluginIdentity::new(plugin.filename.clone(), plugin.shell.clone()).map_err(|_| { PluginIdentity::new(plugin.filename.clone(), plugin.shell.clone()).map_err(|_| {
ShellError::GenericError { ShellError::GenericError {
error: "Invalid plugin filename in plugin cache file".into(), error: "Invalid plugin filename in plugin registry file".into(),
msg: "loaded from here".into(), msg: "loaded from here".into(),
span, span,
help: Some(format!( help: Some(format!(
@ -959,7 +959,7 @@ pub fn load_plugin_cache_item(
})?; })?;
match &plugin.data { match &plugin.data {
PluginCacheItemData::Valid { commands } => { PluginRegistryItemData::Valid { commands } => {
let plugin = add_plugin_to_working_set(working_set, &identity)?; let plugin = add_plugin_to_working_set(working_set, &identity)?;
// Ensure that the plugin is reset. We're going to load new signatures, so we want to // Ensure that the plugin is reset. We're going to load new signatures, so we want to
@ -974,7 +974,7 @@ pub fn load_plugin_cache_item(
} }
Ok(plugin) Ok(plugin)
} }
PluginCacheItemData::Invalid => Err(ShellError::PluginCacheDataInvalid { PluginRegistryItemData::Invalid => Err(ShellError::PluginRegistryDataInvalid {
plugin_name: identity.name().to_owned(), plugin_name: identity.name().to_owned(),
span, span,
add_command: identity.add_command(), add_command: identity.add_command(),

View File

@ -24,7 +24,7 @@ use std::{
type PoisonDebuggerError<'a> = PoisonError<MutexGuard<'a, Box<dyn Debugger>>>; type PoisonDebuggerError<'a> = PoisonError<MutexGuard<'a, Box<dyn Debugger>>>;
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
use crate::{PluginCacheFile, PluginCacheItem, RegisteredPlugin}; use crate::{PluginRegistryFile, PluginRegistryItem, RegisteredPlugin};
pub static PWD_ENV: &str = "PWD"; pub static PWD_ENV: &str = "PWD";
@ -267,10 +267,10 @@ impl EngineState {
} }
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
if !delta.plugin_cache_items.is_empty() { if !delta.plugin_registry_items.is_empty() {
// Update the plugin file with the new signatures. // Update the plugin file with the new signatures.
if self.plugin_path.is_some() { if self.plugin_path.is_some() {
self.update_plugin_file(std::mem::take(&mut delta.plugin_cache_items))?; self.update_plugin_file(std::mem::take(&mut delta.plugin_registry_items))?;
} }
} }
@ -482,7 +482,7 @@ impl EngineState {
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
pub fn update_plugin_file( pub fn update_plugin_file(
&self, &self,
updated_items: Vec<PluginCacheItem>, updated_items: Vec<PluginRegistryItem>,
) -> Result<(), ShellError> { ) -> Result<(), ShellError> {
// Updating the signatures plugin file with the added signatures // Updating the signatures plugin file with the added signatures
use std::fs::File; use std::fs::File;
@ -500,10 +500,10 @@ impl EngineState {
// Read the current contents of the plugin file if it exists // Read the current contents of the plugin file if it exists
let mut contents = match File::open(plugin_path.as_path()) { let mut contents = match File::open(plugin_path.as_path()) {
Ok(mut plugin_file) => PluginCacheFile::read_from(&mut plugin_file, None), Ok(mut plugin_file) => PluginRegistryFile::read_from(&mut plugin_file, None),
Err(err) => { Err(err) => {
if err.kind() == std::io::ErrorKind::NotFound { if err.kind() == std::io::ErrorKind::NotFound {
Ok(PluginCacheFile::default()) Ok(PluginRegistryFile::default())
} else { } else {
Err(ShellError::GenericError { Err(ShellError::GenericError {
error: "Failed to open plugin file".into(), error: "Failed to open plugin file".into(),

View File

@ -9,7 +9,7 @@ use crate::{
use std::sync::Arc; use std::sync::Arc;
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
use crate::{PluginCacheItem, RegisteredPlugin}; use crate::{PluginRegistryItem, RegisteredPlugin};
/// A delta (or change set) between the current global state and a possible future global state. Deltas /// A delta (or change set) between the current global state and a possible future global state. Deltas
/// can be applied to the global state to update it to contain both previous state and the state held /// can be applied to the global state to update it to contain both previous state and the state held
@ -26,7 +26,7 @@ pub struct StateDelta {
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
pub(super) plugins: Vec<Arc<dyn RegisteredPlugin>>, pub(super) plugins: Vec<Arc<dyn RegisteredPlugin>>,
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
pub(super) plugin_cache_items: Vec<PluginCacheItem>, pub(super) plugin_registry_items: Vec<PluginRegistryItem>,
} }
impl StateDelta { impl StateDelta {
@ -50,7 +50,7 @@ impl StateDelta {
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
plugins: vec![], plugins: vec![],
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
plugin_cache_items: vec![], plugin_registry_items: vec![],
} }
} }

View File

@ -15,7 +15,7 @@ use std::{
}; };
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
use crate::{PluginCacheItem, PluginIdentity, RegisteredPlugin}; use crate::{PluginIdentity, PluginRegistryItem, RegisteredPlugin};
/// A temporary extension to the global state. This handles bridging between the global state and the /// A temporary extension to the global state. This handles bridging between the global state and the
/// additional declarations and scope changes that are not yet part of the global scope. /// additional declarations and scope changes that are not yet part of the global scope.
@ -182,8 +182,8 @@ impl<'a> StateWorkingSet<'a> {
} }
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
pub fn update_plugin_cache(&mut self, item: PluginCacheItem) { pub fn update_plugin_registry(&mut self, item: PluginRegistryItem) {
self.delta.plugin_cache_items.push(item); self.delta.plugin_registry_items.push(item);
} }
pub fn merge_predecl(&mut self, name: &[u8]) -> Option<DeclId> { pub fn merge_predecl(&mut self, name: &[u8]) -> Option<DeclId> {

View File

@ -442,13 +442,13 @@ pub enum ParseError {
#[error("Plugin not found")] #[error("Plugin not found")]
#[diagnostic( #[diagnostic(
code(nu::parser::plugin_not_found), code(nu::parser::plugin_not_found),
help("plugins need to be added to the plugin cache file before your script is run (see `plugin add`)"), help("plugins need to be added to the plugin registry file before your script is run (see `plugin add`)"),
)] )]
PluginNotFound { PluginNotFound {
name: String, name: String,
#[label("Plugin not found: {name}")] #[label("Plugin not found: {name}")]
name_span: Span, name_span: Span,
#[label("in this cache file")] #[label("in this registry file")]
plugin_config_span: Option<Span>, plugin_config_span: Option<Span>,
}, },

View File

@ -750,18 +750,18 @@ pub enum ShellError {
span: Span, span: Span,
}, },
/// The cached plugin data for a plugin is invalid. /// The registered plugin data for a plugin is invalid.
/// ///
/// ## Resolution /// ## Resolution
/// ///
/// `plugin add` the plugin again to update the data, or remove it with `plugin rm`. /// `plugin add` the plugin again to update the data, or remove it with `plugin rm`.
#[error("The cached plugin data for `{plugin_name}` is invalid")] #[error("The registered plugin data for `{plugin_name}` is invalid")]
#[diagnostic(code(nu::shell::plugin_cache_data_invalid))] #[diagnostic(code(nu::shell::plugin_registry_data_invalid))]
PluginCacheDataInvalid { PluginRegistryDataInvalid {
plugin_name: String, plugin_name: String,
#[label("plugin `{plugin_name}` loaded here")] #[label("plugin `{plugin_name}` loaded here")]
span: Option<Span>, span: Option<Span>,
#[help("the format in the plugin cache file is not compatible with this version of Nushell.\n\nTry adding the plugin again with `{}`")] #[help("the format in the plugin registry file is not compatible with this version of Nushell.\n\nTry adding the plugin again with `{}`")]
add_command: String, add_command: String,
}, },

View File

@ -1,9 +1,9 @@
mod cache_file;
mod identity; mod identity;
mod registered; mod registered;
mod registry_file;
mod signature; mod signature;
pub use cache_file::*;
pub use identity::*; pub use identity::*;
pub use registered::*; pub use registered::*;
pub use registry_file::*;
pub use signature::*; pub use signature::*;

View File

@ -15,34 +15,34 @@ const COMPRESSION_QUALITY: u32 = 1;
const WIN_SIZE: u32 = 20; // recommended 20-22 const WIN_SIZE: u32 = 20; // recommended 20-22
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PluginCacheFile { pub struct PluginRegistryFile {
/// The Nushell version that last updated the file. /// The Nushell version that last updated the file.
pub nushell_version: String, pub nushell_version: String,
/// The installed plugins. /// The installed plugins.
pub plugins: Vec<PluginCacheItem>, pub plugins: Vec<PluginRegistryItem>,
} }
impl Default for PluginCacheFile { impl Default for PluginRegistryFile {
fn default() -> Self { fn default() -> Self {
Self::new() Self::new()
} }
} }
impl PluginCacheFile { impl PluginRegistryFile {
/// Create a new, empty plugin cache file. /// Create a new, empty plugin registry file.
pub fn new() -> PluginCacheFile { pub fn new() -> PluginRegistryFile {
PluginCacheFile { PluginRegistryFile {
nushell_version: env!("CARGO_PKG_VERSION").to_owned(), nushell_version: env!("CARGO_PKG_VERSION").to_owned(),
plugins: vec![], plugins: vec![],
} }
} }
/// Read the plugin cache file from a reader, e.g. [`File`](std::fs::File). /// Read the plugin registry file from a reader, e.g. [`File`](std::fs::File).
pub fn read_from( pub fn read_from(
reader: impl Read, reader: impl Read,
error_span: Option<Span>, error_span: Option<Span>,
) -> Result<PluginCacheFile, ShellError> { ) -> Result<PluginRegistryFile, ShellError> {
// Format is brotli compressed messagepack // Format is brotli compressed messagepack
let brotli_reader = brotli::Decompressor::new(reader, BUFFER_SIZE); let brotli_reader = brotli::Decompressor::new(reader, BUFFER_SIZE);
@ -57,7 +57,7 @@ impl PluginCacheFile {
}) })
} }
/// Write the plugin cache file to a writer, e.g. [`File`](std::fs::File). /// Write the plugin registry file to a writer, e.g. [`File`](std::fs::File).
/// ///
/// The `nushell_version` will be updated to the current version before writing. /// The `nushell_version` will be updated to the current version before writing.
pub fn write_to( pub fn write_to(
@ -84,8 +84,8 @@ impl PluginCacheFile {
}) })
} }
/// Insert or update a plugin in the plugin cache file. /// Insert or update a plugin in the plugin registry file.
pub fn upsert_plugin(&mut self, item: PluginCacheItem) { pub fn upsert_plugin(&mut self, item: PluginRegistryItem) {
if let Some(existing_item) = self.plugins.iter_mut().find(|p| p.name == item.name) { if let Some(existing_item) = self.plugins.iter_mut().find(|p| p.name == item.name) {
*existing_item = item; *existing_item = item;
} else { } else {
@ -98,12 +98,12 @@ impl PluginCacheFile {
} }
} }
/// A single plugin definition from a [`PluginCacheFile`]. /// A single plugin definition from a [`PluginRegistryFile`].
/// ///
/// Contains the information necessary for the [`PluginIdentity`], as well as possibly valid data /// Contains the information necessary for the [`PluginIdentity`], as well as possibly valid data
/// about the plugin including the cached command signatures. /// about the plugin including the registered command signatures.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PluginCacheItem { pub struct PluginRegistryItem {
/// The name of the plugin, as would show in `plugin list`. This does not include the file /// The name of the plugin, as would show in `plugin list`. This does not include the file
/// extension or the `nu_plugin_` prefix. /// extension or the `nu_plugin_` prefix.
pub name: String, pub name: String,
@ -117,29 +117,32 @@ pub struct PluginCacheItem {
/// Additional data that might be invalid so that we don't fail to load the whole plugin file /// Additional data that might be invalid so that we don't fail to load the whole plugin file
/// if there's a deserialization error. /// if there's a deserialization error.
#[serde(flatten)] #[serde(flatten)]
pub data: PluginCacheItemData, pub data: PluginRegistryItemData,
} }
impl PluginCacheItem { impl PluginRegistryItem {
/// Create a [`PluginCacheItem`] from an identity and signatures. /// Create a [`PluginRegistryItem`] from an identity and signatures.
pub fn new(identity: &PluginIdentity, mut commands: Vec<PluginSignature>) -> PluginCacheItem { pub fn new(
identity: &PluginIdentity,
mut commands: Vec<PluginSignature>,
) -> PluginRegistryItem {
// Sort the commands for consistency // Sort the commands for consistency
commands.sort_by(|cmd1, cmd2| cmd1.sig.name.cmp(&cmd2.sig.name)); commands.sort_by(|cmd1, cmd2| cmd1.sig.name.cmp(&cmd2.sig.name));
PluginCacheItem { PluginRegistryItem {
name: identity.name().to_owned(), name: identity.name().to_owned(),
filename: identity.filename().to_owned(), filename: identity.filename().to_owned(),
shell: identity.shell().map(|p| p.to_owned()), shell: identity.shell().map(|p| p.to_owned()),
data: PluginCacheItemData::Valid { commands }, data: PluginRegistryItemData::Valid { commands },
} }
} }
} }
/// Possibly valid data about a plugin in a [`PluginCacheFile`]. If deserialization fails, it will /// Possibly valid data about a plugin in a [`PluginRegistryFile`]. If deserialization fails, it will
/// be `Invalid`. /// be `Invalid`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)] #[serde(untagged)]
pub enum PluginCacheItemData { pub enum PluginRegistryItemData {
Valid { Valid {
/// Signatures and examples for each command provided by the plugin. /// Signatures and examples for each command provided by the plugin.
commands: Vec<PluginSignature>, commands: Vec<PluginSignature>,

View File

@ -1,16 +1,16 @@
use super::{PluginCacheFile, PluginCacheItem, PluginCacheItemData}; use super::{PluginRegistryFile, PluginRegistryItem, PluginRegistryItemData};
use crate::{ use crate::{
Category, PluginExample, PluginSignature, ShellError, Signature, SyntaxShape, Type, Value, Category, PluginExample, PluginSignature, ShellError, Signature, SyntaxShape, Type, Value,
}; };
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use std::io::Cursor; use std::io::Cursor;
fn foo_plugin() -> PluginCacheItem { fn foo_plugin() -> PluginRegistryItem {
PluginCacheItem { PluginRegistryItem {
name: "foo".into(), name: "foo".into(),
filename: "/path/to/nu_plugin_foo".into(), filename: "/path/to/nu_plugin_foo".into(),
shell: None, shell: None,
data: PluginCacheItemData::Valid { data: PluginRegistryItemData::Valid {
commands: vec![PluginSignature { commands: vec![PluginSignature {
sig: Signature::new("foo") sig: Signature::new("foo")
.input_output_type(Type::Int, Type::List(Box::new(Type::Int))) .input_output_type(Type::Int, Type::List(Box::new(Type::Int)))
@ -30,12 +30,12 @@ fn foo_plugin() -> PluginCacheItem {
} }
} }
fn bar_plugin() -> PluginCacheItem { fn bar_plugin() -> PluginRegistryItem {
PluginCacheItem { PluginRegistryItem {
name: "bar".into(), name: "bar".into(),
filename: "/path/to/nu_plugin_bar".into(), filename: "/path/to/nu_plugin_bar".into(),
shell: None, shell: None,
data: PluginCacheItemData::Valid { data: PluginRegistryItemData::Valid {
commands: vec![PluginSignature { commands: vec![PluginSignature {
sig: Signature::new("bar") sig: Signature::new("bar")
.usage("overwrites files with random data") .usage("overwrites files with random data")
@ -54,48 +54,48 @@ fn bar_plugin() -> PluginCacheItem {
#[test] #[test]
fn roundtrip() -> Result<(), ShellError> { fn roundtrip() -> Result<(), ShellError> {
let mut plugin_cache_file = PluginCacheFile { let mut plugin_registry_file = PluginRegistryFile {
nushell_version: env!("CARGO_PKG_VERSION").to_owned(), nushell_version: env!("CARGO_PKG_VERSION").to_owned(),
plugins: vec![foo_plugin(), bar_plugin()], plugins: vec![foo_plugin(), bar_plugin()],
}; };
let mut output = vec![]; let mut output = vec![];
plugin_cache_file.write_to(&mut output, None)?; plugin_registry_file.write_to(&mut output, None)?;
let read_file = PluginCacheFile::read_from(Cursor::new(&output[..]), None)?; let read_file = PluginRegistryFile::read_from(Cursor::new(&output[..]), None)?;
assert_eq!(plugin_cache_file, read_file); assert_eq!(plugin_registry_file, read_file);
Ok(()) Ok(())
} }
#[test] #[test]
fn roundtrip_invalid() -> Result<(), ShellError> { fn roundtrip_invalid() -> Result<(), ShellError> {
let mut plugin_cache_file = PluginCacheFile { let mut plugin_registry_file = PluginRegistryFile {
nushell_version: env!("CARGO_PKG_VERSION").to_owned(), nushell_version: env!("CARGO_PKG_VERSION").to_owned(),
plugins: vec![PluginCacheItem { plugins: vec![PluginRegistryItem {
name: "invalid".into(), name: "invalid".into(),
filename: "/path/to/nu_plugin_invalid".into(), filename: "/path/to/nu_plugin_invalid".into(),
shell: None, shell: None,
data: PluginCacheItemData::Invalid, data: PluginRegistryItemData::Invalid,
}], }],
}; };
let mut output = vec![]; let mut output = vec![];
plugin_cache_file.write_to(&mut output, None)?; plugin_registry_file.write_to(&mut output, None)?;
let read_file = PluginCacheFile::read_from(Cursor::new(&output[..]), None)?; let read_file = PluginRegistryFile::read_from(Cursor::new(&output[..]), None)?;
assert_eq!(plugin_cache_file, read_file); assert_eq!(plugin_registry_file, read_file);
Ok(()) Ok(())
} }
#[test] #[test]
fn upsert_new() { fn upsert_new() {
let mut file = PluginCacheFile::new(); let mut file = PluginRegistryFile::new();
file.plugins.push(foo_plugin()); file.plugins.push(foo_plugin());
@ -106,7 +106,7 @@ fn upsert_new() {
#[test] #[test]
fn upsert_replace() { fn upsert_replace() {
let mut file = PluginCacheFile::new(); let mut file = PluginRegistryFile::new();
file.plugins.push(foo_plugin()); file.plugins.push(foo_plugin());

View File

@ -334,7 +334,7 @@ where
temp_file temp_file
}); });
// We don't have to write the plugin cache file, it's ok for it to not exist // We don't have to write the plugin registry file, it's ok for it to not exist
let temp_plugin_file = temp.path().join("plugin.msgpackz"); let temp_plugin_file = temp.path().join("plugin.msgpackz");
crate::commands::ensure_plugins_built(); crate::commands::ensure_plugins_built();

View File

@ -392,13 +392,13 @@ impl Command for Nu {
.named( .named(
"plugin-config", "plugin-config",
SyntaxShape::Filepath, SyntaxShape::Filepath,
"start with an alternate plugin cache file", "start with an alternate plugin registry file",
None, None,
) )
.named( .named(
"plugins", "plugins",
SyntaxShape::List(Box::new(SyntaxShape::Filepath)), SyntaxShape::List(Box::new(SyntaxShape::Filepath)),
"list of plugin executable files to load, separately from the cache file", "list of plugin executable files to load, separately from the registry file",
None, None,
) )
} }

View File

@ -598,7 +598,7 @@ register $file
fn plugin_use_with_string_literal() -> TestResult { fn plugin_use_with_string_literal() -> TestResult {
fail_test( fail_test(
r#"plugin use 'nu-plugin-math'"#, r#"plugin use 'nu-plugin-math'"#,
"Plugin cache file not set", "Plugin registry file not set",
) )
} }
@ -609,7 +609,7 @@ const file = 'nu-plugin-math'
plugin use $file plugin use $file
"; ";
// should not fail with `not a constant` // should not fail with `not a constant`
fail_test(input, "Plugin cache file not set") fail_test(input, "Plugin registry file not set")
} }
#[test] #[test]

View File

@ -1,4 +1,3 @@
mod cache_file;
mod config; mod config;
mod core_inc; mod core_inc;
mod custom_values; mod custom_values;
@ -6,5 +5,6 @@ mod env;
mod formats; mod formats;
mod nu_plugin_nu_example; mod nu_plugin_nu_example;
mod register; mod register;
mod registry_file;
mod stream; mod stream;
mod stress_internals; mod stress_internals;

View File

@ -1,6 +1,6 @@
use std::{fs::File, path::PathBuf}; use std::{fs::File, path::PathBuf};
use nu_protocol::{PluginCacheFile, PluginCacheItem, PluginCacheItemData}; use nu_protocol::{PluginRegistryFile, PluginRegistryItem, PluginRegistryItemData};
use nu_test_support::{fs::Stub, nu, nu_with_plugins, playground::Playground}; use nu_test_support::{fs::Stub, nu, nu_with_plugins, playground::Playground};
fn example_plugin_path() -> PathBuf { fn example_plugin_path() -> PathBuf {
@ -120,7 +120,7 @@ fn plugin_add_to_custom_path() {
assert!(result.status.success()); assert!(result.status.success());
let contents = PluginCacheFile::read_from( let contents = PluginRegistryFile::read_from(
File::open(dirs.test().join("test-plugin-file.msgpackz")) File::open(dirs.test().join("test-plugin-file.msgpackz"))
.expect("failed to open plugin file"), .expect("failed to open plugin file"),
None, None,
@ -143,21 +143,21 @@ fn plugin_rm_then_restart_nu() {
let file = File::create(dirs.test().join("test-plugin-file.msgpackz")) let file = File::create(dirs.test().join("test-plugin-file.msgpackz"))
.expect("failed to create file"); .expect("failed to create file");
let mut contents = PluginCacheFile::new(); let mut contents = PluginRegistryFile::new();
contents.upsert_plugin(PluginCacheItem { contents.upsert_plugin(PluginRegistryItem {
name: "example".into(), name: "example".into(),
filename: example_plugin_path, filename: example_plugin_path,
shell: None, shell: None,
data: PluginCacheItemData::Valid { commands: vec![] }, data: PluginRegistryItemData::Valid { commands: vec![] },
}); });
contents.upsert_plugin(PluginCacheItem { contents.upsert_plugin(PluginRegistryItem {
name: "foo".into(), name: "foo".into(),
// this doesn't exist, but it should be ok // this doesn't exist, but it should be ok
filename: dirs.test().join("nu_plugin_foo"), filename: dirs.test().join("nu_plugin_foo"),
shell: None, shell: None,
data: PluginCacheItemData::Valid { commands: vec![] }, data: PluginRegistryItemData::Valid { commands: vec![] },
}); });
contents contents
@ -219,21 +219,21 @@ fn plugin_rm_from_custom_path() {
Playground::setup("plugin rm from custom path", |dirs, _playground| { Playground::setup("plugin rm from custom path", |dirs, _playground| {
let file = File::create(dirs.test().join("test-plugin-file.msgpackz")) let file = File::create(dirs.test().join("test-plugin-file.msgpackz"))
.expect("failed to create file"); .expect("failed to create file");
let mut contents = PluginCacheFile::new(); let mut contents = PluginRegistryFile::new();
contents.upsert_plugin(PluginCacheItem { contents.upsert_plugin(PluginRegistryItem {
name: "example".into(), name: "example".into(),
filename: example_plugin_path, filename: example_plugin_path,
shell: None, shell: None,
data: PluginCacheItemData::Valid { commands: vec![] }, data: PluginRegistryItemData::Valid { commands: vec![] },
}); });
contents.upsert_plugin(PluginCacheItem { contents.upsert_plugin(PluginRegistryItem {
name: "foo".into(), name: "foo".into(),
// this doesn't exist, but it should be ok // this doesn't exist, but it should be ok
filename: dirs.test().join("nu_plugin_foo"), filename: dirs.test().join("nu_plugin_foo"),
shell: None, shell: None,
data: PluginCacheItemData::Valid { commands: vec![] }, data: PluginRegistryItemData::Valid { commands: vec![] },
}); });
contents contents
@ -248,7 +248,7 @@ fn plugin_rm_from_custom_path() {
assert!(result.err.trim().is_empty()); assert!(result.err.trim().is_empty());
// Check the contents after running // Check the contents after running
let contents = PluginCacheFile::read_from( let contents = PluginRegistryFile::read_from(
File::open(dirs.test().join("test-plugin-file.msgpackz")).expect("failed to open file"), File::open(dirs.test().join("test-plugin-file.msgpackz")).expect("failed to open file"),
None, None,
) )
@ -267,21 +267,21 @@ fn plugin_rm_using_filename() {
Playground::setup("plugin rm using filename", |dirs, _playground| { Playground::setup("plugin rm using filename", |dirs, _playground| {
let file = File::create(dirs.test().join("test-plugin-file.msgpackz")) let file = File::create(dirs.test().join("test-plugin-file.msgpackz"))
.expect("failed to create file"); .expect("failed to create file");
let mut contents = PluginCacheFile::new(); let mut contents = PluginRegistryFile::new();
contents.upsert_plugin(PluginCacheItem { contents.upsert_plugin(PluginRegistryItem {
name: "example".into(), name: "example".into(),
filename: example_plugin_path.clone(), filename: example_plugin_path.clone(),
shell: None, shell: None,
data: PluginCacheItemData::Valid { commands: vec![] }, data: PluginRegistryItemData::Valid { commands: vec![] },
}); });
contents.upsert_plugin(PluginCacheItem { contents.upsert_plugin(PluginRegistryItem {
name: "foo".into(), name: "foo".into(),
// this doesn't exist, but it should be ok // this doesn't exist, but it should be ok
filename: dirs.test().join("nu_plugin_foo"), filename: dirs.test().join("nu_plugin_foo"),
shell: None, shell: None,
data: PluginCacheItemData::Valid { commands: vec![] }, data: PluginRegistryItemData::Valid { commands: vec![] },
}); });
contents contents
@ -299,7 +299,7 @@ fn plugin_rm_using_filename() {
assert!(result.err.trim().is_empty()); assert!(result.err.trim().is_empty());
// Check the contents after running // Check the contents after running
let contents = PluginCacheFile::read_from( let contents = PluginRegistryFile::read_from(
File::open(dirs.test().join("test-plugin-file.msgpackz")).expect("failed to open file"), File::open(dirs.test().join("test-plugin-file.msgpackz")).expect("failed to open file"),
None, None,
) )
@ -325,21 +325,21 @@ fn warning_on_invalid_plugin_item() {
let file = File::create(dirs.test().join("test-plugin-file.msgpackz")) let file = File::create(dirs.test().join("test-plugin-file.msgpackz"))
.expect("failed to create file"); .expect("failed to create file");
let mut contents = PluginCacheFile::new(); let mut contents = PluginRegistryFile::new();
contents.upsert_plugin(PluginCacheItem { contents.upsert_plugin(PluginRegistryItem {
name: "example".into(), name: "example".into(),
filename: example_plugin_path, filename: example_plugin_path,
shell: None, shell: None,
data: PluginCacheItemData::Valid { commands: vec![] }, data: PluginRegistryItemData::Valid { commands: vec![] },
}); });
contents.upsert_plugin(PluginCacheItem { contents.upsert_plugin(PluginRegistryItem {
name: "badtest".into(), name: "badtest".into(),
// this doesn't exist, but it should be ok // this doesn't exist, but it should be ok
filename: dirs.test().join("nu_plugin_badtest"), filename: dirs.test().join("nu_plugin_badtest"),
shell: None, shell: None,
data: PluginCacheItemData::Invalid, data: PluginRegistryItemData::Invalid,
}); });
contents contents
@ -372,7 +372,7 @@ fn warning_on_invalid_plugin_item() {
// The "example" plugin should be unaffected // The "example" plugin should be unaffected
assert_eq!(r#"["example"]"#, out); assert_eq!(r#"["example"]"#, out);
// The warning should be in there // The warning should be in there
assert!(err.contains("cached plugin data")); assert!(err.contains("registered plugin data"));
assert!(err.contains("badtest")); assert!(err.contains("badtest"));
}) })
} }
@ -388,9 +388,9 @@ fn plugin_use_error_not_found() {
// Make an empty msgpackz // Make an empty msgpackz
let file = File::create(dirs.test().join("plugin.msgpackz")) let file = File::create(dirs.test().join("plugin.msgpackz"))
.expect("failed to open plugin.msgpackz"); .expect("failed to open plugin.msgpackz");
PluginCacheFile::default() PluginRegistryFile::default()
.write_to(file, None) .write_to(file, None)
.expect("failed to write empty cache file"); .expect("failed to write empty registry file");
let output = assert_cmd::Command::new(nu_test_support::fs::executable_path()) let output = assert_cmd::Command::new(nu_test_support::fs::executable_path())
.current_dir(dirs.test()) .current_dir(dirs.test())