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 20# Extend Module to implement a decorator for ISAPI methods 21class Module 22 def cached(method_name) 23 noncached_method = instance_method(method_name) 24 define_method(method_name) do 25 unless instance_variable_defined? "@#{method_name}" 26 instance_variable_set("@#{method_name}", noncached_method.bind(self).call) 27 end 28 instance_variable_get("@#{method_name}") 29 end 30 end 31end 32 33# Gen.on_require will be called after requiring scripts. 34# May (or even should) be redefined in scripts. 35module Gen 36 def self.on_require(data); end 37end 38 39def create_sandbox 40 # nothing but Ruby core libs and 'required' files 41 binding 42end 43 44def check_option(optparser, options, key) 45 return if options[key] 46 47 puts "Missing option: --#{key}" 48 puts optparser 49 exit false 50end 51 52options = OpenStruct.new 53 54optparser = OptionParser.new do |opts| 55 opts.banner = 'Usage: gen.rb [options]' 56 57 opts.on('-t', '--template FILE', 'Template for file generation (required)') 58 opts.on('-d', '--data FILE', 'Source data in YAML format (required)') 59 opts.on('-o', '--output FILE', 'Output file (default is stdout)') 60 opts.on('-a', '--assert FILE', 'Go through assertions on data provided and exit') 61 opts.on('-r', '--require foo,bar,baz', Array, 'List of files to be required for generation') 62 63 opts.on('-h', '--help', 'Prints this help') do 64 puts opts 65 exit 66 end 67end 68optparser.parse!(into: options) 69 70check_option(optparser, options, :data) 71data = YAML.load_file(File.expand_path(options.data)) 72data = JSON.parse(data.to_json, object_class: OpenStruct) 73 74options&.require&.each { |r| require File.expand_path(r) } if options.require 75Gen.on_require(data) 76 77if options.assert 78 require options.assert 79 exit 80end 81 82check_option(optparser, options, :template) 83template = File.read(File.expand_path(options.template)) 84output = options.output ? File.open(File.expand_path(options.output), 'w') : STDOUT 85t = ERB.new(template, nil, '%-') 86t.filename = options.template 87output.write(t.result(create_sandbox)) 88output.close 89