1#[cfg(feature = "run")]
6use std::collections::BTreeMap;
7#[cfg(feature = "run")]
8use std::ffi::OsString;
9#[cfg(feature = "run")]
10use std::io::{BufRead, BufReader, Read};
11#[cfg(feature = "run")]
12use std::path::{Path, PathBuf};
13#[cfg(feature = "run")]
14use std::process::{Child, ExitStatus};
15#[cfg(feature = "run")]
16use std::process::{Command, Stdio};
17#[cfg(feature = "run")]
18use std::sync::atomic::{AtomicBool, Ordering};
19#[cfg(feature = "run")]
20use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, SyncSender};
21#[cfg(feature = "run")]
22use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
23#[cfg(feature = "run")]
24use std::thread::JoinHandle;
25#[cfg(feature = "run")]
26use std::time::{Duration, Instant, SystemTime};
27
28#[cfg(feature = "run")]
29use super::history::OUTPUT_LIMIT;
30#[cfg(feature = "run")]
31use super::{CommandLine, Failure, PhpSettings};
32#[cfg(feature = "run")]
33use crate::program::command;
34
35#[cfg(feature = "run")]
37const TICK: Duration = Duration::from_millis(50);
38
39#[cfg(feature = "run")]
42const GRACE: Duration = Duration::from_millis(250);
43
44#[cfg(feature = "run")]
47const DETACH: Duration = Duration::from_secs(1);
48
49#[cfg(feature = "run")]
52const DRAIN: Duration = Duration::from_secs(10);
53
54#[cfg(feature = "run")]
56const STOP_GRACE: Duration = Duration::from_secs(3);
57
58#[cfg(feature = "run")]
63pub const STOP_WAIT: Duration = STOP_GRACE
64 .saturating_add(GRACE)
65 .saturating_add(DETACH)
66 .saturating_add(Duration::from_millis(500));
67
68#[cfg(feature = "run")]
71const KEEP: usize = 64 * 1024;
72
73#[cfg(feature = "run")]
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum Stream {
77 Out,
78 Err,
79}
80
81#[cfg(feature = "run")]
83#[derive(Debug, Clone, Default)]
84pub struct Runs {
85 running: Arc<Mutex<BTreeMap<PathBuf, String>>>,
87}
88
89#[cfg(feature = "run")]
90impl Runs {
91 pub fn new() -> Self {
92 Self::default()
93 }
94
95 pub fn start(
99 &self,
100 app: &Path,
101 php: &PhpSettings,
102 args: &[String],
103 limit: Duration,
104 ) -> Result<Run, StartError> {
105 self.start_with_input(app, php, args, limit, None)
106 }
107
108 pub fn start_with_input(
111 &self,
112 app: &Path,
113 php: &PhpSettings,
114 args: &[String],
115 limit: Duration,
116 input: Option<Vec<u8>>,
117 ) -> Result<Run, StartError> {
118 let label = label(args);
119 let folder = php.folder(app);
120 let line = {
121 let mut running = self.lock();
122 if let Some(command) = running.get(app) {
123 return Err(StartError::Busy {
124 command: command.clone(),
125 });
126 }
127 let runner = php.runner.as_ref().ok_or(StartError::NoRunner)?;
128 let words: Vec<&str> = args.iter().map(String::as_str).collect();
129 let line = CommandLine::artisan(runner, &words)
130 .ok_or(StartError::Failed(Failure::NoCommand))?;
131 if !folder.is_dir() {
132 return Err(StartError::Failed(Failure::NoFolder { folder }));
133 }
134 running.insert(app.to_owned(), label.clone());
135 line
136 };
137 let process = match Process::start(&line, &folder, input) {
138 Ok(process) => process,
139 Err(error) => {
140 self.lock().remove(app);
141 return Err(StartError::Failed(not_started(error, &line.program)));
142 }
143 };
144 let started = Instant::now();
145 let stop = Arc::new(AtomicBool::new(false));
146 let (sender, events) = mpsc::channel();
147 let owner = Owner {
148 process,
149 started,
150 limit,
151 stop: Arc::clone(&stop),
152 events: sender,
153 runs: self.clone(),
154 app: app.to_owned(),
155 };
156 std::thread::spawn(move || owner.run());
157 Ok(Run {
158 line,
159 label,
160 args: args.to_vec(),
161 started_at: SystemTime::now(),
162 started,
163 events,
164 stop,
165 })
166 }
167
168 pub fn running(&self, app: &Path) -> Option<String> {
170 self.lock().get(app).cloned()
171 }
172
173 fn lock(&self) -> MutexGuard<'_, BTreeMap<PathBuf, String>> {
174 self.running.lock().unwrap_or_else(PoisonError::into_inner)
175 }
176}
177
178#[cfg(feature = "run")]
180#[derive(Debug, Clone, PartialEq, Eq)]
181pub enum StartError {
182 Busy { command: String },
184 NoRunner,
186 Failed(Failure),
188}
189
190#[cfg(feature = "run")]
192#[derive(Debug)]
193pub struct Run {
194 pub line: CommandLine,
196 pub label: String,
198 pub args: Vec<String>,
200 pub started_at: SystemTime,
201 started: Instant,
202 events: Receiver<RunEvent>,
203 stop: Arc<AtomicBool>,
204}
205
206#[cfg(feature = "run")]
207impl Run {
208 pub fn stop(&self) {
210 self.stop.store(true, Ordering::Relaxed);
211 }
212
213 pub fn elapsed(&self) -> Duration {
215 self.started.elapsed()
216 }
217
218 pub fn events(&self) -> Vec<RunEvent> {
220 self.events.try_iter().collect()
221 }
222
223 pub fn wait(&self, deadline: Instant) -> Vec<RunEvent> {
227 let mut arrived = Vec::new();
228 loop {
229 let left = deadline.saturating_duration_since(Instant::now());
230 match self.events.recv_timeout(left) {
231 Ok(event) => {
232 let ended = matches!(event, RunEvent::Ended(_));
233 arrived.push(event);
234 if ended {
235 return arrived;
236 }
237 }
238 Err(RecvTimeoutError::Timeout | RecvTimeoutError::Disconnected) => {
239 return arrived;
240 }
241 }
242 }
243 }
244}
245
246#[cfg(feature = "run")]
248#[derive(Debug, Clone, PartialEq, Eq)]
249pub enum RunEvent {
250 Line {
253 stream: Stream,
254 text: String,
255 cut: bool,
256 },
257 Cut,
259 Ended(RunEnd),
261}
262
263#[cfg(feature = "run")]
265#[derive(Debug, Clone, Copy, PartialEq, Eq)]
266pub enum RunEnd {
267 Exited {
270 code: Option<i32>,
271 elapsed: Duration,
272 },
273 Stopped {
275 elapsed: Duration,
276 limit: Option<Duration>,
277 },
278}
279
280#[cfg(feature = "run")]
283pub fn stop_asks_first(args: &[String]) -> bool {
284 const ASK: [&str; 6] = [
285 "module:migrate",
286 "module:migrate-rollback",
287 "module:migrate-refresh",
288 "module:migrate-reset",
289 "module:migrate-fresh",
290 "module:seed",
291 ];
292 args.first()
293 .is_some_and(|word| ASK.contains(&word.as_str()))
294}
295
296#[cfg(feature = "run")]
299fn label(args: &[String]) -> String {
300 let line = CommandLine {
302 program: "artisan".into(),
303 args: args.to_vec(),
304 };
305 let shown = line.display();
306 shown
307 .strip_prefix("artisan")
308 .unwrap_or(&shown)
309 .trim_start()
310 .to_string()
311}
312
313#[cfg(feature = "run")]
315pub(crate) fn not_started(error: std::io::Error, program: &str) -> Failure {
316 if error.kind() == std::io::ErrorKind::NotFound {
317 Failure::NotFound {
318 program: program.to_owned(),
319 }
320 } else {
321 Failure::NotStarted {
322 program: program.to_owned(),
323 message: error.to_string(),
324 }
325 }
326}
327
328#[cfg(feature = "run")]
330struct Owner {
331 process: Process,
332 started: Instant,
333 limit: Duration,
334 stop: Arc<AtomicBool>,
335 events: Sender<RunEvent>,
336 runs: Runs,
337 app: PathBuf,
338}
339
340#[cfg(feature = "run")]
341impl Owner {
342 fn run(self) {
346 let Owner {
347 mut process,
348 started,
349 limit,
350 stop,
351 events,
352 runs,
353 app,
354 } = self;
355 let mut sent = 0;
356 let mut cut = false;
357 let mut forward = |stream, text: String, line_cut| {
358 if cut {
359 return;
360 }
361 sent += text.len() + 1;
362 if sent > OUTPUT_LIMIT {
363 cut = true;
364 let _ = events.send(RunEvent::Cut);
365 } else {
366 let _ = events.send(RunEvent::Line {
367 stream,
368 text,
369 cut: line_cut,
370 });
371 }
372 };
373 let mut ended = false;
376 let stopped = loop {
377 match process.exited() {
378 Ok(true) => break None,
379 Ok(false) => {}
380 Err(_) => {
381 process.stop(&mut forward);
382 ended = true;
383 break None;
384 }
385 }
386 let at_limit = started.elapsed() >= limit;
387 if at_limit || stop.load(Ordering::Relaxed) {
388 process.stop(&mut forward);
389 ended = true;
390 break Some(at_limit.then_some(limit));
391 }
392 process.read(TICK, &mut forward);
393 };
394 let elapsed = started.elapsed();
395 let (status, late) = process.finish(ended, &stop, &mut forward);
396 let end = match stopped {
397 Some(limit) => RunEnd::Stopped { elapsed, limit },
398 None if late => RunEnd::Stopped {
399 elapsed: started.elapsed(),
400 limit: None,
401 },
402 None => RunEnd::Exited {
403 code: status.and_then(|status| status.code()),
404 elapsed,
405 },
406 };
407 runs.lock().remove(&app);
408 let _ = events.send(RunEvent::Ended(end));
409 }
410}
411
412#[cfg(feature = "run")]
415const QUEUE: usize = 1024;
416
417#[cfg(feature = "run")]
419struct Process {
420 child: Child,
421 lines: Receiver<(Stream, String, bool)>,
422 readers: Vec<JoinHandle<()>>,
423}
424
425#[cfg(feature = "run")]
426impl Process {
427 fn start(line: &CommandLine, folder: &Path, input: Option<Vec<u8>>) -> std::io::Result<Self> {
430 let mut command = prepare(line, folder)?;
431 if input.is_some() {
432 command.stdin(Stdio::piped());
433 }
434 #[cfg(unix)]
436 {
437 use std::os::unix::process::CommandExt;
438 command.process_group(0);
439 }
440 let mut child = command.spawn()?;
441 if let (Some(input), Some(mut stdin)) = (input, child.stdin.take()) {
444 std::thread::spawn(move || {
445 use std::io::Write;
446 let _ = stdin.write_all(&input);
447 });
448 }
449 let (sender, lines) = mpsc::sync_channel(QUEUE);
450 let readers = [
451 read_lines(child.stdout.take(), Stream::Out, sender.clone()),
452 read_lines(child.stderr.take(), Stream::Err, sender),
453 ];
454 Ok(Self {
455 child,
456 lines,
457 readers: readers.into_iter().flatten().collect(),
458 })
459 }
460
461 fn read(&self, wait: Duration, forward: &mut impl FnMut(Stream, String, bool)) -> bool {
465 match self.lines.recv_timeout(wait) {
466 Ok((stream, text, cut)) => forward(stream, text, cut),
467 Err(RecvTimeoutError::Timeout) => return false,
468 Err(RecvTimeoutError::Disconnected) => {
469 std::thread::sleep(wait);
470 return false;
471 }
472 }
473 for (stream, text, cut) in self.lines.try_iter().take(QUEUE) {
474 forward(stream, text, cut);
475 }
476 true
477 }
478
479 #[cfg(unix)]
482 fn exited(&mut self) -> std::io::Result<bool> {
483 use rustix::process::{Pid, WaitId, WaitIdOptions, waitid};
484 let options = WaitIdOptions::EXITED | WaitIdOptions::NOHANG | WaitIdOptions::NOWAIT;
485 let status = waitid(WaitId::Pid(Pid::from_child(&self.child)), options)?;
486 Ok(status.is_some())
487 }
488
489 #[cfg(not(unix))]
492 fn exited(&mut self) -> std::io::Result<bool> {
493 Ok(self.child.try_wait()?.is_some())
494 }
495
496 fn stop(&mut self, forward: &mut impl FnMut(Stream, String, bool)) {
499 self.terminate();
500 let asked = Instant::now();
501 while !self.exited().unwrap_or(true) {
502 if asked.elapsed() >= STOP_GRACE {
503 self.kill();
504 return;
505 }
506 self.read(TICK, forward);
507 }
508 }
509
510 #[cfg(unix)]
512 fn terminate(&mut self) {
513 self.signal(rustix::process::Signal::TERM);
514 }
515
516 #[cfg(unix)]
518 fn kill(&mut self) {
519 self.signal(rustix::process::Signal::KILL);
520 }
521
522 #[cfg(unix)]
525 fn signal(&mut self, signal: rustix::process::Signal) {
526 use rustix::process::{Pid, kill_process_group};
527 match kill_process_group(Pid::from_child(&self.child), signal) {
528 Ok(()) | Err(rustix::io::Errno::SRCH) => {}
529 Err(_) => {
530 let _ = self.child.kill();
531 }
532 }
533 }
534
535 #[cfg(not(unix))]
540 fn terminate(&mut self) {
541 let pid = self.child.id().to_string();
542 let ended = command("taskkill")
543 .args(["/PID", pid.as_str(), "/T", "/F"])
544 .stdout(Stdio::null())
545 .stderr(Stdio::null())
546 .status()
547 .is_ok_and(|status| status.success());
548 if !ended {
549 let _ = self.child.kill();
550 }
551 }
552
553 #[cfg(not(unix))]
555 fn kill(&mut self) {
556 let _ = self.child.kill();
557 }
558
559 fn finish(
579 &mut self,
580 stopped: bool,
581 stop: &AtomicBool,
582 forward: &mut impl FnMut(Stream, String, bool),
583 ) -> (Option<ExitStatus>, bool) {
584 let stopping = || stop.load(Ordering::Relaxed);
585 let mut done = self.wait_for_readers(GRACE, (!stopped).then_some(stop), forward);
586 let mut late = !stopped && stopping();
587 let status = if late {
588 let (status, rest_done) = self.stop_the_rest(done, forward);
589 done = rest_done;
590 status
591 } else {
592 #[cfg(unix)]
594 self.kill();
595 self.child.wait().ok()
596 };
597 if !done {
598 let watch = !stopped && !late;
599 done = self.wait_for_readers(DETACH, watch.then_some(stop), forward);
600 late |= watch && !done && stopping();
601 }
602 for reader in std::mem::take(&mut self.readers) {
603 if reader.is_finished() {
604 let _ = reader.join();
605 }
606 }
607 for (stream, text, cut) in self.lines.try_iter().take(QUEUE) {
609 forward(stream, text, cut);
610 }
611 (status, late)
612 }
613
614 fn stop_the_rest(
630 &mut self,
631 done: bool,
632 forward: &mut impl FnMut(Stream, String, bool),
633 ) -> (Option<ExitStatus>, bool) {
634 self.terminate();
635 #[cfg(unix)]
636 {
637 use rustix::process::{Pid, test_kill_process_group};
638 let asked = Instant::now();
639 let status = self.child.wait().ok();
640 let group = Pid::from_child(&self.child);
641 while test_kill_process_group(group).is_ok() {
642 if asked.elapsed() >= STOP_GRACE {
643 self.kill();
644 break;
645 }
646 self.read(TICK, forward);
648 }
649 let finished = self.readers.iter().all(JoinHandle::is_finished);
650 (status, done || finished)
651 }
652 #[cfg(not(unix))]
653 {
654 let done = done || self.wait_for_readers(STOP_GRACE, None, forward);
655 self.kill();
656 (self.child.wait().ok(), done)
657 }
658 }
659
660 fn wait_for_readers(
665 &self,
666 wait: Duration,
667 stop: Option<&AtomicBool>,
668 forward: &mut impl FnMut(Stream, String, bool),
669 ) -> bool {
670 let last = Instant::now() + DRAIN;
671 let mut until = Instant::now() + wait;
672 loop {
673 if self.readers.iter().all(JoinHandle::is_finished) {
674 return true;
675 }
676 if stop.is_some_and(|stop| stop.load(Ordering::Relaxed)) {
677 return false;
678 }
679 let left = until.saturating_duration_since(Instant::now());
680 if left.is_zero() {
681 return false;
682 }
683 if self.read(left.min(TICK), forward) && stop.is_some() {
684 until = (Instant::now() + wait).min(last);
685 }
686 }
687 }
688}
689
690#[cfg(feature = "run")]
692#[derive(Debug, Default)]
693pub(crate) struct Captured {
694 pub code: Option<i32>,
696 pub stdout: Vec<String>,
697 pub stderr: Vec<String>,
698 pub timed_out: bool,
700}
701
702#[cfg(feature = "run")]
706pub(crate) fn capture(
707 line: &CommandLine,
708 folder: &Path,
709 limit: Duration,
710) -> std::io::Result<Captured> {
711 let mut process = Process::start(line, folder, None)?;
712 let started = Instant::now();
713 let mut stdout = Vec::new();
714 let mut stderr = Vec::new();
715 let mut kept = [0, 0];
716 let mut keep = |stream, text: String, _cut| {
717 let (kept, lines) = match stream {
718 Stream::Out => (&mut kept[0], &mut stdout),
719 Stream::Err => (&mut kept[1], &mut stderr),
720 };
721 if *kept + text.len() > KEEP {
723 *kept = KEEP + 1;
724 } else {
725 *kept += text.len() + 1;
726 lines.push(text);
727 }
728 };
729 let mut timed_out = false;
730 while !process.exited()? {
731 if started.elapsed() >= limit {
732 process.stop(&mut keep);
733 timed_out = true;
734 break;
735 }
736 process.read(TICK, &mut keep);
737 }
738 let (status, _) = process.finish(timed_out, &AtomicBool::new(false), &mut keep);
739 Ok(Captured {
740 code: status
741 .and_then(|status| status.code())
742 .filter(|_| !timed_out),
743 stdout,
744 stderr,
745 timed_out,
746 })
747}
748
749#[cfg(feature = "run")]
752fn prepare(line: &CommandLine, folder: &Path) -> std::io::Result<Command> {
753 let program = program_path(&line.program, folder);
754 if cfg!(windows) {
755 refuse_batch_with_percent(&program)?;
756 }
757 let mut command = command(program);
758 command
759 .args(&line.args)
760 .current_dir(folder)
761 .stdout(Stdio::piped())
762 .stderr(Stdio::piped());
763 let home = directories::BaseDirs::new().map(|dirs| dirs.home_dir().to_path_buf());
764 if let Some(path) = child_path(std::env::var_os("PATH"), home.as_deref()) {
765 command.env("PATH", path);
766 }
767 Ok(command)
768}
769
770#[cfg(feature = "run")]
775fn refuse_batch_with_percent(program: &Path) -> std::io::Result<()> {
776 let name = program.to_string_lossy();
777 let name = name.trim_end_matches(['.', ' ']).to_ascii_lowercase();
778 if (name.ends_with(".bat") || name.ends_with(".cmd")) && name.contains('%') {
779 return Err(std::io::Error::new(
780 std::io::ErrorKind::InvalidInput,
781 "the path of the batch file holds %, which cmd.exe would expand",
782 ));
783 }
784 Ok(())
785}
786
787#[cfg(feature = "run")]
791fn program_path(program: &str, folder: &Path) -> PathBuf {
792 let separators: &[char] = if cfg!(windows) { &['/', '\\'] } else { &['/'] };
793 if program.contains(separators) {
794 folder.join(program)
795 } else {
796 PathBuf::from(program)
797 }
798}
799
800#[cfg(feature = "run")]
803fn child_path(path: Option<OsString>, home: Option<&Path>) -> Option<OsString> {
804 let mut folders: Vec<PathBuf> = path.iter().flat_map(std::env::split_paths).collect();
805 folders.extend(extra_folders(home));
806 std::env::join_paths(folders).ok()
807}
808
809#[cfg(feature = "run")]
813fn extra_folders(home: Option<&Path>) -> Vec<PathBuf> {
814 let at_home = |folder: &str| home.map(|home| home.join(folder));
815 let folders = if cfg!(target_os = "macos") {
816 vec![
817 at_home("Library/Application Support/Herd/bin"),
818 Some("/opt/homebrew/bin".into()),
819 Some("/usr/local/bin".into()),
820 at_home(".docker/bin"),
821 ]
822 } else if cfg!(windows) {
823 vec![at_home(r".config\herd\bin")]
824 } else {
825 vec![Some("/usr/local/bin".into()), at_home(".local/bin")]
826 };
827 folders.into_iter().flatten().collect()
828}
829
830#[cfg(feature = "run")]
834fn read_lines(
835 pipe: Option<impl Read + Send + 'static>,
836 stream: Stream,
837 sender: SyncSender<(Stream, String, bool)>,
838) -> Option<JoinHandle<()>> {
839 let pipe = pipe?;
840 Some(std::thread::spawn(move || {
841 let mut reader = BufReader::new(pipe);
842 let mut bytes = Vec::new();
843 loop {
844 bytes.clear();
845 match reader
847 .by_ref()
848 .take(KEEP as u64)
849 .read_until(b'\n', &mut bytes)
850 {
851 Ok(0) | Err(_) => return,
852 Ok(_) => {}
853 }
854 let mut cut = false;
855 if bytes.last() == Some(&b'\n') {
856 bytes.pop();
857 } else if bytes.len() == KEEP {
858 cut = skip_line(&mut reader).unwrap_or(true);
860 }
861 if bytes.last() == Some(&b'\r') {
862 bytes.pop();
863 }
864 let text = String::from_utf8_lossy(&bytes).into_owned();
865 if sender.send((stream, text, cut)).is_err() {
866 return;
867 }
868 }
869 }))
870}
871
872#[cfg(feature = "run")]
875fn skip_line(reader: &mut impl BufRead) -> std::io::Result<bool> {
876 let mut dropped = false;
877 loop {
878 let buffer = match reader.fill_buf() {
879 Ok(buffer) => buffer,
880 Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
881 Err(error) => return Err(error),
882 };
883 if buffer.is_empty() {
884 return Ok(dropped);
885 }
886 let end = buffer.iter().position(|byte| *byte == b'\n');
887 let rest = &buffer[..end.unwrap_or(buffer.len())];
888 dropped |= rest.iter().any(|byte| *byte != b'\r');
889 match end {
890 Some(at) => {
891 reader.consume(at + 1);
892 return Ok(dropped);
893 }
894 None => {
895 let read = buffer.len();
896 reader.consume(read);
897 }
898 }
899 }
900}
901
902#[cfg(all(test, feature = "run"))]
903mod tests {
904 use super::*;
905
906 #[cfg(unix)]
909 fn exited_with_its_child(
910 script: &str,
911 folder: &Path,
912 ready: impl Fn(&Process, &[String]) -> bool,
913 ) -> (Process, Vec<String>) {
914 let line = CommandLine {
915 program: "/bin/sh".into(),
916 args: vec!["-c".into(), script.into()],
917 };
918 let mut process = Process::start(&line, folder, None).unwrap();
919 let mut lines = Vec::new();
920 let deadline = Instant::now() + Duration::from_secs(10);
921 while !(process.exited().unwrap() && ready(&process, &lines)) {
922 assert!(Instant::now() < deadline, "{lines:?}");
923 process.read(TICK, &mut |_, text, _| lines.push(text));
924 }
925 (process, lines)
926 }
927
928 #[cfg(unix)]
932 #[test]
933 fn a_stop_pending_when_the_readers_drain_asks_the_rest_to_end() {
934 let folder =
935 std::env::temp_dir().join(format!("mortise-pending-stop-{}", std::process::id()));
936 std::fs::create_dir_all(&folder).unwrap();
937 let pending = AtomicBool::new(true);
938
939 let (mut process, mut lines) = exited_with_its_child(
941 r#"(trap 'echo term; exit 0' TERM; while :; do echo tick; sleep 0.05; done) &"#,
942 &folder,
943 |_, lines| lines.iter().any(|line| line == "tick"),
944 );
945 let (_, late) = process.finish(false, &pending, &mut |_, text, _| lines.push(text));
946 assert!(late);
947 assert!(lines.iter().any(|line| line == "term"), "{lines:?}");
948
949 let (mut process, _) = exited_with_its_child(
952 r#"(trap 'touch term; exit 0' TERM; exec >&- 2>&-; touch ready; while :; do sleep 0.05; done) &"#,
953 &folder,
954 |process, _| {
955 folder.join("ready").exists() && process.readers.iter().all(JoinHandle::is_finished)
956 },
957 );
958 let asked = Instant::now();
959 let (_, late) = process.finish(false, &pending, &mut |_, _, _| {});
960 assert!(late);
961 assert!(asked.elapsed() < STOP_GRACE, "{:?}", asked.elapsed());
962 assert!(folder.join("term").exists());
963 let _ = std::fs::remove_dir_all(&folder);
964 }
965
966 #[test]
967 fn a_stop_of_a_migration_or_a_seed_asks_first() {
968 let words = |words: &[&str]| {
969 words
970 .iter()
971 .map(|word| word.to_string())
972 .collect::<Vec<_>>()
973 };
974 assert!(stop_asks_first(&words(&["module:migrate", "Blog"])));
975 assert!(stop_asks_first(&words(&["module:migrate-fresh"])));
976 assert!(stop_asks_first(&words(&["module:seed", "Blog"])));
977 assert!(!stop_asks_first(&words(&["module:make", "module:migrate"])));
978 assert!(!stop_asks_first(&words(&["migrate"])));
979 assert!(!stop_asks_first(&[]));
980 }
981
982 #[test]
983 fn a_program_with_a_separator_starts_in_the_folder() {
984 let folder = Path::new("/code/shop-api");
985 assert_eq!(program_path("php", folder), PathBuf::from("php"));
986 assert_eq!(
987 program_path("./vendor/bin/sail", folder),
988 folder.join("./vendor/bin/sail")
989 );
990 assert_eq!(
991 program_path("vendor/bin/sail", folder),
992 folder.join("vendor/bin/sail")
993 );
994 let windows = program_path(r"vendor\bin\sail", folder);
995 if cfg!(windows) {
996 assert_eq!(windows, folder.join(r"vendor\bin\sail"));
997 } else {
998 assert_eq!(windows, PathBuf::from(r"vendor\bin\sail"));
999 }
1000 let absolute = std::env::temp_dir().join("php");
1001 let absolute = absolute.to_str().unwrap();
1002 assert_eq!(program_path(absolute, folder), PathBuf::from(absolute));
1003 }
1004
1005 #[test]
1006 fn a_batch_file_with_percent_in_its_path_is_refused() {
1007 for program in [
1008 r"C:\100%\herd.bat",
1009 r"C:\%USERPROFILE%\herd.CMD",
1010 "%a%.Bat. ",
1011 ] {
1012 let error = refuse_batch_with_percent(Path::new(program)).unwrap_err();
1013 assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput, "{program}");
1014 }
1015 let refusal = std::io::Error::new(
1017 std::io::ErrorKind::InvalidInput,
1018 "batch file arguments are invalid",
1019 );
1020 assert_eq!(
1021 not_started(refusal, "herd.bat"),
1022 Failure::NotStarted {
1023 program: "herd.bat".to_owned(),
1024 message: "batch file arguments are invalid".to_owned(),
1025 }
1026 );
1027 for program in [r"C:\100%\php.exe", r"C:\herd\herd.bat", "herd.bat"] {
1028 assert!(
1029 refuse_batch_with_percent(Path::new(program)).is_ok(),
1030 "{program}"
1031 );
1032 }
1033 }
1034
1035 #[test]
1036 fn the_path_of_mortise_comes_first() {
1037 let home = Path::new("/home/ada");
1038 let path = std::env::join_paths(["/usr/bin", "/bin"]).unwrap();
1039 let joined = child_path(Some(path), Some(home)).unwrap();
1040 let folders: Vec<PathBuf> = std::env::split_paths(&joined).collect();
1041 assert_eq!(
1042 folders[..2],
1043 [PathBuf::from("/usr/bin"), PathBuf::from("/bin")]
1044 );
1045 assert_eq!(folders[2..], extra_folders(Some(home)));
1046 assert!(folders.iter().any(|folder| folder.starts_with(home)));
1047 }
1048}