summaryrefslogtreecommitdiff
path: root/lib/dslkeywords/file.rb
diff options
context:
space:
mode:
Diffstat (limited to 'lib/dslkeywords/file.rb')
-rw-r--r--lib/dslkeywords/file.rb23
1 files changed, 22 insertions, 1 deletions
diff --git a/lib/dslkeywords/file.rb b/lib/dslkeywords/file.rb
index 501b7c8..e83906e 100644
--- a/lib/dslkeywords/file.rb
+++ b/lib/dslkeywords/file.rb
@@ -1,13 +1,32 @@
+require 'digest'
require 'erb'
require 'fileutils'
require_relative 'resource'
module RCM
+ # Backup the file on change
+ module FileBackup
+ def backup!(path)
+ return unless ::File.exist?(path)
+
+ backup_dir = "#{::File.dirname(path)}/.rcm"
+ Dir.mkdir(backup_dir) unless ::File.directory?(backup_dir)
+ checksum = Digest::SHA256.file(path).hexdigest
+ backup_path = "#{backup_dir}/#{::File.basename(path)}.#{checksum}"
+ return if ::File.exist?(backup_path)
+
+ info("Backing up #{path} -> #{backup_path}")
+ ::File.rename(path, backup_path)
+ end
+ end
+
# Managing files
class File < Resource
attr_reader :path
+ include FileBackup
+
def initialize(path)
super(path)
@path = path
@@ -25,6 +44,7 @@ module RCM
def ensure_line(line) = @ensure_line = line
def evaluate!
+ return unless super
return evaluate_ensure_line! unless @ensure_line.nil?
write_content!(real_content)
@@ -44,9 +64,10 @@ module RCM
def write_content!(text)
create_parent_directory!
debug text if option :debug
- info "Creating file #{@path}"
+ info "Managing file #{@path}"
tmp_path = "#{@path}.tmp"
::File.write(tmp_path, text)
+ backup!(@path)
::File.rename(tmp_path, @path)
end