Apply Library.Template updates

This commit is contained in:
Andrew Arnott 2020-10-20 16:24:28 -06:00
Родитель 0548531a08
Коммит 147bb41665
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: A9B9910CDCCDA441
63 изменённых файлов: 926 добавлений и 372 удалений

8
.devcontainer/Dockerfile Normal file
Просмотреть файл

@ -0,0 +1,8 @@
FROM mcr.microsoft.com/dotnet/core/sdk:3.1-bionic
# Installing mono makes `dotnet test` work without errors even for net472.
# But installing it takes a long time, so it's excluded by default.
#RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
#RUN echo "deb https://download.mono-project.com/repo/ubuntu stable-bionic main" | tee /etc/apt/sources.list.d/mono-official-stable.list
#RUN apt-get update
#RUN DEBIAN_FRONTEND=noninteractive apt-get install -y mono-devel

Просмотреть файл

@ -0,0 +1,16 @@
{
"name": "Dev space",
"dockerFile": "Dockerfile",
"postCreateCommand": "./init.ps1 -InstallLocality machine",
"extensions": [
"ms-azure-devops.azure-pipelines",
"ms-dotnettools.csharp",
"k--kato.docomment",
"editorconfig.editorconfig",
"pflannery.vscode-versionlens",
"davidanson.vscode-markdownlint",
"dotjoshjohnson.xml",
"ms-vscode-remote.remote-containers",
"ms-azuretools.vscode-docker"
]
}

Просмотреть файл

@ -9,6 +9,10 @@ indent_style = space
# (Please don't specify an indent_size here; that has too many unintended consequences.)
[*.yml]
indent_size = 2
indent_style = space
# Code files
[*.{cs,csx,vb,vbx,h,cpp,idl}]
indent_size = 4
@ -16,7 +20,7 @@ insert_final_newline = true
trim_trailing_whitespace = true
# Xml project files
[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}]
[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj,runsettings}]
indent_size = 2
# Xml config files
@ -155,3 +159,11 @@ csharp_new_line_before_members_in_anonymous_types = true
# Blocks are allowed
csharp_prefer_braces = true:silent
[*.cs]
# SA1130: Use lambda syntax
dotnet_diagnostic.SA1130.severity = silent
[*.sln]
indent_style = tab

10
.gitattributes поставляемый
Просмотреть файл

@ -3,6 +3,10 @@
###############################################################################
* text=auto
# Ensure shell scripts use LF line endings (linux only accepts LF)
*.sh eol=lf
*.ps1 eol=lf
###############################################################################
# Set default behavior for command prompt diff.
#
@ -17,7 +21,7 @@
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
@ -46,9 +50,9 @@
###############################################################################
# diff behavior for common document formats
#
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain

1
.gitignore поставляемый
Просмотреть файл

@ -72,6 +72,7 @@ StyleCopReport.xml
*.pgc
*.pgd
*.rsp
!Directory.Build.rsp
*.sbr
*.tlb
*.tli

18
.vscode/extensions.json поставляемый Normal file
Просмотреть файл

@ -0,0 +1,18 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations.
// Extension identifier format: ${publisher}.${name}. Example: vscode.csharp
// List of extensions which should be recommended for users of this workspace.
"recommendations": [
"ms-azure-devops.azure-pipelines",
"ms-dotnettools.csharp",
"k--kato.docomment",
"editorconfig.editorconfig",
"pflannery.vscode-versionlens",
"davidanson.vscode-markdownlint",
"dotjoshjohnson.xml",
"ms-vscode-remote.remote-containers",
"ms-azuretools.vscode-docker"
],
// List of extensions recommended by VS Code that should not be recommended for users of this workspace.
"unwantedRecommendations": []
}

14
.vscode/launch.json поставляемый Normal file
Просмотреть файл

@ -0,0 +1,14 @@
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
]
}

8
.vscode/settings.json поставляемый Normal file
Просмотреть файл

@ -0,0 +1,8 @@
{
"files.trimTrailingWhitespace": true,
"files.insertFinalNewline": true,
"files.trimFinalNewlines": true,
"omnisharp.enableEditorConfigSupport": true,
"omnisharp.enableImportCompletion": true,
"omnisharp.enableRoslynAnalyzers": true
}

17
.vscode/tasks.json поставляемый Normal file
Просмотреть файл

@ -0,0 +1,17 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
}
]
}

Просмотреть файл

@ -1,7 +1,7 @@
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<RepoRootPath>$([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)..\'))</RepoRootPath>
<RepoRootPath>$(MSBuildThisFileDirectory)</RepoRootPath>
<BaseIntermediateOutputPath>$(RepoRootPath)obj\$(MSBuildProjectName)\</BaseIntermediateOutputPath>
<BaseOutputPath Condition=" '$(BaseOutputPath)' == '' ">$(RepoRootPath)bin\$(MSBuildProjectName)\</BaseOutputPath>
<PackageOutputPath>$(RepoRootPath)bin\Packages\$(Configuration)\NuGet\</PackageOutputPath>
@ -19,20 +19,27 @@
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<MicroBuildVersion>2.0.61</MicroBuildVersion>
</PropertyGroup>
<TargetFramework>net472</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MicroBuild.VisualStudio" Version="$(MicroBuildVersion)" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="3.0.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.Net.Compilers.Toolset" Version="3.7.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.0" PrivateAssets="All" />
<!--<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" />-->
<PackageReference Include="Microsoft.SourceLink.AzureRepos.Git" Version="1.0.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" />
<PackageReference Include="Nerdbank.GitVersioning" Version="3.1.91" PrivateAssets="all" />
<PackageReference Include="Microsoft.Net.Compilers.Toolset" Version="3.5.0" PrivateAssets="all" />
<PackageReference Include="Nullable" Version="1.3.0" PrivateAssets="all" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.164" PrivateAssets="all" />
</ItemGroup>
<ItemGroup>
<AdditionalFiles Include="$(MSBuildThisFileDirectory)stylecop.json" Link="stylecop.json" />
</ItemGroup>
<ItemDefinitionGroup>
<!-- We always want MSBuild properties generated that point at the restored location of each package. -->
<PackageReference GeneratePathProperty="true" />
</ItemDefinitionGroup>
</Project>

16
Directory.Build.rsp Normal file
Просмотреть файл

@ -0,0 +1,16 @@
#------------------------------------------------------------------------------
# This file contains command-line options that MSBuild will process as part of
# every build, unless the "/noautoresponse" switch is specified.
#
# MSBuild processes the options in this file first, before processing the
# options on the command line. As a result, options on the command line can
# override the options in this file. However, depending on the options being
# set, the overriding can also result in conflicts.
#
# NOTE: The "/noautoresponse" switch cannot be specified in this file, nor in
# any response file that is referenced by this file.
#------------------------------------------------------------------------------
/nr:false
/m
/verbosity:minimal
/clp:Summary;ForceNoAlign

2
Directory.Build.targets Normal file
Просмотреть файл

@ -0,0 +1,2 @@
<Project>
</Project>

Просмотреть файл

@ -3,20 +3,20 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29824.212
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.VisualStudio.Sdk.TestFramework", "Microsoft.VisualStudio.Sdk.TestFramework\Microsoft.VisualStudio.Sdk.TestFramework.csproj", "{A62E3D92-0B5C-4D53-9269-EAC253BBCDEE}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.VisualStudio.Sdk.TestFramework", "src\Microsoft.VisualStudio.Sdk.TestFramework\Microsoft.VisualStudio.Sdk.TestFramework.csproj", "{A62E3D92-0B5C-4D53-9269-EAC253BBCDEE}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.VisualStudio.Sdk.TestFramework.Tests", "Microsoft.VisualStudio.Sdk.TestFramework.Tests\Microsoft.VisualStudio.Sdk.TestFramework.Tests.csproj", "{94569D82-0C5E-4437-AADF-67738037ED9D}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = ".VisualStudio.Sdk.TestFramework.Tests", "test\Microsoft.VisualStudio.Sdk.TestFramework.Tests\Microsoft.VisualStudio.Sdk.TestFramework.Tests.csproj", "{94569D82-0C5E-4437-AADF-67738037ED9D}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{824473EA-BB16-47EE-96CA-CD854BF62276}"
ProjectSection(SolutionItems) = preProject
..\.gitignore = ..\.gitignore
.gitignore = .gitignore
Directory.Build.props = Directory.Build.props
Directory.Build.targets = Directory.Build.targets
..\global.json = ..\global.json
..\nuget.config = ..\nuget.config
..\README.md = ..\README.md
global.json = global.json
nuget.config = nuget.config
README.md = README.md
stylecop.json = stylecop.json
..\version.json = ..\version.json
version.json = version.json
EndProjectSection
EndProject
Global

128
README.md
Просмотреть файл

@ -1,129 +1,39 @@
# Visual Studio SDK Test Framework
[![NuGet package](https://img.shields.io/nuget/v/Microsoft.VisualStudio.Sdk.TestFramework.svg)](https://nuget.org/packages/Microsoft.VisualStudio.Sdk.TestFramework)
<!-- [![Build Status](https://dev.azure.com/azure-public/vside/_apis/build/status/vssdktestfx)](https://dev.azure.com/azure-public/vside/_build/latest?definitionId=12) -->
[![Join the chat at https://gitter.im/Microsoft/extendvs](https://badges.gitter.im/extendvs/Lobby.svg)](https://gitter.im/Microsoft/extendvs)
The VS SDK Test Framework is a library for your unit tests that exercise VS code to use
so that certain core VS functionality works outside the VS process so your unit tests can function.
For example, `ThreadHelper` and obtaining global services from the static `ServiceProvider`
tend to fail in unit tests without this library installed.
## Referencing
## Consuming this test framework
### For tests that build outside the VS repo:
**Microsoft Internal users**: See [specific guidance if consuming within the `VS` repo](doc/vs_repo.md).
To reference this test framework outside the VS repo,
you will need these feeds as package sources in your [nuget.config file](https://docs.microsoft.com/en-us/nuget/schema/nuget-config-file#packagesources):
1. Install the NuGet package: [![NuGet package](https://img.shields.io/nuget/v/Microsoft.VisualStudio.Sdk.TestFramework.svg)](https://nuget.org/packages/Microsoft.VisualStudio.Sdk.TestFramework)
https://api.nuget.org/v3/index.json (this is the default feed)
https://pkgs.dev.azure.com/devdiv/_packaging/vs-impl/nuget/v3/index.json"
1. Make sure your unit test project generates the required binding redirects by adding these two properties to your project file:
Then install its NuGet package:
```xml
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
```
Install-Package Microsoft.VisualStudio.Sdk.TestFramework -Pre
1. Apply some changes to your test project source as appropriate given the test framework you're already using:
Make sure your unit test project generates the required binding redirects by adding these two properties to your project file:
* [Xunit](doc/xunit.md)
* [MSTest](doc/mstest.md)
```xml
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
```
### For tests that build within the VS repo:
Add this import to your project:
```xml
<Import Project="$(SrcRoot)\Tests\vssdktestfx.targets" />
```
Remove any references to an App.config or App.config.tt file from your test project
since this is now generated during the build automatically.
## Unit test source code changes
### Xunit instructions
Add this class to your project (if a MockedVS.cs file was not added to your project automatically):
```csharp
using Xunit;
using Microsoft.VisualStudio.Sdk.TestFramework;
/// <summary>
/// Defines the "MockedVS" xunit test collection.
/// </summary>
[CollectionDefinition(Collection)]
public class MockedVS : ICollectionFixture<GlobalServiceProvider>, ICollectionFixture<MefHostingFixture>
{
/// <summary>
/// The name of the xunit test collection.
/// </summary>
public const string Collection = "MockedVS";
}
```
Then for *each* of your test classes, apply the `Collection` attribute and
add a parameter and statement to your constructor:
```csharp
using Microsoft.VisualStudio.Sdk.TestFramework;
[Collection(MockedVS.Collection)]
public class YourTestClass
{
public TestFrameworkTests(GlobalServiceProvider sp)
{
sp.Reset();
}
}
```
### MSTest instructions
Add these members to *one* of your test classes:
```csharp
using Microsoft.VisualStudio.Sdk.TestFramework;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class AssemblyFixture
{
internal static GlobalServiceProvider MockServiceProvider { get; private set; }
[AssemblyInitialize]
public static void AssemblyInit(TestContext context)
{
MockServiceProvider = new GlobalServiceProvider();
}
[AssemblyCleanup]
public static void AssemblyCleanup()
{
MockServiceProvider.Dispose();
}
}
```
Then in *each* of your test classes, Reset() the static service provider created earlier:
```csharp
using Microsoft.VisualStudio.Sdk.TestFramework;
[TestInitialize]
public void TestInit()
{
AssemblyFixture.MockServiceProvider.Reset();
}
```
For a sample of applying this pattern to an MSTest project within the VS repo, check out [this pull request](https://devdiv.visualstudio.com/DevDiv/default/_git/VS/pullrequest/57056?_a=files&path=%2Fsrc%2Fenv%2Fshell%2FConnected%2Ftests).
## Main Thread considerations
### Main Thread considerations
This library will create a mocked up UI thread, such that `ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync()`
can switch to it. Your unit tests do *not* start on this mocked up UI thread. If your product code contains checks
that it is invoked on the UI thread (e.g. `ThreadHelper.ThrowIfNotOnUIThread()`) your test method should look like this:
```csharp
```cs
[TestMethod] // or [Fact]
public async Task VerifyWeDoSomethingGood()
{
@ -132,7 +42,7 @@ public async Task VerifyWeDoSomethingGood()
}
```
## Built in service mocks
### Built in service mocks
There are a collection of "base services" that the VSSDKTestFx comes with mocks for.
Calling `GlobalServiceProvider.AddService` for any of these will result in an `InvalidOperationException` being thrown claiming
@ -145,7 +55,7 @@ These services include:
* `SVsTaskSchedulerService`
* `SVsUIThreadInvokerPrivate`
More may be added and can be found in [source code](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/default/_git/VSSDKTestFx?_a=contents&path=%2Fsrc%2FMicrosoft.VisualStudio.Sdk.TestFramework%2FGlobalServiceProvider.cs&version=GBmaster&line=194&lineStyle=plain&lineEnd=198&lineStartColumn=1&lineEndColumn=1).
More may be added and can be found in [source code](https://github.com/microsoft/vssdktestfx/blob/main/src/Microsoft.VisualStudio.Sdk.TestFramework/GlobalServiceProvider.cs#L217-L224).
## Contributing

Просмотреть файл

@ -8,6 +8,7 @@ trigger:
- doc/
- '*.md'
- .vscode/
- .github/
variables:
TreatWarningsAsErrors: true

Просмотреть файл

@ -0,0 +1,14 @@
<#
.SYNOPSIS
Downloads 32-bit and 64-bit procdump executables and returns the path to where they were installed.
#>
$version = '0.0.1'
$baseDir = "$PSScriptRoot\..\obj\tools"
$procDumpToolPath = "$baseDir\procdump.$version\bin"
if (-not (Test-Path $procDumpToolPath)) {
if (-not (Test-Path $baseDir)) { New-Item -Type Directory -Path $baseDir | Out-Null }
$baseDir = (Resolve-Path $baseDir).Path # Normalize it
& (& $PSScriptRoot\Get-NuGetTool.ps1) install procdump -version $version -PackageSaveMode nuspec -OutputDirectory $baseDir -Source https://api.nuget.org/v3/index.json | Out-Null
}
(Resolve-Path $procDumpToolPath).Path

Просмотреть файл

@ -0,0 +1,14 @@
<RunSettings>
<DataCollectionRunSettings>
<DataCollectors>
<DataCollector friendlyName="blame" enabled="True">
<Configuration>
<CollectDump DumpType="full" />
<CollectDumpOnTestSessionHang TestTimeout="30000" DumpType="full" />
<!-- This ResultsDirectory must exist, but it is totally ignored. -->
<ResultsDirectory>%BUILD_ARTIFACTSTAGINGDIRECTORY%</ResultsDirectory>
</Configuration>
</DataCollector>
</DataCollectors>
</DataCollectionRunSettings>
</RunSettings>

Просмотреть файл

@ -0,0 +1,15 @@
# This artifact captures everything needed to insert into VS (NuGet packages, insertion metadata, etc.)
$RepoRoot = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
$BuildConfiguration = $env:BUILDCONFIGURATION
if (!$BuildConfiguration) {
$BuildConfiguration = 'Debug'
}
$PackagesRoot = "$RepoRoot/bin/Packages/$BuildConfiguration/NuGet"
if (!(Test-Path $PackagesRoot)) { return }
@{
"$PackagesRoot" = (Get-ChildItem $PackagesRoot -Recurse)
}

Просмотреть файл

@ -12,8 +12,11 @@ Get-ChildItem -Path (Join-Path $PSScriptRoot (Join-Path .. variables)) |% {
$value = $null
if (-not $_.BaseName.StartsWith('_')) { # Skip trying to interpret special scripts
# First check the environment variables in case the variable was set in a queued build
if (Test-Path env:$($_.BaseName)) {
$value = Get-Content "env:$($_.BaseName)"
# Always use all caps for env var access because Azure Pipelines converts variables to upper-case for env vars,
# and on non-Windows env vars are case sensitive.
$envVarName = $_.BaseName.ToUpper()
if (Test-Path env:$envVarName) {
$value = Get-Content "env:$envVarName"
}
# If that didn't give us anything, try executing the script right now from its original position

Просмотреть файл

@ -1,3 +1,5 @@
#!/usr/bin/env pwsh
# This script returns all the artifacts that should be collected after a build.
#
# Each powershell artifact is expressed as an object with these properties:
@ -28,7 +30,7 @@ Get-ChildItem "$PSScriptRoot\*.ps1" -Exclude "_*" -Recurse |% {
Write-Warning "No files found for the `"$ArtifactName`" artifact."
} else {
$fileGroups.GetEnumerator() | % {
$BaseDirectory = New-Object Uri ((EnsureTrailingSlash $_.Key), [UriKind]::Absolute)
$BaseDirectory = New-Object Uri ((EnsureTrailingSlash $_.Key.ToString()), [UriKind]::Absolute)
$_.Value | % {
if ($_.GetType() -eq [IO.FileInfo] -or $_.GetType() -eq [IO.DirectoryInfo]) {
$_ = $_.FullName

Просмотреть файл

@ -0,0 +1,12 @@
if ($env:AGENT_TEMPDIRECTORY) {
# The DotNetCoreCLI uses an alternate location to publish these files
$guidRegex = '^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$'
@{
$env:AGENT_TEMPDIRECTORY = (Get-ChildItem $env:AGENT_TEMPDIRECTORY -Directory |? { $_.Name -match $guidRegex } |% { Get-ChildItem "$($_.FullName)\testhost*.dmp","$($_.FullName)\Sequence_*.xml" -Recurse });
}
} else {
$testRoot = Resolve-Path "$PSScriptRoot\..\..\test"
@{
$testRoot = (Get-ChildItem "$testRoot\TestResults" -Recurse -Directory | Get-ChildItem -Recurse -File);
}
}

Просмотреть файл

@ -1,5 +1,7 @@
parameters:
windowsPool: Hosted Windows 2019 with VS2019
- name: windowsPool
type: string
default: Hosted Windows 2019 with VS2019
jobs:
- job: Windows
@ -9,7 +11,7 @@ jobs:
clean: true
- template: install-dependencies.yml
- powershell: '& (./azure-pipelines/Get-nbgv.ps1) cloud -p src'
- powershell: '& (./azure-pipelines/Get-nbgv.ps1) cloud'
displayName: Set build number
- ${{ if eq(variables['system.collectionId'], '011b8bdf-6d56-4f87-be0d-0092136884d9') }}:

Просмотреть файл

@ -8,34 +8,31 @@ steps:
configuration: $(BuildConfiguration)
- task: DotNetCoreCLI@2
displayName: dotnet test
displayName: dotnet test -f net472
inputs:
command: test
arguments: --no-build -c $(BuildConfiguration) --filter "TestCategory!=FailsInCloudTest" -v n /p:CollectCoverage=true
workingDirectory: src
arguments: --no-build -c $(BuildConfiguration) -f net472 --filter "TestCategory!=FailsInCloudTest" -v n /p:CollectCoverage=true --settings "$(Build.Repository.LocalPath)/azure-pipelines/$(Agent.OS).runsettings"
testRunTitle: net472-$(Agent.JobName)
condition: succeededOrFailed()
- task: PowerShell@2
inputs:
filePath: azure-pipelines/variables/_pipelines.ps1
failOnStderr: true
- powershell: azure-pipelines/variables/_pipelines.ps1
failOnStderr: true
displayName: Update pipeline variables based on build outputs
condition: succeededOrFailed()
- task: PowerShell@2
inputs:
filePath: azure-pipelines/artifacts/_pipelines.ps1
arguments: -ArtifactNameSuffix "-$(Agent.JobName)"
- powershell: azure-pipelines/artifacts/_pipelines.ps1 -ArtifactNameSuffix "-$(Agent.JobName)"
failOnStderr: true
displayName: Publish artifacts
condition: succeededOrFailed()
- task: PublishSymbols@2
inputs:
SymbolsFolder: $(Build.ArtifactStagingDirectory)/symbols-Windows
SymbolsFolder: $(Build.ArtifactStagingDirectory)/symbols-$(Agent.JobName)
SearchPattern: '**/*.pdb'
IndexSources: false
SymbolServerType: TeamServices
displayName: Publish symbols to symbol server
condition: and(succeeded(), ne(variables['Build.Reason'], 'PullRequest'))
condition: and(succeeded(), ne(variables['Build.Reason'], 'PullRequest'), eq(variables['Agent.OS'], 'Windows_NT'))
- bash: bash <(curl -s https://codecov.io/bash)
displayName: Publish code coverage results to codecov.io

Просмотреть файл

@ -4,12 +4,12 @@ parameters:
steps:
- powershell: |
.\init.ps1 -AccessToken '$(System.AccessToken)' ${{ parameters['initArgs'] }} -UpgradePrerequisites
$AccessToken = '$(System.AccessToken)' # Avoid specifying the access token directly on the init.ps1 command line to avoid it showing up in errors
.\init.ps1 -AccessToken $AccessToken ${{ parameters['initArgs'] }} -UpgradePrerequisites
dotnet --info
displayName: Install prerequisites
- task: PowerShell@2
inputs:
filePath: azure-pipelines/variables/_pipelines.ps1
failOnStderr: true
- powershell: azure-pipelines/variables/_pipelines.ps1
failOnStderr: true
displayName: Set pipeline variables based on source
name: SetPipelineVariables

Просмотреть файл

@ -23,5 +23,7 @@ steps:
/repoName:$(Build.Repository.Name)
/additionalCodexArguments:-bld
/additionalCodexArguments:$(Build.ArtifactStagingDirectory)/build_logs
condition: and(succeeded(), ne(variables['Build.Reason'], 'PullRequest'))
condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'), ne(variables['Build.Reason'], 'PullRequest'))
continueOnError: true
- template: secure-development-tools.yml

Просмотреть файл

@ -1,5 +1,5 @@
steps:
- task: MicroBuildSigningPlugin@2
- task: MicroBuildSigningPlugin@3
inputs:
signType: $(SignType)
zipSources: false

Просмотреть файл

@ -2,6 +2,7 @@ trigger:
branches:
include:
- main
- microbuild
- 'validate/*'
paths:
exclude:
@ -9,16 +10,82 @@ trigger:
- '*.md'
- .vscode/
variables:
TreatWarningsAsErrors: true
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true
BuildConfiguration: Release
BuildPlatform: Any CPU
push_to_ci: true
NUGET_PACKAGES: $(Agent.TempDirectory)/.nuget/packages
ci_feed: vs-impl
parameters:
- name: SignTypeSelection
displayName: Sign type
type: string
default: Test
values: [ 'Test', 'Real' ]
jobs:
- template: build.yml
parameters:
windowsPool: VSEng-MicroBuildVS2019
stages:
- stage: Build
variables:
TreatWarningsAsErrors: true
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true
BuildConfiguration: Release
BuildPlatform: Any CPU
push_to_ci: true
NUGET_PACKAGES: $(Agent.TempDirectory)/.nuget/packages
SignTypeSelection: ${{ parameters.SignTypeSelection }}
jobs:
- template: build.yml
parameters:
windowsPool: VSEng-MicroBuildVS2019
- stage: symbol_archive
displayName: Symbol archival
condition: and(succeeded(), eq(dependencies.Build.outputs['Windows.SetPipelineVariables.SignType'], 'Real'))
jobs:
- job: archive
pool: VSEng-ReleasePool
steps:
- download: current
artifact: Variables-Windows
displayName: Download Variables-Windows artifact
- task: PowerShell@2
displayName: Set VSTS variables based on artifacts
inputs:
targetType: filePath
filePath: $(Pipeline.Workspace)/Variables-Windows/_pipelines.ps1
- download: current
artifact: symbols-Windows
displayName: Download symbols-Windows artifact
- task: MicroBuildArchiveSymbols@1
displayName: Archive $(SymbolsFeatureName) on Symweb
inputs:
SymbolsFeatureName: $(SymbolsFeatureName)
SymbolsSymwebProject: VS
SymbolsUncPath: \\cpvsbuild\drops\$(TeamName)\$(Build.DefinitionName)\$(Build.SourceBranchName)\$(Build.BuildNumber)\Symbols.Archival
SymbolsEmailContacts: vsidemicrobuild
SymbolsAgentPath: $(Pipeline.Workspace)/symbols-Windows
- task: MicroBuildCleanup@1
displayName: Send Telemetry
- stage: azure_public_vssdk_feed
displayName: azure-public/vssdk feed
condition: and(succeeded(), eq(dependencies.Build.outputs['Windows.SetPipelineVariables.SignType'], 'Real'))
jobs:
- deployment: push
pool:
vmImage: ubuntu-latest
environment: No-Approval
strategy:
runOnce:
deploy:
steps:
- download: current
artifact: deployables-Windows
displayName: Download deployables-Windows artifact
- task: NuGetToolInstaller@1
displayName: Use NuGet 5.x
inputs:
versionSpec: 5.x
- task: NuGetCommand@2
displayName: NuGet push
inputs:
command: push
packagesToPush: $(Pipeline.Workspace)/deployables-Windows/NuGet/*.nupkg
nuGetFeedType: external
publishFeedCredentials: azure-public/vssdk

Просмотреть файл

@ -0,0 +1,23 @@
steps:
- download: current
artifact: coverageResults-Windows
displayName: Download Windows code coverage results
continueOnError: true
- powershell: |
dotnet tool install --tool-path obj dotnet-reportgenerator-globaltool --version 4.2.2 --configfile azure-pipelines/justnugetorg.nuget.config
Copy-Item -Recurse $(Pipeline.Workspace)/coverageResults-Windows/obj/* $(System.DefaultWorkingDirectory)/obj
Write-Host "Substituting {reporoot} with $(System.DefaultWorkingDirectory)"
$reports = Get-ChildItem -Recurse "$(Pipeline.Workspace)/coverage.*.cobertura.xml"
$reports |% {
$content = Get-Content -Path $_ |% { $_.Replace("{reporoot}", "$(System.DefaultWorkingDirectory)") }
Set-Content -Path $_ -Value $content -Encoding UTF8
}
$Inputs = [string]::join(';', ($reports |% { Resolve-Path -relative $_ }))
obj/reportgenerator -reports:"$Inputs" -targetdir:coveragereport -reporttypes:Cobertura
displayName: Merge coverage
- task: PublishCodeCoverageResults@1
displayName: Publish code coverage results to Azure DevOps
inputs:
codeCoverageTool: cobertura
summaryFileLocation: 'coveragereport/Cobertura.xml'
failIfCoverageEmpty: true

Просмотреть файл

@ -0,0 +1,19 @@
steps:
- download: current
displayName: Download deployables
artifact: deployables-Windows
- task: NuGetToolInstaller@1
displayName: Use NuGet 5.x
inputs:
versionSpec: 5.x
- task: NuGetCommand@2
displayName: Push packages to CI feed
inputs:
command: push
packagesToPush: $(Pipeline.Workspace)/deployables-Windows/NuGet/*.nupkg
nuGetFeedType: internal
publishVstsFeed: $(ci_feed)
allowPackageConflicts: true
condition: and(succeeded(), eq(variables['push_to_ci'], 'true'), ne(variables['ci_feed'], ''), ne(variables['Build.Reason'], 'PullRequest'))

Просмотреть файл

@ -0,0 +1,72 @@
trigger: none # We only want to trigger manually or based on resources
pr: none
resources:
pipelines:
- pipeline: CI
source: VSSDKTestFx
trigger:
tags:
- auto-release
stages:
- stage: GitHubRelease
displayName: GitHub Release
jobs:
- deployment: create
pool:
vmImage: ubuntu-latest
environment: No-Approval
strategy:
runOnce:
deploy:
steps:
- download: none
- powershell: |
Write-Host "##vso[build.updatebuildnumber]$(resources.pipeline.CI.runName)"
displayName: Set pipeline name
- task: GitHubRelease@1
displayName: GitHub release (create)
inputs:
gitHubConnection: AArnott
repositoryName: $(Build.Repository.Name)
target: $(resources.pipeline.CI.sourceCommit)
tagSource: userSpecifiedTag
tag: v$(resources.pipeline.CI.runName)
title: v$(resources.pipeline.CI.runName)
isDraft: true # After running this step, visit the new draft release, edit, and publish.
changeLogCompareToRelease: lastNonDraftRelease
changeLogType: issueBased
changeLogLabels: |
[
{ "label" : "bug", "displayName" : "Fixes", "state" : "closed" },
{ "label" : "enhancement", "displayName": "Enhancements", "state" : "closed" }
]
- stage: nuget_org
displayName: nuget.org
dependsOn: GitHubRelease
jobs:
- deployment: push
pool:
vmImage: ubuntu-latest
environment: No-Approval
strategy:
runOnce:
deploy:
steps:
- download: CI
artifact: deployables-Windows
displayName: Download deployables-Windows artifact
patterns: 'deployables-Windows/*'
- task: NuGetToolInstaller@1
displayName: Use NuGet 5.x
inputs:
versionSpec: 5.x
- task: NuGetCommand@2
displayName: NuGet push
inputs:
command: push
packagesToPush: $(Pipeline.Workspace)/CI/deployables-Windows/*.nupkg
nuGetFeedType: external
publishFeedCredentials: VisualStudioExtensibility (nuget.org)

Просмотреть файл

@ -0,0 +1,11 @@
steps:
### Check for checked in credentials.
- task: CredScan@3
displayName: 'Run CredScan'
### Run PoliCheck to check for disallowed terms. targetType: F indicates we're searching files and folders.
- task: PoliCheck@1
displayName: 'Run PoliCheck'
inputs:
targetType: F

Просмотреть файл

@ -1,3 +1,11 @@
if ($env:SYSTEM_COLLECTIONID -eq '011b8bdf-6d56-4f87-be0d-0092136884d9') {
'test'
}
if ($env:BUILD_REASON -eq 'Schedule') {
'real'
} else {
if ($env:SIGNTYPESELECTION) {
$env:SIGNTYPESELECTION
} else {
'test'
}
}
}

Просмотреть файл

@ -1,3 +1,5 @@
#!/usr/bin/env pwsh
# This script returns a hashtable of build variables that should be set
# at the start of a build or release definition's execution.

Просмотреть файл

@ -5,15 +5,20 @@
# what the build would do. So only set them if they have not already been set.
(& "$PSScriptRoot\_all.ps1").GetEnumerator() |% {
if (Test-Path -Path "env:$($_.Key)") {
Write-Host "Skipping setting $($_.Key) because variable is already set." -ForegroundColor Cyan
# Always use ALL CAPS for env var names since Azure Pipelines converts variable names to all caps and on non-Windows OS, env vars are case sensitive.
$keyCaps = $_.Key.ToUpper()
if (Test-Path -Path "env:$keyCaps") {
Write-Host "Skipping setting $keyCaps because variable is already set to '$(Get-Content env:$keyCaps)'." -ForegroundColor Cyan
} else {
Write-Host "$($_.Key)=$($_.Value)" -ForegroundColor Yellow
Write-Host "$keyCaps=$($_.Value)" -ForegroundColor Yellow
if ($env:TF_BUILD) {
Write-Host "##vso[task.setvariable variable=$($_.Key);]$($_.Value)"
# Create two variables: the first that can be used by its simple name and accessible only within this job.
Write-Host "##vso[task.setvariable variable=$keyCaps]$($_.Value)"
# and the second that works across jobs and stages but must be fully qualified when referenced.
Write-Host "##vso[task.setvariable variable=$keyCaps;isOutput=true]$($_.Value)"
} elseif ($env:GITHUB_ACTIONS) {
Write-Host "::set-env name=$($_.Key)::$($_.Value)"
Write-Host "::set-env name=$keyCaps::$($_.Value)"
}
Set-Item -Path "env:$($_.Key)" -Value $_.Value
Set-Item -Path "env:$keyCaps" -Value $_.Value
}
}

Просмотреть файл

@ -1,4 +1,7 @@
if ($env:SIGNTYPE -eq 'Real') {
$signType = $env:SIGNTYPE
if (!$signType) { $signType = & "$PSScriptRoot/SignType.ps1" }
if ($signType -eq 'Real') {
'09d8d03c-1ac8-456e-9274-4d2364527d99' # VSIDE-RealSigned-Release
} else {
'da484c78-f942-44ef-b197-99e2a1bef53c' # VSIDE-TestSigned-Release

Просмотреть файл

@ -0,0 +1,50 @@
trigger: none # We only want to trigger manually or based on resources
pr: none
resources:
pipelines:
- pipeline: CI
source: VSSDKTestFx
tags:
- Real signed
trigger:
tags:
- Real signed
- auto-insertion
stages:
- stage: VS
displayName: VS insertion
jobs:
- deployment: insertion
pool: VSEng-ReleasePool
environment: No-Approval
strategy:
runOnce:
deploy:
steps:
- powershell: |
Write-Host "##vso[build.updatebuildnumber]$(resources.pipeline.CI.runName)"
displayName: Set pipeline name
- template: release-deployment-prep.yml
- download: CI
artifact: VSInsertion-Windows
displayName: Download VSInsertion-Windows artifact
- task: NuGetCommand@2
displayName: Push CoreXT packages to VS feed
inputs:
command: push
packagesToPush: $(Pipeline.Workspace)/CI/VSInsertion-windows/*.nupkg
publishVstsFeed: 97a41293-2972-4f48-8c0e-05493ae82010
allowPackageConflicts: true
- task: MicroBuildInsertVsPayload@3
displayName: Insert VS Payload
inputs:
TeamName: $(TeamName)
TeamEmail: $(TeamEmail)
InsertionPayloadName: $(Build.Repository.Name) $(Build.BuildNumber)
InsertionBuildPolicy: Request Perf DDRITs
AutoCompletePR: true
AutoCompleteMergeStrategy: Squash
- task: MicroBuildCleanup@1
displayName: Send Telemetry

43
doc/mstest.md Normal file
Просмотреть файл

@ -0,0 +1,43 @@
# MSTest instructions
These instructions apply when consuming this test framework from an MSTest project.
This is just a subset of the full instructions outlined in [our README](../README.md).
Add these members to *one* of your test classes:
```csharp
using Microsoft.VisualStudio.Sdk.TestFramework;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class AssemblyFixture
{
internal static GlobalServiceProvider MockServiceProvider { get; private set; }
[AssemblyInitialize]
public static void AssemblyInit(TestContext context)
{
MockServiceProvider = new GlobalServiceProvider();
}
[AssemblyCleanup]
public static void AssemblyCleanup()
{
MockServiceProvider.Dispose();
}
}
```
Then in *each* of your test classes, Reset() the static service provider created earlier:
```csharp
using Microsoft.VisualStudio.Sdk.TestFramework;
[TestInitialize]
public void TestInit()
{
AssemblyFixture.MockServiceProvider.Reset();
}
```
For a sample of applying this pattern to an MSTest project within the VS repo, check out [this pull request](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/57056?_a=files&path=%2Fsrc%2Fenv%2Fshell%2FConnected%2Ftests).

10
doc/vs_repo.md Normal file
Просмотреть файл

@ -0,0 +1,10 @@
# Special instructions for consuming within the DevDiv `VS` repo
Add this import to your project:
```xml
<Import Project="$(SrcRoot)\Tests\vssdktestfx.targets" />
```
Remove any references to an App.config or App.config.tt file from your test project
since this is now generated during the build automatically.

39
doc/xunit.md Normal file
Просмотреть файл

@ -0,0 +1,39 @@
# Xunit instructions
These instructions apply when consuming this test framework from an Xunit project.
This is just a subset of the full instructions outlined in [our README](../README.md).
Add this class to your project (if a MockedVS.cs file was not added to your project automatically):
```csharp
using Xunit;
using Microsoft.VisualStudio.Sdk.TestFramework;
/// <summary>
/// Defines the "MockedVS" xunit test collection.
/// </summary>
[CollectionDefinition(Collection)]
public class MockedVS : ICollectionFixture<GlobalServiceProvider>, ICollectionFixture<MefHostingFixture>
{
/// <summary>
/// The name of the xunit test collection.
/// </summary>
public const string Collection = "MockedVS";
}
```
Then for *each* of your test classes, apply the `Collection` attribute and
add a parameter and statement to your constructor:
```csharp
using Microsoft.VisualStudio.Sdk.TestFramework;
[Collection(MockedVS.Collection)]
public class YourTestClass
{
public TestFrameworkTests(GlobalServiceProvider sp)
{
sp.Reset();
}
}
```

Просмотреть файл

@ -1,7 +1,7 @@
{
"sdk": {
"version": "3.1.100",
"rollForward": "latestPatch",
"version": "3.1.302",
"rollForward": "patch",
"allowPrerelease": false
}
}

Просмотреть файл

@ -1,4 +1,20 @@
@echo off
SETLOCAL
set PS1UnderCmd=1
:: Get the datetime in a format that can go in a filename.
set _my_datetime=%date%_%time%
set _my_datetime=%_my_datetime: =_%
set _my_datetime=%_my_datetime::=%
set _my_datetime=%_my_datetime:/=_%
set _my_datetime=%_my_datetime:.=_%
set CmdEnvScriptPath=%temp%\envvarscript_%_my_datetime%.cmd
powershell.exe -NoProfile -NoLogo -ExecutionPolicy bypass -Command "try { & '%~dpn0.ps1' %*; exit $LASTEXITCODE } catch { write-host $_; exit 1 }"
:: Set environment variables in the parent cmd.exe process.
IF EXIST "%CmdEnvScriptPath%" (
ENDLOCAL
CALL "%CmdEnvScriptPath%"
DEL "%CmdEnvScriptPath%"
)

Просмотреть файл

@ -1,38 +1,43 @@
#!/usr/bin/env pwsh
<#
.SYNOPSIS
Installs dependencies required to build and test the projects in this repository.
Installs dependencies required to build and test the projects in this repository.
.DESCRIPTION
This MAY not require elevation, as the SDK and runtimes are installed to a per-user location,
unless the `-InstallLocality` switch is specified directing to a per-repo or per-machine location.
See detailed help on that switch for more information.
This MAY not require elevation, as the SDK and runtimes are installed to a per-user location,
unless the `-InstallLocality` switch is specified directing to a per-repo or per-machine location.
See detailed help on that switch for more information.
The CmdEnvScriptPath environment variable may be optionally set to a path to a cmd shell script to be created (or appended to if it already exists) that will set the environment variables in cmd.exe that are set within the PowerShell environment.
This is used by init.cmd in order to reapply any new environment variables to the parent cmd.exe process that were set in the powershell child process.
.PARAMETER InstallLocality
A value indicating whether dependencies should be installed locally to the repo or at a per-user location.
Per-user allows sharing the installed dependencies across repositories and allows use of a shared expanded package cache.
Visual Studio will only notice and use these SDKs/runtimes if VS is launched from the environment that runs this script.
Per-repo allows for high isolation, allowing for a more precise recreation of the environment within an Azure Pipelines build.
When using 'repo', environment variables are set to cause the locally installed dotnet SDK to be used.
Per-repo can lead to file locking issues when dotnet.exe is left running as a build server and can be mitigated by running `dotnet build-server shutdown`.
Per-machine requires elevation and will download and install all SDKs and runtimes to machine-wide locations so all applications can find it.
A value indicating whether dependencies should be installed locally to the repo or at a per-user location.
Per-user allows sharing the installed dependencies across repositories and allows use of a shared expanded package cache.
Visual Studio will only notice and use these SDKs/runtimes if VS is launched from the environment that runs this script.
Per-repo allows for high isolation, allowing for a more precise recreation of the environment within an Azure Pipelines build.
When using 'repo', environment variables are set to cause the locally installed dotnet SDK to be used.
Per-repo can lead to file locking issues when dotnet.exe is left running as a build server and can be mitigated by running `dotnet build-server shutdown`.
Per-machine requires elevation and will download and install all SDKs and runtimes to machine-wide locations so all applications can find it.
.PARAMETER NoPrerequisites
Skips the installation of prerequisite software (e.g. SDKs, tools).
Skips the installation of prerequisite software (e.g. SDKs, tools).
.PARAMETER UpgradePrerequisites
Takes time to install prerequisites even if they are already present in case they need to be upgraded.
No effect if -NoPrerequisites is specified.
Takes time to install prerequisites even if they are already present in case they need to be upgraded.
No effect if -NoPrerequisites is specified.
.PARAMETER NoRestore
Skips the package restore step.
Skips the package restore step.
.PARAMETER Signing
Install the MicroBuild signing plugin for building test-signed builds on desktop machines.
Install the MicroBuild signing plugin for building test-signed builds on desktop machines.
.PARAMETER Localization
Install the MicroBuild localization plugin for building loc builds on desktop machines.
The environment is configured to build pseudo-loc for JPN only, but may be used to build
all languages with shipping-style loc by using the `/p:loctype=full,loclanguages=vs`
when building.
Install the MicroBuild localization plugin for building loc builds on desktop machines.
The environment is configured to build pseudo-loc for JPN only, but may be used to build
all languages with shipping-style loc by using the `/p:loctype=full,loclanguages=vs`
when building.
.PARAMETER Setup
Install the MicroBuild setup plugin for building VSIXv3 packages.
Install the MicroBuild setup plugin for building VSIXv3 packages.
.PARAMETER OptProf
Install the MicroBuild OptProf plugin for building optimized assemblies on desktop machines.
Install the MicroBuild OptProf plugin for building optimized assemblies on desktop machines.
.PARAMETER AccessToken
An optional access token for authenticating to Azure Artifacts authenticated feeds.
An optional access token for authenticating to Azure Artifacts authenticated feeds.
#>
[CmdletBinding(SupportsShouldProcess=$true)]
Param (
@ -56,9 +61,20 @@ Param (
[string]$AccessToken
)
$EnvVars = @{}
if (!$NoPrerequisites) {
& "$PSScriptRoot\tools\Install-NuGetCredProvider.ps1" -AccessToken $AccessToken -Force:$UpgradePrerequisites
& "$PSScriptRoot\tools\Install-DotNetSdk.ps1" -InstallLocality $InstallLocality
if ($LASTEXITCODE -eq 3010) {
Exit 3010
}
# The procdump tool and env var is required for dotnet test to collect hang/crash dumps of tests.
# But it only works on Windows.
if ($env:OS -eq 'Windows_NT') {
$EnvVars['PROCDUMP_PATH'] = & "$PSScriptRoot\azure-pipelines\Get-ProcDump.ps1"
}
}
# Workaround nuget credential provider bug that causes very unreliable package restores on Azure Pipelines
@ -71,13 +87,12 @@ try {
if (!$NoRestore -and $PSCmdlet.ShouldProcess("NuGet packages", "Restore")) {
Write-Host "Restoring NuGet packages" -ForegroundColor $HeaderColor
dotnet restore src
dotnet restore
if ($lastexitcode -ne 0) {
throw "Failure while restoring packages."
}
}
$EnvVars = @{}
$InstallNuGetPkgScriptPath = ".\azure-pipelines\Install-NuGetPackage.ps1"
$nugetVerbosity = 'quiet'
if ($Verbose) { $nugetVerbosity = 'normal' }
@ -106,7 +121,7 @@ try {
$EnvVars['LocLanguages'] = "JPN"
}
& "$PSScriptRoot\azure-pipelines\Set-EnvVars.ps1" -Variables $EnvVars | Out-Null
& "$PSScriptRoot/tools/Set-EnvVars.ps1" -Variables $EnvVars | Out-Null
}
catch {
Write-Error $error[0]

Просмотреть файл

@ -6,8 +6,6 @@
<packageSources>
<clear />
<add key="api.nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
<!-- These next two should eventually be upstreams of the private vs-impl above, but until then... -->
<add key="vs-impl-public" value="https://pkgs.dev.azure.com/azure-public/vside/_packaging/vs-impl/nuget/v3/index.json" protocolVersion="3" />
<add key="vssdk-public" value="https://pkgs.dev.azure.com/azure-public/vside/_packaging/vssdk/nuget/v3/index.json" protocolVersion="3" />
</packageSources>

Просмотреть файл

@ -1,24 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net472</TargetFramework>
<NoWarn>$(NoWarn);CS1591</NoWarn>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
<CodeAnalysisRuleSet>..\tests.ruleset</CodeAnalysisRuleSet>
<RootNamespace />
</PropertyGroup>
<ItemGroup>
<Compile Include="..\Microsoft.VisualStudio.Sdk.TestFramework\content\MockedVS.cs">
<Link>MockedVS.cs</Link>
</Compile>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Microsoft.VisualStudio.Sdk.TestFramework\Microsoft.VisualStudio.Sdk.TestFramework.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="coverlet.msbuild" Version="2.8.1" />
<PackageReference Include="MicroBuild.NonShipping" Version="$(MicroBuildVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.6.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" />
<PackageReference Include="xunit" Version="2.4.1" />
</ItemGroup>
</Project>

Просмотреть файл

@ -1,7 +1,5 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net472</TargetFramework>
<CodeAnalysisRuleSet>..\shipping.ruleset</CodeAnalysisRuleSet>
<Description>A test library to help in writing unit and integration tests for Visual Studio extensions.</Description>
<Authors>Andrew Arnott</Authors>
<Company>Microsoft</Company>

Просмотреть файл

@ -1,74 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="Microsoft Managed Recommended Rules" Description="These rules focus on the most critical problems in your code, including potential security holes, application crashes, and other important logic and design errors. It is recommended to include this rule set in any custom rule set you create for your projects." ToolsVersion="10.0">
<Localization ResourceAssembly="Microsoft.VisualStudio.CodeAnalysis.RuleSets.Strings.dll" ResourceBaseName="Microsoft.VisualStudio.CodeAnalysis.RuleSets.Strings.Localized">
<Name Resource="MinimumRecommendedRules_Name" />
<Description Resource="MinimumRecommendedRules_Description" />
</Localization>
<Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed">
<Rule Id="CA1001" Action="Warning" />
<Rule Id="CA1009" Action="Warning" />
<Rule Id="CA1016" Action="Warning" />
<Rule Id="CA1033" Action="Warning" />
<Rule Id="CA1049" Action="Warning" />
<Rule Id="CA1060" Action="Warning" />
<Rule Id="CA1061" Action="Warning" />
<Rule Id="CA1063" Action="Warning" />
<Rule Id="CA1065" Action="Warning" />
<Rule Id="CA1301" Action="Warning" />
<Rule Id="CA1400" Action="Warning" />
<Rule Id="CA1401" Action="Warning" />
<Rule Id="CA1403" Action="Warning" />
<Rule Id="CA1404" Action="Warning" />
<Rule Id="CA1405" Action="Warning" />
<Rule Id="CA1410" Action="Warning" />
<Rule Id="CA1415" Action="Warning" />
<Rule Id="CA1821" Action="Warning" />
<Rule Id="CA1900" Action="Warning" />
<Rule Id="CA1901" Action="Warning" />
<Rule Id="CA2002" Action="Warning" />
<Rule Id="CA2100" Action="Warning" />
<Rule Id="CA2101" Action="Warning" />
<Rule Id="CA2108" Action="Warning" />
<Rule Id="CA2111" Action="Warning" />
<Rule Id="CA2112" Action="Warning" />
<Rule Id="CA2114" Action="Warning" />
<Rule Id="CA2116" Action="Warning" />
<Rule Id="CA2117" Action="Warning" />
<Rule Id="CA2122" Action="Warning" />
<Rule Id="CA2123" Action="Warning" />
<Rule Id="CA2124" Action="Warning" />
<Rule Id="CA2126" Action="Warning" />
<Rule Id="CA2131" Action="Warning" />
<Rule Id="CA2132" Action="Warning" />
<Rule Id="CA2133" Action="Warning" />
<Rule Id="CA2134" Action="Warning" />
<Rule Id="CA2137" Action="Warning" />
<Rule Id="CA2138" Action="Warning" />
<Rule Id="CA2140" Action="Warning" />
<Rule Id="CA2141" Action="Warning" />
<Rule Id="CA2146" Action="Warning" />
<Rule Id="CA2147" Action="Warning" />
<Rule Id="CA2149" Action="Warning" />
<Rule Id="CA2200" Action="Warning" />
<Rule Id="CA2202" Action="Warning" />
<Rule Id="CA2207" Action="Warning" />
<Rule Id="CA2212" Action="Warning" />
<Rule Id="CA2213" Action="Warning" />
<Rule Id="CA2214" Action="Warning" />
<Rule Id="CA2216" Action="Warning" />
<Rule Id="CA2220" Action="Warning" />
<Rule Id="CA2229" Action="Warning" />
<Rule Id="CA2231" Action="Warning" />
<Rule Id="CA2232" Action="Warning" />
<Rule Id="CA2235" Action="Warning" />
<Rule Id="CA2236" Action="Warning" />
<Rule Id="CA2237" Action="Warning" />
<Rule Id="CA2238" Action="Warning" />
<Rule Id="CA2240" Action="Warning" />
<Rule Id="CA2241" Action="Warning" />
<Rule Id="CA2242" Action="Warning" />
</Rules>
<Rules AnalyzerId="StyleCop.Analyzers" RuleNamespace="StyleCop.Analyzers">
<Rule Id="SA1130" Action="None" />
</Rules>
</RuleSet>

Просмотреть файл

@ -1,22 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="Microsoft Managed Recommended Rules" Description="These rules focus on the most critical problems in your code, including potential security holes, application crashes, and other important logic and design errors. It is recommended to include this rule set in any custom rule set you create for your projects." ToolsVersion="10.0">
<Include Path="shipping.ruleset" Action="Default" />
<Rules AnalyzerId="StyleCop.Analyzers" RuleNamespace="StyleCop.Analyzers">
<Rule Id="SA1600" Action="Hidden" />
<Rule Id="SA1601" Action="Hidden" />
<Rule Id="SA1602" Action="Hidden" />
<Rule Id="SA1615" Action="Hidden" />
</Rules>
<Rules AnalyzerId="Microsoft.VisualStudio.Threading.Analyzers" RuleNamespace="Microsoft.VisualStudio.Threading.Analyzers">
<Rule Id="VSTHRD103" Action="Hidden" />
<Rule Id="VSTHRD111" Action="None" />
<Rule Id="VSTHRD200" Action="Hidden" />
</Rules>
<Rules AnalyzerId="Microsoft.NetCore.Analyzers" RuleNamespace="Microsoft.NetCore.Analyzers">
<Rule Id="CA1303" Action="None" />
</Rules>
<Rules AnalyzerId="Microsoft.CodeQuality.Analyzers" RuleNamespace="Microsoft.CodeQuality.Analyzers">
<Rule Id="CA2007" Action="Hidden" />
<Rule Id="CA1707" Action="Hidden" />
</Rules>
</RuleSet>

Просмотреть файл

43
test/.editorconfig Normal file
Просмотреть файл

@ -0,0 +1,43 @@
[*.cs]
# SA1600: Elements should be documented
dotnet_diagnostic.SA1600.severity = silent
# SA1601: Partial elements should be documented
dotnet_diagnostic.SA1601.severity = silent
# SA1602: Enumeration items should be documented
dotnet_diagnostic.SA1602.severity = silent
# SA1615: Element return value should be documented
dotnet_diagnostic.SA1615.severity = silent
# VSTHRD103: Call async methods when in an async method
dotnet_diagnostic.VSTHRD103.severity = silent
# VSTHRD111: Use .ConfigureAwait(bool)
dotnet_diagnostic.VSTHRD111.severity = none
# VSTHRD200: Use Async suffix for async methods
dotnet_diagnostic.VSTHRD200.severity = silent
# CA1303: Do not pass literals as localized parameters
dotnet_diagnostic.CA1303.severity = none
# CS1591: Missing XML comment for publicly visible type or member
dotnet_diagnostic.CS1591.severity = silent
# CA1707: Identifiers should not contain underscores
dotnet_diagnostic.CA1707.severity = silent
# CA1062: Validate arguments of public methods
dotnet_diagnostic.CA1062.severity = suggestion
# CA1063: Implement IDisposable Correctly
dotnet_diagnostic.CA1063.severity = silent
# CA1816: Dispose methods should call SuppressFinalize
dotnet_diagnostic.CA1816.severity = silent
# CA2007: Consider calling ConfigureAwait on the awaited task
dotnet_diagnostic.CA2007.severity = none

Просмотреть файл

@ -0,0 +1,12 @@
<Project>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory)../, Directory.Build.props))\Directory.Build.props" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory)../, Directory.Build.props))' != '' " />
<PropertyGroup>
<IsPackable>false</IsPackable>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MicroBuild.NonShipping" Version="$(MicroBuildVersion)" />
</ItemGroup>
</Project>

Просмотреть файл

@ -5,4 +5,6 @@
<!-- Ensure we preserve each coverlet output file per target framework: https://github.com/tonerdo/coverlet/issues/177 -->
<CoverletOutput>$(OutputPath)/</CoverletOutput>
</PropertyGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory)../, Directory.Build.targets))\Directory.Build.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory)../, Directory.Build.targets))' != '' " />
</Project>

Просмотреть файл

@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<RootNamespace />
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\Microsoft.VisualStudio.Sdk.TestFramework\content\MockedVS.cs">
<Link>MockedVS.cs</Link>
</Compile>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Microsoft.VisualStudio.Sdk.TestFramework\Microsoft.VisualStudio.Sdk.TestFramework.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="coverlet.msbuild" Version="2.9.0" />
<PackageReference Include="MicroBuild.NonShipping" Version="$(MicroBuildVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" />
<PackageReference Include="xunit" Version="2.4.1" />
</ItemGroup>
</Project>

Просмотреть файл

@ -0,0 +1,41 @@
<#
.SYNOPSIS
Checks whether a given .NET Core runtime is installed.
#>
[CmdletBinding()]
Param (
[Parameter()]
[ValidateSet('Microsoft.AspNetCore.App','Microsoft.NETCore.App')]
[string]$Runtime='Microsoft.NETCore.App',
[Parameter(Mandatory=$true)]
[Version]$Version
)
$dotnet = Get-Command dotnet -ErrorAction SilentlyContinue
if (!$dotnet) {
# Nothing is installed.
Write-Output $false
exit 1
}
Function IsVersionMatch {
Param(
[Parameter()]
$actualVersion
)
return $actualVersion -and
$Version.Major -eq $actualVersion.Major -and
$Version.Minor -eq $actualVersion.Minor -and
(($Version.Build -eq -1) -or ($Version.Build -eq $actualVersion.Build)) -and
(($Version.Revision -eq -1) -or ($Version.Revision -eq $actualVersion.Revision))
}
$installedRuntimes = dotnet --list-runtimes |? { $_.Split()[0] -ieq $Runtime } |% { $v = $null; [Version]::tryparse($_.Split()[1], [ref] $v); $v }
$matchingRuntimes = $installedRuntimes |? { IsVersionMatch -actualVersion $_ }
if (!$matchingRuntimes) {
Write-Output $false
exit 1
}
Write-Output $true
exit 0

37
tools/Check-DotNetSdk.ps1 Normal file
Просмотреть файл

@ -0,0 +1,37 @@
<#
.SYNOPSIS
Checks whether the .NET Core SDK required by this repo is installed.
#>
[CmdletBinding()]
Param (
)
$dotnet = Get-Command dotnet -ErrorAction SilentlyContinue
if (!$dotnet) {
# Nothing is installed.
Write-Output $false
exit 1
}
# We need to set the current directory so dotnet considers the SDK required by our global.json file.
Push-Location "$PSScriptRoot\.."
try {
dotnet -h 2>&1 | Out-Null
if (($LASTEXITCODE -eq 129) -or # On Linux
($LASTEXITCODE -eq -2147450751) # On Windows
) {
# These exit codes indicate no matching SDK exists.
Write-Output $false
exit 2
}
# The required SDK is already installed!
Write-Output $true
exit 0
} catch {
# I don't know why, but on some build agents (e.g. MicroBuild), an exception is thrown from the `dotnet` invocation when a match is not found.
Write-Output $false
exit 3
} finally {
Pop-Location
}

Просмотреть файл

@ -1,18 +1,20 @@
#!/usr/bin/env pwsh
<#
.SYNOPSIS
Installs the .NET SDK specified in the global.json file at the root of this repository,
along with supporting .NET Core runtimes used for testing.
Installs the .NET SDK specified in the global.json file at the root of this repository,
along with supporting .NET Core runtimes used for testing.
.DESCRIPTION
This MAY not require elevation, as the SDK and runtimes are installed locally to this repo location,
unless `-InstallLocality machine` is specified.
This MAY not require elevation, as the SDK and runtimes are installed locally to this repo location,
unless `-InstallLocality machine` is specified.
.PARAMETER InstallLocality
A value indicating whether dependencies should be installed locally to the repo or at a per-user location.
Per-user allows sharing the installed dependencies across repositories and allows use of a shared expanded package cache.
Visual Studio will only notice and use these SDKs/runtimes if VS is launched from the environment that runs this script.
Per-repo allows for high isolation, allowing for a more precise recreation of the environment within an Azure Pipelines build.
When using 'repo', environment variables are set to cause the locally installed dotnet SDK to be used.
Per-repo can lead to file locking issues when dotnet.exe is left running as a build server and can be mitigated by running `dotnet build-server shutdown`.
Per-machine requires elevation and will download and install all SDKs and runtimes to machine-wide locations so all applications can find it.
A value indicating whether dependencies should be installed locally to the repo or at a per-user location.
Per-user allows sharing the installed dependencies across repositories and allows use of a shared expanded package cache.
Visual Studio will only notice and use these SDKs/runtimes if VS is launched from the environment that runs this script.
Per-repo allows for high isolation, allowing for a more precise recreation of the environment within an Azure Pipelines build.
When using 'repo', environment variables are set to cause the locally installed dotnet SDK to be used.
Per-repo can lead to file locking issues when dotnet.exe is left running as a build server and can be mitigated by running `dotnet build-server shutdown`.
Per-machine requires elevation and will download and install all SDKs and runtimes to machine-wide locations so all applications can find it.
#>
[CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact='Medium')]
Param (
@ -21,7 +23,7 @@ Param (
)
$DotNetInstallScriptRoot = "$PSScriptRoot/../obj/tools"
if (!(Test-Path $DotNetInstallScriptRoot)) { New-Item -ItemType Directory -Path $DotNetInstallScriptRoot | Out-Null }
if (!(Test-Path $DotNetInstallScriptRoot)) { New-Item -ItemType Directory -Path $DotNetInstallScriptRoot -WhatIf:$false | Out-Null }
$DotNetInstallScriptRoot = Resolve-Path $DotNetInstallScriptRoot
# Look up actual required .NET Core SDK version from global.json
@ -29,7 +31,7 @@ $sdkVersion = & "$PSScriptRoot/../azure-pipelines/variables/DotNetSdkVersion.ps1
# Search for all .NET Core runtime versions referenced from MSBuild projects and arrange to install them.
$runtimeVersions = @()
Get-ChildItem "$PSScriptRoot\..\src\*.*proj" -Recurse |% {
Get-ChildItem "$PSScriptRoot\..\src\*.*proj","$PSScriptRoot\..\test\*.*proj","$PSScriptRoot\..\Directory.Build.props" -Recurse |% {
$projXml = [xml](Get-Content -Path $_)
$targetFrameworks = $projXml.Project.PropertyGroup.TargetFramework
if (!$targetFrameworks) {
@ -75,31 +77,14 @@ Function Install-DotNet($Version, [switch]$Runtime) {
Write-Host "Downloading .NET Core $sdkSubstring$Version..."
$Installer = Get-InstallerExe -Version $Version -Runtime:$Runtime
Write-Host "Installing .NET Core $sdkSubstring$Version..."
cmd /c start /wait $Installer /install /quiet
if ($LASTEXITCODE -ne 0) {
cmd /c start /wait $Installer /install /passive /norestart
if ($LASTEXITCODE -eq 3010) {
Write-Verbose "Restart required"
} elseif ($LASTEXITCODE -ne 0) {
throw "Failure to install .NET Core SDK"
}
}
if ($InstallLocality -eq 'machine') {
if ($IsMacOS -or $IsLinux) {
Write-Error "Installing the .NET Core SDK or runtime at a machine-wide location is only supported by this script on Windows."
exit 1
}
if ($PSCmdlet.ShouldProcess(".NET Core SDK $sdkVersion", "Install")) {
Install-DotNet -Version $sdkVersion
}
$runtimeVersions |% {
if ($PSCmdlet.ShouldProcess(".NET Core runtime $_", "Install")) {
Install-DotNet -Version $_ -Runtime
}
}
return
}
$switches = @(
'-Architecture','x64'
)
@ -108,7 +93,31 @@ $envVars = @{
'DOTNET_SKIP_FIRST_TIME_EXPERIENCE' = 'true';
}
if ($InstallLocality -eq 'repo') {
if ($InstallLocality -eq 'machine') {
if ($IsMacOS -or $IsLinux) {
$DotNetInstallDir = '/usr/share/dotnet'
} else {
$restartRequired = $false
if ($PSCmdlet.ShouldProcess(".NET Core SDK $sdkVersion", "Install")) {
Install-DotNet -Version $sdkVersion
$restartRequired = $restartRequired -or ($LASTEXITCODE -eq 3010)
}
$runtimeVersions | Get-Unique |% {
if ($PSCmdlet.ShouldProcess(".NET Core runtime $_", "Install")) {
Install-DotNet -Version $_ -Runtime
$restartRequired = $restartRequired -or ($LASTEXITCODE -eq 3010)
}
}
if ($restartRequired) {
Write-Host -ForegroundColor Yellow "System restart required"
Exit 3010
}
return
}
} elseif ($InstallLocality -eq 'repo') {
$DotNetInstallDir = "$DotNetInstallScriptRoot/.dotnet"
} elseif ($env:AGENT_TOOLSDIRECTORY) {
$DotNetInstallDir = "$env:AGENT_TOOLSDIRECTORY/dotnet"
@ -139,7 +148,10 @@ if (-not (Test-Path $DotNetInstallScriptPath)) {
}
}
$anythingInstalled = $false
if ($PSCmdlet.ShouldProcess(".NET Core SDK $sdkVersion", "Install")) {
$anythingInstalled = $true
Invoke-Expression -Command "$DotNetInstallScriptPath -Version $sdkVersion $switches"
} else {
Invoke-Expression -Command "$DotNetInstallScriptPath -Version $sdkVersion $switches -DryRun"
@ -149,6 +161,7 @@ $switches += '-Runtime','dotnet'
$runtimeVersions | Get-Unique |% {
if ($PSCmdlet.ShouldProcess(".NET Core runtime $_", "Install")) {
$anythingInstalled = $true
Invoke-Expression -Command "$DotNetInstallScriptPath -Channel $_ $switches"
} else {
Invoke-Expression -Command "$DotNetInstallScriptPath -Channel $_ $switches -DryRun"
@ -156,5 +169,9 @@ $runtimeVersions | Get-Unique |% {
}
if ($PSCmdlet.ShouldProcess("Set DOTNET environment variables to discover these installed runtimes?")) {
& "$PSScriptRoot/../azure-pipelines/Set-EnvVars.ps1" -Variables $envVars -PrependPath $DotNetInstallDir | Out-Null
& "$PSScriptRoot/Set-EnvVars.ps1" -Variables $envVars -PrependPath $DotNetInstallDir | Out-Null
}
if ($anythingInstalled -and ($InstallLocality -ne 'machine') -and !$env:TF_BUILD -and !$env:GITHUB_ACTIONS) {
Write-Warning ".NET Core runtimes or SDKs were installed to a non-machine location. Perform your builds or open Visual Studio from this same environment in order for tools to discover the location of these dependencies."
}

Просмотреть файл

@ -1,3 +1,5 @@
#!/usr/bin/env pwsh
<#
.SYNOPSIS
Downloads and installs the Microsoft Artifacts Credential Provider
@ -17,6 +19,8 @@ Param (
[string]$AccessToken
)
$envVars = @{}
$toolsPath = & "$PSScriptRoot\..\azure-pipelines\Get-TempToolsPath.ps1"
if ($IsMacOS -or $IsLinux) {
@ -44,23 +48,29 @@ if ($IsMacOS -or $IsLinux) {
if ($AccessToken) {
$endpoints = @()
$nugetConfig = [xml](Get-Content -Path "$PSScriptRoot\..\nuget.config")
$endpointURIs = @()
Get-ChildItem "$PSScriptRoot\..\nuget.config" -Recurse |% {
$nugetConfig = [xml](Get-Content -Path $_)
$nugetConfig.configuration.packageSources.add |? { ($_.value -match '^https://pkgs\.dev\.azure\.com/') -or ($_.value -match '^https://[\w\-]+\.pkgs\.visualstudio\.com/') } |% {
$endpoint = New-Object -TypeName PSObject
Add-Member -InputObject $endpoint -MemberType NoteProperty -Name endpoint -Value $_.value
Add-Member -InputObject $endpoint -MemberType NoteProperty -Name username -Value ado
Add-Member -InputObject $endpoint -MemberType NoteProperty -Name password -Value $AccessToken
$endpoints += $endpoint
$nugetConfig.configuration.packageSources.add |? { ($_.value -match '^https://pkgs\.dev\.azure\.com/') -or ($_.value -match '^https://[\w\-]+\.pkgs\.visualstudio\.com/') } |% {
if ($endpointURIs -notcontains $_.Value) {
$endpointURIs += $_.Value
$endpoint = New-Object -TypeName PSObject
Add-Member -InputObject $endpoint -MemberType NoteProperty -Name endpoint -Value $_.value
Add-Member -InputObject $endpoint -MemberType NoteProperty -Name username -Value ado
Add-Member -InputObject $endpoint -MemberType NoteProperty -Name password -Value $AccessToken
$endpoints += $endpoint
}
}
}
$auth = New-Object -TypeName PSObject
Add-Member -InputObject $auth -MemberType NoteProperty -Name endpointCredentials -Value $endpoints
$authJson = ConvertTo-Json -InputObject $auth
$envVars = @{
$envVars += @{
'VSS_NUGET_EXTERNAL_FEED_ENDPOINTS'=$authJson;
}
& "$PSScriptRoot\..\azure-pipelines\Set-EnvVars.ps1" -Variables $envVars | Out-Null
}
& "$PSScriptRoot/Set-EnvVars.ps1" -Variables $envVars | Out-Null

Просмотреть файл

@ -4,8 +4,13 @@
Azure Pipeline and CMD environments are considered.
.PARAMETER Variables
A hashtable of variables to be set.
.PARAMETER PrependPath
A set of paths to prepend to the PATH environment variable.
.OUTPUTS
A boolean indicating whether the environment variables can be expected to propagate to the caller's environment.
.DESCRIPTION
The CmdEnvScriptPath environment variable may be optionally set to a path to a cmd shell script to be created (or appended to if it already exists) that will set the environment variables in cmd.exe that are set within the PowerShell environment.
This is used by init.cmd in order to reapply any new environment variables to the parent cmd.exe process that were set in the powershell child process.
#>
[CmdletBinding(SupportsShouldProcess=$true)]
Param(
@ -18,13 +23,13 @@ if ($Variables.Count -eq 0) {
return $true
}
$cmdInstructions = !$env:TF_BUILD -and !$env:GITHUB_ACTIONS -and $env:PS1UnderCmd -eq '1'
$cmdInstructions = !$env:TF_BUILD -and !$env:GITHUB_ACTIONS -and !$env:CmdEnvScriptPath -and ($env:PS1UnderCmd -eq '1')
if ($cmdInstructions) {
Write-Warning "Environment variables have been set that will be lost because you're running under cmd.exe"
Write-Host "Environment variables that must be set manually:" -ForegroundColor Blue
} else {
Write-Host "Environment variables set:" -ForegroundColor Blue
$envVars
Write-Host ($Variables | Out-String)
if ($PrependPath) {
Write-Host "Paths prepended to PATH: $PrependPath"
}
@ -38,6 +43,7 @@ if ($env:GITHUB_ACTIONS) {
Write-Host "GitHub Actions detected. Logging commands will be used to propagate environment variables and prepend path."
}
$CmdEnvScript = ''
$Variables.GetEnumerator() |% {
Set-Item -Path env:$($_.Key) -Value $_.Value
@ -52,6 +58,8 @@ $Variables.GetEnumerator() |% {
if ($cmdInstructions) {
Write-Host "SET $($_.Key)=$($_.Value)"
}
$CmdEnvScript += "SET $($_.Key)=$($_.Value)`r`n"
}
$pathDelimiter = ';'
@ -73,7 +81,17 @@ if ($PrependPath) {
if ($env:GITHUB_ACTIONS) {
Write-Host "::add-path::$_"
}
$CmdEnvScript += "SET PATH=$_$pathDelimiter%PATH%"
}
}
if ($env:CmdEnvScriptPath) {
if (Test-Path $env:CmdEnvScriptPath) {
$CmdEnvScript = (Get-Content -Path $env:CmdEnvScriptPath) + $CmdEnvScript
}
Set-Content -Path $env:CmdEnvScriptPath -Value $CmdEnvScript
}
return !$cmdInstructions

Просмотреть файл

@ -1,5 +1,5 @@
{
"$schema": "https://raw.githubusercontent.com/AArnott/Nerdbank.GitVersioning/master/src/NerdBank.GitVersioning/version.schema.json",
"$schema": "https://raw.githubusercontent.com/dotnet/Nerdbank.GitVersioning/master/src/NerdBank.GitVersioning/version.schema.json",
"version": "16.5-beta",
"publicReleaseRefSpec": [
"^refs/heads/main$",