Skip to content

Commit

Permalink
custom json formatter
Browse files Browse the repository at this point in the history
  • Loading branch information
rrelmy committed Dec 11, 2016
1 parent 809c13e commit 904d070
Show file tree
Hide file tree
Showing 2 changed files with 114 additions and 0 deletions.
26 changes: 26 additions & 0 deletions bin/formatjson.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# reformat manifest json
param($path)

. "$psscriptroot\..\lib\core.ps1"
. "$psscriptroot\..\lib\manifest.ps1"
. "$psscriptroot\..\lib\json.ps1"

if(!$path) { $path = "$psscriptroot\..\bucket" }
$path = resolve-path $path

$dir = ""
$type = Get-Item $path
if ($type -is [System.IO.DirectoryInfo]) {
$dir = "$path\"
$files = Get-ChildItem $path "*.json"
} elseif ($type -is [System.IO.FileInfo]) {
$files = @($path)
} else {
Write-Error "unknown item"
exit
}

$files | % {
$json = parse_json "$dir$_" | ConvertToPrettyJson
[System.IO.File]::WriteAllLines("$dir$_", $json)
}
88 changes: 88 additions & 0 deletions lib/json.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# Convert objects to pretty json
# Only needed until PowerShell ConvertTo-Json will be improved https://github.com/PowerShell/PowerShell/issues/2736
Function ConvertToPrettyJson {
[cmdletbinding()]

Param (
[parameter(Mandatory, ValueFromPipeline)]
$data
)

Process {
[String]$json = $data | ConvertTo-Json -Compress
[String]$output = ""

# state
[String]$buffer = ""
[Int]$depth = 0
[Bool]$inString = $false

# configuration
[String]$indent = " " * 4
[Bool]$unescapeString = $true
[String]$eol = "`r`n"

for ($i = 0; $i -lt $json.Length; $i++) {
# read current char
$buffer = $json.Substring($i, 1)

#
$objectStart = !$inString -and $buffer.Equals("{")
$objectEnd = !$inString -and $buffer.Equals("}")
$arrayStart = !$inString -and $buffer.Equals("[")
$arrayEnd = !$inString -and $buffer.Equals("]")
$colon = !$inString -and $buffer.Equals(":")
$comma = !$inString -and $buffer.Equals(",")
$quote = $buffer.Equals('"')
$escape = $buffer.Equals('\')

if ($quote) {
$inString = !$inString
}

# skip escape sequences
if ($escape) {
$buffer = $json.Substring($i, 2)
++$i

# Unescape unicode
if ($inString -and $unescapeString) {
if ($buffer.Equals('\n')) {
$buffer = "`n"
} elseif ($buffer.Equals('\r')) {
$buffer = "`r"
} elseif ($buffer.Equals('\t')) {
$buffer = "`t"
} elseif ($buffer.Equals('\u')) {
$buffer = [regex]::Unescape($json.Substring($i - 1, 6))
$i += 4
}
}

$output += $buffer
continue
}

# indent / outdent
if ($objectStart -or $arrayStart) {
++$depth
} elseif ($objectEnd -or $arrayEnd) {
--$depth
$output += $eol + ($indent * $depth)
}

# add content
$output += $buffer

# add whitespace and newlines after the content
if ($colon) {
$output += " "
} elseif ($comma -or $arrayStart -or $objectStart) {
$output += $eol
$output += $indent * $depth
}
}

$output
}
}

0 comments on commit 904d070

Please sign in to comment.