💾 Archived View for gemini.ctrl-c.club › ~de_alchmst › data › gen-from-templates.rb.txt captured on 2024-08-18 at 17:26:48.
⬅️ Previous capture (2024-05-10)
-=-=-=-=-=-=-
#!/usr/bin/ruby ############# # VARIABLES # ############# SELF_DIR = File.dirname(__FILE__) simple_word_list = [] complex_word_list = [] ########################## # LOAD TEMPLATE KEYWORDS # ########################## unless File.exist? SELF_DIR + "/" + "simple-template-list" abort "\x1b[91msimple-template-list does not exist\x1b[0m" end unless File.exist? SELF_DIR + "/" + "complex-template-list" abort "\x1b[91mcomplex-template-list does not exist\x1b[0m" end # simple # f = File.open SELF_DIR + "/" + "simple-template-list", "r" # allows to continue on next line with '\' f.read.gsub(/\\\s*?\n\s*(?=\S)/, "").split(/\n/).each { |line| line = line.strip # skip comments and empty lines unless line[0] == "#" or line.length == 0 # split by first whitespace parts = line.partition /\s/ if parts[2] == "" abort "\x1b[91minvalid line: #{line}\x1b[0m" end # add to word list # simple_word_list.push [ "||#{parts[0]}||", eval(parts[2].strip) ] rescue abort("\x1b[91mcannot interpret: #{parts[2].strip}\x1b[0m") end } f.close # complex # f = File.open SELF_DIR + "/" + "complex-template-list", "r" # allows to continue on next line with '\' f.read.gsub(/\\\s*?\n\s*(?=\S)/, "").split(/\n/).each { |line| line = line.strip # skip comments and empty lines unless line[0] == "#" or line.length == 0 # split by first whitespace parts = line.partition /\s/ if parts[2] == "" abort "\x1b[91minvalid line: #{line}\x1b[0m" end # add to word list # complex_word_list.push [ Regexp.new(";;#{parts[0]};;(.*?);;"), parts[2].strip ] end } f.close ###################### # GENERATE NEW FILES # ###################### # go through found files Dir.children(SELF_DIR).each { |child| if child.match /\.template$/ f = File.open(SELF_DIR + "/" + child, "r") contents = f.read.partition(/\n/) f.close # 1st line is outcome path path = contents[0].strip.sub(/^~/, ENV["HOME"]) outcome = contents[2] # replace each word defined in template-list with evaluated value # # complex # complex_word_list.each { |words| begin while (outcome =~ words[0]) != nil arg = $1 x = eval words[1] outcome.sub!(words[0], x) end rescue abort "\x1b[91mcannot execute: #{words[1]} " + \ "with arg: #{arg} in file: #{child}\x1b[0m" end } # simple # simple_word_list.each { |words| outcome.gsub! words[0], words[1] } # try to write f = File.open(path, "w") rescue \ abort("\x1b[91mcould not write to: #{path} in file #{child}\x1b[91m") f.print outcome f.close end }