elemental_core/launcher/
command.rs1use std::{collections::HashMap, path::PathBuf};
2
3use tokio::process::{Child, Command};
4
5use super::error::{Error, Result};
6use crate::runtime::distribution::Distribution;
7
8#[derive(Debug, Clone)]
9pub struct LaunchCommand {
10 pub runtime: Distribution,
11 pub jvm_arguments: Vec<String>,
12 pub main_class: String,
13 pub game_arguments: Vec<String>,
14 pub env: HashMap<String, String>,
15 pub cwd: Option<PathBuf>,
16}
17
18impl LaunchCommand {
19 pub fn new(
20 runtime: Distribution,
21 jvm_arguments: Vec<String>,
22 main_class: String,
23 game_arguments: Vec<String>,
24 ) -> Self {
25 Self {
26 runtime,
27 jvm_arguments,
28 main_class,
29 game_arguments,
30 env: HashMap::new(),
31 cwd: None,
32 }
33 }
34
35 pub fn runtime_executable(&self) -> PathBuf {
36 self.runtime.executable()
37 }
38
39 pub fn program(&self) -> PathBuf {
40 self.runtime
41 .executablew()
42 .unwrap_or_else(|| self.runtime.executable())
43 }
44
45 pub fn arguments(&self) -> Vec<String> {
46 let mut arguments = self.jvm_arguments.clone();
47 arguments.push(self.main_class.clone());
48 arguments.extend(self.game_arguments.clone());
49 arguments
50 }
51
52 pub fn add_jvm_argument(&mut self, argument: String) {
53 self.jvm_arguments.push(argument);
54 }
55
56 pub fn add_jvm_arguments(&mut self, arguments: Vec<String>) {
57 self.jvm_arguments.extend(arguments);
58 }
59
60 pub fn add_game_argument(&mut self, argument: String) {
61 self.game_arguments.push(argument);
62 }
63
64 pub fn add_game_arguments(&mut self, arguments: Vec<String>) {
65 self.game_arguments.extend(arguments);
66 }
67
68 pub fn with_cwd(mut self, cwd: PathBuf) -> Self {
69 self.cwd = Some(cwd);
70 self
71 }
72
73 pub fn with_env(mut self, key: String, value: String) -> Self {
74 self.env.insert(key, value);
75 self
76 }
77
78 pub fn spawn(&self) -> Result<Child> {
79 let program = self.program();
80 if program.as_os_str().is_empty() {
81 return Err(Error::EmptyExecutable);
82 }
83
84 let mut child = Command::new(&program);
85 child.args(self.arguments());
86
87 if let Some(cwd) = &self.cwd {
88 child.current_dir(cwd);
89 }
90
91 for (key, value) in &self.env {
92 child.env(key, value);
93 }
94
95 child
96 .spawn()
97 .map_err(|source| Error::Spawn { program, source })
98 }
99}