public static IEnumerable<string> GetPatternsCollection(JsonObject rawProject,
                                                                string projectDirectory,
                                                                string projectFilePath,
                                                                string propertyName,
                                                                IEnumerable<string> defaultPatterns = null,
                                                                bool literalPath = false)
        {
            defaultPatterns = defaultPatterns ?? Enumerable.Empty<string>();

            try
            {
                if (!rawProject.Keys.Contains(propertyName))
                {
                    return CreateCollection(projectDirectory, propertyName, defaultPatterns, literalPath);
                }

                var valueInString = rawProject.ValueAsString(propertyName);
                if (valueInString != null)
                {
                    return CreateCollection(projectDirectory, propertyName, new string[] { valueInString }, literalPath);
                }

                var valuesInArray = rawProject.ValueAsStringArray(propertyName);
                if (valuesInArray != null)
                {
                    return CreateCollection(projectDirectory, propertyName, valuesInArray.Select(s => s.ToString()), literalPath);
                }
            }
            catch (Exception ex)
            {
                throw FileFormatException.Create(ex, rawProject.Value(propertyName), projectFilePath);
            }

            throw FileFormatException.Create("Value must be either string or array.", rawProject.Value(propertyName), projectFilePath);
        }
示例#2
0
        internal static PatternGroup Build(JsonObject rawProject,
                                           string projectDirectory,
                                           string projectFilePath,
                                           string name,
                                           IEnumerable<string> fallbackIncluding = null,
                                           IEnumerable<string> additionalIncluding = null,
                                           IEnumerable<string> additionalExcluding = null,
                                           bool includePatternsOnly = false,
                                           ICollection<DiagnosticMessage> warnings = null)
        {
            string includePropertyName = name;
            additionalIncluding = additionalIncluding ?? Enumerable.Empty<string>();
            var includePatterns = PatternsCollectionHelper.GetPatternsCollection(rawProject, projectDirectory, projectFilePath, includePropertyName, defaultPatterns: fallbackIncluding)
                                                          .Concat(additionalIncluding)
                                                          .Distinct();

            if (includePatternsOnly)
            {
                return new PatternGroup(includePatterns);
            }

            additionalExcluding = additionalExcluding ?? Enumerable.Empty<string>();
            var excludePatterns = PatternsCollectionHelper.GetPatternsCollection(rawProject, projectDirectory, projectFilePath, propertyName: name + "Exclude")
                                                          .Concat(additionalExcluding)
                                                          .Distinct();

            var includeLiterals = PatternsCollectionHelper.GetPatternsCollection(rawProject, projectDirectory, projectFilePath, propertyName: name + "Files", literalPath: true)
                                                          .Distinct();

            return new PatternGroup(includePatterns, excludePatterns, includeLiterals);
        }
示例#3
0
        public static IDictionary<string, string> ReadNamedResources(JsonObject rawProject, string projectFilePath)
        {
            if (!rawProject.Keys.Contains("namedResource"))
            {
                return new Dictionary<string, string>();
            }

            var namedResourceToken = rawProject.ValueAsJsonObject("namedResource");
            if (namedResourceToken == null)
            {
                throw FileFormatException.Create("Value must be object.", rawProject.Value("namedResource"), projectFilePath);
            }

            var namedResources = new Dictionary<string, string>();

            foreach (var namedResourceKey in namedResourceToken.Keys)
            {
                var resourcePath = namedResourceToken.ValueAsString(namedResourceKey);
                if (resourcePath == null)
                {
                    throw FileFormatException.Create("Value must be string.", namedResourceToken.Value(namedResourceKey), projectFilePath);
                }

                if (resourcePath.Value.Contains("*"))
                {
                    throw FileFormatException.Create("Value cannot contain wildcards.", resourcePath, projectFilePath);
                }

                var resourceFileFullPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(projectFilePath), resourcePath));

                if (namedResources.ContainsKey(namedResourceKey))
                {
                    throw FileFormatException.Create(
                        string.Format("The named resource {0} already exists.", namedResourceKey),
                        resourcePath,
                        projectFilePath);
                }

                namedResources.Add(
                    namedResourceKey,
                    resourceFileFullPath);
            }

            return namedResources;
        }
示例#4
0
        private void BuildTargetFrameworksAndConfigurations(Project project, JsonObject projectJsonObject, ICollection<DiagnosticMessage> diagnostics)
        {
            // Get the shared compilationOptions
            project._defaultCompilerOptions = GetCompilationOptions(projectJsonObject) ?? new CommonCompilerOptions();

            project._defaultTargetFrameworkConfiguration = new TargetFrameworkInformation
            {
                Dependencies = new List<LibraryRange>()
            };

            // Add default configurations
            project._compilerOptionsByConfiguration["Debug"] = new CommonCompilerOptions
            {
                Defines = new[] { "DEBUG", "TRACE" },
                Optimize = false
            };

            project._compilerOptionsByConfiguration["Release"] = new CommonCompilerOptions
            {
                Defines = new[] { "RELEASE", "TRACE" },
                Optimize = true
            };

            // The configuration node has things like debug/release compiler settings
            /*
                {
                    "configurations": {
                        "Debug": {
                        },
                        "Release": {
                        }
                    }
                }
            */

            var configurationsSection = projectJsonObject.ValueAsJsonObject("configurations");
            if (configurationsSection != null)
            {
                foreach (var configKey in configurationsSection.Keys)
                {
                    var compilerOptions = GetCompilationOptions(configurationsSection.ValueAsJsonObject(configKey));

                    // Only use this as a configuration if it's not a target framework
                    project._compilerOptionsByConfiguration[configKey] = compilerOptions;
                }
            }

            // The frameworks node is where target frameworks go
            /*
                {
                    "frameworks": {
                        "net45": {
                        },
                        "dnxcore50": {
                        }
                    }
                }
            */

            var frameworks = projectJsonObject.ValueAsJsonObject("frameworks");
            if (frameworks != null)
            {
                foreach (var frameworkKey in frameworks.Keys)
                {
                    try
                    {
                        var frameworkToken = frameworks.ValueAsJsonObject(frameworkKey);
                        var success = BuildTargetFrameworkNode(project, frameworkKey, frameworkToken);
                        if (!success)
                        {
                            diagnostics?.Add(
                                new DiagnosticMessage(
                                    ErrorCodes.NU1008,
                                    $"\"{frameworkKey}\" is an unsupported framework.",
                                    project.ProjectFilePath,
                                    DiagnosticMessageSeverity.Error,
                                    frameworkToken.Line,
                                    frameworkToken.Column));
                        }
                    }
                    catch (Exception ex)
                    {
                        throw FileFormatException.Create(ex, frameworks.Value(frameworkKey), project.ProjectFilePath);
                    }
                }
            }
        }
示例#5
0
        /// <summary>
        /// Parse a Json object which represents project configuration for a specified framework
        /// </summary>
        /// <param name="frameworkKey">The name of the framework</param>
        /// <param name="frameworkValue">The Json object represent the settings</param>
        /// <returns>Returns true if it successes.</returns>
        private bool BuildTargetFrameworkNode(Project project, string frameworkKey, JsonObject frameworkValue)
        {
            // If no compilation options are provided then figure them out from the node
            var compilerOptions = GetCompilationOptions(frameworkValue) ??
                                  new CommonCompilerOptions();

            var frameworkName = NuGetFramework.Parse(frameworkKey);

            // If it's not unsupported then keep it
            if (frameworkName.IsUnsupported)
            {
                // REVIEW: Should we skip unsupported target frameworks
                return false;
            }

            // Add the target framework specific define
            var defines = new HashSet<string>(compilerOptions.Defines ?? Enumerable.Empty<string>());
            var frameworkDefine = MakeDefaultTargetFrameworkDefine(frameworkName);

            if (!string.IsNullOrEmpty(frameworkDefine))
            {
                defines.Add(frameworkDefine);
            }

            compilerOptions.Defines = defines;

            var targetFrameworkInformation = new TargetFrameworkInformation
            {
                FrameworkName = frameworkName,
                Dependencies = new List<LibraryRange>(),
                CompilerOptions = compilerOptions,
                Line = frameworkValue.Line,
                Column = frameworkValue.Column
            };

            var frameworkDependencies = new List<LibraryRange>();

            PopulateDependencies(
                project.ProjectFilePath,
                frameworkDependencies,
                frameworkValue,
                "dependencies",
                isGacOrFrameworkReference: false);

            var frameworkAssemblies = new List<LibraryRange>();
            PopulateDependencies(
                project.ProjectFilePath,
                frameworkAssemblies,
                frameworkValue,
                "frameworkAssemblies",
                isGacOrFrameworkReference: true);

            frameworkDependencies.AddRange(frameworkAssemblies);
            targetFrameworkInformation.Dependencies = frameworkDependencies;

            targetFrameworkInformation.WrappedProject = frameworkValue.ValueAsString("wrappedProject");

            var binNode = frameworkValue.ValueAsJsonObject("bin");
            if (binNode != null)
            {
                targetFrameworkInformation.AssemblyPath = binNode.ValueAsString("assembly");
                targetFrameworkInformation.PdbPath = binNode.ValueAsString("pdb");
            }

            project._targetFrameworks[frameworkName] = targetFrameworkInformation;

            return true;
        }
示例#6
0
        private static bool TryGetStringEnumerable(JsonObject parent, string property, out IEnumerable<string> result)
        {
            var collection = new List<string>();
            var valueInString = parent.ValueAsString(property);
            if (valueInString != null)
            {
                collection.Add(valueInString);
            }
            else
            {
                var valueInArray = parent.ValueAsStringArray(property);
                if (valueInArray != null)
                {
                    collection.AddRange(valueInArray);
                }
                else
                {
                    result = null;
                    return false;
                }
            }

            result = collection.SelectMany(value => value.Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries));
            return true;
        }
示例#7
0
        private static void PopulateDependencies(
            string projectPath,
            IList<LibraryRange> results,
            JsonObject settings,
            string propertyName,
            bool isGacOrFrameworkReference)
        {
            var dependencies = settings.ValueAsJsonObject(propertyName);
            if (dependencies != null)
            {
                foreach (var dependencyKey in dependencies.Keys)
                {
                    if (string.IsNullOrEmpty(dependencyKey))
                    {
                        throw FileFormatException.Create(
                            "Unable to resolve dependency ''.",
                            dependencies.Value(dependencyKey),
                            projectPath);
                    }

                    var dependencyValue = dependencies.Value(dependencyKey);
                    var dependencyTypeValue = LibraryDependencyType.Default;
                    JsonString dependencyVersionAsString = null;
                    LibraryType target = isGacOrFrameworkReference ? LibraryType.ReferenceAssembly : LibraryType.Unspecified;

                    if (dependencyValue is JsonObject)
                    {
                        // "dependencies" : { "Name" : { "version": "1.0", "type": "build", "target": "project" } }
                        var dependencyValueAsObject = (JsonObject)dependencyValue;
                        dependencyVersionAsString = dependencyValueAsObject.ValueAsString("version");

                        var type = dependencyValueAsObject.ValueAsString("type");
                        if (type != null)
                        {
                            dependencyTypeValue = LibraryDependencyType.Parse(type.Value);
                        }

                        // Read the target if specified
                        if (!isGacOrFrameworkReference)
                        {
                            LibraryType parsedTarget;
                            var targetStr = dependencyValueAsObject.ValueAsString("target");
                            if (!string.IsNullOrEmpty(targetStr) && LibraryType.TryParse(targetStr, out parsedTarget))
                            {
                                target = parsedTarget;
                            }
                        }
                    }
                    else if (dependencyValue is JsonString)
                    {
                        // "dependencies" : { "Name" : "1.0" }
                        dependencyVersionAsString = (JsonString)dependencyValue;
                    }
                    else
                    {
                        throw FileFormatException.Create(
                            string.Format("Invalid dependency version: {0}. The format is not recognizable.", dependencyKey),
                            dependencyValue,
                            projectPath);
                    }

                    VersionRange dependencyVersionRange = null;
                    if (!string.IsNullOrEmpty(dependencyVersionAsString?.Value))
                    {
                        try
                        {
                            dependencyVersionRange = VersionRange.Parse(dependencyVersionAsString.Value);
                        }
                        catch (Exception ex)
                        {
                            throw FileFormatException.Create(
                                ex,
                                dependencyValue,
                                projectPath);
                        }
                    }

                    results.Add(new LibraryRange(
                        dependencyKey,
                        dependencyVersionRange,
                        target,
                        dependencyTypeValue,
                        projectPath,
                        dependencies.Value(dependencyKey).Line,
                        dependencies.Value(dependencyKey).Column));
                }
            }
        }
示例#8
0
        private static CommonCompilerOptions GetCompilationOptions(JsonObject rawObject)
        {
            var rawOptions = rawObject.ValueAsJsonObject("compilationOptions");
            if (rawOptions == null)
            {
                return null;
            }

            return new CommonCompilerOptions
            {
                Defines = rawOptions.ValueAsStringArray("define"),
                LanguageVersion = rawOptions.ValueAsString("languageVersion"),
                AllowUnsafe = rawOptions.ValueAsNullableBoolean("allowUnsafe"),
                Platform = rawOptions.ValueAsString("platform"),
                WarningsAsErrors = rawOptions.ValueAsNullableBoolean("warningsAsErrors"),
                Optimize = rawOptions.ValueAsNullableBoolean("optimize"),
                KeyFile = rawOptions.ValueAsString("keyFile"),
                DelaySign = rawOptions.ValueAsNullableBoolean("delaySign"),
                UseOssSigning = rawOptions.ValueAsNullableBoolean("useOssSigning"),
                EmitEntryPoint = rawOptions.ValueAsNullableBoolean("emitEntryPoint")
            };
        }
示例#9
0
        internal void EnsureInitialized()
        {
            if (_initialized)
            {
                return;
            }

            var excludeBuiltIns = PatternsCollectionHelper.GetPatternsCollection(_rawProject, _projectDirectory, _projectFilePath, "excludeBuiltIn", DefaultBuiltInExcludePatterns);
            var excludePatterns = PatternsCollectionHelper.GetPatternsCollection(_rawProject, _projectDirectory, _projectFilePath, "exclude")
                                                          .Concat(excludeBuiltIns);
            var contentBuiltIns = PatternsCollectionHelper.GetPatternsCollection(_rawProject, _projectDirectory, _projectFilePath, "contentBuiltIn", DefaultContentsBuiltInPatterns);
            var compileBuiltIns = PatternsCollectionHelper.GetPatternsCollection(_rawProject, _projectDirectory, _projectFilePath, "compileBuiltIn", DefaultCompileBuiltInPatterns);
            var resourceBuiltIns = PatternsCollectionHelper.GetPatternsCollection(_rawProject, _projectDirectory, _projectFilePath, "resourceBuiltIn", DefaultResourcesBuiltInPatterns);

            _publishExcludePatterns = PatternsCollectionHelper.GetPatternsCollection(_rawProject, _projectDirectory, _projectFilePath, "publishExclude", DefaultPublishExcludePatterns);

            _sharedPatternsGroup = PatternGroup.Build(_rawProject, _projectDirectory, _projectFilePath, "shared", fallbackIncluding: DefaultSharedPatterns, additionalExcluding: excludePatterns);

            _resourcePatternsGroup = PatternGroup.Build(_rawProject, _projectDirectory, _projectFilePath, "resource", additionalIncluding: resourceBuiltIns, additionalExcluding: excludePatterns);

            _preprocessPatternsGroup = PatternGroup.Build(_rawProject, _projectDirectory, _projectFilePath, "preprocess", fallbackIncluding: DefaultPreprocessPatterns, additionalExcluding: excludePatterns)
                .ExcludeGroup(_sharedPatternsGroup)
                .ExcludeGroup(_resourcePatternsGroup);

            _compilePatternsGroup = PatternGroup.Build(_rawProject, _projectDirectory, _projectFilePath, "compile", additionalIncluding: compileBuiltIns, additionalExcluding: excludePatterns)
                .ExcludeGroup(_sharedPatternsGroup)
                .ExcludeGroup(_preprocessPatternsGroup)
                .ExcludeGroup(_resourcePatternsGroup);

            _contentPatternsGroup = PatternGroup.Build(_rawProject, _projectDirectory, _projectFilePath, "content", additionalIncluding: contentBuiltIns, additionalExcluding: _publishExcludePatterns);

            _namedResources = NamedResourceReader.ReadNamedResources(_rawProject, _projectFilePath);

            // Files to be packed along with the project
            var packIncludeJson = _rawProject.ValueAsJsonObject(PackIncludePropertyName);
            if (packIncludeJson != null)
            {
                _packInclude = packIncludeJson
                    .Keys
                    .Select(k => new PackIncludeEntry(k, packIncludeJson.Value(k)))
                    .ToList();
            }
            else
            {
                _packInclude = new List<PackIncludeEntry>();
            }

            _initialized = true;
            _rawProject = null;
        }
示例#10
0
 internal ProjectFilesCollection(JsonObject rawProject, string projectDirectory, string projectFilePath)
 {
     _projectDirectory = projectDirectory;
     _projectFilePath = projectFilePath;
     _rawProject = rawProject;
 }
示例#11
0
        private static void PopulateDependencies(
            string projectPath,
            IList<LibraryDependency> results,
            JsonObject settings,
            string propertyName,
            bool isGacOrFrameworkReference)
        {
            var dependencies = settings.ValueAsJsonObject(propertyName);
            if (dependencies != null)
            {
                foreach (var dependencyKey in dependencies.Keys)
                {
                    if (string.IsNullOrEmpty(dependencyKey))
                    {
                        throw FileFormatException.Create(
                            "Unable to resolve dependency ''.",
                            dependencies.Value(dependencyKey),
                            projectPath);
                    }

                    var dependencyValue = dependencies.Value(dependencyKey);
                    var dependencyTypeValue = LibraryDependencyType.Default;
                    JsonString dependencyVersionAsString = null;
                    string target = null;

                    if (dependencyValue is JsonObject)
                    {
                        // "dependencies" : { "Name" : { "version": "1.0", "type": "build", "target": "project" } }
                        var dependencyValueAsObject = (JsonObject)dependencyValue;
                        dependencyVersionAsString = dependencyValueAsObject.ValueAsString("version");

                        // Remove support for flags (we only support build and nothing right now)
                        var type = dependencyValueAsObject.ValueAsString("type");
                        if (type != null)
                        {
                            dependencyTypeValue = LibraryDependencyType.Parse(type.Value);
                        }

                        // Read the target if specified
                        target = dependencyValueAsObject.ValueAsString("target")?.Value;
                    }
                    else if (dependencyValue is JsonString)
                    {
                        // "dependencies" : { "Name" : "1.0" }
                        dependencyVersionAsString = (JsonString)dependencyValue;
                    }
                    else
                    {
                        throw FileFormatException.Create(
                            string.Format("Invalid dependency version: {0}. The format is not recognizable.", dependencyKey),
                            dependencyValue,
                            projectPath);
                    }

                    SemanticVersionRange dependencyVersionRange = null;
                    if (!string.IsNullOrEmpty(dependencyVersionAsString?.Value))
                    {
                        try
                        {
                            dependencyVersionRange = VersionUtility.ParseVersionRange(dependencyVersionAsString.Value);
                        }
                        catch (Exception ex)
                        {
                            throw FileFormatException.Create(
                                ex,
                                dependencyValue,
                                projectPath);
                        }
                    }

                    results.Add(new LibraryDependency
                    {
                        LibraryRange = new LibraryRange(dependencyKey, isGacOrFrameworkReference)
                        {
                            VersionRange = dependencyVersionRange,
                            FileName = projectPath,
                            Line = dependencyValue.Line,
                            Column = dependencyValue.Column,
                            Target = target
                        },
                        Type = dependencyTypeValue
                    });
                }
            }
        }
示例#12
0
        private static CommonCompilerOptions GetCompilationOptions(JsonObject rawObject, Project project)
        {
            var rawOptions = rawObject.ValueAsJsonObject("compilationOptions");
            if (rawOptions == null)
            {
                return null;
            }

            var analyzerOptionsJson = rawOptions.Value("analyzerOptions") as JsonObject;
            if (analyzerOptionsJson != null)
            {
                var analyzerOptions = new AnalyzerOptions();

                foreach (var key in analyzerOptionsJson.Keys)
                {
                    switch (key)
                    {
                        case "languageId":
                            var languageId = analyzerOptionsJson.ValueAsString(key);
                            if (languageId == null)
                            {
                                throw FileFormatException.Create(
                                    "The analyzer languageId must be a string",
                                    analyzerOptionsJson.Value(key),
                                    project.ProjectFilePath);
                            }
                            analyzerOptions.LanguageId = languageId;
                            break;

                        default:;
                            throw FileFormatException.Create(
                               $"Unrecognized analyzerOption key: {key}",
                               project.ProjectFilePath);
                    }
                }

                project.AnalyzerOptions = analyzerOptions;
            }

            return new CommonCompilerOptions
            {
                Defines = rawOptions.ValueAsStringArray("define"),
                SuppressWarnings = rawOptions.ValueAsStringArray("nowarn"),
                AdditionalArguments = rawOptions.ValueAsStringArray("additionalArguments"),
                LanguageVersion = rawOptions.ValueAsString("languageVersion"),
                AllowUnsafe = rawOptions.ValueAsNullableBoolean("allowUnsafe"),
                Platform = rawOptions.ValueAsString("platform"),
                WarningsAsErrors = rawOptions.ValueAsNullableBoolean("warningsAsErrors"),
                Optimize = rawOptions.ValueAsNullableBoolean("optimize"),
                KeyFile = rawOptions.ValueAsString("keyFile"),
                DelaySign = rawOptions.ValueAsNullableBoolean("delaySign"),
                PublicSign = rawOptions.ValueAsNullableBoolean("publicSign"),
                EmitEntryPoint = rawOptions.ValueAsNullableBoolean("emitEntryPoint"),
                GenerateXmlDocumentation = rawOptions.ValueAsNullableBoolean("xmlDoc"),
                PreserveCompilationContext = rawOptions.ValueAsNullableBoolean("preserveCompilationContext")
            };
        }
示例#13
0
        private static List<DiagnosticMessage> ValueAsCompilationMessages(JsonObject obj, string key)
        {
            var messages = new List<DiagnosticMessage>();

            var arrayValue = obj.Value(key) as JsonArray;
            for (int i = 0; i < arrayValue.Length; i++)
            {
                var item = arrayValue[i] as JsonObject;

                var message = new DiagnosticMessage(
                    item.ValueAsString(nameof(DiagnosticMessage.ErrorCode)),
                    item.ValueAsString(nameof(DiagnosticMessage.Message)),
                    item.ValueAsString(nameof(DiagnosticMessage.FormattedMessage)),
                    item.ValueAsString(nameof(DiagnosticMessage.SourceFilePath)),
                    (DiagnosticMessageSeverity)item.ValueAsInt(nameof(DiagnosticMessage.Severity)),
                    item.ValueAsInt(nameof(DiagnosticMessage.StartColumn)),
                    item.ValueAsInt(nameof(DiagnosticMessage.StartLine)),
                    item.ValueAsInt(nameof(DiagnosticMessage.EndColumn)),
                    item.ValueAsInt(nameof(DiagnosticMessage.EndLine)));

                messages.Add(message);
            }

            return messages;
        }
示例#14
0
        private static CommonCompilerOptions GetCompilationOptions(JsonObject rawObject)
        {
            var rawOptions = rawObject.ValueAsJsonObject("compilationOptions");
            if (rawOptions == null)
            {
                return null;
            }

            return new CommonCompilerOptions
            {
                Defines = rawOptions.ValueAsStringArray("define"),
                SuppressWarnings = rawOptions.ValueAsStringArray("nowarn"),
                LanguageVersion = rawOptions.ValueAsString("languageVersion"),
                AllowUnsafe = rawOptions.ValueAsNullableBoolean("allowUnsafe"),
                Platform = rawOptions.ValueAsString("platform"),
                WarningsAsErrors = rawOptions.ValueAsNullableBoolean("warningsAsErrors"),
                Optimize = rawOptions.ValueAsNullableBoolean("optimize"),
                KeyFile = rawOptions.ValueAsString("keyFile"),
                DelaySign = rawOptions.ValueAsNullableBoolean("delaySign"),
                PublicSign = rawOptions.ValueAsNullableBoolean("publicSign"),
                EmitEntryPoint = rawOptions.ValueAsNullableBoolean("emitEntryPoint"),
                GenerateXmlDocumentation = rawOptions.ValueAsNullableBoolean("xmlDoc"),
                PreserveCompilationContext = rawOptions.ValueAsNullableBoolean("preserveCompilationContext")
            };
        }