Skip to content

Commit d20f703

Browse files
committed
feat: initial commit
0 parents  commit d20f703

6 files changed

Lines changed: 681 additions & 0 deletions

File tree

.gitignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
/target
2+
/.vscode
3+
4+
Cargo.lock

Cargo.toml

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
[package]
2+
name = "cargo-msfs"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
[dependencies]
7+
anyhow = "1.0.91"
8+
cab = "0.6.0"
9+
cargo_metadata = "0.18.1"
10+
clap = { version = "4.5.20", features = ["derive"] }
11+
console = "0.15.8"
12+
directories = "5.0.1"
13+
indicatif = "0.17.8"
14+
msi = { git = "https://github.com/pepperoni505/rust-msi" } # TODO: put this back to normal msi crate after PR is merged
15+
reqwest = { version = "0.12.8", features = ["blocking"] }
16+
serde = { version = "1.0.213", features = ["derive"] }
17+
serde_json = "1.0.132"
18+
zip = "2.2.0"

LICENSE.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Copyright 2024 Navigraph
2+
3+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4+
5+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6+
7+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

README.md

Whitespace-only changes.

src/main.rs

Lines changed: 261 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,261 @@
1+
use std::{
2+
io::BufReader,
3+
path::PathBuf,
4+
process::{Command, Stdio},
5+
time::Duration,
6+
};
7+
8+
use anyhow::{Context, Result};
9+
use cargo_metadata::Message;
10+
use clap::{builder::ArgPredicate, Parser, ValueEnum};
11+
use console::style;
12+
use directories::ProjectDirs;
13+
use indicatif::{ProgressBar, ProgressStyle};
14+
use sdk::{
15+
get_installed_sdk_version, get_latest_sdk_release, get_latest_sdk_version, get_sdk_path,
16+
get_wasi_sysroot_path, install_latest_sdk, remove_sdk_version,
17+
};
18+
19+
/// SDK info and download utility
20+
mod sdk;
21+
22+
/// A specific version of MSFS
23+
#[derive(Debug, PartialEq, Eq, Clone, Copy, ValueEnum)]
24+
enum SimulatorVersion {
25+
Msfs2020,
26+
Msfs2024,
27+
}
28+
29+
#[derive(Debug, Clone, Copy, ValueEnum)]
30+
enum CommandType {
31+
/// Installs the SDK for a specified MSFS version
32+
Install,
33+
/// Removes the SDK for a specified MSFS version
34+
Remove,
35+
/// Updates the SDK for a specified MSFS version
36+
Update,
37+
/// Builds a crate for a specified MSFS version
38+
Build,
39+
/// Gets info on installed SDKs
40+
Info,
41+
}
42+
43+
#[derive(Debug, Parser)]
44+
struct Args {
45+
/// The command to run
46+
#[arg(value_enum)]
47+
command: CommandType,
48+
/// The version of MSFS to run for. This is optional if the command type is info
49+
#[arg(value_enum, required_if_eq_any([
50+
("command", "install"),
51+
("command", "remove"),
52+
("command", "update"),
53+
("command", "build"),
54+
]))]
55+
msfs_version: Option<SimulatorVersion>,
56+
}
57+
58+
/// Formats a string containing the installed SDK version of a given sim
59+
///
60+
/// Example: `MSFS2024 SDK version X.X.X is installed` or `MSFS 2024 SDK is not installed`
61+
///
62+
/// * `simulator_version` - The simulator version to format for
63+
fn format_version_string(simulator_version: SimulatorVersion) -> Result<String> {
64+
let root_string = format!(
65+
"MSFS {} SDK",
66+
if simulator_version == SimulatorVersion::Msfs2020 {
67+
"2020"
68+
} else {
69+
"2024"
70+
}
71+
);
72+
73+
if let Some(installed_version) = get_installed_sdk_version(simulator_version)? {
74+
Ok(format!(
75+
"{} version {} is installed, latest available version is {}",
76+
root_string,
77+
style(installed_version).bold(),
78+
style(get_latest_sdk_version(simulator_version)?).bold()
79+
))
80+
} else {
81+
Ok(format!("{} is not installed", root_string))
82+
}
83+
}
84+
85+
/// Gets the directory that can be used for data
86+
fn get_data_dir() -> Result<PathBuf> {
87+
Ok(ProjectDirs::from("", "", "cargo-msfs")
88+
.context("could not get project dir")?
89+
.data_dir()
90+
.to_path_buf())
91+
}
92+
93+
/// Logs info
94+
fn print_info(message: &str) {
95+
println!("{} {}", style("[INFO]").cyan(), message);
96+
}
97+
98+
/// Logs success
99+
fn print_success(message: &str) {
100+
println!("{} {}", style("[SUCCESS]").green(), message);
101+
}
102+
103+
/// Logs a step
104+
fn print_step(step_number: u8, num_steps: u8, message: &str) {
105+
if step_number == num_steps {
106+
println!("{} {}", style("{step_number}/{num_steps}").green(), message);
107+
} else {
108+
println!(
109+
"{} {}",
110+
style("{step_number}/{num_steps}").yellow(),
111+
message
112+
);
113+
}
114+
}
115+
116+
fn main() -> Result<()> {
117+
let args = Args::parse();
118+
119+
match args.command {
120+
CommandType::Install => {
121+
let sim_version = args.msfs_version.context("msfs version is not present")?;
122+
let installed_version = get_installed_sdk_version(sim_version)?;
123+
if installed_version.is_some() {
124+
print_info("SDK for simulator version is already installed. To update it, run with the update command");
125+
return Ok(());
126+
}
127+
128+
print_info("Downloading and installing SDK...");
129+
// Create the progress bar. Since we won't know the full length until the callback, initialize with 0
130+
let progress_bar = ProgressBar::new(0);
131+
progress_bar.set_style(
132+
ProgressStyle::with_template(
133+
"{spinner:.green} [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} (ETA {eta})",
134+
)
135+
.unwrap()
136+
.progress_chars("#>-"),
137+
);
138+
progress_bar.enable_steady_tick(Duration::from_millis(100));
139+
install_latest_sdk(
140+
sim_version,
141+
Some(|downloaded, total| {
142+
if progress_bar.length() != Some(total) {
143+
progress_bar.set_length(total);
144+
}
145+
146+
progress_bar.set_position(downloaded);
147+
}),
148+
)?;
149+
print_success("SDK installed");
150+
}
151+
CommandType::Remove => {
152+
let sim_version = args.msfs_version.context("msfs version is not present")?;
153+
if get_sdk_path(sim_version)?.exists() {
154+
remove_sdk_version(sim_version)?;
155+
print_success("SDK deleted");
156+
} else {
157+
print_info("SDK is not installed, nothing to remove");
158+
}
159+
}
160+
CommandType::Update => {
161+
let sim_version = args.msfs_version.context("msfs version is not present")?;
162+
let latest_release = get_latest_sdk_version(sim_version)?;
163+
let installed_version = get_installed_sdk_version(sim_version)?;
164+
if installed_version == Some(latest_release) {
165+
print_info("Latest SDK is already installed");
166+
return Ok(());
167+
} else if installed_version.is_none() {
168+
print_info("SDK is not installed. To install it, run with the install command");
169+
return Ok(());
170+
}
171+
172+
print_info("Downloading and installing SDK...");
173+
// Create the progress bar. Since we won't know the full length until the callback, initialize with 0
174+
let progress_bar = ProgressBar::new(0);
175+
progress_bar.set_style(
176+
ProgressStyle::with_template(
177+
"{spinner:.green} [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} (ETA {eta})",
178+
)
179+
.unwrap()
180+
.progress_chars("#>-"),
181+
);
182+
progress_bar.enable_steady_tick(Duration::from_millis(100));
183+
install_latest_sdk(
184+
sim_version,
185+
Some(|downloaded, total| {
186+
if progress_bar.length() != Some(total) {
187+
progress_bar.set_length(total);
188+
}
189+
190+
progress_bar.set_position(downloaded);
191+
}),
192+
)?;
193+
print_success("SDK updated");
194+
}
195+
CommandType::Build => {
196+
let sim_version = args.msfs_version.context("msfs version is not present")?;
197+
let sdk_path = get_sdk_path(sim_version)?;
198+
let wasi_sysroot_path = get_wasi_sysroot_path(sim_version)?
199+
.as_os_str()
200+
.to_str()
201+
.context("couldn't convert osstr to str")?
202+
.to_string();
203+
let flags = [
204+
"-Cstrip=symbols",
205+
"-Clto",
206+
"-Ctarget-feature=-crt-static,+bulk-memory",
207+
"-Clink-self-contained=no",
208+
"-Clink-arg=-l",
209+
"-Clink-arg=c",
210+
&format!(
211+
"-Clink-arg={}\\lib\\wasm32-wasi\\libclang_rt.builtins-wasm32.a",
212+
wasi_sysroot_path
213+
),
214+
"-Clink-arg=-L",
215+
&format!(
216+
"-Clink-arg={}\\wasi-sysroot\\lib\\wasm32-wasi",
217+
wasi_sysroot_path
218+
),
219+
"-Clink-arg=--export-table",
220+
"-Clink-arg=--allow-undefined",
221+
"-Clink-arg=--export-dynamic",
222+
"-Clink-arg=--export=__wasm_call_ctors",
223+
"-Clink-arg=--export=malloc",
224+
"-Clink-arg=--export=free",
225+
"-Clink-arg=--export=mark_decommit_pages",
226+
"-Clink-arg=--export=mallinfo",
227+
"-Clink-arg=--export=mchunkit_begin",
228+
"-Clink-arg=--export=mchunkit_next",
229+
"-Clink-arg=--export=get_pages_state",
230+
];
231+
let mut command = Command::new("cargo")
232+
.args(&[
233+
"build",
234+
"--release",
235+
"--target",
236+
"wasm32-wasip1",
237+
// "--message-format=json",
238+
])
239+
.env("MSFS_SDK", sdk_path)
240+
.env("RUSTFLAGS", flags.join(" "))
241+
.env("CFLAGS", format!("--sysroot={}", wasi_sysroot_path))
242+
// .stdout(Stdio::piped())
243+
.spawn()?;
244+
// let reader = BufReader::new(command.stdout.take().context("couldn't take stdout")?);
245+
// for message in Message::parse_stream(reader) {
246+
// dbg!(message?);
247+
// }
248+
}
249+
250+
CommandType::Info => {
251+
if args.msfs_version == None || args.msfs_version == Some(SimulatorVersion::Msfs2020) {
252+
print_info(&format_version_string(SimulatorVersion::Msfs2020)?);
253+
}
254+
if args.msfs_version == None || args.msfs_version == Some(SimulatorVersion::Msfs2024) {
255+
print_info(&format_version_string(SimulatorVersion::Msfs2024)?);
256+
}
257+
}
258+
}
259+
260+
Ok(())
261+
}

0 commit comments

Comments
 (0)