Skip to content

Instantly share code, notes, and snippets.

@RobinDaugherty
Forked from macielsmith/home-bin-prettify
Last active May 1, 2018 17:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RobinDaugherty/ddf3887202a5d0bc2a8ed54cf6476df3 to your computer and use it in GitHub Desktop.
Save RobinDaugherty/ddf3887202a5d0bc2a8ed54cf6476df3 to your computer and use it in GitHub Desktop.
prettify json files in git project before comparing
#!/bin/zsh
# Staged files
{ git diff --name-only --diff-filter=d --relative &
# Staged files
git diff --cached --name-only --relative &
# Unstaged new files
git ls-files --others --exclude-standard } |
# Remove duplicates
sort -u |
# Filter to the files we're interested in.
egrep '(dg5|df5|json)$' |
# Replace newlines with null terminators
tr "\n" "\0" |
# Call the script for each entry terminated by a null terminator (rather than space or newline, which breaks for filenames with space).
xargs -0 -n1 ~/.bin/prettify.rb
#!/usr/bin/env ruby
require "json"
class PrettifyFile
def initialize(filename)
@filename = filename
end
attr_reader :filename
def run
contents = File.open(filename).read
new_contents = JSON.pretty_generate(JSON.parse(contents))
if new_contents != contents
puts colorize("#{filename} was prettified.", :yellow)
File.open(filename, "w").write(new_contents)
else
puts colorize("#{filename} stayed the same.", :green)
end
rescue JSON::ParserError => e
puts colorize("Error: #{filename} could not be parsed: #{e}", :red)
rescue Errno::ENOENT
puts colorize("Warning: #{filename} could not be prettified because it's been deleted.", :yellow)
end
private
def colorize(text, color = "default", bgColor = "default")
colors = {
default: "38",
black: "30",
red: "31",
green: "32",
brown: "33",
blue: "34",
purple: "35",
cyan: "36",
gray: "37",
dark_gray: "1;30",
light_red: "1;31",
light_green: "1;32",
yellow: "1;33",
light_blue: "1;34",
light_purple: "1;35",
light_cyan: "1;36",
white: "1;37",
}
bgColors = {
default: "0",
black: "40",
red: "41",
green: "42",
brown: "43",
blue: "44",
purple: "45",
cyan: "46",
gray: "47",
dark_gray: "100",
light_red: "101",
light_green: "102",
yellow: "103",
light_blue: "104",
light_purple: "105",
light_cyan: "106",
white: "107",
}
color_code = colors[color]
bgColor_code = bgColors[bgColor]
return "\033[#{bgColor_code};#{color_code}m#{text}\033[0m"
end
end
PrettifyFile.new(ARGV[0]).run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment