Class: Caco::FileWriter

Inherits:
Trailblazer::Operation
  • Object
show all
Defined in:
lib/caco/file_writer.rb

Constant Summary collapse

SameMD5 =
Class.new(Trailblazer::Activity::Signal)
DifferentMD5 =
Class.new(Trailblazer::Activity::Signal)
UseCustomRoot =
Class.new(Trailblazer::Activity::Signal)

Instance Method Summary collapse

Instance Method Details

#calculate_md5(ctx, path:, file_exist:, content:) ⇒ Object



31
32
33
34
# File 'lib/caco/file_writer.rb', line 31

def calculate_md5(ctx, path:, file_exist:, content:, **)
  ctx[:current_md5] = (file_exist ? Digest::MD5.hexdigest(File.read(path)) : "")
  ctx[:content_md5] = Digest::MD5.hexdigest(content)
end

#compare_md5(ctx, content_md5:, current_md5:) ⇒ Object



36
37
38
39
40
# File 'lib/caco/file_writer.rb', line 36

def compare_md5(ctx, content_md5:, current_md5:, **)
  different_md5 = (content_md5 != current_md5)
  ctx[:file_changed] = different_md5 ? true : false
  different_md5 ? DifferentMD5 : SameMD5
end

#file_exist(ctx, path:) ⇒ Object



25
26
27
28
29
# File 'lib/caco/file_writer.rb', line 25

def file_exist(ctx, path:, **)
  ctx[:file_exist] = File.exist?(path)
  ctx[:file_created] = !ctx[:file_exist]
  ctx[:file_exist]
end

#mkdir_p(ctx, path:) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/caco/file_writer.rb', line 42

def mkdir_p(ctx, path:, **)
  dirname = File.dirname(path)
  if Caco.config.write_files
    FileUtils.mkdir_p(dirname) unless File.exist?(dirname)
  end
  true
end

#use_custom_root(ctx, path:) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/caco/file_writer.rb', line 17

def use_custom_root(ctx, path:, **)
  return true unless Caco.config.write_files_root
  unless ctx[:path].start_with?(Caco.config.write_files_root.to_s)
    ctx[:path] = "#{Caco.config.write_files_root}#{ctx[:path]}"
  end
  UseCustomRoot
end

#write_file(ctx, path:, content:, file_exist:) ⇒ Object



50
51
52
53
54
55
56
# File 'lib/caco/file_writer.rb', line 50

def write_file(ctx, path:, content:, file_exist:, **)
  if Caco.config.write_files
    File.write(path, content)
  end
  ctx[:file_created] = !file_exist
  ctx[:file_changed] = true
end