public static void Run() { var pkg = new RantPackage(); var paths = GetPaths(); var outputPath = Property("out", Path.Combine( Directory.GetParent(Environment.CurrentDirectory).FullName, Path.GetFileName(Environment.CurrentDirectory) + ".rantpkg")); Console.WriteLine("Packing..."); if (paths.Length == 0) { Pack(pkg, Environment.CurrentDirectory); } else { foreach (var path in paths) { Pack(pkg, path); } } pkg.Save(outputPath); Console.WriteLine("\nPackage saved to " + outputPath); Console.ResetColor(); }
private static RantPackage LoadOldPackage(EasyReader reader) { int numPatterns = reader.ReadInt32(); int numTables = reader.ReadInt32(); if (numPatterns < 0 || numTables < 0) { throw new InvalidDataException("File is corrupt."); } var pkg = new RantPackage(); // Patterns for (int i = 0; i < numPatterns; i++) { var name = reader.ReadString(); var code = reader.ReadString(); pkg.AddPattern(new RantPattern(name, RantPatternOrigin.String, code)); } // Tables for (int i = 0; i < numTables; i++) { var name = reader.ReadString(); var subs = reader.ReadStringArray(); int numEntries = reader.ReadInt32(); var hiddenClasses = reader.ReadStringArray(); var entries = new RantDictionaryEntry[numEntries]; for (int j = 0; j < numEntries; j++) { int weight = reader.ReadInt32(); bool flags = reader.ReadBoolean(); // unused int numTerms = reader.ReadInt32(); var terms = new RantDictionaryTerm[numTerms]; for (int k = 0; k < numTerms; k++) { var value = reader.ReadString(); var pron = reader.ReadString(); terms[k] = new RantDictionaryTerm(value, pron); } var classes = reader.ReadStringArray(); entries[j] = new RantDictionaryEntry(terms, classes, weight); } pkg.AddTable(new RantDictionaryTable(name, subs, entries, hiddenClasses)); } return(pkg); }
/// <summary> /// Loads the specified package into the engine. /// </summary> /// <param name="package">The package to load.</param> /// <param name="mergeBehavior">The table merging strategy to employ.</param> public void LoadPackage(RantPackage package, TableMergeBehavior mergeBehavior = TableMergeBehavior.Naive) { if (package == null) { throw new ArgumentNullException(nameof(package)); } if (_loadedPackages.Contains(RantPackageDependency.Create(package))) { return; } var patterns = package.GetPatterns(); var tables = package.GetTables(); if (patterns.Any()) { foreach (var pattern in patterns) { _patternCache[pattern.Name] = pattern; if (pattern.Module != null) { PackageModules[pattern.Name] = pattern.Module; } } } if (tables.Any()) { if (_dictionary == null) { _dictionary = new RantDictionary(tables, mergeBehavior); } else { foreach (var table in tables) { _dictionary.AddTable(table, mergeBehavior); } } } _loadedPackages.Add(RantPackageDependency.Create(package)); foreach (var dependency in package.GetDependencies()) { RantPackage pkg; if (!_resolver.TryResolvePackage(dependency, out pkg)) { throw new FileNotFoundException($"Package '{package}' was unable to resolve dependency '{dependency}'"); } LoadPackage(pkg, mergeBehavior); } }
/// <summary> /// Loads the package at the specified file path into the engine. /// </summary> /// <param name="path">The path to the package to load.</param> public void LoadPackage(string path) { if (Util.IsNullOrWhiteSpace(path)) { throw new ArgumentException(GetString("err-empty-path")); } if (Util.IsNullOrWhiteSpace(Path.GetExtension(path))) { path += RantPackage.EXTENSION; } LoadPackage(RantPackage.Load(path)); }
/// <summary> /// Loads the package at the specified file path into the engine. /// </summary> /// <param name="path">The path to the package to load.</param> /// <param name="mergeBehavior">The table merging strategy to employ.</param> public void LoadPackage(string path, TableMergeBehavior mergeBehavior = TableMergeBehavior.Naive) { if (Util.IsNullOrWhiteSpace(path)) { throw new ArgumentException("Path cannot be null nor empty."); } if (Util.IsNullOrWhiteSpace(Path.GetExtension(path))) { path += ".rantpkg"; } LoadPackage(RantPackage.Load(path), mergeBehavior); }
/// <summary> /// Attempts to resolve a depdendency to the appropriate package. /// </summary> /// <param name="depdendency">The depdendency to resolve.</param> /// <param name="package">The package loaded from the depdendency.</param> /// <returns></returns> public virtual bool TryResolvePackage(RantPackageDependency depdendency, out RantPackage package) { package = null; var path = Path.Combine(Environment.CurrentDirectory, $"{depdendency.ID}.rantpkg"); if (!File.Exists(path)) { RantPackageVersion version; // Fallback to name with version appended #if UNITY path = Directory.GetFiles(Environment.CurrentDirectory, $"{depdendency.ID}*.rantpkg", SearchOption.AllDirectories).FirstOrDefault(p => #else path = Directory.EnumerateFiles(Environment.CurrentDirectory, "*.rantpkg", SearchOption.AllDirectories).FirstOrDefault(p => #endif { var match = FallbackRegex.Match(Path.GetFileNameWithoutExtension(p)); if (!match.Success) { return(false); } version = RantPackageVersion.Parse(match.Groups["version"].Value); return((depdendency.AllowNewer && version >= depdendency.Version) || depdendency.Version == version); }); if (path == null) { return(false); } } try { var pkg = RantPackage.Load(path); if (pkg.ID != depdendency.ID) { return(false); } if ((depdendency.AllowNewer && pkg.Version >= depdendency.Version) || pkg.Version == depdendency.Version) { package = pkg; return(true); } return(false); } catch { return(false); } }
private static void Pack(RantPackage package, string contentPath) { foreach (var path in Directory.GetFiles(contentPath, "*.rant", SearchOption.AllDirectories)) { Console.WriteLine("+ " + path); var pattern = RantPattern.FromFile(path); package.AddPattern(pattern); } foreach (var path in Directory.GetFiles(contentPath, "*.dic", SearchOption.AllDirectories)) { Console.WriteLine("+ " + path); var table = RantDictionaryTable.FromFile(path); package.AddTable(table); } }
static Resources() { if (!String.IsNullOrWhiteSpace(Config.Current.Package)) { try { Package = RantPackage.Load(Config.Current.Package); } catch (Exception ex) { C.WriteLine(ConsoleColor.Red, $"Failed to load package {Config.Current.Package}: {ex.Message}"); C.WriteLine("Using empty package"); } } else { Package = new RantPackage(); } }
/// <summary> /// Attempts to resolve a depdendency to the appropriate package. /// </summary> /// <param name="depdendency">The depdendency to resolve.</param> /// <param name="package">The package loaded from the depdendency.</param> /// <returns></returns> public virtual bool TryResolvePackage(RantPackageDependency depdendency, out RantPackage package) { package = null; var path = Path.Combine(Environment.CurrentDirectory, $"{depdendency.ID}.rantpkg"); if (!File.Exists(path)) { RantPackageVersion version; // Fallback to name with version appended #if UNITY path = Directory.GetFiles(Environment.CurrentDirectory, $"{depdendency.ID}*.rantpkg", SearchOption.AllDirectories).FirstOrDefault(p => #else path = Directory.EnumerateFiles(Environment.CurrentDirectory, "*.rantpkg", SearchOption.AllDirectories).FirstOrDefault(p => #endif { var match = FallbackRegex.Match(Path.GetFileNameWithoutExtension(p)); if (!match.Success) return false; version = RantPackageVersion.Parse(match.Groups["version"].Value); return (depdendency.AllowNewer && version >= depdendency.Version) || depdendency.Version == version; }); if (path == null) return false; } try { var pkg = RantPackage.Load(path); if (pkg.ID != depdendency.ID) return false; if ((depdendency.AllowNewer && pkg.Version >= depdendency.Version) || pkg.Version == depdendency.Version) { package = pkg; return true; } return false; } catch { return false; } }
public static void Run() { var pkg = new RantPackage(); var paths = GetPaths(); var compress = Property("compression", "true") == "true"; var stringTableMode = int.Parse(Property("string-table", "1")); if (stringTableMode < 0 || stringTableMode > 2) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Invalid string table mode."); Console.ResetColor(); return; } var modeEnum = (Rant.IO.Bson.BsonStringTableMode)stringTableMode; Console.WriteLine("Packing..."); var contentDir = Path.GetFullPath(paths.Length == 0 ? Environment.CurrentDirectory : paths[0]); Pack(pkg, contentDir); string outputPath; if (!Flag("old")) { var infoPath = Path.Combine(contentDir, "rantpkg.json"); if (!File.Exists(infoPath)) throw new FileNotFoundException("rantpkg.json missing from root directory."); var info = JsonConvert.DeserializeObject<PackInfo>(File.ReadAllText(infoPath)); pkg.Title = info.Title; pkg.Authors = info.Authors; pkg.Version = RantPackageVersion.Parse(!String.IsNullOrWhiteSpace(Property("version")) ? Property("version") : info.Version); pkg.Description = info.Description; pkg.ID = info.ID; pkg.Tags = info.Tags; foreach (var dep in info.Dependencies) { pkg.AddDependency(dep); } if (!String.IsNullOrWhiteSpace(info.OutputPath)) { outputPath = Path.Combine(contentDir, info.OutputPath, $"{pkg.ID}-{pkg.Version}.rantpkg"); Directory.CreateDirectory(Path.GetDirectoryName(outputPath)); } else { outputPath = Path.Combine(Directory.GetParent(contentDir).FullName, $"{pkg.ID}-{pkg.Version}.rantpkg"); } Console.WriteLine($"String table mode: {modeEnum}"); Console.WriteLine($"Compression: {(compress ? "yes" : "no")}"); Console.WriteLine(compress ? "Compressing and saving..." : "Saving..."); pkg.Save(outputPath, compress, modeEnum); } else { outputPath = Property("out", Path.Combine( Directory.GetParent(Environment.CurrentDirectory).FullName, Path.GetFileName(Environment.CurrentDirectory) + ".rantpkg")); Console.WriteLine("Saving..."); pkg.SaveOld(outputPath); } Console.WriteLine("\nPackage saved to " + outputPath); Console.ResetColor(); }
private static void Pack(RantPackage package, string contentPath) { foreach (var path in Directory.EnumerateFiles(contentPath, "*.*", SearchOption.AllDirectories) .Where(p => p.EndsWith(".rant") || p.EndsWith(".rants"))) { var pattern = RantPattern.FromFile(path); string relativePath; TryGetRelativePath(contentPath, path, out relativePath, true); pattern.Name = relativePath; package.AddPattern(pattern); Console.WriteLine("+ " + pattern.Name); } foreach (var path in Directory.GetFiles(contentPath, "*.dic", SearchOption.AllDirectories)) { Console.WriteLine("+ " + path); var table = RantDictionaryTable.FromFile(path); package.AddTable(table); } }
/// <summary> /// Loads the specified package into the engine. /// </summary> /// <param name="package">The package to load.</param> /// <param name="mergeBehavior">The table merging strategy to employ.</param> public void LoadPackage(RantPackage package, TableMergeBehavior mergeBehavior = TableMergeBehavior.Naive) { if (package == null) throw new ArgumentNullException(nameof(package)); if (_loadedPackages.Contains(RantPackageDependency.Create(package))) return; var patterns = package.GetPatterns(); var tables = package.GetTables(); if (patterns.Any()) { foreach (var pattern in patterns) { _patternCache[pattern.Name] = pattern; if (pattern.Module != null) PackageModules[pattern.Name] = pattern.Module; } } if (tables.Any()) { if (_dictionary == null) { _dictionary = new RantDictionary(tables, mergeBehavior); } else { foreach (var table in tables) { _dictionary.AddTable(table, mergeBehavior); } } } _loadedPackages.Add(RantPackageDependency.Create(package)); foreach (var dependency in package.GetDependencies()) { RantPackage pkg; if (!_resolver.TryResolvePackage(dependency, out pkg)) throw new FileNotFoundException($"Package '{package}' was unable to resolve dependency '{dependency}'"); LoadPackage(pkg, mergeBehavior); } }
/// <summary> /// Loads the specified package into the engine. /// </summary> /// <param name="package">The package to load.</param> /// <param name="mergeBehavior">The table merging strategy to employ.</param> public void LoadPackage(RantPackage package, TableMergeBehavior mergeBehavior = TableMergeBehavior.Naive) { if (package == null) throw new ArgumentNullException(nameof(package)); var patterns = package.GetPatterns(); var tables = package.GetTables(); if (patterns.Any()) { foreach (var pattern in patterns) _patternCache[pattern.Name] = pattern; } if (tables.Any()) { if (_dictionary == null) { _dictionary = new RantDictionary(tables, mergeBehavior); } else { foreach (var table in tables) { _dictionary.AddTable(table, mergeBehavior); } } } }
/// <summary> /// Loads a package from the specified stream and returns it as a RantPackage object. /// </summary> /// <param name="source">The stream to load the package data from.</param> /// <returns></returns> public static RantPackage Load(Stream source) { using (var reader = new EasyReader(source)) { var magic = Encoding.ASCII.GetString(reader.ReadBytes(4)); if (magic == OLD_MAGIC) return LoadOldPackage(reader); if (magic != MAGIC) throw new InvalidDataException("File is corrupt."); var package = new RantPackage(); var version = reader.ReadUInt32(); if (version != PACKAGE_VERSION) throw new InvalidDataException("Invalid package version: " + version); var compress = reader.ReadBoolean(); var size = reader.ReadInt32(); var data = reader.ReadBytes(size); if (compress) data = EasyCompressor.Decompress(data); var doc = BsonDocument.Read(data); var info = doc["info"]; if (info == null) throw new InvalidDataException("Metadata is missing from package."); package.Title = info["title"]; package.ID = info["id"]; package.Version = RantPackageVersion.Parse(info["version"]); package.Description = info["description"]; package.Authors = (string[])info["authors"]; package.Tags = (string[])info["tags"]; var deps = info["dependencies"]; if (deps != null && deps.IsArray) { for(int i = 0; i < deps.Count; i++) { var dep = deps[i]; var depId = dep["id"].Value; var depVersion = dep["version"].Value; bool depAllowNewer = (bool)dep["allow-newer"].Value; package.AddDependency(new RantPackageDependency(depId.ToString(), depVersion.ToString()) { AllowNewer = depAllowNewer }); } } var patterns = doc["patterns"]; if(patterns != null) { var names = patterns.Keys; foreach (string name in names) package.AddPattern(new RantPattern(name, RantPatternOrigin.File, patterns[name])); } var tables = doc["tables"]; if(tables != null) { var names = tables.Keys; foreach(string name in names) { var table = tables[name]; string tableName = table["name"]; string[] tableSubs = (string[])table["subs"]; string[] hiddenClasses = (string[])table["hidden"]; var entries = new List<RantDictionaryEntry>(); var entryList = table["entries"]; for(var i = 0; i < entryList.Count; i++) { var loadedEntry = entryList[i]; int weight = 1; if (loadedEntry.HasKey("weight")) weight = (int)loadedEntry["weight"].Value; string[] requiredClasses = (string[])loadedEntry["classes"]; string[] optionalClasses = (string[])loadedEntry["optional_classes"]; var terms = new List<RantDictionaryTerm>(); var termList = loadedEntry["terms"]; for(var j = 0; j < termList.Count; j++) { var t = new RantDictionaryTerm(termList[j]["value"], termList[j]["pron"]); terms.Add(t); } var entry = new RantDictionaryEntry( terms.ToArray(), requiredClasses.Concat(optionalClasses.Select(x => x + "?")), weight ); entries.Add(entry); } var rantTable = new RantDictionaryTable( tableName, tableSubs, entries, hiddenClasses ); package.AddTable(rantTable); } } return package; } }
/// <summary> /// Creates a dependency for the specified package. /// </summary> /// <param name="package">The package to create the dependency for.</param> /// <returns></returns> public static RantPackageDependency Create(RantPackage package) { if (Util.IsNullOrWhiteSpace(package.ID)) throw new ArgumentException("Package ID cannot be empty."); return new RantPackageDependency(package.ID, package.Version); }
/// <summary> /// Loads a package from the specified stream and returns it as a RantPackage object. /// </summary> /// <param name="source">The stream to load the package data from.</param> /// <returns></returns> public static RantPackage Load(Stream source) { using (var reader = new EasyReader(source)) { if (Encoding.ASCII.GetString(reader.ReadBytes(4)) != Magic) throw new InvalidDataException("File is corrupt."); int numPatterns = reader.ReadInt32(); int numTables = reader.ReadInt32(); if (numPatterns < 0 || numTables < 0) throw new InvalidDataException("File is corrupt."); var pkg = new RantPackage(); // Patterns for (int i = 0; i < numPatterns; i++) { var name = reader.ReadString(); var code = reader.ReadString(); pkg.AddPattern(new RantPattern(name, RantPatternSource.String, code)); } // Tables for (int i = 0; i < numTables; i++) { var name = reader.ReadString(); var subs = reader.ReadStringArray(); int numEntries = reader.ReadInt32(); var hiddenClasses = reader.ReadStringArray(); var entries = new RantDictionaryEntry[numEntries]; for (int j = 0; j < numEntries; j++) { int weight = reader.ReadInt32(); bool flags = reader.ReadBoolean(); // unused int numTerms = reader.ReadInt32(); var terms = new RantDictionaryTerm[numTerms]; for (int k = 0; k < numTerms; k++) { var value = reader.ReadString(); var pron = reader.ReadString(); terms[k] = new RantDictionaryTerm(value, pron); } var classes = reader.ReadStringArray(); entries[j] = new RantDictionaryEntry(terms, classes, weight); } pkg.AddTable(new RantDictionaryTable(name, subs, entries, hiddenClasses)); } return pkg; } }
/// <summary> /// Loads a package from the specified stream and returns it as a RantPackage object. /// </summary> /// <param name="source">The stream to load the package data from.</param> /// <returns></returns> public static RantPackage Load(Stream source) { using (var reader = new EasyReader(source)) { var magic = Encoding.ASCII.GetString(reader.ReadBytes(4)); if (magic == OLD_MAGIC) { return(LoadOldPackage(reader)); } if (magic != MAGIC) { throw new InvalidDataException("File is corrupt."); } var package = new RantPackage(); var version = reader.ReadUInt32(); if (version != PACKAGE_VERSION) { throw new InvalidDataException("Invalid package version: " + version); } var compress = reader.ReadBoolean(); var size = reader.ReadInt32(); var data = reader.ReadBytes(size); if (compress) { data = EasyCompressor.Decompress(data); } var doc = BsonDocument.Read(data); var info = doc["info"]; if (info == null) { throw new InvalidDataException("Metadata is missing from package."); } package.Title = info["title"]; package.ID = info["id"]; package.Version = RantPackageVersion.Parse(info["version"]); package.Description = info["description"]; package.Authors = (string[])info["authors"]; package.Tags = (string[])info["tags"]; var deps = info["dependencies"]; if (deps != null && deps.IsArray) { for (int i = 0; i < deps.Count; i++) { var dep = deps[i]; var depId = dep["id"].Value; var depVersion = dep["version"].Value; bool depAllowNewer = (bool)dep["allow-newer"].Value; package.AddDependency(new RantPackageDependency(depId.ToString(), depVersion.ToString()) { AllowNewer = depAllowNewer }); } } var patterns = doc["patterns"]; if (patterns != null) { var names = patterns.Keys; foreach (string name in names) { package.AddPattern(new RantPattern(name, RantPatternOrigin.File, patterns[name])); } } var tables = doc["tables"]; if (tables != null) { var names = tables.Keys; foreach (string name in names) { var table = tables[name]; string tableName = table["name"]; string[] tableSubs = (string[])table["subs"]; string[] hiddenClasses = (string[])table["hidden"]; var entries = new List <RantDictionaryEntry>(); var entryList = table["entries"]; for (var i = 0; i < entryList.Count; i++) { var loadedEntry = entryList[i]; int weight = 1; if (loadedEntry.HasKey("weight")) { weight = (int)loadedEntry["weight"].Value; } string[] requiredClasses = (string[])loadedEntry["classes"]; string[] optionalClasses = (string[])loadedEntry["optional_classes"]; var terms = new List <RantDictionaryTerm>(); var termList = loadedEntry["terms"]; for (var j = 0; j < termList.Count; j++) { var t = new RantDictionaryTerm(termList[j]["value"], termList[j]["pron"]); terms.Add(t); } var entry = new RantDictionaryEntry( terms.ToArray(), requiredClasses.Concat(optionalClasses.Select(x => x + "?")), weight ); entries.Add(entry); } var rantTable = new RantDictionaryTable( tableName, tableSubs, entries, hiddenClasses ); package.AddTable(rantTable); } } return(package); } }