Core files style updates.

Closes Homebrew/homebrew#42354.

Signed-off-by: Mike McQuaid <mike@mikemcquaid.com>
This commit is contained in:
BrewTestBot 2015-08-03 13:09:07 +01:00 committed by Mike McQuaid
parent 3b68215be7
commit 13d544e11e
184 changed files with 2954 additions and 2756 deletions

View File

@ -12,7 +12,7 @@ class ExampleFormula < Formula
desc "Example formula" # shows up in `brew info`, and can be searched with `brew search --desc`. desc "Example formula" # shows up in `brew info`, and can be searched with `brew search --desc`.
homepage "https://www.example.com" # used by `brew home example-formula`. homepage "https://www.example.com" # used by `brew home example-formula`.
revision 1 # This is used when there's no new version but it needs recompiling for another reason. revision 1 # This is used when there's no new version but it needs recompiling for another reason.
# 0 is default & unwritten. # 0 is default & unwritten.
# The URL of the archive. Prefer https (security and proxy issues): # The URL of the archive. Prefer https (security and proxy issues):
url "https://packed.sources.and.we.prefer.https.example.com/archive-1.2.3.tar.bz2" url "https://packed.sources.and.we.prefer.https.example.com/archive-1.2.3.tar.bz2"
@ -72,7 +72,6 @@ class ExampleFormula < Formula
depends_on "pixman" depends_on "pixman"
end end
## Options ## Options
# Options can be used as arguments to `brew install`. # Options can be used as arguments to `brew install`.
@ -120,7 +119,6 @@ class ExampleFormula < Formula
keg_only :provided_by_osx keg_only :provided_by_osx
keg_only "because I want it so" keg_only "because I want it so"
## Dependencies ## Dependencies
# The dependencies for this formula. Use strings for the names of other # The dependencies for this formula. Use strings for the names of other
@ -184,7 +182,6 @@ class ExampleFormula < Formula
# If this formula conflicts with another one: # If this formula conflicts with another one:
conflicts_with "imagemagick", :because => "because this is just a stupid example" conflicts_with "imagemagick", :because => "because this is just a stupid example"
## Failing with a certain compiler? ## Failing with a certain compiler?
# If it is failing for certain compiler: # If it is failing for certain compiler:
@ -208,7 +205,6 @@ class ExampleFormula < Formula
sha256 "c6bc3f48ce8e797854c4b865f6a8ff969867bbcaebd648ae6fd825683e59fef2" sha256 "c6bc3f48ce8e797854c4b865f6a8ff969867bbcaebd648ae6fd825683e59fef2"
end end
## Patches ## Patches
# External patches can be declared using resource-style blocks. # External patches can be declared using resource-style blocks.
@ -399,7 +395,6 @@ class ExampleFormula < Formula
# `name` and `version` are accessible too, if you need them. # `name` and `version` are accessible too, if you need them.
end end
## Caveats ## Caveats
def caveats def caveats
@ -416,7 +411,6 @@ class ExampleFormula < Formula
s s
end end
## Test (is optional but makes us happy) ## Test (is optional but makes us happy)
test do test do
@ -444,7 +438,6 @@ class ExampleFormula < Formula
# Failed assertions and failed `system` commands will raise exceptions. # Failed assertions and failed `system` commands will raise exceptions.
end end
## Plist handling ## Plist handling
# Does your plist need to be loaded at startup? # Does your plist need to be loaded at startup?

View File

@ -1,8 +1,8 @@
#!/System/Library/Frameworks/Ruby.framework/Versions/Current/usr/bin/ruby -W0 #!/System/Library/Frameworks/Ruby.framework/Versions/Current/usr/bin/ruby -W0
$:.unshift Dir["/System/Library/Frameworks/Ruby.framework/Versions/Current/usr/lib/ruby/{1.8,2.0.0}"].first $:.unshift Dir["/System/Library/Frameworks/Ruby.framework/Versions/Current/usr/lib/ruby/{1.8,2.0.0}"].first
require 'pathname' require "pathname"
require 'set' require "set"
class Cmd class Cmd
attr_reader :config, :prefix, :cellar, :tmpdir, :sysroot attr_reader :config, :prefix, :cellar, :tmpdir, :sysroot
@ -12,24 +12,24 @@ class Cmd
@arg0 = arg0 @arg0 = arg0
@args = args.freeze @args = args.freeze
@config = ENV.fetch("HOMEBREW_CCCFG") { "" } @config = ENV.fetch("HOMEBREW_CCCFG") { "" }
@prefix = ENV['HOMEBREW_PREFIX'] @prefix = ENV["HOMEBREW_PREFIX"]
@cellar = ENV['HOMEBREW_CELLAR'] @cellar = ENV["HOMEBREW_CELLAR"]
@tmpdir = ENV['HOMEBREW_TEMP'] @tmpdir = ENV["HOMEBREW_TEMP"]
@sysroot = ENV['HOMEBREW_SDKROOT'] @sysroot = ENV["HOMEBREW_SDKROOT"]
@archflags = ENV.fetch("HOMEBREW_ARCHFLAGS") { "" }.split(" ") @archflags = ENV.fetch("HOMEBREW_ARCHFLAGS") { "" }.split(" ")
@optflags = ENV.fetch("HOMEBREW_OPTFLAGS") { "" }.split(" ") @optflags = ENV.fetch("HOMEBREW_OPTFLAGS") { "" }.split(" ")
end end
def mode def mode
if @arg0 == 'cpp' or @arg0 == 'ld' if @arg0 == "cpp" or @arg0 == "ld"
@arg0.to_sym @arg0.to_sym
elsif @args.include? '-c' elsif @args.include? "-c"
if @arg0 =~ /(?:c|g|clang)\+\+/ if @arg0 =~ /(?:c|g|clang)\+\+/
:cxx :cxx
else else
:cc :cc
end end
elsif @args.include? '-E' elsif @args.include? "-E"
:ccE :ccE
else else
if @arg0 =~ /(?:c|g|clang)\+\+/ if @arg0 =~ /(?:c|g|clang)\+\+/
@ -42,26 +42,26 @@ class Cmd
def tool def tool
@tool ||= case @arg0 @tool ||= case @arg0
when 'ld' then 'ld' when "ld" then "ld"
when 'cpp' then 'cpp' when "cpp" then "cpp"
when /\w\+\+(-\d(\.\d)?)?$/ when /\w\+\+(-\d(\.\d)?)?$/
case ENV['HOMEBREW_CC'] case ENV["HOMEBREW_CC"]
when /clang/ when /clang/
'clang++' "clang++"
when /llvm-gcc/ when /llvm-gcc/
'llvm-g++-4.2' "llvm-g++-4.2"
when /gcc(-\d(\.\d)?)?$/ when /gcc(-\d(\.\d)?)?$/
'g++' + $1.to_s "g++" + $1.to_s
end end
else else
# Note that this is a universal fallback, so that we'll always invoke # Note that this is a universal fallback, so that we'll always invoke
# HOMEBREW_CC regardless of what name under which the tool was invoked. # HOMEBREW_CC regardless of what name under which the tool was invoked.
ENV['HOMEBREW_CC'] ENV["HOMEBREW_CC"]
end end
end end
def args def args
if @args.length == 1 and @args[0] == '-v' if @args.length == 1 and @args[0] == "-v"
# Don't add linker arguments if -v passed as sole option. This stops gcc # Don't add linker arguments if -v passed as sole option. This stops gcc
# -v with no other arguments from outputting a linker error. Some # -v with no other arguments from outputting a linker error. Some
# software uses gcc -v (wrongly) to sniff the GCC version. # software uses gcc -v (wrongly) to sniff the GCC version.
@ -135,34 +135,34 @@ class Cmd
args = [] args = []
case arg case arg
when /^-g\d?/, /^-gstabs\d+/, '-gstabs+', /^-ggdb\d?/, '-gdwarf-2', when /^-g\d?/, /^-gstabs\d+/, "-gstabs+", /^-ggdb\d?/, "-gdwarf-2",
/^-march=.+/, /^-mtune=.+/, /^-mcpu=.+/, /^-march=.+/, /^-mtune=.+/, /^-mcpu=.+/,
/^-O[0-9zs]?$/, '-fast', '-no-cpp-precomp', /^-O[0-9zs]?$/, "-fast", "-no-cpp-precomp",
'-pedantic', '-pedantic-errors', '-Wno-long-double', "-pedantic", "-pedantic-errors", "-Wno-long-double",
'-Wno-unused-but-set-variable' "-Wno-unused-but-set-variable"
when '-fopenmp', '-lgomp', '-mno-fused-madd', '-fforce-addr', '-fno-defer-pop', when "-fopenmp", "-lgomp", "-mno-fused-madd", "-fforce-addr", "-fno-defer-pop",
'-mno-dynamic-no-pic', '-fearly-inlining', /^-f(?:no-)?inline-functions-called-once/, "-mno-dynamic-no-pic", "-fearly-inlining", /^-f(?:no-)?inline-functions-called-once/,
/^-finline-limit/, /^-f(?:no-)?check-new/, '-fno-delete-null-pointer-checks', /^-finline-limit/, /^-f(?:no-)?check-new/, "-fno-delete-null-pointer-checks",
'-fcaller-saves', '-fthread-jumps', '-fno-reorder-blocks', '-fcse-skip-blocks', "-fcaller-saves", "-fthread-jumps", "-fno-reorder-blocks", "-fcse-skip-blocks",
'-frerun-cse-after-loop', '-frerun-loop-opt', '-fcse-follow-jumps', "-frerun-cse-after-loop", "-frerun-loop-opt", "-fcse-follow-jumps",
'-fno-regmove', '-fno-for-scope', '-fno-tree-pre', '-fno-tree-dominator-opts', "-fno-regmove", "-fno-for-scope", "-fno-tree-pre", "-fno-tree-dominator-opts",
'-fuse-linker-plugin' "-fuse-linker-plugin"
# clang doesn't support these flags # clang doesn't support these flags
args << arg if not tool =~ /^clang/ args << arg unless tool =~ /^clang/
when /^-W[alp],/, /^-Wno-/ when /^-W[alp],/, /^-Wno-/
args << arg args << arg
when /^-W.*/ when /^-W.*/
# prune warnings # prune warnings
when '-macosx_version_min', '-dylib_install_name' when "-macosx_version_min", "-dylib_install_name"
args << "-Wl,#{arg},#{enum.next}" args << "-Wl,#{arg},#{enum.next}"
when '-multiply_definedsuppress' when "-multiply_definedsuppress"
args << "-Wl,-multiply_defined,suppress" args << "-Wl,-multiply_defined,suppress"
when '-undefineddynamic_lookup' when "-undefineddynamic_lookup"
args << "-Wl,-undefined,dynamic_lookup" args << "-Wl,-undefined,dynamic_lookup"
when /^-isysroot/, /^--sysroot/ when /^-isysroot/, /^--sysroot/
# We set the sysroot # We set the sysroot
enum.next enum.next
when '-dylib' when "-dylib"
args << "-Wl,#{arg}" args << "-Wl,#{arg}"
when /^-I(.+)?/ when /^-I(.+)?/
# Support both "-Ifoo" (one argument) and "-I foo" (two arguments) # Support both "-Ifoo" (one argument) and "-I foo" (two arguments)
@ -180,7 +180,7 @@ class Cmd
args args
end end
def keep? path def keep?(path)
path.start_with?(prefix, cellar, tmpdir) || !path.start_with?("/opt", "/sw", "/usr/X11") path.start_with?(prefix, cellar, tmpdir) || !path.start_with?("/opt", "/sw", "/usr/X11")
end end
@ -189,8 +189,8 @@ class Cmd
return args unless refurbish_args? || configure? return args unless refurbish_args? || configure?
args << '-pipe' args << "-pipe"
args << '-w' unless configure? args << "-w" unless configure?
args << "-#{ENV["HOMEBREW_OPTIMIZATION_LEVEL"]}" args << "-#{ENV["HOMEBREW_OPTIMIZATION_LEVEL"]}"
args.concat(optflags) args.concat(optflags)
args.concat(archflags) args.concat(archflags)
@ -234,12 +234,12 @@ class Cmd
end end
def system_library_paths def system_library_paths
%W{#{sysroot}/usr/lib /usr/local/lib} %W[#{sysroot}/usr/lib /usr/local/lib]
end end
def configure? def configure?
# configure scripts generated with autoconf 2.61 or later export as_nl # configure scripts generated with autoconf 2.61 or later export as_nl
ENV.key? 'as_nl' ENV.key? "as_nl"
end end
def refurbish_args? def refurbish_args?
@ -300,11 +300,11 @@ end
if __FILE__ == $PROGRAM_NAME if __FILE__ == $PROGRAM_NAME
##################################################################### sanity ##################################################################### sanity
abort "The build-tool has reset ENV. --env=std required." unless ENV['HOMEBREW_BREW_FILE'] abort "The build-tool has reset ENV. --env=std required." unless ENV["HOMEBREW_BREW_FILE"]
if (cc = ENV["HOMEBREW_CC"]).nil? || cc.empty? || cc == "cc" if (cc = ENV["HOMEBREW_CC"]).nil? || cc.empty? || cc == "cc"
# those values are not allowed # those values are not allowed
ENV['HOMEBREW_CC'] = 'clang' ENV["HOMEBREW_CC"] = "clang"
end end
####################################################################### main ####################################################################### main
@ -312,7 +312,8 @@ if __FILE__ == $PROGRAM_NAME
dirname, basename = File.split($0) dirname, basename = File.split($0)
cmd = Cmd.new(basename, ARGV) cmd = Cmd.new(basename, ARGV)
tool, args = cmd.tool, cmd.args tool = cmd.tool
args = cmd.args
log(basename, ARGV, tool, args) log(basename, ARGV, tool, args)

View File

@ -5,7 +5,7 @@
F = File.basename(__FILE__).freeze F = File.basename(__FILE__).freeze
D = File.expand_path(File.dirname(__FILE__)).freeze D = File.expand_path(File.dirname(__FILE__)).freeze
def exec *args def exec(*args)
# prevent fork-bombs # prevent fork-bombs
arg0 = args.first arg0 = args.first
return if arg0 =~ /^#{F}/i || File.expand_path(arg0) == File.expand_path(__FILE__) return if arg0 =~ /^#{F}/i || File.expand_path(arg0) == File.expand_path(__FILE__)
@ -13,9 +13,9 @@ def exec *args
end end
case F.downcase case F.downcase
when 'git' then %W{HOMEBREW_GIT GIT} when "git" then %W[HOMEBREW_GIT GIT]
when 'svn' then %W{HOMEBREW_SVN} when "svn" then %W[HOMEBREW_SVN]
else [] else []
end.each do |key| end.each do |key|
exec ENV[key], *ARGV if ENV[key] and File.executable? ENV[key] exec ENV[key], *ARGV if ENV[key] and File.executable? ENV[key]
end end

View File

@ -1,29 +1,29 @@
def blacklisted? name def blacklisted?(name)
case name.downcase case name.downcase
when 'gem', /^rubygems?$/ then <<-EOS.undent when "gem", /^rubygems?$/ then <<-EOS.undent
Homebrew provides gem via: `brew install ruby`. Homebrew provides gem via: `brew install ruby`.
EOS EOS
when 'tex', 'tex-live', 'texlive', 'latex' then <<-EOS.undent when "tex", "tex-live", "texlive", "latex" then <<-EOS.undent
Installing TeX from source is weird and gross, requires a lot of patches, Installing TeX from source is weird and gross, requires a lot of patches,
and only builds 32-bit (and thus can't use Homebrew deps on Snow Leopard.) and only builds 32-bit (and thus can't use Homebrew deps on Snow Leopard.)
We recommend using a MacTeX distribution: https://www.tug.org/mactex/ We recommend using a MacTeX distribution: https://www.tug.org/mactex/
EOS EOS
when 'pip' then <<-EOS.undent when "pip" then <<-EOS.undent
Homebrew provides pip via: `brew install python`. However you will then Homebrew provides pip via: `brew install python`. However you will then
have two Pythons installed on your Mac, so alternatively you can: have two Pythons installed on your Mac, so alternatively you can:
sudo easy_install pip sudo easy_install pip
EOS EOS
when 'pil' then <<-EOS.undent when "pil" then <<-EOS.undent
Instead of PIL, consider `pip install pillow` or `brew install Homebrew/python/pillow`. Instead of PIL, consider `pip install pillow` or `brew install Homebrew/python/pillow`.
EOS EOS
when 'macruby' then <<-EOS.undent when "macruby" then <<-EOS.undent
MacRuby works better when you install their package: MacRuby works better when you install their package:
http://www.macruby.org/ http://www.macruby.org/
EOS EOS
when /(lib)?lzma/ when /(lib)?lzma/
"lzma is now part of the xz formula." "lzma is now part of the xz formula."
when 'xcode' when "xcode"
if MacOS.version >= :lion if MacOS.version >= :lion
<<-EOS.undent <<-EOS.undent
Xcode can be installed from the App Store. Xcode can be installed from the App Store.
@ -33,22 +33,22 @@ def blacklisted? name
Xcode can be installed from https://developer.apple.com/xcode/downloads/ Xcode can be installed from https://developer.apple.com/xcode/downloads/
EOS EOS
end end
when 'gtest', 'googletest', 'google-test' then <<-EOS.undent when "gtest", "googletest", "google-test" then <<-EOS.undent
Installing gtest system-wide is not recommended; it should be vendored Installing gtest system-wide is not recommended; it should be vendored
in your projects that use it. in your projects that use it.
EOS EOS
when 'gmock', 'googlemock', 'google-mock' then <<-EOS.undent when "gmock", "googlemock", "google-mock" then <<-EOS.undent
Installing gmock system-wide is not recommended; it should be vendored Installing gmock system-wide is not recommended; it should be vendored
in your projects that use it. in your projects that use it.
EOS EOS
when 'sshpass' then <<-EOS.undent when "sshpass" then <<-EOS.undent
We won't add sshpass because it makes it too easy for novice SSH users to We won't add sshpass because it makes it too easy for novice SSH users to
ruin SSH's security. ruin SSH's security.
EOS EOS
when 'gsutil' then <<-EOS.undent when "gsutil" then <<-EOS.undent
Install gsutil with `pip install gsutil` Install gsutil with `pip install gsutil`
EOS EOS
when 'clojure' then <<-EOS.undent when "clojure" then <<-EOS.undent
Clojure isn't really a program but a library managed as part of a Clojure isn't really a program but a library managed as part of a
project and Leiningen is the user interface to that library. project and Leiningen is the user interface to that library.
@ -57,15 +57,15 @@ def blacklisted? name
and then follow the tutorial: and then follow the tutorial:
https://github.com/technomancy/leiningen/blob/stable/doc/TUTORIAL.md https://github.com/technomancy/leiningen/blob/stable/doc/TUTORIAL.md
EOS EOS
when 'osmium' then <<-EOS.undent when "osmium" then <<-EOS.undent
The creator of Osmium requests that it not be packaged and that people The creator of Osmium requests that it not be packaged and that people
use the GitHub master branch instead. use the GitHub master branch instead.
EOS EOS
when 'gfortran' then <<-EOS.undent when "gfortran" then <<-EOS.undent
GNU Fortran is now provided as part of GCC, and can be installed with: GNU Fortran is now provided as part of GCC, and can be installed with:
brew install gcc brew install gcc
EOS EOS
when 'play' then <<-EOS.undent when "play" then <<-EOS.undent
Play 2.3 replaces the play command with activator: Play 2.3 replaces the play command with activator:
brew install typesafe-activator brew install typesafe-activator
@ -73,7 +73,7 @@ def blacklisted? name
https://www.playframework.com/documentation/2.3.x/Migration23 https://www.playframework.com/documentation/2.3.x/Migration23
https://www.playframework.com/documentation/2.3.x/Highlights23 https://www.playframework.com/documentation/2.3.x/Highlights23
EOS EOS
when 'haskell-platform' then <<-EOS.undent when "haskell-platform" then <<-EOS.undent
We no longer package haskell-platform. Consider installing ghc We no longer package haskell-platform. Consider installing ghc
and cabal-install instead: and cabal-install instead:
brew install ghc cabal-install brew install ghc cabal-install

View File

@ -1,14 +1,14 @@
require 'tab' require "tab"
require 'os/mac' require "os/mac"
require 'extend/ARGV' require "extend/ARGV"
def built_as_bottle? f def built_as_bottle?(f)
return false unless f.installed? return false unless f.installed?
tab = Tab.for_keg(f.installed_prefix) tab = Tab.for_keg(f.installed_prefix)
tab.built_as_bottle tab.built_as_bottle
end end
def bottle_file_outdated? f, file def bottle_file_outdated?(f, file)
filename = file.basename.to_s filename = file.basename.to_s
return unless f.bottle && filename.match(Pathname::BOTTLE_EXTNAME_RX) return unless f.bottle && filename.match(Pathname::BOTTLE_EXTNAME_RX)
@ -38,11 +38,11 @@ def bottle_tag
end end
end end
def bottle_receipt_path bottle_file def bottle_receipt_path(bottle_file)
Utils.popen_read("tar", "-tzf", bottle_file, "*/*/INSTALL_RECEIPT.json").chomp Utils.popen_read("tar", "-tzf", bottle_file, "*/*/INSTALL_RECEIPT.json").chomp
end end
def bottle_resolve_formula_names bottle_file def bottle_resolve_formula_names(bottle_file)
receipt_file_path = bottle_receipt_path bottle_file receipt_file_path = bottle_receipt_path bottle_file
receipt_file = Utils.popen_read("tar", "-xOzf", bottle_file, receipt_file_path) receipt_file = Utils.popen_read("tar", "-xOzf", bottle_file, receipt_file_path)
name = receipt_file_path.split("/").first name = receipt_file_path.split("/").first
@ -57,7 +57,7 @@ def bottle_resolve_formula_names bottle_file
[name, full_name] [name, full_name]
end end
def bottle_resolve_version bottle_file def bottle_resolve_version(bottle_file)
PkgVersion.parse bottle_receipt_path(bottle_file).split("/")[1] PkgVersion.parse bottle_receipt_path(bottle_file).split("/")[1]
end end
@ -66,7 +66,7 @@ class Bintray
formula_name.to_s.gsub "+", "x" formula_name.to_s.gsub "+", "x"
end end
def self.repository(tap=nil) def self.repository(tap = nil)
return "bottles" if tap.nil? || tap == "Homebrew/homebrew" return "bottles" if tap.nil? || tap == "Homebrew/homebrew"
"bottles-#{tap.sub(/^homebrew\/(homebrew-)?/i, "")}" "bottles-#{tap.sub(/^homebrew\/(homebrew-)?/i, "")}"
end end

View File

@ -81,7 +81,7 @@ class Build
if superenv? if superenv?
ENV.keg_only_deps = keg_only_deps ENV.keg_only_deps = keg_only_deps
ENV.deps = deps.map(&:to_formula) ENV.deps = deps.map(&:to_formula)
ENV.x11 = reqs.any? { |rq| rq.kind_of?(X11Requirement) } ENV.x11 = reqs.any? { |rq| rq.is_a?(X11Requirement) }
ENV.setup_build_environment(formula) ENV.setup_build_environment(formula)
post_superenv_hacks post_superenv_hacks
reqs.each(&:modify_build_environment) reqs.each(&:modify_build_environment)
@ -148,12 +148,12 @@ class Build
keg.detect_cxx_stdlibs(:skip_executables => true) keg.detect_cxx_stdlibs(:skip_executables => true)
end end
def fixopt f def fixopt(f)
path = if f.linked_keg.directory? and f.linked_keg.symlink? path = if f.linked_keg.directory? && f.linked_keg.symlink?
f.linked_keg.resolved_path f.linked_keg.resolved_path
elsif f.prefix.directory? elsif f.prefix.directory?
f.prefix f.prefix
elsif (kids = f.rack.children).size == 1 and kids.first.directory? elsif (kids = f.rack.children).size == 1 && kids.first.directory?
kids.first kids.first
else else
raise raise

View File

@ -1,4 +1,4 @@
require 'set' require "set"
class BuildEnvironment class BuildEnvironment
def initialize(*settings) def initialize(*settings)

View File

@ -4,24 +4,24 @@ class BuildOptions
@options = options @options = options
end end
def include? name def include?(name)
@args.include?("--#{name}") @args.include?("--#{name}")
end end
def with? val def with?(val)
name = val.respond_to?(:option_name) ? val.option_name : val name = val.respond_to?(:option_name) ? val.option_name : val
if option_defined? "with-#{name}" if option_defined? "with-#{name}"
include? "with-#{name}" include? "with-#{name}"
elsif option_defined? "without-#{name}" elsif option_defined? "without-#{name}"
not include? "without-#{name}" !include? "without-#{name}"
else else
false false
end end
end end
def without? name def without?(name)
not with? name !with? name
end end
def bottle? def bottle?
@ -37,7 +37,7 @@ class BuildOptions
end end
def stable? def stable?
not (head? or devel?) !(head? || devel?)
end end
# True if the user requested a universal build. # True if the user requested a universal build.
@ -67,7 +67,7 @@ class BuildOptions
private private
def option_defined? name def option_defined?(name)
@options.include? name @options.include? name
end end
end end

View File

@ -36,8 +36,8 @@ class Caveats
return unless f.keg_only? return unless f.keg_only?
s = "This formula is keg-only, which means it was not symlinked into #{HOMEBREW_PREFIX}." s = "This formula is keg-only, which means it was not symlinked into #{HOMEBREW_PREFIX}."
s << "\n\n#{f.keg_only_reason.to_s}" s << "\n\n#{f.keg_only_reason}"
if f.lib.directory? or f.include.directory? if f.lib.directory? || f.include.directory?
s << s <<
<<-EOS.undent_________________________________________________________72 <<-EOS.undent_________________________________________________________72
@ -54,7 +54,7 @@ class Caveats
end end
def bash_completion_caveats def bash_completion_caveats
if keg and keg.completion_installed? :bash then <<-EOS.undent if keg && keg.completion_installed?(:bash) then <<-EOS.undent
Bash completion has been installed to: Bash completion has been installed to:
#{HOMEBREW_PREFIX}/etc/bash_completion.d #{HOMEBREW_PREFIX}/etc/bash_completion.d
EOS EOS
@ -62,7 +62,7 @@ class Caveats
end end
def zsh_completion_caveats def zsh_completion_caveats
if keg and keg.completion_installed? :zsh then <<-EOS.undent if keg && keg.completion_installed?(:zsh) then <<-EOS.undent
zsh completion has been installed to: zsh completion has been installed to:
#{HOMEBREW_PREFIX}/share/zsh/site-functions #{HOMEBREW_PREFIX}/share/zsh/site-functions
EOS EOS
@ -70,7 +70,7 @@ class Caveats
end end
def fish_completion_caveats def fish_completion_caveats
if keg and keg.completion_installed? :fish and which("fish") then <<-EOS.undent if keg && keg.completion_installed?(:fish) && which("fish") then <<-EOS.undent
fish completion has been installed to: fish completion has been installed to:
#{HOMEBREW_PREFIX}/share/fish/vendor_completions.d #{HOMEBREW_PREFIX}/share/fish/vendor_completions.d
EOS EOS
@ -125,7 +125,7 @@ class Caveats
end end
def app_caveats def app_caveats
if keg and keg.app_installed? if keg && keg.app_installed?
<<-EOS.undent <<-EOS.undent
.app bundles were installed. .app bundles were installed.
Run `brew linkapps #{keg.name}` to symlink these to /Applications. Run `brew linkapps #{keg.name}` to symlink these to /Applications.
@ -148,9 +148,9 @@ class Caveats
def plist_caveats def plist_caveats
s = [] s = []
if f.plist or (keg and keg.plist_installed?) if f.plist || (keg && keg.plist_installed?)
destination = f.plist_startup ? '/Library/LaunchDaemons' \ destination = f.plist_startup ? "/Library/LaunchDaemons" \
: '~/Library/LaunchAgents' : "~/Library/LaunchAgents"
plist_filename = if f.plist plist_filename = if f.plist
f.plist_path.basename f.plist_path.basename
@ -158,7 +158,7 @@ class Caveats
File.basename Dir["#{keg}/*.plist"].first File.basename Dir["#{keg}/*.plist"].first
end end
plist_link = "#{destination}/#{plist_filename}" plist_link = "#{destination}/#{plist_filename}"
plist_domain = f.plist_path.basename('.plist') plist_domain = f.plist_path.basename(".plist")
destination_path = Pathname.new File.expand_path destination destination_path = Pathname.new File.expand_path destination
plist_path = destination_path/plist_filename plist_path = destination_path/plist_filename

View File

@ -5,9 +5,8 @@
# * sets permissions on executables # * sets permissions on executables
# * removes unresolved symlinks # * removes unresolved symlinks
class Cleaner class Cleaner
# Create a cleaner for the given formula # Create a cleaner for the given formula
def initialize f def initialize(f)
@f = f @f = f
end end
@ -17,13 +16,13 @@ class Cleaner
# Many formulae include 'lib/charset.alias', but it is not strictly needed # Many formulae include 'lib/charset.alias', but it is not strictly needed
# and will conflict if more than one formula provides it # and will conflict if more than one formula provides it
observe_file_removal @f.lib/'charset.alias' observe_file_removal @f.lib/"charset.alias"
[@f.bin, @f.sbin, @f.lib].select{ |d| d.exist? }.each{ |d| clean_dir d } [@f.bin, @f.sbin, @f.lib].select(&:exist?).each { |d| clean_dir d }
# Get rid of any info 'dir' files, so they don't conflict at the link stage # Get rid of any info 'dir' files, so they don't conflict at the link stage
info_dir_file = @f.info + 'dir' info_dir_file = @f.info + "dir"
if info_dir_file.file? and not @f.skip_clean? info_dir_file if info_dir_file.file? and !@f.skip_clean? info_dir_file
observe_file_removal info_dir_file observe_file_removal info_dir_file
end end
@ -32,7 +31,7 @@ class Cleaner
private private
def observe_file_removal path def observe_file_removal(path)
path.extend(ObserverPathnameExtension).unlink if path.exist? path.extend(ObserverPathnameExtension).unlink if path.exist?
end end
@ -43,7 +42,7 @@ class Cleaner
dirs = [] dirs = []
symlinks = [] symlinks = []
@f.prefix.find do |path| @f.prefix.find do |path|
if path == @f.libexec or @f.skip_clean?(path) if path == @f.libexec || @f.skip_clean?(path)
Find.prune Find.prune
elsif path.symlink? elsif path.symlink?
symlinks << path symlinks << path
@ -76,23 +75,23 @@ class Cleaner
# #
# lib may have a large directory tree (see Erlang for instance), and # lib may have a large directory tree (see Erlang for instance), and
# clean_dir applies cleaning rules to the entire tree # clean_dir applies cleaning rules to the entire tree
def clean_dir d def clean_dir(d)
d.find do |path| d.find do |path|
path.extend(ObserverPathnameExtension) path.extend(ObserverPathnameExtension)
Find.prune if @f.skip_clean? path Find.prune if @f.skip_clean? path
if path.symlink? or path.directory? if path.symlink? || path.directory?
next next
elsif path.extname == '.la' elsif path.extname == ".la"
path.unlink path.unlink
else else
# Set permissions for executables and non-executables # Set permissions for executables and non-executables
perms = if path.mach_o_executable? || path.text_executable? perms = if path.mach_o_executable? || path.text_executable?
0555 0555
else else
0444 0444
end end
if ARGV.debug? if ARGV.debug?
old_perms = path.stat.mode & 0777 old_perms = path.stat.mode & 0777
if perms != old_perms if perms != old_perms
@ -103,5 +102,4 @@ class Cleaner
end end
end end
end end
end end

View File

@ -16,7 +16,7 @@ module Homebrew
end end
end end
def build_env_keys env def build_env_keys(env)
%w[ %w[
CC CXX LD OBJC OBJCXX CC CXX LD OBJC OBJCXX
HOMEBREW_CC HOMEBREW_CXX HOMEBREW_CC HOMEBREW_CXX
@ -30,7 +30,7 @@ module Homebrew
ACLOCAL_PATH PATH CPATH].select { |key| env.key?(key) } ACLOCAL_PATH PATH CPATH].select { |key| env.key?(key) }
end end
def dump_build_env env, f=$stdout def dump_build_env(env, f = $stdout)
keys = build_env_keys(env) keys = build_env_keys(env)
keys -= %w[CC CXX OBJC OBJCXX] if env["CC"] == env["HOMEBREW_CC"] keys -= %w[CC CXX OBJC OBJCXX] if env["CC"] == env["HOMEBREW_CC"]

View File

@ -3,7 +3,7 @@ module Homebrew
if ARGV.named.empty? if ARGV.named.empty?
puts HOMEBREW_PREFIX puts HOMEBREW_PREFIX
else else
puts ARGV.resolved_formulae.map{ |f| f.opt_prefix.exist? ? f.opt_prefix : f.installed_prefix } puts ARGV.resolved_formulae.map { |f| f.opt_prefix.exist? ? f.opt_prefix : f.installed_prefix }
end end
end end
end end

View File

@ -1,6 +1,6 @@
require 'open-uri' require "open-uri"
require 'resource' require "resource"
require 'formula' require "formula"
module Homebrew module Homebrew
def aspell_dictionaries def aspell_dictionaries
@ -14,7 +14,8 @@ module Homebrew
next unless /^<tr><td><a/ === line next unless /^<tr><td><a/ === line
fields = line.split('"') fields = line.split('"')
lang, path = fields[1], fields[3] lang = fields[1]
path = fields[3]
lang.gsub!("-", "_") lang.gsub!("-", "_")
languages[lang] = path languages[lang] = path
end end

View File

@ -41,7 +41,7 @@ module Homebrew
end end
$times = {} $times = {}
at_exit { puts $times.sort_by{ |k, v| v }.map{ |k, v| "#{k}: #{v}" } } at_exit { puts $times.sort_by { |_k, v| v }.map { |k, v| "#{k}: #{v}" } }
end end
ff = if ARGV.named.empty? ff = if ARGV.named.empty?
@ -78,7 +78,7 @@ module Homebrew
end end
class FormulaText class FormulaText
def initialize path def initialize(path)
@text = path.open("rb", &:read) @text = path.open("rb", &:read)
@lines = @text.lines.to_a @lines = @text.lines.to_a
end end
@ -99,11 +99,11 @@ class FormulaText
/\Z\n/ =~ @text /\Z\n/ =~ @text
end end
def =~ regex def =~(regex)
regex =~ @text regex =~ @text
end end
def line_number regex def line_number(regex)
index = @lines.index { |line| line =~ regex } index = @lines.index { |line| line =~ regex }
index ? index + 1 : nil index ? index + 1 : nil
end end
@ -131,13 +131,13 @@ class FormulaAuditor
FILEUTILS_METHODS = FileUtils.singleton_methods(false).join "|" FILEUTILS_METHODS = FileUtils.singleton_methods(false).join "|"
def initialize(formula, options={}) def initialize(formula, options = {})
@formula = formula @formula = formula
@strict = !!options[:strict] @strict = !!options[:strict]
@online = !!options[:online] @online = !!options[:online]
@problems = [] @problems = []
@text = FormulaText.new(formula.path) @text = FormulaText.new(formula.path)
@specs = %w{stable devel head}.map { |s| formula.send(s) }.compact @specs = %w[stable devel head].map { |s| formula.send(s) }.compact
end end
def audit_file def audit_file
@ -145,11 +145,11 @@ class FormulaAuditor
problem "Incorrect file permissions: chmod 644 #{formula.path}" problem "Incorrect file permissions: chmod 644 #{formula.path}"
end end
if text.has_DATA? and not text.has_END? if text.has_DATA? && !text.has_END?
problem "'DATA' was found, but no '__END__'" problem "'DATA' was found, but no '__END__'"
end end
if text.has_END? and not text.has_DATA? if text.has_END? && !text.has_DATA?
problem "'__END__' was found, but 'DATA' is not used" problem "'__END__' was found, but 'DATA' is not used"
end end
@ -160,22 +160,22 @@ class FormulaAuditor
return unless @strict return unless @strict
component_list = [ component_list = [
[/^ desc ["'][\S\ ]+["']/, "desc" ], [/^ desc ["'][\S\ ]+["']/, "desc"],
[/^ homepage ["'][\S\ ]+["']/, "homepage" ], [/^ homepage ["'][\S\ ]+["']/, "homepage"],
[/^ url ["'][\S\ ]+["']/, "url" ], [/^ url ["'][\S\ ]+["']/, "url"],
[/^ mirror ["'][\S\ ]+["']/, "mirror" ], [/^ mirror ["'][\S\ ]+["']/, "mirror"],
[/^ version ["'][\S\ ]+["']/, "version" ], [/^ version ["'][\S\ ]+["']/, "version"],
[/^ (sha1|sha256) ["'][\S\ ]+["']/, "checksum" ], [/^ (sha1|sha256) ["'][\S\ ]+["']/, "checksum"],
[/^ head ["'][\S\ ]+["']/, "head" ], [/^ head ["'][\S\ ]+["']/, "head"],
[/^ stable do/, "stable block" ], [/^ stable do/, "stable block"],
[/^ bottle do/, "bottle block" ], [/^ bottle do/, "bottle block"],
[/^ devel do/, "devel block" ], [/^ devel do/, "devel block"],
[/^ head do/, "head block" ], [/^ head do/, "head block"],
[/^ option/, "option" ], [/^ option/, "option"],
[/^ depends_on/, "depends_on" ], [/^ depends_on/, "depends_on"],
[/^ def install/, "install method"], [/^ def install/, "install method"],
[/^ def caveats/, "caveats method"], [/^ def caveats/, "caveats method"],
[/^ test do/, "test block" ], [/^ test do/, "test block"]
] ]
component_list.map do |regex, name| component_list.map do |regex, name|
@ -289,7 +289,7 @@ class FormulaAuditor
case dep.name case dep.name
when *BUILD_TIME_DEPS when *BUILD_TIME_DEPS
next if dep.build? or dep.run? next if dep.build? || dep.run?
problem <<-EOS.undent problem <<-EOS.undent
#{dep} dependency should be #{dep} dependency should be
depends_on "#{dep}" => :build depends_on "#{dep}" => :build
@ -346,7 +346,7 @@ class FormulaAuditor
desc = formula.desc desc = formula.desc
unless desc and desc.length > 0 unless desc && desc.length > 0
problem "Formula should have a desc (Description)." problem "Formula should have a desc (Description)."
return return
end end
@ -360,11 +360,11 @@ class FormulaAuditor
EOS EOS
end end
if desc =~ %r[[Cc]ommandline] if desc =~ /[Cc]ommandline/
problem "It should be \"command-line\", not \"commandline\"." problem "It should be \"command-line\", not \"commandline\"."
end end
if desc =~ %r[[Cc]ommand line] if desc =~ /[Cc]ommand line/
problem "It should be \"command-line\", not \"command line\"." problem "It should be \"command-line\", not \"command line\"."
end end
end end
@ -372,19 +372,19 @@ class FormulaAuditor
def audit_homepage def audit_homepage
homepage = formula.homepage homepage = formula.homepage
unless homepage =~ %r[^https?://] unless homepage =~ %r{^https?://}
problem "The homepage should start with http or https (URL is #{homepage})." problem "The homepage should start with http or https (URL is #{homepage})."
end end
# Check for http:// GitHub homepage urls, https:// is preferred. # Check for http:// GitHub homepage urls, https:// is preferred.
# Note: only check homepages that are repo pages, not *.github.com hosts # Note: only check homepages that are repo pages, not *.github.com hosts
if homepage =~ %r[^http://github\.com/] if homepage =~ %r{^http://github\.com/}
problem "Please use https:// for #{homepage}" problem "Please use https:// for #{homepage}"
end end
# Savannah has full SSL/TLS support but no auto-redirect. # Savannah has full SSL/TLS support but no auto-redirect.
# Doesn't apply to the download URLs, only the homepage. # Doesn't apply to the download URLs, only the homepage.
if homepage =~ %r[^http://savannah\.nongnu\.org/] if homepage =~ %r{^http://savannah\.nongnu\.org/}
problem "Please use https:// for #{homepage}" problem "Please use https:// for #{homepage}"
end end
@ -392,7 +392,7 @@ class FormulaAuditor
# To enable https Freedesktop change the URL from http://project.freedesktop.org/wiki to # To enable https Freedesktop change the URL from http://project.freedesktop.org/wiki to
# https://wiki.freedesktop.org/project_name. # https://wiki.freedesktop.org/project_name.
# "Software" is redirected to https://wiki.freedesktop.org/www/Software/project_name # "Software" is redirected to https://wiki.freedesktop.org/www/Software/project_name
if homepage =~ %r[^http://((?:www|nice|libopenraw|liboil|telepathy|xorg)\.)?freedesktop\.org/(?:wiki/)?] if homepage =~ %r{^http://((?:www|nice|libopenraw|liboil|telepathy|xorg)\.)?freedesktop\.org/(?:wiki/)?}
if homepage =~ /Software/ if homepage =~ /Software/
problem "#{homepage} should be styled `https://wiki.freedesktop.org/www/Software/project_name`" problem "#{homepage} should be styled `https://wiki.freedesktop.org/www/Software/project_name`"
else else
@ -401,34 +401,34 @@ class FormulaAuditor
end end
# Google Code homepages should end in a slash # Google Code homepages should end in a slash
if homepage =~ %r[^https?://code\.google\.com/p/[^/]+[^/]$] if homepage =~ %r{^https?://code\.google\.com/p/[^/]+[^/]$}
problem "#{homepage} should end with a slash" problem "#{homepage} should end with a slash"
end end
# People will run into mixed content sometimes, but we should enforce and then add # People will run into mixed content sometimes, but we should enforce and then add
# exemptions as they are discovered. Treat mixed content on homepages as a bug. # exemptions as they are discovered. Treat mixed content on homepages as a bug.
# Justify each exemptions with a code comment so we can keep track here. # Justify each exemptions with a code comment so we can keep track here.
if homepage =~ %r[^http://[^/]*github\.io/] if homepage =~ %r{^http://[^/]*github\.io/}
problem "Please use https:// for #{homepage}" problem "Please use https:// for #{homepage}"
end end
# There's an auto-redirect here, but this mistake is incredibly common too. # There's an auto-redirect here, but this mistake is incredibly common too.
# Only applies to the homepage and subdomains for now, not the FTP URLs. # Only applies to the homepage and subdomains for now, not the FTP URLs.
if homepage =~ %r[^http://((?:build|cloud|developer|download|extensions|git|glade|help|library|live|nagios|news|people|projects|rt|static|wiki|www)\.)?gnome\.org] if homepage =~ %r{^http://((?:build|cloud|developer|download|extensions|git|glade|help|library|live|nagios|news|people|projects|rt|static|wiki|www)\.)?gnome\.org}
problem "Please use https:// for #{homepage}" problem "Please use https:// for #{homepage}"
end end
# Compact the above into this list as we're able to remove detailed notations, etc over time. # Compact the above into this list as we're able to remove detailed notations, etc over time.
case homepage case homepage
when %r[^http://[^/]*\.apache\.org], when %r{^http://[^/]*\.apache\.org},
%r[^http://packages\.debian\.org], %r{^http://packages\.debian\.org},
%r[^http://wiki\.freedesktop\.org/], %r{^http://wiki\.freedesktop\.org/},
%r[^http://((?:www)\.)?gnupg.org/], %r{^http://((?:www)\.)?gnupg.org/},
%r[^http://ietf\.org], %r{^http://ietf\.org},
%r[^http://[^/.]+\.ietf\.org], %r{^http://[^/.]+\.ietf\.org},
%r[^http://[^/.]+\.tools\.ietf\.org], %r{^http://[^/.]+\.tools\.ietf\.org},
%r[^http://www\.gnu\.org/], %r{^http://www\.gnu\.org/},
%r[^http://code\.google\.com/] %r{^http://code\.google\.com/}
problem "Please use https:// for #{homepage}" problem "Please use https:// for #{homepage}"
end end
@ -462,7 +462,7 @@ class FormulaAuditor
problem "GitHub repository not notable enough (<10 forks, <10 watchers and <20 stars)" problem "GitHub repository not notable enough (<10 forks, <10 watchers and <20 stars)"
end end
if (Date.parse(metadata["created_at"]) > (Date.today - 30)) if Date.parse(metadata["created_at"]) > (Date.today - 30)
problem "GitHub repository too new (<30 days old)" problem "GitHub repository too new (<30 days old)"
end end
end end
@ -530,16 +530,16 @@ class FormulaAuditor
def audit_patch(patch) def audit_patch(patch)
case patch.url case patch.url
when %r[raw\.github\.com], %r[gist\.github\.com/raw], %r[gist\.github\.com/.+/raw], when /raw\.github\.com/, %r{gist\.github\.com/raw}, %r{gist\.github\.com/.+/raw},
%r[gist\.githubusercontent\.com/.+/raw] %r{gist\.githubusercontent\.com/.+/raw}
unless patch.url =~ /[a-fA-F0-9]{40}/ unless patch.url =~ /[a-fA-F0-9]{40}/
problem "GitHub/Gist patches should specify a revision:\n#{patch.url}" problem "GitHub/Gist patches should specify a revision:\n#{patch.url}"
end end
when %r[macports/trunk] when %r{macports/trunk}
problem "MacPorts patches should specify a revision instead of trunk:\n#{patch.url}" problem "MacPorts patches should specify a revision instead of trunk:\n#{patch.url}"
when %r[^http://trac\.macports\.org] when %r{^http://trac\.macports\.org}
problem "Patches from MacPorts Trac should be https://, not http:\n#{patch.url}" problem "Patches from MacPorts Trac should be https://, not http:\n#{patch.url}"
when %r[^http://bugs\.debian\.org] when %r{^http://bugs\.debian\.org}
problem "Patches from Debian should be https://, not http:\n#{patch.url}" problem "Patches from Debian should be https://, not http:\n#{patch.url}"
end end
end end
@ -550,11 +550,11 @@ class FormulaAuditor
end end
if text =~ /system\s+['"]xcodebuild/ if text =~ /system\s+['"]xcodebuild/
problem %{use "xcodebuild *args" instead of "system 'xcodebuild', *args"} problem %(use "xcodebuild *args" instead of "system 'xcodebuild', *args")
end end
if text =~ /xcodebuild[ (]["'*]/ && text !~ /SYMROOT=/ if text =~ /xcodebuild[ (]["'*]/ && text !~ /SYMROOT=/
problem %{xcodebuild should be passed an explicit "SYMROOT"} problem %(xcodebuild should be passed an explicit "SYMROOT")
end end
if text =~ /Formula\.factory\(/ if text =~ /Formula\.factory\(/
@ -635,7 +635,7 @@ class FormulaAuditor
problem "\"(#{$1}...#{$2})\" should be \"(#{$3.downcase}+...)\"" problem "\"(#{$1}...#{$2})\" should be \"(#{$3.downcase}+...)\""
end end
if line =~ %r[((man)\s*\+\s*(['"])(man[1-8])(['"]))] if line =~ /((man)\s*\+\s*(['"])(man[1-8])(['"]))/
problem "\"#{$1}\" should be \"#{$4}\"" problem "\"#{$1}\" should be \"#{$4}\""
end end
@ -656,7 +656,7 @@ class FormulaAuditor
problem "\"#{$1}\" should be \"\#{#{$2}}\"" problem "\"#{$1}\" should be \"\#{#{$2}}\""
end end
if line =~ %r[depends_on :(automake|autoconf|libtool)] if line =~ /depends_on :(automake|autoconf|libtool)/
problem ":#{$1} is deprecated. Usage should be \"#{$1}\"" problem ":#{$1} is deprecated. Usage should be \"#{$1}\""
end end
@ -751,13 +751,13 @@ class FormulaAuditor
problem "Use MacOS.version instead of MACOS_VERSION" problem "Use MacOS.version instead of MACOS_VERSION"
end end
cats = %w{leopard snow_leopard lion mountain_lion}.join("|") cats = %w[leopard snow_leopard lion mountain_lion].join("|")
if line =~ /MacOS\.(?:#{cats})\?/ if line =~ /MacOS\.(?:#{cats})\?/
problem "\"#{$&}\" is deprecated, use a comparison to MacOS.version instead" problem "\"#{$&}\" is deprecated, use a comparison to MacOS.version instead"
end end
if line =~ /skip_clean\s+:all/ if line =~ /skip_clean\s+:all/
problem "`skip_clean :all` is deprecated; brew no longer strips symbols\n" + problem "`skip_clean :all` is deprecated; brew no longer strips symbols\n" \
"\tPass explicit paths to prevent Homebrew from removing empty folders." "\tPass explicit paths to prevent Homebrew from removing empty folders."
end end
@ -827,7 +827,7 @@ class FormulaAuditor
return unless @strict return unless @strict
return unless formula.core_formula? return unless formula.core_formula?
if TAP_MIGRATIONS.has_key?(formula.name) if TAP_MIGRATIONS.key?(formula.name)
problem <<-EOS.undent problem <<-EOS.undent
#{formula.name} seems to be listed in tap_migrations.rb! #{formula.name} seems to be listed in tap_migrations.rb!
Please remove #{formula.name} from present tap & tap_migrations.rb Please remove #{formula.name} from present tap & tap_migrations.rb
@ -860,9 +860,9 @@ class FormulaAuditor
case condition case condition
when /if build\.include\? ['"]with-#{dep}['"]$/, /if build\.with\? ['"]#{dep}['"]$/ when /if build\.include\? ['"]with-#{dep}['"]$/, /if build\.with\? ['"]#{dep}['"]$/
problem %{Replace #{line.inspect} with "depends_on #{quoted_dep} => :optional"} problem %(Replace #{line.inspect} with "depends_on #{quoted_dep} => :optional")
when /unless build\.include\? ['"]without-#{dep}['"]$/, /unless build\.without\? ['"]#{dep}['"]$/ when /unless build\.include\? ['"]without-#{dep}['"]$/, /unless build\.without\? ['"]#{dep}['"]$/
problem %{Replace #{line.inspect} with "depends_on #{quoted_dep} => :recommended"} problem %(Replace #{line.inspect} with "depends_on #{quoted_dep} => :recommended")
end end
end end
@ -896,7 +896,7 @@ class FormulaAuditor
private private
def problem p def problem(p)
@problems << p @problems << p
end end
@ -937,7 +937,7 @@ class ResourceAuditor
problem "missing version" problem "missing version"
elsif version.to_s.empty? elsif version.to_s.empty?
problem "version is set to an empty string" problem "version is set to an empty string"
elsif not version.detected_from_url? elsif !version.detected_from_url?
version_text = version version_text = version
version_url = Version.detect(url, specs) version_url = Version.detect(url, specs)
if version_url.to_s == version_text.to_s && version.instance_of?(Version) if version_url.to_s == version_text.to_s && version.instance_of?(Version)
@ -977,7 +977,7 @@ class ResourceAuditor
end end
def audit_download_strategy def audit_download_strategy
if url =~ %r[^(cvs|bzr|hg|fossil)://] || url =~ %r[^(svn)\+http://] if url =~ %r{^(cvs|bzr|hg|fossil)://} || url =~ %r{^(svn)\+http://}
problem "Use of the #{$&} scheme is deprecated, pass `:using => :#{$1}` instead" problem "Use of the #{$&} scheme is deprecated, pass `:using => :#{$1}` instead"
end end
@ -992,10 +992,10 @@ class ResourceAuditor
return unless using return unless using
if using == :ssl3 || \ if using == :ssl3 || \
(Object.const_defined?("CurlSSL3DownloadStrategy") && using == CurlSSL3DownloadStrategy) (Object.const_defined?("CurlSSL3DownloadStrategy") && using == CurlSSL3DownloadStrategy)
problem "The SSL3 download strategy is deprecated, please choose a different URL" problem "The SSL3 download strategy is deprecated, please choose a different URL"
elsif (Object.const_defined?("CurlUnsafeDownloadStrategy") && using == CurlUnsafeDownloadStrategy) || \ elsif (Object.const_defined?("CurlUnsafeDownloadStrategy") && using == CurlUnsafeDownloadStrategy) || \
(Object.const_defined?("UnsafeSubversionDownloadStrategy") && using == UnsafeSubversionDownloadStrategy) (Object.const_defined?("UnsafeSubversionDownloadStrategy") && using == UnsafeSubversionDownloadStrategy)
problem "#{using.name} is deprecated, please choose a different URL" problem "#{using.name} is deprecated, please choose a different URL"
end end
@ -1006,7 +1006,7 @@ class ResourceAuditor
problem "Redundant :module value in URL" problem "Redundant :module value in URL"
end end
if url =~ %r[:[^/]+$] if url =~ %r{:[^/]+$}
mod = url.split(":").last mod = url.split(":").last
if mod == name if mod == name
@ -1017,7 +1017,7 @@ class ResourceAuditor
end end
end end
using_strategy = DownloadStrategyDetector.detect('', using) using_strategy = DownloadStrategyDetector.detect("", using)
if url_strategy == using_strategy if url_strategy == using_strategy
problem "Redundant :using value in URL" problem "Redundant :using value in URL"
@ -1026,12 +1026,12 @@ class ResourceAuditor
def audit_urls def audit_urls
# Check GNU urls; doesn't apply to mirrors # Check GNU urls; doesn't apply to mirrors
if url =~ %r[^(?:https?|ftp)://(?!alpha).+/gnu/] if url =~ %r{^(?:https?|ftp)://(?!alpha).+/gnu/}
problem "Please use \"http://ftpmirror.gnu.org\" instead of #{url}." problem "Please use \"http://ftpmirror.gnu.org\" instead of #{url}."
end end
# GNU's ftpmirror does NOT support SSL/TLS. # GNU's ftpmirror does NOT support SSL/TLS.
if url =~ %r[^https://ftpmirror\.gnu\.org/] if url =~ %r{^https://ftpmirror\.gnu\.org/}
problem "Please use http:// for #{url}" problem "Please use http:// for #{url}"
end end
@ -1045,17 +1045,17 @@ class ResourceAuditor
# or are overly common errors that need to be reduced & fixed over time. # or are overly common errors that need to be reduced & fixed over time.
urls.each do |p| urls.each do |p|
case p case p
when %r[^http://ftp\.gnu\.org/], when %r{^http://ftp\.gnu\.org/},
%r[^http://[^/]*\.apache\.org/], %r{^http://[^/]*\.apache\.org/},
%r[^http://code\.google\.com/], %r{^http://code\.google\.com/},
%r[^http://fossies\.org/], %r{^http://fossies\.org/},
%r[^http://mirrors\.kernel\.org/], %r{^http://mirrors\.kernel\.org/},
%r[^http://([^/]*\.|)bintray\.com/], %r{^http://([^/]*\.|)bintray\.com/},
%r[^http://tools\.ietf\.org/] %r{^http://tools\.ietf\.org/}
problem "Please use https:// for #{p}" problem "Please use https:// for #{p}"
when %r[^http://search\.mcpan\.org/CPAN/(.*)]i when %r{^http://search\.mcpan\.org/CPAN/(.*)}i
problem "#{p} should be `https://cpan.metacpan.org/#{$1}`" problem "#{p} should be `https://cpan.metacpan.org/#{$1}`"
when %r[^(http|ftp)://ftp\.gnome\.org/pub/gnome/(.*)]i when %r{^(http|ftp)://ftp\.gnome\.org/pub/gnome/(.*)}i
problem "#{p} should be `https://download.gnome.org/#{$2}`" problem "#{p} should be `https://download.gnome.org/#{$2}`"
end end
end end
@ -1063,11 +1063,11 @@ class ResourceAuditor
# Check SourceForge urls # Check SourceForge urls
urls.each do |p| urls.each do |p|
# Skip if the URL looks like a SVN repo # Skip if the URL looks like a SVN repo
next if p =~ %r[/svnroot/] next if p =~ %r{/svnroot/}
next if p =~ %r[svn\.sourceforge] next if p =~ /svn\.sourceforge/
# Is it a sourceforge http(s) URL? # Is it a sourceforge http(s) URL?
next unless p =~ %r[^https?://.*\b(sourceforge|sf)\.(com|net)] next unless p =~ %r{^https?://.*\b(sourceforge|sf)\.(com|net)}
if p =~ /(\?|&)use_mirror=/ if p =~ /(\?|&)use_mirror=/
problem "Don't use #{$1}use_mirror in SourceForge urls (url is #{p})." problem "Don't use #{$1}use_mirror in SourceForge urls (url is #{p})."
@ -1077,16 +1077,16 @@ class ResourceAuditor
problem "Don't use /download in SourceForge urls (url is #{p})." problem "Don't use /download in SourceForge urls (url is #{p})."
end end
if p =~ %r[^https?://sourceforge\.] if p =~ %r{^https?://sourceforge\.}
problem "Use https://downloads.sourceforge.net to get geolocation (url is #{p})." problem "Use https://downloads.sourceforge.net to get geolocation (url is #{p})."
end end
if p =~ %r[^https?://prdownloads\.] if p =~ %r{^https?://prdownloads\.}
problem "Don't use prdownloads in SourceForge urls (url is #{p}).\n" + problem "Don't use prdownloads in SourceForge urls (url is #{p}).\n" \
"\tSee: http://librelist.com/browser/homebrew/2011/1/12/prdownloads-is-bad/" "\tSee: http://librelist.com/browser/homebrew/2011/1/12/prdownloads-is-bad/"
end end
if p =~ %r[^http://\w+\.dl\.] if p =~ %r{^http://\w+\.dl\.}
problem "Don't use specific dl mirrors in SourceForge urls (url is #{p})." problem "Don't use specific dl mirrors in SourceForge urls (url is #{p})."
end end
@ -1098,42 +1098,42 @@ class ResourceAuditor
# Check for Google Code download urls, https:// is preferred # Check for Google Code download urls, https:// is preferred
# Intentionally not extending this to SVN repositories due to certificate # Intentionally not extending this to SVN repositories due to certificate
# issues. # issues.
urls.grep(%r[^http://.*\.googlecode\.com/files.*]) do |u| urls.grep(%r{^http://.*\.googlecode\.com/files.*}) do |u|
problem "Please use https:// for #{u}" problem "Please use https:// for #{u}"
end end
# Check for new-url Google Code download urls, https:// is preferred # Check for new-url Google Code download urls, https:// is preferred
urls.grep(%r[^http://code\.google\.com/]) do |u| urls.grep(%r{^http://code\.google\.com/}) do |u|
problem "Please use https:// for #{u}" problem "Please use https:// for #{u}"
end end
# Check for git:// GitHub repo urls, https:// is preferred. # Check for git:// GitHub repo urls, https:// is preferred.
urls.grep(%r[^git://[^/]*github\.com/]) do |u| urls.grep(%r{^git://[^/]*github\.com/}) do |u|
problem "Please use https:// for #{u}" problem "Please use https:// for #{u}"
end end
# Check for git:// Gitorious repo urls, https:// is preferred. # Check for git:// Gitorious repo urls, https:// is preferred.
urls.grep(%r[^git://[^/]*gitorious\.org/]) do |u| urls.grep(%r{^git://[^/]*gitorious\.org/}) do |u|
problem "Please use https:// for #{u}" problem "Please use https:// for #{u}"
end end
# Check for http:// GitHub repo urls, https:// is preferred. # Check for http:// GitHub repo urls, https:// is preferred.
urls.grep(%r[^http://github\.com/.*\.git$]) do |u| urls.grep(%r{^http://github\.com/.*\.git$}) do |u|
problem "Please use https:// for #{u}" problem "Please use https:// for #{u}"
end end
# Use new-style archive downloads # Use new-style archive downloads
urls.select { |u| u =~ %r[https://.*github.*/(?:tar|zip)ball/] && u !~ %r[\.git$] }.each do |u| urls.select { |u| u =~ %r{https://.*github.*/(?:tar|zip)ball/} && u !~ /\.git$/ }.each do |u|
problem "Use /archive/ URLs for GitHub tarballs (url is #{u})." problem "Use /archive/ URLs for GitHub tarballs (url is #{u})."
end end
# Don't use GitHub .zip files # Don't use GitHub .zip files
urls.select { |u| u =~ %r[https://.*github.*/(archive|releases)/.*\.zip$] && u !~ %r[releases/download] }.each do |u| urls.select { |u| u =~ %r{https://.*github.*/(archive|releases)/.*\.zip$} && u !~ %r{releases/download} }.each do |u|
problem "Use GitHub tarballs rather than zipballs (url is #{u})." problem "Use GitHub tarballs rather than zipballs (url is #{u})."
end end
end end
def problem text def problem(text)
@problems << text @problems << text
end end
end end

View File

@ -1,11 +1,11 @@
require 'formula' require "formula"
require 'bottles' require "bottles"
require 'tab' require "tab"
require 'keg' require "keg"
require 'formula_versions' require "formula_versions"
require 'utils/inreplace' require "utils/inreplace"
require 'erb' require "erb"
require 'extend/pathname' require "extend/pathname"
BOTTLE_ERB = <<-EOS BOTTLE_ERB = <<-EOS
bottle do bottle do
@ -33,10 +33,10 @@ BOTTLE_ERB = <<-EOS
EOS EOS
module Homebrew module Homebrew
def keg_contains string, keg, ignores def keg_contains(string, keg, ignores)
@put_string_exists_header, @put_filenames = nil @put_string_exists_header, @put_filenames = nil
def print_filename string, filename def print_filename(string, filename)
unless @put_string_exists_header unless @put_string_exists_header
opoo "String '#{string}' still exists in these files:" opoo "String '#{string}' still exists in these files:"
@put_string_exists_header = true @put_string_exists_header = true
@ -57,7 +57,7 @@ module Homebrew
# Check dynamic library linkage. Importantly, do not run otool on static # Check dynamic library linkage. Importantly, do not run otool on static
# libraries, which will falsely report "linkage" to themselves. # libraries, which will falsely report "linkage" to themselves.
if file.mach_o_executable? or file.dylib? or file.mach_o_bundle? if file.mach_o_executable? || file.dylib? || file.mach_o_bundle?
linked_libraries = file.dynamically_linked_libraries linked_libraries = file.dynamically_linked_libraries
linked_libraries = linked_libraries.select { |lib| lib.include? string } linked_libraries = linked_libraries.select { |lib| lib.include? string }
result ||= linked_libraries.any? result ||= linked_libraries.any?
@ -77,7 +77,7 @@ module Homebrew
until io.eof? until io.eof?
str = io.readline.chomp str = io.readline.chomp
next if ignores.any? {|i| i =~ str } next if ignores.any? { |i| i =~ str }
next unless str.include? string next unless str.include? string
@ -110,12 +110,12 @@ module Homebrew
result result
end end
def bottle_output bottle def bottle_output(bottle)
erb = ERB.new BOTTLE_ERB erb = ERB.new BOTTLE_ERB
erb.result(bottle.instance_eval { binding }).gsub(/^\s*$\n/, '') erb.result(bottle.instance_eval { binding }).gsub(/^\s*$\n/, "")
end end
def bottle_formula f def bottle_formula(f)
unless f.installed? unless f.installed?
return ofail "Formula not installed or up-to-date: #{f.full_name}" return ofail "Formula not installed or up-to-date: #{f.full_name}"
end end
@ -128,7 +128,7 @@ module Homebrew
return ofail "Formula has no stable version: #{f.full_name}" return ofail "Formula has no stable version: #{f.full_name}"
end end
if ARGV.include? '--no-revision' if ARGV.include? "--no-revision"
bottle_revision = 0 bottle_revision = 0
else else
ohai "Determining #{f.full_name} bottle revision..." ohai "Determining #{f.full_name} bottle revision..."
@ -158,14 +158,14 @@ module Homebrew
cd cellar do cd cellar do
# Use gzip, faster to compress than bzip2, faster to uncompress than bzip2 # Use gzip, faster to compress than bzip2, faster to uncompress than bzip2
# or an uncompressed tarball (and more bandwidth friendly). # or an uncompressed tarball (and more bandwidth friendly).
safe_system 'tar', 'czf', bottle_path, "#{f.name}/#{f.pkg_version}" safe_system "tar", "czf", bottle_path, "#{f.name}/#{f.pkg_version}"
end end
if bottle_path.size > 1*1024*1024 if bottle_path.size > 1*1024*1024
ohai "Detecting if #{filename} is relocatable..." ohai "Detecting if #{filename} is relocatable..."
end end
if prefix == '/usr/local' if prefix == "/usr/local"
prefix_check = File.join(prefix, "opt") prefix_check = File.join(prefix, "opt")
else else
prefix_check = prefix prefix_check = prefix
@ -206,7 +206,7 @@ module Homebrew
puts "./#{filename}" puts "./#{filename}"
puts output puts output
if ARGV.include? '--rb' if ARGV.include? "--rb"
File.open("#{filename.prefix}.bottle.rb", "w") do |file| File.open("#{filename.prefix}.bottle.rb", "w") do |file|
file.write("\# #{f.full_name}\n") file.write("\# #{f.full_name}\n")
file.write(output) file.write(output)
@ -224,7 +224,7 @@ module Homebrew
merge_hash = {} merge_hash = {}
ARGV.named.each do |argument| ARGV.named.each do |argument|
bottle_block = IO.read(argument) bottle_block = IO.read(argument)
formula_name = bottle_block.lines.first.sub(/^# /,"").chomp formula_name = bottle_block.lines.first.sub(/^# /, "").chomp
merge_hash[formula_name] ||= [] merge_hash[formula_name] ||= []
merge_hash[formula_name] << bottle_block merge_hash[formula_name] << bottle_block
end end
@ -238,18 +238,18 @@ module Homebrew
output = bottle_output bottle output = bottle_output bottle
puts output puts output
if ARGV.include? '--write' if ARGV.include? "--write"
f = Formulary.factory(formula_name) f = Formulary.factory(formula_name)
update_or_add = nil update_or_add = nil
Utils::Inreplace.inreplace(f.path) do |s| Utils::Inreplace.inreplace(f.path) do |s|
if s.include? 'bottle do' if s.include? "bottle do"
update_or_add = 'update' update_or_add = "update"
string = s.sub!(/ bottle do.+?end\n/m, output) string = s.sub!(/ bottle do.+?end\n/m, output)
odie 'Bottle block update failed!' unless string odie "Bottle block update failed!" unless string
else else
update_or_add = 'add' update_or_add = "add"
if s.include? 'stable do' if s.include? "stable do"
indent = s.slice(/^ +stable do/).length - "stable do".length indent = s.slice(/^ +stable do/).length - "stable do".length
string = s.sub!(/^ {#{indent}}stable do(.|\n)+?^ {#{indent}}end\n/m, '\0' + output + "\n") string = s.sub!(/^ {#{indent}}stable do(.|\n)+?^ {#{indent}}end\n/m, '\0' + output + "\n")
else else
@ -267,7 +267,7 @@ module Homebrew
)+ )+
/mx, '\0' + output + "\n") /mx, '\0' + output + "\n")
end end
odie 'Bottle block addition failed!' unless string odie "Bottle block addition failed!" unless string
end end
end end
@ -282,7 +282,7 @@ module Homebrew
end end
def bottle def bottle
merge if ARGV.include? '--merge' merge if ARGV.include? "--merge"
ARGV.resolved_formulae.each do |f| ARGV.resolved_formulae.each do |f|
bottle_formula f bottle_formula f

View File

@ -1,6 +1,6 @@
require 'formula' require "formula"
require 'keg' require "keg"
require 'bottles' require "bottles"
module Homebrew module Homebrew
def cleanup def cleanup
@ -39,7 +39,7 @@ module Homebrew
end end
end end
def cleanup_formula f def cleanup_formula(f)
if f.installed? if f.installed?
eligible_kegs = f.rack.subdirs.map { |d| Keg.new(d) }.select { |k| f.pkg_version > k.version } eligible_kegs = f.rack.subdirs.map { |d| Keg.new(d) }.select { |k| f.pkg_version > k.version }
if eligible_kegs.any? && eligible_for_cleanup?(f) if eligible_kegs.any? && eligible_for_cleanup?(f)
@ -54,7 +54,7 @@ module Homebrew
end end
end end
def cleanup_keg keg def cleanup_keg(keg)
if keg.linked? if keg.linked?
opoo "Skipping (old) #{keg} due to it being linked" opoo "Skipping (old) #{keg} due to it being linked"
else else
@ -84,12 +84,12 @@ module Homebrew
end end
file_is_stale = if PkgVersion === version file_is_stale = if PkgVersion === version
f.pkg_version > version f.pkg_version > version
else else
f.version > version f.version > version
end end
if file_is_stale || ARGV.switch?('s') && !f.installed? || bottle_file_outdated?(f, file) if file_is_stale || ARGV.switch?("s") && !f.installed? || bottle_file_outdated?(f, file)
cleanup_path(file) { file.unlink } cleanup_path(file) { file.unlink }
end end
end end
@ -107,15 +107,15 @@ module Homebrew
def cleanup_lockfiles def cleanup_lockfiles
return unless HOMEBREW_CACHE_FORMULA.directory? return unless HOMEBREW_CACHE_FORMULA.directory?
candidates = HOMEBREW_CACHE_FORMULA.children candidates = HOMEBREW_CACHE_FORMULA.children
lockfiles = candidates.select { |f| f.file? && f.extname == '.brewing' } lockfiles = candidates.select { |f| f.file? && f.extname == ".brewing" }
lockfiles.select(&:readable?).each do |file| lockfiles.select(&:readable?).each do |file|
file.open.flock(File::LOCK_EX | File::LOCK_NB) and file.unlink file.open.flock(File::LOCK_EX | File::LOCK_NB) && file.unlink
end end
end end
def rm_DS_Store def rm_DS_Store
paths = %w[Cellar Frameworks Library bin etc include lib opt sbin share var]. paths = %w[Cellar Frameworks Library bin etc include lib opt sbin share var].
map { |p| HOMEBREW_PREFIX/p }.select(&:exist?) map { |p| HOMEBREW_PREFIX/p }.select(&:exist?)
args = paths.map(&:to_s) + %w[-name .DS_Store -delete] args = paths.map(&:to_s) + %w[-name .DS_Store -delete]
quiet_system "find", *args quiet_system "find", *args
end end
@ -126,7 +126,7 @@ module Homebrew
# introduced the opt symlink, and built against that instead. So provided # introduced the opt symlink, and built against that instead. So provided
# no brew exists that was built against an old-style keg-only keg, we can # no brew exists that was built against an old-style keg-only keg, we can
# remove it. # remove it.
if not formula.keg_only? or ARGV.force? if !formula.keg_only? || ARGV.force?
true true
elsif formula.opt_prefix.directory? elsif formula.opt_prefix.directory?
# SHA records were added to INSTALL_RECEIPTS the same day as opt symlinks # SHA records were added to INSTALL_RECEIPTS the same day as opt symlinks

View File

@ -3,7 +3,7 @@ module Homebrew
cmd = ARGV.first cmd = ARGV.first
cmd = HOMEBREW_INTERNAL_COMMAND_ALIASES.fetch(cmd, cmd) cmd = HOMEBREW_INTERNAL_COMMAND_ALIASES.fetch(cmd, cmd)
if (path = HOMEBREW_LIBRARY_PATH/"cmd/#{cmd}.rb"; path.file?) if (path = HOMEBREW_LIBRARY_PATH/"cmd/#{cmd}.rb" && path.file?)
puts path puts path
elsif (path = which("brew-#{cmd}") || which("brew-#{cmd}.rb")) elsif (path = which("brew-#{cmd}") || which("brew-#{cmd}.rb"))
puts path puts path

View File

@ -21,13 +21,13 @@ module Homebrew
def internal_commands def internal_commands
with_directory = false with_directory = false
(HOMEBREW_REPOSITORY/"Library/Homebrew/cmd"). (HOMEBREW_REPOSITORY/"Library/Homebrew/cmd").
children(with_directory). children(with_directory).
map {|f| File.basename(f, '.rb')} map { |f| File.basename(f, ".rb") }
end end
def external_commands def external_commands
paths.map{ |p| Dir["#{p}/brew-*"] }.flatten. paths.map { |p| Dir["#{p}/brew-*"] }.flatten.
map{ |f| File.basename(f, '.rb')[5..-1] }. map { |f| File.basename(f, ".rb")[5..-1] }.
reject{ |f| f =~ /\./ } reject { |f| f =~ /\./ }
end end
end end

View File

@ -1,4 +1,4 @@
require 'hardware' require "hardware"
require "software_spec" require "software_spec"
module Homebrew module Homebrew
@ -59,7 +59,7 @@ module Homebrew
if origin.empty? then "(none)" else origin end if origin.empty? then "(none)" else origin end
end end
def describe_path path def describe_path(path)
return "N/A" if path.nil? return "N/A" if path.nil?
realpath = path.realpath realpath = path.realpath
if realpath == path then path else "#{path} => #{realpath}" end if realpath == path then path else "#{path} => #{realpath}" end
@ -67,16 +67,16 @@ module Homebrew
def describe_x11 def describe_x11
return "N/A" unless MacOS::XQuartz.installed? return "N/A" unless MacOS::XQuartz.installed?
return "#{MacOS::XQuartz.version} => #{describe_path(MacOS::XQuartz.prefix)}" "#{MacOS::XQuartz.version} => #{describe_path(MacOS::XQuartz.prefix)}"
end end
def describe_perl def describe_perl
describe_path(which 'perl') describe_path(which "perl")
end end
def describe_python def describe_python
python = which 'python' python = which "python"
if %r{/shims/python$} =~ python && which('pyenv') if %r{/shims/python$} =~ python && which("pyenv")
"#{python} => #{Pathname.new(`pyenv which python`.strip).realpath}" rescue describe_path(python) "#{python} => #{Pathname.new(`pyenv which python`.strip).realpath}" rescue describe_path(python)
else else
describe_path(python) describe_path(python)
@ -84,8 +84,8 @@ module Homebrew
end end
def describe_ruby def describe_ruby
ruby = which 'ruby' ruby = which "ruby"
if %r{/shims/ruby$} =~ ruby && which('rbenv') if %r{/shims/ruby$} =~ ruby && which("rbenv")
"#{ruby} => #{Pathname.new(`rbenv which ruby`.strip).realpath}" rescue describe_path(ruby) "#{ruby} => #{Pathname.new(`rbenv which ruby`.strip).realpath}" rescue describe_path(ruby)
else else
describe_path(ruby) describe_path(ruby)
@ -114,7 +114,7 @@ module Homebrew
s << RUBY_VERSION s << RUBY_VERSION
end end
if RUBY_PATH.to_s !~ %r[^/System/Library/Frameworks/Ruby.framework/Versions/[12]\.[089]/usr/bin/ruby] if RUBY_PATH.to_s !~ %r{^/System/Library/Frameworks/Ruby.framework/Versions/[12]\.[089]/usr/bin/ruby}
s << " => #{RUBY_PATH}" s << " => #{RUBY_PATH}"
end end
s s
@ -131,7 +131,7 @@ module Homebrew
end end
end end
def dump_verbose_config(f=$stdout) def dump_verbose_config(f = $stdout)
f.puts "HOMEBREW_VERSION: #{HOMEBREW_VERSION}" f.puts "HOMEBREW_VERSION: #{HOMEBREW_VERSION}"
f.puts "ORIGIN: #{origin}" f.puts "ORIGIN: #{origin}"
f.puts "HEAD: #{head}" f.puts "HEAD: #{head}"

View File

@ -1,17 +1,15 @@
require 'formula' require "formula"
require 'blacklist' require "blacklist"
require 'digest' require "digest"
require 'erb' require "erb"
module Homebrew module Homebrew
# Create a formula from a tarball URL # Create a formula from a tarball URL
def create def create
# Allow searching MacPorts or Fink. # Allow searching MacPorts or Fink.
if ARGV.include? '--macports' if ARGV.include? "--macports"
exec_browser "https://www.macports.org/ports.php?by=name&substr=#{ARGV.next}" exec_browser "https://www.macports.org/ports.php?by=name&substr=#{ARGV.next}"
elsif ARGV.include? '--fink' elsif ARGV.include? "--fink"
exec_browser "http://pdb.finkproject.org/pdb/browse.php?summary=#{ARGV.next}" exec_browser "http://pdb.finkproject.org/pdb/browse.php?summary=#{ARGV.next}"
end end
@ -22,17 +20,17 @@ module Homebrew
url = ARGV.named.first # Pull the first (and only) url from ARGV url = ARGV.named.first # Pull the first (and only) url from ARGV
version = ARGV.next if ARGV.include? '--set-version' version = ARGV.next if ARGV.include? "--set-version"
name = ARGV.next if ARGV.include? '--set-name' name = ARGV.next if ARGV.include? "--set-name"
fc = FormulaCreator.new fc = FormulaCreator.new
fc.name = name fc.name = name
fc.version = version fc.version = version
fc.url = url fc.url = url
fc.mode = if ARGV.include? '--cmake' fc.mode = if ARGV.include? "--cmake"
:cmake :cmake
elsif ARGV.include? '--autotools' elsif ARGV.include? "--autotools"
:autotools :autotools
end end
@ -76,7 +74,7 @@ class FormulaCreator
attr_reader :url, :sha256 attr_reader :url, :sha256
attr_accessor :name, :version, :path, :mode attr_accessor :name, :version, :path, :mode
def url= url def url=(url)
@url = url @url = url
path = Pathname.new(url) path = Pathname.new(url)
if @name.nil? if @name.nil?
@ -115,7 +113,7 @@ class FormulaCreator
@sha256 = r.fetch.sha256 if r.download_strategy == CurlDownloadStrategy @sha256 = r.fetch.sha256 if r.download_strategy == CurlDownloadStrategy
end end
path.write ERB.new(template, nil, '>').result(binding) path.write ERB.new(template, nil, ">").result(binding)
end end
def template; <<-EOS.undent def template; <<-EOS.undent

View File

@ -1,15 +1,15 @@
# encoding: UTF-8 # encoding: UTF-8
require 'formula' require "formula"
require 'ostruct' require "ostruct"
module Homebrew module Homebrew
def deps def deps
mode = OpenStruct.new( mode = OpenStruct.new(
:installed? => ARGV.include?('--installed'), :installed? => ARGV.include?("--installed"),
:tree? => ARGV.include?('--tree'), :tree? => ARGV.include?("--tree"),
:all? => ARGV.include?('--all'), :all? => ARGV.include?("--all"),
:topo_order? => ARGV.include?('-n'), :topo_order? => ARGV.include?("-n"),
:union? => ARGV.include?('--union') :union? => ARGV.include?("--union")
) )
if mode.installed? && mode.tree? if mode.installed? && mode.tree?
@ -30,7 +30,7 @@ module Homebrew
end end
end end
def deps_for_formula(f, recursive=false) def deps_for_formula(f, recursive = false)
ignores = [] ignores = []
ignores << "build?" if ARGV.include? "--skip-build" ignores << "build?" if ARGV.include? "--skip-build"
ignores << "optional?" if ARGV.include? "--skip-optional" ignores << "optional?" if ARGV.include? "--skip-optional"
@ -54,8 +54,8 @@ module Homebrew
deps + reqs.select(&:default_formula?).map(&:to_dependency) deps + reqs.select(&:default_formula?).map(&:to_dependency)
end end
def deps_for_formulae(formulae, recursive=false, &block) def deps_for_formulae(formulae, recursive = false, &block)
formulae.map {|f| deps_for_formula(f, recursive) }.inject(&block) formulae.map { |f| deps_for_formula(f, recursive) }.inject(&block)
end end
def puts_deps(formulae) def puts_deps(formulae)
@ -70,7 +70,7 @@ module Homebrew
end end
end end
def recursive_deps_tree f, prefix def recursive_deps_tree(f, prefix)
reqs = f.requirements.select(&:default_formula?) reqs = f.requirements.select(&:default_formula?)
max = reqs.length - 1 max = reqs.length - 1
reqs.each_with_index do |req, i| reqs.each_with_index do |req, i|

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +1,8 @@
require 'formula' require "formula"
module Homebrew module Homebrew
def edit def edit
unless (HOMEBREW_REPOSITORY/'.git').directory? unless (HOMEBREW_REPOSITORY/".git").directory?
raise <<-EOS.undent raise <<-EOS.undent
Changes will be lost! Changes will be lost!
The first time you `brew update', all local changes will be lost, you should The first time you `brew update', all local changes will be lost, you should
@ -13,11 +13,11 @@ module Homebrew
# If no brews are listed, open the project root in an editor. # If no brews are listed, open the project root in an editor.
if ARGV.named.empty? if ARGV.named.empty?
editor = File.basename which_editor editor = File.basename which_editor
if editor == "mate" or editor == "subl" if editor == "mate" || editor == "subl"
# If the user is using TextMate or Sublime Text, # If the user is using TextMate or Sublime Text,
# give a nice project view instead. # give a nice project view instead.
exec_editor HOMEBREW_REPOSITORY+"bin/brew", exec_editor HOMEBREW_REPOSITORY+"bin/brew",
HOMEBREW_REPOSITORY+'README.md', HOMEBREW_REPOSITORY+"README.md",
HOMEBREW_REPOSITORY+".gitignore", HOMEBREW_REPOSITORY+".gitignore",
*library_folders *library_folders
else else
@ -38,7 +38,7 @@ module Homebrew
def library_folders def library_folders
Dir["#{HOMEBREW_LIBRARY}/*"].reject do |d| Dir["#{HOMEBREW_LIBRARY}/*"].reject do |d|
case File.basename(d) when 'LinkedKegs', 'Aliases' then true end case File.basename(d) when "LinkedKegs", "Aliases" then true end
end end
end end
end end

View File

@ -1,10 +1,10 @@
require 'formula' require "formula"
module Homebrew module Homebrew
def fetch def fetch
raise FormulaUnspecifiedError if ARGV.named.empty? raise FormulaUnspecifiedError if ARGV.named.empty?
if ARGV.include? '--deps' if ARGV.include? "--deps"
bucket = [] bucket = []
ARGV.formulae.each do |f| ARGV.formulae.each do |f|
bucket << f bucket << f
@ -15,7 +15,7 @@ module Homebrew
bucket = ARGV.formulae bucket = ARGV.formulae
end end
puts "Fetching: #{bucket * ', '}" if bucket.size > 1 puts "Fetching: #{bucket * ", "}" if bucket.size > 1
bucket.each do |f| bucket.each do |f|
f.print_tap_action :verb => "Fetching" f.print_tap_action :verb => "Fetching"
@ -29,7 +29,7 @@ module Homebrew
end end
end end
def fetch_bottle? f def fetch_bottle?(f)
return true if ARGV.force_bottle? && f.bottle return true if ARGV.force_bottle? && f.bottle
return false unless f.bottle && f.pour_bottle? return false unless f.bottle && f.pour_bottle?
return false if ARGV.build_from_source? || ARGV.build_bottle? return false if ARGV.build_from_source? || ARGV.build_bottle?
@ -41,10 +41,10 @@ module Homebrew
return false return false
end end
return false unless f.bottle.compatible_cellar? return false unless f.bottle.compatible_cellar?
return true true
end end
def fetch_resource r def fetch_resource(r)
puts "Resource: #{r.name}" puts "Resource: #{r.name}"
fetch_fetchable r fetch_fetchable r
rescue ChecksumMismatchError => e rescue ChecksumMismatchError => e
@ -52,14 +52,14 @@ module Homebrew
opoo "Resource #{r.name} reports different #{e.hash_type}: #{e.expected}" opoo "Resource #{r.name} reports different #{e.hash_type}: #{e.expected}"
end end
def fetch_formula f def fetch_formula(f)
fetch_fetchable f fetch_fetchable f
rescue ChecksumMismatchError => e rescue ChecksumMismatchError => e
retry if retry_fetch? f retry if retry_fetch? f
opoo "Formula reports different #{e.hash_type}: #{e.expected}" opoo "Formula reports different #{e.hash_type}: #{e.expected}"
end end
def fetch_patch p def fetch_patch(p)
fetch_fetchable p fetch_fetchable p
rescue ChecksumMismatchError => e rescue ChecksumMismatchError => e
Homebrew.failed = true Homebrew.failed = true
@ -68,7 +68,7 @@ module Homebrew
private private
def retry_fetch? f def retry_fetch?(f)
@fetch_failed ||= Set.new @fetch_failed ||= Set.new
if ARGV.include?("--retry") && @fetch_failed.add?(f) if ARGV.include?("--retry") && @fetch_failed.add?(f)
ohai "Retrying download" ohai "Retrying download"
@ -80,7 +80,7 @@ module Homebrew
end end
end end
def fetch_fetchable f def fetch_fetchable(f)
f.clear_cache if ARGV.force? f.clear_cache if ARGV.force?
already_fetched = f.cached_download.exist? already_fetched = f.cached_download.exist?

View File

@ -1,11 +1,11 @@
require 'formula' require "formula"
require 'cmd/config' require "cmd/config"
require 'net/http' require "net/http"
require 'net/https' require "net/https"
require 'stringio' require "stringio"
module Homebrew module Homebrew
def gistify_logs f def gistify_logs(f)
files = load_logs(f.logs) files = load_logs(f.logs)
s = StringIO.new s = StringIO.new
@ -23,12 +23,12 @@ module Homebrew
url = create_gist(files) url = create_gist(files)
if ARGV.include?('--new-issue') || ARGV.switch?('n') if ARGV.include?("--new-issue") || ARGV.switch?("n")
auth = :AUTH_TOKEN auth = :AUTH_TOKEN
unless HOMEBREW_GITHUB_API_TOKEN unless HOMEBREW_GITHUB_API_TOKEN
puts 'You can create a personal access token: https://github.com/settings/tokens' puts "You can create a personal access token: https://github.com/settings/tokens"
puts 'and then set HOMEBREW_GITHUB_API_TOKEN as authentication method.' puts "and then set HOMEBREW_GITHUB_API_TOKEN as authentication method."
puts puts
auth = :AUTH_BASIC auth = :AUTH_BASIC
@ -40,19 +40,19 @@ module Homebrew
puts url if url puts url if url
end end
#Hack for ruby < 1.9.3 # Hack for ruby < 1.9.3
def noecho_gets def noecho_gets
system 'stty -echo' system "stty -echo"
result = $stdin.gets result = $stdin.gets
system 'stty echo' system "stty echo"
puts puts
result result
end end
def login request def login(request)
print 'GitHub User: ' print "GitHub User: "
user = $stdin.gets.chomp user = $stdin.gets.chomp
print 'Password: ' print "Password: "
password = noecho_gets.chomp password = noecho_gets.chomp
puts puts
request.basic_auth(user, password) request.basic_auth(user, password)
@ -64,23 +64,23 @@ module Homebrew
contents = file.size? ? file.read : "empty log" contents = file.size? ? file.read : "empty log"
logs[file.basename.to_s] = { :content => contents } logs[file.basename.to_s] = { :content => contents }
end if dir.exist? end if dir.exist?
raise 'No logs.' if logs.empty? raise "No logs." if logs.empty?
logs logs
end end
def create_gist files def create_gist(files)
post("/gists", { "public" => true, "files" => files })["html_url"] post("/gists", "public" => true, "files" => files)["html_url"]
end end
def new_issue repo, title, body, auth def new_issue(repo, title, body, auth)
post("/repos/#{repo}/issues", { "title" => title, "body" => body }, auth)["html_url"] post("/repos/#{repo}/issues", { "title" => title, "body" => body }, auth)["html_url"]
end end
def http def http
@http ||= begin @http ||= begin
uri = URI.parse('https://api.github.com') uri = URI.parse("https://api.github.com")
p = ENV['http_proxy'] ? URI.parse(ENV['http_proxy']) : nil p = ENV["http_proxy"] ? URI.parse(ENV["http_proxy"]) : nil
if p.class == URI::HTTP or p.class == URI::HTTPS if p.class == URI::HTTP || p.class == URI::HTTPS
@http = Net::HTTP.new(uri.host, uri.port, p.host, p.port, p.user, p.password) @http = Net::HTTP.new(uri.host, uri.port, p.host, p.port, p.user, p.password)
else else
@http = Net::HTTP.new(uri.host, uri.port) @http = Net::HTTP.new(uri.host, uri.port)
@ -94,10 +94,10 @@ module Homebrew
headers = { headers = {
"User-Agent" => HOMEBREW_USER_AGENT, "User-Agent" => HOMEBREW_USER_AGENT,
"Accept" => "application/vnd.github.v3+json", "Accept" => "application/vnd.github.v3+json",
"Content-Type" => "application/json", "Content-Type" => "application/json"
} }
if auth == :AUTH_TOKEN || (auth == nil && HOMEBREW_GITHUB_API_TOKEN) if auth == :AUTH_TOKEN || (auth.nil? && HOMEBREW_GITHUB_API_TOKEN)
headers["Authorization"] = "token #{HOMEBREW_GITHUB_API_TOKEN}" headers["Authorization"] = "token #{HOMEBREW_GITHUB_API_TOKEN}"
end end

View File

@ -35,6 +35,7 @@ module Homebrew
def help def help
puts HOMEBREW_HELP puts HOMEBREW_HELP
end end
def help_s def help_s
HOMEBREW_HELP HOMEBREW_HELP
end end

View File

@ -12,7 +12,7 @@ module Homebrew
# awhile around for compatibility # awhile around for compatibility
if ARGV.json == "v1" if ARGV.json == "v1"
print_json print_json
elsif ARGV.flag? '--github' elsif ARGV.flag? "--github"
exec_browser(*ARGV.formulae.map { |f| github_info(f) }) exec_browser(*ARGV.formulae.map { |f| github_info(f) })
else else
print_info print_info
@ -26,7 +26,7 @@ module Homebrew
puts "#{count} keg#{plural(count)}, #{HOMEBREW_CELLAR.abv}" puts "#{count} keg#{plural(count)}, #{HOMEBREW_CELLAR.abv}"
end end
else else
ARGV.named.each_with_index do |f,i| ARGV.named.each_with_index do |f, i|
puts unless i == 0 puts unless i == 0
begin begin
info_formula Formulary.factory(f) info_formula Formulary.factory(f)
@ -44,13 +44,13 @@ module Homebrew
def print_json def print_json
ff = if ARGV.include? "--all" ff = if ARGV.include? "--all"
Formula Formula
elsif ARGV.include? "--installed" elsif ARGV.include? "--installed"
Formula.installed Formula.installed
else else
ARGV.formulae ARGV.formulae
end end
json = ff.map {|f| f.to_hash} json = ff.map(&:to_hash)
puts Utils::JSON.dump(json) puts Utils::JSON.dump(json)
end end
@ -62,7 +62,7 @@ module Homebrew
end end
end end
def github_info f def github_info(f)
if f.tap? if f.tap?
user, repo = f.tap.split("/", 2) user, repo = f.tap.split("/", 2)
path = f.path.relative_path_from(HOMEBREW_LIBRARY.join("Taps", f.tap)) path = f.path.relative_path_from(HOMEBREW_LIBRARY.join("Taps", f.tap))
@ -76,7 +76,7 @@ module Homebrew
end end
end end
def info_formula f def info_formula(f)
specs = [] specs = []
if stable = f.stable if stable = f.stable
@ -93,7 +93,7 @@ module Homebrew
specs << "HEAD" if f.head specs << "HEAD" if f.head
puts "#{f.full_name}: #{specs*', '}#{' (pinned)' if f.pinned?}" puts "#{f.full_name}: #{specs*", "}#{" (pinned)" if f.pinned?}"
puts f.desc if f.desc puts f.desc if f.desc
@ -107,12 +107,12 @@ module Homebrew
end end
conflicts = f.conflicts.map(&:name).sort! conflicts = f.conflicts.map(&:name).sort!
puts "Conflicts with: #{conflicts*', '}" unless conflicts.empty? puts "Conflicts with: #{conflicts*", "}" unless conflicts.empty?
if f.rack.directory? if f.rack.directory?
kegs = f.rack.subdirs.map { |keg| Keg.new(keg) }.sort_by(&:version) kegs = f.rack.subdirs.map { |keg| Keg.new(keg) }.sort_by(&:version)
kegs.each do |keg| kegs.each do |keg|
puts "#{keg} (#{keg.abv})#{' *' if keg.linked?}" puts "#{keg} (#{keg.abv})#{" *" if keg.linked?}"
tab = Tab.for_keg(keg).to_s tab = Tab.for_keg(keg).to_s
puts " #{tab}" unless tab.empty? puts " #{tab}" unless tab.empty?
end end
@ -125,7 +125,7 @@ module Homebrew
unless f.deps.empty? unless f.deps.empty?
ohai "Dependencies" ohai "Dependencies"
%w{build required recommended optional}.map do |type| %w[build required recommended optional].map do |type|
deps = f.deps.send(type).uniq deps = f.deps.send(type).uniq
puts "#{type.capitalize}: #{decorate_dependencies deps}" unless deps.empty? puts "#{type.capitalize}: #{decorate_dependencies deps}" unless deps.empty?
end end
@ -137,10 +137,10 @@ module Homebrew
end end
c = Caveats.new(f) c = Caveats.new(f)
ohai 'Caveats', c.caveats unless c.empty? ohai "Caveats", c.caveats unless c.empty?
end end
def decorate_dependencies dependencies def decorate_dependencies(dependencies)
# necessary for 1.8.7 unicode handling since many installs are on 1.8.7 # necessary for 1.8.7 unicode handling since many installs are on 1.8.7
tick = ["2714".hex].pack("U*") tick = ["2714".hex].pack("U*")
cross = ["2718".hex].pack("U*") cross = ["2718".hex].pack("U*")
@ -153,7 +153,7 @@ module Homebrew
color = Tty.red color = Tty.red
symbol = cross symbol = cross
end end
if ENV['HOMEBREW_NO_EMOJI'] if ENV["HOMEBREW_NO_EMOJI"]
colored_dep = "#{color}#{dep}" colored_dep = "#{color}#{dep}"
else else
colored_dep = "#{dep} #{color}#{symbol}" colored_dep = "#{dep} #{color}#{symbol}"

View File

@ -9,7 +9,7 @@ module Homebrew
def install def install
raise FormulaUnspecifiedError if ARGV.named.empty? raise FormulaUnspecifiedError if ARGV.named.empty?
if ARGV.include? '--head' if ARGV.include? "--head"
raise "Specify `--HEAD` in uppercase to build from trunk." raise "Specify `--HEAD` in uppercase to build from trunk."
end end
@ -40,7 +40,7 @@ module Homebrew
ARGV.formulae.each do |f| ARGV.formulae.each do |f|
# head-only without --HEAD is an error # head-only without --HEAD is an error
if not ARGV.build_head? and f.stable.nil? and f.devel.nil? if !ARGV.build_head? && f.stable.nil? && f.devel.nil?
raise <<-EOS.undent raise <<-EOS.undent
#{f.full_name} is a head-only formula #{f.full_name} is a head-only formula
Install with `brew install --HEAD #{f.full_name}` Install with `brew install --HEAD #{f.full_name}`
@ -48,30 +48,30 @@ module Homebrew
end end
# devel-only without --devel is an error # devel-only without --devel is an error
if not ARGV.build_devel? and f.stable.nil? and f.head.nil? if !ARGV.build_devel? && f.stable.nil? && f.head.nil?
raise <<-EOS.undent raise <<-EOS.undent
#{f.full_name} is a devel-only formula #{f.full_name} is a devel-only formula
Install with `brew install --devel #{f.full_name}` Install with `brew install --devel #{f.full_name}`
EOS EOS
end end
if ARGV.build_stable? and f.stable.nil? if ARGV.build_stable? && f.stable.nil?
raise "#{f.full_name} has no stable download, please choose --devel or --HEAD" raise "#{f.full_name} has no stable download, please choose --devel or --HEAD"
end end
# --HEAD, fail with no head defined # --HEAD, fail with no head defined
if ARGV.build_head? and f.head.nil? if ARGV.build_head? && f.head.nil?
raise "No head is defined for #{f.full_name}" raise "No head is defined for #{f.full_name}"
end end
# --devel, fail with no devel defined # --devel, fail with no devel defined
if ARGV.build_devel? and f.devel.nil? if ARGV.build_devel? && f.devel.nil?
raise "No devel block is defined for #{f.full_name}" raise "No devel block is defined for #{f.full_name}"
end end
if f.installed? if f.installed?
msg = "#{f.full_name}-#{f.installed_version} already installed" msg = "#{f.full_name}-#{f.installed_version} already installed"
msg << ", it's just not linked" unless f.linked_keg.symlink? or f.keg_only? msg << ", it's just not linked" unless f.linked_keg.symlink? || f.keg_only?
opoo msg opoo msg
else else
formulae << f formulae << f
@ -107,17 +107,18 @@ module Homebrew
end end
def check_ppc def check_ppc
case Hardware::CPU.type when :ppc, :dunno case Hardware::CPU.type
when :ppc, :dunno
abort <<-EOS.undent abort <<-EOS.undent
Sorry, Homebrew does not support your computer's CPU architecture. Sorry, Homebrew does not support your computer's CPU architecture.
For PPC support, see: https://github.com/mistydemeo/tigerbrew For PPC support, see: https://github.com/mistydemeo/tigerbrew
EOS EOS
end end
end end
def check_writable_install_location def check_writable_install_location
raise "Cannot write to #{HOMEBREW_CELLAR}" if HOMEBREW_CELLAR.exist? and not HOMEBREW_CELLAR.writable_real? raise "Cannot write to #{HOMEBREW_CELLAR}" if HOMEBREW_CELLAR.exist? && !HOMEBREW_CELLAR.writable_real?
raise "Cannot write to #{HOMEBREW_PREFIX}" unless HOMEBREW_PREFIX.writable_real? or HOMEBREW_PREFIX.to_s == '/usr/local' raise "Cannot write to #{HOMEBREW_PREFIX}" unless HOMEBREW_PREFIX.writable_real? || HOMEBREW_PREFIX.to_s == "/usr/local"
end end
def check_xcode def check_xcode
@ -143,7 +144,7 @@ module Homebrew
end end
def check_cellar def check_cellar
FileUtils.mkdir_p HOMEBREW_CELLAR if not File.exist? HOMEBREW_CELLAR FileUtils.mkdir_p HOMEBREW_CELLAR unless File.exist? HOMEBREW_CELLAR
rescue rescue
raise <<-EOS.undent raise <<-EOS.undent
Could not create #{HOMEBREW_CELLAR} Could not create #{HOMEBREW_CELLAR}
@ -158,7 +159,7 @@ module Homebrew
check_cellar check_cellar
end end
def install_formula f def install_formula(f)
f.print_tap_action f.print_tap_action
fi = FormulaInstaller.new(f) fi = FormulaInstaller.new(f)

View File

@ -1,6 +1,6 @@
require 'formula' require "formula"
require 'keg' require "keg"
require 'irb' require "irb"
class Symbol class Symbol
def f(*args) def f(*args)

View File

@ -1,6 +1,6 @@
require 'formula' require "formula"
require 'tab' require "tab"
require 'set' require "set"
module Homebrew module Homebrew
def leaves def leaves

View File

@ -1,4 +1,4 @@
require 'ostruct' require "ostruct"
module Homebrew module Homebrew
def link def link
@ -6,7 +6,7 @@ module Homebrew
mode = OpenStruct.new mode = OpenStruct.new
mode.overwrite = true if ARGV.include? '--overwrite' mode.overwrite = true if ARGV.include? "--overwrite"
mode.dry_run = true if ARGV.dry_run? mode.dry_run = true if ARGV.dry_run?
ARGV.kegs.each do |keg| ARGV.kegs.each do |keg|

View File

@ -1,5 +1,5 @@
# Links any Applications (.app) found in installed prefixes to /Applications # Links any Applications (.app) found in installed prefixes to /Applications
require 'keg' require "keg"
module Homebrew module Homebrew
def linkapps def linkapps
@ -16,7 +16,7 @@ module Homebrew
kegs = racks.map do |rack| kegs = racks.map do |rack|
keg = rack.subdirs.map { |d| Keg.new(d) } keg = rack.subdirs.map { |d| Keg.new(d) }
next if keg.empty? next if keg.empty?
keg.detect(&:linked?) || keg.max {|a,b| a.version <=> b.version} keg.detect(&:linked?) || keg.max { |a, b| a.version <=> b.version }
end end
else else
kegs = ARGV.kegs kegs = ARGV.kegs

View File

@ -3,9 +3,8 @@ require "formula"
module Homebrew module Homebrew
def list def list
# Use of exec means we don't explicitly exit # Use of exec means we don't explicitly exit
list_unbrewed if ARGV.flag? '--unbrewed' list_unbrewed if ARGV.flag? "--unbrewed"
# Unbrewed uses the PREFIX, which will exist # Unbrewed uses the PREFIX, which will exist
# Things below use the CELLAR, which doesn't until the first formula is installed. # Things below use the CELLAR, which doesn't until the first formula is installed.
@ -14,7 +13,7 @@ module Homebrew
return return
end end
if ARGV.include? '--pinned' or ARGV.include? '--versions' if ARGV.include?("--pinned") || ARGV.include?("--versions")
filtered_list filtered_list
elsif ARGV.named.empty? elsif ARGV.named.empty?
if ARGV.include? "--full-name" if ARGV.include? "--full-name"
@ -29,13 +28,13 @@ module Homebrew
end end
puts_columns full_names puts_columns full_names
else else
ENV['CLICOLOR'] = nil ENV["CLICOLOR"] = nil
exec 'ls', *ARGV.options_only << HOMEBREW_CELLAR exec "ls", *ARGV.options_only << HOMEBREW_CELLAR
end end
elsif ARGV.verbose? or not $stdout.tty? elsif ARGV.verbose? || !$stdout.tty?
exec "find", *ARGV.kegs.map(&:to_s) + %w[-not -type d -print] exec "find", *ARGV.kegs.map(&:to_s) + %w[-not -type d -print]
else else
ARGV.kegs.each{ |keg| PrettyListing.new keg } ARGV.kegs.each { |keg| PrettyListing.new keg }
end end
end end
@ -65,8 +64,8 @@ module Homebrew
# Exclude the repository and cache, if they are located under the prefix # Exclude the repository and cache, if they are located under the prefix
dirs.delete HOMEBREW_CACHE.relative_path_from(HOMEBREW_PREFIX).to_s dirs.delete HOMEBREW_CACHE.relative_path_from(HOMEBREW_PREFIX).to_s
dirs.delete HOMEBREW_REPOSITORY.relative_path_from(HOMEBREW_PREFIX).to_s dirs.delete HOMEBREW_REPOSITORY.relative_path_from(HOMEBREW_PREFIX).to_s
dirs.delete 'etc' dirs.delete "etc"
dirs.delete 'var' dirs.delete "var"
args = dirs + %w[-type f (] args = dirs + %w[-type f (]
args.concat UNBREWED_EXCLUDE_FILES.map { |f| %W[! -name #{f}] }.flatten args.concat UNBREWED_EXCLUDE_FILES.map { |f| %W[! -name #{f}] }.flatten
@ -74,46 +73,46 @@ module Homebrew
args.concat %w[)] args.concat %w[)]
cd HOMEBREW_PREFIX cd HOMEBREW_PREFIX
exec 'find', *args exec "find", *args
end end
def filtered_list def filtered_list
names = if ARGV.named.empty? names = if ARGV.named.empty?
HOMEBREW_CELLAR.subdirs HOMEBREW_CELLAR.subdirs
else else
ARGV.named.map{ |n| HOMEBREW_CELLAR+n }.select{ |pn| pn.exist? } ARGV.named.map { |n| HOMEBREW_CELLAR+n }.select(&:exist?)
end end
if ARGV.include? '--pinned' if ARGV.include? "--pinned"
pinned_versions = {} pinned_versions = {}
names.each do |d| names.each do |d|
keg_pin = (HOMEBREW_LIBRARY/"PinnedKegs"/d.basename.to_s) keg_pin = (HOMEBREW_LIBRARY/"PinnedKegs"/d.basename.to_s)
if keg_pin.exist? or keg_pin.symlink? if keg_pin.exist? || keg_pin.symlink?
pinned_versions[d] = keg_pin.readlink.basename.to_s pinned_versions[d] = keg_pin.readlink.basename.to_s
end end
end end
pinned_versions.each do |d, version| pinned_versions.each do |d, version|
puts "#{d.basename}".concat(ARGV.include?('--versions') ? " #{version}" : '') puts "#{d.basename}".concat(ARGV.include?("--versions") ? " #{version}" : "")
end end
else # --versions without --pinned else # --versions without --pinned
names.each do |d| names.each do |d|
versions = d.subdirs.map { |pn| pn.basename.to_s } versions = d.subdirs.map { |pn| pn.basename.to_s }
next if ARGV.include?('--multiple') && versions.count < 2 next if ARGV.include?("--multiple") && versions.count < 2
puts "#{d.basename} #{versions*' '}" puts "#{d.basename} #{versions*" "}"
end end
end end
end end
end end
class PrettyListing class PrettyListing
def initialize path def initialize(path)
Pathname.new(path).children.sort_by { |p| p.to_s.downcase }.each do |pn| Pathname.new(path).children.sort_by { |p| p.to_s.downcase }.each do |pn|
case pn.basename.to_s case pn.basename.to_s
when 'bin', 'sbin' when "bin", "sbin"
pn.find { |pnn| puts pnn unless pnn.directory? } pn.find { |pnn| puts pnn unless pnn.directory? }
when 'lib' when "lib"
print_dir pn do |pnn| print_dir pn do |pnn|
# dylibs have multiple symlinks and we don't care about them # dylibs have multiple symlinks and we don't care about them
(pnn.extname == '.dylib' or pnn.extname == '.pc') and not pnn.symlink? (pnn.extname == ".dylib" || pnn.extname == ".pc") && !pnn.symlink?
end end
else else
if pn.directory? if pn.directory?
@ -129,19 +128,19 @@ class PrettyListing
end end
end end
def print_dir root def print_dir(root)
dirs = [] dirs = []
remaining_root_files = [] remaining_root_files = []
other = '' other = ""
root.children.sort.each do |pn| root.children.sort.each do |pn|
if pn.directory? if pn.directory?
dirs << pn dirs << pn
elsif block_given? and yield pn elsif block_given? and yield pn
puts pn puts pn
other = 'other ' other = "other "
else else
remaining_root_files << pn unless pn.basename.to_s == '.DS_Store' remaining_root_files << pn unless pn.basename.to_s == ".DS_Store"
end end
end end
@ -154,7 +153,7 @@ class PrettyListing
print_remaining_files remaining_root_files, root, other print_remaining_files remaining_root_files, root, other
end end
def print_remaining_files files, root, other = '' def print_remaining_files(files, root, other = "")
case files.length case files.length
when 0 when 0
# noop # noop

View File

@ -1,4 +1,4 @@
require 'formula' require "formula"
module Homebrew module Homebrew
SOURCE_PATH=HOMEBREW_REPOSITORY/"Library/Homebrew/manpages" SOURCE_PATH=HOMEBREW_REPOSITORY/"Library/Homebrew/manpages"

View File

@ -1,8 +1,8 @@
require 'formula' require "formula"
require 'tab' require "tab"
module Homebrew module Homebrew
def missing_deps ff def missing_deps(ff)
missing = {} missing = {}
ff.each do |f| ff.each do |f|
missing_deps = f.recursive_dependencies do |dependent, dep| missing_deps = f.recursive_dependencies do |dependent, dep|
@ -36,7 +36,7 @@ module Homebrew
missing_deps(ff) do |name, missing| missing_deps(ff) do |name, missing|
print "#{name}: " if ff.size > 1 print "#{name}: " if ff.size > 1
puts "#{missing * ' '}" puts "#{missing * " "}"
end end
end end
end end

View File

@ -1,10 +1,10 @@
require 'formula' require "formula"
module Homebrew module Homebrew
def options def options
if ARGV.include? '--all' if ARGV.include? "--all"
puts_options Formula.to_a puts_options Formula.to_a
elsif ARGV.include? '--installed' elsif ARGV.include? "--installed"
puts_options Formula.installed puts_options Formula.installed
else else
raise FormulaUnspecifiedError if ARGV.named.empty? raise FormulaUnspecifiedError if ARGV.named.empty?
@ -15,7 +15,7 @@ module Homebrew
def puts_options(formulae) def puts_options(formulae)
formulae.each do |f| formulae.each do |f|
next if f.options.empty? next if f.options.empty?
if ARGV.include? '--compact' if ARGV.include? "--compact"
puts f.options.as_flags.sort * " " puts f.options.as_flags.sort * " "
else else
puts f.full_name if formulae.length > 1 puts f.full_name if formulae.length > 1
@ -25,7 +25,7 @@ module Homebrew
end end
end end
def dump_options_for_formula f def dump_options_for_formula(f)
f.options.sort_by(&:flag).each do |opt| f.options.sort_by(&:flag).each do |opt|
puts "#{opt.flag}\n\t#{opt.description}" puts "#{opt.flag}\n\t#{opt.description}"
end end

View File

@ -1,5 +1,5 @@
require 'formula' require "formula"
require 'keg' require "keg"
module Homebrew module Homebrew
def outdated def outdated
@ -40,7 +40,7 @@ module Homebrew
outdated_brews(formulae) do |f, versions| outdated_brews(formulae) do |f, versions|
if verbose if verbose
puts "#{f.full_name} (#{versions*', '} < #{f.pkg_version})" puts "#{f.full_name} (#{versions*", "} < #{f.pkg_version})"
else else
puts f.full_name puts f.full_name
end end
@ -50,9 +50,9 @@ module Homebrew
def print_outdated_json(formulae) def print_outdated_json(formulae)
json = [] json = []
outdated = outdated_brews(formulae) do |f, versions| outdated = outdated_brews(formulae) do |f, versions|
json << {:name => f.full_name, json << { :name => f.full_name,
:installed_versions => versions.collect(&:to_s), :installed_versions => versions.collect(&:to_s),
:current_version => f.pkg_version.to_s} :current_version => f.pkg_version.to_s }
end end
puts Utils::JSON.dump(json) puts Utils::JSON.dump(json)

View File

@ -1,4 +1,4 @@
require 'formula' require "formula"
module Homebrew module Homebrew
def pin def pin

View File

@ -1,5 +1,5 @@
require 'keg' require "keg"
require 'cmd/tap' require "cmd/tap"
module Homebrew module Homebrew
def prune def prune
@ -44,7 +44,7 @@ module Homebrew
n, d = ObserverPathnameExtension.counts n, d = ObserverPathnameExtension.counts
print "Pruned #{n} symbolic links " print "Pruned #{n} symbolic links "
print "and #{d} directories " if d > 0 print "and #{d} directories " if d > 0
puts "from #{HOMEBREW_PREFIX}" puts "from #{HOMEBREW_PREFIX}"
end unless ARGV.dry_run? end unless ARGV.dry_run?
end end
end end

View File

@ -1,33 +1,33 @@
# Gets a patch from a GitHub commit or pull request and applies it to Homebrew. # Gets a patch from a GitHub commit or pull request and applies it to Homebrew.
# Optionally, installs it too. # Optionally, installs it too.
require 'utils' require "utils"
require 'formula' require "formula"
require 'cmd/tap' require "cmd/tap"
module Homebrew module Homebrew
HOMEBREW_PULL_API_REGEX = %r{https://api\.github\.com/repos/([\w-]+)/homebrew(-[\w-]+)?/pulls/(\d+)} HOMEBREW_PULL_API_REGEX = %r{https://api\.github\.com/repos/([\w-]+)/homebrew(-[\w-]+)?/pulls/(\d+)}
def tap arg def tap(arg)
match = arg.match(%r[homebrew-([\w-]+)/]) match = arg.match(%r{homebrew-([\w-]+)/})
match[1].downcase if match match[1].downcase if match
end end
def pull_url url def pull_url(url)
# GitHub provides commits/pull-requests raw patches using this URL. # GitHub provides commits/pull-requests raw patches using this URL.
url += '.patch' url += ".patch"
patchpath = HOMEBREW_CACHE + File.basename(url) patchpath = HOMEBREW_CACHE + File.basename(url)
curl url, '-o', patchpath curl url, "-o", patchpath
ohai 'Applying patch' ohai "Applying patch"
patch_args = [] patch_args = []
# Normally we don't want whitespace errors, but squashing them can break # Normally we don't want whitespace errors, but squashing them can break
# patches so an option is provided to skip this step. # patches so an option is provided to skip this step.
if ARGV.include? '--ignore-whitespace' or ARGV.include? '--clean' if ARGV.include?("--ignore-whitespace") || ARGV.include?("--clean")
patch_args << '--whitespace=nowarn' patch_args << "--whitespace=nowarn"
else else
patch_args << '--whitespace=fix' patch_args << "--whitespace=fix"
end end
# Fall back to three-way merge if patch does not apply cleanly # Fall back to three-way merge if patch does not apply cleanly
@ -35,13 +35,13 @@ module Homebrew
patch_args << patchpath patch_args << patchpath
begin begin
safe_system 'git', 'am', *patch_args safe_system "git", "am", *patch_args
rescue ErrorDuringExecution rescue ErrorDuringExecution
if ARGV.include? "--resolve" if ARGV.include? "--resolve"
odie "Patch failed to apply: try to resolve it." odie "Patch failed to apply: try to resolve it."
else else
system 'git', 'am', '--abort' system "git", "am", "--abort"
odie 'Patch failed to apply: aborted.' odie "Patch failed to apply: aborted."
end end
ensure ensure
patchpath.unlink patchpath.unlink
@ -50,11 +50,11 @@ module Homebrew
def pull def pull
if ARGV.empty? if ARGV.empty?
odie 'This command requires at least one argument containing a URL or pull request number' odie "This command requires at least one argument containing a URL or pull request number"
end end
if ARGV[0] == '--rebase' if ARGV[0] == "--rebase"
odie 'You meant `git pull --rebase`.' odie "You meant `git pull --rebase`."
end end
ARGV.named.each do |arg| ARGV.named.each do |arg|
@ -64,7 +64,7 @@ module Homebrew
elsif (testing_match = arg.match %r{brew.sh/job/Homebrew%20Testing/(\d+)/}) elsif (testing_match = arg.match %r{brew.sh/job/Homebrew%20Testing/(\d+)/})
_, testing_job = *testing_match _, testing_job = *testing_match
url = "https://github.com/Homebrew/homebrew/compare/master...BrewTestBot:testing-#{testing_job}" url = "https://github.com/Homebrew/homebrew/compare/master...BrewTestBot:testing-#{testing_job}"
odie "Testing URLs require `--bottle`!" unless ARGV.include?('--bottle') odie "Testing URLs require `--bottle`!" unless ARGV.include?("--bottle")
else else
if (api_match = arg.match HOMEBREW_PULL_API_REGEX) if (api_match = arg.match HOMEBREW_PULL_API_REGEX)
_, user, tap, pull = *api_match _, user, tap, pull = *api_match
@ -126,19 +126,19 @@ module Homebrew
end end
end end
unless ARGV.include? '--bottle' unless ARGV.include? "--bottle"
changed_formulae.each do |f| changed_formulae.each do |f|
next unless f.bottle next unless f.bottle
opoo "#{f.full_name} has a bottle: do you need to update it with --bottle?" opoo "#{f.full_name} has a bottle: do you need to update it with --bottle?"
end end
end end
if issue && !ARGV.include?('--clean') if issue && !ARGV.include?("--clean")
ohai "Patch closes issue ##{issue}" ohai "Patch closes issue ##{issue}"
message = `git log HEAD^.. --format=%B` message = `git log HEAD^.. --format=%B`
if ARGV.include? '--bump' if ARGV.include? "--bump"
odie 'Can only bump one changed formula' unless changed_formulae.length == 1 odie "Can only bump one changed formula" unless changed_formulae.length == 1
formula = changed_formulae.first formula = changed_formulae.first
subject = "#{formula.name} #{formula.version}" subject = "#{formula.name} #{formula.version}"
ohai "New bump commit subject: #{subject}" ohai "New bump commit subject: #{subject}"
@ -149,7 +149,7 @@ module Homebrew
# If this is a pull request, append a close message. # If this is a pull request, append a close message.
unless message.include? "Closes ##{issue}." unless message.include? "Closes ##{issue}."
message += "\nCloses ##{issue}." message += "\nCloses ##{issue}."
safe_system 'git', 'commit', '--amend', '--signoff', '--allow-empty', '-q', '-m', message safe_system "git", "commit", "--amend", "--signoff", "--allow-empty", "-q", "-m", message
end end
end end
@ -202,14 +202,14 @@ module Homebrew
end end
end end
ohai 'Patch changed:' ohai "Patch changed:"
safe_system "git", "diff-tree", "-r", "--stat", revision, "HEAD" safe_system "git", "diff-tree", "-r", "--stat", revision, "HEAD"
if ARGV.include? '--install' if ARGV.include? "--install"
changed_formulae.each do |f| changed_formulae.each do |f|
ohai "Installing #{f.full_name}" ohai "Installing #{f.full_name}"
install = f.installed? ? 'upgrade' : 'install' install = f.installed? ? "upgrade" : "install"
safe_system 'brew', install, '--debug', f.full_name safe_system "brew", install, "--debug", f.full_name
end end
end end
end end

View File

@ -5,7 +5,7 @@ module Homebrew
ARGV.resolved_formulae.each { |f| reinstall_formula(f) } ARGV.resolved_formulae.each { |f| reinstall_formula(f) }
end end
def reinstall_formula f def reinstall_formula(f)
tab = Tab.for_formula(f) tab = Tab.for_formula(f)
options = tab.used_options | f.build.used_options options = tab.used_options | f.build.used_options
@ -38,12 +38,12 @@ module Homebrew
backup_path(keg).rmtree if backup_path(keg).exist? backup_path(keg).rmtree if backup_path(keg).exist?
end end
def backup keg def backup(keg)
keg.unlink keg.unlink
keg.rename backup_path(keg) keg.rename backup_path(keg)
end end
def restore_backup keg, formula def restore_backup(keg, formula)
path = backup_path(keg) path = backup_path(keg)
if path.directory? if path.directory?
path.rename keg path.rename keg
@ -51,7 +51,7 @@ module Homebrew
end end
end end
def backup_path path def backup_path(path)
Pathname.new "#{path}.reinstall" Pathname.new "#{path}.reinstall"
end end
end end

View File

@ -1,27 +1,26 @@
require 'formula' require "formula"
require 'blacklist' require "blacklist"
require 'utils' require "utils"
require 'thread' require "thread"
require "official_taps" require "official_taps"
module Homebrew module Homebrew
SEARCH_ERROR_QUEUE = Queue.new SEARCH_ERROR_QUEUE = Queue.new
def search def search
if ARGV.include? '--macports' if ARGV.include? "--macports"
exec_browser "https://www.macports.org/ports.php?by=name&substr=#{ARGV.next}" exec_browser "https://www.macports.org/ports.php?by=name&substr=#{ARGV.next}"
elsif ARGV.include? '--fink' elsif ARGV.include? "--fink"
exec_browser "http://pdb.finkproject.org/pdb/browse.php?summary=#{ARGV.next}" exec_browser "http://pdb.finkproject.org/pdb/browse.php?summary=#{ARGV.next}"
elsif ARGV.include? '--debian' elsif ARGV.include? "--debian"
exec_browser "https://packages.debian.org/search?keywords=#{ARGV.next}&searchon=names&suite=all&section=all" exec_browser "https://packages.debian.org/search?keywords=#{ARGV.next}&searchon=names&suite=all&section=all"
elsif ARGV.include? '--opensuse' elsif ARGV.include? "--opensuse"
exec_browser "https://software.opensuse.org/search?q=#{ARGV.next}" exec_browser "https://software.opensuse.org/search?q=#{ARGV.next}"
elsif ARGV.include? '--fedora' elsif ARGV.include? "--fedora"
exec_browser "https://admin.fedoraproject.org/pkgdb/packages/%2A#{ARGV.next}%2A/" exec_browser "https://admin.fedoraproject.org/pkgdb/packages/%2A#{ARGV.next}%2A/"
elsif ARGV.include? '--ubuntu' elsif ARGV.include? "--ubuntu"
exec_browser "http://packages.ubuntu.com/search?keywords=#{ARGV.next}&searchon=names&suite=all&section=all" exec_browser "http://packages.ubuntu.com/search?keywords=#{ARGV.next}&searchon=names&suite=all&section=all"
elsif ARGV.include? '--desc' elsif ARGV.include? "--desc"
query = ARGV.next query = ARGV.next
rx = query_regexp(query) rx = query_regexp(query)
Formula.each do |formula| Formula.each do |formula|
@ -48,7 +47,7 @@ module Homebrew
local_results = search_formulae(rx) local_results = search_formulae(rx)
puts_columns(local_results) puts_columns(local_results)
if not query.empty? and $stdout.tty? and msg = blacklisted?(query) if !query.empty? && $stdout.tty? && msg = blacklisted?(query)
unless local_results.empty? unless local_results.empty?
puts puts
puts "If you meant #{query.inspect} precisely:" puts "If you meant #{query.inspect} precisely:"
@ -61,7 +60,7 @@ module Homebrew
puts_columns(tap_results) puts_columns(tap_results)
count = local_results.length + tap_results.length count = local_results.length + tap_results.length
if count == 0 and not blacklisted? query if count == 0 and !blacklisted? query
puts "No formula found for #{query.inspect}." puts "No formula found for #{query.inspect}."
begin begin
GitHub.print_pull_requests_matching(query) GitHub.print_pull_requests_matching(query)
@ -73,7 +72,7 @@ module Homebrew
metacharacters = %w[\\ | ( ) [ ] { } ^ $ * + ? .] metacharacters = %w[\\ | ( ) [ ] { } ^ $ * + ? .]
bad_regex = metacharacters.any? do |char| bad_regex = metacharacters.any? do |char|
ARGV.any? do |arg| ARGV.any? do |arg|
arg.include?(char) && !arg.start_with?('/') arg.include?(char) && !arg.start_with?("/")
end end
end end
if ARGV.any? && bad_regex if ARGV.any? && bad_regex
@ -84,7 +83,7 @@ module Homebrew
end end
SEARCHABLE_TAPS = OFFICIAL_TAPS.map { |tap| ["Homebrew", tap] } + [ SEARCHABLE_TAPS = OFFICIAL_TAPS.map { |tap| ["Homebrew", tap] } + [
%w{Caskroom cask}, %w[Caskroom cask]
] ]
def query_regexp(query) def query_regexp(query)
@ -102,7 +101,7 @@ module Homebrew
end end
end end
def search_tap user, repo, rx def search_tap(user, repo, rx)
if (HOMEBREW_LIBRARY/"Taps/#{user.downcase}/homebrew-#{repo.downcase}").directory? && \ if (HOMEBREW_LIBRARY/"Taps/#{user.downcase}/homebrew-#{repo.downcase}").directory? && \
"#{user}/#{repo}" != "Caskroom/cask" "#{user}/#{repo}" != "Caskroom/cask"
return [] return []
@ -140,7 +139,7 @@ module Homebrew
[] []
end end
def search_formulae rx def search_formulae(rx)
aliases = Formula.aliases aliases = Formula.aliases
results = (Formula.full_names+aliases).grep(rx).sort results = (Formula.full_names+aliases).grep(rx).sort

View File

@ -1,5 +1,5 @@
require 'extend/ENV' require "extend/ENV"
require 'formula' require "formula"
module Homebrew module Homebrew
def sh def sh
@ -12,10 +12,10 @@ module Homebrew
ENV.setup_build_environment ENV.setup_build_environment
if superenv? if superenv?
# superenv stopped adding brew's bin but generally user's will want it # superenv stopped adding brew's bin but generally user's will want it
ENV['PATH'] = ENV['PATH'].split(File::PATH_SEPARATOR).insert(1, "#{HOMEBREW_PREFIX}/bin").join(File::PATH_SEPARATOR) ENV["PATH"] = ENV["PATH"].split(File::PATH_SEPARATOR).insert(1, "#{HOMEBREW_PREFIX}/bin").join(File::PATH_SEPARATOR)
end end
ENV['PS1'] = 'brew \[\033[1;32m\]\w\[\033[0m\]$ ' ENV["PS1"] = 'brew \[\033[1;32m\]\w\[\033[0m\]$ '
ENV['VERBOSE'] = '1' ENV["VERBOSE"] = "1"
puts <<-EOS.undent_________________________________________________________72 puts <<-EOS.undent_________________________________________________________72
Your shell has been configured to use Homebrew's build environment: Your shell has been configured to use Homebrew's build environment:
this should help you build stuff. Notably though, the system versions of this should help you build stuff. Notably though, the system versions of
@ -24,6 +24,6 @@ module Homebrew
ignore our configuration. ignore our configuration.
When done, type `exit'. When done, type `exit'.
EOS EOS
exec ENV['SHELL'] exec ENV["SHELL"]
end end
end end

View File

@ -25,7 +25,7 @@ module Homebrew
onoe "#{name} does not have a version \"#{version}\" in the Cellar." onoe "#{name} does not have a version \"#{version}\" in the Cellar."
versions = rack.subdirs.map { |d| Keg.new(d).version } versions = rack.subdirs.map { |d| Keg.new(d).version }
puts "Versions available: #{versions.join(', ')}" puts "Versions available: #{versions.join(", ")}"
exit 3 exit 3
end end

View File

@ -25,7 +25,7 @@ module Homebrew
EOS EOS
puts template if ARGV.verbose? puts template if ARGV.verbose?
path = Pathname.new('./README.md') path = Pathname.new("./README.md")
raise "#{path} already exists" if path.exist? raise "#{path} already exists" if path.exist?
path.write template path.write template
end end

View File

@ -13,7 +13,7 @@ module Homebrew
end end
end end
def install_tap user, repo, clone_target=nil def install_tap(user, repo, clone_target = nil)
tap = Tap.new user, repo tap = Tap.new user, repo
return false if tap.installed? return false if tap.installed?
ohai "Tapping #{tap}" ohai "Tapping #{tap}"
@ -23,7 +23,7 @@ module Homebrew
safe_system "git", *args safe_system "git", *args
formula_count = tap.formula_files.size formula_count = tap.formula_files.size
puts "Tapped #{formula_count} formula#{plural(formula_count, 'e')} (#{tap.path.abv})" puts "Tapped #{formula_count} formula#{plural(formula_count, "e")} (#{tap.path.abv})"
if !clone_target && tap.private? if !clone_target && tap.private?
puts <<-EOS.undent puts <<-EOS.undent
@ -40,7 +40,7 @@ module Homebrew
end end
# Migrate tapped formulae from symlink-based to directory-based structure. # Migrate tapped formulae from symlink-based to directory-based structure.
def migrate_taps(options={}) def migrate_taps(options = {})
ignore = HOMEBREW_LIBRARY/"Formula/.gitignore" ignore = HOMEBREW_LIBRARY/"Formula/.gitignore"
return unless ignore.exist? || options.fetch(:force, false) return unless ignore.exist? || options.fetch(:force, false)
(HOMEBREW_LIBRARY/"Formula").children.select(&:symlink?).each(&:unlink) (HOMEBREW_LIBRARY/"Formula").children.select(&:symlink?).each(&:unlink)
@ -49,7 +49,7 @@ module Homebrew
private private
def tap_args(tap_name=ARGV.named.first) def tap_args(tap_name = ARGV.named.first)
tap_name =~ HOMEBREW_TAP_ARGS_REGEX tap_name =~ HOMEBREW_TAP_ARGS_REGEX
raise "Invalid tap name" unless $1 && $3 raise "Invalid tap name" unless $1 && $3
[$1, $3] [$1, $3]

View File

@ -23,19 +23,19 @@
# --ci-upload: Homebrew CI bottle upload. # --ci-upload: Homebrew CI bottle upload.
# --ci-reset-and-update: Homebrew CI repository and tap reset and update. # --ci-reset-and-update: Homebrew CI repository and tap reset and update.
require 'formula' require "formula"
require 'utils' require "utils"
require 'date' require "date"
require 'rexml/document' require "rexml/document"
require 'rexml/xmldecl' require "rexml/xmldecl"
require 'rexml/cdata' require "rexml/cdata"
require 'cmd/tap' require "cmd/tap"
module Homebrew module Homebrew
EMAIL_SUBJECT_FILE = "brew-test-bot.#{MacOS.cat}.email.txt" EMAIL_SUBJECT_FILE = "brew-test-bot.#{MacOS.cat}.email.txt"
BYTES_IN_1_MEGABYTE = 1024*1024 BYTES_IN_1_MEGABYTE = 1024*1024
def homebrew_git_repo tap=nil def homebrew_git_repo(tap = nil)
if tap if tap
user, repo = tap.split "/" user, repo = tap.split "/"
HOMEBREW_LIBRARY/"Taps/#{user}/homebrew-#{repo}" HOMEBREW_LIBRARY/"Taps/#{user}/homebrew-#{repo}"
@ -47,7 +47,7 @@ module Homebrew
class Step class Step
attr_reader :command, :name, :status, :output, :time attr_reader :command, :name, :status, :output, :time
def initialize test, command, options={} def initialize(test, command, options = {})
@test = test @test = test
@category = test.category @category = test.category
@command = command @command = command
@ -92,7 +92,7 @@ module Homebrew
cmd = @command.join(" ") cmd = @command.join(" ")
print "#{Tty.blue}==>#{Tty.white} #{cmd}#{Tty.reset}" print "#{Tty.blue}==>#{Tty.white} #{cmd}#{Tty.reset}"
tabs = (80 - "PASSED".length + 1 - cmd.length) / 8 tabs = (80 - "PASSED".length + 1 - cmd.length) / 8
tabs.times{ print "\t" } tabs.times { print "\t" }
$stdout.flush $stdout.flush
end end
@ -129,8 +129,8 @@ module Homebrew
end end
write.close write.close
while line = read.gets while line = read.gets
puts line if verbose puts line if verbose
@output += line @output += line
end end
ensure ensure
read.close read.close
@ -143,7 +143,7 @@ module Homebrew
if has_output? if has_output?
@output = fix_encoding(@output) @output = fix_encoding(@output)
puts @output if (failed? or @puts_output_on_success) && !verbose puts @output if (failed? || @puts_output_on_success) && !verbose
File.write(log_file_path, @output) if ARGV.include? "--keep-logs" File.write(log_file_path, @output) if ARGV.include? "--keep-logs"
end end
@ -174,7 +174,7 @@ module Homebrew
class Test class Test
attr_reader :log_root, :category, :name, :steps attr_reader :log_root, :category, :name, :steps
def initialize argument, tap=nil def initialize(argument, tap = nil)
@hash = nil @hash = nil
@url = nil @url = nil
@formulae = [] @formulae = []
@ -208,7 +208,7 @@ module Homebrew
end end
def no_args? def no_args?
@hash == 'HEAD' @hash == "HEAD"
end end
def git(*args) def git(*args)
@ -231,23 +231,23 @@ module Homebrew
end end
def download def download
def shorten_revision revision def shorten_revision(revision)
git("rev-parse", "--short", revision).strip git("rev-parse", "--short", revision).strip
end end
def current_sha1 def current_sha1
shorten_revision 'HEAD' shorten_revision "HEAD"
end end
def current_branch def current_branch
git("symbolic-ref", "HEAD").gsub("refs/heads/", "").strip git("symbolic-ref", "HEAD").gsub("refs/heads/", "").strip
end end
def single_commit? start_revision, end_revision def single_commit?(start_revision, end_revision)
git("rev-list", "--count", "#{start_revision}..#{end_revision}").to_i == 1 git("rev-list", "--count", "#{start_revision}..#{end_revision}").to_i == 1
end end
def diff_formulae start_revision, end_revision, path, filter def diff_formulae(start_revision, end_revision, path, filter)
git( git(
"diff-tree", "-r", "--name-only", "--diff-filter=#{filter}", "diff-tree", "-r", "--name-only", "--diff-filter=#{filter}",
start_revision, end_revision, "--", path start_revision, end_revision, "--", path
@ -266,10 +266,10 @@ module Homebrew
@start_branch = current_branch @start_branch = current_branch
# Use Jenkins environment variables if present. # Use Jenkins environment variables if present.
if no_args? and ENV['GIT_PREVIOUS_COMMIT'] and ENV['GIT_COMMIT'] \ if no_args? && ENV["GIT_PREVIOUS_COMMIT"] && ENV["GIT_COMMIT"] \
and not ENV['ghprbPullLink'] && !ENV["ghprbPullLink"]
diff_start_sha1 = shorten_revision ENV['GIT_PREVIOUS_COMMIT'] diff_start_sha1 = shorten_revision ENV["GIT_PREVIOUS_COMMIT"]
diff_end_sha1 = shorten_revision ENV['GIT_COMMIT'] diff_end_sha1 = shorten_revision ENV["GIT_COMMIT"]
brew_update brew_update
elsif @hash elsif @hash
diff_start_sha1 = current_sha1 diff_start_sha1 = current_sha1
@ -280,14 +280,14 @@ module Homebrew
end end
# Handle Jenkins pull request builder plugin. # Handle Jenkins pull request builder plugin.
if ENV['ghprbPullLink'] if ENV["ghprbPullLink"]
@url = ENV['ghprbPullLink'] @url = ENV["ghprbPullLink"]
@hash = nil @hash = nil
end end
if no_args? if no_args?
if diff_start_sha1 == diff_end_sha1 or \ if diff_start_sha1 == diff_end_sha1 || \
single_commit?(diff_start_sha1, diff_end_sha1) single_commit?(diff_start_sha1, diff_end_sha1)
@name = diff_end_sha1 @name = diff_end_sha1
else else
@name = "#{diff_start_sha1}-#{diff_end_sha1}" @name = "#{diff_start_sha1}-#{diff_end_sha1}"
@ -302,8 +302,8 @@ module Homebrew
test "git", "checkout", diff_start_sha1 test "git", "checkout", diff_start_sha1
test "brew", "pull", "--clean", @url test "brew", "pull", "--clean", @url
diff_end_sha1 = current_sha1 diff_end_sha1 = current_sha1
@short_url = @url.gsub('https://github.com/', '') @short_url = @url.gsub("https://github.com/", "")
if @short_url.include? '/commit/' if @short_url.include? "/commit/"
# 7 characters should be enough for a commit (not 40). # 7 characters should be enough for a commit (not 40).
@short_url.gsub!(/(commit\/\w{7}).*/, '\1') @short_url.gsub!(/(commit\/\w{7}).*/, '\1')
@name = @short_url @name = @short_url
@ -319,7 +319,7 @@ module Homebrew
FileUtils.mkdir_p @log_root FileUtils.mkdir_p @log_root
return unless diff_start_sha1 != diff_end_sha1 return unless diff_start_sha1 != diff_end_sha1
return if @url and not steps.last.passed? return if @url && !steps.last.passed?
if @tap if @tap
formula_path = %w[Formula HomebrewFormula].find { |dir| (@repository/dir).directory? } || "" formula_path = %w[Formula HomebrewFormula].find { |dir| (@repository/dir).directory? } || ""
@ -332,11 +332,11 @@ module Homebrew
@formulae += @added_formulae + @modified_formula @formulae += @added_formulae + @modified_formula
end end
def skip formula_name def skip(formula_name)
puts "#{Tty.blue}==>#{Tty.white} SKIPPING: #{formula_name}#{Tty.reset}" puts "#{Tty.blue}==>#{Tty.white} SKIPPING: #{formula_name}#{Tty.reset}"
end end
def satisfied_requirements? formula, spec, dependency=nil def satisfied_requirements?(formula, spec, dependency = nil)
requirements = formula.send(spec).requirements requirements = formula.send(spec).requirements
unsatisfied_requirements = requirements.reject do |requirement| unsatisfied_requirements = requirements.reject do |requirement|
@ -370,7 +370,7 @@ module Homebrew
test "brew", "config" test "brew", "config"
end end
def formula formula_name def formula(formula_name)
@category = "#{__method__}.#{formula_name}" @category = "#{__method__}.#{formula_name}"
canonical_formula_name = if @tap canonical_formula_name = if @tap
@ -384,7 +384,7 @@ module Homebrew
formula = Formulary.factory(canonical_formula_name) formula = Formulary.factory(canonical_formula_name)
formula.conflicts.map { |c| Formulary.factory(c.name) }. formula.conflicts.map { |c| Formulary.factory(c.name) }.
select { |f| f.installed? }.each do |conflict| select(&:installed?).each do |conflict|
test "brew", "unlink", conflict.name test "brew", "unlink", conflict.name
end end
@ -402,7 +402,7 @@ module Homebrew
return unless satisfied_requirements?(formula, :devel) return unless satisfied_requirements?(formula, :devel)
end end
if formula.devel && !ARGV.include?('--HEAD') if formula.devel && !ARGV.include?("--HEAD")
deps |= formula.devel.deps.to_a deps |= formula.devel.deps.to_a
reqs |= formula.devel.requirements.to_a reqs |= formula.devel.requirements.to_a
end end
@ -448,8 +448,8 @@ module Homebrew
(installed & dependencies).each do |installed_dependency| (installed & dependencies).each do |installed_dependency|
installed_dependency_formula = Formulary.factory(installed_dependency) installed_dependency_formula = Formulary.factory(installed_dependency)
if installed_dependency_formula.installed? && if installed_dependency_formula.installed? &&
!installed_dependency_formula.keg_only? && !installed_dependency_formula.keg_only? &&
!installed_dependency_formula.linked_keg.exist? !installed_dependency_formula.linked_keg.exist?
test "brew", "link", installed_dependency test "brew", "link", installed_dependency
end end
end end
@ -466,7 +466,7 @@ module Homebrew
dependents = Utils.popen_read("brew", "uses", "--skip-build", "--skip-optional", canonical_formula_name).split("\n") dependents = Utils.popen_read("brew", "uses", "--skip-build", "--skip-optional", canonical_formula_name).split("\n")
dependents -= @formulae dependents -= @formulae
dependents = dependents.map {|d| Formulary.factory(d)} dependents = dependents.map { |d| Formulary.factory(d) }
testable_dependents = dependents.select { |d| d.test_defined? && d.bottled? } testable_dependents = dependents.select { |d| d.test_defined? && d.bottled? }
@ -507,12 +507,12 @@ module Homebrew
audit_args << "--strict" << "--online" if @added_formulae.include? formula_name audit_args << "--strict" << "--online" if @added_formulae.include? formula_name
test "brew", "audit", *audit_args test "brew", "audit", *audit_args
if install_passed if install_passed
if formula.stable? && !ARGV.include?('--no-bottle') if formula.stable? && !ARGV.include?("--no-bottle")
bottle_args = ["--verbose", "--rb", canonical_formula_name] bottle_args = ["--verbose", "--rb", canonical_formula_name]
bottle_args << { :puts_output_on_success => true } bottle_args << { :puts_output_on_success => true }
test "brew", "bottle", *bottle_args test "brew", "bottle", *bottle_args
bottle_step = steps.last bottle_step = steps.last
if bottle_step.passed? and bottle_step.has_output? if bottle_step.passed? && bottle_step.has_output?
bottle_filename = bottle_filename =
bottle_step.output.gsub(/.*(\.\/\S+#{bottle_native_regex}).*/m, '\1') bottle_step.output.gsub(/.*(\.\/\S+#{bottle_native_regex}).*/m, '\1')
test "brew", "uninstall", "--force", canonical_formula_name test "brew", "uninstall", "--force", canonical_formula_name
@ -528,7 +528,7 @@ module Homebrew
unless dependent.installed? unless dependent.installed?
test "brew", "fetch", "--retry", dependent.name test "brew", "fetch", "--retry", dependent.name
next if steps.last.failed? next if steps.last.failed?
conflicts = dependent.conflicts.map { |c| Formulary.factory(c.name) }.select { |f| f.installed? } conflicts = dependent.conflicts.map { |c| Formulary.factory(c.name) }.select(&:installed?)
conflicts.each do |conflict| conflicts.each do |conflict|
test "brew", "unlink", conflict.name test "brew", "unlink", conflict.name
end end
@ -542,7 +542,7 @@ module Homebrew
test "brew", "uninstall", "--force", canonical_formula_name test "brew", "uninstall", "--force", canonical_formula_name
end end
if formula.devel && formula.stable? && !ARGV.include?('--HEAD') \ if formula.devel && formula.stable? && !ARGV.include?("--HEAD") \
&& satisfied_requirements?(formula, :devel) && satisfied_requirements?(formula, :devel)
test "brew", "fetch", "--retry", "--devel", *formula_fetch_options test "brew", "fetch", "--retry", "--devel", *formula_fetch_options
run_as_not_developer { test "brew", "install", "--devel", "--verbose", canonical_formula_name } run_as_not_developer { test "brew", "install", "--devel", "--verbose", canonical_formula_name }
@ -568,7 +568,7 @@ module Homebrew
def cleanup_before def cleanup_before
@category = __method__ @category = __method__
return unless ARGV.include? '--cleanup' return unless ARGV.include? "--cleanup"
git "stash" git "stash"
git "am", "--abort" git "am", "--abort"
git "rebase", "--abort" git "rebase", "--abort"
@ -576,25 +576,25 @@ module Homebrew
git "checkout", "-f", "master" git "checkout", "-f", "master"
git "clean", "-ffdx" git "clean", "-ffdx"
pr_locks = "#{HOMEBREW_REPOSITORY}/.git/refs/remotes/*/pr/*/*.lock" pr_locks = "#{HOMEBREW_REPOSITORY}/.git/refs/remotes/*/pr/*/*.lock"
Dir.glob(pr_locks) {|lock| FileUtils.rm_rf lock } Dir.glob(pr_locks) { |lock| FileUtils.rm_rf lock }
end end
def cleanup_after def cleanup_after
@category = __method__ @category = __method__
checkout_args = [] checkout_args = []
if ARGV.include? '--cleanup' if ARGV.include? "--cleanup"
test "git", "clean", "-ffdx" test "git", "clean", "-ffdx"
checkout_args << "-f" checkout_args << "-f"
end end
checkout_args << @start_branch checkout_args << @start_branch
if ARGV.include? '--cleanup' or @url or @hash if ARGV.include?("--cleanup") || @url || @hash
test "git", "checkout", *checkout_args test "git", "checkout", *checkout_args
end end
if ARGV.include? '--cleanup' if ARGV.include? "--cleanup"
test "git", "reset", "--hard" test "git", "reset", "--hard"
git "stash", "pop" git "stash", "pop"
test "brew", "cleanup", "--prune=30" test "brew", "cleanup", "--prune=30"
@ -635,7 +635,7 @@ module Homebrew
end end
end end
changed_formulae = changed_formulae_dependents.sort do |a1,a2| changed_formulae = changed_formulae_dependents.sort do |a1, a2|
a2[1].to_i <=> a1[1].to_i a2[1].to_i <=> a1[1].to_i
end end
changed_formulae.map!(&:first) changed_formulae.map!(&:first)
@ -643,11 +643,11 @@ module Homebrew
changed_formulae + unchanged_formulae changed_formulae + unchanged_formulae
end end
def head_only_tap? formula def head_only_tap?(formula)
formula.head && formula.devel.nil? && formula.stable.nil? && formula.tap == "homebrew/homebrew-head-only" formula.head && formula.devel.nil? && formula.stable.nil? && formula.tap == "homebrew/homebrew-head-only"
end end
def devel_only_tap? formula def devel_only_tap?(formula)
formula.devel && formula.stable.nil? && formula.tap == "homebrew/homebrew-devel-only" formula.devel && formula.stable.nil? && formula.tap == "homebrew/homebrew-devel-only"
end end
@ -665,17 +665,17 @@ module Homebrew
end end
def test_bot def test_bot
tap = ARGV.value('tap') tap = ARGV.value("tap")
if !tap && ENV['UPSTREAM_BOT_PARAMS'] if !tap && ENV["UPSTREAM_BOT_PARAMS"]
bot_argv = ENV['UPSTREAM_BOT_PARAMS'].split " " bot_argv = ENV["UPSTREAM_BOT_PARAMS"].split " "
bot_argv.extend HomebrewArgvExtension bot_argv.extend HomebrewArgvExtension
tap ||= bot_argv.value('tap') tap ||= bot_argv.value("tap")
end end
tap.gsub!(/homebrew\/homebrew-/i, "Homebrew/") if tap tap.gsub!(/homebrew\/homebrew-/i, "Homebrew/") if tap
git_url = ENV['UPSTREAM_GIT_URL'] || ENV['GIT_URL'] git_url = ENV["UPSTREAM_GIT_URL"] || ENV["GIT_URL"]
if !tap && git_url if !tap && git_url
# Also can get tap from Jenkins GIT_URL. # Also can get tap from Jenkins GIT_URL.
url_path = git_url.gsub(%r{^https?://github\.com/}, "").gsub(%r{/$}, "") url_path = git_url.gsub(%r{^https?://github\.com/}, "").gsub(%r{/$}, "")
@ -683,33 +683,33 @@ module Homebrew
tap = "#{$1}/#{$3}" if $1 && $3 tap = "#{$1}/#{$3}" if $1 && $3
end end
if Pathname.pwd == HOMEBREW_PREFIX and ARGV.include? "--cleanup" if Pathname.pwd == HOMEBREW_PREFIX && ARGV.include?("--cleanup")
odie 'cannot use --cleanup from HOMEBREW_PREFIX as it will delete all output.' odie "cannot use --cleanup from HOMEBREW_PREFIX as it will delete all output."
end end
if ARGV.include? "--email" if ARGV.include? "--email"
File.open EMAIL_SUBJECT_FILE, 'w' do |file| File.open EMAIL_SUBJECT_FILE, "w" do |file|
# The file should be written at the end but in case we don't get to that # The file should be written at the end but in case we don't get to that
# point ensure that we have something valid. # point ensure that we have something valid.
file.write "#{MacOS.version}: internal error." file.write "#{MacOS.version}: internal error."
end end
end end
ENV['HOMEBREW_DEVELOPER'] = '1' ENV["HOMEBREW_DEVELOPER"] = "1"
ENV['HOMEBREW_NO_EMOJI'] = '1' ENV["HOMEBREW_NO_EMOJI"] = "1"
if ARGV.include? '--ci-master' or ARGV.include? '--ci-pr' \ if ARGV.include?("--ci-master") || ARGV.include?("--ci-pr") \
or ARGV.include? '--ci-testing' || ARGV.include?("--ci-testing")
ARGV << "--cleanup" if ENV["JENKINS_HOME"] || ENV["TRAVIS_COMMIT"] ARGV << "--cleanup" if ENV["JENKINS_HOME"] || ENV["TRAVIS_COMMIT"]
ARGV << "--junit" << "--local" ARGV << "--junit" << "--local"
end end
if ARGV.include? '--ci-master' if ARGV.include? "--ci-master"
ARGV << '--no-bottle' << '--email' ARGV << "--no-bottle" << "--email"
end end
if ARGV.include? '--local' if ARGV.include? "--local"
ENV['HOME'] = "#{Dir.pwd}/home" ENV["HOME"] = "#{Dir.pwd}/home"
mkdir_p ENV['HOME'] mkdir_p ENV["HOME"]
ENV['HOMEBREW_LOGS'] = "#{Dir.pwd}/logs" ENV["HOMEBREW_LOGS"] = "#{Dir.pwd}/logs"
end end
if ARGV.include? "--ci-reset-and-update" if ARGV.include? "--ci-reset-and-update"
@ -733,10 +733,10 @@ module Homebrew
safe_system "brew", "tap", tap safe_system "brew", "tap", tap
end end
if ARGV.include? '--ci-upload' if ARGV.include? "--ci-upload"
jenkins = ENV['JENKINS_HOME'] jenkins = ENV["JENKINS_HOME"]
job = ENV['UPSTREAM_JOB_NAME'] job = ENV["UPSTREAM_JOB_NAME"]
id = ENV['UPSTREAM_BUILD_ID'] id = ENV["UPSTREAM_BUILD_ID"]
raise "Missing Jenkins variables!" if !jenkins || !job || !id raise "Missing Jenkins variables!" if !jenkins || !job || !id
bintray_user = ENV["BINTRAY_USER"] bintray_user = ENV["BINTRAY_USER"]
@ -751,7 +751,7 @@ module Homebrew
ENV["JENKINS_SERVER_COOKIE"] = nil ENV["JENKINS_SERVER_COOKIE"] = nil
ENV["HUDSON_COOKIE"] = nil ENV["HUDSON_COOKIE"] = nil
ARGV << '--verbose' ARGV << "--verbose"
bottles = Dir["#{jenkins}/jobs/#{job}/configurations/axis-version/*/builds/#{id}/archive/*.bottle*.*"] bottles = Dir["#{jenkins}/jobs/#{job}/configurations/axis-version/*/builds/#{id}/archive/*.bottle*.*"]
return if bottles.empty? return if bottles.empty?
@ -762,8 +762,8 @@ module Homebrew
ENV["GIT_WORK_TREE"] = repository ENV["GIT_WORK_TREE"] = repository
ENV["GIT_DIR"] = "#{ENV["GIT_WORK_TREE"]}/.git" ENV["GIT_DIR"] = "#{ENV["GIT_WORK_TREE"]}/.git"
pr = ENV['UPSTREAM_PULL_REQUEST'] pr = ENV["UPSTREAM_PULL_REQUEST"]
number = ENV['UPSTREAM_BUILD_NUMBER'] number = ENV["UPSTREAM_BUILD_NUMBER"]
system "git am --abort 2>/dev/null" system "git am --abort 2>/dev/null"
system "git rebase --abort 2>/dev/null" system "git rebase --abort 2>/dev/null"
@ -839,7 +839,7 @@ module Homebrew
any_errors = false any_errors = false
if ARGV.named.empty? if ARGV.named.empty?
# With no arguments just build the most recent commit. # With no arguments just build the most recent commit.
head_test = Test.new('HEAD', tap) head_test = Test.new("HEAD", tap)
any_errors = !head_test.run any_errors = !head_test.run
tests << head_test tests << head_test
else else
@ -913,12 +913,12 @@ module Homebrew
end end
if failed_steps.empty? if failed_steps.empty?
email_subject = '' email_subject = ""
else else
email_subject = "#{MacOS.version}: #{failed_steps.join ', '}." email_subject = "#{MacOS.version}: #{failed_steps.join ", "}."
end end
File.open EMAIL_SUBJECT_FILE, 'w' do |file| File.open EMAIL_SUBJECT_FILE, "w" do |file|
file.write email_subject file.write email_subject
end end
end end

View File

@ -4,7 +4,6 @@ require "sandbox"
require "timeout" require "timeout"
module Homebrew module Homebrew
def test def test
raise FormulaUnspecifiedError if ARGV.named.empty? raise FormulaUnspecifiedError if ARGV.named.empty?

View File

@ -1,11 +1,11 @@
require 'keg' require "keg"
require 'formula' require "formula"
module Homebrew module Homebrew
def uninstall def uninstall
raise KegUnspecifiedError if ARGV.named.empty? raise KegUnspecifiedError if ARGV.named.empty?
if not ARGV.force? if !ARGV.force?
ARGV.kegs.each do |keg| ARGV.kegs.each do |keg|
keg.lock do keg.lock do
puts "Uninstalling #{keg}... (#{keg.abv})" puts "Uninstalling #{keg}... (#{keg.abv})"
@ -43,7 +43,7 @@ module Homebrew
puts "Use `brew remove --force #{e.name}` to remove all versions." puts "Use `brew remove --force #{e.name}` to remove all versions."
end end
def rm_pin rack def rm_pin(rack)
Formulary.from_rack(rack).unpin rescue nil Formulary.from_rack(rack).unpin rescue nil
end end
end end

View File

@ -1,5 +1,5 @@
# Unlinks any Applications (.app) found in installed prefixes from /Applications # Unlinks any Applications (.app) found in installed prefixes from /Applications
require 'keg' require "keg"
module Homebrew module Homebrew
def unlinkapps def unlinkapps
@ -23,7 +23,7 @@ module Homebrew
private private
def should_unlink? file def should_unlink?(file)
if ARGV.named.empty? if ARGV.named.empty?
file.match(HOMEBREW_CELLAR) || file.match("#{HOMEBREW_PREFIX}/opt") file.match(HOMEBREW_CELLAR) || file.match("#{HOMEBREW_PREFIX}/opt")
else else

View File

@ -25,12 +25,12 @@ module Homebrew
oh1 "Unpacking #{f.full_name} to: #{stage_dir}" oh1 "Unpacking #{f.full_name} to: #{stage_dir}"
ENV['VERBOSE'] = '1' # show messages about tar ENV["VERBOSE"] = "1" # show messages about tar
f.brew do f.brew do
f.patch if ARGV.flag?("--patch") f.patch if ARGV.flag?("--patch")
cp_r getwd, stage_dir cp_r getwd, stage_dir
end end
ENV['VERBOSE'] = nil ENV["VERBOSE"] = nil
if ARGV.git? if ARGV.git?
ohai "Setting up git repository" ohai "Setting up git repository"

View File

@ -1,4 +1,4 @@
require 'formula' require "formula"
module Homebrew module Homebrew
def unpin def unpin

View File

@ -1,4 +1,4 @@
require 'cmd/tap' # for tap_args require "cmd/tap" # for tap_args
module Homebrew module Homebrew
def untap def untap
@ -13,7 +13,7 @@ module Homebrew
formula_count = tap.formula_files.size formula_count = tap.formula_files.size
tap.path.rmtree tap.path.rmtree
tap.path.dirname.rmdir_if_possible tap.path.dirname.rmdir_if_possible
puts "Untapped #{formula_count} formula#{plural(formula_count, 'e')}" puts "Untapped #{formula_count} formula#{plural(formula_count, "e")}"
end end
end end
end end

View File

@ -1,4 +1,4 @@
require 'cmd/tap' require "cmd/tap"
module Homebrew module Homebrew
def update def update
@ -10,7 +10,7 @@ module Homebrew
end end
# ensure GIT_CONFIG is unset as we need to operate on .git/config # ensure GIT_CONFIG is unset as we need to operate on .git/config
ENV.delete('GIT_CONFIG') ENV.delete("GIT_CONFIG")
cd HOMEBREW_REPOSITORY cd HOMEBREW_REPOSITORY
git_init_if_necessary git_init_if_necessary
@ -36,7 +36,7 @@ module Homebrew
rescue rescue
onoe "Failed to update tap: #{tap}" onoe "Failed to update tap: #{tap}"
else else
report.update(updater.report) do |key, oldval, newval| report.update(updater.report) do |_key, oldval, newval|
oldval.concat(newval) oldval.concat(newval)
end end
end end
@ -48,14 +48,14 @@ module Homebrew
next unless (HOMEBREW_CELLAR/f).exist? next unless (HOMEBREW_CELLAR/f).exist?
migration = TAP_MIGRATIONS[f] migration = TAP_MIGRATIONS[f]
next unless migration next unless migration
tap_user, tap_repo = migration.split '/' tap_user, tap_repo = migration.split "/"
install_tap tap_user, tap_repo install_tap tap_user, tap_repo
end if load_tap_migrations end if load_tap_migrations
if report.empty? if report.empty?
puts "Already up-to-date." puts "Already up-to-date."
else else
puts "Updated Homebrew from #{master_updater.initial_revision[0,8]} to #{master_updater.current_revision[0,8]}." puts "Updated Homebrew from #{master_updater.initial_revision[0, 8]} to #{master_updater.current_revision[0, 8]}."
report.dump report.dump
end end
end end
@ -111,7 +111,7 @@ module Homebrew
end end
def load_tap_migrations def load_tap_migrations
require 'tap_migrations' require "tap_migrations"
rescue LoadError rescue LoadError
false false
end end
@ -125,7 +125,7 @@ class Updater
@stashed = false @stashed = false
end end
def pull!(options={}) def pull!(options = {})
quiet = [] quiet = []
quiet << "--quiet" unless ARGV.verbose? quiet << "--quiet" unless ARGV.verbose?
@ -184,12 +184,13 @@ class Updater
end end
def report def report
map = Hash.new{ |h,k| h[k] = [] } map = Hash.new { |h, k| h[k] = [] }
if initial_revision && initial_revision != current_revision if initial_revision && initial_revision != current_revision
diff.each_line do |line| diff.each_line do |line|
status, *paths = line.split status, *paths = line.split
src, dst = paths.first, paths.last src = paths.first
dst = paths.last
next unless File.extname(dst) == ".rb" next unless File.extname(dst) == ".rb"
next unless paths.any? { |p| File.dirname(p) == formula_directory } next unless paths.any? { |p| File.dirname(p) == formula_directory }
@ -255,7 +256,6 @@ class Updater
end end
end end
class Report class Report
def initialize def initialize
@hash = {} @hash = {}
@ -281,7 +281,7 @@ class Report
dump_formula_report :D, "Deleted Formulae" dump_formula_report :D, "Deleted Formulae"
end end
def select_formula key def select_formula(key)
fetch(key, []).map do |path| fetch(key, []).map do |path|
case path.to_s case path.to_s
when HOMEBREW_TAP_PATH_REGEX when HOMEBREW_TAP_PATH_REGEX
@ -292,7 +292,7 @@ class Report
end.sort end.sort
end end
def dump_formula_report key, title def dump_formula_report(key, title)
formula = select_formula(key) formula = select_formula(key)
unless formula.empty? unless formula.empty?
ohai title ohai title

View File

@ -1,5 +1,5 @@
require 'cmd/install' require "cmd/install"
require 'cmd/outdated' require "cmd/outdated"
module Homebrew module Homebrew
def upgrade def upgrade
@ -29,24 +29,24 @@ module Homebrew
unless outdated.empty? unless outdated.empty?
oh1 "Upgrading #{outdated.length} outdated package#{plural(outdated.length)}, with result:" oh1 "Upgrading #{outdated.length} outdated package#{plural(outdated.length)}, with result:"
puts outdated.map{ |f| "#{f.full_name} #{f.pkg_version}" } * ", " puts outdated.map { |f| "#{f.full_name} #{f.pkg_version}" } * ", "
else else
oh1 "No packages to upgrade" oh1 "No packages to upgrade"
end end
unless upgrade_pinned? || pinned.empty? unless upgrade_pinned? || pinned.empty?
oh1 "Not upgrading #{pinned.length} pinned package#{plural(pinned.length)}:" oh1 "Not upgrading #{pinned.length} pinned package#{plural(pinned.length)}:"
puts pinned.map{ |f| "#{f.full_name} #{f.pkg_version}" } * ", " puts pinned.map { |f| "#{f.full_name} #{f.pkg_version}" } * ", "
end end
outdated.each { |f| upgrade_formula(f) } outdated.each { |f| upgrade_formula(f) }
end end
def upgrade_pinned? def upgrade_pinned?
not ARGV.named.empty? !ARGV.named.empty?
end end
def upgrade_formula f def upgrade_formula(f)
outdated_keg = Keg.new(f.linked_keg.resolved_path) if f.linked_keg.directory? outdated_keg = Keg.new(f.linked_keg.resolved_path) if f.linked_keg.directory?
tab = Tab.for_formula(f) tab = Tab.for_formula(f)
@ -89,7 +89,6 @@ module Homebrew
ofail e ofail e
ensure ensure
# restore previous installation state if build failed # restore previous installation state if build failed
outdated_keg.link if outdated_keg and not f.installed? rescue nil outdated_keg.link if outdated_keg && !f.installed? rescue nil
end end
end end

View File

@ -1,4 +1,4 @@
require 'formula' require "formula"
# `brew uses foo bar` returns formulae that use both foo and bar # `brew uses foo bar` returns formulae that use both foo and bar
# If you want the union, run the command twice and concatenate the results. # If you want the union, run the command twice and concatenate the results.
@ -26,7 +26,7 @@ module Homebrew
Requirement.prune if ignores.any? { |ignore| req.send(ignore) } && !dependent.build.with?(req) Requirement.prune if ignores.any? { |ignore| req.send(ignore) } && !dependent.build.with?(req)
end end
deps.any? { |dep| dep.to_formula.full_name == ff.full_name rescue dep.name == ff.name } || deps.any? { |dep| dep.to_formula.full_name == ff.full_name rescue dep.name == ff.name } ||
reqs.any? { |req| req.name == ff.name || [ff.name, ff.full_name].include?(req.default_formula) } reqs.any? { |req| req.name == ff.name || [ff.name, ff.full_name].include?(req.default_formula) }
else else
deps = f.deps.reject do |dep| deps = f.deps.reject do |dep|
ignores.any? { |ignore| dep.send(ignore) } ignores.any? { |ignore| dep.send(ignore) }
@ -35,7 +35,7 @@ module Homebrew
ignores.any? { |ignore| req.send(ignore) } ignores.any? { |ignore| req.send(ignore) }
end end
deps.any? { |dep| dep.to_formula.full_name == ff.full_name rescue dep.name == ff.name } || deps.any? { |dep| dep.to_formula.full_name == ff.full_name rescue dep.name == ff.name } ||
reqs.any? { |req| req.name == ff.name || [ff.name, ff.full_name].include?(req.default_formula) } reqs.any? { |req| req.name == ff.name || [ff.name, ff.full_name].include?(req.default_formula) }
end end
rescue FormulaUnavailableError rescue FormulaUnavailableError
# Silently ignore this case as we don't care about things used in # Silently ignore this case as we don't care about things used in

View File

@ -1,9 +1,9 @@
require 'compat/fails_with_llvm' require "compat/fails_with_llvm"
require 'compat/formula' require "compat/formula"
require 'compat/formula_specialties' require "compat/formula_specialties"
require 'compat/hardware' require "compat/hardware"
require 'compat/macos' require "compat/macos"
require 'compat/md5' require "compat/md5"
require 'compat/requirements' require "compat/requirements"
require 'compat/version' require "compat/version"
require 'compat/download_strategy' require "compat/download_strategy"

View File

@ -1,10 +1,10 @@
class Formula class Formula
def fails_with_llvm msg=nil, data=nil def fails_with_llvm(_msg = nil, _data = nil)
opoo "Calling fails_with_llvm in the install method is deprecated" opoo "Calling fails_with_llvm in the install method is deprecated"
puts "Use the fails_with DSL instead" puts "Use the fails_with DSL instead"
end end
def self.fails_with_llvm msg=nil, data={} def self.fails_with_llvm(msg = nil, data = {})
data = msg if Hash === msg data = msg if Hash === msg
fails_with(:llvm) { build(data.delete(:build).to_i) } fails_with(:llvm) { build(data.delete(:build).to_i) }
end end

View File

@ -16,7 +16,7 @@ class Formula
"-DCMAKE_INSTALL_PREFIX='#{prefix}' -DCMAKE_BUILD_TYPE=None -DCMAKE_FIND_FRAMEWORK=LAST -Wno-dev" "-DCMAKE_INSTALL_PREFIX='#{prefix}' -DCMAKE_BUILD_TYPE=None -DCMAKE_FIND_FRAMEWORK=LAST -Wno-dev"
end end
def cxxstdlib_check check_type def cxxstdlib_check(check_type)
self.class.cxxstdlib_check check_type self.class.cxxstdlib_check check_type
end end
@ -44,16 +44,18 @@ class Formula
define_method(:require_universal_deps?) { true } define_method(:require_universal_deps?) { true }
end end
def self.path name def self.path(name)
Formulary.core_path(name) Formulary.core_path(name)
end end
DATA = :DATA DATA = :DATA
def patches; {} end def patches
{}
end
def python(options={}, &block) def python(_options = {}, &block)
opoo 'Formula#python is deprecated and will go away shortly.' opoo "Formula#python is deprecated and will go away shortly."
block.call if block_given? block.call if block_given?
PythonRequirement.new PythonRequirement.new
end end

View File

@ -3,7 +3,7 @@
# See chcase for an example # See chcase for an example
class ScriptFileFormula < Formula class ScriptFileFormula < Formula
def install def install
bin.install Dir['*'] bin.install Dir["*"]
end end
end end
@ -21,14 +21,14 @@ class AmazonWebServicesFormula < Formula
# Use this method to peform a standard install for Java-based tools, # Use this method to peform a standard install for Java-based tools,
# keeping the .jars out of HOMEBREW_PREFIX/lib # keeping the .jars out of HOMEBREW_PREFIX/lib
def install def install
rm Dir['bin/*.cmd'] # Remove Windows versions rm Dir["bin/*.cmd"] # Remove Windows versions
libexec.install Dir['*'] libexec.install Dir["*"]
bin.install_symlink Dir["#{libexec}/bin/*"] - ["#{libexec}/bin/service"] bin.install_symlink Dir["#{libexec}/bin/*"] - ["#{libexec}/bin/service"]
end end
alias_method :standard_install, :install alias_method :standard_install, :install
# Use this method to generate standard caveats. # Use this method to generate standard caveats.
def standard_instructions home_name, home_value=libexec def standard_instructions(home_name, home_value = libexec)
<<-EOS.undent <<-EOS.undent
Before you can use these tools you must export some variables to your $SHELL. Before you can use these tools you must export some variables to your $SHELL.

View File

@ -1,7 +1,7 @@
class Hardware class Hardware
class << self class << self
def is_32_bit? def is_32_bit?
not CPU.is_64_bit? !CPU.is_64_bit?
end end
def is_64_bit? def is_64_bit?

View File

@ -1,5 +1,5 @@
class Version class Version
def slice *args def slice(*args)
opoo "Calling slice on versions is deprecated, use: to_s.slice" opoo "Calling slice on versions is deprecated, use: to_s.slice"
to_s.slice(*args) to_s.slice(*args)
end end

View File

@ -5,11 +5,11 @@ module CompilerConstants
"gcc-4.0" => :gcc_4_0, "gcc-4.0" => :gcc_4_0,
"gcc-4.2" => :gcc, "gcc-4.2" => :gcc,
"llvm-gcc" => :llvm, "llvm-gcc" => :llvm,
"clang" => :clang, "clang" => :clang
} }
COMPILERS = COMPILER_SYMBOL_MAP.values + COMPILERS = COMPILER_SYMBOL_MAP.values +
GNU_GCC_VERSIONS.map { |n| "gcc-#{n}" } GNU_GCC_VERSIONS.map { |n| "gcc-#{n}" }
end end
class CompilerFailure class CompilerFailure
@ -23,7 +23,7 @@ class CompilerFailure
# The cause is no longer used so we need not hold a reference to the string # The cause is no longer used so we need not hold a reference to the string
def cause(_); end def cause(_); end
def self.for_standard standard def self.for_standard(standard)
COLLECTIONS.fetch(standard) do COLLECTIONS.fetch(standard) do
raise ArgumentError, "\"#{standard}\" is not a recognized standard" raise ArgumentError, "\"#{standard}\" is not a recognized standard"
end end
@ -66,12 +66,12 @@ class CompilerFailure
create(:gcc => "4.3"), create(:gcc => "4.3"),
create(:gcc => "4.4"), create(:gcc => "4.4"),
create(:gcc => "4.5"), create(:gcc => "4.5"),
create(:gcc => "4.6"), create(:gcc => "4.6")
], ],
:openmp => [ :openmp => [
create(:clang), create(:clang),
create(:llvm), create(:llvm)
], ]
} }
end end
@ -84,10 +84,10 @@ class CompilerSelector
:clang => [:clang, :gcc, :llvm, :gnu, :gcc_4_0], :clang => [:clang, :gcc, :llvm, :gnu, :gcc_4_0],
:gcc => [:gcc, :llvm, :gnu, :clang, :gcc_4_0], :gcc => [:gcc, :llvm, :gnu, :clang, :gcc_4_0],
:llvm => [:llvm, :gcc, :gnu, :clang, :gcc_4_0], :llvm => [:llvm, :gcc, :gnu, :clang, :gcc_4_0],
:gcc_4_0 => [:gcc_4_0, :gcc, :llvm, :gnu, :clang], :gcc_4_0 => [:gcc_4_0, :gcc, :llvm, :gnu, :clang]
} }
def self.select_for(formula, compilers=self.compilers) def self.select_for(formula, compilers = self.compilers)
new(formula, MacOS, compilers).compiler new(formula, MacOS, compilers).compiler
end end

View File

@ -26,8 +26,8 @@ undef cache
# Where brews installed via URL are cached # Where brews installed via URL are cached
HOMEBREW_CACHE_FORMULA = HOMEBREW_CACHE+"Formula" HOMEBREW_CACHE_FORMULA = HOMEBREW_CACHE+"Formula"
if not defined? HOMEBREW_BREW_FILE unless defined? HOMEBREW_BREW_FILE
HOMEBREW_BREW_FILE = ENV['HOMEBREW_BREW_FILE'] || which('brew').to_s HOMEBREW_BREW_FILE = ENV["HOMEBREW_BREW_FILE"] || which("brew").to_s
end end
# Where we link under # Where we link under
@ -47,11 +47,11 @@ else
HOMEBREW_REPOSITORY+"Cellar" HOMEBREW_REPOSITORY+"Cellar"
end end
HOMEBREW_LOGS = Pathname.new(ENV['HOMEBREW_LOGS'] || '~/Library/Logs/Homebrew/').expand_path HOMEBREW_LOGS = Pathname.new(ENV["HOMEBREW_LOGS"] || "~/Library/Logs/Homebrew/").expand_path
HOMEBREW_TEMP = Pathname.new(ENV.fetch('HOMEBREW_TEMP', '/tmp')) HOMEBREW_TEMP = Pathname.new(ENV.fetch("HOMEBREW_TEMP", "/tmp"))
if not defined? HOMEBREW_LIBRARY_PATH unless defined? HOMEBREW_LIBRARY_PATH
HOMEBREW_LIBRARY_PATH = Pathname.new(__FILE__).realpath.parent.join("Homebrew") HOMEBREW_LIBRARY_PATH = Pathname.new(__FILE__).realpath.parent.join("Homebrew")
end end

View File

@ -59,14 +59,14 @@ class CxxStdlib
next if dep.build? next if dep.build?
dep_stdlib = Tab.for_formula(dep.to_formula).cxxstdlib dep_stdlib = Tab.for_formula(dep.to_formula).cxxstdlib
if !compatible_with? dep_stdlib unless compatible_with? dep_stdlib
raise CompatibilityError.new(formula, dep, dep_stdlib) raise CompatibilityError.new(formula, dep, dep_stdlib)
end end
end end
end end
def type_string def type_string
type.to_s.gsub(/cxx$/, 'c++') type.to_s.gsub(/cxx$/, "c++")
end end
def inspect def inspect

View File

@ -85,8 +85,8 @@ module Debrew
@active @active
end end
def self.debugged_exceptions class << self
@debugged_exceptions attr_reader :debugged_exceptions
end end
def self.debrew def self.debrew

View File

@ -1,4 +1,4 @@
require 'irb' require "irb"
module IRB module IRB
@setup_done = false @setup_done = false

View File

@ -1,4 +1,4 @@
require 'options' require "options"
module Dependable module Dependable
RESERVED_TAGS = [:build, :optional, :recommended, :run] RESERVED_TAGS = [:build, :optional, :recommended, :run]

View File

@ -1,4 +1,4 @@
require 'dependable' require "dependable"
# A dependency on another Homebrew formula. # A dependency on another Homebrew formula.
class Dependency class Dependency
@ -8,7 +8,7 @@ class Dependency
DEFAULT_ENV_PROC = proc {} DEFAULT_ENV_PROC = proc {}
def initialize(name, tags=[], env_proc=DEFAULT_ENV_PROC, option_name=name) def initialize(name, tags = [], env_proc = DEFAULT_ENV_PROC, option_name = name)
@name = name @name = name
@tags = tags @tags = tags
@env_proc = env_proc @env_proc = env_proc
@ -70,11 +70,11 @@ class Dependency
# the list. # the list.
# The default filter, which is applied when a block is not given, omits # The default filter, which is applied when a block is not given, omits
# optionals and recommendeds based on what the dependent has asked for. # optionals and recommendeds based on what the dependent has asked for.
def expand(dependent, deps=dependent.deps, &block) def expand(dependent, deps = dependent.deps, &block)
expanded_deps = [] expanded_deps = []
deps.each do |dep| deps.each do |dep|
# FIXME don't hide cyclic dependencies # FIXME: don't hide cyclic dependencies
next if dependent.name == dep.name next if dependent.name == dep.name
case action(dependent, dep, &block) case action(dependent, dep, &block)
@ -93,7 +93,7 @@ class Dependency
merge_repeats(expanded_deps) merge_repeats(expanded_deps)
end end
def action(dependent, dep, &block) def action(dependent, dep, &_block)
catch(:action) do catch(:action) do
if block_given? if block_given?
yield dependent, dep yield dependent, dep
@ -134,7 +134,7 @@ end
class TapDependency < Dependency class TapDependency < Dependency
attr_reader :tap attr_reader :tap
def initialize(name, tags=[], env_proc=DEFAULT_ENV_PROC, option_name=name) def initialize(name, tags = [], env_proc = DEFAULT_ENV_PROC, option_name = name)
@tap, _, option_name = option_name.rpartition "/" @tap, _, option_name = option_name.rpartition "/"
super(name, tags, env_proc, option_name) super(name, tags, env_proc, option_name)
end end

View File

@ -1,9 +1,9 @@
require 'dependency' require "dependency"
require 'dependencies' require "dependencies"
require 'ld64_dependency' require "ld64_dependency"
require 'requirement' require "requirement"
require 'requirements' require "requirements"
require 'set' require "set"
## A dependency is a formula that another formula needs to install. ## A dependency is a formula that another formula needs to install.
## A requirement is something other than a formula that another formula ## A requirement is something other than a formula that another formula
@ -177,10 +177,10 @@ class DependencyCollector
def parse_url_spec(url, tags) def parse_url_spec(url, tags)
case File.extname(url) case File.extname(url)
when '.xz' then Dependency.new('xz', tags) when ".xz" then Dependency.new("xz", tags)
when '.lz' then Dependency.new('lzip', tags) when ".lz" then Dependency.new("lzip", tags)
when '.rar' then Dependency.new('unrar', tags) when ".rar" then Dependency.new("unrar", tags)
when '.7z' then Dependency.new('p7zip', tags) when ".7z" then Dependency.new("p7zip", tags)
end end
end end
end end

View File

@ -1,11 +1,11 @@
require 'utils/json' require "utils/json"
class AbstractDownloadStrategy class AbstractDownloadStrategy
include FileUtils include FileUtils
attr_reader :meta, :name, :version, :resource attr_reader :meta, :name, :version, :resource
def initialize name, resource def initialize(name, resource)
@name = name @name = name
@resource = resource @resource = resource
@url = resource.url @url = resource.url
@ -32,7 +32,7 @@ class AbstractDownloadStrategy
rm_rf(cached_location) rm_rf(cached_location)
end end
def expand_safe_system_args args def expand_safe_system_args(args)
args = args.dup args = args.dup
args.each_with_index do |arg, ii| args.each_with_index do |arg, ii|
if arg.is_a? Hash if arg.is_a? Hash
@ -45,11 +45,11 @@ class AbstractDownloadStrategy
end end
end end
# 2 as default because commands are eg. svn up, git pull # 2 as default because commands are eg. svn up, git pull
args.insert(2, '-q') unless ARGV.verbose? args.insert(2, "-q") unless ARGV.verbose?
args args
end end
def quiet_safe_system *args def quiet_safe_system(*args)
safe_system(*expand_safe_system_args(args)) safe_system(*expand_safe_system_args(args))
end end
@ -73,7 +73,7 @@ class AbstractDownloadStrategy
#{HOMEBREW_PREFIX}/bin/cvs #{HOMEBREW_PREFIX}/bin/cvs
#{HOMEBREW_PREFIX}/opt/cvs/bin/cvs #{HOMEBREW_PREFIX}/opt/cvs/bin/cvs
#{which("cvs")} #{which("cvs")}
].find { |p| File.executable? p } ].find { |p| File.executable? p }
end end
def hgpath def hgpath
@ -81,7 +81,7 @@ class AbstractDownloadStrategy
#{which("hg")} #{which("hg")}
#{HOMEBREW_PREFIX}/bin/hg #{HOMEBREW_PREFIX}/bin/hg
#{HOMEBREW_PREFIX}/opt/mercurial/bin/hg #{HOMEBREW_PREFIX}/opt/mercurial/bin/hg
].find { |p| File.executable? p } ].find { |p| File.executable? p }
end end
def bzrpath def bzrpath
@ -89,7 +89,7 @@ class AbstractDownloadStrategy
#{which("bzr")} #{which("bzr")}
#{HOMEBREW_PREFIX}/bin/bzr #{HOMEBREW_PREFIX}/bin/bzr
#{HOMEBREW_PREFIX}/opt/bazaar/bin/bzr #{HOMEBREW_PREFIX}/opt/bazaar/bin/bzr
].find { |p| File.executable? p } ].find { |p| File.executable? p }
end end
def fossilpath def fossilpath
@ -97,14 +97,14 @@ class AbstractDownloadStrategy
#{which("fossil")} #{which("fossil")}
#{HOMEBREW_PREFIX}/bin/fossil #{HOMEBREW_PREFIX}/bin/fossil
#{HOMEBREW_PREFIX}/opt/fossil/bin/fossil #{HOMEBREW_PREFIX}/opt/fossil/bin/fossil
].find { |p| File.executable? p } ].find { |p| File.executable? p }
end end
end end
class VCSDownloadStrategy < AbstractDownloadStrategy class VCSDownloadStrategy < AbstractDownloadStrategy
REF_TYPES = [:tag, :branch, :revisions, :revision].freeze REF_TYPES = [:tag, :branch, :revisions, :revision].freeze
def initialize name, resource def initialize(name, resource)
super super
@ref_type, @ref = extract_ref(meta) @ref_type, @ref = extract_ref(meta)
@revision = meta[:revision] @revision = meta[:revision]
@ -172,7 +172,7 @@ class VCSDownloadStrategy < AbstractDownloadStrategy
def extract_ref(specs) def extract_ref(specs)
key = REF_TYPES.find { |type| specs.key?(type) } key = REF_TYPES.find { |type| specs.key?(type) }
return key, specs[key] [key, specs[key]]
end end
end end
@ -180,7 +180,7 @@ class AbstractFileDownloadStrategy < AbstractDownloadStrategy
def stage def stage
case cached_location.compression_type case cached_location.compression_type
when :zip when :zip
with_system_path { quiet_safe_system 'unzip', {:quiet_flag => '-qq'}, cached_location } with_system_path { quiet_safe_system "unzip", { :quiet_flag => "-qq" }, cached_location }
chdir chdir
when :gzip_only when :gzip_only
with_system_path { buffered_write("gunzip") } with_system_path { buffered_write("gunzip") }
@ -188,7 +188,7 @@ class AbstractFileDownloadStrategy < AbstractDownloadStrategy
with_system_path { buffered_write("bunzip2") } with_system_path { buffered_write("bunzip2") }
when :gzip, :bzip2, :compress, :tar when :gzip, :bzip2, :compress, :tar
# Assume these are also tarred # Assume these are also tarred
with_system_path { safe_system 'tar', 'xf', cached_location } with_system_path { safe_system "tar", "xf", cached_location }
chdir chdir
when :xz when :xz
with_system_path { pipe_to_tar(xzpath) } with_system_path { pipe_to_tar(xzpath) }
@ -201,9 +201,9 @@ class AbstractFileDownloadStrategy < AbstractDownloadStrategy
when :xar when :xar
safe_system "/usr/bin/xar", "-xf", cached_location safe_system "/usr/bin/xar", "-xf", cached_location
when :rar when :rar
quiet_safe_system 'unrar', 'x', {:quiet_flag => '-inul'}, cached_location quiet_safe_system "unrar", "x", { :quiet_flag => "-inul" }, cached_location
when :p7zip when :p7zip
safe_system '7zr', 'x', cached_location safe_system "7zr", "x", cached_location
else else
cp cached_location, basename_without_params cp cached_location, basename_without_params
end end
@ -212,7 +212,7 @@ class AbstractFileDownloadStrategy < AbstractDownloadStrategy
private private
def chdir def chdir
entries = Dir['*'] entries = Dir["*"]
case entries.length case entries.length
when 0 then raise "Empty archive" when 0 then raise "Empty archive"
when 1 then Dir.chdir entries.first rescue nil when 1 then Dir.chdir entries.first rescue nil
@ -275,7 +275,7 @@ class CurlDownloadStrategy < AbstractFileDownloadStrategy
unless urls.empty? unless urls.empty?
ohai "Downloading from #{urls.last}" ohai "Downloading from #{urls.last}"
if !ENV["HOMEBREW_NO_INSECURE_REDIRECT"].nil? && @url.start_with?("https://") && if !ENV["HOMEBREW_NO_INSECURE_REDIRECT"].nil? && @url.start_with?("https://") &&
urls.any? { |u| !u.start_with? "https://" } urls.any? { |u| !u.start_with? "https://" }
raise "HTTPS to HTTP redirect detected & HOMEBREW_NO_INSECURE_REDIRECT is set." raise "HTTPS to HTTP redirect detected & HOMEBREW_NO_INSECURE_REDIRECT is set."
end end
@url = urls.last @url = urls.last
@ -346,7 +346,7 @@ class CurlDownloadStrategy < AbstractFileDownloadStrategy
def curl(*args) def curl(*args)
args.concat _curl_opts args.concat _curl_opts
args << '--connect-timeout' << '5' unless mirrors.empty? args << "--connect-timeout" << "5" unless mirrors.empty?
super super
end end
end end
@ -378,7 +378,7 @@ class CurlApacheMirrorDownloadStrategy < CurlDownloadStrategy
mirrors = Utils::JSON.load(apache_mirrors) mirrors = Utils::JSON.load(apache_mirrors)
path_info = mirrors.fetch("path_info") path_info = mirrors.fetch("path_info")
@url = mirrors.fetch('preferred') + path_info @url = mirrors.fetch("preferred") + path_info
@mirrors |= %W[https://archive.apache.org/dist/#{path_info}] @mirrors |= %W[https://archive.apache.org/dist/#{path_info}]
ohai "Best Mirror #{@url}" ohai "Best Mirror #{@url}"
@ -392,8 +392,8 @@ end
# Query parameters on the URL are converted into POST parameters # Query parameters on the URL are converted into POST parameters
class CurlPostDownloadStrategy < CurlDownloadStrategy class CurlPostDownloadStrategy < CurlDownloadStrategy
def _fetch def _fetch
base_url,data = @url.split('?') base_url, data = @url.split("?")
curl base_url, '-d', data, '-C', downloaded_size, '-o', temporary_path curl base_url, "-d", data, "-C", downloaded_size, "-o", temporary_path
end end
end end
@ -438,20 +438,21 @@ class S3DownloadStrategy < CurlDownloadStrategy
def _fetch def _fetch
# Put the aws gem requirement here (vs top of file) so it's only # Put the aws gem requirement here (vs top of file) so it's only
# a dependency of S3 users, not all Homebrew users # a dependency of S3 users, not all Homebrew users
require 'rubygems' require "rubygems"
begin begin
require 'aws-sdk-v1' require "aws-sdk-v1"
rescue LoadError rescue LoadError
onoe "Install the aws-sdk gem into the gem repo used by brew." onoe "Install the aws-sdk gem into the gem repo used by brew."
raise raise
end end
if @url !~ %r[^https?://+([^.]+).s3.amazonaws.com/+(.+)$] then if @url !~ %r{^https?://+([^.]+).s3.amazonaws.com/+(.+)$}
raise "Bad S3 URL: " + @url raise "Bad S3 URL: " + @url
end end
(bucket,key) = $1,$2 bucket = $1
key = $2
obj = AWS::S3.new().buckets[bucket].objects[key] obj = AWS::S3.new.buckets[bucket].objects[key]
begin begin
s3url = obj.url_for(:get) s3url = obj.url_for(:get)
rescue AWS::Errors::MissingCredentialsError rescue AWS::Errors::MissingCredentialsError
@ -459,7 +460,7 @@ class S3DownloadStrategy < CurlDownloadStrategy
s3url = obj.public_url s3url = obj.public_url
end end
curl s3url, '-C', downloaded_size, '-o', temporary_path curl s3url, "-C", downloaded_size, "-o", temporary_path
end end
end end
@ -470,7 +471,7 @@ class SubversionDownloadStrategy < VCSDownloadStrategy
end end
def fetch def fetch
clear_cache unless @url.chomp("/") == repo_url or quiet_system "svn", "switch", @url, cached_location clear_cache unless @url.chomp("/") == repo_url || quiet_system("svn", "switch", @url, cached_location)
super super
end end
@ -492,16 +493,16 @@ class SubversionDownloadStrategy < VCSDownloadStrategy
end end
end end
def fetch_repo target, url, revision=nil, ignore_externals=false def fetch_repo(target, url, revision = nil, ignore_externals = false)
# Use "svn up" when the repository already exists locally. # Use "svn up" when the repository already exists locally.
# This saves on bandwidth and will have a similar effect to verifying the # This saves on bandwidth and will have a similar effect to verifying the
# cache as it will make any changes to get the right revision. # cache as it will make any changes to get the right revision.
svncommand = target.directory? ? 'up' : 'checkout' svncommand = target.directory? ? "up" : "checkout"
args = ['svn', svncommand] args = ["svn", svncommand]
args << url unless target.directory? args << url unless target.directory?
args << target args << target
args << '-r' << revision if revision args << "-r" << revision if revision
args << '--ignore-externals' if ignore_externals args << "--ignore-externals" if ignore_externals
quiet_safe_system(*args) quiet_safe_system(*args)
end end
@ -537,10 +538,10 @@ class GitDownloadStrategy < VCSDownloadStrategy
%r{git://}, %r{git://},
%r{https://github\.com}, %r{https://github\.com},
%r{http://git\.sv\.gnu\.org}, %r{http://git\.sv\.gnu\.org},
%r{http://llvm\.org}, %r{http://llvm\.org}
] ]
def initialize name, resource def initialize(name, resource)
super super
@ref_type ||= :branch @ref_type ||= :branch
@ref ||= "master" @ref ||= "master"
@ -589,11 +590,11 @@ class GitDownloadStrategy < VCSDownloadStrategy
end end
def has_ref? def has_ref?
quiet_system 'git', '--git-dir', git_dir, 'rev-parse', '-q', '--verify', "#{@ref}^{commit}" quiet_system "git", "--git-dir", git_dir, "rev-parse", "-q", "--verify", "#{@ref}^{commit}"
end end
def current_revision def current_revision
Utils.popen_read('git', '--git-dir', git_dir, 'rev-parse', '-q', '--verify', "HEAD").strip Utils.popen_read("git", "--git-dir", git_dir, "rev-parse", "-q", "--verify", "HEAD").strip
end end
def repo_valid? def repo_valid?
@ -605,11 +606,11 @@ class GitDownloadStrategy < VCSDownloadStrategy
end end
def clone_args def clone_args
args = %w{clone} args = %w[clone]
args << '--depth' << '1' if shallow_clone? args << "--depth" << "1" if shallow_clone?
case @ref_type case @ref_type
when :branch, :tag then args << '--branch' << @ref when :branch, :tag then args << "--branch" << @ref
end end
args << @url << cached_location args << @url << cached_location
@ -617,29 +618,29 @@ class GitDownloadStrategy < VCSDownloadStrategy
def refspec def refspec
case @ref_type case @ref_type
when :branch then "+refs/heads/#@ref:refs/remotes/origin/#@ref" when :branch then "+refs/heads/#{@ref}:refs/remotes/origin/#{@ref}"
when :tag then "+refs/tags/#@ref:refs/tags/#@ref" when :tag then "+refs/tags/#{@ref}:refs/tags/#{@ref}"
else "+refs/heads/master:refs/remotes/origin/master" else "+refs/heads/master:refs/remotes/origin/master"
end end
end end
def config_repo def config_repo
safe_system 'git', 'config', 'remote.origin.url', @url safe_system "git", "config", "remote.origin.url", @url
safe_system 'git', 'config', 'remote.origin.fetch', refspec safe_system "git", "config", "remote.origin.fetch", refspec
end end
def update_repo def update_repo
if @ref_type == :branch || !has_ref? if @ref_type == :branch || !has_ref?
if !shallow_clone? && is_shallow_clone? if !shallow_clone? && is_shallow_clone?
quiet_safe_system 'git', 'fetch', 'origin', '--unshallow' quiet_safe_system "git", "fetch", "origin", "--unshallow"
else else
quiet_safe_system 'git', 'fetch', 'origin' quiet_safe_system "git", "fetch", "origin"
end end
end end
end end
def clone_repo def clone_repo
safe_system 'git', *clone_args safe_system "git", *clone_args
cached_location.cd do cached_location.cd do
safe_system "git", "config", "homebrew.cacheversion", cache_version safe_system "git", "config", "homebrew.cacheversion", cache_version
update_submodules if submodules? update_submodules if submodules?
@ -652,15 +653,15 @@ class GitDownloadStrategy < VCSDownloadStrategy
def reset_args def reset_args
ref = case @ref_type ref = case @ref_type
when :branch then "origin/#@ref" when :branch then "origin/#{@ref}"
when :revision, :tag then @ref when :revision, :tag then @ref
end end
%W{reset --hard #{ref}} %W[reset --hard #{ref}]
end end
def reset def reset
quiet_safe_system 'git', *reset_args quiet_safe_system "git", *reset_args
end end
def update_submodules def update_submodules
@ -672,11 +673,11 @@ end
class CVSDownloadStrategy < VCSDownloadStrategy class CVSDownloadStrategy < VCSDownloadStrategy
def initialize(name, resource) def initialize(name, resource)
super super
@url = @url.sub(%r[^cvs://], "") @url = @url.sub(%r{^cvs://}, "")
if meta.key?(:module) if meta.key?(:module)
@module = meta.fetch(:module) @module = meta.fetch(:module)
elsif @url !~ %r[:[^/]+$] elsif @url !~ %r{:[^/]+$}
@module = name @module = name
else else
@module, @url = split_url(@url) @module, @url = split_url(@url)
@ -712,15 +713,15 @@ class CVSDownloadStrategy < VCSDownloadStrategy
def split_url(in_url) def split_url(in_url)
parts = in_url.split(/:/) parts = in_url.split(/:/)
mod=parts.pop mod=parts.pop
url=parts.join(':') url=parts.join(":")
[ mod, url ] [mod, url]
end end
end end
class MercurialDownloadStrategy < VCSDownloadStrategy class MercurialDownloadStrategy < VCSDownloadStrategy
def initialize(name, resource) def initialize(name, resource)
super super
@url = @url.sub(%r[^hg://], "") @url = @url.sub(%r{^hg://}, "")
end end
def stage def stage
@ -728,10 +729,10 @@ class MercurialDownloadStrategy < VCSDownloadStrategy
dst = Dir.getwd dst = Dir.getwd
cached_location.cd do cached_location.cd do
if @ref_type and @ref if @ref_type && @ref
safe_system hgpath, 'archive', '--subrepos', '-y', '-r', @ref, '-t', 'files', dst safe_system hgpath, "archive", "--subrepos", "-y", "-r", @ref, "-t", "files", dst
else else
safe_system hgpath, 'archive', '--subrepos', '-y', '-t', 'files', dst safe_system hgpath, "archive", "--subrepos", "-y", "-t", "files", dst
end end
end end
end end
@ -758,7 +759,7 @@ end
class BazaarDownloadStrategy < VCSDownloadStrategy class BazaarDownloadStrategy < VCSDownloadStrategy
def initialize(name, resource) def initialize(name, resource)
super super
@url = @url.sub(%r[^bzr://], "") @url = @url.sub(%r{^bzr://}, "")
end end
def stage def stage
@ -791,7 +792,7 @@ end
class FossilDownloadStrategy < VCSDownloadStrategy class FossilDownloadStrategy < VCSDownloadStrategy
def initialize(name, resource) def initialize(name, resource)
super super
@url = @url.sub(%r[^fossil://], "") @url = @url.sub(%r{^fossil://}, "")
end end
def stage def stage
@ -814,15 +815,14 @@ class FossilDownloadStrategy < VCSDownloadStrategy
def update def update
safe_system fossilpath, "pull", "-R", cached_location safe_system fossilpath, "pull", "-R", cached_location
end end
end end
class DownloadStrategyDetector class DownloadStrategyDetector
def self.detect(url, strategy=nil) def self.detect(url, strategy = nil)
if strategy.nil? if strategy.nil?
detect_from_url(url) detect_from_url(url)
elsif Class === strategy && strategy < AbstractDownloadStrategy elsif Class === strategy && strategy < AbstractDownloadStrategy
strategy strategy
elsif Symbol === strategy elsif Symbol === strategy
detect_from_symbol(strategy) detect_from_symbol(strategy)
else else
@ -833,25 +833,25 @@ class DownloadStrategyDetector
def self.detect_from_url(url) def self.detect_from_url(url)
case url case url
when %r[^https?://.+\.git$], %r[^git://] when %r{^https?://.+\.git$}, %r{^git://}
GitDownloadStrategy GitDownloadStrategy
when %r[^https?://www\.apache\.org/dyn/closer\.cgi] when %r{^https?://www\.apache\.org/dyn/closer\.cgi}
CurlApacheMirrorDownloadStrategy CurlApacheMirrorDownloadStrategy
when %r[^https?://(.+?\.)?googlecode\.com/svn], %r[^https?://svn\.], %r[^svn://], %r[^https?://(.+?\.)?sourceforge\.net/svnroot/] when %r{^https?://(.+?\.)?googlecode\.com/svn}, %r{^https?://svn\.}, %r{^svn://}, %r{^https?://(.+?\.)?sourceforge\.net/svnroot/}
SubversionDownloadStrategy SubversionDownloadStrategy
when %r[^cvs://] when %r{^cvs://}
CVSDownloadStrategy CVSDownloadStrategy
when %r[^https?://(.+?\.)?googlecode\.com/hg] when %r{^https?://(.+?\.)?googlecode\.com/hg}
MercurialDownloadStrategy MercurialDownloadStrategy
when %r[^hg://] when %r{^hg://}
MercurialDownloadStrategy MercurialDownloadStrategy
when %r[^bzr://] when %r{^bzr://}
BazaarDownloadStrategy BazaarDownloadStrategy
when %r[^fossil://] when %r{^fossil://}
FossilDownloadStrategy FossilDownloadStrategy
when %r[^http://svn\.apache\.org/repos/], %r[^svn\+http://] when %r{^http://svn\.apache\.org/repos/}, %r{^svn\+http://}
SubversionDownloadStrategy SubversionDownloadStrategy
when %r[^https?://(.+?\.)?sourceforge\.net/hgweb/] when %r{^https?://(.+?\.)?sourceforge\.net/hgweb/}
MercurialDownloadStrategy MercurialDownloadStrategy
else else
CurlDownloadStrategy CurlDownloadStrategy

View File

@ -5,7 +5,7 @@ class KegUnspecifiedError < UsageError; end
class MultipleVersionsInstalledError < RuntimeError class MultipleVersionsInstalledError < RuntimeError
attr_reader :name attr_reader :name
def initialize name def initialize(name)
@name = name @name = name
super "#{name} has multiple installed versions" super "#{name} has multiple installed versions"
end end
@ -16,7 +16,7 @@ class NotAKegError < RuntimeError; end
class NoSuchKegError < RuntimeError class NoSuchKegError < RuntimeError
attr_reader :name attr_reader :name
def initialize name def initialize(name)
@name = name @name = name
super "No such keg: #{HOMEBREW_CELLAR}/#{name}" super "No such keg: #{HOMEBREW_CELLAR}/#{name}"
end end
@ -37,12 +37,12 @@ class FormulaUnavailableError < RuntimeError
attr_reader :name attr_reader :name
attr_accessor :dependent attr_accessor :dependent
def initialize name def initialize(name)
@name = name @name = name
end end
def dependent_s def dependent_s
"(dependency of #{dependent})" if dependent and dependent != name "(dependency of #{dependent})" if dependent && dependent != name
end end
def to_s def to_s
@ -53,7 +53,7 @@ end
class TapFormulaUnavailableError < FormulaUnavailableError class TapFormulaUnavailableError < FormulaUnavailableError
attr_reader :tap, :user, :repo attr_reader :tap, :user, :repo
def initialize tap, name def initialize(tap, name)
@tap = tap @tap = tap
@user = tap.user @user = tap.user
@repo = tap.repo @repo = tap.repo
@ -70,7 +70,7 @@ end
class TapFormulaAmbiguityError < RuntimeError class TapFormulaAmbiguityError < RuntimeError
attr_reader :name, :paths, :formulae attr_reader :name, :paths, :formulae
def initialize name, paths def initialize(name, paths)
@name = name @name = name
@paths = paths @paths = paths
@formulae = paths.map do |path| @formulae = paths.map do |path|
@ -89,7 +89,7 @@ end
class TapUnavailableError < RuntimeError class TapUnavailableError < RuntimeError
attr_reader :name attr_reader :name
def initialize name def initialize(name)
@name = name @name = name
super <<-EOS.undent super <<-EOS.undent
@ -99,7 +99,7 @@ class TapUnavailableError < RuntimeError
end end
class OperationInProgressError < RuntimeError class OperationInProgressError < RuntimeError
def initialize name def initialize(name)
message = <<-EOS.undent message = <<-EOS.undent
Operation already in progress for #{name} Operation already in progress for #{name}
Another active Homebrew process is already using #{name}. Another active Homebrew process is already using #{name}.
@ -149,7 +149,7 @@ class FormulaConflictError < RuntimeError
message << "Cannot install #{formula.full_name} because conflicting formulae are installed.\n" message << "Cannot install #{formula.full_name} because conflicting formulae are installed.\n"
message.concat conflicts.map { |c| conflict_message(c) } << "" message.concat conflicts.map { |c| conflict_message(c) } << ""
message << <<-EOS.undent message << <<-EOS.undent
Please `brew unlink #{conflicts.map(&:name)*' '}` before continuing. Please `brew unlink #{conflicts.map(&:name)*" "}` before continuing.
Unlinking removes a formula's symlinks from #{HOMEBREW_PREFIX}. You can Unlinking removes a formula's symlinks from #{HOMEBREW_PREFIX}. You can
link the formula again after the install finishes. You can --force this link the formula again after the install finishes. You can --force this
@ -166,7 +166,7 @@ class BuildError < RuntimeError
def initialize(formula, cmd, args, env) def initialize(formula, cmd, args, env)
@formula = formula @formula = formula
@env = env @env = env
args = args.map{ |arg| arg.to_s.gsub " ", "\\ " }.join(" ") args = args.map { |arg| arg.to_s.gsub " ", "\\ " }.join(" ")
super "Failed executing: #{cmd} #{args}" super "Failed executing: #{cmd} #{args}"
end end
@ -182,7 +182,7 @@ class BuildError < RuntimeError
end end
def dump def dump
if not ARGV.verbose? if !ARGV.verbose?
puts puts
puts "#{Tty.red}READ THIS#{Tty.reset}: #{Tty.em}#{OS::ISSUES_URL}#{Tty.reset}" puts "#{Tty.red}READ THIS#{Tty.reset}: #{Tty.em}#{OS::ISSUES_URL}#{Tty.reset}"
if formula.tap? if formula.tap?
@ -196,8 +196,8 @@ class BuildError < RuntimeError
end end
end end
else else
require 'cmd/config' require "cmd/config"
require 'cmd/--env' require "cmd/--env"
ohai "Formula" ohai "Formula"
puts "Tap: #{formula.tap}" if formula.tap? puts "Tap: #{formula.tap}" if formula.tap?
@ -210,13 +210,13 @@ class BuildError < RuntimeError
onoe "#{formula.full_name} #{formula.version} did not build" onoe "#{formula.full_name} #{formula.version} did not build"
unless (logs = Dir["#{formula.logs}/*"]).empty? unless (logs = Dir["#{formula.logs}/*"]).empty?
puts "Logs:" puts "Logs:"
puts logs.map{|fn| " #{fn}"}.join("\n") puts logs.map { |fn| " #{fn}" }.join("\n")
end end
end end
puts puts
unless RUBY_VERSION < "1.8.7" || issues.empty? unless RUBY_VERSION < "1.8.7" || issues.empty?
puts "These open issues may also help:" puts "These open issues may also help:"
puts issues.map{ |i| "#{i['title']} #{i['html_url']}" }.join("\n") puts issues.map { |i| "#{i["title"]} #{i["html_url"]}" }.join("\n")
end end
if MacOS.version >= "10.11" if MacOS.version >= "10.11"
@ -253,7 +253,7 @@ end
class CurlDownloadStrategyError < RuntimeError class CurlDownloadStrategyError < RuntimeError
def initialize(url) def initialize(url)
case url case url
when %r[^file://(.+)] when %r{^file://(.+)}
super "File does not exist: #{$1}" super "File does not exist: #{$1}"
else else
super "Download failed: #{url}" super "Download failed: #{url}"
@ -263,7 +263,7 @@ end
# raised by safe_system in utils.rb # raised by safe_system in utils.rb
class ErrorDuringExecution < RuntimeError class ErrorDuringExecution < RuntimeError
def initialize(cmd, args=[]) def initialize(cmd, args = [])
args = args.map { |a| a.to_s.gsub " ", "\\ " }.join(" ") args = args.map { |a| a.to_s.gsub " ", "\\ " }.join(" ")
super "Failure while executing: #{cmd} #{args}" super "Failure while executing: #{cmd} #{args}"
end end
@ -276,7 +276,7 @@ class ChecksumMissingError < ArgumentError; end
class ChecksumMismatchError < RuntimeError class ChecksumMismatchError < RuntimeError
attr_reader :expected, :hash_type attr_reader :expected, :hash_type
def initialize fn, expected, actual def initialize(fn, expected, actual)
@expected = expected @expected = expected
@hash_type = expected.hash_type.to_s.upcase @hash_type = expected.hash_type.to_s.upcase
@ -303,7 +303,7 @@ class DuplicateResourceError < ArgumentError
end end
class BottleVersionMismatchError < RuntimeError class BottleVersionMismatchError < RuntimeError
def initialize bottle_file, bottle_version, formula, formula_version def initialize(bottle_file, bottle_version, formula, formula_version)
super <<-EOS.undent super <<-EOS.undent
Bottle version mismatch Bottle version mismatch
Bottle: #{bottle_file} (#{bottle_version}) Bottle: #{bottle_file} (#{bottle_version})

View File

@ -37,8 +37,8 @@ module HomebrewArgvExtension
end end
def kegs def kegs
require 'keg' require "keg"
require 'formula' require "formula"
@kegs ||= downcased_unique_named.collect do |name| @kegs ||= downcased_unique_named.collect do |name|
canonical_name = Formulary.canonical_name(name) canonical_name = Formulary.canonical_name(name)
rack = HOMEBREW_CELLAR/canonical_name rack = HOMEBREW_CELLAR/canonical_name
@ -72,38 +72,45 @@ module HomebrewArgvExtension
end end
# self documenting perhaps? # self documenting perhaps?
def include? arg def include?(arg)
@n=index arg @n=index arg
end end
def next def next
at @n+1 or raise UsageError at(@n+1) || raise(UsageError)
end end
def value arg def value(arg)
arg = find {|o| o =~ /--#{arg}=(.+)/} arg = find { |o| o =~ /--#{arg}=(.+)/ }
$1 if arg $1 if arg
end end
def force? def force?
flag? '--force' flag? "--force"
end end
def verbose? def verbose?
flag? '--verbose' or !ENV['VERBOSE'].nil? or !ENV['HOMEBREW_VERBOSE'].nil? flag?("--verbose") || !ENV["VERBOSE"].nil? || !ENV["HOMEBREW_VERBOSE"].nil?
end end
def debug? def debug?
flag? '--debug' or !ENV['HOMEBREW_DEBUG'].nil? flag?("--debug") || !ENV["HOMEBREW_DEBUG"].nil?
end end
def quieter? def quieter?
flag? '--quieter' flag? "--quieter"
end end
def interactive? def interactive?
flag? '--interactive' flag? "--interactive"
end end
def one? def one?
flag? '--1' flag? "--1"
end end
def dry_run? def dry_run?
include?('--dry-run') || switch?('n') include?("--dry-run") || switch?("n")
end end
def git? def git?
@ -111,7 +118,7 @@ module HomebrewArgvExtension
end end
def homebrew_developer? def homebrew_developer?
include? '--homebrew-developer' or !ENV['HOMEBREW_DEVELOPER'].nil? include?("--homebrew-developer") || !ENV["HOMEBREW_DEVELOPER"].nil?
end end
def sandbox? def sandbox?
@ -119,46 +126,46 @@ module HomebrewArgvExtension
end end
def ignore_deps? def ignore_deps?
include? '--ignore-dependencies' include? "--ignore-dependencies"
end end
def only_deps? def only_deps?
include? '--only-dependencies' include? "--only-dependencies"
end end
def json def json
value 'json' value "json"
end end
def build_head? def build_head?
include? '--HEAD' include? "--HEAD"
end end
def build_devel? def build_devel?
include? '--devel' include? "--devel"
end end
def build_stable? def build_stable?
not (build_head? or build_devel?) !(build_head? || build_devel?)
end end
def build_universal? def build_universal?
include? '--universal' include? "--universal"
end end
# Request a 32-bit only build. # Request a 32-bit only build.
# This is needed for some use-cases though we prefer to build Universal # This is needed for some use-cases though we prefer to build Universal
# when a 32-bit version is needed. # when a 32-bit version is needed.
def build_32_bit? def build_32_bit?
include? '--32-bit' include? "--32-bit"
end end
def build_bottle? def build_bottle?
include? '--build-bottle' or !ENV['HOMEBREW_BUILD_BOTTLE'].nil? include?("--build-bottle") || !ENV["HOMEBREW_BUILD_BOTTLE"].nil?
end end
def bottle_arch def bottle_arch
arch = value 'bottle-arch' arch = value "bottle-arch"
arch.to_sym if arch arch.to_sym if arch
end end
@ -166,36 +173,36 @@ module HomebrewArgvExtension
switch?("s") || include?("--build-from-source") || !!ENV["HOMEBREW_BUILD_FROM_SOURCE"] switch?("s") || include?("--build-from-source") || !!ENV["HOMEBREW_BUILD_FROM_SOURCE"]
end end
def flag? flag def flag?(flag)
options_only.include?(flag) || switch?(flag[2, 1]) options_only.include?(flag) || switch?(flag[2, 1])
end end
def force_bottle? def force_bottle?
include? '--force-bottle' include? "--force-bottle"
end end
# eg. `foo -ns -i --bar` has three switches, n, s and i # eg. `foo -ns -i --bar` has three switches, n, s and i
def switch? char def switch?(char)
return false if char.length > 1 return false if char.length > 1
options_only.any? { |arg| arg[1, 1] != "-" && arg.include?(char) } options_only.any? { |arg| arg[1, 1] != "-" && arg.include?(char) }
end end
def usage def usage
require 'cmd/help' require "cmd/help"
Homebrew.help_s Homebrew.help_s
end end
def cc def cc
value 'cc' value "cc"
end end
def env def env
value 'env' value "env"
end end
private private
def spec(default=:stable) def spec(default = :stable)
if include?("--HEAD") if include?("--HEAD")
:head :head
elsif include?("--devel") elsif include?("--devel")

View File

@ -1,7 +1,7 @@
require 'hardware' require "hardware"
require 'extend/ENV/shared' require "extend/ENV/shared"
require 'extend/ENV/std' require "extend/ENV/std"
require 'extend/ENV/super' require "extend/ENV/super"
def superenv? def superenv?
Superenv.bin && ARGV.env != "std" Superenv.bin && ARGV.env != "std"

View File

@ -4,8 +4,8 @@ require "compilers"
module SharedEnvExtension module SharedEnvExtension
include CompilerConstants include CompilerConstants
CC_FLAG_VARS = %w{CFLAGS CXXFLAGS OBJCFLAGS OBJCXXFLAGS} CC_FLAG_VARS = %w[CFLAGS CXXFLAGS OBJCFLAGS OBJCXXFLAGS]
FC_FLAG_VARS = %w{FCFLAGS FFLAGS} FC_FLAG_VARS = %w[FCFLAGS FFLAGS]
SANITIZED_VARS = %w[ SANITIZED_VARS = %w[
CDPATH GREP_OPTIONS CLICOLOR_FORCE CDPATH GREP_OPTIONS CLICOLOR_FORCE
@ -18,7 +18,7 @@ module SharedEnvExtension
LIBRARY_PATH LIBRARY_PATH
] ]
def setup_build_environment(formula=nil) def setup_build_environment(formula = nil)
@formula = formula @formula = formula
reset reset
end end
@ -28,20 +28,23 @@ module SharedEnvExtension
end end
def remove_cc_etc def remove_cc_etc
keys = %w{CC CXX OBJC OBJCXX LD CPP CFLAGS CXXFLAGS OBJCFLAGS OBJCXXFLAGS LDFLAGS CPPFLAGS} keys = %w[CC CXX OBJC OBJCXX LD CPP CFLAGS CXXFLAGS OBJCFLAGS OBJCXXFLAGS LDFLAGS CPPFLAGS]
removed = Hash[*keys.map{ |key| [key, self[key]] }.flatten] removed = Hash[*keys.map { |key| [key, self[key]] }.flatten]
keys.each do |key| keys.each do |key|
delete(key) delete(key)
end end
removed removed
end end
def append_to_cflags newflags
def append_to_cflags(newflags)
append(CC_FLAG_VARS, newflags) append(CC_FLAG_VARS, newflags)
end end
def remove_from_cflags val
def remove_from_cflags(val)
remove CC_FLAG_VARS, val remove CC_FLAG_VARS, val
end end
def append keys, value, separator = ' '
def append(keys, value, separator = " ")
value = value.to_s value = value.to_s
Array(keys).each do |key| Array(keys).each do |key|
old = self[key] old = self[key]
@ -52,7 +55,8 @@ module SharedEnvExtension
end end
end end
end end
def prepend keys, value, separator = ' '
def prepend(keys, value, separator = " ")
value = value.to_s value = value.to_s
Array(keys).each do |key| Array(keys).each do |key|
old = self[key] old = self[key]
@ -64,37 +68,63 @@ module SharedEnvExtension
end end
end end
def append_path key, path def append_path(key, path)
append key, path, File::PATH_SEPARATOR if File.directory? path append key, path, File::PATH_SEPARATOR if File.directory? path
end end
def prepend_path key, path def prepend_path(key, path)
prepend key, path, File::PATH_SEPARATOR if File.directory? path prepend key, path, File::PATH_SEPARATOR if File.directory? path
end end
def prepend_create_path key, path def prepend_create_path(key, path)
path = Pathname.new(path) unless path.is_a? Pathname path = Pathname.new(path) unless path.is_a? Pathname
path.mkpath path.mkpath
prepend_path key, path prepend_path key, path
end end
def remove keys, value def remove(keys, value)
Array(keys).each do |key| Array(keys).each do |key|
next unless self[key] next unless self[key]
self[key] = self[key].sub(value, '') self[key] = self[key].sub(value, "")
delete(key) if self[key].empty? delete(key) if self[key].empty?
end if value end if value
end end
def cc; self['CC']; end def cc
def cxx; self['CXX']; end self["CC"]
def cflags; self['CFLAGS']; end end
def cxxflags; self['CXXFLAGS']; end
def cppflags; self['CPPFLAGS']; end def cxx
def ldflags; self['LDFLAGS']; end self["CXX"]
def fc; self['FC']; end end
def fflags; self['FFLAGS']; end
def fcflags; self['FCFLAGS']; end def cflags
self["CFLAGS"]
end
def cxxflags
self["CXXFLAGS"]
end
def cppflags
self["CPPFLAGS"]
end
def ldflags
self["LDFLAGS"]
end
def fc
self["FC"]
end
def fflags
self["FFLAGS"]
end
def fcflags
self["FCFLAGS"]
end
def compiler def compiler
@compiler ||= if (cc = ARGV.cc) @compiler ||= if (cc = ARGV.cc)
@ -133,14 +163,14 @@ module SharedEnvExtension
# See: https://bugs.python.org/issue6848 # See: https://bugs.python.org/issue6848
# Currently only used by aalib in core # Currently only used by aalib in core
def ncurses_define def ncurses_define
append 'CPPFLAGS', "-DNCURSES_OPAQUE=0" append "CPPFLAGS", "-DNCURSES_OPAQUE=0"
end end
def userpaths! def userpaths!
paths = ORIGINAL_PATHS.map { |p| p.realpath.to_s rescue nil } - %w{/usr/X11/bin /opt/X11/bin} paths = ORIGINAL_PATHS.map { |p| p.realpath.to_s rescue nil } - %w[/usr/X11/bin /opt/X11/bin]
self['PATH'] = paths.unshift(*self['PATH'].split(File::PATH_SEPARATOR)).uniq.join(File::PATH_SEPARATOR) self["PATH"] = paths.unshift(*self["PATH"].split(File::PATH_SEPARATOR)).uniq.join(File::PATH_SEPARATOR)
# XXX hot fix to prefer brewed stuff (e.g. python) over /usr/bin. # XXX hot fix to prefer brewed stuff (e.g. python) over /usr/bin.
prepend_path 'PATH', HOMEBREW_PREFIX/'bin' prepend_path "PATH", HOMEBREW_PREFIX/"bin"
end end
def fortran def fortran
@ -149,9 +179,9 @@ module SharedEnvExtension
if fc if fc
ohai "Building with an alternative Fortran compiler" ohai "Building with an alternative Fortran compiler"
puts "This is unsupported." puts "This is unsupported."
self['F77'] ||= fc self["F77"] ||= fc
if ARGV.include? '--default-fortran-flags' if ARGV.include? "--default-fortran-flags"
flags = FC_FLAG_VARS.reject { |key| self[key] } flags = FC_FLAG_VARS.reject { |key| self[key] }
elsif values_at(*FC_FLAG_VARS).compact.empty? elsif values_at(*FC_FLAG_VARS).compact.empty?
opoo <<-EOS.undent opoo <<-EOS.undent
@ -165,14 +195,14 @@ module SharedEnvExtension
end end
else else
if (gfortran = which('gfortran', (HOMEBREW_PREFIX/'bin').to_s)) if (gfortran = which("gfortran", (HOMEBREW_PREFIX/"bin").to_s))
ohai "Using Homebrew-provided fortran compiler." ohai "Using Homebrew-provided fortran compiler."
elsif (gfortran = which('gfortran', ORIGINAL_PATHS.join(File::PATH_SEPARATOR))) elsif (gfortran = which("gfortran", ORIGINAL_PATHS.join(File::PATH_SEPARATOR)))
ohai "Using a fortran compiler found at #{gfortran}." ohai "Using a fortran compiler found at #{gfortran}."
end end
if gfortran if gfortran
puts "This may be changed by setting the FC environment variable." puts "This may be changed by setting the FC environment variable."
self['FC'] = self['F77'] = gfortran self["FC"] = self["F77"] = gfortran
flags = FC_FLAG_VARS flags = FC_FLAG_VARS
end end
end end
@ -183,14 +213,14 @@ module SharedEnvExtension
# ld64 is a newer linker provided for Xcode 2.5 # ld64 is a newer linker provided for Xcode 2.5
def ld64 def ld64
ld64 = Formulary.factory('ld64') ld64 = Formulary.factory("ld64")
self['LD'] = ld64.bin/'ld' self["LD"] = ld64.bin/"ld"
append "LDFLAGS", "-B#{ld64.bin}/" append "LDFLAGS", "-B#{ld64.bin}/"
end end
def gcc_version_formula(name) def gcc_version_formula(name)
version = name[GNU_GCC_REGEXP, 1] version = name[GNU_GCC_REGEXP, 1]
gcc_version_name = "gcc#{version.delete('.')}" gcc_version_name = "gcc#{version.delete(".")}"
gcc = Formulary.factory("gcc") gcc = Formulary.factory("gcc")
if gcc.opt_bin.join(name).exist? if gcc.opt_bin.join(name).exist?
@ -222,11 +252,11 @@ module SharedEnvExtension
private private
def cc= val def cc=(val)
self["CC"] = self["OBJC"] = val.to_s self["CC"] = self["OBJC"] = val.to_s
end end
def cxx= val def cxx=(val)
self["CXX"] = self["OBJCXX"] = val.to_s self["CXX"] = self["OBJCXX"] = val.to_s
end end

View File

@ -1,44 +1,44 @@
require 'hardware' require "hardware"
require 'os/mac' require "os/mac"
require 'extend/ENV/shared' require "extend/ENV/shared"
module Stdenv module Stdenv
include SharedEnvExtension include SharedEnvExtension
SAFE_CFLAGS_FLAGS = "-w -pipe" SAFE_CFLAGS_FLAGS = "-w -pipe"
DEFAULT_FLAGS = '-march=core2 -msse4' DEFAULT_FLAGS = "-march=core2 -msse4"
def self.extended(base) def self.extended(base)
unless ORIGINAL_PATHS.include? HOMEBREW_PREFIX/'bin' unless ORIGINAL_PATHS.include? HOMEBREW_PREFIX/"bin"
base.prepend_path 'PATH', "#{HOMEBREW_PREFIX}/bin" base.prepend_path "PATH", "#{HOMEBREW_PREFIX}/bin"
end end
end end
def setup_build_environment(formula=nil) def setup_build_environment(formula = nil)
super super
if MacOS.version >= :mountain_lion if MacOS.version >= :mountain_lion
# Mountain Lion's sed is stricter, and errors out when # Mountain Lion's sed is stricter, and errors out when
# it encounters files with mixed character sets # it encounters files with mixed character sets
delete('LC_ALL') delete("LC_ALL")
self['LC_CTYPE']="C" self["LC_CTYPE"]="C"
end end
# Set the default pkg-config search path, overriding the built-in paths # Set the default pkg-config search path, overriding the built-in paths
# Anything in PKG_CONFIG_PATH is searched before paths in this variable # Anything in PKG_CONFIG_PATH is searched before paths in this variable
self['PKG_CONFIG_LIBDIR'] = determine_pkg_config_libdir self["PKG_CONFIG_LIBDIR"] = determine_pkg_config_libdir
# make any aclocal stuff installed in Homebrew available # make any aclocal stuff installed in Homebrew available
self['ACLOCAL_PATH'] = "#{HOMEBREW_PREFIX}/share/aclocal" if MacOS::Xcode.provides_autotools? self["ACLOCAL_PATH"] = "#{HOMEBREW_PREFIX}/share/aclocal" if MacOS::Xcode.provides_autotools?
self['MAKEFLAGS'] = "-j#{self.make_jobs}" self["MAKEFLAGS"] = "-j#{make_jobs}"
unless HOMEBREW_PREFIX.to_s == '/usr/local' unless HOMEBREW_PREFIX.to_s == "/usr/local"
# /usr/local is already an -isystem and -L directory so we skip it # /usr/local is already an -isystem and -L directory so we skip it
self['CPPFLAGS'] = "-isystem#{HOMEBREW_PREFIX}/include" self["CPPFLAGS"] = "-isystem#{HOMEBREW_PREFIX}/include"
self['LDFLAGS'] = "-L#{HOMEBREW_PREFIX}/lib" self["LDFLAGS"] = "-L#{HOMEBREW_PREFIX}/lib"
# CMake ignores the variables above # CMake ignores the variables above
self['CMAKE_PREFIX_PATH'] = HOMEBREW_PREFIX.to_s self["CMAKE_PREFIX_PATH"] = HOMEBREW_PREFIX.to_s
end end
frameworks = HOMEBREW_PREFIX.join("Frameworks") frameworks = HOMEBREW_PREFIX.join("Frameworks")
@ -51,7 +51,7 @@ module Stdenv
# Os is the default Apple uses for all its stuff so let's trust them # Os is the default Apple uses for all its stuff so let's trust them
set_cflags "-Os #{SAFE_CFLAGS_FLAGS}" set_cflags "-Os #{SAFE_CFLAGS_FLAGS}"
append 'LDFLAGS', '-Wl,-headerpad_max_install_names' append "LDFLAGS", "-Wl,-headerpad_max_install_names"
send(compiler) send(compiler)
@ -82,13 +82,13 @@ module Stdenv
# This is useful for makefiles with race conditions. # This is useful for makefiles with race conditions.
# When passed a block, MAKEFLAGS is removed only for the duration of the block and is restored after its completion. # When passed a block, MAKEFLAGS is removed only for the duration of the block and is restored after its completion.
def deparallelize def deparallelize
old = self['MAKEFLAGS'] old = self["MAKEFLAGS"]
remove 'MAKEFLAGS', /-j\d+/ remove "MAKEFLAGS", /-j\d+/
if block_given? if block_given?
begin begin
yield yield
ensure ensure
self['MAKEFLAGS'] = old self["MAKEFLAGS"] = old
end end
end end
@ -97,9 +97,9 @@ module Stdenv
alias_method :j1, :deparallelize alias_method :j1, :deparallelize
# These methods are no-ops for compatibility. # These methods are no-ops for compatibility.
%w{fast O4 Og}.each { |opt| define_method(opt) {} } %w[fast O4 Og].each { |opt| define_method(opt) {} }
%w{O3 O2 O1 O0 Os}.each do |opt| %w[O3 O2 O1 O0 Os].each do |opt|
define_method opt do define_method opt do
remove_from_cflags(/-O./) remove_from_cflags(/-O./)
append_to_cflags "-#{opt}" append_to_cflags "-#{opt}"
@ -118,7 +118,7 @@ module Stdenv
def gcc_4_0 def gcc_4_0
super super
set_cpu_cflags '-march=nocona -mssse3' set_cpu_cflags "-march=nocona -mssse3"
end end
alias_method :gcc_4_0_1, :gcc_4_0 alias_method :gcc_4_0_1, :gcc_4_0
@ -149,53 +149,53 @@ module Stdenv
set_cpu_cflags "-march=native", map set_cpu_cflags "-march=native", map
end end
def remove_macosxsdk version=MacOS.version def remove_macosxsdk(version = MacOS.version)
# Clear all lib and include dirs from CFLAGS, CPPFLAGS, LDFLAGS that were # Clear all lib and include dirs from CFLAGS, CPPFLAGS, LDFLAGS that were
# previously added by macosxsdk # previously added by macosxsdk
version = version.to_s version = version.to_s
remove_from_cflags(/ ?-mmacosx-version-min=10\.\d/) remove_from_cflags(/ ?-mmacosx-version-min=10\.\d/)
delete('MACOSX_DEPLOYMENT_TARGET') delete("MACOSX_DEPLOYMENT_TARGET")
delete('CPATH') delete("CPATH")
remove 'LDFLAGS', "-L#{HOMEBREW_PREFIX}/lib" remove "LDFLAGS", "-L#{HOMEBREW_PREFIX}/lib"
if (sdk = MacOS.sdk_path(version)) && !MacOS::CLT.installed? if (sdk = MacOS.sdk_path(version)) && !MacOS::CLT.installed?
delete('SDKROOT') delete("SDKROOT")
remove_from_cflags "-isysroot #{sdk}" remove_from_cflags "-isysroot #{sdk}"
remove 'CPPFLAGS', "-isysroot #{sdk}" remove "CPPFLAGS", "-isysroot #{sdk}"
remove 'LDFLAGS', "-isysroot #{sdk}" remove "LDFLAGS", "-isysroot #{sdk}"
if HOMEBREW_PREFIX.to_s == '/usr/local' if HOMEBREW_PREFIX.to_s == "/usr/local"
delete('CMAKE_PREFIX_PATH') delete("CMAKE_PREFIX_PATH")
else else
# It was set in setup_build_environment, so we have to restore it here. # It was set in setup_build_environment, so we have to restore it here.
self['CMAKE_PREFIX_PATH'] = HOMEBREW_PREFIX.to_s self["CMAKE_PREFIX_PATH"] = HOMEBREW_PREFIX.to_s
end end
remove 'CMAKE_FRAMEWORK_PATH', "#{sdk}/System/Library/Frameworks" remove "CMAKE_FRAMEWORK_PATH", "#{sdk}/System/Library/Frameworks"
end end
end end
def macosxsdk version=MacOS.version def macosxsdk(version = MacOS.version)
return unless OS.mac? return unless OS.mac?
# Sets all needed lib and include dirs to CFLAGS, CPPFLAGS, LDFLAGS. # Sets all needed lib and include dirs to CFLAGS, CPPFLAGS, LDFLAGS.
remove_macosxsdk remove_macosxsdk
version = version.to_s version = version.to_s
append_to_cflags("-mmacosx-version-min=#{version}") append_to_cflags("-mmacosx-version-min=#{version}")
self['MACOSX_DEPLOYMENT_TARGET'] = version self["MACOSX_DEPLOYMENT_TARGET"] = version
self['CPATH'] = "#{HOMEBREW_PREFIX}/include" self["CPATH"] = "#{HOMEBREW_PREFIX}/include"
prepend 'LDFLAGS', "-L#{HOMEBREW_PREFIX}/lib" prepend "LDFLAGS", "-L#{HOMEBREW_PREFIX}/lib"
if (sdk = MacOS.sdk_path(version)) && !MacOS::CLT.installed? if (sdk = MacOS.sdk_path(version)) && !MacOS::CLT.installed?
# Extra setup to support Xcode 4.3+ without CLT. # Extra setup to support Xcode 4.3+ without CLT.
self['SDKROOT'] = sdk self["SDKROOT"] = sdk
# Tell clang/gcc where system include's are: # Tell clang/gcc where system include's are:
append_path 'CPATH', "#{sdk}/usr/include" append_path "CPATH", "#{sdk}/usr/include"
# The -isysroot is needed, too, because of the Frameworks # The -isysroot is needed, too, because of the Frameworks
append_to_cflags "-isysroot #{sdk}" append_to_cflags "-isysroot #{sdk}"
append 'CPPFLAGS', "-isysroot #{sdk}" append "CPPFLAGS", "-isysroot #{sdk}"
# And the linker needs to find sdk/usr/lib # And the linker needs to find sdk/usr/lib
append 'LDFLAGS', "-isysroot #{sdk}" append "LDFLAGS", "-isysroot #{sdk}"
# Needed to build cmake itself and perhaps some cmake projects: # Needed to build cmake itself and perhaps some cmake projects:
append_path 'CMAKE_PREFIX_PATH', "#{sdk}/usr" append_path "CMAKE_PREFIX_PATH", "#{sdk}/usr"
append_path 'CMAKE_FRAMEWORK_PATH', "#{sdk}/System/Library/Frameworks" append_path "CMAKE_FRAMEWORK_PATH", "#{sdk}/System/Library/Frameworks"
end end
end end
@ -203,6 +203,7 @@ module Stdenv
set_cflags "-Os #{SAFE_CFLAGS_FLAGS}" set_cflags "-Os #{SAFE_CFLAGS_FLAGS}"
macosxsdk unless MacOS::CLT.installed? macosxsdk unless MacOS::CLT.installed?
end end
def no_optimization def no_optimization
set_cflags SAFE_CFLAGS_FLAGS set_cflags SAFE_CFLAGS_FLAGS
macosxsdk unless MacOS::CLT.installed? macosxsdk unless MacOS::CLT.installed?
@ -211,10 +212,10 @@ module Stdenv
# Some configure scripts won't find libxml2 without help # Some configure scripts won't find libxml2 without help
def libxml2 def libxml2
if MacOS::CLT.installed? if MacOS::CLT.installed?
append 'CPPFLAGS', '-I/usr/include/libxml2' append "CPPFLAGS", "-I/usr/include/libxml2"
else else
# Use the includes form the sdk # Use the includes form the sdk
append 'CPPFLAGS', "-I#{MacOS.sdk_path}/usr/include/libxml2" append "CPPFLAGS", "-I#{MacOS.sdk_path}/usr/include/libxml2"
end end
end end
@ -238,7 +239,7 @@ module Stdenv
append_path "ACLOCAL_PATH", "#{MacOS::X11.share}/aclocal" append_path "ACLOCAL_PATH", "#{MacOS::X11.share}/aclocal"
if MacOS::XQuartz.provided_by_apple? and not MacOS::CLT.installed? if MacOS::XQuartz.provided_by_apple? && !MacOS::CLT.installed?
append_path "CMAKE_PREFIX_PATH", "#{MacOS.sdk_path}/usr/X11" append_path "CMAKE_PREFIX_PATH", "#{MacOS.sdk_path}/usr/X11"
end end
@ -248,21 +249,22 @@ module Stdenv
# we've seen some packages fail to build when warnings are disabled! # we've seen some packages fail to build when warnings are disabled!
def enable_warnings def enable_warnings
remove_from_cflags '-w' remove_from_cflags "-w"
end end
def m64 def m64
append_to_cflags '-m64' append_to_cflags "-m64"
append 'LDFLAGS', "-arch #{Hardware::CPU.arch_64_bit}" append "LDFLAGS", "-arch #{Hardware::CPU.arch_64_bit}"
end end
def m32 def m32
append_to_cflags '-m32' append_to_cflags "-m32"
append 'LDFLAGS', "-arch #{Hardware::CPU.arch_32_bit}" append "LDFLAGS", "-arch #{Hardware::CPU.arch_32_bit}"
end end
def universal_binary def universal_binary
append_to_cflags Hardware::CPU.universal_archs.as_arch_flags append_to_cflags Hardware::CPU.universal_archs.as_arch_flags
append 'LDFLAGS', Hardware::CPU.universal_archs.as_arch_flags append "LDFLAGS", Hardware::CPU.universal_archs.as_arch_flags
if compiler != :clang && Hardware.is_32_bit? if compiler != :clang && Hardware.is_32_bit?
# Can't mix "-march" for a 32-bit CPU with "-arch x86_64" # Can't mix "-march" for a 32-bit CPU with "-arch x86_64"
@ -272,10 +274,10 @@ module Stdenv
def cxx11 def cxx11
if compiler == :clang if compiler == :clang
append 'CXX', '-std=c++11' append "CXX", "-std=c++11"
append 'CXX', '-stdlib=libc++' append "CXX", "-stdlib=libc++"
elsif compiler =~ /gcc-(4\.(8|9)|5)/ elsif compiler =~ /gcc-(4\.(8|9)|5)/
append 'CXX', '-std=c++11' append "CXX", "-std=c++11"
else else
raise "The selected compiler doesn't support C++11: #{compiler}" raise "The selected compiler doesn't support C++11: #{compiler}"
end end
@ -283,36 +285,36 @@ module Stdenv
def libcxx def libcxx
if compiler == :clang if compiler == :clang
append 'CXX', '-stdlib=libc++' append "CXX", "-stdlib=libc++"
end end
end end
def libstdcxx def libstdcxx
if compiler == :clang if compiler == :clang
append 'CXX', '-stdlib=libstdc++' append "CXX", "-stdlib=libstdc++"
end end
end end
def replace_in_cflags before, after def replace_in_cflags(before, after)
CC_FLAG_VARS.each do |key| CC_FLAG_VARS.each do |key|
self[key] = self[key].sub(before, after) if has_key?(key) self[key] = self[key].sub(before, after) if key?(key)
end end
end end
# Convenience method to set all C compiler flags in one shot. # Convenience method to set all C compiler flags in one shot.
def set_cflags val def set_cflags(val)
CC_FLAG_VARS.each { |key| self[key] = val } CC_FLAG_VARS.each { |key| self[key] = val }
end end
# Sets architecture-specific flags for every environment variable # Sets architecture-specific flags for every environment variable
# given in the list `flags`. # given in the list `flags`.
def set_cpu_flags flags, default=DEFAULT_FLAGS, map=Hardware::CPU.optimization_flags def set_cpu_flags(flags, default = DEFAULT_FLAGS, map = Hardware::CPU.optimization_flags)
cflags =~ %r{(-Xarch_#{Hardware::CPU.arch_32_bit} )-march=} cflags =~ /(-Xarch_#{Hardware::CPU.arch_32_bit} )-march=/
xarch = $1.to_s xarch = $1.to_s
remove flags, %r{(-Xarch_#{Hardware::CPU.arch_32_bit} )?-march=\S*} remove flags, /(-Xarch_#{Hardware::CPU.arch_32_bit} )?-march=\S*/
remove flags, %r{( -Xclang \S+)+} remove flags, /( -Xclang \S+)+/
remove flags, %r{-mssse3} remove flags, /-mssse3/
remove flags, %r{-msse4(\.\d)?} remove flags, /-msse4(\.\d)?/
append flags, xarch unless xarch.empty? append flags, xarch unless xarch.empty?
append flags, map.fetch(effective_arch, default) append flags, map.fetch(effective_arch, default)
end end
@ -330,14 +332,14 @@ module Stdenv
end end
end end
def set_cpu_cflags default=DEFAULT_FLAGS, map=Hardware::CPU.optimization_flags def set_cpu_cflags(default = DEFAULT_FLAGS, map = Hardware::CPU.optimization_flags)
set_cpu_flags CC_FLAG_VARS, default, map set_cpu_flags CC_FLAG_VARS, default, map
end end
def make_jobs def make_jobs
# '-j' requires a positive integral argument # '-j' requires a positive integral argument
if self['HOMEBREW_MAKE_JOBS'].to_i > 0 if self["HOMEBREW_MAKE_JOBS"].to_i > 0
self['HOMEBREW_MAKE_JOBS'].to_i self["HOMEBREW_MAKE_JOBS"].to_i
else else
Hardware::CPU.cores Hardware::CPU.cores
end end

View File

@ -1,5 +1,5 @@
require 'os/mac' require "os/mac"
require 'extend/ENV/shared' require "extend/ENV/shared"
### Why `superenv`? ### Why `superenv`?
# 1) Only specify the environment we need (NO LDFLAGS for cmake) # 1) Only specify the environment we need (NO LDFLAGS for cmake)
@ -34,29 +34,29 @@ module Superenv
delete("as_nl") delete("as_nl")
end end
def setup_build_environment(formula=nil) def setup_build_environment(formula = nil)
super super
send(compiler) send(compiler)
self['MAKEFLAGS'] ||= "-j#{determine_make_jobs}" self["MAKEFLAGS"] ||= "-j#{determine_make_jobs}"
self['PATH'] = determine_path self["PATH"] = determine_path
self['PKG_CONFIG_PATH'] = determine_pkg_config_path self["PKG_CONFIG_PATH"] = determine_pkg_config_path
self['PKG_CONFIG_LIBDIR'] = determine_pkg_config_libdir self["PKG_CONFIG_LIBDIR"] = determine_pkg_config_libdir
self['HOMEBREW_CCCFG'] = determine_cccfg self["HOMEBREW_CCCFG"] = determine_cccfg
self['HOMEBREW_OPTIMIZATION_LEVEL'] = 'Os' self["HOMEBREW_OPTIMIZATION_LEVEL"] = "Os"
self['HOMEBREW_BREW_FILE'] = HOMEBREW_BREW_FILE.to_s self["HOMEBREW_BREW_FILE"] = HOMEBREW_BREW_FILE.to_s
self['HOMEBREW_PREFIX'] = HOMEBREW_PREFIX.to_s self["HOMEBREW_PREFIX"] = HOMEBREW_PREFIX.to_s
self['HOMEBREW_CELLAR'] = HOMEBREW_CELLAR.to_s self["HOMEBREW_CELLAR"] = HOMEBREW_CELLAR.to_s
self['HOMEBREW_TEMP'] = HOMEBREW_TEMP.to_s self["HOMEBREW_TEMP"] = HOMEBREW_TEMP.to_s
self['HOMEBREW_SDKROOT'] = effective_sysroot self["HOMEBREW_SDKROOT"] = effective_sysroot
self['HOMEBREW_OPTFLAGS'] = determine_optflags self["HOMEBREW_OPTFLAGS"] = determine_optflags
self['HOMEBREW_ARCHFLAGS'] = '' self["HOMEBREW_ARCHFLAGS"] = ""
self['CMAKE_PREFIX_PATH'] = determine_cmake_prefix_path self["CMAKE_PREFIX_PATH"] = determine_cmake_prefix_path
self['CMAKE_FRAMEWORK_PATH'] = determine_cmake_frameworks_path self["CMAKE_FRAMEWORK_PATH"] = determine_cmake_frameworks_path
self['CMAKE_INCLUDE_PATH'] = determine_cmake_include_path self["CMAKE_INCLUDE_PATH"] = determine_cmake_include_path
self['CMAKE_LIBRARY_PATH'] = determine_cmake_library_path self["CMAKE_LIBRARY_PATH"] = determine_cmake_library_path
self['ACLOCAL_PATH'] = determine_aclocal_path self["ACLOCAL_PATH"] = determine_aclocal_path
self['M4'] = MacOS.locate("m4") if deps.any? { |d| d.name == "autoconf" } self["M4"] = MacOS.locate("m4") if deps.any? { |d| d.name == "autoconf" }
self["HOMEBREW_ISYSTEM_PATHS"] = determine_isystem_paths self["HOMEBREW_ISYSTEM_PATHS"] = determine_isystem_paths
self["HOMEBREW_INCLUDE_PATHS"] = determine_include_paths self["HOMEBREW_INCLUDE_PATHS"] = determine_include_paths
self["HOMEBREW_LIBRARY_PATHS"] = determine_library_paths self["HOMEBREW_LIBRARY_PATHS"] = determine_library_paths
@ -83,11 +83,11 @@ module Superenv
private private
def cc= val def cc=(val)
self["HOMEBREW_CC"] = super self["HOMEBREW_CC"] = super
end end
def cxx= val def cxx=(val)
self["HOMEBREW_CXX"] = super self["HOMEBREW_CXX"] = super
end end
@ -96,7 +96,7 @@ module Superenv
end end
def determine_cxx def determine_cxx
determine_cc.to_s.gsub('gcc', 'g++').gsub('clang', 'clang++') determine_cc.to_s.gsub("gcc", "g++").gsub("clang", "clang++")
end end
def determine_path def determine_path
@ -113,15 +113,15 @@ module Superenv
end end
paths << MacOS::X11.bin.to_s if x11? paths << MacOS::X11.bin.to_s if x11?
paths += %w{/usr/bin /bin /usr/sbin /sbin} paths += %w[/usr/bin /bin /usr/sbin /sbin]
# Homebrew's apple-gcc42 will be outside the PATH in superenv, # Homebrew's apple-gcc42 will be outside the PATH in superenv,
# so xcrun may not be able to find it # so xcrun may not be able to find it
case homebrew_cc case homebrew_cc
when "gcc-4.2" when "gcc-4.2"
begin begin
apple_gcc42 = Formulary.factory('apple-gcc42') apple_gcc42 = Formulary.factory("apple-gcc42")
rescue FormulaUnavailableError rescue FormulaUnavailableError
end end
paths << apple_gcc42.opt_bin.to_s if apple_gcc42 paths << apple_gcc42.opt_bin.to_s if apple_gcc42
when GNU_GCC_REGEXP when GNU_GCC_REGEXP
@ -139,7 +139,7 @@ module Superenv
end end
def determine_pkg_config_libdir def determine_pkg_config_libdir
paths = %W{/usr/lib/pkgconfig #{HOMEBREW_LIBRARY}/ENV/pkgconfig/#{MacOS.version}} paths = %W[/usr/lib/pkgconfig #{HOMEBREW_LIBRARY}/ENV/pkgconfig/#{MacOS.version}]
paths << "#{MacOS::X11.lib}/pkgconfig" << "#{MacOS::X11.share}/pkgconfig" if x11? paths << "#{MacOS::X11.lib}/pkgconfig" << "#{MacOS::X11.share}/pkgconfig" if x11?
paths.to_path_s paths.to_path_s
end end
@ -210,7 +210,7 @@ module Superenv
end end
def determine_make_jobs def determine_make_jobs
if (j = self['HOMEBREW_MAKE_JOBS'].to_i) < 1 if (j = self["HOMEBREW_MAKE_JOBS"].to_i) < 1
Hardware::CPU.cores Hardware::CPU.cores
else else
j j
@ -234,9 +234,9 @@ module Superenv
def determine_cccfg def determine_cccfg
s = "" s = ""
# Fix issue with sed barfing on unicode characters on Mountain Lion # Fix issue with sed barfing on unicode characters on Mountain Lion
s << 's' if MacOS.version >= :mountain_lion s << "s" if MacOS.version >= :mountain_lion
# Fix issue with >= 10.8 apr-1-config having broken paths # Fix issue with >= 10.8 apr-1-config having broken paths
s << 'a' if MacOS.version >= :mountain_lion s << "a" if MacOS.version >= :mountain_lion
s s
end end
@ -246,12 +246,12 @@ module Superenv
# This is useful for makefiles with race conditions. # This is useful for makefiles with race conditions.
# When passed a block, MAKEFLAGS is removed only for the duration of the block and is restored after its completion. # When passed a block, MAKEFLAGS is removed only for the duration of the block and is restored after its completion.
def deparallelize def deparallelize
old = delete('MAKEFLAGS') old = delete("MAKEFLAGS")
if block_given? if block_given?
begin begin
yield yield
ensure ensure
self['MAKEFLAGS'] = old self["MAKEFLAGS"] = old
end end
end end
@ -260,16 +260,16 @@ module Superenv
alias_method :j1, :deparallelize alias_method :j1, :deparallelize
def make_jobs def make_jobs
self['MAKEFLAGS'] =~ /-\w*j(\d)+/ self["MAKEFLAGS"] =~ /-\w*j(\d)+/
[$1.to_i, 1].max [$1.to_i, 1].max
end end
def universal_binary def universal_binary
self['HOMEBREW_ARCHFLAGS'] = Hardware::CPU.universal_archs.as_arch_flags self["HOMEBREW_ARCHFLAGS"] = Hardware::CPU.universal_archs.as_arch_flags
# GCC doesn't accept "-march" for a 32-bit CPU with "-arch x86_64" # GCC doesn't accept "-march" for a 32-bit CPU with "-arch x86_64"
if compiler != :clang && Hardware.is_32_bit? if compiler != :clang && Hardware.is_32_bit?
self['HOMEBREW_OPTFLAGS'] = self['HOMEBREW_OPTFLAGS'].sub( self["HOMEBREW_OPTFLAGS"] = self["HOMEBREW_OPTFLAGS"].sub(
/-march=\S*/, /-march=\S*/,
"-Xarch_#{Hardware::CPU.arch_32_bit} \\0" "-Xarch_#{Hardware::CPU.arch_32_bit} \\0"
) )
@ -291,10 +291,10 @@ module Superenv
def cxx11 def cxx11
case homebrew_cc case homebrew_cc
when "clang" when "clang"
append 'HOMEBREW_CCCFG', "x", '' append "HOMEBREW_CCCFG", "x", ""
append 'HOMEBREW_CCCFG', "g", '' append "HOMEBREW_CCCFG", "g", ""
when /gcc-(4\.(8|9)|5)/ when /gcc-(4\.(8|9)|5)/
append 'HOMEBREW_CCCFG', "x", '' append "HOMEBREW_CCCFG", "x", ""
else else
raise "The selected compiler doesn't support C++11: #{homebrew_cc}" raise "The selected compiler doesn't support C++11: #{homebrew_cc}"
end end
@ -309,32 +309,31 @@ module Superenv
end end
def refurbish_args def refurbish_args
append 'HOMEBREW_CCCFG', "O", '' append "HOMEBREW_CCCFG", "O", ""
end end
%w{O3 O2 O1 O0 Os}.each do |opt| %w[O3 O2 O1 O0 Os].each do |opt|
define_method opt do define_method opt do
self['HOMEBREW_OPTIMIZATION_LEVEL'] = opt self["HOMEBREW_OPTIMIZATION_LEVEL"] = opt
end end
end end
def noop(*args); end def noop(*_args); end
noops = [] noops = []
# These methods are no longer necessary under superenv, but are needed to # These methods are no longer necessary under superenv, but are needed to
# maintain an interface compatible with stdenv. # maintain an interface compatible with stdenv.
noops.concat %w{fast O4 Og libxml2 set_cpu_flags macosxsdk remove_macosxsdk} noops.concat %w[fast O4 Og libxml2 set_cpu_flags macosxsdk remove_macosxsdk]
# These methods provide functionality that has not yet been ported to # These methods provide functionality that has not yet been ported to
# superenv. # superenv.
noops.concat %w{gcc_4_0_1 minimal_optimization no_optimization enable_warnings} noops.concat %w[gcc_4_0_1 minimal_optimization no_optimization enable_warnings]
noops.each { |m| alias_method m, :noop } noops.each { |m| alias_method m, :noop }
end end
class Array class Array
def to_path_s def to_path_s
map(&:to_s).uniq.select{|s| File.directory? s }.join(File::PATH_SEPARATOR).chuzzle map(&:to_s).uniq.select { |s| File.directory? s }.join(File::PATH_SEPARATOR).chuzzle
end end
end end

View File

@ -3,10 +3,9 @@ require "tmpdir"
# We enhance FileUtils to make our Formula code more readable. # We enhance FileUtils to make our Formula code more readable.
module FileUtils module FileUtils
# Create a temporary directory then yield. When the block returns, # Create a temporary directory then yield. When the block returns,
# recursively delete the temporary directory. # recursively delete the temporary directory.
def mktemp(prefix=name) def mktemp(prefix = name)
prev = pwd prev = pwd
tmp = Dir.mktmpdir(prefix, HOMEBREW_TEMP) tmp = Dir.mktmpdir(prefix, HOMEBREW_TEMP)
@ -26,7 +25,7 @@ module FileUtils
# A version of mkdir that also changes to that folder in a block. # A version of mkdir that also changes to that folder in a block.
alias_method :old_mkdir, :mkdir alias_method :old_mkdir, :mkdir
def mkdir name, &block def mkdir(name, &_block)
old_mkdir(name) old_mkdir(name)
if block_given? if block_given?
chdir name do chdir name do
@ -46,8 +45,8 @@ module FileUtils
class Entry_ class Entry_
alias_method :old_copy_metadata, :copy_metadata alias_method :old_copy_metadata, :copy_metadata
def copy_metadata(path) def copy_metadata(path)
st = lstat() st = lstat
if !st.symlink? unless st.symlink?
File.utime st.atime, st.mtime, path File.utime st.atime, st.mtime, path
end end
begin begin
@ -87,20 +86,20 @@ module FileUtils
# Run scons using a Homebrew-installed version, instead of whatever # Run scons using a Homebrew-installed version, instead of whatever
# is in the user's PATH # is in the user's PATH
def scons *args def scons(*args)
system Formulary.factory("scons").opt_bin/"scons", *args system Formulary.factory("scons").opt_bin/"scons", *args
end end
def rake *args def rake(*args)
system RUBY_BIN/'rake', *args system RUBY_BIN/"rake", *args
end end
alias_method :old_ruby, :ruby if method_defined?(:ruby) alias_method :old_ruby, :ruby if method_defined?(:ruby)
def ruby *args def ruby(*args)
system RUBY_PATH, *args system RUBY_PATH, *args
end end
def xcodebuild *args def xcodebuild(*args)
removed = ENV.remove_cc_etc removed = ENV.remove_cc_etc
system "xcodebuild", *args system "xcodebuild", *args
ensure ensure

View File

@ -1,6 +1,6 @@
class Module class Module
def attr_rw(*attrs) def attr_rw(*attrs)
file, line, _ = caller.first.split(":") file, line, = caller.first.split(":")
line = line.to_i line = line.to_i
attrs.each do |attr| attrs.each do |attr|

View File

@ -1,7 +1,7 @@
require 'pathname' require "pathname"
require 'mach' require "mach"
require 'resource' require "resource"
require 'metafiles' require "metafiles"
# we enhance pathname to make our code more readable # we enhance pathname to make our code more readable
class Pathname class Pathname
@ -9,7 +9,7 @@ class Pathname
BOTTLE_EXTNAME_RX = /(\.[a-z0-9_]+\.bottle\.(\d+\.)?tar\.gz)$/ BOTTLE_EXTNAME_RX = /(\.[a-z0-9_]+\.bottle\.(\d+\.)?tar\.gz)$/
def install *sources def install(*sources)
sources.each do |src| sources.each do |src|
case src case src
when Resource when Resource
@ -48,7 +48,7 @@ class Pathname
# https://bugs.ruby-lang.org/issues/7707 # https://bugs.ruby-lang.org/issues/7707
# In that case, use the system "mv" command. # In that case, use the system "mv" command.
if src.symlink? if src.symlink?
raise unless Kernel.system 'mv', src, dst raise unless Kernel.system "mv", src, dst
else else
FileUtils.mv src, dst FileUtils.mv src, dst
end end
@ -56,7 +56,7 @@ class Pathname
private :install_p private :install_p
# Creates symlinks to sources in this folder. # Creates symlinks to sources in this folder.
def install_symlink *sources def install_symlink(*sources)
sources.each do |src| sources.each do |src|
case src case src
when Array when Array
@ -80,7 +80,7 @@ class Pathname
# we assume this pathname object is a file obviously # we assume this pathname object is a file obviously
alias_method :old_write, :write if method_defined?(:write) alias_method :old_write, :write if method_defined?(:write)
def write(content, *open_args) def write(content, *open_args)
raise "Will not overwrite #{to_s}" if exist? raise "Will not overwrite #{self}" if exist?
dirname.mkpath dirname.mkpath
open("w", *open_args) { |f| f.write(content) } open("w", *open_args) { |f| f.write(content) }
end end
@ -94,7 +94,7 @@ class Pathname
end unless method_defined?(:binread) end unless method_defined?(:binread)
# NOTE always overwrites # NOTE always overwrites
def atomic_write content def atomic_write(content)
require "tempfile" require "tempfile"
tf = Tempfile.new(basename.to_s, dirname) tf = Tempfile.new(basename.to_s, dirname)
begin begin
@ -124,24 +124,24 @@ class Pathname
def default_stat def default_stat
sentinel = parent.join(".brew.#{Process.pid}.#{rand(Time.now.to_i)}") sentinel = parent.join(".brew.#{Process.pid}.#{rand(Time.now.to_i)}")
sentinel.open("w") { } sentinel.open("w") {}
sentinel.stat sentinel.stat
ensure ensure
sentinel.unlink sentinel.unlink
end end
private :default_stat private :default_stat
def cp dst def cp(dst)
opoo "Pathname#cp is deprecated, use FileUtils.cp" opoo "Pathname#cp is deprecated, use FileUtils.cp"
if file? if file?
FileUtils.cp to_s, dst FileUtils.cp to_s, dst
else else
FileUtils.cp_r to_s, dst FileUtils.cp_r to_s, dst
end end
return dst dst
end end
def cp_path_sub pattern, replacement def cp_path_sub(pattern, replacement)
raise "#{self} does not exist" unless self.exist? raise "#{self} does not exist" unless self.exist?
dst = sub(pattern, replacement) dst = sub(pattern, replacement)
@ -158,13 +158,13 @@ class Pathname
end end
# extended to support common double extensions # extended to support common double extensions
alias extname_old extname alias_method :extname_old, :extname
def extname(path=to_s) def extname(path = to_s)
BOTTLE_EXTNAME_RX.match(path) BOTTLE_EXTNAME_RX.match(path)
return $1 if $1 return $1 if $1
/(\.(tar|cpio|pax)\.(gz|bz2|lz|xz|Z))$/.match(path) /(\.(tar|cpio|pax)\.(gz|bz2|lz|xz|Z))$/.match(path)
return $1 if $1 return $1 if $1
return File.extname(path) File.extname(path)
end end
# for filetypes we support, basename without extension # for filetypes we support, basename without extension
@ -179,7 +179,7 @@ class Pathname
rmdir rmdir
true true
rescue Errno::ENOTEMPTY rescue Errno::ENOTEMPTY
if (ds_store = self+'.DS_Store').exist? && children.length == 1 if (ds_store = self+".DS_Store").exist? && children.length == 1
ds_store.unlink ds_store.unlink
retry retry
else else
@ -189,14 +189,14 @@ class Pathname
false false
end end
def chmod_R perms def chmod_R(perms)
opoo "Pathname#chmod_R is deprecated, use FileUtils.chmod_R" opoo "Pathname#chmod_R is deprecated, use FileUtils.chmod_R"
require 'fileutils' require "fileutils"
FileUtils.chmod_R perms, to_s FileUtils.chmod_R perms, to_s
end end
def version def version
require 'version' require "version"
Version.parse(self) Version.parse(self)
end end
@ -218,7 +218,7 @@ class Pathname
# Get enough of the file to detect common file types # Get enough of the file to detect common file types
# POSIX tar magic has a 257 byte offset # POSIX tar magic has a 257 byte offset
# magic numbers stolen from /usr/share/file/magic/ # magic numbers stolen from /usr/share/file/magic/
case open('rb') { |f| f.read(262) } case open("rb") { |f| f.read(262) }
when /^PK\003\004/n then :zip when /^PK\003\004/n then :zip
when /^\037\213/n then :gzip when /^\037\213/n then :gzip
when /^BZh/n then :bzip2 when /^BZh/n then :bzip2
@ -241,7 +241,7 @@ class Pathname
end end
def text_executable? def text_executable?
%r[^#!\s*\S+] === open('r') { |f| f.read(1024) } /^#!\s*\S+/ === open("r") { |f| f.read(1024) }
end end
def incremental_hash(klass) def incremental_hash(klass)
@ -256,30 +256,30 @@ class Pathname
end end
def sha1 def sha1
require 'digest/sha1' require "digest/sha1"
incremental_hash(Digest::SHA1) incremental_hash(Digest::SHA1)
end end
def sha256 def sha256
require 'digest/sha2' require "digest/sha2"
incremental_hash(Digest::SHA2) incremental_hash(Digest::SHA2)
end end
def verify_checksum expected def verify_checksum(expected)
raise ChecksumMissingError if expected.nil? or expected.empty? raise ChecksumMissingError if expected.nil? || expected.empty?
actual = Checksum.new(expected.hash_type, send(expected.hash_type).downcase) actual = Checksum.new(expected.hash_type, send(expected.hash_type).downcase)
raise ChecksumMismatchError.new(self, expected, actual) unless expected == actual raise ChecksumMismatchError.new(self, expected, actual) unless expected == actual
end end
# FIXME eliminate the places where we rely on this method # FIXME: eliminate the places where we rely on this method
alias_method :to_str, :to_s unless method_defined?(:to_str) alias_method :to_str, :to_s unless method_defined?(:to_str)
def cd def cd
Dir.chdir(self){ yield } Dir.chdir(self) { yield }
end end
def subdirs def subdirs
children.select{ |child| child.directory? } children.select(&:directory?)
end end
def resolved_path def resolved_path
@ -328,7 +328,7 @@ class Pathname
end end
# Writes an exec script in this folder for each target pathname # Writes an exec script in this folder for each target pathname
def write_exec_script *targets def write_exec_script(*targets)
targets.flatten! targets.flatten!
if targets.empty? if targets.empty?
opoo "tried to write exec scripts to #{self} for an empty list of targets" opoo "tried to write exec scripts to #{self} for an empty list of targets"
@ -337,7 +337,7 @@ class Pathname
mkpath mkpath
targets.each do |target| targets.each do |target|
target = Pathname.new(target) # allow pathnames or strings target = Pathname.new(target) # allow pathnames or strings
(self+target.basename()).write <<-EOS.undent (self+target.basename).write <<-EOS.undent
#!/bin/bash #!/bin/bash
exec "#{target}" "$@" exec "#{target}" "$@"
EOS EOS
@ -345,18 +345,18 @@ class Pathname
end end
# Writes an exec script that sets environment variables # Writes an exec script that sets environment variables
def write_env_script target, env def write_env_script(target, env)
env_export = '' env_export = ""
env.each {|key, value| env_export += "#{key}=\"#{value}\" "} env.each { |key, value| env_export += "#{key}=\"#{value}\" " }
dirname.mkpath dirname.mkpath
self.write <<-EOS.undent write <<-EOS.undent
#!/bin/bash #!/bin/bash
#{env_export}exec "#{target}" "$@" #{env_export}exec "#{target}" "$@"
EOS EOS
end end
# Writes a wrapper env script and moves all files to the dst # Writes a wrapper env script and moves all files to the dst
def env_script_all_files dst, env def env_script_all_files(dst, env)
dst.mkpath dst.mkpath
Pathname.glob("#{self}/*") do |file| Pathname.glob("#{self}/*") do |file|
next if file.directory? next if file.directory?
@ -367,7 +367,7 @@ class Pathname
end end
# Writes an exec script that invokes a java jar # Writes an exec script that invokes a java jar
def write_jar_script target_jar, script_name, java_opts="" def write_jar_script(target_jar, script_name, java_opts = "")
mkpath mkpath
(self+script_name).write <<-EOS.undent (self+script_name).write <<-EOS.undent
#!/bin/bash #!/bin/bash
@ -375,7 +375,7 @@ class Pathname
EOS EOS
end end
def install_metafiles from=Pathname.pwd def install_metafiles(from = Pathname.pwd)
Pathname(from).children.each do |p| Pathname(from).children.each do |p|
next if p.directory? next if p.directory?
next unless Metafiles.copy?(p.basename.to_s) next unless Metafiles.copy?(p.basename.to_s)
@ -420,7 +420,7 @@ class Pathname
File.dirname(prefix) File.dirname(prefix)
elsif /#{SEPARATOR_PAT}/o =~ prefix elsif /#{SEPARATOR_PAT}/o =~ prefix
prefix = File.dirname(prefix) prefix = File.dirname(prefix)
prefix = File.join(prefix, "") if File.basename(prefix + 'a') != 'a' prefix = File.join(prefix, "") if File.basename(prefix + "a") != "a"
prefix + relpath prefix + relpath
else else
prefix + relpath prefix + relpath
@ -456,25 +456,29 @@ module ObserverPathnameExtension
def unlink def unlink
super super
puts "rm #{to_s}" if ARGV.verbose? puts "rm #{self}" if ARGV.verbose?
ObserverPathnameExtension.n += 1 ObserverPathnameExtension.n += 1
end end
def rmdir def rmdir
super super
puts "rmdir #{to_s}" if ARGV.verbose? puts "rmdir #{self}" if ARGV.verbose?
ObserverPathnameExtension.d += 1 ObserverPathnameExtension.d += 1
end end
def make_relative_symlink src
def make_relative_symlink(src)
super super
puts "ln -s #{src.relative_path_from(dirname)} #{basename}" if ARGV.verbose? puts "ln -s #{src.relative_path_from(dirname)} #{basename}" if ARGV.verbose?
ObserverPathnameExtension.n += 1 ObserverPathnameExtension.n += 1
end end
def install_info def install_info
super super
puts "info #{to_s}" if ARGV.verbose? puts "info #{self}" if ARGV.verbose?
end end
def uninstall_info def uninstall_info
super super
puts "uninfo #{to_s}" if ARGV.verbose? puts "uninfo #{self}" if ARGV.verbose?
end end
end end

View File

@ -1,6 +1,6 @@
class String class String
def undent def undent
gsub(/^.{#{(slice(/^ +/) || '').length}}/, '') gsub(/^.{#{(slice(/^ +/) || '').length}}/, "")
end end
# eg: # eg:
@ -35,7 +35,7 @@ module StringInreplaceExtension
str.errors = [] str.errors = []
end end
def sub! before, after def sub!(before, after)
result = super result = super
unless result unless result
errors << "expected replacement of #{before.inspect} with #{after.inspect}" errors << "expected replacement of #{before.inspect} with #{after.inspect}"
@ -44,7 +44,7 @@ module StringInreplaceExtension
end end
# Warn if nothing was replaced # Warn if nothing was replaced
def gsub! before, after, audit_result=true def gsub!(before, after, audit_result = true)
result = super(before, after) result = super(before, after)
if audit_result && result.nil? if audit_result && result.nil?
errors << "expected replacement of #{before.inspect} with #{after.inspect}" errors << "expected replacement of #{before.inspect} with #{after.inspect}"
@ -54,14 +54,14 @@ module StringInreplaceExtension
# Looks for Makefile style variable defintions and replaces the # Looks for Makefile style variable defintions and replaces the
# value with "new_value", or removes the definition entirely. # value with "new_value", or removes the definition entirely.
def change_make_var! flag, new_value def change_make_var!(flag, new_value)
unless gsub!(/^#{Regexp.escape(flag)}[ \t]*=[ \t]*(.*)$/, "#{flag}=#{new_value}", false) unless gsub!(/^#{Regexp.escape(flag)}[ \t]*=[ \t]*(.*)$/, "#{flag}=#{new_value}", false)
errors << "expected to change #{flag.inspect} to #{new_value.inspect}" errors << "expected to change #{flag.inspect} to #{new_value.inspect}"
end end
end end
# Removes variable assignments completely. # Removes variable assignments completely.
def remove_make_var! flags def remove_make_var!(flags)
Array(flags).each do |flag| Array(flags).each do |flag|
# Also remove trailing \n, if present. # Also remove trailing \n, if present.
unless gsub!(/^#{Regexp.escape(flag)}[ \t]*=.*$\n?/, "", false) unless gsub!(/^#{Regexp.escape(flag)}[ \t]*=.*$\n?/, "", false)
@ -71,7 +71,7 @@ module StringInreplaceExtension
end end
# Finds the specified variable # Finds the specified variable
def get_make_var flag def get_make_var(flag)
self[/^#{Regexp.escape(flag)}[ \t]*=[ \t]*(.*)$/, 1] self[/^#{Regexp.escape(flag)}[ \t]*=[ \t]*(.*)$/, 1]
end end
end end

View File

@ -1,15 +1,15 @@
require 'formula_support' require "formula_support"
require 'formula_lock' require "formula_lock"
require 'formula_pin' require "formula_pin"
require 'hardware' require "hardware"
require 'bottles' require "bottles"
require 'build_environment' require "build_environment"
require 'build_options' require "build_options"
require 'formulary' require "formulary"
require 'software_spec' require "software_spec"
require 'install_renamed' require "install_renamed"
require 'pkg_version' require "pkg_version"
require 'tap' require "tap"
# A formula provides instructions and metadata for Homebrew to install a piece # A formula provides instructions and metadata for Homebrew to install a piece
# of software. Every Homebrew formula is a {Formula}. # of software. Every Homebrew formula is a {Formula}.
@ -141,7 +141,7 @@ class Formula
def determine_active_spec(requested) def determine_active_spec(requested)
spec = send(requested) || stable || devel || head spec = send(requested) || stable || devel || head
spec or raise FormulaSpecificationError, "formulae require at least a URL" spec || raise(FormulaSpecificationError, "formulae require at least a URL")
end end
def validate_attributes! def validate_attributes!
@ -314,175 +314,242 @@ class Formula
# The currently installed version for this formula. Will raise an exception # The currently installed version for this formula. Will raise an exception
# if the formula is not installed. # if the formula is not installed.
def installed_version def installed_version
require 'keg' require "keg"
Keg.new(installed_prefix).version Keg.new(installed_prefix).version
end end
# The directory in the cellar that the formula is installed to. # The directory in the cellar that the formula is installed to.
# This directory contains the formula's name and version. # This directory contains the formula's name and version.
def prefix(v=pkg_version) def prefix(v = pkg_version)
Pathname.new("#{HOMEBREW_CELLAR}/#{name}/#{v}") Pathname.new("#{HOMEBREW_CELLAR}/#{name}/#{v}")
end end
# The parent of the prefix; the named directory in the cellar containing all # The parent of the prefix; the named directory in the cellar containing all
# installed versions of this software # installed versions of this software
def rack; prefix.parent end def rack
prefix.parent
end
# The directory where the formula's binaries should be installed. # The directory where the formula's binaries should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with # This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only. # `brew link` for formulae that are not keg-only.
def bin; prefix+'bin' end def bin
prefix+"bin"
end
# The directory where the formula's documentation should be installed. # The directory where the formula's documentation should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with # This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only. # `brew link` for formulae that are not keg-only.
def doc; share+'doc'+name end def doc
share+"doc"+name
end
# The directory where the formula's headers should be installed. # The directory where the formula's headers should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with # This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only. # `brew link` for formulae that are not keg-only.
def include; prefix+'include' end def include
prefix+"include"
end
# The directory where the formula's info files should be installed. # The directory where the formula's info files should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with # This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only. # `brew link` for formulae that are not keg-only.
def info; share+'info' end def info
share+"info"
end
# The directory where the formula's libraries should be installed. # The directory where the formula's libraries should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with # This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only. # `brew link` for formulae that are not keg-only.
def lib; prefix+'lib' end def lib
prefix+"lib"
end
# The directory where the formula's binaries should be installed. # The directory where the formula's binaries should be installed.
# This is not symlinked into `HOMEBREW_PREFIX`. # This is not symlinked into `HOMEBREW_PREFIX`.
# It is also commonly used to install files that we do not wish to be # It is also commonly used to install files that we do not wish to be
# symlinked into HOMEBREW_PREFIX from one of the other directories and # symlinked into HOMEBREW_PREFIX from one of the other directories and
# instead manually create symlinks or wrapper scripts into e.g. {#bin}. # instead manually create symlinks or wrapper scripts into e.g. {#bin}.
def libexec; prefix+'libexec' end def libexec
prefix+"libexec"
end
# The root directory where the formula's manual pages should be installed. # The root directory where the formula's manual pages should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with # This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only. # `brew link` for formulae that are not keg-only.
# Often one of the more specific `man` functions should be used instead # Often one of the more specific `man` functions should be used instead
# e.g. {#man1} # e.g. {#man1}
def man; share+'man' end def man
share+"man"
end
# The directory where the formula's man1 pages should be installed. # The directory where the formula's man1 pages should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with # This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only. # `brew link` for formulae that are not keg-only.
def man1; man+'man1' end def man1
man+"man1"
end
# The directory where the formula's man2 pages should be installed. # The directory where the formula's man2 pages should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with # This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only. # `brew link` for formulae that are not keg-only.
def man2; man+'man2' end def man2
man+"man2"
end
# The directory where the formula's man3 pages should be installed. # The directory where the formula's man3 pages should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with # This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only. # `brew link` for formulae that are not keg-only.
def man3; man+'man3' end def man3
man+"man3"
end
# The directory where the formula's man4 pages should be installed. # The directory where the formula's man4 pages should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with # This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only. # `brew link` for formulae that are not keg-only.
def man4; man+'man4' end def man4
man+"man4"
end
# The directory where the formula's man5 pages should be installed. # The directory where the formula's man5 pages should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with # This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only. # `brew link` for formulae that are not keg-only.
def man5; man+'man5' end def man5
man+"man5"
end
# The directory where the formula's man6 pages should be installed. # The directory where the formula's man6 pages should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with # This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only. # `brew link` for formulae that are not keg-only.
def man6; man+'man6' end def man6
man+"man6"
end
# The directory where the formula's man7 pages should be installed. # The directory where the formula's man7 pages should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with # This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only. # `brew link` for formulae that are not keg-only.
def man7; man+'man7' end def man7
man+"man7"
end
# The directory where the formula's man8 pages should be installed. # The directory where the formula's man8 pages should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with # This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only. # `brew link` for formulae that are not keg-only.
def man8; man+'man8' end def man8
man+"man8"
end
# The directory where the formula's `sbin` binaries should be installed. # The directory where the formula's `sbin` binaries should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with # This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only. # `brew link` for formulae that are not keg-only.
# Generally we try to migrate these to {#bin} instead. # Generally we try to migrate these to {#bin} instead.
def sbin; prefix+'sbin' end def sbin
prefix+"sbin"
end
# The directory where the formula's shared files should be installed. # The directory where the formula's shared files should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with # This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only. # `brew link` for formulae that are not keg-only.
def share; prefix+'share' end def share
prefix+"share"
end
# The directory where the formula's shared files should be installed, # The directory where the formula's shared files should be installed,
# with the name of the formula appended to avoid linking conflicts. # with the name of the formula appended to avoid linking conflicts.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with # This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only. # `brew link` for formulae that are not keg-only.
def pkgshare; prefix+'share'+name end def pkgshare
prefix+"share"+name
end
# The directory where the formula's Frameworks should be installed. # The directory where the formula's Frameworks should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with # This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only. # `brew link` for formulae that are not keg-only.
# This is not symlinked into `HOMEBREW_PREFIX`. # This is not symlinked into `HOMEBREW_PREFIX`.
def frameworks; prefix+'Frameworks' end def frameworks
prefix+"Frameworks"
end
# The directory where the formula's kernel extensions should be installed. # The directory where the formula's kernel extensions should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with # This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only. # `brew link` for formulae that are not keg-only.
# This is not symlinked into `HOMEBREW_PREFIX`. # This is not symlinked into `HOMEBREW_PREFIX`.
def kext_prefix; prefix+'Library/Extensions' end def kext_prefix
prefix+"Library/Extensions"
end
# The directory where the formula's configuration files should be installed. # The directory where the formula's configuration files should be installed.
# Anything using `etc.install` will not overwrite other files on e.g. upgrades # Anything using `etc.install` will not overwrite other files on e.g. upgrades
# but will write a new file named `*.default`. # but will write a new file named `*.default`.
# This directory is not inside the `HOMEBREW_CELLAR` so it is persisted # This directory is not inside the `HOMEBREW_CELLAR` so it is persisted
# across upgrades. # across upgrades.
def etc; (HOMEBREW_PREFIX+'etc').extend(InstallRenamed) end def etc
(HOMEBREW_PREFIX+"etc").extend(InstallRenamed)
end
# The directory where the formula's variable files should be installed. # The directory where the formula's variable files should be installed.
# This directory is not inside the `HOMEBREW_CELLAR` so it is persisted # This directory is not inside the `HOMEBREW_CELLAR` so it is persisted
# across upgrades. # across upgrades.
def var; HOMEBREW_PREFIX+'var' end def var
HOMEBREW_PREFIX+"var"
end
# The directory where the formula's Bash completion files should be # The directory where the formula's Bash completion files should be
# installed. # installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with # This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only. # `brew link` for formulae that are not keg-only.
def bash_completion; prefix+'etc/bash_completion.d' end def bash_completion
prefix+"etc/bash_completion.d"
end
# The directory where the formula's ZSH completion files should be # The directory where the formula's ZSH completion files should be
# installed. # installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with # This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only. # `brew link` for formulae that are not keg-only.
def zsh_completion; share+'zsh/site-functions' end def zsh_completion
share+"zsh/site-functions"
end
# The directory where the formula's fish completion files should be # The directory where the formula's fish completion files should be
# installed. # installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with # This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only. # `brew link` for formulae that are not keg-only.
def fish_completion; share+'fish/vendor_completions.d' end def fish_completion
share+"fish/vendor_completions.d"
end
# The directory used for as the prefix for {#etc} and {#var} files on # The directory used for as the prefix for {#etc} and {#var} files on
# installation so, despite not being in `HOMEBREW_CELLAR`, they are installed # installation so, despite not being in `HOMEBREW_CELLAR`, they are installed
# there after pouring a bottle. # there after pouring a bottle.
def bottle_prefix; prefix+'.bottle' end def bottle_prefix
prefix+".bottle"
end
def logs def logs
HOMEBREW_LOGS+name HOMEBREW_LOGS+name
end end
# override this to provide a plist # override this to provide a plist
def plist; nil; end def plist
alias :startup_plist :plist nil
end
alias_method :startup_plist, :plist
# plist name, i.e. the name of the launchd service # plist name, i.e. the name of the launchd service
def plist_name; 'homebrew.mxcl.'+name end def plist_name
def plist_path; prefix+(plist_name+'.plist') end "homebrew.mxcl."+name
def plist_manual; self.class.plist_manual end end
def plist_startup; self.class.plist_startup end
def plist_path
prefix+(plist_name+".plist")
end
def plist_manual
self.class.plist_manual
end
def plist_startup
self.class.plist_startup
end
# A stable path for this formula, when installed. Contains the formula name # A stable path for this formula, when installed. Contains the formula name
# but no version number. Only the active version will be linked here if # but no version number. Only the active version will be linked here if
@ -494,19 +561,44 @@ class Formula
Pathname.new("#{HOMEBREW_PREFIX}/opt/#{name}") Pathname.new("#{HOMEBREW_PREFIX}/opt/#{name}")
end end
def opt_bin; opt_prefix+'bin' end def opt_bin
def opt_include; opt_prefix+'include' end opt_prefix+"bin"
def opt_lib; opt_prefix+'lib' end end
def opt_libexec; opt_prefix+'libexec' end
def opt_sbin; opt_prefix+'sbin' end def opt_include
def opt_share; opt_prefix+'share' end opt_prefix+"include"
def opt_pkgshare; opt_prefix+'share'+name end end
def opt_frameworks; opt_prefix+'Frameworks' end
def opt_lib
opt_prefix+"lib"
end
def opt_libexec
opt_prefix+"libexec"
end
def opt_sbin
opt_prefix+"sbin"
end
def opt_share
opt_prefix+"share"
end
def opt_pkgshare
opt_prefix+"share"+name
end
def opt_frameworks
opt_prefix+"Frameworks"
end
# Can be overridden to selectively disable bottles from formulae. # Can be overridden to selectively disable bottles from formulae.
# Defaults to true so overridden version does not have to check if bottles # Defaults to true so overridden version does not have to check if bottles
# are supported. # are supported.
def pour_bottle?; true end def pour_bottle?
true
end
# Can be overridden to run commands on both source and bottle installation. # Can be overridden to run commands on both source and bottle installation.
def post_install; end def post_install; end
@ -524,7 +616,9 @@ class Formula
end end
# tell the user about any caveats regarding this package, return a string # tell the user about any caveats regarding this package, return a string
def caveats; nil end def caveats
nil
end
# rarely, you don't want your library symlinked into the main prefix # rarely, you don't want your library symlinked into the main prefix
# see gettext.rb for an example # see gettext.rb for an example
@ -541,8 +635,8 @@ class Formula
# skip_clean "bin/foo", "lib/bar" # skip_clean "bin/foo", "lib/bar"
# keep .la files with: # keep .la files with:
# skip_clean :la # skip_clean :la
def skip_clean? path def skip_clean?(path)
return true if path.extname == '.la' and self.class.skip_clean_paths.include? :la return true if path.extname == ".la" && self.class.skip_clean_paths.include?(:la)
to_check = path.relative_path_from(prefix).to_s to_check = path.relative_path_from(prefix).to_s
self.class.skip_clean_paths.include? to_check self.class.skip_clean_paths.include? to_check
end end
@ -601,7 +695,7 @@ class Formula
@pin.unpin @pin.unpin
end end
def == other def ==(other)
instance_of?(other.class) && instance_of?(other.class) &&
name == other.name && name == other.name &&
active_spec == other.active_spec active_spec == other.active_spec
@ -653,7 +747,7 @@ class Formula
# an array of all core {Formula} names # an array of all core {Formula} names
def self.core_names def self.core_names
@core_names ||= Dir["#{HOMEBREW_LIBRARY}/Formula/*.rb"].map{ |f| File.basename f, ".rb" }.sort @core_names ||= Dir["#{HOMEBREW_LIBRARY}/Formula/*.rb"].map { |f| File.basename f, ".rb" }.sort
end end
# an array of all core {Formula} files # an array of all core {Formula} files
@ -714,7 +808,7 @@ class Formula
end end
def self.aliases def self.aliases
Dir["#{HOMEBREW_LIBRARY}/Aliases/*"].map{ |f| File.basename f }.sort Dir["#{HOMEBREW_LIBRARY}/Aliases/*"].map { |f| File.basename f }.sort
end end
def self.[](name) def self.[](name)
@ -727,13 +821,13 @@ class Formula
def tap def tap
if path.to_s =~ HOMEBREW_TAP_DIR_REGEX if path.to_s =~ HOMEBREW_TAP_DIR_REGEX
"#$1/#$2" "#{$1}/#{$2}"
elsif core_formula? elsif core_formula?
"Homebrew/homebrew" "Homebrew/homebrew"
end end
end end
def print_tap_action options={} def print_tap_action(options = {})
if tap? if tap?
verb = options[:verb] || "Installing" verb = options[:verb] || "Installing"
ohai "#{verb} #{name} from #{tap}" ohai "#{verb} #{name} from #{tap}"
@ -794,9 +888,9 @@ class Formula
} }
end end
hsh["options"] = options.map { |opt| hsh["options"] = options.map do |opt|
{ "option" => opt.flag, "description" => opt.description } { "option" => opt.flag, "description" => opt.description }
} end
if rack.directory? if rack.directory?
rack.subdirs.each do |keg_path| rack.subdirs.each do |keg_path|
@ -815,14 +909,13 @@ class Formula
end end
hsh hsh
end end
def fetch def fetch
active_spec.fetch active_spec.fetch
end end
def verify_download_integrity fn def verify_download_integrity(fn)
active_spec.verify_download_integrity(fn) active_spec.verify_download_integrity(fn)
end end
@ -857,7 +950,7 @@ class Formula
protected protected
def setup_test_home home def setup_test_home(home)
# keep Homebrew's site-packages in sys.path when testing with system Python # keep Homebrew's site-packages in sys.path when testing with system Python
user_site_packages = home/"Library/Python/2.7/lib/python/site-packages" user_site_packages = home/"Library/Python/2.7/lib/python/site-packages"
user_site_packages.mkpath user_site_packages.mkpath
@ -869,12 +962,12 @@ class Formula
# Pretty titles the command and buffers stdout/stderr # Pretty titles the command and buffers stdout/stderr
# Throws if there's an error # Throws if there's an error
def system cmd, *args def system(cmd, *args)
verbose = ARGV.verbose? verbose = ARGV.verbose?
# remove "boring" arguments so that the important ones are more likely to # remove "boring" arguments so that the important ones are more likely to
# be shown considering that we trim long ohai lines to the terminal width # be shown considering that we trim long ohai lines to the terminal width
pretty_args = args.dup pretty_args = args.dup
if cmd == "./configure" and not verbose if cmd == "./configure" && !verbose
pretty_args.delete "--disable-dependency-tracking" pretty_args.delete "--disable-dependency-tracking"
pretty_args.delete "--disable-debug" pretty_args.delete "--disable-debug"
end end
@ -883,11 +976,11 @@ class Formula
pretty_args[i] = "import setuptools..." pretty_args[i] = "import setuptools..."
end end
end end
ohai "#{cmd} #{pretty_args*' '}".strip ohai "#{cmd} #{pretty_args*" "}".strip
@exec_count ||= 0 @exec_count ||= 0
@exec_count += 1 @exec_count += 1
logfn = "#{logs}/%02d.%s" % [@exec_count, File.basename(cmd).split(' ').first] logfn = "#{logs}/%02d.%s" % [@exec_count, File.basename(cmd).split(" ").first]
logs.mkpath logs.mkpath
File.open(logfn, "w") do |log| File.open(logfn, "w") do |log|
@ -941,9 +1034,9 @@ class Formula
private private
def exec_cmd(cmd, args, out, logfn) def exec_cmd(cmd, args, out, logfn)
ENV['HOMEBREW_CC_LOG_PATH'] = logfn ENV["HOMEBREW_CC_LOG_PATH"] = logfn
# TODO system "xcodebuild" is deprecated, this should be removed soon. # TODO: system "xcodebuild" is deprecated, this should be removed soon.
if cmd.to_s.start_with? "xcodebuild" if cmd.to_s.start_with? "xcodebuild"
ENV.remove_cc_etc ENV.remove_cc_etc
end end
@ -962,7 +1055,7 @@ class Formula
$stdout.reopen(out) $stdout.reopen(out)
$stderr.reopen(out) $stderr.reopen(out)
out.close out.close
args.collect!{|arg| arg.to_s} args.collect!(&:to_s)
exec(cmd, *args) rescue nil exec(cmd, *args) rescue nil
puts "Failed to execute: #{cmd}" puts "Failed to execute: #{cmd}"
exit! 1 # never gets here unless exec threw or failed exit! 1 # never gets here unless exec threw or failed
@ -995,7 +1088,7 @@ class Formula
end end
end end
def self.method_added method def self.method_added(method)
case method case method
when :brew when :brew
raise "You cannot override Formula#brew in class #{name}" raise "You cannot override Formula#brew in class #{name}"
@ -1061,7 +1154,7 @@ class Formula
# @!attribute [w] url # @!attribute [w] url
# The URL used to download the source for the {#stable} version of the formula. # The URL used to download the source for the {#stable} version of the formula.
# We prefer `https` for security and proxy reasons. # We prefer `https` for security and proxy reasons.
def url val, specs={} def url(val, specs = {})
stable.url(val, specs) stable.url(val, specs)
end end
@ -1069,7 +1162,7 @@ class Formula
# The version string for the {#stable} version of the formula. # The version string for the {#stable} version of the formula.
# The version is autodetected from the URL and/or tag so only needs to be # The version is autodetected from the URL and/or tag so only needs to be
# declared if it cannot be autodetected correctly. # declared if it cannot be autodetected correctly.
def version val=nil def version(val = nil)
stable.version(val) stable.version(val)
end end
@ -1079,7 +1172,7 @@ class Formula
# there can be more than one. Generally we add them when the main {.url} # there can be more than one. Generally we add them when the main {.url}
# is unreliable. If {.url} is really unreliable then we may swap the # is unreliable. If {.url} is really unreliable then we may swap the
# {.mirror} and {.url}. # {.mirror} and {.url}.
def mirror val def mirror(val)
stable.mirror(val) stable.mirror(val)
end end
@ -1098,7 +1191,7 @@ class Formula
define_method(type) { |val| stable.send(type, val) } define_method(type) { |val| stable.send(type, val) }
end end
def bottle *, &block def bottle(*, &block)
stable.bottle(&block) stable.bottle(&block)
end end
@ -1106,19 +1199,19 @@ class Formula
stable.build stable.build
end end
def stable &block def stable(&block)
@stable ||= SoftwareSpec.new @stable ||= SoftwareSpec.new
return @stable unless block_given? return @stable unless block_given?
@stable.instance_eval(&block) @stable.instance_eval(&block)
end end
def devel &block def devel(&block)
@devel ||= SoftwareSpec.new @devel ||= SoftwareSpec.new
return @devel unless block_given? return @devel unless block_given?
@devel.instance_eval(&block) @devel.instance_eval(&block)
end end
def head val=nil, specs={}, &block def head(val = nil, specs = {}, &block)
@head ||= HeadSoftwareSpec.new @head ||= HeadSoftwareSpec.new
if block_given? if block_given?
@head.instance_eval(&block) @head.instance_eval(&block)
@ -1130,33 +1223,33 @@ class Formula
end end
# Define a named resource using a {SoftwareSpec} style block # Define a named resource using a {SoftwareSpec} style block
def resource name, klass=Resource, &block def resource(name, klass = Resource, &block)
specs.each do |spec| specs.each do |spec|
spec.resource(name, klass, &block) unless spec.resource_defined?(name) spec.resource(name, klass, &block) unless spec.resource_defined?(name)
end end
end end
def go_resource name, &block def go_resource(name, &block)
specs.each { |spec| spec.go_resource(name, &block) } specs.each { |spec| spec.go_resource(name, &block) }
end end
def depends_on dep def depends_on(dep)
specs.each { |spec| spec.depends_on(dep) } specs.each { |spec| spec.depends_on(dep) }
end end
def option name, description="" def option(name, description = "")
specs.each { |spec| spec.option(name, description) } specs.each { |spec| spec.option(name, description) }
end end
def deprecated_option hash def deprecated_option(hash)
specs.each { |spec| spec.deprecated_option(hash) } specs.each { |spec| spec.deprecated_option(hash) }
end end
def patch strip=:p1, src=nil, &block def patch(strip = :p1, src = nil, &block)
specs.each { |spec| spec.patch(strip, src, &block) } specs.each { |spec| spec.patch(strip, src, &block) }
end end
def plist_options options def plist_options(options)
@plist_startup = options[:startup] @plist_startup = options[:startup]
@plist_manual = options[:manual] @plist_manual = options[:manual]
end end
@ -1165,12 +1258,12 @@ class Formula
@conflicts ||= [] @conflicts ||= []
end end
def conflicts_with *names def conflicts_with(*names)
opts = Hash === names.last ? names.pop : {} opts = Hash === names.last ? names.pop : {}
names.each { |name| conflicts << FormulaConflict.new(name, opts[:because]) } names.each { |name| conflicts << FormulaConflict.new(name, opts[:because]) }
end end
def skip_clean *paths def skip_clean(*paths)
paths.flatten! paths.flatten!
# Specifying :all is deprecated and will become an error # Specifying :all is deprecated and will become an error
skip_clean_paths.merge(paths) skip_clean_paths.merge(paths)
@ -1180,12 +1273,12 @@ class Formula
@skip_clean_paths ||= Set.new @skip_clean_paths ||= Set.new
end end
def keg_only reason, explanation="" def keg_only(reason, explanation = "")
@keg_only_reason = KegOnlyReason.new(reason, explanation) @keg_only_reason = KegOnlyReason.new(reason, explanation)
end end
# Pass :skip to this method to disable post-install stdlib checking # Pass :skip to this method to disable post-install stdlib checking
def cxxstdlib_check check_type def cxxstdlib_check(check_type)
define_method(:skip_cxxstdlib_check?) { true } if check_type == :skip define_method(:skip_cxxstdlib_check?) { true } if check_type == :skip
end end
@ -1216,15 +1309,15 @@ class Formula
# fails_with :gcc => '4.8' do # fails_with :gcc => '4.8' do
# version '4.8.1' # version '4.8.1'
# end # end
def fails_with compiler, &block def fails_with(compiler, &block)
specs.each { |spec| spec.fails_with(compiler, &block) } specs.each { |spec| spec.fails_with(compiler, &block) }
end end
def needs *standards def needs(*standards)
specs.each { |spec| spec.needs(*standards) } specs.each { |spec| spec.needs(*standards) }
end end
def test &block def test(&block)
define_method(:test, &block) define_method(:test, &block)
end end
end end

View File

@ -24,7 +24,7 @@ module Homebrew
include Test::Unit::Assertions include Test::Unit::Assertions
# Returns the output of running cmd, and asserts the exit status # Returns the output of running cmd, and asserts the exit status
def shell_output(cmd, result=0) def shell_output(cmd, result = 0)
ohai cmd ohai cmd
output = `#{cmd}` output = `#{cmd}`
assert_equal result, $?.exitstatus assert_equal result, $?.exitstatus
@ -33,7 +33,7 @@ module Homebrew
# Returns the output of running the cmd with the optional input, and # Returns the output of running the cmd with the optional input, and
# optionally asserts the exit status # optionally asserts the exit status
def pipe_output(cmd, input=nil, result=nil) def pipe_output(cmd, input = nil, result = nil)
ohai cmd ohai cmd
output = IO.popen(cmd, "w+") do |pipe| output = IO.popen(cmd, "w+") do |pipe|
pipe.write(input) unless input.nil? pipe.write(input) unless input.nil?

View File

@ -1,5 +1,5 @@
module FormulaCellarChecks module FormulaCellarChecks
def check_PATH bin def check_PATH(bin)
# warn the user if stuff was installed outside of their PATH # warn the user if stuff was installed outside of their PATH
return unless bin.directory? return unless bin.directory?
return unless bin.children.length > 0 return unless bin.children.length > 0
@ -18,7 +18,7 @@ module FormulaCellarChecks
def check_manpages def check_manpages
# Check for man pages that aren't in share/man # Check for man pages that aren't in share/man
return unless (formula.prefix+'man').directory? return unless (formula.prefix+"man").directory?
<<-EOS.undent <<-EOS.undent
A top-level "man" directory was found A top-level "man" directory was found
@ -29,7 +29,7 @@ module FormulaCellarChecks
def check_infopages def check_infopages
# Check for info pages that aren't in share/info # Check for info pages that aren't in share/info
return unless (formula.prefix+'info').directory? return unless (formula.prefix+"info").directory?
<<-EOS.undent <<-EOS.undent
A top-level "info" directory was found A top-level "info" directory was found
@ -57,11 +57,11 @@ module FormulaCellarChecks
def check_non_libraries def check_non_libraries
return unless formula.lib.directory? return unless formula.lib.directory?
valid_extensions = %w(.a .dylib .framework .jnilib .la .o .so valid_extensions = %w[.a .dylib .framework .jnilib .la .o .so
.jar .prl .pm .sh) .jar .prl .pm .sh]
non_libraries = formula.lib.children.select do |g| non_libraries = formula.lib.children.select do |g|
next if g.directory? next if g.directory?
not valid_extensions.include? g.extname !valid_extensions.include? g.extname
end end
return if non_libraries.empty? return if non_libraries.empty?
@ -73,10 +73,10 @@ module FormulaCellarChecks
EOS EOS
end end
def check_non_executables bin def check_non_executables(bin)
return unless bin.directory? return unless bin.directory?
non_exes = bin.children.select { |g| g.directory? or not g.executable? } non_exes = bin.children.select { |g| g.directory? || !g.executable? }
return if non_exes.empty? return if non_exes.empty?
<<-EOS.undent <<-EOS.undent
@ -86,7 +86,7 @@ module FormulaCellarChecks
EOS EOS
end end
def check_generic_executables bin def check_generic_executables(bin)
return unless bin.directory? return unless bin.directory?
generic_names = %w[run service start stop] generic_names = %w[run service start stop]
generics = bin.children.select { |g| generic_names.include? g.basename.to_s } generics = bin.children.select { |g| generic_names.include? g.basename.to_s }
@ -126,7 +126,7 @@ module FormulaCellarChecks
EOS EOS
end end
def check_easy_install_pth lib def check_easy_install_pth(lib)
pth_found = Dir["#{lib}/python{2.7,3}*/site-packages/easy-install.pth"].map { |f| File.dirname(f) } pth_found = Dir["#{lib}/python{2.7,3}*/site-packages/easy-install.pth"].map { |f| File.dirname(f) }
return if pth_found.empty? return if pth_found.empty?
@ -156,7 +156,7 @@ module FormulaCellarChecks
EOS EOS
end end
def check_python_framework_links lib def check_python_framework_links(lib)
python_modules = Pathname.glob lib/"python*/site-packages/**/*.so" python_modules = Pathname.glob lib/"python*/site-packages/**/*.so"
framework_links = python_modules.select do |obj| framework_links = python_modules.select do |obj|
dlls = obj.dynamically_linked_libraries dlls = obj.dynamically_linked_libraries
@ -206,7 +206,7 @@ module FormulaCellarChecks
audit_check_output(check_easy_install_pth(formula.lib)) audit_check_output(check_easy_install_pth(formula.lib))
audit_check_output(check_openssl_links) audit_check_output(check_openssl_links)
audit_check_output(check_python_framework_links(formula.lib)) audit_check_output(check_python_framework_links(formula.lib))
audit_check_output(check_emacs_lisp(formula.share,formula.name)) audit_check_output(check_emacs_lisp(formula.share, formula.name))
end end
private private

View File

@ -1,18 +1,18 @@
require 'cxxstdlib' require "cxxstdlib"
require 'exceptions' require "exceptions"
require 'formula' require "formula"
require 'keg' require "keg"
require 'tab' require "tab"
require 'bottles' require "bottles"
require 'caveats' require "caveats"
require 'cleaner' require "cleaner"
require 'formula_cellar_checks' require "formula_cellar_checks"
require 'install_renamed' require "install_renamed"
require 'cmd/tap' require "cmd/tap"
require 'cmd/postinstall' require "cmd/postinstall"
require 'hooks/bottles' require "hooks/bottles"
require 'debrew' require "debrew"
require 'sandbox' require "sandbox"
class FormulaInstaller class FormulaInstaller
include FormulaCellarChecks include FormulaCellarChecks
@ -55,7 +55,7 @@ class FormulaInstaller
@pour_failed = false @pour_failed = false
end end
def pour_bottle? install_bottle_options={:warn=>false} def pour_bottle?(install_bottle_options = { :warn=>false })
return true if Homebrew::Hooks::Bottles.formula_has_bottle?(formula) return true if Homebrew::Hooks::Bottles.formula_has_bottle?(formula)
return false if @pour_failed return false if @pour_failed
@ -84,7 +84,7 @@ class FormulaInstaller
return false unless dep.bottle && dep.pour_bottle? return false unless dep.bottle && dep.pour_bottle?
return false unless build.used_options.empty? return false unless build.used_options.empty?
return false unless dep.bottle.compatible_cellar? return false unless dep.bottle.compatible_cellar?
return true true
end end
def prelude def prelude
@ -113,10 +113,10 @@ class FormulaInstaller
unless ignore_deps? unless ignore_deps?
unlinked_deps = formula.recursive_dependencies.map(&:to_formula).select do |dep| unlinked_deps = formula.recursive_dependencies.map(&:to_formula).select do |dep|
dep.installed? and not dep.keg_only? and not dep.linked_keg.directory? dep.installed? && !dep.keg_only? && !dep.linked_keg.directory?
end end
raise CannotInstallFormulaError, raise CannotInstallFormulaError,
"You must `brew link #{unlinked_deps*' '}' before #{formula.full_name} can be installed" unless unlinked_deps.empty? "You must `brew link #{unlinked_deps*" "}' before #{formula.full_name} can be installed" unless unlinked_deps.empty?
end end
end end
@ -186,7 +186,7 @@ class FormulaInstaller
puts "Building from source because #{filename} has local changes" puts "Building from source because #{filename} has local changes"
puts "To install from a bottle instead, run with --force-bottle" puts "To install from a bottle instead, run with --force-bottle"
end end
compute_and_install_dependencies if @pour_failed and not ignore_deps? compute_and_install_dependencies if @pour_failed && !ignore_deps?
build build
clean clean
end end
@ -222,7 +222,7 @@ class FormulaInstaller
deps = expand_dependencies(req_deps + formula.deps) deps = expand_dependencies(req_deps + formula.deps)
if deps.empty? and only_deps? if deps.empty? && only_deps?
puts "All dependencies for #{formula.full_name} are satisfied." puts "All dependencies for #{formula.full_name} are satisfied."
else else
install_dependencies(deps) install_dependencies(deps)
@ -275,7 +275,7 @@ class FormulaInstaller
end end
end end
return unsatisfied_reqs, deps [unsatisfied_reqs, deps]
end end
def expand_dependencies(deps) def expand_dependencies(deps)
@ -300,7 +300,7 @@ class FormulaInstaller
expanded_deps.map { |dep| [dep, inherited_options[dep.name]] } expanded_deps.map { |dep| [dep, inherited_options[dep.name]] }
end end
def effective_build_options_for(dependent, inherited_options=[]) def effective_build_options_for(dependent, inherited_options = [])
args = dependent.build.used_options args = dependent.build.used_options
args |= dependent == formula ? options : inherited_options args |= dependent == formula ? options : inherited_options
args |= Tab.for_formula(dependent).used_options args |= Tab.for_formula(dependent).used_options
@ -379,20 +379,20 @@ class FormulaInstaller
def caveats def caveats
return if only_deps? return if only_deps?
audit_installed if ARGV.homebrew_developer? and not formula.keg_only? audit_installed if ARGV.homebrew_developer? && !formula.keg_only?
c = Caveats.new(formula) c = Caveats.new(formula)
unless c.empty? unless c.empty?
@show_summary_heading = true @show_summary_heading = true
ohai 'Caveats', c.caveats ohai "Caveats", c.caveats
end end
end end
def finish def finish
return if only_deps? return if only_deps?
ohai 'Finishing up' if verbose? ohai "Finishing up" if verbose?
install_plist install_plist
@ -407,19 +407,19 @@ class FormulaInstaller
post_install post_install
end end
ohai "Summary" if verbose? or show_summary_heading? ohai "Summary" if verbose? || show_summary_heading?
puts summary puts summary
ensure ensure
unlock unlock
end end
def emoji def emoji
ENV['HOMEBREW_INSTALL_BADGE'] || "\xf0\x9f\x8d\xba" ENV["HOMEBREW_INSTALL_BADGE"] || "\xf0\x9f\x8d\xba"
end end
def summary def summary
s = "" s = ""
s << "#{emoji} " if MacOS.version >= :lion and not ENV['HOMEBREW_NO_EMOJI'] s << "#{emoji} " if MacOS.version >= :lion && !ENV["HOMEBREW_NO_EMOJI"]
s << "#{formula.prefix}: #{formula.prefix.abv}" s << "#{formula.prefix}: #{formula.prefix.abv}"
s << ", built in #{pretty_duration build_time}" if build_time s << ", built in #{pretty_duration build_time}" if build_time
s s

View File

@ -1,4 +1,4 @@
require 'fcntl' require "fcntl"
class FormulaLock class FormulaLock
LOCKDIR = HOMEBREW_CACHE_FORMULA LOCKDIR = HOMEBREW_CACHE_FORMULA

View File

@ -4,7 +4,7 @@ class FormulaVersions
IGNORED_EXCEPTIONS = [ IGNORED_EXCEPTIONS = [
ArgumentError, NameError, SyntaxError, TypeError, ArgumentError, NameError, SyntaxError, TypeError,
FormulaSpecificationError, FormulaValidationError, FormulaSpecificationError, FormulaValidationError,
ErrorDuringExecution, LoadError, ErrorDuringExecution, LoadError
] ]
attr_reader :name, :repository, :entry_name attr_reader :name, :repository, :entry_name

View File

@ -40,10 +40,10 @@ class Formulary
end end
end end
def self.class_s name def self.class_s(name)
class_name = name.capitalize class_name = name.capitalize
class_name.gsub!(/[-_.\s]([a-zA-Z0-9])/) { $1.upcase } class_name.gsub!(/[-_.\s]([a-zA-Z0-9])/) { $1.upcase }
class_name.gsub!('+', 'x') class_name.gsub!("+", "x")
class_name class_name
end end
@ -81,7 +81,7 @@ class Formulary
# Loads formulae from bottles. # Loads formulae from bottles.
class BottleLoader < FormulaLoader class BottleLoader < FormulaLoader
def initialize bottle_name def initialize(bottle_name)
@bottle_filename = Pathname(bottle_name).realpath @bottle_filename = Pathname(bottle_name).realpath
name, full_name = bottle_resolve_formula_names @bottle_filename name, full_name = bottle_resolve_formula_names @bottle_filename
super name, Formulary.path(full_name) super name, Formulary.path(full_name)
@ -100,7 +100,7 @@ class Formulary
end end
class AliasLoader < FormulaLoader class AliasLoader < FormulaLoader
def initialize alias_path def initialize(alias_path)
path = alias_path.resolved_path path = alias_path.resolved_path
name = path.basename(".rb").to_s name = path.basename(".rb").to_s
super name, path super name, path
@ -109,7 +109,7 @@ class Formulary
# Loads formulae from disk using a path # Loads formulae from disk using a path
class FromPathLoader < FormulaLoader class FromPathLoader < FormulaLoader
def initialize path def initialize(path)
path = Pathname.new(path).expand_path path = Pathname.new(path).expand_path
super path.basename(".rb").to_s, path super path.basename(".rb").to_s, path
end end
@ -119,7 +119,7 @@ class Formulary
class FromUrlLoader < FormulaLoader class FromUrlLoader < FormulaLoader
attr_reader :url attr_reader :url
def initialize url def initialize(url)
@url = url @url = url
uri = URI(url) uri = URI(url)
formula = File.basename(uri.path, ".rb") formula = File.basename(uri.path, ".rb")
@ -138,7 +138,7 @@ class Formulary
class TapLoader < FormulaLoader class TapLoader < FormulaLoader
attr_reader :tap attr_reader :tap
def initialize tapped_name def initialize(tapped_name)
user, repo, name = tapped_name.split("/", 3).map(&:downcase) user, repo, name = tapped_name.split("/", 3).map(&:downcase)
@tap = Tap.new user, repo.sub(/^homebrew-/, "") @tap = Tap.new user, repo.sub(/^homebrew-/, "")
path = @tap.formula_files.detect { |file| file.basename(".rb").to_s == name } path = @tap.formula_files.detect { |file| file.basename(".rb").to_s == name }
@ -159,7 +159,7 @@ class Formulary
super name, Formulary.core_path(name) super name, Formulary.core_path(name)
end end
def get_formula(spec) def get_formula(_spec)
raise FormulaUnavailableError.new(name) raise FormulaUnavailableError.new(name)
end end
end end
@ -170,13 +170,13 @@ class Formulary
# * a formula pathname # * a formula pathname
# * a formula URL # * a formula URL
# * a local bottle reference # * a local bottle reference
def self.factory(ref, spec=:stable) def self.factory(ref, spec = :stable)
loader_for(ref).get_formula(spec) loader_for(ref).get_formula(spec)
end end
# Return a Formula instance for the given rack. # Return a Formula instance for the given rack.
# It will auto resolve formula's spec when requested spec is nil # It will auto resolve formula's spec when requested spec is nil
def self.from_rack(rack, spec=nil) def self.from_rack(rack, spec = nil)
kegs = rack.directory? ? rack.subdirs.map { |d| Keg.new(d) } : [] kegs = rack.directory? ? rack.subdirs.map { |d| Keg.new(d) } : []
keg = kegs.detect(&:linked?) || kegs.detect(&:optlinked?) || kegs.max_by(&:version) keg = kegs.detect(&:linked?) || kegs.detect(&:optlinked?) || kegs.max_by(&:version)
@ -207,7 +207,7 @@ class Formulary
def self.loader_for(ref) def self.loader_for(ref)
case ref case ref
when %r[(https?|ftp)://] when %r{(https?|ftp)://}
return FromUrlLoader.new(ref) return FromUrlLoader.new(ref)
when Pathname::BOTTLE_EXTNAME_RX when Pathname::BOTTLE_EXTNAME_RX
return BottleLoader.new(ref) return BottleLoader.new(ref)
@ -241,7 +241,7 @@ class Formulary
return FormulaLoader.new(ref, possible_cached_formula) return FormulaLoader.new(ref, possible_cached_formula)
end end
return NullLoader.new(ref) NullLoader.new(ref)
end end
def self.core_path(name) def self.core_path(name)
@ -254,7 +254,7 @@ class Formulary
Pathname.glob([ Pathname.glob([
"#{tap}Formula/#{name}.rb", "#{tap}Formula/#{name}.rb",
"#{tap}HomebrewFormula/#{name}.rb", "#{tap}HomebrewFormula/#{name}.rb",
"#{tap}#{name}.rb", "#{tap}#{name}.rb"
]).detect(&:file?) ]).detect(&:file?)
end.compact end.compact
end end

View File

@ -1,18 +1,18 @@
require 'extend/module' require "extend/module"
require 'extend/fileutils' require "extend/fileutils"
require 'extend/pathname' require "extend/pathname"
require 'extend/ARGV' require "extend/ARGV"
require 'extend/string' require "extend/string"
require 'os' require "os"
require 'utils' require "utils"
require 'exceptions' require "exceptions"
require 'set' require "set"
require 'rbconfig' require "rbconfig"
ARGV.extend(HomebrewArgvExtension) ARGV.extend(HomebrewArgvExtension)
HOMEBREW_VERSION = '0.9.5' HOMEBREW_VERSION = "0.9.5"
HOMEBREW_WWW = 'http://brew.sh' HOMEBREW_WWW = "http://brew.sh"
require "config" require "config"
@ -37,9 +37,9 @@ end
HOMEBREW_GITHUB_API_TOKEN = ENV["HOMEBREW_GITHUB_API_TOKEN"] HOMEBREW_GITHUB_API_TOKEN = ENV["HOMEBREW_GITHUB_API_TOKEN"]
HOMEBREW_USER_AGENT = "Homebrew #{HOMEBREW_VERSION} (Ruby #{RUBY_VERSION}-#{RUBY_PATCHLEVEL}; #{OS_VERSION})" HOMEBREW_USER_AGENT = "Homebrew #{HOMEBREW_VERSION} (Ruby #{RUBY_VERSION}-#{RUBY_PATCHLEVEL}; #{OS_VERSION})"
HOMEBREW_CURL_ARGS = '-f#LA' HOMEBREW_CURL_ARGS = "-f#LA"
require 'tap_constants' require "tap_constants"
module Homebrew module Homebrew
include FileUtils include FileUtils
@ -51,23 +51,23 @@ end
HOMEBREW_PULL_OR_COMMIT_URL_REGEX = %r[https://github\.com/([\w-]+)/homebrew(-[\w-]+)?/(?:pull/(\d+)|commit/[0-9a-fA-F]{4,40})] HOMEBREW_PULL_OR_COMMIT_URL_REGEX = %r[https://github\.com/([\w-]+)/homebrew(-[\w-]+)?/(?:pull/(\d+)|commit/[0-9a-fA-F]{4,40})]
require 'compat' unless ARGV.include? "--no-compat" or ENV['HOMEBREW_NO_COMPAT'] require "compat" unless ARGV.include?("--no-compat") || ENV["HOMEBREW_NO_COMPAT"]
ORIGINAL_PATHS = ENV['PATH'].split(File::PATH_SEPARATOR).map{ |p| Pathname.new(p).expand_path rescue nil }.compact.freeze ORIGINAL_PATHS = ENV["PATH"].split(File::PATH_SEPARATOR).map { |p| Pathname.new(p).expand_path rescue nil }.compact.freeze
HOMEBREW_INTERNAL_COMMAND_ALIASES = { HOMEBREW_INTERNAL_COMMAND_ALIASES = {
'ls' => 'list', "ls" => "list",
'homepage' => 'home', "homepage" => "home",
'-S' => 'search', "-S" => "search",
'up' => 'update', "up" => "update",
'ln' => 'link', "ln" => "link",
'instal' => 'install', # gem does the same "instal" => "install", # gem does the same
'rm' => 'uninstall', "rm" => "uninstall",
'remove' => 'uninstall', "remove" => "uninstall",
'configure' => 'diy', "configure" => "diy",
'abv' => 'info', "abv" => "info",
'dr' => 'doctor', "dr" => "doctor",
'--repo' => '--repository', "--repo" => "--repository",
'environment' => '--env', "environment" => "--env",
'--config' => 'config', "--config" => "config"
} }

View File

@ -1,7 +1,8 @@
require 'os' require "os"
class Hardware class Hardware
module CPU extend self module CPU
extend self
INTEL_32BIT_ARCHS = [:i386].freeze INTEL_32BIT_ARCHS = [:i386].freeze
INTEL_64BIT_ARCHS = [:x86_64].freeze INTEL_64BIT_ARCHS = [:x86_64].freeze
PPC_32BIT_ARCHS = [:ppc, :ppc7400, :ppc7450, :ppc970].freeze PPC_32BIT_ARCHS = [:ppc, :ppc7400, :ppc7450, :ppc970].freeze
@ -49,10 +50,10 @@ class Hardware
end end
if OS.mac? if OS.mac?
require 'os/mac/hardware' require "os/mac/hardware"
CPU.extend MacCPUs CPU.extend MacCPUs
elsif OS.linux? elsif OS.linux?
require 'os/linux/hardware' require "os/linux/hardware"
CPU.extend LinuxCPUs CPU.extend LinuxCPUs
else else
raise "The system `#{`uname`.chomp}' is not supported." raise "The system `#{`uname`.chomp}' is not supported."
@ -60,9 +61,9 @@ class Hardware
def self.cores_as_words def self.cores_as_words
case Hardware::CPU.cores case Hardware::CPU.cores
when 1 then 'single' when 1 then "single"
when 2 then 'dual' when 2 then "dual"
when 4 then 'quad' when 4 then "quad"
else else
Hardware::CPU.cores Hardware::CPU.cores
end end

View File

@ -7,12 +7,12 @@
module Homebrew module Homebrew
module Hooks module Hooks
module Bottles module Bottles
def self.setup_formula_has_bottle &block def self.setup_formula_has_bottle(&block)
@has_bottle = block @has_bottle = block
true true
end end
def self.setup_pour_formula_bottle &block def self.setup_pour_formula_bottle(&block)
@pour_bottle = block @pour_bottle = block
true true
end end

View File

@ -9,17 +9,17 @@ module InstallRenamed
end end
end end
def cp_path_sub pattern, replacement def cp_path_sub(pattern, replacement)
super do |src, dst| super do |src, dst|
append_default_if_different(src, dst) append_default_if_different(src, dst)
end end
end end
def + path def +(path)
super(path).extend(InstallRenamed) super(path).extend(InstallRenamed)
end end
def / path def /(path)
super(path).extend(InstallRenamed) super(path).extend(InstallRenamed)
end end

View File

@ -63,10 +63,10 @@ class Keg
# locale-specific directories have the form language[_territory][.codeset][@modifier] # locale-specific directories have the form language[_territory][.codeset][@modifier]
LOCALEDIR_RX = /(locale|man)\/([a-z]{2}|C|POSIX)(_[A-Z]{2})?(\.[a-zA-Z\-0-9]+(@.+)?)?/ LOCALEDIR_RX = /(locale|man)\/([a-z]{2}|C|POSIX)(_[A-Z]{2})?(\.[a-zA-Z\-0-9]+(@.+)?)?/
INFOFILE_RX = %r[info/([^.].*?\.info|dir)$] INFOFILE_RX = %r{info/([^.].*?\.info|dir)$}
TOP_LEVEL_DIRECTORIES = %w[bin etc include lib sbin share var Frameworks] TOP_LEVEL_DIRECTORIES = %w[bin etc include lib sbin share var Frameworks]
PRUNEABLE_DIRECTORIES = %w[bin etc include lib sbin share Frameworks LinkedKegs].map do |d| PRUNEABLE_DIRECTORIES = %w[bin etc include lib sbin share Frameworks LinkedKegs].map do |d|
case d when 'LinkedKegs' then HOMEBREW_LIBRARY/d else HOMEBREW_PREFIX/d end case d when "LinkedKegs" then HOMEBREW_LIBRARY/d else HOMEBREW_PREFIX/d end
end end
# These paths relative to the keg's share directory should always be real # These paths relative to the keg's share directory should always be real
@ -82,9 +82,9 @@ class Keg
] ]
# if path is a file in a keg then this will return the containing Keg object # if path is a file in a keg then this will return the containing Keg object
def self.for path def self.for(path)
path = path.realpath path = path.realpath
while not path.root? until path.root?
return Keg.new(path) if path.parent.parent == HOMEBREW_CELLAR.realpath return Keg.new(path) if path.parent.parent == HOMEBREW_CELLAR.realpath
path = path.parent.realpath # realpath() prevents root? failing path = path.parent.realpath # realpath() prevents root? failing
end end
@ -94,7 +94,7 @@ class Keg
attr_reader :path, :name, :linked_keg_record, :opt_record attr_reader :path, :name, :linked_keg_record, :opt_record
protected :path protected :path
def initialize path def initialize(path)
raise "#{path} is not a valid keg" unless path.parent.parent.realpath == HOMEBREW_CELLAR.realpath raise "#{path} is not a valid keg" unless path.parent.parent.realpath == HOMEBREW_CELLAR.realpath
raise "#{path} is not a directory" unless path.directory? raise "#{path} is not a directory" unless path.directory?
@path = path @path = path
@ -190,7 +190,7 @@ class Keg
dirs = [] dirs = []
TOP_LEVEL_DIRECTORIES.map{ |d| path.join(d) }.each do |dir| TOP_LEVEL_DIRECTORIES.map { |d| path.join(d) }.each do |dir|
next unless dir.exist? next unless dir.exist?
dir.find do |src| dir.find do |src|
dst = HOMEBREW_PREFIX + src.relative_path_from(path) dst = HOMEBREW_PREFIX + src.relative_path_from(path)
@ -218,7 +218,7 @@ class Keg
FormulaLock.new(name).with_lock { yield } FormulaLock.new(name).with_lock { yield }
end end
def completion_installed? shell def completion_installed?(shell)
dir = case shell dir = case shell
when :bash then path.join("etc", "bash_completion.d") when :bash then path.join("etc", "bash_completion.d")
when :zsh then path.join("share", "zsh", "site-functions") when :zsh then path.join("share", "zsh", "site-functions")
@ -248,7 +248,7 @@ class Keg
end end
def version def version
require 'pkg_version' require "pkg_version"
PkgVersion.parse(path.basename.to_s) PkgVersion.parse(path.basename.to_s)
end end
@ -256,21 +256,21 @@ class Keg
path.find(*args, &block) path.find(*args, &block)
end end
def link mode=OpenStruct.new def link(mode = OpenStruct.new)
raise AlreadyLinkedError.new(self) if linked_keg_record.directory? raise AlreadyLinkedError.new(self) if linked_keg_record.directory?
ObserverPathnameExtension.reset_counts! ObserverPathnameExtension.reset_counts!
# yeah indeed, you have to force anything you need in the main tree into # yeah indeed, you have to force anything you need in the main tree into
# these dirs REMEMBER that *NOT* everything needs to be in the main tree # these dirs REMEMBER that *NOT* everything needs to be in the main tree
link_dir('etc', mode) {:mkpath} link_dir("etc", mode) { :mkpath }
link_dir('bin', mode) {:skip_dir} link_dir("bin", mode) { :skip_dir }
link_dir('sbin', mode) {:skip_dir} link_dir("sbin", mode) { :skip_dir }
link_dir('include', mode) {:link} link_dir("include", mode) { :link }
link_dir('share', mode) do |relative_path| link_dir("share", mode) do |relative_path|
case relative_path.to_s case relative_path.to_s
when 'locale/locale.alias' then :skip_file when "locale/locale.alias" then :skip_file
when INFOFILE_RX then :info when INFOFILE_RX then :info
when LOCALEDIR_RX then :mkpath when LOCALEDIR_RX then :mkpath
when *SHARE_PATHS then :mkpath when *SHARE_PATHS then :mkpath
@ -283,22 +283,22 @@ class Keg
end end
end end
link_dir('lib', mode) do |relative_path| link_dir("lib", mode) do |relative_path|
case relative_path.to_s case relative_path.to_s
when 'charset.alias' then :skip_file when "charset.alias" then :skip_file
# pkg-config database gets explicitly created # pkg-config database gets explicitly created
when 'pkgconfig' then :mkpath when "pkgconfig" then :mkpath
# cmake database gets explicitly created # cmake database gets explicitly created
when 'cmake' then :mkpath when "cmake" then :mkpath
# lib/language folders also get explicitly created # lib/language folders also get explicitly created
when 'dtrace' then :mkpath when "dtrace" then :mkpath
when /^gdk-pixbuf/ then :mkpath when /^gdk-pixbuf/ then :mkpath
when 'ghc' then :mkpath when "ghc" then :mkpath
when 'lua' then :mkpath when "lua" then :mkpath
when /^node/ then :mkpath when /^node/ then :mkpath
when /^ocaml/ then :mkpath when /^ocaml/ then :mkpath
when /^perl5/ then :mkpath when /^perl5/ then :mkpath
when 'php' then :mkpath when "php" then :mkpath
when /^python[23]\.\d/ then :mkpath when /^python[23]\.\d/ then :mkpath
when /^ruby/ then :mkpath when /^ruby/ then :mkpath
# Everything else is symlinked to the cellar # Everything else is symlinked to the cellar
@ -306,7 +306,7 @@ class Keg
end end
end end
link_dir('Frameworks', mode) do |relative_path| link_dir("Frameworks", mode) do |relative_path|
# Frameworks contain symlinks pointing into a subdir, so we have to use # Frameworks contain symlinks pointing into a subdir, so we have to use
# the :link strategy. However, for Foo.framework and # the :link strategy. However, for Foo.framework and
# Foo.framework/Versions we have to use :mkpath so that multiple formulae # Foo.framework/Versions we have to use :mkpath so that multiple formulae
@ -329,7 +329,7 @@ class Keg
ObserverPathnameExtension.total ObserverPathnameExtension.total
end end
def optlink(mode=OpenStruct.new) def optlink(mode = OpenStruct.new)
opt_record.delete if opt_record.symlink? || opt_record.exist? opt_record.delete if opt_record.symlink? || opt_record.exist?
make_relative_symlink(opt_record, path, mode) make_relative_symlink(opt_record, path, mode)
end end
@ -340,7 +340,7 @@ class Keg
private private
def resolve_any_conflicts dst, mode def resolve_any_conflicts(dst, mode)
return unless dst.symlink? return unless dst.symlink?
src = dst.resolved_path src = dst.resolved_path
@ -371,14 +371,14 @@ class Keg
end end
end end
def make_relative_symlink dst, src, mode def make_relative_symlink(dst, src, mode)
if dst.symlink? && src == dst.resolved_path if dst.symlink? && src == dst.resolved_path
puts "Skipping; link already exists: #{dst}" if ARGV.verbose? puts "Skipping; link already exists: #{dst}" if ARGV.verbose?
return return
end end
# cf. git-clean -n: list files to delete, don't really link or delete # cf. git-clean -n: list files to delete, don't really link or delete
if mode.dry_run and mode.overwrite if mode.dry_run && mode.overwrite
if dst.symlink? if dst.symlink?
puts "#{dst} -> #{dst.resolved_path}" puts "#{dst} -> #{dst.resolved_path}"
elsif dst.exist? elsif dst.exist?
@ -411,7 +411,7 @@ class Keg
protected protected
# symlinks the contents of path+relative_dir recursively into #{HOMEBREW_PREFIX}/relative_dir # symlinks the contents of path+relative_dir recursively into #{HOMEBREW_PREFIX}/relative_dir
def link_dir relative_dir, mode def link_dir(relative_dir, mode)
root = path+relative_dir root = path+relative_dir
return unless root.exist? return unless root.exist?
root.find do |src| root.find do |src|
@ -420,10 +420,10 @@ class Keg
dst.extend ObserverPathnameExtension dst.extend ObserverPathnameExtension
if src.symlink? || src.file? if src.symlink? || src.file?
Find.prune if File.basename(src) == '.DS_Store' Find.prune if File.basename(src) == ".DS_Store"
# Don't link pyc files because Python overwrites these cached object # Don't link pyc files because Python overwrites these cached object
# files and next time brew wants to link, the pyc file is in the way. # files and next time brew wants to link, the pyc file is in the way.
if src.extname == '.pyc' && src.to_s =~ /site-packages/ if src.extname == ".pyc" && src.to_s =~ /site-packages/
Find.prune Find.prune
end end
@ -431,7 +431,7 @@ class Keg
when :skip_file, nil when :skip_file, nil
Find.prune Find.prune
when :info when :info
next if File.basename(src) == 'dir' # skip historical local 'dir' files next if File.basename(src) == "dir" # skip historical local 'dir' files
make_relative_symlink dst, src, mode make_relative_symlink dst, src, mode
dst.install_info dst.install_info
else else
@ -439,10 +439,10 @@ class Keg
end end
elsif src.directory? elsif src.directory?
# if the dst dir already exists, then great! walk the rest of the tree tho # if the dst dir already exists, then great! walk the rest of the tree tho
next if dst.directory? and not dst.symlink? next if dst.directory? && !dst.symlink?
# no need to put .app bundles in the path, the user can just use # no need to put .app bundles in the path, the user can just use
# spotlight, or the open command and actual mac apps use an equivalent # spotlight, or the open command and actual mac apps use an equivalent
Find.prune if src.extname == '.app' Find.prune if src.extname == ".app"
case yield src.relative_path_from(root) case yield src.relative_path_from(root)
when :skip_dir when :skip_dir

View File

@ -2,14 +2,14 @@ class Keg
PREFIX_PLACEHOLDER = "@@HOMEBREW_PREFIX@@".freeze PREFIX_PLACEHOLDER = "@@HOMEBREW_PREFIX@@".freeze
CELLAR_PLACEHOLDER = "@@HOMEBREW_CELLAR@@".freeze CELLAR_PLACEHOLDER = "@@HOMEBREW_CELLAR@@".freeze
def fix_install_names options={} def fix_install_names(options = {})
mach_o_files.each do |file| mach_o_files.each do |file|
file.ensure_writable do file.ensure_writable do
change_dylib_id(dylib_id_for(file, options), file) if file.dylib? change_dylib_id(dylib_id_for(file, options), file) if file.dylib?
each_install_name_for(file) do |bad_name| each_install_name_for(file) do |bad_name|
# Don't fix absolute paths unless they are rooted in the build directory # Don't fix absolute paths unless they are rooted in the build directory
next if bad_name.start_with? '/' and not bad_name.start_with? HOMEBREW_TEMP.to_s next if bad_name.start_with? "/" and !bad_name.start_with? HOMEBREW_TEMP.to_s
new_name = fixed_name(file, bad_name) new_name = fixed_name(file, bad_name)
change_install_name(bad_name, new_name, file) unless new_name == bad_name change_install_name(bad_name, new_name, file) unless new_name == bad_name
@ -18,7 +18,7 @@ class Keg
end end
end end
def relocate_install_names old_prefix, new_prefix, old_cellar, new_cellar, options={} def relocate_install_names(old_prefix, new_prefix, old_cellar, new_cellar, options = {})
mach_o_files.each do |file| mach_o_files.each do |file|
file.ensure_writable do file.ensure_writable do
if file.dylib? if file.dylib?
@ -71,7 +71,7 @@ class Keg
# of the files within the keg. # of the files within the keg.
# Note that this doesn't attempt to distinguish between libstdc++ versions, # Note that this doesn't attempt to distinguish between libstdc++ versions,
# for instance between Apple libstdc++ and GNU libstdc++ # for instance between Apple libstdc++ and GNU libstdc++
def detect_cxx_stdlibs(options={}) def detect_cxx_stdlibs(options = {})
skip_executables = options.fetch(:skip_executables, false) skip_executables = options.fetch(:skip_executables, false)
results = Set.new results = Set.new
@ -85,7 +85,7 @@ class Keg
results.to_a results.to_a
end end
def each_unique_file_matching string def each_unique_file_matching(string)
Utils.popen_read("/usr/bin/fgrep", "-lr", string, to_s) do |io| Utils.popen_read("/usr/bin/fgrep", "-lr", string, to_s) do |io|
hardlinks = Set.new hardlinks = Set.new
@ -99,7 +99,7 @@ class Keg
def install_name_tool(*args) def install_name_tool(*args)
tool = MacOS.locate("install_name_tool") tool = MacOS.locate("install_name_tool")
system(tool, *args) or raise ErrorDuringExecution.new(tool, args) system(tool, *args) || raise(ErrorDuringExecution.new(tool, args))
end end
# If file is a dylib or bundle itself, look for the dylib named by # If file is a dylib or bundle itself, look for the dylib named by
@ -126,7 +126,7 @@ class Keg
path.join("lib") path.join("lib")
end end
def each_install_name_for file, &block def each_install_name_for(file, &block)
dylibs = file.dynamically_linked_libraries dylibs = file.dynamically_linked_libraries
dylibs.reject! { |fn| fn =~ /^@(loader_|executable_|r)path/ } dylibs.reject! { |fn| fn =~ /^@(loader_|executable_|r)path/ }
dylibs.each(&block) dylibs.each(&block)
@ -139,22 +139,22 @@ class Keg
relative_dirname = file.dirname.relative_path_from(path) relative_dirname = file.dirname.relative_path_from(path)
shortpath = HOMEBREW_PREFIX.join(relative_dirname, basename) shortpath = HOMEBREW_PREFIX.join(relative_dirname, basename)
if shortpath.exist? and not options[:keg_only] if shortpath.exist? && !options[:keg_only]
shortpath.to_s shortpath.to_s
else else
opt_record.join(relative_dirname, basename).to_s opt_record.join(relative_dirname, basename).to_s
end end
end end
def find_dylib name def find_dylib(name)
lib.find { |pn| break pn if pn.basename == name } if lib.directory? lib.find { |pn| break pn if pn.basename == name } if lib.directory?
end end
def mach_o_files def mach_o_files
mach_o_files = [] mach_o_files = []
path.find do |pn| path.find do |pn|
next if pn.symlink? or pn.directory? next if pn.symlink? || pn.directory?
mach_o_files << pn if pn.dylib? or pn.mach_o_bundle? or pn.mach_o_executable? mach_o_files << pn if pn.dylib? || pn.mach_o_bundle? || pn.mach_o_executable?
end end
mach_o_files mach_o_files
@ -163,10 +163,10 @@ class Keg
def text_files def text_files
text_files = [] text_files = []
path.find do |pn| path.find do |pn|
next if pn.symlink? or pn.directory? next if pn.symlink? || pn.directory?
next if Metafiles::EXTENSIONS.include? pn.extname next if Metafiles::EXTENSIONS.include? pn.extname
if Utils.popen_read("/usr/bin/file", "--brief", pn).include?("text") || if Utils.popen_read("/usr/bin/file", "--brief", pn).include?("text") ||
pn.text_executable? pn.text_executable?
text_files << pn text_files << pn
end end
end end
@ -179,7 +179,7 @@ class Keg
# find .la files, which are stored in lib/ # find .la files, which are stored in lib/
lib.find do |pn| lib.find do |pn|
next if pn.symlink? or pn.directory? or pn.extname != '.la' next if pn.symlink? || pn.directory? || pn.extname != ".la"
libtool_files << pn libtool_files << pn
end if lib.directory? end if lib.directory?
libtool_files libtool_files

View File

@ -6,7 +6,7 @@ module Language
# building go software. # building go software.
# The resource names should be the import name of the package, # The resource names should be the import name of the package,
# e.g. `resource "github.com/foo/bar"` # e.g. `resource "github.com/foo/bar"`
def self.stage_deps resources, target def self.stage_deps(resources, target)
resources.grep(Resource::Go) { |resource| resource.stage(target) } resources.grep(Resource::Go) { |resource| resource.stage(target) }
end end
end end

View File

@ -9,7 +9,7 @@ module Language
end end
end end
def self.included base def self.included(base)
base.extend ClassMethods base.extend ClassMethods
end end
@ -23,7 +23,7 @@ module Language
ENV["HOME"] = pwd ENV["HOME"] = pwd
# use cabal's sandbox feature if available # use cabal's sandbox feature if available
cabal_version = `cabal --version`[/[0-9.]+/].split('.').collect(&:to_i) cabal_version = `cabal --version`[/[0-9.]+/].split(".").collect(&:to_i)
if (cabal_version <=> [1, 20]) > -1 if (cabal_version <=> [1, 20]) > -1
system "cabal", "sandbox", "init" system "cabal", "sandbox", "init"
cabal_sandbox_bin = pwd/".cabal-sandbox/bin" cabal_sandbox_bin = pwd/".cabal-sandbox/bin"
@ -34,7 +34,7 @@ module Language
# cabal may build useful tools that should be found in the PATH # cabal may build useful tools that should be found in the PATH
mkdir_p cabal_sandbox_bin mkdir_p cabal_sandbox_bin
path = ENV["PATH"] path = ENV["PATH"]
ENV.prepend_path 'PATH', cabal_sandbox_bin ENV.prepend_path "PATH", cabal_sandbox_bin
# update cabal package database # update cabal package database
system "cabal", "update" system "cabal", "update"
yield yield
@ -55,7 +55,7 @@ module Language
# package. The tools are installed sequentially in order to make possible # package. The tools are installed sequentially in order to make possible
# to install several tools that depends on each other # to install several tools that depends on each other
def cabal_install_tools(*opts) def cabal_install_tools(*opts)
opts.each {|t| cabal_install t} opts.each { |t| cabal_install t }
rm_rf Dir[".cabal*/*packages.conf.d/"] rm_rf Dir[".cabal*/*packages.conf.d/"]
end end
@ -66,7 +66,7 @@ module Language
rm_rf lib rm_rf lib
end end
def install_cabal_package args=[] def install_cabal_package(args = [])
cabal_sandbox do cabal_sandbox do
# the dependencies are built first and installed locally, and only the # the dependencies are built first and installed locally, and only the
# current package is actually installed in the destination dir # current package is actually installed in the destination dir

View File

@ -1,15 +1,15 @@
module Language module Language
module Java module Java
def self.java_home_cmd(version=nil) def self.java_home_cmd(version = nil)
version_flag = " --version #{version}" if version version_flag = " --version #{version}" if version
"/usr/libexec/java_home#{version_flag}" "/usr/libexec/java_home#{version_flag}"
end end
def self.java_home_env(version=nil) def self.java_home_env(version = nil)
{ :JAVA_HOME => "$(#{java_home_cmd(version)})" } { :JAVA_HOME => "$(#{java_home_cmd(version)})" }
end end
def self.overridable_java_home_env(version=nil) def self.overridable_java_home_env(version = nil)
{ :JAVA_HOME => "${JAVA_HOME:-$(#{java_home_cmd(version)})}" } { :JAVA_HOME => "${JAVA_HOME:-$(#{java_home_cmd(version)})}" }
end end
end end

View File

@ -2,21 +2,21 @@ require "utils.rb"
module Language module Language
module Python module Python
def self.major_minor_version python def self.major_minor_version(python)
version = /\d\.\d/.match `#{python} --version 2>&1` version = /\d\.\d/.match `#{python} --version 2>&1`
return unless version return unless version
Version.new(version.to_s) Version.new(version.to_s)
end end
def self.homebrew_site_packages(version="2.7") def self.homebrew_site_packages(version = "2.7")
HOMEBREW_PREFIX/"lib/python#{version}/site-packages" HOMEBREW_PREFIX/"lib/python#{version}/site-packages"
end end
def self.each_python build, &block def self.each_python(build, &block)
original_pythonpath = ENV["PYTHONPATH"] original_pythonpath = ENV["PYTHONPATH"]
["python", "python3"].each do |python| ["python", "python3"].each do |python|
next if build.without? python next if build.without? python
version = self.major_minor_version python version = major_minor_version python
ENV["PYTHONPATH"] = if Formulary.factory(python).installed? ENV["PYTHONPATH"] = if Formulary.factory(python).installed?
nil nil
else else
@ -27,7 +27,7 @@ module Language
ENV["PYTHONPATH"] = original_pythonpath ENV["PYTHONPATH"] = original_pythonpath
end end
def self.reads_brewed_pth_files? python def self.reads_brewed_pth_files?(python)
version = major_minor_version python version = major_minor_version python
return unless homebrew_site_packages(version).directory? return unless homebrew_site_packages(version).directory?
return unless homebrew_site_packages(version).writable_real? return unless homebrew_site_packages(version).writable_real?
@ -40,11 +40,11 @@ module Language
end end
end end
def self.user_site_packages python def self.user_site_packages(python)
Pathname.new(`#{python} -c "import site; print(site.getusersitepackages())"`.chomp) Pathname.new(`#{python} -c "import site; print(site.getusersitepackages())"`.chomp)
end end
def self.in_sys_path? python, path def self.in_sys_path?(python, path)
script = <<-EOS.undent script = <<-EOS.undent
import os, sys import os, sys
[os.path.realpath(p) for p in sys.path].index(os.path.realpath("#{path}")) [os.path.realpath(p) for p in sys.path].index(os.path.realpath("#{path}"))
@ -53,7 +53,7 @@ module Language
end end
# deprecated; use system "python", *setup_install_args(prefix) instead # deprecated; use system "python", *setup_install_args(prefix) instead
def self.setup_install python, prefix, *args def self.setup_install(python, prefix, *args)
opoo <<-EOS.undent opoo <<-EOS.undent
Language::Python.setup_install is deprecated. Language::Python.setup_install is deprecated.
If you are a formula author, please use If you are a formula author, please use
@ -75,7 +75,7 @@ module Language
system python, "-c", shim, "install", *args system python, "-c", shim, "install", *args
end end
def self.setup_install_args prefix def self.setup_install_args(prefix)
shim = <<-EOS.undent shim = <<-EOS.undent
import setuptools, tokenize import setuptools, tokenize
__file__ = 'setup.py' __file__ = 'setup.py'
@ -93,7 +93,7 @@ module Language
] ]
end end
def self.package_available? python, module_name def self.package_available?(python, module_name)
quiet_system python, "-c", "import #{module_name}" quiet_system python, "-c", "import #{module_name}"
end end
end end

View File

@ -1,10 +1,10 @@
require 'dependency' require "dependency"
# This special dependency ensures that the Tigerbrew ld64 # This special dependency ensures that the Tigerbrew ld64
# formula is used as gcc's ld in place of the old version # formula is used as gcc's ld in place of the old version
# that comes with the OS. # that comes with the OS.
class LD64Dependency < Dependency class LD64Dependency < Dependency
def initialize(name='ld64', tags=[:build], env_proc=nil) def initialize(name = "ld64", tags = [:build], env_proc = nil)
super super
@env_proc = proc { ENV.ld64 } @env_proc = proc { ENV.ld64 }
end end

View File

@ -21,26 +21,26 @@ module ArchitectureListExtension
end end
def ppc? def ppc?
(Hardware::CPU::PPC_32BIT_ARCHS+Hardware::CPU::PPC_64BIT_ARCHS).any? {|a| self.include? a} (Hardware::CPU::PPC_32BIT_ARCHS+Hardware::CPU::PPC_64BIT_ARCHS).any? { |a| self.include? a }
end end
def remove_ppc! def remove_ppc!
(Hardware::CPU::PPC_32BIT_ARCHS+Hardware::CPU::PPC_64BIT_ARCHS).each {|a| self.delete a} (Hardware::CPU::PPC_32BIT_ARCHS+Hardware::CPU::PPC_64BIT_ARCHS).each { |a| delete a }
end end
def as_arch_flags def as_arch_flags
self.collect{ |a| "-arch #{a}" }.join(' ') collect { |a| "-arch #{a}" }.join(" ")
end end
def as_cmake_arch_flags def as_cmake_arch_flags
self.join(';') join(";")
end end
protected protected
def intersects_all?(*set) def intersects_all?(*set)
set.all? do |archset| set.all? do |archset|
archset.any? {|a| self.include? a} archset.any? { |a| self.include? a }
end end
end end
end end
@ -101,7 +101,7 @@ module MachO
end end
def archs def archs
mach_data.map{ |m| m.fetch :arch }.extend(ArchitectureListExtension) mach_data.map { |m| m.fetch :arch }.extend(ArchitectureListExtension)
end end
def arch def arch

Some files were not shown because too many files have changed in this diff Show More