yamis 1.2.0

Task runner for teams and individuals.
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
use crate::debug_config::ConfigFileDebugConfig;
use crate::defaults::default_quote;
use crate::parser::EscapeMode;
use crate::tasks::Task;
use crate::types::DynErrResult;
use crate::utils::{
    get_path_relative_to_base, get_task_dependency_graph, read_env_file, to_os_task_name,
};
use indexmap::IndexMap;
use petgraph::algo::toposort;
use serde_derive::Deserialize;
use std::collections::HashMap;
use std::ffi::OsStr;
use std::fmt::{Display, Formatter};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::{env, error, fmt, fs};

pub type ConfigFileSharedPtr = Arc<Mutex<ConfigFile>>;

/// Config file names by order of priority. The first one refers to local config and
/// should not be committed to the repository. The program should discover config files
/// by looping on the parent folders and current directory until reaching the root path
/// or a the project config (last one on the list) is found.
const CONFIG_FILES_PRIO: &[&str] = &["local.yamis", "yamis", "project.yamis"];

const GLOBAL_CONFIG_FILE: &str = "user.yamis";
/// Name the global config file, without extension.

#[cfg(not(test))]
const GLOBAL_CONFIG_FILE_PATH: &str = "~/.yamis";

/// Allowed extensions for config files.
const ALLOWED_EXTENSIONS: &[&str] = &["yml", "yaml", "toml"];

/// Errors related to config files and tasks
#[derive(Debug)]
pub(crate) enum ConfigError {
    // /// Raised when a config file is not found for a given path
    // FileNotFound(String), // Given config file not found
    // /// Raised when no config file is found during auto-discovery
    // NoConfigFile, // No config file was discovered
    /// Bad Config error
    BadConfigFile(PathBuf, String),
    /// Found a config file multiple times with different extensions
    DuplicateConfigFile(String),
}

impl Display for ConfigError {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match *self {
            // ConfigError::FileNotFound(ref s) => write!(f, "File {} not found.", s),
            // ConfigError::NoConfigFile => write!(f, "No config file found."),
            ConfigError::BadConfigFile(ref path, ref reason) => write!(f, "Bad config file `{}`:\n    {}", path.to_string_lossy(), reason),
            ConfigError::DuplicateConfigFile(ref s) => write!(f,
                                                              "Config file `{}` defined multiple times with different extensions in the same directory.", s),
        }
    }
}

impl error::Error for ConfigError {}

/// Represents a config file.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ConfigFile {
    /// Version of the config file.
    #[allow(dead_code)] // to avoid lint errors
    #[serde(default, skip_serializing)]
    version: serde::de::IgnoredAny,
    /// Path of the file.
    #[serde(skip)]
    pub(crate) filepath: PathBuf,

    /// Debug options
    #[serde(default)]
    pub(crate) debug_config: ConfigFileDebugConfig,

    #[serde(default)]
    /// Working directory. Defaults to the folder where the script runs.
    wd: Option<String>,
    /// Whether to automatically quote argument with spaces unless task specified
    #[serde(default = "default_quote")]
    pub(crate) quote: EscapeMode,
    /// Tasks inside the config file.
    #[serde(default)]
    pub(crate) tasks: HashMap<String, Task>,
    /// Env variables for all the tasks.
    pub(crate) env: Option<HashMap<String, String>>,
    /// Env file to read environment variables from
    pub(crate) env_file: Option<String>,
    #[serde(skip)]
    pub(crate) loaded_tasks: HashMap<String, Arc<Task>>,
}

/// Iterates over existing config file paths, in order of priority.
pub struct ConfigFilePaths {
    /// Index of value to use from `CONFIG_FILES_PRIO`
    index: usize,
    /// Whether the iterator finished or not
    root_reached: bool,
    /// Whether the iterator finished or not
    ended: bool,
    /// Only loaded one file, which should already be in the cache
    single: bool,
    /// Current directory
    current_dir: PathBuf,
    /// Cached config files
    cached: Vec<PathBuf>,
}

pub struct ConfigFilesContainer {
    /// Cached config files
    cached: IndexMap<PathBuf, ConfigFileSharedPtr>,
}

impl Iterator for ConfigFilePaths {
    // Returning &Path would be more optimal but complicates more the code. There is no need
    // to optimize that much since it should not find that many config files.
    type Item = DynErrResult<PathBuf>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.ended {
            return None;
        }

        if self.single {
            self.ended = true;
            return if self.cached.is_empty() {
                None
            } else {
                Some(Ok(PathBuf::from(self.cached.last().unwrap())))
            };
        }

        // Stores any error to return after breaking the loop
        let mut err: Option<Box<dyn error::Error>> = None;

        // Loops until a project config file is found or the root path is reached
        while !self.root_reached {
            let config_file_name = CONFIG_FILES_PRIO[self.index];

            // project file is the last one on the list
            let checking_for_project_config = CONFIG_FILES_PRIO.len() - 1 == self.index;
            self.index = (self.index + 1) % CONFIG_FILES_PRIO.len();

            let found_file =
                self.get_config_file_path(self.current_dir.as_path(), config_file_name);
            let found_file = match found_file {
                Ok(v) => v,
                Err(e) => {
                    err = Some(e.into());
                    break;
                }
            };

            if checking_for_project_config {
                // When checking for project config, we need to update the next dir to check
                let new_current = self.current_dir.parent();
                match new_current {
                    None => {
                        self.root_reached = true;
                    }
                    Some(new_current) => {
                        self.current_dir = new_current.to_path_buf();
                    }
                }
            }

            if let Some(found_file) = found_file {
                if checking_for_project_config {
                    self.root_reached = true;
                }
                self.cached.push(found_file.clone());
                return Some(Ok(found_file));
            }
        }

        self.root_reached = true;
        self.ended = true;

        if let Some(err) = err {
            return Some(Err(err));
        }

        let global_config_dir = Self::get_global_config_file_dir();
        let found_file = self.get_config_file_path(&global_config_dir, GLOBAL_CONFIG_FILE);
        let found_file = match found_file {
            Ok(v) => v,
            Err(e) => {
                return Some(Err(e.into()));
            }
        };

        if let Some(found_file) = found_file {
            self.cached.push(found_file.clone());
            return Some(Ok(found_file));
        }

        None
    }
}

impl ConfigFilePaths {
    /// Initializes ConfigFilePaths to start at the given path.
    ///
    /// # Arguments
    ///
    /// * `path`: Path to start searching for config files.
    ///
    /// returns: ConfigFilePaths
    pub fn new<S: AsRef<OsStr> + ?Sized>(path: &S) -> ConfigFilePaths {
        let current = PathBuf::from(path);
        ConfigFilePaths {
            index: 0,
            ended: false,
            root_reached: false,
            single: false,
            current_dir: current,
            cached: Vec::with_capacity(2),
        }
    }

    /// Initializes ConfigFilePaths such that it only loads the config file for the given path.
    ///
    /// # Arguments
    ///
    /// * `path`: Path of the config file to load
    ///
    /// returns:  Result<ConfigFilePaths, Box<dyn error::Error>>
    pub fn only<S: AsRef<OsStr> + ?Sized>(path: &S) -> DynErrResult<ConfigFilePaths> {
        let path = PathBuf::from(path);
        if !path.is_file() {
            return Err(format!("{} does not exist", path.display()).into());
        }
        let config_files = ConfigFilePaths {
            index: 0,
            ended: false,
            root_reached: true,
            single: true,
            current_dir: path.clone(),
            cached: vec![path],
        };
        Ok(config_files)
    }

    /// Returns the path of the global config file directory.
    #[cfg(not(test))]
    pub(crate) fn get_global_config_file_dir() -> PathBuf {
        let global_config_dir = shellexpand::tilde(GLOBAL_CONFIG_FILE_PATH);
        PathBuf::from(global_config_dir.as_ref())
    }

    /// Returns the path of the global config file directory.
    #[cfg(test)]
    pub(crate) fn get_global_config_file_dir() -> PathBuf {
        use assert_fs::TempDir;
        use lazy_static::lazy_static;
        lazy_static! {
            static ref GLOBAL_CONFIG_DIR: TempDir = TempDir::new().unwrap();
            pub static ref TEST_GLOBAL_CONFIG_PATH: PathBuf =
                PathBuf::from(GLOBAL_CONFIG_DIR.path());
        }
        TEST_GLOBAL_CONFIG_PATH.clone()
    }

    /// Finds the appropriate filepath to load in the given dir.
    ///
    /// # Arguments
    ///
    /// * `dir`:
    /// * `config_file_name`:
    ///
    /// returns: Result<Option<PathBuf>, ConfigError>
    fn get_config_file_path(
        &self,
        dir: &Path,
        config_file_name: &str,
    ) -> Result<Option<PathBuf>, ConfigError> {
        let mut files_count: u8 = 0;
        let mut found_file: Option<PathBuf> = None;

        for file_extension in ALLOWED_EXTENSIONS {
            let file_name = format!("{}.{}", config_file_name, file_extension);
            let path = dir.join(file_name);
            if path.is_file() {
                files_count += 1;
                found_file = Some(path);
            }
        }

        if files_count > 1 {
            Err(ConfigError::DuplicateConfigFile(String::from(
                config_file_name,
            )))
        } else {
            Ok(found_file)
        }
    }
}

impl ConfigFilesContainer {
    /// Initializes ConfigFilesContainer.
    pub fn new() -> ConfigFilesContainer {
        ConfigFilesContainer {
            cached: IndexMap::new(),
        }
    }

    /// Reads the config file from the given path.
    ///
    /// # Arguments
    ///
    /// * `path`: Path to read the config file from
    ///
    /// returns: Result<Arc<Mutex<ConfigFile>>, Box<dyn Error, Global>>
    pub fn read_config_file(&mut self, path: PathBuf) -> DynErrResult<ConfigFileSharedPtr> {
        let config_file = ConfigFile::load(path.clone());
        match config_file {
            Ok(config_file) => {
                let arc_config_file = Arc::new(Mutex::new(config_file));
                let result = Ok(Arc::clone(&arc_config_file));
                self.cached.insert(path, arc_config_file);
                result
            }
            Err(e) => Err(e),
        }
    }

    #[cfg(test)] // Used in tests only for now, but still leaving it here just in case
    /// Returns whether the given task exists in the config files.
    pub fn has_task<S: AsRef<str>>(&mut self, name: S) -> bool {
        for config_file in self.cached.values() {
            let config_file_ptr = config_file.as_ref();
            let handle = config_file_ptr.lock().unwrap();
            if handle.has_task(name.as_ref()) {
                return true;
            }
        }
        false
    }
}

impl Default for ConfigFilesContainer {
    fn default() -> Self {
        Self::new()
    }
}

impl ConfigFile {
    /// Reads the file from the path and constructs a config file
    fn extract(path: &Path) -> DynErrResult<ConfigFile> {
        let extension = path
            .extension()
            .unwrap_or_else(|| OsStr::new(""))
            .to_string_lossy()
            .to_string();

        let is_yaml = match extension.as_str() {
            "yaml" => true,
            "yml" => true,
            "toml" => false,
            _ => {
                return Err(ConfigError::BadConfigFile(
                    path.to_path_buf(),
                    String::from("Extension must be either `.toml`, `.yaml` or `.yml`"),
                )
                .into());
            }
        };
        let contents = match fs::read_to_string(path) {
            Ok(file_contents) => file_contents,
            Err(e) => return Err(format!("There was an error reading the file:\n{}", e).into()),
        };
        if is_yaml {
            Ok(serde_yaml::from_str(&contents)?)
        } else {
            Ok(toml::from_str(&contents)?)
        }
    }

    /// Loads a config file
    ///
    /// # Arguments
    ///
    /// * path - path of the toml file to load
    pub fn load(path: PathBuf) -> DynErrResult<ConfigFile> {
        let mut conf: ConfigFile = ConfigFile::extract(path.as_path())?;
        conf.filepath = path;

        if let Some(env_file_path) = &conf.env_file {
            let env_file_path = get_path_relative_to_base(conf.directory(), &env_file_path);
            let env_from_file = read_env_file(&env_file_path)?;
            match conf.env.as_mut() {
                None => {
                    conf.env = Some(HashMap::from_iter(env_from_file.into_iter()));
                }
                Some(env) => {
                    for (key, val) in env_from_file.into_iter() {
                        // manually set env takes precedence over env_file
                        env.entry(key).or_insert(val);
                    }
                }
            }
        }

        let mut tasks = conf.get_flat_tasks()?;

        let dep_graph = get_task_dependency_graph(&tasks)?;
        let dependencies = toposort(&dep_graph, None);
        let dependencies = match dependencies {
            Ok(dependencies) => dependencies,
            Err(e) => {
                return Err(format!("Found a cyclic dependency for Task:\n{}", e.node_id()).into());
            }
        };
        let dependencies: Vec<String> = dependencies
            .iter()
            .rev()
            .map(|v| String::from(*v))
            .collect();

        for dependency_name in dependencies {
            // temp remove because of rules of references
            let mut task = tasks.remove(&dependency_name).unwrap();
            // task.bases should be empty for the first item in the iteration
            // we no longer need the bases
            let bases = std::mem::take(&mut task.bases);
            for base in bases {
                let os_task_name = format!("{}.{}", &base, env::consts::OS);
                if let Some(base_task) = conf.loaded_tasks.get(&os_task_name) {
                    task.extend_task(base_task);
                } else if let Some(base_task) = conf.loaded_tasks.get(&base) {
                    task.extend_task(base_task);
                } else {
                    panic!("found non existent task {}", base);
                }
            }
            // insert modified task back in
            conf.loaded_tasks.insert(dependency_name, Arc::new(task));
        }

        // Store the other tasks left
        for (task_name, task) in tasks {
            conf.loaded_tasks.insert(task_name, Arc::new(task));
        }
        Ok(conf)
    }

    /// Returns the directory where the config file
    pub fn directory(&self) -> &Path {
        self.filepath.parent().unwrap()
    }

    /// If set in the config file, returns the working directory as an absolute path.
    pub fn working_directory(&self) -> Option<PathBuf> {
        // Some sort of cache would make it faster, but keeping it
        // simple until it is really needed
        self.wd
            .as_ref()
            .map(|wd| get_path_relative_to_base(self.directory(), wd))
    }

    /// Returns plain and OS specific tasks with normalized names. This consumes `self.tasks`
    fn get_flat_tasks(&mut self) -> DynErrResult<HashMap<String, Task>> {
        let mut flat_tasks = HashMap::new();
        let tasks = std::mem::take(&mut self.tasks);
        for (name, mut task) in tasks {
            // TODO: Use a macro
            if task.linux.is_some() {
                let os_task = std::mem::replace(&mut task.linux, None);
                let mut os_task = *os_task.unwrap();
                let os_task_name = format!("{}.linux", name);
                if flat_tasks.contains_key(&os_task_name) {
                    return Err(format!("Duplicate task `{}`", os_task_name).into());
                }
                os_task.setup(&os_task_name, self.directory())?;
                flat_tasks.insert(os_task_name, os_task);
            }

            if task.windows.is_some() {
                let os_task = std::mem::replace(&mut task.windows, None);
                let mut os_task = *os_task.unwrap();
                let os_task_name = format!("{}.windows", name);
                if flat_tasks.contains_key(&os_task_name) {
                    return Err(format!("Duplicate task `{}`", os_task_name).into());
                }
                os_task.setup(&os_task_name, self.directory())?;
                flat_tasks.insert(os_task_name, os_task);
            }

            if task.macos.is_some() {
                let os_task = std::mem::replace(&mut task.macos, None);
                let mut os_task = *os_task.unwrap();
                let os_task_name = format!("{}.macos", name);
                if flat_tasks.contains_key(&os_task_name) {
                    return Err(format!("Duplicate task `{}`", os_task_name).into());
                }
                os_task.setup(&os_task_name, self.directory())?;
                flat_tasks.insert(os_task_name, os_task);
            }
            task.setup(&name, self.directory())?;
            flat_tasks.insert(name, task);
        }
        Ok(flat_tasks)
    }

    /// Finds and task by name on this config file and returns it if it exists.
    /// It searches fist for the current OS version of the task, if None is found,
    /// it tries with the plain name.
    ///
    /// # Arguments
    ///
    /// * task_name - Name of the task to search for
    pub fn get_task(&self, task_name: &str) -> Option<Arc<Task>> {
        let os_task_name = to_os_task_name(task_name);

        if let Some(task) = self.loaded_tasks.get(&os_task_name) {
            return Some(Arc::clone(task));
        } else if let Some(task) = self.loaded_tasks.get(task_name) {
            return Some(Arc::clone(task));
        }
        None
    }

    /// Finds an public task by name on this config file and returns it if it exists.
    /// It searches fist for the current OS version of the task, if None is found,
    /// it tries with the plain name.
    ///
    /// # Arguments
    ///
    /// * task_name - Name of the task to search for
    pub fn get_public_task(&self, task_name: &str) -> Option<Arc<Task>> {
        let os_task_name = to_os_task_name(task_name);

        if let Some(task) = self.loaded_tasks.get(&os_task_name) {
            if task.is_private() {
                return None;
            }
            return Some(Arc::clone(task));
        } else if let Some(task) = self.loaded_tasks.get(task_name) {
            if task.is_private() {
                return None;
            }
            return Some(Arc::clone(task));
        }
        None
    }

    /// Returns whether the config file has a task with the given name. This also
    /// checks for the OS specific version of the task.
    ///
    /// # Arguments
    ///
    /// * `task_name`: Name of the task to check for
    ///
    /// returns: bool
    #[cfg(test)]
    pub fn has_task(&self, task_name: &str) -> bool {
        let os_task_name = to_os_task_name(task_name);

        self.loaded_tasks.contains_key(&os_task_name) || self.loaded_tasks.contains_key(task_name)
    }

    /// Returns the list of names of tasks in this config file
    pub fn get_task_names(&self) -> Vec<&String> {
        self.loaded_tasks.keys().collect()
    }

    /// Returns the list of names of tasks that are not private in this config file
    pub fn get_public_task_names(&self) -> Vec<&str> {
        self.loaded_tasks
            .values()
            .filter(|t| !t.is_private())
            .map(|t| t.get_name())
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use assert_fs::TempDir;
    use std::fs::File;
    use std::io::Write;

    #[test]
    fn test_discovery() {
        let tmp_dir = TempDir::new().unwrap();
        let project_config_path = tmp_dir.path().join("project.yamis.toml");
        let mut project_config_file = File::create(project_config_path.as_path()).unwrap();
        project_config_file
            .write_all(
                r#"
    [tasks.hello_project]
    script = "echo hello project"
    "#
                .as_bytes(),
            )
            .unwrap();

        let config_path = tmp_dir.path().join("yamis.yaml");
        let mut config_file = File::create(config_path.as_path()).unwrap();
        config_file
            .write_all(
                r#"
    tasks:
        hello:
            script: echo hello
    "#
                .as_bytes(),
            )
            .unwrap();

        let local_config_path = tmp_dir.path().join("local.yamis.yaml");
        let mut local_file = File::create(local_config_path.as_path()).unwrap();
        local_file
            .write_all(
                r#"
    tasks:
        hello_local:
            script: echo hello local
    "#
                .as_bytes(),
            )
            .unwrap();

        let global_config_path =
            ConfigFilePaths::get_global_config_file_dir().join("user.yamis.toml");
        let mut global_config_file = File::create(global_config_path.as_path()).unwrap();
        global_config_file
            .write_all(
                r#"
                [tasks.hello_global]
                script = "echo hello project"
                "#
                .as_bytes(),
            )
            .unwrap();

        let mut config_files = ConfigFilesContainer::new();
        let mut paths = ConfigFilePaths::new(&tmp_dir.path());
        let local_path = paths.next().unwrap().unwrap();
        let regular_path = paths.next().unwrap().unwrap();
        let project_path = paths.next().unwrap().unwrap();
        let global_path = paths.next().unwrap().unwrap();
        assert!(paths.next().is_none());
        config_files.read_config_file(local_path).unwrap();
        config_files.read_config_file(regular_path).unwrap();
        config_files.read_config_file(project_path).unwrap();
        config_files.read_config_file(global_path).unwrap();

        assert!(!config_files.has_task("non_existent"));
        assert!(config_files.has_task("hello_project"));
        assert!(config_files.has_task("hello"));
        assert!(config_files.has_task("hello_local"));
        assert!(config_files.has_task("hello_global"));
    }

    #[test]
    fn test_discovery_given_file() {
        let tmp_dir = TempDir::new().unwrap();
        let sample_config_file_path = tmp_dir.path().join("sample.yamis.toml");
        let mut sample_config_file = File::create(sample_config_file_path.as_path()).unwrap();
        sample_config_file
            .write_all(
                r#"
    [tasks.hello_project]
    script = "echo hello project"
    "#
                .as_bytes(),
            )
            .unwrap();

        let mut config_files = ConfigFilesContainer::new();
        let mut paths = ConfigFilePaths::only(&sample_config_file_path).unwrap();
        let sample_path = paths.next().unwrap().unwrap();
        assert!(paths.next().is_none());
        config_files.read_config_file(sample_path).unwrap();

        assert!(config_files.has_task("hello_project"));
    }

    #[test]
    fn test_dup_config_error() {
        let tmp_dir = TempDir::new().unwrap();

        let project_config_path = tmp_dir.path().join("project.yamis.toml");
        File::create(project_config_path.as_path()).unwrap();

        let config_path = tmp_dir.path().join("project.yamis.yaml");
        File::create(config_path.as_path()).unwrap();

        let mut paths = ConfigFilePaths::new(&tmp_dir.path());
        let val = paths.next().unwrap();
        assert!(val.is_err());
        assert_eq!(
            val.unwrap_err().to_string(),
            "Config file `project.yamis` defined multiple times with different extensions in the same directory."
        );
    }

    #[test]
    fn test_config_file_only_iter() {
        let path = PathBuf::from("sample_path.yml");
        let mut config_files = ConfigFilePaths {
            index: 0,
            ended: false,
            root_reached: true,
            single: true,
            current_dir: path.clone(),
            cached: vec![],
        };
        // cache is empty, nothing to return
        assert!(config_files.next().is_none());

        let mut config_files = ConfigFilePaths {
            index: 0,
            ended: false,
            root_reached: true,
            single: true,
            current_dir: path.clone(),
            cached: vec![path.clone()],
        };
        assert_eq!(config_files.next().unwrap().unwrap(), path);
    }

    #[test]
    fn test_config_file_invalid_path() {
        let cnfg = ConfigFile::extract(Path::new("non_existent"));
        assert!(cnfg.is_err());

        let cnfg = ConfigFile::extract(Path::new("non_existent.ext"));
        assert!(cnfg.is_err());

        let cnfg = ConfigFile::extract(Path::new("non_existent.yml"));
        assert!(cnfg.is_err());
    }

    #[test]
    fn test_container_read_config_error() {
        let tmp_dir = TempDir::new().unwrap();
        let project_config_path = tmp_dir.path().join("project.yamis.toml");
        let mut project_config_file = File::create(project_config_path.as_path()).unwrap();
        project_config_file
            .write_all(
                r#"
    some invalid condig
    "#
                .as_bytes(),
            )
            .unwrap();

        let mut config_files = ConfigFilesContainer::default();
        let result = config_files.read_config_file(project_config_path);

        assert!(result.is_err());
    }

    #[test]
    fn test_config_file_read() {
        let tmp_dir = TempDir::new().unwrap();

        let dot_env_path = tmp_dir.path().join(".env");
        let mut dot_env_file = File::create(dot_env_path.as_path()).unwrap();
        dot_env_file
            .write_all(
                r#"VALUE_OVERRIDE=OLD_VALUE
OTHER_VALUE=HELLO
"#
                .as_bytes(),
            )
            .unwrap();

        let project_config_path = tmp_dir.path().join("project.yamis.yaml");
        let mut project_config_file = File::create(project_config_path.as_path()).unwrap();
        project_config_file
            .write_all(
                r#"
env_file: ".env"
env:
  VALUE_OVERRIDE: NEW_VALUE
tasks:
  hello_local:
    script: echo hello local
        "#
                .as_bytes(),
            )
            .unwrap();
        let config_file = ConfigFile::load(project_config_path).unwrap();
        assert!(config_file.has_task("hello_local"));
        let env = config_file.env.unwrap();
        assert_eq!(env.get("VALUE_OVERRIDE").unwrap(), "NEW_VALUE");
        assert_eq!(env.get("OTHER_VALUE").unwrap(), "HELLO");
    }

    #[test]
    fn test_config_file_get_task_names() {
        let tmp_dir = TempDir::new().unwrap();

        let project_config_path = tmp_dir.path().join("project.yamis.yaml");
        let mut project_config_file = File::create(project_config_path.as_path()).unwrap();
        project_config_file
            .write_all(
                r#"
tasks:
  task_1:
    script: echo hello

  task_2:
    script: echo hello again

  task_3:
    script: echo hello again
    private: true

        "#
                .as_bytes(),
            )
            .unwrap();
        let config_file = ConfigFile::load(project_config_path).unwrap();
        let mut task_names = config_file.get_task_names();
        task_names.sort();
        assert_eq!(task_names, vec!["task_1", "task_2", "task_3"]);
        let mut task_names = config_file.get_public_task_names();
        task_names.sort();
        assert_eq!(task_names, vec!["task_1", "task_2"]);
    }

    #[test]
    fn test_config_file_get_task() {
        let tmp_dir = TempDir::new().unwrap();

        let project_config_path = tmp_dir.path().join("project.yamis.yaml");
        let mut project_config_file = File::create(project_config_path.as_path()).unwrap();
        project_config_file
            .write_all(
                r#"
tasks:
  task_1:
    script: echo hello

  task_2:
    script: echo hello again

  task_3:
    script: echo hello again
    private: true

        "#
                .as_bytes(),
            )
            .unwrap();
        let config_file = ConfigFile::load(project_config_path).unwrap();

        let task_nam = config_file.get_task("task_1");
        assert!(task_nam.is_some());
        assert_eq!(task_nam.unwrap().get_name(), "task_1");

        let task_nam = config_file.get_task("task_2");
        assert!(task_nam.is_some());
        assert_eq!(task_nam.unwrap().get_name(), "task_2");

        let task_nam = config_file.get_task("task_3");
        assert!(task_nam.is_some());
        assert_eq!(task_nam.unwrap().get_name(), "task_3");
    }

    #[test]
    fn test_config_file_get_non_private_task() {
        let tmp_dir = TempDir::new().unwrap();

        let project_config_path = tmp_dir.path().join("project.yamis.yaml");
        let mut project_config_file = File::create(project_config_path.as_path()).unwrap();
        project_config_file
            .write_all(
                r#"
tasks:
  task_1:
    script: echo hello

  task_2:
    script: echo hello again

  task_3:
    script: echo hello again
    private: true

        "#
                .as_bytes(),
            )
            .unwrap();
        let config_file = ConfigFile::load(project_config_path).unwrap();

        let task_nam = config_file.get_public_task("task_1");
        assert!(task_nam.is_some());
        assert_eq!(task_nam.unwrap().get_name(), "task_1");

        let task_nam = config_file.get_public_task("task_2");
        assert!(task_nam.is_some());
        assert_eq!(task_nam.unwrap().get_name(), "task_2");

        let task_nam = config_file.get_public_task("task_3");
        assert!(task_nam.is_none());
    }

    #[test]
    fn test_wrong_config_file_extension() {
        let tmp_dir = TempDir::new().unwrap();

        let project_config_path = tmp_dir.path().join("project.yamis.wrong");
        File::create(project_config_path.as_path()).unwrap();
        let config_file = ConfigFile::load(project_config_path);
        assert!(config_file.is_err());
        assert!(config_file
            .unwrap_err()
            .to_string()
            .contains("Bad config file"));
    }
}