Last active
December 10, 2015 00:19
-
-
Save tsnow/4350306 to your computer and use it in GitHub Desktop.
sorting environments/*.json for chef
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env ruby | |
# ruby sort_env_json.rb environments/*.json | |
# ruby sort_env_json.rb environments/*.json --like environments/prod.json | |
require './json_file' | |
require 'optparse' | |
begin | |
$stderr.puts "please supply a list of environments/*.json paths you'd like to have sorted alphabetically" | |
exit(1) | |
end if ARGV.length == 0 | |
OptionParser.new do |opt| | |
opt.on("--like [JSONFILE]", "sort using the order in JSONFILE, with remainders at the beginning") do |o| | |
#'environments/prod.json' | |
$orderer = lambda{|trunk| | |
$prod ||= begin; a=JSONfile.new(o); a.files; end | |
(trunk.apps - $prod.apps) + $prod.apps | |
} | |
end | |
end.parse!(ARGV) | |
$orderer ||= lambda{|trunk| trunk.apps.sort } #alphabetically | |
ARGV.map{|i| a=JSONFile.new(i); a.files; a}.each do |trunk| | |
order = $orderer.call(trunk) | |
out = trunk.sort_apps(order) | |
puts JSON.pretty_generate(out) if $DEBUG | |
trunk.write | |
trunk.close | |
end | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'json' | |
class Chef | |
class Environment | |
end | |
end | |
class JSONfile | |
def initialize(path) | |
@path = path | |
end | |
def files | |
@read = File.read(@path) | |
@write = File.open(@path,'w') | |
end | |
def close | |
@write.close | |
end | |
def json | |
@json ||= JSON.parse(@read) | |
end | |
def app_root | |
json['default_attributes'] | |
end | |
def apps | |
app_root.keys | |
end | |
def write | |
@write.puts JSON.pretty_generate(@json) | |
end | |
def sort_apps(order = self.apps) | |
json['default_attributes'] = | |
begin | |
old = app_root.to_a | |
_new = {} | |
order.each do |i| v=old.find{|j| j.first == i} | |
_new[i] = v.last if v | |
end | |
_new | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'll look at getting this into a knife plugin ASAP. Slick.