Created
March 3, 2016 14:28
-
-
Save clausd/3def09952d7a08e3513a to your computer and use it in GitHub Desktop.
Just want to expand some values into static files - not a "blog engine". This is already overkilll
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
require 'erb' | |
require 'json' | |
require 'yaml' | |
require 'fileutils' | |
@from = ARGV.shift || 'files' | |
@to = ARGV.shift || 'dist' | |
# definitions | |
class Hash | |
@@warn = false; | |
def self.warn(setting) | |
@@warn = setting | |
end | |
def method_missing(method_sym, *arguments) | |
puts "Missing #{method_sym}" if @@warn | |
if method_sym.to_s[-1] == "=" | |
self[method_sym[0..-2].to_sym] = arguments.first | |
else | |
self[method_sym] || self[method_sym.to_s] | |
end | |
end | |
end | |
def vars | |
@vars ||= Hash.new() | |
end | |
# filesystem | |
def rebase(file) | |
file.gsub(/^#{@from}/, @to) | |
end | |
def glob(extension = '*') | |
Dir.glob(File.join(@from, '**', extension)) | |
end | |
def path(file) | |
File.dirname(file).gsub(/^#{@from}/, '') | |
end | |
def writable(file) | |
FileUtils.mkdir_p(File.dirname(file)) | |
if block_given? | |
File.open(file, 'w') {|f| yield f} | |
end | |
end | |
done = {} | |
# require .rb | |
glob('*.rb').each do |file| | |
puts "requiring #{file}" | |
require './' + file | |
done[file] = 1 | |
end | |
# load variables from yaml or json | |
glob('*.yaml').each do |file| | |
puts "loading #{file}" | |
vars.merge!(YAML.load(File.read(file))) | |
done[file] = 1 | |
end | |
glob('*.json').each do |file| | |
puts "parsing #{file}" | |
vars.merge!(JSON.parse(File.read(file))) | |
done[file] = 1 | |
end | |
Hash.warn(true) | |
# process templates | |
Dir.glob(File.join(@from, '**', '*.erb')).each do |file| | |
puts "expanding #{file}" | |
new_file = rebase(file).gsub(/\.erb$/, '') | |
if File.extname(new_file) == "" | |
new_file = new_file + '/index.html' | |
end | |
writable(new_file) {|f| f.write(ERB.new(File.read(file)).result())} | |
done[file] = 1 | |
end | |
# maybe todo: Markdown over erb (but then I almost built jekyll) | |
# this works ok - store post in yaml.... | |
# copy remaining files | |
glob.reject {|file| done[file]}.each do |file| | |
unless File.directory?(file) | |
puts "copying #{file}" | |
writable(rebase(file)) {|f| f.write(File.read(file))} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment