1pub mod projects_yaml;
14
15use anyhow::Context;
16use notify::{Config, RecommendedWatcher, RecursiveMode, Watcher};
17use std::collections::{HashMap, HashSet};
18use std::env;
19use std::fs;
20use std::path::{Path, PathBuf};
21use std::sync::LazyLock;
22use std::sync::PoisonError;
23use std::sync::{Arc, Mutex, RwLock};
24use std::time::Duration;
25use tokio::sync::broadcast;
26
27use crate::home;
28
29use tokio::fs as tokio_fs;
30use tokio::runtime::Handle;
31use tokio::runtime::RuntimeFlavor;
32use tokio::task;
33
34static CACHE: LazyLock<RwLock<HashMap<PathBuf, serde_norway::Value>>> =
37 LazyLock::new(|| RwLock::new(HashMap::new()));
38
39static WATCHER: LazyLock<RwLock<HashSet<PathBuf>>> = LazyLock::new(|| RwLock::new(HashSet::new()));
41
42static FILE_WATCHER: LazyLock<Arc<Mutex<Option<RecommendedWatcher>>>> =
44 LazyLock::new(|| Arc::new(Mutex::new(None)));
45
46static BAD_FILES: LazyLock<RwLock<HashSet<PathBuf>>> =
50 LazyLock::new(|| RwLock::new(HashSet::new()));
51
52static CHANGE_TX: LazyLock<broadcast::Sender<PathBuf>> = LazyLock::new(|| {
55 let (tx, _) = broadcast::channel(16);
56 tx
57});
58
59pub fn subscribe() -> broadcast::Receiver<PathBuf> {
64 CHANGE_TX.subscribe()
65}
66
67pub async fn warm_cache() -> anyhow::Result<()> {
73 let global_path = global_config_path()?;
74 if global_path.exists() {
75 match tokio_fs::read_to_string(&global_path).await {
76 Ok(content) => {
77 if let Ok(parsed) = serde_norway::from_str::<serde_norway::Value>(&content) {
78 if let Ok(mut cache) = CACHE.write() {
79 cache.insert(global_path.clone(), parsed);
80 }
81 watch_file(&global_path);
82 }
83 }
84 Err(e) => tracing::warn!("failed to warm global config cache: {e}"),
85 }
86 }
87
88 let project_path = env::current_dir()
89 .unwrap_or_else(|_| PathBuf::from("."))
90 .join(".orch.yml");
91 if project_path.exists() {
92 match tokio_fs::read_to_string(&project_path).await {
93 Ok(content) => {
94 if let Ok(parsed) = serde_norway::from_str::<serde_norway::Value>(&content) {
95 if let Ok(mut cache) = CACHE.write() {
96 cache.insert(project_path.clone(), parsed);
97 }
98 watch_file(&project_path);
99 }
100 }
101 Err(e) => tracing::warn!("failed to warm project config cache: {e}"),
102 }
103 }
104
105 Ok(())
106}
107
108#[cfg(test)]
112pub fn clear_test_cache() {
113 if let Ok(mut cache) = CACHE.write() {
114 cache.clear();
115 }
116}
117
118pub fn reloaded(path: &Path) {
129 let path = path.to_path_buf();
130 watch_file(&path);
131 reload_file(&path);
132}
133
134fn reload_file(path: &PathBuf) -> bool {
135 let parsed = fs::read_to_string(path)
136 .map_err(|e| e.to_string())
137 .and_then(|content| {
138 serde_norway::from_str::<serde_norway::Value>(&content).map_err(|e| e.to_string())
139 });
140
141 match parsed {
142 Ok(value) => {
143 if let Ok(mut cache) = CACHE.write() {
144 cache.insert(path.clone(), value);
145 }
146 if let Ok(mut bad) = BAD_FILES.write()
147 && bad.remove(path)
148 {
149 tracing::info!(path = %path.display(), "config file parses again, reloaded");
150 }
151 tracing::debug!("config cache refreshed for: {}", path.display());
152 let _ = CHANGE_TX.send(path.clone());
154 false
155 }
156 Err(err) => {
157 let first_failure = BAD_FILES
158 .write()
159 .is_ok_and(|mut bad| bad.insert(path.clone()));
160 if first_failure {
161 tracing::error!(
162 path = %path.display(),
163 %err,
164 "config file is invalid, keeping the last good values"
165 );
166 }
167 first_failure
168 }
169 }
170}
171
172fn ensure_watcher() {
174 let mut watcher_guard = FILE_WATCHER.lock().unwrap_or_else(PoisonError::into_inner);
175 if watcher_guard.is_some() {
176 return;
177 }
178
179 let watcher = RecommendedWatcher::new(
181 move |res: Result<notify::Event, notify::Error>| {
182 if let Ok(event) = res {
183 if !is_content_change(event.kind) {
184 return;
185 }
186 for path in event.paths {
187 let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
189
190 if filename == "config.yml" || filename == ".orch.yml" {
191 let _ = reload_file(&path);
192 }
193 }
194 }
195 },
196 Config::default().with_poll_interval(Duration::from_secs(2)),
197 );
198
199 if let Ok(w) = watcher {
200 *watcher_guard = Some(w);
201 }
202}
203
204fn is_content_change(kind: notify::EventKind) -> bool {
207 kind.is_create() || kind.is_modify() || kind.is_remove()
208}
209
210pub fn watch(path: &Path) {
218 if !path.exists() {
219 tracing::debug!(path = %path.display(), "no config file to watch here");
220 return;
221 }
222 watch_file(&path.to_path_buf());
223}
224
225fn watch_file(path: &PathBuf) {
227 ensure_watcher();
229
230 if let Ok(mut watched) = WATCHER.write()
232 && !watched.contains(path)
233 {
234 watched.insert(path.clone());
235
236 if let Ok(mut guard) = FILE_WATCHER.lock()
238 && let Some(ref mut watcher) = *guard
239 {
240 match watcher.watch(path, RecursiveMode::NonRecursive) {
241 Ok(()) => tracing::debug!("now watching config file: {}", path.display()),
242 Err(e) => tracing::warn!(
243 "failed to register config file watcher for {}: {}",
244 path.display(),
245 e
246 ),
247 }
248 }
249 }
250}
251
252fn read_file_to_string(path: &Path) -> anyhow::Result<String> {
253 match Handle::try_current() {
254 Ok(handle) if handle.runtime_flavor() == RuntimeFlavor::MultiThread => {
255 Ok(task::block_in_place(|| fs::read_to_string(path))?)
256 }
257 _ => Ok(fs::read_to_string(path)?),
258 }
259}
260
261fn load_cached_root(path: &PathBuf) -> anyhow::Result<serde_norway::Value> {
262 if let Ok(cache) = CACHE.read()
263 && let Some(cached) = cache.get(path)
264 {
265 return Ok(cached.clone());
266 }
267
268 let content =
269 read_file_to_string(path).with_context(|| format!("reading {}", path.display()))?;
270 let parsed: serde_norway::Value =
271 serde_norway::from_str(&content).with_context(|| format!("parsing {}", path.display()))?;
272
273 if let Ok(mut cache) = CACHE.write() {
274 cache.insert(path.clone(), parsed.clone());
275 }
276
277 Ok(parsed)
278}
279
280fn global_config_path() -> anyhow::Result<PathBuf> {
282 home::config_path()
283}
284
285pub fn get_list(key: &str) -> anyhow::Result<Vec<String>> {
303 let project_path = env::current_dir()
307 .unwrap_or_else(|_| PathBuf::from("."))
308 .join(".orch.yml");
309 if project_path.exists()
310 && let Ok(val) = resolve_list(&project_path, key)
311 && !val.is_empty()
312 {
313 return Ok(val);
314 }
315
316 let global_path = global_config_path()?;
318 if global_path.exists() {
319 return resolve_list(&global_path, key);
320 }
321
322 Ok(vec![])
323}
324
325fn resolve_list(path: &PathBuf, key: &str) -> anyhow::Result<Vec<String>> {
327 watch_file(path);
328
329 let root = load_cached_root(path)?;
330
331 Ok(extract_list(&root, key))
332}
333
334fn extract_list(root: &serde_norway::Value, key: &str) -> Vec<String> {
336 let mut current = root;
337 for part in key.split('.') {
338 match current.get(part) {
339 Some(v) => current = v,
340 None => return vec![],
341 }
342 }
343
344 match current {
345 serde_norway::Value::Sequence(seq) => seq
346 .iter()
347 .filter_map(|item| item.as_str().map(String::from))
348 .collect(),
349 serde_norway::Value::String(s) => {
350 s.split(',')
352 .map(|s| s.trim().to_string())
353 .filter(|s| !s.is_empty())
354 .collect()
355 }
356 _ => vec![],
357 }
358}
359
360pub fn get(key: &str) -> anyhow::Result<String> {
369 let project_path = env::current_dir()
373 .unwrap_or_else(|_| PathBuf::from("."))
374 .join(".orch.yml");
375 if project_path.exists()
376 && let Ok(val) = resolve_key(&project_path, key)
377 {
378 return Ok(val);
379 }
380
381 let global_path = global_config_path()?;
383 if global_path.exists() {
384 return resolve_key(&global_path, key);
385 }
386
387 anyhow::bail!("config key not found: {key}")
388}
389
390pub fn get_for_project(project_dir: &Path, key: &str) -> anyhow::Result<String> {
392 let project_path = project_dir.join(".orch.yml");
393 if project_path.exists()
394 && let Ok(val) = resolve_key(&project_path, key)
395 {
396 return Ok(val);
397 }
398
399 let global_path = global_config_path()?;
400 if global_path.exists() {
401 return resolve_key(&global_path, key);
402 }
403
404 anyhow::bail!("config key not found: {key}")
405}
406
407pub fn get_project_only(project_dir: &Path, key: &str) -> anyhow::Result<String> {
409 let project_path = project_dir.join(".orch.yml");
410 if project_path.exists() {
411 return resolve_key(&project_path, key);
412 }
413
414 anyhow::bail!("config key not found: {key}")
415}
416
417pub fn get_global(key: &str) -> anyhow::Result<String> {
419 let global_path = global_config_path()?;
420 if global_path.exists() {
421 return resolve_key(&global_path, key);
422 }
423
424 anyhow::bail!("config key not found: {key}")
425}
426
427pub fn get_project_paths() -> anyhow::Result<Vec<String>> {
432 let global_path = global_config_path()?;
433
434 if global_path.exists()
435 && let Ok(paths) = resolve_projects_list(&global_path, "projects")
436 && !paths.is_empty()
437 {
438 return Ok(paths);
439 }
440
441 Ok(vec![])
442}
443
444pub fn get_projects_with_paths() -> anyhow::Result<Vec<(String, PathBuf)>> {
449 let paths = get_project_paths()?;
450
451 if !paths.is_empty() {
452 let mut results = Vec::new();
453 for path_str in &paths {
454 let path = PathBuf::from(path_str);
455 let orch_yml = path.join(".orch.yml");
456
457 let config_file = if orch_yml.exists() {
458 orch_yml
459 } else {
460 let legacy = path.join(".orchestrator.yml");
461 if legacy.exists() {
462 legacy
463 } else {
464 continue;
465 }
466 };
467
468 if let Ok(content) = fs::read_to_string(&config_file)
469 && let Ok(doc) = serde_norway::from_str::<serde_norway::Value>(&content)
470 && let Some(repo) = doc
471 .get("gh")
472 .and_then(|gh| gh.get("repo"))
473 .and_then(|r| r.as_str())
474 {
475 results.push((repo.to_string(), path));
476 }
477 }
478
479 if !results.is_empty() {
480 return Ok(results);
481 }
482 }
483
484 if let Ok(repo) = get("gh.repo")
486 && !repo.is_empty()
487 {
488 return Ok(vec![(repo, PathBuf::from("."))]);
489 }
490
491 Ok(vec![])
492}
493
494pub fn get_repo_for_project(project_path: &Path) -> anyhow::Result<String> {
498 let orch_yml = project_path.join(".orch.yml");
499 let config_file = if orch_yml.exists() {
500 orch_yml
501 } else {
502 let legacy = project_path.join(".orchestrator.yml");
503 if legacy.exists() {
504 legacy
505 } else {
506 anyhow::bail!("no .orch.yml found in {}", project_path.display());
507 }
508 };
509
510 let content = fs::read_to_string(&config_file)?;
511 let doc: serde_norway::Value = serde_norway::from_str(&content)?;
512
513 doc.get("gh")
514 .and_then(|gh| gh.get("repo"))
515 .and_then(|r| r.as_str())
516 .map(String::from)
517 .ok_or_else(|| anyhow::anyhow!("gh.repo not set in {}", config_file.display()))
518}
519
520pub fn find_project_root() -> anyhow::Result<PathBuf> {
524 let mut dir = env::current_dir()?;
525
526 loop {
527 if dir.join(".orch.yml").exists() || dir.join(".orchestrator.yml").exists() {
528 return Ok(dir);
529 }
530
531 if !dir.pop() {
532 break;
533 }
534 }
535
536 anyhow::bail!("no .orch.yml found in current directory or parents — run `orch init`")
537}
538
539pub fn get_current_repo() -> anyhow::Result<String> {
544 if let Ok(project_root) = find_project_root()
546 && let Ok(repo) = get_repo_for_project(&project_root)
547 {
548 return Ok(repo);
549 }
550
551 if let Ok(repo) = get("gh.repo")
553 && !repo.is_empty()
554 {
555 return Ok(repo);
556 }
557
558 if let Ok(repo) = get("repo")
560 && !repo.is_empty()
561 {
562 return Ok(repo);
563 }
564
565 anyhow::bail!("could not determine repo — ensure .orch.yml has gh.repo set")
566}
567
568fn resolve_projects_list(path: &PathBuf, key: &str) -> anyhow::Result<Vec<String>> {
570 watch_file(path);
572
573 let root = load_cached_root(path)?;
574
575 Ok(extract_projects_list(&root, key))
576}
577
578fn extract_projects_list(root: &serde_norway::Value, key: &str) -> Vec<String> {
580 let mut current = root;
581 for part in key.split('.') {
582 let Some(next) = current.get(part) else {
584 return vec![];
585 };
586 current = next;
587 }
588
589 match current {
590 serde_norway::Value::Sequence(seq) => {
591 let mut projects = Vec::new();
592 for item in seq {
593 if let serde_norway::Value::String(s) = item {
594 projects.push(s.clone());
595 } else if let serde_norway::Value::Mapping(map) = item {
596 if let Some(serde_norway::Value::String(repo)) = map.get("repo") {
598 projects.push(repo.clone());
599 }
600 }
601 }
602 projects
603 }
604 _ => vec![],
605 }
606}
607
608fn resolve_key(path: &PathBuf, key: &str) -> anyhow::Result<String> {
613 watch_file(path);
615
616 let root = load_cached_root(path)?;
617
618 extract_value(&root, key)
619}
620
621fn extract_value(root: &serde_norway::Value, key: &str) -> anyhow::Result<String> {
623 let mut current = root;
624 for part in key.split('.') {
625 current = current
626 .get(part)
627 .with_context(|| format!("key not found: {key}"))?;
628 }
629
630 match current {
631 serde_norway::Value::String(s) => Ok(s.clone()),
632 serde_norway::Value::Number(n) => Ok(n.to_string()),
633 serde_norway::Value::Bool(b) => Ok(b.to_string()),
634 serde_norway::Value::Null => Ok(String::new()),
635 _ => Ok(serde_norway::to_string(current)?),
636 }
637}
638
639#[cfg(test)]
640mod tests {
641 use super::*;
642 use std::io::Write;
643
644 use notify::event::AccessKind;
645 use notify::event::AccessMode;
646 use notify::event::CreateKind;
647 use notify::event::DataChange;
648 use notify::event::ModifyKind;
649 use tokio::sync::broadcast::Receiver;
650
651 use std::fs::File;
652
653 fn write_yaml(dir: &Path, name: &str, content: &str) -> PathBuf {
654 let path = dir.join(name);
655 let mut f = File::create(&path).unwrap();
656 f.write_all(content.as_bytes()).unwrap();
657 path
658 }
659
660 #[test]
661 fn resolve_simple_key() {
662 let dir = tempfile::tempdir().unwrap();
663 let path = write_yaml(dir.path(), "config.yml", "repo: owner/repo\n");
664 let val = resolve_key(&path, "repo").unwrap();
665 assert_eq!(val, "owner/repo");
666 }
667
668 #[test]
669 fn resolve_nested_key() {
670 let dir = tempfile::tempdir().unwrap();
671 let path = write_yaml(
672 dir.path(),
673 "config.yml",
674 "agents:\n claude:\n model: opus\n",
675 );
676 let val = resolve_key(&path, "agents.claude.model").unwrap();
677 assert_eq!(val, "opus");
678 }
679
680 #[test]
681 fn resolve_boolean_value() {
682 let dir = tempfile::tempdir().unwrap();
683 let path = write_yaml(dir.path(), "config.yml", "enabled: true\n");
684 let val = resolve_key(&path, "enabled").unwrap();
685 assert_eq!(val, "true");
686 }
687
688 #[test]
689 fn resolve_number_value() {
690 let dir = tempfile::tempdir().unwrap();
691 let path = write_yaml(dir.path(), "config.yml", "timeout: 300\n");
692 let val = resolve_key(&path, "timeout").unwrap();
693 assert_eq!(val, "300");
694 }
695
696 #[test]
697 fn resolve_missing_key_errors() {
698 let dir = tempfile::tempdir().unwrap();
699 let path = write_yaml(dir.path(), "config.yml", "repo: owner/repo\n");
700 let result = resolve_key(&path, "missing.key");
701 assert!(result.is_err());
702 }
703
704 #[test]
705 fn resolve_missing_file_errors() {
706 let path = PathBuf::from("/nonexistent/config.yml");
707 let result = resolve_key(&path, "repo");
708 assert!(result.is_err());
709 }
710
711 #[test]
712 fn resolve_projects_list_string_array() {
713 let dir = tempfile::tempdir().unwrap();
714 let path = write_yaml(
715 dir.path(),
716 "config.yml",
717 "projects:\n - owner/repo1\n - owner/repo2\n",
718 );
719 let projects = resolve_projects_list(&path, "projects").unwrap();
720 assert_eq!(projects, vec!["owner/repo1", "owner/repo2"]);
721 }
722
723 #[test]
724 fn resolve_projects_list_map_array() {
725 let dir = tempfile::tempdir().unwrap();
726 let path = write_yaml(
727 dir.path(),
728 "config.yml",
729 "projects:\n - repo: owner/repo1\n project_dir: /path/to/repo1\n - repo: owner/repo2\n project_dir: /path/to/repo2\n",
730 );
731 let projects = resolve_projects_list(&path, "projects").unwrap();
732 assert_eq!(projects, vec!["owner/repo1", "owner/repo2"]);
733 }
734
735 #[test]
736 fn resolve_projects_list_fallback_to_repo() {
737 let dir = tempfile::tempdir().unwrap();
738 let path = write_yaml(dir.path(), "config.yml", "repo: owner/single-repo\n");
739 let projects = resolve_projects_list(&path, "projects").unwrap();
740 assert!(projects.is_empty(), "{projects:?}");
741 }
742
743 #[test]
744 fn extract_projects_list_from_sequence() {
745 let yaml =
746 serde_norway::from_str::<serde_norway::Value>("projects:\n - a\n - b\n - c\n")
747 .unwrap();
748 let projects = extract_projects_list(&yaml, "projects");
749 assert_eq!(projects, vec!["a", "b", "c"]);
750 }
751
752 #[test]
753 fn extract_projects_list_from_mapping_sequence() {
754 let yaml =
755 serde_norway::from_str::<serde_norway::Value>("projects:\n - repo: a\n - repo: b\n")
756 .unwrap();
757 let projects = extract_projects_list(&yaml, "projects");
758 assert_eq!(projects, vec!["a", "b"]);
759 }
760
761 #[test]
762 fn extract_projects_list_empty_for_missing() {
763 let yaml = serde_norway::from_str::<serde_norway::Value>("foo: bar").unwrap();
764 let projects = extract_projects_list(&yaml, "projects");
765 assert!(projects.is_empty(), "{projects:?}");
766 }
767
768 #[test]
769 fn subscribe_receives_change_notifications() {
770 let mut rx = subscribe();
771 let dir = tempfile::tempdir().unwrap();
772 let path = write_yaml(dir.path(), "config.yml", "repo: owner/repo\n");
773
774 assert!(!reload_file(&path));
776
777 loop {
779 match rx.try_recv() {
780 Ok(received_path) if received_path == path => break,
781 Ok(_) => {} Err(e) => panic!("expected config change notification, got error: {e:?}"),
783 }
784 }
785 }
786
787 #[test]
788 fn subscribe_multiple_receivers() {
789 let mut rx1 = subscribe();
790 let mut rx2 = subscribe();
791 let dir = tempfile::tempdir().unwrap();
792 let path = write_yaml(dir.path(), "config.yml", "repo: owner/repo\n");
793
794 assert!(!reload_file(&path));
795
796 let find_path = |rx: &mut Receiver<PathBuf>, expected: &PathBuf| loop {
798 match rx.try_recv() {
799 Ok(p) if &p == expected => return,
800 Ok(_) => {}
801 Err(e) => panic!("expected config change notification, got error: {e:?}"),
802 }
803 };
804 find_path(&mut rx1, &path);
805 find_path(&mut rx2, &path);
806 }
807
808 #[test]
809 fn resolve_list_from_sequence() {
810 let dir = tempfile::tempdir().unwrap();
811 let path = write_yaml(
812 dir.path(),
813 "config.yml",
814 "workflow:\n allowed_tools:\n - Edit\n - Write\n - git\n - npm\n",
815 );
816 let list = resolve_list(&path, "workflow.allowed_tools").unwrap();
817 assert_eq!(list, vec!["Edit", "Write", "git", "npm"]);
818 }
819
820 #[test]
821 fn resolve_list_from_comma_string() {
822 let dir = tempfile::tempdir().unwrap();
823 let path = write_yaml(
824 dir.path(),
825 "config.yml",
826 "workflow:\n allowed_tools: \"Edit,Write,git,npm\"\n",
827 );
828 let list = resolve_list(&path, "workflow.allowed_tools").unwrap();
829 assert_eq!(list, vec!["Edit", "Write", "git", "npm"]);
830 }
831
832 #[test]
833 fn resolve_list_missing_key_returns_empty() {
834 let dir = tempfile::tempdir().unwrap();
835 let path = write_yaml(dir.path(), "config.yml", "foo: bar\n");
836 let list = resolve_list(&path, "workflow.allowed_tools").unwrap();
837 assert!(list.is_empty(), "{list:?}");
838 }
839
840 fn cached_value(path: &PathBuf, key: &str) -> String {
846 extract_value(&load_cached_root(path).unwrap(), key).unwrap()
847 }
848
849 fn cached_projects(path: &PathBuf) -> Vec<String> {
850 extract_projects_list(&load_cached_root(path).unwrap(), "projects")
851 }
852
853 #[test]
854 fn reading_a_config_file_does_not_trigger_a_reload() {
855 assert!(!is_content_change(notify::EventKind::Access(
856 AccessKind::Open(AccessMode::Read)
857 )));
858 assert!(!is_content_change(notify::EventKind::Access(
859 AccessKind::Close(AccessMode::Read)
860 )));
861 assert!(is_content_change(notify::EventKind::Modify(
862 ModifyKind::Data(DataChange::Content)
863 )));
864 assert!(is_content_change(notify::EventKind::Create(
865 CreateKind::File
866 )));
867 }
868
869 #[test]
870 fn invalid_edit_keeps_last_good_values_and_sends_no_notification() {
871 let dir = tempfile::tempdir().unwrap();
872 let path = write_yaml(dir.path(), "config.yml", "engine:\n max_parallel: 8\n");
873 assert!(!reload_file(&path));
874 assert_eq!(cached_value(&path, "engine.max_parallel"), "8");
875
876 let mut rx = subscribe();
877 fs::write(&path, "engine:\n max_parallel: [unclosed\n").unwrap();
878 assert!(reload_file(&path));
879
880 assert_eq!(cached_value(&path, "engine.max_parallel"), "8");
881 assert!(rx.try_recv().is_err(), "a broken edit must not notify");
882
883 fs::write(&path, "engine:\n max_parallel: 12\n").unwrap();
885 assert!(!reload_file(&path));
886 assert_eq!(cached_value(&path, "engine.max_parallel"), "12");
887 }
888
889 #[test]
890 fn adding_a_project_is_visible_after_reload() {
891 let dir = tempfile::tempdir().unwrap();
892 let path = write_yaml(dir.path(), "config.yml", "projects:\n - /srv/one\n");
893 assert_eq!(cached_projects(&path), vec!["/srv/one"]);
894
895 fs::write(&path, "projects:\n - /srv/one\n - /srv/two\n").unwrap();
896 assert!(!reload_file(&path));
897
898 assert_eq!(cached_projects(&path), vec!["/srv/one", "/srv/two"]);
899 }
900
901 #[test]
902 fn repeated_watcher_events_for_one_breakage_log_once() {
903 let dir = tempfile::tempdir().unwrap();
904 let path = write_yaml(dir.path(), "config.yml", "engine:\n max_parallel: 4\n");
905 reload_file(&path);
906
907 fs::write(&path, "engine: [broken\n").unwrap();
908 assert!(reload_file(&path), "first bad read logs");
909 assert!(!reload_file(&path), "same breakage does not log again");
910 }
911
912 #[test]
913 #[serial_test::serial(orch_home)]
914 fn a_project_setting_overrides_the_global_one() {
915 let (home, with, without) = (
916 tempfile::tempdir().unwrap(),
917 tempfile::tempdir().unwrap(),
918 tempfile::tempdir().unwrap(),
919 );
920 write_yaml(home.path(), "config.yml", "workflow:\n sandbox: os\n");
921 write_yaml(with.path(), ".orch.yml", "workflow:\n sandbox: false\n");
922 unsafe { env::set_var("ORCH_HOME", home.path()) };
924
925 let got = (
926 get_for_project(with.path(), "workflow.sandbox").unwrap(),
927 get_for_project(without.path(), "workflow.sandbox").unwrap(),
928 );
929 unsafe { env::remove_var("ORCH_HOME") };
931 assert_eq!(got, ("false".to_string(), "os".to_string()));
932 }
933}