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
use std::fmt::Display;
use std::sync::Arc;

use anyhow::{bail, ensure};
use mcvm_pkg::properties::PackageProperties;
use mcvm_pkg::PackageContentType;
use mcvm_shared::pkg::{is_valid_package_id, ArcPkgReq, PackageID, PackageStability};
use mcvm_shared::util::is_valid_identifier;
use serde::{Deserialize, Serialize};

use crate::package::eval::EvalPermissions;
use mcvm_pkg::{PkgRequest, PkgRequestSource};

/// Different representations for the configuration of a package
#[derive(Deserialize, Serialize, Clone, Debug)]
#[serde(untagged)]
pub enum PackageConfig {
	/// Basic configuration for a repository package with just the package ID
	Basic(PackageID),
	/// Full configuration for a package
	Full(FullPackageConfig),
}

/// Full configuration for a package
#[derive(Deserialize, Serialize, Clone, Debug)]
#[serde(untagged)]
#[serde(rename_all = "snake_case")]
pub enum FullPackageConfig {
	/// Config for a local package
	Local {
		/// The type of the package
		r#type: PackageType,
		/// The ID of the pcakage
		id: PackageID,
		/// The package's content type
		#[serde(default)]
		content_type: PackageContentType,
		/// The path to the local package
		path: String,
		/// The package's enabled features
		#[serde(default)]
		features: Vec<String>,
		/// Whether or not to use the package's default features
		#[serde(default = "use_default_features_default")]
		use_default_features: bool,
		/// Permissions for the package
		#[serde(default)]
		permissions: EvalPermissions,
		/// Expected stability for the package
		#[serde(default)]
		stability: Option<PackageStability>,
	},
	/// Config for a repository package
	Repository {
		/// The ID of the pcakage
		id: PackageID,
		#[serde(default)]
		/// The package's enabled features
		features: Vec<String>,
		/// Whether or not to use the package's default features
		#[serde(default = "use_default_features_default")]
		use_default_features: bool,
		/// Permissions for the package
		#[serde(default)]
		permissions: EvalPermissions,
		/// Expected stability for the package
		#[serde(default)]
		stability: Option<PackageStability>,
	},
}

/// Trick enum used to make deserialization work in the way we want
#[derive(Deserialize, Serialize, Clone, Debug)]
#[serde(rename_all = "snake_case")]
pub enum PackageType {
	/// Yeah this is kinda stupid
	Local,
}

/// Default value for use_default_features
fn use_default_features_default() -> bool {
	true
}

impl Display for PackageConfig {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(
			f,
			"{}",
			match self {
				Self::Basic(id) => id,
				Self::Full(FullPackageConfig::Local { id, .. }) => id,
				Self::Full(FullPackageConfig::Repository { id, .. }) => id,
			}
		)
	}
}

impl PackageConfig {
	/// Get the package ID of the config
	pub fn get_pkg_id(&self) -> PackageID {
		match &self {
			Self::Basic(id) => id.clone(),
			Self::Full(cfg) => match cfg {
				FullPackageConfig::Local { id, .. } => id.clone(),
				FullPackageConfig::Repository { id, .. } => id.clone(),
			},
		}
	}

	/// Get the request of the config
	pub fn get_request(&self) -> ArcPkgReq {
		let id = self.get_pkg_id();
		Arc::new(PkgRequest::new(id.clone(), PkgRequestSource::UserRequire))
	}

	/// Get the features of the config
	pub fn get_features(&self) -> Vec<String> {
		match &self {
			Self::Basic(..) => Vec::new(),
			Self::Full(cfg) => match cfg {
				FullPackageConfig::Local { features, .. } => features.clone(),
				FullPackageConfig::Repository { features, .. } => features.clone(),
			},
		}
	}

	/// Get the use_default_features option of the config
	pub fn get_use_default_features(&self) -> bool {
		match &self {
			Self::Basic(..) => use_default_features_default(),
			Self::Full(cfg) => match cfg {
				FullPackageConfig::Local {
					use_default_features,
					..
				} => *use_default_features,
				FullPackageConfig::Repository {
					use_default_features,
					..
				} => *use_default_features,
			},
		}
	}

	/// Get the permissions of the config
	pub fn get_permissions(&self) -> EvalPermissions {
		match &self {
			Self::Basic(..) => EvalPermissions::Standard,
			Self::Full(cfg) => match cfg {
				FullPackageConfig::Local { permissions, .. } => *permissions,
				FullPackageConfig::Repository { permissions, .. } => *permissions,
			},
		}
	}

	/// Get the stability of the config
	pub fn get_stability(&self, profile_stability: PackageStability) -> PackageStability {
		match &self {
			Self::Basic(..) => profile_stability,
			Self::Full(cfg) => match cfg {
				FullPackageConfig::Local { stability, .. } => {
					stability.unwrap_or(profile_stability)
				}
				FullPackageConfig::Repository { stability, .. } => {
					stability.unwrap_or(profile_stability)
				}
			},
		}
	}

	/// Calculate the features of the config
	pub fn calculate_features(
		&self,
		properties: &PackageProperties,
	) -> anyhow::Result<Vec<String>> {
		let allowed_features = properties.features.clone().unwrap_or_default();
		let default_features = properties.default_features.clone().unwrap_or_default();

		let features = self.get_features();
		for feature in &features {
			ensure!(
				allowed_features.contains(feature),
				"Configured feature '{feature}' does not exist"
			);
		}

		let mut out = Vec::new();
		if self.get_use_default_features() {
			out.extend(default_features);
		}
		out.extend(features);

		Ok(out)
	}

	/// Validate this config
	pub fn validate(&self) -> anyhow::Result<()> {
		let id = self.get_pkg_id();
		if !is_valid_package_id(&id) {
			bail!("Invalid package ID '{id}'");
		}

		for feature in self.get_features() {
			if !is_valid_identifier(&feature) {
				bail!("Invalid string '{feature}'");
			}
		}

		Ok(())
	}
}