aboutsummaryrefslogtreecommitdiffstats
path: root/Library/Homebrew/cmd/link.rb
blob: 67ce43478a3adfa2625f953ad9568f1ccd85dbac (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
require 'ostruct'

module Homebrew extend self

  def link
    raise KegUnspecifiedError if ARGV.named.empty?

    mode = OpenStruct.new

    mode.overwrite = true if ARGV.include? '--overwrite'
    mode.dry_run = true if ARGV.dry_run?

    ARGV.kegs.each do |keg|
      if keg.linked?
        opoo "Already linked: #{keg}"
        puts "To relink: brew unlink #{keg.fname} && brew link #{keg.fname}"
        next
      elsif keg_only?(keg.fname) && !ARGV.force?
        opoo "#{keg.fname} is keg-only and must be linked with --force"
        puts "Note that doing so can interfere with building software."
        next
      elsif mode.dry_run && mode.overwrite
        print "Would remove:\n" do
          keg.link(mode)
        end

        next
      elsif mode.dry_run
        print "Would link:\n" do
          keg.link(mode)
        end

        next
      end

      keg.lock do
        print "Linking #{keg}... " do
          puts "#{keg.link(mode)} symlinks created"
        end
      end
    end
  end

  private

  def keg_only?(name)
    Formula.factory(name).keg_only?
  rescue FormulaUnavailableError
    false
  end

  # Allows us to ensure a puts happens before the block exits so that if say,
  # an exception is thrown, its output starts on a new line.
  def print str, &block
    Kernel.print str
    puts_capture = Class.new do
      def self.puts str
        $did_puts = true
        Kernel.puts str
      end
    end

    puts_capture.instance_eval(&block)

  ensure
    puts unless $did_puts
  end

end