예제 #1
0
        public void Deserialize_NoDeserializerForResourceType_ReportsError()
        {
            // Arrange
            const string yamlText =
                @"resourceType: Generic
resources:
- resourceUri: Microsoft.ServiceBus/namespaces/promitor-messaging
- resourceUri: Microsoft.ServiceBus/namespaces/promitor-messaging-2";
            var node = YamlUtils.CreateYamlNode(yamlText);

            _resourceDeserializerFactory.Setup(
                f => f.GetDeserializerFor(It.IsAny <ResourceType>())).Returns((IDeserializer <AzureResourceDefinitionV1>)null);

            // Act / Assert
            YamlAssert.ReportsError(
                _deserializer,
                node,
                node.Children["resourceType"],
                "Could not find a deserializer for resource type 'Generic'.");
        }
예제 #2
0
        public void Deserialize_AggregationSupplied_UsesDeserializer()
        {
            // Arrange
            const string yamlText =
                @"aggregation:
    type: Average";
            var node            = YamlUtils.CreateYamlNode(yamlText);
            var aggregationNode = (YamlMappingNode)node.Children["aggregation"];

            var aggregation = new MetricAggregationV1();

            _aggregationDeserializer.Setup(
                d => d.DeserializeObject(aggregationNode, _errorReporter.Object)).Returns(aggregation);

            // Act
            var config = _deserializer.Deserialize(node, _errorReporter.Object);

            // Assert
            Assert.Same(aggregation, config.Aggregation);
        }
예제 #3
0
        public void Deserialize_ResourceDiscoveryGroupsSupplied_DoesNotReportWarning()
        {
            // Because we're handling deserializing the resources manually, we
            // need to explicitly ignore the field to stop a warning being reported
            // about an unknown field

            // Arrange
            const string yamlText =
                @"resourceType: Generic
resourceDiscoveryGroups:
- name: sample-1
- name: sample-2";
            var node = YamlUtils.CreateYamlNode(yamlText);

            // Act
            _deserializer.Deserialize(node, _errorReporter.Object);

            // Assert
            _errorReporter.Verify(
                r => r.ReportWarning(It.IsAny <YamlNode>(), It.Is <string>(s => s.Contains("resourceDiscoveryGroups"))), Times.Never);
        }
예제 #4
0
        public void Deserialize_ResourcesSupplied_DoesNotReportError()
        {
            // Arrange
            const string yamlText =
                @"resourceType: Generic
resources:
- resourceUri: Microsoft.ServiceBus/namespaces/promitor-messaging
- resourceUri: Microsoft.ServiceBus/namespaces/promitor-messaging-2";
            var node = YamlUtils.CreateYamlNode(yamlText);

            SetupResourceDeserializer(node, new List <AzureResourceDefinitionV1> {
                new AzureResourceDefinitionV1()
            });

            // Act
            _deserializer.Deserialize(node, _errorReporter.Object);

            // Assert
            _errorReporter.Verify(
                reporter => reporter.ReportError(node, "Either 'resources' or 'resourceDiscoveryGroups' must be specified."), Times.Never);
        }
        private void SaveConfig()
        {
            List <string> lines   = YamlUtils.GetAllConfigLines(configFilePath);
            int           endLine = lines.Count - 1;

            if (!(materialExtractor as YamlObject).Save(ref lines, 0, ref endLine, 0))
            {
                Console.WriteLine("failed to save config!");
                return;
            }

            Console.WriteLine("updating config values successful, writing to file...");
            using (var writer = new StreamWriter(configFilePath, false)) {
                foreach (string line in lines)
                {
                    writer.WriteLine(line);
                }
            }

            Console.WriteLine("successfully saved config");
        }
예제 #6
0
        public void Deserialize_DictionarySupplied_DeserializesDictionary()
        {
            // Arrange
            var node = YamlUtils.CreateYamlNode(
                @"classes:
    first: maths
    second: chemistry
    third: art");

            // Act
            var result = _deserializer.Deserialize(node, _errorReporter.Object);

            // Assert
            var expectedClasses = new Dictionary <string, string>
            {
                { "first", "maths" },
                { "second", "chemistry" },
                { "third", "art" }
            };

            Assert.Equal(expectedClasses, result.Classes);
        }
        public WingetInstallerViewModel(YamlUtils yamlUtils, IInteractionService interactionService)
        {
            this.yamlUtils          = yamlUtils;
            this.interactionService = interactionService;
            this.AddChildren(
                this.Architecture              = new ChangeableProperty <YamlArchitecture>(),
                this.PlatformUwp               = new ChangeableProperty <bool>(this.Model?.Platform?.Contains(YamlPlatform.WindowsUniversal) == true),
                this.PlatformWin32             = new ChangeableProperty <bool>(this.Model?.Platform?.Contains(YamlPlatform.WindowsDesktop) == true),
                this.ProductCode               = new ValidatedChangeableProperty <string>("Product code", ValidatorFactory.ValidateGuid(false)),
                this.PackageFamilyName         = new ValidatedChangeableProperty <string>("Package family name", WingetValidators.GetPackageFamilyNameError),
                this.SignatureSha256           = new ValidatedChangeableProperty <string>("Signature hash", ValidatorFactory.ValidateSha256(false)),
                this.Scope                     = new ChangeableProperty <YamlScope>(),
                this.SilentCommand             = new ValidatedChangeableProperty <string>("Silent command", WingetValidators.GetInstallerSwitchesError),
                this.InteractiveCommand        = new ValidatedChangeableProperty <string>("Interactive command", WingetValidators.GetInstallerSwitchesError),
                this.LogCommand                = new ValidatedChangeableProperty <string>("Log command", WingetValidators.GetInstallerSwitchesError),
                this.UpgradeCommand            = new ValidatedChangeableProperty <string>("Upgrade command", WingetValidators.GetInstallerSwitchesError),
                this.CustomCommand             = new ValidatedChangeableProperty <string>("Custom command", WingetValidators.GetCustomInstallerSwitchesError),
                this.SilentCommandWithProgress = new ValidatedChangeableProperty <string>("Silent command with progress", WingetValidators.GetInstallerSwitchesError),
                this.InstallerType             = new ValidatedChangeableProperty <YamlInstallerType>("Installer type", ValidateInstallerType)
                );

            this.InstallerType.ValueChanged += InstallerTypeOnValueChanged;
        }
예제 #8
0
        public void Deserialize_ResourceDiscoveryGroupsSupplied_DoesNotReportError()
        {
            // Arrange
            const string yamlText =
                @"resourceType: Generic
resourceDiscoveryGroups:
- name: orders";
            var node = YamlUtils.CreateYamlNode(yamlText);
            var resourceDiscoveryGroups = new List <AzureResourceDiscoveryGroupDefinitionV1>
            {
                new AzureResourceDiscoveryGroupDefinitionV1()
            };

            _resourceDiscoveryGroupDeserializer.Setup(
                d => d.Deserialize(It.IsAny <YamlSequenceNode>(), It.IsAny <IErrorReporter>())).Returns(resourceDiscoveryGroups);

            // Act
            _deserializer.Deserialize(node, _errorReporter.Object);

            // Assert
            _errorReporter.Verify(
                reporter => reporter.ReportError(node, "Either 'resources' or 'resourceDiscoveryGroups' must be specified."), Times.Never);
        }
예제 #9
0
        public void Deserialize_Metrics_UsesMetricsDeserializer()
        {
            // Arrange
            const string config =
                @"version: v1
metrics:
- name: promitor_metrics_total";
            var yamlNode = YamlUtils.CreateYamlNode(config);
            var metrics  = new List <MetricDefinitionV1> {
                new MetricDefinitionV1 {
                    Name = "test_metric"
                }
            };

            _metricsDeserializer.Setup(
                d => d.Deserialize(It.IsAny <YamlSequenceNode>(), It.IsAny <IErrorReporter>())).Returns(metrics);

            // Act
            var declaration = _deserializer.Deserialize(yamlNode, _errorReporter.Object);

            // Assert
            Assert.Collection(declaration.Metrics, metric => Assert.Equal("test_metric", metric.Name));
        }
예제 #10
0
        public void SaveConfig(MenuUtils menuUtils, string header, int spacing)
        {
            List <string> lines   = YamlUtils.GetAllConfigLines(configPath);
            int           endLine = lines.Count - 1;

            if (!YamlUtils.ChangeYamlObjects(ref lines, 0, ref endLine, 0, new BetterDict <string, YamlObject> {
                { nameof(menuStyle), menuStyle }
            }))
            {
                Console.WriteLine("failed to save menuStyle");
                Console.ReadKey(true);
                return;
            }

            using (var writer = new StreamWriter(configPath, false)) {
                foreach (string line in lines)
                {
                    writer.WriteLine(line);
                }
            }

            Console.WriteLine("successfully saved menuStyle");
            Console.ReadKey(true);
        }
예제 #11
0
        public void Deserialize_ResourcesWithUnspecifiedResourceType_Null()
        {
            // Arrange
            const string yamlText =
                @"resources:
- resourceUri: Microsoft.ServiceBus/namespaces/promitor-messaging
- resourceUri: Microsoft.ServiceBus/namespaces/promitor-messaging-2";
            var node = YamlUtils.CreateYamlNode(yamlText);

            var resourceDeserializer = new Mock <IDeserializer <AzureResourceDefinitionV1> >();

            _resourceDeserializerFactory.Setup(
                f => f.GetDeserializerFor(It.IsAny <ResourceType>())).Returns(resourceDeserializer.Object);

            resourceDeserializer.Setup(
                d => d.Deserialize((YamlSequenceNode)node.Children["resources"], _errorReporter.Object))
            .Returns(new List <AzureResourceDefinitionV1>());

            // Act
            var definition = _deserializer.Deserialize(node, _errorReporter.Object);

            // Assert
            Assert.Null(definition.Resources);
        }
예제 #12
0
        public void Deserialize_SerializedModel_CanDeserialize()
        {
            // This test creates a v1 model, serializes it to yaml, and then verifies that
            // the V1Deserializer can deserialize it.

            // Arrange
            var yaml = _configurationSerializer.Serialize(_metricsDeclaration);

            // Act
            var deserializedModel = _v1Deserializer.Deserialize(YamlUtils.CreateYamlNode(yaml), _errorReporter);

            // Assert
            Assert.NotNull(deserializedModel);
            Assert.Equal("tenant", deserializedModel.AzureMetadata.TenantId);
            Assert.Equal("subscription", deserializedModel.AzureMetadata.SubscriptionId);
            Assert.Equal("promitor-group", deserializedModel.AzureMetadata.ResourceGroupName);
            Assert.Equal(TimeSpan.FromMinutes(7), deserializedModel.MetricDefaults.Aggregation.Interval);
            Assert.Equal("1 2 3 4 5", deserializedModel.MetricDefaults.Scraping.Schedule);
            Assert.Equal("china", deserializedModel.MetricDefaults.Labels["geo"]);

            // Check first metric
            Assert.Equal("promitor_demo_generic_queue_size", deserializedModel.Metrics.ElementAt(0).Name);
            Assert.Equal("Amount of active messages of the 'orders' queue (determined with Generic provider)", deserializedModel.Metrics.ElementAt(0).Description);
            Assert.Equal(ResourceType.Generic, deserializedModel.Metrics.ElementAt(0).ResourceType);
            Assert.Equal(new Dictionary <string, string> {
                { "app", "promitor" }
            }, deserializedModel.Metrics.ElementAt(0).Labels);
            Assert.Equal("ActiveMessages", deserializedModel.Metrics.ElementAt(0).AzureMetricConfiguration.MetricName);
            Assert.Equal(AggregationType.Average, deserializedModel.Metrics.ElementAt(0).AzureMetricConfiguration.Aggregation.Type);
            Assert.Equal(2, deserializedModel.Metrics.ElementAt(0).Resources.Count);

            var genericResource1 = Assert.IsType <GenericResourceV1>(deserializedModel.Metrics.ElementAt(0).Resources.ElementAt(0));

            Assert.Equal("Microsoft.ServiceBus/namespaces/promitor-messaging", genericResource1.ResourceUri);
            Assert.Equal("EntityName eq 'orders'", genericResource1.Filter);

            var genericResource2 = Assert.IsType <GenericResourceV1>(deserializedModel.Metrics.ElementAt(0).Resources.ElementAt(1));

            Assert.Equal("Microsoft.ServiceBus/namespaces/promitor-messaging", genericResource2.ResourceUri);
            Assert.Equal("EntityName eq 'accounts'", genericResource2.Filter);

            // Check second metric
            Assert.Equal("promitor_demo_servicebusqueue_queue_size", deserializedModel.Metrics.ElementAt(1).Name);
            Assert.Equal("Amount of active messages of the 'orders' queue (determined with ServiceBusNamespace provider)", deserializedModel.Metrics.ElementAt(1).Description);
            Assert.Equal(ResourceType.ServiceBusNamespace, deserializedModel.Metrics.ElementAt(1).ResourceType);
            Assert.Null(deserializedModel.Metrics.ElementAt(1).Labels);
            Assert.Equal(TimeSpan.FromMinutes(15), deserializedModel.Metrics.ElementAt(1).AzureMetricConfiguration.Aggregation.Interval);
            Assert.Equal("5 4 3 2 1", deserializedModel.Metrics.ElementAt(1).Scraping.Schedule);

            Assert.Single(deserializedModel.Metrics.ElementAt(1).Resources);
            var serviceBusQueueResource = Assert.IsType <ServiceBusNamespaceResourceV1>(deserializedModel.Metrics.ElementAt(1).Resources.ElementAt(0));

            Assert.Equal("promitor-messaging", serviceBusQueueResource.Namespace);
            Assert.Equal("orders", serviceBusQueueResource.QueueName);
            Assert.Equal("promitor-demo-group", serviceBusQueueResource.ResourceGroupName);
            Assert.NotNull(deserializedModel.Metrics.ElementAt(1).ResourceDiscoveryGroups);
            Assert.Single(deserializedModel.Metrics.ElementAt(1).ResourceDiscoveryGroups);
            var resourceDiscoveryGroup = deserializedModel.Metrics.ElementAt(1).ResourceDiscoveryGroups.ElementAt(0);

            Assert.Equal("example-resource-collection", resourceDiscoveryGroup.Name);
        }
예제 #13
0
 bool YamlObject.Save(ref List <string> lines, int startLine, ref int endLine, int currentTabDepth)
 {
     return(YamlUtils.ChangeSimpleValues(ref lines, startLine, ref endLine, currentTabDepth, GetValueChangeDict()));
 }
예제 #14
0
 public string Object2String(object obj)
 {
     return(YamlUtils.ToYaml(obj));
 }
예제 #15
0
 public T String2Object <T>(string content)
 {
     return(YamlUtils.FromYaml <T>(content));
 }
예제 #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Matcher"/> class.
        /// </summary>
        /// <param name="analyzer">The analyzer used for parsing>.</param>
        /// <param name="wantedFieldNames">The wanted field names.</param>
        /// <param name="matcherConfig">The matcher configuration.</param>
        /// <param name="filename">The filename.</param>
        public Matcher(IAnalyzer analyzer, ICollection <string> wantedFieldNames, YamlMappingNode matcherConfig, string filename)
        {
            this.analyzer           = analyzer;
            this.fixedStringActions = new List <MatcherAction>();
            this.variableActions    = new List <MatcherVariableAction>();
            this.dynamicActions     = new List <MatcherAction>();
            this.newValuesUserAgent = new UserAgent(wantedFieldNames);

            this.MatcherSourceLocation = filename + ':' + matcherConfig.Start.Line;

#if VERBOSE
            this.Verbose = true;
#else
            this.Verbose = false;
#endif
            var hasActiveExtractConfigs  = false;
            var hasDefinedExtractConfigs = false;

            // List of 'attribute', 'confidence', 'expression'
            var configLines = new List <ConfigLine>(16);
            foreach (var nodeTuple in matcherConfig)
            {
                var name = YamlUtils.GetKeyAsString(nodeTuple, this.MatcherSourceLocation);
                switch (name)
                {
                case "options":
                    var options = YamlUtils.GetStringValues(nodeTuple.Value, this.MatcherSourceLocation);
                    this.Verbose = options.Contains("verbose");
                    break;

                case "variable":
                    foreach (var variableConfig in YamlUtils.GetStringValues(nodeTuple.Value, this.MatcherSourceLocation))
                    {
                        var configParts = variableConfig.Split(new char[] { ':' }, 2);

                        if (configParts.Length != 2)
                        {
                            throw new InvalidParserConfigurationException($"Invalid variable config line: {variableConfig}");
                        }

                        var variableName = configParts[0].Trim();
                        var config       = configParts[1].Trim();

                        configLines.Add(new ConfigLine(ConfigLine.ConfigType.VARIABLE, variableName, null, config));
                    }

                    break;

                case "require":
                    foreach (var requireConfig in YamlUtils.GetStringValues(nodeTuple.Value, this.MatcherSourceLocation))
                    {
                        configLines.Add(new ConfigLine(ConfigLine.ConfigType.REQUIRE, null, null, requireConfig));
                    }

                    break;

                case "extract":
                    foreach (var extractConfig in YamlUtils.GetStringValues(nodeTuple.Value, this.MatcherSourceLocation))
                    {
                        var configParts = extractConfig.Split(new char[] { ':' }, 3);

                        if (configParts.Length != 3)
                        {
                            throw new InvalidParserConfigurationException($"Invalid extract config line: {extractConfig}");
                        }

                        var  attribute  = configParts[0].Trim();
                        long?confidence = null;
                        if (long.TryParse(configParts[1].Trim(), out var tmp))
                        {
                            confidence = tmp;
                        }

                        var config = configParts[2].Trim();
                        hasDefinedExtractConfigs = true;

                        // If we have a restriction on the wanted fields we check if this one is needed at all
                        if (wantedFieldNames is null || wantedFieldNames.Contains(attribute))
                        {
                            configLines.Add(new ConfigLine(ConfigLine.ConfigType.EXTRACT, attribute, confidence, config));
                            hasActiveExtractConfigs = true;
                        }
예제 #17
0
        private SolarSystem(YamlNode node)
        {
            YamlNode        gateNode         = null;
            YamlNode        planetNode       = null;
            YamlNode        starNode         = null;
            YamlNode        secondarySunNode = null;
            YamlMappingNode mapping          = (YamlMappingNode)node;

            foreach (var entry in mapping.Children)
            {
                string paramName = entry.Key.ToString();
                switch (paramName)
                {
                case "solarSystemID":
                    solarSystemID = Int32.Parse(entry.Value.ToString());
                    break;

                case "solarSystemNameID":
                    solarSystemNameID = Int32.Parse(entry.Value.ToString());
                    break;

                case "regional":
                    regional = Boolean.Parse(entry.Value.ToString());
                    break;

                case "border":
                    border = Boolean.Parse(entry.Value.ToString());
                    break;

                case "corridor":
                    corridor = Boolean.Parse(entry.Value.ToString());
                    break;

                case "fringe":
                    fringe = Boolean.Parse(entry.Value.ToString());
                    break;

                case "hub":
                    hub = Boolean.Parse(entry.Value.ToString());
                    break;

                case "international":
                    international = Boolean.Parse(entry.Value.ToString());
                    break;

                case "luminosity":
                    luminosity = Double.Parse(entry.Value.ToString());
                    break;

                case "radius":
                    radius = Double.Parse(entry.Value.ToString());
                    break;

                case "security":
                    security = Double.Parse(entry.Value.ToString());
                    break;

                case "sunTypeID":
                    sunTypeID = Int32.Parse(entry.Value.ToString());
                    break;

                case "center":
                    center = Location.ParseLocation(entry.Value);
                    break;

                case "max":
                    max = Location.ParseLocation(entry.Value);
                    break;

                case "min":
                    min = Location.ParseLocation(entry.Value);
                    break;

                case "wormholeClassID":
                    wormholeClassID = Int32.Parse(entry.Value.ToString());
                    break;

                case "descriptionID":
                    descriptionID = Int32.Parse(entry.Value.ToString());
                    break;

                case "factionID":
                    factionID = Int32.Parse(entry.Value.ToString());
                    break;

                case "securityClass":
                    securityClass = entry.Value.ToString();
                    break;

                case "disallowedAnchorCategories":
                    disallowedAnchorCategories = new List <int>();
                    YamlSequenceNode seq = (YamlSequenceNode)entry.Value;
                    foreach (YamlNode seqNode in seq.Children)
                    {
                        disallowedAnchorCategories.Add(Int32.Parse(seqNode.ToString()));
                    }
                    break;

                case "planets":
                    planetNode = entry.Value;
                    break;

                case "star":
                    starNode = entry.Value;
                    break;

                case "stargates":
                    gateNode = entry.Value;
                    break;

                case "secondarySun":
                    secondarySunNode = entry.Value;
                    break;

                case "visualEffect":
                    visualEffect = entry.Value.ToString();
                    break;

                case "disallowedAnchorGroups":
                    disallowedAnchorGroups = YamlUtils.LoadIntList(entry.Value);
                    break;

                default:
                    System.Diagnostics.Debug.WriteLine("SolarSystem unknown value:" + entry.Key + " = " + entry.Value);
                    break;
                }
            }
            // Parse these here so we can know we have the solarSystemID.
            if (gateNode != null)
            {
                stargates = Stargate.LoadYAML(gateNode, solarSystemID);
            }
            if (planetNode != null)
            {
                planets = OrbitalBody.LoadYAML(planetNode, solarSystemID);
            }
            if (starNode != null)
            {
                star = new Star(starNode, solarSystemID);
            }
            if (secondarySunNode != null)
            {
                secondarySun = new SecondarySun(secondarySunNode, solarSystemID);
            }
        }
예제 #18
0
        public InvType(YamlNode key, YamlNode node)
        {
            typeID = Int32.Parse(key.ToString());
            YamlMappingNode mapping = (YamlMappingNode)node;

            foreach (var entry in mapping.Children)
            {
                string paramName = entry.Key.ToString();
                switch (paramName)
                {
                case "name":
                    name = YamlUtils.GetLanguageString(YamlUtils.GetLanguageStrings(entry.Value), UserData.language);
                    break;

                case "description":
                    description = YamlUtils.GetLanguageString(YamlUtils.GetLanguageStrings(entry.Value), UserData.language);
                    break;

                case "capacity":
                    capacity = Double.Parse(entry.Value.ToString());
                    break;

                case "groupID":
                    groupID = Int32.Parse(entry.Value.ToString());
                    break;

                case "factionID":
                    factionID = Int64.Parse(entry.Value.ToString());
                    break;

                case "published":
                    published = Boolean.Parse(entry.Value.ToString());
                    break;

                case "graphicID":
                    graphicID = Int32.Parse(entry.Value.ToString());
                    break;

                case "iconID":
                    iconID = Int32.Parse(entry.Value.ToString());
                    break;

                case "marketGroupID":
                    marketGroupID = Int32.Parse(entry.Value.ToString());
                    break;

                case "mass":
                    mass = Double.Parse(entry.Value.ToString());
                    break;

                case "volume":
                    volume = Double.Parse(entry.Value.ToString());
                    break;

                case "radius":
                    radius = Double.Parse(entry.Value.ToString());
                    break;

                case "portionSize":
                    portionSize = Int32.Parse(entry.Value.ToString());
                    break;

                case "raceID":
                    raceID = Int32.Parse(entry.Value.ToString());
                    break;

                case "soundID":
                    soundID = Int32.Parse(entry.Value.ToString());
                    break;

                case "sofMaterialSetID":
                    sofMaterialSetID = Int32.Parse(entry.Value.ToString());
                    break;

                case "basePrice":
                    basePrice = Double.Parse(entry.Value.ToString());
                    break;

                case "sofFactionName":
                    sofFactionName = entry.Value.ToString();
                    break;

                case "masteries":
                    masteries = YamlUtils.LoadIndexedIntList(entry.Value);
                    break;

                case "traits":
                    YamlMappingNode traitMap = (YamlMappingNode)entry.Value;
                    foreach (var trait in traitMap.Children)
                    {
                        string traitName = trait.Key.ToString();
                        switch (traitName)
                        {
                        case "roleBonuses":
                            roleBonuses = ShipBonus.LoadBonusList(trait.Value);
                            break;

                        case "types":
                            traitTypes = ShipBonus.LoadBonusMap(trait.Value);
                            break;

                        case "miscBonuses":
                            miscBonuses = ShipBonus.LoadBonusList(trait.Value);
                            break;

                        default:
                            System.Diagnostics.Debug.WriteLine("InvType unknown trait:" + trait.Key + " = " + trait.Value);
                            break;
                        }
                    }
                    break;

                default:
                    System.Diagnostics.Debug.WriteLine("InvType unknown value:" + entry.Key + " = " + entry.Value);
                    break;
                }
            }
            types[typeID] = this;
        }
예제 #19
0
        public static async Task <(bool Success, string name, string filePath)> PackageAsync(IPathManager pathManager, ICacheManager cacheManager, IDatabaseManager databaseManager, string directory, bool isOverride)
        {
            var site = await databaseManager.SiteRepository.GetSiteByDirectoryAsync(directory);

            var sitePath = await pathManager.GetSitePathAsync(site);

            if (site == null || !DirectoryUtils.IsDirectoryExists(sitePath))
            {
                await WriteUtils.PrintErrorAsync($@"Invalid site directory path: ""{directory}""");

                return(false, null, null);
            }

            var   readme = string.Empty;
            Theme theme  = null;

            var readmePath = PathUtils.Combine(sitePath, "README.md");

            if (FileUtils.IsFileExists(readmePath))
            {
                readme = FileUtils.ReadText(readmePath);
                var yaml = MarkdownUtils.GetYamlFrontMatter(readme);
                if (!string.IsNullOrEmpty(yaml))
                {
                    readme = MarkdownUtils.RemoveYamlFrontMatter(readme);
                    theme  = YamlUtils.Deserialize <Theme>(yaml);
                }
            }

            var writeReadme = false;

            if (theme == null || string.IsNullOrEmpty(theme.Name) || string.IsNullOrEmpty(theme.CoverUrl))
            {
                writeReadme = true;
                theme       = new Theme
                {
                    Name            = ReadUtils.GetString("name:"),
                    CoverUrl        = ReadUtils.GetString("cover image url:"),
                    Summary         = ReadUtils.GetString("repository url:"),
                    Tags            = ReadUtils.GetStringList("tags:"),
                    ThumbUrls       = ReadUtils.GetStringList("thumb image urls:"),
                    Compatibilities = ReadUtils.GetStringList("compatibilities:"),
                    Price           = ReadUtils.GetYesNo("is free?") ? 0 : ReadUtils.GetDecimal("price:"),
                };
            }

            if (writeReadme)
            {
                readme = @$ "---
{YamlUtils.Serialize(theme)}
---

" + readme;
                FileUtils.WriteText(readmePath, readme);
            }

            var packageName = "T_" + theme.Name.Replace(" ", "_");
            var packagePath = pathManager.GetSiteTemplatesPath(packageName);
            var fileName    = packageName + ".zip";
            var filePath    = pathManager.GetSiteTemplatesPath(fileName);

            if (!isOverride && FileUtils.IsFileExists(filePath))
            {
                return(true, theme.Name, filePath);
            }

            FileUtils.DeleteFileIfExists(filePath);
            DirectoryUtils.DeleteDirectoryIfExists(packagePath);

            await Console.Out.WriteLineAsync($"Theme name: {theme.Name}");

            await Console.Out.WriteLineAsync($"Theme folder: {packagePath}");

            await Console.Out.WriteLineAsync("Theme packaging...");

            var caching = new CacheUtils(cacheManager);
            var manager = new SiteTemplateManager(pathManager, databaseManager, caching);

            if (manager.IsSiteTemplateDirectoryExists(packageName))
            {
                manager.DeleteSiteTemplate(packageName);
            }

            var directoryNames = DirectoryUtils.GetDirectoryNames(sitePath);

            var directories = new List <string>();
            var siteDirList = await databaseManager.SiteRepository.GetSiteDirsAsync(0);

            foreach (var directoryName in directoryNames)
            {
                var isSiteDirectory = false;
                if (site.Root)
                {
                    foreach (var siteDir in siteDirList)
                    {
                        if (StringUtils.EqualsIgnoreCase(siteDir, directoryName))
                        {
                            isSiteDirectory = true;
                        }
                    }
                }
                if (!isSiteDirectory && !pathManager.IsSystemDirectory(directoryName))
                {
                    directories.Add(directoryName);
                }
            }

            var files = DirectoryUtils.GetFileNames(sitePath);

            var exportObject = new ExportObject(pathManager, databaseManager, caching, site);
            await exportObject.ExportFilesToSiteAsync(packagePath, true, directories, files, true);

            var siteContentDirectoryPath = pathManager.GetSiteTemplateMetadataPath(packagePath, DirectoryUtils.SiteFiles.SiteTemplates.SiteContent);

            await exportObject.ExportSiteContentAsync(siteContentDirectoryPath, true, true, new List <int>());

            await SiteTemplateManager.ExportSiteToSiteTemplateAsync(pathManager, databaseManager, caching, site, packageName);

            var siteTemplateInfo = new SiteTemplateInfo
            {
                SiteTemplateName = theme.Name,
                PicFileName      = string.Empty,
                WebSiteUrl       = string.Empty,
                Description      = string.Empty
            };
            var xmlPath = pathManager.GetSiteTemplateMetadataPath(packagePath,
                                                                  DirectoryUtils.SiteFiles.SiteTemplates.FileMetadata);

            XmlUtils.SaveAsXml(siteTemplateInfo, xmlPath);

            pathManager.CreateZip(filePath, packagePath);

            return(true, theme.Name, filePath);
        }
        public void YamlSerialization_serialization_produces_correct_yaml()
        {
            var yaml = YamlUtils.Serialize(new ColorRGBAUtils.YamlSerialization(_yamlColor));

            Assert.That(yaml, Is.EqualTo(_yamlData));
        }
예제 #21
0
        internal static void GatherMods()
        {
            YamlFile <GuuMod>[] modFiles  = YamlUtils.GetModFiles();
            SortedSet <GuuMod>  loadOrder = new SortedSet <GuuMod>(new ModComparer());

            // Filter what is valid and invalid for load
            foreach (YamlFile <GuuMod> modFile in modFiles)
            {
                GuuMod mod = modFile.Read();

                // Check for mod ID
                if (mod.ID == null || mod.ID.Equals(string.Empty))
                {
                    GuuCore.LOGGER?.LogWarning($"Missing 'modID' key on file '{modFile.Info.FullName}' or the value is blank. Skipping mod!");
                    continue;
                }

                // Check if it is not example mod
                if (mod.ID.Equals(EXAMPLE_MOD_ID))
                {
                    GuuCore.LOGGER?.LogWarning($"Found example mod ID on file '{modFile.Info.FullName}', please change the ID of the mod. Skipping mod!");
                    continue;
                }

                // Check for assembly to load
                if (mod.AssemblyName == null || mod.AssemblyName.Equals(string.Empty))
                {
                    GuuCore.LOGGER?.LogWarning($"Missing 'assembly' key on file  {modFile.Info.FullName}' or the value is blank. Skipping mod!");
                    continue;
                }

                // Check for guu version to see if it can be loaded
                if (mod.GuuVersion != null && !mod.GuuVersion.Equals(string.Empty))
                {
                    if (!ValidateVersion(mod.GuuVersion, GuuCore.GUU_VERSION))
                    {
                        GuuCore.LOGGER?.LogWarning($"Guu version is outdated. Requires at least '{mod.GuuVersion}' but has '{GuuCore.GUU_VERSION}'. Skipping mod!");
                        continue;
                    }
                }

                mod.Info = modFile.Info;
                MODS.Add(mod.ID, null);
                loadOrder.Add(mod);
            }

            // Loads the mods and generates their mod information
            foreach (GuuMod mod in loadOrder)
            {
                string           modid        = mod.ID;
                string           mainAssembly = mod.AssemblyName;
                string           version      = mod.Version ?? ASSEMBLY_VERSION_TAG;
                bool             unsafeCheck  = mod.IsUnsafe;
                HashSet <string> required     = new HashSet <string>(mod.RequiredMods);

                EdenHarmony harmony = new EdenHarmony(modid);

                // Checks if all required mods are available
                foreach (string req in required)
                {
                    if (!MODS.ContainsKey(req))
                    {
                        throw new Exception($"Missing required mod '{req}' when loading '{modid}'");
                    }
                }

                // Checks and loads the main assembly
                FileInfo assembly = new FileInfo(Path.Combine(mod.Info.Directory.FullName, mainAssembly + GuuCore.DLL_EXTENSION));
                if (!assembly.Exists)
                {
                    throw new Exception($"Cannot load the main assembly '{mainAssembly}' for mod '{modid}'");
                }

                Assembly modAssembly = AssemblyUtils.LoadWithSymbols(assembly.FullName);
                harmony.LatePatchAll(modAssembly, !unsafeCheck ? AllowedPatchType.ALL : SAFE_PATCH);

                // Checks if version as {assemblyVersion} tag, and replaces it
                if (version.Equals(ASSEMBLY_VERSION_TAG))
                {
                    mod.Version = modAssembly.GetRuntimeVersion();
                }

                // Obtains the ModMain
                Type    mainType = modAssembly.GetTypes().Single(t => t.IsSubclassOf(typeof(ModMain)));
                ModMain main     = Activator.CreateInstance(mainType) as ModMain;

                main.Assembly    = modAssembly;
                main.Mod         = mod;
                main.Logger      = new ModLogger(modid);
                main.HarmonyInst = harmony;

                MOD_CONTEXTS.Add(modAssembly, new ModContext(main.Mod, main));

                // Finalizes the load process
                MODS[modid] = main;
            }

            // Loads all modules and registers them
            foreach (string modid in MODS.Keys)
            {
                ModMain         main        = MODS[modid];
                List <IModLoad> moduleMains = new List <IModLoad> {
                    main
                };

                foreach (ModModuleAttribute module in main.GetType().GetCustomAttributes <ModModuleAttribute>())
                {
                    string name   = module.moduleName;
                    string depID  = module.dependentID;
                    string depVer = module.dependentVersion;

                    // Checks if dependent is available, and if so if the version matches
                    if (!MODS.ContainsKey(depID))
                    {
                        continue;
                    }
                    if (!ValidateVersion(depVer, MODS[depID].Mod.Version))
                    {
                        continue;
                    }

                    // Checks and loads the assembly
                    FileInfo assembly = new FileInfo(Path.Combine(main.Mod.Info.Directory.FullName, name + GuuCore.DLL_EXTENSION));
                    if (!assembly.Exists)
                    {
                        throw new Exception($"Trying to load module '{name}' for mod '{modid}', but it wasn't found!");
                    }

                    Assembly moduleAssembly = AssemblyUtils.LoadWithSymbols(assembly.FullName);
                    main.HarmonyInst?.LatePatchAll(moduleAssembly, !main.Mod.IsUnsafe ? AllowedPatchType.ALL : SAFE_PATCH);

                    // Obtains the ModuleMain
                    Type       mainType   = moduleAssembly.GetTypes().Single(t => t.IsSubclassOf(typeof(ModuleMain)));
                    ModuleMain moduleMain = Activator.CreateInstance(mainType) as ModuleMain;

                    moduleMain.Assembly = moduleAssembly;
                    moduleMain.Main     = main;

                    MOD_CONTEXTS.Add(moduleAssembly, MOD_CONTEXTS[main.Assembly]);

                    // Finalizes the load process for this mod's modules
                    moduleMains.Add(moduleMain);
                }

                // Finalizes the load process for all modules
                main.Mod.Modules = moduleMains.ToArray();
            }

            // Executes all late patches
            foreach (ModMain main in MODS.Values)
            {
                main.HarmonyInst?.ExecuteLatePatches();
            }

            // Initializes the mods
            Init();

            // Preloads the mods
            PreLoad();

            // Triggers registration for all mods
            Register();
        }
        public void YamlSerialization_deserialization_produces_correct_color()
        {
            var color = YamlUtils.Deserialize <ColorRGBAUtils.YamlSerialization>(_yamlData).Deserialize();

            Assert.That(color, Is.EqualTo(_yamlColor));
        }