1#!/usr/bin/env ruby 2# Copyright (c) 2022-2022 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 15# Huawei Technologies Co.,Ltd. 16 17require 'json' 18require 'optparse' 19require 'set' 20require 'yaml' 21 22def check_option(optparser, options, key) 23 return if options[key] 24 25 puts "Missing option: --#{key}" 26 puts optparser 27 exit false 28end 29 30def check_version 31 major, minor, = RUBY_VERSION.split('.').map(&:to_i) 32 major > 2 || (major == 2 && minor >= 5) 33end 34 35raise "Update your ruby version, #{RUBY_VERSION} is not supported" unless check_version 36 37options = OpenStruct.new 38 39optparser = OptionParser.new do |opts| 40 opts.banner = 'Usage: merge.rb [options]' 41 42 opts.on('-d', '--data foo.yaml,bar.yaml,baz.yaml', Array, 'List of source data in YAML format (required)') 43 opts.on('-o', '--output FILE', 'Output file (default is stdout)') 44 45 opts.on('-h', '--help', 'Prints this help') do 46 puts opts 47 exit 48 end 49end 50optparser.parse!(into: options) 51 52check_option(optparser, options, :data) 53 54# Merge yamls into 'options_hash' 55options_hash = Hash.new("") 56options.data.each do |options_yaml| 57 data = YAML.load_file(File.expand_path(options_yaml)) 58 data = JSON.parse(data.to_json) 59 data["options"].each do |option| 60 name = option["name"] 61 if !options_hash.has_key?(name) 62 options_hash[name] = option 63 next 64 end 65 66 assert_eq = -> (key) { 67 raise "Option '#{name}' conflicts for key '#{key}'" unless options_hash[name][key] == option[key] 68 } 69 70 merge_arrays = -> (key) { 71 options_hash[name][key] = (Set.new(options_hash[name][key]) + Set.new(option[key])).to_a 72 } 73 74 assert_eq.call("type") 75 assert_eq.call("description") 76 77 if !option["possible_values"].nil? 78 merge_arrays.call("possible_values") 79 end 80 81 if !option["lang"].nil? 82 merge_arrays.call("lang") 83 end 84 85 if !option["default"].nil? 86 if option["type"] == "arg_list_t" 87 merge_arrays.call("default") 88 else 89 assert_eq.call("default") 90 end 91 end 92 end 93end 94 95# Dump resulted 'options_hash' to yaml output 96data = YAML.load_file(File.expand_path(options.data[0])) 97data = JSON.parse(data.to_json) 98data["options"] = options_hash.values 99output = options.output ? File.open(File.expand_path(options.output), 'w') : $stdout 100output_yaml = YAML.dump(JSON.load(data.to_json)) 101output.write(output_yaml) 102output.close 103