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::tui::theme::ThemeDef;
8use crate::{Result, env};
9use indexmap::IndexMap;
10use miette::Context;
11use once_cell::sync::Lazy;
12use schemars::JsonSchema;
13use std::collections::{HashMap, HashSet};
14use std::path::{Path, PathBuf};
15use std::sync::Mutex as StdMutex;
16use std::time::SystemTime;
17
18pub use crate::config_types::{
20 CpuLimit, CronRetrigger, Dir, HealthCmd, HealthHttp, HealthPort, MemoryLimit, OnOutputHook,
21 PitchforkTomlAuto, PitchforkTomlCron, PitchforkTomlHooks, PortBump, PortConfig, ProxyConfig,
22 ProxyIdleTimeout, ProxyProtocol, ProxyTlsMode, ReadyCmd, ReadyHttp, ReadyOutput, ReadyPort,
23 Retry, StopConfig, StopSignal, WatchMode,
24};
25
26#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, JsonSchema)]
34pub struct SlugEntryRaw {
35 #[serde(default, skip_serializing_if = "Option::is_none")]
37 pub dir: Option<String>,
38 #[serde(default, skip_serializing_if = "Option::is_none")]
40 pub namespace: Option<String>,
41 #[serde(skip_serializing_if = "Option::is_none", default)]
43 pub daemon: Option<String>,
44}
45
46#[derive(Debug, Clone)]
48pub struct SlugEntry {
49 pub dir: Option<PathBuf>,
51 pub namespace: Option<String>,
53 pub daemon: Option<String>,
55}
56
57impl SlugEntry {
58 pub fn resolve_dir(&self) -> Option<PathBuf> {
61 self.dir.clone().or_else(|| {
62 self.namespace.as_ref().and_then(|ns| {
63 let namespaces = PitchforkToml::read_global_namespaces();
64 namespaces.get(ns).map(|entry| entry.dir.clone())
65 })
66 })
67 }
68
69 pub fn resolve_namespace(&self) -> Option<String> {
72 self.namespace.clone().or_else(|| {
73 self.resolve_dir()
74 .and_then(|dir| PitchforkToml::namespace_for_dir(&dir).ok())
75 })
76 }
77}
78
79#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, JsonSchema)]
89pub struct GroupEntryRaw {
90 #[serde(default, skip_serializing_if = "Vec::is_empty")]
92 #[schemars(with = "Vec<DaemonId>")]
93 pub daemons: Vec<String>,
94 #[serde(default, skip_serializing_if = "Vec::is_empty")]
96 pub groups: Vec<String>,
97}
98
99#[derive(Debug, Clone, Default)]
105pub struct GroupEntry {
106 pub daemons: Vec<DaemonId>,
107 pub groups: Vec<String>,
108}
109
110pub fn expand_group(groups: &IndexMap<String, GroupEntry>, name: &str) -> Result<Vec<DaemonId>> {
117 fn visit(
118 groups: &IndexMap<String, GroupEntry>,
119 name: &str,
120 path: &mut Vec<String>,
121 done: &mut HashSet<String>,
122 seen: &mut HashSet<DaemonId>,
123 out: &mut Vec<DaemonId>,
124 ) -> Result<()> {
125 if done.contains(name) {
128 return Ok(());
129 }
130 let Some(group) = groups.get(name) else {
131 let suggestion = find_similar_daemon(name, groups.keys().map(|s| s.as_str()));
132 return Err(match path.last() {
133 Some(parent) => miette::miette!(
134 "group '{parent}' includes undefined group '{name}'{}",
135 suggestion.map(|s| format!(", {s}")).unwrap_or_default()
136 ),
137 None => miette::miette!(
138 "group '{name}' not found in configuration{}",
139 suggestion.map(|s| format!(", {s}")).unwrap_or_default()
140 ),
141 });
142 };
143 if path.iter().any(|p| p == name) {
144 return Err(miette::miette!(
145 "group include cycle: {} -> {name}",
146 path.join(" -> ")
147 ));
148 }
149 path.push(name.to_string());
150 for included in &group.groups {
151 visit(groups, included, path, done, seen, out)?;
152 }
153 path.pop();
154 for id in &group.daemons {
155 if seen.insert(id.clone()) {
156 out.push(id.clone());
157 }
158 }
159 done.insert(name.to_string());
160 Ok(())
161 }
162
163 let mut out = Vec::new();
164 visit(
165 groups,
166 name,
167 &mut Vec::new(),
168 &mut HashSet::new(),
169 &mut HashSet::new(),
170 &mut out,
171 )?;
172 Ok(out)
173}
174
175#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, JsonSchema)]
181pub struct NamespaceEntryRaw {
182 pub dir: String,
184 #[serde(default, skip_serializing_if = "Vec::is_empty")]
186 pub config: Vec<String>,
187 #[serde(default, skip_serializing_if = "Option::is_none")]
191 pub label: Option<String>,
192}
193
194#[derive(Debug, Clone)]
196pub struct NamespaceEntry {
197 pub dir: PathBuf,
199 pub config: Vec<PathBuf>,
200 pub label: Option<String>,
202}
203
204#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
206struct PitchforkTomlRaw {
207 #[serde(skip_serializing_if = "Option::is_none", default)]
208 pub namespace: Option<String>,
209 #[serde(skip_serializing_if = "Option::is_none", default)]
211 pub worktree_label: Option<String>,
212 #[serde(default)]
213 pub daemons: IndexMap<String, PitchforkTomlDaemonRaw>,
214 #[serde(skip_serializing_if = "Option::is_none", default)]
217 pub env: Option<IndexMap<String, String>>,
218 #[serde(default)]
219 pub settings: Option<SettingsPartial>,
220 #[serde(skip_serializing_if = "IndexMap::is_empty", default)]
223 pub slugs: IndexMap<String, SlugEntryRaw>,
224 #[serde(skip_serializing_if = "IndexMap::is_empty", default)]
226 pub groups: IndexMap<String, GroupEntryRaw>,
227 #[serde(skip_serializing_if = "IndexMap::is_empty", default)]
230 pub namespaces: IndexMap<String, NamespaceEntryRaw>,
231 #[serde(skip_serializing_if = "IndexMap::is_empty", default)]
233 pub themes: IndexMap<String, ThemeDef>,
234}
235
236#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
241pub struct PitchforkTomlDaemonLogs {
242 #[serde(skip_serializing_if = "Option::is_none", default)]
245 pub log_format: Option<String>,
246 #[serde(skip_serializing_if = "Option::is_none", default)]
248 pub time_retention: Option<String>,
249 #[serde(skip_serializing_if = "Option::is_none", default)]
251 pub line_retention: Option<i64>,
252 #[serde(skip_serializing_if = "Option::is_none", default)]
254 pub archive_hook: Option<String>,
255}
256
257#[derive(Debug, serde::Serialize, serde::Deserialize)]
264struct PitchforkTomlDaemonRaw {
265 pub run: RunCommand,
266 #[serde(skip_serializing_if = "Vec::is_empty", default)]
267 pub auto: Vec<PitchforkTomlAuto>,
268 #[serde(skip_serializing_if = "Option::is_none", default)]
269 pub oneshot: Option<bool>,
270 #[serde(skip_serializing_if = "Option::is_none", default)]
271 pub cron: Option<PitchforkTomlCron>,
272 #[serde(default)]
273 pub retry: Retry,
274 #[serde(skip_serializing_if = "Option::is_none", default)]
275 pub ready_delay: Option<u64>,
276 #[serde(skip_serializing_if = "Option::is_none", default)]
277 pub ready_output: Option<ReadyOutput>,
278 #[serde(skip_serializing_if = "Option::is_none", default)]
279 pub ready_http: Option<ReadyHttp>,
280 #[serde(skip_serializing_if = "Option::is_none", default)]
281 pub ready_port: Option<ReadyPort>,
282 #[serde(skip_serializing_if = "Option::is_none", default)]
283 pub ready_cmd: Option<ReadyCmd>,
284 #[serde(skip_serializing_if = "Option::is_none", default)]
285 pub health_cmd: Option<HealthCmd>,
286 #[serde(skip_serializing_if = "Option::is_none", default)]
287 pub health_http: Option<HealthHttp>,
288 #[serde(skip_serializing_if = "Option::is_none", default)]
289 pub health_port: Option<HealthPort>,
290 #[serde(skip_serializing_if = "Option::is_none", default)]
292 pub port: Option<PortConfig>,
293 #[serde(skip_serializing_if = "Option::is_none", default)]
295 pub proxy: Option<ProxyConfig>,
296 #[serde(skip_serializing_if = "Vec::is_empty", default)]
298 pub expected_port: Vec<u16>,
299 #[serde(skip_serializing_if = "Option::is_none", default)]
301 pub auto_bump_port: Option<bool>,
302 #[serde(skip_serializing_if = "Option::is_none", default)]
304 pub port_bump_attempts: Option<u32>,
305 #[serde(skip_serializing_if = "Option::is_none", default)]
307 pub proxy_tls: Option<ProxyTlsMode>,
308 #[serde(skip_serializing_if = "Option::is_none", default)]
310 pub proxy_protocol: Option<ProxyProtocol>,
311 #[serde(skip_serializing_if = "Option::is_none", default)]
313 pub proxy_tls_port: Option<u16>,
314 #[serde(skip_serializing_if = "Option::is_none", default)]
317 pub proxy_port: Option<u16>,
318 #[serde(skip_serializing_if = "Option::is_none", default)]
320 pub proxy_idle_timeout: Option<ProxyIdleTimeout>,
321 #[serde(skip_serializing_if = "Option::is_none", default)]
322 pub boot_start: Option<bool>,
323 #[serde(skip_serializing_if = "Vec::is_empty", default)]
324 pub depends: Vec<String>,
325 #[serde(skip_serializing_if = "Vec::is_empty", default)]
326 pub watch: Vec<String>,
327 #[serde(skip_serializing_if = "Option::is_none", default)]
328 pub watch_mode: Option<WatchMode>,
329 #[serde(skip_serializing_if = "Option::is_none", default)]
330 pub dir: Option<String>,
331 #[serde(skip_serializing_if = "Option::is_none", default)]
332 pub env: Option<IndexMap<String, String>>,
333 #[serde(skip_serializing_if = "Vec::is_empty", default)]
334 pub env_file: Vec<String>,
335 #[serde(skip_serializing_if = "Option::is_none", default)]
336 pub hooks: Option<PitchforkTomlHooks>,
337 #[serde(skip_serializing_if = "Option::is_none", default)]
338 pub mise: Option<bool>,
339 #[serde(skip_serializing_if = "Option::is_none", default)]
342 pub user: Option<String>,
343 #[serde(skip_serializing_if = "Option::is_none", default)]
345 pub memory_limit: Option<MemoryLimit>,
346 #[serde(skip_serializing_if = "Option::is_none", default)]
348 pub cpu_limit: Option<CpuLimit>,
349 #[serde(skip_serializing_if = "Option::is_none", default)]
351 pub stop_signal: Option<StopConfig>,
352 #[serde(skip_serializing_if = "Option::is_none", default)]
354 pub pty: Option<bool>,
355 #[serde(skip_serializing_if = "Option::is_none", default)]
358 pub time_retention: Option<String>,
359 #[serde(skip_serializing_if = "Option::is_none", default)]
362 pub line_retention: Option<i64>,
363 #[serde(skip_serializing_if = "Option::is_none", default)]
366 pub archive_hook: Option<String>,
367 #[serde(skip_serializing_if = "Option::is_none", default)]
369 pub logs: Option<PitchforkTomlDaemonLogs>,
370}
371
372#[derive(Debug, Clone, Default, JsonSchema)]
377#[schemars(title = "Pitchfork Configuration")]
378pub struct PitchforkToml {
379 #[serde(default)]
381 pub daemons: IndexMap<DaemonId, PitchforkTomlDaemon>,
382 #[serde(skip_serializing_if = "Option::is_none", default)]
386 pub env: Option<IndexMap<String, String>>,
387 pub namespace: Option<String>,
392 #[schemars(default, with = "Option<String>")]
396 pub worktree_label: Option<String>,
397 #[serde(default)]
406 pub(crate) settings: SettingsPartial,
407 #[schemars(default, with = "IndexMap<String, SlugEntryRaw>")]
412 pub slugs: IndexMap<String, SlugEntry>,
413 #[schemars(default, with = "IndexMap<String, GroupEntryRaw>")]
415 pub groups: IndexMap<String, GroupEntry>,
416 #[schemars(default, with = "IndexMap<String, NamespaceEntryRaw>")]
419 pub namespaces: IndexMap<String, NamespaceEntry>,
420 #[serde(default)]
432 pub themes: IndexMap<String, ThemeDef>,
433 #[schemars(skip)]
434 pub path: Option<PathBuf>,
435 #[schemars(skip)]
443 pub(crate) foreign_env: IndexMap<DaemonId, Option<IndexMap<String, String>>>,
444}
445
446impl PitchforkToml {
447 pub(crate) fn env_for(&self, id: &DaemonId) -> Option<&IndexMap<String, String>> {
450 self.foreign_env
451 .get(id)
452 .map_or(self.env.as_ref(), |env| env.as_ref())
453 }
454}
455
456pub fn is_global_config(path: &Path) -> bool {
457 path == *env::PITCHFORK_GLOBAL_CONFIG_USER || path == *env::PITCHFORK_GLOBAL_CONFIG_SYSTEM
458}
459
460pub(crate) fn is_dot_config_pitchfork(path: &Path) -> bool {
461 path.ends_with(".config/pitchfork.toml") || path.ends_with(".config/pitchfork.local.toml")
462}
463
464fn parse_namespace_override_from_content(path: &Path, content: &str) -> Result<Option<String>> {
465 use toml::Value;
466
467 let doc: Value = toml::from_str(content)
468 .map_err(|e| ConfigParseError::from_toml_error(path, content.to_string(), e))?;
469 let Some(value) = doc.get("namespace") else {
470 return Ok(None);
471 };
472
473 match value {
474 Value::String(s) => Ok(Some(s.clone())),
475 _ => Err(ConfigParseError::InvalidNamespace {
476 path: path.to_path_buf(),
477 namespace: value.to_string(),
478 reason: "top-level 'namespace' must be a string".to_string(),
479 }
480 .into()),
481 }
482}
483
484fn read_namespace_override_from_file(path: &Path) -> Result<Option<String>> {
485 if !path.exists() {
486 return Ok(None);
487 }
488 let content = std::fs::read_to_string(path).map_err(|e| FileError::ReadError {
489 path: path.to_path_buf(),
490 source: e,
491 })?;
492 parse_namespace_override_from_content(path, &content)
493}
494
495pub fn project_dir_for_config(path: &Path) -> Option<PathBuf> {
496 crate::extra_configs::project_dir(path).or_else(|| {
497 if is_dot_config_pitchfork(path) {
498 path.parent().and_then(Path::parent).map(Path::to_path_buf)
499 } else {
500 path.parent().map(Path::to_path_buf)
501 }
502 })
503}
504
505fn project_config_family(path: &Path) -> Vec<PathBuf> {
506 let Some(dir) = project_dir_for_config(path) else {
507 return vec![path.to_path_buf()];
508 };
509 vec![
510 dir.join(".config/pitchfork.toml"),
511 dir.join(".config/pitchfork.local.toml"),
512 dir.join("pitchfork.toml"),
513 dir.join("pitchfork.local.toml"),
514 ]
515}
516
517fn directory_namespace_override(
520 path: &Path,
521 content_override: Option<&str>,
522) -> Result<Option<String>> {
523 if is_global_config(path) {
524 return match content_override {
525 Some(content) => parse_namespace_override_from_content(path, content),
526 None => read_namespace_override_from_file(path),
527 };
528 }
529
530 let mut selected: Option<(String, PathBuf)> = None;
531 for candidate in project_config_family(path) {
532 let explicit = if candidate == path {
533 match content_override {
534 Some(content) => parse_namespace_override_from_content(&candidate, content)?,
535 None => read_namespace_override_from_file(&candidate)?,
536 }
537 } else {
538 read_namespace_override_from_file(&candidate)?
539 };
540 let Some(namespace) = explicit else { continue };
541 if let Some((selected_namespace, selected_path)) = &selected
542 && selected_namespace != &namespace
543 {
544 return Err(ConfigParseError::InvalidNamespace {
545 path: candidate,
546 namespace,
547 reason: format!(
548 "namespace does not match directory-level namespace '{}' declared in {}",
549 selected_namespace,
550 selected_path.display()
551 ),
552 }
553 .into());
554 }
555 selected = Some((namespace, candidate));
556 }
557 Ok(selected.map(|(namespace, _)| namespace))
558}
559
560fn validate_namespace(path: &Path, namespace: &str) -> Result<String> {
561 if let Err(e) = DaemonId::try_new(namespace, "probe") {
562 return Err(ConfigParseError::InvalidNamespace {
563 path: path.to_path_buf(),
564 namespace: namespace.to_string(),
565 reason: e.to_string(),
566 }
567 .into());
568 }
569 Ok(namespace.to_string())
570}
571
572fn derive_namespace_from_dir(path: &Path) -> Result<String> {
573 let dir_for_namespace = project_dir_for_config(path);
574 if let Some(namespace) = dir_for_namespace
575 .as_deref()
576 .and_then(crate::extra_configs::namespace_for_dir)
577 {
578 return validate_namespace(path, &namespace);
579 }
580 let raw_namespace = dir_for_namespace
581 .as_deref()
582 .and_then(|p| p.file_name())
583 .and_then(|n| n.to_str())
584 .ok_or_else(|| miette::miette!("cannot derive namespace from path '{}'", path.display()))?
585 .to_string();
586
587 validate_namespace(path, &raw_namespace).map_err(|e| {
588 ConfigParseError::InvalidNamespace {
589 path: path.to_path_buf(),
590 namespace: raw_namespace,
591 reason: format!(
592 "{e}. Set a valid top-level namespace, e.g. namespace = \"my-project\""
593 ),
594 }
595 .into()
596 })
597}
598
599fn namespace_from_path_with_override(path: &Path, explicit: Option<&str>) -> Result<String> {
600 if is_global_config(path) {
601 if let Some(ns) = explicit
602 && ns != "global"
603 {
604 return Err(ConfigParseError::InvalidNamespace {
605 path: path.to_path_buf(),
606 namespace: ns.to_string(),
607 reason: "global config files must use namespace 'global'".to_string(),
608 }
609 .into());
610 }
611 return Ok("global".to_string());
612 }
613
614 if let Some(ns) = explicit {
615 return validate_namespace(path, ns);
616 }
617
618 derive_namespace_from_dir(path)
619}
620
621fn namespace_from_file(path: &Path) -> Result<String> {
622 let explicit = directory_namespace_override(path, None)?;
623 namespace_from_path_with_override(path, explicit.as_deref())
624}
625
626pub fn namespace_from_path(path: &Path) -> Result<String> {
639 namespace_from_file(path)
640}
641
642fn find_project_root(dir: &Path) -> Option<PathBuf> {
650 let canonical_dir = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
654 let mut current = canonical_dir.as_path();
655 loop {
656 if current.join(".git").exists() || current.join(".jj").exists() {
657 return Some(current.to_path_buf());
658 }
659 current = current.parent()?;
660 }
661}
662
663struct ConfigCacheEntry {
682 config: PitchforkToml,
683 source_meta: Vec<(PathBuf, Option<(SystemTime, u64)>)>,
685}
686
687static CONFIG_CACHE: Lazy<StdMutex<HashMap<PathBuf, ConfigCacheEntry>>> =
694 Lazy::new(|| StdMutex::new(HashMap::new()));
695
696fn meta_matches(paths: &[PathBuf], snapshot: &[(PathBuf, Option<(SystemTime, u64)>)]) -> bool {
702 if paths.len() != snapshot.len() {
703 return false;
704 }
705 paths
706 .iter()
707 .zip(snapshot.iter())
708 .all(|(p, (snap_p, snap_meta))| p == snap_p && current_meta(p) == *snap_meta)
709}
710
711pub(crate) fn current_meta(path: &Path) -> Option<(SystemTime, u64)> {
713 let md = std::fs::metadata(path).ok()?;
714 Some((md.modified().ok()?, md.len()))
715}
716
717fn snapshot_meta(paths: &[PathBuf]) -> Vec<(PathBuf, Option<(SystemTime, u64)>)> {
719 paths.iter().map(|p| (p.clone(), current_meta(p))).collect()
720}
721
722pub fn invalidate_config_cache() {
739 crate::extra_configs::invalidate();
740 crate::web::routes::api::projects::invalidate_group_cache();
743 if let Ok(mut cache) = CONFIG_CACHE.lock() {
744 cache.clear();
745 }
746}
747
748impl PitchforkToml {
749 pub fn resolve_daemon_id(&self, user_id: &str) -> Result<Vec<DaemonId>> {
762 if user_id.contains('/') {
764 return match DaemonId::parse(user_id) {
765 Ok(id) => Ok(vec![id]),
766 Err(e) => Err(e), };
768 }
769
770 let global_slugs = Self::read_global_slugs();
772 if let Some(entry) = global_slugs.get(user_id) {
773 let daemon_name = entry.daemon.as_deref().unwrap_or(user_id);
775 if let Some(dir) = entry.resolve_dir()
776 && let Ok(project_config) = Self::all_merged_from(&dir)
777 {
778 let matches: Vec<DaemonId> = project_config
780 .daemons
781 .keys()
782 .filter(|id| id.name() == daemon_name)
783 .cloned()
784 .collect();
785 match matches.as_slice() {
786 [] => {}
787 [id] => return Ok(vec![id.clone()]),
788 _ => {
789 let mut candidates: Vec<String> =
790 matches.iter().map(|id| id.qualified()).collect();
791 candidates.sort();
792 return Err(miette::miette!(
793 "slug '{}' maps to daemon '{}' which matches multiple daemons: {}",
794 user_id,
795 daemon_name,
796 candidates.join(", ")
797 ));
798 }
799 }
800 }
801 }
802
803 let matches: Vec<DaemonId> = self
805 .daemons
806 .keys()
807 .filter(|id| id.name() == user_id)
808 .cloned()
809 .collect();
810
811 if matches.is_empty() {
812 let state_matches = Self::find_in_state_file(user_id);
814 match state_matches.as_slice() {
815 [] => {}
816 [id] => return Ok(vec![id.clone()]),
817 _ => {
818 let mut candidates: Vec<String> =
819 state_matches.iter().map(|id| id.qualified()).collect();
820 candidates.sort();
821 return Err(miette::miette!(
822 "daemon '{}' is ambiguous; matches: {}. Use a qualified daemon ID (namespace/name)",
823 user_id,
824 candidates.join(", ")
825 ));
826 }
827 }
828 let _ = DaemonId::try_new("global", user_id)?;
830 }
831 Ok(matches)
832 }
833
834 fn find_in_state_file(short_name: &str) -> Vec<DaemonId> {
840 match StateFile::read(&*env::PITCHFORK_STATE_FILE) {
841 Ok(state) => state
842 .daemons
843 .keys()
844 .filter(|id| id.name() == short_name)
845 .cloned()
846 .collect(),
847 Err(e) => {
848 warn!("cannot read state file: {e}");
849 Vec::new()
850 }
851 }
852 }
853
854 #[allow(dead_code)]
875 pub fn resolve_daemon_id_prefer_local(
876 &self,
877 user_id: &str,
878 current_dir: &Path,
879 ) -> Result<DaemonId> {
880 if user_id.contains('/') {
882 return DaemonId::parse(user_id);
883 }
884
885 let current_namespace = Self::namespace_for_dir(current_dir)?;
889
890 self.resolve_daemon_id_with_namespace(user_id, ¤t_namespace)
891 }
892
893 fn resolve_daemon_id_with_namespace(
896 &self,
897 user_id: &str,
898 current_namespace: &str,
899 ) -> Result<DaemonId> {
900 if let Ok(preferred_id) = DaemonId::try_new(current_namespace, user_id)
905 && self.daemons.contains_key(&preferred_id)
906 {
907 return Ok(preferred_id);
908 }
909
910 let global_slugs = Self::read_global_slugs();
912 if let Some(entry) = global_slugs.get(user_id) {
913 let daemon_name = entry.daemon.as_deref().unwrap_or(user_id);
914 if let Some(dir) = entry.resolve_dir()
915 && let Ok(project_config) = Self::all_merged_from(&dir)
916 {
917 let matches: Vec<DaemonId> = project_config
918 .daemons
919 .keys()
920 .filter(|id| id.name() == daemon_name)
921 .cloned()
922 .collect();
923 match matches.as_slice() {
924 [] => {}
925 [id] => return Ok(id.clone()),
926 _ => {
927 let mut candidates: Vec<String> =
928 matches.iter().map(|id| id.qualified()).collect();
929 candidates.sort();
930 return Err(miette::miette!(
931 "slug '{}' maps to daemon '{}' which matches multiple daemons: {}",
932 user_id,
933 daemon_name,
934 candidates.join(", ")
935 ));
936 }
937 }
938 }
939 }
940
941 DaemonId::try_new(current_namespace, user_id)?;
943
944 let matches = self.resolve_daemon_id(user_id)?;
946
947 if matches.len() > 1 {
949 let mut candidates: Vec<String> = matches.iter().map(|id| id.qualified()).collect();
950 candidates.sort();
951 return Err(miette::miette!(
952 "daemon '{}' is ambiguous; matches: {}. Use a qualified daemon ID (namespace/name)",
953 user_id,
954 candidates.join(", ")
955 ));
956 }
957
958 if let Some(id) = matches.into_iter().next() {
959 return Ok(id);
960 }
961
962 let global_id = DaemonId::try_new("global", user_id)?;
965 if self.daemons.contains_key(&global_id) {
966 return Ok(global_id);
967 }
968
969 let suggestion = find_similar_daemon(user_id, self.daemons.keys().map(|id| id.name()));
970 Err(DependencyError::DaemonNotFound {
971 name: user_id.to_string(),
972 suggestion,
973 }
974 .into())
975 }
976
977 pub fn namespace_for_project_dir(dir: &Path) -> Result<String> {
979 namespace_from_path(&dir.join("pitchfork.toml"))
980 }
981
982 pub fn project_worktree_label(dir: &Path) -> Option<String> {
990 let mut label = None;
991 let candidates = project_config_family(&dir.join("pitchfork.toml"))
992 .into_iter()
993 .chain(crate::extra_configs::configs_for_dir(dir));
994 for candidate in candidates {
995 if !candidate.exists() {
996 continue;
997 }
998 if let Ok(pt) = Self::read(&candidate)
999 && let Some(found) = pt.worktree_label
1000 {
1001 label = Some(found);
1002 }
1003 }
1004 label
1005 }
1006
1007 pub fn project_namespace_override(dir: &Path) -> Result<Option<String>> {
1009 directory_namespace_override(&dir.join("pitchfork.toml"), None)
1010 }
1011
1012 pub fn namespace_for_dir(dir: &Path) -> Result<String> {
1014 Ok(Self::list_paths_from(dir)
1015 .iter()
1016 .filter(|p| p.exists())
1017 .max_by_key(|p| {
1018 if is_global_config(p) {
1019 0
1020 } else {
1021 project_dir_for_config(p).map_or(0, |dir| dir.components().count())
1022 }
1023 })
1024 .map(|p| namespace_from_path(p))
1025 .transpose()?
1026 .unwrap_or_else(|| "global".to_string()))
1027 }
1028
1029 pub fn resolve_id(user_id: &str) -> Result<DaemonId> {
1039 if user_id.contains('/') {
1040 return DaemonId::parse(user_id);
1041 }
1042
1043 let config = Self::all_merged()?;
1046 let ns = Self::namespace_for_dir(&env::CWD)?;
1047 config.resolve_daemon_id_with_namespace(user_id, &ns)
1048 }
1049
1050 pub fn resolve_id_allow_adhoc(user_id: &str) -> Result<DaemonId> {
1056 Self::resolve_id_allow_adhoc_from(user_id, &env::CWD)
1057 }
1058
1059 fn resolve_id_allow_adhoc_from(user_id: &str, dir: &Path) -> Result<DaemonId> {
1060 if user_id.contains('/') {
1061 return DaemonId::parse(user_id);
1062 }
1063
1064 let ns = Self::namespace_for_dir(dir)?;
1065 DaemonId::try_new(ns, user_id)
1066 }
1067
1068 pub fn resolve_ids<S: AsRef<str>>(user_ids: &[S]) -> Result<Vec<DaemonId>> {
1079 if user_ids.iter().all(|s| s.as_ref().contains('/')) {
1081 return user_ids
1082 .iter()
1083 .map(|s| DaemonId::parse(s.as_ref()))
1084 .collect();
1085 }
1086
1087 let config = Self::all_merged()?;
1088 let ns = Self::namespace_for_dir(&env::CWD)?;
1090 user_ids
1091 .iter()
1092 .map(|s| {
1093 let id = s.as_ref();
1094 if id.contains('/') {
1095 DaemonId::parse(id)
1096 } else {
1097 config.resolve_daemon_id_with_namespace(id, &ns)
1098 }
1099 })
1100 .collect()
1101 }
1102
1103 pub fn resolve_ids_and_group<S: AsRef<str>>(
1108 user_ids: &[S],
1109 group_name: Option<&str>,
1110 ) -> Result<Vec<DaemonId>> {
1111 let config = Self::all_merged()?;
1112 let ns = Self::namespace_for_dir(&env::CWD)?;
1113 let mut ids = Vec::new();
1114 let mut seen = std::collections::HashSet::new();
1115
1116 for id in user_ids {
1117 let id_str = id.as_ref();
1118 let daemon_id = if id_str.contains('/') {
1119 DaemonId::parse(id_str)?
1120 } else {
1121 config.resolve_daemon_id_with_namespace(id_str, &ns)?
1122 };
1123 if seen.insert(daemon_id.clone()) {
1124 ids.push(daemon_id);
1125 }
1126 }
1127
1128 if let Some(name) = group_name {
1129 let members = expand_group(&config.groups, name)?;
1130 let missing: Vec<String> = members
1131 .iter()
1132 .filter(|id| !config.daemons.contains_key(*id))
1133 .map(|id| id.qualified())
1134 .collect();
1135 if !missing.is_empty() {
1136 return Err(miette::miette!(
1137 "group '{}' references undefined daemon{}: {}",
1138 name,
1139 if missing.len() > 1 { "s" } else { "" },
1140 missing.join(", ")
1141 ));
1142 }
1143 for daemon_id in members {
1144 if seen.insert(daemon_id.clone()) {
1145 ids.push(daemon_id);
1146 }
1147 }
1148 }
1149
1150 Ok(ids)
1151 }
1152
1153 pub fn list_paths() -> Vec<PathBuf> {
1156 Self::list_paths_from(&env::CWD)
1157 }
1158
1159 pub fn list_paths_from(cwd: &Path) -> Vec<PathBuf> {
1170 let mut paths = Vec::new();
1171 paths.push(env::PITCHFORK_GLOBAL_CONFIG_SYSTEM.clone());
1172 paths.push(env::PITCHFORK_GLOBAL_CONFIG_USER.clone());
1173
1174 let mut project_paths = xx::file::find_up_all(
1178 cwd,
1179 &[
1180 "pitchfork.local.toml",
1181 "pitchfork.toml",
1182 ".config/pitchfork.local.toml",
1183 ".config/pitchfork.toml",
1184 ],
1185 );
1186 project_paths.reverse();
1187 paths.extend(project_paths);
1188 paths.extend(crate::extra_configs::paths_for(cwd));
1189
1190 paths
1191 }
1192
1193 pub fn all_merged() -> Result<PitchforkToml> {
1196 Self::all_merged_from(&env::CWD)
1197 }
1198 pub async fn all_merged_all_namespaces() -> Result<Self> {
1210 Self::all_merged_all_namespaces_from(&env::CWD).await
1211 }
1212
1213 pub(crate) async fn all_merged_all_namespaces_from(start_dir: &Path) -> Result<Self> {
1215 let start_dir = start_dir.to_path_buf();
1216 match tokio::task::spawn_blocking(move || {
1217 Self::all_merged_all_namespaces_from_blocking(&start_dir)
1218 })
1219 .await
1220 {
1221 Ok(result) => result,
1222 Err(e) => Err(miette::miette!("reading the merged config panicked: {e}")),
1223 }
1224 }
1225
1226 pub fn all_merged_all_namespaces_blocking() -> Result<Self> {
1229 Self::all_merged_all_namespaces_from_blocking(&env::CWD)
1230 }
1231
1232 pub(crate) fn all_merged_all_namespaces_from_blocking(start_dir: &Path) -> Result<Self> {
1235 let mut pt = Self::all_merged_from(start_dir)?;
1236
1237 let namespaces = Self::read_global_namespaces();
1238 for (ns_name, entry) in namespaces {
1239 match Self::all_merged_from(&entry.dir) {
1240 Ok(ns_config) => {
1241 for (daemon_id, daemon_config) in ns_config.daemons {
1242 if !pt.daemons.contains_key(&daemon_id) {
1243 pt.foreign_env
1244 .insert(daemon_id.clone(), ns_config.env.clone());
1245 pt.daemons.insert(daemon_id, daemon_config);
1246 }
1247 }
1248 pt.settings.merge_from(&ns_config.settings);
1251 }
1252 Err(e) => {
1253 log::warn!(
1254 "Failed to load namespace '{ns_name}' from {}: {e}",
1255 entry.dir.display()
1256 );
1257 }
1258 }
1259 }
1260
1261 if crate::settings::settings().general.worktree
1271 && let Some(project_root) = find_project_root(start_dir)
1272 {
1273 let worktrees = crate::proxy::worktree::discover_worktrees(&project_root);
1274 for wt in &worktrees {
1275 match Self::all_merged_from(&wt.path) {
1276 Ok(wt_config) => {
1277 for (daemon_id, daemon_config) in wt_config.daemons {
1278 if !pt.daemons.contains_key(&daemon_id) {
1279 pt.daemons.insert(daemon_id, daemon_config);
1280 }
1281 }
1282 pt.settings.merge_from(&wt_config.settings);
1283 }
1284 Err(e) => {
1285 log::warn!(
1286 "Failed to load worktree '{}' config from {}: {e}",
1287 wt.branch,
1288 wt.path.display()
1289 );
1290 }
1291 }
1292 }
1293 }
1294
1295 Ok(pt)
1296 }
1297
1298 pub fn all_merged_from(cwd: &Path) -> Result<PitchforkToml> {
1316 let paths = Self::list_paths_from(cwd);
1317
1318 let cache_key = cwd.canonicalize().unwrap_or_else(|_| cwd.to_path_buf());
1322
1323 {
1324 let cache = CONFIG_CACHE.lock().unwrap_or_else(|e| e.into_inner());
1325 if let Some(entry) = cache.get(&cache_key)
1326 && meta_matches(&paths, &entry.source_meta)
1327 {
1328 return Ok(entry.config.clone());
1329 }
1330 }
1331
1332 let snapshot = snapshot_meta(&paths);
1338 let pt = Self::all_merged_from_uncached(&paths)?;
1339
1340 let mut cache = CONFIG_CACHE.lock().unwrap_or_else(|e| e.into_inner());
1342 cache.insert(
1343 cache_key,
1344 ConfigCacheEntry {
1345 config: pt.clone(),
1346 source_meta: snapshot,
1347 },
1348 );
1349
1350 Ok(pt)
1351 }
1352
1353 fn all_merged_from_uncached(paths: &[PathBuf]) -> Result<PitchforkToml> {
1358 use std::collections::HashMap as StdHashMap;
1359
1360 let mut ns_to_origin: StdHashMap<String, (PathBuf, PathBuf)> = StdHashMap::new();
1361
1362 let mut pt = Self::default();
1363 for p in paths {
1364 match Self::read(p) {
1365 Ok(pt2) => {
1366 if p.exists() && !is_global_config(p) {
1370 let ns = namespace_from_path(p)?;
1371 let origin_dir = project_dir_for_config(p)
1372 .map(|dir| dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf()))
1373 .unwrap_or_else(|| p.clone());
1374
1375 if let Some((other_path, other_dir)) = ns_to_origin.get(ns.as_str())
1376 && *other_dir != origin_dir
1377 {
1378 return Err(crate::error::ConfigParseError::NamespaceCollision {
1379 path_a: other_path.clone(),
1380 path_b: p.clone(),
1381 ns,
1382 }
1383 .into());
1384 }
1385 ns_to_origin.insert(ns, (p.clone(), origin_dir));
1386 }
1387
1388 pt.merge(pt2)
1389 }
1390 Err(e) => return Err(e.wrap_err(format!("error reading {}", p.display()))),
1391 }
1392 }
1393 Ok(pt)
1394 }
1395}
1396
1397impl PitchforkToml {
1398 pub fn new(path: PathBuf) -> Self {
1399 Self {
1400 daemons: Default::default(),
1401 env: None,
1402 namespace: None,
1403 worktree_label: None,
1404 settings: SettingsPartial::default(),
1405 slugs: IndexMap::new(),
1406 groups: IndexMap::new(),
1407 namespaces: IndexMap::new(),
1408 themes: IndexMap::new(),
1409 path: Some(path),
1410 foreign_env: IndexMap::new(),
1411 }
1412 }
1413
1414 pub fn parse_str(content: &str, path: &Path) -> Result<Self> {
1422 let mut raw_config: PitchforkTomlRaw = toml::from_str(content)
1423 .map_err(|e| ConfigParseError::from_toml_error(path, content.to_string(), e))?;
1424 if let Some(settings) = &mut raw_config.settings {
1425 settings.canonicalize_aliases();
1426 }
1427
1428 let explicit = directory_namespace_override(path, Some(content))?;
1429 let namespace = namespace_from_path_with_override(path, explicit.as_deref())?;
1430 let mut pt = Self::new(path.to_path_buf());
1431 pt.namespace = raw_config.namespace.clone();
1432 pt.worktree_label = raw_config.worktree_label.clone();
1433
1434 for (short_name, raw_daemon) in raw_config.daemons {
1435 let id = match DaemonId::try_new(&namespace, &short_name) {
1436 Ok(id) => id,
1437 Err(e) => {
1438 return Err(ConfigParseError::InvalidDaemonName {
1439 name: short_name,
1440 path: path.to_path_buf(),
1441 reason: e.to_string(),
1442 }
1443 .into());
1444 }
1445 };
1446
1447 let mut depends = Vec::new();
1448 for dep in raw_daemon.depends {
1449 let dep_id = if dep.contains('/') {
1450 match DaemonId::parse(&dep) {
1451 Ok(id) => id,
1452 Err(e) => {
1453 return Err(ConfigParseError::InvalidDependency {
1454 daemon: short_name.clone(),
1455 dependency: dep,
1456 path: path.to_path_buf(),
1457 reason: e.to_string(),
1458 }
1459 .into());
1460 }
1461 }
1462 } else {
1463 match DaemonId::try_new(&namespace, &dep) {
1464 Ok(id) => id,
1465 Err(e) => {
1466 return Err(ConfigParseError::InvalidDependency {
1467 daemon: short_name.clone(),
1468 dependency: dep,
1469 path: path.to_path_buf(),
1470 reason: e.to_string(),
1471 }
1472 .into());
1473 }
1474 }
1475 };
1476 depends.push(dep_id);
1477 }
1478
1479 let has_deprecated = !raw_daemon.expected_port.is_empty()
1481 || raw_daemon.auto_bump_port.is_some()
1482 || raw_daemon.port_bump_attempts.is_some();
1483 let deprecated_port = has_deprecated.then(|| {
1484 let bump = if raw_daemon.auto_bump_port.unwrap_or(false) {
1485 PortBump(
1486 raw_daemon
1487 .port_bump_attempts
1488 .unwrap_or_else(|| settings().default_port_bump_attempts()),
1489 )
1490 } else {
1491 PortBump(0)
1492 };
1493 PortConfig {
1494 expect: raw_daemon.expected_port,
1495 bump,
1496 }
1497 });
1498 let port = match (raw_daemon.port, deprecated_port) {
1499 (Some(port), Some(deprecated)) => {
1500 if deprecated != port {
1503 warn!(
1504 "daemon {short_name}: both `port` and deprecated expected_port/auto_bump_port/port_bump_attempts are set; ignoring deprecated fields"
1505 );
1506 }
1507 Some(port)
1508 }
1509 (Some(port), None) => Some(port),
1510 (None, Some(deprecated)) => {
1511 deprecated_at!(
1512 "2026-10-03",
1513 "2027-10-03",
1514 format!("port-fields:{id}"),
1515 "daemon {short_name}: expected_port/auto_bump_port/port_bump_attempts are deprecated, use [daemons.{short_name}.port] instead."
1516 );
1517 Some(deprecated)
1518 }
1519 (None, None) => None,
1520 };
1521
1522 if let (Some(explicit), Some(short)) =
1524 (raw_daemon.proxy_tls_port, raw_daemon.proxy_port)
1525 && explicit != short
1526 {
1527 warn!(
1528 "daemon {short_name}: proxy_tls_port ({explicit}) and proxy_port ({short}) \
1529 disagree; using proxy_tls_port"
1530 );
1531 }
1532 let proxy_tls_port = raw_daemon.proxy_tls_port.or(raw_daemon.proxy_port);
1533
1534 for (key, value) in [
1537 ("proxy_tls_port", raw_daemon.proxy_tls_port),
1538 ("proxy_port", raw_daemon.proxy_port),
1539 ] {
1540 if value == Some(0) {
1541 return Err(ConfigParseError::ProxyPortZero {
1542 daemon: short_name.clone(),
1543 key,
1544 path: path.to_path_buf(),
1545 }
1546 .into());
1547 }
1548 }
1549
1550 if let Some(port_want) = proxy_tls_port {
1553 let declared = port.as_ref().map(|p| p.expect.clone()).unwrap_or_default();
1554 if !declared.contains(&port_want) {
1555 return Err(ConfigParseError::ProxyPortNotDeclared {
1556 daemon: short_name.clone(),
1557 port: port_want,
1558 declared,
1559 path: path.to_path_buf(),
1560 }
1561 .into());
1562 }
1563 }
1564
1565 if raw_daemon
1568 .proxy_tls
1569 .is_some_and(ProxyTlsMode::is_passthrough)
1570 && port
1571 .as_ref()
1572 .is_none_or(|p| p.expect.iter().all(|&port| port == 0))
1573 {
1574 return Err(ConfigParseError::PassthroughWithoutPort {
1575 daemon: short_name.clone(),
1576 path: path.to_path_buf(),
1577 }
1578 .into());
1579 }
1580
1581 if let RunCommand::Argv(argv) = &raw_daemon.run {
1582 match argv.first().map(String::as_str) {
1583 None => {
1584 return Err(ConfigParseError::EmptyRunArgv {
1585 daemon: short_name.clone(),
1586 path: path.to_path_buf(),
1587 }
1588 .into());
1589 }
1590 Some("exec") => {
1593 return Err(ConfigParseError::ExecInRunArgv {
1594 daemon: short_name.clone(),
1595 path: path.to_path_buf(),
1596 }
1597 .into());
1598 }
1599 Some(_) => {}
1600 }
1601 }
1602
1603 if let Some(RunCommand::Argv(argv)) = raw_daemon.ready_cmd.as_ref().map(|c| &c.run) {
1604 match argv.first().map(String::as_str) {
1605 None | Some("") => {
1608 return Err(ConfigParseError::EmptyReadyCmdArgv {
1609 daemon: short_name.clone(),
1610 path: path.to_path_buf(),
1611 }
1612 .into());
1613 }
1614 Some("exec") => {
1615 return Err(ConfigParseError::ExecInReadyCmdArgv {
1616 daemon: short_name.clone(),
1617 path: path.to_path_buf(),
1618 }
1619 .into());
1620 }
1621 Some(_) => {}
1622 }
1623 }
1624
1625 if let Some(RunCommand::Argv(argv)) = raw_daemon.health_cmd.as_ref().map(|c| &c.run) {
1626 match argv.first().map(String::as_str) {
1627 None | Some("") => {
1630 return Err(ConfigParseError::EmptyHealthCmdArgv {
1631 daemon: short_name.clone(),
1632 path: path.to_path_buf(),
1633 }
1634 .into());
1635 }
1636 Some("exec") => {
1637 return Err(ConfigParseError::ExecInHealthCmdArgv {
1638 daemon: short_name.clone(),
1639 path: path.to_path_buf(),
1640 }
1641 .into());
1642 }
1643 Some(_) => {}
1644 }
1645 }
1646
1647 let daemon = PitchforkTomlDaemon {
1648 run: raw_daemon.run,
1649 auto: raw_daemon.auto,
1650 oneshot: raw_daemon.oneshot,
1651 cron: raw_daemon.cron,
1652 retry: raw_daemon.retry,
1653 ready_delay: raw_daemon.ready_delay,
1654 ready_output: raw_daemon.ready_output,
1655 ready_http: raw_daemon.ready_http,
1656 ready_port: raw_daemon.ready_port,
1657 ready_cmd: raw_daemon.ready_cmd,
1658 health_cmd: raw_daemon.health_cmd,
1659 health_http: raw_daemon.health_http,
1660 health_port: raw_daemon.health_port,
1661 port,
1662 proxy: raw_daemon.proxy,
1663 proxy_tls: raw_daemon.proxy_tls,
1664 proxy_protocol: raw_daemon.proxy_protocol,
1665 proxy_tls_port: raw_daemon.proxy_tls_port,
1666 proxy_port: raw_daemon.proxy_port,
1667 proxy_idle_timeout: raw_daemon.proxy_idle_timeout,
1668 boot_start: raw_daemon.boot_start,
1669 depends,
1670 watch: raw_daemon.watch,
1671 watch_mode: raw_daemon.watch_mode.unwrap_or_default(),
1672 dir: raw_daemon.dir,
1673 env: raw_daemon.env,
1674 env_file: raw_daemon.env_file,
1675 hooks: raw_daemon.hooks,
1676 mise: raw_daemon.mise,
1677 deferred_template_context: None,
1678 user: raw_daemon.user,
1679 memory_limit: raw_daemon.memory_limit,
1680 cpu_limit: raw_daemon.cpu_limit,
1681 stop_signal: raw_daemon.stop_signal,
1682 pty: raw_daemon.pty,
1683 time_retention: raw_daemon.time_retention,
1684 line_retention: raw_daemon.line_retention,
1685 archive_hook: raw_daemon.archive_hook,
1686 logs: raw_daemon.logs,
1687 path: Some(path.to_path_buf()),
1688 };
1689 if daemon.is_oneshot() {
1690 let conflicts = daemon.oneshot_conflicts();
1691 if !conflicts.is_empty() {
1692 return Err(ConfigParseError::OneshotConflict {
1693 daemon: short_name.clone(),
1694 path: path.to_path_buf(),
1695 conflicts: conflicts.into_iter().map(str::to_string).collect(),
1696 }
1697 .into());
1698 }
1699 }
1700 pt.daemons.insert(id, daemon);
1701 }
1702
1703 if let Some(settings) = raw_config.settings {
1705 pt.settings = settings;
1706 }
1707
1708 pt.env = raw_config.env;
1710
1711 for (slug, entry) in raw_config.slugs {
1713 pt.slugs.insert(
1714 slug,
1715 SlugEntry {
1716 dir: entry.dir.map(env::expand_tilde),
1717 namespace: entry.namespace,
1718 daemon: entry.daemon,
1719 },
1720 );
1721 }
1722
1723 for (name, entry) in raw_config.namespaces {
1725 pt.namespaces.insert(
1726 name,
1727 NamespaceEntry {
1728 config: entry
1729 .config
1730 .iter()
1731 .map(|p| {
1732 crate::extra_configs::resolve_path(&env::expand_tilde(&entry.dir), p)
1733 })
1734 .collect(),
1735 dir: env::expand_tilde(entry.dir),
1736 label: entry.label,
1737 },
1738 );
1739 }
1740
1741 for (group_name, raw_group) in raw_config.groups {
1743 let mut daemons = Vec::new();
1744 for daemon_name in &raw_group.daemons {
1745 let id = if daemon_name.contains('/') {
1746 DaemonId::parse(daemon_name).map_err(|e| {
1747 ConfigParseError::InvalidDependency {
1748 daemon: group_name.clone(),
1749 dependency: daemon_name.clone(),
1750 path: path.to_path_buf(),
1751 reason: e.to_string(),
1752 }
1753 })?
1754 } else {
1755 DaemonId::try_new(&namespace, daemon_name).map_err(|e| {
1756 ConfigParseError::InvalidDaemonName {
1757 name: daemon_name.clone(),
1758 path: path.to_path_buf(),
1759 reason: e.to_string(),
1760 }
1761 })?
1762 };
1763 daemons.push(id);
1764 }
1765 pt.groups.insert(
1766 group_name,
1767 GroupEntry {
1768 daemons,
1769 groups: raw_group.groups,
1770 },
1771 );
1772 }
1773
1774 pt.themes = raw_config.themes;
1775
1776 Ok(pt)
1777 }
1778
1779 pub fn read<P: AsRef<Path>>(path: P) -> Result<Self> {
1780 let path = path.as_ref();
1781 if !path.exists() {
1782 return Ok(Self::new(path.to_path_buf()));
1783 }
1784 let _lock = xx::fslock::get(path, false)
1785 .wrap_err_with(|| format!("failed to acquire lock on {}", path.display()))?;
1786 let raw = std::fs::read_to_string(path).map_err(|e| FileError::ReadError {
1787 path: path.to_path_buf(),
1788 source: e,
1789 })?;
1790 Self::parse_str(&raw, path)
1791 }
1792
1793 pub fn write(&self) -> Result<()> {
1794 if let Some(path) = &self.path {
1795 let _lock = xx::fslock::get(path, false)
1796 .wrap_err_with(|| format!("failed to acquire lock on {}", path.display()))?;
1797 self.write_unlocked()
1798 } else {
1799 Err(FileError::NoPath.into())
1800 }
1801 }
1802
1803 pub(crate) fn write_unlocked(&self) -> Result<()> {
1809 if let Some(path) = &self.path {
1810 let config_namespace = if path.exists() || self.namespace.is_none() {
1814 namespace_from_path(path)?
1815 } else {
1816 namespace_from_path_with_override(path, self.namespace.as_deref())?
1817 };
1818
1819 let mut raw = PitchforkTomlRaw {
1823 namespace: self.namespace.clone(),
1824 worktree_label: self.worktree_label.clone(),
1825 env: self.env.clone(),
1826 settings: (!self.settings.is_empty()).then(|| self.settings.clone()),
1827 themes: self.themes.clone(),
1828 ..PitchforkTomlRaw::default()
1829 };
1830 for (id, daemon) in &self.daemons {
1831 if id.namespace() != config_namespace {
1832 return Err(miette::miette!(
1833 "cannot write daemon '{}' to {}: daemon belongs to namespace '{}' but file namespace is '{}'",
1834 id,
1835 path.display(),
1836 id.namespace(),
1837 config_namespace
1838 ));
1839 }
1840 let port = daemon.port.as_ref();
1841 let raw_daemon = PitchforkTomlDaemonRaw {
1842 run: daemon.run.clone(),
1843 auto: daemon.auto.clone(),
1844 oneshot: daemon.oneshot,
1845 cron: daemon.cron.clone(),
1846 retry: daemon.retry,
1847 ready_delay: daemon.ready_delay,
1848 ready_output: daemon.ready_output.clone(),
1849 ready_http: daemon.ready_http.clone(),
1850 ready_port: daemon.ready_port.clone(),
1851 ready_cmd: daemon.ready_cmd.clone(),
1852 health_cmd: daemon.health_cmd.clone(),
1853 health_http: daemon.health_http.clone(),
1854 health_port: daemon.health_port.clone(),
1855 port: port.cloned(),
1856 proxy: daemon.proxy.clone(),
1857 proxy_tls: daemon.proxy_tls,
1858 proxy_protocol: daemon.proxy_protocol,
1859 proxy_tls_port: daemon.proxy_tls_port,
1860 proxy_port: daemon.proxy_port,
1861 proxy_idle_timeout: daemon.proxy_idle_timeout,
1862 expected_port: port.map(|p| p.expect.clone()).unwrap_or_default(),
1864 auto_bump_port: port.filter(|p| p.auto_bump()).map(|_| true),
1865 port_bump_attempts: port
1866 .filter(|p| p.auto_bump())
1867 .map(|p| p.max_bump_attempts()),
1868 boot_start: daemon.boot_start,
1869 depends: daemon
1872 .depends
1873 .iter()
1874 .map(|d| {
1875 if d.namespace() == config_namespace {
1876 d.name().to_string()
1877 } else {
1878 d.qualified()
1879 }
1880 })
1881 .collect(),
1882 watch: daemon.watch.clone(),
1883 watch_mode: match daemon.watch_mode {
1884 WatchMode::Native => None,
1885 mode => Some(mode),
1886 },
1887 dir: daemon.dir.clone(),
1888 env: daemon.env.clone(),
1889 env_file: daemon.env_file.clone(),
1890 hooks: daemon.hooks.clone(),
1891 mise: daemon.mise,
1892 user: daemon.user.clone(),
1893 memory_limit: daemon.memory_limit,
1894 cpu_limit: daemon.cpu_limit,
1895 stop_signal: daemon.stop_signal,
1896 pty: daemon.pty,
1897 time_retention: daemon.time_retention.clone(),
1898 line_retention: daemon.line_retention,
1899 archive_hook: daemon.archive_hook.clone(),
1900 logs: daemon.logs.clone(),
1901 };
1902 raw.daemons.insert(id.name().to_string(), raw_daemon);
1903 }
1904
1905 for (slug, entry) in &self.slugs {
1907 raw.slugs.insert(
1908 slug.clone(),
1909 SlugEntryRaw {
1910 dir: entry.dir.as_ref().map(|d| d.to_string_lossy().to_string()),
1911 namespace: entry.namespace.clone(),
1912 daemon: entry.daemon.clone(),
1913 },
1914 );
1915 }
1916
1917 for (name, group) in &self.groups {
1919 let raw_daemons: Vec<String> = group
1920 .daemons
1921 .iter()
1922 .map(|id| {
1923 if id.namespace() == config_namespace {
1924 id.name().to_string()
1925 } else {
1926 id.qualified()
1927 }
1928 })
1929 .collect();
1930 raw.groups.insert(
1931 name.clone(),
1932 GroupEntryRaw {
1933 daemons: raw_daemons,
1934 groups: group.groups.clone(),
1935 },
1936 );
1937 }
1938
1939 for (name, entry) in &self.namespaces {
1941 raw.namespaces.insert(
1942 name.clone(),
1943 NamespaceEntryRaw {
1944 dir: entry.dir.to_string_lossy().to_string(),
1945 config: entry
1946 .config
1947 .iter()
1948 .map(|p| p.to_string_lossy().into_owned())
1949 .collect(),
1950 label: entry.label.clone(),
1951 },
1952 );
1953 }
1954
1955 let raw_str = toml::to_string(&raw).map_err(|e| FileError::SerializeError {
1956 path: path.clone(),
1957 source: e,
1958 })?;
1959 xx::file::write(path, &raw_str).map_err(|e| FileError::WriteError {
1960 path: path.clone(),
1961 details: Some(e.to_string()),
1962 })?;
1963 invalidate_config_cache();
1964 Ok(())
1965 } else {
1966 Err(FileError::NoPath.into())
1967 }
1968 }
1969
1970 pub fn merge(&mut self, pt: Self) {
1975 if pt.worktree_label.is_some() {
1976 self.worktree_label = pt.worktree_label.clone();
1977 }
1978 for (id, d) in pt.daemons {
1979 self.daemons.insert(id, d);
1980 }
1981 if let Some(env) = pt.env {
1983 let merged = self.env.get_or_insert_with(IndexMap::new);
1984 for (k, v) in env {
1985 merged.insert(k, v);
1986 }
1987 }
1988 for (slug, entry) in pt.slugs {
1990 self.slugs.insert(slug, entry);
1991 }
1992 for (name, group) in pt.groups {
1994 self.groups.insert(name, group);
1995 }
1996 for (name, entry) in pt.namespaces {
1998 self.namespaces.insert(name, entry);
1999 }
2000 for (name, theme) in pt.themes {
2002 self.themes.insert(name, theme);
2003 }
2004 self.settings.merge_from(&pt.settings);
2006 }
2007
2008 pub fn read_global_slugs() -> IndexMap<String, SlugEntry> {
2013 match Self::read(&*env::PITCHFORK_GLOBAL_CONFIG_USER) {
2014 Ok(pt) => pt.slugs,
2015 Err(_) => IndexMap::new(),
2016 }
2017 }
2018
2019 pub fn slug_is_ambiguous(slug: &str, global_slugs: &IndexMap<String, SlugEntry>) -> bool {
2026 global_slugs
2027 .keys()
2028 .filter(|k| k.eq_ignore_ascii_case(slug))
2029 .count()
2030 > 1
2031 }
2032
2033 pub fn find_slug_for_daemon_in_registry(
2038 daemon_id: &DaemonId,
2039 global_slugs: &IndexMap<String, SlugEntry>,
2040 ) -> Option<String> {
2041 global_slugs
2042 .iter()
2043 .find(|(slug, entry)| {
2044 let daemon_name = entry.daemon.as_deref().unwrap_or(slug);
2045 if daemon_id.name() != daemon_name {
2046 return false;
2047 }
2048
2049 if Self::slug_is_ambiguous(slug, global_slugs) {
2052 return false;
2053 }
2054
2055 match entry.resolve_namespace() {
2056 Some(namespace) => daemon_id.namespace() == namespace,
2057 None => false,
2058 }
2059 })
2060 .map(|(slug, _)| slug.clone())
2061 }
2062
2063 #[allow(dead_code)]
2065 pub fn is_slug_registered(slug: &str) -> bool {
2066 Self::read_global_slugs().contains_key(slug)
2067 }
2068
2069 pub fn add_slug_with_namespace(
2075 slug: &str,
2076 namespace: Option<&str>,
2077 daemon: Option<&str>,
2078 ) -> Result<()> {
2079 let global_path = &*env::PITCHFORK_GLOBAL_CONFIG_USER;
2080
2081 if let Some(parent) = global_path.parent() {
2083 std::fs::create_dir_all(parent).map_err(|e| {
2084 miette::miette!(
2085 "Failed to create config directory {}: {e}",
2086 parent.display()
2087 )
2088 })?;
2089 }
2090
2091 let _lock = xx::fslock::get(global_path, false)
2092 .wrap_err_with(|| format!("failed to acquire lock on {}", global_path.display()))?;
2093
2094 let mut pt = if global_path.exists() {
2095 let raw = std::fs::read_to_string(global_path).map_err(|e| FileError::ReadError {
2096 path: global_path.to_path_buf(),
2097 source: e,
2098 })?;
2099 Self::parse_str(&raw, global_path)?
2100 } else {
2101 Self::new(global_path.to_path_buf())
2102 };
2103
2104 if let Some(ns) = namespace
2108 && !pt.namespaces.contains_key(ns)
2109 {
2110 let dir = pt
2115 .slugs
2116 .get(slug)
2117 .and_then(|e| {
2118 e.dir.clone().or_else(|| {
2119 e.namespace
2120 .as_ref()
2121 .and_then(|ns| pt.namespaces.get(ns).map(|entry| entry.dir.clone()))
2122 })
2123 })
2124 .or_else(|| env::CWD.as_path().canonicalize().ok());
2125 if let Some(ref d) = dir {
2126 pt.namespaces.insert(
2127 ns.to_string(),
2128 NamespaceEntry {
2129 dir: d.clone(),
2130 config: Vec::new(),
2131 label: None,
2132 },
2133 );
2134 }
2135 }
2136
2137 pt.slugs.insert(
2138 slug.to_string(),
2139 SlugEntry {
2140 dir: None,
2141 namespace: namespace.map(str::to_string),
2142 daemon: daemon.map(str::to_string),
2143 },
2144 );
2145 pt.write_unlocked()?;
2146 let slug_names: Vec<String> = pt.slugs.keys().cloned().collect();
2152 crate::proxy::hosts::sync_hosts_from_settings_with_slugs(&slug_names);
2153 Ok(())
2154 }
2155
2156 pub fn remove_slug(slug: &str) -> Result<bool> {
2158 let global_path = &*env::PITCHFORK_GLOBAL_CONFIG_USER;
2159 if !global_path.exists() {
2160 return Ok(false);
2161 }
2162
2163 let _lock = xx::fslock::get(global_path, false)
2164 .wrap_err_with(|| format!("failed to acquire lock on {}", global_path.display()))?;
2165
2166 let raw = std::fs::read_to_string(global_path).map_err(|e| FileError::ReadError {
2167 path: global_path.to_path_buf(),
2168 source: e,
2169 })?;
2170 let mut pt = Self::parse_str(&raw, global_path)?;
2171
2172 let removed = pt.slugs.shift_remove(slug).is_some();
2173 if removed {
2174 pt.write_unlocked()?;
2175 let slug_names: Vec<String> = pt.slugs.keys().cloned().collect();
2181 crate::proxy::hosts::sync_hosts_from_settings_with_slugs(&slug_names);
2182 }
2183 Ok(removed)
2184 }
2185 pub fn read_global_namespaces() -> IndexMap<String, NamespaceEntry> {
2188 match Self::read(&*env::PITCHFORK_GLOBAL_CONFIG_USER) {
2189 Ok(pt) => pt.namespaces,
2190 Err(_) => IndexMap::new(),
2191 }
2192 }
2193
2194 pub fn register_namespace(name: &str, dir: &str) -> crate::Result<()> {
2198 let global_path = &*crate::env::PITCHFORK_GLOBAL_CONFIG_USER;
2199
2200 if let Some(parent) = global_path.parent() {
2202 std::fs::create_dir_all(parent).map_err(|e| {
2203 miette::miette!(
2204 "Failed to create config directory {}: {e}",
2205 parent.display()
2206 )
2207 })?;
2208 }
2209
2210 let _lock = xx::fslock::get(global_path, false)
2211 .wrap_err_with(|| format!("failed to acquire lock on {}", global_path.display()))?;
2212
2213 let mut pt = if global_path.exists() {
2214 let raw = std::fs::read_to_string(global_path).map_err(|e| {
2215 crate::error::FileError::ReadError {
2216 path: global_path.to_path_buf(),
2217 source: e,
2218 }
2219 })?;
2220 Self::parse_str(&raw, global_path)?
2221 } else {
2222 Self::new(global_path.to_path_buf())
2223 };
2224
2225 let dir = env::expand_tilde(dir);
2226 if let Some(entry) = pt.namespaces.get_mut(name) {
2227 if crate::extra_configs::path_is_gone(&entry.dir)
2228 && crate::extra_configs::normalize(&entry.dir)
2229 != crate::extra_configs::normalize(&dir)
2230 {
2231 if crate::extra_configs::namespace_has_running_daemon(name) {
2232 miette::bail!(
2235 "namespace '{name}' has running daemons from {}, which no longer exists; stop them first",
2236 entry.dir.display()
2237 );
2238 }
2239 entry.config.clear();
2241 entry.label = None;
2242 }
2243 if !entry.config.is_empty()
2244 && crate::extra_configs::normalize(&entry.dir)
2245 != crate::extra_configs::normalize(&dir)
2246 {
2247 miette::bail!(
2248 "namespace '{name}' has external configuration attached to another directory"
2249 );
2250 }
2251 entry.dir = dir;
2252 } else {
2253 pt.namespaces.insert(
2254 name.to_string(),
2255 NamespaceEntry {
2256 dir,
2257 config: Vec::new(),
2258 label: None,
2259 },
2260 );
2261 }
2262 pt.write_unlocked()?;
2263 Ok(())
2264 }
2265
2266 pub fn remove_namespace(name: &str) -> crate::Result<bool> {
2268 let global_path = &*crate::env::PITCHFORK_GLOBAL_CONFIG_USER;
2269 if !global_path.exists() {
2270 return Ok(false);
2271 }
2272
2273 let _lock = xx::fslock::get(global_path, false)
2274 .wrap_err_with(|| format!("failed to acquire lock on {}", global_path.display()))?;
2275
2276 let raw = std::fs::read_to_string(global_path).map_err(|e| {
2277 crate::error::FileError::ReadError {
2278 path: global_path.to_path_buf(),
2279 source: e,
2280 }
2281 })?;
2282 let mut pt = Self::parse_str(&raw, global_path)?;
2283
2284 let removed = pt.namespaces.shift_remove(name).is_some();
2285 if removed {
2286 pt.write_unlocked()?;
2287 }
2288 Ok(removed)
2289 }
2290}
2291
2292#[derive(Debug, Default, Clone, PartialEq, Eq)]
2294pub struct PruneReport {
2295 pub namespaces: Vec<String>,
2297 pub slugs: Vec<String>,
2299 pub config_files: usize,
2301}
2302
2303impl PruneReport {
2304 pub fn is_empty(&self) -> bool {
2305 self.namespaces.is_empty() && self.slugs.is_empty() && self.config_files == 0
2306 }
2307}
2308
2309impl PitchforkToml {
2310 pub fn prune_stale_registrations(
2324 keep: &std::collections::HashSet<String>,
2325 only: &[String],
2326 ) -> Result<PruneReport> {
2327 let global_path = &*env::PITCHFORK_GLOBAL_CONFIG_USER;
2328 let mut report = PruneReport::default();
2329 if !global_path.exists() {
2330 return Ok(report);
2331 }
2332 let _lock = xx::fslock::get(global_path, false)
2333 .wrap_err_with(|| format!("failed to acquire lock on {}", global_path.display()))?;
2334 let raw = std::fs::read_to_string(global_path).map_err(|e| FileError::ReadError {
2335 path: global_path.to_path_buf(),
2336 source: e,
2337 })?;
2338 let mut pt = Self::parse_str(&raw, global_path)?;
2339 let in_scope = |ns: &str| only.is_empty() || only.iter().any(|o| o == ns);
2340
2341 for (name, entry) in pt.namespaces.iter_mut() {
2342 if keep.contains(name) || !in_scope(name) {
2343 continue;
2344 }
2345 if crate::extra_configs::path_is_gone(&entry.dir) {
2346 report.namespaces.push(name.clone());
2347 continue;
2348 }
2349 let before = entry.config.len();
2350 entry
2351 .config
2352 .retain(|file| !crate::extra_configs::path_is_gone(file));
2353 let dropped = before - entry.config.len();
2354 if dropped > 0 {
2355 report.config_files += dropped;
2356 if entry.config.is_empty() {
2357 entry.label = None;
2359 }
2360 }
2361 }
2362 for name in &report.namespaces {
2363 pt.namespaces.shift_remove(name);
2364 }
2365
2366 if only.is_empty() || !report.namespaces.is_empty() {
2367 for (slug, entry) in &pt.slugs {
2368 if entry.namespace.as_ref().is_some_and(|ns| keep.contains(ns)) {
2371 continue;
2372 }
2373 let ns_pruned = entry
2374 .namespace
2375 .as_ref()
2376 .is_some_and(|ns| report.namespaces.contains(ns));
2377 let dir_gone = entry
2378 .dir
2379 .as_ref()
2380 .is_some_and(|d| crate::extra_configs::path_is_gone(d));
2381 let scoped_ok = only.is_empty() || ns_pruned;
2384 if scoped_ok && (ns_pruned || dir_gone) {
2385 report.slugs.push(slug.clone());
2386 }
2387 }
2388 for slug in &report.slugs {
2389 pt.slugs.shift_remove(slug);
2390 }
2391 }
2392
2393 if !report.is_empty() {
2394 pt.write_unlocked()?;
2395 if !report.slugs.is_empty() {
2396 let slug_names: Vec<String> = pt.slugs.keys().cloned().collect();
2397 crate::proxy::hosts::sync_hosts_from_settings_with_slugs(&slug_names);
2398 }
2399 }
2400 Ok(report)
2401 }
2402}
2403
2404#[derive(Debug, Clone, JsonSchema, Default)]
2406pub struct PitchforkTomlDaemon {
2407 #[schemars(example = example_run_command())]
2411 pub run: RunCommand,
2412 #[schemars(default)]
2414 pub auto: Vec<PitchforkTomlAuto>,
2415 pub oneshot: Option<bool>,
2421 pub cron: Option<PitchforkTomlCron>,
2423 #[schemars(default)]
2426 pub retry: Retry,
2427 pub ready_delay: Option<u64>,
2429 pub ready_output: Option<ReadyOutput>,
2431 pub ready_http: Option<ReadyHttp>,
2433 pub ready_port: Option<ReadyPort>,
2437 pub ready_cmd: Option<ReadyCmd>,
2439 pub health_cmd: Option<HealthCmd>,
2441 pub health_http: Option<HealthHttp>,
2443 pub health_port: Option<HealthPort>,
2447 pub port: Option<PortConfig>,
2449 #[serde(skip_serializing_if = "Option::is_none", default)]
2452 pub proxy: Option<ProxyConfig>,
2453 pub proxy_tls: Option<ProxyTlsMode>,
2462 pub proxy_protocol: Option<ProxyProtocol>,
2470 #[schemars(range(min = 1))]
2475 pub proxy_tls_port: Option<u16>,
2476 #[schemars(range(min = 1))]
2482 pub proxy_port: Option<u16>,
2483 pub proxy_idle_timeout: Option<ProxyIdleTimeout>,
2494 pub boot_start: Option<bool>,
2496 #[schemars(default)]
2498 pub depends: Vec<DaemonId>,
2499 #[schemars(default)]
2501 pub watch: Vec<String>,
2502 #[schemars(default)]
2508 pub watch_mode: WatchMode,
2509 pub dir: Option<String>,
2511 pub env: Option<IndexMap<String, String>>,
2513 #[serde(default)]
2518 pub env_file: Vec<String>,
2519 pub hooks: Option<PitchforkTomlHooks>,
2521 pub mise: Option<bool>,
2524 #[schemars(skip)]
2527 pub deferred_template_context: Option<String>,
2528 pub user: Option<String>,
2531 pub memory_limit: Option<MemoryLimit>,
2534 pub cpu_limit: Option<CpuLimit>,
2537 pub stop_signal: Option<StopConfig>,
2540 pub pty: Option<bool>,
2542 pub time_retention: Option<String>,
2545 pub line_retention: Option<i64>,
2548 pub archive_hook: Option<String>,
2551 pub logs: Option<PitchforkTomlDaemonLogs>,
2553 #[schemars(skip)]
2554 pub path: Option<PathBuf>,
2555}
2556
2557impl PitchforkTomlDaemon {
2558 pub fn effective_proxy_tls_port(&self) -> Option<u16> {
2564 self.proxy_tls_port.or(self.proxy_port)
2565 }
2566
2567 pub fn is_oneshot(&self) -> bool {
2569 self.oneshot.unwrap_or(false)
2570 }
2571
2572 pub(crate) fn oneshot_conflicts(&self) -> Vec<&'static str> {
2575 [
2576 ("ready_delay", self.ready_delay.is_some()),
2577 ("ready_output", self.ready_output.is_some()),
2578 ("ready_http", self.ready_http.is_some()),
2579 ("ready_port", self.ready_port.is_some()),
2580 ("ready_cmd", self.ready_cmd.is_some()),
2581 ("health_cmd", self.health_cmd.is_some()),
2582 ("health_http", self.health_http.is_some()),
2583 ("health_port", self.health_port.is_some()),
2584 ]
2585 .into_iter()
2586 .filter(|(_, set)| *set)
2587 .map(|(name, _)| name)
2588 .collect()
2589 }
2590
2591 pub fn effective_user(&self) -> Option<String> {
2595 let daemon_user = self
2596 .user
2597 .as_deref()
2598 .map(str::trim)
2599 .filter(|u| !u.is_empty());
2600 daemon_user.map(str::to_owned).or_else(|| {
2601 let s = crate::settings::settings();
2602 let su = s.supervisor.user.trim();
2603 (!su.is_empty()).then(|| su.to_owned())
2604 })
2605 }
2606
2607 pub fn to_run_options(
2612 &self,
2613 id: &crate::daemon_id::DaemonId,
2614 cmd: Vec<String>,
2615 ) -> crate::daemon::RunOptions {
2616 use crate::daemon::RunOptions;
2617
2618 let effective_user = self.effective_user();
2619 let dir = crate::ipc::batch::resolve_daemon_dir(
2620 self.dir.as_deref(),
2621 self.path.as_deref(),
2622 effective_user.as_deref(),
2623 );
2624 let slug = PitchforkToml::find_slug_for_daemon_in_registry(
2627 id,
2628 &PitchforkToml::read_global_slugs(),
2629 );
2630
2631 RunOptions {
2632 id: id.clone(),
2633 cmd,
2634 run: self.run.shell_script().map(str::to_string),
2635 no_shell: self.run.is_argv(),
2636 replaces_ready_checks: false,
2637 requested_by_client: false,
2639 force: false,
2640 shell_pid: None,
2641 dir: Dir(dir),
2642 autostop: self.auto.contains(&PitchforkTomlAuto::Stop),
2643 oneshot: self.is_oneshot(),
2644 cron_started: false,
2647 oneshot_wait: None,
2651 on_directory_enter: false,
2652 cron_schedule: self.cron.as_ref().map(|c| c.schedule.clone()),
2653 cron_retrigger: self.cron.as_ref().map(|c| c.retrigger),
2654 cron_immediate: self.cron.as_ref().map(|c| c.immediate),
2655 retry: self.retry,
2656 retry_count: 0,
2657 ready_delay: self.ready_delay,
2658 ready_output: self.ready_output.clone(),
2659 ready_http: self.ready_http.clone(),
2660 ready_port: self.ready_port.clone(),
2661 ready_cmd: self.ready_cmd.clone(),
2662 health_cmd: self.health_cmd.clone(),
2663 health_http: self.health_http.clone(),
2664 health_port: self.health_port.clone(),
2665 port: self.port.clone(),
2666 wait_ready: false,
2667 depends: self.depends.clone(),
2668 env: self.env.clone(),
2669 watch: self.watch.clone(),
2670 watch_mode: self.watch_mode,
2671 watch_base_dir: Some(crate::ipc::batch::resolve_config_base_dir(
2672 self.path.as_deref(),
2673 )),
2674 mise: self.mise,
2675 deferred_template_context: self.deferred_template_context.clone(),
2676 mise_bin: None,
2678 slug,
2679 proxy: None,
2680 user: self.user.clone(),
2681 memory_limit: self.memory_limit,
2682 cpu_limit: self.cpu_limit,
2683 stop_signal: self.stop_signal,
2684 archive_hook: self
2685 .logs
2686 .as_ref()
2687 .and_then(|l| l.archive_hook.clone())
2688 .or_else(|| self.archive_hook.clone()),
2689 log_format: self.logs.as_ref().and_then(|l| l.log_format.clone()),
2690 on_output_hook: self.hooks.as_ref().and_then(|h| h.on_output.clone()),
2691 pty: self.pty,
2692 proxy_idle_timeout_ms: None,
2694 replaces_saved_record: true,
2695 }
2696 }
2697}
2698fn example_run_command() -> &'static str {
2699 "exec node server.js"
2700}
2701
2702#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, JsonSchema)]
2705#[serde(untagged)]
2706pub enum RunCommand {
2707 Shell(String),
2710 Argv(#[schemars(length(min = 1))] Vec<String>),
2714}
2715
2716impl Default for RunCommand {
2717 fn default() -> Self {
2718 Self::Shell(String::new())
2719 }
2720}
2721
2722impl From<String> for RunCommand {
2723 fn from(run: String) -> Self {
2724 Self::Shell(run)
2725 }
2726}
2727
2728impl From<&str> for RunCommand {
2729 fn from(run: &str) -> Self {
2730 Self::Shell(run.to_string())
2731 }
2732}
2733
2734impl From<Vec<String>> for RunCommand {
2735 fn from(argv: Vec<String>) -> Self {
2736 Self::Argv(argv)
2737 }
2738}
2739
2740impl PartialEq<str> for RunCommand {
2741 fn eq(&self, other: &str) -> bool {
2742 matches!(self, Self::Shell(run) if run == other)
2743 }
2744}
2745
2746impl PartialEq<&str> for RunCommand {
2747 fn eq(&self, other: &&str) -> bool {
2748 self == *other
2749 }
2750}
2751
2752impl std::fmt::Display for RunCommand {
2755 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2756 match self {
2757 Self::Shell(run) => f.write_str(run),
2758 Self::Argv(argv) => f.write_str(&shell_words::join(argv)),
2759 }
2760 }
2761}
2762
2763impl RunCommand {
2764 pub fn argv(&self) -> std::result::Result<Vec<String>, shell_words::ParseError> {
2767 match self {
2768 Self::Shell(run) => shell_words::split(run),
2769 Self::Argv(argv) => Ok(argv.clone()),
2770 }
2771 }
2772
2773 pub fn shell_script(&self) -> Option<&str> {
2775 match self {
2776 Self::Shell(run) => Some(run),
2777 Self::Argv(_) => None,
2778 }
2779 }
2780
2781 pub fn is_argv(&self) -> bool {
2782 matches!(self, Self::Argv(_))
2783 }
2784
2785 pub fn try_map<E>(
2787 &self,
2788 mut f: impl FnMut(&str) -> std::result::Result<String, E>,
2789 ) -> std::result::Result<Self, E> {
2790 Ok(match self {
2791 Self::Shell(run) => Self::Shell(f(run)?),
2792 Self::Argv(argv) => Self::Argv(
2793 argv.iter()
2794 .map(|arg| f(arg))
2795 .collect::<std::result::Result<_, _>>()?,
2796 ),
2797 })
2798 }
2799}
2800
2801#[cfg(test)]
2802mod tests {
2803 use super::*;
2804 use std::path::Path;
2805
2806 fn parse_groups(toml: &str) -> IndexMap<String, GroupEntry> {
2807 PitchforkToml::parse_str(toml, Path::new("/tmp/my-project/pitchfork.toml"))
2808 .unwrap()
2809 .groups
2810 }
2811
2812 fn names(ids: &[DaemonId]) -> Vec<&str> {
2813 ids.iter().map(|id| id.name()).collect()
2814 }
2815
2816 #[test]
2817 fn test_group_includes_expand_before_own_daemons_and_dedupe() {
2818 let groups = parse_groups(
2819 r#"
2820[groups.core]
2821daemons = ["db", "cache"]
2822
2823[groups.extras]
2824daemons = ["mailer", "cache"]
2825
2826[groups.all]
2827groups = ["core", "extras"]
2828daemons = ["api", "db"]
2829"#,
2830 );
2831 let all = expand_group(&groups, "all").unwrap();
2832 assert_eq!(names(&all), ["db", "cache", "mailer", "api"]);
2833 }
2834
2835 #[test]
2836 fn test_group_includes_nest_and_allow_diamonds() {
2837 let groups = parse_groups(
2838 r#"
2839[groups.base]
2840daemons = ["db"]
2841
2842[groups.left]
2843groups = ["base"]
2844daemons = ["l"]
2845
2846[groups.right]
2847groups = ["base"]
2848daemons = ["r"]
2849
2850[groups.top]
2851groups = ["left", "right"]
2852"#,
2853 );
2854 let top = expand_group(&groups, "top").unwrap();
2855 assert_eq!(names(&top), ["db", "l", "r"]);
2856 }
2857
2858 #[test]
2859 fn test_group_includes_shared_by_many_paths_are_expanded_once() {
2860 let mut toml = String::from("[groups.g0]\ngroups = [\"g1\", \"g1\"]\n");
2863 for i in 1..60 {
2864 toml.push_str(&format!(
2865 "\n[groups.g{i}]\ngroups = [\"g{n}\", \"g{n}\"]\n",
2866 n = i + 1
2867 ));
2868 }
2869 toml.push_str("\n[groups.g60]\ndaemons = [\"db\"]\n");
2870 let groups = parse_groups(&toml);
2871 assert_eq!(names(&expand_group(&groups, "g0").unwrap()), ["db"]);
2872 }
2873
2874 #[test]
2875 fn test_group_include_cycle_is_an_error() {
2876 let groups = parse_groups(
2877 r#"
2878[groups.a]
2879groups = ["b"]
2880
2881[groups.b]
2882groups = ["c"]
2883
2884[groups.c]
2885groups = ["a"]
2886"#,
2887 );
2888 let err = expand_group(&groups, "a").unwrap_err().to_string();
2889 assert!(err.contains("a -> b -> c -> a"), "{err}");
2890 let err = expand_group(&parse_groups("[groups.x]\ngroups = [\"x\"]\n"), "x")
2891 .unwrap_err()
2892 .to_string();
2893 assert!(err.contains("x -> x"), "{err}");
2894 }
2895
2896 #[test]
2897 fn test_group_include_of_undefined_group_is_an_error() {
2898 let groups = parse_groups("[groups.all]\ngroups = [\"cor\"]\n\n[groups.core]\n");
2899 let err = expand_group(&groups, "all").unwrap_err().to_string();
2900 assert!(
2901 err.contains("group 'all' includes undefined group 'cor'"),
2902 "{err}"
2903 );
2904 }
2905
2906 #[test]
2907 fn test_group_without_daemons_key_parses() {
2908 let groups = parse_groups("[groups.empty]\n");
2909 assert!(expand_group(&groups, "empty").unwrap().is_empty());
2910 }
2911
2912 #[test]
2913 fn test_themes_parse_merge_and_survive_a_write() {
2914 let dir = tempfile::tempdir().unwrap();
2915 let path = dir.path().join("pitchfork.toml");
2916 std::fs::write(
2917 &path,
2918 "[themes.mine]\nbase = \"catppuccin_latte\"\nred = \"#ff0000\"\n",
2919 )
2920 .unwrap();
2921 let mut pt = PitchforkToml::read(&path).unwrap();
2922 assert_eq!(pt.themes["mine"].red.as_deref(), Some("#ff0000"));
2923
2924 let mut other = PitchforkToml::new(dir.path().join("other.toml"));
2925 other.themes.insert("mine".into(), ThemeDef::default());
2926 pt.merge(other);
2927 assert_eq!(pt.themes["mine"], ThemeDef::default());
2928
2929 let pt = PitchforkToml::read(&path).unwrap();
2930 pt.write().unwrap();
2931 assert_eq!(PitchforkToml::read(&path).unwrap().themes, pt.themes);
2932 }
2933
2934 #[test]
2935 fn test_daemon_user_parses_and_flows_to_run_options() {
2936 let pt = PitchforkToml::parse_str(
2937 r#"
2938[daemons.api]
2939run = "node server.js"
2940user = "postgres"
2941"#,
2942 Path::new("/tmp/my-project/pitchfork.toml"),
2943 )
2944 .unwrap();
2945
2946 let id = DaemonId::new("my-project", "api");
2947 let daemon = pt.daemons.get(&id).unwrap();
2948 assert_eq!(daemon.user.as_deref(), Some("postgres"));
2949
2950 let opts = daemon.to_run_options(&id, vec!["node".to_string(), "server.js".to_string()]);
2951 assert_eq!(opts.user.as_deref(), Some("postgres"));
2952 assert!(opts.replaces_saved_record);
2954 }
2955
2956 #[test]
2957 fn test_new_local_file_writes_daemons_of_the_directory_namespace() {
2958 let temp = tempfile::tempdir().unwrap();
2959 std::fs::write(
2960 temp.path().join("pitchfork.toml"),
2961 "namespace = \"myns\"\n\n[daemons.web]\nrun = \"sleep 60\"\n",
2962 )
2963 .unwrap();
2964 let path = temp.path().join("pitchfork.local.toml");
2965 let mut pt = PitchforkToml::new(path.clone());
2966 let id = DaemonId::new(namespace_from_path(&path).unwrap(), "api");
2967 assert_eq!(id.namespace(), "myns");
2968 pt.daemons.insert(
2969 id.clone(),
2970 PitchforkTomlDaemon {
2971 run: "sleep 60".into(),
2972 ..PitchforkTomlDaemon::default()
2973 },
2974 );
2975
2976 pt.write().unwrap();
2977
2978 let parsed = PitchforkToml::read(&path).unwrap();
2979 assert!(parsed.daemons.contains_key(&id));
2980 }
2981
2982 #[test]
2983 fn test_daemon_user_write_roundtrip() {
2984 let temp = tempfile::tempdir().unwrap();
2985 let path = temp.path().join("pitchfork.toml");
2986 let mut pt = PitchforkToml::new(path.clone());
2987 pt.namespace = Some("test-project".to_string());
2988 pt.daemons.insert(
2989 DaemonId::new("test-project", "api"),
2990 PitchforkTomlDaemon {
2991 run: "node server.js".into(),
2992 user: Some("postgres".to_string()),
2993 ..PitchforkTomlDaemon::default()
2994 },
2995 );
2996
2997 pt.write().unwrap();
2998
2999 let raw = std::fs::read_to_string(&path).unwrap();
3000 assert!(raw.contains("user = \"postgres\""));
3001
3002 let parsed = PitchforkToml::read(&path).unwrap();
3003 let daemon = parsed
3004 .daemons
3005 .get(&DaemonId::new("test-project", "api"))
3006 .unwrap();
3007 assert_eq!(daemon.user.as_deref(), Some("postgres"));
3008 }
3009
3010 fn awkward_argv() -> Vec<String> {
3012 [
3013 "node",
3014 "my server.js",
3015 "--name=\"a b\"",
3016 "it's",
3017 "a&b",
3018 "%PATH%",
3019 "$HOME",
3020 ]
3021 .map(str::to_string)
3022 .to_vec()
3023 }
3024
3025 #[test]
3026 fn test_run_array_parses_and_starts_without_a_shell() {
3027 let pt = PitchforkToml::parse_str(
3028 r#"
3029[daemons.api]
3030run = ["node", "my server.js", "--name=\"a b\"", "it's", "a&b", "%PATH%", "$HOME"]
3031"#,
3032 Path::new("/tmp/my-project/pitchfork.toml"),
3033 )
3034 .unwrap();
3035
3036 let id = DaemonId::new("my-project", "api");
3037 let daemon = pt.daemons.get(&id).unwrap();
3038 assert_eq!(daemon.run, RunCommand::Argv(awkward_argv()));
3039
3040 let opts = daemon.to_run_options(&id, daemon.run.argv().unwrap());
3041 assert_eq!(opts.cmd, awkward_argv());
3042 assert!(opts.no_shell);
3043 assert_eq!(opts.run, None);
3044 }
3045
3046 #[test]
3047 fn test_run_string_still_goes_through_the_shell() {
3048 let pt = PitchforkToml::parse_str(
3049 "[daemons.api]\nrun = \"exec node server.js\"\n",
3050 Path::new("/tmp/my-project/pitchfork.toml"),
3051 )
3052 .unwrap();
3053
3054 let id = DaemonId::new("my-project", "api");
3055 let daemon = pt.daemons.get(&id).unwrap();
3056 let opts = daemon.to_run_options(&id, daemon.run.argv().unwrap());
3057 assert!(!opts.no_shell);
3058 assert_eq!(opts.run.as_deref(), Some("exec node server.js"));
3059 }
3060
3061 #[test]
3062 fn test_run_array_write_roundtrip() {
3063 let temp = tempfile::tempdir().unwrap();
3064 let path = temp.path().join("pitchfork.toml");
3065 let mut pt = PitchforkToml::new(path.clone());
3066 pt.namespace = Some("test-project".to_string());
3067 let id = DaemonId::new("test-project", "api");
3068 pt.daemons.insert(
3069 id.clone(),
3070 PitchforkTomlDaemon {
3071 run: RunCommand::Argv(awkward_argv()),
3072 ..PitchforkTomlDaemon::default()
3073 },
3074 );
3075 pt.daemons.insert(
3076 DaemonId::new("test-project", "worker"),
3077 PitchforkTomlDaemon {
3078 run: "exec ./worker --queue \"a b\"".into(),
3079 ..PitchforkTomlDaemon::default()
3080 },
3081 );
3082
3083 pt.write().unwrap();
3084
3085 let parsed = PitchforkToml::read(&path).unwrap();
3086 assert_eq!(parsed.daemons[&id].run, RunCommand::Argv(awkward_argv()));
3087 assert_eq!(
3088 parsed.daemons[&DaemonId::new("test-project", "worker")].run,
3089 "exec ./worker --queue \"a b\""
3090 );
3091 }
3092
3093 #[test]
3094 fn test_run_array_must_name_a_program() {
3095 let err = PitchforkToml::parse_str(
3096 "[daemons.api]\nrun = []\n",
3097 Path::new("/tmp/my-project/pitchfork.toml"),
3098 )
3099 .unwrap_err();
3100 assert!(
3101 err.chain()
3102 .any(|cause| cause.to_string().contains("empty run array")),
3103 "unexpected error: {err:?}"
3104 );
3105 }
3106
3107 #[test]
3108 fn test_run_array_rejects_exec() {
3109 let err = PitchforkToml::parse_str(
3110 "[daemons.api]\nrun = [\"exec\", \"node\", \"server.js\"]\n",
3111 Path::new("/tmp/my-project/pitchfork.toml"),
3112 )
3113 .unwrap_err();
3114 assert!(
3115 err.chain().any(|cause| cause
3116 .to_string()
3117 .contains("starts its run array with \"exec\"")),
3118 "unexpected error: {err:?}"
3119 );
3120 }
3121
3122 #[test]
3123 fn test_ready_cmd_array_parses_in_both_forms() {
3124 let pt = PitchforkToml::parse_str(
3125 r#"
3126[daemons.api]
3127run = "node server.js"
3128ready_cmd = ["node", "my server.js", "--name=\"a b\"", "it's", "a&b", "%PATH%", "$HOME"]
3129
3130[daemons.db]
3131run = "postgres"
3132ready_cmd = { run = ["pg_isready", "-h", "localhost"], timeout = "30s" }
3133
3134[daemons.cache]
3135run = "redis-server"
3136ready_cmd = "redis-cli ping"
3137"#,
3138 Path::new("/tmp/my-project/pitchfork.toml"),
3139 )
3140 .unwrap();
3141
3142 let ready = |name: &str| {
3143 pt.daemons[&DaemonId::new("my-project", name)]
3144 .ready_cmd
3145 .clone()
3146 .unwrap()
3147 };
3148 assert_eq!(ready("api").run, RunCommand::Argv(awkward_argv()));
3149 assert_eq!(ready("api").timeout, None);
3150 assert_eq!(
3151 ready("db").run,
3152 RunCommand::Argv(
3153 ["pg_isready", "-h", "localhost"]
3154 .map(str::to_string)
3155 .to_vec()
3156 )
3157 );
3158 assert_eq!(
3159 ready("db").timeout,
3160 Some(std::time::Duration::from_secs(30))
3161 );
3162 assert_eq!(ready("cache").run, "redis-cli ping");
3163 }
3164
3165 #[test]
3166 fn test_ready_cmd_array_write_roundtrip() {
3167 let temp = tempfile::tempdir().unwrap();
3168 let path = temp.path().join("pitchfork.toml");
3169 let mut pt = PitchforkToml::new(path.clone());
3170 pt.namespace = Some("test-project".to_string());
3171 let short = ReadyCmd::new(awkward_argv());
3172 let full = ReadyCmd {
3173 run: RunCommand::Argv(
3174 ["pg_isready", "-h", "localhost"]
3175 .map(str::to_string)
3176 .to_vec(),
3177 ),
3178 timeout: Some(std::time::Duration::from_secs(30)),
3179 };
3180 for (name, ready_cmd) in [("api", &short), ("db", &full)] {
3181 pt.daemons.insert(
3182 DaemonId::new("test-project", name),
3183 PitchforkTomlDaemon {
3184 run: "true".into(),
3185 ready_cmd: Some(ready_cmd.clone()),
3186 ..PitchforkTomlDaemon::default()
3187 },
3188 );
3189 }
3190
3191 pt.write().unwrap();
3192
3193 let parsed = PitchforkToml::read(&path).unwrap();
3194 let ready = |name: &str| {
3195 parsed.daemons[&DaemonId::new("test-project", name)]
3196 .ready_cmd
3197 .clone()
3198 };
3199 assert_eq!(ready("api"), Some(short));
3200 assert_eq!(ready("db"), Some(full));
3201 }
3202
3203 #[test]
3204 fn test_ready_cmd_array_must_name_a_program() {
3205 for ready_cmd in ["[]", "[\"\"]", "{ run = [\"\", \"-h\"] }"] {
3206 let err = PitchforkToml::parse_str(
3207 &format!("[daemons.api]\nrun = \"true\"\nready_cmd = {ready_cmd}\n"),
3208 Path::new("/tmp/my-project/pitchfork.toml"),
3209 )
3210 .unwrap_err();
3211 assert!(
3212 err.chain().any(|cause| cause
3213 .to_string()
3214 .contains("has no program in its ready_cmd array")),
3215 "unexpected error for {ready_cmd}: {err:?}"
3216 );
3217 }
3218 }
3219
3220 #[test]
3221 fn test_ready_cmd_array_rejects_exec() {
3222 let err = PitchforkToml::parse_str(
3223 "[daemons.api]\nrun = \"true\"\nready_cmd = { run = [\"exec\", \"pg_isready\"] }\n",
3224 Path::new("/tmp/my-project/pitchfork.toml"),
3225 )
3226 .unwrap_err();
3227 assert!(
3228 err.chain().any(|cause| cause
3229 .to_string()
3230 .contains("starts its ready_cmd array with \"exec\"")),
3231 "unexpected error: {err:?}"
3232 );
3233 }
3234
3235 #[test]
3236 fn test_health_cmd_array_parses_and_round_trips() {
3237 let pt = PitchforkToml::parse_str(
3238 r#"
3239[daemons.api]
3240run = "node server.js"
3241health_cmd = ["node", "my server.js", "--name=\"a b\"", "it's", "a&b", "%PATH%", "$HOME"]
3242
3243[daemons.db]
3244run = "postgres"
3245health_cmd = { run = ["pg_isready", "-h", "localhost"], interval = "5s", retries = 2 }
3246
3247[daemons.cache]
3248run = "redis-server"
3249health_cmd = "redis-cli ping"
3250"#,
3251 Path::new("/tmp/my-project/pitchfork.toml"),
3252 )
3253 .unwrap();
3254 let health = |pt: &PitchforkToml, ns: &str, name: &str| {
3255 pt.daemons[&DaemonId::new(ns, name)]
3256 .health_cmd
3257 .clone()
3258 .unwrap()
3259 };
3260 assert_eq!(
3261 health(&pt, "my-project", "api").run,
3262 RunCommand::Argv(awkward_argv())
3263 );
3264 let db = health(&pt, "my-project", "db");
3265 assert_eq!(
3266 db.run,
3267 RunCommand::Argv(
3268 ["pg_isready", "-h", "localhost"]
3269 .map(str::to_string)
3270 .to_vec()
3271 )
3272 );
3273 assert_eq!(db.interval, Some(std::time::Duration::from_secs(5)));
3274 assert_eq!(db.retries, Some(2));
3275 assert_eq!(health(&pt, "my-project", "cache").run, "redis-cli ping");
3276
3277 let temp = tempfile::tempdir().unwrap();
3278 let path = temp.path().join("pitchfork.toml");
3279 let mut written = PitchforkToml::new(path.clone());
3280 written.namespace = Some("test-project".to_string());
3281 for name in ["api", "db"] {
3282 written.daemons.insert(
3283 DaemonId::new("test-project", name),
3284 PitchforkTomlDaemon {
3285 run: "true".into(),
3286 health_cmd: Some(health(&pt, "my-project", name)),
3287 ..PitchforkTomlDaemon::default()
3288 },
3289 );
3290 }
3291 written.write().unwrap();
3292 let parsed = PitchforkToml::read(&path).unwrap();
3293 for name in ["api", "db"] {
3294 assert_eq!(
3295 health(&parsed, "test-project", name),
3296 health(&pt, "my-project", name)
3297 );
3298 }
3299 }
3300
3301 #[test]
3302 fn test_health_cmd_array_must_name_a_program_and_not_exec() {
3303 for (health_cmd, expected) in [
3304 ("[]", "has no program in its health_cmd array"),
3305 ("[\"\"]", "has no program in its health_cmd array"),
3306 (
3307 "{ run = [\"exec\", \"pg_isready\"] }",
3308 "starts its health_cmd array with \"exec\"",
3309 ),
3310 ] {
3311 let err = PitchforkToml::parse_str(
3312 &format!("[daemons.api]\nrun = \"true\"\nhealth_cmd = {health_cmd}\n"),
3313 Path::new("/tmp/my-project/pitchfork.toml"),
3314 )
3315 .unwrap_err();
3316 assert!(
3317 err.chain()
3318 .any(|cause| cause.to_string().contains(expected)),
3319 "unexpected error for {health_cmd}: {err:?}"
3320 );
3321 }
3322 }
3323
3324 #[test]
3325 fn test_registry_dirs_expand_tilde() {
3326 let pt = PitchforkToml::parse_str(
3327 r#"
3328[slugs.api]
3329dir = "~/projects/api"
3330
3331[namespaces.web]
3332dir = "~/projects/web"
3333"#,
3334 Path::new("/tmp/config.toml"),
3335 )
3336 .unwrap();
3337
3338 assert_eq!(
3339 pt.slugs["api"].dir,
3340 Some(crate::env::HOME_DIR.join("projects/api"))
3341 );
3342 assert_eq!(
3343 pt.namespaces["web"].dir,
3344 crate::env::HOME_DIR.join("projects/web")
3345 );
3346 }
3347
3348 #[test]
3349 fn test_settings_write_roundtrip() {
3350 let temp = tempfile::tempdir().unwrap();
3351 let path = temp.path().join("pitchfork.toml");
3352 let mut pt = PitchforkToml::new(path.clone());
3353 pt.namespace = Some("test-project".to_string());
3354 pt.settings.web.auto_start = Some(true);
3355 pt.settings.general.log_level = Some("debug".to_string());
3356
3357 pt.write().unwrap();
3358
3359 let raw = std::fs::read_to_string(&path).unwrap();
3360 assert!(
3361 raw.contains("[settings.web]"),
3362 "settings.web section should be written, got:\n{raw}"
3363 );
3364 assert!(raw.contains("auto_start = true"));
3365 assert!(raw.contains("log_level = \"debug\""));
3366
3367 let parsed = PitchforkToml::read(&path).unwrap();
3368 assert_eq!(parsed.settings.web.auto_start, Some(true));
3369 assert_eq!(parsed.settings.general.log_level.as_deref(), Some("debug"));
3370 }
3371
3372 fn slug_entry(namespace: &str, daemon: Option<&str>) -> SlugEntry {
3373 SlugEntry {
3374 dir: None,
3375 namespace: Some(namespace.to_string()),
3376 daemon: daemon.map(str::to_string),
3377 }
3378 }
3379
3380 #[test]
3381 fn test_slug_is_ambiguous() {
3382 let mut slugs = IndexMap::new();
3383 slugs.insert("api".to_string(), slug_entry("my-project", None));
3384 assert!(!PitchforkToml::slug_is_ambiguous("api", &slugs));
3385
3386 slugs.insert("API".to_string(), slug_entry("other-project", None));
3387 assert!(PitchforkToml::slug_is_ambiguous("api", &slugs));
3389 assert!(PitchforkToml::slug_is_ambiguous("API", &slugs));
3390 }
3391
3392 #[test]
3393 fn test_find_slug_for_daemon_skips_case_collisions() {
3394 let id = DaemonId::new("my-project", "api");
3395 let mut slugs = IndexMap::new();
3396 slugs.insert("api".to_string(), slug_entry("my-project", None));
3397 assert_eq!(
3398 PitchforkToml::find_slug_for_daemon_in_registry(&id, &slugs),
3399 Some("api".to_string())
3400 );
3401
3402 slugs.insert("API".to_string(), slug_entry("other-project", None));
3405 assert_eq!(
3406 PitchforkToml::find_slug_for_daemon_in_registry(&id, &slugs),
3407 None
3408 );
3409 }
3410
3411 #[test]
3412 fn test_find_slug_for_daemon_prefers_a_routable_alias() {
3413 let id = DaemonId::new("my-project", "api");
3414 let mut slugs = IndexMap::new();
3415 slugs.insert("api".to_string(), slug_entry("my-project", None));
3418 slugs.insert("API".to_string(), slug_entry("my-project", None));
3419 slugs.insert("my-api".to_string(), slug_entry("my-project", Some("api")));
3420
3421 assert_eq!(
3422 PitchforkToml::find_slug_for_daemon_in_registry(&id, &slugs),
3423 Some("my-api".to_string())
3424 );
3425 }
3426
3427 #[test]
3428 fn test_settings_preserved_on_unrelated_write() {
3429 let temp = tempfile::tempdir().unwrap();
3432 let path = temp.path().join("pitchfork.toml");
3433 std::fs::write(&path, "[settings.web]\nauto_start = true\n").unwrap();
3434
3435 let mut pt = PitchforkToml::read(&path).unwrap();
3436 pt.slugs.insert(
3437 "api".to_string(),
3438 SlugEntry {
3439 dir: None,
3440 namespace: Some("myproject".to_string()),
3441 daemon: None,
3442 },
3443 );
3444 pt.namespaces.insert(
3445 "myproject".to_string(),
3446 NamespaceEntry {
3447 dir: PathBuf::from("/tmp/myproject"),
3448 config: Vec::new(),
3449 label: None,
3450 },
3451 );
3452 pt.write().unwrap();
3453
3454 let raw = std::fs::read_to_string(&path).unwrap();
3455 assert!(
3456 raw.contains("[settings.web]"),
3457 "existing settings must be preserved, got:\n{raw}"
3458 );
3459 assert!(raw.contains("auto_start = true"));
3460 assert!(raw.contains("[slugs.api]"));
3461
3462 let parsed = PitchforkToml::read(&path).unwrap();
3463 assert_eq!(parsed.settings.web.auto_start, Some(true));
3464 assert!(parsed.slugs.contains_key("api"));
3465 }
3466
3467 #[tokio::test]
3468 async fn test_proxy_worktree_alias_is_canonicalized_on_rewrite() {
3469 let temp = tempfile::tempdir().unwrap();
3470 let path = temp.path().join("pitchfork.toml");
3471 tokio::fs::write(&path, "[settings.proxy]\nworktree = false\n")
3472 .await
3473 .unwrap();
3474
3475 let read_path = path.clone();
3476 let pt = tokio::task::spawn_blocking(move || PitchforkToml::read(&read_path))
3477 .await
3478 .unwrap()
3479 .unwrap();
3480 assert_eq!(pt.settings.general.worktree, Some(false));
3481 assert_eq!(pt.settings.proxy.worktree, None);
3482 tokio::task::spawn_blocking(move || pt.write())
3483 .await
3484 .unwrap()
3485 .unwrap();
3486
3487 let raw = tokio::fs::read_to_string(&path).await.unwrap();
3488 assert!(raw.contains("[settings.general]"), "{raw}");
3489 assert!(raw.contains("worktree = false"), "{raw}");
3490 assert!(!raw.contains("[settings.proxy]"), "{raw}");
3491
3492 let parsed = tokio::task::spawn_blocking(move || PitchforkToml::read(&path))
3493 .await
3494 .unwrap()
3495 .unwrap();
3496 assert_eq!(parsed.settings.general.worktree, Some(false));
3497 }
3498
3499 #[test]
3500 fn test_config_cache_hit_and_invalidation() {
3501 let temp = tempfile::tempdir().unwrap();
3502 let dir = temp.path();
3503 let config_path = dir.join("pitchfork.toml");
3504 std::fs::write(&config_path, "[daemons.api]\nrun = \"echo v1\"\n").unwrap();
3505
3506 super::invalidate_config_cache();
3508
3509 let pt1 = PitchforkToml::all_merged_from(dir).unwrap();
3511 let daemon_id = DaemonId::new(namespace_from_path(&config_path).unwrap(), "api");
3512 assert_eq!(pt1.daemons[&daemon_id].run, "echo v1");
3513
3514 let pt2 = PitchforkToml::all_merged_from(dir).unwrap();
3516 assert_eq!(pt2.daemons[&daemon_id].run, "echo v1");
3517
3518 std::thread::sleep(std::time::Duration::from_millis(50));
3521 std::fs::write(&config_path, "[daemons.api]\nrun = \"echo v2\"\n").unwrap();
3522
3523 let pt3 = PitchforkToml::all_merged_from(dir).unwrap();
3524 assert_eq!(pt3.daemons[&daemon_id].run, "echo v2");
3525
3526 super::invalidate_config_cache();
3528 let pt4 = PitchforkToml::all_merged_from(dir).unwrap();
3529 assert_eq!(pt4.daemons[&daemon_id].run, "echo v2");
3530
3531 super::invalidate_config_cache();
3533 }
3534
3535 #[test]
3536 fn test_config_cache_invalidation_on_write() {
3537 let temp = tempfile::tempdir().unwrap();
3538 let dir = temp.path();
3539 let config_path = dir.join("pitchfork.toml");
3540 std::fs::write(&config_path, "[daemons.api]\nrun = \"echo v1\"\n").unwrap();
3541
3542 super::invalidate_config_cache();
3543
3544 let pt1 = PitchforkToml::all_merged_from(dir).unwrap();
3546 let daemon_id = DaemonId::new(namespace_from_path(&config_path).unwrap(), "api");
3547 assert_eq!(pt1.daemons[&daemon_id].run, "echo v1");
3548
3549 let mut pt = PitchforkToml::read(&config_path).unwrap();
3551 pt.daemons.get_mut(&daemon_id).unwrap().run = "echo v3".into();
3552 let _ = pt.write();
3554
3555 let pt2 = PitchforkToml::all_merged_from(dir).unwrap();
3557 assert_eq!(pt2.daemons[&daemon_id].run, "echo v3");
3558
3559 super::invalidate_config_cache();
3560 }
3561
3562 #[test]
3563 fn test_config_cache_size_invalidation() {
3564 let temp = tempfile::tempdir().unwrap();
3565 let dir = temp.path();
3566 let config_path = dir.join("pitchfork.toml");
3567 std::fs::write(&config_path, "[daemons.api]\nrun = \"echo v1\"\n").unwrap();
3568
3569 super::invalidate_config_cache();
3570
3571 let pt1 = PitchforkToml::all_merged_from(dir).unwrap();
3573 let daemon_id = DaemonId::new(namespace_from_path(&config_path).unwrap(), "api");
3574 assert_eq!(pt1.daemons[&daemon_id].run, "echo v1");
3575
3576 let original_mtime = std::fs::metadata(&config_path).unwrap().modified().unwrap();
3580 std::fs::write(&config_path, "[daemons.api]\nrun = \"echo different\"\n").unwrap();
3581 let file = std::fs::OpenOptions::new()
3584 .write(true)
3585 .open(&config_path)
3586 .unwrap();
3587 let times = std::fs::FileTimes::new().set_modified(original_mtime);
3588 file.set_times(times).unwrap();
3589
3590 let pt2 = PitchforkToml::all_merged_from(dir).unwrap();
3593 assert_eq!(
3594 pt2.daemons[&daemon_id].run, "echo different",
3595 "cache should invalidate on size change even with identical mtime"
3596 );
3597
3598 super::invalidate_config_cache();
3599 }
3600
3601 #[test]
3602 fn test_find_project_root_in_plain_dir_returns_none() {
3603 let temp = tempfile::tempdir().unwrap();
3604 assert_eq!(find_project_root(temp.path()), None);
3605 }
3606
3607 #[test]
3608 fn test_find_project_root_finds_git_marker() {
3609 let temp = tempfile::tempdir().unwrap();
3610 let repo = temp.path().join("my-repo");
3611 std::fs::create_dir(&repo).unwrap();
3612 std::fs::create_dir(repo.join(".git")).unwrap();
3613
3614 let sub = repo.join("sub/dir");
3615 std::fs::create_dir_all(&sub).unwrap();
3616
3617 assert_eq!(find_project_root(&sub), Some(repo.canonicalize().unwrap()));
3620 }
3621
3622 #[test]
3623 fn test_find_project_root_accepts_git_file_marker() {
3624 let temp = tempfile::tempdir().unwrap();
3627 let wt = temp.path().join("my-worktree");
3628 std::fs::create_dir(&wt).unwrap();
3629 std::fs::write(wt.join(".git"), "gitdir: /tmp/some-common-gitdir\n").unwrap();
3630
3631 assert_eq!(find_project_root(&wt), Some(wt.canonicalize().unwrap()));
3632 }
3633
3634 #[cfg(unix)]
3637 #[test]
3638 fn test_find_project_root_resolves_symlinked_start_dir() {
3639 use std::os::unix::fs::symlink;
3640
3641 let temp = tempfile::tempdir().unwrap();
3642 let repo = temp.path().join("real-repo");
3643 std::fs::create_dir(&repo).unwrap();
3644 std::fs::create_dir(repo.join(".git")).unwrap();
3645
3646 let sub = repo.join("sub/dir");
3647 std::fs::create_dir_all(&sub).unwrap();
3648 let link = temp.path().join("link-to-sub");
3649 symlink(&sub, &link).unwrap();
3650
3651 assert_eq!(find_project_root(&link), Some(repo.canonicalize().unwrap()));
3652 }
3653
3654 #[test]
3657 fn test_all_merged_all_namespaces_discovers_worktrees() {
3658 let temp = tempfile::tempdir().unwrap();
3659 let repo = temp.path().join("my-repo");
3660 std::fs::create_dir(&repo).unwrap();
3661
3662 let git_init = std::process::Command::new("git")
3664 .args(["init", "-b", "main"])
3665 .current_dir(&repo)
3666 .output()
3667 .expect("git init");
3668 assert!(git_init.status.success(), "git init failed: {:?}", git_init);
3669
3670 std::fs::write(repo.join("main.toml"), "hello\n").unwrap();
3671
3672 let git_commit = std::process::Command::new("git")
3673 .args([
3674 "-c",
3675 "user.name=pitchfork-test",
3676 "-c",
3677 "user.email=pitchfork-test@example.com",
3678 "add",
3679 "-A",
3680 ])
3681 .current_dir(&repo)
3682 .output()
3683 .expect("git add");
3684 assert!(git_commit.status.success());
3685
3686 let git_commit = std::process::Command::new("git")
3687 .args([
3688 "-c",
3689 "user.name=pitchfork-test",
3690 "-c",
3691 "user.email=pitchfork-test@example.com",
3692 "commit",
3693 "-m",
3694 "init",
3695 ])
3696 .current_dir(&repo)
3697 .output()
3698 .expect("git commit");
3699 assert!(
3700 git_commit.status.success(),
3701 "git commit failed: {:?}",
3702 git_commit
3703 );
3704
3705 let wt = temp.path().join("my-repo-feature");
3706 let git_wt = std::process::Command::new("git")
3707 .args(["worktree", "add", "-b", "feature-x", wt.to_str().unwrap()])
3708 .current_dir(&repo)
3709 .output()
3710 .expect("git worktree add");
3711 assert!(
3712 git_wt.status.success(),
3713 "git worktree add failed: {:?}",
3714 git_wt
3715 );
3716
3717 std::fs::write(
3719 repo.join("pitchfork.toml"),
3720 "[daemons.api]\nrun = \"echo main\"\n",
3721 )
3722 .unwrap();
3723 std::fs::write(
3725 wt.join("pitchfork.toml"),
3726 "[daemons.worker]\nrun = \"echo wt\"\n",
3727 )
3728 .unwrap();
3729
3730 super::invalidate_config_cache();
3731
3732 let pt = PitchforkToml::all_merged_all_namespaces_from_blocking(&wt).unwrap();
3734
3735 let main_id = DaemonId::new("my-repo", "api");
3736 let wt_id = DaemonId::new("my-repo-feature", "worker");
3737 assert!(
3738 pt.daemons.contains_key(&main_id),
3739 "main checkout daemon missing"
3740 );
3741 assert!(pt.daemons.contains_key(&wt_id), "worktree daemon missing");
3742
3743 let pt_from_main = PitchforkToml::all_merged_all_namespaces_from_blocking(&repo).unwrap();
3745 assert!(pt_from_main.daemons.contains_key(&wt_id));
3746
3747 let _ = std::process::Command::new("git")
3749 .args(["worktree", "remove", "--force", wt.to_str().unwrap()])
3750 .current_dir(&repo)
3751 .output();
3752 super::invalidate_config_cache();
3753 }
3754
3755 #[test]
3756 fn test_adhoc_id_uses_invocation_directory_namespace() {
3757 let temp = tempfile::tempdir().unwrap();
3758 let project = temp.path().join("feature-tree");
3759 std::fs::create_dir(&project).unwrap();
3760 std::fs::write(
3761 project.join("pitchfork.toml"),
3762 "[daemons.other]\nrun = \"true\"\n",
3763 )
3764 .unwrap();
3765
3766 let id = PitchforkToml::resolve_id_allow_adhoc_from("api", &project).unwrap();
3767 assert_eq!(id, DaemonId::new("feature-tree", "api"));
3768 let qualified =
3769 PitchforkToml::resolve_id_allow_adhoc_from("explicit/api", &project).unwrap();
3770 assert_eq!(qualified, DaemonId::new("explicit", "api"));
3771 }
3772
3773 #[test]
3774 fn test_adhoc_id_falls_back_to_global_without_project_config() {
3775 let temp = tempfile::tempdir().unwrap();
3776 let id = PitchforkToml::resolve_id_allow_adhoc_from("api", temp.path()).unwrap();
3777 assert_eq!(id, DaemonId::new("global", "api"));
3778 }
3779}