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:
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 = "$(Names)"%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):
- First build:
Banner.g.csdoesn't exist, so the target runs, andCoreCompilecompiles it along withProgram.cs. - 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. - After touching a template: the template is newer than
Banner.g.cs, so the target runs again, rewrites the file, and that makesCoreCompilerun 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.csstill compiled againstBanner. When MSBuild skips a target, it still creates the items and properties the target would have created (theCompileitem here). Without that, a skipped generator would make the build fail. FileWritesregisters the generated file with the SDK'sCleantarget, sodotnet cleandeletes 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 checkoutthat 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 withWriteOnlyWhenDifferent="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:
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:
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?
- No, skipped targets have no effect
- Yes: MSBuild's output inference still creates the target's items and properties
- Only in Release builds
- Only if the target has Returns
What does MSBuild compare to decide whether a target is up to date?
- File content hashes
- File timestamps of Inputs and Outputs
- The git status
- Nothing; it always runs
Outputs is written as @(Page->'html/%(Filename).html') and only one page changed. What runs?
- Nothing
- The whole target for all pages
- A partial build: the target runs with only the out-of-date page in @(Page)
- Only the Copy task, for all pages