/// <summary> /// Serializes the specified deinitions and events to a file. /// </summary> /// <param name="definitions">The definitions to serialize.</param> /// <param name="filename">The filename to serialize to.</param> public static void SerializeToFile(DefinitionCollection definitions, string filename) { var definitionFile = new DefinitionFile(definitions); string serialized = JsonSerializer.Serialize(definitionFile, JsonOptions); File.WriteAllText(filename, serialized); }
/// <summary> /// Deserializes all definitions and events from the specified directory. /// </summary> /// <param name="compiler">The condition compiler to use.</param> /// <param name="path">The path to the directory.</param> /// <returns>A tuple of definitions and events from the directory.</returns> public static DefinitionCollection DeserializeFromDirectory(IConditionCompiler compiler, string path) { List <BaseDefinition> defs = new List <BaseDefinition>(); foreach (string file in Directory.EnumerateFiles(path, "*.json", SearchOption.AllDirectories)) { string json = File.ReadAllText(file); DefinitionFile?deserializedFile = JsonSerializer.Deserialize <DefinitionFile>(json, JsonOptions); if (deserializedFile != null) { foreach (BaseDefinition eve in deserializedFile.AllDefinitions) { if (eve is ITopLevelDefinition toplevel) { toplevel.SourceFile = file; } defs.Add(eve); } } } var definitions = new DefinitionCollection(defs); definitions.Attach(compiler); return(definitions); }
/// <summary> /// Reserializes all definitions to files based on the SoureFile property. /// </summary> /// <param name="definitions">The definitions.</param> public static void ReserializeToFiles(DefinitionCollection definitions) { if (definitions.IsInheritanceCompiled) { throw new InvalidOperationException("Can not re-serialize after inheritance has been compiled."); } IEnumerable <IGrouping <string, ITopLevelDefinition> > byFile = definitions.AllDefinitions.OfType <ITopLevelDefinition>().GroupBy(d => d.SourceFile); // Alert early if any definition is invalid. IGrouping <string, ITopLevelDefinition>?unsetGroup = byFile.FirstOrDefault(x => x.Key.Equals(BaseDefinition.UnsetString)); if (unsetGroup != null) { throw new InvalidOperationException( $"The following definitions have unset source files: {string.Join(", ", unsetGroup.Select(d => d.DefinitionName))}"); } foreach (IGrouping <string, ITopLevelDefinition> file in byFile) { SerializeToFile(new DefinitionCollection(file.OfType <BaseDefinition>()), file.Key); } }
/// <summary> /// Initializes a new instance of the <see cref="DefinitionFile"/> class. /// </summary> /// <param name="definitions">The list of definitions.</param> public DefinitionFile(DefinitionCollection definitions) { this.AllDefinitions = definitions.AllDefinitions.ToList(); }