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
/// Core packages that are built into the binary
mod core;
/// Package evaluation functions
pub mod eval;
/// Registry used to store packages
pub mod reg;
/// Interacting with package repositories
pub mod repo;

use crate::io::files::paths::Paths;
use crate::net::download;
use mcvm_pkg::declarative::{deserialize_declarative_package, DeclarativePackage};
use mcvm_pkg::PackageContentType;
use mcvm_shared::later::Later;

use std::fs;
use std::path::PathBuf;

use self::core::get_core_package;
use anyhow::{anyhow, bail, Context};
use mcvm_parse::parse::{lex_and_parse, Parsed};
use mcvm_pkg::metadata::{eval_metadata, PackageMetadata};
use mcvm_pkg::properties::{eval_properties, PackageProperties};
use mcvm_shared::pkg::PackageID;
use reqwest::Client;

const PKG_EXTENSION: &str = ".pkg.txt";

/// An installable package that loads content into your game
#[derive(Debug)]
pub struct Package {
	/// The package ID
	pub id: PackageID,
	/// Where the package is being retrieved from
	pub location: PkgLocation,
	/// Type of the content in the package
	pub content_type: PackageContentType,
	/// The data of the package
	pub data: Later<PkgData>,
}

/// Location of a package
#[derive(Debug, Clone)]
pub enum PkgLocation {
	/// Contained on the local filesystem
	Local(PathBuf),
	/// Contained on an external repository
	Remote(Option<String>),
	/// Included in the binary
	Core,
}

/// Data pertaining to the contents of a package
#[derive(Debug)]
pub struct PkgData {
	text: String,
	contents: Later<PkgContents>,
	metadata: Later<PackageMetadata>,
	properties: Later<PackageProperties>,
}

impl PkgData {
	/// Create a new PkgData
	pub fn new(text: &str) -> Self {
		Self {
			text: text.to_owned(),
			contents: Later::new(),
			metadata: Later::new(),
			properties: Later::new(),
		}
	}

	/// Get the text content of the PkgData
	pub fn get_text(&self) -> String {
		self.text.clone()
	}
}

/// Type of data inside a package
#[derive(Debug)]
pub enum PkgContents {
	/// A package script
	Script(Parsed),
	/// A declarative package
	Declarative(Box<DeclarativePackage>),
}

impl PkgContents {
	/// Get the contents with an assertion that it is a script package
	pub fn get_script_contents(&self) -> &Parsed {
		if let Self::Script(parsed) = &self {
			parsed
		} else {
			panic!("Attempted to get script package contents from a non-script package");
		}
	}

	/// Get the contents with an assertion that it is a declarative package
	pub fn get_declarative_contents(&self) -> &DeclarativePackage {
		if let Self::Declarative(contents) = &self {
			contents
		} else {
			panic!("Attempted to get declarative package contents from a non-declarative package");
		}
	}
}

impl Package {
	/// Create a new Package
	pub fn new(id: PackageID, location: PkgLocation, content_type: PackageContentType) -> Self {
		Self {
			id,
			location,
			data: Later::new(),
			content_type,
		}
	}

	/// Get the cached file name of the package
	pub fn filename(&self) -> String {
		format!("{}{PKG_EXTENSION}", self.id)
	}

	/// Get the cached path of the package
	pub fn cached_path(&self, paths: &Paths) -> PathBuf {
		let cache_dir = paths.project.cache_dir().join("pkg");
		cache_dir.join(self.filename())
	}

	/// Remove the cached package file
	pub fn remove_cached(&self, paths: &Paths) -> anyhow::Result<()> {
		let path = self.cached_path(paths);
		if path.exists() {
			fs::remove_file(path)?;
		}
		Ok(())
	}

	/// Ensure the raw contents of the package
	pub async fn ensure_loaded(
		&mut self,
		paths: &Paths,
		force: bool,
		client: &Client,
	) -> anyhow::Result<()> {
		if self.data.is_empty() {
			match &self.location {
				PkgLocation::Local(path) => {
					if !path.exists() {
						bail!("Local package path does not exist");
					}
					self.data
						.fill(PkgData::new(&tokio::fs::read_to_string(path).await?));
				}
				PkgLocation::Remote(url) => {
					let path = self.cached_path(paths);
					if !force && path.exists() {
						self.data
							.fill(PkgData::new(&tokio::fs::read_to_string(path).await?));
					} else {
						let url = url.as_ref().expect("URL for remote package missing");
						let text = download::text(url, client).await?;
						tokio::fs::write(&path, &text).await?;
						self.data.fill(PkgData::new(&text));
					}
				}
				PkgLocation::Core => {
					let contents = get_core_package(&self.id)
						.ok_or(anyhow!("Package is not a core package"))?;
					self.data.fill(PkgData::new(contents));
				}
			};
		}
		Ok(())
	}

	/// Parse the contents of the package
	pub async fn parse(&mut self, paths: &Paths, client: &Client) -> anyhow::Result<()> {
		self.ensure_loaded(paths, false, client).await?;
		let data = self.data.get_mut();
		if data.contents.is_full() {
			return Ok(());
		}

		match self.content_type {
			PackageContentType::Script => {
				let parsed = lex_and_parse(&data.get_text())?;
				data.contents.fill(PkgContents::Script(parsed));
			}
			PackageContentType::Declarative => {
				let contents = deserialize_declarative_package(&data.get_text())
					.context("Failed to deserialize declarative package")?;
				data.contents
					.fill(PkgContents::Declarative(Box::new(contents)));
			}
		}

		Ok(())
	}

	/// Get the metadata of the package
	pub async fn get_metadata<'a>(
		&'a mut self,
		paths: &Paths,
		client: &Client,
	) -> anyhow::Result<&'a PackageMetadata> {
		self.parse(paths, client).await.context("Failed to parse")?;
		let data = self.data.get_mut();
		match self.content_type {
			PackageContentType::Script => {
				let parsed = data.contents.get().get_script_contents();
				if data.metadata.is_empty() {
					let metadata = eval_metadata(parsed).context("Failed to evaluate metadata")?;
					data.metadata.fill(metadata);
				}
				Ok(data.metadata.get())
			}
			PackageContentType::Declarative => {
				let contents = data.contents.get().get_declarative_contents();
				Ok(&contents.meta)
			}
		}
	}

	/// Get the properties of the package
	pub async fn get_properties<'a>(
		&'a mut self,
		paths: &Paths,
		client: &Client,
	) -> anyhow::Result<&'a PackageProperties> {
		self.parse(paths, client).await.context("Failed to parse")?;
		let data = self.data.get_mut();
		match self.content_type {
			PackageContentType::Script => {
				let parsed = data.contents.get().get_script_contents();
				if data.properties.is_empty() {
					let properties =
						eval_properties(parsed).context("Failed to evaluate properties")?;
					data.properties.fill(properties);
				}
				Ok(data.properties.get())
			}
			PackageContentType::Declarative => {
				let contents = data.contents.get().get_declarative_contents();
				Ok(&contents.properties)
			}
		}
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn test_package_id() {
		let package = Package::new(
			PackageID::from("sodium"),
			PkgLocation::Remote(None),
			PackageContentType::Script,
		);
		assert_eq!(package.filename(), "sodium".to_string() + PKG_EXTENSION);

		let package = Package::new(
			PackageID::from("fabriclike-api"),
			PkgLocation::Remote(None),
			PackageContentType::Script,
		);
		assert_eq!(
			package.filename(),
			"fabriclike-api".to_string() + PKG_EXTENSION
		);
	}
}