/
file_creator.rb
45 lines (36 loc) · 1.02 KB
/
file_creator.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# frozen_string_literal: true
module Jekyll
module Compose
class FileCreator
attr_reader :file, :force, :root
def initialize(file_info, force = false, root = nil)
@file = file_info
@force = force
@root = root
end
def create!
validate_should_write!
ensure_directory_exists
write_file
end
def file_path
return file.path if root.nil? || root.empty?
File.join(root, file.path)
end
private
def validate_should_write!
return Jekyll.logger.warn "A #{file.resource_type} already exists at #{file_path}".yellow if File.exist?(file_path) && !force
end
def ensure_directory_exists
dir = File.dirname file_path
FileUtils.mkdir_p(dir) unless Dir.exist?(dir)
end
def write_file
File.open(file_path, "w") do |f|
f.puts(file.content)
end
Jekyll.logger.info "New #{file.resource_type} created at #{file_path.cyan}"
end
end
end
end