Skip to content

Instantly share code, notes, and snippets.

@rosalynnas
Created February 15, 2024 20:05
Show Gist options
  • Save rosalynnas/e9a457300c0655063b0218ce6e4252ca to your computer and use it in GitHub Desktop.
Save rosalynnas/e9a457300c0655063b0218ce6e4252ca to your computer and use it in GitHub Desktop.
Simple .xlsx to .yml file converter
require 'roo'
require 'yaml'
class Converter
def initialize(input_path, output_path)
@input_path = input_path
@output_path = output_path
end
def convert
xlsx = Roo::Spreadsheet.open(@input_path)
sheet = xlsx.sheet(0)
headers = sheet.row(1)
data = (2..sheet.last_row).map do |i|
row = Hash[headers.zip(sheet.row(i))]
transformed_row = transform_row(row)
next if transformed_row[row['Resource']][row['Action']][row['Role']].include?("none")
transformed_row
end.compact
# Deep merge all the hashes into one
data = deep_merge_hashes(*data)
# Generate YAML without document separator
yaml_data = data.to_yaml(lines: {chomp: true})
yaml_data = yaml_data.lines.map do |line|
next if line.start_with?("---\n")
if line.include?("- all")
line.gsub!('all', ':all')
elsif line.include?(" is_")
line.gsub!('is_', ':')
line = "#{line.chomp}?\n"
elsif !line.include?(":")
line = "#{line.chomp}?\n"
end
if line.strip.start_with?('-')
' ' + line
else
line
end
end
yaml_data = yaml_data.join
yaml_data.slice!(0, 4) if yaml_data.start_with?("---\n") # Remove "---\n" at the start
File.open(@output_path, 'w') { |f| f.write(yaml_data) }
end
def deep_merge_hashes(*hashes)
hashes.inject do |merged, hash|
merged.merge(hash) do |key, old_val, new_val|
if old_val.is_a?(Hash) && new_val.is_a?(Hash)
deep_merge_hashes(old_val, new_val)
else
[*old_val, *new_val]
end
end
end
end
private
def transform_row(row)
{
row['Resource'] => {
row['Action'] => {
row['Role'] => row['Rule'] ? [row['Rule']] : []
}
}
}
end
end
source "https://rubygems.org"
gem "roo"
require_relative 'converter'
excel_converter = Converter.new('permissions.xlsx', 'permissions.yml')
excel_converter.convert
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment