Tuesday, March 28, 2006

Ruby is just so beautiful

took about 90 minutes, since I had to learn about rubyzip:

=begin
# Simple script to retrieve all properties files, package them in the target directory,
# and add a comment to the top and bottom informing developers #to place entries at the bottom
# requires rubyzip (http://rubyzip.sourceforge.net/)
=end

require 'date'
require 'zip/zip'

class Properties_Packager

DECORATION = "#============================================="

HEADER_COMMENT =
DECORATION +
"\n#Please place all new additions at the bottom of the file\n" +
DECORATION

FOOTER_COMMENT =
DECORATION +
"\n#Packaged and processed on " + (Time.now.to_s ) + ". Please place all new entries after this section\n" +
DECORATION

@prop_files
attr_reader :prop_files, :HEADER_COMMENT

def initialize
@prop_files = []
@header_comment
end

private
def legit_file file
! (file.index("env.") != nil ||
file.index("junit") != nil ||
file.index("project.") != nil ||
file.index("#") != nil)
end


public
def obtain_properties_files(directory)
current_dir = Dir.open(directory)

for file in current_dir
next if(file == "." ||
file==".." ||
file=="target")

path = current_dir.path + "/" + file

if File.directory?(path)
obtain_properties_files(path)
else
if (legit_file file and file.index("properties") != nil)
puts "Adding " + path
@prop_files << path
end
end
@prop_files
end
@prop_files
end

def add_comments files
files.each do |file|
contents_buffer = []
current_lines = IO.readlines(file.to_s)

possible_header = current_lines[0]

if(! possible_header.strip.eql? DECORATION)

contents_buffer << HEADER_COMMENT
end

contents_buffer << IO.readlines(file.to_s).to_s
contents_buffer << FOOTER_COMMENT

open_file = File.open(file,"r+")
open_file.puts(contents_buffer)
open_file.close
end
end

def put_files_in_zip files, out_file_name

#if the file exists, erase it
if File.exists?(out_file_name)
File.delete(out_file_name)
puts "DELETED old zip file"
end

zipfile = Zip::ZipFile.new out_file_name, true
files.each do |file|
puts "zipping " + file.to_s
zipfile.add file, file.to_s
end
zipfile.close

end
end

zip_file = 'target/packaged_properties.zip'

packager = Properties_Packager.new
props = packager.obtain_properties_files('src/webapp')
packager.add_comments props
packager.put_files_in_zip props, zip_file

puts "Properties package ready for delivery #{zip_file}"


No comments: