Class: Gitenv::Symlink

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

Defined Under Namespace

Classes: Action

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Symlink.



23
24
25
26
27
28
29
30
31
# File 'lib/gitenv/actions/symlink.rb', line 23

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

Instance Method Details

#applyObject



33
34
35
36
37
38
39
40
41
42
# File 'lib/gitenv/actions/symlink.rb', line 33

def apply
  FileUtils.mkdir_p File.dirname(link) if @mkdir
  backup_exists = File.exist? link_backup
  FileUtils.mv link, link_backup if @backup && file_or_symlink_exists?(link) && !backup_exists
  return if File.symlink?(link) && File.readlink(link) == target

  # TODO: only if link points somewhere else
  FileUtils.rm link if @overwrite && file_or_symlink_exists?(link) && !backup_exists
  File.symlink target, link unless File.exist?(link)
end


72
73
74
# File 'lib/gitenv/actions/symlink.rb', line 72

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


76
77
78
# File 'lib/gitenv/actions/symlink.rb', line 76

def link_backup
  @link_backup ||= "#{link}.orig"
end

#statusObject



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/gitenv/actions/symlink.rb', line 48

def status
  backup_notice = (' backup the file and' if @backup)
  if File.symlink? link
    current_target = File.expand_path File.readlink(link)
    if @overwrite == false || current_target == target
      Status.ok 'ok'
    elsif !@overwrite
      Status.error "exists but points to #{current_target}; enable overwrite if you want to replace it"
    elsif @backup && File.exist?(link_backup)
      Status.error 'already exists with backup copy'
    else
      Status.warning "currently points to #{current_target}; apply will#{backup_notice} overwrite"
    end
  elsif File.exist? link
    if @overwrite
      Status.warning "exists but is not a symlink; apply will#{backup_notice} overwrite"
    else
      Status.error 'exists but is not a symlink; apply will ignore'
    end
  else
    Status.missing 'is not set up; apply will create the link'
  end
end

#targetObject



80
81
82
# File 'lib/gitenv/actions/symlink.rb', line 80

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

#to_sObject



44
45
46
# File 'lib/gitenv/actions/symlink.rb', line 44

def to_s
  "#{Paint[link, :cyan]} #{Paint['->', :bold]} #{target}"
end