Ejemplo n.º 1
0
        public void Upgrade(AssetMigrationContext context, string dependencyName, PackageVersion currentVersion, PackageVersion targetVersion, YamlMappingNode yamlAssetNode, PackageLoadingAssetFile assetFile)
        {
            dynamic asset = new DynamicYamlMapping(yamlAssetNode);

            // upgrade the asset
            UpgradeAsset(context, currentVersion, targetVersion, asset, assetFile);
            SetSerializableVersion(asset, dependencyName, targetVersion);

            // upgrade its base
            var baseBranch = asset[Asset.BaseProperty];
            if (baseBranch != null)
            {
                UpgradeBase(context, dependencyName, currentVersion, targetVersion, baseBranch, assetFile);
            }

            // upgrade base parts
            var basePartsBranch = asset[Asset.BasePartsProperty] as DynamicYamlArray;
            if (basePartsBranch != null)
            {
                foreach (dynamic assetBase in basePartsBranch)
                {
                    UpgradeBase(context, dependencyName, currentVersion, targetVersion, assetBase, assetFile);
                }
            }
        }
Ejemplo n.º 2
0
        public void Upgrade(AssetMigrationContext context, string dependencyName, PackageVersion currentVersion, PackageVersion targetVersion, YamlMappingNode yamlAssetNode, PackageLoadingAssetFile assetFile)
        {
            dynamic asset = new DynamicYamlMapping(yamlAssetNode);

            // upgrade the asset
            var baseBranch = asset[Asset.BaseProperty];
            var basePartsBranch = asset[Asset.BasePartsProperty] as DynamicYamlArray;

            // Detect in what kind of override context we are
            var overrideHint = (baseBranch != null || (basePartsBranch != null && basePartsBranch.Node.Children.Count > 0))
                ? OverrideUpgraderHint.Derived
                : OverrideUpgraderHint.Unknown;

            // Upgrade the asset
            UpgradeAsset(context, currentVersion, targetVersion, asset, assetFile, overrideHint);
            SetSerializableVersion(asset, dependencyName, targetVersion);

            // Upgrade its base
            if (baseBranch != null)
            {
                UpgradeBase(context, dependencyName, currentVersion, targetVersion, baseBranch, assetFile);
            }

            // Upgrade base parts
            if (basePartsBranch != null)
            {
                foreach (dynamic assetBase in basePartsBranch)
                {
                    UpgradeBase(context, dependencyName, currentVersion, targetVersion, assetBase, assetFile);
                }
            }
        }
        public static YamlNode GetNodes(Asset source)
        {
            var root = new YamlMappingNode();
            var assetType = source.AssetType;
            root.Add("asset", assetType);
            JObject obj = JObject.FromObject(source.GetChangesDto());
            obj.Remove("AssetType");

            YamlMappingNode attributes = new YamlMappingNode();

            var tuples = (from prop in
                            (
                                from token in JToken.FromObject(obj)
                                where token.Type == JTokenType.Property
                                select token as JProperty
                             )
                          select GetUpdateAttribute(prop)
                        );
            foreach (var tuple in tuples)
            {
                attributes.Add(tuple.Item1, tuple.Item2);
            }

            root.Add("attributes", attributes);

            return root;
        }
Ejemplo n.º 4
0
        private static void FindNodes(YamlMappingNode container, string name, List<KeyValuePair<YamlMappingNode, YamlNode>> matches)
        {
            var key = new YamlScalarNode(name);
            YamlNode matchNode;

            if (container.Children.TryGetValue(key, out matchNode))
            {
                matches.Add(new KeyValuePair<YamlMappingNode, YamlNode>(container, new YamlScalarNode(name)));
            }

            var nodes = container.Children.Values.OfType<YamlMappingNode>();
            foreach (var node in nodes)
            {
                FindNodes(node, name, matches);
            }

            var sequenceNodes = container.Children.Values.OfType<YamlSequenceNode>();
            foreach (var sequenceNode in sequenceNodes)
            {
                foreach (var node in sequenceNode.Children.OfType<YamlMappingNode>())
                {
                    FindNodes(node, name, matches);
                }
            }
        }
        public void ParsesTeamCityServerCorrectly()
        {
            var kernel = new StandardKernel();

            var parser = kernel.Get<TeamCityConfigParser>();

            kernel.Bind<ITimer>().ToConstant(new Mock<ITimer>().Object);
            kernel.Bind<IParser>().ToConstant(new Mock<IParser>().Object).Named("TeamCity");

            var config = new YamlMappingNode
                             {
                                 {"url", "http://localhost"},
                                 {"username", "ci"},
                                 {"password", "secret"}
                             };
            var pipeline1 = new YamlMappingNode {{"name", "bt1"}};
            var pipeline2 = new YamlMappingNode { { "name", "bt2" } };
            var pipelines = new YamlSequenceNode {pipeline1, pipeline2};
            config.Add("pipelines",pipelines);

            var teamCityServer = parser.Parse(config) as TeamCityServer;
            Assert.IsNotNull(teamCityServer);
            Assert.IsNotNull(teamCityServer.Config);
            var teamCityServerConfig = teamCityServer.Config;
            Assert.AreEqual("http://localhost", teamCityServerConfig.URL);
            Assert.AreEqual("ci", teamCityServerConfig.Username);
            Assert.AreEqual("secret", teamCityServerConfig.Password);
            Assert.IsNotNull(teamCityServerConfig.Pipelines);
            Assert.AreEqual(2, teamCityServerConfig.Pipelines.Count());
        }
Ejemplo n.º 6
0
        private static void FindEncryptedNodes(YamlMappingNode parent, KeyValuePair<YamlNode, YamlNode> container, List<YamlEncryptedNode> matches)
        {
            var node = container.Value;
            if (node is YamlMappingNode)
            {
                var nodes = ((YamlMappingNode) node).Children.ToList();

                if (nodes.Count == 2 &&
                    nodes[0].Key.ToString().Equals("IV", StringComparison.InvariantCultureIgnoreCase) &&
                    nodes[1].Key.ToString().Equals("Value", StringComparison.InvariantCultureIgnoreCase))
                {
                    var encryptedNode = new YamlEncryptedNode {Container = container, Parent = parent};
                    matches.Add(encryptedNode);
                }
            }

            if (node is YamlMappingNode)
            {
                foreach (var childNode in ((YamlMappingNode)node).Children)
                {
                    FindEncryptedNodes((YamlMappingNode) node, childNode, matches);
                }
            }

            if (node is YamlSequenceNode)
            {
                var sequenceNodes = ((YamlSequenceNode) node).Children;
                foreach (var child in sequenceNodes.OfType<YamlMappingNode>())
                {
                    child.Children.ToList().ForEach(x => FindEncryptedNodes(child, x, matches));
                }
            }
        }
Ejemplo n.º 7
0
    private void openRulesetToolStripMenuItem_Click(object sender, EventArgs e)
    {
      if( ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK )
      {
        string rulesetContents;

        rulesetFilename = ofd.FileName;
        this.Text = "M.A.R.S. for OpenXCOM [" + rulesetFilename + "]";

        rulesetContents = System.IO.File.ReadAllText( ofd.FileName );
        rulesetStream = new YamlStream();

        using( System.IO.StringReader docReader = new System.IO.StringReader(rulesetContents) )
        {
          rulesetStream.Load( docReader );
        }

        rulesetRoot = (YamlMappingNode)rulesetStream.Documents[0].RootNode;

        foreach( System.Collections.Generic.KeyValuePair<YamlNode, YamlNode> child in rulesetRoot.Children )
        {
          // child are "<name>:" markers in the yaml
          TreeNode coreNode = null;
          TreeNode objNode = null;

          switch( child.Key.ToString() )
          {
            case "countries":
              coreNode = oxcTree.Nodes.Add( "Countries" );
              coreNode.Tag = child.Value;

              rulesetCountries = new Rulesets.Countries();
              rulesetCountries.Load( (YamlSequenceNode)child.Value );

              foreach( Rulesets.Country c in rulesetCountries.CountryList )
              {
                objNode = coreNode.Nodes.Add( c.CountryString );
                objNode.Tag = c;
              }

              break;

            case "regions":
              coreNode = oxcTree.Nodes.Add( "Regions" );
              coreNode.Tag = child.Value;
              break;
          }

          /*
          if( coreNode == null )
          {
            coreNode = oxcTree.Nodes.Add( child.Key.ToString() );
            coreNode.Tag = child.Value;
          }
          */

        }
        
      }
    }
        public void ParsesCruiseControlServerCorrectly()
        {
            var kernel = new StandardKernel();

            var parser = kernel.Get<CruiseControlConfigParser>();

            kernel.Bind<ITimer>().ToConstant(new Mock<ITimer>().Object);
            kernel.Bind<IParser>().ToConstant(new Mock<IParser>().Object).Named("CruiseControl");

            var config = new YamlMappingNode
                             {
                                 {"url", "http://goserver.localdomain:8153/go/cctray.xml"},
                                 {"username", "ci"},
                                 {"password", "secret"}
                             };
            var pipeline1 = new YamlMappingNode {{"name", "Cosby-Kid"}};
            var pipeline2 = new YamlMappingNode { { "name", "Family-Tieman" } };
            var pipelines = new YamlSequenceNode {pipeline1, pipeline2};
            config.Add("pipelines",pipelines);

            var cruiseControlServer = parser.Parse(config) as CruiseControlServer;
            Assert.IsNotNull(cruiseControlServer);
            Assert.IsNotNull(cruiseControlServer.Config);
            var cruiseControlServerconfig = cruiseControlServer.Config;
            Assert.AreEqual("http://goserver.localdomain:8153/go/cctray.xml", cruiseControlServerconfig.URL);
            Assert.AreEqual("ci", cruiseControlServerconfig.Username);
            Assert.AreEqual("secret", cruiseControlServerconfig.Password);
            Assert.IsNotNull(cruiseControlServerconfig.Pipelines);
            Assert.AreEqual(2, cruiseControlServerconfig.Pipelines.Count());
        }
 private void VisitYamlMappingNode(YamlMappingNode yamlNode)
 {
     foreach (var entry in yamlNode.Children)
     {
         VisitYamlNode(entry);
     }
 }
Ejemplo n.º 10
0
 public void FromYaml(YamlMappingNode mapping) {
     foreach (var entry in mapping.Children) {
         var key = ((YamlScalarNode) entry.Key).Value;
         switch (key) {
         case ":archive_format":
             ArchiveFormat = YamlExtensions.GetStringOrDefault(entry.Value);
             break;
         case ":format_version":
             FormatVersion = YamlExtensions.GetLongOrDefault(entry.Value);
             break;
         case ":guid":
             Guid = YamlExtensions.GetStringOrDefault(entry.Value);
             break;
         case ":version":
             Version = YamlExtensions.GetLongOrDefault(entry.Value);
             break;
         case ":pack_size":
             PackSize = YamlExtensions.GetLongOrDefault(entry.Value);
             break;
         case ":wd_size":
             WdSize = YamlExtensions.GetLongOrDefault(entry.Value);
             break;
         case ":pack":
             Pack = YamlExtensions.GetStringDictionary(entry.Value);
             break;
         case ":wd":
             WD = YamlExtensions.GetStringDictionary(entry.Value);
             break;
         }
     }
 }
Ejemplo n.º 11
0
 protected override void UpgradeAsset(AssetMigrationContext context, PackageVersion currentVersion, PackageVersion targetVersion, dynamic asset, PackageLoadingAssetFile assetFile)
 {
     // Introduction of MaterialInstance
     var material = asset.Type.Material;
     if (material != null)
     {
         asset.Type.MaterialInstance = new YamlMappingNode();
         asset.Type.MaterialInstance.Material = material;
         asset.Type.Material = DynamicYamlEmpty.Default;
     }
     var type = asset.Type.Node as YamlMappingNode;
     if (type != null && type.Tag == "!CubeProceduralModel")
     {
         // Size changed from scalar to vector3
         var size = asset.Type.Size as DynamicYamlScalar;
         if (size != null)
         {
             var vecSize = new YamlMappingNode
             {
                 { new YamlScalarNode("X"), new YamlScalarNode(size.Node.Value) },
                 { new YamlScalarNode("Y"), new YamlScalarNode(size.Node.Value) },
                 { new YamlScalarNode("Z"), new YamlScalarNode(size.Node.Value) }
             };
             vecSize.Style = YamlStyle.Flow;
             asset.Type.Size = vecSize;
         }
     }
 }
        private void VisitYamlMappingNode(YamlScalarNode yamlNodeKey, YamlMappingNode yamlNodeValue)
        {
            EnterContext(yamlNodeKey.Value);

            VisitYamlMappingNode(yamlNodeValue);

            ExitContext();
        }
Ejemplo n.º 13
0
            public void Upgrade(int currentVersion, int targetVersion, ILogger log, YamlMappingNode yamlAssetNode)
            {
                dynamic asset = new DynamicYamlMapping(yamlAssetNode);
                var baseBranch = asset["~Base"];
                if (baseBranch != null)
                    asset["~Base"] = DynamicYamlEmpty.Default;

                SetSerializableVersion(asset, targetVersion);
            }
Ejemplo n.º 14
0
 public void FromYaml(YamlMappingNode mapping) {
     foreach (var entry in mapping.Children) {
         var key = ((YamlScalarNode) entry.Key).Value;
         switch (key) {
         case ":name":
             Name = YamlExtensions.GetStringOrDefault(entry.Value);
             break;
         case ":max_threads":
             MaxThreads = YamlExtensions.GetIntOrDefault(entry.Value);
             break;
         case ":uuid":
             Uuid = YamlExtensions.GetStringOrDefault(entry.Value);
             break;
         case ":homepage":
             Homepage = YamlExtensions.GetStringOrDefault(entry.Value);
             break;
         case ":server_mods_path":
             ServerModsPath = YamlExtensions.GetStringOrDefault(entry.Value);
             break;
         case ":archive_format":
             ArchiveFormat = YamlExtensions.GetStringOrDefault(entry.Value);
             break;
         case ":hosts":
             var hosts = YamlExtensions.GetStringArray(entry.Value);
             var invalidHost =
                 hosts.FirstOrDefault(x => x == null || !Uri.IsWellFormedUriString(x, UriKind.Absolute));
             if (invalidHost != null) {
                 throw new InvalidHostFoundException(
                     string.Format("Malformed host found, does it contain valid protocol like 'http://'?\n{0}",
                         invalidHost));
             }
             Hosts = hosts.Select(x => x.ToUri()).ToArray();
             break;
         case ":missions":
             Missions = YamlExtensions.GetStringDictionary(entry.Value);
             break;
         case ":mpmissions":
             MPMissions = YamlExtensions.GetStringDictionary(entry.Value);
             break;
         case ":image":
             Image = YamlExtensions.GetStringOrDefault(entry.Value);
             break;
         case ":image_large":
             ImageLarge = YamlExtensions.GetStringOrDefault(entry.Value);
             break;
         case ":servers":
             Servers = YamlExtensions.GetStringArray(entry.Value);
             break;
         case ":mods":
             Mods = GetModDictionary(entry.Value) ?? new Dictionary<string, SixRepoMod>();
             break;
         case ":apps":
             Apps = GetAppDictionary(entry.Value) ?? new Dictionary<string, SixRepoApp>();
             break;
         }
     }
 }
Ejemplo n.º 15
0
            public void Upgrade(AssetMigrationContext context, int currentVersion, int targetVersion, YamlMappingNode yamlAssetNode, PackageLoadingAssetFile assetFile)
            {
                dynamic asset = new DynamicYamlMapping(yamlAssetNode);
                var baseBranch = asset["~Base"];
                if (baseBranch != null)
                    asset["~Base"] = DynamicYamlEmpty.Default;

                SetSerializableVersion(asset, targetVersion);
            }
Ejemplo n.º 16
0
            public void Upgrade(AssetMigrationContext context, string dependencyName, PackageVersion currentVersion, PackageVersion targetVersion, YamlMappingNode yamlAssetNode, PackageLoadingAssetFile assetFile)
            {
                dynamic asset = new DynamicYamlMapping(yamlAssetNode);
                var baseBranch = asset[Asset.BaseProperty];
                if (baseBranch != null)
                    asset[BaseProperty] = DynamicYamlEmpty.Default;

                AssetUpgraderBase.SetSerializableVersion(asset, dependencyName, targetVersion);
            }
Ejemplo n.º 17
0
                public void Upgrade(AssetMigrationContext context, string dependencyName, PackageVersion currentVersion, PackageVersion targetVersion, YamlMappingNode yamlAssetNode, PackageLoadingAssetFile assetFile)
                {
                    dynamic asset = new DynamicYamlMapping(yamlAssetNode);

                    AssetUpgraderBase.SetSerializableVersion(asset, dependencyName, targetVersion);

                    // Move Test4 to Test5
                    asset.Test5 = asset.Test4;
                    asset.Test4 = DynamicYamlEmpty.Default;
                }
 protected override void Visit(YamlMappingNode mapping)
 {
     var nestedVisitor = new ContextAwareMappingVisitor(context);
     mapping.Accept(nestedVisitor);
     
     foreach (var item in nestedVisitor.Items)
     {
         this.items.Add(new KeyValuePair<string, string>(item.Key, item.Value));
     }
 }
Ejemplo n.º 19
0
                public void Upgrade(int currentVersion, int targetVersion, ILogger log, YamlMappingNode yamlAssetNode)
                {
                    dynamic asset = new DynamicYamlMapping(yamlAssetNode);

                    asset.SerializedVersion = targetVersion;

                    // Move Test4 to Test5
                    asset.Test5 = asset.Test4;
                    asset.Test4 = DynamicYamlEmpty.Default;
                }
Ejemplo n.º 20
0
                public void Upgrade(int currentVersion, int targetVersion, ILogger log, YamlMappingNode yamlAssetNode)
                {
                    dynamic asset = new DynamicYamlMapping(yamlAssetNode);

                    asset.SerializedVersion = AssetRegistry.GetCurrentFormatVersion(typeof(MyUpgradedAsset));

                    // Move Test1 to Test2
                    asset.Test2 = asset.Test1;
                    asset.Test1 = DynamicYamlEmpty.Default;
                }
Ejemplo n.º 21
0
        protected YamlQuery(YamlQuery parent, bool error, YamlMappingNode root, string key)
        {
            _path = parent == null ? "" : parent.QueryPath;
            _path += key + ":";

            this.IsError = error;
            if (!error)
            {
                // Find next mapping node
                this.Node = Find(root, key);
            }
        }
Ejemplo n.º 22
0
                public void Upgrade(AssetMigrationContext context, string dependencyName, PackageVersion currentVersion, PackageVersion targetVersion, YamlMappingNode yamlAssetNode, PackageLoadingAssetFile assetFile)
                {
                    dynamic asset = new DynamicYamlMapping(yamlAssetNode);

                    // Note: seems little bit strange, but original test was not using targetVersion...
                    var serializedVersion = AssetRegistry.GetCurrentFormatVersions(typeof(MyUpgradedAsset))[dependencyName];
                    AssetUpgraderBase.SetSerializableVersion(asset, dependencyName, serializedVersion);

                    // Move Test1 to Test2
                    asset.Test2 = asset.Test1;
                    asset.Test1 = DynamicYamlEmpty.Default;
                }
Ejemplo n.º 23
0
 private static string GetPrefix(YamlMappingNode node)
 {
     try
     {
         var prefixNode = node.Children.First(c => ((YamlScalarNode)c.Key).Value == "_prefix");
         return ((YamlScalarNode)prefixNode.Value).Value;
     }
     catch (InvalidOperationException)
     {
         // We get to here if no "_prefix" node was found.
         return "";
     }
 }
Ejemplo n.º 24
0
            public virtual void PrintMapping(YamlMappingNode mapping) {
                Contract.Requires<ArgumentNullException>(mapping != null);

                foreach (var entry in mapping.Children) {
                    var key = ((YamlScalarNode) entry.Key).Value;
                    var value = String.Empty;

                    try {
                        value = ((YamlScalarNode) entry.Value).Value;
                    } catch (Exception) {}

                    Console.WriteLine("{0}: {1}", key, value);
                }
            }
Ejemplo n.º 25
0
        static ShortcutCollection GetShortcuts(YamlMappingNode collection)
        {
            string group = GetValueByKey(collection, "group");
            string process = GetValueByKey(collection, "process");

            var shortCuts = from groupShortcuts in collection.Children.Where(n => n.Key.ToString() == "shortcuts").Take(1).Select(x => x.Value).OfType<YamlSequenceNode>()
                            from shortcut in GetKeyShortcuts(groupShortcuts)
                            select shortcut;

            return new ShortcutCollection(shortCuts.ToList())
            {
                Process = process, 
                Group = @group
            };
        }
        public IBuildServer Parse(YamlMappingNode config)
        {
            var server = _kernel.Get<CruiseControlServer>();
            var serverConfig = new CruiseControlServerConfig()
                                   {
                                       URL = BurroUtils.ExtractValue(config, "url"),
                                       Username = BurroUtils.ExtractValue(config, "username"),
                                       Password = BurroUtils.ExtractValue(config, "password"),
                                       Pipelines = ParsePipelines(config)
                                   };

            server.Initialise(serverConfig);

            return server;
        }
Ejemplo n.º 27
0
 public void FromYaml(YamlMappingNode mapping) {
     foreach (var entry in mapping.Children) {
         var key = ((YamlScalarNode) entry.Key).Value;
         switch (key) {
         case ":key":
             Key = YamlExtensions.GetStringOrDefault(entry.Value);
             break;
         case ":default_host":
             DefaultHost = YamlExtensions.GetStringOrDefault(entry.Value);
             break;
         case ":default_host_path":
             DefaultHostPath = YamlExtensions.GetStringOrDefault(entry.Value);
             break;
         }
     }
 }
Ejemplo n.º 28
0
        public void generateFromYaml(YamlMappingNode cubeEventsNode)
        {
            foreach (var cubeEvent in cubeEventsNode.Children) {
            String cubeEventName = (((YamlScalarNode)cubeEvent.Key).Value);

            YamlMappingNode eventEndpoints = (YamlMappingNode)cubeEvent.Value;
            List<SiftOscCubeEvent> cubeEvents = new List<SiftOscCubeEvent>();

            foreach (var eventEndpoint in eventEndpoints.Children) {
              SiftOscCubeEvent siftOscCubeEvent = new SiftOscCubeEvent(cube, this.client, null, null);
              siftOscCubeEvent.generateFromYaml(eventEndpoint);
              cubeEvents.Add(siftOscCubeEvent);
            }

            this.siftOscCubeEvents.Add(cubeEventName, cubeEvents);
              }
        }
Ejemplo n.º 29
0
        public void Upgrade(AssetMigrationContext context, int currentVersion, int targetVersion, YamlMappingNode yamlAssetNode, PackageLoadingAssetFile assetFile)
        {
            dynamic asset = new DynamicYamlMapping(yamlAssetNode);

            // upgrade the asset
            UpgradeAsset(context, currentVersion, targetVersion, asset, assetFile);
            SetSerializableVersion(asset, targetVersion);
            // upgrade its base
            var baseBranch = asset["~Base"];
            if (baseBranch != null)
            {
                var baseAsset = baseBranch["Asset"];
                if (baseAsset != null)
                    UpgradeAsset(context, currentVersion, targetVersion, baseAsset, assetFile);
                SetSerializableVersion(baseAsset, targetVersion);
            }
        }
Ejemplo n.º 30
0
        public void Upgrade(int currentVersion, int targetVersion, ILogger log, YamlMappingNode yamlAssetNode)
        {
            dynamic asset = new DynamicYamlMapping(yamlAssetNode);

            // upgrade the asset
            UpgradeAsset(currentVersion, targetVersion, log, asset);
            SetSerializableVersion(asset, targetVersion);
            // upgrade its base
            var baseBranch = asset["~Base"];
            if (baseBranch != null)
            {
                var baseAsset = baseBranch["Asset"];
                if (baseAsset != null)
                    UpgradeAsset(currentVersion, targetVersion, log, baseAsset);
                SetSerializableVersion(baseAsset, targetVersion);
            }
        }
Ejemplo n.º 31
0
 /// <summary>
 /// Attempts to fetch a node like <see cref="GetNode" />,
 /// but does not throw a <c>KeyNotFoundException</c> if the node doesn't exist.
 /// Instead it returns whether the node was successfully found.
 /// </summary>
 /// <param name="mapping">The mapping to retrieve the node from.</param>
 /// <param name="key">The value of the scalar node that will be looked up.</param>
 /// <param name="returnNode">The node found, <c>null</c> if it could not be found.</param>
 /// <returns>True if the value could be found, false otherwise.</returns>
 public static bool TryGetNode(this YamlMappingNode mapping, string key, out YamlNode returnNode)
 {
     return(mapping.Children.TryGetValue(new YamlScalarNode(key), out returnNode));
 }
Ejemplo n.º 32
0
            public void Upgrade(AssetMigrationContext context, string dependencyName, PackageVersion currentVersion, PackageVersion targetVersion, YamlMappingNode yamlAssetNode, PackageLoadingAssetFile assetFile)
            {
                dynamic asset      = new DynamicYamlMapping(yamlAssetNode);
                var     baseBranch = asset[Asset.BaseProperty];

                if (baseBranch != null)
                {
                    asset[BaseProperty] = DynamicYamlEmpty.Default;
                }

                AssetUpgraderBase.SetSerializableVersion(asset, dependencyName, targetVersion);
            }
Ejemplo n.º 33
0
 public MapContext(YamlMappingNode node, IMap targetMap)
 {
     RootNode  = node;
     TargetMap = targetMap;
 }
Ejemplo n.º 34
0
        private static void ParseService(YamlMappingNode node, ConfigService service)
        {
            foreach (var child in node.Children)
            {
                var key = YamlParser.GetScalarValue(child.Key);

                switch (key)
                {
                case "build":
                    ParseBuild((child.Value as YamlMappingNode) !, service);
                    break;

                case "cap_add":
                    break;

                case "cap_drop":
                    break;

                case "cgroup_parent":
                    break;

                case "command":
                    break;

                case "configs":
                    break;

                case "container_name":
                    break;

                case "credential_spec":
                    break;

                case "depends_on":
                    break;

                case "deploy":
                    break;

                case "devices":
                    break;

                case "dns":
                    break;

                case "dns_search":
                    break;

                case "endpoint":
                    break;

                case "env_file":
                    break;

                case "environment":
                    ParseEnvironment(child.Value, service);
                    break;

                case "expose":
                    break;

                case "external_links":
                    break;

                case "extra_hosts":
                    break;

                case "healthcheck":
                    break;

                case "image":
                    service.Image = YamlParser.GetScalarValue(child.Value);
                    break;

                case "init":
                    break;

                case "isolation":
                    break;

                case "labels":
                    break;

                case "links":
                    break;

                case "logging":
                    break;

                case "network_mode":
                    break;

                case "networks":
                    break;

                case "pid":
                    break;

                case "ports":
                    ParsePortSequence((child.Value as YamlSequenceNode) !, service);
                    break;

                case "restart":
                    break;

                case "secrets":
                    break;

                case "security_opt":
                    break;

                case "stop_grace_period":
                    break;

                case "stop_signal":
                    break;

                case "sysctls":
                    break;

                case "tmpfs":
                    break;

                case "ulimits":
                    break;

                case "userns_mode":
                    break;

                case "volumes":
                    break;

                case "user":
                    break;

                case "working_dir":
                    break;

                case "domainname":
                    break;

                case "hostname":
                    break;

                case "ipc":
                    break;

                case "mac_address":
                    break;

                case "privileged":
                    break;

                case "read_only":
                    break;

                case "shm_size":
                    break;

                case "stdin_open":
                    break;

                case "tty":
                    break;

                default:
                    throw new TyeYamlException(child.Key.Start, CoreStrings.FormatUnrecognizedKey(key));
                }
            }
        }
Ejemplo n.º 35
0
 public MapContext(YamlMappingNode node, IMap targetMap)
 {
     IoCManager.InjectDependencies(this);
     RootNode  = node;
     TargetMap = targetMap;
 }
Ejemplo n.º 36
0
 internal override Task InitAsync(YamlMappingNode moduleOptions)
 {
     return(Task.CompletedTask);
 }
Ejemplo n.º 37
0
 protected override void Visit(YamlMappingNode mapping)
 {
     PushNode(options.MappingElementName);
 }
Ejemplo n.º 38
0
 public override void Visit(YamlMappingNode mapping)
 {
     Spec.Import = new ImportSpec();
     VisitChildren(mapping);
 }
Ejemplo n.º 39
0
 // We don't need to set the key to literal because all of our keys are simple one-line strings.
 internal static void AddStringMapping(this YamlMappingNode root, string key, string item)
 {
     root.Children[new YamlScalarNode(key)] = BuildStringNode(item);
 }
Ejemplo n.º 40
0
    private void NewHandleFile(string file)
    {
        bool filenameWrote = false;

        var fileContent = File.ReadAllText(file);

        //unity seem to use non valid yaml by added a "stripped" keyword on object that are linked to a prefab. Since the pareser itch on those, we remove them
        fileContent = fileContent.Replace("stripped", "");
        var input = new StringReader(fileContent);

        var yaml = new YamlStream();

        yaml.Load(input);

        YamlVisitorEvent visitor = new YamlVisitorEvent();

        visitor.referenceFinder = this;

        //map gameobject id to a hashset of monobehaviour to check for type against the searched type
        Dictionary <string, HashSet <string> > gameobjectToIdToCheck = new Dictionary <string, HashSet <string> >();

        //we store the anchor <-> node mapping, as there don't seem to be anyway to do that quickly through the YAml graph
        Dictionary <string, YamlMappingNode> parsedNodes = new Dictionary <string, YamlMappingNode>();

        foreach (var doc in yaml.Documents)
        {
            var root = (YamlMappingNode)doc.RootNode;

            parsedNodes[root.Anchor] = root;

            foreach (var node in root.Children)
            {
                var scalarNode = (YamlScalarNode)node.Key;
                if (scalarNode.Value == "MonoBehaviour")
                {//if it's a monobehaviour, it may have a list of event as child
                    YamlMappingNode sequenceNode = node.Value as YamlMappingNode;

                    visitor.havePersistentCall = false;
                    visitor.idToCheck.Clear();
                    sequenceNode.Accept(visitor);

                    if (visitor.havePersistentCall)
                    {//we found persistent call
                        string gameobjectID = ((YamlScalarNode)node.Value["m_GameObject"]["fileID"]).Value;

                        if (!gameobjectToIdToCheck.ContainsKey(gameobjectID))
                        {
                            gameobjectToIdToCheck[gameobjectID] = new HashSet <string>();
                        }

                        gameobjectToIdToCheck[gameobjectID].UnionWith(visitor.idToCheck);
                    }
                }
            }
        }

        //now we go over all our gameobject to check, and if one of the monobehaviour they ahve been associated with are of the researched type, they are added to the result
        foreach (var pair in gameobjectToIdToCheck)
        {
            bool haveOneValidCall = false;
            if (!parsedNodes.ContainsKey(pair.Key))
            {
                Debug.LogError("Tried to check an object id that don't exist : " + pair.Key);
                continue;
            }

            foreach (var id in pair.Value)
            {
                var targetNode = parsedNodes[id];
                var guid       = ((YamlScalarNode)targetNode["MonoBehaviour"]["m_Script"]["guid"]).Value;

                MonoScript script = AssetDatabase.LoadAssetAtPath <MonoScript>(AssetDatabase.GUIDToAssetPath(guid));

                if (script.GetClass() == typeSearched)
                {
                    haveOneValidCall = true;
                }
            }

            if (haveOneValidCall)
            {
                if (!filenameWrote)
                {
                    filenameWrote     = true;
                    tempSearchResult += Path.GetFileName(file) + "\n";
                }

                if (((YamlScalarNode)parsedNodes[pair.Key]["GameObject"]["m_PrefabParentObject"]["fileID"]).Value != "0")
                {//this is a prefab instance, need to find the prefab value linked to it!!
                    tempSearchResult += "\t" + "A Prefab \n";
                }
                else
                {
                    string fullPath = "";

                    //make an assumption here that the 1st component of every gameobject will always be its transform.
                    string currentGOId = pair.Key;
                    while (currentGOId != "0")
                    {
                        fullPath = parsedNodes[currentGOId]["GameObject"]["m_Name"] + (fullPath == "" ? "" : "/" + fullPath);

                        string transformID = parsedNodes[currentGOId]["GameObject"]["m_Component"][0]["component"]["fileID"].ToString();

                        Debug.Log("TransformID " + transformID);

                        string parentTransformID = parsedNodes[transformID].Children.Values.ElementAt(0)["m_Father"]["fileID"].ToString();
                        Debug.Log("Parent transform ID " + parentTransformID);
                        if (parentTransformID != "0")
                        {
                            currentGOId = parsedNodes[parentTransformID].Children.Values.ElementAt(0)["m_GameObject"]["fileID"].ToString();
                        }
                        else
                        {
                            currentGOId = "0";
                        }

                        Debug.Log("currentGOID " + currentGOId);
                    }

                    tempSearchResult += "\t" + fullPath + "\n";
                }
            }
        }
    }
Ejemplo n.º 41
0
        public void MergeTileChunks(YamlSequenceNode aChunks, YamlSequenceNode bChunks, YamlSequenceNode cChunks)
        {
            var aMap = ConvertTileChunks(aChunks);
            var bMap = ConvertTileChunks(bChunks);
            var cMap = ConvertTileChunks(cChunks);

            var xMap = new HashSet <string>();

            foreach (var kvp in aMap)
            {
                xMap.Add(kvp.Key);
            }
            // don't include b because that would mess with chunk deletion
            foreach (var kvp in cMap)
            {
                xMap.Add(kvp.Key);
            }

            foreach (var ind in xMap)
            {
                using var a  = new MemoryStream(GetChunkBytes(aMap, ind));
                using var b  = new MemoryStream(GetChunkBytes(bMap, ind));
                using var c  = new MemoryStream(GetChunkBytes(cMap, ind));
                using var aR = new BinaryReader(a);
                using var bR = new BinaryReader(b);
                using var cR = new BinaryReader(c);

                var outB = new byte[ExpectedChunkSize];

                {
                    using (var outS = new MemoryStream(outB))
                        using (var outW = new BinaryWriter(outS))

                            for (var i = 0; i < ExpectedChunkSize; i += 4)
                            {
                                var aI = aR.ReadUInt32();
                                var bI = MapTileId(bR.ReadUInt32(), TileMapFromBasedToOurs);
                                var cI = MapTileId(cR.ReadUInt32(), TileMapFromOtherToOurs);
                                // cI needs translation.

                                uint result = aI;
                                if (aI == bI)
                                {
                                    // If aI == bI then aI did not change anything, so cI always wins
                                    result = cI;
                                }
                                else if (bI != cI)
                                {
                                    // If bI != cI then cI definitely changed something (conflict, but overrides aI)
                                    result = cI;
                                    Console.WriteLine("WARNING: Tile (" + ind + ")[" + i + "] was changed by both branches.");
                                }
                                outW.Write(result);
                            }
                }

                // Actually output chunk
                if (!aMap.ContainsKey(ind))
                {
                    var res = new YamlMappingNode();
                    res.Children["ind"] = ind;
                    aMap[ind]           = res;
                }
                aMap[ind].Children["tiles"] = Convert.ToBase64String(outB);
            }
        }
Ejemplo n.º 42
0
        // Mapping specific helpers.

        /// <summary>
        /// Get the node corresponding to a scalar node with value <paramref name="key" /> inside <paramref name="mapping" />,
        /// attempting to cast it to <typeparamref name="T" />.
        /// </summary>
        /// <param name="mapping">The mapping to retrieve the node from.</param>
        /// <param name="name">The value of the scalar node that will be looked up.</param>
        /// <returns>The corresponding node casted to <typeparamref name="T" />.</returns>
        /// <exception cref="KeyNotFoundException">
        /// Thrown if <paramref name="mapping" /> does not contain a scalar with value <paramref name="key" />.
        /// </exception>
        /// <exception cref="InvalidCastException">
        /// Thrown if the node could be found, but could not be cast to <typeparamref name="T" />.
        /// </exception>
        /// <seealso cref="GetNode" />
        /// <seealso cref="TryGetNode{T}" />
        public static T GetNode <T>(this YamlMappingNode mapping, string key) where T : YamlNode
        {
            return((T)mapping[new YamlScalarNode(key)]);
        }
Ejemplo n.º 43
0
        private void ValidatePubspecFile()
        {
            YamlDocument    doc  = _pubspecDocument;
            DartProjectType type = Type;

            // Check if "name" exists
            YamlScalarNode name = doc.GetScalarNode(new[] { NameYamlNode });

            if (name == null)
            {
                throw new ArgumentException($"Missing '{NameYamlNode}' node inside '{PubspecFilename}' file.");
            }

            // Check if "description" exists
            YamlScalarNode description = doc.GetScalarNode(new[] { DescriptionYamlNode });

            if (description == null)
            {
                throw new ArgumentException($"Missing '{DescriptionYamlNode}' node inside '{PubspecFilename}' file.");
            }

            // Check if "author" exists
            YamlScalarNode author = doc.GetScalarNode(new[] { AuthorYamlNode });

            if (author == null && type == DartProjectType.Package)
            {
                throw new ArgumentException($"Missing '{AuthorYamlNode}' node inside '{PubspecFilename}' file.");
            }

            // Check if "homepage" exists
            YamlScalarNode homepage = doc.GetScalarNode(new[] { HomepageYamlNode });

            if (homepage == null && type == DartProjectType.Package)
            {
                throw new ArgumentException($"Missing '{HomepageYamlNode}' node inside '{PubspecFilename}' file.");
            }

            // Check if "version" exists
            YamlScalarNode version = doc.GetScalarNode(new[] { VersionYamlNode });

            if (version == null)
            {
                throw new ArgumentException($"Missing '{VersionYamlNode}' node inside '{PubspecFilename}' file.");
            }

            // Check if "dependencies" exists
            YamlMappingNode dependencies = doc.GetMappingNode(new[] { DependenciesYaml });

            if (dependencies == null)
            {
                throw new ArgumentException($"Missing '{DependenciesYaml}' node inside '{PubspecFilename}' file.");
            }

            // Check if "dev_dependencies" exists
            YamlMappingNode devDependencies = doc.GetMappingNode(new[] { DevDependenciesYaml });

            if (devDependencies == null)
            {
                throw new ArgumentException($"Missing '{DevDependenciesYaml}' node inside '{PubspecFilename}' file.");
            }

            // Check if "environment" exists
            YamlMappingNode environment = doc.GetMappingNode(new[] { EnvironmentYamlNode });

            if (environment == null)
            {
                throw new ArgumentException($"Missing '{EnvironmentYamlNode}' node inside '{PubspecFilename}' file.");
            }

            // Check if "sdk" exists
            YamlScalarNode sdk = doc.GetScalarNode(new[] { EnvironmentYamlNode, SdkYamlNode });

            if (sdk == null)
            {
                throw new ArgumentException($"Missing '{SdkYamlNode}' node inside '{PubspecFilename}' file.");
            }
        }
Ejemplo n.º 44
0
 protected override void Visited(YamlMappingNode mapping)
 {
     PopNode();
 }
Ejemplo n.º 45
0
        public void ToJObject_ValidInput_Works()
        {
            // Arrange
            var yaml = new YamlMappingNode()
            {
                { "spec_version", "v1.4" },
                { "identifier", "Astrogator" },
                { "$kref", "#/ckan/github/HebaruSan/Astrogator" },
                { "$vref", "#/ckan/ksp-avc" },
                { "license", "GPL-3.0" },
                {
                    "tags",
                    new YamlSequenceNode(
                        "plugin",
                        "information",
                        "control"
                        )
                },
                {
                    "resources",
                    new YamlMappingNode()
                    {
                        { "homepage", "https://forum.kerbalspaceprogram.com/index.php?/topic/155998-*" },
                        { "bugtracker", "https://github.com/HebaruSan/Astrogator/issues" },
                        { "repository", "https://github.com/HebaruSan/Astrogator" },
                    }
                },
                {
                    "recommends",
                    new YamlSequenceNode(
                        new YamlMappingNode()
                    {
                        { "name", "ModuleManager" }
                    },
                        new YamlMappingNode()
                    {
                        { "name", "LoadingTipsPlus" }
                    }
                        )
                }
            };

            // Act
            JObject json = yaml.ToJObject();

            // Assert
            Assert.AreEqual("v1.4", (string)json["spec_version"]);
            Assert.AreEqual("Astrogator", (string)json["identifier"]);
            Assert.AreEqual("#/ckan/github/HebaruSan/Astrogator", (string)json["$kref"]);
            Assert.AreEqual("#/ckan/ksp-avc", (string)json["$vref"]);
            Assert.AreEqual("GPL-3.0", (string)json["license"]);

            CollectionAssert.AreEqual(
                new string[] { "plugin", "information", "control" },
                (json["tags"] as JArray).Select(elt => (string)elt)
                );
            Assert.AreEqual(
                "https://forum.kerbalspaceprogram.com/index.php?/topic/155998-*",
                (string)json["resources"]["homepage"]
                );
            Assert.AreEqual(
                "https://github.com/HebaruSan/Astrogator/issues",
                (string)json["resources"]["bugtracker"]
                );
            Assert.AreEqual(
                "https://github.com/HebaruSan/Astrogator",
                (string)json["resources"]["repository"]
                );
            Assert.AreEqual("ModuleManager", (string)json["recommends"][0]["name"]);
            Assert.AreEqual("LoadingTipsPlus", (string)json["recommends"][1]["name"]);
        }
        /// <summary>
        /// Parses the specified file.
        /// </summary>
        public override void ParseFile(string absolutePath)
        {
            using (StreamReader fileReader = new StreamReader(new FileStream(absolutePath, FileMode.Open, FileAccess.Read)))
            {
                YamlStream stream = new YamlStream();
                stream.Load(fileReader);
                YamlDocument    document = stream.Documents[0];
                YamlMappingNode rootNode = (YamlMappingNode)document.RootNode;

                YamlScalarNode guidNode      = (YamlScalarNode)rootNode.Children["guid"];
                Guid           assetGuid     = new Guid(guidNode.Value);
                string         assetUniqueId = assetGuid.ToString();

                // determine the asset's default file id
                int defaultFileId = 0;
                foreach (string key in rootNode.Children.Keys)
                {
                    if (key.EndsWith("Importer", StringComparison.OrdinalIgnoreCase))
                    {
                        int classId;
                        if (UnityClassIds.TryGetClassIdByImporterName(key, out classId))
                        {
                            defaultFileId = classId * 100000;
                            break;
                        }
                    }
                }
                UnityObjectKey defaultAssetKey = new UnityObjectKey(assetGuid, defaultFileId);

                bool     isFolderAsset = false;
                YamlNode folderAssetNode;
                if (rootNode.Children.TryGetValue("folderAsset", out folderAssetNode))
                {
                    YamlScalarNode folderAssetScalarNode = (YamlScalarNode)folderAssetNode;
                    isFolderAsset = folderAssetScalarNode.Value == "yes";
                }

                if (isFolderAsset)
                {
                    string folderPath = Path.Combine(Path.GetDirectoryName(absolutePath), Path.GetFileNameWithoutExtension(absolutePath));
                    ObjectDatabase.MapFolderObject(folderPath, assetUniqueId);
                    ObjectDatabase.AddObject(assetUniqueId, new UnityFolder(absolutePath, assetGuid));
                }
                else
                {
                    // metas shouldn't override assets we've already parsed
                    ObjectDatabase.AddPlaceholderObject(assetUniqueId, new UnityAsset(absolutePath, assetUniqueId));
                    if (defaultAssetKey.FileId != 0)
                    {
                        ObjectDatabase.AddObject(defaultAssetKey.ToString(), new UnityDefaultAsset(assetUniqueId, defaultAssetKey));
                    }
                }

                // check for sprites
                YamlNode textureImporterNode;
                if (rootNode.Children.TryGetValue("TextureImporter", out textureImporterNode))
                {
                    YamlMappingNode textureImporterMappingNode = (YamlMappingNode)textureImporterNode;
                    YamlNode        fileIDToRecycleNameNode;
                    if (textureImporterMappingNode.Children.TryGetValue("fileIDToRecycleName", out fileIDToRecycleNameNode))
                    {
                        YamlMappingNode fileIDToRecycleNameMappingNode = (YamlMappingNode)fileIDToRecycleNameNode;
                        foreach (var kv in fileIDToRecycleNameMappingNode.Children)
                        {
                            string         fileIdStr = ((YamlScalarNode)kv.Key).Value;
                            string         name      = ((YamlScalarNode)kv.Value).Value;
                            long           fileId    = long.Parse(fileIdStr);
                            UnityObjectKey spriteKey = new UnityObjectKey(assetGuid, fileId);
                            ObjectDatabase.AddObject(spriteKey.ToString(), new UnitySprite(assetUniqueId, name, spriteKey));
                        }
                    }

                    YamlNode spriteModeNode;
                    if (textureImporterMappingNode.Children.TryGetValue("spriteMode", out spriteModeNode))
                    {
                        YamlScalarNode spriteModeScalarNode = (YamlScalarNode)spriteModeNode;
                        if (spriteModeScalarNode.Value == "1")
                        {
                            // single sprite
                            string         name      = Path.GetFileNameWithoutExtension(absolutePath);
                            UnityObjectKey spriteKey = new UnityObjectKey(assetGuid, 21300000);
                            ObjectDatabase.AddObject(spriteKey.ToString(), new UnitySprite(assetUniqueId, name, spriteKey));
                        }
                    }
                }
            }
        }
Ejemplo n.º 47
0
            // Create custom object serializers that will correctly allow data to be overriden by the map file.
            ObjectSerializer IEntityLoadContext.GetComponentSerializer(string componentName, YamlMappingNode protoData)
            {
                if (CurrentReadingEntityComponents == null)
                {
                    throw new InvalidOperationException();
                }

                if (CurrentReadingEntityComponents.TryGetValue(componentName, out var mapping))
                {
                    var list = new List <YamlMappingNode> {
                        mapping
                    };
                    if (protoData != null)
                    {
                        list.Add(protoData);
                    }
                    return(YamlObjectSerializer.NewReader(list, this));
                }

                return(YamlObjectSerializer.NewReader(protoData, this));
            }
        internal void ParseDeploymentParameters(string traceContext, YamlMappingNode rootDeployNode, HashSet <string> ignoredKeys)
        {
            foreach (var item in rootDeployNode)
            {
                var key = item.Key.ToString();
                switch (key)
                {
                case DockerComposeConstants.DeploymentModeKey:
                {
                    var value = item.Value.ToString();
                    if (value != DockerComposeConstants.DeploymentModeReplicatedValue)
                    {
                        throw new FabricComposeException(
                                  string.Format("{0} - Only 'replicated' deployment mode is supported. Specified {1}", traceContext, value));
                    }
                    break;
                }

                case DockerComposeConstants.ReplicasKey:
                {
                    var value = DockerComposeUtils.ValidateAndGetScalar(traceContext, DockerComposeConstants.ReplicasKey, item.Value).ToString();
                    try
                    {
                        this.InstanceCount = Int32.Parse(value);
                    }
                    catch (Exception e)
                    {
                        throw new FabricComposeException(string.Format("{0} - Parsing 'replicas' with value {1} failed", e, value));
                    }
                    break;
                }

                case DockerComposeConstants.PlacementKey:
                {
                    this.ParsePlacementConstraints(
                        DockerComposeUtils.GenerateTraceContext(traceContext, DockerComposeConstants.PlacementKey),
                        DockerComposeUtils.ValidateAndGetMapping(traceContext, DockerComposeConstants.PlacementKey, item.Value));
                    break;
                }

                case DockerComposeConstants.ResourcesKey:
                {
                    this.ParseResourceGovernance(
                        DockerComposeUtils.GenerateTraceContext(traceContext, DockerComposeConstants.ResourcesKey),
                        DockerComposeUtils.ValidateAndGetMapping(traceContext, DockerComposeConstants.ResourcesKey, item.Value),
                        ignoredKeys);
                    break;
                }

                case DockerComposeConstants.LabelsKey:
                {
                    break;
                }

                default:
                {
                    ignoredKeys.Add(key);
                    break;
                }
                }
            }
        }
Ejemplo n.º 49
0
 public MapContext()
 {
     IoCManager.InjectDependencies(this);
     RootNode = new YamlMappingNode();
 }
Ejemplo n.º 50
0
        public static void Run()
        {
            var pluginImporters = PluginImporter.GetAllImporters();

            foreach (var pluginImporter in pluginImporters)
            {
                // Skip native plugins
                if (pluginImporter.isNativePlugin)
                {
                    continue;
                }

                // Skip built-in Unity plugins, which are referenced by full path
                if (!pluginImporter.assetPath.StartsWith("Assets"))
                {
                    continue;
                }

                var assemblyPath = Path.Combine(Directory.GetParent(Application.dataPath).FullName, pluginImporter.assetPath);

                var assembly = Codebase.assemblies.FirstOrDefault(a => !string.IsNullOrEmpty(a.Location) && new Uri(assemblyPath) == new Uri(a.Location));

                // Skip if plugin importer has no matching assembly
                if (assembly == null)
                {
                    continue;
                }

                var plugin = PluginContainer.plugins.FirstOrDefault(p => p.runtimeAssembly == assembly);

                // Skip if the assembly is not mapped to a Ludiq plugin
                if (plugin == null)
                {
                    continue;
                }

                var mappableTypes = assembly.GetTypesSafely().Where(t => typeof(UnityObject).IsAssignableFrom(t));

                // Skip assemblies without any mappable types
                if (!mappableTypes.Any())
                {
                    continue;
                }

                // Create a dictionary of type-to-icon mapping
                // The key is the fully qualified type name.
                // The value is the Unity-assigned GUID of the icon file.
                var iconsByTypes = new Dictionary <string, string>();

                foreach (var type in mappableTypes)
                {
                    var iconAssetPath = PathUtility.FromProject(Path.Combine(plugin.paths.iconMap, type.CSharpFileName(true, false) + ".png"));

                    var typeIcon = AssetDatabase.LoadAssetAtPath <Texture2D>(iconAssetPath);

                    // Skip if type icon loading fails
                    if (typeIcon == null)
                    {
                        continue;
                    }

                    iconsByTypes.Add(type.ToString(), AssetDatabase.AssetPathToGUID(iconAssetPath));
                }

                // Modify the matching meta file's YAML
                var metaFilePath = assemblyPath + ".meta";

                try
                {
                    var yaml = new YamlStream();

                    new FileInfo(metaFilePath).IsReadOnly = false;

                    using (var input = new StreamReader(metaFilePath))
                    {
                        yaml.Load(input);

                        // Dig down the PluginImporter.iconMap node and clear it
                        var rootNode           = (YamlMappingNode)yaml.Documents[0].RootNode;
                        var pluginImporterNode = (YamlMappingNode)rootNode.Children["PluginImporter"];
                        var iconMapNode        = (YamlMappingNode)pluginImporterNode.Children["iconMap"];

                        iconMapNode.Children.Clear();

                        AddIconMap(iconMapNode, iconsByTypes);

                        iconMapNode.Style = MappingStyle.Block;
                    }

                    // The only way I found to get Unity to release its freaking file lock
                    File.Delete(metaFilePath);

                    using (var output = new StreamWriter(metaFilePath))
                    {
                        yaml.Save(output, false);
                    }

                    Debug.Log($"Added icon mapping.\n{metaFilePath}");
                }
                catch (Exception ex)
                {
                    Debug.LogWarning($"Failed to traverse plugin meta file '{Path.GetFileName(metaFilePath)}' for icon mapping: \n{ex}");

                    if (iconsByTypes.Count > 0)
                    {
                        // Unity broke Yaml specification in 5.5: (... ugh)
                        // https://fogbugz.unity3d.com/default.asp?909364_td7ssft6c2cgh3i2
                        // YamlDotNet won't be able to load the meta files.
                        // Therefore, we'll have to add the iconmap manually in the meta files.
                        // To facilitate that process, we'll output the proper required Yaml
                        // to the console for each file.

                        var iconMapNode = new YamlMappingNode();
                        AddIconMap(iconMapNode, iconsByTypes);
                        iconMapNode.Style = MappingStyle.Block;
                        var rootNode = new YamlMappingNode {
                            { "iconMap", iconMapNode }
                        };
                        var yaml   = new YamlStream(new YamlDocument(rootNode));
                        var output = new StringWriter();
                        yaml.Save(output, false);
                        output.Dispose();
                        var @string  = output.ToString();
                        var indented = "";
                        foreach (var line in @string.Split('\n'))
                        {
                            indented += "  " + line + "\n";
                        }
                        Debug.Log($"Manual iconMap node for '{Path.GetFileName(metaFilePath)}':\n\n{indented}\n\n");
                    }
                }
            }

            AssetDatabase.Refresh();

            AnnotationDisabler.DisableGizmos();
        }
Ejemplo n.º 51
0
            ObjectSerializer IEntityFinishContext.GetComponentSerializer(string componentName, YamlMappingNode protoData)
            {
                if (CurrentReadingEntityComponents == null)
                {
                    throw new InvalidOperationException();
                }

                if (CurrentReadingEntityComponents.TryGetValue(componentName, out var mapping))
                {
                    return(YamlObjectSerializer.NewReader(new List <YamlMappingNode> {
                        mapping, protoData
                    }, this));
                }

                return(YamlObjectSerializer.NewReader(protoData, this));
            }
Ejemplo n.º 52
0
        protected override StorageAccountResourceV1 DeserializeResource(YamlMappingNode node)
        {
            var storageAccountResource = base.DeserializeResource(node);

            return(new BlobStorageResourceV1(storageAccountResource));
        }
Ejemplo n.º 53
0
 public MapContext()
 {
     RootNode = new YamlMappingNode();
 }
Ejemplo n.º 54
0
        public override void LoadData(YamlMappingNode node)
        {
            base.LoadData(node);

            var delay = 0.8f;

            var openSound  = node.GetNode("open_sound").AsString();
            var closeSound = node.GetNode("close_sound").AsString();
            var denySound  = node.GetNode("deny_sound").AsString();

            if (node.TryGetNode("animation_time", out var yamlNode))
            {
                delay = yamlNode.AsFloat();
            }

            CloseAnimation = new Animation {
                Length = TimeSpan.FromSeconds(delay)
            };
            {
                var flick = new AnimationTrackSpriteFlick();
                CloseAnimation.AnimationTracks.Add(flick);
                flick.LayerKey = DoorVisualLayers.Base;
                flick.KeyFrames.Add(new AnimationTrackSpriteFlick.KeyFrame("closing", 0f));

                var flickUnlit = new AnimationTrackSpriteFlick();
                CloseAnimation.AnimationTracks.Add(flickUnlit);
                flickUnlit.LayerKey = DoorVisualLayers.BaseUnlit;
                flickUnlit.KeyFrames.Add(new AnimationTrackSpriteFlick.KeyFrame("closing_unlit", 0f));

                var flickMaintenancePanel = new AnimationTrackSpriteFlick();
                CloseAnimation.AnimationTracks.Add(flickMaintenancePanel);
                flickMaintenancePanel.LayerKey = WiresVisualizer.WiresVisualLayers.MaintenancePanel;
                flickMaintenancePanel.KeyFrames.Add(new AnimationTrackSpriteFlick.KeyFrame("panel_closing", 0f));

                var sound = new AnimationTrackPlaySound();
                CloseAnimation.AnimationTracks.Add(sound);
                sound.KeyFrames.Add(new AnimationTrackPlaySound.KeyFrame(closeSound, 0));
            }

            OpenAnimation = new Animation {
                Length = TimeSpan.FromSeconds(delay)
            };
            {
                var flick = new AnimationTrackSpriteFlick();
                OpenAnimation.AnimationTracks.Add(flick);
                flick.LayerKey = DoorVisualLayers.Base;
                flick.KeyFrames.Add(new AnimationTrackSpriteFlick.KeyFrame("opening", 0f));

                var flickUnlit = new AnimationTrackSpriteFlick();
                OpenAnimation.AnimationTracks.Add(flickUnlit);
                flickUnlit.LayerKey = DoorVisualLayers.BaseUnlit;
                flickUnlit.KeyFrames.Add(new AnimationTrackSpriteFlick.KeyFrame("opening_unlit", 0f));

                var flickMaintenancePanel = new AnimationTrackSpriteFlick();
                OpenAnimation.AnimationTracks.Add(flickMaintenancePanel);
                flickMaintenancePanel.LayerKey = WiresVisualizer.WiresVisualLayers.MaintenancePanel;
                flickMaintenancePanel.KeyFrames.Add(new AnimationTrackSpriteFlick.KeyFrame("panel_opening", 0f));

                var sound = new AnimationTrackPlaySound();
                OpenAnimation.AnimationTracks.Add(sound);
                sound.KeyFrames.Add(new AnimationTrackPlaySound.KeyFrame(openSound, 0));
            }

            DenyAnimation = new Animation {
                Length = TimeSpan.FromSeconds(0.3f)
            };
            {
                var flick = new AnimationTrackSpriteFlick();
                DenyAnimation.AnimationTracks.Add(flick);
                flick.LayerKey = DoorVisualLayers.BaseUnlit;
                flick.KeyFrames.Add(new AnimationTrackSpriteFlick.KeyFrame("deny", 0f));

                var sound = new AnimationTrackPlaySound();
                DenyAnimation.AnimationTracks.Add(sound);
                sound.KeyFrames.Add(new AnimationTrackPlaySound.KeyFrame(denySound, 0, () => AudioHelpers.WithVariation(0.05f)));
            }
        }
Ejemplo n.º 55
0
        internal void MergeNamespaceIntoToc(YamlSequenceNode toc)
        {
            bool MatchByUid(YamlNode n, string key)
            {
                var uid = new YamlScalarNode(this.uid);

                if (n is YamlMappingNode map)
                {
                    if (map.Children != null && map.Children.TryGetValue(new YamlScalarNode(Utils.UidKey), out YamlNode node))
                    {
                        if (node is YamlScalarNode valueNode)
                        {
                            return(valueNode.Equals(uid));
                        }
                    }
                }
                return(false);
            }

            string?TryGetUid(YamlNode node)
            {
                if (node is YamlMappingNode mappingNode)
                {
                    mappingNode.Children.TryGetValue(Utils.UidKey, out var uidNode);
                    return((uidNode as YamlScalarNode)?.Value);
                }
                else
                {
                    return(null);
                }
            }

            string?TryGetName(YamlNode node)
            {
                if (node is YamlMappingNode mappingNode)
                {
                    mappingNode.Children.TryGetValue(Utils.NameKey, out var nameNode);
                    return((nameNode as YamlScalarNode)?.Value);
                }
                else
                {
                    return(null);
                }
            }

            int CompareUids(YamlNode node1, YamlNode node2) =>
            string.Compare(
                TryGetUid(node1),
                TryGetUid(node2));

            var namespaceNode             = toc.Children.SingleOrDefault(c => MatchByUid(c, this.uid)) as YamlMappingNode;
            YamlSequenceNode?itemListNode = null;

            if (namespaceNode == null)
            {
                namespaceNode = new YamlMappingNode();
                namespaceNode.AddStringMapping(Utils.UidKey, this.uid);
                namespaceNode.AddStringMapping(Utils.NameKey, this.name);
                toc.Add(namespaceNode);
                toc.Children.Sort((node1, node2) => CompareUids(node1, node2));
            }
            else
            {
                YamlNode itemsNode;
                if (namespaceNode.Children.TryGetValue(new YamlScalarNode(Utils.ItemsKey), out itemsNode))
                {
                    itemListNode = itemsNode as YamlSequenceNode;
                }
            }
            if (itemListNode == null)
            {
                itemListNode = new YamlSequenceNode();
                namespaceNode.Add(Utils.ItemsKey, itemListNode);
            }

            var itemsByUid = this.items
                             .GroupBy(item => item.Uid)
                             .ToDictionary(
                group => group.Key,
                group => group
                .Select(item => item.Name)
                .Single());

            // Update itemsByUid with any items that may already exist.
            foreach (var existingChild in itemListNode.Children)
            {
                var uid = TryGetUid(existingChild);
                if (uid != null)
                {
                    itemsByUid[uid] = TryGetName(existingChild) ?? "";
                }
            }

            itemListNode.Children.Clear();
            foreach (var(uid, name) in itemsByUid.OrderBy(item => item.Key))
            {
                itemListNode.Add(Utils.BuildMappingNode(
                                     Utils.NameKey, name, Utils.UidKey, uid));
            }
        }
Ejemplo n.º 56
0
 public virtual void LoadData(YamlMappingNode parameters)
 {
 }
Ejemplo n.º 57
0
        /// <summary>
        /// Populates a YAML mapping node with information describing a Q# resolved type.
        /// </summary>
        /// <param name="t">The resolved type to describe</param>
        /// <param name="map">The YAML node to populate</param>
        internal static void ResolvedTypeToYaml(ResolvedType t, YamlMappingNode map)
        {
            IEnumerable <ResolvedType> FlattenType(ResolvedType ty)
            {
                var resol = ty.Resolution;

                if (resol.IsTupleType)
                {
                    var elements = ((QsTypeKind.TupleType)resol).Item;
                    foreach (var element in elements)
                    {
                        foreach (var subelement in FlattenType(element))
                        {
                            yield return(subelement);
                        }
                    }
                }
                else
                {
                    yield return(ty);
                }
            }

            void CallableCore(ResolvedType inputType, ResolvedType outputType, IEnumerable <QsFunctor> functors)
            {
                var types = new YamlSequenceNode();
                var input = new YamlMappingNode();

                input.Add("types", types);
                foreach (var argType in FlattenType(inputType))
                {
                    var argNode = new YamlMappingNode();
                    ResolvedTypeToYaml(argType, argNode);
                    types.Add(argNode);
                }
                map.Add("input", input);
                var otypes = new YamlSequenceNode();
                var output = new YamlMappingNode();

                output.Add("types", otypes);
                var otype = new YamlMappingNode();

                ResolvedTypeToYaml(outputType, otype);
                otypes.Add(otype);
                map.Add("output", output);
            }

            var resolution = t.Resolution;

            if (resolution.IsUnitType)
            {
                map.AddStringMapping("isPrimitive", "true");
                map.AddStringMapping("uid", "Unit");
            }
            else if (resolution.IsInt || resolution.IsBigInt || resolution.IsDouble || resolution.IsBool || resolution.IsString ||
                     resolution.IsQubit || resolution.IsResult || resolution.IsPauli || resolution.IsRange)
            {
                map.AddStringMapping("isPrimitive", "true");
                map.AddStringMapping("uid", ResolvedTypeToString(t));
            }
            else if (resolution.IsArrayType)
            {
                map.AddStringMapping("isArray", "true");
                var elementType = ((QsTypeKind.ArrayType)resolution).Item;
                if (elementType.Resolution.IsArrayType)
                {
                    var seq  = new YamlSequenceNode();
                    var node = new YamlMappingNode();
                    ResolvedTypeToYaml(elementType, node);
                    seq.Add(node);
                    map.Add(BuildStringNode("types"), seq);
                }
                else
                {
                    ResolvedTypeToYaml(elementType, map);
                }
            }
            else if (resolution.IsTupleType)
            {
                var elements = ((QsTypeKind.TupleType)resolution).Item;
                var seq      = new YamlSequenceNode();
                foreach (var element in elements)
                {
                    var node = new YamlMappingNode();
                    ResolvedTypeToYaml(element, node);
                    seq.Add(node);
                }
                map.Add(BuildStringNode("types"), seq);
            }
            else if (resolution.IsUserDefinedType)
            {
                var udtName = ((QsTypeKind.UserDefinedType)resolution).Item;
                map.AddStringMapping("uid", (udtName.Namespace.Value + "." + udtName.Name.Value).ToLowerInvariant());
            }
            else if (resolution.IsTypeParameter)
            {
                var typeParam = ((QsTypeKind.TypeParameter)resolution).Item;
                map.AddStringMapping("uid", "'" + typeParam.TypeName.Value);
                map.AddStringMapping("isLocal", "true");
            }
            else if (resolution.IsOperation)
            {
                var op         = ((QsTypeKind.Operation)resolution);
                var inputType  = op.Item1.Item1;
                var outputType = op.Item1.Item2;
                var functors   = op.Item2.Characteristics.SupportedFunctors.ValueOr(ImmutableHashSet <QsFunctor> .Empty);

                map.AddStringMapping("isOperation", "true");
                CallableCore(inputType, outputType, functors);
                if (!functors.IsEmpty)
                {
                    var seq = new YamlSequenceNode();
                    map.Add("functors", seq);
                    foreach (var f in functors)
                    {
                        if (f.IsAdjoint)
                        {
                            seq.AddString("Adjoint");
                        }
                        else if (f.IsControlled)
                        {
                            seq.AddString("Controlled");
                        }
                    }
                }
            }
            else if (resolution.IsFunction)
            {
                var fct        = ((QsTypeKind.Function)resolution);
                var inputType  = fct.Item1;
                var outputType = fct.Item2;

                map.AddStringMapping("isFunction", "true");
                CallableCore(inputType, outputType, Enumerable.Empty <QsFunctor>());
            }
        }
Ejemplo n.º 58
0
 /// <summary>
 /// Same as <see cref="GetNode{T}" />, but has <c>T</c> at <c>YamlNode</c>.
 /// </summary>
 /// <param name="mapping">The mapping to retrieve the node from.</param>
 /// <param name="key">The value of the scalar node that will be looked up.</param>
 /// <exception cref="KeyNotFoundException">
 /// Thrown if <paramref name="mapping" /> does not contain a scalar with value <paramref name="key" />.
 /// </exception>
 /// <returns>The node found.</returns>
 public static YamlNode GetNode(this YamlMappingNode mapping, string key)
 {
     return(mapping.GetNode <YamlNode>(key));
 }
Ejemplo n.º 59
0
 /// <summary>
 /// Copies a <see cref="YamlMappingNode" /> to a dictionary by using scalar values as keys for the dictionary.
 /// </summary>
 /// <param name="mapping">The mapping to copy from.</param>
 /// <returns>The dictionary.</returns>
 public static Dictionary <string, YamlNode> YamlMappingToDict(YamlMappingNode mapping)
 {
     return(mapping.ToDictionary(p => p.Key.AsString(), p => p.Value));
 }
Ejemplo n.º 60
0
 protected override void Visited(YamlMappingNode mapping)
 {
     events.Add(new YamlNodeEvent(YamlNodeEventType.MappingEnd, mapping.Anchor, mapping.Tag, null));
 }