Sha256: 066abf20d2d10d3e5c3ad3a455f0072fd5ed96cfc975fdb02d8f2ec909c0eb85

Contents?: true

Size: 1.95 KB

Versions: 1

Compression:

Stored size: 1.95 KB

Contents

#!/usr/bin/env ruby

require 'fileutils'

require 'methadone'

require 'tomograph'
require 'tomograph/version'

include Methadone::Main
include Methadone::CLILogging

version Tomograph::VERSION
description 'Converts API Blueprint to JSON Schema'
on('-d DRAFTER_VERSION', '--drafter', 'Choose drafter version: crafter or 4. Default: use drafter v.4.')
on('--exclude-description', 'Exclude "description" keys.')
on('--split', 'Split output into files by method.')
arg :input, 'path/to/doc.yaml (API Elements)'
arg :output, 'path/to/doc.json or path/to/dir if --split is used.'

def prune!(obj, unwanted_key)
  if obj.is_a?(Hash)
    obj.delete(unwanted_key)
    obj.each_value { |value| prune!(value, unwanted_key) }
  elsif obj.is_a?(Array)
    obj.each { |value| prune!(value, unwanted_key) }
  end
end

def choose_drafter(opt_parser)
  case opt_parser
  when 'crafter'
    :crafter
  when '4'
    :drafter_4
  when nil
    :drafter_4
  else
    raise 'Unsupported drafter version!'
  end
end

def write_split_json(actions, output)
  FileUtils.mkdir_p(output)
  actions.clone.each do |action|
    json_name = "#{action.delete("path").to_s} #{action.delete("method")}.json"
    [['/', '#'],
     ['{', '('],
     ['}', ')']].each do |pattern, replacement|
      json_name.gsub!(pattern, replacement)
    end
    write_json(action, File.join(output, json_name))
  end
end

def write_json(obj, path)
  json = JSON.pretty_generate(obj)
  File.open(path, 'w') do |file|
    file.write(json)
  end
end

main do |input, output|
  version = choose_drafter(options['drafter'])
  format_key = {
                  crafter:   :crafter_yaml_path,
                  drafter_4: :drafter_yaml_path
               }[version]

  tomogram = Tomograph::Tomogram.new(format_key => input)
  actions = tomogram.to_a.map(&:to_hash)

  prune!(actions, 'description') if options['exclude-description']

  if options['split']
    write_split_json(actions, output)
  else
    write_json(actions, output)
  end
  0
end

go!

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
tomograph-3.0.1 exe/tomograph