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 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
use convert_case::{Case, Casing};
use quick_xml::{events::*, reader::Reader, writer::Writer};
use semver::{BuildMetadata, Prerelease, Version};
use std::{
borrow::Cow,
collections::HashMap,
fmt, fs,
io::Cursor,
path::{Path, PathBuf},
str::FromStr,
};
use thiserror::Error;
#[cfg(test)]
// mod tests;
mod tests;
// Include Modules
mod impls;
pub use impls::*;
mod version_tools;
pub use version_tools::*;
/// Errors that can occur while parsing a ModInfo.xml file
#[derive(Debug, Error)]
pub enum ModinfoError {
#[error("I/O error occurred: {0}")]
IoError(std::io::Error),
#[error("Invalid version: {0}")]
InvalidVersion(lenient_semver_parser::Error<'static>),
#[error("File not found")]
FsNotFound,
#[error("No modinfo.xml found")]
NoModinfo,
#[error("No Author found in modinfo.xml")]
NoModinfoAuthor,
#[error("No Description found in modinfo.xml")]
NoModinfoDescription,
#[error("No Name found in modinfo.xml")]
NoModinfoName,
#[error("No Version found in modinfo.xml")]
NoModinfoVersion,
#[error("Unable to determine the version for modinfo.xml")]
NoModinfoValueVersion,
#[error("Unknown tag: {0}")]
UnknownTag(String),
#[error("Could not write modinfo.xml")]
WriteError,
#[error("Could not parse XML: {0}")]
XMLError(quick_xml::Error),
}
impl From<std::io::Error> for ModinfoError {
fn from(err: std::io::Error) -> Self {
ModinfoError::IoError(err)
}
}
impl From<quick_xml::Error> for ModinfoError {
fn from(err: quick_xml::Error) -> Self {
ModinfoError::XMLError(err)
}
}
impl From<lenient_semver_parser::Error<'static>> for ModinfoError {
fn from(err: lenient_semver_parser::Error<'static>) -> Self {
ModinfoError::InvalidVersion(err)
}
}
/// The version of the modinfo.xml file
///
/// For reference, here are the two formats:
///
/// V1:
/// ```xml
/// <ModInfo>
/// <Name value="SomeMod" />
/// <Description value="Mod to show format of ModInfo v1" />
/// <Author value="Name" />
/// <Version value="0.1.0" />
/// </ModInfo>
/// ```
///
/// V2:
/// ```xml
/// <?xml version="1.0" encoding="utf-8"?>
/// <xml>
/// <Name value="SomeMod" />
/// <DisplayName value="Official Mod Name" />
/// <Version value="0.1.0" />
/// <Description value="Mod to show format of ModInfo v2" />
/// <Author value="Name" />
/// <Website value="https://example.org" />
/// </xml>
/// ```
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum ModinfoVersion {
V1,
V2,
}
#[derive(Debug, PartialEq)]
struct ModinfoValueMeta {
version: ModinfoVersion,
path: PathBuf,
}
impl Default for ModinfoValueMeta {
fn default() -> Self {
ModinfoValueMeta {
version: ModinfoVersion::V2,
path: PathBuf::new(),
}
}
}
#[derive(Clone, Debug, Default, PartialEq)]
struct ModinfoValue {
value: Option<Cow<'static, str>>,
}
impl fmt::Display for ModinfoValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.value {
Some(ref value) => write!(f, "{}", value),
None => write!(f, ""),
}
}
}
#[derive(Clone, Debug, PartialEq)]
struct ModinfoValueVersion {
value: Version,
compat: Option<Cow<'static, str>>,
}
impl fmt::Display for ModinfoValueVersion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let version = &self.value.to_string();
let compat = match &self.compat {
Some(ref value) => value.to_string(),
None => String::new(),
};
if compat.is_empty() {
write!(f, "{}", version)
} else {
write!(f, "{} ({})", version, compat)
}
}
}
impl Default for ModinfoValueVersion {
fn default() -> Self {
ModinfoValueVersion {
value: Version::new(0, 1, 0),
compat: None,
}
}
}
/// The main struct for the library
///
/// # Fields
///
/// * `name` - the name of the modlet
/// * `display_name` - the display name of the modlet (v2 only)
/// * `version` - the version of the modlet
/// * `description` - the description of the modlet
/// * `author` - the author of the modlet
/// * `website` - the website of the modlet (v2 only)
///
/// Additionally, version supports an optional `compat` field which can be used to indicate the game's version for the compatibility string
///
/// # Example
///
/// ```rust
/// use modinfo::Modinfo;
/// use std::borrow::Cow;
///
/// let mut modinfo = Modinfo::new();
///
/// modinfo.set_version("0.1.0".to_owned());
/// modinfo.set_value_for("name", "SomeMod");
/// modinfo.set_value_for("display_name", "Some Mod");
/// modinfo.set_value_for("author", "Some Author");
/// modinfo.set_value_for("description", "Some Description");
/// modinfo.set_value_for("website", "https://example.org");
///
/// assert_eq!(modinfo.get_value_for("name"), Some(&Cow::from("SomeMod")));
/// assert_eq!(modinfo.get_value_for("display_name"), Some(&Cow::from("Some Mod")));
/// assert_eq!(modinfo.get_value_for("author"), Some(&Cow::from("Some Author")));
/// assert_eq!(modinfo.get_value_for("description"), Some(&Cow::from("Some Description")));
/// assert_eq!(modinfo.get_value_for("website"), Some(&Cow::from("https://example.org")));
/// assert_eq!(modinfo.get_version(), &semver::Version::new(0, 1, 0));
/// ```
///
#[derive(Debug, Default)]
pub struct Modinfo {
author: ModinfoValue,
description: ModinfoValue,
display_name: ModinfoValue,
name: ModinfoValue,
version: ModinfoValueVersion,
website: ModinfoValue,
meta: ModinfoValueMeta,
}
impl ToString for Modinfo {
fn to_string(&self) -> String {
let mut writer = Writer::new_with_indent(Cursor::new(Vec::new()), b' ', 2);
let is_v2 = ModinfoVersion::V2 == self.meta.version;
let root_str = match is_v2 {
true => String::from("xml"),
false => String::from("ModInfo"),
};
if is_v2 {
writer
.write_event(Event::Decl(BytesDecl::new("1.0", Some("UTF-8"), None)))
.unwrap();
}
writer
.write_event(Event::Start(BytesStart::new(&root_str)))
.unwrap();
// inject the attributes here
for field in [
"name",
"display_name",
"version",
"description",
"author",
"website",
] {
if !is_v2 && (field == "website" || field == "display_name") {
continue;
}
let field_name = field.to_owned().to_case(Case::Pascal);
let mut elem = BytesStart::new(field_name);
let value = match field {
"version" => self.get_version().to_string(),
_ => match self.get_value_for(field) {
Some(value) => value.to_string(),
None => String::new(),
},
};
elem.push_attribute(attributes::Attribute {
key: quick_xml::name::QName(b"value"),
value: Cow::from(value.clone().into_bytes()),
});
if field == "version" && self.version.compat.is_some() {
elem.push_attribute(attributes::Attribute {
key: quick_xml::name::QName(b"compat"),
value: Cow::from(self.version.compat.as_ref().unwrap().as_bytes()),
});
};
writer.write_event(Event::Empty(elem)).unwrap();
}
writer
.write_event(Event::End(BytesEnd::new(&root_str)))
.unwrap();
String::from_utf8(writer.into_inner().into_inner()).unwrap()
}
}
impl FromStr for Modinfo {
type Err = ModinfoError;
fn from_str(xml: &str) -> Result<Self, Self::Err> {
let mut modinfo = Modinfo::default();
let mut buf: Vec<u8> = Vec::new();
let mut reader = Reader::from_str(xml);
reader.trim_text(true);
loop {
match reader.read_event_into(&mut buf) {
Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e),
Ok(Event::Eof) => break,
// Root Element
Ok(Event::Start(e)) => {
modinfo.meta.version = match e.name().as_ref() {
b"xml" => ModinfoVersion::V2,
_ => ModinfoVersion::V1,
}
}
// Child Elements (because they have no children)
Ok(Event::Empty(e)) => {
let attributes = parse_attributes(e.attributes());
let value = attributes["value"].clone();
match e.name().as_ref() {
b"Author" => {
modinfo.author = ModinfoValue {
value: Some(value.into()),
}
}
b"Description" => {
modinfo.description = ModinfoValue {
value: Some(value.into()),
}
}
b"DisplayName" => {
modinfo.display_name = ModinfoValue {
value: Some(value.into()),
}
}
b"Name" => {
if modinfo.display_name.value.is_none() {
modinfo.display_name = ModinfoValue {
value: Some(value.clone().into()),
}
}
modinfo.name = ModinfoValue {
value: Some(value.into()),
}
}
b"Version" => {
let mut compat = None;
if attributes.contains_key("compat") {
compat = Some(attributes["compat"].clone().into());
}
modinfo.version = ModinfoValueVersion {
value: match lenient_semver::parse_into::<Version>(&value) {
Ok(result) => result.clone(),
Err(err) => lenient_semver::parse_into::<Version>(
format!("0.0.0+{}", err).as_ref(),
)
.unwrap(),
},
compat,
}
}
b"Website" => {
modinfo.website = ModinfoValue {
value: Some(value.into()),
}
}
_ => (),
}
}
Ok(_) => (),
}
buf.clear();
}
Ok(modinfo)
}
}
fn parse_attributes(input: attributes::Attributes) -> HashMap<String, String> {
let mut attributes = HashMap::new();
input.map(|a| a.unwrap()).for_each(|a| {
let key: String = String::from_utf8_lossy(a.key.as_ref()).to_lowercase();
let value = String::from_utf8(a.value.into_owned()).unwrap();
attributes.insert(key, value);
});
attributes
}
/// Parses a Modinfo.xml file and produces a Modinfo struct
///
/// It will auto-detect the version of the Modinfo.xml file (either V1 or V2)
///
/// # Arguments
///
/// * `file` - a Path-like object pointing to a ModInfo.xml file
///
/// # Returns
///
/// A `Result` containing either a `Modinfo` struct or a `ModinfoError`
///
/// ## Possible ModinfoError
///
/// * `ModinfoError::FsNotFound` - the file does not exist
/// * `ModinfoError::IoError` - an I/O error occurred
/// * `ModinfoError::NoModinfoAuthor` - no Author tag found (required)
/// * `ModinfoError::NoModinfoDescription` - no Description tag found (required)
/// * `ModinfoError::NoModinfoName` - no Name tag found (required)
/// * `ModinfoError::NoModinfoVersion` - no Version value found (required)
/// * `ModinfoError::XMLError` - an error occurred while trying to parse the XML (possibly invalid XML structure?)
///
pub fn parse(file: impl AsRef<Path>) -> Result<Modinfo, ModinfoError> {
let modinfo = match Path::try_exists(file.as_ref()) {
Ok(true) => Modinfo::from_str(fs::read_to_string(&file)?.as_ref()),
Ok(false) => return Err(ModinfoError::FsNotFound),
Err(err) => return Err(ModinfoError::IoError(err)),
};
match modinfo {
Ok(mut modinfo) => {
if modinfo.author.value.is_none() {
return Err(ModinfoError::NoModinfoAuthor);
}
if modinfo.description.value.is_none() {
return Err(ModinfoError::NoModinfoDescription);
}
if modinfo.name.value.is_none() {
return Err(ModinfoError::NoModinfoName);
}
if modinfo.version.value.to_string().is_empty() {
return Err(ModinfoError::NoModinfoVersion);
}
// store the original file path in the metadata
modinfo.meta.path = file.as_ref().to_path_buf();
Ok(modinfo)
}
Err(err) => Err(err),
}
}