Module: Json2hcl

Defined in:
lib/json2hcl/exceptions.rb,
lib/json2hcl.rb,
lib/json2hcl/os.rb,
lib/json2hcl/version.rb

Overview

Exceptions

Defined Under Namespace

Modules: OS Classes: CommandExecutionError, InvalidFileError, InvalidHCLError, InvalidJSONError

Constant Summary collapse

VERSION =
File.read(File.expand_path(File.join('..', '..', 'VERSION'), __dir__)).sub(/v/, '').strip

Class Method Summary collapse

Class Method Details

.binfileObject



8
9
10
11
12
# File 'lib/json2hcl.rb', line 8

def self.binfile
  file = "json2hcl_v#{VERSION}_#{OS.os}_#{OS.arch}"
  file += '.exe' if OS.os == 'windows'
  File.expand_path(File.join('json2hcl', 'bin', file), __dir__)
end

.cmd(data, reverse = false) ⇒ Object

Raises:

  • (ArgumentError)


63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/json2hcl.rb', line 63

def self.cmd(data, reverse=false)
  raise ArgumentError     unless [true, false].include? reverse
  raise InvalidFileError  unless Pathname.new(data).absolute?

  cmd = binfile
  cmd += ' -reverse' if reverse
  cmd += ' 2>&1'
  cmd += " < #{data}"

  stdout = `#{cmd}`
  # puts cmd
  raise CommandExecutionError unless $?.exitstatus == 0

  return stdout
end

.to_hcl(data) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/json2hcl.rb', line 39

def self.to_hcl(data)
  if File.file?(data)
    begin
      hclstr = cmd(data, false)
    rescue CommandExecutionError
      raise InvalidJSONError
    end
  else
    f = ::Tempfile.new
    f.write(data)
    f.close

    begin
      hclstr = cmd(f.path, false)
    rescue CommandExecutionError
      raise InvalidJSONError
    ensure
      f.unlink
    end
  end

  return hclstr
end

.to_json(data) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/json2hcl.rb', line 14

def self.to_json(data)
  if File.file?(data)
    begin
      jsonstr = cmd(data, true)
    rescue CommandExecutionError
      raise InvalidHCLError
    end
  else
    # TODO: REFACTOR THIS!
    f = ::Tempfile.new
    f.write(data)
    f.close

    begin
      jsonstr = cmd(f.path, true)
    rescue CommandExecutionError
      raise InvalidHCLError
    ensure
      f.unlink
    end
  end

  return jsonstr
end