1pub mod projects_yaml;
14
15use anyhow::Context;
16use notify::{Config, RecommendedWatcher, RecursiveMode, Watcher};
17use std::collections::{HashMap, HashSet};
18use std::path::{Path, PathBuf};
19use std::sync::{Arc, Mutex, RwLock};
20use std::time::Duration;
21use tokio::sync::broadcast;
22
23static CACHE: std::sync::LazyLock<RwLock<HashMap<PathBuf, serde_norway::Value>>> =
26 std::sync::LazyLock::new(|| RwLock::new(HashMap::new()));
27
28static WATCHER: std::sync::LazyLock<RwLock<HashMap<PathBuf, ()>>> =
30 std::sync::LazyLock::new(|| RwLock::new(HashMap::new()));
31
32static FILE_WATCHER: std::sync::LazyLock<Arc<Mutex<Option<RecommendedWatcher>>>> =
34 std::sync::LazyLock::new(|| Arc::new(Mutex::new(None)));
35
36static BAD_FILES: std::sync::LazyLock<RwLock<HashSet<PathBuf>>> =
40 std::sync::LazyLock::new(|| RwLock::new(HashSet::new()));
41
42static CHANGE_TX: std::sync::LazyLock<broadcast::Sender<PathBuf>> =
45 std::sync::LazyLock::new(|| {
46 let (tx, _) = broadcast::channel(16);
47 tx
48 });
49
50pub fn subscribe() -> broadcast::Receiver<PathBuf> {
55 CHANGE_TX.subscribe()
56}
57
58pub async fn warm_cache() -> anyhow::Result<()> {
64 let global_path = global_config_path()?;
65 if global_path.exists() {
66 match tokio::fs::read_to_string(&global_path).await {
67 Ok(content) => {
68 if let Ok(parsed) = serde_norway::from_str::<serde_norway::Value>(&content) {
69 if let Ok(mut cache) = CACHE.write() {
70 cache.insert(global_path.clone(), parsed);
71 }
72 watch_file(&global_path);
73 }
74 }
75 Err(e) => tracing::warn!("failed to warm global config cache: {e}"),
76 }
77 }
78
79 let project_path = std::env::current_dir()
80 .unwrap_or_else(|_| PathBuf::from("."))
81 .join(".orch.yml");
82 if project_path.exists() {
83 match tokio::fs::read_to_string(&project_path).await {
84 Ok(content) => {
85 if let Ok(parsed) = serde_norway::from_str::<serde_norway::Value>(&content) {
86 if let Ok(mut cache) = CACHE.write() {
87 cache.insert(project_path.clone(), parsed);
88 }
89 watch_file(&project_path);
90 }
91 }
92 Err(e) => tracing::warn!("failed to warm project config cache: {e}"),
93 }
94 }
95
96 Ok(())
97}
98
99#[cfg(test)]
103pub fn clear_test_cache() {
104 if let Ok(mut cache) = CACHE.write() {
105 cache.clear();
106 }
107}
108
109fn reload_file(path: &PathBuf) -> bool {
118 let parsed = std::fs::read_to_string(path)
119 .map_err(|e| e.to_string())
120 .and_then(|content| {
121 serde_norway::from_str::<serde_norway::Value>(&content).map_err(|e| e.to_string())
122 });
123
124 match parsed {
125 Ok(value) => {
126 if let Ok(mut cache) = CACHE.write() {
127 cache.insert(path.clone(), value);
128 }
129 if let Ok(mut bad) = BAD_FILES.write() {
130 if bad.remove(path) {
131 tracing::info!(path = %path.display(), "config file parses again, reloaded");
132 }
133 }
134 tracing::debug!("config cache refreshed for: {}", path.display());
135 let _ = CHANGE_TX.send(path.clone());
137 false
138 }
139 Err(err) => {
140 let first_failure = BAD_FILES
141 .write()
142 .map(|mut bad| bad.insert(path.clone()))
143 .unwrap_or(false);
144 if first_failure {
145 tracing::error!(
146 path = %path.display(),
147 %err,
148 "config file is invalid, keeping the last good values"
149 );
150 }
151 first_failure
152 }
153 }
154}
155
156fn ensure_watcher() {
158 let mut watcher_guard = FILE_WATCHER.lock().unwrap_or_else(|e| e.into_inner());
159 if watcher_guard.is_some() {
160 return;
161 }
162
163 let watcher = RecommendedWatcher::new(
165 move |res: Result<notify::Event, notify::Error>| {
166 if let Ok(event) = res {
167 if !is_content_change(&event.kind) {
168 return;
169 }
170 for path in event.paths {
171 let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
173
174 if filename == "config.yml" || filename == ".orch.yml" {
175 let _ = reload_file(&path);
176 }
177 }
178 }
179 },
180 Config::default().with_poll_interval(Duration::from_secs(2)),
181 );
182
183 if let Ok(w) = watcher {
184 *watcher_guard = Some(w);
185 }
186}
187
188fn is_content_change(kind: ¬ify::EventKind) -> bool {
191 kind.is_create() || kind.is_modify() || kind.is_remove()
192}
193
194pub fn watch(path: &Path) {
202 if !path.exists() {
203 tracing::debug!(path = %path.display(), "no config file to watch here");
204 return;
205 }
206 watch_file(&path.to_path_buf());
207}
208
209fn watch_file(path: &PathBuf) {
211 ensure_watcher();
213
214 if let Ok(mut watched) = WATCHER.write() {
216 if !watched.contains_key(path) {
217 watched.insert(path.clone(), ());
218
219 if let Ok(mut guard) = FILE_WATCHER.lock() {
221 if let Some(ref mut watcher) = *guard {
222 match watcher.watch(path, RecursiveMode::NonRecursive) {
223 Ok(()) => tracing::debug!("now watching config file: {}", path.display()),
224 Err(e) => tracing::warn!(
225 "failed to register config file watcher for {}: {}",
226 path.display(),
227 e
228 ),
229 }
230 }
231 }
232 }
233 }
234}
235
236fn read_file_to_string(path: &Path) -> anyhow::Result<String> {
237 match tokio::runtime::Handle::try_current() {
238 Ok(handle) if handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread => {
239 Ok(tokio::task::block_in_place(|| {
240 std::fs::read_to_string(path)
241 })?)
242 }
243 _ => Ok(std::fs::read_to_string(path)?),
244 }
245}
246
247fn load_cached_root(path: &PathBuf) -> anyhow::Result<serde_norway::Value> {
248 if let Ok(cache) = CACHE.read() {
249 if let Some(cached) = cache.get(path) {
250 return Ok(cached.clone());
251 }
252 }
253
254 let content =
255 read_file_to_string(path).with_context(|| format!("reading {}", path.display()))?;
256 let parsed: serde_norway::Value =
257 serde_norway::from_str(&content).with_context(|| format!("parsing {}", path.display()))?;
258
259 if let Ok(mut cache) = CACHE.write() {
260 cache.insert(path.clone(), parsed.clone());
261 }
262
263 Ok(parsed)
264}
265
266fn global_config_path() -> anyhow::Result<PathBuf> {
268 crate::home::config_path()
269}
270
271pub fn get_list(key: &str) -> anyhow::Result<Vec<String>> {
289 let project_path = std::env::current_dir()
293 .unwrap_or_else(|_| PathBuf::from("."))
294 .join(".orch.yml");
295 if project_path.exists() {
296 if let Ok(val) = resolve_list(&project_path, key) {
297 if !val.is_empty() {
298 return Ok(val);
299 }
300 }
301 }
302
303 let global_path = global_config_path()?;
305 if global_path.exists() {
306 return resolve_list(&global_path, key);
307 }
308
309 Ok(vec![])
310}
311
312fn resolve_list(path: &PathBuf, key: &str) -> anyhow::Result<Vec<String>> {
314 watch_file(path);
315
316 let root = load_cached_root(path)?;
317
318 extract_list(&root, key)
319}
320
321fn extract_list(root: &serde_norway::Value, key: &str) -> anyhow::Result<Vec<String>> {
323 let mut current = root;
324 for part in key.split('.') {
325 match current.get(part) {
326 Some(v) => current = v,
327 None => return Ok(vec![]),
328 }
329 }
330
331 match current {
332 serde_norway::Value::Sequence(seq) => Ok(seq
333 .iter()
334 .filter_map(|item| item.as_str().map(String::from))
335 .collect()),
336 serde_norway::Value::String(s) => {
337 Ok(s.split(',')
339 .map(|s| s.trim().to_string())
340 .filter(|s| !s.is_empty())
341 .collect())
342 }
343 _ => Ok(vec![]),
344 }
345}
346
347pub fn get(key: &str) -> anyhow::Result<String> {
356 let project_path = std::env::current_dir()
360 .unwrap_or_else(|_| PathBuf::from("."))
361 .join(".orch.yml");
362 if project_path.exists() {
363 if let Ok(val) = resolve_key(&project_path, key) {
364 return Ok(val);
365 }
366 }
367
368 let global_path = global_config_path()?;
370 if global_path.exists() {
371 return resolve_key(&global_path, key);
372 }
373
374 anyhow::bail!("config key not found: {key}")
375}
376
377pub fn get_for_project(project_dir: &std::path::Path, key: &str) -> anyhow::Result<String> {
379 let project_path = project_dir.join(".orch.yml");
380 if project_path.exists() {
381 if let Ok(val) = resolve_key(&project_path, key) {
382 return Ok(val);
383 }
384 }
385
386 let global_path = global_config_path()?;
387 if global_path.exists() {
388 return resolve_key(&global_path, key);
389 }
390
391 anyhow::bail!("config key not found: {key}")
392}
393
394pub fn get_project_paths() -> anyhow::Result<Vec<String>> {
399 let global_path = global_config_path()?;
400
401 if global_path.exists() {
402 if let Ok(paths) = resolve_projects_list(&global_path, "projects") {
403 if !paths.is_empty() {
404 return Ok(paths);
405 }
406 }
407 }
408
409 Ok(vec![])
410}
411
412pub fn get_projects_with_paths() -> anyhow::Result<Vec<(String, std::path::PathBuf)>> {
417 let paths = get_project_paths()?;
418
419 if !paths.is_empty() {
420 let mut results = Vec::new();
421 for path_str in &paths {
422 let path = std::path::PathBuf::from(path_str);
423 let orch_yml = path.join(".orch.yml");
424
425 let config_file = if orch_yml.exists() {
426 orch_yml
427 } else {
428 let legacy = path.join(".orchestrator.yml");
429 if legacy.exists() {
430 legacy
431 } else {
432 continue;
433 }
434 };
435
436 if let Ok(content) = std::fs::read_to_string(&config_file) {
437 if let Ok(doc) = serde_norway::from_str::<serde_norway::Value>(&content) {
438 if let Some(repo) = doc
439 .get("gh")
440 .and_then(|gh| gh.get("repo"))
441 .and_then(|r| r.as_str())
442 {
443 results.push((repo.to_string(), path));
444 }
445 }
446 }
447 }
448
449 if !results.is_empty() {
450 return Ok(results);
451 }
452 }
453
454 if let Ok(repo) = get("gh.repo") {
456 if !repo.is_empty() {
457 return Ok(vec![(repo, std::path::PathBuf::from("."))]);
458 }
459 }
460
461 Ok(vec![])
462}
463
464pub fn get_repo_for_project(project_path: &std::path::Path) -> anyhow::Result<String> {
468 let orch_yml = project_path.join(".orch.yml");
469 let config_file = if orch_yml.exists() {
470 orch_yml
471 } else {
472 let legacy = project_path.join(".orchestrator.yml");
473 if legacy.exists() {
474 legacy
475 } else {
476 anyhow::bail!("no .orch.yml found in {}", project_path.display());
477 }
478 };
479
480 let content = std::fs::read_to_string(&config_file)?;
481 let doc: serde_norway::Value = serde_norway::from_str(&content)?;
482
483 doc.get("gh")
484 .and_then(|gh| gh.get("repo"))
485 .and_then(|r| r.as_str())
486 .map(String::from)
487 .ok_or_else(|| anyhow::anyhow!("gh.repo not set in {}", config_file.display()))
488}
489
490pub fn find_project_root() -> anyhow::Result<std::path::PathBuf> {
494 let mut dir = std::env::current_dir()?;
495
496 loop {
497 if dir.join(".orch.yml").exists() || dir.join(".orchestrator.yml").exists() {
498 return Ok(dir);
499 }
500
501 if !dir.pop() {
502 break;
503 }
504 }
505
506 anyhow::bail!("no .orch.yml found in current directory or parents — run `orch init`")
507}
508
509pub fn get_current_repo() -> anyhow::Result<String> {
514 if let Ok(project_root) = find_project_root() {
516 if let Ok(repo) = get_repo_for_project(&project_root) {
517 return Ok(repo);
518 }
519 }
520
521 if let Ok(repo) = get("gh.repo") {
523 if !repo.is_empty() {
524 return Ok(repo);
525 }
526 }
527
528 if let Ok(repo) = get("repo") {
530 if !repo.is_empty() {
531 return Ok(repo);
532 }
533 }
534
535 anyhow::bail!("could not determine repo — ensure .orch.yml has gh.repo set")
536}
537
538#[derive(Debug, Clone)]
540pub struct SkillConfig {
541 pub repo: String,
543}
544
545pub fn get_skills() -> anyhow::Result<Vec<SkillConfig>> {
556 let global_path = global_config_path()?;
557
558 if !global_path.exists() {
559 return Ok(vec![]);
560 }
561
562 let root = load_cached_root(&global_path)?;
563
564 extract_skills_list(&root)
565}
566
567fn extract_skills_list(root: &serde_norway::Value) -> anyhow::Result<Vec<SkillConfig>> {
569 let Some(serde_norway::Value::Sequence(seq)) = root.get("skills") else {
570 return Ok(vec![]);
571 };
572
573 let mut skills = Vec::new();
574 for item in seq {
575 if let serde_norway::Value::Mapping(map) = item {
576 let repo = map
577 .get("repo")
578 .and_then(|v| v.as_str())
579 .map(String::from)
580 .unwrap_or_default();
581
582 if !repo.is_empty() {
583 skills.push(SkillConfig { repo });
584 }
585 }
586 }
587
588 Ok(skills)
589}
590
591fn resolve_projects_list(path: &PathBuf, key: &str) -> anyhow::Result<Vec<String>> {
593 watch_file(path);
595
596 let root = load_cached_root(path)?;
597
598 match extract_projects_list(&root, key) {
600 Ok(projects) => Ok(projects),
601 Err(_) => Ok(vec![]),
602 }
603}
604
605fn extract_projects_list(root: &serde_norway::Value, key: &str) -> anyhow::Result<Vec<String>> {
607 let mut current = root;
608 for part in key.split('.') {
609 let next = match current.get(part) {
611 Some(v) => v,
612 None => return Ok(vec![]),
613 };
614 current = next;
615 }
616
617 match current {
618 serde_norway::Value::Sequence(seq) => {
619 let mut projects = Vec::new();
620 for item in seq {
621 if let serde_norway::Value::String(s) = item {
622 projects.push(s.clone());
623 } else if let serde_norway::Value::Mapping(map) = item {
624 if let Some(serde_norway::Value::String(repo)) = map.get("repo") {
626 projects.push(repo.clone());
627 }
628 }
629 }
630 Ok(projects)
631 }
632 _ => Ok(vec![]),
633 }
634}
635
636fn resolve_key(path: &PathBuf, key: &str) -> anyhow::Result<String> {
641 watch_file(path);
643
644 let root = load_cached_root(path)?;
645
646 extract_value(&root, key)
647}
648
649fn extract_value(root: &serde_norway::Value, key: &str) -> anyhow::Result<String> {
651 let mut current = root;
652 for part in key.split('.') {
653 current = current
654 .get(part)
655 .with_context(|| format!("key not found: {key}"))?;
656 }
657
658 match current {
659 serde_norway::Value::String(s) => Ok(s.clone()),
660 serde_norway::Value::Number(n) => Ok(n.to_string()),
661 serde_norway::Value::Bool(b) => Ok(b.to_string()),
662 serde_norway::Value::Null => Ok(String::new()),
663 _ => Ok(serde_norway::to_string(current)?),
664 }
665}
666
667#[cfg(test)]
668mod tests {
669 use super::*;
670 use std::io::Write;
671
672 fn write_yaml(dir: &std::path::Path, name: &str, content: &str) -> PathBuf {
673 let path = dir.join(name);
674 let mut f = std::fs::File::create(&path).unwrap();
675 f.write_all(content.as_bytes()).unwrap();
676 path
677 }
678
679 #[test]
680 fn resolve_simple_key() {
681 let dir = tempfile::tempdir().unwrap();
682 let path = write_yaml(dir.path(), "config.yml", "repo: owner/repo\n");
683 let val = resolve_key(&path, "repo").unwrap();
684 assert_eq!(val, "owner/repo");
685 }
686
687 #[test]
688 fn resolve_nested_key() {
689 let dir = tempfile::tempdir().unwrap();
690 let path = write_yaml(
691 dir.path(),
692 "config.yml",
693 "agents:\n claude:\n model: opus\n",
694 );
695 let val = resolve_key(&path, "agents.claude.model").unwrap();
696 assert_eq!(val, "opus");
697 }
698
699 #[test]
700 fn resolve_boolean_value() {
701 let dir = tempfile::tempdir().unwrap();
702 let path = write_yaml(dir.path(), "config.yml", "enabled: true\n");
703 let val = resolve_key(&path, "enabled").unwrap();
704 assert_eq!(val, "true");
705 }
706
707 #[test]
708 fn resolve_number_value() {
709 let dir = tempfile::tempdir().unwrap();
710 let path = write_yaml(dir.path(), "config.yml", "timeout: 300\n");
711 let val = resolve_key(&path, "timeout").unwrap();
712 assert_eq!(val, "300");
713 }
714
715 #[test]
716 fn resolve_missing_key_errors() {
717 let dir = tempfile::tempdir().unwrap();
718 let path = write_yaml(dir.path(), "config.yml", "repo: owner/repo\n");
719 let result = resolve_key(&path, "missing.key");
720 assert!(result.is_err());
721 }
722
723 #[test]
724 fn resolve_missing_file_errors() {
725 let path = PathBuf::from("/nonexistent/config.yml");
726 let result = resolve_key(&path, "repo");
727 assert!(result.is_err());
728 }
729
730 #[test]
731 fn resolve_projects_list_string_array() {
732 let dir = tempfile::tempdir().unwrap();
733 let path = write_yaml(
734 dir.path(),
735 "config.yml",
736 "projects:\n - owner/repo1\n - owner/repo2\n",
737 );
738 let projects = resolve_projects_list(&path, "projects").unwrap();
739 assert_eq!(projects, vec!["owner/repo1", "owner/repo2"]);
740 }
741
742 #[test]
743 fn resolve_projects_list_map_array() {
744 let dir = tempfile::tempdir().unwrap();
745 let path = write_yaml(
746 dir.path(),
747 "config.yml",
748 "projects:\n - repo: owner/repo1\n project_dir: /path/to/repo1\n - repo: owner/repo2\n project_dir: /path/to/repo2\n",
749 );
750 let projects = resolve_projects_list(&path, "projects").unwrap();
751 assert_eq!(projects, vec!["owner/repo1", "owner/repo2"]);
752 }
753
754 #[test]
755 fn resolve_projects_list_fallback_to_repo() {
756 let dir = tempfile::tempdir().unwrap();
757 let path = write_yaml(dir.path(), "config.yml", "repo: owner/single-repo\n");
758 let projects = resolve_projects_list(&path, "projects").unwrap();
759 assert!(projects.is_empty());
760 }
761
762 #[test]
763 fn extract_projects_list_from_sequence() {
764 let yaml =
765 serde_norway::from_str::<serde_norway::Value>("projects:\n - a\n - b\n - c\n")
766 .unwrap();
767 let projects = extract_projects_list(&yaml, "projects").unwrap();
768 assert_eq!(projects, vec!["a", "b", "c"]);
769 }
770
771 #[test]
772 fn extract_projects_list_from_mapping_sequence() {
773 let yaml =
774 serde_norway::from_str::<serde_norway::Value>("projects:\n - repo: a\n - repo: b\n")
775 .unwrap();
776 let projects = extract_projects_list(&yaml, "projects").unwrap();
777 assert_eq!(projects, vec!["a", "b"]);
778 }
779
780 #[test]
781 fn extract_projects_list_empty_for_missing() {
782 let yaml = serde_norway::from_str::<serde_norway::Value>("foo: bar").unwrap();
783 let projects = extract_projects_list(&yaml, "projects").unwrap();
784 assert!(projects.is_empty());
785 }
786
787 #[test]
788 fn subscribe_receives_change_notifications() {
789 let mut rx = subscribe();
790 let dir = tempfile::tempdir().unwrap();
791 let path = write_yaml(dir.path(), "config.yml", "repo: owner/repo\n");
792
793 assert!(!reload_file(&path));
795
796 loop {
798 match rx.try_recv() {
799 Ok(received_path) if received_path == path => break,
800 Ok(_) => continue, Err(e) => panic!("expected config change notification, got error: {e:?}"),
802 }
803 }
804 }
805
806 #[test]
807 fn subscribe_multiple_receivers() {
808 let mut rx1 = subscribe();
809 let mut rx2 = subscribe();
810 let dir = tempfile::tempdir().unwrap();
811 let path = write_yaml(dir.path(), "config.yml", "repo: owner/repo\n");
812
813 assert!(!reload_file(&path));
814
815 let find_path = |rx: &mut tokio::sync::broadcast::Receiver<PathBuf>, expected: &PathBuf| loop {
817 match rx.try_recv() {
818 Ok(p) if &p == expected => return,
819 Ok(_) => continue,
820 Err(e) => panic!("expected config change notification, got error: {e:?}"),
821 }
822 };
823 find_path(&mut rx1, &path);
824 find_path(&mut rx2, &path);
825 }
826
827 #[test]
828 fn resolve_list_from_sequence() {
829 let dir = tempfile::tempdir().unwrap();
830 let path = write_yaml(
831 dir.path(),
832 "config.yml",
833 "workflow:\n allowed_tools:\n - Edit\n - Write\n - git\n - npm\n",
834 );
835 let list = resolve_list(&path, "workflow.allowed_tools").unwrap();
836 assert_eq!(list, vec!["Edit", "Write", "git", "npm"]);
837 }
838
839 #[test]
840 fn resolve_list_from_comma_string() {
841 let dir = tempfile::tempdir().unwrap();
842 let path = write_yaml(
843 dir.path(),
844 "config.yml",
845 "workflow:\n allowed_tools: \"Edit,Write,git,npm\"\n",
846 );
847 let list = resolve_list(&path, "workflow.allowed_tools").unwrap();
848 assert_eq!(list, vec!["Edit", "Write", "git", "npm"]);
849 }
850
851 #[test]
852 fn resolve_list_missing_key_returns_empty() {
853 let dir = tempfile::tempdir().unwrap();
854 let path = write_yaml(dir.path(), "config.yml", "foo: bar\n");
855 let list = resolve_list(&path, "workflow.allowed_tools").unwrap();
856 assert!(list.is_empty());
857 }
858
859 #[test]
860 fn extract_skills_list_from_sequence() {
861 let yaml = serde_norway::from_str::<serde_norway::Value>(
862 "skills:\n - repo: owner/skills1\n - repo: owner/skills2\n",
863 )
864 .unwrap();
865 let skills = extract_skills_list(&yaml).unwrap();
866 assert_eq!(skills.len(), 2);
867 assert_eq!(skills[0].repo, "owner/skills1");
868 assert_eq!(skills[1].repo, "owner/skills2");
869 }
870
871 #[test]
872 fn extract_skills_list_single_repo() {
873 let yaml =
874 serde_norway::from_str::<serde_norway::Value>("skills:\n - repo: owner/skills\n")
875 .unwrap();
876 let skills = extract_skills_list(&yaml).unwrap();
877 assert_eq!(skills.len(), 1);
878 assert_eq!(skills[0].repo, "owner/skills");
879 }
880
881 fn cached_value(path: &PathBuf, key: &str) -> String {
887 extract_value(&load_cached_root(path).unwrap(), key).unwrap()
888 }
889
890 fn cached_projects(path: &PathBuf) -> Vec<String> {
891 extract_projects_list(&load_cached_root(path).unwrap(), "projects").unwrap()
892 }
893
894 #[test]
895 fn reading_a_config_file_does_not_trigger_a_reload() {
896 use notify::event::{AccessKind, AccessMode, CreateKind, DataChange, ModifyKind};
897 assert!(!is_content_change(¬ify::EventKind::Access(
898 AccessKind::Open(AccessMode::Read)
899 )));
900 assert!(!is_content_change(¬ify::EventKind::Access(
901 AccessKind::Close(AccessMode::Read)
902 )));
903 assert!(is_content_change(¬ify::EventKind::Modify(
904 ModifyKind::Data(DataChange::Content)
905 )));
906 assert!(is_content_change(¬ify::EventKind::Create(
907 CreateKind::File
908 )));
909 }
910
911 #[test]
912 fn invalid_edit_keeps_last_good_values_and_sends_no_notification() {
913 let dir = tempfile::tempdir().unwrap();
914 let path = write_yaml(dir.path(), "config.yml", "engine:\n max_parallel: 8\n");
915 assert!(!reload_file(&path));
916 assert_eq!(cached_value(&path, "engine.max_parallel"), "8");
917
918 let mut rx = subscribe();
919 std::fs::write(&path, "engine:\n max_parallel: [unclosed\n").unwrap();
920 assert!(reload_file(&path));
921
922 assert_eq!(cached_value(&path, "engine.max_parallel"), "8");
923 assert!(rx.try_recv().is_err(), "a broken edit must not notify");
924
925 std::fs::write(&path, "engine:\n max_parallel: 12\n").unwrap();
927 assert!(!reload_file(&path));
928 assert_eq!(cached_value(&path, "engine.max_parallel"), "12");
929 }
930
931 #[test]
932 fn adding_a_project_is_visible_after_reload() {
933 let dir = tempfile::tempdir().unwrap();
934 let path = write_yaml(dir.path(), "config.yml", "projects:\n - /srv/one\n");
935 assert_eq!(cached_projects(&path), vec!["/srv/one"]);
936
937 std::fs::write(&path, "projects:\n - /srv/one\n - /srv/two\n").unwrap();
938 assert!(!reload_file(&path));
939
940 assert_eq!(cached_projects(&path), vec!["/srv/one", "/srv/two"]);
941 }
942
943 #[test]
944 fn repeated_watcher_events_for_one_breakage_log_once() {
945 let dir = tempfile::tempdir().unwrap();
946 let path = write_yaml(dir.path(), "config.yml", "engine:\n max_parallel: 4\n");
947 reload_file(&path);
948
949 std::fs::write(&path, "engine: [broken\n").unwrap();
950 assert!(reload_file(&path), "first bad read logs");
951 assert!(!reload_file(&path), "same breakage does not log again");
952 }
953
954 #[test]
955 #[serial_test::serial(orch_home)]
956 fn a_project_setting_overrides_the_global_one() {
957 let (home, with, without) = (
958 tempfile::tempdir().unwrap(),
959 tempfile::tempdir().unwrap(),
960 tempfile::tempdir().unwrap(),
961 );
962 write_yaml(home.path(), "config.yml", "workflow:\n sandbox: os\n");
963 write_yaml(with.path(), ".orch.yml", "workflow:\n sandbox: false\n");
964 std::env::set_var("ORCH_HOME", home.path());
965
966 let got = (
967 get_for_project(with.path(), "workflow.sandbox").unwrap(),
968 get_for_project(without.path(), "workflow.sandbox").unwrap(),
969 );
970 std::env::remove_var("ORCH_HOME");
971 assert_eq!(got, ("false".to_string(), "os".to_string()));
972 }
973
974 #[test]
975 fn extract_skills_list_empty_for_missing() {
976 let yaml = serde_norway::from_str::<serde_norway::Value>("foo: bar").unwrap();
977 let skills = extract_skills_list(&yaml).unwrap();
978 assert!(skills.is_empty());
979 }
980}