2019-04-19 15:38:03 +09:00
|
|
|
# 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)
|
2017-04-28 11:22:23 +02:00
|
|
|
@paths = parse(*paths, *@paths)
|
2017-04-27 08:48:29 +02:00
|
|
|
self
|
|
|
|
end
|
|
|
|
|
|
|
|
def append(*paths)
|
2017-04-28 11:22:23 +02:00
|
|
|
@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
|
|
|
|
|
2017-04-28 12:42:17 +02:00
|
|
|
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
|
|
|
|
|
2017-04-28 12:42:17 +02:00
|
|
|
def existing
|
|
|
|
existing_path = select(&File.method(:directory?))
|
2017-04-30 21:23:12 +02:00
|
|
|
# return nil instead of empty PATH, to unset environment variables
|
2017-04-28 12:42:17 +02:00
|
|
|
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
|