r2x 0.1.14

The r2x-cli plugin manager for model interoperability.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! Package verification and automatic reinstallation

use crate::manifest_lookup::resolve_plugin_ref;
use crate::plugins::package_spec::{is_git_url, is_local_path};
use r2x_config::Config;
use r2x_logger as logger;
use r2x_manifest::types::{Manifest, Package, PackageSource};
use r2x_python::utils::resolve_site_package_path;
use std::path::{Path, PathBuf};

#[derive(Debug, Clone, PartialEq)]
pub enum VerificationResult {
    /// All packages are valid and installed
    Valid,
    /// Some packages are missing or changed
    Missing(Vec<String>),
}

#[derive(Debug)]
pub enum VerificationError {
    /// Failed to read venv directory
    VenvNotFound(PathBuf),
    /// Failed to verify package installation
    VerificationFailed(String),
    /// Failed to reinstall packages
    ReinstallFailed(String),
}

impl std::fmt::Display for VerificationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            VerificationError::VenvNotFound(path) => {
                write!(f, "Virtual environment not found at: {}", path.display())
            }
            VerificationError::VerificationFailed(msg) => {
                write!(f, "Package verification failed: {}", msg)
            }
            VerificationError::ReinstallFailed(msg) => {
                write!(f, "Package reinstallation failed: {}", msg)
            }
        }
    }
}

impl std::error::Error for VerificationError {}

/// Verify that all packages required for a plugin are installed
///
/// # Arguments
/// * `manifest` - Plugin manifest containing cached plugin metadata
/// * `plugin_key` - Key of the plugin to verify (e.g., "parser-reeds")
///
/// # Returns
/// * `Ok(VerificationResult::Valid)` - All packages installed and valid
/// * `Ok(VerificationResult::Missing(packages))` - List of missing/changed packages
/// * `Err(VerificationError)` - Critical error during verification
fn verify_plugin_packages(
    manifest: &Manifest,
    plugin_key: &str,
) -> Result<VerificationResult, VerificationError> {
    logger::debug(&format!("Verifying packages for plugin: {}", plugin_key));

    let resolved = resolve_plugin_ref(manifest, plugin_key)
        .map_err(|e| VerificationError::VerificationFailed(e.to_string()))?;
    let package_name = resolved.package.name.to_string();

    // Get venv path
    let config = Config::load().map_err(|e| {
        VerificationError::VerificationFailed(format!("Failed to load config: {}", e))
    })?;
    let venv_path = PathBuf::from(config.get_venv_path());

    if !venv_path.exists() {
        return Err(VerificationError::VenvNotFound(venv_path));
    }

    // Check if package is installed
    let missing_packages = check_packages_installed(&venv_path, &[&package_name])?;

    if missing_packages.is_empty() {
        logger::debug(&format!("Package '{}' verified successfully", package_name));
        Ok(VerificationResult::Valid)
    } else {
        logger::debug(&format!("Missing packages: {:?}", missing_packages));
        Ok(VerificationResult::Missing(missing_packages))
    }
}

/// Check if packages are installed in the virtual environment
///
/// # Arguments
/// * `venv_path` - Path to virtual environment
/// * `packages` - List of package names to check
///
/// # Returns
/// List of packages that are not installed or invalid
fn check_packages_installed(
    venv_path: &Path,
    packages: &[&str],
) -> Result<Vec<String>, VerificationError> {
    let site_packages = get_site_packages_dir(venv_path)?;
    let mut missing = Vec::new();

    for package in packages {
        // Convert package name format: "r2x-reeds" -> "r2x_reeds"
        let package_dir_name = package.replace('-', "_");

        // Check if package directory exists
        let package_dir = site_packages.join(&package_dir_name);
        let dist_info_pattern = format!("{}-*.dist-info", package_dir_name);

        let package_exists =
            package_dir.exists() || dist_info_exists(&site_packages, &dist_info_pattern);

        if package_exists {
            logger::debug(&format!("Package '{}' found in site-packages", package));
        } else {
            logger::debug(&format!("Package '{}' not found in site-packages", package));
            missing.push((*package).to_string());
        }
    }

    Ok(missing)
}

/// Get the site-packages directory from venv
fn get_site_packages_dir(venv_path: &Path) -> Result<PathBuf, VerificationError> {
    logger::debug(&format!(
        "Getting site-packages directory for venv: {}",
        venv_path.display()
    ));

    resolve_site_package_path(venv_path).map_err(|e| match e {
        r2x_python::errors::BridgeError::VenvNotFound(path) => {
            VerificationError::VenvNotFound(path)
        }
        _ => VerificationError::VerificationFailed(format!("{}", e)),
    })
}

/// Check if a dist-info directory matching the pattern exists
fn dist_info_exists(site_packages: &Path, pattern: &str) -> bool {
    let pattern_prefix = pattern.split('-').next().unwrap_or("");

    if let Ok(entries) = std::fs::read_dir(site_packages) {
        for entry in entries.flatten() {
            let name = entry.file_name();
            let name_str = name.to_string_lossy();
            if name_str.starts_with(pattern_prefix) && name_str.ends_with(".dist-info") {
                return true;
            }
        }
    }

    false
}

fn ensure_manifest_package(package: &Package, config: &Config) -> Result<(), VerificationError> {
    let (package_spec, editable) = manifest_install_spec(package)?;
    let python_exe = config.get_venv_python_path();
    let install_args = build_pip_install_args(&python_exe, &[package_spec], editable);

    run_pip_install(config, &install_args, 1)
}

fn manifest_install_spec(package: &Package) -> Result<(&str, bool), VerificationError> {
    let source_uri = package
        .source_uri
        .as_deref()
        .filter(|source_uri| !source_uri.trim().is_empty());
    let source_is_explicit = source_uri.is_some_and(|source_uri| {
        is_git_url(source_uri) || is_local_path(source_uri) || source_uri.starts_with("file:")
    });
    let source_is_required = package.editable_install
        || source_is_explicit
        || matches!(
            package.source_kind,
            PackageSource::Github | PackageSource::Git | PackageSource::Local
        );

    if source_is_required {
        let source_uri = source_uri.ok_or_else(|| {
            VerificationError::ReinstallFailed(format!(
                "Package '{}' requires its original source URI for reinstallation",
                package.name
            ))
        })?;
        return Ok((source_uri, package.editable_install));
    }

    Ok((package.name.as_ref(), false))
}

fn build_pip_install_args(python_exe: &str, packages: &[&str], editable: bool) -> Vec<String> {
    let mut install_args = vec![
        "pip".to_string(),
        "install".to_string(),
        "--python".to_string(),
        python_exe.to_string(),
        "--prerelease=allow".to_string(),
    ];

    if editable {
        install_args.push("-e".to_string());
    }

    install_args.extend(packages.iter().map(|package| (*package).to_string()));
    install_args
}

fn run_pip_install(
    config: &Config,
    install_args: &[String],
    package_count: usize,
) -> Result<(), VerificationError> {
    let uv_path = config
        .uv_path
        .as_ref()
        .ok_or_else(|| VerificationError::ReinstallFailed("uv not configured".to_string()))?;

    let package_target = install_args
        .last()
        .map_or("requested packages", String::as_str);
    crate::uv::run(
        uv_path,
        "Installing missing package",
        package_target,
        install_args.to_vec(),
    )
    .map_err(|error| VerificationError::ReinstallFailed(error.to_string()))?;

    logger::success(&format!(
        "Successfully installed {package_count} package(s)"
    ));
    Ok(())
}

/// Verify and ensure packages for a plugin are installed
///
/// This is the main entry point that combines verification and reinstallation.
/// It will automatically reinstall missing packages.
///
/// # Arguments
/// * `manifest` - Plugin manifest
/// * `plugin_key` - Plugin to verify (e.g., "parser-reeds")
///
/// # Returns
/// * `Ok(())` - Plugin packages verified and available
/// * `Err(VerificationError)` - Failed to verify or install packages
///
/// # Example
///
/// ```rust,ignore
/// use r2x::package_verification::verify_and_ensure_plugin;
/// use r2x_manifest::types::Manifest;
///
/// let manifest = Manifest::load()?;
///
/// // This will verify r2x-reeds is installed
/// // If missing, it will automatically reinstall it
/// verify_and_ensure_plugin(&manifest, "parser-reeds")?;
///
/// // Now safe to run the plugin
/// ```
pub(crate) fn verify_and_ensure_plugin(
    manifest: &Manifest,
    plugin_key: &str,
) -> Result<(), VerificationError> {
    logger::debug(&format!("Verifying and ensuring plugin: {}", plugin_key));

    match verify_plugin_packages(manifest, plugin_key)? {
        VerificationResult::Valid => {
            logger::debug("All packages verified successfully");
            Ok(())
        }
        VerificationResult::Missing(packages) => {
            logger::info(&format!(
                "Missing {} package(s), reinstalling...",
                packages.len()
            ));
            let config = Config::load().map_err(|e| {
                VerificationError::ReinstallFailed(format!("Failed to load config: {}", e))
            })?;
            let resolved = resolve_plugin_ref(manifest, plugin_key)
                .map_err(|e| VerificationError::ReinstallFailed(e.to_string()))?;
            ensure_manifest_package(resolved.package, &config)?;
            logger::success("Packages verified and installed");
            Ok(())
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::package_verification::*;
    use r2x_manifest::types::{Package, PackageSource};
    use std::sync::Arc;

    fn package_with_source(
        source_kind: PackageSource,
        source_uri: Option<&str>,
        editable_install: bool,
    ) -> Package {
        Package {
            name: Arc::from("r2x-reeds"),
            source_kind,
            source_uri: source_uri.map(Arc::from),
            editable_install,
            ..Default::default()
        }
    }

    #[test]
    fn test_verification_result_valid() {
        let result = VerificationResult::Valid;
        assert_eq!(result, VerificationResult::Valid);
    }

    #[test]
    fn test_verification_result_missing() {
        let packages = vec!["r2x-reeds".to_string(), "r2x-core".to_string()];
        let result = VerificationResult::Missing(packages.clone());
        match result {
            VerificationResult::Missing(p) => assert_eq!(p, packages),
            VerificationResult::Valid => unreachable!("Expected Missing variant"),
        }
    }

    #[test]
    fn test_package_name_conversion() {
        let package = "r2x-reeds";
        let converted = package.replace('-', "_");
        assert_eq!(converted, "r2x_reeds");
    }

    #[test]
    fn test_verification_error_display() {
        let err = VerificationError::VerificationFailed("test error".to_string());
        assert_eq!(err.to_string(), "Package verification failed: test error");
    }

    #[test]
    fn test_dist_info_pattern() {
        // Test that dist-info pattern matching works
        let pattern = "r2x_reeds-*.dist-info";
        let pattern_prefix = pattern.split('-').next().unwrap_or("");
        assert_eq!(pattern_prefix, "r2x_reeds");

        // Verify pattern matches expected format
        let example_dist_info = "r2x_reeds-1.2.3.dist-info";
        assert!(example_dist_info.starts_with(pattern_prefix));
        assert!(example_dist_info.ends_with(".dist-info"));
    }

    #[test]
    fn test_verification_workflow() {
        // This test documents the expected verification workflow
        // Actual integration tests would require a real venv

        // 1. User runs: r2x python venv --clear
        // 2. Venv is wiped but manifest still has plugins
        // 3. User runs: r2x run parser-reeds
        // 4. Verification detects missing packages
        // 5. Auto-reinstall kicks in
        // 6. Plugin executes successfully

        // Simulate the workflow states
        let valid_result = VerificationResult::Valid;
        let missing_result = VerificationResult::Missing(vec!["r2x-reeds".to_string()]);

        // After venv wipe, we expect Missing
        assert!(matches!(missing_result, VerificationResult::Missing(_)));

        // After reinstall, we expect Valid
        assert!(matches!(valid_result, VerificationResult::Valid));
    }

    #[test]
    fn manifest_reinstall_uses_package_name_for_pypi() {
        let package = package_with_source(PackageSource::Pypi, None, false);

        let Ok((package_spec, editable)) = manifest_install_spec(&package) else {
            unreachable!("PyPI install spec should resolve");
        };
        let args = build_pip_install_args("/tmp/python", &[package_spec], editable);

        assert_eq!(args.last(), Some(&"r2x-reeds".to_string()));
        assert!(!args.iter().any(|arg| arg == "-e"));
    }

    #[test]
    fn manifest_reinstall_uses_editable_local_source() {
        let package = package_with_source(PackageSource::Local, Some("/tmp/r2x-reeds"), true);
        let Ok((package_spec, editable)) = manifest_install_spec(&package) else {
            unreachable!("local install spec should resolve");
        };

        let args = build_pip_install_args("/tmp/python", &[package_spec], editable);

        assert!(args.iter().any(|arg| arg == "-e"));
        assert_eq!(args.last(), Some(&"/tmp/r2x-reeds".to_string()));
    }

    #[test]
    fn manifest_reinstall_uses_git_uri_despite_legacy_pypi_kind() {
        let package = package_with_source(
            PackageSource::Pypi,
            Some("git+https://github.com/NREL/r2x-reeds.git@main"),
            false,
        );

        let Ok((package_spec, editable)) = manifest_install_spec(&package) else {
            unreachable!("git install spec should resolve");
        };

        assert_eq!(
            package_spec,
            "git+https://github.com/NREL/r2x-reeds.git@main"
        );
        assert!(!editable);
    }

    #[test]
    fn manifest_reinstall_rejects_missing_required_source_uri() {
        let package = package_with_source(PackageSource::Local, None, true);

        let error = match manifest_install_spec(&package) {
            Err(error) => error,
            Ok(_) => unreachable!("editable local package without source URI should fail"),
        };

        assert!(error
            .to_string()
            .contains("requires its original source URI"));
    }
}