public override IProjectProperties GetCommonProperties(ProjectInstance projectInstance)
        {
            IProjectProperties defaultProperties = base.GetCommonProperties(projectInstance);

            return(InterceptProperties(defaultProperties));
        }
コード例 #2
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();
                    parser.ParseSolution(projectFile, project_collection, root, LogWarning);
                    foreach (var p in project_collection.LoadedProjects)
                    {
                        projectInstances.Add(p.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 ? projectInstance.DefaultTargets.ToArray() : parameters.Targets;
                    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);
            }
        }
コード例 #3
0
 public virtual IProjectProperties GetItemProperties(ProjectInstance projectInstance, string itemType, string itemName)
 => DelegatedInstanceProvider.GetItemProperties(projectInstance, itemType, itemName);
コード例 #4
0
        public void GetBuckets()
        {
            ProjectInstance project    = ProjectHelpers.CreateEmptyProjectInstance();
            List <string>   parameters = new List <string>();

            parameters.Add("@(File);$(unittests)");
            parameters.Add("$(obj)\\%(Filename).ext");
            parameters.Add("@(File->'%(extension)')");  // attributes in transforms don't affect batching

            ItemDictionary <ProjectItemInstance> itemsByType = new ItemDictionary <ProjectItemInstance>();

            IList <ProjectItemInstance> items = new List <ProjectItemInstance>();

            items.Add(new ProjectItemInstance(project, "File", "a.foo", project.FullPath));
            items.Add(new ProjectItemInstance(project, "File", "b.foo", project.FullPath));
            items.Add(new ProjectItemInstance(project, "File", "c.foo", project.FullPath));
            items.Add(new ProjectItemInstance(project, "File", "d.foo", project.FullPath));
            items.Add(new ProjectItemInstance(project, "File", "e.foo", project.FullPath));
            itemsByType.ImportItems(items);

            items = new List <ProjectItemInstance>();
            items.Add(new ProjectItemInstance(project, "Doc", "a.doc", project.FullPath));
            items.Add(new ProjectItemInstance(project, "Doc", "b.doc", project.FullPath));
            items.Add(new ProjectItemInstance(project, "Doc", "c.doc", project.FullPath));
            items.Add(new ProjectItemInstance(project, "Doc", "d.doc", project.FullPath));
            items.Add(new ProjectItemInstance(project, "Doc", "e.doc", project.FullPath));
            itemsByType.ImportItems(items);

            PropertyDictionary <ProjectPropertyInstance> properties = new PropertyDictionary <ProjectPropertyInstance>();

            properties.Set(ProjectPropertyInstance.Create("UnitTests", "unittests.foo"));
            properties.Set(ProjectPropertyInstance.Create("OBJ", "obj"));

            List <ItemBucket> buckets = BatchingEngine.PrepareBatchingBuckets(parameters, CreateLookup(itemsByType, properties), MockElementLocation.Instance);

            Assert.Equal(5, buckets.Count);

            foreach (ItemBucket bucket in buckets)
            {
                // non-batching data -- same for all buckets
                XmlAttribute tempXmlAttribute = (new XmlDocument()).CreateAttribute("attrib");
                tempXmlAttribute.Value = "'$(Obj)'=='obj'";

                Assert.True(ConditionEvaluator.EvaluateCondition(tempXmlAttribute.Value, ParserOptions.AllowAll, bucket.Expander, ExpanderOptions.ExpandAll, Directory.GetCurrentDirectory(), MockElementLocation.Instance, null, new BuildEventContext(1, 2, 3, 4), FileSystems.Default));
                Assert.Equal("a.doc;b.doc;c.doc;d.doc;e.doc", bucket.Expander.ExpandIntoStringAndUnescape("@(doc)", ExpanderOptions.ExpandItems, MockElementLocation.Instance));
                Assert.Equal("unittests.foo", bucket.Expander.ExpandIntoStringAndUnescape("$(bogus)$(UNITTESTS)", ExpanderOptions.ExpandPropertiesAndMetadata, MockElementLocation.Instance));
            }

            Assert.Equal("a.foo", buckets[0].Expander.ExpandIntoStringAndUnescape("@(File)", ExpanderOptions.ExpandItems, MockElementLocation.Instance));
            Assert.Equal(".foo", buckets[0].Expander.ExpandIntoStringAndUnescape("@(File->'%(Extension)')", ExpanderOptions.ExpandItems, MockElementLocation.Instance));
            Assert.Equal("obj\\a.ext", buckets[0].Expander.ExpandIntoStringAndUnescape("$(obj)\\%(Filename).ext", ExpanderOptions.ExpandPropertiesAndMetadata, MockElementLocation.Instance));

            // we weren't batching on this attribute, so it has no value
            Assert.Equal(String.Empty, buckets[0].Expander.ExpandIntoStringAndUnescape("%(Extension)", ExpanderOptions.ExpandAll, MockElementLocation.Instance));

            ProjectItemInstanceFactory factory = new ProjectItemInstanceFactory(project, "i");

            items = buckets[0].Expander.ExpandIntoItemsLeaveEscaped("@(file)", factory, ExpanderOptions.ExpandItems, MockElementLocation.Instance);
            Assert.NotNull(items);
            Assert.Single(items);

            int invalidProjectFileExceptions = 0;

            try
            {
                // This should throw because we don't allow item lists to be concatenated
                // with other strings.
                bool throwAway;
                items = buckets[0].Expander.ExpandSingleItemVectorExpressionIntoItems("@(file)$(unitests)", factory, ExpanderOptions.ExpandItems, false /* no nulls */, out throwAway, MockElementLocation.Instance);
            }
            catch (InvalidProjectFileException ex)
            {
                // check we don't lose error codes from IPFE's during build
                Assert.Equal("MSB4012", ex.ErrorCode);
                invalidProjectFileExceptions++;
            }

            // We do allow separators in item vectors, this results in an item group with a single flattened item
            items = buckets[0].Expander.ExpandIntoItemsLeaveEscaped("@(file, ',')", factory, ExpanderOptions.ExpandItems, MockElementLocation.Instance);
            Assert.NotNull(items);
            Assert.Single(items);
            Assert.Equal("a.foo", items[0].EvaluatedInclude);

            Assert.Equal(1, invalidProjectFileExceptions);
        }
コード例 #5
0
        private static void AssertAnalysisTargetsAreNotImported(ProjectInstance projectInstance)
        {
            ProjectPropertyInstance propertyInstance = projectInstance.GetProperty(DummyAnalysisTargetsMarkerProperty);

            Assert.IsNull(propertyInstance, "SonarQube Analysis targets should not have been imported");
        }
コード例 #6
0
        public void TestCache()
        {
            string projectBody = ObjectModelHelpers.CleanupFileContents(@"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<PropertyGroup>
    <One>1</One>
    <Two>2</Two>
    <Three>$(ThreeIn)</Three>
</PropertyGroup>
<ItemGroup>
    <Foo Include=""*""/>
    <Bar Include=""msbuild.out"">
        <One>1</One>
    </Bar>
    <Baz Include=""$(BazIn)""/>
</ItemGroup>
<Target Name='Build'>
    <CallTarget Targets='Foo;Goo'/>
</Target>

<Target Name='Foo' DependsOnTargets='Foo2'>
    <FooTarget/>
</Target>

<Target Name='Goo'>
    <GooTarget/>
</Target>

<Target Name='Foo2'>
    <Foo2Target/>
</Target>
</Project>");

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

            globalProperties["ThreeIn"] = "3";
            globalProperties["BazIn"]   = "bazfile";

            Project project = new Project(
                XmlReader.Create(new StringReader(projectBody)),
                globalProperties,
                ObjectModelHelpers.MSBuildDefaultToolsVersion,
                new ProjectCollection());

            project.FullPath = "foo";
            ProjectInstance           instance      = project.CreateProjectInstance();
            BuildRequestConfiguration configuration = new BuildRequestConfiguration(new BuildRequestData(instance, new string[] { }, null), "2.0");

            configuration.ConfigurationId = 1;

            string originalValue = Environment.GetEnvironmentVariable("MSBUILDCACHE");

            try
            {
                Environment.SetEnvironmentVariable("MSBUILDCACHE", "1");
                Assert.Equal("3", instance.GlobalProperties["ThreeIn"]);
                Assert.Equal("bazfile", instance.GlobalProperties["BazIn"]);
                Assert.Equal("1", instance.PropertiesToBuildWith["One"].EvaluatedValue);
                Assert.Equal("2", instance.PropertiesToBuildWith["Two"].EvaluatedValue);
                Assert.Equal("3", instance.PropertiesToBuildWith["Three"].EvaluatedValue);

                int fooCount = instance.ItemsToBuildWith["Foo"].Count;
                Assert.True(fooCount > 0);
                Assert.Single(instance.ItemsToBuildWith["Bar"]);
                Assert.Single(instance.ItemsToBuildWith["Baz"]);
                Assert.Equal("bazfile", instance.ItemsToBuildWith["Baz"].First().EvaluatedInclude);

                Lookup lookup = configuration.BaseLookup;

                Assert.NotNull(lookup);
                Assert.Equal(fooCount, lookup.GetItems("Foo").Count);

                // Configuration initialized with a ProjectInstance should not be cacheable by default.
                Assert.False(configuration.IsCacheable);
                configuration.IsCacheable = true;
                configuration.CacheIfPossible();

                Assert.Null(instance.GlobalPropertiesDictionary);
                Assert.Null(instance.ItemsToBuildWith);
                Assert.Null(instance.PropertiesToBuildWith);

                configuration.RetrieveFromCache();

                Assert.Equal("3", instance.GlobalProperties["ThreeIn"]);
                Assert.Equal("bazfile", instance.GlobalProperties["BazIn"]);
                Assert.Equal("1", instance.PropertiesToBuildWith["One"].EvaluatedValue);
                Assert.Equal("2", instance.PropertiesToBuildWith["Two"].EvaluatedValue);
                Assert.Equal("3", instance.PropertiesToBuildWith["Three"].EvaluatedValue);
                Assert.Equal(fooCount, instance.ItemsToBuildWith["Foo"].Count);
                Assert.Single(instance.ItemsToBuildWith["Bar"]);
                Assert.Single(instance.ItemsToBuildWith["Baz"]);
                Assert.Equal("bazfile", instance.ItemsToBuildWith["Baz"].First().EvaluatedInclude);

                lookup = configuration.BaseLookup;

                Assert.NotNull(lookup);
                Assert.Equal(fooCount, lookup.GetItems("Foo").Count);
            }
            finally
            {
                configuration.ClearCacheFile();
                Environment.SetEnvironmentVariable("MSBUILDCACHE", originalValue);
            }
        }
コード例 #7
0
        public void ConditionedPropertyUpdateTests()
        {
            Parser          p             = new Parser();
            ProjectInstance parentProject = new ProjectInstance(ProjectRootElement.Create());
            ItemDictionary <ProjectItemInstance> itemBag = new ItemDictionary <ProjectItemInstance>();

            itemBag.Add(new ProjectItemInstance(parentProject, "Compile", "foo.cs", parentProject.FullPath));
            itemBag.Add(new ProjectItemInstance(parentProject, "Compile", "bar.cs", parentProject.FullPath));
            itemBag.Add(new ProjectItemInstance(parentProject, "Compile", "baz.cs", parentProject.FullPath));

            Expander <ProjectPropertyInstance, ProjectItemInstance> expander = new Expander <ProjectPropertyInstance, ProjectItemInstance>(new PropertyDictionary <ProjectPropertyInstance>(), itemBag, FileSystems.Default);
            Dictionary <string, List <string> > conditionedProperties        = new Dictionary <string, List <string> >();

            ConditionEvaluator.IConditionEvaluationState state =
                new ConditionEvaluator.ConditionEvaluationState <ProjectPropertyInstance, ProjectItemInstance>
                (
                    String.Empty,
                    expander,
                    ExpanderOptions.ExpandAll,
                    conditionedProperties,
                    Directory.GetCurrentDirectory(),
                    ElementLocation.EmptyLocation,
                    FileSystems.Default
                );

            List <string> properties = null;

            AssertParseEvaluate(p, "'0' == '1'", expander, false, state);
            Assert.Empty(conditionedProperties);

            AssertParseEvaluate(p, "$(foo) == foo", expander, false, state);
            Assert.Single(conditionedProperties);
            properties = conditionedProperties["foo"];
            Assert.Single(properties);

            AssertParseEvaluate(p, "'$(foo)' != 'bar'", expander, true, state);
            Assert.Single(conditionedProperties);
            properties = conditionedProperties["foo"];
            Assert.Equal(2, properties.Count);

            AssertParseEvaluate(p, "'$(branch)|$(build)|$(platform)' == 'lab22dev|debug|x86'", expander, false, state);
            Assert.Equal(4, conditionedProperties.Count);
            properties = conditionedProperties["foo"];
            Assert.Equal(2, properties.Count);
            properties = conditionedProperties["branch"];
            Assert.Single(properties);
            properties = conditionedProperties["build"];
            Assert.Single(properties);
            properties = conditionedProperties["platform"];
            Assert.Single(properties);

            AssertParseEvaluate(p, "'$(branch)|$(build)|$(platform)' == 'lab21|debug|x86'", expander, false, state);
            Assert.Equal(4, conditionedProperties.Count);
            properties = conditionedProperties["foo"];
            Assert.Equal(2, properties.Count);
            properties = conditionedProperties["branch"];
            Assert.Equal(2, properties.Count);
            properties = conditionedProperties["build"];
            Assert.Single(properties);
            properties = conditionedProperties["platform"];
            Assert.Single(properties);

            AssertParseEvaluate(p, "'$(branch)|$(build)|$(platform)' == 'lab23|retail|ia64'", expander, false, state);
            Assert.Equal(4, conditionedProperties.Count);
            properties = conditionedProperties["foo"];
            Assert.Equal(2, properties.Count);
            properties = conditionedProperties["branch"];
            Assert.Equal(3, properties.Count);
            properties = conditionedProperties["build"];
            Assert.Equal(2, properties.Count);
            properties = conditionedProperties["platform"];
            Assert.Equal(2, properties.Count);
            DumpDictionary(conditionedProperties);
        }
コード例 #8
0
        public void GetDefaultTargets()
        {
            ProjectInstance p = GetSampleProjectInstance();

            Helpers.AssertListsValueEqual(new string[] { "dt" }, p.DefaultTargets);
        }
コード例 #9
0
        public void GetInitialTargets()
        {
            ProjectInstance p = GetSampleProjectInstance();

            Helpers.AssertListsValueEqual(new string[] { "it" }, p.InitialTargets);
        }
コード例 #10
0
        public void GetTaskRegistry()
        {
            ProjectInstance p = GetSampleProjectInstance();

            Assert.True(p.TaskRegistry != null);
        }
コード例 #11
0
        public void GetToolsVersion()
        {
            ProjectInstance p = GetSampleProjectInstance();

            Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, p.Toolset.ToolsVersion);
        }
コード例 #12
0
 /// <summary>
 /// Instantiates an ItemGroup task
 /// </summary>
 /// <param name="taskInstance">The original task instance data</param>
 /// <param name="loggingContext">The logging context</param>
 /// <param name="projectInstance">The project instance</param>
 /// <param name="logTaskInputs">Flag to determine whether or not to log task inputs.</param>
 public ItemGroupIntrinsicTask(ProjectItemGroupTaskInstance taskInstance, TargetLoggingContext loggingContext, ProjectInstance projectInstance, bool logTaskInputs)
     : base(loggingContext, projectInstance, logTaskInputs)
 {
     _taskInstance        = taskInstance;
     _engineFileUtilities = EngineFileUtilities.Default;
 }
コード例 #13
0
        public RoslynMetadataHelper(string configuration, Compilation sourceCompilation, ProjectInstance projectInstance, Project roslynProject, string[] additionalTypes = null, Dictionary <string, string> legacyTypes = null)
        {
            Compilation = sourceCompilation;

            _findTypesByName    = Funcs.Create <string, ITypeSymbol[]>(SourceFindTypesByName).AsLockedMemoized();
            _findTypeByFullName = Funcs.Create <string, ITypeSymbol>(SourceFindTypeByFullName).AsLockedMemoized();
            _additionalTypes    = additionalTypes ?? new string[0];
            _legacyTypes        = legacyTypes ?? new Dictionary <string, string>();
            _project            = roslynProject;

            _compilationTask = Task.FromResult(sourceCompilation);

            GenerateAdditionalTypes();
        }
コード例 #14
0
 public static void SetProjectInstance(this SourceGeneratorContext context, ProjectInstance projectInstance)
 {
     _project.Add(context, projectInstance);
 }
コード例 #15
0
 private static string GetInnerBuildPropertyValues(ProjectInstance project)
 {
     return(project.GetPropertyValue(project.GetPropertyValue(PropertyNames.InnerBuildPropertyValues)));
 }
コード例 #16
0
 IRule IPropertyPagesCatalog.BindToContext(string schemaName, ProjectInstance projectInstance, ITaskItem taskItem)
 {
     throw new NotImplementedException();
 }
コード例 #17
0
 protected internal virtual void SetHintPathAndPrivateValue(ProjectInstance instance, ProjectItemInstance iteminstance)
 {
 }
コード例 #18
0
 public static string GetDefaultProjectTypeGuid(this ProjectInstance projectInstance)
 {
     return(projectInstance.GetPropertyValue("DefaultProjectTypeGuid"));
 }
コード例 #19
0
        public void TestCache2()
        {
            string projectBody = ObjectModelHelpers.CleanupFileContents(@"
                <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
                <PropertyGroup>
                    <One>1</One>
                    <Two>2</Two>
                    <Three>$(ThreeIn)</Three>
                </PropertyGroup>
                <ItemGroup>
                    <Foo Include=""*""/>
                    <Bar Include=""msbuild.out"">
                        <One>1</One>
                    </Bar>
                    <Baz Include=""$(BazIn)""/>
                </ItemGroup>
                <Target Name='Build'>
                    <CallTarget Targets='Foo;Bar'/>
                </Target>

                <Target Name='Foo' DependsOnTargets='Foo'>
                    <FooTarget/>
                </Target>

                <Target Name='Bar'>
                    <BarTarget/>
                </Target>

                <Target Name='Foo'>
                    <FooTarget/>
                </Target>
                </Project>");

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

            globalProperties["ThreeIn"] = "3";
            globalProperties["BazIn"]   = "bazfile";

            Project project = new Project(XmlReader.Create(new StringReader(projectBody)), globalProperties, ObjectModelHelpers.MSBuildDefaultToolsVersion, new ProjectCollection());

            project.FullPath = "foo";
            ProjectInstance           instance      = project.CreateProjectInstance();
            BuildRequestConfiguration configuration = new BuildRequestConfiguration(new BuildRequestData(instance, new string[] { }, null), "2.0");

            string originalTmp  = Environment.GetEnvironmentVariable("TMP");
            string originalTemp = Environment.GetEnvironmentVariable("TEMP");

            try
            {
                string problematicTmpPath = @"C:\Users\}\blabla\temp";
                Environment.SetEnvironmentVariable("TMP", problematicTmpPath);
                Environment.SetEnvironmentVariable("TEMP", problematicTmpPath);

                FileUtilities.ClearCacheDirectoryPath();
                string cacheFilePath = configuration.GetCacheFile();
                Assert.StartsWith(problematicTmpPath, cacheFilePath);
            }
            finally
            {
                Environment.SetEnvironmentVariable("TMP", originalTmp);
                Environment.SetEnvironmentVariable("TEMP", originalTemp);
                FileUtilities.ClearCacheDirectoryPath();
            }
        }
コード例 #20
0
 /// <summary>
 /// Instantiates an ItemGroup task
 /// </summary>
 /// <param name="taskInstance">The original task instance data</param>
 /// <param name="loggingContext">The logging context</param>
 /// <param name="projectInstance">The project instance</param>
 /// <param name="logTaskInputs">Flag to determine whether or not to log task inputs.</param>
 public ItemGroupIntrinsicTask(ProjectItemGroupTaskInstance taskInstance, TargetLoggingContext loggingContext, ProjectInstance projectInstance, bool logTaskInputs)
     : base(loggingContext, projectInstance, logTaskInputs)
 {
     _taskInstance = taskInstance;
 }
コード例 #21
0
ファイル: TargetBuilder.cs プロジェクト: maoxingda/msbuild-1
        /// <summary>
        /// Builds the specified targets.
        /// </summary>
        /// <param name="loggingContext">The logging context for the project.</param>
        /// <param name="entry">The BuildRequestEntry for which we are building targets.</param>
        /// <param name="callback">The callback to be used to handle new project build requests.</param>
        /// <param name="targetNames">The names of the targets to build.</param>
        /// <param name="baseLookup">The Lookup containing all current items and properties for this target.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> to use when building the targets.</param>
        /// <returns>The target's outputs and result codes</returns>
        public async Task <BuildResult> BuildTargets(ProjectLoggingContext loggingContext, BuildRequestEntry entry, IRequestBuilderCallback callback, string[] targetNames, Lookup baseLookup, CancellationToken cancellationToken)
        {
            ErrorUtilities.VerifyThrowArgumentNull(loggingContext, "projectLoggingContext");
            ErrorUtilities.VerifyThrowArgumentNull(entry, "entry");
            ErrorUtilities.VerifyThrowArgumentNull(callback, "requestBuilderCallback");
            ErrorUtilities.VerifyThrowArgumentNull(targetNames, "targetNames");
            ErrorUtilities.VerifyThrowArgumentNull(baseLookup, "baseLookup");
            ErrorUtilities.VerifyThrow(targetNames.Length > 0, "List of targets must be non-empty");
            ErrorUtilities.VerifyThrow(_componentHost != null, "InitializeComponent must be called before building targets.");

            _requestEntry           = entry;
            _requestBuilderCallback = callback;
            _projectLoggingContext  = loggingContext;
            _cancellationToken      = cancellationToken;

            // Clone the base lookup so that if we are re-entered by another request while this one in blocked, we don't have visibility to
            // their state, and they have no visibility into ours.
            _baseLookup = baseLookup.Clone();

            _targetsToBuild = new ConcurrentStack <TargetEntry>();

            // Get the actual target objects from the names
            BuildRequestConfiguration configuration = _requestEntry.RequestConfiguration;

            bool previousCacheableStatus = configuration.IsCacheable;

            configuration.IsCacheable = false;
            configuration.RetrieveFromCache();
            _projectInstance = configuration.Project;

            // Now get the current results cache entry.
            IResultsCache resultsCache        = (IResultsCache)_componentHost.GetComponent(BuildComponentType.ResultsCache);
            BuildResult   existingBuildResult = resultsCache.GetResultsForConfiguration(_requestEntry.Request.ConfigurationId);

            _buildResult = new BuildResult(entry.Request, existingBuildResult, null);

            if (existingBuildResult == null)
            {
                // Add this result so that if our project gets re-entered we won't rebuild any targets we have already built.
                resultsCache.AddResult(_buildResult);
            }

            List <TargetSpecification> targets = new List <TargetSpecification>(targetNames.Length);

            foreach (string targetName in targetNames)
            {
                var targetExists = _projectInstance.Targets.ContainsKey(targetName);
                if (!targetExists && entry.Request.BuildRequestDataFlags.HasFlag(BuildRequestDataFlags.SkipNonexistentTargets))
                {
                    _projectLoggingContext.LogComment(Framework.MessageImportance.Low,
                                                      "TargetSkippedWhenSkipNonexistentTargets", targetName);

                    continue;
                }

                targets.Add(new TargetSpecification(targetName, targetExists ? _projectInstance.Targets[targetName].Location : _projectInstance.ProjectFileLocation));
            }

            // Push targets onto the stack.  This method will reverse their push order so that they
            // get built in the same order specified in the array.
            await PushTargets(targets, null, baseLookup, false, false, TargetBuiltReason.None);

            // Now process the targets
            ITaskBuilder taskBuilder = _componentHost.GetComponent(BuildComponentType.TaskBuilder) as ITaskBuilder;

            try
            {
                await ProcessTargetStack(taskBuilder);
            }
            finally
            {
                // If there are still targets left on the stack, they need to be removed from the 'active targets' list
                foreach (TargetEntry target in _targetsToBuild)
                {
                    configuration.ActivelyBuildingTargets.Remove(target.Name);
                }

                ((IBuildComponent)taskBuilder).ShutdownComponent();
            }

            if (_cancellationToken.IsCancellationRequested)
            {
                throw new BuildAbortedException();
            }

            // Gather up outputs for the requested targets and return those.  All of our information should be in the base lookup now.
            BuildResult resultsToReport = new BuildResult(_buildResult, targetNames);

            // Return after-build project state if requested.
            if (_requestEntry.Request.BuildRequestDataFlags.HasFlag(BuildRequestDataFlags.ProvideProjectStateAfterBuild))
            {
                resultsToReport.ProjectStateAfterBuild = _projectInstance;
            }

            if (_requestEntry.Request.RequestedProjectState != null)
            {
                resultsToReport.ProjectStateAfterBuild =
                    _projectInstance.FilteredCopy(_requestEntry.Request.RequestedProjectState);
            }

            configuration.IsCacheable = previousCacheableStatus;

            return(resultsToReport);
        }
コード例 #22
0
 // No public creation.
 internal ProjectGraphNode(ProjectInstance projectInstance)
 {
     ProjectInstance = projectInstance;
 }
コード例 #23
0
        /// <summary>
        /// Parses the input and output files for copy tasks of given target.
        /// </summary>
        private static void ParseCopyTask(
            ProjectTargetInstance target,
            ProjectInstance projectInstance,
            HashSet <BuildInput> buildInputs,
            HashSet <string> buildOutputDirectories)
        {
            // Get all Copy tasks from targets.
            List <ProjectTaskInstance> tasks = target.Tasks
                                               .Where(task => string.Equals(task.Name, CopyTaskName, StringComparison.Ordinal))
                                               .ToList();

            if (tasks.Any() && projectInstance.EvaluateConditionCarefully(target.Condition))
            {
                foreach (ProjectTaskInstance task in tasks)
                {
                    if (projectInstance.EvaluateConditionCarefully(task.Condition))
                    {
                        var inputs = new FileExpressionList(
                            task.Parameters[CopyTaskSourceFiles],
                            projectInstance,
                            task);
                        if (inputs.Expressions.Count == 0)
                        {
                            continue;
                        }

                        buildInputs.UnionWith(inputs.DedupedFiles.
                                              Select(file => new BuildInput(Path.Combine(projectInstance.Directory, file), false)));

                        bool hasDestinationFolder = task.Parameters.TryGetValue(
                            CopyTaskDestinationFolder,
                            out string destinationFolder);
                        bool hasDestinationFiles = task.Parameters.TryGetValue(
                            CopyTaskDestinationFiles,
                            out string destinationFiles);

                        if (hasDestinationFiles || hasDestinationFolder)
                        {
                            // Having both is an MSBuild violation, which it will complain about.
                            if (hasDestinationFolder && hasDestinationFiles)
                            {
                                continue;
                            }

                            string destination = destinationFolder ?? destinationFiles;

                            var outputs = new FileExpressionList(destination, projectInstance, task);

                            // When using batch tokens, the user should specify exactly one total token, and it must appear in both the input and output.
                            // Doing otherwise should be a BuildCop error. If not using batch tokens, then any number of other tokens is fine.
                            if ((outputs.NumBatchExpressions == 1 && outputs.Expressions.Count == 1 &&
                                 inputs.NumBatchExpressions == 1 && inputs.Expressions.Count == 1) ||
                                (outputs.NumBatchExpressions == 0 && inputs.NumBatchExpressions == 0))
                            {
                                ProcessOutputs(projectInstance.FullPath, inputs, outputs, hasDestinationFolder, buildOutputDirectories);
                            }
                            else
                            {
                                // Ignore case we cannot handle.
                            }
                        }
                        else
                        {
                            // Ignore malformed case.
                        }
                    }
                }
            }
        }
コード例 #24
0
 // No public creation.
 internal ProjectGraphNode(ProjectInstance projectInstance)
 {
     ErrorUtilities.VerifyThrowInternalNull(projectInstance, nameof(projectInstance));
     ProjectInstance = projectInstance;
 }
コード例 #25
0
        private static void AssertAnalysisTargetsAreImported(ProjectInstance projectInstance)
        {
            ProjectPropertyInstance propertyInstance = projectInstance.GetProperty(DummyAnalysisTargetsMarkerProperty);

            Assert.IsNotNull(propertyInstance, "Failed to import the SonarQube Analysis targets");
        }
コード例 #26
0
 private IEnumerable <string> GetProjectCapabilities(ProjectInstance projectInstance)
 {
     return(projectInstance.GetItems(ItemNames.ProjectCapability).Select(item => item.ToString()));
 }
コード例 #27
0
 public virtual IProjectProperties GetCommonProperties(ProjectInstance projectInstance)
 => DelegatedInstanceProvider.GetCommonProperties(projectInstance);
コード例 #28
0
ファイル: OnError_Tests.cs プロジェクト: 3F/IeXod
        public void FailingTaskStillPublishesOutputs()
        {
            MockLogger l = new MockLogger();

            string resx = Path.Combine(Path.GetTempPath(), "FailingTaskStillPublishesOutputs.resx");

            try
            {
                File.WriteAllText(resx, @"
                    <root>
                      <resheader name=""resmimetype"">
                        <value>text/microsoft-resx</value>
                      </resheader>
                      <resheader name=""version"">
                        <value>2.0</value>
                      </resheader>
                      <resheader name=""reader"">
                        <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
                      </resheader>
                      <resheader name=""writer"">
                        <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
                      </resheader>
                      <data name=""a"">
                        <value>aa</value>
                      </data>
                      <data name=""b"">
                        <value>bb</value>
                      </data>
                    </root>");

                Project project = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"
                    <Project DefaultTargets='Build' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> 
                        <Target Name='Build'>
                            
                            <GenerateResource
                                ExecuteAsTool='false'
                                Sources='" + resx + @"'
                                StronglyTypedLanguage='!@:|'>
                                    <Output TaskParameter='FilesWritten' ItemName='FilesWrittenItem'/>
                                    <Output TaskParameter='FilesWritten' PropertyName='FilesWrittenProperty'/>
                            </GenerateResource>
                                               
                            <OnError ExecuteTargets='ErrorTarget'/>
                        </Target>

                        <Target Name='ErrorTarget'>    
                            <Message Text='[@(fileswrittenitem)]'/>
                            <Message Text='[$(fileswrittenproperty)]'/>
                        </Target>
                    </Project>"))));

                ProjectInstance p = project.CreateProjectInstance();
                p.Build(new string[] { "Build" }, new ILogger[] { l });

                string resource = Path.ChangeExtension(resx, ".resources");

                Assert.Equal(1, l.ErrorCount); // "Expected one error because 'Build' failed."
                l.AssertLogContains("[" + resource + "]", "[" + resource + "]");

                // And outputs are visible at the project level
                Assert.Equal(resource, Helpers.MakeList(p.GetItems("FilesWrittenItem"))[0].EvaluatedInclude);
                Assert.Equal(resource, p.GetPropertyValue("FilesWrittenProperty"));

                p = project.CreateProjectInstance();

                // But are gone after resetting of course
                Assert.Empty(Helpers.MakeList(p.GetItems("FilesWrittenItem")));
                Assert.Equal(String.Empty, p.GetPropertyValue("FilesWrittenProperty"));
            }
            finally
            {
                File.Delete(resx);
            }
        }
コード例 #29
0
ファイル: TestBase.cs プロジェクト: wjk/xamarin-macios
 public void RunTarget_WithErrors(ProjectInstance instance, string target)
 {
     Engine.BuildProject(instance, new [] { target }, new Hashtable());
     Assert.IsTrue(Engine.Logger.ErrorEvents.Count > 0, "#RunTarget-HasExpectedErrors");
 }
        /// <inheritdoc/>
        public void PredictInputsAndOutputs(
            ProjectInstance projectInstance,
            ProjectPredictionReporter predictionReporter)
        {
            // This is based on NuGet.Build.Tasks.Pack.targets and GetPackOutputItemsTask
            // See: https://github.com/NuGet/NuGet.Client/blob/dev/src/NuGet.Core/NuGet.Build.Tasks.Pack/NuGet.Build.Tasks.Pack.targets
            // See: https://github.com/NuGet/NuGet.Client/blob/dev/src/NuGet.Core/NuGet.Build.Tasks.Pack/GetPackOutputItemsTask.cs
            var generatePackageOnBuild = projectInstance.GetPropertyValue(GeneratePackageOnBuildPropertyName);

            if (!generatePackageOnBuild.Equals("true", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            var packageId         = projectInstance.GetPropertyValue(PackageIdPropertyName);
            var packageVersion    = projectInstance.GetPropertyValue(PackageVersionPropertyName);
            var packageOutputPath = projectInstance.GetPropertyValue(PackageOutputPathPropertyName);
            var nuspecOutputPath  = projectInstance.GetPropertyValue(NuspecOutputPathPropertyName);
            var includeSource     = projectInstance.GetPropertyValue(IncludeSourcePropertyName).Equals("true", StringComparison.OrdinalIgnoreCase);
            var includeSymbols    = projectInstance.GetPropertyValue(IncludeSymbolsPropertyName).Equals("true", StringComparison.OrdinalIgnoreCase);

            var symbolPackageFormat = projectInstance.GetPropertyValue(SymbolPackageFormatPropertyName);

            // PackageOutputPath defaults to OutputPath in the _CalculateInputsOutputsForPack target, not statically.
            if (string.IsNullOrEmpty(packageOutputPath))
            {
                packageOutputPath = projectInstance.GetPropertyValue(OutputPathPropertyName);
            }

            // All params are effectively required
            if (!string.IsNullOrEmpty(packageId) &&
                !string.IsNullOrEmpty(packageVersion) &&
                !string.IsNullOrEmpty(packageOutputPath) &&
                !string.IsNullOrEmpty(nuspecOutputPath) &&
                !string.IsNullOrEmpty(symbolPackageFormat))
            {
                var fileBaseName = $"{packageId}.{packageVersion}";

                // Nuspec files can also be provided instead of generated, in which case we should treat it like an input, not an output.
                var nuspecFile = projectInstance.GetPropertyValue(NuspecFilePropertyName);

                predictionReporter.ReportOutputFile(Path.Combine(packageOutputPath, fileBaseName + ".nupkg"));
                if (string.IsNullOrEmpty(nuspecFile))
                {
                    predictionReporter.ReportOutputFile(Path.Combine(nuspecOutputPath, fileBaseName + ".nuspec"));
                }
                else
                {
                    predictionReporter.ReportInputFile(nuspecFile);
                }

                if (includeSource || includeSymbols)
                {
                    predictionReporter.ReportOutputFile(Path.Combine(packageOutputPath, fileBaseName + (symbolPackageFormat.Equals("snupkg", StringComparison.OrdinalIgnoreCase) ? ".snupkg" : ".symbols.nupkg")));
                    if (string.IsNullOrEmpty(nuspecFile))
                    {
                        predictionReporter.ReportOutputFile(Path.Combine(nuspecOutputPath, fileBaseName + ".symbols.nuspec"));
                    }
                }
            }
        }