ognibuild 0.2.11

Detect and run any build system
Documentation
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
use crate::dependencies::BinaryDependency;
use crate::dependency::Dependency;
use crate::installer::{
    install_missing_deps, Error as InstallerError, InstallationScope, Installer,
};
use crate::output::Output;
use crate::session::{which, Session};
use std::path::{Path, PathBuf};

/// The category of a dependency
#[derive(Debug, Clone, PartialEq, Eq, std::hash::Hash)]
pub enum DependencyCategory {
    /// A dependency that is required for the package to build and run
    Universal,
    /// Building of artefacts
    Build,
    /// For running artefacts after build or install
    Runtime,
    /// Test infrastructure, e.g. test frameworks or test runners
    Test,
    /// Needed for development, e.g. linters or IDE plugins
    Dev,
    /// Extra build dependencies, e.g. for optional features
    BuildExtra(String),
    /// Extra dependencies, e.g. for optional features
    RuntimeExtra(String),
}

impl std::fmt::Display for DependencyCategory {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            DependencyCategory::Universal => write!(f, "universal"),
            DependencyCategory::Build => write!(f, "build"),
            DependencyCategory::Runtime => write!(f, "runtime"),
            DependencyCategory::Test => write!(f, "test"),
            DependencyCategory::Dev => write!(f, "dev"),
            DependencyCategory::BuildExtra(s) => write!(f, "build-extra:{}", s),
            DependencyCategory::RuntimeExtra(s) => write!(f, "runtime-extra:{}", s),
        }
    }
}

#[derive(Debug)]
/// Error types for build system operations.
///
/// These represent different kinds of errors that can occur when working with build systems.
pub enum Error {
    /// The build system could not be detected.
    NoBuildSystemDetected,

    /// Error occurred while installing dependencies.
    DependencyInstallError(InstallerError),

    /// Error detected and analyzed from build output.
    Error(crate::analyze::AnalyzedError),

    /// Error from an IO operation.
    IoError(std::io::Error),

    /// The requested operation is not implemented by this build system.
    Unimplemented,

    /// Generic error with a message.
    Other(String),
}

impl From<InstallerError> for Error {
    fn from(e: InstallerError) -> Self {
        Error::DependencyInstallError(e)
    }
}

impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Self {
        Error::IoError(e)
    }
}

impl From<crate::analyze::AnalyzedError> for Error {
    fn from(e: crate::analyze::AnalyzedError) -> Self {
        Error::Error(e)
    }
}

impl From<crate::session::Error> for Error {
    fn from(e: crate::session::Error) -> Self {
        match e {
            crate::session::Error::CalledProcessError(e) => {
                crate::analyze::AnalyzedError::Unidentified {
                    retcode: e.code().unwrap(),
                    lines: Vec::new(),
                    secondary: None,
                }
                .into()
            }
            crate::session::Error::IoError(e) => e.into(),
            crate::session::Error::SetupFailure(_, _) => unreachable!(),
            crate::session::Error::ImageError(_) => unreachable!(),
        }
    }
}

impl From<crate::fix_build::IterateBuildError<InstallerError>> for Error {
    fn from(e: crate::fix_build::IterateBuildError<InstallerError>) -> Self {
        match e {
            crate::fix_build::IterateBuildError::FixerLimitReached(n) => {
                Error::Other(format!("Fixer limit reached: {}", n))
            }
            crate::fix_build::IterateBuildError::Persistent(e) => {
                crate::analyze::AnalyzedError::Detailed {
                    error: e,
                    retcode: 1,
                }
                .into()
            }
            crate::fix_build::IterateBuildError::Unidentified {
                retcode,
                lines,
                secondary,
            } => crate::analyze::AnalyzedError::Unidentified {
                retcode,
                lines,
                secondary,
            }
            .into(),
            crate::fix_build::IterateBuildError::Other(o) => o.into(),
        }
    }
}

impl From<crate::fix_build::IterateBuildError<Error>> for Error {
    fn from(e: crate::fix_build::IterateBuildError<Error>) -> Self {
        match e {
            crate::fix_build::IterateBuildError::FixerLimitReached(n) => {
                Error::Other(format!("Fixer limit reached: {}", n))
            }
            crate::fix_build::IterateBuildError::Persistent(e) => {
                crate::analyze::AnalyzedError::Detailed {
                    error: e,
                    retcode: 1,
                }
                .into()
            }
            crate::fix_build::IterateBuildError::Unidentified {
                retcode,
                lines,
                secondary,
            } => crate::analyze::AnalyzedError::Unidentified {
                retcode,
                lines,
                secondary,
            }
            .into(),
            crate::fix_build::IterateBuildError::Other(o) => o,
        }
    }
}

impl From<Error> for crate::fix_build::InterimError<Error> {
    fn from(e: Error) -> Self {
        match e {
            Error::Error(crate::analyze::AnalyzedError::Detailed { error, retcode: _ }) => {
                crate::fix_build::InterimError::Recognized(error)
            }
            e => crate::fix_build::InterimError::Other(e),
        }
    }
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Error::NoBuildSystemDetected => write!(f, "No build system detected"),
            Error::DependencyInstallError(e) => write!(f, "Error installing dependency: {}", e),
            Error::Error(e) => write!(f, "Error: {}", e),
            Error::IoError(e) => write!(f, "IO Error: {}", e),
            Error::Other(e) => write!(f, "Error: {}", e),
            Error::Unimplemented => write!(f, "Unimplemented"),
        }
    }
}

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

#[derive(Debug, Clone)]
/// Target configuration for installation.
///
/// Defines where and how packages should be installed.
pub struct InstallTarget {
    /// The scope of installation (e.g., global or user).
    pub scope: InstallationScope,

    /// Optional installation prefix directory.
    pub prefix: Option<PathBuf>,
}

impl DependencyCategory {
    /// Get all standard dependency categories.
    ///
    /// Returns an array containing all standard dependency categories.
    pub fn all() -> [DependencyCategory; 5] {
        [
            DependencyCategory::Universal,
            DependencyCategory::Build,
            DependencyCategory::Runtime,
            DependencyCategory::Test,
            DependencyCategory::Dev,
        ]
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Standard build system actions.
///
/// These represent the common actions that can be performed by build systems.
pub enum Action {
    /// Clean the build environment.
    Clean,
    /// Build the project.
    Build,
    /// Run the project's tests.
    Test,
    /// Install the project.
    Install,
}

/// Determine the path to a binary, installing it if necessary
pub fn guaranteed_which(
    session: &dyn Session,
    installer: &dyn Installer,
    name: &str,
) -> Result<PathBuf, InstallerError> {
    match which(session, name) {
        Some(path) => Ok(PathBuf::from(path)),
        None => {
            installer.install(&BinaryDependency::new(name), InstallationScope::Global)?;
            Ok(PathBuf::from(which(session, name).unwrap()))
        }
    }
}

/// A particular buildsystem.
pub trait BuildSystem: std::fmt::Debug {
    /// The name of the buildsystem.
    fn name(&self) -> &str;

    /// Create a distribution package for the project.
    ///
    /// # Arguments
    /// * `session` - The session to run commands in
    /// * `installer` - Installer to use for installing dependencies
    /// * `target_directory` - Directory where the distribution package should be created
    /// * `quiet` - Whether to suppress output
    ///
    /// # Returns
    /// * The filename of the created distribution package on success
    /// * Error if the distribution creation fails
    fn dist(
        &self,
        session: &dyn Session,
        installer: &dyn Installer,
        target_directory: &Path,
        quiet: bool,
    ) -> Result<std::ffi::OsString, Error>;

    /// Install the dependencies declared by the build system.
    ///
    /// # Arguments
    /// * `categories` - The categories of dependencies to install
    /// * `scopes` - The scopes in which to install the dependencies
    /// * `session` - The session to run commands in
    /// * `installer` - Installer to use for installing dependencies
    /// * `fixers` - Optional list of fixers to use if getting dependency information fails
    ///
    /// # Returns
    /// * `Ok(())` if the dependencies were installed successfully
    /// * Error if installation fails
    fn install_declared_dependencies(
        &self,
        categories: &[DependencyCategory],
        scopes: &[InstallationScope],
        session: &dyn Session,
        installer: &dyn Installer,
        fixers: Option<&[&dyn crate::fix_build::BuildFixer<InstallerError>]>,
    ) -> Result<(), Error> {
        let declared_deps = self.get_declared_dependencies(session, fixers)?;
        let relevant: Vec<_> = declared_deps
            .into_iter()
            .filter(|(c, _d)| categories.contains(c))
            .map(|(_, d)| d)
            .collect();
        log::debug!("Declared dependencies: {:?}", relevant);
        let dep_refs: Vec<&dyn Dependency> = relevant.iter().map(|d| d.as_ref()).collect();
        install_missing_deps(session, installer, scopes, &dep_refs)?;
        Ok(())
    }

    /// Run tests for the project.
    ///
    /// # Arguments
    /// * `session` - The session to run commands in
    /// * `installer` - Installer to use for installing dependencies
    ///
    /// # Returns
    /// * `Ok(())` if the tests pass
    /// * Error if the tests fail
    fn test(&self, session: &dyn Session, installer: &dyn Installer) -> Result<(), Error>;

    /// Build the project.
    ///
    /// # Arguments
    /// * `session` - The session to run commands in
    /// * `installer` - Installer to use for installing dependencies
    ///
    /// # Returns
    /// * `Ok(())` if the build succeeds
    /// * Error if the build fails
    fn build(&self, session: &dyn Session, installer: &dyn Installer) -> Result<(), Error>;

    /// Clean the project's build artifacts.
    ///
    /// # Arguments
    /// * `session` - The session to run commands in
    /// * `installer` - Installer to use for installing dependencies
    ///
    /// # Returns
    /// * `Ok(())` if the clean succeeds
    /// * Error if the clean fails
    fn clean(&self, session: &dyn Session, installer: &dyn Installer) -> Result<(), Error>;

    /// Install the project.
    ///
    /// # Arguments
    /// * `session` - The session to run commands in
    /// * `installer` - Installer to use for installing dependencies
    /// * `install_target` - Target configuration for the installation
    ///
    /// # Returns
    /// * `Ok(())` if the installation succeeds
    /// * Error if the installation fails
    fn install(
        &self,
        session: &dyn Session,
        installer: &dyn Installer,
        install_target: &InstallTarget,
    ) -> Result<(), Error>;

    /// Get the dependencies declared by the build system.
    ///
    /// # Arguments
    /// * `session` - The session to run commands in
    /// * `fixers` - Optional list of fixers to use if getting dependency information fails
    ///
    /// # Returns
    /// * List of dependencies with their categories
    /// * Error if getting dependency information fails
    fn get_declared_dependencies(
        &self,
        session: &dyn Session,
        fixers: Option<&[&dyn crate::fix_build::BuildFixer<InstallerError>]>,
    ) -> Result<Vec<(DependencyCategory, Box<dyn Dependency>)>, Error>;

    /// Get the outputs declared by the build system.
    ///
    /// # Arguments
    /// * `session` - The session to run commands in
    /// * `fixers` - Optional list of fixers to use if getting output information fails
    ///
    /// # Returns
    /// * List of declared outputs
    /// * Error if getting output information fails
    fn get_declared_outputs(
        &self,
        session: &dyn Session,
        fixers: Option<&[&dyn crate::fix_build::BuildFixer<InstallerError>]>,
    ) -> Result<Vec<Box<dyn Output>>, Error>;

    /// Convert this build system to Any for dynamic casting.
    ///
    /// This method allows for conversion of the build system to concrete types at runtime.
    ///
    /// # Returns
    /// A reference to this build system as Any
    fn as_any(&self) -> &dyn std::any::Any;
}

/// A single buildsystem registry entry.
struct BuildSystemEntry {
    /// The name of the buildsystem
    name: &'static str,
    /// Function to probe for this buildsystem
    probe: fn(&Path) -> Option<Box<dyn BuildSystem>>,
}

/// Registry of all supported buildsystems in detection order.
const BUILDSYSTEM_REGISTRY: &[BuildSystemEntry] = &[
    BuildSystemEntry {
        name: "pear",
        probe: Pear::probe,
    },
    BuildSystemEntry {
        name: "setup.py",
        probe: crate::buildsystems::python::SetupPy::probe,
    },
    BuildSystemEntry {
        name: "node",
        probe: crate::buildsystems::node::Node::probe,
    },
    BuildSystemEntry {
        name: "waf",
        probe: crate::buildsystems::waf::Waf::probe,
    },
    BuildSystemEntry {
        name: "gem",
        probe: crate::buildsystems::ruby::Gem::probe,
    },
    BuildSystemEntry {
        name: "meson",
        probe: crate::buildsystems::meson::Meson::probe,
    },
    BuildSystemEntry {
        name: "cargo",
        probe: crate::buildsystems::rust::Cargo::probe,
    },
    BuildSystemEntry {
        name: "cabal",
        probe: crate::buildsystems::haskell::Cabal::probe,
    },
    BuildSystemEntry {
        name: "gradle",
        probe: crate::buildsystems::java::Gradle::probe,
    },
    BuildSystemEntry {
        name: "maven",
        probe: crate::buildsystems::java::Maven::probe,
    },
    BuildSystemEntry {
        name: "distzilla",
        probe: crate::buildsystems::perl::DistZilla::probe,
    },
    BuildSystemEntry {
        name: "perl-build-tiny",
        probe: crate::buildsystems::perl::PerlBuildTiny::probe,
    },
    BuildSystemEntry {
        name: "go",
        probe: crate::buildsystems::go::Golang::probe,
    },
    BuildSystemEntry {
        name: "bazel",
        probe: crate::buildsystems::bazel::Bazel::probe,
    },
    BuildSystemEntry {
        name: "r",
        probe: crate::buildsystems::r::R::probe,
    },
    BuildSystemEntry {
        name: "octave",
        probe: crate::buildsystems::octave::Octave::probe,
    },
    BuildSystemEntry {
        name: "cmake",
        probe: crate::buildsystems::make::CMake::probe,
    },
    BuildSystemEntry {
        name: "gnome-shell-extension",
        probe: crate::buildsystems::gnome::GnomeShellExtension::probe,
    },
    // Make is intentionally at the end of the list.
    BuildSystemEntry {
        name: "make",
        probe: crate::buildsystems::make::Make::probe,
    },
    BuildSystemEntry {
        name: "composer",
        probe: Composer::probe,
    },
    BuildSystemEntry {
        name: "runtests",
        probe: RunTests::probe,
    },
];

/// XML namespaces used by PEAR package definitions.
pub const PEAR_NAMESPACES: &[&str] = &[
    "http://pear.php.net/dtd/package-2.0",
    "http://pear.php.net/dtd/package-2.1",
];

#[derive(Debug)]
/// PEAR (PHP Extension and Application Repository) build system.
pub struct Pear(pub PathBuf);

impl Pear {
    /// Create a new PEAR build system.
    ///
    /// # Arguments
    /// * `path` - Path to the PEAR package.xml file
    ///
    /// # Returns
    /// A new PEAR build system instance
    pub fn new(path: PathBuf) -> Self {
        Self(path)
    }

    /// Detect if a directory contains a PEAR project.
    ///
    /// # Arguments
    /// * `path` - Directory to probe
    ///
    /// # Returns
    /// * `Some(Box<dyn BuildSystem>)` if a PEAR project is detected
    /// * `None` if no PEAR project is detected
    pub fn probe(path: &Path) -> Option<Box<dyn BuildSystem>> {
        let package_xml_path = path.join("package.xml");
        if !package_xml_path.exists() {
            return None;
        }

        use xmltree::Element;

        let root = Element::parse(std::fs::File::open(package_xml_path).unwrap()).unwrap();

        // Check that the root tag is <package> and that the namespace is one of the known PEAR
        // namespaces.

        if root
            .namespace
            .as_deref()
            .and_then(|ns| PEAR_NAMESPACES.iter().find(|&n| *n == ns))
            .is_none()
        {
            log::warn!(
                "Namespace of package.xml is not recognized as a PEAR package: {:?}",
                root.namespace
            );
            return None;
        }

        if root.name != "package" {
            log::warn!("Root tag of package.xml is not <package>: {:?}", root.name);
            return None;
        }

        log::debug!(
            "Found package.xml with namespace {}, assuming pear package.",
            root.namespace.as_ref().unwrap()
        );

        Some(Box::new(Self(PathBuf::from(path))))
    }
}

impl BuildSystem for Pear {
    fn name(&self) -> &str {
        "pear"
    }

    fn dist(
        &self,
        session: &dyn Session,
        installer: &dyn Installer,
        target_directory: &Path,
        quiet: bool,
    ) -> Result<std::ffi::OsString, Error> {
        let dc = crate::dist_catcher::DistCatcher::new(vec![session.external_path(Path::new("."))]);
        let pear = guaranteed_which(session, installer, "pear")?;
        session
            .command(vec![pear.to_str().unwrap(), "package"])
            .quiet(quiet)
            .run_detecting_problems()?;
        Ok(dc.copy_single(target_directory).unwrap().unwrap())
    }

    fn test(&self, session: &dyn Session, installer: &dyn Installer) -> Result<(), Error> {
        let pear = guaranteed_which(session, installer, "pear")?;
        session
            .command(vec![pear.to_str().unwrap(), "run-tests"])
            .run_detecting_problems()?;
        Ok(())
    }

    fn build(&self, session: &dyn Session, installer: &dyn Installer) -> Result<(), Error> {
        let pear = guaranteed_which(session, installer, "pear")?;
        session
            .command(vec![
                pear.to_str().unwrap(),
                "build",
                self.0.to_str().unwrap(),
            ])
            .run_detecting_problems()?;
        Ok(())
    }

    fn clean(&self, _session: &dyn Session, _installer: &dyn Installer) -> Result<(), Error> {
        todo!()
    }

    fn install(
        &self,
        session: &dyn Session,
        installer: &dyn Installer,
        _install_target: &InstallTarget,
    ) -> Result<(), Error> {
        let pear = guaranteed_which(session, installer, "pear")?;
        session
            .command(vec![
                pear.to_str().unwrap(),
                "install",
                self.0.to_str().unwrap(),
            ])
            .run_detecting_problems()?;
        Ok(())
    }

    fn get_declared_dependencies(
        &self,
        _session: &dyn Session,
        _fixers: Option<&[&dyn crate::fix_build::BuildFixer<InstallerError>]>,
    ) -> Result<Vec<(DependencyCategory, Box<dyn Dependency>)>, Error> {
        let path = self.0.join("package.xml");
        use xmltree::Element;
        let root = Element::parse(std::fs::File::open(path).unwrap()).unwrap();

        // Check that the root tag is <package> and that the namespace is one of the known PEAR
        // namespaces.

        if root
            .namespace
            .as_deref()
            .and_then(|ns| PEAR_NAMESPACES.iter().find(|&n| *n == ns))
            .is_none()
        {
            log::warn!(
                "Namespace of package.xml is not recognized as a PEAR package: {:?}",
                root.namespace
            );
            return Ok(vec![]);
        }

        if root.name != "package" {
            log::warn!("Root tag of package.xml is not <package>: {:?}", root.name);
            return Ok(vec![]);
        }

        let dependencies_tag = root
            .get_child("dependencies")
            .ok_or_else(|| Error::Other("No <dependencies> tag found in <package>".to_owned()))?;

        let required_tag = dependencies_tag
            .get_child("required")
            .ok_or_else(|| Error::Other("No <required> tag found in <dependencies>".to_owned()))?;

        Ok(required_tag
            .children
            .iter()
            .filter_map(|x| x.as_element())
            .filter(|c| c.name.as_str() == "package")
            .filter_map(
                |package_tag| -> Option<(DependencyCategory, Box<dyn Dependency>)> {
                    let name = package_tag
                        .get_child("name")
                        .and_then(|n| n.get_text())
                        .unwrap()
                        .into_owned();
                    let min_version = package_tag
                        .get_child("min")
                        .and_then(|m| m.get_text())
                        .map(|s| s.into_owned());
                    let max_version = package_tag
                        .get_child("max")
                        .and_then(|m| m.get_text())
                        .map(|s| s.into_owned());
                    let channel = package_tag
                        .get_child("channel")
                        .and_then(|c| c.get_text())
                        .map(|s| s.into_owned());

                    Some((
                        DependencyCategory::Universal,
                        Box::new(crate::dependencies::php::PhpPackageDependency {
                            package: name,
                            channel,
                            min_version,
                            max_version,
                        }) as Box<dyn Dependency>,
                    ))
                },
            )
            .collect())
    }

    fn get_declared_outputs(
        &self,
        _session: &dyn Session,
        _fixers: Option<&[&dyn crate::fix_build::BuildFixer<InstallerError>]>,
    ) -> Result<Vec<Box<dyn Output>>, Error> {
        todo!()
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// Detect build systems.
pub fn scan_buildsystems(path: &Path) -> Vec<(PathBuf, Box<dyn BuildSystem>)> {
    let mut ret = vec![];
    ret.extend(
        detect_buildsystems(path)
            .into_iter()
            .map(|bs| (PathBuf::from(path), bs)),
    );

    if ret.is_empty() {
        // Nothing found. Try the next level?
        for entry in std::fs::read_dir(path).unwrap() {
            let entry = entry.unwrap();
            if entry.file_type().unwrap().is_dir() {
                ret.extend(
                    detect_buildsystems(&entry.path())
                        .into_iter()
                        .map(|bs| (entry.path(), bs)),
                );
            }
        }
    }

    ret
}

#[derive(Debug)]
/// PHP Composer build system.
pub struct Composer(pub PathBuf);

impl Composer {
    /// Create a new Composer build system instance.
    ///
    /// # Arguments
    /// * `path` - Path to the project directory
    ///
    /// # Returns
    /// A new Composer build system instance
    pub fn new(path: PathBuf) -> Self {
        Self(path)
    }

    /// Detect if a directory contains a Composer project.
    ///
    /// # Arguments
    /// * `path` - Directory to probe
    ///
    /// # Returns
    /// * `Some(Box<dyn BuildSystem>)` if a Composer project is detected
    /// * `None` if no Composer project is detected
    pub fn probe(path: &Path) -> Option<Box<dyn BuildSystem>> {
        if path.join("composer.json").exists() {
            Some(Box::new(Self(path.into())))
        } else {
            None
        }
    }
}

impl BuildSystem for Composer {
    fn name(&self) -> &str {
        "composer"
    }

    fn dist(
        &self,
        _session: &dyn Session,
        _installer: &dyn Installer,
        _target_directory: &Path,
        _quiet: bool,
    ) -> Result<std::ffi::OsString, Error> {
        todo!()
    }

    fn test(&self, _session: &dyn Session, _installer: &dyn Installer) -> Result<(), Error> {
        todo!()
    }

    fn build(&self, _session: &dyn Session, _installer: &dyn Installer) -> Result<(), Error> {
        todo!()
    }

    fn clean(&self, _session: &dyn Session, _installer: &dyn Installer) -> Result<(), Error> {
        todo!()
    }

    fn install(
        &self,
        _session: &dyn Session,
        _installer: &dyn Installer,
        _install_target: &InstallTarget,
    ) -> Result<(), Error> {
        todo!()
    }

    fn get_declared_dependencies(
        &self,
        _session: &dyn Session,
        _fixers: Option<&[&dyn crate::fix_build::BuildFixer<InstallerError>]>,
    ) -> Result<Vec<(DependencyCategory, Box<dyn Dependency>)>, Error> {
        todo!()
    }

    fn get_declared_outputs(
        &self,
        _session: &dyn Session,
        _fixers: Option<&[&dyn crate::fix_build::BuildFixer<InstallerError>]>,
    ) -> Result<Vec<Box<dyn Output>>, Error> {
        todo!()
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

#[derive(Debug)]
/// Generic build system that just runs tests.
pub struct RunTests(pub PathBuf);

impl RunTests {
    /// Create a new RunTests build system instance.
    ///
    /// # Arguments
    /// * `path` - Path to the project directory
    ///
    /// # Returns
    /// A new RunTests build system instance
    pub fn new(path: PathBuf) -> Self {
        Self(path)
    }

    /// Detect if a directory contains a project with tests that can be run.
    ///
    /// # Arguments
    /// * `path` - Directory to probe
    ///
    /// # Returns
    /// * `Some(Box<dyn BuildSystem>)` if runnable tests are detected
    /// * `None` if no runnable tests are detected
    pub fn probe(path: &Path) -> Option<Box<dyn BuildSystem>> {
        if path.join("runtests.sh").exists() {
            Some(Box::new(Self(path.into())))
        } else {
            None
        }
    }
}

impl BuildSystem for RunTests {
    fn name(&self) -> &str {
        "runtests"
    }

    fn dist(
        &self,
        _session: &dyn Session,
        _installer: &dyn Installer,
        _target_directory: &Path,
        _quiet: bool,
    ) -> Result<std::ffi::OsString, Error> {
        todo!()
    }

    fn test(&self, session: &dyn Session, _installer: &dyn Installer) -> Result<(), Error> {
        let interpreter = crate::shebang::shebang_binary(&self.0.join("runtests.sh")).unwrap();
        let argv = if interpreter.is_some() {
            vec!["./runtests.sh"]
        } else {
            vec!["/bin/bash", "./runtests.sh"]
        };

        session.command(argv).run_detecting_problems()?;
        Ok(())
    }

    fn build(&self, _session: &dyn Session, _installer: &dyn Installer) -> Result<(), Error> {
        todo!()
    }

    fn clean(&self, _session: &dyn Session, _installer: &dyn Installer) -> Result<(), Error> {
        todo!()
    }

    fn install(
        &self,
        _session: &dyn Session,
        _installer: &dyn Installer,
        _install_target: &InstallTarget,
    ) -> Result<(), Error> {
        todo!()
    }

    fn get_declared_dependencies(
        &self,
        _session: &dyn Session,
        _fixers: Option<&[&dyn crate::fix_build::BuildFixer<InstallerError>]>,
    ) -> Result<Vec<(DependencyCategory, Box<dyn Dependency>)>, Error> {
        todo!()
    }

    fn get_declared_outputs(
        &self,
        _session: &dyn Session,
        _fixers: Option<&[&dyn crate::fix_build::BuildFixer<InstallerError>]>,
    ) -> Result<Vec<Box<dyn Output>>, Error> {
        todo!()
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// Detect all applicable build systems for a given path.
///
/// This function attempts to detect any build systems that can be used with the
/// provided project directory. Multiple build systems may be detected for a single project.
///
/// # Arguments
/// * `path` - Path to the project directory
///
/// # Returns
/// A vector of detected build systems, sorted in order of preference
pub fn detect_buildsystems(path: &std::path::Path) -> Vec<Box<dyn BuildSystem>> {
    if !path.exists() {
        log::error!("Path does not exist: {:?}", path);
        return vec![];
    }
    let path = path.canonicalize().unwrap();
    let mut ret = vec![];
    for entry in BUILDSYSTEM_REGISTRY {
        let bs = (entry.probe)(&path);
        if let Some(bs) = bs {
            ret.push(bs);
        }
    }
    ret
}

/// Get the most appropriate build system for a given path.
///
/// This function returns the first (most preferred) build system that can be used
/// with the provided project directory, along with its path.
///
/// # Arguments
/// * `path` - Path to the project directory
///
/// # Returns
/// An optional tuple containing the path to the build system file and the build system instance
pub fn get_buildsystem(path: &Path) -> Option<(PathBuf, Box<dyn BuildSystem>)> {
    scan_buildsystems(path).into_iter().next()
}

/// Get all supported build system names.
///
/// # Returns
/// A vector of all supported build system names in detection order
pub fn supported_buildsystem_names() -> Vec<&'static str> {
    BUILDSYSTEM_REGISTRY
        .iter()
        .map(|entry| entry.name)
        .collect()
}

/// Get a build system by name for a given path.
///
/// This function tries to create a specific build system by name for the provided
/// project directory.
///
/// # Arguments
/// * `name` - Name of the build system to use
/// * `path` - Path to the project directory
///
/// # Returns
/// An optional build system instance if the specified build system is applicable
pub fn buildsystem_by_name(name: &str, path: &Path) -> Option<Box<dyn BuildSystem>> {
    BUILDSYSTEM_REGISTRY
        .iter()
        .find(|entry| entry.name == name)
        .and_then(|entry| (entry.probe)(path))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::installer::NullInstaller;
    use crate::session::plain::PlainSession;

    #[test]
    fn test_guaranteed_which() {
        let session = PlainSession::new();
        let installer = NullInstaller::new();

        let _path = guaranteed_which(&session, &installer, "ls").unwrap();
    }

    #[test]
    fn test_guaranteed_which_not_found() {
        let session = PlainSession::new();
        let installer = NullInstaller::new();

        assert!(matches!(
            guaranteed_which(&session, &installer, "this-does-not-exist").unwrap_err(),
            InstallerError::UnknownDependencyFamily,
        ));
    }

    #[test]
    fn test_supported_buildsystem_names() {
        let names = supported_buildsystem_names();
        assert!(!names.is_empty());
        assert!(names.contains(&"cargo"));
        assert!(names.contains(&"make"));
        assert!(names.contains(&"meson"));
        assert_eq!(names.len(), 21);
    }
}