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::sys::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
325pub fn get_global_list(key: &str) -> Vec<String> {
327 global_config_path()
328 .ok()
329 .filter(|file| file.exists())
330 .and_then(|file| resolve_list(&file, key).ok())
331 .unwrap_or_default()
332}
333
334pub fn get_list_for_project(project_dir: &Path, key: &str) -> Vec<String> {
336 let project = project_dir.join(".orch.yml");
337 let mut found = if project.exists() {
338 resolve_list(&project, key).unwrap_or_default()
339 } else {
340 Vec::new()
341 };
342
343 for item in get_global_list(key) {
344 if !found.contains(&item) {
345 found.push(item);
346 }
347 }
348
349 found
350}
351
352fn resolve_list(path: &PathBuf, key: &str) -> anyhow::Result<Vec<String>> {
354 watch_file(path);
355
356 let root = load_cached_root(path)?;
357
358 Ok(extract_list(&root, key))
359}
360
361fn extract_list(root: &serde_norway::Value, key: &str) -> Vec<String> {
363 let mut current = root;
364 for part in key.split('.') {
365 match current.get(part) {
366 Some(v) => current = v,
367 None => return vec![],
368 }
369 }
370
371 match current {
372 serde_norway::Value::Sequence(seq) => seq
373 .iter()
374 .filter_map(|item| item.as_str().map(String::from))
375 .collect(),
376 serde_norway::Value::String(s) => {
377 s.split(',')
379 .map(|s| s.trim().to_string())
380 .filter(|s| !s.is_empty())
381 .collect()
382 }
383 _ => vec![],
384 }
385}
386
387pub fn get(key: &str) -> anyhow::Result<String> {
396 let project_path = env::current_dir()
400 .unwrap_or_else(|_| PathBuf::from("."))
401 .join(".orch.yml");
402 if project_path.exists()
403 && let Ok(val) = resolve_key(&project_path, key)
404 {
405 return Ok(val);
406 }
407
408 let global_path = global_config_path()?;
410 if global_path.exists() {
411 return resolve_key(&global_path, key);
412 }
413
414 anyhow::bail!("config key not found: {key}")
415}
416
417pub fn get_for_project(project_dir: &Path, key: &str) -> anyhow::Result<String> {
419 let project_path = project_dir.join(".orch.yml");
420 if project_path.exists()
421 && let Ok(val) = resolve_key(&project_path, key)
422 {
423 return Ok(val);
424 }
425
426 let global_path = global_config_path()?;
427 if global_path.exists() {
428 return resolve_key(&global_path, key);
429 }
430
431 anyhow::bail!("config key not found: {key}")
432}
433
434pub fn get_project_only(project_dir: &Path, key: &str) -> anyhow::Result<String> {
436 let project_path = project_dir.join(".orch.yml");
437 if project_path.exists() {
438 return resolve_key(&project_path, key);
439 }
440
441 anyhow::bail!("config key not found: {key}")
442}
443
444pub fn get_global(key: &str) -> anyhow::Result<String> {
446 let global_path = global_config_path()?;
447 if global_path.exists() {
448 return resolve_key(&global_path, key);
449 }
450
451 anyhow::bail!("config key not found: {key}")
452}
453
454pub fn get_project_paths() -> anyhow::Result<Vec<String>> {
459 let global_path = global_config_path()?;
460
461 if global_path.exists()
462 && let Ok(paths) = resolve_projects_list(&global_path, "projects")
463 && !paths.is_empty()
464 {
465 return Ok(paths);
466 }
467
468 Ok(vec![])
469}
470
471pub fn get_projects_with_paths() -> anyhow::Result<Vec<(String, PathBuf)>> {
476 let paths = get_project_paths()?;
477
478 if !paths.is_empty() {
479 let mut results = Vec::new();
480 for path_str in &paths {
481 let path = PathBuf::from(path_str);
482 let orch_yml = path.join(".orch.yml");
483
484 let config_file = if orch_yml.exists() {
485 orch_yml
486 } else {
487 let legacy = path.join(".orchestrator.yml");
488 if legacy.exists() {
489 legacy
490 } else {
491 continue;
492 }
493 };
494
495 if let Ok(content) = fs::read_to_string(&config_file)
496 && let Ok(doc) = serde_norway::from_str::<serde_norway::Value>(&content)
497 && let Some(repo) = doc
498 .get("gh")
499 .and_then(|gh| gh.get("repo"))
500 .and_then(|r| r.as_str())
501 {
502 results.push((repo.to_string(), path));
503 }
504 }
505
506 if !results.is_empty() {
507 return Ok(results);
508 }
509 }
510
511 if let Ok(repo) = get("gh.repo")
513 && !repo.is_empty()
514 {
515 return Ok(vec![(repo, PathBuf::from("."))]);
516 }
517
518 Ok(vec![])
519}
520
521pub fn get_repo_for_project(project_path: &Path) -> anyhow::Result<String> {
525 let orch_yml = project_path.join(".orch.yml");
526 let config_file = if orch_yml.exists() {
527 orch_yml
528 } else {
529 let legacy = project_path.join(".orchestrator.yml");
530 if legacy.exists() {
531 legacy
532 } else {
533 anyhow::bail!("no .orch.yml found in {}", project_path.display());
534 }
535 };
536
537 let content = fs::read_to_string(&config_file)?;
538 let doc: serde_norway::Value = serde_norway::from_str(&content)?;
539
540 doc.get("gh")
541 .and_then(|gh| gh.get("repo"))
542 .and_then(|r| r.as_str())
543 .map(String::from)
544 .ok_or_else(|| anyhow::anyhow!("gh.repo not set in {}", config_file.display()))
545}
546
547pub fn find_project_root() -> anyhow::Result<PathBuf> {
551 let mut dir = env::current_dir()?;
552
553 loop {
554 if dir.join(".orch.yml").exists() || dir.join(".orchestrator.yml").exists() {
555 return Ok(dir);
556 }
557
558 if !dir.pop() {
559 break;
560 }
561 }
562
563 anyhow::bail!("no .orch.yml found in current directory or parents — run `orch init`")
564}
565
566pub fn get_current_repo() -> anyhow::Result<String> {
571 if let Ok(project_root) = find_project_root()
573 && let Ok(repo) = get_repo_for_project(&project_root)
574 {
575 return Ok(repo);
576 }
577
578 if let Ok(repo) = get("gh.repo")
580 && !repo.is_empty()
581 {
582 return Ok(repo);
583 }
584
585 if let Ok(repo) = get("repo")
587 && !repo.is_empty()
588 {
589 return Ok(repo);
590 }
591
592 anyhow::bail!("could not determine repo — ensure .orch.yml has gh.repo set")
593}
594
595fn resolve_projects_list(path: &PathBuf, key: &str) -> anyhow::Result<Vec<String>> {
597 watch_file(path);
599
600 let root = load_cached_root(path)?;
601
602 Ok(extract_projects_list(&root, key))
603}
604
605fn extract_projects_list(root: &serde_norway::Value, key: &str) -> Vec<String> {
607 let mut current = root;
608 for part in key.split('.') {
609 let Some(next) = current.get(part) else {
611 return vec![];
612 };
613 current = next;
614 }
615
616 match current {
617 serde_norway::Value::Sequence(seq) => {
618 let mut projects = Vec::new();
619 for item in seq {
620 if let serde_norway::Value::String(s) = item {
621 projects.push(s.clone());
622 } else if let serde_norway::Value::Mapping(map) = item {
623 if let Some(serde_norway::Value::String(repo)) = map.get("repo") {
625 projects.push(repo.clone());
626 }
627 }
628 }
629 projects
630 }
631 _ => vec![],
632 }
633}
634
635fn resolve_key(path: &PathBuf, key: &str) -> anyhow::Result<String> {
640 watch_file(path);
642
643 let root = load_cached_root(path)?;
644
645 extract_value(&root, key)
646}
647
648fn extract_value(root: &serde_norway::Value, key: &str) -> anyhow::Result<String> {
650 let mut current = root;
651 for part in key.split('.') {
652 current = current
653 .get(part)
654 .with_context(|| format!("key not found: {key}"))?;
655 }
656
657 match current {
658 serde_norway::Value::String(s) => Ok(s.clone()),
659 serde_norway::Value::Number(n) => Ok(n.to_string()),
660 serde_norway::Value::Bool(b) => Ok(b.to_string()),
661 serde_norway::Value::Null => Ok(String::new()),
662 _ => Ok(serde_norway::to_string(current)?),
663 }
664}
665
666#[cfg(test)]
667mod tests {
668 use super::*;
669 use std::io::Write;
670
671 use notify::event::AccessKind;
672 use notify::event::AccessMode;
673 use notify::event::CreateKind;
674 use notify::event::DataChange;
675 use notify::event::ModifyKind;
676 use tokio::sync::broadcast::Receiver;
677
678 use std::fs::File;
679
680 fn write_yaml(dir: &Path, name: &str, content: &str) -> PathBuf {
681 let path = dir.join(name);
682 let mut f = File::create(&path).unwrap();
683 f.write_all(content.as_bytes()).unwrap();
684 path
685 }
686
687 #[test]
688 fn resolve_simple_key() {
689 let dir = tempfile::tempdir().unwrap();
690 let path = write_yaml(dir.path(), "config.yml", "repo: owner/repo\n");
691 let val = resolve_key(&path, "repo").unwrap();
692 assert_eq!(val, "owner/repo");
693 }
694
695 #[test]
696 fn resolve_nested_key() {
697 let dir = tempfile::tempdir().unwrap();
698 let path = write_yaml(
699 dir.path(),
700 "config.yml",
701 "agents:\n claude:\n model: opus\n",
702 );
703 let val = resolve_key(&path, "agents.claude.model").unwrap();
704 assert_eq!(val, "opus");
705 }
706
707 #[test]
708 fn resolve_boolean_value() {
709 let dir = tempfile::tempdir().unwrap();
710 let path = write_yaml(dir.path(), "config.yml", "enabled: true\n");
711 let val = resolve_key(&path, "enabled").unwrap();
712 assert_eq!(val, "true");
713 }
714
715 #[test]
716 fn resolve_number_value() {
717 let dir = tempfile::tempdir().unwrap();
718 let path = write_yaml(dir.path(), "config.yml", "timeout: 300\n");
719 let val = resolve_key(&path, "timeout").unwrap();
720 assert_eq!(val, "300");
721 }
722
723 #[test]
724 fn resolve_missing_key_errors() {
725 let dir = tempfile::tempdir().unwrap();
726 let path = write_yaml(dir.path(), "config.yml", "repo: owner/repo\n");
727 let result = resolve_key(&path, "missing.key");
728 assert!(result.is_err());
729 }
730
731 #[test]
732 fn resolve_missing_file_errors() {
733 let path = PathBuf::from("/nonexistent/config.yml");
734 let result = resolve_key(&path, "repo");
735 assert!(result.is_err());
736 }
737
738 #[test]
739 fn resolve_projects_list_string_array() {
740 let dir = tempfile::tempdir().unwrap();
741 let path = write_yaml(
742 dir.path(),
743 "config.yml",
744 "projects:\n - owner/repo1\n - owner/repo2\n",
745 );
746 let projects = resolve_projects_list(&path, "projects").unwrap();
747 assert_eq!(projects, vec!["owner/repo1", "owner/repo2"]);
748 }
749
750 #[test]
751 fn resolve_projects_list_map_array() {
752 let dir = tempfile::tempdir().unwrap();
753 let path = write_yaml(
754 dir.path(),
755 "config.yml",
756 "projects:\n - repo: owner/repo1\n project_dir: /path/to/repo1\n - repo: owner/repo2\n project_dir: /path/to/repo2\n",
757 );
758 let projects = resolve_projects_list(&path, "projects").unwrap();
759 assert_eq!(projects, vec!["owner/repo1", "owner/repo2"]);
760 }
761
762 #[test]
763 fn resolve_projects_list_fallback_to_repo() {
764 let dir = tempfile::tempdir().unwrap();
765 let path = write_yaml(dir.path(), "config.yml", "repo: owner/single-repo\n");
766 let projects = resolve_projects_list(&path, "projects").unwrap();
767 assert!(projects.is_empty(), "{projects:?}");
768 }
769
770 #[test]
771 fn extract_projects_list_from_sequence() {
772 let yaml =
773 serde_norway::from_str::<serde_norway::Value>("projects:\n - a\n - b\n - c\n")
774 .unwrap();
775 let projects = extract_projects_list(&yaml, "projects");
776 assert_eq!(projects, vec!["a", "b", "c"]);
777 }
778
779 #[test]
780 fn extract_projects_list_from_mapping_sequence() {
781 let yaml =
782 serde_norway::from_str::<serde_norway::Value>("projects:\n - repo: a\n - repo: b\n")
783 .unwrap();
784 let projects = extract_projects_list(&yaml, "projects");
785 assert_eq!(projects, vec!["a", "b"]);
786 }
787
788 #[test]
789 fn extract_projects_list_empty_for_missing() {
790 let yaml = serde_norway::from_str::<serde_norway::Value>("foo: bar").unwrap();
791 let projects = extract_projects_list(&yaml, "projects");
792 assert!(projects.is_empty(), "{projects:?}");
793 }
794
795 #[test]
796 fn subscribe_receives_change_notifications() {
797 let mut rx = subscribe();
798 let dir = tempfile::tempdir().unwrap();
799 let path = write_yaml(dir.path(), "config.yml", "repo: owner/repo\n");
800
801 assert!(!reload_file(&path));
803
804 loop {
806 match rx.try_recv() {
807 Ok(received_path) if received_path == path => break,
808 Ok(_) => {} Err(e) => panic!("expected config change notification, got error: {e:?}"),
810 }
811 }
812 }
813
814 #[test]
815 fn subscribe_multiple_receivers() {
816 let mut rx1 = subscribe();
817 let mut rx2 = subscribe();
818 let dir = tempfile::tempdir().unwrap();
819 let path = write_yaml(dir.path(), "config.yml", "repo: owner/repo\n");
820
821 assert!(!reload_file(&path));
822
823 let find_path = |rx: &mut Receiver<PathBuf>, expected: &PathBuf| loop {
825 match rx.try_recv() {
826 Ok(p) if &p == expected => return,
827 Ok(_) => {}
828 Err(e) => panic!("expected config change notification, got error: {e:?}"),
829 }
830 };
831 find_path(&mut rx1, &path);
832 find_path(&mut rx2, &path);
833 }
834
835 #[test]
836 fn resolve_list_from_sequence() {
837 let dir = tempfile::tempdir().unwrap();
838 let path = write_yaml(
839 dir.path(),
840 "config.yml",
841 "workflow:\n allowed_tools:\n - Edit\n - Write\n - git\n - npm\n",
842 );
843 let list = resolve_list(&path, "workflow.allowed_tools").unwrap();
844 assert_eq!(list, vec!["Edit", "Write", "git", "npm"]);
845 }
846
847 #[test]
848 fn resolve_list_from_comma_string() {
849 let dir = tempfile::tempdir().unwrap();
850 let path = write_yaml(
851 dir.path(),
852 "config.yml",
853 "workflow:\n allowed_tools: \"Edit,Write,git,npm\"\n",
854 );
855 let list = resolve_list(&path, "workflow.allowed_tools").unwrap();
856 assert_eq!(list, vec!["Edit", "Write", "git", "npm"]);
857 }
858
859 #[test]
860 fn resolve_list_missing_key_returns_empty() {
861 let dir = tempfile::tempdir().unwrap();
862 let path = write_yaml(dir.path(), "config.yml", "foo: bar\n");
863 let list = resolve_list(&path, "workflow.allowed_tools").unwrap();
864 assert!(list.is_empty(), "{list:?}");
865 }
866
867 fn cached_value(path: &PathBuf, key: &str) -> String {
873 extract_value(&load_cached_root(path).unwrap(), key).unwrap()
874 }
875
876 fn cached_projects(path: &PathBuf) -> Vec<String> {
877 extract_projects_list(&load_cached_root(path).unwrap(), "projects")
878 }
879
880 #[test]
881 fn reading_a_config_file_does_not_trigger_a_reload() {
882 assert!(!is_content_change(notify::EventKind::Access(
883 AccessKind::Open(AccessMode::Read)
884 )));
885 assert!(!is_content_change(notify::EventKind::Access(
886 AccessKind::Close(AccessMode::Read)
887 )));
888 assert!(is_content_change(notify::EventKind::Modify(
889 ModifyKind::Data(DataChange::Content)
890 )));
891 assert!(is_content_change(notify::EventKind::Create(
892 CreateKind::File
893 )));
894 }
895
896 #[test]
897 fn invalid_edit_keeps_last_good_values_and_sends_no_notification() {
898 let dir = tempfile::tempdir().unwrap();
899 let path = write_yaml(dir.path(), "config.yml", "engine:\n max_parallel: 8\n");
900 assert!(!reload_file(&path));
901 assert_eq!(cached_value(&path, "engine.max_parallel"), "8");
902
903 let mut rx = subscribe();
904 fs::write(&path, "engine:\n max_parallel: [unclosed\n").unwrap();
905 assert!(reload_file(&path));
906
907 assert_eq!(cached_value(&path, "engine.max_parallel"), "8");
908 assert!(rx.try_recv().is_err(), "a broken edit must not notify");
909
910 fs::write(&path, "engine:\n max_parallel: 12\n").unwrap();
912 assert!(!reload_file(&path));
913 assert_eq!(cached_value(&path, "engine.max_parallel"), "12");
914 }
915
916 #[test]
917 fn adding_a_project_is_visible_after_reload() {
918 let dir = tempfile::tempdir().unwrap();
919 let path = write_yaml(dir.path(), "config.yml", "projects:\n - /srv/one\n");
920 assert_eq!(cached_projects(&path), vec!["/srv/one"]);
921
922 fs::write(&path, "projects:\n - /srv/one\n - /srv/two\n").unwrap();
923 assert!(!reload_file(&path));
924
925 assert_eq!(cached_projects(&path), vec!["/srv/one", "/srv/two"]);
926 }
927
928 #[test]
929 fn repeated_watcher_events_for_one_breakage_log_once() {
930 let dir = tempfile::tempdir().unwrap();
931 let path = write_yaml(dir.path(), "config.yml", "engine:\n max_parallel: 4\n");
932 reload_file(&path);
933
934 fs::write(&path, "engine: [broken\n").unwrap();
935 assert!(reload_file(&path), "first bad read logs");
936 assert!(!reload_file(&path), "same breakage does not log again");
937 }
938
939 #[test]
940 #[serial_test::serial(orch_home)]
941 fn a_project_setting_overrides_the_global_one() {
942 let (home, with, without) = (
943 tempfile::tempdir().unwrap(),
944 tempfile::tempdir().unwrap(),
945 tempfile::tempdir().unwrap(),
946 );
947 write_yaml(home.path(), "config.yml", "workflow:\n sandbox: os\n");
948 write_yaml(with.path(), ".orch.yml", "workflow:\n sandbox: false\n");
949 unsafe { env::set_var("ORCH_HOME", home.path()) };
951
952 let got = (
953 get_for_project(with.path(), "workflow.sandbox").unwrap(),
954 get_for_project(without.path(), "workflow.sandbox").unwrap(),
955 );
956 unsafe { env::remove_var("ORCH_HOME") };
958 assert_eq!(got, ("false".to_string(), "os".to_string()));
959 }
960}