Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rework XAML compilation targets #17539

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ x64/
*.vssscc
.builds
*.pidb
*.log
*.scc
*.binlog

# Visual C++ cache files
ipch/
Expand Down
2 changes: 2 additions & 0 deletions .nuke/build.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@
"RunTests",
"RunToolsTests",
"ValidateApiDiff",
"VerifyXamlCompilation",
"ZipFiles"
]
}
Expand Down Expand Up @@ -131,6 +132,7 @@
"RunTests",
"RunToolsTests",
"ValidateApiDiff",
"VerifyXamlCompilation",
"ZipFiles"
]
}
Expand Down
2 changes: 1 addition & 1 deletion dirs.proj
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<ProjectReference Include="src/Avalonia.Build.Tasks/Avalonia.Build.Tasks.csproj" />
<ProjectReference Include="src/**/*.*proj" />
<ProjectReference Condition="'$(SkipBuildingSamples)' != 'True'" Include="samples/**/*.*proj" />
<ProjectReference Condition="'$(SkipBuildingTests)' != 'True'" Include="tests/**/*.*proj" />
<ProjectReference Condition="'$(SkipBuildingTests)' != 'True'" Include="tests/**/*.*proj" Exclude="tests/BuildTests/**" />
<ProjectReference Include="packages/**/*.*proj" />
<ProjectReference Remove="**/*.shproj" />
<ProjectReference Remove="src/Markup/Avalonia.Markup.Xaml.Loader/xamlil.github/**/*.*proj" />
Expand Down
62 changes: 62 additions & 0 deletions nukebuild/Build.cs
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,7 @@ await Task.WhenAll(

Target CiAzureWindows => _ => _
.DependsOn(Package)
.DependsOn(VerifyXamlCompilation)
.DependsOn(ZipFiles);

Target BuildToNuGetCache => _ => _
Expand Down Expand Up @@ -407,6 +408,67 @@ await Task.WhenAll(
file.GenerateCppHeader());
});

Target VerifyXamlCompilation => _ => _
.DependsOn(CreateNugetPackages)
.Executes(() =>
{
var buildTestsDirectory = RootDirectory / "tests" / "BuildTests";
var artifactsDirectory = buildTestsDirectory / "artifacts";
var nugetCacheDirectory = artifactsDirectory / "nuget-cache";

DeleteDirectory(artifactsDirectory);
BuildTestsAndVerify("Debug");
BuildTestsAndVerify("Release");

void BuildTestsAndVerify(string configuration)
{
var configName = configuration.ToLowerInvariant();

DotNetBuild(settings => settings
.SetConfiguration(configuration)
.SetProperty("AvaloniaVersion", Parameters.Version)
.SetProperty("NuGetPackageRoot", nugetCacheDirectory)
.SetPackageDirectory(nugetCacheDirectory)
.SetProjectFile(buildTestsDirectory / "BuildTests.sln")
.SetProcessArgumentConfigurator(arguments => arguments.Add("--nodeReuse:false")));

// Standard compilation - should have compiled XAML
VerifyBuildTestAssembly("bin", "BuildTests");
VerifyBuildTestAssembly("bin", "BuildTests.Android");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that the original issue can't be reproduced with a plain dotnet build, with Rider it was only happened when one tries to debug the app.

VerifyBuildTestAssembly("bin", "BuildTests.Browser");
VerifyBuildTestAssembly("bin", "BuildTests.Desktop");
VerifyBuildTestAssembly("bin", "BuildTests.FSharp");
VerifyBuildTestAssembly("bin", "BuildTests.iOS");
VerifyBuildTestAssembly("bin", "BuildTests.WpfHybrid");

// Publish previously built project without rebuilding - should have compiled XAML
PublishBuildTestProject("BuildTests.Desktop", noBuild: true);
VerifyBuildTestAssembly("publish", "BuildTests.Desktop");

// Publish NativeAOT build, then run it - should not crash and have the expected output
PublishBuildTestProject("BuildTests.NativeAot");
var exeExtension = OperatingSystem.IsWindows() ? ".exe" : null;
XamlCompilationVerifier.VerifyNativeAot(
GetBuildTestOutputPath("publish", "BuildTests.NativeAot", exeExtension));

void PublishBuildTestProject(string projectName, bool? noBuild = null)
=> DotNetPublish(settings => settings
.SetConfiguration(configuration)
.SetProperty("AvaloniaVersion", Parameters.Version)
.SetProperty("NuGetPackageRoot", nugetCacheDirectory)
.SetPackageDirectory(nugetCacheDirectory)
.SetNoBuild(noBuild)
.SetProject(buildTestsDirectory / projectName / (projectName + ".csproj"))
.SetProcessArgumentConfigurator(arguments => arguments.Add("--nodeReuse:false")));

void VerifyBuildTestAssembly(string folder, string projectName)
=> XamlCompilationVerifier.VerifyAssemblyCompiledXaml(
GetBuildTestOutputPath(folder, projectName, ".dll"));

AbsolutePath GetBuildTestOutputPath(string folder, string projectName, string extension)
=> artifactsDirectory / folder / projectName / configName / (projectName + extension);
}
});

public static int Main() =>
RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
Expand Down
56 changes: 56 additions & 0 deletions nukebuild/XamlCompilationVerifier.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using System;
using System.Linq;
using Mono.Cecil;
using Nuke.Common.Tooling;
using Serilog;

internal static class XamlCompilationVerifier
{
public static void VerifyAssemblyCompiledXaml(string assemblyPath)
{
const string avaloniaResourcesTypeName = "CompiledAvaloniaXaml.!AvaloniaResources";
const string mainViewTypeName = "BuildTests.MainView";
const string populateMethodName = "!XamlIlPopulate";

using var assembly = AssemblyDefinition.ReadAssembly(assemblyPath);

if (assembly.MainModule.GetType(avaloniaResourcesTypeName) is null)
{
throw new InvalidOperationException(
$"Assembly {assemblyPath} is missing type {avaloniaResourcesTypeName}");
}

if (assembly.MainModule.GetType(mainViewTypeName) is not { } mainViewType)
{
throw new InvalidOperationException(
$"Assembly {assemblyPath} is missing type {mainViewTypeName}");
}

if (!mainViewType.Methods.Any(method => method.Name == populateMethodName))
{
throw new InvalidOperationException(
$"Assembly {assemblyPath} is missing method {populateMethodName} on {mainViewTypeName}");
}

Log.Information($"Assembly {assemblyPath} correctly has compiled XAML");
}

public static void VerifyNativeAot(string programPath)
{
const string expectedOutput = "Hello from AOT";

using var process = ProcessTasks.StartProcess(programPath, string.Empty);

process.WaitForExit();
process.AssertZeroExitCode();

var output = process.Output.Select(o => o.Text).FirstOrDefault();
if (output != expectedOutput)
{
throw new InvalidOperationException(
$"{programPath} returned text \"{output}\", expected \"{expectedOutput}\"");
}

Log.Information($"Native program {programPath} correctly has compiled XAML");
}
}
97 changes: 24 additions & 73 deletions packages/Avalonia/AvaloniaBuildTasks.targets
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@

<PropertyGroup>
<BuildAvaloniaResourcesDependsOn>$(BuildAvaloniaResourcesDependsOn);AddAvaloniaResources;ResolveReferences;_GenerateAvaloniaResourcesDependencyCache</BuildAvaloniaResourcesDependsOn>
<CompileAvaloniaXamlDependsOn>$(CompileAvaloniaXamlDependsOn);FindReferenceAssembliesForReferences;PrepareToCompileAvaloniaXaml</CompileAvaloniaXamlDependsOn>
<CompileAvaloniaXamlDependsOn>$(CompileAvaloniaXamlDependsOn);FindReferenceAssembliesForReferences</CompileAvaloniaXamlDependsOn>
</PropertyGroup>

<Target Name="_GenerateAvaloniaResourcesDependencyCache" BeforeTargets="GenerateAvaloniaResources">
Expand Down Expand Up @@ -107,34 +107,39 @@
</ItemGroup>
</Target>

<Target Name="PrepareToCompileAvaloniaXaml">
<!-- Adjust CoreCompile with our XAML inputs and compiler -->
<Target Name="AvaloniaPrepareCoreCompile" BeforeTargets="CoreCompile">
<PropertyGroup>
<AvaloniaXamlIlVerifyIl Condition="'$(AvaloniaXamlIlVerifyIl)' == ''">false</AvaloniaXamlIlVerifyIl>
<AvaloniaXamlIlDebuggerLaunch Condition="'$(AvaloniaXamlIlDebuggerLaunch)' == ''">false</AvaloniaXamlIlDebuggerLaunch>
<AvaloniaXamlVerboseExceptions Condition="'$(AvaloniaXamlVerboseExceptions)' == ''">false</AvaloniaXamlVerboseExceptions>
<_AvaloniaHasCompiledXaml>true</_AvaloniaHasCompiledXaml>
<TargetsTriggeredByCompilation>$(TargetsTriggeredByCompilation);CompileAvaloniaXaml</TargetsTriggeredByCompilation>
</PropertyGroup>

<ItemGroup>
<IntermediateAssembly Update="*" AvaloniaCompileOutput="%(RelativeDir)Avalonia\%(Filename)%(Extension)"/>
<_DebugSymbolsIntermediatePath Update="*" AvaloniaCompileOutput="%(RelativeDir)Avalonia\%(Filename)%(Extension)"/>
<IntermediateRefAssembly Update="*" AvaloniaCompileOutput="%(RelativeDir)Avalonia\%(Filename)%(Extension)"/>
<CompileAvaloniaXamlInputs Include="@(IntermediateAssembly);@(_DebugSymbolsIntermediatePath);@(IntermediateRefAssembly)"/>
<CompileAvaloniaXamlOutputs Include="@(CompileAvaloniaXamlInputs->'%(AvaloniaCompileOutput)')"/>
<CompileAvaloniaXamlInputs Include="@(AvaloniaResource);@(AvaloniaXaml)"/>

<FileWrites Include="@(CompileAvaloniaXamlOutputs)"/>
<CustomAdditionalCompileInputs Include="@(AvaloniaResource)" />
<CustomAdditionalCompileInputs Include="@(AvaloniaXaml)" />
</ItemGroup>
</Target>

<Target Name="AvaloniaCollectUpToDateCheckInputDesignTime" BeforeTargets="CollectUpToDateCheckInputDesignTime">
<UpToDateCheckInput Include="@(AvaloniaResource)" />
<UpToDateCheckInput Include="@(AvaloniaXaml)" />
</Target>

<Target
Name="CompileAvaloniaXaml"
AfterTargets="AfterCompile"
DependsOnTargets="$(CompileAvaloniaXamlDependsOn)"
Inputs="@(CompileAvaloniaXamlInputs)"
Outputs="@(CompileAvaloniaXamlOutputs)"
Condition="'@(AvaloniaResource)@(AvaloniaXaml)' != '' AND $(DesignTimeBuild) != true AND $(EnableAvaloniaXamlCompilation) != false">

<PropertyGroup>
<AvaloniaXamlIlVerifyIl Condition="'$(AvaloniaXamlIlVerifyIl)' == ''">false</AvaloniaXamlIlVerifyIl>
<AvaloniaXamlIlDebuggerLaunch Condition="'$(AvaloniaXamlIlDebuggerLaunch)' == ''">false</AvaloniaXamlIlDebuggerLaunch>
<AvaloniaXamlVerboseExceptions Condition="'$(AvaloniaXamlVerboseExceptions)' == ''">false</AvaloniaXamlVerboseExceptions>
</PropertyGroup>

<ItemGroup>
<IntermediateAssembly Update="*" AvaloniaCompileOutput="%(FullPath)"/>
<_DebugSymbolsIntermediatePath Update="*" AvaloniaCompileOutput="%(FullPath)"/>
<IntermediateRefAssembly Update="*" AvaloniaCompileOutput="%(FullPath)"/>
</ItemGroup>

<!--
$(IntermediateOutputPath)/Avalonia/references is using from AvaloniaVS for retrieve library references.
-->
Expand All @@ -160,60 +165,6 @@
AnalyzerConfigFiles="@(EditorConfigFiles)"/>
</Target>

<Target Name="InjectAvaloniaXamlOutput" DependsOnTargets="PrepareToCompileAvaloniaXaml" AfterTargets="CompileAvaloniaXaml" BeforeTargets="CopyFilesToOutputDirectory;BuiltProjectOutputGroup;ComputeResolvedFilesToPublishList"
Condition="'@(AvaloniaResource)@(AvaloniaXaml)' != '' AND $(EnableAvaloniaXamlCompilation) != false">
<ItemGroup>
<_AvaloniaXamlCompiledAssembly Include="@(IntermediateAssembly->Metadata('AvaloniaCompileOutput'))"/>
<IntermediateAssembly Remove="@(IntermediateAssembly)"/>
<IntermediateAssembly Include="@(_AvaloniaXamlCompiledAssembly)"/>

<_AvaloniaXamlCompiledRefAssembly Include="@(IntermediateRefAssembly->Metadata('AvaloniaCompileOutput'))"/>
<IntermediateRefAssembly Remove="@(IntermediateRefAssembly)"/>
<IntermediateRefAssembly Include="@(_AvaloniaXamlCompiledRefAssembly)"/>

<_AvaloniaXamlCompiledSymbols Include="@(_DebugSymbolsIntermediatePath->Metadata('AvaloniaCompileOutput'))"/>
<_DebugSymbolsIntermediatePath Remove="@(_DebugSymbolsIntermediatePath)"/>
<_DebugSymbolsIntermediatePath Include="@(_AvaloniaXamlCompiledSymbols)"/>

<!-- ClickOnce takes a copy of @(IntermediateAssembly) during the evaluation phase -->
<_DeploymentManifestEntryPoint Remove="@(_DeploymentManifestEntryPoint)" />
<_DeploymentManifestEntryPoint Include="@(_AvaloniaXamlCompiledAssembly)">
<TargetPath>$(TargetFileName)</TargetPath>
</_DeploymentManifestEntryPoint>
</ItemGroup>
</Target>

<!--
For some reason the IL Compiler hardcodes $(IntermediateOutputPath)$(TargetName)$(TargetExt)
instead of using @(IntermediateAssembly), change that to our assembly.
This is fixed in .NET 9.0 (https://github.com/dotnet/runtime/pull/99732)
-->
<Target Name="InjectIlcAvaloniaXamlOutput"
DependsOnTargets="InjectAvaloniaXamlOutput"
AfterTargets="ComputeIlcCompileInputs"
BeforeTargets="PrepareForILLink"
Condition="$([MSBuild]::VersionLessThan($(TargetFrameworkVersion), '9.0')) AND '@(AvaloniaResource)@(AvaloniaXaml)' != '' AND $(EnableAvaloniaXamlCompilation) != false">
<ItemGroup>
<ManagedBinary Remove="$(IntermediateOutputPath)$(TargetName)$(TargetExt)" />
<ManagedBinary Include="@(_AvaloniaXamlCompiledAssembly)" />

<IlcCompileInput Remove="$(IntermediateOutputPath)$(TargetName)$(TargetExt)" />
<IlcCompileInput Include="@(_AvaloniaXamlCompiledAssembly)" />
</ItemGroup>
</Target>

<Target Name="Avalonia_CollectUpToDateCheckOutputDesignTime" Condition="'@(AvaloniaResource)@(AvaloniaXaml)' != '' AND $(EnableAvaloniaXamlCompilation) != false"
BeforeTargets="CollectUpToDateCheckOutputDesignTime" DependsOnTargets="PrepareToCompileAvaloniaXaml">
<ItemGroup>
<UpToDateCheckOutput Include="@(CompileAvaloniaXamlOutputs)"/>
</ItemGroup>
</Target>

<ItemGroup>
<UpToDateCheckInput Include="@(AvaloniaResource)" />
<UpToDateCheckInput Include="@(AvaloniaXaml)" />
</ItemGroup>

<PropertyGroup>
<AvaloniaFilePreviewDependsOn Condition="'$(SkipBuild)'!='True'">Build</AvaloniaFilePreviewDependsOn>
</PropertyGroup>
Expand Down Expand Up @@ -252,7 +203,7 @@
Name="AvaloniaDeleteRefAssemblyBeforeOutputCopy"
BeforeTargets="CopyFilesToOutputDirectory"
Condition="
'$(_AvaloniaHasCompiledXaml)' == 'true' and
'@(AvaloniaResource)@(AvaloniaXaml)' != '' and
'$(TargetRefPath)' != '' and
'$(ProduceReferenceAssembly)' == 'true' and
('$(CopyBuildOutputToOutputDirectory)' == '' or '$(CopyBuildOutputToOutputDirectory)' == 'true') and
Expand Down
15 changes: 11 additions & 4 deletions src/Avalonia.Build.Tasks/CompileAvaloniaXamlTask.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,18 +51,25 @@ public bool Execute()

private static void CopyAndTouch(string source, string destination, bool shouldExist = true)
{
if (!File.Exists(source))
var normalizedSource = Path.GetFullPath(source);
var normalizedDestination = Path.GetFullPath(destination);

if (!File.Exists(normalizedSource))
{
if (shouldExist)
{
throw new FileNotFoundException($"Could not copy file '{source}'. File does not exist.");
throw new FileNotFoundException($"Could not copy file '{normalizedSource}'. File does not exist.");
}

return;
}

File.Copy(source, destination, overwrite: true);
File.SetLastWriteTimeUtc(destination, DateTime.UtcNow);
if (normalizedSource != normalizedDestination)
{
File.Copy(normalizedSource, normalizedDestination, overwrite: true);
}

File.SetLastWriteTimeUtc(normalizedDestination, DateTime.UtcNow);
}

[Required]
Expand Down
21 changes: 21 additions & 0 deletions tests/BuildTests/BuildTests.Android/BuildTests.Android.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0-android</TargetFramework>
<SupportedOSPlatformVersion>21</SupportedOSPlatformVersion>
<Nullable>enable</Nullable>
<ApplicationId>com.Avalonia.BuildTests</ApplicationId>
<ApplicationVersion>1</ApplicationVersion>
<ApplicationDisplayVersion>1.0</ApplicationDisplayVersion>
<AndroidPackageFormat>apk</AndroidPackageFormat>
<AndroidEnableProfiledAot>false</AndroidEnableProfiledAot>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Avalonia.Android" />
</ItemGroup>

<Import Project="../IncludeBuildTestsAvaloniaItems.props" />

</Project>
11 changes: 11 additions & 0 deletions tests/BuildTests/BuildTests.Android/MainActivity.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using Android.App;
using Android.Content.PM;
using Avalonia.Android;

namespace BuildTests.Android;

[Activity(
Label = "BuildTests.Android",
MainLauncher = true,
ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize | ConfigChanges.UiMode)]
public class MainActivity : AvaloniaMainActivity<App>;
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="auto">
<uses-permission android:name="android.permission.INTERNET" />
<application android:label="BuildTests" />
</manifest>
16 changes: 16 additions & 0 deletions tests/BuildTests/BuildTests.Browser/BuildTests.Browser.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk.WebAssembly">

<PropertyGroup>
<TargetFramework>net8.0-browser</TargetFramework>
<OutputType>Exe</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Avalonia.Browser" />
</ItemGroup>

<Import Project="../IncludeBuildTestsAvaloniaItems.props" />

</Project>
Loading
Loading