summaryrefslogtreecommitdiff
path: root/lib/dslkeywords
diff options
context:
space:
mode:
Diffstat (limited to 'lib/dslkeywords')
-rw-r--r--lib/dslkeywords/file.rb78
-rw-r--r--lib/dslkeywords/only_when.rb37
2 files changed, 115 insertions, 0 deletions
diff --git a/lib/dslkeywords/file.rb b/lib/dslkeywords/file.rb
new file mode 100644
index 0000000..a22e52f
--- /dev/null
+++ b/lib/dslkeywords/file.rb
@@ -0,0 +1,78 @@
+require 'erb'
+require 'fileutils'
+
+require_relative '../options'
+require_relative '../log'
+
+module RCM
+ # Managing files
+ class File
+ attr_reader :id, :path
+
+ include Options
+ include Log
+
+ def initialize(path)
+ @id = "#{self.class}(#{path})"
+ @path = path
+ end
+
+ def to_s
+ id
+ end
+
+ def content(content = nil)
+ content.nil? ? @content : @content = content
+ end
+
+ def create_parent_directory
+ @create_parent = true
+ self
+ end
+
+ def from_file(...)
+ @from_file = true
+ self
+ end
+
+ def from_template(...)
+ @from_template = true
+ self
+ end
+
+ def do!
+ content = file_content
+
+ dirname = ::File.dirname(@path)
+ if !::File.directory?(dirname) && @create_parent
+ info "Creating parent directory #{parent}"
+ FileUtils.mkdir_p(dirname)
+ end
+
+ info "Creating file #{@path}"
+ debug content if option :debug
+
+ tmp_path = "#{@path}.tmp"
+ ::File.write(tmp_path, content)
+ ::File.rename(tmp_path, @path)
+ end
+
+ private
+
+ def file_content
+ content = @from_file ? ::File.read(@content) : @content
+ @from_template ? ERB.new(content).result : content
+ end
+ end
+
+ # Add file keyword to the DSL
+ class RCM
+ def file(path, &block)
+ return unless @conds_met
+
+ f = File.new(path)
+ f.instance_eval(&block)
+ self << f
+ end
+ end
+end
diff --git a/lib/dslkeywords/only_when.rb b/lib/dslkeywords/only_when.rb
new file mode 100644
index 0000000..2700bee
--- /dev/null
+++ b/lib/dslkeywords/only_when.rb
@@ -0,0 +1,37 @@
+module RCM
+ # OnlyWhen (e.g. run on host foo)
+ class OnlyWhen
+ require 'socket'
+
+ def initialize
+ @conds = {}
+ end
+
+ def is(arg)
+ arg
+ end
+
+ def method_missing(method_name, *args, &block)
+ @conds[method_name] = args.first
+ end
+
+ def respond_to_missing?
+ true
+ end
+
+ def met?
+ return false if @conds.key?(:hostname) && Socket.gethostname != @conds[:hostname].to_s
+
+ true
+ end
+ end
+
+ # Add 'only_when' to DSL
+ class RCM
+ def only_when(&block)
+ conds = OnlyWhen.new
+ conds.instance_eval(&block)
+ @conds_met = conds.met?
+ end
+ end
+end