DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Edit Compressed/encrypted Files
This script will allow you to edit .gz, .bz2, .gpg files with vi or whatever the EDITOR environment variable points to. If the file is modified, it will be re-encode. It's real easy to add new file types.
#! /usr/bin/env ruby
require 'tempfile'
require "fileutils"
class Coder
def initialize(encode_cmd, decode_cmd)
@encode_cmd = encode_cmd
@decode_cmd = decode_cmd
end
def encode(infile, outfile)
cmd = @encode_cmd
cmd = cmd.sub("INFILE", infile).sub("OUTFILE", outfile)
print cmd, "\n"
system(cmd)
end
def decode(infile, outfile)
cmd = @decode_cmd
cmd = cmd.sub("INFILE", infile).sub("OUTFILE", outfile)
print cmd, "\n"
system(cmd)
end
def to_s
"encode #{@encode_cmd} decode #{@decode_cmd}"
end
end
$map ={
".gz"=>Coder.new("gzip < INFILE > OUTFILE", "gunzip < INFILE > OUTFILE"),
".bz2"=>Coder.new("bzip2 < INFILE > OUTFILE", "bunzip2 < INFILE > OUTFILE"),
".gpg"=>Coder.new("gpg -c < INFILE > OUTFILE", "gpg -d < INFILE > OUTFILE")
}
$editor = ENV["EDITOR"] || "vi"
class Edit
def edit(encoded)
ext = File.extname(encoded)
coder = $map[ext]
p ext
p coder
tempfile = Tempfile.new("t")
editfile = tempfile.path
coder.decode(encoded, editfile)
before = File.stat(editfile).mtime
system("#{$editor} #{editfile}")
after = File.stat(editfile).mtime
if (before != after)
# editfile was modified"
print "mv #{encoded} #{encoded+".bak"}\n"
FileUtils.mv encoded, encoded+".bak"
coder.encode( editfile, encoded)
end
end
end
if __FILE__ == $0 then
edit = Edit.new
ARGV.each do |filename|
edit.edit(filename)
end
end





