using Newtonsoft.Json; using System; using System.IO; namespace TShockAPI.Configuration { /// /// Implements to provide a generic config file containing some settings /// /// public class ConfigFile : IConfigFile where TSettings : new() { /// /// Settings managed by this config file /// public virtual TSettings Settings { get; set; } = new TSettings(); /// /// Action invoked when the config file is read /// public static Action> OnConfigRead; /// /// Reads json-formatted settings from a given path. /// If the given path does not exist is set to /// and a default object is returned /// /// The path to the file containing the settings /// /// Whether the config object has any new fields in it, meaning that the config file should be /// overwritten. /// /// Settings object public virtual TSettings Read(string path, out bool incompleteSettings) { if (!File.Exists(path)) { incompleteSettings = true; return default; } using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { return Read(fs, out incompleteSettings); } } /// /// Reads json-formatted settings from a given stream /// /// stream /// /// Whether the config object has any new fields in it, meaning that the config file has to be /// overwritten. /// /// Settings object public virtual TSettings Read(Stream stream, out bool incompleteSettings) { using (var sr = new StreamReader(stream)) { return ConvertJson(sr.ReadToEnd(), out incompleteSettings); } } /// /// Converts a json-formatted string into the settings object used by this configuration. Invokes the hook /// /// Json string to parse /// Whether or not the json string contained an incomplete set of settings /// Settings object public virtual TSettings ConvertJson(string json, out bool incompleteSettings) { var settings = FileTools.LoadConfigAndCheckForChanges(json, out incompleteSettings); Settings = settings; OnConfigRead?.Invoke(this); return settings; } /// /// Writes the configuration to a given path /// /// The file path the configuration file will be written to public virtual void Write(string path) { using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Write)) { Write(fs); } } /// /// Writes the configuration to a stream /// /// stream public virtual void Write(Stream stream) { var str = JsonConvert.SerializeObject(this, Formatting.Indented); using (var sw = new StreamWriter(stream)) { sw.Write(str); } } } }