示例#1
0
        void InitializeProperties(ProjectRootElement xml, ProjectInstance parent)
        {
                        #if NET_4_5
            location = xml.Location;
                        #endif
            full_path      = xml.FullPath;
            directory      = string.IsNullOrWhiteSpace(xml.DirectoryPath) ? System.IO.Directory.GetCurrentDirectory() : xml.DirectoryPath;
            DefaultTargets = GetDefaultTargets(xml);
            InitialTargets = xml.InitialTargets.Split(item_target_sep, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToList();

            raw_imports      = new List <ResolvedImport> ();
            item_definitions = new Dictionary <string, ProjectItemDefinitionInstance> ();
            targets          = new Dictionary <string, ProjectTargetInstance> ();
            raw_items        = new List <ProjectItemInstance> ();

            // FIXME: this is likely hack. Test ImportedProject.Properties to see what exactly should happen.
            if (parent != null)
            {
                properties = parent.properties;
            }
            else
            {
                properties = new List <ProjectPropertyInstance> ();

                foreach (DictionaryEntry p in Environment.GetEnvironmentVariables())
                {
                    // FIXME: this is kind of workaround for unavoidable issue that PLATFORM=* is actually given
                    // on some platforms and that prevents setting default "PLATFORM=AnyCPU" property.
                    if (!string.Equals("PLATFORM", (string)p.Key, StringComparison.OrdinalIgnoreCase))
                    {
                        this.properties.Add(new ProjectPropertyInstance((string)p.Key, false, (string)p.Value));
                    }
                }
                foreach (var p in global_properties)
                {
                    this.properties.Add(new ProjectPropertyInstance(p.Key, false, p.Value));
                }
                var tools = projects.GetToolset(tools_version) ?? projects.GetToolset(projects.DefaultToolsVersion);
                foreach (var p in projects.GetReservedProperties(tools, this, xml))
                {
                    this.properties.Add(p);
                }
                foreach (var p in ProjectCollection.GetWellKnownProperties(this))
                {
                    this.properties.Add(p);
                }
            }

            ProcessXml(parent, xml);
        }
示例#2
0
        public void TestGenerateSubToolsetVersion_ExplicitlyPassedGlobalPropertyWins()
        {
            string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion");

            try
            {
                Environment.SetEnvironmentVariable("VisualStudioVersion", ObjectModelHelpers.CurrentVisualStudioVersion);

                IDictionary <string, string> globalProperties = new Dictionary <string, string>();
                globalProperties.Add("VisualStudioVersion", "v13.0");

                ProjectCollection projectCollection = new ProjectCollection(globalProperties);
                Toolset           parentToolset     = projectCollection.GetToolset("4.0");

                Toolset t = new Toolset("Fake", parentToolset.ToolsPath, null, projectCollection, null, parentToolset.OverrideTasksPath);

                IDictionary <string, string> explicitGlobalProperties = new Dictionary <string, string>();
                explicitGlobalProperties.Add("VisualStudioVersion", "FakeSubToolset");

                Assert.Equal("FakeSubToolset", t.GenerateSubToolsetVersion(explicitGlobalProperties, 0));
            }
            finally
            {
                Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion);
            }
        }
示例#3
0
        public void TestGenerateSubToolsetVersionWhenNoSubToolset()
        {
            string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion");

            try
            {
                Environment.SetEnvironmentVariable("VisualStudioVersion", null);

                ProjectCollection projectCollection = new ProjectCollection();
                Toolset           parentToolset     = projectCollection.GetToolset("4.0");

                Toolset t = new Toolset("Fake", parentToolset.ToolsPath, null, projectCollection, null, parentToolset.OverrideTasksPath);

                string subToolsetVersion = t.GenerateSubToolsetVersion();

                if (Toolset.Dev10IsInstalled)
                {
                    Assert.Equal(Constants.Dev10SubToolsetValue, subToolsetVersion);
                }
                else
                {
                    Assert.Null(subToolsetVersion);
                }
            }
            finally
            {
                Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion);
            }
        }
示例#4
0
        public void TestGenerateSubToolsetVersionWhenNoSubToolset()
        {
            if (NativeMethodsShared.IsUnixLike)
            {
                return; // "TODO: Under Unix this test throws. Investigate"
            }

            string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion");

            try
            {
                Environment.SetEnvironmentVariable("VisualStudioVersion", null);

                ProjectCollection projectCollection = new ProjectCollection();
                Toolset           parentToolset     = projectCollection.GetToolset(ObjectModelHelpers.MSBuildDefaultToolsVersion);

                Toolset t = new Toolset("Fake", parentToolset.ToolsPath, null, projectCollection, null, parentToolset.OverrideTasksPath);

                string subToolsetVersion = t.GenerateSubToolsetVersion();

                if (Toolset.Dev10IsInstalled)
                {
                    Assert.Equal(Constants.Dev10SubToolsetValue, subToolsetVersion);
                }
                else
                {
                    Assert.Null(subToolsetVersion);
                }
            }
            finally
            {
                Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion);
            }
        }
示例#5
0
        public void TestDefaultWhenNoSubToolset()
        {
            string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion");

            try
            {
                Environment.SetEnvironmentVariable("VisualStudioVersion", null);

                ProjectCollection projectCollection = new ProjectCollection();
                Toolset           parentToolset     = projectCollection.GetToolset(ObjectModelHelpers.MSBuildDefaultToolsVersion);

                Toolset t = new Toolset("Fake", parentToolset.ToolsPath, null, projectCollection, null, parentToolset.OverrideTasksPath);

                if (Toolset.Dev10IsInstalled)
                {
                    Assert.Equal(Constants.Dev10SubToolsetValue, t.DefaultSubToolsetVersion);
                }
                else
                {
                    Assert.Null(t.DefaultSubToolsetVersion);
                }
            }
            finally
            {
                Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion);
            }
        }
示例#6
0
        /// <summary>
        ///     Create an MSBuild project collection.
        /// </summary>
        /// <param name="solutionDirectory">
        ///     The base (i.e. solution) directory.
        /// </param>
        /// <param name="runtimeInfo">
        ///     Information about the current .NET Core runtime.
        /// </param>
        /// <param name="globalPropertyOverrides">
        ///     An optional dictionary containing property values to override.
        /// </param>
        /// <returns>
        ///     The project collection.
        /// </returns>
        public static ProjectCollection CreateProjectCollection(string solutionDirectory, DotNetRuntimeInfo runtimeInfo, Dictionary <string, string> globalPropertyOverrides = null)
        {
            if (String.IsNullOrWhiteSpace(solutionDirectory))
            {
                throw new ArgumentException("Argument cannot be null, empty, or entirely composed of whitespace: 'baseDir'.", nameof(solutionDirectory));
            }

            if (runtimeInfo == null)
            {
                throw new ArgumentNullException(nameof(runtimeInfo));
            }

            if (String.IsNullOrWhiteSpace(runtimeInfo.BaseDirectory))
            {
                throw new InvalidOperationException("Cannot determine base directory for .NET Core (check the output of 'dotnet --info').");
            }

            Dictionary <string, string> globalProperties = CreateGlobalMSBuildProperties(runtimeInfo, solutionDirectory, globalPropertyOverrides);

            EnsureMSBuildEnvironment(globalProperties);

            ProjectCollection projectCollection = new ProjectCollection(globalProperties)
            {
                IsBuildEnabled = false
            };

            SemanticVersion netcoreVersion;

            if (!SemanticVersion.TryParse(runtimeInfo.Version, out netcoreVersion))
            {
                throw new FormatException($"Cannot parse .NET Core version '{runtimeInfo.Version}' (does not appear to be a valid semantic version).");
            }

            // For .NET Core 3.0 and newer, toolset version is simply "Current" instead of "15.0" (tintoy/msbuild-project-tools-vscode#46).
            string toolsVersion = netcoreVersion.Major < 3 ? "15.0" : "Current";

            // Override toolset paths (for some reason these point to the main directory where the dotnet executable lives).
            Toolset toolset = projectCollection.GetToolset(toolsVersion);

            toolset = new Toolset(toolsVersion,
                                  toolsPath: runtimeInfo.BaseDirectory,
                                  projectCollection: projectCollection,
                                  msbuildOverrideTasksPath: ""
                                  );

            // Other toolset versions won't be supported by the .NET Core SDK
            projectCollection.RemoveAllToolsets();

            // TODO: Add configuration setting that enables user to configure custom toolsets.

            projectCollection.AddToolset(toolset);
            projectCollection.DefaultToolsVersion = toolsVersion;

            return(projectCollection);
        }
示例#7
0
        /// <summary>
        /// Creates a standard ProjectCollection and adds a fake toolset with the following contents to it:
        ///
        /// ToolsVersion = Fake
        /// Base Properties:
        /// a = a1
        /// b = b1
        ///
        /// SubToolset "12.0":
        /// d = d4
        /// e = e5
        ///
        /// SubToolset "v11.0":
        /// b = b2
        /// c = c2
        ///
        /// SubToolset "FakeSubToolset":
        /// a = a3
        /// c = c3
        ///
        /// SubToolset "v13.0":
        /// f = f6
        /// g = g7
        /// </summary>
        private Toolset GetFakeToolset(IDictionary <string, string> globalPropertiesForProjectCollection)
        {
            ProjectCollection projectCollection = new ProjectCollection(globalPropertiesForProjectCollection);

            IDictionary <string, string> properties = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            properties.Add("a", "a1");
            properties.Add("b", "b1");

            Dictionary <string, SubToolset> subToolsets = new Dictionary <string, SubToolset>(StringComparer.OrdinalIgnoreCase);

            // SubToolset 12.0 properties
            PropertyDictionary <ProjectPropertyInstance> subToolset12Properties = new PropertyDictionary <ProjectPropertyInstance>();

            subToolset12Properties.Set(ProjectPropertyInstance.Create("d", "d4"));
            subToolset12Properties.Set(ProjectPropertyInstance.Create("e", "e5"));

            // SubToolset v11.0 properties
            PropertyDictionary <ProjectPropertyInstance> subToolset11Properties = new PropertyDictionary <ProjectPropertyInstance>();

            subToolset11Properties.Set(ProjectPropertyInstance.Create("b", "b2"));
            subToolset11Properties.Set(ProjectPropertyInstance.Create("c", "c2"));

            // FakeSubToolset properties
            PropertyDictionary <ProjectPropertyInstance> fakeSubToolsetProperties = new PropertyDictionary <ProjectPropertyInstance>();

            fakeSubToolsetProperties.Set(ProjectPropertyInstance.Create("a", "a3"));
            fakeSubToolsetProperties.Set(ProjectPropertyInstance.Create("c", "c3"));

            // SubToolset v13.0 properties
            PropertyDictionary <ProjectPropertyInstance> subToolset13Properties = new PropertyDictionary <ProjectPropertyInstance>();

            subToolset13Properties.Set(ProjectPropertyInstance.Create("f", "f6"));
            subToolset13Properties.Set(ProjectPropertyInstance.Create("g", "g7"));

            subToolsets.Add("12.0", new SubToolset("12.0", subToolset12Properties));
            subToolsets.Add("v11.0", new SubToolset("v11.0", subToolset11Properties));
            subToolsets.Add("FakeSubToolset", new SubToolset("FakeSubToolset", fakeSubToolsetProperties));
            subToolsets.Add("v13.0", new SubToolset("v13.0", subToolset13Properties));

            Toolset parentToolset = projectCollection.GetToolset("4.0");

            Toolset fakeToolset = new Toolset("Fake", parentToolset.ToolsPath, properties, projectCollection, subToolsets, parentToolset.OverrideTasksPath);

            projectCollection.AddToolset(fakeToolset);

            return(fakeToolset);
        }
示例#8
0
        public void TestNoSubToolset_EnvironmentOverrides()
        {
            string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion");

            try
            {
                Environment.SetEnvironmentVariable("VisualStudioVersion", "foo");

                ProjectCollection projectCollection = new ProjectCollection();
                Toolset           parentToolset     = projectCollection.GetToolset("4.0");

                Toolset t = new Toolset("Fake", parentToolset.ToolsPath, null, projectCollection, null, parentToolset.OverrideTasksPath);

                Assert.Equal("foo", t.GenerateSubToolsetVersion());
            }
            finally
            {
                Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion);
            }
        }
示例#9
0
        /// <summary>
        ///     Create an MSBuild project collection.
        /// </summary>
        /// <param name="solutionDirectory">
        ///     The base (i.e. solution) directory.
        /// </param>
        /// <param name="runtimeInfo">
        ///     Information about the current .NET Core runtime.
        /// </param>
        /// <returns>
        ///     The project collection.
        /// </returns>
        public static ProjectCollection CreateProjectCollection(string solutionDirectory, DotNetRuntimeInfo runtimeInfo)
        {
            if (String.IsNullOrWhiteSpace(solutionDirectory))
            {
                throw new ArgumentException("Argument cannot be null, empty, or entirely composed of whitespace: 'baseDir'.", nameof(solutionDirectory));
            }

            if (runtimeInfo == null)
            {
                throw new ArgumentNullException(nameof(runtimeInfo));
            }

            if (String.IsNullOrWhiteSpace(runtimeInfo.BaseDirectory))
            {
                throw new InvalidOperationException("Cannot determine base directory for .NET Core.");
            }

            Dictionary <string, string> globalProperties = CreateGlobalMSBuildProperties(runtimeInfo, solutionDirectory);

            EnsureMSBuildEnvironment(globalProperties);

            ProjectCollection projectCollection = new ProjectCollection(globalProperties)
            {
                IsBuildEnabled = false
            };

            // Override toolset paths (for some reason these point to the main directory where the dotnet executable lives).
            Toolset toolset = projectCollection.GetToolset("15.0");

            toolset = new Toolset(
                toolsVersion: "15.0",
                toolsPath: globalProperties["MSBuildExtensionsPath"],
                projectCollection: projectCollection,
                msbuildOverrideTasksPath: ""
                );
            projectCollection.AddToolset(toolset);

            return(projectCollection);
        }
示例#10
0
        public void TestNoSubToolset_GlobalPropertyOverrides()
        {
            string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion");

            try
            {
                Environment.SetEnvironmentVariable("VisualStudioVersion", null);

                IDictionary <string, string> globalProperties = new Dictionary <string, string>();
                globalProperties.Add("VisualStudioVersion", "99.0");

                ProjectCollection projectCollection = new ProjectCollection(globalProperties);
                Toolset           parentToolset     = projectCollection.GetToolset("4.0");

                Toolset t = new Toolset("Fake", parentToolset.ToolsPath, null, projectCollection, null, parentToolset.OverrideTasksPath);

                Assert.Equal("99.0", t.GenerateSubToolsetVersion());
            }
            finally
            {
                Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion);
            }
        }
示例#11
0
        public void Execute()
        {
            bool result          = false;
            bool show_stacktrace = false;

            try {
                parameters.ParseArguments(args);
                show_stacktrace = (parameters.LoggerVerbosity == LoggerVerbosity.Detailed ||
                                   parameters.LoggerVerbosity == LoggerVerbosity.Diagnostic);

                if (!parameters.NoLogo)
                {
                    ErrorUtilities.ShowVersion(false);
                }

                project_collection = new ProjectCollection();
                if (!String.IsNullOrEmpty(parameters.ToolsVersion))
                {
                    if (project_collection.GetToolset(parameters.ToolsVersion) == null)
                    {
                        ErrorUtilities.ReportError(0, new InvalidToolsetDefinitionException("Toolset " + parameters.ToolsVersion + " was not found").Message);
                    }

                    project_collection.DefaultToolsVersion = parameters.ToolsVersion;
                }

                foreach (var p in parameters.Properties)
                {
                    project_collection.GlobalProperties.Add(p.Key, p.Value);
                }

                if (!parameters.NoConsoleLogger)
                {
                    printer = new ConsoleReportPrinter();
                    ConsoleLogger cl = new ConsoleLogger(parameters.LoggerVerbosity,
                                                         printer.Print, printer.SetForeground, printer.ResetColor);

                    cl.Parameters = parameters.ConsoleLoggerParameters;
                    cl.Verbosity  = parameters.LoggerVerbosity;
                    project_collection.RegisterLogger(cl);
                }

                if (parameters.FileLoggerParameters != null)
                {
                    for (int i = 0; i < parameters.FileLoggerParameters.Length; i++)
                    {
                        string fl_params = parameters.FileLoggerParameters [i];
                        if (fl_params == null)
                        {
                            continue;
                        }

                        var fl = new FileLogger();
                        if (fl_params.Length == 0 && i > 0)
                        {
                            fl.Parameters = String.Format("LogFile=msbuild{0}.log", i);
                        }
                        else
                        {
                            fl.Parameters = fl_params;
                        }
                        project_collection.RegisterLogger(fl);
                    }
                }

                foreach (LoggerInfo li in parameters.Loggers)
                {
                    Assembly assembly;
                    if (li.InfoType == LoadInfoType.AssemblyFilename)
                    {
                        assembly = Assembly.LoadFrom(li.Filename);
                    }
                    else
                    {
                        assembly = Assembly.Load(li.AssemblyName);
                    }
                    ILogger logger = (ILogger)Activator.CreateInstance(assembly.GetType(li.ClassName));
                    logger.Parameters = li.Parameters;
                    project_collection.RegisterLogger(logger);
                }

                string projectFile = parameters.ProjectFile;
                if (!File.Exists(projectFile))
                {
                    ErrorUtilities.ReportError(0, String.Format("Project file '{0}' not found.", projectFile));
                    return;
                }

                XmlReaderSettings settings = new XmlReaderSettings();
                if (parameters.Validate)
                {
                    settings.ValidationType = ValidationType.Schema;
                    if (parameters.ValidationSchema == null)
                    {
                        using (var xsdxml = XmlReader.Create(defaultSchema))
                            settings.Schemas.Add(XmlSchema.Read(xsdxml, null));
                    }
                    else
                    {
                        using (var xsdxml = XmlReader.Create(parameters.ValidationSchema))
                            settings.Schemas.Add(XmlSchema.Read(xsdxml, null));
                    }
                }

                var projectInstances = new List <ProjectInstance> ();
                if (string.Equals(Path.GetExtension(projectFile), ".sln", StringComparison.OrdinalIgnoreCase))
                {
                    var parser = new SolutionParser();
                    var root   = ProjectRootElement.Create(project_collection);
                    root.FullPath = projectFile;
                    parser.ParseSolution(projectFile, project_collection, root, LogWarning);
                    projectInstances.Add(new Project(root, parameters.Properties, parameters.ToolsVersion, project_collection).CreateProjectInstance());
                }
                else
                {
                    project          = ProjectRootElement.Create(XmlReader.Create(projectFile, settings), project_collection);
                    project.FullPath = projectFile;
                    var pi = new ProjectInstance(project, parameters.Properties, parameters.ToolsVersion, project_collection);
                    projectInstances.Add(pi);
                }
                foreach (var projectInstance in projectInstances)
                {
                    var targets = parameters.Targets.Length > 0 ? parameters.Targets : projectInstance.DefaultTargets.ToArray();
                    result = projectInstance.Build(targets, parameters.Loggers.Count > 0 ? parameters.Loggers : project_collection.Loggers);
                    if (!result)
                    {
                        break;
                    }
                }
            }

            catch (InvalidProjectFileException ipfe) {
                ErrorUtilities.ReportError(0, show_stacktrace ? ipfe.ToString() : ipfe.Message);
            }

            catch (InternalLoggerException ile) {
                ErrorUtilities.ReportError(0, show_stacktrace ? ile.ToString() : ile.Message);
            }

            catch (CommandLineException cle) {
                ErrorUtilities.ReportError(cle.ErrorCode, show_stacktrace ? cle.ToString() : cle.Message);
            }
            finally {
                //if (project_collection != null)
                //	project_collection.UnregisterAllLoggers ();

                Environment.Exit(result ? 0 : 1);
            }
        }
示例#12
0
        string [] GetDefaultTargets(ProjectRootElement xml, bool fromAttribute, bool checkImports)
        {
            if (fromAttribute)
            {
                var ret = xml.DefaultTargets.Split(item_target_sep, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray();
                if (checkImports && ret.Length == 0)
                {
                    foreach (var imp in this.raw_imports)
                    {
                        ret = GetDefaultTargets(imp.ImportedProject, true, false);
                        if (ret.Any())
                        {
                            break;
                        }
                    }
                }
                return(ret);
            }
            else
            {
                if (xml.Targets.Any())
                {
                    return new String [] { xml.Targets.First().Name }
                }
                ;
                if (checkImports)
                {
                    foreach (var imp in this.raw_imports)
                    {
                        var ret = GetDefaultTargets(imp.ImportedProject, false, false);
                        if (ret.Any())
                        {
                            return(ret);
                        }
                    }
                }
                return(new string [0]);
            }
        }

        void InitializeProperties(ProjectRootElement xml)
        {
            location       = xml.Location;
            full_path      = xml.FullPath;
            directory      = string.IsNullOrWhiteSpace(xml.DirectoryPath) ? System.IO.Directory.GetCurrentDirectory() : xml.DirectoryPath;
            InitialTargets = xml.InitialTargets.Split(item_target_sep, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToList();

            raw_imports      = new List <ResolvedImport> ();
            item_definitions = new Dictionary <string, ProjectItemDefinitionInstance> ();
            targets          = new Dictionary <string, ProjectTargetInstance> ();
            raw_items        = new List <ProjectItemInstance> ();

            properties = new Dictionary <string, ProjectPropertyInstance> ();

            foreach (DictionaryEntry p in Environment.GetEnvironmentVariables())
            {
                // FIXME: this is kind of workaround for unavoidable issue that PLATFORM=* is actually given
                // on some platforms and that prevents setting default "PLATFORM=AnyCPU" property.
                if (!string.Equals("PLATFORM", (string)p.Key, StringComparison.OrdinalIgnoreCase))
                {
                    this.properties [(string)p.Key] = new ProjectPropertyInstance((string)p.Key, true, (string)p.Value);
                }
            }
            foreach (var p in global_properties)
            {
                this.properties [p.Key] = new ProjectPropertyInstance(p.Key, false, p.Value);
            }
            var tools = projects.GetToolset(tools_version) ?? projects.GetToolset(projects.DefaultToolsVersion);

            foreach (var p in projects.GetReservedProperties(tools, this, xml))
            {
                this.properties [p.Name] = p;
            }
            foreach (var p in ProjectCollection.GetWellKnownProperties(this))
            {
                this.properties [p.Name] = p;
            }

            ProcessXml(xml);

            DefaultTargets = GetDefaultTargets(xml).ToList();
        }