module Jf
Constants
- VERSION
Public Class Methods
apply_format(target, opts)
click to toggle source
# File lib/jf.rb, line 46 def self.apply_format(target, opts) data_hash = JSON.parse(target) indent = opts[:indent] != nil ? " " * opts[:indent].to_i : " " formatted = JSON.pretty_generate(data_hash, {:indent => indent}).gsub /^$\n/, '' return formatted end
assert_file_not_found()
click to toggle source
# File lib/jf.rb, line 82 def self.assert_file_not_found puts "[Error] Could not find directory ot file." end
assert_parse_failed()
click to toggle source
# File lib/jf.rb, line 86 def self.assert_parse_failed puts "[Error] Could not parse json correctly." end
execute(target, opts)
click to toggle source
# File lib/jf.rb, line 8 def self.execute(target, opts) if target.is_stdin parse_stdin(target.body, opts) return end if File.exists?(target.body) paths = opts[:gitdiff] ? get_diff_list.split(/$/).map(&:strip) : get_path_list(target.body) else assert_file_not_found exit end for path in paths next if is_not_json(path) begin if opts[:minify] minify(path) elsif opts[:merge] merge(path, opts) else rewrite(path, opts) end rescue FileParseError => e assert_parse_failed next end end end
get_diff_list()
click to toggle source
# File lib/jf.rb, line 38 def self.get_diff_list `git status | egrep "$*.json" | sed -E "s/([^:]+: +)(.*)/\\2/"` end
get_path_list(path)
click to toggle source
# File lib/jf.rb, line 42 def self.get_path_list(path) File.directory?(path) ? Dir.glob("#{path}/**/*.json") : Dir.glob(path) end
is_not_json(path)
click to toggle source
# File lib/jf.rb, line 78 def self.is_not_json(path) return /.+.json/ !~ path end
merge(origin, opts)
click to toggle source
# File lib/jf.rb, line 53 def self.merge(origin, opts) origin_json = JSON.parse(File.read(origin)) target_json = JSON.parse(File.read(opts[:merge])) if opts[:key] target_keys = opts[:key].split(".") origin_json = origin_json.deep_merge(*target_keys, target_json) else origin_json = origin_json.merge(target_json) end File.write(origin, origin_json.to_json) rewrite(origin, opts) end
minify(path)
click to toggle source
# File lib/jf.rb, line 74 def self.minify(path) File.write(path, JSON.parse(File.read(path).force_encoding("UTF-8")).to_json) end
parse_stdin(stdin, opts)
click to toggle source
# File lib/jf.rb, line 70 def self.parse_stdin(stdin, opts) puts apply_format(stdin, opts) end
rewrite(path, opts)
click to toggle source
# File lib/jf.rb, line 66 def self.rewrite(path, opts) File.write(path, apply_format(File.read(path).force_encoding("UTF-8"), opts)) end