• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env ruby
2# Copyright (c) 2021 Huawei Device Co., Ltd.
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15require 'optparse'
16require 'yaml'
17require 'json'
18require 'erb'
19
20module Gen
21  def self.on_require(data); end
22end
23
24require_relative  ('diagnostic')
25
26def create_sandbox
27  # nothing but Ruby core libs and 'required' files
28  binding
29end
30
31def check_option(optparser, options, key)
32  return if options[key]
33
34  puts "Missing option: --#{key}"
35  puts optparser
36  exit false
37end
38
39options = OpenStruct.new
40
41optparser = OptionParser.new do |opts|
42  opts.banner = 'Usage: gen.rb [options]'
43
44  opts.on('-t', '--template FILE', 'Template for file generation (required)')
45  opts.on('-d', '--datafile FILE', 'Source data in JSON format (required)')
46  opts.on('-o', '--output FILE', 'Output file (required)')
47  opts.on('-r', '--require foo,bar,baz', Array, 'List of files to be required for generation')
48
49  opts.on('-h', '--help', 'Prints this help') do
50    puts opts
51    exit
52  end
53end
54optparser.parse!(into: options)
55
56check_option(optparser, options, :datafile)
57check_option(optparser, options, :template)
58check_option(optparser, options, :output)
59
60template_file = File.read(options.template)
61output_file = File.open(options.output, 'w')
62
63data = YAML.load_file(options.datafile)
64data = JSON.parse(data.to_json)
65options&.require&.each { |r| require r }
66Gen.on_require(data)
67
68t = ERB.new(template_file, nil, '%-')
69t.filename = options.template
70
71output_file.write(t.result(create_sandbox))
72output_file.close
73