Skip to content

Instantly share code, notes, and snippets.

@babarot
Created May 31, 2014 12:39
Show Gist options
  • Save babarot/a6aac2befaef841be610 to your computer and use it in GitHub Desktop.
Save babarot/a6aac2befaef841be610 to your computer and use it in GitHub Desktop.
Encodes standard input by base64. Vice versa.
#!/usr/bin/ruby
require 'optparse'
require 'base64'
option_hash = {}
OptionParser.new{|opt|
opt.on('-e [VAL]') {|v| option_hash[:e] = v}
opt.on('-d VAL') {|v| option_hash[:d] = v}
begin
# Argument shift
opt.parse!(ARGV)
rescue
puts "Invalid option."
exit 1
end
}
def usage
puts "Usage: base64 [-e <filename>] [-d filename] [-h]"
puts "Help: This script encodes file or standard input using Base64."
puts " Moreover, it decodes file that was encoded in Base64."
puts "Option:"
puts "-e Encode as Base64. It supports argument and standard input."
puts "-d Decode as Base64. Only argument."
puts "-h Help."
puts ""
end
def encode64(recieve)
if File.pipe?(STDIN) || File.select([STDIN], [], [], 0) != nil then
STDIN.read.each_line do |line|
puts Base64.encode64(line)
end
else
if recieve != nil then
# Case: No STDIN and Is recieve
file = File.expand_path(recieve)
if File.exist?(file) then
# Case: File exists
contents = File.open(file).read
puts Base64.encode64(contents)
else
# Use argument as is for Base64
puts Base64.encode64(recieve)
end
else
usage
exit 1
end
end
end
def decode64(recieve)
file = File.expand_path(recieve)
if File.exist?(file) then
contents = File.open(file).read
puts Base64.decode64(contents)
else
puts File.basename(file) + ": No such file or directory"
end
end
if option_hash.size <= 0 then
# Case: No argument
usage
exit 1
end
if option_hash.key?(:e) then
# Call sub
encode64(option_hash[:e])
elsif option_hash.key?(:d) then
# Call sub
decode64(option_hash[:d])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment