TExcelTAD
Home › .NET Builds: MSBuild & NuGet › Incremental Targets: Inputs & Outputs

Incremental Targets: Inputs & Outputs

The second dotnet build of an unchanged project takes a fraction of the first one's time. MSBuild isn't remembering anything clever: most SDK targets declare which files they read (Inputs) and which they write (Outputs), and MSBuild skips a target whose outputs are all newer than its inputs. Your custom targets get the same behaviour if you declare the same two attributes.

A target that generates code

This target turns the files in templates/ into a C# source file before the compiler runs:

bash · try it yourself
mkdir stamp && cd stamp
cat > stamp.csproj <<'XML'
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <Template Include="templates/*.txt" />
  </ItemGroup>
  <Target Name="GenerateBanner" BeforeTargets="CoreCompile"
          Inputs="@(Template)" Outputs="$(IntermediateOutputPath)Banner.g.cs">
    <Message Importance="high" Text="Generating Banner.g.cs from @(Template->Count()) template(s)" />
    <PropertyGroup>
      <Names>@(Template->'%(Filename)', ', ')</Names>
    </PropertyGroup>
    <WriteLinesToFile File="$(IntermediateOutputPath)Banner.g.cs" Overwrite="true"
      Lines="static class Banner { public const string Text = &quot;$(Names)&quot;%3B }" />
    <ItemGroup>
      <Compile Include="$(IntermediateOutputPath)Banner.g.cs" />
      <FileWrites Include="$(IntermediateOutputPath)Banner.g.cs" />
    </ItemGroup>
  </Target>
</Project>
XML
mkdir templates
echo a > templates/alpha.txt
echo b > templates/beta.txt
echo 'System.Console.WriteLine(Banner.Text);' > Program.cs
echo "=== first build"
dotnet build -nologo -v:n | grep -E 'Generating Banner|GenerateBanner|CoreCompile'
dotnet run --no-build
echo "=== second build, nothing changed"
dotnet build -nologo -v:n | grep -E 'Generating Banner|GenerateBanner|CoreCompile'
echo "=== a template changes"
sleep 1 && touch templates/beta.txt
dotnet build -nologo -v:n | grep -E 'Generating Banner|GenerateBanner|CoreCompile'
=== first build
       GenerateBanner:
         Generating Banner.g.cs from 2 template(s)
       CoreCompile:
alpha, beta
=== second build, nothing changed
       GenerateBanner:
       Skipping target "GenerateBanner" because all output files are up-to-date with respect to the input files.
       CoreCompile:
       Skipping target "CoreCompile" because all output files are up-to-date with respect to the input files.
=== a template changes
       GenerateBanner:
         Generating Banner.g.cs from 2 template(s)
       CoreCompile:

Read the three builds with normal verbosity (-v:n prints each target's name):

  1. First build: Banner.g.cs doesn't exist, so the target runs, and CoreCompile compiles it along with Program.cs.
  2. Second build: Skipping target "GenerateBanner" because all output files are up-to-date with respect to the input files. The compiler target, which declares its own Inputs and Outputs, is skipped for the same reason.
  3. After touching a template: the template is newer than Banner.g.cs, so the target runs again, rewrites the file, and that makes CoreCompile run too. One changed input ripples exactly as far as it needs to.

Three details make the target correct, not just fast:

  • Output inference. On the second build the target was skipped, yet Program.cs still compiled against Banner. When MSBuild skips a target, it still creates the items and properties the target would have created (the Compile item here). Without that, a skipped generator would make the build fail.
  • FileWrites registers the generated file with the SDK's Clean target, so dotnet clean deletes it.
  • $(IntermediateOutputPath) (obj/Debug/net10.0/) keeps generated files out of the source tree and separate per configuration and framework.

Note: MSBuild compares timestamps, not contents. Saving a file without changing it, or a git checkout that rewrites it, triggers a rebuild of everything downstream. A target whose output doesn't depend on files at all (a git commit hash, an environment variable) needs a trick: write the value to a file with WriteOnlyWhenDifferent="true" and use that file as an input.

Partial builds: one output per input

When Outputs is a transform of Inputs, MSBuild maps them one-to-one and runs the target only for the items that are out of date:

bash · try it yourself
mkdir docs && cd docs
mkdir -p md
for p in intro setup usage; do echo "# $p" > md/$p.md; done
cat > docs.proj <<'XML'
<Project>
  <ItemGroup>
    <Page Include="md/*.md" />
  </ItemGroup>
  <Target Name="Html" Inputs="@(Page)" Outputs="@(Page->'html/%(Filename).html')">
    <Message Importance="high" Text="rendering @(Page)" />
    <Copy SourceFiles="@(Page)" DestinationFiles="@(Page->'html/%(Filename).html')" />
  </Target>
</Project>
XML
dotnet msbuild -nologo -v:m -t:Html
dotnet msbuild -nologo -v:m -t:Html
sleep 1 && touch md/setup.md
dotnet msbuild -nologo -v:m -t:Html
ls html
  rendering md/intro.md;md/setup.md;md/usage.md
  rendering md/setup.md
intro.html
setup.html
usage.html

The third run printed only md/setup.md: inside the target, @(Page) contained just the stale item. With minimal verbosity a fully skipped target prints nothing at all, which is why the second run is silent.

The decision, as a model

This is the rule MSBuild applies before every target that has Inputs and Outputs:

python · try it yourself
def decide(inputs, outputs, mtime):
    """Return ('full'|'partial'|'skip', items to process)."""
    if not inputs or not outputs:
        return "full", inputs           # no declaration: always run
    pairs = len(inputs) == len(outputs)
    if pairs:                            # transform: compare item by item
        stale = [i for i, o in zip(inputs, outputs)
                 if o not in mtime or mtime[o] < mtime[i]]
        if not stale:
            return "skip", []
        return ("full" if len(stale) == len(inputs) else "partial"), stale
    newest_in = max(mtime[i] for i in inputs)
    oldest_out = min(mtime.get(o, -1) for o in outputs)
    return ("skip", []) if oldest_out >= newest_in else ("full", inputs)

mtime = {"md/intro.md": 10, "md/setup.md": 10, "md/usage.md": 10}
pages = ["md/intro.md", "md/setup.md", "md/usage.md"]
html = ["html/intro.html", "html/setup.html", "html/usage.html"]
print("1st:", decide(pages, html, mtime))
mtime.update({h: 11 for h in html})
print("2nd:", decide(pages, html, mtime))
mtime["md/setup.md"] = 12
print("3rd:", decide(pages, html, mtime))
print("many-to-one:", decide(pages, ["Banner.g.cs"], {**mtime, "Banner.g.cs": 11}))
1st: ('full', ['md/intro.md', 'md/setup.md', 'md/usage.md'])
2nd: ('skip', [])
3rd: ('partial', ['md/setup.md'])
many-to-one: ('full', ['md/intro.md', 'md/setup.md', 'md/usage.md'])

The real implementation also handles missing inputs (an error), outputs that MSBuild can't map one-to-one (it falls back to the all-or-nothing rule shown for Banner.g.cs) and logs the reason it chose, which you saw in the -v:n output.

Test yourself

A target with Inputs and Outputs is skipped on the second build. Are the Compile items it creates inside the target still added?

  1. No, skipped targets have no effect
  2. Yes: MSBuild's output inference still creates the target's items and properties
  3. Only in Release builds
  4. Only if the target has Returns

What does MSBuild compare to decide whether a target is up to date?

  1. File content hashes
  2. File timestamps of Inputs and Outputs
  3. The git status
  4. Nothing; it always runs

Outputs is written as @(Page->'html/%(Filename).html') and only one page changed. What runs?

  1. Nothing
  2. The whole target for all pages
  3. A partial build: the target runs with only the out-of-date page in @(Page)
  4. Only the Copy task, for all pages