Browse files

Merge pull request #2 from chrisroberts/file-edit

File edit
  • Loading branch information...
2 parents 0331f2e + 1d3b1a4 commit c67b91fd6a662269d8fdf6d16d2d590aba06554f @dje dje committed Apr 21, 2012
Showing with 60 additions and 7 deletions.
  1. +51 −0 file_edit_patch.rb
  2. +9 −7 recipes/default.rb
View
51 file_edit_patch.rb
@@ -0,0 +1,51 @@
+# This backports a few file edit helpers that became available
+# in 0.10.9. It will only affect chef versions <= 0.10.8 and can
+# be removed completely once support for pre-0.10.10 installs
+# is no longer required
+unless(Chef::Util::FileEdit.public_instance_methods(false).map(&:to_sym).include?(:insert_line_if_no_match))
+ class Chef::Util::FileEdit
+ def insert_line_after_match(regex, newline)
+ search_match(regex, newline, 'i', 1)
+ end
+
+ def insert_line_if_no_match(regex, newline)
+ search_match(regex, newline, 'i', 2)
+ end
+
+ private
+
+ def search_match(regex, replace, command, method)
+
+ #convert regex to a Regexp object (if not already is one) and store it in exp.
+ exp = Regexp.new(regex)
+
+ #loop through contents and do the appropriate operation depending on 'command' and 'method'
+ new_contents = []
+
+ contents.each do |line|
+ if line.match(exp)
+ self.file_edited = true
+ case
+ when command == 'r'
+ new_contents << ((method == 1) ? replace : line.gsub!(exp, replace))
+ when command == 'd'
+ if method == 2
+ new_contents << line.gsub!(exp, "")
+ end
+ when command == 'i'
+ new_contents << line
+ new_contents << replace unless method == 2
+ end
+ else
+ new_contents << line
+ end
+ end
+ if command == 'i' && method == 2 && ! file_edited
+ new_contents << replace
+ self.file_edited = true
+ end
+
+ self.contents = new_contents
+ end
+ end
+end
View
16 recipes/default.rb
@@ -52,12 +52,14 @@
action :nothing
end
-execute "bundle_unicorn" do
- command 'echo "gem \'unicorn\'" >> Gemfile'
- user 'www-data'
- group 'www-data'
- cwd node.gdash.base
- action :nothing
+ruby_block "bundle_unicorn" do
+ block do
+ gemfile = Chef::Util::FileEdit.new(
+ File.join(node.gdash.base, 'Gemfile')
+ )
+ gemfile.insert_line_if_no_match(/unicorn/, 'gem "unicorn"')
+ gemfile.write_file
+ end
notifies :run, resources(:execute => "bundle"), :immediately
not_if do
File.exists?(File.join(node.gdash.base, 'Gemfile')) &&
@@ -75,7 +77,7 @@
creates File.join(node.gdash.base, "Gemfile.lock")
user "www-data"
group "www-data"
- notifies :run, resources(:execute => "bundle_unicorn"), :immediately
+ notifies :create, resources(:ruby_block => "bundle_unicorn"), :immediately
notifies :delete, resources(:directory => File.join(node.gdash.base, 'graph_templates', 'dashboards')), :immediately
end

0 comments on commit c67b91f

Please sign in to comment.