Class: FileDiscard::Discarder

Inherits:
Object
  • Object
show all
Defined in:
lib/file_discard.rb

Overview

The core logic for moving files to an appropriate trash directory.

Direct Known Subclasses

LinuxDiscarder, OsxDiscarder

Constant Summary collapse

SPECIAL_DIRS =

:nodoc:

['.','..']

Instance Method Summary collapse

Constructor Details

#initialize(home, home_trash, mountpoint_trash_fmt) ⇒ Discarder

Returns a new instance of Discarder.



92
93
94
95
96
97
# File 'lib/file_discard.rb', line 92

def initialize(home, home_trash, mountpoint_trash_fmt)
  home = pathname_for(home).expand_path
  @home_trash = home.join(home_trash)
  @home_mountpoint = mountpoint_of home
  @mountpoint_trash_fmt = mountpoint_trash_fmt
end

Instance Method Details

#discard(obj, options = {}) ⇒ Object

Request that obj be moved to the trash.

options - a hash of any of the following:

  • :directory - allow an empty directory to be discarded

  • :recursive - allow a directory to be discarded even if not empty

  • :verbose - report the move operation

May raise:

  • Errno::EINVAL - obj is “.” or “..” which are not allowed to be discarded

  • Errno::EISDIR - obj is a directory

  • Errno::ENOTEMPTY - obj is a directory with children

  • Errno::ENOENT - obj does not exist on the file system

  • TrashMissing - the trash directory for the mountpoint associated with obj did not exist



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/file_discard.rb', line 113

def discard(obj, options = {})
  pn = pathname_for obj
  if pn.directory?
    SPECIAL_DIRS.include?(pn.basename.to_s) and
      raise Errno::EINVAL.new(SPECIAL_DIRS.join(' and ') << ' may not be removed')
    unless options[:recursive]
      options[:directory] or raise Errno::EISDIR.new(pn.to_s)
      pn.children.any? and raise Errno::ENOTEMPTY.new(pn.to_s)
    end
  end

  if options.key?(:force) && options[:force] > 1
    $stderr.puts "Warning: Permanently removing #{pn}"
    FileUtils.rm_rf(pn, {verbose: options[:verbose] || false})
    return
  end

  trash = find_trash_for pn
  unless trash.exist?
    FileDiscard.create_trash_when_missing or raise TrashMissing.new(trash.to_s)
    trash.mkpath
  end

  move_options = options.has_key?(:verbose) ? {verbose: options[:verbose]} : {}
  move(pn, trash, move_options)
end