-# Subject: Addressing Needs
-#
-# Community:
-#
-# Just wanted to send a quick note assuring that your needs are being addressed.
-#
-# I want you to know that my team will keep working on the issues, especially:
-#
-# * Run Ruby Quiz
-# * Document Modules
-# * Answer Questions on Ruby Talk
-#
-# Thanks for your patience.
-#
-# James Edward Gray II
-#
-# === Ruby in HTML
-#
-# ERB is often used in .rhtml files (HTML with embedded Ruby). Notice the need in
-# this example to provide a special binding when the template is run, so that the instance
-# variables in the Product object can be resolved.
-#
-# require "erb"
-#
-# # Build template data class.
-# class Product
-# def initialize( code, name, desc, cost )
-# @code = code
-# @name = name
-# @desc = desc
-# @cost = cost
-#
-# @features = [ ]
-# end
-#
-# def add_feature( feature )
-# @features << feature
-# end
-#
-# # Support templating of member data.
-# def get_binding
-# binding
-# end
-#
-# # ...
-# end
-#
-# # Create template.
-# template = %{
-#
-# Ruby Toys -- <%= @name %>
-#
-#
-# <%= @name %> (<%= @code %>)
-# <%= @desc %>
-#
-#
-# <% @features.each do |f| %>
-# - <%= f %>
-# <% end %>
-#
-#
-#
-# <% if @cost < 10 %>
-# Only <%= @cost %>!!!
-# <% else %>
-# Call for a price, today!
-# <% end %>
-#
-#
-#
-#
-# }.gsub(/^ /, '')
-#
-# rhtml = ERB.new(template)
-#
-# # Set up template data.
-# toy = Product.new( "TZ-1002",
-# "Rubysapien",
-# "Geek's Best Friend! Responds to Ruby commands...",
-# 999.95 )
-# toy.add_feature("Listens for verbal commands in the Ruby language!")
-# toy.add_feature("Ignores Perl, Java, and all C variants.")
-# toy.add_feature("Karate-Chop Action!!!")
-# toy.add_feature("Matz signature on left leg.")
-# toy.add_feature("Gem studded eyes... Rubies, of course!")
-#
-# # Produce result.
-# rhtml.run(toy.get_binding)
-#
-# Generates (some blank lines removed):
-#
-#
-# Ruby Toys -- Rubysapien
-#
-#
-# Rubysapien (TZ-1002)
-# Geek's Best Friend! Responds to Ruby commands...
-#
-#
-# - Listens for verbal commands in the Ruby language!
-# - Ignores Perl, Java, and all C variants.
-# - Karate-Chop Action!!!
-# - Matz signature on left leg.
-# - Gem studded eyes... Rubies, of course!
-#
-#
-#
-# Call for a price, today!
-#
-#
-#
-#
-#
-#
-# == Notes
-#
-# There are a variety of templating solutions available in various Ruby projects:
-# * ERB's big brother, eRuby, works the same but is written in C for speed;
-# * Amrita (smart at producing HTML/XML);
-# * cs/Template (written in C for speed);
-# * RDoc, distributed with Ruby, uses its own template engine, which can be reused elsewhere;
-# * and others; search {RubyGems.org}[https://rubygems.org/] or
-# {The Ruby Toolbox}[https://www.ruby-toolbox.com/].
-#
-# Rails, the web application framework, uses ERB to create views.
-#
-class ERB
- Revision = '$Date:: 2014-12-12 19:48:57 +0900#$' # :nodoc: #'
-
- # Returns revision information for the erb.rb module.
- def self.version
- "erb.rb [2.1.0 #{ERB::Revision.split[1]}]"
- end
-end
-
-#--
-# ERB::Compiler
-class ERB
- # = ERB::Compiler
- #
- # Compiles ERB templates into Ruby code; the compiled code produces the
- # template result when evaluated. ERB::Compiler provides hooks to define how
- # generated output is handled.
- #
- # Internally ERB does something like this to generate the code returned by
- # ERB#src:
- #
- # compiler = ERB::Compiler.new('<>')
- # compiler.pre_cmd = ["_erbout=''"]
- # compiler.put_cmd = "_erbout.concat"
- # compiler.insert_cmd = "_erbout.concat"
- # compiler.post_cmd = ["_erbout"]
- #
- # code, enc = compiler.compile("Got <%= obj %>!\n")
- # puts code
- #
- # Generates:
- #
- # #coding:UTF-8
- # _erbout=''; _erbout.concat "Got "; _erbout.concat(( obj ).to_s); _erbout.concat "!\n"; _erbout
- #
- # By default the output is sent to the print method. For example:
- #
- # compiler = ERB::Compiler.new('<>')
- # code, enc = compiler.compile("Got <%= obj %>!\n")
- # puts code
- #
- # Generates:
- #
- # #coding:UTF-8
- # print "Got "; print(( obj ).to_s); print "!\n"
- #
- # == Evaluation
- #
- # The compiled code can be used in any context where the names in the code
- # correctly resolve. Using the last example, each of these print 'Got It!'
- #
- # Evaluate using a variable:
- #
- # obj = 'It'
- # eval code
- #
- # Evaluate using an input:
- #
- # mod = Module.new
- # mod.module_eval %{
- # def get(obj)
- # #{code}
- # end
- # }
- # extend mod
- # get('It')
- #
- # Evaluate using an accessor:
- #
- # klass = Class.new Object
- # klass.class_eval %{
- # attr_accessor :obj
- # def initialize(obj)
- # @obj = obj
- # end
- # def get_it
- # #{code}
- # end
- # }
- # klass.new('It').get_it
- #
- # Good! See also ERB#def_method, ERB#def_module, and ERB#def_class.
- class Compiler # :nodoc:
- class PercentLine # :nodoc:
- def initialize(str)
- @value = str
- end
- attr_reader :value
- alias :to_s :value
-
- def empty?
- @value.empty?
- end
- end
-
- class Scanner # :nodoc:
- @scanner_map = {}
- def self.regist_scanner(klass, trim_mode, percent)
- @scanner_map[[trim_mode, percent]] = klass
- end
-
- def self.default_scanner=(klass)
- @default_scanner = klass
- end
-
- def self.make_scanner(src, trim_mode, percent)
- klass = @scanner_map.fetch([trim_mode, percent], @default_scanner)
- klass.new(src, trim_mode, percent)
- end
-
- def initialize(src, trim_mode, percent)
- @src = src
- @stag = nil
- end
- attr_accessor :stag
-
- def scan; end
- end
-
- class TrimScanner < Scanner # :nodoc:
- def initialize(src, trim_mode, percent)
- super
- @trim_mode = trim_mode
- @percent = percent
- if @trim_mode == '>'
- @scan_line = self.method(:trim_line1)
- elsif @trim_mode == '<>'
- @scan_line = self.method(:trim_line2)
- elsif @trim_mode == '-'
- @scan_line = self.method(:explicit_trim_line)
- else
- @scan_line = self.method(:scan_line)
- end
- end
- attr_accessor :stag
-
- def scan(&block)
- @stag = nil
- if @percent
- @src.each_line do |line|
- percent_line(line, &block)
- end
- else
- @scan_line.call(@src, &block)
- end
- nil
- end
-
- def percent_line(line, &block)
- if @stag || line[0] != ?%
- return @scan_line.call(line, &block)
- end
-
- line[0] = ''
- if line[0] == ?%
- @scan_line.call(line, &block)
- else
- yield(PercentLine.new(line.chomp))
- end
- end
-
- def scan_line(line)
- line.scan(/(.*?)(<%%|%%>|<%=|<%#|<%|%>|\n|\z)/m) do |tokens|
- tokens.each do |token|
- next if token.empty?
- yield(token)
- end
- end
- end
-
- def trim_line1(line)
- line.scan(/(.*?)(<%%|%%>|<%=|<%#|<%|%>\n|%>|\n|\z)/m) do |tokens|
- tokens.each do |token|
- next if token.empty?
- if token == "%>\n"
- yield('%>')
- yield(:cr)
- else
- yield(token)
- end
- end
- end
- end
-
- def trim_line2(line)
- head = nil
- line.scan(/(.*?)(<%%|%%>|<%=|<%#|<%|%>\n|%>|\n|\z)/m) do |tokens|
- tokens.each do |token|
- next if token.empty?
- head = token unless head
- if token == "%>\n"
- yield('%>')
- if is_erb_stag?(head)
- yield(:cr)
- else
- yield("\n")
- end
- head = nil
- else
- yield(token)
- head = nil if token == "\n"
- end
- end
- end
- end
-
- def explicit_trim_line(line)
- line.scan(/(.*?)(^[ \t]*<%\-|<%\-|<%%|%%>|<%=|<%#|<%|-%>\n|-%>|%>|\z)/m) do |tokens|
- tokens.each do |token|
- next if token.empty?
- if @stag.nil? && /[ \t]*<%-/ =~ token
- yield('<%')
- elsif @stag && token == "-%>\n"
- yield('%>')
- yield(:cr)
- elsif @stag && token == '-%>'
- yield('%>')
- else
- yield(token)
- end
- end
- end
- end
-
- ERB_STAG = %w(<%= <%# <%)
- def is_erb_stag?(s)
- ERB_STAG.member?(s)
- end
- end
-
- Scanner.default_scanner = TrimScanner
-
- class SimpleScanner < Scanner # :nodoc:
- def scan
- @src.scan(/(.*?)(<%%|%%>|<%=|<%#|<%|%>|\n|\z)/m) do |tokens|
- tokens.each do |token|
- next if token.empty?
- yield(token)
- end
- end
- end
- end
-
- Scanner.regist_scanner(SimpleScanner, nil, false)
-
- begin
- require 'strscan'
- class SimpleScanner2 < Scanner # :nodoc:
- def scan
- stag_reg = /(.*?)(<%%|<%=|<%#|<%|\z)/m
- etag_reg = /(.*?)(%%>|%>|\z)/m
- scanner = StringScanner.new(@src)
- while ! scanner.eos?
- scanner.scan(@stag ? etag_reg : stag_reg)
- yield(scanner[1])
- yield(scanner[2])
- end
- end
- end
- Scanner.regist_scanner(SimpleScanner2, nil, false)
-
- class ExplicitScanner < Scanner # :nodoc:
- def scan
- stag_reg = /(.*?)(^[ \t]*<%-|<%%|<%=|<%#|<%-|<%|\z)/m
- etag_reg = /(.*?)(%%>|-%>|%>|\z)/m
- scanner = StringScanner.new(@src)
- while ! scanner.eos?
- scanner.scan(@stag ? etag_reg : stag_reg)
- yield(scanner[1])
-
- elem = scanner[2]
- if /[ \t]*<%-/ =~ elem
- yield('<%')
- elsif elem == '-%>'
- yield('%>')
- yield(:cr) if scanner.scan(/(\n|\z)/)
- else
- yield(elem)
- end
- end
- end
- end
- Scanner.regist_scanner(ExplicitScanner, '-', false)
-
- rescue LoadError
- end
-
- class Buffer # :nodoc:
- def initialize(compiler, enc=nil)
- @compiler = compiler
- @line = []
- @script = enc ? "#coding:#{enc}\n" : ""
- @compiler.pre_cmd.each do |x|
- push(x)
- end
- end
- attr_reader :script
-
- def push(cmd)
- @line << cmd
- end
-
- def cr
- @script << (@line.join('; '))
- @line = []
- @script << "\n"
- end
-
- def close
- return unless @line
- @compiler.post_cmd.each do |x|
- push(x)
- end
- @script << (@line.join('; '))
- @line = nil
- end
- end
-
- def content_dump(s) # :nodoc:
- n = s.count("\n")
- if n > 0
- s.dump + "\n" * n
- else
- s.dump
- end
- end
-
- def add_put_cmd(out, content)
- out.push("#{@put_cmd} #{content_dump(content)}")
- end
-
- def add_insert_cmd(out, content)
- out.push("#{@insert_cmd}((#{content}).to_s)")
- end
-
- # Compiles an ERB template into Ruby code. Returns an array of the code
- # and encoding like ["code", Encoding].
- def compile(s)
- enc = s.encoding
- raise ArgumentError, "#{enc} is not ASCII compatible" if enc.dummy?
- s = s.b # see String#b
- enc = detect_magic_comment(s) || enc
- out = Buffer.new(self, enc)
-
- content = ''
- scanner = make_scanner(s)
- scanner.scan do |token|
- next if token.nil?
- next if token == ''
- if scanner.stag.nil?
- case token
- when PercentLine
- add_put_cmd(out, content) if content.size > 0
- content = ''
- out.push(token.to_s)
- out.cr
- when :cr
- out.cr
- when '<%', '<%=', '<%#'
- scanner.stag = token
- add_put_cmd(out, content) if content.size > 0
- content = ''
- when "\n"
- content << "\n"
- add_put_cmd(out, content)
- content = ''
- when '<%%'
- content << '<%'
- else
- content << token
- end
- else
- case token
- when '%>'
- case scanner.stag
- when '<%'
- if content[-1] == ?\n
- content.chop!
- out.push(content)
- out.cr
- else
- out.push(content)
- end
- when '<%='
- add_insert_cmd(out, content)
- when '<%#'
- # out.push("# #{content_dump(content)}")
- end
- scanner.stag = nil
- content = ''
- when '%%>'
- content << '%>'
- else
- content << token
- end
- end
- end
- add_put_cmd(out, content) if content.size > 0
- out.close
- return out.script, enc
- end
-
- def prepare_trim_mode(mode) # :nodoc:
- case mode
- when 1
- return [false, '>']
- when 2
- return [false, '<>']
- when 0
- return [false, nil]
- when String
- perc = mode.include?('%')
- if mode.include?('-')
- return [perc, '-']
- elsif mode.include?('<>')
- return [perc, '<>']
- elsif mode.include?('>')
- return [perc, '>']
- else
- [perc, nil]
- end
- else
- return [false, nil]
- end
- end
-
- def make_scanner(src) # :nodoc:
- Scanner.make_scanner(src, @trim_mode, @percent)
- end
-
- # Construct a new compiler using the trim_mode. See ERB::new for available
- # trim modes.
- def initialize(trim_mode)
- @percent, @trim_mode = prepare_trim_mode(trim_mode)
- @put_cmd = 'print'
- @insert_cmd = @put_cmd
- @pre_cmd = []
- @post_cmd = []
- end
- attr_reader :percent, :trim_mode
-
- # The command to handle text that ends with a newline
- attr_accessor :put_cmd
-
- # The command to handle text that is inserted prior to a newline
- attr_accessor :insert_cmd
-
- # An array of commands prepended to compiled code
- attr_accessor :pre_cmd
-
- # An array of commands appended to compiled code
- attr_accessor :post_cmd
-
- private
- def detect_magic_comment(s)
- if /\A<%#(.*)%>/ =~ s or (@percent and /\A%#(.*)/ =~ s)
- comment = $1
- comment = $1 if comment[/-\*-\s*(.*?)\s*-*-$/]
- if %r"coding\s*[=:]\s*([[:alnum:]\-_]+)" =~ comment
- enc = $1.sub(/-(?:mac|dos|unix)/i, '')
- Encoding.find(enc)
- end
- end
- end
- end
-end
-
-#--
-# ERB
-class ERB
- #
- # Constructs a new ERB object with the template specified in _str_.
- #
- # An ERB object works by building a chunk of Ruby code that will output
- # the completed template when run. If _safe_level_ is set to a non-nil value,
- # ERB code will be run in a separate thread with $SAFE set to the
- # provided level.
- #
- # If _trim_mode_ is passed a String containing one or more of the following
- # modifiers, ERB will adjust its code generation as listed:
- #
- # % enables Ruby code processing for lines beginning with %
- # <> omit newline for lines starting with <% and ending in %>
- # > omit newline for lines ending in %>
- # - omit blank lines ending in -%>
- #
- # _eoutvar_ can be used to set the name of the variable ERB will build up
- # its output in. This is useful when you need to run multiple ERB
- # templates through the same binding and/or when you want to control where
- # output ends up. Pass the name of the variable to be used inside a String.
- #
- # === Example
- #
- # require "erb"
- #
- # # build data class
- # class Listings
- # PRODUCT = { :name => "Chicken Fried Steak",
- # :desc => "A well messages pattie, breaded and fried.",
- # :cost => 9.95 }
- #
- # attr_reader :product, :price
- #
- # def initialize( product = "", price = "" )
- # @product = product
- # @price = price
- # end
- #
- # def build
- # b = binding
- # # create and run templates, filling member data variables
- # ERB.new(<<-'END_PRODUCT'.gsub(/^\s+/, ""), 0, "", "@product").result b
- # <%= PRODUCT[:name] %>
- # <%= PRODUCT[:desc] %>
- # END_PRODUCT
- # ERB.new(<<-'END_PRICE'.gsub(/^\s+/, ""), 0, "", "@price").result b
- # <%= PRODUCT[:name] %> -- <%= PRODUCT[:cost] %>
- # <%= PRODUCT[:desc] %>
- # END_PRICE
- # end
- # end
- #
- # # setup template data
- # listings = Listings.new
- # listings.build
- #
- # puts listings.product + "\n" + listings.price
- #
- # _Generates_
- #
- # Chicken Fried Steak
- # A well messages pattie, breaded and fried.
- #
- # Chicken Fried Steak -- 9.95
- # A well messages pattie, breaded and fried.
- #
- def initialize(str, safe_level=nil, trim_mode=nil, eoutvar='_erbout')
- @safe_level = safe_level
- compiler = make_compiler(trim_mode)
- set_eoutvar(compiler, eoutvar)
- @src, @encoding = *compiler.compile(str)
- @filename = nil
- @lineno = 0
- end
-
- ##
- # Creates a new compiler for ERB. See ERB::Compiler.new for details
-
- def make_compiler(trim_mode)
- ERB::Compiler.new(trim_mode)
- end
-
- # The Ruby code generated by ERB
- attr_reader :src
-
- # The encoding to eval
- attr_reader :encoding
-
- # The optional _filename_ argument passed to Kernel#eval when the ERB code
- # is run
- attr_accessor :filename
-
- # The optional _lineno_ argument passed to Kernel#eval when the ERB code
- # is run
- attr_accessor :lineno
-
- def location=((filename, lineno))
- @filename = filename
- @lineno = lineno if lineno
- end
-
- #
- # Can be used to set _eoutvar_ as described in ERB::new. It's probably
- # easier to just use the constructor though, since calling this method
- # requires the setup of an ERB _compiler_ object.
- #
- def set_eoutvar(compiler, eoutvar = '_erbout')
- compiler.put_cmd = "#{eoutvar}.concat"
- compiler.insert_cmd = "#{eoutvar}.concat"
- compiler.pre_cmd = ["#{eoutvar} = ''"]
- compiler.post_cmd = ["#{eoutvar}.force_encoding(__ENCODING__)"]
- end
-
- # Generate results and print them. (see ERB#result)
- def run(b=new_toplevel)
- print self.result(b)
- end
-
- #
- # Executes the generated ERB code to produce a completed template, returning
- # the results of that code. (See ERB::new for details on how this process
- # can be affected by _safe_level_.)
- #
- # _b_ accepts a Binding object which is used to set the context of
- # code evaluation.
- #
- def result(b=new_toplevel)
- if @safe_level
- proc {
- $SAFE = @safe_level
- eval(@src, b, (@filename || '(erb)'), @lineno)
- }.call
- else
- eval(@src, b, (@filename || '(erb)'), @lineno)
- end
- end
-
- ##
- # Returns a new binding each time *near* TOPLEVEL_BINDING for runs that do
- # not specify a binding.
-
- def new_toplevel
- TOPLEVEL_BINDING.dup
- end
- private :new_toplevel
-
- # Define _methodname_ as instance method of _mod_ from compiled Ruby source.
- #
- # example:
- # filename = 'example.rhtml' # 'arg1' and 'arg2' are used in example.rhtml
- # erb = ERB.new(File.read(filename))
- # erb.def_method(MyClass, 'render(arg1, arg2)', filename)
- # print MyClass.new.render('foo', 123)
- def def_method(mod, methodname, fname='(ERB)')
- src = self.src
- magic_comment = "#coding:#{@encoding}\n"
- mod.module_eval do
- eval(magic_comment + "def #{methodname}\n" + src + "\nend\n", binding, fname, -2)
- end
- end
-
- # Create unnamed module, define _methodname_ as instance method of it, and return it.
- #
- # example:
- # filename = 'example.rhtml' # 'arg1' and 'arg2' are used in example.rhtml
- # erb = ERB.new(File.read(filename))
- # erb.filename = filename
- # MyModule = erb.def_module('render(arg1, arg2)')
- # class MyClass
- # include MyModule
- # end
- def def_module(methodname='erb')
- mod = Module.new
- def_method(mod, methodname, @filename || '(ERB)')
- mod
- end
-
- # Define unnamed class which has _methodname_ as instance method, and return it.
- #
- # example:
- # class MyClass_
- # def initialize(arg1, arg2)
- # @arg1 = arg1; @arg2 = arg2
- # end
- # end
- # filename = 'example.rhtml' # @arg1 and @arg2 are used in example.rhtml
- # erb = ERB.new(File.read(filename))
- # erb.filename = filename
- # MyClass = erb.def_class(MyClass_, 'render()')
- # print MyClass.new('foo', 123).render()
- def def_class(superklass=Object, methodname='result')
- cls = Class.new(superklass)
- def_method(cls, methodname, @filename || '(ERB)')
- cls
- end
-end
-
-#--
-# ERB::Util
-class ERB
- # A utility module for conversion routines, often handy in HTML generation.
- module Util
- public
- #
- # A utility method for escaping HTML tag characters in _s_.
- #
- # require "erb"
- # include ERB::Util
- #
- # puts html_escape("is a > 0 & a < 10?")
- #
- # _Generates_
- #
- # is a > 0 & a < 10?
- #
- def html_escape(s)
- CGI.escapeHTML(s.to_s)
- end
- alias h html_escape
- module_function :h
- module_function :html_escape
-
- #
- # A utility method for encoding the String _s_ as a URL.
- #
- # require "erb"
- # include ERB::Util
- #
- # puts url_encode("Programming Ruby: The Pragmatic Programmer's Guide")
- #
- # _Generates_
- #
- # Programming%20Ruby%3A%20%20The%20Pragmatic%20Programmer%27s%20Guide
- #
- def url_encode(s)
- s.to_s.b.gsub(/[^a-zA-Z0-9_\-.]/n) { |m|
- sprintf("%%%02X", m.unpack("C")[0])
- }
- end
- alias u url_encode
- module_function :u
- module_function :url_encode
- end
-end
-
-#--
-# ERB::DefMethod
-class ERB
- # Utility module to define eRuby script as instance method.
- #
- # === Example
- #
- # example.rhtml:
- # <% for item in @items %>
- # <%= item %>
- # <% end %>
- #
- # example.rb:
- # require 'erb'
- # class MyClass
- # extend ERB::DefMethod
- # def_erb_method('render()', 'example.rhtml')
- # def initialize(items)
- # @items = items
- # end
- # end
- # print MyClass.new([10,20,30]).render()
- #
- # result:
- #
- # 10
- #
- # 20
- #
- # 30
- #
- module DefMethod
- public
- # define _methodname_ as instance method of current module, using ERB
- # object or eRuby file
- def def_erb_method(methodname, erb_or_fname)
- if erb_or_fname.kind_of? String
- fname = erb_or_fname
- erb = ERB.new(File.read(fname))
- erb.def_method(self, methodname, fname)
- else
- erb = erb_or_fname
- erb.def_method(self, methodname, erb.filename || '(ERB)')
- end
- end
- module_function :def_erb_method
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/expect.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/expect.rb
deleted file mode 100755
index c3f3925be..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/expect.rb
+++ /dev/null
@@ -1,71 +0,0 @@
-$expect_verbose = false
-
-# Expect library adds the IO instance method #expect, which does similar act to
-# tcl's expect extension.
-#
-# In order to use this method, you must require expect:
-#
-# require 'expect'
-#
-# Please see #expect for usage.
-class IO
- # call-seq:
- # IO#expect(pattern,timeout=9999999) -> Array
- # IO#expect(pattern,timeout=9999999) { |result| ... } -> nil
- #
- # Reads from the IO until the given +pattern+ matches or the +timeout+ is over.
- #
- # It returns an array with the read buffer, followed by the matches.
- # If a block is given, the result is yielded to the block and returns nil.
- #
- # When called without a block, it waits until the input that matches the
- # given +pattern+ is obtained from the IO or the time specified as the
- # timeout passes. An array is returned when the pattern is obtained from the
- # IO. The first element of the array is the entire string obtained from the
- # IO until the pattern matches, followed by elements indicating which the
- # pattern which matched to the anchor in the regular expression.
- #
- # The optional timeout parameter defines, in seconds, the total time to wait
- # for the pattern. If the timeout expires or eof is found, nil is returned
- # or yielded. However, the buffer in a timeout session is kept for the next
- # expect call. The default timeout is 9999999 seconds.
- def expect(pat,timeout=9999999)
- buf = ''
- case pat
- when String
- e_pat = Regexp.new(Regexp.quote(pat))
- when Regexp
- e_pat = pat
- else
- raise TypeError, "unsupported pattern class: #{pat.class}"
- end
- @unusedBuf ||= ''
- while true
- if not @unusedBuf.empty?
- c = @unusedBuf.slice!(0).chr
- elsif !IO.select([self],nil,nil,timeout) or eof? then
- result = nil
- @unusedBuf = buf
- break
- else
- c = getc.chr
- end
- buf << c
- if $expect_verbose
- STDOUT.print c
- STDOUT.flush
- end
- if mat=e_pat.match(buf) then
- result = [buf,*mat.to_a[1..-1]]
- break
- end
- end
- if block_given? then
- yield result
- else
- return result
- end
- nil
- end
-end
-
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle.rb
deleted file mode 100755
index ae6e29963..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle.rb
+++ /dev/null
@@ -1,55 +0,0 @@
-require 'fiddle.so'
-require 'fiddle/function'
-require 'fiddle/closure'
-
-module Fiddle
- if WINDOWS
- # Returns the last win32 +Error+ of the current executing +Thread+ or nil
- # if none
- def self.win32_last_error
- Thread.current[:__FIDDLE_WIN32_LAST_ERROR__]
- end
-
- # Sets the last win32 +Error+ of the current executing +Thread+ to +error+
- def self.win32_last_error= error
- Thread.current[:__FIDDLE_WIN32_LAST_ERROR__] = error
- end
- end
-
- # Returns the last +Error+ of the current executing +Thread+ or nil if none
- def self.last_error
- Thread.current[:__FIDDLE_LAST_ERROR__]
- end
-
- # Sets the last +Error+ of the current executing +Thread+ to +error+
- def self.last_error= error
- Thread.current[:__DL2_LAST_ERROR__] = error
- Thread.current[:__FIDDLE_LAST_ERROR__] = error
- end
-
- # call-seq: dlopen(library) => Fiddle::Handle
- #
- # Creates a new handler that opens +library+, and returns an instance of
- # Fiddle::Handle.
- #
- # If +nil+ is given for the +library+, Fiddle::Handle::DEFAULT is used, which
- # is the equivalent to RTLD_DEFAULT. See man 3 dlopen
for more.
- #
- # lib = Fiddle.dlopen(nil)
- #
- # The default is dependent on OS, and provide a handle for all libraries
- # already loaded. For example, in most cases you can use this to access
- # +libc+ functions, or ruby functions like +rb_str_new+.
- #
- # See Fiddle::Handle.new for more.
- def dlopen library
- Fiddle::Handle.new library
- end
- module_function :dlopen
-
- # Add constants for backwards compat
-
- RTLD_GLOBAL = Handle::RTLD_GLOBAL # :nodoc:
- RTLD_LAZY = Handle::RTLD_LAZY # :nodoc:
- RTLD_NOW = Handle::RTLD_NOW # :nodoc:
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle/closure.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle/closure.rb
deleted file mode 100755
index beb90ecbe..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle/closure.rb
+++ /dev/null
@@ -1,48 +0,0 @@
-module Fiddle
- class Closure
-
- # the C type of the return of the FFI closure
- attr_reader :ctype
-
- # arguments of the FFI closure
- attr_reader :args
-
- # Extends Fiddle::Closure to allow for building the closure in a block
- class BlockCaller < Fiddle::Closure
-
- # == Description
- #
- # Construct a new BlockCaller object.
- #
- # * +ctype+ is the C type to be returned
- # * +args+ are passed the callback
- # * +abi+ is the abi of the closure
- #
- # If there is an error in preparing the +ffi_cif+ or +ffi_prep_closure+,
- # then a RuntimeError will be raised.
- #
- # == Example
- #
- # include Fiddle
- #
- # cb = Closure::BlockCaller.new(TYPE_INT, [TYPE_INT]) do |one|
- # one
- # end
- #
- # func = Function.new(cb, [TYPE_INT], TYPE_INT)
- #
- def initialize ctype, args, abi = Fiddle::Function::DEFAULT, &block
- super(ctype, args, abi)
- @block = block
- end
-
- # Calls the constructed BlockCaller, with +args+
- #
- # For an example see Fiddle::Closure::BlockCaller.new
- #
- def call *args
- @block.call(*args)
- end
- end
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle/cparser.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle/cparser.rb
deleted file mode 100755
index 43fb184a1..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle/cparser.rb
+++ /dev/null
@@ -1,176 +0,0 @@
-module Fiddle
- # A mixin that provides methods for parsing C struct and prototype signatures.
- #
- # == Example
- # require 'fiddle/import'
- #
- # include Fiddle::CParser
- # #=> Object
- #
- # parse_ctype('int increment(int)')
- # #=> ["increment", Fiddle::TYPE_INT, [Fiddle::TYPE_INT]]
- #
- module CParser
- # Parses a C struct's members
- #
- # Example:
- #
- # include Fiddle::CParser
- # #=> Object
- #
- # parse_struct_signature(['int i', 'char c'])
- # #=> [[Fiddle::TYPE_INT, Fiddle::TYPE_CHAR], ["i", "c"]]
- #
- def parse_struct_signature(signature, tymap=nil)
- if( signature.is_a?(String) )
- signature = signature.split(/\s*,\s*/)
- end
- mems = []
- tys = []
- signature.each{|msig|
- tks = msig.split(/\s+(\*)?/)
- ty = tks[0..-2].join(" ")
- member = tks[-1]
-
- case ty
- when /\[(\d+)\]/
- n = $1.to_i
- ty.gsub!(/\s*\[\d+\]/,"")
- ty = [ty, n]
- when /\[\]/
- ty.gsub!(/\s*\[\]/, "*")
- end
-
- case member
- when /\[(\d+)\]/
- ty = [ty, $1.to_i]
- member.gsub!(/\s*\[\d+\]/,"")
- when /\[\]/
- ty = ty + "*"
- member.gsub!(/\s*\[\]/, "")
- end
-
- mems.push(member)
- tys.push(parse_ctype(ty,tymap))
- }
- return tys, mems
- end
-
- # Parses a C prototype signature
- #
- # If Hash +tymap+ is provided, the return value and the arguments from the
- # +signature+ are expected to be keys, and the value will be the C type to
- # be looked up.
- #
- # Example:
- #
- # include Fiddle::CParser
- # #=> Object
- #
- # parse_signature('double sum(double, double)')
- # #=> ["sum", Fiddle::TYPE_DOUBLE, [Fiddle::TYPE_DOUBLE, Fiddle::TYPE_DOUBLE]]
- #
- def parse_signature(signature, tymap=nil)
- tymap ||= {}
- signature = signature.gsub(/\s+/, " ").strip
- case signature
- when /^([\w@\*\s]+)\(([\w\*\s\,\[\]]*)\)$/
- ret = $1
- (args = $2).strip!
- ret = ret.split(/\s+/)
- args = args.split(/\s*,\s*/)
- func = ret.pop
- if( func =~ /^\*/ )
- func.gsub!(/^\*+/,"")
- ret.push("*")
- end
- ret = ret.join(" ")
- return [func, parse_ctype(ret, tymap), args.collect{|arg| parse_ctype(arg, tymap)}]
- else
- raise(RuntimeError,"can't parse the function prototype: #{signature}")
- end
- end
-
- # Given a String of C type +ty+, returns the corresponding Fiddle constant.
- #
- # +ty+ can also accept an Array of C type Strings, and will be returned in
- # a corresponding Array.
- #
- # If Hash +tymap+ is provided, +ty+ is expected to be the key, and the
- # value will be the C type to be looked up.
- #
- # Example:
- #
- # include Fiddle::CParser
- # #=> Object
- #
- # parse_ctype('int')
- # #=> Fiddle::TYPE_INT
- #
- # parse_ctype('double')
- # #=> Fiddle::TYPE_DOUBLE
- #
- # parse_ctype('unsigned char')
- # #=> -Fiddle::TYPE_CHAR
- #
- def parse_ctype(ty, tymap=nil)
- tymap ||= {}
- case ty
- when Array
- return [parse_ctype(ty[0], tymap), ty[1]]
- when "void"
- return TYPE_VOID
- when "char"
- return TYPE_CHAR
- when "unsigned char"
- return -TYPE_CHAR
- when "short"
- return TYPE_SHORT
- when "unsigned short"
- return -TYPE_SHORT
- when "int"
- return TYPE_INT
- when "unsigned int", 'uint'
- return -TYPE_INT
- when "long"
- return TYPE_LONG
- when "unsigned long"
- return -TYPE_LONG
- when "long long"
- if( defined?(TYPE_LONG_LONG) )
- return TYPE_LONG_LONG
- else
- raise(RuntimeError, "unsupported type: #{ty}")
- end
- when "unsigned long long"
- if( defined?(TYPE_LONG_LONG) )
- return -TYPE_LONG_LONG
- else
- raise(RuntimeError, "unsupported type: #{ty}")
- end
- when "float"
- return TYPE_FLOAT
- when "double"
- return TYPE_DOUBLE
- when "size_t"
- return TYPE_SIZE_T
- when "ssize_t"
- return TYPE_SSIZE_T
- when "ptrdiff_t"
- return TYPE_PTRDIFF_T
- when "intptr_t"
- return TYPE_INTPTR_T
- when "uintptr_t"
- return TYPE_UINTPTR_T
- when /\*/, /\[\s*\]/
- return TYPE_VOIDP
- else
- if( tymap[ty] )
- return parse_ctype(tymap[ty], tymap)
- else
- raise(DLError, "unknown type: #{ty}")
- end
- end
- end
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle/function.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle/function.rb
deleted file mode 100755
index ab7496e94..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle/function.rb
+++ /dev/null
@@ -1,17 +0,0 @@
-module Fiddle
- class Function
- # The ABI of the Function.
- attr_reader :abi
-
- # The address of this function
- attr_reader :ptr
-
- # The name of this function
- attr_reader :name
-
- # The integer memory location of this function
- def to_i
- ptr.to_i
- end
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle/import.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle/import.rb
deleted file mode 100755
index 34f5d7f81..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle/import.rb
+++ /dev/null
@@ -1,314 +0,0 @@
-require 'fiddle'
-require 'fiddle/struct'
-require 'fiddle/cparser'
-
-module Fiddle
-
- # Used internally by Fiddle::Importer
- class CompositeHandler
- # Create a new handler with the open +handlers+
- #
- # Used internally by Fiddle::Importer.dlload
- def initialize(handlers)
- @handlers = handlers
- end
-
- # Array of the currently loaded libraries.
- def handlers()
- @handlers
- end
-
- # Returns the address as an Integer from any handlers with the function
- # named +symbol+.
- #
- # Raises a DLError if the handle is closed.
- def sym(symbol)
- @handlers.each{|handle|
- if( handle )
- begin
- addr = handle.sym(symbol)
- return addr
- rescue DLError
- end
- end
- }
- return nil
- end
-
- # See Fiddle::CompositeHandler.sym
- def [](symbol)
- sym(symbol)
- end
- end
-
- # A DSL that provides the means to dynamically load libraries and build
- # modules around them including calling extern functions within the C
- # library that has been loaded.
- #
- # == Example
- #
- # require 'fiddle'
- # require 'fiddle/import'
- #
- # module LibSum
- # extend Fiddle::Importer
- # dlload './libsum.so'
- # extern 'double sum(double*, int)'
- # extern 'double split(double)'
- # end
- #
- module Importer
- include Fiddle
- include CParser
- extend Importer
-
- # Creates an array of handlers for the given +libs+, can be an instance of
- # Fiddle::Handle, Fiddle::Importer, or will create a new instance of
- # Fiddle::Handle using Fiddle.dlopen
- #
- # Raises a DLError if the library cannot be loaded.
- #
- # See Fiddle.dlopen
- def dlload(*libs)
- handles = libs.collect{|lib|
- case lib
- when nil
- nil
- when Handle
- lib
- when Importer
- lib.handlers
- else
- begin
- Fiddle.dlopen(lib)
- rescue DLError
- raise(DLError, "can't load #{lib}")
- end
- end
- }.flatten()
- @handler = CompositeHandler.new(handles)
- @func_map = {}
- @type_alias = {}
- end
-
- # Sets the type alias for +alias_type+ as +orig_type+
- def typealias(alias_type, orig_type)
- @type_alias[alias_type] = orig_type
- end
-
- # Returns the sizeof +ty+, using Fiddle::Importer.parse_ctype to determine
- # the C type and the appropriate Fiddle constant.
- def sizeof(ty)
- case ty
- when String
- ty = parse_ctype(ty, @type_alias).abs()
- case ty
- when TYPE_CHAR
- return SIZEOF_CHAR
- when TYPE_SHORT
- return SIZEOF_SHORT
- when TYPE_INT
- return SIZEOF_INT
- when TYPE_LONG
- return SIZEOF_LONG
- when TYPE_LONG_LONG
- return SIZEOF_LONG_LONG
- when TYPE_FLOAT
- return SIZEOF_FLOAT
- when TYPE_DOUBLE
- return SIZEOF_DOUBLE
- when TYPE_VOIDP
- return SIZEOF_VOIDP
- else
- raise(DLError, "unknown type: #{ty}")
- end
- when Class
- if( ty.instance_methods().include?(:to_ptr) )
- return ty.size()
- end
- end
- return Pointer[ty].size()
- end
-
- def parse_bind_options(opts)
- h = {}
- while( opt = opts.shift() )
- case opt
- when :stdcall, :cdecl
- h[:call_type] = opt
- when :carried, :temp, :temporal, :bind
- h[:callback_type] = opt
- h[:carrier] = opts.shift()
- else
- h[opt] = true
- end
- end
- h
- end
- private :parse_bind_options
-
- # :stopdoc:
- CALL_TYPE_TO_ABI = Hash.new { |h, k|
- raise RuntimeError, "unsupported call type: #{k}"
- }.merge({ :stdcall => (Function::STDCALL rescue Function::DEFAULT),
- :cdecl => Function::DEFAULT,
- nil => Function::DEFAULT
- }).freeze
- private_constant :CALL_TYPE_TO_ABI
- # :startdoc:
-
- # Creates a global method from the given C +signature+.
- def extern(signature, *opts)
- symname, ctype, argtype = parse_signature(signature, @type_alias)
- opt = parse_bind_options(opts)
- f = import_function(symname, ctype, argtype, opt[:call_type])
- name = symname.gsub(/@.+/,'')
- @func_map[name] = f
- # define_method(name){|*args,&block| f.call(*args,&block)}
- begin
- /^(.+?):(\d+)/ =~ caller.first
- file, line = $1, $2.to_i
- rescue
- file, line = __FILE__, __LINE__+3
- end
- module_eval(<<-EOS, file, line)
- def #{name}(*args, &block)
- @func_map['#{name}'].call(*args,&block)
- end
- EOS
- module_function(name)
- f
- end
-
- # Creates a global method from the given C +signature+ using the given
- # +opts+ as bind parameters with the given block.
- def bind(signature, *opts, &blk)
- name, ctype, argtype = parse_signature(signature, @type_alias)
- h = parse_bind_options(opts)
- case h[:callback_type]
- when :bind, nil
- f = bind_function(name, ctype, argtype, h[:call_type], &blk)
- else
- raise(RuntimeError, "unknown callback type: #{h[:callback_type]}")
- end
- @func_map[name] = f
- #define_method(name){|*args,&block| f.call(*args,&block)}
- begin
- /^(.+?):(\d+)/ =~ caller.first
- file, line = $1, $2.to_i
- rescue
- file, line = __FILE__, __LINE__+3
- end
- module_eval(<<-EOS, file, line)
- def #{name}(*args,&block)
- @func_map['#{name}'].call(*args,&block)
- end
- EOS
- module_function(name)
- f
- end
-
- # Creates a class to wrap the C struct described by +signature+.
- #
- # MyStruct = struct ['int i', 'char c']
- def struct(signature)
- tys, mems = parse_struct_signature(signature, @type_alias)
- Fiddle::CStructBuilder.create(CStruct, tys, mems)
- end
-
- # Creates a class to wrap the C union described by +signature+.
- #
- # MyUnion = union ['int i', 'char c']
- def union(signature)
- tys, mems = parse_struct_signature(signature, @type_alias)
- Fiddle::CStructBuilder.create(CUnion, tys, mems)
- end
-
- # Returns the function mapped to +name+, that was created by either
- # Fiddle::Importer.extern or Fiddle::Importer.bind
- def [](name)
- @func_map[name]
- end
-
- # Creates a class to wrap the C struct with the value +ty+
- #
- # See also Fiddle::Importer.struct
- def create_value(ty, val=nil)
- s = struct([ty + " value"])
- ptr = s.malloc()
- if( val )
- ptr.value = val
- end
- return ptr
- end
- alias value create_value
-
- # Returns a new instance of the C struct with the value +ty+ at the +addr+
- # address.
- def import_value(ty, addr)
- s = struct([ty + " value"])
- ptr = s.new(addr)
- return ptr
- end
-
-
- # The Fiddle::CompositeHandler instance
- #
- # Will raise an error if no handlers are open.
- def handler
- @handler or raise "call dlload before importing symbols and functions"
- end
-
- # Returns a new Fiddle::Pointer instance at the memory address of the given
- # +name+ symbol.
- #
- # Raises a DLError if the +name+ doesn't exist.
- #
- # See Fiddle::CompositeHandler.sym and Fiddle::Handle.sym
- def import_symbol(name)
- addr = handler.sym(name)
- if( !addr )
- raise(DLError, "cannot find the symbol: #{name}")
- end
- Pointer.new(addr)
- end
-
- # Returns a new Fiddle::Function instance at the memory address of the given
- # +name+ function.
- #
- # Raises a DLError if the +name+ doesn't exist.
- #
- # * +argtype+ is an Array of arguments, passed to the +name+ function.
- # * +ctype+ is the return type of the function
- # * +call_type+ is the ABI of the function
- #
- # See also Fiddle:Function.new
- #
- # See Fiddle::CompositeHandler.sym and Fiddle::Handler.sym
- def import_function(name, ctype, argtype, call_type = nil)
- addr = handler.sym(name)
- if( !addr )
- raise(DLError, "cannot find the function: #{name}()")
- end
- Function.new(addr, argtype, ctype, CALL_TYPE_TO_ABI[call_type],
- name: name)
- end
-
- # Returns a new closure wrapper for the +name+ function.
- #
- # * +ctype+ is the return type of the function
- # * +argtype+ is an Array of arguments, passed to the callback function
- # * +call_type+ is the abi of the closure
- # * +block+ is passed to the callback
- #
- # See Fiddle::Closure
- def bind_function(name, ctype, argtype, call_type = nil, &block)
- abi = CALL_TYPE_TO_ABI[call_type]
- closure = Class.new(Fiddle::Closure) {
- define_method(:call, block)
- }.new(ctype, argtype, abi)
-
- Function.new(closure, argtype, ctype, abi, name: name)
- end
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle/pack.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle/pack.rb
deleted file mode 100755
index e4e9542cc..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle/pack.rb
+++ /dev/null
@@ -1,128 +0,0 @@
-require 'fiddle'
-
-module Fiddle
- module PackInfo # :nodoc: all
- ALIGN_MAP = {
- TYPE_VOIDP => ALIGN_VOIDP,
- TYPE_CHAR => ALIGN_CHAR,
- TYPE_SHORT => ALIGN_SHORT,
- TYPE_INT => ALIGN_INT,
- TYPE_LONG => ALIGN_LONG,
- TYPE_FLOAT => ALIGN_FLOAT,
- TYPE_DOUBLE => ALIGN_DOUBLE,
- -TYPE_CHAR => ALIGN_CHAR,
- -TYPE_SHORT => ALIGN_SHORT,
- -TYPE_INT => ALIGN_INT,
- -TYPE_LONG => ALIGN_LONG,
- }
-
- PACK_MAP = {
- TYPE_VOIDP => ((SIZEOF_VOIDP == SIZEOF_LONG_LONG) ? "q" : "l!"),
- TYPE_CHAR => "c",
- TYPE_SHORT => "s!",
- TYPE_INT => "i!",
- TYPE_LONG => "l!",
- TYPE_FLOAT => "f",
- TYPE_DOUBLE => "d",
- -TYPE_CHAR => "c",
- -TYPE_SHORT => "s!",
- -TYPE_INT => "i!",
- -TYPE_LONG => "l!",
- }
-
- SIZE_MAP = {
- TYPE_VOIDP => SIZEOF_VOIDP,
- TYPE_CHAR => SIZEOF_CHAR,
- TYPE_SHORT => SIZEOF_SHORT,
- TYPE_INT => SIZEOF_INT,
- TYPE_LONG => SIZEOF_LONG,
- TYPE_FLOAT => SIZEOF_FLOAT,
- TYPE_DOUBLE => SIZEOF_DOUBLE,
- -TYPE_CHAR => SIZEOF_CHAR,
- -TYPE_SHORT => SIZEOF_SHORT,
- -TYPE_INT => SIZEOF_INT,
- -TYPE_LONG => SIZEOF_LONG,
- }
- if defined?(TYPE_LONG_LONG)
- ALIGN_MAP[TYPE_LONG_LONG] = ALIGN_MAP[-TYPE_LONG_LONG] = ALIGN_LONG_LONG
- PACK_MAP[TYPE_LONG_LONG] = PACK_MAP[-TYPE_LONG_LONG] = "q"
- SIZE_MAP[TYPE_LONG_LONG] = SIZE_MAP[-TYPE_LONG_LONG] = SIZEOF_LONG_LONG
- end
-
- def align(addr, align)
- d = addr % align
- if( d == 0 )
- addr
- else
- addr + (align - d)
- end
- end
- module_function :align
- end
-
- class Packer # :nodoc: all
- include PackInfo
-
- def self.[](*types)
- new(types)
- end
-
- def initialize(types)
- parse_types(types)
- end
-
- def size()
- @size
- end
-
- def pack(ary)
- case SIZEOF_VOIDP
- when SIZEOF_LONG
- ary.pack(@template)
- when SIZEOF_LONG_LONG
- ary.pack(@template)
- else
- raise(RuntimeError, "sizeof(void*)?")
- end
- end
-
- def unpack(ary)
- case SIZEOF_VOIDP
- when SIZEOF_LONG
- ary.join().unpack(@template)
- when SIZEOF_LONG_LONG
- ary.join().unpack(@template)
- else
- raise(RuntimeError, "sizeof(void*)?")
- end
- end
-
- private
-
- def parse_types(types)
- @template = ""
- addr = 0
- types.each{|t|
- orig_addr = addr
- if( t.is_a?(Array) )
- addr = align(orig_addr, ALIGN_MAP[TYPE_VOIDP])
- else
- addr = align(orig_addr, ALIGN_MAP[t])
- end
- d = addr - orig_addr
- if( d > 0 )
- @template << "x#{d}"
- end
- if( t.is_a?(Array) )
- @template << (PACK_MAP[t[0]] * t[1])
- addr += (SIZE_MAP[t[0]] * t[1])
- else
- @template << PACK_MAP[t]
- addr += SIZE_MAP[t]
- end
- }
- addr = align(addr, ALIGN_MAP[TYPE_VOIDP])
- @size = addr
- end
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle/struct.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle/struct.rb
deleted file mode 100755
index 695a4d224..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle/struct.rb
+++ /dev/null
@@ -1,243 +0,0 @@
-require 'fiddle'
-require 'fiddle/value'
-require 'fiddle/pack'
-
-module Fiddle
- # C struct shell
- class CStruct
- # accessor to Fiddle::CStructEntity
- def CStruct.entity_class
- CStructEntity
- end
- end
-
- # C union shell
- class CUnion
- # accessor to Fiddle::CUnionEntity
- def CUnion.entity_class
- CUnionEntity
- end
- end
-
- # Used to construct C classes (CUnion, CStruct, etc)
- #
- # Fiddle::Importer#struct and Fiddle::Importer#union wrap this functionality in an
- # easy-to-use manner.
- module CStructBuilder
- # Construct a new class given a C:
- # * class +klass+ (CUnion, CStruct, or other that provide an
- # #entity_class)
- # * +types+ (Fiddle::TYPE_INT, Fiddle::TYPE_SIZE_T, etc., see the C types
- # constants)
- # * corresponding +members+
- #
- # Fiddle::Importer#struct and Fiddle::Importer#union wrap this functionality in an
- # easy-to-use manner.
- #
- # Example:
- #
- # require 'fiddle/struct'
- # require 'fiddle/cparser'
- #
- # include Fiddle::CParser
- #
- # types, members = parse_struct_signature(['int i','char c'])
- #
- # MyStruct = Fiddle::CStructBuilder.create(Fiddle::CUnion, types, members)
- #
- # obj = MyStruct.allocate
- #
- def create(klass, types, members)
- new_class = Class.new(klass){
- define_method(:initialize){|addr|
- @entity = klass.entity_class.new(addr, types)
- @entity.assign_names(members)
- }
- define_method(:to_ptr){ @entity }
- define_method(:to_i){ @entity.to_i }
- members.each{|name|
- define_method(name){ @entity[name] }
- define_method(name + "="){|val| @entity[name] = val }
- }
- }
- size = klass.entity_class.size(types)
- new_class.module_eval(<<-EOS, __FILE__, __LINE__+1)
- def new_class.size()
- #{size}
- end
- def new_class.malloc()
- addr = Fiddle.malloc(#{size})
- new(addr)
- end
- EOS
- return new_class
- end
- module_function :create
- end
-
- # A C struct wrapper
- class CStructEntity < Fiddle::Pointer
- include PackInfo
- include ValueUtil
-
- # Allocates a C struct with the +types+ provided.
- #
- # When the instance is garbage collected, the C function +func+ is called.
- def CStructEntity.malloc(types, func = nil)
- addr = Fiddle.malloc(CStructEntity.size(types))
- CStructEntity.new(addr, types, func)
- end
-
- # Returns the offset for the packed sizes for the given +types+.
- #
- # Fiddle::CStructEntity.size(
- # [ Fiddle::TYPE_DOUBLE,
- # Fiddle::TYPE_INT,
- # Fiddle::TYPE_CHAR,
- # Fiddle::TYPE_VOIDP ]) #=> 24
- def CStructEntity.size(types)
- offset = 0
-
- max_align = types.map { |type, count = 1|
- last_offset = offset
-
- align = PackInfo::ALIGN_MAP[type]
- offset = PackInfo.align(last_offset, align) +
- (PackInfo::SIZE_MAP[type] * count)
-
- align
- }.max
-
- PackInfo.align(offset, max_align)
- end
-
- # Wraps the C pointer +addr+ as a C struct with the given +types+.
- #
- # When the instance is garbage collected, the C function +func+ is called.
- #
- # See also Fiddle::Pointer.new
- def initialize(addr, types, func = nil)
- set_ctypes(types)
- super(addr, @size, func)
- end
-
- # Set the names of the +members+ in this C struct
- def assign_names(members)
- @members = members
- end
-
- # Calculates the offsets and sizes for the given +types+ in the struct.
- def set_ctypes(types)
- @ctypes = types
- @offset = []
- offset = 0
-
- max_align = types.map { |type, count = 1|
- orig_offset = offset
- align = ALIGN_MAP[type]
- offset = PackInfo.align(orig_offset, align)
-
- @offset << offset
-
- offset += (SIZE_MAP[type] * count)
-
- align
- }.max
-
- @size = PackInfo.align(offset, max_align)
- end
-
- # Fetch struct member +name+
- def [](name)
- idx = @members.index(name)
- if( idx.nil? )
- raise(ArgumentError, "no such member: #{name}")
- end
- ty = @ctypes[idx]
- if( ty.is_a?(Array) )
- r = super(@offset[idx], SIZE_MAP[ty[0]] * ty[1])
- else
- r = super(@offset[idx], SIZE_MAP[ty.abs])
- end
- packer = Packer.new([ty])
- val = packer.unpack([r])
- case ty
- when Array
- case ty[0]
- when TYPE_VOIDP
- val = val.collect{|v| Pointer.new(v)}
- end
- when TYPE_VOIDP
- val = Pointer.new(val[0])
- else
- val = val[0]
- end
- if( ty.is_a?(Integer) && (ty < 0) )
- return unsigned_value(val, ty)
- elsif( ty.is_a?(Array) && (ty[0] < 0) )
- return val.collect{|v| unsigned_value(v,ty[0])}
- else
- return val
- end
- end
-
- # Set struct member +name+, to value +val+
- def []=(name, val)
- idx = @members.index(name)
- if( idx.nil? )
- raise(ArgumentError, "no such member: #{name}")
- end
- ty = @ctypes[idx]
- packer = Packer.new([ty])
- val = wrap_arg(val, ty, [])
- buff = packer.pack([val].flatten())
- super(@offset[idx], buff.size, buff)
- if( ty.is_a?(Integer) && (ty < 0) )
- return unsigned_value(val, ty)
- elsif( ty.is_a?(Array) && (ty[0] < 0) )
- return val.collect{|v| unsigned_value(v,ty[0])}
- else
- return val
- end
- end
-
- def to_s() # :nodoc:
- super(@size)
- end
- end
-
- # A C union wrapper
- class CUnionEntity < CStructEntity
- include PackInfo
-
- # Allocates a C union the +types+ provided.
- #
- # When the instance is garbage collected, the C function +func+ is called.
- def CUnionEntity.malloc(types, func=nil)
- addr = Fiddle.malloc(CUnionEntity.size(types))
- CUnionEntity.new(addr, types, func)
- end
-
- # Returns the size needed for the union with the given +types+.
- #
- # Fiddle::CUnionEntity.size(
- # [ Fiddle::TYPE_DOUBLE,
- # Fiddle::TYPE_INT,
- # Fiddle::TYPE_CHAR,
- # Fiddle::TYPE_VOIDP ]) #=> 8
- def CUnionEntity.size(types)
- types.map { |type, count = 1|
- PackInfo::SIZE_MAP[type] * count
- }.max
- end
-
- # Calculate the necessary offset and for each union member with the given
- # +types+
- def set_ctypes(types)
- @ctypes = types
- @offset = Array.new(types.length, 0)
- @size = self.class.size types
- end
- end
-end
-
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle/types.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle/types.rb
deleted file mode 100755
index 02c1d25a3..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle/types.rb
+++ /dev/null
@@ -1,71 +0,0 @@
-module Fiddle
- # Adds Windows type aliases to the including class for use with
- # Fiddle::Importer.
- #
- # The aliases added are:
- # * ATOM
- # * BOOL
- # * BYTE
- # * DWORD
- # * DWORD32
- # * DWORD64
- # * HANDLE
- # * HDC
- # * HINSTANCE
- # * HWND
- # * LPCSTR
- # * LPSTR
- # * PBYTE
- # * PDWORD
- # * PHANDLE
- # * PVOID
- # * PWORD
- # * UCHAR
- # * UINT
- # * ULONG
- # * WORD
- module Win32Types
- def included(m) # :nodoc:
- m.module_eval{
- typealias "DWORD", "unsigned long"
- typealias "PDWORD", "unsigned long *"
- typealias "DWORD32", "unsigned long"
- typealias "DWORD64", "unsigned long long"
- typealias "WORD", "unsigned short"
- typealias "PWORD", "unsigned short *"
- typealias "BOOL", "int"
- typealias "ATOM", "int"
- typealias "BYTE", "unsigned char"
- typealias "PBYTE", "unsigned char *"
- typealias "UINT", "unsigned int"
- typealias "ULONG", "unsigned long"
- typealias "UCHAR", "unsigned char"
- typealias "HANDLE", "uintptr_t"
- typealias "PHANDLE", "void*"
- typealias "PVOID", "void*"
- typealias "LPCSTR", "char*"
- typealias "LPSTR", "char*"
- typealias "HINSTANCE", "unsigned int"
- typealias "HDC", "unsigned int"
- typealias "HWND", "unsigned int"
- }
- end
- module_function :included
- end
-
- # Adds basic type aliases to the including class for use with Fiddle::Importer.
- #
- # The aliases added are +uint+ and +u_int+ (unsigned int) and
- # +ulong+ and +u_long+ (unsigned long)
- module BasicTypes
- def included(m) # :nodoc:
- m.module_eval{
- typealias "uint", "unsigned int"
- typealias "u_int", "unsigned int"
- typealias "ulong", "unsigned long"
- typealias "u_long", "unsigned long"
- }
- end
- module_function :included
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle/value.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle/value.rb
deleted file mode 100755
index 8d71e47ce..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fiddle/value.rb
+++ /dev/null
@@ -1,112 +0,0 @@
-require 'fiddle'
-
-module Fiddle
- module ValueUtil #:nodoc: all
- def unsigned_value(val, ty)
- case ty.abs
- when TYPE_CHAR
- [val].pack("c").unpack("C")[0]
- when TYPE_SHORT
- [val].pack("s!").unpack("S!")[0]
- when TYPE_INT
- [val].pack("i!").unpack("I!")[0]
- when TYPE_LONG
- [val].pack("l!").unpack("L!")[0]
- when TYPE_LONG_LONG
- [val].pack("q").unpack("Q")[0]
- else
- val
- end
- end
-
- def signed_value(val, ty)
- case ty.abs
- when TYPE_CHAR
- [val].pack("C").unpack("c")[0]
- when TYPE_SHORT
- [val].pack("S!").unpack("s!")[0]
- when TYPE_INT
- [val].pack("I!").unpack("i!")[0]
- when TYPE_LONG
- [val].pack("L!").unpack("l!")[0]
- when TYPE_LONG_LONG
- [val].pack("Q").unpack("q")[0]
- else
- val
- end
- end
-
- def wrap_args(args, tys, funcs, &block)
- result = []
- tys ||= []
- args.each_with_index{|arg, idx|
- result.push(wrap_arg(arg, tys[idx], funcs, &block))
- }
- result
- end
-
- def wrap_arg(arg, ty, funcs = [], &block)
- funcs ||= []
- case arg
- when nil
- return 0
- when Pointer
- return arg.to_i
- when IO
- case ty
- when TYPE_VOIDP
- return Pointer[arg].to_i
- else
- return arg.to_i
- end
- when Function
- if( block )
- arg.bind_at_call(&block)
- funcs.push(arg)
- elsif !arg.bound?
- raise(RuntimeError, "block must be given.")
- end
- return arg.to_i
- when String
- if( ty.is_a?(Array) )
- return arg.unpack('C*')
- else
- case SIZEOF_VOIDP
- when SIZEOF_LONG
- return [arg].pack("p").unpack("l!")[0]
- when SIZEOF_LONG_LONG
- return [arg].pack("p").unpack("q")[0]
- else
- raise(RuntimeError, "sizeof(void*)?")
- end
- end
- when Float, Integer
- return arg
- when Array
- if( ty.is_a?(Array) ) # used only by struct
- case ty[0]
- when TYPE_VOIDP
- return arg.collect{|v| Integer(v)}
- when TYPE_CHAR
- if( arg.is_a?(String) )
- return val.unpack('C*')
- end
- end
- return arg
- else
- return arg
- end
- else
- if( arg.respond_to?(:to_ptr) )
- return arg.to_ptr.to_i
- else
- begin
- return Integer(arg)
- rescue
- raise(ArgumentError, "unknown argument type: #{arg.class}")
- end
- end
- end
- end
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fileutils.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fileutils.rb
deleted file mode 100755
index 932776c84..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/fileutils.rb
+++ /dev/null
@@ -1,1761 +0,0 @@
-#
-# = fileutils.rb
-#
-# Copyright (c) 2000-2007 Minero Aoki
-#
-# This program is free software.
-# You can distribute/modify this program under the same terms of ruby.
-#
-# == module FileUtils
-#
-# Namespace for several file utility methods for copying, moving, removing, etc.
-#
-# === Module Functions
-#
-# require 'fileutils'
-#
-# FileUtils.cd(dir, options)
-# FileUtils.cd(dir, options) {|dir| .... }
-# FileUtils.pwd()
-# FileUtils.mkdir(dir, options)
-# FileUtils.mkdir(list, options)
-# FileUtils.mkdir_p(dir, options)
-# FileUtils.mkdir_p(list, options)
-# FileUtils.rmdir(dir, options)
-# FileUtils.rmdir(list, options)
-# FileUtils.ln(old, new, options)
-# FileUtils.ln(list, destdir, options)
-# FileUtils.ln_s(old, new, options)
-# FileUtils.ln_s(list, destdir, options)
-# FileUtils.ln_sf(src, dest, options)
-# FileUtils.cp(src, dest, options)
-# FileUtils.cp(list, dir, options)
-# FileUtils.cp_r(src, dest, options)
-# FileUtils.cp_r(list, dir, options)
-# FileUtils.mv(src, dest, options)
-# FileUtils.mv(list, dir, options)
-# FileUtils.rm(list, options)
-# FileUtils.rm_r(list, options)
-# FileUtils.rm_rf(list, options)
-# FileUtils.install(src, dest, mode = , options)
-# FileUtils.chmod(mode, list, options)
-# FileUtils.chmod_R(mode, list, options)
-# FileUtils.chown(user, group, list, options)
-# FileUtils.chown_R(user, group, list, options)
-# FileUtils.touch(list, options)
-#
-# The options parameter is a hash of options, taken from the list
-# :force, :noop, :preserve, and :verbose.
-# :noop means that no changes are made. The other two are obvious.
-# Each method documents the options that it honours.
-#
-# All methods that have the concept of a "source" file or directory can take
-# either one file or a list of files in that argument. See the method
-# documentation for examples.
-#
-# There are some `low level' methods, which do not accept any option:
-#
-# FileUtils.copy_entry(src, dest, preserve = false, dereference = false)
-# FileUtils.copy_file(src, dest, preserve = false, dereference = true)
-# FileUtils.copy_stream(srcstream, deststream)
-# FileUtils.remove_entry(path, force = false)
-# FileUtils.remove_entry_secure(path, force = false)
-# FileUtils.remove_file(path, force = false)
-# FileUtils.compare_file(path_a, path_b)
-# FileUtils.compare_stream(stream_a, stream_b)
-# FileUtils.uptodate?(file, cmp_list)
-#
-# == module FileUtils::Verbose
-#
-# This module has all methods of FileUtils module, but it outputs messages
-# before acting. This equates to passing the :verbose flag to methods
-# in FileUtils.
-#
-# == module FileUtils::NoWrite
-#
-# This module has all methods of FileUtils module, but never changes
-# files/directories. This equates to passing the :noop flag to methods
-# in FileUtils.
-#
-# == module FileUtils::DryRun
-#
-# This module has all methods of FileUtils module, but never changes
-# files/directories. This equates to passing the :noop and
-# :verbose flags to methods in FileUtils.
-#
-
-module FileUtils
-
- def self.private_module_function(name) #:nodoc:
- module_function name
- private_class_method name
- end
-
- # This hash table holds command options.
- OPT_TABLE = {} #:nodoc: internal use only
-
- #
- # Options: (none)
- #
- # Returns the name of the current directory.
- #
- def pwd
- Dir.pwd
- end
- module_function :pwd
-
- alias getwd pwd
- module_function :getwd
-
- #
- # Options: verbose
- #
- # Changes the current directory to the directory +dir+.
- #
- # If this method is called with block, resumes to the old
- # working directory after the block execution finished.
- #
- # FileUtils.cd('/', :verbose => true) # chdir and report it
- #
- # FileUtils.cd('/') do # chdir
- # [...] # do something
- # end # return to original directory
- #
- def cd(dir, options = {}, &block) # :yield: dir
- fu_check_options options, OPT_TABLE['cd']
- fu_output_message "cd #{dir}" if options[:verbose]
- Dir.chdir(dir, &block)
- fu_output_message 'cd -' if options[:verbose] and block
- end
- module_function :cd
-
- alias chdir cd
- module_function :chdir
-
- OPT_TABLE['cd'] =
- OPT_TABLE['chdir'] = [:verbose]
-
- #
- # Options: (none)
- #
- # Returns true if +new+ is newer than all +old_list+.
- # Non-existent files are older than any file.
- #
- # FileUtils.uptodate?('hello.o', %w(hello.c hello.h)) or \
- # system 'make hello.o'
- #
- def uptodate?(new, old_list)
- return false unless File.exist?(new)
- new_time = File.mtime(new)
- old_list.each do |old|
- if File.exist?(old)
- return false unless new_time > File.mtime(old)
- end
- end
- true
- end
- module_function :uptodate?
-
- def remove_tailing_slash(dir)
- dir == '/' ? dir : dir.chomp(?/)
- end
- private_module_function :remove_tailing_slash
-
- #
- # Options: mode noop verbose
- #
- # Creates one or more directories.
- #
- # FileUtils.mkdir 'test'
- # FileUtils.mkdir %w( tmp data )
- # FileUtils.mkdir 'notexist', :noop => true # Does not really create.
- # FileUtils.mkdir 'tmp', :mode => 0700
- #
- def mkdir(list, options = {})
- fu_check_options options, OPT_TABLE['mkdir']
- list = fu_list(list)
- fu_output_message "mkdir #{options[:mode] ? ('-m %03o ' % options[:mode]) : ''}#{list.join ' '}" if options[:verbose]
- return if options[:noop]
-
- list.each do |dir|
- fu_mkdir dir, options[:mode]
- end
- end
- module_function :mkdir
-
- OPT_TABLE['mkdir'] = [:mode, :noop, :verbose]
-
- #
- # Options: mode noop verbose
- #
- # Creates a directory and all its parent directories.
- # For example,
- #
- # FileUtils.mkdir_p '/usr/local/lib/ruby'
- #
- # causes to make following directories, if it does not exist.
- # * /usr
- # * /usr/local
- # * /usr/local/lib
- # * /usr/local/lib/ruby
- #
- # You can pass several directories at a time in a list.
- #
- def mkdir_p(list, options = {})
- fu_check_options options, OPT_TABLE['mkdir_p']
- list = fu_list(list)
- fu_output_message "mkdir -p #{options[:mode] ? ('-m %03o ' % options[:mode]) : ''}#{list.join ' '}" if options[:verbose]
- return *list if options[:noop]
-
- list.map {|path| remove_tailing_slash(path)}.each do |path|
- # optimize for the most common case
- begin
- fu_mkdir path, options[:mode]
- next
- rescue SystemCallError
- next if File.directory?(path)
- end
-
- stack = []
- until path == stack.last # dirname("/")=="/", dirname("C:/")=="C:/"
- stack.push path
- path = File.dirname(path)
- end
- stack.reverse_each do |dir|
- begin
- fu_mkdir dir, options[:mode]
- rescue SystemCallError
- raise unless File.directory?(dir)
- end
- end
- end
-
- return *list
- end
- module_function :mkdir_p
-
- alias mkpath mkdir_p
- alias makedirs mkdir_p
- module_function :mkpath
- module_function :makedirs
-
- OPT_TABLE['mkdir_p'] =
- OPT_TABLE['mkpath'] =
- OPT_TABLE['makedirs'] = [:mode, :noop, :verbose]
-
- def fu_mkdir(path, mode) #:nodoc:
- path = remove_tailing_slash(path)
- if mode
- Dir.mkdir path, mode
- File.chmod mode, path
- else
- Dir.mkdir path
- end
- end
- private_module_function :fu_mkdir
-
- #
- # Options: parents, noop, verbose
- #
- # Removes one or more directories.
- #
- # FileUtils.rmdir 'somedir'
- # FileUtils.rmdir %w(somedir anydir otherdir)
- # # Does not really remove directory; outputs message.
- # FileUtils.rmdir 'somedir', :verbose => true, :noop => true
- #
- def rmdir(list, options = {})
- fu_check_options options, OPT_TABLE['rmdir']
- list = fu_list(list)
- parents = options[:parents]
- fu_output_message "rmdir #{parents ? '-p ' : ''}#{list.join ' '}" if options[:verbose]
- return if options[:noop]
- list.each do |dir|
- begin
- Dir.rmdir(dir = remove_tailing_slash(dir))
- if parents
- until (parent = File.dirname(dir)) == '.' or parent == dir
- dir = parent
- Dir.rmdir(dir)
- end
- end
- rescue Errno::ENOTEMPTY, Errno::EEXIST, Errno::ENOENT
- end
- end
- end
- module_function :rmdir
-
- OPT_TABLE['rmdir'] = [:parents, :noop, :verbose]
-
- #
- # Options: force noop verbose
- #
- # ln(old, new, options = {})
- #
- # Creates a hard link +new+ which points to +old+.
- # If +new+ already exists and it is a directory, creates a link +new/old+.
- # If +new+ already exists and it is not a directory, raises Errno::EEXIST.
- # But if :force option is set, overwrite +new+.
- #
- # FileUtils.ln 'gcc', 'cc', :verbose => true
- # FileUtils.ln '/usr/bin/emacs21', '/usr/bin/emacs'
- #
- # ln(list, destdir, options = {})
- #
- # Creates several hard links in a directory, with each one pointing to the
- # item in +list+. If +destdir+ is not a directory, raises Errno::ENOTDIR.
- #
- # include FileUtils
- # cd '/sbin'
- # FileUtils.ln %w(cp mv mkdir), '/bin' # Now /sbin/cp and /bin/cp are linked.
- #
- def ln(src, dest, options = {})
- fu_check_options options, OPT_TABLE['ln']
- fu_output_message "ln#{options[:force] ? ' -f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
- return if options[:noop]
- fu_each_src_dest0(src, dest) do |s,d|
- remove_file d, true if options[:force]
- File.link s, d
- end
- end
- module_function :ln
-
- alias link ln
- module_function :link
-
- OPT_TABLE['ln'] =
- OPT_TABLE['link'] = [:force, :noop, :verbose]
-
- #
- # Options: force noop verbose
- #
- # ln_s(old, new, options = {})
- #
- # Creates a symbolic link +new+ which points to +old+. If +new+ already
- # exists and it is a directory, creates a symbolic link +new/old+. If +new+
- # already exists and it is not a directory, raises Errno::EEXIST. But if
- # :force option is set, overwrite +new+.
- #
- # FileUtils.ln_s '/usr/bin/ruby', '/usr/local/bin/ruby'
- # FileUtils.ln_s 'verylongsourcefilename.c', 'c', :force => true
- #
- # ln_s(list, destdir, options = {})
- #
- # Creates several symbolic links in a directory, with each one pointing to the
- # item in +list+. If +destdir+ is not a directory, raises Errno::ENOTDIR.
- #
- # If +destdir+ is not a directory, raises Errno::ENOTDIR.
- #
- # FileUtils.ln_s Dir.glob('bin/*.rb'), '/home/aamine/bin'
- #
- def ln_s(src, dest, options = {})
- fu_check_options options, OPT_TABLE['ln_s']
- fu_output_message "ln -s#{options[:force] ? 'f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
- return if options[:noop]
- fu_each_src_dest0(src, dest) do |s,d|
- remove_file d, true if options[:force]
- File.symlink s, d
- end
- end
- module_function :ln_s
-
- alias symlink ln_s
- module_function :symlink
-
- OPT_TABLE['ln_s'] =
- OPT_TABLE['symlink'] = [:force, :noop, :verbose]
-
- #
- # Options: noop verbose
- #
- # Same as
- # #ln_s(src, dest, :force => true)
- #
- def ln_sf(src, dest, options = {})
- fu_check_options options, OPT_TABLE['ln_sf']
- options = options.dup
- options[:force] = true
- ln_s src, dest, options
- end
- module_function :ln_sf
-
- OPT_TABLE['ln_sf'] = [:noop, :verbose]
-
- #
- # Options: preserve noop verbose
- #
- # Copies a file content +src+ to +dest+. If +dest+ is a directory,
- # copies +src+ to +dest/src+.
- #
- # If +src+ is a list of files, then +dest+ must be a directory.
- #
- # FileUtils.cp 'eval.c', 'eval.c.org'
- # FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6'
- # FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6', :verbose => true
- # FileUtils.cp 'symlink', 'dest' # copy content, "dest" is not a symlink
- #
- def cp(src, dest, options = {})
- fu_check_options options, OPT_TABLE['cp']
- fu_output_message "cp#{options[:preserve] ? ' -p' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
- return if options[:noop]
- fu_each_src_dest(src, dest) do |s, d|
- copy_file s, d, options[:preserve]
- end
- end
- module_function :cp
-
- alias copy cp
- module_function :copy
-
- OPT_TABLE['cp'] =
- OPT_TABLE['copy'] = [:preserve, :noop, :verbose]
-
- #
- # Options: preserve noop verbose dereference_root remove_destination
- #
- # Copies +src+ to +dest+. If +src+ is a directory, this method copies
- # all its contents recursively. If +dest+ is a directory, copies
- # +src+ to +dest/src+.
- #
- # +src+ can be a list of files.
- #
- # # Installing Ruby library "mylib" under the site_ruby
- # FileUtils.rm_r site_ruby + '/mylib', :force
- # FileUtils.cp_r 'lib/', site_ruby + '/mylib'
- #
- # # Examples of copying several files to target directory.
- # FileUtils.cp_r %w(mail.rb field.rb debug/), site_ruby + '/tmail'
- # FileUtils.cp_r Dir.glob('*.rb'), '/home/aamine/lib/ruby', :noop => true, :verbose => true
- #
- # # If you want to copy all contents of a directory instead of the
- # # directory itself, c.f. src/x -> dest/x, src/y -> dest/y,
- # # use following code.
- # FileUtils.cp_r 'src/.', 'dest' # cp_r('src', 'dest') makes dest/src,
- # # but this doesn't.
- #
- def cp_r(src, dest, options = {})
- fu_check_options options, OPT_TABLE['cp_r']
- fu_output_message "cp -r#{options[:preserve] ? 'p' : ''}#{options[:remove_destination] ? ' --remove-destination' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
- return if options[:noop]
- options = options.dup
- options[:dereference_root] = true unless options.key?(:dereference_root)
- fu_each_src_dest(src, dest) do |s, d|
- copy_entry s, d, options[:preserve], options[:dereference_root], options[:remove_destination]
- end
- end
- module_function :cp_r
-
- OPT_TABLE['cp_r'] = [:preserve, :noop, :verbose,
- :dereference_root, :remove_destination]
-
- #
- # Copies a file system entry +src+ to +dest+.
- # If +src+ is a directory, this method copies its contents recursively.
- # This method preserves file types, c.f. symlink, directory...
- # (FIFO, device files and etc. are not supported yet)
- #
- # Both of +src+ and +dest+ must be a path name.
- # +src+ must exist, +dest+ must not exist.
- #
- # If +preserve+ is true, this method preserves owner, group, and
- # modified time. Permissions are copied regardless +preserve+.
- #
- # If +dereference_root+ is true, this method dereference tree root.
- #
- # If +remove_destination+ is true, this method removes each destination file before copy.
- #
- def copy_entry(src, dest, preserve = false, dereference_root = false, remove_destination = false)
- Entry_.new(src, nil, dereference_root).wrap_traverse(proc do |ent|
- destent = Entry_.new(dest, ent.rel, false)
- File.unlink destent.path if remove_destination && File.file?(destent.path)
- ent.copy destent.path
- end, proc do |ent|
- destent = Entry_.new(dest, ent.rel, false)
- ent.copy_metadata destent.path if preserve
- end)
- end
- module_function :copy_entry
-
- #
- # Copies file contents of +src+ to +dest+.
- # Both of +src+ and +dest+ must be a path name.
- #
- def copy_file(src, dest, preserve = false, dereference = true)
- ent = Entry_.new(src, nil, dereference)
- ent.copy_file dest
- ent.copy_metadata dest if preserve
- end
- module_function :copy_file
-
- #
- # Copies stream +src+ to +dest+.
- # +src+ must respond to #read(n) and
- # +dest+ must respond to #write(str).
- #
- def copy_stream(src, dest)
- IO.copy_stream(src, dest)
- end
- module_function :copy_stream
-
- #
- # Options: force noop verbose
- #
- # Moves file(s) +src+ to +dest+. If +file+ and +dest+ exist on the different
- # disk partition, the file is copied then the original file is removed.
- #
- # FileUtils.mv 'badname.rb', 'goodname.rb'
- # FileUtils.mv 'stuff.rb', '/notexist/lib/ruby', :force => true # no error
- #
- # FileUtils.mv %w(junk.txt dust.txt), '/home/aamine/.trash/'
- # FileUtils.mv Dir.glob('test*.rb'), 'test', :noop => true, :verbose => true
- #
- def mv(src, dest, options = {})
- fu_check_options options, OPT_TABLE['mv']
- fu_output_message "mv#{options[:force] ? ' -f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
- return if options[:noop]
- fu_each_src_dest(src, dest) do |s, d|
- destent = Entry_.new(d, nil, true)
- begin
- if destent.exist?
- if destent.directory?
- raise Errno::EEXIST, d
- else
- destent.remove_file if rename_cannot_overwrite_file?
- end
- end
- begin
- File.rename s, d
- rescue Errno::EXDEV
- copy_entry s, d, true
- if options[:secure]
- remove_entry_secure s, options[:force]
- else
- remove_entry s, options[:force]
- end
- end
- rescue SystemCallError
- raise unless options[:force]
- end
- end
- end
- module_function :mv
-
- alias move mv
- module_function :move
-
- OPT_TABLE['mv'] =
- OPT_TABLE['move'] = [:force, :noop, :verbose, :secure]
-
- def rename_cannot_overwrite_file? #:nodoc:
- /cygwin|mswin|mingw|bccwin|emx/ =~ RUBY_PLATFORM
- end
- private_module_function :rename_cannot_overwrite_file?
-
- #
- # Options: force noop verbose
- #
- # Remove file(s) specified in +list+. This method cannot remove directories.
- # All StandardErrors are ignored when the :force option is set.
- #
- # FileUtils.rm %w( junk.txt dust.txt )
- # FileUtils.rm Dir.glob('*.so')
- # FileUtils.rm 'NotExistFile', :force => true # never raises exception
- #
- def rm(list, options = {})
- fu_check_options options, OPT_TABLE['rm']
- list = fu_list(list)
- fu_output_message "rm#{options[:force] ? ' -f' : ''} #{list.join ' '}" if options[:verbose]
- return if options[:noop]
-
- list.each do |path|
- remove_file path, options[:force]
- end
- end
- module_function :rm
-
- alias remove rm
- module_function :remove
-
- OPT_TABLE['rm'] =
- OPT_TABLE['remove'] = [:force, :noop, :verbose]
-
- #
- # Options: noop verbose
- #
- # Equivalent to
- #
- # #rm(list, :force => true)
- #
- def rm_f(list, options = {})
- fu_check_options options, OPT_TABLE['rm_f']
- options = options.dup
- options[:force] = true
- rm list, options
- end
- module_function :rm_f
-
- alias safe_unlink rm_f
- module_function :safe_unlink
-
- OPT_TABLE['rm_f'] =
- OPT_TABLE['safe_unlink'] = [:noop, :verbose]
-
- #
- # Options: force noop verbose secure
- #
- # remove files +list+[0] +list+[1]... If +list+[n] is a directory,
- # removes its all contents recursively. This method ignores
- # StandardError when :force option is set.
- #
- # FileUtils.rm_r Dir.glob('/tmp/*')
- # FileUtils.rm_r '/', :force => true # :-)
- #
- # WARNING: This method causes local vulnerability
- # if one of parent directories or removing directory tree are world
- # writable (including /tmp, whose permission is 1777), and the current
- # process has strong privilege such as Unix super user (root), and the
- # system has symbolic link. For secure removing, read the documentation
- # of #remove_entry_secure carefully, and set :secure option to true.
- # Default is :secure=>false.
- #
- # NOTE: This method calls #remove_entry_secure if :secure option is set.
- # See also #remove_entry_secure.
- #
- def rm_r(list, options = {})
- fu_check_options options, OPT_TABLE['rm_r']
- # options[:secure] = true unless options.key?(:secure)
- list = fu_list(list)
- fu_output_message "rm -r#{options[:force] ? 'f' : ''} #{list.join ' '}" if options[:verbose]
- return if options[:noop]
- list.each do |path|
- if options[:secure]
- remove_entry_secure path, options[:force]
- else
- remove_entry path, options[:force]
- end
- end
- end
- module_function :rm_r
-
- OPT_TABLE['rm_r'] = [:force, :noop, :verbose, :secure]
-
- #
- # Options: noop verbose secure
- #
- # Equivalent to
- #
- # #rm_r(list, :force => true)
- #
- # WARNING: This method causes local vulnerability.
- # Read the documentation of #rm_r first.
- #
- def rm_rf(list, options = {})
- fu_check_options options, OPT_TABLE['rm_rf']
- options = options.dup
- options[:force] = true
- rm_r list, options
- end
- module_function :rm_rf
-
- alias rmtree rm_rf
- module_function :rmtree
-
- OPT_TABLE['rm_rf'] =
- OPT_TABLE['rmtree'] = [:noop, :verbose, :secure]
-
- #
- # This method removes a file system entry +path+. +path+ shall be a
- # regular file, a directory, or something. If +path+ is a directory,
- # remove it recursively. This method is required to avoid TOCTTOU
- # (time-of-check-to-time-of-use) local security vulnerability of #rm_r.
- # #rm_r causes security hole when:
- #
- # * Parent directory is world writable (including /tmp).
- # * Removing directory tree includes world writable directory.
- # * The system has symbolic link.
- #
- # To avoid this security hole, this method applies special preprocess.
- # If +path+ is a directory, this method chown(2) and chmod(2) all
- # removing directories. This requires the current process is the
- # owner of the removing whole directory tree, or is the super user (root).
- #
- # WARNING: You must ensure that *ALL* parent directories cannot be
- # moved by other untrusted users. For example, parent directories
- # should not be owned by untrusted users, and should not be world
- # writable except when the sticky bit set.
- #
- # WARNING: Only the owner of the removing directory tree, or Unix super
- # user (root) should invoke this method. Otherwise this method does not
- # work.
- #
- # For details of this security vulnerability, see Perl's case:
- #
- # http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CAN-2005-0448
- # http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CAN-2004-0452
- #
- # For fileutils.rb, this vulnerability is reported in [ruby-dev:26100].
- #
- def remove_entry_secure(path, force = false)
- unless fu_have_symlink?
- remove_entry path, force
- return
- end
- fullpath = File.expand_path(path)
- st = File.lstat(fullpath)
- unless st.directory?
- File.unlink fullpath
- return
- end
- # is a directory.
- parent_st = File.stat(File.dirname(fullpath))
- unless parent_st.world_writable?
- remove_entry path, force
- return
- end
- unless parent_st.sticky?
- raise ArgumentError, "parent directory is world writable, FileUtils#remove_entry_secure does not work; abort: #{path.inspect} (parent directory mode #{'%o' % parent_st.mode})"
- end
- # freeze tree root
- euid = Process.euid
- File.open(fullpath + '/.') {|f|
- unless fu_stat_identical_entry?(st, f.stat)
- # symlink (TOC-to-TOU attack?)
- File.unlink fullpath
- return
- end
- f.chown euid, -1
- f.chmod 0700
- unless fu_stat_identical_entry?(st, File.lstat(fullpath))
- # TOC-to-TOU attack?
- File.unlink fullpath
- return
- end
- }
- # ---- tree root is frozen ----
- root = Entry_.new(path)
- root.preorder_traverse do |ent|
- if ent.directory?
- ent.chown euid, -1
- ent.chmod 0700
- end
- end
- root.postorder_traverse do |ent|
- begin
- ent.remove
- rescue
- raise unless force
- end
- end
- rescue
- raise unless force
- end
- module_function :remove_entry_secure
-
- def fu_have_symlink? #:nodoc:
- File.symlink nil, nil
- rescue NotImplementedError
- return false
- rescue TypeError
- return true
- end
- private_module_function :fu_have_symlink?
-
- def fu_stat_identical_entry?(a, b) #:nodoc:
- a.dev == b.dev and a.ino == b.ino
- end
- private_module_function :fu_stat_identical_entry?
-
- #
- # This method removes a file system entry +path+.
- # +path+ might be a regular file, a directory, or something.
- # If +path+ is a directory, remove it recursively.
- #
- # See also #remove_entry_secure.
- #
- def remove_entry(path, force = false)
- Entry_.new(path).postorder_traverse do |ent|
- begin
- ent.remove
- rescue
- raise unless force
- end
- end
- rescue
- raise unless force
- end
- module_function :remove_entry
-
- #
- # Removes a file +path+.
- # This method ignores StandardError if +force+ is true.
- #
- def remove_file(path, force = false)
- Entry_.new(path).remove_file
- rescue
- raise unless force
- end
- module_function :remove_file
-
- #
- # Removes a directory +dir+ and its contents recursively.
- # This method ignores StandardError if +force+ is true.
- #
- def remove_dir(path, force = false)
- remove_entry path, force # FIXME?? check if it is a directory
- end
- module_function :remove_dir
-
- #
- # Returns true if the contents of a file A and a file B are identical.
- #
- # FileUtils.compare_file('somefile', 'somefile') #=> true
- # FileUtils.compare_file('/bin/cp', '/bin/mv') #=> maybe false
- #
- def compare_file(a, b)
- return false unless File.size(a) == File.size(b)
- File.open(a, 'rb') {|fa|
- File.open(b, 'rb') {|fb|
- return compare_stream(fa, fb)
- }
- }
- end
- module_function :compare_file
-
- alias identical? compare_file
- alias cmp compare_file
- module_function :identical?
- module_function :cmp
-
- #
- # Returns true if the contents of a stream +a+ and +b+ are identical.
- #
- def compare_stream(a, b)
- bsize = fu_stream_blksize(a, b)
- sa = ""
- sb = ""
- begin
- a.read(bsize, sa)
- b.read(bsize, sb)
- return true if sa.empty? && sb.empty?
- end while sa == sb
- false
- end
- module_function :compare_stream
-
- #
- # Options: mode preserve noop verbose
- #
- # If +src+ is not same as +dest+, copies it and changes the permission
- # mode to +mode+. If +dest+ is a directory, destination is +dest+/+src+.
- # This method removes destination before copy.
- #
- # FileUtils.install 'ruby', '/usr/local/bin/ruby', :mode => 0755, :verbose => true
- # FileUtils.install 'lib.rb', '/usr/local/lib/ruby/site_ruby', :verbose => true
- #
- def install(src, dest, options = {})
- fu_check_options options, OPT_TABLE['install']
- fu_output_message "install -c#{options[:preserve] && ' -p'}#{options[:mode] ? (' -m 0%o' % options[:mode]) : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
- return if options[:noop]
- fu_each_src_dest(src, dest) do |s, d|
- st = File.stat(s)
- unless File.exist?(d) and compare_file(s, d)
- remove_file d, true
- copy_file s, d
- File.utime st.atime, st.mtime, d if options[:preserve]
- File.chmod options[:mode], d if options[:mode]
- end
- end
- end
- module_function :install
-
- OPT_TABLE['install'] = [:mode, :preserve, :noop, :verbose]
-
- def user_mask(target) #:nodoc:
- target.each_char.inject(0) do |mask, chr|
- case chr
- when "u"
- mask | 04700
- when "g"
- mask | 02070
- when "o"
- mask | 01007
- when "a"
- mask | 07777
- else
- raise ArgumentError, "invalid `who' symbol in file mode: #{chr}"
- end
- end
- end
- private_module_function :user_mask
-
- def apply_mask(mode, user_mask, op, mode_mask)
- case op
- when '='
- (mode & ~user_mask) | (user_mask & mode_mask)
- when '+'
- mode | (user_mask & mode_mask)
- when '-'
- mode & ~(user_mask & mode_mask)
- end
- end
- private_module_function :apply_mask
-
- def symbolic_modes_to_i(mode_sym, path) #:nodoc:
- mode_sym.split(/,/).inject(File.stat(path).mode & 07777) do |current_mode, clause|
- target, *actions = clause.split(/([=+-])/)
- raise ArgumentError, "invalid file mode: #{mode_sym}" if actions.empty?
- target = 'a' if target.empty?
- user_mask = user_mask(target)
- actions.each_slice(2) do |op, perm|
- need_apply = op == '='
- mode_mask = (perm || '').each_char.inject(0) do |mask, chr|
- case chr
- when "r"
- mask | 0444
- when "w"
- mask | 0222
- when "x"
- mask | 0111
- when "X"
- if FileTest.directory? path
- mask | 0111
- else
- mask
- end
- when "s"
- mask | 06000
- when "t"
- mask | 01000
- when "u", "g", "o"
- if mask.nonzero?
- current_mode = apply_mask(current_mode, user_mask, op, mask)
- end
- need_apply = false
- copy_mask = user_mask(chr)
- (current_mode & copy_mask) / (copy_mask & 0111) * (user_mask & 0111)
- else
- raise ArgumentError, "invalid `perm' symbol in file mode: #{chr}"
- end
- end
-
- if mode_mask.nonzero? || need_apply
- current_mode = apply_mask(current_mode, user_mask, op, mode_mask)
- end
- end
- current_mode
- end
- end
- private_module_function :symbolic_modes_to_i
-
- def fu_mode(mode, path) #:nodoc:
- mode.is_a?(String) ? symbolic_modes_to_i(mode, path) : mode
- end
- private_module_function :fu_mode
-
- def mode_to_s(mode) #:nodoc:
- mode.is_a?(String) ? mode : "%o" % mode
- end
- private_module_function :mode_to_s
-
- #
- # Options: noop verbose
- #
- # Changes permission bits on the named files (in +list+) to the bit pattern
- # represented by +mode+.
- #
- # +mode+ is the symbolic and absolute mode can be used.
- #
- # Absolute mode is
- # FileUtils.chmod 0755, 'somecommand'
- # FileUtils.chmod 0644, %w(my.rb your.rb his.rb her.rb)
- # FileUtils.chmod 0755, '/usr/bin/ruby', :verbose => true
- #
- # Symbolic mode is
- # FileUtils.chmod "u=wrx,go=rx", 'somecommand'
- # FileUtils.chmod "u=wr,go=rr", %w(my.rb your.rb his.rb her.rb)
- # FileUtils.chmod "u=wrx,go=rx", '/usr/bin/ruby', :verbose => true
- #
- # "a" :: is user, group, other mask.
- # "u" :: is user's mask.
- # "g" :: is group's mask.
- # "o" :: is other's mask.
- # "w" :: is write permission.
- # "r" :: is read permission.
- # "x" :: is execute permission.
- # "X" ::
- # is execute permission for directories only, must be used in conjunction with "+"
- # "s" :: is uid, gid.
- # "t" :: is sticky bit.
- # "+" :: is added to a class given the specified mode.
- # "-" :: Is removed from a given class given mode.
- # "=" :: Is the exact nature of the class will be given a specified mode.
-
- def chmod(mode, list, options = {})
- fu_check_options options, OPT_TABLE['chmod']
- list = fu_list(list)
- fu_output_message sprintf('chmod %s %s', mode_to_s(mode), list.join(' ')) if options[:verbose]
- return if options[:noop]
- list.each do |path|
- Entry_.new(path).chmod(fu_mode(mode, path))
- end
- end
- module_function :chmod
-
- OPT_TABLE['chmod'] = [:noop, :verbose]
-
- #
- # Options: noop verbose force
- #
- # Changes permission bits on the named files (in +list+)
- # to the bit pattern represented by +mode+.
- #
- # FileUtils.chmod_R 0700, "/tmp/app.#{$$}"
- # FileUtils.chmod_R "u=wrx", "/tmp/app.#{$$}"
- #
- def chmod_R(mode, list, options = {})
- fu_check_options options, OPT_TABLE['chmod_R']
- list = fu_list(list)
- fu_output_message sprintf('chmod -R%s %s %s',
- (options[:force] ? 'f' : ''),
- mode_to_s(mode), list.join(' ')) if options[:verbose]
- return if options[:noop]
- list.each do |root|
- Entry_.new(root).traverse do |ent|
- begin
- ent.chmod(fu_mode(mode, ent.path))
- rescue
- raise unless options[:force]
- end
- end
- end
- end
- module_function :chmod_R
-
- OPT_TABLE['chmod_R'] = [:noop, :verbose, :force]
-
- #
- # Options: noop verbose
- #
- # Changes owner and group on the named files (in +list+)
- # to the user +user+ and the group +group+. +user+ and +group+
- # may be an ID (Integer/String) or a name (String).
- # If +user+ or +group+ is nil, this method does not change
- # the attribute.
- #
- # FileUtils.chown 'root', 'staff', '/usr/local/bin/ruby'
- # FileUtils.chown nil, 'bin', Dir.glob('/usr/bin/*'), :verbose => true
- #
- def chown(user, group, list, options = {})
- fu_check_options options, OPT_TABLE['chown']
- list = fu_list(list)
- fu_output_message sprintf('chown %s %s',
- (group ? "#{user}:#{group}" : user || ':'),
- list.join(' ')) if options[:verbose]
- return if options[:noop]
- uid = fu_get_uid(user)
- gid = fu_get_gid(group)
- list.each do |path|
- Entry_.new(path).chown uid, gid
- end
- end
- module_function :chown
-
- OPT_TABLE['chown'] = [:noop, :verbose]
-
- #
- # Options: noop verbose force
- #
- # Changes owner and group on the named files (in +list+)
- # to the user +user+ and the group +group+ recursively.
- # +user+ and +group+ may be an ID (Integer/String) or
- # a name (String). If +user+ or +group+ is nil, this
- # method does not change the attribute.
- #
- # FileUtils.chown_R 'www', 'www', '/var/www/htdocs'
- # FileUtils.chown_R 'cvs', 'cvs', '/var/cvs', :verbose => true
- #
- def chown_R(user, group, list, options = {})
- fu_check_options options, OPT_TABLE['chown_R']
- list = fu_list(list)
- fu_output_message sprintf('chown -R%s %s %s',
- (options[:force] ? 'f' : ''),
- (group ? "#{user}:#{group}" : user || ':'),
- list.join(' ')) if options[:verbose]
- return if options[:noop]
- uid = fu_get_uid(user)
- gid = fu_get_gid(group)
- list.each do |root|
- Entry_.new(root).traverse do |ent|
- begin
- ent.chown uid, gid
- rescue
- raise unless options[:force]
- end
- end
- end
- end
- module_function :chown_R
-
- OPT_TABLE['chown_R'] = [:noop, :verbose, :force]
-
- begin
- require 'etc'
- rescue LoadError # rescue LoadError for miniruby
- end
-
- def fu_get_uid(user) #:nodoc:
- return nil unless user
- case user
- when Integer
- user
- when /\A\d+\z/
- user.to_i
- else
- Etc.getpwnam(user) ? Etc.getpwnam(user).uid : nil
- end
- end
- private_module_function :fu_get_uid
-
- def fu_get_gid(group) #:nodoc:
- return nil unless group
- case group
- when Integer
- group
- when /\A\d+\z/
- group.to_i
- else
- Etc.getgrnam(group) ? Etc.getgrnam(group).gid : nil
- end
- end
- private_module_function :fu_get_gid
-
- #
- # Options: noop verbose mtime nocreate
- #
- # Updates modification time (mtime) and access time (atime) of file(s) in
- # +list+. Files are created if they don't exist.
- #
- # FileUtils.touch 'timestamp'
- # FileUtils.touch Dir.glob('*.c'); system 'make'
- #
- def touch(list, options = {})
- fu_check_options options, OPT_TABLE['touch']
- list = fu_list(list)
- nocreate = options[:nocreate]
- t = options[:mtime]
- if options[:verbose]
- fu_output_message "touch #{nocreate ? '-c ' : ''}#{t ? t.strftime('-t %Y%m%d%H%M.%S ') : ''}#{list.join ' '}"
- end
- return if options[:noop]
- list.each do |path|
- created = nocreate
- begin
- File.utime(t, t, path)
- rescue Errno::ENOENT
- raise if created
- File.open(path, 'a') {
- ;
- }
- created = true
- retry if t
- end
- end
- end
- module_function :touch
-
- OPT_TABLE['touch'] = [:noop, :verbose, :mtime, :nocreate]
-
- private
-
- module StreamUtils_
- private
-
- def fu_windows?
- /mswin|mingw|bccwin|emx/ =~ RUBY_PLATFORM
- end
-
- def fu_copy_stream0(src, dest, blksize = nil) #:nodoc:
- IO.copy_stream(src, dest)
- end
-
- def fu_stream_blksize(*streams)
- streams.each do |s|
- next unless s.respond_to?(:stat)
- size = fu_blksize(s.stat)
- return size if size
- end
- fu_default_blksize()
- end
-
- def fu_blksize(st)
- s = st.blksize
- return nil unless s
- return nil if s == 0
- s
- end
-
- def fu_default_blksize
- 1024
- end
- end
-
- include StreamUtils_
- extend StreamUtils_
-
- class Entry_ #:nodoc: internal use only
- include StreamUtils_
-
- def initialize(a, b = nil, deref = false)
- @prefix = @rel = @path = nil
- if b
- @prefix = a
- @rel = b
- else
- @path = a
- end
- @deref = deref
- @stat = nil
- @lstat = nil
- end
-
- def inspect
- "\#<#{self.class} #{path()}>"
- end
-
- def path
- if @path
- File.path(@path)
- else
- join(@prefix, @rel)
- end
- end
-
- def prefix
- @prefix || @path
- end
-
- def rel
- @rel
- end
-
- def dereference?
- @deref
- end
-
- def exist?
- begin
- lstat
- true
- rescue Errno::ENOENT
- false
- end
- end
-
- def file?
- s = lstat!
- s and s.file?
- end
-
- def directory?
- s = lstat!
- s and s.directory?
- end
-
- def symlink?
- s = lstat!
- s and s.symlink?
- end
-
- def chardev?
- s = lstat!
- s and s.chardev?
- end
-
- def blockdev?
- s = lstat!
- s and s.blockdev?
- end
-
- def socket?
- s = lstat!
- s and s.socket?
- end
-
- def pipe?
- s = lstat!
- s and s.pipe?
- end
-
- S_IF_DOOR = 0xD000
-
- def door?
- s = lstat!
- s and (s.mode & 0xF000 == S_IF_DOOR)
- end
-
- def entries
- opts = {}
- opts[:encoding] = ::Encoding::UTF_8 if fu_windows?
- Dir.entries(path(), opts)\
- .reject {|n| n == '.' or n == '..' }\
- .map {|n| Entry_.new(prefix(), join(rel(), n.untaint)) }
- end
-
- def stat
- return @stat if @stat
- if lstat() and lstat().symlink?
- @stat = File.stat(path())
- else
- @stat = lstat()
- end
- @stat
- end
-
- def stat!
- return @stat if @stat
- if lstat! and lstat!.symlink?
- @stat = File.stat(path())
- else
- @stat = lstat!
- end
- @stat
- rescue SystemCallError
- nil
- end
-
- def lstat
- if dereference?
- @lstat ||= File.stat(path())
- else
- @lstat ||= File.lstat(path())
- end
- end
-
- def lstat!
- lstat()
- rescue SystemCallError
- nil
- end
-
- def chmod(mode)
- if symlink?
- File.lchmod mode, path() if have_lchmod?
- else
- File.chmod mode, path()
- end
- end
-
- def chown(uid, gid)
- if symlink?
- File.lchown uid, gid, path() if have_lchown?
- else
- File.chown uid, gid, path()
- end
- end
-
- def copy(dest)
- case
- when file?
- copy_file dest
- when directory?
- if !File.exist?(dest) and descendant_directory?(dest, path)
- raise ArgumentError, "cannot copy directory %s to itself %s" % [path, dest]
- end
- begin
- Dir.mkdir dest
- rescue
- raise unless File.directory?(dest)
- end
- when symlink?
- File.symlink File.readlink(path()), dest
- when chardev?
- raise "cannot handle device file" unless File.respond_to?(:mknod)
- mknod dest, ?c, 0666, lstat().rdev
- when blockdev?
- raise "cannot handle device file" unless File.respond_to?(:mknod)
- mknod dest, ?b, 0666, lstat().rdev
- when socket?
- raise "cannot handle socket" unless File.respond_to?(:mknod)
- mknod dest, nil, lstat().mode, 0
- when pipe?
- raise "cannot handle FIFO" unless File.respond_to?(:mkfifo)
- mkfifo dest, 0666
- when door?
- raise "cannot handle door: #{path()}"
- else
- raise "unknown file type: #{path()}"
- end
- end
-
- def copy_file(dest)
- File.open(path()) do |s|
- File.open(dest, 'wb', s.stat.mode) do |f|
- IO.copy_stream(s, f)
- end
- end
- end
-
- def copy_metadata(path)
- st = lstat()
- if !st.symlink?
- File.utime st.atime, st.mtime, path
- end
- begin
- if st.symlink?
- begin
- File.lchown st.uid, st.gid, path
- rescue NotImplementedError
- end
- else
- File.chown st.uid, st.gid, path
- end
- rescue Errno::EPERM
- # clear setuid/setgid
- if st.symlink?
- begin
- File.lchmod st.mode & 01777, path
- rescue NotImplementedError
- end
- else
- File.chmod st.mode & 01777, path
- end
- else
- if st.symlink?
- begin
- File.lchmod st.mode, path
- rescue NotImplementedError
- end
- else
- File.chmod st.mode, path
- end
- end
- end
-
- def remove
- if directory?
- remove_dir1
- else
- remove_file
- end
- end
-
- def remove_dir1
- platform_support {
- Dir.rmdir path().chomp(?/)
- }
- end
-
- def remove_file
- platform_support {
- File.unlink path
- }
- end
-
- def platform_support
- return yield unless fu_windows?
- first_time_p = true
- begin
- yield
- rescue Errno::ENOENT
- raise
- rescue => err
- if first_time_p
- first_time_p = false
- begin
- File.chmod 0700, path() # Windows does not have symlink
- retry
- rescue SystemCallError
- end
- end
- raise err
- end
- end
-
- def preorder_traverse
- stack = [self]
- while ent = stack.pop
- yield ent
- stack.concat ent.entries.reverse if ent.directory?
- end
- end
-
- alias traverse preorder_traverse
-
- def postorder_traverse
- if directory?
- entries().each do |ent|
- ent.postorder_traverse do |e|
- yield e
- end
- end
- end
- ensure
- yield self
- end
-
- def wrap_traverse(pre, post)
- pre.call self
- if directory?
- entries.each do |ent|
- ent.wrap_traverse pre, post
- end
- end
- post.call self
- end
-
- private
-
- $fileutils_rb_have_lchmod = nil
-
- def have_lchmod?
- # This is not MT-safe, but it does not matter.
- if $fileutils_rb_have_lchmod == nil
- $fileutils_rb_have_lchmod = check_have_lchmod?
- end
- $fileutils_rb_have_lchmod
- end
-
- def check_have_lchmod?
- return false unless File.respond_to?(:lchmod)
- File.lchmod 0
- return true
- rescue NotImplementedError
- return false
- end
-
- $fileutils_rb_have_lchown = nil
-
- def have_lchown?
- # This is not MT-safe, but it does not matter.
- if $fileutils_rb_have_lchown == nil
- $fileutils_rb_have_lchown = check_have_lchown?
- end
- $fileutils_rb_have_lchown
- end
-
- def check_have_lchown?
- return false unless File.respond_to?(:lchown)
- File.lchown nil, nil
- return true
- rescue NotImplementedError
- return false
- end
-
- def join(dir, base)
- return File.path(dir) if not base or base == '.'
- return File.path(base) if not dir or dir == '.'
- File.join(dir, base)
- end
-
- if File::ALT_SEPARATOR
- DIRECTORY_TERM = "(?=[/#{Regexp.quote(File::ALT_SEPARATOR)}]|\\z)".freeze
- else
- DIRECTORY_TERM = "(?=/|\\z)".freeze
- end
- SYSCASE = File::FNM_SYSCASE.nonzero? ? "-i" : ""
-
- def descendant_directory?(descendant, ascendant)
- /\A(?#{SYSCASE}:#{Regexp.quote(ascendant)})#{DIRECTORY_TERM}/ =~ File.dirname(descendant)
- end
- end # class Entry_
-
- def fu_list(arg) #:nodoc:
- [arg].flatten.map {|path| File.path(path) }
- end
- private_module_function :fu_list
-
- def fu_each_src_dest(src, dest) #:nodoc:
- fu_each_src_dest0(src, dest) do |s, d|
- raise ArgumentError, "same file: #{s} and #{d}" if fu_same?(s, d)
- yield s, d
- end
- end
- private_module_function :fu_each_src_dest
-
- def fu_each_src_dest0(src, dest) #:nodoc:
- if tmp = Array.try_convert(src)
- tmp.each do |s|
- s = File.path(s)
- yield s, File.join(dest, File.basename(s))
- end
- else
- src = File.path(src)
- if File.directory?(dest)
- yield src, File.join(dest, File.basename(src))
- else
- yield src, File.path(dest)
- end
- end
- end
- private_module_function :fu_each_src_dest0
-
- def fu_same?(a, b) #:nodoc:
- File.identical?(a, b)
- end
- private_module_function :fu_same?
-
- def fu_check_options(options, optdecl) #:nodoc:
- h = options.dup
- optdecl.each do |opt|
- h.delete opt
- end
- raise ArgumentError, "no such option: #{h.keys.join(' ')}" unless h.empty?
- end
- private_module_function :fu_check_options
-
- def fu_update_option(args, new) #:nodoc:
- if tmp = Hash.try_convert(args.last)
- args[-1] = tmp.dup.update(new)
- else
- args.push new
- end
- args
- end
- private_module_function :fu_update_option
-
- @fileutils_output = $stderr
- @fileutils_label = ''
-
- def fu_output_message(msg) #:nodoc:
- @fileutils_output ||= $stderr
- @fileutils_label ||= ''
- @fileutils_output.puts @fileutils_label + msg
- end
- private_module_function :fu_output_message
-
- #
- # Returns an Array of method names which have any options.
- #
- # p FileUtils.commands #=> ["chmod", "cp", "cp_r", "install", ...]
- #
- def FileUtils.commands
- OPT_TABLE.keys
- end
-
- #
- # Returns an Array of option names.
- #
- # p FileUtils.options #=> ["noop", "force", "verbose", "preserve", "mode"]
- #
- def FileUtils.options
- OPT_TABLE.values.flatten.uniq.map {|sym| sym.to_s }
- end
-
- #
- # Returns true if the method +mid+ have an option +opt+.
- #
- # p FileUtils.have_option?(:cp, :noop) #=> true
- # p FileUtils.have_option?(:rm, :force) #=> true
- # p FileUtils.have_option?(:rm, :preserve) #=> false
- #
- def FileUtils.have_option?(mid, opt)
- li = OPT_TABLE[mid.to_s] or raise ArgumentError, "no such method: #{mid}"
- li.include?(opt)
- end
-
- #
- # Returns an Array of option names of the method +mid+.
- #
- # p FileUtils.options_of(:rm) #=> ["noop", "verbose", "force"]
- #
- def FileUtils.options_of(mid)
- OPT_TABLE[mid.to_s].map {|sym| sym.to_s }
- end
-
- #
- # Returns an Array of method names which have the option +opt+.
- #
- # p FileUtils.collect_method(:preserve) #=> ["cp", "cp_r", "copy", "install"]
- #
- def FileUtils.collect_method(opt)
- OPT_TABLE.keys.select {|m| OPT_TABLE[m].include?(opt) }
- end
-
- LOW_METHODS = singleton_methods(false) - collect_method(:noop).map(&:intern)
- module LowMethods
- module_eval("private\n" + ::FileUtils::LOW_METHODS.map {|name| "def #{name}(*)end"}.join("\n"),
- __FILE__, __LINE__)
- end
-
- METHODS = singleton_methods() - [:private_module_function,
- :commands, :options, :have_option?, :options_of, :collect_method]
-
- #
- # This module has all methods of FileUtils module, but it outputs messages
- # before acting. This equates to passing the :verbose flag to
- # methods in FileUtils.
- #
- module Verbose
- include FileUtils
- @fileutils_output = $stderr
- @fileutils_label = ''
- ::FileUtils.collect_method(:verbose).each do |name|
- module_eval(<<-EOS, __FILE__, __LINE__ + 1)
- def #{name}(*args)
- super(*fu_update_option(args, :verbose => true))
- end
- private :#{name}
- EOS
- end
- extend self
- class << self
- ::FileUtils::METHODS.each do |m|
- public m
- end
- end
- end
-
- #
- # This module has all methods of FileUtils module, but never changes
- # files/directories. This equates to passing the :noop flag
- # to methods in FileUtils.
- #
- module NoWrite
- include FileUtils
- include LowMethods
- @fileutils_output = $stderr
- @fileutils_label = ''
- ::FileUtils.collect_method(:noop).each do |name|
- module_eval(<<-EOS, __FILE__, __LINE__ + 1)
- def #{name}(*args)
- super(*fu_update_option(args, :noop => true))
- end
- private :#{name}
- EOS
- end
- extend self
- class << self
- ::FileUtils::METHODS.each do |m|
- public m
- end
- end
- end
-
- #
- # This module has all methods of FileUtils module, but never changes
- # files/directories, with printing message before acting.
- # This equates to passing the :noop and :verbose flag
- # to methods in FileUtils.
- #
- module DryRun
- include FileUtils
- include LowMethods
- @fileutils_output = $stderr
- @fileutils_label = ''
- ::FileUtils.collect_method(:noop).each do |name|
- module_eval(<<-EOS, __FILE__, __LINE__ + 1)
- def #{name}(*args)
- super(*fu_update_option(args, :noop => true, :verbose => true))
- end
- private :#{name}
- EOS
- end
- extend self
- class << self
- ::FileUtils::METHODS.each do |m|
- public m
- end
- end
- end
-
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/find.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/find.rb
deleted file mode 100755
index 55783a569..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/find.rb
+++ /dev/null
@@ -1,88 +0,0 @@
-#
-# find.rb: the Find module for processing all files under a given directory.
-#
-
-#
-# The +Find+ module supports the top-down traversal of a set of file paths.
-#
-# For example, to total the size of all files under your home directory,
-# ignoring anything in a "dot" directory (e.g. $HOME/.ssh):
-#
-# require 'find'
-#
-# total_size = 0
-#
-# Find.find(ENV["HOME"]) do |path|
-# if FileTest.directory?(path)
-# if File.basename(path)[0] == ?.
-# Find.prune # Don't look any further into this directory.
-# else
-# next
-# end
-# else
-# total_size += FileTest.size(path)
-# end
-# end
-#
-module Find
-
- #
- # Calls the associated block with the name of every file and directory listed
- # as arguments, then recursively on their subdirectories, and so on.
- #
- # Returns an enumerator if no block is given.
- #
- # See the +Find+ module documentation for an example.
- #
- def find(*paths, ignore_error: true) # :yield: path
- block_given? or return enum_for(__method__, *paths, ignore_error: ignore_error)
-
- fs_encoding = Encoding.find("filesystem")
-
- paths.collect!{|d| raise Errno::ENOENT unless File.exist?(d); d.dup}.each do |path|
- path = path.to_path if path.respond_to? :to_path
- enc = path.encoding == Encoding::US_ASCII ? fs_encoding : path.encoding
- ps = [path]
- while file = ps.shift
- catch(:prune) do
- yield file.dup.taint
- begin
- s = File.lstat(file)
- rescue Errno::ENOENT, Errno::EACCES, Errno::ENOTDIR, Errno::ELOOP, Errno::ENAMETOOLONG
- raise unless ignore_error
- next
- end
- if s.directory? then
- begin
- fs = Dir.entries(file, encoding: enc)
- rescue Errno::ENOENT, Errno::EACCES, Errno::ENOTDIR, Errno::ELOOP, Errno::ENAMETOOLONG
- raise unless ignore_error
- next
- end
- fs.sort!
- fs.reverse_each {|f|
- next if f == "." or f == ".."
- f = File.join(file, f)
- ps.unshift f.untaint
- }
- end
- end
- end
- end
- nil
- end
-
- #
- # Skips the current file or directory, restarting the loop with the next
- # entry. If the current file is a directory, that directory will not be
- # recursively entered. Meaningful only within the block associated with
- # Find::find.
- #
- # See the +Find+ module documentation for an example.
- #
- def prune
- throw :prune
- end
-
- module_function :find, :prune
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/forwardable.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/forwardable.rb
deleted file mode 100755
index 694ab891e..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/forwardable.rb
+++ /dev/null
@@ -1,289 +0,0 @@
-#
-# forwardable.rb -
-# $Release Version: 1.1$
-# $Revision: 40906 $
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-# original definition by delegator.rb
-# Revised by Daniel J. Berger with suggestions from Florian Gross.
-#
-# Documentation by James Edward Gray II and Gavin Sinclair
-
-
-
-# The Forwardable module provides delegation of specified
-# methods to a designated object, using the methods #def_delegator
-# and #def_delegators.
-#
-# For example, say you have a class RecordCollection which
-# contains an array @records. You could provide the lookup method
-# #record_number(), which simply calls #[] on the @records
-# array, like this:
-#
-# require 'forwardable'
-#
-# class RecordCollection
-# attr_accessor :records
-# extend Forwardable
-# def_delegator :@records, :[], :record_number
-# end
-#
-# We can use the lookup method like so:
-#
-# r = RecordCollection.new
-# r.records = [4,5,6]
-# r.record_number(0) # => 4
-#
-# Further, if you wish to provide the methods #size, #<<, and #map,
-# all of which delegate to @records, this is how you can do it:
-#
-# class RecordCollection # re-open RecordCollection class
-# def_delegators :@records, :size, :<<, :map
-# end
-#
-# r = RecordCollection.new
-# r.records = [1,2,3]
-# r.record_number(0) # => 1
-# r.size # => 3
-# r << 4 # => [1, 2, 3, 4]
-# r.map { |x| x * 2 } # => [2, 4, 6, 8]
-#
-# You can even extend regular objects with Forwardable.
-#
-# my_hash = Hash.new
-# my_hash.extend Forwardable # prepare object for delegation
-# my_hash.def_delegator "STDOUT", "puts" # add delegation for STDOUT.puts()
-# my_hash.puts "Howdy!"
-#
-# == Another example
-#
-# We want to rely on what has come before obviously, but with delegation we can
-# take just the methods we need and even rename them as appropriate. In many
-# cases this is preferable to inheritance, which gives us the entire old
-# interface, even if much of it isn't needed.
-#
-# class Queue
-# extend Forwardable
-#
-# def initialize
-# @q = [ ] # prepare delegate object
-# end
-#
-# # setup preferred interface, enq() and deq()...
-# def_delegator :@q, :push, :enq
-# def_delegator :@q, :shift, :deq
-#
-# # support some general Array methods that fit Queues well
-# def_delegators :@q, :clear, :first, :push, :shift, :size
-# end
-#
-# q = Queue.new
-# q.enq 1, 2, 3, 4, 5
-# q.push 6
-#
-# q.shift # => 1
-# while q.size > 0
-# puts q.deq
-# end
-#
-# q.enq "Ruby", "Perl", "Python"
-# puts q.first
-# q.clear
-# puts q.first
-#
-# This should output:
-#
-# 2
-# 3
-# 4
-# 5
-# 6
-# Ruby
-# nil
-#
-# == Notes
-#
-# Be advised, RDoc will not detect delegated methods.
-#
-# +forwardable.rb+ provides single-method delegation via the def_delegator and
-# def_delegators methods. For full-class delegation via DelegateClass, see
-# +delegate.rb+.
-#
-module Forwardable
- # Version of +forwardable.rb+
- FORWARDABLE_VERSION = "1.1.0"
-
- FILE_REGEXP = %r"#{Regexp.quote(__FILE__)}"
-
- @debug = nil
- class << self
- # If true, __FILE__ will remain in the backtrace in the event an
- # Exception is raised.
- attr_accessor :debug
- end
-
- # Takes a hash as its argument. The key is a symbol or an array of
- # symbols. These symbols correspond to method names. The value is
- # the accessor to which the methods will be delegated.
- #
- # :call-seq:
- # delegate method => accessor
- # delegate [method, method, ...] => accessor
- #
- def instance_delegate(hash)
- hash.each{ |methods, accessor|
- methods = [methods] unless methods.respond_to?(:each)
- methods.each{ |method|
- def_instance_delegator(accessor, method)
- }
- }
- end
-
- #
- # Shortcut for defining multiple delegator methods, but with no
- # provision for using a different name. The following two code
- # samples have the same effect:
- #
- # def_delegators :@records, :size, :<<, :map
- #
- # def_delegator :@records, :size
- # def_delegator :@records, :<<
- # def_delegator :@records, :map
- #
- def def_instance_delegators(accessor, *methods)
- methods.delete("__send__")
- methods.delete("__id__")
- for method in methods
- def_instance_delegator(accessor, method)
- end
- end
-
- # Define +method+ as delegator instance method with an optional
- # alias name +ali+. Method calls to +ali+ will be delegated to
- # +accessor.method+.
- #
- # class MyQueue
- # extend Forwardable
- # attr_reader :queue
- # def initialize
- # @queue = []
- # end
- #
- # def_delegator :@queue, :push, :mypush
- # end
- #
- # q = MyQueue.new
- # q.mypush 42
- # q.queue #=> [42]
- # q.push 23 #=> NoMethodError
- #
- def def_instance_delegator(accessor, method, ali = method)
- line_no = __LINE__; str = %{
- def #{ali}(*args, &block)
- begin
- #{accessor}.__send__(:#{method}, *args, &block)
- rescue Exception
- $@.delete_if{|s| Forwardable::FILE_REGEXP =~ s} unless Forwardable::debug
- ::Kernel::raise
- end
- end
- }
- # If it's not a class or module, it's an instance
- begin
- module_eval(str, __FILE__, line_no)
- rescue
- instance_eval(str, __FILE__, line_no)
- end
-
- end
-
- alias delegate instance_delegate
- alias def_delegators def_instance_delegators
- alias def_delegator def_instance_delegator
-end
-
-# SingleForwardable can be used to setup delegation at the object level as well.
-#
-# printer = String.new
-# printer.extend SingleForwardable # prepare object for delegation
-# printer.def_delegator "STDOUT", "puts" # add delegation for STDOUT.puts()
-# printer.puts "Howdy!"
-#
-# Also, SingleForwardable can be used to set up delegation for a Class or Module.
-#
-# class Implementation
-# def self.service
-# puts "serviced!"
-# end
-# end
-#
-# module Facade
-# extend SingleForwardable
-# def_delegator :Implementation, :service
-# end
-#
-# Facade.service #=> serviced!
-#
-# If you want to use both Forwardable and SingleForwardable, you can
-# use methods def_instance_delegator and def_single_delegator, etc.
-module SingleForwardable
- # Takes a hash as its argument. The key is a symbol or an array of
- # symbols. These symbols correspond to method names. The value is
- # the accessor to which the methods will be delegated.
- #
- # :call-seq:
- # delegate method => accessor
- # delegate [method, method, ...] => accessor
- #
- def single_delegate(hash)
- hash.each{ |methods, accessor|
- methods = [methods] unless methods.respond_to?(:each)
- methods.each{ |method|
- def_single_delegator(accessor, method)
- }
- }
- end
-
- #
- # Shortcut for defining multiple delegator methods, but with no
- # provision for using a different name. The following two code
- # samples have the same effect:
- #
- # def_delegators :@records, :size, :<<, :map
- #
- # def_delegator :@records, :size
- # def_delegator :@records, :<<
- # def_delegator :@records, :map
- #
- def def_single_delegators(accessor, *methods)
- methods.delete("__send__")
- methods.delete("__id__")
- for method in methods
- def_single_delegator(accessor, method)
- end
- end
-
- # :call-seq:
- # def_single_delegator(accessor, method, new_name=method)
- #
- # Defines a method _method_ which delegates to _accessor_ (i.e. it calls
- # the method of the same name in _accessor_). If _new_name_ is
- # provided, it is used as the name for the delegate method.
- def def_single_delegator(accessor, method, ali = method)
- str = %{
- def #{ali}(*args, &block)
- begin
- #{accessor}.__send__(:#{method}, *args, &block)
- rescue Exception
- $@.delete_if{|s| Forwardable::FILE_REGEXP =~ s} unless Forwardable::debug
- ::Kernel::raise
- end
- end
- }
-
- instance_eval(str, __FILE__, __LINE__)
- end
-
- alias delegate single_delegate
- alias def_delegators def_single_delegators
- alias def_delegator def_single_delegator
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/getoptlong.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/getoptlong.rb
deleted file mode 100755
index cf635f043..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/getoptlong.rb
+++ /dev/null
@@ -1,612 +0,0 @@
-#
-# GetoptLong for Ruby
-#
-# Copyright (C) 1998, 1999, 2000 Motoyuki Kasahara.
-#
-# You may redistribute and/or modify this library under the same license
-# terms as Ruby.
-#
-# See GetoptLong for documentation.
-#
-# Additional documents and the latest version of `getoptlong.rb' can be
-# found at http://www.sra.co.jp/people/m-kasahr/ruby/getoptlong/
-
-# The GetoptLong class allows you to parse command line options similarly to
-# the GNU getopt_long() C library call. Note, however, that GetoptLong is a
-# pure Ruby implementation.
-#
-# GetoptLong allows for POSIX-style options like --file as well
-# as single letter options like -f
-#
-# The empty option -- (two minus symbols) is used to end option
-# processing. This can be particularly important if options have optional
-# arguments.
-#
-# Here is a simple example of usage:
-#
-# require 'getoptlong'
-#
-# opts = GetoptLong.new(
-# [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
-# [ '--repeat', '-n', GetoptLong::REQUIRED_ARGUMENT ],
-# [ '--name', GetoptLong::OPTIONAL_ARGUMENT ]
-# )
-#
-# dir = nil
-# name = nil
-# repetitions = 1
-# opts.each do |opt, arg|
-# case opt
-# when '--help'
-# puts <<-EOF
-# hello [OPTION] ... DIR
-#
-# -h, --help:
-# show help
-#
-# --repeat x, -n x:
-# repeat x times
-#
-# --name [name]:
-# greet user by name, if name not supplied default is John
-#
-# DIR: The directory in which to issue the greeting.
-# EOF
-# when '--repeat'
-# repetitions = arg.to_i
-# when '--name'
-# if arg == ''
-# name = 'John'
-# else
-# name = arg
-# end
-# end
-# end
-#
-# if ARGV.length != 1
-# puts "Missing dir argument (try --help)"
-# exit 0
-# end
-#
-# dir = ARGV.shift
-#
-# Dir.chdir(dir)
-# for i in (1..repetitions)
-# print "Hello"
-# if name
-# print ", #{name}"
-# end
-# puts
-# end
-#
-# Example command line:
-#
-# hello -n 6 --name -- /tmp
-#
-class GetoptLong
- #
- # Orderings.
- #
- ORDERINGS = [REQUIRE_ORDER = 0, PERMUTE = 1, RETURN_IN_ORDER = 2]
-
- #
- # Argument flags.
- #
- ARGUMENT_FLAGS = [NO_ARGUMENT = 0, REQUIRED_ARGUMENT = 1,
- OPTIONAL_ARGUMENT = 2]
-
- #
- # Status codes.
- #
- STATUS_YET, STATUS_STARTED, STATUS_TERMINATED = 0, 1, 2
-
- #
- # Error types.
- #
- class Error < StandardError; end
- class AmbiguousOption < Error; end
- class NeedlessArgument < Error; end
- class MissingArgument < Error; end
- class InvalidOption < Error; end
-
- #
- # Set up option processing.
- #
- # The options to support are passed to new() as an array of arrays.
- # Each sub-array contains any number of String option names which carry
- # the same meaning, and one of the following flags:
- #
- # GetoptLong::NO_ARGUMENT :: Option does not take an argument.
- #
- # GetoptLong::REQUIRED_ARGUMENT :: Option always takes an argument.
- #
- # GetoptLong::OPTIONAL_ARGUMENT :: Option may or may not take an argument.
- #
- # The first option name is considered to be the preferred (canonical) name.
- # Other than that, the elements of each sub-array can be in any order.
- #
- def initialize(*arguments)
- #
- # Current ordering.
- #
- if ENV.include?('POSIXLY_CORRECT')
- @ordering = REQUIRE_ORDER
- else
- @ordering = PERMUTE
- end
-
- #
- # Hash table of option names.
- # Keys of the table are option names, and their values are canonical
- # names of the options.
- #
- @canonical_names = Hash.new
-
- #
- # Hash table of argument flags.
- # Keys of the table are option names, and their values are argument
- # flags of the options.
- #
- @argument_flags = Hash.new
-
- #
- # Whether error messages are output to $stderr.
- #
- @quiet = FALSE
-
- #
- # Status code.
- #
- @status = STATUS_YET
-
- #
- # Error code.
- #
- @error = nil
-
- #
- # Error message.
- #
- @error_message = nil
-
- #
- # Rest of catenated short options.
- #
- @rest_singles = ''
-
- #
- # List of non-option-arguments.
- # Append them to ARGV when option processing is terminated.
- #
- @non_option_arguments = Array.new
-
- if 0 < arguments.length
- set_options(*arguments)
- end
- end
-
- #
- # Set the handling of the ordering of options and arguments.
- # A RuntimeError is raised if option processing has already started.
- #
- # The supplied value must be a member of GetoptLong::ORDERINGS. It alters
- # the processing of options as follows:
- #
- # REQUIRE_ORDER :
- #
- # Options are required to occur before non-options.
- #
- # Processing of options ends as soon as a word is encountered that has not
- # been preceded by an appropriate option flag.
- #
- # For example, if -a and -b are options which do not take arguments,
- # parsing command line arguments of '-a one -b two' would result in
- # 'one', '-b', 'two' being left in ARGV, and only ('-a', '') being
- # processed as an option/arg pair.
- #
- # This is the default ordering, if the environment variable
- # POSIXLY_CORRECT is set. (This is for compatibility with GNU getopt_long.)
- #
- # PERMUTE :
- #
- # Options can occur anywhere in the command line parsed. This is the
- # default behavior.
- #
- # Every sequence of words which can be interpreted as an option (with or
- # without argument) is treated as an option; non-option words are skipped.
- #
- # For example, if -a does not require an argument and -b optionally takes
- # an argument, parsing '-a one -b two three' would result in ('-a','') and
- # ('-b', 'two') being processed as option/arg pairs, and 'one','three'
- # being left in ARGV.
- #
- # If the ordering is set to PERMUTE but the environment variable
- # POSIXLY_CORRECT is set, REQUIRE_ORDER is used instead. This is for
- # compatibility with GNU getopt_long.
- #
- # RETURN_IN_ORDER :
- #
- # All words on the command line are processed as options. Words not
- # preceded by a short or long option flag are passed as arguments
- # with an option of '' (empty string).
- #
- # For example, if -a requires an argument but -b does not, a command line
- # of '-a one -b two three' would result in option/arg pairs of ('-a', 'one')
- # ('-b', ''), ('', 'two'), ('', 'three') being processed.
- #
- def ordering=(ordering)
- #
- # The method is failed if option processing has already started.
- #
- if @status != STATUS_YET
- set_error(ArgumentError, "argument error")
- raise RuntimeError,
- "invoke ordering=, but option processing has already started"
- end
-
- #
- # Check ordering.
- #
- if !ORDERINGS.include?(ordering)
- raise ArgumentError, "invalid ordering `#{ordering}'"
- end
- if ordering == PERMUTE && ENV.include?('POSIXLY_CORRECT')
- @ordering = REQUIRE_ORDER
- else
- @ordering = ordering
- end
- end
-
- #
- # Return ordering.
- #
- attr_reader :ordering
-
- #
- # Set options. Takes the same argument as GetoptLong.new.
- #
- # Raises a RuntimeError if option processing has already started.
- #
- def set_options(*arguments)
- #
- # The method is failed if option processing has already started.
- #
- if @status != STATUS_YET
- raise RuntimeError,
- "invoke set_options, but option processing has already started"
- end
-
- #
- # Clear tables of option names and argument flags.
- #
- @canonical_names.clear
- @argument_flags.clear
-
- arguments.each do |arg|
- if !arg.is_a?(Array)
- raise ArgumentError, "the option list contains non-Array argument"
- end
-
- #
- # Find an argument flag and it set to `argument_flag'.
- #
- argument_flag = nil
- arg.each do |i|
- if ARGUMENT_FLAGS.include?(i)
- if argument_flag != nil
- raise ArgumentError, "too many argument-flags"
- end
- argument_flag = i
- end
- end
-
- raise ArgumentError, "no argument-flag" if argument_flag == nil
-
- canonical_name = nil
- arg.each do |i|
- #
- # Check an option name.
- #
- next if i == argument_flag
- begin
- if !i.is_a?(String) || i !~ /^-([^-]|-.+)$/
- raise ArgumentError, "an invalid option `#{i}'"
- end
- if (@canonical_names.include?(i))
- raise ArgumentError, "option redefined `#{i}'"
- end
- rescue
- @canonical_names.clear
- @argument_flags.clear
- raise
- end
-
- #
- # Register the option (`i') to the `@canonical_names' and
- # `@canonical_names' Hashes.
- #
- if canonical_name == nil
- canonical_name = i
- end
- @canonical_names[i] = canonical_name
- @argument_flags[i] = argument_flag
- end
- raise ArgumentError, "no option name" if canonical_name == nil
- end
- return self
- end
-
- #
- # Set/Unset `quiet' mode.
- #
- attr_writer :quiet
-
- #
- # Return the flag of `quiet' mode.
- #
- attr_reader :quiet
-
- #
- # `quiet?' is an alias of `quiet'.
- #
- alias quiet? quiet
-
- #
- # Explicitly terminate option processing.
- #
- def terminate
- return nil if @status == STATUS_TERMINATED
- raise RuntimeError, "an error has occurred" if @error != nil
-
- @status = STATUS_TERMINATED
- @non_option_arguments.reverse_each do |argument|
- ARGV.unshift(argument)
- end
-
- @canonical_names = nil
- @argument_flags = nil
- @rest_singles = nil
- @non_option_arguments = nil
-
- return self
- end
-
- #
- # Returns true if option processing has terminated, false otherwise.
- #
- def terminated?
- return @status == STATUS_TERMINATED
- end
-
- #
- # Set an error (a protected method).
- #
- def set_error(type, message)
- $stderr.print("#{$0}: #{message}\n") if !@quiet
-
- @error = type
- @error_message = message
- @canonical_names = nil
- @argument_flags = nil
- @rest_singles = nil
- @non_option_arguments = nil
-
- raise type, message
- end
- protected :set_error
-
- #
- # Examine whether an option processing is failed.
- #
- attr_reader :error
-
- #
- # `error?' is an alias of `error'.
- #
- alias error? error
-
- # Return the appropriate error message in POSIX-defined format.
- # If no error has occurred, returns nil.
- #
- def error_message
- return @error_message
- end
-
- #
- # Get next option name and its argument, as an Array of two elements.
- #
- # The option name is always converted to the first (preferred)
- # name given in the original options to GetoptLong.new.
- #
- # Example: ['--option', 'value']
- #
- # Returns nil if the processing is complete (as determined by
- # STATUS_TERMINATED).
- #
- def get
- option_name, option_argument = nil, ''
-
- #
- # Check status.
- #
- return nil if @error != nil
- case @status
- when STATUS_YET
- @status = STATUS_STARTED
- when STATUS_TERMINATED
- return nil
- end
-
- #
- # Get next option argument.
- #
- if 0 < @rest_singles.length
- argument = '-' + @rest_singles
- elsif (ARGV.length == 0)
- terminate
- return nil
- elsif @ordering == PERMUTE
- while 0 < ARGV.length && ARGV[0] !~ /^-./
- @non_option_arguments.push(ARGV.shift)
- end
- if ARGV.length == 0
- terminate
- return nil
- end
- argument = ARGV.shift
- elsif @ordering == REQUIRE_ORDER
- if (ARGV[0] !~ /^-./)
- terminate
- return nil
- end
- argument = ARGV.shift
- else
- argument = ARGV.shift
- end
-
- #
- # Check the special argument `--'.
- # `--' indicates the end of the option list.
- #
- if argument == '--' && @rest_singles.length == 0
- terminate
- return nil
- end
-
- #
- # Check for long and short options.
- #
- if argument =~ /^(--[^=]+)/ && @rest_singles.length == 0
- #
- # This is a long style option, which start with `--'.
- #
- pattern = $1
- if @canonical_names.include?(pattern)
- option_name = pattern
- else
- #
- # The option `option_name' is not registered in `@canonical_names'.
- # It may be an abbreviated.
- #
- matches = []
- @canonical_names.each_key do |key|
- if key.index(pattern) == 0
- option_name = key
- matches << key
- end
- end
- if 2 <= matches.length
- set_error(AmbiguousOption, "option `#{argument}' is ambiguous between #{matches.join(', ')}")
- elsif matches.length == 0
- set_error(InvalidOption, "unrecognized option `#{argument}'")
- end
- end
-
- #
- # Check an argument to the option.
- #
- if @argument_flags[option_name] == REQUIRED_ARGUMENT
- if argument =~ /=(.*)$/
- option_argument = $1
- elsif 0 < ARGV.length
- option_argument = ARGV.shift
- else
- set_error(MissingArgument,
- "option `#{argument}' requires an argument")
- end
- elsif @argument_flags[option_name] == OPTIONAL_ARGUMENT
- if argument =~ /=(.*)$/
- option_argument = $1
- elsif 0 < ARGV.length && ARGV[0] !~ /^-./
- option_argument = ARGV.shift
- else
- option_argument = ''
- end
- elsif argument =~ /=(.*)$/
- set_error(NeedlessArgument,
- "option `#{option_name}' doesn't allow an argument")
- end
-
- elsif argument =~ /^(-(.))(.*)/
- #
- # This is a short style option, which start with `-' (not `--').
- # Short options may be catenated (e.g. `-l -g' is equivalent to
- # `-lg').
- #
- option_name, ch, @rest_singles = $1, $2, $3
-
- if @canonical_names.include?(option_name)
- #
- # The option `option_name' is found in `@canonical_names'.
- # Check its argument.
- #
- if @argument_flags[option_name] == REQUIRED_ARGUMENT
- if 0 < @rest_singles.length
- option_argument = @rest_singles
- @rest_singles = ''
- elsif 0 < ARGV.length
- option_argument = ARGV.shift
- else
- # 1003.2 specifies the format of this message.
- set_error(MissingArgument, "option requires an argument -- #{ch}")
- end
- elsif @argument_flags[option_name] == OPTIONAL_ARGUMENT
- if 0 < @rest_singles.length
- option_argument = @rest_singles
- @rest_singles = ''
- elsif 0 < ARGV.length && ARGV[0] !~ /^-./
- option_argument = ARGV.shift
- else
- option_argument = ''
- end
- end
- else
- #
- # This is an invalid option.
- # 1003.2 specifies the format of this message.
- #
- if ENV.include?('POSIXLY_CORRECT')
- set_error(InvalidOption, "invalid option -- #{ch}")
- else
- set_error(InvalidOption, "invalid option -- #{ch}")
- end
- end
- else
- #
- # This is a non-option argument.
- # Only RETURN_IN_ORDER falled into here.
- #
- return '', argument
- end
-
- return @canonical_names[option_name], option_argument
- end
-
- #
- # `get_option' is an alias of `get'.
- #
- alias get_option get
-
- # Iterator version of `get'.
- #
- # The block is called repeatedly with two arguments:
- # The first is the option name.
- # The second is the argument which followed it (if any).
- # Example: ('--opt', 'value')
- #
- # The option name is always converted to the first (preferred)
- # name given in the original options to GetoptLong.new.
- #
- def each
- loop do
- option_name, option_argument = get_option
- break if option_name == nil
- yield option_name, option_argument
- end
- end
-
- #
- # `each_option' is an alias of `each'.
- #
- alias each_option each
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/io/console/size.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/io/console/size.rb
deleted file mode 100755
index 519bc3be6..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/io/console/size.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-# fallback to console window size
-def IO.default_console_size
- [
- ENV["LINES"].to_i.nonzero? || 25,
- ENV["COLUMNS"].to_i.nonzero? || 80,
- ]
-end
-
-begin
- require 'io/console'
-rescue LoadError
- class IO
- alias console_size default_console_size
- end
-else
- # returns console window size
- def IO.console_size
- console.winsize
- rescue NoMethodError
- default_console_size
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/ipaddr.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/ipaddr.rb
deleted file mode 100755
index 4b6f3ae36..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/ipaddr.rb
+++ /dev/null
@@ -1,658 +0,0 @@
-#
-# ipaddr.rb - A class to manipulate an IP address
-#
-# Copyright (c) 2002 Hajimu UMEMOTO .
-# Copyright (c) 2007, 2009, 2012 Akinori MUSHA .
-# All rights reserved.
-#
-# You can redistribute and/or modify it under the same terms as Ruby.
-#
-# $Id: ipaddr.rb 52741 2015-11-24 15:49:21Z nagachika $
-#
-# Contact:
-# - Akinori MUSHA (current maintainer)
-#
-# TODO:
-# - scope_id support
-#
-require 'socket'
-
-# IPAddr provides a set of methods to manipulate an IP address. Both IPv4 and
-# IPv6 are supported.
-#
-# == Example
-#
-# require 'ipaddr'
-#
-# ipaddr1 = IPAddr.new "3ffe:505:2::1"
-#
-# p ipaddr1 #=> #
-#
-# p ipaddr1.to_s #=> "3ffe:505:2::1"
-#
-# ipaddr2 = ipaddr1.mask(48) #=> #
-#
-# p ipaddr2.to_s #=> "3ffe:505:2::"
-#
-# ipaddr3 = IPAddr.new "192.168.2.0/24"
-#
-# p ipaddr3 #=> #
-
-class IPAddr
-
- # 32 bit mask for IPv4
- IN4MASK = 0xffffffff
- # 128 bit mask for IPv4
- IN6MASK = 0xffffffffffffffffffffffffffffffff
- # Format string for IPv6
- IN6FORMAT = (["%.4x"] * 8).join(':')
-
- # Regexp _internally_ used for parsing IPv4 address.
- RE_IPV4ADDRLIKE = %r{
- \A
- (\d+) \. (\d+) \. (\d+) \. (\d+)
- \z
- }x
-
- # Regexp _internally_ used for parsing IPv6 address.
- RE_IPV6ADDRLIKE_FULL = %r{
- \A
- (?:
- (?: [\da-f]{1,4} : ){7} [\da-f]{1,4}
- |
- ( (?: [\da-f]{1,4} : ){6} )
- (\d+) \. (\d+) \. (\d+) \. (\d+)
- )
- \z
- }xi
-
- # Regexp _internally_ used for parsing IPv6 address.
- RE_IPV6ADDRLIKE_COMPRESSED = %r{
- \A
- ( (?: (?: [\da-f]{1,4} : )* [\da-f]{1,4} )? )
- ::
- ( (?:
- ( (?: [\da-f]{1,4} : )* )
- (?:
- [\da-f]{1,4}
- |
- (\d+) \. (\d+) \. (\d+) \. (\d+)
- )
- )? )
- \z
- }xi
-
- # Generic IPAddr related error. Exceptions raised in this class should
- # inherit from Error.
- class Error < ArgumentError; end
-
- # Raised when the provided IP address is an invalid address.
- class InvalidAddressError < Error; end
-
- # Raised when the address family is invalid such as an address with an
- # unsupported family, an address with an inconsistent family, or an address
- # who's family cannot be determined.
- class AddressFamilyError < Error; end
-
- # Raised when the address is an invalid length.
- class InvalidPrefixError < InvalidAddressError; end
-
- # Returns the address family of this IP address.
- attr_reader :family
-
- # Creates a new ipaddr containing the given network byte ordered
- # string form of an IP address.
- def IPAddr::new_ntoh(addr)
- return IPAddr.new(IPAddr::ntop(addr))
- end
-
- # Convert a network byte ordered string form of an IP address into
- # human readable form.
- def IPAddr::ntop(addr)
- case addr.size
- when 4
- s = addr.unpack('C4').join('.')
- when 16
- s = IN6FORMAT % addr.unpack('n8')
- else
- raise AddressFamilyError, "unsupported address family"
- end
- return s
- end
-
- # Returns a new ipaddr built by bitwise AND.
- def &(other)
- return self.clone.set(@addr & coerce_other(other).to_i)
- end
-
- # Returns a new ipaddr built by bitwise OR.
- def |(other)
- return self.clone.set(@addr | coerce_other(other).to_i)
- end
-
- # Returns a new ipaddr built by bitwise right-shift.
- def >>(num)
- return self.clone.set(@addr >> num)
- end
-
- # Returns a new ipaddr built by bitwise left shift.
- def <<(num)
- return self.clone.set(addr_mask(@addr << num))
- end
-
- # Returns a new ipaddr built by bitwise negation.
- def ~
- return self.clone.set(addr_mask(~@addr))
- end
-
- # Returns true if two ipaddrs are equal.
- def ==(other)
- other = coerce_other(other)
- return @family == other.family && @addr == other.to_i
- end
-
- # Returns a new ipaddr built by masking IP address with the given
- # prefixlen/netmask. (e.g. 8, 64, "255.255.255.0", etc.)
- def mask(prefixlen)
- return self.clone.mask!(prefixlen)
- end
-
- # Returns true if the given ipaddr is in the range.
- #
- # e.g.:
- # require 'ipaddr'
- # net1 = IPAddr.new("192.168.2.0/24")
- # net2 = IPAddr.new("192.168.2.100")
- # net3 = IPAddr.new("192.168.3.0")
- # p net1.include?(net2) #=> true
- # p net1.include?(net3) #=> false
- def include?(other)
- other = coerce_other(other)
- if ipv4_mapped?
- if (@mask_addr >> 32) != 0xffffffffffffffffffffffff
- return false
- end
- mask_addr = (@mask_addr & IN4MASK)
- addr = (@addr & IN4MASK)
- family = Socket::AF_INET
- else
- mask_addr = @mask_addr
- addr = @addr
- family = @family
- end
- if other.ipv4_mapped?
- other_addr = (other.to_i & IN4MASK)
- other_family = Socket::AF_INET
- else
- other_addr = other.to_i
- other_family = other.family
- end
-
- if family != other_family
- return false
- end
- return ((addr & mask_addr) == (other_addr & mask_addr))
- end
- alias === include?
-
- # Returns the integer representation of the ipaddr.
- def to_i
- return @addr
- end
-
- # Returns a string containing the IP address representation.
- def to_s
- str = to_string
- return str if ipv4?
-
- str.gsub!(/\b0{1,3}([\da-f]+)\b/i, '\1')
- loop do
- break if str.sub!(/\A0:0:0:0:0:0:0:0\z/, '::')
- break if str.sub!(/\b0:0:0:0:0:0:0\b/, ':')
- break if str.sub!(/\b0:0:0:0:0:0\b/, ':')
- break if str.sub!(/\b0:0:0:0:0\b/, ':')
- break if str.sub!(/\b0:0:0:0\b/, ':')
- break if str.sub!(/\b0:0:0\b/, ':')
- break if str.sub!(/\b0:0\b/, ':')
- break
- end
- str.sub!(/:{3,}/, '::')
-
- if /\A::(ffff:)?([\da-f]{1,4}):([\da-f]{1,4})\z/i =~ str
- str = sprintf('::%s%d.%d.%d.%d', $1, $2.hex / 256, $2.hex % 256, $3.hex / 256, $3.hex % 256)
- end
-
- str
- end
-
- # Returns a string containing the IP address representation in
- # canonical form.
- def to_string
- return _to_string(@addr)
- end
-
- # Returns a network byte ordered string form of the IP address.
- def hton
- case @family
- when Socket::AF_INET
- return [@addr].pack('N')
- when Socket::AF_INET6
- return (0..7).map { |i|
- (@addr >> (112 - 16 * i)) & 0xffff
- }.pack('n8')
- else
- raise AddressFamilyError, "unsupported address family"
- end
- end
-
- # Returns true if the ipaddr is an IPv4 address.
- def ipv4?
- return @family == Socket::AF_INET
- end
-
- # Returns true if the ipaddr is an IPv6 address.
- def ipv6?
- return @family == Socket::AF_INET6
- end
-
- # Returns true if the ipaddr is an IPv4-mapped IPv6 address.
- def ipv4_mapped?
- return ipv6? && (@addr >> 32) == 0xffff
- end
-
- # Returns true if the ipaddr is an IPv4-compatible IPv6 address.
- def ipv4_compat?
- if !ipv6? || (@addr >> 32) != 0
- return false
- end
- a = (@addr & IN4MASK)
- return a != 0 && a != 1
- end
-
- # Returns a new ipaddr built by converting the native IPv4 address
- # into an IPv4-mapped IPv6 address.
- def ipv4_mapped
- if !ipv4?
- raise InvalidAddressError, "not an IPv4 address"
- end
- return self.clone.set(@addr | 0xffff00000000, Socket::AF_INET6)
- end
-
- # Returns a new ipaddr built by converting the native IPv4 address
- # into an IPv4-compatible IPv6 address.
- def ipv4_compat
- if !ipv4?
- raise InvalidAddressError, "not an IPv4 address"
- end
- return self.clone.set(@addr, Socket::AF_INET6)
- end
-
- # Returns a new ipaddr built by converting the IPv6 address into a
- # native IPv4 address. If the IP address is not an IPv4-mapped or
- # IPv4-compatible IPv6 address, returns self.
- def native
- if !ipv4_mapped? && !ipv4_compat?
- return self
- end
- return self.clone.set(@addr & IN4MASK, Socket::AF_INET)
- end
-
- # Returns a string for DNS reverse lookup. It returns a string in
- # RFC3172 form for an IPv6 address.
- def reverse
- case @family
- when Socket::AF_INET
- return _reverse + ".in-addr.arpa"
- when Socket::AF_INET6
- return ip6_arpa
- else
- raise AddressFamilyError, "unsupported address family"
- end
- end
-
- # Returns a string for DNS reverse lookup compatible with RFC3172.
- def ip6_arpa
- if !ipv6?
- raise InvalidAddressError, "not an IPv6 address"
- end
- return _reverse + ".ip6.arpa"
- end
-
- # Returns a string for DNS reverse lookup compatible with RFC1886.
- def ip6_int
- if !ipv6?
- raise InvalidAddressError, "not an IPv6 address"
- end
- return _reverse + ".ip6.int"
- end
-
- # Returns the successor to the ipaddr.
- def succ
- return self.clone.set(@addr + 1, @family)
- end
-
- # Compares the ipaddr with another.
- def <=>(other)
- other = coerce_other(other)
-
- return nil if other.family != @family
-
- return @addr <=> other.to_i
- end
- include Comparable
-
- # Checks equality used by Hash.
- def eql?(other)
- return self.class == other.class && self.hash == other.hash && self == other
- end
-
- # Returns a hash value used by Hash, Set, and Array classes
- def hash
- return ([@addr, @mask_addr].hash << 1) | (ipv4? ? 0 : 1)
- end
-
- # Creates a Range object for the network address.
- def to_range
- begin_addr = (@addr & @mask_addr)
-
- case @family
- when Socket::AF_INET
- end_addr = (@addr | (IN4MASK ^ @mask_addr))
- when Socket::AF_INET6
- end_addr = (@addr | (IN6MASK ^ @mask_addr))
- else
- raise AddressFamilyError, "unsupported address family"
- end
-
- return clone.set(begin_addr, @family)..clone.set(end_addr, @family)
- end
-
- # Returns a string containing a human-readable representation of the
- # ipaddr. ("#")
- def inspect
- case @family
- when Socket::AF_INET
- af = "IPv4"
- when Socket::AF_INET6
- af = "IPv6"
- else
- raise AddressFamilyError, "unsupported address family"
- end
- return sprintf("#<%s: %s:%s/%s>", self.class.name,
- af, _to_string(@addr), _to_string(@mask_addr))
- end
-
- protected
-
- # Set +@addr+, the internal stored ip address, to given +addr+. The
- # parameter +addr+ is validated using the first +family+ member,
- # which is +Socket::AF_INET+ or +Socket::AF_INET6+.
- def set(addr, *family)
- case family[0] ? family[0] : @family
- when Socket::AF_INET
- if addr < 0 || addr > IN4MASK
- raise InvalidAddressError, "invalid address"
- end
- when Socket::AF_INET6
- if addr < 0 || addr > IN6MASK
- raise InvalidAddressError, "invalid address"
- end
- else
- raise AddressFamilyError, "unsupported address family"
- end
- @addr = addr
- if family[0]
- @family = family[0]
- end
- return self
- end
-
- # Set current netmask to given mask.
- def mask!(mask)
- if mask.kind_of?(String)
- if mask =~ /\A\d+\z/
- prefixlen = mask.to_i
- else
- m = IPAddr.new(mask)
- if m.family != @family
- raise InvalidPrefixError, "address family is not same"
- end
- @mask_addr = m.to_i
- @addr &= @mask_addr
- return self
- end
- else
- prefixlen = mask
- end
- case @family
- when Socket::AF_INET
- if prefixlen < 0 || prefixlen > 32
- raise InvalidPrefixError, "invalid length"
- end
- masklen = 32 - prefixlen
- @mask_addr = ((IN4MASK >> masklen) << masklen)
- when Socket::AF_INET6
- if prefixlen < 0 || prefixlen > 128
- raise InvalidPrefixError, "invalid length"
- end
- masklen = 128 - prefixlen
- @mask_addr = ((IN6MASK >> masklen) << masklen)
- else
- raise AddressFamilyError, "unsupported address family"
- end
- @addr = ((@addr >> masklen) << masklen)
- return self
- end
-
- private
-
- # Creates a new ipaddr object either from a human readable IP
- # address representation in string, or from a packed in_addr value
- # followed by an address family.
- #
- # In the former case, the following are the valid formats that will
- # be recognized: "address", "address/prefixlen" and "address/mask",
- # where IPv6 address may be enclosed in square brackets (`[' and
- # `]'). If a prefixlen or a mask is specified, it returns a masked
- # IP address. Although the address family is determined
- # automatically from a specified string, you can specify one
- # explicitly by the optional second argument.
- #
- # Otherwise an IP address is generated from a packed in_addr value
- # and an address family.
- #
- # The IPAddr class defines many methods and operators, and some of
- # those, such as &, |, include? and ==, accept a string, or a packed
- # in_addr value instead of an IPAddr object.
- def initialize(addr = '::', family = Socket::AF_UNSPEC)
- if !addr.kind_of?(String)
- case family
- when Socket::AF_INET, Socket::AF_INET6
- set(addr.to_i, family)
- @mask_addr = (family == Socket::AF_INET) ? IN4MASK : IN6MASK
- return
- when Socket::AF_UNSPEC
- raise AddressFamilyError, "address family must be specified"
- else
- raise AddressFamilyError, "unsupported address family: #{family}"
- end
- end
- prefix, prefixlen = addr.split('/')
- if prefix =~ /\A\[(.*)\]\z/i
- prefix = $1
- family = Socket::AF_INET6
- end
- # It seems AI_NUMERICHOST doesn't do the job.
- #Socket.getaddrinfo(left, nil, Socket::AF_INET6, Socket::SOCK_STREAM, nil,
- # Socket::AI_NUMERICHOST)
- @addr = @family = nil
- if family == Socket::AF_UNSPEC || family == Socket::AF_INET
- @addr = in_addr(prefix)
- if @addr
- @family = Socket::AF_INET
- end
- end
- if !@addr && (family == Socket::AF_UNSPEC || family == Socket::AF_INET6)
- @addr = in6_addr(prefix)
- @family = Socket::AF_INET6
- end
- if family != Socket::AF_UNSPEC && @family != family
- raise AddressFamilyError, "address family mismatch"
- end
- if prefixlen
- mask!(prefixlen)
- else
- @mask_addr = (@family == Socket::AF_INET) ? IN4MASK : IN6MASK
- end
- end
-
- def coerce_other(other)
- case other
- when IPAddr
- other
- when String
- self.class.new(other)
- else
- self.class.new(other, @family)
- end
- end
-
- def in_addr(addr)
- case addr
- when Array
- octets = addr
- else
- m = RE_IPV4ADDRLIKE.match(addr) or return nil
- octets = m.captures
- end
- octets.inject(0) { |i, s|
- (n = s.to_i) < 256 or raise InvalidAddressError, "invalid address"
- s.match(/\A0./) and raise InvalidAddressError, "zero-filled number in IPv4 address is ambiguous"
- i << 8 | n
- }
- end
-
- def in6_addr(left)
- case left
- when RE_IPV6ADDRLIKE_FULL
- if $2
- addr = in_addr($~[2,4])
- left = $1 + ':'
- else
- addr = 0
- end
- right = ''
- when RE_IPV6ADDRLIKE_COMPRESSED
- if $4
- left.count(':') <= 6 or raise InvalidAddressError, "invalid address"
- addr = in_addr($~[4,4])
- left = $1
- right = $3 + '0:0'
- else
- left.count(':') <= ($1.empty? || $2.empty? ? 8 : 7) or
- raise InvalidAddressError, "invalid address"
- left = $1
- right = $2
- addr = 0
- end
- else
- raise InvalidAddressError, "invalid address"
- end
- l = left.split(':')
- r = right.split(':')
- rest = 8 - l.size - r.size
- if rest < 0
- return nil
- end
- (l + Array.new(rest, '0') + r).inject(0) { |i, s|
- i << 16 | s.hex
- } | addr
- end
-
- def addr_mask(addr)
- case @family
- when Socket::AF_INET
- return addr & IN4MASK
- when Socket::AF_INET6
- return addr & IN6MASK
- else
- raise AddressFamilyError, "unsupported address family"
- end
- end
-
- def _reverse
- case @family
- when Socket::AF_INET
- return (0..3).map { |i|
- (@addr >> (8 * i)) & 0xff
- }.join('.')
- when Socket::AF_INET6
- return ("%.32x" % @addr).reverse!.gsub!(/.(?!$)/, '\&.')
- else
- raise AddressFamilyError, "unsupported address family"
- end
- end
-
- def _to_string(addr)
- case @family
- when Socket::AF_INET
- return (0..3).map { |i|
- (addr >> (24 - 8 * i)) & 0xff
- }.join('.')
- when Socket::AF_INET6
- return (("%.32x" % addr).gsub!(/.{4}(?!$)/, '\&:'))
- else
- raise AddressFamilyError, "unsupported address family"
- end
- end
-
-end
-
-unless Socket.const_defined? :AF_INET6
- class Socket < BasicSocket
- # IPv6 protocol family
- AF_INET6 = Object.new
- end
-
- class << IPSocket
- private
-
- def valid_v6?(addr)
- case addr
- when IPAddr::RE_IPV6ADDRLIKE_FULL
- if $2
- $~[2,4].all? {|i| i.to_i < 256 }
- else
- true
- end
- when IPAddr::RE_IPV6ADDRLIKE_COMPRESSED
- if $4
- addr.count(':') <= 6 && $~[4,4].all? {|i| i.to_i < 256}
- else
- addr.count(':') <= 7
- end
- else
- false
- end
- end
-
- alias getaddress_orig getaddress
-
- public
-
- # Returns a +String+ based representation of a valid DNS hostname,
- # IPv4 or IPv6 address.
- #
- # IPSocket.getaddress 'localhost' #=> "::1"
- # IPSocket.getaddress 'broadcasthost' #=> "255.255.255.255"
- # IPSocket.getaddress 'www.ruby-lang.org' #=> "221.186.184.68"
- # IPSocket.getaddress 'www.ccc.de' #=> "2a00:1328:e102:ccc0::122"
- def getaddress(s)
- if valid_v6?(s)
- s
- else
- getaddress_orig(s)
- end
- end
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb.rb
deleted file mode 100755
index 9944fee7a..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb.rb
+++ /dev/null
@@ -1,703 +0,0 @@
-#
-# irb.rb - irb main module
-# $Release Version: 0.9.6 $
-# $Revision: 47266 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-require "e2mmap"
-
-require "irb/init"
-require "irb/context"
-require "irb/extend-command"
-
-require "irb/ruby-lex"
-require "irb/input-method"
-require "irb/locale"
-
-STDOUT.sync = true
-
-# IRB stands for "interactive Ruby" and is a tool to interactively execute Ruby
-# expressions read from the standard input.
-#
-# The +irb+ command from your shell will start the interpreter.
-#
-# == Usage
-#
-# Use of irb is easy if you know Ruby.
-#
-# When executing irb, prompts are displayed as follows. Then, enter the Ruby
-# expression. An input is executed when it is syntactically complete.
-#
-# $ irb
-# irb(main):001:0> 1+2
-# #=> 3
-# irb(main):002:0> class Foo
-# irb(main):003:1> def foo
-# irb(main):004:2> print 1
-# irb(main):005:2> end
-# irb(main):006:1> end
-# #=> nil
-#
-# The Readline extension module can be used with irb. Use of Readline is
-# default if it's installed.
-#
-# == Command line options
-#
-# Usage: irb.rb [options] [programfile] [arguments]
-# -f Suppress read of ~/.irbrc
-# -m Bc mode (load mathn, fraction or matrix are available)
-# -d Set $DEBUG to true (same as `ruby -d')
-# -r load-module Same as `ruby -r'
-# -I path Specify $LOAD_PATH directory
-# -U Same as `ruby -U`
-# -E enc Same as `ruby -E`
-# -w Same as `ruby -w`
-# -W[level=2] Same as `ruby -W`
-# --inspect Use `inspect' for output (default except for bc mode)
-# --noinspect Don't use inspect for output
-# --readline Use Readline extension module
-# --noreadline Don't use Readline extension module
-# --prompt prompt-mode
-# --prompt-mode prompt-mode
-# Switch prompt mode. Pre-defined prompt modes are
-# `default', `simple', `xmp' and `inf-ruby'
-# --inf-ruby-mode Use prompt appropriate for inf-ruby-mode on emacs.
-# Suppresses --readline.
-# --simple-prompt Simple prompt mode
-# --noprompt No prompt mode
-# --tracer Display trace for each execution of commands.
-# --back-trace-limit n
-# Display backtrace top n and tail n. The default
-# value is 16.
-# --irb_debug n Set internal debug level to n (not for popular use)
-# -v, --version Print the version of irb
-#
-# == Configuration
-#
-# IRB reads from ~/.irbrc
when it's invoked.
-#
-# If ~/.irbrc
doesn't exist, +irb+ will try to read in the following order:
-#
-# * +.irbrc+
-# * +irb.rc+
-# * +_irbrc+
-# * $irbrc
-#
-# The following are alternatives to the command line options. To use them type
-# as follows in an +irb+ session:
-#
-# IRB.conf[:IRB_NAME]="irb"
-# IRB.conf[:MATH_MODE]=false
-# IRB.conf[:INSPECT_MODE]=nil
-# IRB.conf[:IRB_RC] = nil
-# IRB.conf[:BACK_TRACE_LIMIT]=16
-# IRB.conf[:USE_LOADER] = false
-# IRB.conf[:USE_READLINE] = nil
-# IRB.conf[:USE_TRACER] = false
-# IRB.conf[:IGNORE_SIGINT] = true
-# IRB.conf[:IGNORE_EOF] = false
-# IRB.conf[:PROMPT_MODE] = :DEFAULT
-# IRB.conf[:PROMPT] = {...}
-# IRB.conf[:DEBUG_LEVEL]=0
-#
-# === Auto indentation
-#
-# To enable auto-indent mode in irb, add the following to your +.irbrc+:
-#
-# IRB.conf[:AUTO_INDENT] = true
-#
-# === Autocompletion
-#
-# To enable autocompletion for irb, add the following to your +.irbrc+:
-#
-# require 'irb/completion'
-#
-# === History
-#
-# By default, irb disables history and will not store any commands you used.
-#
-# If you want to enable history, add the following to your +.irbrc+:
-#
-# IRB.conf[:SAVE_HISTORY] = 1000
-#
-# This will now store the last 1000 commands in ~/.irb_history
.
-#
-# See IRB::Context#save_history= for more information.
-#
-# == Customizing the IRB Prompt
-#
-# In order to customize the prompt, you can change the following Hash:
-#
-# IRB.conf[:PROMPT]
-#
-# This example can be used in your +.irbrc+
-#
-# IRB.conf[:PROMPT][:MY_PROMPT] = { # name of prompt mode
-# :AUTO_INDENT => true, # enables auto-indent mode
-# :PROMPT_I => ">> ", # simple prompt
-# :PROMPT_S => nil, # prompt for continuated strings
-# :PROMPT_C => nil, # prompt for continuated statement
-# :RETURN => " ==>%s\n" # format to return value
-# }
-#
-# IRB.conf[:PROMPT_MODE] = :MY_PROMPT
-#
-# Or, invoke irb with the above prompt mode by:
-#
-# irb --prompt my-prompt
-#
-# Constants +PROMPT_I+, +PROMPT_S+ and +PROMPT_C+ specify the format. In the
-# prompt specification, some special strings are available:
-#
-# %N # command name which is running
-# %m # to_s of main object (self)
-# %M # inspect of main object (self)
-# %l # type of string(", ', /, ]), `]' is inner %w[...]
-# %NNi # indent level. NN is digits and means as same as printf("%NNd").
-# # It can be ommited
-# %NNn # line number.
-# %% # %
-#
-# For instance, the default prompt mode is defined as follows:
-#
-# IRB.conf[:PROMPT_MODE][:DEFAULT] = {
-# :PROMPT_I => "%N(%m):%03n:%i> ",
-# :PROMPT_S => "%N(%m):%03n:%i%l ",
-# :PROMPT_C => "%N(%m):%03n:%i* ",
-# :RETURN => "%s\n" # used to printf
-# }
-#
-# irb comes with a number of available modes:
-#
-# # :NULL:
-# # :PROMPT_I:
-# # :PROMPT_N:
-# # :PROMPT_S:
-# # :PROMPT_C:
-# # :RETURN: |
-# # %s
-# # :DEFAULT:
-# # :PROMPT_I: ! '%N(%m):%03n:%i> '
-# # :PROMPT_N: ! '%N(%m):%03n:%i> '
-# # :PROMPT_S: ! '%N(%m):%03n:%i%l '
-# # :PROMPT_C: ! '%N(%m):%03n:%i* '
-# # :RETURN: |
-# # => %s
-# # :CLASSIC:
-# # :PROMPT_I: ! '%N(%m):%03n:%i> '
-# # :PROMPT_N: ! '%N(%m):%03n:%i> '
-# # :PROMPT_S: ! '%N(%m):%03n:%i%l '
-# # :PROMPT_C: ! '%N(%m):%03n:%i* '
-# # :RETURN: |
-# # %s
-# # :SIMPLE:
-# # :PROMPT_I: ! '>> '
-# # :PROMPT_N: ! '>> '
-# # :PROMPT_S:
-# # :PROMPT_C: ! '?> '
-# # :RETURN: |
-# # => %s
-# # :INF_RUBY:
-# # :PROMPT_I: ! '%N(%m):%03n:%i> '
-# # :PROMPT_N:
-# # :PROMPT_S:
-# # :PROMPT_C:
-# # :RETURN: |
-# # %s
-# # :AUTO_INDENT: true
-# # :XMP:
-# # :PROMPT_I:
-# # :PROMPT_N:
-# # :PROMPT_S:
-# # :PROMPT_C:
-# # :RETURN: |2
-# # ==>%s
-#
-# == Restrictions
-#
-# Because irb evaluates input immediately after it is syntactically complete,
-# the results may be slightly different than directly using Ruby.
-#
-# == IRB Sessions
-#
-# IRB has a special feature, that allows you to manage many sessions at once.
-#
-# You can create new sessions with Irb.irb, and get a list of current sessions
-# with the +jobs+ command in the prompt.
-#
-# === Commands
-#
-# JobManager provides commands to handle the current sessions:
-#
-# jobs # List of current sessions
-# fg # Switches to the session of the given number
-# kill # Kills the session with the given number
-#
-# The +exit+ command, or ::irb_exit, will quit the current session and call any
-# exit hooks with IRB.irb_at_exit.
-#
-# A few commands for loading files within the session are also available:
-#
-# +source+::
-# Loads a given file in the current session and displays the source lines,
-# see IrbLoader#source_file
-# +irb_load+::
-# Loads the given file similarly to Kernel#load, see IrbLoader#irb_load
-# +irb_require+::
-# Loads the given file similarly to Kernel#require
-#
-# === Configuration
-#
-# The command line options, or IRB.conf, specify the default behavior of
-# Irb.irb.
-#
-# On the other hand, each conf in IRB@Command+line+options is used to
-# individually configure IRB.irb.
-#
-# If a proc is set for IRB.conf[:IRB_RC], its will be invoked after execution
-# of that proc with the context of the current session as its argument. Each
-# session can be configured using this mechanism.
-#
-# === Session variables
-#
-# There are a few variables in every Irb session that can come in handy:
-#
-# _
::
-# The value command executed, as a local variable
-# __
::
-# The history of evaluated commands
-# __[line_no]
::
-# Returns the evaluation value at the given line number, +line_no+.
-# If +line_no+ is a negative, the return value +line_no+ many lines before
-# the most recent return value.
-#
-# === Example using IRB Sessions
-#
-# # invoke a new session
-# irb(main):001:0> irb
-# # list open sessions
-# irb.1(main):001:0> jobs
-# #0->irb on main (# : stop)
-# #1->irb#1 on main (# : running)
-#
-# # change the active session
-# irb.1(main):002:0> fg 0
-# # define class Foo in top-level session
-# irb(main):002:0> class Foo;end
-# # invoke a new session with the context of Foo
-# irb(main):003:0> irb Foo
-# # define Foo#foo
-# irb.2(Foo):001:0> def foo
-# irb.2(Foo):002:1> print 1
-# irb.2(Foo):003:1> end
-#
-# # change the active session
-# irb.2(Foo):004:0> fg 0
-# # list open sessions
-# irb(main):004:0> jobs
-# #0->irb on main (# : running)
-# #1->irb#1 on main (# : stop)
-# #2->irb#2 on Foo (# : stop)
-# # check if Foo#foo is available
-# irb(main):005:0> Foo.instance_methods #=> [:foo, ...]
-#
-# # change the active sesssion
-# irb(main):006:0> fg 2
-# # define Foo#bar in the context of Foo
-# irb.2(Foo):005:0> def bar
-# irb.2(Foo):006:1> print "bar"
-# irb.2(Foo):007:1> end
-# irb.2(Foo):010:0> Foo.instance_methods #=> [:bar, :foo, ...]
-#
-# # change the active session
-# irb.2(Foo):011:0> fg 0
-# irb(main):007:0> f = Foo.new #=> #
-# # invoke a new session with the context of f (instance of Foo)
-# irb(main):008:0> irb f
-# # list open sessions
-# irb.3():001:0> jobs
-# #0->irb on main (# : stop)
-# #1->irb#1 on main (# : stop)
-# #2->irb#2 on Foo (# : stop)
-# #3->irb#3 on # (# : running)
-# # evaluate f.foo
-# irb.3():002:0> foo #=> 1 => nil
-# # evaluate f.bar
-# irb.3():003:0> bar #=> bar => nil
-# # kill jobs 1, 2, and 3
-# irb.3():004:0> kill 1, 2, 3
-# # list open sesssions, should only include main session
-# irb(main):009:0> jobs
-# #0->irb on main (# : running)
-# # quit irb
-# irb(main):010:0> exit
-module IRB
-
- # An exception raised by IRB.irb_abort
- class Abort < Exception;end
-
- @CONF = {}
-
-
- # Displays current configuration.
- #
- # Modifing the configuration is achieved by sending a message to IRB.conf.
- #
- # See IRB@Configuration for more information.
- def IRB.conf
- @CONF
- end
-
- # Returns the current version of IRB, including release version and last
- # updated date.
- def IRB.version
- if v = @CONF[:VERSION] then return v end
-
- require "irb/version"
- rv = @RELEASE_VERSION.sub(/\.0/, "")
- @CONF[:VERSION] = format("irb %s(%s)", rv, @LAST_UPDATE_DATE)
- end
-
- # The current IRB::Context of the session, see IRB.conf
- #
- # irb
- # irb(main):001:0> IRB.CurrentContext.irb_name = "foo"
- # foo(main):002:0> IRB.conf[:MAIN_CONTEXT].irb_name #=> "foo"
- def IRB.CurrentContext
- IRB.conf[:MAIN_CONTEXT]
- end
-
- # Initializes IRB and creates a new Irb.irb object at the +TOPLEVEL_BINDING+
- def IRB.start(ap_path = nil)
- $0 = File::basename(ap_path, ".rb") if ap_path
-
- IRB.setup(ap_path)
-
- if @CONF[:SCRIPT]
- irb = Irb.new(nil, @CONF[:SCRIPT])
- else
- irb = Irb.new
- end
-
- @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC]
- @CONF[:MAIN_CONTEXT] = irb.context
-
- trap("SIGINT") do
- irb.signal_handle
- end
-
- begin
- catch(:IRB_EXIT) do
- irb.eval_input
- end
- ensure
- irb_at_exit
- end
- end
-
- # Calls each event hook of IRB.conf[:AT_EXIT] when the current session quits.
- def IRB.irb_at_exit
- @CONF[:AT_EXIT].each{|hook| hook.call}
- end
-
- # Quits irb
- def IRB.irb_exit(irb, ret)
- throw :IRB_EXIT, ret
- end
-
- # Aborts then interrupts irb.
- #
- # Will raise an Abort exception, or the given +exception+.
- def IRB.irb_abort(irb, exception = Abort)
- if defined? Thread
- irb.context.thread.raise exception, "abort then interrupt!"
- else
- raise exception, "abort then interrupt!"
- end
- end
-
- class Irb
- # Creates a new irb session
- def initialize(workspace = nil, input_method = nil, output_method = nil)
- @context = Context.new(self, workspace, input_method, output_method)
- @context.main.extend ExtendCommandBundle
- @signal_status = :IN_IRB
-
- @scanner = RubyLex.new
- @scanner.exception_on_syntax_error = false
- end
- # Returns the current context of this irb session
- attr_reader :context
- # The lexer used by this irb session
- attr_accessor :scanner
-
- # Evaluates input for this session.
- def eval_input
- @scanner.set_prompt do
- |ltype, indent, continue, line_no|
- if ltype
- f = @context.prompt_s
- elsif continue
- f = @context.prompt_c
- elsif indent > 0
- f = @context.prompt_n
- else
- f = @context.prompt_i
- end
- f = "" unless f
- if @context.prompting?
- @context.io.prompt = p = prompt(f, ltype, indent, line_no)
- else
- @context.io.prompt = p = ""
- end
- if @context.auto_indent_mode
- unless ltype
- ind = prompt(@context.prompt_i, ltype, indent, line_no)[/.*\z/].size +
- indent * 2 - p.size
- ind += 2 if continue
- @context.io.prompt = p + " " * ind if ind > 0
- end
- end
- end
-
- @scanner.set_input(@context.io) do
- signal_status(:IN_INPUT) do
- if l = @context.io.gets
- print l if @context.verbose?
- else
- if @context.ignore_eof? and @context.io.readable_after_eof?
- l = "\n"
- if @context.verbose?
- printf "Use \"exit\" to leave %s\n", @context.ap_name
- end
- else
- print "\n"
- end
- end
- l
- end
- end
-
- @scanner.each_top_level_statement do |line, line_no|
- signal_status(:IN_EVAL) do
- begin
- line.untaint
- @context.evaluate(line, line_no)
- output_value if @context.echo?
- exc = nil
- rescue Interrupt => exc
- rescue SystemExit, SignalException
- raise
- rescue Exception => exc
- end
- if exc
- print exc.class, ": ", exc, "\n"
- if exc.backtrace && exc.backtrace[0] =~ /irb(2)?(\/.*|-.*|\.rb)?:/ && exc.class.to_s !~ /^IRB/ &&
- !(SyntaxError === exc)
- irb_bug = true
- else
- irb_bug = false
- end
-
- messages = []
- lasts = []
- levels = 0
- if exc.backtrace
- for m in exc.backtrace
- m = @context.workspace.filter_backtrace(m) unless irb_bug
- if m
- if messages.size < @context.back_trace_limit
- messages.push "\tfrom "+m
- else
- lasts.push "\tfrom "+m
- if lasts.size > @context.back_trace_limit
- lasts.shift
- levels += 1
- end
- end
- end
- end
- end
- print messages.join("\n"), "\n"
- unless lasts.empty?
- printf "... %d levels...\n", levels if levels > 0
- print lasts.join("\n")
- end
- print "Maybe IRB bug!\n" if irb_bug
- end
- if $SAFE > 2
- abort "Error: irb does not work for $SAFE level higher than 2"
- end
- end
- end
- end
-
- # Evaluates the given block using the given +path+ as the Context#irb_path
- # and +name+ as the Context#irb_name.
- #
- # Used by the irb command +source+, see IRB@IRB+Sessions for more
- # information.
- def suspend_name(path = nil, name = nil)
- @context.irb_path, back_path = path, @context.irb_path if path
- @context.irb_name, back_name = name, @context.irb_name if name
- begin
- yield back_path, back_name
- ensure
- @context.irb_path = back_path if path
- @context.irb_name = back_name if name
- end
- end
-
- # Evaluates the given block using the given +workspace+ as the
- # Context#workspace.
- #
- # Used by the irb command +irb_load+, see IRB@IRB+Sessions for more
- # information.
- def suspend_workspace(workspace)
- @context.workspace, back_workspace = workspace, @context.workspace
- begin
- yield back_workspace
- ensure
- @context.workspace = back_workspace
- end
- end
-
- # Evaluates the given block using the given +input_method+ as the
- # Context#io.
- #
- # Used by the irb commands +source+ and +irb_load+, see IRB@IRB+Sessions
- # for more information.
- def suspend_input_method(input_method)
- back_io = @context.io
- @context.instance_eval{@io = input_method}
- begin
- yield back_io
- ensure
- @context.instance_eval{@io = back_io}
- end
- end
-
- # Evaluates the given block using the given +context+ as the Context.
- def suspend_context(context)
- @context, back_context = context, @context
- begin
- yield back_context
- ensure
- @context = back_context
- end
- end
-
- # Handler for the signal SIGINT, see Kernel#trap for more information.
- def signal_handle
- unless @context.ignore_sigint?
- print "\nabort!\n" if @context.verbose?
- exit
- end
-
- case @signal_status
- when :IN_INPUT
- print "^C\n"
- raise RubyLex::TerminateLineInput
- when :IN_EVAL
- IRB.irb_abort(self)
- when :IN_LOAD
- IRB.irb_abort(self, LoadAbort)
- when :IN_IRB
- # ignore
- else
- # ignore other cases as well
- end
- end
-
- # Evaluates the given block using the given +status+.
- def signal_status(status)
- return yield if @signal_status == :IN_LOAD
-
- signal_status_back = @signal_status
- @signal_status = status
- begin
- yield
- ensure
- @signal_status = signal_status_back
- end
- end
-
- def prompt(prompt, ltype, indent, line_no) # :nodoc:
- p = prompt.dup
- p.gsub!(/%([0-9]+)?([a-zA-Z])/) do
- case $2
- when "N"
- @context.irb_name
- when "m"
- @context.main.to_s
- when "M"
- @context.main.inspect
- when "l"
- ltype
- when "i"
- if $1
- format("%" + $1 + "d", indent)
- else
- indent.to_s
- end
- when "n"
- if $1
- format("%" + $1 + "d", line_no)
- else
- line_no.to_s
- end
- when "%"
- "%"
- end
- end
- p
- end
-
- def output_value # :nodoc:
- printf @context.return_format, @context.inspect_last_value
- end
-
- # Outputs the local variables to this current session, including
- # #signal_status and #context, using IRB::Locale.
- def inspect
- ary = []
- for iv in instance_variables
- case (iv = iv.to_s)
- when "@signal_status"
- ary.push format("%s=:%s", iv, @signal_status.id2name)
- when "@context"
- ary.push format("%s=%s", iv, eval(iv).__to_s__)
- else
- ary.push format("%s=%s", iv, eval(iv))
- end
- end
- format("#<%s: %s>", self.class, ary.join(", "))
- end
- end
-
- def @CONF.inspect
- IRB.version unless self[:VERSION]
-
- array = []
- for k, v in sort{|a1, a2| a1[0].id2name <=> a2[0].id2name}
- case k
- when :MAIN_CONTEXT, :__TMP__EHV__
- array.push format("CONF[:%s]=...myself...", k.id2name)
- when :PROMPT
- s = v.collect{
- |kk, vv|
- ss = vv.collect{|kkk, vvv| ":#{kkk.id2name}=>#{vvv.inspect}"}
- format(":%s=>{%s}", kk.id2name, ss.join(", "))
- }
- array.push format("CONF[:%s]={%s}", k.id2name, s.join(", "))
- else
- array.push format("CONF[:%s]=%s", k.id2name, v.inspect)
- end
- end
- array.join("\n")
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/cmd/chws.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/cmd/chws.rb
deleted file mode 100755
index bc39fd11e..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/cmd/chws.rb
+++ /dev/null
@@ -1,33 +0,0 @@
-#
-# change-ws.rb -
-# $Release Version: 0.9.6$
-# $Revision: 47112 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-require "irb/cmd/nop.rb"
-require "irb/ext/change-ws.rb"
-
-# :stopdoc:
-module IRB
- module ExtendCommand
-
- class CurrentWorkingWorkspace == === =~ > >= >> [] []= ^ ! != !~]
-
- def self.select_message(receiver, message, candidates, sep = ".")
- candidates.grep(/^#{message}/).collect do |e|
- case e
- when /^[a-zA-Z_]/
- receiver + sep + e
- when /^[0-9]/
- when *Operators
- #receiver + " " + e
- end
- end
- end
- end
-end
-
-if Readline.respond_to?("basic_word_break_characters=")
- Readline.basic_word_break_characters= " \t\n`><=;|&{("
-end
-Readline.completion_append_character = nil
-Readline.completion_proc = IRB::InputCompletor::CompletionProc
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/context.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/context.rb
deleted file mode 100755
index 00061867c..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/context.rb
+++ /dev/null
@@ -1,419 +0,0 @@
-#
-# irb/context.rb - irb context
-# $Release Version: 0.9.6$
-# $Revision: 47114 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-require "irb/workspace"
-require "irb/inspector"
-
-module IRB
- # A class that wraps the current state of the irb session, including the
- # configuration of IRB.conf.
- class Context
- # Creates a new IRB context.
- #
- # The optional +input_method+ argument:
- #
- # +nil+:: uses stdin or Readline
- # +String+:: uses a File
- # +other+:: uses this as InputMethod
- def initialize(irb, workspace = nil, input_method = nil, output_method = nil)
- @irb = irb
- if workspace
- @workspace = workspace
- else
- @workspace = WorkSpace.new
- end
- @thread = Thread.current if defined? Thread
-
- # copy of default configuration
- @ap_name = IRB.conf[:AP_NAME]
- @rc = IRB.conf[:RC]
- @load_modules = IRB.conf[:LOAD_MODULES]
-
- @use_readline = IRB.conf[:USE_READLINE]
- @verbose = IRB.conf[:VERBOSE]
- @io = nil
-
- self.inspect_mode = IRB.conf[:INSPECT_MODE]
- self.math_mode = IRB.conf[:MATH_MODE] if IRB.conf[:MATH_MODE]
- self.use_tracer = IRB.conf[:USE_TRACER] if IRB.conf[:USE_TRACER]
- self.use_loader = IRB.conf[:USE_LOADER] if IRB.conf[:USE_LOADER]
- self.eval_history = IRB.conf[:EVAL_HISTORY] if IRB.conf[:EVAL_HISTORY]
-
- @ignore_sigint = IRB.conf[:IGNORE_SIGINT]
- @ignore_eof = IRB.conf[:IGNORE_EOF]
-
- @back_trace_limit = IRB.conf[:BACK_TRACE_LIMIT]
-
- self.prompt_mode = IRB.conf[:PROMPT_MODE]
-
- if IRB.conf[:SINGLE_IRB] or !defined?(IRB::JobManager)
- @irb_name = IRB.conf[:IRB_NAME]
- else
- @irb_name = IRB.conf[:IRB_NAME]+"#"+IRB.JobManager.n_jobs.to_s
- end
- @irb_path = "(" + @irb_name + ")"
-
- case input_method
- when nil
- case use_readline?
- when nil
- if (defined?(ReadlineInputMethod) && STDIN.tty? &&
- IRB.conf[:PROMPT_MODE] != :INF_RUBY)
- @io = ReadlineInputMethod.new
- else
- @io = StdioInputMethod.new
- end
- when false
- @io = StdioInputMethod.new
- when true
- if defined?(ReadlineInputMethod)
- @io = ReadlineInputMethod.new
- else
- @io = StdioInputMethod.new
- end
- end
-
- when String
- @io = FileInputMethod.new(input_method)
- @irb_name = File.basename(input_method)
- @irb_path = input_method
- else
- @io = input_method
- end
- self.save_history = IRB.conf[:SAVE_HISTORY] if IRB.conf[:SAVE_HISTORY]
-
- if output_method
- @output_method = output_method
- else
- @output_method = StdioOutputMethod.new
- end
-
- @echo = IRB.conf[:ECHO]
- if @echo.nil?
- @echo = true
- end
- self.debug_level = IRB.conf[:DEBUG_LEVEL]
- end
-
- # The top-level workspace, see WorkSpace#main
- def main
- @workspace.main
- end
-
- # The toplevel workspace, see #home_workspace
- attr_reader :workspace_home
- # WorkSpace in the current context
- attr_accessor :workspace
- # The current thread in this context
- attr_reader :thread
- # The current input method
- #
- # Can be either StdioInputMethod, ReadlineInputMethod, FileInputMethod or
- # other specified when the context is created. See ::new for more
- # information on +input_method+.
- attr_accessor :io
-
- # Current irb session
- attr_accessor :irb
- # A copy of the default IRB.conf[:AP_NAME]
- attr_accessor :ap_name
- # A copy of the default IRB.conf[:RC]
- attr_accessor :rc
- # A copy of the default IRB.conf[:LOAD_MODULES]
- attr_accessor :load_modules
- # Can be either name from IRB.conf[:IRB_NAME]
, or the number of
- # the current job set by JobManager, such as irb#2
- attr_accessor :irb_name
- # Can be either the #irb_name surrounded by parenthesis, or the
- # +input_method+ passed to Context.new
- attr_accessor :irb_path
-
- # Whether +Readline+ is enabled or not.
- #
- # A copy of the default IRB.conf[:USE_READLINE]
- #
- # See #use_readline= for more information.
- attr_reader :use_readline
- # A copy of the default IRB.conf[:INSPECT_MODE]
- attr_reader :inspect_mode
-
- # A copy of the default IRB.conf[:PROMPT_MODE]
- attr_reader :prompt_mode
- # Standard IRB prompt
- #
- # See IRB@Customizing+the+IRB+Prompt for more information.
- attr_accessor :prompt_i
- # IRB prompt for continuated strings
- #
- # See IRB@Customizing+the+IRB+Prompt for more information.
- attr_accessor :prompt_s
- # IRB prompt for continuated statement (e.g. immediately after an +if+)
- #
- # See IRB@Customizing+the+IRB+Prompt for more information.
- attr_accessor :prompt_c
- # See IRB@Customizing+the+IRB+Prompt for more information.
- attr_accessor :prompt_n
- # Can be either the default IRB.conf[:AUTO_INDENT]
, or the
- # mode set by #prompt_mode=
- #
- # To enable auto-indentation in irb:
- #
- # IRB.conf[:AUTO_INDENT] = true
- #
- # or
- #
- # irb_context.auto_indent_mode = true
- #
- # or
- #
- # IRB.CurrentContext.auto_indent_mode = true
- #
- # See IRB@Configuration for more information.
- attr_accessor :auto_indent_mode
- # The format of the return statement, set by #prompt_mode= using the
- # +:RETURN+ of the +mode+ passed to set the current #prompt_mode.
- attr_accessor :return_format
-
- # Whether ^C
(+control-c+) will be ignored or not.
- #
- # If set to +false+, ^C
will quit irb.
- #
- # If set to +true+,
- #
- # * during input: cancel input then return to top level.
- # * during execute: abandon current execution.
- attr_accessor :ignore_sigint
- # Whether ^D
(+control-d+) will be ignored or not.
- #
- # If set to +false+, ^D
will quit irb.
- attr_accessor :ignore_eof
- # Whether to echo the return value to output or not.
- #
- # Uses IRB.conf[:ECHO] if available, or defaults to +true+.
- #
- # puts "hello"
- # # hello
- # #=> nil
- # IRB.CurrentContext.echo = false
- # puts "omg"
- # # omg
- attr_accessor :echo
- # Whether verbose messages are displayed or not.
- #
- # A copy of the default IRB.conf[:VERBOSE]
- attr_accessor :verbose
- # The debug level of irb
- #
- # See #debug_level= for more information.
- attr_reader :debug_level
-
- # The limit of backtrace lines displayed as top +n+ and tail +n+.
- #
- # The default value is 16.
- #
- # Can also be set using the +--back-trace-limit+ command line option.
- #
- # See IRB@Command+line+options for more command line options.
- attr_accessor :back_trace_limit
-
- # Alias for #use_readline
- alias use_readline? use_readline
- # Alias for #rc
- alias rc? rc
- alias ignore_sigint? ignore_sigint
- alias ignore_eof? ignore_eof
- alias echo? echo
-
- # Returns whether messages are displayed or not.
- def verbose?
- if @verbose.nil?
- if defined?(ReadlineInputMethod) && @io.kind_of?(ReadlineInputMethod)
- false
- elsif !STDIN.tty? or @io.kind_of?(FileInputMethod)
- true
- else
- false
- end
- else
- @verbose
- end
- end
-
- # Whether #verbose? is +true+, and +input_method+ is either
- # StdioInputMethod or ReadlineInputMethod, see #io for more information.
- def prompting?
- verbose? || (STDIN.tty? && @io.kind_of?(StdioInputMethod) ||
- (defined?(ReadlineInputMethod) && @io.kind_of?(ReadlineInputMethod)))
- end
-
- # The return value of the last statement evaluated.
- attr_reader :last_value
-
- # Sets the return value from the last statement evaluated in this context
- # to #last_value.
- def set_last_value(value)
- @last_value = value
- @workspace.evaluate self, "_ = IRB.CurrentContext.last_value"
- end
-
- # Sets the +mode+ of the prompt in this context.
- #
- # See IRB@Customizing+the+IRB+Prompt for more information.
- def prompt_mode=(mode)
- @prompt_mode = mode
- pconf = IRB.conf[:PROMPT][mode]
- @prompt_i = pconf[:PROMPT_I]
- @prompt_s = pconf[:PROMPT_S]
- @prompt_c = pconf[:PROMPT_C]
- @prompt_n = pconf[:PROMPT_N]
- @return_format = pconf[:RETURN]
- if ai = pconf.include?(:AUTO_INDENT)
- @auto_indent_mode = ai
- else
- @auto_indent_mode = IRB.conf[:AUTO_INDENT]
- end
- end
-
- # Whether #inspect_mode is set or not, see #inspect_mode= for more detail.
- def inspect?
- @inspect_mode.nil? or @inspect_mode
- end
-
- # Whether #io uses a File for the +input_method+ passed when creating the
- # current context, see ::new
- def file_input?
- @io.class == FileInputMethod
- end
-
- # Specifies the inspect mode with +opt+:
- #
- # +true+:: display +inspect+
- # +false+:: display +to_s+
- # +nil+:: inspect mode in non-math mode,
- # non-inspect mode in math mode
- #
- # See IRB::Inspector for more information.
- #
- # Can also be set using the +--inspect+ and +--noinspect+ command line
- # options.
- #
- # See IRB@Command+line+options for more command line options.
- def inspect_mode=(opt)
-
- if i = Inspector::INSPECTORS[opt]
- @inspect_mode = opt
- @inspect_method = i
- i.init
- else
- case opt
- when nil
- if Inspector.keys_with_inspector(Inspector::INSPECTORS[true]).include?(@inspect_mode)
- self.inspect_mode = false
- elsif Inspector.keys_with_inspector(Inspector::INSPECTORS[false]).include?(@inspect_mode)
- self.inspect_mode = true
- else
- puts "Can't switch inspect mode."
- return
- end
- when /^\s*\{.*\}\s*$/
- begin
- inspector = eval "proc#{opt}"
- rescue Exception
- puts "Can't switch inspect mode(#{opt})."
- return
- end
- self.inspect_mode = inspector
- when Proc
- self.inspect_mode = IRB::Inspector(opt)
- when Inspector
- prefix = "usr%d"
- i = 1
- while Inspector::INSPECTORS[format(prefix, i)]; i += 1; end
- @inspect_mode = format(prefix, i)
- @inspect_method = opt
- Inspector.def_inspector(format(prefix, i), @inspect_method)
- else
- puts "Can't switch inspect mode(#{opt})."
- return
- end
- end
- print "Switch to#{unless @inspect_mode; ' non';end} inspect mode.\n" if verbose?
- @inspect_mode
- end
-
- # Obsolete method.
- #
- # Can be set using the +--noreadline+ and +--readline+ command line
- # options.
- #
- # See IRB@Command+line+options for more command line options.
- def use_readline=(opt)
- print "This method is obsolete."
- print "Do nothing."
- end
-
- # Sets the debug level of irb
- #
- # Can also be set using the +--irb_debug+ command line option.
- #
- # See IRB@Command+line+options for more command line options.
- def debug_level=(value)
- @debug_level = value
- RubyLex.debug_level = value
- end
-
- # Whether or not debug mode is enabled, see #debug_level=.
- def debug?
- @debug_level > 0
- end
-
- def evaluate(line, line_no) # :nodoc:
- @line_no = line_no
- set_last_value(@workspace.evaluate(self, line, irb_path, line_no))
- end
-
- def inspect_last_value # :nodoc:
- @inspect_method.inspect_value(@last_value)
- end
-
- alias __exit__ exit
- # Exits the current session, see IRB.irb_exit
- def exit(ret = 0)
- IRB.irb_exit(@irb, ret)
- end
-
- NOPRINTING_IVARS = ["@last_value"] # :nodoc:
- NO_INSPECTING_IVARS = ["@irb", "@io"] # :nodoc:
- IDNAME_IVARS = ["@prompt_mode"] # :nodoc:
-
- alias __inspect__ inspect
- def inspect # :nodoc:
- array = []
- for ivar in instance_variables.sort{|e1, e2| e1 <=> e2}
- ivar = ivar.to_s
- name = ivar.sub(/^@(.*)$/, '\1')
- val = instance_eval(ivar)
- case ivar
- when *NOPRINTING_IVARS
- array.push format("conf.%s=%s", name, "...")
- when *NO_INSPECTING_IVARS
- array.push format("conf.%s=%s", name, val.to_s)
- when *IDNAME_IVARS
- array.push format("conf.%s=:%s", name, val.id2name)
- else
- array.push format("conf.%s=%s", name, val.inspect)
- end
- end
- array.join("\n")
- end
- alias __to_s__ to_s
- alias to_s inspect
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ext/change-ws.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ext/change-ws.rb
deleted file mode 100755
index 866a710dc..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ext/change-ws.rb
+++ /dev/null
@@ -1,45 +0,0 @@
-#
-# irb/ext/cb.rb -
-# $Release Version: 0.9.6$
-# $Revision: 47114 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-module IRB # :nodoc:
- class Context
-
- # Inherited from +TOPLEVEL_BINDING+.
- def home_workspace
- if defined? @home_workspace
- @home_workspace
- else
- @home_workspace = @workspace
- end
- end
-
- # Changes the current workspace to given object or binding.
- #
- # If the optional argument is omitted, the workspace will be
- # #home_workspace which is inherited from +TOPLEVEL_BINDING+ or the main
- # object, IRB.conf[:MAIN_CONTEXT]
when irb was initialized.
- #
- # See IRB::WorkSpace.new for more information.
- def change_workspace(*_main)
- if _main.empty?
- @workspace = home_workspace
- return main
- end
-
- @workspace = WorkSpace.new(_main[0])
-
- if !(class<= 0
- @contents.find{|no, val| no == idx}[1]
- else
- @contents[idx][1]
- end
- rescue NameError
- nil
- end
- end
-
- def push(no, val)
- @contents.push [no, val]
- @contents.shift if @size != 0 && @contents.size > @size
- end
-
- alias real_inspect inspect
-
- def inspect
- if @contents.empty?
- return real_inspect
- end
-
- unless (last = @contents.pop)[1].equal?(self)
- @contents.push last
- last = nil
- end
- str = @contents.collect{|no, val|
- if val.equal?(self)
- "#{no} ...self-history..."
- else
- "#{no} #{val.inspect}"
- end
- }.join("\n")
- if str == ""
- str = "Empty."
- end
- @contents.push last if last
- str
- end
- end
-end
-
-
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ext/loader.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ext/loader.rb
deleted file mode 100755
index 4c6b2baa5..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ext/loader.rb
+++ /dev/null
@@ -1,128 +0,0 @@
-#
-# loader.rb -
-# $Release Version: 0.9.6$
-# $Revision: 47266 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-
-module IRB # :nodoc:
- # Raised in the event of an exception in a file loaded from an Irb session
- class LoadAbort < Exception;end
-
- # Provides a few commands for loading files within an irb session.
- #
- # See ExtendCommandBundle for more information.
- module IrbLoader
-
- alias ruby_load load
- alias ruby_require require
-
- # Loads the given file similarly to Kernel#load
- def irb_load(fn, priv = nil)
- path = search_file_from_ruby_path(fn)
- raise LoadError, "No such file to load -- #{fn}" unless path
-
- load_file(path, priv)
- end
-
- def search_file_from_ruby_path(fn) # :nodoc:
- if /^#{Regexp.quote(File::Separator)}/ =~ fn
- return fn if File.exist?(fn)
- return nil
- end
-
- for path in $:
- if File.exist?(f = File.join(path, fn))
- return f
- end
- end
- return nil
- end
-
- # Loads a given file in the current session and displays the source lines
- #
- # See Irb#suspend_input_method for more information.
- def source_file(path)
- irb.suspend_name(path, File.basename(path)) do
- irb.suspend_input_method(FileInputMethod.new(path)) do
- |back_io|
- irb.signal_status(:IN_LOAD) do
- if back_io.kind_of?(FileInputMethod)
- irb.eval_input
- else
- begin
- irb.eval_input
- rescue LoadAbort
- print "load abort!!\n"
- end
- end
- end
- end
- end
- end
-
- # Loads the given file in the current session's context and evaluates it.
- #
- # See Irb#suspend_input_method for more information.
- def load_file(path, priv = nil)
- irb.suspend_name(path, File.basename(path)) do
-
- if priv
- ws = WorkSpace.new(Module.new)
- else
- ws = WorkSpace.new
- end
- irb.suspend_workspace(ws) do
- irb.suspend_input_method(FileInputMethod.new(path)) do
- |back_io|
- irb.signal_status(:IN_LOAD) do
- if back_io.kind_of?(FileInputMethod)
- irb.eval_input
- else
- begin
- irb.eval_input
- rescue LoadAbort
- print "load abort!!\n"
- end
- end
- end
- end
- end
- end
- end
-
- def old # :nodoc:
- back_io = @io
- back_path = @irb_path
- back_name = @irb_name
- back_scanner = @irb.scanner
- begin
- @io = FileInputMethod.new(path)
- @irb_name = File.basename(path)
- @irb_path = path
- @irb.signal_status(:IN_LOAD) do
- if back_io.kind_of?(FileInputMethod)
- @irb.eval_input
- else
- begin
- @irb.eval_input
- rescue LoadAbort
- print "load abort!!\n"
- end
- end
- end
- ensure
- @io = back_io
- @irb_name = back_name
- @irb_path = back_path
- @irb.scanner = back_scanner
- end
- end
- end
-end
-
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ext/math-mode.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ext/math-mode.rb
deleted file mode 100755
index 33e99688e..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ext/math-mode.rb
+++ /dev/null
@@ -1,47 +0,0 @@
-#
-# math-mode.rb -
-# $Release Version: 0.9.6$
-# $Revision: 47112 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-require "mathn"
-
-module IRB
- class Context
- # Returns whether bc mode is enabled.
- #
- # See #math_mode=
- attr_reader :math_mode
- # Alias for #math_mode
- alias math? math_mode
-
- # Sets bc mode, which loads +lib/mathn.rb+ so fractions or matrix are
- # available.
- #
- # Also available as the +-m+ command line option.
- #
- # See IRB@Command+line+options and the unix manpage bc(1)
for
- # more information.
- def math_mode=(opt)
- if @math_mode == true && !opt
- IRB.fail CantReturnToNormalMode
- return
- end
-
- @math_mode = opt
- if math_mode
- main.extend Math
- print "start math mode\n" if verbose?
- end
- end
-
- def inspect?
- @inspect_mode.nil? && !@math_mode or @inspect_mode
- end
- end
-end
-
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ext/multi-irb.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ext/multi-irb.rb
deleted file mode 100755
index 294f4e26a..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ext/multi-irb.rb
+++ /dev/null
@@ -1,265 +0,0 @@
-#
-# irb/multi-irb.rb - multiple irb module
-# $Release Version: 0.9.6$
-# $Revision: 47266 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-IRB.fail CantShiftToMultiIrbMode unless defined?(Thread)
-require "thread"
-
-module IRB
- class JobManager
-
- # Creates a new JobManager object
- def initialize
- @jobs = []
- @current_job = nil
- end
-
- # The active irb session
- attr_accessor :current_job
-
- # The total number of irb sessions, used to set +irb_name+ of the current
- # Context.
- def n_jobs
- @jobs.size
- end
-
- # Returns the thread for the given +key+ object, see #search for more
- # information.
- def thread(key)
- th, = search(key)
- th
- end
-
- # Returns the irb session for the given +key+ object, see #search for more
- # information.
- def irb(key)
- _, irb = search(key)
- irb
- end
-
- # Returns the top level thread.
- def main_thread
- @jobs[0][0]
- end
-
- # Returns the top level irb session.
- def main_irb
- @jobs[0][1]
- end
-
- # Add the given +irb+ session to the jobs Array.
- def insert(irb)
- @jobs.push [Thread.current, irb]
- end
-
- # Changes the current active irb session to the given +key+ in the jobs
- # Array.
- #
- # Raises an IrbAlreadyDead exception if the given +key+ is no longer alive.
- #
- # If the given irb session is already active, an IrbSwitchedToCurrentThread
- # exception is raised.
- def switch(key)
- th, irb = search(key)
- IRB.fail IrbAlreadyDead unless th.alive?
- IRB.fail IrbSwitchedToCurrentThread if th == Thread.current
- @current_job = irb
- th.run
- Thread.stop
- @current_job = irb(Thread.current)
- end
-
- # Terminates the irb sessions specified by the given +keys+.
- #
- # Raises an IrbAlreadyDead exception if one of the given +keys+ is already
- # terminated.
- #
- # See Thread#exit for more information.
- def kill(*keys)
- for key in keys
- th, _ = search(key)
- IRB.fail IrbAlreadyDead unless th.alive?
- th.exit
- end
- end
-
- # Returns the associated job for the given +key+.
- #
- # If given an Integer, it will return the +key+ index for the jobs Array.
- #
- # When an instance of Irb is given, it will return the irb session
- # associated with +key+.
- #
- # If given an instance of Thread, it will return the associated thread
- # +key+ using Object#=== on the jobs Array.
- #
- # Otherwise returns the irb session with the same top-level binding as the
- # given +key+.
- #
- # Raises a NoSuchJob exception if no job can be found with the given +key+.
- def search(key)
- job = case key
- when Integer
- @jobs[key]
- when Irb
- @jobs.find{|k, v| v.equal?(key)}
- when Thread
- @jobs.assoc(key)
- else
- @jobs.find{|k, v| v.context.main.equal?(key)}
- end
- IRB.fail NoSuchJob, key if job.nil?
- job
- end
-
- # Deletes the job at the given +key+.
- def delete(key)
- case key
- when Integer
- IRB.fail NoSuchJob, key unless @jobs[key]
- @jobs[key] = nil
- else
- catch(:EXISTS) do
- @jobs.each_index do
- |i|
- if @jobs[i] and (@jobs[i][0] == key ||
- @jobs[i][1] == key ||
- @jobs[i][1].context.main.equal?(key))
- @jobs[i] = nil
- throw :EXISTS
- end
- end
- IRB.fail NoSuchJob, key
- end
- end
- until assoc = @jobs.pop; end unless @jobs.empty?
- @jobs.push assoc
- end
-
- # Outputs a list of jobs, see the irb command +irb_jobs+, or +jobs+.
- def inspect
- ary = []
- @jobs.each_index do
- |i|
- th, irb = @jobs[i]
- next if th.nil?
-
- if th.alive?
- if th.stop?
- t_status = "stop"
- else
- t_status = "running"
- end
- else
- t_status = "exited"
- end
- ary.push format("#%d->%s on %s (%s: %s)",
- i,
- irb.context.irb_name,
- irb.context.main,
- th,
- t_status)
- end
- ary.join("\n")
- end
- end
-
- @JobManager = JobManager.new
-
- # The current JobManager in the session
- def IRB.JobManager
- @JobManager
- end
-
- # The current Context in this session
- def IRB.CurrentContext
- IRB.JobManager.irb(Thread.current).context
- end
-
- # Creates a new IRB session, see Irb.new.
- #
- # The optional +file+ argument is given to Context.new, along with the
- # workspace created with the remaining arguments, see WorkSpace.new
- def IRB.irb(file = nil, *main)
- workspace = WorkSpace.new(*main)
- parent_thread = Thread.current
- Thread.start do
- begin
- irb = Irb.new(workspace, file)
- rescue
- print "Subirb can't start with context(self): ", workspace.main.inspect, "\n"
- print "return to main irb\n"
- Thread.pass
- Thread.main.wakeup
- Thread.exit
- end
- @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC]
- @JobManager.insert(irb)
- @JobManager.current_job = irb
- begin
- system_exit = false
- catch(:IRB_EXIT) do
- irb.eval_input
- end
- rescue SystemExit
- system_exit = true
- raise
- #fail
- ensure
- unless system_exit
- @JobManager.delete(irb)
- if @JobManager.current_job == irb
- if parent_thread.alive?
- @JobManager.current_job = @JobManager.irb(parent_thread)
- parent_thread.run
- else
- @JobManager.current_job = @JobManager.main_irb
- @JobManager.main_thread.run
- end
- end
- end
- end
- end
- Thread.stop
- @JobManager.current_job = @JobManager.irb(Thread.current)
- end
-
- @CONF[:SINGLE_IRB_MODE] = false
- @JobManager.insert(@CONF[:MAIN_CONTEXT].irb)
- @JobManager.current_job = @CONF[:MAIN_CONTEXT].irb
-
- class Irb
- def signal_handle
- unless @context.ignore_sigint?
- print "\nabort!!\n" if @context.verbose?
- exit
- end
-
- case @signal_status
- when :IN_INPUT
- print "^C\n"
- IRB.JobManager.thread(self).raise RubyLex::TerminateLineInput
- when :IN_EVAL
- IRB.irb_abort(self)
- when :IN_LOAD
- IRB.irb_abort(self, LoadAbort)
- when :IN_IRB
- # ignore
- else
- # ignore other cases as well
- end
- end
- end
-
- trap("SIGINT") do
- @JobManager.current_job.signal_handle
- Thread.stop
- end
-
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ext/save-history.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ext/save-history.rb
deleted file mode 100755
index 575b2760e..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ext/save-history.rb
+++ /dev/null
@@ -1,103 +0,0 @@
-# save-history.rb -
-# $Release Version: 0.9.6$
-# $Revision: 47266 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-require "readline"
-
-module IRB
- module HistorySavingAbility # :nodoc:
- end
-
- class Context
- def init_save_history# :nodoc:
- unless (class<<@io;self;end).include?(HistorySavingAbility)
- @io.extend(HistorySavingAbility)
- end
- end
-
- # A copy of the default IRB.conf[:SAVE_HISTORY]
- def save_history
- IRB.conf[:SAVE_HISTORY]
- end
-
- # Sets IRB.conf[:SAVE_HISTORY]
to the given +val+ and calls
- # #init_save_history with this context.
- #
- # Will store the number of +val+ entries of history in the #history_file
- #
- # Add the following to your +.irbrc+ to change the number of history
- # entries stored to 1000:
- #
- # IRB.conf[:SAVE_HISTORY] = 1000
- def save_history=(val)
- IRB.conf[:SAVE_HISTORY] = val
- if val
- main_context = IRB.conf[:MAIN_CONTEXT]
- main_context = self unless main_context
- main_context.init_save_history
- end
- end
-
- # A copy of the default IRB.conf[:HISTORY_FILE]
- def history_file
- IRB.conf[:HISTORY_FILE]
- end
-
- # Set IRB.conf[:HISTORY_FILE]
to the given +hist+.
- def history_file=(hist)
- IRB.conf[:HISTORY_FILE] = hist
- end
- end
-
- module HistorySavingAbility # :nodoc:
- include Readline
-
- def HistorySavingAbility.extended(obj)
- IRB.conf[:AT_EXIT].push proc{obj.save_history}
- obj.load_history
- obj
- end
-
- def load_history
- if history_file = IRB.conf[:HISTORY_FILE]
- history_file = File.expand_path(history_file)
- end
- history_file = IRB.rc_file("_history") unless history_file
- if File.exist?(history_file)
- open(history_file) do |f|
- f.each {|l| HISTORY << l.chomp}
- end
- end
- end
-
- def save_history
- if num = IRB.conf[:SAVE_HISTORY] and (num = num.to_i) > 0
- if history_file = IRB.conf[:HISTORY_FILE]
- history_file = File.expand_path(history_file)
- end
- history_file = IRB.rc_file("_history") unless history_file
-
- # Change the permission of a file that already exists[BUG #7694]
- begin
- if File.stat(history_file).mode & 066 != 0
- File.chmod(0600, history_file)
- end
- rescue Errno::ENOENT
- rescue
- raise
- end
-
- open(history_file, 'w', 0600 ) do |f|
- hist = HISTORY.to_a
- f.puts(hist[-num..-1] || hist)
- end
- end
- end
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ext/tracer.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ext/tracer.rb
deleted file mode 100755
index 691215ad4..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ext/tracer.rb
+++ /dev/null
@@ -1,71 +0,0 @@
-#
-# irb/lib/tracer.rb -
-# $Release Version: 0.9.6$
-# $Revision: 47112 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-require "tracer"
-
-module IRB
-
- # initialize tracing function
- def IRB.initialize_tracer
- Tracer.verbose = false
- Tracer.add_filter {
- |event, file, line, id, binding, *rests|
- /^#{Regexp.quote(@CONF[:IRB_LIB_PATH])}/ !~ file and
- File::basename(file) != "irb.rb"
- }
- end
-
- class Context
- # Whether Tracer is used when evaluating statements in this context.
- #
- # See +lib/tracer.rb+ for more information.
- attr_reader :use_tracer
- alias use_tracer? use_tracer
-
- # Sets whether or not to use the Tracer library when evaluating statements
- # in this context.
- #
- # See +lib/tracer.rb+ for more information.
- def use_tracer=(opt)
- if opt
- Tracer.set_get_line_procs(@irb_path) {
- |line_no, *rests|
- @io.line(line_no)
- }
- elsif !opt && @use_tracer
- Tracer.off
- end
- @use_tracer=opt
- end
- end
-
- class WorkSpace
- alias __evaluate__ evaluate
- # Evaluate the context of this workspace and use the Tracer library to
- # output the exact lines of code are being executed in chronological order.
- #
- # See +lib/tracer.rb+ for more information.
- def evaluate(context, statements, file = nil, line = nil)
- if context.use_tracer? && file != nil && line != nil
- Tracer.on
- begin
- __evaluate__(context, statements, file, line)
- ensure
- Tracer.off
- end
- else
- __evaluate__(context, statements, file || __FILE__, line || __LINE__)
- end
- end
- end
-
- IRB.initialize_tracer
-end
-
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ext/use-loader.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ext/use-loader.rb
deleted file mode 100755
index 728299533..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ext/use-loader.rb
+++ /dev/null
@@ -1,73 +0,0 @@
-#
-# use-loader.rb -
-# $Release Version: 0.9.6$
-# $Revision: 47112 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-require "irb/cmd/load"
-require "irb/ext/loader"
-
-class Object
- alias __original__load__IRB_use_loader__ load
- alias __original__require__IRB_use_loader__ require
-end
-
-module IRB
- module ExtendCommandBundle
- # Loads the given file similarly to Kernel#load, see IrbLoader#irb_load
- def irb_load(*opts, &b)
- ExtendCommand::Load.execute(irb_context, *opts, &b)
- end
- # Loads the given file similarly to Kernel#require
- def irb_require(*opts, &b)
- ExtendCommand::Require.execute(irb_context, *opts, &b)
- end
- end
-
- class Context
-
- IRB.conf[:USE_LOADER] = false
-
- # Returns whether +irb+'s own file reader method is used by
- # +load+/+require+ or not.
- #
- # This mode is globally affected (irb-wide).
- def use_loader
- IRB.conf[:USE_LOADER]
- end
-
- alias use_loader? use_loader
-
- # Sets IRB.conf[:USE_LOADER]
- #
- # See #use_loader for more information.
- def use_loader=(opt)
-
- if IRB.conf[:USE_LOADER] != opt
- IRB.conf[:USE_LOADER] = opt
- if opt
- if !$".include?("irb/cmd/load")
- end
- (class<<@workspace.main;self;end).instance_eval {
- alias_method :load, :irb_load
- alias_method :require, :irb_require
- }
- else
- (class<<@workspace.main;self;end).instance_eval {
- alias_method :load, :__original__load__IRB_use_loader__
- alias_method :require, :__original__require__IRB_use_loader__
- }
- end
- end
- print "Switch to load/require#{unless use_loader; ' non';end} trace mode.\n" if verbose?
- opt
- end
- end
-end
-
-
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ext/workspaces.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ext/workspaces.rb
deleted file mode 100755
index a11cea35d..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ext/workspaces.rb
+++ /dev/null
@@ -1,66 +0,0 @@
-#
-# push-ws.rb -
-# $Release Version: 0.9.6$
-# $Revision: 47112 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-module IRB # :nodoc:
- class Context
-
- # Size of the current WorkSpace stack
- def irb_level
- workspace_stack.size
- end
-
- # WorkSpaces in the current stack
- def workspaces
- if defined? @workspaces
- @workspaces
- else
- @workspaces = []
- end
- end
-
- # Creates a new workspace with the given object or binding, and appends it
- # onto the current #workspaces stack.
- #
- # See IRB::Context#change_workspace and IRB::WorkSpace.new for more
- # information.
- def push_workspace(*_main)
- if _main.empty?
- if workspaces.empty?
- print "No other workspace\n"
- return nil
- end
- ws = workspaces.pop
- workspaces.push @workspace
- @workspace = ws
- return workspaces
- end
-
- workspaces.push @workspace
- @workspace = WorkSpace.new(@workspace.binding, _main[0])
- if !(class<IRB.CurrentContext.exit.
- def irb_exit(ret = 0)
- irb_context.exit(ret)
- end
-
- # Displays current configuration.
- #
- # Modifing the configuration is achieved by sending a message to IRB.conf.
- def irb_context
- IRB.CurrentContext
- end
-
- @ALIASES = [
- [:context, :irb_context, NO_OVERRIDE],
- [:conf, :irb_context, NO_OVERRIDE],
- [:irb_quit, :irb_exit, OVERRIDE_PRIVATE_ONLY],
- [:exit, :irb_exit, OVERRIDE_PRIVATE_ONLY],
- [:quit, :irb_exit, OVERRIDE_PRIVATE_ONLY],
- ]
-
- @EXTEND_COMMANDS = [
- [:irb_current_working_workspace, :CurrentWorkingWorkspace, "irb/cmd/chws",
- [:irb_print_working_workspace, OVERRIDE_ALL],
- [:irb_cwws, OVERRIDE_ALL],
- [:irb_pwws, OVERRIDE_ALL],
- [:cwws, NO_OVERRIDE],
- [:pwws, NO_OVERRIDE],
- [:irb_current_working_binding, OVERRIDE_ALL],
- [:irb_print_working_binding, OVERRIDE_ALL],
- [:irb_cwb, OVERRIDE_ALL],
- [:irb_pwb, OVERRIDE_ALL],
- ],
- [:irb_change_workspace, :ChangeWorkspace, "irb/cmd/chws",
- [:irb_chws, OVERRIDE_ALL],
- [:irb_cws, OVERRIDE_ALL],
- [:chws, NO_OVERRIDE],
- [:cws, NO_OVERRIDE],
- [:irb_change_binding, OVERRIDE_ALL],
- [:irb_cb, OVERRIDE_ALL],
- [:cb, NO_OVERRIDE]],
-
- [:irb_workspaces, :Workspaces, "irb/cmd/pushws",
- [:workspaces, NO_OVERRIDE],
- [:irb_bindings, OVERRIDE_ALL],
- [:bindings, NO_OVERRIDE]],
- [:irb_push_workspace, :PushWorkspace, "irb/cmd/pushws",
- [:irb_pushws, OVERRIDE_ALL],
- [:pushws, NO_OVERRIDE],
- [:irb_push_binding, OVERRIDE_ALL],
- [:irb_pushb, OVERRIDE_ALL],
- [:pushb, NO_OVERRIDE]],
- [:irb_pop_workspace, :PopWorkspace, "irb/cmd/pushws",
- [:irb_popws, OVERRIDE_ALL],
- [:popws, NO_OVERRIDE],
- [:irb_pop_binding, OVERRIDE_ALL],
- [:irb_popb, OVERRIDE_ALL],
- [:popb, NO_OVERRIDE]],
-
- [:irb_load, :Load, "irb/cmd/load"],
- [:irb_require, :Require, "irb/cmd/load"],
- [:irb_source, :Source, "irb/cmd/load",
- [:source, NO_OVERRIDE]],
-
- [:irb, :IrbCommand, "irb/cmd/subirb"],
- [:irb_jobs, :Jobs, "irb/cmd/subirb",
- [:jobs, NO_OVERRIDE]],
- [:irb_fg, :Foreground, "irb/cmd/subirb",
- [:fg, NO_OVERRIDE]],
- [:irb_kill, :Kill, "irb/cmd/subirb",
- [:kill, OVERRIDE_PRIVATE_ONLY]],
-
- [:irb_help, :Help, "irb/cmd/help",
- [:help, NO_OVERRIDE]],
-
- ]
-
- # Installs the default irb commands:
- #
- # +irb_current_working_workspace+:: Context#main
- # +irb_change_workspace+:: Context#change_workspace
- # +irb_workspaces+:: Context#workspaces
- # +irb_push_workspace+:: Context#push_workspace
- # +irb_pop_workspace+:: Context#pop_workspace
- # +irb_load+:: #irb_load
- # +irb_require+:: #irb_require
- # +irb_source+:: IrbLoader#source_file
- # +irb+:: IRB.irb
- # +irb_jobs+:: JobManager
- # +irb_fg+:: JobManager#switch
- # +irb_kill+:: JobManager#kill
- # +irb_help+:: IRB@Command+line+options
- def self.install_extend_commands
- for args in @EXTEND_COMMANDS
- def_extend_command(*args)
- end
- end
-
- # Evaluate the given +cmd_name+ on the given +cmd_class+ Class.
- #
- # Will also define any given +aliases+ for the method.
- #
- # The optional +load_file+ parameter will be required within the method
- # definition.
- def self.def_extend_command(cmd_name, cmd_class, load_file = nil, *aliases)
- case cmd_class
- when Symbol
- cmd_class = cmd_class.id2name
- when String
- when Class
- cmd_class = cmd_class.name
- end
-
- if load_file
- line = __LINE__; eval %[
- def #{cmd_name}(*opts, &b)
- require "#{load_file}"
- arity = ExtendCommand::#{cmd_class}.instance_method(:execute).arity
- args = (1..(arity < 0 ? ~arity : arity)).map {|i| "arg" + i.to_s }
- args << "*opts" if arity < 0
- args << "&block"
- args = args.join(", ")
- line = __LINE__; eval %[
- def #{cmd_name}(\#{args})
- ExtendCommand::#{cmd_class}.execute(irb_context, \#{args})
- end
- ], nil, __FILE__, line
- send :#{cmd_name}, *opts, &b
- end
- ], nil, __FILE__, line
- else
- line = __LINE__; eval %[
- def #{cmd_name}(*opts, &b)
- ExtendCommand::#{cmd_class}.execute(irb_context, *opts, &b)
- end
- ], nil, __FILE__, line
- end
-
- for ali, flag in aliases
- @ALIASES.push [ali, cmd_name, flag]
- end
- end
-
- # Installs alias methods for the default irb commands, see
- # ::install_extend_commands.
- def install_alias_method(to, from, override = NO_OVERRIDE)
- to = to.id2name unless to.kind_of?(String)
- from = from.id2name unless from.kind_of?(String)
-
- if override == OVERRIDE_ALL or
- (override == OVERRIDE_PRIVATE_ONLY) && !respond_to?(to) or
- (override == NO_OVERRIDE) && !respond_to?(to, true)
- target = self
- (class << self; self; end).instance_eval{
- if target.respond_to?(to, true) &&
- !target.respond_to?(EXCB.irb_original_method_name(to), true)
- alias_method(EXCB.irb_original_method_name(to), to)
- end
- alias_method to, from
- }
- else
- print "irb: warn: can't alias #{to} from #{from}.\n"
- end
- end
-
- def self.irb_original_method_name(method_name) # :nodoc:
- "irb_" + method_name + "_org"
- end
-
- # Installs alias methods for the default irb commands on the given object
- # using #install_alias_method.
- def self.extend_object(obj)
- unless (class << obj; ancestors; end).include?(EXCB)
- super
- for ali, com, flg in @ALIASES
- obj.install_alias_method(ali, com, flg)
- end
- end
- end
-
- install_extend_commands
- end
-
- # Extends methods for the Context module
- module ContextExtender
- CE = ContextExtender # :nodoc:
-
- @EXTEND_COMMANDS = [
- [:eval_history=, "irb/ext/history.rb"],
- [:use_tracer=, "irb/ext/tracer.rb"],
- [:math_mode=, "irb/ext/math-mode.rb"],
- [:use_loader=, "irb/ext/use-loader.rb"],
- [:save_history=, "irb/ext/save-history.rb"],
- ]
-
- # Installs the default context extensions as irb commands:
- #
- # Context#eval_history=:: +irb/ext/history.rb+
- # Context#use_tracer=:: +irb/ext/tracer.rb+
- # Context#math_mode=:: +irb/ext/math-mode.rb+
- # Context#use_loader=:: +irb/ext/use-loader.rb+
- # Context#save_history=:: +irb/ext/save-history.rb+
- def self.install_extend_commands
- for args in @EXTEND_COMMANDS
- def_extend_command(*args)
- end
- end
-
- # Evaluate the given +command+ from the given +load_file+ on the Context
- # module.
- #
- # Will also define any given +aliases+ for the method.
- def self.def_extend_command(cmd_name, load_file, *aliases)
- line = __LINE__; Context.module_eval %[
- def #{cmd_name}(*opts, &b)
- Context.module_eval {remove_method(:#{cmd_name})}
- require "#{load_file}"
- send :#{cmd_name}, *opts, &b
- end
- for ali in aliases
- alias_method ali, cmd_name
- end
- ], __FILE__, line
- end
-
- CE.install_extend_commands
- end
-
- # A convenience module for extending Ruby methods.
- module MethodExtender
- # Extends the given +base_method+ with a prefix call to the given
- # +extend_method+.
- def def_pre_proc(base_method, extend_method)
- base_method = base_method.to_s
- extend_method = extend_method.to_s
-
- alias_name = new_alias_name(base_method)
- module_eval %[
- alias_method alias_name, base_method
- def #{base_method}(*opts)
- send :#{extend_method}, *opts
- send :#{alias_name}, *opts
- end
- ]
- end
-
- # Extends the given +base_method+ with a postfix call to the given
- # +extend_method+.
- def def_post_proc(base_method, extend_method)
- base_method = base_method.to_s
- extend_method = extend_method.to_s
-
- alias_name = new_alias_name(base_method)
- module_eval %[
- alias_method alias_name, base_method
- def #{base_method}(*opts)
- send :#{alias_name}, *opts
- send :#{extend_method}, *opts
- end
- ]
- end
-
- # Returns a unique method name to use as an alias for the given +name+.
- #
- # Usually returns #{prefix}#{name}#{postfix}
, example:
- #
- # new_alias_name('foo') #=> __alias_of__foo__
- # def bar; end
- # new_alias_name('bar') #=> __alias_of__bar__2
- def new_alias_name(name, prefix = "__alias_of__", postfix = "__")
- base_name = "#{prefix}#{name}#{postfix}"
- all_methods = instance_methods(true) + private_instance_methods(true)
- same_methods = all_methods.grep(/^#{Regexp.quote(base_name)}[0-9]*$/)
- return base_name if same_methods.empty?
- no = same_methods.size
- while !same_methods.include?(alias_name = base_name + no)
- no += 1
- end
- alias_name
- end
- end
-end
-
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/frame.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/frame.rb
deleted file mode 100755
index 4a1d08074..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/frame.rb
+++ /dev/null
@@ -1,80 +0,0 @@
-#
-# frame.rb -
-# $Release Version: 0.9$
-# $Revision: 47112 $
-# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
-#
-# --
-#
-#
-#
-
-require "e2mmap"
-
-module IRB
- class Frame
- extend Exception2MessageMapper
- def_exception :FrameOverflow, "frame overflow"
- def_exception :FrameUnderflow, "frame underflow"
-
- # Default number of stack frames
- INIT_STACK_TIMES = 3
- # Default number of frames offset
- CALL_STACK_OFFSET = 3
-
- # Creates a new stack frame
- def initialize
- @frames = [TOPLEVEL_BINDING] * INIT_STACK_TIMES
- end
-
- # Used by Kernel#set_trace_func to register each event in the call stack
- def trace_func(event, file, line, id, binding)
- case event
- when 'call', 'class'
- @frames.push binding
- when 'return', 'end'
- @frames.pop
- end
- end
-
- # Returns the +n+ number of frames on the call stack from the last frame
- # initialized.
- #
- # Raises FrameUnderflow if there are no frames in the given stack range.
- def top(n = 0)
- bind = @frames[-(n + CALL_STACK_OFFSET)]
- Fail FrameUnderflow unless bind
- bind
- end
-
- # Returns the +n+ number of frames on the call stack from the first frame
- # initialized.
- #
- # Raises FrameOverflow if there are no frames in the given stack range.
- def bottom(n = 0)
- bind = @frames[n]
- Fail FrameOverflow unless bind
- bind
- end
-
- # Convenience method for Frame#bottom
- def Frame.bottom(n = 0)
- @backtrace.bottom(n)
- end
-
- # Convenience method for Frame#top
- def Frame.top(n = 0)
- @backtrace.top(n)
- end
-
- # Returns the binding context of the caller from the last frame initialized
- def Frame.sender
- eval "self", @backtrace.top
- end
-
- @backtrace = Frame.new
- set_trace_func proc{|event, file, line, id, binding, klass|
- @backtrace.trace_func(event, file, line, id, binding)
- }
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/help.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/help.rb
deleted file mode 100755
index c0160f051..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/help.rb
+++ /dev/null
@@ -1,36 +0,0 @@
-#
-# irb/help.rb - print usage module
-# $Release Version: 0.9.6$
-# $Revision: 47112 $
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-# --
-#
-#
-#
-
-require 'irb/magic-file'
-
-module IRB
- # Outputs the irb help message, see IRB@Command+line+options.
- def IRB.print_usage
- lc = IRB.conf[:LC_MESSAGES]
- path = lc.find("irb/help-message")
- space_line = false
- IRB::MagicFile.open(path){|f|
- f.each_line do |l|
- if /^\s*$/ =~ l
- lc.puts l unless space_line
- space_line = true
- next
- end
- space_line = false
-
- l.sub!(/#.*$/, "")
- next if /^\s*$/ =~ l
- lc.puts l
- end
- }
- end
-end
-
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/init.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/init.rb
deleted file mode 100755
index 98289b3f0..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/init.rb
+++ /dev/null
@@ -1,304 +0,0 @@
-#
-# irb/init.rb - irb initialize module
-# $Release Version: 0.9.6$
-# $Revision: 47114 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-module IRB # :nodoc:
-
- # initialize config
- def IRB.setup(ap_path)
- IRB.init_config(ap_path)
- IRB.init_error
- IRB.parse_opts
- IRB.run_config
- IRB.load_modules
-
- unless @CONF[:PROMPT][@CONF[:PROMPT_MODE]]
- IRB.fail(UndefinedPromptMode, @CONF[:PROMPT_MODE])
- end
- end
-
- # @CONF default setting
- def IRB.init_config(ap_path)
- # class instance variables
- @TRACER_INITIALIZED = false
-
- # default configurations
- unless ap_path and @CONF[:AP_NAME]
- ap_path = File.join(File.dirname(File.dirname(__FILE__)), "irb.rb")
- end
- @CONF[:AP_NAME] = File::basename(ap_path, ".rb")
-
- @CONF[:IRB_NAME] = "irb"
- @CONF[:IRB_LIB_PATH] = File.dirname(__FILE__)
-
- @CONF[:RC] = true
- @CONF[:LOAD_MODULES] = []
- @CONF[:IRB_RC] = nil
-
- @CONF[:MATH_MODE] = false
- @CONF[:USE_READLINE] = false unless defined?(ReadlineInputMethod)
- @CONF[:INSPECT_MODE] = true
- @CONF[:USE_TRACER] = false
- @CONF[:USE_LOADER] = false
- @CONF[:IGNORE_SIGINT] = true
- @CONF[:IGNORE_EOF] = false
- @CONF[:ECHO] = nil
- @CONF[:VERBOSE] = nil
-
- @CONF[:EVAL_HISTORY] = nil
- @CONF[:SAVE_HISTORY] = nil
-
- @CONF[:BACK_TRACE_LIMIT] = 16
-
- @CONF[:PROMPT] = {
- :NULL => {
- :PROMPT_I => nil,
- :PROMPT_N => nil,
- :PROMPT_S => nil,
- :PROMPT_C => nil,
- :RETURN => "%s\n"
- },
- :DEFAULT => {
- :PROMPT_I => "%N(%m):%03n:%i> ",
- :PROMPT_N => "%N(%m):%03n:%i> ",
- :PROMPT_S => "%N(%m):%03n:%i%l ",
- :PROMPT_C => "%N(%m):%03n:%i* ",
- :RETURN => "=> %s\n"
- },
- :CLASSIC => {
- :PROMPT_I => "%N(%m):%03n:%i> ",
- :PROMPT_N => "%N(%m):%03n:%i> ",
- :PROMPT_S => "%N(%m):%03n:%i%l ",
- :PROMPT_C => "%N(%m):%03n:%i* ",
- :RETURN => "%s\n"
- },
- :SIMPLE => {
- :PROMPT_I => ">> ",
- :PROMPT_N => ">> ",
- :PROMPT_S => nil,
- :PROMPT_C => "?> ",
- :RETURN => "=> %s\n"
- },
- :INF_RUBY => {
- :PROMPT_I => "%N(%m):%03n:%i> ",
- :PROMPT_N => nil,
- :PROMPT_S => nil,
- :PROMPT_C => nil,
- :RETURN => "%s\n",
- :AUTO_INDENT => true
- },
- :XMP => {
- :PROMPT_I => nil,
- :PROMPT_N => nil,
- :PROMPT_S => nil,
- :PROMPT_C => nil,
- :RETURN => " ==>%s\n"
- }
- }
-
- @CONF[:PROMPT_MODE] = (STDIN.tty? ? :DEFAULT : :NULL)
- @CONF[:AUTO_INDENT] = false
-
- @CONF[:CONTEXT_MODE] = 3 # use binding in function on TOPLEVEL_BINDING
- @CONF[:SINGLE_IRB] = false
-
- @CONF[:LC_MESSAGES] = Locale.new
-
- @CONF[:AT_EXIT] = []
-
- @CONF[:DEBUG_LEVEL] = 0
- end
-
- def IRB.init_error
- @CONF[:LC_MESSAGES].load("irb/error.rb")
- end
-
- # option analyzing
- def IRB.parse_opts
- load_path = []
- while opt = ARGV.shift
- case opt
- when "-f"
- @CONF[:RC] = false
- when "-m"
- @CONF[:MATH_MODE] = true
- when "-d"
- $DEBUG = true
- $VERBOSE = true
- when "-w"
- $VERBOSE = true
- when /^-W(.+)?/
- opt = $1 || ARGV.shift
- case opt
- when "0"
- $VERBOSE = nil
- when "1"
- $VERBOSE = false
- else
- $VERBOSE = true
- end
- when /^-r(.+)?/
- opt = $1 || ARGV.shift
- @CONF[:LOAD_MODULES].push opt if opt
- when /^-I(.+)?/
- opt = $1 || ARGV.shift
- load_path.concat(opt.split(File::PATH_SEPARATOR)) if opt
- when '-U'
- set_encoding("UTF-8", "UTF-8")
- when /^-E(.+)?/, /^--encoding(?:=(.+))?/
- opt = $1 || ARGV.shift
- set_encoding(*opt.split(':', 2))
- when "--inspect"
- if /^-/ !~ ARGV.first
- @CONF[:INSPECT_MODE] = ARGV.shift
- else
- @CONF[:INSPECT_MODE] = true
- end
- when "--noinspect"
- @CONF[:INSPECT_MODE] = false
- when "--readline"
- @CONF[:USE_READLINE] = true
- when "--noreadline"
- @CONF[:USE_READLINE] = false
- when "--echo"
- @CONF[:ECHO] = true
- when "--noecho"
- @CONF[:ECHO] = false
- when "--verbose"
- @CONF[:VERBOSE] = true
- when "--noverbose"
- @CONF[:VERBOSE] = false
- when /^--prompt-mode(?:=(.+))?/, /^--prompt(?:=(.+))?/
- opt = $1 || ARGV.shift
- prompt_mode = opt.upcase.tr("-", "_").intern
- @CONF[:PROMPT_MODE] = prompt_mode
- when "--noprompt"
- @CONF[:PROMPT_MODE] = :NULL
- when "--inf-ruby-mode"
- @CONF[:PROMPT_MODE] = :INF_RUBY
- when "--sample-book-mode", "--simple-prompt"
- @CONF[:PROMPT_MODE] = :SIMPLE
- when "--tracer"
- @CONF[:USE_TRACER] = true
- when /^--back-trace-limit(?:=(.+))?/
- @CONF[:BACK_TRACE_LIMIT] = ($1 || ARGV.shift).to_i
- when /^--context-mode(?:=(.+))?/
- @CONF[:CONTEXT_MODE] = ($1 || ARGV.shift).to_i
- when "--single-irb"
- @CONF[:SINGLE_IRB] = true
- when /^--irb_debug(?:=(.+))?/
- @CONF[:DEBUG_LEVEL] = ($1 || ARGV.shift).to_i
- when "-v", "--version"
- print IRB.version, "\n"
- exit 0
- when "-h", "--help"
- require "irb/help"
- IRB.print_usage
- exit 0
- when "--"
- if opt = ARGV.shift
- @CONF[:SCRIPT] = opt
- $0 = opt
- end
- break
- when /^-/
- IRB.fail UnrecognizedSwitch, opt
- else
- @CONF[:SCRIPT] = opt
- $0 = opt
- break
- end
- end
- load_path.collect! do |path|
- /\A\.\// =~ path ? path : File.expand_path(path)
- end
- $LOAD_PATH.unshift(*load_path)
-
- end
-
- # running config
- def IRB.run_config
- if @CONF[:RC]
- begin
- load rc_file
- rescue LoadError, Errno::ENOENT
- rescue # StandardError, ScriptError
- print "load error: #{rc_file}\n"
- print $!.class, ": ", $!, "\n"
- for err in $@[0, $@.size - 2]
- print "\t", err, "\n"
- end
- end
- end
- end
-
- IRBRC_EXT = "rc"
- def IRB.rc_file(ext = IRBRC_EXT)
- if !@CONF[:RC_NAME_GENERATOR]
- rc_file_generators do |rcgen|
- @CONF[:RC_NAME_GENERATOR] ||= rcgen
- if File.exist?(rcgen.call(IRBRC_EXT))
- @CONF[:RC_NAME_GENERATOR] = rcgen
- break
- end
- end
- end
- case rc_file = @CONF[:RC_NAME_GENERATOR].call(ext)
- when String
- return rc_file
- else
- IRB.fail IllegalRCNameGenerator
- end
- end
-
- # enumerate possible rc-file base name generators
- def IRB.rc_file_generators
- if irbrc = ENV["IRBRC"]
- yield proc{|rc| rc == "rc" ? irbrc : irbrc+rc}
- end
- if home = ENV["HOME"]
- yield proc{|rc| home+"/.irb#{rc}"}
- end
- home = Dir.pwd
- yield proc{|rc| home+"/.irb#{rc}"}
- yield proc{|rc| home+"/irb#{rc.sub(/\A_?/, '.')}"}
- yield proc{|rc| home+"/_irb#{rc}"}
- yield proc{|rc| home+"/$irb#{rc}"}
- end
-
- # loading modules
- def IRB.load_modules
- for m in @CONF[:LOAD_MODULES]
- begin
- require m
- rescue LoadError => err
- warn err.backtrace[0] << ":#{err.class}: #{err}"
- end
- end
- end
-
-
- DefaultEncodings = Struct.new(:external, :internal)
- class << IRB
- private
- def set_encoding(extern, intern = nil)
- verbose, $VERBOSE = $VERBOSE, nil
- Encoding.default_external = extern unless extern.nil? || extern.empty?
- Encoding.default_internal = intern unless intern.nil? || intern.empty?
- @CONF[:ENCODINGS] = IRB::DefaultEncodings.new(extern, intern)
- [$stdin, $stdout, $stderr].each do |io|
- io.set_encoding(extern, intern)
- end
- @CONF[:LC_MESSAGES].instance_variable_set(:@encoding, extern)
- ensure
- $VERBOSE = verbose
- end
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/input-method.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/input-method.rb
deleted file mode 100755
index 97add9209..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/input-method.rb
+++ /dev/null
@@ -1,191 +0,0 @@
-#
-# irb/input-method.rb - input methods used irb
-# $Release Version: 0.9.6$
-# $Revision: 47266 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-require 'irb/src_encoding'
-require 'irb/magic-file'
-
-module IRB
- STDIN_FILE_NAME = "(line)" # :nodoc:
- class InputMethod
-
- # Creates a new input method object
- def initialize(file = STDIN_FILE_NAME)
- @file_name = file
- end
- # The file name of this input method, usually given during initialization.
- attr_reader :file_name
-
- # The irb prompt associated with this input method
- attr_accessor :prompt
-
- # Reads the next line from this input method.
- #
- # See IO#gets for more information.
- def gets
- IRB.fail NotImplementedError, "gets"
- end
- public :gets
-
- # Whether this input method is still readable when there is no more data to
- # read.
- #
- # See IO#eof for more information.
- def readable_after_eof?
- false
- end
- end
-
- class StdioInputMethod < InputMethod
- # Creates a new input method object
- def initialize
- super
- @line_no = 0
- @line = []
- @stdin = IO.open(STDIN.to_i, :external_encoding => IRB.conf[:LC_MESSAGES].encoding, :internal_encoding => "-")
- @stdout = IO.open(STDOUT.to_i, 'w', :external_encoding => IRB.conf[:LC_MESSAGES].encoding, :internal_encoding => "-")
- end
-
- # Reads the next line from this input method.
- #
- # See IO#gets for more information.
- def gets
- print @prompt
- line = @stdin.gets
- @line[@line_no += 1] = line
- end
-
- # Whether the end of this input method has been reached, returns +true+ if
- # there is no more data to read.
- #
- # See IO#eof? for more information.
- def eof?
- @stdin.eof?
- end
-
- # Whether this input method is still readable when there is no more data to
- # read.
- #
- # See IO#eof for more information.
- def readable_after_eof?
- true
- end
-
- # Returns the current line number for #io.
- #
- # #line counts the number of times #gets is called.
- #
- # See IO#lineno for more information.
- def line(line_no)
- @line[line_no]
- end
-
- # The external encoding for standard input.
- def encoding
- @stdin.external_encoding
- end
- end
-
- # Use a File for IO with irb, see InputMethod
- class FileInputMethod < InputMethod
- # Creates a new input method object
- def initialize(file)
- super
- @io = IRB::MagicFile.open(file)
- end
- # The file name of this input method, usually given during initialization.
- attr_reader :file_name
-
- # Whether the end of this input method has been reached, returns +true+ if
- # there is no more data to read.
- #
- # See IO#eof? for more information.
- def eof?
- @io.eof?
- end
-
- # Reads the next line from this input method.
- #
- # See IO#gets for more information.
- def gets
- print @prompt
- l = @io.gets
- l
- end
-
- # The external encoding for standard input.
- def encoding
- @io.external_encoding
- end
- end
-
- begin
- require "readline"
- class ReadlineInputMethod < InputMethod
- include Readline
- # Creates a new input method object using Readline
- def initialize
- super
-
- @line_no = 0
- @line = []
- @eof = false
-
- @stdin = IO.open(STDIN.to_i, :external_encoding => IRB.conf[:LC_MESSAGES].encoding, :internal_encoding => "-")
- @stdout = IO.open(STDOUT.to_i, 'w', :external_encoding => IRB.conf[:LC_MESSAGES].encoding, :internal_encoding => "-")
- end
-
- # Reads the next line from this input method.
- #
- # See IO#gets for more information.
- def gets
- Readline.input = @stdin
- Readline.output = @stdout
- if l = readline(@prompt, false)
- HISTORY.push(l) if !l.empty?
- @line[@line_no += 1] = l + "\n"
- else
- @eof = true
- l
- end
- end
-
- # Whether the end of this input method has been reached, returns +true+
- # if there is no more data to read.
- #
- # See IO#eof? for more information.
- def eof?
- @eof
- end
-
- # Whether this input method is still readable when there is no more data to
- # read.
- #
- # See IO#eof for more information.
- def readable_after_eof?
- true
- end
-
- # Returns the current line number for #io.
- #
- # #line counts the number of times #gets is called.
- #
- # See IO#lineno for more information.
- def line(line_no)
- @line[line_no]
- end
-
- # The external encoding for standard input.
- def encoding
- @stdin.external_encoding
- end
- end
- rescue LoadError
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/inspector.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/inspector.rb
deleted file mode 100755
index f09b12927..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/inspector.rb
+++ /dev/null
@@ -1,131 +0,0 @@
-#
-# irb/inspector.rb - inspect methods
-# $Release Version: 0.9.6$
-# $Revision: 1.19 $
-# $Date: 2002/06/11 07:51:31 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-module IRB # :nodoc:
-
-
- # Convenience method to create a new Inspector, using the given +inspect+
- # proc, and optional +init+ proc and passes them to Inspector.new
- #
- # irb(main):001:0> ins = IRB::Inspector(proc{ |v| "omg! #{v}" })
- # irb(main):001:0> IRB.CurrentContext.inspect_mode = ins # => omg! #
- # irb(main):001:0> "what?" #=> omg! what?
- #
- def IRB::Inspector(inspect, init = nil)
- Inspector.new(inspect, init)
- end
-
- # An irb inspector
- #
- # In order to create your own custom inspector there are two things you
- # should be aware of:
- #
- # Inspector uses #inspect_value, or +inspect_proc+, for output of return values.
- #
- # This also allows for an optional #init+, or +init_proc+, which is called
- # when the inspector is activated.
- #
- # Knowing this, you can create a rudimentary inspector as follows:
- #
- # irb(main):001:0> ins = IRB::Inspector.new(proc{ |v| "omg! #{v}" })
- # irb(main):001:0> IRB.CurrentContext.inspect_mode = ins # => omg! #
- # irb(main):001:0> "what?" #=> omg! what?
- #
- class Inspector
- # Default inspectors available to irb, this includes:
- #
- # +:pp+:: Using Kernel#pretty_inspect
- # +:yaml+:: Using YAML.dump
- # +:marshal+:: Using Marshal.dump
- INSPECTORS = {}
-
- # Determines the inspector to use where +inspector+ is one of the keys passed
- # during inspector definition.
- def self.keys_with_inspector(inspector)
- INSPECTORS.select{|k,v| v == inspector}.collect{|k, v| k}
- end
-
- # Example
- #
- # Inspector.def_inspector(key, init_p=nil){|v| v.inspect}
- # Inspector.def_inspector([key1,..], init_p=nil){|v| v.inspect}
- # Inspector.def_inspector(key, inspector)
- # Inspector.def_inspector([key1,...], inspector)
- def self.def_inspector(key, arg=nil, &block)
- if block_given?
- inspector = IRB::Inspector(block, arg)
- else
- inspector = arg
- end
-
- case key
- when Array
- for k in key
- def_inspector(k, inspector)
- end
- when Symbol
- INSPECTORS[key] = inspector
- INSPECTORS[key.to_s] = inspector
- when String
- INSPECTORS[key] = inspector
- INSPECTORS[key.intern] = inspector
- else
- INSPECTORS[key] = inspector
- end
- end
-
- # Creates a new inspector object, using the given +inspect_proc+ when
- # output return values in irb.
- def initialize(inspect_proc, init_proc = nil)
- @init = init_proc
- @inspect = inspect_proc
- end
-
- # Proc to call when the inspector is activated, good for requiring
- # dependent libraries.
- def init
- @init.call if @init
- end
-
- # Proc to call when the input is evaluated and output in irb.
- def inspect_value(v)
- @inspect.call(v)
- end
- end
-
- Inspector.def_inspector([false, :to_s, :raw]){|v| v.to_s}
- Inspector.def_inspector([true, :p, :inspect]){|v|
- begin
- v.inspect
- rescue NoMethodError
- puts "(Object doesn't support #inspect)"
- end
- }
- Inspector.def_inspector([:pp, :pretty_inspect], proc{require "pp"}){|v| v.pretty_inspect.chomp}
- Inspector.def_inspector([:yaml, :YAML], proc{require "yaml"}){|v|
- begin
- YAML.dump(v)
- rescue
- puts "(can't dump yaml. use inspect)"
- v.inspect
- end
- }
-
- Inspector.def_inspector([:marshal, :Marshal, :MARSHAL, Marshal]){|v|
- Marshal.dump(v)
- }
-end
-
-
-
-
-
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/lc/error.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/lc/error.rb
deleted file mode 100755
index a0d0dc853..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/lc/error.rb
+++ /dev/null
@@ -1,31 +0,0 @@
-#
-# irb/lc/error.rb -
-# $Release Version: 0.9.6$
-# $Revision: 38600 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-require "e2mmap"
-
-# :stopdoc:
-module IRB
-
- # exceptions
- extend Exception2MessageMapper
- def_exception :UnrecognizedSwitch, "Unrecognized switch: %s"
- def_exception :NotImplementedError, "Need to define `%s'"
- def_exception :CantReturnToNormalMode, "Can't return to normal mode."
- def_exception :IllegalParameter, "Invalid parameter(%s)."
- def_exception :IrbAlreadyDead, "Irb is already dead."
- def_exception :IrbSwitchedToCurrentThread, "Switched to current thread."
- def_exception :NoSuchJob, "No such job(%s)."
- def_exception :CantShiftToMultiIrbMode, "Can't shift to multi irb mode."
- def_exception :CantChangeBinding, "Can't change binding to (%s)."
- def_exception :UndefinedPromptMode, "Undefined prompt mode(%s)."
- def_exception :IllegalRCGenerator, 'Define illegal RC_NAME_GENERATOR.'
-
-end
-# :startdoc:
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/lc/help-message b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/lc/help-message
deleted file mode 100755
index 7ac1b2a03..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/lc/help-message
+++ /dev/null
@@ -1,50 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# irb/lc/help-message.rb -
-# $Release Version: 0.9.6$
-# $Revision: 41028 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-Usage: irb.rb [options] [programfile] [arguments]
- -f Suppress read of ~/.irbrc
- -m Bc mode (load mathn, fraction or matrix are available)
- -d Set $DEBUG to true (same as `ruby -d')
- -r load-module Same as `ruby -r'
- -I path Specify $LOAD_PATH directory
- -U Same as `ruby -U`
- -E enc Same as `ruby -E`
- -w Same as `ruby -w`
- -W[level=2] Same as `ruby -W`
- --context-mode n Set n[0-3] to method to create Binding Object,
- when new workspace was created
- --echo Show result(default)
- --noecho Don't show result
- --inspect Use `inspect' for output (default except for bc mode)
- --noinspect Don't use inspect for output
- --readline Use Readline extension module
- --noreadline Don't use Readline extension module
- --prompt prompt-mode/--prompt-mode prompt-mode
- Switch prompt mode. Pre-defined prompt modes are
- `default', `simple', `xmp' and `inf-ruby'
- --inf-ruby-mode Use prompt appropriate for inf-ruby-mode on emacs.
- Suppresses --readline.
- --sample-book-mode/--simple-prompt
- Simple prompt mode
- --noprompt No prompt mode
- --single-irb Share self with sub-irb.
- --tracer Display trace for each execution of commands.
- --back-trace-limit n
- Display backtrace top n and tail n. The default
- value is 16.
- --irb_debug n Set internal debug level to n (not for popular use)
- --verbose Show details
- --noverbose Don't show details
- -v, --version Print the version of irb
- -h, --help Print help
- -- Separate options of irb from the list of command-line args
-
-# vim:fileencoding=utf-8
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/lc/ja/encoding_aliases.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/lc/ja/encoding_aliases.rb
deleted file mode 100755
index 5bef32e20..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/lc/ja/encoding_aliases.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-# :stopdoc:
-module IRB
- class Locale
- @@legacy_encoding_alias_map = {
- 'ujis' => Encoding::EUC_JP,
- 'euc' => Encoding::EUC_JP
- }.freeze
- end
-end
-# :startdoc:
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/lc/ja/error.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/lc/ja/error.rb
deleted file mode 100755
index 653277732..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/lc/ja/error.rb
+++ /dev/null
@@ -1,30 +0,0 @@
-# -*- coding: utf-8 -*-
-# irb/lc/ja/error.rb -
-# $Release Version: 0.9.6$
-# $Revision: 38600 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-require "e2mmap"
-
-# :stopdoc:
-module IRB
- # exceptions
- extend Exception2MessageMapper
- def_exception :UnrecognizedSwitch, 'スイッチ(%s)が分りません'
- def_exception :NotImplementedError, '`%s\'の定義が必要です'
- def_exception :CantReturnToNormalMode, 'Normalモードに戻れません.'
- def_exception :IllegalParameter, 'パラメータ(%s)が間違っています.'
- def_exception :IrbAlreadyDead, 'Irbは既に死んでいます.'
- def_exception :IrbSwitchedToCurrentThread, 'カレントスレッドに切り替わりました.'
- def_exception :NoSuchJob, 'そのようなジョブ(%s)はありません.'
- def_exception :CantShiftToMultiIrbMode, 'multi-irb modeに移れません.'
- def_exception :CantChangeBinding, 'バインディング(%s)に変更できません.'
- def_exception :UndefinedPromptMode, 'プロンプトモード(%s)は定義されていません.'
- def_exception :IllegalRCNameGenerator, 'RC_NAME_GENERATORが正しく定義されていません.'
-end
-# :startdoc:
-# vim:fileencoding=utf-8
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/lc/ja/help-message b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/lc/ja/help-message
deleted file mode 100755
index 1483892ff..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/lc/ja/help-message
+++ /dev/null
@@ -1,53 +0,0 @@
-# -*- coding: utf-8 -*-
-# irb/lc/ja/help-message.rb -
-# $Release Version: 0.9.6$
-# $Revision: 41071 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-Usage: irb.rb [options] [programfile] [arguments]
- -f ~/.irbrc を読み込まない.
- -m bcモード(分数, 行列の計算ができる)
- -d $DEBUG をtrueにする(ruby -d と同じ)
- -r load-module ruby -r と同じ.
- -I path $LOAD_PATH に path を追加する.
- -U ruby -U と同じ.
- -E enc ruby -E と同じ.
- -w ruby -w と同じ.
- -W[level=2] ruby -W と同じ.
- --context-mode n 新しいワークスペースを作成した時に関連する Binding
- オブジェクトの作成方法を 0 から 3 のいずれかに設定する.
- --echo 実行結果を表示する(デフォルト).
- --noecho 実行結果を表示しない.
- --inspect 結果出力にinspectを用いる(bcモード以外はデフォルト).
- --noinspect 結果出力にinspectを用いない.
- --readline readlineライブラリを利用する.
- --noreadline readlineライブラリを利用しない.
- --prompt prompt-mode/--prompt-mode prompt-mode
- プロンプトモードを切替えます. 現在定義されているプ
- ロンプトモードは, default, simple, xmp, inf-rubyが
- 用意されています.
- --inf-ruby-mode emacsのinf-ruby-mode用のプロンプト表示を行なう. 特
- に指定がない限り, readlineライブラリは使わなくなる.
- --sample-book-mode/--simple-prompt
- 非常にシンプルなプロンプトを用いるモードです.
- --noprompt プロンプト表示を行なわない.
- --single-irb irb 中で self を実行して得られるオブジェクトをサ
- ブ irb と共有する.
- --tracer コマンド実行時にトレースを行なう.
- --back-trace-limit n
- バックトレース表示をバックトレースの頭から n, 後ろ
- からnだけ行なう. デフォルトは16
-
- --irb_debug n irbのデバッグレベルをnに設定する(非推奨).
-
- --verbose 詳細なメッセージを出力する.
- --noverbose 詳細なメッセージを出力しない(デフォルト).
- -v, --version irbのバージョンを表示する.
- -h, --help irb のヘルプを表示する.
- -- 以降のコマンドライン引数をオプションとして扱わない.
-
-# vim:fileencoding=utf-8
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/locale.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/locale.rb
deleted file mode 100755
index f3bd2d73c..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/locale.rb
+++ /dev/null
@@ -1,181 +0,0 @@
-#
-# irb/locale.rb - internationalization module
-# $Release Version: 0.9.6$
-# $Revision: 47266 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-module IRB # :nodoc:
- class Locale
-
- LOCALE_NAME_RE = %r[
- (?[[:alpha:]]{2,3})
- (?:_ (?[[:alpha:]]{2,3}) )?
- (?:\. (?[^@]+) )?
- (?:@ (?.*) )?
- ]x
- LOCALE_DIR = "/lc/"
-
- @@legacy_encoding_alias_map = {}.freeze
-
- def initialize(locale = nil)
- @lang = @territory = @encoding_name = @modifier = nil
- @locale = locale || ENV["IRB_LANG"] || ENV["LC_MESSAGES"] || ENV["LC_ALL"] || ENV["LANG"] || "C"
- if m = LOCALE_NAME_RE.match(@locale)
- @lang, @territory, @encoding_name, @modifier = m[:language], m[:territory], m[:codeset], m[:modifier]
-
- if @encoding_name
- begin load 'irb/encoding_aliases.rb'; rescue LoadError; end
- if @encoding = @@legacy_encoding_alias_map[@encoding_name]
- warn "%s is obsolete. use %s" % ["#{@lang}_#{@territory}.#{@encoding_name}", "#{@lang}_#{@territory}.#{@encoding.name}"]
- end
- @encoding = Encoding.find(@encoding_name) rescue nil
- end
- end
- @encoding ||= (Encoding.find('locale') rescue Encoding::ASCII_8BIT)
- end
-
- attr_reader :lang, :territory, :encoding, :modifier
-
- def String(mes)
- mes = super(mes)
- if @encoding
- mes.encode(@encoding, undef: :replace)
- else
- mes
- end
- end
-
- def format(*opts)
- String(super(*opts))
- end
-
- def gets(*rs)
- String(super(*rs))
- end
-
- def readline(*rs)
- String(super(*rs))
- end
-
- def print(*opts)
- ary = opts.collect{|opt| String(opt)}
- super(*ary)
- end
-
- def printf(*opts)
- s = format(*opts)
- print s
- end
-
- def puts(*opts)
- ary = opts.collect{|opt| String(opt)}
- super(*ary)
- end
-
- def require(file, priv = nil)
- rex = Regexp.new("lc/#{Regexp.quote(file)}\.(so|o|sl|rb)?")
- return false if $".find{|f| f =~ rex}
-
- case file
- when /\.rb$/
- begin
- load(file, priv)
- $".push file
- return true
- rescue LoadError
- end
- when /\.(so|o|sl)$/
- return super
- end
-
- begin
- load(f = file + ".rb")
- $".push f #"
- return true
- rescue LoadError
- return ruby_require(file)
- end
- end
-
- alias toplevel_load load
-
- def load(file, priv=nil)
- found = find(file)
- if found
- return real_load(found, priv)
- else
- raise LoadError, "No such file to load -- #{file}"
- end
- end
-
- def find(file , paths = $:)
- dir = File.dirname(file)
- dir = "" if dir == "."
- base = File.basename(file)
-
- if dir.start_with?('/')
- return each_localized_path(dir, base).find{|full_path| File.readable? full_path}
- else
- return search_file(paths, dir, base)
- end
- end
-
- private
- def real_load(path, priv)
- src = MagicFile.open(path){|f| f.read}
- if priv
- eval("self", TOPLEVEL_BINDING).extend(Module.new {eval(src, nil, path)})
- else
- eval(src, TOPLEVEL_BINDING, path)
- end
- end
-
- # @param paths load paths in which IRB find a localized file.
- # @param dir directory
- # @param file basename to be localized
- #
- # typically, for the parameters and a in paths, it searches
- # ///
- def search_file(lib_paths, dir, file)
- each_localized_path(dir, file) do |lc_path|
- lib_paths.each do |libpath|
- full_path = File.join(libpath, lc_path)
- return full_path if File.readable?(full_path)
- end
- redo if defined?(Gem) and Gem.try_activate(lc_path)
- end
- nil
- end
-
- def each_localized_path(dir, file)
- return enum_for(:each_localized_path) unless block_given?
- each_sublocale do |lc|
- yield lc.nil? ? File.join(dir, LOCALE_DIR, file) : File.join(dir, LOCALE_DIR, lc, file)
- end
- end
-
- def each_sublocale
- if @lang
- if @territory
- if @encoding_name
- yield "#{@lang}_#{@territory}.#{@encoding_name}@#{@modifier}" if @modifier
- yield "#{@lang}_#{@territory}.#{@encoding_name}"
- end
- yield "#{@lang}_#{@territory}@#{@modifier}" if @modifier
- yield "#{@lang}_#{@territory}"
- end
- if @encoding_name
- yield "#{@lang}.#{@encoding_name}@#{@modifier}" if @modifier
- yield "#{@lang}.#{@encoding_name}"
- end
- yield "#{@lang}@#{@modifier}" if @modifier
- yield "#{@lang}"
- end
- yield nil
- end
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/magic-file.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/magic-file.rb
deleted file mode 100755
index 339ed60b6..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/magic-file.rb
+++ /dev/null
@@ -1,37 +0,0 @@
-module IRB
- class << (MagicFile = Object.new)
- # see parser_magic_comment in parse.y
- ENCODING_SPEC_RE = %r"coding\s*[=:]\s*([[:alnum:]\-_]+)"
-
- def open(path)
- io = File.open(path, 'rb')
- line = io.gets
- line = io.gets if line[0,2] == "#!"
- encoding = detect_encoding(line)
- internal_encoding = encoding
- encoding ||= default_src_encoding
- io.rewind
- io.set_encoding(encoding, internal_encoding)
-
- if block_given?
- begin
- return (yield io)
- ensure
- io.close
- end
- else
- return io
- end
- end
-
- private
- def detect_encoding(line)
- return unless line[0] == ?#
- line = line[1..-1]
- line = $1 if line[/-\*-\s*(.*?)\s*-*-$/]
- return nil unless ENCODING_SPEC_RE =~ line
- encoding = $1
- return encoding.sub(/-(?:mac|dos|unix)/i, '')
- end
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/notifier.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/notifier.rb
deleted file mode 100755
index b08d201bd..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/notifier.rb
+++ /dev/null
@@ -1,231 +0,0 @@
-#
-# notifier.rb - output methods used by irb
-# $Release Version: 0.9.6$
-# $Revision: 47112 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-require "e2mmap"
-require "irb/output-method"
-
-module IRB
- # An output formatter used internally by the lexer.
- module Notifier
- extend Exception2MessageMapper
- def_exception :ErrUndefinedNotifier,
- "undefined notifier level: %d is specified"
- def_exception :ErrUnrecognizedLevel,
- "unrecognized notifier level: %s is specified"
-
- # Define a new Notifier output source, returning a new CompositeNotifier
- # with the given +prefix+ and +output_method+.
- #
- # The optional +prefix+ will be appended to all objects being inspected
- # during output, using the given +output_method+ as the output source. If
- # no +output_method+ is given, StdioOutputMethod will be used, and all
- # expressions will be sent directly to STDOUT without any additional
- # formatting.
- def def_notifier(prefix = "", output_method = StdioOutputMethod.new)
- CompositeNotifier.new(prefix, output_method)
- end
- module_function :def_notifier
-
- # An abstract class, or superclass, for CompositeNotifier and
- # LeveledNotifier to inherit. It provides several wrapper methods for the
- # OutputMethod object used by the Notifier.
- class AbstractNotifier
- # Creates a new Notifier object
- def initialize(prefix, base_notifier)
- @prefix = prefix
- @base_notifier = base_notifier
- end
-
- # The +prefix+ for this Notifier, which is appended to all objects being
- # inspected during output.
- attr_reader :prefix
-
- # A wrapper method used to determine whether notifications are enabled.
- #
- # Defaults to +true+.
- def notify?
- true
- end
-
- # See OutputMethod#print for more detail.
- def print(*opts)
- @base_notifier.print prefix, *opts if notify?
- end
-
- # See OutputMethod#printn for more detail.
- def printn(*opts)
- @base_notifier.printn prefix, *opts if notify?
- end
-
- # See OutputMethod#printf for more detail.
- def printf(format, *opts)
- @base_notifier.printf(prefix + format, *opts) if notify?
- end
-
- # See OutputMethod#puts for more detail.
- def puts(*objs)
- if notify?
- @base_notifier.puts(*objs.collect{|obj| prefix + obj.to_s})
- end
- end
-
- # Same as #ppx, except it uses the #prefix given during object
- # initialization.
- # See OutputMethod#ppx for more detail.
- def pp(*objs)
- if notify?
- @base_notifier.ppx @prefix, *objs
- end
- end
-
- # Same as #pp, except it concatenates the given +prefix+ with the #prefix
- # given during object initialization.
- #
- # See OutputMethod#ppx for more detail.
- def ppx(prefix, *objs)
- if notify?
- @base_notifier.ppx @prefix+prefix, *objs
- end
- end
-
- # Execute the given block if notifications are enabled.
- def exec_if
- yield(@base_notifier) if notify?
- end
- end
-
- # A class that can be used to create a group of notifier objects with the
- # intent of representing a leveled notification system for irb.
- #
- # This class will allow you to generate other notifiers, and assign them
- # the appropriate level for output.
- #
- # The Notifier class provides a class-method Notifier.def_notifier to
- # create a new composite notifier. Using the first composite notifier
- # object you create, sibling notifiers can be initialized with
- # #def_notifier.
- class CompositeNotifier(other)
- @level <=> other.level
- end
-
- # Whether to output messages to the output method, depending on the level
- # of this notifier object.
- def notify?
- @base_notifier.level >= self
- end
- end
-
- # NoMsgNotifier is a LeveledNotifier that's used as the default notifier
- # when creating a new CompositeNotifier.
- #
- # This notifier is used as the +zero+ index, or level +0+, for
- # CompositeNotifier#notifiers, and will not output messages of any sort.
- class NoMsgNotifier [#0- +]
- # (\*|\*[1-9][0-9]*\$|[1-9][0-9]*)
- # .(\*|\*[1-9][0-9]*\$|[1-9][0-9]*|)?
- # #(hh|h|l|ll|L|q|j|z|t)
- # [diouxXeEfgGcsb%]
- def parse_printf_format(format, opts)
- return format, opts if $1.size % 2 == 1
- end
-
- # Calls #print on each element in the given +objs+, followed by a newline
- # character.
- def puts(*objs)
- for obj in objs
- print(*obj)
- print "\n"
- end
- end
-
- # Prints the given +objs+ calling Object#inspect on each.
- #
- # See #puts for more detail.
- def pp(*objs)
- puts(*objs.collect{|obj| obj.inspect})
- end
-
- # Prints the given +objs+ calling Object#inspect on each and appending the
- # given +prefix+.
- #
- # See #puts for more detail.
- def ppx(prefix, *objs)
- puts(*objs.collect{|obj| prefix+obj.inspect})
- end
-
- end
-
- # A standard output printer
- class StdioOutputMethod 0
- end
- end
- @debug_level = 0
-
- def initialize
- lex_init
- set_input(STDIN)
-
- @seek = 0
- @exp_line_no = @line_no = 1
- @base_char_no = 0
- @char_no = 0
- @rests = []
- @readed = []
- @here_readed = []
-
- @indent = 0
- @indent_stack = []
- @lex_state = EXPR_BEG
- @space_seen = false
- @here_header = false
- @post_symbeg = false
-
- @continue = false
- @line = ""
-
- @skip_space = false
- @readed_auto_clean_up = false
- @exception_on_syntax_error = true
-
- @prompt = nil
- end
-
- attr_accessor :skip_space
- attr_accessor :readed_auto_clean_up
- attr_accessor :exception_on_syntax_error
-
- attr_reader :seek
- attr_reader :char_no
- attr_reader :line_no
- attr_reader :indent
-
- # io functions
- def set_input(io, p = nil, &block)
- @io = io
- if p.respond_to?(:call)
- @input = p
- elsif block_given?
- @input = block
- else
- @input = Proc.new{@io.gets}
- end
- end
-
- def get_readed
- if idx = @readed.rindex("\n")
- @base_char_no = @readed.size - (idx + 1)
- else
- @base_char_no += @readed.size
- end
-
- readed = @readed.join("")
- @readed = []
- readed
- end
-
- def getc
- while @rests.empty?
- @rests.push nil unless buf_input
- end
- c = @rests.shift
- if @here_header
- @here_readed.push c
- else
- @readed.push c
- end
- @seek += 1
- if c == "\n"
- @line_no += 1
- @char_no = 0
- else
- @char_no += 1
- end
- c
- end
-
- def gets
- l = ""
- while c = getc
- l.concat(c)
- break if c == "\n"
- end
- return nil if l == "" and c.nil?
- l
- end
-
- def eof?
- @io.eof?
- end
-
- def getc_of_rests
- if @rests.empty?
- nil
- else
- getc
- end
- end
-
- def ungetc(c = nil)
- if @here_readed.empty?
- c2 = @readed.pop
- else
- c2 = @here_readed.pop
- end
- c = c2 unless c
- @rests.unshift c #c =
- @seek -= 1
- if c == "\n"
- @line_no -= 1
- if idx = @readed.rindex("\n")
- @char_no = idx + 1
- else
- @char_no = @base_char_no + @readed.size
- end
- else
- @char_no -= 1
- end
- end
-
- def peek_equal?(str)
- chrs = str.split(//)
- until @rests.size >= chrs.size
- return false unless buf_input
- end
- @rests[0, chrs.size] == chrs
- end
-
- def peek_match?(regexp)
- while @rests.empty?
- return false unless buf_input
- end
- regexp =~ @rests.join("")
- end
-
- def peek(i = 0)
- while @rests.size <= i
- return nil unless buf_input
- end
- @rests[i]
- end
-
- def buf_input
- prompt
- line = @input.call
- return nil unless line
- @rests.concat line.chars.to_a
- true
- end
- private :buf_input
-
- def set_prompt(p = nil, &block)
- p = block if block_given?
- if p.respond_to?(:call)
- @prompt = p
- else
- @prompt = Proc.new{print p}
- end
- end
-
- def prompt
- if @prompt
- @prompt.call(@ltype, @indent, @continue, @line_no)
- end
- end
-
- def initialize_input
- @ltype = nil
- @quoted = nil
- @indent = 0
- @indent_stack = []
- @lex_state = EXPR_BEG
- @space_seen = false
- @here_header = false
-
- @continue = false
- @post_symbeg = false
-
- prompt
-
- @line = ""
- @exp_line_no = @line_no
- end
-
- def each_top_level_statement
- initialize_input
- catch(:TERM_INPUT) do
- loop do
- begin
- @continue = false
- prompt
- unless l = lex
- throw :TERM_INPUT if @line == ''
- else
- @line.concat l
- if @ltype or @continue or @indent > 0
- next
- end
- end
- if @line != "\n"
- @line.force_encoding(@io.encoding)
- yield @line, @exp_line_no
- end
- break unless l
- @line = ''
- @exp_line_no = @line_no
-
- @indent = 0
- @indent_stack = []
- prompt
- rescue TerminateLineInput
- initialize_input
- prompt
- get_readed
- end
- end
- end
- end
-
- def lex
- until (((tk = token).kind_of?(TkNL) || tk.kind_of?(TkEND_OF_SCRIPT)) &&
- !@continue or
- tk.nil?)
- end
- line = get_readed
- if line == "" and tk.kind_of?(TkEND_OF_SCRIPT) || tk.nil?
- nil
- else
- line
- end
- end
-
- def token
- @prev_seek = @seek
- @prev_line_no = @line_no
- @prev_char_no = @char_no
- begin
- begin
- tk = @OP.match(self)
- @space_seen = tk.kind_of?(TkSPACE)
- @lex_state = EXPR_END if @post_symbeg && tk.kind_of?(TkOp)
- @post_symbeg = tk.kind_of?(TkSYMBEG)
- rescue SyntaxError
- raise if @exception_on_syntax_error
- tk = TkError.new(@seek, @line_no, @char_no)
- end
- end while @skip_space and tk.kind_of?(TkSPACE)
- if @readed_auto_clean_up
- get_readed
- end
- tk
- end
-
- ENINDENT_CLAUSE = [
- "case", "class", "def", "do", "for", "if",
- "module", "unless", "until", "while", "begin"
- ]
- DEINDENT_CLAUSE = ["end"
- ]
-
- PERCENT_LTYPE = {
- "q" => "\'",
- "Q" => "\"",
- "x" => "\`",
- "r" => "/",
- "w" => "]",
- "W" => "]",
- "i" => "]",
- "I" => "]",
- "s" => ":"
- }
-
- PERCENT_PAREN = {
- "{" => "}",
- "[" => "]",
- "<" => ">",
- "(" => ")"
- }
-
- Ltype2Token = {
- "\'" => TkSTRING,
- "\"" => TkSTRING,
- "\`" => TkXSTRING,
- "/" => TkREGEXP,
- "]" => TkDSTRING,
- ":" => TkSYMBOL
- }
- DLtype2Token = {
- "\"" => TkDSTRING,
- "\`" => TkDXSTRING,
- "/" => TkDREGEXP,
- }
-
- def lex_init()
- @OP = IRB::SLex.new
- @OP.def_rules("\0", "\004", "\032") do |op, io|
- Token(TkEND_OF_SCRIPT)
- end
-
- @OP.def_rules(" ", "\t", "\f", "\r", "\13") do |op, io|
- @space_seen = true
- while getc =~ /[ \t\f\r\13]/; end
- ungetc
- Token(TkSPACE)
- end
-
- @OP.def_rule("#") do |op, io|
- identify_comment
- end
-
- @OP.def_rule("=begin",
- proc{|op, io| @prev_char_no == 0 && peek(0) =~ /\s/}) do
- |op, io|
- @ltype = "="
- until getc == "\n"; end
- until peek_equal?("=end") && peek(4) =~ /\s/
- until getc == "\n"; end
- end
- gets
- @ltype = nil
- Token(TkRD_COMMENT)
- end
-
- @OP.def_rule("\n") do |op, io|
- print "\\n\n" if RubyLex.debug?
- case @lex_state
- when EXPR_BEG, EXPR_FNAME, EXPR_DOT
- @continue = true
- else
- @continue = false
- @lex_state = EXPR_BEG
- until (@indent_stack.empty? ||
- [TkLPAREN, TkLBRACK, TkLBRACE,
- TkfLPAREN, TkfLBRACK, TkfLBRACE].include?(@indent_stack.last))
- @indent_stack.pop
- end
- end
- @here_header = false
- @here_readed = []
- Token(TkNL)
- end
-
- @OP.def_rules("*", "**",
- "=", "==", "===",
- "=~", "<=>",
- "<", "<=",
- ">", ">=", ">>",
- "!", "!=", "!~") do
- |op, io|
- case @lex_state
- when EXPR_FNAME, EXPR_DOT
- @lex_state = EXPR_ARG
- else
- @lex_state = EXPR_BEG
- end
- Token(op)
- end
-
- @OP.def_rules("<<") do
- |op, io|
- tk = nil
- if @lex_state != EXPR_END && @lex_state != EXPR_CLASS &&
- (@lex_state != EXPR_ARG || @space_seen)
- c = peek(0)
- if /\S/ =~ c && (/["'`]/ =~ c || /\w/ =~ c || c == "-")
- tk = identify_here_document
- end
- end
- unless tk
- tk = Token(op)
- case @lex_state
- when EXPR_FNAME, EXPR_DOT
- @lex_state = EXPR_ARG
- else
- @lex_state = EXPR_BEG
- end
- end
- tk
- end
-
- @OP.def_rules("'", '"') do
- |op, io|
- identify_string(op)
- end
-
- @OP.def_rules("`") do
- |op, io|
- if @lex_state == EXPR_FNAME
- @lex_state = EXPR_END
- Token(op)
- else
- identify_string(op)
- end
- end
-
- @OP.def_rules('?') do
- |op, io|
- if @lex_state == EXPR_END
- @lex_state = EXPR_BEG
- Token(TkQUESTION)
- else
- ch = getc
- if @lex_state == EXPR_ARG && ch =~ /\s/
- ungetc
- @lex_state = EXPR_BEG;
- Token(TkQUESTION)
- else
- if (ch == '\\')
- read_escape
- end
- @lex_state = EXPR_END
- Token(TkINTEGER)
- end
- end
- end
-
- @OP.def_rules("&", "&&", "|", "||") do
- |op, io|
- @lex_state = EXPR_BEG
- Token(op)
- end
-
- @OP.def_rules("+=", "-=", "*=", "**=",
- "&=", "|=", "^=", "<<=", ">>=", "||=", "&&=") do
- |op, io|
- @lex_state = EXPR_BEG
- op =~ /^(.*)=$/
- Token(TkOPASGN, $1)
- end
-
- @OP.def_rule("+@", proc{|op, io| @lex_state == EXPR_FNAME}) do
- |op, io|
- @lex_state = EXPR_ARG
- Token(op)
- end
-
- @OP.def_rule("-@", proc{|op, io| @lex_state == EXPR_FNAME}) do
- |op, io|
- @lex_state = EXPR_ARG
- Token(op)
- end
-
- @OP.def_rules("+", "-") do
- |op, io|
- catch(:RET) do
- if @lex_state == EXPR_ARG
- if @space_seen and peek(0) =~ /[0-9]/
- throw :RET, identify_number
- else
- @lex_state = EXPR_BEG
- end
- elsif @lex_state != EXPR_END and peek(0) =~ /[0-9]/
- throw :RET, identify_number
- else
- @lex_state = EXPR_BEG
- end
- Token(op)
- end
- end
-
- @OP.def_rule(".") do
- |op, io|
- @lex_state = EXPR_BEG
- if peek(0) =~ /[0-9]/
- ungetc
- identify_number
- else
- # for "obj.if" etc.
- @lex_state = EXPR_DOT
- Token(TkDOT)
- end
- end
-
- @OP.def_rules("..", "...") do
- |op, io|
- @lex_state = EXPR_BEG
- Token(op)
- end
-
- lex_int2
- end
-
- def lex_int2
- @OP.def_rules("]", "}", ")") do
- |op, io|
- @lex_state = EXPR_END
- @indent -= 1
- @indent_stack.pop
- Token(op)
- end
-
- @OP.def_rule(":") do
- |op, io|
- if @lex_state == EXPR_END || peek(0) =~ /\s/
- @lex_state = EXPR_BEG
- Token(TkCOLON)
- else
- @lex_state = EXPR_FNAME
- Token(TkSYMBEG)
- end
- end
-
- @OP.def_rule("::") do
- |op, io|
- if @lex_state == EXPR_BEG or @lex_state == EXPR_ARG && @space_seen
- @lex_state = EXPR_BEG
- Token(TkCOLON3)
- else
- @lex_state = EXPR_DOT
- Token(TkCOLON2)
- end
- end
-
- @OP.def_rule("/") do
- |op, io|
- if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
- identify_string(op)
- elsif peek(0) == '='
- getc
- @lex_state = EXPR_BEG
- Token(TkOPASGN, "/") #/)
- elsif @lex_state == EXPR_ARG and @space_seen and peek(0) !~ /\s/
- identify_string(op)
- else
- @lex_state = EXPR_BEG
- Token("/") #/)
- end
- end
-
- @OP.def_rules("^") do
- |op, io|
- @lex_state = EXPR_BEG
- Token("^")
- end
-
- @OP.def_rules(",") do
- |op, io|
- @lex_state = EXPR_BEG
- Token(op)
- end
-
- @OP.def_rules(";") do
- |op, io|
- @lex_state = EXPR_BEG
- until (@indent_stack.empty? ||
- [TkLPAREN, TkLBRACK, TkLBRACE,
- TkfLPAREN, TkfLBRACK, TkfLBRACE].include?(@indent_stack.last))
- @indent_stack.pop
- end
- Token(op)
- end
-
- @OP.def_rule("~") do
- |op, io|
- @lex_state = EXPR_BEG
- Token("~")
- end
-
- @OP.def_rule("~@", proc{|op, io| @lex_state == EXPR_FNAME}) do
- |op, io|
- @lex_state = EXPR_BEG
- Token("~")
- end
-
- @OP.def_rule("(") do
- |op, io|
- @indent += 1
- if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
- @lex_state = EXPR_BEG
- tk_c = TkfLPAREN
- else
- @lex_state = EXPR_BEG
- tk_c = TkLPAREN
- end
- @indent_stack.push tk_c
- Token(tk_c)
- end
-
- @OP.def_rule("[]", proc{|op, io| @lex_state == EXPR_FNAME}) do
- |op, io|
- @lex_state = EXPR_ARG
- Token("[]")
- end
-
- @OP.def_rule("[]=", proc{|op, io| @lex_state == EXPR_FNAME}) do
- |op, io|
- @lex_state = EXPR_ARG
- Token("[]=")
- end
-
- @OP.def_rule("[") do
- |op, io|
- @indent += 1
- if @lex_state == EXPR_FNAME
- tk_c = TkfLBRACK
- else
- if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
- tk_c = TkLBRACK
- elsif @lex_state == EXPR_ARG && @space_seen
- tk_c = TkLBRACK
- else
- tk_c = TkfLBRACK
- end
- @lex_state = EXPR_BEG
- end
- @indent_stack.push tk_c
- Token(tk_c)
- end
-
- @OP.def_rule("{") do
- |op, io|
- @indent += 1
- if @lex_state != EXPR_END && @lex_state != EXPR_ARG
- tk_c = TkLBRACE
- else
- tk_c = TkfLBRACE
- end
- @lex_state = EXPR_BEG
- @indent_stack.push tk_c
- Token(tk_c)
- end
-
- @OP.def_rule('\\') do
- |op, io|
- if getc == "\n"
- @space_seen = true
- @continue = true
- Token(TkSPACE)
- else
- read_escape
- Token("\\")
- end
- end
-
- @OP.def_rule('%') do
- |op, io|
- if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
- identify_quotation
- elsif peek(0) == '='
- getc
- Token(TkOPASGN, :%)
- elsif @lex_state == EXPR_ARG and @space_seen and peek(0) !~ /\s/
- identify_quotation
- else
- @lex_state = EXPR_BEG
- Token("%") #))
- end
- end
-
- @OP.def_rule('$') do
- |op, io|
- identify_gvar
- end
-
- @OP.def_rule('@') do
- |op, io|
- if peek(0) =~ /[\w@]/
- ungetc
- identify_identifier
- else
- Token("@")
- end
- end
-
- @OP.def_rule("") do
- |op, io|
- printf "MATCH: start %s: %s\n", op, io.inspect if RubyLex.debug?
- if peek(0) =~ /[0-9]/
- t = identify_number
- elsif peek(0) =~ /[^\x00-\/:-@\[-^`{-\x7F]/
- t = identify_identifier
- end
- printf "MATCH: end %s: %s\n", op, io.inspect if RubyLex.debug?
- t
- end
-
- p @OP if RubyLex.debug?
- end
-
- def identify_gvar
- @lex_state = EXPR_END
-
- case ch = getc
- when /[~_*$?!@\/\\;,=:<>".]/ #"
- Token(TkGVAR, "$" + ch)
- when "-"
- Token(TkGVAR, "$-" + getc)
- when "&", "`", "'", "+"
- Token(TkBACK_REF, "$"+ch)
- when /[1-9]/
- while getc =~ /[0-9]/; end
- ungetc
- Token(TkNTH_REF)
- when /\w/
- ungetc
- ungetc
- identify_identifier
- else
- ungetc
- Token("$")
- end
- end
-
- def identify_identifier
- token = ""
- if peek(0) =~ /[$@]/
- token.concat(c = getc)
- if c == "@" and peek(0) == "@"
- token.concat getc
- end
- end
-
- while (ch = getc) =~ /[^\x00-\/:-@\[-^`{-\x7F]/
- print ":", ch, ":" if RubyLex.debug?
- token.concat ch
- end
- ungetc
-
- if (ch == "!" || ch == "?") && token[0,1] =~ /\w/ && peek(0) != "="
- token.concat getc
- end
-
- # almost fix token
-
- case token
- when /^\$/
- return Token(TkGVAR, token)
- when /^\@\@/
- @lex_state = EXPR_END
- # p Token(TkCVAR, token)
- return Token(TkCVAR, token)
- when /^\@/
- @lex_state = EXPR_END
- return Token(TkIVAR, token)
- end
-
- if @lex_state != EXPR_DOT
- print token, "\n" if RubyLex.debug?
-
- token_c, *trans = TkReading2Token[token]
- if token_c
- # reserved word?
-
- if (@lex_state != EXPR_BEG &&
- @lex_state != EXPR_FNAME &&
- trans[1])
- # modifiers
- token_c = TkSymbol2Token[trans[1]]
- @lex_state = trans[0]
- else
- if @lex_state != EXPR_FNAME
- if ENINDENT_CLAUSE.include?(token)
- # check for ``class = val'' etc.
- valid = true
- case token
- when "class"
- valid = false unless peek_match?(/^\s*(<<|\w|::)/)
- when "def"
- valid = false if peek_match?(/^\s*(([+\-\/*&\|^]|<<|>>|\|\||\&\&)=|\&\&|\|\|)/)
- when "do"
- valid = false if peek_match?(/^\s*([+\-\/*]?=|\*|<|>|\&)/)
- when *ENINDENT_CLAUSE
- valid = false if peek_match?(/^\s*([+\-\/*]?=|\*|<|>|\&|\|)/)
- else
- # no nothing
- end
- if valid
- if token == "do"
- if ![TkFOR, TkWHILE, TkUNTIL].include?(@indent_stack.last)
- @indent += 1
- @indent_stack.push token_c
- end
- else
- @indent += 1
- @indent_stack.push token_c
- end
- end
-
- elsif DEINDENT_CLAUSE.include?(token)
- @indent -= 1
- @indent_stack.pop
- end
- @lex_state = trans[0]
- else
- @lex_state = EXPR_END
- end
- end
- return Token(token_c, token)
- end
- end
-
- if @lex_state == EXPR_FNAME
- @lex_state = EXPR_END
- if peek(0) == '='
- token.concat getc
- end
- elsif @lex_state == EXPR_BEG || @lex_state == EXPR_DOT
- @lex_state = EXPR_ARG
- else
- @lex_state = EXPR_END
- end
-
- if token[0, 1] =~ /[A-Z]/
- return Token(TkCONSTANT, token)
- elsif token[token.size - 1, 1] =~ /[!?]/
- return Token(TkFID, token)
- else
- return Token(TkIDENTIFIER, token)
- end
- end
-
- def identify_here_document
- ch = getc
- if ch == "-"
- ch = getc
- indent = true
- end
- if /['"`]/ =~ ch
- lt = ch
- quoted = ""
- while (c = getc) && c != lt
- quoted.concat c
- end
- else
- lt = '"'
- quoted = ch.dup
- while (c = getc) && c =~ /\w/
- quoted.concat c
- end
- ungetc
- end
-
- ltback, @ltype = @ltype, lt
- reserve = []
- while ch = getc
- reserve.push ch
- if ch == "\\"
- reserve.push ch = getc
- elsif ch == "\n"
- break
- end
- end
-
- @here_header = false
-
- line = ""
- while ch = getc
- if ch == "\n"
- if line == quoted
- break
- end
- line = ""
- else
- line.concat ch unless indent && line == "" && /\s/ =~ ch
- if @ltype != "'" && ch == "#" && peek(0) == "{"
- identify_string_dvar
- end
- end
- end
-
- @here_header = true
- @here_readed.concat reserve
- while ch = reserve.pop
- ungetc ch
- end
-
- @ltype = ltback
- @lex_state = EXPR_END
- Token(Ltype2Token[lt])
- end
-
- def identify_quotation
- ch = getc
- if lt = PERCENT_LTYPE[ch]
- ch = getc
- elsif ch =~ /\W/
- lt = "\""
- else
- RubyLex.fail SyntaxError, "unknown type of %string"
- end
- @quoted = ch unless @quoted = PERCENT_PAREN[ch]
- identify_string(lt, @quoted)
- end
-
- def identify_number
- @lex_state = EXPR_END
-
- if peek(0) == "0" && peek(1) !~ /[.eE]/
- getc
- case peek(0)
- when /[xX]/
- ch = getc
- match = /[0-9a-fA-F_]/
- when /[bB]/
- ch = getc
- match = /[01_]/
- when /[oO]/
- ch = getc
- match = /[0-7_]/
- when /[dD]/
- ch = getc
- match = /[0-9_]/
- when /[0-7]/
- match = /[0-7_]/
- when /[89]/
- RubyLex.fail SyntaxError, "Invalid octal digit"
- else
- return Token(TkINTEGER)
- end
-
- len0 = true
- non_digit = false
- while ch = getc
- if match =~ ch
- if ch == "_"
- if non_digit
- RubyLex.fail SyntaxError, "trailing `#{ch}' in number"
- else
- non_digit = ch
- end
- else
- non_digit = false
- len0 = false
- end
- else
- ungetc
- if len0
- RubyLex.fail SyntaxError, "numeric literal without digits"
- end
- if non_digit
- RubyLex.fail SyntaxError, "trailing `#{non_digit}' in number"
- end
- break
- end
- end
- return Token(TkINTEGER)
- end
-
- type = TkINTEGER
- allow_point = true
- allow_e = true
- non_digit = false
- while ch = getc
- case ch
- when /[0-9]/
- non_digit = false
- when "_"
- non_digit = ch
- when allow_point && "."
- if non_digit
- RubyLex.fail SyntaxError, "trailing `#{non_digit}' in number"
- end
- type = TkFLOAT
- if peek(0) !~ /[0-9]/
- type = TkINTEGER
- ungetc
- break
- end
- allow_point = false
- when allow_e && "e", allow_e && "E"
- if non_digit
- RubyLex.fail SyntaxError, "trailing `#{non_digit}' in number"
- end
- type = TkFLOAT
- if peek(0) =~ /[+-]/
- getc
- end
- allow_e = false
- allow_point = false
- non_digit = ch
- else
- if non_digit
- RubyLex.fail SyntaxError, "trailing `#{non_digit}' in number"
- end
- ungetc
- break
- end
- end
- Token(type)
- end
-
- def identify_string(ltype, quoted = ltype)
- @ltype = ltype
- @quoted = quoted
- subtype = nil
- begin
- nest = 0
- while ch = getc
- if @quoted == ch and nest == 0
- break
- elsif @ltype != "'" && ch == "#" && peek(0) == "{"
- identify_string_dvar
- elsif @ltype != "'" && @ltype != "]" && @ltype != ":" and ch == "#"
- subtype = true
- elsif ch == '\\' and @ltype == "'" #'
- case ch = getc
- when "\\", "\n", "'"
- else
- ungetc
- end
- elsif ch == '\\' #'
- read_escape
- end
- if PERCENT_PAREN.values.include?(@quoted)
- if PERCENT_PAREN[ch] == @quoted
- nest += 1
- elsif ch == @quoted
- nest -= 1
- end
- end
- end
- if @ltype == "/"
- while /[imxoesun]/ =~ peek(0)
- getc
- end
- end
- if subtype
- Token(DLtype2Token[ltype])
- else
- Token(Ltype2Token[ltype])
- end
- ensure
- @ltype = nil
- @quoted = nil
- @lex_state = EXPR_END
- end
- end
-
- def identify_string_dvar
- begin
- getc
-
- reserve_continue = @continue
- reserve_ltype = @ltype
- reserve_indent = @indent
- reserve_indent_stack = @indent_stack
- reserve_state = @lex_state
- reserve_quoted = @quoted
-
- @ltype = nil
- @quoted = nil
- @indent = 0
- @indent_stack = []
- @lex_state = EXPR_BEG
-
- loop do
- @continue = false
- prompt
- tk = token
- if @ltype or @continue or @indent >= 0
- next
- end
- break if tk.kind_of?(TkRBRACE)
- end
- ensure
- @continue = reserve_continue
- @ltype = reserve_ltype
- @indent = reserve_indent
- @indent_stack = reserve_indent_stack
- @lex_state = reserve_state
- @quoted = reserve_quoted
- end
- end
-
- def identify_comment
- @ltype = "#"
-
- while ch = getc
- if ch == "\n"
- @ltype = nil
- ungetc
- break
- end
- end
- return Token(TkCOMMENT)
- end
-
- def read_escape
- case ch = getc
- when "\n", "\r", "\f"
- when "\\", "n", "t", "r", "f", "v", "a", "e", "b", "s" #"
- when /[0-7]/
- ungetc ch
- 3.times do
- case ch = getc
- when /[0-7]/
- when nil
- break
- else
- ungetc
- break
- end
- end
-
- when "x"
- 2.times do
- case ch = getc
- when /[0-9a-fA-F]/
- when nil
- break
- else
- ungetc
- break
- end
- end
-
- when "M"
- if (ch = getc) != '-'
- ungetc
- else
- if (ch = getc) == "\\" #"
- read_escape
- end
- end
-
- when "C", "c" #, "^"
- if ch == "C" and (ch = getc) != "-"
- ungetc
- elsif (ch = getc) == "\\" #"
- read_escape
- end
- else
- # other characters
- end
- end
-end
-# :startdoc:
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ruby-token.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ruby-token.rb
deleted file mode 100755
index cb95955cd..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ruby-token.rb
+++ /dev/null
@@ -1,266 +0,0 @@
-#
-# irb/ruby-token.rb - ruby tokens
-# $Release Version: 0.9.6$
-# $Revision: 47298 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-# :stopdoc:
-module RubyToken
- EXPR_BEG = :EXPR_BEG
- EXPR_MID = :EXPR_MID
- EXPR_END = :EXPR_END
- EXPR_ARG = :EXPR_ARG
- EXPR_FNAME = :EXPR_FNAME
- EXPR_DOT = :EXPR_DOT
- EXPR_CLASS = :EXPR_CLASS
-
- class Token
- def initialize(seek, line_no, char_no)
- @seek = seek
- @line_no = line_no
- @char_no = char_no
- end
- attr_reader :seek, :line_no, :char_no
- end
-
- class TkNode < Token
- def initialize(seek, line_no, char_no)
- super
- end
- attr_reader :node
- end
-
- class TkId < Token
- def initialize(seek, line_no, char_no, name)
- super(seek, line_no, char_no)
- @name = name
- end
- attr_reader :name
- end
-
- class TkVal < Token
- def initialize(seek, line_no, char_no, value = nil)
- super(seek, line_no, char_no)
- @value = value
- end
- attr_reader :value
- end
-
- class TkOp < Token
- attr_accessor :name
- end
-
- class TkOPASGN < TkOp
- def initialize(seek, line_no, char_no, op)
- super(seek, line_no, char_no)
- op = TkReading2Token[op][0] unless op.kind_of?(Symbol)
- @op = op
- end
- attr_reader :op
- end
-
- class TkUnknownChar < Token
- def initialize(seek, line_no, char_no, id)
- super(seek, line_no, char_no)
- @name = name
- end
- attr_reader :name
- end
-
- class TkError < Token
- end
-
- def Token(token, value = nil)
- case token
- when String
- if (tk = TkReading2Token[token]).nil?
- IRB.fail TkReading2TokenNoKey, token
- end
- tk = Token(tk[0], value)
- if tk.kind_of?(TkOp)
- tk.name = token
- end
- return tk
- when Symbol
- if (tk = TkSymbol2Token[token]).nil?
- IRB.fail TkSymbol2TokenNoKey, token
- end
- return Token(tk[0], value)
- else
- if (token.ancestors & [TkId, TkVal, TkOPASGN, TkUnknownChar]).empty?
- token.new(@prev_seek, @prev_line_no, @prev_char_no)
- else
- token.new(@prev_seek, @prev_line_no, @prev_char_no, value)
- end
- end
- end
-
- TokenDefinitions = [
- [:TkCLASS, TkId, "class", EXPR_CLASS],
- [:TkMODULE, TkId, "module", EXPR_BEG],
- [:TkDEF, TkId, "def", EXPR_FNAME],
- [:TkUNDEF, TkId, "undef", EXPR_FNAME],
- [:TkBEGIN, TkId, "begin", EXPR_BEG],
- [:TkRESCUE, TkId, "rescue", EXPR_MID],
- [:TkENSURE, TkId, "ensure", EXPR_BEG],
- [:TkEND, TkId, "end", EXPR_END],
- [:TkIF, TkId, "if", EXPR_BEG, :TkIF_MOD],
- [:TkUNLESS, TkId, "unless", EXPR_BEG, :TkUNLESS_MOD],
- [:TkTHEN, TkId, "then", EXPR_BEG],
- [:TkELSIF, TkId, "elsif", EXPR_BEG],
- [:TkELSE, TkId, "else", EXPR_BEG],
- [:TkCASE, TkId, "case", EXPR_BEG],
- [:TkWHEN, TkId, "when", EXPR_BEG],
- [:TkWHILE, TkId, "while", EXPR_BEG, :TkWHILE_MOD],
- [:TkUNTIL, TkId, "until", EXPR_BEG, :TkUNTIL_MOD],
- [:TkFOR, TkId, "for", EXPR_BEG],
- [:TkBREAK, TkId, "break", EXPR_END],
- [:TkNEXT, TkId, "next", EXPR_END],
- [:TkREDO, TkId, "redo", EXPR_END],
- [:TkRETRY, TkId, "retry", EXPR_END],
- [:TkIN, TkId, "in", EXPR_BEG],
- [:TkDO, TkId, "do", EXPR_BEG],
- [:TkRETURN, TkId, "return", EXPR_MID],
- [:TkYIELD, TkId, "yield", EXPR_END],
- [:TkSUPER, TkId, "super", EXPR_END],
- [:TkSELF, TkId, "self", EXPR_END],
- [:TkNIL, TkId, "nil", EXPR_END],
- [:TkTRUE, TkId, "true", EXPR_END],
- [:TkFALSE, TkId, "false", EXPR_END],
- [:TkAND, TkId, "and", EXPR_BEG],
- [:TkOR, TkId, "or", EXPR_BEG],
- [:TkNOT, TkId, "not", EXPR_BEG],
- [:TkIF_MOD, TkId],
- [:TkUNLESS_MOD, TkId],
- [:TkWHILE_MOD, TkId],
- [:TkUNTIL_MOD, TkId],
- [:TkALIAS, TkId, "alias", EXPR_FNAME],
- [:TkDEFINED, TkId, "defined?", EXPR_END],
- [:TklBEGIN, TkId, "BEGIN", EXPR_END],
- [:TklEND, TkId, "END", EXPR_END],
- [:Tk__LINE__, TkId, "__LINE__", EXPR_END],
- [:Tk__FILE__, TkId, "__FILE__", EXPR_END],
-
- [:TkIDENTIFIER, TkId],
- [:TkFID, TkId],
- [:TkGVAR, TkId],
- [:TkCVAR, TkId],
- [:TkIVAR, TkId],
- [:TkCONSTANT, TkId],
-
- [:TkINTEGER, TkVal],
- [:TkFLOAT, TkVal],
- [:TkSTRING, TkVal],
- [:TkXSTRING, TkVal],
- [:TkREGEXP, TkVal],
- [:TkSYMBOL, TkVal],
-
- [:TkDSTRING, TkNode],
- [:TkDXSTRING, TkNode],
- [:TkDREGEXP, TkNode],
- [:TkNTH_REF, TkNode],
- [:TkBACK_REF, TkNode],
-
- [:TkUPLUS, TkOp, "+@"],
- [:TkUMINUS, TkOp, "-@"],
- [:TkPOW, TkOp, "**"],
- [:TkCMP, TkOp, "<=>"],
- [:TkEQ, TkOp, "=="],
- [:TkEQQ, TkOp, "==="],
- [:TkNEQ, TkOp, "!="],
- [:TkGEQ, TkOp, ">="],
- [:TkLEQ, TkOp, "<="],
- [:TkANDOP, TkOp, "&&"],
- [:TkOROP, TkOp, "||"],
- [:TkMATCH, TkOp, "=~"],
- [:TkNMATCH, TkOp, "!~"],
- [:TkDOT2, TkOp, ".."],
- [:TkDOT3, TkOp, "..."],
- [:TkAREF, TkOp, "[]"],
- [:TkASET, TkOp, "[]="],
- [:TkLSHFT, TkOp, "<<"],
- [:TkRSHFT, TkOp, ">>"],
- [:TkCOLON2, TkOp],
- [:TkCOLON3, TkOp],
- [:TkASSOC, TkOp, "=>"],
- [:TkQUESTION, TkOp, "?"], #?
- [:TkCOLON, TkOp, ":"], #:
-
- [:TkfLPAREN], # func( #
- [:TkfLBRACK], # func[ #
- [:TkfLBRACE], # func{ #
- [:TkSTAR], # *arg
- [:TkAMPER], # &arg #
- [:TkSYMBEG], # :SYMBOL
-
- [:TkGT, TkOp, ">"],
- [:TkLT, TkOp, "<"],
- [:TkPLUS, TkOp, "+"],
- [:TkMINUS, TkOp, "-"],
- [:TkMULT, TkOp, "*"],
- [:TkDIV, TkOp, "/"],
- [:TkMOD, TkOp, "%"],
- [:TkBITOR, TkOp, "|"],
- [:TkBITXOR, TkOp, "^"],
- [:TkBITAND, TkOp, "&"],
- [:TkBITNOT, TkOp, "~"],
- [:TkNOTOP, TkOp, "!"],
-
- [:TkBACKQUOTE, TkOp, "`"],
-
- [:TkASSIGN, Token, "="],
- [:TkDOT, Token, "."],
- [:TkLPAREN, Token, "("], #(exp)
- [:TkLBRACK, Token, "["], #[arry]
- [:TkLBRACE, Token, "{"], #{hash}
- [:TkRPAREN, Token, ")"],
- [:TkRBRACK, Token, "]"],
- [:TkRBRACE, Token, "}"],
- [:TkCOMMA, Token, ","],
- [:TkSEMICOLON, Token, ";"],
-
- [:TkCOMMENT],
- [:TkRD_COMMENT],
- [:TkSPACE],
- [:TkNL],
- [:TkEND_OF_SCRIPT],
-
- [:TkBACKSLASH, TkUnknownChar, "\\"],
- [:TkAT, TkUnknownChar, "@"],
- [:TkDOLLAR, TkUnknownChar, "$"],
- ]
-
- # {reading => token_class}
- # {reading => [token_class, *opt]}
- TkReading2Token = {}
- TkSymbol2Token = {}
-
- def RubyToken.def_token(token_n, super_token = Token, reading = nil, *opts)
- token_n = token_n.id2name if token_n.kind_of?(Symbol)
- if RubyToken.const_defined?(token_n)
- IRB.fail AlreadyDefinedToken, token_n
- end
- token_c = eval("class #{token_n} < #{super_token}; end; #{token_n}")
-
- if reading
- if TkReading2Token[reading]
- IRB.fail TkReading2TokenDuplicateError, token_n, reading
- end
- if opts.empty?
- TkReading2Token[reading] = [token_c]
- else
- TkReading2Token[reading] = [token_c].concat(opts)
- end
- end
- TkSymbol2Token[token_n.intern] = token_c
- end
-
- for defs in TokenDefinitions
- def_token(*defs)
- end
-end
-# :startdoc:
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/slex.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/slex.rb
deleted file mode 100755
index 54429cf99..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/slex.rb
+++ /dev/null
@@ -1,281 +0,0 @@
-#
-# irb/slex.rb - simple lex analyzer
-# $Release Version: 0.9.6$
-# $Revision: 47266 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-require "e2mmap"
-require "irb/notifier"
-
-# :stopdoc:
-module IRB
- class SLex
-
- extend Exception2MessageMapper
- def_exception :ErrNodeNothing, "node nothing"
- def_exception :ErrNodeAlreadyExists, "node already exists"
-
- DOUT = Notifier::def_notifier("SLex::")
- D_WARN = DOUT::def_notifier(1, "Warn: ")
- D_DEBUG = DOUT::def_notifier(2, "Debug: ")
- D_DETAIL = DOUT::def_notifier(4, "Detail: ")
-
- DOUT.level = Notifier::D_NOMSG
-
- def initialize
- @head = Node.new("")
- end
-
- def def_rule(token, preproc = nil, postproc = nil, &block)
- D_DETAIL.pp token
-
- postproc = block if block_given?
- create(token, preproc, postproc)
- end
-
- def def_rules(*tokens, &block)
- if block_given?
- p = block
- end
- for token in tokens
- def_rule(token, nil, p)
- end
- end
-
- def preproc(token, proc)
- node = search(token)
- node.preproc=proc
- end
-
- #$BMW%A%'%C%/(B?
- def postproc(token)
- node = search(token, proc)
- node.postproc=proc
- end
-
- def search(token)
- @head.search(token.split(//))
- end
-
- def create(token, preproc = nil, postproc = nil)
- @head.create_subnode(token.split(//), preproc, postproc)
- end
-
- def match(token)
- case token
- when Array
- when String
- return match(token.split(//))
- else
- return @head.match_io(token)
- end
- ret = @head.match(token)
- D_DETAIL.exec_if{D_DETAIL.printf "match end: %s:%s\n", ret, token.inspect}
- ret
- end
-
- def inspect
- format("", @head.inspect)
- end
-
- #----------------------------------------------------------------------
- #
- # class Node -
- #
- #----------------------------------------------------------------------
- class Node
- # if postproc is nil, this node is an abstract node.
- # if postproc is non-nil, this node is a real node.
- def initialize(preproc = nil, postproc = nil)
- @Tree = {}
- @preproc = preproc
- @postproc = postproc
- end
-
- attr_accessor :preproc
- attr_accessor :postproc
-
- def search(chrs, opt = nil)
- return self if chrs.empty?
- ch = chrs.shift
- if node = @Tree[ch]
- node.search(chrs, opt)
- else
- if opt
- chrs.unshift ch
- self.create_subnode(chrs)
- else
- SLex.fail ErrNodeNothing
- end
- end
- end
-
- def create_subnode(chrs, preproc = nil, postproc = nil)
- if chrs.empty?
- if @postproc
- D_DETAIL.pp node
- SLex.fail ErrNodeAlreadyExists
- else
- D_DEBUG.puts "change abstract node to real node."
- @preproc = preproc
- @postproc = postproc
- end
- return self
- end
-
- ch = chrs.shift
- if node = @Tree[ch]
- if chrs.empty?
- if node.postproc
- DebugLogger.pp node
- DebugLogger.pp self
- DebugLogger.pp ch
- DebugLogger.pp chrs
- SLex.fail ErrNodeAlreadyExists
- else
- D_WARN.puts "change abstract node to real node"
- node.preproc = preproc
- node.postproc = postproc
- end
- else
- node.create_subnode(chrs, preproc, postproc)
- end
- else
- if chrs.empty?
- node = Node.new(preproc, postproc)
- else
- node = Node.new
- node.create_subnode(chrs, preproc, postproc)
- end
- @Tree[ch] = node
- end
- node
- end
-
- #
- # chrs: String
- # character array
- # io must have getc()/ungetc(); and ungetc() must be
- # able to be called arbitrary number of times.
- #
- def match(chrs, op = "")
- D_DETAIL.print "match>: ", chrs, "op:", op, "\n"
- if chrs.empty?
- if @preproc.nil? || @preproc.call(op, chrs)
- DOUT.printf(D_DETAIL, "op1: %s\n", op)
- @postproc.call(op, chrs)
- else
- nil
- end
- else
- ch = chrs.shift
- if node = @Tree[ch]
- if ret = node.match(chrs, op+ch)
- return ret
- else
- chrs.unshift ch
- if @postproc and @preproc.nil? || @preproc.call(op, chrs)
- DOUT.printf(D_DETAIL, "op2: %s\n", op.inspect)
- ret = @postproc.call(op, chrs)
- return ret
- else
- return nil
- end
- end
- else
- chrs.unshift ch
- if @postproc and @preproc.nil? || @preproc.call(op, chrs)
- DOUT.printf(D_DETAIL, "op3: %s\n", op)
- @postproc.call(op, chrs)
- return ""
- else
- return nil
- end
- end
- end
- end
-
- def match_io(io, op = "")
- if op == ""
- ch = io.getc
- if ch == nil
- return nil
- end
- else
- ch = io.getc_of_rests
- end
- if ch.nil?
- if @preproc.nil? || @preproc.call(op, io)
- D_DETAIL.printf("op1: %s\n", op)
- @postproc.call(op, io)
- else
- nil
- end
- else
- if node = @Tree[ch]
- if ret = node.match_io(io, op+ch)
- ret
- else
- io.ungetc ch
- if @postproc and @preproc.nil? || @preproc.call(op, io)
- DOUT.exec_if{D_DETAIL.printf "op2: %s\n", op.inspect}
- @postproc.call(op, io)
- else
- nil
- end
- end
- else
- io.ungetc ch
- if @postproc and @preproc.nil? || @preproc.call(op, io)
- D_DETAIL.printf("op3: %s\n", op)
- @postproc.call(op, io)
- else
- nil
- end
- end
- end
- end
- end
- end
-end
-# :startdoc:
-
-if $0 == __FILE__
- case $1
- when "1"
- tr = SLex.new
- print "0: ", tr.inspect, "\n"
- tr.def_rule("=") {print "=\n"}
- print "1: ", tr.inspect, "\n"
- tr.def_rule("==") {print "==\n"}
- print "2: ", tr.inspect, "\n"
-
- print "case 1:\n"
- print tr.match("="), "\n"
- print "case 2:\n"
- print tr.match("=="), "\n"
- print "case 3:\n"
- print tr.match("=>"), "\n"
-
- when "2"
- tr = SLex.new
- print "0: ", tr.inspect, "\n"
- tr.def_rule("=") {print "=\n"}
- print "1: ", tr.inspect, "\n"
- tr.def_rule("==", proc{false}) {print "==\n"}
- print "2: ", tr.inspect, "\n"
-
- print "case 1:\n"
- print tr.match("="), "\n"
- print "case 2:\n"
- print tr.match("=="), "\n"
- print "case 3:\n"
- print tr.match("=>"), "\n"
- end
- exit
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/src_encoding.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/src_encoding.rb
deleted file mode 100755
index 958cef104..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/src_encoding.rb
+++ /dev/null
@@ -1,4 +0,0 @@
-# DO NOT WRITE ANY MAGIC COMMENT HERE.
-def default_src_encoding
- return __ENCODING__
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/version.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/version.rb
deleted file mode 100755
index a0e556e45..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/version.rb
+++ /dev/null
@@ -1,15 +0,0 @@
-#
-# irb/version.rb - irb version definition file
-# $Release Version: 0.9.6$
-# $Revision: 38358 $
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-# --
-#
-#
-#
-
-module IRB # :nodoc:
- @RELEASE_VERSION = "0.9.6"
- @LAST_UPDATE_DATE = "09/06/30"
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/workspace.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/workspace.rb
deleted file mode 100755
index b7eb81080..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/workspace.rb
+++ /dev/null
@@ -1,114 +0,0 @@
-#
-# irb/workspace-binding.rb -
-# $Release Version: 0.9.6$
-# $Revision: 47112 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-module IRB # :nodoc:
- class WorkSpace
- # Creates a new workspace.
- #
- # set self to main if specified, otherwise
- # inherit main from TOPLEVEL_BINDING.
- def initialize(*main)
- if main[0].kind_of?(Binding)
- @binding = main.shift
- elsif IRB.conf[:SINGLE_IRB]
- @binding = TOPLEVEL_BINDING
- else
- case IRB.conf[:CONTEXT_MODE]
- when 0 # binding in proc on TOPLEVEL_BINDING
- @binding = eval("proc{binding}.call",
- TOPLEVEL_BINDING,
- __FILE__,
- __LINE__)
- when 1 # binding in loaded file
- require "tempfile"
- f = Tempfile.open("irb-binding")
- f.print <IRB.conf[:__MAIN__]
- attr_reader :main
-
- # Evaluate the given +statements+ within the context of this workspace.
- def evaluate(context, statements, file = __FILE__, line = __LINE__)
- eval(statements, @binding, file, line)
- end
-
- # error message manipulator
- def filter_backtrace(bt)
- case IRB.conf[:CONTEXT_MODE]
- when 0
- return nil if bt =~ /\(irb_local_binding\)/
- when 1
- if(bt =~ %r!/tmp/irb-binding! or
- bt =~ %r!irb/.*\.rb! or
- bt =~ /irb\.rb/)
- return nil
- end
- when 2
- return nil if bt =~ /irb\/.*\.rb/
- return nil if bt =~ /irb\.rb/
- when 3
- return nil if bt =~ /irb\/.*\.rb/
- return nil if bt =~ /irb\.rb/
- bt = bt.sub(/:\s*in `irb_binding'/, '')
- end
- bt
- end
-
- def IRB.delete_caller
- end
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ws-for-case-2.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ws-for-case-2.rb
deleted file mode 100755
index a70183e00..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/ws-for-case-2.rb
+++ /dev/null
@@ -1,14 +0,0 @@
-#
-# irb/ws-for-case-2.rb -
-# $Release Version: 0.9.6$
-# $Revision: 29726 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-while true
- IRB::BINDING_QUEUE.push _ = binding
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/xmp.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/xmp.rb
deleted file mode 100755
index 395a56250..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/irb/xmp.rb
+++ /dev/null
@@ -1,169 +0,0 @@
-#
-# xmp.rb - irb version of gotoken xmp
-# $Release Version: 0.9$
-# $Revision: 47266 $
-# by Keiju ISHITSUKA(Nippon Rational Inc.)
-#
-# --
-#
-#
-#
-
-require "irb"
-require "irb/frame"
-
-# An example printer for irb.
-#
-# It's much like the standard library PrettyPrint, that shows the value of each
-# expression as it runs.
-#
-# In order to use this library, you must first require it:
-#
-# require 'irb/xmp'
-#
-# Now, you can take advantage of the Object#xmp convenience method.
-#
-# xmp < foo = "bar"
-# #==>"bar"
-# #=> baz = 42
-# #==>42
-#
-# You can also create an XMP object, with an optional binding to print
-# expressions in the given binding:
-#
-# ctx = binding
-# x = XMP.new ctx
-# x.puts
-# #=> today = "a good day"
-# #==>"a good day"
-# ctx.eval 'today # is what?'
-# #=> "a good day"
-class XMP
-
- # Creates a new XMP object.
- #
- # The top-level binding or, optional +bind+ parameter will be used when
- # creating the workspace. See WorkSpace.new for more information.
- #
- # This uses the +:XMP+ prompt mode, see IRB@Customizing+the+IRB+Prompt for
- # full detail.
- def initialize(bind = nil)
- IRB.init_config(nil)
-
- IRB.conf[:PROMPT_MODE] = :XMP
-
- bind = IRB::Frame.top(1) unless bind
- ws = IRB::WorkSpace.new(bind)
- @io = StringInputMethod.new
- @irb = IRB::Irb.new(ws, @io)
- @irb.context.ignore_sigint = false
-
- IRB.conf[:MAIN_CONTEXT] = @irb.context
- end
-
- # Evaluates the given +exps+, for example:
- #
- # require 'irb/xmp'
- # x = XMP.new
- #
- # x.puts '{:a => 1, :b => 2, :c => 3}'
- # #=> {:a => 1, :b => 2, :c => 3}
- # # ==>{:a=>1, :b=>2, :c=>3}
- # x.puts 'foo = "bar"'
- # # => foo = "bar"
- # # ==>"bar"
- def puts(exps)
- @io.puts exps
-
- if @irb.context.ignore_sigint
- begin
- trap_proc_b = trap("SIGINT"){@irb.signal_handle}
- catch(:IRB_EXIT) do
- @irb.eval_input
- end
- ensure
- trap("SIGINT", trap_proc_b)
- end
- else
- catch(:IRB_EXIT) do
- @irb.eval_input
- end
- end
- end
-
- # A custom InputMethod class used by XMP for evaluating string io.
- class StringInputMethod < IRB::InputMethod
- # Creates a new StringInputMethod object
- def initialize
- super
- @exps = []
- end
-
- # Whether there are any expressions left in this printer.
- def eof?
- @exps.empty?
- end
-
- # Reads the next expression from this printer.
- #
- # See IO#gets for more information.
- def gets
- while l = @exps.shift
- next if /^\s+$/ =~ l
- l.concat "\n"
- print @prompt, l
- break
- end
- l
- end
-
- # Concatenates all expressions in this printer, separated by newlines.
- #
- # An Encoding::CompatibilityError is raised of the given +exps+'s encoding
- # doesn't match the previous expression evaluated.
- def puts(exps)
- if @encoding and exps.encoding != @encoding
- enc = Encoding.compatible?(@exps.join("\n"), exps)
- if enc.nil?
- raise Encoding::CompatibilityError, "Encoding in which the passed expression is encoded is not compatible to the preceding's one"
- else
- @encoding = enc
- end
- else
- @encoding = exps.encoding
- end
- @exps.concat exps.split(/\n/)
- end
-
- # Returns the encoding of last expression printed by #puts.
- attr_reader :encoding
- end
-end
-
-# A convenience method that's only available when the you require the IRB::XMP standard library.
-#
-# Creates a new XMP object, using the given expressions as the +exps+
-# parameter, and optional binding as +bind+ or uses the top-level binding. Then
-# evaluates the given expressions using the +:XMP+ prompt mode.
-#
-# For example:
-#
-# require 'irb/xmp'
-# ctx = binding
-# xmp 'foo = "bar"', ctx
-# #=> foo = "bar"
-# #==>"bar"
-# ctx.eval 'foo'
-# #=> "bar"
-#
-# See XMP.new for more information.
-def xmp(exps, bind = nil)
- bind = IRB::Frame.top(1) unless bind
- xmp = XMP.new(bind)
- xmp.puts exps
- xmp
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json.rb
deleted file mode 100755
index 24aa385c9..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json.rb
+++ /dev/null
@@ -1,62 +0,0 @@
-require 'json/common'
-
-##
-# = JavaScript Object Notation (JSON)
-#
-# JSON is a lightweight data-interchange format. It is easy for us
-# humans to read and write. Plus, equally simple for machines to generate or parse.
-# JSON is completely language agnostic, making it the ideal interchange format.
-#
-# Built on two universally available structures:
-# 1. A collection of name/value pairs. Often referred to as an _object_, hash table, record, struct, keyed list, or associative array.
-# 2. An ordered list of values. More commonly called an _array_, vector, sequence or list.
-#
-# To read more about JSON visit: http://json.org
-#
-# == Parsing JSON
-#
-# To parse a JSON string received by another application or generated within
-# your existing application:
-#
-# require 'json'
-#
-# my_hash = JSON.parse('{"hello": "goodbye"}')
-# puts my_hash["hello"] => "goodbye"
-#
-# Notice the extra quotes '' around the hash notation. Ruby expects
-# the argument to be a string and can't convert objects like a hash or array.
-#
-# Ruby converts your string into a hash
-#
-# == Generating JSON
-#
-# Creating a JSON string for communication or serialization is
-# just as simple.
-#
-# require 'json'
-#
-# my_hash = {:hello => "goodbye"}
-# puts JSON.generate(my_hash) => "{\"hello\":\"goodbye\"}"
-#
-# Or an alternative way:
-#
-# require 'json'
-# puts {:hello => "goodbye"}.to_json => "{\"hello\":\"goodbye\"}"
-#
-# JSON.generate only allows objects or arrays to be converted
-# to JSON syntax. to_json, however, accepts many Ruby classes
-# even though it acts only as a method for serialization:
-#
-# require 'json'
-#
-# 1.to_json => "1"
-#
-module JSON
- require 'json/version'
-
- begin
- require 'json/ext'
- rescue LoadError
- require 'json/pure'
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/bigdecimal.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/bigdecimal.rb
deleted file mode 100755
index 0ef69f12e..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/bigdecimal.rb
+++ /dev/null
@@ -1,28 +0,0 @@
-unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
- require 'json'
-end
-defined?(::BigDecimal) or require 'bigdecimal'
-
-class BigDecimal
- # Import a JSON Marshalled object.
- #
- # method used for JSON marshalling support.
- def self.json_create(object)
- BigDecimal._load object['b']
- end
-
- # Marshal the object to JSON.
- #
- # method used for JSON marshalling support.
- def as_json(*)
- {
- JSON.create_id => self.class.name,
- 'b' => _dump,
- }
- end
-
- # return the JSON value
- def to_json(*)
- as_json.to_json
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/complex.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/complex.rb
deleted file mode 100755
index d7ebebf5f..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/complex.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
- require 'json'
-end
-defined?(::Complex) or require 'complex'
-
-class Complex
- def self.json_create(object)
- Complex(object['r'], object['i'])
- end
-
- def as_json(*)
- {
- JSON.create_id => self.class.name,
- 'r' => real,
- 'i' => imag,
- }
- end
-
- def to_json(*)
- as_json.to_json
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/core.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/core.rb
deleted file mode 100755
index 77d9dc0b2..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/core.rb
+++ /dev/null
@@ -1,11 +0,0 @@
-# This file requires the implementations of ruby core's custom objects for
-# serialisation/deserialisation.
-
-require 'json/add/date'
-require 'json/add/date_time'
-require 'json/add/exception'
-require 'json/add/range'
-require 'json/add/regexp'
-require 'json/add/struct'
-require 'json/add/symbol'
-require 'json/add/time'
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/date.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/date.rb
deleted file mode 100755
index 4288237db..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/date.rb
+++ /dev/null
@@ -1,34 +0,0 @@
-unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
- require 'json'
-end
-require 'date'
-
-# Date serialization/deserialization
-class Date
-
- # Deserializes JSON string by converting Julian year y, month
- # m, day d and Day of Calendar Reform sg to Date.
- def self.json_create(object)
- civil(*object.values_at('y', 'm', 'd', 'sg'))
- end
-
- alias start sg unless method_defined?(:start)
-
- # Returns a hash, that will be turned into a JSON object and represent this
- # object.
- def as_json(*)
- {
- JSON.create_id => self.class.name,
- 'y' => year,
- 'm' => month,
- 'd' => day,
- 'sg' => start,
- }
- end
-
- # Stores class name (Date) with Julian year y, month m, day
- # d and Day of Calendar Reform sg as JSON string
- def to_json(*args)
- as_json.to_json(*args)
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/date_time.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/date_time.rb
deleted file mode 100755
index 5ea42ea65..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/date_time.rb
+++ /dev/null
@@ -1,50 +0,0 @@
-unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
- require 'json'
-end
-require 'date'
-
-# DateTime serialization/deserialization
-class DateTime
-
- # Deserializes JSON string by converting year y, month m,
- # day d, hour H, minute M, second S,
- # offset of and Day of Calendar Reform sg to DateTime.
- def self.json_create(object)
- args = object.values_at('y', 'm', 'd', 'H', 'M', 'S')
- of_a, of_b = object['of'].split('/')
- if of_b and of_b != '0'
- args << Rational(of_a.to_i, of_b.to_i)
- else
- args << of_a
- end
- args << object['sg']
- civil(*args)
- end
-
- alias start sg unless method_defined?(:start)
-
- # Returns a hash, that will be turned into a JSON object and represent this
- # object.
- def as_json(*)
- {
- JSON.create_id => self.class.name,
- 'y' => year,
- 'm' => month,
- 'd' => day,
- 'H' => hour,
- 'M' => min,
- 'S' => sec,
- 'of' => offset.to_s,
- 'sg' => start,
- }
- end
-
- # Stores class name (DateTime) with Julian year y, month m,
- # day d, hour H, minute M, second S,
- # offset of and Day of Calendar Reform sg as JSON string
- def to_json(*args)
- as_json.to_json(*args)
- end
-end
-
-
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/exception.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/exception.rb
deleted file mode 100755
index e6ad257ab..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/exception.rb
+++ /dev/null
@@ -1,31 +0,0 @@
-unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
- require 'json'
-end
-
-# Exception serialization/deserialization
-class Exception
-
- # Deserializes JSON string by constructing new Exception object with message
- # m and backtrace b serialized with to_json
- def self.json_create(object)
- result = new(object['m'])
- result.set_backtrace object['b']
- result
- end
-
- # Returns a hash, that will be turned into a JSON object and represent this
- # object.
- def as_json(*)
- {
- JSON.create_id => self.class.name,
- 'm' => message,
- 'b' => backtrace,
- }
- end
-
- # Stores class name (Exception) with message m and backtrace array
- # b as JSON string
- def to_json(*args)
- as_json.to_json(*args)
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/ostruct.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/ostruct.rb
deleted file mode 100755
index da81e107a..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/ostruct.rb
+++ /dev/null
@@ -1,31 +0,0 @@
-unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
- require 'json'
-end
-require 'ostruct'
-
-# OpenStruct serialization/deserialization
-class OpenStruct
-
- # Deserializes JSON string by constructing new Struct object with values
- # v serialized by to_json.
- def self.json_create(object)
- new(object['t'] || object[:t])
- end
-
- # Returns a hash, that will be turned into a JSON object and represent this
- # object.
- def as_json(*)
- klass = self.class.name
- klass.to_s.empty? and raise JSON::JSONError, "Only named structs are supported!"
- {
- JSON.create_id => klass,
- 't' => table,
- }
- end
-
- # Stores class name (OpenStruct) with this struct's values v as a
- # JSON string.
- def to_json(*args)
- as_json.to_json(*args)
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/range.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/range.rb
deleted file mode 100755
index e61e553cd..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/range.rb
+++ /dev/null
@@ -1,29 +0,0 @@
-unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
- require 'json'
-end
-
-# Range serialization/deserialization
-class Range
-
- # Deserializes JSON string by constructing new Range object with arguments
- # a serialized by to_json.
- def self.json_create(object)
- new(*object['a'])
- end
-
- # Returns a hash, that will be turned into a JSON object and represent this
- # object.
- def as_json(*)
- {
- JSON.create_id => self.class.name,
- 'a' => [ first, last, exclude_end? ]
- }
- end
-
- # Stores class name (Range) with JSON array of arguments a which
- # include first (integer), last (integer), and
- # exclude_end? (boolean) as JSON string.
- def to_json(*args)
- as_json.to_json(*args)
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/rational.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/rational.rb
deleted file mode 100755
index 867cd92f0..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/rational.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
- require 'json'
-end
-defined?(::Rational) or require 'rational'
-
-class Rational
- def self.json_create(object)
- Rational(object['n'], object['d'])
- end
-
- def as_json(*)
- {
- JSON.create_id => self.class.name,
- 'n' => numerator,
- 'd' => denominator,
- }
- end
-
- def to_json(*)
- as_json.to_json
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/regexp.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/regexp.rb
deleted file mode 100755
index 2fcbb6fb1..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/regexp.rb
+++ /dev/null
@@ -1,30 +0,0 @@
-unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
- require 'json'
-end
-
-# Regexp serialization/deserialization
-class Regexp
-
- # Deserializes JSON string by constructing new Regexp object with source
- # s (Regexp or String) and options o serialized by
- # to_json
- def self.json_create(object)
- new(object['s'], object['o'])
- end
-
- # Returns a hash, that will be turned into a JSON object and represent this
- # object.
- def as_json(*)
- {
- JSON.create_id => self.class.name,
- 'o' => options,
- 's' => source,
- }
- end
-
- # Stores class name (Regexp) with options o and source s
- # (Regexp or String) as JSON string
- def to_json(*)
- as_json.to_json
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/struct.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/struct.rb
deleted file mode 100755
index 6847cde99..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/struct.rb
+++ /dev/null
@@ -1,30 +0,0 @@
-unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
- require 'json'
-end
-
-# Struct serialization/deserialization
-class Struct
-
- # Deserializes JSON string by constructing new Struct object with values
- # v serialized by to_json.
- def self.json_create(object)
- new(*object['v'])
- end
-
- # Returns a hash, that will be turned into a JSON object and represent this
- # object.
- def as_json(*)
- klass = self.class.name
- klass.to_s.empty? and raise JSON::JSONError, "Only named structs are supported!"
- {
- JSON.create_id => klass,
- 'v' => values,
- }
- end
-
- # Stores class name (Struct) with Struct values v as a JSON string.
- # Only named structs are supported.
- def to_json(*args)
- as_json.to_json(*args)
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/symbol.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/symbol.rb
deleted file mode 100755
index 03dc9a56a..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/symbol.rb
+++ /dev/null
@@ -1,25 +0,0 @@
-unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
- require 'json'
-end
-
-# Symbol serialization/deserialization
-class Symbol
- # Returns a hash, that will be turned into a JSON object and represent this
- # object.
- def as_json(*)
- {
- JSON.create_id => self.class.name,
- 's' => to_s,
- }
- end
-
- # Stores class name (Symbol) with String representation of Symbol as a JSON string.
- def to_json(*a)
- as_json.to_json(*a)
- end
-
- # Deserializes JSON string by converting the string value stored in the object to a Symbol
- def self.json_create(o)
- o['s'].to_sym
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/time.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/time.rb
deleted file mode 100755
index 338209d89..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/add/time.rb
+++ /dev/null
@@ -1,38 +0,0 @@
-unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
- require 'json'
-end
-
-# Time serialization/deserialization
-class Time
-
- # Deserializes JSON string by converting time since epoch to Time
- def self.json_create(object)
- if usec = object.delete('u') # used to be tv_usec -> tv_nsec
- object['n'] = usec * 1000
- end
- if instance_methods.include?(:tv_nsec)
- at(object['s'], Rational(object['n'], 1000))
- else
- at(object['s'], object['n'] / 1000)
- end
- end
-
- # Returns a hash, that will be turned into a JSON object and represent this
- # object.
- def as_json(*)
- nanoseconds = [ tv_usec * 1000 ]
- respond_to?(:tv_nsec) and nanoseconds << tv_nsec
- nanoseconds = nanoseconds.max
- {
- JSON.create_id => self.class.name,
- 's' => tv_sec,
- 'n' => nanoseconds,
- }
- end
-
- # Stores class name (Time) with number of seconds since epoch and number of
- # microseconds for Time as JSON string
- def to_json(*args)
- as_json.to_json(*args)
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/common.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/common.rb
deleted file mode 100755
index 8fbaa2baa..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/common.rb
+++ /dev/null
@@ -1,484 +0,0 @@
-require 'json/version'
-require 'json/generic_object'
-
-module JSON
- class << self
- # If _object_ is string-like, parse the string and return the parsed result
- # as a Ruby data structure. Otherwise generate a JSON text from the Ruby
- # data structure object and return it.
- #
- # The _opts_ argument is passed through to generate/parse respectively. See
- # generate and parse for their documentation.
- def [](object, opts = {})
- if object.respond_to? :to_str
- JSON.parse(object.to_str, opts)
- else
- JSON.generate(object, opts)
- end
- end
-
- # Returns the JSON parser class that is used by JSON. This is either
- # JSON::Ext::Parser or JSON::Pure::Parser.
- attr_reader :parser
-
- # Set the JSON parser class _parser_ to be used by JSON.
- def parser=(parser) # :nodoc:
- @parser = parser
- remove_const :Parser if JSON.const_defined_in?(self, :Parser)
- const_set :Parser, parser
- end
-
- # Return the constant located at _path_. The format of _path_ has to be
- # either ::A::B::C or A::B::C. In any case, A has to be located at the top
- # level (absolute namespace path?). If there doesn't exist a constant at
- # the given path, an ArgumentError is raised.
- def deep_const_get(path) # :nodoc:
- path.to_s.split(/::/).inject(Object) do |p, c|
- case
- when c.empty? then p
- when JSON.const_defined_in?(p, c) then p.const_get(c)
- else
- begin
- p.const_missing(c)
- rescue NameError => e
- raise ArgumentError, "can't get const #{path}: #{e}"
- end
- end
- end
- end
-
- # Set the module _generator_ to be used by JSON.
- def generator=(generator) # :nodoc:
- old, $VERBOSE = $VERBOSE, nil
- @generator = generator
- generator_methods = generator::GeneratorMethods
- for const in generator_methods.constants
- klass = deep_const_get(const)
- modul = generator_methods.const_get(const)
- klass.class_eval do
- instance_methods(false).each do |m|
- m.to_s == 'to_json' and remove_method m
- end
- include modul
- end
- end
- self.state = generator::State
- const_set :State, self.state
- const_set :SAFE_STATE_PROTOTYPE, State.new
- const_set :FAST_STATE_PROTOTYPE, State.new(
- :indent => '',
- :space => '',
- :object_nl => "",
- :array_nl => "",
- :max_nesting => false
- )
- const_set :PRETTY_STATE_PROTOTYPE, State.new(
- :indent => ' ',
- :space => ' ',
- :object_nl => "\n",
- :array_nl => "\n"
- )
- ensure
- $VERBOSE = old
- end
-
- # Returns the JSON generator module that is used by JSON. This is
- # either JSON::Ext::Generator or JSON::Pure::Generator.
- attr_reader :generator
-
- # Returns the JSON generator state class that is used by JSON. This is
- # either JSON::Ext::Generator::State or JSON::Pure::Generator::State.
- attr_accessor :state
-
- # This is create identifier, which is used to decide if the _json_create_
- # hook of a class should be called. It defaults to 'json_class'.
- attr_accessor :create_id
- end
- self.create_id = 'json_class'
-
- NaN = 0.0/0
-
- Infinity = 1.0/0
-
- MinusInfinity = -Infinity
-
- # The base exception for JSON errors.
- class JSONError < StandardError
- def self.wrap(exception)
- obj = new("Wrapped(#{exception.class}): #{exception.message.inspect}")
- obj.set_backtrace exception.backtrace
- obj
- end
- end
-
- # This exception is raised if a parser error occurs.
- class ParserError < JSONError; end
-
- # This exception is raised if the nesting of parsed data structures is too
- # deep.
- class NestingError < ParserError; end
-
- # :stopdoc:
- class CircularDatastructure < NestingError; end
- # :startdoc:
-
- # This exception is raised if a generator or unparser error occurs.
- class GeneratorError < JSONError; end
- # For backwards compatibility
- UnparserError = GeneratorError
-
- # This exception is raised if the required unicode support is missing on the
- # system. Usually this means that the iconv library is not installed.
- class MissingUnicodeSupport < JSONError; end
-
- module_function
-
- # Parse the JSON document _source_ into a Ruby data structure and return it.
- #
- # _opts_ can have the following
- # keys:
- # * *max_nesting*: The maximum depth of nesting allowed in the parsed data
- # structures. Disable depth checking with :max_nesting => false. It defaults
- # to 100.
- # * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in
- # defiance of RFC 4627 to be parsed by the Parser. This option defaults
- # to false.
- # * *symbolize_names*: If set to true, returns symbols for the names
- # (keys) in a JSON object. Otherwise strings are returned. Strings are
- # the default.
- # * *create_additions*: If set to false, the Parser doesn't create
- # additions even if a matching class and create_id was found. This option
- # defaults to true.
- # * *object_class*: Defaults to Hash
- # * *array_class*: Defaults to Array
- def parse(source, opts = {})
- Parser.new(source, opts).parse
- end
-
- # Parse the JSON document _source_ into a Ruby data structure and return it.
- # The bang version of the parse method defaults to the more dangerous values
- # for the _opts_ hash, so be sure only to parse trusted _source_ documents.
- #
- # _opts_ can have the following keys:
- # * *max_nesting*: The maximum depth of nesting allowed in the parsed data
- # structures. Enable depth checking with :max_nesting => anInteger. The parse!
- # methods defaults to not doing max depth checking: This can be dangerous
- # if someone wants to fill up your stack.
- # * *allow_nan*: If set to true, allow NaN, Infinity, and -Infinity in
- # defiance of RFC 4627 to be parsed by the Parser. This option defaults
- # to true.
- # * *create_additions*: If set to false, the Parser doesn't create
- # additions even if a matching class and create_id was found. This option
- # defaults to true.
- def parse!(source, opts = {})
- opts = {
- :max_nesting => false,
- :allow_nan => true
- }.update(opts)
- Parser.new(source, opts).parse
- end
-
- # Generate a JSON document from the Ruby data structure _obj_ and return
- # it. _state_ is * a JSON::State object,
- # * or a Hash like object (responding to to_hash),
- # * an object convertible into a hash by a to_h method,
- # that is used as or to configure a State object.
- #
- # It defaults to a state object, that creates the shortest possible JSON text
- # in one line, checks for circular data structures and doesn't allow NaN,
- # Infinity, and -Infinity.
- #
- # A _state_ hash can have the following keys:
- # * *indent*: a string used to indent levels (default: ''),
- # * *space*: a string that is put after, a : or , delimiter (default: ''),
- # * *space_before*: a string that is put before a : pair delimiter (default: ''),
- # * *object_nl*: a string that is put at the end of a JSON object (default: ''),
- # * *array_nl*: a string that is put at the end of a JSON array (default: ''),
- # * *allow_nan*: true if NaN, Infinity, and -Infinity should be
- # generated, otherwise an exception is thrown if these values are
- # encountered. This options defaults to false.
- # * *max_nesting*: The maximum depth of nesting allowed in the data
- # structures from which JSON is to be generated. Disable depth checking
- # with :max_nesting => false, it defaults to 100.
- #
- # See also the fast_generate for the fastest creation method with the least
- # amount of sanity checks, and the pretty_generate method for some
- # defaults for pretty output.
- def generate(obj, opts = nil)
- if State === opts
- state, opts = opts, nil
- else
- state = SAFE_STATE_PROTOTYPE.dup
- end
- if opts
- if opts.respond_to? :to_hash
- opts = opts.to_hash
- elsif opts.respond_to? :to_h
- opts = opts.to_h
- else
- raise TypeError, "can't convert #{opts.class} into Hash"
- end
- state = state.configure(opts)
- end
- state.generate(obj)
- end
-
- # :stopdoc:
- # I want to deprecate these later, so I'll first be silent about them, and
- # later delete them.
- alias unparse generate
- module_function :unparse
- # :startdoc:
-
- # Generate a JSON document from the Ruby data structure _obj_ and return it.
- # This method disables the checks for circles in Ruby objects.
- #
- # *WARNING*: Be careful not to pass any Ruby data structures with circles as
- # _obj_ argument because this will cause JSON to go into an infinite loop.
- def fast_generate(obj, opts = nil)
- if State === opts
- state, opts = opts, nil
- else
- state = FAST_STATE_PROTOTYPE.dup
- end
- if opts
- if opts.respond_to? :to_hash
- opts = opts.to_hash
- elsif opts.respond_to? :to_h
- opts = opts.to_h
- else
- raise TypeError, "can't convert #{opts.class} into Hash"
- end
- state.configure(opts)
- end
- state.generate(obj)
- end
-
- # :stopdoc:
- # I want to deprecate these later, so I'll first be silent about them, and later delete them.
- alias fast_unparse fast_generate
- module_function :fast_unparse
- # :startdoc:
-
- # Generate a JSON document from the Ruby data structure _obj_ and return it.
- # The returned document is a prettier form of the document returned by
- # #unparse.
- #
- # The _opts_ argument can be used to configure the generator. See the
- # generate method for a more detailed explanation.
- def pretty_generate(obj, opts = nil)
- if State === opts
- state, opts = opts, nil
- else
- state = PRETTY_STATE_PROTOTYPE.dup
- end
- if opts
- if opts.respond_to? :to_hash
- opts = opts.to_hash
- elsif opts.respond_to? :to_h
- opts = opts.to_h
- else
- raise TypeError, "can't convert #{opts.class} into Hash"
- end
- state.configure(opts)
- end
- state.generate(obj)
- end
-
- # :stopdoc:
- # I want to deprecate these later, so I'll first be silent about them, and later delete them.
- alias pretty_unparse pretty_generate
- module_function :pretty_unparse
- # :startdoc:
-
- class << self
- # The global default options for the JSON.load method:
- # :max_nesting: false
- # :allow_nan: true
- # :quirks_mode: true
- attr_accessor :load_default_options
- end
- self.load_default_options = {
- :max_nesting => false,
- :allow_nan => true,
- :quirks_mode => true,
- :create_additions => true,
- }
-
- # Load a ruby data structure from a JSON _source_ and return it. A source can
- # either be a string-like object, an IO-like object, or an object responding
- # to the read method. If _proc_ was given, it will be called with any nested
- # Ruby object as an argument recursively in depth first order. To modify the
- # default options pass in the optional _options_ argument as well.
- #
- # BEWARE: This method is meant to serialise data from trusted user input,
- # like from your own database server or clients under your control, it could
- # be dangerous to allow untrusted users to pass JSON sources into it. The
- # default options for the parser can be changed via the load_default_options
- # method.
- #
- # This method is part of the implementation of the load/dump interface of
- # Marshal and YAML.
- def load(source, proc = nil, options = {})
- opts = load_default_options.merge options
- if source.respond_to? :to_str
- source = source.to_str
- elsif source.respond_to? :to_io
- source = source.to_io.read
- elsif source.respond_to?(:read)
- source = source.read
- end
- if opts[:quirks_mode] && (source.nil? || source.empty?)
- source = 'null'
- end
- result = parse(source, opts)
- recurse_proc(result, &proc) if proc
- result
- end
-
- # Recursively calls passed _Proc_ if the parsed data structure is an _Array_ or _Hash_
- def recurse_proc(result, &proc)
- case result
- when Array
- result.each { |x| recurse_proc x, &proc }
- proc.call result
- when Hash
- result.each { |x, y| recurse_proc x, &proc; recurse_proc y, &proc }
- proc.call result
- else
- proc.call result
- end
- end
-
- alias restore load
- module_function :restore
-
- class << self
- # The global default options for the JSON.dump method:
- # :max_nesting: false
- # :allow_nan: true
- # :quirks_mode: true
- attr_accessor :dump_default_options
- end
- self.dump_default_options = {
- :max_nesting => false,
- :allow_nan => true,
- :quirks_mode => true,
- }
-
- # Dumps _obj_ as a JSON string, i.e. calls generate on the object and returns
- # the result.
- #
- # If anIO (an IO-like object or an object that responds to the write method)
- # was given, the resulting JSON is written to it.
- #
- # If the number of nested arrays or objects exceeds _limit_, an ArgumentError
- # exception is raised. This argument is similar (but not exactly the
- # same!) to the _limit_ argument in Marshal.dump.
- #
- # The default options for the generator can be changed via the
- # dump_default_options method.
- #
- # This method is part of the implementation of the load/dump interface of
- # Marshal and YAML.
- def dump(obj, anIO = nil, limit = nil)
- if anIO and limit.nil?
- anIO = anIO.to_io if anIO.respond_to?(:to_io)
- unless anIO.respond_to?(:write)
- limit = anIO
- anIO = nil
- end
- end
- opts = JSON.dump_default_options
- limit and opts.update(:max_nesting => limit)
- result = generate(obj, opts)
- if anIO
- anIO.write result
- anIO
- else
- result
- end
- rescue JSON::NestingError
- raise ArgumentError, "exceed depth limit"
- end
-
- # Swap consecutive bytes of _string_ in place.
- def self.swap!(string) # :nodoc:
- 0.upto(string.size / 2) do |i|
- break unless string[2 * i + 1]
- string[2 * i], string[2 * i + 1] = string[2 * i + 1], string[2 * i]
- end
- string
- end
-
- # Shortuct for iconv.
- if ::String.method_defined?(:encode)
- # Encodes string using Ruby's _String.encode_
- def self.iconv(to, from, string)
- string.encode(to, from)
- end
- else
- require 'iconv'
- # Encodes string using _iconv_ library
- def self.iconv(to, from, string)
- Iconv.conv(to, from, string)
- end
- end
-
- if ::Object.method(:const_defined?).arity == 1
- def self.const_defined_in?(modul, constant)
- modul.const_defined?(constant)
- end
- else
- def self.const_defined_in?(modul, constant)
- modul.const_defined?(constant, false)
- end
- end
-end
-
-module ::Kernel
- private
-
- # Outputs _objs_ to STDOUT as JSON strings in the shortest form, that is in
- # one line.
- def j(*objs)
- objs.each do |obj|
- puts JSON::generate(obj, :allow_nan => true, :max_nesting => false)
- end
- nil
- end
-
- # Outputs _objs_ to STDOUT as JSON strings in a pretty format, with
- # indentation and over many lines.
- def jj(*objs)
- objs.each do |obj|
- puts JSON::pretty_generate(obj, :allow_nan => true, :max_nesting => false)
- end
- nil
- end
-
- # If _object_ is string-like, parse the string and return the parsed result as
- # a Ruby data structure. Otherwise, generate a JSON text from the Ruby data
- # structure object and return it.
- #
- # The _opts_ argument is passed through to generate/parse respectively. See
- # generate and parse for their documentation.
- def JSON(object, *args)
- if object.respond_to? :to_str
- JSON.parse(object.to_str, args.first)
- else
- JSON.generate(object, args.first)
- end
- end
-end
-
-# Extends any Class to include _json_creatable?_ method.
-class ::Class
- # Returns true if this class can be used to create an instance
- # from a serialised JSON string. The class has to implement a class
- # method _json_create_ that expects a hash as first parameter. The hash
- # should include the required data.
- def json_creatable?
- respond_to?(:json_create)
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/ext.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/ext.rb
deleted file mode 100755
index c5f813181..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/ext.rb
+++ /dev/null
@@ -1,21 +0,0 @@
-if ENV['SIMPLECOV_COVERAGE'].to_i == 1
- require 'simplecov'
- SimpleCov.start do
- add_filter "/tests/"
- end
-end
-require 'json/common'
-
-module JSON
- # This module holds all the modules/classes that implement JSON's
- # functionality as C extensions.
- module Ext
- require 'json/ext/parser'
- require 'json/ext/generator'
- $DEBUG and warn "Using Ext extension for JSON."
- JSON.parser = Parser
- JSON.generator = Generator
- end
-
- JSON_LOADED = true unless defined?(::JSON::JSON_LOADED)
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/generic_object.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/generic_object.rb
deleted file mode 100755
index 8b8fd53be..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/generic_object.rb
+++ /dev/null
@@ -1,70 +0,0 @@
-require 'ostruct'
-
-module JSON
- class GenericObject < OpenStruct
- class << self
- alias [] new
-
- def json_creatable?
- @json_creatable
- end
-
- attr_writer :json_creatable
-
- def json_create(data)
- data = data.dup
- data.delete JSON.create_id
- self[data]
- end
-
- def from_hash(object)
- case
- when object.respond_to?(:to_hash)
- result = new
- object.to_hash.each do |key, value|
- result[key] = from_hash(value)
- end
- result
- when object.respond_to?(:to_ary)
- object.to_ary.map { |a| from_hash(a) }
- else
- object
- end
- end
-
- def load(source, proc = nil, opts = {})
- result = ::JSON.load(source, proc, opts.merge(:object_class => self))
- result.nil? ? new : result
- end
-
- def dump(obj, *args)
- ::JSON.dump(obj, *args)
- end
- end
- self.json_creatable = false
-
- def to_hash
- table
- end
-
- def [](name)
- table[name.to_sym]
- end
-
- def []=(name, value)
- __send__ "#{name}=", value
- end
-
- def |(other)
- self.class[other.to_hash.merge(to_hash)]
- end
-
- def as_json(*)
- { JSON.create_id => self.class.name }.merge to_hash
- end
-
- def to_json(*a)
- as_json.to_json(*a)
- end
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/version.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/version.rb
deleted file mode 100755
index 47cdcd607..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/json/version.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-module JSON
- # JSON version
- VERSION = '1.8.1'
- VERSION_ARRAY = VERSION.split(/\./).map { |x| x.to_i } # :nodoc:
- VERSION_MAJOR = VERSION_ARRAY[0] # :nodoc:
- VERSION_MINOR = VERSION_ARRAY[1] # :nodoc:
- VERSION_BUILD = VERSION_ARRAY[2] # :nodoc:
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/kconv.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/kconv.rb
deleted file mode 100755
index 25e04ed49..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/kconv.rb
+++ /dev/null
@@ -1,282 +0,0 @@
-#
-# kconv.rb - Kanji Converter.
-#
-# $Id: kconv.rb 30112 2010-12-07 11:47:39Z naruse $
-#
-# ----
-#
-# kconv.rb implements the Kconv class for Kanji Converter. Additionally,
-# some methods in String classes are added to allow easy conversion.
-#
-
-require 'nkf'
-
-#
-# Kanji Converter for Ruby.
-#
-module Kconv
- #
- # Public Constants
- #
-
- #Constant of Encoding
-
- # Auto-Detect
- AUTO = NKF::AUTO
- # ISO-2022-JP
- JIS = NKF::JIS
- # EUC-JP
- EUC = NKF::EUC
- # Shift_JIS
- SJIS = NKF::SJIS
- # BINARY
- BINARY = NKF::BINARY
- # NOCONV
- NOCONV = NKF::NOCONV
- # ASCII
- ASCII = NKF::ASCII
- # UTF-8
- UTF8 = NKF::UTF8
- # UTF-16
- UTF16 = NKF::UTF16
- # UTF-32
- UTF32 = NKF::UTF32
- # UNKNOWN
- UNKNOWN = NKF::UNKNOWN
-
- #
- # Public Methods
- #
-
- # call-seq:
- # Kconv.kconv(str, to_enc, from_enc=nil)
- #
- # Convert str
to to_enc
.
- # to_enc
and from_enc
are given as constants of Kconv or Encoding objects.
- def kconv(str, to_enc, from_enc=nil)
- opt = ''
- opt += ' --ic=' + from_enc.to_s if from_enc
- opt += ' --oc=' + to_enc.to_s if to_enc
-
- ::NKF::nkf(opt, str)
- end
- module_function :kconv
-
- #
- # Encode to
- #
-
- # call-seq:
- # Kconv.tojis(str) => string
- #
- # Convert str
to ISO-2022-JP
- def tojis(str)
- kconv(str, JIS)
- end
- module_function :tojis
-
- # call-seq:
- # Kconv.toeuc(str) => string
- #
- # Convert str
to EUC-JP
- def toeuc(str)
- kconv(str, EUC)
- end
- module_function :toeuc
-
- # call-seq:
- # Kconv.tosjis(str) => string
- #
- # Convert str
to Shift_JIS
- def tosjis(str)
- kconv(str, SJIS)
- end
- module_function :tosjis
-
- # call-seq:
- # Kconv.toutf8(str) => string
- #
- # Convert str
to UTF-8
- def toutf8(str)
- kconv(str, UTF8)
- end
- module_function :toutf8
-
- # call-seq:
- # Kconv.toutf16(str) => string
- #
- # Convert str
to UTF-16
- def toutf16(str)
- kconv(str, UTF16)
- end
- module_function :toutf16
-
- # call-seq:
- # Kconv.toutf32(str) => string
- #
- # Convert str
to UTF-32
- def toutf32(str)
- kconv(str, UTF32)
- end
- module_function :toutf32
-
- # call-seq:
- # Kconv.tolocale => string
- #
- # Convert self
to locale encoding
- def tolocale(str)
- kconv(str, Encoding.locale_charmap)
- end
- module_function :tolocale
-
- #
- # guess
- #
-
- # call-seq:
- # Kconv.guess(str) => encoding
- #
- # Guess input encoding by NKF.guess
- def guess(str)
- ::NKF::guess(str)
- end
- module_function :guess
-
- #
- # isEncoding
- #
-
- # call-seq:
- # Kconv.iseuc(str) => true or false
- #
- # Returns whether input encoding is EUC-JP or not.
- #
- # *Note* don't expect this return value is MatchData.
- def iseuc(str)
- str.dup.force_encoding(EUC).valid_encoding?
- end
- module_function :iseuc
-
- # call-seq:
- # Kconv.issjis(str) => true or false
- #
- # Returns whether input encoding is Shift_JIS or not.
- def issjis(str)
- str.dup.force_encoding(SJIS).valid_encoding?
- end
- module_function :issjis
-
- # call-seq:
- # Kconv.isjis(str) => true or false
- #
- # Returns whether input encoding is ISO-2022-JP or not.
- def isjis(str)
- /\A [\t\n\r\x20-\x7E]*
- (?:
- (?:\x1b \x28 I [\x21-\x7E]*
- |\x1b \x28 J [\x21-\x7E]*
- |\x1b \x24 @ (?:[\x21-\x7E]{2})*
- |\x1b \x24 B (?:[\x21-\x7E]{2})*
- |\x1b \x24 \x28 D (?:[\x21-\x7E]{2})*
- )*
- \x1b \x28 B [\t\n\r\x20-\x7E]*
- )*
- \z/nox =~ str.dup.force_encoding('BINARY') ? true : false
- end
- module_function :isjis
-
- # call-seq:
- # Kconv.isutf8(str) => true or false
- #
- # Returns whether input encoding is UTF-8 or not.
- def isutf8(str)
- str.dup.force_encoding(UTF8).valid_encoding?
- end
- module_function :isutf8
-end
-
-class String
- # call-seq:
- # String#kconv(to_enc, from_enc)
- #
- # Convert self
to to_enc
.
- # to_enc
and from_enc
are given as constants of Kconv or Encoding objects.
- def kconv(to_enc, from_enc=nil)
- from_enc = self.encoding if !from_enc && self.encoding != Encoding.list[0]
- Kconv::kconv(self, to_enc, from_enc)
- end
-
- #
- # to Encoding
- #
-
- # call-seq:
- # String#tojis => string
- #
- # Convert self
to ISO-2022-JP
- def tojis; Kconv.tojis(self) end
-
- # call-seq:
- # String#toeuc => string
- #
- # Convert self
to EUC-JP
- def toeuc; Kconv.toeuc(self) end
-
- # call-seq:
- # String#tosjis => string
- #
- # Convert self
to Shift_JIS
- def tosjis; Kconv.tosjis(self) end
-
- # call-seq:
- # String#toutf8 => string
- #
- # Convert self
to UTF-8
- def toutf8; Kconv.toutf8(self) end
-
- # call-seq:
- # String#toutf16 => string
- #
- # Convert self
to UTF-16
- def toutf16; Kconv.toutf16(self) end
-
- # call-seq:
- # String#toutf32 => string
- #
- # Convert self
to UTF-32
- def toutf32; Kconv.toutf32(self) end
-
- # call-seq:
- # String#tolocale => string
- #
- # Convert self
to locale encoding
- def tolocale; Kconv.tolocale(self) end
-
- #
- # is Encoding
- #
-
- # call-seq:
- # String#iseuc => true or false
- #
- # Returns whether self
's encoding is EUC-JP or not.
- def iseuc; Kconv.iseuc(self) end
-
- # call-seq:
- # String#issjis => true or false
- #
- # Returns whether self
's encoding is Shift_JIS or not.
- def issjis; Kconv.issjis(self) end
-
- # call-seq:
- # String#isjis => true or false
- #
- # Returns whether self
's encoding is ISO-2022-JP or not.
- def isjis; Kconv.isjis(self) end
-
- # call-seq:
- # String#isutf8 => true or false
- #
- # Returns whether self
's encoding is UTF-8 or not.
- def isutf8; Kconv.isutf8(self) end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/logger.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/logger.rb
deleted file mode 100755
index a5d88c5b1..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/logger.rb
+++ /dev/null
@@ -1,737 +0,0 @@
-# logger.rb - simple logging utility
-# Copyright (C) 2000-2003, 2005, 2008, 2011 NAKAMURA, Hiroshi .
-#
-# Documentation:: NAKAMURA, Hiroshi and Gavin Sinclair
-# License::
-# You can redistribute it and/or modify it under the same terms of Ruby's
-# license; either the dual license version in 2003, or any later version.
-# Revision:: $Id: logger.rb 47272 2014-08-25 04:03:33Z nobu $
-#
-# A simple system for logging messages. See Logger for more documentation.
-
-require 'monitor'
-
-# == Description
-#
-# The Logger class provides a simple but sophisticated logging utility that
-# you can use to output messages.
-#
-# The messages have associated levels, such as +INFO+ or +ERROR+ that indicate
-# their importance. You can then give the Logger a level, and only messages
-# at that level or higher will be printed.
-#
-# The levels are:
-#
-# +UNKNOWN+:: An unknown message that should always be logged.
-# +FATAL+:: An unhandleable error that results in a program crash.
-# +ERROR+:: A handleable error condition.
-# +WARN+:: A warning.
-# +INFO+:: Generic (useful) information about system operation.
-# +DEBUG+:: Low-level information for developers.
-#
-# For instance, in a production system, you may have your Logger set to
-# +INFO+ or even +WARN+.
-# When you are developing the system, however, you probably
-# want to know about the program's internal state, and would set the Logger to
-# +DEBUG+.
-#
-# *Note*: Logger does not escape or sanitize any messages passed to it.
-# Developers should be aware of when potentially malicious data (user-input)
-# is passed to Logger, and manually escape the untrusted data:
-#
-# logger.info("User-input: #{input.dump}")
-# logger.info("User-input: %p" % input)
-#
-# You can use #formatter= for escaping all data.
-#
-# original_formatter = Logger::Formatter.new
-# logger.formatter = proc { |severity, datetime, progname, msg|
-# original_formatter.call(severity, datetime, progname, msg.dump)
-# }
-# logger.info(input)
-#
-# === Example
-#
-# This creates a Logger that outputs to the standard output stream, with a
-# level of +WARN+:
-#
-# require 'logger'
-#
-# logger = Logger.new(STDOUT)
-# logger.level = Logger::WARN
-#
-# logger.debug("Created logger")
-# logger.info("Program started")
-# logger.warn("Nothing to do!")
-#
-# path = "a_non_existent_file"
-#
-# begin
-# File.foreach(path) do |line|
-# unless line =~ /^(\w+) = (.*)$/
-# logger.error("Line in wrong format: #{line.chomp}")
-# end
-# end
-# rescue => err
-# logger.fatal("Caught exception; exiting")
-# logger.fatal(err)
-# end
-#
-# Because the Logger's level is set to +WARN+, only the warning, error, and
-# fatal messages are recorded. The debug and info messages are silently
-# discarded.
-#
-# === Features
-#
-# There are several interesting features that Logger provides, like
-# auto-rolling of log files, setting the format of log messages, and
-# specifying a program name in conjunction with the message. The next section
-# shows you how to achieve these things.
-#
-#
-# == HOWTOs
-#
-# === How to create a logger
-#
-# The options below give you various choices, in more or less increasing
-# complexity.
-#
-# 1. Create a logger which logs messages to STDERR/STDOUT.
-#
-# logger = Logger.new(STDERR)
-# logger = Logger.new(STDOUT)
-#
-# 2. Create a logger for the file which has the specified name.
-#
-# logger = Logger.new('logfile.log')
-#
-# 3. Create a logger for the specified file.
-#
-# file = File.open('foo.log', File::WRONLY | File::APPEND)
-# # To create new (and to remove old) logfile, add File::CREAT like:
-# # file = File.open('foo.log', File::WRONLY | File::APPEND | File::CREAT)
-# logger = Logger.new(file)
-#
-# 4. Create a logger which ages the logfile once it reaches a certain size.
-# Leave 10 "old" log files where each file is about 1,024,000 bytes.
-#
-# logger = Logger.new('foo.log', 10, 1024000)
-#
-# 5. Create a logger which ages the logfile daily/weekly/monthly.
-#
-# logger = Logger.new('foo.log', 'daily')
-# logger = Logger.new('foo.log', 'weekly')
-# logger = Logger.new('foo.log', 'monthly')
-#
-# === How to log a message
-#
-# Notice the different methods (+fatal+, +error+, +info+) being used to log
-# messages of various levels? Other methods in this family are +warn+ and
-# +debug+. +add+ is used below to log a message of an arbitrary (perhaps
-# dynamic) level.
-#
-# 1. Message in a block.
-#
-# logger.fatal { "Argument 'foo' not given." }
-#
-# 2. Message as a string.
-#
-# logger.error "Argument #{@foo} mismatch."
-#
-# 3. With progname.
-#
-# logger.info('initialize') { "Initializing..." }
-#
-# 4. With severity.
-#
-# logger.add(Logger::FATAL) { 'Fatal error!' }
-#
-# The block form allows you to create potentially complex log messages,
-# but to delay their evaluation until and unless the message is
-# logged. For example, if we have the following:
-#
-# logger.debug { "This is a " + potentially + " expensive operation" }
-#
-# If the logger's level is +INFO+ or higher, no debug messages will be logged,
-# and the entire block will not even be evaluated. Compare to this:
-#
-# logger.debug("This is a " + potentially + " expensive operation")
-#
-# Here, the string concatenation is done every time, even if the log
-# level is not set to show the debug message.
-#
-# === How to close a logger
-#
-# logger.close
-#
-# === Setting severity threshold
-#
-# 1. Original interface.
-#
-# logger.sev_threshold = Logger::WARN
-#
-# 2. Log4r (somewhat) compatible interface.
-#
-# logger.level = Logger::INFO
-#
-# # DEBUG < INFO < WARN < ERROR < FATAL < UNKNOWN
-#
-# == Format
-#
-# Log messages are rendered in the output stream in a certain format by
-# default. The default format and a sample are shown below:
-#
-# Log format:
-# SeverityID, [DateTime #pid] SeverityLabel -- ProgName: message
-#
-# Log sample:
-# I, [1999-03-03T02:34:24.895701 #19074] INFO -- Main: info.
-#
-# You may change the date and time format via #datetime_format=.
-#
-# logger.datetime_format = '%Y-%m-%d %H:%M:%S'
-# # e.g. "2004-01-03 00:54:26"
-#
-# Or, you may change the overall format via the #formatter= method.
-#
-# logger.formatter = proc do |severity, datetime, progname, msg|
-# "#{datetime}: #{msg}\n"
-# end
-# # e.g. "2005-09-22 08:51:08 +0900: hello world"
-#
-class Logger
- VERSION = "1.2.7"
- _, name, rev = %w$Id: logger.rb 47272 2014-08-25 04:03:33Z nobu $
- if name
- name = name.chomp(",v")
- else
- name = File.basename(__FILE__)
- end
- rev ||= "v#{VERSION}"
- ProgName = "#{name}/#{rev}"
-
- class Error < RuntimeError # :nodoc:
- end
- # not used after 1.2.7. just for compat.
- class ShiftingError < Error # :nodoc:
- end
-
- # Logging severity.
- module Severity
- # Low-level information, mostly for developers.
- DEBUG = 0
- # Generic (useful) information about system operation.
- INFO = 1
- # A warning.
- WARN = 2
- # A handleable error condition.
- ERROR = 3
- # An unhandleable error that results in a program crash.
- FATAL = 4
- # An unknown message that should always be logged.
- UNKNOWN = 5
- end
- include Severity
-
- # Logging severity threshold (e.g. Logger::INFO).
- attr_accessor :level
-
- # Program name to include in log messages.
- attr_accessor :progname
-
- # Set date-time format.
- #
- # +datetime_format+:: A string suitable for passing to +strftime+.
- def datetime_format=(datetime_format)
- @default_formatter.datetime_format = datetime_format
- end
-
- # Returns the date format being used. See #datetime_format=
- def datetime_format
- @default_formatter.datetime_format
- end
-
- # Logging formatter, as a +Proc+ that will take four arguments and
- # return the formatted message. The arguments are:
- #
- # +severity+:: The Severity of the log message.
- # +time+:: A Time instance representing when the message was logged.
- # +progname+:: The #progname configured, or passed to the logger method.
- # +msg+:: The _Object_ the user passed to the log message; not necessarily a
- # String.
- #
- # The block should return an Object that can be written to the logging
- # device via +write+. The default formatter is used when no formatter is
- # set.
- attr_accessor :formatter
-
- alias sev_threshold level
- alias sev_threshold= level=
-
- # Returns +true+ iff the current severity level allows for the printing of
- # +DEBUG+ messages.
- def debug?; @level <= DEBUG; end
-
- # Returns +true+ iff the current severity level allows for the printing of
- # +INFO+ messages.
- def info?; @level <= INFO; end
-
- # Returns +true+ iff the current severity level allows for the printing of
- # +WARN+ messages.
- def warn?; @level <= WARN; end
-
- # Returns +true+ iff the current severity level allows for the printing of
- # +ERROR+ messages.
- def error?; @level <= ERROR; end
-
- # Returns +true+ iff the current severity level allows for the printing of
- # +FATAL+ messages.
- def fatal?; @level <= FATAL; end
-
- #
- # :call-seq:
- # Logger.new(logdev, shift_age = 7, shift_size = 1048576)
- # Logger.new(logdev, shift_age = 'weekly')
- #
- # === Args
- #
- # +logdev+::
- # The log device. This is a filename (String) or IO object (typically
- # +STDOUT+, +STDERR+, or an open file).
- # +shift_age+::
- # Number of old log files to keep, *or* frequency of rotation (+daily+,
- # +weekly+ or +monthly+).
- # +shift_size+::
- # Maximum logfile size (only applies when +shift_age+ is a number).
- #
- # === Description
- #
- # Create an instance.
- #
- def initialize(logdev, shift_age = 0, shift_size = 1048576)
- @progname = nil
- @level = DEBUG
- @default_formatter = Formatter.new
- @formatter = nil
- @logdev = nil
- if logdev
- @logdev = LogDevice.new(logdev, :shift_age => shift_age,
- :shift_size => shift_size)
- end
- end
-
- #
- # :call-seq:
- # Logger#add(severity, message = nil, progname = nil) { ... }
- #
- # === Args
- #
- # +severity+::
- # Severity. Constants are defined in Logger namespace: +DEBUG+, +INFO+,
- # +WARN+, +ERROR+, +FATAL+, or +UNKNOWN+.
- # +message+::
- # The log message. A String or Exception.
- # +progname+::
- # Program name string. Can be omitted. Treated as a message if no
- # +message+ and +block+ are given.
- # +block+::
- # Can be omitted. Called to get a message string if +message+ is nil.
- #
- # === Return
- #
- # When the given severity is not high enough (for this particular logger),
- # log no message, and return +true+.
- #
- # === Description
- #
- # Log a message if the given severity is high enough. This is the generic
- # logging method. Users will be more inclined to use #debug, #info, #warn,
- # #error, and #fatal.
- #
- # Message format: +message+ can be any object, but it has to be
- # converted to a String in order to log it. Generally, +inspect+ is used
- # if the given object is not a String.
- # A special case is an +Exception+ object, which will be printed in detail,
- # including message, class, and backtrace. See #msg2str for the
- # implementation if required.
- #
- # === Bugs
- #
- # * Logfile is not locked.
- # * Append open does not need to lock file.
- # * If the OS supports multi I/O, records possibly may be mixed.
- #
- def add(severity, message = nil, progname = nil, &block)
- severity ||= UNKNOWN
- if @logdev.nil? or severity < @level
- return true
- end
- progname ||= @progname
- if message.nil?
- if block_given?
- message = yield
- else
- message = progname
- progname = @progname
- end
- end
- @logdev.write(
- format_message(format_severity(severity), Time.now, progname, message))
- true
- end
- alias log add
-
- #
- # Dump given message to the log device without any formatting. If no log
- # device exists, return +nil+.
- #
- def <<(msg)
- unless @logdev.nil?
- @logdev.write(msg)
- end
- end
-
- #
- # Log a +DEBUG+ message.
- #
- # See #info for more information.
- #
- def debug(progname = nil, &block)
- add(DEBUG, nil, progname, &block)
- end
-
- #
- # :call-seq:
- # info(message)
- # info(progname, &block)
- #
- # Log an +INFO+ message.
- #
- # +message+:: The message to log; does not need to be a String.
- # +progname+:: In the block form, this is the #progname to use in the
- # log message. The default can be set with #progname=.
- # +block+:: Evaluates to the message to log. This is not evaluated unless
- # the logger's level is sufficient to log the message. This
- # allows you to create potentially expensive logging messages that
- # are only called when the logger is configured to show them.
- #
- # === Examples
- #
- # logger.info("MainApp") { "Received connection from #{ip}" }
- # # ...
- # logger.info "Waiting for input from user"
- # # ...
- # logger.info { "User typed #{input}" }
- #
- # You'll probably stick to the second form above, unless you want to provide a
- # program name (which you can do with #progname= as well).
- #
- # === Return
- #
- # See #add.
- #
- def info(progname = nil, &block)
- add(INFO, nil, progname, &block)
- end
-
- #
- # Log a +WARN+ message.
- #
- # See #info for more information.
- #
- def warn(progname = nil, &block)
- add(WARN, nil, progname, &block)
- end
-
- #
- # Log an +ERROR+ message.
- #
- # See #info for more information.
- #
- def error(progname = nil, &block)
- add(ERROR, nil, progname, &block)
- end
-
- #
- # Log a +FATAL+ message.
- #
- # See #info for more information.
- #
- def fatal(progname = nil, &block)
- add(FATAL, nil, progname, &block)
- end
-
- #
- # Log an +UNKNOWN+ message. This will be printed no matter what the logger's
- # level is.
- #
- # See #info for more information.
- #
- def unknown(progname = nil, &block)
- add(UNKNOWN, nil, progname, &block)
- end
-
- #
- # Close the logging device.
- #
- def close
- @logdev.close if @logdev
- end
-
-private
-
- # Severity label for logging (max 5 chars).
- SEV_LABEL = %w(DEBUG INFO WARN ERROR FATAL ANY)
-
- def format_severity(severity)
- SEV_LABEL[severity] || 'ANY'
- end
-
- def format_message(severity, datetime, progname, msg)
- (@formatter || @default_formatter).call(severity, datetime, progname, msg)
- end
-
-
- # Default formatter for log messages.
- class Formatter
- Format = "%s, [%s#%d] %5s -- %s: %s\n"
-
- attr_accessor :datetime_format
-
- def initialize
- @datetime_format = nil
- end
-
- def call(severity, time, progname, msg)
- Format % [severity[0..0], format_datetime(time), $$, severity, progname,
- msg2str(msg)]
- end
-
- private
-
- def format_datetime(time)
- time.strftime(@datetime_format || "%Y-%m-%dT%H:%M:%S.%6N ".freeze)
- end
-
- def msg2str(msg)
- case msg
- when ::String
- msg
- when ::Exception
- "#{ msg.message } (#{ msg.class })\n" <<
- (msg.backtrace || []).join("\n")
- else
- msg.inspect
- end
- end
- end
-
- module Period
- module_function
-
- SiD = 24 * 60 * 60
-
- def next_rotate_time(now, shift_age)
- case shift_age
- when /^daily$/
- t = Time.mktime(now.year, now.month, now.mday) + SiD
- when /^weekly$/
- t = Time.mktime(now.year, now.month, now.mday) + SiD * (7 - now.wday)
- when /^monthly$/
- t = Time.mktime(now.year, now.month, 1) + SiD * 31
- mday = (1 if t.mday > 1)
- else
- return now
- end
- if mday or t.hour.nonzero? or t.min.nonzero? or t.sec.nonzero?
- t = Time.mktime(t.year, t.month, mday || (t.mday + (t.hour > 12 ? 1 : 0)))
- end
- t
- end
-
- def previous_period_end(now, shift_age)
- case shift_age
- when /^daily$/
- t = Time.mktime(now.year, now.month, now.mday) - SiD / 2
- when /^weekly$/
- t = Time.mktime(now.year, now.month, now.mday) - (SiD * (now.wday + 1) + SiD / 2)
- when /^monthly$/
- t = Time.mktime(now.year, now.month, 1) - SiD / 2
- else
- return now
- end
- Time.mktime(t.year, t.month, t.mday, 23, 59, 59)
- end
- end
-
- # Device used for logging messages.
- class LogDevice
- include Period
-
- attr_reader :dev
- attr_reader :filename
-
- class LogDeviceMutex
- include MonitorMixin
- end
-
- def initialize(log = nil, opt = {})
- @dev = @filename = @shift_age = @shift_size = nil
- @mutex = LogDeviceMutex.new
- if log.respond_to?(:write) and log.respond_to?(:close)
- @dev = log
- else
- @dev = open_logfile(log)
- @dev.sync = true
- @filename = log
- @shift_age = opt[:shift_age] || 7
- @shift_size = opt[:shift_size] || 1048576
- @next_rotate_time = next_rotate_time(Time.now, @shift_age) unless @shift_age.is_a?(Integer)
- end
- end
-
- def write(message)
- begin
- @mutex.synchronize do
- if @shift_age and @dev.respond_to?(:stat)
- begin
- check_shift_log
- rescue
- warn("log shifting failed. #{$!}")
- end
- end
- begin
- @dev.write(message)
- rescue
- warn("log writing failed. #{$!}")
- end
- end
- rescue Exception => ignored
- warn("log writing failed. #{ignored}")
- end
- end
-
- def close
- begin
- @mutex.synchronize do
- @dev.close rescue nil
- end
- rescue Exception
- @dev.close rescue nil
- end
- end
-
- private
-
- def open_logfile(filename)
- begin
- open(filename, (File::WRONLY | File::APPEND))
- rescue Errno::ENOENT
- create_logfile(filename)
- end
- end
-
- def create_logfile(filename)
- begin
- logdev = open(filename, (File::WRONLY | File::APPEND | File::CREAT | File::EXCL))
- logdev.flock(File::LOCK_EX)
- logdev.sync = true
- add_log_header(logdev)
- logdev.flock(File::LOCK_UN)
- rescue Errno::EEXIST
- # file is created by another process
- logdev = open_logfile(filename)
- logdev.sync = true
- end
- logdev
- end
-
- def add_log_header(file)
- file.write(
- "# Logfile created on %s by %s\n" % [Time.now.to_s, Logger::ProgName]
- ) if file.size == 0
- end
-
- def check_shift_log
- if @shift_age.is_a?(Integer)
- # Note: always returns false if '0'.
- if @filename && (@shift_age > 0) && (@dev.stat.size > @shift_size)
- lock_shift_log { shift_log_age }
- end
- else
- now = Time.now
- if now >= @next_rotate_time
- @next_rotate_time = next_rotate_time(now, @shift_age)
- lock_shift_log { shift_log_period(previous_period_end(now, @shift_age)) }
- end
- end
- end
-
- if /mswin|mingw/ =~ RUBY_PLATFORM
- def lock_shift_log
- yield
- end
- else
- def lock_shift_log
- retry_limit = 8
- retry_sleep = 0.1
- begin
- File.open(@filename, File::WRONLY | File::APPEND) do |lock|
- lock.flock(File::LOCK_EX) # inter-process locking. will be unlocked at closing file
- if File.identical?(@filename, lock) and File.identical?(lock, @dev)
- yield # log shifting
- else
- # log shifted by another process (i-node before locking and i-node after locking are different)
- @dev.close rescue nil
- @dev = open_logfile(@filename)
- @dev.sync = true
- end
- end
- rescue Errno::ENOENT
- # @filename file would not exist right after #rename and before #create_logfile
- if retry_limit <= 0
- warn("log rotation inter-process lock failed. #{$!}")
- else
- sleep retry_sleep
- retry_limit -= 1
- retry_sleep *= 2
- retry
- end
- end
- rescue
- warn("log rotation inter-process lock failed. #{$!}")
- end
- end
-
- def shift_log_age
- (@shift_age-3).downto(0) do |i|
- if FileTest.exist?("#{@filename}.#{i}")
- File.rename("#{@filename}.#{i}", "#{@filename}.#{i+1}")
- end
- end
- @dev.close rescue nil
- File.rename("#{@filename}", "#{@filename}.0")
- @dev = create_logfile(@filename)
- return true
- end
-
- def shift_log_period(period_end)
- postfix = period_end.strftime("%Y%m%d") # YYYYMMDD
- age_file = "#{@filename}.#{postfix}"
- if FileTest.exist?(age_file)
- # try to avoid filename crash caused by Timestamp change.
- idx = 0
- # .99 can be overridden; avoid too much file search with 'loop do'
- while idx < 100
- idx += 1
- age_file = "#{@filename}.#{postfix}.#{idx}"
- break unless FileTest.exist?(age_file)
- end
- end
- @dev.close rescue nil
- File.rename("#{@filename}", age_file)
- @dev = create_logfile(@filename)
- return true
- end
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/mathn.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/mathn.rb
deleted file mode 100755
index 315e5438d..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/mathn.rb
+++ /dev/null
@@ -1,191 +0,0 @@
-#--
-# $Release Version: 0.5 $
-# $Revision: 1.1.1.1.4.1 $
-
-##
-# = mathn
-#
-# mathn serves to make mathematical operations more precise in Ruby
-# and to integrate other mathematical standard libraries.
-#
-# Without mathn:
-#
-# 3 / 2 => 1 # Integer
-#
-# With mathn:
-#
-# 3 / 2 => 3/2 # Rational
-#
-# mathn keeps value in exact terms.
-#
-# Without mathn:
-#
-# 20 / 9 * 3 * 14 / 7 * 3 / 2 # => 18
-#
-# With mathn:
-#
-# 20 / 9 * 3 * 14 / 7 * 3 / 2 # => 20
-#
-#
-# When you require 'mathn', the libraries for Prime, CMath, Matrix and Vector
-# are also loaded.
-#
-# == Copyright
-#
-# Author: Keiju ISHITSUKA (SHL Japan Inc.)
-#--
-# class Numeric follows to make this documentation findable in a reasonable
-# location
-
-warn('lib/mathn.rb is deprecated') if $VERBOSE
-
-class Numeric; end
-
-require "cmath.rb"
-require "matrix.rb"
-require "prime.rb"
-
-require "mathn/rational"
-require "mathn/complex"
-
-unless defined?(Math.exp!)
- Object.instance_eval{remove_const :Math}
- Math = CMath # :nodoc:
-end
-
-##
-# When mathn is required, Fixnum's division is enhanced to
-# return more precise values from mathematical expressions.
-#
-# 2/3*3 # => 0
-# require 'mathn'
-# 2/3*3 # => 2
-
-class Fixnum
- remove_method :/
-
- ##
- # +/+ defines the Rational division for Fixnum.
- #
- # 1/3 # => (1/3)
-
- alias / quo
-end
-
-##
-# When mathn is required Bignum's division is enhanced to
-# return more precise values from mathematical expressions.
-#
-# (2**72) / ((2**70) * 3) # => 4/3
-
-class Bignum
- remove_method :/
-
- ##
- # +/+ defines the Rational division for Bignum.
- #
- # (2**72) / ((2**70) * 3) # => 4/3
-
- alias / quo
-end
-
-##
-# When mathn is required, the Math module changes as follows:
-#
-# Standard Math module behaviour:
-# Math.sqrt(4/9) # => 0.0
-# Math.sqrt(4.0/9.0) # => 0.666666666666667
-# Math.sqrt(- 4/9) # => Errno::EDOM: Numerical argument out of domain - sqrt
-#
-# After require 'mathn', this is changed to:
-#
-# require 'mathn'
-# Math.sqrt(4/9) # => 2/3
-# Math.sqrt(4.0/9.0) # => 0.666666666666667
-# Math.sqrt(- 4/9) # => Complex(0, 2/3)
-
-module Math
- remove_method(:sqrt)
-
- ##
- # Computes the square root of +a+. It makes use of Complex and
- # Rational to have no rounding errors if possible.
- #
- # Math.sqrt(4/9) # => 2/3
- # Math.sqrt(- 4/9) # => Complex(0, 2/3)
- # Math.sqrt(4.0/9.0) # => 0.666666666666667
-
- def sqrt(a)
- if a.kind_of?(Complex)
- abs = sqrt(a.real*a.real + a.imag*a.imag)
- x = sqrt((a.real + abs)/Rational(2))
- y = sqrt((-a.real + abs)/Rational(2))
- if a.imag >= 0
- Complex(x, y)
- else
- Complex(x, -y)
- end
- elsif a.respond_to?(:nan?) and a.nan?
- a
- elsif a >= 0
- rsqrt(a)
- else
- Complex(0,rsqrt(-a))
- end
- end
-
- ##
- # Compute square root of a non negative number. This method is
- # internally used by +Math.sqrt+.
-
- def rsqrt(a)
- if a.kind_of?(Float)
- sqrt!(a)
- elsif a.kind_of?(Rational)
- rsqrt(a.numerator)/rsqrt(a.denominator)
- else
- src = a
- max = 2 ** 32
- byte_a = [src & 0xffffffff]
- # ruby's bug
- while (src >= max) and (src >>= 32)
- byte_a.unshift src & 0xffffffff
- end
-
- answer = 0
- main = 0
- side = 0
- for elm in byte_a
- main = (main << 32) + elm
- side <<= 16
- if answer != 0
- if main * 4 < side * side
- applo = main.div(side)
- else
- applo = ((sqrt!(side * side + 4 * main) - side)/2.0).to_i + 1
- end
- else
- applo = sqrt!(main).to_i + 1
- end
-
- while (x = (side + applo) * applo) > main
- applo -= 1
- end
- main -= x
- answer = (answer << 16) + applo
- side += applo * 2
- end
- if main == 0
- answer
- else
- sqrt!(a)
- end
- end
- end
-
- class << self
- remove_method(:sqrt)
- end
- module_function :sqrt
- module_function :rsqrt
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/matrix.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/matrix.rb
deleted file mode 100755
index fb98d0932..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/matrix.rb
+++ /dev/null
@@ -1,2161 +0,0 @@
-# encoding: utf-8
-#
-# = matrix.rb
-#
-# An implementation of Matrix and Vector classes.
-#
-# See classes Matrix and Vector for documentation.
-#
-# Current Maintainer:: Marc-André Lafortune
-# Original Author:: Keiju ISHITSUKA
-# Original Documentation:: Gavin Sinclair (sourced from Ruby in a Nutshell (Matsumoto, O'Reilly))
-##
-
-require "e2mmap.rb"
-
-module ExceptionForMatrix # :nodoc:
- extend Exception2MessageMapper
- def_e2message(TypeError, "wrong argument type %s (expected %s)")
- def_e2message(ArgumentError, "Wrong # of arguments(%d for %d)")
-
- def_exception("ErrDimensionMismatch", "\#{self.name} dimension mismatch")
- def_exception("ErrNotRegular", "Not Regular Matrix")
- def_exception("ErrOperationNotDefined", "Operation(%s) can\\'t be defined: %s op %s")
- def_exception("ErrOperationNotImplemented", "Sorry, Operation(%s) not implemented: %s op %s")
-end
-
-#
-# The +Matrix+ class represents a mathematical matrix. It provides methods for creating
-# matrices, operating on them arithmetically and algebraically,
-# and determining their mathematical properties (trace, rank, inverse, determinant).
-#
-# == Method Catalogue
-#
-# To create a matrix:
-# * Matrix[*rows]
-# * Matrix.[](*rows)
-# * Matrix.rows(rows, copy = true)
-# * Matrix.columns(columns)
-# * Matrix.build(row_count, column_count, &block)
-# * Matrix.diagonal(*values)
-# * Matrix.scalar(n, value)
-# * Matrix.identity(n)
-# * Matrix.unit(n)
-# * Matrix.I(n)
-# * Matrix.zero(n)
-# * Matrix.row_vector(row)
-# * Matrix.column_vector(column)
-# * Matrix.hstack(*matrices)
-# * Matrix.vstack(*matrices)
-#
-# To access Matrix elements/columns/rows/submatrices/properties:
-# * #[](i, j)
-# * #row_count (row_size)
-# * #column_count (column_size)
-# * #row(i)
-# * #column(j)
-# * #collect
-# * #map
-# * #each
-# * #each_with_index
-# * #find_index
-# * #minor(*param)
-# * #first_minor(row, column)
-# * #cofactor(row, column)
-# * #adjugate
-# * #laplace_expansion(row_or_column: num)
-# * #cofactor_expansion(row_or_column: num)
-#
-# Properties of a matrix:
-# * #diagonal?
-# * #empty?
-# * #hermitian?
-# * #lower_triangular?
-# * #normal?
-# * #orthogonal?
-# * #permutation?
-# * #real?
-# * #regular?
-# * #singular?
-# * #square?
-# * #symmetric?
-# * #unitary?
-# * #upper_triangular?
-# * #zero?
-#
-# Matrix arithmetic:
-# * #*(m)
-# * #+(m)
-# * #-(m)
-# * #/(m)
-# * #inverse
-# * #inv
-# * #**
-# * #+@
-# * #-@
-#
-# Matrix functions:
-# * #determinant
-# * #det
-# * #hstack(*matrices)
-# * #rank
-# * #round
-# * #trace
-# * #tr
-# * #transpose
-# * #t
-# * #vstack(*matrices)
-#
-# Matrix decompositions:
-# * #eigen
-# * #eigensystem
-# * #lup
-# * #lup_decomposition
-#
-# Complex arithmetic:
-# * conj
-# * conjugate
-# * imag
-# * imaginary
-# * real
-# * rect
-# * rectangular
-#
-# Conversion to other data types:
-# * #coerce(other)
-# * #row_vectors
-# * #column_vectors
-# * #to_a
-#
-# String representations:
-# * #to_s
-# * #inspect
-#
-class Matrix
- include Enumerable
- include ExceptionForMatrix
- autoload :EigenvalueDecomposition, "matrix/eigenvalue_decomposition"
- autoload :LUPDecomposition, "matrix/lup_decomposition"
-
- # instance creations
- private_class_method :new
- attr_reader :rows
- protected :rows
-
- #
- # Creates a matrix where each argument is a row.
- # Matrix[ [25, 93], [-1, 66] ]
- # => 25 93
- # -1 66
- #
- def Matrix.[](*rows)
- rows(rows, false)
- end
-
- #
- # Creates a matrix where +rows+ is an array of arrays, each of which is a row
- # of the matrix. If the optional argument +copy+ is false, use the given
- # arrays as the internal structure of the matrix without copying.
- # Matrix.rows([[25, 93], [-1, 66]])
- # => 25 93
- # -1 66
- #
- def Matrix.rows(rows, copy = true)
- rows = convert_to_array(rows, copy)
- rows.map! do |row|
- convert_to_array(row, copy)
- end
- size = (rows[0] || []).size
- rows.each do |row|
- raise ErrDimensionMismatch, "row size differs (#{row.size} should be #{size})" unless row.size == size
- end
- new rows, size
- end
-
- #
- # Creates a matrix using +columns+ as an array of column vectors.
- # Matrix.columns([[25, 93], [-1, 66]])
- # => 25 -1
- # 93 66
- #
- def Matrix.columns(columns)
- rows(columns, false).transpose
- end
-
- #
- # Creates a matrix of size +row_count+ x +column_count+.
- # It fills the values by calling the given block,
- # passing the current row and column.
- # Returns an enumerator if no block is given.
- #
- # m = Matrix.build(2, 4) {|row, col| col - row }
- # => Matrix[[0, 1, 2, 3], [-1, 0, 1, 2]]
- # m = Matrix.build(3) { rand }
- # => a 3x3 matrix with random elements
- #
- def Matrix.build(row_count, column_count = row_count)
- row_count = CoercionHelper.coerce_to_int(row_count)
- column_count = CoercionHelper.coerce_to_int(column_count)
- raise ArgumentError if row_count < 0 || column_count < 0
- return to_enum :build, row_count, column_count unless block_given?
- rows = Array.new(row_count) do |i|
- Array.new(column_count) do |j|
- yield i, j
- end
- end
- new rows, column_count
- end
-
- #
- # Creates a matrix where the diagonal elements are composed of +values+.
- # Matrix.diagonal(9, 5, -3)
- # => 9 0 0
- # 0 5 0
- # 0 0 -3
- #
- def Matrix.diagonal(*values)
- size = values.size
- return Matrix.empty if size == 0
- rows = Array.new(size) {|j|
- row = Array.new(size, 0)
- row[j] = values[j]
- row
- }
- new rows
- end
-
- #
- # Creates an +n+ by +n+ diagonal matrix where each diagonal element is
- # +value+.
- # Matrix.scalar(2, 5)
- # => 5 0
- # 0 5
- #
- def Matrix.scalar(n, value)
- diagonal(*Array.new(n, value))
- end
-
- #
- # Creates an +n+ by +n+ identity matrix.
- # Matrix.identity(2)
- # => 1 0
- # 0 1
- #
- def Matrix.identity(n)
- scalar(n, 1)
- end
- class << Matrix
- alias unit identity
- alias I identity
- end
-
- #
- # Creates a zero matrix.
- # Matrix.zero(2)
- # => 0 0
- # 0 0
- #
- def Matrix.zero(row_count, column_count = row_count)
- rows = Array.new(row_count){Array.new(column_count, 0)}
- new rows, column_count
- end
-
- #
- # Creates a single-row matrix where the values of that row are as given in
- # +row+.
- # Matrix.row_vector([4,5,6])
- # => 4 5 6
- #
- def Matrix.row_vector(row)
- row = convert_to_array(row)
- new [row]
- end
-
- #
- # Creates a single-column matrix where the values of that column are as given
- # in +column+.
- # Matrix.column_vector([4,5,6])
- # => 4
- # 5
- # 6
- #
- def Matrix.column_vector(column)
- column = convert_to_array(column)
- new [column].transpose, 1
- end
-
- #
- # Creates a empty matrix of +row_count+ x +column_count+.
- # At least one of +row_count+ or +column_count+ must be 0.
- #
- # m = Matrix.empty(2, 0)
- # m == Matrix[ [], [] ]
- # => true
- # n = Matrix.empty(0, 3)
- # n == Matrix.columns([ [], [], [] ])
- # => true
- # m * n
- # => Matrix[[0, 0, 0], [0, 0, 0]]
- #
- def Matrix.empty(row_count = 0, column_count = 0)
- raise ArgumentError, "One size must be 0" if column_count != 0 && row_count != 0
- raise ArgumentError, "Negative size" if column_count < 0 || row_count < 0
-
- new([[]]*row_count, column_count)
- end
-
- #
- # Create a matrix by stacking matrices vertically
- #
- # x = Matrix[[1, 2], [3, 4]]
- # y = Matrix[[5, 6], [7, 8]]
- # Matrix.vstack(x, y) # => Matrix[[1, 2], [3, 4], [5, 6], [7, 8]]
- #
- def Matrix.vstack(x, *matrices)
- raise TypeError, "Expected a Matrix, got a #{x.class}" unless x.is_a?(Matrix)
- result = x.send(:rows).map(&:dup)
- matrices.each do |m|
- raise TypeError, "Expected a Matrix, got a #{m.class}" unless m.is_a?(Matrix)
- if m.column_count != x.column_count
- raise ErrDimensionMismatch, "The given matrices must have #{x.column_count} columns, but one has #{m.column_count}"
- end
- result.concat(m.send(:rows))
- end
- new result, x.column_count
- end
-
-
- #
- # Create a matrix by stacking matrices horizontally
- #
- # x = Matrix[[1, 2], [3, 4]]
- # y = Matrix[[5, 6], [7, 8]]
- # Matrix.hstack(x, y) # => Matrix[[1, 2, 5, 6], [3, 4, 7, 8]]
- #
- def Matrix.hstack(x, *matrices)
- raise TypeError, "Expected a Matrix, got a #{x.class}" unless x.is_a?(Matrix)
- result = x.send(:rows).map(&:dup)
- total_column_count = x.column_count
- matrices.each do |m|
- raise TypeError, "Expected a Matrix, got a #{m.class}" unless m.is_a?(Matrix)
- if m.row_count != x.row_count
- raise ErrDimensionMismatch, "The given matrices must have #{x.row_count} rows, but one has #{m.row_count}"
- end
- result.each_with_index do |row, i|
- row.concat m.send(:rows)[i]
- end
- total_column_count += m.column_count
- end
- new result, total_column_count
- end
-
- #
- # Matrix.new is private; use Matrix.rows, columns, [], etc... to create.
- #
- def initialize(rows, column_count = rows[0].size)
- # No checking is done at this point. rows must be an Array of Arrays.
- # column_count must be the size of the first row, if there is one,
- # otherwise it *must* be specified and can be any integer >= 0
- @rows = rows
- @column_count = column_count
- end
-
- def new_matrix(rows, column_count = rows[0].size) # :nodoc:
- self.class.send(:new, rows, column_count) # bypass privacy of Matrix.new
- end
- private :new_matrix
-
- #
- # Returns element (+i+,+j+) of the matrix. That is: row +i+, column +j+.
- #
- def [](i, j)
- @rows.fetch(i){return nil}[j]
- end
- alias element []
- alias component []
-
- def []=(i, j, v)
- @rows[i][j] = v
- end
- alias set_element []=
- alias set_component []=
- private :[]=, :set_element, :set_component
-
- #
- # Returns the number of rows.
- #
- def row_count
- @rows.size
- end
-
- alias_method :row_size, :row_count
- #
- # Returns the number of columns.
- #
- attr_reader :column_count
- alias_method :column_size, :column_count
-
- #
- # Returns row vector number +i+ of the matrix as a Vector (starting at 0 like
- # an array). When a block is given, the elements of that vector are iterated.
- #
- def row(i, &block) # :yield: e
- if block_given?
- @rows.fetch(i){return self}.each(&block)
- self
- else
- Vector.elements(@rows.fetch(i){return nil})
- end
- end
-
- #
- # Returns column vector number +j+ of the matrix as a Vector (starting at 0
- # like an array). When a block is given, the elements of that vector are
- # iterated.
- #
- def column(j) # :yield: e
- if block_given?
- return self if j >= column_count || j < -column_count
- row_count.times do |i|
- yield @rows[i][j]
- end
- self
- else
- return nil if j >= column_count || j < -column_count
- col = Array.new(row_count) {|i|
- @rows[i][j]
- }
- Vector.elements(col, false)
- end
- end
-
- #
- # Returns a matrix that is the result of iteration of the given block over all
- # elements of the matrix.
- # Matrix[ [1,2], [3,4] ].collect { |e| e**2 }
- # => 1 4
- # 9 16
- #
- def collect(&block) # :yield: e
- return to_enum(:collect) unless block_given?
- rows = @rows.collect{|row| row.collect(&block)}
- new_matrix rows, column_count
- end
- alias map collect
-
- #
- # Yields all elements of the matrix, starting with those of the first row,
- # or returns an Enumerator if no block given.
- # Elements can be restricted by passing an argument:
- # * :all (default): yields all elements
- # * :diagonal: yields only elements on the diagonal
- # * :off_diagonal: yields all elements except on the diagonal
- # * :lower: yields only elements on or below the diagonal
- # * :strict_lower: yields only elements below the diagonal
- # * :strict_upper: yields only elements above the diagonal
- # * :upper: yields only elements on or above the diagonal
- #
- # Matrix[ [1,2], [3,4] ].each { |e| puts e }
- # # => prints the numbers 1 to 4
- # Matrix[ [1,2], [3,4] ].each(:strict_lower).to_a # => [3]
- #
- def each(which = :all) # :yield: e
- return to_enum :each, which unless block_given?
- last = column_count - 1
- case which
- when :all
- block = Proc.new
- @rows.each do |row|
- row.each(&block)
- end
- when :diagonal
- @rows.each_with_index do |row, row_index|
- yield row.fetch(row_index){return self}
- end
- when :off_diagonal
- @rows.each_with_index do |row, row_index|
- column_count.times do |col_index|
- yield row[col_index] unless row_index == col_index
- end
- end
- when :lower
- @rows.each_with_index do |row, row_index|
- 0.upto([row_index, last].min) do |col_index|
- yield row[col_index]
- end
- end
- when :strict_lower
- @rows.each_with_index do |row, row_index|
- [row_index, column_count].min.times do |col_index|
- yield row[col_index]
- end
- end
- when :strict_upper
- @rows.each_with_index do |row, row_index|
- (row_index+1).upto(last) do |col_index|
- yield row[col_index]
- end
- end
- when :upper
- @rows.each_with_index do |row, row_index|
- row_index.upto(last) do |col_index|
- yield row[col_index]
- end
- end
- else
- raise ArgumentError, "expected #{which.inspect} to be one of :all, :diagonal, :off_diagonal, :lower, :strict_lower, :strict_upper or :upper"
- end
- self
- end
-
- #
- # Same as #each, but the row index and column index in addition to the element
- #
- # Matrix[ [1,2], [3,4] ].each_with_index do |e, row, col|
- # puts "#{e} at #{row}, #{col}"
- # end
- # # => Prints:
- # # 1 at 0, 0
- # # 2 at 0, 1
- # # 3 at 1, 0
- # # 4 at 1, 1
- #
- def each_with_index(which = :all) # :yield: e, row, column
- return to_enum :each_with_index, which unless block_given?
- last = column_count - 1
- case which
- when :all
- @rows.each_with_index do |row, row_index|
- row.each_with_index do |e, col_index|
- yield e, row_index, col_index
- end
- end
- when :diagonal
- @rows.each_with_index do |row, row_index|
- yield row.fetch(row_index){return self}, row_index, row_index
- end
- when :off_diagonal
- @rows.each_with_index do |row, row_index|
- column_count.times do |col_index|
- yield row[col_index], row_index, col_index unless row_index == col_index
- end
- end
- when :lower
- @rows.each_with_index do |row, row_index|
- 0.upto([row_index, last].min) do |col_index|
- yield row[col_index], row_index, col_index
- end
- end
- when :strict_lower
- @rows.each_with_index do |row, row_index|
- [row_index, column_count].min.times do |col_index|
- yield row[col_index], row_index, col_index
- end
- end
- when :strict_upper
- @rows.each_with_index do |row, row_index|
- (row_index+1).upto(last) do |col_index|
- yield row[col_index], row_index, col_index
- end
- end
- when :upper
- @rows.each_with_index do |row, row_index|
- row_index.upto(last) do |col_index|
- yield row[col_index], row_index, col_index
- end
- end
- else
- raise ArgumentError, "expected #{which.inspect} to be one of :all, :diagonal, :off_diagonal, :lower, :strict_lower, :strict_upper or :upper"
- end
- self
- end
-
- SELECTORS = {all: true, diagonal: true, off_diagonal: true, lower: true, strict_lower: true, strict_upper: true, upper: true}.freeze
- #
- # :call-seq:
- # index(value, selector = :all) -> [row, column]
- # index(selector = :all){ block } -> [row, column]
- # index(selector = :all) -> an_enumerator
- #
- # The index method is specialized to return the index as [row, column]
- # It also accepts an optional +selector+ argument, see #each for details.
- #
- # Matrix[ [1,2], [3,4] ].index(&:even?) # => [0, 1]
- # Matrix[ [1,1], [1,1] ].index(1, :strict_lower) # => [1, 0]
- #
- def index(*args)
- raise ArgumentError, "wrong number of arguments(#{args.size} for 0-2)" if args.size > 2
- which = (args.size == 2 || SELECTORS.include?(args.last)) ? args.pop : :all
- return to_enum :find_index, which, *args unless block_given? || args.size == 1
- if args.size == 1
- value = args.first
- each_with_index(which) do |e, row_index, col_index|
- return row_index, col_index if e == value
- end
- else
- each_with_index(which) do |e, row_index, col_index|
- return row_index, col_index if yield e
- end
- end
- nil
- end
- alias_method :find_index, :index
-
- #
- # Returns a section of the matrix. The parameters are either:
- # * start_row, nrows, start_col, ncols; OR
- # * row_range, col_range
- #
- # Matrix.diagonal(9, 5, -3).minor(0..1, 0..2)
- # => 9 0 0
- # 0 5 0
- #
- # Like Array#[], negative indices count backward from the end of the
- # row or column (-1 is the last element). Returns nil if the starting
- # row or column is greater than row_count or column_count respectively.
- #
- def minor(*param)
- case param.size
- when 2
- row_range, col_range = param
- from_row = row_range.first
- from_row += row_count if from_row < 0
- to_row = row_range.end
- to_row += row_count if to_row < 0
- to_row += 1 unless row_range.exclude_end?
- size_row = to_row - from_row
-
- from_col = col_range.first
- from_col += column_count if from_col < 0
- to_col = col_range.end
- to_col += column_count if to_col < 0
- to_col += 1 unless col_range.exclude_end?
- size_col = to_col - from_col
- when 4
- from_row, size_row, from_col, size_col = param
- return nil if size_row < 0 || size_col < 0
- from_row += row_count if from_row < 0
- from_col += column_count if from_col < 0
- else
- raise ArgumentError, param.inspect
- end
-
- return nil if from_row > row_count || from_col > column_count || from_row < 0 || from_col < 0
- rows = @rows[from_row, size_row].collect{|row|
- row[from_col, size_col]
- }
- new_matrix rows, [column_count - from_col, size_col].min
- end
-
- #
- # Returns the submatrix obtained by deleting the specified row and column.
- #
- # Matrix.diagonal(9, 5, -3, 4).first_minor(1, 2)
- # => 9 0 0
- # 0 0 0
- # 0 0 4
- #
- def first_minor(row, column)
- raise RuntimeError, "first_minor of empty matrix is not defined" if empty?
-
- unless 0 <= row && row < row_count
- raise ArgumentError, "invalid row (#{row.inspect} for 0..#{row_count - 1})"
- end
-
- unless 0 <= column && column < column_count
- raise ArgumentError, "invalid column (#{column.inspect} for 0..#{column_count - 1})"
- end
-
- arrays = to_a
- arrays.delete_at(row)
- arrays.each do |array|
- array.delete_at(column)
- end
-
- new_matrix arrays, column_count - 1
- end
-
- #
- # Returns the (row, column) cofactor which is obtained by multiplying
- # the first minor by (-1)**(row + column).
- #
- # Matrix.diagonal(9, 5, -3, 4).cofactor(1, 1)
- # => -108
- #
- def cofactor(row, column)
- raise RuntimeError, "cofactor of empty matrix is not defined" if empty?
- Matrix.Raise ErrDimensionMismatch unless square?
-
- det_of_minor = first_minor(row, column).determinant
- det_of_minor * (-1) ** (row + column)
- end
-
- #
- # Returns the adjugate of the matrix.
- #
- # Matrix[ [7,6],[3,9] ].adjugate
- # => 9 -6
- # -3 7
- #
- def adjugate
- Matrix.Raise ErrDimensionMismatch unless square?
- Matrix.build(row_count, column_count) do |row, column|
- cofactor(column, row)
- end
- end
-
- #
- # Returns the Laplace expansion along given row or column.
- #
- # Matrix[[7,6], [3,9]].laplace_expansion(column: 1)
- # => 45
- #
- # Matrix[[Vector[1, 0], Vector[0, 1]], [2, 3]].laplace_expansion(row: 0)
- # => Vector[3, -2]
- #
- #
- def laplace_expansion(row: nil, column: nil)
- num = row || column
-
- if !num || (row && column)
- raise ArgumentError, "exactly one the row or column arguments must be specified"
- end
-
- Matrix.Raise ErrDimensionMismatch unless square?
- raise RuntimeError, "laplace_expansion of empty matrix is not defined" if empty?
-
- unless 0 <= num && num < row_count
- raise ArgumentError, "invalid num (#{num.inspect} for 0..#{row_count - 1})"
- end
-
- send(row ? :row : :column, num).map.with_index { |e, k|
- e * cofactor(*(row ? [num, k] : [k,num]))
- }.inject(:+)
- end
- alias_method :cofactor_expansion, :laplace_expansion
-
-
- #--
- # TESTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- #++
-
- #
- # Returns +true+ if this is a diagonal matrix.
- # Raises an error if matrix is not square.
- #
- def diagonal?
- Matrix.Raise ErrDimensionMismatch unless square?
- each(:off_diagonal).all?(&:zero?)
- end
-
- #
- # Returns +true+ if this is an empty matrix, i.e. if the number of rows
- # or the number of columns is 0.
- #
- def empty?
- column_count == 0 || row_count == 0
- end
-
- #
- # Returns +true+ if this is an hermitian matrix.
- # Raises an error if matrix is not square.
- #
- def hermitian?
- Matrix.Raise ErrDimensionMismatch unless square?
- each_with_index(:upper).all? do |e, row, col|
- e == rows[col][row].conj
- end
- end
-
- #
- # Returns +true+ if this is a lower triangular matrix.
- #
- def lower_triangular?
- each(:strict_upper).all?(&:zero?)
- end
-
- #
- # Returns +true+ if this is a normal matrix.
- # Raises an error if matrix is not square.
- #
- def normal?
- Matrix.Raise ErrDimensionMismatch unless square?
- rows.each_with_index do |row_i, i|
- rows.each_with_index do |row_j, j|
- s = 0
- rows.each_with_index do |row_k, k|
- s += row_i[k] * row_j[k].conj - row_k[i].conj * row_k[j]
- end
- return false unless s == 0
- end
- end
- true
- end
-
- #
- # Returns +true+ if this is an orthogonal matrix
- # Raises an error if matrix is not square.
- #
- def orthogonal?
- Matrix.Raise ErrDimensionMismatch unless square?
- rows.each_with_index do |row, i|
- column_count.times do |j|
- s = 0
- row_count.times do |k|
- s += row[k] * rows[k][j]
- end
- return false unless s == (i == j ? 1 : 0)
- end
- end
- true
- end
-
- #
- # Returns +true+ if this is a permutation matrix
- # Raises an error if matrix is not square.
- #
- def permutation?
- Matrix.Raise ErrDimensionMismatch unless square?
- cols = Array.new(column_count)
- rows.each_with_index do |row, i|
- found = false
- row.each_with_index do |e, j|
- if e == 1
- return false if found || cols[j]
- found = cols[j] = true
- elsif e != 0
- return false
- end
- end
- return false unless found
- end
- true
- end
-
- #
- # Returns +true+ if all entries of the matrix are real.
- #
- def real?
- all?(&:real?)
- end
-
- #
- # Returns +true+ if this is a regular (i.e. non-singular) matrix.
- #
- def regular?
- not singular?
- end
-
- #
- # Returns +true+ if this is a singular matrix.
- #
- def singular?
- determinant == 0
- end
-
- #
- # Returns +true+ if this is a square matrix.
- #
- def square?
- column_count == row_count
- end
-
- #
- # Returns +true+ if this is a symmetric matrix.
- # Raises an error if matrix is not square.
- #
- def symmetric?
- Matrix.Raise ErrDimensionMismatch unless square?
- each_with_index(:strict_upper) do |e, row, col|
- return false if e != rows[col][row]
- end
- true
- end
-
- #
- # Returns +true+ if this is a unitary matrix
- # Raises an error if matrix is not square.
- #
- def unitary?
- Matrix.Raise ErrDimensionMismatch unless square?
- rows.each_with_index do |row, i|
- column_count.times do |j|
- s = 0
- row_count.times do |k|
- s += row[k].conj * rows[k][j]
- end
- return false unless s == (i == j ? 1 : 0)
- end
- end
- true
- end
-
- #
- # Returns +true+ if this is an upper triangular matrix.
- #
- def upper_triangular?
- each(:strict_lower).all?(&:zero?)
- end
-
- #
- # Returns +true+ if this is a matrix with only zero elements
- #
- def zero?
- all?(&:zero?)
- end
-
- #--
- # OBJECT METHODS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- #++
-
- #
- # Returns +true+ if and only if the two matrices contain equal elements.
- #
- def ==(other)
- return false unless Matrix === other &&
- column_count == other.column_count # necessary for empty matrices
- rows == other.rows
- end
-
- def eql?(other)
- return false unless Matrix === other &&
- column_count == other.column_count # necessary for empty matrices
- rows.eql? other.rows
- end
-
- #
- # Returns a clone of the matrix, so that the contents of each do not reference
- # identical objects.
- # There should be no good reason to do this since Matrices are immutable.
- #
- def clone
- new_matrix @rows.map(&:dup), column_count
- end
-
- #
- # Returns a hash-code for the matrix.
- #
- def hash
- @rows.hash
- end
-
- #--
- # ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- #++
-
- #
- # Matrix multiplication.
- # Matrix[[2,4], [6,8]] * Matrix.identity(2)
- # => 2 4
- # 6 8
- #
- def *(m) # m is matrix or vector or number
- case(m)
- when Numeric
- rows = @rows.collect {|row|
- row.collect {|e| e * m }
- }
- return new_matrix rows, column_count
- when Vector
- m = self.class.column_vector(m)
- r = self * m
- return r.column(0)
- when Matrix
- Matrix.Raise ErrDimensionMismatch if column_count != m.row_count
-
- rows = Array.new(row_count) {|i|
- Array.new(m.column_count) {|j|
- (0 ... column_count).inject(0) do |vij, k|
- vij + self[i, k] * m[k, j]
- end
- }
- }
- return new_matrix rows, m.column_count
- else
- return apply_through_coercion(m, __method__)
- end
- end
-
- #
- # Matrix addition.
- # Matrix.scalar(2,5) + Matrix[[1,0], [-4,7]]
- # => 6 0
- # -4 12
- #
- def +(m)
- case m
- when Numeric
- Matrix.Raise ErrOperationNotDefined, "+", self.class, m.class
- when Vector
- m = self.class.column_vector(m)
- when Matrix
- else
- return apply_through_coercion(m, __method__)
- end
-
- Matrix.Raise ErrDimensionMismatch unless row_count == m.row_count && column_count == m.column_count
-
- rows = Array.new(row_count) {|i|
- Array.new(column_count) {|j|
- self[i, j] + m[i, j]
- }
- }
- new_matrix rows, column_count
- end
-
- #
- # Matrix subtraction.
- # Matrix[[1,5], [4,2]] - Matrix[[9,3], [-4,1]]
- # => -8 2
- # 8 1
- #
- def -(m)
- case m
- when Numeric
- Matrix.Raise ErrOperationNotDefined, "-", self.class, m.class
- when Vector
- m = self.class.column_vector(m)
- when Matrix
- else
- return apply_through_coercion(m, __method__)
- end
-
- Matrix.Raise ErrDimensionMismatch unless row_count == m.row_count && column_count == m.column_count
-
- rows = Array.new(row_count) {|i|
- Array.new(column_count) {|j|
- self[i, j] - m[i, j]
- }
- }
- new_matrix rows, column_count
- end
-
- #
- # Matrix division (multiplication by the inverse).
- # Matrix[[7,6], [3,9]] / Matrix[[2,9], [3,1]]
- # => -7 1
- # -3 -6
- #
- def /(other)
- case other
- when Numeric
- rows = @rows.collect {|row|
- row.collect {|e| e / other }
- }
- return new_matrix rows, column_count
- when Matrix
- return self * other.inverse
- else
- return apply_through_coercion(other, __method__)
- end
- end
-
- #
- # Returns the inverse of the matrix.
- # Matrix[[-1, -1], [0, -1]].inverse
- # => -1 1
- # 0 -1
- #
- def inverse
- Matrix.Raise ErrDimensionMismatch unless square?
- self.class.I(row_count).send(:inverse_from, self)
- end
- alias inv inverse
-
- def inverse_from(src) # :nodoc:
- last = row_count - 1
- a = src.to_a
-
- 0.upto(last) do |k|
- i = k
- akk = a[k][k].abs
- (k+1).upto(last) do |j|
- v = a[j][k].abs
- if v > akk
- i = j
- akk = v
- end
- end
- Matrix.Raise ErrNotRegular if akk == 0
- if i != k
- a[i], a[k] = a[k], a[i]
- @rows[i], @rows[k] = @rows[k], @rows[i]
- end
- akk = a[k][k]
-
- 0.upto(last) do |ii|
- next if ii == k
- q = a[ii][k].quo(akk)
- a[ii][k] = 0
-
- (k + 1).upto(last) do |j|
- a[ii][j] -= a[k][j] * q
- end
- 0.upto(last) do |j|
- @rows[ii][j] -= @rows[k][j] * q
- end
- end
-
- (k+1).upto(last) do |j|
- a[k][j] = a[k][j].quo(akk)
- end
- 0.upto(last) do |j|
- @rows[k][j] = @rows[k][j].quo(akk)
- end
- end
- self
- end
- private :inverse_from
-
- #
- # Matrix exponentiation.
- # Equivalent to multiplying the matrix by itself N times.
- # Non integer exponents will be handled by diagonalizing the matrix.
- #
- # Matrix[[7,6], [3,9]] ** 2
- # => 67 96
- # 48 99
- #
- def ** (other)
- case other
- when Integer
- x = self
- if other <= 0
- x = self.inverse
- return self.class.identity(self.column_count) if other == 0
- other = -other
- end
- z = nil
- loop do
- z = z ? z * x : x if other[0] == 1
- return z if (other >>= 1).zero?
- x *= x
- end
- when Numeric
- v, d, v_inv = eigensystem
- v * self.class.diagonal(*d.each(:diagonal).map{|e| e ** other}) * v_inv
- else
- Matrix.Raise ErrOperationNotDefined, "**", self.class, other.class
- end
- end
-
- def +@
- self
- end
-
- def -@
- collect {|e| -e }
- end
-
- #--
- # MATRIX FUNCTIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- #++
-
- #
- # Returns the determinant of the matrix.
- #
- # Beware that using Float values can yield erroneous results
- # because of their lack of precision.
- # Consider using exact types like Rational or BigDecimal instead.
- #
- # Matrix[[7,6], [3,9]].determinant
- # => 45
- #
- def determinant
- Matrix.Raise ErrDimensionMismatch unless square?
- m = @rows
- case row_count
- # Up to 4x4, give result using Laplacian expansion by minors.
- # This will typically be faster, as well as giving good results
- # in case of Floats
- when 0
- +1
- when 1
- + m[0][0]
- when 2
- + m[0][0] * m[1][1] - m[0][1] * m[1][0]
- when 3
- m0, m1, m2 = m
- + m0[0] * m1[1] * m2[2] - m0[0] * m1[2] * m2[1] \
- - m0[1] * m1[0] * m2[2] + m0[1] * m1[2] * m2[0] \
- + m0[2] * m1[0] * m2[1] - m0[2] * m1[1] * m2[0]
- when 4
- m0, m1, m2, m3 = m
- + m0[0] * m1[1] * m2[2] * m3[3] - m0[0] * m1[1] * m2[3] * m3[2] \
- - m0[0] * m1[2] * m2[1] * m3[3] + m0[0] * m1[2] * m2[3] * m3[1] \
- + m0[0] * m1[3] * m2[1] * m3[2] - m0[0] * m1[3] * m2[2] * m3[1] \
- - m0[1] * m1[0] * m2[2] * m3[3] + m0[1] * m1[0] * m2[3] * m3[2] \
- + m0[1] * m1[2] * m2[0] * m3[3] - m0[1] * m1[2] * m2[3] * m3[0] \
- - m0[1] * m1[3] * m2[0] * m3[2] + m0[1] * m1[3] * m2[2] * m3[0] \
- + m0[2] * m1[0] * m2[1] * m3[3] - m0[2] * m1[0] * m2[3] * m3[1] \
- - m0[2] * m1[1] * m2[0] * m3[3] + m0[2] * m1[1] * m2[3] * m3[0] \
- + m0[2] * m1[3] * m2[0] * m3[1] - m0[2] * m1[3] * m2[1] * m3[0] \
- - m0[3] * m1[0] * m2[1] * m3[2] + m0[3] * m1[0] * m2[2] * m3[1] \
- + m0[3] * m1[1] * m2[0] * m3[2] - m0[3] * m1[1] * m2[2] * m3[0] \
- - m0[3] * m1[2] * m2[0] * m3[1] + m0[3] * m1[2] * m2[1] * m3[0]
- else
- # For bigger matrices, use an efficient and general algorithm.
- # Currently, we use the Gauss-Bareiss algorithm
- determinant_bareiss
- end
- end
- alias_method :det, :determinant
-
- #
- # Private. Use Matrix#determinant
- #
- # Returns the determinant of the matrix, using
- # Bareiss' multistep integer-preserving gaussian elimination.
- # It has the same computational cost order O(n^3) as standard Gaussian elimination.
- # Intermediate results are fraction free and of lower complexity.
- # A matrix of Integers will have thus intermediate results that are also Integers,
- # with smaller bignums (if any), while a matrix of Float will usually have
- # intermediate results with better precision.
- #
- def determinant_bareiss
- size = row_count
- last = size - 1
- a = to_a
- no_pivot = Proc.new{ return 0 }
- sign = +1
- pivot = 1
- size.times do |k|
- previous_pivot = pivot
- if (pivot = a[k][k]) == 0
- switch = (k+1 ... size).find(no_pivot) {|row|
- a[row][k] != 0
- }
- a[switch], a[k] = a[k], a[switch]
- pivot = a[k][k]
- sign = -sign
- end
- (k+1).upto(last) do |i|
- ai = a[i]
- (k+1).upto(last) do |j|
- ai[j] = (pivot * ai[j] - ai[k] * a[k][j]) / previous_pivot
- end
- end
- end
- sign * pivot
- end
- private :determinant_bareiss
-
- #
- # deprecated; use Matrix#determinant
- #
- def determinant_e
- warn "#{caller(1)[0]}: warning: Matrix#determinant_e is deprecated; use #determinant"
- determinant
- end
- alias det_e determinant_e
-
- #
- # Returns a new matrix resulting by stacking horizontally
- # the receiver with the given matrices
- #
- # x = Matrix[[1, 2], [3, 4]]
- # y = Matrix[[5, 6], [7, 8]]
- # x.hstack(y) # => Matrix[[1, 2, 5, 6], [3, 4, 7, 8]]
- #
- def hstack(*matrices)
- self.class.hstack(self, *matrices)
- end
-
- #
- # Returns the rank of the matrix.
- # Beware that using Float values can yield erroneous results
- # because of their lack of precision.
- # Consider using exact types like Rational or BigDecimal instead.
- #
- # Matrix[[7,6], [3,9]].rank
- # => 2
- #
- def rank
- # We currently use Bareiss' multistep integer-preserving gaussian elimination
- # (see comments on determinant)
- a = to_a
- last_column = column_count - 1
- last_row = row_count - 1
- pivot_row = 0
- previous_pivot = 1
- 0.upto(last_column) do |k|
- switch_row = (pivot_row .. last_row).find {|row|
- a[row][k] != 0
- }
- if switch_row
- a[switch_row], a[pivot_row] = a[pivot_row], a[switch_row] unless pivot_row == switch_row
- pivot = a[pivot_row][k]
- (pivot_row+1).upto(last_row) do |i|
- ai = a[i]
- (k+1).upto(last_column) do |j|
- ai[j] = (pivot * ai[j] - ai[k] * a[pivot_row][j]) / previous_pivot
- end
- end
- pivot_row += 1
- previous_pivot = pivot
- end
- end
- pivot_row
- end
-
- #
- # deprecated; use Matrix#rank
- #
- def rank_e
- warn "#{caller(1)[0]}: warning: Matrix#rank_e is deprecated; use #rank"
- rank
- end
-
- # Returns a matrix with entries rounded to the given precision
- # (see Float#round)
- #
- def round(ndigits=0)
- map{|e| e.round(ndigits)}
- end
-
- #
- # Returns the trace (sum of diagonal elements) of the matrix.
- # Matrix[[7,6], [3,9]].trace
- # => 16
- #
- def trace
- Matrix.Raise ErrDimensionMismatch unless square?
- (0...column_count).inject(0) do |tr, i|
- tr + @rows[i][i]
- end
- end
- alias tr trace
-
- #
- # Returns the transpose of the matrix.
- # Matrix[[1,2], [3,4], [5,6]]
- # => 1 2
- # 3 4
- # 5 6
- # Matrix[[1,2], [3,4], [5,6]].transpose
- # => 1 3 5
- # 2 4 6
- #
- def transpose
- return self.class.empty(column_count, 0) if row_count.zero?
- new_matrix @rows.transpose, row_count
- end
- alias t transpose
-
- #
- # Returns a new matrix resulting by stacking vertically
- # the receiver with the given matrices
- #
- # x = Matrix[[1, 2], [3, 4]]
- # y = Matrix[[5, 6], [7, 8]]
- # x.vstack(y) # => Matrix[[1, 2], [3, 4], [5, 6], [7, 8]]
- #
- def vstack(*matrices)
- self.class.vstack(self, *matrices)
- end
-
- #--
- # DECOMPOSITIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- #++
-
- #
- # Returns the Eigensystem of the matrix; see +EigenvalueDecomposition+.
- # m = Matrix[[1, 2], [3, 4]]
- # v, d, v_inv = m.eigensystem
- # d.diagonal? # => true
- # v.inv == v_inv # => true
- # (v * d * v_inv).round(5) == m # => true
- #
- def eigensystem
- EigenvalueDecomposition.new(self)
- end
- alias eigen eigensystem
-
- #
- # Returns the LUP decomposition of the matrix; see +LUPDecomposition+.
- # a = Matrix[[1, 2], [3, 4]]
- # l, u, p = a.lup
- # l.lower_triangular? # => true
- # u.upper_triangular? # => true
- # p.permutation? # => true
- # l * u == p * a # => true
- # a.lup.solve([2, 5]) # => Vector[(1/1), (1/2)]
- #
- def lup
- LUPDecomposition.new(self)
- end
- alias lup_decomposition lup
-
- #--
- # COMPLEX ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- #++
-
- #
- # Returns the conjugate of the matrix.
- # Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]]
- # => 1+2i i 0
- # 1 2 3
- # Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]].conjugate
- # => 1-2i -i 0
- # 1 2 3
- #
- def conjugate
- collect(&:conjugate)
- end
- alias conj conjugate
-
- #
- # Returns the imaginary part of the matrix.
- # Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]]
- # => 1+2i i 0
- # 1 2 3
- # Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]].imaginary
- # => 2i i 0
- # 0 0 0
- #
- def imaginary
- collect(&:imaginary)
- end
- alias imag imaginary
-
- #
- # Returns the real part of the matrix.
- # Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]]
- # => 1+2i i 0
- # 1 2 3
- # Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]].real
- # => 1 0 0
- # 1 2 3
- #
- def real
- collect(&:real)
- end
-
- #
- # Returns an array containing matrices corresponding to the real and imaginary
- # parts of the matrix
- #
- # m.rect == [m.real, m.imag] # ==> true for all matrices m
- #
- def rect
- [real, imag]
- end
- alias rectangular rect
-
- #--
- # CONVERTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- #++
-
- #
- # The coerce method provides support for Ruby type coercion.
- # This coercion mechanism is used by Ruby to handle mixed-type
- # numeric operations: it is intended to find a compatible common
- # type between the two operands of the operator.
- # See also Numeric#coerce.
- #
- def coerce(other)
- case other
- when Numeric
- return Scalar.new(other), self
- else
- raise TypeError, "#{self.class} can't be coerced into #{other.class}"
- end
- end
-
- #
- # Returns an array of the row vectors of the matrix. See Vector.
- #
- def row_vectors
- Array.new(row_count) {|i|
- row(i)
- }
- end
-
- #
- # Returns an array of the column vectors of the matrix. See Vector.
- #
- def column_vectors
- Array.new(column_count) {|i|
- column(i)
- }
- end
-
- #
- # Returns an array of arrays that describe the rows of the matrix.
- #
- def to_a
- @rows.collect(&:dup)
- end
-
- def elements_to_f
- warn "#{caller(1)[0]}: warning: Matrix#elements_to_f is deprecated, use map(&:to_f)"
- map(&:to_f)
- end
-
- def elements_to_i
- warn "#{caller(1)[0]}: warning: Matrix#elements_to_i is deprecated, use map(&:to_i)"
- map(&:to_i)
- end
-
- def elements_to_r
- warn "#{caller(1)[0]}: warning: Matrix#elements_to_r is deprecated, use map(&:to_r)"
- map(&:to_r)
- end
-
- #--
- # PRINTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- #++
-
- #
- # Overrides Object#to_s
- #
- def to_s
- if empty?
- "#{self.class}.empty(#{row_count}, #{column_count})"
- else
- "#{self.class}[" + @rows.collect{|row|
- "[" + row.collect{|e| e.to_s}.join(", ") + "]"
- }.join(", ")+"]"
- end
- end
-
- #
- # Overrides Object#inspect
- #
- def inspect
- if empty?
- "#{self.class}.empty(#{row_count}, #{column_count})"
- else
- "#{self.class}#{@rows.inspect}"
- end
- end
-
- # Private helper modules
-
- module ConversionHelper # :nodoc:
- #
- # Converts the obj to an Array. If copy is set to true
- # a copy of obj will be made if necessary.
- #
- def convert_to_array(obj, copy = false) # :nodoc:
- case obj
- when Array
- copy ? obj.dup : obj
- when Vector
- obj.to_a
- else
- begin
- converted = obj.to_ary
- rescue Exception => e
- raise TypeError, "can't convert #{obj.class} into an Array (#{e.message})"
- end
- raise TypeError, "#{obj.class}#to_ary should return an Array" unless converted.is_a? Array
- converted
- end
- end
- private :convert_to_array
- end
-
- extend ConversionHelper
-
- module CoercionHelper # :nodoc:
- #
- # Applies the operator +oper+ with argument +obj+
- # through coercion of +obj+
- #
- def apply_through_coercion(obj, oper)
- coercion = obj.coerce(self)
- raise TypeError unless coercion.is_a?(Array) && coercion.length == 2
- coercion[0].public_send(oper, coercion[1])
- rescue
- raise TypeError, "#{obj.inspect} can't be coerced into #{self.class}"
- end
- private :apply_through_coercion
-
- #
- # Helper method to coerce a value into a specific class.
- # Raises a TypeError if the coercion fails or the returned value
- # is not of the right class.
- # (from Rubinius)
- #
- def self.coerce_to(obj, cls, meth) # :nodoc:
- return obj if obj.kind_of?(cls)
-
- begin
- ret = obj.__send__(meth)
- rescue Exception => e
- raise TypeError, "Coercion error: #{obj.inspect}.#{meth} => #{cls} failed:\n" \
- "(#{e.message})"
- end
- raise TypeError, "Coercion error: obj.#{meth} did NOT return a #{cls} (was #{ret.class})" unless ret.kind_of? cls
- ret
- end
-
- def self.coerce_to_int(obj)
- coerce_to(obj, Integer, :to_int)
- end
- end
-
- include CoercionHelper
-
- # Private CLASS
-
- class Scalar < Numeric # :nodoc:
- include ExceptionForMatrix
- include CoercionHelper
-
- def initialize(value)
- @value = value
- end
-
- # ARITHMETIC
- def +(other)
- case other
- when Numeric
- Scalar.new(@value + other)
- when Vector, Matrix
- Scalar.Raise ErrOperationNotDefined, "+", @value.class, other.class
- else
- apply_through_coercion(other, __method__)
- end
- end
-
- def -(other)
- case other
- when Numeric
- Scalar.new(@value - other)
- when Vector, Matrix
- Scalar.Raise ErrOperationNotDefined, "-", @value.class, other.class
- else
- apply_through_coercion(other, __method__)
- end
- end
-
- def *(other)
- case other
- when Numeric
- Scalar.new(@value * other)
- when Vector, Matrix
- other.collect{|e| @value * e}
- else
- apply_through_coercion(other, __method__)
- end
- end
-
- def / (other)
- case other
- when Numeric
- Scalar.new(@value / other)
- when Vector
- Scalar.Raise ErrOperationNotDefined, "/", @value.class, other.class
- when Matrix
- self * other.inverse
- else
- apply_through_coercion(other, __method__)
- end
- end
-
- def ** (other)
- case other
- when Numeric
- Scalar.new(@value ** other)
- when Vector
- Scalar.Raise ErrOperationNotDefined, "**", @value.class, other.class
- when Matrix
- #other.powered_by(self)
- Scalar.Raise ErrOperationNotImplemented, "**", @value.class, other.class
- else
- apply_through_coercion(other, __method__)
- end
- end
- end
-
-end
-
-
-#
-# The +Vector+ class represents a mathematical vector, which is useful in its own right, and
-# also constitutes a row or column of a Matrix.
-#
-# == Method Catalogue
-#
-# To create a Vector:
-# * Vector.[](*array)
-# * Vector.elements(array, copy = true)
-# * Vector.basis(size: n, index: k)
-#
-# To access elements:
-# * #[](i)
-#
-# To enumerate the elements:
-# * #each2(v)
-# * #collect2(v)
-#
-# Properties of vectors:
-# * #angle_with(v)
-# * Vector.independent?(*vs)
-# * #independent?(*vs)
-#
-# Vector arithmetic:
-# * #*(x) "is matrix or number"
-# * #+(v)
-# * #-(v)
-# * #+@
-# * #-@
-#
-# Vector functions:
-# * #inner_product(v), dot(v)
-# * #cross_product(v), cross(v)
-# * #collect
-# * #magnitude
-# * #map
-# * #map2(v)
-# * #norm
-# * #normalize
-# * #r
-# * #size
-#
-# Conversion to other data types:
-# * #covector
-# * #to_a
-# * #coerce(other)
-#
-# String representations:
-# * #to_s
-# * #inspect
-#
-class Vector
- include ExceptionForMatrix
- include Enumerable
- include Matrix::CoercionHelper
- extend Matrix::ConversionHelper
- #INSTANCE CREATION
-
- private_class_method :new
- attr_reader :elements
- protected :elements
-
- #
- # Creates a Vector from a list of elements.
- # Vector[7, 4, ...]
- #
- def Vector.[](*array)
- new convert_to_array(array, false)
- end
-
- #
- # Creates a vector from an Array. The optional second argument specifies
- # whether the array itself or a copy is used internally.
- #
- def Vector.elements(array, copy = true)
- new convert_to_array(array, copy)
- end
-
- #
- # Returns a standard basis +n+-vector, where k is the index.
- #
- # Vector.basis(size:, index:) # => Vector[0, 1, 0]
- #
- def Vector.basis(size:, index:)
- raise ArgumentError, "invalid size (#{size} for 1..)" if size < 1
- raise ArgumentError, "invalid index (#{index} for 0...#{size})" unless 0 <= index && index < size
- array = Array.new(size, 0)
- array[index] = 1
- new convert_to_array(array, false)
- end
-
- #
- # Vector.new is private; use Vector[] or Vector.elements to create.
- #
- def initialize(array)
- # No checking is done at this point.
- @elements = array
- end
-
- # ACCESSING
-
- #
- # Returns element number +i+ (starting at zero) of the vector.
- #
- def [](i)
- @elements[i]
- end
- alias element []
- alias component []
-
- def []=(i, v)
- @elements[i]= v
- end
- alias set_element []=
- alias set_component []=
- private :[]=, :set_element, :set_component
-
- #
- # Returns the number of elements in the vector.
- #
- def size
- @elements.size
- end
-
- #--
- # ENUMERATIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- #++
-
- #
- # Iterate over the elements of this vector
- #
- def each(&block)
- return to_enum(:each) unless block_given?
- @elements.each(&block)
- self
- end
-
- #
- # Iterate over the elements of this vector and +v+ in conjunction.
- #
- def each2(v) # :yield: e1, e2
- raise TypeError, "Integer is not like Vector" if v.kind_of?(Integer)
- Vector.Raise ErrDimensionMismatch if size != v.size
- return to_enum(:each2, v) unless block_given?
- size.times do |i|
- yield @elements[i], v[i]
- end
- self
- end
-
- #
- # Collects (as in Enumerable#collect) over the elements of this vector and +v+
- # in conjunction.
- #
- def collect2(v) # :yield: e1, e2
- raise TypeError, "Integer is not like Vector" if v.kind_of?(Integer)
- Vector.Raise ErrDimensionMismatch if size != v.size
- return to_enum(:collect2, v) unless block_given?
- Array.new(size) do |i|
- yield @elements[i], v[i]
- end
- end
-
- #--
- # PROPERTIES -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- #++
-
- #
- # Returns +true+ iff all of vectors are linearly independent.
- #
- # Vector.independent?(Vector[1,0], Vector[0,1])
- # => true
- #
- # Vector.independent?(Vector[1,2], Vector[2,4])
- # => false
- #
- def Vector.independent?(*vs)
- vs.each do |v|
- raise TypeError, "expected Vector, got #{v.class}" unless v.is_a?(Vector)
- Vector.Raise ErrDimensionMismatch unless v.size == vs.first.size
- end
- return false if vs.count > vs.first.size
- Matrix[*vs].rank.eql?(vs.count)
- end
-
- #
- # Returns +true+ iff all of vectors are linearly independent.
- #
- # Vector[1,0].independent?(Vector[0,1])
- # => true
- #
- # Vector[1,2].independent?(Vector[2,4])
- # => false
- #
- def independent?(*vs)
- self.class.independent?(self, *vs)
- end
-
- #--
- # COMPARING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- #++
-
- #
- # Returns +true+ iff the two vectors have the same elements in the same order.
- #
- def ==(other)
- return false unless Vector === other
- @elements == other.elements
- end
-
- def eql?(other)
- return false unless Vector === other
- @elements.eql? other.elements
- end
-
- #
- # Returns a copy of the vector.
- #
- def clone
- self.class.elements(@elements)
- end
-
- #
- # Returns a hash-code for the vector.
- #
- def hash
- @elements.hash
- end
-
- #--
- # ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- #++
-
- #
- # Multiplies the vector by +x+, where +x+ is a number or another vector.
- #
- def *(x)
- case x
- when Numeric
- els = @elements.collect{|e| e * x}
- self.class.elements(els, false)
- when Matrix
- Matrix.column_vector(self) * x
- when Vector
- Vector.Raise ErrOperationNotDefined, "*", self.class, x.class
- else
- apply_through_coercion(x, __method__)
- end
- end
-
- #
- # Vector addition.
- #
- def +(v)
- case v
- when Vector
- Vector.Raise ErrDimensionMismatch if size != v.size
- els = collect2(v) {|v1, v2|
- v1 + v2
- }
- self.class.elements(els, false)
- when Matrix
- Matrix.column_vector(self) + v
- else
- apply_through_coercion(v, __method__)
- end
- end
-
- #
- # Vector subtraction.
- #
- def -(v)
- case v
- when Vector
- Vector.Raise ErrDimensionMismatch if size != v.size
- els = collect2(v) {|v1, v2|
- v1 - v2
- }
- self.class.elements(els, false)
- when Matrix
- Matrix.column_vector(self) - v
- else
- apply_through_coercion(v, __method__)
- end
- end
-
- #
- # Vector division.
- #
- def /(x)
- case x
- when Numeric
- els = @elements.collect{|e| e / x}
- self.class.elements(els, false)
- when Matrix, Vector
- Vector.Raise ErrOperationNotDefined, "/", self.class, x.class
- else
- apply_through_coercion(x, __method__)
- end
- end
-
- def +@
- self
- end
-
- def -@
- collect {|e| -e }
- end
-
- #--
- # VECTOR FUNCTIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- #++
-
- #
- # Returns the inner product of this vector with the other.
- # Vector[4,7].inner_product Vector[10,1] => 47
- #
- def inner_product(v)
- Vector.Raise ErrDimensionMismatch if size != v.size
-
- p = 0
- each2(v) {|v1, v2|
- p += v1 * v2.conj
- }
- p
- end
- alias_method :dot, :inner_product
-
- #
- # Returns the cross product of this vector with the others.
- # Vector[1, 0, 0].cross_product Vector[0, 1, 0] => Vector[0, 0, 1]
- #
- # It is generalized to other dimensions to return a vector perpendicular
- # to the arguments.
- # Vector[1, 2].cross_product # => Vector[-2, 1]
- # Vector[1, 0, 0, 0].cross_product(
- # Vector[0, 1, 0, 0],
- # Vector[0, 0, 1, 0]
- # ) #=> Vector[0, 0, 0, 1]
- #
- def cross_product(*vs)
- raise ErrOperationNotDefined, "cross product is not defined on vectors of dimension #{size}" unless size >= 2
- raise ArgumentError, "wrong number of arguments (#{vs.size} for #{size - 2})" unless vs.size == size - 2
- vs.each do |v|
- raise TypeError, "expected Vector, got #{v.class}" unless v.is_a? Vector
- Vector.Raise ErrDimensionMismatch unless v.size == size
- end
- case size
- when 2
- Vector[-@elements[1], @elements[0]]
- when 3
- v = vs[0]
- Vector[ v[2]*@elements[1] - v[1]*@elements[2],
- v[0]*@elements[2] - v[2]*@elements[0],
- v[1]*@elements[0] - v[0]*@elements[1] ]
- else
- rows = self, *vs, Array.new(size) {|i| Vector.basis(size: size, index: i) }
- Matrix.rows(rows).laplace_expansion(row: size - 1)
- end
- end
- alias_method :cross, :cross_product
-
- #
- # Like Array#collect.
- #
- def collect(&block) # :yield: e
- return to_enum(:collect) unless block_given?
- els = @elements.collect(&block)
- self.class.elements(els, false)
- end
- alias map collect
-
- #
- # Returns the modulus (Pythagorean distance) of the vector.
- # Vector[5,8,2].r => 9.643650761
- #
- def magnitude
- Math.sqrt(@elements.inject(0) {|v, e| v + e.abs2})
- end
- alias r magnitude
- alias norm magnitude
-
- #
- # Like Vector#collect2, but returns a Vector instead of an Array.
- #
- def map2(v, &block) # :yield: e1, e2
- return to_enum(:map2, v) unless block_given?
- els = collect2(v, &block)
- self.class.elements(els, false)
- end
-
- class ZeroVectorError < StandardError
- end
- #
- # Returns a new vector with the same direction but with norm 1.
- # v = Vector[5,8,2].normalize
- # # => Vector[0.5184758473652127, 0.8295613557843402, 0.20739033894608505]
- # v.norm => 1.0
- #
- def normalize
- n = magnitude
- raise ZeroVectorError, "Zero vectors can not be normalized" if n == 0
- self / n
- end
-
- #
- # Returns an angle with another vector. Result is within the [0...Math::PI].
- # Vector[1,0].angle_with(Vector[0,1])
- # # => Math::PI / 2
- #
- def angle_with(v)
- raise TypeError, "Expected a Vector, got a #{v.class}" unless v.is_a?(Vector)
- Vector.Raise ErrDimensionMismatch if size != v.size
- prod = magnitude * v.magnitude
- raise ZeroVectorError, "Can't get angle of zero vector" if prod == 0
-
- Math.acos( inner_product(v) / prod )
- end
-
- #--
- # CONVERTING
- #++
-
- #
- # Creates a single-row matrix from this vector.
- #
- def covector
- Matrix.row_vector(self)
- end
-
- #
- # Returns the elements of the vector in an array.
- #
- def to_a
- @elements.dup
- end
-
- def elements_to_f
- warn "#{caller(1)[0]}: warning: Vector#elements_to_f is deprecated"
- map(&:to_f)
- end
-
- def elements_to_i
- warn "#{caller(1)[0]}: warning: Vector#elements_to_i is deprecated"
- map(&:to_i)
- end
-
- def elements_to_r
- warn "#{caller(1)[0]}: warning: Vector#elements_to_r is deprecated"
- map(&:to_r)
- end
-
- #
- # The coerce method provides support for Ruby type coercion.
- # This coercion mechanism is used by Ruby to handle mixed-type
- # numeric operations: it is intended to find a compatible common
- # type between the two operands of the operator.
- # See also Numeric#coerce.
- #
- def coerce(other)
- case other
- when Numeric
- return Matrix::Scalar.new(other), self
- else
- raise TypeError, "#{self.class} can't be coerced into #{other.class}"
- end
- end
-
- #--
- # PRINTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- #++
-
- #
- # Overrides Object#to_s
- #
- def to_s
- "Vector[" + @elements.join(", ") + "]"
- end
-
- #
- # Overrides Object#inspect
- #
- def inspect
- "Vector" + @elements.inspect
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/matrix/eigenvalue_decomposition.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/matrix/eigenvalue_decomposition.rb
deleted file mode 100755
index ab353ecf6..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/matrix/eigenvalue_decomposition.rb
+++ /dev/null
@@ -1,882 +0,0 @@
-class Matrix
- # Adapted from JAMA: http://math.nist.gov/javanumerics/jama/
-
- # Eigenvalues and eigenvectors of a real matrix.
- #
- # Computes the eigenvalues and eigenvectors of a matrix A.
- #
- # If A is diagonalizable, this provides matrices V and D
- # such that A = V*D*V.inv, where D is the diagonal matrix with entries
- # equal to the eigenvalues and V is formed by the eigenvectors.
- #
- # If A is symmetric, then V is orthogonal and thus A = V*D*V.t
-
- class EigenvalueDecomposition
-
- # Constructs the eigenvalue decomposition for a square matrix +A+
- #
- def initialize(a)
- # @d, @e: Arrays for internal storage of eigenvalues.
- # @v: Array for internal storage of eigenvectors.
- # @h: Array for internal storage of nonsymmetric Hessenberg form.
- raise TypeError, "Expected Matrix but got #{a.class}" unless a.is_a?(Matrix)
- @size = a.row_count
- @d = Array.new(@size, 0)
- @e = Array.new(@size, 0)
-
- if (@symmetric = a.symmetric?)
- @v = a.to_a
- tridiagonalize
- diagonalize
- else
- @v = Array.new(@size) { Array.new(@size, 0) }
- @h = a.to_a
- @ort = Array.new(@size, 0)
- reduce_to_hessenberg
- hessenberg_to_real_schur
- end
- end
-
- # Returns the eigenvector matrix +V+
- #
- def eigenvector_matrix
- Matrix.send(:new, build_eigenvectors.transpose)
- end
- alias v eigenvector_matrix
-
- # Returns the inverse of the eigenvector matrix +V+
- #
- def eigenvector_matrix_inv
- r = Matrix.send(:new, build_eigenvectors)
- r = r.transpose.inverse unless @symmetric
- r
- end
- alias v_inv eigenvector_matrix_inv
-
- # Returns the eigenvalues in an array
- #
- def eigenvalues
- values = @d.dup
- @e.each_with_index{|imag, i| values[i] = Complex(values[i], imag) unless imag == 0}
- values
- end
-
- # Returns an array of the eigenvectors
- #
- def eigenvectors
- build_eigenvectors.map{|ev| Vector.send(:new, ev)}
- end
-
- # Returns the block diagonal eigenvalue matrix +D+
- #
- def eigenvalue_matrix
- Matrix.diagonal(*eigenvalues)
- end
- alias d eigenvalue_matrix
-
- # Returns [eigenvector_matrix, eigenvalue_matrix, eigenvector_matrix_inv]
- #
- def to_ary
- [v, d, v_inv]
- end
- alias_method :to_a, :to_ary
-
- private
- def build_eigenvectors
- # JAMA stores complex eigenvectors in a strange way
- # See http://web.archive.org/web/20111016032731/http://cio.nist.gov/esd/emaildir/lists/jama/msg01021.html
- @e.each_with_index.map do |imag, i|
- if imag == 0
- Array.new(@size){|j| @v[j][i]}
- elsif imag > 0
- Array.new(@size){|j| Complex(@v[j][i], @v[j][i+1])}
- else
- Array.new(@size){|j| Complex(@v[j][i-1], -@v[j][i])}
- end
- end
- end
- # Complex scalar division.
-
- def cdiv(xr, xi, yr, yi)
- if (yr.abs > yi.abs)
- r = yi/yr
- d = yr + r*yi
- [(xr + r*xi)/d, (xi - r*xr)/d]
- else
- r = yr/yi
- d = yi + r*yr
- [(r*xr + xi)/d, (r*xi - xr)/d]
- end
- end
-
-
- # Symmetric Householder reduction to tridiagonal form.
-
- def tridiagonalize
-
- # This is derived from the Algol procedures tred2 by
- # Bowdler, Martin, Reinsch, and Wilkinson, Handbook for
- # Auto. Comp., Vol.ii-Linear Algebra, and the corresponding
- # Fortran subroutine in EISPACK.
-
- @size.times do |j|
- @d[j] = @v[@size-1][j]
- end
-
- # Householder reduction to tridiagonal form.
-
- (@size-1).downto(0+1) do |i|
-
- # Scale to avoid under/overflow.
-
- scale = 0.0
- h = 0.0
- i.times do |k|
- scale = scale + @d[k].abs
- end
- if (scale == 0.0)
- @e[i] = @d[i-1]
- i.times do |j|
- @d[j] = @v[i-1][j]
- @v[i][j] = 0.0
- @v[j][i] = 0.0
- end
- else
-
- # Generate Householder vector.
-
- i.times do |k|
- @d[k] /= scale
- h += @d[k] * @d[k]
- end
- f = @d[i-1]
- g = Math.sqrt(h)
- if (f > 0)
- g = -g
- end
- @e[i] = scale * g
- h -= f * g
- @d[i-1] = f - g
- i.times do |j|
- @e[j] = 0.0
- end
-
- # Apply similarity transformation to remaining columns.
-
- i.times do |j|
- f = @d[j]
- @v[j][i] = f
- g = @e[j] + @v[j][j] * f
- (j+1).upto(i-1) do |k|
- g += @v[k][j] * @d[k]
- @e[k] += @v[k][j] * f
- end
- @e[j] = g
- end
- f = 0.0
- i.times do |j|
- @e[j] /= h
- f += @e[j] * @d[j]
- end
- hh = f / (h + h)
- i.times do |j|
- @e[j] -= hh * @d[j]
- end
- i.times do |j|
- f = @d[j]
- g = @e[j]
- j.upto(i-1) do |k|
- @v[k][j] -= (f * @e[k] + g * @d[k])
- end
- @d[j] = @v[i-1][j]
- @v[i][j] = 0.0
- end
- end
- @d[i] = h
- end
-
- # Accumulate transformations.
-
- 0.upto(@size-1-1) do |i|
- @v[@size-1][i] = @v[i][i]
- @v[i][i] = 1.0
- h = @d[i+1]
- if (h != 0.0)
- 0.upto(i) do |k|
- @d[k] = @v[k][i+1] / h
- end
- 0.upto(i) do |j|
- g = 0.0
- 0.upto(i) do |k|
- g += @v[k][i+1] * @v[k][j]
- end
- 0.upto(i) do |k|
- @v[k][j] -= g * @d[k]
- end
- end
- end
- 0.upto(i) do |k|
- @v[k][i+1] = 0.0
- end
- end
- @size.times do |j|
- @d[j] = @v[@size-1][j]
- @v[@size-1][j] = 0.0
- end
- @v[@size-1][@size-1] = 1.0
- @e[0] = 0.0
- end
-
-
- # Symmetric tridiagonal QL algorithm.
-
- def diagonalize
- # This is derived from the Algol procedures tql2, by
- # Bowdler, Martin, Reinsch, and Wilkinson, Handbook for
- # Auto. Comp., Vol.ii-Linear Algebra, and the corresponding
- # Fortran subroutine in EISPACK.
-
- 1.upto(@size-1) do |i|
- @e[i-1] = @e[i]
- end
- @e[@size-1] = 0.0
-
- f = 0.0
- tst1 = 0.0
- eps = Float::EPSILON
- @size.times do |l|
-
- # Find small subdiagonal element
-
- tst1 = [tst1, @d[l].abs + @e[l].abs].max
- m = l
- while (m < @size) do
- if (@e[m].abs <= eps*tst1)
- break
- end
- m+=1
- end
-
- # If m == l, @d[l] is an eigenvalue,
- # otherwise, iterate.
-
- if (m > l)
- iter = 0
- begin
- iter = iter + 1 # (Could check iteration count here.)
-
- # Compute implicit shift
-
- g = @d[l]
- p = (@d[l+1] - g) / (2.0 * @e[l])
- r = Math.hypot(p, 1.0)
- if (p < 0)
- r = -r
- end
- @d[l] = @e[l] / (p + r)
- @d[l+1] = @e[l] * (p + r)
- dl1 = @d[l+1]
- h = g - @d[l]
- (l+2).upto(@size-1) do |i|
- @d[i] -= h
- end
- f += h
-
- # Implicit QL transformation.
-
- p = @d[m]
- c = 1.0
- c2 = c
- c3 = c
- el1 = @e[l+1]
- s = 0.0
- s2 = 0.0
- (m-1).downto(l) do |i|
- c3 = c2
- c2 = c
- s2 = s
- g = c * @e[i]
- h = c * p
- r = Math.hypot(p, @e[i])
- @e[i+1] = s * r
- s = @e[i] / r
- c = p / r
- p = c * @d[i] - s * g
- @d[i+1] = h + s * (c * g + s * @d[i])
-
- # Accumulate transformation.
-
- @size.times do |k|
- h = @v[k][i+1]
- @v[k][i+1] = s * @v[k][i] + c * h
- @v[k][i] = c * @v[k][i] - s * h
- end
- end
- p = -s * s2 * c3 * el1 * @e[l] / dl1
- @e[l] = s * p
- @d[l] = c * p
-
- # Check for convergence.
-
- end while (@e[l].abs > eps*tst1)
- end
- @d[l] = @d[l] + f
- @e[l] = 0.0
- end
-
- # Sort eigenvalues and corresponding vectors.
-
- 0.upto(@size-2) do |i|
- k = i
- p = @d[i]
- (i+1).upto(@size-1) do |j|
- if (@d[j] < p)
- k = j
- p = @d[j]
- end
- end
- if (k != i)
- @d[k] = @d[i]
- @d[i] = p
- @size.times do |j|
- p = @v[j][i]
- @v[j][i] = @v[j][k]
- @v[j][k] = p
- end
- end
- end
- end
-
- # Nonsymmetric reduction to Hessenberg form.
-
- def reduce_to_hessenberg
- # This is derived from the Algol procedures orthes and ortran,
- # by Martin and Wilkinson, Handbook for Auto. Comp.,
- # Vol.ii-Linear Algebra, and the corresponding
- # Fortran subroutines in EISPACK.
-
- low = 0
- high = @size-1
-
- (low+1).upto(high-1) do |m|
-
- # Scale column.
-
- scale = 0.0
- m.upto(high) do |i|
- scale = scale + @h[i][m-1].abs
- end
- if (scale != 0.0)
-
- # Compute Householder transformation.
-
- h = 0.0
- high.downto(m) do |i|
- @ort[i] = @h[i][m-1]/scale
- h += @ort[i] * @ort[i]
- end
- g = Math.sqrt(h)
- if (@ort[m] > 0)
- g = -g
- end
- h -= @ort[m] * g
- @ort[m] = @ort[m] - g
-
- # Apply Householder similarity transformation
- # @h = (I-u*u'/h)*@h*(I-u*u')/h)
-
- m.upto(@size-1) do |j|
- f = 0.0
- high.downto(m) do |i|
- f += @ort[i]*@h[i][j]
- end
- f = f/h
- m.upto(high) do |i|
- @h[i][j] -= f*@ort[i]
- end
- end
-
- 0.upto(high) do |i|
- f = 0.0
- high.downto(m) do |j|
- f += @ort[j]*@h[i][j]
- end
- f = f/h
- m.upto(high) do |j|
- @h[i][j] -= f*@ort[j]
- end
- end
- @ort[m] = scale*@ort[m]
- @h[m][m-1] = scale*g
- end
- end
-
- # Accumulate transformations (Algol's ortran).
-
- @size.times do |i|
- @size.times do |j|
- @v[i][j] = (i == j ? 1.0 : 0.0)
- end
- end
-
- (high-1).downto(low+1) do |m|
- if (@h[m][m-1] != 0.0)
- (m+1).upto(high) do |i|
- @ort[i] = @h[i][m-1]
- end
- m.upto(high) do |j|
- g = 0.0
- m.upto(high) do |i|
- g += @ort[i] * @v[i][j]
- end
- # Double division avoids possible underflow
- g = (g / @ort[m]) / @h[m][m-1]
- m.upto(high) do |i|
- @v[i][j] += g * @ort[i]
- end
- end
- end
- end
- end
-
-
-
- # Nonsymmetric reduction from Hessenberg to real Schur form.
-
- def hessenberg_to_real_schur
-
- # This is derived from the Algol procedure hqr2,
- # by Martin and Wilkinson, Handbook for Auto. Comp.,
- # Vol.ii-Linear Algebra, and the corresponding
- # Fortran subroutine in EISPACK.
-
- # Initialize
-
- nn = @size
- n = nn-1
- low = 0
- high = nn-1
- eps = Float::EPSILON
- exshift = 0.0
- p=q=r=s=z=0
-
- # Store roots isolated by balanc and compute matrix norm
-
- norm = 0.0
- nn.times do |i|
- if (i < low || i > high)
- @d[i] = @h[i][i]
- @e[i] = 0.0
- end
- ([i-1, 0].max).upto(nn-1) do |j|
- norm = norm + @h[i][j].abs
- end
- end
-
- # Outer loop over eigenvalue index
-
- iter = 0
- while (n >= low) do
-
- # Look for single small sub-diagonal element
-
- l = n
- while (l > low) do
- s = @h[l-1][l-1].abs + @h[l][l].abs
- if (s == 0.0)
- s = norm
- end
- if (@h[l][l-1].abs < eps * s)
- break
- end
- l-=1
- end
-
- # Check for convergence
- # One root found
-
- if (l == n)
- @h[n][n] = @h[n][n] + exshift
- @d[n] = @h[n][n]
- @e[n] = 0.0
- n-=1
- iter = 0
-
- # Two roots found
-
- elsif (l == n-1)
- w = @h[n][n-1] * @h[n-1][n]
- p = (@h[n-1][n-1] - @h[n][n]) / 2.0
- q = p * p + w
- z = Math.sqrt(q.abs)
- @h[n][n] = @h[n][n] + exshift
- @h[n-1][n-1] = @h[n-1][n-1] + exshift
- x = @h[n][n]
-
- # Real pair
-
- if (q >= 0)
- if (p >= 0)
- z = p + z
- else
- z = p - z
- end
- @d[n-1] = x + z
- @d[n] = @d[n-1]
- if (z != 0.0)
- @d[n] = x - w / z
- end
- @e[n-1] = 0.0
- @e[n] = 0.0
- x = @h[n][n-1]
- s = x.abs + z.abs
- p = x / s
- q = z / s
- r = Math.sqrt(p * p+q * q)
- p /= r
- q /= r
-
- # Row modification
-
- (n-1).upto(nn-1) do |j|
- z = @h[n-1][j]
- @h[n-1][j] = q * z + p * @h[n][j]
- @h[n][j] = q * @h[n][j] - p * z
- end
-
- # Column modification
-
- 0.upto(n) do |i|
- z = @h[i][n-1]
- @h[i][n-1] = q * z + p * @h[i][n]
- @h[i][n] = q * @h[i][n] - p * z
- end
-
- # Accumulate transformations
-
- low.upto(high) do |i|
- z = @v[i][n-1]
- @v[i][n-1] = q * z + p * @v[i][n]
- @v[i][n] = q * @v[i][n] - p * z
- end
-
- # Complex pair
-
- else
- @d[n-1] = x + p
- @d[n] = x + p
- @e[n-1] = z
- @e[n] = -z
- end
- n -= 2
- iter = 0
-
- # No convergence yet
-
- else
-
- # Form shift
-
- x = @h[n][n]
- y = 0.0
- w = 0.0
- if (l < n)
- y = @h[n-1][n-1]
- w = @h[n][n-1] * @h[n-1][n]
- end
-
- # Wilkinson's original ad hoc shift
-
- if (iter == 10)
- exshift += x
- low.upto(n) do |i|
- @h[i][i] -= x
- end
- s = @h[n][n-1].abs + @h[n-1][n-2].abs
- x = y = 0.75 * s
- w = -0.4375 * s * s
- end
-
- # MATLAB's new ad hoc shift
-
- if (iter == 30)
- s = (y - x) / 2.0
- s *= s + w
- if (s > 0)
- s = Math.sqrt(s)
- if (y < x)
- s = -s
- end
- s = x - w / ((y - x) / 2.0 + s)
- low.upto(n) do |i|
- @h[i][i] -= s
- end
- exshift += s
- x = y = w = 0.964
- end
- end
-
- iter = iter + 1 # (Could check iteration count here.)
-
- # Look for two consecutive small sub-diagonal elements
-
- m = n-2
- while (m >= l) do
- z = @h[m][m]
- r = x - z
- s = y - z
- p = (r * s - w) / @h[m+1][m] + @h[m][m+1]
- q = @h[m+1][m+1] - z - r - s
- r = @h[m+2][m+1]
- s = p.abs + q.abs + r.abs
- p /= s
- q /= s
- r /= s
- if (m == l)
- break
- end
- if (@h[m][m-1].abs * (q.abs + r.abs) <
- eps * (p.abs * (@h[m-1][m-1].abs + z.abs +
- @h[m+1][m+1].abs)))
- break
- end
- m-=1
- end
-
- (m+2).upto(n) do |i|
- @h[i][i-2] = 0.0
- if (i > m+2)
- @h[i][i-3] = 0.0
- end
- end
-
- # Double QR step involving rows l:n and columns m:n
-
- m.upto(n-1) do |k|
- notlast = (k != n-1)
- if (k != m)
- p = @h[k][k-1]
- q = @h[k+1][k-1]
- r = (notlast ? @h[k+2][k-1] : 0.0)
- x = p.abs + q.abs + r.abs
- next if x == 0
- p /= x
- q /= x
- r /= x
- end
- s = Math.sqrt(p * p + q * q + r * r)
- if (p < 0)
- s = -s
- end
- if (s != 0)
- if (k != m)
- @h[k][k-1] = -s * x
- elsif (l != m)
- @h[k][k-1] = -@h[k][k-1]
- end
- p += s
- x = p / s
- y = q / s
- z = r / s
- q /= p
- r /= p
-
- # Row modification
-
- k.upto(nn-1) do |j|
- p = @h[k][j] + q * @h[k+1][j]
- if (notlast)
- p += r * @h[k+2][j]
- @h[k+2][j] = @h[k+2][j] - p * z
- end
- @h[k][j] = @h[k][j] - p * x
- @h[k+1][j] = @h[k+1][j] - p * y
- end
-
- # Column modification
-
- 0.upto([n, k+3].min) do |i|
- p = x * @h[i][k] + y * @h[i][k+1]
- if (notlast)
- p += z * @h[i][k+2]
- @h[i][k+2] = @h[i][k+2] - p * r
- end
- @h[i][k] = @h[i][k] - p
- @h[i][k+1] = @h[i][k+1] - p * q
- end
-
- # Accumulate transformations
-
- low.upto(high) do |i|
- p = x * @v[i][k] + y * @v[i][k+1]
- if (notlast)
- p += z * @v[i][k+2]
- @v[i][k+2] = @v[i][k+2] - p * r
- end
- @v[i][k] = @v[i][k] - p
- @v[i][k+1] = @v[i][k+1] - p * q
- end
- end # (s != 0)
- end # k loop
- end # check convergence
- end # while (n >= low)
-
- # Backsubstitute to find vectors of upper triangular form
-
- if (norm == 0.0)
- return
- end
-
- (nn-1).downto(0) do |n|
- p = @d[n]
- q = @e[n]
-
- # Real vector
-
- if (q == 0)
- l = n
- @h[n][n] = 1.0
- (n-1).downto(0) do |i|
- w = @h[i][i] - p
- r = 0.0
- l.upto(n) do |j|
- r += @h[i][j] * @h[j][n]
- end
- if (@e[i] < 0.0)
- z = w
- s = r
- else
- l = i
- if (@e[i] == 0.0)
- if (w != 0.0)
- @h[i][n] = -r / w
- else
- @h[i][n] = -r / (eps * norm)
- end
-
- # Solve real equations
-
- else
- x = @h[i][i+1]
- y = @h[i+1][i]
- q = (@d[i] - p) * (@d[i] - p) + @e[i] * @e[i]
- t = (x * s - z * r) / q
- @h[i][n] = t
- if (x.abs > z.abs)
- @h[i+1][n] = (-r - w * t) / x
- else
- @h[i+1][n] = (-s - y * t) / z
- end
- end
-
- # Overflow control
-
- t = @h[i][n].abs
- if ((eps * t) * t > 1)
- i.upto(n) do |j|
- @h[j][n] = @h[j][n] / t
- end
- end
- end
- end
-
- # Complex vector
-
- elsif (q < 0)
- l = n-1
-
- # Last vector component imaginary so matrix is triangular
-
- if (@h[n][n-1].abs > @h[n-1][n].abs)
- @h[n-1][n-1] = q / @h[n][n-1]
- @h[n-1][n] = -(@h[n][n] - p) / @h[n][n-1]
- else
- cdivr, cdivi = cdiv(0.0, -@h[n-1][n], @h[n-1][n-1]-p, q)
- @h[n-1][n-1] = cdivr
- @h[n-1][n] = cdivi
- end
- @h[n][n-1] = 0.0
- @h[n][n] = 1.0
- (n-2).downto(0) do |i|
- ra = 0.0
- sa = 0.0
- l.upto(n) do |j|
- ra = ra + @h[i][j] * @h[j][n-1]
- sa = sa + @h[i][j] * @h[j][n]
- end
- w = @h[i][i] - p
-
- if (@e[i] < 0.0)
- z = w
- r = ra
- s = sa
- else
- l = i
- if (@e[i] == 0)
- cdivr, cdivi = cdiv(-ra, -sa, w, q)
- @h[i][n-1] = cdivr
- @h[i][n] = cdivi
- else
-
- # Solve complex equations
-
- x = @h[i][i+1]
- y = @h[i+1][i]
- vr = (@d[i] - p) * (@d[i] - p) + @e[i] * @e[i] - q * q
- vi = (@d[i] - p) * 2.0 * q
- if (vr == 0.0 && vi == 0.0)
- vr = eps * norm * (w.abs + q.abs +
- x.abs + y.abs + z.abs)
- end
- cdivr, cdivi = cdiv(x*r-z*ra+q*sa, x*s-z*sa-q*ra, vr, vi)
- @h[i][n-1] = cdivr
- @h[i][n] = cdivi
- if (x.abs > (z.abs + q.abs))
- @h[i+1][n-1] = (-ra - w * @h[i][n-1] + q * @h[i][n]) / x
- @h[i+1][n] = (-sa - w * @h[i][n] - q * @h[i][n-1]) / x
- else
- cdivr, cdivi = cdiv(-r-y*@h[i][n-1], -s-y*@h[i][n], z, q)
- @h[i+1][n-1] = cdivr
- @h[i+1][n] = cdivi
- end
- end
-
- # Overflow control
-
- t = [@h[i][n-1].abs, @h[i][n].abs].max
- if ((eps * t) * t > 1)
- i.upto(n) do |j|
- @h[j][n-1] = @h[j][n-1] / t
- @h[j][n] = @h[j][n] / t
- end
- end
- end
- end
- end
- end
-
- # Vectors of isolated roots
-
- nn.times do |i|
- if (i < low || i > high)
- i.upto(nn-1) do |j|
- @v[i][j] = @h[i][j]
- end
- end
- end
-
- # Back transformation to get eigenvectors of original matrix
-
- (nn-1).downto(low) do |j|
- low.upto(high) do |i|
- z = 0.0
- low.upto([j, high].min) do |k|
- z += @v[i][k] * @h[k][j]
- end
- @v[i][j] = z
- end
- end
- end
-
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/matrix/lup_decomposition.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/matrix/lup_decomposition.rb
deleted file mode 100755
index 30f327625..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/matrix/lup_decomposition.rb
+++ /dev/null
@@ -1,218 +0,0 @@
-class Matrix
- # Adapted from JAMA: http://math.nist.gov/javanumerics/jama/
-
- #
- # For an m-by-n matrix A with m >= n, the LU decomposition is an m-by-n
- # unit lower triangular matrix L, an n-by-n upper triangular matrix U,
- # and a m-by-m permutation matrix P so that L*U = P*A.
- # If m < n, then L is m-by-m and U is m-by-n.
- #
- # The LUP decomposition with pivoting always exists, even if the matrix is
- # singular, so the constructor will never fail. The primary use of the
- # LU decomposition is in the solution of square systems of simultaneous
- # linear equations. This will fail if singular? returns true.
- #
-
- class LUPDecomposition
- # Returns the lower triangular factor +L+
-
- include Matrix::ConversionHelper
-
- def l
- Matrix.build(@row_count, [@column_count, @row_count].min) do |i, j|
- if (i > j)
- @lu[i][j]
- elsif (i == j)
- 1
- else
- 0
- end
- end
- end
-
- # Returns the upper triangular factor +U+
-
- def u
- Matrix.build([@column_count, @row_count].min, @column_count) do |i, j|
- if (i <= j)
- @lu[i][j]
- else
- 0
- end
- end
- end
-
- # Returns the permutation matrix +P+
-
- def p
- rows = Array.new(@row_count){Array.new(@row_count, 0)}
- @pivots.each_with_index{|p, i| rows[i][p] = 1}
- Matrix.send :new, rows, @row_count
- end
-
- # Returns +L+, +U+, +P+ in an array
-
- def to_ary
- [l, u, p]
- end
- alias_method :to_a, :to_ary
-
- # Returns the pivoting indices
-
- attr_reader :pivots
-
- # Returns +true+ if +U+, and hence +A+, is singular.
-
- def singular? ()
- @column_count.times do |j|
- if (@lu[j][j] == 0)
- return true
- end
- end
- false
- end
-
- # Returns the determinant of +A+, calculated efficiently
- # from the factorization.
-
- def det
- if (@row_count != @column_count)
- Matrix.Raise Matrix::ErrDimensionMismatch
- end
- d = @pivot_sign
- @column_count.times do |j|
- d *= @lu[j][j]
- end
- d
- end
- alias_method :determinant, :det
-
- # Returns +m+ so that A*m = b,
- # or equivalently so that L*U*m = P*b
- # +b+ can be a Matrix or a Vector
-
- def solve b
- if (singular?)
- Matrix.Raise Matrix::ErrNotRegular, "Matrix is singular."
- end
- if b.is_a? Matrix
- if (b.row_count != @row_count)
- Matrix.Raise Matrix::ErrDimensionMismatch
- end
-
- # Copy right hand side with pivoting
- nx = b.column_count
- m = @pivots.map{|row| b.row(row).to_a}
-
- # Solve L*Y = P*b
- @column_count.times do |k|
- (k+1).upto(@column_count-1) do |i|
- nx.times do |j|
- m[i][j] -= m[k][j]*@lu[i][k]
- end
- end
- end
- # Solve U*m = Y
- (@column_count-1).downto(0) do |k|
- nx.times do |j|
- m[k][j] = m[k][j].quo(@lu[k][k])
- end
- k.times do |i|
- nx.times do |j|
- m[i][j] -= m[k][j]*@lu[i][k]
- end
- end
- end
- Matrix.send :new, m, nx
- else # same algorithm, specialized for simpler case of a vector
- b = convert_to_array(b)
- if (b.size != @row_count)
- Matrix.Raise Matrix::ErrDimensionMismatch
- end
-
- # Copy right hand side with pivoting
- m = b.values_at(*@pivots)
-
- # Solve L*Y = P*b
- @column_count.times do |k|
- (k+1).upto(@column_count-1) do |i|
- m[i] -= m[k]*@lu[i][k]
- end
- end
- # Solve U*m = Y
- (@column_count-1).downto(0) do |k|
- m[k] = m[k].quo(@lu[k][k])
- k.times do |i|
- m[i] -= m[k]*@lu[i][k]
- end
- end
- Vector.elements(m, false)
- end
- end
-
- def initialize a
- raise TypeError, "Expected Matrix but got #{a.class}" unless a.is_a?(Matrix)
- # Use a "left-looking", dot-product, Crout/Doolittle algorithm.
- @lu = a.to_a
- @row_count = a.row_count
- @column_count = a.column_count
- @pivots = Array.new(@row_count)
- @row_count.times do |i|
- @pivots[i] = i
- end
- @pivot_sign = 1
- lu_col_j = Array.new(@row_count)
-
- # Outer loop.
-
- @column_count.times do |j|
-
- # Make a copy of the j-th column to localize references.
-
- @row_count.times do |i|
- lu_col_j[i] = @lu[i][j]
- end
-
- # Apply previous transformations.
-
- @row_count.times do |i|
- lu_row_i = @lu[i]
-
- # Most of the time is spent in the following dot product.
-
- kmax = [i, j].min
- s = 0
- kmax.times do |k|
- s += lu_row_i[k]*lu_col_j[k]
- end
-
- lu_row_i[j] = lu_col_j[i] -= s
- end
-
- # Find pivot and exchange if necessary.
-
- p = j
- (j+1).upto(@row_count-1) do |i|
- if (lu_col_j[i].abs > lu_col_j[p].abs)
- p = i
- end
- end
- if (p != j)
- @column_count.times do |k|
- t = @lu[p][k]; @lu[p][k] = @lu[j][k]; @lu[j][k] = t
- end
- k = @pivots[p]; @pivots[p] = @pivots[j]; @pivots[j] = k
- @pivot_sign = -@pivot_sign
- end
-
- # Compute multipliers.
-
- if (j < @row_count && @lu[j][j] != 0)
- (j+1).upto(@row_count-1) do |i|
- @lu[i][j] = @lu[i][j].quo(@lu[j][j])
- end
- end
- end
- end
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/mkmf.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/mkmf.rb
deleted file mode 100755
index b38bd2e4f..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/mkmf.rb
+++ /dev/null
@@ -1,2684 +0,0 @@
-# -*- coding: us-ascii -*-
-# module to create Makefile for extension modules
-# invoke like: ruby -r mkmf extconf.rb
-
-require 'rbconfig'
-require 'fileutils'
-require 'shellwords'
-
-# :stopdoc:
-class String
- # Wraps a string in escaped quotes if it contains whitespace.
- def quote
- /\s/ =~ self ? "\"#{self}\"" : "#{self}"
- end
-
- # Escape whitespaces for Makefile.
- def unspace
- gsub(/\s/, '\\\\\\&')
- end
-
- # Generates a string used as cpp macro name.
- def tr_cpp
- strip.upcase.tr_s("^A-Z0-9_*", "_").tr_s("*", "P")
- end
-
- def funcall_style
- /\)\z/ =~ self ? dup : "#{self}()"
- end
-
- def sans_arguments
- self[/\A[^()]+/]
- end
-end
-
-class Array
- # Wraps all strings in escaped quotes if they contain whitespace.
- def quote
- map {|s| s.quote}
- end
-end
-# :startdoc:
-
-##
-# mkmf.rb is used by Ruby C extensions to generate a Makefile which will
-# correctly compile and link the C extension to Ruby and a third-party
-# library.
-module MakeMakefile
- #### defer until this module become global-state free.
- # def self.extended(obj)
- # obj.init_mkmf
- # super
- # end
- #
- # def initialize(*args, rbconfig: RbConfig, **rest)
- # init_mkmf(rbconfig::MAKEFILE_CONFIG, rbconfig::CONFIG)
- # super(*args, **rest)
- # end
-
- ##
- # The makefile configuration using the defaults from when Ruby was built.
-
- CONFIG = RbConfig::MAKEFILE_CONFIG
- ORIG_LIBPATH = ENV['LIB']
-
- ##
- # Extensions for files compiled with a C compiler
-
- C_EXT = %w[c m]
-
- ##
- # Extensions for files complied with a C++ compiler
-
- CXX_EXT = %w[cc mm cxx cpp]
- unless File.exist?(File.join(*File.split(__FILE__).tap {|d, b| b.swapcase}))
- CXX_EXT.concat(%w[C])
- end
-
- ##
- # Extensions for source files
-
- SRC_EXT = C_EXT + CXX_EXT
-
- ##
- # Extensions for header files
-
- HDR_EXT = %w[h hpp]
- $static = nil
- $config_h = '$(arch_hdrdir)/ruby/config.h'
- $default_static = $static
-
- unless defined? $configure_args
- $configure_args = {}
- args = CONFIG["configure_args"]
- if ENV["CONFIGURE_ARGS"]
- args << " " << ENV["CONFIGURE_ARGS"]
- end
- for arg in Shellwords::shellwords(args)
- arg, val = arg.split('=', 2)
- next unless arg
- arg.tr!('_', '-')
- if arg.sub!(/^(?!--)/, '--')
- val or next
- arg.downcase!
- end
- next if /^--(?:top|topsrc|src|cur)dir$/ =~ arg
- $configure_args[arg] = val || true
- end
- for arg in ARGV
- arg, val = arg.split('=', 2)
- next unless arg
- arg.tr!('_', '-')
- if arg.sub!(/^(?!--)/, '--')
- val or next
- arg.downcase!
- end
- $configure_args[arg] = val || true
- end
- end
-
- $libdir = CONFIG["libdir"]
- $rubylibdir = CONFIG["rubylibdir"]
- $archdir = CONFIG["archdir"]
- $sitedir = CONFIG["sitedir"]
- $sitelibdir = CONFIG["sitelibdir"]
- $sitearchdir = CONFIG["sitearchdir"]
- $vendordir = CONFIG["vendordir"]
- $vendorlibdir = CONFIG["vendorlibdir"]
- $vendorarchdir = CONFIG["vendorarchdir"]
-
- $mswin = /mswin/ =~ RUBY_PLATFORM
- $bccwin = /bccwin/ =~ RUBY_PLATFORM
- $mingw = /mingw/ =~ RUBY_PLATFORM
- $cygwin = /cygwin/ =~ RUBY_PLATFORM
- $netbsd = /netbsd/ =~ RUBY_PLATFORM
- $os2 = /os2/ =~ RUBY_PLATFORM
- $beos = /beos/ =~ RUBY_PLATFORM
- $haiku = /haiku/ =~ RUBY_PLATFORM
- $solaris = /solaris/ =~ RUBY_PLATFORM
- $universal = /universal/ =~ RUBY_PLATFORM
- $dest_prefix_pattern = (File::PATH_SEPARATOR == ';' ? /\A([[:alpha:]]:)?/ : /\A/)
-
- # :stopdoc:
-
- def config_string(key, config = CONFIG)
- s = config[key] and !s.empty? and block_given? ? yield(s) : s
- end
- module_function :config_string
-
- def dir_re(dir)
- Regexp.new('\$(?:\('+dir+'\)|\{'+dir+'\})(?:\$(?:\(target_prefix\)|\{target_prefix\}))?')
- end
- module_function :dir_re
-
- def relative_from(path, base)
- dir = File.join(path, "")
- if File.expand_path(dir) == File.expand_path(dir, base)
- path
- else
- File.join(base, path)
- end
- end
-
- INSTALL_DIRS = [
- [dir_re('commondir'), "$(RUBYCOMMONDIR)"],
- [dir_re('sitedir'), "$(RUBYCOMMONDIR)"],
- [dir_re('vendordir'), "$(RUBYCOMMONDIR)"],
- [dir_re('rubylibdir'), "$(RUBYLIBDIR)"],
- [dir_re('archdir'), "$(RUBYARCHDIR)"],
- [dir_re('sitelibdir'), "$(RUBYLIBDIR)"],
- [dir_re('vendorlibdir'), "$(RUBYLIBDIR)"],
- [dir_re('sitearchdir'), "$(RUBYARCHDIR)"],
- [dir_re('vendorarchdir'), "$(RUBYARCHDIR)"],
- [dir_re('rubyhdrdir'), "$(RUBYHDRDIR)"],
- [dir_re('sitehdrdir'), "$(SITEHDRDIR)"],
- [dir_re('vendorhdrdir'), "$(VENDORHDRDIR)"],
- [dir_re('bindir'), "$(BINDIR)"],
- ]
-
- def install_dirs(target_prefix = nil)
- if $extout
- dirs = [
- ['BINDIR', '$(extout)/bin'],
- ['RUBYCOMMONDIR', '$(extout)/common'],
- ['RUBYLIBDIR', '$(RUBYCOMMONDIR)$(target_prefix)'],
- ['RUBYARCHDIR', '$(extout)/$(arch)$(target_prefix)'],
- ['HDRDIR', '$(extout)/include/ruby$(target_prefix)'],
- ['ARCHHDRDIR', '$(extout)/include/$(arch)/ruby$(target_prefix)'],
- ['extout', "#$extout"],
- ['extout_prefix', "#$extout_prefix"],
- ]
- elsif $extmk
- dirs = [
- ['BINDIR', '$(bindir)'],
- ['RUBYCOMMONDIR', '$(rubylibdir)'],
- ['RUBYLIBDIR', '$(rubylibdir)$(target_prefix)'],
- ['RUBYARCHDIR', '$(archdir)$(target_prefix)'],
- ['HDRDIR', '$(rubyhdrdir)/ruby$(target_prefix)'],
- ['ARCHHDRDIR', '$(rubyhdrdir)/$(arch)/ruby$(target_prefix)'],
- ]
- elsif $configure_args.has_key?('--vendor')
- dirs = [
- ['BINDIR', '$(bindir)'],
- ['RUBYCOMMONDIR', '$(vendordir)$(target_prefix)'],
- ['RUBYLIBDIR', '$(vendorlibdir)$(target_prefix)'],
- ['RUBYARCHDIR', '$(vendorarchdir)$(target_prefix)'],
- ['HDRDIR', '$(rubyhdrdir)/ruby$(target_prefix)'],
- ['ARCHHDRDIR', '$(rubyhdrdir)/$(arch)/ruby$(target_prefix)'],
- ]
- else
- dirs = [
- ['BINDIR', '$(bindir)'],
- ['RUBYCOMMONDIR', '$(sitedir)$(target_prefix)'],
- ['RUBYLIBDIR', '$(sitelibdir)$(target_prefix)'],
- ['RUBYARCHDIR', '$(sitearchdir)$(target_prefix)'],
- ['HDRDIR', '$(rubyhdrdir)/ruby$(target_prefix)'],
- ['ARCHHDRDIR', '$(rubyhdrdir)/$(arch)/ruby$(target_prefix)'],
- ]
- end
- dirs << ['target_prefix', (target_prefix ? "/#{target_prefix}" : "")]
- dirs
- end
-
- def map_dir(dir, map = nil)
- map ||= INSTALL_DIRS
- map.inject(dir) {|d, (orig, new)| d.gsub(orig, new)}
- end
-
- topdir = File.dirname(File.dirname(__FILE__))
- path = File.expand_path($0)
- until (dir = File.dirname(path)) == path
- if File.identical?(dir, topdir)
- $extmk = true if %r"\A(?:ext|enc|tool|test)\z" =~ File.basename(path)
- break
- end
- path = dir
- end
- $extmk ||= false
- if not $extmk and File.exist?(($hdrdir = RbConfig::CONFIG["rubyhdrdir"]) + "/ruby/ruby.h")
- $topdir = $hdrdir
- $top_srcdir = $hdrdir
- $arch_hdrdir = RbConfig::CONFIG["rubyarchhdrdir"]
- elsif File.exist?(($hdrdir = ($top_srcdir ||= topdir) + "/include") + "/ruby.h")
- $topdir ||= RbConfig::CONFIG["topdir"]
- $arch_hdrdir = "$(extout)/include/$(arch)"
- else
- abort "mkmf.rb can't find header files for ruby at #{$hdrdir}/ruby.h"
- end
-
- CONFTEST = "conftest".freeze
- CONFTEST_C = "#{CONFTEST}.c"
-
- OUTFLAG = CONFIG['OUTFLAG']
- COUTFLAG = CONFIG['COUTFLAG']
- CPPOUTFILE = config_string('CPPOUTFILE') {|str| str.sub(/\bconftest\b/, CONFTEST)}
-
- def rm_f(*files)
- opt = (Hash === files.last ? [files.pop] : [])
- FileUtils.rm_f(Dir[*files.flatten], *opt)
- end
- module_function :rm_f
-
- def rm_rf(*files)
- opt = (Hash === files.last ? [files.pop] : [])
- FileUtils.rm_rf(Dir[*files.flatten], *opt)
- end
- module_function :rm_rf
-
- # Returns time stamp of the +target+ file if it exists and is newer than or
- # equal to all of +times+.
- def modified?(target, times)
- (t = File.mtime(target)) rescue return nil
- Array === times or times = [times]
- t if times.all? {|n| n <= t}
- end
-
- def split_libs(*strs)
- strs.map {|s| s.split(/\s+(?=-|\z)/)}.flatten
- end
-
- def merge_libs(*libs)
- libs.inject([]) do |x, y|
- y = y.inject([]) {|ary, e| ary.last == e ? ary : ary << e}
- y.each_with_index do |v, yi|
- if xi = x.rindex(v)
- x[(xi+1)..-1] = merge_libs(y[(yi+1)..-1], x[(xi+1)..-1])
- x[xi, 0] = y[0...yi]
- break
- end
- end and x.concat(y)
- x
- end
- end
-
- # This is a custom logging module. It generates an mkmf.log file when you
- # run your extconf.rb script. This can be useful for debugging unexpected
- # failures.
- #
- # This module and its associated methods are meant for internal use only.
- #
- module Logging
- @log = nil
- @logfile = 'mkmf.log'
- @orgerr = $stderr.dup
- @orgout = $stdout.dup
- @postpone = 0
- @quiet = $extmk
-
- def self::log_open
- @log ||= File::open(@logfile, 'wb')
- @log.sync = true
- end
-
- def self::log_opened?
- @log and not @log.closed?
- end
-
- def self::open
- log_open
- $stderr.reopen(@log)
- $stdout.reopen(@log)
- yield
- ensure
- $stderr.reopen(@orgerr)
- $stdout.reopen(@orgout)
- end
-
- def self::message(*s)
- log_open
- @log.printf(*s)
- end
-
- def self::logfile file
- @logfile = file
- log_close
- end
-
- def self::log_close
- if @log and not @log.closed?
- @log.flush
- @log.close
- @log = nil
- end
- end
-
- def self::postpone
- tmplog = "mkmftmp#{@postpone += 1}.log"
- open do
- log, *save = @log, @logfile, @orgout, @orgerr
- @log, @logfile, @orgout, @orgerr = nil, tmplog, log, log
- begin
- log.print(open {yield @log})
- ensure
- @log.close if @log and not @log.closed?
- File::open(tmplog) {|t| FileUtils.copy_stream(t, log)} if File.exist?(tmplog)
- @log, @logfile, @orgout, @orgerr = log, *save
- @postpone -= 1
- MakeMakefile.rm_f tmplog
- end
- end
- end
-
- class << self
- attr_accessor :quiet
- end
- end
-
- def libpath_env
- # used only if native compiling
- if libpathenv = config_string("LIBPATHENV")
- pathenv = ENV[libpathenv]
- libpath = RbConfig.expand($DEFLIBPATH.join(File::PATH_SEPARATOR))
- {libpathenv => [libpath, pathenv].compact.join(File::PATH_SEPARATOR)}
- else
- {}
- end
- end
-
- def xsystem command, opts = nil
- varpat = /\$\((\w+)\)|\$\{(\w+)\}/
- if varpat =~ command
- vars = Hash.new {|h, k| h[k] = ENV[k]}
- command = command.dup
- nil while command.gsub!(varpat) {vars[$1||$2]}
- end
- Logging::open do
- puts command.quote
- if opts and opts[:werror]
- result = nil
- Logging.postpone do |log|
- result = (system(libpath_env, command) and File.zero?(log.path))
- ""
- end
- result
- else
- system(libpath_env, command)
- end
- end
- end
-
- def xpopen command, *mode, &block
- Logging::open do
- case mode[0]
- when nil, /^r/
- puts "#{command} |"
- else
- puts "| #{command}"
- end
- IO.popen(libpath_env, command, *mode, &block)
- end
- end
-
- def log_src(src, heading="checked program was")
- src = src.split(/^/)
- fmt = "%#{src.size.to_s.size}d: %s"
- Logging::message <<"EOM"
-#{heading}:
-/* begin */
-EOM
- src.each_with_index {|line, no| Logging::message fmt, no+1, line}
- Logging::message <<"EOM"
-/* end */
-
-EOM
- end
-
- def create_tmpsrc(src)
- src = "#{COMMON_HEADERS}\n#{src}"
- src = yield(src) if block_given?
- src.gsub!(/[ \t]+$/, '')
- src.gsub!(/\A\n+|^\n+$/, '')
- src.sub!(/[^\n]\z/, "\\&\n")
- count = 0
- begin
- open(CONFTEST_C, "wb") do |cfile|
- cfile.print src
- end
- rescue Errno::EACCES
- if (count += 1) < 5
- sleep 0.2
- retry
- end
- end
- src
- end
-
- def have_devel?
- unless defined? $have_devel
- $have_devel = true
- $have_devel = try_link(MAIN_DOES_NOTHING)
- end
- $have_devel
- end
-
- def try_do(src, command, *opts, &b)
- unless have_devel?
- raise < $hdrdir.quote,
- 'src' => "#{CONFTEST_C}",
- 'arch_hdrdir' => $arch_hdrdir.quote,
- 'top_srcdir' => $top_srcdir.quote,
- 'INCFLAGS' => "#$INCFLAGS",
- 'CPPFLAGS' => "#$CPPFLAGS",
- 'CFLAGS' => "#$CFLAGS",
- 'ARCH_FLAG' => "#$ARCH_FLAG",
- 'LDFLAGS' => "#$LDFLAGS #{ldflags}",
- 'LOCAL_LIBS' => "#$LOCAL_LIBS #$libs",
- 'LIBS' => "#{librubyarg} #{opt} #$LIBS")
- conf['LIBPATH'] = libpathflag(libpath.map {|s| RbConfig::expand(s.dup, conf)})
- RbConfig::expand(TRY_LINK.dup, conf)
- end
-
- def cc_command(opt="")
- conf = RbConfig::CONFIG.merge('hdrdir' => $hdrdir.quote, 'srcdir' => $srcdir.quote,
- 'arch_hdrdir' => $arch_hdrdir.quote,
- 'top_srcdir' => $top_srcdir.quote)
- RbConfig::expand("$(CC) #$INCFLAGS #$CPPFLAGS #$CFLAGS #$ARCH_FLAG #{opt} -c #{CONFTEST_C}",
- conf)
- end
-
- def cpp_command(outfile, opt="")
- conf = RbConfig::CONFIG.merge('hdrdir' => $hdrdir.quote, 'srcdir' => $srcdir.quote,
- 'arch_hdrdir' => $arch_hdrdir.quote,
- 'top_srcdir' => $top_srcdir.quote)
- if $universal and (arch_flag = conf['ARCH_FLAG']) and !arch_flag.empty?
- conf['ARCH_FLAG'] = arch_flag.gsub(/(?:\G|\s)-arch\s+\S+/, '')
- end
- RbConfig::expand("$(CPP) #$INCFLAGS #$CPPFLAGS #$CFLAGS #{opt} #{CONFTEST_C} #{outfile}",
- conf)
- end
-
- def libpathflag(libpath=$LIBPATH|$DEFLIBPATH)
- libpath.map{|x|
- case x
- when "$(topdir)", /\A\./
- LIBPATHFLAG
- else
- LIBPATHFLAG+RPATHFLAG
- end % x.quote
- }.join
- end
-
- def with_werror(opt, opts = nil)
- if opts
- if opts[:werror] and config_string("WERRORFLAG") {|flag| opt = opt ? "#{opt} #{flag}" : flag}
- (opts = opts.dup).delete(:werror)
- end
- yield(opt, opts)
- else
- yield(opt)
- end
- end
-
- def try_link0(src, opt="", *opts, &b) # :nodoc:
- cmd = link_command("", opt)
- if $universal
- require 'tmpdir'
- Dir.mktmpdir("mkmf_", oldtmpdir = ENV["TMPDIR"]) do |tmpdir|
- begin
- ENV["TMPDIR"] = tmpdir
- try_do(src, cmd, *opts, &b)
- ensure
- ENV["TMPDIR"] = oldtmpdir
- end
- end
- else
- try_do(src, cmd, *opts, &b)
- end and File.executable?(CONFTEST+$EXEEXT)
- end
-
- # Returns whether or not the +src+ can be compiled as a C source and linked
- # with its depending libraries successfully. +opt+ is passed to the linker
- # as options. Note that +$CFLAGS+ and +$LDFLAGS+ are also passed to the
- # linker.
- #
- # If a block given, it is called with the source before compilation. You can
- # modify the source in the block.
- #
- # [+src+] a String which contains a C source
- # [+opt+] a String which contains linker options
- def try_link(src, opt="", *opts, &b)
- try_link0(src, opt, *opts, &b)
- ensure
- MakeMakefile.rm_f "#{CONFTEST}*", "c0x32*"
- end
-
- # Returns whether or not the +src+ can be compiled as a C source. +opt+ is
- # passed to the C compiler as options. Note that +$CFLAGS+ is also passed to
- # the compiler.
- #
- # If a block given, it is called with the source before compilation. You can
- # modify the source in the block.
- #
- # [+src+] a String which contains a C source
- # [+opt+] a String which contains compiler options
- def try_compile(src, opt="", *opts, &b)
- with_werror(opt, *opts) {|_opt, *_opts| try_do(src, cc_command(_opt), *_opts, &b)} and
- File.file?("#{CONFTEST}.#{$OBJEXT}")
- ensure
- MakeMakefile.rm_f "#{CONFTEST}*"
- end
-
- # Returns whether or not the +src+ can be preprocessed with the C
- # preprocessor. +opt+ is passed to the preprocessor as options. Note that
- # +$CFLAGS+ is also passed to the preprocessor.
- #
- # If a block given, it is called with the source before preprocessing. You
- # can modify the source in the block.
- #
- # [+src+] a String which contains a C source
- # [+opt+] a String which contains preprocessor options
- def try_cpp(src, opt="", *opts, &b)
- try_do(src, cpp_command(CPPOUTFILE, opt), *opts, &b) and
- File.file?("#{CONFTEST}.i")
- ensure
- MakeMakefile.rm_f "#{CONFTEST}*"
- end
-
- alias_method :try_header, (config_string('try_header') || :try_cpp)
-
- def cpp_include(header)
- if header
- header = [header] unless header.kind_of? Array
- header.map {|h| String === h ? "#include <#{h}>\n" : h}.join
- else
- ""
- end
- end
-
- def with_cppflags(flags)
- cppflags = $CPPFLAGS
- $CPPFLAGS = flags
- ret = yield
- ensure
- $CPPFLAGS = cppflags unless ret
- end
-
- def try_cppflags(flags)
- try_header(MAIN_DOES_NOTHING, flags)
- end
-
- def with_cflags(flags)
- cflags = $CFLAGS
- $CFLAGS = flags
- ret = yield
- ensure
- $CFLAGS = cflags unless ret
- end
-
- def try_cflags(flags)
- try_compile(MAIN_DOES_NOTHING, flags)
- end
-
- def with_ldflags(flags)
- ldflags = $LDFLAGS
- $LDFLAGS = flags
- ret = yield
- ensure
- $LDFLAGS = ldflags unless ret
- end
-
- def try_ldflags(flags)
- try_link(MAIN_DOES_NOTHING, flags)
- end
-
- def try_static_assert(expr, headers = nil, opt = "", &b)
- headers = cpp_include(headers)
- try_compile(< 0", headers, opt)
- # positive constant
- elsif try_static_assert("#{const} == 0", headers, opt)
- return 0
- else
- # not a constant
- return nil
- end
- upper = 1
- until try_static_assert("#{const} <= #{upper}", headers, opt)
- lower = upper
- upper <<= 1
- end
- return nil unless lower
- while upper > lower + 1
- mid = (upper + lower) / 2
- if try_static_assert("#{const} > #{mid}", headers, opt)
- lower = mid
- else
- upper = mid
- end
- end
- upper = -upper if neg
- return upper
- else
- src = %{#{includes}
-#include
-/*top*/
-typedef#{neg ? '' : ' unsigned'}
-#ifdef PRI_LL_PREFIX
-#define PRI_CONFTEST_PREFIX PRI_LL_PREFIX
-LONG_LONG
-#else
-#define PRI_CONFTEST_PREFIX "l"
-long
-#endif
-conftest_type;
-conftest_type conftest_const = (conftest_type)(#{const});
-int main() {printf("%"PRI_CONFTEST_PREFIX"#{neg ? 'd' : 'u'}\\n", conftest_const); return 0;}
-}
- begin
- if try_link0(src, opt, &b)
- xpopen("./#{CONFTEST}") do |f|
- return Integer(f.gets)
- end
- end
- ensure
- MakeMakefile.rm_f "#{CONFTEST}*"
- end
- end
- nil
- end
-
- # You should use +have_func+ rather than +try_func+.
- #
- # [+func+] a String which contains a symbol name
- # [+libs+] a String which contains library names.
- # [+headers+] a String or an Array of strings which contains names of header
- # files.
- def try_func(func, libs, headers = nil, opt = "", &b)
- headers = cpp_include(headers)
- case func
- when /^&/
- decltype = proc {|x|"const volatile void *#{x}"}
- when /\)$/
- call = func
- else
- call = "#{func}()"
- decltype = proc {|x| "void ((*#{x})())"}
- end
- if opt and !opt.empty?
- [[:to_str], [:join, " "], [:to_s]].each do |meth, *args|
- if opt.respond_to?(meth)
- break opt = opt.send(meth, *args)
- end
- end
- opt = "#{opt} #{libs}"
- else
- opt = libs
- end
- decltype && try_link(<<"SRC", opt, &b) or
-#{headers}
-/*top*/
-extern int t(void);
-#{MAIN_DOES_NOTHING 't'}
-int t(void) { #{decltype["volatile p"]}; p = (#{decltype[]})#{func}; return 0; }
-SRC
- call && try_link(<<"SRC", opt, &b)
-#{headers}
-/*top*/
-extern int t(void);
-#{MAIN_DOES_NOTHING 't'}
-int t(void) { #{call}; return 0; }
-SRC
- end
-
- # You should use +have_var+ rather than +try_var+.
- def try_var(var, headers = nil, opt = "", &b)
- headers = cpp_include(headers)
- try_compile(<<"SRC", opt, &b)
-#{headers}
-/*top*/
-extern int t(void);
-#{MAIN_DOES_NOTHING 't'}
-int t(void) { const volatile void *volatile p; p = &({var})[0]; return 0; }
-SRC
- end
-
- # Returns whether or not the +src+ can be preprocessed with the C
- # preprocessor and matches with +pat+.
- #
- # If a block given, it is called with the source before compilation. You can
- # modify the source in the block.
- #
- # [+pat+] a Regexp or a String
- # [+src+] a String which contains a C source
- # [+opt+] a String which contains preprocessor options
- #
- # NOTE: When pat is a Regexp the matching will be checked in process,
- # otherwise egrep(1) will be invoked to check it.
- def egrep_cpp(pat, src, opt = "", &b)
- src = create_tmpsrc(src, &b)
- xpopen(cpp_command('', opt)) do |f|
- if Regexp === pat
- puts(" ruby -ne 'print if #{pat.inspect}'")
- f.grep(pat) {|l|
- puts "#{f.lineno}: #{l}"
- return true
- }
- false
- else
- puts(" egrep '#{pat}'")
- begin
- stdin = $stdin.dup
- $stdin.reopen(f)
- system("egrep", pat)
- ensure
- $stdin.reopen(stdin)
- end
- end
- end
- ensure
- MakeMakefile.rm_f "#{CONFTEST}*"
- log_src(src)
- end
-
- # This is used internally by the have_macro? method.
- def macro_defined?(macro, src, opt = "", &b)
- src = src.sub(/[^\n]\z/, "\\&\n")
- try_compile(src + <<"SRC", opt, &b)
-/*top*/
-#ifndef #{macro}
-# error
-|:/ === #{macro} undefined === /:|
-#endif
-SRC
- end
-
- # Returns whether or not:
- # * the +src+ can be compiled as a C source,
- # * the result object can be linked with its depending libraries
- # successfully,
- # * the linked file can be invoked as an executable
- # * and the executable exits successfully
- #
- # +opt+ is passed to the linker as options. Note that +$CFLAGS+ and
- # +$LDFLAGS+ are also passed to the linker.
- #
- # If a block given, it is called with the source before compilation. You can
- # modify the source in the block.
- #
- # [+src+] a String which contains a C source
- # [+opt+] a String which contains linker options
- #
- # Returns true when the executable exits successfully, false when it fails,
- # or nil when preprocessing, compilation or link fails.
- def try_run(src, opt = "", &b)
- raise "cannot run test program while cross compiling" if CROSS_COMPILING
- if try_link0(src, opt, &b)
- xsystem("./#{CONFTEST}")
- else
- nil
- end
- ensure
- MakeMakefile.rm_f "#{CONFTEST}*"
- end
-
- def install_files(mfile, ifiles, map = nil, srcprefix = nil)
- ifiles or return
- ifiles.empty? and return
- srcprefix ||= "$(srcdir)/#{srcprefix}".chomp('/')
- RbConfig::expand(srcdir = srcprefix.dup)
- dirs = []
- path = Hash.new {|h, i| h[i] = dirs.push([i])[-1]}
- ifiles.each do |files, dir, prefix|
- dir = map_dir(dir, map)
- prefix &&= %r|\A#{Regexp.quote(prefix)}/?|
- if /\A\.\// =~ files
- # install files which are in current working directory.
- files = files[2..-1]
- len = nil
- else
- # install files which are under the $(srcdir).
- files = File.join(srcdir, files)
- len = srcdir.size
- end
- f = nil
- Dir.glob(files) do |fx|
- f = fx
- f[0..len] = "" if len
- case File.basename(f)
- when *$NONINSTALLFILES
- next
- end
- d = File.dirname(f)
- d.sub!(prefix, "") if prefix
- d = (d.empty? || d == ".") ? dir : File.join(dir, d)
- f = File.join(srcprefix, f) if len
- path[d] << f
- end
- unless len or f
- d = File.dirname(files)
- d.sub!(prefix, "") if prefix
- d = (d.empty? || d == ".") ? dir : File.join(dir, d)
- path[d] << files
- end
- end
- dirs
- end
-
- def install_rb(mfile, dest, srcdir = nil)
- install_files(mfile, [["lib/**/*.rb", dest, "lib"]], nil, srcdir)
- end
-
- def append_library(libs, lib) # :no-doc:
- format(LIBARG, lib) + " " + libs
- end
-
- def message(*s)
- unless Logging.quiet and not $VERBOSE
- printf(*s)
- $stdout.flush
- end
- end
-
- # This emits a string to stdout that allows users to see the results of the
- # various have* and find* methods as they are tested.
- #
- # Internal use only.
- #
- def checking_for(m, fmt = nil)
- f = caller[0][/in `([^<].*)'$/, 1] and f << ": " #` for vim #'
- m = "checking #{/\Acheck/ =~ f ? '' : 'for '}#{m}... "
- message "%s", m
- a = r = nil
- Logging::postpone do
- r = yield
- a = (fmt ? "#{fmt % r}" : r ? "yes" : "no") << "\n"
- "#{f}#{m}-------------------- #{a}\n"
- end
- message(a)
- Logging::message "--------------------\n\n"
- r
- end
-
- def checking_message(target, place = nil, opt = nil)
- [["in", place], ["with", opt]].inject("#{target}") do |msg, (pre, noun)|
- if noun
- [[:to_str], [:join, ","], [:to_s]].each do |meth, *args|
- if noun.respond_to?(meth)
- break noun = noun.send(meth, *args)
- end
- end
- msg << " #{pre} #{noun}" unless noun.empty?
- end
- msg
- end
- end
-
- # :startdoc:
-
- # Returns whether or not +macro+ is defined either in the common header
- # files or within any +headers+ you provide.
- #
- # Any options you pass to +opt+ are passed along to the compiler.
- #
- def have_macro(macro, headers = nil, opt = "", &b)
- checking_for checking_message(macro, headers, opt) do
- macro_defined?(macro, cpp_include(headers), opt, &b)
- end
- end
-
- # Returns whether or not the given entry point +func+ can be found within
- # +lib+. If +func+ is +nil+, the main()
entry point is used by
- # default. If found, it adds the library to list of libraries to be used
- # when linking your extension.
- #
- # If +headers+ are provided, it will include those header files as the
- # header files it looks in when searching for +func+.
- #
- # The real name of the library to be linked can be altered by
- # --with-FOOlib
configuration option.
- #
- def have_library(lib, func = nil, headers = nil, opt = "", &b)
- func = "main" if !func or func.empty?
- lib = with_config(lib+'lib', lib)
- checking_for checking_message(func.funcall_style, LIBARG%lib, opt) do
- if COMMON_LIBS.include?(lib)
- true
- else
- libs = append_library($libs, lib)
- if try_func(func, libs, headers, opt, &b)
- $libs = libs
- true
- else
- false
- end
- end
- end
- end
-
- # Returns whether or not the entry point +func+ can be found within the
- # library +lib+ in one of the +paths+ specified, where +paths+ is an array
- # of strings. If +func+ is +nil+ , then the main()
function is
- # used as the entry point.
- #
- # If +lib+ is found, then the path it was found on is added to the list of
- # library paths searched and linked against.
- #
- def find_library(lib, func, *paths, &b)
- func = "main" if !func or func.empty?
- lib = with_config(lib+'lib', lib)
- paths = paths.collect {|path| path.split(File::PATH_SEPARATOR)}.flatten
- checking_for checking_message(func.funcall_style, LIBARG%lib) do
- libpath = $LIBPATH
- libs = append_library($libs, lib)
- begin
- until r = try_func(func, libs, &b) or paths.empty?
- $LIBPATH = libpath | [paths.shift]
- end
- if r
- $libs = libs
- libpath = nil
- end
- ensure
- $LIBPATH = libpath if libpath
- end
- r
- end
- end
-
- # Returns whether or not the function +func+ can be found in the common
- # header files, or within any +headers+ that you provide. If found, a macro
- # is passed as a preprocessor constant to the compiler using the function
- # name, in uppercase, prepended with +HAVE_+.
- #
- # To check functions in an additional library, you need to check that
- # library first using have_library()
. The +func+ shall be
- # either mere function name or function name with arguments.
- #
- # For example, if have_func('foo')
returned +true+, then the
- # +HAVE_FOO+ preprocessor macro would be passed to the compiler.
- #
- def have_func(func, headers = nil, opt = "", &b)
- checking_for checking_message(func.funcall_style, headers, opt) do
- if try_func(func, $libs, headers, opt, &b)
- $defs << "-DHAVE_#{func.sans_arguments.tr_cpp}"
- true
- else
- false
- end
- end
- end
-
- # Returns whether or not the variable +var+ can be found in the common
- # header files, or within any +headers+ that you provide. If found, a macro
- # is passed as a preprocessor constant to the compiler using the variable
- # name, in uppercase, prepended with +HAVE_+.
- #
- # To check variables in an additional library, you need to check that
- # library first using have_library()
.
- #
- # For example, if have_var('foo')
returned true, then the
- # +HAVE_FOO+ preprocessor macro would be passed to the compiler.
- #
- def have_var(var, headers = nil, opt = "", &b)
- checking_for checking_message(var, headers, opt) do
- if try_var(var, headers, opt, &b)
- $defs.push(format("-DHAVE_%s", var.tr_cpp))
- true
- else
- false
- end
- end
- end
-
- # Returns whether or not the given +header+ file can be found on your system.
- # If found, a macro is passed as a preprocessor constant to the compiler
- # using the header file name, in uppercase, prepended with +HAVE_+.
- #
- # For example, if have_header('foo.h')
returned true, then the
- # +HAVE_FOO_H+ preprocessor macro would be passed to the compiler.
- #
- def have_header(header, preheaders = nil, opt = "", &b)
- checking_for header do
- if try_header(cpp_include(preheaders)+cpp_include(header), opt, &b)
- $defs.push(format("-DHAVE_%s", header.tr_cpp))
- true
- else
- false
- end
- end
- end
-
- # Returns whether or not the given +framework+ can be found on your system.
- # If found, a macro is passed as a preprocessor constant to the compiler
- # using the framework name, in uppercase, prepended with +HAVE_FRAMEWORK_+.
- #
- # For example, if have_framework('Ruby')
returned true, then
- # the +HAVE_FRAMEWORK_RUBY+ preprocessor macro would be passed to the
- # compiler.
- #
- # If +fw+ is a pair of the framework name and its header file name
- # that header file is checked, instead of the normally used header
- # file which is named same as the framework.
- def have_framework(fw, &b)
- if Array === fw
- fw, header = *fw
- else
- header = "#{fw}.h"
- end
- checking_for fw do
- src = cpp_include("#{fw}/#{header}") << "\n" "int main(void){return 0;}"
- opt = " -framework #{fw}"
- if try_link(src, opt, &b) or (objc = try_link(src, "-ObjC#{opt}", &b))
- $defs.push(format("-DHAVE_FRAMEWORK_%s", fw.tr_cpp))
- # TODO: non-worse way than this hack, to get rid of separating
- # option and its argument.
- $LDFLAGS << " -ObjC" if objc and /(\A|\s)-ObjC(\s|\z)/ !~ $LDFLAGS
- $LIBS << opt
- true
- else
- false
- end
- end
- end
-
- # Instructs mkmf to search for the given +header+ in any of the +paths+
- # provided, and returns whether or not it was found in those paths.
- #
- # If the header is found then the path it was found on is added to the list
- # of included directories that are sent to the compiler (via the
- # -I
switch).
- #
- def find_header(header, *paths)
- message = checking_message(header, paths)
- header = cpp_include(header)
- checking_for message do
- if try_header(header)
- true
- else
- found = false
- paths.each do |dir|
- opt = "-I#{dir}".quote
- if try_header(header, opt)
- $INCFLAGS << " " << opt
- found = true
- break
- end
- end
- found
- end
- end
- end
-
- # Returns whether or not the struct of type +type+ contains +member+. If
- # it does not, or the struct type can't be found, then false is returned.
- # You may optionally specify additional +headers+ in which to look for the
- # struct (in addition to the common header files).
- #
- # If found, a macro is passed as a preprocessor constant to the compiler
- # using the type name and the member name, in uppercase, prepended with
- # +HAVE_+.
- #
- # For example, if have_struct_member('struct foo', 'bar')
- # returned true, then the +HAVE_STRUCT_FOO_BAR+ preprocessor macro would be
- # passed to the compiler.
- #
- # +HAVE_ST_BAR+ is also defined for backward compatibility.
- #
- def have_struct_member(type, member, headers = nil, opt = "", &b)
- checking_for checking_message("#{type}.#{member}", headers) do
- if try_compile(<<"SRC", opt, &b)
-#{cpp_include(headers)}
-/*top*/
-int s = (char *)&((#{type}*)0)->#{member} - (char *)0;
-#{MAIN_DOES_NOTHING}
-SRC
- $defs.push(format("-DHAVE_%s_%s", type.tr_cpp, member.tr_cpp))
- $defs.push(format("-DHAVE_ST_%s", member.tr_cpp)) # backward compatibility
- true
- else
- false
- end
- end
- end
-
- # Returns whether or not the static type +type+ is defined.
- #
- # See also +have_type+
- #
- def try_type(type, headers = nil, opt = "", &b)
- if try_compile(<<"SRC", opt, &b)
-#{cpp_include(headers)}
-/*top*/
-typedef #{type} conftest_type;
-int conftestval[sizeof(conftest_type)?1:-1];
-SRC
- $defs.push(format("-DHAVE_TYPE_%s", type.tr_cpp))
- true
- else
- false
- end
- end
-
- # Returns whether or not the static type +type+ is defined. You may
- # optionally pass additional +headers+ to check against in addition to the
- # common header files.
- #
- # You may also pass additional flags to +opt+ which are then passed along to
- # the compiler.
- #
- # If found, a macro is passed as a preprocessor constant to the compiler
- # using the type name, in uppercase, prepended with +HAVE_TYPE_+.
- #
- # For example, if have_type('foo')
returned true, then the
- # +HAVE_TYPE_FOO+ preprocessor macro would be passed to the compiler.
- #
- def have_type(type, headers = nil, opt = "", &b)
- checking_for checking_message(type, headers, opt) do
- try_type(type, headers, opt, &b)
- end
- end
-
- # Returns where the static type +type+ is defined.
- #
- # You may also pass additional flags to +opt+ which are then passed along to
- # the compiler.
- #
- # See also +have_type+.
- #
- def find_type(type, opt, *headers, &b)
- opt ||= ""
- fmt = "not found"
- def fmt.%(x)
- x ? x.respond_to?(:join) ? x.join(",") : x : self
- end
- checking_for checking_message(type, nil, opt), fmt do
- headers.find do |h|
- try_type(type, h, opt, &b)
- end
- end
- end
-
- # Returns whether or not the constant +const+ is defined.
- #
- # See also +have_const+
- #
- def try_const(const, headers = nil, opt = "", &b)
- const, type = *const
- if try_compile(<<"SRC", opt, &b)
-#{cpp_include(headers)}
-/*top*/
-typedef #{type || 'int'} conftest_type;
-conftest_type conftestval = #{type ? '' : '(int)'}#{const};
-SRC
- $defs.push(format("-DHAVE_CONST_%s", const.tr_cpp))
- true
- else
- false
- end
- end
-
- # Returns whether or not the constant +const+ is defined. You may
- # optionally pass the +type+ of +const+ as [const, type]
,
- # such as:
- #
- # have_const(%w[PTHREAD_MUTEX_INITIALIZER pthread_mutex_t], "pthread.h")
- #
- # You may also pass additional +headers+ to check against in addition to the
- # common header files, and additional flags to +opt+ which are then passed
- # along to the compiler.
- #
- # If found, a macro is passed as a preprocessor constant to the compiler
- # using the type name, in uppercase, prepended with +HAVE_CONST_+.
- #
- # For example, if have_const('foo')
returned true, then the
- # +HAVE_CONST_FOO+ preprocessor macro would be passed to the compiler.
- #
- def have_const(const, headers = nil, opt = "", &b)
- checking_for checking_message([*const].compact.join(' '), headers, opt) do
- try_const(const, headers, opt, &b)
- end
- end
-
- # :stopdoc:
- STRING_OR_FAILED_FORMAT = "%s"
- def STRING_OR_FAILED_FORMAT.%(x) # :nodoc:
- x ? super : "failed"
- end
-
- def typedef_expr(type, headers)
- typename, member = type.split('.', 2)
- prelude = cpp_include(headers).split(/$/)
- prelude << "typedef #{typename} rbcv_typedef_;\n"
- return "rbcv_typedef_", member, prelude
- end
-
- def try_signedness(type, member, headers = nil, opts = nil)
- raise ArgumentError, "don't know how to tell signedness of members" if member
- if try_static_assert("(#{type})-1 < 0", headers, opts)
- return -1
- elsif try_static_assert("(#{type})-1 > 0", headers, opts)
- return +1
- end
- end
-
- # :startdoc:
-
- # Returns the size of the given +type+. You may optionally specify
- # additional +headers+ to search in for the +type+.
- #
- # If found, a macro is passed as a preprocessor constant to the compiler
- # using the type name, in uppercase, prepended with +SIZEOF_+, followed by
- # the type name, followed by =X
where "X" is the actual size.
- #
- # For example, if check_sizeof('mystruct')
returned 12, then
- # the SIZEOF_MYSTRUCT=12
preprocessor macro would be passed to
- # the compiler.
- #
- def check_sizeof(type, headers = nil, opts = "", &b)
- typedef, member, prelude = typedef_expr(type, headers)
- prelude << "static #{typedef} *rbcv_ptr_;\n"
- prelude = [prelude]
- expr = "sizeof((*rbcv_ptr_)#{"." << member if member})"
- fmt = STRING_OR_FAILED_FORMAT
- checking_for checking_message("size of #{type}", headers), fmt do
- if size = try_constant(expr, prelude, opts, &b)
- $defs.push(format("-DSIZEOF_%s=%s", type.tr_cpp, size))
- size
- end
- end
- end
-
- # Returns the signedness of the given +type+. You may optionally specify
- # additional +headers+ to search in for the +type+.
- #
- # If the +type+ is found and is a numeric type, a macro is passed as a
- # preprocessor constant to the compiler using the +type+ name, in uppercase,
- # prepended with +SIGNEDNESS_OF_+, followed by the +type+ name, followed by
- # =X
where "X" is positive integer if the +type+ is unsigned
- # and a negative integer if the +type+ is signed.
- #
- # For example, if +size_t+ is defined as unsigned, then
- # check_signedness('size_t')
would return +1 and the
- # SIGNEDNESS_OF_SIZE_T=+1
preprocessor macro would be passed to
- # the compiler. The SIGNEDNESS_OF_INT=-1
macro would be set
- # for check_signedness('int')
- #
- def check_signedness(type, headers = nil, opts = nil, &b)
- typedef, member, prelude = typedef_expr(type, headers)
- signed = nil
- checking_for("signedness of #{type}", STRING_OR_FAILED_FORMAT) do
- signed = try_signedness(typedef, member, [prelude], opts, &b) or next nil
- $defs.push("-DSIGNEDNESS_OF_%s=%+d" % [type.tr_cpp, signed])
- signed < 0 ? "signed" : "unsigned"
- end
- signed
- end
-
- # Returns the convertible integer type of the given +type+. You may
- # optionally specify additional +headers+ to search in for the +type+.
- # _convertible_ means actually the same type, or typedef'd from the same
- # type.
- #
- # If the +type+ is a integer type and the _convertible_ type is found,
- # the following macros are passed as preprocessor constants to the compiler
- # using the +type+ name, in uppercase.
- #
- # * +TYPEOF_+, followed by the +type+ name, followed by =X
- # where "X" is the found _convertible_ type name.
- # * +TYP2NUM+ and +NUM2TYP+,
- # where +TYP+ is the +type+ name in uppercase with replacing an +_t+
- # suffix with "T", followed by =X
where "X" is the macro name
- # to convert +type+ to an Integer object, and vice versa.
- #
- # For example, if +foobar_t+ is defined as unsigned long, then
- # convertible_int("foobar_t")
would return "unsigned long", and
- # define these macros:
- #
- # #define TYPEOF_FOOBAR_T unsigned long
- # #define FOOBART2NUM ULONG2NUM
- # #define NUM2FOOBART NUM2ULONG
- #
- def convertible_int(type, headers = nil, opts = nil, &b)
- type, macname = *type
- checking_for("convertible type of #{type}", STRING_OR_FAILED_FORMAT) do
- if UNIVERSAL_INTS.include?(type)
- type
- else
- typedef, member, prelude = typedef_expr(type, headers, &b)
- if member
- prelude << "static rbcv_typedef_ rbcv_var;"
- compat = UNIVERSAL_INTS.find {|t|
- try_static_assert("sizeof(rbcv_var.#{member}) == sizeof(#{t})", [prelude], opts, &b)
- }
- else
- next unless signed = try_signedness(typedef, member, [prelude])
- u = "unsigned " if signed > 0
- prelude << "extern rbcv_typedef_ foo();"
- compat = UNIVERSAL_INTS.find {|t|
- try_compile([prelude, "extern #{u}#{t} foo();"].join("\n"), opts, :werror=>true, &b)
- }
- end
- if compat
- macname ||= type.sub(/_(?=t\z)/, '').tr_cpp
- conv = (compat == "long long" ? "LL" : compat.upcase)
- compat = "#{u}#{compat}"
- typename = type.tr_cpp
- $defs.push(format("-DSIZEOF_%s=SIZEOF_%s", typename, compat.tr_cpp))
- $defs.push(format("-DTYPEOF_%s=%s", typename, compat.quote))
- $defs.push(format("-DPRI_%s_PREFIX=PRI_%s_PREFIX", macname, conv))
- conv = (u ? "U" : "") + conv
- $defs.push(format("-D%s2NUM=%s2NUM", macname, conv))
- $defs.push(format("-DNUM2%s=NUM2%s", macname, conv))
- compat
- end
- end
- end
- end
- # :stopdoc:
-
- # Used internally by the what_type? method to determine if +type+ is a scalar
- # pointer.
- def scalar_ptr_type?(type, member = nil, headers = nil, &b)
- try_compile(<<"SRC", &b) # pointer
-#{cpp_include(headers)}
-/*top*/
-volatile #{type} conftestval;
-extern int t(void);
-#{MAIN_DOES_NOTHING 't'}
-int t(void) {return (int)(1-*(conftestval#{member ? ".#{member}" : ""}));}
-SRC
- end
-
- # Used internally by the what_type? method to determine if +type+ is a scalar
- # pointer.
- def scalar_type?(type, member = nil, headers = nil, &b)
- try_compile(<<"SRC", &b) # pointer
-#{cpp_include(headers)}
-/*top*/
-volatile #{type} conftestval;
-extern int t(void);
-#{MAIN_DOES_NOTHING 't'}
-int t(void) {return (int)(1-(conftestval#{member ? ".#{member}" : ""}));}
-SRC
- end
-
- # Used internally by the what_type? method to check if the _typeof_ GCC
- # extension is available.
- def have_typeof?
- return $typeof if defined?($typeof)
- $typeof = %w[__typeof__ typeof].find do |t|
- try_compile(<--with-_config_ or
- # --without-_config_ option. Returns +true+ if the with option is
- # given, +false+ if the without option is given, and the default value
- # otherwise.
- #
- # This can be useful for adding custom definitions, such as debug
- # information.
- #
- # Example:
- #
- # if with_config("debug")
- # $defs.push("-DOSSL_DEBUG") unless $defs.include? "-DOSSL_DEBUG"
- # end
- #
- def with_config(config, default=nil)
- config = config.sub(/^--with[-_]/, '')
- val = arg_config("--with-"+config) do
- if arg_config("--without-"+config)
- false
- elsif block_given?
- yield(config, default)
- else
- break default
- end
- end
- case val
- when "yes"
- true
- when "no"
- false
- else
- val
- end
- end
-
- # Tests for the presence of an --enable-_config_ or
- # --disable-_config_ option. Returns +true+ if the enable option is
- # given, +false+ if the disable option is given, and the default value
- # otherwise.
- #
- # This can be useful for adding custom definitions, such as debug
- # information.
- #
- # Example:
- #
- # if enable_config("debug")
- # $defs.push("-DOSSL_DEBUG") unless $defs.include? "-DOSSL_DEBUG"
- # end
- #
- def enable_config(config, default=nil)
- if arg_config("--enable-"+config)
- true
- elsif arg_config("--disable-"+config)
- false
- elsif block_given?
- yield(config, default)
- else
- return default
- end
- end
-
- # Generates a header file consisting of the various macro definitions
- # generated by other methods such as have_func and have_header. These are
- # then wrapped in a custom #ifndef
based on the +header+ file
- # name, which defaults to "extconf.h".
- #
- # For example:
- #
- # # extconf.rb
- # require 'mkmf'
- # have_func('realpath')
- # have_header('sys/utime.h')
- # create_header
- # create_makefile('foo')
- #
- # The above script would generate the following extconf.h file:
- #
- # #ifndef EXTCONF_H
- # #define EXTCONF_H
- # #define HAVE_REALPATH 1
- # #define HAVE_SYS_UTIME_H 1
- # #endif
- #
- # Given that the create_header method generates a file based on definitions
- # set earlier in your extconf.rb file, you will probably want to make this
- # one of the last methods you call in your script.
- #
- def create_header(header = "extconf.h")
- message "creating %s\n", header
- sym = header.tr_cpp
- hdr = ["#ifndef #{sym}\n#define #{sym}\n"]
- for line in $defs
- case line
- when /^-D([^=]+)(?:=(.*))?/
- hdr << "#define #$1 #{$2 ? Shellwords.shellwords($2)[0].gsub(/(?=\t+)/, "\\\n") : 1}\n"
- when /^-U(.*)/
- hdr << "#undef #$1\n"
- end
- end
- hdr << "#endif\n"
- hdr = hdr.join("")
- log_src(hdr, "#{header} is")
- unless (IO.read(header) == hdr rescue false)
- open(header, "wb") do |hfile|
- hfile.write(hdr)
- end
- end
- $extconf_h = header
- end
-
- # call-seq:
- # dir_config(target)
- # dir_config(target, prefix)
- # dir_config(target, idefault, ldefault)
- #
- # Sets a +target+ name that the user can then use to configure
- # various "with" options with on the command line by using that
- # name. For example, if the target is set to "foo", then the user
- # could use the --with-foo-dir=prefix
,
- # --with-foo-include=dir
and
- # --with-foo-lib=dir
command line options to tell where
- # to search for header/library files.
- #
- # You may pass along additional parameters to specify default
- # values. If one is given it is taken as default +prefix+, and if
- # two are given they are taken as "include" and "lib" defaults in
- # that order.
- #
- # In any case, the return value will be an array of determined
- # "include" and "lib" directories, either of which can be nil if no
- # corresponding command line option is given when no default value
- # is specified.
- #
- # Note that dir_config only adds to the list of places to search for
- # libraries and include files. It does not link the libraries into your
- # application.
- #
- def dir_config(target, idefault=nil, ldefault=nil)
- if dir = with_config(target + "-dir", (idefault unless ldefault))
- defaults = Array === dir ? dir : dir.split(File::PATH_SEPARATOR)
- idefault = ldefault = nil
- end
-
- idir = with_config(target + "-include", idefault)
- $arg_config.last[1] ||= "${#{target}-dir}/include"
- ldir = with_config(target + "-lib", ldefault)
- $arg_config.last[1] ||= "${#{target}-dir}/#{_libdir_basename}"
-
- idirs = idir ? Array === idir ? idir.dup : idir.split(File::PATH_SEPARATOR) : []
- if defaults
- idirs.concat(defaults.collect {|d| d + "/include"})
- idir = ([idir] + idirs).compact.join(File::PATH_SEPARATOR)
- end
- unless idirs.empty?
- idirs.collect! {|d| "-I" + d}
- idirs -= Shellwords.shellwords($CPPFLAGS)
- unless idirs.empty?
- $CPPFLAGS = (idirs.quote << $CPPFLAGS).join(" ")
- end
- end
-
- ldirs = ldir ? Array === ldir ? ldir.dup : ldir.split(File::PATH_SEPARATOR) : []
- if defaults
- ldirs.concat(defaults.collect {|d| "#{d}/#{_libdir_basename}"})
- ldir = ([ldir] + ldirs).compact.join(File::PATH_SEPARATOR)
- end
- $LIBPATH = ldirs | $LIBPATH
-
- [idir, ldir]
- end
-
- # Returns compile/link information about an installed library in a
- # tuple of [cflags, ldflags, libs]
, by using the
- # command found first in the following commands:
- #
- # 1. If --with-{pkg}-config={command}
is given via
- # command line option: {command} {option}
- #
- # 2. {pkg}-config {option}
- #
- # 3. pkg-config {option} {pkg}
- #
- # Where {option} is, for instance, --cflags
.
- #
- # The values obtained are appended to +$CFLAGS+, +$LDFLAGS+ and
- # +$libs+.
- #
- # If an option
argument is given, the config command is
- # invoked with the option and a stripped output string is returned
- # without modifying any of the global values mentioned above.
- def pkg_config(pkg, option=nil)
- if pkgconfig = with_config("#{pkg}-config") and find_executable0(pkgconfig)
- # iff package specific config command is given
- elsif ($PKGCONFIG ||=
- (pkgconfig = with_config("pkg-config", ("pkg-config" unless CROSS_COMPILING))) &&
- find_executable0(pkgconfig) && pkgconfig) and
- system("#{$PKGCONFIG} --exists #{pkg}")
- # default to pkg-config command
- pkgconfig = $PKGCONFIG
- get = proc {|opt|
- opt = IO.popen("#{$PKGCONFIG} --#{opt} #{pkg}", err:[:child, :out], &:read)
- opt.strip if $?.success?
- }
- elsif find_executable0(pkgconfig = "#{pkg}-config")
- # default to package specific config command, as a last resort.
- else
- pkgconfig = nil
- end
- if pkgconfig
- get ||= proc {|opt|
- opt = IO.popen("#{pkgconfig} --#{opt}", err:[:child, :out], &:read)
- opt.strip if $?.success?
- }
- end
- orig_ldflags = $LDFLAGS
- if get and option
- get[option]
- elsif get and try_ldflags(ldflags = get['libs'])
- if incflags = get['cflags-only-I']
- $INCFLAGS << " " << incflags
- cflags = get['cflags-only-other']
- else
- cflags = get['cflags']
- end
- libs = get['libs-only-l']
- if cflags
- $CFLAGS += " " << cflags
- $CXXFLAGS += " " << cflags
- end
- if libs
- ldflags = (Shellwords.shellwords(ldflags) - Shellwords.shellwords(libs)).quote.join(" ")
- else
- libs, ldflags = Shellwords.shellwords(ldflags).partition {|s| s =~ /-l([^ ]+)/ }.map {|l|l.quote.join(" ")}
- end
- $libs += " " << libs
-
- $LDFLAGS = [orig_ldflags, ldflags].join(' ')
- Logging::message "package configuration for %s\n", pkg
- Logging::message "cflags: %s\nldflags: %s\nlibs: %s\n\n",
- cflags, ldflags, libs
- [cflags, ldflags, libs]
- else
- Logging::message "package configuration for %s is not found\n", pkg
- nil
- end
- end
-
- # :stopdoc:
-
- def with_destdir(dir)
- dir = dir.sub($dest_prefix_pattern, '')
- /\A\$[\(\{]/ =~ dir ? dir : "$(DESTDIR)"+dir
- end
-
- # Converts forward slashes to backslashes. Aimed at MS Windows.
- #
- # Internal use only.
- #
- def winsep(s)
- s.tr('/', '\\')
- end
-
- # Converts native path to format acceptable in Makefile
- #
- # Internal use only.
- #
- if !CROSS_COMPILING
- case CONFIG['build_os']
- when 'mingw32'
- def mkintpath(path)
- # mingw uses make from msys and it needs special care
- # converts from C:\some\path to /C/some/path
- path = path.dup
- path.tr!('\\', '/')
- path.sub!(/\A([A-Za-z]):(?=\/)/, '/\1')
- path
- end
- when 'cygwin'
- if CONFIG['target_os'] != 'cygwin'
- def mkintpath(path)
- IO.popen(["cygpath", "-u", path], &:read).chomp
- end
- end
- end
- end
- unless method_defined?(:mkintpath)
- def mkintpath(path)
- path
- end
- end
-
- def configuration(srcdir)
- mk = []
- vpath = $VPATH.dup
- CONFIG["hdrdir"] ||= $hdrdir
- mk << %{
-SHELL = /bin/sh
-
-# V=0 quiet, V=1 verbose. other values don't work.
-V = 0
-Q1 = $(V:1=)
-Q = $(Q1:0=@)
-ECHO1 = $(V:1=@#{CONFIG['NULLCMD']})
-ECHO = $(ECHO1:0=@echo)
-NULLCMD = #{CONFIG['NULLCMD']}
-
-#### Start of system configuration section. ####
-#{"top_srcdir = " + $top_srcdir.sub(%r"\A#{Regexp.quote($topdir)}/", "$(topdir)/") if $extmk}
-srcdir = #{srcdir.gsub(/\$\((srcdir)\)|\$\{(srcdir)\}/) {mkintpath(CONFIG[$1||$2]).unspace}}
-topdir = #{mkintpath(topdir = $extmk ? CONFIG["topdir"] : $topdir).unspace}
-hdrdir = #{(hdrdir = CONFIG["hdrdir"]) == topdir ? "$(topdir)" : mkintpath(hdrdir).unspace}
-arch_hdrdir = #{$arch_hdrdir.quote}
-PATH_SEPARATOR = #{CONFIG['PATH_SEPARATOR']}
-VPATH = #{vpath.join(CONFIG['PATH_SEPARATOR'])}
-}
- if $extmk
- mk << "RUBYLIB =\n""RUBYOPT = -\n"
- end
- prefix = mkintpath(CONFIG["prefix"])
- if destdir = prefix[$dest_prefix_pattern, 1]
- mk << "\nDESTDIR = #{destdir}\n"
- prefix = prefix[destdir.size..-1]
- end
- mk << "prefix = #{with_destdir(prefix).unspace}\n"
- CONFIG.each do |key, var|
- mk << "#{key} = #{with_destdir(mkintpath(var)).unspace}\n" if /.prefix$/ =~ key
- end
- CONFIG.each do |key, var|
- next if /^abs_/ =~ key
- next if /^(?:src|top|hdr)dir$/ =~ key
- next unless /dir$/ =~ key
- mk << "#{key} = #{with_destdir(var)}\n"
- end
- if !$extmk and !$configure_args.has_key?('--ruby') and
- sep = config_string('BUILD_FILE_SEPARATOR')
- sep = ":/=#{sep}"
- else
- sep = ""
- end
- possible_command = (proc {|s| s if /top_srcdir/ !~ s} unless $extmk)
- extconf_h = $extconf_h ? "-DRUBY_EXTCONF_H=\\\"$(RUBY_EXTCONF_H)\\\" " : $defs.join(" ") << " "
- headers = %w[
- $(hdrdir)/ruby.h
- $(hdrdir)/ruby/ruby.h
- $(hdrdir)/ruby/defines.h
- $(hdrdir)/ruby/missing.h
- $(hdrdir)/ruby/intern.h
- $(hdrdir)/ruby/st.h
- $(hdrdir)/ruby/subst.h
- ]
- if RULE_SUBST
- headers.each {|h| h.sub!(/.*/, &RULE_SUBST.method(:%))}
- end
- headers << $config_h
- headers << '$(RUBY_EXTCONF_H)' if $extconf_h
- mk << %{
-
-CC = #{CONFIG['CC']}
-CXX = #{CONFIG['CXX']}
-LIBRUBY = #{CONFIG['LIBRUBY']}
-LIBRUBY_A = #{CONFIG['LIBRUBY_A']}
-LIBRUBYARG_SHARED = #$LIBRUBYARG_SHARED
-LIBRUBYARG_STATIC = #$LIBRUBYARG_STATIC
-empty =
-OUTFLAG = #{OUTFLAG}$(empty)
-COUTFLAG = #{COUTFLAG}$(empty)
-
-RUBY_EXTCONF_H = #{$extconf_h}
-cflags = #{CONFIG['cflags']}
-optflags = #{CONFIG['optflags']}
-debugflags = #{CONFIG['debugflags']}
-warnflags = #{$warnflags}
-CCDLFLAGS = #{$static ? '' : CONFIG['CCDLFLAGS']}
-CFLAGS = $(CCDLFLAGS) #$CFLAGS $(ARCH_FLAG)
-INCFLAGS = -I. #$INCFLAGS
-DEFS = #{CONFIG['DEFS']}
-CPPFLAGS = #{extconf_h}#{$CPPFLAGS}
-CXXFLAGS = $(CCDLFLAGS) #$CXXFLAGS $(ARCH_FLAG)
-ldflags = #{$LDFLAGS}
-dldflags = #{$DLDFLAGS} #{CONFIG['EXTDLDFLAGS']}
-ARCH_FLAG = #{$ARCH_FLAG}
-DLDFLAGS = $(ldflags) $(dldflags) $(ARCH_FLAG)
-LDSHARED = #{CONFIG['LDSHARED']}
-LDSHAREDXX = #{config_string('LDSHAREDXX') || '$(LDSHARED)'}
-AR = #{CONFIG['AR']}
-EXEEXT = #{CONFIG['EXEEXT']}
-
-}
- CONFIG.each do |key, val|
- mk << "#{key} = #{val}\n" if /^RUBY.*NAME/ =~ key
- end
- mk << %{
-arch = #{CONFIG['arch']}
-sitearch = #{CONFIG['sitearch']}
-ruby_version = #{RbConfig::CONFIG['ruby_version']}
-ruby = #{$ruby.sub(%r[\A#{Regexp.quote(RbConfig::CONFIG['bindir'])}(?=/|\z)]) {'$(bindir)'}}
-RUBY = $(ruby#{sep})
-ruby_headers = #{headers.join(' ')}
-
-RM = #{config_string('RM', &possible_command) || '$(RUBY) -run -e rm -- -f'}
-RM_RF = #{'$(RUBY) -run -e rm -- -rf'}
-RMDIRS = #{config_string('RMDIRS', &possible_command) || '$(RUBY) -run -e rmdir -- -p'}
-MAKEDIRS = #{config_string('MAKEDIRS', &possible_command) || '@$(RUBY) -run -e mkdir -- -p'}
-INSTALL = #{config_string('INSTALL', &possible_command) || '@$(RUBY) -run -e install -- -vp'}
-INSTALL_PROG = #{config_string('INSTALL_PROG') || '$(INSTALL) -m 0755'}
-INSTALL_DATA = #{config_string('INSTALL_DATA') || '$(INSTALL) -m 0644'}
-COPY = #{config_string('CP', &possible_command) || '@$(RUBY) -run -e cp -- -v'}
-TOUCH = exit >
-
-#### End of system configuration section. ####
-
-preload = #{defined?($preload) && $preload ? $preload.join(' ') : ''}
-}
- if $nmake == ?b
- mk.each do |x|
- x.gsub!(/^(MAKEDIRS|INSTALL_(?:PROG|DATA))+\s*=.*\n/) do
- "!ifndef " + $1 + "\n" +
- $& +
- "!endif\n"
- end
- end
- end
- mk
- end
-
- def timestamp_file(name, target_prefix = nil)
- if target_prefix
- pat = []
- install_dirs.each do |n, d|
- pat << n if /\$\(target_prefix\)\z/ =~ d
- end
- name = name.gsub(/\$\((#{pat.join("|")})\)/) {$&+target_prefix}
- end
- name = name.gsub(/(\$[({]|[})])|(\/+)|[^-.\w]+/) {$1 ? "" : $2 ? ".-." : "_"}
- "$(TIMESTAMP_DIR)/.#{name}.time"
- end
- # :startdoc:
-
- # creates a stub Makefile.
- #
- def dummy_makefile(srcdir)
- configuration(srcdir) << <require 'test/foo'.
- #
- # The +srcprefix+ should be used when your source files are not in the same
- # directory as your build script. This will not only eliminate the need for
- # you to manually copy the source files into the same directory as your
- # build script, but it also sets the proper +target_prefix+ in the generated
- # Makefile.
- #
- # Setting the +target_prefix+ will, in turn, install the generated binary in
- # a directory under your RbConfig::CONFIG['sitearchdir']
that
- # mimics your local filesystem when you run make install
.
- #
- # For example, given the following file tree:
- #
- # ext/
- # extconf.rb
- # test/
- # foo.c
- #
- # And given the following code:
- #
- # create_makefile('test/foo', 'test')
- #
- # That will set the +target_prefix+ in the generated Makefile to "test".
- # That, in turn, will create the following file tree when installed via the
- # make install
command:
- #
- # /path/to/ruby/sitearchdir/test/foo.so
- #
- # It is recommended that you use this approach to generate your makefiles,
- # instead of copying files around manually, because some third party
- # libraries may depend on the +target_prefix+ being set properly.
- #
- # The +srcprefix+ argument can be used to override the default source
- # directory, i.e. the current directory. It is included as part of the
- # +VPATH+ and added to the list of +INCFLAGS+.
- #
- def create_makefile(target, srcprefix = nil)
- $target = target
- libpath = $LIBPATH|$DEFLIBPATH
- message "creating Makefile\n"
- MakeMakefile.rm_f "#{CONFTEST}*"
- if CONFIG["DLEXT"] == $OBJEXT
- for lib in libs = $libs.split
- lib.sub!(/-l(.*)/, %%"lib\\1.#{$LIBEXT}"%)
- end
- $defs.push(format("-DEXTLIB='%s'", libs.join(",")))
- end
-
- if target.include?('/')
- target_prefix, target = File.split(target)
- target_prefix[0,0] = '/'
- else
- target_prefix = ""
- end
-
- srcprefix ||= "$(srcdir)/#{srcprefix}".chomp('/')
- RbConfig.expand(srcdir = srcprefix.dup)
-
- ext = ".#{$OBJEXT}"
- orig_srcs = Dir[File.join(srcdir, "*.{#{SRC_EXT.join(%q{,})}}")]
- if not $objs
- srcs = $srcs || orig_srcs
- objs = srcs.inject(Hash.new {[]}) {|h, f| h[File.basename(f, ".*") << ext] <<= f; h}
- $objs = objs.keys
- unless objs.delete_if {|b, f| f.size == 1}.empty?
- dups = objs.sort.map {|b, f|
- "#{b[/.*\./]}{#{f.collect {|n| n[/([^.]+)\z/]}.join(',')}}"
- }
- abort "source files duplication - #{dups.join(", ")}"
- end
- else
- $objs.collect! {|o| File.basename(o, ".*") << ext} unless $OBJEXT == "o"
- srcs = $srcs || $objs.collect {|o| o.chomp(ext) << ".c"}
- end
- $srcs = srcs
-
- hdrs = Dir[File.join(srcdir, "*.{#{HDR_EXT.join(%q{,})}}")]
-
- target = nil if $objs.empty?
-
- if target and EXPORT_PREFIX
- if File.exist?(File.join(srcdir, target + '.def'))
- deffile = "$(srcdir)/$(TARGET).def"
- unless EXPORT_PREFIX.empty?
- makedef = %{-pe "$_.sub!(/^(?=\\w)/,'#{EXPORT_PREFIX}') unless 1../^EXPORTS$/i"}
- end
- else
- makedef = %{-e "puts 'EXPORTS', '$(TARGET_ENTRY)'"}
- end
- if makedef
- $cleanfiles << '$(DEFFILE)'
- origdef = deffile
- deffile = "$(TARGET)-$(arch).def"
- end
- end
- origdef ||= ''
-
- if $extout and $INSTALLFILES
- $cleanfiles.concat($INSTALLFILES.collect {|files, dir|File.join(dir, files.sub(/\A\.\//, ''))})
- $distcleandirs.concat($INSTALLFILES.collect {|files, dir| dir})
- end
-
- if $extmk and $static
- $defs << "-DRUBY_EXPORT=1"
- end
-
- if $extmk and not $extconf_h
- create_header
- end
-
- libpath = libpathflag(libpath)
-
- dllib = target ? "$(TARGET).#{CONFIG['DLEXT']}" : ""
- staticlib = target ? "$(TARGET).#$LIBEXT" : ""
- mfile = open("Makefile", "wb")
- conf = configuration(srcprefix)
- conf = yield(conf) if block_given?
- mfile.puts(conf)
- mfile.print "
-libpath = #{($LIBPATH|$DEFLIBPATH).join(" ")}
-LIBPATH = #{libpath}
-DEFFILE = #{deffile}
-
-CLEANFILES = #{$cleanfiles.join(' ')}
-DISTCLEANFILES = #{$distcleanfiles.join(' ')}
-DISTCLEANDIRS = #{$distcleandirs.join(' ')}
-
-extout = #{$extout && $extout.quote}
-extout_prefix = #{$extout_prefix}
-target_prefix = #{target_prefix}
-LOCAL_LIBS = #{$LOCAL_LIBS}
-LIBS = #{$LIBRUBYARG} #{$libs} #{$LIBS}
-ORIG_SRCS = #{orig_srcs.collect(&File.method(:basename)).join(' ')}
-SRCS = $(ORIG_SRCS) #{(srcs - orig_srcs).collect(&File.method(:basename)).join(' ')}
-OBJS = #{$objs.join(" ")}
-HDRS = #{hdrs.map{|h| '$(srcdir)/' + File.basename(h)}.join(' ')}
-TARGET = #{target}
-TARGET_NAME = #{target && target[/\A\w+/]}
-TARGET_ENTRY = #{EXPORT_PREFIX || ''}Init_$(TARGET_NAME)
-DLLIB = #{dllib}
-EXTSTATIC = #{$static || ""}
-STATIC_LIB = #{staticlib unless $static.nil?}
-#{!$extout && defined?($installed_list) ? "INSTALLED_LIST = #{$installed_list}\n" : ""}
-TIMESTAMP_DIR = #{$extout ? '$(extout)/.timestamp' : '.'}
-" #"
- # TODO: fixme
- install_dirs.each {|d| mfile.print("%-14s= %s\n" % d) if /^[[:upper:]]/ =~ d[0]}
- n = ($extout ? '$(RUBYARCHDIR)/' : '') + '$(TARGET)'
- mfile.print "
-TARGET_SO = #{($extout ? '$(RUBYARCHDIR)/' : '')}$(DLLIB)
-CLEANLIBS = #{n}.#{CONFIG['DLEXT']} #{config_string('cleanlibs') {|t| t.gsub(/\$\*/) {n}}}
-CLEANOBJS = *.#{$OBJEXT} #{config_string('cleanobjs') {|t| t.gsub(/\$\*/, "$(TARGET)#{deffile ? '-$(arch)': ''}")} if target} *.bak
-
-all: #{$extout ? "install" : target ? "$(DLLIB)" : "Makefile"}
-static: $(STATIC_LIB)#{$extout ? " install-rb" : ""}
-.PHONY: all install static install-so install-rb
-.PHONY: clean clean-so clean-static clean-rb
-"
- mfile.print CLEANINGS
- fsep = config_string('BUILD_FILE_SEPARATOR') {|s| s unless s == "/"}
- if fsep
- sep = ":/=#{fsep}"
- fseprepl = proc {|s|
- s = s.gsub("/", fsep)
- s = s.gsub(/(\$\(\w+)(\))/) {$1+sep+$2}
- s.gsub(/(\$\{\w+)(\})/) {$1+sep+$2}
- }
- rsep = ":#{fsep}=/"
- else
- fseprepl = proc {|s| s}
- sep = ""
- rsep = ""
- end
- dirs = []
- mfile.print "install: install-so install-rb\n\n"
- sodir = (dir = "$(RUBYARCHDIR)").dup
- mfile.print("install-so: ")
- if target
- f = "$(DLLIB)"
- dest = "#{dir}/#{f}"
- if $extout
- mfile.puts dest
- mfile.print "clean-so::\n"
- mfile.print "\t-$(Q)$(RM) #{fseprepl[dest]}\n"
- mfile.print "\t-$(Q)$(RMDIRS) #{fseprepl[dir]}#{$ignore_error}\n"
- else
- mfile.print "#{f} #{timestamp_file(dir, target_prefix)}\n"
- mfile.print "\t$(INSTALL_PROG) #{fseprepl[f]} #{dir}\n"
- if defined?($installed_list)
- mfile.print "\t@echo #{dir}/#{File.basename(f)}>>$(INSTALLED_LIST)\n"
- end
- end
- mfile.print "clean-static::\n"
- mfile.print "\t-$(Q)$(RM) $(STATIC_LIB)\n"
- else
- mfile.puts "Makefile"
- end
- mfile.print("install-rb: pre-install-rb install-rb-default\n")
- mfile.print("install-rb-default: pre-install-rb-default\n")
- mfile.print("pre-install-rb: Makefile\n")
- mfile.print("pre-install-rb-default: Makefile\n")
- for sfx, i in [["-default", [["lib/**/*.rb", "$(RUBYLIBDIR)", "lib"]]], ["", $INSTALLFILES]]
- files = install_files(mfile, i, nil, srcprefix) or next
- for dir, *files in files
- unless dirs.include?(dir)
- dirs << dir
- mfile.print "pre-install-rb#{sfx}: #{timestamp_file(dir, target_prefix)}\n"
- end
- for f in files
- dest = "#{dir}/#{File.basename(f)}"
- mfile.print("install-rb#{sfx}: #{dest}\n")
- mfile.print("#{dest}: #{f} #{timestamp_file(dir, target_prefix)}\n")
- mfile.print("\t$(Q) $(#{$extout ? 'COPY' : 'INSTALL_DATA'}) #{f} $(@D)\n")
- if defined?($installed_list) and !$extout
- mfile.print("\t@echo #{dest}>>$(INSTALLED_LIST)\n")
- end
- if $extout
- mfile.print("clean-rb#{sfx}::\n")
- mfile.print("\t-$(Q)$(RM) #{fseprepl[dest]}\n")
- end
- end
- end
- mfile.print "pre-install-rb#{sfx}:\n"
- if files.empty?
- mfile.print("\t@$(NULLCMD)\n")
- else
- mfile.print("\t$(ECHO) installing#{sfx.sub(/^-/, " ")} #{target} libraries\n")
- end
- if $extout
- dirs.uniq!
- unless dirs.empty?
- mfile.print("clean-rb#{sfx}::\n")
- for dir in dirs.sort_by {|d| -d.count('/')}
- mfile.print("\t-$(Q)$(RMDIRS) #{fseprepl[dir]}#{$ignore_error}\n")
- end
- end
- end
- end
- dirs.unshift(sodir) if target and !dirs.include?(sodir)
- dirs.each do |d|
- t = timestamp_file(d, target_prefix)
- mfile.print "#{t}:\n\t$(Q) $(MAKEDIRS) $(@D) #{d}\n\t$(Q) $(TOUCH) $@\n"
- end
-
- mfile.print <<-SITEINSTALL
-
-site-install: site-install-so site-install-rb
-site-install-so: install-so
-site-install-rb: install-rb
-
- SITEINSTALL
-
- return unless target
-
- mfile.puts SRC_EXT.collect {|e| ".path.#{e} = $(VPATH)"} if $nmake == ?b
- mfile.print ".SUFFIXES: .#{(SRC_EXT + [$OBJEXT, $ASMEXT]).compact.join(' .')}\n"
- mfile.print "\n"
-
- compile_command = "\n\t$(ECHO) compiling $(<#{rsep})\n\t$(Q) %s\n\n"
- command = compile_command % COMPILE_CXX
- asm_command = compile_command.sub(/compiling/, 'translating') % ASSEMBLE_CXX
- CXX_EXT.each do |e|
- each_compile_rules do |rule|
- mfile.printf(rule, e, $OBJEXT)
- mfile.print(command)
- mfile.printf(rule, e, $ASMEXT)
- mfile.print(asm_command)
- end
- end
- command = compile_command % COMPILE_C
- asm_command = compile_command.sub(/compiling/, 'translating') % ASSEMBLE_C
- C_EXT.each do |e|
- each_compile_rules do |rule|
- mfile.printf(rule, e, $OBJEXT)
- mfile.print(command)
- mfile.printf(rule, e, $ASMEXT)
- mfile.print(asm_command)
- end
- end
-
- mfile.print "$(RUBYARCHDIR)/" if $extout
- mfile.print "$(DLLIB): "
- mfile.print "$(DEFFILE) " if makedef
- mfile.print "$(OBJS) Makefile"
- mfile.print " #{timestamp_file('$(RUBYARCHDIR)', target_prefix)}" if $extout
- mfile.print "\n"
- mfile.print "\t$(ECHO) linking shared-object #{target_prefix.sub(/\A\/(.*)/, '\1/')}$(DLLIB)\n"
- mfile.print "\t-$(Q)$(RM) $(@#{sep})\n"
- link_so = LINK_SO.gsub(/^/, "\t$(Q) ")
- if srcs.any?(&%r"\.(?:#{CXX_EXT.join('|')})\z".method(:===))
- link_so = link_so.sub(/\bLDSHARED\b/, '\&XX')
- end
- mfile.print link_so, "\n\n"
- unless $static.nil?
- mfile.print "$(STATIC_LIB): $(OBJS)\n\t-$(Q)$(RM) $(@#{sep})\n\t"
- mfile.print "$(ECHO) linking static-library $(@#{rsep})\n\t$(Q) "
- mfile.print "$(AR) #{config_string('ARFLAGS') || 'cru '}$@ $(OBJS)"
- config_string('RANLIB') do |ranlib|
- mfile.print "\n\t-$(Q)#{ranlib} $(@) 2> /dev/null || true"
- end
- end
- mfile.print "\n\n"
- if makedef
- mfile.print "$(DEFFILE): #{origdef}\n"
- mfile.print "\t$(ECHO) generating $(@#{rsep})\n"
- mfile.print "\t$(Q) $(RUBY) #{makedef} #{origdef} > $@\n\n"
- end
-
- depend = File.join(srcdir, "depend")
- if File.exist?(depend)
- mfile.print("###\n", *depend_rules(File.read(depend)))
- else
- mfile.print "$(OBJS): $(HDRS) $(ruby_headers)\n"
- end
-
- $makefile_created = true
- ensure
- mfile.close if mfile
- end
-
- # :stopdoc:
-
- def init_mkmf(config = CONFIG, rbconfig = RbConfig::CONFIG)
- $makefile_created = false
- $arg_config = []
- $enable_shared = config['ENABLE_SHARED'] == 'yes'
- $defs = []
- $extconf_h = nil
- if $warnflags = CONFIG['warnflags'] and CONFIG['GCC'] == 'yes'
- # turn warnings into errors only for bundled extensions.
- config['warnflags'] = $warnflags.gsub(/(\A|\s)-Werror[-=]/, '\1-W')
- RbConfig.expand(rbconfig['warnflags'] = config['warnflags'].dup)
- config.each do |key, val|
- RbConfig.expand(rbconfig[key] = val.dup) if /warnflags/ =~ val
- end
- $warnflags = config['warnflags'] unless $extmk
- end
- $CFLAGS = with_config("cflags", arg_config("CFLAGS", config["CFLAGS"])).dup
- $CXXFLAGS = (with_config("cxxflags", arg_config("CXXFLAGS", config["CXXFLAGS"]))||'').dup
- $ARCH_FLAG = with_config("arch_flag", arg_config("ARCH_FLAG", config["ARCH_FLAG"])).dup
- $CPPFLAGS = with_config("cppflags", arg_config("CPPFLAGS", config["CPPFLAGS"])).dup
- $LDFLAGS = with_config("ldflags", arg_config("LDFLAGS", config["LDFLAGS"])).dup
- $INCFLAGS = "-I$(arch_hdrdir)"
- $INCFLAGS << " -I$(hdrdir)/ruby/backward" unless $extmk
- $INCFLAGS << " -I$(hdrdir) -I$(srcdir)"
- $DLDFLAGS = with_config("dldflags", arg_config("DLDFLAGS", config["DLDFLAGS"])).dup
- $LIBEXT = config['LIBEXT'].dup
- $OBJEXT = config["OBJEXT"].dup
- $EXEEXT = config["EXEEXT"].dup
- $ASMEXT = config_string('ASMEXT', &:dup) || 'S'
- $LIBS = "#{config['LIBS']} #{config['DLDLIBS']}"
- $LIBRUBYARG = ""
- $LIBRUBYARG_STATIC = config['LIBRUBYARG_STATIC']
- $LIBRUBYARG_SHARED = config['LIBRUBYARG_SHARED']
- $DEFLIBPATH = [$extmk ? "$(topdir)" : "$(#{config["libdirname"] || "libdir"})"]
- $DEFLIBPATH.unshift(".")
- $LIBPATH = []
- $INSTALLFILES = []
- $NONINSTALLFILES = [/~\z/, /\A#.*#\z/, /\A\.#/, /\.bak\z/i, /\.orig\z/, /\.rej\z/, /\.l[ao]\z/, /\.o\z/]
- $VPATH = %w[$(srcdir) $(arch_hdrdir)/ruby $(hdrdir)/ruby]
-
- $objs = nil
- $srcs = nil
- $libs = ""
- if $enable_shared or RbConfig.expand(config["LIBRUBY"].dup) != RbConfig.expand(config["LIBRUBY_A"].dup)
- $LIBRUBYARG = config['LIBRUBYARG']
- end
-
- $LOCAL_LIBS = ""
-
- $cleanfiles = config_string('CLEANFILES') {|s| Shellwords.shellwords(s)} || []
- $cleanfiles << "mkmf.log"
- $distcleanfiles = config_string('DISTCLEANFILES') {|s| Shellwords.shellwords(s)} || []
- $distcleandirs = config_string('DISTCLEANDIRS') {|s| Shellwords.shellwords(s)} || []
-
- $extout ||= nil
- $extout_prefix ||= nil
-
- $arg_config.clear
- dir_config("opt")
- end
-
- FailedMessage = < 1000000) {\n" +
- refs.map {|n|" printf(\"%p\", {n});\n"}.join("") +
- " }\n"
- end
- end
- src
- end
-
- extend self
- init_mkmf
-
- $make = with_config("make-prog", ENV["MAKE"] || "make")
- make, = Shellwords.shellwords($make)
- $nmake = nil
- case
- when $mswin
- $nmake = ?m if /nmake/i =~ make
- when $bccwin
- $nmake = ?b if /Borland/i =~ `#{make} -h`
- end
- $ignore_error = $nmake ? '' : ' 2> /dev/null || true'
-
- RbConfig::CONFIG["srcdir"] = CONFIG["srcdir"] =
- $srcdir = arg_config("--srcdir", File.dirname($0))
- $configure_args["--topsrcdir"] ||= $srcdir
- if $curdir = arg_config("--curdir")
- RbConfig.expand(curdir = $curdir.dup)
- else
- curdir = $curdir = "."
- end
- unless File.expand_path(RbConfig::CONFIG["topdir"]) == File.expand_path(curdir)
- CONFIG["topdir"] = $curdir
- RbConfig::CONFIG["topdir"] = curdir
- end
- $configure_args["--topdir"] ||= $curdir
- $ruby = arg_config("--ruby", File.join(RbConfig::CONFIG["bindir"], CONFIG["ruby_install_name"]))
-
- RbConfig.expand(CONFIG["RUBY_SO_NAME"])
-
- # :startdoc:
-
- split = Shellwords.method(:shellwords).to_proc
-
- EXPORT_PREFIX = config_string('EXPORT_PREFIX') {|s| s.strip}
-
- hdr = ['#include "ruby.h"' "\n"]
- config_string('COMMON_MACROS') do |s|
- Shellwords.shellwords(s).each do |w|
- w, v = w.split(/=/, 2)
- hdr << "#ifndef #{w}"
- hdr << "#define #{[w, v].compact.join(" ")}"
- hdr << "#endif /* #{w} */"
- end
- end
- config_string('COMMON_HEADERS') do |s|
- Shellwords.shellwords(s).each {|w| hdr << "#include <#{w}>"}
- end
-
- ##
- # Common headers for Ruby C extensions
-
- COMMON_HEADERS = hdr.join("\n")
-
- ##
- # Common libraries for Ruby C extensions
-
- COMMON_LIBS = config_string('COMMON_LIBS', &split) || []
-
- ##
- # make compile rules
-
- COMPILE_RULES = config_string('COMPILE_RULES', &split) || %w[.%s.%s:]
- RULE_SUBST = config_string('RULE_SUBST')
-
- ##
- # Command which will compile C files in the generated Makefile
-
- COMPILE_C = config_string('COMPILE_C') || '$(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $<'
-
- ##
- # Command which will compile C++ files in the generated Makefile
-
- COMPILE_CXX = config_string('COMPILE_CXX') || '$(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $<'
-
- ##
- # Command which will translate C files to assembler sources in the generated Makefile
-
- ASSEMBLE_C = config_string('ASSEMBLE_C') || COMPILE_C.sub(/(?<=\s)-c(?=\s)/, '-S')
-
- ##
- # Command which will translate C++ files to assembler sources in the generated Makefile
-
- ASSEMBLE_CXX = config_string('ASSEMBLE_CXX') || COMPILE_CXX.sub(/(?<=\s)-c(?=\s)/, '-S')
-
- ##
- # Command which will compile a program in order to test linking a library
-
- TRY_LINK = config_string('TRY_LINK') ||
- "$(CC) #{OUTFLAG}#{CONFTEST}#{$EXEEXT} $(INCFLAGS) $(CPPFLAGS) " \
- "$(CFLAGS) $(src) $(LIBPATH) $(LDFLAGS) $(ARCH_FLAG) $(LOCAL_LIBS) $(LIBS)"
-
- ##
- # Command which will link a shared library
-
- LINK_SO = (config_string('LINK_SO') || "").sub(/^$/) do
- if CONFIG["DLEXT"] == $OBJEXT
- "ld $(DLDFLAGS) -r -o $@ $(OBJS)\n"
- else
- "$(LDSHARED) #{OUTFLAG}$@ $(OBJS) " \
- "$(LIBPATH) $(DLDFLAGS) $(LOCAL_LIBS) $(LIBS)"
- end
- end
-
- ##
- # Argument which will add a library path to the linker
-
- LIBPATHFLAG = config_string('LIBPATHFLAG') || ' -L%s'
- RPATHFLAG = config_string('RPATHFLAG') || ''
-
- ##
- # Argument which will add a library to the linker
-
- LIBARG = config_string('LIBARG') || '-l%s'
-
- ##
- # A C main function which does no work
-
- MAIN_DOES_NOTHING = config_string('MAIN_DOES_NOTHING') || "int main(int argc, char **argv)\n{\n return 0;\n}"
- UNIVERSAL_INTS = config_string('UNIVERSAL_INTS') {|s| Shellwords.shellwords(s)} ||
- %w[int short long long\ long]
-
- sep = config_string('BUILD_FILE_SEPARATOR') {|s| ":/=#{s}" if s != "/"} || ""
-
- ##
- # Makefile rules that will clean the extension build directory
-
- CLEANINGS = "
-clean-static::
-clean-rb-default::
-clean-rb::
-clean-so::
-clean: clean-so clean-static clean-rb-default clean-rb
-\t\t-$(Q)$(RM) $(CLEANLIBS#{sep}) $(CLEANOBJS#{sep}) $(CLEANFILES#{sep}) .*.time
-
-distclean-rb-default::
-distclean-rb::
-distclean-so::
-distclean-static::
-distclean: clean distclean-so distclean-static distclean-rb-default distclean-rb
-\t\t-$(Q)$(RM) Makefile $(RUBY_EXTCONF_H) #{CONFTEST}.* mkmf.log
-\t\t-$(Q)$(RM) core ruby$(EXEEXT) *~ $(DISTCLEANFILES#{sep})
-\t\t-$(Q)$(RMDIRS) $(DISTCLEANDIRS#{sep})#{$ignore_error}
-
-realclean: distclean
-"
-end
-
-include MakeMakefile
-
-if not $extmk and /\A(extconf|makefile).rb\z/ =~ File.basename($0)
- END {mkmf_failed($0)}
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/monitor.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/monitor.rb
deleted file mode 100755
index 07394b590..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/monitor.rb
+++ /dev/null
@@ -1,300 +0,0 @@
-# = monitor.rb
-#
-# Copyright (C) 2001 Shugo Maeda
-#
-# This library is distributed under the terms of the Ruby license.
-# You can freely distribute/modify this library.
-#
-
-require 'thread'
-
-#
-# In concurrent programming, a monitor is an object or module intended to be
-# used safely by more than one thread. The defining characteristic of a
-# monitor is that its methods are executed with mutual exclusion. That is, at
-# each point in time, at most one thread may be executing any of its methods.
-# This mutual exclusion greatly simplifies reasoning about the implementation
-# of monitors compared to reasoning about parallel code that updates a data
-# structure.
-#
-# You can read more about the general principles on the Wikipedia page for
-# Monitors[http://en.wikipedia.org/wiki/Monitor_%28synchronization%29]
-#
-# == Examples
-#
-# === Simple object.extend
-#
-# require 'monitor.rb'
-#
-# buf = []
-# buf.extend(MonitorMixin)
-# empty_cond = buf.new_cond
-#
-# # consumer
-# Thread.start do
-# loop do
-# buf.synchronize do
-# empty_cond.wait_while { buf.empty? }
-# print buf.shift
-# end
-# end
-# end
-#
-# # producer
-# while line = ARGF.gets
-# buf.synchronize do
-# buf.push(line)
-# empty_cond.signal
-# end
-# end
-#
-# The consumer thread waits for the producer thread to push a line to buf
-# while buf.empty?. The producer thread (main thread) reads a
-# line from ARGF and pushes it into buf then calls empty_cond.signal
-# to notify the consumer thread of new data.
-#
-# === Simple Class include
-#
-# require 'monitor'
-#
-# class SynchronizedArray < Array
-#
-# include MonitorMixin
-#
-# def initialize(*args)
-# super(*args)
-# end
-#
-# alias :old_shift :shift
-# alias :old_unshift :unshift
-#
-# def shift(n=1)
-# self.synchronize do
-# self.old_shift(n)
-# end
-# end
-#
-# def unshift(item)
-# self.synchronize do
-# self.old_unshift(item)
-# end
-# end
-#
-# # other methods ...
-# end
-#
-# +SynchronizedArray+ implements an Array with synchronized access to items.
-# This Class is implemented as subclass of Array which includes the
-# MonitorMixin module.
-#
-module MonitorMixin
- #
- # FIXME: This isn't documented in Nutshell.
- #
- # Since MonitorMixin.new_cond returns a ConditionVariable, and the example
- # above calls while_wait and signal, this class should be documented.
- #
- class ConditionVariable
- class Timeout < Exception; end
-
- #
- # Releases the lock held in the associated monitor and waits; reacquires the lock on wakeup.
- #
- # If +timeout+ is given, this method returns after +timeout+ seconds passed,
- # even if no other thread doesn't signal.
- #
- def wait(timeout = nil)
- @monitor.__send__(:mon_check_owner)
- count = @monitor.__send__(:mon_exit_for_cond)
- begin
- @cond.wait(@monitor.instance_variable_get(:@mon_mutex), timeout)
- return true
- ensure
- @monitor.__send__(:mon_enter_for_cond, count)
- end
- end
-
- #
- # Calls wait repeatedly while the given block yields a truthy value.
- #
- def wait_while
- while yield
- wait
- end
- end
-
- #
- # Calls wait repeatedly until the given block yields a truthy value.
- #
- def wait_until
- until yield
- wait
- end
- end
-
- #
- # Wakes up the first thread in line waiting for this lock.
- #
- def signal
- @monitor.__send__(:mon_check_owner)
- @cond.signal
- end
-
- #
- # Wakes up all threads waiting for this lock.
- #
- def broadcast
- @monitor.__send__(:mon_check_owner)
- @cond.broadcast
- end
-
- private
-
- def initialize(monitor)
- @monitor = monitor
- @cond = ::ConditionVariable.new
- end
- end
-
- def self.extend_object(obj)
- super(obj)
- obj.__send__(:mon_initialize)
- end
-
- #
- # Attempts to enter exclusive section. Returns +false+ if lock fails.
- #
- def mon_try_enter
- if @mon_owner != Thread.current
- unless @mon_mutex.try_lock
- return false
- end
- @mon_owner = Thread.current
- end
- @mon_count += 1
- return true
- end
- # For backward compatibility
- alias try_mon_enter mon_try_enter
-
- #
- # Enters exclusive section.
- #
- def mon_enter
- if @mon_owner != Thread.current
- @mon_mutex.lock
- @mon_owner = Thread.current
- end
- @mon_count += 1
- end
-
- #
- # Leaves exclusive section.
- #
- def mon_exit
- mon_check_owner
- @mon_count -=1
- if @mon_count == 0
- @mon_owner = nil
- @mon_mutex.unlock
- end
- end
-
- #
- # Enters exclusive section and executes the block. Leaves the exclusive
- # section automatically when the block exits. See example under
- # +MonitorMixin+.
- #
- def mon_synchronize
- mon_enter
- begin
- yield
- ensure
- mon_exit
- end
- end
- alias synchronize mon_synchronize
-
- #
- # Creates a new MonitorMixin::ConditionVariable associated with the
- # receiver.
- #
- def new_cond
- return ConditionVariable.new(self)
- end
-
- private
-
- # Use extend MonitorMixin or include MonitorMixin instead
- # of this constructor. Have look at the examples above to understand how to
- # use this module.
- def initialize(*args)
- super
- mon_initialize
- end
-
- # Initializes the MonitorMixin after being included in a class or when an
- # object has been extended with the MonitorMixin
- def mon_initialize
- @mon_owner = nil
- @mon_count = 0
- @mon_mutex = Mutex.new
- end
-
- def mon_check_owner
- if @mon_owner != Thread.current
- raise ThreadError, "current thread not owner"
- end
- end
-
- def mon_enter_for_cond(count)
- @mon_owner = Thread.current
- @mon_count = count
- end
-
- def mon_exit_for_cond
- count = @mon_count
- @mon_owner = nil
- @mon_count = 0
- return count
- end
-end
-
-# Use the Monitor class when you want to have a lock object for blocks with
-# mutual exclusion.
-#
-# require 'monitor'
-#
-# lock = Monitor.new
-# lock.synchronize do
-# # exclusive access
-# end
-#
-class Monitor
- include MonitorMixin
- alias try_enter try_mon_enter
- alias enter mon_enter
- alias exit mon_exit
-end
-
-
-# Documentation comments:
-# - All documentation comes from Nutshell.
-# - MonitorMixin.new_cond appears in the example, but is not documented in
-# Nutshell.
-# - All the internals (internal modules Accessible and Initializable, class
-# ConditionVariable) appear in RDoc. It might be good to hide them, by
-# making them private, or marking them :nodoc:, etc.
-# - RDoc doesn't recognise aliases, so we have mon_synchronize documented, but
-# not synchronize.
-# - mon_owner is in Nutshell, but appears as an accessor in a separate module
-# here, so is hard/impossible to RDoc. Some other useful accessors
-# (mon_count and some queue stuff) are also in this module, and don't appear
-# directly in the RDoc output.
-# - in short, it may be worth changing the code layout in this file to make the
-# documentation easier
-
-# Local variables:
-# mode: Ruby
-# tab-width: 8
-# End:
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/mutex_m.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/mutex_m.rb
deleted file mode 100755
index 6698cb5ac..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/mutex_m.rb
+++ /dev/null
@@ -1,111 +0,0 @@
-#
-# mutex_m.rb -
-# $Release Version: 3.0$
-# $Revision: 1.7 $
-# Original from mutex.rb
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-# modified by matz
-# patched by akira yamada
-#
-# --
-
-
-require 'thread'
-
-# = mutex_m.rb
-#
-# When 'mutex_m' is required, any object that extends or includes Mutex_m will
-# be treated like a Mutex.
-#
-# Start by requiring the standard library Mutex_m:
-#
-# require "mutex_m.rb"
-#
-# From here you can extend an object with Mutex instance methods:
-#
-# obj = Object.new
-# obj.extend Mutex_m
-#
-# Or mixin Mutex_m into your module to your class inherit Mutex instance
-# methods.
-#
-# class Foo
-# include Mutex_m
-# # ...
-# end
-# obj = Foo.new
-# # this obj can be handled like Mutex
-#
-module Mutex_m
- def Mutex_m.define_aliases(cl) # :nodoc:
- cl.module_eval %q{
- alias locked? mu_locked?
- alias lock mu_lock
- alias unlock mu_unlock
- alias try_lock mu_try_lock
- alias synchronize mu_synchronize
- }
- end
-
- def Mutex_m.append_features(cl) # :nodoc:
- super
- define_aliases(cl) unless cl.instance_of?(Module)
- end
-
- def Mutex_m.extend_object(obj) # :nodoc:
- super
- obj.mu_extended
- end
-
- def mu_extended # :nodoc:
- unless (defined? locked? and
- defined? lock and
- defined? unlock and
- defined? try_lock and
- defined? synchronize)
- Mutex_m.define_aliases(singleton_class)
- end
- mu_initialize
- end
-
- # See Mutex#synchronize
- def mu_synchronize(&block)
- @_mutex.synchronize(&block)
- end
-
- # See Mutex#locked?
- def mu_locked?
- @_mutex.locked?
- end
-
- # See Mutex#try_lock
- def mu_try_lock
- @_mutex.try_lock
- end
-
- # See Mutex#lock
- def mu_lock
- @_mutex.lock
- end
-
- # See Mutex#unlock
- def mu_unlock
- @_mutex.unlock
- end
-
- # See Mutex#sleep
- def sleep(timeout = nil)
- @_mutex.sleep(timeout)
- end
-
- private
-
- def mu_initialize # :nodoc:
- @_mutex = Mutex.new
- end
-
- def initialize(*args) # :nodoc:
- mu_initialize
- super
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/ftp.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/ftp.rb
deleted file mode 100755
index f513ca6ee..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/ftp.rb
+++ /dev/null
@@ -1,1121 +0,0 @@
-#
-# = net/ftp.rb - FTP Client Library
-#
-# Written by Shugo Maeda .
-#
-# Documentation by Gavin Sinclair, sourced from "Programming Ruby" (Hunt/Thomas)
-# and "Ruby In a Nutshell" (Matsumoto), used with permission.
-#
-# This library is distributed under the terms of the Ruby license.
-# You can freely distribute/modify this library.
-#
-# It is included in the Ruby standard library.
-#
-# See the Net::FTP class for an overview.
-#
-
-require "socket"
-require "monitor"
-require "net/protocol"
-
-module Net
-
- # :stopdoc:
- class FTPError < StandardError; end
- class FTPReplyError < FTPError; end
- class FTPTempError < FTPError; end
- class FTPPermError < FTPError; end
- class FTPProtoError < FTPError; end
- class FTPConnectionError < FTPError; end
- # :startdoc:
-
- #
- # This class implements the File Transfer Protocol. If you have used a
- # command-line FTP program, and are familiar with the commands, you will be
- # able to use this class easily. Some extra features are included to take
- # advantage of Ruby's style and strengths.
- #
- # == Example
- #
- # require 'net/ftp'
- #
- # === Example 1
- #
- # ftp = Net::FTP.new('example.com')
- # ftp.login
- # files = ftp.chdir('pub/lang/ruby/contrib')
- # files = ftp.list('n*')
- # ftp.getbinaryfile('nif.rb-0.91.gz', 'nif.gz', 1024)
- # ftp.close
- #
- # === Example 2
- #
- # Net::FTP.open('example.com') do |ftp|
- # ftp.login
- # files = ftp.chdir('pub/lang/ruby/contrib')
- # files = ftp.list('n*')
- # ftp.getbinaryfile('nif.rb-0.91.gz', 'nif.gz', 1024)
- # end
- #
- # == Major Methods
- #
- # The following are the methods most likely to be useful to users:
- # - FTP.open
- # - #getbinaryfile
- # - #gettextfile
- # - #putbinaryfile
- # - #puttextfile
- # - #chdir
- # - #nlst
- # - #size
- # - #rename
- # - #delete
- #
- class FTP
- include MonitorMixin
-
- # :stopdoc:
- FTP_PORT = 21
- CRLF = "\r\n"
- DEFAULT_BLOCKSIZE = BufferedIO::BUFSIZE
- # :startdoc:
-
- # When +true+, transfers are performed in binary mode. Default: +true+.
- attr_reader :binary
-
- # When +true+, the connection is in passive mode. Default: +false+.
- attr_accessor :passive
-
- # When +true+, all traffic to and from the server is written
- # to +$stdout+. Default: +false+.
- attr_accessor :debug_mode
-
- # Sets or retrieves the +resume+ status, which decides whether incomplete
- # transfers are resumed or restarted. Default: +false+.
- attr_accessor :resume
-
- # Number of seconds to wait for the connection to open. Any number
- # may be used, including Floats for fractional seconds. If the FTP
- # object cannot open a connection in this many seconds, it raises a
- # Net::OpenTimeout exception. The default value is +nil+.
- attr_accessor :open_timeout
-
- # Number of seconds to wait for one block to be read (via one read(2)
- # call). Any number may be used, including Floats for fractional
- # seconds. If the FTP object cannot read data in this many seconds,
- # it raises a Timeout::Error exception. The default value is 60 seconds.
- attr_reader :read_timeout
-
- # Setter for the read_timeout attribute.
- def read_timeout=(sec)
- @sock.read_timeout = sec
- @read_timeout = sec
- end
-
- # The server's welcome message.
- attr_reader :welcome
-
- # The server's last response code.
- attr_reader :last_response_code
- alias lastresp last_response_code
-
- # The server's last response.
- attr_reader :last_response
-
- #
- # A synonym for FTP.new, but with a mandatory host parameter.
- #
- # If a block is given, it is passed the +FTP+ object, which will be closed
- # when the block finishes, or when an exception is raised.
- #
- def FTP.open(host, user = nil, passwd = nil, acct = nil)
- if block_given?
- ftp = new(host, user, passwd, acct)
- begin
- yield ftp
- ensure
- ftp.close
- end
- else
- new(host, user, passwd, acct)
- end
- end
-
- #
- # Creates and returns a new +FTP+ object. If a +host+ is given, a connection
- # is made. Additionally, if the +user+ is given, the given user name,
- # password, and (optionally) account are used to log in. See #login.
- #
- def initialize(host = nil, user = nil, passwd = nil, acct = nil)
- super()
- @binary = true
- @passive = false
- @debug_mode = false
- @resume = false
- @sock = NullSocket.new
- @logged_in = false
- @open_timeout = nil
- @read_timeout = 60
- if host
- connect(host)
- if user
- login(user, passwd, acct)
- end
- end
- end
-
- # A setter to toggle transfers in binary mode.
- # +newmode+ is either +true+ or +false+
- def binary=(newmode)
- if newmode != @binary
- @binary = newmode
- send_type_command if @logged_in
- end
- end
-
- # Sends a command to destination host, with the current binary sendmode
- # type.
- #
- # If binary mode is +true+, then "TYPE I" (image) is sent, otherwise "TYPE
- # A" (ascii) is sent.
- def send_type_command # :nodoc:
- if @binary
- voidcmd("TYPE I")
- else
- voidcmd("TYPE A")
- end
- end
- private :send_type_command
-
- # Toggles transfers in binary mode and yields to a block.
- # This preserves your current binary send mode, but allows a temporary
- # transaction with binary sendmode of +newmode+.
- #
- # +newmode+ is either +true+ or +false+
- def with_binary(newmode) # :nodoc:
- oldmode = binary
- self.binary = newmode
- begin
- yield
- ensure
- self.binary = oldmode
- end
- end
- private :with_binary
-
- # Obsolete
- def return_code # :nodoc:
- $stderr.puts("warning: Net::FTP#return_code is obsolete and do nothing")
- return "\n"
- end
-
- # Obsolete
- def return_code=(s) # :nodoc:
- $stderr.puts("warning: Net::FTP#return_code= is obsolete and do nothing")
- end
-
- # Constructs a socket with +host+ and +port+.
- #
- # If SOCKSSocket is defined and the environment (ENV) defines
- # SOCKS_SERVER, then a SOCKSSocket is returned, else a TCPSocket is
- # returned.
- def open_socket(host, port) # :nodoc:
- return Timeout.timeout(@open_timeout, Net::OpenTimeout) {
- if defined? SOCKSSocket and ENV["SOCKS_SERVER"]
- @passive = true
- sock = SOCKSSocket.open(host, port)
- else
- sock = TCPSocket.open(host, port)
- end
- io = BufferedSocket.new(sock)
- io.read_timeout = @read_timeout
- io
- }
- end
- private :open_socket
-
- #
- # Establishes an FTP connection to host, optionally overriding the default
- # port. If the environment variable +SOCKS_SERVER+ is set, sets up the
- # connection through a SOCKS proxy. Raises an exception (typically
- # Errno::ECONNREFUSED) if the connection cannot be established.
- #
- def connect(host, port = FTP_PORT)
- if @debug_mode
- print "connect: ", host, ", ", port, "\n"
- end
- synchronize do
- @sock = open_socket(host, port)
- voidresp
- end
- end
-
- #
- # Set the socket used to connect to the FTP server.
- #
- # May raise FTPReplyError if +get_greeting+ is false.
- def set_socket(sock, get_greeting = true)
- synchronize do
- @sock = sock
- if get_greeting
- voidresp
- end
- end
- end
-
- # If string +s+ includes the PASS command (password), then the contents of
- # the password are cleaned from the string using "*"
- def sanitize(s) # :nodoc:
- if s =~ /^PASS /i
- return s[0, 5] + "*" * (s.length - 5)
- else
- return s
- end
- end
- private :sanitize
-
- # Ensures that +line+ has a control return / line feed (CRLF) and writes
- # it to the socket.
- def putline(line) # :nodoc:
- if @debug_mode
- print "put: ", sanitize(line), "\n"
- end
- line = line + CRLF
- @sock.write(line)
- end
- private :putline
-
- # Reads a line from the sock. If EOF, then it will raise EOFError
- def getline # :nodoc:
- line = @sock.readline # if get EOF, raise EOFError
- line.sub!(/(\r\n|\n|\r)\z/n, "")
- if @debug_mode
- print "get: ", sanitize(line), "\n"
- end
- return line
- end
- private :getline
-
- # Receive a section of lines until the response code's match.
- def getmultiline # :nodoc:
- line = getline
- buff = line
- if line[3] == ?-
- code = line[0, 3]
- begin
- line = getline
- buff << "\n" << line
- end until line[0, 3] == code and line[3] != ?-
- end
- return buff << "\n"
- end
- private :getmultiline
-
- # Receives a response from the destination host.
- #
- # Returns the response code or raises FTPTempError, FTPPermError, or
- # FTPProtoError
- def getresp # :nodoc:
- @last_response = getmultiline
- @last_response_code = @last_response[0, 3]
- case @last_response_code
- when /\A[123]/
- return @last_response
- when /\A4/
- raise FTPTempError, @last_response
- when /\A5/
- raise FTPPermError, @last_response
- else
- raise FTPProtoError, @last_response
- end
- end
- private :getresp
-
- # Receives a response.
- #
- # Raises FTPReplyError if the first position of the response code is not
- # equal 2.
- def voidresp # :nodoc:
- resp = getresp
- if resp[0] != ?2
- raise FTPReplyError, resp
- end
- end
- private :voidresp
-
- #
- # Sends a command and returns the response.
- #
- def sendcmd(cmd)
- synchronize do
- putline(cmd)
- return getresp
- end
- end
-
- #
- # Sends a command and expect a response beginning with '2'.
- #
- def voidcmd(cmd)
- synchronize do
- putline(cmd)
- voidresp
- end
- end
-
- # Constructs and send the appropriate PORT (or EPRT) command
- def sendport(host, port) # :nodoc:
- af = (@sock.peeraddr)[0]
- if af == "AF_INET"
- cmd = "PORT " + (host.split(".") + port.divmod(256)).join(",")
- elsif af == "AF_INET6"
- cmd = sprintf("EPRT |2|%s|%d|", host, port)
- else
- raise FTPProtoError, host
- end
- voidcmd(cmd)
- end
- private :sendport
-
- # Constructs a TCPServer socket
- def makeport # :nodoc:
- TCPServer.open(@sock.addr[3], 0)
- end
- private :makeport
-
- # sends the appropriate command to enable a passive connection
- def makepasv # :nodoc:
- if @sock.peeraddr[0] == "AF_INET"
- host, port = parse227(sendcmd("PASV"))
- else
- host, port = parse229(sendcmd("EPSV"))
- # host, port = parse228(sendcmd("LPSV"))
- end
- return host, port
- end
- private :makepasv
-
- # Constructs a connection for transferring data
- def transfercmd(cmd, rest_offset = nil) # :nodoc:
- if @passive
- host, port = makepasv
- conn = open_socket(host, port)
- if @resume and rest_offset
- resp = sendcmd("REST " + rest_offset.to_s)
- if resp[0] != ?3
- raise FTPReplyError, resp
- end
- end
- resp = sendcmd(cmd)
- # skip 2XX for some ftp servers
- resp = getresp if resp[0] == ?2
- if resp[0] != ?1
- raise FTPReplyError, resp
- end
- else
- sock = makeport
- begin
- sendport(sock.addr[3], sock.addr[1])
- if @resume and rest_offset
- resp = sendcmd("REST " + rest_offset.to_s)
- if resp[0] != ?3
- raise FTPReplyError, resp
- end
- end
- resp = sendcmd(cmd)
- # skip 2XX for some ftp servers
- resp = getresp if resp[0] == ?2
- if resp[0] != ?1
- raise FTPReplyError, resp
- end
- conn = BufferedSocket.new(sock.accept)
- conn.read_timeout = @read_timeout
- sock.shutdown(Socket::SHUT_WR) rescue nil
- sock.read rescue nil
- ensure
- sock.close
- end
- end
- return conn
- end
- private :transfercmd
-
- #
- # Logs in to the remote host. The session must have been
- # previously connected. If +user+ is the string "anonymous" and
- # the +password+ is +nil+, "anonymous@" is used as a password. If
- # the +acct+ parameter is not +nil+, an FTP ACCT command is sent
- # following the successful login. Raises an exception on error
- # (typically Net::FTPPermError).
- #
- def login(user = "anonymous", passwd = nil, acct = nil)
- if user == "anonymous" and passwd == nil
- passwd = "anonymous@"
- end
-
- resp = ""
- synchronize do
- resp = sendcmd('USER ' + user)
- if resp[0] == ?3
- raise FTPReplyError, resp if passwd.nil?
- resp = sendcmd('PASS ' + passwd)
- end
- if resp[0] == ?3
- raise FTPReplyError, resp if acct.nil?
- resp = sendcmd('ACCT ' + acct)
- end
- end
- if resp[0] != ?2
- raise FTPReplyError, resp
- end
- @welcome = resp
- send_type_command
- @logged_in = true
- end
-
- #
- # Puts the connection into binary (image) mode, issues the given command,
- # and fetches the data returned, passing it to the associated block in
- # chunks of +blocksize+ characters. Note that +cmd+ is a server command
- # (such as "RETR myfile").
- #
- def retrbinary(cmd, blocksize, rest_offset = nil) # :yield: data
- synchronize do
- with_binary(true) do
- begin
- conn = transfercmd(cmd, rest_offset)
- loop do
- data = conn.read(blocksize)
- break if data == nil
- yield(data)
- end
- conn.shutdown(Socket::SHUT_WR)
- conn.read_timeout = 1
- conn.read
- ensure
- conn.close if conn
- end
- voidresp
- end
- end
- end
-
- #
- # Puts the connection into ASCII (text) mode, issues the given command, and
- # passes the resulting data, one line at a time, to the associated block. If
- # no block is given, prints the lines. Note that +cmd+ is a server command
- # (such as "RETR myfile").
- #
- def retrlines(cmd) # :yield: line
- synchronize do
- with_binary(false) do
- begin
- conn = transfercmd(cmd)
- loop do
- line = conn.gets
- break if line == nil
- yield(line.sub(/\r?\n\z/, ""), !line.match(/\n\z/).nil?)
- end
- conn.shutdown(Socket::SHUT_WR)
- conn.read_timeout = 1
- conn.read
- ensure
- conn.close if conn
- end
- voidresp
- end
- end
- end
-
- #
- # Puts the connection into binary (image) mode, issues the given server-side
- # command (such as "STOR myfile"), and sends the contents of the file named
- # +file+ to the server. If the optional block is given, it also passes it
- # the data, in chunks of +blocksize+ characters.
- #
- def storbinary(cmd, file, blocksize, rest_offset = nil) # :yield: data
- if rest_offset
- file.seek(rest_offset, IO::SEEK_SET)
- end
- synchronize do
- with_binary(true) do
- conn = transfercmd(cmd)
- loop do
- buf = file.read(blocksize)
- break if buf == nil
- conn.write(buf)
- yield(buf) if block_given?
- end
- conn.close
- voidresp
- end
- end
- rescue Errno::EPIPE
- # EPIPE, in this case, means that the data connection was unexpectedly
- # terminated. Rather than just raising EPIPE to the caller, check the
- # response on the control connection. If getresp doesn't raise a more
- # appropriate exception, re-raise the original exception.
- getresp
- raise
- end
-
- #
- # Puts the connection into ASCII (text) mode, issues the given server-side
- # command (such as "STOR myfile"), and sends the contents of the file
- # named +file+ to the server, one line at a time. If the optional block is
- # given, it also passes it the lines.
- #
- def storlines(cmd, file) # :yield: line
- synchronize do
- with_binary(false) do
- conn = transfercmd(cmd)
- loop do
- buf = file.gets
- break if buf == nil
- if buf[-2, 2] != CRLF
- buf = buf.chomp + CRLF
- end
- conn.write(buf)
- yield(buf) if block_given?
- end
- conn.close
- voidresp
- end
- end
- rescue Errno::EPIPE
- # EPIPE, in this case, means that the data connection was unexpectedly
- # terminated. Rather than just raising EPIPE to the caller, check the
- # response on the control connection. If getresp doesn't raise a more
- # appropriate exception, re-raise the original exception.
- getresp
- raise
- end
-
- #
- # Retrieves +remotefile+ in binary mode, storing the result in +localfile+.
- # If +localfile+ is nil, returns retrieved data.
- # If a block is supplied, it is passed the retrieved data in +blocksize+
- # chunks.
- #
- def getbinaryfile(remotefile, localfile = File.basename(remotefile),
- blocksize = DEFAULT_BLOCKSIZE) # :yield: data
- result = nil
- if localfile
- if @resume
- rest_offset = File.size?(localfile)
- f = open(localfile, "a")
- else
- rest_offset = nil
- f = open(localfile, "w")
- end
- elsif !block_given?
- result = ""
- end
- begin
- f.binmode if localfile
- retrbinary("RETR " + remotefile.to_s, blocksize, rest_offset) do |data|
- f.write(data) if localfile
- yield(data) if block_given?
- result.concat(data) if result
- end
- return result
- ensure
- f.close if localfile
- end
- end
-
- #
- # Retrieves +remotefile+ in ASCII (text) mode, storing the result in
- # +localfile+.
- # If +localfile+ is nil, returns retrieved data.
- # If a block is supplied, it is passed the retrieved data one
- # line at a time.
- #
- def gettextfile(remotefile, localfile = File.basename(remotefile)) # :yield: line
- result = nil
- if localfile
- f = open(localfile, "w")
- elsif !block_given?
- result = ""
- end
- begin
- retrlines("RETR " + remotefile) do |line, newline|
- l = newline ? line + "\n" : line
- f.print(l) if localfile
- yield(line, newline) if block_given?
- result.concat(l) if result
- end
- return result
- ensure
- f.close if localfile
- end
- end
-
- #
- # Retrieves +remotefile+ in whatever mode the session is set (text or
- # binary). See #gettextfile and #getbinaryfile.
- #
- def get(remotefile, localfile = File.basename(remotefile),
- blocksize = DEFAULT_BLOCKSIZE, &block) # :yield: data
- if @binary
- getbinaryfile(remotefile, localfile, blocksize, &block)
- else
- gettextfile(remotefile, localfile, &block)
- end
- end
-
- #
- # Transfers +localfile+ to the server in binary mode, storing the result in
- # +remotefile+. If a block is supplied, calls it, passing in the transmitted
- # data in +blocksize+ chunks.
- #
- def putbinaryfile(localfile, remotefile = File.basename(localfile),
- blocksize = DEFAULT_BLOCKSIZE, &block) # :yield: data
- if @resume
- begin
- rest_offset = size(remotefile)
- rescue Net::FTPPermError
- rest_offset = nil
- end
- else
- rest_offset = nil
- end
- f = open(localfile)
- begin
- f.binmode
- if rest_offset
- storbinary("APPE " + remotefile, f, blocksize, rest_offset, &block)
- else
- storbinary("STOR " + remotefile, f, blocksize, rest_offset, &block)
- end
- ensure
- f.close
- end
- end
-
- #
- # Transfers +localfile+ to the server in ASCII (text) mode, storing the result
- # in +remotefile+. If callback or an associated block is supplied, calls it,
- # passing in the transmitted data one line at a time.
- #
- def puttextfile(localfile, remotefile = File.basename(localfile), &block) # :yield: line
- f = open(localfile)
- begin
- storlines("STOR " + remotefile, f, &block)
- ensure
- f.close
- end
- end
-
- #
- # Transfers +localfile+ to the server in whatever mode the session is set
- # (text or binary). See #puttextfile and #putbinaryfile.
- #
- def put(localfile, remotefile = File.basename(localfile),
- blocksize = DEFAULT_BLOCKSIZE, &block)
- if @binary
- putbinaryfile(localfile, remotefile, blocksize, &block)
- else
- puttextfile(localfile, remotefile, &block)
- end
- end
-
- #
- # Sends the ACCT command.
- #
- # This is a less common FTP command, to send account
- # information if the destination host requires it.
- #
- def acct(account)
- cmd = "ACCT " + account
- voidcmd(cmd)
- end
-
- #
- # Returns an array of filenames in the remote directory.
- #
- def nlst(dir = nil)
- cmd = "NLST"
- if dir
- cmd = cmd + " " + dir
- end
- files = []
- retrlines(cmd) do |line|
- files.push(line)
- end
- return files
- end
-
- #
- # Returns an array of file information in the directory (the output is like
- # `ls -l`). If a block is given, it iterates through the listing.
- #
- def list(*args, &block) # :yield: line
- cmd = "LIST"
- args.each do |arg|
- cmd = cmd + " " + arg.to_s
- end
- if block
- retrlines(cmd, &block)
- else
- lines = []
- retrlines(cmd) do |line|
- lines << line
- end
- return lines
- end
- end
- alias ls list
- alias dir list
-
- #
- # Renames a file on the server.
- #
- def rename(fromname, toname)
- resp = sendcmd("RNFR " + fromname)
- if resp[0] != ?3
- raise FTPReplyError, resp
- end
- voidcmd("RNTO " + toname)
- end
-
- #
- # Deletes a file on the server.
- #
- def delete(filename)
- resp = sendcmd("DELE " + filename)
- if resp[0, 3] == "250"
- return
- elsif resp[0] == ?5
- raise FTPPermError, resp
- else
- raise FTPReplyError, resp
- end
- end
-
- #
- # Changes the (remote) directory.
- #
- def chdir(dirname)
- if dirname == ".."
- begin
- voidcmd("CDUP")
- return
- rescue FTPPermError => e
- if e.message[0, 3] != "500"
- raise e
- end
- end
- end
- cmd = "CWD " + dirname
- voidcmd(cmd)
- end
-
- #
- # Returns the size of the given (remote) filename.
- #
- def size(filename)
- with_binary(true) do
- resp = sendcmd("SIZE " + filename)
- if resp[0, 3] != "213"
- raise FTPReplyError, resp
- end
- return resp[3..-1].strip.to_i
- end
- end
-
- MDTM_REGEXP = /^(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/ # :nodoc:
-
- #
- # Returns the last modification time of the (remote) file. If +local+ is
- # +true+, it is returned as a local time, otherwise it's a UTC time.
- #
- def mtime(filename, local = false)
- str = mdtm(filename)
- ary = str.scan(MDTM_REGEXP)[0].collect {|i| i.to_i}
- return local ? Time.local(*ary) : Time.gm(*ary)
- end
-
- #
- # Creates a remote directory.
- #
- def mkdir(dirname)
- resp = sendcmd("MKD " + dirname)
- return parse257(resp)
- end
-
- #
- # Removes a remote directory.
- #
- def rmdir(dirname)
- voidcmd("RMD " + dirname)
- end
-
- #
- # Returns the current remote directory.
- #
- def pwd
- resp = sendcmd("PWD")
- return parse257(resp)
- end
- alias getdir pwd
-
- #
- # Returns system information.
- #
- def system
- resp = sendcmd("SYST")
- if resp[0, 3] != "215"
- raise FTPReplyError, resp
- end
- return resp[4 .. -1]
- end
-
- #
- # Aborts the previous command (ABOR command).
- #
- def abort
- line = "ABOR" + CRLF
- print "put: ABOR\n" if @debug_mode
- @sock.send(line, Socket::MSG_OOB)
- resp = getmultiline
- unless ["426", "226", "225"].include?(resp[0, 3])
- raise FTPProtoError, resp
- end
- return resp
- end
-
- #
- # Returns the status (STAT command).
- #
- def status
- line = "STAT" + CRLF
- print "put: STAT\n" if @debug_mode
- @sock.send(line, Socket::MSG_OOB)
- return getresp
- end
-
- #
- # Returns the raw last modification time of the (remote) file in the format
- # "YYYYMMDDhhmmss" (MDTM command).
- #
- # Use +mtime+ if you want a parsed Time instance.
- #
- def mdtm(filename)
- resp = sendcmd("MDTM " + filename)
- if resp[0, 3] == "213"
- return resp[3 .. -1].strip
- end
- end
-
- #
- # Issues the HELP command.
- #
- def help(arg = nil)
- cmd = "HELP"
- if arg
- cmd = cmd + " " + arg
- end
- sendcmd(cmd)
- end
-
- #
- # Exits the FTP session.
- #
- def quit
- voidcmd("QUIT")
- end
-
- #
- # Issues a NOOP command.
- #
- # Does nothing except return a response.
- #
- def noop
- voidcmd("NOOP")
- end
-
- #
- # Issues a SITE command.
- #
- def site(arg)
- cmd = "SITE " + arg
- voidcmd(cmd)
- end
-
- #
- # Closes the connection. Further operations are impossible until you open
- # a new connection with #connect.
- #
- def close
- if @sock and not @sock.closed?
- begin
- @sock.shutdown(Socket::SHUT_WR) rescue nil
- orig, self.read_timeout = self.read_timeout, 3
- @sock.read rescue nil
- ensure
- @sock.close
- self.read_timeout = orig
- end
- end
- end
-
- #
- # Returns +true+ iff the connection is closed.
- #
- def closed?
- @sock == nil or @sock.closed?
- end
-
- # handler for response code 227
- # (Entering Passive Mode (h1,h2,h3,h4,p1,p2))
- #
- # Returns host and port.
- def parse227(resp) # :nodoc:
- if resp[0, 3] != "227"
- raise FTPReplyError, resp
- end
- if m = /\((?\d+(,\d+){3}),(?\d+,\d+)\)/.match(resp)
- return parse_pasv_ipv4_host(m["host"]), parse_pasv_port(m["port"])
- else
- raise FTPProtoError, resp
- end
- end
- private :parse227
-
- # handler for response code 228
- # (Entering Long Passive Mode)
- #
- # Returns host and port.
- def parse228(resp) # :nodoc:
- if resp[0, 3] != "228"
- raise FTPReplyError, resp
- end
- if m = /\(4,4,(?\d+(,\d+){3}),2,(?\d+,\d+)\)/.match(resp)
- return parse_pasv_ipv4_host(m["host"]), parse_pasv_port(m["port"])
- elsif m = /\(6,16,(?\d+(,(\d+)){15}),2,(?\d+,\d+)\)/.match(resp)
- return parse_pasv_ipv6_host(m["host"]), parse_pasv_port(m["port"])
- else
- raise FTPProtoError, resp
- end
- end
- private :parse228
-
- def parse_pasv_ipv4_host(s)
- return s.tr(",", ".")
- end
- private :parse_pasv_ipv4_host
-
- def parse_pasv_ipv6_host(s)
- return s.split(/,/).map { |i|
- "%02x" % i.to_i
- }.each_slice(2).map(&:join).join(":")
- end
- private :parse_pasv_ipv6_host
-
- def parse_pasv_port(s)
- return s.split(/,/).map(&:to_i).inject { |x, y|
- (x << 8) + y
- }
- end
- private :parse_pasv_port
-
- # handler for response code 229
- # (Extended Passive Mode Entered)
- #
- # Returns host and port.
- def parse229(resp) # :nodoc:
- if resp[0, 3] != "229"
- raise FTPReplyError, resp
- end
- if m = /\((?[!-~])\k\k(?\d+)\k\)/.match(resp)
- return @sock.peeraddr[3], m["port"].to_i
- else
- raise FTPProtoError, resp
- end
- end
- private :parse229
-
- # handler for response code 257
- # ("PATHNAME" created)
- #
- # Returns host and port.
- def parse257(resp) # :nodoc:
- if resp[0, 3] != "257"
- raise FTPReplyError, resp
- end
- if resp[3, 2] != ' "'
- return ""
- end
- dirname = ""
- i = 5
- n = resp.length
- while i < n
- c = resp[i, 1]
- i = i + 1
- if c == '"'
- if i > n or resp[i, 1] != '"'
- break
- end
- i = i + 1
- end
- dirname = dirname + c
- end
- return dirname
- end
- private :parse257
-
- # :stopdoc:
- class NullSocket
- def read_timeout=(sec)
- end
-
- def close
- end
-
- def method_missing(mid, *args)
- raise FTPConnectionError, "not connected"
- end
- end
-
- class BufferedSocket < BufferedIO
- [:addr, :peeraddr, :send, :shutdown].each do |method|
- define_method(method) { |*args|
- @io.__send__(method, *args)
- }
- end
-
- def read(len = nil)
- if len
- s = super(len, "", true)
- return s.empty? ? nil : s
- else
- result = ""
- while s = super(DEFAULT_BLOCKSIZE, "", true)
- break if s.empty?
- result << s
- end
- return result
- end
- end
-
- def gets
- line = readuntil("\n", true)
- return line.empty? ? nil : line
- end
-
- def readline
- line = gets
- if line.nil?
- raise EOFError, "end of file reached"
- end
- return line
- end
- end
- # :startdoc:
- end
-end
-
-
-# Documentation comments:
-# - sourced from pickaxe and nutshell, with improvements (hopefully)
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http.rb
deleted file mode 100755
index 6647914a5..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http.rb
+++ /dev/null
@@ -1,1559 +0,0 @@
-#
-# = net/http.rb
-#
-# Copyright (c) 1999-2007 Yukihiro Matsumoto
-# Copyright (c) 1999-2007 Minero Aoki
-# Copyright (c) 2001 GOTOU Yuuzou
-#
-# Written and maintained by Minero Aoki .
-# HTTPS support added by GOTOU Yuuzou .
-#
-# This file is derived from "http-access.rb".
-#
-# Documented by Minero Aoki; converted to RDoc by William Webber.
-#
-# This program is free software. You can re-distribute and/or
-# modify this program under the same terms of ruby itself ---
-# Ruby Distribution License or GNU General Public License.
-#
-# See Net::HTTP for an overview and examples.
-#
-
-require 'net/protocol'
-require 'uri'
-
-module Net #:nodoc:
- autoload :OpenSSL, 'openssl'
-
- # :stopdoc:
- class HTTPBadResponse < StandardError; end
- class HTTPHeaderSyntaxError < StandardError; end
- # :startdoc:
-
- # == An HTTP client API for Ruby.
- #
- # Net::HTTP provides a rich library which can be used to build HTTP
- # user-agents. For more details about HTTP see
- # [RFC2616](http://www.ietf.org/rfc/rfc2616.txt)
- #
- # Net::HTTP is designed to work closely with URI. URI::HTTP#host,
- # URI::HTTP#port and URI::HTTP#request_uri are designed to work with
- # Net::HTTP.
- #
- # If you are only performing a few GET requests you should try OpenURI.
- #
- # == Simple Examples
- #
- # All examples assume you have loaded Net::HTTP with:
- #
- # require 'net/http'
- #
- # This will also require 'uri' so you don't need to require it separately.
- #
- # The Net::HTTP methods in the following section do not persist
- # connections. They are not recommended if you are performing many HTTP
- # requests.
- #
- # === GET
- #
- # Net::HTTP.get('example.com', '/index.html') # => String
- #
- # === GET by URI
- #
- # uri = URI('http://example.com/index.html?count=10')
- # Net::HTTP.get(uri) # => String
- #
- # === GET with Dynamic Parameters
- #
- # uri = URI('http://example.com/index.html')
- # params = { :limit => 10, :page => 3 }
- # uri.query = URI.encode_www_form(params)
- #
- # res = Net::HTTP.get_response(uri)
- # puts res.body if res.is_a?(Net::HTTPSuccess)
- #
- # === POST
- #
- # uri = URI('http://www.example.com/search.cgi')
- # res = Net::HTTP.post_form(uri, 'q' => 'ruby', 'max' => '50')
- # puts res.body
- #
- # === POST with Multiple Values
- #
- # uri = URI('http://www.example.com/search.cgi')
- # res = Net::HTTP.post_form(uri, 'q' => ['ruby', 'perl'], 'max' => '50')
- # puts res.body
- #
- # == How to use Net::HTTP
- #
- # The following example code can be used as the basis of a HTTP user-agent
- # which can perform a variety of request types using persistent
- # connections.
- #
- # uri = URI('http://example.com/some_path?query=string')
- #
- # Net::HTTP.start(uri.host, uri.port) do |http|
- # request = Net::HTTP::Get.new uri
- #
- # response = http.request request # Net::HTTPResponse object
- # end
- #
- # Net::HTTP::start immediately creates a connection to an HTTP server which
- # is kept open for the duration of the block. The connection will remain
- # open for multiple requests in the block if the server indicates it
- # supports persistent connections.
- #
- # The request types Net::HTTP supports are listed below in the section "HTTP
- # Request Classes".
- #
- # If you wish to re-use a connection across multiple HTTP requests without
- # automatically closing it you can use ::new instead of ::start. #request
- # will automatically open a connection to the server if one is not currently
- # open. You can manually close the connection with #finish.
- #
- # For all the Net::HTTP request objects and shortcut request methods you may
- # supply either a String for the request path or a URI from which Net::HTTP
- # will extract the request path.
- #
- # === Response Data
- #
- # uri = URI('http://example.com/index.html')
- # res = Net::HTTP.get_response(uri)
- #
- # # Headers
- # res['Set-Cookie'] # => String
- # res.get_fields('set-cookie') # => Array
- # res.to_hash['set-cookie'] # => Array
- # puts "Headers: #{res.to_hash.inspect}"
- #
- # # Status
- # puts res.code # => '200'
- # puts res.message # => 'OK'
- # puts res.class.name # => 'HTTPOK'
- #
- # # Body
- # puts res.body if res.response_body_permitted?
- #
- # === Following Redirection
- #
- # Each Net::HTTPResponse object belongs to a class for its response code.
- #
- # For example, all 2XX responses are instances of a Net::HTTPSuccess
- # subclass, a 3XX response is an instance of a Net::HTTPRedirection
- # subclass and a 200 response is an instance of the Net::HTTPOK class. For
- # details of response classes, see the section "HTTP Response Classes"
- # below.
- #
- # Using a case statement you can handle various types of responses properly:
- #
- # def fetch(uri_str, limit = 10)
- # # You should choose a better exception.
- # raise ArgumentError, 'too many HTTP redirects' if limit == 0
- #
- # response = Net::HTTP.get_response(URI(uri_str))
- #
- # case response
- # when Net::HTTPSuccess then
- # response
- # when Net::HTTPRedirection then
- # location = response['location']
- # warn "redirected to #{location}"
- # fetch(location, limit - 1)
- # else
- # response.value
- # end
- # end
- #
- # print fetch('http://www.ruby-lang.org')
- #
- # === POST
- #
- # A POST can be made using the Net::HTTP::Post request class. This example
- # creates a urlencoded POST body:
- #
- # uri = URI('http://www.example.com/todo.cgi')
- # req = Net::HTTP::Post.new(uri)
- # req.set_form_data('from' => '2005-01-01', 'to' => '2005-03-31')
- #
- # res = Net::HTTP.start(uri.hostname, uri.port) do |http|
- # http.request(req)
- # end
- #
- # case res
- # when Net::HTTPSuccess, Net::HTTPRedirection
- # # OK
- # else
- # res.value
- # end
- #
- # At this time Net::HTTP does not support multipart/form-data. To send
- # multipart/form-data use Net::HTTPRequest#body= and
- # Net::HTTPRequest#content_type=:
- #
- # req = Net::HTTP::Post.new(uri)
- # req.body = multipart_data
- # req.content_type = 'multipart/form-data'
- #
- # Other requests that can contain a body such as PUT can be created in the
- # same way using the corresponding request class (Net::HTTP::Put).
- #
- # === Setting Headers
- #
- # The following example performs a conditional GET using the
- # If-Modified-Since header. If the files has not been modified since the
- # time in the header a Not Modified response will be returned. See RFC 2616
- # section 9.3 for further details.
- #
- # uri = URI('http://example.com/cached_response')
- # file = File.stat 'cached_response'
- #
- # req = Net::HTTP::Get.new(uri)
- # req['If-Modified-Since'] = file.mtime.rfc2822
- #
- # res = Net::HTTP.start(uri.hostname, uri.port) {|http|
- # http.request(req)
- # }
- #
- # open 'cached_response', 'w' do |io|
- # io.write res.body
- # end if res.is_a?(Net::HTTPSuccess)
- #
- # === Basic Authentication
- #
- # Basic authentication is performed according to
- # [RFC2617](http://www.ietf.org/rfc/rfc2617.txt)
- #
- # uri = URI('http://example.com/index.html?key=value')
- #
- # req = Net::HTTP::Get.new(uri)
- # req.basic_auth 'user', 'pass'
- #
- # res = Net::HTTP.start(uri.hostname, uri.port) {|http|
- # http.request(req)
- # }
- # puts res.body
- #
- # === Streaming Response Bodies
- #
- # By default Net::HTTP reads an entire response into memory. If you are
- # handling large files or wish to implement a progress bar you can instead
- # stream the body directly to an IO.
- #
- # uri = URI('http://example.com/large_file')
- #
- # Net::HTTP.start(uri.host, uri.port) do |http|
- # request = Net::HTTP::Get.new uri
- #
- # http.request request do |response|
- # open 'large_file', 'w' do |io|
- # response.read_body do |chunk|
- # io.write chunk
- # end
- # end
- # end
- # end
- #
- # === HTTPS
- #
- # HTTPS is enabled for an HTTP connection by Net::HTTP#use_ssl=.
- #
- # uri = URI('https://secure.example.com/some_path?query=string')
- #
- # Net::HTTP.start(uri.host, uri.port,
- # :use_ssl => uri.scheme == 'https') do |http|
- # request = Net::HTTP::Get.new uri
- #
- # response = http.request request # Net::HTTPResponse object
- # end
- #
- # In previous versions of Ruby you would need to require 'net/https' to use
- # HTTPS. This is no longer true.
- #
- # === Proxies
- #
- # Net::HTTP will automatically create a proxy from the +http_proxy+
- # environment variable if it is present. To disable use of +http_proxy+,
- # pass +nil+ for the proxy address.
- #
- # You may also create a custom proxy:
- #
- # proxy_addr = 'your.proxy.host'
- # proxy_port = 8080
- #
- # Net::HTTP.new('example.com', nil, proxy_addr, proxy_port).start { |http|
- # # always proxy via your.proxy.addr:8080
- # }
- #
- # See Net::HTTP.new for further details and examples such as proxies that
- # require a username and password.
- #
- # === Compression
- #
- # Net::HTTP automatically adds Accept-Encoding for compression of response
- # bodies and automatically decompresses gzip and deflate responses unless a
- # Range header was sent.
- #
- # Compression can be disabled through the Accept-Encoding: identity header.
- #
- # == HTTP Request Classes
- #
- # Here is the HTTP request class hierarchy.
- #
- # * Net::HTTPRequest
- # * Net::HTTP::Get
- # * Net::HTTP::Head
- # * Net::HTTP::Post
- # * Net::HTTP::Patch
- # * Net::HTTP::Put
- # * Net::HTTP::Proppatch
- # * Net::HTTP::Lock
- # * Net::HTTP::Unlock
- # * Net::HTTP::Options
- # * Net::HTTP::Propfind
- # * Net::HTTP::Delete
- # * Net::HTTP::Move
- # * Net::HTTP::Copy
- # * Net::HTTP::Mkcol
- # * Net::HTTP::Trace
- #
- # == HTTP Response Classes
- #
- # Here is HTTP response class hierarchy. All classes are defined in Net
- # module and are subclasses of Net::HTTPResponse.
- #
- # HTTPUnknownResponse:: For unhandled HTTP extensions
- # HTTPInformation:: 1xx
- # HTTPContinue:: 100
- # HTTPSwitchProtocol:: 101
- # HTTPSuccess:: 2xx
- # HTTPOK:: 200
- # HTTPCreated:: 201
- # HTTPAccepted:: 202
- # HTTPNonAuthoritativeInformation:: 203
- # HTTPNoContent:: 204
- # HTTPResetContent:: 205
- # HTTPPartialContent:: 206
- # HTTPMultiStatus:: 207
- # HTTPIMUsed:: 226
- # HTTPRedirection:: 3xx
- # HTTPMultipleChoices:: 300
- # HTTPMovedPermanently:: 301
- # HTTPFound:: 302
- # HTTPSeeOther:: 303
- # HTTPNotModified:: 304
- # HTTPUseProxy:: 305
- # HTTPTemporaryRedirect:: 307
- # HTTPClientError:: 4xx
- # HTTPBadRequest:: 400
- # HTTPUnauthorized:: 401
- # HTTPPaymentRequired:: 402
- # HTTPForbidden:: 403
- # HTTPNotFound:: 404
- # HTTPMethodNotAllowed:: 405
- # HTTPNotAcceptable:: 406
- # HTTPProxyAuthenticationRequired:: 407
- # HTTPRequestTimeOut:: 408
- # HTTPConflict:: 409
- # HTTPGone:: 410
- # HTTPLengthRequired:: 411
- # HTTPPreconditionFailed:: 412
- # HTTPRequestEntityTooLarge:: 413
- # HTTPRequestURITooLong:: 414
- # HTTPUnsupportedMediaType:: 415
- # HTTPRequestedRangeNotSatisfiable:: 416
- # HTTPExpectationFailed:: 417
- # HTTPUnprocessableEntity:: 422
- # HTTPLocked:: 423
- # HTTPFailedDependency:: 424
- # HTTPUpgradeRequired:: 426
- # HTTPPreconditionRequired:: 428
- # HTTPTooManyRequests:: 429
- # HTTPRequestHeaderFieldsTooLarge:: 431
- # HTTPServerError:: 5xx
- # HTTPInternalServerError:: 500
- # HTTPNotImplemented:: 501
- # HTTPBadGateway:: 502
- # HTTPServiceUnavailable:: 503
- # HTTPGatewayTimeOut:: 504
- # HTTPVersionNotSupported:: 505
- # HTTPInsufficientStorage:: 507
- # HTTPNetworkAuthenticationRequired:: 511
- #
- # There is also the Net::HTTPBadResponse exception which is raised when
- # there is a protocol error.
- #
- class HTTP < Protocol
-
- # :stopdoc:
- Revision = %q$Revision: 52785 $.split[1]
- HTTPVersion = '1.1'
- begin
- require 'zlib'
- require 'stringio' #for our purposes (unpacking gzip) lump these together
- HAVE_ZLIB=true
- rescue LoadError
- HAVE_ZLIB=false
- end
- # :startdoc:
-
- # Turns on net/http 1.2 (Ruby 1.8) features.
- # Defaults to ON in Ruby 1.8 or later.
- def HTTP.version_1_2
- true
- end
-
- # Returns true if net/http is in version 1.2 mode.
- # Defaults to true.
- def HTTP.version_1_2?
- true
- end
-
- def HTTP.version_1_1? #:nodoc:
- false
- end
-
- class << HTTP
- alias is_version_1_1? version_1_1? #:nodoc:
- alias is_version_1_2? version_1_2? #:nodoc:
- end
-
- #
- # short cut methods
- #
-
- #
- # Gets the body text from the target and outputs it to $stdout. The
- # target can either be specified as
- # (+uri+), or as (+host+, +path+, +port+ = 80); so:
- #
- # Net::HTTP.get_print URI('http://www.example.com/index.html')
- #
- # or:
- #
- # Net::HTTP.get_print 'www.example.com', '/index.html'
- #
- def HTTP.get_print(uri_or_host, path = nil, port = nil)
- get_response(uri_or_host, path, port) {|res|
- res.read_body do |chunk|
- $stdout.print chunk
- end
- }
- nil
- end
-
- # Sends a GET request to the target and returns the HTTP response
- # as a string. The target can either be specified as
- # (+uri+), or as (+host+, +path+, +port+ = 80); so:
- #
- # print Net::HTTP.get(URI('http://www.example.com/index.html'))
- #
- # or:
- #
- # print Net::HTTP.get('www.example.com', '/index.html')
- #
- def HTTP.get(uri_or_host, path = nil, port = nil)
- get_response(uri_or_host, path, port).body
- end
-
- # Sends a GET request to the target and returns the HTTP response
- # as a Net::HTTPResponse object. The target can either be specified as
- # (+uri+), or as (+host+, +path+, +port+ = 80); so:
- #
- # res = Net::HTTP.get_response(URI('http://www.example.com/index.html'))
- # print res.body
- #
- # or:
- #
- # res = Net::HTTP.get_response('www.example.com', '/index.html')
- # print res.body
- #
- def HTTP.get_response(uri_or_host, path = nil, port = nil, &block)
- if path
- host = uri_or_host
- new(host, port || HTTP.default_port).start {|http|
- return http.request_get(path, &block)
- }
- else
- uri = uri_or_host
- start(uri.hostname, uri.port,
- :use_ssl => uri.scheme == 'https') {|http|
- return http.request_get(uri, &block)
- }
- end
- end
-
- # Posts HTML form data to the specified URI object.
- # The form data must be provided as a Hash mapping from String to String.
- # Example:
- #
- # { "cmd" => "search", "q" => "ruby", "max" => "50" }
- #
- # This method also does Basic Authentication iff +url+.user exists.
- # But userinfo for authentication is deprecated (RFC3986).
- # So this feature will be removed.
- #
- # Example:
- #
- # require 'net/http'
- # require 'uri'
- #
- # Net::HTTP.post_form URI('http://www.example.com/search.cgi'),
- # { "q" => "ruby", "max" => "50" }
- #
- def HTTP.post_form(url, params)
- req = Post.new(url)
- req.form_data = params
- req.basic_auth url.user, url.password if url.user
- start(url.hostname, url.port,
- :use_ssl => url.scheme == 'https' ) {|http|
- http.request(req)
- }
- end
-
- #
- # HTTP session management
- #
-
- # The default port to use for HTTP requests; defaults to 80.
- def HTTP.default_port
- http_default_port()
- end
-
- # The default port to use for HTTP requests; defaults to 80.
- def HTTP.http_default_port
- 80
- end
-
- # The default port to use for HTTPS requests; defaults to 443.
- def HTTP.https_default_port
- 443
- end
-
- def HTTP.socket_type #:nodoc: obsolete
- BufferedIO
- end
-
- # :call-seq:
- # HTTP.start(address, port, p_addr, p_port, p_user, p_pass, &block)
- # HTTP.start(address, port=nil, p_addr=nil, p_port=nil, p_user=nil, p_pass=nil, opt, &block)
- #
- # Creates a new Net::HTTP object, then additionally opens the TCP
- # connection and HTTP session.
- #
- # Arguments are the following:
- # _address_ :: hostname or IP address of the server
- # _port_ :: port of the server
- # _p_addr_ :: address of proxy
- # _p_port_ :: port of proxy
- # _p_user_ :: user of proxy
- # _p_pass_ :: pass of proxy
- # _opt_ :: optional hash
- #
- # _opt_ sets following values by its accessor.
- # The keys are ca_file, ca_path, cert, cert_store, ciphers,
- # close_on_empty_response, key, open_timeout, read_timeout, ssl_timeout,
- # ssl_version, use_ssl, verify_callback, verify_depth and verify_mode.
- # If you set :use_ssl as true, you can use https and default value of
- # verify_mode is set as OpenSSL::SSL::VERIFY_PEER.
- #
- # If the optional block is given, the newly
- # created Net::HTTP object is passed to it and closed when the
- # block finishes. In this case, the return value of this method
- # is the return value of the block. If no block is given, the
- # return value of this method is the newly created Net::HTTP object
- # itself, and the caller is responsible for closing it upon completion
- # using the finish() method.
- def HTTP.start(address, *arg, &block) # :yield: +http+
- arg.pop if opt = Hash.try_convert(arg[-1])
- port, p_addr, p_port, p_user, p_pass = *arg
- port = https_default_port if !port && opt && opt[:use_ssl]
- http = new(address, port, p_addr, p_port, p_user, p_pass)
-
- if opt
- if opt[:use_ssl]
- opt = {verify_mode: OpenSSL::SSL::VERIFY_PEER}.update(opt)
- end
- http.methods.grep(/\A(\w+)=\z/) do |meth|
- key = $1.to_sym
- opt.key?(key) or next
- http.__send__(meth, opt[key])
- end
- end
-
- http.start(&block)
- end
-
- class << HTTP
- alias newobj new # :nodoc:
- end
-
- # Creates a new Net::HTTP object without opening a TCP connection or
- # HTTP session.
- #
- # The +address+ should be a DNS hostname or IP address, the +port+ is the
- # port the server operates on. If no +port+ is given the default port for
- # HTTP or HTTPS is used.
- #
- # If none of the +p_+ arguments are given, the proxy host and port are
- # taken from the +http_proxy+ environment variable (or its uppercase
- # equivalent) if present. If the proxy requires authentication you must
- # supply it by hand. See URI::Generic#find_proxy for details of proxy
- # detection from the environment. To disable proxy detection set +p_addr+
- # to nil.
- #
- # If you are connecting to a custom proxy, +p_addr+ the DNS name or IP
- # address of the proxy host, +p_port+ the port to use to access the proxy,
- # and +p_user+ and +p_pass+ the username and password if authorization is
- # required to use the proxy.
- #
- def HTTP.new(address, port = nil, p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil)
- http = super address, port
-
- if proxy_class? then # from Net::HTTP::Proxy()
- http.proxy_from_env = @proxy_from_env
- http.proxy_address = @proxy_address
- http.proxy_port = @proxy_port
- http.proxy_user = @proxy_user
- http.proxy_pass = @proxy_pass
- elsif p_addr == :ENV then
- http.proxy_from_env = true
- else
- http.proxy_address = p_addr
- http.proxy_port = p_port || default_port
- http.proxy_user = p_user
- http.proxy_pass = p_pass
- end
-
- http
- end
-
- # Creates a new Net::HTTP object for the specified server address,
- # without opening the TCP connection or initializing the HTTP session.
- # The +address+ should be a DNS hostname or IP address.
- def initialize(address, port = nil)
- @address = address
- @port = (port || HTTP.default_port)
- @local_host = nil
- @local_port = nil
- @curr_http_version = HTTPVersion
- @keep_alive_timeout = 2
- @last_communicated = nil
- @close_on_empty_response = false
- @socket = nil
- @started = false
- @open_timeout = nil
- @read_timeout = 60
- @continue_timeout = nil
- @debug_output = nil
-
- @proxy_from_env = false
- @proxy_uri = nil
- @proxy_address = nil
- @proxy_port = nil
- @proxy_user = nil
- @proxy_pass = nil
-
- @use_ssl = false
- @ssl_context = nil
- @ssl_session = nil
- @enable_post_connection_check = true
- @sspi_enabled = false
- SSL_IVNAMES.each do |ivname|
- instance_variable_set ivname, nil
- end
- end
-
- def inspect
- "#<#{self.class} #{@address}:#{@port} open=#{started?}>"
- end
-
- # *WARNING* This method opens a serious security hole.
- # Never use this method in production code.
- #
- # Sets an output stream for debugging.
- #
- # http = Net::HTTP.new(hostname)
- # http.set_debug_output $stderr
- # http.start { .... }
- #
- def set_debug_output(output)
- warn 'Net::HTTP#set_debug_output called after HTTP started' if started?
- @debug_output = output
- end
-
- # The DNS host name or IP address to connect to.
- attr_reader :address
-
- # The port number to connect to.
- attr_reader :port
-
- # The local host used to establish the connection.
- attr_accessor :local_host
-
- # The local port used to establish the connection.
- attr_accessor :local_port
-
- attr_writer :proxy_from_env
- attr_writer :proxy_address
- attr_writer :proxy_port
- attr_writer :proxy_user
- attr_writer :proxy_pass
-
- # Number of seconds to wait for the connection to open. Any number
- # may be used, including Floats for fractional seconds. If the HTTP
- # object cannot open a connection in this many seconds, it raises a
- # Net::OpenTimeout exception. The default value is +nil+.
- attr_accessor :open_timeout
-
- # Number of seconds to wait for one block to be read (via one read(2)
- # call). Any number may be used, including Floats for fractional
- # seconds. If the HTTP object cannot read data in this many seconds,
- # it raises a Net::ReadTimeout exception. The default value is 60 seconds.
- attr_reader :read_timeout
-
- # Setter for the read_timeout attribute.
- def read_timeout=(sec)
- @socket.read_timeout = sec if @socket
- @read_timeout = sec
- end
-
- # Seconds to wait for 100 Continue response. If the HTTP object does not
- # receive a response in this many seconds it sends the request body. The
- # default value is +nil+.
- attr_reader :continue_timeout
-
- # Setter for the continue_timeout attribute.
- def continue_timeout=(sec)
- @socket.continue_timeout = sec if @socket
- @continue_timeout = sec
- end
-
- # Seconds to reuse the connection of the previous request.
- # If the idle time is less than this Keep-Alive Timeout,
- # Net::HTTP reuses the TCP/IP socket used by the previous communication.
- # The default value is 2 seconds.
- attr_accessor :keep_alive_timeout
-
- # Returns true if the HTTP session has been started.
- def started?
- @started
- end
-
- alias active? started? #:nodoc: obsolete
-
- attr_accessor :close_on_empty_response
-
- # Returns true if SSL/TLS is being used with HTTP.
- def use_ssl?
- @use_ssl
- end
-
- # Turn on/off SSL.
- # This flag must be set before starting session.
- # If you change use_ssl value after session started,
- # a Net::HTTP object raises IOError.
- def use_ssl=(flag)
- flag = flag ? true : false
- if started? and @use_ssl != flag
- raise IOError, "use_ssl value changed, but session already started"
- end
- @use_ssl = flag
- end
-
- SSL_IVNAMES = [
- :@ca_file,
- :@ca_path,
- :@cert,
- :@cert_store,
- :@ciphers,
- :@key,
- :@ssl_timeout,
- :@ssl_version,
- :@verify_callback,
- :@verify_depth,
- :@verify_mode,
- ]
- SSL_ATTRIBUTES = [
- :ca_file,
- :ca_path,
- :cert,
- :cert_store,
- :ciphers,
- :key,
- :ssl_timeout,
- :ssl_version,
- :verify_callback,
- :verify_depth,
- :verify_mode,
- ]
-
- # Sets path of a CA certification file in PEM format.
- #
- # The file can contain several CA certificates.
- attr_accessor :ca_file
-
- # Sets path of a CA certification directory containing certifications in
- # PEM format.
- attr_accessor :ca_path
-
- # Sets an OpenSSL::X509::Certificate object as client certificate.
- # (This method is appeared in Michal Rokos's OpenSSL extension).
- attr_accessor :cert
-
- # Sets the X509::Store to verify peer certificate.
- attr_accessor :cert_store
-
- # Sets the available ciphers. See OpenSSL::SSL::SSLContext#ciphers=
- attr_accessor :ciphers
-
- # Sets an OpenSSL::PKey::RSA or OpenSSL::PKey::DSA object.
- # (This method is appeared in Michal Rokos's OpenSSL extension.)
- attr_accessor :key
-
- # Sets the SSL timeout seconds.
- attr_accessor :ssl_timeout
-
- # Sets the SSL version. See OpenSSL::SSL::SSLContext#ssl_version=
- attr_accessor :ssl_version
-
- # Sets the verify callback for the server certification verification.
- attr_accessor :verify_callback
-
- # Sets the maximum depth for the certificate chain verification.
- attr_accessor :verify_depth
-
- # Sets the flags for server the certification verification at beginning of
- # SSL/TLS session.
- #
- # OpenSSL::SSL::VERIFY_NONE or OpenSSL::SSL::VERIFY_PEER are acceptable.
- attr_accessor :verify_mode
-
- # Returns the X.509 certificates the server presented.
- def peer_cert
- if not use_ssl? or not @socket
- return nil
- end
- @socket.io.peer_cert
- end
-
- # Opens a TCP connection and HTTP session.
- #
- # When this method is called with a block, it passes the Net::HTTP
- # object to the block, and closes the TCP connection and HTTP session
- # after the block has been executed.
- #
- # When called with a block, it returns the return value of the
- # block; otherwise, it returns self.
- #
- def start # :yield: http
- raise IOError, 'HTTP session already opened' if @started
- if block_given?
- begin
- do_start
- return yield(self)
- ensure
- do_finish
- end
- end
- do_start
- self
- end
-
- def do_start
- connect
- @started = true
- end
- private :do_start
-
- def connect
- if proxy? then
- conn_address = proxy_address
- conn_port = proxy_port
- else
- conn_address = address
- conn_port = port
- end
-
- D "opening connection to #{conn_address}:#{conn_port}..."
- s = Timeout.timeout(@open_timeout, Net::OpenTimeout) {
- TCPSocket.open(conn_address, conn_port, @local_host, @local_port)
- }
- s.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
- D "opened"
- if use_ssl?
- ssl_parameters = Hash.new
- iv_list = instance_variables
- SSL_IVNAMES.each_with_index do |ivname, i|
- if iv_list.include?(ivname) and
- value = instance_variable_get(ivname)
- ssl_parameters[SSL_ATTRIBUTES[i]] = value if value
- end
- end
- @ssl_context = OpenSSL::SSL::SSLContext.new
- @ssl_context.set_params(ssl_parameters)
- D "starting SSL for #{conn_address}:#{conn_port}..."
- s = OpenSSL::SSL::SSLSocket.new(s, @ssl_context)
- s.sync_close = true
- D "SSL established"
- end
- @socket = BufferedIO.new(s)
- @socket.read_timeout = @read_timeout
- @socket.continue_timeout = @continue_timeout
- @socket.debug_output = @debug_output
- if use_ssl?
- begin
- if proxy?
- buf = "CONNECT #{@address}:#{@port} HTTP/#{HTTPVersion}\r\n"
- buf << "Host: #{@address}:#{@port}\r\n"
- if proxy_user
- credential = ["#{proxy_user}:#{proxy_pass}"].pack('m')
- credential.delete!("\r\n")
- buf << "Proxy-Authorization: Basic #{credential}\r\n"
- end
- buf << "\r\n"
- @socket.write(buf)
- HTTPResponse.read_new(@socket).value
- end
- # Server Name Indication (SNI) RFC 3546
- s.hostname = @address if s.respond_to? :hostname=
- if @ssl_session and
- Process.clock_gettime(Process::CLOCK_REALTIME) < @ssl_session.time.to_f + @ssl_session.timeout
- s.session = @ssl_session if @ssl_session
- end
- Timeout.timeout(@open_timeout, Net::OpenTimeout) { s.connect }
- if @ssl_context.verify_mode != OpenSSL::SSL::VERIFY_NONE
- s.post_connection_check(@address)
- end
- @ssl_session = s.session
- rescue => exception
- D "Conn close because of connect error #{exception}"
- @socket.close if @socket and not @socket.closed?
- raise exception
- end
- end
- on_connect
- end
- private :connect
-
- def on_connect
- end
- private :on_connect
-
- # Finishes the HTTP session and closes the TCP connection.
- # Raises IOError if the session has not been started.
- def finish
- raise IOError, 'HTTP session not yet started' unless started?
- do_finish
- end
-
- def do_finish
- @started = false
- @socket.close if @socket and not @socket.closed?
- @socket = nil
- end
- private :do_finish
-
- #
- # proxy
- #
-
- public
-
- # no proxy
- @is_proxy_class = false
- @proxy_from_env = false
- @proxy_addr = nil
- @proxy_port = nil
- @proxy_user = nil
- @proxy_pass = nil
-
- # Creates an HTTP proxy class which behaves like Net::HTTP, but
- # performs all access via the specified proxy.
- #
- # This class is obsolete. You may pass these same parameters directly to
- # Net::HTTP.new. See Net::HTTP.new for details of the arguments.
- def HTTP.Proxy(p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil)
- return self unless p_addr
-
- Class.new(self) {
- @is_proxy_class = true
-
- if p_addr == :ENV then
- @proxy_from_env = true
- @proxy_address = nil
- @proxy_port = nil
- else
- @proxy_from_env = false
- @proxy_address = p_addr
- @proxy_port = p_port || default_port
- end
-
- @proxy_user = p_user
- @proxy_pass = p_pass
- }
- end
-
- class << HTTP
- # returns true if self is a class which was created by HTTP::Proxy.
- def proxy_class?
- defined?(@is_proxy_class) ? @is_proxy_class : false
- end
-
- # Address of proxy host. If Net::HTTP does not use a proxy, nil.
- attr_reader :proxy_address
-
- # Port number of proxy host. If Net::HTTP does not use a proxy, nil.
- attr_reader :proxy_port
-
- # User name for accessing proxy. If Net::HTTP does not use a proxy, nil.
- attr_reader :proxy_user
-
- # User password for accessing proxy. If Net::HTTP does not use a proxy,
- # nil.
- attr_reader :proxy_pass
- end
-
- # True if requests for this connection will be proxied
- def proxy?
- !!if @proxy_from_env then
- proxy_uri
- else
- @proxy_address
- end
- end
-
- # True if the proxy for this connection is determined from the environment
- def proxy_from_env?
- @proxy_from_env
- end
-
- # The proxy URI determined from the environment for this connection.
- def proxy_uri # :nodoc:
- @proxy_uri ||= URI::HTTP.new(
- "http".freeze, nil, address, port, nil, nil, nil, nil, nil
- ).find_proxy
- end
-
- # The address of the proxy server, if one is configured.
- def proxy_address
- if @proxy_from_env then
- proxy_uri && proxy_uri.hostname
- else
- @proxy_address
- end
- end
-
- # The port of the proxy server, if one is configured.
- def proxy_port
- if @proxy_from_env then
- proxy_uri && proxy_uri.port
- else
- @proxy_port
- end
- end
-
- # The proxy username, if one is configured
- def proxy_user
- @proxy_user
- end
-
- # The proxy password, if one is configured
- def proxy_pass
- @proxy_pass
- end
-
- alias proxyaddr proxy_address #:nodoc: obsolete
- alias proxyport proxy_port #:nodoc: obsolete
-
- private
-
- # without proxy, obsolete
-
- def conn_address # :nodoc:
- address()
- end
-
- def conn_port # :nodoc:
- port()
- end
-
- def edit_path(path)
- if proxy? and not use_ssl? then
- "http://#{addr_port}#{path}"
- else
- path
- end
- end
-
- #
- # HTTP operations
- #
-
- public
-
- # Retrieves data from +path+ on the connected-to host which may be an
- # absolute path String or a URI to extract the path from.
- #
- # +initheader+ must be a Hash like { 'Accept' => '*/*', ... },
- # and it defaults to an empty hash.
- # If +initheader+ doesn't have the key 'accept-encoding', then
- # a value of "gzip;q=1.0,deflate;q=0.6,identity;q=0.3" is used,
- # so that gzip compression is used in preference to deflate
- # compression, which is used in preference to no compression.
- # Ruby doesn't have libraries to support the compress (Lempel-Ziv)
- # compression, so that is not supported. The intent of this is
- # to reduce bandwidth by default. If this routine sets up
- # compression, then it does the decompression also, removing
- # the header as well to prevent confusion. Otherwise
- # it leaves the body as it found it.
- #
- # This method returns a Net::HTTPResponse object.
- #
- # If called with a block, yields each fragment of the
- # entity body in turn as a string as it is read from
- # the socket. Note that in this case, the returned response
- # object will *not* contain a (meaningful) body.
- #
- # +dest+ argument is obsolete.
- # It still works but you must not use it.
- #
- # This method never raises an exception.
- #
- # response = http.get('/index.html')
- #
- # # using block
- # File.open('result.txt', 'w') {|f|
- # http.get('/~foo/') do |str|
- # f.write str
- # end
- # }
- #
- def get(path, initheader = nil, dest = nil, &block) # :yield: +body_segment+
- res = nil
- request(Get.new(path, initheader)) {|r|
- r.read_body dest, &block
- res = r
- }
- res
- end
-
- # Gets only the header from +path+ on the connected-to host.
- # +header+ is a Hash like { 'Accept' => '*/*', ... }.
- #
- # This method returns a Net::HTTPResponse object.
- #
- # This method never raises an exception.
- #
- # response = nil
- # Net::HTTP.start('some.www.server', 80) {|http|
- # response = http.head('/index.html')
- # }
- # p response['content-type']
- #
- def head(path, initheader = nil)
- request(Head.new(path, initheader))
- end
-
- # Posts +data+ (must be a String) to +path+. +header+ must be a Hash
- # like { 'Accept' => '*/*', ... }.
- #
- # This method returns a Net::HTTPResponse object.
- #
- # If called with a block, yields each fragment of the
- # entity body in turn as a string as it is read from
- # the socket. Note that in this case, the returned response
- # object will *not* contain a (meaningful) body.
- #
- # +dest+ argument is obsolete.
- # It still works but you must not use it.
- #
- # This method never raises exception.
- #
- # response = http.post('/cgi-bin/search.rb', 'query=foo')
- #
- # # using block
- # File.open('result.txt', 'w') {|f|
- # http.post('/cgi-bin/search.rb', 'query=foo') do |str|
- # f.write str
- # end
- # }
- #
- # You should set Content-Type: header field for POST.
- # If no Content-Type: field given, this method uses
- # "application/x-www-form-urlencoded" by default.
- #
- def post(path, data, initheader = nil, dest = nil, &block) # :yield: +body_segment+
- send_entity(path, data, initheader, dest, Post, &block)
- end
-
- # Sends a PATCH request to the +path+ and gets a response,
- # as an HTTPResponse object.
- def patch(path, data, initheader = nil, dest = nil, &block) # :yield: +body_segment+
- send_entity(path, data, initheader, dest, Patch, &block)
- end
-
- def put(path, data, initheader = nil) #:nodoc:
- request(Put.new(path, initheader), data)
- end
-
- # Sends a PROPPATCH request to the +path+ and gets a response,
- # as an HTTPResponse object.
- def proppatch(path, body, initheader = nil)
- request(Proppatch.new(path, initheader), body)
- end
-
- # Sends a LOCK request to the +path+ and gets a response,
- # as an HTTPResponse object.
- def lock(path, body, initheader = nil)
- request(Lock.new(path, initheader), body)
- end
-
- # Sends a UNLOCK request to the +path+ and gets a response,
- # as an HTTPResponse object.
- def unlock(path, body, initheader = nil)
- request(Unlock.new(path, initheader), body)
- end
-
- # Sends a OPTIONS request to the +path+ and gets a response,
- # as an HTTPResponse object.
- def options(path, initheader = nil)
- request(Options.new(path, initheader))
- end
-
- # Sends a PROPFIND request to the +path+ and gets a response,
- # as an HTTPResponse object.
- def propfind(path, body = nil, initheader = {'Depth' => '0'})
- request(Propfind.new(path, initheader), body)
- end
-
- # Sends a DELETE request to the +path+ and gets a response,
- # as an HTTPResponse object.
- def delete(path, initheader = {'Depth' => 'Infinity'})
- request(Delete.new(path, initheader))
- end
-
- # Sends a MOVE request to the +path+ and gets a response,
- # as an HTTPResponse object.
- def move(path, initheader = nil)
- request(Move.new(path, initheader))
- end
-
- # Sends a COPY request to the +path+ and gets a response,
- # as an HTTPResponse object.
- def copy(path, initheader = nil)
- request(Copy.new(path, initheader))
- end
-
- # Sends a MKCOL request to the +path+ and gets a response,
- # as an HTTPResponse object.
- def mkcol(path, body = nil, initheader = nil)
- request(Mkcol.new(path, initheader), body)
- end
-
- # Sends a TRACE request to the +path+ and gets a response,
- # as an HTTPResponse object.
- def trace(path, initheader = nil)
- request(Trace.new(path, initheader))
- end
-
- # Sends a GET request to the +path+.
- # Returns the response as a Net::HTTPResponse object.
- #
- # When called with a block, passes an HTTPResponse object to the block.
- # The body of the response will not have been read yet;
- # the block can process it using HTTPResponse#read_body,
- # if desired.
- #
- # Returns the response.
- #
- # This method never raises Net::* exceptions.
- #
- # response = http.request_get('/index.html')
- # # The entity body is already read in this case.
- # p response['content-type']
- # puts response.body
- #
- # # Using a block
- # http.request_get('/index.html') {|response|
- # p response['content-type']
- # response.read_body do |str| # read body now
- # print str
- # end
- # }
- #
- def request_get(path, initheader = nil, &block) # :yield: +response+
- request(Get.new(path, initheader), &block)
- end
-
- # Sends a HEAD request to the +path+ and returns the response
- # as a Net::HTTPResponse object.
- #
- # Returns the response.
- #
- # This method never raises Net::* exceptions.
- #
- # response = http.request_head('/index.html')
- # p response['content-type']
- #
- def request_head(path, initheader = nil, &block)
- request(Head.new(path, initheader), &block)
- end
-
- # Sends a POST request to the +path+.
- #
- # Returns the response as a Net::HTTPResponse object.
- #
- # When called with a block, the block is passed an HTTPResponse
- # object. The body of that response will not have been read yet;
- # the block can process it using HTTPResponse#read_body, if desired.
- #
- # Returns the response.
- #
- # This method never raises Net::* exceptions.
- #
- # # example
- # response = http.request_post('/cgi-bin/nice.rb', 'datadatadata...')
- # p response.status
- # puts response.body # body is already read in this case
- #
- # # using block
- # http.request_post('/cgi-bin/nice.rb', 'datadatadata...') {|response|
- # p response.status
- # p response['content-type']
- # response.read_body do |str| # read body now
- # print str
- # end
- # }
- #
- def request_post(path, data, initheader = nil, &block) # :yield: +response+
- request Post.new(path, initheader), data, &block
- end
-
- def request_put(path, data, initheader = nil, &block) #:nodoc:
- request Put.new(path, initheader), data, &block
- end
-
- alias get2 request_get #:nodoc: obsolete
- alias head2 request_head #:nodoc: obsolete
- alias post2 request_post #:nodoc: obsolete
- alias put2 request_put #:nodoc: obsolete
-
-
- # Sends an HTTP request to the HTTP server.
- # Also sends a DATA string if +data+ is given.
- #
- # Returns a Net::HTTPResponse object.
- #
- # This method never raises Net::* exceptions.
- #
- # response = http.send_request('GET', '/index.html')
- # puts response.body
- #
- def send_request(name, path, data = nil, header = nil)
- has_response_body = name != 'HEAD'
- r = HTTPGenericRequest.new(name,(data ? true : false),has_response_body,path,header)
- request r, data
- end
-
- # Sends an HTTPRequest object +req+ to the HTTP server.
- #
- # If +req+ is a Net::HTTP::Post or Net::HTTP::Put request containing
- # data, the data is also sent. Providing data for a Net::HTTP::Head or
- # Net::HTTP::Get request results in an ArgumentError.
- #
- # Returns an HTTPResponse object.
- #
- # When called with a block, passes an HTTPResponse object to the block.
- # The body of the response will not have been read yet;
- # the block can process it using HTTPResponse#read_body,
- # if desired.
- #
- # This method never raises Net::* exceptions.
- #
- def request(req, body = nil, &block) # :yield: +response+
- unless started?
- start {
- req['connection'] ||= 'close'
- return request(req, body, &block)
- }
- end
- if proxy_user()
- req.proxy_basic_auth proxy_user(), proxy_pass() unless use_ssl?
- end
- req.set_body_internal body
- res = transport_request(req, &block)
- if sspi_auth?(res)
- sspi_auth(req)
- res = transport_request(req, &block)
- end
- res
- end
-
- private
-
- # Executes a request which uses a representation
- # and returns its body.
- def send_entity(path, data, initheader, dest, type, &block)
- res = nil
- request(type.new(path, initheader), data) {|r|
- r.read_body dest, &block
- res = r
- }
- res
- end
-
- IDEMPOTENT_METHODS_ = %w/GET HEAD PUT DELETE OPTIONS TRACE/ # :nodoc:
-
- def transport_request(req)
- count = 0
- begin
- begin_transport req
- res = catch(:response) {
- req.exec @socket, @curr_http_version, edit_path(req.path)
- begin
- res = HTTPResponse.read_new(@socket)
- res.decode_content = req.decode_content
- end while res.kind_of?(HTTPContinue)
-
- res.uri = req.uri
-
- res
- }
- res.reading_body(@socket, req.response_body_permitted?) {
- yield res if block_given?
- }
- rescue Net::OpenTimeout
- raise
- rescue Net::ReadTimeout, IOError, EOFError,
- Errno::ECONNRESET, Errno::ECONNABORTED, Errno::EPIPE,
- # avoid a dependency on OpenSSL
- defined?(OpenSSL::SSL) ? OpenSSL::SSL::SSLError : IOError,
- Timeout::Error => exception
- if count == 0 && IDEMPOTENT_METHODS_.include?(req.method)
- count += 1
- @socket.close if @socket and not @socket.closed?
- D "Conn close because of error #{exception}, and retry"
- retry
- end
- D "Conn close because of error #{exception}"
- @socket.close if @socket and not @socket.closed?
- raise
- end
-
- end_transport req, res
- res
- rescue => exception
- D "Conn close because of error #{exception}"
- @socket.close if @socket and not @socket.closed?
- raise exception
- end
-
- def begin_transport(req)
- if @socket.closed?
- connect
- elsif @last_communicated && @last_communicated + @keep_alive_timeout < Time.now
- D 'Conn close because of keep_alive_timeout'
- @socket.close
- connect
- end
-
- if not req.response_body_permitted? and @close_on_empty_response
- req['connection'] ||= 'close'
- end
-
- req.update_uri address, port, use_ssl?
- req['host'] ||= addr_port()
- end
-
- def end_transport(req, res)
- @curr_http_version = res.http_version
- @last_communicated = nil
- if @socket.closed?
- D 'Conn socket closed'
- elsif not res.body and @close_on_empty_response
- D 'Conn close'
- @socket.close
- elsif keep_alive?(req, res)
- D 'Conn keep-alive'
- @last_communicated = Time.now
- else
- D 'Conn close'
- @socket.close
- end
- end
-
- def keep_alive?(req, res)
- return false if req.connection_close?
- if @curr_http_version <= '1.0'
- res.connection_keep_alive?
- else # HTTP/1.1 or later
- not res.connection_close?
- end
- end
-
- def sspi_auth?(res)
- return false unless @sspi_enabled
- if res.kind_of?(HTTPProxyAuthenticationRequired) and
- proxy? and res["Proxy-Authenticate"].include?("Negotiate")
- begin
- require 'win32/sspi'
- true
- rescue LoadError
- false
- end
- else
- false
- end
- end
-
- def sspi_auth(req)
- n = Win32::SSPI::NegotiateAuth.new
- req["Proxy-Authorization"] = "Negotiate #{n.get_initial_token}"
- # Some versions of ISA will close the connection if this isn't present.
- req["Connection"] = "Keep-Alive"
- req["Proxy-Connection"] = "Keep-Alive"
- res = transport_request(req)
- authphrase = res["Proxy-Authenticate"] or return res
- req["Proxy-Authorization"] = "Negotiate #{n.complete_authentication(authphrase)}"
- rescue => err
- raise HTTPAuthenticationError.new('HTTP authentication failed', err)
- end
-
- #
- # utils
- #
-
- private
-
- def addr_port
- if use_ssl?
- address() + (port == HTTP.https_default_port ? '' : ":#{port()}")
- else
- address() + (port == HTTP.http_default_port ? '' : ":#{port()}")
- end
- end
-
- def D(msg)
- return unless @debug_output
- @debug_output << msg
- @debug_output << "\n"
- end
- end
-
-end
-
-require 'net/http/exceptions'
-
-require 'net/http/header'
-
-require 'net/http/generic_request'
-require 'net/http/request'
-require 'net/http/requests'
-
-require 'net/http/response'
-require 'net/http/responses'
-
-require 'net/http/proxy_delta'
-
-require 'net/http/backward'
-
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/backward.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/backward.rb
deleted file mode 100755
index faf47b848..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/backward.rb
+++ /dev/null
@@ -1,25 +0,0 @@
-# for backward compatibility
-
-# :enddoc:
-
-class Net::HTTP
- ProxyMod = ProxyDelta
-end
-
-module Net
- HTTPSession = Net::HTTP
-end
-
-module Net::NetPrivate
- HTTPRequest = ::Net::HTTPRequest
-end
-
-Net::HTTPInformationCode = Net::HTTPInformation
-Net::HTTPSuccessCode = Net::HTTPSuccess
-Net::HTTPRedirectionCode = Net::HTTPRedirection
-Net::HTTPRetriableCode = Net::HTTPRedirection
-Net::HTTPClientErrorCode = Net::HTTPClientError
-Net::HTTPFatalErrorCode = Net::HTTPClientError
-Net::HTTPServerErrorCode = Net::HTTPServerError
-Net::HTTPResponceReceiver = Net::HTTPResponse
-
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/exceptions.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/exceptions.rb
deleted file mode 100755
index 6c5d81cb0..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/exceptions.rb
+++ /dev/null
@@ -1,25 +0,0 @@
-# Net::HTTP exception class.
-# You cannot use Net::HTTPExceptions directly; instead, you must use
-# its subclasses.
-module Net::HTTPExceptions
- def initialize(msg, res) #:nodoc:
- super msg
- @response = res
- end
- attr_reader :response
- alias data response #:nodoc: obsolete
-end
-class Net::HTTPError < Net::ProtocolError
- include Net::HTTPExceptions
-end
-class Net::HTTPRetriableError < Net::ProtoRetriableError
- include Net::HTTPExceptions
-end
-class Net::HTTPServerException < Net::ProtoServerError
- # We cannot use the name "HTTPServerError", it is the name of the response.
- include Net::HTTPExceptions
-end
-class Net::HTTPFatalError < Net::ProtoFatalError
- include Net::HTTPExceptions
-end
-
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/generic_request.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/generic_request.rb
deleted file mode 100755
index 00ff434cc..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/generic_request.rb
+++ /dev/null
@@ -1,332 +0,0 @@
-# HTTPGenericRequest is the parent of the HTTPRequest class.
-# Do not use this directly; use a subclass of HTTPRequest.
-#
-# Mixes in the HTTPHeader module to provide easier access to HTTP headers.
-#
-class Net::HTTPGenericRequest
-
- include Net::HTTPHeader
-
- def initialize(m, reqbody, resbody, uri_or_path, initheader = nil)
- @method = m
- @request_has_body = reqbody
- @response_has_body = resbody
-
- if URI === uri_or_path then
- @uri = uri_or_path.dup
- host = @uri.hostname.dup
- host << ":".freeze << @uri.port.to_s if @uri.port != @uri.default_port
- @path = uri_or_path.request_uri
- raise ArgumentError, "no HTTP request path given" unless @path
- else
- @uri = nil
- host = nil
- raise ArgumentError, "no HTTP request path given" unless uri_or_path
- raise ArgumentError, "HTTP request path is empty" if uri_or_path.empty?
- @path = uri_or_path.dup
- end
-
- @decode_content = false
-
- if @response_has_body and Net::HTTP::HAVE_ZLIB then
- if !initheader ||
- !initheader.keys.any? { |k|
- %w[accept-encoding range].include? k.downcase
- } then
- @decode_content = true
- initheader = initheader ? initheader.dup : {}
- initheader["accept-encoding"] =
- "gzip;q=1.0,deflate;q=0.6,identity;q=0.3"
- end
- end
-
- initialize_http_header initheader
- self['Accept'] ||= '*/*'
- self['User-Agent'] ||= 'Ruby'
- self['Host'] ||= host if host
- @body = nil
- @body_stream = nil
- @body_data = nil
- end
-
- attr_reader :method
- attr_reader :path
- attr_reader :uri
-
- # Automatically set to false if the user sets the Accept-Encoding header.
- # This indicates they wish to handle Content-encoding in responses
- # themselves.
- attr_reader :decode_content
-
- def inspect
- "\#<#{self.class} #{@method}>"
- end
-
- ##
- # Don't automatically decode response content-encoding if the user indicates
- # they want to handle it.
-
- def []=(key, val) # :nodoc:
- @decode_content = false if key.downcase == 'accept-encoding'
-
- super key, val
- end
-
- def request_body_permitted?
- @request_has_body
- end
-
- def response_body_permitted?
- @response_has_body
- end
-
- def body_exist?
- warn "Net::HTTPRequest#body_exist? is obsolete; use response_body_permitted?" if $VERBOSE
- response_body_permitted?
- end
-
- attr_reader :body
-
- def body=(str)
- @body = str
- @body_stream = nil
- @body_data = nil
- str
- end
-
- attr_reader :body_stream
-
- def body_stream=(input)
- @body = nil
- @body_stream = input
- @body_data = nil
- input
- end
-
- def set_body_internal(str) #:nodoc: internal use only
- raise ArgumentError, "both of body argument and HTTPRequest#body set" if str and (@body or @body_stream)
- self.body = str if str
- if @body.nil? && @body_stream.nil? && @body_data.nil? && request_body_permitted?
- self.body = ''
- end
- end
-
- #
- # write
- #
-
- def exec(sock, ver, path) #:nodoc: internal use only
- if @body
- send_request_with_body sock, ver, path, @body
- elsif @body_stream
- send_request_with_body_stream sock, ver, path, @body_stream
- elsif @body_data
- send_request_with_body_data sock, ver, path, @body_data
- else
- write_header sock, ver, path
- end
- end
-
- def update_uri(addr, port, ssl) # :nodoc: internal use only
- # reflect the connection and @path to @uri
- return unless @uri
-
- if ssl
- scheme = 'https'.freeze
- klass = URI::HTTPS
- else
- scheme = 'http'.freeze
- klass = URI::HTTP
- end
-
- if host = self['host']
- host.sub!(/:.*/s, ''.freeze)
- elsif host = @uri.host
- else
- host = addr
- end
- # convert the class of the URI
- if @uri.is_a?(klass)
- @uri.host = host
- @uri.port = port
- else
- @uri = klass.new(
- scheme, @uri.userinfo,
- host, port, nil,
- @uri.path, nil, @uri.query, nil)
- end
- end
-
- private
-
- class Chunker #:nodoc:
- def initialize(sock)
- @sock = sock
- @prev = nil
- end
-
- def write(buf)
- # avoid memcpy() of buf, buf can huge and eat memory bandwidth
- @sock.write("#{buf.bytesize.to_s(16)}\r\n")
- rv = @sock.write(buf)
- @sock.write("\r\n")
- rv
- end
-
- def finish
- @sock.write("0\r\n\r\n")
- end
- end
-
- def send_request_with_body(sock, ver, path, body)
- self.content_length = body.bytesize
- delete 'Transfer-Encoding'
- supply_default_content_type
- write_header sock, ver, path
- wait_for_continue sock, ver if sock.continue_timeout
- sock.write body
- end
-
- def send_request_with_body_stream(sock, ver, path, f)
- unless content_length() or chunked?
- raise ArgumentError,
- "Content-Length not given and Transfer-Encoding is not `chunked'"
- end
- supply_default_content_type
- write_header sock, ver, path
- wait_for_continue sock, ver if sock.continue_timeout
- if chunked?
- chunker = Chunker.new(sock)
- IO.copy_stream(f, chunker)
- chunker.finish
- else
- # copy_stream can sendfile() to sock.io unless we use SSL.
- # If sock.io is an SSLSocket, copy_stream will hit SSL_write()
- IO.copy_stream(f, sock.io)
- end
- end
-
- def send_request_with_body_data(sock, ver, path, params)
- if /\Amultipart\/form-data\z/i !~ self.content_type
- self.content_type = 'application/x-www-form-urlencoded'
- return send_request_with_body(sock, ver, path, URI.encode_www_form(params))
- end
-
- opt = @form_option.dup
- require 'securerandom' unless defined?(SecureRandom)
- opt[:boundary] ||= SecureRandom.urlsafe_base64(40)
- self.set_content_type(self.content_type, boundary: opt[:boundary])
- if chunked?
- write_header sock, ver, path
- encode_multipart_form_data(sock, params, opt)
- else
- require 'tempfile'
- file = Tempfile.new('multipart')
- file.binmode
- encode_multipart_form_data(file, params, opt)
- file.rewind
- self.content_length = file.size
- write_header sock, ver, path
- IO.copy_stream(file, sock)
- file.close(true)
- end
- end
-
- def encode_multipart_form_data(out, params, opt)
- charset = opt[:charset]
- boundary = opt[:boundary]
- require 'securerandom' unless defined?(SecureRandom)
- boundary ||= SecureRandom.urlsafe_base64(40)
- chunked_p = chunked?
-
- buf = ''
- params.each do |key, value, h={}|
- key = quote_string(key, charset)
- filename =
- h.key?(:filename) ? h[:filename] :
- value.respond_to?(:to_path) ? File.basename(value.to_path) :
- nil
-
- buf << "--#{boundary}\r\n"
- if filename
- filename = quote_string(filename, charset)
- type = h[:content_type] || 'application/octet-stream'
- buf << "Content-Disposition: form-data; " \
- "name=\"#{key}\"; filename=\"#{filename}\"\r\n" \
- "Content-Type: #{type}\r\n\r\n"
- if !out.respond_to?(:write) || !value.respond_to?(:read)
- # if +out+ is not an IO or +value+ is not an IO
- buf << (value.respond_to?(:read) ? value.read : value)
- elsif value.respond_to?(:size) && chunked_p
- # if +out+ is an IO and +value+ is a File, use IO.copy_stream
- flush_buffer(out, buf, chunked_p)
- out << "%x\r\n" % value.size if chunked_p
- IO.copy_stream(value, out)
- out << "\r\n" if chunked_p
- else
- # +out+ is an IO, and +value+ is not a File but an IO
- flush_buffer(out, buf, chunked_p)
- 1 while flush_buffer(out, value.read(4096), chunked_p)
- end
- else
- # non-file field:
- # HTML5 says, "The parts of the generated multipart/form-data
- # resource that correspond to non-file fields must not have a
- # Content-Type header specified."
- buf << "Content-Disposition: form-data; name=\"#{key}\"\r\n\r\n"
- buf << (value.respond_to?(:read) ? value.read : value)
- end
- buf << "\r\n"
- end
- buf << "--#{boundary}--\r\n"
- flush_buffer(out, buf, chunked_p)
- out << "0\r\n\r\n" if chunked_p
- end
-
- def quote_string(str, charset)
- str = str.encode(charset, fallback:->(c){'%d;'%c.encode("UTF-8").ord}) if charset
- str.gsub(/[\\"]/, '\\\\\&')
- end
-
- def flush_buffer(out, buf, chunked_p)
- return unless buf
- out << "%x\r\n"%buf.bytesize if chunked_p
- out << buf
- out << "\r\n" if chunked_p
- buf.clear
- end
-
- def supply_default_content_type
- return if content_type()
- warn 'net/http: warning: Content-Type did not set; using application/x-www-form-urlencoded' if $VERBOSE
- set_content_type 'application/x-www-form-urlencoded'
- end
-
- ##
- # Waits up to the continue timeout for a response from the server provided
- # we're speaking HTTP 1.1 and are expecting a 100-continue response.
-
- def wait_for_continue(sock, ver)
- if ver >= '1.1' and @header['expect'] and
- @header['expect'].include?('100-continue')
- if IO.select([sock.io], nil, nil, sock.continue_timeout)
- res = Net::HTTPResponse.read_new(sock)
- unless res.kind_of?(Net::HTTPContinue)
- res.decode_content = @decode_content
- throw :response, res
- end
- end
- end
- end
-
- def write_header(sock, ver, path)
- buf = "#{@method} #{path} HTTP/#{ver}\r\n"
- each_capitalized do |k,v|
- buf << "#{k}: #{v}\r\n"
- end
- buf << "\r\n"
- sock.write buf
- end
-
-end
-
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/header.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/header.rb
deleted file mode 100755
index 912419df5..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/header.rb
+++ /dev/null
@@ -1,452 +0,0 @@
-# The HTTPHeader module defines methods for reading and writing
-# HTTP headers.
-#
-# It is used as a mixin by other classes, to provide hash-like
-# access to HTTP header values. Unlike raw hash access, HTTPHeader
-# provides access via case-insensitive keys. It also provides
-# methods for accessing commonly-used HTTP header values in more
-# convenient formats.
-#
-module Net::HTTPHeader
-
- def initialize_http_header(initheader)
- @header = {}
- return unless initheader
- initheader.each do |key, value|
- warn "net/http: warning: duplicated HTTP header: #{key}" if key?(key) and $VERBOSE
- @header[key.downcase] = [value.strip]
- end
- end
-
- def size #:nodoc: obsolete
- @header.size
- end
-
- alias length size #:nodoc: obsolete
-
- # Returns the header field corresponding to the case-insensitive key.
- # For example, a key of "Content-Type" might return "text/html"
- def [](key)
- a = @header[key.downcase] or return nil
- a.join(', ')
- end
-
- # Sets the header field corresponding to the case-insensitive key.
- def []=(key, val)
- unless val
- @header.delete key.downcase
- return val
- end
- @header[key.downcase] = [val]
- end
-
- # [Ruby 1.8.3]
- # Adds a value to a named header field, instead of replacing its value.
- # Second argument +val+ must be a String.
- # See also #[]=, #[] and #get_fields.
- #
- # request.add_field 'X-My-Header', 'a'
- # p request['X-My-Header'] #=> "a"
- # p request.get_fields('X-My-Header') #=> ["a"]
- # request.add_field 'X-My-Header', 'b'
- # p request['X-My-Header'] #=> "a, b"
- # p request.get_fields('X-My-Header') #=> ["a", "b"]
- # request.add_field 'X-My-Header', 'c'
- # p request['X-My-Header'] #=> "a, b, c"
- # p request.get_fields('X-My-Header') #=> ["a", "b", "c"]
- #
- def add_field(key, val)
- if @header.key?(key.downcase)
- @header[key.downcase].push val
- else
- @header[key.downcase] = [val]
- end
- end
-
- # [Ruby 1.8.3]
- # Returns an array of header field strings corresponding to the
- # case-insensitive +key+. This method allows you to get duplicated
- # header fields without any processing. See also #[].
- #
- # p response.get_fields('Set-Cookie')
- # #=> ["session=al98axx; expires=Fri, 31-Dec-1999 23:58:23",
- # "query=rubyscript; expires=Fri, 31-Dec-1999 23:58:23"]
- # p response['Set-Cookie']
- # #=> "session=al98axx; expires=Fri, 31-Dec-1999 23:58:23, query=rubyscript; expires=Fri, 31-Dec-1999 23:58:23"
- #
- def get_fields(key)
- return nil unless @header[key.downcase]
- @header[key.downcase].dup
- end
-
- # Returns the header field corresponding to the case-insensitive key.
- # Returns the default value +args+, or the result of the block, or
- # raises an IndexError if there's no header field named +key+
- # See Hash#fetch
- def fetch(key, *args, &block) #:yield: +key+
- a = @header.fetch(key.downcase, *args, &block)
- a.kind_of?(Array) ? a.join(', ') : a
- end
-
- # Iterates through the header names and values, passing in the name
- # and value to the code block supplied.
- #
- # Example:
- #
- # response.header.each_header {|key,value| puts "#{key} = #{value}" }
- #
- def each_header #:yield: +key+, +value+
- block_given? or return enum_for(__method__)
- @header.each do |k,va|
- yield k, va.join(', ')
- end
- end
-
- alias each each_header
-
- # Iterates through the header names in the header, passing
- # each header name to the code block.
- def each_name(&block) #:yield: +key+
- block_given? or return enum_for(__method__)
- @header.each_key(&block)
- end
-
- alias each_key each_name
-
- # Iterates through the header names in the header, passing
- # capitalized header names to the code block.
- #
- # Note that header names are capitalized systematically;
- # capitalization may not match that used by the remote HTTP
- # server in its response.
- def each_capitalized_name #:yield: +key+
- block_given? or return enum_for(__method__)
- @header.each_key do |k|
- yield capitalize(k)
- end
- end
-
- # Iterates through header values, passing each value to the
- # code block.
- def each_value #:yield: +value+
- block_given? or return enum_for(__method__)
- @header.each_value do |va|
- yield va.join(', ')
- end
- end
-
- # Removes a header field, specified by case-insensitive key.
- def delete(key)
- @header.delete(key.downcase)
- end
-
- # true if +key+ header exists.
- def key?(key)
- @header.key?(key.downcase)
- end
-
- # Returns a Hash consisting of header names and array of values.
- # e.g.
- # {"cache-control" => ["private"],
- # "content-type" => ["text/html"],
- # "date" => ["Wed, 22 Jun 2005 22:11:50 GMT"]}
- def to_hash
- @header.dup
- end
-
- # As for #each_header, except the keys are provided in capitalized form.
- #
- # Note that header names are capitalized systematically;
- # capitalization may not match that used by the remote HTTP
- # server in its response.
- def each_capitalized
- block_given? or return enum_for(__method__)
- @header.each do |k,v|
- yield capitalize(k), v.join(', ')
- end
- end
-
- alias canonical_each each_capitalized
-
- def capitalize(name)
- name.split(/-/).map {|s| s.capitalize }.join('-')
- end
- private :capitalize
-
- # Returns an Array of Range objects which represent the Range:
- # HTTP header field, or +nil+ if there is no such header.
- def range
- return nil unless @header['range']
-
- value = self['Range']
- # byte-range-set = *( "," OWS ) ( byte-range-spec / suffix-byte-range-spec )
- # *( OWS "," [ OWS ( byte-range-spec / suffix-byte-range-spec ) ] )
- # corrected collected ABNF
- # http://tools.ietf.org/html/draft-ietf-httpbis-p5-range-19#section-5.4.1
- # http://tools.ietf.org/html/draft-ietf-httpbis-p5-range-19#appendix-C
- # http://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-19#section-3.2.5
- unless /\Abytes=((?:,[ \t]*)*(?:\d+-\d*|-\d+)(?:[ \t]*,(?:[ \t]*\d+-\d*|-\d+)?)*)\z/ =~ value
- raise Net::HTTPHeaderSyntaxError, "invalid syntax for byte-ranges-specifier: '#{value}'"
- end
-
- byte_range_set = $1
- result = byte_range_set.split(/,/).map {|spec|
- m = /(\d+)?\s*-\s*(\d+)?/i.match(spec) or
- raise Net::HTTPHeaderSyntaxError, "invalid byte-range-spec: '#{spec}'"
- d1 = m[1].to_i
- d2 = m[2].to_i
- if m[1] and m[2]
- if d1 > d2
- raise Net::HTTPHeaderSyntaxError, "last-byte-pos MUST greater than or equal to first-byte-pos but '#{spec}'"
- end
- d1..d2
- elsif m[1]
- d1..-1
- elsif m[2]
- -d2..-1
- else
- raise Net::HTTPHeaderSyntaxError, 'range is not specified'
- end
- }
- # if result.empty?
- # byte-range-set must include at least one byte-range-spec or suffix-byte-range-spec
- # but above regexp already denies it.
- if result.size == 1 && result[0].begin == 0 && result[0].end == -1
- raise Net::HTTPHeaderSyntaxError, 'only one suffix-byte-range-spec with zero suffix-length'
- end
- result
- end
-
- # Sets the HTTP Range: header.
- # Accepts either a Range object as a single argument,
- # or a beginning index and a length from that index.
- # Example:
- #
- # req.range = (0..1023)
- # req.set_range 0, 1023
- #
- def set_range(r, e = nil)
- unless r
- @header.delete 'range'
- return r
- end
- r = (r...r+e) if e
- case r
- when Numeric
- n = r.to_i
- rangestr = (n > 0 ? "0-#{n-1}" : "-#{-n}")
- when Range
- first = r.first
- last = r.end
- last -= 1 if r.exclude_end?
- if last == -1
- rangestr = (first > 0 ? "#{first}-" : "-#{-first}")
- else
- raise Net::HTTPHeaderSyntaxError, 'range.first is negative' if first < 0
- raise Net::HTTPHeaderSyntaxError, 'range.last is negative' if last < 0
- raise Net::HTTPHeaderSyntaxError, 'must be .first < .last' if first > last
- rangestr = "#{first}-#{last}"
- end
- else
- raise TypeError, 'Range/Integer is required'
- end
- @header['range'] = ["bytes=#{rangestr}"]
- r
- end
-
- alias range= set_range
-
- # Returns an Integer object which represents the HTTP Content-Length:
- # header field, or +nil+ if that field was not provided.
- def content_length
- return nil unless key?('Content-Length')
- len = self['Content-Length'].slice(/\d+/) or
- raise Net::HTTPHeaderSyntaxError, 'wrong Content-Length format'
- len.to_i
- end
-
- def content_length=(len)
- unless len
- @header.delete 'content-length'
- return nil
- end
- @header['content-length'] = [len.to_i.to_s]
- end
-
- # Returns "true" if the "transfer-encoding" header is present and
- # set to "chunked". This is an HTTP/1.1 feature, allowing the
- # the content to be sent in "chunks" without at the outset
- # stating the entire content length.
- def chunked?
- return false unless @header['transfer-encoding']
- field = self['Transfer-Encoding']
- (/(?:\A|[^\-\w])chunked(?![\-\w])/i =~ field) ? true : false
- end
-
- # Returns a Range object which represents the value of the Content-Range:
- # header field.
- # For a partial entity body, this indicates where this fragment
- # fits inside the full entity body, as range of byte offsets.
- def content_range
- return nil unless @header['content-range']
- m = %ri.match(self['Content-Range']) or
- raise Net::HTTPHeaderSyntaxError, 'wrong Content-Range format'
- m[1].to_i .. m[2].to_i
- end
-
- # The length of the range represented in Content-Range: header.
- def range_length
- r = content_range() or return nil
- r.end - r.begin + 1
- end
-
- # Returns a content type string such as "text/html".
- # This method returns nil if Content-Type: header field does not exist.
- def content_type
- return nil unless main_type()
- if sub_type()
- then "#{main_type()}/#{sub_type()}"
- else main_type()
- end
- end
-
- # Returns a content type string such as "text".
- # This method returns nil if Content-Type: header field does not exist.
- def main_type
- return nil unless @header['content-type']
- self['Content-Type'].split(';').first.to_s.split('/')[0].to_s.strip
- end
-
- # Returns a content type string such as "html".
- # This method returns nil if Content-Type: header field does not exist
- # or sub-type is not given (e.g. "Content-Type: text").
- def sub_type
- return nil unless @header['content-type']
- _, sub = *self['Content-Type'].split(';').first.to_s.split('/')
- return nil unless sub
- sub.strip
- end
-
- # Any parameters specified for the content type, returned as a Hash.
- # For example, a header of Content-Type: text/html; charset=EUC-JP
- # would result in type_params returning {'charset' => 'EUC-JP'}
- def type_params
- result = {}
- list = self['Content-Type'].to_s.split(';')
- list.shift
- list.each do |param|
- k, v = *param.split('=', 2)
- result[k.strip] = v.strip
- end
- result
- end
-
- # Sets the content type in an HTTP header.
- # The +type+ should be a full HTTP content type, e.g. "text/html".
- # The +params+ are an optional Hash of parameters to add after the
- # content type, e.g. {'charset' => 'iso-8859-1'}
- def set_content_type(type, params = {})
- @header['content-type'] = [type + params.map{|k,v|"; #{k}=#{v}"}.join('')]
- end
-
- alias content_type= set_content_type
-
- # Set header fields and a body from HTML form data.
- # +params+ should be an Array of Arrays or
- # a Hash containing HTML form data.
- # Optional argument +sep+ means data record separator.
- #
- # Values are URL encoded as necessary and the content-type is set to
- # application/x-www-form-urlencoded
- #
- # Example:
- # http.form_data = {"q" => "ruby", "lang" => "en"}
- # http.form_data = {"q" => ["ruby", "perl"], "lang" => "en"}
- # http.set_form_data({"q" => "ruby", "lang" => "en"}, ';')
- #
- def set_form_data(params, sep = '&')
- query = URI.encode_www_form(params)
- query.gsub!(/&/, sep) if sep != '&'
- self.body = query
- self.content_type = 'application/x-www-form-urlencoded'
- end
-
- alias form_data= set_form_data
-
- # Set a HTML form data set.
- # +params+ is the form data set; it is an Array of Arrays or a Hash
- # +enctype is the type to encode the form data set.
- # It is application/x-www-form-urlencoded or multipart/form-data.
- # +formpot+ is an optional hash to specify the detail.
- #
- # boundary:: the boundary of the multipart message
- # charset:: the charset of the message. All names and the values of
- # non-file fields are encoded as the charset.
- #
- # Each item of params is an array and contains following items:
- # +name+:: the name of the field
- # +value+:: the value of the field, it should be a String or a File
- # +opt+:: an optional hash to specify additional information
- #
- # Each item is a file field or a normal field.
- # If +value+ is a File object or the +opt+ have a filename key,
- # the item is treated as a file field.
- #
- # If Transfer-Encoding is set as chunked, this send the request in
- # chunked encoding. Because chunked encoding is HTTP/1.1 feature,
- # you must confirm the server to support HTTP/1.1 before sending it.
- #
- # Example:
- # http.set_form([["q", "ruby"], ["lang", "en"]])
- #
- # See also RFC 2388, RFC 2616, HTML 4.01, and HTML5
- #
- def set_form(params, enctype='application/x-www-form-urlencoded', formopt={})
- @body_data = params
- @body = nil
- @body_stream = nil
- @form_option = formopt
- case enctype
- when /\Aapplication\/x-www-form-urlencoded\z/i,
- /\Amultipart\/form-data\z/i
- self.content_type = enctype
- else
- raise ArgumentError, "invalid enctype: #{enctype}"
- end
- end
-
- # Set the Authorization: header for "Basic" authorization.
- def basic_auth(account, password)
- @header['authorization'] = [basic_encode(account, password)]
- end
-
- # Set Proxy-Authorization: header for "Basic" authorization.
- def proxy_basic_auth(account, password)
- @header['proxy-authorization'] = [basic_encode(account, password)]
- end
-
- def basic_encode(account, password)
- 'Basic ' + ["#{account}:#{password}"].pack('m').delete("\r\n")
- end
- private :basic_encode
-
- def connection_close?
- tokens(@header['connection']).include?('close') or
- tokens(@header['proxy-connection']).include?('close')
- end
-
- def connection_keep_alive?
- tokens(@header['connection']).include?('keep-alive') or
- tokens(@header['proxy-connection']).include?('keep-alive')
- end
-
- def tokens(vals)
- return [] unless vals
- vals.map {|v| v.split(',') }.flatten\
- .reject {|str| str.strip.empty? }\
- .map {|tok| tok.strip.downcase }
- end
- private :tokens
-
-end
-
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/proxy_delta.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/proxy_delta.rb
deleted file mode 100755
index b16c9f1ed..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/proxy_delta.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-module Net::HTTP::ProxyDelta #:nodoc: internal use only
- private
-
- def conn_address
- proxy_address()
- end
-
- def conn_port
- proxy_port()
- end
-
- def edit_path(path)
- use_ssl? ? path : "http://#{addr_port()}#{path}"
- end
-end
-
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/request.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/request.rb
deleted file mode 100755
index e8b0f48fc..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/request.rb
+++ /dev/null
@@ -1,20 +0,0 @@
-# HTTP request class.
-# This class wraps together the request header and the request path.
-# You cannot use this class directly. Instead, you should use one of its
-# subclasses: Net::HTTP::Get, Net::HTTP::Post, Net::HTTP::Head.
-#
-class Net::HTTPRequest < Net::HTTPGenericRequest
- # Creates an HTTP request object for +path+.
- #
- # +initheader+ are the default headers to use. Net::HTTP adds
- # Accept-Encoding to enable compression of the response body unless
- # Accept-Encoding or Range are supplied in +initheader+.
-
- def initialize(path, initheader = nil)
- super self.class::METHOD,
- self.class::REQUEST_HAS_BODY,
- self.class::RESPONSE_HAS_BODY,
- path, initheader
- end
-end
-
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/requests.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/requests.rb
deleted file mode 100755
index c1f836047..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/requests.rb
+++ /dev/null
@@ -1,122 +0,0 @@
-#
-# HTTP/1.1 methods --- RFC2616
-#
-
-# See Net::HTTPGenericRequest for attributes and methods.
-# See Net::HTTP for usage examples.
-class Net::HTTP::Get < Net::HTTPRequest
- METHOD = 'GET'
- REQUEST_HAS_BODY = false
- RESPONSE_HAS_BODY = true
-end
-
-# See Net::HTTPGenericRequest for attributes and methods.
-# See Net::HTTP for usage examples.
-class Net::HTTP::Head < Net::HTTPRequest
- METHOD = 'HEAD'
- REQUEST_HAS_BODY = false
- RESPONSE_HAS_BODY = false
-end
-
-# See Net::HTTPGenericRequest for attributes and methods.
-# See Net::HTTP for usage examples.
-class Net::HTTP::Post < Net::HTTPRequest
- METHOD = 'POST'
- REQUEST_HAS_BODY = true
- RESPONSE_HAS_BODY = true
-end
-
-# See Net::HTTPGenericRequest for attributes and methods.
-# See Net::HTTP for usage examples.
-class Net::HTTP::Put < Net::HTTPRequest
- METHOD = 'PUT'
- REQUEST_HAS_BODY = true
- RESPONSE_HAS_BODY = true
-end
-
-# See Net::HTTPGenericRequest for attributes and methods.
-# See Net::HTTP for usage examples.
-class Net::HTTP::Delete < Net::HTTPRequest
- METHOD = 'DELETE'
- REQUEST_HAS_BODY = false
- RESPONSE_HAS_BODY = true
-end
-
-# See Net::HTTPGenericRequest for attributes and methods.
-class Net::HTTP::Options < Net::HTTPRequest
- METHOD = 'OPTIONS'
- REQUEST_HAS_BODY = false
- RESPONSE_HAS_BODY = true
-end
-
-# See Net::HTTPGenericRequest for attributes and methods.
-class Net::HTTP::Trace < Net::HTTPRequest
- METHOD = 'TRACE'
- REQUEST_HAS_BODY = false
- RESPONSE_HAS_BODY = true
-end
-
-#
-# PATCH method --- RFC5789
-#
-
-# See Net::HTTPGenericRequest for attributes and methods.
-class Net::HTTP::Patch < Net::HTTPRequest
- METHOD = 'PATCH'
- REQUEST_HAS_BODY = true
- RESPONSE_HAS_BODY = true
-end
-
-#
-# WebDAV methods --- RFC2518
-#
-
-# See Net::HTTPGenericRequest for attributes and methods.
-class Net::HTTP::Propfind < Net::HTTPRequest
- METHOD = 'PROPFIND'
- REQUEST_HAS_BODY = true
- RESPONSE_HAS_BODY = true
-end
-
-# See Net::HTTPGenericRequest for attributes and methods.
-class Net::HTTP::Proppatch < Net::HTTPRequest
- METHOD = 'PROPPATCH'
- REQUEST_HAS_BODY = true
- RESPONSE_HAS_BODY = true
-end
-
-# See Net::HTTPGenericRequest for attributes and methods.
-class Net::HTTP::Mkcol < Net::HTTPRequest
- METHOD = 'MKCOL'
- REQUEST_HAS_BODY = true
- RESPONSE_HAS_BODY = true
-end
-
-# See Net::HTTPGenericRequest for attributes and methods.
-class Net::HTTP::Copy < Net::HTTPRequest
- METHOD = 'COPY'
- REQUEST_HAS_BODY = false
- RESPONSE_HAS_BODY = true
-end
-
-# See Net::HTTPGenericRequest for attributes and methods.
-class Net::HTTP::Move < Net::HTTPRequest
- METHOD = 'MOVE'
- REQUEST_HAS_BODY = false
- RESPONSE_HAS_BODY = true
-end
-
-# See Net::HTTPGenericRequest for attributes and methods.
-class Net::HTTP::Lock < Net::HTTPRequest
- METHOD = 'LOCK'
- REQUEST_HAS_BODY = true
- RESPONSE_HAS_BODY = true
-end
-
-# See Net::HTTPGenericRequest for attributes and methods.
-class Net::HTTP::Unlock < Net::HTTPRequest
- METHOD = 'UNLOCK'
- REQUEST_HAS_BODY = true
- RESPONSE_HAS_BODY = true
-end
-
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/response.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/response.rb
deleted file mode 100755
index 126c22160..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/response.rb
+++ /dev/null
@@ -1,416 +0,0 @@
-# HTTP response class.
-#
-# This class wraps together the response header and the response body (the
-# entity requested).
-#
-# It mixes in the HTTPHeader module, which provides access to response
-# header values both via hash-like methods and via individual readers.
-#
-# Note that each possible HTTP response code defines its own
-# HTTPResponse subclass. These are listed below.
-#
-# All classes are defined under the Net module. Indentation indicates
-# inheritance. For a list of the classes see Net::HTTP.
-#
-#
-class Net::HTTPResponse
- class << self
- # true if the response has a body.
- def body_permitted?
- self::HAS_BODY
- end
-
- def exception_type # :nodoc: internal use only
- self::EXCEPTION_TYPE
- end
-
- def read_new(sock) #:nodoc: internal use only
- httpv, code, msg = read_status_line(sock)
- res = response_class(code).new(httpv, code, msg)
- each_response_header(sock) do |k,v|
- res.add_field k, v
- end
- res
- end
-
- private
-
- def read_status_line(sock)
- str = sock.readline
- m = /\AHTTP(?:\/(\d+\.\d+))?\s+(\d\d\d)(?:\s+(.*))?\z/in.match(str) or
- raise Net::HTTPBadResponse, "wrong status line: #{str.dump}"
- m.captures
- end
-
- def response_class(code)
- CODE_TO_OBJ[code] or
- CODE_CLASS_TO_OBJ[code[0,1]] or
- Net::HTTPUnknownResponse
- end
-
- def each_response_header(sock)
- key = value = nil
- while true
- line = sock.readuntil("\n", true).sub(/\s+\z/, '')
- break if line.empty?
- if line[0] == ?\s or line[0] == ?\t and value
- value << ' ' unless value.empty?
- value << line.strip
- else
- yield key, value if key
- key, value = line.strip.split(/\s*:\s*/, 2)
- raise Net::HTTPBadResponse, 'wrong header line format' if value.nil?
- end
- end
- yield key, value if key
- end
- end
-
- # next is to fix bug in RDoc, where the private inside class << self
- # spills out.
- public
-
- include Net::HTTPHeader
-
- def initialize(httpv, code, msg) #:nodoc: internal use only
- @http_version = httpv
- @code = code
- @message = msg
- initialize_http_header nil
- @body = nil
- @read = false
- @uri = nil
- @decode_content = false
- end
-
- # The HTTP version supported by the server.
- attr_reader :http_version
-
- # The HTTP result code string. For example, '302'. You can also
- # determine the response type by examining which response subclass
- # the response object is an instance of.
- attr_reader :code
-
- # The HTTP result message sent by the server. For example, 'Not Found'.
- attr_reader :message
- alias msg message # :nodoc: obsolete
-
- # The URI used to fetch this response. The response URI is only available
- # if a URI was used to create the request.
- attr_reader :uri
-
- # Set to true automatically when the request did not contain an
- # Accept-Encoding header from the user.
- attr_accessor :decode_content
-
- def inspect
- "#<#{self.class} #{@code} #{@message} readbody=#{@read}>"
- end
-
- #
- # response <-> exception relationship
- #
-
- def code_type #:nodoc:
- self.class
- end
-
- def error! #:nodoc:
- raise error_type().new(@code + ' ' + @message.dump, self)
- end
-
- def error_type #:nodoc:
- self.class::EXCEPTION_TYPE
- end
-
- # Raises an HTTP error if the response is not 2xx (success).
- def value
- error! unless self.kind_of?(Net::HTTPSuccess)
- end
-
- def uri= uri # :nodoc:
- @uri = uri.dup if uri
- end
-
- #
- # header (for backward compatibility only; DO NOT USE)
- #
-
- def response #:nodoc:
- warn "#{caller(1)[0]}: warning: Net::HTTPResponse#response is obsolete" if $VERBOSE
- self
- end
-
- def header #:nodoc:
- warn "#{caller(1)[0]}: warning: Net::HTTPResponse#header is obsolete" if $VERBOSE
- self
- end
-
- def read_header #:nodoc:
- warn "#{caller(1)[0]}: warning: Net::HTTPResponse#read_header is obsolete" if $VERBOSE
- self
- end
-
- #
- # body
- #
-
- def reading_body(sock, reqmethodallowbody) #:nodoc: internal use only
- @socket = sock
- @body_exist = reqmethodallowbody && self.class.body_permitted?
- begin
- yield
- self.body # ensure to read body
- ensure
- @socket = nil
- end
- end
-
- # Gets the entity body returned by the remote HTTP server.
- #
- # If a block is given, the body is passed to the block, and
- # the body is provided in fragments, as it is read in from the socket.
- #
- # Calling this method a second or subsequent time for the same
- # HTTPResponse object will return the value already read.
- #
- # http.request_get('/index.html') {|res|
- # puts res.read_body
- # }
- #
- # http.request_get('/index.html') {|res|
- # p res.read_body.object_id # 538149362
- # p res.read_body.object_id # 538149362
- # }
- #
- # # using iterator
- # http.request_get('/index.html') {|res|
- # res.read_body do |segment|
- # print segment
- # end
- # }
- #
- def read_body(dest = nil, &block)
- if @read
- raise IOError, "#{self.class}\#read_body called twice" if dest or block
- return @body
- end
- to = procdest(dest, block)
- stream_check
- if @body_exist
- read_body_0 to
- @body = to
- else
- @body = nil
- end
- @read = true
-
- @body
- end
-
- # Returns the full entity body.
- #
- # Calling this method a second or subsequent time will return the
- # string already read.
- #
- # http.request_get('/index.html') {|res|
- # puts res.body
- # }
- #
- # http.request_get('/index.html') {|res|
- # p res.body.object_id # 538149362
- # p res.body.object_id # 538149362
- # }
- #
- def body
- read_body()
- end
-
- # Because it may be necessary to modify the body, Eg, decompression
- # this method facilitates that.
- def body=(value)
- @body = value
- end
-
- alias entity body #:nodoc: obsolete
-
- private
-
- ##
- # Checks for a supported Content-Encoding header and yields an Inflate
- # wrapper for this response's socket when zlib is present. If the
- # Content-Encoding is unsupported or zlib is missing the plain socket is
- # yielded.
- #
- # If a Content-Range header is present a plain socket is yielded as the
- # bytes in the range may not be a complete deflate block.
-
- def inflater # :nodoc:
- return yield @socket unless Net::HTTP::HAVE_ZLIB
- return yield @socket unless @decode_content
- return yield @socket if self['content-range']
-
- v = self['content-encoding']
- case v && v.downcase
- when 'deflate', 'gzip', 'x-gzip' then
- self.delete 'content-encoding'
-
- inflate_body_io = Inflater.new(@socket)
-
- begin
- yield inflate_body_io
- ensure
- orig_err = $!
- begin
- inflate_body_io.finish
- rescue => err
- raise orig_err || err
- end
- end
- when 'none', 'identity' then
- self.delete 'content-encoding'
-
- yield @socket
- else
- yield @socket
- end
- end
-
- def read_body_0(dest)
- inflater do |inflate_body_io|
- if chunked?
- read_chunked dest, inflate_body_io
- return
- end
-
- @socket = inflate_body_io
-
- clen = content_length()
- if clen
- @socket.read clen, dest, true # ignore EOF
- return
- end
- clen = range_length()
- if clen
- @socket.read clen, dest
- return
- end
- @socket.read_all dest
- end
- end
-
- ##
- # read_chunked reads from +@socket+ for chunk-size, chunk-extension, CRLF,
- # etc. and +chunk_data_io+ for chunk-data which may be deflate or gzip
- # encoded.
- #
- # See RFC 2616 section 3.6.1 for definitions
-
- def read_chunked(dest, chunk_data_io) # :nodoc:
- total = 0
- while true
- line = @socket.readline
- hexlen = line.slice(/[0-9a-fA-F]+/) or
- raise Net::HTTPBadResponse, "wrong chunk size line: #{line}"
- len = hexlen.hex
- break if len == 0
- begin
- chunk_data_io.read len, dest
- ensure
- total += len
- @socket.read 2 # \r\n
- end
- end
- until @socket.readline.empty?
- # none
- end
- end
-
- def stream_check
- raise IOError, 'attempt to read body out of block' if @socket.closed?
- end
-
- def procdest(dest, block)
- raise ArgumentError, 'both arg and block given for HTTP method' if
- dest and block
- if block
- Net::ReadAdapter.new(block)
- else
- dest || ''
- end
- end
-
- ##
- # Inflater is a wrapper around Net::BufferedIO that transparently inflates
- # zlib and gzip streams.
-
- class Inflater # :nodoc:
-
- ##
- # Creates a new Inflater wrapping +socket+
-
- def initialize socket
- @socket = socket
- # zlib with automatic gzip detection
- @inflate = Zlib::Inflate.new(32 + Zlib::MAX_WBITS)
- end
-
- ##
- # Finishes the inflate stream.
-
- def finish
- return if @inflate.total_in == 0
- @inflate.finish
- end
-
- ##
- # Returns a Net::ReadAdapter that inflates each read chunk into +dest+.
- #
- # This allows a large response body to be inflated without storing the
- # entire body in memory.
-
- def inflate_adapter(dest)
- if dest.respond_to?(:set_encoding)
- dest.set_encoding(Encoding::ASCII_8BIT)
- elsif dest.respond_to?(:force_encoding)
- dest.force_encoding(Encoding::ASCII_8BIT)
- end
- block = proc do |compressed_chunk|
- @inflate.inflate(compressed_chunk) do |chunk|
- dest << chunk
- end
- end
-
- Net::ReadAdapter.new(block)
- end
-
- ##
- # Reads +clen+ bytes from the socket, inflates them, then writes them to
- # +dest+. +ignore_eof+ is passed down to Net::BufferedIO#read
- #
- # Unlike Net::BufferedIO#read, this method returns more than +clen+ bytes.
- # At this time there is no way for a user of Net::HTTPResponse to read a
- # specific number of bytes from the HTTP response body, so this internal
- # API does not return the same number of bytes as were requested.
- #
- # See https://bugs.ruby-lang.org/issues/6492 for further discussion.
-
- def read clen, dest, ignore_eof = false
- temp_dest = inflate_adapter(dest)
-
- @socket.read clen, temp_dest, ignore_eof
- end
-
- ##
- # Reads the rest of the socket, inflates it, then writes it to +dest+.
-
- def read_all dest
- temp_dest = inflate_adapter(dest)
-
- @socket.read_all temp_dest
- end
-
- end
-
-end
-
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/responses.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/responses.rb
deleted file mode 100755
index 1454a27a3..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/http/responses.rb
+++ /dev/null
@@ -1,273 +0,0 @@
-# :stopdoc:
-class Net::HTTPUnknownResponse < Net::HTTPResponse
- HAS_BODY = true
- EXCEPTION_TYPE = Net::HTTPError
-end
-class Net::HTTPInformation < Net::HTTPResponse # 1xx
- HAS_BODY = false
- EXCEPTION_TYPE = Net::HTTPError
-end
-class Net::HTTPSuccess < Net::HTTPResponse # 2xx
- HAS_BODY = true
- EXCEPTION_TYPE = Net::HTTPError
-end
-class Net::HTTPRedirection < Net::HTTPResponse # 3xx
- HAS_BODY = true
- EXCEPTION_TYPE = Net::HTTPRetriableError
-end
-class Net::HTTPClientError < Net::HTTPResponse # 4xx
- HAS_BODY = true
- EXCEPTION_TYPE = Net::HTTPServerException # for backward compatibility
-end
-class Net::HTTPServerError < Net::HTTPResponse # 5xx
- HAS_BODY = true
- EXCEPTION_TYPE = Net::HTTPFatalError # for backward compatibility
-end
-
-class Net::HTTPContinue < Net::HTTPInformation # 100
- HAS_BODY = false
-end
-class Net::HTTPSwitchProtocol < Net::HTTPInformation # 101
- HAS_BODY = false
-end
-# 102 - RFC 2518; removed in RFC 4918
-
-class Net::HTTPOK < Net::HTTPSuccess # 200
- HAS_BODY = true
-end
-class Net::HTTPCreated < Net::HTTPSuccess # 201
- HAS_BODY = true
-end
-class Net::HTTPAccepted < Net::HTTPSuccess # 202
- HAS_BODY = true
-end
-class Net::HTTPNonAuthoritativeInformation < Net::HTTPSuccess # 203
- HAS_BODY = true
-end
-class Net::HTTPNoContent < Net::HTTPSuccess # 204
- HAS_BODY = false
-end
-class Net::HTTPResetContent < Net::HTTPSuccess # 205
- HAS_BODY = false
-end
-class Net::HTTPPartialContent < Net::HTTPSuccess # 206
- HAS_BODY = true
-end
-class Net::HTTPMultiStatus < Net::HTTPSuccess # 207 - RFC 4918
- HAS_BODY = true
-end
-# 208 Already Reported - RFC 5842; experimental
-class Net::HTTPIMUsed < Net::HTTPSuccess # 226 - RFC 3229
- HAS_BODY = true
-end
-
-class Net::HTTPMultipleChoices < Net::HTTPRedirection # 300
- HAS_BODY = true
-end
-Net::HTTPMultipleChoice = Net::HTTPMultipleChoices
-class Net::HTTPMovedPermanently < Net::HTTPRedirection # 301
- HAS_BODY = true
-end
-class Net::HTTPFound < Net::HTTPRedirection # 302
- HAS_BODY = true
-end
-Net::HTTPMovedTemporarily = Net::HTTPFound
-class Net::HTTPSeeOther < Net::HTTPRedirection # 303
- HAS_BODY = true
-end
-class Net::HTTPNotModified < Net::HTTPRedirection # 304
- HAS_BODY = false
-end
-class Net::HTTPUseProxy < Net::HTTPRedirection # 305
- HAS_BODY = false
-end
-# 306 Switch Proxy - no longer unused
-class Net::HTTPTemporaryRedirect < Net::HTTPRedirection # 307
- HAS_BODY = true
-end
-class Net::HTTPPermanentRedirect < Net::HTTPRedirection # 308
- HAS_BODY = true
-end
-
-class Net::HTTPBadRequest < Net::HTTPClientError # 400
- HAS_BODY = true
-end
-class Net::HTTPUnauthorized < Net::HTTPClientError # 401
- HAS_BODY = true
-end
-class Net::HTTPPaymentRequired < Net::HTTPClientError # 402
- HAS_BODY = true
-end
-class Net::HTTPForbidden < Net::HTTPClientError # 403
- HAS_BODY = true
-end
-class Net::HTTPNotFound < Net::HTTPClientError # 404
- HAS_BODY = true
-end
-class Net::HTTPMethodNotAllowed < Net::HTTPClientError # 405
- HAS_BODY = true
-end
-class Net::HTTPNotAcceptable < Net::HTTPClientError # 406
- HAS_BODY = true
-end
-class Net::HTTPProxyAuthenticationRequired < Net::HTTPClientError # 407
- HAS_BODY = true
-end
-class Net::HTTPRequestTimeOut < Net::HTTPClientError # 408
- HAS_BODY = true
-end
-class Net::HTTPConflict < Net::HTTPClientError # 409
- HAS_BODY = true
-end
-class Net::HTTPGone < Net::HTTPClientError # 410
- HAS_BODY = true
-end
-class Net::HTTPLengthRequired < Net::HTTPClientError # 411
- HAS_BODY = true
-end
-class Net::HTTPPreconditionFailed < Net::HTTPClientError # 412
- HAS_BODY = true
-end
-class Net::HTTPRequestEntityTooLarge < Net::HTTPClientError # 413
- HAS_BODY = true
-end
-class Net::HTTPRequestURITooLong < Net::HTTPClientError # 414
- HAS_BODY = true
-end
-Net::HTTPRequestURITooLarge = Net::HTTPRequestURITooLong
-class Net::HTTPUnsupportedMediaType < Net::HTTPClientError # 415
- HAS_BODY = true
-end
-class Net::HTTPRequestedRangeNotSatisfiable < Net::HTTPClientError # 416
- HAS_BODY = true
-end
-class Net::HTTPExpectationFailed < Net::HTTPClientError # 417
- HAS_BODY = true
-end
-# 418 I'm a teapot - RFC 2324; a joke RFC
-# 420 Enhance Your Calm - Twitter
-class Net::HTTPUnprocessableEntity < Net::HTTPClientError # 422 - RFC 4918
- HAS_BODY = true
-end
-class Net::HTTPLocked < Net::HTTPClientError # 423 - RFC 4918
- HAS_BODY = true
-end
-class Net::HTTPFailedDependency < Net::HTTPClientError # 424 - RFC 4918
- HAS_BODY = true
-end
-# 425 Unordered Collection - existed only in draft
-class Net::HTTPUpgradeRequired < Net::HTTPClientError # 426 - RFC 2817
- HAS_BODY = true
-end
-class Net::HTTPPreconditionRequired < Net::HTTPClientError # 428 - RFC 6585
- HAS_BODY = true
-end
-class Net::HTTPTooManyRequests < Net::HTTPClientError # 429 - RFC 6585
- HAS_BODY = true
-end
-class Net::HTTPRequestHeaderFieldsTooLarge < Net::HTTPClientError # 431 - RFC 6585
- HAS_BODY = true
-end
-# 444 No Response - Nginx
-# 449 Retry With - Microsoft
-# 450 Blocked by Windows Parental Controls - Microsoft
-# 499 Client Closed Request - Nginx
-
-class Net::HTTPInternalServerError < Net::HTTPServerError # 500
- HAS_BODY = true
-end
-class Net::HTTPNotImplemented < Net::HTTPServerError # 501
- HAS_BODY = true
-end
-class Net::HTTPBadGateway < Net::HTTPServerError # 502
- HAS_BODY = true
-end
-class Net::HTTPServiceUnavailable < Net::HTTPServerError # 503
- HAS_BODY = true
-end
-class Net::HTTPGatewayTimeOut < Net::HTTPServerError # 504
- HAS_BODY = true
-end
-class Net::HTTPVersionNotSupported < Net::HTTPServerError # 505
- HAS_BODY = true
-end
-# 506 Variant Also Negotiates - RFC 2295; experimental
-class Net::HTTPInsufficientStorage < Net::HTTPServerError # 507 - RFC 4918
- HAS_BODY = true
-end
-# 508 Loop Detected - RFC 5842; experimental
-# 509 Bandwidth Limit Exceeded - Apache bw/limited extension
-# 510 Not Extended - RFC 2774; experimental
-class Net::HTTPNetworkAuthenticationRequired < Net::HTTPServerError # 511 - RFC 6585
- HAS_BODY = true
-end
-
-class Net::HTTPResponse
- CODE_CLASS_TO_OBJ = {
- '1' => Net::HTTPInformation,
- '2' => Net::HTTPSuccess,
- '3' => Net::HTTPRedirection,
- '4' => Net::HTTPClientError,
- '5' => Net::HTTPServerError
- }
- CODE_TO_OBJ = {
- '100' => Net::HTTPContinue,
- '101' => Net::HTTPSwitchProtocol,
-
- '200' => Net::HTTPOK,
- '201' => Net::HTTPCreated,
- '202' => Net::HTTPAccepted,
- '203' => Net::HTTPNonAuthoritativeInformation,
- '204' => Net::HTTPNoContent,
- '205' => Net::HTTPResetContent,
- '206' => Net::HTTPPartialContent,
- '207' => Net::HTTPMultiStatus,
- '226' => Net::HTTPIMUsed,
-
- '300' => Net::HTTPMultipleChoices,
- '301' => Net::HTTPMovedPermanently,
- '302' => Net::HTTPFound,
- '303' => Net::HTTPSeeOther,
- '304' => Net::HTTPNotModified,
- '305' => Net::HTTPUseProxy,
- '307' => Net::HTTPTemporaryRedirect,
-
- '400' => Net::HTTPBadRequest,
- '401' => Net::HTTPUnauthorized,
- '402' => Net::HTTPPaymentRequired,
- '403' => Net::HTTPForbidden,
- '404' => Net::HTTPNotFound,
- '405' => Net::HTTPMethodNotAllowed,
- '406' => Net::HTTPNotAcceptable,
- '407' => Net::HTTPProxyAuthenticationRequired,
- '408' => Net::HTTPRequestTimeOut,
- '409' => Net::HTTPConflict,
- '410' => Net::HTTPGone,
- '411' => Net::HTTPLengthRequired,
- '412' => Net::HTTPPreconditionFailed,
- '413' => Net::HTTPRequestEntityTooLarge,
- '414' => Net::HTTPRequestURITooLong,
- '415' => Net::HTTPUnsupportedMediaType,
- '416' => Net::HTTPRequestedRangeNotSatisfiable,
- '417' => Net::HTTPExpectationFailed,
- '422' => Net::HTTPUnprocessableEntity,
- '423' => Net::HTTPLocked,
- '424' => Net::HTTPFailedDependency,
- '426' => Net::HTTPUpgradeRequired,
- '428' => Net::HTTPPreconditionRequired,
- '429' => Net::HTTPTooManyRequests,
- '431' => Net::HTTPRequestHeaderFieldsTooLarge,
-
- '500' => Net::HTTPInternalServerError,
- '501' => Net::HTTPNotImplemented,
- '502' => Net::HTTPBadGateway,
- '503' => Net::HTTPServiceUnavailable,
- '504' => Net::HTTPGatewayTimeOut,
- '505' => Net::HTTPVersionNotSupported,
- '507' => Net::HTTPInsufficientStorage,
- '511' => Net::HTTPNetworkAuthenticationRequired,
- }
-end
-
-# :startdoc:
-
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/https.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/https.rb
deleted file mode 100755
index d36f82002..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/https.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-=begin
-
-= net/https -- SSL/TLS enhancement for Net::HTTP.
-
- This file has been merged with net/http. There is no longer any need to
- require 'net/https' to use HTTPS.
-
- See Net::HTTP for details on how to make HTTPS connections.
-
-== Info
- 'OpenSSL for Ruby 2' project
- Copyright (C) 2001 GOTOU Yuuzou
- All rights reserved.
-
-== Licence
- This program is licenced under the same licence as Ruby.
- (See the file 'LICENCE'.)
-
-=end
-
-require 'net/http'
-require 'openssl'
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/imap.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/imap.rb
deleted file mode 100755
index 0517ca138..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/imap.rb
+++ /dev/null
@@ -1,3622 +0,0 @@
-#
-# = net/imap.rb
-#
-# Copyright (C) 2000 Shugo Maeda
-#
-# This library is distributed under the terms of the Ruby license.
-# You can freely distribute/modify this library.
-#
-# Documentation: Shugo Maeda, with RDoc conversion and overview by William
-# Webber.
-#
-# See Net::IMAP for documentation.
-#
-
-
-require "socket"
-require "monitor"
-require "digest/md5"
-require "strscan"
-begin
- require "openssl"
-rescue LoadError
-end
-
-module Net
-
- #
- # Net::IMAP implements Internet Message Access Protocol (IMAP) client
- # functionality. The protocol is described in [IMAP].
- #
- # == IMAP Overview
- #
- # An IMAP client connects to a server, and then authenticates
- # itself using either #authenticate() or #login(). Having
- # authenticated itself, there is a range of commands
- # available to it. Most work with mailboxes, which may be
- # arranged in an hierarchical namespace, and each of which
- # contains zero or more messages. How this is implemented on
- # the server is implementation-dependent; on a UNIX server, it
- # will frequently be implemented as files in mailbox format
- # within a hierarchy of directories.
- #
- # To work on the messages within a mailbox, the client must
- # first select that mailbox, using either #select() or (for
- # read-only access) #examine(). Once the client has successfully
- # selected a mailbox, they enter _selected_ state, and that
- # mailbox becomes the _current_ mailbox, on which mail-item
- # related commands implicitly operate.
- #
- # Messages have two sorts of identifiers: message sequence
- # numbers and UIDs.
- #
- # Message sequence numbers number messages within a mailbox
- # from 1 up to the number of items in the mailbox. If a new
- # message arrives during a session, it receives a sequence
- # number equal to the new size of the mailbox. If messages
- # are expunged from the mailbox, remaining messages have their
- # sequence numbers "shuffled down" to fill the gaps.
- #
- # UIDs, on the other hand, are permanently guaranteed not to
- # identify another message within the same mailbox, even if
- # the existing message is deleted. UIDs are required to
- # be assigned in ascending (but not necessarily sequential)
- # order within a mailbox; this means that if a non-IMAP client
- # rearranges the order of mailitems within a mailbox, the
- # UIDs have to be reassigned. An IMAP client thus cannot
- # rearrange message orders.
- #
- # == Examples of Usage
- #
- # === List sender and subject of all recent messages in the default mailbox
- #
- # imap = Net::IMAP.new('mail.example.com')
- # imap.authenticate('LOGIN', 'joe_user', 'joes_password')
- # imap.examine('INBOX')
- # imap.search(["RECENT"]).each do |message_id|
- # envelope = imap.fetch(message_id, "ENVELOPE")[0].attr["ENVELOPE"]
- # puts "#{envelope.from[0].name}: \t#{envelope.subject}"
- # end
- #
- # === Move all messages from April 2003 from "Mail/sent-mail" to "Mail/sent-apr03"
- #
- # imap = Net::IMAP.new('mail.example.com')
- # imap.authenticate('LOGIN', 'joe_user', 'joes_password')
- # imap.select('Mail/sent-mail')
- # if not imap.list('Mail/', 'sent-apr03')
- # imap.create('Mail/sent-apr03')
- # end
- # imap.search(["BEFORE", "30-Apr-2003", "SINCE", "1-Apr-2003"]).each do |message_id|
- # imap.copy(message_id, "Mail/sent-apr03")
- # imap.store(message_id, "+FLAGS", [:Deleted])
- # end
- # imap.expunge
- #
- # == Thread Safety
- #
- # Net::IMAP supports concurrent threads. For example,
- #
- # imap = Net::IMAP.new("imap.foo.net", "imap2")
- # imap.authenticate("cram-md5", "bar", "password")
- # imap.select("inbox")
- # fetch_thread = Thread.start { imap.fetch(1..-1, "UID") }
- # search_result = imap.search(["BODY", "hello"])
- # fetch_result = fetch_thread.value
- # imap.disconnect
- #
- # This script invokes the FETCH command and the SEARCH command concurrently.
- #
- # == Errors
- #
- # An IMAP server can send three different types of responses to indicate
- # failure:
- #
- # NO:: the attempted command could not be successfully completed. For
- # instance, the username/password used for logging in are incorrect;
- # the selected mailbox does not exist; etc.
- #
- # BAD:: the request from the client does not follow the server's
- # understanding of the IMAP protocol. This includes attempting
- # commands from the wrong client state; for instance, attempting
- # to perform a SEARCH command without having SELECTed a current
- # mailbox. It can also signal an internal server
- # failure (such as a disk crash) has occurred.
- #
- # BYE:: the server is saying goodbye. This can be part of a normal
- # logout sequence, and can be used as part of a login sequence
- # to indicate that the server is (for some reason) unwilling
- # to accept your connection. As a response to any other command,
- # it indicates either that the server is shutting down, or that
- # the server is timing out the client connection due to inactivity.
- #
- # These three error response are represented by the errors
- # Net::IMAP::NoResponseError, Net::IMAP::BadResponseError, and
- # Net::IMAP::ByeResponseError, all of which are subclasses of
- # Net::IMAP::ResponseError. Essentially, all methods that involve
- # sending a request to the server can generate one of these errors.
- # Only the most pertinent instances have been documented below.
- #
- # Because the IMAP class uses Sockets for communication, its methods
- # are also susceptible to the various errors that can occur when
- # working with sockets. These are generally represented as
- # Errno errors. For instance, any method that involves sending a
- # request to the server and/or receiving a response from it could
- # raise an Errno::EPIPE error if the network connection unexpectedly
- # goes down. See the socket(7), ip(7), tcp(7), socket(2), connect(2),
- # and associated man pages.
- #
- # Finally, a Net::IMAP::DataFormatError is thrown if low-level data
- # is found to be in an incorrect format (for instance, when converting
- # between UTF-8 and UTF-16), and Net::IMAP::ResponseParseError is
- # thrown if a server response is non-parseable.
- #
- #
- # == References
- #
- # [[IMAP]]
- # M. Crispin, "INTERNET MESSAGE ACCESS PROTOCOL - VERSION 4rev1",
- # RFC 2060, December 1996. (Note: since obsoleted by RFC 3501)
- #
- # [[LANGUAGE-TAGS]]
- # Alvestrand, H., "Tags for the Identification of
- # Languages", RFC 1766, March 1995.
- #
- # [[MD5]]
- # Myers, J., and M. Rose, "The Content-MD5 Header Field", RFC
- # 1864, October 1995.
- #
- # [[MIME-IMB]]
- # Freed, N., and N. Borenstein, "MIME (Multipurpose Internet
- # Mail Extensions) Part One: Format of Internet Message Bodies", RFC
- # 2045, November 1996.
- #
- # [[RFC-822]]
- # Crocker, D., "Standard for the Format of ARPA Internet Text
- # Messages", STD 11, RFC 822, University of Delaware, August 1982.
- #
- # [[RFC-2087]]
- # Myers, J., "IMAP4 QUOTA extension", RFC 2087, January 1997.
- #
- # [[RFC-2086]]
- # Myers, J., "IMAP4 ACL extension", RFC 2086, January 1997.
- #
- # [[RFC-2195]]
- # Klensin, J., Catoe, R., and Krumviede, P., "IMAP/POP AUTHorize Extension
- # for Simple Challenge/Response", RFC 2195, September 1997.
- #
- # [[SORT-THREAD-EXT]]
- # Crispin, M., "INTERNET MESSAGE ACCESS PROTOCOL - SORT and THREAD
- # Extensions", draft-ietf-imapext-sort, May 2003.
- #
- # [[OSSL]]
- # http://www.openssl.org
- #
- # [[RSSL]]
- # http://savannah.gnu.org/projects/rubypki
- #
- # [[UTF7]]
- # Goldsmith, D. and Davis, M., "UTF-7: A Mail-Safe Transformation Format of
- # Unicode", RFC 2152, May 1997.
- #
- class IMAP
- include MonitorMixin
- if defined?(OpenSSL::SSL)
- include OpenSSL
- include SSL
- end
-
- # Returns an initial greeting response from the server.
- attr_reader :greeting
-
- # Returns recorded untagged responses. For example:
- #
- # imap.select("inbox")
- # p imap.responses["EXISTS"][-1]
- # #=> 2
- # p imap.responses["UIDVALIDITY"][-1]
- # #=> 968263756
- attr_reader :responses
-
- # Returns all response handlers.
- attr_reader :response_handlers
-
- # The thread to receive exceptions.
- attr_accessor :client_thread
-
- # Flag indicating a message has been seen.
- SEEN = :Seen
-
- # Flag indicating a message has been answered.
- ANSWERED = :Answered
-
- # Flag indicating a message has been flagged for special or urgent
- # attention.
- FLAGGED = :Flagged
-
- # Flag indicating a message has been marked for deletion. This
- # will occur when the mailbox is closed or expunged.
- DELETED = :Deleted
-
- # Flag indicating a message is only a draft or work-in-progress version.
- DRAFT = :Draft
-
- # Flag indicating that the message is "recent," meaning that this
- # session is the first session in which the client has been notified
- # of this message.
- RECENT = :Recent
-
- # Flag indicating that a mailbox context name cannot contain
- # children.
- NOINFERIORS = :Noinferiors
-
- # Flag indicating that a mailbox is not selected.
- NOSELECT = :Noselect
-
- # Flag indicating that a mailbox has been marked "interesting" by
- # the server; this commonly indicates that the mailbox contains
- # new messages.
- MARKED = :Marked
-
- # Flag indicating that the mailbox does not contains new messages.
- UNMARKED = :Unmarked
-
- # Returns the debug mode.
- def self.debug
- return @@debug
- end
-
- # Sets the debug mode.
- def self.debug=(val)
- return @@debug = val
- end
-
- # Returns the max number of flags interned to symbols.
- def self.max_flag_count
- return @@max_flag_count
- end
-
- # Sets the max number of flags interned to symbols.
- def self.max_flag_count=(count)
- @@max_flag_count = count
- end
-
- # Adds an authenticator for Net::IMAP#authenticate. +auth_type+
- # is the type of authentication this authenticator supports
- # (for instance, "LOGIN"). The +authenticator+ is an object
- # which defines a process() method to handle authentication with
- # the server. See Net::IMAP::LoginAuthenticator,
- # Net::IMAP::CramMD5Authenticator, and Net::IMAP::DigestMD5Authenticator
- # for examples.
- #
- #
- # If +auth_type+ refers to an existing authenticator, it will be
- # replaced by the new one.
- def self.add_authenticator(auth_type, authenticator)
- @@authenticators[auth_type] = authenticator
- end
-
- # The default port for IMAP connections, port 143
- def self.default_port
- return PORT
- end
-
- # The default port for IMAPS connections, port 993
- def self.default_tls_port
- return SSL_PORT
- end
-
- class << self
- alias default_imap_port default_port
- alias default_imaps_port default_tls_port
- alias default_ssl_port default_tls_port
- end
-
- # Disconnects from the server.
- def disconnect
- begin
- begin
- # try to call SSL::SSLSocket#io.
- @sock.io.shutdown
- rescue NoMethodError
- # @sock is not an SSL::SSLSocket.
- @sock.shutdown
- end
- rescue Errno::ENOTCONN
- # ignore `Errno::ENOTCONN: Socket is not connected' on some platforms.
- rescue Exception => e
- @receiver_thread.raise(e)
- end
- @receiver_thread.join
- synchronize do
- unless @sock.closed?
- @sock.close
- end
- end
- raise e if e
- end
-
- # Returns true if disconnected from the server.
- def disconnected?
- return @sock.closed?
- end
-
- # Sends a CAPABILITY command, and returns an array of
- # capabilities that the server supports. Each capability
- # is a string. See [IMAP] for a list of possible
- # capabilities.
- #
- # Note that the Net::IMAP class does not modify its
- # behaviour according to the capabilities of the server;
- # it is up to the user of the class to ensure that
- # a certain capability is supported by a server before
- # using it.
- def capability
- synchronize do
- send_command("CAPABILITY")
- return @responses.delete("CAPABILITY")[-1]
- end
- end
-
- # Sends a NOOP command to the server. It does nothing.
- def noop
- send_command("NOOP")
- end
-
- # Sends a LOGOUT command to inform the server that the client is
- # done with the connection.
- def logout
- send_command("LOGOUT")
- end
-
- # Sends a STARTTLS command to start TLS session.
- def starttls(options = {}, verify = true)
- send_command("STARTTLS") do |resp|
- if resp.kind_of?(TaggedResponse) && resp.name == "OK"
- begin
- # for backward compatibility
- certs = options.to_str
- options = create_ssl_params(certs, verify)
- rescue NoMethodError
- end
- start_tls_session(options)
- end
- end
- end
-
- # Sends an AUTHENTICATE command to authenticate the client.
- # The +auth_type+ parameter is a string that represents
- # the authentication mechanism to be used. Currently Net::IMAP
- # supports the authentication mechanisms:
- #
- # LOGIN:: login using cleartext user and password.
- # CRAM-MD5:: login with cleartext user and encrypted password
- # (see [RFC-2195] for a full description). This
- # mechanism requires that the server have the user's
- # password stored in clear-text password.
- #
- # For both of these mechanisms, there should be two +args+: username
- # and (cleartext) password. A server may not support one or the other
- # of these mechanisms; check #capability() for a capability of
- # the form "AUTH=LOGIN" or "AUTH=CRAM-MD5".
- #
- # Authentication is done using the appropriate authenticator object:
- # see @@authenticators for more information on plugging in your own
- # authenticator.
- #
- # For example:
- #
- # imap.authenticate('LOGIN', user, password)
- #
- # A Net::IMAP::NoResponseError is raised if authentication fails.
- def authenticate(auth_type, *args)
- auth_type = auth_type.upcase
- unless @@authenticators.has_key?(auth_type)
- raise ArgumentError,
- format('unknown auth type - "%s"', auth_type)
- end
- authenticator = @@authenticators[auth_type].new(*args)
- send_command("AUTHENTICATE", auth_type) do |resp|
- if resp.instance_of?(ContinuationRequest)
- data = authenticator.process(resp.data.text.unpack("m")[0])
- s = [data].pack("m").gsub(/\n/, "")
- send_string_data(s)
- put_string(CRLF)
- end
- end
- end
-
- # Sends a LOGIN command to identify the client and carries
- # the plaintext +password+ authenticating this +user+. Note
- # that, unlike calling #authenticate() with an +auth_type+
- # of "LOGIN", #login() does *not* use the login authenticator.
- #
- # A Net::IMAP::NoResponseError is raised if authentication fails.
- def login(user, password)
- send_command("LOGIN", user, password)
- end
-
- # Sends a SELECT command to select a +mailbox+ so that messages
- # in the +mailbox+ can be accessed.
- #
- # After you have selected a mailbox, you may retrieve the
- # number of items in that mailbox from @responses["EXISTS"][-1],
- # and the number of recent messages from @responses["RECENT"][-1].
- # Note that these values can change if new messages arrive
- # during a session; see #add_response_handler() for a way of
- # detecting this event.
- #
- # A Net::IMAP::NoResponseError is raised if the mailbox does not
- # exist or is for some reason non-selectable.
- def select(mailbox)
- synchronize do
- @responses.clear
- send_command("SELECT", mailbox)
- end
- end
-
- # Sends a EXAMINE command to select a +mailbox+ so that messages
- # in the +mailbox+ can be accessed. Behaves the same as #select(),
- # except that the selected +mailbox+ is identified as read-only.
- #
- # A Net::IMAP::NoResponseError is raised if the mailbox does not
- # exist or is for some reason non-examinable.
- def examine(mailbox)
- synchronize do
- @responses.clear
- send_command("EXAMINE", mailbox)
- end
- end
-
- # Sends a CREATE command to create a new +mailbox+.
- #
- # A Net::IMAP::NoResponseError is raised if a mailbox with that name
- # cannot be created.
- def create(mailbox)
- send_command("CREATE", mailbox)
- end
-
- # Sends a DELETE command to remove the +mailbox+.
- #
- # A Net::IMAP::NoResponseError is raised if a mailbox with that name
- # cannot be deleted, either because it does not exist or because the
- # client does not have permission to delete it.
- def delete(mailbox)
- send_command("DELETE", mailbox)
- end
-
- # Sends a RENAME command to change the name of the +mailbox+ to
- # +newname+.
- #
- # A Net::IMAP::NoResponseError is raised if a mailbox with the
- # name +mailbox+ cannot be renamed to +newname+ for whatever
- # reason; for instance, because +mailbox+ does not exist, or
- # because there is already a mailbox with the name +newname+.
- def rename(mailbox, newname)
- send_command("RENAME", mailbox, newname)
- end
-
- # Sends a SUBSCRIBE command to add the specified +mailbox+ name to
- # the server's set of "active" or "subscribed" mailboxes as returned
- # by #lsub().
- #
- # A Net::IMAP::NoResponseError is raised if +mailbox+ cannot be
- # subscribed to; for instance, because it does not exist.
- def subscribe(mailbox)
- send_command("SUBSCRIBE", mailbox)
- end
-
- # Sends a UNSUBSCRIBE command to remove the specified +mailbox+ name
- # from the server's set of "active" or "subscribed" mailboxes.
- #
- # A Net::IMAP::NoResponseError is raised if +mailbox+ cannot be
- # unsubscribed from; for instance, because the client is not currently
- # subscribed to it.
- def unsubscribe(mailbox)
- send_command("UNSUBSCRIBE", mailbox)
- end
-
- # Sends a LIST command, and returns a subset of names from
- # the complete set of all names available to the client.
- # +refname+ provides a context (for instance, a base directory
- # in a directory-based mailbox hierarchy). +mailbox+ specifies
- # a mailbox or (via wildcards) mailboxes under that context.
- # Two wildcards may be used in +mailbox+: '*', which matches
- # all characters *including* the hierarchy delimiter (for instance,
- # '/' on a UNIX-hosted directory-based mailbox hierarchy); and '%',
- # which matches all characters *except* the hierarchy delimiter.
- #
- # If +refname+ is empty, +mailbox+ is used directly to determine
- # which mailboxes to match. If +mailbox+ is empty, the root
- # name of +refname+ and the hierarchy delimiter are returned.
- #
- # The return value is an array of +Net::IMAP::MailboxList+. For example:
- #
- # imap.create("foo/bar")
- # imap.create("foo/baz")
- # p imap.list("", "foo/%")
- # #=> [#, \\
- # #, \\
- # #]
- def list(refname, mailbox)
- synchronize do
- send_command("LIST", refname, mailbox)
- return @responses.delete("LIST")
- end
- end
-
- # Sends a XLIST command, and returns a subset of names from
- # the complete set of all names available to the client.
- # +refname+ provides a context (for instance, a base directory
- # in a directory-based mailbox hierarchy). +mailbox+ specifies
- # a mailbox or (via wildcards) mailboxes under that context.
- # Two wildcards may be used in +mailbox+: '*', which matches
- # all characters *including* the hierarchy delimiter (for instance,
- # '/' on a UNIX-hosted directory-based mailbox hierarchy); and '%',
- # which matches all characters *except* the hierarchy delimiter.
- #
- # If +refname+ is empty, +mailbox+ is used directly to determine
- # which mailboxes to match. If +mailbox+ is empty, the root
- # name of +refname+ and the hierarchy delimiter are returned.
- #
- # The XLIST command is like the LIST command except that the flags
- # returned refer to the function of the folder/mailbox, e.g. :Sent
- #
- # The return value is an array of +Net::IMAP::MailboxList+. For example:
- #
- # imap.create("foo/bar")
- # imap.create("foo/baz")
- # p imap.xlist("", "foo/%")
- # #=> [#, \\
- # #, \\
- # #]
- def xlist(refname, mailbox)
- synchronize do
- send_command("XLIST", refname, mailbox)
- return @responses.delete("XLIST")
- end
- end
-
- # Sends the GETQUOTAROOT command along with the specified +mailbox+.
- # This command is generally available to both admin and user.
- # If this mailbox exists, it returns an array containing objects of type
- # Net::IMAP::MailboxQuotaRoot and Net::IMAP::MailboxQuota.
- def getquotaroot(mailbox)
- synchronize do
- send_command("GETQUOTAROOT", mailbox)
- result = []
- result.concat(@responses.delete("QUOTAROOT"))
- result.concat(@responses.delete("QUOTA"))
- return result
- end
- end
-
- # Sends the GETQUOTA command along with specified +mailbox+.
- # If this mailbox exists, then an array containing a
- # Net::IMAP::MailboxQuota object is returned. This
- # command is generally only available to server admin.
- def getquota(mailbox)
- synchronize do
- send_command("GETQUOTA", mailbox)
- return @responses.delete("QUOTA")
- end
- end
-
- # Sends a SETQUOTA command along with the specified +mailbox+ and
- # +quota+. If +quota+ is nil, then +quota+ will be unset for that
- # mailbox. Typically one needs to be logged in as a server admin
- # for this to work. The IMAP quota commands are described in
- # [RFC-2087].
- def setquota(mailbox, quota)
- if quota.nil?
- data = '()'
- else
- data = '(STORAGE ' + quota.to_s + ')'
- end
- send_command("SETQUOTA", mailbox, RawData.new(data))
- end
-
- # Sends the SETACL command along with +mailbox+, +user+ and the
- # +rights+ that user is to have on that mailbox. If +rights+ is nil,
- # then that user will be stripped of any rights to that mailbox.
- # The IMAP ACL commands are described in [RFC-2086].
- def setacl(mailbox, user, rights)
- if rights.nil?
- send_command("SETACL", mailbox, user, "")
- else
- send_command("SETACL", mailbox, user, rights)
- end
- end
-
- # Send the GETACL command along with a specified +mailbox+.
- # If this mailbox exists, an array containing objects of
- # Net::IMAP::MailboxACLItem will be returned.
- def getacl(mailbox)
- synchronize do
- send_command("GETACL", mailbox)
- return @responses.delete("ACL")[-1]
- end
- end
-
- # Sends a LSUB command, and returns a subset of names from the set
- # of names that the user has declared as being "active" or
- # "subscribed." +refname+ and +mailbox+ are interpreted as
- # for #list().
- # The return value is an array of +Net::IMAP::MailboxList+.
- def lsub(refname, mailbox)
- synchronize do
- send_command("LSUB", refname, mailbox)
- return @responses.delete("LSUB")
- end
- end
-
- # Sends a STATUS command, and returns the status of the indicated
- # +mailbox+. +attr+ is a list of one or more attributes whose
- # statuses are to be requested. Supported attributes include:
- #
- # MESSAGES:: the number of messages in the mailbox.
- # RECENT:: the number of recent messages in the mailbox.
- # UNSEEN:: the number of unseen messages in the mailbox.
- #
- # The return value is a hash of attributes. For example:
- #
- # p imap.status("inbox", ["MESSAGES", "RECENT"])
- # #=> {"RECENT"=>0, "MESSAGES"=>44}
- #
- # A Net::IMAP::NoResponseError is raised if status values
- # for +mailbox+ cannot be returned; for instance, because it
- # does not exist.
- def status(mailbox, attr)
- synchronize do
- send_command("STATUS", mailbox, attr)
- return @responses.delete("STATUS")[-1].attr
- end
- end
-
- # Sends a APPEND command to append the +message+ to the end of
- # the +mailbox+. The optional +flags+ argument is an array of
- # flags initially passed to the new message. The optional
- # +date_time+ argument specifies the creation time to assign to the
- # new message; it defaults to the current time.
- # For example:
- #
- # imap.append("inbox", <:: a set of message sequence numbers. ',' indicates
- # an interval, ':' indicates a range. For instance,
- # '2,10:12,15' means "2,10,11,12,15".
- #
- # BEFORE :: messages with an internal date strictly before
- # . The date argument has a format similar
- # to 8-Aug-2002.
- #
- # BODY :: messages that contain within their body.
- #
- # CC :: messages containing in their CC field.
- #
- # FROM :: messages that contain in their FROM field.
- #
- # NEW:: messages with the \Recent, but not the \Seen, flag set.
- #
- # NOT :: negate the following search key.
- #
- # OR :: "or" two search keys together.
- #
- # ON :: messages with an internal date exactly equal to ,
- # which has a format similar to 8-Aug-2002.
- #
- # SINCE :: messages with an internal date on or after .
- #
- # SUBJECT :: messages with in their subject.
- #
- # TO :: messages with in their TO field.
- #
- # For example:
- #
- # p imap.search(["SUBJECT", "hello", "NOT", "NEW"])
- # #=> [1, 6, 7, 8]
- def search(keys, charset = nil)
- return search_internal("SEARCH", keys, charset)
- end
-
- # Similar to #search(), but returns unique identifiers.
- def uid_search(keys, charset = nil)
- return search_internal("UID SEARCH", keys, charset)
- end
-
- # Sends a FETCH command to retrieve data associated with a message
- # in the mailbox.
- #
- # The +set+ parameter is a number or a range between two numbers,
- # or an array of those. The number is a message sequence number,
- # where -1 repesents a '*' for use in range notation like 100..-1
- # being interpreted as '100:*'. Beware that the +exclude_end?+
- # property of a Range object is ignored, and the contents of a
- # range are independent of the order of the range endpoints as per
- # the protocol specification, so 1...5, 5..1 and 5...1 are all
- # equivalent to 1..5.
- #
- # +attr+ is a list of attributes to fetch; see the documentation
- # for Net::IMAP::FetchData for a list of valid attributes.
- #
- # The return value is an array of Net::IMAP::FetchData or nil
- # (instead of an empty array) if there is no matching message.
- #
- # For example:
- #
- # p imap.fetch(6..8, "UID")
- # #=> [#98}>, \\
- # #99}>, \\
- # #100}>]
- # p imap.fetch(6, "BODY[HEADER.FIELDS (SUBJECT)]")
- # #=> [#"Subject: test\r\n\r\n"}>]
- # data = imap.uid_fetch(98, ["RFC822.SIZE", "INTERNALDATE"])[0]
- # p data.seqno
- # #=> 6
- # p data.attr["RFC822.SIZE"]
- # #=> 611
- # p data.attr["INTERNALDATE"]
- # #=> "12-Oct-2000 22:40:59 +0900"
- # p data.attr["UID"]
- # #=> 98
- def fetch(set, attr)
- return fetch_internal("FETCH", set, attr)
- end
-
- # Similar to #fetch(), but +set+ contains unique identifiers.
- def uid_fetch(set, attr)
- return fetch_internal("UID FETCH", set, attr)
- end
-
- # Sends a STORE command to alter data associated with messages
- # in the mailbox, in particular their flags. The +set+ parameter
- # is a number, an array of numbers, or a Range object. Each number
- # is a message sequence number. +attr+ is the name of a data item
- # to store: 'FLAGS' will replace the message's flag list
- # with the provided one, '+FLAGS' will add the provided flags,
- # and '-FLAGS' will remove them. +flags+ is a list of flags.
- #
- # The return value is an array of Net::IMAP::FetchData. For example:
- #
- # p imap.store(6..8, "+FLAGS", [:Deleted])
- # #=> [#[:Seen, :Deleted]}>, \\
- # #[:Seen, :Deleted]}>, \\
- # #[:Seen, :Deleted]}>]
- def store(set, attr, flags)
- return store_internal("STORE", set, attr, flags)
- end
-
- # Similar to #store(), but +set+ contains unique identifiers.
- def uid_store(set, attr, flags)
- return store_internal("UID STORE", set, attr, flags)
- end
-
- # Sends a COPY command to copy the specified message(s) to the end
- # of the specified destination +mailbox+. The +set+ parameter is
- # a number, an array of numbers, or a Range object. The number is
- # a message sequence number.
- def copy(set, mailbox)
- copy_internal("COPY", set, mailbox)
- end
-
- # Similar to #copy(), but +set+ contains unique identifiers.
- def uid_copy(set, mailbox)
- copy_internal("UID COPY", set, mailbox)
- end
-
- # Sends a SORT command to sort messages in the mailbox.
- # Returns an array of message sequence numbers. For example:
- #
- # p imap.sort(["FROM"], ["ALL"], "US-ASCII")
- # #=> [1, 2, 3, 5, 6, 7, 8, 4, 9]
- # p imap.sort(["DATE"], ["SUBJECT", "hello"], "US-ASCII")
- # #=> [6, 7, 8, 1]
- #
- # See [SORT-THREAD-EXT] for more details.
- def sort(sort_keys, search_keys, charset)
- return sort_internal("SORT", sort_keys, search_keys, charset)
- end
-
- # Similar to #sort(), but returns an array of unique identifiers.
- def uid_sort(sort_keys, search_keys, charset)
- return sort_internal("UID SORT", sort_keys, search_keys, charset)
- end
-
- # Adds a response handler. For example, to detect when
- # the server sends a new EXISTS response (which normally
- # indicates new messages being added to the mailbox),
- # add the following handler after selecting the
- # mailbox:
- #
- # imap.add_response_handler { |resp|
- # if resp.kind_of?(Net::IMAP::UntaggedResponse) and resp.name == "EXISTS"
- # puts "Mailbox now has #{resp.data} messages"
- # end
- # }
- #
- def add_response_handler(handler = Proc.new)
- @response_handlers.push(handler)
- end
-
- # Removes the response handler.
- def remove_response_handler(handler)
- @response_handlers.delete(handler)
- end
-
- # Similar to #search(), but returns message sequence numbers in threaded
- # format, as a Net::IMAP::ThreadMember tree. The supported algorithms
- # are:
- #
- # ORDEREDSUBJECT:: split into single-level threads according to subject,
- # ordered by date.
- # REFERENCES:: split into threads by parent/child relationships determined
- # by which message is a reply to which.
- #
- # Unlike #search(), +charset+ is a required argument. US-ASCII
- # and UTF-8 are sample values.
- #
- # See [SORT-THREAD-EXT] for more details.
- def thread(algorithm, search_keys, charset)
- return thread_internal("THREAD", algorithm, search_keys, charset)
- end
-
- # Similar to #thread(), but returns unique identifiers instead of
- # message sequence numbers.
- def uid_thread(algorithm, search_keys, charset)
- return thread_internal("UID THREAD", algorithm, search_keys, charset)
- end
-
- # Sends an IDLE command that waits for notifications of new or expunged
- # messages. Yields responses from the server during the IDLE.
- #
- # Use #idle_done() to leave IDLE.
- def idle(&response_handler)
- raise LocalJumpError, "no block given" unless response_handler
-
- response = nil
-
- synchronize do
- tag = Thread.current[:net_imap_tag] = generate_tag
- put_string("#{tag} IDLE#{CRLF}")
-
- begin
- add_response_handler(response_handler)
- @idle_done_cond = new_cond
- @idle_done_cond.wait
- @idle_done_cond = nil
- if @receiver_thread_terminating
- raise Net::IMAP::Error, "connection closed"
- end
- ensure
- unless @receiver_thread_terminating
- remove_response_handler(response_handler)
- put_string("DONE#{CRLF}")
- response = get_tagged_response(tag, "IDLE")
- end
- end
- end
-
- return response
- end
-
- # Leaves IDLE.
- def idle_done
- synchronize do
- if @idle_done_cond.nil?
- raise Net::IMAP::Error, "not during IDLE"
- end
- @idle_done_cond.signal
- end
- end
-
- # Decode a string from modified UTF-7 format to UTF-8.
- #
- # UTF-7 is a 7-bit encoding of Unicode [UTF7]. IMAP uses a
- # slightly modified version of this to encode mailbox names
- # containing non-ASCII characters; see [IMAP] section 5.1.3.
- #
- # Net::IMAP does _not_ automatically encode and decode
- # mailbox names to and from UTF-7.
- def self.decode_utf7(s)
- return s.gsub(/&([^-]+)?-/n) {
- if $1
- ($1.tr(",", "/") + "===").unpack("m")[0].encode(Encoding::UTF_8, Encoding::UTF_16BE)
- else
- "&"
- end
- }
- end
-
- # Encode a string from UTF-8 format to modified UTF-7.
- def self.encode_utf7(s)
- return s.gsub(/(&)|[^\x20-\x7e]+/) {
- if $1
- "&-"
- else
- base64 = [$&.encode(Encoding::UTF_16BE)].pack("m")
- "&" + base64.delete("=\n").tr("/", ",") + "-"
- end
- }.force_encoding("ASCII-8BIT")
- end
-
- # Formats +time+ as an IMAP-style date.
- def self.format_date(time)
- return time.strftime('%d-%b-%Y')
- end
-
- # Formats +time+ as an IMAP-style date-time.
- def self.format_datetime(time)
- return time.strftime('%d-%b-%Y %H:%M %z')
- end
-
- private
-
- CRLF = "\r\n" # :nodoc:
- PORT = 143 # :nodoc:
- SSL_PORT = 993 # :nodoc:
-
- @@debug = false
- @@authenticators = {}
- @@max_flag_count = 10000
-
- # :call-seq:
- # Net::IMAP.new(host, options = {})
- #
- # Creates a new Net::IMAP object and connects it to the specified
- # +host+.
- #
- # +options+ is an option hash, each key of which is a symbol.
- #
- # The available options are:
- #
- # port:: Port number (default value is 143 for imap, or 993 for imaps)
- # ssl:: If options[:ssl] is true, then an attempt will be made
- # to use SSL (now TLS) to connect to the server. For this to work
- # OpenSSL [OSSL] and the Ruby OpenSSL [RSSL] extensions need to
- # be installed.
- # If options[:ssl] is a hash, it's passed to
- # OpenSSL::SSL::SSLContext#set_params as parameters.
- #
- # The most common errors are:
- #
- # Errno::ECONNREFUSED:: Connection refused by +host+ or an intervening
- # firewall.
- # Errno::ETIMEDOUT:: Connection timed out (possibly due to packets
- # being dropped by an intervening firewall).
- # Errno::ENETUNREACH:: There is no route to that network.
- # SocketError:: Hostname not known or other socket error.
- # Net::IMAP::ByeResponseError:: The connected to the host was successful, but
- # it immediately said goodbye.
- def initialize(host, port_or_options = {},
- usessl = false, certs = nil, verify = true)
- super()
- @host = host
- begin
- options = port_or_options.to_hash
- rescue NoMethodError
- # for backward compatibility
- options = {}
- options[:port] = port_or_options
- if usessl
- options[:ssl] = create_ssl_params(certs, verify)
- end
- end
- @port = options[:port] || (options[:ssl] ? SSL_PORT : PORT)
- @tag_prefix = "RUBY"
- @tagno = 0
- @parser = ResponseParser.new
- @sock = TCPSocket.open(@host, @port)
- begin
- if options[:ssl]
- start_tls_session(options[:ssl])
- @usessl = true
- else
- @usessl = false
- end
- @responses = Hash.new([].freeze)
- @tagged_responses = {}
- @response_handlers = []
- @tagged_response_arrival = new_cond
- @continuation_request_arrival = new_cond
- @idle_done_cond = nil
- @logout_command_tag = nil
- @debug_output_bol = true
- @exception = nil
-
- @greeting = get_response
- if @greeting.nil?
- raise Error, "connection closed"
- end
- if @greeting.name == "BYE"
- raise ByeResponseError, @greeting
- end
-
- @client_thread = Thread.current
- @receiver_thread = Thread.start {
- begin
- receive_responses
- rescue Exception
- end
- }
- @receiver_thread_terminating = false
- rescue Exception
- @sock.close
- raise
- end
- end
-
- def receive_responses
- connection_closed = false
- until connection_closed
- synchronize do
- @exception = nil
- end
- begin
- resp = get_response
- rescue Exception => e
- synchronize do
- @sock.close
- @exception = e
- end
- break
- end
- unless resp
- synchronize do
- @exception = EOFError.new("end of file reached")
- end
- break
- end
- begin
- synchronize do
- case resp
- when TaggedResponse
- @tagged_responses[resp.tag] = resp
- @tagged_response_arrival.broadcast
- if resp.tag == @logout_command_tag
- return
- end
- when UntaggedResponse
- record_response(resp.name, resp.data)
- if resp.data.instance_of?(ResponseText) &&
- (code = resp.data.code)
- record_response(code.name, code.data)
- end
- if resp.name == "BYE" && @logout_command_tag.nil?
- @sock.close
- @exception = ByeResponseError.new(resp)
- connection_closed = true
- end
- when ContinuationRequest
- @continuation_request_arrival.signal
- end
- @response_handlers.each do |handler|
- handler.call(resp)
- end
- end
- rescue Exception => e
- @exception = e
- synchronize do
- @tagged_response_arrival.broadcast
- @continuation_request_arrival.broadcast
- end
- end
- end
- synchronize do
- @receiver_thread_terminating = true
- @tagged_response_arrival.broadcast
- @continuation_request_arrival.broadcast
- if @idle_done_cond
- @idle_done_cond.signal
- end
- end
- end
-
- def get_tagged_response(tag, cmd)
- until @tagged_responses.key?(tag)
- raise @exception if @exception
- @tagged_response_arrival.wait
- end
- resp = @tagged_responses.delete(tag)
- case resp.name
- when /\A(?:NO)\z/ni
- raise NoResponseError, resp
- when /\A(?:BAD)\z/ni
- raise BadResponseError, resp
- else
- return resp
- end
- end
-
- def get_response
- buff = ""
- while true
- s = @sock.gets(CRLF)
- break unless s
- buff.concat(s)
- if /\{(\d+)\}\r\n/n =~ s
- s = @sock.read($1.to_i)
- buff.concat(s)
- else
- break
- end
- end
- return nil if buff.length == 0
- if @@debug
- $stderr.print(buff.gsub(/^/n, "S: "))
- end
- return @parser.parse(buff)
- end
-
- def record_response(name, data)
- unless @responses.has_key?(name)
- @responses[name] = []
- end
- @responses[name].push(data)
- end
-
- def send_command(cmd, *args, &block)
- synchronize do
- args.each do |i|
- validate_data(i)
- end
- tag = generate_tag
- put_string(tag + " " + cmd)
- args.each do |i|
- put_string(" ")
- send_data(i)
- end
- put_string(CRLF)
- if cmd == "LOGOUT"
- @logout_command_tag = tag
- end
- if block
- add_response_handler(block)
- end
- begin
- return get_tagged_response(tag, cmd)
- ensure
- if block
- remove_response_handler(block)
- end
- end
- end
- end
-
- def generate_tag
- @tagno += 1
- return format("%s%04d", @tag_prefix, @tagno)
- end
-
- def put_string(str)
- @sock.print(str)
- if @@debug
- if @debug_output_bol
- $stderr.print("C: ")
- end
- $stderr.print(str.gsub(/\n(?!\z)/n, "\nC: "))
- if /\r\n\z/n.match(str)
- @debug_output_bol = true
- else
- @debug_output_bol = false
- end
- end
- end
-
- def validate_data(data)
- case data
- when nil
- when String
- when Integer
- NumValidator.ensure_number(data)
- when Array
- data.each do |i|
- validate_data(i)
- end
- when Time
- when Symbol
- else
- data.validate
- end
- end
-
- def send_data(data)
- case data
- when nil
- put_string("NIL")
- when String
- send_string_data(data)
- when Integer
- send_number_data(data)
- when Array
- send_list_data(data)
- when Time
- send_time_data(data)
- when Symbol
- send_symbol_data(data)
- else
- data.send_data(self)
- end
- end
-
- def send_string_data(str)
- case str
- when ""
- put_string('""')
- when /[\x80-\xff\r\n]/n
- # literal
- send_literal(str)
- when /[(){ \x00-\x1f\x7f%*"\\]/n
- # quoted string
- send_quoted_string(str)
- else
- put_string(str)
- end
- end
-
- def send_quoted_string(str)
- put_string('"' + str.gsub(/["\\]/n, "\\\\\\&") + '"')
- end
-
- def send_literal(str)
- put_string("{" + str.bytesize.to_s + "}" + CRLF)
- @continuation_request_arrival.wait
- raise @exception if @exception
- put_string(str)
- end
-
- def send_number_data(num)
- put_string(num.to_s)
- end
-
- def send_list_data(list)
- put_string("(")
- first = true
- list.each do |i|
- if first
- first = false
- else
- put_string(" ")
- end
- send_data(i)
- end
- put_string(")")
- end
-
- DATE_MONTH = %w(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)
-
- def send_time_data(time)
- t = time.dup.gmtime
- s = format('"%2d-%3s-%4d %02d:%02d:%02d +0000"',
- t.day, DATE_MONTH[t.month - 1], t.year,
- t.hour, t.min, t.sec)
- put_string(s)
- end
-
- def send_symbol_data(symbol)
- put_string("\\" + symbol.to_s)
- end
-
- def search_internal(cmd, keys, charset)
- if keys.instance_of?(String)
- keys = [RawData.new(keys)]
- else
- normalize_searching_criteria(keys)
- end
- synchronize do
- if charset
- send_command(cmd, "CHARSET", charset, *keys)
- else
- send_command(cmd, *keys)
- end
- return @responses.delete("SEARCH")[-1]
- end
- end
-
- def fetch_internal(cmd, set, attr)
- case attr
- when String then
- attr = RawData.new(attr)
- when Array then
- attr = attr.map { |arg|
- arg.is_a?(String) ? RawData.new(arg) : arg
- }
- end
-
- synchronize do
- @responses.delete("FETCH")
- send_command(cmd, MessageSet.new(set), attr)
- return @responses.delete("FETCH")
- end
- end
-
- def store_internal(cmd, set, attr, flags)
- if attr.instance_of?(String)
- attr = RawData.new(attr)
- end
- synchronize do
- @responses.delete("FETCH")
- send_command(cmd, MessageSet.new(set), attr, flags)
- return @responses.delete("FETCH")
- end
- end
-
- def copy_internal(cmd, set, mailbox)
- send_command(cmd, MessageSet.new(set), mailbox)
- end
-
- def sort_internal(cmd, sort_keys, search_keys, charset)
- if search_keys.instance_of?(String)
- search_keys = [RawData.new(search_keys)]
- else
- normalize_searching_criteria(search_keys)
- end
- normalize_searching_criteria(search_keys)
- synchronize do
- send_command(cmd, sort_keys, charset, *search_keys)
- return @responses.delete("SORT")[-1]
- end
- end
-
- def thread_internal(cmd, algorithm, search_keys, charset)
- if search_keys.instance_of?(String)
- search_keys = [RawData.new(search_keys)]
- else
- normalize_searching_criteria(search_keys)
- end
- normalize_searching_criteria(search_keys)
- send_command(cmd, algorithm, charset, *search_keys)
- return @responses.delete("THREAD")[-1]
- end
-
- def normalize_searching_criteria(keys)
- keys.collect! do |i|
- case i
- when -1, Range, Array
- MessageSet.new(i)
- else
- i
- end
- end
- end
-
- def create_ssl_params(certs = nil, verify = true)
- params = {}
- if certs
- if File.file?(certs)
- params[:ca_file] = certs
- elsif File.directory?(certs)
- params[:ca_path] = certs
- end
- end
- if verify
- params[:verify_mode] = VERIFY_PEER
- else
- params[:verify_mode] = VERIFY_NONE
- end
- return params
- end
-
- def start_tls_session(params = {})
- unless defined?(OpenSSL::SSL)
- raise "SSL extension not installed"
- end
- if @sock.kind_of?(OpenSSL::SSL::SSLSocket)
- raise RuntimeError, "already using SSL"
- end
- begin
- params = params.to_hash
- rescue NoMethodError
- params = {}
- end
- context = SSLContext.new
- context.set_params(params)
- if defined?(VerifyCallbackProc)
- context.verify_callback = VerifyCallbackProc
- end
- @sock = SSLSocket.new(@sock, context)
- @sock.sync_close = true
- @sock.connect
- if context.verify_mode != VERIFY_NONE
- @sock.post_connection_check(@host)
- end
- end
-
- class RawData # :nodoc:
- def send_data(imap)
- imap.send(:put_string, @data)
- end
-
- def validate
- end
-
- private
-
- def initialize(data)
- @data = data
- end
- end
-
- class Atom # :nodoc:
- def send_data(imap)
- imap.send(:put_string, @data)
- end
-
- def validate
- end
-
- private
-
- def initialize(data)
- @data = data
- end
- end
-
- class QuotedString # :nodoc:
- def send_data(imap)
- imap.send(:send_quoted_string, @data)
- end
-
- def validate
- end
-
- private
-
- def initialize(data)
- @data = data
- end
- end
-
- class Literal # :nodoc:
- def send_data(imap)
- imap.send(:send_literal, @data)
- end
-
- def validate
- end
-
- private
-
- def initialize(data)
- @data = data
- end
- end
-
- class MessageSet # :nodoc:
- def send_data(imap)
- imap.send(:put_string, format_internal(@data))
- end
-
- def validate
- validate_internal(@data)
- end
-
- private
-
- def initialize(data)
- @data = data
- end
-
- def format_internal(data)
- case data
- when "*"
- return data
- when Integer
- if data == -1
- return "*"
- else
- return data.to_s
- end
- when Range
- return format_internal(data.first) +
- ":" + format_internal(data.last)
- when Array
- return data.collect {|i| format_internal(i)}.join(",")
- when ThreadMember
- return data.seqno.to_s +
- ":" + data.children.collect {|i| format_internal(i).join(",")}
- end
- end
-
- def validate_internal(data)
- case data
- when "*"
- when Integer
- NumValidator.ensure_nz_number(data)
- when Range
- when Array
- data.each do |i|
- validate_internal(i)
- end
- when ThreadMember
- data.children.each do |i|
- validate_internal(i)
- end
- else
- raise DataFormatError, data.inspect
- end
- end
- end
-
- # Common validators of number and nz_number types
- module NumValidator # :nodoc
- class << self
- # Check is passed argument valid 'number' in RFC 3501 terminology
- def valid_number?(num)
- # [RFC 3501]
- # number = 1*DIGIT
- # ; Unsigned 32-bit integer
- # ; (0 <= n < 4,294,967,296)
- num >= 0 && num < 4294967296
- end
-
- # Check is passed argument valid 'nz_number' in RFC 3501 terminology
- def valid_nz_number?(num)
- # [RFC 3501]
- # nz-number = digit-nz *DIGIT
- # ; Non-zero unsigned 32-bit integer
- # ; (0 < n < 4,294,967,296)
- num != 0 && valid_number?(num)
- end
-
- # Ensure argument is 'number' or raise DataFormatError
- def ensure_number(num)
- return if valid_number?(num)
-
- msg = "number must be unsigned 32-bit integer: #{num}"
- raise DataFormatError, msg
- end
-
- # Ensure argument is 'nz_number' or raise DataFormatError
- def ensure_nz_number(num)
- return if valid_nz_number?(num)
-
- msg = "nz_number must be non-zero unsigned 32-bit integer: #{num}"
- raise DataFormatError, msg
- end
- end
- end
-
- # Net::IMAP::ContinuationRequest represents command continuation requests.
- #
- # The command continuation request response is indicated by a "+" token
- # instead of a tag. This form of response indicates that the server is
- # ready to accept the continuation of a command from the client. The
- # remainder of this response is a line of text.
- #
- # continue_req ::= "+" SPACE (resp_text / base64)
- #
- # ==== Fields:
- #
- # data:: Returns the data (Net::IMAP::ResponseText).
- #
- # raw_data:: Returns the raw data string.
- ContinuationRequest = Struct.new(:data, :raw_data)
-
- # Net::IMAP::UntaggedResponse represents untagged responses.
- #
- # Data transmitted by the server to the client and status responses
- # that do not indicate command completion are prefixed with the token
- # "*", and are called untagged responses.
- #
- # response_data ::= "*" SPACE (resp_cond_state / resp_cond_bye /
- # mailbox_data / message_data / capability_data)
- #
- # ==== Fields:
- #
- # name:: Returns the name, such as "FLAGS", "LIST", or "FETCH".
- #
- # data:: Returns the data such as an array of flag symbols,
- # a (()) object.
- #
- # raw_data:: Returns the raw data string.
- UntaggedResponse = Struct.new(:name, :data, :raw_data)
-
- # Net::IMAP::TaggedResponse represents tagged responses.
- #
- # The server completion result response indicates the success or
- # failure of the operation. It is tagged with the same tag as the
- # client command which began the operation.
- #
- # response_tagged ::= tag SPACE resp_cond_state CRLF
- #
- # tag ::= 1*
- #
- # resp_cond_state ::= ("OK" / "NO" / "BAD") SPACE resp_text
- #
- # ==== Fields:
- #
- # tag:: Returns the tag.
- #
- # name:: Returns the name, one of "OK", "NO", or "BAD".
- #
- # data:: Returns the data. See (()).
- #
- # raw_data:: Returns the raw data string.
- #
- TaggedResponse = Struct.new(:tag, :name, :data, :raw_data)
-
- # Net::IMAP::ResponseText represents texts of responses.
- # The text may be prefixed by the response code.
- #
- # resp_text ::= ["[" resp_text_code "]" SPACE] (text_mime2 / text)
- # ;; text SHOULD NOT begin with "[" or "="
- #
- # ==== Fields:
- #
- # code:: Returns the response code. See (()).
- #
- # text:: Returns the text.
- #
- ResponseText = Struct.new(:code, :text)
-
- # Net::IMAP::ResponseCode represents response codes.
- #
- # resp_text_code ::= "ALERT" / "PARSE" /
- # "PERMANENTFLAGS" SPACE "(" #(flag / "\*") ")" /
- # "READ-ONLY" / "READ-WRITE" / "TRYCREATE" /
- # "UIDVALIDITY" SPACE nz_number /
- # "UNSEEN" SPACE nz_number /
- # atom [SPACE 1*]
- #
- # ==== Fields:
- #
- # name:: Returns the name, such as "ALERT", "PERMANENTFLAGS", or "UIDVALIDITY".
- #
- # data:: Returns the data, if it exists.
- #
- ResponseCode = Struct.new(:name, :data)
-
- # Net::IMAP::MailboxList represents contents of the LIST response.
- #
- # mailbox_list ::= "(" #("\Marked" / "\Noinferiors" /
- # "\Noselect" / "\Unmarked" / flag_extension) ")"
- # SPACE (<"> QUOTED_CHAR <"> / nil) SPACE mailbox
- #
- # ==== Fields:
- #
- # attr:: Returns the name attributes. Each name attribute is a symbol
- # capitalized by String#capitalize, such as :Noselect (not :NoSelect).
- #
- # delim:: Returns the hierarchy delimiter.
- #
- # name:: Returns the mailbox name.
- #
- MailboxList = Struct.new(:attr, :delim, :name)
-
- # Net::IMAP::MailboxQuota represents contents of GETQUOTA response.
- # This object can also be a response to GETQUOTAROOT. In the syntax
- # specification below, the delimiter used with the "#" construct is a
- # single space (SPACE).
- #
- # quota_list ::= "(" #quota_resource ")"
- #
- # quota_resource ::= atom SPACE number SPACE number
- #
- # quota_response ::= "QUOTA" SPACE astring SPACE quota_list
- #
- # ==== Fields:
- #
- # mailbox:: The mailbox with the associated quota.
- #
- # usage:: Current storage usage of the mailbox.
- #
- # quota:: Quota limit imposed on the mailbox.
- #
- MailboxQuota = Struct.new(:mailbox, :usage, :quota)
-
- # Net::IMAP::MailboxQuotaRoot represents part of the GETQUOTAROOT
- # response. (GETQUOTAROOT can also return Net::IMAP::MailboxQuota.)
- #
- # quotaroot_response ::= "QUOTAROOT" SPACE astring *(SPACE astring)
- #
- # ==== Fields:
- #
- # mailbox:: The mailbox with the associated quota.
- #
- # quotaroots:: Zero or more quotaroots that affect the quota on the
- # specified mailbox.
- #
- MailboxQuotaRoot = Struct.new(:mailbox, :quotaroots)
-
- # Net::IMAP::MailboxACLItem represents the response from GETACL.
- #
- # acl_data ::= "ACL" SPACE mailbox *(SPACE identifier SPACE rights)
- #
- # identifier ::= astring
- #
- # rights ::= astring
- #
- # ==== Fields:
- #
- # user:: Login name that has certain rights to the mailbox
- # that was specified with the getacl command.
- #
- # rights:: The access rights the indicated user has to the
- # mailbox.
- #
- MailboxACLItem = Struct.new(:user, :rights, :mailbox)
-
- # Net::IMAP::StatusData represents the contents of the STATUS response.
- #
- # ==== Fields:
- #
- # mailbox:: Returns the mailbox name.
- #
- # attr:: Returns a hash. Each key is one of "MESSAGES", "RECENT", "UIDNEXT",
- # "UIDVALIDITY", "UNSEEN". Each value is a number.
- #
- StatusData = Struct.new(:mailbox, :attr)
-
- # Net::IMAP::FetchData represents the contents of the FETCH response.
- #
- # ==== Fields:
- #
- # seqno:: Returns the message sequence number.
- # (Note: not the unique identifier, even for the UID command response.)
- #
- # attr:: Returns a hash. Each key is a data item name, and each value is
- # its value.
- #
- # The current data items are:
- #
- # [BODY]
- # A form of BODYSTRUCTURE without extension data.
- # [BODY[]<>]
- # A string expressing the body contents of the specified section.
- # [BODYSTRUCTURE]
- # An object that describes the [MIME-IMB] body structure of a message.
- # See Net::IMAP::BodyTypeBasic, Net::IMAP::BodyTypeText,
- # Net::IMAP::BodyTypeMessage, Net::IMAP::BodyTypeMultipart.
- # [ENVELOPE]
- # A Net::IMAP::Envelope object that describes the envelope
- # structure of a message.
- # [FLAGS]
- # A array of flag symbols that are set for this message. Flag symbols
- # are capitalized by String#capitalize.
- # [INTERNALDATE]
- # A string representing the internal date of the message.
- # [RFC822]
- # Equivalent to BODY[].
- # [RFC822.HEADER]
- # Equivalent to BODY.PEEK[HEADER].
- # [RFC822.SIZE]
- # A number expressing the [RFC-822] size of the message.
- # [RFC822.TEXT]
- # Equivalent to BODY[TEXT].
- # [UID]
- # A number expressing the unique identifier of the message.
- #
- FetchData = Struct.new(:seqno, :attr)
-
- # Net::IMAP::Envelope represents envelope structures of messages.
- #
- # ==== Fields:
- #
- # date:: Returns a string that represents the date.
- #
- # subject:: Returns a string that represents the subject.
- #
- # from:: Returns an array of Net::IMAP::Address that represents the from.
- #
- # sender:: Returns an array of Net::IMAP::Address that represents the sender.
- #
- # reply_to:: Returns an array of Net::IMAP::Address that represents the reply-to.
- #
- # to:: Returns an array of Net::IMAP::Address that represents the to.
- #
- # cc:: Returns an array of Net::IMAP::Address that represents the cc.
- #
- # bcc:: Returns an array of Net::IMAP::Address that represents the bcc.
- #
- # in_reply_to:: Returns a string that represents the in-reply-to.
- #
- # message_id:: Returns a string that represents the message-id.
- #
- Envelope = Struct.new(:date, :subject, :from, :sender, :reply_to,
- :to, :cc, :bcc, :in_reply_to, :message_id)
-
- #
- # Net::IMAP::Address represents electronic mail addresses.
- #
- # ==== Fields:
- #
- # name:: Returns the phrase from [RFC-822] mailbox.
- #
- # route:: Returns the route from [RFC-822] route-addr.
- #
- # mailbox:: nil indicates end of [RFC-822] group.
- # If non-nil and host is nil, returns [RFC-822] group name.
- # Otherwise, returns [RFC-822] local-part.
- #
- # host:: nil indicates [RFC-822] group syntax.
- # Otherwise, returns [RFC-822] domain name.
- #
- Address = Struct.new(:name, :route, :mailbox, :host)
-
- #
- # Net::IMAP::ContentDisposition represents Content-Disposition fields.
- #
- # ==== Fields:
- #
- # dsp_type:: Returns the disposition type.
- #
- # param:: Returns a hash that represents parameters of the Content-Disposition
- # field.
- #
- ContentDisposition = Struct.new(:dsp_type, :param)
-
- # Net::IMAP::ThreadMember represents a thread-node returned
- # by Net::IMAP#thread.
- #
- # ==== Fields:
- #
- # seqno:: The sequence number of this message.
- #
- # children:: An array of Net::IMAP::ThreadMember objects for mail
- # items that are children of this in the thread.
- #
- ThreadMember = Struct.new(:seqno, :children)
-
- # Net::IMAP::BodyTypeBasic represents basic body structures of messages.
- #
- # ==== Fields:
- #
- # media_type:: Returns the content media type name as defined in [MIME-IMB].
- #
- # subtype:: Returns the content subtype name as defined in [MIME-IMB].
- #
- # param:: Returns a hash that represents parameters as defined in [MIME-IMB].
- #
- # content_id:: Returns a string giving the content id as defined in [MIME-IMB].
- #
- # description:: Returns a string giving the content description as defined in
- # [MIME-IMB].
- #
- # encoding:: Returns a string giving the content transfer encoding as defined in
- # [MIME-IMB].
- #
- # size:: Returns a number giving the size of the body in octets.
- #
- # md5:: Returns a string giving the body MD5 value as defined in [MD5].
- #
- # disposition:: Returns a Net::IMAP::ContentDisposition object giving
- # the content disposition.
- #
- # language:: Returns a string or an array of strings giving the body
- # language value as defined in [LANGUAGE-TAGS].
- #
- # extension:: Returns extension data.
- #
- # multipart?:: Returns false.
- #
- class BodyTypeBasic < Struct.new(:media_type, :subtype,
- :param, :content_id,
- :description, :encoding, :size,
- :md5, :disposition, :language,
- :extension)
- def multipart?
- return false
- end
-
- # Obsolete: use +subtype+ instead. Calling this will
- # generate a warning message to +stderr+, then return
- # the value of +subtype+.
- def media_subtype
- $stderr.printf("warning: media_subtype is obsolete.\n")
- $stderr.printf(" use subtype instead.\n")
- return subtype
- end
- end
-
- # Net::IMAP::BodyTypeText represents TEXT body structures of messages.
- #
- # ==== Fields:
- #
- # lines:: Returns the size of the body in text lines.
- #
- # And Net::IMAP::BodyTypeText has all fields of Net::IMAP::BodyTypeBasic.
- #
- class BodyTypeText < Struct.new(:media_type, :subtype,
- :param, :content_id,
- :description, :encoding, :size,
- :lines,
- :md5, :disposition, :language,
- :extension)
- def multipart?
- return false
- end
-
- # Obsolete: use +subtype+ instead. Calling this will
- # generate a warning message to +stderr+, then return
- # the value of +subtype+.
- def media_subtype
- $stderr.printf("warning: media_subtype is obsolete.\n")
- $stderr.printf(" use subtype instead.\n")
- return subtype
- end
- end
-
- # Net::IMAP::BodyTypeMessage represents MESSAGE/RFC822 body structures of messages.
- #
- # ==== Fields:
- #
- # envelope:: Returns a Net::IMAP::Envelope giving the envelope structure.
- #
- # body:: Returns an object giving the body structure.
- #
- # And Net::IMAP::BodyTypeMessage has all methods of Net::IMAP::BodyTypeText.
- #
- class BodyTypeMessage < Struct.new(:media_type, :subtype,
- :param, :content_id,
- :description, :encoding, :size,
- :envelope, :body, :lines,
- :md5, :disposition, :language,
- :extension)
- def multipart?
- return false
- end
-
- # Obsolete: use +subtype+ instead. Calling this will
- # generate a warning message to +stderr+, then return
- # the value of +subtype+.
- def media_subtype
- $stderr.printf("warning: media_subtype is obsolete.\n")
- $stderr.printf(" use subtype instead.\n")
- return subtype
- end
- end
-
- # Net::IMAP::BodyTypeAttachment represents attachment body structures
- # of messages.
- #
- # ==== Fields:
- #
- # media_type:: Returns the content media type name.
- #
- # subtype:: Returns +nil+.
- #
- # param:: Returns a hash that represents parameters.
- #
- # multipart?:: Returns false.
- #
- class BodyTypeAttachment < Struct.new(:media_type, :subtype,
- :param)
- def multipart?
- return false
- end
- end
-
- # Net::IMAP::BodyTypeMultipart represents multipart body structures
- # of messages.
- #
- # ==== Fields:
- #
- # media_type:: Returns the content media type name as defined in [MIME-IMB].
- #
- # subtype:: Returns the content subtype name as defined in [MIME-IMB].
- #
- # parts:: Returns multiple parts.
- #
- # param:: Returns a hash that represents parameters as defined in [MIME-IMB].
- #
- # disposition:: Returns a Net::IMAP::ContentDisposition object giving
- # the content disposition.
- #
- # language:: Returns a string or an array of strings giving the body
- # language value as defined in [LANGUAGE-TAGS].
- #
- # extension:: Returns extension data.
- #
- # multipart?:: Returns true.
- #
- class BodyTypeMultipart < Struct.new(:media_type, :subtype,
- :parts,
- :param, :disposition, :language,
- :extension)
- def multipart?
- return true
- end
-
- # Obsolete: use +subtype+ instead. Calling this will
- # generate a warning message to +stderr+, then return
- # the value of +subtype+.
- def media_subtype
- $stderr.printf("warning: media_subtype is obsolete.\n")
- $stderr.printf(" use subtype instead.\n")
- return subtype
- end
- end
-
- class BodyTypeExtension < Struct.new(:media_type, :subtype,
- :params, :content_id,
- :description, :encoding, :size)
- def multipart?
- return false
- end
- end
-
- class ResponseParser # :nodoc:
- def initialize
- @str = nil
- @pos = nil
- @lex_state = nil
- @token = nil
- @flag_symbols = {}
- end
-
- def parse(str)
- @str = str
- @pos = 0
- @lex_state = EXPR_BEG
- @token = nil
- return response
- end
-
- private
-
- EXPR_BEG = :EXPR_BEG
- EXPR_DATA = :EXPR_DATA
- EXPR_TEXT = :EXPR_TEXT
- EXPR_RTEXT = :EXPR_RTEXT
- EXPR_CTEXT = :EXPR_CTEXT
-
- T_SPACE = :SPACE
- T_NIL = :NIL
- T_NUMBER = :NUMBER
- T_ATOM = :ATOM
- T_QUOTED = :QUOTED
- T_LPAR = :LPAR
- T_RPAR = :RPAR
- T_BSLASH = :BSLASH
- T_STAR = :STAR
- T_LBRA = :LBRA
- T_RBRA = :RBRA
- T_LITERAL = :LITERAL
- T_PLUS = :PLUS
- T_PERCENT = :PERCENT
- T_CRLF = :CRLF
- T_EOF = :EOF
- T_TEXT = :TEXT
-
- BEG_REGEXP = /\G(?:\
-(?# 1: SPACE )( +)|\
-(?# 2: NIL )(NIL)(?=[\x80-\xff(){ \x00-\x1f\x7f%*"\\\[\]+])|\
-(?# 3: NUMBER )(\d+)(?=[\x80-\xff(){ \x00-\x1f\x7f%*"\\\[\]+])|\
-(?# 4: ATOM )([^\x80-\xff(){ \x00-\x1f\x7f%*"\\\[\]+]+)|\
-(?# 5: QUOTED )"((?:[^\x00\r\n"\\]|\\["\\])*)"|\
-(?# 6: LPAR )(\()|\
-(?# 7: RPAR )(\))|\
-(?# 8: BSLASH )(\\)|\
-(?# 9: STAR )(\*)|\
-(?# 10: LBRA )(\[)|\
-(?# 11: RBRA )(\])|\
-(?# 12: LITERAL )\{(\d+)\}\r\n|\
-(?# 13: PLUS )(\+)|\
-(?# 14: PERCENT )(%)|\
-(?# 15: CRLF )(\r\n)|\
-(?# 16: EOF )(\z))/ni
-
- DATA_REGEXP = /\G(?:\
-(?# 1: SPACE )( )|\
-(?# 2: NIL )(NIL)|\
-(?# 3: NUMBER )(\d+)|\
-(?# 4: QUOTED )"((?:[^\x00\r\n"\\]|\\["\\])*)"|\
-(?# 5: LITERAL )\{(\d+)\}\r\n|\
-(?# 6: LPAR )(\()|\
-(?# 7: RPAR )(\)))/ni
-
- TEXT_REGEXP = /\G(?:\
-(?# 1: TEXT )([^\x00\r\n]*))/ni
-
- RTEXT_REGEXP = /\G(?:\
-(?# 1: LBRA )(\[)|\
-(?# 2: TEXT )([^\x00\r\n]*))/ni
-
- CTEXT_REGEXP = /\G(?:\
-(?# 1: TEXT )([^\x00\r\n\]]*))/ni
-
- Token = Struct.new(:symbol, :value)
-
- def response
- token = lookahead
- case token.symbol
- when T_PLUS
- result = continue_req
- when T_STAR
- result = response_untagged
- else
- result = response_tagged
- end
- match(T_CRLF)
- match(T_EOF)
- return result
- end
-
- def continue_req
- match(T_PLUS)
- match(T_SPACE)
- return ContinuationRequest.new(resp_text, @str)
- end
-
- def response_untagged
- match(T_STAR)
- match(T_SPACE)
- token = lookahead
- if token.symbol == T_NUMBER
- return numeric_response
- elsif token.symbol == T_ATOM
- case token.value
- when /\A(?:OK|NO|BAD|BYE|PREAUTH)\z/ni
- return response_cond
- when /\A(?:FLAGS)\z/ni
- return flags_response
- when /\A(?:LIST|LSUB|XLIST)\z/ni
- return list_response
- when /\A(?:QUOTA)\z/ni
- return getquota_response
- when /\A(?:QUOTAROOT)\z/ni
- return getquotaroot_response
- when /\A(?:ACL)\z/ni
- return getacl_response
- when /\A(?:SEARCH|SORT)\z/ni
- return search_response
- when /\A(?:THREAD)\z/ni
- return thread_response
- when /\A(?:STATUS)\z/ni
- return status_response
- when /\A(?:CAPABILITY)\z/ni
- return capability_response
- else
- return text_response
- end
- else
- parse_error("unexpected token %s", token.symbol)
- end
- end
-
- def response_tagged
- tag = atom
- match(T_SPACE)
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return TaggedResponse.new(tag, name, resp_text, @str)
- end
-
- def response_cond
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return UntaggedResponse.new(name, resp_text, @str)
- end
-
- def numeric_response
- n = number
- match(T_SPACE)
- token = match(T_ATOM)
- name = token.value.upcase
- case name
- when "EXISTS", "RECENT", "EXPUNGE"
- return UntaggedResponse.new(name, n, @str)
- when "FETCH"
- shift_token
- match(T_SPACE)
- data = FetchData.new(n, msg_att(n))
- return UntaggedResponse.new(name, data, @str)
- end
- end
-
- def msg_att(n)
- match(T_LPAR)
- attr = {}
- while true
- token = lookahead
- case token.symbol
- when T_RPAR
- shift_token
- break
- when T_SPACE
- shift_token
- next
- end
- case token.value
- when /\A(?:ENVELOPE)\z/ni
- name, val = envelope_data
- when /\A(?:FLAGS)\z/ni
- name, val = flags_data
- when /\A(?:INTERNALDATE)\z/ni
- name, val = internaldate_data
- when /\A(?:RFC822(?:\.HEADER|\.TEXT)?)\z/ni
- name, val = rfc822_text
- when /\A(?:RFC822\.SIZE)\z/ni
- name, val = rfc822_size
- when /\A(?:BODY(?:STRUCTURE)?)\z/ni
- name, val = body_data
- when /\A(?:UID)\z/ni
- name, val = uid_data
- else
- parse_error("unknown attribute `%s' for {%d}", token.value, n)
- end
- attr[name] = val
- end
- return attr
- end
-
- def envelope_data
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return name, envelope
- end
-
- def envelope
- @lex_state = EXPR_DATA
- token = lookahead
- if token.symbol == T_NIL
- shift_token
- result = nil
- else
- match(T_LPAR)
- date = nstring
- match(T_SPACE)
- subject = nstring
- match(T_SPACE)
- from = address_list
- match(T_SPACE)
- sender = address_list
- match(T_SPACE)
- reply_to = address_list
- match(T_SPACE)
- to = address_list
- match(T_SPACE)
- cc = address_list
- match(T_SPACE)
- bcc = address_list
- match(T_SPACE)
- in_reply_to = nstring
- match(T_SPACE)
- message_id = nstring
- match(T_RPAR)
- result = Envelope.new(date, subject, from, sender, reply_to,
- to, cc, bcc, in_reply_to, message_id)
- end
- @lex_state = EXPR_BEG
- return result
- end
-
- def flags_data
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return name, flag_list
- end
-
- def internaldate_data
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- token = match(T_QUOTED)
- return name, token.value
- end
-
- def rfc822_text
- token = match(T_ATOM)
- name = token.value.upcase
- token = lookahead
- if token.symbol == T_LBRA
- shift_token
- match(T_RBRA)
- end
- match(T_SPACE)
- return name, nstring
- end
-
- def rfc822_size
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return name, number
- end
-
- def body_data
- token = match(T_ATOM)
- name = token.value.upcase
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- return name, body
- end
- name.concat(section)
- token = lookahead
- if token.symbol == T_ATOM
- name.concat(token.value)
- shift_token
- end
- match(T_SPACE)
- data = nstring
- return name, data
- end
-
- def body
- @lex_state = EXPR_DATA
- token = lookahead
- if token.symbol == T_NIL
- shift_token
- result = nil
- else
- match(T_LPAR)
- token = lookahead
- if token.symbol == T_LPAR
- result = body_type_mpart
- else
- result = body_type_1part
- end
- match(T_RPAR)
- end
- @lex_state = EXPR_BEG
- return result
- end
-
- def body_type_1part
- token = lookahead
- case token.value
- when /\A(?:TEXT)\z/ni
- return body_type_text
- when /\A(?:MESSAGE)\z/ni
- return body_type_msg
- when /\A(?:ATTACHMENT)\z/ni
- return body_type_attachment
- when /\A(?:MIXED)\z/ni
- return body_type_mixed
- else
- return body_type_basic
- end
- end
-
- def body_type_basic
- mtype, msubtype = media_type
- token = lookahead
- if token.symbol == T_RPAR
- return BodyTypeBasic.new(mtype, msubtype)
- end
- match(T_SPACE)
- param, content_id, desc, enc, size = body_fields
- md5, disposition, language, extension = body_ext_1part
- return BodyTypeBasic.new(mtype, msubtype,
- param, content_id,
- desc, enc, size,
- md5, disposition, language, extension)
- end
-
- def body_type_text
- mtype, msubtype = media_type
- match(T_SPACE)
- param, content_id, desc, enc, size = body_fields
- match(T_SPACE)
- lines = number
- md5, disposition, language, extension = body_ext_1part
- return BodyTypeText.new(mtype, msubtype,
- param, content_id,
- desc, enc, size,
- lines,
- md5, disposition, language, extension)
- end
-
- def body_type_msg
- mtype, msubtype = media_type
- match(T_SPACE)
- param, content_id, desc, enc, size = body_fields
-
- token = lookahead
- if token.symbol == T_RPAR
- # If this is not message/rfc822, we shouldn't apply the RFC822
- # spec to it. We should handle anything other than
- # message/rfc822 using multipart extension data [rfc3501] (i.e.
- # the data itself won't be returned, we would have to retrieve it
- # with BODYSTRUCTURE instead of with BODY
-
- # Also, sometimes a message/rfc822 is included as a large
- # attachment instead of having all of the other details
- # (e.g. attaching a .eml file to an email)
- if msubtype == "RFC822"
- return BodyTypeMessage.new(mtype, msubtype, param, content_id,
- desc, enc, size, nil, nil, nil, nil,
- nil, nil, nil)
- else
- return BodyTypeExtension.new(mtype, msubtype,
- param, content_id,
- desc, enc, size)
- end
- end
-
- match(T_SPACE)
- env = envelope
- match(T_SPACE)
- b = body
- match(T_SPACE)
- lines = number
- md5, disposition, language, extension = body_ext_1part
- return BodyTypeMessage.new(mtype, msubtype,
- param, content_id,
- desc, enc, size,
- env, b, lines,
- md5, disposition, language, extension)
- end
-
- def body_type_attachment
- mtype = case_insensitive_string
- match(T_SPACE)
- param = body_fld_param
- return BodyTypeAttachment.new(mtype, nil, param)
- end
-
- def body_type_mixed
- mtype = "MULTIPART"
- msubtype = case_insensitive_string
- param, disposition, language, extension = body_ext_mpart
- return BodyTypeBasic.new(mtype, msubtype, param, nil, nil, nil, nil, nil, disposition, language, extension)
- end
-
- def body_type_mpart
- parts = []
- while true
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- break
- end
- parts.push(body)
- end
- mtype = "MULTIPART"
- msubtype = case_insensitive_string
- param, disposition, language, extension = body_ext_mpart
- return BodyTypeMultipart.new(mtype, msubtype, parts,
- param, disposition, language,
- extension)
- end
-
- def media_type
- mtype = case_insensitive_string
- token = lookahead
- if token.symbol != T_SPACE
- return mtype, nil
- end
- match(T_SPACE)
- msubtype = case_insensitive_string
- return mtype, msubtype
- end
-
- def body_fields
- param = body_fld_param
- match(T_SPACE)
- content_id = nstring
- match(T_SPACE)
- desc = nstring
- match(T_SPACE)
- enc = case_insensitive_string
- match(T_SPACE)
- size = number
- return param, content_id, desc, enc, size
- end
-
- def body_fld_param
- token = lookahead
- if token.symbol == T_NIL
- shift_token
- return nil
- end
- match(T_LPAR)
- param = {}
- while true
- token = lookahead
- case token.symbol
- when T_RPAR
- shift_token
- break
- when T_SPACE
- shift_token
- end
- name = case_insensitive_string
- match(T_SPACE)
- val = string
- param[name] = val
- end
- return param
- end
-
- def body_ext_1part
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- else
- return nil
- end
- md5 = nstring
-
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- else
- return md5
- end
- disposition = body_fld_dsp
-
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- else
- return md5, disposition
- end
- language = body_fld_lang
-
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- else
- return md5, disposition, language
- end
-
- extension = body_extensions
- return md5, disposition, language, extension
- end
-
- def body_ext_mpart
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- else
- return nil
- end
- param = body_fld_param
-
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- else
- return param
- end
- disposition = body_fld_dsp
-
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- else
- return param, disposition
- end
- language = body_fld_lang
-
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- else
- return param, disposition, language
- end
-
- extension = body_extensions
- return param, disposition, language, extension
- end
-
- def body_fld_dsp
- token = lookahead
- if token.symbol == T_NIL
- shift_token
- return nil
- end
- match(T_LPAR)
- dsp_type = case_insensitive_string
- match(T_SPACE)
- param = body_fld_param
- match(T_RPAR)
- return ContentDisposition.new(dsp_type, param)
- end
-
- def body_fld_lang
- token = lookahead
- if token.symbol == T_LPAR
- shift_token
- result = []
- while true
- token = lookahead
- case token.symbol
- when T_RPAR
- shift_token
- return result
- when T_SPACE
- shift_token
- end
- result.push(case_insensitive_string)
- end
- else
- lang = nstring
- if lang
- return lang.upcase
- else
- return lang
- end
- end
- end
-
- def body_extensions
- result = []
- while true
- token = lookahead
- case token.symbol
- when T_RPAR
- return result
- when T_SPACE
- shift_token
- end
- result.push(body_extension)
- end
- end
-
- def body_extension
- token = lookahead
- case token.symbol
- when T_LPAR
- shift_token
- result = body_extensions
- match(T_RPAR)
- return result
- when T_NUMBER
- return number
- else
- return nstring
- end
- end
-
- def section
- str = ""
- token = match(T_LBRA)
- str.concat(token.value)
- token = match(T_ATOM, T_NUMBER, T_RBRA)
- if token.symbol == T_RBRA
- str.concat(token.value)
- return str
- end
- str.concat(token.value)
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- str.concat(token.value)
- token = match(T_LPAR)
- str.concat(token.value)
- while true
- token = lookahead
- case token.symbol
- when T_RPAR
- str.concat(token.value)
- shift_token
- break
- when T_SPACE
- shift_token
- str.concat(token.value)
- end
- str.concat(format_string(astring))
- end
- end
- token = match(T_RBRA)
- str.concat(token.value)
- return str
- end
-
- def format_string(str)
- case str
- when ""
- return '""'
- when /[\x80-\xff\r\n]/n
- # literal
- return "{" + str.bytesize.to_s + "}" + CRLF + str
- when /[(){ \x00-\x1f\x7f%*"\\]/n
- # quoted string
- return '"' + str.gsub(/["\\]/n, "\\\\\\&") + '"'
- else
- # atom
- return str
- end
- end
-
- def uid_data
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return name, number
- end
-
- def text_response
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- @lex_state = EXPR_TEXT
- token = match(T_TEXT)
- @lex_state = EXPR_BEG
- return UntaggedResponse.new(name, token.value)
- end
-
- def flags_response
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return UntaggedResponse.new(name, flag_list, @str)
- end
-
- def list_response
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return UntaggedResponse.new(name, mailbox_list, @str)
- end
-
- def mailbox_list
- attr = flag_list
- match(T_SPACE)
- token = match(T_QUOTED, T_NIL)
- if token.symbol == T_NIL
- delim = nil
- else
- delim = token.value
- end
- match(T_SPACE)
- name = astring
- return MailboxList.new(attr, delim, name)
- end
-
- def getquota_response
- # If quota never established, get back
- # `NO Quota root does not exist'.
- # If quota removed, get `()' after the
- # folder spec with no mention of `STORAGE'.
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- mailbox = astring
- match(T_SPACE)
- match(T_LPAR)
- token = lookahead
- case token.symbol
- when T_RPAR
- shift_token
- data = MailboxQuota.new(mailbox, nil, nil)
- return UntaggedResponse.new(name, data, @str)
- when T_ATOM
- shift_token
- match(T_SPACE)
- token = match(T_NUMBER)
- usage = token.value
- match(T_SPACE)
- token = match(T_NUMBER)
- quota = token.value
- match(T_RPAR)
- data = MailboxQuota.new(mailbox, usage, quota)
- return UntaggedResponse.new(name, data, @str)
- else
- parse_error("unexpected token %s", token.symbol)
- end
- end
-
- def getquotaroot_response
- # Similar to getquota, but only admin can use getquota.
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- mailbox = astring
- quotaroots = []
- while true
- token = lookahead
- break unless token.symbol == T_SPACE
- shift_token
- quotaroots.push(astring)
- end
- data = MailboxQuotaRoot.new(mailbox, quotaroots)
- return UntaggedResponse.new(name, data, @str)
- end
-
- def getacl_response
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- mailbox = astring
- data = []
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- while true
- token = lookahead
- case token.symbol
- when T_CRLF
- break
- when T_SPACE
- shift_token
- end
- user = astring
- match(T_SPACE)
- rights = astring
- data.push(MailboxACLItem.new(user, rights, mailbox))
- end
- end
- return UntaggedResponse.new(name, data, @str)
- end
-
- def search_response
- token = match(T_ATOM)
- name = token.value.upcase
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- data = []
- while true
- token = lookahead
- case token.symbol
- when T_CRLF
- break
- when T_SPACE
- shift_token
- when T_NUMBER
- data.push(number)
- when T_LPAR
- # TODO: include the MODSEQ value in a response
- shift_token
- match(T_ATOM)
- match(T_SPACE)
- match(T_NUMBER)
- match(T_RPAR)
- end
- end
- else
- data = []
- end
- return UntaggedResponse.new(name, data, @str)
- end
-
- def thread_response
- token = match(T_ATOM)
- name = token.value.upcase
- token = lookahead
-
- if token.symbol == T_SPACE
- threads = []
-
- while true
- shift_token
- token = lookahead
-
- case token.symbol
- when T_LPAR
- threads << thread_branch(token)
- when T_CRLF
- break
- end
- end
- else
- # no member
- threads = []
- end
-
- return UntaggedResponse.new(name, threads, @str)
- end
-
- def thread_branch(token)
- rootmember = nil
- lastmember = nil
-
- while true
- shift_token # ignore first T_LPAR
- token = lookahead
-
- case token.symbol
- when T_NUMBER
- # new member
- newmember = ThreadMember.new(number, [])
- if rootmember.nil?
- rootmember = newmember
- else
- lastmember.children << newmember
- end
- lastmember = newmember
- when T_SPACE
- # do nothing
- when T_LPAR
- if rootmember.nil?
- # dummy member
- lastmember = rootmember = ThreadMember.new(nil, [])
- end
-
- lastmember.children << thread_branch(token)
- when T_RPAR
- break
- end
- end
-
- return rootmember
- end
-
- def status_response
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- mailbox = astring
- match(T_SPACE)
- match(T_LPAR)
- attr = {}
- while true
- token = lookahead
- case token.symbol
- when T_RPAR
- shift_token
- break
- when T_SPACE
- shift_token
- end
- token = match(T_ATOM)
- key = token.value.upcase
- match(T_SPACE)
- val = number
- attr[key] = val
- end
- data = StatusData.new(mailbox, attr)
- return UntaggedResponse.new(name, data, @str)
- end
-
- def capability_response
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- data = []
- while true
- token = lookahead
- case token.symbol
- when T_CRLF
- break
- when T_SPACE
- shift_token
- next
- end
- data.push(atom.upcase)
- end
- return UntaggedResponse.new(name, data, @str)
- end
-
- def resp_text
- @lex_state = EXPR_RTEXT
- token = lookahead
- if token.symbol == T_LBRA
- code = resp_text_code
- else
- code = nil
- end
- token = match(T_TEXT)
- @lex_state = EXPR_BEG
- return ResponseText.new(code, token.value)
- end
-
- def resp_text_code
- @lex_state = EXPR_BEG
- match(T_LBRA)
- token = match(T_ATOM)
- name = token.value.upcase
- case name
- when /\A(?:ALERT|PARSE|READ-ONLY|READ-WRITE|TRYCREATE|NOMODSEQ)\z/n
- result = ResponseCode.new(name, nil)
- when /\A(?:PERMANENTFLAGS)\z/n
- match(T_SPACE)
- result = ResponseCode.new(name, flag_list)
- when /\A(?:UIDVALIDITY|UIDNEXT|UNSEEN)\z/n
- match(T_SPACE)
- result = ResponseCode.new(name, number)
- else
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- @lex_state = EXPR_CTEXT
- token = match(T_TEXT)
- @lex_state = EXPR_BEG
- result = ResponseCode.new(name, token.value)
- else
- result = ResponseCode.new(name, nil)
- end
- end
- match(T_RBRA)
- @lex_state = EXPR_RTEXT
- return result
- end
-
- def address_list
- token = lookahead
- if token.symbol == T_NIL
- shift_token
- return nil
- else
- result = []
- match(T_LPAR)
- while true
- token = lookahead
- case token.symbol
- when T_RPAR
- shift_token
- break
- when T_SPACE
- shift_token
- end
- result.push(address)
- end
- return result
- end
- end
-
- ADDRESS_REGEXP = /\G\
-(?# 1: NAME )(?:NIL|"((?:[^\x80-\xff\x00\r\n"\\]|\\["\\])*)") \
-(?# 2: ROUTE )(?:NIL|"((?:[^\x80-\xff\x00\r\n"\\]|\\["\\])*)") \
-(?# 3: MAILBOX )(?:NIL|"((?:[^\x80-\xff\x00\r\n"\\]|\\["\\])*)") \
-(?# 4: HOST )(?:NIL|"((?:[^\x80-\xff\x00\r\n"\\]|\\["\\])*)")\
-\)/ni
-
- def address
- match(T_LPAR)
- if @str.index(ADDRESS_REGEXP, @pos)
- # address does not include literal.
- @pos = $~.end(0)
- name = $1
- route = $2
- mailbox = $3
- host = $4
- for s in [name, route, mailbox, host]
- if s
- s.gsub!(/\\(["\\])/n, "\\1")
- end
- end
- else
- name = nstring
- match(T_SPACE)
- route = nstring
- match(T_SPACE)
- mailbox = nstring
- match(T_SPACE)
- host = nstring
- match(T_RPAR)
- end
- return Address.new(name, route, mailbox, host)
- end
-
- FLAG_REGEXP = /\
-(?# FLAG )\\([^\x80-\xff(){ \x00-\x1f\x7f%"\\]+)|\
-(?# ATOM )([^\x80-\xff(){ \x00-\x1f\x7f%*"\\]+)/n
-
- def flag_list
- if @str.index(/\(([^)]*)\)/ni, @pos)
- @pos = $~.end(0)
- return $1.scan(FLAG_REGEXP).collect { |flag, atom|
- if atom
- atom
- else
- symbol = flag.capitalize.untaint.intern
- @flag_symbols[symbol] = true
- if @flag_symbols.length > IMAP.max_flag_count
- raise FlagCountError, "number of flag symbols exceeded"
- end
- symbol
- end
- }
- else
- parse_error("invalid flag list")
- end
- end
-
- def nstring
- token = lookahead
- if token.symbol == T_NIL
- shift_token
- return nil
- else
- return string
- end
- end
-
- def astring
- token = lookahead
- if string_token?(token)
- return string
- else
- return atom
- end
- end
-
- def string
- token = lookahead
- if token.symbol == T_NIL
- shift_token
- return nil
- end
- token = match(T_QUOTED, T_LITERAL)
- return token.value
- end
-
- STRING_TOKENS = [T_QUOTED, T_LITERAL, T_NIL]
-
- def string_token?(token)
- return STRING_TOKENS.include?(token.symbol)
- end
-
- def case_insensitive_string
- token = lookahead
- if token.symbol == T_NIL
- shift_token
- return nil
- end
- token = match(T_QUOTED, T_LITERAL)
- return token.value.upcase
- end
-
- def atom
- result = ""
- while true
- token = lookahead
- if atom_token?(token)
- result.concat(token.value)
- shift_token
- else
- if result.empty?
- parse_error("unexpected token %s", token.symbol)
- else
- return result
- end
- end
- end
- end
-
- ATOM_TOKENS = [
- T_ATOM,
- T_NUMBER,
- T_NIL,
- T_LBRA,
- T_RBRA,
- T_PLUS
- ]
-
- def atom_token?(token)
- return ATOM_TOKENS.include?(token.symbol)
- end
-
- def number
- token = lookahead
- if token.symbol == T_NIL
- shift_token
- return nil
- end
- token = match(T_NUMBER)
- return token.value.to_i
- end
-
- def nil_atom
- match(T_NIL)
- return nil
- end
-
- def match(*args)
- token = lookahead
- unless args.include?(token.symbol)
- parse_error('unexpected token %s (expected %s)',
- token.symbol.id2name,
- args.collect {|i| i.id2name}.join(" or "))
- end
- shift_token
- return token
- end
-
- def lookahead
- unless @token
- @token = next_token
- end
- return @token
- end
-
- def shift_token
- @token = nil
- end
-
- def next_token
- case @lex_state
- when EXPR_BEG
- if @str.index(BEG_REGEXP, @pos)
- @pos = $~.end(0)
- if $1
- return Token.new(T_SPACE, $+)
- elsif $2
- return Token.new(T_NIL, $+)
- elsif $3
- return Token.new(T_NUMBER, $+)
- elsif $4
- return Token.new(T_ATOM, $+)
- elsif $5
- return Token.new(T_QUOTED,
- $+.gsub(/\\(["\\])/n, "\\1"))
- elsif $6
- return Token.new(T_LPAR, $+)
- elsif $7
- return Token.new(T_RPAR, $+)
- elsif $8
- return Token.new(T_BSLASH, $+)
- elsif $9
- return Token.new(T_STAR, $+)
- elsif $10
- return Token.new(T_LBRA, $+)
- elsif $11
- return Token.new(T_RBRA, $+)
- elsif $12
- len = $+.to_i
- val = @str[@pos, len]
- @pos += len
- return Token.new(T_LITERAL, val)
- elsif $13
- return Token.new(T_PLUS, $+)
- elsif $14
- return Token.new(T_PERCENT, $+)
- elsif $15
- return Token.new(T_CRLF, $+)
- elsif $16
- return Token.new(T_EOF, $+)
- else
- parse_error("[Net::IMAP BUG] BEG_REGEXP is invalid")
- end
- else
- @str.index(/\S*/n, @pos)
- parse_error("unknown token - %s", $&.dump)
- end
- when EXPR_DATA
- if @str.index(DATA_REGEXP, @pos)
- @pos = $~.end(0)
- if $1
- return Token.new(T_SPACE, $+)
- elsif $2
- return Token.new(T_NIL, $+)
- elsif $3
- return Token.new(T_NUMBER, $+)
- elsif $4
- return Token.new(T_QUOTED,
- $+.gsub(/\\(["\\])/n, "\\1"))
- elsif $5
- len = $+.to_i
- val = @str[@pos, len]
- @pos += len
- return Token.new(T_LITERAL, val)
- elsif $6
- return Token.new(T_LPAR, $+)
- elsif $7
- return Token.new(T_RPAR, $+)
- else
- parse_error("[Net::IMAP BUG] DATA_REGEXP is invalid")
- end
- else
- @str.index(/\S*/n, @pos)
- parse_error("unknown token - %s", $&.dump)
- end
- when EXPR_TEXT
- if @str.index(TEXT_REGEXP, @pos)
- @pos = $~.end(0)
- if $1
- return Token.new(T_TEXT, $+)
- else
- parse_error("[Net::IMAP BUG] TEXT_REGEXP is invalid")
- end
- else
- @str.index(/\S*/n, @pos)
- parse_error("unknown token - %s", $&.dump)
- end
- when EXPR_RTEXT
- if @str.index(RTEXT_REGEXP, @pos)
- @pos = $~.end(0)
- if $1
- return Token.new(T_LBRA, $+)
- elsif $2
- return Token.new(T_TEXT, $+)
- else
- parse_error("[Net::IMAP BUG] RTEXT_REGEXP is invalid")
- end
- else
- @str.index(/\S*/n, @pos)
- parse_error("unknown token - %s", $&.dump)
- end
- when EXPR_CTEXT
- if @str.index(CTEXT_REGEXP, @pos)
- @pos = $~.end(0)
- if $1
- return Token.new(T_TEXT, $+)
- else
- parse_error("[Net::IMAP BUG] CTEXT_REGEXP is invalid")
- end
- else
- @str.index(/\S*/n, @pos) #/
- parse_error("unknown token - %s", $&.dump)
- end
- else
- parse_error("invalid @lex_state - %s", @lex_state.inspect)
- end
- end
-
- def parse_error(fmt, *args)
- if IMAP.debug
- $stderr.printf("@str: %s\n", @str.dump)
- $stderr.printf("@pos: %d\n", @pos)
- $stderr.printf("@lex_state: %s\n", @lex_state)
- if @token
- $stderr.printf("@token.symbol: %s\n", @token.symbol)
- $stderr.printf("@token.value: %s\n", @token.value.inspect)
- end
- end
- raise ResponseParseError, format(fmt, *args)
- end
- end
-
- # Authenticator for the "LOGIN" authentication type. See
- # #authenticate().
- class LoginAuthenticator
- def process(data)
- case @state
- when STATE_USER
- @state = STATE_PASSWORD
- return @user
- when STATE_PASSWORD
- return @password
- end
- end
-
- private
-
- STATE_USER = :USER
- STATE_PASSWORD = :PASSWORD
-
- def initialize(user, password)
- @user = user
- @password = password
- @state = STATE_USER
- end
- end
- add_authenticator "LOGIN", LoginAuthenticator
-
- # Authenticator for the "PLAIN" authentication type. See
- # #authenticate().
- class PlainAuthenticator
- def process(data)
- return "\0#{@user}\0#{@password}"
- end
-
- private
-
- def initialize(user, password)
- @user = user
- @password = password
- end
- end
- add_authenticator "PLAIN", PlainAuthenticator
-
- # Authenticator for the "CRAM-MD5" authentication type. See
- # #authenticate().
- class CramMD5Authenticator
- def process(challenge)
- digest = hmac_md5(challenge, @password)
- return @user + " " + digest
- end
-
- private
-
- def initialize(user, password)
- @user = user
- @password = password
- end
-
- def hmac_md5(text, key)
- if key.length > 64
- key = Digest::MD5.digest(key)
- end
-
- k_ipad = key + "\0" * (64 - key.length)
- k_opad = key + "\0" * (64 - key.length)
- for i in 0..63
- k_ipad[i] = (k_ipad[i].ord ^ 0x36).chr
- k_opad[i] = (k_opad[i].ord ^ 0x5c).chr
- end
-
- digest = Digest::MD5.digest(k_ipad + text)
-
- return Digest::MD5.hexdigest(k_opad + digest)
- end
- end
- add_authenticator "CRAM-MD5", CramMD5Authenticator
-
- # Authenticator for the "DIGEST-MD5" authentication type. See
- # #authenticate().
- class DigestMD5Authenticator
- def process(challenge)
- case @stage
- when STAGE_ONE
- @stage = STAGE_TWO
- sparams = {}
- c = StringScanner.new(challenge)
- while c.scan(/(?:\s*,)?\s*(\w+)=("(?:[^\\"]+|\\.)*"|[^,]+)\s*/)
- k, v = c[1], c[2]
- if v =~ /^"(.*)"$/
- v = $1
- if v =~ /,/
- v = v.split(',')
- end
- end
- sparams[k] = v
- end
-
- raise DataFormatError, "Bad Challenge: '#{challenge}'" unless c.rest.size == 0
- raise Error, "Server does not support auth (qop = #{sparams['qop'].join(',')})" unless sparams['qop'].include?("auth")
-
- response = {
- :nonce => sparams['nonce'],
- :username => @user,
- :realm => sparams['realm'],
- :cnonce => Digest::MD5.hexdigest("%.15f:%.15f:%d" % [Time.now.to_f, rand, Process.pid.to_s]),
- :'digest-uri' => 'imap/' + sparams['realm'],
- :qop => 'auth',
- :maxbuf => 65535,
- :nc => "%08d" % nc(sparams['nonce']),
- :charset => sparams['charset'],
- }
-
- response[:authzid] = @authname unless @authname.nil?
-
- # now, the real thing
- a0 = Digest::MD5.digest( [ response.values_at(:username, :realm), @password ].join(':') )
-
- a1 = [ a0, response.values_at(:nonce,:cnonce) ].join(':')
- a1 << ':' + response[:authzid] unless response[:authzid].nil?
-
- a2 = "AUTHENTICATE:" + response[:'digest-uri']
- a2 << ":00000000000000000000000000000000" if response[:qop] and response[:qop] =~ /^auth-(?:conf|int)$/
-
- response[:response] = Digest::MD5.hexdigest(
- [
- Digest::MD5.hexdigest(a1),
- response.values_at(:nonce, :nc, :cnonce, :qop),
- Digest::MD5.hexdigest(a2)
- ].join(':')
- )
-
- return response.keys.map {|key| qdval(key.to_s, response[key]) }.join(',')
- when STAGE_TWO
- @stage = nil
- # if at the second stage, return an empty string
- if challenge =~ /rspauth=/
- return ''
- else
- raise ResponseParseError, challenge
- end
- else
- raise ResponseParseError, challenge
- end
- end
-
- def initialize(user, password, authname = nil)
- @user, @password, @authname = user, password, authname
- @nc, @stage = {}, STAGE_ONE
- end
-
- private
-
- STAGE_ONE = :stage_one
- STAGE_TWO = :stage_two
-
- def nc(nonce)
- if @nc.has_key? nonce
- @nc[nonce] = @nc[nonce] + 1
- else
- @nc[nonce] = 1
- end
- return @nc[nonce]
- end
-
- # some responses need quoting
- def qdval(k, v)
- return if k.nil? or v.nil?
- if %w"username authzid realm nonce cnonce digest-uri qop".include? k
- v.gsub!(/([\\"])/, "\\\1")
- return '%s="%s"' % [k, v]
- else
- return '%s=%s' % [k, v]
- end
- end
- end
- add_authenticator "DIGEST-MD5", DigestMD5Authenticator
-
- # Superclass of IMAP errors.
- class Error < StandardError
- end
-
- # Error raised when data is in the incorrect format.
- class DataFormatError < Error
- end
-
- # Error raised when a response from the server is non-parseable.
- class ResponseParseError < Error
- end
-
- # Superclass of all errors used to encapsulate "fail" responses
- # from the server.
- class ResponseError < Error
-
- # The response that caused this error
- attr_accessor :response
-
- def initialize(response)
- @response = response
-
- super @response.data.text
- end
-
- end
-
- # Error raised upon a "NO" response from the server, indicating
- # that the client command could not be completed successfully.
- class NoResponseError < ResponseError
- end
-
- # Error raised upon a "BAD" response from the server, indicating
- # that the client command violated the IMAP protocol, or an internal
- # server failure has occurred.
- class BadResponseError < ResponseError
- end
-
- # Error raised upon a "BYE" response from the server, indicating
- # that the client is not being allowed to login, or has been timed
- # out due to inactivity.
- class ByeResponseError < ResponseError
- end
-
- # Error raised when too many flags are interned to symbols.
- class FlagCountError < Error
- end
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/pop.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/pop.rb
deleted file mode 100755
index cec7aa988..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/pop.rb
+++ /dev/null
@@ -1,1021 +0,0 @@
-# = net/pop.rb
-#
-# Copyright (c) 1999-2007 Yukihiro Matsumoto.
-#
-# Copyright (c) 1999-2007 Minero Aoki.
-#
-# Written & maintained by Minero Aoki .
-#
-# Documented by William Webber and Minero Aoki.
-#
-# This program is free software. You can re-distribute and/or
-# modify this program under the same terms as Ruby itself,
-# Ruby Distribute License.
-#
-# NOTE: You can find Japanese version of this document at:
-# http://www.ruby-lang.org/ja/man/html/net_pop.html
-#
-# $Id: pop.rb 44164 2013-12-13 02:38:55Z a_matsuda $
-#
-# See Net::POP3 for documentation.
-#
-
-require 'net/protocol'
-require 'digest/md5'
-require 'timeout'
-
-begin
- require "openssl"
-rescue LoadError
-end
-
-module Net
-
- # Non-authentication POP3 protocol error
- # (reply code "-ERR", except authentication).
- class POPError < ProtocolError; end
-
- # POP3 authentication error.
- class POPAuthenticationError < ProtoAuthError; end
-
- # Unexpected response from the server.
- class POPBadResponse < POPError; end
-
- #
- # == What is This Library?
- #
- # This library provides functionality for retrieving
- # email via POP3, the Post Office Protocol version 3. For details
- # of POP3, see [RFC1939] (http://www.ietf.org/rfc/rfc1939.txt).
- #
- # == Examples
- #
- # === Retrieving Messages
- #
- # This example retrieves messages from the server and deletes them
- # on the server.
- #
- # Messages are written to files named 'inbox/1', 'inbox/2', ....
- # Replace 'pop.example.com' with your POP3 server address, and
- # 'YourAccount' and 'YourPassword' with the appropriate account
- # details.
- #
- # require 'net/pop'
- #
- # pop = Net::POP3.new('pop.example.com')
- # pop.start('YourAccount', 'YourPassword') # (1)
- # if pop.mails.empty?
- # puts 'No mail.'
- # else
- # i = 0
- # pop.each_mail do |m| # or "pop.mails.each ..." # (2)
- # File.open("inbox/#{i}", 'w') do |f|
- # f.write m.pop
- # end
- # m.delete
- # i += 1
- # end
- # puts "#{pop.mails.size} mails popped."
- # end
- # pop.finish # (3)
- #
- # 1. Call Net::POP3#start and start POP session.
- # 2. Access messages by using POP3#each_mail and/or POP3#mails.
- # 3. Close POP session by calling POP3#finish or use the block form of #start.
- #
- # === Shortened Code
- #
- # The example above is very verbose. You can shorten the code by using
- # some utility methods. First, the block form of Net::POP3.start can
- # be used instead of POP3.new, POP3#start and POP3#finish.
- #
- # require 'net/pop'
- #
- # Net::POP3.start('pop.example.com', 110,
- # 'YourAccount', 'YourPassword') do |pop|
- # if pop.mails.empty?
- # puts 'No mail.'
- # else
- # i = 0
- # pop.each_mail do |m| # or "pop.mails.each ..."
- # File.open("inbox/#{i}", 'w') do |f|
- # f.write m.pop
- # end
- # m.delete
- # i += 1
- # end
- # puts "#{pop.mails.size} mails popped."
- # end
- # end
- #
- # POP3#delete_all is an alternative for #each_mail and #delete.
- #
- # require 'net/pop'
- #
- # Net::POP3.start('pop.example.com', 110,
- # 'YourAccount', 'YourPassword') do |pop|
- # if pop.mails.empty?
- # puts 'No mail.'
- # else
- # i = 1
- # pop.delete_all do |m|
- # File.open("inbox/#{i}", 'w') do |f|
- # f.write m.pop
- # end
- # i += 1
- # end
- # end
- # end
- #
- # And here is an even shorter example.
- #
- # require 'net/pop'
- #
- # i = 0
- # Net::POP3.delete_all('pop.example.com', 110,
- # 'YourAccount', 'YourPassword') do |m|
- # File.open("inbox/#{i}", 'w') do |f|
- # f.write m.pop
- # end
- # i += 1
- # end
- #
- # === Memory Space Issues
- #
- # All the examples above get each message as one big string.
- # This example avoids this.
- #
- # require 'net/pop'
- #
- # i = 1
- # Net::POP3.delete_all('pop.example.com', 110,
- # 'YourAccount', 'YourPassword') do |m|
- # File.open("inbox/#{i}", 'w') do |f|
- # m.pop do |chunk| # get a message little by little.
- # f.write chunk
- # end
- # i += 1
- # end
- # end
- #
- # === Using APOP
- #
- # The net/pop library supports APOP authentication.
- # To use APOP, use the Net::APOP class instead of the Net::POP3 class.
- # You can use the utility method, Net::POP3.APOP(). For example:
- #
- # require 'net/pop'
- #
- # # Use APOP authentication if $isapop == true
- # pop = Net::POP3.APOP($is_apop).new('apop.example.com', 110)
- # pop.start(YourAccount', 'YourPassword') do |pop|
- # # Rest of the code is the same.
- # end
- #
- # === Fetch Only Selected Mail Using 'UIDL' POP Command
- #
- # If your POP server provides UIDL functionality,
- # you can grab only selected mails from the POP server.
- # e.g.
- #
- # def need_pop?( id )
- # # determine if we need pop this mail...
- # end
- #
- # Net::POP3.start('pop.example.com', 110,
- # 'Your account', 'Your password') do |pop|
- # pop.mails.select { |m| need_pop?(m.unique_id) }.each do |m|
- # do_something(m.pop)
- # end
- # end
- #
- # The POPMail#unique_id() method returns the unique-id of the message as a
- # String. Normally the unique-id is a hash of the message.
- #
- class POP3 < Protocol
-
- # svn revision of this library
- Revision = %q$Revision: 44164 $.split[1]
-
- #
- # Class Parameters
- #
-
- # returns the port for POP3
- def POP3.default_port
- default_pop3_port()
- end
-
- # The default port for POP3 connections, port 110
- def POP3.default_pop3_port
- 110
- end
-
- # The default port for POP3S connections, port 995
- def POP3.default_pop3s_port
- 995
- end
-
- def POP3.socket_type #:nodoc: obsolete
- Net::InternetMessageIO
- end
-
- #
- # Utilities
- #
-
- # Returns the APOP class if +isapop+ is true; otherwise, returns
- # the POP class. For example:
- #
- # # Example 1
- # pop = Net::POP3::APOP($is_apop).new(addr, port)
- #
- # # Example 2
- # Net::POP3::APOP($is_apop).start(addr, port) do |pop|
- # ....
- # end
- #
- def POP3.APOP(isapop)
- isapop ? APOP : POP3
- end
-
- # Starts a POP3 session and iterates over each POPMail object,
- # yielding it to the +block+.
- # This method is equivalent to:
- #
- # Net::POP3.start(address, port, account, password) do |pop|
- # pop.each_mail do |m|
- # yield m
- # end
- # end
- #
- # This method raises a POPAuthenticationError if authentication fails.
- #
- # === Example
- #
- # Net::POP3.foreach('pop.example.com', 110,
- # 'YourAccount', 'YourPassword') do |m|
- # file.write m.pop
- # m.delete if $DELETE
- # end
- #
- def POP3.foreach(address, port = nil,
- account = nil, password = nil,
- isapop = false, &block) # :yields: message
- start(address, port, account, password, isapop) {|pop|
- pop.each_mail(&block)
- }
- end
-
- # Starts a POP3 session and deletes all messages on the server.
- # If a block is given, each POPMail object is yielded to it before
- # being deleted.
- #
- # This method raises a POPAuthenticationError if authentication fails.
- #
- # === Example
- #
- # Net::POP3.delete_all('pop.example.com', 110,
- # 'YourAccount', 'YourPassword') do |m|
- # file.write m.pop
- # end
- #
- def POP3.delete_all(address, port = nil,
- account = nil, password = nil,
- isapop = false, &block)
- start(address, port, account, password, isapop) {|pop|
- pop.delete_all(&block)
- }
- end
-
- # Opens a POP3 session, attempts authentication, and quits.
- #
- # This method raises POPAuthenticationError if authentication fails.
- #
- # === Example: normal POP3
- #
- # Net::POP3.auth_only('pop.example.com', 110,
- # 'YourAccount', 'YourPassword')
- #
- # === Example: APOP
- #
- # Net::POP3.auth_only('pop.example.com', 110,
- # 'YourAccount', 'YourPassword', true)
- #
- def POP3.auth_only(address, port = nil,
- account = nil, password = nil,
- isapop = false)
- new(address, port, isapop).auth_only account, password
- end
-
- # Starts a pop3 session, attempts authentication, and quits.
- # This method must not be called while POP3 session is opened.
- # This method raises POPAuthenticationError if authentication fails.
- def auth_only(account, password)
- raise IOError, 'opening previously opened POP session' if started?
- start(account, password) {
- ;
- }
- end
-
- #
- # SSL
- #
-
- @ssl_params = nil
-
- # :call-seq:
- # Net::POP.enable_ssl(params = {})
- #
- # Enable SSL for all new instances.
- # +params+ is passed to OpenSSL::SSLContext#set_params.
- def POP3.enable_ssl(*args)
- @ssl_params = create_ssl_params(*args)
- end
-
- # Constructs proper parameters from arguments
- def POP3.create_ssl_params(verify_or_params = {}, certs = nil)
- begin
- params = verify_or_params.to_hash
- rescue NoMethodError
- params = {}
- params[:verify_mode] = verify_or_params
- if certs
- if File.file?(certs)
- params[:ca_file] = certs
- elsif File.directory?(certs)
- params[:ca_path] = certs
- end
- end
- end
- return params
- end
-
- # Disable SSL for all new instances.
- def POP3.disable_ssl
- @ssl_params = nil
- end
-
- # returns the SSL Parameters
- #
- # see also POP3.enable_ssl
- def POP3.ssl_params
- return @ssl_params
- end
-
- # returns +true+ if POP3.ssl_params is set
- def POP3.use_ssl?
- return !@ssl_params.nil?
- end
-
- # returns whether verify_mode is enable from POP3.ssl_params
- def POP3.verify
- return @ssl_params[:verify_mode]
- end
-
- # returns the :ca_file or :ca_path from POP3.ssl_params
- def POP3.certs
- return @ssl_params[:ca_file] || @ssl_params[:ca_path]
- end
-
- #
- # Session management
- #
-
- # Creates a new POP3 object and open the connection. Equivalent to
- #
- # Net::POP3.new(address, port, isapop).start(account, password)
- #
- # If +block+ is provided, yields the newly-opened POP3 object to it,
- # and automatically closes it at the end of the session.
- #
- # === Example
- #
- # Net::POP3.start(addr, port, account, password) do |pop|
- # pop.each_mail do |m|
- # file.write m.pop
- # m.delete
- # end
- # end
- #
- def POP3.start(address, port = nil,
- account = nil, password = nil,
- isapop = false, &block) # :yield: pop
- new(address, port, isapop).start(account, password, &block)
- end
-
- # Creates a new POP3 object.
- #
- # +address+ is the hostname or ip address of your POP3 server.
- #
- # The optional +port+ is the port to connect to.
- #
- # The optional +isapop+ specifies whether this connection is going
- # to use APOP authentication; it defaults to +false+.
- #
- # This method does *not* open the TCP connection.
- def initialize(addr, port = nil, isapop = false)
- @address = addr
- @ssl_params = POP3.ssl_params
- @port = port
- @apop = isapop
-
- @command = nil
- @socket = nil
- @started = false
- @open_timeout = 30
- @read_timeout = 60
- @debug_output = nil
-
- @mails = nil
- @n_mails = nil
- @n_bytes = nil
- end
-
- # Does this instance use APOP authentication?
- def apop?
- @apop
- end
-
- # does this instance use SSL?
- def use_ssl?
- return !@ssl_params.nil?
- end
-
- # :call-seq:
- # Net::POP#enable_ssl(params = {})
- #
- # Enables SSL for this instance. Must be called before the connection is
- # established to have any effect.
- # +params[:port]+ is port to establish the SSL connection on; Defaults to 995.
- # +params+ (except :port) is passed to OpenSSL::SSLContext#set_params.
- def enable_ssl(verify_or_params = {}, certs = nil, port = nil)
- begin
- @ssl_params = verify_or_params.to_hash.dup
- @port = @ssl_params.delete(:port) || @port
- rescue NoMethodError
- @ssl_params = POP3.create_ssl_params(verify_or_params, certs)
- @port = port || @port
- end
- end
-
- # Disable SSL for all new instances.
- def disable_ssl
- @ssl_params = nil
- end
-
- # Provide human-readable stringification of class state.
- def inspect
- "#<#{self.class} #{@address}:#{@port} open=#{@started}>"
- end
-
- # *WARNING*: This method causes a serious security hole.
- # Use this method only for debugging.
- #
- # Set an output stream for debugging.
- #
- # === Example
- #
- # pop = Net::POP.new(addr, port)
- # pop.set_debug_output $stderr
- # pop.start(account, passwd) do |pop|
- # ....
- # end
- #
- def set_debug_output(arg)
- @debug_output = arg
- end
-
- # The address to connect to.
- attr_reader :address
-
- # The port number to connect to.
- def port
- return @port || (use_ssl? ? POP3.default_pop3s_port : POP3.default_pop3_port)
- end
-
- # Seconds to wait until a connection is opened.
- # If the POP3 object cannot open a connection within this time,
- # it raises a Net::OpenTimeout exception. The default value is 30 seconds.
- attr_accessor :open_timeout
-
- # Seconds to wait until reading one block (by one read(1) call).
- # If the POP3 object cannot complete a read() within this time,
- # it raises a Net::ReadTimeout exception. The default value is 60 seconds.
- attr_reader :read_timeout
-
- # Set the read timeout.
- def read_timeout=(sec)
- @command.socket.read_timeout = sec if @command
- @read_timeout = sec
- end
-
- # +true+ if the POP3 session has started.
- def started?
- @started
- end
-
- alias active? started? #:nodoc: obsolete
-
- # Starts a POP3 session.
- #
- # When called with block, gives a POP3 object to the block and
- # closes the session after block call finishes.
- #
- # This method raises a POPAuthenticationError if authentication fails.
- def start(account, password) # :yield: pop
- raise IOError, 'POP session already started' if @started
- if block_given?
- begin
- do_start account, password
- return yield(self)
- ensure
- do_finish
- end
- else
- do_start account, password
- return self
- end
- end
-
- # internal method for Net::POP3.start
- def do_start(account, password) # :nodoc:
- s = Timeout.timeout(@open_timeout, Net::OpenTimeout) do
- TCPSocket.open(@address, port)
- end
- if use_ssl?
- raise 'openssl library not installed' unless defined?(OpenSSL)
- context = OpenSSL::SSL::SSLContext.new
- context.set_params(@ssl_params)
- s = OpenSSL::SSL::SSLSocket.new(s, context)
- s.sync_close = true
- s.connect
- if context.verify_mode != OpenSSL::SSL::VERIFY_NONE
- s.post_connection_check(@address)
- end
- end
- @socket = InternetMessageIO.new(s)
- logging "POP session started: #{@address}:#{@port} (#{@apop ? 'APOP' : 'POP'})"
- @socket.read_timeout = @read_timeout
- @socket.debug_output = @debug_output
- on_connect
- @command = POP3Command.new(@socket)
- if apop?
- @command.apop account, password
- else
- @command.auth account, password
- end
- @started = true
- ensure
- # Authentication failed, clean up connection.
- unless @started
- s.close if s and not s.closed?
- @socket = nil
- @command = nil
- end
- end
- private :do_start
-
- # Does nothing
- def on_connect # :nodoc:
- end
- private :on_connect
-
- # Finishes a POP3 session and closes TCP connection.
- def finish
- raise IOError, 'POP session not yet started' unless started?
- do_finish
- end
-
- # nil's out the:
- # - mails
- # - number counter for mails
- # - number counter for bytes
- # - quits the current command, if any
- def do_finish # :nodoc:
- @mails = nil
- @n_mails = nil
- @n_bytes = nil
- @command.quit if @command
- ensure
- @started = false
- @command = nil
- @socket.close if @socket and not @socket.closed?
- @socket = nil
- end
- private :do_finish
-
- # Returns the current command.
- #
- # Raises IOError if there is no active socket
- def command # :nodoc:
- raise IOError, 'POP session not opened yet' \
- if not @socket or @socket.closed?
- @command
- end
- private :command
-
- #
- # POP protocol wrapper
- #
-
- # Returns the number of messages on the POP server.
- def n_mails
- return @n_mails if @n_mails
- @n_mails, @n_bytes = command().stat
- @n_mails
- end
-
- # Returns the total size in bytes of all the messages on the POP server.
- def n_bytes
- return @n_bytes if @n_bytes
- @n_mails, @n_bytes = command().stat
- @n_bytes
- end
-
- # Returns an array of Net::POPMail objects, representing all the
- # messages on the server. This array is renewed when the session
- # restarts; otherwise, it is fetched from the server the first time
- # this method is called (directly or indirectly) and cached.
- #
- # This method raises a POPError if an error occurs.
- def mails
- return @mails.dup if @mails
- if n_mails() == 0
- # some popd raises error for LIST on the empty mailbox.
- @mails = []
- return []
- end
-
- @mails = command().list.map {|num, size|
- POPMail.new(num, size, self, command())
- }
- @mails.dup
- end
-
- # Yields each message to the passed-in block in turn.
- # Equivalent to:
- #
- # pop3.mails.each do |popmail|
- # ....
- # end
- #
- # This method raises a POPError if an error occurs.
- def each_mail(&block) # :yield: message
- mails().each(&block)
- end
-
- alias each each_mail
-
- # Deletes all messages on the server.
- #
- # If called with a block, yields each message in turn before deleting it.
- #
- # === Example
- #
- # n = 1
- # pop.delete_all do |m|
- # File.open("inbox/#{n}") do |f|
- # f.write m.pop
- # end
- # n += 1
- # end
- #
- # This method raises a POPError if an error occurs.
- #
- def delete_all # :yield: message
- mails().each do |m|
- yield m if block_given?
- m.delete unless m.deleted?
- end
- end
-
- # Resets the session. This clears all "deleted" marks from messages.
- #
- # This method raises a POPError if an error occurs.
- def reset
- command().rset
- mails().each do |m|
- m.instance_eval {
- @deleted = false
- }
- end
- end
-
- def set_all_uids #:nodoc: internal use only (called from POPMail#uidl)
- uidl = command().uidl
- @mails.each {|m| m.uid = uidl[m.number] }
- end
-
- # debugging output for +msg+
- def logging(msg)
- @debug_output << msg + "\n" if @debug_output
- end
-
- end # class POP3
-
- # class aliases
- POP = POP3 # :nodoc:
- POPSession = POP3 # :nodoc:
- POP3Session = POP3 # :nodoc:
-
- #
- # This class is equivalent to POP3, except that it uses APOP authentication.
- #
- class APOP < POP3
- # Always returns true.
- def apop?
- true
- end
- end
-
- # class aliases
- APOPSession = APOP
-
- #
- # This class represents a message which exists on the POP server.
- # Instances of this class are created by the POP3 class; they should
- # not be directly created by the user.
- #
- class POPMail
-
- def initialize(num, len, pop, cmd) #:nodoc:
- @number = num
- @length = len
- @pop = pop
- @command = cmd
- @deleted = false
- @uid = nil
- end
-
- # The sequence number of the message on the server.
- attr_reader :number
-
- # The length of the message in octets.
- attr_reader :length
- alias size length
-
- # Provide human-readable stringification of class state.
- def inspect
- "#<#{self.class} #{@number}#{@deleted ? ' deleted' : ''}>"
- end
-
- #
- # This method fetches the message. If called with a block, the
- # message is yielded to the block one chunk at a time. If called
- # without a block, the message is returned as a String. The optional
- # +dest+ argument will be prepended to the returned String; this
- # argument is essentially obsolete.
- #
- # === Example without block
- #
- # POP3.start('pop.example.com', 110,
- # 'YourAccount, 'YourPassword') do |pop|
- # n = 1
- # pop.mails.each do |popmail|
- # File.open("inbox/#{n}", 'w') do |f|
- # f.write popmail.pop
- # end
- # popmail.delete
- # n += 1
- # end
- # end
- #
- # === Example with block
- #
- # POP3.start('pop.example.com', 110,
- # 'YourAccount, 'YourPassword') do |pop|
- # n = 1
- # pop.mails.each do |popmail|
- # File.open("inbox/#{n}", 'w') do |f|
- # popmail.pop do |chunk| ####
- # f.write chunk
- # end
- # end
- # n += 1
- # end
- # end
- #
- # This method raises a POPError if an error occurs.
- #
- def pop( dest = '', &block ) # :yield: message_chunk
- if block_given?
- @command.retr(@number, &block)
- nil
- else
- @command.retr(@number) do |chunk|
- dest << chunk
- end
- dest
- end
- end
-
- alias all pop #:nodoc: obsolete
- alias mail pop #:nodoc: obsolete
-
- # Fetches the message header and +lines+ lines of body.
- #
- # The optional +dest+ argument is obsolete.
- #
- # This method raises a POPError if an error occurs.
- def top(lines, dest = '')
- @command.top(@number, lines) do |chunk|
- dest << chunk
- end
- dest
- end
-
- # Fetches the message header.
- #
- # The optional +dest+ argument is obsolete.
- #
- # This method raises a POPError if an error occurs.
- def header(dest = '')
- top(0, dest)
- end
-
- # Marks a message for deletion on the server. Deletion does not
- # actually occur until the end of the session; deletion may be
- # cancelled for _all_ marked messages by calling POP3#reset().
- #
- # This method raises a POPError if an error occurs.
- #
- # === Example
- #
- # POP3.start('pop.example.com', 110,
- # 'YourAccount, 'YourPassword') do |pop|
- # n = 1
- # pop.mails.each do |popmail|
- # File.open("inbox/#{n}", 'w') do |f|
- # f.write popmail.pop
- # end
- # popmail.delete ####
- # n += 1
- # end
- # end
- #
- def delete
- @command.dele @number
- @deleted = true
- end
-
- alias delete! delete #:nodoc: obsolete
-
- # True if the mail has been deleted.
- def deleted?
- @deleted
- end
-
- # Returns the unique-id of the message.
- # Normally the unique-id is a hash string of the message.
- #
- # This method raises a POPError if an error occurs.
- def unique_id
- return @uid if @uid
- @pop.set_all_uids
- @uid
- end
-
- alias uidl unique_id
-
- def uid=(uid) #:nodoc: internal use only
- @uid = uid
- end
-
- end # class POPMail
-
-
- class POP3Command #:nodoc: internal use only
-
- def initialize(sock)
- @socket = sock
- @error_occurred = false
- res = check_response(critical { recv_response() })
- @apop_stamp = res.slice(/<[!-~]+@[!-~]+>/)
- end
-
- attr_reader :socket
-
- def inspect
- "#<#{self.class} socket=#{@socket}>"
- end
-
- def auth(account, password)
- check_response_auth(critical {
- check_response_auth(get_response('USER %s', account))
- get_response('PASS %s', password)
- })
- end
-
- def apop(account, password)
- raise POPAuthenticationError, 'not APOP server; cannot login' \
- unless @apop_stamp
- check_response_auth(critical {
- get_response('APOP %s %s',
- account,
- Digest::MD5.hexdigest(@apop_stamp + password))
- })
- end
-
- def list
- critical {
- getok 'LIST'
- list = []
- @socket.each_list_item do |line|
- m = /\A(\d+)[ \t]+(\d+)/.match(line) or
- raise POPBadResponse, "bad response: #{line}"
- list.push [m[1].to_i, m[2].to_i]
- end
- return list
- }
- end
-
- def stat
- res = check_response(critical { get_response('STAT') })
- m = /\A\+OK\s+(\d+)\s+(\d+)/.match(res) or
- raise POPBadResponse, "wrong response format: #{res}"
- [m[1].to_i, m[2].to_i]
- end
-
- def rset
- check_response(critical { get_response('RSET') })
- end
-
- def top(num, lines = 0, &block)
- critical {
- getok('TOP %d %d', num, lines)
- @socket.each_message_chunk(&block)
- }
- end
-
- def retr(num, &block)
- critical {
- getok('RETR %d', num)
- @socket.each_message_chunk(&block)
- }
- end
-
- def dele(num)
- check_response(critical { get_response('DELE %d', num) })
- end
-
- def uidl(num = nil)
- if num
- res = check_response(critical { get_response('UIDL %d', num) })
- return res.split(/ /)[1]
- else
- critical {
- getok('UIDL')
- table = {}
- @socket.each_list_item do |line|
- num, uid = line.split
- table[num.to_i] = uid
- end
- return table
- }
- end
- end
-
- def quit
- check_response(critical { get_response('QUIT') })
- end
-
- private
-
- def getok(fmt, *fargs)
- @socket.writeline sprintf(fmt, *fargs)
- check_response(recv_response())
- end
-
- def get_response(fmt, *fargs)
- @socket.writeline sprintf(fmt, *fargs)
- recv_response()
- end
-
- def recv_response
- @socket.readline
- end
-
- def check_response(res)
- raise POPError, res unless /\A\+OK/i =~ res
- res
- end
-
- def check_response_auth(res)
- raise POPAuthenticationError, res unless /\A\+OK/i =~ res
- res
- end
-
- def critical
- return '+OK dummy ok response' if @error_occurred
- begin
- return yield()
- rescue Exception
- @error_occurred = true
- raise
- end
- end
-
- end # class POP3Command
-
-end # module Net
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/protocol.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/protocol.rb
deleted file mode 100755
index ae3620d27..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/protocol.rb
+++ /dev/null
@@ -1,420 +0,0 @@
-#
-# = net/protocol.rb
-#
-#--
-# Copyright (c) 1999-2004 Yukihiro Matsumoto
-# Copyright (c) 1999-2004 Minero Aoki
-#
-# written and maintained by Minero Aoki
-#
-# This program is free software. You can re-distribute and/or
-# modify this program under the same terms as Ruby itself,
-# Ruby Distribute License or GNU General Public License.
-#
-# $Id: protocol.rb 46060 2014-05-23 12:36:30Z nobu $
-#++
-#
-# WARNING: This file is going to remove.
-# Do not rely on the implementation written in this file.
-#
-
-require 'socket'
-require 'timeout'
-
-module Net # :nodoc:
-
- class Protocol #:nodoc: internal use only
- private
- def Protocol.protocol_param(name, val)
- module_eval(<<-End, __FILE__, __LINE__ + 1)
- def #{name}
- #{val}
- end
- End
- end
- end
-
-
- class ProtocolError < StandardError; end
- class ProtoSyntaxError < ProtocolError; end
- class ProtoFatalError < ProtocolError; end
- class ProtoUnknownError < ProtocolError; end
- class ProtoServerError < ProtocolError; end
- class ProtoAuthError < ProtocolError; end
- class ProtoCommandError < ProtocolError; end
- class ProtoRetriableError < ProtocolError; end
- ProtocRetryError = ProtoRetriableError
-
- ##
- # OpenTimeout, a subclass of Timeout::Error, is raised if a connection cannot
- # be created within the open_timeout.
-
- class OpenTimeout < Timeout::Error; end
-
- ##
- # ReadTimeout, a subclass of Timeout::Error, is raised if a chunk of the
- # response cannot be read within the read_timeout.
-
- class ReadTimeout < Timeout::Error; end
-
-
- class BufferedIO #:nodoc: internal use only
- def initialize(io)
- @io = io
- @read_timeout = 60
- @continue_timeout = nil
- @debug_output = nil
- @rbuf = ''
- end
-
- attr_reader :io
- attr_accessor :read_timeout
- attr_accessor :continue_timeout
- attr_accessor :debug_output
-
- def inspect
- "#<#{self.class} io=#{@io}>"
- end
-
- def eof?
- @io.eof?
- end
-
- def closed?
- @io.closed?
- end
-
- def close
- @io.close
- end
-
- #
- # Read
- #
-
- public
-
- def read(len, dest = '', ignore_eof = false)
- LOG "reading #{len} bytes..."
- read_bytes = 0
- begin
- while read_bytes + @rbuf.size < len
- dest << (s = rbuf_consume(@rbuf.size))
- read_bytes += s.size
- rbuf_fill
- end
- dest << (s = rbuf_consume(len - read_bytes))
- read_bytes += s.size
- rescue EOFError
- raise unless ignore_eof
- end
- LOG "read #{read_bytes} bytes"
- dest
- end
-
- def read_all(dest = '')
- LOG 'reading all...'
- read_bytes = 0
- begin
- while true
- dest << (s = rbuf_consume(@rbuf.size))
- read_bytes += s.size
- rbuf_fill
- end
- rescue EOFError
- ;
- end
- LOG "read #{read_bytes} bytes"
- dest
- end
-
- def readuntil(terminator, ignore_eof = false)
- begin
- until idx = @rbuf.index(terminator)
- rbuf_fill
- end
- return rbuf_consume(idx + terminator.size)
- rescue EOFError
- raise unless ignore_eof
- return rbuf_consume(@rbuf.size)
- end
- end
-
- def readline
- readuntil("\n").chop
- end
-
- private
-
- BUFSIZE = 1024 * 16
-
- def rbuf_fill
- begin
- @rbuf << @io.read_nonblock(BUFSIZE)
- rescue IO::WaitReadable
- if IO.select([@io], nil, nil, @read_timeout)
- retry
- else
- raise Net::ReadTimeout
- end
- rescue IO::WaitWritable
- # OpenSSL::Buffering#read_nonblock may fail with IO::WaitWritable.
- # http://www.openssl.org/support/faq.html#PROG10
- if IO.select(nil, [@io], nil, @read_timeout)
- retry
- else
- raise Net::ReadTimeout
- end
- end
- end
-
- def rbuf_consume(len)
- s = @rbuf.slice!(0, len)
- @debug_output << %Q[-> #{s.dump}\n] if @debug_output
- s
- end
-
- #
- # Write
- #
-
- public
-
- def write(str)
- writing {
- write0 str
- }
- end
-
- alias << write
-
- def writeline(str)
- writing {
- write0 str + "\r\n"
- }
- end
-
- private
-
- def writing
- @written_bytes = 0
- @debug_output << '<- ' if @debug_output
- yield
- @debug_output << "\n" if @debug_output
- bytes = @written_bytes
- @written_bytes = nil
- bytes
- end
-
- def write0(str)
- @debug_output << str.dump if @debug_output
- len = @io.write(str)
- @written_bytes += len
- len
- end
-
- #
- # Logging
- #
-
- private
-
- def LOG_off
- @save_debug_out = @debug_output
- @debug_output = nil
- end
-
- def LOG_on
- @debug_output = @save_debug_out
- end
-
- def LOG(msg)
- return unless @debug_output
- @debug_output << msg + "\n"
- end
- end
-
-
- class InternetMessageIO < BufferedIO #:nodoc: internal use only
- def initialize(io)
- super
- @wbuf = nil
- end
-
- #
- # Read
- #
-
- def each_message_chunk
- LOG 'reading message...'
- LOG_off()
- read_bytes = 0
- while (line = readuntil("\r\n")) != ".\r\n"
- read_bytes += line.size
- yield line.sub(/\A\./, '')
- end
- LOG_on()
- LOG "read message (#{read_bytes} bytes)"
- end
-
- # *library private* (cannot handle 'break')
- def each_list_item
- while (str = readuntil("\r\n")) != ".\r\n"
- yield str.chop
- end
- end
-
- def write_message_0(src)
- prev = @written_bytes
- each_crlf_line(src) do |line|
- write0 dot_stuff(line)
- end
- @written_bytes - prev
- end
-
- #
- # Write
- #
-
- def write_message(src)
- LOG "writing message from #{src.class}"
- LOG_off()
- len = writing {
- using_each_crlf_line {
- write_message_0 src
- }
- }
- LOG_on()
- LOG "wrote #{len} bytes"
- len
- end
-
- def write_message_by_block(&block)
- LOG 'writing message from block'
- LOG_off()
- len = writing {
- using_each_crlf_line {
- begin
- block.call(WriteAdapter.new(self, :write_message_0))
- rescue LocalJumpError
- # allow `break' from writer block
- end
- }
- }
- LOG_on()
- LOG "wrote #{len} bytes"
- len
- end
-
- private
-
- def dot_stuff(s)
- s.sub(/\A\./, '..')
- end
-
- def using_each_crlf_line
- @wbuf = ''
- yield
- if not @wbuf.empty? # unterminated last line
- write0 dot_stuff(@wbuf.chomp) + "\r\n"
- elsif @written_bytes == 0 # empty src
- write0 "\r\n"
- end
- write0 ".\r\n"
- @wbuf = nil
- end
-
- def each_crlf_line(src)
- buffer_filling(@wbuf, src) do
- while line = @wbuf.slice!(/\A[^\r\n]*(?:\n|\r(?:\n|(?!\z)))/)
- yield line.chomp("\n") + "\r\n"
- end
- end
- end
-
- def buffer_filling(buf, src)
- case src
- when String # for speeding up.
- 0.step(src.size - 1, 1024) do |i|
- buf << src[i, 1024]
- yield
- end
- when File # for speeding up.
- while s = src.read(1024)
- buf << s
- yield
- end
- else # generic reader
- src.each do |str|
- buf << str
- yield if buf.size > 1024
- end
- yield unless buf.empty?
- end
- end
- end
-
-
- #
- # The writer adapter class
- #
- class WriteAdapter
- def initialize(socket, method)
- @socket = socket
- @method_id = method
- end
-
- def inspect
- "#<#{self.class} socket=#{@socket.inspect}>"
- end
-
- def write(str)
- @socket.__send__(@method_id, str)
- end
-
- alias print write
-
- def <<(str)
- write str
- self
- end
-
- def puts(str = '')
- write str.chomp("\n") + "\n"
- end
-
- def printf(*args)
- write sprintf(*args)
- end
- end
-
-
- class ReadAdapter #:nodoc: internal use only
- def initialize(block)
- @block = block
- end
-
- def inspect
- "#<#{self.class}>"
- end
-
- def <<(str)
- call_block(str, &@block) if @block
- end
-
- private
-
- # This method is needed because @block must be called by yield,
- # not Proc#call. You can see difference when using `break' in
- # the block.
- def call_block(str)
- yield str
- end
- end
-
-
- module NetPrivate #:nodoc: obsolete
- Socket = ::Net::InternetMessageIO
- end
-
-end # module Net
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/smtp.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/smtp.rb
deleted file mode 100755
index 04640e35a..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/net/smtp.rb
+++ /dev/null
@@ -1,1073 +0,0 @@
-# = net/smtp.rb
-#
-# Copyright (c) 1999-2007 Yukihiro Matsumoto.
-#
-# Copyright (c) 1999-2007 Minero Aoki.
-#
-# Written & maintained by Minero Aoki .
-#
-# Documented by William Webber and Minero Aoki.
-#
-# This program is free software. You can re-distribute and/or
-# modify this program under the same terms as Ruby itself.
-#
-# NOTE: You can find Japanese version of this document at:
-# http://www.ruby-lang.org/ja/man/html/net_smtp.html
-#
-# $Id: smtp.rb 46793 2014-07-11 19:22:19Z kosaki $
-#
-# See Net::SMTP for documentation.
-#
-
-require 'net/protocol'
-require 'digest/md5'
-require 'timeout'
-begin
- require 'openssl'
-rescue LoadError
-end
-
-module Net
-
- # Module mixed in to all SMTP error classes
- module SMTPError
- # This *class* is a module for backward compatibility.
- # In later release, this module becomes a class.
- end
-
- # Represents an SMTP authentication error.
- class SMTPAuthenticationError < ProtoAuthError
- include SMTPError
- end
-
- # Represents SMTP error code 420 or 450, a temporary error.
- class SMTPServerBusy < ProtoServerError
- include SMTPError
- end
-
- # Represents an SMTP command syntax error (error code 500)
- class SMTPSyntaxError < ProtoSyntaxError
- include SMTPError
- end
-
- # Represents a fatal SMTP error (error code 5xx, except for 500)
- class SMTPFatalError < ProtoFatalError
- include SMTPError
- end
-
- # Unexpected reply code returned from server.
- class SMTPUnknownError < ProtoUnknownError
- include SMTPError
- end
-
- # Command is not supported on server.
- class SMTPUnsupportedCommand < ProtocolError
- include SMTPError
- end
-
- #
- # == What is This Library?
- #
- # This library provides functionality to send internet
- # mail via SMTP, the Simple Mail Transfer Protocol. For details of
- # SMTP itself, see [RFC2821] (http://www.ietf.org/rfc/rfc2821.txt).
- #
- # == What is This Library NOT?
- #
- # This library does NOT provide functions to compose internet mails.
- # You must create them by yourself. If you want better mail support,
- # try RubyMail or TMail or search for alternatives in
- # {RubyGems.org}[https://rubygems.org/] or {The Ruby
- # Toolbox}[https://www.ruby-toolbox.com/].
- #
- # FYI: the official documentation on internet mail is: [RFC2822] (http://www.ietf.org/rfc/rfc2822.txt).
- #
- # == Examples
- #
- # === Sending Messages
- #
- # You must open a connection to an SMTP server before sending messages.
- # The first argument is the address of your SMTP server, and the second
- # argument is the port number. Using SMTP.start with a block is the simplest
- # way to do this. This way, the SMTP connection is closed automatically
- # after the block is executed.
- #
- # require 'net/smtp'
- # Net::SMTP.start('your.smtp.server', 25) do |smtp|
- # # Use the SMTP object smtp only in this block.
- # end
- #
- # Replace 'your.smtp.server' with your SMTP server. Normally
- # your system manager or internet provider supplies a server
- # for you.
- #
- # Then you can send messages.
- #
- # msgstr = <
- # To: Destination Address
- # Subject: test message
- # Date: Sat, 23 Jun 2001 16:26:43 +0900
- # Message-Id:
- #
- # This is a test message.
- # END_OF_MESSAGE
- #
- # require 'net/smtp'
- # Net::SMTP.start('your.smtp.server', 25) do |smtp|
- # smtp.send_message msgstr,
- # 'your@mail.address',
- # 'his_address@example.com'
- # end
- #
- # === Closing the Session
- #
- # You MUST close the SMTP session after sending messages, by calling
- # the #finish method:
- #
- # # using SMTP#finish
- # smtp = Net::SMTP.start('your.smtp.server', 25)
- # smtp.send_message msgstr, 'from@address', 'to@address'
- # smtp.finish
- #
- # You can also use the block form of SMTP.start/SMTP#start. This closes
- # the SMTP session automatically:
- #
- # # using block form of SMTP.start
- # Net::SMTP.start('your.smtp.server', 25) do |smtp|
- # smtp.send_message msgstr, 'from@address', 'to@address'
- # end
- #
- # I strongly recommend this scheme. This form is simpler and more robust.
- #
- # === HELO domain
- #
- # In almost all situations, you must provide a third argument
- # to SMTP.start/SMTP#start. This is the domain name which you are on
- # (the host to send mail from). It is called the "HELO domain".
- # The SMTP server will judge whether it should send or reject
- # the SMTP session by inspecting the HELO domain.
- #
- # Net::SMTP.start('your.smtp.server', 25,
- # 'mail.from.domain') { |smtp| ... }
- #
- # === SMTP Authentication
- #
- # The Net::SMTP class supports three authentication schemes;
- # PLAIN, LOGIN and CRAM MD5. (SMTP Authentication: [RFC2554])
- # To use SMTP authentication, pass extra arguments to
- # SMTP.start/SMTP#start.
- #
- # # PLAIN
- # Net::SMTP.start('your.smtp.server', 25, 'mail.from.domain',
- # 'Your Account', 'Your Password', :plain)
- # # LOGIN
- # Net::SMTP.start('your.smtp.server', 25, 'mail.from.domain',
- # 'Your Account', 'Your Password', :login)
- #
- # # CRAM MD5
- # Net::SMTP.start('your.smtp.server', 25, 'mail.from.domain',
- # 'Your Account', 'Your Password', :cram_md5)
- #
- class SMTP
-
- Revision = %q$Revision: 46793 $.split[1]
-
- # The default SMTP port number, 25.
- def SMTP.default_port
- 25
- end
-
- # The default mail submission port number, 587.
- def SMTP.default_submission_port
- 587
- end
-
- # The default SMTPS port number, 465.
- def SMTP.default_tls_port
- 465
- end
-
- class << self
- alias default_ssl_port default_tls_port
- end
-
- def SMTP.default_ssl_context
- OpenSSL::SSL::SSLContext.new
- end
-
- #
- # Creates a new Net::SMTP object.
- #
- # +address+ is the hostname or ip address of your SMTP
- # server. +port+ is the port to connect to; it defaults to
- # port 25.
- #
- # This method does not open the TCP connection. You can use
- # SMTP.start instead of SMTP.new if you want to do everything
- # at once. Otherwise, follow SMTP.new with SMTP#start.
- #
- def initialize(address, port = nil)
- @address = address
- @port = (port || SMTP.default_port)
- @esmtp = true
- @capabilities = nil
- @socket = nil
- @started = false
- @open_timeout = 30
- @read_timeout = 60
- @error_occurred = false
- @debug_output = nil
- @tls = false
- @starttls = false
- @ssl_context = nil
- end
-
- # Provide human-readable stringification of class state.
- def inspect
- "#<#{self.class} #{@address}:#{@port} started=#{@started}>"
- end
-
- #
- # Set whether to use ESMTP or not. This should be done before
- # calling #start. Note that if #start is called in ESMTP mode,
- # and the connection fails due to a ProtocolError, the SMTP
- # object will automatically switch to plain SMTP mode and
- # retry (but not vice versa).
- #
- attr_accessor :esmtp
-
- # +true+ if the SMTP object uses ESMTP (which it does by default).
- alias :esmtp? :esmtp
-
- # true if server advertises STARTTLS.
- # You cannot get valid value before opening SMTP session.
- def capable_starttls?
- capable?('STARTTLS')
- end
-
- def capable?(key)
- return nil unless @capabilities
- @capabilities[key] ? true : false
- end
- private :capable?
-
- # true if server advertises AUTH PLAIN.
- # You cannot get valid value before opening SMTP session.
- def capable_plain_auth?
- auth_capable?('PLAIN')
- end
-
- # true if server advertises AUTH LOGIN.
- # You cannot get valid value before opening SMTP session.
- def capable_login_auth?
- auth_capable?('LOGIN')
- end
-
- # true if server advertises AUTH CRAM-MD5.
- # You cannot get valid value before opening SMTP session.
- def capable_cram_md5_auth?
- auth_capable?('CRAM-MD5')
- end
-
- def auth_capable?(type)
- return nil unless @capabilities
- return false unless @capabilities['AUTH']
- @capabilities['AUTH'].include?(type)
- end
- private :auth_capable?
-
- # Returns supported authentication methods on this server.
- # You cannot get valid value before opening SMTP session.
- def capable_auth_types
- return [] unless @capabilities
- return [] unless @capabilities['AUTH']
- @capabilities['AUTH']
- end
-
- # true if this object uses SMTP/TLS (SMTPS).
- def tls?
- @tls
- end
-
- alias ssl? tls?
-
- # Enables SMTP/TLS (SMTPS: SMTP over direct TLS connection) for
- # this object. Must be called before the connection is established
- # to have any effect. +context+ is a OpenSSL::SSL::SSLContext object.
- def enable_tls(context = SMTP.default_ssl_context)
- raise 'openssl library not installed' unless defined?(OpenSSL)
- raise ArgumentError, "SMTPS and STARTTLS is exclusive" if @starttls
- @tls = true
- @ssl_context = context
- end
-
- alias enable_ssl enable_tls
-
- # Disables SMTP/TLS for this object. Must be called before the
- # connection is established to have any effect.
- def disable_tls
- @tls = false
- @ssl_context = nil
- end
-
- alias disable_ssl disable_tls
-
- # Returns truth value if this object uses STARTTLS.
- # If this object always uses STARTTLS, returns :always.
- # If this object uses STARTTLS when the server support TLS, returns :auto.
- def starttls?
- @starttls
- end
-
- # true if this object uses STARTTLS.
- def starttls_always?
- @starttls == :always
- end
-
- # true if this object uses STARTTLS when server advertises STARTTLS.
- def starttls_auto?
- @starttls == :auto
- end
-
- # Enables SMTP/TLS (STARTTLS) for this object.
- # +context+ is a OpenSSL::SSL::SSLContext object.
- def enable_starttls(context = SMTP.default_ssl_context)
- raise 'openssl library not installed' unless defined?(OpenSSL)
- raise ArgumentError, "SMTPS and STARTTLS is exclusive" if @tls
- @starttls = :always
- @ssl_context = context
- end
-
- # Enables SMTP/TLS (STARTTLS) for this object if server accepts.
- # +context+ is a OpenSSL::SSL::SSLContext object.
- def enable_starttls_auto(context = SMTP.default_ssl_context)
- raise 'openssl library not installed' unless defined?(OpenSSL)
- raise ArgumentError, "SMTPS and STARTTLS is exclusive" if @tls
- @starttls = :auto
- @ssl_context = context
- end
-
- # Disables SMTP/TLS (STARTTLS) for this object. Must be called
- # before the connection is established to have any effect.
- def disable_starttls
- @starttls = false
- @ssl_context = nil
- end
-
- # The address of the SMTP server to connect to.
- attr_reader :address
-
- # The port number of the SMTP server to connect to.
- attr_reader :port
-
- # Seconds to wait while attempting to open a connection.
- # If the connection cannot be opened within this time, a
- # Net::OpenTimeout is raised. The default value is 30 seconds.
- attr_accessor :open_timeout
-
- # Seconds to wait while reading one block (by one read(2) call).
- # If the read(2) call does not complete within this time, a
- # Net::ReadTimeout is raised. The default value is 60 seconds.
- attr_reader :read_timeout
-
- # Set the number of seconds to wait until timing-out a read(2)
- # call.
- def read_timeout=(sec)
- @socket.read_timeout = sec if @socket
- @read_timeout = sec
- end
-
- #
- # WARNING: This method causes serious security holes.
- # Use this method for only debugging.
- #
- # Set an output stream for debug logging.
- # You must call this before #start.
- #
- # # example
- # smtp = Net::SMTP.new(addr, port)
- # smtp.set_debug_output $stderr
- # smtp.start do |smtp|
- # ....
- # end
- #
- def debug_output=(arg)
- @debug_output = arg
- end
-
- alias set_debug_output debug_output=
-
- #
- # SMTP session control
- #
-
- #
- # Creates a new Net::SMTP object and connects to the server.
- #
- # This method is equivalent to:
- #
- # Net::SMTP.new(address, port).start(helo_domain, account, password, authtype)
- #
- # === Example
- #
- # Net::SMTP.start('your.smtp.server') do |smtp|
- # smtp.send_message msgstr, 'from@example.com', ['dest@example.com']
- # end
- #
- # === Block Usage
- #
- # If called with a block, the newly-opened Net::SMTP object is yielded
- # to the block, and automatically closed when the block finishes. If called
- # without a block, the newly-opened Net::SMTP object is returned to
- # the caller, and it is the caller's responsibility to close it when
- # finished.
- #
- # === Parameters
- #
- # +address+ is the hostname or ip address of your smtp server.
- #
- # +port+ is the port to connect to; it defaults to port 25.
- #
- # +helo+ is the _HELO_ _domain_ provided by the client to the
- # server (see overview comments); it defaults to 'localhost'.
- #
- # The remaining arguments are used for SMTP authentication, if required
- # or desired. +user+ is the account name; +secret+ is your password
- # or other authentication token; and +authtype+ is the authentication
- # type, one of :plain, :login, or :cram_md5. See the discussion of
- # SMTP Authentication in the overview notes.
- #
- # === Errors
- #
- # This method may raise:
- #
- # * Net::SMTPAuthenticationError
- # * Net::SMTPServerBusy
- # * Net::SMTPSyntaxError
- # * Net::SMTPFatalError
- # * Net::SMTPUnknownError
- # * Net::OpenTimeout
- # * Net::ReadTimeout
- # * IOError
- #
- def SMTP.start(address, port = nil, helo = 'localhost',
- user = nil, secret = nil, authtype = nil,
- &block) # :yield: smtp
- new(address, port).start(helo, user, secret, authtype, &block)
- end
-
- # +true+ if the SMTP session has been started.
- def started?
- @started
- end
-
- #
- # Opens a TCP connection and starts the SMTP session.
- #
- # === Parameters
- #
- # +helo+ is the _HELO_ _domain_ that you'll dispatch mails from; see
- # the discussion in the overview notes.
- #
- # If both of +user+ and +secret+ are given, SMTP authentication
- # will be attempted using the AUTH command. +authtype+ specifies
- # the type of authentication to attempt; it must be one of
- # :login, :plain, and :cram_md5. See the notes on SMTP Authentication
- # in the overview.
- #
- # === Block Usage
- #
- # When this methods is called with a block, the newly-started SMTP
- # object is yielded to the block, and automatically closed after
- # the block call finishes. Otherwise, it is the caller's
- # responsibility to close the session when finished.
- #
- # === Example
- #
- # This is very similar to the class method SMTP.start.
- #
- # require 'net/smtp'
- # smtp = Net::SMTP.new('smtp.mail.server', 25)
- # smtp.start(helo_domain, account, password, authtype) do |smtp|
- # smtp.send_message msgstr, 'from@example.com', ['dest@example.com']
- # end
- #
- # The primary use of this method (as opposed to SMTP.start)
- # is probably to set debugging (#set_debug_output) or ESMTP
- # (#esmtp=), which must be done before the session is
- # started.
- #
- # === Errors
- #
- # If session has already been started, an IOError will be raised.
- #
- # This method may raise:
- #
- # * Net::SMTPAuthenticationError
- # * Net::SMTPServerBusy
- # * Net::SMTPSyntaxError
- # * Net::SMTPFatalError
- # * Net::SMTPUnknownError
- # * Net::OpenTimeout
- # * Net::ReadTimeout
- # * IOError
- #
- def start(helo = 'localhost',
- user = nil, secret = nil, authtype = nil) # :yield: smtp
- if block_given?
- begin
- do_start helo, user, secret, authtype
- return yield(self)
- ensure
- do_finish
- end
- else
- do_start helo, user, secret, authtype
- return self
- end
- end
-
- # Finishes the SMTP session and closes TCP connection.
- # Raises IOError if not started.
- def finish
- raise IOError, 'not yet started' unless started?
- do_finish
- end
-
- private
-
- def tcp_socket(address, port)
- TCPSocket.open address, port
- end
-
- def do_start(helo_domain, user, secret, authtype)
- raise IOError, 'SMTP session already started' if @started
- if user or secret
- check_auth_method(authtype || DEFAULT_AUTH_TYPE)
- check_auth_args user, secret
- end
- s = Timeout.timeout(@open_timeout, Net::OpenTimeout) do
- tcp_socket(@address, @port)
- end
- logging "Connection opened: #{@address}:#{@port}"
- @socket = new_internet_message_io(tls? ? tlsconnect(s) : s)
- check_response critical { recv_response() }
- do_helo helo_domain
- if starttls_always? or (capable_starttls? and starttls_auto?)
- unless capable_starttls?
- raise SMTPUnsupportedCommand,
- "STARTTLS is not supported on this server"
- end
- starttls
- @socket = new_internet_message_io(tlsconnect(s))
- # helo response may be different after STARTTLS
- do_helo helo_domain
- end
- authenticate user, secret, (authtype || DEFAULT_AUTH_TYPE) if user
- @started = true
- ensure
- unless @started
- # authentication failed, cancel connection.
- s.close if s and not s.closed?
- @socket = nil
- end
- end
-
- def ssl_socket(socket, context)
- OpenSSL::SSL::SSLSocket.new socket, context
- end
-
- def tlsconnect(s)
- verified = false
- s = ssl_socket(s, @ssl_context)
- logging "TLS connection started"
- s.sync_close = true
- s.connect
- if @ssl_context.verify_mode != OpenSSL::SSL::VERIFY_NONE
- s.post_connection_check(@address)
- end
- verified = true
- s
- ensure
- s.close unless verified
- end
-
- def new_internet_message_io(s)
- io = InternetMessageIO.new(s)
- io.read_timeout = @read_timeout
- io.debug_output = @debug_output
- io
- end
-
- def do_helo(helo_domain)
- res = @esmtp ? ehlo(helo_domain) : helo(helo_domain)
- @capabilities = res.capabilities
- rescue SMTPError
- if @esmtp
- @esmtp = false
- @error_occurred = false
- retry
- end
- raise
- end
-
- def do_finish
- quit if @socket and not @socket.closed? and not @error_occurred
- ensure
- @started = false
- @error_occurred = false
- @socket.close if @socket and not @socket.closed?
- @socket = nil
- end
-
- #
- # Message Sending
- #
-
- public
-
- #
- # Sends +msgstr+ as a message. Single CR ("\r") and LF ("\n") found
- # in the +msgstr+, are converted into the CR LF pair. You cannot send a
- # binary message with this method. +msgstr+ should include both
- # the message headers and body.
- #
- # +from_addr+ is a String representing the source mail address.
- #
- # +to_addr+ is a String or Strings or Array of Strings, representing
- # the destination mail address or addresses.
- #
- # === Example
- #
- # Net::SMTP.start('smtp.example.com') do |smtp|
- # smtp.send_message msgstr,
- # 'from@example.com',
- # ['dest@example.com', 'dest2@example.com']
- # end
- #
- # === Errors
- #
- # This method may raise:
- #
- # * Net::SMTPServerBusy
- # * Net::SMTPSyntaxError
- # * Net::SMTPFatalError
- # * Net::SMTPUnknownError
- # * Net::ReadTimeout
- # * IOError
- #
- def send_message(msgstr, from_addr, *to_addrs)
- raise IOError, 'closed session' unless @socket
- mailfrom from_addr
- rcptto_list(to_addrs) {data msgstr}
- end
-
- alias send_mail send_message
- alias sendmail send_message # obsolete
-
- #
- # Opens a message writer stream and gives it to the block.
- # The stream is valid only in the block, and has these methods:
- #
- # puts(str = ''):: outputs STR and CR LF.
- # print(str):: outputs STR.
- # printf(fmt, *args):: outputs sprintf(fmt,*args).
- # write(str):: outputs STR and returns the length of written bytes.
- # <<(str):: outputs STR and returns self.
- #
- # If a single CR ("\r") or LF ("\n") is found in the message,
- # it is converted to the CR LF pair. You cannot send a binary
- # message with this method.
- #
- # === Parameters
- #
- # +from_addr+ is a String representing the source mail address.
- #
- # +to_addr+ is a String or Strings or Array of Strings, representing
- # the destination mail address or addresses.
- #
- # === Example
- #
- # Net::SMTP.start('smtp.example.com', 25) do |smtp|
- # smtp.open_message_stream('from@example.com', ['dest@example.com']) do |f|
- # f.puts 'From: from@example.com'
- # f.puts 'To: dest@example.com'
- # f.puts 'Subject: test message'
- # f.puts
- # f.puts 'This is a test message.'
- # end
- # end
- #
- # === Errors
- #
- # This method may raise:
- #
- # * Net::SMTPServerBusy
- # * Net::SMTPSyntaxError
- # * Net::SMTPFatalError
- # * Net::SMTPUnknownError
- # * Net::ReadTimeout
- # * IOError
- #
- def open_message_stream(from_addr, *to_addrs, &block) # :yield: stream
- raise IOError, 'closed session' unless @socket
- mailfrom from_addr
- rcptto_list(to_addrs) {data(&block)}
- end
-
- alias ready open_message_stream # obsolete
-
- #
- # Authentication
- #
-
- public
-
- DEFAULT_AUTH_TYPE = :plain
-
- def authenticate(user, secret, authtype = DEFAULT_AUTH_TYPE)
- check_auth_method authtype
- check_auth_args user, secret
- send auth_method(authtype), user, secret
- end
-
- def auth_plain(user, secret)
- check_auth_args user, secret
- res = critical {
- get_response('AUTH PLAIN ' + base64_encode("\0#{user}\0#{secret}"))
- }
- check_auth_response res
- res
- end
-
- def auth_login(user, secret)
- check_auth_args user, secret
- res = critical {
- check_auth_continue get_response('AUTH LOGIN')
- check_auth_continue get_response(base64_encode(user))
- get_response(base64_encode(secret))
- }
- check_auth_response res
- res
- end
-
- def auth_cram_md5(user, secret)
- check_auth_args user, secret
- res = critical {
- res0 = get_response('AUTH CRAM-MD5')
- check_auth_continue res0
- crammed = cram_md5_response(secret, res0.cram_md5_challenge)
- get_response(base64_encode("#{user} #{crammed}"))
- }
- check_auth_response res
- res
- end
-
- private
-
- def check_auth_method(type)
- unless respond_to?(auth_method(type), true)
- raise ArgumentError, "wrong authentication type #{type}"
- end
- end
-
- def auth_method(type)
- "auth_#{type.to_s.downcase}".intern
- end
-
- def check_auth_args(user, secret, authtype = DEFAULT_AUTH_TYPE)
- unless user
- raise ArgumentError, 'SMTP-AUTH requested but missing user name'
- end
- unless secret
- raise ArgumentError, 'SMTP-AUTH requested but missing secret phrase'
- end
- end
-
- def base64_encode(str)
- # expects "str" may not become too long
- [str].pack('m').gsub(/\s+/, '')
- end
-
- IMASK = 0x36
- OMASK = 0x5c
-
- # CRAM-MD5: [RFC2195]
- def cram_md5_response(secret, challenge)
- tmp = Digest::MD5.digest(cram_secret(secret, IMASK) + challenge)
- Digest::MD5.hexdigest(cram_secret(secret, OMASK) + tmp)
- end
-
- CRAM_BUFSIZE = 64
-
- def cram_secret(secret, mask)
- secret = Digest::MD5.digest(secret) if secret.size > CRAM_BUFSIZE
- buf = secret.ljust(CRAM_BUFSIZE, "\0")
- 0.upto(buf.size - 1) do |i|
- buf[i] = (buf[i].ord ^ mask).chr
- end
- buf
- end
-
- #
- # SMTP command dispatcher
- #
-
- public
-
- # Aborts the current mail transaction
-
- def rset
- getok('RSET')
- end
-
- def starttls
- getok('STARTTLS')
- end
-
- def helo(domain)
- getok("HELO #{domain}")
- end
-
- def ehlo(domain)
- getok("EHLO #{domain}")
- end
-
- def mailfrom(from_addr)
- if $SAFE > 0
- raise SecurityError, 'tainted from_addr' if from_addr.tainted?
- end
- getok("MAIL FROM:<#{from_addr}>")
- end
-
- def rcptto_list(to_addrs)
- raise ArgumentError, 'mail destination not given' if to_addrs.empty?
- ok_users = []
- unknown_users = []
- to_addrs.flatten.each do |addr|
- begin
- rcptto addr
- rescue SMTPAuthenticationError
- unknown_users << addr.dump
- else
- ok_users << addr
- end
- end
- raise ArgumentError, 'mail destination not given' if ok_users.empty?
- ret = yield
- unless unknown_users.empty?
- raise SMTPAuthenticationError, "failed to deliver for #{unknown_users.join(', ')}"
- end
- ret
- end
-
- def rcptto(to_addr)
- if $SAFE > 0
- raise SecurityError, 'tainted to_addr' if to_addr.tainted?
- end
- getok("RCPT TO:<#{to_addr}>")
- end
-
- # This method sends a message.
- # If +msgstr+ is given, sends it as a message.
- # If block is given, yield a message writer stream.
- # You must write message before the block is closed.
- #
- # # Example 1 (by string)
- # smtp.data(<
-# Documentation:: William Webber and Wakou Aoyama
-#
-# This file holds the class Net::Telnet, which provides client-side
-# telnet functionality.
-#
-# For documentation, see Net::Telnet.
-#
-
-require "net/protocol"
-require "English"
-
-module Net
-
- #
- # == Net::Telnet
- #
- # Provides telnet client functionality.
- #
- # This class also has, through delegation, all the methods of a
- # socket object (by default, a +TCPSocket+, but can be set by the
- # +Proxy+ option to new()). This provides methods such as
- # close() to end the session and sysread() to read
- # data directly from the host, instead of via the waitfor()
- # mechanism. Note that if you do use sysread() directly
- # when in telnet mode, you should probably pass the output through
- # preprocess() to extract telnet command sequences.
- #
- # == Overview
- #
- # The telnet protocol allows a client to login remotely to a user
- # account on a server and execute commands via a shell. The equivalent
- # is done by creating a Net::Telnet class with the +Host+ option
- # set to your host, calling #login() with your user and password,
- # issuing one or more #cmd() calls, and then calling #close()
- # to end the session. The #waitfor(), #print(), #puts(), and
- # #write() methods, which #cmd() is implemented on top of, are
- # only needed if you are doing something more complicated.
- #
- # A Net::Telnet object can also be used to connect to non-telnet
- # services, such as SMTP or HTTP. In this case, you normally
- # want to provide the +Port+ option to specify the port to
- # connect to, and set the +Telnetmode+ option to false to prevent
- # the client from attempting to interpret telnet command sequences.
- # Generally, #login() will not work with other protocols, and you
- # have to handle authentication yourself.
- #
- # For some protocols, it will be possible to specify the +Prompt+
- # option once when you create the Telnet object and use #cmd() calls;
- # for others, you will have to specify the response sequence to
- # look for as the Match option to every #cmd() call, or call
- # #puts() and #waitfor() directly; for yet others, you will have
- # to use #sysread() instead of #waitfor() and parse server
- # responses yourself.
- #
- # It is worth noting that when you create a new Net::Telnet object,
- # you can supply a proxy IO channel via the Proxy option. This
- # can be used to attach the Telnet object to other Telnet objects,
- # to already open sockets, or to any read-write IO object. This
- # can be useful, for instance, for setting up a test fixture for
- # unit testing.
- #
- # == Examples
- #
- # === Log in and send a command, echoing all output to stdout
- #
- # localhost = Net::Telnet::new("Host" => "localhost",
- # "Timeout" => 10,
- # "Prompt" => /[$%#>] \z/n)
- # localhost.login("username", "password") { |c| print c }
- # localhost.cmd("command") { |c| print c }
- # localhost.close
- #
- #
- # === Check a POP server to see if you have mail
- #
- # pop = Net::Telnet::new("Host" => "your_destination_host_here",
- # "Port" => 110,
- # "Telnetmode" => false,
- # "Prompt" => /^\+OK/n)
- # pop.cmd("user " + "your_username_here") { |c| print c }
- # pop.cmd("pass " + "your_password_here") { |c| print c }
- # pop.cmd("list") { |c| print c }
- #
- # == References
- #
- # There are a large number of RFCs relevant to the Telnet protocol.
- # RFCs 854-861 define the base protocol. For a complete listing
- # of relevant RFCs, see
- # http://www.omnifarious.org/~hopper/technical/telnet-rfc.html
- #
- class Telnet
-
- # :stopdoc:
- IAC = 255.chr # "\377" # "\xff" # interpret as command
- DONT = 254.chr # "\376" # "\xfe" # you are not to use option
- DO = 253.chr # "\375" # "\xfd" # please, you use option
- WONT = 252.chr # "\374" # "\xfc" # I won't use option
- WILL = 251.chr # "\373" # "\xfb" # I will use option
- SB = 250.chr # "\372" # "\xfa" # interpret as subnegotiation
- GA = 249.chr # "\371" # "\xf9" # you may reverse the line
- EL = 248.chr # "\370" # "\xf8" # erase the current line
- EC = 247.chr # "\367" # "\xf7" # erase the current character
- AYT = 246.chr # "\366" # "\xf6" # are you there
- AO = 245.chr # "\365" # "\xf5" # abort output--but let prog finish
- IP = 244.chr # "\364" # "\xf4" # interrupt process--permanently
- BREAK = 243.chr # "\363" # "\xf3" # break
- DM = 242.chr # "\362" # "\xf2" # data mark--for connect. cleaning
- NOP = 241.chr # "\361" # "\xf1" # nop
- SE = 240.chr # "\360" # "\xf0" # end sub negotiation
- EOR = 239.chr # "\357" # "\xef" # end of record (transparent mode)
- ABORT = 238.chr # "\356" # "\xee" # Abort process
- SUSP = 237.chr # "\355" # "\xed" # Suspend process
- EOF = 236.chr # "\354" # "\xec" # End of file
- SYNCH = 242.chr # "\362" # "\xf2" # for telfunc calls
-
- OPT_BINARY = 0.chr # "\000" # "\x00" # Binary Transmission
- OPT_ECHO = 1.chr # "\001" # "\x01" # Echo
- OPT_RCP = 2.chr # "\002" # "\x02" # Reconnection
- OPT_SGA = 3.chr # "\003" # "\x03" # Suppress Go Ahead
- OPT_NAMS = 4.chr # "\004" # "\x04" # Approx Message Size Negotiation
- OPT_STATUS = 5.chr # "\005" # "\x05" # Status
- OPT_TM = 6.chr # "\006" # "\x06" # Timing Mark
- OPT_RCTE = 7.chr # "\a" # "\x07" # Remote Controlled Trans and Echo
- OPT_NAOL = 8.chr # "\010" # "\x08" # Output Line Width
- OPT_NAOP = 9.chr # "\t" # "\x09" # Output Page Size
- OPT_NAOCRD = 10.chr # "\n" # "\x0a" # Output Carriage-Return Disposition
- OPT_NAOHTS = 11.chr # "\v" # "\x0b" # Output Horizontal Tab Stops
- OPT_NAOHTD = 12.chr # "\f" # "\x0c" # Output Horizontal Tab Disposition
- OPT_NAOFFD = 13.chr # "\r" # "\x0d" # Output Formfeed Disposition
- OPT_NAOVTS = 14.chr # "\016" # "\x0e" # Output Vertical Tabstops
- OPT_NAOVTD = 15.chr # "\017" # "\x0f" # Output Vertical Tab Disposition
- OPT_NAOLFD = 16.chr # "\020" # "\x10" # Output Linefeed Disposition
- OPT_XASCII = 17.chr # "\021" # "\x11" # Extended ASCII
- OPT_LOGOUT = 18.chr # "\022" # "\x12" # Logout
- OPT_BM = 19.chr # "\023" # "\x13" # Byte Macro
- OPT_DET = 20.chr # "\024" # "\x14" # Data Entry Terminal
- OPT_SUPDUP = 21.chr # "\025" # "\x15" # SUPDUP
- OPT_SUPDUPOUTPUT = 22.chr # "\026" # "\x16" # SUPDUP Output
- OPT_SNDLOC = 23.chr # "\027" # "\x17" # Send Location
- OPT_TTYPE = 24.chr # "\030" # "\x18" # Terminal Type
- OPT_EOR = 25.chr # "\031" # "\x19" # End of Record
- OPT_TUID = 26.chr # "\032" # "\x1a" # TACACS User Identification
- OPT_OUTMRK = 27.chr # "\e" # "\x1b" # Output Marking
- OPT_TTYLOC = 28.chr # "\034" # "\x1c" # Terminal Location Number
- OPT_3270REGIME = 29.chr # "\035" # "\x1d" # Telnet 3270 Regime
- OPT_X3PAD = 30.chr # "\036" # "\x1e" # X.3 PAD
- OPT_NAWS = 31.chr # "\037" # "\x1f" # Negotiate About Window Size
- OPT_TSPEED = 32.chr # " " # "\x20" # Terminal Speed
- OPT_LFLOW = 33.chr # "!" # "\x21" # Remote Flow Control
- OPT_LINEMODE = 34.chr # "\"" # "\x22" # Linemode
- OPT_XDISPLOC = 35.chr # "#" # "\x23" # X Display Location
- OPT_OLD_ENVIRON = 36.chr # "$" # "\x24" # Environment Option
- OPT_AUTHENTICATION = 37.chr # "%" # "\x25" # Authentication Option
- OPT_ENCRYPT = 38.chr # "&" # "\x26" # Encryption Option
- OPT_NEW_ENVIRON = 39.chr # "'" # "\x27" # New Environment Option
- OPT_EXOPL = 255.chr # "\377" # "\xff" # Extended-Options-List
-
- NULL = "\000"
- CR = "\015"
- LF = "\012"
- EOL = CR + LF
- REVISION = '$Id: telnet.rb 47298 2014-08-27 12:10:21Z hsbt $'
- # :startdoc:
-
- #
- # Creates a new Net::Telnet object.
- #
- # Attempts to connect to the host (unless the Proxy option is
- # provided: see below). If a block is provided, it is yielded
- # status messages on the attempt to connect to the server, of
- # the form:
- #
- # Trying localhost...
- # Connected to localhost.
- #
- # +options+ is a hash of options. The following example lists
- # all options and their default values.
- #
- # host = Net::Telnet::new(
- # "Host" => "localhost", # default: "localhost"
- # "Port" => 23, # default: 23
- # "Binmode" => false, # default: false
- # "Output_log" => "output_log", # default: nil (no output)
- # "Dump_log" => "dump_log", # default: nil (no output)
- # "Prompt" => /[$%#>] \z/n, # default: /[$%#>] \z/n
- # "Telnetmode" => true, # default: true
- # "Timeout" => 10, # default: 10
- # # if ignore timeout then set "Timeout" to false.
- # "Waittime" => 0, # default: 0
- # "Proxy" => proxy # default: nil
- # # proxy is Net::Telnet or IO object
- # )
- #
- # The options have the following meanings:
- #
- # Host:: the hostname or IP address of the host to connect to, as a String.
- # Defaults to "localhost".
- #
- # Port:: the port to connect to. Defaults to 23.
- #
- # Binmode:: if false (the default), newline substitution is performed.
- # Outgoing LF is
- # converted to CRLF, and incoming CRLF is converted to LF. If
- # true, this substitution is not performed. This value can
- # also be set with the #binmode() method. The
- # outgoing conversion only applies to the #puts() and #print()
- # methods, not the #write() method. The precise nature of
- # the newline conversion is also affected by the telnet options
- # SGA and BIN.
- #
- # Output_log:: the name of the file to write connection status messages
- # and all received traffic to. In the case of a proper
- # Telnet session, this will include the client input as
- # echoed by the host; otherwise, it only includes server
- # responses. Output is appended verbatim to this file.
- # By default, no output log is kept.
- #
- # Dump_log:: as for Output_log, except that output is written in hexdump
- # format (16 bytes per line as hex pairs, followed by their
- # printable equivalent), with connection status messages
- # preceded by '#', sent traffic preceded by '>', and
- # received traffic preceded by '<'. By default, not dump log
- # is kept.
- #
- # Prompt:: a regular expression matching the host's command-line prompt
- # sequence. This is needed by the Telnet class to determine
- # when the output from a command has finished and the host is
- # ready to receive a new command. By default, this regular
- # expression is /[$%#>] \z/n.
- #
- # Telnetmode:: a boolean value, true by default. In telnet mode,
- # traffic received from the host is parsed for special
- # command sequences, and these sequences are escaped
- # in outgoing traffic sent using #puts() or #print()
- # (but not #write()). If you are using the Net::Telnet
- # object to connect to a non-telnet service (such as
- # SMTP or POP), this should be set to "false" to prevent
- # undesired data corruption. This value can also be set
- # by the #telnetmode() method.
- #
- # Timeout:: the number of seconds to wait before timing out both the
- # initial attempt to connect to host (in this constructor),
- # which raises a Net::OpenTimeout, and all attempts to read data
- # from the host, which raises a Net::ReadTimeout (in #waitfor(),
- # #cmd(), and #login()). The default value is 10 seconds.
- # You can disable the timeout by setting this value to false.
- # In this case, the connect attempt will eventually timeout
- # on the underlying connect(2) socket call with an
- # Errno::ETIMEDOUT error (but generally only after a few
- # minutes), but other attempts to read data from the host
- # will hang indefinitely if no data is forthcoming.
- #
- # Waittime:: the amount of time to wait after seeing what looks like a
- # prompt (that is, received data that matches the Prompt
- # option regular expression) to see if more data arrives.
- # If more data does arrive in this time, Net::Telnet assumes
- # that what it saw was not really a prompt. This is to try to
- # avoid false matches, but it can also lead to missing real
- # prompts (if, for instance, a background process writes to
- # the terminal soon after the prompt is displayed). By
- # default, set to 0, meaning not to wait for more data.
- #
- # Proxy:: a proxy object to used instead of opening a direct connection
- # to the host. Must be either another Net::Telnet object or
- # an IO object. If it is another Net::Telnet object, this
- # instance will use that one's socket for communication. If an
- # IO object, it is used directly for communication. Any other
- # kind of object will cause an error to be raised.
- #
- def initialize(options) # :yield: mesg
- @options = options
- @options["Host"] = "localhost" unless @options.has_key?("Host")
- @options["Port"] = 23 unless @options.has_key?("Port")
- @options["Prompt"] = /[$%#>] \z/n unless @options.has_key?("Prompt")
- @options["Timeout"] = 10 unless @options.has_key?("Timeout")
- @options["Waittime"] = 0 unless @options.has_key?("Waittime")
- unless @options.has_key?("Binmode")
- @options["Binmode"] = false
- else
- unless (true == @options["Binmode"] or false == @options["Binmode"])
- raise ArgumentError, "Binmode option must be true or false"
- end
- end
-
- unless @options.has_key?("Telnetmode")
- @options["Telnetmode"] = true
- else
- unless (true == @options["Telnetmode"] or false == @options["Telnetmode"])
- raise ArgumentError, "Telnetmode option must be true or false"
- end
- end
-
- @telnet_option = { "SGA" => false, "BINARY" => false }
-
- if @options.has_key?("Output_log")
- @log = File.open(@options["Output_log"], 'a+')
- @log.sync = true
- @log.binmode
- end
-
- if @options.has_key?("Dump_log")
- @dumplog = File.open(@options["Dump_log"], 'a+')
- @dumplog.sync = true
- @dumplog.binmode
- def @dumplog.log_dump(dir, x) # :nodoc:
- len = x.length
- addr = 0
- offset = 0
- while 0 < len
- if len < 16
- line = x[offset, len]
- else
- line = x[offset, 16]
- end
- hexvals = line.unpack('H*')[0]
- hexvals += ' ' * (32 - hexvals.length)
- hexvals = format("%s %s %s %s " * 4, *hexvals.unpack('a2' * 16))
- line = line.gsub(/[\000-\037\177-\377]/n, '.')
- printf "%s 0x%5.5x: %s%s\n", dir, addr, hexvals, line
- addr += 16
- offset += 16
- len -= 16
- end
- print "\n"
- end
- end
-
- if @options.has_key?("Proxy")
- if @options["Proxy"].kind_of?(Net::Telnet)
- @sock = @options["Proxy"].sock
- elsif @options["Proxy"].kind_of?(IO)
- @sock = @options["Proxy"]
- else
- raise "Error: Proxy must be an instance of Net::Telnet or IO."
- end
- else
- message = "Trying " + @options["Host"] + "...\n"
- yield(message) if block_given?
- @log.write(message) if @options.has_key?("Output_log")
- @dumplog.log_dump('#', message) if @options.has_key?("Dump_log")
-
- begin
- if @options["Timeout"] == false
- @sock = TCPSocket.open(@options["Host"], @options["Port"])
- else
- Timeout.timeout(@options["Timeout"], Net::OpenTimeout) do
- @sock = TCPSocket.open(@options["Host"], @options["Port"])
- end
- end
- rescue Net::OpenTimeout
- raise Net::OpenTimeout, "timed out while opening a connection to the host"
- rescue
- @log.write($ERROR_INFO.to_s + "\n") if @options.has_key?("Output_log")
- @dumplog.log_dump('#', $ERROR_INFO.to_s + "\n") if @options.has_key?("Dump_log")
- raise
- end
- @sock.sync = true
- @sock.binmode
-
- message = "Connected to " + @options["Host"] + ".\n"
- yield(message) if block_given?
- @log.write(message) if @options.has_key?("Output_log")
- @dumplog.log_dump('#', message) if @options.has_key?("Dump_log")
- end
-
- end # initialize
-
- # The socket the Telnet object is using. Note that this object becomes
- # a delegate of the Telnet object, so normally you invoke its methods
- # directly on the Telnet object.
- attr_reader :sock
-
- # Set telnet command interpretation on (+mode+ == true) or off
- # (+mode+ == false), or return the current value (+mode+ not
- # provided). It should be on for true telnet sessions, off if
- # using Net::Telnet to connect to a non-telnet service such
- # as SMTP.
- def telnetmode(mode = nil)
- case mode
- when nil
- @options["Telnetmode"]
- when true, false
- @options["Telnetmode"] = mode
- else
- raise ArgumentError, "argument must be true or false, or missing"
- end
- end
-
- # Turn telnet command interpretation on (true) or off (false). It
- # should be on for true telnet sessions, off if using Net::Telnet
- # to connect to a non-telnet service such as SMTP.
- def telnetmode=(mode)
- if (true == mode or false == mode)
- @options["Telnetmode"] = mode
- else
- raise ArgumentError, "argument must be true or false"
- end
- end
-
- # Turn newline conversion on (+mode+ == false) or off (+mode+ == true),
- # or return the current value (+mode+ is not specified).
- def binmode(mode = nil)
- case mode
- when nil
- @options["Binmode"]
- when true, false
- @options["Binmode"] = mode
- else
- raise ArgumentError, "argument must be true or false"
- end
- end
-
- # Turn newline conversion on (false) or off (true).
- def binmode=(mode)
- if (true == mode or false == mode)
- @options["Binmode"] = mode
- else
- raise ArgumentError, "argument must be true or false"
- end
- end
-
- # Preprocess received data from the host.
- #
- # Performs newline conversion and detects telnet command sequences.
- # Called automatically by #waitfor(). You should only use this
- # method yourself if you have read input directly using sysread()
- # or similar, and even then only if in telnet mode.
- def preprocess(string)
- # combine CR+NULL into CR
- string = string.gsub(/#{CR}#{NULL}/no, CR) if @options["Telnetmode"]
-
- # combine EOL into "\n"
- string = string.gsub(/#{EOL}/no, "\n") unless @options["Binmode"]
-
- # remove NULL
- string = string.gsub(/#{NULL}/no, '') unless @options["Binmode"]
-
- string.gsub(/#{IAC}(
- [#{IAC}#{AO}#{AYT}#{DM}#{IP}#{NOP}]|
- [#{DO}#{DONT}#{WILL}#{WONT}]
- [#{OPT_BINARY}-#{OPT_NEW_ENVIRON}#{OPT_EXOPL}]|
- #{SB}[^#{IAC}]*#{IAC}#{SE}
- )/xno) do
- if IAC == $1 # handle escaped IAC characters
- IAC
- elsif AYT == $1 # respond to "IAC AYT" (are you there)
- self.write("nobody here but us pigeons" + EOL)
- ''
- elsif DO[0] == $1[0] # respond to "IAC DO x"
- if OPT_BINARY[0] == $1[1]
- @telnet_option["BINARY"] = true
- self.write(IAC + WILL + OPT_BINARY)
- else
- self.write(IAC + WONT + $1[1..1])
- end
- ''
- elsif DONT[0] == $1[0] # respond to "IAC DON'T x" with "IAC WON'T x"
- self.write(IAC + WONT + $1[1..1])
- ''
- elsif WILL[0] == $1[0] # respond to "IAC WILL x"
- if OPT_BINARY[0] == $1[1]
- self.write(IAC + DO + OPT_BINARY)
- elsif OPT_ECHO[0] == $1[1]
- self.write(IAC + DO + OPT_ECHO)
- elsif OPT_SGA[0] == $1[1]
- @telnet_option["SGA"] = true
- self.write(IAC + DO + OPT_SGA)
- else
- self.write(IAC + DONT + $1[1..1])
- end
- ''
- elsif WONT[0] == $1[0] # respond to "IAC WON'T x"
- if OPT_ECHO[0] == $1[1]
- self.write(IAC + DONT + OPT_ECHO)
- elsif OPT_SGA[0] == $1[1]
- @telnet_option["SGA"] = false
- self.write(IAC + DONT + OPT_SGA)
- else
- self.write(IAC + DONT + $1[1..1])
- end
- ''
- else
- ''
- end
- end
- end # preprocess
-
- # Read data from the host until a certain sequence is matched.
- #
- # If a block is given, the received data will be yielded as it
- # is read in (not necessarily all in one go), or nil if EOF
- # occurs before any data is received. Whether a block is given
- # or not, all data read will be returned in a single string, or again
- # nil if EOF occurs before any data is received. Note that
- # received data includes the matched sequence we were looking for.
- #
- # +options+ can be either a regular expression or a hash of options.
- # If a regular expression, this specifies the data to wait for.
- # If a hash, this can specify the following options:
- #
- # Match:: a regular expression, specifying the data to wait for.
- # Prompt:: as for Match; used only if Match is not specified.
- # String:: as for Match, except a string that will be converted
- # into a regular expression. Used only if Match and
- # Prompt are not specified.
- # Timeout:: the number of seconds to wait for data from the host
- # before raising a Timeout::Error. If set to false,
- # no timeout will occur. If not specified, the
- # Timeout option value specified when this instance
- # was created will be used, or, failing that, the
- # default value of 10 seconds.
- # Waittime:: the number of seconds to wait after matching against
- # the input data to see if more data arrives. If more
- # data arrives within this time, we will judge ourselves
- # not to have matched successfully, and will continue
- # trying to match. If not specified, the Waittime option
- # value specified when this instance was created will be
- # used, or, failing that, the default value of 0 seconds,
- # which means not to wait for more input.
- # FailEOF:: if true, when the remote end closes the connection then an
- # EOFError will be raised. Otherwise, defaults to the old
- # behaviour that the function will return whatever data
- # has been received already, or nil if nothing was received.
- #
- def waitfor(options) # :yield: recvdata
- time_out = @options["Timeout"]
- waittime = @options["Waittime"]
- fail_eof = @options["FailEOF"]
-
- if options.kind_of?(Hash)
- prompt = if options.has_key?("Match")
- options["Match"]
- elsif options.has_key?("Prompt")
- options["Prompt"]
- elsif options.has_key?("String")
- Regexp.new( Regexp.quote(options["String"]) )
- end
- time_out = options["Timeout"] if options.has_key?("Timeout")
- waittime = options["Waittime"] if options.has_key?("Waittime")
- fail_eof = options["FailEOF"] if options.has_key?("FailEOF")
- else
- prompt = options
- end
-
- if time_out == false
- time_out = nil
- end
-
- line = ''
- buf = ''
- rest = ''
- until(prompt === line and not IO::select([@sock], nil, nil, waittime))
- unless IO::select([@sock], nil, nil, time_out)
- raise Net::ReadTimeout, "timed out while waiting for more data"
- end
- begin
- c = @sock.readpartial(1024 * 1024)
- @dumplog.log_dump('<', c) if @options.has_key?("Dump_log")
- if @options["Telnetmode"]
- c = rest + c
- if Integer(c.rindex(/#{IAC}#{SE}/no) || 0) <
- Integer(c.rindex(/#{IAC}#{SB}/no) || 0)
- buf = preprocess(c[0 ... c.rindex(/#{IAC}#{SB}/no)])
- rest = c[c.rindex(/#{IAC}#{SB}/no) .. -1]
- elsif pt = c.rindex(/#{IAC}[^#{IAC}#{AO}#{AYT}#{DM}#{IP}#{NOP}]?\z/no) ||
- c.rindex(/\r\z/no)
- buf = preprocess(c[0 ... pt])
- rest = c[pt .. -1]
- else
- buf = preprocess(c)
- rest = ''
- end
- else
- # Not Telnetmode.
- #
- # We cannot use preprocess() on this data, because that
- # method makes some Telnetmode-specific assumptions.
- buf = rest + c
- rest = ''
- unless @options["Binmode"]
- if pt = buf.rindex(/\r\z/no)
- buf = buf[0 ... pt]
- rest = buf[pt .. -1]
- end
- buf.gsub!(/#{EOL}/no, "\n")
- end
- end
- @log.print(buf) if @options.has_key?("Output_log")
- line += buf
- yield buf if block_given?
- rescue EOFError # End of file reached
- raise if fail_eof
- if line == ''
- line = nil
- yield nil if block_given?
- end
- break
- end
- end
- line
- end
-
- # Write +string+ to the host.
- #
- # Does not perform any conversions on +string+. Will log +string+ to the
- # dumplog, if the Dump_log option is set.
- def write(string)
- length = string.length
- while 0 < length
- IO::select(nil, [@sock])
- @dumplog.log_dump('>', string[-length..-1]) if @options.has_key?("Dump_log")
- length -= @sock.syswrite(string[-length..-1])
- end
- end
-
- # Sends a string to the host.
- #
- # This does _not_ automatically append a newline to the string. Embedded
- # newlines may be converted and telnet command sequences escaped
- # depending upon the values of telnetmode, binmode, and telnet options
- # set by the host.
- def print(string)
- string = string.gsub(/#{IAC}/no, IAC + IAC) if @options["Telnetmode"]
-
- if @options["Binmode"]
- self.write(string)
- else
- if @telnet_option["BINARY"] and @telnet_option["SGA"]
- # IAC WILL SGA IAC DO BIN send EOL --> CR
- self.write(string.gsub(/\n/n, CR))
- elsif @telnet_option["SGA"]
- # IAC WILL SGA send EOL --> CR+NULL
- self.write(string.gsub(/\n/n, CR + NULL))
- else
- # NONE send EOL --> CR+LF
- self.write(string.gsub(/\n/n, EOL))
- end
- end
- end
-
- # Sends a string to the host.
- #
- # Same as #print(), but appends a newline to the string.
- def puts(string)
- self.print(string + "\n")
- end
-
- # Send a command to the host.
- #
- # More exactly, sends a string to the host, and reads in all received
- # data until is sees the prompt or other matched sequence.
- #
- # If a block is given, the received data will be yielded to it as
- # it is read in. Whether a block is given or not, the received data
- # will be return as a string. Note that the received data includes
- # the prompt and in most cases the host's echo of our command.
- #
- # +options+ is either a String, specified the string or command to
- # send to the host; or it is a hash of options. If a hash, the
- # following options can be specified:
- #
- # String:: the command or other string to send to the host.
- # Match:: a regular expression, the sequence to look for in
- # the received data before returning. If not specified,
- # the Prompt option value specified when this instance
- # was created will be used, or, failing that, the default
- # prompt of /[$%#>] \z/n.
- # Timeout:: the seconds to wait for data from the host before raising
- # a Timeout error. If not specified, the Timeout option
- # value specified when this instance was created will be
- # used, or, failing that, the default value of 10 seconds.
- #
- # The command or other string will have the newline sequence appended
- # to it.
- def cmd(options) # :yield: recvdata
- match = @options["Prompt"]
- time_out = @options["Timeout"]
- fail_eof = @options["FailEOF"]
-
- if options.kind_of?(Hash)
- string = options["String"]
- match = options["Match"] if options.has_key?("Match")
- time_out = options["Timeout"] if options.has_key?("Timeout")
- fail_eof = options["FailEOF"] if options.has_key?("FailEOF")
- else
- string = options
- end
-
- self.puts(string)
- if block_given?
- waitfor({"Prompt" => match, "Timeout" => time_out, "FailEOF" => fail_eof}){|c| yield c }
- else
- waitfor({"Prompt" => match, "Timeout" => time_out, "FailEOF" => fail_eof})
- end
- end
-
- # Login to the host with a given username and password.
- #
- # The username and password can either be provided as two string
- # arguments in that order, or as a hash with keys "Name" and
- # "Password".
- #
- # This method looks for the strings "login" and "Password" from the
- # host to determine when to send the username and password. If the
- # login sequence does not follow this pattern (for instance, you
- # are connecting to a service other than telnet), you will need
- # to handle login yourself.
- #
- # The password can be omitted, either by only
- # provided one String argument, which will be used as the username,
- # or by providing a has that has no "Password" key. In this case,
- # the method will not look for the "Password:" prompt; if it is
- # sent, it will have to be dealt with by later calls.
- #
- # The method returns all data received during the login process from
- # the host, including the echoed username but not the password (which
- # the host should not echo). If a block is passed in, this received
- # data is also yielded to the block as it is received.
- def login(options, password = nil) # :yield: recvdata
- login_prompt = /[Ll]ogin[: ]*\z/n
- password_prompt = /[Pp]ass(?:word|phrase)[: ]*\z/n
- if options.kind_of?(Hash)
- username = options["Name"]
- password = options["Password"]
- login_prompt = options["LoginPrompt"] if options["LoginPrompt"]
- password_prompt = options["PasswordPrompt"] if options["PasswordPrompt"]
- else
- username = options
- end
-
- if block_given?
- line = waitfor(login_prompt){|c| yield c }
- if password
- line += cmd({"String" => username,
- "Match" => password_prompt}){|c| yield c }
- line += cmd(password){|c| yield c }
- else
- line += cmd(username){|c| yield c }
- end
- else
- line = waitfor(login_prompt)
- if password
- line += cmd({"String" => username,
- "Match" => password_prompt})
- line += cmd(password)
- else
- line += cmd(username)
- end
- end
- line
- end
-
- # Closes the connection
- def close
- @sock.close
- end
-
- end # class Telnet
-end # module Net
-
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/observer.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/observer.rb
deleted file mode 100755
index 10f2eb0db..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/observer.rb
+++ /dev/null
@@ -1,203 +0,0 @@
-#
-# Implementation of the _Observer_ object-oriented design pattern. The
-# following documentation is copied, with modifications, from "Programming
-# Ruby", by Hunt and Thomas; http://www.ruby-doc.org/docs/ProgrammingRuby/html/lib_patterns.html.
-#
-# See Observable for more info.
-
-# The Observer pattern (also known as publish/subscribe) provides a simple
-# mechanism for one object to inform a set of interested third-party objects
-# when its state changes.
-#
-# == Mechanism
-#
-# The notifying class mixes in the +Observable+
-# module, which provides the methods for managing the associated observer
-# objects.
-#
-# The observable object must:
-# * assert that it has +#changed+
-# * call +#notify_observers+
-#
-# An observer subscribes to updates using Observable#add_observer, which also
-# specifies the method called via #notify_observers. The default method for
-# #notify_observers is #update.
-#
-# === Example
-#
-# The following example demonstrates this nicely. A +Ticker+, when run,
-# continually receives the stock +Price+ for its @symbol. A +Warner+
-# is a general observer of the price, and two warners are demonstrated, a
-# +WarnLow+ and a +WarnHigh+, which print a warning if the price is below or
-# above their set limits, respectively.
-#
-# The +update+ callback allows the warners to run without being explicitly
-# called. The system is set up with the +Ticker+ and several observers, and the
-# observers do their duty without the top-level code having to interfere.
-#
-# Note that the contract between publisher and subscriber (observable and
-# observer) is not declared or enforced. The +Ticker+ publishes a time and a
-# price, and the warners receive that. But if you don't ensure that your
-# contracts are correct, nothing else can warn you.
-#
-# require "observer"
-#
-# class Ticker ### Periodically fetch a stock price.
-# include Observable
-#
-# def initialize(symbol)
-# @symbol = symbol
-# end
-#
-# def run
-# last_price = nil
-# loop do
-# price = Price.fetch(@symbol)
-# print "Current price: #{price}\n"
-# if price != last_price
-# changed # notify observers
-# last_price = price
-# notify_observers(Time.now, price)
-# end
-# sleep 1
-# end
-# end
-# end
-#
-# class Price ### A mock class to fetch a stock price (60 - 140).
-# def self.fetch(symbol)
-# 60 + rand(80)
-# end
-# end
-#
-# class Warner ### An abstract observer of Ticker objects.
-# def initialize(ticker, limit)
-# @limit = limit
-# ticker.add_observer(self)
-# end
-# end
-#
-# class WarnLow < Warner
-# def update(time, price) # callback for observer
-# if price < @limit
-# print "--- #{time.to_s}: Price below #@limit: #{price}\n"
-# end
-# end
-# end
-#
-# class WarnHigh < Warner
-# def update(time, price) # callback for observer
-# if price > @limit
-# print "+++ #{time.to_s}: Price above #@limit: #{price}\n"
-# end
-# end
-# end
-#
-# ticker = Ticker.new("MSFT")
-# WarnLow.new(ticker, 80)
-# WarnHigh.new(ticker, 120)
-# ticker.run
-#
-# Produces:
-#
-# Current price: 83
-# Current price: 75
-# --- Sun Jun 09 00:10:25 CDT 2002: Price below 80: 75
-# Current price: 90
-# Current price: 134
-# +++ Sun Jun 09 00:10:25 CDT 2002: Price above 120: 134
-# Current price: 134
-# Current price: 112
-# Current price: 79
-# --- Sun Jun 09 00:10:25 CDT 2002: Price below 80: 79
-module Observable
-
- #
- # Add +observer+ as an observer on this object. so that it will receive
- # notifications.
- #
- # +observer+:: the object that will be notified of changes.
- # +func+:: Symbol naming the method that will be called when this Observable
- # has changes.
- #
- # This method must return true for +observer.respond_to?+ and will
- # receive *arg when #notify_observers is called, where
- # *arg is the value passed to #notify_observers by this
- # Observable
- def add_observer(observer, func=:update)
- @observer_peers = {} unless defined? @observer_peers
- unless observer.respond_to? func
- raise NoMethodError, "observer does not respond to `#{func}'"
- end
- @observer_peers[observer] = func
- end
-
- #
- # Remove +observer+ as an observer on this object so that it will no longer
- # receive notifications.
- #
- # +observer+:: An observer of this Observable
- def delete_observer(observer)
- @observer_peers.delete observer if defined? @observer_peers
- end
-
- #
- # Remove all observers associated with this object.
- #
- def delete_observers
- @observer_peers.clear if defined? @observer_peers
- end
-
- #
- # Return the number of observers associated with this object.
- #
- def count_observers
- if defined? @observer_peers
- @observer_peers.size
- else
- 0
- end
- end
-
- #
- # Set the changed state of this object. Notifications will be sent only if
- # the changed +state+ is +true+.
- #
- # +state+:: Boolean indicating the changed state of this Observable.
- #
- def changed(state=true)
- @observer_state = state
- end
-
- #
- # Returns true if this object's state has been changed since the last
- # #notify_observers call.
- #
- def changed?
- if defined? @observer_state and @observer_state
- true
- else
- false
- end
- end
-
- #
- # Notify observers of a change in state *if* this object's changed state is
- # +true+.
- #
- # This will invoke the method named in #add_observer, passing *arg.
- # The changed state is then set to +false+.
- #
- # *arg:: Any arguments to pass to the observers.
- def notify_observers(*arg)
- if defined? @observer_state and @observer_state
- if defined? @observer_peers
- @observer_peers.each do |k, v|
- k.send v, *arg
- end
- end
- @observer_state = false
- end
- end
-
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/open-uri.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/open-uri.rb
deleted file mode 100755
index e49a09b19..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/open-uri.rb
+++ /dev/null
@@ -1,801 +0,0 @@
-require 'uri'
-require 'stringio'
-require 'time'
-
-module Kernel
- private
- alias open_uri_original_open open # :nodoc:
- class << self
- alias open_uri_original_open open # :nodoc:
- end
-
- # Allows the opening of various resources including URIs.
- #
- # If the first argument responds to the 'open' method, 'open' is called on
- # it with the rest of the arguments.
- #
- # If the first argument is a string that begins with xxx://, it is parsed by
- # URI.parse. If the parsed object responds to the 'open' method,
- # 'open' is called on it with the rest of the arguments.
- #
- # Otherwise, the original Kernel#open is called.
- #
- # OpenURI::OpenRead#open provides URI::HTTP#open, URI::HTTPS#open and
- # URI::FTP#open, Kernel#open.
- #
- # We can accept URIs and strings that begin with http://, https:// and
- # ftp://. In these cases, the opened file object is extended by OpenURI::Meta.
- def open(name, *rest, &block) # :doc:
- if name.respond_to?(:open)
- name.open(*rest, &block)
- elsif name.respond_to?(:to_str) &&
- %r{\A[A-Za-z][A-Za-z0-9+\-\.]*://} =~ name &&
- (uri = URI.parse(name)).respond_to?(:open)
- uri.open(*rest, &block)
- else
- open_uri_original_open(name, *rest, &block)
- end
- end
- module_function :open
-end
-
-# OpenURI is an easy-to-use wrapper for Net::HTTP, Net::HTTPS and Net::FTP.
-#
-# == Example
-#
-# It is possible to open an http, https or ftp URL as though it were a file:
-#
-# open("http://www.ruby-lang.org/") {|f|
-# f.each_line {|line| p line}
-# }
-#
-# The opened file has several getter methods for its meta-information, as
-# follows, since it is extended by OpenURI::Meta.
-#
-# open("http://www.ruby-lang.org/en") {|f|
-# f.each_line {|line| p line}
-# p f.base_uri #
-# p f.content_type # "text/html"
-# p f.charset # "iso-8859-1"
-# p f.content_encoding # []
-# p f.last_modified # Thu Dec 05 02:45:02 UTC 2002
-# }
-#
-# Additional header fields can be specified by an optional hash argument.
-#
-# open("http://www.ruby-lang.org/en/",
-# "User-Agent" => "Ruby/#{RUBY_VERSION}",
-# "From" => "foo@bar.invalid",
-# "Referer" => "http://www.ruby-lang.org/") {|f|
-# # ...
-# }
-#
-# The environment variables such as http_proxy, https_proxy and ftp_proxy
-# are in effect by default. Here we disable proxy:
-#
-# open("http://www.ruby-lang.org/en/", :proxy => nil) {|f|
-# # ...
-# }
-#
-# See OpenURI::OpenRead.open and Kernel#open for more on available options.
-#
-# URI objects can be opened in a similar way.
-#
-# uri = URI.parse("http://www.ruby-lang.org/en/")
-# uri.open {|f|
-# # ...
-# }
-#
-# URI objects can be read directly. The returned string is also extended by
-# OpenURI::Meta.
-#
-# str = uri.read
-# p str.base_uri
-#
-# Author:: Tanaka Akira
-
-module OpenURI
- Options = {
- :proxy => true,
- :proxy_http_basic_authentication => true,
- :progress_proc => true,
- :content_length_proc => true,
- :http_basic_authentication => true,
- :read_timeout => true,
- :open_timeout => true,
- :ssl_ca_cert => nil,
- :ssl_verify_mode => nil,
- :ftp_active_mode => false,
- :redirect => true,
- }
-
- def OpenURI.check_options(options) # :nodoc:
- options.each {|k, v|
- next unless Symbol === k
- unless Options.include? k
- raise ArgumentError, "unrecognized option: #{k}"
- end
- }
- end
-
- def OpenURI.scan_open_optional_arguments(*rest) # :nodoc:
- if !rest.empty? && (String === rest.first || Integer === rest.first)
- mode = rest.shift
- if !rest.empty? && Integer === rest.first
- perm = rest.shift
- end
- end
- return mode, perm, rest
- end
-
- def OpenURI.open_uri(name, *rest) # :nodoc:
- uri = URI::Generic === name ? name : URI.parse(name)
- mode, _, rest = OpenURI.scan_open_optional_arguments(*rest)
- options = rest.shift if !rest.empty? && Hash === rest.first
- raise ArgumentError.new("extra arguments") if !rest.empty?
- options ||= {}
- OpenURI.check_options(options)
-
- if /\Arb?(?:\Z|:([^:]+))/ =~ mode
- encoding, = $1,Encoding.find($1) if $1
- mode = nil
- end
-
- unless mode == nil ||
- mode == 'r' || mode == 'rb' ||
- mode == File::RDONLY
- raise ArgumentError.new("invalid access mode #{mode} (#{uri.class} resource is read only.)")
- end
-
- io = open_loop(uri, options)
- io.set_encoding(encoding) if encoding
- if block_given?
- begin
- yield io
- ensure
- if io.respond_to? :close!
- io.close! # Tempfile
- else
- io.close if !io.closed?
- end
- end
- else
- io
- end
- end
-
- def OpenURI.open_loop(uri, options) # :nodoc:
- proxy_opts = []
- proxy_opts << :proxy_http_basic_authentication if options.include? :proxy_http_basic_authentication
- proxy_opts << :proxy if options.include? :proxy
- proxy_opts.compact!
- if 1 < proxy_opts.length
- raise ArgumentError, "multiple proxy options specified"
- end
- case proxy_opts.first
- when :proxy_http_basic_authentication
- opt_proxy, proxy_user, proxy_pass = options.fetch(:proxy_http_basic_authentication)
- proxy_user = proxy_user.to_str
- proxy_pass = proxy_pass.to_str
- if opt_proxy == true
- raise ArgumentError.new("Invalid authenticated proxy option: #{options[:proxy_http_basic_authentication].inspect}")
- end
- when :proxy
- opt_proxy = options.fetch(:proxy)
- proxy_user = nil
- proxy_pass = nil
- when nil
- opt_proxy = true
- proxy_user = nil
- proxy_pass = nil
- end
- case opt_proxy
- when true
- find_proxy = lambda {|u| pxy = u.find_proxy; pxy ? [pxy, nil, nil] : nil}
- when nil, false
- find_proxy = lambda {|u| nil}
- when String
- opt_proxy = URI.parse(opt_proxy)
- find_proxy = lambda {|u| [opt_proxy, proxy_user, proxy_pass]}
- when URI::Generic
- find_proxy = lambda {|u| [opt_proxy, proxy_user, proxy_pass]}
- else
- raise ArgumentError.new("Invalid proxy option: #{opt_proxy}")
- end
-
- uri_set = {}
- buf = nil
- while true
- redirect = catch(:open_uri_redirect) {
- buf = Buffer.new
- uri.buffer_open(buf, find_proxy.call(uri), options)
- nil
- }
- if redirect
- if redirect.relative?
- # Although it violates RFC2616, Location: field may have relative
- # URI. It is converted to absolute URI using uri as a base URI.
- redirect = uri + redirect
- end
- if !options.fetch(:redirect, true)
- raise HTTPRedirect.new(buf.io.status.join(' '), buf.io, redirect)
- end
- unless OpenURI.redirectable?(uri, redirect)
- raise "redirection forbidden: #{uri} -> #{redirect}"
- end
- if options.include? :http_basic_authentication
- # send authentication only for the URI directly specified.
- options = options.dup
- options.delete :http_basic_authentication
- end
- uri = redirect
- raise "HTTP redirection loop: #{uri}" if uri_set.include? uri.to_s
- uri_set[uri.to_s] = true
- else
- break
- end
- end
- io = buf.io
- io.base_uri = uri
- io
- end
-
- def OpenURI.redirectable?(uri1, uri2) # :nodoc:
- # This test is intended to forbid a redirection from http://... to
- # file:///etc/passwd, file:///dev/zero, etc. CVE-2011-1521
- # https to http redirect is also forbidden intentionally.
- # It avoids sending secure cookie or referer by non-secure HTTP protocol.
- # (RFC 2109 4.3.1, RFC 2965 3.3, RFC 2616 15.1.3)
- # However this is ad hoc. It should be extensible/configurable.
- uri1.scheme.downcase == uri2.scheme.downcase ||
- (/\A(?:http|ftp)\z/i =~ uri1.scheme && /\A(?:http|ftp)\z/i =~ uri2.scheme)
- end
-
- def OpenURI.open_http(buf, target, proxy, options) # :nodoc:
- if proxy
- proxy_uri, proxy_user, proxy_pass = proxy
- raise "Non-HTTP proxy URI: #{proxy_uri}" if proxy_uri.class != URI::HTTP
- end
-
- if target.userinfo
- raise ArgumentError, "userinfo not supported. [RFC3986]"
- end
-
- header = {}
- options.each {|k, v| header[k] = v if String === k }
-
- require 'net/http'
- klass = Net::HTTP
- if URI::HTTP === target
- # HTTP or HTTPS
- if proxy
- if proxy_user && proxy_pass
- klass = Net::HTTP::Proxy(proxy_uri.hostname, proxy_uri.port, proxy_user, proxy_pass)
- else
- klass = Net::HTTP::Proxy(proxy_uri.hostname, proxy_uri.port)
- end
- end
- target_host = target.hostname
- target_port = target.port
- request_uri = target.request_uri
- else
- # FTP over HTTP proxy
- target_host = proxy_uri.hostname
- target_port = proxy_uri.port
- request_uri = target.to_s
- if proxy_user && proxy_pass
- header["Proxy-Authorization"] = 'Basic ' + ["#{proxy_user}:#{proxy_pass}"].pack('m').delete("\r\n")
- end
- end
-
- http = proxy ? klass.new(target_host, target_port) : klass.new(target_host, target_port, nil)
- if target.class == URI::HTTPS
- require 'net/https'
- http.use_ssl = true
- http.verify_mode = options[:ssl_verify_mode] || OpenSSL::SSL::VERIFY_PEER
- store = OpenSSL::X509::Store.new
- if options[:ssl_ca_cert]
- Array(options[:ssl_ca_cert]).each do |cert|
- if File.directory? cert
- store.add_path cert
- else
- store.add_file cert
- end
- end
- else
- store.set_default_paths
- end
- http.cert_store = store
- end
- if options.include? :read_timeout
- http.read_timeout = options[:read_timeout]
- end
- if options.include? :open_timeout
- http.open_timeout = options[:open_timeout]
- end
-
- resp = nil
- http.start {
- req = Net::HTTP::Get.new(request_uri, header)
- if options.include? :http_basic_authentication
- user, pass = options[:http_basic_authentication]
- req.basic_auth user, pass
- end
- http.request(req) {|response|
- resp = response
- if options[:content_length_proc] && Net::HTTPSuccess === resp
- if resp.key?('Content-Length')
- options[:content_length_proc].call(resp['Content-Length'].to_i)
- else
- options[:content_length_proc].call(nil)
- end
- end
- resp.read_body {|str|
- buf << str
- if options[:progress_proc] && Net::HTTPSuccess === resp
- options[:progress_proc].call(buf.size)
- end
- }
- }
- }
- io = buf.io
- io.rewind
- io.status = [resp.code, resp.message]
- resp.each_name {|name| buf.io.meta_add_field2 name, resp.get_fields(name) }
- case resp
- when Net::HTTPSuccess
- when Net::HTTPMovedPermanently, # 301
- Net::HTTPFound, # 302
- Net::HTTPSeeOther, # 303
- Net::HTTPTemporaryRedirect # 307
- begin
- loc_uri = URI.parse(resp['location'])
- rescue URI::InvalidURIError
- raise OpenURI::HTTPError.new(io.status.join(' ') + ' (Invalid Location URI)', io)
- end
- throw :open_uri_redirect, loc_uri
- else
- raise OpenURI::HTTPError.new(io.status.join(' '), io)
- end
- end
-
- class HTTPError < StandardError
- def initialize(message, io)
- super(message)
- @io = io
- end
- attr_reader :io
- end
-
- # Raised on redirection,
- # only occurs when +redirect+ option for HTTP is +false+.
- class HTTPRedirect < HTTPError
- def initialize(message, io, uri)
- super(message, io)
- @uri = uri
- end
- attr_reader :uri
- end
-
- class Buffer # :nodoc: all
- def initialize
- @io = StringIO.new
- @size = 0
- end
- attr_reader :size
-
- StringMax = 10240
- def <<(str)
- @io << str
- @size += str.length
- if StringIO === @io && StringMax < @size
- require 'tempfile'
- io = Tempfile.new('open-uri')
- io.binmode
- Meta.init io, @io if Meta === @io
- io << @io.string
- @io = io
- end
- end
-
- def io
- Meta.init @io unless Meta === @io
- @io
- end
- end
-
- # Mixin for holding meta-information.
- module Meta
- def Meta.init(obj, src=nil) # :nodoc:
- obj.extend Meta
- obj.instance_eval {
- @base_uri = nil
- @meta = {} # name to string. legacy.
- @metas = {} # name to array of strings.
- }
- if src
- obj.status = src.status
- obj.base_uri = src.base_uri
- src.metas.each {|name, values|
- obj.meta_add_field2(name, values)
- }
- end
- end
-
- # returns an Array that consists of status code and message.
- attr_accessor :status
-
- # returns a URI that is the base of relative URIs in the data.
- # It may differ from the URI supplied by a user due to redirection.
- attr_accessor :base_uri
-
- # returns a Hash that represents header fields.
- # The Hash keys are downcased for canonicalization.
- # The Hash values are a field body.
- # If there are multiple field with same field name,
- # the field values are concatenated with a comma.
- attr_reader :meta
-
- # returns a Hash that represents header fields.
- # The Hash keys are downcased for canonicalization.
- # The Hash value are an array of field values.
- attr_reader :metas
-
- def meta_setup_encoding # :nodoc:
- charset = self.charset
- enc = nil
- if charset
- begin
- enc = Encoding.find(charset)
- rescue ArgumentError
- end
- end
- enc = Encoding::ASCII_8BIT unless enc
- if self.respond_to? :force_encoding
- self.force_encoding(enc)
- elsif self.respond_to? :string
- self.string.force_encoding(enc)
- else # Tempfile
- self.set_encoding enc
- end
- end
-
- def meta_add_field2(name, values) # :nodoc:
- name = name.downcase
- @metas[name] = values
- @meta[name] = values.join(', ')
- meta_setup_encoding if name == 'content-type'
- end
-
- def meta_add_field(name, value) # :nodoc:
- meta_add_field2(name, [value])
- end
-
- # returns a Time that represents the Last-Modified field.
- def last_modified
- if vs = @metas['last-modified']
- v = vs.join(', ')
- Time.httpdate(v)
- else
- nil
- end
- end
-
- # :stopdoc:
- RE_LWS = /[\r\n\t ]+/n
- RE_TOKEN = %r{[^\x00- ()<>@,;:\\"/\[\]?={}\x7f]+}n
- RE_QUOTED_STRING = %r{"(?:[\r\n\t !#-\[\]-~\x80-\xff]|\\[\x00-\x7f])*"}n
- RE_PARAMETERS = %r{(?:;#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?=#{RE_LWS}?(?:#{RE_TOKEN}|#{RE_QUOTED_STRING})#{RE_LWS}?)*}n
- # :startdoc:
-
- def content_type_parse # :nodoc:
- vs = @metas['content-type']
- # The last (?:;#{RE_LWS}?)? matches extra ";" which violates RFC2045.
- if vs && %r{\A#{RE_LWS}?(#{RE_TOKEN})#{RE_LWS}?/(#{RE_TOKEN})#{RE_LWS}?(#{RE_PARAMETERS})(?:;#{RE_LWS}?)?\z}no =~ vs.join(', ')
- type = $1.downcase
- subtype = $2.downcase
- parameters = []
- $3.scan(/;#{RE_LWS}?(#{RE_TOKEN})#{RE_LWS}?=#{RE_LWS}?(?:(#{RE_TOKEN})|(#{RE_QUOTED_STRING}))/no) {|att, val, qval|
- if qval
- val = qval[1...-1].gsub(/[\r\n\t !#-\[\]-~\x80-\xff]+|(\\[\x00-\x7f])/n) { $1 ? $1[1,1] : $& }
- end
- parameters << [att.downcase, val]
- }
- ["#{type}/#{subtype}", *parameters]
- else
- nil
- end
- end
-
- # returns "type/subtype" which is MIME Content-Type.
- # It is downcased for canonicalization.
- # Content-Type parameters are stripped.
- def content_type
- type, *_ = content_type_parse
- type || 'application/octet-stream'
- end
-
- # returns a charset parameter in Content-Type field.
- # It is downcased for canonicalization.
- #
- # If charset parameter is not given but a block is given,
- # the block is called and its result is returned.
- # It can be used to guess charset.
- #
- # If charset parameter and block is not given,
- # nil is returned except text type in HTTP.
- # In that case, "iso-8859-1" is returned as defined by RFC2616 3.7.1.
- def charset
- type, *parameters = content_type_parse
- if pair = parameters.assoc('charset')
- pair.last.downcase
- elsif block_given?
- yield
- elsif type && %r{\Atext/} =~ type &&
- @base_uri && /\Ahttp\z/i =~ @base_uri.scheme
- "iso-8859-1" # RFC2616 3.7.1
- else
- nil
- end
- end
-
- # Returns a list of encodings in Content-Encoding field as an array of
- # strings.
- #
- # The encodings are downcased for canonicalization.
- def content_encoding
- vs = @metas['content-encoding']
- if vs && %r{\A#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?(?:,#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?)*}o =~ (v = vs.join(', '))
- v.scan(RE_TOKEN).map {|content_coding| content_coding.downcase}
- else
- []
- end
- end
- end
-
- # Mixin for HTTP and FTP URIs.
- module OpenRead
- # OpenURI::OpenRead#open provides `open' for URI::HTTP and URI::FTP.
- #
- # OpenURI::OpenRead#open takes optional 3 arguments as:
- #
- # OpenURI::OpenRead#open([mode [, perm]] [, options]) [{|io| ... }]
- #
- # OpenURI::OpenRead#open returns an IO-like object if block is not given.
- # Otherwise it yields the IO object and return the value of the block.
- # The IO object is extended with OpenURI::Meta.
- #
- # +mode+ and +perm+ are the same as Kernel#open.
- #
- # However, +mode+ must be read mode because OpenURI::OpenRead#open doesn't
- # support write mode (yet).
- # Also +perm+ is ignored because it is meaningful only for file creation.
- #
- # +options+ must be a hash.
- #
- # Each option with a string key specifies an extra header field for HTTP.
- # I.e., it is ignored for FTP without HTTP proxy.
- #
- # The hash may include other options, where keys are symbols:
- #
- # [:proxy]
- # Synopsis:
- # :proxy => "http://proxy.foo.com:8000/"
- # :proxy => URI.parse("http://proxy.foo.com:8000/")
- # :proxy => true
- # :proxy => false
- # :proxy => nil
- #
- # If :proxy option is specified, the value should be String, URI,
- # boolean or nil.
- #
- # When String or URI is given, it is treated as proxy URI.
- #
- # When true is given or the option itself is not specified,
- # environment variable `scheme_proxy' is examined.
- # `scheme' is replaced by `http', `https' or `ftp'.
- #
- # When false or nil is given, the environment variables are ignored and
- # connection will be made to a server directly.
- #
- # [:proxy_http_basic_authentication]
- # Synopsis:
- # :proxy_http_basic_authentication =>
- # ["http://proxy.foo.com:8000/", "proxy-user", "proxy-password"]
- # :proxy_http_basic_authentication =>
- # [URI.parse("http://proxy.foo.com:8000/"),
- # "proxy-user", "proxy-password"]
- #
- # If :proxy option is specified, the value should be an Array with 3
- # elements. It should contain a proxy URI, a proxy user name and a proxy
- # password. The proxy URI should be a String, an URI or nil. The proxy
- # user name and password should be a String.
- #
- # If nil is given for the proxy URI, this option is just ignored.
- #
- # If :proxy and :proxy_http_basic_authentication is specified,
- # ArgumentError is raised.
- #
- # [:http_basic_authentication]
- # Synopsis:
- # :http_basic_authentication=>[user, password]
- #
- # If :http_basic_authentication is specified,
- # the value should be an array which contains 2 strings:
- # username and password.
- # It is used for HTTP Basic authentication defined by RFC 2617.
- #
- # [:content_length_proc]
- # Synopsis:
- # :content_length_proc => lambda {|content_length| ... }
- #
- # If :content_length_proc option is specified, the option value procedure
- # is called before actual transfer is started.
- # It takes one argument, which is expected content length in bytes.
- #
- # If two or more transfer is done by HTTP redirection, the procedure
- # is called only one for a last transfer.
- #
- # When expected content length is unknown, the procedure is called with
- # nil. This happens when the HTTP response has no Content-Length header.
- #
- # [:progress_proc]
- # Synopsis:
- # :progress_proc => lambda {|size| ...}
- #
- # If :progress_proc option is specified, the proc is called with one
- # argument each time when `open' gets content fragment from network.
- # The argument +size+ is the accumulated transferred size in bytes.
- #
- # If two or more transfer is done by HTTP redirection, the procedure
- # is called only one for a last transfer.
- #
- # :progress_proc and :content_length_proc are intended to be used for
- # progress bar.
- # For example, it can be implemented as follows using Ruby/ProgressBar.
- #
- # pbar = nil
- # open("http://...",
- # :content_length_proc => lambda {|t|
- # if t && 0 < t
- # pbar = ProgressBar.new("...", t)
- # pbar.file_transfer_mode
- # end
- # },
- # :progress_proc => lambda {|s|
- # pbar.set s if pbar
- # }) {|f| ... }
- #
- # [:read_timeout]
- # Synopsis:
- # :read_timeout=>nil (no timeout)
- # :read_timeout=>10 (10 second)
- #
- # :read_timeout option specifies a timeout of read for http connections.
- #
- # [:open_timeout]
- # Synopsis:
- # :open_timeout=>nil (no timeout)
- # :open_timeout=>10 (10 second)
- #
- # :open_timeout option specifies a timeout of open for http connections.
- #
- # [:ssl_ca_cert]
- # Synopsis:
- # :ssl_ca_cert=>filename or an Array of filenames
- #
- # :ssl_ca_cert is used to specify CA certificate for SSL.
- # If it is given, default certificates are not used.
- #
- # [:ssl_verify_mode]
- # Synopsis:
- # :ssl_verify_mode=>mode
- #
- # :ssl_verify_mode is used to specify openssl verify mode.
- #
- # [:ftp_active_mode]
- # Synopsis:
- # :ftp_active_mode=>bool
- #
- # :ftp_active_mode => true is used to make ftp active mode.
- # Ruby 1.9 uses passive mode by default.
- # Note that the active mode is default in Ruby 1.8 or prior.
- #
- # [:redirect]
- # Synopsis:
- # :redirect=>bool
- #
- # +:redirect+ is true by default. :redirect => false is used to
- # disable all HTTP redirects.
- #
- # OpenURI::HTTPRedirect exception raised on redirection.
- # Using +true+ also means that redirections between http and ftp are
- # permitted.
- #
- def open(*rest, &block)
- OpenURI.open_uri(self, *rest, &block)
- end
-
- # OpenURI::OpenRead#read([options]) reads a content referenced by self and
- # returns the content as string.
- # The string is extended with OpenURI::Meta.
- # The argument +options+ is same as OpenURI::OpenRead#open.
- def read(options={})
- self.open(options) {|f|
- str = f.read
- Meta.init str, f
- str
- }
- end
- end
-end
-
-module URI
- class HTTP
- def buffer_open(buf, proxy, options) # :nodoc:
- OpenURI.open_http(buf, self, proxy, options)
- end
-
- include OpenURI::OpenRead
- end
-
- class FTP
- def buffer_open(buf, proxy, options) # :nodoc:
- if proxy
- OpenURI.open_http(buf, self, proxy, options)
- return
- end
- require 'net/ftp'
-
- path = self.path
- path = path.sub(%r{\A/}, '%2F') # re-encode the beginning slash because uri library decodes it.
- directories = path.split(%r{/}, -1)
- directories.each {|d|
- d.gsub!(/%([0-9A-Fa-f][0-9A-Fa-f])/) { [$1].pack("H2") }
- }
- unless filename = directories.pop
- raise ArgumentError, "no filename: #{self.inspect}"
- end
- directories.each {|d|
- if /[\r\n]/ =~ d
- raise ArgumentError, "invalid directory: #{d.inspect}"
- end
- }
- if /[\r\n]/ =~ filename
- raise ArgumentError, "invalid filename: #{filename.inspect}"
- end
- typecode = self.typecode
- if typecode && /\A[aid]\z/ !~ typecode
- raise ArgumentError, "invalid typecode: #{typecode.inspect}"
- end
-
- # The access sequence is defined by RFC 1738
- ftp = Net::FTP.new
- ftp.connect(self.hostname, self.port)
- ftp.passive = true if !options[:ftp_active_mode]
- # todo: extract user/passwd from .netrc.
- user = 'anonymous'
- passwd = nil
- user, passwd = self.userinfo.split(/:/) if self.userinfo
- ftp.login(user, passwd)
- directories.each {|cwd|
- ftp.voidcmd("CWD #{cwd}")
- }
- if typecode
- # xxx: typecode D is not handled.
- ftp.voidcmd("TYPE #{typecode.upcase}")
- end
- if options[:content_length_proc]
- options[:content_length_proc].call(ftp.size(filename))
- end
- ftp.retrbinary("RETR #{filename}", 4096) { |str|
- buf << str
- options[:progress_proc].call(buf.size) if options[:progress_proc]
- }
- ftp.close
- buf.io.rewind
- end
-
- include OpenURI::OpenRead
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/open3.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/open3.rb
deleted file mode 100755
index 6ec4a941d..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/open3.rb
+++ /dev/null
@@ -1,663 +0,0 @@
-#
-# = open3.rb: Popen, but with stderr, too
-#
-# Author:: Yukihiro Matsumoto
-# Documentation:: Konrad Meyer
-#
-# Open3 gives you access to stdin, stdout, and stderr when running other
-# programs.
-#
-
-#
-# Open3 grants you access to stdin, stdout, stderr and a thread to wait for the
-# child process when running another program.
-# You can specify various attributes, redirections, current directory, etc., of
-# the program in the same way as for Process.spawn.
-#
-# - Open3.popen3 : pipes for stdin, stdout, stderr
-# - Open3.popen2 : pipes for stdin, stdout
-# - Open3.popen2e : pipes for stdin, merged stdout and stderr
-# - Open3.capture3 : give a string for stdin; get strings for stdout, stderr
-# - Open3.capture2 : give a string for stdin; get a string for stdout
-# - Open3.capture2e : give a string for stdin; get a string for merged stdout and stderr
-# - Open3.pipeline_rw : pipes for first stdin and last stdout of a pipeline
-# - Open3.pipeline_r : pipe for last stdout of a pipeline
-# - Open3.pipeline_w : pipe for first stdin of a pipeline
-# - Open3.pipeline_start : run a pipeline without waiting
-# - Open3.pipeline : run a pipeline and wait for its completion
-#
-
-module Open3
-
- # Open stdin, stdout, and stderr streams and start external executable.
- # In addition, a thread to wait for the started process is created.
- # The thread has a pid method and a thread variable :pid which is the pid of
- # the started process.
- #
- # Block form:
- #
- # Open3.popen3([env,] cmd... [, opts]) {|stdin, stdout, stderr, wait_thr|
- # pid = wait_thr.pid # pid of the started process.
- # ...
- # exit_status = wait_thr.value # Process::Status object returned.
- # }
- #
- # Non-block form:
- #
- # stdin, stdout, stderr, wait_thr = Open3.popen3([env,] cmd... [, opts])
- # pid = wait_thr[:pid] # pid of the started process
- # ...
- # stdin.close # stdin, stdout and stderr should be closed explicitly in this form.
- # stdout.close
- # stderr.close
- # exit_status = wait_thr.value # Process::Status object returned.
- #
- # The parameters env, cmd, and opts are passed to Process.spawn.
- # A commandline string and a list of argument strings can be accepted as follows:
- #
- # Open3.popen3("echo abc") {|i, o, e, t| ... }
- # Open3.popen3("echo", "abc") {|i, o, e, t| ... }
- # Open3.popen3(["echo", "argv0"], "abc") {|i, o, e, t| ... }
- #
- # If the last parameter, opts, is a Hash, it is recognized as an option for Process.spawn.
- #
- # Open3.popen3("pwd", :chdir=>"/") {|i,o,e,t|
- # p o.read.chomp #=> "/"
- # }
- #
- # wait_thr.value waits for the termination of the process.
- # The block form also waits for the process when it returns.
- #
- # Closing stdin, stdout and stderr does not wait for the process to complete.
- #
- # You should be careful to avoid deadlocks.
- # Since pipes are fixed length buffers,
- # Open3.popen3("prog") {|i, o, e, t| o.read } deadlocks if
- # the program generates too much output on stderr.
- # You should read stdout and stderr simultaneously (using threads or IO.select).
- # However, if you don't need stderr output, you can use Open3.popen2.
- # If merged stdout and stderr output is not a problem, you can use Open3.popen2e.
- # If you really need stdout and stderr output as separate strings, you can consider Open3.capture3.
- #
- def popen3(*cmd, **opts, &block)
- in_r, in_w = IO.pipe
- opts[:in] = in_r
- in_w.sync = true
-
- out_r, out_w = IO.pipe
- opts[:out] = out_w
-
- err_r, err_w = IO.pipe
- opts[:err] = err_w
-
- popen_run(cmd, opts, [in_r, out_w, err_w], [in_w, out_r, err_r], &block)
- end
- module_function :popen3
-
- # Open3.popen2 is similar to Open3.popen3 except that it doesn't create a pipe for
- # the standard error stream.
- #
- # Block form:
- #
- # Open3.popen2([env,] cmd... [, opts]) {|stdin, stdout, wait_thr|
- # pid = wait_thr.pid # pid of the started process.
- # ...
- # exit_status = wait_thr.value # Process::Status object returned.
- # }
- #
- # Non-block form:
- #
- # stdin, stdout, wait_thr = Open3.popen2([env,] cmd... [, opts])
- # ...
- # stdin.close # stdin and stdout should be closed explicitly in this form.
- # stdout.close
- #
- # See Process.spawn for the optional hash arguments _env_ and _opts_.
- #
- # Example:
- #
- # Open3.popen2("wc -c") {|i,o,t|
- # i.print "answer to life the universe and everything"
- # i.close
- # p o.gets #=> "42\n"
- # }
- #
- # Open3.popen2("bc -q") {|i,o,t|
- # i.puts "obase=13"
- # i.puts "6 * 9"
- # p o.gets #=> "42\n"
- # }
- #
- # Open3.popen2("dc") {|i,o,t|
- # i.print "42P"
- # i.close
- # p o.read #=> "*"
- # }
- #
- def popen2(*cmd, **opts, &block)
- in_r, in_w = IO.pipe
- opts[:in] = in_r
- in_w.sync = true
-
- out_r, out_w = IO.pipe
- opts[:out] = out_w
-
- popen_run(cmd, opts, [in_r, out_w], [in_w, out_r], &block)
- end
- module_function :popen2
-
- # Open3.popen2e is similar to Open3.popen3 except that it merges
- # the standard output stream and the standard error stream.
- #
- # Block form:
- #
- # Open3.popen2e([env,] cmd... [, opts]) {|stdin, stdout_and_stderr, wait_thr|
- # pid = wait_thr.pid # pid of the started process.
- # ...
- # exit_status = wait_thr.value # Process::Status object returned.
- # }
- #
- # Non-block form:
- #
- # stdin, stdout_and_stderr, wait_thr = Open3.popen2e([env,] cmd... [, opts])
- # ...
- # stdin.close # stdin and stdout_and_stderr should be closed explicitly in this form.
- # stdout_and_stderr.close
- #
- # See Process.spawn for the optional hash arguments _env_ and _opts_.
- #
- # Example:
- # # check gcc warnings
- # source = "foo.c"
- # Open3.popen2e("gcc", "-Wall", source) {|i,oe,t|
- # oe.each {|line|
- # if /warning/ =~ line
- # ...
- # end
- # }
- # }
- #
- def popen2e(*cmd, **opts, &block)
- in_r, in_w = IO.pipe
- opts[:in] = in_r
- in_w.sync = true
-
- out_r, out_w = IO.pipe
- opts[[:out, :err]] = out_w
-
- popen_run(cmd, opts, [in_r, out_w], [in_w, out_r], &block)
- end
- module_function :popen2e
-
- def popen_run(cmd, opts, child_io, parent_io) # :nodoc:
- pid = spawn(*cmd, opts)
- wait_thr = Process.detach(pid)
- child_io.each {|io| io.close }
- result = [*parent_io, wait_thr]
- if defined? yield
- begin
- return yield(*result)
- ensure
- parent_io.each{|io| io.close unless io.closed?}
- wait_thr.join
- end
- end
- result
- end
- module_function :popen_run
- class << self
- private :popen_run
- end
-
- # Open3.capture3 captures the standard output and the standard error of a command.
- #
- # stdout_str, stderr_str, status = Open3.capture3([env,] cmd... [, opts])
- #
- # The arguments env, cmd and opts are passed to Open3.popen3 except
- # opts[:stdin_data]
and opts[:binmode]
. See Process.spawn.
- #
- # If opts[:stdin_data]
is specified, it is sent to the command's standard input.
- #
- # If opts[:binmode]
is true, internal pipes are set to binary mode.
- #
- # Examples:
- #
- # # dot is a command of graphviz.
- # graph = <<'End'
- # digraph g {
- # a -> b
- # }
- # End
- # drawn_graph, dot_log = Open3.capture3("dot -v", :stdin_data=>graph)
- #
- # o, e, s = Open3.capture3("echo abc; sort >&2", :stdin_data=>"foo\nbar\nbaz\n")
- # p o #=> "abc\n"
- # p e #=> "bar\nbaz\nfoo\n"
- # p s #=> #
- #
- # # generate a thumbnail image using the convert command of ImageMagick.
- # # However, if the image is really stored in a file,
- # # system("convert", "-thumbnail", "80", "png:#{filename}", "png:-") is better
- # # because of reduced memory consumption.
- # # But if the image is stored in a DB or generated by the gnuplot Open3.capture2 example,
- # # Open3.capture3 should be considered.
- # #
- # image = File.read("/usr/share/openclipart/png/animals/mammals/sheep-md-v0.1.png", :binmode=>true)
- # thumbnail, err, s = Open3.capture3("convert -thumbnail 80 png:- png:-", :stdin_data=>image, :binmode=>true)
- # if s.success?
- # STDOUT.binmode; print thumbnail
- # end
- #
- def capture3(*cmd, stdin_data: '', binmode: false, **opts)
- popen3(*cmd, opts) {|i, o, e, t|
- if binmode
- i.binmode
- o.binmode
- e.binmode
- end
- out_reader = Thread.new { o.read }
- err_reader = Thread.new { e.read }
- begin
- i.write stdin_data
- rescue Errno::EPIPE
- end
- i.close
- [out_reader.value, err_reader.value, t.value]
- }
- end
- module_function :capture3
-
- # Open3.capture2 captures the standard output of a command.
- #
- # stdout_str, status = Open3.capture2([env,] cmd... [, opts])
- #
- # The arguments env, cmd and opts are passed to Open3.popen3 except
- # opts[:stdin_data]
and opts[:binmode]
. See Process.spawn.
- #
- # If opts[:stdin_data]
is specified, it is sent to the command's standard input.
- #
- # If opts[:binmode]
is true, internal pipes are set to binary mode.
- #
- # Example:
- #
- # # factor is a command for integer factorization.
- # o, s = Open3.capture2("factor", :stdin_data=>"42")
- # p o #=> "42: 2 3 7\n"
- #
- # # generate x**2 graph in png using gnuplot.
- # gnuplot_commands = <<"End"
- # set terminal png
- # plot x**2, "-" with lines
- # 1 14
- # 2 1
- # 3 8
- # 4 5
- # e
- # End
- # image, s = Open3.capture2("gnuplot", :stdin_data=>gnuplot_commands, :binmode=>true)
- #
- def capture2(*cmd, stdin_data: nil, binmode: false, **opts)
- popen2(*cmd, opts) {|i, o, t|
- if binmode
- i.binmode
- o.binmode
- end
- out_reader = Thread.new { o.read }
- if stdin_data
- begin
- i.write stdin_data
- rescue Errno::EPIPE
- end
- end
- i.close
- [out_reader.value, t.value]
- }
- end
- module_function :capture2
-
- # Open3.capture2e captures the standard output and the standard error of a command.
- #
- # stdout_and_stderr_str, status = Open3.capture2e([env,] cmd... [, opts])
- #
- # The arguments env, cmd and opts are passed to Open3.popen3 except
- # opts[:stdin_data]
and opts[:binmode]
. See Process.spawn.
- #
- # If opts[:stdin_data]
is specified, it is sent to the command's standard input.
- #
- # If opts[:binmode]
is true, internal pipes are set to binary mode.
- #
- # Example:
- #
- # # capture make log
- # make_log, s = Open3.capture2e("make")
- #
- def capture2e(*cmd, stdin_data: nil, binmode: false, **opts)
- popen2e(*cmd, opts) {|i, oe, t|
- if binmode
- i.binmode
- oe.binmode
- end
- outerr_reader = Thread.new { oe.read }
- if stdin_data
- begin
- i.write stdin_data
- rescue Errno::EPIPE
- end
- end
- i.close
- [outerr_reader.value, t.value]
- }
- end
- module_function :capture2e
-
- # Open3.pipeline_rw starts a list of commands as a pipeline with pipes
- # which connect to stdin of the first command and stdout of the last command.
- #
- # Open3.pipeline_rw(cmd1, cmd2, ... [, opts]) {|first_stdin, last_stdout, wait_threads|
- # ...
- # }
- #
- # first_stdin, last_stdout, wait_threads = Open3.pipeline_rw(cmd1, cmd2, ... [, opts])
- # ...
- # first_stdin.close
- # last_stdout.close
- #
- # Each cmd is a string or an array.
- # If it is an array, the elements are passed to Process.spawn.
- #
- # cmd:
- # commandline command line string which is passed to a shell
- # [env, commandline, opts] command line string which is passed to a shell
- # [env, cmdname, arg1, ..., opts] command name and one or more arguments (no shell)
- # [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
- #
- # Note that env and opts are optional, as for Process.spawn.
- #
- # The options to pass to Process.spawn are constructed by merging
- # +opts+, the last hash element of the array, and
- # specifications for the pipes between each of the commands.
- #
- # Example:
- #
- # Open3.pipeline_rw("tr -dc A-Za-z", "wc -c") {|i, o, ts|
- # i.puts "All persons more than a mile high to leave the court."
- # i.close
- # p o.gets #=> "42\n"
- # }
- #
- # Open3.pipeline_rw("sort", "cat -n") {|stdin, stdout, wait_thrs|
- # stdin.puts "foo"
- # stdin.puts "bar"
- # stdin.puts "baz"
- # stdin.close # send EOF to sort.
- # p stdout.read #=> " 1\tbar\n 2\tbaz\n 3\tfoo\n"
- # }
- def pipeline_rw(*cmds, **opts, &block)
- in_r, in_w = IO.pipe
- opts[:in] = in_r
- in_w.sync = true
-
- out_r, out_w = IO.pipe
- opts[:out] = out_w
-
- pipeline_run(cmds, opts, [in_r, out_w], [in_w, out_r], &block)
- end
- module_function :pipeline_rw
-
- # Open3.pipeline_r starts a list of commands as a pipeline with a pipe
- # which connects to stdout of the last command.
- #
- # Open3.pipeline_r(cmd1, cmd2, ... [, opts]) {|last_stdout, wait_threads|
- # ...
- # }
- #
- # last_stdout, wait_threads = Open3.pipeline_r(cmd1, cmd2, ... [, opts])
- # ...
- # last_stdout.close
- #
- # Each cmd is a string or an array.
- # If it is an array, the elements are passed to Process.spawn.
- #
- # cmd:
- # commandline command line string which is passed to a shell
- # [env, commandline, opts] command line string which is passed to a shell
- # [env, cmdname, arg1, ..., opts] command name and one or more arguments (no shell)
- # [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
- #
- # Note that env and opts are optional, as for Process.spawn.
- #
- # Example:
- #
- # Open3.pipeline_r("zcat /var/log/apache2/access.log.*.gz",
- # [{"LANG"=>"C"}, "grep", "GET /favicon.ico"],
- # "logresolve") {|o, ts|
- # o.each_line {|line|
- # ...
- # }
- # }
- #
- # Open3.pipeline_r("yes", "head -10") {|o, ts|
- # p o.read #=> "y\ny\ny\ny\ny\ny\ny\ny\ny\ny\n"
- # p ts[0].value #=> #
- # p ts[1].value #=> #
- # }
- #
- def pipeline_r(*cmds, **opts, &block)
- out_r, out_w = IO.pipe
- opts[:out] = out_w
-
- pipeline_run(cmds, opts, [out_w], [out_r], &block)
- end
- module_function :pipeline_r
-
- # Open3.pipeline_w starts a list of commands as a pipeline with a pipe
- # which connects to stdin of the first command.
- #
- # Open3.pipeline_w(cmd1, cmd2, ... [, opts]) {|first_stdin, wait_threads|
- # ...
- # }
- #
- # first_stdin, wait_threads = Open3.pipeline_w(cmd1, cmd2, ... [, opts])
- # ...
- # first_stdin.close
- #
- # Each cmd is a string or an array.
- # If it is an array, the elements are passed to Process.spawn.
- #
- # cmd:
- # commandline command line string which is passed to a shell
- # [env, commandline, opts] command line string which is passed to a shell
- # [env, cmdname, arg1, ..., opts] command name and one or more arguments (no shell)
- # [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
- #
- # Note that env and opts are optional, as for Process.spawn.
- #
- # Example:
- #
- # Open3.pipeline_w("bzip2 -c", :out=>"/tmp/hello.bz2") {|i, ts|
- # i.puts "hello"
- # }
- #
- def pipeline_w(*cmds, **opts, &block)
- in_r, in_w = IO.pipe
- opts[:in] = in_r
- in_w.sync = true
-
- pipeline_run(cmds, opts, [in_r], [in_w], &block)
- end
- module_function :pipeline_w
-
- # Open3.pipeline_start starts a list of commands as a pipeline.
- # No pipes are created for stdin of the first command and
- # stdout of the last command.
- #
- # Open3.pipeline_start(cmd1, cmd2, ... [, opts]) {|wait_threads|
- # ...
- # }
- #
- # wait_threads = Open3.pipeline_start(cmd1, cmd2, ... [, opts])
- # ...
- #
- # Each cmd is a string or an array.
- # If it is an array, the elements are passed to Process.spawn.
- #
- # cmd:
- # commandline command line string which is passed to a shell
- # [env, commandline, opts] command line string which is passed to a shell
- # [env, cmdname, arg1, ..., opts] command name and one or more arguments (no shell)
- # [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
- #
- # Note that env and opts are optional, as for Process.spawn.
- #
- # Example:
- #
- # # Run xeyes in 10 seconds.
- # Open3.pipeline_start("xeyes") {|ts|
- # sleep 10
- # t = ts[0]
- # Process.kill("TERM", t.pid)
- # p t.value #=> #
- # }
- #
- # # Convert pdf to ps and send it to a printer.
- # # Collect error message of pdftops and lpr.
- # pdf_file = "paper.pdf"
- # printer = "printer-name"
- # err_r, err_w = IO.pipe
- # Open3.pipeline_start(["pdftops", pdf_file, "-"],
- # ["lpr", "-P#{printer}"],
- # :err=>err_w) {|ts|
- # err_w.close
- # p err_r.read # error messages of pdftops and lpr.
- # }
- #
- def pipeline_start(*cmds, **opts, &block)
- if block
- pipeline_run(cmds, opts, [], [], &block)
- else
- ts, = pipeline_run(cmds, opts, [], [])
- ts
- end
- end
- module_function :pipeline_start
-
- # Open3.pipeline starts a list of commands as a pipeline.
- # It waits for the completion of the commands.
- # No pipes are created for stdin of the first command and
- # stdout of the last command.
- #
- # status_list = Open3.pipeline(cmd1, cmd2, ... [, opts])
- #
- # Each cmd is a string or an array.
- # If it is an array, the elements are passed to Process.spawn.
- #
- # cmd:
- # commandline command line string which is passed to a shell
- # [env, commandline, opts] command line string which is passed to a shell
- # [env, cmdname, arg1, ..., opts] command name and one or more arguments (no shell)
- # [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
- #
- # Note that env and opts are optional, as Process.spawn.
- #
- # Example:
- #
- # fname = "/usr/share/man/man1/ruby.1.gz"
- # p Open3.pipeline(["zcat", fname], "nroff -man", "less")
- # #=> [#,
- # # #,
- # # #]
- #
- # fname = "/usr/share/man/man1/ls.1.gz"
- # Open3.pipeline(["zcat", fname], "nroff -man", "colcrt")
- #
- # # convert PDF to PS and send to a printer by lpr
- # pdf_file = "paper.pdf"
- # printer = "printer-name"
- # Open3.pipeline(["pdftops", pdf_file, "-"],
- # ["lpr", "-P#{printer}"])
- #
- # # count lines
- # Open3.pipeline("sort", "uniq -c", :in=>"names.txt", :out=>"count")
- #
- # # cyclic pipeline
- # r,w = IO.pipe
- # w.print "ibase=14\n10\n"
- # Open3.pipeline("bc", "tee /dev/tty", :in=>r, :out=>w)
- # #=> 14
- # # 18
- # # 22
- # # 30
- # # 42
- # # 58
- # # 78
- # # 106
- # # 202
- #
- def pipeline(*cmds, **opts)
- pipeline_run(cmds, opts, [], []) {|ts|
- ts.map {|t| t.value }
- }
- end
- module_function :pipeline
-
- def pipeline_run(cmds, pipeline_opts, child_io, parent_io) # :nodoc:
- if cmds.empty?
- raise ArgumentError, "no commands"
- end
-
- opts_base = pipeline_opts.dup
- opts_base.delete :in
- opts_base.delete :out
-
- wait_thrs = []
- r = nil
- cmds.each_with_index {|cmd, i|
- cmd_opts = opts_base.dup
- if String === cmd
- cmd = [cmd]
- else
- cmd_opts.update cmd.pop if Hash === cmd.last
- end
- if i == 0
- if !cmd_opts.include?(:in)
- if pipeline_opts.include?(:in)
- cmd_opts[:in] = pipeline_opts[:in]
- end
- end
- else
- cmd_opts[:in] = r
- end
- if i != cmds.length - 1
- r2, w2 = IO.pipe
- cmd_opts[:out] = w2
- else
- if !cmd_opts.include?(:out)
- if pipeline_opts.include?(:out)
- cmd_opts[:out] = pipeline_opts[:out]
- end
- end
- end
- pid = spawn(*cmd, cmd_opts)
- wait_thrs << Process.detach(pid)
- r.close if r
- w2.close if w2
- r = r2
- }
- result = parent_io + [wait_thrs]
- child_io.each {|io| io.close }
- if defined? yield
- begin
- return yield(*result)
- ensure
- parent_io.each{|io| io.close unless io.closed?}
- wait_thrs.each {|t| t.join }
- end
- end
- result
- end
- module_function :pipeline_run
- class << self
- private :pipeline_run
- end
-
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/openssl.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/openssl.rb
deleted file mode 100755
index adcaee729..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/openssl.rb
+++ /dev/null
@@ -1,24 +0,0 @@
-=begin
-= $RCSfile$ -- Loader for all OpenSSL C-space and Ruby-space definitions
-
-= Info
- 'OpenSSL for Ruby 2' project
- Copyright (C) 2002 Michal Rokos
- All rights reserved.
-
-= Licence
- This program is licenced under the same licence as Ruby.
- (See the file 'LICENCE'.)
-
-= Version
- $Id: openssl.rb 32664 2011-07-25 06:30:07Z nahi $
-=end
-
-require 'openssl.so'
-
-require 'openssl/bn'
-require 'openssl/cipher'
-require 'openssl/config'
-require 'openssl/digest'
-require 'openssl/x509'
-require 'openssl/ssl'
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/openssl/bn.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/openssl/bn.rb
deleted file mode 100755
index 8c07eacc4..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/openssl/bn.rb
+++ /dev/null
@@ -1,45 +0,0 @@
-#--
-#
-# $RCSfile$
-#
-# = Ruby-space definitions that completes C-space funcs for BN
-#
-# = Info
-# 'OpenSSL for Ruby 2' project
-# Copyright (C) 2002 Michal Rokos
-# All rights reserved.
-#
-# = Licence
-# This program is licenced under the same licence as Ruby.
-# (See the file 'LICENCE'.)
-#
-# = Version
-# $Id: bn.rb 47647 2014-09-20 01:17:05Z akr $
-#
-#++
-
-module OpenSSL
- class BN
- include Comparable
-
- def pretty_print(q)
- q.object_group(self) {
- q.text ' '
- q.text to_i.to_s
- }
- end
- end # BN
-end # OpenSSL
-
-##
-# Add double dispatch to Integer
-#
-class Integer
- # Casts an Integer as an OpenSSL::BN
- #
- # See `man bn` for more info.
- def to_bn
- OpenSSL::BN::new(self)
- end
-end # Integer
-
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/openssl/buffering.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/openssl/buffering.rb
deleted file mode 100755
index 40bbd0ffb..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/openssl/buffering.rb
+++ /dev/null
@@ -1,457 +0,0 @@
-# coding: binary
-#--
-#= $RCSfile$ -- Buffering mix-in module.
-#
-#= Info
-# 'OpenSSL for Ruby 2' project
-# Copyright (C) 2001 GOTOU YUUZOU
-# All rights reserved.
-#
-#= Licence
-# This program is licenced under the same licence as Ruby.
-# (See the file 'LICENCE'.)
-#
-#= Version
-# $Id: buffering.rb 43964 2013-12-03 01:44:41Z drbrain $
-#++
-
-##
-# OpenSSL IO buffering mix-in module.
-#
-# This module allows an OpenSSL::SSL::SSLSocket to behave like an IO.
-#
-# You typically won't use this module directly, you can see it implemented in
-# OpenSSL::SSL::SSLSocket.
-
-module OpenSSL::Buffering
- include Enumerable
-
- ##
- # The "sync mode" of the SSLSocket.
- #
- # See IO#sync for full details.
-
- attr_accessor :sync
-
- ##
- # Default size to read from or write to the SSLSocket for buffer operations.
-
- BLOCK_SIZE = 1024*16
-
- ##
- # Creates an instance of OpenSSL's buffering IO module.
-
- def initialize(*)
- super
- @eof = false
- @rbuffer = ""
- @sync = @io.sync
- end
-
- #
- # for reading.
- #
- private
-
- ##
- # Fills the buffer from the underlying SSLSocket
-
- def fill_rbuff
- begin
- @rbuffer << self.sysread(BLOCK_SIZE)
- rescue Errno::EAGAIN
- retry
- rescue EOFError
- @eof = true
- end
- end
-
- ##
- # Consumes +size+ bytes from the buffer
-
- def consume_rbuff(size=nil)
- if @rbuffer.empty?
- nil
- else
- size = @rbuffer.size unless size
- ret = @rbuffer[0, size]
- @rbuffer[0, size] = ""
- ret
- end
- end
-
- public
-
- ##
- # Reads +size+ bytes from the stream. If +buf+ is provided it must
- # reference a string which will receive the data.
- #
- # See IO#read for full details.
-
- def read(size=nil, buf=nil)
- if size == 0
- if buf
- buf.clear
- return buf
- else
- return ""
- end
- end
- until @eof
- break if size && size <= @rbuffer.size
- fill_rbuff
- end
- ret = consume_rbuff(size) || ""
- if buf
- buf.replace(ret)
- ret = buf
- end
- (size && ret.empty?) ? nil : ret
- end
-
- ##
- # Reads at most +maxlen+ bytes from the stream. If +buf+ is provided it
- # must reference a string which will receive the data.
- #
- # See IO#readpartial for full details.
-
- def readpartial(maxlen, buf=nil)
- if maxlen == 0
- if buf
- buf.clear
- return buf
- else
- return ""
- end
- end
- if @rbuffer.empty?
- begin
- return sysread(maxlen, buf)
- rescue Errno::EAGAIN
- retry
- end
- end
- ret = consume_rbuff(maxlen)
- if buf
- buf.replace(ret)
- ret = buf
- end
- raise EOFError if ret.empty?
- ret
- end
-
- ##
- # Reads at most +maxlen+ bytes in the non-blocking manner.
- #
- # When no data can be read without blocking it raises
- # OpenSSL::SSL::SSLError extended by IO::WaitReadable or IO::WaitWritable.
- #
- # IO::WaitReadable means SSL needs to read internally so read_nonblock
- # should be called again when the underlying IO is readable.
- #
- # IO::WaitWritable means SSL needs to write internally so read_nonblock
- # should be called again after the underlying IO is writable.
- #
- # OpenSSL::Buffering#read_nonblock needs two rescue clause as follows:
- #
- # # emulates blocking read (readpartial).
- # begin
- # result = ssl.read_nonblock(maxlen)
- # rescue IO::WaitReadable
- # IO.select([io])
- # retry
- # rescue IO::WaitWritable
- # IO.select(nil, [io])
- # retry
- # end
- #
- # Note that one reason that read_nonblock writes to the underlying IO is
- # when the peer requests a new TLS/SSL handshake. See openssl the FAQ for
- # more details. http://www.openssl.org/support/faq.html
-
- def read_nonblock(maxlen, buf=nil, exception: true)
- if maxlen == 0
- if buf
- buf.clear
- return buf
- else
- return ""
- end
- end
- if @rbuffer.empty?
- return sysread_nonblock(maxlen, buf, exception: exception)
- end
- ret = consume_rbuff(maxlen)
- if buf
- buf.replace(ret)
- ret = buf
- end
- raise EOFError if ret.empty?
- ret
- end
-
- ##
- # Reads the next "line+ from the stream. Lines are separated by +eol+. If
- # +limit+ is provided the result will not be longer than the given number of
- # bytes.
- #
- # +eol+ may be a String or Regexp.
- #
- # Unlike IO#gets the line read will not be assigned to +$_+.
- #
- # Unlike IO#gets the separator must be provided if a limit is provided.
-
- def gets(eol=$/, limit=nil)
- idx = @rbuffer.index(eol)
- until @eof
- break if idx
- fill_rbuff
- idx = @rbuffer.index(eol)
- end
- if eol.is_a?(Regexp)
- size = idx ? idx+$&.size : nil
- else
- size = idx ? idx+eol.size : nil
- end
- if limit and limit >= 0
- size = [size, limit].min
- end
- consume_rbuff(size)
- end
-
- ##
- # Executes the block for every line in the stream where lines are separated
- # by +eol+.
- #
- # See also #gets
-
- def each(eol=$/)
- while line = self.gets(eol)
- yield line
- end
- end
- alias each_line each
-
- ##
- # Reads lines from the stream which are separated by +eol+.
- #
- # See also #gets
-
- def readlines(eol=$/)
- ary = []
- while line = self.gets(eol)
- ary << line
- end
- ary
- end
-
- ##
- # Reads a line from the stream which is separated by +eol+.
- #
- # Raises EOFError if at end of file.
-
- def readline(eol=$/)
- raise EOFError if eof?
- gets(eol)
- end
-
- ##
- # Reads one character from the stream. Returns nil if called at end of
- # file.
-
- def getc
- read(1)
- end
-
- ##
- # Calls the given block once for each byte in the stream.
-
- def each_byte # :yields: byte
- while c = getc
- yield(c.ord)
- end
- end
-
- ##
- # Reads a one-character string from the stream. Raises an EOFError at end
- # of file.
-
- def readchar
- raise EOFError if eof?
- getc
- end
-
- ##
- # Pushes character +c+ back onto the stream such that a subsequent buffered
- # character read will return it.
- #
- # Unlike IO#getc multiple bytes may be pushed back onto the stream.
- #
- # Has no effect on unbuffered reads (such as #sysread).
-
- def ungetc(c)
- @rbuffer[0,0] = c.chr
- end
-
- ##
- # Returns true if the stream is at file which means there is no more data to
- # be read.
-
- def eof?
- fill_rbuff if !@eof && @rbuffer.empty?
- @eof && @rbuffer.empty?
- end
- alias eof eof?
-
- #
- # for writing.
- #
- private
-
- ##
- # Writes +s+ to the buffer. When the buffer is full or #sync is true the
- # buffer is flushed to the underlying socket.
-
- def do_write(s)
- @wbuffer = "" unless defined? @wbuffer
- @wbuffer << s
- @wbuffer.force_encoding(Encoding::BINARY)
- @sync ||= false
- if @sync or @wbuffer.size > BLOCK_SIZE or idx = @wbuffer.rindex($/)
- remain = idx ? idx + $/.size : @wbuffer.length
- nwritten = 0
- while remain > 0
- str = @wbuffer[nwritten,remain]
- begin
- nwrote = syswrite(str)
- rescue Errno::EAGAIN
- retry
- end
- remain -= nwrote
- nwritten += nwrote
- end
- @wbuffer[0,nwritten] = ""
- end
- end
-
- public
-
- ##
- # Writes +s+ to the stream. If the argument is not a string it will be
- # converted using String#to_s. Returns the number of bytes written.
-
- def write(s)
- do_write(s)
- s.bytesize
- end
-
- ##
- # Writes +str+ in the non-blocking manner.
- #
- # If there is buffered data, it is flushed first. This may block.
- #
- # write_nonblock returns number of bytes written to the SSL connection.
- #
- # When no data can be written without blocking it raises
- # OpenSSL::SSL::SSLError extended by IO::WaitReadable or IO::WaitWritable.
- #
- # IO::WaitReadable means SSL needs to read internally so write_nonblock
- # should be called again after the underlying IO is readable.
- #
- # IO::WaitWritable means SSL needs to write internally so write_nonblock
- # should be called again after underlying IO is writable.
- #
- # So OpenSSL::Buffering#write_nonblock needs two rescue clause as follows.
- #
- # # emulates blocking write.
- # begin
- # result = ssl.write_nonblock(str)
- # rescue IO::WaitReadable
- # IO.select([io])
- # retry
- # rescue IO::WaitWritable
- # IO.select(nil, [io])
- # retry
- # end
- #
- # Note that one reason that write_nonblock reads from the underlying IO
- # is when the peer requests a new TLS/SSL handshake. See the openssl FAQ
- # for more details. http://www.openssl.org/support/faq.html
-
- def write_nonblock(s, exception: true)
- flush
- syswrite_nonblock(s, exception: exception)
- end
-
- ##
- # Writes +s+ to the stream. +s+ will be converted to a String using
- # String#to_s.
-
- def << (s)
- do_write(s)
- self
- end
-
- ##
- # Writes +args+ to the stream along with a record separator.
- #
- # See IO#puts for full details.
-
- def puts(*args)
- s = ""
- if args.empty?
- s << "\n"
- end
- args.each{|arg|
- s << arg.to_s
- if $/ && /\n\z/ !~ s
- s << "\n"
- end
- }
- do_write(s)
- nil
- end
-
- ##
- # Writes +args+ to the stream.
- #
- # See IO#print for full details.
-
- def print(*args)
- s = ""
- args.each{ |arg| s << arg.to_s }
- do_write(s)
- nil
- end
-
- ##
- # Formats and writes to the stream converting parameters under control of
- # the format string.
- #
- # See Kernel#sprintf for format string details.
-
- def printf(s, *args)
- do_write(s % args)
- nil
- end
-
- ##
- # Flushes buffered data to the SSLSocket.
-
- def flush
- osync = @sync
- @sync = true
- do_write ""
- return self
- ensure
- @sync = osync
- end
-
- ##
- # Closes the SSLSocket and flushes any unwritten data.
-
- def close
- flush rescue nil
- sysclose
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/openssl/cipher.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/openssl/cipher.rb
deleted file mode 100755
index c32cea2da..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/openssl/cipher.rb
+++ /dev/null
@@ -1,65 +0,0 @@
-#--
-#
-# $RCSfile$
-#
-# = Ruby-space predefined Cipher subclasses
-#
-# = Info
-# 'OpenSSL for Ruby 2' project
-# Copyright (C) 2002 Michal Rokos
-# All rights reserved.
-#
-# = Licence
-# This program is licenced under the same licence as Ruby.
-# (See the file 'LICENCE'.)
-#
-# = Version
-# $Id: cipher.rb 36895 2012-09-04 00:57:31Z nobu $
-#
-#++
-
-module OpenSSL
- class Cipher
- %w(AES CAST5 BF DES IDEA RC2 RC4 RC5).each{|name|
- klass = Class.new(Cipher){
- define_method(:initialize){|*args|
- cipher_name = args.inject(name){|n, arg| "#{n}-#{arg}" }
- super(cipher_name)
- }
- }
- const_set(name, klass)
- }
-
- %w(128 192 256).each{|keylen|
- klass = Class.new(Cipher){
- define_method(:initialize){|mode|
- mode ||= "CBC"
- cipher_name = "AES-#{keylen}-#{mode}"
- super(cipher_name)
- }
- }
- const_set("AES#{keylen}", klass)
- }
-
- # Generate, set, and return a random key.
- # You must call cipher.encrypt or cipher.decrypt before calling this method.
- def random_key
- str = OpenSSL::Random.random_bytes(self.key_len)
- self.key = str
- return str
- end
-
- # Generate, set, and return a random iv.
- # You must call cipher.encrypt or cipher.decrypt before calling this method.
- def random_iv
- str = OpenSSL::Random.random_bytes(self.iv_len)
- self.iv = str
- return str
- end
-
- # This class is only provided for backwards compatibility. Use OpenSSL::Cipher in the future.
- class Cipher < Cipher
- # add warning
- end
- end # Cipher
-end # OpenSSL
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/openssl/config.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/openssl/config.rb
deleted file mode 100755
index 5716d59fd..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/openssl/config.rb
+++ /dev/null
@@ -1,472 +0,0 @@
-=begin
-= Ruby-space definitions that completes C-space funcs for Config
-
-= Info
- Copyright (C) 2010 Hiroshi Nakamura
-
-= Licence
- This program is licenced under the same licence as Ruby.
- (See the file 'LICENCE'.)
-
-=end
-
-require 'stringio'
-
-module OpenSSL
- ##
- # = OpenSSL::Config
- #
- # Configuration for the openssl library.
- #
- # Many system's installation of openssl library will depend on your system
- # configuration. See the value of OpenSSL::Config::DEFAULT_CONFIG_FILE for
- # the location of the file for your host.
- #
- # See also http://www.openssl.org/docs/apps/config.html
- class Config
- include Enumerable
-
- class << self
-
- ##
- # Parses a given +string+ as a blob that contains configuration for openssl.
- #
- # If the source of the IO is a file, then consider using #parse_config.
- def parse(string)
- c = new()
- parse_config(StringIO.new(string)).each do |section, hash|
- c[section] = hash
- end
- c
- end
-
- ##
- # load is an alias to ::new
- alias load new
-
- ##
- # Parses the configuration data read from +io+, see also #parse.
- #
- # Raises a ConfigError on invalid configuration data.
- def parse_config(io)
- begin
- parse_config_lines(io)
- rescue ConfigError => e
- e.message.replace("error in line #{io.lineno}: " + e.message)
- raise
- end
- end
-
- def get_key_string(data, section, key) # :nodoc:
- if v = data[section] && data[section][key]
- return v
- elsif section == 'ENV'
- if v = ENV[key]
- return v
- end
- end
- if v = data['default'] && data['default'][key]
- return v
- end
- end
-
- private
-
- def parse_config_lines(io)
- section = 'default'
- data = {section => {}}
- while definition = get_definition(io)
- definition = clear_comments(definition)
- next if definition.empty?
- if definition[0] == ?[
- if /\[([^\]]*)\]/ =~ definition
- section = $1.strip
- data[section] ||= {}
- else
- raise ConfigError, "missing close square bracket"
- end
- else
- if /\A([^:\s]*)(?:::([^:\s]*))?\s*=(.*)\z/ =~ definition
- if $2
- section = $1
- key = $2
- else
- key = $1
- end
- value = unescape_value(data, section, $3)
- (data[section] ||= {})[key] = value.strip
- else
- raise ConfigError, "missing equal sign"
- end
- end
- end
- data
- end
-
- # escape with backslash
- QUOTE_REGEXP_SQ = /\A([^'\\]*(?:\\.[^'\\]*)*)'/
- # escape with backslash and doubled dq
- QUOTE_REGEXP_DQ = /\A([^"\\]*(?:""[^"\\]*|\\.[^"\\]*)*)"/
- # escaped char map
- ESCAPE_MAP = {
- "r" => "\r",
- "n" => "\n",
- "b" => "\b",
- "t" => "\t",
- }
-
- def unescape_value(data, section, value)
- scanned = []
- while m = value.match(/['"\\$]/)
- scanned << m.pre_match
- c = m[0]
- value = m.post_match
- case c
- when "'"
- if m = value.match(QUOTE_REGEXP_SQ)
- scanned << m[1].gsub(/\\(.)/, '\\1')
- value = m.post_match
- else
- break
- end
- when '"'
- if m = value.match(QUOTE_REGEXP_DQ)
- scanned << m[1].gsub(/""/, '').gsub(/\\(.)/, '\\1')
- value = m.post_match
- else
- break
- end
- when "\\"
- c = value.slice!(0, 1)
- scanned << (ESCAPE_MAP[c] || c)
- when "$"
- ref, value = extract_reference(value)
- refsec = section
- if ref.index('::')
- refsec, ref = ref.split('::', 2)
- end
- if v = get_key_string(data, refsec, ref)
- scanned << v
- else
- raise ConfigError, "variable has no value"
- end
- else
- raise 'must not reaced'
- end
- end
- scanned << value
- scanned.join
- end
-
- def extract_reference(value)
- rest = ''
- if m = value.match(/\(([^)]*)\)|\{([^}]*)\}/)
- value = m[1] || m[2]
- rest = m.post_match
- elsif [?(, ?{].include?(value[0])
- raise ConfigError, "no close brace"
- end
- if m = value.match(/[a-zA-Z0-9_]*(?:::[a-zA-Z0-9_]*)?/)
- return m[0], m.post_match + rest
- else
- raise
- end
- end
-
- def clear_comments(line)
- # FCOMMENT
- if m = line.match(/\A([\t\n\f ]*);.*\z/)
- return m[1]
- end
- # COMMENT
- scanned = []
- while m = line.match(/[#'"\\]/)
- scanned << m.pre_match
- c = m[0]
- line = m.post_match
- case c
- when '#'
- line = nil
- break
- when "'", '"'
- regexp = (c == "'") ? QUOTE_REGEXP_SQ : QUOTE_REGEXP_DQ
- scanned << c
- if m = line.match(regexp)
- scanned << m[0]
- line = m.post_match
- else
- scanned << line
- line = nil
- break
- end
- when "\\"
- scanned << c
- scanned << line.slice!(0, 1)
- else
- raise 'must not reaced'
- end
- end
- scanned << line
- scanned.join
- end
-
- def get_definition(io)
- if line = get_line(io)
- while /[^\\]\\\z/ =~ line
- if extra = get_line(io)
- line += extra
- else
- break
- end
- end
- return line.strip
- end
- end
-
- def get_line(io)
- if line = io.gets
- line.gsub(/[\r\n]*/, '')
- end
- end
- end
-
- ##
- # Creates an instance of OpenSSL's configuration class.
- #
- # This can be used in contexts like OpenSSL::X509::ExtensionFactory.config=
- #
- # If the optional +filename+ parameter is provided, then it is read in and
- # parsed via #parse_config.
- #
- # This can raise IO exceptions based on the access, or availability of the
- # file. A ConfigError exception may be raised depending on the validity of
- # the data being configured.
- #
- def initialize(filename = nil)
- @data = {}
- if filename
- File.open(filename.to_s) do |file|
- Config.parse_config(file).each do |section, hash|
- self[section] = hash
- end
- end
- end
- end
-
- ##
- # Gets the value of +key+ from the given +section+
- #
- # Given the following configurating file being loaded:
- #
- # config = OpenSSL::Config.load('foo.cnf')
- # #=> #
- # puts config.to_s
- # #=> [ default ]
- # # foo=bar
- #
- # You can get a specific value from the config if you know the +section+
- # and +key+ like so:
- #
- # config.get_value('default','foo')
- # #=> "bar"
- #
- def get_value(section, key)
- if section.nil?
- raise TypeError.new('nil not allowed')
- end
- section = 'default' if section.empty?
- get_key_string(section, key)
- end
-
- ##
- #
- # *Deprecated*
- #
- # Use #get_value instead
- def value(arg1, arg2 = nil) # :nodoc:
- warn('Config#value is deprecated; use Config#get_value')
- if arg2.nil?
- section, key = 'default', arg1
- else
- section, key = arg1, arg2
- end
- section ||= 'default'
- section = 'default' if section.empty?
- get_key_string(section, key)
- end
-
- ##
- # Set the target +key+ with a given +value+ under a specific +section+.
- #
- # Given the following configurating file being loaded:
- #
- # config = OpenSSL::Config.load('foo.cnf')
- # #=> #
- # puts config.to_s
- # #=> [ default ]
- # # foo=bar
- #
- # You can set the value of +foo+ under the +default+ section to a new
- # value:
- #
- # config.add_value('default', 'foo', 'buzz')
- # #=> "buzz"
- # puts config.to_s
- # #=> [ default ]
- # # foo=buzz
- #
- def add_value(section, key, value)
- check_modify
- (@data[section] ||= {})[key] = value
- end
-
- ##
- # Get a specific +section+ from the current configuration
- #
- # Given the following configurating file being loaded:
- #
- # config = OpenSSL::Config.load('foo.cnf')
- # #=> #
- # puts config.to_s
- # #=> [ default ]
- # # foo=bar
- #
- # You can get a hash of the specific section like so:
- #
- # config['default']
- # #=> {"foo"=>"bar"}
- #
- def [](section)
- @data[section] || {}
- end
-
- ##
- # Deprecated
- #
- # Use #[] instead
- def section(name) # :nodoc:
- warn('Config#section is deprecated; use Config#[]')
- @data[name] || {}
- end
-
- ##
- # Sets a specific +section+ name with a Hash +pairs+
- #
- # Given the following configuration being created:
- #
- # config = OpenSSL::Config.new
- # #=> #
- # config['default'] = {"foo"=>"bar","baz"=>"buz"}
- # #=> {"foo"=>"bar", "baz"=>"buz"}
- # puts config.to_s
- # #=> [ default ]
- # # foo=bar
- # # baz=buz
- #
- # It's important to note that this will essentially merge any of the keys
- # in +pairs+ with the existing +section+. For example:
- #
- # config['default']
- # #=> {"foo"=>"bar", "baz"=>"buz"}
- # config['default'] = {"foo" => "changed"}
- # #=> {"foo"=>"changed"}
- # config['default']
- # #=> {"foo"=>"changed", "baz"=>"buz"}
- #
- def []=(section, pairs)
- check_modify
- @data[section] ||= {}
- pairs.each do |key, value|
- self.add_value(section, key, value)
- end
- end
-
- ##
- # Get the names of all sections in the current configuration
- def sections
- @data.keys
- end
-
- ##
- # Get the parsable form of the current configuration
- #
- # Given the following configuration being created:
- #
- # config = OpenSSL::Config.new
- # #=> #
- # config['default'] = {"foo"=>"bar","baz"=>"buz"}
- # #=> {"foo"=>"bar", "baz"=>"buz"}
- # puts config.to_s
- # #=> [ default ]
- # # foo=bar
- # # baz=buz
- #
- # You can parse get the serialized configuration using #to_s and then parse
- # it later:
- #
- # serialized_config = config.to_s
- # # much later...
- # new_config = OpenSSL::Config.parse(serialized_config)
- # #=> #
- # puts new_config
- # #=> [ default ]
- # foo=bar
- # baz=buz
- #
- def to_s
- ary = []
- @data.keys.sort.each do |section|
- ary << "[ #{section} ]\n"
- @data[section].keys.each do |key|
- ary << "#{key}=#{@data[section][key]}\n"
- end
- ary << "\n"
- end
- ary.join
- end
-
- ##
- # For a block.
- #
- # Receive the section and its pairs for the current configuration.
- #
- # config.each do |section, key, value|
- # # ...
- # end
- #
- def each
- @data.each do |section, hash|
- hash.each do |key, value|
- yield [section, key, value]
- end
- end
- end
-
- ##
- # String representation of this configuration object, including the class
- # name and its sections.
- def inspect
- "#<#{self.class.name} sections=#{sections.inspect}>"
- end
-
- protected
-
- def data # :nodoc:
- @data
- end
-
- private
-
- def initialize_copy(other)
- @data = other.data.dup
- end
-
- def check_modify
- raise TypeError.new("Insecure: can't modify OpenSSL config") if frozen?
- end
-
- def get_key_string(section, key)
- Config.get_key_string(@data, section, key)
- end
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/openssl/digest.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/openssl/digest.rb
deleted file mode 100755
index f63892a6d..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/openssl/digest.rb
+++ /dev/null
@@ -1,88 +0,0 @@
-#--
-#
-# $RCSfile$
-#
-# = Ruby-space predefined Digest subclasses
-#
-# = Info
-# 'OpenSSL for Ruby 2' project
-# Copyright (C) 2002 Michal Rokos
-# All rights reserved.
-#
-# = Licence
-# This program is licenced under the same licence as Ruby.
-# (See the file 'LICENCE'.)
-#
-# = Version
-# $Id: digest.rb 44116 2013-12-10 07:16:03Z nobu $
-#
-#++
-
-module OpenSSL
- class Digest
-
- alg = %w(DSS DSS1 MD2 MD4 MD5 MDC2 RIPEMD160 SHA SHA1)
- if OPENSSL_VERSION_NUMBER > 0x00908000
- alg += %w(SHA224 SHA256 SHA384 SHA512)
- end
-
- # Return the +data+ hash computed with +name+ Digest. +name+ is either the
- # long name or short name of a supported digest algorithm.
- #
- # === Examples
- #
- # OpenSSL::Digest.digest("SHA256", "abc")
- #
- # which is equivalent to:
- #
- # OpenSSL::Digest::SHA256.digest("abc")
-
- def self.digest(name, data)
- super(data, name)
- end
-
- alg.each{|name|
- klass = Class.new(self) {
- define_method(:initialize, ->(data = nil) {super(name, data)})
- }
- singleton = (class << klass; self; end)
- singleton.class_eval{
- define_method(:digest){|data| new.digest(data) }
- define_method(:hexdigest){|data| new.hexdigest(data) }
- }
- const_set(name, klass)
- }
-
- # Deprecated.
- #
- # This class is only provided for backwards compatibility.
- class Digest < Digest # :nodoc:
- # Deprecated.
- #
- # See OpenSSL::Digest.new
- def initialize(*args)
- warn('Digest::Digest is deprecated; use Digest')
- super(*args)
- end
- end
-
- end # Digest
-
- # Returns a Digest subclass by +name+.
- #
- # require 'openssl'
- #
- # OpenSSL::Digest("MD5")
- # # => OpenSSL::Digest::MD5
- #
- # Digest("Foo")
- # # => NameError: wrong constant name Foo
-
- def Digest(name)
- OpenSSL::Digest.const_get(name)
- end
-
- module_function :Digest
-
-end # OpenSSL
-
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/openssl/ssl.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/openssl/ssl.rb
deleted file mode 100755
index fdd037bc5..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/openssl/ssl.rb
+++ /dev/null
@@ -1,324 +0,0 @@
-=begin
-= $RCSfile$ -- Ruby-space definitions that completes C-space funcs for SSL
-
-= Info
- 'OpenSSL for Ruby 2' project
- Copyright (C) 2001 GOTOU YUUZOU
- All rights reserved.
-
-= Licence
- This program is licenced under the same licence as Ruby.
- (See the file 'LICENCE'.)
-
-= Version
- $Id: ssl.rb 51554 2015-08-12 15:16:42Z nagachika $
-=end
-
-require "openssl/buffering"
-require "fcntl"
-
-module OpenSSL
- module SSL
- class SSLContext
- DEFAULT_PARAMS = {
- :ssl_version => "SSLv23",
- :verify_mode => OpenSSL::SSL::VERIFY_PEER,
- :ciphers => %w{
- ECDHE-ECDSA-AES128-GCM-SHA256
- ECDHE-RSA-AES128-GCM-SHA256
- ECDHE-ECDSA-AES256-GCM-SHA384
- ECDHE-RSA-AES256-GCM-SHA384
- DHE-RSA-AES128-GCM-SHA256
- DHE-DSS-AES128-GCM-SHA256
- DHE-RSA-AES256-GCM-SHA384
- DHE-DSS-AES256-GCM-SHA384
- ECDHE-ECDSA-AES128-SHA256
- ECDHE-RSA-AES128-SHA256
- ECDHE-ECDSA-AES128-SHA
- ECDHE-RSA-AES128-SHA
- ECDHE-ECDSA-AES256-SHA384
- ECDHE-RSA-AES256-SHA384
- ECDHE-ECDSA-AES256-SHA
- ECDHE-RSA-AES256-SHA
- DHE-RSA-AES128-SHA256
- DHE-RSA-AES256-SHA256
- DHE-RSA-AES128-SHA
- DHE-RSA-AES256-SHA
- DHE-DSS-AES128-SHA256
- DHE-DSS-AES256-SHA256
- DHE-DSS-AES128-SHA
- DHE-DSS-AES256-SHA
- AES128-GCM-SHA256
- AES256-GCM-SHA384
- AES128-SHA256
- AES256-SHA256
- AES128-SHA
- AES256-SHA
- ECDHE-ECDSA-RC4-SHA
- ECDHE-RSA-RC4-SHA
- RC4-SHA
- }.join(":"),
- :options => -> {
- opts = OpenSSL::SSL::OP_ALL
- opts &= ~OpenSSL::SSL::OP_DONT_INSERT_EMPTY_FRAGMENTS if defined?(OpenSSL::SSL::OP_DONT_INSERT_EMPTY_FRAGMENTS)
- opts |= OpenSSL::SSL::OP_NO_COMPRESSION if defined?(OpenSSL::SSL::OP_NO_COMPRESSION)
- opts |= OpenSSL::SSL::OP_NO_SSLv2 if defined?(OpenSSL::SSL::OP_NO_SSLv2)
- opts |= OpenSSL::SSL::OP_NO_SSLv3 if defined?(OpenSSL::SSL::OP_NO_SSLv3)
- opts
- }.call
- }
-
- DEFAULT_CERT_STORE = OpenSSL::X509::Store.new
- DEFAULT_CERT_STORE.set_default_paths
- if defined?(OpenSSL::X509::V_FLAG_CRL_CHECK_ALL)
- DEFAULT_CERT_STORE.flags = OpenSSL::X509::V_FLAG_CRL_CHECK_ALL
- end
-
- ##
- # Sets the parameters for this SSL context to the values in +params+.
- # The keys in +params+ must be assignment methods on SSLContext.
- #
- # If the verify_mode is not VERIFY_NONE and ca_file, ca_path and
- # cert_store are not set then the system default certificate store is
- # used.
-
- def set_params(params={})
- params = DEFAULT_PARAMS.merge(params)
- params.each{|name, value| self.__send__("#{name}=", value) }
- if self.verify_mode != OpenSSL::SSL::VERIFY_NONE
- unless self.ca_file or self.ca_path or self.cert_store
- self.cert_store = DEFAULT_CERT_STORE
- end
- end
- return params
- end
- end
-
- module SocketForwarder
- def addr
- to_io.addr
- end
-
- def peeraddr
- to_io.peeraddr
- end
-
- def setsockopt(level, optname, optval)
- to_io.setsockopt(level, optname, optval)
- end
-
- def getsockopt(level, optname)
- to_io.getsockopt(level, optname)
- end
-
- def fcntl(*args)
- to_io.fcntl(*args)
- end
-
- def closed?
- to_io.closed?
- end
-
- def do_not_reverse_lookup=(flag)
- to_io.do_not_reverse_lookup = flag
- end
- end
-
- module Nonblock
- def initialize(*args)
- flag = File::NONBLOCK
- flag |= @io.fcntl(Fcntl::F_GETFL) if defined?(Fcntl::F_GETFL)
- @io.fcntl(Fcntl::F_SETFL, flag)
- super
- end
- end
-
- def verify_certificate_identity(cert, hostname)
- should_verify_common_name = true
- cert.extensions.each{|ext|
- next if ext.oid != "subjectAltName"
- ostr = OpenSSL::ASN1.decode(ext.to_der).value.last
- sequence = OpenSSL::ASN1.decode(ostr.value)
- sequence.value.each{|san|
- case san.tag
- when 2 # dNSName in GeneralName (RFC5280)
- should_verify_common_name = false
- return true if verify_hostname(hostname, san.value)
- when 7 # iPAddress in GeneralName (RFC5280)
- should_verify_common_name = false
- # follows GENERAL_NAME_print() in x509v3/v3_alt.c
- if san.value.size == 4
- return true if san.value.unpack('C*').join('.') == hostname
- elsif san.value.size == 16
- return true if san.value.unpack('n*').map { |e| sprintf("%X", e) }.join(':') == hostname
- end
- end
- }
- }
- if should_verify_common_name
- cert.subject.to_a.each{|oid, value|
- if oid == "CN"
- return true if verify_hostname(hostname, value)
- end
- }
- end
- return false
- end
- module_function :verify_certificate_identity
-
- def verify_hostname(hostname, san) # :nodoc:
- # RFC 5280, IA5String is limited to the set of ASCII characters
- return false unless san.ascii_only?
- return false unless hostname.ascii_only?
-
- # See RFC 6125, section 6.4.1
- # Matching is case-insensitive.
- san_parts = san.downcase.split(".")
-
- # TODO: this behavior should probably be more strict
- return san == hostname if san_parts.size < 2
-
- # Matching is case-insensitive.
- host_parts = hostname.downcase.split(".")
-
- # RFC 6125, section 6.4.3, subitem 2.
- # If the wildcard character is the only character of the left-most
- # label in the presented identifier, the client SHOULD NOT compare
- # against anything but the left-most label of the reference
- # identifier (e.g., *.example.com would match foo.example.com but
- # not bar.foo.example.com or example.com).
- return false unless san_parts.size == host_parts.size
-
- # RFC 6125, section 6.4.3, subitem 1.
- # The client SHOULD NOT attempt to match a presented identifier in
- # which the wildcard character comprises a label other than the
- # left-most label (e.g., do not match bar.*.example.net).
- return false unless verify_wildcard(host_parts.shift, san_parts.shift)
-
- san_parts.join(".") == host_parts.join(".")
- end
- module_function :verify_hostname
-
- def verify_wildcard(domain_component, san_component) # :nodoc:
- parts = san_component.split("*", -1)
-
- return false if parts.size > 2
- return san_component == domain_component if parts.size == 1
-
- # RFC 6125, section 6.4.3, subitem 3.
- # The client SHOULD NOT attempt to match a presented identifier
- # where the wildcard character is embedded within an A-label or
- # U-label of an internationalized domain name.
- return false if domain_component.start_with?("xn--") && san_component != "*"
-
- parts[0].length + parts[1].length < domain_component.length &&
- domain_component.start_with?(parts[0]) &&
- domain_component.end_with?(parts[1])
- end
- module_function :verify_wildcard
-
- class SSLSocket
- include Buffering
- include SocketForwarder
- include Nonblock
-
- ##
- # Perform hostname verification after an SSL connection is established
- #
- # This method MUST be called after calling #connect to ensure that the
- # hostname of a remote peer has been verified.
- def post_connection_check(hostname)
- if peer_cert.nil?
- msg = "Peer verification enabled, but no certificate received."
- if using_anon_cipher?
- msg += " Anonymous cipher suite #{cipher[0]} was negotiated. Anonymous suites must be disabled to use peer verification."
- end
- raise SSLError, msg
- end
-
- unless OpenSSL::SSL.verify_certificate_identity(peer_cert, hostname)
- raise SSLError, "hostname \"#{hostname}\" does not match the server certificate"
- end
- return true
- end
-
- def session
- SSL::Session.new(self)
- rescue SSL::Session::SessionError
- nil
- end
-
- private
-
- def using_anon_cipher?
- ctx = OpenSSL::SSL::SSLContext.new
- ctx.ciphers = "aNULL"
- ctx.ciphers.include?(cipher)
- end
- end
-
- ##
- # SSLServer represents a TCP/IP server socket with Secure Sockets Layer.
- class SSLServer
- include SocketForwarder
- # When true then #accept works exactly the same as TCPServer#accept
- attr_accessor :start_immediately
-
- # Creates a new instance of SSLServer.
- # * +srv+ is an instance of TCPServer.
- # * +ctx+ is an instance of OpenSSL::SSL::SSLContext.
- def initialize(svr, ctx)
- @svr = svr
- @ctx = ctx
- unless ctx.session_id_context
- # see #6137 - session id may not exceed 32 bytes
- prng = ::Random.new($0.hash)
- session_id = prng.bytes(16).unpack('H*')[0]
- @ctx.session_id_context = session_id
- end
- @start_immediately = true
- end
-
- # Returns the TCPServer passed to the SSLServer when initialized.
- def to_io
- @svr
- end
-
- # See TCPServer#listen for details.
- def listen(backlog=5)
- @svr.listen(backlog)
- end
-
- # See BasicSocket#shutdown for details.
- def shutdown(how=Socket::SHUT_RDWR)
- @svr.shutdown(how)
- end
-
- # Works similar to TCPServer#accept.
- def accept
- # Socket#accept returns [socket, addrinfo].
- # TCPServer#accept returns a socket.
- # The following comma strips addrinfo.
- sock, = @svr.accept
- begin
- ssl = OpenSSL::SSL::SSLSocket.new(sock, @ctx)
- ssl.sync_close = true
- ssl.accept if @start_immediately
- ssl
- rescue Exception => ex
- if ssl
- ssl.close
- else
- sock.close
- end
- raise ex
- end
- end
-
- # See IO#close for details.
- def close
- @svr.close
- end
- end
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/openssl/x509.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/openssl/x509.rb
deleted file mode 100755
index bdeadb12f..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/openssl/x509.rb
+++ /dev/null
@@ -1,182 +0,0 @@
-#--
-#
-# $RCSfile$
-#
-# = Ruby-space definitions that completes C-space funcs for X509 and subclasses
-#
-# = Info
-# 'OpenSSL for Ruby 2' project
-# Copyright (C) 2002 Michal Rokos
-# All rights reserved.
-#
-# = Licence
-# This program is licenced under the same licence as Ruby.
-# (See the file 'LICENCE'.)
-#
-# = Version
-# $Id: x509.rb 48521 2014-11-20 15:39:03Z usa $
-#
-#++
-
-module OpenSSL
- module X509
- class ExtensionFactory
- def create_extension(*arg)
- if arg.size > 1
- create_ext(*arg)
- else
- send("create_ext_from_"+arg[0].class.name.downcase, arg[0])
- end
- end
-
- def create_ext_from_array(ary)
- raise ExtensionError, "unexpected array form" if ary.size > 3
- create_ext(ary[0], ary[1], ary[2])
- end
-
- def create_ext_from_string(str) # "oid = critical, value"
- oid, value = str.split(/=/, 2)
- oid.strip!
- value.strip!
- create_ext(oid, value)
- end
-
- def create_ext_from_hash(hash)
- create_ext(hash["oid"], hash["value"], hash["critical"])
- end
- end
-
- class Extension
- def to_s # "oid = critical, value"
- str = self.oid
- str << " = "
- str << "critical, " if self.critical?
- str << self.value.gsub(/\n/, ", ")
- end
-
- def to_h # {"oid"=>sn|ln, "value"=>value, "critical"=>true|false}
- {"oid"=>self.oid,"value"=>self.value,"critical"=>self.critical?}
- end
-
- def to_a
- [ self.oid, self.value, self.critical? ]
- end
- end
-
- class Name
- module RFC2253DN
- Special = ',=+<>#;'
- HexChar = /[0-9a-fA-F]/
- HexPair = /#{HexChar}#{HexChar}/
- HexString = /#{HexPair}+/
- Pair = /\\(?:[#{Special}]|\\|"|#{HexPair})/
- StringChar = /[^\\"#{Special}]/
- QuoteChar = /[^\\"]/
- AttributeType = /[a-zA-Z][0-9a-zA-Z]*|[0-9]+(?:\.[0-9]+)*/
- AttributeValue = /
- (?!["#])((?:#{StringChar}|#{Pair})*)|
- \#(#{HexString})|
- "((?:#{QuoteChar}|#{Pair})*)"
- /x
- TypeAndValue = /\A(#{AttributeType})=#{AttributeValue}/
-
- module_function
-
- def expand_pair(str)
- return nil unless str
- return str.gsub(Pair){
- pair = $&
- case pair.size
- when 2 then pair[1,1]
- when 3 then Integer("0x#{pair[1,2]}").chr
- else raise OpenSSL::X509::NameError, "invalid pair: #{str}"
- end
- }
- end
-
- def expand_hexstring(str)
- return nil unless str
- der = str.gsub(HexPair){$&.to_i(16).chr }
- a1 = OpenSSL::ASN1.decode(der)
- return a1.value, a1.tag
- end
-
- def expand_value(str1, str2, str3)
- value = expand_pair(str1)
- value, tag = expand_hexstring(str2) unless value
- value = expand_pair(str3) unless value
- return value, tag
- end
-
- def scan(dn)
- str = dn
- ary = []
- while true
- if md = TypeAndValue.match(str)
- remain = md.post_match
- type = md[1]
- value, tag = expand_value(md[2], md[3], md[4]) rescue nil
- if value
- type_and_value = [type, value]
- type_and_value.push(tag) if tag
- ary.unshift(type_and_value)
- if remain.length > 2 && remain[0] == ?,
- str = remain[1..-1]
- next
- elsif remain.length > 2 && remain[0] == ?+
- raise OpenSSL::X509::NameError,
- "multi-valued RDN is not supported: #{dn}"
- elsif remain.empty?
- break
- end
- end
- end
- msg_dn = dn[0, dn.length - str.length] + " =>" + str
- raise OpenSSL::X509::NameError, "malformed RDN: #{msg_dn}"
- end
- return ary
- end
- end
-
- class << self
- def parse_rfc2253(str, template=OBJECT_TYPE_TEMPLATE)
- ary = OpenSSL::X509::Name::RFC2253DN.scan(str)
- self.new(ary, template)
- end
-
- def parse_openssl(str, template=OBJECT_TYPE_TEMPLATE)
- ary = str.scan(/\s*([^\/,]+)\s*/).collect{|i| i[0].split("=", 2) }
- self.new(ary, template)
- end
-
- alias parse parse_openssl
- end
-
- def pretty_print(q)
- q.object_group(self) {
- q.text ' '
- q.text to_s(OpenSSL::X509::Name::RFC2253)
- }
- end
- end
-
- class StoreContext
- def cleanup
- warn "(#{caller.first}) OpenSSL::X509::StoreContext#cleanup is deprecated with no replacement" if $VERBOSE
- end
- end
-
- class Certificate
- def pretty_print(q)
- q.object_group(self) {
- q.breakable
- q.text 'subject='; q.pp self.subject; q.text ','; q.breakable
- q.text 'issuer='; q.pp self.issuer; q.text ','; q.breakable
- q.text 'serial='; q.pp self.serial; q.text ','; q.breakable
- q.text 'not_before='; q.pp self.not_before; q.text ','; q.breakable
- q.text 'not_after='; q.pp self.not_after
- }
- end
- end
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/optionparser.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/optionparser.rb
deleted file mode 100755
index d89a4d22f..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/optionparser.rb
+++ /dev/null
@@ -1 +0,0 @@
-require_relative 'optparse'
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/optparse.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/optparse.rb
deleted file mode 100755
index 4ec891e3a..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/optparse.rb
+++ /dev/null
@@ -1,1997 +0,0 @@
-#
-# optparse.rb - command-line option analysis with the OptionParser class.
-#
-# Author:: Nobu Nakada
-# Documentation:: Nobu Nakada and Gavin Sinclair.
-#
-# See OptionParser for documentation.
-#
-
-
-#--
-# == Developer Documentation (not for RDoc output)
-#
-# === Class tree
-#
-# - OptionParser:: front end
-# - OptionParser::Switch:: each switches
-# - OptionParser::List:: options list
-# - OptionParser::ParseError:: errors on parsing
-# - OptionParser::AmbiguousOption
-# - OptionParser::NeedlessArgument
-# - OptionParser::MissingArgument
-# - OptionParser::InvalidOption
-# - OptionParser::InvalidArgument
-# - OptionParser::AmbiguousArgument
-#
-# === Object relationship diagram
-#
-# +--------------+
-# | OptionParser |<>-----+
-# +--------------+ | +--------+
-# | ,-| Switch |
-# on_head -------->+---------------+ / +--------+
-# accept/reject -->| List |<|>-
-# | |<|>- +----------+
-# on ------------->+---------------+ `-| argument |
-# : : | class |
-# +---------------+ |==========|
-# on_tail -------->| | |pattern |
-# +---------------+ |----------|
-# OptionParser.accept ->| DefaultList | |converter |
-# reject |(shared between| +----------+
-# | all instances)|
-# +---------------+
-#
-#++
-#
-# == OptionParser
-#
-# === Introduction
-#
-# OptionParser is a class for command-line option analysis. It is much more
-# advanced, yet also easier to use, than GetoptLong, and is a more Ruby-oriented
-# solution.
-#
-# === Features
-#
-# 1. The argument specification and the code to handle it are written in the
-# same place.
-# 2. It can output an option summary; you don't need to maintain this string
-# separately.
-# 3. Optional and mandatory arguments are specified very gracefully.
-# 4. Arguments can be automatically converted to a specified class.
-# 5. Arguments can be restricted to a certain set.
-#
-# All of these features are demonstrated in the examples below. See
-# #make_switch for full documentation.
-#
-# === Minimal example
-#
-# require 'optparse'
-#
-# options = {}
-# OptionParser.new do |opts|
-# opts.banner = "Usage: example.rb [options]"
-#
-# opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
-# options[:verbose] = v
-# end
-# end.parse!
-#
-# p options
-# p ARGV
-#
-# === Generating Help
-#
-# OptionParser can be used to automatically generate help for the commands you
-# write:
-#
-# require 'optparse'
-#
-# Options = Struct.new(:name)
-#
-# class Parser
-# def self.parse(options)
-# args = Options.new("world")
-#
-# opt_parser = OptionParser.new do |opts|
-# opts.banner = "Usage: example.rb [options]"
-#
-# opts.on("-nNAME", "--name=NAME", "Name to say hello to") do |n|
-# args.name = n
-# end
-#
-# opts.on("-h", "--help", "Prints this help") do
-# puts opts
-# exit
-# end
-# end
-#
-# opt_parser.parse!(options)
-# return args
-# end
-# end
-# options = Parser.parse %w[--help]
-#
-# #=>
-# # Usage: example.rb [options]
-# # -n, --name=NAME Name to say hello to
-# # -h, --help Prints this help#
-#
-# === Complete example
-#
-# The following example is a complete Ruby program. You can run it and see the
-# effect of specifying various options. This is probably the best way to learn
-# the features of +optparse+.
-#
-# require 'optparse'
-# require 'optparse/time'
-# require 'ostruct'
-# require 'pp'
-#
-# class OptparseExample
-#
-# CODES = %w[iso-2022-jp shift_jis euc-jp utf8 binary]
-# CODE_ALIASES = { "jis" => "iso-2022-jp", "sjis" => "shift_jis" }
-#
-# #
-# # Return a structure describing the options.
-# #
-# def self.parse(args)
-# # The options specified on the command line will be collected in *options*.
-# # We set default values here.
-# options = OpenStruct.new
-# options.library = []
-# options.inplace = false
-# options.encoding = "utf8"
-# options.transfer_type = :auto
-# options.verbose = false
-#
-# opt_parser = OptionParser.new do |opts|
-# opts.banner = "Usage: example.rb [options]"
-#
-# opts.separator ""
-# opts.separator "Specific options:"
-#
-# # Mandatory argument.
-# opts.on("-r", "--require LIBRARY",
-# "Require the LIBRARY before executing your script") do |lib|
-# options.library << lib
-# end
-#
-# # Optional argument; multi-line description.
-# opts.on("-i", "--inplace [EXTENSION]",
-# "Edit ARGV files in place",
-# " (make backup if EXTENSION supplied)") do |ext|
-# options.inplace = true
-# options.extension = ext || ''
-# options.extension.sub!(/\A\.?(?=.)/, ".") # Ensure extension begins with dot.
-# end
-#
-# # Cast 'delay' argument to a Float.
-# opts.on("--delay N", Float, "Delay N seconds before executing") do |n|
-# options.delay = n
-# end
-#
-# # Cast 'time' argument to a Time object.
-# opts.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time|
-# options.time = time
-# end
-#
-# # Cast to octal integer.
-# opts.on("-F", "--irs [OCTAL]", OptionParser::OctalInteger,
-# "Specify record separator (default \\0)") do |rs|
-# options.record_separator = rs
-# end
-#
-# # List of arguments.
-# opts.on("--list x,y,z", Array, "Example 'list' of arguments") do |list|
-# options.list = list
-# end
-#
-# # Keyword completion. We are specifying a specific set of arguments (CODES
-# # and CODE_ALIASES - notice the latter is a Hash), and the user may provide
-# # the shortest unambiguous text.
-# code_list = (CODE_ALIASES.keys + CODES).join(',')
-# opts.on("--code CODE", CODES, CODE_ALIASES, "Select encoding",
-# " (#{code_list})") do |encoding|
-# options.encoding = encoding
-# end
-#
-# # Optional argument with keyword completion.
-# opts.on("--type [TYPE]", [:text, :binary, :auto],
-# "Select transfer type (text, binary, auto)") do |t|
-# options.transfer_type = t
-# end
-#
-# # Boolean switch.
-# opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
-# options.verbose = v
-# end
-#
-# opts.separator ""
-# opts.separator "Common options:"
-#
-# # No argument, shows at tail. This will print an options summary.
-# # Try it and see!
-# opts.on_tail("-h", "--help", "Show this message") do
-# puts opts
-# exit
-# end
-#
-# # Another typical switch to print the version.
-# opts.on_tail("--version", "Show version") do
-# puts ::Version.join('.')
-# exit
-# end
-# end
-#
-# opt_parser.parse!(args)
-# options
-# end # parse()
-#
-# end # class OptparseExample
-#
-# options = OptparseExample.parse(ARGV)
-# pp options
-# pp ARGV
-#
-# === Shell Completion
-#
-# For modern shells (e.g. bash, zsh, etc.), you can use shell
-# completion for command line options.
-#
-# === Further documentation
-#
-# The above examples should be enough to learn how to use this class. If you
-# have any questions, file a ticket at http://bugs.ruby-lang.org.
-#
-class OptionParser
- # :stopdoc:
- NoArgument = [NO_ARGUMENT = :NONE, nil].freeze
- RequiredArgument = [REQUIRED_ARGUMENT = :REQUIRED, true].freeze
- OptionalArgument = [OPTIONAL_ARGUMENT = :OPTIONAL, false].freeze
- # :startdoc:
-
- #
- # Keyword completion module. This allows partial arguments to be specified
- # and resolved against a list of acceptable values.
- #
- module Completion
- def self.regexp(key, icase)
- Regexp.new('\A' + Regexp.quote(key).gsub(/\w+\b/, '\&\w*'), icase)
- end
-
- def self.candidate(key, icase = false, pat = nil, &block)
- pat ||= Completion.regexp(key, icase)
- candidates = []
- block.call do |k, *v|
- (if Regexp === k
- kn = nil
- k === key
- else
- kn = defined?(k.id2name) ? k.id2name : k
- pat === kn
- end) or next
- v << k if v.empty?
- candidates << [k, v, kn]
- end
- candidates
- end
-
- def candidate(key, icase = false, pat = nil)
- Completion.candidate(key, icase, pat, &method(:each))
- end
-
- public
- def complete(key, icase = false, pat = nil)
- candidates = candidate(key, icase, pat, &method(:each)).sort_by {|k, v, kn| kn.size}
- if candidates.size == 1
- canon, sw, * = candidates[0]
- elsif candidates.size > 1
- canon, sw, cn = candidates.shift
- candidates.each do |k, v, kn|
- next if sw == v
- if String === cn and String === kn
- if cn.rindex(kn, 0)
- canon, sw, cn = k, v, kn
- next
- elsif kn.rindex(cn, 0)
- next
- end
- end
- throw :ambiguous, key
- end
- end
- if canon
- block_given? or return key, *sw
- yield(key, *sw)
- end
- end
-
- def convert(opt = nil, val = nil, *)
- val
- end
- end
-
-
- #
- # Map from option/keyword string to object with completion.
- #
- class OptionMap < Hash
- include Completion
- end
-
-
- #
- # Individual switch class. Not important to the user.
- #
- # Defined within Switch are several Switch-derived classes: NoArgument,
- # RequiredArgument, etc.
- #
- class Switch
- attr_reader :pattern, :conv, :short, :long, :arg, :desc, :block
-
- #
- # Guesses argument style from +arg+. Returns corresponding
- # OptionParser::Switch class (OptionalArgument, etc.).
- #
- def self.guess(arg)
- case arg
- when ""
- t = self
- when /\A=?\[/
- t = Switch::OptionalArgument
- when /\A\s+\[/
- t = Switch::PlacedArgument
- else
- t = Switch::RequiredArgument
- end
- self >= t or incompatible_argument_styles(arg, t)
- t
- end
-
- def self.incompatible_argument_styles(arg, t)
- raise(ArgumentError, "#{arg}: incompatible argument styles\n #{self}, #{t}",
- ParseError.filter_backtrace(caller(2)))
- end
-
- def self.pattern
- NilClass
- end
-
- def initialize(pattern = nil, conv = nil,
- short = nil, long = nil, arg = nil,
- desc = ([] if short or long), block = Proc.new)
- raise if Array === pattern
- @pattern, @conv, @short, @long, @arg, @desc, @block =
- pattern, conv, short, long, arg, desc, block
- end
-
- #
- # Parses +arg+ and returns rest of +arg+ and matched portion to the
- # argument pattern. Yields when the pattern doesn't match substring.
- #
- def parse_arg(arg)
- pattern or return nil, [arg]
- unless m = pattern.match(arg)
- yield(InvalidArgument, arg)
- return arg, []
- end
- if String === m
- m = [s = m]
- else
- m = m.to_a
- s = m[0]
- return nil, m unless String === s
- end
- raise InvalidArgument, arg unless arg.rindex(s, 0)
- return nil, m if s.length == arg.length
- yield(InvalidArgument, arg) # didn't match whole arg
- return arg[s.length..-1], m
- end
- private :parse_arg
-
- #
- # Parses argument, converts and returns +arg+, +block+ and result of
- # conversion. Yields at semi-error condition instead of raising an
- # exception.
- #
- def conv_arg(arg, val = [])
- if conv
- val = conv.call(*val)
- else
- val = proc {|v| v}.call(*val)
- end
- return arg, block, val
- end
- private :conv_arg
-
- #
- # Produces the summary text. Each line of the summary is yielded to the
- # block (without newline).
- #
- # +sdone+:: Already summarized short style options keyed hash.
- # +ldone+:: Already summarized long style options keyed hash.
- # +width+:: Width of left side (option part). In other words, the right
- # side (description part) starts after +width+ columns.
- # +max+:: Maximum width of left side -> the options are filled within
- # +max+ columns.
- # +indent+:: Prefix string indents all summarized lines.
- #
- def summarize(sdone = [], ldone = [], width = 1, max = width - 1, indent = "")
- sopts, lopts = [], [], nil
- @short.each {|s| sdone.fetch(s) {sopts << s}; sdone[s] = true} if @short
- @long.each {|s| ldone.fetch(s) {lopts << s}; ldone[s] = true} if @long
- return if sopts.empty? and lopts.empty? # completely hidden
-
- left = [sopts.join(', ')]
- right = desc.dup
-
- while s = lopts.shift
- l = left[-1].length + s.length
- l += arg.length if left.size == 1 && arg
- l < max or sopts.empty? or left << ''
- left[-1] << if left[-1].empty? then ' ' * 4 else ', ' end << s
- end
-
- if arg
- left[0] << (left[1] ? arg.sub(/\A(\[?)=/, '\1') + ',' : arg)
- end
- mlen = left.collect {|ss| ss.length}.max.to_i
- while mlen > width and l = left.shift
- mlen = left.collect {|ss| ss.length}.max.to_i if l.length == mlen
- if l.length < width and (r = right[0]) and !r.empty?
- l = l.to_s.ljust(width) + ' ' + r
- right.shift
- end
- yield(indent + l)
- end
-
- while begin l = left.shift; r = right.shift; l or r end
- l = l.to_s.ljust(width) + ' ' + r if r and !r.empty?
- yield(indent + l)
- end
-
- self
- end
-
- def add_banner(to) # :nodoc:
- unless @short or @long
- s = desc.join
- to << " [" + s + "]..." unless s.empty?
- end
- to
- end
-
- def match_nonswitch?(str) # :nodoc:
- @pattern =~ str unless @short or @long
- end
-
- #
- # Main name of the switch.
- #
- def switch_name
- (long.first || short.first).sub(/\A-+(?:\[no-\])?/, '')
- end
-
- def compsys(sdone, ldone) # :nodoc:
- sopts, lopts = [], []
- @short.each {|s| sdone.fetch(s) {sopts << s}; sdone[s] = true} if @short
- @long.each {|s| ldone.fetch(s) {lopts << s}; ldone[s] = true} if @long
- return if sopts.empty? and lopts.empty? # completely hidden
-
- (sopts+lopts).each do |opt|
- # "(-x -c -r)-l[left justify]" \
- if /^--\[no-\](.+)$/ =~ opt
- o = $1
- yield("--#{o}", desc.join(""))
- yield("--no-#{o}", desc.join(""))
- else
- yield("#{opt}", desc.join(""))
- end
- end
- end
-
- #
- # Switch that takes no arguments.
- #
- class NoArgument < self
-
- #
- # Raises an exception if any arguments given.
- #
- def parse(arg, argv)
- yield(NeedlessArgument, arg) if arg
- conv_arg(arg)
- end
-
- def self.incompatible_argument_styles(*)
- end
-
- def self.pattern
- Object
- end
- end
-
- #
- # Switch that takes an argument.
- #
- class RequiredArgument < self
-
- #
- # Raises an exception if argument is not present.
- #
- def parse(arg, argv)
- unless arg
- raise MissingArgument if argv.empty?
- arg = argv.shift
- end
- conv_arg(*parse_arg(arg, &method(:raise)))
- end
- end
-
- #
- # Switch that can omit argument.
- #
- class OptionalArgument < self
-
- #
- # Parses argument if given, or uses default value.
- #
- def parse(arg, argv, &error)
- if arg
- conv_arg(*parse_arg(arg, &error))
- else
- conv_arg(arg)
- end
- end
- end
-
- #
- # Switch that takes an argument, which does not begin with '-'.
- #
- class PlacedArgument < self
-
- #
- # Returns nil if argument is not present or begins with '-'.
- #
- def parse(arg, argv, &error)
- if !(val = arg) and (argv.empty? or /\A-/ =~ (val = argv[0]))
- return nil, block, nil
- end
- opt = (val = parse_arg(val, &error))[1]
- val = conv_arg(*val)
- if opt and !arg
- argv.shift
- else
- val[0] = nil
- end
- val
- end
- end
- end
-
- #
- # Simple option list providing mapping from short and/or long option
- # string to OptionParser::Switch and mapping from acceptable argument to
- # matching pattern and converter pair. Also provides summary feature.
- #
- class List
- # Map from acceptable argument types to pattern and converter pairs.
- attr_reader :atype
-
- # Map from short style option switches to actual switch objects.
- attr_reader :short
-
- # Map from long style option switches to actual switch objects.
- attr_reader :long
-
- # List of all switches and summary string.
- attr_reader :list
-
- #
- # Just initializes all instance variables.
- #
- def initialize
- @atype = {}
- @short = OptionMap.new
- @long = OptionMap.new
- @list = []
- end
-
- #
- # See OptionParser.accept.
- #
- def accept(t, pat = /.*/m, &block)
- if pat
- pat.respond_to?(:match) or
- raise TypeError, "has no `match'", ParseError.filter_backtrace(caller(2))
- else
- pat = t if t.respond_to?(:match)
- end
- unless block
- block = pat.method(:convert).to_proc if pat.respond_to?(:convert)
- end
- @atype[t] = [pat, block]
- end
-
- #
- # See OptionParser.reject.
- #
- def reject(t)
- @atype.delete(t)
- end
-
- #
- # Adds +sw+ according to +sopts+, +lopts+ and +nlopts+.
- #
- # +sw+:: OptionParser::Switch instance to be added.
- # +sopts+:: Short style option list.
- # +lopts+:: Long style option list.
- # +nlopts+:: Negated long style options list.
- #
- def update(sw, sopts, lopts, nsw = nil, nlopts = nil)
- sopts.each {|o| @short[o] = sw} if sopts
- lopts.each {|o| @long[o] = sw} if lopts
- nlopts.each {|o| @long[o] = nsw} if nsw and nlopts
- used = @short.invert.update(@long.invert)
- @list.delete_if {|o| Switch === o and !used[o]}
- end
- private :update
-
- #
- # Inserts +switch+ at the head of the list, and associates short, long
- # and negated long options. Arguments are:
- #
- # +switch+:: OptionParser::Switch instance to be inserted.
- # +short_opts+:: List of short style options.
- # +long_opts+:: List of long style options.
- # +nolong_opts+:: List of long style options with "no-" prefix.
- #
- # prepend(switch, short_opts, long_opts, nolong_opts)
- #
- def prepend(*args)
- update(*args)
- @list.unshift(args[0])
- end
-
- #
- # Appends +switch+ at the tail of the list, and associates short, long
- # and negated long options. Arguments are:
- #
- # +switch+:: OptionParser::Switch instance to be inserted.
- # +short_opts+:: List of short style options.
- # +long_opts+:: List of long style options.
- # +nolong_opts+:: List of long style options with "no-" prefix.
- #
- # append(switch, short_opts, long_opts, nolong_opts)
- #
- def append(*args)
- update(*args)
- @list.push(args[0])
- end
-
- #
- # Searches +key+ in +id+ list. The result is returned or yielded if a
- # block is given. If it isn't found, nil is returned.
- #
- def search(id, key)
- if list = __send__(id)
- val = list.fetch(key) {return nil}
- block_given? ? yield(val) : val
- end
- end
-
- #
- # Searches list +id+ for +opt+ and the optional patterns for completion
- # +pat+. If +icase+ is true, the search is case insensitive. The result
- # is returned or yielded if a block is given. If it isn't found, nil is
- # returned.
- #
- def complete(id, opt, icase = false, *pat, &block)
- __send__(id).complete(opt, icase, *pat, &block)
- end
-
- #
- # Iterates over each option, passing the option to the +block+.
- #
- def each_option(&block)
- list.each(&block)
- end
-
- #
- # Creates the summary table, passing each line to the +block+ (without
- # newline). The arguments +args+ are passed along to the summarize
- # method which is called on every option.
- #
- def summarize(*args, &block)
- sum = []
- list.reverse_each do |opt|
- if opt.respond_to?(:summarize) # perhaps OptionParser::Switch
- s = []
- opt.summarize(*args) {|l| s << l}
- sum.concat(s.reverse)
- elsif !opt or opt.empty?
- sum << ""
- elsif opt.respond_to?(:each_line)
- sum.concat([*opt.each_line].reverse)
- else
- sum.concat([*opt.each].reverse)
- end
- end
- sum.reverse_each(&block)
- end
-
- def add_banner(to) # :nodoc:
- list.each do |opt|
- if opt.respond_to?(:add_banner)
- opt.add_banner(to)
- end
- end
- to
- end
-
- def compsys(*args, &block) # :nodoc:
- list.each do |opt|
- if opt.respond_to?(:compsys)
- opt.compsys(*args, &block)
- end
- end
- end
- end
-
- #
- # Hash with completion search feature. See OptionParser::Completion.
- #
- class CompletingHash < Hash
- include Completion
-
- #
- # Completion for hash key.
- #
- def match(key)
- *values = fetch(key) {
- raise AmbiguousArgument, catch(:ambiguous) {return complete(key)}
- }
- return key, *values
- end
- end
-
- # :stopdoc:
-
- #
- # Enumeration of acceptable argument styles. Possible values are:
- #
- # NO_ARGUMENT:: The switch takes no arguments. (:NONE)
- # REQUIRED_ARGUMENT:: The switch requires an argument. (:REQUIRED)
- # OPTIONAL_ARGUMENT:: The switch requires an optional argument. (:OPTIONAL)
- #
- # Use like --switch=argument (long style) or -Xargument (short style). For
- # short style, only portion matched to argument pattern is treated as
- # argument.
- #
- ArgumentStyle = {}
- NoArgument.each {|el| ArgumentStyle[el] = Switch::NoArgument}
- RequiredArgument.each {|el| ArgumentStyle[el] = Switch::RequiredArgument}
- OptionalArgument.each {|el| ArgumentStyle[el] = Switch::OptionalArgument}
- ArgumentStyle.freeze
-
- #
- # Switches common used such as '--', and also provides default
- # argument classes
- #
- DefaultList = List.new
- DefaultList.short['-'] = Switch::NoArgument.new {}
- DefaultList.long[''] = Switch::NoArgument.new {throw :terminate}
-
-
- COMPSYS_HEADER = <<'XXX' # :nodoc:
-
-typeset -A opt_args
-local context state line
-
-_arguments -s -S \
-XXX
-
- def compsys(to, name = File.basename($0)) # :nodoc:
- to << "#compdef #{name}\n"
- to << COMPSYS_HEADER
- visit(:compsys, {}, {}) {|o, d|
- to << %Q[ "#{o}[#{d.gsub(/[\"\[\]]/, '\\\\\&')}]" \\\n]
- }
- to << " '*:file:_files' && return 0\n"
- end
-
- #
- # Default options for ARGV, which never appear in option summary.
- #
- Officious = {}
-
- #
- # --help
- # Shows option summary.
- #
- Officious['help'] = proc do |parser|
- Switch::NoArgument.new do |arg|
- puts parser.help
- exit
- end
- end
-
- #
- # --*-completion-bash=WORD
- # Shows candidates for command line completion.
- #
- Officious['*-completion-bash'] = proc do |parser|
- Switch::RequiredArgument.new do |arg|
- puts parser.candidate(arg)
- exit
- end
- end
-
- #
- # --*-completion-zsh[=NAME:FILE]
- # Creates zsh completion file.
- #
- Officious['*-completion-zsh'] = proc do |parser|
- Switch::OptionalArgument.new do |arg|
- parser.compsys(STDOUT, arg)
- exit
- end
- end
-
- #
- # --version
- # Shows version string if Version is defined.
- #
- Officious['version'] = proc do |parser|
- Switch::OptionalArgument.new do |pkg|
- if pkg
- begin
- require 'optparse/version'
- rescue LoadError
- else
- show_version(*pkg.split(/,/)) or
- abort("#{parser.program_name}: no version found in package #{pkg}")
- exit
- end
- end
- v = parser.ver or abort("#{parser.program_name}: version unknown")
- puts v
- exit
- end
- end
-
- # :startdoc:
-
- #
- # Class methods
- #
-
- #
- # Initializes a new instance and evaluates the optional block in context
- # of the instance. Arguments +args+ are passed to #new, see there for
- # description of parameters.
- #
- # This method is *deprecated*, its behavior corresponds to the older #new
- # method.
- #
- def self.with(*args, &block)
- opts = new(*args)
- opts.instance_eval(&block)
- opts
- end
-
- #
- # Returns an incremented value of +default+ according to +arg+.
- #
- def self.inc(arg, default = nil)
- case arg
- when Integer
- arg.nonzero?
- when nil
- default.to_i + 1
- end
- end
- def inc(*args)
- self.class.inc(*args)
- end
-
- #
- # Initializes the instance and yields itself if called with a block.
- #
- # +banner+:: Banner message.
- # +width+:: Summary width.
- # +indent+:: Summary indent.
- #
- def initialize(banner = nil, width = 32, indent = ' ' * 4)
- @stack = [DefaultList, List.new, List.new]
- @program_name = nil
- @banner = banner
- @summary_width = width
- @summary_indent = indent
- @default_argv = ARGV
- add_officious
- yield self if block_given?
- end
-
- def add_officious # :nodoc:
- list = base()
- Officious.each do |opt, block|
- list.long[opt] ||= block.call(self)
- end
- end
-
- #
- # Terminates option parsing. Optional parameter +arg+ is a string pushed
- # back to be the first non-option argument.
- #
- def terminate(arg = nil)
- self.class.terminate(arg)
- end
- def self.terminate(arg = nil)
- throw :terminate, arg
- end
-
- @stack = [DefaultList]
- def self.top() DefaultList end
-
- #
- # Directs to accept specified class +t+. The argument string is passed to
- # the block in which it should be converted to the desired class.
- #
- # +t+:: Argument class specifier, any object including Class.
- # +pat+:: Pattern for argument, defaults to +t+ if it responds to match.
- #
- # accept(t, pat, &block)
- #
- def accept(*args, &blk) top.accept(*args, &blk) end
- #
- # See #accept.
- #
- def self.accept(*args, &blk) top.accept(*args, &blk) end
-
- #
- # Directs to reject specified class argument.
- #
- # +t+:: Argument class specifier, any object including Class.
- #
- # reject(t)
- #
- def reject(*args, &blk) top.reject(*args, &blk) end
- #
- # See #reject.
- #
- def self.reject(*args, &blk) top.reject(*args, &blk) end
-
- #
- # Instance methods
- #
-
- # Heading banner preceding summary.
- attr_writer :banner
-
- # Program name to be emitted in error message and default banner,
- # defaults to $0.
- attr_writer :program_name
-
- # Width for option list portion of summary. Must be Numeric.
- attr_accessor :summary_width
-
- # Indentation for summary. Must be String (or have + String method).
- attr_accessor :summary_indent
-
- # Strings to be parsed in default.
- attr_accessor :default_argv
-
- #
- # Heading banner preceding summary.
- #
- def banner
- unless @banner
- @banner = "Usage: #{program_name} [options]"
- visit(:add_banner, @banner)
- end
- @banner
- end
-
- #
- # Program name to be emitted in error message and default banner, defaults
- # to $0.
- #
- def program_name
- @program_name || File.basename($0, '.*')
- end
-
- # for experimental cascading :-)
- alias set_banner banner=
- alias set_program_name program_name=
- alias set_summary_width summary_width=
- alias set_summary_indent summary_indent=
-
- # Version
- attr_writer :version
- # Release code
- attr_writer :release
-
- #
- # Version
- #
- def version
- @version || (defined?(::Version) && ::Version)
- end
-
- #
- # Release code
- #
- def release
- @release || (defined?(::Release) && ::Release) || (defined?(::RELEASE) && ::RELEASE)
- end
-
- #
- # Returns version string from program_name, version and release.
- #
- def ver
- if v = version
- str = "#{program_name} #{[v].join('.')}"
- str << " (#{v})" if v = release
- str
- end
- end
-
- def warn(mesg = $!)
- super("#{program_name}: #{mesg}")
- end
-
- def abort(mesg = $!)
- super("#{program_name}: #{mesg}")
- end
-
- #
- # Subject of #on / #on_head, #accept / #reject
- #
- def top
- @stack[-1]
- end
-
- #
- # Subject of #on_tail.
- #
- def base
- @stack[1]
- end
-
- #
- # Pushes a new List.
- #
- def new
- @stack.push(List.new)
- if block_given?
- yield self
- else
- self
- end
- end
-
- #
- # Removes the last List.
- #
- def remove
- @stack.pop
- end
-
- #
- # Puts option summary into +to+ and returns +to+. Yields each line if
- # a block is given.
- #
- # +to+:: Output destination, which must have method <<. Defaults to [].
- # +width+:: Width of left side, defaults to @summary_width.
- # +max+:: Maximum length allowed for left side, defaults to +width+ - 1.
- # +indent+:: Indentation, defaults to @summary_indent.
- #
- def summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk)
- blk ||= proc {|l| to << (l.index($/, -1) ? l : l + $/)}
- visit(:summarize, {}, {}, width, max, indent, &blk)
- to
- end
-
- #
- # Returns option summary string.
- #
- def help; summarize("#{banner}".sub(/\n?\z/, "\n")) end
- alias to_s help
-
- #
- # Returns option summary list.
- #
- def to_a; summarize("#{banner}".split(/^/)) end
-
- #
- # Checks if an argument is given twice, in which case an ArgumentError is
- # raised. Called from OptionParser#switch only.
- #
- # +obj+:: New argument.
- # +prv+:: Previously specified argument.
- # +msg+:: Exception message.
- #
- def notwice(obj, prv, msg)
- unless !prv or prv == obj
- raise(ArgumentError, "argument #{msg} given twice: #{obj}",
- ParseError.filter_backtrace(caller(2)))
- end
- obj
- end
- private :notwice
-
- SPLAT_PROC = proc {|*a| a.length <= 1 ? a.first : a} # :nodoc:
- #
- # Creates an OptionParser::Switch from the parameters. The parsed argument
- # value is passed to the given block, where it can be processed.
- #
- # See at the beginning of OptionParser for some full examples.
- #
- # +opts+ can include the following elements:
- #
- # [Argument style:]
- # One of the following:
- # :NONE, :REQUIRED, :OPTIONAL
- #
- # [Argument pattern:]
- # Acceptable option argument format, must be pre-defined with
- # OptionParser.accept or OptionParser#accept, or Regexp. This can appear
- # once or assigned as String if not present, otherwise causes an
- # ArgumentError. Examples:
- # Float, Time, Array
- #
- # [Possible argument values:]
- # Hash or Array.
- # [:text, :binary, :auto]
- # %w[iso-2022-jp shift_jis euc-jp utf8 binary]
- # { "jis" => "iso-2022-jp", "sjis" => "shift_jis" }
- #
- # [Long style switch:]
- # Specifies a long style switch which takes a mandatory, optional or no
- # argument. It's a string of the following form:
- # "--switch=MANDATORY" or "--switch MANDATORY"
- # "--switch[=OPTIONAL]"
- # "--switch"
- #
- # [Short style switch:]
- # Specifies short style switch which takes a mandatory, optional or no
- # argument. It's a string of the following form:
- # "-xMANDATORY"
- # "-x[OPTIONAL]"
- # "-x"
- # There is also a special form which matches character range (not full
- # set of regular expression):
- # "-[a-z]MANDATORY"
- # "-[a-z][OPTIONAL]"
- # "-[a-z]"
- #
- # [Argument style and description:]
- # Instead of specifying mandatory or optional arguments directly in the
- # switch parameter, this separate parameter can be used.
- # "=MANDATORY"
- # "=[OPTIONAL]"
- #
- # [Description:]
- # Description string for the option.
- # "Run verbosely"
- #
- # [Handler:]
- # Handler for the parsed argument value. Either give a block or pass a
- # Proc or Method as an argument.
- #
- def make_switch(opts, block = nil)
- short, long, nolong, style, pattern, conv, not_pattern, not_conv, not_style = [], [], []
- ldesc, sdesc, desc, arg = [], [], []
- default_style = Switch::NoArgument
- default_pattern = nil
- klass = nil
- q, a = nil
-
- opts.each do |o|
- # argument class
- next if search(:atype, o) do |pat, c|
- klass = notwice(o, klass, 'type')
- if not_style and not_style != Switch::NoArgument
- not_pattern, not_conv = pat, c
- else
- default_pattern, conv = pat, c
- end
- end
-
- # directly specified pattern(any object possible to match)
- if (!(String === o || Symbol === o)) and o.respond_to?(:match)
- pattern = notwice(o, pattern, 'pattern')
- if pattern.respond_to?(:convert)
- conv = pattern.method(:convert).to_proc
- else
- conv = SPLAT_PROC
- end
- next
- end
-
- # anything others
- case o
- when Proc, Method
- block = notwice(o, block, 'block')
- when Array, Hash
- case pattern
- when CompletingHash
- when nil
- pattern = CompletingHash.new
- conv = pattern.method(:convert).to_proc if pattern.respond_to?(:convert)
- else
- raise ArgumentError, "argument pattern given twice"
- end
- o.each {|pat, *v| pattern[pat] = v.fetch(0) {pat}}
- when Module
- raise ArgumentError, "unsupported argument type: #{o}", ParseError.filter_backtrace(caller(4))
- when *ArgumentStyle.keys
- style = notwice(ArgumentStyle[o], style, 'style')
- when /^--no-([^\[\]=\s]*)(.+)?/
- q, a = $1, $2
- o = notwice(a ? Object : TrueClass, klass, 'type')
- not_pattern, not_conv = search(:atype, o) unless not_style
- not_style = (not_style || default_style).guess(arg = a) if a
- default_style = Switch::NoArgument
- default_pattern, conv = search(:atype, FalseClass) unless default_pattern
- ldesc << "--no-#{q}"
- long << 'no-' + (q = q.downcase)
- nolong << q
- when /^--\[no-\]([^\[\]=\s]*)(.+)?/
- q, a = $1, $2
- o = notwice(a ? Object : TrueClass, klass, 'type')
- if a
- default_style = default_style.guess(arg = a)
- default_pattern, conv = search(:atype, o) unless default_pattern
- end
- ldesc << "--[no-]#{q}"
- long << (o = q.downcase)
- not_pattern, not_conv = search(:atype, FalseClass) unless not_style
- not_style = Switch::NoArgument
- nolong << 'no-' + o
- when /^--([^\[\]=\s]*)(.+)?/
- q, a = $1, $2
- if a
- o = notwice(NilClass, klass, 'type')
- default_style = default_style.guess(arg = a)
- default_pattern, conv = search(:atype, o) unless default_pattern
- end
- ldesc << "--#{q}"
- long << (o = q.downcase)
- when /^-(\[\^?\]?(?:[^\\\]]|\\.)*\])(.+)?/
- q, a = $1, $2
- o = notwice(Object, klass, 'type')
- if a
- default_style = default_style.guess(arg = a)
- default_pattern, conv = search(:atype, o) unless default_pattern
- end
- sdesc << "-#{q}"
- short << Regexp.new(q)
- when /^-(.)(.+)?/
- q, a = $1, $2
- if a
- o = notwice(NilClass, klass, 'type')
- default_style = default_style.guess(arg = a)
- default_pattern, conv = search(:atype, o) unless default_pattern
- end
- sdesc << "-#{q}"
- short << q
- when /^=/
- style = notwice(default_style.guess(arg = o), style, 'style')
- default_pattern, conv = search(:atype, Object) unless default_pattern
- else
- desc.push(o)
- end
- end
-
- default_pattern, conv = search(:atype, default_style.pattern) unless default_pattern
- if !(short.empty? and long.empty?)
- s = (style || default_style).new(pattern || default_pattern,
- conv, sdesc, ldesc, arg, desc, block)
- elsif !block
- if style or pattern
- raise ArgumentError, "no switch given", ParseError.filter_backtrace(caller)
- end
- s = desc
- else
- short << pattern
- s = (style || default_style).new(pattern,
- conv, nil, nil, arg, desc, block)
- end
- return s, short, long,
- (not_style.new(not_pattern, not_conv, sdesc, ldesc, nil, desc, block) if not_style),
- nolong
- end
-
- def define(*opts, &block)
- top.append(*(sw = make_switch(opts, block)))
- sw[0]
- end
-
- #
- # Add option switch and handler. See #make_switch for an explanation of
- # parameters.
- #
- def on(*opts, &block)
- define(*opts, &block)
- self
- end
- alias def_option define
-
- def define_head(*opts, &block)
- top.prepend(*(sw = make_switch(opts, block)))
- sw[0]
- end
-
- #
- # Add option switch like with #on, but at head of summary.
- #
- def on_head(*opts, &block)
- define_head(*opts, &block)
- self
- end
- alias def_head_option define_head
-
- def define_tail(*opts, &block)
- base.append(*(sw = make_switch(opts, block)))
- sw[0]
- end
-
- #
- # Add option switch like with #on, but at tail of summary.
- #
- def on_tail(*opts, &block)
- define_tail(*opts, &block)
- self
- end
- alias def_tail_option define_tail
-
- #
- # Add separator in summary.
- #
- def separator(string)
- top.append(string, nil, nil)
- end
-
- #
- # Parses command line arguments +argv+ in order. When a block is given,
- # each non-option argument is yielded.
- #
- # Returns the rest of +argv+ left unparsed.
- #
- def order(*argv, &block)
- argv = argv[0].dup if argv.size == 1 and Array === argv[0]
- order!(argv, &block)
- end
-
- #
- # Same as #order, but removes switches destructively.
- # Non-option arguments remain in +argv+.
- #
- def order!(argv = default_argv, &nonopt)
- parse_in_order(argv, &nonopt)
- end
-
- def parse_in_order(argv = default_argv, setter = nil, &nonopt) # :nodoc:
- opt, arg, val, rest = nil
- nonopt ||= proc {|a| throw :terminate, a}
- argv.unshift(arg) if arg = catch(:terminate) {
- while arg = argv.shift
- case arg
- # long option
- when /\A--([^=]*)(?:=(.*))?/m
- opt, rest = $1, $2
- begin
- sw, = complete(:long, opt, true)
- rescue ParseError
- raise $!.set_option(arg, true)
- end
- begin
- opt, cb, val = sw.parse(rest, argv) {|*exc| raise(*exc)}
- val = cb.call(val) if cb
- setter.call(sw.switch_name, val) if setter
- rescue ParseError
- raise $!.set_option(arg, rest)
- end
-
- # short option
- when /\A-(.)((=).*|.+)?/m
- opt, has_arg, eq, val, rest = $1, $3, $3, $2, $2
- begin
- sw, = search(:short, opt)
- unless sw
- begin
- sw, = complete(:short, opt)
- # short option matched.
- val = arg.sub(/\A-/, '')
- has_arg = true
- rescue InvalidOption
- # if no short options match, try completion with long
- # options.
- sw, = complete(:long, opt)
- eq ||= !rest
- end
- end
- rescue ParseError
- raise $!.set_option(arg, true)
- end
- begin
- opt, cb, val = sw.parse(val, argv) {|*exc| raise(*exc) if eq}
- raise InvalidOption, arg if has_arg and !eq and arg == "-#{opt}"
- argv.unshift(opt) if opt and (!rest or (opt = opt.sub(/\A-*/, '-')) != '-')
- val = cb.call(val) if cb
- setter.call(sw.switch_name, val) if setter
- rescue ParseError
- raise $!.set_option(arg, arg.length > 2)
- end
-
- # non-option argument
- else
- catch(:prune) do
- visit(:each_option) do |sw0|
- sw = sw0
- sw.block.call(arg) if Switch === sw and sw.match_nonswitch?(arg)
- end
- nonopt.call(arg)
- end
- end
- end
-
- nil
- }
-
- visit(:search, :short, nil) {|sw| sw.block.call(*argv) if !sw.pattern}
-
- argv
- end
- private :parse_in_order
-
- #
- # Parses command line arguments +argv+ in permutation mode and returns
- # list of non-option arguments.
- #
- def permute(*argv)
- argv = argv[0].dup if argv.size == 1 and Array === argv[0]
- permute!(argv)
- end
-
- #
- # Same as #permute, but removes switches destructively.
- # Non-option arguments remain in +argv+.
- #
- def permute!(argv = default_argv)
- nonopts = []
- order!(argv, &nonopts.method(:<<))
- argv[0, 0] = nonopts
- argv
- end
-
- #
- # Parses command line arguments +argv+ in order when environment variable
- # POSIXLY_CORRECT is set, and in permutation mode otherwise.
- #
- def parse(*argv)
- argv = argv[0].dup if argv.size == 1 and Array === argv[0]
- parse!(argv)
- end
-
- #
- # Same as #parse, but removes switches destructively.
- # Non-option arguments remain in +argv+.
- #
- def parse!(argv = default_argv)
- if ENV.include?('POSIXLY_CORRECT')
- order!(argv)
- else
- permute!(argv)
- end
- end
-
- #
- # Wrapper method for getopts.rb.
- #
- # params = ARGV.getopts("ab:", "foo", "bar:", "zot:Z;zot option)
- # # params[:a] = true # -a
- # # params[:b] = "1" # -b1
- # # params[:foo] = "1" # --foo
- # # params[:bar] = "x" # --bar x
- # # params[:zot] = "z" # --zot Z
- #
- def getopts(*args)
- argv = Array === args.first ? args.shift : default_argv
- single_options, *long_options = *args
-
- result = {}
-
- single_options.scan(/(.)(:)?/) do |opt, val|
- if val
- result[opt] = nil
- define("-#{opt} VAL")
- else
- result[opt] = false
- define("-#{opt}")
- end
- end if single_options
-
- long_options.each do |arg|
- arg, desc = arg.split(';', 2)
- opt, val = arg.split(':', 2)
- if val
- result[opt] = val.empty? ? nil : val
- define("--#{opt}=#{result[opt] || "VAL"}", *[desc].compact)
- else
- result[opt] = false
- define("--#{opt}", *[desc].compact)
- end
- end
-
- parse_in_order(argv, result.method(:[]=))
- result
- end
-
- #
- # See #getopts.
- #
- def self.getopts(*args)
- new.getopts(*args)
- end
-
- #
- # Traverses @stack, sending each element method +id+ with +args+ and
- # +block+.
- #
- def visit(id, *args, &block)
- @stack.reverse_each do |el|
- el.send(id, *args, &block)
- end
- nil
- end
- private :visit
-
- #
- # Searches +key+ in @stack for +id+ hash and returns or yields the result.
- #
- def search(id, key)
- block_given = block_given?
- visit(:search, id, key) do |k|
- return block_given ? yield(k) : k
- end
- end
- private :search
-
- #
- # Completes shortened long style option switch and returns pair of
- # canonical switch and switch descriptor OptionParser::Switch.
- #
- # +id+:: Searching table.
- # +opt+:: Searching key.
- # +icase+:: Search case insensitive if true.
- # +pat+:: Optional pattern for completion.
- #
- def complete(typ, opt, icase = false, *pat)
- if pat.empty?
- search(typ, opt) {|sw| return [sw, opt]} # exact match or...
- end
- raise AmbiguousOption, catch(:ambiguous) {
- visit(:complete, typ, opt, icase, *pat) {|o, *sw| return sw}
- raise InvalidOption, opt
- }
- end
- private :complete
-
- def candidate(word)
- list = []
- case word
- when /\A--/
- word, arg = word.split(/=/, 2)
- argpat = Completion.regexp(arg, false) if arg and !arg.empty?
- long = true
- when /\A-(!-)/
- short = true
- when /\A-/
- long = short = true
- end
- pat = Completion.regexp(word, true)
- visit(:each_option) do |opt|
- next unless Switch === opt
- opts = (long ? opt.long : []) + (short ? opt.short : [])
- opts = Completion.candidate(word, true, pat, &opts.method(:each)).map(&:first) if pat
- if /\A=/ =~ opt.arg
- opts.map! {|sw| sw + "="}
- if arg and CompletingHash === opt.pattern
- if opts = opt.pattern.candidate(arg, false, argpat)
- opts.map!(&:last)
- end
- end
- end
- list.concat(opts)
- end
- list
- end
-
- #
- # Loads options from file names as +filename+. Does nothing when the file
- # is not present. Returns whether successfully loaded.
- #
- # +filename+ defaults to basename of the program without suffix in a
- # directory ~/.options.
- #
- def load(filename = nil)
- begin
- filename ||= File.expand_path(File.basename($0, '.*'), '~/.options')
- rescue
- return false
- end
- begin
- parse(*IO.readlines(filename).each {|s| s.chomp!})
- true
- rescue Errno::ENOENT, Errno::ENOTDIR
- false
- end
- end
-
- #
- # Parses environment variable +env+ or its uppercase with splitting like a
- # shell.
- #
- # +env+ defaults to the basename of the program.
- #
- def environment(env = File.basename($0, '.*'))
- env = ENV[env] || ENV[env.upcase] or return
- require 'shellwords'
- parse(*Shellwords.shellwords(env))
- end
-
- #
- # Acceptable argument classes
- #
-
- #
- # Any string and no conversion. This is fall-back.
- #
- accept(Object) {|s,|s or s.nil?}
-
- accept(NilClass) {|s,|s}
-
- #
- # Any non-empty string, and no conversion.
- #
- accept(String, /.+/m) {|s,*|s}
-
- #
- # Ruby/C-like integer, octal for 0-7 sequence, binary for 0b, hexadecimal
- # for 0x, and decimal for others; with optional sign prefix. Converts to
- # Integer.
- #
- decimal = '\d+(?:_\d+)*'
- binary = 'b[01]+(?:_[01]+)*'
- hex = 'x[\da-f]+(?:_[\da-f]+)*'
- octal = "0(?:[0-7]+(?:_[0-7]+)*|#{binary}|#{hex})?"
- integer = "#{octal}|#{decimal}"
-
- accept(Integer, %r"\A[-+]?(?:#{integer})\z"io) {|s,|
- begin
- Integer(s)
- rescue ArgumentError
- raise OptionParser::InvalidArgument, s
- end if s
- }
-
- #
- # Float number format, and converts to Float.
- #
- float = "(?:#{decimal}(?:\\.(?:#{decimal})?)?|\\.#{decimal})(?:E[-+]?#{decimal})?"
- floatpat = %r"\A[-+]?#{float}\z"io
- accept(Float, floatpat) {|s,| s.to_f if s}
-
- #
- # Generic numeric format, converts to Integer for integer format, Float
- # for float format, and Rational for rational format.
- #
- real = "[-+]?(?:#{octal}|#{float})"
- accept(Numeric, /\A(#{real})(?:\/(#{real}))?\z/io) {|s, d, n|
- if n
- Rational(d, n)
- elsif s
- eval(s)
- end
- }
-
- #
- # Decimal integer format, to be converted to Integer.
- #
- DecimalInteger = /\A[-+]?#{decimal}\z/io
- accept(DecimalInteger, DecimalInteger) {|s,|
- begin
- Integer(s)
- rescue ArgumentError
- raise OptionParser::InvalidArgument, s
- end if s
- }
-
- #
- # Ruby/C like octal/hexadecimal/binary integer format, to be converted to
- # Integer.
- #
- OctalInteger = /\A[-+]?(?:[0-7]+(?:_[0-7]+)*|0(?:#{binary}|#{hex}))\z/io
- accept(OctalInteger, OctalInteger) {|s,|
- begin
- Integer(s, 8)
- rescue ArgumentError
- raise OptionParser::InvalidArgument, s
- end if s
- }
-
- #
- # Decimal integer/float number format, to be converted to Integer for
- # integer format, Float for float format.
- #
- DecimalNumeric = floatpat # decimal integer is allowed as float also.
- accept(DecimalNumeric, floatpat) {|s,|
- begin
- eval(s)
- rescue SyntaxError
- raise OptionParser::InvalidArgument, s
- end if s
- }
-
- #
- # Boolean switch, which means whether it is present or not, whether it is
- # absent or not with prefix no-, or it takes an argument
- # yes/no/true/false/+/-.
- #
- yesno = CompletingHash.new
- %w[- no false].each {|el| yesno[el] = false}
- %w[+ yes true].each {|el| yesno[el] = true}
- yesno['nil'] = false # should be nil?
- accept(TrueClass, yesno) {|arg, val| val == nil or val}
- #
- # Similar to TrueClass, but defaults to false.
- #
- accept(FalseClass, yesno) {|arg, val| val != nil and val}
-
- #
- # List of strings separated by ",".
- #
- accept(Array) do |s,|
- if s
- s = s.split(',').collect {|ss| ss unless ss.empty?}
- end
- s
- end
-
- #
- # Regular expression with options.
- #
- accept(Regexp, %r"\A/((?:\\.|[^\\])*)/([[:alpha:]]+)?\z|.*") do |all, s, o|
- f = 0
- if o
- f |= Regexp::IGNORECASE if /i/ =~ o
- f |= Regexp::MULTILINE if /m/ =~ o
- f |= Regexp::EXTENDED if /x/ =~ o
- k = o.delete("imx")
- k = nil if k.empty?
- end
- Regexp.new(s || all, f, k)
- end
-
- #
- # Exceptions
- #
-
- #
- # Base class of exceptions from OptionParser.
- #
- class ParseError < RuntimeError
- # Reason which caused the error.
- Reason = 'parse error'.freeze
-
- def initialize(*args)
- @args = args
- @reason = nil
- end
-
- attr_reader :args
- attr_writer :reason
-
- #
- # Pushes back erred argument(s) to +argv+.
- #
- def recover(argv)
- argv[0, 0] = @args
- argv
- end
-
- def self.filter_backtrace(array)
- unless $DEBUG
- array.delete_if(&%r"\A#{Regexp.quote(__FILE__)}:"o.method(:=~))
- end
- array
- end
-
- def set_backtrace(array)
- super(self.class.filter_backtrace(array))
- end
-
- def set_option(opt, eq)
- if eq
- @args[0] = opt
- else
- @args.unshift(opt)
- end
- self
- end
-
- #
- # Returns error reason. Override this for I18N.
- #
- def reason
- @reason || self.class::Reason
- end
-
- def inspect
- "#<#{self.class}: #{args.join(' ')}>"
- end
-
- #
- # Default stringizing method to emit standard error message.
- #
- def message
- reason + ': ' + args.join(' ')
- end
-
- alias to_s message
- end
-
- #
- # Raises when ambiguously completable string is encountered.
- #
- class AmbiguousOption < ParseError
- const_set(:Reason, 'ambiguous option'.freeze)
- end
-
- #
- # Raises when there is an argument for a switch which takes no argument.
- #
- class NeedlessArgument < ParseError
- const_set(:Reason, 'needless argument'.freeze)
- end
-
- #
- # Raises when a switch with mandatory argument has no argument.
- #
- class MissingArgument < ParseError
- const_set(:Reason, 'missing argument'.freeze)
- end
-
- #
- # Raises when switch is undefined.
- #
- class InvalidOption < ParseError
- const_set(:Reason, 'invalid option'.freeze)
- end
-
- #
- # Raises when the given argument does not match required format.
- #
- class InvalidArgument < ParseError
- const_set(:Reason, 'invalid argument'.freeze)
- end
-
- #
- # Raises when the given argument word can't be completed uniquely.
- #
- class AmbiguousArgument < InvalidArgument
- const_set(:Reason, 'ambiguous argument'.freeze)
- end
-
- #
- # Miscellaneous
- #
-
- #
- # Extends command line arguments array (ARGV) to parse itself.
- #
- module Arguable
-
- #
- # Sets OptionParser object, when +opt+ is +false+ or +nil+, methods
- # OptionParser::Arguable#options and OptionParser::Arguable#options= are
- # undefined. Thus, there is no ways to access the OptionParser object
- # via the receiver object.
- #
- def options=(opt)
- unless @optparse = opt
- class << self
- undef_method(:options)
- undef_method(:options=)
- end
- end
- end
-
- #
- # Actual OptionParser object, automatically created if nonexistent.
- #
- # If called with a block, yields the OptionParser object and returns the
- # result of the block. If an OptionParser::ParseError exception occurs
- # in the block, it is rescued, a error message printed to STDERR and
- # +nil+ returned.
- #
- def options
- @optparse ||= OptionParser.new
- @optparse.default_argv = self
- block_given? or return @optparse
- begin
- yield @optparse
- rescue ParseError
- @optparse.warn $!
- nil
- end
- end
-
- #
- # Parses +self+ destructively in order and returns +self+ containing the
- # rest arguments left unparsed.
- #
- def order!(&blk) options.order!(self, &blk) end
-
- #
- # Parses +self+ destructively in permutation mode and returns +self+
- # containing the rest arguments left unparsed.
- #
- def permute!() options.permute!(self) end
-
- #
- # Parses +self+ destructively and returns +self+ containing the
- # rest arguments left unparsed.
- #
- def parse!() options.parse!(self) end
-
- #
- # Substitution of getopts is possible as follows. Also see
- # OptionParser#getopts.
- #
- # def getopts(*args)
- # ($OPT = ARGV.getopts(*args)).each do |opt, val|
- # eval "$OPT_#{opt.gsub(/[^A-Za-z0-9_]/, '_')} = val"
- # end
- # rescue OptionParser::ParseError
- # end
- #
- def getopts(*args)
- options.getopts(self, *args)
- end
-
- #
- # Initializes instance variable.
- #
- def self.extend_object(obj)
- super
- obj.instance_eval {@optparse = nil}
- end
- def initialize(*args)
- super
- @optparse = nil
- end
- end
-
- #
- # Acceptable argument classes. Now contains DecimalInteger, OctalInteger
- # and DecimalNumeric. See Acceptable argument classes (in source code).
- #
- module Acceptables
- const_set(:DecimalInteger, OptionParser::DecimalInteger)
- const_set(:OctalInteger, OptionParser::OctalInteger)
- const_set(:DecimalNumeric, OptionParser::DecimalNumeric)
- end
-end
-
-# ARGV is arguable by OptionParser
-ARGV.extend(OptionParser::Arguable)
-
-OptParse = OptionParser
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/optparse/ac.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/optparse/ac.rb
deleted file mode 100755
index 6a8626094..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/optparse/ac.rb
+++ /dev/null
@@ -1,50 +0,0 @@
-require 'optparse'
-
-class OptionParser::AC < OptionParser
- private
-
- def _check_ac_args(name, block)
- unless /\A\w[-\w]*\z/ =~ name
- raise ArgumentError, name
- end
- unless block
- raise ArgumentError, "no block given", ParseError.filter_backtrace(caller)
- end
- end
-
- def _ac_arg_enable(prefix, name, help_string, block)
- _check_ac_args(name, block)
-
- sdesc = []
- ldesc = ["--#{prefix}-#{name}"]
- desc = [help_string]
- q = name.downcase
- enable = Switch::NoArgument.new(nil, proc {true}, sdesc, ldesc, nil, desc, block)
- disable = Switch::NoArgument.new(nil, proc {false}, sdesc, ldesc, nil, desc, block)
- top.append(enable, [], ["enable-" + q], disable, ['disable-' + q])
- enable
- end
-
- public
-
- def ac_arg_enable(name, help_string, &block)
- _ac_arg_enable("enable", name, help_string, block)
- end
-
- def ac_arg_disable(name, help_string, &block)
- _ac_arg_enable("disable", name, help_string, block)
- end
-
- def ac_arg_with(name, help_string, &block)
- _check_ac_args(name, block)
-
- sdesc = []
- ldesc = ["--with-#{name}"]
- desc = [help_string]
- q = name.downcase
- with = Switch::PlacedArgument.new(*search(:atype, String), sdesc, ldesc, nil, desc, block)
- without = Switch::NoArgument.new(nil, proc {}, sdesc, ldesc, nil, desc, block)
- top.append(with, [], ["with-" + q], without, ['without-' + q])
- with
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/optparse/date.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/optparse/date.rb
deleted file mode 100755
index d680559f3..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/optparse/date.rb
+++ /dev/null
@@ -1,17 +0,0 @@
-require 'optparse'
-require 'date'
-
-OptionParser.accept(DateTime) do |s,|
- begin
- DateTime.parse(s) if s
- rescue ArgumentError
- raise OptionParser::InvalidArgument, s
- end
-end
-OptionParser.accept(Date) do |s,|
- begin
- Date.parse(s) if s
- rescue ArgumentError
- raise OptionParser::InvalidArgument, s
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/optparse/shellwords.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/optparse/shellwords.rb
deleted file mode 100755
index 0422d7c88..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/optparse/shellwords.rb
+++ /dev/null
@@ -1,6 +0,0 @@
-# -*- ruby -*-
-
-require 'shellwords'
-require 'optparse'
-
-OptionParser.accept(Shellwords) {|s,| Shellwords.shellwords(s)}
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/optparse/time.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/optparse/time.rb
deleted file mode 100755
index 402cadcf1..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/optparse/time.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-require 'optparse'
-require 'time'
-
-OptionParser.accept(Time) do |s,|
- begin
- (Time.httpdate(s) rescue Time.parse(s)) if s
- rescue
- raise OptionParser::InvalidArgument, s
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/optparse/uri.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/optparse/uri.rb
deleted file mode 100755
index 024dc69ea..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/optparse/uri.rb
+++ /dev/null
@@ -1,6 +0,0 @@
-# -*- ruby -*-
-
-require 'optparse'
-require 'uri'
-
-OptionParser.accept(URI) {|s,| URI.parse(s) if s}
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/optparse/version.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/optparse/version.rb
deleted file mode 100755
index 852567741..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/optparse/version.rb
+++ /dev/null
@@ -1,70 +0,0 @@
-# OptionParser internal utility
-
-class << OptionParser
- def show_version(*pkgs)
- progname = ARGV.options.program_name
- result = false
- show = proc do |klass, cname, version|
- str = "#{progname}"
- unless klass == ::Object and cname == :VERSION
- version = version.join(".") if Array === version
- str << ": #{klass}" unless klass == Object
- str << " version #{version}"
- end
- [:Release, :RELEASE].find do |rel|
- if klass.const_defined?(rel)
- str << " (#{klass.const_get(rel)})"
- end
- end
- puts str
- result = true
- end
- if pkgs.size == 1 and pkgs[0] == "all"
- self.search_const(::Object, /\AV(?:ERSION|ersion)\z/) do |klass, cname, version|
- unless cname[1] == ?e and klass.const_defined?(:Version)
- show.call(klass, cname.intern, version)
- end
- end
- else
- pkgs.each do |pkg|
- begin
- pkg = pkg.split(/::|\//).inject(::Object) {|m, c| m.const_get(c)}
- v = case
- when pkg.const_defined?(:Version)
- pkg.const_get(n = :Version)
- when pkg.const_defined?(:VERSION)
- pkg.const_get(n = :VERSION)
- else
- n = nil
- "unknown"
- end
- show.call(pkg, n, v)
- rescue NameError
- end
- end
- end
- result
- end
-
- def each_const(path, base = ::Object)
- path.split(/::|\//).inject(base) do |klass, name|
- raise NameError, path unless Module === klass
- klass.constants.grep(/#{name}/i) do |c|
- klass.const_defined?(c) or next
- klass.const_get(c)
- end
- end
- end
-
- def search_const(klass, name)
- klasses = [klass]
- while klass = klasses.shift
- klass.constants.each do |cname|
- klass.const_defined?(cname) or next
- const = klass.const_get(cname)
- yield klass, cname, const if name === cname
- klasses << const if Module === const and const != ::Object
- end
- end
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/ostruct.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/ostruct.rb
deleted file mode 100755
index f51eb7b5d..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/ostruct.rb
+++ /dev/null
@@ -1,286 +0,0 @@
-#
-# = ostruct.rb: OpenStruct implementation
-#
-# Author:: Yukihiro Matsumoto
-# Documentation:: Gavin Sinclair
-#
-# OpenStruct allows the creation of data objects with arbitrary attributes.
-# See OpenStruct for an example.
-#
-
-#
-# An OpenStruct is a data structure, similar to a Hash, that allows the
-# definition of arbitrary attributes with their accompanying values. This is
-# accomplished by using Ruby's metaprogramming to define methods on the class
-# itself.
-#
-# == Examples:
-#
-# require 'ostruct'
-#
-# person = OpenStruct.new
-# person.name = "John Smith"
-# person.age = 70
-# person.pension = 300
-#
-# puts person.name # -> "John Smith"
-# puts person.age # -> 70
-# puts person.address # -> nil
-#
-# An OpenStruct employs a Hash internally to store the methods and values and
-# can even be initialized with one:
-#
-# australia = OpenStruct.new(:country => "Australia", :population => 20_000_000)
-# p australia # ->
-#
-# Hash keys with spaces or characters that would normally not be able to use for
-# method calls (e.g. ()[]*) will not be immediately available on the
-# OpenStruct object as a method for retrieval or assignment, but can be still be
-# reached through the Object#send method.
-#
-# measurements = OpenStruct.new("length (in inches)" => 24)
-# measurements.send("length (in inches)") # -> 24
-#
-# data_point = OpenStruct.new(:queued? => true)
-# data_point.queued? # -> true
-# data_point.send("queued?=",false)
-# data_point.queued? # -> false
-#
-# Removing the presence of a method requires the execution the delete_field
-# method as setting the property value to +nil+ will not remove the method.
-#
-# first_pet = OpenStruct.new(:name => 'Rowdy', :owner => 'John Smith')
-# first_pet.owner = nil
-# second_pet = OpenStruct.new(:name => 'Rowdy')
-#
-# first_pet == second_pet # -> false
-#
-# first_pet.delete_field(:owner)
-# first_pet == second_pet # -> true
-#
-#
-# == Implementation:
-#
-# An OpenStruct utilizes Ruby's method lookup structure to find and define the
-# necessary methods for properties. This is accomplished through the method
-# method_missing and define_method.
-#
-# This should be a consideration if there is a concern about the performance of
-# the objects that are created, as there is much more overhead in the setting
-# of these properties compared to using a Hash or a Struct.
-#
-class OpenStruct
- #
- # Creates a new OpenStruct object. By default, the resulting OpenStruct
- # object will have no attributes.
- #
- # The optional +hash+, if given, will generate attributes and values
- # (can be a Hash, an OpenStruct or a Struct).
- # For example:
- #
- # require 'ostruct'
- # hash = { "country" => "Australia", :population => 20_000_000 }
- # data = OpenStruct.new(hash)
- #
- # p data # ->
- #
- def initialize(hash=nil)
- @table = {}
- if hash
- hash.each_pair do |k, v|
- k = k.to_sym
- @table[k] = v
- new_ostruct_member(k)
- end
- end
- end
-
- # Duplicate an OpenStruct object members.
- def initialize_copy(orig)
- super
- @table = @table.dup
- @table.each_key{|key| new_ostruct_member(key)}
- end
-
- #
- # Converts the OpenStruct to a hash with keys representing
- # each attribute (as symbols) and their corresponding values
- # Example:
- #
- # require 'ostruct'
- # data = OpenStruct.new("country" => "Australia", :population => 20_000_000)
- # data.to_h # => {:country => "Australia", :population => 20000000 }
- #
- def to_h
- @table.dup
- end
-
- #
- # Yields all attributes (as a symbol) along with the corresponding values
- # or returns an enumerator if not block is given.
- # Example:
- #
- # require 'ostruct'
- # data = OpenStruct.new("country" => "Australia", :population => 20_000_000)
- # data.each_pair.to_a # => [[:country, "Australia"], [:population, 20000000]]
- #
- def each_pair
- return to_enum(__method__) { @table.size } unless block_given?
- @table.each_pair{|p| yield p}
- end
-
- #
- # Provides marshalling support for use by the Marshal library.
- #
- def marshal_dump
- @table
- end
-
- #
- # Provides marshalling support for use by the Marshal library.
- #
- def marshal_load(x)
- @table = x
- @table.each_key{|key| new_ostruct_member(key)}
- end
-
- #
- # Used internally to check if the OpenStruct is able to be
- # modified before granting access to the internal Hash table to be modified.
- #
- def modifiable
- begin
- @modifiable = true
- rescue
- raise RuntimeError, "can't modify frozen #{self.class}", caller(3)
- end
- @table
- end
- protected :modifiable
-
- #
- # Used internally to defined properties on the
- # OpenStruct. It does this by using the metaprogramming function
- # define_singleton_method for both the getter method and the setter method.
- #
- def new_ostruct_member(name)
- name = name.to_sym
- unless respond_to?(name)
- define_singleton_method(name) { @table[name] }
- define_singleton_method("#{name}=") { |x| modifiable[name] = x }
- end
- name
- end
- protected :new_ostruct_member
-
- def method_missing(mid, *args) # :nodoc:
- mname = mid.id2name
- len = args.length
- if mname.chomp!('=')
- if len != 1
- raise ArgumentError, "wrong number of arguments (#{len} for 1)", caller(1)
- end
- modifiable[new_ostruct_member(mname)] = args[0]
- elsif len == 0
- @table[mid]
- else
- err = NoMethodError.new "undefined method `#{mid}' for #{self}", mid, args
- err.set_backtrace caller(1)
- raise err
- end
- end
-
- # Returns the value of a member.
- #
- # person = OpenStruct.new('name' => 'John Smith', 'age' => 70)
- # person[:age] # => 70, same as ostruct.age
- #
- def [](name)
- @table[name.to_sym]
- end
-
- #
- # Sets the value of a member.
- #
- # person = OpenStruct.new('name' => 'John Smith', 'age' => 70)
- # person[:age] = 42 # => equivalent to ostruct.age = 42
- # person.age # => 42
- #
- def []=(name, value)
- modifiable[new_ostruct_member(name)] = value
- end
-
- #
- # Remove the named field from the object. Returns the value that the field
- # contained if it was defined.
- #
- # require 'ostruct'
- #
- # person = OpenStruct.new('name' => 'John Smith', 'age' => 70)
- #
- # person.delete_field('name') # => 'John Smith'
- #
- def delete_field(name)
- sym = name.to_sym
- singleton_class.__send__(:remove_method, sym, "#{sym}=")
- @table.delete sym
- end
-
- InspectKey = :__inspect_key__ # :nodoc:
-
- #
- # Returns a string containing a detailed summary of the keys and values.
- #
- def inspect
- str = "#<#{self.class}"
-
- ids = (Thread.current[InspectKey] ||= [])
- if ids.include?(object_id)
- return str << ' ...>'
- end
-
- ids << object_id
- begin
- first = true
- for k,v in @table
- str << "," unless first
- first = false
- str << " #{k}=#{v.inspect}"
- end
- return str << '>'
- ensure
- ids.pop
- end
- end
- alias :to_s :inspect
-
- attr_reader :table # :nodoc:
- protected :table
-
- #
- # Compares this object and +other+ for equality. An OpenStruct is equal to
- # +other+ when +other+ is an OpenStruct and the two objects' Hash tables are
- # equal.
- #
- def ==(other)
- return false unless other.kind_of?(OpenStruct)
- @table == other.table
- end
-
- #
- # Compares this object and +other+ for equality. An OpenStruct is eql? to
- # +other+ when +other+ is an OpenStruct and the two objects' Hash tables are
- # eql?.
- #
- def eql?(other)
- return false unless other.kind_of?(OpenStruct)
- @table.eql?(other.table)
- end
-
- # Compute a hash-code for this OpenStruct.
- # Two hashes with the same content will have the same hash code
- # (and will be eql?).
- def hash
- @table.hash
- end
-end
diff --git a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/pathname.rb b/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/pathname.rb
deleted file mode 100755
index 82541e9b1..000000000
--- a/ThirdParty/lib/Mac/Ruby.framework/Versions/2.2/lib/ruby/2.2.0/pathname.rb
+++ /dev/null
@@ -1,579 +0,0 @@
-#
-# = pathname.rb
-#
-# Object-Oriented Pathname Class
-#
-# Author:: Tanaka Akira
-# Documentation:: Author and Gavin Sinclair
-#
-# For documentation, see class Pathname.
-#
-
-require 'pathname.so'
-
-class Pathname
-
- # :stopdoc:
- if RUBY_VERSION < "1.9"
- TO_PATH = :to_str
- else
- # to_path is implemented so Pathname objects are usable with File.open, etc.
- TO_PATH = :to_path
- end
-
- SAME_PATHS = if File::FNM_SYSCASE.nonzero?
- # Avoid #zero? here because #casecmp can return nil.
- proc {|a, b| a.casecmp(b) == 0}
- else
- proc {|a, b| a == b}
- end
-
-
- if File::ALT_SEPARATOR
- SEPARATOR_LIST = "#{Regexp.quote File::ALT_SEPARATOR}#{Regexp.quote File::SEPARATOR}"
- SEPARATOR_PAT = /[#{SEPARATOR_LIST}]/
- else
- SEPARATOR_LIST = "#{Regexp.quote File::SEPARATOR}"
- SEPARATOR_PAT = /#{Regexp.quote File::SEPARATOR}/
- end
-
- # :startdoc:
-
- # chop_basename(path) -> [pre-basename, basename] or nil
- def chop_basename(path) # :nodoc:
- base = File.basename(path)
- if /\A#{SEPARATOR_PAT}?\z/o =~ base
- return nil
- else
- return path[0, path.rindex(base)], base
- end
- end
- private :chop_basename
-
- # split_names(path) -> prefix, [name, ...]
- def split_names(path) # :nodoc:
- names = []
- while r = chop_basename(path)
- path, basename = r
- names.unshift basename
- end
- return path, names
- end
- private :split_names
-
- def prepend_prefix(prefix, relpath) # :nodoc:
- if relpath.empty?
- File.dirname(prefix)
- elsif /#{SEPARATOR_PAT}/o =~ prefix
- prefix = File.dirname(prefix)
- prefix = File.join(prefix, "") if File.basename(prefix + 'a') != 'a'
- prefix + relpath
- else
- prefix + relpath
- end
- end
- private :prepend_prefix
-
- # Returns clean pathname of +self+ with consecutive slashes and useless dots
- # removed. The filesystem is not accessed.
- #
- # If +consider_symlink+ is +true+, then a more conservative algorithm is used
- # to avoid breaking symbolic linkages. This may retain more +..+
- # entries than absolutely necessary, but without accessing the filesystem,
- # this can't be avoided.
- #
- # See Pathname#realpath.
- #
- def cleanpath(consider_symlink=false)
- if consider_symlink
- cleanpath_conservative
- else
- cleanpath_aggressive
- end
- end
-
- #
- # Clean the path simply by resolving and removing excess +.+ and +..+ entries.
- # Nothing more, nothing less.
- #
- def cleanpath_aggressive # :nodoc:
- path = @path
- names = []
- pre = path
- while r = chop_basename(pre)
- pre, base = r
- case base
- when '.'
- when '..'
- names.unshift base
- else
- if names[0] == '..'
- names.shift
- else
- names.unshift base
- end
- end
- end
- pre.tr!(File::ALT_SEPARATOR, File::SEPARATOR) if File::ALT_SEPARATOR
- if /#{SEPARATOR_PAT}/o =~ File.basename(pre)
- names.shift while names[0] == '..'
- end
- self.class.new(prepend_prefix(pre, File.join(*names)))
- end
- private :cleanpath_aggressive
-
- # has_trailing_separator?(path) -> bool
- def has_trailing_separator?(path) # :nodoc:
- if r = chop_basename(path)
- pre, basename = r
- pre.length + basename.length < path.length
- else
- false
- end
- end
- private :has_trailing_separator?
-
- # add_trailing_separator(path) -> path
- def add_trailing_separator(path) # :nodoc:
- if File.basename(path + 'a') == 'a'
- path
- else
- File.join(path, "") # xxx: Is File.join is appropriate to add separator?
- end
- end
- private :add_trailing_separator
-
- def del_trailing_separator(path) # :nodoc:
- if r = chop_basename(path)
- pre, basename = r
- pre + basename
- elsif /#{SEPARATOR_PAT}+\z/o =~ path
- $` + File.dirname(path)[/#{SEPARATOR_PAT}*\z/o]
- else
- path
- end
- end
- private :del_trailing_separator
-
- def cleanpath_conservative # :nodoc:
- path = @path
- names = []
- pre = path
- while r = chop_basename(pre)
- pre, base = r
- names.unshift base if base != '.'
- end
- pre.tr!(File::ALT_SEPARATOR, File::SEPARATOR) if File::ALT_SEPARATOR
- if /#{SEPARATOR_PAT}/o =~ File.basename(pre)
- names.shift while names[0] == '..'
- end
- if names.empty?
- self.class.new(File.dirname(pre))
- else
- if names.last != '..' && File.basename(path) == '.'
- names << '.'
- end
- result = prepend_prefix(pre, File.join(*names))
- if /\A(?:\.|\.\.)\z/ !~ names.last && has_trailing_separator?(path)
- self.class.new(add_trailing_separator(result))
- else
- self.class.new(result)
- end
- end
- end
- private :cleanpath_conservative
-
- # Returns the parent directory.
- #
- # This is same as self + '..'
.
- def parent
- self + '..'
- end
-
- # Returns +true+ if +self+ points to a mountpoint.
- def mountpoint?
- begin
- stat1 = self.lstat
- stat2 = self.parent.lstat
- stat1.dev == stat2.dev && stat1.ino == stat2.ino ||
- stat1.dev != stat2.dev
- rescue Errno::ENOENT
- false
- end
- end
-
- #
- # Predicate method for root directories. Returns +true+ if the
- # pathname consists of consecutive slashes.
- #
- # It doesn't access the filesystem. So it may return +false+ for some
- # pathnames which points to roots such as /usr/...
- #
- def root?
- !!(chop_basename(@path) == nil && /#{SEPARATOR_PAT}/o =~ @path)
- end
-
- # Predicate method for testing whether a path is absolute.
- #
- # It returns +true+ if the pathname begins with a slash.
- #
- # p = Pathname.new('/im/sure')
- # p.absolute?
- # #=> true
- #
- # p = Pathname.new('not/so/sure')
- # p.absolute?
- # #=> false
- def absolute?
- !relative?
- end
-
- # The opposite of Pathname#absolute?
- #
- # It returns +false+ if the pathname begins with a slash.
- #
- # p = Pathname.new('/im/sure')
- # p.relative?
- # #=> false
- #
- # p = Pathname.new('not/so/sure')
- # p.relative?
- # #=> true
- def relative?
- path = @path
- while r = chop_basename(path)
- path, = r
- end
- path == ''
- end
-
- #
- # Iterates over each component of the path.
- #
- # Pathname.new("/usr/bin/ruby").each_filename {|filename| ... }
- # # yields "usr", "bin", and "ruby".
- #
- # Returns an Enumerator if no block was given.
- #
- # enum = Pathname.new("/usr/bin/ruby").each_filename
- # # ... do stuff ...
- # enum.each { |e| ... }
- # # yields "usr", "bin", and "ruby".
- #
- def each_filename # :yield: filename
- return to_enum(__method__) unless block_given?
- _, names = split_names(@path)
- names.each {|filename| yield filename }
- nil
- end
-
- # Iterates over and yields a new Pathname object
- # for each element in the given path in descending order.
- #
- # Pathname.new('/path/to/some/file.rb').descend {|v| p v}
- # #
- # #
- # #
- # #
- # #
- #
- # Pathname.new('path/to/some/file.rb').descend {|v| p v}
- # #