diff --git a/.azure-pipelines/generation-pipeline.yml b/.azure-pipelines/generation-pipeline.yml index dfbcfb226..e5ea76083 100644 --- a/.azure-pipelines/generation-pipeline.yml +++ b/.azure-pipelines/generation-pipeline.yml @@ -155,6 +155,13 @@ variables: cleanOpenAPIFolderV1: 'clean_v10_openapi' rawMetadataFileBeta: '$(Build.SourcesDirectory)/msgraph-metadata/schemas/beta-Prod.csdl' rawMetadataFileV1: '$(Build.SourcesDirectory)/msgraph-metadata/schemas/v1.0-Prod.csdl' + rawMetadataFileFairfaxV1: '$(Build.SourcesDirectory)/msgraph-metadata/schemas/v1.0-Fairfax.csdl' + cleanMetadataFolderFairfaxV1: 'clean_v10_fairfax_metadata' + cleanMetadataFileFairfaxV1OutputPath: '$(Build.SourcesDirectory)/msgraph-metadata/clean_v10_fairfax_metadata/' + cleanMetadataFileFairfaxV1: '$(Build.SourcesDirectory)/msgraph-metadata/clean_v10_fairfax_metadata/cleanMetadataWithDescriptionsv1.0.xml' + cleanMetadataFileWithAnnotationsFairfaxV1: '$(Build.SourcesDirectory)/msgraph-metadata/clean_v10_fairfax_metadata/cleanMetadataWithDescriptionsAndAnnotationsv1.0.xml' + cleanOpenAPIFolderFairfaxV1: 'clean_v10_fairfax_openapi' + cleanOpenAPIFileFairfaxV1OutputPath: '$(Build.SourcesDirectory)/msgraph-metadata/openapi/fairfax/v1.0/' typewriterDirectory: '$(Build.SourcesDirectory)/typewriter' kiotaDirectory: '$(Build.SourcesDirectory)/kiota' typewriterExecutable: '$(typewriterDirectory)/Typewriter' @@ -283,6 +290,54 @@ extends: cleanMetadataFileWithAnnotations: $(cleanMetadataFileWithAnnotationsBeta) metadataTypeSpecAnnotationsSource: $(metadataTypeSpecAnnotationsSource) + - stage: stage_fairfax_v1_metadata + dependsOn: stage_build_and_publish_typewriter + condition: | + and(succeeded('stage_build_and_publish_typewriter'), + eq( ${{ parameters.skipMetadataCaptureAndClean }}, false)) + jobs: + - job: fairfax_v1_metadata + templateContext: + outputs: + - output: pipelineArtifact + targetPath: '$(Build.ArtifactStagingDirectory)' + artifactName: $(cleanMetadataFolderFairfaxV1) + inputs: + - input: pipelineArtifact + buildType: 'current' + artifactName: 'typewriter' + targetPath: '$(Build.SourcesDirectory)/typewriter' + steps: + - template: /.azure-pipelines/generation-templates/capture-metadata.yml@self + parameters: + endpoint: 'v1.0' + cloud: Fairfax + inputMetadata: $(rawMetadataFileFairfaxV1) + outputPath: $(cleanMetadataFileFairfaxV1OutputPath) + cleanMetadataFile: $(cleanMetadataFileFairfaxV1) + cleanMetadataFolder: $(cleanMetadataFolderFairfaxV1) + cleanMetadataFileWithAnnotations: $(cleanMetadataFileWithAnnotationsFairfaxV1) + metadataTypeSpecAnnotationsSource: $(metadataTypeSpecAnnotationsSource) + + - stage: stage_fairfax_v1_openapi + dependsOn: stage_fairfax_v1_metadata + condition: and(in(dependencies.stage_fairfax_v1_metadata.result, 'Succeeded', 'Skipped'), eq( ${{ parameters.skipOpenApiCaptureAndClean }}, false)) + jobs: + - template: /.azure-pipelines/generation-templates/capture-openapi.yml@self + parameters: + endpoint: 'v1.0' + cloud: Fairfax + outputPath: $(cleanOpenAPIFileFairfaxV1OutputPath) + cleanMetadataFolder: $(cleanOpenAPIFolderFairfaxV1) + ${{ if eq(parameters.skipMetadataCaptureAndClean, false) }}: + metadataArtifact: $(cleanMetadataFolderFairfaxV1) + metadataDirectory: '$(Pipeline.Workspace)/$(cleanMetadataFolderFairfaxV1)' + ${{ else }}: + metadataDirectory: $(cleanMetadataFileFairfaxV1OutputPath) + serviceRoot: 'https://graph.microsoft.us/v1.0' + publishPath: 'openapi/fairfax/v1.0' + skipOpenAPIPRGeneration: ${{ parameters.skipOpenAPIPRGeneration }} + - stage: stage_v1_openapi dependsOn: stage_v1_metadata condition: and(in(dependencies.stage_v1_metadata.result, 'Succeeded', 'Skipped'), eq( ${{ parameters.skipOpenApiCaptureAndClean }}, false)) diff --git a/.azure-pipelines/generation-templates/capture-metadata.yml b/.azure-pipelines/generation-templates/capture-metadata.yml index 9843847c1..f26da7fbd 100644 --- a/.azure-pipelines/generation-templates/capture-metadata.yml +++ b/.azure-pipelines/generation-templates/capture-metadata.yml @@ -31,6 +31,9 @@ parameters: - name: metadataAnnotationsCopyScriptPath type: string default: '/../scripts/copy-annotations-to-csdl.ps1' +- name: cloud + type: string + default: Prod steps: @@ -97,7 +100,7 @@ steps: endpointVersion: ${{ parameters.endpoint }} displayName: 'run Typewriter to clean ${{ parameters.endpoint }} metadata' -- pwsh: '. $(metadataTypeSpecAnnotationsSource)/$Env:ScriptPath -targetCsdlPath "$(Build.SourcesDirectory)/msgraph-metadata/clean_$($Env:Endpoint.Replace(''.'', ''''))_metadata/cleanMetadataWithDescriptions${{ parameters.endpoint }}.xml" -sourceCsdlDirectoryPath "$(metadataTypeSpecAnnotationsSource)/${{ parameters.metadataTypeSpecAnnotationsOutputDir }}"' +- pwsh: '. $(metadataTypeSpecAnnotationsSource)/$Env:ScriptPath -targetCsdlPath "${{ parameters.cleanMetadataFile }}" -sourceCsdlDirectoryPath "$(metadataTypeSpecAnnotationsSource)/${{ parameters.metadataTypeSpecAnnotationsOutputDir }}"' env: ScriptPath: ${{ parameters.metadataAnnotationsCopyScriptPath }} Endpoint: ${{ parameters.endpoint }} @@ -118,7 +121,7 @@ steps: OutputMetadataFileName: 'cleanMetadataWithDescriptionsAndAnnotations' displayName: 'run Typewriter to clean ${{ parameters.endpoint }} metadata and keep capability annotations' -- pwsh: '. $(metadataTypeSpecAnnotationsSource)/$Env:ScriptPath -targetCsdlPath "$(Build.SourcesDirectory)/msgraph-metadata/clean_$($Env:Endpoint.Replace(''.'', ''''))_metadata/cleanMetadataWithDescriptionsAndAnnotations${{ parameters.endpoint }}.xml" -sourceCsdlDirectoryPath "$(metadataTypeSpecAnnotationsSource)/${{ parameters.metadataTypeSpecAnnotationsOutputDir }}"' +- pwsh: '. $(metadataTypeSpecAnnotationsSource)/$Env:ScriptPath -targetCsdlPath "${{ parameters.cleanMetadataFileWithAnnotations }}" -sourceCsdlDirectoryPath "$(metadataTypeSpecAnnotationsSource)/${{ parameters.metadataTypeSpecAnnotationsOutputDir }}"' env: ScriptPath: ${{ parameters.metadataAnnotationsCopyScriptPath }} Endpoint: ${{ parameters.endpoint }} @@ -140,7 +143,7 @@ steps: OutputMetadataFileName: 'cleanMetadataWithDescriptionsAndAnnotationsAndErrors' displayName: 'run Typewriter to clean ${{ parameters.endpoint }} metadata and keep capability annotations and include error information' -- pwsh: '. $(metadataTypeSpecAnnotationsSource)/$Env:ScriptPath -targetCsdlPath "$(Build.SourcesDirectory)/msgraph-metadata/clean_$($Env:Endpoint.Replace(''.'', ''''))_metadata/cleanMetadataWithDescriptionsAndAnnotationsAndErrors${{ parameters.endpoint }}.xml" -sourceCsdlDirectoryPath "$(metadataTypeSpecAnnotationsSource)/${{ parameters.metadataTypeSpecAnnotationsOutputDir }}"' +- pwsh: '. $(metadataTypeSpecAnnotationsSource)/$Env:ScriptPath -targetCsdlPath "${{ parameters.outputPath }}/cleanMetadataWithDescriptionsAndAnnotationsAndErrors${{ parameters.endpoint }}.xml" -sourceCsdlDirectoryPath "$(metadataTypeSpecAnnotationsSource)/${{ parameters.metadataTypeSpecAnnotationsOutputDir }}"' env: ScriptPath: ${{ parameters.metadataAnnotationsCopyScriptPath }} Endpoint: ${{ parameters.endpoint }} @@ -162,12 +165,22 @@ steps: displayName: 'Install hidi tool' # verify that generated metadata is parsable as an Edm model -- pwsh: $(Build.SourcesDirectory)/msgraph-metadata/scripts/run-metadata-validation.ps1 -repoDirectory "$(Build.SourcesDirectory)/msgraph-metadata/" -version "${{ parameters.endpoint }}" - displayName: 'verify whether metadata is parsable as an Edm model' +- ${{ if eq(parameters.cloud, 'Prod') }}: + - pwsh: $(Build.SourcesDirectory)/msgraph-metadata/scripts/run-metadata-validation.ps1 -repoDirectory "$(Build.SourcesDirectory)/msgraph-metadata/" -version "${{ parameters.endpoint }}" + displayName: 'verify whether metadata is parsable as an Edm model' # clean up extra files -- pwsh: Remove-Item "$(Build.SourcesDirectory)/msgraph-metadata/transformed_*_metadata.*" -Verbose -Force - displayName: 'clean up transformed metadata generated by validation' + - pwsh: Remove-Item "$(Build.SourcesDirectory)/msgraph-metadata/transformed_*_metadata.*" -Verbose -Force + displayName: 'clean up transformed metadata generated by validation' + +- ${{ if ne(parameters.cloud, 'Prod') }}: + - pwsh: | + $validationOutput = "$(Agent.TempDirectory)/${{ parameters.cloud }}-${{ parameters.endpoint }}-validation.yaml" + hidi transform --csdl "${{ parameters.outputPath }}/cleanMetadataWithDescriptionsAndAnnotationsAndErrors${{ parameters.endpoint }}.xml" --output $validationOutput --co --format yaml --settings-path "$(conversionSettingsDirectory)/openapi.json" + if ($LASTEXITCODE -ne 0) { + throw "Metadata validation failed with exit code $LASTEXITCODE." + } + displayName: 'validate cleaned ${{ parameters.cloud }} ${{ parameters.endpoint }} metadata' # Checkin clean metadata into metadata repo or make it an artifact. - pwsh: '$(scriptsDirectory)/git-push-cleanmetadata.ps1' @@ -176,5 +189,8 @@ steps: CreateOpenAPIPR: False EndpointVersion: ${{ parameters.endpoint }} PublishChanges: $(publishChanges) + ${{ if ne(parameters.cloud, 'Prod') }}: + PublishPath: ${{ parameters.cleanMetadataFolder }} + PublicationIdentifier: '${{ parameters.cloud }}/${{ parameters.endpoint }}' workingDirectory: '$(Build.SourcesDirectory)/msgraph-metadata' enabled: true diff --git a/.azure-pipelines/generation-templates/capture-openapi.yml b/.azure-pipelines/generation-templates/capture-openapi.yml index 4e75b4946..0cd65816a 100644 --- a/.azure-pipelines/generation-templates/capture-openapi.yml +++ b/.azure-pipelines/generation-templates/capture-openapi.yml @@ -14,6 +14,21 @@ parameters: type: string - name: 'skipOpenAPIPRGeneration' type: boolean +- name: cloud + type: string + default: Prod +- name: metadataDirectory + type: string + default: '' +- name: metadataArtifact + type: string + default: '' +- name: serviceRoot + type: string + default: '' +- name: publishPath + type: string + default: '' jobs: - job: get_conversion_settings displayName: "Get conversion settings" @@ -34,6 +49,9 @@ jobs: $name = $f.Name.replace('.json','') $data = @{"File"=$f.Name;"Name"=$name;} $key = "$endpoint-$name" + if ("${{ parameters.cloud }}" -ne "Prod") { + $key = "${{ parameters.cloud }}-$key" + } $jsonBase.Add($key,$data) } $json = $jsonBase | ConvertTo-Json -Compress @@ -50,6 +68,12 @@ jobs: variables: targets: $[ dependencies.get_conversion_settings.outputs['setTargets.targets'] ] templateContext: + ${{ if ne(parameters.metadataArtifact, '') }}: + inputs: + - input: pipelineArtifact + buildType: current + artifactName: ${{ parameters.metadataArtifact }} + targetPath: '$(Pipeline.Workspace)/${{ parameters.metadataArtifact }}' outputs: - output: pipelineArtifact targetPath: '$(Build.ArtifactStagingDirectory)/$(Name)' @@ -79,14 +103,30 @@ jobs: - pwsh: | git fetch origin master + if ($LASTEXITCODE -ne 0) { + throw "Failed to fetch metadata master." + } git switch master + if ($LASTEXITCODE -ne 0) { + throw "Failed to switch to metadata master." + } displayName: ensure the generation happens from master latest workingDirectory: $(Build.SourcesDirectory)/msgraph-metadata - pwsh: | Write-Host "`ngit status before generation:" git status - $(scriptsDirectory)/generate-open-api.ps1 -endpointVersion ${{ parameters.endpoint }} -settings "$(conversionSettingsDirectory)/$(File)" -platformName "$(Name)" + $arguments = @{ + endpointVersion = "${{ parameters.endpoint }}" + settings = "$(conversionSettingsDirectory)/$(File)" + platformName = "$(Name)" + } + if ("${{ parameters.cloud }}" -ne "Prod") { + $arguments.metadataDirectory = "${{ parameters.metadataDirectory }}" + $arguments.outputDirectory = "${{ parameters.outputPath }}" + $arguments.serviceRoot = "${{ parameters.serviceRoot }}" + } + & "$(scriptsDirectory)/generate-open-api.ps1" @arguments Write-Host "`ngit status after generation:" git status displayName: 'generate ${{ parameters.endpoint }} open API description' @@ -100,10 +140,19 @@ jobs: targetFolder: '$(Build.ArtifactStagingDirectory)/$(Name)' displayName: Copy generated OpenAPI yaml file to ArtifactStagingDirectory - - pwsh: | - ./scripts/run-openapi-validation.ps1 -repoDirectory (Get-Location).Path -version "${{ parameters.endpoint }}" -platformName "$(Name)" - displayName: Validate that OpenAPI docs can be parsed - workingDirectory: $(Build.SourcesDirectory)/msgraph-metadata + - ${{ if eq(parameters.cloud, 'Prod') }}: + - pwsh: | + ./scripts/run-openapi-validation.ps1 -repoDirectory (Get-Location).Path -version "${{ parameters.endpoint }}" -platformName "$(Name)" + displayName: Validate that OpenAPI docs can be parsed + workingDirectory: $(Build.SourcesDirectory)/msgraph-metadata + - ${{ if ne(parameters.cloud, 'Prod') }}: + - pwsh: | + hidi validate -d "${{ parameters.outputPath }}/$(Name).yaml" + if ($LASTEXITCODE -ne 0) { + throw "OpenAPI validation failed with exit code $LASTEXITCODE." + } + displayName: Validate that ${{ parameters.cloud }} OpenAPI docs can be parsed + workingDirectory: $(Build.SourcesDirectory)/msgraph-metadata - job: publish_openapi dependsOn: convert_openapi @@ -153,18 +202,27 @@ jobs: inputs: sourceFolder: '$(Build.ArtifactStagingDirectory)' contents: '**/*.yaml' - targetFolder: '$(Build.SourcesDirectory)/msgraph-metadata/openapi/${{ parameters.endpoint }}' + ${{ if eq(parameters.cloud, 'Prod') }}: + targetFolder: '$(Build.SourcesDirectory)/msgraph-metadata/openapi/${{ parameters.endpoint }}' + ${{ else }}: + targetFolder: ${{ parameters.outputPath }} overwrite: true displayName: Copy OpenAPI files to local msgraph-metadata repo # Push changes to msgraph-metadata repo - pwsh: '$(scriptsDirectory)/git-push-cleanmetadata.ps1' - condition: eq('${{ parameters.skipOpenAPIPRGeneration }}', false) + ${{ if eq(parameters.cloud, 'Prod') }}: + condition: eq('${{ parameters.skipOpenAPIPRGeneration }}', false) + ${{ else }}: + condition: and(succeeded(), eq('${{ parameters.skipOpenAPIPRGeneration }}', false)) displayName: Publish ${{ parameters.endpoint }} OpenAPI description to msgraph-metadata repo env: CreateOpenAPIPR: True EndpointVersion: ${{ parameters.endpoint }} PublishChanges: $(publishChanges) + ${{ if ne(parameters.cloud, 'Prod') }}: + PublishPath: ${{ parameters.publishPath }} + PublicationIdentifier: '${{ parameters.cloud }}/${{ parameters.endpoint }}' workingDirectory: '$(Build.SourcesDirectory)/msgraph-metadata' enabled: true @@ -174,13 +232,18 @@ jobs: - task: AzureKeyVault@2 displayName: "Azure Key Vault: Get Secrets" + ${{ if ne(parameters.cloud, 'Prod') }}: + condition: and(succeeded(), eq('${{ parameters.skipOpenAPIPRGeneration }}', false), eq(variables.publishChanges, true), eq(variables.publicationHasChanges, true)) inputs: azureSubscription: "Federated AKV Managed Identity Connection" KeyVaultName: akv-prod-eastus SecretsFilter: "microsoft-graph-devx-bot-appid,microsoft-graph-devx-bot-privatekey" - pwsh: '$(scriptsDirectory)/create-pull-request.ps1' - condition: eq('${{ parameters.skipOpenAPIPRGeneration }}', false) + ${{ if eq(parameters.cloud, 'Prod') }}: + condition: eq('${{ parameters.skipOpenAPIPRGeneration }}', false) + ${{ else }}: + condition: and(succeeded(), eq('${{ parameters.skipOpenAPIPRGeneration }}', false), eq(variables.publishChanges, true), eq(variables.publicationHasChanges, true)) displayName: 'Create Pull Request for the generated OpenAPI files for msgraph-metadata' env: BaseBranch: master @@ -190,6 +253,10 @@ jobs: OverrideSkipCI: false RepoName: 'microsoftgraph/msgraph-metadata' ScriptsDirectory: $(scriptsDirectory) - # Version is intentionally left empty for OpenAPI PRs as versioning is not applicable in this context. - Version: '' + # Prod retains its existing title; Fairfax is labelled to distinguish its discovery PR. + ${{ if eq(parameters.cloud, 'Prod') }}: + Version: '' + ${{ else }}: + Version: '${{ parameters.cloud }} ${{ parameters.endpoint }}' + BranchName: 'publish-open-api-files/$(Build.BuildId)/${{ parameters.cloud }}/${{ parameters.endpoint }}' workingDirectory: '$(Build.SourcesDirectory)/msgraph-metadata' \ No newline at end of file diff --git a/README.md b/README.md index 9ec30a812..45d9024c8 100755 --- a/README.md +++ b/README.md @@ -83,6 +83,16 @@ The output C# code files will go in to the `output` directory. - Prerequisite is that `msgraph-metadata` is checked out at the same root folder as `MSGraph-SDK-Code-Generator`. - `launch.json` file contains main generation scenarios for each language/endpoint pair. Running Typewriter using one of those generation scenarios (e.g. `Generate TypeScript beta`) will output the corresponding models into a folder, which will be a sibling to `MSGraph-SDK-Code-Generator`. The folder will be named as `generator-output--` e.g. `generator-output-TypeScript-beta`. +## Generator pipeline + +`.azure-pipelines/generation-pipeline.yml` cleans CSDL and generates OpenAPI descriptions for Prod v1.0, Prod beta, and Fairfax v1.0. Fairfax uses `schemas/v1.0-Fairfax.csdl` from `microsoftgraph/msgraph-metadata`, the same Typewriter transforms, documentation and TypeSpec annotations, and Hidi conversion profiles (`default`, `graphexplorer`, `openapi`, and `powershell_v2`) as Prod. + +Fairfax cleaned CSDL is published under `clean_v10_fairfax_metadata`; OpenAPI descriptions are published under `openapi/fairfax/v1.0` with the service URL `https://graph.microsoft.us/v1.0`. Its pipeline artifacts are `clean_v10_fairfax_metadata` and `clean_v10_fairfax_openapi` (plus one OpenAPI artifact per profile). The OpenAPI stage consumes the current run's cleaned CSDL artifact even when publication is disabled. No Fairfax SDK generation stages are included. + +The existing `skipMetadataCaptureAndClean`, `skipOpenApiCaptureAndClean`, `publishChanges`, and `skipOpenAPIPRGeneration` controls also apply to Fairfax. Skipping metadata capture requires previously published Fairfax cleaned CSDL in the metadata repository. Cleaned CSDL is pushed to metadata master; OpenAPI publication uses a separate `publish-open-api-files//Fairfax/v1.0` discovery PR branch. As with Prod, manual runs skip discovery PR creation. `publishChanges: false` produces artifacts without publishing Fairfax changes or creating its PR. + +Run the focused generation and publication regression checks with `pwsh -File test/scripts/FairfaxPipeline.Tests.ps1`. Hidi is mocked for these checks; publication uses temporary local Git repositories. + ## Use Typewriter to test your beta metadata We assume that the metadata you are using is based off the beta metadata file. diff --git a/scripts/generate-open-api.ps1 b/scripts/generate-open-api.ps1 index 1788e484b..40d27ee6d 100644 --- a/scripts/generate-open-api.ps1 +++ b/scripts/generate-open-api.ps1 @@ -13,19 +13,40 @@ # #.Parameter platformName # Specifies the file name of the configuration settings used to transform the csdl. Will be used to separate the different output folders +# +#.Parameter metadataDirectory +# Overrides the directory containing cleaned CSDL for a non-production cloud. +# +#.Parameter outputDirectory +# Overrides the directory containing generated OpenAPI descriptions. +# +#.Parameter serviceRoot +# Overrides the service URL used in place of the localhost placeholder. #> param( [parameter(Mandatory = $true)][String]$endpointVersion, [parameter(Mandatory = $true)][String]$settings, - [parameter(Mandatory = $true)][String]$platformName + [parameter(Mandatory = $true)][String]$platformName, + [String]$metadataDirectory, + [String]$outputDirectory, + [String]$serviceRoot ) Write-Host "Starting $endpointVersion OpenAPI generation for $platformName using generate-open-api.ps1" -$outputFile = Join-Path "./" "openapi" $endpointVersion "$platformName.yaml" -$oldOutputFile = "$outputFile.old" $cleanVersion = $endpointVersion.Replace(".", "") +if ([String]::IsNullOrWhiteSpace($metadataDirectory)) { + $metadataDirectory = Join-Path "./" "clean_$($cleanVersion)_metadata" +} +if ([String]::IsNullOrWhiteSpace($outputDirectory)) { + $outputDirectory = Join-Path "./" "openapi" $endpointVersion +} +if ([String]::IsNullOrWhiteSpace($serviceRoot)) { + $serviceRoot = "https://graph.microsoft.com/$endpointVersion" +} +$outputFile = Join-Path $outputDirectory "$platformName.yaml" +$oldOutputFile = "$outputFile.old" # The clean metadata file name is different for openapi and other versions $baseFileName = "cleanMetadataWithDescriptionsAndAnnotations"; @@ -35,7 +56,8 @@ if($platformName -eq "openapi") } $fileName = "$baseFileName$endpointVersion.xml"; -$inputFile = Join-Path "./" "clean_$($cleanVersion)_metadata" "$fileName" +$inputFile = Join-Path $metadataDirectory $fileName +New-Item -ItemType Directory -Path $outputDirectory -Force | Out-Null Write-Host "`nSettings: $settings" Write-Host "Generating OpenAPI description from $inputFile" Write-Host "Output file: $outputFile" @@ -59,9 +81,12 @@ Write-Host $command try { Invoke-Expression "$command" + if ($LASTEXITCODE -ne 0) { + throw "Hidi transformation failed with exit code $LASTEXITCODE." + } # temporary fix for the server url https://github.com/microsoftgraph/msgraph-metadata/issues/124 $content = Get-Content $outputFile -Raw - $updatedContent = $content -replace "http://localhost", "https://graph.microsoft.com/$endpointVersion" + $updatedContent = $content.Replace("http://localhost", $serviceRoot) Set-Content $outputFile $updatedContent -NoNewline if(Test-Path $oldOutputFile) { @@ -73,6 +98,9 @@ try { if(Test-Path $oldOutputFile) { Write-Host "`nRestoring old output file: $oldOutputFile" + if (Test-Path $outputFile) { + Remove-Item $outputFile -Force + } $originalFileName = Split-Path $outputFile -leaf Rename-Item $oldOutputFile $originalFileName } diff --git a/scripts/git-push-cleanmetadata.ps1 b/scripts/git-push-cleanmetadata.ps1 index a580d8a89..03b10917f 100644 --- a/scripts/git-push-cleanmetadata.ps1 +++ b/scripts/git-push-cleanmetadata.ps1 @@ -15,6 +15,58 @@ if ($env:PublishChanges -eq $False) return; } +# Cloud outputs may be new directories. Stash and stage only their generated files. +if (![string]::IsNullOrWhiteSpace($env:PublishPath)) +{ + function Invoke-PublicationGit { + param([string[]]$Arguments) + & git @Arguments | Write-Host + if ($LASTEXITCODE -ne 0) { + throw "Git publication command '$($Arguments -join ' ')' failed with exit code $LASTEXITCODE." + } + } + + if ([string]::IsNullOrWhiteSpace($env:PublicationIdentifier)) { + throw "PublicationIdentifier is required when PublishPath is specified." + } + + $changes = & git status --porcelain -- $env:PublishPath + if ($LASTEXITCODE -ne 0) { + throw "Failed to inspect generated files for publication." + } + if (!$changes) { + Write-Host "No changes to publish in $env:PublishPath." + Write-Host "##vso[task.setvariable variable=publicationHasChanges]false" + return + } + + Invoke-PublicationGit -Arguments @('stash', 'push', '--include-untracked', '--', $env:PublishPath) + Invoke-PublicationGit -Arguments @('fetch', 'origin', 'master') + Invoke-PublicationGit -Arguments @('switch', 'master') + Invoke-PublicationGit -Arguments @('stash', 'pop') + + $branch = "publish-open-api-files/$env:BUILD_BUILDID/$env:PublicationIdentifier" + if ($env:CreateOpenAPIPR -eq $True) { + Invoke-PublicationGit -Arguments @('checkout', '-B', $branch) + } + + Invoke-PublicationGit -Arguments @('add', '--', $env:PublishPath) + $message = "Update clean $env:PublicationIdentifier metadata file with $env:BUILD_BUILDID" + if ($env:BUILD_REASON -eq 'Manual') { + $message += " [skip ci]" + } + Invoke-PublicationGit -Arguments @('commit', '-m', $message) + if ($env:CreateOpenAPIPR -eq $True) { + Invoke-PublicationGit -Arguments @('push', '--set-upstream', 'origin', $branch) + } + else { + Invoke-PublicationGit -Arguments @('pull', 'origin', 'master', '--rebase') + Invoke-PublicationGit -Arguments @('push', '--set-upstream', 'origin', 'master') + } + Write-Host "##vso[task.setvariable variable=publicationHasChanges]true" + return +} + Write-Host "`n1. git status:" git status | Write-Host diff --git a/test/scripts/FairfaxPipeline.Tests.ps1 b/test/scripts/FairfaxPipeline.Tests.ps1 new file mode 100644 index 000000000..7fa3ccf4e --- /dev/null +++ b/test/scripts/FairfaxPipeline.Tests.ps1 @@ -0,0 +1,169 @@ +# Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. +param([string]$FixtureRoot = [System.IO.Path]::GetTempPath()) + +$ErrorActionPreference = 'Stop' +$repoRoot = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent +$generationScript = Join-Path $repoRoot 'scripts/generate-open-api.ps1' +$publicationScript = Join-Path $repoRoot 'scripts/git-push-cleanmetadata.ps1' +$testRoot = Join-Path $FixtureRoot "fairfax-pipeline-tests-$([guid]::NewGuid())" +$environmentNames = @('PublishChanges', 'PublishPath', 'PublicationIdentifier', 'CreateOpenAPIPR', 'BUILD_BUILDID', 'BUILD_REASON') +$originalEnvironment = @{} +foreach ($name in $environmentNames) { + $originalEnvironment[$name] = [Environment]::GetEnvironmentVariable($name) +} + +function Assert-Equal($actual, $expected, [string]$message) { + if ($actual -ne $expected) { + throw "$message`: expected '$expected', got '$actual'." + } +} + +function Invoke-TestGit { + param([string[]]$Arguments) + $output = & git @Arguments 2>&1 + if ($LASTEXITCODE -ne 0) { + throw "Test git command failed: $($Arguments -join ' ')`n$output" + } + return $output +} + +$hidiState = @{ Arguments = @(); ExitCode = 0 } +$function:hidi = { + $hidiState.Arguments = @($args) + $inputFile = $args[[Array]::IndexOf($args, '--csdl') + 1] + $outputFile = $args[[Array]::IndexOf($args, '--output') + 1] + if (!(Test-Path $inputFile)) { + throw "Unexpected CSDL input: $inputFile" + } + Set-Content -LiteralPath $outputFile -Value "servers:`n - url: http://localhost" + $global:LASTEXITCODE = $hidiState.ExitCode +}.GetNewClosure() + +New-Item -ItemType Directory -Path $testRoot | Out-Null +Push-Location $testRoot +try { + foreach ($version in @('v1.0', 'beta')) { + $metadataDirectory = "clean_$($version.Replace('.', ''))_metadata" + New-Item -ItemType Directory -Path $metadataDirectory | Out-Null + Set-Content (Join-Path $metadataDirectory "cleanMetadataWithDescriptionsAndAnnotations$version.xml") '' + & $generationScript -endpointVersion $version -settings 'default.json' -platformName default + Assert-Equal (Get-Content "openapi/$version/default.yaml" -Raw).Trim() "servers:`n - url: https://graph.microsoft.com/$version" 'Prod defaults changed' + Assert-Equal $hidiState.Arguments[[Array]::IndexOf($hidiState.Arguments, '--metadata-version') + 1] $version 'Prod metadata version changed' + } + + $fairfaxMetadata = Join-Path $testRoot 'Fairfax metadata' + $fairfaxOutput = Join-Path $testRoot 'openapi/fairfax/v1.0' + New-Item -ItemType Directory -Path $fairfaxMetadata | Out-Null + Set-Content (Join-Path $fairfaxMetadata 'cleanMetadataWithDescriptionsAndAnnotationsv1.0.xml') '' + Set-Content (Join-Path $fairfaxMetadata 'cleanMetadataWithDescriptionsAndAnnotationsAndErrorsv1.0.xml') '' + $fairfaxArguments = @{ + endpointVersion = 'v1.0' + metadataDirectory = $fairfaxMetadata + outputDirectory = $fairfaxOutput + serviceRoot = 'https://graph.microsoft.us/v1.0' + } + foreach ($platform in @('default', 'graphexplorer', 'openapi', 'powershell_v2')) { + & $generationScript @fairfaxArguments -settings "$platform.json" -platformName $platform + $expectedFile = 'cleanMetadataWithDescriptionsAndAnnotationsv1.0.xml' + if ($platform -eq 'openapi') { + $expectedFile = 'cleanMetadataWithDescriptionsAndAnnotationsAndErrorsv1.0.xml' + } + Assert-Equal $hidiState.Arguments[[Array]::IndexOf($hidiState.Arguments, '--csdl') + 1] (Join-Path $fairfaxMetadata $expectedFile) 'Incorrect Fairfax annotation variant' + Assert-Equal $hidiState.Arguments[[Array]::IndexOf($hidiState.Arguments, '--metadata-version') + 1] 'v1.0' 'Cloud identity leaked into metadata version' + Assert-Equal (Get-Content (Join-Path $fairfaxOutput "$platform.yaml") -Raw).Trim() "servers:`n - url: https://graph.microsoft.us/v1.0" 'Incorrect Fairfax service URL' + } + + $originalOpenApi = Get-Content (Join-Path $fairfaxOutput 'openapi.yaml') -Raw + $hidiState.ExitCode = 1 + $failure = $null + try { + & $generationScript @fairfaxArguments -settings 'openapi.json' -platformName openapi + } + catch { + $failure = $_ + } + if (!$failure) { + throw 'Hidi failure was reported as success.' + } + Assert-Equal (Get-Content (Join-Path $fairfaxOutput 'openapi.yaml') -Raw) $originalOpenApi 'Previous OpenAPI was not restored after failure' + Assert-Equal (Test-Path (Join-Path $fairfaxOutput 'openapi.yaml.old')) $false 'Backup remained after restoration' + + $remote = Join-Path $testRoot 'remote.git' + Invoke-TestGit -Arguments @('init', '--bare', '--initial-branch=master', $remote) | Out-Null + Invoke-TestGit -Arguments @('clone', $remote, 'seed') | Out-Null + Push-Location 'seed' + try { + Invoke-TestGit -Arguments @('config', 'user.name', 'Pipeline test') | Out-Null + Invoke-TestGit -Arguments @('config', 'user.email', 'pipeline-test@example.invalid') | Out-Null + Set-Content 'README.txt' 'Seed repository' + Invoke-TestGit -Arguments @('add', 'README.txt') | Out-Null + Invoke-TestGit -Arguments @('commit', '-m', "Seed fixture`n`nCo-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>") | Out-Null + Invoke-TestGit -Arguments @('push', 'origin', 'master') | Out-Null + } + finally { + Pop-Location + } + Invoke-TestGit -Arguments @('clone', $remote, 'publication') | Out-Null + Push-Location 'publication' + try { + Invoke-TestGit -Arguments @('config', 'user.name', 'Pipeline test') | Out-Null + Invoke-TestGit -Arguments @('config', 'user.email', 'pipeline-test@example.invalid') | Out-Null + Invoke-TestGit -Arguments @('checkout', '--detach') | Out-Null + $env:PublishChanges = 'True' + $env:PublishPath = 'clean_v10_fairfax_metadata' + $env:PublicationIdentifier = 'Fairfax/v1.0' + $env:CreateOpenAPIPR = 'False' + $env:BUILD_BUILDID = '123' + $env:BUILD_REASON = 'Manual' + New-Item -ItemType Directory -Path $env:PublishPath | Out-Null + Set-Content "$env:PublishPath/cleanMetadataWithDescriptionsv1.0.xml" 'Fairfax CSDL' + Set-Content 'unrelated.txt' 'Must not be published' + & $publicationScript + Assert-Equal ((Invoke-TestGit -Arguments @('--git-dir', $remote, 'show', 'master:clean_v10_fairfax_metadata/cleanMetadataWithDescriptionsv1.0.xml')) -join "`n") 'Fairfax CSDL' 'First-run cleaned CSDL was not pushed' + Assert-Equal (Test-Path 'unrelated.txt') $true 'Unrelated file was lost' + Assert-Equal ((Invoke-TestGit -Arguments @('--git-dir', $remote, 'ls-tree', '--name-only', 'master', 'unrelated.txt')) -join '') '' 'Unrelated file was committed' + + $env:PublishPath = 'openapi/fairfax/v1.0' + $env:CreateOpenAPIPR = 'True' + New-Item -ItemType Directory -Path $env:PublishPath -Force | Out-Null + Set-Content "$env:PublishPath/default.yaml" 'Fairfax OpenAPI' + $env:PublishChanges = 'False' + $before = (Invoke-TestGit -Arguments @('rev-parse', 'HEAD')) -join '' + & $publicationScript + Assert-Equal ((Invoke-TestGit -Arguments @('rev-parse', 'HEAD')) -join '') $before 'Disabled publication created a commit' + Assert-Equal (Get-Content "$env:PublishPath/default.yaml") 'Fairfax OpenAPI' 'Disabled publication lost generated files' + + $env:PublishChanges = 'True' + & $publicationScript + $branch = 'publish-open-api-files/123/Fairfax/v1.0' + Assert-Equal ((Invoke-TestGit -Arguments @('--git-dir', $remote, 'show', "${branch}:openapi/fairfax/v1.0/default.yaml")) -join "`n") 'Fairfax OpenAPI' 'First-run OpenAPI was not pushed to its isolated branch' + Assert-Equal ((Invoke-TestGit -Arguments @('--git-dir', $remote, 'ls-tree', '--name-only', 'master', 'openapi')) -join '') '' 'OpenAPI was pushed directly to master' + $before = (Invoke-TestGit -Arguments @('rev-parse', 'HEAD')) -join '' + & $publicationScript + Assert-Equal ((Invoke-TestGit -Arguments @('rev-parse', 'HEAD')) -join '') $before 'No-change publication created a commit' + + Set-Content "$env:PublishPath/default.yaml" 'Updated Fairfax OpenAPI' + Invoke-TestGit -Arguments @('remote', 'set-url', 'origin', (Join-Path $testRoot 'missing-remote.git')) | Out-Null + $failure = $null + try { + & $publicationScript + } + catch { + $failure = $_ + } + if (!$failure) { + throw 'Git publication failure was reported as success.' + } + } + finally { + Pop-Location + } + Write-Host 'Passed: Prod defaults, four Fairfax profiles, Hidi failure recovery, first-run CSDL/OpenAPI publication, publication controls, and Git failure propagation.' +} +finally { + Pop-Location + foreach ($name in $environmentNames) { + [Environment]::SetEnvironmentVariable($name, $originalEnvironment[$name]) + } + Remove-Item -LiteralPath $testRoot -Recurse -Force +}