0

I'm trying to populate an ItemGroup with directory basenames, pass it through a transform to create absolute paths from them and import the files residing there. It works flawlessly in a Message element, but fails to do anything in an Import. What am I missing?

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <ItemGroup>
        <MyDependencies Include="Dir1" />
        <MyDependencies Include="Dir2" />
    </ItemGroup>

    <!-- "Expansion: C:\path\Dir1\import.targets;C:\some\path\Dir2\import.targets" -->
    <Target Name="TestMessage" BeforeTargets="PrepareForBuild">
        <Message
            Importance="High"
            Text="Expansion: @(MyDependencies -> 'C:\path\%(Identity)\import.targets')"
        />
    </Target>

<!-- Uncomment to trigger error -->
<!--<Import Project="@(MyDependencies -> 'C:\path\%(Identity)\import.targets')" />-->
</Project>

The Import's path remains unexpanded and leads to:

error MSB4102: The value "@(MyDependencies -> 'C:\path\%(Identity)\import.targets')" of the "Project" attribute in element <Import> is invalid. Illegal characters in path.
Quentin
  • 62,093
  • 7
  • 131
  • 191
  • This is a classic evaluation order problem (and a duplicate IIRC). I can't pinpoint the exact piece of documentation stating this but the transform is only evaluated in a pass *after* importing. *edit* well https://learn.microsoft.com/en-us/visualstudio/msbuild/comparing-properties-and-items?view=vs-2017 says "During the execution phase of a build ... Item values and item transformations are also expanded" and it says Import is part of the evaluation phase so I guess that does answer it. – stijn Dec 28 '18 at 09:53
  • @stijn damn, the documentation is incomplete but it looks like you're right and item groups plain don't work with `Import`... – Quentin Dec 28 '18 at 14:57
  • 1
    @stijn Add your findings as an answer so others can find that valuable information more easily. Also, Quentin could then accept it as an answer and the world would be a better place :-) Or, if you don't feel like it, I can do it. – Oliver Jun 06 '22 at 09:53
  • 1
    @Oliver ok good point, clearly forgot about this one :) Added answer with relevant link – stijn Jun 07 '22 at 10:05

1 Answers1

2

This happens because the ItemGroup gets evaluated after Import only. See https://learn.microsoft.com/en-us/visualstudio/msbuild/comparing-properties-and-items?view=vs-2022#property-and-item-evaluation-order:

During the evaluation phase of a build, imported files are incorporated into the build in the order in which they appear. Properties and items are defined in three passes in the following order:

In other words an Import is almost the same as copy-pasting the content of the file at the location of that import, and only after that MSBuild begins to evaluate properties and items.

stijn
  • 34,664
  • 13
  • 111
  • 163