From f8004a476fa7e88b56dfb955c5e6ad7291f81f43 Mon Sep 17 00:00:00 2001 From: Michael Taylor Date: Tue, 1 Aug 2017 00:41:48 -0500 Subject: [PATCH] Moved to src folder --- .gitignore | 293 ++++ LICENSE => src/LICENSE | 0 .../ShowVariables}/ShowVariables.ps1 | 98 +- {ShowVariables => src/ShowVariables}/icon.png | Bin .../ps_modules/VstsTaskSdk/FindFunctions.ps1 | 1378 ++++++++--------- .../ps_modules/VstsTaskSdk/InputFunctions.ps1 | 850 +++++----- .../VstsTaskSdk/LegacyFindFunctions.ps1 | 640 ++++---- .../VstsTaskSdk/LocalizationFunctions.ps1 | 300 ++-- .../VstsTaskSdk/LoggingCommandFunctions.ps1 | 1012 ++++++------ .../VstsTaskSdk/LongPathFunctions.ps1 | 736 ++++----- .../ps_modules/VstsTaskSdk/Minimatch.dll | Bin .../ps_modules/VstsTaskSdk/OutFunctions.ps1 | 158 +- .../VstsTaskSdk/ServerOMFunctions.ps1 | 1098 ++++++------- .../resources.resjson/de-de/resources.resjson | 32 +- .../resources.resjson/en-US/resources.resjson | 0 .../resources.resjson/es-es/resources.resjson | 32 +- .../resources.resjson/fr-fr/resources.resjson | 32 +- .../resources.resjson/it-IT/resources.resjson | 32 +- .../resources.resjson/ja-jp/resources.resjson | 32 +- .../resources.resjson/ko-KR/resources.resjson | 32 +- .../resources.resjson/ru-RU/resources.resjson | 32 +- .../resources.resjson/zh-CN/resources.resjson | 32 +- .../resources.resjson/zh-TW/resources.resjson | 32 +- .../ps_modules/VstsTaskSdk/ToolFunctions.ps1 | 198 +-- .../ps_modules/VstsTaskSdk/TraceFunctions.ps1 | 278 ++-- .../ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 | Bin .../ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 | 322 ++-- .../ps_modules/VstsTaskSdk/lib.json | 38 +- .../ShowVariables}/task.json | 0 .../VersionAssemblies}/icon.png | Bin .../ps_modules/VstsTaskSdk/FindFunctions.ps1 | 1378 ++++++++--------- .../ps_modules/VstsTaskSdk/InputFunctions.ps1 | 850 +++++----- .../VstsTaskSdk/LegacyFindFunctions.ps1 | 640 ++++---- .../VstsTaskSdk/LocalizationFunctions.ps1 | 300 ++-- .../VstsTaskSdk/LoggingCommandFunctions.ps1 | 1012 ++++++------ .../VstsTaskSdk/LongPathFunctions.ps1 | 736 ++++----- .../ps_modules/VstsTaskSdk/Minimatch.dll | Bin .../ps_modules/VstsTaskSdk/OutFunctions.ps1 | 158 +- .../VstsTaskSdk/ServerOMFunctions.ps1 | 1098 ++++++------- .../resources.resjson/de-de/resources.resjson | 32 +- .../resources.resjson/en-US/resources.resjson | 0 .../resources.resjson/es-es/resources.resjson | 32 +- .../resources.resjson/fr-fr/resources.resjson | 32 +- .../resources.resjson/it-IT/resources.resjson | 32 +- .../resources.resjson/ja-jp/resources.resjson | 32 +- .../resources.resjson/ko-KR/resources.resjson | 32 +- .../resources.resjson/ru-RU/resources.resjson | 32 +- .../resources.resjson/zh-CN/resources.resjson | 32 +- .../resources.resjson/zh-TW/resources.resjson | 32 +- .../ps_modules/VstsTaskSdk/ToolFunctions.ps1 | 198 +-- .../ps_modules/VstsTaskSdk/TraceFunctions.ps1 | 278 ++-- .../ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 | Bin .../ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 | 322 ++-- .../ps_modules/VstsTaskSdk/lib.json | 38 +- .../VersionAssemblies}/task.json | 0 .../VersionAssemblies}/versionAssemblies.ps1 | 370 ++--- extension-icon.png => src/extension-icon.png | Bin overview.md => src/overview.md | 8 +- vss-extension.json => src/vss-extension.json | 114 +- 59 files changed, 7884 insertions(+), 7591 deletions(-) create mode 100644 .gitignore rename LICENSE => src/LICENSE (100%) rename {ShowVariables => src/ShowVariables}/ShowVariables.ps1 (96%) rename {ShowVariables => src/ShowVariables}/icon.png (100%) rename {ShowVariables => src/ShowVariables}/ps_modules/VstsTaskSdk/FindFunctions.ps1 (97%) rename {VersionAssemblies => src/ShowVariables}/ps_modules/VstsTaskSdk/InputFunctions.ps1 (97%) rename {VersionAssemblies => src/ShowVariables}/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 (97%) rename {VersionAssemblies => src/ShowVariables}/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 (97%) rename {VersionAssemblies => src/ShowVariables}/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 (96%) rename {ShowVariables => src/ShowVariables}/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 (97%) rename {ShowVariables => src/ShowVariables}/ps_modules/VstsTaskSdk/Minimatch.dll (100%) rename {ShowVariables => src/ShowVariables}/ps_modules/VstsTaskSdk/OutFunctions.ps1 (97%) rename {VersionAssemblies => src/ShowVariables}/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 (97%) rename {ShowVariables => src/ShowVariables}/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson (98%) rename {ShowVariables => src/ShowVariables}/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson (100%) rename {VersionAssemblies => src/ShowVariables}/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson (98%) rename {VersionAssemblies => src/ShowVariables}/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson (98%) rename {VersionAssemblies => src/ShowVariables}/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson (98%) rename {ShowVariables => src/ShowVariables}/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson (98%) rename {VersionAssemblies => src/ShowVariables}/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson (98%) rename {ShowVariables => src/ShowVariables}/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson (99%) rename {VersionAssemblies => src/ShowVariables}/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson (98%) rename {VersionAssemblies => src/ShowVariables}/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson (98%) rename {VersionAssemblies => src/ShowVariables}/ps_modules/VstsTaskSdk/ToolFunctions.ps1 (97%) rename {ShowVariables => src/ShowVariables}/ps_modules/VstsTaskSdk/TraceFunctions.ps1 (96%) rename {ShowVariables => src/ShowVariables}/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 (100%) rename {ShowVariables => src/ShowVariables}/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 (97%) rename {ShowVariables => src/ShowVariables}/ps_modules/VstsTaskSdk/lib.json (98%) rename {ShowVariables => src/ShowVariables}/task.json (100%) rename {VersionAssemblies => src/VersionAssemblies}/icon.png (100%) rename {VersionAssemblies => src/VersionAssemblies}/ps_modules/VstsTaskSdk/FindFunctions.ps1 (97%) rename {ShowVariables => src/VersionAssemblies}/ps_modules/VstsTaskSdk/InputFunctions.ps1 (97%) rename {ShowVariables => src/VersionAssemblies}/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 (97%) rename {ShowVariables => src/VersionAssemblies}/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 (97%) rename {ShowVariables => src/VersionAssemblies}/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 (96%) rename {VersionAssemblies => src/VersionAssemblies}/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 (97%) rename {VersionAssemblies => src/VersionAssemblies}/ps_modules/VstsTaskSdk/Minimatch.dll (100%) rename {VersionAssemblies => src/VersionAssemblies}/ps_modules/VstsTaskSdk/OutFunctions.ps1 (97%) rename {ShowVariables => src/VersionAssemblies}/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 (97%) rename {VersionAssemblies => src/VersionAssemblies}/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson (98%) rename {VersionAssemblies => src/VersionAssemblies}/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson (100%) rename {ShowVariables => src/VersionAssemblies}/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson (98%) rename {ShowVariables => src/VersionAssemblies}/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson (98%) rename {ShowVariables => src/VersionAssemblies}/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson (98%) rename {VersionAssemblies => src/VersionAssemblies}/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson (98%) rename {ShowVariables => src/VersionAssemblies}/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson (98%) rename {VersionAssemblies => src/VersionAssemblies}/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson (99%) rename {ShowVariables => src/VersionAssemblies}/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson (98%) rename {ShowVariables => src/VersionAssemblies}/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson (98%) rename {ShowVariables => src/VersionAssemblies}/ps_modules/VstsTaskSdk/ToolFunctions.ps1 (97%) rename {VersionAssemblies => src/VersionAssemblies}/ps_modules/VstsTaskSdk/TraceFunctions.ps1 (96%) rename {VersionAssemblies => src/VersionAssemblies}/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 (100%) rename {VersionAssemblies => src/VersionAssemblies}/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 (97%) rename {VersionAssemblies => src/VersionAssemblies}/ps_modules/VstsTaskSdk/lib.json (98%) rename {VersionAssemblies => src/VersionAssemblies}/task.json (100%) rename {VersionAssemblies => src/VersionAssemblies}/versionAssemblies.ps1 (96%) rename extension-icon.png => src/extension-icon.png (100%) rename overview.md => src/overview.md (95%) rename vss-extension.json => src/vss-extension.json (94%) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f163d1a --- /dev/null +++ b/.gitignore @@ -0,0 +1,293 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ +**/Properties/launchSettings.json + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml + +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg + +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ + +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config + +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache + +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Typescript v1 declaration files +typings/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs \ No newline at end of file diff --git a/LICENSE b/src/LICENSE similarity index 100% rename from LICENSE rename to src/LICENSE diff --git a/ShowVariables/ShowVariables.ps1 b/src/ShowVariables/ShowVariables.ps1 similarity index 96% rename from ShowVariables/ShowVariables.ps1 rename to src/ShowVariables/ShowVariables.ps1 index 9c133ed..1d8a836 100644 --- a/ShowVariables/ShowVariables.ps1 +++ b/src/ShowVariables/ShowVariables.ps1 @@ -1,50 +1,50 @@ -[CmdletBinding()] -param() - -function Display -{ - param( - [string][Parameter(Mandatory=$true)] $msg - ) - - if ($logLevel -eq "Debug") { - Write-VstsTaskDebug $msg - } elseif ($logLevel -eq "Verbose") { - Write-VstsTaskVerbose $msg - } else { - Write-Output $msg - } -} - -Trace-VstsEnteringInvocation $MyInvocation - -# Get inputs -$logLevel = Get-VstsInput -Name logLevel -Require -$showEmpty = Get-VstsInput -Name showEmpty -AsBool -Require -$message = Get-VstsInput -Name message -$currentPath = $env:SYSTEM_DEFAULTWORKINGDDIRECTORY - -try { - # Display optional message - if (-not [String]::IsNullOrEmpty($message)) { - Display $message - } - - Write-VstsTaskDebug "logLevel = $logLevel" - Write-VstsTaskDebug "showEmpty = $showEmpty" - - # Display variables - $count = 0 - $vars = Get-ChildItem env: - foreach ($var in $vars) { - if (-not [String]::IsNullOrEmpty($var.Value) -or $showEmpty) { - Display "$($var.Name) = $($var.Value)" - } - $count++ - } - - # Set p3net_environmentVariableCount to the # of variables - Set-VstsTaskVariable -Name "ps3net_environmentVariableCount" -Value $count -} finally { - Trace-VstsLeavingInvocation $MyInvocation +[CmdletBinding()] +param() + +function Display +{ + param( + [string][Parameter(Mandatory=$true)] $msg + ) + + if ($logLevel -eq "Debug") { + Write-VstsTaskDebug $msg + } elseif ($logLevel -eq "Verbose") { + Write-VstsTaskVerbose $msg + } else { + Write-Output $msg + } +} + +Trace-VstsEnteringInvocation $MyInvocation + +# Get inputs +$logLevel = Get-VstsInput -Name logLevel -Require +$showEmpty = Get-VstsInput -Name showEmpty -AsBool -Require +$message = Get-VstsInput -Name message +$currentPath = $env:SYSTEM_DEFAULTWORKINGDDIRECTORY + +try { + # Display optional message + if (-not [String]::IsNullOrEmpty($message)) { + Display $message + } + + Write-VstsTaskDebug "logLevel = $logLevel" + Write-VstsTaskDebug "showEmpty = $showEmpty" + + # Display variables + $count = 0 + $vars = Get-ChildItem env: + foreach ($var in $vars) { + if (-not [String]::IsNullOrEmpty($var.Value) -or $showEmpty) { + Display "$($var.Name) = $($var.Value)" + } + $count++ + } + + # Set p3net_environmentVariableCount to the # of variables + Set-VstsTaskVariable -Name "ps3net_environmentVariableCount" -Value $count +} finally { + Trace-VstsLeavingInvocation $MyInvocation } \ No newline at end of file diff --git a/ShowVariables/icon.png b/src/ShowVariables/icon.png similarity index 100% rename from ShowVariables/icon.png rename to src/ShowVariables/icon.png diff --git a/ShowVariables/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/src/ShowVariables/ps_modules/VstsTaskSdk/FindFunctions.ps1 similarity index 97% rename from ShowVariables/ps_modules/VstsTaskSdk/FindFunctions.ps1 rename to src/ShowVariables/ps_modules/VstsTaskSdk/FindFunctions.ps1 index c380b5e..d2087b1 100644 --- a/ShowVariables/ps_modules/VstsTaskSdk/FindFunctions.ps1 +++ b/src/ShowVariables/ps_modules/VstsTaskSdk/FindFunctions.ps1 @@ -1,689 +1,689 @@ -<# -.SYNOPSIS -Finds files using match patterns. - -.DESCRIPTION -Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root. - -.PARAMETER DefaultRoot -Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location. - -.PARAMETER Pattern -Patterns to apply. Supports interleaved exclude patterns. - -.PARAMETER FindOptions -When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files. - -.PARAMETER MatchOptions -When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase). -#> -function Find-Match { - [CmdletBinding()] - param( - [Parameter()] - [string]$DefaultRoot, - [Parameter()] - [string[]]$Pattern, - $FindOptions, - $MatchOptions) - - Trace-EnteringInvocation $MyInvocation -Parameter None - $originalErrorActionPreference = $ErrorActionPreference - try { - $ErrorActionPreference = 'Stop' - - # Apply defaults for parameters and trace. - if (!$DefaultRoot) { - $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path - } - - Write-Verbose "DefaultRoot: '$DefaultRoot'" - if (!$FindOptions) { - $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks - } - - Trace-FindOptions -Options $FindOptions - if (!$MatchOptions) { - $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase - } - - Trace-MatchOptions -Options $MatchOptions - Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll - - # Normalize slashes for root dir. - $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot - - $results = @{ } - $originalMatchOptions = $MatchOptions - foreach ($pat in $Pattern) { - Write-Verbose "Pattern: '$pat'" - - # Trim and skip empty. - $pat = "$pat".Trim() - if (!$pat) { - Write-Verbose 'Skipping empty pattern.' - continue - } - - # Clone match options. - $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions - - # Skip comments. - if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) { - Write-Verbose 'Skipping comment.' - continue - } - - # Set NoComment. Brace expansion could result in a leading '#'. - $MatchOptions.NoComment = $true - - # Determine whether pattern is include or exclude. - $negateCount = 0 - if (!$MatchOptions.NoNegate) { - while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') { - $negateCount++ - } - - $pat = $pat.Substring($negateCount) # trim leading '!' - if ($negateCount) { - Write-Verbose "Trimmed leading '!'. Pattern: '$pat'" - } - } - - $isIncludePattern = $negateCount -eq 0 -or - ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or - ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate) - - # Set NoNegate. Brace expansion could result in a leading '!'. - $MatchOptions.NoNegate = $true - $MatchOptions.FlipNegate = $false - - # Trim and skip empty. - $pat = "$pat".Trim() - if (!$pat) { - Write-Verbose 'Skipping empty pattern.' - continue - } - - # Expand braces - required to accurately interpret findPath. - $expanded = $null - $preExpanded = $pat - if ($MatchOptions.NoBrace) { - $expanded = @( $pat ) - } else { - # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot - # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3). - Write-Verbose "Expanding braces." - $convertedPattern = $pat -replace '\\', '/' - $expanded = [Minimatch.Minimatcher]::BraceExpand( - $convertedPattern, - (ConvertTo-MinimatchOptions -Options $MatchOptions)) - } - - # Set NoBrace. - $MatchOptions.NoBrace = $true - - foreach ($pat in $expanded) { - if ($pat -ne $preExpanded) { - Write-Verbose "Pattern: '$pat'" - } - - # Trim and skip empty. - $pat = "$pat".Trim() - if (!$pat) { - Write-Verbose "Skipping empty pattern." - continue - } - - if ($isIncludePattern) { - # Determine the findPath. - $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions - $findPath = $findInfo.FindPath - Write-Verbose "FindPath: '$findPath'" - - if (!$findPath) { - Write-Verbose "Skipping empty path." - continue - } - - # Perform the find. - Write-Verbose "StatOnly: '$($findInfo.StatOnly)'" - [string[]]$findResults = @( ) - if ($findInfo.StatOnly) { - # Simply stat the path - all path segments were used to build the path. - if ((Test-Path -LiteralPath $findPath)) { - $findResults += $findPath - } - } else { - $findResults = Get-FindResult -Path $findPath -Options $FindOptions - } - - Write-Verbose "Found $($findResults.Count) paths." - - # Apply the pattern. - Write-Verbose "Applying include pattern." - if ($findInfo.AdjustedPattern -ne $pat) { - Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'" - $pat = $findInfo.AdjustedPattern - } - - $matchResults = [Minimatch.Minimatcher]::Filter( - $findResults, - $pat, - (ConvertTo-MinimatchOptions -Options $MatchOptions)) - - # Union the results. - $matchCount = 0 - foreach ($matchResult in $matchResults) { - $matchCount++ - $results[$matchResult.ToUpperInvariant()] = $matchResult - } - - Write-Verbose "$matchCount matches" - } else { - # Check if basename only and MatchBase=true. - if ($MatchOptions.MatchBase -and - !(Test-Rooted -Path $pat) -and - ($pat -replace '\\', '/').IndexOf('/') -lt 0) { - - # Do not root the pattern. - Write-Verbose "MatchBase and basename only." - } else { - # Root the exclude pattern. - $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat - Write-Verbose "After Get-RootedPattern, pattern: '$pat'" - } - - # Apply the pattern. - Write-Verbose 'Applying exclude pattern.' - $matchResults = [Minimatch.Minimatcher]::Filter( - [string[]]$results.Values, - $pat, - (ConvertTo-MinimatchOptions -Options $MatchOptions)) - - # Subtract the results. - $matchCount = 0 - foreach ($matchResult in $matchResults) { - $matchCount++ - $results.Remove($matchResult.ToUpperInvariant()) - } - - Write-Verbose "$matchCount matches" - } - } - } - - $finalResult = @( $results.Values | Sort-Object ) - Write-Verbose "$($finalResult.Count) final results" - return $finalResult - } catch { - $ErrorActionPreference = $originalErrorActionPreference - Write-Error $_ - } finally { - Trace-LeavingInvocation -InvocationInfo $MyInvocation - } -} - -<# -.SYNOPSIS -Creates FindOptions for use with Find-VstsMatch. - -.DESCRIPTION -Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks. - -.PARAMETER FollowSpecifiedSymbolicLink -Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed. - -.PARAMETER FollowSymbolicLinks -Indicates whether to traverse descendants of symbolic link directories. -#> -function New-FindOptions { - [CmdletBinding()] - param( - [switch]$FollowSpecifiedSymbolicLink, - [switch]$FollowSymbolicLinks) - - return New-Object psobject -Property @{ - FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent - FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent - } -} - -<# -.SYNOPSIS -Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. - -.DESCRIPTION -Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied. -#> -function New-MatchOptions { - [CmdletBinding()] - param( - [switch]$Dot, - [switch]$FlipNegate, - [switch]$MatchBase, - [switch]$NoBrace, - [switch]$NoCase, - [switch]$NoComment, - [switch]$NoExt, - [switch]$NoGlobStar, - [switch]$NoNegate, - [switch]$NoNull) - - return New-Object psobject -Property @{ - Dot = $Dot.IsPresent - FlipNegate = $FlipNegate.IsPresent - MatchBase = $MatchBase.IsPresent - NoBrace = $NoBrace.IsPresent - NoCase = $NoCase.IsPresent - NoComment = $NoComment.IsPresent - NoExt = $NoExt.IsPresent - NoGlobStar = $NoGlobStar.IsPresent - NoNegate = $NoNegate.IsPresent - NoNull = $NoNull.IsPresent - } -} - -<# -.SYNOPSIS -Applies match patterns against a list of files. - -.DESCRIPTION -Applies match patterns to a list of paths. Supports interleaved exclude patterns. - -.PARAMETER ItemPath -Array of paths. - -.PARAMETER Pattern -Patterns to apply. Supports interleaved exclude patterns. - -.PARAMETER Options -When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase). -#> -function Select-Match { - [CmdletBinding()] - param( - [Parameter()] - [string[]]$ItemPath, - [Parameter()] - [string[]]$Pattern, - $Options) - - - Trace-EnteringInvocation $MyInvocation -Parameter None - $originalErrorActionPreference = $ErrorActionPreference - try { - $ErrorActionPreference = 'Stop' - if (!$Options) { - $Options = New-MatchOptions -Dot -NoBrace -NoCase - } - - Trace-MatchOptions -Options $Options - Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll - - # Hashtable to keep track of matches. - $map = @{ } - - $originalOptions = $Options - foreach ($pat in $Pattern) { - Write-Verbose "Pattern: '$pat'" - - # Trim and skip empty. - $pat = "$pat".Trim() - if (!$pat) { - Write-Verbose 'Skipping empty pattern.' - continue - } - - # Clone match options. - $Options = Copy-MatchOptions -Options $originalOptions - - # Skip comments. - if (!$Options.NoComment -and $pat.StartsWith('#')) { - Write-Verbose 'Skipping comment.' - continue - } - - # Set NoComment. - $Options.NoComment = $true - - # Determine whether pattern is include or exclude. - $negateCount = 0 - if (!$Options.NoNegate) { - while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') { - $negateCount++ - } - - $pat = $pat.Substring($negateCount) # trim leading '!' - if ($negateCount) { - Write-Verbose "Trimmed leading '!'. Pattern: '$pat'" - } - } - - $isIncludePattern = $negateCount -eq 0 -or - ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or - ($negateCount % 2 -eq 1 -and $Options.FlipNegate) - - # Set NoNegate. Brace expansion could result in a leading '!'. - $Options.NoNegate = $true - $Options.FlipNegate = $false - - # Trim and skip empty. - $pat = "$pat".Trim() - if (!$pat) { - Write-Verbose 'Skipping empty pattern.' - continue - } - - if ($isIncludePattern) { - # Apply the pattern. - Write-Verbose 'Applying include pattern against original list' - $matchResults = [Minimatch.Minimatcher]::Filter( - $ItemPath, - $pat, - (ConvertTo-MinimatchOptions -Options $Options)) - - # Union the results. - $matchCount = 0 - foreach ($matchResult in $matchResults) { - $matchCount++ - $map[$matchResult] = $true - } - - Write-Verbose "$matchCount matches" - } - else { - # Apply the pattern. - Write-Verbose 'Applying exclude pattern against original list' - $matchResults = [Minimatch.Minimatcher]::Filter( - $ItemPath, - $pat, - (ConvertTo-MinimatchOptions -Options $Options)) - - # Subtract the results. - $matchCount = 0 - foreach ($matchResult in $matchResults) { - $matchCount++ - $map.Remove($matchResult) - } - - Write-Verbose "$matchCount matches" - } - } - - # return a filtered version of the original list (preserves order and prevents duplication) - $result = $ItemPath | Where-Object { $map[$_] } - Write-Verbose "$($result.Count) final results" - $result - } catch { - $ErrorActionPreference = $originalErrorActionPreference - Write-Error $_ - } finally { - Trace-LeavingInvocation -InvocationInfo $MyInvocation - } -} - -################################################################################ -# Private functions. -################################################################################ - -function Copy-MatchOptions { - [CmdletBinding()] - param($Options) - - return New-Object psobject -Property @{ - Dot = $Options.Dot -eq $true - FlipNegate = $Options.FlipNegate -eq $true - MatchBase = $Options.MatchBase -eq $true - NoBrace = $Options.NoBrace -eq $true - NoCase = $Options.NoCase -eq $true - NoComment = $Options.NoComment -eq $true - NoExt = $Options.NoExt -eq $true - NoGlobStar = $Options.NoGlobStar -eq $true - NoNegate = $Options.NoNegate -eq $true - NoNull = $Options.NoNull -eq $true - } -} - -function ConvertTo-MinimatchOptions { - [CmdletBinding()] - param($Options) - - $opt = New-Object Minimatch.Options - $opt.AllowWindowsPaths = $true - $opt.Dot = $Options.Dot -eq $true - $opt.FlipNegate = $Options.FlipNegate -eq $true - $opt.MatchBase = $Options.MatchBase -eq $true - $opt.NoBrace = $Options.NoBrace -eq $true - $opt.NoCase = $Options.NoCase -eq $true - $opt.NoComment = $Options.NoComment -eq $true - $opt.NoExt = $Options.NoExt -eq $true - $opt.NoGlobStar = $Options.NoGlobStar -eq $true - $opt.NoNegate = $Options.NoNegate -eq $true - $opt.NoNull = $Options.NoNull -eq $true - return $opt -} - -function ConvertTo-NormalizedSeparators { - [CmdletBinding()] - param([string]$Path) - - # Convert slashes. - $Path = "$Path".Replace('/', '\') - - # Remove redundant slashes. - $isUnc = $Path -match '^\\\\+[^\\]' - $Path = $Path -replace '\\\\+', '\' - if ($isUnc) { - $Path = '\' + $Path - } - - return $Path -} - -function Get-FindInfoFromPattern { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$DefaultRoot, - [Parameter(Mandatory = $true)] - [string]$Pattern, - [Parameter(Mandatory = $true)] - $MatchOptions) - - if (!$MatchOptions.NoBrace) { - throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true." - } - - # For the sake of determining the find path, pretend NoCase=false. - $MatchOptions = Copy-MatchOptions -Options $MatchOptions - $MatchOptions.NoCase = $false - - # Check if basename only and MatchBase=true - if ($MatchOptions.MatchBase -and - !(Test-Rooted -Path $Pattern) -and - ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) { - - return New-Object psobject -Property @{ - AdjustedPattern = $Pattern - FindPath = $DefaultRoot - StatOnly = $false - } - } - - # The technique applied by this function is to use the information on the Minimatch object determine - # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which - # segments are literal vs patterns. - # - # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the - # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved - # for now. - $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions)) - - # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only - # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer - # enumerable, but that should be turned off by the time this function is reached. - # - # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs - # implementation. The .NET implementation is a port and is by a different author. - $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic') - [object[]]$set = $setFieldInfo.GetValue($minimatchObj) - if ($set.Count -ne 1) { - throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'" - } - - [string[]]$literalSegments = @( ) - [object[]]$parsedSegments = $set[0] - foreach ($parsedSegment in $parsedSegments) { - if ($parsedSegment.GetType().Name -eq 'LiteralItem') { - # The item is a LiteralItem when the original input for the path segment does not contain any - # unescaped glob characters. - $literalSegments += $parsedSegment.Source; - continue - } - - break; - } - - # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes - # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can - # be detected from the original pattern. - $joinedSegments = [string]::Join('/', $literalSegments) - if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) { - $joinedSegments = '/' + $joinedSegments # restore UNC format - } - - # Determine the find path. - $findPath = '' - if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted. - $findPath = $joinedSegments - } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found. - $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments) - } else { # The pattern is not rooted, and no literal segements were found. - $findPath = $DefaultRoot - } - - # Clean up the path. - if ($findPath) { - $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash. - $findPath = ConvertTo-NormalizedSeparators -Path $findPath - } - - return New-Object psobject -Property @{ - AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern - FindPath = $findPath - StatOnly = $literalSegments.Count -eq $parsedSegments.Count - } -} - -function Get-FindResult { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Path, - [Parameter(Mandatory = $true)] - $Options) - - if (!(Test-Path -LiteralPath $Path)) { - Write-Verbose 'Path not found.' - return - } - - $Path = ConvertTo-NormalizedSeparators -Path $Path - - # Push the first item. - [System.Collections.Stack]$stack = New-Object System.Collections.Stack - $stack.Push((Get-Item -LiteralPath $Path)) - - $count = 0 - while ($stack.Count) { - # Pop the next item and yield the result. - $item = $stack.Pop() - $count++ - $item.FullName - - # Traverse. - if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory - if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint - $Options.FollowSymbolicLinks -or - ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) { - - $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force ) - [System.Array]::Reverse($childItems) - foreach ($childItem in $childItems) { - $stack.Push($childItem) - } - } - } - } -} - -function Get-RootedPattern { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$DefaultRoot, - [Parameter(Mandatory = $true)] - [string]$Pattern) - - if ((Test-Rooted -Path $Pattern)) { - return $Pattern - } - - # Normalize root. - $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot - - # Escape special glob characters. - $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment - $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?' - $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*' - $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+(' - $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@(' - $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!(' - - if ($DefaultRoot -like '[A-Z]:') { # e.g. C: - return "$DefaultRoot$Pattern" - } - - # Ensure root ends with a separator. - if (!$DefaultRoot.EndsWith('\')) { - $DefaultRoot = "$DefaultRoot\" - } - - return "$DefaultRoot$Pattern" -} - -function Test-Rooted { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Path) - - $Path = ConvertTo-NormalizedSeparators -Path $Path - return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello - $Path -like '[A-Z]:*' # e.g. C: or C:\hello -} - -function Trace-MatchOptions { - [CmdletBinding()] - param($Options) - - Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'" - Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'" - Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'" - Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'" - Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'" - Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'" - Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'" - Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'" - Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'" - Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'" -} - -function Trace-FindOptions { - [CmdletBinding()] - param($Options) - - Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'" - Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'" -} +<# +.SYNOPSIS +Finds files using match patterns. + +.DESCRIPTION +Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root. + +.PARAMETER DefaultRoot +Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location. + +.PARAMETER Pattern +Patterns to apply. Supports interleaved exclude patterns. + +.PARAMETER FindOptions +When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files. + +.PARAMETER MatchOptions +When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase). +#> +function Find-Match { + [CmdletBinding()] + param( + [Parameter()] + [string]$DefaultRoot, + [Parameter()] + [string[]]$Pattern, + $FindOptions, + $MatchOptions) + + Trace-EnteringInvocation $MyInvocation -Parameter None + $originalErrorActionPreference = $ErrorActionPreference + try { + $ErrorActionPreference = 'Stop' + + # Apply defaults for parameters and trace. + if (!$DefaultRoot) { + $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path + } + + Write-Verbose "DefaultRoot: '$DefaultRoot'" + if (!$FindOptions) { + $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks + } + + Trace-FindOptions -Options $FindOptions + if (!$MatchOptions) { + $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase + } + + Trace-MatchOptions -Options $MatchOptions + Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll + + # Normalize slashes for root dir. + $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot + + $results = @{ } + $originalMatchOptions = $MatchOptions + foreach ($pat in $Pattern) { + Write-Verbose "Pattern: '$pat'" + + # Trim and skip empty. + $pat = "$pat".Trim() + if (!$pat) { + Write-Verbose 'Skipping empty pattern.' + continue + } + + # Clone match options. + $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions + + # Skip comments. + if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) { + Write-Verbose 'Skipping comment.' + continue + } + + # Set NoComment. Brace expansion could result in a leading '#'. + $MatchOptions.NoComment = $true + + # Determine whether pattern is include or exclude. + $negateCount = 0 + if (!$MatchOptions.NoNegate) { + while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') { + $negateCount++ + } + + $pat = $pat.Substring($negateCount) # trim leading '!' + if ($negateCount) { + Write-Verbose "Trimmed leading '!'. Pattern: '$pat'" + } + } + + $isIncludePattern = $negateCount -eq 0 -or + ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or + ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate) + + # Set NoNegate. Brace expansion could result in a leading '!'. + $MatchOptions.NoNegate = $true + $MatchOptions.FlipNegate = $false + + # Trim and skip empty. + $pat = "$pat".Trim() + if (!$pat) { + Write-Verbose 'Skipping empty pattern.' + continue + } + + # Expand braces - required to accurately interpret findPath. + $expanded = $null + $preExpanded = $pat + if ($MatchOptions.NoBrace) { + $expanded = @( $pat ) + } else { + # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot + # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3). + Write-Verbose "Expanding braces." + $convertedPattern = $pat -replace '\\', '/' + $expanded = [Minimatch.Minimatcher]::BraceExpand( + $convertedPattern, + (ConvertTo-MinimatchOptions -Options $MatchOptions)) + } + + # Set NoBrace. + $MatchOptions.NoBrace = $true + + foreach ($pat in $expanded) { + if ($pat -ne $preExpanded) { + Write-Verbose "Pattern: '$pat'" + } + + # Trim and skip empty. + $pat = "$pat".Trim() + if (!$pat) { + Write-Verbose "Skipping empty pattern." + continue + } + + if ($isIncludePattern) { + # Determine the findPath. + $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions + $findPath = $findInfo.FindPath + Write-Verbose "FindPath: '$findPath'" + + if (!$findPath) { + Write-Verbose "Skipping empty path." + continue + } + + # Perform the find. + Write-Verbose "StatOnly: '$($findInfo.StatOnly)'" + [string[]]$findResults = @( ) + if ($findInfo.StatOnly) { + # Simply stat the path - all path segments were used to build the path. + if ((Test-Path -LiteralPath $findPath)) { + $findResults += $findPath + } + } else { + $findResults = Get-FindResult -Path $findPath -Options $FindOptions + } + + Write-Verbose "Found $($findResults.Count) paths." + + # Apply the pattern. + Write-Verbose "Applying include pattern." + if ($findInfo.AdjustedPattern -ne $pat) { + Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'" + $pat = $findInfo.AdjustedPattern + } + + $matchResults = [Minimatch.Minimatcher]::Filter( + $findResults, + $pat, + (ConvertTo-MinimatchOptions -Options $MatchOptions)) + + # Union the results. + $matchCount = 0 + foreach ($matchResult in $matchResults) { + $matchCount++ + $results[$matchResult.ToUpperInvariant()] = $matchResult + } + + Write-Verbose "$matchCount matches" + } else { + # Check if basename only and MatchBase=true. + if ($MatchOptions.MatchBase -and + !(Test-Rooted -Path $pat) -and + ($pat -replace '\\', '/').IndexOf('/') -lt 0) { + + # Do not root the pattern. + Write-Verbose "MatchBase and basename only." + } else { + # Root the exclude pattern. + $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat + Write-Verbose "After Get-RootedPattern, pattern: '$pat'" + } + + # Apply the pattern. + Write-Verbose 'Applying exclude pattern.' + $matchResults = [Minimatch.Minimatcher]::Filter( + [string[]]$results.Values, + $pat, + (ConvertTo-MinimatchOptions -Options $MatchOptions)) + + # Subtract the results. + $matchCount = 0 + foreach ($matchResult in $matchResults) { + $matchCount++ + $results.Remove($matchResult.ToUpperInvariant()) + } + + Write-Verbose "$matchCount matches" + } + } + } + + $finalResult = @( $results.Values | Sort-Object ) + Write-Verbose "$($finalResult.Count) final results" + return $finalResult + } catch { + $ErrorActionPreference = $originalErrorActionPreference + Write-Error $_ + } finally { + Trace-LeavingInvocation -InvocationInfo $MyInvocation + } +} + +<# +.SYNOPSIS +Creates FindOptions for use with Find-VstsMatch. + +.DESCRIPTION +Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks. + +.PARAMETER FollowSpecifiedSymbolicLink +Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed. + +.PARAMETER FollowSymbolicLinks +Indicates whether to traverse descendants of symbolic link directories. +#> +function New-FindOptions { + [CmdletBinding()] + param( + [switch]$FollowSpecifiedSymbolicLink, + [switch]$FollowSymbolicLinks) + + return New-Object psobject -Property @{ + FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent + FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent + } +} + +<# +.SYNOPSIS +Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. + +.DESCRIPTION +Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied. +#> +function New-MatchOptions { + [CmdletBinding()] + param( + [switch]$Dot, + [switch]$FlipNegate, + [switch]$MatchBase, + [switch]$NoBrace, + [switch]$NoCase, + [switch]$NoComment, + [switch]$NoExt, + [switch]$NoGlobStar, + [switch]$NoNegate, + [switch]$NoNull) + + return New-Object psobject -Property @{ + Dot = $Dot.IsPresent + FlipNegate = $FlipNegate.IsPresent + MatchBase = $MatchBase.IsPresent + NoBrace = $NoBrace.IsPresent + NoCase = $NoCase.IsPresent + NoComment = $NoComment.IsPresent + NoExt = $NoExt.IsPresent + NoGlobStar = $NoGlobStar.IsPresent + NoNegate = $NoNegate.IsPresent + NoNull = $NoNull.IsPresent + } +} + +<# +.SYNOPSIS +Applies match patterns against a list of files. + +.DESCRIPTION +Applies match patterns to a list of paths. Supports interleaved exclude patterns. + +.PARAMETER ItemPath +Array of paths. + +.PARAMETER Pattern +Patterns to apply. Supports interleaved exclude patterns. + +.PARAMETER Options +When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase). +#> +function Select-Match { + [CmdletBinding()] + param( + [Parameter()] + [string[]]$ItemPath, + [Parameter()] + [string[]]$Pattern, + $Options) + + + Trace-EnteringInvocation $MyInvocation -Parameter None + $originalErrorActionPreference = $ErrorActionPreference + try { + $ErrorActionPreference = 'Stop' + if (!$Options) { + $Options = New-MatchOptions -Dot -NoBrace -NoCase + } + + Trace-MatchOptions -Options $Options + Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll + + # Hashtable to keep track of matches. + $map = @{ } + + $originalOptions = $Options + foreach ($pat in $Pattern) { + Write-Verbose "Pattern: '$pat'" + + # Trim and skip empty. + $pat = "$pat".Trim() + if (!$pat) { + Write-Verbose 'Skipping empty pattern.' + continue + } + + # Clone match options. + $Options = Copy-MatchOptions -Options $originalOptions + + # Skip comments. + if (!$Options.NoComment -and $pat.StartsWith('#')) { + Write-Verbose 'Skipping comment.' + continue + } + + # Set NoComment. + $Options.NoComment = $true + + # Determine whether pattern is include or exclude. + $negateCount = 0 + if (!$Options.NoNegate) { + while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') { + $negateCount++ + } + + $pat = $pat.Substring($negateCount) # trim leading '!' + if ($negateCount) { + Write-Verbose "Trimmed leading '!'. Pattern: '$pat'" + } + } + + $isIncludePattern = $negateCount -eq 0 -or + ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or + ($negateCount % 2 -eq 1 -and $Options.FlipNegate) + + # Set NoNegate. Brace expansion could result in a leading '!'. + $Options.NoNegate = $true + $Options.FlipNegate = $false + + # Trim and skip empty. + $pat = "$pat".Trim() + if (!$pat) { + Write-Verbose 'Skipping empty pattern.' + continue + } + + if ($isIncludePattern) { + # Apply the pattern. + Write-Verbose 'Applying include pattern against original list' + $matchResults = [Minimatch.Minimatcher]::Filter( + $ItemPath, + $pat, + (ConvertTo-MinimatchOptions -Options $Options)) + + # Union the results. + $matchCount = 0 + foreach ($matchResult in $matchResults) { + $matchCount++ + $map[$matchResult] = $true + } + + Write-Verbose "$matchCount matches" + } + else { + # Apply the pattern. + Write-Verbose 'Applying exclude pattern against original list' + $matchResults = [Minimatch.Minimatcher]::Filter( + $ItemPath, + $pat, + (ConvertTo-MinimatchOptions -Options $Options)) + + # Subtract the results. + $matchCount = 0 + foreach ($matchResult in $matchResults) { + $matchCount++ + $map.Remove($matchResult) + } + + Write-Verbose "$matchCount matches" + } + } + + # return a filtered version of the original list (preserves order and prevents duplication) + $result = $ItemPath | Where-Object { $map[$_] } + Write-Verbose "$($result.Count) final results" + $result + } catch { + $ErrorActionPreference = $originalErrorActionPreference + Write-Error $_ + } finally { + Trace-LeavingInvocation -InvocationInfo $MyInvocation + } +} + +################################################################################ +# Private functions. +################################################################################ + +function Copy-MatchOptions { + [CmdletBinding()] + param($Options) + + return New-Object psobject -Property @{ + Dot = $Options.Dot -eq $true + FlipNegate = $Options.FlipNegate -eq $true + MatchBase = $Options.MatchBase -eq $true + NoBrace = $Options.NoBrace -eq $true + NoCase = $Options.NoCase -eq $true + NoComment = $Options.NoComment -eq $true + NoExt = $Options.NoExt -eq $true + NoGlobStar = $Options.NoGlobStar -eq $true + NoNegate = $Options.NoNegate -eq $true + NoNull = $Options.NoNull -eq $true + } +} + +function ConvertTo-MinimatchOptions { + [CmdletBinding()] + param($Options) + + $opt = New-Object Minimatch.Options + $opt.AllowWindowsPaths = $true + $opt.Dot = $Options.Dot -eq $true + $opt.FlipNegate = $Options.FlipNegate -eq $true + $opt.MatchBase = $Options.MatchBase -eq $true + $opt.NoBrace = $Options.NoBrace -eq $true + $opt.NoCase = $Options.NoCase -eq $true + $opt.NoComment = $Options.NoComment -eq $true + $opt.NoExt = $Options.NoExt -eq $true + $opt.NoGlobStar = $Options.NoGlobStar -eq $true + $opt.NoNegate = $Options.NoNegate -eq $true + $opt.NoNull = $Options.NoNull -eq $true + return $opt +} + +function ConvertTo-NormalizedSeparators { + [CmdletBinding()] + param([string]$Path) + + # Convert slashes. + $Path = "$Path".Replace('/', '\') + + # Remove redundant slashes. + $isUnc = $Path -match '^\\\\+[^\\]' + $Path = $Path -replace '\\\\+', '\' + if ($isUnc) { + $Path = '\' + $Path + } + + return $Path +} + +function Get-FindInfoFromPattern { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$DefaultRoot, + [Parameter(Mandatory = $true)] + [string]$Pattern, + [Parameter(Mandatory = $true)] + $MatchOptions) + + if (!$MatchOptions.NoBrace) { + throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true." + } + + # For the sake of determining the find path, pretend NoCase=false. + $MatchOptions = Copy-MatchOptions -Options $MatchOptions + $MatchOptions.NoCase = $false + + # Check if basename only and MatchBase=true + if ($MatchOptions.MatchBase -and + !(Test-Rooted -Path $Pattern) -and + ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) { + + return New-Object psobject -Property @{ + AdjustedPattern = $Pattern + FindPath = $DefaultRoot + StatOnly = $false + } + } + + # The technique applied by this function is to use the information on the Minimatch object determine + # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which + # segments are literal vs patterns. + # + # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the + # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved + # for now. + $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions)) + + # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only + # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer + # enumerable, but that should be turned off by the time this function is reached. + # + # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs + # implementation. The .NET implementation is a port and is by a different author. + $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic') + [object[]]$set = $setFieldInfo.GetValue($minimatchObj) + if ($set.Count -ne 1) { + throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'" + } + + [string[]]$literalSegments = @( ) + [object[]]$parsedSegments = $set[0] + foreach ($parsedSegment in $parsedSegments) { + if ($parsedSegment.GetType().Name -eq 'LiteralItem') { + # The item is a LiteralItem when the original input for the path segment does not contain any + # unescaped glob characters. + $literalSegments += $parsedSegment.Source; + continue + } + + break; + } + + # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes + # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can + # be detected from the original pattern. + $joinedSegments = [string]::Join('/', $literalSegments) + if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) { + $joinedSegments = '/' + $joinedSegments # restore UNC format + } + + # Determine the find path. + $findPath = '' + if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted. + $findPath = $joinedSegments + } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found. + $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments) + } else { # The pattern is not rooted, and no literal segements were found. + $findPath = $DefaultRoot + } + + # Clean up the path. + if ($findPath) { + $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash. + $findPath = ConvertTo-NormalizedSeparators -Path $findPath + } + + return New-Object psobject -Property @{ + AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern + FindPath = $findPath + StatOnly = $literalSegments.Count -eq $parsedSegments.Count + } +} + +function Get-FindResult { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Path, + [Parameter(Mandatory = $true)] + $Options) + + if (!(Test-Path -LiteralPath $Path)) { + Write-Verbose 'Path not found.' + return + } + + $Path = ConvertTo-NormalizedSeparators -Path $Path + + # Push the first item. + [System.Collections.Stack]$stack = New-Object System.Collections.Stack + $stack.Push((Get-Item -LiteralPath $Path)) + + $count = 0 + while ($stack.Count) { + # Pop the next item and yield the result. + $item = $stack.Pop() + $count++ + $item.FullName + + # Traverse. + if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory + if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint + $Options.FollowSymbolicLinks -or + ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) { + + $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force ) + [System.Array]::Reverse($childItems) + foreach ($childItem in $childItems) { + $stack.Push($childItem) + } + } + } + } +} + +function Get-RootedPattern { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$DefaultRoot, + [Parameter(Mandatory = $true)] + [string]$Pattern) + + if ((Test-Rooted -Path $Pattern)) { + return $Pattern + } + + # Normalize root. + $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot + + # Escape special glob characters. + $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment + $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?' + $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*' + $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+(' + $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@(' + $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!(' + + if ($DefaultRoot -like '[A-Z]:') { # e.g. C: + return "$DefaultRoot$Pattern" + } + + # Ensure root ends with a separator. + if (!$DefaultRoot.EndsWith('\')) { + $DefaultRoot = "$DefaultRoot\" + } + + return "$DefaultRoot$Pattern" +} + +function Test-Rooted { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Path) + + $Path = ConvertTo-NormalizedSeparators -Path $Path + return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello + $Path -like '[A-Z]:*' # e.g. C: or C:\hello +} + +function Trace-MatchOptions { + [CmdletBinding()] + param($Options) + + Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'" + Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'" + Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'" + Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'" + Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'" + Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'" + Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'" + Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'" + Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'" + Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'" +} + +function Trace-FindOptions { + [CmdletBinding()] + param($Options) + + Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'" + Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'" +} diff --git a/VersionAssemblies/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/src/ShowVariables/ps_modules/VstsTaskSdk/InputFunctions.ps1 similarity index 97% rename from VersionAssemblies/ps_modules/VstsTaskSdk/InputFunctions.ps1 rename to src/ShowVariables/ps_modules/VstsTaskSdk/InputFunctions.ps1 index 25299be..5f3ab9e 100644 --- a/VersionAssemblies/ps_modules/VstsTaskSdk/InputFunctions.ps1 +++ b/src/ShowVariables/ps_modules/VstsTaskSdk/InputFunctions.ps1 @@ -1,425 +1,425 @@ -# Hash table of known variable info. The formatted env var name is the lookup key. -# -# The purpose of this hash table is to keep track of known variables. The hash table -# needs to be maintained for multiple reasons: -# 1) to distinguish between env vars and job vars -# 2) to distinguish between secret vars and public -# 3) to know the real variable name and not just the formatted env var name. -$script:knownVariables = @{ } -$script:vault = @{ } - -<# -.SYNOPSIS -Gets an endpoint. - -.DESCRIPTION -Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url. - -The Data property requires a 1.97 agent or higher. - -.PARAMETER Require -Writes an error to the error pipeline if the endpoint is not found. -#> -function Get-Endpoint { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Name, - [switch]$Require) - - $originalErrorActionPreference = $ErrorActionPreference - try { - $ErrorActionPreference = 'Stop' - - # Get the URL. - $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name - $key = "ENDPOINT_URL_$Name" - $url = Get-VaultValue -Description $description -Key $key -Require:$Require - - # Get the auth object. - $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name - $key = "ENDPOINT_AUTH_$Name" - if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) { - $auth = ConvertFrom-Json -InputObject $auth - } - - # Get the data. - $description = "'$Name' service endpoint data" - $key = "ENDPOINT_DATA_$Name" - if ($data = (Get-VaultValue -Description $description -Key $key)) { - $data = ConvertFrom-Json -InputObject $data - } - - # Return the endpoint. - if ($url -or $auth -or $data) { - New-Object -TypeName psobject -Property @{ - Url = $url - Auth = $auth - Data = $data - } - } - } catch { - $ErrorActionPreference = $originalErrorActionPreference - Write-Error $_ - } -} - -<# -.SYNOPSIS -Gets an input. - -.DESCRIPTION -Gets the value for the specified input name. - -.PARAMETER AsBool -Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false. - -.PARAMETER AsInt -Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails. - -.PARAMETER Default -Default value to use if the input is null or empty. - -.PARAMETER Require -Writes an error to the error pipeline if the input is null or empty. -#> -function Get-Input { - [CmdletBinding(DefaultParameterSetName = 'Require')] - param( - [Parameter(Mandatory = $true)] - [string]$Name, - [Parameter(ParameterSetName = 'Default')] - $Default, - [Parameter(ParameterSetName = 'Require')] - [switch]$Require, - [switch]$AsBool, - [switch]$AsInt) - - # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required - # in order to concisely invoke the correct parameter set. - $null = $PSBoundParameters.Remove('Name') - $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name - $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())" - Get-VaultValue @PSBoundParameters -Description $description -Key $key -} - -<# -.SYNOPSIS -Gets a task variable. - -.DESCRIPTION -Gets the value for the specified task variable. - -.PARAMETER AsBool -Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false. - -.PARAMETER AsInt -Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails. - -.PARAMETER Default -Default value to use if the input is null or empty. - -.PARAMETER Require -Writes an error to the error pipeline if the input is null or empty. -#> -function Get-TaskVariable { - [CmdletBinding(DefaultParameterSetName = 'Require')] - param( - [Parameter(Mandatory = $true)] - [string]$Name, - [Parameter(ParameterSetName = 'Default')] - $Default, - [Parameter(ParameterSetName = 'Require')] - [switch]$Require, - [switch]$AsBool, - [switch]$AsInt) - - $originalErrorActionPreference = $ErrorActionPreference - try { - $ErrorActionPreference = 'Stop' - $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name - $variableKey = Get-VariableKey -Name $Name - if ($script:knownVariables.$variableKey.Secret) { - # Get secret variable. Splatting is required to concisely invoke the correct parameter set. - $null = $PSBoundParameters.Remove('Name') - $vaultKey = "SECRET_$variableKey" - Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey - } else { - # Get public variable. - $item = $null - $path = "Env:$variableKey" - if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) { - # Intentionally empty. Value was successfully retrieved. - } elseif (!$script:nonInteractive) { - # The value wasn't found and the module is running in interactive dev mode. - # Prompt for the value. - Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description) - if (Test-Path -LiteralPath $path) { - $item = Get-Item -LiteralPath $path - } - } - - # Get the converted value. Splatting is required to concisely invoke the correct parameter set. - $null = $PSBoundParameters.Remove('Name') - Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value - } - } catch { - $ErrorActionPreference = $originalErrorActionPreference - Write-Error $_ - } -} - -<# -.SYNOPSIS -Gets all job variables available to the task. Requires 2.104.1 agent or higher. - -.DESCRIPTION -Gets a snapshot of the current state of all job variables available to the task. -Requires a 2.104.1 agent or higher for full functionality. - -Returns an array of objects with the following properties: - [string]Name - [string]Value - [bool]Secret - -Limitations on an agent prior to 2.104.1: - 1) The return value does not include all public variables. Only public variables - that have been added using setVariable are returned. - 2) The name returned for each secret variable is the formatted environment variable - name, not the actual variable name (unless it was set explicitly at runtime using - setVariable). -#> -function Get-TaskVariableInfo { - [CmdletBinding()] - param() - - foreach ($info in $script:knownVariables.Values) { - New-Object -TypeName psobject -Property @{ - Name = $info.Name - Value = Get-TaskVariable -Name $info.Name - Secret = $info.Secret - } - } -} - -<# -.SYNOPSIS -Sets a task variable. - -.DESCRIPTION -Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job. -#> -function Set-TaskVariable { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Name, - [string]$Value, - [switch]$Secret) - - # Once a secret always a secret. - $variableKey = Get-VariableKey -Name $Name - [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret - if ($Secret) { - $vaultKey = "SECRET_$variableKey" - if (!$Value) { - # Clear the secret. - Write-Verbose "Set $Name = ''" - $script:vault.Remove($vaultKey) - } else { - # Store the secret in the vault. - Write-Verbose "Set $Name = '********'" - $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential( - $vaultKey, - (ConvertTo-SecureString -String $Value -AsPlainText -Force)) - } - - # Clear the environment variable. - Set-Item -LiteralPath "Env:$variableKey" -Value '' - } else { - # Set the environment variable. - Write-Verbose "Set $Name = '$Value'" - Set-Item -LiteralPath "Env:$variableKey" -Value $Value - } - - # Store the metadata. - $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{ - Name = $name - Secret = $Secret - } - - # Persist the variable in the task context. - Write-SetVariable -Name $Name -Value $Value -Secret:$Secret -} - -######################################## -# Private functions. -######################################## -function Get-VaultValue { - [CmdletBinding(DefaultParameterSetName = 'Require')] - param( - [Parameter(Mandatory = $true)] - [string]$Description, - [Parameter(Mandatory = $true)] - [string]$Key, - [Parameter(ParameterSetName = 'Require')] - [switch]$Require, - [Parameter(ParameterSetName = 'Default')] - [object]$Default, - [switch]$AsBool, - [switch]$AsInt) - - # Attempt to get the vault value. - $value = $null - if ($psCredential = $script:vault[$Key]) { - $value = $psCredential.GetNetworkCredential().Password - } elseif (!$script:nonInteractive) { - # The value wasn't found. Prompt for the value if running in interactive dev mode. - $value = Read-Host -Prompt $Description - if ($value) { - $script:vault[$Key] = New-Object System.Management.Automation.PSCredential( - $Key, - (ConvertTo-SecureString -String $value -AsPlainText -Force)) - } - } - - Get-Value -Value $value @PSBoundParameters -} - -function Get-Value { - [CmdletBinding(DefaultParameterSetName = 'Require')] - param( - [string]$Value, - [Parameter(Mandatory = $true)] - [string]$Description, - [Parameter(Mandatory = $true)] - [string]$Key, - [Parameter(ParameterSetName = 'Require')] - [switch]$Require, - [Parameter(ParameterSetName = 'Default')] - [object]$Default, - [switch]$AsBool, - [switch]$AsInt) - - $result = $Value - if ($result) { - if ($Key -like 'ENDPOINT_AUTH_*') { - Write-Verbose "$($Key): '********'" - } else { - Write-Verbose "$($Key): '$result'" - } - } else { - Write-Verbose "$Key (empty)" - - # Write error if required. - if ($Require) { - Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)" - return - } - - # Fallback to the default if provided. - if ($PSCmdlet.ParameterSetName -eq 'Default') { - $result = $Default - $OFS = ' ' - Write-Verbose " Defaulted to: '$result'" - } else { - $result = '' - } - } - - # Convert to bool if specified. - if ($AsBool) { - if ($result -isnot [bool]) { - $result = "$result" -in '1', 'true' - Write-Verbose " Converted to bool: $result" - } - - return $result - } - - # Convert to int if specified. - if ($AsInt) { - if ($result -isnot [int]) { - try { - $result = [int]"$result" - } catch { - $result = 0 - } - - Write-Verbose " Converted to int: $result" - } - - return $result - } - - return $result -} - -function Initialize-Inputs { - # Store endpoints, inputs, and secret variables in the vault. - foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*)) { - # Record the secret variable metadata. This is required by Get-TaskVariable to - # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten - # when $env:VSTS_SECRET_VARIABLES is processed. - if ($variable.Name -like 'SECRET_?*') { - $variableKey = $variable.Name.Substring('SECRET_'.Length) - $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{ - # This is technically not the variable name (has underscores instead of dots), - # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent - # where $env:VSTS_SECRET_VARIABLES is not defined. - Name = $variableKey - Secret = $true - } - } - - # Store the value in the vault. - $vaultKey = $variable.Name - if ($variable.Value) { - $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential( - $vaultKey, - (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force)) - } - - # Clear the environment variable. - Remove-Item -LiteralPath "Env:$($variable.Name)" - } - - # Record the public variable names. Env var added in 2.104.1 agent. - if ($env:VSTS_PUBLIC_VARIABLES) { - foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) { - $variableKey = Get-VariableKey -Name $name - $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{ - Name = $name - Secret = $false - } - } - - $env:VSTS_PUBLIC_VARIABLES = '' - } - - # Record the secret variable names. Env var added in 2.104.1 agent. - if ($env:VSTS_SECRET_VARIABLES) { - foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) { - $variableKey = Get-VariableKey -Name $name - $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{ - Name = $name - Secret = $true - } - } - - $env:VSTS_SECRET_VARIABLES = '' - } -} - -function Get-VariableKey { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Name) - - if ($Name -ne 'agent.jobstatus') { - $Name = $Name.Replace('.', '_') - } - - $Name.ToUpperInvariant() -} +# Hash table of known variable info. The formatted env var name is the lookup key. +# +# The purpose of this hash table is to keep track of known variables. The hash table +# needs to be maintained for multiple reasons: +# 1) to distinguish between env vars and job vars +# 2) to distinguish between secret vars and public +# 3) to know the real variable name and not just the formatted env var name. +$script:knownVariables = @{ } +$script:vault = @{ } + +<# +.SYNOPSIS +Gets an endpoint. + +.DESCRIPTION +Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url. + +The Data property requires a 1.97 agent or higher. + +.PARAMETER Require +Writes an error to the error pipeline if the endpoint is not found. +#> +function Get-Endpoint { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Name, + [switch]$Require) + + $originalErrorActionPreference = $ErrorActionPreference + try { + $ErrorActionPreference = 'Stop' + + # Get the URL. + $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name + $key = "ENDPOINT_URL_$Name" + $url = Get-VaultValue -Description $description -Key $key -Require:$Require + + # Get the auth object. + $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name + $key = "ENDPOINT_AUTH_$Name" + if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) { + $auth = ConvertFrom-Json -InputObject $auth + } + + # Get the data. + $description = "'$Name' service endpoint data" + $key = "ENDPOINT_DATA_$Name" + if ($data = (Get-VaultValue -Description $description -Key $key)) { + $data = ConvertFrom-Json -InputObject $data + } + + # Return the endpoint. + if ($url -or $auth -or $data) { + New-Object -TypeName psobject -Property @{ + Url = $url + Auth = $auth + Data = $data + } + } + } catch { + $ErrorActionPreference = $originalErrorActionPreference + Write-Error $_ + } +} + +<# +.SYNOPSIS +Gets an input. + +.DESCRIPTION +Gets the value for the specified input name. + +.PARAMETER AsBool +Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false. + +.PARAMETER AsInt +Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails. + +.PARAMETER Default +Default value to use if the input is null or empty. + +.PARAMETER Require +Writes an error to the error pipeline if the input is null or empty. +#> +function Get-Input { + [CmdletBinding(DefaultParameterSetName = 'Require')] + param( + [Parameter(Mandatory = $true)] + [string]$Name, + [Parameter(ParameterSetName = 'Default')] + $Default, + [Parameter(ParameterSetName = 'Require')] + [switch]$Require, + [switch]$AsBool, + [switch]$AsInt) + + # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required + # in order to concisely invoke the correct parameter set. + $null = $PSBoundParameters.Remove('Name') + $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name + $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())" + Get-VaultValue @PSBoundParameters -Description $description -Key $key +} + +<# +.SYNOPSIS +Gets a task variable. + +.DESCRIPTION +Gets the value for the specified task variable. + +.PARAMETER AsBool +Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false. + +.PARAMETER AsInt +Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails. + +.PARAMETER Default +Default value to use if the input is null or empty. + +.PARAMETER Require +Writes an error to the error pipeline if the input is null or empty. +#> +function Get-TaskVariable { + [CmdletBinding(DefaultParameterSetName = 'Require')] + param( + [Parameter(Mandatory = $true)] + [string]$Name, + [Parameter(ParameterSetName = 'Default')] + $Default, + [Parameter(ParameterSetName = 'Require')] + [switch]$Require, + [switch]$AsBool, + [switch]$AsInt) + + $originalErrorActionPreference = $ErrorActionPreference + try { + $ErrorActionPreference = 'Stop' + $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name + $variableKey = Get-VariableKey -Name $Name + if ($script:knownVariables.$variableKey.Secret) { + # Get secret variable. Splatting is required to concisely invoke the correct parameter set. + $null = $PSBoundParameters.Remove('Name') + $vaultKey = "SECRET_$variableKey" + Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey + } else { + # Get public variable. + $item = $null + $path = "Env:$variableKey" + if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) { + # Intentionally empty. Value was successfully retrieved. + } elseif (!$script:nonInteractive) { + # The value wasn't found and the module is running in interactive dev mode. + # Prompt for the value. + Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description) + if (Test-Path -LiteralPath $path) { + $item = Get-Item -LiteralPath $path + } + } + + # Get the converted value. Splatting is required to concisely invoke the correct parameter set. + $null = $PSBoundParameters.Remove('Name') + Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value + } + } catch { + $ErrorActionPreference = $originalErrorActionPreference + Write-Error $_ + } +} + +<# +.SYNOPSIS +Gets all job variables available to the task. Requires 2.104.1 agent or higher. + +.DESCRIPTION +Gets a snapshot of the current state of all job variables available to the task. +Requires a 2.104.1 agent or higher for full functionality. + +Returns an array of objects with the following properties: + [string]Name + [string]Value + [bool]Secret + +Limitations on an agent prior to 2.104.1: + 1) The return value does not include all public variables. Only public variables + that have been added using setVariable are returned. + 2) The name returned for each secret variable is the formatted environment variable + name, not the actual variable name (unless it was set explicitly at runtime using + setVariable). +#> +function Get-TaskVariableInfo { + [CmdletBinding()] + param() + + foreach ($info in $script:knownVariables.Values) { + New-Object -TypeName psobject -Property @{ + Name = $info.Name + Value = Get-TaskVariable -Name $info.Name + Secret = $info.Secret + } + } +} + +<# +.SYNOPSIS +Sets a task variable. + +.DESCRIPTION +Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job. +#> +function Set-TaskVariable { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Name, + [string]$Value, + [switch]$Secret) + + # Once a secret always a secret. + $variableKey = Get-VariableKey -Name $Name + [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret + if ($Secret) { + $vaultKey = "SECRET_$variableKey" + if (!$Value) { + # Clear the secret. + Write-Verbose "Set $Name = ''" + $script:vault.Remove($vaultKey) + } else { + # Store the secret in the vault. + Write-Verbose "Set $Name = '********'" + $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential( + $vaultKey, + (ConvertTo-SecureString -String $Value -AsPlainText -Force)) + } + + # Clear the environment variable. + Set-Item -LiteralPath "Env:$variableKey" -Value '' + } else { + # Set the environment variable. + Write-Verbose "Set $Name = '$Value'" + Set-Item -LiteralPath "Env:$variableKey" -Value $Value + } + + # Store the metadata. + $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{ + Name = $name + Secret = $Secret + } + + # Persist the variable in the task context. + Write-SetVariable -Name $Name -Value $Value -Secret:$Secret +} + +######################################## +# Private functions. +######################################## +function Get-VaultValue { + [CmdletBinding(DefaultParameterSetName = 'Require')] + param( + [Parameter(Mandatory = $true)] + [string]$Description, + [Parameter(Mandatory = $true)] + [string]$Key, + [Parameter(ParameterSetName = 'Require')] + [switch]$Require, + [Parameter(ParameterSetName = 'Default')] + [object]$Default, + [switch]$AsBool, + [switch]$AsInt) + + # Attempt to get the vault value. + $value = $null + if ($psCredential = $script:vault[$Key]) { + $value = $psCredential.GetNetworkCredential().Password + } elseif (!$script:nonInteractive) { + # The value wasn't found. Prompt for the value if running in interactive dev mode. + $value = Read-Host -Prompt $Description + if ($value) { + $script:vault[$Key] = New-Object System.Management.Automation.PSCredential( + $Key, + (ConvertTo-SecureString -String $value -AsPlainText -Force)) + } + } + + Get-Value -Value $value @PSBoundParameters +} + +function Get-Value { + [CmdletBinding(DefaultParameterSetName = 'Require')] + param( + [string]$Value, + [Parameter(Mandatory = $true)] + [string]$Description, + [Parameter(Mandatory = $true)] + [string]$Key, + [Parameter(ParameterSetName = 'Require')] + [switch]$Require, + [Parameter(ParameterSetName = 'Default')] + [object]$Default, + [switch]$AsBool, + [switch]$AsInt) + + $result = $Value + if ($result) { + if ($Key -like 'ENDPOINT_AUTH_*') { + Write-Verbose "$($Key): '********'" + } else { + Write-Verbose "$($Key): '$result'" + } + } else { + Write-Verbose "$Key (empty)" + + # Write error if required. + if ($Require) { + Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)" + return + } + + # Fallback to the default if provided. + if ($PSCmdlet.ParameterSetName -eq 'Default') { + $result = $Default + $OFS = ' ' + Write-Verbose " Defaulted to: '$result'" + } else { + $result = '' + } + } + + # Convert to bool if specified. + if ($AsBool) { + if ($result -isnot [bool]) { + $result = "$result" -in '1', 'true' + Write-Verbose " Converted to bool: $result" + } + + return $result + } + + # Convert to int if specified. + if ($AsInt) { + if ($result -isnot [int]) { + try { + $result = [int]"$result" + } catch { + $result = 0 + } + + Write-Verbose " Converted to int: $result" + } + + return $result + } + + return $result +} + +function Initialize-Inputs { + # Store endpoints, inputs, and secret variables in the vault. + foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*)) { + # Record the secret variable metadata. This is required by Get-TaskVariable to + # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten + # when $env:VSTS_SECRET_VARIABLES is processed. + if ($variable.Name -like 'SECRET_?*') { + $variableKey = $variable.Name.Substring('SECRET_'.Length) + $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{ + # This is technically not the variable name (has underscores instead of dots), + # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent + # where $env:VSTS_SECRET_VARIABLES is not defined. + Name = $variableKey + Secret = $true + } + } + + # Store the value in the vault. + $vaultKey = $variable.Name + if ($variable.Value) { + $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential( + $vaultKey, + (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force)) + } + + # Clear the environment variable. + Remove-Item -LiteralPath "Env:$($variable.Name)" + } + + # Record the public variable names. Env var added in 2.104.1 agent. + if ($env:VSTS_PUBLIC_VARIABLES) { + foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) { + $variableKey = Get-VariableKey -Name $name + $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{ + Name = $name + Secret = $false + } + } + + $env:VSTS_PUBLIC_VARIABLES = '' + } + + # Record the secret variable names. Env var added in 2.104.1 agent. + if ($env:VSTS_SECRET_VARIABLES) { + foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) { + $variableKey = Get-VariableKey -Name $name + $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{ + Name = $name + Secret = $true + } + } + + $env:VSTS_SECRET_VARIABLES = '' + } +} + +function Get-VariableKey { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Name) + + if ($Name -ne 'agent.jobstatus') { + $Name = $Name.Replace('.', '_') + } + + $Name.ToUpperInvariant() +} diff --git a/VersionAssemblies/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/src/ShowVariables/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 similarity index 97% rename from VersionAssemblies/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 rename to src/ShowVariables/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 index b4080ae..f6aaa5a 100644 --- a/VersionAssemblies/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 +++ b/src/ShowVariables/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 @@ -1,320 +1,320 @@ -<# -.SYNOPSIS -Finds files or directories. - -.DESCRIPTION -Finds files or directories using advanced pattern matching. - -.PARAMETER LiteralDirectory -Directory to search. - -.PARAMETER LegacyPattern -Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns. - -Separate multiple patterns using ";". Escape actual ";" in the path by using ";;". -"?" indicates a wildcard that represents any single character within a path segment. -"*" indicates a wildcard that represents zero or more characters within a path segment. -"**" as the entire path segment indicates a recursive search. -"**" within a path segment indicates a recursive intersegment wildcard. -"+:" (can be omitted) indicates an include pattern. -"-:" indicates an exclude pattern. - -The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns. - -.PARAMETER IncludeFiles -Indicates whether to include files in the results. - -If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed. - -.PARAMETER IncludeDirectories -Indicates whether to include directories in the results. - -If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed. - -.PARAMETER Force -Indicates whether to include hidden items. - -.EXAMPLE -Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt" - -Given: -C:\Directory\Is1Match.txt -C:\Directory\Is2Match.txt -C:\Directory\IsNotMatch.txt - -Returns: -C:\Directory\Is1Match.txt -C:\Directory\Is2Match.txt - -.EXAMPLE -Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt" - -Given: -C:\Directory\IsOneMatch.txt -C:\Directory\IsTwoMatch.txt -C:\Directory\NonMatch.txt - -Returns: -C:\Directory\IsOneMatch.txt -C:\Directory\IsTwoMatch.txt - -.EXAMPLE -Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt" - -Given: -C:\Directory\Match.txt -C:\Directory\NotAMatch.txt -C:\Directory\SubDir\Match.txt -C:\Directory\SubDir\SubSubDir\Match.txt - -Returns: -C:\Directory\Match.txt -C:\Directory\SubDir\Match.txt -C:\Directory\SubDir\SubSubDir\Match.txt - -.EXAMPLE -Find-VstsFiles -LegacyPattern "C:\Directory\**" - -Given: -C:\Directory\One.txt -C:\Directory\SubDir\Two.txt -C:\Directory\SubDir\SubSubDir\Three.txt - -Returns: -C:\Directory\One.txt -C:\Directory\SubDir\Two.txt -C:\Directory\SubDir\SubSubDir\Three.txt - -.EXAMPLE -Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt" - -Given: -C:\Directory\IsNotAMatch.txt -C:\Directory\SubDir\IsAMatch.txt -C:\Directory\SubDir\IsNot.txt -C:\Directory\SubDir\SubSubDir\IsAMatch.txt -C:\Directory\SubDir\SubSubDir\IsNot.txt - -Returns: -C:\Directory\SubDir\IsAMatch.txt -C:\Directory\SubDir\SubSubDir\IsAMatch.txt -#> -function Find-Files { - [CmdletBinding()] - param( - [ValidateNotNullOrEmpty()] - [Parameter()] - [string]$LiteralDirectory, - [Parameter(Mandatory = $true)] - [string]$LegacyPattern, - [switch]$IncludeFiles, - [switch]$IncludeDirectories, - [switch]$Force) - - # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator, - # this function does not appear to be able to search the root of a drive and other - # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix. - - Trace-EnteringInvocation $MyInvocation - if (!$IncludeFiles -and !$IncludeDirectories) { - $IncludeFiles = $true - } - - $includePatterns = New-Object System.Collections.Generic.List[string] - $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex] - $LegacyPattern = $LegacyPattern.Replace(';;', "`0") - foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) { - $pattern = $pattern.Replace("`0", ';') - $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern) - if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) { - # Use the root directory provided to make the pattern a rooted path. - $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern) - } - - # Validate pattern does not end with a \. - if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) { - throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern) - } - - if ($isIncludePattern) { - $includePatterns.Add($pattern) - } else { - $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern)) - } - } - - $count = 0 - foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) { - $count++ - $path - } - - Write-Verbose "Total found: $count" - Trace-LeavingInvocation $MyInvocation -} - -######################################## -# Private functions. -######################################## -function Convert-PatternToRegex { - [CmdletBinding()] - param([string]$Pattern) - - $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape. - Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar. - Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators. - Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators. - # bug: should be '[^/]' instead of '.' - Replace('\?', '.') # Replace single character wildcards. - New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase) -} - -function Get-FileNameFilter { - [CmdletBinding()] - param([string]$Pattern) - - $index = $Pattern.LastIndexOf('\') - if ($index -eq -1 -or # Pattern does not contain a backslash. - !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash. - $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard. - { - return '*' - } - - # bug? is this supposed to do substring? - return $Pattern -} - -function Get-MatchingItems { - [CmdletBinding()] - param( - [System.Collections.Generic.List[string]]$IncludePatterns, - [System.Collections.Generic.List[regex]]$ExcludePatterns, - [switch]$IncludeFiles, - [switch]$IncludeDirectories, - [switch]$Force) - - Trace-EnteringInvocation $MyInvocation - $allFiles = New-Object System.Collections.Generic.HashSet[string] - foreach ($pattern in $IncludePatterns) { - $pathPrefix = Get-PathPrefix -Pattern $pattern - $fileNameFilter = Get-FileNameFilter -Pattern $pattern - $patternRegex = Convert-PatternToRegex -Pattern $pattern - # Iterate over the directories and files under the pathPrefix. - Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force | - ForEach-Object { - # Normalize separators. - $normalizedPath = $_.Replace('\', '/') - # **/times/** will not match C:/fun/times because there isn't a trailing slash. - # So try both if including directories. - $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false - # positive if the item is a regular file and not a directory - - $isMatch = $false - if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) { - $isMatch = $true - - # Test whether the path should be excluded. - foreach ($regex in $ExcludePatterns) { - if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) { - $isMatch = $false - break - } - } - } - - if ($isMatch) { - $null = $allFiles.Add($_) - } - } - } - - Trace-Path -Path $allFiles -PassThru - Trace-LeavingInvocation $MyInvocation -} - -function Get-PathIterator { - [CmdletBinding()] - param( - [string]$Path, - [string]$Filter, - [switch]$IncludeFiles, - [switch]$IncludeDirectories, - [switch]$Force) - - if (!$Path) { - return - } - - # bug: this returns the dir without verifying whether exists - if ($IncludeDirectories) { - $Path - } - - Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse | - ForEach-Object { - if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) { - if ($IncludeDirectories) { - $_.FullName - } - } elseif ($IncludeFiles) { - $_.FullName - } - } -} - -function Get-PathPrefix { - [CmdletBinding()] - param([string]$Pattern) - - # Note, unable to search root directories is a limitation due to subtleties of this function - # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty. - # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield - # empty in some cases. See the following examples of Path.GetDirectoryName() input => output: - # C:/ => - # C:/hello => C:\ - # C:/hello/ => C:\hello - # C:/hello/world => C:\hello - # C:/hello/world/ => C:\hello\world - # C: => - # C:hello => C: - # C:hello/ => C:hello - # / => - # /hello => \ - # /hello/ => \hello - # //hello => - # //hello/ => - # //hello/world => - # //hello/world/ => \\hello\world - - $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0])) - if ($index -eq -1) { - # If no wildcards are found, return the directory name portion of the path. - # If there is no directory name (file name only in pattern), this will return empty string. - return [System.IO.Path]::GetDirectoryName($Pattern) - } - - [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index)) -} - -function Test-IsIncludePattern { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [ref]$Pattern) - - # Include patterns start with +: or anything except -: - # Exclude patterns start with -: - if ($Pattern.value.StartsWith("+:")) { - # Remove the prefix. - $Pattern.value = $Pattern.value.Substring(2) - $true - } elseif ($Pattern.value.StartsWith("-:")) { - # Remove the prefix. - $Pattern.value = $Pattern.value.Substring(2) - $false - } else { - # No prefix, so leave the string alone. - $true; - } -} +<# +.SYNOPSIS +Finds files or directories. + +.DESCRIPTION +Finds files or directories using advanced pattern matching. + +.PARAMETER LiteralDirectory +Directory to search. + +.PARAMETER LegacyPattern +Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns. + +Separate multiple patterns using ";". Escape actual ";" in the path by using ";;". +"?" indicates a wildcard that represents any single character within a path segment. +"*" indicates a wildcard that represents zero or more characters within a path segment. +"**" as the entire path segment indicates a recursive search. +"**" within a path segment indicates a recursive intersegment wildcard. +"+:" (can be omitted) indicates an include pattern. +"-:" indicates an exclude pattern. + +The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns. + +.PARAMETER IncludeFiles +Indicates whether to include files in the results. + +If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed. + +.PARAMETER IncludeDirectories +Indicates whether to include directories in the results. + +If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed. + +.PARAMETER Force +Indicates whether to include hidden items. + +.EXAMPLE +Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt" + +Given: +C:\Directory\Is1Match.txt +C:\Directory\Is2Match.txt +C:\Directory\IsNotMatch.txt + +Returns: +C:\Directory\Is1Match.txt +C:\Directory\Is2Match.txt + +.EXAMPLE +Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt" + +Given: +C:\Directory\IsOneMatch.txt +C:\Directory\IsTwoMatch.txt +C:\Directory\NonMatch.txt + +Returns: +C:\Directory\IsOneMatch.txt +C:\Directory\IsTwoMatch.txt + +.EXAMPLE +Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt" + +Given: +C:\Directory\Match.txt +C:\Directory\NotAMatch.txt +C:\Directory\SubDir\Match.txt +C:\Directory\SubDir\SubSubDir\Match.txt + +Returns: +C:\Directory\Match.txt +C:\Directory\SubDir\Match.txt +C:\Directory\SubDir\SubSubDir\Match.txt + +.EXAMPLE +Find-VstsFiles -LegacyPattern "C:\Directory\**" + +Given: +C:\Directory\One.txt +C:\Directory\SubDir\Two.txt +C:\Directory\SubDir\SubSubDir\Three.txt + +Returns: +C:\Directory\One.txt +C:\Directory\SubDir\Two.txt +C:\Directory\SubDir\SubSubDir\Three.txt + +.EXAMPLE +Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt" + +Given: +C:\Directory\IsNotAMatch.txt +C:\Directory\SubDir\IsAMatch.txt +C:\Directory\SubDir\IsNot.txt +C:\Directory\SubDir\SubSubDir\IsAMatch.txt +C:\Directory\SubDir\SubSubDir\IsNot.txt + +Returns: +C:\Directory\SubDir\IsAMatch.txt +C:\Directory\SubDir\SubSubDir\IsAMatch.txt +#> +function Find-Files { + [CmdletBinding()] + param( + [ValidateNotNullOrEmpty()] + [Parameter()] + [string]$LiteralDirectory, + [Parameter(Mandatory = $true)] + [string]$LegacyPattern, + [switch]$IncludeFiles, + [switch]$IncludeDirectories, + [switch]$Force) + + # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator, + # this function does not appear to be able to search the root of a drive and other + # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix. + + Trace-EnteringInvocation $MyInvocation + if (!$IncludeFiles -and !$IncludeDirectories) { + $IncludeFiles = $true + } + + $includePatterns = New-Object System.Collections.Generic.List[string] + $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex] + $LegacyPattern = $LegacyPattern.Replace(';;', "`0") + foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) { + $pattern = $pattern.Replace("`0", ';') + $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern) + if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) { + # Use the root directory provided to make the pattern a rooted path. + $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern) + } + + # Validate pattern does not end with a \. + if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) { + throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern) + } + + if ($isIncludePattern) { + $includePatterns.Add($pattern) + } else { + $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern)) + } + } + + $count = 0 + foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) { + $count++ + $path + } + + Write-Verbose "Total found: $count" + Trace-LeavingInvocation $MyInvocation +} + +######################################## +# Private functions. +######################################## +function Convert-PatternToRegex { + [CmdletBinding()] + param([string]$Pattern) + + $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape. + Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar. + Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators. + Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators. + # bug: should be '[^/]' instead of '.' + Replace('\?', '.') # Replace single character wildcards. + New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase) +} + +function Get-FileNameFilter { + [CmdletBinding()] + param([string]$Pattern) + + $index = $Pattern.LastIndexOf('\') + if ($index -eq -1 -or # Pattern does not contain a backslash. + !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash. + $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard. + { + return '*' + } + + # bug? is this supposed to do substring? + return $Pattern +} + +function Get-MatchingItems { + [CmdletBinding()] + param( + [System.Collections.Generic.List[string]]$IncludePatterns, + [System.Collections.Generic.List[regex]]$ExcludePatterns, + [switch]$IncludeFiles, + [switch]$IncludeDirectories, + [switch]$Force) + + Trace-EnteringInvocation $MyInvocation + $allFiles = New-Object System.Collections.Generic.HashSet[string] + foreach ($pattern in $IncludePatterns) { + $pathPrefix = Get-PathPrefix -Pattern $pattern + $fileNameFilter = Get-FileNameFilter -Pattern $pattern + $patternRegex = Convert-PatternToRegex -Pattern $pattern + # Iterate over the directories and files under the pathPrefix. + Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force | + ForEach-Object { + # Normalize separators. + $normalizedPath = $_.Replace('\', '/') + # **/times/** will not match C:/fun/times because there isn't a trailing slash. + # So try both if including directories. + $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false + # positive if the item is a regular file and not a directory + + $isMatch = $false + if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) { + $isMatch = $true + + # Test whether the path should be excluded. + foreach ($regex in $ExcludePatterns) { + if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) { + $isMatch = $false + break + } + } + } + + if ($isMatch) { + $null = $allFiles.Add($_) + } + } + } + + Trace-Path -Path $allFiles -PassThru + Trace-LeavingInvocation $MyInvocation +} + +function Get-PathIterator { + [CmdletBinding()] + param( + [string]$Path, + [string]$Filter, + [switch]$IncludeFiles, + [switch]$IncludeDirectories, + [switch]$Force) + + if (!$Path) { + return + } + + # bug: this returns the dir without verifying whether exists + if ($IncludeDirectories) { + $Path + } + + Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse | + ForEach-Object { + if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) { + if ($IncludeDirectories) { + $_.FullName + } + } elseif ($IncludeFiles) { + $_.FullName + } + } +} + +function Get-PathPrefix { + [CmdletBinding()] + param([string]$Pattern) + + # Note, unable to search root directories is a limitation due to subtleties of this function + # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty. + # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield + # empty in some cases. See the following examples of Path.GetDirectoryName() input => output: + # C:/ => + # C:/hello => C:\ + # C:/hello/ => C:\hello + # C:/hello/world => C:\hello + # C:/hello/world/ => C:\hello\world + # C: => + # C:hello => C: + # C:hello/ => C:hello + # / => + # /hello => \ + # /hello/ => \hello + # //hello => + # //hello/ => + # //hello/world => + # //hello/world/ => \\hello\world + + $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0])) + if ($index -eq -1) { + # If no wildcards are found, return the directory name portion of the path. + # If there is no directory name (file name only in pattern), this will return empty string. + return [System.IO.Path]::GetDirectoryName($Pattern) + } + + [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index)) +} + +function Test-IsIncludePattern { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [ref]$Pattern) + + # Include patterns start with +: or anything except -: + # Exclude patterns start with -: + if ($Pattern.value.StartsWith("+:")) { + # Remove the prefix. + $Pattern.value = $Pattern.value.Substring(2) + $true + } elseif ($Pattern.value.StartsWith("-:")) { + # Remove the prefix. + $Pattern.value = $Pattern.value.Substring(2) + $false + } else { + # No prefix, so leave the string alone. + $true; + } +} diff --git a/VersionAssemblies/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/src/ShowVariables/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 similarity index 97% rename from VersionAssemblies/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 rename to src/ShowVariables/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 index c31790c..6f3b6bb 100644 --- a/VersionAssemblies/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 +++ b/src/ShowVariables/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 @@ -1,150 +1,150 @@ -$script:resourceStrings = @{ } - -<# -.SYNOPSIS -Gets a localized resource string. - -.DESCRIPTION -Gets a localized resource string and optionally formats the string with arguments. - -If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space). - -If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space). - -.PARAMETER Require -Writes an error to the error pipeline if the endpoint is not found. -#> -function Get-LocString { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true, Position = 1)] - [string]$Key, - [Parameter(Position = 2)] - [object[]]$ArgumentList = @( )) - - # Due to the dynamically typed nature of PowerShell, a single null argument passed - # to an array parameter is interpreted as a null array. - if ([object]::ReferenceEquals($null, $ArgumentList)) { - $ArgumentList = @( $null ) - } - - # Lookup the format string. - $format = '' - if (!($format = $script:resourceStrings[$Key])) { - # Warn the key was not found. Prevent recursion if the lookup key is the - # "string resource key not found" lookup key. - $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0' - if ($key -ne $resourceNotFoundKey) { - Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key) - } - - # Fallback to just the key itself if there aren't any arguments to format. - if (!$ArgumentList.Count) { return $key } - - # Otherwise fallback to the key followed by the arguments. - $OFS = " " - return "$key $ArgumentList" - } - - # Return the string if there aren't any arguments to format. - if (!$ArgumentList.Count) { return $format } - - try { - [string]::Format($format, $ArgumentList) - } catch { - Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed') - $OFS = " " - "$format $ArgumentList" - } -} - -<# -.SYNOPSIS -Imports resource strings for use with Get-VstsLocString. - -.DESCRIPTION -Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary. - -Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings. - -.Parameter LiteralPath -JSON file containing resource strings. - -.EXAMPLE -Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json - -Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section: -{ - "messages": { - "Hello": "Hello you!", - "Hello0": "Hello {0}!" - } -} - -.EXAMPLE -Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json - -Overlays strings from an optional separate resource file for the current culture. - -Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job. -Given the file Task.json contains: -{ - "messages": { - "GoodDay": "Good day!", - } -} -Given the file resources.resjson\de-DE\resources.resjson: -{ - "loc.messages.GoodDay": "Guten Tag!" -} - -The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!' -#> -function Import-LocStrings { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$LiteralPath) - - # Validate the file exists. - if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) { - Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath) - return - } - - # Load the json. - Write-Verbose "Loading resource strings from: $LiteralPath" - $count = 0 - if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) { - # Add each resource string to the hashtable. - foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) { - [string]$key = $member.Name - $script:resourceStrings[$key] = $messages."$key" - $count++ - } - } - - Write-Verbose "Loaded $count strings." - - # Get the culture. - $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US" - - # Load the resjson. - $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson" - if (Test-Path -LiteralPath $resjsonPath) { - Write-Verbose "Loading resource strings from: $resjsonPath" - $count = 0 - $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json - foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) { - if (!($value = $resjson."$($member.Name)")) { - continue - } - - [string]$key = $member.Name.Substring('loc.messages.'.Length) - $script:resourceStrings[$key] = $value - $count++ - } - - Write-Verbose "Loaded $count strings." - } -} +$script:resourceStrings = @{ } + +<# +.SYNOPSIS +Gets a localized resource string. + +.DESCRIPTION +Gets a localized resource string and optionally formats the string with arguments. + +If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space). + +If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space). + +.PARAMETER Require +Writes an error to the error pipeline if the endpoint is not found. +#> +function Get-LocString { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true, Position = 1)] + [string]$Key, + [Parameter(Position = 2)] + [object[]]$ArgumentList = @( )) + + # Due to the dynamically typed nature of PowerShell, a single null argument passed + # to an array parameter is interpreted as a null array. + if ([object]::ReferenceEquals($null, $ArgumentList)) { + $ArgumentList = @( $null ) + } + + # Lookup the format string. + $format = '' + if (!($format = $script:resourceStrings[$Key])) { + # Warn the key was not found. Prevent recursion if the lookup key is the + # "string resource key not found" lookup key. + $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0' + if ($key -ne $resourceNotFoundKey) { + Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key) + } + + # Fallback to just the key itself if there aren't any arguments to format. + if (!$ArgumentList.Count) { return $key } + + # Otherwise fallback to the key followed by the arguments. + $OFS = " " + return "$key $ArgumentList" + } + + # Return the string if there aren't any arguments to format. + if (!$ArgumentList.Count) { return $format } + + try { + [string]::Format($format, $ArgumentList) + } catch { + Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed') + $OFS = " " + "$format $ArgumentList" + } +} + +<# +.SYNOPSIS +Imports resource strings for use with Get-VstsLocString. + +.DESCRIPTION +Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary. + +Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings. + +.Parameter LiteralPath +JSON file containing resource strings. + +.EXAMPLE +Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json + +Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section: +{ + "messages": { + "Hello": "Hello you!", + "Hello0": "Hello {0}!" + } +} + +.EXAMPLE +Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json + +Overlays strings from an optional separate resource file for the current culture. + +Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job. +Given the file Task.json contains: +{ + "messages": { + "GoodDay": "Good day!", + } +} +Given the file resources.resjson\de-DE\resources.resjson: +{ + "loc.messages.GoodDay": "Guten Tag!" +} + +The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!' +#> +function Import-LocStrings { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$LiteralPath) + + # Validate the file exists. + if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) { + Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath) + return + } + + # Load the json. + Write-Verbose "Loading resource strings from: $LiteralPath" + $count = 0 + if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) { + # Add each resource string to the hashtable. + foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) { + [string]$key = $member.Name + $script:resourceStrings[$key] = $messages."$key" + $count++ + } + } + + Write-Verbose "Loaded $count strings." + + # Get the culture. + $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US" + + # Load the resjson. + $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson" + if (Test-Path -LiteralPath $resjsonPath) { + Write-Verbose "Loading resource strings from: $resjsonPath" + $count = 0 + $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json + foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) { + if (!($value = $resjson."$($member.Name)")) { + continue + } + + [string]$key = $member.Name.Substring('loc.messages.'.Length) + $script:resourceStrings[$key] = $value + $count++ + } + + Write-Verbose "Loaded $count strings." + } +} diff --git a/VersionAssemblies/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/src/ShowVariables/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 similarity index 96% rename from VersionAssemblies/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 rename to src/ShowVariables/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 index f7ca5c1..a8462ef 100644 --- a/VersionAssemblies/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 +++ b/src/ShowVariables/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 @@ -1,506 +1,506 @@ -$script:loggingCommandPrefix = '##vso[' -$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"? - New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' } - New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' } - New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' } -) -# TODO: BUG: Escape ] -# TODO: BUG: Escape % ??? -# TODO: Add test to verify don't need to escape "=". - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-AddAttachment { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Type, - [Parameter(Mandatory = $true)] - [string]$Name, - [Parameter(Mandatory = $true)] - [string]$Path, - [switch]$AsOutput) - - Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{ - 'type' = $Type - 'name' = $Name - } -AsOutput:$AsOutput -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-AddBuildTag { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Value, - [switch]$AsOutput) - - Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-AssociateArtifact { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Name, - [Parameter(Mandatory = $true)] - [string]$Path, - [Parameter(Mandatory = $true)] - [string]$Type, - [hashtable]$Properties, - [switch]$AsOutput) - - $p = @{ } - if ($Properties) { - foreach ($key in $Properties.Keys) { - $p[$key] = $Properties[$key] - } - } - - $p['artifactname'] = $Name - $p['artifacttype'] = $Type - Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-LogDetail { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [guid]$Id, - $ParentId, - [string]$Type, - [string]$Name, - $Order, - $StartTime, - $FinishTime, - $Progress, - [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')] - [Parameter()] - $State, - [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')] - [Parameter()] - $Result, - [string]$Message, - [switch]$AsOutput) - - Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{ - 'id' = $Id - 'parentid' = $ParentId - 'type' = $Type - 'name' = $Name - 'order' = $Order - 'starttime' = $StartTime - 'finishtime' = $FinishTime - 'progress' = $Progress - 'state' = $State - 'result' = $Result - } -AsOutput:$AsOutput -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-SetProgress { - [CmdletBinding()] - param( - [ValidateRange(0, 100)] - [Parameter(Mandatory = $true)] - [int]$Percent, - [string]$CurrentOperation, - [switch]$AsOutput) - - Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{ - 'value' = $Percent - } -AsOutput:$AsOutput -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-SetResult { - [CmdletBinding(DefaultParameterSetName = 'AsOutput')] - param( - [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")] - [Parameter(Mandatory = $true)] - [string]$Result, - [string]$Message, - [Parameter(ParameterSetName = 'AsOutput')] - [switch]$AsOutput, - [Parameter(ParameterSetName = 'DoNotThrow')] - [switch]$DoNotThrow) - - Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{ - 'result' = $Result - } -AsOutput:$AsOutput - if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) { - # Special internal exception type to control the flow. Not currently intended - # for public usage and subject to change. - throw (New-Object VstsTaskSdk.TerminationException($Message)) - } -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-SetSecret { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Value, - [switch]$AsOutput) - - Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-SetVariable { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Name, - [string]$Value, - [switch]$Secret, - [switch]$AsOutput) - - Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{ - 'variable' = $Name - 'issecret' = $Secret - } -AsOutput:$AsOutput -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-TaskDebug { - [CmdletBinding()] - param( - [string]$Message, - [switch]$AsOutput) - - Write-TaskDebug_Internal @PSBoundParameters -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-TaskError { - [CmdletBinding()] - param( - [string]$Message, - [string]$ErrCode, - [string]$SourcePath, - [string]$LineNumber, - [string]$ColumnNumber, - [switch]$AsOutput) - - Write-LogIssue -Type error @PSBoundParameters -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-TaskVerbose { - [CmdletBinding()] - param( - [string]$Message, - [switch]$AsOutput) - - Write-TaskDebug_Internal @PSBoundParameters -AsVerbose -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-TaskWarning { - [CmdletBinding()] - param( - [string]$Message, - [string]$ErrCode, - [string]$SourcePath, - [string]$LineNumber, - [string]$ColumnNumber, - [switch]$AsOutput) - - Write-LogIssue -Type warning @PSBoundParameters -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-UpdateBuildNumber { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Value, - [switch]$AsOutput) - - Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-UploadArtifact { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$ContainerFolder, - [Parameter(Mandatory = $true)] - [string]$Name, - [Parameter(Mandatory = $true)] - [string]$Path, - [switch]$AsOutput) - - Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{ - 'containerfolder' = $ContainerFolder - 'artifactname' = $Name - } -AsOutput:$AsOutput -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-UploadBuildLog { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Path, - [switch]$AsOutput) - - Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput -} - -######################################## -# Private functions. -######################################## -function Format-LoggingCommandData { - [CmdletBinding()] - param([string]$Value, [switch]$Reverse) - - if (!$Value) { - return '' - } - - if (!$Reverse) { - foreach ($mapping in $script:loggingCommandEscapeMappings) { - $Value = $Value.Replace($mapping.Token, $mapping.Replacement) - } - } else { - for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) { - $mapping = $script:loggingCommandEscapeMappings[$i] - $Value = $Value.Replace($mapping.Replacement, $mapping.Token) - } - } - - return $Value -} - -function Format-LoggingCommand { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Area, - [Parameter(Mandatory = $true)] - [string]$Event, - [string]$Data, - [hashtable]$Properties) - - # Append the preamble. - [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder - $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event) - - # Append the properties. - if ($Properties) { - $first = $true - foreach ($key in $Properties.Keys) { - [string]$value = Format-LoggingCommandData $Properties[$key] - if ($value) { - if ($first) { - $null = $sb.Append(' ') - $first = $false - } else { - $null = $sb.Append(';') - } - - $null = $sb.Append("$key=$value") - } - } - } - - # Append the tail and output the value. - $Data = Format-LoggingCommandData $Data - $sb.Append(']').Append($Data).ToString() -} - -function Write-LoggingCommand { - [CmdletBinding(DefaultParameterSetName = 'Parameters')] - param( - [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')] - [string]$Area, - [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')] - [string]$Event, - [Parameter(ParameterSetName = 'Parameters')] - [string]$Data, - [Parameter(ParameterSetName = 'Parameters')] - [hashtable]$Properties, - [Parameter(Mandatory = $true, ParameterSetName = 'Object')] - $Command, - [switch]$AsOutput) - - if ($PSCmdlet.ParameterSetName -eq 'Object') { - Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput - return - } - - $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties - if ($AsOutput) { - $command - } else { - Write-Host $command - } -} - -function Write-LogIssue { - [CmdletBinding()] - param( - [ValidateSet('warning', 'error')] - [Parameter(Mandatory = $true)] - [string]$Type, - [string]$Message, - [string]$ErrCode, - [string]$SourcePath, - [string]$LineNumber, - [string]$ColumnNumber, - [switch]$AsOutput) - - $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{ - 'type' = $Type - 'code' = $ErrCode - 'sourcepath' = $SourcePath - 'linenumber' = $LineNumber - 'columnnumber' = $ColumnNumber - } - if ($AsOutput) { - return $command - } - - if ($Type -eq 'error') { - $foregroundColor = $host.PrivateData.ErrorForegroundColor - $backgroundColor = $host.PrivateData.ErrorBackgroundColor - if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) { - $foregroundColor = [System.ConsoleColor]::Red - $backgroundColor = [System.ConsoleColor]::Black - } - } else { - $foregroundColor = $host.PrivateData.WarningForegroundColor - $backgroundColor = $host.PrivateData.WarningBackgroundColor - if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) { - $foregroundColor = [System.ConsoleColor]::Yellow - $backgroundColor = [System.ConsoleColor]::Black - } - } - - Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor -} - -function Write-TaskDebug_Internal { - [CmdletBinding()] - param( - [string]$Message, - [switch]$AsVerbose, - [switch]$AsOutput) - - $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message - if ($AsOutput) { - return $command - } - - if ($AsVerbose) { - $foregroundColor = $host.PrivateData.VerboseForegroundColor - $backgroundColor = $host.PrivateData.VerboseBackgroundColor - if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) { - $foregroundColor = [System.ConsoleColor]::Cyan - $backgroundColor = [System.ConsoleColor]::Black - } - } else { - $foregroundColor = $host.PrivateData.DebugForegroundColor - $backgroundColor = $host.PrivateData.DebugBackgroundColor - if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) { - $foregroundColor = [System.ConsoleColor]::DarkGray - $backgroundColor = [System.ConsoleColor]::Black - } - } - - Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor -} +$script:loggingCommandPrefix = '##vso[' +$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"? + New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' } + New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' } + New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' } +) +# TODO: BUG: Escape ] +# TODO: BUG: Escape % ??? +# TODO: Add test to verify don't need to escape "=". + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-AddAttachment { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Type, + [Parameter(Mandatory = $true)] + [string]$Name, + [Parameter(Mandatory = $true)] + [string]$Path, + [switch]$AsOutput) + + Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{ + 'type' = $Type + 'name' = $Name + } -AsOutput:$AsOutput +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-AddBuildTag { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Value, + [switch]$AsOutput) + + Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-AssociateArtifact { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Name, + [Parameter(Mandatory = $true)] + [string]$Path, + [Parameter(Mandatory = $true)] + [string]$Type, + [hashtable]$Properties, + [switch]$AsOutput) + + $p = @{ } + if ($Properties) { + foreach ($key in $Properties.Keys) { + $p[$key] = $Properties[$key] + } + } + + $p['artifactname'] = $Name + $p['artifacttype'] = $Type + Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-LogDetail { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [guid]$Id, + $ParentId, + [string]$Type, + [string]$Name, + $Order, + $StartTime, + $FinishTime, + $Progress, + [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')] + [Parameter()] + $State, + [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')] + [Parameter()] + $Result, + [string]$Message, + [switch]$AsOutput) + + Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{ + 'id' = $Id + 'parentid' = $ParentId + 'type' = $Type + 'name' = $Name + 'order' = $Order + 'starttime' = $StartTime + 'finishtime' = $FinishTime + 'progress' = $Progress + 'state' = $State + 'result' = $Result + } -AsOutput:$AsOutput +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-SetProgress { + [CmdletBinding()] + param( + [ValidateRange(0, 100)] + [Parameter(Mandatory = $true)] + [int]$Percent, + [string]$CurrentOperation, + [switch]$AsOutput) + + Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{ + 'value' = $Percent + } -AsOutput:$AsOutput +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-SetResult { + [CmdletBinding(DefaultParameterSetName = 'AsOutput')] + param( + [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")] + [Parameter(Mandatory = $true)] + [string]$Result, + [string]$Message, + [Parameter(ParameterSetName = 'AsOutput')] + [switch]$AsOutput, + [Parameter(ParameterSetName = 'DoNotThrow')] + [switch]$DoNotThrow) + + Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{ + 'result' = $Result + } -AsOutput:$AsOutput + if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) { + # Special internal exception type to control the flow. Not currently intended + # for public usage and subject to change. + throw (New-Object VstsTaskSdk.TerminationException($Message)) + } +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-SetSecret { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Value, + [switch]$AsOutput) + + Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-SetVariable { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Name, + [string]$Value, + [switch]$Secret, + [switch]$AsOutput) + + Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{ + 'variable' = $Name + 'issecret' = $Secret + } -AsOutput:$AsOutput +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-TaskDebug { + [CmdletBinding()] + param( + [string]$Message, + [switch]$AsOutput) + + Write-TaskDebug_Internal @PSBoundParameters +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-TaskError { + [CmdletBinding()] + param( + [string]$Message, + [string]$ErrCode, + [string]$SourcePath, + [string]$LineNumber, + [string]$ColumnNumber, + [switch]$AsOutput) + + Write-LogIssue -Type error @PSBoundParameters +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-TaskVerbose { + [CmdletBinding()] + param( + [string]$Message, + [switch]$AsOutput) + + Write-TaskDebug_Internal @PSBoundParameters -AsVerbose +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-TaskWarning { + [CmdletBinding()] + param( + [string]$Message, + [string]$ErrCode, + [string]$SourcePath, + [string]$LineNumber, + [string]$ColumnNumber, + [switch]$AsOutput) + + Write-LogIssue -Type warning @PSBoundParameters +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-UpdateBuildNumber { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Value, + [switch]$AsOutput) + + Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-UploadArtifact { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$ContainerFolder, + [Parameter(Mandatory = $true)] + [string]$Name, + [Parameter(Mandatory = $true)] + [string]$Path, + [switch]$AsOutput) + + Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{ + 'containerfolder' = $ContainerFolder + 'artifactname' = $Name + } -AsOutput:$AsOutput +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-UploadBuildLog { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Path, + [switch]$AsOutput) + + Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput +} + +######################################## +# Private functions. +######################################## +function Format-LoggingCommandData { + [CmdletBinding()] + param([string]$Value, [switch]$Reverse) + + if (!$Value) { + return '' + } + + if (!$Reverse) { + foreach ($mapping in $script:loggingCommandEscapeMappings) { + $Value = $Value.Replace($mapping.Token, $mapping.Replacement) + } + } else { + for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) { + $mapping = $script:loggingCommandEscapeMappings[$i] + $Value = $Value.Replace($mapping.Replacement, $mapping.Token) + } + } + + return $Value +} + +function Format-LoggingCommand { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Area, + [Parameter(Mandatory = $true)] + [string]$Event, + [string]$Data, + [hashtable]$Properties) + + # Append the preamble. + [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder + $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event) + + # Append the properties. + if ($Properties) { + $first = $true + foreach ($key in $Properties.Keys) { + [string]$value = Format-LoggingCommandData $Properties[$key] + if ($value) { + if ($first) { + $null = $sb.Append(' ') + $first = $false + } else { + $null = $sb.Append(';') + } + + $null = $sb.Append("$key=$value") + } + } + } + + # Append the tail and output the value. + $Data = Format-LoggingCommandData $Data + $sb.Append(']').Append($Data).ToString() +} + +function Write-LoggingCommand { + [CmdletBinding(DefaultParameterSetName = 'Parameters')] + param( + [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')] + [string]$Area, + [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')] + [string]$Event, + [Parameter(ParameterSetName = 'Parameters')] + [string]$Data, + [Parameter(ParameterSetName = 'Parameters')] + [hashtable]$Properties, + [Parameter(Mandatory = $true, ParameterSetName = 'Object')] + $Command, + [switch]$AsOutput) + + if ($PSCmdlet.ParameterSetName -eq 'Object') { + Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput + return + } + + $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties + if ($AsOutput) { + $command + } else { + Write-Host $command + } +} + +function Write-LogIssue { + [CmdletBinding()] + param( + [ValidateSet('warning', 'error')] + [Parameter(Mandatory = $true)] + [string]$Type, + [string]$Message, + [string]$ErrCode, + [string]$SourcePath, + [string]$LineNumber, + [string]$ColumnNumber, + [switch]$AsOutput) + + $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{ + 'type' = $Type + 'code' = $ErrCode + 'sourcepath' = $SourcePath + 'linenumber' = $LineNumber + 'columnnumber' = $ColumnNumber + } + if ($AsOutput) { + return $command + } + + if ($Type -eq 'error') { + $foregroundColor = $host.PrivateData.ErrorForegroundColor + $backgroundColor = $host.PrivateData.ErrorBackgroundColor + if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) { + $foregroundColor = [System.ConsoleColor]::Red + $backgroundColor = [System.ConsoleColor]::Black + } + } else { + $foregroundColor = $host.PrivateData.WarningForegroundColor + $backgroundColor = $host.PrivateData.WarningBackgroundColor + if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) { + $foregroundColor = [System.ConsoleColor]::Yellow + $backgroundColor = [System.ConsoleColor]::Black + } + } + + Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor +} + +function Write-TaskDebug_Internal { + [CmdletBinding()] + param( + [string]$Message, + [switch]$AsVerbose, + [switch]$AsOutput) + + $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message + if ($AsOutput) { + return $command + } + + if ($AsVerbose) { + $foregroundColor = $host.PrivateData.VerboseForegroundColor + $backgroundColor = $host.PrivateData.VerboseBackgroundColor + if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) { + $foregroundColor = [System.ConsoleColor]::Cyan + $backgroundColor = [System.ConsoleColor]::Black + } + } else { + $foregroundColor = $host.PrivateData.DebugForegroundColor + $backgroundColor = $host.PrivateData.DebugBackgroundColor + if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) { + $foregroundColor = [System.ConsoleColor]::DarkGray + $backgroundColor = [System.ConsoleColor]::Black + } + } + + Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor +} diff --git a/ShowVariables/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/src/ShowVariables/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 similarity index 97% rename from ShowVariables/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 rename to src/ShowVariables/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 index 5fc2f8a..f81e377 100644 --- a/ShowVariables/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 +++ b/src/ShowVariables/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 @@ -1,368 +1,368 @@ -######################################## -# Private functions. -######################################## -function ConvertFrom-LongFormPath { - [CmdletBinding()] - param([string]$Path) - - if ($Path) { - if ($Path.StartsWith('\\?\UNC')) { - # E.g. \\?\UNC\server\share -> \\server\share - return $Path.Substring(1, '\?\UNC'.Length) - } elseif ($Path.StartsWith('\\?\')) { - # E.g. \\?\C:\directory -> C:\directory - return $Path.Substring('\\?\'.Length) - } - } - - return $Path -} -function ConvertTo-LongFormPath { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Path) - - [string]$longFormPath = Get-FullNormalizedPath -Path $Path - if ($longFormPath -and !$longFormPath.StartsWith('\\?')) { - if ($longFormPath.StartsWith('\\')) { - # E.g. \\server\share -> \\?\UNC\server\share - return "\\?\UNC$($longFormPath.Substring(1))" - } else { - # E.g. C:\directory -> \\?\C:\directory - return "\\?\$longFormPath" - } - } - - return $longFormPath -} - -# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS. -function Get-DirectoryChildItem { - [CmdletBinding()] - param( - [string]$Path, - [ValidateNotNullOrEmpty()] - [Parameter()] - [string]$Filter = "*", - [switch]$Force, - [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch, - [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic, - [switch]$Recurse) - - $stackOfDirectoryQueues = New-Object System.Collections.Stack - while ($true) { - $directoryQueue = New-Object System.Collections.Queue - $fileQueue = New-Object System.Collections.Queue - $findData = New-Object VstsTaskSdk.FS.FindData - $longFormPath = (ConvertTo-LongFormPath $Path) - $handle = $null - try { - $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx( - [System.IO.Path]::Combine($longFormPath, $Filter), - $InfoLevel, - $findData, - [VstsTaskSdk.FS.FindSearchOps]::NameMatch, - [System.IntPtr]::Zero, - $Flags) - if (!$handle.IsInvalid) { - while ($true) { - if ($findData.fileName -notin '.', '..') { - $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes - # If the item is hidden, check if $Force is specified. - if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) { - # Create the item. - $item = New-Object -TypeName psobject -Property @{ - 'Attributes' = $attributes - 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName))) - 'Name' = $findData.fileName - } - # Output directories immediately. - if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) { - $item - # Append to the directory queue if recursive and default filter. - if ($Recurse -and $Filter -eq '*') { - $directoryQueue.Enqueue($item) - } - } else { - # Hold the files until all directories have been output. - $fileQueue.Enqueue($item) - } - } - } - - if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break } - - if ($handle.IsInvalid) { - throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @( - [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() - Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path - )) - } - } - } - } finally { - if ($handle -ne $null) { $handle.Dispose() } - } - - # If recursive and non-default filter, queue child directories. - if ($Recurse -and $Filter -ne '*') { - $findData = New-Object VstsTaskSdk.FS.FindData - $handle = $null - try { - $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx( - [System.IO.Path]::Combine($longFormPath, '*'), - [VstsTaskSdk.FS.FindInfoLevel]::Basic, - $findData, - [VstsTaskSdk.FS.FindSearchOps]::NameMatch, - [System.IntPtr]::Zero, - $Flags) - if (!$handle.IsInvalid) { - while ($true) { - if ($findData.fileName -notin '.', '..') { - $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes - # If the item is hidden, check if $Force is specified. - if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) { - # Collect directories only. - if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) { - # Create the item. - $item = New-Object -TypeName psobject -Property @{ - 'Attributes' = $attributes - 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName))) - 'Name' = $findData.fileName - } - $directoryQueue.Enqueue($item) - } - } - } - - if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break } - - if ($handle.IsInvalid) { - throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @( - [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() - Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path - )) - } - } - } - } finally { - if ($handle -ne $null) { $handle.Dispose() } - } - } - - # Output the files. - $fileQueue - - # Push the directory queue onto the stack if any directories were found. - if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) } - - # Break out of the loop if no more directory queues to process. - if (!$stackOfDirectoryQueues.Count) { break } - - # Get the next path. - $directoryQueue = $stackOfDirectoryQueues.Peek() - $Path = $directoryQueue.Dequeue().FullName - - # Pop the directory queue if it's empty. - if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() } - } -} - -function Get-FullNormalizedPath { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Path) - - [string]$outPath = $Path - [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null) - [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() - if ($bufferSize -gt 0) { - $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize) - [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null) - $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() - if ($length -gt 0) { - $outPath = $absolutePath.ToString() - } else { - throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @( - $lastWin32Error - Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path - )) - } - } else { - throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @( - $lastWin32Error - Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path - )) - } - - if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) { - $outPath = $outPath.TrimEnd('\') - } - - $outPath -} - -######################################## -# Types. -######################################## -# If the type has already been loaded once, then it is not loaded again. -Write-Verbose "Adding long path native methods." -Add-Type -Debug:$false -TypeDefinition @' -namespace VstsTaskSdk.FS -{ - using System; - using System.Runtime.InteropServices; - - public static class NativeMethods - { - private const string Kernel32Dll = "kernel32.dll"; - - [DllImport(Kernel32Dll, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool FindClose(IntPtr hFindFile); - - // HANDLE WINAPI FindFirstFile( - // _In_ LPCTSTR lpFileName, - // _Out_ LPWIN32_FIND_DATA lpFindFileData - // ); - [DllImport(Kernel32Dll, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)] - public static extern SafeFindHandle FindFirstFile( - [MarshalAs(UnmanagedType.LPTStr)] - string fileName, - [In, Out] FindData findFileData - ); - - //HANDLE WINAPI FindFirstFileEx( - // _In_ LPCTSTR lpFileName, - // _In_ FINDEX_INFO_LEVELS fInfoLevelId, - // _Out_ LPVOID lpFindFileData, - // _In_ FINDEX_SEARCH_OPS fSearchOp, - // _Reserved_ LPVOID lpSearchFilter, - // _In_ DWORD dwAdditionalFlags - //); - [DllImport(Kernel32Dll, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)] - public static extern SafeFindHandle FindFirstFileEx( - [MarshalAs(UnmanagedType.LPTStr)] - string fileName, - [In] FindInfoLevel fInfoLevelId, - [In, Out] FindData lpFindFileData, - [In] FindSearchOps fSearchOp, - IntPtr lpSearchFilter, - [In] FindFlags dwAdditionalFlags - ); - - [DllImport(Kernel32Dll, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool FindNextFile(SafeFindHandle hFindFile, [In, Out] FindData lpFindFileData); - - [DllImport(Kernel32Dll, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)] - public static extern int GetFileAttributes(string lpFileName); - - [DllImport(Kernel32Dll, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)] - public static extern uint GetFullPathName( - [MarshalAs(UnmanagedType.LPTStr)] - string lpFileName, - uint nBufferLength, - [Out] - System.Text.StringBuilder lpBuffer, - System.Text.StringBuilder lpFilePart - ); - } - - //for mapping to the WIN32_FIND_DATA native structure - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public sealed class FindData - { - // NOTE: - // Although it may seem correct to Marshal the string members of this class as UnmanagedType.LPWStr, they - // must explicitly remain UnmanagedType.ByValTStr with the size constraints noted. Otherwise we end up with - // COM Interop exceptions while trying to marshal the data across the PInvoke boundaries. - public int fileAttributes; - public System.Runtime.InteropServices.ComTypes.FILETIME creationTime; - public System.Runtime.InteropServices.ComTypes.FILETIME lastAccessTime; - public System.Runtime.InteropServices.ComTypes.FILETIME lastWriteTime; - public int nFileSizeHigh; - public int nFileSizeLow; - public int dwReserved0; - public int dwReserved1; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] - public string fileName; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)] - public string alternateFileName; - } - - //A Win32 safe find handle in which a return value of -1 indicates it's invalid - public sealed class SafeFindHandle : Microsoft.Win32.SafeHandles.SafeHandleMinusOneIsInvalid - { - public SafeFindHandle() - : base(true) - { - return; - } - - [System.Runtime.ConstrainedExecution.ReliabilityContract(System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState, System.Runtime.ConstrainedExecution.Cer.Success)] - protected override bool ReleaseHandle() - { - return NativeMethods.FindClose(handle); - } - } - - // Refer https://msdn.microsoft.com/en-us/library/windows/desktop/gg258117(v=vs.85).aspx - [Flags] - public enum Attributes : uint - { - None = 0x00000000, - Readonly = 0x00000001, - Hidden = 0x00000002, - System = 0x00000004, - Directory = 0x00000010, - Archive = 0x00000020, - Device = 0x00000040, - Normal = 0x00000080, - Temporary = 0x00000100, - SparseFile = 0x00000200, - ReparsePoint = 0x00000400, - Compressed = 0x00000800, - Offline = 0x00001000, - NotContentIndexed = 0x00002000, - Encrypted = 0x00004000, - IntegrityStream = 0x00008000, - Virtual = 0x00010000, - NoScrubData = 0x00020000, - Write_Through = 0x80000000, - Overlapped = 0x40000000, - NoBuffering = 0x20000000, - RandomAccess = 0x10000000, - SequentialScan = 0x08000000, - DeleteOnClose = 0x04000000, - BackupSemantics = 0x02000000, - PosixSemantics = 0x01000000, - OpenReparsePoint = 0x00200000, - OpenNoRecall = 0x00100000, - FirstPipeInstance = 0x00080000 - } - - [Flags] - public enum FindFlags - { - None = 0, - CaseSensitive = 1, - LargeFetch = 2, - } - - public enum FindInfoLevel - { - Standard = 0, - Basic = 1, - } - - public enum FindSearchOps - { - NameMatch = 0, - LimitToDirectories = 1, - LimitToDevices = 2, - } -} -'@ +######################################## +# Private functions. +######################################## +function ConvertFrom-LongFormPath { + [CmdletBinding()] + param([string]$Path) + + if ($Path) { + if ($Path.StartsWith('\\?\UNC')) { + # E.g. \\?\UNC\server\share -> \\server\share + return $Path.Substring(1, '\?\UNC'.Length) + } elseif ($Path.StartsWith('\\?\')) { + # E.g. \\?\C:\directory -> C:\directory + return $Path.Substring('\\?\'.Length) + } + } + + return $Path +} +function ConvertTo-LongFormPath { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Path) + + [string]$longFormPath = Get-FullNormalizedPath -Path $Path + if ($longFormPath -and !$longFormPath.StartsWith('\\?')) { + if ($longFormPath.StartsWith('\\')) { + # E.g. \\server\share -> \\?\UNC\server\share + return "\\?\UNC$($longFormPath.Substring(1))" + } else { + # E.g. C:\directory -> \\?\C:\directory + return "\\?\$longFormPath" + } + } + + return $longFormPath +} + +# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS. +function Get-DirectoryChildItem { + [CmdletBinding()] + param( + [string]$Path, + [ValidateNotNullOrEmpty()] + [Parameter()] + [string]$Filter = "*", + [switch]$Force, + [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch, + [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic, + [switch]$Recurse) + + $stackOfDirectoryQueues = New-Object System.Collections.Stack + while ($true) { + $directoryQueue = New-Object System.Collections.Queue + $fileQueue = New-Object System.Collections.Queue + $findData = New-Object VstsTaskSdk.FS.FindData + $longFormPath = (ConvertTo-LongFormPath $Path) + $handle = $null + try { + $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx( + [System.IO.Path]::Combine($longFormPath, $Filter), + $InfoLevel, + $findData, + [VstsTaskSdk.FS.FindSearchOps]::NameMatch, + [System.IntPtr]::Zero, + $Flags) + if (!$handle.IsInvalid) { + while ($true) { + if ($findData.fileName -notin '.', '..') { + $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes + # If the item is hidden, check if $Force is specified. + if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) { + # Create the item. + $item = New-Object -TypeName psobject -Property @{ + 'Attributes' = $attributes + 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName))) + 'Name' = $findData.fileName + } + # Output directories immediately. + if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) { + $item + # Append to the directory queue if recursive and default filter. + if ($Recurse -and $Filter -eq '*') { + $directoryQueue.Enqueue($item) + } + } else { + # Hold the files until all directories have been output. + $fileQueue.Enqueue($item) + } + } + } + + if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break } + + if ($handle.IsInvalid) { + throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @( + [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() + Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path + )) + } + } + } + } finally { + if ($handle -ne $null) { $handle.Dispose() } + } + + # If recursive and non-default filter, queue child directories. + if ($Recurse -and $Filter -ne '*') { + $findData = New-Object VstsTaskSdk.FS.FindData + $handle = $null + try { + $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx( + [System.IO.Path]::Combine($longFormPath, '*'), + [VstsTaskSdk.FS.FindInfoLevel]::Basic, + $findData, + [VstsTaskSdk.FS.FindSearchOps]::NameMatch, + [System.IntPtr]::Zero, + $Flags) + if (!$handle.IsInvalid) { + while ($true) { + if ($findData.fileName -notin '.', '..') { + $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes + # If the item is hidden, check if $Force is specified. + if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) { + # Collect directories only. + if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) { + # Create the item. + $item = New-Object -TypeName psobject -Property @{ + 'Attributes' = $attributes + 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName))) + 'Name' = $findData.fileName + } + $directoryQueue.Enqueue($item) + } + } + } + + if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break } + + if ($handle.IsInvalid) { + throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @( + [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() + Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path + )) + } + } + } + } finally { + if ($handle -ne $null) { $handle.Dispose() } + } + } + + # Output the files. + $fileQueue + + # Push the directory queue onto the stack if any directories were found. + if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) } + + # Break out of the loop if no more directory queues to process. + if (!$stackOfDirectoryQueues.Count) { break } + + # Get the next path. + $directoryQueue = $stackOfDirectoryQueues.Peek() + $Path = $directoryQueue.Dequeue().FullName + + # Pop the directory queue if it's empty. + if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() } + } +} + +function Get-FullNormalizedPath { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Path) + + [string]$outPath = $Path + [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null) + [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() + if ($bufferSize -gt 0) { + $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize) + [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null) + $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() + if ($length -gt 0) { + $outPath = $absolutePath.ToString() + } else { + throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @( + $lastWin32Error + Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path + )) + } + } else { + throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @( + $lastWin32Error + Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path + )) + } + + if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) { + $outPath = $outPath.TrimEnd('\') + } + + $outPath +} + +######################################## +# Types. +######################################## +# If the type has already been loaded once, then it is not loaded again. +Write-Verbose "Adding long path native methods." +Add-Type -Debug:$false -TypeDefinition @' +namespace VstsTaskSdk.FS +{ + using System; + using System.Runtime.InteropServices; + + public static class NativeMethods + { + private const string Kernel32Dll = "kernel32.dll"; + + [DllImport(Kernel32Dll, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool FindClose(IntPtr hFindFile); + + // HANDLE WINAPI FindFirstFile( + // _In_ LPCTSTR lpFileName, + // _Out_ LPWIN32_FIND_DATA lpFindFileData + // ); + [DllImport(Kernel32Dll, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)] + public static extern SafeFindHandle FindFirstFile( + [MarshalAs(UnmanagedType.LPTStr)] + string fileName, + [In, Out] FindData findFileData + ); + + //HANDLE WINAPI FindFirstFileEx( + // _In_ LPCTSTR lpFileName, + // _In_ FINDEX_INFO_LEVELS fInfoLevelId, + // _Out_ LPVOID lpFindFileData, + // _In_ FINDEX_SEARCH_OPS fSearchOp, + // _Reserved_ LPVOID lpSearchFilter, + // _In_ DWORD dwAdditionalFlags + //); + [DllImport(Kernel32Dll, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)] + public static extern SafeFindHandle FindFirstFileEx( + [MarshalAs(UnmanagedType.LPTStr)] + string fileName, + [In] FindInfoLevel fInfoLevelId, + [In, Out] FindData lpFindFileData, + [In] FindSearchOps fSearchOp, + IntPtr lpSearchFilter, + [In] FindFlags dwAdditionalFlags + ); + + [DllImport(Kernel32Dll, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool FindNextFile(SafeFindHandle hFindFile, [In, Out] FindData lpFindFileData); + + [DllImport(Kernel32Dll, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)] + public static extern int GetFileAttributes(string lpFileName); + + [DllImport(Kernel32Dll, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)] + public static extern uint GetFullPathName( + [MarshalAs(UnmanagedType.LPTStr)] + string lpFileName, + uint nBufferLength, + [Out] + System.Text.StringBuilder lpBuffer, + System.Text.StringBuilder lpFilePart + ); + } + + //for mapping to the WIN32_FIND_DATA native structure + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public sealed class FindData + { + // NOTE: + // Although it may seem correct to Marshal the string members of this class as UnmanagedType.LPWStr, they + // must explicitly remain UnmanagedType.ByValTStr with the size constraints noted. Otherwise we end up with + // COM Interop exceptions while trying to marshal the data across the PInvoke boundaries. + public int fileAttributes; + public System.Runtime.InteropServices.ComTypes.FILETIME creationTime; + public System.Runtime.InteropServices.ComTypes.FILETIME lastAccessTime; + public System.Runtime.InteropServices.ComTypes.FILETIME lastWriteTime; + public int nFileSizeHigh; + public int nFileSizeLow; + public int dwReserved0; + public int dwReserved1; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] + public string fileName; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)] + public string alternateFileName; + } + + //A Win32 safe find handle in which a return value of -1 indicates it's invalid + public sealed class SafeFindHandle : Microsoft.Win32.SafeHandles.SafeHandleMinusOneIsInvalid + { + public SafeFindHandle() + : base(true) + { + return; + } + + [System.Runtime.ConstrainedExecution.ReliabilityContract(System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState, System.Runtime.ConstrainedExecution.Cer.Success)] + protected override bool ReleaseHandle() + { + return NativeMethods.FindClose(handle); + } + } + + // Refer https://msdn.microsoft.com/en-us/library/windows/desktop/gg258117(v=vs.85).aspx + [Flags] + public enum Attributes : uint + { + None = 0x00000000, + Readonly = 0x00000001, + Hidden = 0x00000002, + System = 0x00000004, + Directory = 0x00000010, + Archive = 0x00000020, + Device = 0x00000040, + Normal = 0x00000080, + Temporary = 0x00000100, + SparseFile = 0x00000200, + ReparsePoint = 0x00000400, + Compressed = 0x00000800, + Offline = 0x00001000, + NotContentIndexed = 0x00002000, + Encrypted = 0x00004000, + IntegrityStream = 0x00008000, + Virtual = 0x00010000, + NoScrubData = 0x00020000, + Write_Through = 0x80000000, + Overlapped = 0x40000000, + NoBuffering = 0x20000000, + RandomAccess = 0x10000000, + SequentialScan = 0x08000000, + DeleteOnClose = 0x04000000, + BackupSemantics = 0x02000000, + PosixSemantics = 0x01000000, + OpenReparsePoint = 0x00200000, + OpenNoRecall = 0x00100000, + FirstPipeInstance = 0x00080000 + } + + [Flags] + public enum FindFlags + { + None = 0, + CaseSensitive = 1, + LargeFetch = 2, + } + + public enum FindInfoLevel + { + Standard = 0, + Basic = 1, + } + + public enum FindSearchOps + { + NameMatch = 0, + LimitToDirectories = 1, + LimitToDevices = 2, + } +} +'@ diff --git a/ShowVariables/ps_modules/VstsTaskSdk/Minimatch.dll b/src/ShowVariables/ps_modules/VstsTaskSdk/Minimatch.dll similarity index 100% rename from ShowVariables/ps_modules/VstsTaskSdk/Minimatch.dll rename to src/ShowVariables/ps_modules/VstsTaskSdk/Minimatch.dll diff --git a/ShowVariables/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/src/ShowVariables/ps_modules/VstsTaskSdk/OutFunctions.ps1 similarity index 97% rename from ShowVariables/ps_modules/VstsTaskSdk/OutFunctions.ps1 rename to src/ShowVariables/ps_modules/VstsTaskSdk/OutFunctions.ps1 index 0be1fe2..79b5f45 100644 --- a/ShowVariables/ps_modules/VstsTaskSdk/OutFunctions.ps1 +++ b/src/ShowVariables/ps_modules/VstsTaskSdk/OutFunctions.ps1 @@ -1,79 +1,79 @@ -# TODO: It would be better if the Out-Default function resolved the underlying Out-Default -# command in the begin block. This would allow for supporting other modules that override -# Out-Default. -$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default") - -######################################## -# Public functions. -######################################## -function Out-Default { - [CmdletBinding(ConfirmImpact = "Medium")] - param( - [Parameter(ValueFromPipeline = $true)] - [System.Management.Automation.PSObject]$InputObject) - - begin { - #Write-Host '[Entering Begin Out-Default]' - $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline() - $__sp.Begin($pscmdlet) - #Write-Host '[Leaving Begin Out-Default]' - } - - process { - #Write-Host '[Entering Process Out-Default]' - if ($_ -is [System.Management.Automation.ErrorRecord]) { - Write-Verbose -Message 'Error record:' 4>&1 | Out-Default - Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default - Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default - Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default - Write-Verbose -Message 'Exception:' 4>&1 | Out-Default - Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default - Write-TaskError -Message $_.Exception.Message - } elseif ($_ -is [System.Management.Automation.WarningRecord]) { - Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) - } elseif ($_ -is [System.Management.Automation.VerboseRecord]) { - foreach ($private:str in (Format-DebugMessage -Object $_)) { - Write-TaskVerbose -Message $private:str - } - } elseif ($_ -is [System.Management.Automation.DebugRecord]) { - foreach ($private:str in (Format-DebugMessage -Object $_)) { - Write-TaskDebug -Message $private:str - } - } else { -# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking. - $__sp.Process($_) - } - - #Write-Host '[Leaving Process Out-Default]' - } - - end { - #Write-Host '[Entering End Out-Default]' - $__sp.End() - #Write-Host '[Leaving End Out-Default]' - } -} - -######################################## -# Private functions. -######################################## -function Format-DebugMessage { - [CmdletBinding()] - param([psobject]$Object) - - $private:str = Out-String -InputObject $Object -Width 2147483647 - $private:str = Remove-TrailingNewLine $private:str - "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0]) -} - -function Remove-TrailingNewLine { - [CmdletBinding()] - param($Str) - if ([object]::ReferenceEquals($Str, $null)) { - return $Str - } elseif ($Str.EndsWith("`r`n")) { - return $Str.Substring(0, $Str.Length - 2) - } else { - return $Str - } -} +# TODO: It would be better if the Out-Default function resolved the underlying Out-Default +# command in the begin block. This would allow for supporting other modules that override +# Out-Default. +$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default") + +######################################## +# Public functions. +######################################## +function Out-Default { + [CmdletBinding(ConfirmImpact = "Medium")] + param( + [Parameter(ValueFromPipeline = $true)] + [System.Management.Automation.PSObject]$InputObject) + + begin { + #Write-Host '[Entering Begin Out-Default]' + $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline() + $__sp.Begin($pscmdlet) + #Write-Host '[Leaving Begin Out-Default]' + } + + process { + #Write-Host '[Entering Process Out-Default]' + if ($_ -is [System.Management.Automation.ErrorRecord]) { + Write-Verbose -Message 'Error record:' 4>&1 | Out-Default + Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default + Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default + Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default + Write-Verbose -Message 'Exception:' 4>&1 | Out-Default + Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default + Write-TaskError -Message $_.Exception.Message + } elseif ($_ -is [System.Management.Automation.WarningRecord]) { + Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) + } elseif ($_ -is [System.Management.Automation.VerboseRecord]) { + foreach ($private:str in (Format-DebugMessage -Object $_)) { + Write-TaskVerbose -Message $private:str + } + } elseif ($_ -is [System.Management.Automation.DebugRecord]) { + foreach ($private:str in (Format-DebugMessage -Object $_)) { + Write-TaskDebug -Message $private:str + } + } else { +# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking. + $__sp.Process($_) + } + + #Write-Host '[Leaving Process Out-Default]' + } + + end { + #Write-Host '[Entering End Out-Default]' + $__sp.End() + #Write-Host '[Leaving End Out-Default]' + } +} + +######################################## +# Private functions. +######################################## +function Format-DebugMessage { + [CmdletBinding()] + param([psobject]$Object) + + $private:str = Out-String -InputObject $Object -Width 2147483647 + $private:str = Remove-TrailingNewLine $private:str + "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0]) +} + +function Remove-TrailingNewLine { + [CmdletBinding()] + param($Str) + if ([object]::ReferenceEquals($Str, $null)) { + return $Str + } elseif ($Str.EndsWith("`r`n")) { + return $Str.Substring(0, $Str.Length - 2) + } else { + return $Str + } +} diff --git a/VersionAssemblies/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/src/ShowVariables/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 similarity index 97% rename from VersionAssemblies/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 rename to src/ShowVariables/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 index d2b8f6e..94832ae 100644 --- a/VersionAssemblies/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 +++ b/src/ShowVariables/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 @@ -1,549 +1,549 @@ -<# -.SYNOPSIS -Gets assembly reference information. - -.DESCRIPTION -Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK. - -Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario. - -Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted. - -See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task. - -.PARAMETER LiteralPath -Assembly to walk. - -.EXAMPLE -Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll -#> -function Get-AssemblyReference { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$LiteralPath) - - $ErrorActionPreference = 'Stop' - Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK." - Write-Output '' - Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario." - $directory = [System.IO.Path]::GetDirectoryName($LiteralPath) - $hashtable = @{ } - $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() ) - while ($queue.Count) { - # Add a blank line between assemblies. - Write-Output '' - - # Pop. - $assemblyName = $queue[0] - $queue = @( $queue | Select-Object -Skip 1 ) - - # Attempt to find the assembly in the same directory. - $assembly = $null - $path = "$directory\$($assemblyName.Name).dll" - if ((Test-Path -LiteralPath $path -PathType Leaf)) { - $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path) - } else { - $path = "$directory\$($assemblyName.Name).exe" - if ((Test-Path -LiteralPath $path -PathType Leaf)) { - $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path) - } - } - - # Make sure the assembly full name matches, not just the file name. - if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) { - $assembly = $null - } - - # Print the assembly. - if ($assembly) { - Write-Output $assemblyName.FullName - } else { - if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') { - Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself." - } else { - Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***" - } - - continue - } - - # Walk the references. - $refAssemblyNames = @( $assembly.GetReferencedAssemblies() ) - for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) { - $refAssemblyName = $refAssemblyNames[$i] - - # Skip framework assemblies. - $fxPaths = @( - "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll" - "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll" - ) - $fxPath = $fxPaths | - Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } | - Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName } - if ($fxPath) { - continue - } - - # Print the reference. - Write-Output " $($refAssemblyName.FullName)" - - # Add new references to the queue. - if (!$hashtable[$refAssemblyName.FullName]) { - $queue += $refAssemblyName - $hashtable[$refAssemblyName.FullName] = $true - } - } - } -} - -<# -.SYNOPSIS -Gets a credentials object that can be used with the TFS extended client SDK. - -.DESCRIPTION -The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity). - -Refer to Get-VstsTfsService for a more simple to get a TFS service object. - -*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task. - -.PARAMETER OMDirectory -Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory. - -If not specified, defaults to the directory of the entry script for the task. - -*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task. - -.EXAMPLE -# -# Refer to Get-VstsTfsService for a more simple way to get a TFS service object. -# -$credentials = Get-VstsTfsClientCredentials -Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll" -$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection( - (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require), - $credentials) -$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer]) -$versionControlServer.GetItems('$/*').Items | Format-List -#> -function Get-TfsClientCredentials { - [CmdletBinding()] - param([string]$OMDirectory) - - Trace-EnteringInvocation -InvocationInfo $MyInvocation - $originalErrorActionPreference = $ErrorActionPreference - try { - $ErrorActionPreference = 'Stop' - - # Get the endpoint. - $endpoint = Get-Endpoint -Name SystemVssConnection -Require - - # Validate the type can be found. - $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require - - # Construct the credentials. - $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials. - $credentials.AllowInteractive = $false - $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken) - return $credentials - } catch { - $ErrorActionPreference = $originalErrorActionPreference - Write-Error $_ - } finally { - Trace-LeavingInvocation -InvocationInfo $MyInvocation - } -} - -<# -.SYNOPSIS -Gets a TFS extended client service. - -.DESCRIPTION -Gets an instance of an ITfsTeamProjectCollectionObject. - -*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task. - -.PARAMETER TypeName -Namespace-qualified type name of the service to get. - -.PARAMETER OMDirectory -Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory. - -If not specified, defaults to the directory of the entry script for the task. - -*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task. - -.PARAMETER Uri -URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri. - -.PARAMETER TfsClientCredentials -Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity). - -.EXAMPLE -$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer -$versionControlServer.GetItems('$/*').Items | Format-List -#> -function Get-TfsService { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$TypeName, - - [string]$OMDirectory, - - [string]$Uri, - - $TfsClientCredentials) - - Trace-EnteringInvocation -InvocationInfo $MyInvocation - $originalErrorActionPreference = $ErrorActionPreference - try { - $ErrorActionPreference = 'Stop' - - # Default the URI to the collection URI. - if (!$Uri) { - $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require - } - - # Default the credentials. - if (!$TfsClientCredentials) { - $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory - } - - # Validate the project collection type can be loaded. - $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require - - # Load the project collection object. - $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials) - - # Validate the requested type can be loaded. - $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require - - # Return the service object. - return $tfsTeamProjectCollection.GetService($type) - } catch { - $ErrorActionPreference = $originalErrorActionPreference - Write-Error $_ - } finally { - Trace-LeavingInvocation -InvocationInfo $MyInvocation - } -} - -<# -.SYNOPSIS -Gets a credentials object that can be used with the VSTS REST SDK. - -.DESCRIPTION -The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity). - -Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client. - -*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task. - -.PARAMETER OMDirectory -Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory. - -If not specified, defaults to the directory of the entry script for the task. - -*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task. - -.EXAMPLE -# -# Refer to Get-VstsTfsService for a more simple way to get a TFS service object. -# -# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding -# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient -# to avoid managing the binding redirect. -# -$vssCredentials = Get-VstsVssCredentials -$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require)) -Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll" -$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials) -$projectHttpClient.GetProjects().Result -#> -function Get-VssCredentials { - [CmdletBinding()] - param([string]$OMDirectory) - - Trace-EnteringInvocation -InvocationInfo $MyInvocation - $originalErrorActionPreference = $ErrorActionPreference - try { - $ErrorActionPreference = 'Stop' - - # Get the endpoint. - $endpoint = Get-Endpoint -Name SystemVssConnection -Require - - # Check if the VssOAuthAccessTokenCredential type is available. - if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) { - # Create the federated credential. - $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken) - } else { - # Validate the fallback type can be loaded. - $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require - - # Create the federated credential. - $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken) - } - - # Return the credentials. - return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials( - (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials. - $federatedCredential, - [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt) - } catch { - $ErrorActionPreference = $originalErrorActionPreference - Write-Error $_ - } finally { - Trace-LeavingInvocation -InvocationInfo $MyInvocation - } -} - -<# -.SYNOPSIS -Gets a VSS HTTP client. - -.DESCRIPTION -Gets an instance of an VSS HTTP client. - -*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task. - -.PARAMETER TypeName -Namespace-qualified type name of the HTTP client to get. - -.PARAMETER OMDirectory -Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory. - -If not specified, defaults to the directory of the entry script for the task. - -*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task. - -# .PARAMETER Uri -# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri. - -# .PARAMETER VssCredentials -# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity). - -.EXAMPLE -$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient -$projectHttpClient.GetProjects().Result -#> -function Get-VssHttpClient { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$TypeName, - - [string]$OMDirectory, - - [string]$Uri, - - $VssCredentials) - - Trace-EnteringInvocation -InvocationInfo $MyInvocation - $originalErrorActionPreference = $ErrorActionPreference - try { - $ErrorActionPreference = 'Stop' - - # Default the URI to the collection URI. - if (!$Uri) { - $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require - } - - # Cast the URI. - [uri]$Uri = New-Object System.Uri($Uri) - - # Default the credentials. - if (!$VssCredentials) { - $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory - } - - # Validate the type can be loaded. - $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require - - # Try to construct the HTTP client. - Write-Verbose "Constructing HTTP client." - try { - return New-Object $TypeName($Uri, $VssCredentials) - } catch { - # Rethrow if the exception is not due to Newtonsoft.Json DLL not found. - if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or - $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') { - - throw - } - - # Default the OMDirectory to the directory of the entry script for the task. - if (!$OMDirectory) { - $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..") - Write-Verbose "Defaulted OM directory to: '$OMDirectory'" - } - - # Test if the Newtonsoft.Json DLL exists in the OM directory. - $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll") - Write-Verbose "Testing file path: '$newtonsoftDll'" - if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) { - Write-Verbose 'Not found. Rethrowing exception.' - throw - } - - # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a - # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference - # the 8.0.0.0 Newtonsoft.Json DLL. - Write-Verbose "Adding assembly resolver." - $onAssemblyResolve = [System.ResolveEventHandler]{ - param($sender, $e) - - if ($e.Name -like 'Newtonsoft.Json, *') { - Write-Verbose "Resolving '$($e.Name)'" - return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll) - } - - Write-Verbose "Unable to resolve assembly name '$($e.Name)'" - return $null - } - [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve) - try { - # Try again to construct the HTTP client. - Write-Verbose "Trying again to construct the HTTP client." - return New-Object $TypeName($Uri, $VssCredentials) - } finally { - # Unregister the assembly resolver. - Write-Verbose "Removing assemlby resolver." - [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve) - } - } - } catch { - $ErrorActionPreference = $originalErrorActionPreference - Write-Error $_ - } finally { - Trace-LeavingInvocation -InvocationInfo $MyInvocation - } -} - -######################################## -# Private functions. -######################################## -function Get-OMType { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$TypeName, - - [ValidateSet('ExtendedClient', 'WebApi')] - [Parameter(Mandatory = $true)] - [string]$OMKind, - - [string]$OMDirectory, - - [switch]$Require) - - Trace-EnteringInvocation -InvocationInfo $MyInvocation - try { - # Default the OMDirectory to the directory of the entry script for the task. - if (!$OMDirectory) { - $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..") - Write-Verbose "Defaulted OM directory to: '$OMDirectory'" - } - - # Try to load the type. - $errorRecord = $null - Write-Verbose "Testing whether type can be loaded: '$TypeName'" - $ErrorActionPreference = 'Ignore' - try { - # Failure when attempting to cast a string to a type, transfers control to the - # catch handler even when the error action preference is ignore. The error action - # is set to Ignore so the $Error variable is not polluted. - $type = [type]$TypeName - - # Success. - Write-Verbose "The type was loaded successfully." - return $type - } catch { - # Store the error record. - $errorRecord = $_ - } - - $ErrorActionPreference = 'Stop' - Write-Verbose "The type was not loaded." - - # Build a list of candidate DLL file paths from the namespace. - $dllPaths = @( ) - $namespace = $TypeName - while ($namespace.LastIndexOf('.') -gt 0) { - # Trim the next segment from the namespace. - $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.')) - - # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API). - if ($OMKind -eq 'ExtendedClient') { - if ($namespace -like 'Microsoft.TeamFoundation.*') { - $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll") - } - } else { - if ($namespace -like 'Microsoft.TeamFoundation.*' -or - $namespace -like 'Microsoft.VisualStudio.Services' -or - $namespace -like 'Microsoft.VisualStudio.Services.*') { - - $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll") - $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll") - } - } - } - - foreach ($dllPath in $dllPaths) { - # Check whether the DLL exists. - Write-Verbose "Testing leaf path: '$dllPath'" - if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) { - Write-Verbose "Not found." - continue - } - - # Load the DLL. - Write-Verbose "Loading assembly: $dllPath" - try { - Add-Type -LiteralPath $dllPath - } catch { - # Write the information to the verbose stream and proceed to attempt to load the requested type. - # - # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the - # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even - # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb) - # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API - # HTTP clients. - Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)" - if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) { - for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) { - $loaderException = $_.Exception.LoaderExceptions[$i] - Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)" - } - } - } - - # Try to load the type. - Write-Verbose "Testing whether type can be loaded: '$TypeName'" - $ErrorActionPreference = 'Ignore' - try { - # Failure when attempting to cast a string to a type, transfers control to the - # catch handler even when the error action preference is ignore. The error action - # is set to Ignore so the $Error variable is not polluted. - $type = [type]$TypeName - - # Success. - Write-Verbose "The type was loaded successfully." - return $type - } catch { - $errorRecord = $_ - } - - $ErrorActionPreference = 'Stop' - Write-Verbose "The type was not loaded." - } - - # Check whether to propagate the error. - if ($Require) { - Write-Error $errorRecord - } - } finally { - Trace-LeavingInvocation -InvocationInfo $MyInvocation - } -} +<# +.SYNOPSIS +Gets assembly reference information. + +.DESCRIPTION +Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK. + +Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario. + +Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted. + +See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task. + +.PARAMETER LiteralPath +Assembly to walk. + +.EXAMPLE +Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll +#> +function Get-AssemblyReference { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$LiteralPath) + + $ErrorActionPreference = 'Stop' + Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK." + Write-Output '' + Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario." + $directory = [System.IO.Path]::GetDirectoryName($LiteralPath) + $hashtable = @{ } + $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() ) + while ($queue.Count) { + # Add a blank line between assemblies. + Write-Output '' + + # Pop. + $assemblyName = $queue[0] + $queue = @( $queue | Select-Object -Skip 1 ) + + # Attempt to find the assembly in the same directory. + $assembly = $null + $path = "$directory\$($assemblyName.Name).dll" + if ((Test-Path -LiteralPath $path -PathType Leaf)) { + $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path) + } else { + $path = "$directory\$($assemblyName.Name).exe" + if ((Test-Path -LiteralPath $path -PathType Leaf)) { + $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path) + } + } + + # Make sure the assembly full name matches, not just the file name. + if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) { + $assembly = $null + } + + # Print the assembly. + if ($assembly) { + Write-Output $assemblyName.FullName + } else { + if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') { + Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself." + } else { + Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***" + } + + continue + } + + # Walk the references. + $refAssemblyNames = @( $assembly.GetReferencedAssemblies() ) + for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) { + $refAssemblyName = $refAssemblyNames[$i] + + # Skip framework assemblies. + $fxPaths = @( + "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll" + "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll" + ) + $fxPath = $fxPaths | + Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } | + Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName } + if ($fxPath) { + continue + } + + # Print the reference. + Write-Output " $($refAssemblyName.FullName)" + + # Add new references to the queue. + if (!$hashtable[$refAssemblyName.FullName]) { + $queue += $refAssemblyName + $hashtable[$refAssemblyName.FullName] = $true + } + } + } +} + +<# +.SYNOPSIS +Gets a credentials object that can be used with the TFS extended client SDK. + +.DESCRIPTION +The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity). + +Refer to Get-VstsTfsService for a more simple to get a TFS service object. + +*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task. + +.PARAMETER OMDirectory +Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory. + +If not specified, defaults to the directory of the entry script for the task. + +*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task. + +.EXAMPLE +# +# Refer to Get-VstsTfsService for a more simple way to get a TFS service object. +# +$credentials = Get-VstsTfsClientCredentials +Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll" +$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection( + (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require), + $credentials) +$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer]) +$versionControlServer.GetItems('$/*').Items | Format-List +#> +function Get-TfsClientCredentials { + [CmdletBinding()] + param([string]$OMDirectory) + + Trace-EnteringInvocation -InvocationInfo $MyInvocation + $originalErrorActionPreference = $ErrorActionPreference + try { + $ErrorActionPreference = 'Stop' + + # Get the endpoint. + $endpoint = Get-Endpoint -Name SystemVssConnection -Require + + # Validate the type can be found. + $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require + + # Construct the credentials. + $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials. + $credentials.AllowInteractive = $false + $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken) + return $credentials + } catch { + $ErrorActionPreference = $originalErrorActionPreference + Write-Error $_ + } finally { + Trace-LeavingInvocation -InvocationInfo $MyInvocation + } +} + +<# +.SYNOPSIS +Gets a TFS extended client service. + +.DESCRIPTION +Gets an instance of an ITfsTeamProjectCollectionObject. + +*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task. + +.PARAMETER TypeName +Namespace-qualified type name of the service to get. + +.PARAMETER OMDirectory +Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory. + +If not specified, defaults to the directory of the entry script for the task. + +*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task. + +.PARAMETER Uri +URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri. + +.PARAMETER TfsClientCredentials +Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity). + +.EXAMPLE +$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer +$versionControlServer.GetItems('$/*').Items | Format-List +#> +function Get-TfsService { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$TypeName, + + [string]$OMDirectory, + + [string]$Uri, + + $TfsClientCredentials) + + Trace-EnteringInvocation -InvocationInfo $MyInvocation + $originalErrorActionPreference = $ErrorActionPreference + try { + $ErrorActionPreference = 'Stop' + + # Default the URI to the collection URI. + if (!$Uri) { + $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require + } + + # Default the credentials. + if (!$TfsClientCredentials) { + $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory + } + + # Validate the project collection type can be loaded. + $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require + + # Load the project collection object. + $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials) + + # Validate the requested type can be loaded. + $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require + + # Return the service object. + return $tfsTeamProjectCollection.GetService($type) + } catch { + $ErrorActionPreference = $originalErrorActionPreference + Write-Error $_ + } finally { + Trace-LeavingInvocation -InvocationInfo $MyInvocation + } +} + +<# +.SYNOPSIS +Gets a credentials object that can be used with the VSTS REST SDK. + +.DESCRIPTION +The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity). + +Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client. + +*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task. + +.PARAMETER OMDirectory +Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory. + +If not specified, defaults to the directory of the entry script for the task. + +*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task. + +.EXAMPLE +# +# Refer to Get-VstsTfsService for a more simple way to get a TFS service object. +# +# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding +# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient +# to avoid managing the binding redirect. +# +$vssCredentials = Get-VstsVssCredentials +$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require)) +Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll" +$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials) +$projectHttpClient.GetProjects().Result +#> +function Get-VssCredentials { + [CmdletBinding()] + param([string]$OMDirectory) + + Trace-EnteringInvocation -InvocationInfo $MyInvocation + $originalErrorActionPreference = $ErrorActionPreference + try { + $ErrorActionPreference = 'Stop' + + # Get the endpoint. + $endpoint = Get-Endpoint -Name SystemVssConnection -Require + + # Check if the VssOAuthAccessTokenCredential type is available. + if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) { + # Create the federated credential. + $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken) + } else { + # Validate the fallback type can be loaded. + $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require + + # Create the federated credential. + $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken) + } + + # Return the credentials. + return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials( + (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials. + $federatedCredential, + [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt) + } catch { + $ErrorActionPreference = $originalErrorActionPreference + Write-Error $_ + } finally { + Trace-LeavingInvocation -InvocationInfo $MyInvocation + } +} + +<# +.SYNOPSIS +Gets a VSS HTTP client. + +.DESCRIPTION +Gets an instance of an VSS HTTP client. + +*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task. + +.PARAMETER TypeName +Namespace-qualified type name of the HTTP client to get. + +.PARAMETER OMDirectory +Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory. + +If not specified, defaults to the directory of the entry script for the task. + +*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task. + +# .PARAMETER Uri +# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri. + +# .PARAMETER VssCredentials +# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity). + +.EXAMPLE +$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient +$projectHttpClient.GetProjects().Result +#> +function Get-VssHttpClient { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$TypeName, + + [string]$OMDirectory, + + [string]$Uri, + + $VssCredentials) + + Trace-EnteringInvocation -InvocationInfo $MyInvocation + $originalErrorActionPreference = $ErrorActionPreference + try { + $ErrorActionPreference = 'Stop' + + # Default the URI to the collection URI. + if (!$Uri) { + $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require + } + + # Cast the URI. + [uri]$Uri = New-Object System.Uri($Uri) + + # Default the credentials. + if (!$VssCredentials) { + $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory + } + + # Validate the type can be loaded. + $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require + + # Try to construct the HTTP client. + Write-Verbose "Constructing HTTP client." + try { + return New-Object $TypeName($Uri, $VssCredentials) + } catch { + # Rethrow if the exception is not due to Newtonsoft.Json DLL not found. + if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or + $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') { + + throw + } + + # Default the OMDirectory to the directory of the entry script for the task. + if (!$OMDirectory) { + $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..") + Write-Verbose "Defaulted OM directory to: '$OMDirectory'" + } + + # Test if the Newtonsoft.Json DLL exists in the OM directory. + $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll") + Write-Verbose "Testing file path: '$newtonsoftDll'" + if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) { + Write-Verbose 'Not found. Rethrowing exception.' + throw + } + + # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a + # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference + # the 8.0.0.0 Newtonsoft.Json DLL. + Write-Verbose "Adding assembly resolver." + $onAssemblyResolve = [System.ResolveEventHandler]{ + param($sender, $e) + + if ($e.Name -like 'Newtonsoft.Json, *') { + Write-Verbose "Resolving '$($e.Name)'" + return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll) + } + + Write-Verbose "Unable to resolve assembly name '$($e.Name)'" + return $null + } + [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve) + try { + # Try again to construct the HTTP client. + Write-Verbose "Trying again to construct the HTTP client." + return New-Object $TypeName($Uri, $VssCredentials) + } finally { + # Unregister the assembly resolver. + Write-Verbose "Removing assemlby resolver." + [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve) + } + } + } catch { + $ErrorActionPreference = $originalErrorActionPreference + Write-Error $_ + } finally { + Trace-LeavingInvocation -InvocationInfo $MyInvocation + } +} + +######################################## +# Private functions. +######################################## +function Get-OMType { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$TypeName, + + [ValidateSet('ExtendedClient', 'WebApi')] + [Parameter(Mandatory = $true)] + [string]$OMKind, + + [string]$OMDirectory, + + [switch]$Require) + + Trace-EnteringInvocation -InvocationInfo $MyInvocation + try { + # Default the OMDirectory to the directory of the entry script for the task. + if (!$OMDirectory) { + $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..") + Write-Verbose "Defaulted OM directory to: '$OMDirectory'" + } + + # Try to load the type. + $errorRecord = $null + Write-Verbose "Testing whether type can be loaded: '$TypeName'" + $ErrorActionPreference = 'Ignore' + try { + # Failure when attempting to cast a string to a type, transfers control to the + # catch handler even when the error action preference is ignore. The error action + # is set to Ignore so the $Error variable is not polluted. + $type = [type]$TypeName + + # Success. + Write-Verbose "The type was loaded successfully." + return $type + } catch { + # Store the error record. + $errorRecord = $_ + } + + $ErrorActionPreference = 'Stop' + Write-Verbose "The type was not loaded." + + # Build a list of candidate DLL file paths from the namespace. + $dllPaths = @( ) + $namespace = $TypeName + while ($namespace.LastIndexOf('.') -gt 0) { + # Trim the next segment from the namespace. + $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.')) + + # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API). + if ($OMKind -eq 'ExtendedClient') { + if ($namespace -like 'Microsoft.TeamFoundation.*') { + $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll") + } + } else { + if ($namespace -like 'Microsoft.TeamFoundation.*' -or + $namespace -like 'Microsoft.VisualStudio.Services' -or + $namespace -like 'Microsoft.VisualStudio.Services.*') { + + $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll") + $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll") + } + } + } + + foreach ($dllPath in $dllPaths) { + # Check whether the DLL exists. + Write-Verbose "Testing leaf path: '$dllPath'" + if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) { + Write-Verbose "Not found." + continue + } + + # Load the DLL. + Write-Verbose "Loading assembly: $dllPath" + try { + Add-Type -LiteralPath $dllPath + } catch { + # Write the information to the verbose stream and proceed to attempt to load the requested type. + # + # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the + # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even + # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb) + # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API + # HTTP clients. + Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)" + if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) { + for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) { + $loaderException = $_.Exception.LoaderExceptions[$i] + Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)" + } + } + } + + # Try to load the type. + Write-Verbose "Testing whether type can be loaded: '$TypeName'" + $ErrorActionPreference = 'Ignore' + try { + # Failure when attempting to cast a string to a type, transfers control to the + # catch handler even when the error action preference is ignore. The error action + # is set to Ignore so the $Error variable is not polluted. + $type = [type]$TypeName + + # Success. + Write-Verbose "The type was loaded successfully." + return $type + } catch { + $errorRecord = $_ + } + + $ErrorActionPreference = 'Stop' + Write-Verbose "The type was not loaded." + } + + # Check whether to propagate the error. + if ($Require) { + Write-Error $errorRecord + } + } finally { + Trace-LeavingInvocation -InvocationInfo $MyInvocation + } +} diff --git a/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson similarity index 98% rename from ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson rename to src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson index b412aee..ec97e9b 100644 --- a/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson +++ b/src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson @@ -1,17 +1,17 @@ -{ - "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".", - "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen", - "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL", - "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"", - "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".", - "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe", - "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"", - "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".", - "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"", - "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".", - "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.", - "loc.messages.PSLIB_Required0": "Erforderlich: {0}", - "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.", - "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".", - "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable" +{ + "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".", + "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen", + "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL", + "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"", + "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".", + "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe", + "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"", + "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".", + "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"", + "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".", + "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.", + "loc.messages.PSLIB_Required0": "Erforderlich: {0}", + "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.", + "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".", + "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable" } \ No newline at end of file diff --git a/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson similarity index 100% rename from ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson rename to src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson diff --git a/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson similarity index 98% rename from VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson rename to src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson index b4dadff..d09d96c 100644 --- a/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson +++ b/src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson @@ -1,17 +1,17 @@ -{ - "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'", - "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'", - "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'", - "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'", - "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'", - "loc.messages.PSLIB_Input0": "Entrada '{0}'", - "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'", - "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'", - "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'", - "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'", - "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.", - "loc.messages.PSLIB_Required0": "Se requiere: {0}", - "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.", - "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'", - "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'" +{ + "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'", + "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'", + "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'", + "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'", + "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'", + "loc.messages.PSLIB_Input0": "Entrada '{0}'", + "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'", + "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'", + "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'", + "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'", + "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.", + "loc.messages.PSLIB_Required0": "Se requiere: {0}", + "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.", + "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'", + "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'" } \ No newline at end of file diff --git a/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson similarity index 98% rename from VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson rename to src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson index 9d888c2..6606ddd 100644 --- a/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson +++ b/src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson @@ -1,17 +1,17 @@ -{ - "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'", - "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'", - "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'", - "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'", - "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.", - "loc.messages.PSLIB_Input0": "Entrée '{0}'", - "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'", - "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'", - "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'", - "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'", - "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.", - "loc.messages.PSLIB_Required0": "Obligatoire : {0}", - "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.", - "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'", - "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'" +{ + "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'", + "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'", + "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'", + "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'", + "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.", + "loc.messages.PSLIB_Input0": "Entrée '{0}'", + "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'", + "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'", + "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'", + "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'", + "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.", + "loc.messages.PSLIB_Required0": "Obligatoire : {0}", + "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.", + "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'", + "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'" } \ No newline at end of file diff --git a/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson similarity index 98% rename from VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson rename to src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson index 50079ee..0b54d99 100644 --- a/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson +++ b/src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson @@ -1,17 +1,17 @@ -{ - "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'", - "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'", - "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'", - "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita", - "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'", - "loc.messages.PSLIB_Input0": "Input di '{0}'", - "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'", - "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'", - "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'", - "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'", - "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.", - "loc.messages.PSLIB_Required0": "Obbligatorio: {0}", - "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.", - "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'", - "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'" +{ + "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'", + "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'", + "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'", + "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita", + "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'", + "loc.messages.PSLIB_Input0": "Input di '{0}'", + "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'", + "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'", + "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'", + "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'", + "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.", + "loc.messages.PSLIB_Required0": "Obbligatorio: {0}", + "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.", + "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'", + "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'" } \ No newline at end of file diff --git a/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson similarity index 98% rename from ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson rename to src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson index 5912541..b0e2bdf 100644 --- a/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson +++ b/src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson @@ -1,17 +1,17 @@ -{ - "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'", - "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報", - "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL", - "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした", - "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'", - "loc.messages.PSLIB_Input0": "'{0}' 入力", - "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'", - "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'", - "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした", - "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'", - "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。", - "loc.messages.PSLIB_Required0": "必要: {0}", - "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。", - "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'", - "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数" +{ + "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'", + "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報", + "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL", + "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした", + "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'", + "loc.messages.PSLIB_Input0": "'{0}' 入力", + "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'", + "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'", + "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした", + "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'", + "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。", + "loc.messages.PSLIB_Required0": "必要: {0}", + "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。", + "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'", + "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数" } \ No newline at end of file diff --git a/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson similarity index 98% rename from VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson rename to src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson index e2a1146..60df35b 100644 --- a/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson +++ b/src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson @@ -1,17 +1,17 @@ -{ - "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'", - "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명", - "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL", - "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'", - "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.", - "loc.messages.PSLIB_Input0": "'{0}' 입력", - "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'", - "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'", - "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'", - "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'", - "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.", - "loc.messages.PSLIB_Required0": "필수: {0}", - "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.", - "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'", - "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수" +{ + "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'", + "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명", + "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL", + "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'", + "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.", + "loc.messages.PSLIB_Input0": "'{0}' 입력", + "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'", + "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'", + "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'", + "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'", + "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.", + "loc.messages.PSLIB_Required0": "필수: {0}", + "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.", + "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'", + "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수" } \ No newline at end of file diff --git a/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson similarity index 99% rename from ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson rename to src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson index de01733..2d42208 100644 --- a/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson +++ b/src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson @@ -1,17 +1,17 @@ -{ - "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".", - "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"", - "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"", - "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".", - "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".", - "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".", - "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".", - "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".", - "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".", - "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".", - "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".", - "loc.messages.PSLIB_Required0": "Требуется: {0}", - "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.", - "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".", - "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\"" +{ + "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".", + "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"", + "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"", + "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".", + "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".", + "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".", + "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".", + "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".", + "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".", + "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".", + "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".", + "loc.messages.PSLIB_Required0": "Требуется: {0}", + "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.", + "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".", + "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\"" } \ No newline at end of file diff --git a/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson similarity index 98% rename from VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson rename to src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson index 918a76d..80adce2 100644 --- a/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson +++ b/src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson @@ -1,17 +1,17 @@ -{ - "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”", - "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据", - "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL", - "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”", - "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。", - "loc.messages.PSLIB_Input0": "“{0}”输入", - "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”", - "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”", - "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的", - "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”", - "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。", - "loc.messages.PSLIB_Required0": "必需: {0}", - "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。", - "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”", - "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量" +{ + "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”", + "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据", + "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL", + "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”", + "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。", + "loc.messages.PSLIB_Input0": "“{0}”输入", + "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”", + "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”", + "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的", + "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”", + "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。", + "loc.messages.PSLIB_Required0": "必需: {0}", + "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。", + "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”", + "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量" } \ No newline at end of file diff --git a/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson similarity index 98% rename from VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson rename to src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson index 03c3b4f..d6a041c 100644 --- a/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson +++ b/src/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson @@ -1,17 +1,17 @@ -{ - "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'", - "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證", - "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL", - "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'", - "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'", - "loc.messages.PSLIB_Input0": "'{0}' 輸入", - "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'", - "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'", - "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度", - "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'", - "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。", - "loc.messages.PSLIB_Required0": "必要項: {0}", - "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。", - "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'", - "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數" +{ + "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'", + "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證", + "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL", + "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'", + "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'", + "loc.messages.PSLIB_Input0": "'{0}' 輸入", + "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'", + "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'", + "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度", + "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'", + "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。", + "loc.messages.PSLIB_Required0": "必要項: {0}", + "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。", + "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'", + "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數" } \ No newline at end of file diff --git a/VersionAssemblies/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/src/ShowVariables/ps_modules/VstsTaskSdk/ToolFunctions.ps1 similarity index 97% rename from VersionAssemblies/ps_modules/VstsTaskSdk/ToolFunctions.ps1 rename to src/ShowVariables/ps_modules/VstsTaskSdk/ToolFunctions.ps1 index 3004901..0d0f444 100644 --- a/VersionAssemblies/ps_modules/VstsTaskSdk/ToolFunctions.ps1 +++ b/src/ShowVariables/ps_modules/VstsTaskSdk/ToolFunctions.ps1 @@ -1,99 +1,99 @@ -<# -.SYNOPSIS -Asserts that a path exists. Throws if the path does not exist. - -.PARAMETER PassThru -True to return the path. -#> -function Assert-Path { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$LiteralPath, - [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any, - [switch]$PassThru) - - if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) { - Write-Verbose "Asserting path exists: '$LiteralPath'" - } else { - Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'" - } - - if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) { - if ($PassThru) { - return $LiteralPath - } - - return - } - - $resourceKey = switch ($PathType) { - ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break } - ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break } - default { "PSLIB_PathNotFound0" } - } - - throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath) -} - -<# -.SYNOPSIS -Executes an external program. - -.DESCRIPTION -Executes an external program and waits for the process to exit. - -After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE. - -.PARAMETER Encoding -This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed. - -.PARAMETER RequireExitCodeZero -Indicates whether to write an error to the error pipeline if the exit code is not zero. -#> -function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS? - [CmdletBinding()] - param( - [ValidatePattern('^[^\r\n]*$')] - [Parameter(Mandatory = $true)] - [string]$FileName, - [ValidatePattern('^[^\r\n]*$')] - [Parameter()] - [string]$Arguments, - [string]$WorkingDirectory, - [System.Text.Encoding]$Encoding, - [switch]$RequireExitCodeZero) - - Trace-EnteringInvocation $MyInvocation - $isPushed = $false - $originalEncoding = $null - try { - if ($Encoding) { - $originalEncoding = [System.Console]::OutputEncoding - [System.Console]::OutputEncoding = $Encoding - } - - if ($WorkingDirectory) { - Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop - $isPushed = $true - } - - $FileName = $FileName.Replace('"', '').Replace("'", "''") - Write-Host "##[command]""$FileName"" $Arguments" - Invoke-Expression "& '$FileName' --% $Arguments" - Write-Verbose "Exit code: $LASTEXITCODE" - if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) { - Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE) - } - } finally { - if ($originalEncoding) { - [System.Console]::OutputEncoding = $originalEncoding - } - - if ($isPushed) { - Pop-Location - } - - Trace-LeavingInvocation $MyInvocation - } -} +<# +.SYNOPSIS +Asserts that a path exists. Throws if the path does not exist. + +.PARAMETER PassThru +True to return the path. +#> +function Assert-Path { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$LiteralPath, + [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any, + [switch]$PassThru) + + if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) { + Write-Verbose "Asserting path exists: '$LiteralPath'" + } else { + Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'" + } + + if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) { + if ($PassThru) { + return $LiteralPath + } + + return + } + + $resourceKey = switch ($PathType) { + ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break } + ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break } + default { "PSLIB_PathNotFound0" } + } + + throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath) +} + +<# +.SYNOPSIS +Executes an external program. + +.DESCRIPTION +Executes an external program and waits for the process to exit. + +After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE. + +.PARAMETER Encoding +This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed. + +.PARAMETER RequireExitCodeZero +Indicates whether to write an error to the error pipeline if the exit code is not zero. +#> +function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS? + [CmdletBinding()] + param( + [ValidatePattern('^[^\r\n]*$')] + [Parameter(Mandatory = $true)] + [string]$FileName, + [ValidatePattern('^[^\r\n]*$')] + [Parameter()] + [string]$Arguments, + [string]$WorkingDirectory, + [System.Text.Encoding]$Encoding, + [switch]$RequireExitCodeZero) + + Trace-EnteringInvocation $MyInvocation + $isPushed = $false + $originalEncoding = $null + try { + if ($Encoding) { + $originalEncoding = [System.Console]::OutputEncoding + [System.Console]::OutputEncoding = $Encoding + } + + if ($WorkingDirectory) { + Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop + $isPushed = $true + } + + $FileName = $FileName.Replace('"', '').Replace("'", "''") + Write-Host "##[command]""$FileName"" $Arguments" + Invoke-Expression "& '$FileName' --% $Arguments" + Write-Verbose "Exit code: $LASTEXITCODE" + if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) { + Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE) + } + } finally { + if ($originalEncoding) { + [System.Console]::OutputEncoding = $originalEncoding + } + + if ($isPushed) { + Pop-Location + } + + Trace-LeavingInvocation $MyInvocation + } +} diff --git a/ShowVariables/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/src/ShowVariables/ps_modules/VstsTaskSdk/TraceFunctions.ps1 similarity index 96% rename from ShowVariables/ps_modules/VstsTaskSdk/TraceFunctions.ps1 rename to src/ShowVariables/ps_modules/VstsTaskSdk/TraceFunctions.ps1 index b8e084b..cdbd779 100644 --- a/ShowVariables/ps_modules/VstsTaskSdk/TraceFunctions.ps1 +++ b/src/ShowVariables/ps_modules/VstsTaskSdk/TraceFunctions.ps1 @@ -1,139 +1,139 @@ -<# -.SYNOPSIS -Writes verbose information about the invocation being entered. - -.DESCRIPTION -Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced. - -.PARAMETER Parameter -Wildcard pattern to control which bound parameters are traced. -#> -function Trace-EnteringInvocation { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [System.Management.Automation.InvocationInfo]$InvocationInfo, - [string[]]$Parameter = '*') - - Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)." - $OFS = ", " - if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) { - if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') { - # Trace all parameters. - foreach ($key in $InvocationInfo.BoundParameters.Keys) { - Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'" - } - } else { - # Trace matching parameters. - foreach ($key in $InvocationInfo.BoundParameters.Keys) { - foreach ($p in $Parameter) { - if ($key -like $p) { - Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'" - break - } - } - } - } - } - - # Trace all unbound arguments. - if (@($InvocationInfo.UnboundArguments).Count) { - for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) { - Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'" - } - } -} - -<# -.SYNOPSIS -Writes verbose information about the invocation being left. - -.DESCRIPTION -Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation. -#> -function Trace-LeavingInvocation { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [System.Management.Automation.InvocationInfo]$InvocationInfo) - - Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)." -} - -<# -.SYNOPSIS -Writes verbose information about paths. - -.DESCRIPTION -Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path. - -.PARAMETER PassThru -Indicates whether to return the sorted paths. -#> -function Trace-Path { - [CmdletBinding()] - param( - [string[]]$Path, - [switch]$PassThru) - - if ($Path.Count -eq 0) { - Write-Verbose "No paths." - if ($PassThru) { - $Path - } - } elseif ($Path.Count -eq 1) { - Write-Verbose "Path: $($Path[0])" - if ($PassThru) { - $Path - } - } else { - # Find the greatest common root. - $sorted = $Path | Sort-Object - $firstPath = $sorted[0].ToCharArray() - $lastPath = $sorted[-1].ToCharArray() - $commonEndIndex = 0 - $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length } - for ($i = 0 ; $i -lt $j ; $i++) { - if ($firstPath[$i] -eq $lastPath[$i]) { - if ($firstPath[$i] -eq '\') { - $commonEndIndex = $i - } - } else { - break - } - } - - if ($commonEndIndex -eq 0) { - # No common root. - Write-Verbose "Paths:" - foreach ($p in $sorted) { - Write-Verbose " $p" - } - } else { - Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))" - foreach ($p in $sorted) { - Write-Verbose " $($p.Substring($commonEndIndex + 1))" - } - } - - if ($PassThru) { - $sorted - } - } -} - -######################################## -# Private functions. -######################################## -function Get-InvocationDescription { - [CmdletBinding()] - param([System.Management.Automation.InvocationInfo]$InvocationInfo) - - if ($InvocationInfo.MyCommand.Path) { - $InvocationInfo.MyCommand.Path - } elseif ($InvocationInfo.MyCommand.Name) { - $InvocationInfo.MyCommand.Name - } else { - $InvocationInfo.MyCommand.CommandType - } -} +<# +.SYNOPSIS +Writes verbose information about the invocation being entered. + +.DESCRIPTION +Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced. + +.PARAMETER Parameter +Wildcard pattern to control which bound parameters are traced. +#> +function Trace-EnteringInvocation { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [System.Management.Automation.InvocationInfo]$InvocationInfo, + [string[]]$Parameter = '*') + + Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)." + $OFS = ", " + if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) { + if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') { + # Trace all parameters. + foreach ($key in $InvocationInfo.BoundParameters.Keys) { + Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'" + } + } else { + # Trace matching parameters. + foreach ($key in $InvocationInfo.BoundParameters.Keys) { + foreach ($p in $Parameter) { + if ($key -like $p) { + Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'" + break + } + } + } + } + } + + # Trace all unbound arguments. + if (@($InvocationInfo.UnboundArguments).Count) { + for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) { + Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'" + } + } +} + +<# +.SYNOPSIS +Writes verbose information about the invocation being left. + +.DESCRIPTION +Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation. +#> +function Trace-LeavingInvocation { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [System.Management.Automation.InvocationInfo]$InvocationInfo) + + Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)." +} + +<# +.SYNOPSIS +Writes verbose information about paths. + +.DESCRIPTION +Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path. + +.PARAMETER PassThru +Indicates whether to return the sorted paths. +#> +function Trace-Path { + [CmdletBinding()] + param( + [string[]]$Path, + [switch]$PassThru) + + if ($Path.Count -eq 0) { + Write-Verbose "No paths." + if ($PassThru) { + $Path + } + } elseif ($Path.Count -eq 1) { + Write-Verbose "Path: $($Path[0])" + if ($PassThru) { + $Path + } + } else { + # Find the greatest common root. + $sorted = $Path | Sort-Object + $firstPath = $sorted[0].ToCharArray() + $lastPath = $sorted[-1].ToCharArray() + $commonEndIndex = 0 + $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length } + for ($i = 0 ; $i -lt $j ; $i++) { + if ($firstPath[$i] -eq $lastPath[$i]) { + if ($firstPath[$i] -eq '\') { + $commonEndIndex = $i + } + } else { + break + } + } + + if ($commonEndIndex -eq 0) { + # No common root. + Write-Verbose "Paths:" + foreach ($p in $sorted) { + Write-Verbose " $p" + } + } else { + Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))" + foreach ($p in $sorted) { + Write-Verbose " $($p.Substring($commonEndIndex + 1))" + } + } + + if ($PassThru) { + $sorted + } + } +} + +######################################## +# Private functions. +######################################## +function Get-InvocationDescription { + [CmdletBinding()] + param([System.Management.Automation.InvocationInfo]$InvocationInfo) + + if ($InvocationInfo.MyCommand.Path) { + $InvocationInfo.MyCommand.Path + } elseif ($InvocationInfo.MyCommand.Name) { + $InvocationInfo.MyCommand.Name + } else { + $InvocationInfo.MyCommand.CommandType + } +} diff --git a/ShowVariables/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/src/ShowVariables/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 similarity index 100% rename from ShowVariables/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 rename to src/ShowVariables/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 diff --git a/ShowVariables/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/src/ShowVariables/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 similarity index 97% rename from ShowVariables/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 rename to src/ShowVariables/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 index 2b68050..9ae96cd 100644 --- a/ShowVariables/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 +++ b/src/ShowVariables/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 @@ -1,161 +1,161 @@ -[CmdletBinding()] -param( - [ValidateNotNull()] - [Parameter()] - [hashtable]$ModuleParameters = @{ }) - -if ($host.Name -ne 'ConsoleHost') { - Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts." -} - -# Private module variables. -[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true' -Write-Verbose "NonInteractive: $script:nonInteractive" - -# Import/export functions. -. "$PSScriptRoot\FindFunctions.ps1" -. "$PSScriptRoot\InputFunctions.ps1" -. "$PSScriptRoot\LegacyFindFunctions.ps1" -. "$PSScriptRoot\LocalizationFunctions.ps1" -. "$PSScriptRoot\LoggingCommandFunctions.ps1" -. "$PSScriptRoot\LongPathFunctions.ps1" -. "$PSScriptRoot\ServerOMFunctions.ps1" -. "$PSScriptRoot\ToolFunctions.ps1" -. "$PSScriptRoot\TraceFunctions.ps1" -. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded. -Export-ModuleMember -Function @( - # Find functions. - 'Find-Match' - 'New-FindOptions' - 'New-MatchOptions' - 'Select-Match' - # Input functions. - 'Get-Endpoint' - 'Get-Input' - 'Get-TaskVariable' - 'Get-TaskVariableInfo' - 'Set-TaskVariable' - # Legacy find functions. - 'Find-Files' - # Localization functions. - 'Get-LocString' - 'Import-LocStrings' - # Logging command functions. - 'Write-AddAttachment' - 'Write-AddBuildTag' - 'Write-AssociateArtifact' - 'Write-LogDetail' - 'Write-SetProgress' - 'Write-SetResult' - 'Write-SetSecret' - 'Write-SetVariable' - 'Write-TaskDebug' - 'Write-TaskError' - 'Write-TaskVerbose' - 'Write-TaskWarning' - 'Write-UpdateBuildNumber' - 'Write-UploadArtifact' - 'Write-UploadBuildLog' - # Out functions. - 'Out-Default' - # Server OM functions. - 'Get-AssemblyReference' - 'Get-TfsClientCredentials' - 'Get-TfsService' - 'Get-VssCredentials' - 'Get-VssHttpClient' - # Tool functions. - 'Assert-Path' - 'Invoke-Tool' - # Trace functions. - 'Trace-EnteringInvocation' - 'Trace-LeavingInvocation' - 'Trace-Path' - ) - -# Special internal exception type to control the flow. Not currently intended -# for public usage and subject to change. If the type has already -# been loaded once, then it is not loaded again. -Write-Verbose "Adding exceptions types." -Add-Type -WarningAction SilentlyContinue -Debug:$false -TypeDefinition @' -namespace VstsTaskSdk -{ - public class TerminationException : System.Exception - { - public TerminationException(System.String message) : base(message) { } - } -} -'@ - -# Override Out-Default globally. -$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported) -New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global - -# Perform some initialization in a script block to enable merging the pipelines. -$scriptText = @" -# Load the SDK resource strings. -Import-LocStrings "$PSScriptRoot\lib.json" - -# Load the module that contains ConvertTo-SecureString. -if (!(Get-Module -Name Microsoft.PowerShell.Security)) { - Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'." - Import-Module -Name Microsoft.PowerShell.Security 2>&1 | - ForEach-Object { - if (`$_ -is [System.Management.Automation.ErrorRecord]) { - Write-Verbose `$_.Exception.Message - } else { - ,`$_ - } - } -} -"@ -. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default - -# Create Invoke-VstsTaskScript in a special way so it is not bound to the module. -# Otherwise calling the task script block would run within the module context. -# -# An alternative way to solve the problem is to close the script block (i.e. closure). -# However, that introduces a different problem. Closed script blocks are created within -# a dynamic module. Each module gets it's own session state separate from the global -# session state. When running in a regular script context, Import-Module calls import -# the target module into the global session state. When running in a module context, -# Import-Module calls import the target module into the caller module's session state. -# -# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts -# should run in regular script context. The end user specifying an ad-hoc script expects -# the module import rules to be consistent with the default behavior (i.e. imported -# into the global session state). -$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@' - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [scriptblock]$ScriptBlock) - - try { - $global:ErrorActionPreference = 'Stop' - - # Initialize the environment. - $vstsModule = Get-Module -Name VstsTaskSdk - Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default - & $vstsModule Initialize-Inputs 4>&1 | Out-Default - - # Remove the local variable before calling the user's script. - Remove-Variable -Name vstsModule - - # Call the user's script. - $ScriptBlock | - ForEach-Object { - # Remove the scriptblock variable before calling it. - Remove-Variable -Name ScriptBlock - & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default - } - } catch [VstsTaskSdk.TerminationException] { - # Special internal exception type to control the flow. Not currently intended - # for public usage and subject to change. - Write-Verbose "Task script terminated." 4>&1 | Out-Default - } catch { - Write-Verbose "Caught exception from task script." 4>&1 | Out-Default - $_ | Out-Default - Write-Host "##vso[task.complete result=Failed]" - } -'@)) +[CmdletBinding()] +param( + [ValidateNotNull()] + [Parameter()] + [hashtable]$ModuleParameters = @{ }) + +if ($host.Name -ne 'ConsoleHost') { + Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts." +} + +# Private module variables. +[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true' +Write-Verbose "NonInteractive: $script:nonInteractive" + +# Import/export functions. +. "$PSScriptRoot\FindFunctions.ps1" +. "$PSScriptRoot\InputFunctions.ps1" +. "$PSScriptRoot\LegacyFindFunctions.ps1" +. "$PSScriptRoot\LocalizationFunctions.ps1" +. "$PSScriptRoot\LoggingCommandFunctions.ps1" +. "$PSScriptRoot\LongPathFunctions.ps1" +. "$PSScriptRoot\ServerOMFunctions.ps1" +. "$PSScriptRoot\ToolFunctions.ps1" +. "$PSScriptRoot\TraceFunctions.ps1" +. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded. +Export-ModuleMember -Function @( + # Find functions. + 'Find-Match' + 'New-FindOptions' + 'New-MatchOptions' + 'Select-Match' + # Input functions. + 'Get-Endpoint' + 'Get-Input' + 'Get-TaskVariable' + 'Get-TaskVariableInfo' + 'Set-TaskVariable' + # Legacy find functions. + 'Find-Files' + # Localization functions. + 'Get-LocString' + 'Import-LocStrings' + # Logging command functions. + 'Write-AddAttachment' + 'Write-AddBuildTag' + 'Write-AssociateArtifact' + 'Write-LogDetail' + 'Write-SetProgress' + 'Write-SetResult' + 'Write-SetSecret' + 'Write-SetVariable' + 'Write-TaskDebug' + 'Write-TaskError' + 'Write-TaskVerbose' + 'Write-TaskWarning' + 'Write-UpdateBuildNumber' + 'Write-UploadArtifact' + 'Write-UploadBuildLog' + # Out functions. + 'Out-Default' + # Server OM functions. + 'Get-AssemblyReference' + 'Get-TfsClientCredentials' + 'Get-TfsService' + 'Get-VssCredentials' + 'Get-VssHttpClient' + # Tool functions. + 'Assert-Path' + 'Invoke-Tool' + # Trace functions. + 'Trace-EnteringInvocation' + 'Trace-LeavingInvocation' + 'Trace-Path' + ) + +# Special internal exception type to control the flow. Not currently intended +# for public usage and subject to change. If the type has already +# been loaded once, then it is not loaded again. +Write-Verbose "Adding exceptions types." +Add-Type -WarningAction SilentlyContinue -Debug:$false -TypeDefinition @' +namespace VstsTaskSdk +{ + public class TerminationException : System.Exception + { + public TerminationException(System.String message) : base(message) { } + } +} +'@ + +# Override Out-Default globally. +$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported) +New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global + +# Perform some initialization in a script block to enable merging the pipelines. +$scriptText = @" +# Load the SDK resource strings. +Import-LocStrings "$PSScriptRoot\lib.json" + +# Load the module that contains ConvertTo-SecureString. +if (!(Get-Module -Name Microsoft.PowerShell.Security)) { + Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'." + Import-Module -Name Microsoft.PowerShell.Security 2>&1 | + ForEach-Object { + if (`$_ -is [System.Management.Automation.ErrorRecord]) { + Write-Verbose `$_.Exception.Message + } else { + ,`$_ + } + } +} +"@ +. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default + +# Create Invoke-VstsTaskScript in a special way so it is not bound to the module. +# Otherwise calling the task script block would run within the module context. +# +# An alternative way to solve the problem is to close the script block (i.e. closure). +# However, that introduces a different problem. Closed script blocks are created within +# a dynamic module. Each module gets it's own session state separate from the global +# session state. When running in a regular script context, Import-Module calls import +# the target module into the global session state. When running in a module context, +# Import-Module calls import the target module into the caller module's session state. +# +# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts +# should run in regular script context. The end user specifying an ad-hoc script expects +# the module import rules to be consistent with the default behavior (i.e. imported +# into the global session state). +$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@' + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [scriptblock]$ScriptBlock) + + try { + $global:ErrorActionPreference = 'Stop' + + # Initialize the environment. + $vstsModule = Get-Module -Name VstsTaskSdk + Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default + & $vstsModule Initialize-Inputs 4>&1 | Out-Default + + # Remove the local variable before calling the user's script. + Remove-Variable -Name vstsModule + + # Call the user's script. + $ScriptBlock | + ForEach-Object { + # Remove the scriptblock variable before calling it. + Remove-Variable -Name ScriptBlock + & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default + } + } catch [VstsTaskSdk.TerminationException] { + # Special internal exception type to control the flow. Not currently intended + # for public usage and subject to change. + Write-Verbose "Task script terminated." 4>&1 | Out-Default + } catch { + Write-Verbose "Caught exception from task script." 4>&1 | Out-Default + $_ | Out-Default + Write-Host "##vso[task.complete result=Failed]" + } +'@)) diff --git a/ShowVariables/ps_modules/VstsTaskSdk/lib.json b/src/ShowVariables/ps_modules/VstsTaskSdk/lib.json similarity index 98% rename from ShowVariables/ps_modules/VstsTaskSdk/lib.json rename to src/ShowVariables/ps_modules/VstsTaskSdk/lib.json index 6f3c333..b000819 100644 --- a/ShowVariables/ps_modules/VstsTaskSdk/lib.json +++ b/src/ShowVariables/ps_modules/VstsTaskSdk/lib.json @@ -1,19 +1,19 @@ -{ - "messages": { - "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'", - "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials", - "PSLIB_EndpointUrl0": "'{0}' service endpoint URL", - "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'", - "PSLIB_FileNotFound0": "File not found: '{0}'", - "PSLIB_Input0": "'{0}' input", - "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'", - "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'", - "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'", - "PSLIB_PathNotFound0": "Path not found: '{0}'", - "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.", - "PSLIB_Required0": "Required: {0}", - "PSLIB_StringFormatFailed": "String format failed.", - "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'", - "PSLIB_TaskVariable0": "'{0}' task variable" - } -} +{ + "messages": { + "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'", + "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials", + "PSLIB_EndpointUrl0": "'{0}' service endpoint URL", + "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'", + "PSLIB_FileNotFound0": "File not found: '{0}'", + "PSLIB_Input0": "'{0}' input", + "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'", + "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'", + "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'", + "PSLIB_PathNotFound0": "Path not found: '{0}'", + "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.", + "PSLIB_Required0": "Required: {0}", + "PSLIB_StringFormatFailed": "String format failed.", + "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'", + "PSLIB_TaskVariable0": "'{0}' task variable" + } +} diff --git a/ShowVariables/task.json b/src/ShowVariables/task.json similarity index 100% rename from ShowVariables/task.json rename to src/ShowVariables/task.json diff --git a/VersionAssemblies/icon.png b/src/VersionAssemblies/icon.png similarity index 100% rename from VersionAssemblies/icon.png rename to src/VersionAssemblies/icon.png diff --git a/VersionAssemblies/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/src/VersionAssemblies/ps_modules/VstsTaskSdk/FindFunctions.ps1 similarity index 97% rename from VersionAssemblies/ps_modules/VstsTaskSdk/FindFunctions.ps1 rename to src/VersionAssemblies/ps_modules/VstsTaskSdk/FindFunctions.ps1 index c380b5e..d2087b1 100644 --- a/VersionAssemblies/ps_modules/VstsTaskSdk/FindFunctions.ps1 +++ b/src/VersionAssemblies/ps_modules/VstsTaskSdk/FindFunctions.ps1 @@ -1,689 +1,689 @@ -<# -.SYNOPSIS -Finds files using match patterns. - -.DESCRIPTION -Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root. - -.PARAMETER DefaultRoot -Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location. - -.PARAMETER Pattern -Patterns to apply. Supports interleaved exclude patterns. - -.PARAMETER FindOptions -When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files. - -.PARAMETER MatchOptions -When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase). -#> -function Find-Match { - [CmdletBinding()] - param( - [Parameter()] - [string]$DefaultRoot, - [Parameter()] - [string[]]$Pattern, - $FindOptions, - $MatchOptions) - - Trace-EnteringInvocation $MyInvocation -Parameter None - $originalErrorActionPreference = $ErrorActionPreference - try { - $ErrorActionPreference = 'Stop' - - # Apply defaults for parameters and trace. - if (!$DefaultRoot) { - $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path - } - - Write-Verbose "DefaultRoot: '$DefaultRoot'" - if (!$FindOptions) { - $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks - } - - Trace-FindOptions -Options $FindOptions - if (!$MatchOptions) { - $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase - } - - Trace-MatchOptions -Options $MatchOptions - Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll - - # Normalize slashes for root dir. - $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot - - $results = @{ } - $originalMatchOptions = $MatchOptions - foreach ($pat in $Pattern) { - Write-Verbose "Pattern: '$pat'" - - # Trim and skip empty. - $pat = "$pat".Trim() - if (!$pat) { - Write-Verbose 'Skipping empty pattern.' - continue - } - - # Clone match options. - $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions - - # Skip comments. - if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) { - Write-Verbose 'Skipping comment.' - continue - } - - # Set NoComment. Brace expansion could result in a leading '#'. - $MatchOptions.NoComment = $true - - # Determine whether pattern is include or exclude. - $negateCount = 0 - if (!$MatchOptions.NoNegate) { - while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') { - $negateCount++ - } - - $pat = $pat.Substring($negateCount) # trim leading '!' - if ($negateCount) { - Write-Verbose "Trimmed leading '!'. Pattern: '$pat'" - } - } - - $isIncludePattern = $negateCount -eq 0 -or - ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or - ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate) - - # Set NoNegate. Brace expansion could result in a leading '!'. - $MatchOptions.NoNegate = $true - $MatchOptions.FlipNegate = $false - - # Trim and skip empty. - $pat = "$pat".Trim() - if (!$pat) { - Write-Verbose 'Skipping empty pattern.' - continue - } - - # Expand braces - required to accurately interpret findPath. - $expanded = $null - $preExpanded = $pat - if ($MatchOptions.NoBrace) { - $expanded = @( $pat ) - } else { - # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot - # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3). - Write-Verbose "Expanding braces." - $convertedPattern = $pat -replace '\\', '/' - $expanded = [Minimatch.Minimatcher]::BraceExpand( - $convertedPattern, - (ConvertTo-MinimatchOptions -Options $MatchOptions)) - } - - # Set NoBrace. - $MatchOptions.NoBrace = $true - - foreach ($pat in $expanded) { - if ($pat -ne $preExpanded) { - Write-Verbose "Pattern: '$pat'" - } - - # Trim and skip empty. - $pat = "$pat".Trim() - if (!$pat) { - Write-Verbose "Skipping empty pattern." - continue - } - - if ($isIncludePattern) { - # Determine the findPath. - $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions - $findPath = $findInfo.FindPath - Write-Verbose "FindPath: '$findPath'" - - if (!$findPath) { - Write-Verbose "Skipping empty path." - continue - } - - # Perform the find. - Write-Verbose "StatOnly: '$($findInfo.StatOnly)'" - [string[]]$findResults = @( ) - if ($findInfo.StatOnly) { - # Simply stat the path - all path segments were used to build the path. - if ((Test-Path -LiteralPath $findPath)) { - $findResults += $findPath - } - } else { - $findResults = Get-FindResult -Path $findPath -Options $FindOptions - } - - Write-Verbose "Found $($findResults.Count) paths." - - # Apply the pattern. - Write-Verbose "Applying include pattern." - if ($findInfo.AdjustedPattern -ne $pat) { - Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'" - $pat = $findInfo.AdjustedPattern - } - - $matchResults = [Minimatch.Minimatcher]::Filter( - $findResults, - $pat, - (ConvertTo-MinimatchOptions -Options $MatchOptions)) - - # Union the results. - $matchCount = 0 - foreach ($matchResult in $matchResults) { - $matchCount++ - $results[$matchResult.ToUpperInvariant()] = $matchResult - } - - Write-Verbose "$matchCount matches" - } else { - # Check if basename only and MatchBase=true. - if ($MatchOptions.MatchBase -and - !(Test-Rooted -Path $pat) -and - ($pat -replace '\\', '/').IndexOf('/') -lt 0) { - - # Do not root the pattern. - Write-Verbose "MatchBase and basename only." - } else { - # Root the exclude pattern. - $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat - Write-Verbose "After Get-RootedPattern, pattern: '$pat'" - } - - # Apply the pattern. - Write-Verbose 'Applying exclude pattern.' - $matchResults = [Minimatch.Minimatcher]::Filter( - [string[]]$results.Values, - $pat, - (ConvertTo-MinimatchOptions -Options $MatchOptions)) - - # Subtract the results. - $matchCount = 0 - foreach ($matchResult in $matchResults) { - $matchCount++ - $results.Remove($matchResult.ToUpperInvariant()) - } - - Write-Verbose "$matchCount matches" - } - } - } - - $finalResult = @( $results.Values | Sort-Object ) - Write-Verbose "$($finalResult.Count) final results" - return $finalResult - } catch { - $ErrorActionPreference = $originalErrorActionPreference - Write-Error $_ - } finally { - Trace-LeavingInvocation -InvocationInfo $MyInvocation - } -} - -<# -.SYNOPSIS -Creates FindOptions for use with Find-VstsMatch. - -.DESCRIPTION -Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks. - -.PARAMETER FollowSpecifiedSymbolicLink -Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed. - -.PARAMETER FollowSymbolicLinks -Indicates whether to traverse descendants of symbolic link directories. -#> -function New-FindOptions { - [CmdletBinding()] - param( - [switch]$FollowSpecifiedSymbolicLink, - [switch]$FollowSymbolicLinks) - - return New-Object psobject -Property @{ - FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent - FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent - } -} - -<# -.SYNOPSIS -Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. - -.DESCRIPTION -Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied. -#> -function New-MatchOptions { - [CmdletBinding()] - param( - [switch]$Dot, - [switch]$FlipNegate, - [switch]$MatchBase, - [switch]$NoBrace, - [switch]$NoCase, - [switch]$NoComment, - [switch]$NoExt, - [switch]$NoGlobStar, - [switch]$NoNegate, - [switch]$NoNull) - - return New-Object psobject -Property @{ - Dot = $Dot.IsPresent - FlipNegate = $FlipNegate.IsPresent - MatchBase = $MatchBase.IsPresent - NoBrace = $NoBrace.IsPresent - NoCase = $NoCase.IsPresent - NoComment = $NoComment.IsPresent - NoExt = $NoExt.IsPresent - NoGlobStar = $NoGlobStar.IsPresent - NoNegate = $NoNegate.IsPresent - NoNull = $NoNull.IsPresent - } -} - -<# -.SYNOPSIS -Applies match patterns against a list of files. - -.DESCRIPTION -Applies match patterns to a list of paths. Supports interleaved exclude patterns. - -.PARAMETER ItemPath -Array of paths. - -.PARAMETER Pattern -Patterns to apply. Supports interleaved exclude patterns. - -.PARAMETER Options -When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase). -#> -function Select-Match { - [CmdletBinding()] - param( - [Parameter()] - [string[]]$ItemPath, - [Parameter()] - [string[]]$Pattern, - $Options) - - - Trace-EnteringInvocation $MyInvocation -Parameter None - $originalErrorActionPreference = $ErrorActionPreference - try { - $ErrorActionPreference = 'Stop' - if (!$Options) { - $Options = New-MatchOptions -Dot -NoBrace -NoCase - } - - Trace-MatchOptions -Options $Options - Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll - - # Hashtable to keep track of matches. - $map = @{ } - - $originalOptions = $Options - foreach ($pat in $Pattern) { - Write-Verbose "Pattern: '$pat'" - - # Trim and skip empty. - $pat = "$pat".Trim() - if (!$pat) { - Write-Verbose 'Skipping empty pattern.' - continue - } - - # Clone match options. - $Options = Copy-MatchOptions -Options $originalOptions - - # Skip comments. - if (!$Options.NoComment -and $pat.StartsWith('#')) { - Write-Verbose 'Skipping comment.' - continue - } - - # Set NoComment. - $Options.NoComment = $true - - # Determine whether pattern is include or exclude. - $negateCount = 0 - if (!$Options.NoNegate) { - while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') { - $negateCount++ - } - - $pat = $pat.Substring($negateCount) # trim leading '!' - if ($negateCount) { - Write-Verbose "Trimmed leading '!'. Pattern: '$pat'" - } - } - - $isIncludePattern = $negateCount -eq 0 -or - ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or - ($negateCount % 2 -eq 1 -and $Options.FlipNegate) - - # Set NoNegate. Brace expansion could result in a leading '!'. - $Options.NoNegate = $true - $Options.FlipNegate = $false - - # Trim and skip empty. - $pat = "$pat".Trim() - if (!$pat) { - Write-Verbose 'Skipping empty pattern.' - continue - } - - if ($isIncludePattern) { - # Apply the pattern. - Write-Verbose 'Applying include pattern against original list' - $matchResults = [Minimatch.Minimatcher]::Filter( - $ItemPath, - $pat, - (ConvertTo-MinimatchOptions -Options $Options)) - - # Union the results. - $matchCount = 0 - foreach ($matchResult in $matchResults) { - $matchCount++ - $map[$matchResult] = $true - } - - Write-Verbose "$matchCount matches" - } - else { - # Apply the pattern. - Write-Verbose 'Applying exclude pattern against original list' - $matchResults = [Minimatch.Minimatcher]::Filter( - $ItemPath, - $pat, - (ConvertTo-MinimatchOptions -Options $Options)) - - # Subtract the results. - $matchCount = 0 - foreach ($matchResult in $matchResults) { - $matchCount++ - $map.Remove($matchResult) - } - - Write-Verbose "$matchCount matches" - } - } - - # return a filtered version of the original list (preserves order and prevents duplication) - $result = $ItemPath | Where-Object { $map[$_] } - Write-Verbose "$($result.Count) final results" - $result - } catch { - $ErrorActionPreference = $originalErrorActionPreference - Write-Error $_ - } finally { - Trace-LeavingInvocation -InvocationInfo $MyInvocation - } -} - -################################################################################ -# Private functions. -################################################################################ - -function Copy-MatchOptions { - [CmdletBinding()] - param($Options) - - return New-Object psobject -Property @{ - Dot = $Options.Dot -eq $true - FlipNegate = $Options.FlipNegate -eq $true - MatchBase = $Options.MatchBase -eq $true - NoBrace = $Options.NoBrace -eq $true - NoCase = $Options.NoCase -eq $true - NoComment = $Options.NoComment -eq $true - NoExt = $Options.NoExt -eq $true - NoGlobStar = $Options.NoGlobStar -eq $true - NoNegate = $Options.NoNegate -eq $true - NoNull = $Options.NoNull -eq $true - } -} - -function ConvertTo-MinimatchOptions { - [CmdletBinding()] - param($Options) - - $opt = New-Object Minimatch.Options - $opt.AllowWindowsPaths = $true - $opt.Dot = $Options.Dot -eq $true - $opt.FlipNegate = $Options.FlipNegate -eq $true - $opt.MatchBase = $Options.MatchBase -eq $true - $opt.NoBrace = $Options.NoBrace -eq $true - $opt.NoCase = $Options.NoCase -eq $true - $opt.NoComment = $Options.NoComment -eq $true - $opt.NoExt = $Options.NoExt -eq $true - $opt.NoGlobStar = $Options.NoGlobStar -eq $true - $opt.NoNegate = $Options.NoNegate -eq $true - $opt.NoNull = $Options.NoNull -eq $true - return $opt -} - -function ConvertTo-NormalizedSeparators { - [CmdletBinding()] - param([string]$Path) - - # Convert slashes. - $Path = "$Path".Replace('/', '\') - - # Remove redundant slashes. - $isUnc = $Path -match '^\\\\+[^\\]' - $Path = $Path -replace '\\\\+', '\' - if ($isUnc) { - $Path = '\' + $Path - } - - return $Path -} - -function Get-FindInfoFromPattern { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$DefaultRoot, - [Parameter(Mandatory = $true)] - [string]$Pattern, - [Parameter(Mandatory = $true)] - $MatchOptions) - - if (!$MatchOptions.NoBrace) { - throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true." - } - - # For the sake of determining the find path, pretend NoCase=false. - $MatchOptions = Copy-MatchOptions -Options $MatchOptions - $MatchOptions.NoCase = $false - - # Check if basename only and MatchBase=true - if ($MatchOptions.MatchBase -and - !(Test-Rooted -Path $Pattern) -and - ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) { - - return New-Object psobject -Property @{ - AdjustedPattern = $Pattern - FindPath = $DefaultRoot - StatOnly = $false - } - } - - # The technique applied by this function is to use the information on the Minimatch object determine - # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which - # segments are literal vs patterns. - # - # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the - # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved - # for now. - $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions)) - - # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only - # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer - # enumerable, but that should be turned off by the time this function is reached. - # - # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs - # implementation. The .NET implementation is a port and is by a different author. - $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic') - [object[]]$set = $setFieldInfo.GetValue($minimatchObj) - if ($set.Count -ne 1) { - throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'" - } - - [string[]]$literalSegments = @( ) - [object[]]$parsedSegments = $set[0] - foreach ($parsedSegment in $parsedSegments) { - if ($parsedSegment.GetType().Name -eq 'LiteralItem') { - # The item is a LiteralItem when the original input for the path segment does not contain any - # unescaped glob characters. - $literalSegments += $parsedSegment.Source; - continue - } - - break; - } - - # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes - # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can - # be detected from the original pattern. - $joinedSegments = [string]::Join('/', $literalSegments) - if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) { - $joinedSegments = '/' + $joinedSegments # restore UNC format - } - - # Determine the find path. - $findPath = '' - if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted. - $findPath = $joinedSegments - } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found. - $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments) - } else { # The pattern is not rooted, and no literal segements were found. - $findPath = $DefaultRoot - } - - # Clean up the path. - if ($findPath) { - $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash. - $findPath = ConvertTo-NormalizedSeparators -Path $findPath - } - - return New-Object psobject -Property @{ - AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern - FindPath = $findPath - StatOnly = $literalSegments.Count -eq $parsedSegments.Count - } -} - -function Get-FindResult { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Path, - [Parameter(Mandatory = $true)] - $Options) - - if (!(Test-Path -LiteralPath $Path)) { - Write-Verbose 'Path not found.' - return - } - - $Path = ConvertTo-NormalizedSeparators -Path $Path - - # Push the first item. - [System.Collections.Stack]$stack = New-Object System.Collections.Stack - $stack.Push((Get-Item -LiteralPath $Path)) - - $count = 0 - while ($stack.Count) { - # Pop the next item and yield the result. - $item = $stack.Pop() - $count++ - $item.FullName - - # Traverse. - if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory - if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint - $Options.FollowSymbolicLinks -or - ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) { - - $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force ) - [System.Array]::Reverse($childItems) - foreach ($childItem in $childItems) { - $stack.Push($childItem) - } - } - } - } -} - -function Get-RootedPattern { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$DefaultRoot, - [Parameter(Mandatory = $true)] - [string]$Pattern) - - if ((Test-Rooted -Path $Pattern)) { - return $Pattern - } - - # Normalize root. - $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot - - # Escape special glob characters. - $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment - $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?' - $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*' - $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+(' - $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@(' - $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!(' - - if ($DefaultRoot -like '[A-Z]:') { # e.g. C: - return "$DefaultRoot$Pattern" - } - - # Ensure root ends with a separator. - if (!$DefaultRoot.EndsWith('\')) { - $DefaultRoot = "$DefaultRoot\" - } - - return "$DefaultRoot$Pattern" -} - -function Test-Rooted { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Path) - - $Path = ConvertTo-NormalizedSeparators -Path $Path - return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello - $Path -like '[A-Z]:*' # e.g. C: or C:\hello -} - -function Trace-MatchOptions { - [CmdletBinding()] - param($Options) - - Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'" - Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'" - Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'" - Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'" - Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'" - Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'" - Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'" - Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'" - Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'" - Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'" -} - -function Trace-FindOptions { - [CmdletBinding()] - param($Options) - - Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'" - Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'" -} +<# +.SYNOPSIS +Finds files using match patterns. + +.DESCRIPTION +Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root. + +.PARAMETER DefaultRoot +Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location. + +.PARAMETER Pattern +Patterns to apply. Supports interleaved exclude patterns. + +.PARAMETER FindOptions +When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files. + +.PARAMETER MatchOptions +When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase). +#> +function Find-Match { + [CmdletBinding()] + param( + [Parameter()] + [string]$DefaultRoot, + [Parameter()] + [string[]]$Pattern, + $FindOptions, + $MatchOptions) + + Trace-EnteringInvocation $MyInvocation -Parameter None + $originalErrorActionPreference = $ErrorActionPreference + try { + $ErrorActionPreference = 'Stop' + + # Apply defaults for parameters and trace. + if (!$DefaultRoot) { + $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path + } + + Write-Verbose "DefaultRoot: '$DefaultRoot'" + if (!$FindOptions) { + $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks + } + + Trace-FindOptions -Options $FindOptions + if (!$MatchOptions) { + $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase + } + + Trace-MatchOptions -Options $MatchOptions + Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll + + # Normalize slashes for root dir. + $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot + + $results = @{ } + $originalMatchOptions = $MatchOptions + foreach ($pat in $Pattern) { + Write-Verbose "Pattern: '$pat'" + + # Trim and skip empty. + $pat = "$pat".Trim() + if (!$pat) { + Write-Verbose 'Skipping empty pattern.' + continue + } + + # Clone match options. + $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions + + # Skip comments. + if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) { + Write-Verbose 'Skipping comment.' + continue + } + + # Set NoComment. Brace expansion could result in a leading '#'. + $MatchOptions.NoComment = $true + + # Determine whether pattern is include or exclude. + $negateCount = 0 + if (!$MatchOptions.NoNegate) { + while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') { + $negateCount++ + } + + $pat = $pat.Substring($negateCount) # trim leading '!' + if ($negateCount) { + Write-Verbose "Trimmed leading '!'. Pattern: '$pat'" + } + } + + $isIncludePattern = $negateCount -eq 0 -or + ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or + ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate) + + # Set NoNegate. Brace expansion could result in a leading '!'. + $MatchOptions.NoNegate = $true + $MatchOptions.FlipNegate = $false + + # Trim and skip empty. + $pat = "$pat".Trim() + if (!$pat) { + Write-Verbose 'Skipping empty pattern.' + continue + } + + # Expand braces - required to accurately interpret findPath. + $expanded = $null + $preExpanded = $pat + if ($MatchOptions.NoBrace) { + $expanded = @( $pat ) + } else { + # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot + # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3). + Write-Verbose "Expanding braces." + $convertedPattern = $pat -replace '\\', '/' + $expanded = [Minimatch.Minimatcher]::BraceExpand( + $convertedPattern, + (ConvertTo-MinimatchOptions -Options $MatchOptions)) + } + + # Set NoBrace. + $MatchOptions.NoBrace = $true + + foreach ($pat in $expanded) { + if ($pat -ne $preExpanded) { + Write-Verbose "Pattern: '$pat'" + } + + # Trim and skip empty. + $pat = "$pat".Trim() + if (!$pat) { + Write-Verbose "Skipping empty pattern." + continue + } + + if ($isIncludePattern) { + # Determine the findPath. + $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions + $findPath = $findInfo.FindPath + Write-Verbose "FindPath: '$findPath'" + + if (!$findPath) { + Write-Verbose "Skipping empty path." + continue + } + + # Perform the find. + Write-Verbose "StatOnly: '$($findInfo.StatOnly)'" + [string[]]$findResults = @( ) + if ($findInfo.StatOnly) { + # Simply stat the path - all path segments were used to build the path. + if ((Test-Path -LiteralPath $findPath)) { + $findResults += $findPath + } + } else { + $findResults = Get-FindResult -Path $findPath -Options $FindOptions + } + + Write-Verbose "Found $($findResults.Count) paths." + + # Apply the pattern. + Write-Verbose "Applying include pattern." + if ($findInfo.AdjustedPattern -ne $pat) { + Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'" + $pat = $findInfo.AdjustedPattern + } + + $matchResults = [Minimatch.Minimatcher]::Filter( + $findResults, + $pat, + (ConvertTo-MinimatchOptions -Options $MatchOptions)) + + # Union the results. + $matchCount = 0 + foreach ($matchResult in $matchResults) { + $matchCount++ + $results[$matchResult.ToUpperInvariant()] = $matchResult + } + + Write-Verbose "$matchCount matches" + } else { + # Check if basename only and MatchBase=true. + if ($MatchOptions.MatchBase -and + !(Test-Rooted -Path $pat) -and + ($pat -replace '\\', '/').IndexOf('/') -lt 0) { + + # Do not root the pattern. + Write-Verbose "MatchBase and basename only." + } else { + # Root the exclude pattern. + $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat + Write-Verbose "After Get-RootedPattern, pattern: '$pat'" + } + + # Apply the pattern. + Write-Verbose 'Applying exclude pattern.' + $matchResults = [Minimatch.Minimatcher]::Filter( + [string[]]$results.Values, + $pat, + (ConvertTo-MinimatchOptions -Options $MatchOptions)) + + # Subtract the results. + $matchCount = 0 + foreach ($matchResult in $matchResults) { + $matchCount++ + $results.Remove($matchResult.ToUpperInvariant()) + } + + Write-Verbose "$matchCount matches" + } + } + } + + $finalResult = @( $results.Values | Sort-Object ) + Write-Verbose "$($finalResult.Count) final results" + return $finalResult + } catch { + $ErrorActionPreference = $originalErrorActionPreference + Write-Error $_ + } finally { + Trace-LeavingInvocation -InvocationInfo $MyInvocation + } +} + +<# +.SYNOPSIS +Creates FindOptions for use with Find-VstsMatch. + +.DESCRIPTION +Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks. + +.PARAMETER FollowSpecifiedSymbolicLink +Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed. + +.PARAMETER FollowSymbolicLinks +Indicates whether to traverse descendants of symbolic link directories. +#> +function New-FindOptions { + [CmdletBinding()] + param( + [switch]$FollowSpecifiedSymbolicLink, + [switch]$FollowSymbolicLinks) + + return New-Object psobject -Property @{ + FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent + FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent + } +} + +<# +.SYNOPSIS +Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. + +.DESCRIPTION +Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied. +#> +function New-MatchOptions { + [CmdletBinding()] + param( + [switch]$Dot, + [switch]$FlipNegate, + [switch]$MatchBase, + [switch]$NoBrace, + [switch]$NoCase, + [switch]$NoComment, + [switch]$NoExt, + [switch]$NoGlobStar, + [switch]$NoNegate, + [switch]$NoNull) + + return New-Object psobject -Property @{ + Dot = $Dot.IsPresent + FlipNegate = $FlipNegate.IsPresent + MatchBase = $MatchBase.IsPresent + NoBrace = $NoBrace.IsPresent + NoCase = $NoCase.IsPresent + NoComment = $NoComment.IsPresent + NoExt = $NoExt.IsPresent + NoGlobStar = $NoGlobStar.IsPresent + NoNegate = $NoNegate.IsPresent + NoNull = $NoNull.IsPresent + } +} + +<# +.SYNOPSIS +Applies match patterns against a list of files. + +.DESCRIPTION +Applies match patterns to a list of paths. Supports interleaved exclude patterns. + +.PARAMETER ItemPath +Array of paths. + +.PARAMETER Pattern +Patterns to apply. Supports interleaved exclude patterns. + +.PARAMETER Options +When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase). +#> +function Select-Match { + [CmdletBinding()] + param( + [Parameter()] + [string[]]$ItemPath, + [Parameter()] + [string[]]$Pattern, + $Options) + + + Trace-EnteringInvocation $MyInvocation -Parameter None + $originalErrorActionPreference = $ErrorActionPreference + try { + $ErrorActionPreference = 'Stop' + if (!$Options) { + $Options = New-MatchOptions -Dot -NoBrace -NoCase + } + + Trace-MatchOptions -Options $Options + Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll + + # Hashtable to keep track of matches. + $map = @{ } + + $originalOptions = $Options + foreach ($pat in $Pattern) { + Write-Verbose "Pattern: '$pat'" + + # Trim and skip empty. + $pat = "$pat".Trim() + if (!$pat) { + Write-Verbose 'Skipping empty pattern.' + continue + } + + # Clone match options. + $Options = Copy-MatchOptions -Options $originalOptions + + # Skip comments. + if (!$Options.NoComment -and $pat.StartsWith('#')) { + Write-Verbose 'Skipping comment.' + continue + } + + # Set NoComment. + $Options.NoComment = $true + + # Determine whether pattern is include or exclude. + $negateCount = 0 + if (!$Options.NoNegate) { + while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') { + $negateCount++ + } + + $pat = $pat.Substring($negateCount) # trim leading '!' + if ($negateCount) { + Write-Verbose "Trimmed leading '!'. Pattern: '$pat'" + } + } + + $isIncludePattern = $negateCount -eq 0 -or + ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or + ($negateCount % 2 -eq 1 -and $Options.FlipNegate) + + # Set NoNegate. Brace expansion could result in a leading '!'. + $Options.NoNegate = $true + $Options.FlipNegate = $false + + # Trim and skip empty. + $pat = "$pat".Trim() + if (!$pat) { + Write-Verbose 'Skipping empty pattern.' + continue + } + + if ($isIncludePattern) { + # Apply the pattern. + Write-Verbose 'Applying include pattern against original list' + $matchResults = [Minimatch.Minimatcher]::Filter( + $ItemPath, + $pat, + (ConvertTo-MinimatchOptions -Options $Options)) + + # Union the results. + $matchCount = 0 + foreach ($matchResult in $matchResults) { + $matchCount++ + $map[$matchResult] = $true + } + + Write-Verbose "$matchCount matches" + } + else { + # Apply the pattern. + Write-Verbose 'Applying exclude pattern against original list' + $matchResults = [Minimatch.Minimatcher]::Filter( + $ItemPath, + $pat, + (ConvertTo-MinimatchOptions -Options $Options)) + + # Subtract the results. + $matchCount = 0 + foreach ($matchResult in $matchResults) { + $matchCount++ + $map.Remove($matchResult) + } + + Write-Verbose "$matchCount matches" + } + } + + # return a filtered version of the original list (preserves order and prevents duplication) + $result = $ItemPath | Where-Object { $map[$_] } + Write-Verbose "$($result.Count) final results" + $result + } catch { + $ErrorActionPreference = $originalErrorActionPreference + Write-Error $_ + } finally { + Trace-LeavingInvocation -InvocationInfo $MyInvocation + } +} + +################################################################################ +# Private functions. +################################################################################ + +function Copy-MatchOptions { + [CmdletBinding()] + param($Options) + + return New-Object psobject -Property @{ + Dot = $Options.Dot -eq $true + FlipNegate = $Options.FlipNegate -eq $true + MatchBase = $Options.MatchBase -eq $true + NoBrace = $Options.NoBrace -eq $true + NoCase = $Options.NoCase -eq $true + NoComment = $Options.NoComment -eq $true + NoExt = $Options.NoExt -eq $true + NoGlobStar = $Options.NoGlobStar -eq $true + NoNegate = $Options.NoNegate -eq $true + NoNull = $Options.NoNull -eq $true + } +} + +function ConvertTo-MinimatchOptions { + [CmdletBinding()] + param($Options) + + $opt = New-Object Minimatch.Options + $opt.AllowWindowsPaths = $true + $opt.Dot = $Options.Dot -eq $true + $opt.FlipNegate = $Options.FlipNegate -eq $true + $opt.MatchBase = $Options.MatchBase -eq $true + $opt.NoBrace = $Options.NoBrace -eq $true + $opt.NoCase = $Options.NoCase -eq $true + $opt.NoComment = $Options.NoComment -eq $true + $opt.NoExt = $Options.NoExt -eq $true + $opt.NoGlobStar = $Options.NoGlobStar -eq $true + $opt.NoNegate = $Options.NoNegate -eq $true + $opt.NoNull = $Options.NoNull -eq $true + return $opt +} + +function ConvertTo-NormalizedSeparators { + [CmdletBinding()] + param([string]$Path) + + # Convert slashes. + $Path = "$Path".Replace('/', '\') + + # Remove redundant slashes. + $isUnc = $Path -match '^\\\\+[^\\]' + $Path = $Path -replace '\\\\+', '\' + if ($isUnc) { + $Path = '\' + $Path + } + + return $Path +} + +function Get-FindInfoFromPattern { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$DefaultRoot, + [Parameter(Mandatory = $true)] + [string]$Pattern, + [Parameter(Mandatory = $true)] + $MatchOptions) + + if (!$MatchOptions.NoBrace) { + throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true." + } + + # For the sake of determining the find path, pretend NoCase=false. + $MatchOptions = Copy-MatchOptions -Options $MatchOptions + $MatchOptions.NoCase = $false + + # Check if basename only and MatchBase=true + if ($MatchOptions.MatchBase -and + !(Test-Rooted -Path $Pattern) -and + ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) { + + return New-Object psobject -Property @{ + AdjustedPattern = $Pattern + FindPath = $DefaultRoot + StatOnly = $false + } + } + + # The technique applied by this function is to use the information on the Minimatch object determine + # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which + # segments are literal vs patterns. + # + # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the + # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved + # for now. + $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions)) + + # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only + # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer + # enumerable, but that should be turned off by the time this function is reached. + # + # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs + # implementation. The .NET implementation is a port and is by a different author. + $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic') + [object[]]$set = $setFieldInfo.GetValue($minimatchObj) + if ($set.Count -ne 1) { + throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'" + } + + [string[]]$literalSegments = @( ) + [object[]]$parsedSegments = $set[0] + foreach ($parsedSegment in $parsedSegments) { + if ($parsedSegment.GetType().Name -eq 'LiteralItem') { + # The item is a LiteralItem when the original input for the path segment does not contain any + # unescaped glob characters. + $literalSegments += $parsedSegment.Source; + continue + } + + break; + } + + # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes + # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can + # be detected from the original pattern. + $joinedSegments = [string]::Join('/', $literalSegments) + if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) { + $joinedSegments = '/' + $joinedSegments # restore UNC format + } + + # Determine the find path. + $findPath = '' + if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted. + $findPath = $joinedSegments + } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found. + $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments) + } else { # The pattern is not rooted, and no literal segements were found. + $findPath = $DefaultRoot + } + + # Clean up the path. + if ($findPath) { + $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash. + $findPath = ConvertTo-NormalizedSeparators -Path $findPath + } + + return New-Object psobject -Property @{ + AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern + FindPath = $findPath + StatOnly = $literalSegments.Count -eq $parsedSegments.Count + } +} + +function Get-FindResult { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Path, + [Parameter(Mandatory = $true)] + $Options) + + if (!(Test-Path -LiteralPath $Path)) { + Write-Verbose 'Path not found.' + return + } + + $Path = ConvertTo-NormalizedSeparators -Path $Path + + # Push the first item. + [System.Collections.Stack]$stack = New-Object System.Collections.Stack + $stack.Push((Get-Item -LiteralPath $Path)) + + $count = 0 + while ($stack.Count) { + # Pop the next item and yield the result. + $item = $stack.Pop() + $count++ + $item.FullName + + # Traverse. + if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory + if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint + $Options.FollowSymbolicLinks -or + ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) { + + $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force ) + [System.Array]::Reverse($childItems) + foreach ($childItem in $childItems) { + $stack.Push($childItem) + } + } + } + } +} + +function Get-RootedPattern { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$DefaultRoot, + [Parameter(Mandatory = $true)] + [string]$Pattern) + + if ((Test-Rooted -Path $Pattern)) { + return $Pattern + } + + # Normalize root. + $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot + + # Escape special glob characters. + $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment + $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?' + $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*' + $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+(' + $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@(' + $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!(' + + if ($DefaultRoot -like '[A-Z]:') { # e.g. C: + return "$DefaultRoot$Pattern" + } + + # Ensure root ends with a separator. + if (!$DefaultRoot.EndsWith('\')) { + $DefaultRoot = "$DefaultRoot\" + } + + return "$DefaultRoot$Pattern" +} + +function Test-Rooted { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Path) + + $Path = ConvertTo-NormalizedSeparators -Path $Path + return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello + $Path -like '[A-Z]:*' # e.g. C: or C:\hello +} + +function Trace-MatchOptions { + [CmdletBinding()] + param($Options) + + Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'" + Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'" + Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'" + Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'" + Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'" + Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'" + Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'" + Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'" + Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'" + Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'" +} + +function Trace-FindOptions { + [CmdletBinding()] + param($Options) + + Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'" + Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'" +} diff --git a/ShowVariables/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/src/VersionAssemblies/ps_modules/VstsTaskSdk/InputFunctions.ps1 similarity index 97% rename from ShowVariables/ps_modules/VstsTaskSdk/InputFunctions.ps1 rename to src/VersionAssemblies/ps_modules/VstsTaskSdk/InputFunctions.ps1 index 25299be..5f3ab9e 100644 --- a/ShowVariables/ps_modules/VstsTaskSdk/InputFunctions.ps1 +++ b/src/VersionAssemblies/ps_modules/VstsTaskSdk/InputFunctions.ps1 @@ -1,425 +1,425 @@ -# Hash table of known variable info. The formatted env var name is the lookup key. -# -# The purpose of this hash table is to keep track of known variables. The hash table -# needs to be maintained for multiple reasons: -# 1) to distinguish between env vars and job vars -# 2) to distinguish between secret vars and public -# 3) to know the real variable name and not just the formatted env var name. -$script:knownVariables = @{ } -$script:vault = @{ } - -<# -.SYNOPSIS -Gets an endpoint. - -.DESCRIPTION -Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url. - -The Data property requires a 1.97 agent or higher. - -.PARAMETER Require -Writes an error to the error pipeline if the endpoint is not found. -#> -function Get-Endpoint { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Name, - [switch]$Require) - - $originalErrorActionPreference = $ErrorActionPreference - try { - $ErrorActionPreference = 'Stop' - - # Get the URL. - $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name - $key = "ENDPOINT_URL_$Name" - $url = Get-VaultValue -Description $description -Key $key -Require:$Require - - # Get the auth object. - $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name - $key = "ENDPOINT_AUTH_$Name" - if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) { - $auth = ConvertFrom-Json -InputObject $auth - } - - # Get the data. - $description = "'$Name' service endpoint data" - $key = "ENDPOINT_DATA_$Name" - if ($data = (Get-VaultValue -Description $description -Key $key)) { - $data = ConvertFrom-Json -InputObject $data - } - - # Return the endpoint. - if ($url -or $auth -or $data) { - New-Object -TypeName psobject -Property @{ - Url = $url - Auth = $auth - Data = $data - } - } - } catch { - $ErrorActionPreference = $originalErrorActionPreference - Write-Error $_ - } -} - -<# -.SYNOPSIS -Gets an input. - -.DESCRIPTION -Gets the value for the specified input name. - -.PARAMETER AsBool -Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false. - -.PARAMETER AsInt -Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails. - -.PARAMETER Default -Default value to use if the input is null or empty. - -.PARAMETER Require -Writes an error to the error pipeline if the input is null or empty. -#> -function Get-Input { - [CmdletBinding(DefaultParameterSetName = 'Require')] - param( - [Parameter(Mandatory = $true)] - [string]$Name, - [Parameter(ParameterSetName = 'Default')] - $Default, - [Parameter(ParameterSetName = 'Require')] - [switch]$Require, - [switch]$AsBool, - [switch]$AsInt) - - # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required - # in order to concisely invoke the correct parameter set. - $null = $PSBoundParameters.Remove('Name') - $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name - $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())" - Get-VaultValue @PSBoundParameters -Description $description -Key $key -} - -<# -.SYNOPSIS -Gets a task variable. - -.DESCRIPTION -Gets the value for the specified task variable. - -.PARAMETER AsBool -Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false. - -.PARAMETER AsInt -Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails. - -.PARAMETER Default -Default value to use if the input is null or empty. - -.PARAMETER Require -Writes an error to the error pipeline if the input is null or empty. -#> -function Get-TaskVariable { - [CmdletBinding(DefaultParameterSetName = 'Require')] - param( - [Parameter(Mandatory = $true)] - [string]$Name, - [Parameter(ParameterSetName = 'Default')] - $Default, - [Parameter(ParameterSetName = 'Require')] - [switch]$Require, - [switch]$AsBool, - [switch]$AsInt) - - $originalErrorActionPreference = $ErrorActionPreference - try { - $ErrorActionPreference = 'Stop' - $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name - $variableKey = Get-VariableKey -Name $Name - if ($script:knownVariables.$variableKey.Secret) { - # Get secret variable. Splatting is required to concisely invoke the correct parameter set. - $null = $PSBoundParameters.Remove('Name') - $vaultKey = "SECRET_$variableKey" - Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey - } else { - # Get public variable. - $item = $null - $path = "Env:$variableKey" - if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) { - # Intentionally empty. Value was successfully retrieved. - } elseif (!$script:nonInteractive) { - # The value wasn't found and the module is running in interactive dev mode. - # Prompt for the value. - Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description) - if (Test-Path -LiteralPath $path) { - $item = Get-Item -LiteralPath $path - } - } - - # Get the converted value. Splatting is required to concisely invoke the correct parameter set. - $null = $PSBoundParameters.Remove('Name') - Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value - } - } catch { - $ErrorActionPreference = $originalErrorActionPreference - Write-Error $_ - } -} - -<# -.SYNOPSIS -Gets all job variables available to the task. Requires 2.104.1 agent or higher. - -.DESCRIPTION -Gets a snapshot of the current state of all job variables available to the task. -Requires a 2.104.1 agent or higher for full functionality. - -Returns an array of objects with the following properties: - [string]Name - [string]Value - [bool]Secret - -Limitations on an agent prior to 2.104.1: - 1) The return value does not include all public variables. Only public variables - that have been added using setVariable are returned. - 2) The name returned for each secret variable is the formatted environment variable - name, not the actual variable name (unless it was set explicitly at runtime using - setVariable). -#> -function Get-TaskVariableInfo { - [CmdletBinding()] - param() - - foreach ($info in $script:knownVariables.Values) { - New-Object -TypeName psobject -Property @{ - Name = $info.Name - Value = Get-TaskVariable -Name $info.Name - Secret = $info.Secret - } - } -} - -<# -.SYNOPSIS -Sets a task variable. - -.DESCRIPTION -Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job. -#> -function Set-TaskVariable { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Name, - [string]$Value, - [switch]$Secret) - - # Once a secret always a secret. - $variableKey = Get-VariableKey -Name $Name - [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret - if ($Secret) { - $vaultKey = "SECRET_$variableKey" - if (!$Value) { - # Clear the secret. - Write-Verbose "Set $Name = ''" - $script:vault.Remove($vaultKey) - } else { - # Store the secret in the vault. - Write-Verbose "Set $Name = '********'" - $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential( - $vaultKey, - (ConvertTo-SecureString -String $Value -AsPlainText -Force)) - } - - # Clear the environment variable. - Set-Item -LiteralPath "Env:$variableKey" -Value '' - } else { - # Set the environment variable. - Write-Verbose "Set $Name = '$Value'" - Set-Item -LiteralPath "Env:$variableKey" -Value $Value - } - - # Store the metadata. - $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{ - Name = $name - Secret = $Secret - } - - # Persist the variable in the task context. - Write-SetVariable -Name $Name -Value $Value -Secret:$Secret -} - -######################################## -# Private functions. -######################################## -function Get-VaultValue { - [CmdletBinding(DefaultParameterSetName = 'Require')] - param( - [Parameter(Mandatory = $true)] - [string]$Description, - [Parameter(Mandatory = $true)] - [string]$Key, - [Parameter(ParameterSetName = 'Require')] - [switch]$Require, - [Parameter(ParameterSetName = 'Default')] - [object]$Default, - [switch]$AsBool, - [switch]$AsInt) - - # Attempt to get the vault value. - $value = $null - if ($psCredential = $script:vault[$Key]) { - $value = $psCredential.GetNetworkCredential().Password - } elseif (!$script:nonInteractive) { - # The value wasn't found. Prompt for the value if running in interactive dev mode. - $value = Read-Host -Prompt $Description - if ($value) { - $script:vault[$Key] = New-Object System.Management.Automation.PSCredential( - $Key, - (ConvertTo-SecureString -String $value -AsPlainText -Force)) - } - } - - Get-Value -Value $value @PSBoundParameters -} - -function Get-Value { - [CmdletBinding(DefaultParameterSetName = 'Require')] - param( - [string]$Value, - [Parameter(Mandatory = $true)] - [string]$Description, - [Parameter(Mandatory = $true)] - [string]$Key, - [Parameter(ParameterSetName = 'Require')] - [switch]$Require, - [Parameter(ParameterSetName = 'Default')] - [object]$Default, - [switch]$AsBool, - [switch]$AsInt) - - $result = $Value - if ($result) { - if ($Key -like 'ENDPOINT_AUTH_*') { - Write-Verbose "$($Key): '********'" - } else { - Write-Verbose "$($Key): '$result'" - } - } else { - Write-Verbose "$Key (empty)" - - # Write error if required. - if ($Require) { - Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)" - return - } - - # Fallback to the default if provided. - if ($PSCmdlet.ParameterSetName -eq 'Default') { - $result = $Default - $OFS = ' ' - Write-Verbose " Defaulted to: '$result'" - } else { - $result = '' - } - } - - # Convert to bool if specified. - if ($AsBool) { - if ($result -isnot [bool]) { - $result = "$result" -in '1', 'true' - Write-Verbose " Converted to bool: $result" - } - - return $result - } - - # Convert to int if specified. - if ($AsInt) { - if ($result -isnot [int]) { - try { - $result = [int]"$result" - } catch { - $result = 0 - } - - Write-Verbose " Converted to int: $result" - } - - return $result - } - - return $result -} - -function Initialize-Inputs { - # Store endpoints, inputs, and secret variables in the vault. - foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*)) { - # Record the secret variable metadata. This is required by Get-TaskVariable to - # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten - # when $env:VSTS_SECRET_VARIABLES is processed. - if ($variable.Name -like 'SECRET_?*') { - $variableKey = $variable.Name.Substring('SECRET_'.Length) - $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{ - # This is technically not the variable name (has underscores instead of dots), - # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent - # where $env:VSTS_SECRET_VARIABLES is not defined. - Name = $variableKey - Secret = $true - } - } - - # Store the value in the vault. - $vaultKey = $variable.Name - if ($variable.Value) { - $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential( - $vaultKey, - (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force)) - } - - # Clear the environment variable. - Remove-Item -LiteralPath "Env:$($variable.Name)" - } - - # Record the public variable names. Env var added in 2.104.1 agent. - if ($env:VSTS_PUBLIC_VARIABLES) { - foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) { - $variableKey = Get-VariableKey -Name $name - $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{ - Name = $name - Secret = $false - } - } - - $env:VSTS_PUBLIC_VARIABLES = '' - } - - # Record the secret variable names. Env var added in 2.104.1 agent. - if ($env:VSTS_SECRET_VARIABLES) { - foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) { - $variableKey = Get-VariableKey -Name $name - $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{ - Name = $name - Secret = $true - } - } - - $env:VSTS_SECRET_VARIABLES = '' - } -} - -function Get-VariableKey { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Name) - - if ($Name -ne 'agent.jobstatus') { - $Name = $Name.Replace('.', '_') - } - - $Name.ToUpperInvariant() -} +# Hash table of known variable info. The formatted env var name is the lookup key. +# +# The purpose of this hash table is to keep track of known variables. The hash table +# needs to be maintained for multiple reasons: +# 1) to distinguish between env vars and job vars +# 2) to distinguish between secret vars and public +# 3) to know the real variable name and not just the formatted env var name. +$script:knownVariables = @{ } +$script:vault = @{ } + +<# +.SYNOPSIS +Gets an endpoint. + +.DESCRIPTION +Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url. + +The Data property requires a 1.97 agent or higher. + +.PARAMETER Require +Writes an error to the error pipeline if the endpoint is not found. +#> +function Get-Endpoint { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Name, + [switch]$Require) + + $originalErrorActionPreference = $ErrorActionPreference + try { + $ErrorActionPreference = 'Stop' + + # Get the URL. + $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name + $key = "ENDPOINT_URL_$Name" + $url = Get-VaultValue -Description $description -Key $key -Require:$Require + + # Get the auth object. + $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name + $key = "ENDPOINT_AUTH_$Name" + if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) { + $auth = ConvertFrom-Json -InputObject $auth + } + + # Get the data. + $description = "'$Name' service endpoint data" + $key = "ENDPOINT_DATA_$Name" + if ($data = (Get-VaultValue -Description $description -Key $key)) { + $data = ConvertFrom-Json -InputObject $data + } + + # Return the endpoint. + if ($url -or $auth -or $data) { + New-Object -TypeName psobject -Property @{ + Url = $url + Auth = $auth + Data = $data + } + } + } catch { + $ErrorActionPreference = $originalErrorActionPreference + Write-Error $_ + } +} + +<# +.SYNOPSIS +Gets an input. + +.DESCRIPTION +Gets the value for the specified input name. + +.PARAMETER AsBool +Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false. + +.PARAMETER AsInt +Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails. + +.PARAMETER Default +Default value to use if the input is null or empty. + +.PARAMETER Require +Writes an error to the error pipeline if the input is null or empty. +#> +function Get-Input { + [CmdletBinding(DefaultParameterSetName = 'Require')] + param( + [Parameter(Mandatory = $true)] + [string]$Name, + [Parameter(ParameterSetName = 'Default')] + $Default, + [Parameter(ParameterSetName = 'Require')] + [switch]$Require, + [switch]$AsBool, + [switch]$AsInt) + + # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required + # in order to concisely invoke the correct parameter set. + $null = $PSBoundParameters.Remove('Name') + $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name + $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())" + Get-VaultValue @PSBoundParameters -Description $description -Key $key +} + +<# +.SYNOPSIS +Gets a task variable. + +.DESCRIPTION +Gets the value for the specified task variable. + +.PARAMETER AsBool +Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false. + +.PARAMETER AsInt +Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails. + +.PARAMETER Default +Default value to use if the input is null or empty. + +.PARAMETER Require +Writes an error to the error pipeline if the input is null or empty. +#> +function Get-TaskVariable { + [CmdletBinding(DefaultParameterSetName = 'Require')] + param( + [Parameter(Mandatory = $true)] + [string]$Name, + [Parameter(ParameterSetName = 'Default')] + $Default, + [Parameter(ParameterSetName = 'Require')] + [switch]$Require, + [switch]$AsBool, + [switch]$AsInt) + + $originalErrorActionPreference = $ErrorActionPreference + try { + $ErrorActionPreference = 'Stop' + $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name + $variableKey = Get-VariableKey -Name $Name + if ($script:knownVariables.$variableKey.Secret) { + # Get secret variable. Splatting is required to concisely invoke the correct parameter set. + $null = $PSBoundParameters.Remove('Name') + $vaultKey = "SECRET_$variableKey" + Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey + } else { + # Get public variable. + $item = $null + $path = "Env:$variableKey" + if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) { + # Intentionally empty. Value was successfully retrieved. + } elseif (!$script:nonInteractive) { + # The value wasn't found and the module is running in interactive dev mode. + # Prompt for the value. + Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description) + if (Test-Path -LiteralPath $path) { + $item = Get-Item -LiteralPath $path + } + } + + # Get the converted value. Splatting is required to concisely invoke the correct parameter set. + $null = $PSBoundParameters.Remove('Name') + Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value + } + } catch { + $ErrorActionPreference = $originalErrorActionPreference + Write-Error $_ + } +} + +<# +.SYNOPSIS +Gets all job variables available to the task. Requires 2.104.1 agent or higher. + +.DESCRIPTION +Gets a snapshot of the current state of all job variables available to the task. +Requires a 2.104.1 agent or higher for full functionality. + +Returns an array of objects with the following properties: + [string]Name + [string]Value + [bool]Secret + +Limitations on an agent prior to 2.104.1: + 1) The return value does not include all public variables. Only public variables + that have been added using setVariable are returned. + 2) The name returned for each secret variable is the formatted environment variable + name, not the actual variable name (unless it was set explicitly at runtime using + setVariable). +#> +function Get-TaskVariableInfo { + [CmdletBinding()] + param() + + foreach ($info in $script:knownVariables.Values) { + New-Object -TypeName psobject -Property @{ + Name = $info.Name + Value = Get-TaskVariable -Name $info.Name + Secret = $info.Secret + } + } +} + +<# +.SYNOPSIS +Sets a task variable. + +.DESCRIPTION +Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job. +#> +function Set-TaskVariable { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Name, + [string]$Value, + [switch]$Secret) + + # Once a secret always a secret. + $variableKey = Get-VariableKey -Name $Name + [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret + if ($Secret) { + $vaultKey = "SECRET_$variableKey" + if (!$Value) { + # Clear the secret. + Write-Verbose "Set $Name = ''" + $script:vault.Remove($vaultKey) + } else { + # Store the secret in the vault. + Write-Verbose "Set $Name = '********'" + $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential( + $vaultKey, + (ConvertTo-SecureString -String $Value -AsPlainText -Force)) + } + + # Clear the environment variable. + Set-Item -LiteralPath "Env:$variableKey" -Value '' + } else { + # Set the environment variable. + Write-Verbose "Set $Name = '$Value'" + Set-Item -LiteralPath "Env:$variableKey" -Value $Value + } + + # Store the metadata. + $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{ + Name = $name + Secret = $Secret + } + + # Persist the variable in the task context. + Write-SetVariable -Name $Name -Value $Value -Secret:$Secret +} + +######################################## +# Private functions. +######################################## +function Get-VaultValue { + [CmdletBinding(DefaultParameterSetName = 'Require')] + param( + [Parameter(Mandatory = $true)] + [string]$Description, + [Parameter(Mandatory = $true)] + [string]$Key, + [Parameter(ParameterSetName = 'Require')] + [switch]$Require, + [Parameter(ParameterSetName = 'Default')] + [object]$Default, + [switch]$AsBool, + [switch]$AsInt) + + # Attempt to get the vault value. + $value = $null + if ($psCredential = $script:vault[$Key]) { + $value = $psCredential.GetNetworkCredential().Password + } elseif (!$script:nonInteractive) { + # The value wasn't found. Prompt for the value if running in interactive dev mode. + $value = Read-Host -Prompt $Description + if ($value) { + $script:vault[$Key] = New-Object System.Management.Automation.PSCredential( + $Key, + (ConvertTo-SecureString -String $value -AsPlainText -Force)) + } + } + + Get-Value -Value $value @PSBoundParameters +} + +function Get-Value { + [CmdletBinding(DefaultParameterSetName = 'Require')] + param( + [string]$Value, + [Parameter(Mandatory = $true)] + [string]$Description, + [Parameter(Mandatory = $true)] + [string]$Key, + [Parameter(ParameterSetName = 'Require')] + [switch]$Require, + [Parameter(ParameterSetName = 'Default')] + [object]$Default, + [switch]$AsBool, + [switch]$AsInt) + + $result = $Value + if ($result) { + if ($Key -like 'ENDPOINT_AUTH_*') { + Write-Verbose "$($Key): '********'" + } else { + Write-Verbose "$($Key): '$result'" + } + } else { + Write-Verbose "$Key (empty)" + + # Write error if required. + if ($Require) { + Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)" + return + } + + # Fallback to the default if provided. + if ($PSCmdlet.ParameterSetName -eq 'Default') { + $result = $Default + $OFS = ' ' + Write-Verbose " Defaulted to: '$result'" + } else { + $result = '' + } + } + + # Convert to bool if specified. + if ($AsBool) { + if ($result -isnot [bool]) { + $result = "$result" -in '1', 'true' + Write-Verbose " Converted to bool: $result" + } + + return $result + } + + # Convert to int if specified. + if ($AsInt) { + if ($result -isnot [int]) { + try { + $result = [int]"$result" + } catch { + $result = 0 + } + + Write-Verbose " Converted to int: $result" + } + + return $result + } + + return $result +} + +function Initialize-Inputs { + # Store endpoints, inputs, and secret variables in the vault. + foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*)) { + # Record the secret variable metadata. This is required by Get-TaskVariable to + # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten + # when $env:VSTS_SECRET_VARIABLES is processed. + if ($variable.Name -like 'SECRET_?*') { + $variableKey = $variable.Name.Substring('SECRET_'.Length) + $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{ + # This is technically not the variable name (has underscores instead of dots), + # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent + # where $env:VSTS_SECRET_VARIABLES is not defined. + Name = $variableKey + Secret = $true + } + } + + # Store the value in the vault. + $vaultKey = $variable.Name + if ($variable.Value) { + $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential( + $vaultKey, + (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force)) + } + + # Clear the environment variable. + Remove-Item -LiteralPath "Env:$($variable.Name)" + } + + # Record the public variable names. Env var added in 2.104.1 agent. + if ($env:VSTS_PUBLIC_VARIABLES) { + foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) { + $variableKey = Get-VariableKey -Name $name + $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{ + Name = $name + Secret = $false + } + } + + $env:VSTS_PUBLIC_VARIABLES = '' + } + + # Record the secret variable names. Env var added in 2.104.1 agent. + if ($env:VSTS_SECRET_VARIABLES) { + foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) { + $variableKey = Get-VariableKey -Name $name + $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{ + Name = $name + Secret = $true + } + } + + $env:VSTS_SECRET_VARIABLES = '' + } +} + +function Get-VariableKey { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Name) + + if ($Name -ne 'agent.jobstatus') { + $Name = $Name.Replace('.', '_') + } + + $Name.ToUpperInvariant() +} diff --git a/ShowVariables/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/src/VersionAssemblies/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 similarity index 97% rename from ShowVariables/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 rename to src/VersionAssemblies/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 index b4080ae..f6aaa5a 100644 --- a/ShowVariables/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 +++ b/src/VersionAssemblies/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 @@ -1,320 +1,320 @@ -<# -.SYNOPSIS -Finds files or directories. - -.DESCRIPTION -Finds files or directories using advanced pattern matching. - -.PARAMETER LiteralDirectory -Directory to search. - -.PARAMETER LegacyPattern -Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns. - -Separate multiple patterns using ";". Escape actual ";" in the path by using ";;". -"?" indicates a wildcard that represents any single character within a path segment. -"*" indicates a wildcard that represents zero or more characters within a path segment. -"**" as the entire path segment indicates a recursive search. -"**" within a path segment indicates a recursive intersegment wildcard. -"+:" (can be omitted) indicates an include pattern. -"-:" indicates an exclude pattern. - -The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns. - -.PARAMETER IncludeFiles -Indicates whether to include files in the results. - -If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed. - -.PARAMETER IncludeDirectories -Indicates whether to include directories in the results. - -If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed. - -.PARAMETER Force -Indicates whether to include hidden items. - -.EXAMPLE -Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt" - -Given: -C:\Directory\Is1Match.txt -C:\Directory\Is2Match.txt -C:\Directory\IsNotMatch.txt - -Returns: -C:\Directory\Is1Match.txt -C:\Directory\Is2Match.txt - -.EXAMPLE -Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt" - -Given: -C:\Directory\IsOneMatch.txt -C:\Directory\IsTwoMatch.txt -C:\Directory\NonMatch.txt - -Returns: -C:\Directory\IsOneMatch.txt -C:\Directory\IsTwoMatch.txt - -.EXAMPLE -Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt" - -Given: -C:\Directory\Match.txt -C:\Directory\NotAMatch.txt -C:\Directory\SubDir\Match.txt -C:\Directory\SubDir\SubSubDir\Match.txt - -Returns: -C:\Directory\Match.txt -C:\Directory\SubDir\Match.txt -C:\Directory\SubDir\SubSubDir\Match.txt - -.EXAMPLE -Find-VstsFiles -LegacyPattern "C:\Directory\**" - -Given: -C:\Directory\One.txt -C:\Directory\SubDir\Two.txt -C:\Directory\SubDir\SubSubDir\Three.txt - -Returns: -C:\Directory\One.txt -C:\Directory\SubDir\Two.txt -C:\Directory\SubDir\SubSubDir\Three.txt - -.EXAMPLE -Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt" - -Given: -C:\Directory\IsNotAMatch.txt -C:\Directory\SubDir\IsAMatch.txt -C:\Directory\SubDir\IsNot.txt -C:\Directory\SubDir\SubSubDir\IsAMatch.txt -C:\Directory\SubDir\SubSubDir\IsNot.txt - -Returns: -C:\Directory\SubDir\IsAMatch.txt -C:\Directory\SubDir\SubSubDir\IsAMatch.txt -#> -function Find-Files { - [CmdletBinding()] - param( - [ValidateNotNullOrEmpty()] - [Parameter()] - [string]$LiteralDirectory, - [Parameter(Mandatory = $true)] - [string]$LegacyPattern, - [switch]$IncludeFiles, - [switch]$IncludeDirectories, - [switch]$Force) - - # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator, - # this function does not appear to be able to search the root of a drive and other - # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix. - - Trace-EnteringInvocation $MyInvocation - if (!$IncludeFiles -and !$IncludeDirectories) { - $IncludeFiles = $true - } - - $includePatterns = New-Object System.Collections.Generic.List[string] - $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex] - $LegacyPattern = $LegacyPattern.Replace(';;', "`0") - foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) { - $pattern = $pattern.Replace("`0", ';') - $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern) - if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) { - # Use the root directory provided to make the pattern a rooted path. - $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern) - } - - # Validate pattern does not end with a \. - if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) { - throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern) - } - - if ($isIncludePattern) { - $includePatterns.Add($pattern) - } else { - $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern)) - } - } - - $count = 0 - foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) { - $count++ - $path - } - - Write-Verbose "Total found: $count" - Trace-LeavingInvocation $MyInvocation -} - -######################################## -# Private functions. -######################################## -function Convert-PatternToRegex { - [CmdletBinding()] - param([string]$Pattern) - - $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape. - Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar. - Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators. - Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators. - # bug: should be '[^/]' instead of '.' - Replace('\?', '.') # Replace single character wildcards. - New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase) -} - -function Get-FileNameFilter { - [CmdletBinding()] - param([string]$Pattern) - - $index = $Pattern.LastIndexOf('\') - if ($index -eq -1 -or # Pattern does not contain a backslash. - !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash. - $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard. - { - return '*' - } - - # bug? is this supposed to do substring? - return $Pattern -} - -function Get-MatchingItems { - [CmdletBinding()] - param( - [System.Collections.Generic.List[string]]$IncludePatterns, - [System.Collections.Generic.List[regex]]$ExcludePatterns, - [switch]$IncludeFiles, - [switch]$IncludeDirectories, - [switch]$Force) - - Trace-EnteringInvocation $MyInvocation - $allFiles = New-Object System.Collections.Generic.HashSet[string] - foreach ($pattern in $IncludePatterns) { - $pathPrefix = Get-PathPrefix -Pattern $pattern - $fileNameFilter = Get-FileNameFilter -Pattern $pattern - $patternRegex = Convert-PatternToRegex -Pattern $pattern - # Iterate over the directories and files under the pathPrefix. - Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force | - ForEach-Object { - # Normalize separators. - $normalizedPath = $_.Replace('\', '/') - # **/times/** will not match C:/fun/times because there isn't a trailing slash. - # So try both if including directories. - $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false - # positive if the item is a regular file and not a directory - - $isMatch = $false - if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) { - $isMatch = $true - - # Test whether the path should be excluded. - foreach ($regex in $ExcludePatterns) { - if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) { - $isMatch = $false - break - } - } - } - - if ($isMatch) { - $null = $allFiles.Add($_) - } - } - } - - Trace-Path -Path $allFiles -PassThru - Trace-LeavingInvocation $MyInvocation -} - -function Get-PathIterator { - [CmdletBinding()] - param( - [string]$Path, - [string]$Filter, - [switch]$IncludeFiles, - [switch]$IncludeDirectories, - [switch]$Force) - - if (!$Path) { - return - } - - # bug: this returns the dir without verifying whether exists - if ($IncludeDirectories) { - $Path - } - - Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse | - ForEach-Object { - if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) { - if ($IncludeDirectories) { - $_.FullName - } - } elseif ($IncludeFiles) { - $_.FullName - } - } -} - -function Get-PathPrefix { - [CmdletBinding()] - param([string]$Pattern) - - # Note, unable to search root directories is a limitation due to subtleties of this function - # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty. - # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield - # empty in some cases. See the following examples of Path.GetDirectoryName() input => output: - # C:/ => - # C:/hello => C:\ - # C:/hello/ => C:\hello - # C:/hello/world => C:\hello - # C:/hello/world/ => C:\hello\world - # C: => - # C:hello => C: - # C:hello/ => C:hello - # / => - # /hello => \ - # /hello/ => \hello - # //hello => - # //hello/ => - # //hello/world => - # //hello/world/ => \\hello\world - - $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0])) - if ($index -eq -1) { - # If no wildcards are found, return the directory name portion of the path. - # If there is no directory name (file name only in pattern), this will return empty string. - return [System.IO.Path]::GetDirectoryName($Pattern) - } - - [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index)) -} - -function Test-IsIncludePattern { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [ref]$Pattern) - - # Include patterns start with +: or anything except -: - # Exclude patterns start with -: - if ($Pattern.value.StartsWith("+:")) { - # Remove the prefix. - $Pattern.value = $Pattern.value.Substring(2) - $true - } elseif ($Pattern.value.StartsWith("-:")) { - # Remove the prefix. - $Pattern.value = $Pattern.value.Substring(2) - $false - } else { - # No prefix, so leave the string alone. - $true; - } -} +<# +.SYNOPSIS +Finds files or directories. + +.DESCRIPTION +Finds files or directories using advanced pattern matching. + +.PARAMETER LiteralDirectory +Directory to search. + +.PARAMETER LegacyPattern +Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns. + +Separate multiple patterns using ";". Escape actual ";" in the path by using ";;". +"?" indicates a wildcard that represents any single character within a path segment. +"*" indicates a wildcard that represents zero or more characters within a path segment. +"**" as the entire path segment indicates a recursive search. +"**" within a path segment indicates a recursive intersegment wildcard. +"+:" (can be omitted) indicates an include pattern. +"-:" indicates an exclude pattern. + +The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns. + +.PARAMETER IncludeFiles +Indicates whether to include files in the results. + +If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed. + +.PARAMETER IncludeDirectories +Indicates whether to include directories in the results. + +If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed. + +.PARAMETER Force +Indicates whether to include hidden items. + +.EXAMPLE +Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt" + +Given: +C:\Directory\Is1Match.txt +C:\Directory\Is2Match.txt +C:\Directory\IsNotMatch.txt + +Returns: +C:\Directory\Is1Match.txt +C:\Directory\Is2Match.txt + +.EXAMPLE +Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt" + +Given: +C:\Directory\IsOneMatch.txt +C:\Directory\IsTwoMatch.txt +C:\Directory\NonMatch.txt + +Returns: +C:\Directory\IsOneMatch.txt +C:\Directory\IsTwoMatch.txt + +.EXAMPLE +Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt" + +Given: +C:\Directory\Match.txt +C:\Directory\NotAMatch.txt +C:\Directory\SubDir\Match.txt +C:\Directory\SubDir\SubSubDir\Match.txt + +Returns: +C:\Directory\Match.txt +C:\Directory\SubDir\Match.txt +C:\Directory\SubDir\SubSubDir\Match.txt + +.EXAMPLE +Find-VstsFiles -LegacyPattern "C:\Directory\**" + +Given: +C:\Directory\One.txt +C:\Directory\SubDir\Two.txt +C:\Directory\SubDir\SubSubDir\Three.txt + +Returns: +C:\Directory\One.txt +C:\Directory\SubDir\Two.txt +C:\Directory\SubDir\SubSubDir\Three.txt + +.EXAMPLE +Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt" + +Given: +C:\Directory\IsNotAMatch.txt +C:\Directory\SubDir\IsAMatch.txt +C:\Directory\SubDir\IsNot.txt +C:\Directory\SubDir\SubSubDir\IsAMatch.txt +C:\Directory\SubDir\SubSubDir\IsNot.txt + +Returns: +C:\Directory\SubDir\IsAMatch.txt +C:\Directory\SubDir\SubSubDir\IsAMatch.txt +#> +function Find-Files { + [CmdletBinding()] + param( + [ValidateNotNullOrEmpty()] + [Parameter()] + [string]$LiteralDirectory, + [Parameter(Mandatory = $true)] + [string]$LegacyPattern, + [switch]$IncludeFiles, + [switch]$IncludeDirectories, + [switch]$Force) + + # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator, + # this function does not appear to be able to search the root of a drive and other + # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix. + + Trace-EnteringInvocation $MyInvocation + if (!$IncludeFiles -and !$IncludeDirectories) { + $IncludeFiles = $true + } + + $includePatterns = New-Object System.Collections.Generic.List[string] + $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex] + $LegacyPattern = $LegacyPattern.Replace(';;', "`0") + foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) { + $pattern = $pattern.Replace("`0", ';') + $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern) + if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) { + # Use the root directory provided to make the pattern a rooted path. + $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern) + } + + # Validate pattern does not end with a \. + if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) { + throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern) + } + + if ($isIncludePattern) { + $includePatterns.Add($pattern) + } else { + $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern)) + } + } + + $count = 0 + foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) { + $count++ + $path + } + + Write-Verbose "Total found: $count" + Trace-LeavingInvocation $MyInvocation +} + +######################################## +# Private functions. +######################################## +function Convert-PatternToRegex { + [CmdletBinding()] + param([string]$Pattern) + + $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape. + Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar. + Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators. + Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators. + # bug: should be '[^/]' instead of '.' + Replace('\?', '.') # Replace single character wildcards. + New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase) +} + +function Get-FileNameFilter { + [CmdletBinding()] + param([string]$Pattern) + + $index = $Pattern.LastIndexOf('\') + if ($index -eq -1 -or # Pattern does not contain a backslash. + !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash. + $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard. + { + return '*' + } + + # bug? is this supposed to do substring? + return $Pattern +} + +function Get-MatchingItems { + [CmdletBinding()] + param( + [System.Collections.Generic.List[string]]$IncludePatterns, + [System.Collections.Generic.List[regex]]$ExcludePatterns, + [switch]$IncludeFiles, + [switch]$IncludeDirectories, + [switch]$Force) + + Trace-EnteringInvocation $MyInvocation + $allFiles = New-Object System.Collections.Generic.HashSet[string] + foreach ($pattern in $IncludePatterns) { + $pathPrefix = Get-PathPrefix -Pattern $pattern + $fileNameFilter = Get-FileNameFilter -Pattern $pattern + $patternRegex = Convert-PatternToRegex -Pattern $pattern + # Iterate over the directories and files under the pathPrefix. + Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force | + ForEach-Object { + # Normalize separators. + $normalizedPath = $_.Replace('\', '/') + # **/times/** will not match C:/fun/times because there isn't a trailing slash. + # So try both if including directories. + $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false + # positive if the item is a regular file and not a directory + + $isMatch = $false + if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) { + $isMatch = $true + + # Test whether the path should be excluded. + foreach ($regex in $ExcludePatterns) { + if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) { + $isMatch = $false + break + } + } + } + + if ($isMatch) { + $null = $allFiles.Add($_) + } + } + } + + Trace-Path -Path $allFiles -PassThru + Trace-LeavingInvocation $MyInvocation +} + +function Get-PathIterator { + [CmdletBinding()] + param( + [string]$Path, + [string]$Filter, + [switch]$IncludeFiles, + [switch]$IncludeDirectories, + [switch]$Force) + + if (!$Path) { + return + } + + # bug: this returns the dir without verifying whether exists + if ($IncludeDirectories) { + $Path + } + + Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse | + ForEach-Object { + if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) { + if ($IncludeDirectories) { + $_.FullName + } + } elseif ($IncludeFiles) { + $_.FullName + } + } +} + +function Get-PathPrefix { + [CmdletBinding()] + param([string]$Pattern) + + # Note, unable to search root directories is a limitation due to subtleties of this function + # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty. + # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield + # empty in some cases. See the following examples of Path.GetDirectoryName() input => output: + # C:/ => + # C:/hello => C:\ + # C:/hello/ => C:\hello + # C:/hello/world => C:\hello + # C:/hello/world/ => C:\hello\world + # C: => + # C:hello => C: + # C:hello/ => C:hello + # / => + # /hello => \ + # /hello/ => \hello + # //hello => + # //hello/ => + # //hello/world => + # //hello/world/ => \\hello\world + + $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0])) + if ($index -eq -1) { + # If no wildcards are found, return the directory name portion of the path. + # If there is no directory name (file name only in pattern), this will return empty string. + return [System.IO.Path]::GetDirectoryName($Pattern) + } + + [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index)) +} + +function Test-IsIncludePattern { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [ref]$Pattern) + + # Include patterns start with +: or anything except -: + # Exclude patterns start with -: + if ($Pattern.value.StartsWith("+:")) { + # Remove the prefix. + $Pattern.value = $Pattern.value.Substring(2) + $true + } elseif ($Pattern.value.StartsWith("-:")) { + # Remove the prefix. + $Pattern.value = $Pattern.value.Substring(2) + $false + } else { + # No prefix, so leave the string alone. + $true; + } +} diff --git a/ShowVariables/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/src/VersionAssemblies/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 similarity index 97% rename from ShowVariables/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 rename to src/VersionAssemblies/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 index c31790c..6f3b6bb 100644 --- a/ShowVariables/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 +++ b/src/VersionAssemblies/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 @@ -1,150 +1,150 @@ -$script:resourceStrings = @{ } - -<# -.SYNOPSIS -Gets a localized resource string. - -.DESCRIPTION -Gets a localized resource string and optionally formats the string with arguments. - -If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space). - -If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space). - -.PARAMETER Require -Writes an error to the error pipeline if the endpoint is not found. -#> -function Get-LocString { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true, Position = 1)] - [string]$Key, - [Parameter(Position = 2)] - [object[]]$ArgumentList = @( )) - - # Due to the dynamically typed nature of PowerShell, a single null argument passed - # to an array parameter is interpreted as a null array. - if ([object]::ReferenceEquals($null, $ArgumentList)) { - $ArgumentList = @( $null ) - } - - # Lookup the format string. - $format = '' - if (!($format = $script:resourceStrings[$Key])) { - # Warn the key was not found. Prevent recursion if the lookup key is the - # "string resource key not found" lookup key. - $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0' - if ($key -ne $resourceNotFoundKey) { - Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key) - } - - # Fallback to just the key itself if there aren't any arguments to format. - if (!$ArgumentList.Count) { return $key } - - # Otherwise fallback to the key followed by the arguments. - $OFS = " " - return "$key $ArgumentList" - } - - # Return the string if there aren't any arguments to format. - if (!$ArgumentList.Count) { return $format } - - try { - [string]::Format($format, $ArgumentList) - } catch { - Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed') - $OFS = " " - "$format $ArgumentList" - } -} - -<# -.SYNOPSIS -Imports resource strings for use with Get-VstsLocString. - -.DESCRIPTION -Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary. - -Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings. - -.Parameter LiteralPath -JSON file containing resource strings. - -.EXAMPLE -Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json - -Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section: -{ - "messages": { - "Hello": "Hello you!", - "Hello0": "Hello {0}!" - } -} - -.EXAMPLE -Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json - -Overlays strings from an optional separate resource file for the current culture. - -Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job. -Given the file Task.json contains: -{ - "messages": { - "GoodDay": "Good day!", - } -} -Given the file resources.resjson\de-DE\resources.resjson: -{ - "loc.messages.GoodDay": "Guten Tag!" -} - -The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!' -#> -function Import-LocStrings { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$LiteralPath) - - # Validate the file exists. - if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) { - Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath) - return - } - - # Load the json. - Write-Verbose "Loading resource strings from: $LiteralPath" - $count = 0 - if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) { - # Add each resource string to the hashtable. - foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) { - [string]$key = $member.Name - $script:resourceStrings[$key] = $messages."$key" - $count++ - } - } - - Write-Verbose "Loaded $count strings." - - # Get the culture. - $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US" - - # Load the resjson. - $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson" - if (Test-Path -LiteralPath $resjsonPath) { - Write-Verbose "Loading resource strings from: $resjsonPath" - $count = 0 - $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json - foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) { - if (!($value = $resjson."$($member.Name)")) { - continue - } - - [string]$key = $member.Name.Substring('loc.messages.'.Length) - $script:resourceStrings[$key] = $value - $count++ - } - - Write-Verbose "Loaded $count strings." - } -} +$script:resourceStrings = @{ } + +<# +.SYNOPSIS +Gets a localized resource string. + +.DESCRIPTION +Gets a localized resource string and optionally formats the string with arguments. + +If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space). + +If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space). + +.PARAMETER Require +Writes an error to the error pipeline if the endpoint is not found. +#> +function Get-LocString { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true, Position = 1)] + [string]$Key, + [Parameter(Position = 2)] + [object[]]$ArgumentList = @( )) + + # Due to the dynamically typed nature of PowerShell, a single null argument passed + # to an array parameter is interpreted as a null array. + if ([object]::ReferenceEquals($null, $ArgumentList)) { + $ArgumentList = @( $null ) + } + + # Lookup the format string. + $format = '' + if (!($format = $script:resourceStrings[$Key])) { + # Warn the key was not found. Prevent recursion if the lookup key is the + # "string resource key not found" lookup key. + $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0' + if ($key -ne $resourceNotFoundKey) { + Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key) + } + + # Fallback to just the key itself if there aren't any arguments to format. + if (!$ArgumentList.Count) { return $key } + + # Otherwise fallback to the key followed by the arguments. + $OFS = " " + return "$key $ArgumentList" + } + + # Return the string if there aren't any arguments to format. + if (!$ArgumentList.Count) { return $format } + + try { + [string]::Format($format, $ArgumentList) + } catch { + Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed') + $OFS = " " + "$format $ArgumentList" + } +} + +<# +.SYNOPSIS +Imports resource strings for use with Get-VstsLocString. + +.DESCRIPTION +Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary. + +Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings. + +.Parameter LiteralPath +JSON file containing resource strings. + +.EXAMPLE +Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json + +Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section: +{ + "messages": { + "Hello": "Hello you!", + "Hello0": "Hello {0}!" + } +} + +.EXAMPLE +Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json + +Overlays strings from an optional separate resource file for the current culture. + +Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job. +Given the file Task.json contains: +{ + "messages": { + "GoodDay": "Good day!", + } +} +Given the file resources.resjson\de-DE\resources.resjson: +{ + "loc.messages.GoodDay": "Guten Tag!" +} + +The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!' +#> +function Import-LocStrings { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$LiteralPath) + + # Validate the file exists. + if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) { + Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath) + return + } + + # Load the json. + Write-Verbose "Loading resource strings from: $LiteralPath" + $count = 0 + if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) { + # Add each resource string to the hashtable. + foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) { + [string]$key = $member.Name + $script:resourceStrings[$key] = $messages."$key" + $count++ + } + } + + Write-Verbose "Loaded $count strings." + + # Get the culture. + $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US" + + # Load the resjson. + $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson" + if (Test-Path -LiteralPath $resjsonPath) { + Write-Verbose "Loading resource strings from: $resjsonPath" + $count = 0 + $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json + foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) { + if (!($value = $resjson."$($member.Name)")) { + continue + } + + [string]$key = $member.Name.Substring('loc.messages.'.Length) + $script:resourceStrings[$key] = $value + $count++ + } + + Write-Verbose "Loaded $count strings." + } +} diff --git a/ShowVariables/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/src/VersionAssemblies/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 similarity index 96% rename from ShowVariables/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 rename to src/VersionAssemblies/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 index f7ca5c1..a8462ef 100644 --- a/ShowVariables/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 +++ b/src/VersionAssemblies/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 @@ -1,506 +1,506 @@ -$script:loggingCommandPrefix = '##vso[' -$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"? - New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' } - New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' } - New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' } -) -# TODO: BUG: Escape ] -# TODO: BUG: Escape % ??? -# TODO: Add test to verify don't need to escape "=". - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-AddAttachment { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Type, - [Parameter(Mandatory = $true)] - [string]$Name, - [Parameter(Mandatory = $true)] - [string]$Path, - [switch]$AsOutput) - - Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{ - 'type' = $Type - 'name' = $Name - } -AsOutput:$AsOutput -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-AddBuildTag { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Value, - [switch]$AsOutput) - - Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-AssociateArtifact { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Name, - [Parameter(Mandatory = $true)] - [string]$Path, - [Parameter(Mandatory = $true)] - [string]$Type, - [hashtable]$Properties, - [switch]$AsOutput) - - $p = @{ } - if ($Properties) { - foreach ($key in $Properties.Keys) { - $p[$key] = $Properties[$key] - } - } - - $p['artifactname'] = $Name - $p['artifacttype'] = $Type - Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-LogDetail { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [guid]$Id, - $ParentId, - [string]$Type, - [string]$Name, - $Order, - $StartTime, - $FinishTime, - $Progress, - [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')] - [Parameter()] - $State, - [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')] - [Parameter()] - $Result, - [string]$Message, - [switch]$AsOutput) - - Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{ - 'id' = $Id - 'parentid' = $ParentId - 'type' = $Type - 'name' = $Name - 'order' = $Order - 'starttime' = $StartTime - 'finishtime' = $FinishTime - 'progress' = $Progress - 'state' = $State - 'result' = $Result - } -AsOutput:$AsOutput -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-SetProgress { - [CmdletBinding()] - param( - [ValidateRange(0, 100)] - [Parameter(Mandatory = $true)] - [int]$Percent, - [string]$CurrentOperation, - [switch]$AsOutput) - - Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{ - 'value' = $Percent - } -AsOutput:$AsOutput -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-SetResult { - [CmdletBinding(DefaultParameterSetName = 'AsOutput')] - param( - [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")] - [Parameter(Mandatory = $true)] - [string]$Result, - [string]$Message, - [Parameter(ParameterSetName = 'AsOutput')] - [switch]$AsOutput, - [Parameter(ParameterSetName = 'DoNotThrow')] - [switch]$DoNotThrow) - - Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{ - 'result' = $Result - } -AsOutput:$AsOutput - if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) { - # Special internal exception type to control the flow. Not currently intended - # for public usage and subject to change. - throw (New-Object VstsTaskSdk.TerminationException($Message)) - } -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-SetSecret { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Value, - [switch]$AsOutput) - - Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-SetVariable { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Name, - [string]$Value, - [switch]$Secret, - [switch]$AsOutput) - - Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{ - 'variable' = $Name - 'issecret' = $Secret - } -AsOutput:$AsOutput -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-TaskDebug { - [CmdletBinding()] - param( - [string]$Message, - [switch]$AsOutput) - - Write-TaskDebug_Internal @PSBoundParameters -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-TaskError { - [CmdletBinding()] - param( - [string]$Message, - [string]$ErrCode, - [string]$SourcePath, - [string]$LineNumber, - [string]$ColumnNumber, - [switch]$AsOutput) - - Write-LogIssue -Type error @PSBoundParameters -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-TaskVerbose { - [CmdletBinding()] - param( - [string]$Message, - [switch]$AsOutput) - - Write-TaskDebug_Internal @PSBoundParameters -AsVerbose -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-TaskWarning { - [CmdletBinding()] - param( - [string]$Message, - [string]$ErrCode, - [string]$SourcePath, - [string]$LineNumber, - [string]$ColumnNumber, - [switch]$AsOutput) - - Write-LogIssue -Type warning @PSBoundParameters -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-UpdateBuildNumber { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Value, - [switch]$AsOutput) - - Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-UploadArtifact { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$ContainerFolder, - [Parameter(Mandatory = $true)] - [string]$Name, - [Parameter(Mandatory = $true)] - [string]$Path, - [switch]$AsOutput) - - Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{ - 'containerfolder' = $ContainerFolder - 'artifactname' = $Name - } -AsOutput:$AsOutput -} - -<# -.SYNOPSIS -See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md - -.PARAMETER AsOutput -Indicates whether to write the logging command directly to the host or to the output pipeline. -#> -function Write-UploadBuildLog { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Path, - [switch]$AsOutput) - - Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput -} - -######################################## -# Private functions. -######################################## -function Format-LoggingCommandData { - [CmdletBinding()] - param([string]$Value, [switch]$Reverse) - - if (!$Value) { - return '' - } - - if (!$Reverse) { - foreach ($mapping in $script:loggingCommandEscapeMappings) { - $Value = $Value.Replace($mapping.Token, $mapping.Replacement) - } - } else { - for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) { - $mapping = $script:loggingCommandEscapeMappings[$i] - $Value = $Value.Replace($mapping.Replacement, $mapping.Token) - } - } - - return $Value -} - -function Format-LoggingCommand { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Area, - [Parameter(Mandatory = $true)] - [string]$Event, - [string]$Data, - [hashtable]$Properties) - - # Append the preamble. - [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder - $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event) - - # Append the properties. - if ($Properties) { - $first = $true - foreach ($key in $Properties.Keys) { - [string]$value = Format-LoggingCommandData $Properties[$key] - if ($value) { - if ($first) { - $null = $sb.Append(' ') - $first = $false - } else { - $null = $sb.Append(';') - } - - $null = $sb.Append("$key=$value") - } - } - } - - # Append the tail and output the value. - $Data = Format-LoggingCommandData $Data - $sb.Append(']').Append($Data).ToString() -} - -function Write-LoggingCommand { - [CmdletBinding(DefaultParameterSetName = 'Parameters')] - param( - [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')] - [string]$Area, - [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')] - [string]$Event, - [Parameter(ParameterSetName = 'Parameters')] - [string]$Data, - [Parameter(ParameterSetName = 'Parameters')] - [hashtable]$Properties, - [Parameter(Mandatory = $true, ParameterSetName = 'Object')] - $Command, - [switch]$AsOutput) - - if ($PSCmdlet.ParameterSetName -eq 'Object') { - Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput - return - } - - $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties - if ($AsOutput) { - $command - } else { - Write-Host $command - } -} - -function Write-LogIssue { - [CmdletBinding()] - param( - [ValidateSet('warning', 'error')] - [Parameter(Mandatory = $true)] - [string]$Type, - [string]$Message, - [string]$ErrCode, - [string]$SourcePath, - [string]$LineNumber, - [string]$ColumnNumber, - [switch]$AsOutput) - - $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{ - 'type' = $Type - 'code' = $ErrCode - 'sourcepath' = $SourcePath - 'linenumber' = $LineNumber - 'columnnumber' = $ColumnNumber - } - if ($AsOutput) { - return $command - } - - if ($Type -eq 'error') { - $foregroundColor = $host.PrivateData.ErrorForegroundColor - $backgroundColor = $host.PrivateData.ErrorBackgroundColor - if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) { - $foregroundColor = [System.ConsoleColor]::Red - $backgroundColor = [System.ConsoleColor]::Black - } - } else { - $foregroundColor = $host.PrivateData.WarningForegroundColor - $backgroundColor = $host.PrivateData.WarningBackgroundColor - if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) { - $foregroundColor = [System.ConsoleColor]::Yellow - $backgroundColor = [System.ConsoleColor]::Black - } - } - - Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor -} - -function Write-TaskDebug_Internal { - [CmdletBinding()] - param( - [string]$Message, - [switch]$AsVerbose, - [switch]$AsOutput) - - $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message - if ($AsOutput) { - return $command - } - - if ($AsVerbose) { - $foregroundColor = $host.PrivateData.VerboseForegroundColor - $backgroundColor = $host.PrivateData.VerboseBackgroundColor - if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) { - $foregroundColor = [System.ConsoleColor]::Cyan - $backgroundColor = [System.ConsoleColor]::Black - } - } else { - $foregroundColor = $host.PrivateData.DebugForegroundColor - $backgroundColor = $host.PrivateData.DebugBackgroundColor - if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) { - $foregroundColor = [System.ConsoleColor]::DarkGray - $backgroundColor = [System.ConsoleColor]::Black - } - } - - Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor -} +$script:loggingCommandPrefix = '##vso[' +$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"? + New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' } + New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' } + New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' } +) +# TODO: BUG: Escape ] +# TODO: BUG: Escape % ??? +# TODO: Add test to verify don't need to escape "=". + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-AddAttachment { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Type, + [Parameter(Mandatory = $true)] + [string]$Name, + [Parameter(Mandatory = $true)] + [string]$Path, + [switch]$AsOutput) + + Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{ + 'type' = $Type + 'name' = $Name + } -AsOutput:$AsOutput +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-AddBuildTag { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Value, + [switch]$AsOutput) + + Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-AssociateArtifact { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Name, + [Parameter(Mandatory = $true)] + [string]$Path, + [Parameter(Mandatory = $true)] + [string]$Type, + [hashtable]$Properties, + [switch]$AsOutput) + + $p = @{ } + if ($Properties) { + foreach ($key in $Properties.Keys) { + $p[$key] = $Properties[$key] + } + } + + $p['artifactname'] = $Name + $p['artifacttype'] = $Type + Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-LogDetail { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [guid]$Id, + $ParentId, + [string]$Type, + [string]$Name, + $Order, + $StartTime, + $FinishTime, + $Progress, + [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')] + [Parameter()] + $State, + [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')] + [Parameter()] + $Result, + [string]$Message, + [switch]$AsOutput) + + Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{ + 'id' = $Id + 'parentid' = $ParentId + 'type' = $Type + 'name' = $Name + 'order' = $Order + 'starttime' = $StartTime + 'finishtime' = $FinishTime + 'progress' = $Progress + 'state' = $State + 'result' = $Result + } -AsOutput:$AsOutput +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-SetProgress { + [CmdletBinding()] + param( + [ValidateRange(0, 100)] + [Parameter(Mandatory = $true)] + [int]$Percent, + [string]$CurrentOperation, + [switch]$AsOutput) + + Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{ + 'value' = $Percent + } -AsOutput:$AsOutput +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-SetResult { + [CmdletBinding(DefaultParameterSetName = 'AsOutput')] + param( + [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")] + [Parameter(Mandatory = $true)] + [string]$Result, + [string]$Message, + [Parameter(ParameterSetName = 'AsOutput')] + [switch]$AsOutput, + [Parameter(ParameterSetName = 'DoNotThrow')] + [switch]$DoNotThrow) + + Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{ + 'result' = $Result + } -AsOutput:$AsOutput + if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) { + # Special internal exception type to control the flow. Not currently intended + # for public usage and subject to change. + throw (New-Object VstsTaskSdk.TerminationException($Message)) + } +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-SetSecret { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Value, + [switch]$AsOutput) + + Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-SetVariable { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Name, + [string]$Value, + [switch]$Secret, + [switch]$AsOutput) + + Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{ + 'variable' = $Name + 'issecret' = $Secret + } -AsOutput:$AsOutput +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-TaskDebug { + [CmdletBinding()] + param( + [string]$Message, + [switch]$AsOutput) + + Write-TaskDebug_Internal @PSBoundParameters +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-TaskError { + [CmdletBinding()] + param( + [string]$Message, + [string]$ErrCode, + [string]$SourcePath, + [string]$LineNumber, + [string]$ColumnNumber, + [switch]$AsOutput) + + Write-LogIssue -Type error @PSBoundParameters +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-TaskVerbose { + [CmdletBinding()] + param( + [string]$Message, + [switch]$AsOutput) + + Write-TaskDebug_Internal @PSBoundParameters -AsVerbose +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-TaskWarning { + [CmdletBinding()] + param( + [string]$Message, + [string]$ErrCode, + [string]$SourcePath, + [string]$LineNumber, + [string]$ColumnNumber, + [switch]$AsOutput) + + Write-LogIssue -Type warning @PSBoundParameters +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-UpdateBuildNumber { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Value, + [switch]$AsOutput) + + Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-UploadArtifact { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$ContainerFolder, + [Parameter(Mandatory = $true)] + [string]$Name, + [Parameter(Mandatory = $true)] + [string]$Path, + [switch]$AsOutput) + + Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{ + 'containerfolder' = $ContainerFolder + 'artifactname' = $Name + } -AsOutput:$AsOutput +} + +<# +.SYNOPSIS +See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md + +.PARAMETER AsOutput +Indicates whether to write the logging command directly to the host or to the output pipeline. +#> +function Write-UploadBuildLog { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Path, + [switch]$AsOutput) + + Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput +} + +######################################## +# Private functions. +######################################## +function Format-LoggingCommandData { + [CmdletBinding()] + param([string]$Value, [switch]$Reverse) + + if (!$Value) { + return '' + } + + if (!$Reverse) { + foreach ($mapping in $script:loggingCommandEscapeMappings) { + $Value = $Value.Replace($mapping.Token, $mapping.Replacement) + } + } else { + for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) { + $mapping = $script:loggingCommandEscapeMappings[$i] + $Value = $Value.Replace($mapping.Replacement, $mapping.Token) + } + } + + return $Value +} + +function Format-LoggingCommand { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Area, + [Parameter(Mandatory = $true)] + [string]$Event, + [string]$Data, + [hashtable]$Properties) + + # Append the preamble. + [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder + $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event) + + # Append the properties. + if ($Properties) { + $first = $true + foreach ($key in $Properties.Keys) { + [string]$value = Format-LoggingCommandData $Properties[$key] + if ($value) { + if ($first) { + $null = $sb.Append(' ') + $first = $false + } else { + $null = $sb.Append(';') + } + + $null = $sb.Append("$key=$value") + } + } + } + + # Append the tail and output the value. + $Data = Format-LoggingCommandData $Data + $sb.Append(']').Append($Data).ToString() +} + +function Write-LoggingCommand { + [CmdletBinding(DefaultParameterSetName = 'Parameters')] + param( + [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')] + [string]$Area, + [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')] + [string]$Event, + [Parameter(ParameterSetName = 'Parameters')] + [string]$Data, + [Parameter(ParameterSetName = 'Parameters')] + [hashtable]$Properties, + [Parameter(Mandatory = $true, ParameterSetName = 'Object')] + $Command, + [switch]$AsOutput) + + if ($PSCmdlet.ParameterSetName -eq 'Object') { + Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput + return + } + + $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties + if ($AsOutput) { + $command + } else { + Write-Host $command + } +} + +function Write-LogIssue { + [CmdletBinding()] + param( + [ValidateSet('warning', 'error')] + [Parameter(Mandatory = $true)] + [string]$Type, + [string]$Message, + [string]$ErrCode, + [string]$SourcePath, + [string]$LineNumber, + [string]$ColumnNumber, + [switch]$AsOutput) + + $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{ + 'type' = $Type + 'code' = $ErrCode + 'sourcepath' = $SourcePath + 'linenumber' = $LineNumber + 'columnnumber' = $ColumnNumber + } + if ($AsOutput) { + return $command + } + + if ($Type -eq 'error') { + $foregroundColor = $host.PrivateData.ErrorForegroundColor + $backgroundColor = $host.PrivateData.ErrorBackgroundColor + if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) { + $foregroundColor = [System.ConsoleColor]::Red + $backgroundColor = [System.ConsoleColor]::Black + } + } else { + $foregroundColor = $host.PrivateData.WarningForegroundColor + $backgroundColor = $host.PrivateData.WarningBackgroundColor + if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) { + $foregroundColor = [System.ConsoleColor]::Yellow + $backgroundColor = [System.ConsoleColor]::Black + } + } + + Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor +} + +function Write-TaskDebug_Internal { + [CmdletBinding()] + param( + [string]$Message, + [switch]$AsVerbose, + [switch]$AsOutput) + + $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message + if ($AsOutput) { + return $command + } + + if ($AsVerbose) { + $foregroundColor = $host.PrivateData.VerboseForegroundColor + $backgroundColor = $host.PrivateData.VerboseBackgroundColor + if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) { + $foregroundColor = [System.ConsoleColor]::Cyan + $backgroundColor = [System.ConsoleColor]::Black + } + } else { + $foregroundColor = $host.PrivateData.DebugForegroundColor + $backgroundColor = $host.PrivateData.DebugBackgroundColor + if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) { + $foregroundColor = [System.ConsoleColor]::DarkGray + $backgroundColor = [System.ConsoleColor]::Black + } + } + + Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor +} diff --git a/VersionAssemblies/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/src/VersionAssemblies/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 similarity index 97% rename from VersionAssemblies/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 rename to src/VersionAssemblies/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 index 5fc2f8a..f81e377 100644 --- a/VersionAssemblies/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 +++ b/src/VersionAssemblies/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 @@ -1,368 +1,368 @@ -######################################## -# Private functions. -######################################## -function ConvertFrom-LongFormPath { - [CmdletBinding()] - param([string]$Path) - - if ($Path) { - if ($Path.StartsWith('\\?\UNC')) { - # E.g. \\?\UNC\server\share -> \\server\share - return $Path.Substring(1, '\?\UNC'.Length) - } elseif ($Path.StartsWith('\\?\')) { - # E.g. \\?\C:\directory -> C:\directory - return $Path.Substring('\\?\'.Length) - } - } - - return $Path -} -function ConvertTo-LongFormPath { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Path) - - [string]$longFormPath = Get-FullNormalizedPath -Path $Path - if ($longFormPath -and !$longFormPath.StartsWith('\\?')) { - if ($longFormPath.StartsWith('\\')) { - # E.g. \\server\share -> \\?\UNC\server\share - return "\\?\UNC$($longFormPath.Substring(1))" - } else { - # E.g. C:\directory -> \\?\C:\directory - return "\\?\$longFormPath" - } - } - - return $longFormPath -} - -# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS. -function Get-DirectoryChildItem { - [CmdletBinding()] - param( - [string]$Path, - [ValidateNotNullOrEmpty()] - [Parameter()] - [string]$Filter = "*", - [switch]$Force, - [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch, - [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic, - [switch]$Recurse) - - $stackOfDirectoryQueues = New-Object System.Collections.Stack - while ($true) { - $directoryQueue = New-Object System.Collections.Queue - $fileQueue = New-Object System.Collections.Queue - $findData = New-Object VstsTaskSdk.FS.FindData - $longFormPath = (ConvertTo-LongFormPath $Path) - $handle = $null - try { - $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx( - [System.IO.Path]::Combine($longFormPath, $Filter), - $InfoLevel, - $findData, - [VstsTaskSdk.FS.FindSearchOps]::NameMatch, - [System.IntPtr]::Zero, - $Flags) - if (!$handle.IsInvalid) { - while ($true) { - if ($findData.fileName -notin '.', '..') { - $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes - # If the item is hidden, check if $Force is specified. - if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) { - # Create the item. - $item = New-Object -TypeName psobject -Property @{ - 'Attributes' = $attributes - 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName))) - 'Name' = $findData.fileName - } - # Output directories immediately. - if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) { - $item - # Append to the directory queue if recursive and default filter. - if ($Recurse -and $Filter -eq '*') { - $directoryQueue.Enqueue($item) - } - } else { - # Hold the files until all directories have been output. - $fileQueue.Enqueue($item) - } - } - } - - if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break } - - if ($handle.IsInvalid) { - throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @( - [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() - Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path - )) - } - } - } - } finally { - if ($handle -ne $null) { $handle.Dispose() } - } - - # If recursive and non-default filter, queue child directories. - if ($Recurse -and $Filter -ne '*') { - $findData = New-Object VstsTaskSdk.FS.FindData - $handle = $null - try { - $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx( - [System.IO.Path]::Combine($longFormPath, '*'), - [VstsTaskSdk.FS.FindInfoLevel]::Basic, - $findData, - [VstsTaskSdk.FS.FindSearchOps]::NameMatch, - [System.IntPtr]::Zero, - $Flags) - if (!$handle.IsInvalid) { - while ($true) { - if ($findData.fileName -notin '.', '..') { - $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes - # If the item is hidden, check if $Force is specified. - if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) { - # Collect directories only. - if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) { - # Create the item. - $item = New-Object -TypeName psobject -Property @{ - 'Attributes' = $attributes - 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName))) - 'Name' = $findData.fileName - } - $directoryQueue.Enqueue($item) - } - } - } - - if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break } - - if ($handle.IsInvalid) { - throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @( - [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() - Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path - )) - } - } - } - } finally { - if ($handle -ne $null) { $handle.Dispose() } - } - } - - # Output the files. - $fileQueue - - # Push the directory queue onto the stack if any directories were found. - if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) } - - # Break out of the loop if no more directory queues to process. - if (!$stackOfDirectoryQueues.Count) { break } - - # Get the next path. - $directoryQueue = $stackOfDirectoryQueues.Peek() - $Path = $directoryQueue.Dequeue().FullName - - # Pop the directory queue if it's empty. - if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() } - } -} - -function Get-FullNormalizedPath { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$Path) - - [string]$outPath = $Path - [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null) - [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() - if ($bufferSize -gt 0) { - $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize) - [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null) - $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() - if ($length -gt 0) { - $outPath = $absolutePath.ToString() - } else { - throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @( - $lastWin32Error - Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path - )) - } - } else { - throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @( - $lastWin32Error - Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path - )) - } - - if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) { - $outPath = $outPath.TrimEnd('\') - } - - $outPath -} - -######################################## -# Types. -######################################## -# If the type has already been loaded once, then it is not loaded again. -Write-Verbose "Adding long path native methods." -Add-Type -Debug:$false -TypeDefinition @' -namespace VstsTaskSdk.FS -{ - using System; - using System.Runtime.InteropServices; - - public static class NativeMethods - { - private const string Kernel32Dll = "kernel32.dll"; - - [DllImport(Kernel32Dll, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool FindClose(IntPtr hFindFile); - - // HANDLE WINAPI FindFirstFile( - // _In_ LPCTSTR lpFileName, - // _Out_ LPWIN32_FIND_DATA lpFindFileData - // ); - [DllImport(Kernel32Dll, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)] - public static extern SafeFindHandle FindFirstFile( - [MarshalAs(UnmanagedType.LPTStr)] - string fileName, - [In, Out] FindData findFileData - ); - - //HANDLE WINAPI FindFirstFileEx( - // _In_ LPCTSTR lpFileName, - // _In_ FINDEX_INFO_LEVELS fInfoLevelId, - // _Out_ LPVOID lpFindFileData, - // _In_ FINDEX_SEARCH_OPS fSearchOp, - // _Reserved_ LPVOID lpSearchFilter, - // _In_ DWORD dwAdditionalFlags - //); - [DllImport(Kernel32Dll, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)] - public static extern SafeFindHandle FindFirstFileEx( - [MarshalAs(UnmanagedType.LPTStr)] - string fileName, - [In] FindInfoLevel fInfoLevelId, - [In, Out] FindData lpFindFileData, - [In] FindSearchOps fSearchOp, - IntPtr lpSearchFilter, - [In] FindFlags dwAdditionalFlags - ); - - [DllImport(Kernel32Dll, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool FindNextFile(SafeFindHandle hFindFile, [In, Out] FindData lpFindFileData); - - [DllImport(Kernel32Dll, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)] - public static extern int GetFileAttributes(string lpFileName); - - [DllImport(Kernel32Dll, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)] - public static extern uint GetFullPathName( - [MarshalAs(UnmanagedType.LPTStr)] - string lpFileName, - uint nBufferLength, - [Out] - System.Text.StringBuilder lpBuffer, - System.Text.StringBuilder lpFilePart - ); - } - - //for mapping to the WIN32_FIND_DATA native structure - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public sealed class FindData - { - // NOTE: - // Although it may seem correct to Marshal the string members of this class as UnmanagedType.LPWStr, they - // must explicitly remain UnmanagedType.ByValTStr with the size constraints noted. Otherwise we end up with - // COM Interop exceptions while trying to marshal the data across the PInvoke boundaries. - public int fileAttributes; - public System.Runtime.InteropServices.ComTypes.FILETIME creationTime; - public System.Runtime.InteropServices.ComTypes.FILETIME lastAccessTime; - public System.Runtime.InteropServices.ComTypes.FILETIME lastWriteTime; - public int nFileSizeHigh; - public int nFileSizeLow; - public int dwReserved0; - public int dwReserved1; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] - public string fileName; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)] - public string alternateFileName; - } - - //A Win32 safe find handle in which a return value of -1 indicates it's invalid - public sealed class SafeFindHandle : Microsoft.Win32.SafeHandles.SafeHandleMinusOneIsInvalid - { - public SafeFindHandle() - : base(true) - { - return; - } - - [System.Runtime.ConstrainedExecution.ReliabilityContract(System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState, System.Runtime.ConstrainedExecution.Cer.Success)] - protected override bool ReleaseHandle() - { - return NativeMethods.FindClose(handle); - } - } - - // Refer https://msdn.microsoft.com/en-us/library/windows/desktop/gg258117(v=vs.85).aspx - [Flags] - public enum Attributes : uint - { - None = 0x00000000, - Readonly = 0x00000001, - Hidden = 0x00000002, - System = 0x00000004, - Directory = 0x00000010, - Archive = 0x00000020, - Device = 0x00000040, - Normal = 0x00000080, - Temporary = 0x00000100, - SparseFile = 0x00000200, - ReparsePoint = 0x00000400, - Compressed = 0x00000800, - Offline = 0x00001000, - NotContentIndexed = 0x00002000, - Encrypted = 0x00004000, - IntegrityStream = 0x00008000, - Virtual = 0x00010000, - NoScrubData = 0x00020000, - Write_Through = 0x80000000, - Overlapped = 0x40000000, - NoBuffering = 0x20000000, - RandomAccess = 0x10000000, - SequentialScan = 0x08000000, - DeleteOnClose = 0x04000000, - BackupSemantics = 0x02000000, - PosixSemantics = 0x01000000, - OpenReparsePoint = 0x00200000, - OpenNoRecall = 0x00100000, - FirstPipeInstance = 0x00080000 - } - - [Flags] - public enum FindFlags - { - None = 0, - CaseSensitive = 1, - LargeFetch = 2, - } - - public enum FindInfoLevel - { - Standard = 0, - Basic = 1, - } - - public enum FindSearchOps - { - NameMatch = 0, - LimitToDirectories = 1, - LimitToDevices = 2, - } -} -'@ +######################################## +# Private functions. +######################################## +function ConvertFrom-LongFormPath { + [CmdletBinding()] + param([string]$Path) + + if ($Path) { + if ($Path.StartsWith('\\?\UNC')) { + # E.g. \\?\UNC\server\share -> \\server\share + return $Path.Substring(1, '\?\UNC'.Length) + } elseif ($Path.StartsWith('\\?\')) { + # E.g. \\?\C:\directory -> C:\directory + return $Path.Substring('\\?\'.Length) + } + } + + return $Path +} +function ConvertTo-LongFormPath { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Path) + + [string]$longFormPath = Get-FullNormalizedPath -Path $Path + if ($longFormPath -and !$longFormPath.StartsWith('\\?')) { + if ($longFormPath.StartsWith('\\')) { + # E.g. \\server\share -> \\?\UNC\server\share + return "\\?\UNC$($longFormPath.Substring(1))" + } else { + # E.g. C:\directory -> \\?\C:\directory + return "\\?\$longFormPath" + } + } + + return $longFormPath +} + +# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS. +function Get-DirectoryChildItem { + [CmdletBinding()] + param( + [string]$Path, + [ValidateNotNullOrEmpty()] + [Parameter()] + [string]$Filter = "*", + [switch]$Force, + [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch, + [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic, + [switch]$Recurse) + + $stackOfDirectoryQueues = New-Object System.Collections.Stack + while ($true) { + $directoryQueue = New-Object System.Collections.Queue + $fileQueue = New-Object System.Collections.Queue + $findData = New-Object VstsTaskSdk.FS.FindData + $longFormPath = (ConvertTo-LongFormPath $Path) + $handle = $null + try { + $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx( + [System.IO.Path]::Combine($longFormPath, $Filter), + $InfoLevel, + $findData, + [VstsTaskSdk.FS.FindSearchOps]::NameMatch, + [System.IntPtr]::Zero, + $Flags) + if (!$handle.IsInvalid) { + while ($true) { + if ($findData.fileName -notin '.', '..') { + $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes + # If the item is hidden, check if $Force is specified. + if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) { + # Create the item. + $item = New-Object -TypeName psobject -Property @{ + 'Attributes' = $attributes + 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName))) + 'Name' = $findData.fileName + } + # Output directories immediately. + if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) { + $item + # Append to the directory queue if recursive and default filter. + if ($Recurse -and $Filter -eq '*') { + $directoryQueue.Enqueue($item) + } + } else { + # Hold the files until all directories have been output. + $fileQueue.Enqueue($item) + } + } + } + + if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break } + + if ($handle.IsInvalid) { + throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @( + [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() + Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path + )) + } + } + } + } finally { + if ($handle -ne $null) { $handle.Dispose() } + } + + # If recursive and non-default filter, queue child directories. + if ($Recurse -and $Filter -ne '*') { + $findData = New-Object VstsTaskSdk.FS.FindData + $handle = $null + try { + $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx( + [System.IO.Path]::Combine($longFormPath, '*'), + [VstsTaskSdk.FS.FindInfoLevel]::Basic, + $findData, + [VstsTaskSdk.FS.FindSearchOps]::NameMatch, + [System.IntPtr]::Zero, + $Flags) + if (!$handle.IsInvalid) { + while ($true) { + if ($findData.fileName -notin '.', '..') { + $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes + # If the item is hidden, check if $Force is specified. + if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) { + # Collect directories only. + if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) { + # Create the item. + $item = New-Object -TypeName psobject -Property @{ + 'Attributes' = $attributes + 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName))) + 'Name' = $findData.fileName + } + $directoryQueue.Enqueue($item) + } + } + } + + if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break } + + if ($handle.IsInvalid) { + throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @( + [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() + Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path + )) + } + } + } + } finally { + if ($handle -ne $null) { $handle.Dispose() } + } + } + + # Output the files. + $fileQueue + + # Push the directory queue onto the stack if any directories were found. + if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) } + + # Break out of the loop if no more directory queues to process. + if (!$stackOfDirectoryQueues.Count) { break } + + # Get the next path. + $directoryQueue = $stackOfDirectoryQueues.Peek() + $Path = $directoryQueue.Dequeue().FullName + + # Pop the directory queue if it's empty. + if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() } + } +} + +function Get-FullNormalizedPath { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Path) + + [string]$outPath = $Path + [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null) + [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() + if ($bufferSize -gt 0) { + $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize) + [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null) + $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() + if ($length -gt 0) { + $outPath = $absolutePath.ToString() + } else { + throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @( + $lastWin32Error + Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path + )) + } + } else { + throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @( + $lastWin32Error + Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path + )) + } + + if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) { + $outPath = $outPath.TrimEnd('\') + } + + $outPath +} + +######################################## +# Types. +######################################## +# If the type has already been loaded once, then it is not loaded again. +Write-Verbose "Adding long path native methods." +Add-Type -Debug:$false -TypeDefinition @' +namespace VstsTaskSdk.FS +{ + using System; + using System.Runtime.InteropServices; + + public static class NativeMethods + { + private const string Kernel32Dll = "kernel32.dll"; + + [DllImport(Kernel32Dll, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool FindClose(IntPtr hFindFile); + + // HANDLE WINAPI FindFirstFile( + // _In_ LPCTSTR lpFileName, + // _Out_ LPWIN32_FIND_DATA lpFindFileData + // ); + [DllImport(Kernel32Dll, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)] + public static extern SafeFindHandle FindFirstFile( + [MarshalAs(UnmanagedType.LPTStr)] + string fileName, + [In, Out] FindData findFileData + ); + + //HANDLE WINAPI FindFirstFileEx( + // _In_ LPCTSTR lpFileName, + // _In_ FINDEX_INFO_LEVELS fInfoLevelId, + // _Out_ LPVOID lpFindFileData, + // _In_ FINDEX_SEARCH_OPS fSearchOp, + // _Reserved_ LPVOID lpSearchFilter, + // _In_ DWORD dwAdditionalFlags + //); + [DllImport(Kernel32Dll, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)] + public static extern SafeFindHandle FindFirstFileEx( + [MarshalAs(UnmanagedType.LPTStr)] + string fileName, + [In] FindInfoLevel fInfoLevelId, + [In, Out] FindData lpFindFileData, + [In] FindSearchOps fSearchOp, + IntPtr lpSearchFilter, + [In] FindFlags dwAdditionalFlags + ); + + [DllImport(Kernel32Dll, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool FindNextFile(SafeFindHandle hFindFile, [In, Out] FindData lpFindFileData); + + [DllImport(Kernel32Dll, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)] + public static extern int GetFileAttributes(string lpFileName); + + [DllImport(Kernel32Dll, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)] + public static extern uint GetFullPathName( + [MarshalAs(UnmanagedType.LPTStr)] + string lpFileName, + uint nBufferLength, + [Out] + System.Text.StringBuilder lpBuffer, + System.Text.StringBuilder lpFilePart + ); + } + + //for mapping to the WIN32_FIND_DATA native structure + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public sealed class FindData + { + // NOTE: + // Although it may seem correct to Marshal the string members of this class as UnmanagedType.LPWStr, they + // must explicitly remain UnmanagedType.ByValTStr with the size constraints noted. Otherwise we end up with + // COM Interop exceptions while trying to marshal the data across the PInvoke boundaries. + public int fileAttributes; + public System.Runtime.InteropServices.ComTypes.FILETIME creationTime; + public System.Runtime.InteropServices.ComTypes.FILETIME lastAccessTime; + public System.Runtime.InteropServices.ComTypes.FILETIME lastWriteTime; + public int nFileSizeHigh; + public int nFileSizeLow; + public int dwReserved0; + public int dwReserved1; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] + public string fileName; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)] + public string alternateFileName; + } + + //A Win32 safe find handle in which a return value of -1 indicates it's invalid + public sealed class SafeFindHandle : Microsoft.Win32.SafeHandles.SafeHandleMinusOneIsInvalid + { + public SafeFindHandle() + : base(true) + { + return; + } + + [System.Runtime.ConstrainedExecution.ReliabilityContract(System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState, System.Runtime.ConstrainedExecution.Cer.Success)] + protected override bool ReleaseHandle() + { + return NativeMethods.FindClose(handle); + } + } + + // Refer https://msdn.microsoft.com/en-us/library/windows/desktop/gg258117(v=vs.85).aspx + [Flags] + public enum Attributes : uint + { + None = 0x00000000, + Readonly = 0x00000001, + Hidden = 0x00000002, + System = 0x00000004, + Directory = 0x00000010, + Archive = 0x00000020, + Device = 0x00000040, + Normal = 0x00000080, + Temporary = 0x00000100, + SparseFile = 0x00000200, + ReparsePoint = 0x00000400, + Compressed = 0x00000800, + Offline = 0x00001000, + NotContentIndexed = 0x00002000, + Encrypted = 0x00004000, + IntegrityStream = 0x00008000, + Virtual = 0x00010000, + NoScrubData = 0x00020000, + Write_Through = 0x80000000, + Overlapped = 0x40000000, + NoBuffering = 0x20000000, + RandomAccess = 0x10000000, + SequentialScan = 0x08000000, + DeleteOnClose = 0x04000000, + BackupSemantics = 0x02000000, + PosixSemantics = 0x01000000, + OpenReparsePoint = 0x00200000, + OpenNoRecall = 0x00100000, + FirstPipeInstance = 0x00080000 + } + + [Flags] + public enum FindFlags + { + None = 0, + CaseSensitive = 1, + LargeFetch = 2, + } + + public enum FindInfoLevel + { + Standard = 0, + Basic = 1, + } + + public enum FindSearchOps + { + NameMatch = 0, + LimitToDirectories = 1, + LimitToDevices = 2, + } +} +'@ diff --git a/VersionAssemblies/ps_modules/VstsTaskSdk/Minimatch.dll b/src/VersionAssemblies/ps_modules/VstsTaskSdk/Minimatch.dll similarity index 100% rename from VersionAssemblies/ps_modules/VstsTaskSdk/Minimatch.dll rename to src/VersionAssemblies/ps_modules/VstsTaskSdk/Minimatch.dll diff --git a/VersionAssemblies/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/src/VersionAssemblies/ps_modules/VstsTaskSdk/OutFunctions.ps1 similarity index 97% rename from VersionAssemblies/ps_modules/VstsTaskSdk/OutFunctions.ps1 rename to src/VersionAssemblies/ps_modules/VstsTaskSdk/OutFunctions.ps1 index 0be1fe2..79b5f45 100644 --- a/VersionAssemblies/ps_modules/VstsTaskSdk/OutFunctions.ps1 +++ b/src/VersionAssemblies/ps_modules/VstsTaskSdk/OutFunctions.ps1 @@ -1,79 +1,79 @@ -# TODO: It would be better if the Out-Default function resolved the underlying Out-Default -# command in the begin block. This would allow for supporting other modules that override -# Out-Default. -$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default") - -######################################## -# Public functions. -######################################## -function Out-Default { - [CmdletBinding(ConfirmImpact = "Medium")] - param( - [Parameter(ValueFromPipeline = $true)] - [System.Management.Automation.PSObject]$InputObject) - - begin { - #Write-Host '[Entering Begin Out-Default]' - $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline() - $__sp.Begin($pscmdlet) - #Write-Host '[Leaving Begin Out-Default]' - } - - process { - #Write-Host '[Entering Process Out-Default]' - if ($_ -is [System.Management.Automation.ErrorRecord]) { - Write-Verbose -Message 'Error record:' 4>&1 | Out-Default - Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default - Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default - Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default - Write-Verbose -Message 'Exception:' 4>&1 | Out-Default - Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default - Write-TaskError -Message $_.Exception.Message - } elseif ($_ -is [System.Management.Automation.WarningRecord]) { - Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) - } elseif ($_ -is [System.Management.Automation.VerboseRecord]) { - foreach ($private:str in (Format-DebugMessage -Object $_)) { - Write-TaskVerbose -Message $private:str - } - } elseif ($_ -is [System.Management.Automation.DebugRecord]) { - foreach ($private:str in (Format-DebugMessage -Object $_)) { - Write-TaskDebug -Message $private:str - } - } else { -# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking. - $__sp.Process($_) - } - - #Write-Host '[Leaving Process Out-Default]' - } - - end { - #Write-Host '[Entering End Out-Default]' - $__sp.End() - #Write-Host '[Leaving End Out-Default]' - } -} - -######################################## -# Private functions. -######################################## -function Format-DebugMessage { - [CmdletBinding()] - param([psobject]$Object) - - $private:str = Out-String -InputObject $Object -Width 2147483647 - $private:str = Remove-TrailingNewLine $private:str - "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0]) -} - -function Remove-TrailingNewLine { - [CmdletBinding()] - param($Str) - if ([object]::ReferenceEquals($Str, $null)) { - return $Str - } elseif ($Str.EndsWith("`r`n")) { - return $Str.Substring(0, $Str.Length - 2) - } else { - return $Str - } -} +# TODO: It would be better if the Out-Default function resolved the underlying Out-Default +# command in the begin block. This would allow for supporting other modules that override +# Out-Default. +$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default") + +######################################## +# Public functions. +######################################## +function Out-Default { + [CmdletBinding(ConfirmImpact = "Medium")] + param( + [Parameter(ValueFromPipeline = $true)] + [System.Management.Automation.PSObject]$InputObject) + + begin { + #Write-Host '[Entering Begin Out-Default]' + $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline() + $__sp.Begin($pscmdlet) + #Write-Host '[Leaving Begin Out-Default]' + } + + process { + #Write-Host '[Entering Process Out-Default]' + if ($_ -is [System.Management.Automation.ErrorRecord]) { + Write-Verbose -Message 'Error record:' 4>&1 | Out-Default + Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default + Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default + Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default + Write-Verbose -Message 'Exception:' 4>&1 | Out-Default + Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default + Write-TaskError -Message $_.Exception.Message + } elseif ($_ -is [System.Management.Automation.WarningRecord]) { + Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) + } elseif ($_ -is [System.Management.Automation.VerboseRecord]) { + foreach ($private:str in (Format-DebugMessage -Object $_)) { + Write-TaskVerbose -Message $private:str + } + } elseif ($_ -is [System.Management.Automation.DebugRecord]) { + foreach ($private:str in (Format-DebugMessage -Object $_)) { + Write-TaskDebug -Message $private:str + } + } else { +# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking. + $__sp.Process($_) + } + + #Write-Host '[Leaving Process Out-Default]' + } + + end { + #Write-Host '[Entering End Out-Default]' + $__sp.End() + #Write-Host '[Leaving End Out-Default]' + } +} + +######################################## +# Private functions. +######################################## +function Format-DebugMessage { + [CmdletBinding()] + param([psobject]$Object) + + $private:str = Out-String -InputObject $Object -Width 2147483647 + $private:str = Remove-TrailingNewLine $private:str + "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0]) +} + +function Remove-TrailingNewLine { + [CmdletBinding()] + param($Str) + if ([object]::ReferenceEquals($Str, $null)) { + return $Str + } elseif ($Str.EndsWith("`r`n")) { + return $Str.Substring(0, $Str.Length - 2) + } else { + return $Str + } +} diff --git a/ShowVariables/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/src/VersionAssemblies/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 similarity index 97% rename from ShowVariables/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 rename to src/VersionAssemblies/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 index d2b8f6e..94832ae 100644 --- a/ShowVariables/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 +++ b/src/VersionAssemblies/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 @@ -1,549 +1,549 @@ -<# -.SYNOPSIS -Gets assembly reference information. - -.DESCRIPTION -Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK. - -Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario. - -Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted. - -See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task. - -.PARAMETER LiteralPath -Assembly to walk. - -.EXAMPLE -Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll -#> -function Get-AssemblyReference { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$LiteralPath) - - $ErrorActionPreference = 'Stop' - Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK." - Write-Output '' - Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario." - $directory = [System.IO.Path]::GetDirectoryName($LiteralPath) - $hashtable = @{ } - $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() ) - while ($queue.Count) { - # Add a blank line between assemblies. - Write-Output '' - - # Pop. - $assemblyName = $queue[0] - $queue = @( $queue | Select-Object -Skip 1 ) - - # Attempt to find the assembly in the same directory. - $assembly = $null - $path = "$directory\$($assemblyName.Name).dll" - if ((Test-Path -LiteralPath $path -PathType Leaf)) { - $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path) - } else { - $path = "$directory\$($assemblyName.Name).exe" - if ((Test-Path -LiteralPath $path -PathType Leaf)) { - $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path) - } - } - - # Make sure the assembly full name matches, not just the file name. - if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) { - $assembly = $null - } - - # Print the assembly. - if ($assembly) { - Write-Output $assemblyName.FullName - } else { - if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') { - Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself." - } else { - Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***" - } - - continue - } - - # Walk the references. - $refAssemblyNames = @( $assembly.GetReferencedAssemblies() ) - for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) { - $refAssemblyName = $refAssemblyNames[$i] - - # Skip framework assemblies. - $fxPaths = @( - "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll" - "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll" - ) - $fxPath = $fxPaths | - Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } | - Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName } - if ($fxPath) { - continue - } - - # Print the reference. - Write-Output " $($refAssemblyName.FullName)" - - # Add new references to the queue. - if (!$hashtable[$refAssemblyName.FullName]) { - $queue += $refAssemblyName - $hashtable[$refAssemblyName.FullName] = $true - } - } - } -} - -<# -.SYNOPSIS -Gets a credentials object that can be used with the TFS extended client SDK. - -.DESCRIPTION -The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity). - -Refer to Get-VstsTfsService for a more simple to get a TFS service object. - -*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task. - -.PARAMETER OMDirectory -Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory. - -If not specified, defaults to the directory of the entry script for the task. - -*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task. - -.EXAMPLE -# -# Refer to Get-VstsTfsService for a more simple way to get a TFS service object. -# -$credentials = Get-VstsTfsClientCredentials -Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll" -$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection( - (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require), - $credentials) -$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer]) -$versionControlServer.GetItems('$/*').Items | Format-List -#> -function Get-TfsClientCredentials { - [CmdletBinding()] - param([string]$OMDirectory) - - Trace-EnteringInvocation -InvocationInfo $MyInvocation - $originalErrorActionPreference = $ErrorActionPreference - try { - $ErrorActionPreference = 'Stop' - - # Get the endpoint. - $endpoint = Get-Endpoint -Name SystemVssConnection -Require - - # Validate the type can be found. - $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require - - # Construct the credentials. - $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials. - $credentials.AllowInteractive = $false - $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken) - return $credentials - } catch { - $ErrorActionPreference = $originalErrorActionPreference - Write-Error $_ - } finally { - Trace-LeavingInvocation -InvocationInfo $MyInvocation - } -} - -<# -.SYNOPSIS -Gets a TFS extended client service. - -.DESCRIPTION -Gets an instance of an ITfsTeamProjectCollectionObject. - -*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task. - -.PARAMETER TypeName -Namespace-qualified type name of the service to get. - -.PARAMETER OMDirectory -Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory. - -If not specified, defaults to the directory of the entry script for the task. - -*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task. - -.PARAMETER Uri -URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri. - -.PARAMETER TfsClientCredentials -Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity). - -.EXAMPLE -$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer -$versionControlServer.GetItems('$/*').Items | Format-List -#> -function Get-TfsService { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$TypeName, - - [string]$OMDirectory, - - [string]$Uri, - - $TfsClientCredentials) - - Trace-EnteringInvocation -InvocationInfo $MyInvocation - $originalErrorActionPreference = $ErrorActionPreference - try { - $ErrorActionPreference = 'Stop' - - # Default the URI to the collection URI. - if (!$Uri) { - $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require - } - - # Default the credentials. - if (!$TfsClientCredentials) { - $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory - } - - # Validate the project collection type can be loaded. - $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require - - # Load the project collection object. - $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials) - - # Validate the requested type can be loaded. - $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require - - # Return the service object. - return $tfsTeamProjectCollection.GetService($type) - } catch { - $ErrorActionPreference = $originalErrorActionPreference - Write-Error $_ - } finally { - Trace-LeavingInvocation -InvocationInfo $MyInvocation - } -} - -<# -.SYNOPSIS -Gets a credentials object that can be used with the VSTS REST SDK. - -.DESCRIPTION -The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity). - -Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client. - -*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task. - -.PARAMETER OMDirectory -Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory. - -If not specified, defaults to the directory of the entry script for the task. - -*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task. - -.EXAMPLE -# -# Refer to Get-VstsTfsService for a more simple way to get a TFS service object. -# -# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding -# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient -# to avoid managing the binding redirect. -# -$vssCredentials = Get-VstsVssCredentials -$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require)) -Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll" -$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials) -$projectHttpClient.GetProjects().Result -#> -function Get-VssCredentials { - [CmdletBinding()] - param([string]$OMDirectory) - - Trace-EnteringInvocation -InvocationInfo $MyInvocation - $originalErrorActionPreference = $ErrorActionPreference - try { - $ErrorActionPreference = 'Stop' - - # Get the endpoint. - $endpoint = Get-Endpoint -Name SystemVssConnection -Require - - # Check if the VssOAuthAccessTokenCredential type is available. - if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) { - # Create the federated credential. - $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken) - } else { - # Validate the fallback type can be loaded. - $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require - - # Create the federated credential. - $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken) - } - - # Return the credentials. - return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials( - (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials. - $federatedCredential, - [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt) - } catch { - $ErrorActionPreference = $originalErrorActionPreference - Write-Error $_ - } finally { - Trace-LeavingInvocation -InvocationInfo $MyInvocation - } -} - -<# -.SYNOPSIS -Gets a VSS HTTP client. - -.DESCRIPTION -Gets an instance of an VSS HTTP client. - -*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task. - -.PARAMETER TypeName -Namespace-qualified type name of the HTTP client to get. - -.PARAMETER OMDirectory -Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory. - -If not specified, defaults to the directory of the entry script for the task. - -*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task. - -# .PARAMETER Uri -# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri. - -# .PARAMETER VssCredentials -# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity). - -.EXAMPLE -$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient -$projectHttpClient.GetProjects().Result -#> -function Get-VssHttpClient { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$TypeName, - - [string]$OMDirectory, - - [string]$Uri, - - $VssCredentials) - - Trace-EnteringInvocation -InvocationInfo $MyInvocation - $originalErrorActionPreference = $ErrorActionPreference - try { - $ErrorActionPreference = 'Stop' - - # Default the URI to the collection URI. - if (!$Uri) { - $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require - } - - # Cast the URI. - [uri]$Uri = New-Object System.Uri($Uri) - - # Default the credentials. - if (!$VssCredentials) { - $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory - } - - # Validate the type can be loaded. - $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require - - # Try to construct the HTTP client. - Write-Verbose "Constructing HTTP client." - try { - return New-Object $TypeName($Uri, $VssCredentials) - } catch { - # Rethrow if the exception is not due to Newtonsoft.Json DLL not found. - if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or - $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') { - - throw - } - - # Default the OMDirectory to the directory of the entry script for the task. - if (!$OMDirectory) { - $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..") - Write-Verbose "Defaulted OM directory to: '$OMDirectory'" - } - - # Test if the Newtonsoft.Json DLL exists in the OM directory. - $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll") - Write-Verbose "Testing file path: '$newtonsoftDll'" - if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) { - Write-Verbose 'Not found. Rethrowing exception.' - throw - } - - # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a - # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference - # the 8.0.0.0 Newtonsoft.Json DLL. - Write-Verbose "Adding assembly resolver." - $onAssemblyResolve = [System.ResolveEventHandler]{ - param($sender, $e) - - if ($e.Name -like 'Newtonsoft.Json, *') { - Write-Verbose "Resolving '$($e.Name)'" - return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll) - } - - Write-Verbose "Unable to resolve assembly name '$($e.Name)'" - return $null - } - [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve) - try { - # Try again to construct the HTTP client. - Write-Verbose "Trying again to construct the HTTP client." - return New-Object $TypeName($Uri, $VssCredentials) - } finally { - # Unregister the assembly resolver. - Write-Verbose "Removing assemlby resolver." - [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve) - } - } - } catch { - $ErrorActionPreference = $originalErrorActionPreference - Write-Error $_ - } finally { - Trace-LeavingInvocation -InvocationInfo $MyInvocation - } -} - -######################################## -# Private functions. -######################################## -function Get-OMType { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$TypeName, - - [ValidateSet('ExtendedClient', 'WebApi')] - [Parameter(Mandatory = $true)] - [string]$OMKind, - - [string]$OMDirectory, - - [switch]$Require) - - Trace-EnteringInvocation -InvocationInfo $MyInvocation - try { - # Default the OMDirectory to the directory of the entry script for the task. - if (!$OMDirectory) { - $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..") - Write-Verbose "Defaulted OM directory to: '$OMDirectory'" - } - - # Try to load the type. - $errorRecord = $null - Write-Verbose "Testing whether type can be loaded: '$TypeName'" - $ErrorActionPreference = 'Ignore' - try { - # Failure when attempting to cast a string to a type, transfers control to the - # catch handler even when the error action preference is ignore. The error action - # is set to Ignore so the $Error variable is not polluted. - $type = [type]$TypeName - - # Success. - Write-Verbose "The type was loaded successfully." - return $type - } catch { - # Store the error record. - $errorRecord = $_ - } - - $ErrorActionPreference = 'Stop' - Write-Verbose "The type was not loaded." - - # Build a list of candidate DLL file paths from the namespace. - $dllPaths = @( ) - $namespace = $TypeName - while ($namespace.LastIndexOf('.') -gt 0) { - # Trim the next segment from the namespace. - $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.')) - - # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API). - if ($OMKind -eq 'ExtendedClient') { - if ($namespace -like 'Microsoft.TeamFoundation.*') { - $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll") - } - } else { - if ($namespace -like 'Microsoft.TeamFoundation.*' -or - $namespace -like 'Microsoft.VisualStudio.Services' -or - $namespace -like 'Microsoft.VisualStudio.Services.*') { - - $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll") - $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll") - } - } - } - - foreach ($dllPath in $dllPaths) { - # Check whether the DLL exists. - Write-Verbose "Testing leaf path: '$dllPath'" - if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) { - Write-Verbose "Not found." - continue - } - - # Load the DLL. - Write-Verbose "Loading assembly: $dllPath" - try { - Add-Type -LiteralPath $dllPath - } catch { - # Write the information to the verbose stream and proceed to attempt to load the requested type. - # - # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the - # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even - # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb) - # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API - # HTTP clients. - Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)" - if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) { - for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) { - $loaderException = $_.Exception.LoaderExceptions[$i] - Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)" - } - } - } - - # Try to load the type. - Write-Verbose "Testing whether type can be loaded: '$TypeName'" - $ErrorActionPreference = 'Ignore' - try { - # Failure when attempting to cast a string to a type, transfers control to the - # catch handler even when the error action preference is ignore. The error action - # is set to Ignore so the $Error variable is not polluted. - $type = [type]$TypeName - - # Success. - Write-Verbose "The type was loaded successfully." - return $type - } catch { - $errorRecord = $_ - } - - $ErrorActionPreference = 'Stop' - Write-Verbose "The type was not loaded." - } - - # Check whether to propagate the error. - if ($Require) { - Write-Error $errorRecord - } - } finally { - Trace-LeavingInvocation -InvocationInfo $MyInvocation - } -} +<# +.SYNOPSIS +Gets assembly reference information. + +.DESCRIPTION +Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK. + +Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario. + +Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted. + +See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task. + +.PARAMETER LiteralPath +Assembly to walk. + +.EXAMPLE +Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll +#> +function Get-AssemblyReference { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$LiteralPath) + + $ErrorActionPreference = 'Stop' + Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK." + Write-Output '' + Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario." + $directory = [System.IO.Path]::GetDirectoryName($LiteralPath) + $hashtable = @{ } + $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() ) + while ($queue.Count) { + # Add a blank line between assemblies. + Write-Output '' + + # Pop. + $assemblyName = $queue[0] + $queue = @( $queue | Select-Object -Skip 1 ) + + # Attempt to find the assembly in the same directory. + $assembly = $null + $path = "$directory\$($assemblyName.Name).dll" + if ((Test-Path -LiteralPath $path -PathType Leaf)) { + $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path) + } else { + $path = "$directory\$($assemblyName.Name).exe" + if ((Test-Path -LiteralPath $path -PathType Leaf)) { + $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path) + } + } + + # Make sure the assembly full name matches, not just the file name. + if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) { + $assembly = $null + } + + # Print the assembly. + if ($assembly) { + Write-Output $assemblyName.FullName + } else { + if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') { + Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself." + } else { + Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***" + } + + continue + } + + # Walk the references. + $refAssemblyNames = @( $assembly.GetReferencedAssemblies() ) + for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) { + $refAssemblyName = $refAssemblyNames[$i] + + # Skip framework assemblies. + $fxPaths = @( + "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll" + "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll" + ) + $fxPath = $fxPaths | + Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } | + Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName } + if ($fxPath) { + continue + } + + # Print the reference. + Write-Output " $($refAssemblyName.FullName)" + + # Add new references to the queue. + if (!$hashtable[$refAssemblyName.FullName]) { + $queue += $refAssemblyName + $hashtable[$refAssemblyName.FullName] = $true + } + } + } +} + +<# +.SYNOPSIS +Gets a credentials object that can be used with the TFS extended client SDK. + +.DESCRIPTION +The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity). + +Refer to Get-VstsTfsService for a more simple to get a TFS service object. + +*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task. + +.PARAMETER OMDirectory +Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory. + +If not specified, defaults to the directory of the entry script for the task. + +*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task. + +.EXAMPLE +# +# Refer to Get-VstsTfsService for a more simple way to get a TFS service object. +# +$credentials = Get-VstsTfsClientCredentials +Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll" +$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection( + (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require), + $credentials) +$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer]) +$versionControlServer.GetItems('$/*').Items | Format-List +#> +function Get-TfsClientCredentials { + [CmdletBinding()] + param([string]$OMDirectory) + + Trace-EnteringInvocation -InvocationInfo $MyInvocation + $originalErrorActionPreference = $ErrorActionPreference + try { + $ErrorActionPreference = 'Stop' + + # Get the endpoint. + $endpoint = Get-Endpoint -Name SystemVssConnection -Require + + # Validate the type can be found. + $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require + + # Construct the credentials. + $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials. + $credentials.AllowInteractive = $false + $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken) + return $credentials + } catch { + $ErrorActionPreference = $originalErrorActionPreference + Write-Error $_ + } finally { + Trace-LeavingInvocation -InvocationInfo $MyInvocation + } +} + +<# +.SYNOPSIS +Gets a TFS extended client service. + +.DESCRIPTION +Gets an instance of an ITfsTeamProjectCollectionObject. + +*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task. + +.PARAMETER TypeName +Namespace-qualified type name of the service to get. + +.PARAMETER OMDirectory +Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory. + +If not specified, defaults to the directory of the entry script for the task. + +*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task. + +.PARAMETER Uri +URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri. + +.PARAMETER TfsClientCredentials +Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity). + +.EXAMPLE +$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer +$versionControlServer.GetItems('$/*').Items | Format-List +#> +function Get-TfsService { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$TypeName, + + [string]$OMDirectory, + + [string]$Uri, + + $TfsClientCredentials) + + Trace-EnteringInvocation -InvocationInfo $MyInvocation + $originalErrorActionPreference = $ErrorActionPreference + try { + $ErrorActionPreference = 'Stop' + + # Default the URI to the collection URI. + if (!$Uri) { + $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require + } + + # Default the credentials. + if (!$TfsClientCredentials) { + $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory + } + + # Validate the project collection type can be loaded. + $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require + + # Load the project collection object. + $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials) + + # Validate the requested type can be loaded. + $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require + + # Return the service object. + return $tfsTeamProjectCollection.GetService($type) + } catch { + $ErrorActionPreference = $originalErrorActionPreference + Write-Error $_ + } finally { + Trace-LeavingInvocation -InvocationInfo $MyInvocation + } +} + +<# +.SYNOPSIS +Gets a credentials object that can be used with the VSTS REST SDK. + +.DESCRIPTION +The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity). + +Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client. + +*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task. + +.PARAMETER OMDirectory +Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory. + +If not specified, defaults to the directory of the entry script for the task. + +*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task. + +.EXAMPLE +# +# Refer to Get-VstsTfsService for a more simple way to get a TFS service object. +# +# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding +# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient +# to avoid managing the binding redirect. +# +$vssCredentials = Get-VstsVssCredentials +$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require)) +Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll" +$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials) +$projectHttpClient.GetProjects().Result +#> +function Get-VssCredentials { + [CmdletBinding()] + param([string]$OMDirectory) + + Trace-EnteringInvocation -InvocationInfo $MyInvocation + $originalErrorActionPreference = $ErrorActionPreference + try { + $ErrorActionPreference = 'Stop' + + # Get the endpoint. + $endpoint = Get-Endpoint -Name SystemVssConnection -Require + + # Check if the VssOAuthAccessTokenCredential type is available. + if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) { + # Create the federated credential. + $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken) + } else { + # Validate the fallback type can be loaded. + $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require + + # Create the federated credential. + $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken) + } + + # Return the credentials. + return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials( + (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials. + $federatedCredential, + [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt) + } catch { + $ErrorActionPreference = $originalErrorActionPreference + Write-Error $_ + } finally { + Trace-LeavingInvocation -InvocationInfo $MyInvocation + } +} + +<# +.SYNOPSIS +Gets a VSS HTTP client. + +.DESCRIPTION +Gets an instance of an VSS HTTP client. + +*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task. + +.PARAMETER TypeName +Namespace-qualified type name of the HTTP client to get. + +.PARAMETER OMDirectory +Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory. + +If not specified, defaults to the directory of the entry script for the task. + +*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task. + +# .PARAMETER Uri +# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri. + +# .PARAMETER VssCredentials +# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity). + +.EXAMPLE +$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient +$projectHttpClient.GetProjects().Result +#> +function Get-VssHttpClient { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$TypeName, + + [string]$OMDirectory, + + [string]$Uri, + + $VssCredentials) + + Trace-EnteringInvocation -InvocationInfo $MyInvocation + $originalErrorActionPreference = $ErrorActionPreference + try { + $ErrorActionPreference = 'Stop' + + # Default the URI to the collection URI. + if (!$Uri) { + $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require + } + + # Cast the URI. + [uri]$Uri = New-Object System.Uri($Uri) + + # Default the credentials. + if (!$VssCredentials) { + $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory + } + + # Validate the type can be loaded. + $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require + + # Try to construct the HTTP client. + Write-Verbose "Constructing HTTP client." + try { + return New-Object $TypeName($Uri, $VssCredentials) + } catch { + # Rethrow if the exception is not due to Newtonsoft.Json DLL not found. + if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or + $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') { + + throw + } + + # Default the OMDirectory to the directory of the entry script for the task. + if (!$OMDirectory) { + $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..") + Write-Verbose "Defaulted OM directory to: '$OMDirectory'" + } + + # Test if the Newtonsoft.Json DLL exists in the OM directory. + $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll") + Write-Verbose "Testing file path: '$newtonsoftDll'" + if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) { + Write-Verbose 'Not found. Rethrowing exception.' + throw + } + + # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a + # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference + # the 8.0.0.0 Newtonsoft.Json DLL. + Write-Verbose "Adding assembly resolver." + $onAssemblyResolve = [System.ResolveEventHandler]{ + param($sender, $e) + + if ($e.Name -like 'Newtonsoft.Json, *') { + Write-Verbose "Resolving '$($e.Name)'" + return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll) + } + + Write-Verbose "Unable to resolve assembly name '$($e.Name)'" + return $null + } + [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve) + try { + # Try again to construct the HTTP client. + Write-Verbose "Trying again to construct the HTTP client." + return New-Object $TypeName($Uri, $VssCredentials) + } finally { + # Unregister the assembly resolver. + Write-Verbose "Removing assemlby resolver." + [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve) + } + } + } catch { + $ErrorActionPreference = $originalErrorActionPreference + Write-Error $_ + } finally { + Trace-LeavingInvocation -InvocationInfo $MyInvocation + } +} + +######################################## +# Private functions. +######################################## +function Get-OMType { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$TypeName, + + [ValidateSet('ExtendedClient', 'WebApi')] + [Parameter(Mandatory = $true)] + [string]$OMKind, + + [string]$OMDirectory, + + [switch]$Require) + + Trace-EnteringInvocation -InvocationInfo $MyInvocation + try { + # Default the OMDirectory to the directory of the entry script for the task. + if (!$OMDirectory) { + $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..") + Write-Verbose "Defaulted OM directory to: '$OMDirectory'" + } + + # Try to load the type. + $errorRecord = $null + Write-Verbose "Testing whether type can be loaded: '$TypeName'" + $ErrorActionPreference = 'Ignore' + try { + # Failure when attempting to cast a string to a type, transfers control to the + # catch handler even when the error action preference is ignore. The error action + # is set to Ignore so the $Error variable is not polluted. + $type = [type]$TypeName + + # Success. + Write-Verbose "The type was loaded successfully." + return $type + } catch { + # Store the error record. + $errorRecord = $_ + } + + $ErrorActionPreference = 'Stop' + Write-Verbose "The type was not loaded." + + # Build a list of candidate DLL file paths from the namespace. + $dllPaths = @( ) + $namespace = $TypeName + while ($namespace.LastIndexOf('.') -gt 0) { + # Trim the next segment from the namespace. + $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.')) + + # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API). + if ($OMKind -eq 'ExtendedClient') { + if ($namespace -like 'Microsoft.TeamFoundation.*') { + $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll") + } + } else { + if ($namespace -like 'Microsoft.TeamFoundation.*' -or + $namespace -like 'Microsoft.VisualStudio.Services' -or + $namespace -like 'Microsoft.VisualStudio.Services.*') { + + $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll") + $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll") + } + } + } + + foreach ($dllPath in $dllPaths) { + # Check whether the DLL exists. + Write-Verbose "Testing leaf path: '$dllPath'" + if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) { + Write-Verbose "Not found." + continue + } + + # Load the DLL. + Write-Verbose "Loading assembly: $dllPath" + try { + Add-Type -LiteralPath $dllPath + } catch { + # Write the information to the verbose stream and proceed to attempt to load the requested type. + # + # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the + # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even + # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb) + # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API + # HTTP clients. + Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)" + if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) { + for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) { + $loaderException = $_.Exception.LoaderExceptions[$i] + Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)" + } + } + } + + # Try to load the type. + Write-Verbose "Testing whether type can be loaded: '$TypeName'" + $ErrorActionPreference = 'Ignore' + try { + # Failure when attempting to cast a string to a type, transfers control to the + # catch handler even when the error action preference is ignore. The error action + # is set to Ignore so the $Error variable is not polluted. + $type = [type]$TypeName + + # Success. + Write-Verbose "The type was loaded successfully." + return $type + } catch { + $errorRecord = $_ + } + + $ErrorActionPreference = 'Stop' + Write-Verbose "The type was not loaded." + } + + # Check whether to propagate the error. + if ($Require) { + Write-Error $errorRecord + } + } finally { + Trace-LeavingInvocation -InvocationInfo $MyInvocation + } +} diff --git a/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson similarity index 98% rename from VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson rename to src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson index b412aee..ec97e9b 100644 --- a/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson +++ b/src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson @@ -1,17 +1,17 @@ -{ - "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".", - "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen", - "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL", - "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"", - "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".", - "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe", - "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"", - "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".", - "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"", - "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".", - "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.", - "loc.messages.PSLIB_Required0": "Erforderlich: {0}", - "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.", - "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".", - "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable" +{ + "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".", + "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen", + "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL", + "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"", + "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".", + "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe", + "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"", + "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".", + "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"", + "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".", + "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.", + "loc.messages.PSLIB_Required0": "Erforderlich: {0}", + "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.", + "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".", + "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable" } \ No newline at end of file diff --git a/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson similarity index 100% rename from VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson rename to src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson diff --git a/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson similarity index 98% rename from ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson rename to src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson index b4dadff..d09d96c 100644 --- a/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson +++ b/src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson @@ -1,17 +1,17 @@ -{ - "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'", - "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'", - "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'", - "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'", - "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'", - "loc.messages.PSLIB_Input0": "Entrada '{0}'", - "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'", - "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'", - "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'", - "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'", - "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.", - "loc.messages.PSLIB_Required0": "Se requiere: {0}", - "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.", - "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'", - "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'" +{ + "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'", + "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'", + "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'", + "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'", + "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'", + "loc.messages.PSLIB_Input0": "Entrada '{0}'", + "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'", + "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'", + "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'", + "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'", + "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.", + "loc.messages.PSLIB_Required0": "Se requiere: {0}", + "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.", + "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'", + "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'" } \ No newline at end of file diff --git a/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson similarity index 98% rename from ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson rename to src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson index 9d888c2..6606ddd 100644 --- a/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson +++ b/src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson @@ -1,17 +1,17 @@ -{ - "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'", - "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'", - "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'", - "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'", - "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.", - "loc.messages.PSLIB_Input0": "Entrée '{0}'", - "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'", - "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'", - "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'", - "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'", - "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.", - "loc.messages.PSLIB_Required0": "Obligatoire : {0}", - "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.", - "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'", - "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'" +{ + "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'", + "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'", + "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'", + "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'", + "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.", + "loc.messages.PSLIB_Input0": "Entrée '{0}'", + "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'", + "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'", + "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'", + "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'", + "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.", + "loc.messages.PSLIB_Required0": "Obligatoire : {0}", + "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.", + "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'", + "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'" } \ No newline at end of file diff --git a/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson similarity index 98% rename from ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson rename to src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson index 50079ee..0b54d99 100644 --- a/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson +++ b/src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson @@ -1,17 +1,17 @@ -{ - "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'", - "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'", - "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'", - "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita", - "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'", - "loc.messages.PSLIB_Input0": "Input di '{0}'", - "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'", - "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'", - "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'", - "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'", - "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.", - "loc.messages.PSLIB_Required0": "Obbligatorio: {0}", - "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.", - "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'", - "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'" +{ + "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'", + "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'", + "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'", + "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita", + "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'", + "loc.messages.PSLIB_Input0": "Input di '{0}'", + "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'", + "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'", + "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'", + "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'", + "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.", + "loc.messages.PSLIB_Required0": "Obbligatorio: {0}", + "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.", + "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'", + "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'" } \ No newline at end of file diff --git a/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson similarity index 98% rename from VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson rename to src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson index 5912541..b0e2bdf 100644 --- a/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson +++ b/src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson @@ -1,17 +1,17 @@ -{ - "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'", - "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報", - "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL", - "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした", - "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'", - "loc.messages.PSLIB_Input0": "'{0}' 入力", - "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'", - "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'", - "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした", - "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'", - "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。", - "loc.messages.PSLIB_Required0": "必要: {0}", - "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。", - "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'", - "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数" +{ + "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'", + "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報", + "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL", + "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした", + "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'", + "loc.messages.PSLIB_Input0": "'{0}' 入力", + "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'", + "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'", + "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした", + "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'", + "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。", + "loc.messages.PSLIB_Required0": "必要: {0}", + "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。", + "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'", + "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数" } \ No newline at end of file diff --git a/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson similarity index 98% rename from ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson rename to src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson index e2a1146..60df35b 100644 --- a/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson +++ b/src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson @@ -1,17 +1,17 @@ -{ - "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'", - "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명", - "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL", - "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'", - "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.", - "loc.messages.PSLIB_Input0": "'{0}' 입력", - "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'", - "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'", - "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'", - "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'", - "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.", - "loc.messages.PSLIB_Required0": "필수: {0}", - "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.", - "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'", - "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수" +{ + "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'", + "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명", + "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL", + "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'", + "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.", + "loc.messages.PSLIB_Input0": "'{0}' 입력", + "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'", + "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'", + "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'", + "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'", + "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.", + "loc.messages.PSLIB_Required0": "필수: {0}", + "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.", + "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'", + "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수" } \ No newline at end of file diff --git a/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson similarity index 99% rename from VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson rename to src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson index de01733..2d42208 100644 --- a/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson +++ b/src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson @@ -1,17 +1,17 @@ -{ - "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".", - "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"", - "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"", - "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".", - "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".", - "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".", - "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".", - "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".", - "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".", - "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".", - "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".", - "loc.messages.PSLIB_Required0": "Требуется: {0}", - "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.", - "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".", - "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\"" +{ + "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".", + "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"", + "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"", + "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".", + "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".", + "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".", + "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".", + "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".", + "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".", + "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".", + "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".", + "loc.messages.PSLIB_Required0": "Требуется: {0}", + "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.", + "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".", + "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\"" } \ No newline at end of file diff --git a/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson similarity index 98% rename from ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson rename to src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson index 918a76d..80adce2 100644 --- a/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson +++ b/src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson @@ -1,17 +1,17 @@ -{ - "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”", - "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据", - "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL", - "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”", - "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。", - "loc.messages.PSLIB_Input0": "“{0}”输入", - "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”", - "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”", - "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的", - "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”", - "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。", - "loc.messages.PSLIB_Required0": "必需: {0}", - "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。", - "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”", - "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量" +{ + "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”", + "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据", + "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL", + "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”", + "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。", + "loc.messages.PSLIB_Input0": "“{0}”输入", + "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”", + "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”", + "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的", + "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”", + "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。", + "loc.messages.PSLIB_Required0": "必需: {0}", + "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。", + "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”", + "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量" } \ No newline at end of file diff --git a/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson similarity index 98% rename from ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson rename to src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson index 03c3b4f..d6a041c 100644 --- a/ShowVariables/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson +++ b/src/VersionAssemblies/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson @@ -1,17 +1,17 @@ -{ - "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'", - "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證", - "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL", - "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'", - "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'", - "loc.messages.PSLIB_Input0": "'{0}' 輸入", - "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'", - "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'", - "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度", - "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'", - "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。", - "loc.messages.PSLIB_Required0": "必要項: {0}", - "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。", - "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'", - "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數" +{ + "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'", + "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證", + "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL", + "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'", + "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'", + "loc.messages.PSLIB_Input0": "'{0}' 輸入", + "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'", + "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'", + "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度", + "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'", + "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。", + "loc.messages.PSLIB_Required0": "必要項: {0}", + "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。", + "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'", + "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數" } \ No newline at end of file diff --git a/ShowVariables/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/src/VersionAssemblies/ps_modules/VstsTaskSdk/ToolFunctions.ps1 similarity index 97% rename from ShowVariables/ps_modules/VstsTaskSdk/ToolFunctions.ps1 rename to src/VersionAssemblies/ps_modules/VstsTaskSdk/ToolFunctions.ps1 index 3004901..0d0f444 100644 --- a/ShowVariables/ps_modules/VstsTaskSdk/ToolFunctions.ps1 +++ b/src/VersionAssemblies/ps_modules/VstsTaskSdk/ToolFunctions.ps1 @@ -1,99 +1,99 @@ -<# -.SYNOPSIS -Asserts that a path exists. Throws if the path does not exist. - -.PARAMETER PassThru -True to return the path. -#> -function Assert-Path { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string]$LiteralPath, - [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any, - [switch]$PassThru) - - if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) { - Write-Verbose "Asserting path exists: '$LiteralPath'" - } else { - Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'" - } - - if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) { - if ($PassThru) { - return $LiteralPath - } - - return - } - - $resourceKey = switch ($PathType) { - ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break } - ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break } - default { "PSLIB_PathNotFound0" } - } - - throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath) -} - -<# -.SYNOPSIS -Executes an external program. - -.DESCRIPTION -Executes an external program and waits for the process to exit. - -After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE. - -.PARAMETER Encoding -This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed. - -.PARAMETER RequireExitCodeZero -Indicates whether to write an error to the error pipeline if the exit code is not zero. -#> -function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS? - [CmdletBinding()] - param( - [ValidatePattern('^[^\r\n]*$')] - [Parameter(Mandatory = $true)] - [string]$FileName, - [ValidatePattern('^[^\r\n]*$')] - [Parameter()] - [string]$Arguments, - [string]$WorkingDirectory, - [System.Text.Encoding]$Encoding, - [switch]$RequireExitCodeZero) - - Trace-EnteringInvocation $MyInvocation - $isPushed = $false - $originalEncoding = $null - try { - if ($Encoding) { - $originalEncoding = [System.Console]::OutputEncoding - [System.Console]::OutputEncoding = $Encoding - } - - if ($WorkingDirectory) { - Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop - $isPushed = $true - } - - $FileName = $FileName.Replace('"', '').Replace("'", "''") - Write-Host "##[command]""$FileName"" $Arguments" - Invoke-Expression "& '$FileName' --% $Arguments" - Write-Verbose "Exit code: $LASTEXITCODE" - if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) { - Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE) - } - } finally { - if ($originalEncoding) { - [System.Console]::OutputEncoding = $originalEncoding - } - - if ($isPushed) { - Pop-Location - } - - Trace-LeavingInvocation $MyInvocation - } -} +<# +.SYNOPSIS +Asserts that a path exists. Throws if the path does not exist. + +.PARAMETER PassThru +True to return the path. +#> +function Assert-Path { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$LiteralPath, + [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any, + [switch]$PassThru) + + if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) { + Write-Verbose "Asserting path exists: '$LiteralPath'" + } else { + Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'" + } + + if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) { + if ($PassThru) { + return $LiteralPath + } + + return + } + + $resourceKey = switch ($PathType) { + ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break } + ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break } + default { "PSLIB_PathNotFound0" } + } + + throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath) +} + +<# +.SYNOPSIS +Executes an external program. + +.DESCRIPTION +Executes an external program and waits for the process to exit. + +After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE. + +.PARAMETER Encoding +This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed. + +.PARAMETER RequireExitCodeZero +Indicates whether to write an error to the error pipeline if the exit code is not zero. +#> +function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS? + [CmdletBinding()] + param( + [ValidatePattern('^[^\r\n]*$')] + [Parameter(Mandatory = $true)] + [string]$FileName, + [ValidatePattern('^[^\r\n]*$')] + [Parameter()] + [string]$Arguments, + [string]$WorkingDirectory, + [System.Text.Encoding]$Encoding, + [switch]$RequireExitCodeZero) + + Trace-EnteringInvocation $MyInvocation + $isPushed = $false + $originalEncoding = $null + try { + if ($Encoding) { + $originalEncoding = [System.Console]::OutputEncoding + [System.Console]::OutputEncoding = $Encoding + } + + if ($WorkingDirectory) { + Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop + $isPushed = $true + } + + $FileName = $FileName.Replace('"', '').Replace("'", "''") + Write-Host "##[command]""$FileName"" $Arguments" + Invoke-Expression "& '$FileName' --% $Arguments" + Write-Verbose "Exit code: $LASTEXITCODE" + if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) { + Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE) + } + } finally { + if ($originalEncoding) { + [System.Console]::OutputEncoding = $originalEncoding + } + + if ($isPushed) { + Pop-Location + } + + Trace-LeavingInvocation $MyInvocation + } +} diff --git a/VersionAssemblies/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/src/VersionAssemblies/ps_modules/VstsTaskSdk/TraceFunctions.ps1 similarity index 96% rename from VersionAssemblies/ps_modules/VstsTaskSdk/TraceFunctions.ps1 rename to src/VersionAssemblies/ps_modules/VstsTaskSdk/TraceFunctions.ps1 index b8e084b..cdbd779 100644 --- a/VersionAssemblies/ps_modules/VstsTaskSdk/TraceFunctions.ps1 +++ b/src/VersionAssemblies/ps_modules/VstsTaskSdk/TraceFunctions.ps1 @@ -1,139 +1,139 @@ -<# -.SYNOPSIS -Writes verbose information about the invocation being entered. - -.DESCRIPTION -Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced. - -.PARAMETER Parameter -Wildcard pattern to control which bound parameters are traced. -#> -function Trace-EnteringInvocation { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [System.Management.Automation.InvocationInfo]$InvocationInfo, - [string[]]$Parameter = '*') - - Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)." - $OFS = ", " - if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) { - if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') { - # Trace all parameters. - foreach ($key in $InvocationInfo.BoundParameters.Keys) { - Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'" - } - } else { - # Trace matching parameters. - foreach ($key in $InvocationInfo.BoundParameters.Keys) { - foreach ($p in $Parameter) { - if ($key -like $p) { - Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'" - break - } - } - } - } - } - - # Trace all unbound arguments. - if (@($InvocationInfo.UnboundArguments).Count) { - for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) { - Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'" - } - } -} - -<# -.SYNOPSIS -Writes verbose information about the invocation being left. - -.DESCRIPTION -Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation. -#> -function Trace-LeavingInvocation { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [System.Management.Automation.InvocationInfo]$InvocationInfo) - - Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)." -} - -<# -.SYNOPSIS -Writes verbose information about paths. - -.DESCRIPTION -Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path. - -.PARAMETER PassThru -Indicates whether to return the sorted paths. -#> -function Trace-Path { - [CmdletBinding()] - param( - [string[]]$Path, - [switch]$PassThru) - - if ($Path.Count -eq 0) { - Write-Verbose "No paths." - if ($PassThru) { - $Path - } - } elseif ($Path.Count -eq 1) { - Write-Verbose "Path: $($Path[0])" - if ($PassThru) { - $Path - } - } else { - # Find the greatest common root. - $sorted = $Path | Sort-Object - $firstPath = $sorted[0].ToCharArray() - $lastPath = $sorted[-1].ToCharArray() - $commonEndIndex = 0 - $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length } - for ($i = 0 ; $i -lt $j ; $i++) { - if ($firstPath[$i] -eq $lastPath[$i]) { - if ($firstPath[$i] -eq '\') { - $commonEndIndex = $i - } - } else { - break - } - } - - if ($commonEndIndex -eq 0) { - # No common root. - Write-Verbose "Paths:" - foreach ($p in $sorted) { - Write-Verbose " $p" - } - } else { - Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))" - foreach ($p in $sorted) { - Write-Verbose " $($p.Substring($commonEndIndex + 1))" - } - } - - if ($PassThru) { - $sorted - } - } -} - -######################################## -# Private functions. -######################################## -function Get-InvocationDescription { - [CmdletBinding()] - param([System.Management.Automation.InvocationInfo]$InvocationInfo) - - if ($InvocationInfo.MyCommand.Path) { - $InvocationInfo.MyCommand.Path - } elseif ($InvocationInfo.MyCommand.Name) { - $InvocationInfo.MyCommand.Name - } else { - $InvocationInfo.MyCommand.CommandType - } -} +<# +.SYNOPSIS +Writes verbose information about the invocation being entered. + +.DESCRIPTION +Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced. + +.PARAMETER Parameter +Wildcard pattern to control which bound parameters are traced. +#> +function Trace-EnteringInvocation { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [System.Management.Automation.InvocationInfo]$InvocationInfo, + [string[]]$Parameter = '*') + + Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)." + $OFS = ", " + if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) { + if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') { + # Trace all parameters. + foreach ($key in $InvocationInfo.BoundParameters.Keys) { + Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'" + } + } else { + # Trace matching parameters. + foreach ($key in $InvocationInfo.BoundParameters.Keys) { + foreach ($p in $Parameter) { + if ($key -like $p) { + Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'" + break + } + } + } + } + } + + # Trace all unbound arguments. + if (@($InvocationInfo.UnboundArguments).Count) { + for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) { + Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'" + } + } +} + +<# +.SYNOPSIS +Writes verbose information about the invocation being left. + +.DESCRIPTION +Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation. +#> +function Trace-LeavingInvocation { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [System.Management.Automation.InvocationInfo]$InvocationInfo) + + Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)." +} + +<# +.SYNOPSIS +Writes verbose information about paths. + +.DESCRIPTION +Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path. + +.PARAMETER PassThru +Indicates whether to return the sorted paths. +#> +function Trace-Path { + [CmdletBinding()] + param( + [string[]]$Path, + [switch]$PassThru) + + if ($Path.Count -eq 0) { + Write-Verbose "No paths." + if ($PassThru) { + $Path + } + } elseif ($Path.Count -eq 1) { + Write-Verbose "Path: $($Path[0])" + if ($PassThru) { + $Path + } + } else { + # Find the greatest common root. + $sorted = $Path | Sort-Object + $firstPath = $sorted[0].ToCharArray() + $lastPath = $sorted[-1].ToCharArray() + $commonEndIndex = 0 + $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length } + for ($i = 0 ; $i -lt $j ; $i++) { + if ($firstPath[$i] -eq $lastPath[$i]) { + if ($firstPath[$i] -eq '\') { + $commonEndIndex = $i + } + } else { + break + } + } + + if ($commonEndIndex -eq 0) { + # No common root. + Write-Verbose "Paths:" + foreach ($p in $sorted) { + Write-Verbose " $p" + } + } else { + Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))" + foreach ($p in $sorted) { + Write-Verbose " $($p.Substring($commonEndIndex + 1))" + } + } + + if ($PassThru) { + $sorted + } + } +} + +######################################## +# Private functions. +######################################## +function Get-InvocationDescription { + [CmdletBinding()] + param([System.Management.Automation.InvocationInfo]$InvocationInfo) + + if ($InvocationInfo.MyCommand.Path) { + $InvocationInfo.MyCommand.Path + } elseif ($InvocationInfo.MyCommand.Name) { + $InvocationInfo.MyCommand.Name + } else { + $InvocationInfo.MyCommand.CommandType + } +} diff --git a/VersionAssemblies/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/src/VersionAssemblies/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 similarity index 100% rename from VersionAssemblies/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 rename to src/VersionAssemblies/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 diff --git a/VersionAssemblies/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/src/VersionAssemblies/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 similarity index 97% rename from VersionAssemblies/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 rename to src/VersionAssemblies/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 index 2b68050..9ae96cd 100644 --- a/VersionAssemblies/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 +++ b/src/VersionAssemblies/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 @@ -1,161 +1,161 @@ -[CmdletBinding()] -param( - [ValidateNotNull()] - [Parameter()] - [hashtable]$ModuleParameters = @{ }) - -if ($host.Name -ne 'ConsoleHost') { - Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts." -} - -# Private module variables. -[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true' -Write-Verbose "NonInteractive: $script:nonInteractive" - -# Import/export functions. -. "$PSScriptRoot\FindFunctions.ps1" -. "$PSScriptRoot\InputFunctions.ps1" -. "$PSScriptRoot\LegacyFindFunctions.ps1" -. "$PSScriptRoot\LocalizationFunctions.ps1" -. "$PSScriptRoot\LoggingCommandFunctions.ps1" -. "$PSScriptRoot\LongPathFunctions.ps1" -. "$PSScriptRoot\ServerOMFunctions.ps1" -. "$PSScriptRoot\ToolFunctions.ps1" -. "$PSScriptRoot\TraceFunctions.ps1" -. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded. -Export-ModuleMember -Function @( - # Find functions. - 'Find-Match' - 'New-FindOptions' - 'New-MatchOptions' - 'Select-Match' - # Input functions. - 'Get-Endpoint' - 'Get-Input' - 'Get-TaskVariable' - 'Get-TaskVariableInfo' - 'Set-TaskVariable' - # Legacy find functions. - 'Find-Files' - # Localization functions. - 'Get-LocString' - 'Import-LocStrings' - # Logging command functions. - 'Write-AddAttachment' - 'Write-AddBuildTag' - 'Write-AssociateArtifact' - 'Write-LogDetail' - 'Write-SetProgress' - 'Write-SetResult' - 'Write-SetSecret' - 'Write-SetVariable' - 'Write-TaskDebug' - 'Write-TaskError' - 'Write-TaskVerbose' - 'Write-TaskWarning' - 'Write-UpdateBuildNumber' - 'Write-UploadArtifact' - 'Write-UploadBuildLog' - # Out functions. - 'Out-Default' - # Server OM functions. - 'Get-AssemblyReference' - 'Get-TfsClientCredentials' - 'Get-TfsService' - 'Get-VssCredentials' - 'Get-VssHttpClient' - # Tool functions. - 'Assert-Path' - 'Invoke-Tool' - # Trace functions. - 'Trace-EnteringInvocation' - 'Trace-LeavingInvocation' - 'Trace-Path' - ) - -# Special internal exception type to control the flow. Not currently intended -# for public usage and subject to change. If the type has already -# been loaded once, then it is not loaded again. -Write-Verbose "Adding exceptions types." -Add-Type -WarningAction SilentlyContinue -Debug:$false -TypeDefinition @' -namespace VstsTaskSdk -{ - public class TerminationException : System.Exception - { - public TerminationException(System.String message) : base(message) { } - } -} -'@ - -# Override Out-Default globally. -$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported) -New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global - -# Perform some initialization in a script block to enable merging the pipelines. -$scriptText = @" -# Load the SDK resource strings. -Import-LocStrings "$PSScriptRoot\lib.json" - -# Load the module that contains ConvertTo-SecureString. -if (!(Get-Module -Name Microsoft.PowerShell.Security)) { - Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'." - Import-Module -Name Microsoft.PowerShell.Security 2>&1 | - ForEach-Object { - if (`$_ -is [System.Management.Automation.ErrorRecord]) { - Write-Verbose `$_.Exception.Message - } else { - ,`$_ - } - } -} -"@ -. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default - -# Create Invoke-VstsTaskScript in a special way so it is not bound to the module. -# Otherwise calling the task script block would run within the module context. -# -# An alternative way to solve the problem is to close the script block (i.e. closure). -# However, that introduces a different problem. Closed script blocks are created within -# a dynamic module. Each module gets it's own session state separate from the global -# session state. When running in a regular script context, Import-Module calls import -# the target module into the global session state. When running in a module context, -# Import-Module calls import the target module into the caller module's session state. -# -# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts -# should run in regular script context. The end user specifying an ad-hoc script expects -# the module import rules to be consistent with the default behavior (i.e. imported -# into the global session state). -$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@' - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [scriptblock]$ScriptBlock) - - try { - $global:ErrorActionPreference = 'Stop' - - # Initialize the environment. - $vstsModule = Get-Module -Name VstsTaskSdk - Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default - & $vstsModule Initialize-Inputs 4>&1 | Out-Default - - # Remove the local variable before calling the user's script. - Remove-Variable -Name vstsModule - - # Call the user's script. - $ScriptBlock | - ForEach-Object { - # Remove the scriptblock variable before calling it. - Remove-Variable -Name ScriptBlock - & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default - } - } catch [VstsTaskSdk.TerminationException] { - # Special internal exception type to control the flow. Not currently intended - # for public usage and subject to change. - Write-Verbose "Task script terminated." 4>&1 | Out-Default - } catch { - Write-Verbose "Caught exception from task script." 4>&1 | Out-Default - $_ | Out-Default - Write-Host "##vso[task.complete result=Failed]" - } -'@)) +[CmdletBinding()] +param( + [ValidateNotNull()] + [Parameter()] + [hashtable]$ModuleParameters = @{ }) + +if ($host.Name -ne 'ConsoleHost') { + Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts." +} + +# Private module variables. +[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true' +Write-Verbose "NonInteractive: $script:nonInteractive" + +# Import/export functions. +. "$PSScriptRoot\FindFunctions.ps1" +. "$PSScriptRoot\InputFunctions.ps1" +. "$PSScriptRoot\LegacyFindFunctions.ps1" +. "$PSScriptRoot\LocalizationFunctions.ps1" +. "$PSScriptRoot\LoggingCommandFunctions.ps1" +. "$PSScriptRoot\LongPathFunctions.ps1" +. "$PSScriptRoot\ServerOMFunctions.ps1" +. "$PSScriptRoot\ToolFunctions.ps1" +. "$PSScriptRoot\TraceFunctions.ps1" +. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded. +Export-ModuleMember -Function @( + # Find functions. + 'Find-Match' + 'New-FindOptions' + 'New-MatchOptions' + 'Select-Match' + # Input functions. + 'Get-Endpoint' + 'Get-Input' + 'Get-TaskVariable' + 'Get-TaskVariableInfo' + 'Set-TaskVariable' + # Legacy find functions. + 'Find-Files' + # Localization functions. + 'Get-LocString' + 'Import-LocStrings' + # Logging command functions. + 'Write-AddAttachment' + 'Write-AddBuildTag' + 'Write-AssociateArtifact' + 'Write-LogDetail' + 'Write-SetProgress' + 'Write-SetResult' + 'Write-SetSecret' + 'Write-SetVariable' + 'Write-TaskDebug' + 'Write-TaskError' + 'Write-TaskVerbose' + 'Write-TaskWarning' + 'Write-UpdateBuildNumber' + 'Write-UploadArtifact' + 'Write-UploadBuildLog' + # Out functions. + 'Out-Default' + # Server OM functions. + 'Get-AssemblyReference' + 'Get-TfsClientCredentials' + 'Get-TfsService' + 'Get-VssCredentials' + 'Get-VssHttpClient' + # Tool functions. + 'Assert-Path' + 'Invoke-Tool' + # Trace functions. + 'Trace-EnteringInvocation' + 'Trace-LeavingInvocation' + 'Trace-Path' + ) + +# Special internal exception type to control the flow. Not currently intended +# for public usage and subject to change. If the type has already +# been loaded once, then it is not loaded again. +Write-Verbose "Adding exceptions types." +Add-Type -WarningAction SilentlyContinue -Debug:$false -TypeDefinition @' +namespace VstsTaskSdk +{ + public class TerminationException : System.Exception + { + public TerminationException(System.String message) : base(message) { } + } +} +'@ + +# Override Out-Default globally. +$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported) +New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global + +# Perform some initialization in a script block to enable merging the pipelines. +$scriptText = @" +# Load the SDK resource strings. +Import-LocStrings "$PSScriptRoot\lib.json" + +# Load the module that contains ConvertTo-SecureString. +if (!(Get-Module -Name Microsoft.PowerShell.Security)) { + Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'." + Import-Module -Name Microsoft.PowerShell.Security 2>&1 | + ForEach-Object { + if (`$_ -is [System.Management.Automation.ErrorRecord]) { + Write-Verbose `$_.Exception.Message + } else { + ,`$_ + } + } +} +"@ +. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default + +# Create Invoke-VstsTaskScript in a special way so it is not bound to the module. +# Otherwise calling the task script block would run within the module context. +# +# An alternative way to solve the problem is to close the script block (i.e. closure). +# However, that introduces a different problem. Closed script blocks are created within +# a dynamic module. Each module gets it's own session state separate from the global +# session state. When running in a regular script context, Import-Module calls import +# the target module into the global session state. When running in a module context, +# Import-Module calls import the target module into the caller module's session state. +# +# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts +# should run in regular script context. The end user specifying an ad-hoc script expects +# the module import rules to be consistent with the default behavior (i.e. imported +# into the global session state). +$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@' + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [scriptblock]$ScriptBlock) + + try { + $global:ErrorActionPreference = 'Stop' + + # Initialize the environment. + $vstsModule = Get-Module -Name VstsTaskSdk + Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default + & $vstsModule Initialize-Inputs 4>&1 | Out-Default + + # Remove the local variable before calling the user's script. + Remove-Variable -Name vstsModule + + # Call the user's script. + $ScriptBlock | + ForEach-Object { + # Remove the scriptblock variable before calling it. + Remove-Variable -Name ScriptBlock + & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default + } + } catch [VstsTaskSdk.TerminationException] { + # Special internal exception type to control the flow. Not currently intended + # for public usage and subject to change. + Write-Verbose "Task script terminated." 4>&1 | Out-Default + } catch { + Write-Verbose "Caught exception from task script." 4>&1 | Out-Default + $_ | Out-Default + Write-Host "##vso[task.complete result=Failed]" + } +'@)) diff --git a/VersionAssemblies/ps_modules/VstsTaskSdk/lib.json b/src/VersionAssemblies/ps_modules/VstsTaskSdk/lib.json similarity index 98% rename from VersionAssemblies/ps_modules/VstsTaskSdk/lib.json rename to src/VersionAssemblies/ps_modules/VstsTaskSdk/lib.json index 6f3c333..b000819 100644 --- a/VersionAssemblies/ps_modules/VstsTaskSdk/lib.json +++ b/src/VersionAssemblies/ps_modules/VstsTaskSdk/lib.json @@ -1,19 +1,19 @@ -{ - "messages": { - "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'", - "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials", - "PSLIB_EndpointUrl0": "'{0}' service endpoint URL", - "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'", - "PSLIB_FileNotFound0": "File not found: '{0}'", - "PSLIB_Input0": "'{0}' input", - "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'", - "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'", - "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'", - "PSLIB_PathNotFound0": "Path not found: '{0}'", - "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.", - "PSLIB_Required0": "Required: {0}", - "PSLIB_StringFormatFailed": "String format failed.", - "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'", - "PSLIB_TaskVariable0": "'{0}' task variable" - } -} +{ + "messages": { + "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'", + "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials", + "PSLIB_EndpointUrl0": "'{0}' service endpoint URL", + "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'", + "PSLIB_FileNotFound0": "File not found: '{0}'", + "PSLIB_Input0": "'{0}' input", + "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'", + "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'", + "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'", + "PSLIB_PathNotFound0": "Path not found: '{0}'", + "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.", + "PSLIB_Required0": "Required: {0}", + "PSLIB_StringFormatFailed": "String format failed.", + "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'", + "PSLIB_TaskVariable0": "'{0}' task variable" + } +} diff --git a/VersionAssemblies/task.json b/src/VersionAssemblies/task.json similarity index 100% rename from VersionAssemblies/task.json rename to src/VersionAssemblies/task.json diff --git a/VersionAssemblies/versionAssemblies.ps1 b/src/VersionAssemblies/versionAssemblies.ps1 similarity index 96% rename from VersionAssemblies/versionAssemblies.ps1 rename to src/VersionAssemblies/versionAssemblies.ps1 index 4825aa5..1b27fd3 100644 --- a/VersionAssemblies/versionAssemblies.ps1 +++ b/src/VersionAssemblies/versionAssemblies.ps1 @@ -1,185 +1,185 @@ -[CmdletBinding()] -param() - -# Gets the Julian date -function GetJulianDate -{ - $now = [DateTime]::Now - - return $now.ToString("yy") + $now.DayOfYear.ToString("000") -} - -# Finds the revision in the build number -function GetRevision -{ - param( - [string][Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()] $number - ) - - # Split the value by the . - $tokens = $number.Split('.'); - - # In general we want the last one but a Draft build will have a non-number here so find the - # last token that is a number - for ($index = $tokens.Length - 1; $index -ge 0; $index--) { - $value = 0 - if ([System.Int32]::TryParse($tokens[$index], [ref] $value)) { - return $value.ToString() - } - }; - - throw "Unable to locate revision number" -} - -# Generates the attributes for the version files -function GenerateAttributes -{ - # Build number is the full build name and we just care about the revision part of it so strip that out - $revision = GetRevision $buildNumber - - if ([String]::IsNullOrEmpty($build)) { $build = GetJulianDate } - - # Calculate the values we'll need - $longVersion = "$major.$minor.$build.$revision" - $shortVersion = "$major.$minor.0.0" - - # Set the final attributes - would like to use a hashtable here but VSTS SDK breaks hashtables... - $attributes = @{ - "AssemblyProduct" = $product; - "AssemblyCompany" = $company; - "AssemblyCopyright" = "Copyright $company"; - "AssemblyTrademark" = $trademark; - - "AssemblyVersion" = $shortVersion; - "AssemblyFileVersion" = $longVersion; - "AssemblyInformationalVersion" = $longVersion; - "AssemblyConfiguration" = $configuration; - } - - # Log the attributes - Write-VstsTaskDebug 'Calculated attributes' - foreach ($attribute in $attributes.GetEnumerator()) - { - Write-VstsTaskDebug "$($attribute.Key) = $($attribute.Value)" - } - - # Publish the version information to TFS - Write-Host "Product Version = $shortVersion" - Write-Host "Full Version = $longVersion" - Set-VstsTaskVariable -Name "Version_Product" -Value $shortVersion - Set-VstsTaskVariable -Name "Version_Full" -Value $longVersion - return $attributes -} - -# Trims comments from a line -function TrimComments -{ - param( - [string] $line - ) - - $index = $line.IndexOf("//") - if ($index -lt 0) { return $line } - - return $line.Substring(0, $index).Trim() -} - -# Updates all the files matching the given pattern with the provided attributes -function UpdateVersionFiles -{ - param( - [string][Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()] $filePath, - [string][Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()] $searchPattern, - [Hashtable] $attributes - ) - - $files = [System.IO.Directory]::GetFiles($filePath, $searchPattern, [System.IO.SearchOption]::AllDirectories) - - $fileIndex = 0 - $fileCount = $files.Count - - foreach($file in $files) - { - Write-VstsTaskVerbose "Updating version information in $file" - UpdateVersionFile $file $attributes - $fileIndex += 1 - } - Write-VstsTaskVerbose "Finished updating version files" -} - -# Updates a file with the attributes specified -function UpdateVersionFile -{ - param( - [string][Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()] $filePath, - [Hashtable] $attributes - ) - - #Removes ReadOnly attribute from file - Set-ItemProperty $filePath -name IsReadOnly -value $false - - # Load text into $lines - $lines = New-Object System.Collections.Generic.List[string] - $lines.AddRange([System.IO.File]::ReadAllLines($filePath)) - - foreach($attribute in $attributes.GetEnumerator()) - { - # Create a new regular expression - $re = "^\[assembly\s*:\s*$($attribute.Key)(Attribute)?\s*\(\s*(`".*`"\s*)?\s*\)\s*\]$" - - $foundMatch = $false - $newValue = '[assembly: ' + $($attribute.Key) + '("' + $($attribute.Value) + '")]' - - # Find the matching line, if any - for ($index = 0; $index -lt $lines.Count; ++$index) - { - # Skip comments and blank lines - $line = TrimComments($lines[$index]) - if ([String]::IsNullOrEmpty($line)) { continue } - - # Does the line match - if ($line -imatch $re) - { - Write-VstsTaskDebug "Replacing $($attribute.Key)" - $lines[$index] = $newValue - $foundMatch = $true - } - } - - #If line does not exist then add a new line of the attribute and value into file - if (-not $foundMatch) - { - Write-VstsTaskDebug "Adding $($attribute.Key)" - $lines.Add($newValue) - } - } - [System.IO.File]::WriteAllLines($filePath, $lines.ToArray()) -} - -###### Entry Point ######## - -Trace-VstsEnteringInvocation $MyInvocation - -# Get inputs -$product = Get-VstsInput -Name product -Require -$major = Get-VstsInput -Name major -AsInt -Require -$minor = Get-VstsInput -Name minor -AsInt -Require -$company = Get-VstsInput -Name company -Require -$assemblyInfoFilePattern = Get-VstsInput -Name assemblyInfoFilePattern -Require -$build = Get-VstsInput -Name build -$sourcePath = $env:BUILD_SOURCESDIRECTORY -$buildNumber = $env:BUILD_BUILDNUMBER -$trademark = Get-VstsInput -Name trademark -$configuration = Get-VstsInput -Name configuration - -try { - # Generate the attributes based upon the parameters - Write-VstsTaskVerbose 'Generating attributes' - $attributes = GenerateAttributes - - # Enumerate to get all files needed - Write-VstsTaskVerbose 'Updating files' - UpdateVersionFiles $sourcePath $assemblyInfoFilePattern $attributes -} finally { - Trace-VstsLeavingInvocation $MyInvocation -} +[CmdletBinding()] +param() + +# Gets the Julian date +function GetJulianDate +{ + $now = [DateTime]::Now + + return $now.ToString("yy") + $now.DayOfYear.ToString("000") +} + +# Finds the revision in the build number +function GetRevision +{ + param( + [string][Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()] $number + ) + + # Split the value by the . + $tokens = $number.Split('.'); + + # In general we want the last one but a Draft build will have a non-number here so find the + # last token that is a number + for ($index = $tokens.Length - 1; $index -ge 0; $index--) { + $value = 0 + if ([System.Int32]::TryParse($tokens[$index], [ref] $value)) { + return $value.ToString() + } + }; + + throw "Unable to locate revision number" +} + +# Generates the attributes for the version files +function GenerateAttributes +{ + # Build number is the full build name and we just care about the revision part of it so strip that out + $revision = GetRevision $buildNumber + + if ([String]::IsNullOrEmpty($build)) { $build = GetJulianDate } + + # Calculate the values we'll need + $longVersion = "$major.$minor.$build.$revision" + $shortVersion = "$major.$minor.0.0" + + # Set the final attributes - would like to use a hashtable here but VSTS SDK breaks hashtables... + $attributes = @{ + "AssemblyProduct" = $product; + "AssemblyCompany" = $company; + "AssemblyCopyright" = "Copyright $company"; + "AssemblyTrademark" = $trademark; + + "AssemblyVersion" = $shortVersion; + "AssemblyFileVersion" = $longVersion; + "AssemblyInformationalVersion" = $longVersion; + "AssemblyConfiguration" = $configuration; + } + + # Log the attributes + Write-VstsTaskDebug 'Calculated attributes' + foreach ($attribute in $attributes.GetEnumerator()) + { + Write-VstsTaskDebug "$($attribute.Key) = $($attribute.Value)" + } + + # Publish the version information to TFS + Write-Host "Product Version = $shortVersion" + Write-Host "Full Version = $longVersion" + Set-VstsTaskVariable -Name "Version_Product" -Value $shortVersion + Set-VstsTaskVariable -Name "Version_Full" -Value $longVersion + return $attributes +} + +# Trims comments from a line +function TrimComments +{ + param( + [string] $line + ) + + $index = $line.IndexOf("//") + if ($index -lt 0) { return $line } + + return $line.Substring(0, $index).Trim() +} + +# Updates all the files matching the given pattern with the provided attributes +function UpdateVersionFiles +{ + param( + [string][Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()] $filePath, + [string][Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()] $searchPattern, + [Hashtable] $attributes + ) + + $files = [System.IO.Directory]::GetFiles($filePath, $searchPattern, [System.IO.SearchOption]::AllDirectories) + + $fileIndex = 0 + $fileCount = $files.Count + + foreach($file in $files) + { + Write-VstsTaskVerbose "Updating version information in $file" + UpdateVersionFile $file $attributes + $fileIndex += 1 + } + Write-VstsTaskVerbose "Finished updating version files" +} + +# Updates a file with the attributes specified +function UpdateVersionFile +{ + param( + [string][Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()] $filePath, + [Hashtable] $attributes + ) + + #Removes ReadOnly attribute from file + Set-ItemProperty $filePath -name IsReadOnly -value $false + + # Load text into $lines + $lines = New-Object System.Collections.Generic.List[string] + $lines.AddRange([System.IO.File]::ReadAllLines($filePath)) + + foreach($attribute in $attributes.GetEnumerator()) + { + # Create a new regular expression + $re = "^\[assembly\s*:\s*$($attribute.Key)(Attribute)?\s*\(\s*(`".*`"\s*)?\s*\)\s*\]$" + + $foundMatch = $false + $newValue = '[assembly: ' + $($attribute.Key) + '("' + $($attribute.Value) + '")]' + + # Find the matching line, if any + for ($index = 0; $index -lt $lines.Count; ++$index) + { + # Skip comments and blank lines + $line = TrimComments($lines[$index]) + if ([String]::IsNullOrEmpty($line)) { continue } + + # Does the line match + if ($line -imatch $re) + { + Write-VstsTaskDebug "Replacing $($attribute.Key)" + $lines[$index] = $newValue + $foundMatch = $true + } + } + + #If line does not exist then add a new line of the attribute and value into file + if (-not $foundMatch) + { + Write-VstsTaskDebug "Adding $($attribute.Key)" + $lines.Add($newValue) + } + } + [System.IO.File]::WriteAllLines($filePath, $lines.ToArray()) +} + +###### Entry Point ######## + +Trace-VstsEnteringInvocation $MyInvocation + +# Get inputs +$product = Get-VstsInput -Name product -Require +$major = Get-VstsInput -Name major -AsInt -Require +$minor = Get-VstsInput -Name minor -AsInt -Require +$company = Get-VstsInput -Name company -Require +$assemblyInfoFilePattern = Get-VstsInput -Name assemblyInfoFilePattern -Require +$build = Get-VstsInput -Name build +$sourcePath = $env:BUILD_SOURCESDIRECTORY +$buildNumber = $env:BUILD_BUILDNUMBER +$trademark = Get-VstsInput -Name trademark +$configuration = Get-VstsInput -Name configuration + +try { + # Generate the attributes based upon the parameters + Write-VstsTaskVerbose 'Generating attributes' + $attributes = GenerateAttributes + + # Enumerate to get all files needed + Write-VstsTaskVerbose 'Updating files' + UpdateVersionFiles $sourcePath $assemblyInfoFilePattern $attributes +} finally { + Trace-VstsLeavingInvocation $MyInvocation +} diff --git a/extension-icon.png b/src/extension-icon.png similarity index 100% rename from extension-icon.png rename to src/extension-icon.png diff --git a/overview.md b/src/overview.md similarity index 95% rename from overview.md rename to src/overview.md index 362e41e..b72cbed 100644 --- a/overview.md +++ b/src/overview.md @@ -1,5 +1,5 @@ -# P3.NET Build Tasks - -## ShowVariables - +# P3.NET Build Tasks + +## ShowVariables + Shows environment variables in the log. \ No newline at end of file diff --git a/vss-extension.json b/src/vss-extension.json similarity index 94% rename from vss-extension.json rename to src/vss-extension.json index ffcb313..1f7dc16 100644 --- a/vss-extension.json +++ b/src/vss-extension.json @@ -1,58 +1,58 @@ -{ - "manifestVersion": 1, - "id": "p3net-buildextensions", - "version": "1.0.8", - "name": "P3Net Build Extensions", - "publisher": "p3net", - "targets": [ - { - "id": "Microsoft.VisualStudio.Services" - } - ], - "scopes": [ - "vso.build", - "vso.build_execute" - ], - "description": "Build extensions from P3 NET", - "categories": [ - "Build and release" - ], - "icons": { - "default": "extension-icon.png" - }, - "content": { - "details": { - "path": "overview.md" - } - }, - "files": [ - { - "path": "ShowVariables" - }, - { - "path": "VersionAssemblies" - } - ], - "contributions": [ - { - "id": "p3net-showvariables-task", - "type": "ms.vss-distributed-task.task", - "targets": [ - "ms.vss-distributed-task.tasks" - ], - "properties": { - "name": "ShowVariables" - } - }, - { - "id": "p3net-versionassemblies-task", - "type": "ms.vss-distributed-task.task", - "targets": [ - "ms.vss-distributed-task.tasks" - ], - "properties": { - "name": "VersionAssemblies" - } - } - ] +{ + "manifestVersion": 1, + "id": "p3net-buildextensions", + "version": "1.0.8", + "name": "P3Net Build Extensions", + "publisher": "p3net", + "targets": [ + { + "id": "Microsoft.VisualStudio.Services" + } + ], + "scopes": [ + "vso.build", + "vso.build_execute" + ], + "description": "Build extensions from P3 NET", + "categories": [ + "Build and release" + ], + "icons": { + "default": "extension-icon.png" + }, + "content": { + "details": { + "path": "overview.md" + } + }, + "files": [ + { + "path": "ShowVariables" + }, + { + "path": "VersionAssemblies" + } + ], + "contributions": [ + { + "id": "p3net-showvariables-task", + "type": "ms.vss-distributed-task.task", + "targets": [ + "ms.vss-distributed-task.tasks" + ], + "properties": { + "name": "ShowVariables" + } + }, + { + "id": "p3net-versionassemblies-task", + "type": "ms.vss-distributed-task.task", + "targets": [ + "ms.vss-distributed-task.tasks" + ], + "properties": { + "name": "VersionAssemblies" + } + } + ] } \ No newline at end of file