Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: split asdf into backend+plugin #2226

Merged
merged 1 commit into from
Aug 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
389 changes: 27 additions & 362 deletions src/backend/asdf.rs

Large diffs are not rendered by default.

52 changes: 8 additions & 44 deletions src/backend/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use std::hash::Hash;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use clap::Command;
use console::style;
use contracts::requires;
use eyre::{bail, eyre, WrapErr};
Expand All @@ -21,14 +20,12 @@ use crate::cli::args::BackendArg;
use crate::config::{Config, Settings};
use crate::file::{display_path, remove_all, remove_all_with_warning};
use crate::install_context::InstallContext;
use crate::lock_file::LockFile;
use crate::plugins::core::CORE_PLUGINS;
use crate::plugins::{PluginType, VERSION_REGEX};
use crate::plugins::{Plugin, PluginType, VERSION_REGEX};
use crate::runtime_symlinks::is_runtime_symlink;
use crate::toolset::{ToolRequest, ToolVersion, Toolset};
use crate::ui::multi_progress_report::MultiProgressReport;
use crate::ui::progress_report::SingleReport;
use crate::{dirs, file};
use crate::{dirs, file, lock_file};

use self::backend_meta::BackendMeta;

Expand Down Expand Up @@ -270,7 +267,6 @@ pub trait Backend: Debug + Send + Sync {
None => self.latest_stable_version(),
}
}
#[requires(self.is_installed())]
fn latest_installed_version(&self, query: Option<String>) -> eyre::Result<Option<String>> {
match query {
Some(query) => {
Expand Down Expand Up @@ -300,18 +296,6 @@ pub trait Backend: Debug + Send + Sync {
fn get_remote_url(&self) -> Option<String> {
None
}
fn is_installed(&self) -> bool {
true
}
fn is_installed_err(&self) -> eyre::Result<()> {
if self.is_installed() {
return Ok(());
}
bail!("{} is not installed", self.id())
}
fn ensure_installed(&self, _mpr: &MultiProgressReport, _force: bool) -> eyre::Result<()> {
Ok(())
}
fn ensure_dependencies_installed(&self) -> eyre::Result<()> {
let deps = self
.get_all_dependencies(&ToolRequest::System(self.id().into()))?
Expand All @@ -328,12 +312,6 @@ pub trait Backend: Debug + Send + Sync {
}
Ok(())
}
fn update(&self, _pr: &dyn SingleReport, _git_ref: Option<String>) -> eyre::Result<()> {
Ok(())
}
fn uninstall(&self, _pr: &dyn SingleReport) -> eyre::Result<()> {
Ok(())
}
fn purge(&self, pr: &dyn SingleReport) -> eyre::Result<()> {
rmdir(&self.fa().installs_path, pr)?;
rmdir(&self.fa().cache_path, pr)?;
Expand All @@ -350,16 +328,15 @@ pub trait Backend: Debug + Send + Sync {
let contents = file::read_to_string(path)?;
Ok(contents.trim().to_string())
}
fn external_commands(&self) -> eyre::Result<Vec<Command>> {
Ok(vec![])
}
fn execute_external_command(&self, _command: &str, _args: Vec<String>) -> eyre::Result<()> {
unimplemented!()
fn plugin(&self) -> Option<&dyn Plugin> {
None
}

#[requires(ctx.tv.backend.backend_type == self.get_type())]
fn install_version(&self, ctx: InstallContext) -> eyre::Result<()> {
self.is_installed_err()?;
if let Some(plugin) = self.plugin() {
plugin.is_installed_err()?;
}
let config = Config::get();
let settings = Settings::try_get()?;
if self.is_version_installed(&ctx.tv) {
Expand All @@ -370,7 +347,7 @@ pub trait Backend: Debug + Send + Sync {
return Ok(());
}
}
let _lock = self.get_lock(&ctx.tv.install_path(), ctx.force)?;
let _lock = lock_file::get(&ctx.tv.install_path(), ctx.force)?;
self.create_install_dirs(&ctx.tv)?;

if let Err(e) = self.install_version_impl(&ctx) {
Expand Down Expand Up @@ -458,19 +435,6 @@ pub trait Backend: Debug + Send + Sync {
Ok(None)
}

fn get_lock(&self, path: &Path, force: bool) -> eyre::Result<Option<fslock::LockFile>> {
let lock = if force {
None
} else {
let lock = LockFile::new(path)
.with_callback(|l| {
debug!("waiting for lock on {}", display_path(l));
})
.lock()?;
Some(lock)
};
Ok(lock)
}
fn create_install_dirs(&self, tv: &ToolVersion) -> eyre::Result<()> {
let _ = remove_all_with_warning(tv.install_path());
let _ = remove_all_with_warning(tv.download_path());
Expand Down
18 changes: 11 additions & 7 deletions src/cli/current.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,24 @@ impl Current {
let ts = ToolsetBuilder::new().build(&config)?;
match &self.plugin {
Some(fa) => {
let plugin = backend::get(fa);
if !plugin.is_installed() {
bail!("Plugin {fa} is not installed");
let backend = backend::get(fa);
if let Some(plugin) = backend.plugin() {
if !plugin.is_installed() {
bail!("Plugin {fa} is not installed");
}
}
self.one(ts, plugin.as_ref())
self.one(ts, backend.as_ref())
}
None => self.all(ts),
}
}

fn one(&self, ts: Toolset, tool: &dyn Backend) -> Result<()> {
if !tool.is_installed() {
warn!("Plugin {} is not installed", tool.id());
return Ok(());
if let Some(plugin) = tool.plugin() {
if !plugin.is_installed() {
warn!("Plugin {} is not installed", tool.id());
return Ok(());
}
}
match ts
.list_versions_by_plugin()
Expand Down
17 changes: 11 additions & 6 deletions src/cli/doctor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,13 @@ impl Doctor {
section("backends", render_backends())?;
section("plugins", render_plugins())?;

for plugin in backend::list() {
if !plugin.is_installed() {
self.errors
.push(format!("plugin {} is not installed", &plugin.id()));
continue;
for backend in backend::list() {
if let Some(plugin) = backend.plugin() {
if !plugin.is_installed() {
self.errors
.push(format!("plugin {} is not installed", &plugin.name()));
continue;
}
}
}

Expand Down Expand Up @@ -256,7 +258,10 @@ fn render_backends() -> String {
fn render_plugins() -> String {
let plugins = backend::list()
.into_iter()
.filter(|p| p.is_installed() && p.get_type() == BackendType::Asdf)
.filter(|b| {
b.plugin()
.is_some_and(|p| p.is_installed() && b.get_type() == BackendType::Asdf)
})
.collect::<Vec<_>>();
let max_plugin_name_len = plugins
.iter()
Expand Down
21 changes: 13 additions & 8 deletions src/cli/external.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,15 @@ use crate::cli::args::BackendArg;
pub fn commands() -> Vec<Command> {
backend::list()
.into_par_iter()
.flat_map(|p| {
p.external_commands().unwrap_or_else(|e| {
let p = p.id();
warn!("failed to load external commands for plugin {p}: {e:#}");
vec![]
})
.flat_map(|b| {
if let Some(p) = b.plugin() {
return p.external_commands().unwrap_or_else(|e| {
let p = p.name();
warn!("failed to load external commands for plugin {p}: {e:#}");
vec![]
});
}
vec![]
})
.collect()
}
Expand All @@ -24,13 +27,15 @@ pub fn execute(fa: &BackendArg, args: &ArgMatches) -> Result<()> {
.find(|c| c.get_name() == fa.to_string())
{
if let Some((subcommand, matches)) = args.subcommand() {
let plugin = backend::get(fa);
let backend = backend::get(fa);
let args: Vec<String> = matches
.get_raw("args")
.unwrap_or_default()
.map(|s| s.to_string_lossy().to_string())
.collect();
plugin.execute_external_command(subcommand, args)?;
if let Some(p) = backend.plugin() {
p.execute_external_command(subcommand, args)?;
}
} else {
cmd.print_help().unwrap();
}
Expand Down
12 changes: 7 additions & 5 deletions src/cli/latest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,19 @@ impl Latest {
_ => bail!("invalid version: {}", self.tool.style()),
};

let plugin: ABackend = self.tool.backend.into();
let backend: ABackend = self.tool.backend.into();
let mpr = MultiProgressReport::get();
plugin.ensure_installed(&mpr, false)?;
if let Some(plugin) = backend.plugin() {
plugin.ensure_installed(&mpr, false)?;
}
if let Some(v) = prefix {
prefix = Some(config.resolve_alias(plugin.as_ref(), &v)?);
prefix = Some(config.resolve_alias(backend.as_ref(), &v)?);
}

let latest_version = if self.installed {
plugin.latest_installed_version(prefix)?
backend.latest_installed_version(prefix)?
} else {
plugin.latest_version(prefix)?
backend.latest_version(prefix)?
};
if let Some(version) = latest_version {
miseprintln!("{}", version);
Expand Down
6 changes: 4 additions & 2 deletions src/cli/ls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,10 @@ impl Ls {
fn verify_plugin(&self) -> Result<()> {
if let Some(plugins) = &self.plugin {
for fa in plugins {
let plugin = backend::get(fa);
ensure!(plugin.is_installed(), "{fa} is not installed");
let backend = backend::get(fa);
if let Some(plugin) = backend.plugin() {
ensure!(plugin.is_installed(), "{fa} is not installed");
}
}
}
Ok(())
Expand Down
11 changes: 7 additions & 4 deletions src/cli/ls_remote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ use crate::ui::multi_progress_report::MultiProgressReport;
/// note that the results are cached for 24 hours
/// run `mise cache clean` to clear the cache and get fresh results
#[derive(Debug, clap::Args)]
#[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP, aliases = ["list-all", "list-remote"])]
#[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP, aliases = ["list-all", "list-remote"]
)]
pub struct LsRemote {
/// Plugin to get versions for
#[clap(value_name = "TOOL@VERSION", required_unless_present = "all")]
Expand Down Expand Up @@ -87,10 +88,12 @@ impl LsRemote {
fn get_plugin(&self) -> Result<Option<Arc<dyn Backend>>> {
match &self.plugin {
Some(tool_arg) => {
let plugin = backend::get(&tool_arg.backend);
let backend = backend::get(&tool_arg.backend);
let mpr = MultiProgressReport::get();
plugin.ensure_installed(&mpr, false)?;
Ok(Some(plugin))
if let Some(plugin) = backend.plugin() {
plugin.ensure_installed(&mpr, false)?;
}
Ok(Some(backend))
}
None => Ok(None),
}
Expand Down
13 changes: 8 additions & 5 deletions src/cli/plugins/install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ use rayon::prelude::*;
use rayon::ThreadPoolBuilder;
use url::Url;

use crate::backend::asdf::Asdf;
use crate::backend::{unalias_backend, Backend};
use crate::backend::unalias_backend;
use crate::config::{Config, Settings};
use crate::plugins::asdf_plugin::AsdfPlugin;
use crate::plugins::core::CORE_PLUGINS;
use crate::plugins::Plugin;
use crate::toolset::ToolsetBuilder;
use crate::ui::multi_progress_report::MultiProgressReport;
use crate::ui::style;
Expand All @@ -18,7 +19,8 @@ use crate::ui::style;
///
/// This behavior can be modified in ~/.config/mise/config.toml
#[derive(Debug, clap::Args)]
#[clap(visible_aliases = ["i", "a", "add"], verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)]
#[clap(visible_aliases = ["i", "a", "add"], verbatim_doc_comment, after_long_help = AFTER_LONG_HELP
)]
pub struct PluginsInstall {
/// The name of the plugin to install
/// e.g.: node, ruby
Expand All @@ -28,7 +30,8 @@ pub struct PluginsInstall {

/// The git url of the plugin
/// e.g.: https://github.com/asdf-vm/asdf-nodejs.git
#[clap(help = "The git url of the plugin", value_hint = clap::ValueHint::Url, verbatim_doc_comment)]
#[clap(help = "The git url of the plugin", value_hint = clap::ValueHint::Url, verbatim_doc_comment
)]
git_url: Option<String>,

/// Reinstall even if plugin exists
Expand Down Expand Up @@ -108,7 +111,7 @@ impl PluginsInstall {
git_url: Option<String>,
mpr: &MultiProgressReport,
) -> Result<()> {
let mut plugin = Asdf::new(name.clone());
let mut plugin = AsdfPlugin::new(name.clone());
plugin.repo_url = git_url;
if !self.force && plugin.is_installed() {
warn!("Plugin {name} already installed");
Expand Down
2 changes: 1 addition & 1 deletion src/cli/plugins/ls_remote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ impl PluginsLsRemote {
pub fn run(self, config: &Config) -> Result<()> {
let installed_plugins = plugins::list()
.into_iter()
.filter(|p| p.is_installed())
.filter(|b| b.plugin().is_some_and(|p| p.is_installed()))
.map(|p| p.id().to_string())
.collect::<HashSet<_>>();

Expand Down
20 changes: 10 additions & 10 deletions src/cli/plugins/uninstall.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,17 +42,17 @@ impl PluginsUninstall {
}

fn uninstall_one(&self, plugin_name: &str, mpr: &MultiProgressReport) -> Result<()> {
match plugins::get(plugin_name) {
plugin if plugin.is_installed() => {
let prefix = format!("plugin:{}", style::eblue(&plugin.id()));
let pr = mpr.add(&prefix);
plugin.uninstall(pr.as_ref())?;
if self.purge {
plugin.purge(pr.as_ref())?;
}
pr.finish_with_message("uninstalled".into());
let backend = plugins::get(plugin_name);
if let Some(plugin) = backend.plugin() {
let prefix = format!("plugin:{}", style::eblue(&backend.name()));
let pr = mpr.add(&prefix);
plugin.uninstall(pr.as_ref())?;
if self.purge {
backend.purge(pr.as_ref())?;
}
_ => warn!("{} is not installed", style::eblue(plugin_name)),
pr.finish_with_message("uninstalled".into());
} else {
warn!("{} is not installed", style::eblue(plugin_name));
}
Ok(())
}
Expand Down
13 changes: 8 additions & 5 deletions src/cli/plugins/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,15 @@ impl Update {
.install(|| {
plugins
.into_par_iter()
.map(|(plugin, ref_)| {
let prefix = format!("plugin:{}", style(plugin.id()).blue().for_stderr());
.map(|(backend, ref_)| {
let prefix = format!("plugin:{}", style(backend.id()).blue().for_stderr());
let pr = mpr.add(&prefix);
plugin
.update(pr.as_ref(), ref_)
.map_err(|e| eyre!("[{plugin}] plugin update: {e:?}"))
if let Some(plugin) = backend.plugin() {
plugin
.update(pr.as_ref(), ref_)
.map_err(|e| eyre!("[{backend}] plugin update: {e:?}"))?;
}
Ok(())
})
.filter_map(|r| r.err())
.collect::<Vec<_>>()
Expand Down
Loading
Loading