Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Apply PowerShell Practice Styles #270

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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -374,5 +374,3 @@ Microsoft.WinGet.*.Documentation.xml
# Developer ARM template
src/WinGet.RestSource.Infrastructure/**/*.dev.*json

# VS Code
.vscode/
22 changes: 22 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"editor.formatOnSave": true,
"[powershell]": {
"files.encoding": "utf8bom",
"files.autoGuessEncoding": true
},
"powershell.codeFormatting.preset": "OTBS",
"powershell.codeFormatting.useConstantStrings": true,
"powershell.codeFormatting.trimWhitespaceAroundPipe": true,
"powershell.codeFormatting.useCorrectCasing": true,
"powershell.codeFormatting.whitespaceBeforeOpenParen": true,
"powershell.codeFormatting.whitespaceBetweenParameters": true,
"powershell.codeFormatting.addWhitespaceAroundPipe": true,
"powershell.codeFormatting.alignPropertyValuePairs": true,
"powershell.codeFormatting.autoCorrectAliases": true,
"powershell.codeFormatting.avoidSemicolonsAsLineTerminators": true,
"powershell.codeFormatting.ignoreOneLineBlock": true,
"powershell.codeFormatting.whitespaceBeforeOpenBrace": true,
"powershell.codeFormatting.whitespaceAroundOperator": true,
"powershell.codeFormatting.whitespaceAfterSeparator": true,
"powershell.codeFormatting.whitespaceInsideBrace": true
}
21 changes: 9 additions & 12 deletions Tools/PowershellModule/src/Library/Add-AzureResourceGroup.ps1
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Function Add-AzureResourceGroup
{
Function Add-AzureResourceGroup {
<#
.SYNOPSIS
Adds a Resource Group to the connected to Subscription.
Expand All @@ -25,15 +24,15 @@ Function Add-AzureResourceGroup
#>

PARAM(
[Parameter(Position=0, Mandatory=$true)] [string]$Name,
[Parameter(Position=1, Mandatory=$true)] [string]$Region
[Parameter(Position = 0, Mandatory = $true)] [string]$Name,
[Parameter(Position = 1, Mandatory = $true)] [string]$Region
)

$Return = $false

## Normalize resource group name
$NormalizedName = $Name -replace "[^a-zA-Z0-9-()_.]", ""
if($Name -cne $NormalizedName) {
$NormalizedName = $Name -replace '[^a-zA-Z0-9-()_.]', ''
if ($Name -cne $NormalizedName) {
$Name = $NormalizedName
Write-Warning "Removed special characters from the Azure Resource Group Name (New Name: $Name)."
}
Expand All @@ -45,19 +44,17 @@ Function Add-AzureResourceGroup
Write-Verbose "Retrieving details from Azure for the Resource Group name $Name"
$Result = Get-AzResourceGroup -Name $Name -ErrorAction SilentlyContinue -ErrorVariable ErrorGet

if(!$Result) {
if (!$Result) {
Write-Information "Failed to retrieve Resource Group, will attempt to create $Name in the specified $Region."

$Result = New-AzResourceGroup -Name $Name -Location $Region
if($Result) {
if ($Result) {
Write-Information "Resource Group $Name has been created in the $Region region."
$Return = $true
}
else {
} else {
Write-Error "Failed to retrieve or create Resource Group with name $Name."
}
}
else {
} else {
## Found an existing Resource Group matching the name of $Name
Write-Warning "Found an existing Resource Group matching the name of $Name. Will not create a new Resource Group."
$Return = $true
Expand Down
72 changes: 33 additions & 39 deletions Tools/PowershellModule/src/Library/Add-WinGetManifest.ps1
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Function Add-WinGetManifest
{
Function Add-WinGetManifest {
<#
.SYNOPSIS
Submits a Manifest file to the Azure REST source
Expand Down Expand Up @@ -42,74 +41,72 @@ Function Add-WinGetManifest
#>

PARAM(
[Parameter(Position=0, Mandatory=$true)] [string]$FunctionName,
[Parameter(Position=1, Mandatory=$true, ValueFromPipeline=$true)] [string]$Path,
[Parameter(Mandatory=$false)] [string]$SubscriptionName = ""
[Parameter(Position = 0, Mandatory = $true)] [string]$FunctionName,
[Parameter(Position = 1, Mandatory = $true, ValueFromPipeline = $true)] [string]$Path,
[Parameter(Mandatory = $false)] [string]$SubscriptionName = ''
)
BEGIN
{
BEGIN {
[WinGetManifest[]] $Return = @()

###############################
## Connects to Azure, if not already connected.
Write-Verbose -Message "Validating connection to azure, will attempt to connect if not already connected."
Write-Verbose -Message 'Validating connection to azure, will attempt to connect if not already connected.'
$Result = Connect-ToAzure -SubscriptionName $SubscriptionName
if(!($Result)) {
Write-Error "Failed to connect to Azure. Please run Connect-AzAccount to connect to Azure, or re-run the cmdlet and enter your credentials." -ErrorAction Stop
if (!($Result)) {
Write-Error 'Failed to connect to Azure. Please run Connect-AzAccount to connect to Azure, or re-run the cmdlet and enter your credentials.' -ErrorAction Stop
}

###############################
## Gets Resource Group name of the Azure Function
Write-Verbose -Message "Determines the Azure Function Resource Group Name"
$ResourceGroupName = $(Get-AzFunctionApp).Where({$_.Name -eq $FunctionName}).ResourceGroupName
if(!$ResourceGroupName) {
Write-Verbose -Message 'Determines the Azure Function Resource Group Name'
$ResourceGroupName = $(Get-AzFunctionApp).Where({ $_.Name -eq $FunctionName }).ResourceGroupName
if (!$ResourceGroupName) {
Write-Error "Failed to confirm Azure Function exists in Azure. Please verify and try again. Function Name: $FunctionName" -ErrorAction Stop
}

#############################################
############## REST api call ##############

## Specifies the REST api call that will be performed
$ApiContentType = "application/json"
$ApiMethodPost = "Post"
$ApiMethodGet = "Get"
$ApiMethodPut = "Put"
$ApiContentType = 'application/json'
$ApiMethodPost = 'Post'
$ApiMethodGet = 'Get'
$ApiMethodPut = 'Put'

## Retrieves the Azure Function URL used to add new manifests to the REST source
Write-Verbose -Message "Retrieving the Azure Function $FunctionName to build out the REST API request."
$FunctionApp = Get-AzFunctionApp -ResourceGroupName $ResourceGroupName -Name $FunctionName

$FunctionAppId = $FunctionApp.Id
$FunctionAppId = $FunctionApp.Id
$DefaultHostName = $FunctionApp.DefaultHostName
$FunctionKeyPost = (Invoke-AzResourceAction -ResourceId "$FunctionAppId/functions/ManifestPost" -Action listkeys -Force).default
$FunctionKeyGet = (Invoke-AzResourceAction -ResourceId "$FunctionAppId/functions/ManifestGet" -Action listkeys -Force).default
$FunctionKeyPut = (Invoke-AzResourceAction -ResourceId "$FunctionAppId/functions/ManifestPut" -Action listkeys -Force).default


## Creates the API Post Header
$ApiHeader = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$ApiHeader.Add("Accept", 'application/json')
$ApiHeader = New-Object 'System.Collections.Generic.Dictionary[[String],[String]]'
$ApiHeader.Add('Accept', 'application/json')

$AzFunctionURLBase = "https://" + $DefaultHostName + "/api/packageManifests/"
$AzFunctionURLBase = 'https://' + $DefaultHostName + '/api/packageManifests/'
}
PROCESS
{
PROCESS {
$Path = [System.IO.Path]::GetFullPath($Path, $pwd.Path)

###############################
## Gets the content from the Package Manifest (*.JSON, or *.YAML) file for posting to REST source.
Write-Verbose -Message "Retrieving a copy of the app Manifest file for submission to WinGet source."
Write-Verbose -Message 'Retrieving a copy of the app Manifest file for submission to WinGet source.'
$ApplicationManifest = Get-WinGetManifest -Path $Path
if($ApplicationManifest.Count -ne 1) {
Write-Error "Failed to retrieve a proper manifest. Verify and try again."
if ($ApplicationManifest.Count -ne 1) {
Write-Error 'Failed to retrieve a proper manifest. Verify and try again.'
return
}

$Manifest = $ApplicationManifest[0]
Write-Verbose -Message "Contents of manifest have been retrieved. Package Identifier: $($Manifest.PackageIdentifier)."

Write-Verbose -Message "Confirming that the Package ID doesn't already exist in Azure for $($Manifest.PackageIdentifier)."
$ApiHeader["x-functions-key"] = $FunctionKeyGet
$ApiHeader['x-functions-key'] = $FunctionKeyGet
$AzFunctionURL = $AzFunctionURLBase + $Manifest.PackageIdentifier
$Response = Invoke-RestMethod $AzFunctionURL -Headers $ApiHeader -Method $ApiMethodGet -ErrorVariable ErrorInvoke

Expand All @@ -119,20 +116,19 @@ Function Add-WinGetManifest

$ApiMethod = $ApiMethodPost
$AzFunctionURL = $AzFunctionURLBase
$ApiHeader["x-functions-key"] = $FunctionKeyPost
}
else {
$ApiHeader['x-functions-key'] = $FunctionKeyPost
} else {
## Existing manifest retrieved, submit as update existing manifest
Write-Verbose "Found manifest that matched. Package Identifier: $($Manifest.PackageIdentifier)"

if($Response.Data.Count -gt 1) {
if ($Response.Data.Count -gt 1) {
Write-Error "Found conflicting manifests. Package Identifier: $($Manifest.PackageIdentifier)"
return
}

$ApiMethod = $ApiMethodPut
$AzFunctionURL = $AzFunctionURLBase + $Manifest.PackageIdentifier
$ApiHeader["x-functions-key"] = $FunctionKeyPut
$ApiHeader['x-functions-key'] = $FunctionKeyPut

## Merge with prior manifest
$PriorManifest = [WinGetManifest]::CreateFromObject($Response.Data[0])
Expand All @@ -144,7 +140,7 @@ Function Add-WinGetManifest

$Response = Invoke-RestMethod $AzFunctionURL -Headers $ApiHeader -Method $ApiMethod -Body $Manifest.GetJson() -ContentType $ApiContentType -ErrorVariable ErrorInvoke

if($ErrorInvoke) {
if ($ErrorInvoke) {
$ErrReturnObject = @{
AzFunctionURL = $AzFunctionURL
ApiMethod = $ApiMethod
Expand All @@ -154,21 +150,19 @@ Function Add-WinGetManifest
InvokeError = $ErrorInvoke
}

Write-Error -Message "Failed to add manifest." -TargetObject $ErrReturnObject
}
else {
Write-Error -Message 'Failed to add manifest.' -TargetObject $ErrReturnObject
} else {
if ($Response.Data.Count -ne 1) {
Write-Warning "Returned conflicting manifests after adding the manifest. Package Identifier: $($Manifest.PackageIdentifier)"
}

foreach ($ResponseData in $Response.Data){
foreach ($ResponseData in $Response.Data) {
Write-Verbose "Parsing through the returned results: $ResponseData"
$Return += [WinGetManifest]::CreateFromObject($ResponseData)
}
}
}
END
{
END {
return $Return
}
}
39 changes: 16 additions & 23 deletions Tools/PowershellModule/src/Library/Connect-ToAzure.ps1
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Function Connect-ToAzure
{
Function Connect-ToAzure {
<#
.SYNOPSIS
Connects to an Azure environment and connects to a specific Azure Subscription if a name of the subscription has been provided.
Expand Down Expand Up @@ -38,73 +37,67 @@ Function Connect-ToAzure
#>

PARAM(
[Parameter(Mandatory=$false)] [string]$SubscriptionName = "",
[Parameter(Mandatory=$false)] [string]$SubscriptionId = ""
[Parameter(Mandatory = $false)] [string]$SubscriptionName = '',
[Parameter(Mandatory = $false)] [string]$SubscriptionId = ''
)

$TestAzureConnection = $false

if($SubscriptionName -and $SubscriptionId){
if ($SubscriptionName -and $SubscriptionId) {
## If connected to Azure, and the Subscription Name and Id are provided then verify that the connected Azure session matches the provided Subscription Name and Id.
Write-Verbose -Message "Verifying if PowerShell session is currently connected to your Azure Subscription Name $SubscriptionName and Subscription Id $SubscriptionId"
$TestAzureConnection = Test-ConnectionToAzure -SubscriptionName $SubscriptionName -SubscriptionId $SubscriptionId
}
elseif($SubscriptionName){
} elseif ($SubscriptionName) {
## If connected to Azure, and the Subscription Name are provided then verify that the connected Azure session matches the provided Subscription Name.
Write-Verbose -Message "Verifying if PowerShell session is currently connected to your Azure Subscription Name $SubscriptionName"
$TestAzureConnection = Test-ConnectionToAzure -SubscriptionName $SubscriptionName
}
elseif($SubscriptionId){
} elseif ($SubscriptionId) {
## If connected to Azure, and the Subscription Id are provided then verify that the connected Azure session matches the provided Subscription Id.
Write-Verbose -Message "Verifying if PowerShell session is currently connected to your Azure Subscription Id $SubscriptionId"
$TestAzureConnection = Test-ConnectionToAzure -SubscriptionId $SubscriptionId
}
else{
Write-Information "No Subscription Name or Subscription Id provided. Will test connection to default Azure Subscription"
} else {
Write-Information 'No Subscription Name or Subscription Id provided. Will test connection to default Azure Subscription'
$TestAzureConnection = Test-ConnectionToAzure
}

Write-Verbose -Message "Test Connection Result: $TestAzureConnection"

if(!$TestAzureConnection) {
if($SubscriptionName -and $SubscriptionId) {
if (!$TestAzureConnection) {
if ($SubscriptionName -and $SubscriptionId) {
## Attempts a connection to Azure using both the Subscription Name and Subscription Id
Write-Information "Initiating a connection to your Azure Subscription Name $SubscriptionName and Subscription Id $SubscriptionId"
$ConnectResult = Connect-AzAccount -SubscriptionName $SubscriptionName -SubscriptionId $SubscriptionId

$TestAzureConnection = Test-ConnectionToAzure -SubscriptionName $SubscriptionName -SubscriptionId $SubscriptionId
}
elseif($SubscriptionName) {
} elseif ($SubscriptionName) {
## Attempts a connection to Azure using Subscription Name
Write-Information "Initiating a connection to your Azure Subscription Name $SubscriptionName"
$ConnectResult = Connect-AzAccount -SubscriptionName $SubscriptionName

$TestAzureConnection = Test-ConnectionToAzure -SubscriptionName $SubscriptionName
}
elseif($SubscriptionId) {
} elseif ($SubscriptionId) {
## Attempts a connection to Azure using Subscription Id
Write-Information "Initiating a connection to your Azure Subscription Id $SubscriptionId"
$ConnectResult = Connect-AzAccount -SubscriptionId $SubscriptionId

$TestAzureConnection = Test-ConnectionToAzure -SubscriptionId $SubscriptionId
}
else{
} else {
## Attempts a connection to Azure with the users default Subscription
Write-Information "Initiating a connection to your Azure environment."
Write-Information 'Initiating a connection to your Azure environment.'
$ConnectResult = Connect-AzAccount

$TestAzureConnection = Test-ConnectionToAzure
}

if(!$TestAzureConnection) {
if (!$TestAzureConnection) {
## If the connection fails, or the user cancels the login request, then return as failed.
$ErrReturnObject = @{
SubscriptionName = $SubscriptionName
SubscriptionId = $SubscriptionId
AzureConnected = $TestAzureConnection
}

Write-Error -Message "Failed to connect to Azure" -TargetObject $ErrReturnObject
Write-Error -Message 'Failed to connect to Azure' -TargetObject $ErrReturnObject
}
}

Expand Down
Loading