Skip to content

Instantly share code, notes, and snippets.

@cavebatsofware
Last active August 29, 2015 13:57
Show Gist options
  • Save cavebatsofware/9655901 to your computer and use it in GitHub Desktop.
Save cavebatsofware/9655901 to your computer and use it in GitHub Desktop.
Simple house keeping script. Archives old files.
require 'time'
require 'date'
class Keeper
EXPIRE_TIME = 1209600 # 14 days
def initialize(path)
@root = Dir.new(path)
@client_folders = {}
@root.entries.each do |folder|
next if folder == '..' || folder == '.' || folder == 'graphics'
full_path = path + '/' + folder
@client_folders[full_path] = Dir.new(full_path)
end
end
def clean_house
@client_folders.values.each do |value|
archive_name = value.path + '/' + value.path.gsub(/\//, '__')
archive_path = archive_name + '.tar'
archive_manifest = archive_name + '.manifest'
files = get_path_list(value.entries, value.path)
write_archive_manifest(files, archive_manifest)
create = (File.exists?(archive_path) ? false : true)
archive_files(archive_manifest, archive_path, create)
confirmed = check_archive(archive_path, archive_manifest)
File.delete(archive_manifest)
delete_files(confirmed)
end
end
private
def archive_files(manifest, archive, create = false)
command = 'tar '
if create
command += '--create '
else
command += '--append '
end
command += "--keep-newer-files --format=ustar --no-recursion --absolute-names --no-unquote --files-from=#{manifest} -f #{archive}"
system(command)
end
def check_archive(archive, manifest)
archived = []
listed = []
File.open(manifest, 'r') do |m|
archived = m.read.split("\n")
end
listed = `tar --list -f #{archive}`.split("\n")
archived & listed
end
def delete_files(files)
files.each do |f|
File.delete(f)
end
end
def get_path_list(entries, path)
list = []
entries.each do |file|
next if file == '..' || file == '.' || file =~ /^_.*(\.tar|\.manifest)$/
f = path + '/' + file
list << f
end
list
end
def add_to_manifest(file, manifest)
afname = path_to_local(file)
manifest.write(file + "\n")
end
def path_to_local(file)
segments = file.split('/')
path = file
path = segments.slice(4..-1).join('/') if segments.length > 4
path
end
def write_archive_manifest(files, manifest, close = true)
manifest = File.open(manifest, 'w') unless manifest.respond_to?(:write)
files.each do |f|
if File.directory?(f)
d = Dir.new(f)
paths = get_path_list(d.entries, d.path)
write_archive_manifest(paths, manifest, false)
elsif (Time.now - File.stat(f).mtime) > EXPIRE_TIME
add_to_manifest(f, manifest)
end
end
ensure
manifest.close if close && manifest
end
end
k = Keeper.new('/var/ftp')
k.clean_house
@cavebatsofware
Copy link
Author

k = Keeper.new('/var/ftp')
k.clean_house

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment