Skip to content

Commit 46d16fa

Browse files
authored
Address AutoREST byRef preposition truncation (#915)
* Tweak ByRef OperationId. * Download OpenAPI docs. * Move logic to tweak OpenAPI files to a new files. * Update readme.graph.md * Read files on our own to reduce read time. * Fix debug formatting * Add _top and _count placeholders if not present. * Update group directives * Move regex pattern outside the loop
1 parent 8b12b0c commit 46d16fa

5 files changed

Lines changed: 74 additions & 19 deletions

File tree

src/DeviceManagement/DeviceManagement/readme.md

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,9 +60,18 @@ directive:
6060
- where:
6161
subject: ^(DeviceManagementUserExperienceAnalyticAppHealthApplicationPerformance)$
6262
variant: ^Create2$|^CreateExpanded2$|^Get2$|^GetViaIdentity2$|^List2$|^Delete2$|^DeleteViaIdentity2$|^Update2$|^UpdateExpanded2$|^UpdateViaIdentity2$|^UpdateViaIdentityExpanded2$
63+
set:
64+
subject: $1ByAppVersionDetail
65+
- where:
66+
subject: ^(DeviceManagementUserExperienceAnalyticAppHealthApplicationPerformance)$
67+
variant: ^Create3$|^CreateExpanded3$|^Get3$|^GetViaIdentity3$|^List3$|^Delete3$|^DeleteViaIdentity3$|^Update3$|^UpdateExpanded3$|^UpdateViaIdentity3$|^UpdateViaIdentityExpanded3$
68+
set:
69+
subject: $1ByAppVersionDeviceId
70+
- where:
71+
subject: ^(DeviceManagementUserExperienceAnalyticAppHealthApplicationPerformance)$
72+
variant: ^Create4$|^CreateExpanded4$|^Get4$|^GetViaIdentity4$|^List4$|^Delete4$|^DeleteViaIdentity4$|^Update4$|^UpdateExpanded4$|^UpdateViaIdentity4$|^UpdateViaIdentityExpanded4$
6373
set:
6474
subject: $1ByOSVersion
65-
6675
- where:
6776
subject: ^(DeviceManagementAndroid)$
6877
variant: ^Create$|^CreateExpanded$|^Get$|^GetViaIdentity$|^List$|^Delete$|^DeleteViaIdentity$|^Update$|^UpdateExpanded$|^UpdateViaIdentity$|^UpdateViaIdentityExpanded$

src/readme.graph.md

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -405,11 +405,7 @@ directive:
405405
variant: ^(Check|Verify)(.*)
406406
set:
407407
verb: Confirm
408-
# Rename all /$ref cmdlets to *ByRef e.g. New-MgGroupOwnerByRef
409-
- from: 'openapi-document'
410-
where: $.paths..operationId
411-
transform: |
412-
return ($.endsWith("ByRef")) ? $.replace("_", "GraphRef_") : $
408+
# Add ByRef suffix to /$ref cmdlets
413409
- where:
414410
subject: ^(\w*[a-z])GraphRef([A-Z]\w*)$
415411
set:
@@ -423,19 +419,19 @@ directive:
423419
- where:
424420
verb: Get|New
425421
subject: ^GroupMemberByRef$
426-
variant: ^List$|^Create$|^CreateExpanded$|^CreateViaIdentity$|^CreateViaIdentityExpanded$|^List3$|^Create3$|^CreateExpanded3$|^CreateViaIdentity3$|^CreateViaIdentityExpanded3$
422+
variant: ^List2$|^Create2$|^CreateExpanded2$|^CreateViaIdentity2$|^CreateViaIdentityExpanded2$|^List5$|^Create5$|^CreateExpanded5$|^CreateViaIdentity5$|^CreateViaIdentityExpanded5$
427423
set:
428424
subject: GroupMemberOfByRef
429425
- where:
430426
verb: Get|New
431427
subject: ^GroupMemberByRef$
432-
variant: ^List2$|^Create2$|^CreateExpanded2$|^CreateViaIdentity2$|^CreateViaIdentityExpanded2$|^List5$|^Create5$|^CreateExpanded5$|^CreateViaIdentity5$|^CreateViaIdentityExpanded5$
428+
variant: ^List1$|^Create1$|^CreateExpanded1$|^CreateViaIdentity1$|^CreateViaIdentityExpanded1$|^List4$|^Create4$|^CreateExpanded4$|^CreateViaIdentity4$|^CreateViaIdentityExpanded4$
433429
set:
434430
subject: GroupMemberWithLicenseErrorByRef
435431
- where:
436-
verb: Get
432+
verb: Get|New
437433
subject: ^GroupTransitiveMemberByRef$
438-
variant: ^List$|^List2$
434+
variant: ^List$|^List2$|^Create$|^Create2$|^CreateExpanded$|^CreateExpanded2$|^CreateViaIdentity$|^CreateViaIdentity2$|^CreateViaIdentityExpanded$|^CreateViaIdentityExpanded2$
439435
set:
440436
subject: GroupTransitiveMemberOfByRef
441437
# Alias then rename cmdlets to avoid breaking change.
@@ -558,7 +554,9 @@ directive:
558554
$ = $.replace(psBaseClassImplementationRegex, '$1Microsoft.Graph.PowerShell.Cmdlets.Custom.ListCmdlet');
559555
560556
let beginProcessingRegex = /(^\s*)(protected\s*override\s*void\s*BeginProcessing\(\)\s*{)/gmi
561-
$ = $.replace(beginProcessingRegex, '$1$2\n$1 if (this.InvocationInformation?.BoundParameters != null){ InitializeCmdlet(ref this.__invocationInfo, ref this._top, ref this._count); }\n$1');
557+
let topPlaceholder = (!$.includes("private int _top;")) ? 'int _top = default;': ''
558+
let countPlaceholder = (!$.includes("SwitchParameter _count;")) ? 'global::System.Management.Automation.SwitchParameter _count;': ''
559+
$ = $.replace(beginProcessingRegex, `$1$2\n$1 ${countPlaceholder} ${topPlaceholder} if (this.InvocationInformation?.BoundParameters != null){ InitializeCmdlet(ref this.__invocationInfo, ref _top, ref _count); }\n$1`);
562560
563561
let odataNextLinkCallRegex = /(^\s*)(await\s*this\.Client\.UsersUserListUser_Call\(requestMessage\,\s*onOk\,\s*onDefault\,\s*this\,\s*Pipeline\)\;)/gmi
564562
$ = $.replace(odataNextLinkCallRegex, '$1requestMessage.RequestUri = GetOverflowItemsNextLinkUri(requestMessage.RequestUri);\n$1$2');

tools/DownloadOpenApiDoc.ps1

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
[CmdletBinding()]
12
Param(
23
[string] $ModuleName,
34
[string] $ModuleRegex,
@@ -10,13 +11,13 @@ Param(
1011
if (-not (Test-Path $OpenApiDocOutput)) {
1112
New-Item -Path $OpenApiDocOutput -Type Directory
1213
}
13-
14+
1415
$OpenApiBaseUrl = "https://graphexplorerapi.azurewebsites.net"
1516
$OpenApiServiceUrl = ("$OpenApiBaseUrl/`$openapi?tags={0}&title=$ModuleName&openapiversion=3&style=Powershell&graphVersion=$GraphVersion" -f $ModuleRegex)
1617
if ($ForceRefresh.IsPresent) {
1718
$OpenApiServiceUrl = "$OpenApiServiceUrl&forceRefresh=true"
1819
}
19-
Write-Host -ForegroundColor Green "[$RequestCount] Downloading OpenAPI doc for '$ModuleName' module: $OpenApiServiceUrl"
20+
Write-Debug "[$RequestCount] Downloading OpenAPI doc for '$ModuleName' module: $OpenApiServiceUrl"
2021
$Retries = 3
2122
$Delay = 3
2223
$Retrycount = 0
@@ -45,7 +46,7 @@ while (-not $Completed) {
4546
$mPow = [math]::Pow(2, $Retrycount)
4647
$DelayInSeconds = $mPow * $Delay
4748
}
48-
49+
4950
Write-Warning "Request to $OpenApiServiceUrl failed. Retrying in $DelayInSeconds seconds."
5051
Start-Sleep $DelayInSeconds
5152
$Retrycount++

tools/TweakOpenApi.ps1

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Copyright (c) Microsoft Corporation. All rights reserved.
2+
# Licensed under the MIT License.
3+
[CmdletBinding()]
4+
Param(
5+
[Parameter(Mandatory = $true)]
6+
[ValidateNotNullOrEmpty()]
7+
[string] $OpenAPIFilesPath
8+
)
9+
10+
$TargetWord = "ByRef"
11+
$ReplacementWord = "GraphRef"
12+
$actionPattern = [Regex]::new("(_[A-Z][a-z]+)", "Compiled")
13+
$Stopwatch = [system.diagnostics.stopwatch]::StartNew()
14+
Get-ChildItem -Path $OpenAPIFilesPath | ForEach-Object {
15+
$filePath = $_.FullName
16+
$modified = $false
17+
$updatedContent = Get-Content $filePath | ForEach-Object {
18+
# Tweak '/$ref' operationIds (*ByRef) to byPass -> https://github.com/Azure/autorest.powershell/issues/795.
19+
if ($_.endsWith($TargetWord) -and $_.contains("operationId:")) {
20+
$operationId = $_
21+
# Matches '_{ActionName}' in operationIds formatted as '{entitySet}_{ActionName}{NavigationProperty}'. e.g.,
22+
# For 'applications_GetCreatedOnBehalfOfByRef', we will match '_Get'.
23+
$match = $actionPattern.Match($operationId)
24+
if ($null -ne $match -and $match.Success) {
25+
$operationId = $operationId.Replace($TargetWord, "")
26+
# Suffix matched '_{ActionName}' with 'GraphRef'. GraphRef will be our safe unique word for identifying *ByRef commands in PowerShell e.g.,
27+
# 'applications_GetCreatedOnBehalfOfByRef' will be renamed to 'applications_GetGraphRefCreatedOnBehalfOf'.
28+
$operationId = ($operationId -replace $match.Value, "$($match.Value)$ReplacementWord")
29+
$modified = $true
30+
}
31+
return $operationId
32+
}
33+
return $_
34+
}
35+
if ($modified) { $updatedContent | Out-File $filePath -Force }
36+
}
37+
$stopwatch.Stop()
38+
Write-Debug "Tweaked '$OpenAPIFilesPath' OpenAPI files in '$($Stopwatch.Elapsed.TotalMinutes)' minutes."

tools/UpdateOpenApi.ps1

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# Copyright (c) Microsoft Corporation. All rights reserved.
22
# Licensed under the MIT License.
3+
[CmdletBinding()]
34
Param(
45
[string] $ModuleMappingConfigPath = (Join-Path $PSScriptRoot "..\config\ModulesMapping.jsonc"),
56
[string] $OpenApiDocOutput = (Join-Path $PSScriptRoot "..\openApiDocs"),
@@ -11,8 +12,11 @@ $LASTEXITCODE = $null
1112
if ($PSEdition -ne 'Core') {
1213
Write-Error 'This script requires PowerShell Core to execute. [Note] Generated cmdlets will work in both PowerShell Core or Windows PowerShell.'
1314
}
14-
# Install Powershell-yaml
15-
Install-Module powershell-yaml -Force
15+
16+
if (!(Get-Module powershell-yaml -ListAvailable)){
17+
# Install Powershell-yaml
18+
Install-Module powershell-yaml -Force
19+
}
1620

1721
$GraphVersion = "v1.0"
1822
if ($BetaGraphVersion) {
@@ -21,15 +25,16 @@ if ($BetaGraphVersion) {
2125

2226
$OpenApiDocOutput = Join-Path $OpenApiDocOutput $GraphVersion
2327

24-
# PS Scripts
28+
# Load PS Scripts
2529
$DownloadOpenApiDocPS1 = Join-Path $PSScriptRoot ".\DownloadOpenApiDoc.ps1" -Resolve
30+
$TweakOpenApiPs1 = Join-Path $PSScriptRoot ".\TweakOpenApi.ps1" -Resolve
2631

2732
if (-not (Test-Path $ModuleMappingConfigPath)) {
2833
Write-Error "Module mapping file not be found: $ModuleMappingConfigPath."
2934
}
30-
35+
$Stopwatch = [system.diagnostics.stopwatch]::StartNew()
3136
[HashTable] $ModuleMapping = Get-Content $ModuleMappingConfigPath | ConvertFrom-Json -AsHashTable
32-
$ModuleMapping.Keys | ForEach-Object -Begin { $RequestCount = 0 } -End { Write-Host -ForeGroundColor Green "Requests: $RequestCount" } -Process {
37+
$ModuleMapping.Keys | ForEach-Object -Begin { $RequestCount = 0 } -End { Write-Debug "Requests: $RequestCount" } -Process {
3338
$ModuleName = $_
3439
$ForceRefresh = $false
3540
# Check whether ForceRefresh is required, Only required for the First Request.
@@ -46,5 +51,9 @@ $ModuleMapping.Keys | ForEach-Object -Begin { $RequestCount = 0 } -End { Write-H
4651
}
4752
$RequestCount++
4853
}
54+
$stopwatch.Stop()
55+
Write-Debug "Downloaded $GraphVersion OpenAPI files in '$($Stopwatch.Elapsed.TotalMinutes)` minutes."
4956

57+
# Tweak OperationIds to address known AutoREST.PowerShell limitations.
58+
. $TweakOpenApiPs1 -OpenAPIFilesPath $OpenApiDocOutput
5059
Write-Host -ForegroundColor Green "-------------Done-------------"

0 commit comments

Comments
 (0)