Пример #1
0
        public static bool TryGetGlobalSettings(string path, out GlobalSettings globalSettings)
        {
            globalSettings = null;
            string globalJsonPath = null;

            if (Path.GetFileName(path) == FileName)
            {
                globalJsonPath = path;
                path           = Path.GetDirectoryName(path);
            }
            else if (!HasGlobalFile(path))
            {
                return(false);
            }
            else
            {
                globalJsonPath = Path.Combine(path, FileName);
            }

            globalSettings = new GlobalSettings();

            try
            {
                using (var fs = File.OpenRead(globalJsonPath))
                {
                    var reader  = new StreamReader(fs);
                    var jobject = JsonDeserializer.Deserialize(reader) as JsonObject;

                    if (jobject == null)
                    {
                        throw new InvalidOperationException("The JSON file can't be deserialized to a JSON object.");
                    }

                    var projectSearchPaths = jobject.ValueAsStringArray("projects") ??
                                             jobject.ValueAsStringArray("sources") ??
                                             new string[] { };

                    globalSettings.ProjectSearchPaths = new List <string>(projectSearchPaths);
                    globalSettings.PackagesPath       = jobject.ValueAsString("packages");
                    globalSettings.FilePath           = globalJsonPath;
                }
            }
            catch (Exception ex)
            {
                throw FileFormatException.Create(ex, globalJsonPath);
            }

            return(true);
        }
Пример #2
0
        public static bool TryGetProject(string path, out Project project, ICollection <DiagnosticMessage> diagnostics = null)
        {
            project = null;

            string projectPath = null;

            if (string.Equals(Path.GetFileName(path), Project.FileName, StringComparison.OrdinalIgnoreCase))
            {
                projectPath = path;
                path        = Path.GetDirectoryName(path);
            }
            else if (!HasProjectFile(path))
            {
                return(false);
            }
            else
            {
                projectPath = Path.Combine(path, Project.FileName);
            }

            // Assume the directory name is the project name if none was specified
            var projectName = PathUtility.GetDirectoryName(Path.GetFullPath(path));

            projectPath = Path.GetFullPath(projectPath);

            if (!File.Exists(projectPath))
            {
                return(false);
            }

            try
            {
                using (var stream = File.OpenRead(projectPath))
                {
                    var reader = new ProjectReader();
                    project = reader.ReadProject(stream, projectName, projectPath, diagnostics);
                }
            }
            catch (Exception ex)
            {
                throw FileFormatException.Create(ex, projectPath);
            }

            return(true);
        }
Пример #3
0
        public Project ReadProject(Stream stream, string projectName, string projectPath, ICollection <DiagnosticMessage> diagnostics)
        {
            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 = 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.Authors = rawProject.ValueAsStringArray("authors") ?? new string[0];
            project.Owners  = rawProject.ValueAsStringArray("owners") ?? new string[0];
            project.Tags    = rawProject.ValueAsStringArray("tags") ?? new string[0];

            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);
        }
Пример #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
        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));
                }
            }
        }