1use crate::daemon_id::DaemonId;
2use crate::deprecated_at;
3use crate::error::{ConfigParseError, DependencyError, FileError, find_similar_daemon};
4use crate::settings::SettingsPartial;
5use crate::settings::settings;
6use crate::state_file::StateFile;
7use crate::{Result, env};
8use indexmap::IndexMap;
9use miette::Context;
10use once_cell::sync::Lazy;
11use schemars::JsonSchema;
12use std::collections::{HashMap, HashSet};
13use std::path::{Path, PathBuf};
14use std::sync::Mutex as StdMutex;
15use std::time::SystemTime;
16
17pub use crate::config_types::{
19 CpuLimit, CronRetrigger, Dir, HealthCmd, HealthHttp, HealthPort, MemoryLimit, OnOutputHook,
20 PitchforkTomlAuto, PitchforkTomlCron, PitchforkTomlHooks, PortBump, PortConfig, ProxyConfig,
21 ProxyIdleTimeout, ProxyProtocol, ProxyTlsMode, ReadyCmd, ReadyHttp, ReadyOutput, ReadyPort,
22 Retry, StopConfig, StopSignal, WatchMode,
23};
24
25#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, JsonSchema)]
33pub struct SlugEntryRaw {
34 #[serde(default, skip_serializing_if = "Option::is_none")]
36 pub dir: Option<String>,
37 #[serde(default, skip_serializing_if = "Option::is_none")]
39 pub namespace: Option<String>,
40 #[serde(skip_serializing_if = "Option::is_none", default)]
42 pub daemon: Option<String>,
43}
44
45#[derive(Debug, Clone)]
47pub struct SlugEntry {
48 pub dir: Option<PathBuf>,
50 pub namespace: Option<String>,
52 pub daemon: Option<String>,
54}
55
56impl SlugEntry {
57 pub fn resolve_dir(&self) -> Option<PathBuf> {
60 self.dir.clone().or_else(|| {
61 self.namespace.as_ref().and_then(|ns| {
62 let namespaces = PitchforkToml::read_global_namespaces();
63 namespaces.get(ns).map(|entry| entry.dir.clone())
64 })
65 })
66 }
67
68 pub fn resolve_namespace(&self) -> Option<String> {
71 self.namespace.clone().or_else(|| {
72 self.resolve_dir()
73 .and_then(|dir| PitchforkToml::namespace_for_dir(&dir).ok())
74 })
75 }
76}
77
78#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, JsonSchema)]
88pub struct GroupEntryRaw {
89 #[serde(default, skip_serializing_if = "Vec::is_empty")]
91 #[schemars(with = "Vec<DaemonId>")]
92 pub daemons: Vec<String>,
93 #[serde(default, skip_serializing_if = "Vec::is_empty")]
95 pub groups: Vec<String>,
96}
97
98#[derive(Debug, Clone, Default)]
104pub struct GroupEntry {
105 pub daemons: Vec<DaemonId>,
106 pub groups: Vec<String>,
107}
108
109pub fn expand_group(groups: &IndexMap<String, GroupEntry>, name: &str) -> Result<Vec<DaemonId>> {
116 fn visit(
117 groups: &IndexMap<String, GroupEntry>,
118 name: &str,
119 path: &mut Vec<String>,
120 done: &mut HashSet<String>,
121 seen: &mut HashSet<DaemonId>,
122 out: &mut Vec<DaemonId>,
123 ) -> Result<()> {
124 if done.contains(name) {
127 return Ok(());
128 }
129 let Some(group) = groups.get(name) else {
130 let suggestion = find_similar_daemon(name, groups.keys().map(|s| s.as_str()));
131 return Err(match path.last() {
132 Some(parent) => miette::miette!(
133 "group '{parent}' includes undefined group '{name}'{}",
134 suggestion.map(|s| format!(", {s}")).unwrap_or_default()
135 ),
136 None => miette::miette!(
137 "group '{name}' not found in configuration{}",
138 suggestion.map(|s| format!(", {s}")).unwrap_or_default()
139 ),
140 });
141 };
142 if path.iter().any(|p| p == name) {
143 return Err(miette::miette!(
144 "group include cycle: {} -> {name}",
145 path.join(" -> ")
146 ));
147 }
148 path.push(name.to_string());
149 for included in &group.groups {
150 visit(groups, included, path, done, seen, out)?;
151 }
152 path.pop();
153 for id in &group.daemons {
154 if seen.insert(id.clone()) {
155 out.push(id.clone());
156 }
157 }
158 done.insert(name.to_string());
159 Ok(())
160 }
161
162 let mut out = Vec::new();
163 visit(
164 groups,
165 name,
166 &mut Vec::new(),
167 &mut HashSet::new(),
168 &mut HashSet::new(),
169 &mut out,
170 )?;
171 Ok(out)
172}
173
174#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, JsonSchema)]
180pub struct NamespaceEntryRaw {
181 pub dir: String,
183 #[serde(default, skip_serializing_if = "Vec::is_empty")]
185 pub config: Vec<String>,
186 #[serde(default, skip_serializing_if = "Option::is_none")]
190 pub label: Option<String>,
191}
192
193#[derive(Debug, Clone)]
195pub struct NamespaceEntry {
196 pub dir: PathBuf,
198 pub config: Vec<PathBuf>,
199 pub label: Option<String>,
201}
202
203#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
205struct PitchforkTomlRaw {
206 #[serde(skip_serializing_if = "Option::is_none", default)]
207 pub namespace: Option<String>,
208 #[serde(skip_serializing_if = "Option::is_none", default)]
210 pub worktree_label: Option<String>,
211 #[serde(default)]
212 pub daemons: IndexMap<String, PitchforkTomlDaemonRaw>,
213 #[serde(skip_serializing_if = "Option::is_none", default)]
216 pub env: Option<IndexMap<String, String>>,
217 #[serde(default)]
218 pub settings: Option<SettingsPartial>,
219 #[serde(skip_serializing_if = "IndexMap::is_empty", default)]
222 pub slugs: IndexMap<String, SlugEntryRaw>,
223 #[serde(skip_serializing_if = "IndexMap::is_empty", default)]
225 pub groups: IndexMap<String, GroupEntryRaw>,
226 #[serde(skip_serializing_if = "IndexMap::is_empty", default)]
229 pub namespaces: IndexMap<String, NamespaceEntryRaw>,
230}
231
232#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
237pub struct PitchforkTomlDaemonLogs {
238 #[serde(skip_serializing_if = "Option::is_none", default)]
241 pub log_format: Option<String>,
242 #[serde(skip_serializing_if = "Option::is_none", default)]
244 pub time_retention: Option<String>,
245 #[serde(skip_serializing_if = "Option::is_none", default)]
247 pub line_retention: Option<i64>,
248 #[serde(skip_serializing_if = "Option::is_none", default)]
250 pub archive_hook: Option<String>,
251}
252
253#[derive(Debug, serde::Serialize, serde::Deserialize)]
260struct PitchforkTomlDaemonRaw {
261 pub run: RunCommand,
262 #[serde(skip_serializing_if = "Vec::is_empty", default)]
263 pub auto: Vec<PitchforkTomlAuto>,
264 #[serde(skip_serializing_if = "Option::is_none", default)]
265 pub oneshot: Option<bool>,
266 #[serde(skip_serializing_if = "Option::is_none", default)]
267 pub cron: Option<PitchforkTomlCron>,
268 #[serde(default)]
269 pub retry: Retry,
270 #[serde(skip_serializing_if = "Option::is_none", default)]
271 pub ready_delay: Option<u64>,
272 #[serde(skip_serializing_if = "Option::is_none", default)]
273 pub ready_output: Option<ReadyOutput>,
274 #[serde(skip_serializing_if = "Option::is_none", default)]
275 pub ready_http: Option<ReadyHttp>,
276 #[serde(skip_serializing_if = "Option::is_none", default)]
277 pub ready_port: Option<ReadyPort>,
278 #[serde(skip_serializing_if = "Option::is_none", default)]
279 pub ready_cmd: Option<ReadyCmd>,
280 #[serde(skip_serializing_if = "Option::is_none", default)]
281 pub health_cmd: Option<HealthCmd>,
282 #[serde(skip_serializing_if = "Option::is_none", default)]
283 pub health_http: Option<HealthHttp>,
284 #[serde(skip_serializing_if = "Option::is_none", default)]
285 pub health_port: Option<HealthPort>,
286 #[serde(skip_serializing_if = "Option::is_none", default)]
288 pub port: Option<PortConfig>,
289 #[serde(skip_serializing_if = "Option::is_none", default)]
291 pub proxy: Option<ProxyConfig>,
292 #[serde(skip_serializing_if = "Vec::is_empty", default)]
294 pub expected_port: Vec<u16>,
295 #[serde(skip_serializing_if = "Option::is_none", default)]
297 pub auto_bump_port: Option<bool>,
298 #[serde(skip_serializing_if = "Option::is_none", default)]
300 pub port_bump_attempts: Option<u32>,
301 #[serde(skip_serializing_if = "Option::is_none", default)]
303 pub proxy_tls: Option<ProxyTlsMode>,
304 #[serde(skip_serializing_if = "Option::is_none", default)]
306 pub proxy_protocol: Option<ProxyProtocol>,
307 #[serde(skip_serializing_if = "Option::is_none", default)]
309 pub proxy_tls_port: Option<u16>,
310 #[serde(skip_serializing_if = "Option::is_none", default)]
313 pub proxy_port: Option<u16>,
314 #[serde(skip_serializing_if = "Option::is_none", default)]
316 pub proxy_idle_timeout: Option<ProxyIdleTimeout>,
317 #[serde(skip_serializing_if = "Option::is_none", default)]
318 pub boot_start: Option<bool>,
319 #[serde(skip_serializing_if = "Vec::is_empty", default)]
320 pub depends: Vec<String>,
321 #[serde(skip_serializing_if = "Vec::is_empty", default)]
322 pub watch: Vec<String>,
323 #[serde(skip_serializing_if = "Option::is_none", default)]
324 pub watch_mode: Option<WatchMode>,
325 #[serde(skip_serializing_if = "Option::is_none", default)]
326 pub dir: Option<String>,
327 #[serde(skip_serializing_if = "Option::is_none", default)]
328 pub env: Option<IndexMap<String, String>>,
329 #[serde(skip_serializing_if = "Vec::is_empty", default)]
330 pub env_file: Vec<String>,
331 #[serde(skip_serializing_if = "Option::is_none", default)]
332 pub hooks: Option<PitchforkTomlHooks>,
333 #[serde(skip_serializing_if = "Option::is_none", default)]
334 pub mise: Option<bool>,
335 #[serde(skip_serializing_if = "Option::is_none", default)]
338 pub user: Option<String>,
339 #[serde(skip_serializing_if = "Option::is_none", default)]
341 pub memory_limit: Option<MemoryLimit>,
342 #[serde(skip_serializing_if = "Option::is_none", default)]
344 pub cpu_limit: Option<CpuLimit>,
345 #[serde(skip_serializing_if = "Option::is_none", default)]
347 pub stop_signal: Option<StopConfig>,
348 #[serde(skip_serializing_if = "Option::is_none", default)]
350 pub pty: Option<bool>,
351 #[serde(skip_serializing_if = "Option::is_none", default)]
354 pub time_retention: Option<String>,
355 #[serde(skip_serializing_if = "Option::is_none", default)]
358 pub line_retention: Option<i64>,
359 #[serde(skip_serializing_if = "Option::is_none", default)]
362 pub archive_hook: Option<String>,
363 #[serde(skip_serializing_if = "Option::is_none", default)]
365 pub logs: Option<PitchforkTomlDaemonLogs>,
366}
367
368#[derive(Debug, Clone, Default, JsonSchema)]
373#[schemars(title = "Pitchfork Configuration")]
374pub struct PitchforkToml {
375 #[serde(default)]
377 pub daemons: IndexMap<DaemonId, PitchforkTomlDaemon>,
378 #[serde(skip_serializing_if = "Option::is_none", default)]
382 pub env: Option<IndexMap<String, String>>,
383 pub namespace: Option<String>,
388 #[schemars(default, with = "Option<String>")]
392 pub worktree_label: Option<String>,
393 #[serde(default)]
402 pub(crate) settings: SettingsPartial,
403 #[schemars(default, with = "IndexMap<String, SlugEntryRaw>")]
408 pub slugs: IndexMap<String, SlugEntry>,
409 #[schemars(default, with = "IndexMap<String, GroupEntryRaw>")]
411 pub groups: IndexMap<String, GroupEntry>,
412 #[schemars(default, with = "IndexMap<String, NamespaceEntryRaw>")]
415 pub namespaces: IndexMap<String, NamespaceEntry>,
416 #[schemars(skip)]
417 pub path: Option<PathBuf>,
418 #[schemars(skip)]
426 pub(crate) foreign_env: IndexMap<DaemonId, Option<IndexMap<String, String>>>,
427}
428
429impl PitchforkToml {
430 pub(crate) fn env_for(&self, id: &DaemonId) -> Option<&IndexMap<String, String>> {
433 self.foreign_env
434 .get(id)
435 .map_or(self.env.as_ref(), |env| env.as_ref())
436 }
437}
438
439pub fn is_global_config(path: &Path) -> bool {
440 path == *env::PITCHFORK_GLOBAL_CONFIG_USER || path == *env::PITCHFORK_GLOBAL_CONFIG_SYSTEM
441}
442
443pub(crate) fn is_dot_config_pitchfork(path: &Path) -> bool {
444 path.ends_with(".config/pitchfork.toml") || path.ends_with(".config/pitchfork.local.toml")
445}
446
447fn parse_namespace_override_from_content(path: &Path, content: &str) -> Result<Option<String>> {
448 use toml::Value;
449
450 let doc: Value = toml::from_str(content)
451 .map_err(|e| ConfigParseError::from_toml_error(path, content.to_string(), e))?;
452 let Some(value) = doc.get("namespace") else {
453 return Ok(None);
454 };
455
456 match value {
457 Value::String(s) => Ok(Some(s.clone())),
458 _ => Err(ConfigParseError::InvalidNamespace {
459 path: path.to_path_buf(),
460 namespace: value.to_string(),
461 reason: "top-level 'namespace' must be a string".to_string(),
462 }
463 .into()),
464 }
465}
466
467fn read_namespace_override_from_file(path: &Path) -> Result<Option<String>> {
468 if !path.exists() {
469 return Ok(None);
470 }
471 let content = std::fs::read_to_string(path).map_err(|e| FileError::ReadError {
472 path: path.to_path_buf(),
473 source: e,
474 })?;
475 parse_namespace_override_from_content(path, &content)
476}
477
478pub fn project_dir_for_config(path: &Path) -> Option<PathBuf> {
479 crate::extra_configs::project_dir(path).or_else(|| {
480 if is_dot_config_pitchfork(path) {
481 path.parent().and_then(Path::parent).map(Path::to_path_buf)
482 } else {
483 path.parent().map(Path::to_path_buf)
484 }
485 })
486}
487
488fn project_config_family(path: &Path) -> Vec<PathBuf> {
489 let Some(dir) = project_dir_for_config(path) else {
490 return vec![path.to_path_buf()];
491 };
492 vec![
493 dir.join(".config/pitchfork.toml"),
494 dir.join(".config/pitchfork.local.toml"),
495 dir.join("pitchfork.toml"),
496 dir.join("pitchfork.local.toml"),
497 ]
498}
499
500fn directory_namespace_override(
503 path: &Path,
504 content_override: Option<&str>,
505) -> Result<Option<String>> {
506 if is_global_config(path) {
507 return match content_override {
508 Some(content) => parse_namespace_override_from_content(path, content),
509 None => read_namespace_override_from_file(path),
510 };
511 }
512
513 let mut selected: Option<(String, PathBuf)> = None;
514 for candidate in project_config_family(path) {
515 let explicit = if candidate == path {
516 match content_override {
517 Some(content) => parse_namespace_override_from_content(&candidate, content)?,
518 None => read_namespace_override_from_file(&candidate)?,
519 }
520 } else {
521 read_namespace_override_from_file(&candidate)?
522 };
523 let Some(namespace) = explicit else { continue };
524 if let Some((selected_namespace, selected_path)) = &selected
525 && selected_namespace != &namespace
526 {
527 return Err(ConfigParseError::InvalidNamespace {
528 path: candidate,
529 namespace,
530 reason: format!(
531 "namespace does not match directory-level namespace '{}' declared in {}",
532 selected_namespace,
533 selected_path.display()
534 ),
535 }
536 .into());
537 }
538 selected = Some((namespace, candidate));
539 }
540 Ok(selected.map(|(namespace, _)| namespace))
541}
542
543fn validate_namespace(path: &Path, namespace: &str) -> Result<String> {
544 if let Err(e) = DaemonId::try_new(namespace, "probe") {
545 return Err(ConfigParseError::InvalidNamespace {
546 path: path.to_path_buf(),
547 namespace: namespace.to_string(),
548 reason: e.to_string(),
549 }
550 .into());
551 }
552 Ok(namespace.to_string())
553}
554
555fn derive_namespace_from_dir(path: &Path) -> Result<String> {
556 let dir_for_namespace = project_dir_for_config(path);
557 if let Some(namespace) = dir_for_namespace
558 .as_deref()
559 .and_then(crate::extra_configs::namespace_for_dir)
560 {
561 return validate_namespace(path, &namespace);
562 }
563 let raw_namespace = dir_for_namespace
564 .as_deref()
565 .and_then(|p| p.file_name())
566 .and_then(|n| n.to_str())
567 .ok_or_else(|| miette::miette!("cannot derive namespace from path '{}'", path.display()))?
568 .to_string();
569
570 validate_namespace(path, &raw_namespace).map_err(|e| {
571 ConfigParseError::InvalidNamespace {
572 path: path.to_path_buf(),
573 namespace: raw_namespace,
574 reason: format!(
575 "{e}. Set a valid top-level namespace, e.g. namespace = \"my-project\""
576 ),
577 }
578 .into()
579 })
580}
581
582fn namespace_from_path_with_override(path: &Path, explicit: Option<&str>) -> Result<String> {
583 if is_global_config(path) {
584 if let Some(ns) = explicit
585 && ns != "global"
586 {
587 return Err(ConfigParseError::InvalidNamespace {
588 path: path.to_path_buf(),
589 namespace: ns.to_string(),
590 reason: "global config files must use namespace 'global'".to_string(),
591 }
592 .into());
593 }
594 return Ok("global".to_string());
595 }
596
597 if let Some(ns) = explicit {
598 return validate_namespace(path, ns);
599 }
600
601 derive_namespace_from_dir(path)
602}
603
604fn namespace_from_file(path: &Path) -> Result<String> {
605 let explicit = directory_namespace_override(path, None)?;
606 namespace_from_path_with_override(path, explicit.as_deref())
607}
608
609pub fn namespace_from_path(path: &Path) -> Result<String> {
622 namespace_from_file(path)
623}
624
625fn find_project_root(dir: &Path) -> Option<PathBuf> {
633 let canonical_dir = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
637 let mut current = canonical_dir.as_path();
638 loop {
639 if current.join(".git").exists() || current.join(".jj").exists() {
640 return Some(current.to_path_buf());
641 }
642 current = current.parent()?;
643 }
644}
645
646struct ConfigCacheEntry {
665 config: PitchforkToml,
666 source_meta: Vec<(PathBuf, Option<(SystemTime, u64)>)>,
668}
669
670static CONFIG_CACHE: Lazy<StdMutex<HashMap<PathBuf, ConfigCacheEntry>>> =
677 Lazy::new(|| StdMutex::new(HashMap::new()));
678
679fn meta_matches(paths: &[PathBuf], snapshot: &[(PathBuf, Option<(SystemTime, u64)>)]) -> bool {
685 if paths.len() != snapshot.len() {
686 return false;
687 }
688 paths
689 .iter()
690 .zip(snapshot.iter())
691 .all(|(p, (snap_p, snap_meta))| p == snap_p && current_meta(p) == *snap_meta)
692}
693
694pub(crate) fn current_meta(path: &Path) -> Option<(SystemTime, u64)> {
696 let md = std::fs::metadata(path).ok()?;
697 Some((md.modified().ok()?, md.len()))
698}
699
700fn snapshot_meta(paths: &[PathBuf]) -> Vec<(PathBuf, Option<(SystemTime, u64)>)> {
702 paths.iter().map(|p| (p.clone(), current_meta(p))).collect()
703}
704
705pub fn invalidate_config_cache() {
722 crate::extra_configs::invalidate();
723 crate::web::routes::api::projects::invalidate_group_cache();
726 if let Ok(mut cache) = CONFIG_CACHE.lock() {
727 cache.clear();
728 }
729}
730
731impl PitchforkToml {
732 pub fn resolve_daemon_id(&self, user_id: &str) -> Result<Vec<DaemonId>> {
745 if user_id.contains('/') {
747 return match DaemonId::parse(user_id) {
748 Ok(id) => Ok(vec![id]),
749 Err(e) => Err(e), };
751 }
752
753 let global_slugs = Self::read_global_slugs();
755 if let Some(entry) = global_slugs.get(user_id) {
756 let daemon_name = entry.daemon.as_deref().unwrap_or(user_id);
758 if let Some(dir) = entry.resolve_dir()
759 && let Ok(project_config) = Self::all_merged_from(&dir)
760 {
761 let matches: Vec<DaemonId> = project_config
763 .daemons
764 .keys()
765 .filter(|id| id.name() == daemon_name)
766 .cloned()
767 .collect();
768 match matches.as_slice() {
769 [] => {}
770 [id] => return Ok(vec![id.clone()]),
771 _ => {
772 let mut candidates: Vec<String> =
773 matches.iter().map(|id| id.qualified()).collect();
774 candidates.sort();
775 return Err(miette::miette!(
776 "slug '{}' maps to daemon '{}' which matches multiple daemons: {}",
777 user_id,
778 daemon_name,
779 candidates.join(", ")
780 ));
781 }
782 }
783 }
784 }
785
786 let matches: Vec<DaemonId> = self
788 .daemons
789 .keys()
790 .filter(|id| id.name() == user_id)
791 .cloned()
792 .collect();
793
794 if matches.is_empty() {
795 let state_matches = Self::find_in_state_file(user_id);
797 match state_matches.as_slice() {
798 [] => {}
799 [id] => return Ok(vec![id.clone()]),
800 _ => {
801 let mut candidates: Vec<String> =
802 state_matches.iter().map(|id| id.qualified()).collect();
803 candidates.sort();
804 return Err(miette::miette!(
805 "daemon '{}' is ambiguous; matches: {}. Use a qualified daemon ID (namespace/name)",
806 user_id,
807 candidates.join(", ")
808 ));
809 }
810 }
811 let _ = DaemonId::try_new("global", user_id)?;
813 }
814 Ok(matches)
815 }
816
817 fn find_in_state_file(short_name: &str) -> Vec<DaemonId> {
823 match StateFile::read(&*env::PITCHFORK_STATE_FILE) {
824 Ok(state) => state
825 .daemons
826 .keys()
827 .filter(|id| id.name() == short_name)
828 .cloned()
829 .collect(),
830 Err(e) => {
831 warn!("cannot read state file: {e}");
832 Vec::new()
833 }
834 }
835 }
836
837 #[allow(dead_code)]
858 pub fn resolve_daemon_id_prefer_local(
859 &self,
860 user_id: &str,
861 current_dir: &Path,
862 ) -> Result<DaemonId> {
863 if user_id.contains('/') {
865 return DaemonId::parse(user_id);
866 }
867
868 let current_namespace = Self::namespace_for_dir(current_dir)?;
872
873 self.resolve_daemon_id_with_namespace(user_id, ¤t_namespace)
874 }
875
876 fn resolve_daemon_id_with_namespace(
879 &self,
880 user_id: &str,
881 current_namespace: &str,
882 ) -> Result<DaemonId> {
883 if let Ok(preferred_id) = DaemonId::try_new(current_namespace, user_id)
888 && self.daemons.contains_key(&preferred_id)
889 {
890 return Ok(preferred_id);
891 }
892
893 let global_slugs = Self::read_global_slugs();
895 if let Some(entry) = global_slugs.get(user_id) {
896 let daemon_name = entry.daemon.as_deref().unwrap_or(user_id);
897 if let Some(dir) = entry.resolve_dir()
898 && let Ok(project_config) = Self::all_merged_from(&dir)
899 {
900 let matches: Vec<DaemonId> = project_config
901 .daemons
902 .keys()
903 .filter(|id| id.name() == daemon_name)
904 .cloned()
905 .collect();
906 match matches.as_slice() {
907 [] => {}
908 [id] => return Ok(id.clone()),
909 _ => {
910 let mut candidates: Vec<String> =
911 matches.iter().map(|id| id.qualified()).collect();
912 candidates.sort();
913 return Err(miette::miette!(
914 "slug '{}' maps to daemon '{}' which matches multiple daemons: {}",
915 user_id,
916 daemon_name,
917 candidates.join(", ")
918 ));
919 }
920 }
921 }
922 }
923
924 DaemonId::try_new(current_namespace, user_id)?;
926
927 let matches = self.resolve_daemon_id(user_id)?;
929
930 if matches.len() > 1 {
932 let mut candidates: Vec<String> = matches.iter().map(|id| id.qualified()).collect();
933 candidates.sort();
934 return Err(miette::miette!(
935 "daemon '{}' is ambiguous; matches: {}. Use a qualified daemon ID (namespace/name)",
936 user_id,
937 candidates.join(", ")
938 ));
939 }
940
941 if let Some(id) = matches.into_iter().next() {
942 return Ok(id);
943 }
944
945 let global_id = DaemonId::try_new("global", user_id)?;
948 if self.daemons.contains_key(&global_id) {
949 return Ok(global_id);
950 }
951
952 let suggestion = find_similar_daemon(user_id, self.daemons.keys().map(|id| id.name()));
953 Err(DependencyError::DaemonNotFound {
954 name: user_id.to_string(),
955 suggestion,
956 }
957 .into())
958 }
959
960 pub fn namespace_for_project_dir(dir: &Path) -> Result<String> {
962 namespace_from_path(&dir.join("pitchfork.toml"))
963 }
964
965 pub fn project_worktree_label(dir: &Path) -> Option<String> {
973 let mut label = None;
974 let candidates = project_config_family(&dir.join("pitchfork.toml"))
975 .into_iter()
976 .chain(crate::extra_configs::configs_for_dir(dir));
977 for candidate in candidates {
978 if !candidate.exists() {
979 continue;
980 }
981 if let Ok(pt) = Self::read(&candidate)
982 && let Some(found) = pt.worktree_label
983 {
984 label = Some(found);
985 }
986 }
987 label
988 }
989
990 pub fn project_namespace_override(dir: &Path) -> Result<Option<String>> {
992 directory_namespace_override(&dir.join("pitchfork.toml"), None)
993 }
994
995 pub fn namespace_for_dir(dir: &Path) -> Result<String> {
997 Ok(Self::list_paths_from(dir)
998 .iter()
999 .filter(|p| p.exists())
1000 .max_by_key(|p| {
1001 if is_global_config(p) {
1002 0
1003 } else {
1004 project_dir_for_config(p).map_or(0, |dir| dir.components().count())
1005 }
1006 })
1007 .map(|p| namespace_from_path(p))
1008 .transpose()?
1009 .unwrap_or_else(|| "global".to_string()))
1010 }
1011
1012 pub fn resolve_id(user_id: &str) -> Result<DaemonId> {
1022 if user_id.contains('/') {
1023 return DaemonId::parse(user_id);
1024 }
1025
1026 let config = Self::all_merged()?;
1029 let ns = Self::namespace_for_dir(&env::CWD)?;
1030 config.resolve_daemon_id_with_namespace(user_id, &ns)
1031 }
1032
1033 pub fn resolve_id_allow_adhoc(user_id: &str) -> Result<DaemonId> {
1039 Self::resolve_id_allow_adhoc_from(user_id, &env::CWD)
1040 }
1041
1042 fn resolve_id_allow_adhoc_from(user_id: &str, dir: &Path) -> Result<DaemonId> {
1043 if user_id.contains('/') {
1044 return DaemonId::parse(user_id);
1045 }
1046
1047 let ns = Self::namespace_for_dir(dir)?;
1048 DaemonId::try_new(ns, user_id)
1049 }
1050
1051 pub fn resolve_ids<S: AsRef<str>>(user_ids: &[S]) -> Result<Vec<DaemonId>> {
1062 if user_ids.iter().all(|s| s.as_ref().contains('/')) {
1064 return user_ids
1065 .iter()
1066 .map(|s| DaemonId::parse(s.as_ref()))
1067 .collect();
1068 }
1069
1070 let config = Self::all_merged()?;
1071 let ns = Self::namespace_for_dir(&env::CWD)?;
1073 user_ids
1074 .iter()
1075 .map(|s| {
1076 let id = s.as_ref();
1077 if id.contains('/') {
1078 DaemonId::parse(id)
1079 } else {
1080 config.resolve_daemon_id_with_namespace(id, &ns)
1081 }
1082 })
1083 .collect()
1084 }
1085
1086 pub fn resolve_ids_and_group<S: AsRef<str>>(
1091 user_ids: &[S],
1092 group_name: Option<&str>,
1093 ) -> Result<Vec<DaemonId>> {
1094 let config = Self::all_merged()?;
1095 let ns = Self::namespace_for_dir(&env::CWD)?;
1096 let mut ids = Vec::new();
1097 let mut seen = std::collections::HashSet::new();
1098
1099 for id in user_ids {
1100 let id_str = id.as_ref();
1101 let daemon_id = if id_str.contains('/') {
1102 DaemonId::parse(id_str)?
1103 } else {
1104 config.resolve_daemon_id_with_namespace(id_str, &ns)?
1105 };
1106 if seen.insert(daemon_id.clone()) {
1107 ids.push(daemon_id);
1108 }
1109 }
1110
1111 if let Some(name) = group_name {
1112 let members = expand_group(&config.groups, name)?;
1113 let missing: Vec<String> = members
1114 .iter()
1115 .filter(|id| !config.daemons.contains_key(*id))
1116 .map(|id| id.qualified())
1117 .collect();
1118 if !missing.is_empty() {
1119 return Err(miette::miette!(
1120 "group '{}' references undefined daemon{}: {}",
1121 name,
1122 if missing.len() > 1 { "s" } else { "" },
1123 missing.join(", ")
1124 ));
1125 }
1126 for daemon_id in members {
1127 if seen.insert(daemon_id.clone()) {
1128 ids.push(daemon_id);
1129 }
1130 }
1131 }
1132
1133 Ok(ids)
1134 }
1135
1136 pub fn list_paths() -> Vec<PathBuf> {
1139 Self::list_paths_from(&env::CWD)
1140 }
1141
1142 pub fn list_paths_from(cwd: &Path) -> Vec<PathBuf> {
1153 let mut paths = Vec::new();
1154 paths.push(env::PITCHFORK_GLOBAL_CONFIG_SYSTEM.clone());
1155 paths.push(env::PITCHFORK_GLOBAL_CONFIG_USER.clone());
1156
1157 let mut project_paths = xx::file::find_up_all(
1161 cwd,
1162 &[
1163 "pitchfork.local.toml",
1164 "pitchfork.toml",
1165 ".config/pitchfork.local.toml",
1166 ".config/pitchfork.toml",
1167 ],
1168 );
1169 project_paths.reverse();
1170 paths.extend(project_paths);
1171 paths.extend(crate::extra_configs::paths_for(cwd));
1172
1173 paths
1174 }
1175
1176 pub fn all_merged() -> Result<PitchforkToml> {
1179 Self::all_merged_from(&env::CWD)
1180 }
1181 pub async fn all_merged_all_namespaces() -> Result<Self> {
1193 Self::all_merged_all_namespaces_from(&env::CWD).await
1194 }
1195
1196 pub(crate) async fn all_merged_all_namespaces_from(start_dir: &Path) -> Result<Self> {
1198 let start_dir = start_dir.to_path_buf();
1199 match tokio::task::spawn_blocking(move || {
1200 Self::all_merged_all_namespaces_from_blocking(&start_dir)
1201 })
1202 .await
1203 {
1204 Ok(result) => result,
1205 Err(e) => Err(miette::miette!("reading the merged config panicked: {e}")),
1206 }
1207 }
1208
1209 pub fn all_merged_all_namespaces_blocking() -> Result<Self> {
1212 Self::all_merged_all_namespaces_from_blocking(&env::CWD)
1213 }
1214
1215 pub(crate) fn all_merged_all_namespaces_from_blocking(start_dir: &Path) -> Result<Self> {
1218 let mut pt = Self::all_merged_from(start_dir)?;
1219
1220 let namespaces = Self::read_global_namespaces();
1221 for (ns_name, entry) in namespaces {
1222 match Self::all_merged_from(&entry.dir) {
1223 Ok(ns_config) => {
1224 for (daemon_id, daemon_config) in ns_config.daemons {
1225 if !pt.daemons.contains_key(&daemon_id) {
1226 pt.foreign_env
1227 .insert(daemon_id.clone(), ns_config.env.clone());
1228 pt.daemons.insert(daemon_id, daemon_config);
1229 }
1230 }
1231 pt.settings.merge_from(&ns_config.settings);
1234 }
1235 Err(e) => {
1236 log::warn!(
1237 "Failed to load namespace '{ns_name}' from {}: {e}",
1238 entry.dir.display()
1239 );
1240 }
1241 }
1242 }
1243
1244 if crate::settings::settings().general.worktree
1254 && let Some(project_root) = find_project_root(start_dir)
1255 {
1256 let worktrees = crate::proxy::worktree::discover_worktrees(&project_root);
1257 for wt in &worktrees {
1258 match Self::all_merged_from(&wt.path) {
1259 Ok(wt_config) => {
1260 for (daemon_id, daemon_config) in wt_config.daemons {
1261 if !pt.daemons.contains_key(&daemon_id) {
1262 pt.daemons.insert(daemon_id, daemon_config);
1263 }
1264 }
1265 pt.settings.merge_from(&wt_config.settings);
1266 }
1267 Err(e) => {
1268 log::warn!(
1269 "Failed to load worktree '{}' config from {}: {e}",
1270 wt.branch,
1271 wt.path.display()
1272 );
1273 }
1274 }
1275 }
1276 }
1277
1278 Ok(pt)
1279 }
1280
1281 pub fn all_merged_from(cwd: &Path) -> Result<PitchforkToml> {
1299 let paths = Self::list_paths_from(cwd);
1300
1301 let cache_key = cwd.canonicalize().unwrap_or_else(|_| cwd.to_path_buf());
1305
1306 {
1307 let cache = CONFIG_CACHE.lock().unwrap_or_else(|e| e.into_inner());
1308 if let Some(entry) = cache.get(&cache_key)
1309 && meta_matches(&paths, &entry.source_meta)
1310 {
1311 return Ok(entry.config.clone());
1312 }
1313 }
1314
1315 let snapshot = snapshot_meta(&paths);
1321 let pt = Self::all_merged_from_uncached(&paths)?;
1322
1323 let mut cache = CONFIG_CACHE.lock().unwrap_or_else(|e| e.into_inner());
1325 cache.insert(
1326 cache_key,
1327 ConfigCacheEntry {
1328 config: pt.clone(),
1329 source_meta: snapshot,
1330 },
1331 );
1332
1333 Ok(pt)
1334 }
1335
1336 fn all_merged_from_uncached(paths: &[PathBuf]) -> Result<PitchforkToml> {
1341 use std::collections::HashMap as StdHashMap;
1342
1343 let mut ns_to_origin: StdHashMap<String, (PathBuf, PathBuf)> = StdHashMap::new();
1344
1345 let mut pt = Self::default();
1346 for p in paths {
1347 match Self::read(p) {
1348 Ok(pt2) => {
1349 if p.exists() && !is_global_config(p) {
1353 let ns = namespace_from_path(p)?;
1354 let origin_dir = project_dir_for_config(p)
1355 .map(|dir| dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf()))
1356 .unwrap_or_else(|| p.clone());
1357
1358 if let Some((other_path, other_dir)) = ns_to_origin.get(ns.as_str())
1359 && *other_dir != origin_dir
1360 {
1361 return Err(crate::error::ConfigParseError::NamespaceCollision {
1362 path_a: other_path.clone(),
1363 path_b: p.clone(),
1364 ns,
1365 }
1366 .into());
1367 }
1368 ns_to_origin.insert(ns, (p.clone(), origin_dir));
1369 }
1370
1371 pt.merge(pt2)
1372 }
1373 Err(e) => return Err(e.wrap_err(format!("error reading {}", p.display()))),
1374 }
1375 }
1376 Ok(pt)
1377 }
1378}
1379
1380impl PitchforkToml {
1381 pub fn new(path: PathBuf) -> Self {
1382 Self {
1383 daemons: Default::default(),
1384 env: None,
1385 namespace: None,
1386 worktree_label: None,
1387 settings: SettingsPartial::default(),
1388 slugs: IndexMap::new(),
1389 groups: IndexMap::new(),
1390 namespaces: IndexMap::new(),
1391 path: Some(path),
1392 foreign_env: IndexMap::new(),
1393 }
1394 }
1395
1396 pub fn parse_str(content: &str, path: &Path) -> Result<Self> {
1404 let mut raw_config: PitchforkTomlRaw = toml::from_str(content)
1405 .map_err(|e| ConfigParseError::from_toml_error(path, content.to_string(), e))?;
1406 if let Some(settings) = &mut raw_config.settings {
1407 settings.canonicalize_aliases();
1408 }
1409
1410 let explicit = directory_namespace_override(path, Some(content))?;
1411 let namespace = namespace_from_path_with_override(path, explicit.as_deref())?;
1412 let mut pt = Self::new(path.to_path_buf());
1413 pt.namespace = raw_config.namespace.clone();
1414 pt.worktree_label = raw_config.worktree_label.clone();
1415
1416 for (short_name, raw_daemon) in raw_config.daemons {
1417 let id = match DaemonId::try_new(&namespace, &short_name) {
1418 Ok(id) => id,
1419 Err(e) => {
1420 return Err(ConfigParseError::InvalidDaemonName {
1421 name: short_name,
1422 path: path.to_path_buf(),
1423 reason: e.to_string(),
1424 }
1425 .into());
1426 }
1427 };
1428
1429 let mut depends = Vec::new();
1430 for dep in raw_daemon.depends {
1431 let dep_id = if dep.contains('/') {
1432 match DaemonId::parse(&dep) {
1433 Ok(id) => id,
1434 Err(e) => {
1435 return Err(ConfigParseError::InvalidDependency {
1436 daemon: short_name.clone(),
1437 dependency: dep,
1438 path: path.to_path_buf(),
1439 reason: e.to_string(),
1440 }
1441 .into());
1442 }
1443 }
1444 } else {
1445 match DaemonId::try_new(&namespace, &dep) {
1446 Ok(id) => id,
1447 Err(e) => {
1448 return Err(ConfigParseError::InvalidDependency {
1449 daemon: short_name.clone(),
1450 dependency: dep,
1451 path: path.to_path_buf(),
1452 reason: e.to_string(),
1453 }
1454 .into());
1455 }
1456 }
1457 };
1458 depends.push(dep_id);
1459 }
1460
1461 let has_deprecated = !raw_daemon.expected_port.is_empty()
1463 || raw_daemon.auto_bump_port.is_some()
1464 || raw_daemon.port_bump_attempts.is_some();
1465 let deprecated_port = has_deprecated.then(|| {
1466 let bump = if raw_daemon.auto_bump_port.unwrap_or(false) {
1467 PortBump(
1468 raw_daemon
1469 .port_bump_attempts
1470 .unwrap_or_else(|| settings().default_port_bump_attempts()),
1471 )
1472 } else {
1473 PortBump(0)
1474 };
1475 PortConfig {
1476 expect: raw_daemon.expected_port,
1477 bump,
1478 }
1479 });
1480 let port = match (raw_daemon.port, deprecated_port) {
1481 (Some(port), Some(deprecated)) => {
1482 if deprecated != port {
1485 warn!(
1486 "daemon {short_name}: both `port` and deprecated expected_port/auto_bump_port/port_bump_attempts are set; ignoring deprecated fields"
1487 );
1488 }
1489 Some(port)
1490 }
1491 (Some(port), None) => Some(port),
1492 (None, Some(deprecated)) => {
1493 deprecated_at!(
1494 "2026-10-03",
1495 "2027-10-03",
1496 format!("port-fields:{id}"),
1497 "daemon {short_name}: expected_port/auto_bump_port/port_bump_attempts are deprecated, use [daemons.{short_name}.port] instead."
1498 );
1499 Some(deprecated)
1500 }
1501 (None, None) => None,
1502 };
1503
1504 if let (Some(explicit), Some(short)) =
1506 (raw_daemon.proxy_tls_port, raw_daemon.proxy_port)
1507 && explicit != short
1508 {
1509 warn!(
1510 "daemon {short_name}: proxy_tls_port ({explicit}) and proxy_port ({short}) \
1511 disagree; using proxy_tls_port"
1512 );
1513 }
1514 let proxy_tls_port = raw_daemon.proxy_tls_port.or(raw_daemon.proxy_port);
1515
1516 for (key, value) in [
1519 ("proxy_tls_port", raw_daemon.proxy_tls_port),
1520 ("proxy_port", raw_daemon.proxy_port),
1521 ] {
1522 if value == Some(0) {
1523 return Err(ConfigParseError::ProxyPortZero {
1524 daemon: short_name.clone(),
1525 key,
1526 path: path.to_path_buf(),
1527 }
1528 .into());
1529 }
1530 }
1531
1532 if let Some(port_want) = proxy_tls_port {
1535 let declared = port.as_ref().map(|p| p.expect.clone()).unwrap_or_default();
1536 if !declared.contains(&port_want) {
1537 return Err(ConfigParseError::ProxyPortNotDeclared {
1538 daemon: short_name.clone(),
1539 port: port_want,
1540 declared,
1541 path: path.to_path_buf(),
1542 }
1543 .into());
1544 }
1545 }
1546
1547 if raw_daemon
1550 .proxy_tls
1551 .is_some_and(ProxyTlsMode::is_passthrough)
1552 && port
1553 .as_ref()
1554 .is_none_or(|p| p.expect.iter().all(|&port| port == 0))
1555 {
1556 return Err(ConfigParseError::PassthroughWithoutPort {
1557 daemon: short_name.clone(),
1558 path: path.to_path_buf(),
1559 }
1560 .into());
1561 }
1562
1563 if let RunCommand::Argv(argv) = &raw_daemon.run {
1564 match argv.first().map(String::as_str) {
1565 None => {
1566 return Err(ConfigParseError::EmptyRunArgv {
1567 daemon: short_name.clone(),
1568 path: path.to_path_buf(),
1569 }
1570 .into());
1571 }
1572 Some("exec") => {
1575 return Err(ConfigParseError::ExecInRunArgv {
1576 daemon: short_name.clone(),
1577 path: path.to_path_buf(),
1578 }
1579 .into());
1580 }
1581 Some(_) => {}
1582 }
1583 }
1584
1585 if let Some(RunCommand::Argv(argv)) = raw_daemon.ready_cmd.as_ref().map(|c| &c.run) {
1586 match argv.first().map(String::as_str) {
1587 None | Some("") => {
1590 return Err(ConfigParseError::EmptyReadyCmdArgv {
1591 daemon: short_name.clone(),
1592 path: path.to_path_buf(),
1593 }
1594 .into());
1595 }
1596 Some("exec") => {
1597 return Err(ConfigParseError::ExecInReadyCmdArgv {
1598 daemon: short_name.clone(),
1599 path: path.to_path_buf(),
1600 }
1601 .into());
1602 }
1603 Some(_) => {}
1604 }
1605 }
1606
1607 if let Some(RunCommand::Argv(argv)) = raw_daemon.health_cmd.as_ref().map(|c| &c.run) {
1608 match argv.first().map(String::as_str) {
1609 None | Some("") => {
1612 return Err(ConfigParseError::EmptyHealthCmdArgv {
1613 daemon: short_name.clone(),
1614 path: path.to_path_buf(),
1615 }
1616 .into());
1617 }
1618 Some("exec") => {
1619 return Err(ConfigParseError::ExecInHealthCmdArgv {
1620 daemon: short_name.clone(),
1621 path: path.to_path_buf(),
1622 }
1623 .into());
1624 }
1625 Some(_) => {}
1626 }
1627 }
1628
1629 let daemon = PitchforkTomlDaemon {
1630 run: raw_daemon.run,
1631 auto: raw_daemon.auto,
1632 oneshot: raw_daemon.oneshot,
1633 cron: raw_daemon.cron,
1634 retry: raw_daemon.retry,
1635 ready_delay: raw_daemon.ready_delay,
1636 ready_output: raw_daemon.ready_output,
1637 ready_http: raw_daemon.ready_http,
1638 ready_port: raw_daemon.ready_port,
1639 ready_cmd: raw_daemon.ready_cmd,
1640 health_cmd: raw_daemon.health_cmd,
1641 health_http: raw_daemon.health_http,
1642 health_port: raw_daemon.health_port,
1643 port,
1644 proxy: raw_daemon.proxy,
1645 proxy_tls: raw_daemon.proxy_tls,
1646 proxy_protocol: raw_daemon.proxy_protocol,
1647 proxy_tls_port: raw_daemon.proxy_tls_port,
1648 proxy_port: raw_daemon.proxy_port,
1649 proxy_idle_timeout: raw_daemon.proxy_idle_timeout,
1650 boot_start: raw_daemon.boot_start,
1651 depends,
1652 watch: raw_daemon.watch,
1653 watch_mode: raw_daemon.watch_mode.unwrap_or_default(),
1654 dir: raw_daemon.dir,
1655 env: raw_daemon.env,
1656 env_file: raw_daemon.env_file,
1657 hooks: raw_daemon.hooks,
1658 mise: raw_daemon.mise,
1659 deferred_template_context: None,
1660 user: raw_daemon.user,
1661 memory_limit: raw_daemon.memory_limit,
1662 cpu_limit: raw_daemon.cpu_limit,
1663 stop_signal: raw_daemon.stop_signal,
1664 pty: raw_daemon.pty,
1665 time_retention: raw_daemon.time_retention,
1666 line_retention: raw_daemon.line_retention,
1667 archive_hook: raw_daemon.archive_hook,
1668 logs: raw_daemon.logs,
1669 path: Some(path.to_path_buf()),
1670 };
1671 if daemon.is_oneshot() {
1672 let conflicts = daemon.oneshot_conflicts();
1673 if !conflicts.is_empty() {
1674 return Err(ConfigParseError::OneshotConflict {
1675 daemon: short_name.clone(),
1676 path: path.to_path_buf(),
1677 conflicts: conflicts.into_iter().map(str::to_string).collect(),
1678 }
1679 .into());
1680 }
1681 }
1682 pt.daemons.insert(id, daemon);
1683 }
1684
1685 if let Some(settings) = raw_config.settings {
1687 pt.settings = settings;
1688 }
1689
1690 pt.env = raw_config.env;
1692
1693 for (slug, entry) in raw_config.slugs {
1695 pt.slugs.insert(
1696 slug,
1697 SlugEntry {
1698 dir: entry.dir.map(env::expand_tilde),
1699 namespace: entry.namespace,
1700 daemon: entry.daemon,
1701 },
1702 );
1703 }
1704
1705 for (name, entry) in raw_config.namespaces {
1707 pt.namespaces.insert(
1708 name,
1709 NamespaceEntry {
1710 config: entry
1711 .config
1712 .iter()
1713 .map(|p| {
1714 crate::extra_configs::resolve_path(&env::expand_tilde(&entry.dir), p)
1715 })
1716 .collect(),
1717 dir: env::expand_tilde(entry.dir),
1718 label: entry.label,
1719 },
1720 );
1721 }
1722
1723 for (group_name, raw_group) in raw_config.groups {
1725 let mut daemons = Vec::new();
1726 for daemon_name in &raw_group.daemons {
1727 let id = if daemon_name.contains('/') {
1728 DaemonId::parse(daemon_name).map_err(|e| {
1729 ConfigParseError::InvalidDependency {
1730 daemon: group_name.clone(),
1731 dependency: daemon_name.clone(),
1732 path: path.to_path_buf(),
1733 reason: e.to_string(),
1734 }
1735 })?
1736 } else {
1737 DaemonId::try_new(&namespace, daemon_name).map_err(|e| {
1738 ConfigParseError::InvalidDaemonName {
1739 name: daemon_name.clone(),
1740 path: path.to_path_buf(),
1741 reason: e.to_string(),
1742 }
1743 })?
1744 };
1745 daemons.push(id);
1746 }
1747 pt.groups.insert(
1748 group_name,
1749 GroupEntry {
1750 daemons,
1751 groups: raw_group.groups,
1752 },
1753 );
1754 }
1755
1756 Ok(pt)
1757 }
1758
1759 pub fn read<P: AsRef<Path>>(path: P) -> Result<Self> {
1760 let path = path.as_ref();
1761 if !path.exists() {
1762 return Ok(Self::new(path.to_path_buf()));
1763 }
1764 let _lock = xx::fslock::get(path, false)
1765 .wrap_err_with(|| format!("failed to acquire lock on {}", path.display()))?;
1766 let raw = std::fs::read_to_string(path).map_err(|e| FileError::ReadError {
1767 path: path.to_path_buf(),
1768 source: e,
1769 })?;
1770 Self::parse_str(&raw, path)
1771 }
1772
1773 pub fn write(&self) -> Result<()> {
1774 if let Some(path) = &self.path {
1775 let _lock = xx::fslock::get(path, false)
1776 .wrap_err_with(|| format!("failed to acquire lock on {}", path.display()))?;
1777 self.write_unlocked()
1778 } else {
1779 Err(FileError::NoPath.into())
1780 }
1781 }
1782
1783 pub(crate) fn write_unlocked(&self) -> Result<()> {
1789 if let Some(path) = &self.path {
1790 let config_namespace = if path.exists() || self.namespace.is_none() {
1794 namespace_from_path(path)?
1795 } else {
1796 namespace_from_path_with_override(path, self.namespace.as_deref())?
1797 };
1798
1799 let mut raw = PitchforkTomlRaw {
1803 namespace: self.namespace.clone(),
1804 worktree_label: self.worktree_label.clone(),
1805 env: self.env.clone(),
1806 settings: (!self.settings.is_empty()).then(|| self.settings.clone()),
1807 ..PitchforkTomlRaw::default()
1808 };
1809 for (id, daemon) in &self.daemons {
1810 if id.namespace() != config_namespace {
1811 return Err(miette::miette!(
1812 "cannot write daemon '{}' to {}: daemon belongs to namespace '{}' but file namespace is '{}'",
1813 id,
1814 path.display(),
1815 id.namespace(),
1816 config_namespace
1817 ));
1818 }
1819 let port = daemon.port.as_ref();
1820 let raw_daemon = PitchforkTomlDaemonRaw {
1821 run: daemon.run.clone(),
1822 auto: daemon.auto.clone(),
1823 oneshot: daemon.oneshot,
1824 cron: daemon.cron.clone(),
1825 retry: daemon.retry,
1826 ready_delay: daemon.ready_delay,
1827 ready_output: daemon.ready_output.clone(),
1828 ready_http: daemon.ready_http.clone(),
1829 ready_port: daemon.ready_port.clone(),
1830 ready_cmd: daemon.ready_cmd.clone(),
1831 health_cmd: daemon.health_cmd.clone(),
1832 health_http: daemon.health_http.clone(),
1833 health_port: daemon.health_port.clone(),
1834 port: port.cloned(),
1835 proxy: daemon.proxy.clone(),
1836 proxy_tls: daemon.proxy_tls,
1837 proxy_protocol: daemon.proxy_protocol,
1838 proxy_tls_port: daemon.proxy_tls_port,
1839 proxy_port: daemon.proxy_port,
1840 proxy_idle_timeout: daemon.proxy_idle_timeout,
1841 expected_port: port.map(|p| p.expect.clone()).unwrap_or_default(),
1843 auto_bump_port: port.filter(|p| p.auto_bump()).map(|_| true),
1844 port_bump_attempts: port
1845 .filter(|p| p.auto_bump())
1846 .map(|p| p.max_bump_attempts()),
1847 boot_start: daemon.boot_start,
1848 depends: daemon
1851 .depends
1852 .iter()
1853 .map(|d| {
1854 if d.namespace() == config_namespace {
1855 d.name().to_string()
1856 } else {
1857 d.qualified()
1858 }
1859 })
1860 .collect(),
1861 watch: daemon.watch.clone(),
1862 watch_mode: match daemon.watch_mode {
1863 WatchMode::Native => None,
1864 mode => Some(mode),
1865 },
1866 dir: daemon.dir.clone(),
1867 env: daemon.env.clone(),
1868 env_file: daemon.env_file.clone(),
1869 hooks: daemon.hooks.clone(),
1870 mise: daemon.mise,
1871 user: daemon.user.clone(),
1872 memory_limit: daemon.memory_limit,
1873 cpu_limit: daemon.cpu_limit,
1874 stop_signal: daemon.stop_signal,
1875 pty: daemon.pty,
1876 time_retention: daemon.time_retention.clone(),
1877 line_retention: daemon.line_retention,
1878 archive_hook: daemon.archive_hook.clone(),
1879 logs: daemon.logs.clone(),
1880 };
1881 raw.daemons.insert(id.name().to_string(), raw_daemon);
1882 }
1883
1884 for (slug, entry) in &self.slugs {
1886 raw.slugs.insert(
1887 slug.clone(),
1888 SlugEntryRaw {
1889 dir: entry.dir.as_ref().map(|d| d.to_string_lossy().to_string()),
1890 namespace: entry.namespace.clone(),
1891 daemon: entry.daemon.clone(),
1892 },
1893 );
1894 }
1895
1896 for (name, group) in &self.groups {
1898 let raw_daemons: Vec<String> = group
1899 .daemons
1900 .iter()
1901 .map(|id| {
1902 if id.namespace() == config_namespace {
1903 id.name().to_string()
1904 } else {
1905 id.qualified()
1906 }
1907 })
1908 .collect();
1909 raw.groups.insert(
1910 name.clone(),
1911 GroupEntryRaw {
1912 daemons: raw_daemons,
1913 groups: group.groups.clone(),
1914 },
1915 );
1916 }
1917
1918 for (name, entry) in &self.namespaces {
1920 raw.namespaces.insert(
1921 name.clone(),
1922 NamespaceEntryRaw {
1923 dir: entry.dir.to_string_lossy().to_string(),
1924 config: entry
1925 .config
1926 .iter()
1927 .map(|p| p.to_string_lossy().into_owned())
1928 .collect(),
1929 label: entry.label.clone(),
1930 },
1931 );
1932 }
1933
1934 let raw_str = toml::to_string(&raw).map_err(|e| FileError::SerializeError {
1935 path: path.clone(),
1936 source: e,
1937 })?;
1938 xx::file::write(path, &raw_str).map_err(|e| FileError::WriteError {
1939 path: path.clone(),
1940 details: Some(e.to_string()),
1941 })?;
1942 invalidate_config_cache();
1943 Ok(())
1944 } else {
1945 Err(FileError::NoPath.into())
1946 }
1947 }
1948
1949 pub fn merge(&mut self, pt: Self) {
1954 if pt.worktree_label.is_some() {
1955 self.worktree_label = pt.worktree_label.clone();
1956 }
1957 for (id, d) in pt.daemons {
1958 self.daemons.insert(id, d);
1959 }
1960 if let Some(env) = pt.env {
1962 let merged = self.env.get_or_insert_with(IndexMap::new);
1963 for (k, v) in env {
1964 merged.insert(k, v);
1965 }
1966 }
1967 for (slug, entry) in pt.slugs {
1969 self.slugs.insert(slug, entry);
1970 }
1971 for (name, group) in pt.groups {
1973 self.groups.insert(name, group);
1974 }
1975 for (name, entry) in pt.namespaces {
1977 self.namespaces.insert(name, entry);
1978 }
1979 self.settings.merge_from(&pt.settings);
1981 }
1982
1983 pub fn read_global_slugs() -> IndexMap<String, SlugEntry> {
1988 match Self::read(&*env::PITCHFORK_GLOBAL_CONFIG_USER) {
1989 Ok(pt) => pt.slugs,
1990 Err(_) => IndexMap::new(),
1991 }
1992 }
1993
1994 pub fn slug_is_ambiguous(slug: &str, global_slugs: &IndexMap<String, SlugEntry>) -> bool {
2001 global_slugs
2002 .keys()
2003 .filter(|k| k.eq_ignore_ascii_case(slug))
2004 .count()
2005 > 1
2006 }
2007
2008 pub fn find_slug_for_daemon_in_registry(
2013 daemon_id: &DaemonId,
2014 global_slugs: &IndexMap<String, SlugEntry>,
2015 ) -> Option<String> {
2016 global_slugs
2017 .iter()
2018 .find(|(slug, entry)| {
2019 let daemon_name = entry.daemon.as_deref().unwrap_or(slug);
2020 if daemon_id.name() != daemon_name {
2021 return false;
2022 }
2023
2024 if Self::slug_is_ambiguous(slug, global_slugs) {
2027 return false;
2028 }
2029
2030 match entry.resolve_namespace() {
2031 Some(namespace) => daemon_id.namespace() == namespace,
2032 None => false,
2033 }
2034 })
2035 .map(|(slug, _)| slug.clone())
2036 }
2037
2038 #[allow(dead_code)]
2040 pub fn is_slug_registered(slug: &str) -> bool {
2041 Self::read_global_slugs().contains_key(slug)
2042 }
2043
2044 pub fn add_slug_with_namespace(
2050 slug: &str,
2051 namespace: Option<&str>,
2052 daemon: Option<&str>,
2053 ) -> Result<()> {
2054 let global_path = &*env::PITCHFORK_GLOBAL_CONFIG_USER;
2055
2056 if let Some(parent) = global_path.parent() {
2058 std::fs::create_dir_all(parent).map_err(|e| {
2059 miette::miette!(
2060 "Failed to create config directory {}: {e}",
2061 parent.display()
2062 )
2063 })?;
2064 }
2065
2066 let _lock = xx::fslock::get(global_path, false)
2067 .wrap_err_with(|| format!("failed to acquire lock on {}", global_path.display()))?;
2068
2069 let mut pt = if global_path.exists() {
2070 let raw = std::fs::read_to_string(global_path).map_err(|e| FileError::ReadError {
2071 path: global_path.to_path_buf(),
2072 source: e,
2073 })?;
2074 Self::parse_str(&raw, global_path)?
2075 } else {
2076 Self::new(global_path.to_path_buf())
2077 };
2078
2079 if let Some(ns) = namespace
2083 && !pt.namespaces.contains_key(ns)
2084 {
2085 let dir = pt
2090 .slugs
2091 .get(slug)
2092 .and_then(|e| {
2093 e.dir.clone().or_else(|| {
2094 e.namespace
2095 .as_ref()
2096 .and_then(|ns| pt.namespaces.get(ns).map(|entry| entry.dir.clone()))
2097 })
2098 })
2099 .or_else(|| env::CWD.as_path().canonicalize().ok());
2100 if let Some(ref d) = dir {
2101 pt.namespaces.insert(
2102 ns.to_string(),
2103 NamespaceEntry {
2104 dir: d.clone(),
2105 config: Vec::new(),
2106 label: None,
2107 },
2108 );
2109 }
2110 }
2111
2112 pt.slugs.insert(
2113 slug.to_string(),
2114 SlugEntry {
2115 dir: None,
2116 namespace: namespace.map(str::to_string),
2117 daemon: daemon.map(str::to_string),
2118 },
2119 );
2120 pt.write_unlocked()?;
2121 let slug_names: Vec<String> = pt.slugs.keys().cloned().collect();
2127 crate::proxy::hosts::sync_hosts_from_settings_with_slugs(&slug_names);
2128 Ok(())
2129 }
2130
2131 pub fn remove_slug(slug: &str) -> Result<bool> {
2133 let global_path = &*env::PITCHFORK_GLOBAL_CONFIG_USER;
2134 if !global_path.exists() {
2135 return Ok(false);
2136 }
2137
2138 let _lock = xx::fslock::get(global_path, false)
2139 .wrap_err_with(|| format!("failed to acquire lock on {}", global_path.display()))?;
2140
2141 let raw = std::fs::read_to_string(global_path).map_err(|e| FileError::ReadError {
2142 path: global_path.to_path_buf(),
2143 source: e,
2144 })?;
2145 let mut pt = Self::parse_str(&raw, global_path)?;
2146
2147 let removed = pt.slugs.shift_remove(slug).is_some();
2148 if removed {
2149 pt.write_unlocked()?;
2150 let slug_names: Vec<String> = pt.slugs.keys().cloned().collect();
2156 crate::proxy::hosts::sync_hosts_from_settings_with_slugs(&slug_names);
2157 }
2158 Ok(removed)
2159 }
2160 pub fn read_global_namespaces() -> IndexMap<String, NamespaceEntry> {
2163 match Self::read(&*env::PITCHFORK_GLOBAL_CONFIG_USER) {
2164 Ok(pt) => pt.namespaces,
2165 Err(_) => IndexMap::new(),
2166 }
2167 }
2168
2169 pub fn register_namespace(name: &str, dir: &str) -> crate::Result<()> {
2173 let global_path = &*crate::env::PITCHFORK_GLOBAL_CONFIG_USER;
2174
2175 if let Some(parent) = global_path.parent() {
2177 std::fs::create_dir_all(parent).map_err(|e| {
2178 miette::miette!(
2179 "Failed to create config directory {}: {e}",
2180 parent.display()
2181 )
2182 })?;
2183 }
2184
2185 let _lock = xx::fslock::get(global_path, false)
2186 .wrap_err_with(|| format!("failed to acquire lock on {}", global_path.display()))?;
2187
2188 let mut pt = if global_path.exists() {
2189 let raw = std::fs::read_to_string(global_path).map_err(|e| {
2190 crate::error::FileError::ReadError {
2191 path: global_path.to_path_buf(),
2192 source: e,
2193 }
2194 })?;
2195 Self::parse_str(&raw, global_path)?
2196 } else {
2197 Self::new(global_path.to_path_buf())
2198 };
2199
2200 let dir = env::expand_tilde(dir);
2201 if let Some(entry) = pt.namespaces.get_mut(name) {
2202 if crate::extra_configs::path_is_gone(&entry.dir)
2203 && crate::extra_configs::normalize(&entry.dir)
2204 != crate::extra_configs::normalize(&dir)
2205 {
2206 if crate::extra_configs::namespace_has_running_daemon(name) {
2207 miette::bail!(
2210 "namespace '{name}' has running daemons from {}, which no longer exists; stop them first",
2211 entry.dir.display()
2212 );
2213 }
2214 entry.config.clear();
2216 entry.label = None;
2217 }
2218 if !entry.config.is_empty()
2219 && crate::extra_configs::normalize(&entry.dir)
2220 != crate::extra_configs::normalize(&dir)
2221 {
2222 miette::bail!(
2223 "namespace '{name}' has external configuration attached to another directory"
2224 );
2225 }
2226 entry.dir = dir;
2227 } else {
2228 pt.namespaces.insert(
2229 name.to_string(),
2230 NamespaceEntry {
2231 dir,
2232 config: Vec::new(),
2233 label: None,
2234 },
2235 );
2236 }
2237 pt.write_unlocked()?;
2238 Ok(())
2239 }
2240
2241 pub fn remove_namespace(name: &str) -> crate::Result<bool> {
2243 let global_path = &*crate::env::PITCHFORK_GLOBAL_CONFIG_USER;
2244 if !global_path.exists() {
2245 return Ok(false);
2246 }
2247
2248 let _lock = xx::fslock::get(global_path, false)
2249 .wrap_err_with(|| format!("failed to acquire lock on {}", global_path.display()))?;
2250
2251 let raw = std::fs::read_to_string(global_path).map_err(|e| {
2252 crate::error::FileError::ReadError {
2253 path: global_path.to_path_buf(),
2254 source: e,
2255 }
2256 })?;
2257 let mut pt = Self::parse_str(&raw, global_path)?;
2258
2259 let removed = pt.namespaces.shift_remove(name).is_some();
2260 if removed {
2261 pt.write_unlocked()?;
2262 }
2263 Ok(removed)
2264 }
2265}
2266
2267#[derive(Debug, Default, Clone, PartialEq, Eq)]
2269pub struct PruneReport {
2270 pub namespaces: Vec<String>,
2272 pub slugs: Vec<String>,
2274 pub config_files: usize,
2276}
2277
2278impl PruneReport {
2279 pub fn is_empty(&self) -> bool {
2280 self.namespaces.is_empty() && self.slugs.is_empty() && self.config_files == 0
2281 }
2282}
2283
2284impl PitchforkToml {
2285 pub fn prune_stale_registrations(
2299 keep: &std::collections::HashSet<String>,
2300 only: &[String],
2301 ) -> Result<PruneReport> {
2302 let global_path = &*env::PITCHFORK_GLOBAL_CONFIG_USER;
2303 let mut report = PruneReport::default();
2304 if !global_path.exists() {
2305 return Ok(report);
2306 }
2307 let _lock = xx::fslock::get(global_path, false)
2308 .wrap_err_with(|| format!("failed to acquire lock on {}", global_path.display()))?;
2309 let raw = std::fs::read_to_string(global_path).map_err(|e| FileError::ReadError {
2310 path: global_path.to_path_buf(),
2311 source: e,
2312 })?;
2313 let mut pt = Self::parse_str(&raw, global_path)?;
2314 let in_scope = |ns: &str| only.is_empty() || only.iter().any(|o| o == ns);
2315
2316 for (name, entry) in pt.namespaces.iter_mut() {
2317 if keep.contains(name) || !in_scope(name) {
2318 continue;
2319 }
2320 if crate::extra_configs::path_is_gone(&entry.dir) {
2321 report.namespaces.push(name.clone());
2322 continue;
2323 }
2324 let before = entry.config.len();
2325 entry
2326 .config
2327 .retain(|file| !crate::extra_configs::path_is_gone(file));
2328 let dropped = before - entry.config.len();
2329 if dropped > 0 {
2330 report.config_files += dropped;
2331 if entry.config.is_empty() {
2332 entry.label = None;
2334 }
2335 }
2336 }
2337 for name in &report.namespaces {
2338 pt.namespaces.shift_remove(name);
2339 }
2340
2341 if only.is_empty() || !report.namespaces.is_empty() {
2342 for (slug, entry) in &pt.slugs {
2343 if entry.namespace.as_ref().is_some_and(|ns| keep.contains(ns)) {
2346 continue;
2347 }
2348 let ns_pruned = entry
2349 .namespace
2350 .as_ref()
2351 .is_some_and(|ns| report.namespaces.contains(ns));
2352 let dir_gone = entry
2353 .dir
2354 .as_ref()
2355 .is_some_and(|d| crate::extra_configs::path_is_gone(d));
2356 let scoped_ok = only.is_empty() || ns_pruned;
2359 if scoped_ok && (ns_pruned || dir_gone) {
2360 report.slugs.push(slug.clone());
2361 }
2362 }
2363 for slug in &report.slugs {
2364 pt.slugs.shift_remove(slug);
2365 }
2366 }
2367
2368 if !report.is_empty() {
2369 pt.write_unlocked()?;
2370 if !report.slugs.is_empty() {
2371 let slug_names: Vec<String> = pt.slugs.keys().cloned().collect();
2372 crate::proxy::hosts::sync_hosts_from_settings_with_slugs(&slug_names);
2373 }
2374 }
2375 Ok(report)
2376 }
2377}
2378
2379#[derive(Debug, Clone, JsonSchema, Default)]
2381pub struct PitchforkTomlDaemon {
2382 #[schemars(example = example_run_command())]
2386 pub run: RunCommand,
2387 #[schemars(default)]
2389 pub auto: Vec<PitchforkTomlAuto>,
2390 pub oneshot: Option<bool>,
2396 pub cron: Option<PitchforkTomlCron>,
2398 #[schemars(default)]
2401 pub retry: Retry,
2402 pub ready_delay: Option<u64>,
2404 pub ready_output: Option<ReadyOutput>,
2406 pub ready_http: Option<ReadyHttp>,
2408 pub ready_port: Option<ReadyPort>,
2412 pub ready_cmd: Option<ReadyCmd>,
2414 pub health_cmd: Option<HealthCmd>,
2416 pub health_http: Option<HealthHttp>,
2418 pub health_port: Option<HealthPort>,
2422 pub port: Option<PortConfig>,
2424 #[serde(skip_serializing_if = "Option::is_none", default)]
2427 pub proxy: Option<ProxyConfig>,
2428 pub proxy_tls: Option<ProxyTlsMode>,
2437 pub proxy_protocol: Option<ProxyProtocol>,
2445 #[schemars(range(min = 1))]
2450 pub proxy_tls_port: Option<u16>,
2451 #[schemars(range(min = 1))]
2457 pub proxy_port: Option<u16>,
2458 pub proxy_idle_timeout: Option<ProxyIdleTimeout>,
2469 pub boot_start: Option<bool>,
2471 #[schemars(default)]
2473 pub depends: Vec<DaemonId>,
2474 #[schemars(default)]
2476 pub watch: Vec<String>,
2477 #[schemars(default)]
2483 pub watch_mode: WatchMode,
2484 pub dir: Option<String>,
2486 pub env: Option<IndexMap<String, String>>,
2488 #[serde(default)]
2493 pub env_file: Vec<String>,
2494 pub hooks: Option<PitchforkTomlHooks>,
2496 pub mise: Option<bool>,
2499 #[schemars(skip)]
2502 pub deferred_template_context: Option<String>,
2503 pub user: Option<String>,
2506 pub memory_limit: Option<MemoryLimit>,
2509 pub cpu_limit: Option<CpuLimit>,
2512 pub stop_signal: Option<StopConfig>,
2515 pub pty: Option<bool>,
2517 pub time_retention: Option<String>,
2520 pub line_retention: Option<i64>,
2523 pub archive_hook: Option<String>,
2526 pub logs: Option<PitchforkTomlDaemonLogs>,
2528 #[schemars(skip)]
2529 pub path: Option<PathBuf>,
2530}
2531
2532impl PitchforkTomlDaemon {
2533 pub fn effective_proxy_tls_port(&self) -> Option<u16> {
2539 self.proxy_tls_port.or(self.proxy_port)
2540 }
2541
2542 pub fn is_oneshot(&self) -> bool {
2544 self.oneshot.unwrap_or(false)
2545 }
2546
2547 pub(crate) fn oneshot_conflicts(&self) -> Vec<&'static str> {
2550 [
2551 ("ready_delay", self.ready_delay.is_some()),
2552 ("ready_output", self.ready_output.is_some()),
2553 ("ready_http", self.ready_http.is_some()),
2554 ("ready_port", self.ready_port.is_some()),
2555 ("ready_cmd", self.ready_cmd.is_some()),
2556 ("health_cmd", self.health_cmd.is_some()),
2557 ("health_http", self.health_http.is_some()),
2558 ("health_port", self.health_port.is_some()),
2559 ]
2560 .into_iter()
2561 .filter(|(_, set)| *set)
2562 .map(|(name, _)| name)
2563 .collect()
2564 }
2565
2566 pub fn effective_user(&self) -> Option<String> {
2570 let daemon_user = self
2571 .user
2572 .as_deref()
2573 .map(str::trim)
2574 .filter(|u| !u.is_empty());
2575 daemon_user.map(str::to_owned).or_else(|| {
2576 let s = crate::settings::settings();
2577 let su = s.supervisor.user.trim();
2578 (!su.is_empty()).then(|| su.to_owned())
2579 })
2580 }
2581
2582 pub fn to_run_options(
2587 &self,
2588 id: &crate::daemon_id::DaemonId,
2589 cmd: Vec<String>,
2590 ) -> crate::daemon::RunOptions {
2591 use crate::daemon::RunOptions;
2592
2593 let effective_user = self.effective_user();
2594 let dir = crate::ipc::batch::resolve_daemon_dir(
2595 self.dir.as_deref(),
2596 self.path.as_deref(),
2597 effective_user.as_deref(),
2598 );
2599 let slug = PitchforkToml::find_slug_for_daemon_in_registry(
2602 id,
2603 &PitchforkToml::read_global_slugs(),
2604 );
2605
2606 RunOptions {
2607 id: id.clone(),
2608 cmd,
2609 run: self.run.shell_script().map(str::to_string),
2610 no_shell: self.run.is_argv(),
2611 replaces_ready_checks: false,
2612 requested_by_client: false,
2614 force: false,
2615 shell_pid: None,
2616 dir: Dir(dir),
2617 autostop: self.auto.contains(&PitchforkTomlAuto::Stop),
2618 oneshot: self.is_oneshot(),
2619 cron_started: false,
2622 oneshot_wait: None,
2626 on_directory_enter: false,
2627 cron_schedule: self.cron.as_ref().map(|c| c.schedule.clone()),
2628 cron_retrigger: self.cron.as_ref().map(|c| c.retrigger),
2629 cron_immediate: self.cron.as_ref().map(|c| c.immediate),
2630 retry: self.retry,
2631 retry_count: 0,
2632 ready_delay: self.ready_delay,
2633 ready_output: self.ready_output.clone(),
2634 ready_http: self.ready_http.clone(),
2635 ready_port: self.ready_port.clone(),
2636 ready_cmd: self.ready_cmd.clone(),
2637 health_cmd: self.health_cmd.clone(),
2638 health_http: self.health_http.clone(),
2639 health_port: self.health_port.clone(),
2640 port: self.port.clone(),
2641 wait_ready: false,
2642 depends: self.depends.clone(),
2643 env: self.env.clone(),
2644 watch: self.watch.clone(),
2645 watch_mode: self.watch_mode,
2646 watch_base_dir: Some(crate::ipc::batch::resolve_config_base_dir(
2647 self.path.as_deref(),
2648 )),
2649 mise: self.mise,
2650 deferred_template_context: self.deferred_template_context.clone(),
2651 mise_bin: None,
2653 slug,
2654 proxy: None,
2655 user: self.user.clone(),
2656 memory_limit: self.memory_limit,
2657 cpu_limit: self.cpu_limit,
2658 stop_signal: self.stop_signal,
2659 archive_hook: self
2660 .logs
2661 .as_ref()
2662 .and_then(|l| l.archive_hook.clone())
2663 .or_else(|| self.archive_hook.clone()),
2664 log_format: self.logs.as_ref().and_then(|l| l.log_format.clone()),
2665 on_output_hook: self.hooks.as_ref().and_then(|h| h.on_output.clone()),
2666 pty: self.pty,
2667 proxy_idle_timeout_ms: None,
2669 replaces_saved_record: true,
2670 }
2671 }
2672}
2673fn example_run_command() -> &'static str {
2674 "exec node server.js"
2675}
2676
2677#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, JsonSchema)]
2680#[serde(untagged)]
2681pub enum RunCommand {
2682 Shell(String),
2685 Argv(#[schemars(length(min = 1))] Vec<String>),
2689}
2690
2691impl Default for RunCommand {
2692 fn default() -> Self {
2693 Self::Shell(String::new())
2694 }
2695}
2696
2697impl From<String> for RunCommand {
2698 fn from(run: String) -> Self {
2699 Self::Shell(run)
2700 }
2701}
2702
2703impl From<&str> for RunCommand {
2704 fn from(run: &str) -> Self {
2705 Self::Shell(run.to_string())
2706 }
2707}
2708
2709impl From<Vec<String>> for RunCommand {
2710 fn from(argv: Vec<String>) -> Self {
2711 Self::Argv(argv)
2712 }
2713}
2714
2715impl PartialEq<str> for RunCommand {
2716 fn eq(&self, other: &str) -> bool {
2717 matches!(self, Self::Shell(run) if run == other)
2718 }
2719}
2720
2721impl PartialEq<&str> for RunCommand {
2722 fn eq(&self, other: &&str) -> bool {
2723 self == *other
2724 }
2725}
2726
2727impl std::fmt::Display for RunCommand {
2730 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2731 match self {
2732 Self::Shell(run) => f.write_str(run),
2733 Self::Argv(argv) => f.write_str(&shell_words::join(argv)),
2734 }
2735 }
2736}
2737
2738impl RunCommand {
2739 pub fn argv(&self) -> std::result::Result<Vec<String>, shell_words::ParseError> {
2742 match self {
2743 Self::Shell(run) => shell_words::split(run),
2744 Self::Argv(argv) => Ok(argv.clone()),
2745 }
2746 }
2747
2748 pub fn shell_script(&self) -> Option<&str> {
2750 match self {
2751 Self::Shell(run) => Some(run),
2752 Self::Argv(_) => None,
2753 }
2754 }
2755
2756 pub fn is_argv(&self) -> bool {
2757 matches!(self, Self::Argv(_))
2758 }
2759
2760 pub fn try_map<E>(
2762 &self,
2763 mut f: impl FnMut(&str) -> std::result::Result<String, E>,
2764 ) -> std::result::Result<Self, E> {
2765 Ok(match self {
2766 Self::Shell(run) => Self::Shell(f(run)?),
2767 Self::Argv(argv) => Self::Argv(
2768 argv.iter()
2769 .map(|arg| f(arg))
2770 .collect::<std::result::Result<_, _>>()?,
2771 ),
2772 })
2773 }
2774}
2775
2776#[cfg(test)]
2777mod tests {
2778 use super::*;
2779 use std::path::Path;
2780
2781 fn parse_groups(toml: &str) -> IndexMap<String, GroupEntry> {
2782 PitchforkToml::parse_str(toml, Path::new("/tmp/my-project/pitchfork.toml"))
2783 .unwrap()
2784 .groups
2785 }
2786
2787 fn names(ids: &[DaemonId]) -> Vec<&str> {
2788 ids.iter().map(|id| id.name()).collect()
2789 }
2790
2791 #[test]
2792 fn test_group_includes_expand_before_own_daemons_and_dedupe() {
2793 let groups = parse_groups(
2794 r#"
2795[groups.core]
2796daemons = ["db", "cache"]
2797
2798[groups.extras]
2799daemons = ["mailer", "cache"]
2800
2801[groups.all]
2802groups = ["core", "extras"]
2803daemons = ["api", "db"]
2804"#,
2805 );
2806 let all = expand_group(&groups, "all").unwrap();
2807 assert_eq!(names(&all), ["db", "cache", "mailer", "api"]);
2808 }
2809
2810 #[test]
2811 fn test_group_includes_nest_and_allow_diamonds() {
2812 let groups = parse_groups(
2813 r#"
2814[groups.base]
2815daemons = ["db"]
2816
2817[groups.left]
2818groups = ["base"]
2819daemons = ["l"]
2820
2821[groups.right]
2822groups = ["base"]
2823daemons = ["r"]
2824
2825[groups.top]
2826groups = ["left", "right"]
2827"#,
2828 );
2829 let top = expand_group(&groups, "top").unwrap();
2830 assert_eq!(names(&top), ["db", "l", "r"]);
2831 }
2832
2833 #[test]
2834 fn test_group_includes_shared_by_many_paths_are_expanded_once() {
2835 let mut toml = String::from("[groups.g0]\ngroups = [\"g1\", \"g1\"]\n");
2838 for i in 1..60 {
2839 toml.push_str(&format!(
2840 "\n[groups.g{i}]\ngroups = [\"g{n}\", \"g{n}\"]\n",
2841 n = i + 1
2842 ));
2843 }
2844 toml.push_str("\n[groups.g60]\ndaemons = [\"db\"]\n");
2845 let groups = parse_groups(&toml);
2846 assert_eq!(names(&expand_group(&groups, "g0").unwrap()), ["db"]);
2847 }
2848
2849 #[test]
2850 fn test_group_include_cycle_is_an_error() {
2851 let groups = parse_groups(
2852 r#"
2853[groups.a]
2854groups = ["b"]
2855
2856[groups.b]
2857groups = ["c"]
2858
2859[groups.c]
2860groups = ["a"]
2861"#,
2862 );
2863 let err = expand_group(&groups, "a").unwrap_err().to_string();
2864 assert!(err.contains("a -> b -> c -> a"), "{err}");
2865 let err = expand_group(&parse_groups("[groups.x]\ngroups = [\"x\"]\n"), "x")
2866 .unwrap_err()
2867 .to_string();
2868 assert!(err.contains("x -> x"), "{err}");
2869 }
2870
2871 #[test]
2872 fn test_group_include_of_undefined_group_is_an_error() {
2873 let groups = parse_groups("[groups.all]\ngroups = [\"cor\"]\n\n[groups.core]\n");
2874 let err = expand_group(&groups, "all").unwrap_err().to_string();
2875 assert!(
2876 err.contains("group 'all' includes undefined group 'cor'"),
2877 "{err}"
2878 );
2879 }
2880
2881 #[test]
2882 fn test_group_without_daemons_key_parses() {
2883 let groups = parse_groups("[groups.empty]\n");
2884 assert!(expand_group(&groups, "empty").unwrap().is_empty());
2885 }
2886
2887 #[test]
2888 fn test_daemon_user_parses_and_flows_to_run_options() {
2889 let pt = PitchforkToml::parse_str(
2890 r#"
2891[daemons.api]
2892run = "node server.js"
2893user = "postgres"
2894"#,
2895 Path::new("/tmp/my-project/pitchfork.toml"),
2896 )
2897 .unwrap();
2898
2899 let id = DaemonId::new("my-project", "api");
2900 let daemon = pt.daemons.get(&id).unwrap();
2901 assert_eq!(daemon.user.as_deref(), Some("postgres"));
2902
2903 let opts = daemon.to_run_options(&id, vec!["node".to_string(), "server.js".to_string()]);
2904 assert_eq!(opts.user.as_deref(), Some("postgres"));
2905 assert!(opts.replaces_saved_record);
2907 }
2908
2909 #[test]
2910 fn test_new_local_file_writes_daemons_of_the_directory_namespace() {
2911 let temp = tempfile::tempdir().unwrap();
2912 std::fs::write(
2913 temp.path().join("pitchfork.toml"),
2914 "namespace = \"myns\"\n\n[daemons.web]\nrun = \"sleep 60\"\n",
2915 )
2916 .unwrap();
2917 let path = temp.path().join("pitchfork.local.toml");
2918 let mut pt = PitchforkToml::new(path.clone());
2919 let id = DaemonId::new(namespace_from_path(&path).unwrap(), "api");
2920 assert_eq!(id.namespace(), "myns");
2921 pt.daemons.insert(
2922 id.clone(),
2923 PitchforkTomlDaemon {
2924 run: "sleep 60".into(),
2925 ..PitchforkTomlDaemon::default()
2926 },
2927 );
2928
2929 pt.write().unwrap();
2930
2931 let parsed = PitchforkToml::read(&path).unwrap();
2932 assert!(parsed.daemons.contains_key(&id));
2933 }
2934
2935 #[test]
2936 fn test_daemon_user_write_roundtrip() {
2937 let temp = tempfile::tempdir().unwrap();
2938 let path = temp.path().join("pitchfork.toml");
2939 let mut pt = PitchforkToml::new(path.clone());
2940 pt.namespace = Some("test-project".to_string());
2941 pt.daemons.insert(
2942 DaemonId::new("test-project", "api"),
2943 PitchforkTomlDaemon {
2944 run: "node server.js".into(),
2945 user: Some("postgres".to_string()),
2946 ..PitchforkTomlDaemon::default()
2947 },
2948 );
2949
2950 pt.write().unwrap();
2951
2952 let raw = std::fs::read_to_string(&path).unwrap();
2953 assert!(raw.contains("user = \"postgres\""));
2954
2955 let parsed = PitchforkToml::read(&path).unwrap();
2956 let daemon = parsed
2957 .daemons
2958 .get(&DaemonId::new("test-project", "api"))
2959 .unwrap();
2960 assert_eq!(daemon.user.as_deref(), Some("postgres"));
2961 }
2962
2963 fn awkward_argv() -> Vec<String> {
2965 [
2966 "node",
2967 "my server.js",
2968 "--name=\"a b\"",
2969 "it's",
2970 "a&b",
2971 "%PATH%",
2972 "$HOME",
2973 ]
2974 .map(str::to_string)
2975 .to_vec()
2976 }
2977
2978 #[test]
2979 fn test_run_array_parses_and_starts_without_a_shell() {
2980 let pt = PitchforkToml::parse_str(
2981 r#"
2982[daemons.api]
2983run = ["node", "my server.js", "--name=\"a b\"", "it's", "a&b", "%PATH%", "$HOME"]
2984"#,
2985 Path::new("/tmp/my-project/pitchfork.toml"),
2986 )
2987 .unwrap();
2988
2989 let id = DaemonId::new("my-project", "api");
2990 let daemon = pt.daemons.get(&id).unwrap();
2991 assert_eq!(daemon.run, RunCommand::Argv(awkward_argv()));
2992
2993 let opts = daemon.to_run_options(&id, daemon.run.argv().unwrap());
2994 assert_eq!(opts.cmd, awkward_argv());
2995 assert!(opts.no_shell);
2996 assert_eq!(opts.run, None);
2997 }
2998
2999 #[test]
3000 fn test_run_string_still_goes_through_the_shell() {
3001 let pt = PitchforkToml::parse_str(
3002 "[daemons.api]\nrun = \"exec node server.js\"\n",
3003 Path::new("/tmp/my-project/pitchfork.toml"),
3004 )
3005 .unwrap();
3006
3007 let id = DaemonId::new("my-project", "api");
3008 let daemon = pt.daemons.get(&id).unwrap();
3009 let opts = daemon.to_run_options(&id, daemon.run.argv().unwrap());
3010 assert!(!opts.no_shell);
3011 assert_eq!(opts.run.as_deref(), Some("exec node server.js"));
3012 }
3013
3014 #[test]
3015 fn test_run_array_write_roundtrip() {
3016 let temp = tempfile::tempdir().unwrap();
3017 let path = temp.path().join("pitchfork.toml");
3018 let mut pt = PitchforkToml::new(path.clone());
3019 pt.namespace = Some("test-project".to_string());
3020 let id = DaemonId::new("test-project", "api");
3021 pt.daemons.insert(
3022 id.clone(),
3023 PitchforkTomlDaemon {
3024 run: RunCommand::Argv(awkward_argv()),
3025 ..PitchforkTomlDaemon::default()
3026 },
3027 );
3028 pt.daemons.insert(
3029 DaemonId::new("test-project", "worker"),
3030 PitchforkTomlDaemon {
3031 run: "exec ./worker --queue \"a b\"".into(),
3032 ..PitchforkTomlDaemon::default()
3033 },
3034 );
3035
3036 pt.write().unwrap();
3037
3038 let parsed = PitchforkToml::read(&path).unwrap();
3039 assert_eq!(parsed.daemons[&id].run, RunCommand::Argv(awkward_argv()));
3040 assert_eq!(
3041 parsed.daemons[&DaemonId::new("test-project", "worker")].run,
3042 "exec ./worker --queue \"a b\""
3043 );
3044 }
3045
3046 #[test]
3047 fn test_run_array_must_name_a_program() {
3048 let err = PitchforkToml::parse_str(
3049 "[daemons.api]\nrun = []\n",
3050 Path::new("/tmp/my-project/pitchfork.toml"),
3051 )
3052 .unwrap_err();
3053 assert!(
3054 err.chain()
3055 .any(|cause| cause.to_string().contains("empty run array")),
3056 "unexpected error: {err:?}"
3057 );
3058 }
3059
3060 #[test]
3061 fn test_run_array_rejects_exec() {
3062 let err = PitchforkToml::parse_str(
3063 "[daemons.api]\nrun = [\"exec\", \"node\", \"server.js\"]\n",
3064 Path::new("/tmp/my-project/pitchfork.toml"),
3065 )
3066 .unwrap_err();
3067 assert!(
3068 err.chain().any(|cause| cause
3069 .to_string()
3070 .contains("starts its run array with \"exec\"")),
3071 "unexpected error: {err:?}"
3072 );
3073 }
3074
3075 #[test]
3076 fn test_ready_cmd_array_parses_in_both_forms() {
3077 let pt = PitchforkToml::parse_str(
3078 r#"
3079[daemons.api]
3080run = "node server.js"
3081ready_cmd = ["node", "my server.js", "--name=\"a b\"", "it's", "a&b", "%PATH%", "$HOME"]
3082
3083[daemons.db]
3084run = "postgres"
3085ready_cmd = { run = ["pg_isready", "-h", "localhost"], timeout = "30s" }
3086
3087[daemons.cache]
3088run = "redis-server"
3089ready_cmd = "redis-cli ping"
3090"#,
3091 Path::new("/tmp/my-project/pitchfork.toml"),
3092 )
3093 .unwrap();
3094
3095 let ready = |name: &str| {
3096 pt.daemons[&DaemonId::new("my-project", name)]
3097 .ready_cmd
3098 .clone()
3099 .unwrap()
3100 };
3101 assert_eq!(ready("api").run, RunCommand::Argv(awkward_argv()));
3102 assert_eq!(ready("api").timeout, None);
3103 assert_eq!(
3104 ready("db").run,
3105 RunCommand::Argv(
3106 ["pg_isready", "-h", "localhost"]
3107 .map(str::to_string)
3108 .to_vec()
3109 )
3110 );
3111 assert_eq!(
3112 ready("db").timeout,
3113 Some(std::time::Duration::from_secs(30))
3114 );
3115 assert_eq!(ready("cache").run, "redis-cli ping");
3116 }
3117
3118 #[test]
3119 fn test_ready_cmd_array_write_roundtrip() {
3120 let temp = tempfile::tempdir().unwrap();
3121 let path = temp.path().join("pitchfork.toml");
3122 let mut pt = PitchforkToml::new(path.clone());
3123 pt.namespace = Some("test-project".to_string());
3124 let short = ReadyCmd::new(awkward_argv());
3125 let full = ReadyCmd {
3126 run: RunCommand::Argv(
3127 ["pg_isready", "-h", "localhost"]
3128 .map(str::to_string)
3129 .to_vec(),
3130 ),
3131 timeout: Some(std::time::Duration::from_secs(30)),
3132 };
3133 for (name, ready_cmd) in [("api", &short), ("db", &full)] {
3134 pt.daemons.insert(
3135 DaemonId::new("test-project", name),
3136 PitchforkTomlDaemon {
3137 run: "true".into(),
3138 ready_cmd: Some(ready_cmd.clone()),
3139 ..PitchforkTomlDaemon::default()
3140 },
3141 );
3142 }
3143
3144 pt.write().unwrap();
3145
3146 let parsed = PitchforkToml::read(&path).unwrap();
3147 let ready = |name: &str| {
3148 parsed.daemons[&DaemonId::new("test-project", name)]
3149 .ready_cmd
3150 .clone()
3151 };
3152 assert_eq!(ready("api"), Some(short));
3153 assert_eq!(ready("db"), Some(full));
3154 }
3155
3156 #[test]
3157 fn test_ready_cmd_array_must_name_a_program() {
3158 for ready_cmd in ["[]", "[\"\"]", "{ run = [\"\", \"-h\"] }"] {
3159 let err = PitchforkToml::parse_str(
3160 &format!("[daemons.api]\nrun = \"true\"\nready_cmd = {ready_cmd}\n"),
3161 Path::new("/tmp/my-project/pitchfork.toml"),
3162 )
3163 .unwrap_err();
3164 assert!(
3165 err.chain().any(|cause| cause
3166 .to_string()
3167 .contains("has no program in its ready_cmd array")),
3168 "unexpected error for {ready_cmd}: {err:?}"
3169 );
3170 }
3171 }
3172
3173 #[test]
3174 fn test_ready_cmd_array_rejects_exec() {
3175 let err = PitchforkToml::parse_str(
3176 "[daemons.api]\nrun = \"true\"\nready_cmd = { run = [\"exec\", \"pg_isready\"] }\n",
3177 Path::new("/tmp/my-project/pitchfork.toml"),
3178 )
3179 .unwrap_err();
3180 assert!(
3181 err.chain().any(|cause| cause
3182 .to_string()
3183 .contains("starts its ready_cmd array with \"exec\"")),
3184 "unexpected error: {err:?}"
3185 );
3186 }
3187
3188 #[test]
3189 fn test_health_cmd_array_parses_and_round_trips() {
3190 let pt = PitchforkToml::parse_str(
3191 r#"
3192[daemons.api]
3193run = "node server.js"
3194health_cmd = ["node", "my server.js", "--name=\"a b\"", "it's", "a&b", "%PATH%", "$HOME"]
3195
3196[daemons.db]
3197run = "postgres"
3198health_cmd = { run = ["pg_isready", "-h", "localhost"], interval = "5s", retries = 2 }
3199
3200[daemons.cache]
3201run = "redis-server"
3202health_cmd = "redis-cli ping"
3203"#,
3204 Path::new("/tmp/my-project/pitchfork.toml"),
3205 )
3206 .unwrap();
3207 let health = |pt: &PitchforkToml, ns: &str, name: &str| {
3208 pt.daemons[&DaemonId::new(ns, name)]
3209 .health_cmd
3210 .clone()
3211 .unwrap()
3212 };
3213 assert_eq!(
3214 health(&pt, "my-project", "api").run,
3215 RunCommand::Argv(awkward_argv())
3216 );
3217 let db = health(&pt, "my-project", "db");
3218 assert_eq!(
3219 db.run,
3220 RunCommand::Argv(
3221 ["pg_isready", "-h", "localhost"]
3222 .map(str::to_string)
3223 .to_vec()
3224 )
3225 );
3226 assert_eq!(db.interval, Some(std::time::Duration::from_secs(5)));
3227 assert_eq!(db.retries, Some(2));
3228 assert_eq!(health(&pt, "my-project", "cache").run, "redis-cli ping");
3229
3230 let temp = tempfile::tempdir().unwrap();
3231 let path = temp.path().join("pitchfork.toml");
3232 let mut written = PitchforkToml::new(path.clone());
3233 written.namespace = Some("test-project".to_string());
3234 for name in ["api", "db"] {
3235 written.daemons.insert(
3236 DaemonId::new("test-project", name),
3237 PitchforkTomlDaemon {
3238 run: "true".into(),
3239 health_cmd: Some(health(&pt, "my-project", name)),
3240 ..PitchforkTomlDaemon::default()
3241 },
3242 );
3243 }
3244 written.write().unwrap();
3245 let parsed = PitchforkToml::read(&path).unwrap();
3246 for name in ["api", "db"] {
3247 assert_eq!(
3248 health(&parsed, "test-project", name),
3249 health(&pt, "my-project", name)
3250 );
3251 }
3252 }
3253
3254 #[test]
3255 fn test_health_cmd_array_must_name_a_program_and_not_exec() {
3256 for (health_cmd, expected) in [
3257 ("[]", "has no program in its health_cmd array"),
3258 ("[\"\"]", "has no program in its health_cmd array"),
3259 (
3260 "{ run = [\"exec\", \"pg_isready\"] }",
3261 "starts its health_cmd array with \"exec\"",
3262 ),
3263 ] {
3264 let err = PitchforkToml::parse_str(
3265 &format!("[daemons.api]\nrun = \"true\"\nhealth_cmd = {health_cmd}\n"),
3266 Path::new("/tmp/my-project/pitchfork.toml"),
3267 )
3268 .unwrap_err();
3269 assert!(
3270 err.chain()
3271 .any(|cause| cause.to_string().contains(expected)),
3272 "unexpected error for {health_cmd}: {err:?}"
3273 );
3274 }
3275 }
3276
3277 #[test]
3278 fn test_registry_dirs_expand_tilde() {
3279 let pt = PitchforkToml::parse_str(
3280 r#"
3281[slugs.api]
3282dir = "~/projects/api"
3283
3284[namespaces.web]
3285dir = "~/projects/web"
3286"#,
3287 Path::new("/tmp/config.toml"),
3288 )
3289 .unwrap();
3290
3291 assert_eq!(
3292 pt.slugs["api"].dir,
3293 Some(crate::env::HOME_DIR.join("projects/api"))
3294 );
3295 assert_eq!(
3296 pt.namespaces["web"].dir,
3297 crate::env::HOME_DIR.join("projects/web")
3298 );
3299 }
3300
3301 #[test]
3302 fn test_settings_write_roundtrip() {
3303 let temp = tempfile::tempdir().unwrap();
3304 let path = temp.path().join("pitchfork.toml");
3305 let mut pt = PitchforkToml::new(path.clone());
3306 pt.namespace = Some("test-project".to_string());
3307 pt.settings.web.auto_start = Some(true);
3308 pt.settings.general.log_level = Some("debug".to_string());
3309
3310 pt.write().unwrap();
3311
3312 let raw = std::fs::read_to_string(&path).unwrap();
3313 assert!(
3314 raw.contains("[settings.web]"),
3315 "settings.web section should be written, got:\n{raw}"
3316 );
3317 assert!(raw.contains("auto_start = true"));
3318 assert!(raw.contains("log_level = \"debug\""));
3319
3320 let parsed = PitchforkToml::read(&path).unwrap();
3321 assert_eq!(parsed.settings.web.auto_start, Some(true));
3322 assert_eq!(parsed.settings.general.log_level.as_deref(), Some("debug"));
3323 }
3324
3325 fn slug_entry(namespace: &str, daemon: Option<&str>) -> SlugEntry {
3326 SlugEntry {
3327 dir: None,
3328 namespace: Some(namespace.to_string()),
3329 daemon: daemon.map(str::to_string),
3330 }
3331 }
3332
3333 #[test]
3334 fn test_slug_is_ambiguous() {
3335 let mut slugs = IndexMap::new();
3336 slugs.insert("api".to_string(), slug_entry("my-project", None));
3337 assert!(!PitchforkToml::slug_is_ambiguous("api", &slugs));
3338
3339 slugs.insert("API".to_string(), slug_entry("other-project", None));
3340 assert!(PitchforkToml::slug_is_ambiguous("api", &slugs));
3342 assert!(PitchforkToml::slug_is_ambiguous("API", &slugs));
3343 }
3344
3345 #[test]
3346 fn test_find_slug_for_daemon_skips_case_collisions() {
3347 let id = DaemonId::new("my-project", "api");
3348 let mut slugs = IndexMap::new();
3349 slugs.insert("api".to_string(), slug_entry("my-project", None));
3350 assert_eq!(
3351 PitchforkToml::find_slug_for_daemon_in_registry(&id, &slugs),
3352 Some("api".to_string())
3353 );
3354
3355 slugs.insert("API".to_string(), slug_entry("other-project", None));
3358 assert_eq!(
3359 PitchforkToml::find_slug_for_daemon_in_registry(&id, &slugs),
3360 None
3361 );
3362 }
3363
3364 #[test]
3365 fn test_find_slug_for_daemon_prefers_a_routable_alias() {
3366 let id = DaemonId::new("my-project", "api");
3367 let mut slugs = IndexMap::new();
3368 slugs.insert("api".to_string(), slug_entry("my-project", None));
3371 slugs.insert("API".to_string(), slug_entry("my-project", None));
3372 slugs.insert("my-api".to_string(), slug_entry("my-project", Some("api")));
3373
3374 assert_eq!(
3375 PitchforkToml::find_slug_for_daemon_in_registry(&id, &slugs),
3376 Some("my-api".to_string())
3377 );
3378 }
3379
3380 #[test]
3381 fn test_settings_preserved_on_unrelated_write() {
3382 let temp = tempfile::tempdir().unwrap();
3385 let path = temp.path().join("pitchfork.toml");
3386 std::fs::write(&path, "[settings.web]\nauto_start = true\n").unwrap();
3387
3388 let mut pt = PitchforkToml::read(&path).unwrap();
3389 pt.slugs.insert(
3390 "api".to_string(),
3391 SlugEntry {
3392 dir: None,
3393 namespace: Some("myproject".to_string()),
3394 daemon: None,
3395 },
3396 );
3397 pt.namespaces.insert(
3398 "myproject".to_string(),
3399 NamespaceEntry {
3400 dir: PathBuf::from("/tmp/myproject"),
3401 config: Vec::new(),
3402 label: None,
3403 },
3404 );
3405 pt.write().unwrap();
3406
3407 let raw = std::fs::read_to_string(&path).unwrap();
3408 assert!(
3409 raw.contains("[settings.web]"),
3410 "existing settings must be preserved, got:\n{raw}"
3411 );
3412 assert!(raw.contains("auto_start = true"));
3413 assert!(raw.contains("[slugs.api]"));
3414
3415 let parsed = PitchforkToml::read(&path).unwrap();
3416 assert_eq!(parsed.settings.web.auto_start, Some(true));
3417 assert!(parsed.slugs.contains_key("api"));
3418 }
3419
3420 #[tokio::test]
3421 async fn test_proxy_worktree_alias_is_canonicalized_on_rewrite() {
3422 let temp = tempfile::tempdir().unwrap();
3423 let path = temp.path().join("pitchfork.toml");
3424 tokio::fs::write(&path, "[settings.proxy]\nworktree = false\n")
3425 .await
3426 .unwrap();
3427
3428 let read_path = path.clone();
3429 let pt = tokio::task::spawn_blocking(move || PitchforkToml::read(&read_path))
3430 .await
3431 .unwrap()
3432 .unwrap();
3433 assert_eq!(pt.settings.general.worktree, Some(false));
3434 assert_eq!(pt.settings.proxy.worktree, None);
3435 tokio::task::spawn_blocking(move || pt.write())
3436 .await
3437 .unwrap()
3438 .unwrap();
3439
3440 let raw = tokio::fs::read_to_string(&path).await.unwrap();
3441 assert!(raw.contains("[settings.general]"), "{raw}");
3442 assert!(raw.contains("worktree = false"), "{raw}");
3443 assert!(!raw.contains("[settings.proxy]"), "{raw}");
3444
3445 let parsed = tokio::task::spawn_blocking(move || PitchforkToml::read(&path))
3446 .await
3447 .unwrap()
3448 .unwrap();
3449 assert_eq!(parsed.settings.general.worktree, Some(false));
3450 }
3451
3452 #[test]
3453 fn test_config_cache_hit_and_invalidation() {
3454 let temp = tempfile::tempdir().unwrap();
3455 let dir = temp.path();
3456 let config_path = dir.join("pitchfork.toml");
3457 std::fs::write(&config_path, "[daemons.api]\nrun = \"echo v1\"\n").unwrap();
3458
3459 super::invalidate_config_cache();
3461
3462 let pt1 = PitchforkToml::all_merged_from(dir).unwrap();
3464 let daemon_id = DaemonId::new(namespace_from_path(&config_path).unwrap(), "api");
3465 assert_eq!(pt1.daemons[&daemon_id].run, "echo v1");
3466
3467 let pt2 = PitchforkToml::all_merged_from(dir).unwrap();
3469 assert_eq!(pt2.daemons[&daemon_id].run, "echo v1");
3470
3471 std::thread::sleep(std::time::Duration::from_millis(50));
3474 std::fs::write(&config_path, "[daemons.api]\nrun = \"echo v2\"\n").unwrap();
3475
3476 let pt3 = PitchforkToml::all_merged_from(dir).unwrap();
3477 assert_eq!(pt3.daemons[&daemon_id].run, "echo v2");
3478
3479 super::invalidate_config_cache();
3481 let pt4 = PitchforkToml::all_merged_from(dir).unwrap();
3482 assert_eq!(pt4.daemons[&daemon_id].run, "echo v2");
3483
3484 super::invalidate_config_cache();
3486 }
3487
3488 #[test]
3489 fn test_config_cache_invalidation_on_write() {
3490 let temp = tempfile::tempdir().unwrap();
3491 let dir = temp.path();
3492 let config_path = dir.join("pitchfork.toml");
3493 std::fs::write(&config_path, "[daemons.api]\nrun = \"echo v1\"\n").unwrap();
3494
3495 super::invalidate_config_cache();
3496
3497 let pt1 = PitchforkToml::all_merged_from(dir).unwrap();
3499 let daemon_id = DaemonId::new(namespace_from_path(&config_path).unwrap(), "api");
3500 assert_eq!(pt1.daemons[&daemon_id].run, "echo v1");
3501
3502 let mut pt = PitchforkToml::read(&config_path).unwrap();
3504 pt.daemons.get_mut(&daemon_id).unwrap().run = "echo v3".into();
3505 let _ = pt.write();
3507
3508 let pt2 = PitchforkToml::all_merged_from(dir).unwrap();
3510 assert_eq!(pt2.daemons[&daemon_id].run, "echo v3");
3511
3512 super::invalidate_config_cache();
3513 }
3514
3515 #[test]
3516 fn test_config_cache_size_invalidation() {
3517 let temp = tempfile::tempdir().unwrap();
3518 let dir = temp.path();
3519 let config_path = dir.join("pitchfork.toml");
3520 std::fs::write(&config_path, "[daemons.api]\nrun = \"echo v1\"\n").unwrap();
3521
3522 super::invalidate_config_cache();
3523
3524 let pt1 = PitchforkToml::all_merged_from(dir).unwrap();
3526 let daemon_id = DaemonId::new(namespace_from_path(&config_path).unwrap(), "api");
3527 assert_eq!(pt1.daemons[&daemon_id].run, "echo v1");
3528
3529 let original_mtime = std::fs::metadata(&config_path).unwrap().modified().unwrap();
3533 std::fs::write(&config_path, "[daemons.api]\nrun = \"echo different\"\n").unwrap();
3534 let file = std::fs::OpenOptions::new()
3537 .write(true)
3538 .open(&config_path)
3539 .unwrap();
3540 let times = std::fs::FileTimes::new().set_modified(original_mtime);
3541 file.set_times(times).unwrap();
3542
3543 let pt2 = PitchforkToml::all_merged_from(dir).unwrap();
3546 assert_eq!(
3547 pt2.daemons[&daemon_id].run, "echo different",
3548 "cache should invalidate on size change even with identical mtime"
3549 );
3550
3551 super::invalidate_config_cache();
3552 }
3553
3554 #[test]
3555 fn test_find_project_root_in_plain_dir_returns_none() {
3556 let temp = tempfile::tempdir().unwrap();
3557 assert_eq!(find_project_root(temp.path()), None);
3558 }
3559
3560 #[test]
3561 fn test_find_project_root_finds_git_marker() {
3562 let temp = tempfile::tempdir().unwrap();
3563 let repo = temp.path().join("my-repo");
3564 std::fs::create_dir(&repo).unwrap();
3565 std::fs::create_dir(repo.join(".git")).unwrap();
3566
3567 let sub = repo.join("sub/dir");
3568 std::fs::create_dir_all(&sub).unwrap();
3569
3570 assert_eq!(find_project_root(&sub), Some(repo.canonicalize().unwrap()));
3573 }
3574
3575 #[test]
3576 fn test_find_project_root_accepts_git_file_marker() {
3577 let temp = tempfile::tempdir().unwrap();
3580 let wt = temp.path().join("my-worktree");
3581 std::fs::create_dir(&wt).unwrap();
3582 std::fs::write(wt.join(".git"), "gitdir: /tmp/some-common-gitdir\n").unwrap();
3583
3584 assert_eq!(find_project_root(&wt), Some(wt.canonicalize().unwrap()));
3585 }
3586
3587 #[cfg(unix)]
3590 #[test]
3591 fn test_find_project_root_resolves_symlinked_start_dir() {
3592 use std::os::unix::fs::symlink;
3593
3594 let temp = tempfile::tempdir().unwrap();
3595 let repo = temp.path().join("real-repo");
3596 std::fs::create_dir(&repo).unwrap();
3597 std::fs::create_dir(repo.join(".git")).unwrap();
3598
3599 let sub = repo.join("sub/dir");
3600 std::fs::create_dir_all(&sub).unwrap();
3601 let link = temp.path().join("link-to-sub");
3602 symlink(&sub, &link).unwrap();
3603
3604 assert_eq!(find_project_root(&link), Some(repo.canonicalize().unwrap()));
3605 }
3606
3607 #[test]
3610 fn test_all_merged_all_namespaces_discovers_worktrees() {
3611 let temp = tempfile::tempdir().unwrap();
3612 let repo = temp.path().join("my-repo");
3613 std::fs::create_dir(&repo).unwrap();
3614
3615 let git_init = std::process::Command::new("git")
3617 .args(["init", "-b", "main"])
3618 .current_dir(&repo)
3619 .output()
3620 .expect("git init");
3621 assert!(git_init.status.success(), "git init failed: {:?}", git_init);
3622
3623 std::fs::write(repo.join("main.toml"), "hello\n").unwrap();
3624
3625 let git_commit = std::process::Command::new("git")
3626 .args([
3627 "-c",
3628 "user.name=pitchfork-test",
3629 "-c",
3630 "user.email=pitchfork-test@example.com",
3631 "add",
3632 "-A",
3633 ])
3634 .current_dir(&repo)
3635 .output()
3636 .expect("git add");
3637 assert!(git_commit.status.success());
3638
3639 let git_commit = std::process::Command::new("git")
3640 .args([
3641 "-c",
3642 "user.name=pitchfork-test",
3643 "-c",
3644 "user.email=pitchfork-test@example.com",
3645 "commit",
3646 "-m",
3647 "init",
3648 ])
3649 .current_dir(&repo)
3650 .output()
3651 .expect("git commit");
3652 assert!(
3653 git_commit.status.success(),
3654 "git commit failed: {:?}",
3655 git_commit
3656 );
3657
3658 let wt = temp.path().join("my-repo-feature");
3659 let git_wt = std::process::Command::new("git")
3660 .args(["worktree", "add", "-b", "feature-x", wt.to_str().unwrap()])
3661 .current_dir(&repo)
3662 .output()
3663 .expect("git worktree add");
3664 assert!(
3665 git_wt.status.success(),
3666 "git worktree add failed: {:?}",
3667 git_wt
3668 );
3669
3670 std::fs::write(
3672 repo.join("pitchfork.toml"),
3673 "[daemons.api]\nrun = \"echo main\"\n",
3674 )
3675 .unwrap();
3676 std::fs::write(
3678 wt.join("pitchfork.toml"),
3679 "[daemons.worker]\nrun = \"echo wt\"\n",
3680 )
3681 .unwrap();
3682
3683 super::invalidate_config_cache();
3684
3685 let pt = PitchforkToml::all_merged_all_namespaces_from_blocking(&wt).unwrap();
3687
3688 let main_id = DaemonId::new("my-repo", "api");
3689 let wt_id = DaemonId::new("my-repo-feature", "worker");
3690 assert!(
3691 pt.daemons.contains_key(&main_id),
3692 "main checkout daemon missing"
3693 );
3694 assert!(pt.daemons.contains_key(&wt_id), "worktree daemon missing");
3695
3696 let pt_from_main = PitchforkToml::all_merged_all_namespaces_from_blocking(&repo).unwrap();
3698 assert!(pt_from_main.daemons.contains_key(&wt_id));
3699
3700 let _ = std::process::Command::new("git")
3702 .args(["worktree", "remove", "--force", wt.to_str().unwrap()])
3703 .current_dir(&repo)
3704 .output();
3705 super::invalidate_config_cache();
3706 }
3707
3708 #[test]
3709 fn test_adhoc_id_uses_invocation_directory_namespace() {
3710 let temp = tempfile::tempdir().unwrap();
3711 let project = temp.path().join("feature-tree");
3712 std::fs::create_dir(&project).unwrap();
3713 std::fs::write(
3714 project.join("pitchfork.toml"),
3715 "[daemons.other]\nrun = \"true\"\n",
3716 )
3717 .unwrap();
3718
3719 let id = PitchforkToml::resolve_id_allow_adhoc_from("api", &project).unwrap();
3720 assert_eq!(id, DaemonId::new("feature-tree", "api"));
3721 let qualified =
3722 PitchforkToml::resolve_id_allow_adhoc_from("explicit/api", &project).unwrap();
3723 assert_eq!(qualified, DaemonId::new("explicit", "api"));
3724 }
3725
3726 #[test]
3727 fn test_adhoc_id_falls_back_to_global_without_project_config() {
3728 let temp = tempfile::tempdir().unwrap();
3729 let id = PitchforkToml::resolve_id_allow_adhoc_from("api", temp.path()).unwrap();
3730 assert_eq!(id, DaemonId::new("global", "api"));
3731 }
3732}