aboutsummaryrefslogtreecommitdiffstats
path: root/Library/Homebrew/PATH.rb
blob: de7167eb4b1278c0d2116822469df66250b05cc5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class PATH
  include Enumerable
  extend Forwardable

  def_delegator :@paths, :each

  def initialize(*paths)
    @paths = parse(*paths)
  end

  def prepend(*paths)
    @paths = parse(*paths, *@paths)
    self
  end

  def append(*paths)
    @paths = parse(*@paths, *paths)
    self
  end

  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

  def to_ary
    @paths
  end
  alias to_a to_ary

  def to_str
    @paths.join(File::PATH_SEPARATOR)
  end
  alias to_s to_str

  def ==(other)
    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?
  end

  private

  def parse(*paths)
    paths.flatten
         .compact
         .flat_map { |p| Pathname.new(p).to_path.split(File::PATH_SEPARATOR) }
         .uniq
  end
end