internal static FileFormatException Create(string message, JToken jsonValue) { var result = new FileFormatException(message) .WithLineInfo(jsonValue); return result; }
internal static FileFormatException Create(string message, string filePath) { var result = new FileFormatException(message) .WithFilePath(filePath); return result; }
internal static FileFormatException Create(Exception exception, JToken jsonValue) { var result = new FileFormatException(exception.Message, exception) .WithLineInfo(jsonValue); return result; }
private void BuildTargetFrameworksAndConfigurations(Project project, JObject projectJsonObject) { // Get the shared compilationOptions project._defaultCompilerOptions = GetCompilationOptions(projectJsonObject, project) ?? new CommonCompilerOptions { CompilerName = "csc" }; project._defaultTargetFrameworkConfiguration = new TargetFrameworkInformation { Dependencies = new List <ProjectLibraryDependency>() }; // 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.Value <JToken>("configurations") as JObject; if (configurationsSection != null) { foreach (var configKey in configurationsSection) { var compilerOptions = GetCompilationOptions(configKey.Value as JObject, project); // Only use this as a configuration if it's not a target framework project._compilerOptionsByConfiguration[configKey.Key] = compilerOptions; } } // The frameworks node is where target frameworks go /* * { * "frameworks": { * "net45": { * }, * "dnxcore50": { * } * } * } */ var frameworks = projectJsonObject.Value <JToken>("frameworks") as JObject; if (frameworks != null) { foreach (var framework in frameworks) { try { var frameworkToken = framework.Value as JObject; var success = BuildTargetFrameworkNode(project, framework.Key, frameworkToken); if (!success) { var lineInfo = (IJsonLineInfo)framework.Value; project.Diagnostics.Add( new DiagnosticMessage( ErrorCodes.NU1008, $"\"{framework.Key}\" is an unsupported framework.", project.ProjectFilePath, DiagnosticMessageSeverity.Error, lineInfo.LineNumber, lineInfo.LinePosition)); } } catch (Exception ex) { throw FileFormatException.Create(ex, framework.Value, project.ProjectFilePath); } } } }
private static void PopulateDependencies( string projectPath, IList <ProjectLibraryDependency> results, JObject settings, string propertyName, bool isGacOrFrameworkReference) { var dependencies = settings.Value <JToken>(propertyName) as JObject; if (dependencies != null) { foreach (var dependency in dependencies) { if (string.IsNullOrEmpty(dependency.Key)) { throw FileFormatException.Create( "Unable to resolve dependency ''.", dependency.Key, projectPath); } var dependencyValue = dependency.Value; var dependencyTypeValue = LibraryDependencyType.Default; var target = isGacOrFrameworkReference ? LibraryDependencyTarget.Reference : LibraryDependencyTarget.All; string dependencyVersionAsString = null; if (dependencyValue.Type == JTokenType.Object) { // "dependencies" : { "Name" : { "version": "1.0", "type": "build", "target": "project" } } dependencyVersionAsString = dependencyValue.Value <string>("version"); var type = dependencyValue.Value <string>("type"); if (type != null) { dependencyTypeValue = LibraryDependencyType.Parse(new [] { type }); } // Read the target if specified if (!isGacOrFrameworkReference) { var targetStr = dependencyValue.Value <string>("target"); target = LibraryDependencyTargetUtils.Parse(targetStr); } } else if (dependencyValue.Type == JTokenType.String) { // "dependencies" : { "Name" : "1.0" } dependencyVersionAsString = dependencyValue.Value <string>(); } else { throw FileFormatException.Create( string.Format( "Invalid dependency version: {0}. The format is not recognizable.", dependency.Key), dependencyValue, projectPath); } VersionRange dependencyVersionRange = null; if (!string.IsNullOrEmpty(dependencyVersionAsString)) { try { dependencyVersionRange = VersionRange.Parse(dependencyVersionAsString); } catch (Exception ex) { throw FileFormatException.Create(ex, dependencyValue, projectPath); } } var lineInfo = (IJsonLineInfo)dependencyValue; results.Add(new ProjectLibraryDependency { LibraryRange = new LibraryRange( dependency.Key, dependencyVersionRange, target), Type = dependencyTypeValue, SourceFilePath = projectPath, SourceLine = lineInfo.LineNumber, SourceColumn = lineInfo.LinePosition }); } } }
public Project ReadProject(Stream stream, string projectName, string projectPath, ICollection<DiagnosticMessage> diagnostics, ProjectReaderSettings settings = null) { settings = settings ?? new ProjectReaderSettings(); var project = new Project(); var reader = new StreamReader(stream); var rawProject = JsonDeserializer.Deserialize(reader) as JsonObject; if (rawProject == null) { throw FileFormatException.Create( "The JSON file can't be deserialized to a JSON object.", projectPath); } // Meta-data properties project.Name = rawProject.ValueAsString("name") ?? projectName; project.ProjectFilePath = Path.GetFullPath(projectPath); var version = rawProject.Value("version") as JsonString; if (version == null) { project.Version = new NuGetVersion("1.0.0"); } else { try { var buildVersion = settings.VersionSuffix ?? Environment.GetEnvironmentVariable("DOTNET_BUILD_VERSION"); project.Version = SpecifySnapshot(version, buildVersion); } catch (Exception ex) { throw FileFormatException.Create(ex, version, project.ProjectFilePath); } } var fileVersion = Environment.GetEnvironmentVariable("DOTNET_ASSEMBLY_FILE_VERSION"); if (string.IsNullOrWhiteSpace(fileVersion)) { project.AssemblyFileVersion = project.Version.Version; } else { try { var simpleVersion = project.Version.Version; project.AssemblyFileVersion = new Version(simpleVersion.Major, simpleVersion.Minor, simpleVersion.Build, int.Parse(fileVersion)); } catch (FormatException ex) { throw new FormatException("The assembly file version is invalid: " + fileVersion, ex); } } project.Description = rawProject.ValueAsString("description"); project.Summary = rawProject.ValueAsString("summary"); project.Copyright = rawProject.ValueAsString("copyright"); project.Title = rawProject.ValueAsString("title"); project.EntryPoint = rawProject.ValueAsString("entryPoint"); project.ProjectUrl = rawProject.ValueAsString("projectUrl"); project.LicenseUrl = rawProject.ValueAsString("licenseUrl"); project.IconUrl = rawProject.ValueAsString("iconUrl"); project.CompilerName = rawProject.ValueAsString("compilerName"); project.TestRunner = rawProject.ValueAsString("testRunner"); project.Authors = rawProject.ValueAsStringArray("authors") ?? Array.Empty<string>(); project.Owners = rawProject.ValueAsStringArray("owners") ?? Array.Empty<string>(); project.Tags = rawProject.ValueAsStringArray("tags") ?? Array.Empty<string>(); project.Language = rawProject.ValueAsString("language"); project.ReleaseNotes = rawProject.ValueAsString("releaseNotes"); project.RequireLicenseAcceptance = rawProject.ValueAsBoolean("requireLicenseAcceptance", defaultValue: false); // REVIEW: Move this to the dependencies node? project.EmbedInteropTypes = rawProject.ValueAsBoolean("embedInteropTypes", defaultValue: false); project.Dependencies = new List<LibraryRange>(); // Project files project.Files = new ProjectFilesCollection(rawProject, project.ProjectDirectory, project.ProjectFilePath); var commands = rawProject.Value("commands") as JsonObject; if (commands != null) { foreach (var key in commands.Keys) { var value = commands.ValueAsString(key); if (value != null) { project.Commands[key] = value; } } } var scripts = rawProject.Value("scripts") as JsonObject; if (scripts != null) { foreach (var key in scripts.Keys) { var stringValue = scripts.ValueAsString(key); if (stringValue != null) { project.Scripts[key] = new string[] { stringValue }; continue; } var arrayValue = scripts.ValueAsStringArray(key); if (arrayValue != null) { project.Scripts[key] = arrayValue; continue; } throw FileFormatException.Create( string.Format("The value of a script in {0} can only be a string or an array of strings", Project.FileName), scripts.Value(key), project.ProjectFilePath); } } BuildTargetFrameworksAndConfigurations(project, rawProject, diagnostics); PopulateDependencies( project.ProjectFilePath, project.Dependencies, rawProject, "dependencies", isGacOrFrameworkReference: false); return project; }
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); } } } }
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)); } } }
public Project ReadProject(Stream stream, string projectName, string projectPath, ProjectReaderSettings settings = null) { settings = settings ?? new ProjectReaderSettings(); var project = new Project(); var reader = new StreamReader(stream); JObject rawProject; using (var jsonReader = new JsonTextReader(reader)) { rawProject = JObject.Load(jsonReader); // Try to read another token to ensure we're at the end of the document. // This will no-op if we are, and throw a JsonReaderException if there is additional content (which is what we want) jsonReader.Read(); } if (rawProject == null) { throw FileFormatException.Create( "The JSON file can't be deserialized to a JSON object.", projectPath); } // Meta-data properties project.Name = rawProject.Value <string>("name") ?? projectName; project.ProjectFilePath = Path.GetFullPath(projectPath); var version = rawProject.Value <string>("version"); if (version == null) { project.Version = new NuGetVersion("1.0.0"); } else { try { var buildVersion = settings.VersionSuffix; project.Version = SpecifySnapshot(version, buildVersion); } catch (Exception ex) { throw FileFormatException.Create(ex, version, project.ProjectFilePath); } } var fileVersion = settings.AssemblyFileVersion; if (string.IsNullOrWhiteSpace(fileVersion)) { project.AssemblyFileVersion = project.Version.Version; } else { try { var simpleVersion = project.Version.Version; project.AssemblyFileVersion = new Version(simpleVersion.Major, simpleVersion.Minor, simpleVersion.Build, int.Parse(fileVersion)); } catch (FormatException ex) { throw new FormatException("The assembly file version is invalid: " + fileVersion, ex); } } project.Description = rawProject.Value <string>("description"); project.Copyright = rawProject.Value <string>("copyright"); project.Title = rawProject.Value <string>("title"); project.EntryPoint = rawProject.Value <string>("entryPoint"); project.TestRunner = rawProject.Value <string>("testRunner"); project.Authors = rawProject.Value <JToken>("authors")?.Values <string>().ToArray() ?? EmptyArray <string> .Value; project.Language = rawProject.Value <string>("language"); // REVIEW: Move this to the dependencies node? project.EmbedInteropTypes = rawProject.Value <bool>("embedInteropTypes"); project.Dependencies = new List <LibraryRange>(); project.Tools = new List <LibraryRange>(); // Project files project.Files = new ProjectFilesCollection(rawProject, project.ProjectDirectory, project.ProjectFilePath); AddProjectFilesCollectionDiagnostics(rawProject, project); var commands = rawProject.Value <JToken>("commands") as JObject; if (commands != null) { foreach (var command in commands) { var commandValue = command.Value.Type == JTokenType.String ? command.Value.Value <string>() : null; if (commandValue != null) { project.Commands[command.Key] = commandValue; } } } var scripts = rawProject.Value <JToken>("scripts") as JObject; if (scripts != null) { foreach (var script in scripts) { var stringValue = script.Value.Type == JTokenType.String ? script.Value.Value <string>() : null; if (stringValue != null) { project.Scripts[script.Key] = new string[] { stringValue }; continue; } var arrayValue = script.Value.Type == JTokenType.Array ? script.Value.Values <string>().ToArray() : null; if (arrayValue != null) { project.Scripts[script.Key] = arrayValue; continue; } throw FileFormatException.Create( string.Format("The value of a script in {0} can only be a string or an array of strings", Project.FileName), script.Value, project.ProjectFilePath); } } project.PackOptions = GetPackOptions(rawProject, project) ?? new PackOptions(); project.RuntimeOptions = GetRuntimeOptions(rawProject) ?? new RuntimeOptions(); project.PublishOptions = GetPublishInclude(rawProject, project); BuildTargetFrameworksAndConfigurations(project, rawProject); PopulateDependencies( project.ProjectFilePath, project.Dependencies, rawProject, "dependencies", isGacOrFrameworkReference: false); PopulateDependencies( project.ProjectFilePath, project.Tools, rawProject, "tools", isGacOrFrameworkReference: false); JToken runtimeOptionsToken; if (rawProject.TryGetValue("runtimeOptions", out runtimeOptionsToken)) { var runtimeOptions = runtimeOptionsToken as JObject; if (runtimeOptions == null) { throw FileFormatException.Create("The runtimeOptions must be an object", runtimeOptionsToken); } project.RawRuntimeOptions = runtimeOptions.ToString(); } return(project); }
private static CommonCompilerOptions GetCompilationOptions(JObject rawObject, Project project) { var compilerName = rawObject.Value <string>("compilerName"); if (compilerName != null) { var lineInfo = rawObject.Value <IJsonLineInfo>("compilerName"); project.Diagnostics.Add( new DiagnosticMessage( ErrorCodes.DOTNET1016, $"The 'compilerName' option in the root is deprecated. Use it in 'buildOptions' instead.", project.ProjectFilePath, DiagnosticMessageSeverity.Warning, lineInfo.LineNumber, lineInfo.LinePosition)); } var rawOptions = rawObject.Value <JToken>("buildOptions") as JObject; if (rawOptions == null) { rawOptions = rawObject.Value <JToken>("compilationOptions") as JObject; if (rawOptions == null) { return(new CommonCompilerOptions { CompilerName = compilerName ?? "csc" }); } var lineInfo = (IJsonLineInfo)rawOptions; project.Diagnostics.Add( new DiagnosticMessage( ErrorCodes.DOTNET1015, $"The 'compilationOptions' option is deprecated. Use 'buildOptions' instead.", project.ProjectFilePath, DiagnosticMessageSeverity.Warning, lineInfo.LineNumber, lineInfo.LinePosition)); } var analyzerOptionsJson = rawOptions.Value <JToken>("analyzerOptions") as JObject; if (analyzerOptionsJson != null) { var analyzerOptions = new AnalyzerOptions(); foreach (var analyzerOption in analyzerOptionsJson) { switch (analyzerOption.Key) { case "languageId": if (analyzerOption.Value.Type != JTokenType.String) { throw FileFormatException.Create( "The analyzer languageId must be a string", analyzerOption.Value.ToString(), project.ProjectFilePath); } analyzerOptions = new AnalyzerOptions(analyzerOption.Value.ToString()); break; default: throw FileFormatException.Create( $"Unrecognized analyzerOption key: {analyzerOption.Key}", project.ProjectFilePath); } } project.AnalyzerOptions = analyzerOptions; } return(new CommonCompilerOptions { Defines = rawOptions.Value <JToken>("define")?.Values <string>().ToArray(), SuppressWarnings = rawOptions.Value <JToken>("nowarn")?.Values <string>().ToArray(), AdditionalArguments = rawOptions.Value <JToken>("additionalArguments")?.Values <string>().ToArray(), LanguageVersion = rawOptions.Value <string>("languageVersion"), AllowUnsafe = rawOptions.Value <bool?>("allowUnsafe"), Platform = rawOptions.Value <string>("platform"), WarningsAsErrors = rawOptions.Value <bool?>("warningsAsErrors"), Optimize = rawOptions.Value <bool?>("optimize"), KeyFile = rawOptions.Value <string>("keyFile"), DelaySign = rawOptions.Value <bool?>("delaySign"), PublicSign = rawOptions.Value <bool?>("publicSign"), DebugType = rawOptions.Value <string>("debugType"), EmitEntryPoint = rawOptions.Value <bool?>("emitEntryPoint"), GenerateXmlDocumentation = rawOptions.Value <bool?>("xmlDoc"), PreserveCompilationContext = rawOptions.Value <bool?>("preserveCompilationContext"), OutputName = rawOptions.Value <string>("outputName"), CompilerName = rawOptions.Value <string>("compilerName") ?? compilerName ?? "csc", CompileInclude = GetIncludeContext( project, rawOptions, "compile", defaultBuiltInInclude: ProjectFilesCollection.DefaultCompileBuiltInPatterns, defaultBuiltInExclude: ProjectFilesCollection.DefaultBuiltInExcludePatterns), EmbedInclude = GetIncludeContext( project, rawOptions, "embed", defaultBuiltInInclude: ProjectFilesCollection.DefaultResourcesBuiltInPatterns, defaultBuiltInExclude: ProjectFilesCollection.DefaultBuiltInExcludePatterns), CopyToOutputInclude = GetIncludeContext( project, rawOptions, "copyToOutput", defaultBuiltInInclude: null, defaultBuiltInExclude: ProjectFilesCollection.DefaultPublishExcludePatterns) }); }
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"), DebugType = rawOptions.ValueAsString("debugType"), EmitEntryPoint = rawOptions.ValueAsNullableBoolean("emitEntryPoint"), GenerateXmlDocumentation = rawOptions.ValueAsNullableBoolean("xmlDoc"), PreserveCompilationContext = rawOptions.ValueAsNullableBoolean("preserveCompilationContext") }); }