From 73902e7909f949bc1ab10405328d0b18713b5cec Mon Sep 17 00:00:00 2001 From: Vlada Shubina Date: Fri, 9 Jul 2021 13:39:27 +0300 Subject: [PATCH 01/14] removed app templates, moved changes to console app instead --- .../TemplateInformationCoordinator.cs | 7 +- .../.template.config/dotnetcli.host.json | 15 --- .../localize/templatestrings.cs.json | 20 ---- .../localize/templatestrings.de.json | 20 ---- .../localize/templatestrings.en.json | 20 ---- .../localize/templatestrings.es.json | 20 ---- .../localize/templatestrings.fr.json | 20 ---- .../localize/templatestrings.it.json | 20 ---- .../localize/templatestrings.ja.json | 20 ---- .../localize/templatestrings.ko.json | 20 ---- .../localize/templatestrings.pl.json | 20 ---- .../localize/templatestrings.pt-BR.json | 20 ---- .../localize/templatestrings.ru.json | 20 ---- .../localize/templatestrings.tr.json | 20 ---- .../localize/templatestrings.zh-Hans.json | 20 ---- .../localize/templatestrings.zh-Hant.json | 20 ---- .../App-CSharp/.template.config/template.json | 100 ------------------ .../App-CSharp/Company.Application1.csproj | 11 -- .../content/App-CSharp/Program.cs | 4 - .../Company.ConsoleApplication1.csproj | 2 +- .../ConsoleApplication-CSharp/Program.cs | 14 +-- .../CommonTemplatesTests.cs | 19 +--- .../DotnetNewCommandTests.cs | 15 ++- test/dotnet-new3.UnitTests/DotnetNewHelp.cs | 25 +---- test/dotnet-new3.UnitTests/DotnetNewList.cs | 24 ++--- 25 files changed, 25 insertions(+), 491 deletions(-) delete mode 100644 template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/dotnetcli.host.json delete mode 100644 template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.cs.json delete mode 100644 template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.de.json delete mode 100644 template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.en.json delete mode 100644 template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.es.json delete mode 100644 template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.fr.json delete mode 100644 template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.it.json delete mode 100644 template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.ja.json delete mode 100644 template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.ko.json delete mode 100644 template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.pl.json delete mode 100644 template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.pt-BR.json delete mode 100644 template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.ru.json delete mode 100644 template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.tr.json delete mode 100644 template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.zh-Hans.json delete mode 100644 template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.zh-Hant.json delete mode 100644 template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/template.json delete mode 100644 template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/Company.Application1.csproj delete mode 100644 template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/Program.cs diff --git a/src/Microsoft.TemplateEngine.Cli/HelpAndUsage/TemplateInformationCoordinator.cs b/src/Microsoft.TemplateEngine.Cli/HelpAndUsage/TemplateInformationCoordinator.cs index b8c70237f03..bc6fe4ca4ee 100644 --- a/src/Microsoft.TemplateEngine.Cli/HelpAndUsage/TemplateInformationCoordinator.cs +++ b/src/Microsoft.TemplateEngine.Cli/HelpAndUsage/TemplateInformationCoordinator.cs @@ -329,17 +329,17 @@ internal async Task DisplayCommandDescriptionAsync( await ShowCuratedListAsync(commandInput, cancellationToken).ConfigureAwait(false); Reporter.Output.WriteLine(LocalizableStrings.TemplateInformationCoordinator_DotnetNew_ExampleHeader); - Reporter.Output.WriteCommand(commandInput.InstantiateTemplateExample("app")); + Reporter.Output.WriteCommand(commandInput.InstantiateTemplateExample("console")); Reporter.Output.WriteLine(); Reporter.Output.WriteLine(LocalizableStrings.TemplateInformationCoordinator_DotnetNew_DisplayOptionsHint); - Reporter.Output.WriteCommand(commandInput.HelpCommandExample("app")); + Reporter.Output.WriteCommand(commandInput.HelpCommandExample("console")); Reporter.Output.WriteLine(LocalizableStrings.TemplateInformationCoordinator_DotnetNew_ListTemplatesHint); Reporter.Output.WriteCommand(commandInput.ListCommandExample()); Reporter.Output.WriteLine(LocalizableStrings.TemplateInformationCoordinator_DotnetNew_SearchTemplatesHint); - Reporter.Output.WriteCommand(commandInput.SearchCommandExample("ap")); + Reporter.Output.WriteCommand(commandInput.SearchCommandExample("web")); Reporter.Output.WriteLine(); @@ -418,7 +418,6 @@ private async Task ShowCuratedListAsync(INewCommandInput commandInput, Cancellat { "Microsoft.Common.Library", //classlib "Microsoft.Common.Console", //console - "Microsoft.Common.App", //app "Microsoft.Common.WPF", //wpf "Microsoft.Common.WinForms", //winforms "Microsoft.Web.Blazor.Wasm", //blazorwasm diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/dotnetcli.host.json b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/dotnetcli.host.json deleted file mode 100644 index ac8b2facaed..00000000000 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/dotnetcli.host.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "$schema": "http://json.schemastore.org/dotnetcli.host", - "symbolInfo": { - "target-framework-override": { - "isHidden": "true", - "shortName": "" - }, - "no-restore": { - "shortName": "" - }, - "langVersion": { - "shortName": "" - } - } -} diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.cs.json b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.cs.json deleted file mode 100644 index 5f82ecbe8b1..00000000000 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.cs.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "author": "Microsoft", - "name": "Jednoduchá konzolová aplikace", - "description": "Projekt pro vytvoření aplikace příkazového řádku, která používá nejnovější funkce jazyka C# a běží na .NET Core v systémech Windows, Linux a macOS.", - "symbols/framework/description": "Cílová architektura pro projekt", - "symbols/framework/choices/net6.0/description": "Cílit na net6.0", - "symbols/framework/choices/net6.0/displayName": ".NET 6.0", - "symbols/framework/displayName": "Framework", - "symbols/langVersion/description": "Nastaví vlastnost LangVersion ve vytvořeném souboru projektu.", - "symbols/langVersion/displayName": "Verze jazyka", - "symbols/no-restore/description": "Pokud se tato možnost zadá, přeskočí automatické obnovení projektu při vytvoření.", - "symbols/no-restore/displayName": "Přeskočit obnovení", - "symbols/nullable/description": "Určuje, jestli se mají pro tento projekt povolit odkazové typy s možnou hodnotou null.", - "symbols/nullable/displayName": "Povolit vynulovatelnost", - "symbols/target-framework-override/description": "Přepíše cílovou architekturu.", - "symbols/target-framework-override/displayName": "Přepsání cílové architektury", - "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." -} \ No newline at end of file diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.de.json b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.de.json deleted file mode 100644 index 909d2c6c03e..00000000000 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.de.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "author": "Microsoft", - "name": "Einfache Konsolenanwendung", - "description": "Ein Projekt zum Erstellen einer Befehlszeilenanwendung, die die neuesten C#-Features verwendet und auf „.NET Core“ unter Windows, Linux und macOS ausgeführt wird.", - "symbols/framework/description": "Das Zielframework für das Projekt.", - "symbols/framework/choices/net6.0/description": "Auf „net6.0“ abzielen", - "symbols/framework/choices/net6.0/displayName": ".NET 6.0", - "symbols/framework/displayName": "Framework", - "symbols/langVersion/description": "Legt die „LangVersion“-Eigenschaft in der erstellten Projektdatei fest", - "symbols/langVersion/displayName": "Sprachversion", - "symbols/no-restore/description": "Wenn angegeben, wird die automatische Wiederherstellung des Projekts beim Erstellen übersprungen.", - "symbols/no-restore/displayName": "Wiederherstellung überspringen", - "symbols/nullable/description": "Ob Nullwerte zulassende Verweistypen für dieses Projekt aktiviert werden sollen.", - "symbols/nullable/displayName": "Nullwerte aktivieren", - "symbols/target-framework-override/description": "Überschreibt das Zielframework", - "symbols/target-framework-override/displayName": "Zielframeworküberschreibung", - "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." -} \ No newline at end of file diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.en.json b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.en.json deleted file mode 100644 index 773ec19f70b..00000000000 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.en.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "author": "Microsoft", - "name": "Simple Console Application", - "description": "A project for creating a command line application that uses the latest C# features and runs on .NET Core on Windows, Linux and macOS.", - "symbols/framework/description": "The target framework for the project.", - "symbols/framework/choices/net6.0/description": "Target net6.0", - "symbols/framework/choices/net6.0/displayName": ".NET 6.0", - "symbols/framework/displayName": "Framework", - "symbols/langVersion/description": "Sets the LangVersion property in the created project file", - "symbols/langVersion/displayName": "Language Version", - "symbols/no-restore/description": "If specified, skips the automatic restore of the project on create.", - "symbols/no-restore/displayName": "Skip restore", - "symbols/nullable/description": "Whether to enable nullable reference types for this project.", - "symbols/nullable/displayName": "Enable nullable", - "symbols/target-framework-override/description": "Overrides the target framework", - "symbols/target-framework-override/displayName": "Target framework override", - "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" -} \ No newline at end of file diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.es.json b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.es.json deleted file mode 100644 index cf8958c3cbc..00000000000 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.es.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "author": "Microsoft", - "name": "Aplicación de consola sencilla", - "description": "Proyecto para crear una aplicación de línea de comandos que usa las características más recientes de C# y se ejecuta en .NET Core en Windows, Linux y macOS.", - "symbols/framework/description": "Marco de destino del proyecto.", - "symbols/framework/choices/net6.0/description": "Destino Net 6.0", - "symbols/framework/choices/net6.0/displayName": ".NET 6.0", - "symbols/framework/displayName": "Plataforma", - "symbols/langVersion/description": "Establece la propiedad LangVersion en el archivo de proyecto creado.", - "symbols/langVersion/displayName": "Versión de lenguaje", - "symbols/no-restore/description": "Si se especifica, se omite la restauración automática del proyecto durante la creación.", - "symbols/no-restore/displayName": "Omitir restauración", - "symbols/nullable/description": "Indica si se deben habilitar tipos de referencia que aceptan valores NULL para este proyecto.", - "symbols/nullable/displayName": "Habilitar los que admiten un valor NULL", - "symbols/target-framework-override/description": "Invalida la plataforma de destino", - "symbols/target-framework-override/displayName": "Invalidación de la plataforma de destino", - "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" -} \ No newline at end of file diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.fr.json b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.fr.json deleted file mode 100644 index 99a38d1ae29..00000000000 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.fr.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "author": "Microsoft", - "name": "Application console simple", - "description": "Projet de création d’une application en ligne de commande qui utilise les dernières fonctionnalités C# et s’exécute sur .NET Core sur Windows, Linux et macOS.", - "symbols/framework/description": "Framework cible du projet.", - "symbols/framework/choices/net6.0/description": "Net6.0 cible", - "symbols/framework/choices/net6.0/displayName": ".NET 6.0", - "symbols/framework/displayName": "Framework", - "symbols/langVersion/description": "Définit la propriété LangVersion dans le fichier projet créé", - "symbols/langVersion/displayName": "Version du langage", - "symbols/no-restore/description": "S’il est spécifié, ignore la restauration automatique du projet lors de la création.", - "symbols/no-restore/displayName": "Ignorer la restauration", - "symbols/nullable/description": "Indique s’il faut activer les types référence Nullable pour ce projet.", - "symbols/nullable/displayName": "Autoriser la valeur Null", - "symbols/target-framework-override/description": "Remplace l’infrastructure cible", - "symbols/target-framework-override/displayName": "Remplacement du frame cible", - "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" -} \ No newline at end of file diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.it.json b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.it.json deleted file mode 100644 index 8e881c5d71d..00000000000 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.it.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "author": "Microsoft", - "name": "Applicazione console semplice", - "description": "Un progetto per la creazione di un'applicazione da riga di comando che usa le funzionalità C# più recenti e viene eseguito in .NET Core su Windows, Linux e macOS.", - "symbols/framework/description": "Il framework di destinazione per il progetto.", - "symbols/framework/choices/net6.0/description": "Net6.0 di destinazione", - "symbols/framework/choices/net6.0/displayName": ".NET 6.0", - "symbols/framework/displayName": "Framework", - "symbols/langVersion/description": "Imposta la proprietà LangVersion nel file di progetto creato", - "symbols/langVersion/displayName": "Versione linguaggio", - "symbols/no-restore/description": "Se specificato, ignora il ripristino automatico del progetto durante la creazione.", - "symbols/no-restore/displayName": "Salta ripristino", - "symbols/nullable/description": "Indica se abilitare i tipi di riferimento che ammettono i valori Null per questo progetto.", - "symbols/nullable/displayName": "Abilita valori null", - "symbols/target-framework-override/description": "Ignora il framework di destinazione", - "symbols/target-framework-override/displayName": "Override del framework di destinazione", - "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" -} \ No newline at end of file diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.ja.json b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.ja.json deleted file mode 100644 index 61b45768227..00000000000 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.ja.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "author": "Microsoft", - "name": "シンプル コンソール アプリケーション", - "description": "最新の C# 機能を使用し、Windows、Linux、macOS の .NET Core で実行されるコマンド ライン アプリケーションを作成するためのプロジェクトです。", - "symbols/framework/description": "プロジェクトのターゲット フレームワークです。", - "symbols/framework/choices/net6.0/description": "ターゲット net6.0", - "symbols/framework/choices/net6.0/displayName": ".NET 6.0", - "symbols/framework/displayName": "フレームワーク", - "symbols/langVersion/description": "作成されたプロジェクト ファイルで LangVersion プロパティを設定する", - "symbols/langVersion/displayName": "言語バージョン", - "symbols/no-restore/description": "指定した場合、作成時にプロジェクトの自動復元がスキップされます。", - "symbols/no-restore/displayName": "復元のスキップ", - "symbols/nullable/description": "このプロジェクトの null 許容参照型を有効にするかどうか。", - "symbols/nullable/displayName": "Null 許容を有効にする", - "symbols/target-framework-override/description": "ターゲット フレームワークをオーバーライドする", - "symbols/target-framework-override/displayName": "ターゲット フレームワークのオーバーライド", - "postActions/restore/description": "このプロジェクトに必要な NuGet パッケージを復元します。", - "postActions/restore/manualInstructions/default/text": "'dotnet restore' を実行する", - "postActions/open-file/description": "エディターで Program.cs を開く" -} \ No newline at end of file diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.ko.json b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.ko.json deleted file mode 100644 index eb4115e9149..00000000000 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.ko.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "author": "Microsoft", - "name": "단순 콘솔 응용 프로그램", - "description": "최신 C# 기능을 사용하고 Windows, Linux 및 macOS의 .NET Core에서 실행되는 명령줄 응용 프로그램을 만들기 위한 프로젝트입니다.", - "symbols/framework/description": "프로젝트에 대한 대상 프레임워크입니다.", - "symbols/framework/choices/net6.0/description": "대상 net6.0", - "symbols/framework/choices/net6.0/displayName": ".NET 6.0", - "symbols/framework/displayName": "프레임워크", - "symbols/langVersion/description": "만든 프로젝트 파일에 LangVersion 속성을 설정합니다", - "symbols/langVersion/displayName": "언어 버전", - "symbols/no-restore/description": "지정된 경우, 프로젝트 생성 시 자동 복원을 건너뜁니다.", - "symbols/no-restore/displayName": "복원 건너뛰기", - "symbols/nullable/description": "이 프로젝트에 대해 nullable 참조 형식을 사용할지 여부를 지정합니다.", - "symbols/nullable/displayName": "nullable 사용", - "symbols/target-framework-override/description": "대상 프레임워크를 재정의합니다", - "symbols/target-framework-override/displayName": "대상 프레임워크 재정의", - "postActions/restore/description": "이 프로젝트에 필요한 NuGet 패키지를 복원합니다.", - "postActions/restore/manualInstructions/default/text": "'dotnet restore' 실행", - "postActions/open-file/description": "편집기에서 Program.cs를 엽니다" -} \ No newline at end of file diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.pl.json b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.pl.json deleted file mode 100644 index 0d731877cc1..00000000000 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.pl.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "author": "Microsoft", - "name": "Prosta aplikacja konsoli", - "description": "Projekt służący do tworzenia aplikacji wiersza polecenia, która używa najnowszych funkcji języka C# i działa w środowisku .NET Core w systemach Windows, Linux i macOS.", - "symbols/framework/description": "Platforma docelowa dla projektu.", - "symbols/framework/choices/net6.0/description": "Docelowy net6.0", - "symbols/framework/choices/net6.0/displayName": ".NET 6.0", - "symbols/framework/displayName": "Platforma", - "symbols/langVersion/description": "Ustawia właściwość LangVersion w utworzonym pliku projektu", - "symbols/langVersion/displayName": "Wersja języka", - "symbols/no-restore/description": "Jeśli ta opcja jest określona, pomija automatyczne przywracanie projektu podczas tworzenia.", - "symbols/no-restore/displayName": "Pomiń przywracanie", - "symbols/nullable/description": "Określa, czy w przypadku tego projektu mają być włączane typy pustych referencji.", - "symbols/nullable/displayName": "Włącz dopuszczającą wartość null", - "symbols/target-framework-override/description": "Zastępuje platformę docelową", - "symbols/target-framework-override/displayName": "Odrzucenie platformy docelowej", - "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" -} \ No newline at end of file diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.pt-BR.json b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.pt-BR.json deleted file mode 100644 index ae793754fbf..00000000000 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.pt-BR.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "author": "Microsoft", - "name": "Aplicativo de Console Simples", - "description": "Um projeto para criar um aplicativo de linha de comando que usa os recursos C# mais recentes e é executado no .NET Core no Windows, Linux e macOS.", - "symbols/framework/description": "A estrutura de destino do projeto.", - "symbols/framework/choices/net6.0/description": "Net6.0 de destino", - "symbols/framework/choices/net6.0/displayName": ".NET 6.0", - "symbols/framework/displayName": "Framework", - "symbols/langVersion/description": "Definir a propriedade LangVersion no arquivo do projeto criado", - "symbols/langVersion/displayName": "Versão da Linguagem", - "symbols/no-restore/description": "Se especificado, ignora a restauração automática do projeto em criação.", - "symbols/no-restore/displayName": "Ignorar restauração", - "symbols/nullable/description": "Se os tipos de referência que permitem valor nulo devem ser habilitados para este projeto.", - "symbols/nullable/displayName": "Habilitar anulável", - "symbols/target-framework-override/description": "Substitui a estrutura de destino", - "symbols/target-framework-override/displayName": "Substituição da estrutura de destino", - "postActions/restore/description": "Restaure os pacotes NuGet exigidos por este projeto.", - "postActions/restore/manualInstructions/default/text": "Executar 'dotnet restore'", - "postActions/open-file/description": "Abre Program.cs no editor" -} \ No newline at end of file diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.ru.json b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.ru.json deleted file mode 100644 index b8fef3e36ad..00000000000 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.ru.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "author": "Майкрософт", - "name": "Простое консольное приложение", - "description": "Проект для создания приложения командной строки, которое использует новейшие функции C# и работает на платформе .NET Core в Windows, Linux и macOS.", - "symbols/framework/description": "Целевая платформа для проекта.", - "symbols/framework/choices/net6.0/description": "Целевая платформа: net6.0.", - "symbols/framework/choices/net6.0/displayName": ".NET 6.0", - "symbols/framework/displayName": "Платформа", - "symbols/langVersion/description": "Задает свойство LangVersion в создаваемом файле проекта.", - "symbols/langVersion/displayName": "Версия языка", - "symbols/no-restore/description": "Позволяет пропускать автоматическое восстановление проекта при создании.", - "symbols/no-restore/displayName": "Пропустить восстановление", - "symbols/nullable/description": "Активация в проекте ссылочных типов, допускающих значение null.", - "symbols/nullable/displayName": "Включить допустимость значений NULL", - "symbols/target-framework-override/description": "Переопределяет целевую платформу.", - "symbols/target-framework-override/displayName": "Переопределение целевой платформы", - "postActions/restore/description": "Восстановление требуемых пакетов NuGet для этого проекта.", - "postActions/restore/manualInstructions/default/text": "Запуск \"dotnet restore\"", - "postActions/open-file/description": "Открывает Program.cs в редакторе." -} \ No newline at end of file diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.tr.json b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.tr.json deleted file mode 100644 index 4af71ded004..00000000000 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.tr.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "author": "Microsoft", - "name": "Basit Konsol Uygulaması", - "description": "En son C# özelliklerini kullanan ve Windows, Linux ile macOS üzerindeki .NET Core’da çalışan komut satırı uygulaması oluşturmaya yönelik proje.", - "symbols/framework/description": "Projenin hedef çerçevesi.", - "symbols/framework/choices/net6.0/description": "Hedef net6.0", - "symbols/framework/choices/net6.0/displayName": ".NET 6.0", - "symbols/framework/displayName": "Çerçeve", - "symbols/langVersion/description": "Oluşturulan proje dosyasında LangVersion özelliğini ayarlar", - "symbols/langVersion/displayName": "Dil Sürümü", - "symbols/no-restore/description": "Belirtilirse, oluşturma sırasında projenin otomatik geri yüklenmesini atlar.", - "symbols/no-restore/displayName": "Geri yüklemeyi atla", - "symbols/nullable/description": "Bu proje için null atanabilir başvuru türlerinin etkinleştirilip etkinleştirilmeyeceğini belirtir.", - "symbols/nullable/displayName": "Null atanabilir özelliğini etkinleştir", - "symbols/target-framework-override/description": "Hedef çerçeveyi geçersiz kılar", - "symbols/target-framework-override/displayName": "Hedef çerçeveyi geçersiz kılma", - "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" -} \ No newline at end of file diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.zh-Hans.json b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.zh-Hans.json deleted file mode 100644 index 31823cdaec2..00000000000 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.zh-Hans.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "author": "Microsoft", - "name": "简单控制台应用程序", - "description": "用于创建命令行应用程序的项目,该应用程序使用最新的 C# 功能,并在 Windows、Linux 和 macOS 上的 .NET Core 上运行。", - "symbols/framework/description": "项目的目标框架。", - "symbols/framework/choices/net6.0/description": "目标 net6.0", - "symbols/framework/choices/net6.0/displayName": ".NET 6.0", - "symbols/framework/displayName": "框架", - "symbols/langVersion/description": "在创建的项目文件中设置 LangVersion 属性", - "symbols/langVersion/displayName": "语言版本", - "symbols/no-restore/description": "如果指定,则在创建时跳过项目的自动还原。", - "symbols/no-restore/displayName": "跳过还原", - "symbols/nullable/description": "是否为此项目启用可为 null 的引用类型。", - "symbols/nullable/displayName": "启用可为 null", - "symbols/target-framework-override/description": "替代目标框架", - "symbols/target-framework-override/displayName": "目标框架替代", - "postActions/restore/description": "还原此项目所需的 NuGet 包。", - "postActions/restore/manualInstructions/default/text": "运行“dotnet restore”", - "postActions/open-file/description": "在编辑器中打开 Program.cs" -} \ No newline at end of file diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.zh-Hant.json b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.zh-Hant.json deleted file mode 100644 index 869b93841b7..00000000000 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/localize/templatestrings.zh-Hant.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "author": "Microsoft", - "name": "簡易主控台應用程式", - "description": "用來建立命令列應用程式的專案,其使用最新的功能,且在 Windows、Linux 和 macOS 上的 C# .NET Core 上執行。", - "symbols/framework/description": "專案的目標 Framework。", - "symbols/framework/choices/net6.0/description": "目標 net6.0", - "symbols/framework/choices/net6.0/displayName": ".NET 6.0", - "symbols/framework/displayName": "架構", - "symbols/langVersion/description": "設定建立的專案檔中的 LangVersion 屬性", - "symbols/langVersion/displayName": "語言版本", - "symbols/no-restore/description": "若指定,會在建立時跳過專案的自動還原。", - "symbols/no-restore/displayName": "略過還原", - "symbols/nullable/description": "是否要啟用此專案的可 null 參考類型。", - "symbols/nullable/displayName": "啟用可為 Null", - "symbols/target-framework-override/description": "覆寫目標 Framework", - "symbols/target-framework-override/displayName": "目標 Framework 覆寫", - "postActions/restore/description": "還原此專案所需的 NuGet 套件。", - "postActions/restore/manualInstructions/default/text": "執行 'dotnet restore'", - "postActions/open-file/description": "在編輯器中開啟 Program.cs" -} \ No newline at end of file diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/template.json b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/template.json deleted file mode 100644 index c2cf1e84886..00000000000 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/.template.config/template.json +++ /dev/null @@ -1,100 +0,0 @@ -{ - "$schema": "http://json.schemastore.org/template", - "author": "Microsoft", - "classifications": [ - "Common", - "Console" - ], - "name": "Simple Console Application", - "generatorVersions": "[1.0.0.0-*)", - "description": "A project for creating a command line application that uses the latest C# features and runs on .NET Core on Windows, Linux and macOS.", - "groupIdentity": "Microsoft.Common.App", - "precedence": "1000", - "identity": "Microsoft.Common.App.CSharp.6.0", - "shortName": "app", - "tags": { - "language": "C#", - "type": "project" - }, - "sourceName": "Company.Application1", - "preferNameDirectory": true, - "symbols": { - "framework": { - "type": "parameter", - "description": "The target framework for the project.", - "datatype": "choice", - "choices": [ - { - "choice": "net6.0", - "description": "Target net6.0", - "displayName": ".NET 6.0" - } - ], - "replaces": "net6.0", - "defaultValue": "net6.0", - "displayName": "Framework" - }, - "langVersion": { - "type": "parameter", - "datatype": "text", - "description": "Sets the LangVersion property in the created project file", - "defaultValue": "", - "replaces": "$(ProjectLanguageVersion)", - "displayName": "Language Version" - }, - "no-restore": { - "type": "parameter", - "datatype": "bool", - "description": "If specified, skips the automatic restore of the project on create.", - "defaultValue": "false", - "displayName": "Skip restore" - }, - "target-framework-override": { - "type": "parameter", - "description": "Overrides the target framework", - "replaces": "target-framework-override", - "datatype": "string", - "defaultValue": "", - "displayName": "Target framework override" - }, - "HostIdentifier": { - "type": "bind", - "binding": "HostIdentifier" - } - }, - "primaryOutputs": [ - { - "path": "Company.Application1.csproj" - }, - { - "condition": "(HostIdentifier != \"dotnetcli\" && HostIdentifier != \"dotnetcli-preview\")", - "path": "Program.cs" - } - ], - "defaultName": "Application1", - "postActions": [ - { - "id": "restore", - "condition": "(!no-restore)", - "description": "Restore NuGet packages required by this project.", - "manualInstructions": [ - { - "text": "Run 'dotnet restore'" - } - ], - "actionId": "210D431B-A78B-4D2F-B762-4ED3E3EA9025", - "continueOnError": true - }, - { - "id": "open-file", - "condition": "(HostIdentifier != \"dotnetcli\" && HostIdentifier != \"dotnetcli-preview\")", - "description": "Opens Program.cs in the editor", - "manualInstructions": [], - "actionId": "84C0DA21-51C8-4541-9940-6CA19AF04EE6", - "args": { - "files": "1" - }, - "continueOnError": true - } - ] -} diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/Company.Application1.csproj b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/Company.Application1.csproj deleted file mode 100644 index 0bf8367e010..00000000000 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/Company.Application1.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - - Exe - net6.0 - target-framework-override - $(ProjectLanguageVersion) - enable - - - diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/Program.cs b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/Program.cs deleted file mode 100644 index d4f22b02017..00000000000 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/App-CSharp/Program.cs +++ /dev/null @@ -1,4 +0,0 @@ -using System; - -Console.WriteLine("Hello, World!"); - diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ConsoleApplication-CSharp/Company.ConsoleApplication1.csproj b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ConsoleApplication-CSharp/Company.ConsoleApplication1.csproj index cb9f6e22189..66e0f74129c 100644 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ConsoleApplication-CSharp/Company.ConsoleApplication1.csproj +++ b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ConsoleApplication-CSharp/Company.ConsoleApplication1.csproj @@ -4,8 +4,8 @@ Exe net6.0 TargetFrameworkOverride - Company.ConsoleApplication1 $(ProjectLanguageVersion) + enable diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ConsoleApplication-CSharp/Program.cs b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ConsoleApplication-CSharp/Program.cs index ec62b483237..68c6516d215 100644 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ConsoleApplication-CSharp/Program.cs +++ b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ConsoleApplication-CSharp/Program.cs @@ -1,12 +1,2 @@ -using System; - -namespace Company.ConsoleApplication1 -{ - class Program - { - static void Main(string[] args) - { - Console.WriteLine("Hello World!"); - } - } -} +Console.WriteLine("Hello, World!"); +// See https://aka.ms/new-console-template for more information diff --git a/test/dotnet-new3.UnitTests/CommonTemplatesTests.cs b/test/dotnet-new3.UnitTests/CommonTemplatesTests.cs index df58687bb75..2ca687f016b 100644 --- a/test/dotnet-new3.UnitTests/CommonTemplatesTests.cs +++ b/test/dotnet-new3.UnitTests/CommonTemplatesTests.cs @@ -65,10 +65,6 @@ public CommonTemplatesTests(SharedHomeDirectory fixture, ITestOutputHelper log) [InlineData("Class Library", "classlib", "C#", "netstandard2.0")] [InlineData("Class Library", "classlib", "VB", "netstandard2.0")] [InlineData("Class Library", "classlib", "F#", "netstandard2.0")] - - [InlineData("Simple Console Application", "app")] - [InlineData("Simple Console Application", "app", "C#")] - [InlineData("Simple Console Application", "app", "C#", "net6.0")] public void AllCommonProjectsCreateRestoreAndBuild(string expectedTemplateName, string templateShortName, string? language = null, string? framework = null) { string workingDir = TestUtils.CreateTemporaryFolder(); @@ -175,10 +171,6 @@ Determining projects to restore\.\.\. [InlineData("Class Library", "classlib", "C#", "netstandard2.0")] [InlineData("Class Library", "classlib", "VB", "netstandard2.0")] [InlineData("Class Library", "classlib", "F#", "netstandard2.0")] - - [InlineData("Simple Console Application", "app")] - [InlineData("Simple Console Application", "app", "C#")] - [InlineData("Simple Console Application", "app", "C#", "net6.0")] public void AllCommonProjectsCreate_NoRestore(string expectedTemplateName, string templateShortName, string? language = null, string? framework = null) { string workingDir = TestUtils.CreateTemporaryFolder(); @@ -231,15 +223,13 @@ public void AllCommonItemsCreate(string expectedTemplateName, string templateSho } [Theory] - [InlineData("Nullable", "enable", "Simple Console Application", "app", null, null)] - [InlineData("CheckForOverflowUnderflow", null, "Simple Console Application", "app", null, null)] - [InlineData("LangVersion", null, "Simple Console Application", "app", null, null)] - [InlineData("TargetFramework", "net6.0", "Simple Console Application", "app", null, null)] - - [InlineData("Nullable", null, "Console Application", "console", null, null)] + [InlineData("Nullable", "enable", "Console Application", "console", null, null)] [InlineData("CheckForOverflowUnderflow", null, "Console Application", "console", null, null)] [InlineData("LangVersion", null, "Console Application", "console", null, null)] [InlineData("TargetFramework", "net6.0", "Console Application", "console", null, null)] + [InlineData("Nullable", null, "Console Application", "console", null, "net5.0")] + [InlineData("Nullable", null, "Console Application", "console", null, "netcoreapp3.1")] + [InlineData("Nullable", null, "Console Application", "console", null, "netcoreapp2.1")] [InlineData("Nullable", null, "Console Application", "console", "F#", null)] [InlineData("CheckForOverflowUnderflow", null, "Console Application", "console", "F#", null)] @@ -319,7 +309,6 @@ public void SetPropertiesByDefault(string propertyName, string? propertyValue, s [Theory] //language version - [InlineData("LangVersion", "9.0", "--langVersion", "9.0", "Simple Console Application", "app", null, null)] [InlineData("LangVersion", "9.0", "--langVersion", "9.0", "Console Application", "console", null, null)] [InlineData("LangVersion", "9.0", "--langVersion", "9.0", "Console Application", "console", "VB", null)] [InlineData("LangVersion", "9.0", "--langVersion", "9.0", "Class Library", "classlib", null, null)] diff --git a/test/dotnet-new3.UnitTests/DotnetNewCommandTests.cs b/test/dotnet-new3.UnitTests/DotnetNewCommandTests.cs index d505501841d..05c353c4bb2 100644 --- a/test/dotnet-new3.UnitTests/DotnetNewCommandTests.cs +++ b/test/dotnet-new3.UnitTests/DotnetNewCommandTests.cs @@ -36,21 +36,20 @@ public void CanShowBasicInfo() @"The 'dotnet new3' command creates a .NET project based on a template. Common templates are: -Template Name Short Name Language Tags --------------------------- ---------- ---------- -------------- -Class Library classlib [C#],F#,VB Common/Library -Console Application console [C#],F#,VB Common/Console -Simple Console Application app [C#] Common/Console +Template Name Short Name Language Tags +------------------- ---------- ---------- -------------- +Class Library classlib [C#],F#,VB Common/Library +Console Application console [C#],F#,VB Common/Console An example would be: - dotnet new3 app + dotnet new3 console Display template options with: - dotnet new3 app -h + dotnet new3 console -h Display all installed templates with: dotnet new3 --list Display templates available on NuGet.org with: - dotnet new3 ap --search"); + dotnet new3 web --search"); } [Fact] diff --git a/test/dotnet-new3.UnitTests/DotnetNewHelp.cs b/test/dotnet-new3.UnitTests/DotnetNewHelp.cs index d394bb69b7b..c876a94fdb1 100644 --- a/test/dotnet-new3.UnitTests/DotnetNewHelp.cs +++ b/test/dotnet-new3.UnitTests/DotnetNewHelp.cs @@ -106,18 +106,6 @@ public class DotnetNewHelp To see help for other template languages (F#, VB), use --language option: dotnet new3 classlib -h --language F#"; - private const string ConsoleAppHelp = -@"Simple Console Application (C#) -Author: Microsoft -Description: A project for creating a command line application that uses the latest C# features and runs on .NET Core on Windows, Linux and macOS. -Options: - --langVersion Sets the LangVersion property in the created project file - text - Optional - - --no-restore If specified, skips the automatic restore of the project on create. - bool - Optional - Default: false "; - #endregion private readonly ITestOutputHelper _log; @@ -176,16 +164,6 @@ public void CanShowHelpForTemplate() .And.NotHaveStdErr() .And.HaveStdOut(ClassLibHelp) .And.NotHaveStdOutContaining(HelpOutput); - - new DotnetNewCommand(_log, "app", "-h") - .WithCustomHive(home) - .WithWorkingDirectory(workingDirectory) - .Execute() - .Should() - .ExitWith(0) - .And.NotHaveStdErr() - .And.HaveStdOut(ConsoleAppHelp) - .And.NotHaveStdOutContaining(HelpOutput); } [Fact] @@ -426,13 +404,12 @@ public void WontShowLanguageHintInCaseOfOneLang() string home = TestUtils.CreateTemporaryFolder("Home"); string workingDirectory = TestUtils.CreateTemporaryFolder(); - new DotnetNewCommand(_log, "app", "--help", "--language", "C#") + new DotnetNewCommand(_log, "globaljson", "--help") .WithCustomHive(home) .WithWorkingDirectory(workingDirectory) .Execute() .Should().Pass() .And.NotHaveStdErr() - .And.HaveStdOut(ConsoleAppHelp) .And.NotHaveStdOutContaining("To see help for other template languages"); } diff --git a/test/dotnet-new3.UnitTests/DotnetNewList.cs b/test/dotnet-new3.UnitTests/DotnetNewList.cs index 69806ede949..584ca971519 100644 --- a/test/dotnet-new3.UnitTests/DotnetNewList.cs +++ b/test/dotnet-new3.UnitTests/DotnetNewList.cs @@ -110,7 +110,6 @@ Dotnet local tool manifest file tool-manifest Config global.json file globaljson Config NuGet Config nugetconfig Config Razor Class Library razorclasslib [C#] Web/Razor/Library -Simple Console Application app [C#] Common/Console Solution File sln Solution Web Config webconfig Config Worker Service worker [C#],F# Common/Worker/Web "; @@ -372,7 +371,6 @@ public void CanFilterByChoiceParameterWithValue() .And.HaveStdOutMatching("Template Name\\s+Short Name\\s+Language\\s+Tags") .And.HaveStdOutMatching("Console Application\\s+console\\s+\\[C#\\],F#,VB\\s+Common/Console") .And.HaveStdOutMatching("Class Library\\s+classlib\\s+\\[C#\\],F#,VB\\s+Common/Library") - .And.HaveStdOutMatching("Simple Console Application\\s+app\\s+\\[C#\\]\\s+Common/Console") .And.HaveStdOutMatching("NuGet Config\\s+nugetconfig\\s+Config"); new DotnetNewCommand(_log, "c", "--list") @@ -385,7 +383,6 @@ public void CanFilterByChoiceParameterWithValue() .And.HaveStdOutMatching("Template Name\\s+Short Name\\s+Language\\s+Tags") .And.HaveStdOutMatching("Console Application\\s+console\\s+\\[C#\\],F#,VB\\s+Common/Console") .And.HaveStdOutMatching("Class Library\\s+classlib\\s+\\[C#\\],F#,VB\\s+Common/Library") - .And.HaveStdOutMatching("Simple Console Application\\s+app\\s+\\[C#\\]\\s+Common/Console") .And.HaveStdOutMatching("NuGet Config\\s+nugetconfig\\s+Config"); new DotnetNewCommand(_log, "c", "--list", "--framework", "net5.0") @@ -398,7 +395,6 @@ public void CanFilterByChoiceParameterWithValue() .And.HaveStdOutMatching("Template Name\\s+Short Name\\s+Language\\s+Tags") .And.HaveStdOutMatching("Console Application\\s+console\\s+\\[C#\\],F#,VB\\s+Common/Console") .And.HaveStdOutMatching("Class Library\\s+classlib\\s+\\[C#\\],F#,VB\\s+Common/Library") - .And.NotHaveStdOutMatching("Simple Console Application\\s+app\\s+\\[C#\\]\\s+Common/Console") .And.NotHaveStdOutMatching("NuGet Config\\s+nugetconfig\\s+Config"); new DotnetNewCommand(_log, "c", "--list", "-f", "net5.0") @@ -411,7 +407,6 @@ public void CanFilterByChoiceParameterWithValue() .And.HaveStdOutMatching("Template Name\\s+Short Name\\s+Language\\s+Tags") .And.HaveStdOutMatching("Console Application\\s+console\\s+\\[C#\\],F#,VB\\s+Common/Console") .And.HaveStdOutMatching("Class Library\\s+classlib\\s+\\[C#\\],F#,VB\\s+Common/Library") - .And.NotHaveStdOutMatching("Simple Console Application\\s+app\\s+\\[C#\\]\\s+Common/Console") .And.NotHaveStdOutMatching("NuGet Config\\s+nugetconfig\\s+Config"); new DotnetNewCommand(_log, "--list", "--framework", "net5.0") @@ -424,7 +419,6 @@ public void CanFilterByChoiceParameterWithValue() .And.HaveStdOutMatching("Template Name\\s+Short Name\\s+Language\\s+Tags") .And.HaveStdOutMatching("Console Application\\s+console\\s+\\[C#\\],F#,VB\\s+Common/Console") .And.HaveStdOutMatching("Class Library\\s+classlib\\s+\\[C#\\],F#,VB\\s+Common/Library") - .And.NotHaveStdOutMatching("Simple Console Application\\s+app\\s+\\[C#\\]\\s+Common/Console") .And.NotHaveStdOutMatching("NuGet Config\\s+nugetconfig\\s+Config"); new DotnetNewCommand(_log, "--list", "-f", "net5.0") @@ -437,7 +431,6 @@ public void CanFilterByChoiceParameterWithValue() .And.HaveStdOutMatching("Template Name\\s+Short Name\\s+Language\\s+Tags") .And.HaveStdOutMatching("Console Application\\s+console\\s+\\[C#\\],F#,VB\\s+Common/Console") .And.HaveStdOutMatching("Class Library\\s+classlib\\s+\\[C#\\],F#,VB\\s+Common/Library") - .And.NotHaveStdOutMatching("Simple Console Application\\s+app\\s+\\[C#\\]\\s+Common/Console") .And.NotHaveStdOutMatching("NuGet Config\\s+nugetconfig\\s+Config"); } @@ -454,7 +447,6 @@ public void CannotListTemplatesWithUnknownParameter() .And.HaveStdOutMatching("Template Name\\s+Short Name\\s+Language\\s+Tags") .And.HaveStdOutMatching("Console Application\\s+console\\s+\\[C#\\],F#,VB\\s+Common/Console") .And.HaveStdOutMatching("Class Library\\s+classlib\\s+\\[C#\\],F#,VB\\s+Common/Library") - .And.HaveStdOutMatching("Simple Console Application\\s+app\\s+\\[C#\\]\\s+Common/Console") .And.HaveStdOutMatching("NuGet Config\\s+nugetconfig\\s+Config"); new DotnetNewCommand(_log, "--list", "--unknown") @@ -462,7 +454,7 @@ public void CannotListTemplatesWithUnknownParameter() .Execute() .Should().Fail() .And.HaveStdErrContaining("No templates found matching: --unknown.") - .And.HaveStdErrContaining("9 template(s) partially matched, but failed on --unknown.") + .And.HaveStdErrContaining("8 template(s) partially matched, but failed on --unknown.") .And.HaveStdErrContaining($"To search for the templates on NuGet.org, run:{Environment.NewLine} dotnet new3 --search"); new DotnetNewCommand(_log, "c", "--list", "--unknown") @@ -470,7 +462,7 @@ public void CannotListTemplatesWithUnknownParameter() .Execute() .Should().Fail() .And.HaveStdErrContaining("No templates found matching: 'c', --unknown.") - .And.HaveStdErrContaining("6 template(s) partially matched, but failed on --unknown.") + .And.HaveStdErrContaining("5 template(s) partially matched, but failed on --unknown.") .And.HaveStdErrContaining($"To search for the templates on NuGet.org, run:{Environment.NewLine} dotnet new3 c --search"); new DotnetNewCommand(_log, "c", "--list", "--unknown", "--language", "C#") @@ -478,7 +470,7 @@ public void CannotListTemplatesWithUnknownParameter() .Execute() .Should().Fail() .And.HaveStdErrContaining("No templates found matching: 'c', language='C#', --unknown.") - .And.HaveStdErrContaining("6 template(s) partially matched, but failed on language='C#', --unknown.") + .And.HaveStdErrContaining("5 template(s) partially matched, but failed on language='C#', --unknown.") .And.HaveStdErrContaining($"To search for the templates on NuGet.org, run:{Environment.NewLine} dotnet new3 c --search"); } @@ -495,7 +487,6 @@ public void CannotListTemplatesWithUnknownValueForChoiceParameter() .And.HaveStdOutMatching("Template Name\\s+Short Name\\s+Language\\s+Tags") .And.HaveStdOutMatching("Console Application\\s+console\\s+\\[C#\\],F#,VB\\s+Common/Console") .And.HaveStdOutMatching("Class Library\\s+classlib\\s+\\[C#\\],F#,VB\\s+Common/Library") - .And.HaveStdOutMatching("Simple Console Application\\s+app\\s+\\[C#\\]\\s+Common/Console") .And.HaveStdOutMatching("NuGet Config\\s+nugetconfig\\s+Config"); new DotnetNewCommand(_log, "--list", "--framework", "unknown") @@ -503,7 +494,7 @@ public void CannotListTemplatesWithUnknownValueForChoiceParameter() .Execute() .Should().Fail() .And.HaveStdErrContaining("No templates found matching: --framework='unknown'.") - .And.HaveStdErrContaining("9 template(s) partially matched, but failed on --framework='unknown'.") + .And.HaveStdErrContaining("8 template(s) partially matched, but failed on --framework='unknown'.") .And.HaveStdErrContaining($"To search for the templates on NuGet.org, run:{Environment.NewLine} dotnet new3 --search"); new DotnetNewCommand(_log, "c", "--list", "--framework", "unknown") @@ -511,7 +502,7 @@ public void CannotListTemplatesWithUnknownValueForChoiceParameter() .Execute() .Should().Fail() .And.HaveStdErrContaining("No templates found matching: 'c', --framework='unknown'.") - .And.HaveStdErrContaining("6 template(s) partially matched, but failed on --framework='unknown'.") + .And.HaveStdErrContaining("5 template(s) partially matched, but failed on --framework='unknown'.") .And.HaveStdErrContaining($"To search for the templates on NuGet.org, run:{Environment.NewLine} dotnet new3 c --search"); } @@ -528,7 +519,6 @@ public void CannotListTemplatesForInvalidFilters() .And.HaveStdOutMatching("Template Name\\s+Short Name\\s+Language\\s+Tags") .And.HaveStdOutMatching("Console Application\\s+console\\s+\\[C#\\],F#,VB\\s+Common/Console") .And.HaveStdOutMatching("Class Library\\s+classlib\\s+\\[C#\\],F#,VB\\s+Common/Library") - .And.HaveStdOutMatching("Simple Console Application\\s+app\\s+\\[C#\\]\\s+Common/Console") .And.HaveStdOutMatching("NuGet Config\\s+nugetconfig\\s+Config"); new DotnetNewCommand(_log, "--list", "--language", "unknown", "--framework", "unknown") @@ -536,7 +526,7 @@ public void CannotListTemplatesForInvalidFilters() .Execute() .Should().Fail() .And.HaveStdErrContaining("No templates found matching: language='unknown'.") - .And.HaveStdErrContaining("9 template(s) partially matched, but failed on language='unknown'.") + .And.HaveStdErrContaining("8 template(s) partially matched, but failed on language='unknown'.") .And.HaveStdErrContaining($"To search for the templates on NuGet.org, run:{Environment.NewLine} dotnet new3 --search"); new DotnetNewCommand(_log, "c", "--list", "--language", "unknown", "--framework", "unknown") @@ -544,7 +534,7 @@ public void CannotListTemplatesForInvalidFilters() .Execute() .Should().Fail() .And.HaveStdErrContaining("No templates found matching: 'c', language='unknown'.") - .And.HaveStdErrContaining("6 template(s) partially matched, but failed on language='unknown'.") + .And.HaveStdErrContaining("5 template(s) partially matched, but failed on language='unknown'.") .And.HaveStdErrContaining($"To search for the templates on NuGet.org, run:{Environment.NewLine} dotnet new3 c --search"); } } From 456a9c2eba5ce68f623035c77ab10da2f57c05a3 Mon Sep 17 00:00:00 2001 From: Vlada Shubina Date: Tue, 13 Jul 2021 13:57:12 +0300 Subject: [PATCH 02/14] removed using System; for net6.0 classlib and console templates --- .../content/ClassLibrary-CSharp/Class1.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ClassLibrary-CSharp/Class1.cs b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ClassLibrary-CSharp/Class1.cs index 72abb3efe5a..a6325f3fb1b 100644 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ClassLibrary-CSharp/Class1.cs +++ b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ClassLibrary-CSharp/Class1.cs @@ -1,6 +1,4 @@ -using System; - -namespace Company.ClassLibrary1 +namespace Company.ClassLibrary1 { public class Class1 { From 6875aa558fcf143a08b4bb25398bdd3418895d8a Mon Sep 17 00:00:00 2001 From: Vlada Shubina Date: Tue, 13 Jul 2021 14:19:35 +0300 Subject: [PATCH 03/14] added tests for different language versions --- .../CommonTemplatesTests.cs | 33 +++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/test/dotnet-new3.UnitTests/CommonTemplatesTests.cs b/test/dotnet-new3.UnitTests/CommonTemplatesTests.cs index 2ca687f016b..88132affd06 100644 --- a/test/dotnet-new3.UnitTests/CommonTemplatesTests.cs +++ b/test/dotnet-new3.UnitTests/CommonTemplatesTests.cs @@ -65,7 +65,23 @@ public CommonTemplatesTests(SharedHomeDirectory fixture, ITestOutputHelper log) [InlineData("Class Library", "classlib", "C#", "netstandard2.0")] [InlineData("Class Library", "classlib", "VB", "netstandard2.0")] [InlineData("Class Library", "classlib", "F#", "netstandard2.0")] - public void AllCommonProjectsCreateRestoreAndBuild(string expectedTemplateName, string templateShortName, string? language = null, string? framework = null) + + [InlineData("Class Library", "classlib", "C#", "net6.0", "10.0")] + [InlineData("Class Library", "classlib", "C#", "net6.0", "9.0", Skip = "https://github.com/dotnet/templating/issues/3449")] + [InlineData("Class Library", "classlib", "C#", "net6.0", "8.0", Skip = "https://github.com/dotnet/templating/issues/3449")] + [InlineData("Class Library", "classlib", "C#", "net6.0", "7.3", Skip = "https://github.com/dotnet/templating/issues/3449")] + [InlineData("Class Library", "classlib", "C#", "net6.0", "7.2", Skip = "https://github.com/dotnet/templating/issues/3449")] + [InlineData("Class Library", "classlib", "C#", "net6.0", "7.1", Skip = "https://github.com/dotnet/templating/issues/3449")] + [InlineData("Class Library", "classlib", "C#", "net6.0", "7", Skip = "https://github.com/dotnet/templating/issues/3449")] + + [InlineData("Console Application", "console", "C#", "net6.0", "10.0")] + [InlineData("Console Application", "console", "C#", "net6.0", "9.0", Skip = "https://github.com/dotnet/templating/issues/3449")] + [InlineData("Console Application", "console", "C#", "net6.0", "8.0", Skip = "https://github.com/dotnet/templating/issues/3449")] + [InlineData("Console Application", "console", "C#", "net6.0", "7.3", Skip = "https://github.com/dotnet/templating/issues/3449")] + [InlineData("Console Application", "console", "C#", "net6.0", "7.2", Skip = "https://github.com/dotnet/templating/issues/3449")] + [InlineData("Console Application", "console", "C#", "net6.0", "7.1", Skip = "https://github.com/dotnet/templating/issues/3449")] + [InlineData("Console Application", "console", "C#", "net6.0", "7", Skip = "https://github.com/dotnet/templating/issues/3449")] + public void AllCommonProjectsCreateRestoreAndBuild(string expectedTemplateName, string templateShortName, string? language = null, string? framework = null, string? langVersion = null) { string workingDir = TestUtils.CreateTemporaryFolder(); string workingDirName = Path.GetFileName(workingDir); @@ -94,6 +110,11 @@ public void AllCommonProjectsCreateRestoreAndBuild(string expectedTemplateName, args.Add("--framework"); args.Add(framework); } + if (!string.IsNullOrWhiteSpace(langVersion)) + { + args.Add("--langVersion"); + args.Add(langVersion); + } new DotnetNewCommand(_log, args.ToArray()) .WithCustomHive(_fixture.HomeDirectory) @@ -230,6 +251,9 @@ public void AllCommonItemsCreate(string expectedTemplateName, string templateSho [InlineData("Nullable", null, "Console Application", "console", null, "net5.0")] [InlineData("Nullable", null, "Console Application", "console", null, "netcoreapp3.1")] [InlineData("Nullable", null, "Console Application", "console", null, "netcoreapp2.1")] + [InlineData("Nullable", "enable", "Console Application", "console", null, null, "9.0")] + [InlineData("Nullable", "enable", "Console Application", "console", null, null, "8.0")] + [InlineData("Nullable", "enable", "Console Application", "console", null, null, "7.3")] [InlineData("Nullable", null, "Console Application", "console", "F#", null)] [InlineData("CheckForOverflowUnderflow", null, "Console Application", "console", "F#", null)] @@ -262,7 +286,7 @@ public void AllCommonItemsCreate(string expectedTemplateName, string templateSho [InlineData("TargetFramework", "net6.0", "Class Library", "classlib", "VB", null)] [InlineData("Nullable", null, "Class Library", "classlib", "VB", "netstandard2.0")] - public void SetPropertiesByDefault(string propertyName, string? propertyValue, string expectedTemplateName, string templateShortName, string? language, string? framework) + public void SetPropertiesByDefault(string propertyName, string? propertyValue, string expectedTemplateName, string templateShortName, string? language, string? framework, string? langVersion = null) { string workingDir = TestUtils.CreateTemporaryFolder(); List args = new List() { templateShortName, "--no-restore" }; @@ -276,6 +300,11 @@ public void SetPropertiesByDefault(string propertyName, string? propertyValue, s args.Add("--framework"); args.Add(framework); } + if (!string.IsNullOrWhiteSpace(langVersion)) + { + args.Add("--langVersion"); + args.Add(langVersion); + } new DotnetNewCommand(_log, args.ToArray()) .WithCustomHive(_fixture.HomeDirectory) From 3b32fe6103b551f018912044779f4a7ec27c1eb1 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Wed, 14 Jul 2021 17:31:48 +0000 Subject: [PATCH 04/14] Update dependencies from https://github.com/dotnet/source-build build 20210713.1 (#3452) [main] Update dependencies from dotnet/source-build --- eng/Version.Details.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 8dc612676ac..77c3c3c7403 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,9 +1,9 @@ - + https://github.com/dotnet/source-build - 7d2820d980ed899d53fdbbeeede471a1e34ea8bd + ef9facdeefd5381d7319b25469e9fd5f1250d1f4 From 947126735ed4315050d4d996fd88cf5ab6c3555c Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Wed, 14 Jul 2021 17:33:39 +0000 Subject: [PATCH 05/14] Update dependencies from https://github.com/dotnet/arcade build 20210713.2 (#3451) [main] Update dependencies from dotnet/arcade --- eng/Version.Details.xml | 4 ++-- eng/common/cross/build-rootfs.sh | 6 +++++- global.json | 2 +- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 77c3c3c7403..cccec64c3e8 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -49,9 +49,9 @@ - + https://github.com/dotnet/arcade - 55262f114b0c1b82f0b081bca0d919b657ba24c5 + 1b053babb8a542e3ab20f93b3d0aedc732b7e0c7 diff --git a/eng/common/cross/build-rootfs.sh b/eng/common/cross/build-rootfs.sh index 591d8666a84..735a4c82838 100755 --- a/eng/common/cross/build-rootfs.sh +++ b/eng/common/cross/build-rootfs.sh @@ -33,7 +33,6 @@ __AlpinePackages="alpine-base" __AlpinePackages+=" build-base" __AlpinePackages+=" linux-headers" __AlpinePackagesEdgeCommunity=" lldb-dev" -__AlpinePackagesEdgeMain=" llvm10-libs" __AlpinePackagesEdgeMain+=" python3" __AlpinePackagesEdgeMain+=" libedit" @@ -115,6 +114,8 @@ while :; do __UbuntuArch=s390x __UbuntuRepo="http://ports.ubuntu.com/ubuntu-ports/" __UbuntuPackages=$(echo ${__UbuntuPackages} | sed 's/ libunwind8-dev//') + __UbuntuPackages=$(echo ${__UbuntuPackages} | sed 's/ libomp-dev//') + __UbuntuPackages=$(echo ${__UbuntuPackages} | sed 's/ libomp5//') unset __LLDB_Package ;; x86) @@ -191,6 +192,8 @@ while :; do __CodeName=alpine __UbuntuRepo= __AlpineVersion=3.9 + __AlpinePackagesEdgeMain+=" llvm11-libs" + __AlpinePackagesEdgeMain+=" clang-libs" ;; alpine3.13) __CodeName=alpine @@ -201,6 +204,7 @@ while :; do __AlpinePackagesEdgeCommunity= __AlpinePackages+=$__AlpinePackagesEdgeMain __AlpinePackagesEdgeMain= + __AlpinePackages+=" llvm10-libs" ;; freebsd11) __FreeBSDBase="11.3-RELEASE" diff --git a/global.json b/global.json index 4cebc9516ba..f365d19335c 100644 --- a/global.json +++ b/global.json @@ -8,6 +8,6 @@ } }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "6.0.0-beta.21359.3" + "Microsoft.DotNet.Arcade.Sdk": "6.0.0-beta.21363.2" } } From da9bc9c77b10f421d25cc779169b161fff920f76 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Wed, 14 Jul 2021 17:34:34 +0000 Subject: [PATCH 06/14] Update dependencies from https://github.com/dotnet/runtime build 20210713.9 (#3453) [main] Update dependencies from dotnet/runtime --- eng/Version.Details.xml | 16 ++++++++-------- eng/Versions.props | 8 ++++---- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index cccec64c3e8..72662f522fa 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -11,25 +11,25 @@ def2e2c6dc5064319250e2868a041a3dc07f9579 - + https://github.com/dotnet/runtime - 92ed4005e70b37d6d0093d3e68da51f3749f15be + 3150bfa50618cc98f546ffae7652b12c17cea702 https://github.com/dotnet/command-line-api a2ea4b1defbbc344c9dba1288b19ecc90256aff3 - + https://github.com/dotnet/runtime - 92ed4005e70b37d6d0093d3e68da51f3749f15be + 3150bfa50618cc98f546ffae7652b12c17cea702 - + https://github.com/dotnet/runtime - 92ed4005e70b37d6d0093d3e68da51f3749f15be + 3150bfa50618cc98f546ffae7652b12c17cea702 - + https://github.com/dotnet/runtime - 92ed4005e70b37d6d0093d3e68da51f3749f15be + 3150bfa50618cc98f546ffae7652b12c17cea702 https://github.com/nuget/nuget.client diff --git a/eng/Versions.props b/eng/Versions.props index fbd2e3d6bec..5459fe18b7b 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -19,10 +19,10 @@ 6.0.0-preview.2.129 6.0.0-preview.2.129 - 6.0.0-preview.7.21362.15 - 6.0.0-preview.7.21362.15 - 6.0.0-preview.7.21362.15 - 6.0.0-preview.7.21362.15 + 6.0.0-preview.7.21363.9 + 6.0.0-preview.7.21363.9 + 6.0.0-preview.7.21363.9 + 6.0.0-preview.7.21363.9 1.0.0-preview.19208.1 From e892653cccde82efdc6deb97d16eea521b901785 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 15 Jul 2021 14:36:23 +0000 Subject: [PATCH 07/14] Update dependencies from https://github.com/dotnet/arcade build 20210714.3 (#3462) [main] Update dependencies from dotnet/arcade --- eng/Version.Details.xml | 4 +- eng/common/sdl/configure-sdl-tool.ps1 | 109 +++++++++++++++++++ eng/common/sdl/execute-all-sdl-tools.ps1 | 71 ++++++++++-- eng/common/sdl/extract-artifact-archives.ps1 | 63 +++++++++++ eng/common/sdl/run-sdl.ps1 | 50 +++------ eng/common/templates/job/execute-sdl.yml | 108 ++++++++++++++++-- eng/common/tools.ps1 | 51 +++++++++ global.json | 2 +- 8 files changed, 398 insertions(+), 60 deletions(-) create mode 100644 eng/common/sdl/configure-sdl-tool.ps1 create mode 100644 eng/common/sdl/extract-artifact-archives.ps1 diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 72662f522fa..83e8571cff1 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -49,9 +49,9 @@ - + https://github.com/dotnet/arcade - 1b053babb8a542e3ab20f93b3d0aedc732b7e0c7 + 6a8491b61e0c243cbb6a7ff4966b48e6d1e075b1 diff --git a/eng/common/sdl/configure-sdl-tool.ps1 b/eng/common/sdl/configure-sdl-tool.ps1 new file mode 100644 index 00000000000..4999c307088 --- /dev/null +++ b/eng/common/sdl/configure-sdl-tool.ps1 @@ -0,0 +1,109 @@ +Param( + [string] $GuardianCliLocation, + [string] $WorkingDirectory, + [string] $TargetDirectory, + [string] $GdnFolder, + # The list of Guardian tools to configure. For each object in the array: + # - If the item is a [hashtable], it must contain these entries: + # - Name = The tool name as Guardian knows it. + # - Scenario = (Optional) Scenario-specific name for this configuration entry. It must be unique + # among all tool entries with the same Name. + # - Args = (Optional) Array of Guardian tool configuration args, like '@("Target > C:\temp")' + # - If the item is a [string] $v, it is treated as '@{ Name="$v" }' + [object[]] $ToolsList, + [string] $GuardianLoggerLevel='Standard', + # Optional: Additional params to add to any tool using CredScan. + [string[]] $CrScanAdditionalRunConfigParams, + # Optional: Additional params to add to any tool using PoliCheck. + [string[]] $PoliCheckAdditionalRunConfigParams +) + +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version 2.0 +$disableConfigureToolsetImport = $true +$global:LASTEXITCODE = 0 + +try { + # `tools.ps1` checks $ci to perform some actions. Since the SDL + # scripts don't necessarily execute in the same agent that run the + # build.ps1/sh script this variable isn't automatically set. + $ci = $true + . $PSScriptRoot\..\tools.ps1 + + # Normalize tools list: all in [hashtable] form with defined values for each key. + $ToolsList = $ToolsList | + ForEach-Object { + if ($_ -is [string]) { + $_ = @{ Name = $_ } + } + + if (-not ($_['Scenario'])) { $_.Scenario = "" } + if (-not ($_['Args'])) { $_.Args = @() } + $_ + } + + Write-Host "List of tools to configure:" + $ToolsList | ForEach-Object { $_ | Out-String | Write-Host } + + # We store config files in the r directory of .gdn + $gdnConfigPath = Join-Path $GdnFolder 'r' + $ValidPath = Test-Path $GuardianCliLocation + + if ($ValidPath -eq $False) + { + Write-PipelineTelemetryError -Force -Category 'Sdl' -Message "Invalid Guardian CLI Location." + ExitWithExitCode 1 + } + + foreach ($tool in $ToolsList) { + # Put together the name and scenario to make a unique key. + $toolConfigName = $tool.Name + if ($tool.Scenario) { + $toolConfigName += "_" + $tool.Scenario + } + + Write-Host "=== Configuring $toolConfigName..." + + $gdnConfigFile = Join-Path $gdnConfigPath "$toolConfigName-configure.gdnconfig" + + # For some tools, add default and automatic args. + if ($tool.Name -eq 'credscan') { + if ($targetDirectory) { + $tool.Args += "TargetDirectory < $TargetDirectory" + } + $tool.Args += "OutputType < pre" + $tool.Args += $CrScanAdditionalRunConfigParams + } elseif ($tool.Name -eq 'policheck') { + if ($targetDirectory) { + $tool.Args += "Target < $TargetDirectory" + } + $tool.Args += $PoliCheckAdditionalRunConfigParams + } + + # Create variable pointing to the args array directly so we can use splat syntax later. + $toolArgs = $tool.Args + + # Configure the tool. If args array is provided or the current tool has some default arguments + # defined, add "--args" and splat each element on the end. Arg format is "{Arg id} < {Value}", + # one per parameter. Doc page for "guardian configure": + # https://dev.azure.com/securitytools/SecurityIntegration/_wiki/wikis/Guardian/1395/configure + Exec-BlockVerbosely { + & $GuardianCliLocation configure ` + --working-directory $WorkingDirectory ` + --tool $tool.Name ` + --output-path $gdnConfigFile ` + --logger-level $GuardianLoggerLevel ` + --noninteractive ` + --force ` + $(if ($toolArgs) { "--args" }) @toolArgs + Exit-IfNZEC "Sdl" + } + + Write-Host "Created '$toolConfigName' configuration file: $gdnConfigFile" + } +} +catch { + Write-Host $_.ScriptStackTrace + Write-PipelineTelemetryError -Force -Category 'Sdl' -Message $_ + ExitWithExitCode 1 +} diff --git a/eng/common/sdl/execute-all-sdl-tools.ps1 b/eng/common/sdl/execute-all-sdl-tools.ps1 index 2881a56083c..1157151f486 100644 --- a/eng/common/sdl/execute-all-sdl-tools.ps1 +++ b/eng/common/sdl/execute-all-sdl-tools.ps1 @@ -7,8 +7,17 @@ Param( [string] $SourceDirectory=$env:BUILD_SOURCESDIRECTORY, # Required: the directory where source files are located [string] $ArtifactsDirectory = (Join-Path $env:BUILD_ARTIFACTSTAGINGDIRECTORY ('artifacts')), # Required: the directory where build artifacts are located [string] $AzureDevOpsAccessToken, # Required: access token for dnceng; should be provided via KeyVault - [string[]] $SourceToolsList, # Optional: list of SDL tools to run on source code - [string[]] $ArtifactToolsList, # Optional: list of SDL tools to run on built artifacts + + # Optional: list of SDL tools to run on source code. See 'configure-sdl-tool.ps1' for tools list + # format. + [object[]] $SourceToolsList, + # Optional: list of SDL tools to run on built artifacts. See 'configure-sdl-tool.ps1' for tools + # list format. + [object[]] $ArtifactToolsList, + # Optional: list of SDL tools to run without automatically specifying a target directory. See + # 'configure-sdl-tool.ps1' for tools list format. + [object[]] $CustomToolsList, + [bool] $TsaPublish=$False, # Optional: true will publish results to TSA; only set to true after onboarding to TSA; TSA is the automated framework used to upload test results as bugs. [string] $TsaBranchName=$env:BUILD_SOURCEBRANCH, # Optional: required for TSA publish; defaults to $(Build.SourceBranchName); TSA is the automated framework used to upload test results as bugs. [string] $TsaRepositoryName=$env:BUILD_REPOSITORY_NAME, # Optional: TSA repository name; will be generated automatically if not submitted; TSA is the automated framework used to upload test results as bugs. @@ -63,13 +72,16 @@ try { ExitWithExitCode 1 } - & $(Join-Path $PSScriptRoot 'init-sdl.ps1') -GuardianCliLocation $guardianCliLocation -Repository $RepoName -BranchName $BranchName -WorkingDirectory $workingDirectory -AzureDevOpsAccessToken $AzureDevOpsAccessToken -GuardianLoggerLevel $GuardianLoggerLevel + Exec-BlockVerbosely { + & $(Join-Path $PSScriptRoot 'init-sdl.ps1') -GuardianCliLocation $guardianCliLocation -Repository $RepoName -BranchName $BranchName -WorkingDirectory $workingDirectory -AzureDevOpsAccessToken $AzureDevOpsAccessToken -GuardianLoggerLevel $GuardianLoggerLevel + } $gdnFolder = Join-Path $workingDirectory '.gdn' if ($TsaOnboard) { if ($TsaCodebaseName -and $TsaNotificationEmail -and $TsaCodebaseAdmin -and $TsaBugAreaPath) { - Write-Host "$guardianCliLocation tsa-onboard --codebase-name `"$TsaCodebaseName`" --notification-alias `"$TsaNotificationEmail`" --codebase-admin `"$TsaCodebaseAdmin`" --instance-url `"$TsaInstanceUrl`" --project-name `"$TsaProjectName`" --area-path `"$TsaBugAreaPath`" --iteration-path `"$TsaIterationPath`" --working-directory $workingDirectory --logger-level $GuardianLoggerLevel" - & $guardianCliLocation tsa-onboard --codebase-name "$TsaCodebaseName" --notification-alias "$TsaNotificationEmail" --codebase-admin "$TsaCodebaseAdmin" --instance-url "$TsaInstanceUrl" --project-name "$TsaProjectName" --area-path "$TsaBugAreaPath" --iteration-path "$TsaIterationPath" --working-directory $workingDirectory --logger-level $GuardianLoggerLevel + Exec-BlockVerbosely { + & $guardianCliLocation tsa-onboard --codebase-name "$TsaCodebaseName" --notification-alias "$TsaNotificationEmail" --codebase-admin "$TsaCodebaseAdmin" --instance-url "$TsaInstanceUrl" --project-name "$TsaProjectName" --area-path "$TsaBugAreaPath" --iteration-path "$TsaIterationPath" --working-directory $workingDirectory --logger-level $GuardianLoggerLevel + } if ($LASTEXITCODE -ne 0) { Write-PipelineTelemetryError -Force -Category 'Sdl' -Message "Guardian tsa-onboard failed with exit code $LASTEXITCODE." ExitWithExitCode $LASTEXITCODE @@ -80,11 +92,41 @@ try { } } - if ($ArtifactToolsList -and $ArtifactToolsList.Count -gt 0) { - & $(Join-Path $PSScriptRoot 'run-sdl.ps1') -GuardianCliLocation $guardianCliLocation -WorkingDirectory $workingDirectory -TargetDirectory $ArtifactsDirectory -GdnFolder $gdnFolder -ToolsList $ArtifactToolsList -AzureDevOpsAccessToken $AzureDevOpsAccessToken -UpdateBaseline $UpdateBaseline -GuardianLoggerLevel $GuardianLoggerLevel -CrScanAdditionalRunConfigParams $CrScanAdditionalRunConfigParams -PoliCheckAdditionalRunConfigParams $PoliCheckAdditionalRunConfigParams + # Configure a list of tools with a default target directory. Populates the ".gdn/r" directory. + function Configure-ToolsList([object[]] $tools, [string] $targetDirectory) { + if ($tools -and $tools.Count -gt 0) { + Exec-BlockVerbosely { + & $(Join-Path $PSScriptRoot 'configure-sdl-tool.ps1') ` + -GuardianCliLocation $guardianCliLocation ` + -WorkingDirectory $workingDirectory ` + -TargetDirectory $targetDirectory ` + -GdnFolder $gdnFolder ` + -ToolsList $tools ` + -AzureDevOpsAccessToken $AzureDevOpsAccessToken ` + -GuardianLoggerLevel $GuardianLoggerLevel ` + -CrScanAdditionalRunConfigParams $CrScanAdditionalRunConfigParams ` + -PoliCheckAdditionalRunConfigParams $PoliCheckAdditionalRunConfigParams + if ($BreakOnFailure) { + Exit-IfNZEC "Sdl" + } + } + } } - if ($SourceToolsList -and $SourceToolsList.Count -gt 0) { - & $(Join-Path $PSScriptRoot 'run-sdl.ps1') -GuardianCliLocation $guardianCliLocation -WorkingDirectory $workingDirectory -TargetDirectory $SourceDirectory -GdnFolder $gdnFolder -ToolsList $SourceToolsList -AzureDevOpsAccessToken $AzureDevOpsAccessToken -UpdateBaseline $UpdateBaseline -GuardianLoggerLevel $GuardianLoggerLevel -CrScanAdditionalRunConfigParams $CrScanAdditionalRunConfigParams -PoliCheckAdditionalRunConfigParams $PoliCheckAdditionalRunConfigParams + + # Configure Artifact and Source tools with default Target directories. + Configure-ToolsList $ArtifactToolsList $ArtifactsDirectory + Configure-ToolsList $SourceToolsList $SourceDirectory + # Configure custom tools with no default Target directory. + Configure-ToolsList $CustomToolsList $null + + # At this point, all tools are configured in the ".gdn" directory. Run them all in a single call. + # (If we used "run" multiple times, each run would overwrite data from earlier runs.) + Exec-BlockVerbosely { + & $(Join-Path $PSScriptRoot 'run-sdl.ps1') ` + -GuardianCliLocation $guardianCliLocation ` + -WorkingDirectory $workingDirectory ` + -UpdateBaseline $UpdateBaseline ` + -GdnFolder $gdnFolder } if ($TsaPublish) { @@ -92,8 +134,9 @@ try { if (-not $TsaRepositoryName) { $TsaRepositoryName = "$($Repository)-$($BranchName)" } - Write-Host "$guardianCliLocation tsa-publish --all-tools --repository-name `"$TsaRepositoryName`" --branch-name `"$TsaBranchName`" --build-number `"$BuildNumber`" --codebase-name `"$TsaCodebaseName`" --notification-alias `"$TsaNotificationEmail`" --codebase-admin `"$TsaCodebaseAdmin`" --instance-url `"$TsaInstanceUrl`" --project-name `"$TsaProjectName`" --area-path `"$TsaBugAreaPath`" --iteration-path `"$TsaIterationPath`" --working-directory $workingDirectory --logger-level $GuardianLoggerLevel" - & $guardianCliLocation tsa-publish --all-tools --repository-name "$TsaRepositoryName" --branch-name "$TsaBranchName" --build-number "$BuildNumber" --onboard $True --codebase-name "$TsaCodebaseName" --notification-alias "$TsaNotificationEmail" --codebase-admin "$TsaCodebaseAdmin" --instance-url "$TsaInstanceUrl" --project-name "$TsaProjectName" --area-path "$TsaBugAreaPath" --iteration-path "$TsaIterationPath" --working-directory $workingDirectory --logger-level $GuardianLoggerLevel + Exec-BlockVerbosely { + & $guardianCliLocation tsa-publish --all-tools --repository-name "$TsaRepositoryName" --branch-name "$TsaBranchName" --build-number "$BuildNumber" --onboard $True --codebase-name "$TsaCodebaseName" --notification-alias "$TsaNotificationEmail" --codebase-admin "$TsaCodebaseAdmin" --instance-url "$TsaInstanceUrl" --project-name "$TsaProjectName" --area-path "$TsaBugAreaPath" --iteration-path "$TsaIterationPath" --working-directory $workingDirectory --logger-level $GuardianLoggerLevel + } if ($LASTEXITCODE -ne 0) { Write-PipelineTelemetryError -Force -Category 'Sdl' -Message "Guardian tsa-publish failed with exit code $LASTEXITCODE." ExitWithExitCode $LASTEXITCODE @@ -106,7 +149,11 @@ try { if ($BreakOnFailure) { Write-Host "Failing the build in case of breaking results..." - & $guardianCliLocation break + Exec-BlockVerbosely { + & $guardianCliLocation break --working-directory $workingDirectory --logger-level $GuardianLoggerLevel + } + } else { + Write-Host "Letting the build pass even if there were breaking results..." } } catch { diff --git a/eng/common/sdl/extract-artifact-archives.ps1 b/eng/common/sdl/extract-artifact-archives.ps1 new file mode 100644 index 00000000000..68da4fbf257 --- /dev/null +++ b/eng/common/sdl/extract-artifact-archives.ps1 @@ -0,0 +1,63 @@ +# This script looks for each archive file in a directory and extracts it into the target directory. +# For example, the file "$InputPath/bin.tar.gz" extracts to "$ExtractPath/bin.tar.gz.extracted/**". +# Uses the "tar" utility added to Windows 10 / Windows 2019 that supports tar.gz and zip. +param( + # Full path to directory where archives are stored. + [Parameter(Mandatory=$true)][string] $InputPath, + # Full path to directory to extract archives into. May be the same as $InputPath. + [Parameter(Mandatory=$true)][string] $ExtractPath +) + +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version 2.0 + +$disableConfigureToolsetImport = $true + +try { + # `tools.ps1` checks $ci to perform some actions. Since the SDL + # scripts don't necessarily execute in the same agent that run the + # build.ps1/sh script this variable isn't automatically set. + $ci = $true + . $PSScriptRoot\..\tools.ps1 + + Measure-Command { + $jobs = @() + + # Find archive files for non-Windows and Windows builds. + $archiveFiles = @( + Get-ChildItem (Join-Path $InputPath "*.tar.gz") + Get-ChildItem (Join-Path $InputPath "*.zip") + ) + + foreach ($targzFile in $archiveFiles) { + $jobs += Start-Job -ScriptBlock { + $file = $using:targzFile + $fileName = [System.IO.Path]::GetFileName($file) + $extractDir = Join-Path $using:ExtractPath "$fileName.extracted" + + New-Item $extractDir -ItemType Directory -Force | Out-Null + + Write-Host "Extracting '$file' to '$extractDir'..." + + # Pipe errors to stdout to prevent PowerShell detecting them and quitting the job early. + # This type of quit skips the catch, so we wouldn't be able to tell which file triggered the + # error. Save output so it can be stored in the exception string along with context. + $output = tar -xf $file -C $extractDir 2>&1 + # Handle NZEC manually rather than using Exit-IfNZEC: we are in a background job, so we + # don't have access to the outer scope. + if ($LASTEXITCODE -ne 0) { + throw "Error extracting '$file': non-zero exit code ($LASTEXITCODE). Output: '$output'" + } + + Write-Host "Extracted to $extractDir" + } + } + + Receive-Job $jobs -Wait + } +} +catch { + Write-Host $_ + Write-PipelineTelemetryError -Force -Category 'Sdl' -Message $_ + ExitWithExitCode 1 +} diff --git a/eng/common/sdl/run-sdl.ps1 b/eng/common/sdl/run-sdl.ps1 index 3d9c87aba6a..2eac8c78f10 100644 --- a/eng/common/sdl/run-sdl.ps1 +++ b/eng/common/sdl/run-sdl.ps1 @@ -1,13 +1,9 @@ Param( [string] $GuardianCliLocation, [string] $WorkingDirectory, - [string] $TargetDirectory, [string] $GdnFolder, - [string[]] $ToolsList, [string] $UpdateBaseline, - [string] $GuardianLoggerLevel='Standard', - [string[]] $CrScanAdditionalRunConfigParams, - [string[]] $PoliCheckAdditionalRunConfigParams + [string] $GuardianLoggerLevel='Standard' ) $ErrorActionPreference = 'Stop' @@ -23,7 +19,6 @@ try { . $PSScriptRoot\..\tools.ps1 # We store config files in the r directory of .gdn - Write-Host $ToolsList $gdnConfigPath = Join-Path $GdnFolder 'r' $ValidPath = Test-Path $GuardianCliLocation @@ -33,37 +28,18 @@ try { ExitWithExitCode 1 } - $configParam = @('--config') - - foreach ($tool in $ToolsList) { - $gdnConfigFile = Join-Path $gdnConfigPath "$tool-configure.gdnconfig" - Write-Host $tool - # We have to manually configure tools that run on source to look at the source directory only - if ($tool -eq 'credscan') { - Write-Host "$GuardianCliLocation configure --working-directory $WorkingDirectory --tool $tool --output-path $gdnConfigFile --logger-level $GuardianLoggerLevel --noninteractive --force --args `" TargetDirectory < $TargetDirectory `" `" OutputType < pre `" $(If ($CrScanAdditionalRunConfigParams) {$CrScanAdditionalRunConfigParams})" - & $GuardianCliLocation configure --working-directory $WorkingDirectory --tool $tool --output-path $gdnConfigFile --logger-level $GuardianLoggerLevel --noninteractive --force --args " TargetDirectory < $TargetDirectory " "OutputType < pre" $(If ($CrScanAdditionalRunConfigParams) {$CrScanAdditionalRunConfigParams}) - if ($LASTEXITCODE -ne 0) { - Write-PipelineTelemetryError -Force -Category 'Sdl' -Message "Guardian configure for $tool failed with exit code $LASTEXITCODE." - ExitWithExitCode $LASTEXITCODE - } - } - if ($tool -eq 'policheck') { - Write-Host "$GuardianCliLocation configure --working-directory $WorkingDirectory --tool $tool --output-path $gdnConfigFile --logger-level $GuardianLoggerLevel --noninteractive --force --args `" Target < $TargetDirectory `" $(If ($PoliCheckAdditionalRunConfigParams) {$PoliCheckAdditionalRunConfigParams})" - & $GuardianCliLocation configure --working-directory $WorkingDirectory --tool $tool --output-path $gdnConfigFile --logger-level $GuardianLoggerLevel --noninteractive --force --args " Target < $TargetDirectory " $(If ($PoliCheckAdditionalRunConfigParams) {$PoliCheckAdditionalRunConfigParams}) - if ($LASTEXITCODE -ne 0) { - Write-PipelineTelemetryError -Force -Category 'Sdl' -Message "Guardian configure for $tool failed with exit code $LASTEXITCODE." - ExitWithExitCode $LASTEXITCODE - } - } - - $configParam+=$gdnConfigFile - } - - Write-Host "$GuardianCliLocation run --working-directory $WorkingDirectory --baseline mainbaseline --update-baseline $UpdateBaseline --logger-level $GuardianLoggerLevel $configParam" - & $GuardianCliLocation run --working-directory $WorkingDirectory --tool $tool --baseline mainbaseline --update-baseline $UpdateBaseline --logger-level $GuardianLoggerLevel $configParam - if ($LASTEXITCODE -ne 0) { - Write-PipelineTelemetryError -Force -Category 'Sdl' -Message "Guardian run for $ToolsList using $configParam failed with exit code $LASTEXITCODE." - ExitWithExitCode $LASTEXITCODE + $gdnConfigFiles = Get-ChildItem $gdnConfigPath -Recurse -Include '*.gdnconfig' + Write-Host "Discovered Guardian config files:" + $gdnConfigFiles | Out-String | Write-Host + + Exec-BlockVerbosely { + & $GuardianCliLocation run ` + --working-directory $WorkingDirectory ` + --baseline mainbaseline ` + --update-baseline $UpdateBaseline ` + --logger-level $GuardianLoggerLevel ` + --config @gdnConfigFiles + Exit-IfNZEC "Sdl" } } catch { diff --git a/eng/common/templates/job/execute-sdl.yml b/eng/common/templates/job/execute-sdl.yml index 4a32181fd8f..69eb67849d7 100644 --- a/eng/common/templates/job/execute-sdl.yml +++ b/eng/common/templates/job/execute-sdl.yml @@ -2,17 +2,41 @@ parameters: enable: 'false' # Whether the SDL validation job should execute or not overrideParameters: '' # Optional: to override values for parameters. additionalParameters: '' # Optional: parameters that need user specific values eg: '-SourceToolsList @("abc","def") -ArtifactToolsList @("ghi","jkl")' + # Optional: if specified, restore and use this version of Guardian instead of the default. + overrideGuardianVersion: '' + # Optional: if true, publish the '.gdn' folder as a pipeline artifact. This can help with in-depth + # diagnosis of problems with specific tool configurations. + publishGuardianDirectoryToPipeline: false + # The script to run to execute all SDL tools. Use this if you want to use a script to define SDL + # parameters rather than relying on YAML. It may be better to use a local script, because you can + # reproduce results locally without piecing together a command based on the YAML. + executeAllSdlToolsScript: 'eng/common/sdl/execute-all-sdl-tools.ps1' # There is some sort of bug (has been reported) in Azure DevOps where if this parameter is named # 'continueOnError', the parameter value is not correctly picked up. # This can also be remedied by the caller (post-build.yml) if it does not use a nested parameter sdlContinueOnError: false # optional: determines whether to continue the build if the step errors; - downloadArtifacts: true # optional: determines if the artifacts should be dowloaded + # optional: determines if build artifacts should be downloaded. + downloadArtifacts: true + # optional: determines if this job should search the directory of downloaded artifacts for + # 'tar.gz' and 'zip' archive files and extract them before running SDL validation tasks. + extractArchiveArtifacts: false dependsOn: '' # Optional: dependencies of the job artifactNames: '' # Optional: patterns supplied to DownloadBuildArtifacts # Usage: # artifactNames: # - 'BlobArtifacts' # - 'Artifacts_Windows_NT_Release' + # Optional: download a list of pipeline artifacts. 'downloadArtifacts' controls build artifacts, + # not pipeline artifacts, so doesn't affect the use of this parameter. + pipelineArtifactNames: [] + # Optional: location and ID of the AzDO build that the build/pipeline artifacts should be + # downloaded from. By default, uses runtime expressions to decide based on the variables set by + # the 'setupMaestroVars' dependency. Overriding this parameter is necessary if SDL tasks are + # running without Maestro++/BAR involved, or to download artifacts from a specific existing build + # to iterate quickly on SDL changes. + AzDOProjectName: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOProjectName'] ] + AzDOPipelineId: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOPipelineId'] ] + AzDOBuildId: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOBuildId'] ] jobs: - job: Run_SDL @@ -22,16 +46,29 @@ jobs: variables: - group: DotNet-VSTS-Bot - name: AzDOProjectName - value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOProjectName'] ] + value: ${{ parameters.AzDOProjectName }} - name: AzDOPipelineId - value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOPipelineId'] ] + value: ${{ parameters.AzDOPipelineId }} - name: AzDOBuildId - value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOBuildId'] ] + value: ${{ parameters.AzDOBuildId }} + # The Guardian version specified in 'eng/common/sdl/packages.config'. This value must be kept in + # sync with the packages.config file. + - name: DefaultGuardianVersion + value: 0.53.3 + - name: GuardianVersion + value: ${{ coalesce(parameters.overrideGuardianVersion, '$(DefaultGuardianVersion)') }} + - name: GuardianPackagesConfigFile + value: $(Build.SourcesDirectory)\eng\common\sdl\packages.config pool: - name: Hosted VS2017 + # To extract archives (.tar.gz, .zip), we need access to "tar", added in Windows 10/2019. + ${{ if eq(parameters.extractArchiveArtifacts, 'false') }}: + name: Hosted VS2017 + ${{ if ne(parameters.extractArchiveArtifacts, 'false') }}: + vmImage: windows-2019 steps: - checkout: self clean: true + - ${{ if ne(parameters.downloadArtifacts, 'false')}}: - ${{ if ne(parameters.artifactNames, '') }}: - ${{ each artifactName in parameters.artifactNames }}: @@ -59,16 +96,51 @@ jobs: itemPattern: "**" downloadPath: $(Build.ArtifactStagingDirectory)\artifacts checkDownloadedFiles: true + + - ${{ each artifactName in parameters.pipelineArtifactNames }}: + - task: DownloadPipelineArtifact@2 + displayName: Download Pipeline Artifacts + inputs: + buildType: specific + buildVersionToDownload: specific + project: $(AzDOProjectName) + pipeline: $(AzDOPipelineId) + buildId: $(AzDOBuildId) + artifactName: ${{ artifactName }} + downloadPath: $(Build.ArtifactStagingDirectory)\artifacts + checkDownloadedFiles: true + - powershell: eng/common/sdl/extract-artifact-packages.ps1 -InputPath $(Build.ArtifactStagingDirectory)\artifacts\BlobArtifacts -ExtractPath $(Build.ArtifactStagingDirectory)\artifacts\BlobArtifacts displayName: Extract Blob Artifacts continueOnError: ${{ parameters.sdlContinueOnError }} + - powershell: eng/common/sdl/extract-artifact-packages.ps1 -InputPath $(Build.ArtifactStagingDirectory)\artifacts\PackageArtifacts -ExtractPath $(Build.ArtifactStagingDirectory)\artifacts\PackageArtifacts displayName: Extract Package Artifacts continueOnError: ${{ parameters.sdlContinueOnError }} + + - ${{ if ne(parameters.extractArchiveArtifacts, 'false') }}: + - powershell: eng/common/sdl/extract-artifact-archives.ps1 + -InputPath $(Build.ArtifactStagingDirectory)\artifacts + -ExtractPath $(Build.ArtifactStagingDirectory)\artifacts + displayName: Extract Archive Artifacts + continueOnError: ${{ parameters.sdlContinueOnError }} + + - ${{ if ne(parameters.overrideGuardianVersion, '') }}: + - powershell: | + $content = Get-Content $(GuardianPackagesConfigFile) + + Write-Host "packages.config content was:`n$content" + + $content = $content.Replace('$(DefaultGuardianVersion)', '$(GuardianVersion)') + $content | Set-Content $(GuardianPackagesConfigFile) + + Write-Host "packages.config content updated to:`n$content" + displayName: Use overridden Guardian version ${{ parameters.overrideGuardianVersion }} + - task: NuGetToolInstaller@1 displayName: 'Install NuGet.exe' - task: NuGetCommand@2 @@ -79,15 +151,35 @@ jobs: nugetConfigPath: $(Build.SourcesDirectory)\eng\common\sdl\NuGet.config externalFeedCredentials: GuardianConnect restoreDirectory: $(Build.SourcesDirectory)\.packages + - ${{ if ne(parameters.overrideParameters, '') }}: - - powershell: eng/common/sdl/execute-all-sdl-tools.ps1 ${{ parameters.overrideParameters }} + - powershell: ${{ parameters.executeAllSdlToolsScript }} ${{ parameters.overrideParameters }} displayName: Execute SDL continueOnError: ${{ parameters.sdlContinueOnError }} - ${{ if eq(parameters.overrideParameters, '') }}: - - powershell: eng/common/sdl/execute-all-sdl-tools.ps1 - -GuardianPackageName Microsoft.Guardian.Cli.0.53.3 + - powershell: ${{ parameters.executeAllSdlToolsScript }} + -GuardianPackageName Microsoft.Guardian.Cli.$(GuardianVersion) -NugetPackageDirectory $(Build.SourcesDirectory)\.packages -AzureDevOpsAccessToken $(dn-bot-dotnet-build-rw-code-rw) ${{ parameters.additionalParameters }} displayName: Execute SDL continueOnError: ${{ parameters.sdlContinueOnError }} + + - ${{ if ne(parameters.publishGuardianDirectoryToPipeline, 'false') }}: + # We want to publish the Guardian results and configuration for easy diagnosis. However, the + # '.gdn' dir is a mix of configuration, results, extracted dependencies, and Guardian default + # tooling files. Some of these files are large and aren't useful during an investigation, so + # exclude them by simply deleting them before publishing. (As of writing, there is no documented + # way to selectively exclude a dir from the pipeline artifact publish task.) + - task: DeleteFiles@1 + displayName: Delete Guardian dependencies to avoid uploading + inputs: + SourceFolder: $(Agent.BuildDirectory)/.gdn + Contents: | + c + i + condition: succeededOrFailed() + - publish: $(Agent.BuildDirectory)/.gdn + artifact: GuardianConfiguration + displayName: Publish GuardianConfiguration + condition: succeededOrFailed() diff --git a/eng/common/tools.ps1 b/eng/common/tools.ps1 index 2df0909937d..5d526c74d51 100644 --- a/eng/common/tools.ps1 +++ b/eng/common/tools.ps1 @@ -106,6 +106,46 @@ function Exec-Process([string]$command, [string]$commandArgs) { } } +# Take the given block, print it, print what the block probably references from the current set of +# variables using low-effort string matching, then run the block. +# +# This is intended to replace the pattern of manually copy-pasting a command, wrapping it in quotes, +# and printing it using "Write-Host". The copy-paste method is more readable in build logs, but less +# maintainable and less reliable. It is easy to make a mistake and modify the command without +# properly updating the "Write-Host" line, resulting in misleading build logs. The probability of +# this mistake makes the pattern hard to trust when it shows up in build logs. Finding the bug in +# existing source code can also be difficult, because the strings are not aligned to each other and +# the line may be 300+ columns long. +# +# By removing the need to maintain two copies of the command, Exec-BlockVerbosely avoids the issues. +# +# In Bash (or any posix-like shell), "set -x" prints usable verbose output automatically. +# "Set-PSDebug" appears to be similar at first glance, but unfortunately, it isn't very useful: it +# doesn't print any info about the variables being used by the command, which is normally the +# interesting part to diagnose. +function Exec-BlockVerbosely([scriptblock] $block) { + Write-Host "--- Running script block:" + $blockString = $block.ToString().Trim() + Write-Host $blockString + + Write-Host "--- List of variables that might be used:" + # For each variable x in the environment, check the block for a reference to x via simple "$x" or + # "@x" syntax. This doesn't detect other ways to reference variables ("${x}" nor "$variable:x", + # among others). It only catches what this function was originally written for: simple + # command-line commands. + $variableTable = Get-Variable | + Where-Object { + $blockString.Contains("`$$($_.Name)") -or $blockString.Contains("@$($_.Name)") + } | + Format-Table -AutoSize -HideTableHeaders -Wrap | + Out-String + Write-Host $variableTable.Trim() + + Write-Host "--- Executing:" + & $block + Write-Host "--- Done running script block!" +} + # createSdkLocationFile parameter enables a file being generated under the toolset directory # which writes the sdk's location into. This is only necessary for cmd --> powershell invocations # as dot sourcing isn't possible. @@ -632,6 +672,17 @@ function ExitWithExitCode([int] $exitCode) { exit $exitCode } +# Check if $LASTEXITCODE is a nonzero exit code (NZEC). If so, print a Azure Pipeline error for +# diagnostics, then exit the script with the $LASTEXITCODE. +function Exit-IfNZEC([string] $category = "General") { + Write-Host "Exit code $LASTEXITCODE" + if ($LASTEXITCODE -ne 0) { + $message = "Last command failed with exit code $LASTEXITCODE." + Write-PipelineTelemetryError -Force -Category $category -Message $message + ExitWithExitCode $LASTEXITCODE + } +} + function Stop-Processes() { Write-Host 'Killing running build processes...' foreach ($processName in $processesToStopOnExit) { diff --git a/global.json b/global.json index f365d19335c..2827bf2e270 100644 --- a/global.json +++ b/global.json @@ -8,6 +8,6 @@ } }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "6.0.0-beta.21363.2" + "Microsoft.DotNet.Arcade.Sdk": "6.0.0-beta.21364.3" } } From 967522e40128f9a7ed1ddc240eac538e28f3b760 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 15 Jul 2021 14:37:41 +0000 Subject: [PATCH 08/14] Update dependencies from https://github.com/dotnet/runtime build 20210715.2 (#3464) [main] Update dependencies from dotnet/runtime --- eng/Version.Details.xml | 16 ++++++++-------- eng/Versions.props | 8 ++++---- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 83e8571cff1..e48eb634107 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -11,25 +11,25 @@ def2e2c6dc5064319250e2868a041a3dc07f9579 - + https://github.com/dotnet/runtime - 3150bfa50618cc98f546ffae7652b12c17cea702 + 90b8ddd7a6b28e57aebed7d478547ce07b9b60a6 https://github.com/dotnet/command-line-api a2ea4b1defbbc344c9dba1288b19ecc90256aff3 - + https://github.com/dotnet/runtime - 3150bfa50618cc98f546ffae7652b12c17cea702 + 90b8ddd7a6b28e57aebed7d478547ce07b9b60a6 - + https://github.com/dotnet/runtime - 3150bfa50618cc98f546ffae7652b12c17cea702 + 90b8ddd7a6b28e57aebed7d478547ce07b9b60a6 - + https://github.com/dotnet/runtime - 3150bfa50618cc98f546ffae7652b12c17cea702 + 90b8ddd7a6b28e57aebed7d478547ce07b9b60a6 https://github.com/nuget/nuget.client diff --git a/eng/Versions.props b/eng/Versions.props index 5459fe18b7b..c2a8d7fc770 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -19,10 +19,10 @@ 6.0.0-preview.2.129 6.0.0-preview.2.129 - 6.0.0-preview.7.21363.9 - 6.0.0-preview.7.21363.9 - 6.0.0-preview.7.21363.9 - 6.0.0-preview.7.21363.9 + 6.0.0-preview.7.21365.2 + 6.0.0-preview.7.21365.2 + 6.0.0-preview.7.21365.2 + 6.0.0-preview.7.21365.2 1.0.0-preview.19208.1 From b3e288892e1fa40f525c247cc0030988a39062af Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 15 Jul 2021 14:37:51 +0000 Subject: [PATCH 09/14] Update dependencies from https://github.com/dotnet/command-line-api build 20210714.1 (#3465) [main] Update dependencies from dotnet/command-line-api --- eng/Version.Details.xml | 4 ++-- eng/Versions.props | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index e48eb634107..77ea6646f63 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -15,9 +15,9 @@ https://github.com/dotnet/runtime 90b8ddd7a6b28e57aebed7d478547ce07b9b60a6 - + https://github.com/dotnet/command-line-api - a2ea4b1defbbc344c9dba1288b19ecc90256aff3 + d6d49b068ffa199ca60a2aa4a2d31e748c4dbe73 https://github.com/dotnet/runtime diff --git a/eng/Versions.props b/eng/Versions.props index c2a8d7fc770..60635892853 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -13,7 +13,7 @@ 4.3.0 4.3.0 - 2.0.0-beta1.21361.1 + 2.0.0-beta1.21364.1 6.0.0-preview.2.129 6.0.0-preview.2.129 From a47ed43649510cebdff90a52a0dc16275c7f8c79 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 15 Jul 2021 14:39:38 +0000 Subject: [PATCH 10/14] Update dependencies from https://github.com/dotnet/source-build build 20210714.1 (#3463) [main] Update dependencies from dotnet/source-build --- eng/Version.Details.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 77ea6646f63..4358adb8f5c 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,9 +1,9 @@ - + https://github.com/dotnet/source-build - ef9facdeefd5381d7319b25469e9fd5f1250d1f4 + 540d87fcc48f6e0c84b65009a8538ad4661068a5 From 871b9c01c808915a0825226987bb40bfa2d7ed8e Mon Sep 17 00:00:00 2001 From: Vlada Shubina Date: Wed, 14 Jul 2021 17:12:52 +0300 Subject: [PATCH 11/14] added conditional processing for C# language features based on languageVersion / framework --- .../.template.config/template.json | 30 ++ .../content/ClassLibrary-CSharp/Class1.cs | 7 +- .../Company.ClassLibrary1.csproj | 3 +- .../.template.config/template.json | 39 ++ .../Company.ConsoleApplication1.csproj | 4 +- .../ConsoleApplication-CSharp/Program.cs | 21 +- .../CommonTemplatesTests.cs | 353 ++++++++++++++++-- 7 files changed, 429 insertions(+), 28 deletions(-) diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ClassLibrary-CSharp/.template.config/template.json b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ClassLibrary-CSharp/.template.config/template.json index 144d4d9de37..39c4cd89897 100644 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ClassLibrary-CSharp/.template.config/template.json +++ b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ClassLibrary-CSharp/.template.config/template.json @@ -84,6 +84,36 @@ "description": "If specified, skips the automatic restore of the project on create.", "defaultValue": "false", "displayName": "Skip restore" + }, + "csharp10orLater": { + "type": "generated", + "generator": "regexMatch", + "datatype": "bool", + "parameters": { + "pattern": "^(|10\\.0|10|preview|latest|default|latestMajor)$", + "source": "langVersion" + } + }, + "csharp8orLater": { + "type": "generated", + "generator": "regexMatch", + "datatype": "bool", + "parameters": { + "pattern": "^(|8|8\\.0|9|9\\.0|10\\.0|10|preview|latest|default|latestMajor)$", + "source": "langVersion" + } + }, + "csharpFeature_ImplicitUsings": { + "type": "computed", + "value": "Framework == \"net6.0\" && csharp10orLater == \"true\"" + }, + "csharpFeature_FileScopedNamespaces": { + "type": "computed", + "value": "(Framework == \"net6.0\" || langVersion != \"\") && csharp10orLater == \"true\"" + }, + "csharpFeature_Nullable": { + "type": "computed", + "value": "(Framework != \"netstandard2.0\" || langVersion != \"\") && csharp8orLater == \"true\"" } }, "primaryOutputs": [ diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ClassLibrary-CSharp/Class1.cs b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ClassLibrary-CSharp/Class1.cs index a6325f3fb1b..2dcafee5a35 100644 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ClassLibrary-CSharp/Class1.cs +++ b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ClassLibrary-CSharp/Class1.cs @@ -1,6 +1,11 @@ -namespace Company.ClassLibrary1 +#if (!csharpFeature_ImplicitUsings) +using System; + +#endif +namespace Company.ClassLibrary1 { public class Class1 { + } } diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ClassLibrary-CSharp/Company.ClassLibrary1.csproj b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ClassLibrary-CSharp/Company.ClassLibrary1.csproj index 892876e76de..46784087ed7 100644 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ClassLibrary-CSharp/Company.ClassLibrary1.csproj +++ b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ClassLibrary-CSharp/Company.ClassLibrary1.csproj @@ -5,7 +5,8 @@ TargetFrameworkOverride Company.ClassLibrary1 $(ProjectLanguageVersion) - enable + true + enable diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ConsoleApplication-CSharp/.template.config/template.json b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ConsoleApplication-CSharp/.template.config/template.json index 0d33dafa0e6..1a08e0a395f 100644 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ConsoleApplication-CSharp/.template.config/template.json +++ b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ConsoleApplication-CSharp/.template.config/template.json @@ -60,6 +60,45 @@ "description": "If specified, skips the automatic restore of the project on create.", "defaultValue": "false", "displayName": "Skip restore" + }, + "csharp10orLater": { + "type": "generated", + "generator": "regexMatch", + "datatype": "bool", + "parameters": { + "pattern": "^(|10\\.0|10|preview|latest|default|latestMajor)$", + "source": "langVersion" + } + }, + "csharp9orLater": { + "type": "generated", + "generator": "regexMatch", + "datatype": "bool", + "parameters": { + "pattern": "^(|9|9\\.0|10\\.0|10|preview|latest|default|latestMajor)$", + "source": "langVersion" + } + }, + "csharp8orLater": { + "type": "generated", + "generator": "regexMatch", + "datatype": "bool", + "parameters": { + "pattern": "^(|8|8\\.0|9|9\\.0|10\\.0|10|preview|latest|default|latestMajor)$", + "source": "langVersion" + } + }, + "csharpFeature_ImplicitUsings": { + "type": "computed", + "value": "csharp10orLater == \"true\"" + }, + "csharpFeature_Nullable": { + "type": "computed", + "value": "csharp8orLater == \"true\"" + }, + "csharpFeature_TopLevelProgram": { + "type": "computed", + "value": "csharp9orLater == \"true\"" } }, "primaryOutputs": [ diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ConsoleApplication-CSharp/Company.ConsoleApplication1.csproj b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ConsoleApplication-CSharp/Company.ConsoleApplication1.csproj index 66e0f74129c..ced2071aa9f 100644 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ConsoleApplication-CSharp/Company.ConsoleApplication1.csproj +++ b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ConsoleApplication-CSharp/Company.ConsoleApplication1.csproj @@ -4,8 +4,10 @@ Exe net6.0 TargetFrameworkOverride + Company.ConsoleApplication1 $(ProjectLanguageVersion) - enable + true + enable diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ConsoleApplication-CSharp/Program.cs b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ConsoleApplication-CSharp/Program.cs index 68c6516d215..bdeb5843bdb 100644 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ConsoleApplication-CSharp/Program.cs +++ b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ConsoleApplication-CSharp/Program.cs @@ -1,2 +1,21 @@ -Console.WriteLine("Hello, World!"); +#if (csharpFeature_TopLevelProgram) // See https://aka.ms/new-console-template for more information +#endif +#if (!csharpFeature_ImplicitUsings) +using System; + +#endif +#if (csharpFeature_TopLevelProgram) +Console.WriteLine("Hello, World!"); +#else +namespace Company.ConsoleApplication1 +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("Hello, World!"); + } + } +} +#endif diff --git a/test/dotnet-new3.UnitTests/CommonTemplatesTests.cs b/test/dotnet-new3.UnitTests/CommonTemplatesTests.cs index 88132affd06..ccc22fb5218 100644 --- a/test/dotnet-new3.UnitTests/CommonTemplatesTests.cs +++ b/test/dotnet-new3.UnitTests/CommonTemplatesTests.cs @@ -66,21 +66,6 @@ public CommonTemplatesTests(SharedHomeDirectory fixture, ITestOutputHelper log) [InlineData("Class Library", "classlib", "VB", "netstandard2.0")] [InlineData("Class Library", "classlib", "F#", "netstandard2.0")] - [InlineData("Class Library", "classlib", "C#", "net6.0", "10.0")] - [InlineData("Class Library", "classlib", "C#", "net6.0", "9.0", Skip = "https://github.com/dotnet/templating/issues/3449")] - [InlineData("Class Library", "classlib", "C#", "net6.0", "8.0", Skip = "https://github.com/dotnet/templating/issues/3449")] - [InlineData("Class Library", "classlib", "C#", "net6.0", "7.3", Skip = "https://github.com/dotnet/templating/issues/3449")] - [InlineData("Class Library", "classlib", "C#", "net6.0", "7.2", Skip = "https://github.com/dotnet/templating/issues/3449")] - [InlineData("Class Library", "classlib", "C#", "net6.0", "7.1", Skip = "https://github.com/dotnet/templating/issues/3449")] - [InlineData("Class Library", "classlib", "C#", "net6.0", "7", Skip = "https://github.com/dotnet/templating/issues/3449")] - - [InlineData("Console Application", "console", "C#", "net6.0", "10.0")] - [InlineData("Console Application", "console", "C#", "net6.0", "9.0", Skip = "https://github.com/dotnet/templating/issues/3449")] - [InlineData("Console Application", "console", "C#", "net6.0", "8.0", Skip = "https://github.com/dotnet/templating/issues/3449")] - [InlineData("Console Application", "console", "C#", "net6.0", "7.3", Skip = "https://github.com/dotnet/templating/issues/3449")] - [InlineData("Console Application", "console", "C#", "net6.0", "7.2", Skip = "https://github.com/dotnet/templating/issues/3449")] - [InlineData("Console Application", "console", "C#", "net6.0", "7.1", Skip = "https://github.com/dotnet/templating/issues/3449")] - [InlineData("Console Application", "console", "C#", "net6.0", "7", Skip = "https://github.com/dotnet/templating/issues/3449")] public void AllCommonProjectsCreateRestoreAndBuild(string expectedTemplateName, string templateShortName, string? language = null, string? framework = null, string? langVersion = null) { string workingDir = TestUtils.CreateTemporaryFolder(); @@ -243,6 +228,334 @@ public void AllCommonItemsCreate(string expectedTemplateName, string templateSho Directory.Delete(workingDir, true); } + #region Project templates language features tests + + /// + /// Creates all possible combinations for supported templates, language versions and frameworks. + /// + public static IEnumerable TopLevelProgramSupport_Data() + { + var templatesToTest = new[] + { + new { Name = "console", Frameworks = new[] { null, "net6.0" } } + }; + + string[] unsupportedLanguageVersions = { "1", "ISO-1" }; + string?[] supportedLanguageVersions = { null, "ISO-2", "2", "3", "4", "5", "6", "7", "7.1", "7.2", "7.3", "8.0", "9.0", "10.0", "latest", "latestMajor", "default", "preview" }; + + string?[] topLevelStatementSupport = { null, "9.0", "10.0", "latest", "latestMajor", "default", "preview" }; + + foreach (var template in templatesToTest) + { + foreach (var langVersion in unsupportedLanguageVersions) + { + foreach (var framework in template.Frameworks) + { + yield return new object?[] + { + template.Name, + false, //dotnet build should fail + framework, + langVersion, + topLevelStatementSupport.Contains(langVersion) + }; + } + } + foreach (var langVersion in supportedLanguageVersions) + { + foreach (var framework in template.Frameworks) + { + yield return new object?[] + { + template.Name, + true, //dotnet build should pass + framework, + langVersion, + topLevelStatementSupport.Contains(langVersion) + }; + } + } + } + } + + [Theory] + //creates all possible combinations for supported templates, language versions and frameworks + [MemberData(nameof(TopLevelProgramSupport_Data))] + public void TopLevelProgramSupport(string name, bool buildPass, string? framework, string? langVersion, bool supportsFeature) + { + string workingDir = TestUtils.CreateTemporaryFolder(); + + List args = new List() { name, "-o", "MyProject" }; + if (!string.IsNullOrWhiteSpace(framework)) + { + args.Add("--framework"); + args.Add(framework); + } + if (!string.IsNullOrWhiteSpace(langVersion)) + { + args.Add("--langVersion"); + args.Add(langVersion); + } + + new DotnetNewCommand(_log, args.ToArray()) + .WithCustomHive(_fixture.HomeDirectory) + .WithWorkingDirectory(workingDir) + .Execute() + .Should() + .ExitWith(0) + .And.NotHaveStdErr(); + + var buildResult = new DotnetCommand(_log, "build", "MyProject") + .WithWorkingDirectory(workingDir) + .Execute(); + + if (buildPass) + { + buildResult.Should().ExitWith(0).And.NotHaveStdErr(); + } + else + { + buildResult.Should().Fail(); + return; + } + + string programFileContent = File.ReadAllText(Path.Combine(workingDir, "MyProject", "Program.cs")); + string unexpectedTopLevelContent = +@"namespace MyProject +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine(""Hello, World!""); + } + } +} +"; + if (supportsFeature) + { + Assert.Contains("Console.WriteLine(\"Hello, World!\")", programFileContent); + Assert.Contains("// See https://aka.ms/new-console-template for more information", programFileContent); + Assert.DoesNotContain(unexpectedTopLevelContent, programFileContent); + } + else + { + Assert.DoesNotContain("// See https://aka.ms/new-console-template for more information", programFileContent); + Assert.Contains(unexpectedTopLevelContent, programFileContent); + } + } + + /// + /// Creates all possible combinations for supported templates, language versions and frameworks. + /// + public static IEnumerable NullableSupport_Data() + { + var templatesToTest = new[] + { + new { Template = "console", Frameworks = new[] { null, "net6.0" } }, + new { Template = "classlib", Frameworks = new[] { null, "net6.0", "netstandard2.0", "netstandard2.1" } } + }; + + string[] unsupportedLanguageVersions = { "1", "ISO-1" }; + string?[] supportedLanguageVersions = { null, "ISO-2", "2", "3", "4", "5", "6", "7", "7.1", "7.2", "7.3", "8.0", "9.0", "10.0", "latest", "latestMajor", "default", "preview" }; + + string?[] supportedInFrameworkByDefault = { null, "net6.0", "netstandard2.1" }; + string?[] supportedInLanguageVersion = { "8.0", "9.0", "10.0", "latest", "latestMajor", "default", "preview" }; + + foreach (var template in templatesToTest) + { + foreach (var langVersion in unsupportedLanguageVersions) + { + foreach (var framework in template.Frameworks) + { + yield return new object?[] + { + template.Template, + false, //dotnet build should fail + framework, + langVersion, + supportedInLanguageVersion.Contains(langVersion) + || langVersion == null && supportedInFrameworkByDefault.Contains(framework) + }; + } + } + foreach (var langVersion in supportedLanguageVersions) + { + foreach (var framework in template.Frameworks) + { + yield return new object?[] + { + template.Template, + true, //dotnet build should pass + framework, + langVersion, + supportedInLanguageVersion.Contains(langVersion) + || langVersion == null && supportedInFrameworkByDefault.Contains(framework) + }; + } + } + } + } + + [Theory] + //creates all possible combinations for supported templates, language versions and frameworks + [MemberData(nameof(NullableSupport_Data))] + public void NullableSupport(string name, bool buildPass, string? framework, string? langVersion, bool supportsFeature) + { + string workingDir = TestUtils.CreateTemporaryFolder(); + + List args = new List() { name, "-o", "MyProject" }; + if (!string.IsNullOrWhiteSpace(framework)) + { + args.Add("--framework"); + args.Add(framework); + } + if (!string.IsNullOrWhiteSpace(langVersion)) + { + args.Add("--langVersion"); + args.Add(langVersion); + } + + new DotnetNewCommand(_log, args.ToArray()) + .WithCustomHive(_fixture.HomeDirectory) + .WithWorkingDirectory(workingDir) + .Execute() + .Should() + .ExitWith(0) + .And.NotHaveStdErr(); + + var buildResult = new DotnetCommand(_log, "build", "MyProject") + .WithWorkingDirectory(workingDir) + .Execute(); + + if (buildPass) + { + buildResult.Should().ExitWith(0).And.NotHaveStdErr(); + } + else + { + buildResult.Should().Fail(); + return; + } + + XDocument projectXml = XDocument.Load(Path.Combine(workingDir, "MyProject", "MyProject.csproj")); + XNamespace ns = projectXml.Root?.Name.Namespace ?? throw new Exception("Unexpected project file format"); + if (supportsFeature) + { + Assert.Equal("enable", projectXml.Root?.Element(ns + "PropertyGroup")?.Element(ns + "Nullable")?.Value); + } + else + { + Assert.Null(projectXml.Root?.Element(ns + "PropertyGroup")?.Element(ns + "Nullable")); + } + } + + /// + /// Creates all possible combinations for supported templates, language versions and frameworks. + /// + public static IEnumerable ImplicitUsingsSupport_Data() + { + var templatesToTest = new[] + { + new { Template = "console", Frameworks = new[] { null, "net6.0" } }, + new { Template = "classlib", Frameworks = new[] { null, "net6.0", "netstandard2.0", "netstandard2.1" } } + }; + string[] unsupportedLanguageVersions = { "1", "ISO-1" }; + string?[] supportedLanguageVersions = { null, "ISO-2", "2", "3", "4", "5", "6", "7", "7.1", "7.2", "7.3", "8.0", "9.0", "10.0", "latest", "latestMajor", "default", "preview" }; + + string?[] supportedInFramework = { null, "net6.0" }; + string?[] supportedInLangVersion = { null, "10.0", "latest", "latestMajor", "default", "preview" }; + + foreach (var template in templatesToTest) + { + foreach (var langVersion in unsupportedLanguageVersions) + { + foreach (var framework in template.Frameworks) + { + yield return new object?[] + { + template.Template, + false, //dotnet build should fail + framework, + langVersion, + supportedInLangVersion.Contains(langVersion) && supportedInFramework.Contains(framework) + }; + } + } + foreach (var langVersion in supportedLanguageVersions) + { + foreach (var framework in template.Frameworks) + { + yield return new object?[] + { + template.Template, + true, //dotnet build should pass + framework, + langVersion, + supportedInLangVersion.Contains(langVersion) && supportedInFramework.Contains(framework) + }; + } + } + } + } + + [Theory] + //creates all possible combinations for supported templates, language versions and frameworks + [MemberData(nameof(ImplicitUsingsSupport_Data))] + public void ImplicitUsingsSupport(string name, bool buildPass, string? framework, string? langVersion, bool supportsFeature) + { + string workingDir = TestUtils.CreateTemporaryFolder(); + + List args = new List() { name, "-o", "MyProject" }; + if (!string.IsNullOrWhiteSpace(framework)) + { + args.Add("--framework"); + args.Add(framework); + } + if (!string.IsNullOrWhiteSpace(langVersion)) + { + args.Add("--langVersion"); + args.Add(langVersion); + } + + new DotnetNewCommand(_log, args.ToArray()) + .WithCustomHive(_fixture.HomeDirectory) + .WithWorkingDirectory(workingDir) + .Execute() + .Should() + .ExitWith(0) + .And.NotHaveStdErr(); + + var buildResult = new DotnetCommand(_log, "build", "MyProject") + .WithWorkingDirectory(workingDir) + .Execute(); + + if (buildPass) + { + buildResult.Should().ExitWith(0).And.NotHaveStdErr(); + } + else + { + buildResult.Should().Fail(); + return; + } + string codeFileName = name == "console" ? "Program.cs" : "Class1.cs"; + string programFileContent = File.ReadAllText(Path.Combine(workingDir, "MyProject", codeFileName)); + XDocument projectXml = XDocument.Load(Path.Combine(workingDir, "MyProject", "MyProject.csproj")); + XNamespace ns = projectXml.Root?.Name.Namespace ?? throw new Exception("Unexpected project file format"); + if (supportsFeature) + { + Assert.DoesNotContain("using System;", programFileContent); + Assert.Null(projectXml.Root?.Element(ns + "PropertyGroup")?.Element(ns + "DisableImplicitNamespaceImports")); + } + else + { + Assert.Contains("using System;", programFileContent); + Assert.Equal("true", projectXml.Root?.Element(ns + "PropertyGroup")?.Element(ns + "DisableImplicitNamespaceImports")?.Value); + } + } + #endregion + [Theory] [InlineData("Nullable", "enable", "Console Application", "console", null, null)] [InlineData("CheckForOverflowUnderflow", null, "Console Application", "console", null, null)] @@ -251,9 +564,6 @@ public void AllCommonItemsCreate(string expectedTemplateName, string templateSho [InlineData("Nullable", null, "Console Application", "console", null, "net5.0")] [InlineData("Nullable", null, "Console Application", "console", null, "netcoreapp3.1")] [InlineData("Nullable", null, "Console Application", "console", null, "netcoreapp2.1")] - [InlineData("Nullable", "enable", "Console Application", "console", null, null, "9.0")] - [InlineData("Nullable", "enable", "Console Application", "console", null, null, "8.0")] - [InlineData("Nullable", "enable", "Console Application", "console", null, null, "7.3")] [InlineData("Nullable", null, "Console Application", "console", "F#", null)] [InlineData("CheckForOverflowUnderflow", null, "Console Application", "console", "F#", null)] @@ -286,7 +596,7 @@ public void AllCommonItemsCreate(string expectedTemplateName, string templateSho [InlineData("TargetFramework", "net6.0", "Class Library", "classlib", "VB", null)] [InlineData("Nullable", null, "Class Library", "classlib", "VB", "netstandard2.0")] - public void SetPropertiesByDefault(string propertyName, string? propertyValue, string expectedTemplateName, string templateShortName, string? language, string? framework, string? langVersion = null) + public void SetPropertiesByDefault(string propertyName, string? propertyValue, string expectedTemplateName, string templateShortName, string? language, string? framework) { string workingDir = TestUtils.CreateTemporaryFolder(); List args = new List() { templateShortName, "--no-restore" }; @@ -300,11 +610,6 @@ public void SetPropertiesByDefault(string propertyName, string? propertyValue, s args.Add("--framework"); args.Add(framework); } - if (!string.IsNullOrWhiteSpace(langVersion)) - { - args.Add("--langVersion"); - args.Add(langVersion); - } new DotnetNewCommand(_log, args.ToArray()) .WithCustomHive(_fixture.HomeDirectory) From f3bf9c7aaf44b0a34089055335aeac12818d9bc0 Mon Sep 17 00:00:00 2001 From: Vlada Shubina Date: Thu, 15 Jul 2021 19:59:41 +0300 Subject: [PATCH 12/14] fixes dotnet/templating#3460 wrong locale is used for localizing the template content --- .../Settings/TemplateCache.cs | 82 ++++++++----------- .../LocalizationTests.cs | 8 +- .../TemplateCacheTests.cs | 79 ++++++++++++++++++ 3 files changed, 117 insertions(+), 52 deletions(-) create mode 100644 test/Microsoft.TemplateEngine.Edge.UnitTests/TemplateCacheTests.cs diff --git a/src/Microsoft.TemplateEngine.Edge/Settings/TemplateCache.cs b/src/Microsoft.TemplateEngine.Edge/Settings/TemplateCache.cs index d8e368e75a1..4661ae034cc 100644 --- a/src/Microsoft.TemplateEngine.Edge/Settings/TemplateCache.cs +++ b/src/Microsoft.TemplateEngine.Edge/Settings/TemplateCache.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; using System.Globalization; +using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Newtonsoft.Json; @@ -23,54 +24,27 @@ public TemplateCache(ScanResult?[] scanResults, Dictionary mou // We need this dictionary to de-duplicate templates that have same identity // notice that IEnumerable that we get in is order by priority which means // last template with same Identity wins, others are ignored... - var templateDeduplicationDictionary = new Dictionary(); - var localizationsByTemplateId = new Dictionary(); - - string uiLocale = CultureInfo.CurrentUICulture.Name; - string uiLocaleWithoutCountry = GetLocaleNameWithoutCountry(uiLocale); - + var templateDeduplicationDictionary = new Dictionary(); foreach (var scanResult in scanResults) { if (scanResult == null) { continue; } - foreach (ILocalizationLocator locator in scanResult.Localizations) - { - if (uiLocale != locator.Locale && - localizationsByTemplateId.TryGetValue(locator.Identity, out ILocalizationLocator existingLoc) && - existingLoc.Locale == GetLocaleNameWithoutCountry(existingLoc.Locale)) - { - // This localization is not a perfect match and we already have the localizations for countryless locale available. Ignore this one. - continue; - } - - string templateLocaleWithoutCountry = GetLocaleNameWithoutCountry(locator.Locale); - if (uiLocaleWithoutCountry != templateLocaleWithoutCountry) - { - // UI is "fr", but the localizations are for "en". This localization is not good enough to be a substitute. - continue; - } - - // This localization is either the perfect match, or a suitable substitute and there are no other candidates for the job yet. - localizationsByTemplateId[locator.Identity] = locator; - } - foreach (ITemplate template in scanResult.Templates) { - templateDeduplicationDictionary[template.Identity] = template; + templateDeduplicationDictionary[template.Identity] = (template, GetBestLocalizationLocatorMatch(scanResult.Localizations, template.Identity)); } } var templates = new List(); - foreach (ITemplate newTemplate in templateDeduplicationDictionary.Values) + foreach (var newTemplate in templateDeduplicationDictionary.Values) { - localizationsByTemplateId.TryGetValue(newTemplate.Identity, out ILocalizationLocator locatorForTemplate); - templates.Add(new TemplateInfo(newTemplate, locatorForTemplate, logger)); + templates.Add(new TemplateInfo(newTemplate.Template, newTemplate.Localization, logger)); } Version = Settings.TemplateInfo.CurrentVersion; - Locale = uiLocale; + Locale = CultureInfo.CurrentUICulture.Name; TemplateInfo = templates; MountPointsInfo = mountPoints; } @@ -140,27 +114,37 @@ public TemplateCache(JObject? contentJobject, ILogger logger) [JsonProperty] public Dictionary MountPointsInfo { get; } - /// - /// Given a locale, removes the country/region part and returns. - /// - /// Locale in format "language-countryRegion". - /// - /// - /// Input "en-US" returns "en". - /// Input "de-AU" returns "de". - /// Input "de" returns "de". - /// - /// - private static string GetLocaleNameWithoutCountry(string locale) + private ILocalizationLocator? GetBestLocalizationLocatorMatch(IReadOnlyList localizations, string identity) { - int countrySplitterIndex = locale.IndexOf('-'); - if (countrySplitterIndex != -1) + IEnumerable localizationsForTemplate = localizations.Where(locator => locator.Identity.Equals(identity, StringComparison.OrdinalIgnoreCase)); + + if (!localizations.Any()) { - return locale.Substring(0, countrySplitterIndex); + return null; } + IEnumerable availableLocalizations = localizationsForTemplate.Select(locator => locator.Locale); + string? bestMatch = GetBestLocaleMatch(availableLocalizations); + if (string.IsNullOrWhiteSpace(bestMatch)) + { + return null; + } + return localizationsForTemplate.FirstOrDefault(locator => locator.Locale == bestMatch); + } - // This locale doesn't have country/Region to begin with. - return locale; + /// see https://source.dot.net/#System.Private.CoreLib/ResourceFallbackManager.cs. + private string? GetBestLocaleMatch(IEnumerable availableLocalizations) + { + CultureInfo currentCulture = CultureInfo.CurrentUICulture; + do + { + if (availableLocalizations.Contains(currentCulture.Name, StringComparer.OrdinalIgnoreCase)) + { + return currentCulture.Name; + } + currentCulture = currentCulture.Parent; + } + while (currentCulture.Name != CultureInfo.InvariantCulture.Name); + return null; } } } diff --git a/test/Microsoft.TemplateEngine.Edge.UnitTests/LocalizationTests.cs b/test/Microsoft.TemplateEngine.Edge.UnitTests/LocalizationTests.cs index d58e6c27147..871b5f3f373 100644 --- a/test/Microsoft.TemplateEngine.Edge.UnitTests/LocalizationTests.cs +++ b/test/Microsoft.TemplateEngine.Edge.UnitTests/LocalizationTests.cs @@ -148,10 +148,12 @@ public async Task TestLocalizedPostActionFields( } [Theory] - [InlineData("de", "name_de-DE:äÄßöÖüÜ")] + [InlineData("de", "name")] [InlineData("de-de", "name_de-DE:äÄßöÖüÜ")] - [InlineData("de-Au", "name_de-DE:äÄßöÖüÜ")] - [InlineData("de-AU", "name_de-DE:äÄßöÖüÜ")] + [InlineData("de-AT", "name")] + [InlineData("de-at", "name")] + [InlineData("tr", "name_tr-TR:çÇğĞıIİöÖşŞüÜ")] + [InlineData("tr-TR", "name_tr-TR:çÇğĞıIİöÖşŞüÜ")] public void TestLocaleCountryFallback(string locale, string expectedName) { _ = LoadHostWithLocalizationTemplates(locale, out _, out ITemplateInfo localizationTemplate); diff --git a/test/Microsoft.TemplateEngine.Edge.UnitTests/TemplateCacheTests.cs b/test/Microsoft.TemplateEngine.Edge.UnitTests/TemplateCacheTests.cs new file mode 100644 index 00000000000..e1327a3c880 --- /dev/null +++ b/test/Microsoft.TemplateEngine.Edge.UnitTests/TemplateCacheTests.cs @@ -0,0 +1,79 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#nullable enable + +#if !NET6_0_OR_GREATER +using System; +using System.Collections.Generic; +using System.Linq; +#endif +using System.Globalization; +using FakeItEasy; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.TemplateEngine.Abstractions; +using Microsoft.TemplateEngine.Abstractions.Mount; +using Microsoft.TemplateEngine.Edge.Settings; +using Xunit; + +namespace Microsoft.TemplateEngine.Edge.UnitTests +{ + public class TemplateCacheTests + { + [Theory] + [InlineData("en-US", "en")] + [InlineData("zh-CN", "zh-Hans")] + [InlineData("zh-SG", "zh-Hans")] + [InlineData("zh-TW", "zh-Hant")] + [InlineData("zh-HK", "zh-Hant")] + [InlineData("zh-MO", "zh-Hant")] + [InlineData("pt-BR", "pt-BR")] + [InlineData("pt", null)] + [InlineData("uk-UA", null)] + [InlineData("invariant", null)] + public void PicksCorrectLocator (string currentCulture, string? expectedLocator) + { + CultureInfo persistedCulture = CultureInfo.CurrentUICulture; + try + { + if (currentCulture != "invariant") + { + CultureInfo.CurrentUICulture = new CultureInfo(currentCulture); + } + else + { + currentCulture = ""; + CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + } + string[] availableLocales = new[] { "cs", "de", "en", "es", "fr", "it", "ja", "ko", "pl", "pt-BR", "ru", "tr", "zh-Hans", "zh-Hant" }; + + ITemplate template = A.Fake(); + A.CallTo(() => template.Identity).Returns("testIdentity"); + List locators = new List(); + foreach (string locale in availableLocales) + { + ILocalizationLocator locator = A.Fake(); + A.CallTo(() => locator.Identity).Returns("testIdentity"); + A.CallTo(() => locator.Locale).Returns(locale); + A.CallTo(() => locator.Name).Returns(locale + " name"); + locators.Add(locator); + } + IMountPoint mountPoint = A.Fake(); + A.CallTo(() => mountPoint.MountPointUri).Returns("testMount"); + + ScanResult result = new ScanResult(mountPoint, new[] { template }, locators, Array.Empty<(string AssemblyPath, Type InterfaceType, IIdentifiedComponent Instance)>()); + + TemplateCache templateCache = new TemplateCache(new[] { result }, new Dictionary(), NullLogger.Instance); + + Assert.Equal(currentCulture, templateCache.Locale); + Assert.Equal("testIdentity", templateCache.TemplateInfo.Single().Identity); + Assert.Equal(string.IsNullOrEmpty(expectedLocator) ? "" : expectedLocator + " name", templateCache.TemplateInfo.Single().Name); + } + finally + { + CultureInfo.CurrentUICulture = persistedCulture; + } + } + + } +} From 8a143e4b55e337616d173279afaf297d714f33d1 Mon Sep 17 00:00:00 2001 From: Vlada Shubina Date: Wed, 14 Jul 2021 21:16:59 +0300 Subject: [PATCH 13/14] dotnet/templating#3360 using file-scoped namespaces in classlib template changed SDK version --- global.json | 2 +- .../content/ClassLibrary-CSharp/Class1.cs | 8 ++ .../CommonTemplatesTests.cs | 101 ++++++++++++++++++ 3 files changed, 110 insertions(+), 1 deletion(-) diff --git a/global.json b/global.json index 2827bf2e270..122613aa116 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "tools": { - "dotnet": "6.0.100-preview.7.21362.12", + "dotnet": "6.0.100-preview.7.21364.4", "runtimes": { "dotnet": [ "$(MicrosoftNETCoreAppRefPackageVersion)" diff --git a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ClassLibrary-CSharp/Class1.cs b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ClassLibrary-CSharp/Class1.cs index 2dcafee5a35..24e7f1f8fd4 100644 --- a/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ClassLibrary-CSharp/Class1.cs +++ b/template_feed/Microsoft.DotNet.Common.ProjectTemplates.6.0/content/ClassLibrary-CSharp/Class1.cs @@ -2,6 +2,13 @@ using System; #endif +#if (csharpFeature_FileScopedNamespaces) +namespace Company.ClassLibrary1; +public class Class1 +{ + +} +#else namespace Company.ClassLibrary1 { public class Class1 @@ -9,3 +16,4 @@ public class Class1 } } +#endif diff --git a/test/dotnet-new3.UnitTests/CommonTemplatesTests.cs b/test/dotnet-new3.UnitTests/CommonTemplatesTests.cs index ccc22fb5218..fb07d942899 100644 --- a/test/dotnet-new3.UnitTests/CommonTemplatesTests.cs +++ b/test/dotnet-new3.UnitTests/CommonTemplatesTests.cs @@ -554,6 +554,107 @@ public void ImplicitUsingsSupport(string name, bool buildPass, string? framework Assert.Equal("true", projectXml.Root?.Element(ns + "PropertyGroup")?.Element(ns + "DisableImplicitNamespaceImports")?.Value); } } + + public static IEnumerable FileScopedNamespacesSupport_Data() + { + var templatesToTest = new[] + { + new { Template = "classlib", Frameworks = new[] { null, "net6.0", "netstandard2.0", "netstandard2.1" } } + }; + string[] unsupportedLanguageVersions = { "1", "ISO-1" }; + string?[] supportedLanguageVersions = { null, "ISO-2", "2", "3", "4", "5", "6", "7", "7.1", "7.2", "7.3", "8.0", "9.0", "10.0", "latest", "latestMajor", "default", "preview" }; + + string?[] supportedFrameworks = { null, "net6.0" }; + string?[] fileScopedNamespacesSupportedLanguages = { "10.0", "latest", "latestMajor", "default", "preview" }; + + foreach (var template in templatesToTest) + { + foreach (var langVersion in unsupportedLanguageVersions) + { + foreach (var framework in template.Frameworks) + { + yield return new object?[] { template.Template, false, framework, langVersion, fileScopedNamespacesSupportedLanguages.Contains(langVersion) || langVersion == null && supportedFrameworks.Contains(framework) }; + } + } + foreach (var langVersion in supportedLanguageVersions) + { + foreach (var framework in template.Frameworks) + { + yield return new object?[] { template.Template, true, framework, langVersion, fileScopedNamespacesSupportedLanguages.Contains(langVersion) || langVersion == null && supportedFrameworks.Contains(framework) }; + } + } + } + } + + [Theory] + //creates all possible combinations for supported templates, language versions and frameworks + [MemberData(nameof(FileScopedNamespacesSupport_Data))] + public void FileScopedNamespacesSupport(string name, bool pass, string? framework, string? langVersion, bool supportsFeature) + { + string workingDir = TestUtils.CreateTemporaryFolder(); + + List args = new List() { name, "-o", "MyProject" }; + if (!string.IsNullOrWhiteSpace(framework)) + { + args.Add("--framework"); + args.Add(framework); + } + if (!string.IsNullOrWhiteSpace(langVersion)) + { + args.Add("--langVersion"); + args.Add(langVersion); + } + + new DotnetNewCommand(_log, args.ToArray()) + .WithCustomHive(_fixture.HomeDirectory) + .WithWorkingDirectory(workingDir) + .Execute() + .Should() + .ExitWith(0) + .And.NotHaveStdErr(); + + var buildResult = new DotnetCommand(_log, "build", "MyProject") + .WithWorkingDirectory(workingDir) + .Execute(); + + if (pass) + { + buildResult.Should().ExitWith(0).And.NotHaveStdErr(); + } + else + { + buildResult.Should().Fail(); + return; + } + string codeFileName = name == "console" ? "Program.cs" : "Class1.cs"; + string programFileContent = File.ReadAllText(Path.Combine(workingDir, "MyProject", codeFileName)); + + string supportedContent = +@"namespace MyProject; +public class Class1 +{ + +}"; + string unsupportedContent = +@"namespace MyProject +{ + public class Class1 + { + + } +}"; + + if (supportsFeature) + { + Assert.DoesNotContain(unsupportedContent, programFileContent); + Assert.Contains(supportedContent, programFileContent); + } + else + { + Assert.DoesNotContain(supportedContent, programFileContent); + Assert.Contains(unsupportedContent, programFileContent); + } + } #endregion [Theory] From 64f993298fd979320ee8a1e87171f3264beaf9e6 Mon Sep 17 00:00:00 2001 From: Lukas Lansky Date: Fri, 16 Jul 2021 13:47:43 +0200 Subject: [PATCH 14/14] RC1 branding --- eng/Versions.props | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/eng/Versions.props b/eng/Versions.props index 60635892853..b8bf6526612 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -5,8 +5,8 @@ true true 6.0.100 - preview - 7 + rc + 1 true 12.0.2 4.3.0