80 lines
1.3 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
2020-08-14 02:06:33 +02:00
# Represention of a `*PATH` environment variable.
#
# @api private
2017-04-27 08:48:29 +02:00
class PATH
2017-04-28 12:39:00 +02:00
include Enumerable
extend Forwardable
def_delegator :@paths, :each
2017-04-27 08:48:29 +02:00
def initialize(*paths)
@paths = parse(*paths)
end
def prepend(*paths)
@paths = parse(*paths, *@paths)
2017-04-27 08:48:29 +02:00
self
end
def append(*paths)
@paths = parse(*@paths, *paths)
2017-04-27 08:48:29 +02:00
self
end
2017-04-28 12:39:00 +02:00
def insert(index, *paths)
@paths = parse(*@paths.insert(index, *paths))
self
end
def select(&block)
self.class.new(@paths.select(&block))
end
def reject(&block)
self.class.new(@paths.reject(&block))
end
2017-04-27 08:48:29 +02:00
def to_ary
2018-04-14 06:46:01 +02:00
@paths.dup.to_ary
2017-04-27 08:48:29 +02:00
end
alias to_a to_ary
def to_str
@paths.join(File::PATH_SEPARATOR)
end
alias to_s to_str
2017-04-28 11:12:02 +02:00
def ==(other)
2017-04-27 08:48:29 +02:00
if other.respond_to?(:to_ary)
return true if to_ary == other.to_ary
end
if other.respond_to?(:to_str)
return true if to_str == other.to_str
end
false
end
def empty?
@paths.empty?
end
def existing
existing_path = select(&File.method(:directory?))
# return nil instead of empty PATH, to unset environment variables
existing_path unless existing_path.empty?
2017-04-27 08:48:29 +02:00
end
private
def parse(*paths)
2017-04-28 20:46:52 +02:00
paths.flatten
.compact
.flat_map { |p| Pathname.new(p).to_path.split(File::PATH_SEPARATOR) }
.uniq
2017-04-27 08:48:29 +02:00
end
end