Skip to content

Commit

Permalink
Merge pull request #187 from petems/refactor_highline_import
Browse files Browse the repository at this point in the history
Refactor highline import
  • Loading branch information
sihil committed Mar 2, 2016
2 parents 027e8f0 + 705eadd commit 97c71dd
Show file tree
Hide file tree
Showing 15 changed files with 256 additions and 203 deletions.
3 changes: 1 addition & 2 deletions Gemfile
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
source 'https://rubygems.org/'

gem 'highline', '~> 1.6.19'
gem 'trollop', '~> 2.0'
gemspec

group :development do
gem "aruba", '~> 0.6.2'
Expand Down
8 changes: 4 additions & 4 deletions bin/eyaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ Hiera::Backend::Eyaml::Plugins.find
begin
Hiera::Backend::Eyaml::CLI.parse
rescue StandardError => e
Hiera::Backend::Eyaml::Utils.warn e.message
Hiera::Backend::Eyaml::Utils.debug e.backtrace.join("\n")
Hiera::Backend::Eyaml::LoggingHelper.warn e.message
Hiera::Backend::Eyaml::LoggingHelper.debug e.backtrace.join("\n")
exit 1
end

begin
Hiera::Backend::Eyaml::CLI.execute
rescue StandardError => e
Hiera::Backend::Eyaml::Utils.warn e.message
Hiera::Backend::Eyaml::Utils.debug e.backtrace.join("\n")
Hiera::Backend::Eyaml::LoggingHelper.warn e.message
Hiera::Backend::Eyaml::LoggingHelper.debug e.backtrace.join("\n")
exit 1
end
5 changes: 3 additions & 2 deletions lib/hiera/backend/eyaml/CLI.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
require 'trollop'
require 'hiera/backend/eyaml'
require 'hiera/backend/eyaml/logginghelper'
require 'hiera/backend/eyaml/utils'
require 'hiera/backend/eyaml/plugins'
require 'hiera/backend/eyaml/options'
Expand Down Expand Up @@ -45,8 +46,8 @@ def self.execute
result = executor.execute
puts result unless result.nil?
rescue Exception => e
Utils.warn e.message
Utils.debug e.backtrace.join("\n")
LoggingHelper.warn e.message
LoggingHelper.debug e.backtrace.join("\n")
end

end
Expand Down
72 changes: 72 additions & 0 deletions lib/hiera/backend/eyaml/edithelper.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
require 'hiera/backend/eyaml/logginghelper'

class Hiera
module Backend
module Eyaml
class EditHelper

def self.find_editor
editor = ENV['EDITOR']
editor ||= %w{ /usr/bin/sensible-editor /usr/bin/editor /usr/bin/vim /usr/bin/vi }.collect {|e| e if FileTest.executable? e}.compact.first
raise StandardError, "Editor not found. Please set your EDITOR env variable" if editor.nil?
if editor.index(' ')
editor = editor.dup if editor.frozen? # values from ENV are frozen
editor.gsub!(/([^\\]|^)~/, '\1' + ENV['HOME']) # replace ~ with home unless escaped
editor.gsub!(/(^|[^\\])"/, '\1') # remove unescaped quotes during processing
editor.gsub!(/\\ /, ' ') # unescape spaces since we quote paths
pieces = editor.split(' ')
paths = pieces.each_with_index.map {|_,x| pieces[0..x].join(' ')}.reverse # get possible paths, starting with longest
extensions = (ENV['PATHEXT'] || '').split(';') # handle Windows executables
pathdirs = ENV['PATH'].split(File::PATH_SEPARATOR)
paths += pathdirs.collect { |dir| paths.collect { |path| File.expand_path(path, dir) } }.flatten
editorfile = paths.select { |path|
FileTest.file?(path) || ! extensions.select {|ext| FileTest.file?(path + ext) }.empty?
}.first
raise StandardError, "Editor not found. Please set your EDITOR env variable" if editorfile.nil?
raw_command = paths[(paths.index editorfile) % pieces.size]
editor = "\"#{editorfile}\"#{editor[raw_command.size()..-1]}"
end
editor
end

def self.secure_file_delete args
file = File.open(args[:file], 'r+')
num_bytes = args[:num_bytes]
[0xff, 0x55, 0xaa, 0x00].each do |byte|
file.seek(0, IO::SEEK_SET)
num_bytes.times { file.print(byte.chr) }
file.fsync
end
file.close
File.delete args[:file]
end

def self.write_tempfile data_to_write
file = Tempfile.open(['eyaml_edit', '.yaml'])
path = file.path
file.close!

file = File.open(path, "w")
file.chmod(0600)
if ENV['OS'] == 'Windows_NT'
# Windows doesn't support chmod
icacls = 'C:\Windows\system32\icacls.exe'
if File.executable? icacls
current_user = `C:\\Windows\\system32\\whoami.exe`.chomp
# Use ACLs to restrict access to the current user only
command = %Q{#{icacls} "#{file.path}" /grant:r "#{current_user}":f /inheritance:r}
system "#{command} >NUL 2>&1"
end
end
file.puts data_to_write
file.close

LoggingHelper::debug "Wrote temporary file: #{path}"

path
end

end
end
end
end
40 changes: 40 additions & 0 deletions lib/hiera/backend/eyaml/encrypthelper.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
require 'tempfile'
require 'fileutils'

class Hiera
module Backend
module Eyaml
class EncryptHelper

def self.write_important_file args
require 'hiera/backend/eyaml/highlinehelper'
filename = args[ :filename ]
content = args[ :content ]
mode = args[ :mode ]
if File.file? "#{filename}"
raise StandardError, "User aborted" unless HighlineHelper::confirm? "Are you sure you want to overwrite \"#{filename}\"?"
end
open( "#{filename}", "w" ) do |io|
io.write(content)
end
File.chmod( mode, filename ) unless mode.nil?
end

def self.ensure_key_dir_exists key_file
key_dir = File.dirname key_file

unless File.directory? key_dir
begin
FileUtils.mkdir_p key_dir
LoggingHelper::info "Created key directory: #{key_dir}"
rescue
raise StandardError, "Cannot create key directory: #{key_dir}"
end
end

end

end
end
end
end
10 changes: 5 additions & 5 deletions lib/hiera/backend/eyaml/encryptor.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
require 'base64'
require 'hiera/backend/eyaml/utils'
require 'hiera/backend/eyaml/encrypthelper'

class Hiera
module Backend
Expand Down Expand Up @@ -60,19 +60,19 @@ def self.format_message msg
end

def self.trace msg
Utils::trace :from => plugin_classname, :msg => msg
LoggingHelper::trace :from => plugin_classname, :msg => msg
end

def self.debug msg
Utils::debug :from => plugin_classname, :msg => msg
LoggingHelper::debug :from => plugin_classname, :msg => msg
end

def self.info msg
Utils::info :from => plugin_classname, :msg => msg
LoggingHelper::info :from => plugin_classname, :msg => msg
end

def self.warn msg
Utils::warn :from => plugin_classname, :msg => msg
LoggingHelper::warn :from => plugin_classname, :msg => msg
end

end
Expand Down
13 changes: 7 additions & 6 deletions lib/hiera/backend/eyaml/encryptors/pkcs7.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
require 'openssl'
require 'hiera/backend/eyaml/encryptor'
require 'hiera/backend/eyaml/utils'
require 'hiera/backend/eyaml/encrypthelper'
require 'hiera/backend/eyaml/logginghelper'
require 'hiera/backend/eyaml/options'

class Hiera
Expand Down Expand Up @@ -65,8 +66,8 @@ def self.create_keys
subject = self.option :subject

key = OpenSSL::PKey::RSA.new(2048)
Utils.ensure_key_dir_exists private_key
Utils.write_important_file :filename => private_key, :content => key.to_pem, :mode => 0600
EncryptHelper.ensure_key_dir_exists private_key
EncryptHelper.write_important_file :filename => private_key, :content => key.to_pem, :mode => 0600

cert = OpenSSL::X509::Certificate.new()
cert.subject = OpenSSL::X509::Name.parse(subject)
Expand All @@ -92,9 +93,9 @@ def self.create_keys

cert.sign key, OpenSSL::Digest::SHA1.new

Utils.ensure_key_dir_exists public_key
Utils.write_important_file :filename => public_key, :content => cert.to_pem
Utils.info "Keys created OK"
EncryptHelper.ensure_key_dir_exists public_key
EncryptHelper.write_important_file :filename => public_key, :content => cert.to_pem
LoggingHelper.info "Keys created OK"

end

Expand Down
24 changes: 24 additions & 0 deletions lib/hiera/backend/eyaml/highlinehelper.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
require 'highline/import'

class Hiera
module Backend
module Eyaml
class HighlineHelper

def self.read_password
ask("Enter password: ") {|q| q.echo = "*" }
end

def self.confirm? message
result = ask("#{message} (y/N): ")
if result.downcase == "y" or result.downcase == "yes"
true
else
false
end
end

end
end
end
end
80 changes: 80 additions & 0 deletions lib/hiera/backend/eyaml/logginghelper.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
require 'tempfile'
require 'fileutils'

class Hiera
module Backend
module Eyaml
class LoggingHelper

def self.structure_message messageinfo
message = {:from => "hiera-eyaml-core"}
case messageinfo.class.to_s
when 'Hash'
message.merge!(messageinfo)
else
message.merge!({:msg => messageinfo.to_s})
end
message[:prefix] = "[#{message[:from]}]"
message[:spacer] = " #{' ' * message[:from].length} "
formatted_output = message[:msg].split("\n").each_with_index.map do |line, index|
if index == 0
"#{message[:prefix]} #{line}"
else
"#{message[:spacer]} #{line}"
end
end
formatted_output.join "\n"
end

def self.warn messageinfo
self.print_message({ :message => self.structure_message( messageinfo ), :hiera_loglevel => :warn, :cli_color => :red })
end

def self.info messageinfo
self.print_message({ :message => self.structure_message( messageinfo ), :hiera_loglevel => :debug, :cli_color => :white, :threshold => 0 })
end

def self.debug messageinfo
self.print_message({ :message => self.structure_message( messageinfo ), :hiera_loglevel => :debug, :cli_color => :green, :threshold => 1 })
end

def self.trace messageinfo
self.print_message({ :message => self.structure_message( messageinfo ), :hiera_loglevel => :debug, :cli_color => :blue, :threshold => 2 })
end

def self.print_message( args )
message = args[:message] ||= ""
hiera_loglevel = args[:hiera_loglevel] ||= :debug
cli_color = args[:cli_color] ||= :blue
threshold = args[:threshold]

if self.hiera?
Hiera.send(hiera_loglevel, message) if threshold.nil? or Eyaml.verbosity_level > threshold
else
STDERR.puts self.colorize( message, cli_color ) if threshold.nil? or Eyaml.verbosity_level > threshold
end
end

def self.colorize message, color
suffix = "\e[0m"
prefix = case color
when :red
"\e[31m"
when :green
"\e[32m"
when :blue
"\e[34m"
else #:white
"\e[0m"
end
"#{prefix}#{message}#{suffix}"
end

def self.hiera?
"hiera".eql? Eyaml::Options[:source]
end

end
end
end
end
10 changes: 5 additions & 5 deletions lib/hiera/backend/eyaml/options.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,16 @@ def self.set hash
end

def self.trace
Utils::trace "Dump of eyaml tool options dict:"
Utils::trace "--------------------------------"
LoggingHelper::trace "Dump of eyaml tool options dict:"
LoggingHelper::trace "--------------------------------"
@@options.each do |k, v|
begin
Utils::trace sprintf "%18s %-18s = %18s %-18s", "(#{k.class.name})", k.to_s, "(#{v.class.name})", v.to_s
LoggingHelper::trace sprintf "%18s %-18s = %18s %-18s", "(#{k.class.name})", k.to_s, "(#{v.class.name})", v.to_s
rescue
Utils::trace sprintf "%18s %-18s = %18s %-18s", "(#{k.class.name})", k.to_s, "(#{v.class.name})", "<unprintable>" # case where v is binary
LoggingHelper::trace sprintf "%18s %-18s = %18s %-18s", "(#{k.class.name})", k.to_s, "(#{v.class.name})", "<unprintable>" # case where v is binary
end
end
Utils::trace "--------------------------------"
LoggingHelper::trace "--------------------------------"
end

end
Expand Down
2 changes: 1 addition & 1 deletion lib/hiera/backend/eyaml/subcommand.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def self.load_config_file
[ "/etc/eyaml/config.yaml", "#{ENV['HOME']}/.eyaml/config.yaml", "#{ENV['EYAML_CONFIG']}" ].each do |config_file|
begin
yaml_contents = YAML.load_file(config_file)
Utils::info "Loaded config from #{config_file}"
LoggingHelper::info "Loaded config from #{config_file}"
config.merge! yaml_contents
rescue
raise StandardError, "Could not open config file \"#{config_file}\" for reading"
Expand Down
Loading

0 comments on commit 97c71dd

Please sign in to comment.