using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using StardewModdingAPI.Toolkit.Serialization.Converters;
using StardewModdingAPI.Toolkit.Utilities;
namespace StardewModdingAPI.Toolkit.Serialization.Models
{
/// A manifest which describes a mod for SMAPI.
public class Manifest : IManifest
{
/*********
** Accessors
*********/
/// The mod name.
public string Name { get; }
/// A brief description of the mod.
public string Description { get; }
/// The mod author's name.
public string Author { get; }
/// The mod version.
public ISemanticVersion Version { get; }
/// The minimum SMAPI version required by this mod, if any.
public ISemanticVersion? MinimumApiVersion { get; }
/// The name of the DLL in the directory that has the Entry method. Mutually exclusive with .
public string? EntryDll { get; }
/// The mod which will read this as a content pack. Mutually exclusive with .
[JsonConverter(typeof(ManifestContentPackForConverter))]
public IManifestContentPackFor? ContentPackFor { get; }
/// The other mods that must be loaded before this mod.
[JsonConverter(typeof(ManifestDependencyArrayConverter))]
public IManifestDependency[] Dependencies { get; }
/// The namespaced mod IDs to query for updates (like Nexus:541).
public string[] UpdateKeys { get; private set; }
/// The unique mod ID.
public string UniqueID { get; }
/// Any manifest fields which didn't match a valid field.
[JsonExtensionData]
public IDictionary ExtraFields { get; } = new Dictionary();
/*********
** Public methods
*********/
/// Construct an instance for a transitional content pack.
/// The unique mod ID.
/// The mod name.
/// The mod author's name.
/// A brief description of the mod.
/// The mod version.
/// The modID which will read this as a content pack.
public Manifest(string uniqueID, string name, string author, string description, ISemanticVersion version, string? contentPackFor = null)
: this(
uniqueId: uniqueID,
name: name,
author: author,
description: description,
version: version,
minimumApiVersion: null,
entryDll: null,
contentPackFor: contentPackFor != null
? new ManifestContentPackFor(contentPackFor, null)
: null,
dependencies: null,
updateKeys: null
)
{ }
/// Construct an instance for a transitional content pack.
/// The unique mod ID.
/// The mod name.
/// The mod author's name.
/// A brief description of the mod.
/// The mod version.
/// The minimum SMAPI version required by this mod, if any.
/// The name of the DLL in the directory that has the Entry method. Mutually exclusive with .
/// The modID which will read this as a content pack.
/// The other mods that must be loaded before this mod.
/// The namespaced mod IDs to query for updates (like Nexus:541).
[JsonConstructor]
public Manifest(string uniqueId, string name, string author, string description, ISemanticVersion version, ISemanticVersion? minimumApiVersion, string? entryDll, IManifestContentPackFor? contentPackFor, IManifestDependency[]? dependencies, string[]? updateKeys)
{
this.UniqueID = this.NormalizeField(uniqueId);
this.Name = this.NormalizeField(name, replaceSquareBrackets: true);
this.Author = this.NormalizeField(author);
this.Description = this.NormalizeField(description);
this.Version = version;
this.MinimumApiVersion = minimumApiVersion;
this.EntryDll = this.NormalizeField(entryDll);
this.ContentPackFor = contentPackFor;
this.Dependencies = dependencies ?? Array.Empty();
this.UpdateKeys = updateKeys ?? Array.Empty();
}
/// Try to validate a manifest's fields. Fails if any invalid field is found.
/// The error message to display to the user.
/// Returns whether the manifest was validated successfully.
public bool TryValidate(out string error)
{
// validate DLL / content pack fields
bool hasDll = !string.IsNullOrWhiteSpace(this.EntryDll);
bool isContentPack = this.ContentPackFor != null;
// validate field presence
if (!hasDll && !isContentPack)
{
error = $"manifest has no {nameof(IManifest.EntryDll)} or {nameof(IManifest.ContentPackFor)} field; must specify one.";
return false;
}
if (hasDll && isContentPack)
{
error = $"manifest sets both {nameof(IManifest.EntryDll)} and {nameof(IManifest.ContentPackFor)}, which are mutually exclusive.";
return false;
}
// validate DLL filename format
if (hasDll && this.EntryDll!.Intersect(Path.GetInvalidFileNameChars()).Any())
{
error = $"manifest has invalid filename '{this.EntryDll}' for the EntryDLL field.";
return false;
}
// validate content pack ID
else if (isContentPack && string.IsNullOrWhiteSpace(this.ContentPackFor!.UniqueID))
{
error = $"manifest declares {nameof(IManifest.ContentPackFor)} without its required {nameof(IManifestContentPackFor.UniqueID)} field.";
return false;
}
// validate required fields
{
List missingFields = new List(3);
if (string.IsNullOrWhiteSpace(this.Name))
missingFields.Add(nameof(IManifest.Name));
if (this.Version == null || this.Version.ToString() == "0.0.0")
missingFields.Add(nameof(IManifest.Version));
if (string.IsNullOrWhiteSpace(this.UniqueID))
missingFields.Add(nameof(IManifest.UniqueID));
if (missingFields.Any())
{
error = $"manifest is missing required fields ({string.Join(", ", missingFields)}).";
return false;
}
}
// validate ID format
if (!PathUtilities.IsSlug(this.UniqueID))
{
error = "manifest specifies an invalid ID (IDs must only contain letters, numbers, underscores, periods, or hyphens).";
return false;
}
// validate dependencies
foreach (IManifestDependency? dependency in this.Dependencies)
{
// null dependency
if (dependency == null)
{
error = $"manifest has a null entry under {nameof(IManifest.Dependencies)}.";
return false;
}
// missing ID
if (string.IsNullOrWhiteSpace(dependency.UniqueID))
{
error = $"manifest has a {nameof(IManifest.Dependencies)} entry with no {nameof(IManifestDependency.UniqueID)} field.";
return false;
}
// invalid ID
if (!PathUtilities.IsSlug(dependency.UniqueID))
{
error = $"manifest has a {nameof(IManifest.Dependencies)} entry with an invalid {nameof(IManifestDependency.UniqueID)} field (IDs must only contain letters, numbers, underscores, periods, or hyphens).";
return false;
}
}
error = "";
return true;
}
/// Override the update keys loaded from the mod info.
/// The new update keys to set.
internal void OverrideUpdateKeys(params string[] updateKeys)
{
this.UpdateKeys = updateKeys;
}
/*********
** Private methods
*********/
/// Normalize a manifest field to strip newlines, trim whitespace, and optionally strip square brackets.
/// The input to strip.
/// Whether to replace square brackets with round ones. This is used in the mod name to avoid breaking the log format.
#if NET5_0_OR_GREATER
[return: NotNullIfNotNull("input")]
#endif
private string? NormalizeField(string? input, bool replaceSquareBrackets = false)
{
input = input?.Trim();
if (!string.IsNullOrEmpty(input))
{
StringBuilder? builder = null;
for (int i = 0; i < input.Length; i++)
{
switch (input[i])
{
case '\r':
case '\n':
builder ??= new StringBuilder(input);
builder[i] = ' ';
break;
case '[' when replaceSquareBrackets:
builder ??= new StringBuilder(input);
builder[i] = '(';
break;
case ']' when replaceSquareBrackets:
builder ??= new StringBuilder(input);
builder[i] = ')';
break;
}
}
if (builder != null)
input = builder.ToString();
}
return input;
}
}
}