1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
//! High-level batch operations for daemon management.
//!
//! This module provides batch operations that can be used by CLI, TUI, and Web UI.
use crate::Result;
use crate::daemon::RunOptions;
use crate::daemon_id::DaemonId;
use crate::deps::{compute_reverse_stop_order, resolve_dependencies};
use crate::ipc::client::IpcClient;
use crate::pitchfork_toml::{
PitchforkToml, PitchforkTomlDaemon, ReadyHttp, is_dot_config_pitchfork, is_global_config,
};
use chrono::{DateTime, Local};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// Result of a daemon run operation
#[derive(Debug, Clone)]
pub struct RunResult {
pub started: bool,
pub exit_code: Option<i32>,
pub start_time: DateTime<Local>,
pub resolved_ports: Vec<u16>,
}
/// Result of batch start operation
#[derive(Debug)]
pub struct StartResult {
/// Daemons that were successfully started (id, start_time, resolved_ports)
pub started: Vec<(DaemonId, DateTime<Local>, Vec<u16>)>,
/// Whether any daemon failed to start
pub any_failed: bool,
}
/// Result of batch stop operation
#[derive(Debug)]
pub struct StopResult {
/// Whether any daemon failed to stop
pub any_failed: bool,
}
/// Result of spawning a start task
#[derive(Debug)]
pub struct SpawnTaskResult {
/// Daemon ID
pub id: DaemonId,
/// Start time if the daemon started successfully
pub start_time: Option<DateTime<Local>>,
/// Exit code if the daemon failed
pub exit_code: Option<i32>,
/// Resolved ports after auto-bump
pub resolved_ports: Vec<u16>,
}
/// Options for starting daemons
#[derive(Debug, Clone, Default)]
pub struct StartOptions {
/// Force restart if already running
pub force: bool,
/// Shell PID for autostop tracking
pub shell_pid: Option<u32>,
/// Override ready delay
pub delay: Option<u64>,
/// Override ready output pattern
pub output: Option<String>,
/// Override ready HTTP endpoint
pub http: Option<String>,
/// Override ready port
pub port: Option<u16>,
/// Override ready command
pub cmd: Option<String>,
/// Ports the daemon is expected to bind to (None = not specified, use config)
pub expected_port: Option<Vec<u16>>,
/// Port auto-bump configuration (None = use config, Some = override)
pub auto_bump_port: Option<crate::config_types::PortBump>,
/// Number of times to retry on failure (for ad-hoc daemons)
pub retry: Option<crate::config_types::Retry>,
}
/// Build RunOptions from a daemon configuration and start options.
///
/// This is a shared helper used by both IpcClient batch operations and Web UI.
/// It handles:
/// - Command parsing from the config's run string
/// - Extracting all config values (cron, retry, ready checks, depends, etc.)
/// - Merging CLI/API overrides with config defaults
pub fn build_run_options(
id: &DaemonId,
daemon_config: &PitchforkTomlDaemon,
opts: &StartOptions,
) -> std::result::Result<RunOptions, String> {
let cmd = shell_words::split(&daemon_config.run)
.map_err(|e| format!("Failed to parse command: {e}"))?;
let mut run_opts = daemon_config.to_run_options(id, cmd);
run_opts.shell_pid = opts.shell_pid;
run_opts.force = opts.force;
run_opts.wait_ready = true;
run_opts.ready_delay = opts.delay.or(run_opts.ready_delay).or(Some(3));
run_opts.ready_output = opts.output.clone().or(run_opts.ready_output);
run_opts.ready_http = merge_ready_http_override(run_opts.ready_http, opts.http.clone());
run_opts.ready_port = opts.port.or(run_opts.ready_port);
run_opts.ready_cmd = opts.cmd.clone().or(run_opts.ready_cmd);
if let Some(ref expected) = opts.expected_port {
run_opts.port.get_or_insert_with(Default::default).expect = expected.clone();
}
if let Some(bump) = opts.auto_bump_port {
run_opts.port.get_or_insert_with(Default::default).bump = bump;
}
Ok(run_opts)
}
fn merge_ready_http_override(
configured: Option<ReadyHttp>,
override_url: Option<String>,
) -> Option<ReadyHttp> {
match (configured, override_url) {
(Some(mut ready_http), Some(url)) => {
ready_http.url = url;
Some(ready_http)
}
(None, Some(url)) => Some(ReadyHttp::new(url)),
(ready_http, None) => ready_http,
}
}
impl IpcClient {
// =========================================================================
// Helper functions for resolving daemon IDs
// =========================================================================
/// Get all configured daemon IDs from pitchfork.toml files (both local and global)
pub fn get_all_configured_daemons() -> Result<Vec<DaemonId>> {
Ok(PitchforkToml::all_merged()?
.daemons
.keys()
.cloned()
.collect())
}
/// Get local configured daemon IDs (from pitchfork.toml files in current directory hierarchy)
///
/// This excludes daemons from global config files (~/.config/pitchfork/config.toml
/// and /etc/pitchfork/config.toml), returning only daemons defined in project-level
/// pitchfork.toml files.
pub fn get_local_configured_daemons() -> Result<Vec<DaemonId>> {
Self::get_configured_daemons_filtered(|id| id.namespace() != "global")
}
/// Get global configured daemon IDs (from ~/.config/pitchfork/config.toml and /etc/pitchfork/config.toml)
///
/// This returns only daemons defined in global config files, excluding project-level
/// pitchfork.toml files.
pub fn get_global_configured_daemons() -> Result<Vec<DaemonId>> {
Self::get_configured_daemons_filtered(|id| id.namespace() == "global")
}
/// Get configured daemon IDs filtered by a predicate
fn get_configured_daemons_filtered<F>(predicate: F) -> Result<Vec<DaemonId>>
where
F: Fn(&DaemonId) -> bool,
{
Ok(PitchforkToml::all_merged()?
.daemons
.into_keys()
.filter(predicate)
.collect())
}
/// Get IDs of currently running daemons
pub async fn get_running_daemons(&self) -> Result<Vec<DaemonId>> {
Ok(self
.active_daemons()
.await?
.iter()
.filter(|d| d.status.is_running() || d.status.is_waiting())
.map(|d| d.id.clone())
.collect())
}
/// Get IDs of currently running daemons that are configured
/// for stop / restart with --local or --global
pub async fn get_running_configured_daemons(&self, global: bool) -> Result<Vec<DaemonId>> {
let configured: HashSet<DaemonId> = if global {
Self::get_global_configured_daemons()?
} else {
Self::get_local_configured_daemons()?
}
.into_iter()
.collect();
Ok(self
.get_running_daemons()
.await?
.into_iter()
.filter(|id| configured.contains(id))
.collect())
}
// =========================================================================
// High-level batch operations (for CLI, TUI, Web UI)
// =========================================================================
/// Start daemons by ID with dependency resolution
///
/// Handles:
/// - ID resolution (short ID to qualified ID based on current directory)
/// - Dependency resolution (starts dependencies first)
/// - Disabled daemon filtering
/// - Already running daemon detection
/// - Parallel execution within dependency levels
/// - Ad-hoc daemon restart using saved commands
pub async fn start_daemons(
self: &Arc<Self>,
ids: &[DaemonId],
opts: StartOptions,
) -> Result<StartResult> {
let pt = PitchforkToml::all_merged()?;
let disabled_daemons = self.get_disabled_daemons().await?;
// Get all active daemons for ad-hoc restart support
let all_daemons = self.active_daemons().await?;
let adhoc_daemons: HashMap<DaemonId, crate::daemon::Daemon> = all_daemons
.into_iter()
.filter(|d| !pt.daemons.contains_key(&d.id))
.map(|d| (d.id.clone(), d))
.collect();
// Filter out disabled daemons from the requested list
let requested_ids: Vec<DaemonId> = ids
.iter()
.filter(|id| {
if disabled_daemons.contains(id) {
warn!("Daemon {id} is disabled");
false
} else {
true
}
})
.cloned()
.collect();
if requested_ids.is_empty() {
return Ok(StartResult {
started: vec![],
any_failed: false,
});
}
// Separate config-based daemons from ad-hoc daemons
let (config_ids, adhoc_ids): (Vec<DaemonId>, Vec<DaemonId>) = requested_ids
.into_iter()
.partition(|id| pt.daemons.contains_key(id));
// Get currently running daemons once and reuse the snapshot for both
// restart checks and template context.
let active_daemons = self.active_daemons().await?;
let running_daemons: HashSet<DaemonId> = active_daemons
.iter()
.filter(|d| d.status.is_running() || d.status.is_waiting())
.map(|d| d.id.clone())
.collect();
let running_ports_map: HashMap<DaemonId, Vec<u16>> = active_daemons
.into_iter()
.filter(|d| {
(d.status.is_running() || d.status.is_waiting()) && !d.resolved_port.is_empty()
})
.map(|d| (d.id, d.resolved_port))
.collect();
// Collect set of explicitly requested IDs for force restart check
let explicitly_requested: HashSet<DaemonId> = ids.iter().cloned().collect();
// Start daemons level by level
let mut any_failed = false;
let mut successful_daemons: Vec<(DaemonId, DateTime<Local>, Vec<u16>)> = Vec::new();
// Accumulated resolved ports from completed levels, available for template rendering
let mut resolved_ports_map: std::collections::HashMap<DaemonId, Vec<u16>> =
std::collections::HashMap::new();
// First, handle config-based daemons with dependency resolution
if !config_ids.is_empty() {
// Resolve dependencies to get start order (levels)
let dep_order = resolve_dependencies(&config_ids, &pt.daemons)?;
for level in dep_order.levels {
let mut successful_this_level: Vec<(DaemonId, Vec<u16>)> = Vec::new();
// Filter daemons to start in this level
let to_start: Vec<DaemonId> = level
.iter()
.filter(|&id| {
// Skip disabled daemons (dependencies might be disabled)
if disabled_daemons.contains(id) {
warn!("Skipping disabled daemon {id} (dependency)");
return false;
}
// Skip already running daemons unless they are explicitly requested
// with force=true
if running_daemons.contains(id) {
if opts.force && explicitly_requested.contains(id) {
debug!("Force restarting explicitly requested daemon: {id}");
true // Allow restart if force is set AND explicitly requested
} else {
if explicitly_requested.contains(id) {
info!("Daemon {id} is already running, use --force to restart");
} else {
debug!("Skipping already running daemon {id}");
}
false
}
} else {
true
}
})
.cloned()
.collect();
for id in &level {
if let Some(ports) = running_ports_map.get(id) {
resolved_ports_map.insert(id.clone(), ports.clone());
}
}
if to_start.is_empty() {
continue;
}
// Start all daemons in this level concurrently
let mut tasks = Vec::new();
for id in to_start {
if let Some(daemon_config) = pt.daemons.get(&id) {
// Render Tera templates with context from previously started daemons
let mut rendered_config = daemon_config.clone();
let template_ctx = crate::template::TemplateContext::new(
&id,
daemon_config,
&resolved_ports_map,
&pt.daemons,
);
match crate::template::render_daemon_templates(
&mut rendered_config,
&template_ctx,
) {
Ok(()) => {}
Err(e) => {
error!("Template render error for daemon {id}: {e}");
any_failed = true;
continue;
}
}
let is_explicit = explicitly_requested.contains(&id);
let task = Self::spawn_start_task(
self.clone(),
id,
&rendered_config,
is_explicit,
&opts,
);
tasks.push(task);
}
}
// Wait for all daemons in this level to complete before moving to next level
for task in tasks {
match task.await {
Ok(result) => {
if result.exit_code.is_some() {
any_failed = true;
error!("Daemon {} failed to start", result.id);
} else if let Some(start_time) = result.start_time {
successful_this_level
.push((result.id.clone(), result.resolved_ports.clone()));
successful_daemons.push((
result.id,
start_time,
result.resolved_ports,
));
}
}
Err(e) => {
error!("Task panicked: {e}");
any_failed = true;
}
}
}
// Daemons from this level become visible to later levels if they
// either started successfully now or were already running.
for (id, ports) in successful_this_level {
resolved_ports_map.insert(id, ports);
}
// If any daemon in this level failed, abort starting dependents
if any_failed {
error!("Dependency failed, aborting remaining starts");
break;
}
}
}
// Then, handle ad-hoc daemons (no dependency resolution needed)
if !any_failed && !adhoc_ids.is_empty() {
let mut tasks = Vec::new();
for id in adhoc_ids {
// Skip already running daemons unless force is set
if running_daemons.contains(&id) {
if opts.force && explicitly_requested.contains(&id) {
debug!("Force restarting ad-hoc daemon: {id}");
} else {
if explicitly_requested.contains(&id) {
info!("Ad-hoc daemon {id} is already running, use --force to restart");
}
continue;
}
}
if let Some(adhoc_daemon) = adhoc_daemons.get(&id) {
if adhoc_daemon.cmd.is_some() {
let is_explicit = explicitly_requested.contains(&id);
let task = Self::spawn_adhoc_start_task(
self.clone(),
id,
adhoc_daemon,
is_explicit,
&opts,
);
tasks.push(task);
} else {
warn!("Ad-hoc daemon {id} has no saved command, cannot restart");
}
} else {
warn!("Daemon {id} not found in config or state");
}
}
// Wait for all ad-hoc daemons to complete
for task in tasks {
match task.await {
Ok(result) => {
if result.exit_code.is_some() {
any_failed = true;
error!("Ad-hoc daemon {} failed to start", result.id);
} else if let Some(start_time) = result.start_time {
successful_daemons.push((result.id, start_time, result.resolved_ports));
}
}
Err(e) => {
error!("Task panicked: {e}");
any_failed = true;
}
}
}
}
Ok(StartResult {
started: successful_daemons,
any_failed,
})
}
/// Spawn a task to start a single daemon
///
/// This encapsulates the start logic for one daemon, allowing parallel execution
/// within the same dependency level. It handles:
/// - Command parsing
/// - Config merging (CLI options override config file)
/// - IPC communication with supervisor
fn spawn_start_task(
ipc: Arc<Self>,
id: DaemonId,
daemon_config: &PitchforkTomlDaemon,
is_explicitly_requested: bool,
opts: &StartOptions,
) -> tokio::task::JoinHandle<SpawnTaskResult> {
// Build options with force only if explicitly requested
let mut start_opts = opts.clone();
start_opts.force = opts.force && is_explicitly_requested;
let run_opts = build_run_options(&id, daemon_config, &start_opts);
tokio::spawn(async move {
let run_opts = match run_opts {
Ok(opts) => opts,
Err(e) => {
error!("Failed to parse command for daemon {id}: {e}");
return SpawnTaskResult {
id,
start_time: None,
exit_code: Some(1),
resolved_ports: Vec::new(),
};
}
};
let result = ipc.run(run_opts).await;
match result {
Ok(run_result) => {
if run_result.started {
SpawnTaskResult {
id,
start_time: Some(run_result.start_time),
exit_code: run_result.exit_code,
resolved_ports: run_result.resolved_ports,
}
} else {
SpawnTaskResult {
id,
start_time: None,
exit_code: run_result.exit_code,
resolved_ports: run_result.resolved_ports,
}
}
}
Err(e) => {
error!("Failed to start daemon {id}: {e}");
SpawnTaskResult {
id,
start_time: None,
exit_code: Some(1),
resolved_ports: Vec::new(),
}
}
}
})
}
/// Spawn a task to start an ad-hoc daemon using saved command
///
/// This handles restarting ad-hoc daemons that were originally started
/// via `pitchfork run` command.
fn spawn_adhoc_start_task(
ipc: Arc<Self>,
id: DaemonId,
adhoc_daemon: &crate::daemon::Daemon,
is_explicitly_requested: bool,
opts: &StartOptions,
) -> tokio::task::JoinHandle<SpawnTaskResult> {
let cmd = adhoc_daemon
.cmd
.clone()
.expect("ad-hoc daemon start task requires a saved command");
let dir = adhoc_daemon.dir.clone().unwrap_or_default();
let env = adhoc_daemon.env.clone();
let ready_http = adhoc_daemon.ready_http.clone();
let force = opts.force && is_explicitly_requested;
let delay = opts.delay;
let output = opts.output.clone();
let http = merge_ready_http_override(ready_http, opts.http.clone());
let port = opts.port;
let ready_cmd = opts.cmd.clone();
let expected_port = opts.expected_port.clone();
let auto_bump_port = opts.auto_bump_port;
let retry = opts.retry.unwrap_or_default();
let shell_pid = opts.shell_pid;
tokio::spawn(async move {
let run_opts = RunOptions {
id: id.clone(),
cmd,
force,
shell_pid,
dir: crate::config_types::Dir(dir),
retry,
ready_delay: delay.or(Some(3)),
ready_output: output,
ready_http: http,
ready_port: port,
ready_cmd,
port: crate::config_types::PortConfig::from_parts(
expected_port.unwrap_or_default(),
auto_bump_port.unwrap_or_default(),
),
wait_ready: true,
env,
watch: vec![],
watch_base_dir: None,
mise: None,
slug: None,
proxy: None,
..RunOptions::default()
};
let result = ipc.run(run_opts).await;
match result {
Ok(run_result) => {
if run_result.started {
SpawnTaskResult {
id,
start_time: Some(run_result.start_time),
exit_code: run_result.exit_code,
resolved_ports: run_result.resolved_ports,
}
} else {
SpawnTaskResult {
id,
start_time: None,
exit_code: run_result.exit_code,
resolved_ports: run_result.resolved_ports,
}
}
}
Err(e) => {
error!("Failed to start ad-hoc daemon {id}: {e}");
SpawnTaskResult {
id,
start_time: None,
exit_code: Some(1),
resolved_ports: Vec::new(),
}
}
}
})
}
/// Spawn a task to stop a single daemon
///
/// Similar to spawn_start_task, this allows parallel stopping of daemons
/// within the same dependency level.
fn spawn_stop_task(
ipc: Arc<Self>,
id: DaemonId,
) -> tokio::task::JoinHandle<(DaemonId, Result<()>)> {
tokio::spawn(async move {
let result = ipc.stop(id.clone()).await.map(|_| ());
(id, result)
})
}
/// Stop daemons by ID with dependency resolution
///
/// Handles:
/// - ID resolution (short ID to qualified ID based on current directory)
/// - Dependency resolution (stops dependents first, in reverse order)
/// - Ad-hoc daemon handling (no dependencies)
/// - Parallel execution within dependency levels
pub async fn stop_daemons(self: &Arc<Self>, ids: &[DaemonId]) -> Result<StopResult> {
// Get currently running daemons
let running_daemons: HashSet<DaemonId> = self
.active_daemons()
.await?
.iter()
.filter(|d| d.status.is_running() || d.status.is_waiting())
.map(|d| d.id.clone())
.collect();
// Filter to only running daemons
let requested_ids: Vec<DaemonId> = ids
.iter()
.filter(|id| {
if !running_daemons.contains(*id) {
warn!("Daemon {id} is not running");
false
} else {
true
}
})
.cloned()
.collect();
if requested_ids.is_empty() {
info!("No running daemons to stop");
return Ok(StopResult { any_failed: false });
}
let mut any_failed = false;
// Use shared reverse dependency ordering
let stop_levels = compute_reverse_stop_order(&requested_ids);
for level in stop_levels {
// Filter to only running daemons in this level
let to_stop: Vec<DaemonId> = level
.into_iter()
.filter(|id| running_daemons.contains(id))
.collect();
if to_stop.is_empty() {
continue;
}
// Stop all daemons in this level concurrently
let mut tasks = Vec::new();
for id in to_stop {
let task = Self::spawn_stop_task(self.clone(), id);
tasks.push(task);
}
// Wait for all stops in this level to complete
for task in tasks {
match task.await {
Ok((id, Ok(()))) => {
debug!("Successfully stopped daemon {id}");
}
Ok((id, Err(e))) => {
error!("Failed to stop daemon {id}: {e}");
any_failed = true;
}
Err(e) => {
error!("Stop task panicked: {e}");
any_failed = true;
}
}
}
}
Ok(StopResult { any_failed })
}
/// Run a one-off daemon (not from config)
pub async fn run_adhoc(
&self,
id: DaemonId,
cmd: Vec<String>,
dir: PathBuf,
opts: StartOptions,
) -> Result<RunResult> {
self.run(RunOptions {
id,
cmd,
shell_pid: opts.shell_pid,
force: opts.force,
dir: crate::config_types::Dir(dir),
retry: opts.retry.unwrap_or_default(),
ready_delay: opts.delay.or(Some(3)),
ready_output: opts.output,
ready_http: merge_ready_http_override(None, opts.http),
ready_port: opts.port,
ready_cmd: opts.cmd.clone(),
port: crate::config_types::PortConfig::from_parts(
opts.expected_port.unwrap_or_default(),
opts.auto_bump_port.unwrap_or_default(),
),
wait_ready: true,
mise: None,
slug: None,
proxy: None,
..RunOptions::default()
})
.await
}
}
/// Resolve the project base directory from a config file path.
///
/// For `.config/pitchfork.toml` and `.config/pitchfork.local.toml`, the project
/// directory is the grandparent (i.e. the directory containing `.config/`).
/// For all other config files, it is the parent directory.
pub fn resolve_config_base_dir(config_path: Option<&Path>) -> PathBuf {
config_path
.and_then(|p| {
if is_global_config(p) {
p.parent()
} else if is_dot_config_pitchfork(p) {
// .config/pitchfork.toml and .config/pitchfork.local.toml uses project directory (grandparent)
p.parent().and_then(|p| p.parent())
} else {
p.parent()
}
})
.map(|p| p.to_path_buf())
.unwrap_or_else(|| crate::env::CWD.to_path_buf())
}
/// Resolve the working directory for a daemon.
///
/// If `dir` is set in config, resolve it relative to the project base directory.
/// Otherwise, use the project base directory directly.
pub fn resolve_daemon_dir(dir: Option<&str>, config_path: Option<&Path>) -> PathBuf {
let base_dir = resolve_config_base_dir(config_path);
match dir {
Some(d) => base_dir.join(d),
None => base_dir,
}
}
#[cfg(test)]
mod tests {
use crate::env;
use super::*;
#[test]
fn http_override_preserves_configured_status_codes() {
let configured = Some(ReadyHttp {
url: "http://localhost:3000/original".to_string(),
status: vec![401],
});
let ready_http =
merge_ready_http_override(configured, Some("http://localhost:3000/health".to_string()))
.unwrap();
assert_eq!(ready_http.url, "http://localhost:3000/health");
assert_eq!(ready_http.status, vec![401]);
assert!(ready_http.accepts_status(401));
assert!(!ready_http.accepts_status(200));
}
#[test]
fn build_run_options_preserves_ready_http_status_for_cli_http_override() {
let id = DaemonId::try_new("project", "api").unwrap();
let daemon_config = PitchforkTomlDaemon {
run: "echo ready".to_string(),
ready_http: Some(ReadyHttp {
url: "http://localhost:3000/original".to_string(),
status: vec![401],
}),
..PitchforkTomlDaemon::default()
};
let opts = StartOptions {
http: Some("http://localhost:3000/health".to_string()),
..StartOptions::default()
};
let run_opts = build_run_options(&id, &daemon_config, &opts).unwrap();
let ready_http = run_opts.ready_http.unwrap();
assert_eq!(ready_http.url, "http://localhost:3000/health");
assert_eq!(ready_http.status, vec![401]);
}
#[test]
fn test_resolve_daemon_dir_none() {
// No dir set, config at /projects/myapp/pitchfork.toml -> /projects/myapp
let result = resolve_daemon_dir(None, Some(Path::new("/projects/myapp/pitchfork.toml")));
assert_eq!(result, PathBuf::from("/projects/myapp"));
}
#[test]
fn test_resolve_daemon_dir_relative() {
// Relative dir "frontend" from /projects/myapp/pitchfork.toml -> /projects/myapp/frontend
let result = resolve_daemon_dir(
Some("frontend"),
Some(Path::new("/projects/myapp/pitchfork.toml")),
);
assert_eq!(result, PathBuf::from("/projects/myapp/frontend"));
}
#[test]
fn test_resolve_daemon_dir_absolute() {
// Absolute dir overrides config path entirely
let result = resolve_daemon_dir(
Some("/opt/myapp"),
Some(Path::new("/projects/myapp/pitchfork.toml")),
);
assert_eq!(result, PathBuf::from("/opt/myapp"));
}
#[test]
fn test_resolve_daemon_dir_no_config_path() {
// No config path -> defaults to CWD
let result = resolve_daemon_dir(None, None);
assert_eq!(result, crate::env::CWD.to_path_buf());
}
#[test]
fn test_resolve_daemon_dir_relative_no_config_path() {
// Relative dir but no config path -> relative to CWD
let result = resolve_daemon_dir(Some("subdir"), None);
assert_eq!(result, crate::env::CWD.join("subdir"));
}
#[test]
fn test_resolve_daemon_dir_nested_relative() {
// Nested relative path
let result = resolve_daemon_dir(
Some("services/api"),
Some(Path::new("/projects/myapp/pitchfork.toml")),
);
assert_eq!(result, PathBuf::from("/projects/myapp/services/api"));
}
#[test]
fn test_resolve_daemon_dir_dot_config_none() {
// .config/pitchfork.toml should resolve to project directory (not .config)
let result = resolve_daemon_dir(
None,
Some(Path::new("/projects/myapp/.config/pitchfork.toml")),
);
assert_eq!(
result,
PathBuf::from("/projects/myapp"),
".config/pitchfork.toml should resolve to project dir"
);
}
#[test]
fn test_resolve_daemon_dir_dot_config_local_none() {
// .config/pitchfork.toml should resolve to project directory (not .config)
let result = resolve_daemon_dir(
None,
Some(Path::new("/projects/myapp/.config/pitchfork.local.toml")),
);
assert_eq!(
result,
PathBuf::from("/projects/myapp"),
".config/pitchfork.local.toml should resolve to project dir"
);
}
#[test]
fn test_resolve_daemon_dir_dot_config_relative() {
// Relative dir from .config/pitchfork.toml -> project dir + relative
let result = resolve_daemon_dir(
Some("frontend"),
Some(Path::new("/projects/myapp/.config/pitchfork.toml")),
);
assert_eq!(
result,
PathBuf::from("/projects/myapp/frontend"),
"Relative dir should resolve from project dir"
);
}
#[test]
fn test_resolve_daemon_dir_dot_config_local_relative() {
// Relative dir from .config/pitchfork.toml -> project dir + relative
let result = resolve_daemon_dir(
Some("frontend"),
Some(Path::new("/projects/myapp/.config/pitchfork.local.toml")),
);
assert_eq!(
result,
PathBuf::from("/projects/myapp/frontend"),
"Relative dir should resolve from project dir"
);
}
#[test]
fn test_resolve_daemon_dir_dot_config_absolute() {
// Absolute dir overrides project dir
let result = resolve_daemon_dir(
Some("/opt/service"),
Some(Path::new("/projects/myapp/.config/pitchfork.toml")),
);
assert_eq!(
result,
PathBuf::from("/opt/service"),
"Absolute dir should override project dir"
);
}
#[test]
fn test_resolve_daemon_dir_dot_config_local_absolute() {
// Absolute dir overrides project dir
let result = resolve_daemon_dir(
Some("/opt/service"),
Some(Path::new("/projects/myapp/.config/pitchfork.local.toml")),
);
assert_eq!(
result,
PathBuf::from("/opt/service"),
"Absolute dir should override project dir"
);
}
#[test]
fn test_resolve_daemon_dir_global_config_normal() {
// Global config (~/.config/pitchfork/config.toml) should use normal resolution (parent)
let global_path = env::PITCHFORK_GLOBAL_CONFIG_USER.as_path();
let result = resolve_daemon_dir(None, Some(global_path));
assert_eq!(
result,
global_path.parent().unwrap(),
"Global config should use parent directory"
);
}
}