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

fix: arm inject newline chars on windows #244

Merged
Merged
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
252 changes: 126 additions & 126 deletions src/Arcus.Scripting.ARM/Scripts/Inject-ArmContent.ps1
Original file line number Diff line number Diff line change
@@ -1,127 +1,127 @@
<#
Possible injection instructions in ARM templates or recursively referenced files:

${ fileToInject.xml }
${ FileToInject=file.xml }
${ FileToInject = ".\Parent Directory\file.xml" }
${ FileToInject = ".\Parent Directory\file.xml", EscapeJson, ReplaceSpecialChars }
${ FileToInject = '.\Parent Directory\file.json', InjectAsJsonObject }
#>

param (
[string] $Path = $PSScriptRoot
)

function InjectFile {
param(
[string] $filePath
)

Write-Host "Checking file $filePath"

$replaceContentDelegate = {
param($match)

$completeInjectionInstruction = $match.Groups[1].Value;
$instructionParts = @($completeInjectionInstruction -split "," | foreach { $_.Trim() } )

$filePart = $instructionParts[0];
# Regex uses non-capturing group for 'FileToInject' part,
# afterwards character classes and backreferencing to select the optional single or double quotes
$fileToInjectPathRegex = [regex] "^(?:FileToInject\s*=\s*)?([`"`']?)(?<File>.*?)\1?$";
$fileMatch = $fileToInjectPathRegex.Match($filePart)
if ($fileMatch.Success -ne $True){
throw "The file part '$filePart' of the injection instruction could not be parsed correctly"
}

$relativePathOfFileToInject = $fileMatch.Groups["File"];
$fullPathOfFileToInject = Join-Path (Split-Path $filePath -Parent) $relativePathOfFileToInject
$fileToInjectIsFound = Test-Path -Path $fullPathOfFileToInject -PathType Leaf
if ($false -eq $fileToInjectIsFound) {
throw "No file can be found at '$fullPathofFileToInject'"
}

# Inject content recursively first
InjectFile($fullPathOfFileToInject)

Write-Host "`t Injecting content of $fullPathOfFileToInject into $filePath"

$newString = Get-Content -Path $fullPathOfFileToInject -Raw

# XML declaration can only appear on the first line of an XML document, so remove when injecting
$newString = $newString -replace '(<\?xml).+(\?>)(\r)?(\n)?', ""

# By default: retain double quotes around content-to-inject, if present
$surroundContentWithDoubleQuotes = $match.Value.StartsWith('"') -and $match.Value.EndsWith('"')

if ($instructionParts.Length -gt 1) {
$optionParts = $instructionParts | select -Skip 1

if ($optionParts.Contains("ReplaceSpecialChars")){
Write-Host "`t Replacing special characters"

# Replace newline characters with literal equivalents
if ([environment]::OSVersion.VersionString -like "*Windows*") {
$newString = $newString -replace "`n", "\r\n"
} else {
$newString = $newString -replace "`n", "\n"
}

# Replace tabs with spaces
$newString = $newString -replace "`t", " "

# Replace " with \"
$newString = $newString -replace """", "\"""
}

if ($optionParts.Contains("EscapeJson")) {
Write-Host "`t JSON-escaping file content"

# Use regex negative lookbehind to replace double quotes not preceded by a backslash with escaped quotes
$newString = $newString -replace '(?<!\\)"', '\"'
}


if ($optionParts.Contains("InjectAsJsonObject")){
try{
# Test if content is valid JSON
ConvertFrom-Json $newString

$surroundContentWithDoubleQuotes = $False
}
catch{
Write-Error "Content to inject cannot be parsed as a JSON object!"
}
}
}

if ($surroundContentWithDoubleQuotes){
Write-Host "`t Surrounding content in double quotes"

$newString = '"' + $newString + '"'
}

return $newString;
}

$rawContents = Get-Content $filePath -Raw
$injectionInstructionRegex = [regex] '"?\${(.+)}\$"?';
$injectionInstructionRegex.Replace($rawContents, $replaceContentDelegate) | Set-Content $filePath -Encoding UTF8

Write-Host "Done checking file $filePath"
}


$psScriptFileName = $MyInvocation.MyCommand.Name

$PathIsFound = Test-Path -Path $Path
if ($false -eq $PathIsFound) {
throw "Passed allong path '$Path' doesn't point to valid file path"
}

Write-Host "Starting $psScriptFileName script on path $Path"

$armTemplates = Get-ChildItem -Path $Path -Recurse -Include *.json
$armTemplates | ForEach-Object { InjectFile($_.FullName) }

<#
Possible injection instructions in ARM templates or recursively referenced files:
${ fileToInject.xml }
${ FileToInject=file.xml }
${ FileToInject = ".\Parent Directory\file.xml" }
${ FileToInject = ".\Parent Directory\file.xml", EscapeJson, ReplaceSpecialChars }
${ FileToInject = '.\Parent Directory\file.json', InjectAsJsonObject }
#>
param (
[string] $Path = $PSScriptRoot
)
function InjectFile {
param(
[string] $filePath
)
Write-Host "Checking file $filePath"
$replaceContentDelegate = {
param($match)
$completeInjectionInstruction = $match.Groups[1].Value;
$instructionParts = @($completeInjectionInstruction -split "," | foreach { $_.Trim() } )
$filePart = $instructionParts[0];
# Regex uses non-capturing group for 'FileToInject' part,
# afterwards character classes and backreferencing to select the optional single or double quotes
$fileToInjectPathRegex = [regex] "^(?:FileToInject\s*=\s*)?([`"`']?)(?<File>.*?)\1?$";
$fileMatch = $fileToInjectPathRegex.Match($filePart)
if ($fileMatch.Success -ne $True){
throw "The file part '$filePart' of the injection instruction could not be parsed correctly"
}
$relativePathOfFileToInject = $fileMatch.Groups["File"];
$fullPathOfFileToInject = Join-Path (Split-Path $filePath -Parent) $relativePathOfFileToInject
$fileToInjectIsFound = Test-Path -Path $fullPathOfFileToInject -PathType Leaf
if ($false -eq $fileToInjectIsFound) {
throw "No file can be found at '$fullPathofFileToInject'"
}
# Inject content recursively first
InjectFile($fullPathOfFileToInject)
Write-Host "`t Injecting content of $fullPathOfFileToInject into $filePath"
$newString = Get-Content -Path $fullPathOfFileToInject -Raw
# XML declaration can only appear on the first line of an XML document, so remove when injecting
$newString = $newString -replace '(<\?xml).+(\?>)(\r)?(\n)?', ""
# By default: retain double quotes around content-to-inject, if present
$surroundContentWithDoubleQuotes = $match.Value.StartsWith('"') -and $match.Value.EndsWith('"')
if ($instructionParts.Length -gt 1) {
$optionParts = $instructionParts | select -Skip 1
if ($optionParts.Contains("ReplaceSpecialChars")) {
Write-Host "`t Replacing special characters"
# Replace newline characters with literal equivalents
if ([Environment]::OSVersion.VersionString -like "*Windows*") {
$newString = $newString -replace "`r`n", "\r\n"
} else {
$newString = $newString -replace "`n", "\n"
}
# Replace tabs with spaces
$newString = $newString -replace "`t", " "
# Replace " with \"
$newString = $newString -replace """", "\"""
}
if ($optionParts.Contains("EscapeJson")) {
Write-Host "`t JSON-escaping file content"
# Use regex negative lookbehind to replace double quotes not preceded by a backslash with escaped quotes
$newString = $newString -replace '(?<!\\)"', '\"'
}
if ($optionParts.Contains("InjectAsJsonObject")) {
try {
# Test if content is valid JSON
Write-Host "Test if valid JSON: $newString"
ConvertFrom-Json $newString
$surroundContentWithDoubleQuotes = $False
}
catch {
Write-Warning "Content to inject cannot be parsed as a JSON object!"
}
}
}
if ($surroundContentWithDoubleQuotes) {
Write-Host "`t Surrounding content in double quotes"
$newString = '"' + $newString + '"'
}
return $newString;
}
$rawContents = Get-Content $filePath -Raw
$injectionInstructionRegex = [regex] '"?\${(.+)}\$"?';
$injectionInstructionRegex.Replace($rawContents, $replaceContentDelegate) | Set-Content $filePath -NoNewline -Encoding UTF8
Write-Host "Done checking file $filePath"
}
$psScriptFileName = $MyInvocation.MyCommand.Name
$PathIsFound = Test-Path -Path $Path
if ($false -eq $PathIsFound) {
throw "Passed allong path '$Path' doesn't point to valid file path"
}
Write-Host "Starting $psScriptFileName script on path $Path"
$armTemplates = Get-ChildItem -Path $Path -Recurse -Include *.json
$armTemplates | ForEach-Object { InjectFile($_.FullName) }
Write-Host "Finished script $psScriptFileName"
129 changes: 74 additions & 55 deletions src/Arcus.Scripting.Tests.Integration/Arcus.Scripting.ARM.tests.ps1
Original file line number Diff line number Diff line change
@@ -1,56 +1,75 @@
Import-Module -Name $PSScriptRoot\..\Arcus.Scripting.ARM -ErrorAction Stop

Describe "Arcus" {
Context "ARM" {
InModuleScope Arcus.Scripting.ARM {
It "Replaces file path with inline file contents" {
# Arrange
$armTemplateFile = "$PSScriptRoot\Files\arm-template-inline.json"
try {
# Act
Inject-ArmContent -Path $armTemplateFile

# Assert
$expected = Get-Content "$PSScriptRoot\Files\arm-template-inline-value.json"
$actual = Get-Content $armTemplateFile
$actual[7].Trim(' ') | Should -Match $expected
} finally {
$originalFile = "$PSScriptRoot\Files\arm-template-inline-org.json"
Get-Content $originalFile | Out-File -FilePath $armTemplateFile
}
}
It "Replaces file path with file contents as JSON object" {
# Arrange
$armTemplateFile = "$PSScriptRoot\Files\arm-template-object.json"
try {
# Act
Inject-ArmContent -Path $armTemplateFile

# Assert
$expected = Get-Content "$PSScriptRoot\Files\arm-template-object-value.json"
$actual = Get-Content $armTemplateFile
$actual[7].Trim(' ') | Should -Match """value"": { ""test"": ""this is a test value"" }"
} finally {
$originalFile = "$PSScriptRoot\Files\arm-template-object-org.json"
Get-Content $originalFile | Out-File -FilePath $armTemplateFile
}
}
It "Replaces file path with file contents as escaped JSON and replaced special characters" {
# Arrange
$armTemplateFile = "$PSScriptRoot\Files\arm-template-escape.json"
try {
# Act
Inject-ArmContent -Path $armTemplateFile

# Assert
$expected = Get-Content "$PSScriptRoot\Files\arm-template-escape-value.xml"
$actual = Get-Content $armTemplateFile
$actual[7].Trim(' ') | Should -Match "<Operation value=\\""this is a test value\\"" \/>"
} finally {
$originalFile = "$PSScriptRoot\Files\arm-template-escape-org.json"
Get-Content $originalFile | Out-File -FilePath $armTemplateFile
}
}
}
}
Import-Module -Name $PSScriptRoot\..\Arcus.Scripting.ARM -ErrorAction Stop

InModuleScope Arcus.Scripting.ARM {
Describe "Arcus ARM integration tests" {
Context "ARM injection" {
It "Replaces file path with inline file contents" {
# Arrange
$armTemplateFile = "$PSScriptRoot\Files\arm-template-inline.json"
try {
# Act
Inject-ArmContent -Path $armTemplateFile

# Assert
$expected = Get-Content "$PSScriptRoot\Files\arm-template-inline-value.json"
$actual = Get-Content $armTemplateFile
$actual[7] | Should -Be ' "value": "this is a test value",'
} finally {
$originalFile = "$PSScriptRoot\Files\arm-template-inline-org.json"
Get-Content $originalFile | Out-File -FilePath $armTemplateFile
}
}
if ([Environment]::OSVersion.VersionString -like "*Windows*") {
It "Replaces file path with file contents as JSON object (windows)" {
# Arrange
$armTemplateFile = "$PSScriptRoot\Files\arm-template-object (windows).json"
try {
# Act
Inject-ArmContent -Path $armTemplateFile

# Assert
$expected = Get-Content "$PSScriptRoot\Files\arm-template-object-value (windows).json"
$actual = Get-Content $armTemplateFile
$actual[7] | Should -Be ' "value": "{\r\n \"test\": \"this is a test value\"\r\n}",'
} finally {
$originalFile = "$PSScriptRoot\Files\arm-template-object-org (windows).json"
Get-Content $originalFile | Out-File -FilePath $armTemplateFile
}
}
} else {
It "Replaces file path with file contents as JSON object (linux)" {
# Arrange
$armTemplateFile = "$PSScriptRoot\Files\arm-template-object (linux).json"
try {
# Act
Inject-ArmContent -Path $armTemplateFile

# Assert
$expected = Get-Content "$PSScriptRoot\Files\arm-template-object-value (linux).json"
$actual = Get-Content $armTemplateFile
$actual[7] | Should -Be ' "value": "{\n \"test\": \"this is a test value\"\n}",'
} finally {
$originalFile = "$PSScriptRoot\Files\arm-template-object-org (linux).json"
Get-Content $originalFile | Out-File -FilePath $armTemplateFile
}
}
}
It "Replaces file path with file contents as escaped JSON and replaced special characters" {
# Arrange
$armTemplateFile = "$PSScriptRoot\Files\arm-template-escape.json"
try {
# Act
Inject-ArmContent -Path $armTemplateFile

# Assert
$expected = Get-Content "$PSScriptRoot\Files\arm-template-escape-value.xml"
$actual = Get-Content $armTemplateFile
$actual[7] | Should -Be ' "value": "<Operation value=\"this is a test value\" />",'
} finally {
$originalFile = "$PSScriptRoot\Files\arm-template-escape-org.json"
Get-Content $originalFile | Out-File -FilePath $armTemplateFile
}
}
}
}
}
Loading