Class: Gitenv::Copy

Inherits:
Object
  • Object
show all
Defined in:
lib/gitenv/actions/copy.rb

Defined Under Namespace

Classes: Action

Instance Method Summary collapse

Constructor Details

#initialize(context, file, options = {}) ⇒ Copy

Returns a new instance of Copy.



30
31
32
33
34
35
# File 'lib/gitenv/actions/copy.rb', line 30

def initialize context, file, options = {}
  @context, @file = context, file
  @as, @overwrite, @backup = options[:as], options[:overwrite], options[:backup]
  @mkdir = options.fetch :mkdir, true
  @backup = true if @overwrite && !options.key?(:backup)
end

Instance Method Details

#applyObject



37
38
39
40
41
42
43
44
# File 'lib/gitenv/actions/copy.rb', line 37

def apply
  # TODO: test with mkdir option set to false
  FileUtils.mkdir_p File.dirname(target) if @mkdir
  backup_exists = File.exist? target_backup
  FileUtils.mv target, target_backup if @backup && File.exist?(target) && !backup_exists
  FileUtils.rm target if @overwrite && File.exist?(target) && !backup_exists
  FileUtils.cp origin, target unless File.exist?(target)
end

#originObject



65
66
67
# File 'lib/gitenv/actions/copy.rb', line 65

def origin
  @origin ||= File.join(*[ @context.from, @file ].compact)
end

#statusObject



50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/gitenv/actions/copy.rb', line 50

def status
  if !File.exist?(target)
    Status.missing "is not set up; apply will create the copy"
  elsif @overwrite == false || digest(origin) == digest(target)
    Status.ok 'ok'
  elsif !@overwrite
    Status.error "already exists; enable overwrite if you want to replace it"
  elsif @backup && File.exist?(target_backup)
    Status.error "already exists with backup copy"
  else
    backup_notice = if @backup; " backup the file and"; end
    Status.warning "already exists; apply will#{backup_notice} overwrite"
  end
end

#targetObject



69
70
71
# File 'lib/gitenv/actions/copy.rb', line 69

def target
  @target ||= File.join(*[ @context.to, target_name].compact)
end

#target_backupObject



73
74
75
# File 'lib/gitenv/actions/copy.rb', line 73

def target_backup
  @target_backup ||= "#{target}.orig"
end

#to_sObject



46
47
48
# File 'lib/gitenv/actions/copy.rb', line 46

def to_s
  "#{Paint[target, :cyan]} #{Paint['<', :bold]} #{origin}"
end