Skip to content

Commit

Permalink
Add -aot parameter to the console template (#31739)
Browse files Browse the repository at this point in the history
This is similar to the `api` template in ASP.NET that also allows `-aot` (or `--publish-native-aot`) option (see dotnet/aspnetcore#46064).

We set similar properties:
* `<PublishAot>true</PublishAot>` (this is the obvious one)
* `<InvariantGlobalization>true</InvariantGlobalization>` to get rid of ICU dependency on Linux and make the hello world executable ~20% smaller in general, even outside Linux.
* a commented out `<StripSymbols>true</StripSymbols>`. This is for discoverability. We default this to `false` due to platform conventions, but many users would be fine setting this to `true`. `true` is the .NET convention.

I took the string from ASP.NET. I could have also copied the localized strings but I guess it's better to not step on the toes of the localization team.
  • Loading branch information
MichalStrehovsky committed Apr 20, 2023
1 parent 3eafa1f commit d10b354
Show file tree
Hide file tree
Showing 46 changed files with 229 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,17 @@ Default: false
InsertText: --output,
Detail: Location to place the generated output.
},
{
Label: --publish-native-aot,
Kind: Keyword,
SortText: --publish-native-aot,
InsertText: --publish-native-aot,
Detail:
Whether to enable the project for publishing as native AOT.
Type: bool
Default: false

},
{
Label: --type,
Kind: Keyword,
Expand All @@ -106,6 +117,17 @@ Default: false
InsertText: -?,
Detail: Show help and usage information
},
{
Label: -aot,
Kind: Keyword,
SortText: -aot,
InsertText: -aot,
Detail:
Whether to enable the project for publishing as native AOT.
Type: bool
Default: false

},
{
Label: -f,
Kind: Keyword,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>%FRAMEWORK%</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<InvariantGlobalization>true</InvariantGlobalization>

<!-- Uncomment below line to make native publish outputs a lot smaller on Linux and macOS -->
<!-- <StripSymbols>true</StripSymbols> -->
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The template "Console App" was created successfully.
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>%FRAMEWORK%</TargetFramework>
<RootNamespace>vb_console</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<InvariantGlobalization>true</InvariantGlobalization>

<!-- Uncomment below line to make native publish outputs a lot smaller on Linux and macOS -->
<!-- <StripSymbols>true</StripSymbols> -->
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The template "Console App" was created successfully.
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ Template options:
--use-program-main Whether to generate an explicit Program class and Main method instead of top-level statements.
Type: bool
Default: false
-aot, --publish-native-aot Whether to enable the project for publishing as native AOT.
Type: bool
Default: false

To see help for other template languages (F#, VB), use --language option:
dotnet new console -h --language F#
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ Template options:
--use-program-main Whether to generate an explicit Program class and Main method instead of top-level statements.
Type: bool
Default: false
-aot, --publish-native-aot Whether to enable the project for publishing as native AOT.
Type: bool
Default: false

To see help for other template languages (F#, VB), use --language option:
dotnet new console -h --language F#
60 changes: 60 additions & 0 deletions src/Tests/dotnet-new.Tests/CommonTemplatesTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,66 @@ public void NuGetConfigPermissions()
Directory.Delete(workingDir, true);
}

[Theory]
[InlineData(new object[] { "console", "C#" })]
[InlineData(new object[] { "console", "VB" })]
public async void AotVariants(string name, string language)
{
// "net8.0";
string currentDefaultFramework = $"net{Environment.Version.Major}.{Environment.Version.Minor}";

string workingDir = CreateTemporaryFolder(folderName: $"{name}-{language}");
string outputDir = "MyProject";
string projName = name;

List<string> args = new() { "-o", outputDir };
// VB build would fail for name 'console' (root namespace would conflict with BCL namespace)
if (language.Equals("VB") == true && name.Equals("console"))
{
projName = "vb-console";
args.Add("-n");
args.Add(projName);
}
args.Add("-aot");

// Do not bother restoring. This would need to restore the AOT compiler.
// We would need a nuget.config for that and it's a waste of time anyway.
args.Add("--no-restore");

string extension = language == "VB" ? "vbproj" : "csproj";

string projectDir = Path.Combine(workingDir, outputDir);
string finalProjectName = Path.Combine(projectDir, $"{projName}.{extension}");

Dictionary<string, string> environmentUnderTest = new() { ["DOTNET_NOLOGO"] = false.ToString() };
TestContext.Current.AddTestEnvironmentVariables(environmentUnderTest);

TemplateVerifierOptions options = new TemplateVerifierOptions(templateName: name)
{
TemplateSpecificArgs = args,
SnapshotsDirectory = "Approvals",
OutputDirectory = workingDir,
SettingsDirectory = _fixture.HomeDirectory,
VerifyCommandOutput = true,
DoNotPrependTemplateNameToScenarioName = false,
DoNotAppendTemplateArgsToScenarioName = true,
ScenarioName = language.Replace('#', 's').ToLower(),
VerificationExcludePatterns = new[] { "*/stderr.txt", "*\\stderr.txt" },
DotnetExecutablePath = TestContext.Current.ToolsetUnderTest.DotNetHostPath,
}
.WithCustomEnvironment(environmentUnderTest)
.WithCustomScrubbers(
ScrubbersDefinition.Empty
.AddScrubber(sb => sb.Replace($"<TargetFramework>{currentDefaultFramework}</TargetFramework>", "<TargetFramework>%FRAMEWORK%</TargetFramework>"))
.AddScrubber(sb => sb.Replace(finalProjectName, "%PROJECT_PATH%").UnixifyDirSeparators().ScrubByRegex("(^ Restored .* \\()(.*)(\\)\\.)", "$1%DURATION%$3", RegexOptions.Multiline), "txt")
);

VerificationEngine engine = new VerificationEngine(_logger);
await engine.Execute(options).ConfigureAwait(false);

Directory.Delete(workingDir, true);
}

#region Project templates language features tests

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
"UseProgramMain": {
"longName": "use-program-main",
"shortName": ""
},
"NativeAot": {
"longName": "publish-native-aot",
"shortName": "aot"
}
},
"usageExamples": [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@
"isVisible": true,
"PersistenceScope": "Shared",
"PersistenceScopeName": "Microsoft"
},
{
"id": "NativeAot",
"isVisible": true
}
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
"symbols/skipRestore/displayName": "Přeskočit obnovení",
"symbols/UseProgramMain/description": "Určuje, jestli se má místo příkazů nejvyšší úrovně generovat explicitní třída Program a metoda Main.",
"symbols/UseProgramMain/displayName": "Nepoužívat _příkazy nejvyšší úrovně",
"symbols/NativeAot/description": "Whether to enable the project for publishing as native AOT.",
"symbols/NativeAot/displayName": "Enable _native AOT publish",
"postActions/restore/description": "Obnoví balíčky NuGet vyžadované tímto projektem.",
"postActions/restore/manualInstructions/default/text": "Spustit dotnet restore",
"postActions/open-file/description": "Otevře Program.cs v editoru."
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
"symbols/skipRestore/displayName": "Wiederherstellung überspringen",
"symbols/UseProgramMain/description": "Gibt an, ob anstelle von Anweisungen der obersten Ebene eine explizite Programmklasse und eine Main-Methode generiert werden soll.",
"symbols/UseProgramMain/displayName": "Keine Anweisungen _der obersten Ebene verwenden",
"symbols/NativeAot/description": "Whether to enable the project for publishing as native AOT.",
"symbols/NativeAot/displayName": "Enable _native AOT publish",
"postActions/restore/description": "„NuGet-Pakete“ wiederherstellen, die für dieses Projekt erforderlich sind.",
"postActions/restore/manualInstructions/default/text": "„dotnet restore“ ausführen",
"postActions/open-file/description": "Öffnet „Program.cs“ im Editor."
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
"symbols/UseProgramMain/description": "Whether to generate an explicit Program class and Main method instead of top-level statements.",
"symbols/UseProgramMain/displayName": "Do not use _top-level statements",
"_symbols/UseProgramMain/displayName.comment": "Use '_' as accelerator key when translating.",
"symbols/NativeAot/description": "Whether to enable the project for publishing as native AOT.",
"symbols/NativeAot/displayName": "Enable _native AOT publish",
"_symbols/NativeAot/displayName.comment": "Use '_' as accelerator key when translating.",
"postActions/restore/description": "Restore NuGet packages required by this project.",
"postActions/restore/manualInstructions/default/text": "Run 'dotnet restore'",
"postActions/open-file/description": "Opens Program.cs in the editor"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
"symbols/skipRestore/displayName": "Omitir restauración",
"symbols/UseProgramMain/description": "Indica si se debe generar una clase Program explícita y un método Main en lugar de instrucciones de nivel superior.",
"symbols/UseProgramMain/displayName": "No usar instrucciones de _nivel superior",
"symbols/NativeAot/description": "Whether to enable the project for publishing as native AOT.",
"symbols/NativeAot/displayName": "Enable _native AOT publish",
"postActions/restore/description": "Restaure los paquetes NuGet necesarios para este proyecto.",
"postActions/restore/manualInstructions/default/text": "Ejecutar \"dotnet restore\"",
"postActions/open-file/description": "Abre Program.cs en el editor"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
"symbols/skipRestore/displayName": "Ignorer la restauration",
"symbols/UseProgramMain/description": "Indique s’il faut générer une classe Programme explicite et une méthode Main au lieu d’instructions de niveau supérieur.",
"symbols/UseProgramMain/displayName": "N’utilisez pas _d’instructions de niveau supérieur.",
"symbols/NativeAot/description": "Whether to enable the project for publishing as native AOT.",
"symbols/NativeAot/displayName": "Enable _native AOT publish",
"postActions/restore/description": "Restaurez les packages NuGet requis par ce projet.",
"postActions/restore/manualInstructions/default/text": "Exécuter « dotnet restore »",
"postActions/open-file/description": "Ouvre Program.cs dans l’éditeur"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
"symbols/skipRestore/displayName": "Salta ripristino",
"symbols/UseProgramMain/description": "Indica se generare una classe Program esplicita e un metodo Main anziché istruzioni di primo livello.",
"symbols/UseProgramMain/displayName": "Non usare_istruzioni di primo livello",
"symbols/NativeAot/description": "Whether to enable the project for publishing as native AOT.",
"symbols/NativeAot/displayName": "Enable _native AOT publish",
"postActions/restore/description": "Ripristina i pacchetti NuGet richiesti da questo progetto.",
"postActions/restore/manualInstructions/default/text": "Esegui 'dotnet restore'",
"postActions/open-file/description": "Apre Program.cs nell'editor"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
"symbols/skipRestore/displayName": "復元のスキップ",
"symbols/UseProgramMain/description": "最上位レベルのステートメントではなく、明示的な Program クラスと Main メソッドを生成するかどうか。",
"symbols/UseProgramMain/displayName": "最上位レベルのステートメントを使用しない(_T)",
"symbols/NativeAot/description": "Whether to enable the project for publishing as native AOT.",
"symbols/NativeAot/displayName": "Enable _native AOT publish",
"postActions/restore/description": "このプロジェクトに必要な NuGet パッケージを復元します。",
"postActions/restore/manualInstructions/default/text": "'dotnet restore' を実行する",
"postActions/open-file/description": "エディターで Program.cs を開く"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
"symbols/skipRestore/displayName": "복원 건너뛰기",
"symbols/UseProgramMain/description": "최상위 문 대신 명시적 Program 클래스 및 Main 메서드를 생성할지 여부입니다.",
"symbols/UseProgramMain/displayName": "최상위 문 사용 안 함(_T)",
"symbols/NativeAot/description": "Whether to enable the project for publishing as native AOT.",
"symbols/NativeAot/displayName": "Enable _native AOT publish",
"postActions/restore/description": "이 프로젝트에 필요한 NuGet 패키지를 복원합니다.",
"postActions/restore/manualInstructions/default/text": "'dotnet restore' 실행",
"postActions/open-file/description": "편집기에서 Program.cs를 엽니다"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
"symbols/skipRestore/displayName": "Pomiń przywracanie",
"symbols/UseProgramMain/description": "Określa, czy wygenerować jawną klasę Program i metodę Main zamiast instrukcji najwyższego poziomu.",
"symbols/UseProgramMain/displayName": "Nie używaj ins_trukcji najwyższego poziomu",
"symbols/NativeAot/description": "Whether to enable the project for publishing as native AOT.",
"symbols/NativeAot/displayName": "Enable _native AOT publish",
"postActions/restore/description": "Przywróć pakiety NuGet wymagane przez ten projekt.",
"postActions/restore/manualInstructions/default/text": "Uruchom polecenie \"dotnet restore\"",
"postActions/open-file/description": "Otwiera plik Program.cs w edytorze"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
"symbols/skipRestore/displayName": "Ignorar restauração",
"symbols/UseProgramMain/description": "Se deve gerar uma classe de Programa explícita e um método principal em vez de instruções de nível superior.",
"symbols/UseProgramMain/displayName": "Não use ins_truções de nível superior",
"symbols/NativeAot/description": "Whether to enable the project for publishing as native AOT.",
"symbols/NativeAot/displayName": "Enable _native AOT publish",
"postActions/restore/description": "Restaure os pacotes NuGet exigidos por este projeto.",
"postActions/restore/manualInstructions/default/text": "Executa 'dotnet restore'",
"postActions/open-file/description": "Abre Program.cs no editor"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
"symbols/skipRestore/displayName": "Пропустить восстановление",
"symbols/UseProgramMain/description": "Следует ли создавать явный класс Program и метод Main вместо операторов верхнего уровня.",
"symbols/UseProgramMain/displayName": "Не использовать _операторы верхнего уровня",
"symbols/NativeAot/description": "Whether to enable the project for publishing as native AOT.",
"symbols/NativeAot/displayName": "Enable _native AOT publish",
"postActions/restore/description": "Восстановление пакетов NuGet, необходимых для этого проекта.",
"postActions/restore/manualInstructions/default/text": "Выполнить команду \"dotnet restore\"",
"postActions/open-file/description": "Открывает файл Program.cs в редакторе"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
"symbols/skipRestore/displayName": "Geri yüklemeyi atla",
"symbols/UseProgramMain/description": "Üst düzey deyimler yerine açık bir Program sınıfı ve Ana yöntem oluşturup oluşturulmayacağını belirtir.",
"symbols/UseProgramMain/displayName": "_Üst düzey deyimler kullanmayın",
"symbols/NativeAot/description": "Whether to enable the project for publishing as native AOT.",
"symbols/NativeAot/displayName": "Enable _native AOT publish",
"postActions/restore/description": "Bu projenin gerektirdiği NuGet paketlerini geri yükleyin.",
"postActions/restore/manualInstructions/default/text": "'dotnet restore' çalıştır",
"postActions/open-file/description": "Düzenleyicide Program.cs’yi açar"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
"symbols/skipRestore/displayName": "跳过还原",
"symbols/UseProgramMain/description": "是否生成显式程序类和主方法,而不是顶级语句。",
"symbols/UseProgramMain/displayName": "不使用顶级语句(_T)",
"symbols/NativeAot/description": "Whether to enable the project for publishing as native AOT.",
"symbols/NativeAot/displayName": "Enable _native AOT publish",
"postActions/restore/description": "还原此项目所需的 NuGet 包。",
"postActions/restore/manualInstructions/default/text": "运行 \"dotnet restore\"",
"postActions/open-file/description": "在编辑器中打开 Program.cs"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
"symbols/skipRestore/displayName": "略過還原",
"symbols/UseProgramMain/description": "是否要產生明確的 Program 類別和 Main 方法,而非最上層語句。",
"symbols/UseProgramMain/displayName": "不要使用最上層陳述式(_T)",
"symbols/NativeAot/description": "Whether to enable the project for publishing as native AOT.",
"symbols/NativeAot/displayName": "Enable _native AOT publish",
"postActions/restore/description": "還原此專案所需的 NuGet 套件。",
"postActions/restore/manualInstructions/default/text": "執行 'dotnet restore'",
"postActions/open-file/description": "在編輯器中開啟 Program.cs"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,13 @@
"description": "Whether to generate an explicit Program class and Main method instead of top-level statements.",
"displayName": "Do not use _top-level statements"
},
"NativeAot" : {
"type": "parameter",
"datatype": "bool",
"defaultValue": "false",
"displayName": "Enable _native AOT publish",
"description": "Whether to enable the project for publishing as native AOT."
},
"csharp9orOlder": {
"type": "generated",
"generator": "regexMatch",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@
<LangVersion Condition="'$(langVersion)' != ''">$(ProjectLanguageVersion)</LangVersion>
<ImplicitUsings Condition="'$(csharpFeature_ImplicitUsings)' == 'true'">enable</ImplicitUsings>
<Nullable Condition="'$(csharpFeature_Nullable)' == 'true'">enable</Nullable>
<!--#if (NativeAot) -->
<PublishAot>true</PublishAot>
<InvariantGlobalization>true</InvariantGlobalization>

<!-- Uncomment below line to make native publish outputs a lot smaller on Linux and macOS -->
<!-- <StripSymbols>true</StripSymbols> -->
<!--#endif -->
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@
"langVersion": {
"longName": "langVersion",
"shortName": ""
},
"NativeAot": {
"longName": "publish-native-aot",
"shortName": "aot"
}
},
"usageExamples": [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,11 @@
"add": [],
"remove": [ "Common" ]
}
],
"symbolInfo": [
{
"id": "NativeAot",
"isVisible": true
}
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
"symbols/langVersion/displayName": "Verze jazyka",
"symbols/skipRestore/description": "Pokud se tato možnost zadá, přeskočí automatické obnovení projektu při vytvoření.",
"symbols/skipRestore/displayName": "Přeskočit obnovení",
"symbols/NativeAot/description": "Whether to enable the project for publishing as native AOT.",
"symbols/NativeAot/displayName": "Enable _native AOT publish",
"postActions/restore/description": "Obnoví balíčky NuGet vyžadované tímto projektem.",
"postActions/restore/manualInstructions/default/text": "Spustit dotnet restore",
"postActions/open-file/description": "Otevře Program.vb v editoru."
Expand Down
Loading

0 comments on commit d10b354

Please sign in to comment.