module AsProject ####################################### # TemplateResolver class TemplateResolver < Hash attr_accessor :replace_all, :ignore_all @@ASPROJECT_FILE_NAME = 'AsProject' @@RENDER_IGNORE_FILES = ['asclass_config.rb'] def initialize @replace_all = false @ignore_all = false end def copy_files(from, to, render=false) created_files = Array.new if(!File.exists? from) raise ProjectError.new('AsProject attempted to copy files from (' + from + ') but it does not exist...') end if(File.directory? from) Dir.open(from).each do |filename| if(!AsProject.ignore_file? filename) fullname = File.join(from, filename) new_fullname = File.join(to, filename) cleaned_filename = clean_file_name(filename) cleaned_fullname = File.join(to, cleaned_filename) if(File.directory? fullname) Dir.mkdir(new_fullname) unless File.exists? new_fullname copy_files(fullname, new_fullname, render).each do |file| created_files << file end else file = copy_file(fullname, cleaned_fullname, render) if(file) created_files << file end end end end else raise ProjectError.new("copy_files called with a file (" + from + ") instead of a directory!") end return created_files end def copy_file(from, to, render=false) if(write_file?(to)) content = File.open(from, 'r').read parts = to.split(File::SEPARATOR) parts.pop File.makedirs(parts.join(File::SEPARATOR)) target = File.open(to, 'w') if(render && should_render?(from)) begin content = ERB.new(content, nil, '>').result(binding) rescue NameError => e puts '>> Template ' + from + ' references a value that is not defined' raise e end end target.write(content) target.close return to end return nil end def should_render?(file) if(@@RENDER_IGNORE_FILES.index(File.basename(file))) return false end return true end def write_file?(file) if(!File.exists?(file)) return true elsif(@replace_all) File.delete(file) return true elsif(@ignore_all) return false end relative = file.gsub(Dir.pwd, '') msg = <').result(binding) file.close file = File.open(filename, 'w') file.write(resolved) file.close end def clean_file_name name return name.gsub(@@ASPROJECT_FILE_NAME, project_name) end # Override in subclasses! def project_name return @@ASPROJECT_FILE_NAME end #TODO: Figure out if the file is plain text or not... Possible? def file_is_binary? file return false end end end