File: perl.rs

package info (click to toggle)
rust-ognibuild 0.2.7-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,616 kB
  • sloc: makefile: 17
file content (622 lines) | stat: -rw-r--r-- 19,673 bytes parent folder | download | duplicates (2)
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
//! Support for Perl dependencies.
//!
//! This module provides functionality for working with Perl dependencies,
//! including Perl modules, pre-declared dependencies, and file dependencies.

use crate::dependency::Dependency;
use crate::installer::{Error, Explanation, InstallationScope, Installer};
use crate::session::Session;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
/// A dependency on a Perl module.
///
/// This represents a dependency on a Perl module that needs to be installed
/// for the code to function properly.
pub struct PerlModuleDependency {
    /// The name of the Perl module.
    pub module: String,
    /// The optional filename that contains the module.
    pub filename: Option<String>,
    /// Optional include paths for finding the module.
    pub inc: Option<Vec<String>>,
}

impl PerlModuleDependency {
    /// Create a new Perl module dependency with filename and include paths.
    ///
    /// # Arguments
    /// * `module` - The name of the Perl module
    /// * `filename` - Optional filename that contains the module
    /// * `inc` - Optional include paths for finding the module
    ///
    /// # Returns
    /// A new PerlModuleDependency
    pub fn new(module: &str, filename: Option<&str>, inc: Option<Vec<&str>>) -> Self {
        Self {
            module: module.to_string(),
            filename: filename.map(|s| s.to_string()),
            inc: inc.map(|v| v.iter().map(|s| s.to_string()).collect()),
        }
    }

    /// Create a simple Perl module dependency with just a module name.
    ///
    /// # Arguments
    /// * `module` - The name of the Perl module
    ///
    /// # Returns
    /// A new PerlModuleDependency with no filename or include paths
    pub fn simple(module: &str) -> Self {
        Self {
            module: module.to_string(),
            filename: None,
            inc: None,
        }
    }
}

impl Dependency for PerlModuleDependency {
    fn family(&self) -> &'static str {
        "perl-module"
    }

    fn present(&self, session: &dyn Session) -> bool {
        let mut cmd = vec!["perl".to_string(), "-M".to_string(), self.module.clone()];
        if let Some(filename) = &self.filename {
            cmd.push(filename.to_string());
        }
        if let Some(inc) = &self.inc {
            cmd.push("-I".to_string());
            cmd.push(inc.join(":"));
        }
        cmd.push("-e".to_string());
        cmd.push("1".to_string());
        session
            .command(cmd.iter().map(|s| s.as_str()).collect())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .run()
            .unwrap()
            .success()
    }

    fn project_present(&self, _session: &dyn Session) -> bool {
        todo!()
    }
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

#[cfg(feature = "upstream")]
impl crate::upstream::FindUpstream for PerlModuleDependency {
    fn find_upstream(&self) -> Option<crate::upstream::UpstreamMetadata> {
        let rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(upstream_ontologist::providers::perl::remote_cpan_data(
            &self.module,
        ))
        .ok()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// A dependency on a predeclared Perl module.
///
/// This represents a dependency on a Perl module that is known by name but
/// may map to a different actual module name.
pub struct PerlPreDeclaredDependency {
    name: String,
}

/// Map a predeclared module name to an actual module name.
///
/// # Arguments
/// * `name` - The predeclared module name
///
/// # Returns
/// The actual module name if known
fn known_predeclared_module(name: &str) -> Option<&str> {
    // TODO(jelmer): Can we obtain this information elsewhere?
    match name {
        "auto_set_repository" => Some("Module::Install::Repository"),
        "author_tests" => Some("Module::Install::AuthorTests"),
        "recursive_author_tests" => Some("Module::Install::AuthorTests"),
        "author_requires" => Some("Module::Install::AuthorRequires"),
        "readme_from" => Some("Module::Install::ReadmeFromPod"),
        "catalyst" => Some("Module::Install::Catalyst"),
        "githubmeta" => Some("Module::Install::GithubMeta"),
        "use_ppport" => Some("Module::Install::XSUtil"),
        "pod_from" => Some("Module::Install::PodFromEuclid"),
        "write_doap_changes" => Some("Module::Install::DOAPChangeSets"),
        "use_test_base" => Some("Module::Install::TestBase"),
        "jsonmeta" => Some("Module::Install::JSONMETA"),
        "extra_tests" => Some("Module::Install::ExtraTests"),
        "auto_set_bugtracker" => Some("Module::Install::Bugtracker"),
        _ => None,
    }
}

impl PerlPreDeclaredDependency {
    /// Create a new predeclared Perl module dependency.
    ///
    /// # Arguments
    /// * `name` - The name of the predeclared module
    ///
    /// # Returns
    /// A new PerlPreDeclaredDependency
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
        }
    }
}

impl Dependency for PerlPreDeclaredDependency {
    fn family(&self) -> &'static str {
        "perl-predeclared"
    }

    fn present(&self, session: &dyn Session) -> bool {
        if let Some(module) = known_predeclared_module(&self.name) {
            PerlModuleDependency::simple(module).present(session)
        } else {
            todo!()
        }
    }

    fn project_present(&self, _session: &dyn Session) -> bool {
        todo!()
    }
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

#[cfg(feature = "debian")]
impl crate::dependencies::debian::IntoDebianDependency for PerlPreDeclaredDependency {
    fn try_into_debian_dependency(
        &self,
        apt: &crate::debian::apt::AptManager,
    ) -> std::option::Option<std::vec::Vec<crate::dependencies::debian::DebianDependency>> {
        if let Some(module) = known_predeclared_module(&self.name) {
            PerlModuleDependency::simple(module).try_into_debian_dependency(apt)
        } else {
            None
        }
    }
}

impl crate::buildlog::ToDependency
    for buildlog_consultant::problems::common::MissingPerlPredeclared
{
    fn to_dependency(&self) -> Option<Box<dyn Dependency>> {
        match known_predeclared_module(self.0.as_str()) {
            Some(_module) => Some(Box::new(PerlModuleDependency::simple(self.0.as_str()))),
            None => {
                log::warn!("Unknown predeclared function: {}", self.0);
                None
            }
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// A dependency on a Perl file.
///
/// This represents a dependency on a specific Perl file rather than a module.
pub struct PerlFileDependency {
    filename: String,
}

impl PerlFileDependency {
    /// Create a new Perl file dependency.
    ///
    /// # Arguments
    /// * `filename` - The path to the Perl file
    ///
    /// # Returns
    /// A new PerlFileDependency
    pub fn new(filename: &str) -> Self {
        Self {
            filename: filename.to_string(),
        }
    }
}

impl Dependency for PerlFileDependency {
    fn family(&self) -> &'static str {
        "perl-file"
    }

    fn present(&self, session: &dyn Session) -> bool {
        session
            .command(vec!["perl", "-e", &format!("require '{}'", self.filename)])
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .run()
            .unwrap()
            .success()
    }

    fn project_present(&self, _session: &dyn Session) -> bool {
        false
    }
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl crate::buildlog::ToDependency for buildlog_consultant::problems::common::MissingPerlFile {
    fn to_dependency(&self) -> Option<Box<dyn Dependency>> {
        Some(Box::new(PerlFileDependency {
            filename: self.filename.clone(),
        }))
    }
}

/// A resolver for Perl module dependencies using CPAN.
///
/// This resolver installs Perl modules from CPAN using the cpan command.
pub struct CPAN<'a> {
    session: &'a dyn Session,
    skip_tests: bool,
}

impl<'a> CPAN<'a> {
    /// Create a new CPAN resolver.
    ///
    /// # Arguments
    /// * `session` - The session to use for executing commands
    /// * `skip_tests` - Whether to skip tests when installing modules
    ///
    /// # Returns
    /// A new CPAN resolver
    pub fn new(session: &'a dyn Session, skip_tests: bool) -> Self {
        Self {
            session,
            skip_tests,
        }
    }

    fn cmd(
        &self,
        reqs: &[&PerlModuleDependency],
        _scope: InstallationScope,
    ) -> Result<Vec<String>, Error> {
        let mut ret = vec!["cpan".to_string(), "-i".to_string()];
        if self.skip_tests {
            ret.push("-T".to_string());
        }
        ret.extend(reqs.iter().map(|req| req.module.clone()));
        Ok(ret)
    }
}

impl<'a> Installer for CPAN<'a> {
    fn explain(
        &self,
        dep: &dyn Dependency,
        scope: InstallationScope,
    ) -> Result<Explanation, Error> {
        if let Some(dep) = dep.as_any().downcast_ref::<PerlModuleDependency>() {
            let cmd = self.cmd(&[dep], scope)?;
            let explanation = Explanation {
                message: "Install the following Perl modules".to_string(),
                command: Some(cmd),
            };
            Ok(explanation)
        } else {
            Err(Error::UnknownDependencyFamily)
        }
    }

    fn install(&self, dep: &dyn Dependency, scope: InstallationScope) -> Result<(), Error> {
        let env = maplit::hashmap! {
            "PERL_MM_USE_DEFAULT".to_string() => "1".to_string(),
            "PERL_MM_OPT".to_string() => "".to_string(),
            "PERL_MB_OPT".to_string() => "".to_string(),
        };

        let user = match scope {
            InstallationScope::User => None,
            InstallationScope::Global => Some("root"),
            InstallationScope::Vendor => {
                return Err(Error::UnsupportedScope(scope));
            }
        };

        let dep = dep
            .as_any()
            .downcast_ref::<PerlModuleDependency>()
            .ok_or(Error::UnknownDependencyFamily)?;
        let cmd = self.cmd(&[dep], scope)?;
        log::info!("CPAN: running {:?}", cmd);

        let mut cmd = self
            .session
            .command(cmd.iter().map(|s| s.as_str()).collect())
            .env(env);

        if let Some(user) = user {
            cmd = cmd.user(user);
        }

        cmd.run_detecting_problems()?;

        Ok(())
    }

    fn explain_some(
        &self,
        deps: Vec<Box<dyn Dependency>>,
        scope: InstallationScope,
    ) -> Result<(Vec<Explanation>, Vec<Box<dyn Dependency>>), Error> {
        let mut explanations = Vec::new();
        let mut failed = Vec::new();
        for dep in deps {
            match self.explain(&*dep, scope) {
                Ok(explanation) => explanations.push(explanation),
                Err(Error::UnknownDependencyFamily) => failed.push(dep),
                Err(e) => {
                    return Err(e);
                }
            }
        }
        Ok((explanations, failed))
    }

    fn install_some(
        &self,
        deps: Vec<Box<dyn Dependency>>,
        scope: InstallationScope,
    ) -> Result<(Vec<Box<dyn Dependency>>, Vec<Box<dyn Dependency>>), Error> {
        let mut installed = Vec::new();
        let mut failed = Vec::new();

        for dep in deps {
            match self.install(&*dep, scope) {
                Ok(()) => installed.push(dep),
                Err(Error::UnknownDependencyFamily) => failed.push(dep),
                Err(e) => {
                    return Err(e);
                }
            }
        }
        Ok((installed, failed))
    }
}

/// Default paths where Perl modules can be installed.
pub const DEFAULT_PERL_PATHS: &[&str] = &[
    "/usr/share/perl5",
    "/usr/lib/.*/perl5/.*",
    "/usr/lib/.*/perl-base",
    "/usr/lib/.*/perl/[^/]+",
    "/usr/share/perl/[^/]+",
];

#[cfg(feature = "debian")]
impl crate::dependencies::debian::IntoDebianDependency for PerlModuleDependency {
    fn try_into_debian_dependency(
        &self,
        apt: &crate::debian::apt::AptManager,
    ) -> std::option::Option<std::vec::Vec<crate::dependencies::debian::DebianDependency>> {
        use std::path::Path;

        let (regex, paths) = if let (Some(inc), Some(filename)) =
            (self.inc.as_ref(), self.filename.as_ref())
        {
            (
                false,
                inc.iter().map(|s| Path::new(s).join(filename)).collect(),
            )
        } else if let Some(filename) = &self.filename {
            if !Path::new(filename).is_absolute() {
                (
                    true,
                    DEFAULT_PERL_PATHS
                        .iter()
                        .map(|s| Path::new(s).join(filename))
                        .collect(),
                )
            } else {
                (false, vec![Path::new(filename).to_path_buf()])
            }
        } else {
            (
                true,
                DEFAULT_PERL_PATHS
                    .iter()
                    .map(|s| Path::new(s).join(format!("{}.pm", &self.module.replace("::", "/"))))
                    .collect(),
            )
        };

        let packages = apt
            .get_packages_for_paths(
                paths
                    .iter()
                    .map(|s| s.to_str().unwrap())
                    .collect::<Vec<_>>(),
                regex,
                false,
            )
            .unwrap();

        Some(
            packages
                .into_iter()
                .map(|p| crate::dependencies::debian::DebianDependency::simple(&p))
                .collect(),
        )
    }
}

#[cfg(feature = "debian")]
impl crate::dependencies::debian::IntoDebianDependency for PerlFileDependency {
    fn try_into_debian_dependency(
        &self,
        apt: &crate::debian::apt::AptManager,
    ) -> std::option::Option<std::vec::Vec<crate::dependencies::debian::DebianDependency>> {
        let packages = apt
            .get_packages_for_paths(vec![&self.filename], false, false)
            .unwrap();

        Some(
            packages
                .into_iter()
                .map(|p| crate::dependencies::debian::DebianDependency::simple(&p))
                .collect(),
        )
    }
}

impl crate::buildlog::ToDependency for buildlog_consultant::problems::common::MissingPerlModule {
    fn to_dependency(&self) -> Option<Box<dyn Dependency>> {
        Some(Box::new(PerlModuleDependency {
            module: self.module.clone(),
            filename: self.filename.clone(),
            inc: self.inc.clone(),
        }))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::buildlog::ToDependency;

    #[test]
    fn test_perl_module_dependency_new() {
        let dependency = PerlModuleDependency::new(
            "Test::More",
            Some("Test/More.pm"),
            Some(vec!["/usr/share/perl5"]),
        );
        assert_eq!(dependency.module, "Test::More");
        assert_eq!(dependency.filename, Some("Test/More.pm".to_string()));
        assert_eq!(dependency.inc, Some(vec!["/usr/share/perl5".to_string()]));
    }

    #[test]
    fn test_perl_module_dependency_simple() {
        let dependency = PerlModuleDependency::simple("Test::More");
        assert_eq!(dependency.module, "Test::More");
        assert_eq!(dependency.filename, None);
        assert_eq!(dependency.inc, None);
    }

    #[test]
    fn test_perl_module_dependency_family() {
        let dependency = PerlModuleDependency::simple("Test::More");
        assert_eq!(dependency.family(), "perl-module");
    }

    #[test]
    fn test_perl_module_dependency_as_any() {
        let dependency = PerlModuleDependency::simple("Test::More");
        let any_dep = dependency.as_any();
        assert!(any_dep.downcast_ref::<PerlModuleDependency>().is_some());
    }

    #[test]
    fn test_missing_perl_module_to_dependency() {
        let problem = buildlog_consultant::problems::common::MissingPerlModule {
            module: "Test::More".to_string(),
            filename: Some("Test/More.pm".to_string()),
            inc: None,
            minimum_version: None,
        };
        let dependency = problem.to_dependency();
        assert!(dependency.is_some());
        let dep = dependency.unwrap();
        assert_eq!(dep.family(), "perl-module");
        let perl_dep = dep.as_any().downcast_ref::<PerlModuleDependency>().unwrap();
        assert_eq!(perl_dep.module, "Test::More");
        assert_eq!(perl_dep.filename, Some("Test/More.pm".to_string()));
    }

    #[test]
    fn test_perl_predeclared_dependency_new() {
        let dependency = PerlPreDeclaredDependency::new("auto_set_repository");
        assert_eq!(dependency.name, "auto_set_repository");
    }

    #[test]
    fn test_perl_predeclared_dependency_family() {
        let dependency = PerlPreDeclaredDependency::new("auto_set_repository");
        assert_eq!(dependency.family(), "perl-predeclared");
    }

    #[test]
    fn test_perl_predeclared_dependency_as_any() {
        let dependency = PerlPreDeclaredDependency::new("auto_set_repository");
        let any_dep = dependency.as_any();
        assert!(any_dep
            .downcast_ref::<PerlPreDeclaredDependency>()
            .is_some());
    }

    #[test]
    fn test_known_predeclared_module() {
        assert_eq!(
            known_predeclared_module("auto_set_repository"),
            Some("Module::Install::Repository")
        );
        assert_eq!(
            known_predeclared_module("author_tests"),
            Some("Module::Install::AuthorTests")
        );
        assert_eq!(known_predeclared_module("unknown_function"), None);
    }

    #[test]
    fn test_perl_file_dependency_new() {
        let dependency = PerlFileDependency::new("Test/More.pm");
        assert_eq!(dependency.filename, "Test/More.pm");
    }

    #[test]
    fn test_perl_file_dependency_family() {
        let dependency = PerlFileDependency::new("Test/More.pm");
        assert_eq!(dependency.family(), "perl-file");
    }

    #[test]
    fn test_perl_file_dependency_as_any() {
        let dependency = PerlFileDependency::new("Test/More.pm");
        let any_dep = dependency.as_any();
        assert!(any_dep.downcast_ref::<PerlFileDependency>().is_some());
    }

    #[test]
    fn test_missing_perl_file_to_dependency() {
        let problem = buildlog_consultant::problems::common::MissingPerlFile {
            filename: "Test/More.pm".to_string(),
            inc: None,
        };
        let dependency = problem.to_dependency();
        assert!(dependency.is_some());
        let dep = dependency.unwrap();
        assert_eq!(dep.family(), "perl-file");
        let perl_file_dep = dep.as_any().downcast_ref::<PerlFileDependency>().unwrap();
        assert_eq!(perl_file_dep.filename, "Test/More.pm");
    }

    #[test]
    fn test_cpan_new() {
        let session = crate::session::plain::PlainSession::new();
        let cpan = CPAN::new(&session, true);
        assert!(cpan.skip_tests);
    }

    #[test]
    fn test_cpan_cmd() {
        let session = crate::session::plain::PlainSession::new();
        let cpan = CPAN::new(&session, true);
        let dependency = PerlModuleDependency::simple("Test::More");
        let cmd = cpan.cmd(&[&dependency], InstallationScope::User).unwrap();
        assert_eq!(cmd, vec!["cpan", "-i", "-T", "Test::More"]);
    }
}