Permalink
Browse files

v 0.0.1 envdir

  • Loading branch information...
0 parents commit e9fe25c2edb51ccf5d1684cfc5f2fe7305e5a938 Orion Henry committed Oct 6, 2010
Showing with 120 additions and 0 deletions.
  1. +15 −0 README.markdown
  2. +24 −0 Rakefile
  3. +1 −0 VERSION
  4. +43 −0 bin/json2env
  5. +37 −0 lib/json2env.rb
@@ -0,0 +1,15 @@
+# json2env
+
+This is a simple tool for converting JSON into an envdir. It will take a json file or read from stdin.
+
+ $ json2env -f env.json dir
+
+or
+
+ $ cat env.json | json2env dir
+
+Then you can execute a program with this env using the envdir tool.
+
+
+ $ envdir dir program
+
@@ -0,0 +1,24 @@
+require 'jeweler'
+
+Jeweler::Tasks.new do |s|
+ s.name = "json2env"
+ s.description = "convert json to an envdir"
+ s.summary = s.description
+ s.author = "Orion Henry"
+ s.email = "orion@heroku.com"
+ s.homepage = "http://github.com/orionz/json2env"
+ s.rubyforge_project = "json2env"
+ s.files = FileList["[A-Z]*", "{bin,default,lib,spec}/**/*"]
+ s.executables = %w(json2env)
+ s.add_dependency "json"
+end
+
+Jeweler::RubyforgeTasks.new
+
+desc 'Run specs'
+task :spec do
+ sh 'bacon -s spec/*_spec.rb'
+end
+
+task :default => :spec
+
@@ -0,0 +1 @@
+0.0.1
@@ -0,0 +1,43 @@
+#!/usr/bin/env ruby
+
+require 'optparse'
+require File.dirname(__FILE__) + "/../lib/json2env"
+
+
+options = { :io => STDIN }
+
+ARGV.unshift "-h" if ARGV.size == 0
+
+optparse = OptionParser.new do|opts|
+ opts.banner = <<banner
+Usage: json2env [-f json.file] envdir
+banner
+ opts.on( '-f', '--file FILE', 'Specify a json file, default is stdin' ) do |file|
+ if (File.exists?(file))
+ options[:io] = File.open(file, "r")
+ end
+ end
+ opts.on( '-h', '--help', 'Display this screen' ) do
+ puts opts
+ exit
+ end
+end
+
+optparse.parse!
+
+envdir = ARGV.shift
+json = options[:io].read
+
+begin
+ JSON2Env.new(json,envdir).create;
+rescue JSON::ParserError
+ puts "Invalid JSON format"
+ exit 1
+rescue JSON2Env::TargetNotADirectory
+ puts "Cannot make envdir - file #{envdir} in the way"
+ exit 2
+rescue JSON2Env::TargetHasSubdirs
+ puts "Cowardly refusing to delete the target dir - it has subdirs"
+ exit 3
+end
+
@@ -0,0 +1,37 @@
+require 'json'
+
+class JSON2Env
+ attr_accessor :env, :dir
+
+ class TargetHasSubdirs < Exception ; end
+ class TargetNotADirectory < Exception ; end
+
+ def initialize(json, dir)
+ @env = JSON.load(json)
+ @dir = dir
+ end
+
+ def create
+ if File.exists?(dir)
+ raise TargetNotADirectory unless File.directory?(dir)
+ clean_dir
+ end
+ Dir.mkdir(dir)
+ @env.each do |key, value|
+ File.open("#{dir}/#{key}", "w") do |file|
+ file.write(value.gsub(/\r\n|\r|\n/, "\0"))
+ end
+ end
+ end
+
+ def clean_dir
+ raise TargetHasSubdirs if files.detect { |f| File.directory?(f) }
+ files.each { |f| File.delete(f) }
+ Dir.delete(@dir);
+ end
+
+ def files
+ Dir.glob("#{@dir}/*")
+ end
+end
+

0 comments on commit e9fe25c

Please sign in to comment.