Exemplo n.º 1
0
        public void TestInvalidListOfStrings()
        {
            var resolvers = new ObjectLiteral[] { CreateObject("priority", 1), CreateObject("type", "1") };

            foreach (var resolversList in GetDifferentListRepresenations(resolvers))
            {
                try
                {
                    ConfigurationConverter.ConvertObjectLiteralToConfiguration(
                        m_context,
                        CreateObject("allowedEnvironmentVariables", resolversList));
                    XAssert.Fail("Expected to fail with ConversionException when trying to set ObjectLiteral[] to List<string>");
                }
                catch (ConversionException)
                {
                    // OK, as expected
                }
            }
        }
Exemplo n.º 2
0
        public void TestValidListOfObjectLiteralsButInvalidResolvers()
        {
            var resolvers = new ObjectLiteral[] { CreateObject("priority", 2, "kind", "UnknownResolver") };

            foreach (var resolversList in GetDifferentListRepresenations(resolvers))
            {
                try
                {
                    ConfigurationConverter.ConvertObjectLiteralToConfiguration(
                        m_context,
                        CreateObject("resolvers", resolversList));
                    XAssert.Fail("Expected to fail with ConversionException when trying to set string[] to List<IResolver>");
                }
                catch (ConversionException)
                {
                    // OK, as expected
                }
            }
        }
Exemplo n.º 3
0
        /// <inheritdoc />
        IConfiguration IConfigurationProcessor.InterpretConfiguration(
            AbsolutePath primaryConfigurationFile,
            ICommandLineConfiguration commandLineConfiguration)
        {
            Contract.Requires(primaryConfigurationFile.IsValid);
            Contract.Requires(commandLineConfiguration != null);

            var configObjectLiteral = ParseAndInterpretConfigFile(primaryConfigurationFile);

            if (configObjectLiteral == null)
            {
                // Error has been reported already
                return(null);
            }

            // Apply Additional configurations from the commandline
            foreach (var additionalConfigurationFile in commandLineConfiguration.Startup.AdditionalConfigFiles)
            {
                configObjectLiteral = ParseAndInterpretConfigFile(additionalConfigurationFile, configObjectLiteral);
            }

            // TODO: user override is not really working now. Fix me!

            try
            {
                // Merge the object literal with the initial C# defaults.
                return(ConfigurationConverter.AugmentConfigurationWith(Context, commandLineConfiguration, configObjectLiteral));
            }
            catch (ConversionException conversionException)
            {
                var configFileString = primaryConfigurationFile.ToString(Context.PathTable);
                Logger.ReportConversionException(
                    Context.LoggingContext,
                    new Location()
                {
                    File = configFileString
                },
                    Name,
                    GetConversionExceptionMessage(primaryConfigurationFile, conversionException));
                return(null);
            }
        }
Exemplo n.º 4
0
        public void TestInvalidListOfPaths()
        {
            string PathStr0 = A("x", "temp", "file1.txt");
            string PathStr1 = "file2.txt";

            foreach (var configImportsList in GetDifferentListRepresenations(new[] { PathStr0, PathStr1 }))
            {
                try
                {
                    ConfigurationConverter.ConvertObjectLiteralToConfiguration(
                        m_context,
                        CreateObject(
                            "startup",
                            CreateObject("additionalConfigFiles", configImportsList)));
                    XAssert.Fail("Expected to fail with ConversionException when trying to set string[] containing invalid path strings to List<Path>");
                }
                catch (ConversionException)
                {
                    // OK, as expected
                }
            }
        }
Exemplo n.º 5
0
 private static void AnalyzeSource(INode node, DiagnosticContext context)
 {
     ConfigurationConverter.ValidatePackageConfiguration(context.SourceFile, context.Logger, context.LoggingContext);
 }
Exemplo n.º 6
0
        private static object CreateInstance(BuildXLContext context, Type type, bool booleanDefault)
        {
            string path = A("x", "path");

            type = GetNonNullableType(type);

            if (type == typeof(bool))
            {
                return(booleanDefault);
            }

            if (type == typeof(double))
            {
                return((double)0.23423);
            }

            if (type == typeof(byte))
            {
                return((byte)123);
            }

            if (type == typeof(sbyte))
            {
                return((sbyte)123);
            }

            if (type == typeof(short))
            {
                return((short)123);
            }

            if (type == typeof(ushort))
            {
                return((ushort)123);
            }

            if (type == typeof(int))
            {
                return(123);
            }

            if (type == typeof(uint))
            {
                return((uint)123);
            }

            if (type == typeof(long))
            {
                return((long)123);
            }

            if (type == typeof(ulong))
            {
                return((ulong)123);
            }

            if (type == typeof(string))
            {
                return("nonDefaultString");
            }

            if (type == typeof(ModuleId))
            {
                return(new ModuleId(123));
            }

            if (type == typeof(LocationData))
            {
                return(new LocationData(AbsolutePath.Create(context.PathTable, path), 12, 23));
            }

            if (type == typeof(AbsolutePath))
            {
                return(AbsolutePath.Create(context.PathTable, path));
            }

            if (type == typeof(RelativePath))
            {
                string relativePath = R("rel1", "dir1", "path");
                return(RelativePath.Create(context.StringTable, relativePath));
            }

            if (type == typeof(FileArtifact))
            {
                return(FileArtifact.CreateSourceFile(AbsolutePath.Create(context.PathTable, path)));
            }

            if (type == typeof(PathAtom))
            {
                return(PathAtom.Create(context.StringTable, "atom"));
            }

            if (type == typeof(global::BuildXL.Utilities.LineInfo))
            {
                return(new global::BuildXL.Utilities.LineInfo(1, 1));
            }

            if (type.GetTypeInfo().IsEnum)
            {
                bool first = true;
                foreach (var value in Enum.GetValues(type))
                {
                    if (!first)
                    {
                        return(value);
                    }

                    first = false;
                }

                XAssert.Fail($"Enum {type.FullName} doesn't have more than one value, so can't pick the second one.");
            }

            if (type.GetTypeInfo().IsGenericType)
            {
                var generic = type.GetGenericTypeDefinition();

                if (generic == typeof(IReadOnlyList <>))
                {
                    // Treat IReadOnlyList as if it was List
                    type    = typeof(List <>).MakeGenericType(type.GenericTypeArguments[0]);
                    generic = type.GetGenericTypeDefinition();
                }

                if (generic == typeof(List <>))
                {
                    var newList = (IList)Activator.CreateInstance(type);
                    newList.Add(CreateInstance(context, type.GenericTypeArguments[0], booleanDefault));
                    return(newList);
                }

                if (generic == typeof(IReadOnlyDictionary <,>))
                {
                    // Treat IReadOnlyList as if it was List
                    type    = typeof(Dictionary <,>).MakeGenericType(type.GenericTypeArguments[0], type.GenericTypeArguments[1]);
                    generic = type.GetGenericTypeDefinition();
                }

                if (generic == typeof(Dictionary <,>))
                {
                    var newDictionary = (IDictionary)Activator.CreateInstance(type);
                    newDictionary.Add(
                        CreateInstance(context, type.GenericTypeArguments[0], booleanDefault),
                        CreateInstance(context, type.GenericTypeArguments[1], booleanDefault));
                    return(newDictionary);
                }
            }

            if (type.GetTypeInfo().IsInterface)
            {
                // Treat interfaces as if it was the mutable class
                type = ConfigurationConverter.FindImplementationType(
                    type,
                    ObjectLiteral.Create(new List <Binding>(), default(LineInfo), AbsolutePath.Invalid),

                    // Return a SourceResolver to instantiate
                    () => "SourceResolver");
            }

            if (type.GetTypeInfo().IsClass)
            {
                var instance = Activator.CreateInstance(type);
                PopulateObject(context, type, instance, booleanDefault);
                return(instance);
            }

            XAssert.Fail($"Don't know how to create objects for this type: {type.FullName}.");
            return(null);
        }
Exemplo n.º 7
0
        public static void ValidateEqual(BuildXLContext context, Type type, object expected, object actual, string objPath, Remapper remapper)
        {
            type = GetNonNullableType(type);

            if (type == typeof(bool))
            {
                XAssert.AreEqual((bool)expected, (bool)actual, $"{nameof(Boolean)} values don't match for objPath: {objPath}");
                return;
            }

            if (type == typeof(int) || type == typeof(short) || type == typeof(sbyte) || type == typeof(long))
            {
                XAssert.AreEqual(
                    Convert.ToInt64(expected),
                    Convert.ToInt64(actual),
                    $"Numeric values don't match for objPath: {objPath}");
                return;
            }

            if (type == typeof(uint) || type == typeof(ushort) || type == typeof(byte) || type == typeof(ulong))
            {
                XAssert.AreEqual(
                    Convert.ToUInt64(expected),
                    Convert.ToUInt64(actual),
                    $"Numeric values don't match for objPath: {objPath}");
                return;
            }

            if (type == typeof(double))
            {
                XAssert.AreEqual(
                    Convert.ToDouble(expected),
                    Convert.ToDouble(actual),
                    $"Numeric values don't match for objPath: {objPath}");
                return;
            }

            if (type == typeof(string))
            {
                XAssert.AreEqual((string)expected, (string)actual, $"{nameof(String)} values don't match for objPath: {objPath}");
                return;
            }

            if (type == typeof(ModuleId))
            {
                XAssert.AreEqual(
                    (ModuleId)expected,
                    (ModuleId)actual,
                    $"{nameof(ModuleId)} id values don't match for objPath: {objPath}");
                return;
            }

            if (type == typeof(LocationData))
            {
                AssertEqualLocationData(context, objPath, remapper, (LocationData)expected, (LocationData)actual);
                return;
            }

            if (type == typeof(RelativePath))
            {
                AssertEqualRelativePaths(context, objPath, remapper, (RelativePath)expected, (RelativePath)actual);
                return;
            }

            if (type == typeof(AbsolutePath))
            {
                AssertEqualAbsolutePaths(context, objPath, remapper, (AbsolutePath)expected, (AbsolutePath)actual);
                return;
            }

            if (type == typeof(FileArtifact))
            {
                AssertEqualFileArtifacts(context, objPath, remapper, (FileArtifact)expected, (FileArtifact)actual);
                return;
            }

            if (type == typeof(PathAtom))
            {
                AssertEqualPathAtoms(context, objPath, remapper, (PathAtom)expected, (PathAtom)actual);
                return;
            }

            if (type == typeof(SymbolAtom))
            {
                XAssert.AreEqual((SymbolAtom)expected, (SymbolAtom)actual, $"{nameof(SymbolAtom)} values don't match for objPath: {objPath}");
                return;
            }

            if (type == typeof(global::BuildXL.Utilities.LineInfo))
            {
                XAssert.AreEqual(
                    (global::BuildXL.Utilities.LineInfo)expected,
                    (global::BuildXL.Utilities.LineInfo)actual,
                    $"{nameof(global::BuildXL.Utilities.LineInfo)} values don't match for objPath: {objPath}");
                return;
            }

            if (type == typeof(LineInfo))
            {
                XAssert.AreEqual(
                    (LineInfo)expected,
                    (LineInfo)actual,
                    $"{nameof(LineInfo)} values don't match for objPath: {objPath}");
                return;
            }

            if (type.GetTypeInfo().IsEnum)
            {
                XAssert.AreEqual((Enum)expected, (Enum)actual, $"Enum values don't match for objPath: {objPath}");
                return;
            }

            if (type.GetTypeInfo().IsGenericType)
            {
                var generic = type.GetGenericTypeDefinition();
                if (generic == typeof(List <>) || generic == typeof(IReadOnlyList <>))
                {
                    XAssert.IsTrue((expected == null) == (actual == null));

                    var expectedList = expected as IList;
                    var actualList   = actual as IList;

                    XAssert.IsTrue(
                        (expectedList == null) == (actualList == null),
                        "One of the lists is null, the other isnt for objPath: {0}",
                        objPath);
                    if (expectedList != null)
                    {
                        XAssert.AreEqual(expectedList.Count, actualList.Count, $"Counts of lists don't match for objPath: {objPath}");
                        for (int i = 0; i < expectedList.Count; i++)
                        {
                            ValidateEqual(
                                context,
                                type.GenericTypeArguments[0],
                                expectedList[i],
                                actualList[i],
                                objPath + "[" + i.ToString(CultureInfo.InvariantCulture) + "]",
                                remapper);
                        }
                    }

                    return;
                }

                if (generic == typeof(Dictionary <,>) || generic == typeof(IReadOnlyDictionary <,>) || generic == typeof(ConcurrentDictionary <,>))
                {
                    XAssert.IsTrue((expected == null) == (actual == null));

                    var expectedDictionary = expected as IDictionary;
                    var actualDictionary   = actual as IDictionary;

                    XAssert.IsTrue(
                        (expectedDictionary == null) == (actualDictionary == null),
                        $"One of the dictionaries is null, the other isnt for objPath: {objPath}");
                    if (expectedDictionary != null)
                    {
                        XAssert.AreEqual(
                            expectedDictionary.Count,
                            expectedDictionary.Count,
                            $"Counts of dictionaries don't match for objPath: {objPath}");
                        foreach (var kv in expectedDictionary)
                        {
                            var key         = kv.GetType().GetProperty("Key").GetValue(kv);
                            var value       = kv.GetType().GetTypeInfo().GetProperty("Value").GetValue(kv);
                            var actualValue = actualDictionary[key];

                            ValidateEqual(context, type.GenericTypeArguments[1], value, actualValue, objPath + "[" + key + "]", remapper);
                        }
                    }

                    return;
                }
            }

            if (type.GetTypeInfo().IsInterface)
            {
                var actualType = ConfigurationConverter.FindImplementationType(
                    type,
                    ObjectLiteral.Create(new List <Binding>(), default(LineInfo), AbsolutePath.Invalid),

                    // Note we only create a sourceresolver, so no need to fiddle, just compare with SourceResolver.
                    () => "SourceResolver");
                ValidateEqualMembers(context, actualType, expected, actual, objPath, remapper);
                return;
            }

            if (type.GetTypeInfo().IsClass)
            {
                ValidateEqualMembers(context, type, expected, actual, objPath, remapper);
                return;
            }

            XAssert.Fail($"Don't know how to compare objects of this type '{type}' for objPath: {objPath}");
        }
Exemplo n.º 8
0
 public void TestInvalidEnumMemberConversion()
 {
     Assert.Throws <ConversionException>(() =>
                                         ConfigurationConverter.Convert <MyClassWithEnum>(m_context, CreateObject("member", "enum.member")));
 }
Exemplo n.º 9
0
 public void TestValidEmptyObjectLiteral()
 {
     MyEqual(ConfigurationConverter.Convert <ConfigurationImpl>(m_context, s_emptyObjectLiteral), m_defaultConf);
     MyEqual(ConfigurationConverter.Convert <IConfiguration>(m_context, s_emptyObjectLiteral), m_defaultConf);
 }
Exemplo n.º 10
0
 public void TestInvalidArgObjectLiteral()
 {
     Assert.ThrowsAny <Exception>(() =>
                                  ConfigurationConverter.ConvertObjectLiteralToConfiguration(m_context, null));
 }
Exemplo n.º 11
0
 public void TestInvalidArgTable()
 {
     Assert.ThrowsAny <Exception>(() =>
                                  ConfigurationConverter.ConvertObjectLiteralToConfiguration(null, s_emptyObjectLiteral));
 }
        public void op_ConvertTo_ITypeDescriptorContext_CultureInfo_object_Type()
        {
            var context = new Mock<ITypeDescriptorContext>().Object;
            var culture = CultureInfo.InvariantCulture;
            var value = (object)123;
            var destinationType = typeof(string);

            var actual = new ConfigurationConverter<AbsoluteUri>().ConvertTo(context, culture, value, destinationType);

            Assert.Equal("123", actual);
        }
Exemplo n.º 13
0
 public void ItExists()
 {
     ConfigurationConverter converter = new ConfigurationConverter(_mailTemplateFactory);
 }
        private EvaluationResult WriteFileHelper(Context context, ModuleLiteral env, EvaluationStackFrame args, WriteFileMode mode)
        {
            AbsolutePath path;

            string[] tags;
            string   description;
            PipData  pipData;

            if (args.Length > 0 && args[0].Value is ObjectLiteral)
            {
                var obj = Args.AsObjectLiteral(args, 0);
                path        = Converter.ExtractPath(obj, m_writeOutputPath, allowUndefined: false);
                tags        = Converter.ExtractStringArray(obj, m_writeTags, allowUndefined: true);
                description = Converter.ExtractString(obj, m_writeDescription, allowUndefined: true);
                switch (mode)
                {
                case WriteFileMode.WriteData:
                    var data = obj[m_writeContents];
                    pipData = ProcessData(context, data, new ConversionContext(pos: 1));
                    break;

                case WriteFileMode.WriteAllLines:
                    var lines   = Converter.ExtractArrayLiteral(obj, m_writeLines);
                    var entry   = context.TopStack;
                    var newData = ObjectLiteral.Create(
                        new List <Binding>
                    {
                        new Binding(m_dataSeparator, Environment.NewLine, entry.InvocationLocation),
                        new Binding(m_dataContents, lines, entry.InvocationLocation),
                    },
                        lines.Location,
                        entry.Path);

                    pipData = ProcessData(context, EvaluationResult.Create(newData), new ConversionContext(pos: 1));
                    break;

                case WriteFileMode.WriteAllText:
                    var text = Converter.ExtractString(obj, m_writeText);
                    pipData = ProcessData(context, EvaluationResult.Create(text), new ConversionContext(pos: 1));
                    break;

                default:
                    throw Contract.AssertFailure("Unknown WriteFileMode.");
                }
            }
            else
            {
                path        = Args.AsPath(args, 0, false);
                tags        = Args.AsStringArrayOptional(args, 2);
                description = Args.AsStringOptional(args, 3);

                switch (mode)
                {
                case WriteFileMode.WriteFile:
                    var fileContent = Args.AsIs(args, 1);
                    // WriteFile has a separator argument with default newline
                    var separator = Args.AsStringOptional(args, 3) ?? Environment.NewLine;
                    description = Args.AsStringOptional(args, 4);

                    pipData = ConfigurationConverter.CreatePipDataFromFileContent(context.FrontEndContext, fileContent, separator);
                    break;

                case WriteFileMode.WriteData:
                    var data = Args.AsIs(args, 1);
                    pipData = ProcessData(context, EvaluationResult.Create(data), new ConversionContext(pos: 1));
                    break;

                case WriteFileMode.WriteAllLines:
                    var lines   = Args.AsArrayLiteral(args, 1);
                    var entry   = context.TopStack;
                    var newData = ObjectLiteral.Create(
                        new List <Binding>
                    {
                        new Binding(m_dataSeparator, Environment.NewLine, entry.InvocationLocation),
                        new Binding(m_dataContents, lines, entry.InvocationLocation),
                    },
                        lines.Location,
                        entry.Path);

                    pipData = ProcessData(context, EvaluationResult.Create(newData), new ConversionContext(pos: 1));
                    break;

                case WriteFileMode.WriteAllText:
                    var text = Args.AsString(args, 1);
                    pipData = ProcessData(context, EvaluationResult.Create(text), new ConversionContext(pos: 1));
                    break;

                default:
                    throw Contract.AssertFailure("Unknown WriteFileMode.");
                }
            }

            FileArtifact result;

            if (!context.GetPipConstructionHelper().TryWriteFile(path, pipData, WriteFileEncoding.Utf8, tags, description, out result))
            {
                // Error has been logged
                return(EvaluationResult.Error);
            }

            return(new EvaluationResult(result));
        }