Class: XCRes::FileBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/xcres/builder/file_builder.rb

Direct Known Subclasses

ResourcesBuilder

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#loggerObject

Returns the value of attribute logger.



7
8
9
# File 'lib/xcres/builder/file_builder.rb', line 7

def logger
  @logger
end

#output_pathObject

Returns the value of attribute output_path.



6
7
8
# File 'lib/xcres/builder/file_builder.rb', line 6

def output_path
  @output_path
end

Instance Method Details

#buildObject



24
25
26
# File 'lib/xcres/builder/file_builder.rb', line 24

def build
  prepare_output_path!
end

#build_contents(&block) ⇒ Object



28
29
30
31
32
33
# File 'lib/xcres/builder/file_builder.rb', line 28

def build_contents &block
  # Pass a new string builder to given block
  builder = XCRes::StringBuilder.new
  block.call builder
  builder.result
end

#prepare_output_path!Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/xcres/builder/file_builder.rb', line 9

def prepare_output_path!
  # Ensure that the given directory exists
  output_dir = File.dirname output_path
  unless Dir.exist? output_dir
    logger.success 'Directory did not exist. Will be created.'
    Dir.mkdir output_dir
  end

  # Replace an already existing file, by deleting it and rebuilding from scratch
  if File.exist? output_path
    raise ArgumentError.new 'Output path is a directory!' if Dir.exist? output_path
    logger.warn "Output path already exists. Will be replaced."
  end
end

#write_file(file_path, contents) ⇒ Object



54
55
56
57
58
59
# File 'lib/xcres/builder/file_builder.rb', line 54

def write_file file_path, contents
  # Write file
  File.open file_path, 'w' do |file|
    file.write contents
  end
end

#write_file_eventually(file_path, contents) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/xcres/builder/file_builder.rb', line 35

def write_file_eventually file_path, contents
  # Check if the file already exists and touch it only if the contents changed
  if File.exist? file_path
    tmp_dir_path = `/usr/bin/mktemp -d -t xcres`
    tmp_file_path = tmp_dir_path + File.basename(file_path)

    # Write temp file
    write_file tmp_file_path, contents

    # Diff current version and temporary file
    if FileUtils.compare_file(tmp_file_path, file_path)
      logger.success "Existing file is up-to-date. Don't touch."
      return
    end
  end

  write_file file_path, contents
end