Skip to content

Commit

Permalink
fix: Fix Duplication of Flattened JSON Keys in .env File During Multi…
Browse files Browse the repository at this point in the history
…ple Runs (#1618)
  • Loading branch information
Pavan-Microsoft authored Jan 7, 2025
1 parent dc7b87c commit 2d1af79
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 10 deletions.
11 changes: 8 additions & 3 deletions scripts/parse_env.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ function Flatten-Json {
return $flattened
}

$output = @()
$output = @{}

foreach ($line in Get-Content -Path $envFile) {
Write-Host "Processing line: $line"
Expand Down Expand Up @@ -65,17 +65,22 @@ foreach ($line in Get-Content -Path $envFile) {

# Add each flattened key-value pair to the output
foreach ($flattenedKey in $flattenedJson.Keys) {
$output += "$flattenedKey=`"$($flattenedJson[$flattenedKey])`""
$output[$flattenedKey] = "`"$($flattenedJson[$flattenedKey])`""
}
} catch {
Write-Error "Failed to parse JSON for key: $key, value: $value"
}
} else {
# Keep non-JSON key-value pairs as-is
$output += "$key=$value"
$output[$key] = $value
}
}

# Convert the hashtable to an array of strings in the format KEY=VALUE, sorted by key name
$output = $output.GetEnumerator() |
Sort-Object -Property Key |
ForEach-Object { "$($_.Key)=$($_.Value)" }

# Write the processed content back to the .env file
$output | Set-Content -Path $envFile -Force
Write-Host "Flattened .env file written back to: $envFile"
22 changes: 15 additions & 7 deletions scripts/parse_env.sh
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ flatten_json() {
echo "$json_object" | jq -r "to_entries | .[] | \"${prefix}\(.key | ascii_upcase)=\(.value | @sh)\""
}

output=()
declare -A output

# Read the .env file line by line
while IFS= read -r line; do
Expand Down Expand Up @@ -57,19 +57,27 @@ while IFS= read -r line; do
"AZURE_KEY_VAULT_INFO") prefix="AZURE_KEY_VAULT_" ;;
esac
# Flatten the JSON object
flattened_json=$(flatten_json "$prefix" "$json_object")
output+=("$flattened_json")
while IFS= read -r flattened_line; do
flattened_key=$(echo "$flattened_line" | cut -d'=' -f1)
flattened_value=$(echo "$flattened_line" | cut -d'=' -f2-)
output["$flattened_key"]="$flattened_value"
done < <(flatten_json "$prefix" "$json_object")
else
echo "Failed to parse JSON for key: $key, value: $value"
fi
;;
*)
# Keep non-JSON key-value pairs as-is
output+=("$line")
output["$key"]="$value"
;;
esac
done < "$envFile"

# Write the processed content back to the .env file
printf "%s\n" "${output[@]}" > "$envFile"
echo "Flattened .env file written back to: $envFile"
# Write the processed content back to the .env file, sorted by key
{
for key in $(printf "%s\n" "${!output[@]}" | sort); do
echo "$key=${output[$key]}"
done
} > "$envFile"

echo "Flattened and sorted .env file written back to: $envFile"

0 comments on commit 2d1af79

Please sign in to comment.