Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: d5ffc3f83c
Martin Harrigan September 27, 2012
executable file 86 lines (68 sloc) 2.433 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
#!/usr/bin/env ruby

require "rubygems"
require 'optparse'
require 'ostruct'
require File.join(File.expand_path(File.dirname(__FILE__)), '..', 'lib', 'csv2json.rb') # this form is important for local development

module CSV2JSONRunner

    # command-line parsing
    COMMAND = File.basename($0)
    USAGE = "Usage: #{COMMAND} [INPUT] [OPTIONS]"

    options = OpenStruct.new
    options.output = "-"
    options.separator = ","
    options.pretty = false
    options.headers = nil
    options.skipFirstRow = false

    opts = OptionParser.new do |o|
        o.banner = USAGE
        o.separator ""
        o.separator "Specific options:"

        o.on("-s", "--separator SEP", "Set separator character surrounded by single quotes (default is ',')") do |sep|
            options.separator = sep
        end

        o.on("-o", "--output FILE", "Write output to a file") do |fn|
            options.output = fn
        end

        o.on("-p", "--pretty", "Pretty-format JSON output") do
            options.pretty = true
        end

        o.on("-k", "--skip-headers-from-file", "Ignore the headers (first line) in the file; use with --headers to set your own") do |headers|
            if headers then
                options.skipFirstRow = true
            end
        end

        o.on("-H", "--headers HEADERS", "Supply list of headers, where no headers exist in the file, or where you're using -k to ignore them") do |headers|
            if headers then
                options.headers = headers.split(",")
            end
        end

        o.on_tail("-h", "--help", "Show this message") do
            puts o
            exit
        end

        o.on_tail("-v", "--version", "Show version") do
            puts CSV2JSON::VERSION
            exit
        end
    end

    begin
        opts.parse!(ARGV)
    rescue
        raise "Unable to parse options: #{$!}"
    end

    # initialize output handle
    if options.output == "-"
        OUT = $stdout.clone
    else
        OUT = File.open(options.output, "w")
    end
    
    if ARGV.size > 0
        IN = File.open(ARGV[0], "r")
    else
        IN = StringIO.new($stdin.read) # cannot be just $stdin.clone because CSV is seeking in file :-(
    end
    
    # run the command
    CSV2JSON.parse(IN, OUT, options.headers, {:col_sep => options.separator}, {:pretty => options.pretty, :skipFirstRow => options.skipFirstRow})
    
    # leave in peace
    OUT.flush
end
Something went wrong with that request. Please try again.