Beispiel #1
0
        public static Project GetProject(string projectFile, ICollection<DiagnosticMessage> diagnostics, ProjectReaderSettings settings = null)
        {
            var name = Path.GetFileName(Path.GetDirectoryName(projectFile));

            using (var stream = new FileStream(projectFile, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                return new ProjectReader().ReadProject(stream, name, projectFile, diagnostics, settings);
            }
        }
        public static ProjectReaderSettings ReadFromEnvironment()
        {
            var settings = new ProjectReaderSettings
            {
                VersionSuffix       = Environment.GetEnvironmentVariable("DOTNET_BUILD_VERSION"),
                AssemblyFileVersion = Environment.GetEnvironmentVariable("DOTNET_ASSEMBLY_FILE_VERSION")
            };

            return(settings);
        }
Beispiel #3
0
        public static ProjectReaderSettings ReadFromEnvironment()
        {
            var settings = new ProjectReaderSettings
            {
                VersionSuffix = Environment.GetEnvironmentVariable("DOTNET_BUILD_VERSION"),
                AssemblyFileVersion = Environment.GetEnvironmentVariable("DOTNET_ASSEMBLY_FILE_VERSION")
            };

            return settings;
        }
Beispiel #4
0
        /// <summary>
        /// Create an empty <see cref="WorkspaceContext" /> using the default <see cref="ProjectReaderSettings" />, with the specified Version Suffix
        /// </summary>
        /// <param name="versionSuffix">The suffix to use to replace any '-*' snapshot tokens in Project versions.</param>
        /// <returns></returns>
        public static BuildWorkspace Create(string versionSuffix)
        {
            var settings = ProjectReaderSettings.ReadFromEnvironment();

            if (!string.IsNullOrEmpty(versionSuffix))
            {
                settings.VersionSuffix = versionSuffix;
            }
            return(new BuildWorkspace(settings));
        }
Beispiel #5
0
        public Project ReadProject(string projectPath, ProjectReaderSettings settings)
        {
            projectPath = ProjectPathHelper.NormalizeProjectFilePath(projectPath);

            var name = Path.GetFileName(Path.GetDirectoryName(projectPath));

            using (var stream = new FileStream(projectPath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                return(ReadProject(stream, name, projectPath, settings));
            }
        }
Beispiel #6
0
        public static Project GetProject(string projectPath, ICollection<DiagnosticMessage> diagnostics, ProjectReaderSettings settings = null)
        {
            if (!projectPath.EndsWith(Project.FileName))
            {
                projectPath = Path.Combine(projectPath, Project.FileName);
            }

            var name = Path.GetFileName(Path.GetDirectoryName(projectPath));

            using (var stream = new FileStream(projectPath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                return new ProjectReader().ReadProject(stream, name, projectPath, diagnostics, settings);
            }
        }
Beispiel #7
0
        /// <summary>
        /// Creates a project context for each framework located in the project at <paramref name="projectPath"/>
        /// </summary>
        public static IEnumerable<ProjectContext> CreateContextForEachFramework(string projectPath, ProjectReaderSettings settings = null)
        {
            if (!projectPath.EndsWith(Project.FileName))
            {
                projectPath = Path.Combine(projectPath, Project.FileName);
            }
            var project = ProjectReader.GetProject(projectPath, settings);

            foreach (var framework in project.GetTargetFrameworks())
            {
                yield return new ProjectContextBuilder()
                                .WithProject(project)
                                .WithTargetFramework(framework.FrameworkName)
                                .WithReaderSettings(settings)
                                .Build();
            }
        }
Beispiel #8
0
        public static bool TryGetProject(string path, out Project project, ProjectReaderSettings settings = 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, settings);
                }
            }
            catch (Exception ex)
            {
                throw FileFormatException.Create(ex, projectPath);
            }

            return(true);
        }
Beispiel #9
0
        public static bool TryGetProject(string path, out Project project, ICollection<DiagnosticMessage> diagnostics = null, ProjectReaderSettings settings = 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, settings);
                }
            }
            catch (Exception ex)
            {
                throw FileFormatException.Create(ex, projectPath);
            }

            return true;
        }
Beispiel #10
0
        private static bool TryBuildPackage(string path, string configuration, string outputValue, string intermediateOutputValue, ProjectReaderSettings settings = null)
        {
            var contexts = ProjectContext.CreateContextForEachFramework(path, settings);
            var project = contexts.First().ProjectFile;

            if (project.Files.SourceFiles.Any())
            {
                var argsBuilder = new StringBuilder();
                argsBuilder.Append($"--configuration {configuration}");

                if (!string.IsNullOrEmpty(outputValue))
                {
                    argsBuilder.Append($" --output \"{outputValue}\"");
                }

                if (!string.IsNullOrEmpty(intermediateOutputValue))
                {
                    argsBuilder.Append($" --temp-output \"{intermediateOutputValue}\"");
                }

                argsBuilder.Append($" \"{path}\"");

                var result = Command.Create("dotnet-build", argsBuilder.ToString())
                       .ForwardStdOut()
                       .ForwardStdErr()
                       .Execute();

                if (result.ExitCode != 0)
                {
                    return false;
                }
            }

            var packDiagnostics = new List<DiagnosticMessage>();

            var mainPackageGenerator = new PackageGenerator(project, configuration, outputValue);
            var symbolsPackageGenerator = new SymbolPackageGenerator(project, configuration, outputValue);

            return mainPackageGenerator.BuildPackage(contexts, packDiagnostics) &&
                symbolsPackageGenerator.BuildPackage(contexts, packDiagnostics);
        }
        private Project GetProject(JObject json, ProjectReaderSettings settings = null)
        {
            using (var stream = new MemoryStream())
            {
                using (var sw = new StreamWriter(stream, Encoding.UTF8, 256, true))
                {
                    using (var writer = new JsonTextWriter(sw))
                    {
                        writer.Formatting = Formatting.Indented;
                        json.WriteTo(writer);
                    }

                    stream.Position = 0;
                    var projectReader = new ProjectReader();
                    return projectReader.ReadProject(
                        stream,
                        ProjectName,
                        ProjectFilePath,
                        settings);
                }
            }
        }
Beispiel #12
0
 public static Project GetProject(string projectPath, ProjectReaderSettings settings = null)
 {
     return(new ProjectReader().ReadProject(projectPath, settings));
 }
Beispiel #13
0
 public DesignTimeWorkspace(ProjectReaderSettings settings) : base(settings, true)
 {
 }
Beispiel #14
0
 public static Project GetProject(string projectPath, ProjectReaderSettings settings = null) => GetProject(projectPath, new List<DiagnosticMessage>(), settings);
Beispiel #15
0
        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;
                    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.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.Tools = 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);

            PopulateDependencies(
                project.ProjectFilePath,
                project.Tools,
                rawProject,
                "tools",
                isGacOrFrameworkReference: false);

            return project;
        }
Beispiel #16
0
        public static int Main(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            var app = new CommandLineApplication();
            app.Name = "dotnet pack";
            app.FullName = ".NET Packager";
            app.Description = "Packager for the .NET Platform";
            app.HelpOption("-h|--help");

            var output = app.Option("-o|--output <OUTPUT_DIR>", "Directory in which to place outputs", CommandOptionType.SingleValue);
            var intermediateOutput = app.Option("-t|--temp-output <OUTPUT_DIR>", "Directory in which to place temporary outputs", CommandOptionType.SingleValue);
            var configuration = app.Option("-c|--configuration <CONFIGURATION>", "Configuration under which to build", CommandOptionType.SingleValue);
            var versionSuffix = app.Option("--version-suffix <VERSION_SUFFIX>", "Defines what `*` should be replaced with in version field in project.json", CommandOptionType.SingleValue);
            var project = app.Argument("<PROJECT>", "The project to compile, defaults to the current directory. Can be a path to a project.json or a project directory");

            app.OnExecute(() =>
            {
                // Locate the project and get the name and full path
                var path = project.Value;
                if (string.IsNullOrEmpty(path))
                {
                    path = Directory.GetCurrentDirectory();
                }

                if(!path.EndsWith(Project.FileName))
                {
                    path = Path.Combine(path, Project.FileName);
                }

                if(!File.Exists(path))
                {
                    Reporter.Error.WriteLine($"Unable to find a project.json in {path}");
                    return 1;
                }

                // Set defaults based on the environment
                var settings = new ProjectReaderSettings();
                settings.VersionSuffix = Environment.GetEnvironmentVariable("DOTNET_BUILD_VERSION");
                settings.AssemblyFileVersion = Environment.GetEnvironmentVariable("DOTNET_ASSEMBLY_FILE_VERSION");

                if (versionSuffix.HasValue())
                {
                    settings.VersionSuffix = versionSuffix.Value();
                }

                var configValue = configuration.Value() ?? Cli.Utils.Constants.DefaultConfiguration;
                var outputValue = output.Value();

                return TryBuildPackage(path, configValue, outputValue, intermediateOutput.Value(), settings) ? 0 : 1;
            });

            try
            {
                return app.Execute(args);
            }
            catch (Exception ex)
            {
#if DEBUG
                Console.Error.WriteLine(ex);
#else
                Console.Error.WriteLine(ex.Message);
#endif
                return 1;
            }
        }
 public ProjectContextBuilder WithProjectReaderSettings(ProjectReaderSettings projectReaderSettings)
 {
     ProjectReaderSettings = projectReaderSettings;
     return this;
 }
Beispiel #18
0
        public static int Run(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            var app = new CommandLineApplication();
            app.Name = "dotnet pack";
            app.FullName = ".NET Packager";
            app.Description = "Packager for the .NET Platform";
            app.HelpOption("-h|--help");

            var output = app.Option("-o|--output <OUTPUT_DIR>", "Directory in which to place outputs", CommandOptionType.SingleValue);
            var noBuild = app.Option("--no-build", "Do not build project before packing", CommandOptionType.NoValue);
            var buildBasePath = app.Option("-b|--build-base-path <OUTPUT_DIR>", "Directory in which to place temporary build outputs", CommandOptionType.SingleValue);
            var configuration = app.Option("-c|--configuration <CONFIGURATION>", "Configuration under which to build", CommandOptionType.SingleValue);
            var versionSuffix = app.Option("--version-suffix <VERSION_SUFFIX>", "Defines what `*` should be replaced with in version field in project.json", CommandOptionType.SingleValue);
            var path = app.Argument("<PROJECT>", "The project to compile, defaults to the current directory. Can be a path to a project.json or a project directory");

            app.OnExecute(() =>
            {
                // Locate the project and get the name and full path
                var pathValue = path.Value;
                if (string.IsNullOrEmpty(pathValue))
                {
                    pathValue = Directory.GetCurrentDirectory();
                }

                if(!pathValue.EndsWith(Project.FileName))
                {
                    pathValue = Path.Combine(pathValue, Project.FileName);
                }

                if(!File.Exists(pathValue))
                {
                    Reporter.Error.WriteLine($"Unable to find a project.json in {pathValue}");
                    return 1;
                }

                // Set defaults based on the environment
                var settings = new ProjectReaderSettings();
                settings.VersionSuffix = Environment.GetEnvironmentVariable("DOTNET_BUILD_VERSION");
                settings.AssemblyFileVersion = Environment.GetEnvironmentVariable("DOTNET_ASSEMBLY_FILE_VERSION");

                if (versionSuffix.HasValue())
                {
                    settings.VersionSuffix = versionSuffix.Value();
                }

                var contexts = ProjectContext.CreateContextForEachFramework(pathValue, settings);

                var configValue = configuration.Value() ?? Cli.Utils.Constants.DefaultConfiguration;
                var outputValue = output.Value();
                var buildBasePathValue = buildBasePath.Value();

                var project = contexts.First().ProjectFile;

                var artifactPathsCalculator = new ArtifactPathsCalculator(project, buildBasePathValue, outputValue, configValue);
                var packageBuilder = new PackagesGenerator(contexts, artifactPathsCalculator, configValue);

                int buildResult = 0;
                if (!noBuild.HasValue())
                {
                    var buildProjectCommand = new BuildProjectCommand(project, artifactPathsCalculator, buildBasePathValue, configValue);
                    buildResult = buildProjectCommand.Execute();
                }

                return buildResult != 0 ? buildResult : packageBuilder.Build();
            });

            try
            {
                return app.Execute(args);
            }
            catch (Exception ex)
            {
#if DEBUG
                Console.Error.WriteLine(ex);
#else
                Console.Error.WriteLine(ex.Message);
#endif
                return 1;
            }
        }                
Beispiel #19
0
        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;
                    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.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.Tools        = 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);

            PopulateDependencies(
                project.ProjectFilePath,
                project.Tools,
                rawProject,
                "tools",
                isGacOrFrameworkReference: false);

            return(project);
        }
Beispiel #20
0
 public static Project GetProject(string projectFile, ProjectReaderSettings settings = null)
 {
     return(GetProject(projectFile, new List <DiagnosticMessage>(), settings));
 }
Beispiel #21
0
        /// <summary>
        /// Creates a project context for each target located in the project at <paramref name="projectPath"/>
        /// </summary>
        public static IEnumerable <ProjectContext> CreateContextForEachTarget(string projectPath, ProjectReaderSettings settings = null)
        {
            var project = ProjectReader.GetProject(projectPath);

            return(new ProjectContextBuilder()
                   .WithProjectReaderSettings(settings)
                   .WithProject(project)
                   .BuildAllTargets());
        }
Beispiel #22
0
 public BuildWorkspace(ProjectReaderSettings settings) : base(settings, false)
 {
 }
Beispiel #23
0
 public ProjectContextBuilder WithProjectReaderSettings(ProjectReaderSettings projectReaderSettings)
 {
     ProjectReaderSettings = projectReaderSettings;
     return(this);
 }
Beispiel #24
0
        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 <ProjectLibraryDependency>();
            project.Tools        = new List <ProjectLibraryDependency>();

            // 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);
        }
 public DesignTimeWorkspace(ProjectReaderSettings settings) : base(settings, true) { }
Beispiel #26
0
        /// <summary>
        /// Creates a project context for each target located in the project at <paramref name="projectPath"/>
        /// </summary>
        public static IEnumerable<ProjectContext> CreateContextForEachTarget(string projectPath, ProjectReaderSettings settings = null)
        {
            var project = ProjectReader.GetProject(projectPath);

            return new ProjectContextBuilder()
                        .WithReaderSettings(settings)
                        .WithProject(project)
                        .BuildAllTargets();
        }
Beispiel #27
0
 protected Workspace(ProjectReaderSettings settings, bool designTime)
 {
     _settings       = settings;
     _lockFileReader = new LockFileReader();
     _designTime     = designTime;
 }
Beispiel #28
0
        /// <summary>
        /// Creates a project context for each framework located in the project at <paramref name="projectPath"/>
        /// </summary>
        public static IEnumerable <ProjectContext> CreateContextForEachFramework(string projectPath, ProjectReaderSettings settings = null, IEnumerable <string> runtimeIdentifiers = null)
        {
            if (!projectPath.EndsWith(Project.FileName))
            {
                projectPath = Path.Combine(projectPath, Project.FileName);
            }
            var project = ProjectReader.GetProject(projectPath, settings);

            foreach (var framework in project.GetTargetFrameworks())
            {
                yield return(new ProjectContextBuilder()
                             .WithProject(project)
                             .WithTargetFramework(framework.FrameworkName)
                             .WithReaderSettings(settings)
                             .WithRuntimeIdentifiers(runtimeIdentifiers ?? Enumerable.Empty <string>())
                             .Build());
            }
        }
Beispiel #29
0
 public static Project GetProject(string projectPath, ProjectReaderSettings settings = null) => GetProject(projectPath, new List <DiagnosticMessage>(), settings);
Beispiel #30
0
        public static Project GetProject(string projectFile, ICollection <DiagnosticMessage> diagnostics, ProjectReaderSettings settings = null)
        {
            var name = Path.GetFileName(Path.GetDirectoryName(projectFile));

            using (var stream = new FileStream(projectFile, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                return(new ProjectReader().ReadProject(stream, name, projectFile, diagnostics, settings));
            }
        }
Beispiel #31
0
        public static Project GetProject(string projectPath, ICollection <DiagnosticMessage> diagnostics, ProjectReaderSettings settings = null)
        {
            if (!projectPath.EndsWith(Project.FileName))
            {
                projectPath = Path.Combine(projectPath, Project.FileName);
            }

            var name = Path.GetFileName(Path.GetDirectoryName(projectPath));

            using (var stream = new FileStream(projectPath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                return(new ProjectReader().ReadProject(stream, name, projectPath, diagnostics, settings));
            }
        }
Beispiel #32
0
 public ProjectContextBuilder WithReaderSettings(ProjectReaderSettings settings)
 {
     Settings = settings;
     return this;
 }
Beispiel #33
0
 public static Project GetProject(string projectFile, ProjectReaderSettings settings = null)
 {
     return GetProject(projectFile, new List<DiagnosticMessage>(), settings);
 }
Beispiel #34
0
 public ProjectContextBuilder WithReaderSettings(ProjectReaderSettings settings)
 {
     Settings = settings;
     return(this);
 }
Beispiel #35
0
 public BuildWorkspace(ProjectReaderSettings settings) : base(settings, false) { }