repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/win32/registry.rb | tools/jruby-1.5.1/lib/ruby/1.9/win32/registry.rb | =begin
= Win32 Registry I/F
win32/registry is registry accessor library for Win32 platform.
It uses Win32API to call Win32 Registry APIs.
== example
Win32::Registry::HKEY_CURRENT_USER.open('SOFTWARE\foo') do |reg|
value = reg['foo'] # read a value
value = reg['foo', Win32::Registry::REG_SZ] # read a value with type
type, value = reg.read('foo') # read a value
reg['foo'] = 'bar' # write a value
reg['foo', Win32::Registry::REG_SZ] = 'bar' # write a value with type
reg.write('foo', Win32::Registry::REG_SZ, 'bar') # write a value
reg.each_value { |name, type, data| ... } # Enumerate values
reg.each_key { |key, wtime| ... } # Enumerate subkeys
reg.delete_value(name) # Delete a value
reg.delete_key(name) # Delete a subkey
reg.delete_key(name, true) # Delete a subkey recursively
end
= Reference
== Win32::Registry class
=== including modules
* Enumerable
* Registry::Constants
=== class methods
--- Registry.open(key, subkey, desired = KEY_READ, opt = REG_OPTION_RESERVED)
--- Registry.open(key, subkey, desired = KEY_READ, opt = REG_OPTION_RESERVED) { |reg| ... }
Open the registry key ((|subkey|)) under ((|key|)).
((|key|)) is Win32::Registry object of parent key.
You can use predefined key HKEY_* (see ((<constants>)))
((|desired|)) and ((|opt|)) is access mask and key option.
For detail, see ((<MSDN Library|URL:http://msdn.microsoft.com/library/en-us/sysinfo/base/regopenkeyex.asp>)).
If block is given, the key is closed automatically.
--- Registry.create(key, subkey, desired = KEY_ALL_ACCESS, opt = REG_OPTION_RESERVED)
--- Registry.create(key, subkey, desired = KEY_ALL_ACCESS, opt = REG_OPTION_RESERVED) { |reg| ... }
Create or open the registry key ((|subkey|)) under ((|key|)).
You can use predefined key HKEY_* (see ((<constants>)))
If subkey is already exists, key is opened and Registry#((<created?>))
method will return false.
If block is given, the key is closed automatically.
--- Registry.expand_environ(str)
Replace (({%\w+%})) into the environment value of ((|str|)).
This method is used for REG_EXPAND_SZ.
For detail, see ((<ExpandEnvironmentStrings|URL:http://msdn.microsoft.com/library/en-us/sysinfo/base/expandenvironmentstrings.asp>)) Win32 API.
--- Registry.type2name(type)
Convert registry type value to readable string.
--- Registry.wtime2time(wtime)
Convert 64-bit FILETIME integer into Time object.
--- Registry.time2wtime(time)
Convert Time object or Integer object into 64-bit FILETIME.
=== instance methods
--- open(subkey, desired = KEY_READ, opt = REG_OPTION_RESERVED)
Same as (({Win32::((<Registry.open>))(self, subkey, desired, opt)}))
--- create(subkey, desired = KEY_ALL_ACCESS, opt = REG_OPTION_RESERVED)
Same as (({Win32::((<Registry.create>))(self, subkey, desired, opt)}))
--- close
Close key.
After closed, most method raises error.
--- read(name, *rtype)
Read a registry value named ((|name|)) and return array of
[ ((|type|)), ((|data|)) ].
When name is nil, the `default' value is read.
((|type|)) is value type. (see ((<Win32::Registry::Constants module>)))
((|data|)) is value data, its class is:
:REG_SZ, REG_EXPAND_SZ
String
:REG_MULTI_SZ
Array of String
:REG_DWORD, REG_DWORD_BIG_ENDIAN, REG_QWORD
Integer
:REG_BINARY
String (contains binary data)
When ((|rtype|)) is specified, the value type must be included by
((|rtype|)) array, or TypeError is raised.
--- self[name, *rtype]
Read a registry value named ((|name|)) and return its value data.
The class of value is same as ((<read>)) method returns.
If the value type is REG_EXPAND_SZ, returns value data whose environment
variables are replaced.
If the value type is neither REG_SZ, REG_MULTI_SZ, REG_DWORD,
REG_DWORD_BIG_ENDIAN, nor REG_QWORD, TypeError is raised.
The meaning of ((|rtype|)) is same as ((<read>)) method.
--- read_s(name)
--- read_i(name)
--- read_bin(name)
Read a REG_SZ(read_s), REG_DWORD(read_i), or REG_BINARY(read_bin)
registry value named ((|name|)).
If the values type does not match, TypeError is raised.
--- read_s_expand(name)
Read a REG_SZ or REG_EXPAND_SZ registry value named ((|name|)).
If the value type is REG_EXPAND_SZ, environment variables are replaced.
Unless the value type is REG_SZ or REG_EXPAND_SZ, TypeError is raised.
--- write(name, type, data)
Write ((|data|)) to a registry value named ((|name|)).
When name is nil, write to the `default' value.
((|type|)) is type value. (see ((<Registry::Constants module>)))
Class of ((|data|)) must be same as which ((<read>))
method returns.
--- self[name, wtype = nil] = value
Write ((|value|)) to a registry value named ((|name|)).
If ((|wtype|)) is specified, the value type is it.
Otherwise, the value type is depend on class of ((|value|)):
:Integer
REG_DWORD
:String
REG_SZ
:Array
REG_MULTI_SZ
--- write_s(name, value)
--- write_i(name, value)
--- write_bin(name, value)
Write ((|value|)) to a registry value named ((|name|)).
The value type is REG_SZ(write_s), REG_DWORD(write_i), or
REG_BINARY(write_bin).
--- each { |name, type, value| ... }
--- each_value { |name, type, value| ... }
Enumerate values.
--- each_key { |subkey, wtime| ... }
Enumerate subkeys.
((|subkey|)) is String which contains name of subkey.
((|wtime|)) is last write time as FILETIME (64-bit integer).
(see ((<Registry.wtime2time>)))
--- delete(name)
--- delete_value(name)
Delete a registry value named ((|name|)).
We can not delete the `default' value.
--- delete_key(name, recursive = false)
Delete a subkey named ((|name|)) and all its values.
If ((|recursive|)) is false, the subkey must not have subkeys.
Otherwise, this method deletes all subkeys and values recursively.
--- flush
Write all the attributes into the registry file.
--- created?
Returns if key is created ((*newly*)).
(see ((<Registry.create>)))
--- open?
Returns if key is not closed.
--- hkey
Returns key handle value.
--- parent
Win32::Registry object of parent key, or nil if predefeined key.
--- keyname
Same as ((|subkey|)) value of ((<Registry.open>)) or
((<Registry.create>)) method.
--- disposition
Disposition value (REG_CREATED_NEW_KEY or REG_OPENED_EXISTING_KEY).
--- name
--- to_s
Full path of key such as (({'HKEY_CURRENT_USER\SOFTWARE\foo\bar'})).
--- info
Returns key information as Array of:
:num_keys
The number of subkeys.
:max_key_length
Maximum length of name of subkeys.
:num_values
The number of values.
:max_value_name_length
Maximum length of name of values.
:max_value_length
Maximum length of value of values.
:descriptor_length
Length of security descriptor.
:wtime
Last write time as FILETIME(64-bit integer)
For detail, see ((<RegQueryInfoKey|URL:http://msdn.microsoft.com/library/en-us/sysinfo/base/regqueryinfokey.asp>)) Win32 API.
--- num_keys
--- max_key_length
--- num_values
--- max_value_name_length
--- max_value_length
--- descriptor_length
--- wtime
Returns an item of key information.
=== constants
--- HKEY_CLASSES_ROOT
--- HKEY_CURRENT_USER
--- HKEY_LOCAL_MACHINE
--- HKEY_PERFORMANCE_DATA
--- HKEY_CURRENT_CONFIG
--- HKEY_DYN_DATA
Win32::Registry object whose key is predefined key.
For detail, see ((<MSDN Library|URL:http://msdn.microsoft.com/library/en-us/sysinfo/base/predefined_keys.asp>)).
== Win32::Registry::Constants module
For detail, see ((<MSDN Library|URL:http://msdn.microsoft.com/library/en-us/sysinfo/base/registry.asp>)).
--- HKEY_*
Predefined key ((*handle*)).
These are Integer, not Win32::Registry.
--- REG_*
Registry value type.
--- KEY_*
Security access mask.
--- KEY_OPTIONS_*
Key options.
--- REG_CREATED_NEW_KEY
--- REG_OPENED_EXISTING_KEY
If the key is created newly or opened existing key.
See also Registry#((<disposition>)) method.
=end
require 'Win32API'
module Win32
class Registry
module Constants
HKEY_CLASSES_ROOT = 0x80000000
HKEY_CURRENT_USER = 0x80000001
HKEY_LOCAL_MACHINE = 0x80000002
HKEY_USERS = 0x80000003
HKEY_PERFORMANCE_DATA = 0x80000004
HKEY_PERFORMANCE_TEXT = 0x80000050
HKEY_PERFORMANCE_NLSTEXT = 0x80000060
HKEY_CURRENT_CONFIG = 0x80000005
HKEY_DYN_DATA = 0x80000006
REG_NONE = 0
REG_SZ = 1
REG_EXPAND_SZ = 2
REG_BINARY = 3
REG_DWORD = 4
REG_DWORD_LITTLE_ENDIAN = 4
REG_DWORD_BIG_ENDIAN = 5
REG_LINK = 6
REG_MULTI_SZ = 7
REG_RESOURCE_LIST = 8
REG_FULL_RESOURCE_DESCRIPTOR = 9
REG_RESOURCE_REQUIREMENTS_LIST = 10
REG_QWORD = 11
REG_QWORD_LITTLE_ENDIAN = 11
STANDARD_RIGHTS_READ = 0x00020000
STANDARD_RIGHTS_WRITE = 0x00020000
KEY_QUERY_VALUE = 0x0001
KEY_SET_VALUE = 0x0002
KEY_CREATE_SUB_KEY = 0x0004
KEY_ENUMERATE_SUB_KEYS = 0x0008
KEY_NOTIFY = 0x0010
KEY_CREATE_LINK = 0x0020
KEY_READ = STANDARD_RIGHTS_READ |
KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY
KEY_WRITE = STANDARD_RIGHTS_WRITE |
KEY_SET_VALUE | KEY_CREATE_SUB_KEY
KEY_EXECUTE = KEY_READ
KEY_ALL_ACCESS = KEY_READ | KEY_WRITE | KEY_CREATE_LINK
REG_OPTION_RESERVED = 0x0000
REG_OPTION_NON_VOLATILE = 0x0000
REG_OPTION_VOLATILE = 0x0001
REG_OPTION_CREATE_LINK = 0x0002
REG_OPTION_BACKUP_RESTORE = 0x0004
REG_OPTION_OPEN_LINK = 0x0008
REG_LEGAL_OPTION = REG_OPTION_RESERVED |
REG_OPTION_NON_VOLATILE | REG_OPTION_CREATE_LINK |
REG_OPTION_BACKUP_RESTORE | REG_OPTION_OPEN_LINK
REG_CREATED_NEW_KEY = 1
REG_OPENED_EXISTING_KEY = 2
REG_WHOLE_HIVE_VOLATILE = 0x0001
REG_REFRESH_HIVE = 0x0002
REG_NO_LAZY_FLUSH = 0x0004
REG_FORCE_RESTORE = 0x0008
MAX_KEY_LENGTH = 514
MAX_VALUE_LENGTH = 32768
end
include Constants
include Enumerable
#
# Error
#
class Error < ::StandardError
FormatMessageA = Win32API.new('kernel32.dll', 'FormatMessageA', 'LPLLPLP', 'L')
def initialize(code)
@code = code
msg = "\0" * 1024
len = FormatMessageA.call(0x1200, 0, code, 0, msg, 1024, 0)
super msg[0, len].tr("\r", '').chomp
end
attr_reader :code
end
#
# Predefined Keys
#
class PredefinedKey < Registry
def initialize(hkey, keyname)
@hkey = hkey
@parent = nil
@keyname = keyname
@disposition = REG_OPENED_EXISTING_KEY
end
# Predefined keys cannot be closed
def close
raise Error.new(5) ## ERROR_ACCESS_DENIED
end
# Fake class for Registry#open, Registry#create
def class
Registry
end
# Make all
Constants.constants.grep(/^HKEY_/) do |c|
Registry.const_set c, new(Constants.const_get(c), c)
end
end
#
# Win32 APIs
#
module API
[
%w/RegOpenKeyExA LPLLP L/,
%w/RegCreateKeyExA LPLLLLPPP L/,
%w/RegEnumValueA LLPPPPPP L/,
%w/RegEnumKeyExA LLPPLLLP L/,
%w/RegQueryValueExA LPLPPP L/,
%w/RegSetValueExA LPLLPL L/,
%w/RegDeleteValue LP L/,
%w/RegDeleteKey LP L/,
%w/RegFlushKey L L/,
%w/RegCloseKey L L/,
%w/RegQueryInfoKey LPPPPPPPPPPP L/,
].each do |fn|
const_set fn[0].intern, Win32API.new('advapi32.dll', *fn)
end
module_function
def check(result)
raise Error, result, caller(2) if result != 0
end
def packdw(dw)
[dw].pack('V')
end
def unpackdw(dw)
dw += [0].pack('V')
dw.unpack('V')[0]
end
def packqw(qw)
[ qw & 0xFFFFFFFF, qw >> 32 ].pack('VV')
end
def unpackqw(qw)
qw = qw.unpack('VV')
(qw[1] << 32) | qw[0]
end
def OpenKey(hkey, name, opt, desired)
result = packdw(0)
check RegOpenKeyExA.call(hkey, name, opt, desired, result)
unpackdw(result)
end
def CreateKey(hkey, name, opt, desired)
result = packdw(0)
disp = packdw(0)
check RegCreateKeyExA.call(hkey, name, 0, 0, opt, desired,
0, result, disp)
[ unpackdw(result), unpackdw(disp) ]
end
def EnumValue(hkey, index)
name = ' ' * Constants::MAX_KEY_LENGTH
size = packdw(Constants::MAX_KEY_LENGTH)
check RegEnumValueA.call(hkey, index, name, size, 0, 0, 0, 0)
name[0, unpackdw(size)]
end
def EnumKey(hkey, index)
name = ' ' * Constants::MAX_KEY_LENGTH
size = packdw(Constants::MAX_KEY_LENGTH)
wtime = ' ' * 8
check RegEnumKeyExA.call(hkey, index, name, size, 0, 0, 0, wtime)
[ name[0, unpackdw(size)], unpackqw(wtime) ]
end
def QueryValue(hkey, name)
type = packdw(0)
size = packdw(0)
check RegQueryValueExA.call(hkey, name, 0, type, 0, size)
data = ' ' * unpackdw(size)
check RegQueryValueExA.call(hkey, name, 0, type, data, size)
[ unpackdw(type), data[0, unpackdw(size)] ]
end
def SetValue(hkey, name, type, data, size)
check RegSetValueExA.call(hkey, name, 0, type, data, size)
end
def DeleteValue(hkey, name)
check RegDeleteValue.call(hkey, name)
end
def DeleteKey(hkey, name)
check RegDeleteKey.call(hkey, name)
end
def FlushKey(hkey)
check RegFlushKey.call(hkey)
end
def CloseKey(hkey)
check RegCloseKey.call(hkey)
end
def QueryInfoKey(hkey)
subkeys = packdw(0)
maxsubkeylen = packdw(0)
values = packdw(0)
maxvaluenamelen = packdw(0)
maxvaluelen = packdw(0)
secdescs = packdw(0)
wtime = ' ' * 8
check RegQueryInfoKey.call(hkey, 0, 0, 0, subkeys, maxsubkeylen, 0,
values, maxvaluenamelen, maxvaluelen, secdescs, wtime)
[ unpackdw(subkeys), unpackdw(maxsubkeylen), unpackdw(values),
unpackdw(maxvaluenamelen), unpackdw(maxvaluelen),
unpackdw(secdescs), unpackqw(wtime) ]
end
end
#
# utility functions
#
def self.expand_environ(str)
str.gsub(/%([^%]+)%/) { ENV[$1] || ENV[$1.upcase] || $& }
end
@@type2name = { }
%w[
REG_NONE REG_SZ REG_EXPAND_SZ REG_BINARY REG_DWORD
REG_DWORD_BIG_ENDIAN REG_LINK REG_MULTI_SZ
REG_RESOURCE_LIST REG_FULL_RESOURCE_DESCRIPTOR
REG_RESOURCE_REQUIREMENTS_LIST REG_QWORD
].each do |type|
@@type2name[Constants.const_get(type)] = type
end
def self.type2name(type)
@@type2name[type] || type.to_s
end
def self.wtime2time(wtime)
Time.at((wtime - 116444736000000000) / 10000000)
end
def self.time2wtime(time)
time.to_i * 10000000 + 116444736000000000
end
#
# constructors
#
private_class_method :new
def self.open(hkey, subkey, desired = KEY_READ, opt = REG_OPTION_RESERVED)
subkey = subkey.chomp('\\')
newkey = API.OpenKey(hkey.hkey, subkey, opt, desired)
obj = new(newkey, hkey, subkey, REG_OPENED_EXISTING_KEY)
if block_given?
begin
yield obj
ensure
obj.close
end
else
obj
end
end
def self.create(hkey, subkey, desired = KEY_ALL_ACCESS, opt = REG_OPTION_RESERVED)
newkey, disp = API.CreateKey(hkey.hkey, subkey, opt, desired)
obj = new(newkey, hkey, subkey, disp)
if block_given?
begin
yield obj
ensure
obj.close
end
else
obj
end
end
#
# finalizer
#
@@final = proc { |hkey| proc { API.CloseKey(hkey[0]) if hkey[0] } }
#
# initialize
#
def initialize(hkey, parent, keyname, disposition)
@hkey = hkey
@parent = parent
@keyname = keyname
@disposition = disposition
@hkeyfinal = [ hkey ]
ObjectSpace.define_finalizer self, @@final.call(@hkeyfinal)
end
attr_reader :hkey, :parent, :keyname, :disposition
#
# attributes
#
def created?
@disposition == REG_CREATED_NEW_KEY
end
def open?
!@hkey.nil?
end
def name
parent = self
name = @keyname
while parent = parent.parent
name = parent.keyname + '\\' + name
end
name
end
def inspect
"\#<Win32::Registry key=#{name.inspect}>"
end
#
# marshalling
#
def _dump(depth)
raise TypeError, "can't dump Win32::Registry"
end
#
# open/close
#
def open(subkey, desired = KEY_READ, opt = REG_OPTION_RESERVED, &blk)
self.class.open(self, subkey, desired, opt, &blk)
end
def create(subkey, desired = KEY_ALL_ACCESS, opt = REG_OPTION_RESERVED, &blk)
self.class.create(self, subkey, desired, opt, &blk)
end
def close
API.CloseKey(@hkey)
@hkey = @parent = @keyname = nil
@hkeyfinal[0] = nil
end
#
# iterator
#
def each_value
index = 0
while true
begin
subkey = API.EnumValue(@hkey, index)
rescue Error
break
end
begin
type, data = read(subkey)
rescue Error
next
end
yield subkey, type, data
index += 1
end
index
end
alias each each_value
def each_key
index = 0
while true
begin
subkey, wtime = API.EnumKey(@hkey, index)
rescue Error
break
end
yield subkey, wtime
index += 1
end
index
end
def keys
keys_ary = []
each_key { |key,| keys_ary << key }
keys_ary
end
#
# reader
#
def read(name, *rtype)
type, data = API.QueryValue(@hkey, name)
unless rtype.empty? or rtype.include?(type)
raise TypeError, "Type mismatch (expect #{rtype.inspect} but #{type} present)"
end
case type
when REG_SZ, REG_EXPAND_SZ
[ type, data.chop ]
when REG_MULTI_SZ
[ type, data.split(/\0/) ]
when REG_BINARY
[ type, data ]
when REG_DWORD
[ type, API.unpackdw(data) ]
when REG_DWORD_BIG_ENDIAN
[ type, data.unpack('N')[0] ]
when REG_QWORD
[ type, API.unpackqw(data) ]
else
raise TypeError, "Type #{type} is not supported."
end
end
def [](name, *rtype)
type, data = read(name, *rtype)
case type
when REG_SZ, REG_DWORD, REG_QWORD, REG_MULTI_SZ
data
when REG_EXPAND_SZ
Registry.expand_environ(data)
else
raise TypeError, "Type #{type} is not supported."
end
end
def read_s(name)
read(name, REG_SZ)[1]
end
def read_s_expand(name)
type, data = read(name, REG_SZ, REG_EXPAND_SZ)
if type == REG_EXPAND_SZ
Registry.expand_environ(data)
else
data
end
end
def read_i(name)
read(name, REG_DWORD, REG_DWORD_BIG_ENDIAN, REG_QWORD)[1]
end
def read_bin(name)
read(name, REG_BINARY)[1]
end
#
# writer
#
def write(name, type, data)
case type
when REG_SZ, REG_EXPAND_SZ
data = data.to_s + "\0"
when REG_MULTI_SZ
data = data.to_a.join("\0") + "\0\0"
when REG_BINARY
data = data.to_s
when REG_DWORD
data = API.packdw(data.to_i)
when REG_DWORD_BIG_ENDIAN
data = [data.to_i].pack('N')
when REG_QWORD
data = API.packqw(data.to_i)
else
raise TypeError, "Unsupported type #{type}"
end
API.SetValue(@hkey, name, type, data, data.length)
end
def []=(name, rtype, value = nil)
if value
write name, rtype, value
else
case value = rtype
when Integer
write name, REG_DWORD, value
when String
write name, REG_SZ, value
when Array
write name, REG_MULTI_SZ, value
else
raise TypeError, "Unexpected type #{value.class}"
end
end
value
end
def write_s(name, value)
write name, REG_SZ, value.to_s
end
def write_i(name, value)
write name, REG_DWORD, value.to_i
end
def write_bin(name, value)
write name, REG_BINARY, value.to_s
end
#
# delete
#
def delete_value(name)
API.DeleteValue(@hkey, name)
end
alias delete delete_value
def delete_key(name, recursive = false)
if recursive
open(name, KEY_ALL_ACCESS) do |reg|
reg.keys.each do |key|
begin
reg.delete_key(key, true)
rescue Error
#
end
end
end
API.DeleteKey(@hkey, name)
else
begin
API.EnumKey @hkey, 0
rescue Error
return API.DeleteKey(@hkey, name)
end
raise Error.new(5) ## ERROR_ACCESS_DENIED
end
end
#
# flush
#
def flush
API.FlushKey @hkey
end
#
# key information
#
def info
API.QueryInfoKey(@hkey)
end
%w[
num_keys max_key_length
num_values max_value_name_length max_value_length
descriptor_length wtime
].each_with_index do |s, i|
eval <<-__END__
def #{s}
info[#{i}]
end
__END__
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rinda/rinda.rb | tools/jruby-1.5.1/lib/ruby/1.9/rinda/rinda.rb | require 'drb/drb'
require 'thread'
##
# A module to implement the Linda distributed computing paradigm in Ruby.
#
# Rinda is part of DRb (dRuby).
#
# == Example(s)
#
# See the sample/drb/ directory in the Ruby distribution, from 1.8.2 onwards.
#
#--
# TODO
# == Introduction to Linda/rinda?
#
# == Why is this library separate from DRb?
module Rinda
##
# Rinda error base class
class RindaError < RuntimeError; end
##
# Raised when a hash-based tuple has an invalid key.
class InvalidHashTupleKey < RindaError; end
##
# Raised when trying to use a canceled tuple.
class RequestCanceledError < ThreadError; end
##
# Raised when trying to use an expired tuple.
class RequestExpiredError < ThreadError; end
##
# A tuple is the elementary object in Rinda programming.
# Tuples may be matched against templates if the tuple and
# the template are the same size.
class Tuple
##
# Creates a new Tuple from +ary_or_hash+ which must be an Array or Hash.
def initialize(ary_or_hash)
if hash?(ary_or_hash)
init_with_hash(ary_or_hash)
else
init_with_ary(ary_or_hash)
end
end
##
# The number of elements in the tuple.
def size
@tuple.size
end
##
# Accessor method for elements of the tuple.
def [](k)
@tuple[k]
end
##
# Fetches item +k+ from the tuple.
def fetch(k)
@tuple.fetch(k)
end
##
# Iterate through the tuple, yielding the index or key, and the
# value, thus ensuring arrays are iterated similarly to hashes.
def each # FIXME
if Hash === @tuple
@tuple.each { |k, v| yield(k, v) }
else
@tuple.each_with_index { |v, k| yield(k, v) }
end
end
##
# Return the tuple itself
def value
@tuple
end
private
def hash?(ary_or_hash)
ary_or_hash.respond_to?(:keys)
end
##
# Munges +ary+ into a valid Tuple.
def init_with_ary(ary)
@tuple = Array.new(ary.size)
@tuple.size.times do |i|
@tuple[i] = ary[i]
end
end
##
# Ensures +hash+ is a valid Tuple.
def init_with_hash(hash)
@tuple = Hash.new
hash.each do |k, v|
raise InvalidHashTupleKey unless String === k
@tuple[k] = v
end
end
end
##
# Templates are used to match tuples in Rinda.
class Template < Tuple
##
# Matches this template against +tuple+. The +tuple+ must be the same
# size as the template. An element with a +nil+ value in a template acts
# as a wildcard, matching any value in the corresponding position in the
# tuple. Elements of the template match the +tuple+ if the are #== or
# #===.
#
# Template.new([:foo, 5]).match Tuple.new([:foo, 5]) # => true
# Template.new([:foo, nil]).match Tuple.new([:foo, 5]) # => true
# Template.new([String]).match Tuple.new(['hello']) # => true
#
# Template.new([:foo]).match Tuple.new([:foo, 5]) # => false
# Template.new([:foo, 6]).match Tuple.new([:foo, 5]) # => false
# Template.new([:foo, nil]).match Tuple.new([:foo]) # => false
# Template.new([:foo, 6]).match Tuple.new([:foo]) # => false
def match(tuple)
return false unless tuple.respond_to?(:size)
return false unless tuple.respond_to?(:fetch)
return false unless self.size == tuple.size
each do |k, v|
begin
it = tuple.fetch(k)
rescue
return false
end
next if v.nil?
next if v == it
next if v === it
return false
end
return true
end
##
# Alias for #match.
def ===(tuple)
match(tuple)
end
end
##
# <i>Documentation?</i>
class DRbObjectTemplate
##
# Creates a new DRbObjectTemplate that will match against +uri+ and +ref+.
def initialize(uri=nil, ref=nil)
@drb_uri = uri
@drb_ref = ref
end
##
# This DRbObjectTemplate matches +ro+ if the remote object's drburi and
# drbref are the same. +nil+ is used as a wildcard.
def ===(ro)
return true if super(ro)
unless @drb_uri.nil?
return false unless (@drb_uri === ro.__drburi rescue false)
end
unless @drb_ref.nil?
return false unless (@drb_ref === ro.__drbref rescue false)
end
true
end
end
##
# TupleSpaceProxy allows a remote Tuplespace to appear as local.
class TupleSpaceProxy
##
# Creates a new TupleSpaceProxy to wrap +ts+.
def initialize(ts)
@ts = ts
end
##
# Adds +tuple+ to the proxied TupleSpace. See TupleSpace#write.
def write(tuple, sec=nil)
@ts.write(tuple, sec)
end
##
# Takes +tuple+ from the proxied TupleSpace. See TupleSpace#take.
def take(tuple, sec=nil, &block)
port = []
@ts.move(DRbObject.new(port), tuple, sec, &block)
port[0]
end
##
# Reads +tuple+ from the proxied TupleSpace. See TupleSpace#read.
def read(tuple, sec=nil, &block)
@ts.read(tuple, sec, &block)
end
##
# Reads all tuples matching +tuple+ from the proxied TupleSpace. See
# TupleSpace#read_all.
def read_all(tuple)
@ts.read_all(tuple)
end
##
# Registers for notifications of event +ev+ on the proxied TupleSpace.
# See TupleSpace#notify
def notify(ev, tuple, sec=nil)
@ts.notify(ev, tuple, sec)
end
end
##
# An SimpleRenewer allows a TupleSpace to check if a TupleEntry is still
# alive.
class SimpleRenewer
include DRbUndumped
##
# Creates a new SimpleRenewer that keeps an object alive for another +sec+
# seconds.
def initialize(sec=180)
@sec = sec
end
##
# Called by the TupleSpace to check if the object is still alive.
def renew
@sec
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rinda/ring.rb | tools/jruby-1.5.1/lib/ruby/1.9/rinda/ring.rb | #
# Note: Rinda::Ring API is unstable.
#
require 'drb/drb'
require 'rinda/rinda'
require 'thread'
module Rinda
##
# The default port Ring discovery will use.
Ring_PORT = 7647
##
# A RingServer allows a Rinda::TupleSpace to be located via UDP broadcasts.
# Service location uses the following steps:
#
# 1. A RingServer begins listening on the broadcast UDP address.
# 2. A RingFinger sends a UDP packet containing the DRb URI where it will
# listen for a reply.
# 3. The RingServer receives the UDP packet and connects back to the
# provided DRb URI with the DRb service.
class RingServer
include DRbUndumped
##
# Advertises +ts+ on the UDP broadcast address at +port+.
def initialize(ts, port=Ring_PORT)
@ts = ts
@soc = UDPSocket.open
@soc.bind('', port)
@w_service = write_service
@r_service = reply_service
end
##
# Creates a thread that picks up UDP packets and passes them to do_write
# for decoding.
def write_service
Thread.new do
loop do
msg = @soc.recv(1024)
do_write(msg)
end
end
end
##
# Extracts the response URI from +msg+ and adds it to TupleSpace where it
# will be picked up by +reply_service+ for notification.
def do_write(msg)
Thread.new do
begin
tuple, sec = Marshal.load(msg)
@ts.write(tuple, sec)
rescue
end
end
end
##
# Creates a thread that notifies waiting clients from the TupleSpace.
def reply_service
Thread.new do
loop do
do_reply
end
end
end
##
# Pulls lookup tuples out of the TupleSpace and sends their DRb object the
# address of the local TupleSpace.
def do_reply
tuple = @ts.take([:lookup_ring, DRbObject])
Thread.new { tuple[1].call(@ts) rescue nil}
rescue
end
end
##
# RingFinger is used by RingServer clients to discover the RingServer's
# TupleSpace. Typically, all a client needs to do is call
# RingFinger.primary to retrieve the remote TupleSpace, which it can then
# begin using.
class RingFinger
@@broadcast_list = ['<broadcast>', 'localhost']
@@finger = nil
##
# Creates a singleton RingFinger and looks for a RingServer. Returns the
# created RingFinger.
def self.finger
unless @@finger
@@finger = self.new
@@finger.lookup_ring_any
end
@@finger
end
##
# Returns the first advertised TupleSpace.
def self.primary
finger.primary
end
##
# Contains all discovered TupleSpaces except for the primary.
def self.to_a
finger.to_a
end
##
# The list of addresses where RingFinger will send query packets.
attr_accessor :broadcast_list
##
# The port that RingFinger will send query packets to.
attr_accessor :port
##
# Contain the first advertised TupleSpace after lookup_ring_any is called.
attr_accessor :primary
##
# Creates a new RingFinger that will look for RingServers at +port+ on
# the addresses in +broadcast_list+.
def initialize(broadcast_list=@@broadcast_list, port=Ring_PORT)
@broadcast_list = broadcast_list || ['localhost']
@port = port
@primary = nil
@rings = []
end
##
# Contains all discovered TupleSpaces except for the primary.
def to_a
@rings
end
##
# Iterates over all discovered TupleSpaces starting with the primary.
def each
lookup_ring_any unless @primary
return unless @primary
yield(@primary)
@rings.each { |x| yield(x) }
end
##
# Looks up RingServers waiting +timeout+ seconds. RingServers will be
# given +block+ as a callback, which will be called with the remote
# TupleSpace.
def lookup_ring(timeout=5, &block)
return lookup_ring_any(timeout) unless block_given?
msg = Marshal.dump([[:lookup_ring, DRbObject.new(block)], timeout])
@broadcast_list.each do |it|
soc = UDPSocket.open
begin
soc.setsockopt(Socket::SOL_SOCKET, Socket::SO_BROADCAST, true)
soc.send(msg, 0, it, @port)
rescue
nil
ensure
soc.close
end
end
sleep(timeout)
end
##
# Returns the first found remote TupleSpace. Any further recovered
# TupleSpaces can be found by calling +to_a+.
def lookup_ring_any(timeout=5)
queue = Queue.new
th = Thread.new do
self.lookup_ring(timeout) do |ts|
queue.push(ts)
end
queue.push(nil)
while it = queue.pop
@rings.push(it)
end
end
@primary = queue.pop
raise('RingNotFound') if @primary.nil?
@primary
end
end
##
# RingProvider uses a RingServer advertised TupleSpace as a name service.
# TupleSpace clients can register themselves with the remote TupleSpace and
# look up other provided services via the remote TupleSpace.
#
# Services are registered with a tuple of the format [:name, klass,
# DRbObject, description].
class RingProvider
##
# Creates a RingProvider that will provide a +klass+ service running on
# +front+, with a +description+. +renewer+ is optional.
def initialize(klass, front, desc, renewer = nil)
@tuple = [:name, klass, front, desc]
@renewer = renewer || Rinda::SimpleRenewer.new
end
##
# Advertises this service on the primary remote TupleSpace.
def provide
ts = Rinda::RingFinger.primary
ts.write(@tuple, @renewer)
end
end
end
if __FILE__ == $0
DRb.start_service
case ARGV.shift
when 's'
require 'rinda/tuplespace'
ts = Rinda::TupleSpace.new
place = Rinda::RingServer.new(ts)
$stdin.gets
when 'w'
finger = Rinda::RingFinger.new(nil)
finger.lookup_ring do |ts2|
p ts2
ts2.write([:hello, :world])
end
when 'r'
finger = Rinda::RingFinger.new(nil)
finger.lookup_ring do |ts2|
p ts2
p ts2.take([nil, nil])
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rinda/tuplespace.rb | tools/jruby-1.5.1/lib/ruby/1.9/rinda/tuplespace.rb | require 'monitor'
require 'thread'
require 'drb/drb'
require 'rinda/rinda'
require 'enumerator'
require 'forwardable'
module Rinda
##
# A TupleEntry is a Tuple (i.e. a possible entry in some Tuplespace)
# together with expiry and cancellation data.
class TupleEntry
include DRbUndumped
attr_accessor :expires
##
# Creates a TupleEntry based on +ary+ with an optional renewer or expiry
# time +sec+.
#
# A renewer must implement the +renew+ method which returns a Numeric,
# nil, or true to indicate when the tuple has expired.
def initialize(ary, sec=nil)
@cancel = false
@expires = nil
@tuple = make_tuple(ary)
@renewer = nil
renew(sec)
end
##
# Marks this TupleEntry as canceled.
def cancel
@cancel = true
end
##
# A TupleEntry is dead when it is canceled or expired.
def alive?
!canceled? && !expired?
end
##
# Return the object which makes up the tuple itself: the Array
# or Hash.
def value; @tuple.value; end
##
# Returns the canceled status.
def canceled?; @cancel; end
##
# Has this tuple expired? (true/false).
#
# A tuple has expired when its expiry timer based on the +sec+ argument to
# #initialize runs out.
def expired?
return true unless @expires
return false if @expires > Time.now
return true if @renewer.nil?
renew(@renewer)
return true unless @expires
return @expires < Time.now
end
##
# Reset the expiry time according to +sec_or_renewer+.
#
# +nil+:: it is set to expire in the far future.
# +false+:: it has expired.
# Numeric:: it will expire in that many seconds.
#
# Otherwise the argument refers to some kind of renewer object
# which will reset its expiry time.
def renew(sec_or_renewer)
sec, @renewer = get_renewer(sec_or_renewer)
@expires = make_expires(sec)
end
##
# Returns an expiry Time based on +sec+ which can be one of:
# Numeric:: +sec+ seconds into the future
# +true+:: the expiry time is the start of 1970 (i.e. expired)
# +nil+:: it is Tue Jan 19 03:14:07 GMT Standard Time 2038 (i.e. when
# UNIX clocks will die)
def make_expires(sec=nil)
case sec
when Numeric
Time.now + sec
when true
Time.at(1)
when nil
Time.at(2**31-1)
end
end
##
# Retrieves +key+ from the tuple.
def [](key)
@tuple[key]
end
##
# Fetches +key+ from the tuple.
def fetch(key)
@tuple.fetch(key)
end
##
# The size of the tuple.
def size
@tuple.size
end
##
# Creates a Rinda::Tuple for +ary+.
def make_tuple(ary)
Rinda::Tuple.new(ary)
end
private
##
# Returns a valid argument to make_expires and the renewer or nil.
#
# Given +true+, +nil+, or Numeric, returns that value and +nil+ (no actual
# renewer). Otherwise it returns an expiry value from calling +it.renew+
# and the renewer.
def get_renewer(it)
case it
when Numeric, true, nil
return it, nil
else
begin
return it.renew, it
rescue Exception
return it, nil
end
end
end
end
##
# A TemplateEntry is a Template together with expiry and cancellation data.
class TemplateEntry < TupleEntry
##
# Matches this TemplateEntry against +tuple+. See Template#match for
# details on how a Template matches a Tuple.
def match(tuple)
@tuple.match(tuple)
end
alias === match
def make_tuple(ary) # :nodoc:
Rinda::Template.new(ary)
end
end
##
# <i>Documentation?</i>
class WaitTemplateEntry < TemplateEntry
attr_reader :found
def initialize(place, ary, expires=nil)
super(ary, expires)
@place = place
@cond = place.new_cond
@found = nil
end
def cancel
super
signal
end
def wait
@cond.wait
end
def read(tuple)
@found = tuple
signal
end
def signal
@place.synchronize do
@cond.signal
end
end
end
##
# A NotifyTemplateEntry is returned by TupleSpace#notify and is notified of
# TupleSpace changes. You may receive either your subscribed event or the
# 'close' event when iterating over notifications.
#
# See TupleSpace#notify_event for valid notification types.
#
# == Example
#
# ts = Rinda::TupleSpace.new
# observer = ts.notify 'write', [nil]
#
# Thread.start do
# observer.each { |t| p t }
# end
#
# 3.times { |i| ts.write [i] }
#
# Outputs:
#
# ['write', [0]]
# ['write', [1]]
# ['write', [2]]
class NotifyTemplateEntry < TemplateEntry
##
# Creates a new NotifyTemplateEntry that watches +place+ for +event+s that
# match +tuple+.
def initialize(place, event, tuple, expires=nil)
ary = [event, Rinda::Template.new(tuple)]
super(ary, expires)
@queue = Queue.new
@done = false
end
##
# Called by TupleSpace to notify this NotifyTemplateEntry of a new event.
def notify(ev)
@queue.push(ev)
end
##
# Retrieves a notification. Raises RequestExpiredError when this
# NotifyTemplateEntry expires.
def pop
raise RequestExpiredError if @done
it = @queue.pop
@done = true if it[0] == 'close'
return it
end
##
# Yields event/tuple pairs until this NotifyTemplateEntry expires.
def each # :yields: event, tuple
while !@done
it = pop
yield(it)
end
rescue
ensure
cancel
end
end
##
# TupleBag is an unordered collection of tuples. It is the basis
# of Tuplespace.
class TupleBag
class TupleBin
extend Forwardable
def_delegators '@bin', :find_all, :delete_if, :each, :empty?
def initialize
@bin = []
end
def add(tuple)
@bin.push(tuple)
end
def delete(tuple)
idx = @bin.rindex(tuple)
@bin.delete_at(idx) if idx
end
def find(&blk)
@bin.reverse_each do |x|
return x if yield(x)
end
nil
end
end
def initialize # :nodoc:
@hash = {}
@enum = enum_for(:each_entry)
end
##
# +true+ if the TupleBag to see if it has any expired entries.
def has_expires?
@enum.find do |tuple|
tuple.expires
end
end
##
# Add +tuple+ to the TupleBag.
def push(tuple)
key = bin_key(tuple)
@hash[key] ||= TupleBin.new
@hash[key].add(tuple)
end
##
# Removes +tuple+ from the TupleBag.
def delete(tuple)
key = bin_key(tuple)
bin = @hash[key]
return nil unless bin
bin.delete(tuple)
@hash.delete(key) if bin.empty?
tuple
end
##
# Finds all live tuples that match +template+.
def find_all(template)
bin_for_find(template).find_all do |tuple|
tuple.alive? && template.match(tuple)
end
end
##
# Finds a live tuple that matches +template+.
def find(template)
bin_for_find(template).find do |tuple|
tuple.alive? && template.match(tuple)
end
end
##
# Finds all tuples in the TupleBag which when treated as templates, match
# +tuple+ and are alive.
def find_all_template(tuple)
@enum.find_all do |template|
template.alive? && template.match(tuple)
end
end
##
# Delete tuples which dead tuples from the TupleBag, returning the deleted
# tuples.
def delete_unless_alive
deleted = []
@hash.each do |key, bin|
bin.delete_if do |tuple|
if tuple.alive?
false
else
deleted.push(tuple)
true
end
end
end
deleted
end
private
def each_entry(&blk)
@hash.each do |k, v|
v.each(&blk)
end
end
def bin_key(tuple)
head = tuple[0]
if head.class == Symbol
return head
else
false
end
end
def bin_for_find(template)
key = bin_key(template)
key ? @hash.fetch(key, []) : @enum
end
end
##
# The Tuplespace manages access to the tuples it contains,
# ensuring mutual exclusion requirements are met.
#
# The +sec+ option for the write, take, move, read and notify methods may
# either be a number of seconds or a Renewer object.
class TupleSpace
include DRbUndumped
include MonitorMixin
##
# Creates a new TupleSpace. +period+ is used to control how often to look
# for dead tuples after modifications to the TupleSpace.
#
# If no dead tuples are found +period+ seconds after the last
# modification, the TupleSpace will stop looking for dead tuples.
def initialize(period=60)
super()
@bag = TupleBag.new
@read_waiter = TupleBag.new
@take_waiter = TupleBag.new
@notify_waiter = TupleBag.new
@period = period
@keeper = nil
end
##
# Adds +tuple+
def write(tuple, sec=nil)
entry = create_entry(tuple, sec)
synchronize do
if entry.expired?
@read_waiter.find_all_template(entry).each do |template|
template.read(tuple)
end
notify_event('write', entry.value)
notify_event('delete', entry.value)
else
@bag.push(entry)
start_keeper if entry.expires
@read_waiter.find_all_template(entry).each do |template|
template.read(tuple)
end
@take_waiter.find_all_template(entry).each do |template|
template.signal
end
notify_event('write', entry.value)
end
end
entry
end
##
# Removes +tuple+
def take(tuple, sec=nil, &block)
move(nil, tuple, sec, &block)
end
##
# Moves +tuple+ to +port+.
def move(port, tuple, sec=nil)
template = WaitTemplateEntry.new(self, tuple, sec)
yield(template) if block_given?
synchronize do
entry = @bag.find(template)
if entry
port.push(entry.value) if port
@bag.delete(entry)
notify_event('take', entry.value)
return entry.value
end
raise RequestExpiredError if template.expired?
begin
@take_waiter.push(template)
start_keeper if template.expires
while true
raise RequestCanceledError if template.canceled?
raise RequestExpiredError if template.expired?
entry = @bag.find(template)
if entry
port.push(entry.value) if port
@bag.delete(entry)
notify_event('take', entry.value)
return entry.value
end
template.wait
end
ensure
@take_waiter.delete(template)
end
end
end
##
# Reads +tuple+, but does not remove it.
def read(tuple, sec=nil)
template = WaitTemplateEntry.new(self, tuple, sec)
yield(template) if block_given?
synchronize do
entry = @bag.find(template)
return entry.value if entry
raise RequestExpiredError if template.expired?
begin
@read_waiter.push(template)
start_keeper if template.expires
template.wait
raise RequestCanceledError if template.canceled?
raise RequestExpiredError if template.expired?
return template.found
ensure
@read_waiter.delete(template)
end
end
end
##
# Returns all tuples matching +tuple+. Does not remove the found tuples.
def read_all(tuple)
template = WaitTemplateEntry.new(self, tuple, nil)
synchronize do
entry = @bag.find_all(template)
entry.collect do |e|
e.value
end
end
end
##
# Registers for notifications of +event+. Returns a NotifyTemplateEntry.
# See NotifyTemplateEntry for examples of how to listen for notifications.
#
# +event+ can be:
# 'write':: A tuple was added
# 'take':: A tuple was taken or moved
# 'delete':: A tuple was lost after being overwritten or expiring
#
# The TupleSpace will also notify you of the 'close' event when the
# NotifyTemplateEntry has expired.
def notify(event, tuple, sec=nil)
template = NotifyTemplateEntry.new(self, event, tuple, sec)
synchronize do
@notify_waiter.push(template)
end
template
end
private
def create_entry(tuple, sec)
TupleEntry.new(tuple, sec)
end
##
# Removes dead tuples.
def keep_clean
synchronize do
@read_waiter.delete_unless_alive.each do |e|
e.signal
end
@take_waiter.delete_unless_alive.each do |e|
e.signal
end
@notify_waiter.delete_unless_alive.each do |e|
e.notify(['close'])
end
@bag.delete_unless_alive.each do |e|
notify_event('delete', e.value)
end
end
end
##
# Notifies all registered listeners for +event+ of a status change of
# +tuple+.
def notify_event(event, tuple)
ev = [event, tuple]
@notify_waiter.find_all_template(ev).each do |template|
template.notify(ev)
end
end
##
# Creates a thread that scans the tuplespace for expired tuples.
def start_keeper
return if @keeper && @keeper.alive?
@keeper = Thread.new do
while true
sleep(@period)
synchronize do
break unless need_keeper?
keep_clean
end
end
end
end
##
# Checks the tuplespace to see if it needs cleaning.
def need_keeper?
return true if @bag.has_expires?
return true if @read_waiter.has_expires?
return true if @take_waiter.has_expires?
return true if @notify_waiter.has_expires?
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/shell/process-controller.rb | tools/jruby-1.5.1/lib/ruby/1.9/shell/process-controller.rb | #
# shell/process-controller.rb -
# $Release Version: 0.7 $
# $Revision: 22784 $
# by Keiju ISHITSUKA(keiju@ruby-lang.org)
#
# --
#
#
#
require "forwardable"
require "thread"
require "sync"
class Shell
class ProcessController
@ProcessControllers = {}
@ProcessControllersMonitor = Mutex.new
@ProcessControllersCV = ConditionVariable.new
@BlockOutputMonitor = Mutex.new
@BlockOutputCV = ConditionVariable.new
class<<self
extend Forwardable
def_delegator("@ProcessControllersMonitor",
"synchronize", "process_controllers_exclusive")
def active_process_controllers
process_controllers_exclusive do
@ProcessControllers.dup
end
end
def activate(pc)
process_controllers_exclusive do
@ProcessControllers[pc] ||= 0
@ProcessControllers[pc] += 1
end
end
def inactivate(pc)
process_controllers_exclusive do
if @ProcessControllers[pc]
if (@ProcessControllers[pc] -= 1) == 0
@ProcessControllers.delete(pc)
@ProcessControllersCV.signal
end
end
end
end
def each_active_object
process_controllers_exclusive do
for ref in @ProcessControllers.keys
yield ref
end
end
end
def block_output_synchronize(&b)
@BlockOutputMonitor.synchronize(&b)
end
def wait_to_finish_all_process_controllers
process_controllers_exclusive do
while !@ProcessControllers.empty?
Shell::notify("Process finishing, but active shell exists",
"You can use Shell#transact or Shell#check_point for more safe execution.")
if Shell.debug?
for pc in @ProcessControllers.keys
Shell::notify(" Not finished jobs in "+pc.shell.to_s)
for com in pc.jobs
com.notify(" Jobs: %id")
end
end
end
@ProcessControllersCV.wait(@ProcessControllersMonitor)
end
end
end
end
# for shell-command complete finish at this process exit.
USING_AT_EXIT_WHEN_PROCESS_EXIT = true
at_exit do
wait_to_finish_all_process_controllers unless $@
end
def initialize(shell)
@shell = shell
@waiting_jobs = []
@active_jobs = []
@jobs_sync = Sync.new
@job_monitor = Mutex.new
@job_condition = ConditionVariable.new
end
attr_reader :shell
def jobs
jobs = []
@jobs_sync.synchronize(:SH) do
jobs.concat @waiting_jobs
jobs.concat @active_jobs
end
jobs
end
def active_jobs
@active_jobs
end
def waiting_jobs
@waiting_jobs
end
def jobs_exist?
@jobs_sync.synchronize(:SH) do
@active_jobs.empty? or @waiting_jobs.empty?
end
end
def active_jobs_exist?
@jobs_sync.synchronize(:SH) do
@active_jobs.empty?
end
end
def waiting_jobs_exist?
@jobs_sync.synchronize(:SH) do
@waiting_jobs.empty?
end
end
# schedule a command
def add_schedule(command)
@jobs_sync.synchronize(:EX) do
ProcessController.activate(self)
if @active_jobs.empty?
start_job command
else
@waiting_jobs.push(command)
end
end
end
# start a job
def start_job(command = nil)
@jobs_sync.synchronize(:EX) do
if command
return if command.active?
@waiting_jobs.delete command
else
command = @waiting_jobs.shift
# command.notify "job(%id) pre-start.", @shell.debug?
return unless command
end
@active_jobs.push command
command.start
# command.notify "job(%id) post-start.", @shell.debug?
# start all jobs that input from the job
for job in @waiting_jobs.dup
start_job(job) if job.input == command
end
# command.notify "job(%id) post2-start.", @shell.debug?
end
end
def waiting_job?(job)
@jobs_sync.synchronize(:SH) do
@waiting_jobs.include?(job)
end
end
def active_job?(job)
@jobs_sync.synchronize(:SH) do
@active_jobs.include?(job)
end
end
# terminate a job
def terminate_job(command)
@jobs_sync.synchronize(:EX) do
@active_jobs.delete command
ProcessController.inactivate(self)
if @active_jobs.empty?
command.notify("start_jon in ierminate_jon(%id)", Shell::debug?)
start_job
end
end
end
# kill a job
def kill_job(sig, command)
@jobs_sync.synchronize(:EX) do
if @waiting_jobs.delete command
ProcessController.inactivate(self)
return
elsif @active_jobs.include?(command)
begin
r = command.kill(sig)
ProcessController.inactivate(self)
rescue
print "Shell: Warn: $!\n" if @shell.verbose?
return nil
end
@active_jobs.delete command
r
end
end
end
# wait for all jobs to terminate
def wait_all_jobs_execution
@job_monitor.synchronize do
begin
while !jobs.empty?
@job_condition.wait(@job_monitor)
for job in jobs
job.notify("waiting job(%id)", Shell::debug?)
end
end
ensure
redo unless jobs.empty?
end
end
end
# simple fork
def sfork(command, &block)
pipe_me_in, pipe_peer_out = IO.pipe
pipe_peer_in, pipe_me_out = IO.pipe
pid = nil
pid_mutex = Mutex.new
pid_cv = ConditionVariable.new
Thread.start do
ProcessController.block_output_synchronize do
STDOUT.flush
ProcessController.each_active_object do |pc|
for jobs in pc.active_jobs
jobs.flush
end
end
pid = fork {
Thread.list.each do |th|
# th.kill unless [Thread.main, Thread.current].include?(th)
th.kill unless Thread.current == th
end
STDIN.reopen(pipe_peer_in)
STDOUT.reopen(pipe_peer_out)
ObjectSpace.each_object(IO) do |io|
if ![STDIN, STDOUT, STDERR].include?(io)
io.close unless io.closed?
end
end
yield
}
end
pid_cv.signal
pipe_peer_in.close
pipe_peer_out.close
command.notify "job(%name:##{pid}) start", @shell.debug?
begin
_pid = nil
command.notify("job(%id) start to waiting finish.", @shell.debug?)
_pid = Process.waitpid(pid, nil)
rescue Errno::ECHILD
command.notify "warn: job(%id) was done already waitipd."
_pid = true
# rescue
# STDERR.puts $!
ensure
command.notify("Job(%id): Wait to finish when Process finished.", @shell.debug?)
# when the process ends, wait until the command termintes
if USING_AT_EXIT_WHEN_PROCESS_EXIT or _pid
else
command.notify("notice: Process finishing...",
"wait for Job[%id] to finish.",
"You can use Shell#transact or Shell#check_point for more safe execution.")
redo
end
# command.notify "job(%id) pre-pre-finish.", @shell.debug?
@job_monitor.synchronize do
# command.notify "job(%id) pre-finish.", @shell.debug?
terminate_job(command)
# command.notify "job(%id) pre-finish2.", @shell.debug?
@job_condition.signal
command.notify "job(%id) finish.", @shell.debug?
end
end
end
pid_mutex.synchronize do
while !pid
pid_cv.wait(pid_mutex)
end
end
return pid, pipe_me_in, pipe_me_out
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/shell/version.rb | tools/jruby-1.5.1/lib/ruby/1.9/shell/version.rb | #
# version.rb - shell version definition file
# $Release Version: 0.7$
# $Revision: 22784 $
# by Keiju ISHITSUKA(keiju@ruby-lang.org)
#
# --
#
#
#
class Shell
@RELEASE_VERSION = "0.7"
@LAST_UPDATE_DATE = "07/03/20"
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/shell/builtin-command.rb | tools/jruby-1.5.1/lib/ruby/1.9/shell/builtin-command.rb | #
# shell/builtin-command.rb -
# $Release Version: 0.7 $
# $Revision: 22784 $
# by Keiju ISHITSUKA(keiju@ruby-lang.org)
#
# --
#
#
#
require "shell/filter"
class Shell
class BuiltInCommand<Filter
def wait?
false
end
def active?
true
end
end
class Void < BuiltInCommand
def initialize(sh, *opts)
super sh
end
def each(rs = nil)
# do nothing
end
end
class Echo < BuiltInCommand
def initialize(sh, *strings)
super sh
@strings = strings
end
def each(rs = nil)
rs = @shell.record_separator unless rs
for str in @strings
yield str + rs
end
end
end
class Cat < BuiltInCommand
def initialize(sh, *filenames)
super sh
@cat_files = filenames
end
def each(rs = nil)
if @cat_files.empty?
super
else
for src in @cat_files
@shell.foreach(src, rs){|l| yield l}
end
end
end
end
class Glob < BuiltInCommand
def initialize(sh, pattern)
super sh
@pattern = pattern
end
def each(rs = nil)
if @pattern[0] == ?/
@files = Dir[@pattern]
else
prefix = @shell.pwd+"/"
@files = Dir[prefix+@pattern].collect{|p| p.sub(prefix, "")}
end
rs = @shell.record_separator unless rs
for f in @files
yield f+rs
end
end
end
# class Sort < Cat
# def initialize(sh, *filenames)
# super
# end
#
# def each(rs = nil)
# ary = []
# super{|l| ary.push l}
# for l in ary.sort!
# yield l
# end
# end
# end
class AppendIO < BuiltInCommand
def initialize(sh, io, filter)
super sh
@input = filter
@io = io
end
def input=(filter)
@input.input=filter
for l in @input
@io << l
end
end
end
class AppendFile < AppendIO
def initialize(sh, to_filename, filter)
@file_name = to_filename
io = sh.open(to_filename, "a")
super(sh, io, filter)
end
def input=(filter)
begin
super
ensure
@io.close
end
end
end
class Tee < BuiltInCommand
def initialize(sh, filename)
super sh
@to_filename = filename
end
def each(rs = nil)
to = @shell.open(@to_filename, "w")
begin
super{|l| to << l; yield l}
ensure
to.close
end
end
end
class Concat < BuiltInCommand
def initialize(sh, *jobs)
super(sh)
@jobs = jobs
end
def each(rs = nil)
while job = @jobs.shift
job.each{|l| yield l}
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/shell/filter.rb | tools/jruby-1.5.1/lib/ruby/1.9/shell/filter.rb | #
# shell/filter.rb -
# $Release Version: 0.7 $
# $Revision: 22784 $
# by Keiju ISHITSUKA(keiju@ruby-lang.org)
#
# --
#
#
#
class Shell
#
# Filter
# A method to require
# each()
#
class Filter
include Enumerable
def initialize(sh)
@shell = sh # parent shell
@input = nil # input filter
end
attr_reader :input
def input=(filter)
@input = filter
end
def each(rs = nil)
rs = @shell.record_separator unless rs
if @input
@input.each(rs){|l| yield l}
end
end
def < (src)
case src
when String
cat = Cat.new(@shell, src)
cat | self
when IO
self.input = src
self
else
Shell.Fail Error::CantApplyMethod, "<", to.class
end
end
def > (to)
case to
when String
dst = @shell.open(to, "w")
begin
each(){|l| dst << l}
ensure
dst.close
end
when IO
each(){|l| to << l}
else
Shell.Fail Error::CantApplyMethod, ">", to.class
end
self
end
def >> (to)
begin
Shell.cd(@shell.pwd).append(to, self)
rescue CantApplyMethod
Shell.Fail Error::CantApplyMethod, ">>", to.class
end
end
def | (filter)
filter.input = self
if active?
@shell.process_controller.start_job filter
end
filter
end
def + (filter)
Join.new(@shell, self, filter)
end
def to_a
ary = []
each(){|l| ary.push l}
ary
end
def to_s
str = ""
each(){|l| str.concat l}
str
end
def inspect
if @shell.debug.kind_of?(Integer) && @shell.debug > 2
super
else
to_s
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/shell/system-command.rb | tools/jruby-1.5.1/lib/ruby/1.9/shell/system-command.rb | #
# shell/system-command.rb -
# $Release Version: 0.7 $
# $Revision: 22784 $
# by Keiju ISHITSUKA(keiju@ruby-lang.org)
#
# --
#
#
#
require "shell/filter"
class Shell
class SystemCommand < Filter
def initialize(sh, command, *opts)
if t = opts.find{|opt| !opt.kind_of?(String) && opt.class}
Shell.Fail Error::TypeError, t.class, "String"
end
super(sh)
@command = command
@opts = opts
@input_queue = Queue.new
@pid = nil
sh.process_controller.add_schedule(self)
end
attr_reader :command
alias name command
def wait?
@shell.process_controller.waiting_job?(self)
end
def active?
@shell.process_controller.active_job?(self)
end
def input=(inp)
super
if active?
start_export
end
end
def start
notify([@command, *@opts].join(" "))
@pid, @pipe_in, @pipe_out = @shell.process_controller.sfork(self) {
Dir.chdir @shell.pwd
$0 = @command
exec(@command, *@opts)
}
if @input
start_export
end
start_import
end
def flush
@pipe_out.flush if @pipe_out and !@pipe_out.closed?
end
def terminate
begin
@pipe_in.close
rescue IOError
end
begin
@pipe_out.close
rescue IOError
end
end
def kill(sig)
if @pid
Process.kill(sig, @pid)
end
end
def start_import
notify "Job(%id) start imp-pipe.", @shell.debug?
rs = @shell.record_separator unless rs
_eop = true
th = Thread.start {
begin
while l = @pipe_in.gets
@input_queue.push l
end
_eop = false
rescue Errno::EPIPE
_eop = false
ensure
if !ProcessController::USING_AT_EXIT_WHEN_PROCESS_EXIT and _eop
notify("warn: Process finishing...",
"wait for Job[%id] to finish pipe importing.",
"You can use Shell#transact or Shell#check_point for more safe execution.")
redo
end
notify "job(%id}) close imp-pipe.", @shell.debug?
@input_queue.push :EOF
@pipe_in.close
end
}
end
def start_export
notify "job(%id) start exp-pipe.", @shell.debug?
_eop = true
th = Thread.start{
begin
@input.each do |l|
ProcessController::block_output_synchronize do
@pipe_out.print l
end
end
_eop = false
rescue Errno::EPIPE, Errno::EIO
_eop = false
ensure
if !ProcessController::USING_AT_EXIT_WHEN_PROCESS_EXIT and _eop
notify("shell: warn: Process finishing...",
"wait for Job(%id) to finish pipe exporting.",
"You can use Shell#transact or Shell#check_point for more safe execution.")
redo
end
notify "job(%id) close exp-pipe.", @shell.debug?
@pipe_out.close
end
}
end
alias super_each each
def each(rs = nil)
while (l = @input_queue.pop) != :EOF
yield l
end
end
# ex)
# if you wish to output:
# "shell: job(#{@command}:#{@pid}) close pipe-out."
# then
# mes: "job(%id) close pipe-out."
# yorn: Boolean(@shell.debug? or @shell.verbose?)
def notify(*opts, &block)
@shell.notify(*opts) do |mes|
yield mes if iterator?
mes.gsub!("%id", "#{@command}:##{@pid}")
mes.gsub!("%name", "#{@command}")
mes.gsub!("%pid", "#{@pid}")
mes
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/shell/command-processor.rb | tools/jruby-1.5.1/lib/ruby/1.9/shell/command-processor.rb | #
# shell/command-controller.rb -
# $Release Version: 0.7 $
# $Revision: 22784 $
# by Keiju ISHITSUKA(keiju@ruby-lang.org)
#
# --
#
#
#
require "e2mmap"
require "thread"
require "shell/error"
require "shell/filter"
require "shell/system-command"
require "shell/builtin-command"
class Shell
class CommandProcessor
# include Error
#
# initialize of Shell and related classes.
#
m = [:initialize, :expand_path]
if Object.methods.first.kind_of?(String)
NoDelegateMethods = m.collect{|x| x.id2name}
else
NoDelegateMethods = m
end
def self.initialize
install_builtin_commands
# define CommandProccessor#methods to Shell#methods and Filter#methods
for m in CommandProcessor.instance_methods(false) - NoDelegateMethods
add_delegate_command_to_shell(m)
end
def self.method_added(id)
add_delegate_command_to_shell(id)
end
end
#
# include run file.
#
def self.run_config
begin
load File.expand_path("~/.rb_shell") if ENV.key?("HOME")
rescue LoadError, Errno::ENOENT
rescue
print "load error: #{rc}\n"
print $!.class, ": ", $!, "\n"
for err in $@[0, $@.size - 2]
print "\t", err, "\n"
end
end
end
def initialize(shell)
@shell = shell
@system_commands = {}
end
#
# CommandProcessor#expand_path(path)
# path: String
# return: String
# returns the absolute path for <path>
#
def expand_path(path)
@shell.expand_path(path)
end
#
# File related commands
# Shell#foreach
# Shell#open
# Shell#unlink
# Shell#test
#
# -
#
# CommandProcessor#foreach(path, rs)
# path: String
# rs: String - record separator
# iterator
# Same as:
# File#foreach (when path is file)
# Dir#foreach (when path is directory)
# path is relative to pwd
#
def foreach(path = nil, *rs)
path = "." unless path
path = expand_path(path)
if File.directory?(path)
Dir.foreach(path){|fn| yield fn}
else
IO.foreach(path, *rs){|l| yield l}
end
end
#
# CommandProcessor#open(path, mode)
# path: String
# mode: String
# return: File or Dir
# Same as:
# File#open (when path is file)
# Dir#open (when path is directory)
# mode has an effect only when path is a file
#
def open(path, mode = nil, perm = 0666, &b)
path = expand_path(path)
if File.directory?(path)
Dir.open(path, &b)
else
if @shell.umask
f = File.open(path, mode, perm)
File.chmod(perm & ~@shell.umask, path)
if block_given?
f.each(&b)
end
f
else
f = File.open(path, mode, perm, &b)
end
end
end
# public :open
#
# CommandProcessor#unlink(path)
# same as:
# Dir#unlink (when path is directory)
# File#unlink (when path is file)
#
def unlink(path)
@shell.check_point
path = expand_path(path)
if File.directory?(path)
Dir.unlink(path)
else
IO.unlink(path)
end
Void.new(@shell)
end
#
# CommandProcessor#test(command, file1, file2)
# CommandProcessor#[command, file1, file2]
# command: char or String or Symbol
# file1: String
# file2: String(optional)
# return: Boolean
# same as:
# test() (when command is char or length 1 string or symbol)
# FileTest.command (others)
# example:
# sh[?e, "foo"]
# sh[:e, "foo"]
# sh["e", "foo"]
# sh[:exists?, "foo"]
# sh["exists?", "foo"]
#
alias top_level_test test
def test(command, file1, file2=nil)
file1 = expand_path(file1)
file2 = expand_path(file2) if file2
command = command.id2name if command.kind_of?(Symbol)
case command
when Integer
if file2
top_level_test(command, file1, file2)
else
top_level_test(command, file1)
end
when String
if command.size == 1
if file2
top_level_test(command, file1, file2)
else
top_level_test(command, file1)
end
else
if file2
FileTest.send(command, file1, file2)
else
FileTest.send(command, file1)
end
end
end
end
alias [] test
#
# Dir related methods
#
# Shell#mkdir
# Shell#rmdir
#
#--
#
# CommandProcessor#mkdir(*path)
# path: String
# same as Dir.mkdir()
#
def mkdir(*path)
@shell.check_point
notify("mkdir #{path.join(' ')}")
perm = nil
if path.last.kind_of?(Integer)
perm = path.pop
end
for dir in path
d = expand_path(dir)
if perm
Dir.mkdir(d, perm)
else
Dir.mkdir(d)
end
File.chmod(d, 0666 & ~@shell.umask) if @shell.umask
end
Void.new(@shell)
end
#
# CommandProcessor#rmdir(*path)
# path: String
# same as Dir.rmdir()
#
def rmdir(*path)
@shell.check_point
notify("rmdir #{path.join(' ')}")
for dir in path
Dir.rmdir(expand_path(dir))
end
Void.new(@shell)
end
#
# CommandProcessor#system(command, *opts)
# command: String
# opts: String
# return: SystemCommand
# Same as system() function
# example:
# print sh.system("ls", "-l")
# sh.system("ls", "-l") | sh.head > STDOUT
#
def system(command, *opts)
if opts.empty?
if command =~ /\*|\?|\{|\}|\[|\]|<|>|\(|\)|~|&|\||\\|\$|;|'|`|"|\n/
return SystemCommand.new(@shell, find_system_command("sh"), "-c", command)
else
command, *opts = command.split(/\s+/)
end
end
SystemCommand.new(@shell, find_system_command(command), *opts)
end
#
# ProcessCommand#rehash
# clear command hash table.
#
def rehash
@system_commands = {}
end
#
# ProcessCommand#transact
#
def check_point
@shell.process_controller.wait_all_jobs_execution
end
alias finish_all_jobs check_point
def transact(&block)
begin
@shell.instance_eval(&block)
ensure
check_point
end
end
#
# internal commands
#
def out(dev = STDOUT, &block)
dev.print transact(&block)
end
def echo(*strings)
Echo.new(@shell, *strings)
end
def cat(*filenames)
Cat.new(@shell, *filenames)
end
# def sort(*filenames)
# Sort.new(self, *filenames)
# end
def glob(pattern)
Glob.new(@shell, pattern)
end
def append(to, filter)
case to
when String
AppendFile.new(@shell, to, filter)
when IO
AppendIO.new(@shell, to, filter)
else
Shell.Fail Error::CantApplyMethod, "append", to.class
end
end
def tee(file)
Tee.new(@shell, file)
end
def concat(*jobs)
Concat.new(@shell, *jobs)
end
# %pwd, %cwd -> @pwd
def notify(*opts, &block)
Shell.notify(*opts) {|mes|
yield mes if iterator?
mes.gsub!("%pwd", "#{@cwd}")
mes.gsub!("%cwd", "#{@cwd}")
}
end
#
# private functions
#
def find_system_command(command)
return command if /^\// =~ command
case path = @system_commands[command]
when String
if exists?(path)
return path
else
Shell.Fail Error::CommandNotFound, command
end
when false
Shell.Fail Error::CommandNotFound, command
end
for p in @shell.system_path
path = join(p, command)
if FileTest.exist?(path)
@system_commands[command] = path
return path
end
end
@system_commands[command] = false
Shell.Fail Error::CommandNotFound, command
end
#
# CommandProcessor.def_system_command(command, path)
# command: String
# path: String
# define 'command()' method as method.
#
def self.def_system_command(command, path = command)
begin
eval((d = %Q[def #{command}(*opts)
SystemCommand.new(@shell, '#{path}', *opts)
end]), nil, __FILE__, __LINE__ - 1)
rescue SyntaxError
Shell.notify "warn: Can't define #{command} path: #{path}."
end
Shell.notify "Define #{command} path: #{path}.", Shell.debug?
Shell.notify("Definition of #{command}: ", d,
Shell.debug.kind_of?(Integer) && Shell.debug > 1)
end
def self.undef_system_command(command)
command = command.id2name if command.kind_of?(Symbol)
remove_method(command)
Shell.module_eval{remove_method(command)}
Filter.module_eval{remove_method(command)}
self
end
# define command alias
# ex)
# def_alias_command("ls_c", "ls", "-C", "-F")
# def_alias_command("ls_c", "ls"){|*opts| ["-C", "-F", *opts]}
#
@alias_map = {}
def self.alias_map
@alias_map
end
def self.alias_command(ali, command, *opts, &block)
ali = ali.id2name if ali.kind_of?(Symbol)
command = command.id2name if command.kind_of?(Symbol)
begin
if iterator?
@alias_map[ali.intern] = proc
eval((d = %Q[def #{ali}(*opts)
@shell.__send__(:#{command},
*(CommandProcessor.alias_map[:#{ali}].call *opts))
end]), nil, __FILE__, __LINE__ - 1)
else
args = opts.collect{|opt| '"' + opt + '"'}.join(",")
eval((d = %Q[def #{ali}(*opts)
@shell.__send__(:#{command}, #{args}, *opts)
end]), nil, __FILE__, __LINE__ - 1)
end
rescue SyntaxError
Shell.notify "warn: Can't alias #{ali} command: #{command}."
Shell.notify("Definition of #{ali}: ", d)
raise
end
Shell.notify "Define #{ali} command: #{command}.", Shell.debug?
Shell.notify("Definition of #{ali}: ", d,
Shell.debug.kind_of?(Integer) && Shell.debug > 1)
self
end
def self.unalias_command(ali)
ali = ali.id2name if ali.kind_of?(Symbol)
@alias_map.delete ali.intern
undef_system_command(ali)
end
#
# CommandProcessor.def_builtin_commands(delegation_class, command_specs)
# delegation_class: Class or Module
# command_specs: [[command_name, [argument,...]],...]
# command_name: String
# arguments: String
# FILENAME?? -> expand_path(filename??)
# *FILENAME?? -> filename??.collect{|f|expand_path(f)}.join(", ")
# define command_name(argument,...) as
# delegation_class.command_name(argument,...)
#
def self.def_builtin_commands(delegation_class, command_specs)
for meth, args in command_specs
arg_str = args.collect{|arg| arg.downcase}.join(", ")
call_arg_str = args.collect{
|arg|
case arg
when /^(FILENAME.*)$/
format("expand_path(%s)", $1.downcase)
when /^(\*FILENAME.*)$/
# \*FILENAME* -> filenames.collect{|fn| expand_path(fn)}.join(", ")
$1.downcase + '.collect{|fn| expand_path(fn)}'
else
arg
end
}.join(", ")
d = %Q[def #{meth}(#{arg_str})
#{delegation_class}.#{meth}(#{call_arg_str})
end]
Shell.notify "Define #{meth}(#{arg_str})", Shell.debug?
Shell.notify("Definition of #{meth}: ", d,
Shell.debug.kind_of?(Integer) && Shell.debug > 1)
eval d
end
end
#
# CommandProcessor.install_system_commands(pre)
# pre: String - command name prefix
# defines every command which belongs in default_system_path via
# CommandProcessor.command(). It doesn't define already defined
# methods twice. By default, "pre_" is prefixes to each method
# name. Characters that may not be used in a method name are
# all converted to '_'. Definition errors are just ignored.
#
def self.install_system_commands(pre = "sys_")
defined_meth = {}
for m in Shell.methods
defined_meth[m] = true
end
sh = Shell.new
for path in Shell.default_system_path
next unless sh.directory? path
sh.cd path
sh.foreach do
|cn|
if !defined_meth[pre + cn] && sh.file?(cn) && sh.executable?(cn)
command = (pre + cn).gsub(/\W/, "_").sub(/^([0-9])/, '_\1')
begin
def_system_command(command, sh.expand_path(cn))
rescue
Shell.notify "warn: Can't define #{command} path: #{cn}"
end
defined_meth[command] = command
end
end
end
end
#----------------------------------------------------------------------
#
# class initializing methods -
#
#----------------------------------------------------------------------
def self.add_delegate_command_to_shell(id)
id = id.intern if id.kind_of?(String)
name = id.id2name
if Shell.method_defined?(id)
Shell.notify "warn: override definnition of Shell##{name}."
Shell.notify "warn: alias Shell##{name} to Shell##{name}_org.\n"
Shell.module_eval "alias #{name}_org #{name}"
end
Shell.notify "method added: Shell##{name}.", Shell.debug?
Shell.module_eval(%Q[def #{name}(*args, &block)
begin
@command_processor.__send__(:#{name}, *args, &block)
rescue Exception
$@.delete_if{|s| /:in `__getobj__'$/ =~ s} #`
$@.delete_if{|s| /^\\(eval\\):/ =~ s}
raise
end
end], __FILE__, __LINE__)
if Shell::Filter.method_defined?(id)
Shell.notify "warn: override definnition of Shell::Filter##{name}."
Shell.notify "warn: alias Shell##{name} to Shell::Filter##{name}_org."
Filter.module_eval "alias #{name}_org #{name}"
end
Shell.notify "method added: Shell::Filter##{name}.", Shell.debug?
Filter.module_eval(%Q[def #{name}(*args, &block)
begin
self | @shell.__send__(:#{name}, *args, &block)
rescue Exception
$@.delete_if{|s| /:in `__getobj__'$/ =~ s} #`
$@.delete_if{|s| /^\\(eval\\):/ =~ s}
raise
end
end], __FILE__, __LINE__)
end
#
# define default builtin commands
#
def self.install_builtin_commands
# method related File.
# (exclude open/foreach/unlink)
normal_delegation_file_methods = [
["atime", ["FILENAME"]],
["basename", ["fn", "*opts"]],
["chmod", ["mode", "*FILENAMES"]],
["chown", ["owner", "group", "*FILENAME"]],
["ctime", ["FILENAMES"]],
["delete", ["*FILENAMES"]],
["dirname", ["FILENAME"]],
["ftype", ["FILENAME"]],
["join", ["*items"]],
["link", ["FILENAME_O", "FILENAME_N"]],
["lstat", ["FILENAME"]],
["mtime", ["FILENAME"]],
["readlink", ["FILENAME"]],
["rename", ["FILENAME_FROM", "FILENAME_TO"]],
# ["size", ["FILENAME"]],
["split", ["pathname"]],
["stat", ["FILENAME"]],
["symlink", ["FILENAME_O", "FILENAME_N"]],
["truncate", ["FILENAME", "length"]],
["utime", ["atime", "mtime", "*FILENAMES"]]]
def_builtin_commands(File, normal_delegation_file_methods)
alias_method :rm, :delete
# method related FileTest
def_builtin_commands(FileTest,
FileTest.singleton_methods(false).collect{|m| [m, ["FILENAME"]]})
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/shell/error.rb | tools/jruby-1.5.1/lib/ruby/1.9/shell/error.rb | #
# shell/error.rb -
# $Release Version: 0.7 $
# $Revision: 22784 $
# by Keiju ISHITSUKA(keiju@ruby-lang.org)
#
# --
#
#
#
require "e2mmap"
class Shell
module Error
extend Exception2MessageMapper
def_e2message TypeError, "wrong argument type %s (expected %s)"
def_exception :DirStackEmpty, "Directory stack empty."
def_exception :CantDefine, "Can't define method(%s, %s)."
def_exception :CantApplyMethod, "This method(%s) does not apply to this type(%s)."
def_exception :CommandNotFound, "Command not found(%s)."
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/drb/extserv.rb | tools/jruby-1.5.1/lib/ruby/1.9/drb/extserv.rb | =begin
external service
Copyright (c) 2000,2002 Masatoshi SEKI
=end
require 'drb/drb'
require 'monitor'
module DRb
class ExtServ
include MonitorMixin
include DRbUndumped
def initialize(there, name, server=nil)
super()
@server = server || DRb::primary_server
@name = name
ro = DRbObject.new(nil, there)
synchronize do
@invoker = ro.regist(name, DRbObject.new(self, @server.uri))
end
end
attr_reader :server
def front
DRbObject.new(nil, @server.uri)
end
def stop_service
synchronize do
@invoker.unregist(@name)
server = @server
@server = nil
server.stop_service
true
end
end
def alive?
@server ? @server.alive? : false
end
end
end
if __FILE__ == $0
class Foo
include DRbUndumped
def initialize(str)
@str = str
end
def hello(it)
"#{it}: #{self}"
end
def to_s
@str
end
end
cmd = ARGV.shift
case cmd
when 'itest1', 'itest2'
front = Foo.new(cmd)
manager = DRb::DRbServer.new(nil, front)
es = DRb::ExtServ.new(ARGV.shift, ARGV.shift, manager)
es.server.thread.join
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/drb/extservm.rb | tools/jruby-1.5.1/lib/ruby/1.9/drb/extservm.rb | =begin
external service manager
Copyright (c) 2000 Masatoshi SEKI
=end
require 'drb/drb'
require 'thread'
require 'monitor'
module DRb
class ExtServManager
include DRbUndumped
include MonitorMixin
@@command = {}
def self.command
@@command
end
def self.command=(cmd)
@@command = cmd
end
def initialize
super()
@cond = new_cond
@servers = {}
@waiting = []
@queue = Queue.new
@thread = invoke_thread
@uri = nil
end
attr_accessor :uri
def service(name)
synchronize do
while true
server = @servers[name]
return server if server && server.alive?
invoke_service(name)
@cond.wait
end
end
end
def regist(name, ro)
synchronize do
@servers[name] = ro
@cond.signal
end
self
end
def unregist(name)
synchronize do
@servers.delete(name)
end
end
private
def invoke_thread
Thread.new do
while true
name = @queue.pop
invoke_service_command(name, @@command[name])
end
end
end
def invoke_service(name)
@queue.push(name)
end
def invoke_service_command(name, command)
raise "invalid command. name: #{name}" unless command
synchronize do
return if @servers.include?(name)
@servers[name] = false
end
uri = @uri || DRb.uri
Process.detach spawn("#{command} #{uri} #{name}")
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/drb/observer.rb | tools/jruby-1.5.1/lib/ruby/1.9/drb/observer.rb | require 'observer'
module DRb
module DRbObservable
include Observable
def notify_observers(*arg)
if defined? @observer_state and @observer_state
if defined? @observer_peers
@observer_peers.each do |observer, method|
begin
observer.send(method, *arg)
rescue
delete_observer(observer)
end
end
end
@observer_state = false
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/drb/acl.rb | tools/jruby-1.5.1/lib/ruby/1.9/drb/acl.rb | # acl-2.0 - simple Access Control List
#
# Copyright (c) 2000,2002,2003 Masatoshi SEKI
#
# acl.rb is copyrighted free software by Masatoshi SEKI.
# You can redistribute it and/or modify it under the same terms as Ruby.
require 'ipaddr'
class ACL
VERSION=["2.0.0"]
class ACLEntry
def initialize(str)
if str == '*' or str == 'all'
@pat = [:all]
elsif str.include?('*')
@pat = [:name, dot_pat(str)]
else
begin
@pat = [:ip, IPAddr.new(str)]
rescue ArgumentError
@pat = [:name, dot_pat(str)]
end
end
end
private
def dot_pat_str(str)
list = str.split('.').collect { |s|
(s == '*') ? '.+' : s
}
list.join("\\.")
end
private
def dot_pat(str)
exp = "^" + dot_pat_str(str) + "$"
Regexp.new(exp)
end
public
def match(addr)
case @pat[0]
when :all
true
when :ip
begin
ipaddr = IPAddr.new(addr[3])
ipaddr = ipaddr.ipv4_mapped if @pat[1].ipv6? && ipaddr.ipv4?
rescue ArgumentError
return false
end
(@pat[1].include?(ipaddr)) ? true : false
when :name
(@pat[1] =~ addr[2]) ? true : false
else
false
end
end
end
class ACLList
def initialize
@list = []
end
public
def match(addr)
@list.each do |e|
return true if e.match(addr)
end
false
end
public
def add(str)
@list.push(ACLEntry.new(str))
end
end
DENY_ALLOW = 0
ALLOW_DENY = 1
def initialize(list=nil, order = DENY_ALLOW)
@order = order
@deny = ACLList.new
@allow = ACLList.new
install_list(list) if list
end
public
def allow_socket?(soc)
allow_addr?(soc.peeraddr)
end
public
def allow_addr?(addr)
case @order
when DENY_ALLOW
return true if @allow.match(addr)
return false if @deny.match(addr)
return true
when ALLOW_DENY
return false if @deny.match(addr)
return true if @allow.match(addr)
return false
else
false
end
end
public
def install_list(list)
i = 0
while i < list.size
permission, domain = list.slice(i,2)
case permission.downcase
when 'allow'
@allow.add(domain)
when 'deny'
@deny.add(domain)
else
raise "Invalid ACL entry #{list.to_s}"
end
i += 2
end
end
end
if __FILE__ == $0
# example
list = %w(deny all
allow 192.168.1.1
allow ::ffff:192.168.1.2
allow 192.168.1.3
)
addr = ["AF_INET", 10, "lc630", "192.168.1.3"]
acl = ACL.new
p acl.allow_addr?(addr)
acl = ACL.new(list, ACL::DENY_ALLOW)
p acl.allow_addr?(addr)
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/drb/ssl.rb | tools/jruby-1.5.1/lib/ruby/1.9/drb/ssl.rb | require 'socket'
require 'openssl'
require 'drb/drb'
require 'singleton'
module DRb
class DRbSSLSocket < DRbTCPSocket
class SSLConfig
DEFAULT = {
:SSLCertificate => nil,
:SSLPrivateKey => nil,
:SSLClientCA => nil,
:SSLCACertificatePath => nil,
:SSLCACertificateFile => nil,
:SSLVerifyMode => ::OpenSSL::SSL::VERIFY_NONE,
:SSLVerifyDepth => nil,
:SSLVerifyCallback => nil, # custom verification
:SSLCertificateStore => nil,
# Must specify if you use auto generated certificate.
:SSLCertName => nil, # e.g. [["CN","fqdn.example.com"]]
:SSLCertComment => "Generated by Ruby/OpenSSL"
}
def initialize(config)
@config = config
@cert = config[:SSLCertificate]
@pkey = config[:SSLPrivateKey]
@ssl_ctx = nil
end
def [](key);
@config[key] || DEFAULT[key]
end
def connect(tcp)
ssl = ::OpenSSL::SSL::SSLSocket.new(tcp, @ssl_ctx)
ssl.sync = true
ssl.connect
ssl
end
def accept(tcp)
ssl = OpenSSL::SSL::SSLSocket.new(tcp, @ssl_ctx)
ssl.sync = true
ssl.accept
ssl
end
def setup_certificate
if @cert && @pkey
return
end
rsa = OpenSSL::PKey::RSA.new(512){|p, n|
next unless self[:verbose]
case p
when 0; $stderr.putc "." # BN_generate_prime
when 1; $stderr.putc "+" # BN_generate_prime
when 2; $stderr.putc "*" # searching good prime,
# n = #of try,
# but also data from BN_generate_prime
when 3; $stderr.putc "\n" # found good prime, n==0 - p, n==1 - q,
# but also data from BN_generate_prime
else; $stderr.putc "*" # BN_generate_prime
end
}
cert = OpenSSL::X509::Certificate.new
cert.version = 3
cert.serial = 0
name = OpenSSL::X509::Name.new(self[:SSLCertName])
cert.subject = name
cert.issuer = name
cert.not_before = Time.now
cert.not_after = Time.now + (365*24*60*60)
cert.public_key = rsa.public_key
ef = OpenSSL::X509::ExtensionFactory.new(nil,cert)
cert.extensions = [
ef.create_extension("basicConstraints","CA:FALSE"),
ef.create_extension("subjectKeyIdentifier", "hash") ]
ef.issuer_certificate = cert
cert.add_extension(ef.create_extension("authorityKeyIdentifier",
"keyid:always,issuer:always"))
if comment = self[:SSLCertComment]
cert.add_extension(ef.create_extension("nsComment", comment))
end
cert.sign(rsa, OpenSSL::Digest::SHA1.new)
@cert = cert
@pkey = rsa
end
def setup_ssl_context
ctx = ::OpenSSL::SSL::SSLContext.new
ctx.cert = @cert
ctx.key = @pkey
ctx.client_ca = self[:SSLClientCA]
ctx.ca_path = self[:SSLCACertificatePath]
ctx.ca_file = self[:SSLCACertificateFile]
ctx.verify_mode = self[:SSLVerifyMode]
ctx.verify_depth = self[:SSLVerifyDepth]
ctx.verify_callback = self[:SSLVerifyCallback]
ctx.cert_store = self[:SSLCertificateStore]
@ssl_ctx = ctx
end
end
def self.parse_uri(uri)
if uri =~ /^drbssl:\/\/(.*?):(\d+)(\?(.*))?$/
host = $1
port = $2.to_i
option = $4
[host, port, option]
else
raise(DRbBadScheme, uri) unless uri =~ /^drbssl:/
raise(DRbBadURI, 'can\'t parse uri:' + uri)
end
end
def self.open(uri, config)
host, port, option = parse_uri(uri)
host.untaint
port.untaint
soc = TCPSocket.open(host, port)
ssl_conf = SSLConfig::new(config)
ssl_conf.setup_ssl_context
ssl = ssl_conf.connect(soc)
self.new(uri, ssl, ssl_conf, true)
end
def self.open_server(uri, config)
uri = 'drbssl://:0' unless uri
host, port, opt = parse_uri(uri)
if host.size == 0
host = getservername
soc = open_server_inaddr_any(host, port)
else
soc = TCPServer.open(host, port)
end
port = soc.addr[1] if port == 0
@uri = "drbssl://#{host}:#{port}"
ssl_conf = SSLConfig.new(config)
ssl_conf.setup_certificate
ssl_conf.setup_ssl_context
self.new(@uri, soc, ssl_conf, false)
end
def self.uri_option(uri, config)
host, port, option = parse_uri(uri)
return "drbssl://#{host}:#{port}", option
end
def initialize(uri, soc, config, is_established)
@ssl = is_established ? soc : nil
super(uri, soc.to_io, config)
end
def stream; @ssl; end
def close
if @ssl
@ssl.close
@ssl = nil
end
super
end
def accept
begin
while true
soc = @socket.accept
break if (@acl ? @acl.allow_socket?(soc) : true)
soc.close
end
ssl = @config.accept(soc)
self.class.new(uri, ssl, @config, true)
rescue OpenSSL::SSL::SSLError
warn("#{__FILE__}:#{__LINE__}: warning: #{$!.message} (#{$!.class})") if @config[:verbose]
retry
end
end
end
DRbProtocol.add_protocol(DRbSSLSocket)
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/drb/timeridconv.rb | tools/jruby-1.5.1/lib/ruby/1.9/drb/timeridconv.rb | require 'drb/drb'
require 'monitor'
module DRb
class TimerIdConv < DRbIdConv
class TimerHolder2
include MonitorMixin
class InvalidIndexError < RuntimeError; end
def initialize(timeout=600)
super()
@sentinel = Object.new
@gc = {}
@curr = {}
@renew = {}
@timeout = timeout
@keeper = keeper
end
def add(obj)
synchronize do
key = obj.__id__
@curr[key] = obj
return key
end
end
def fetch(key, dv=@sentinel)
synchronize do
obj = peek(key)
if obj == @sentinel
return dv unless dv == @sentinel
raise InvalidIndexError
end
@renew[key] = obj # KeepIt
return obj
end
end
def include?(key)
synchronize do
obj = peek(key)
return false if obj == @sentinel
true
end
end
def peek(key)
synchronize do
return @curr.fetch(key, @renew.fetch(key, @gc.fetch(key, @sentinel)))
end
end
private
def alternate
synchronize do
@gc = @curr # GCed
@curr = @renew
@renew = {}
end
end
def keeper
Thread.new do
loop do
size = alternate
sleep(@timeout)
end
end
end
end
def initialize(timeout=600)
@holder = TimerHolder2.new(timeout)
end
def to_obj(ref)
return super if ref.nil?
@holder.fetch(ref)
rescue TimerHolder2::InvalidIndexError
raise "invalid reference"
end
def to_id(obj)
return @holder.add(obj)
end
end
end
# DRb.install_id_conv(TimerIdConv.new)
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/drb/drb.rb | tools/jruby-1.5.1/lib/ruby/1.9/drb/drb.rb | #
# = drb/drb.rb
#
# Distributed Ruby: _dRuby_ version 2.0.4
#
# Copyright (c) 1999-2003 Masatoshi SEKI. You can redistribute it and/or
# modify it under the same terms as Ruby.
#
# Author:: Masatoshi SEKI
#
# Documentation:: William Webber (william@williamwebber.com)
#
# == Overview
#
# dRuby is a distributed object system for Ruby. It allows an object in one
# Ruby process to invoke methods on an object in another Ruby process on the
# same or a different machine.
#
# The Ruby standard library contains the core classes of the dRuby package.
# However, the full package also includes access control lists and the
# Rinda tuple-space distributed task management system, as well as a
# large number of samples. The full dRuby package can be downloaded from
# the dRuby home page (see *References*).
#
# For an introduction and examples of usage see the documentation to the
# DRb module.
#
# == References
#
# [http://www2a.biglobe.ne.jp/~seki/ruby/druby.html]
# The dRuby home page, in Japanese. Contains the full dRuby package
# and links to other Japanese-language sources.
#
# [http://www2a.biglobe.ne.jp/~seki/ruby/druby.en.html]
# The English version of the dRuby home page.
#
# [http://www.chadfowler.com/ruby/drb.html]
# A quick tutorial introduction to using dRuby by Chad Fowler.
#
# [http://www.linux-mag.com/2002-09/ruby_05.html]
# A tutorial introduction to dRuby in Linux Magazine by Dave Thomas.
# Includes a discussion of Rinda.
#
# [http://www.eng.cse.dmu.ac.uk/~hgs/ruby/dRuby/]
# Links to English-language Ruby material collected by Hugh Sasse.
#
# [http://www.rubycentral.com/book/ospace.html]
# The chapter from *Programming* *Ruby* by Dave Thomas and Andy Hunt
# which discusses dRuby.
#
# [http://www.clio.ne.jp/home/web-i31s/Flotuard/Ruby/PRC2K_seki/dRuby.en.html]
# Translation of presentation on Ruby by Masatoshi Seki.
require 'socket'
require 'thread'
require 'fcntl'
require 'weakref'
require 'drb/eq'
#
# == Overview
#
# dRuby is a distributed object system for Ruby. It is written in
# pure Ruby and uses its own protocol. No add-in services are needed
# beyond those provided by the Ruby runtime, such as TCP sockets. It
# does not rely on or interoperate with other distributed object
# systems such as CORBA, RMI, or .NET.
#
# dRuby allows methods to be called in one Ruby process upon a Ruby
# object located in another Ruby process, even on another machine.
# References to objects can be passed between processes. Method
# arguments and return values are dumped and loaded in marshalled
# format. All of this is done transparently to both the caller of the
# remote method and the object that it is called upon.
#
# An object in a remote process is locally represented by a
# DRb::DRbObject instance. This acts as a sort of proxy for the
# remote object. Methods called upon this DRbObject instance are
# forwarded to its remote object. This is arranged dynamically at run
# time. There are no statically declared interfaces for remote
# objects, such as CORBA's IDL.
#
# dRuby calls made into a process are handled by a DRb::DRbServer
# instance within that process. This reconstitutes the method call,
# invokes it upon the specified local object, and returns the value to
# the remote caller. Any object can receive calls over dRuby. There
# is no need to implement a special interface, or mixin special
# functionality. Nor, in the general case, does an object need to
# explicitly register itself with a DRbServer in order to receive
# dRuby calls.
#
# One process wishing to make dRuby calls upon another process must
# somehow obtain an initial reference to an object in the remote
# process by some means other than as the return value of a remote
# method call, as there is initially no remote object reference it can
# invoke a method upon. This is done by attaching to the server by
# URI. Each DRbServer binds itself to a URI such as
# 'druby://example.com:8787'. A DRbServer can have an object attached
# to it that acts as the server's *front* *object*. A DRbObject can
# be explicitly created from the server's URI. This DRbObject's
# remote object will be the server's front object. This front object
# can then return references to other Ruby objects in the DRbServer's
# process.
#
# Method calls made over dRuby behave largely the same as normal Ruby
# method calls made within a process. Method calls with blocks are
# supported, as are raising exceptions. In addition to a method's
# standard errors, a dRuby call may also raise one of the
# dRuby-specific errors, all of which are subclasses of DRb::DRbError.
#
# Any type of object can be passed as an argument to a dRuby call or
# returned as its return value. By default, such objects are dumped
# or marshalled at the local end, then loaded or unmarshalled at the
# remote end. The remote end therefore receives a copy of the local
# object, not a distributed reference to it; methods invoked upon this
# copy are executed entirely in the remote process, not passed on to
# the local original. This has semantics similar to pass-by-value.
#
# However, if an object cannot be marshalled, a dRuby reference to it
# is passed or returned instead. This will turn up at the remote end
# as a DRbObject instance. All methods invoked upon this remote proxy
# are forwarded to the local object, as described in the discussion of
# DRbObjects. This has semantics similar to the normal Ruby
# pass-by-reference.
#
# The easiest way to signal that we want an otherwise marshallable
# object to be passed or returned as a DRbObject reference, rather
# than marshalled and sent as a copy, is to include the
# DRb::DRbUndumped mixin module.
#
# dRuby supports calling remote methods with blocks. As blocks (or
# rather the Proc objects that represent them) are not marshallable,
# the block executes in the local, not the remote, context. Each
# value yielded to the block is passed from the remote object to the
# local block, then the value returned by each block invocation is
# passed back to the remote execution context to be collected, before
# the collected values are finally returned to the local context as
# the return value of the method invocation.
#
# == Examples of usage
#
# For more dRuby samples, see the +samples+ directory in the full
# dRuby distribution.
#
# === dRuby in client/server mode
#
# This illustrates setting up a simple client-server drb
# system. Run the server and client code in different terminals,
# starting the server code first.
#
# ==== Server code
#
# require 'drb/drb'
#
# # The URI for the server to connect to
# URI="druby://localhost:8787"
#
# class TimeServer
#
# def get_current_time
# return Time.now
# end
#
# end
#
# # The object that handles requests on the server
# FRONT_OBJECT=TimeServer.new
#
# $SAFE = 1 # disable eval() and friends
#
# DRb.start_service(URI, FRONT_OBJECT)
# # Wait for the drb server thread to finish before exiting.
# DRb.thread.join
#
# ==== Client code
#
# require 'drb/drb'
#
# # The URI to connect to
# SERVER_URI="druby://localhost:8787"
#
# # Start a local DRbServer to handle callbacks.
# #
# # Not necessary for this small example, but will be required
# # as soon as we pass a non-marshallable object as an argument
# # to a dRuby call.
# DRb.start_service
#
# timeserver = DRbObject.new_with_uri(SERVER_URI)
# puts timeserver.get_current_time
#
# === Remote objects under dRuby
#
# This example illustrates returning a reference to an object
# from a dRuby call. The Logger instances live in the server
# process. References to them are returned to the client process,
# where methods can be invoked upon them. These methods are
# executed in the server process.
#
# ==== Server code
#
# require 'drb/drb'
#
# URI="druby://localhost:8787"
#
# class Logger
#
# # Make dRuby send Logger instances as dRuby references,
# # not copies.
# include DRb::DRbUndumped
#
# def initialize(n, fname)
# @name = n
# @filename = fname
# end
#
# def log(message)
# File.open(@filename, "a") do |f|
# f.puts("#{Time.now}: #{@name}: #{message}")
# end
# end
#
# end
#
# # We have a central object for creating and retrieving loggers.
# # This retains a local reference to all loggers created. This
# # is so an existing logger can be looked up by name, but also
# # to prevent loggers from being garbage collected. A dRuby
# # reference to an object is not sufficient to prevent it being
# # garbage collected!
# class LoggerFactory
#
# def initialize(bdir)
# @basedir = bdir
# @loggers = {}
# end
#
# def get_logger(name)
# if !@loggers.has_key? name
# # make the filename safe, then declare it to be so
# fname = name.gsub(/[.\/]/, "_").untaint
# @loggers[name] = Logger.new(name, @basedir + "/" + fname)
# end
# return @loggers[name]
# end
#
# end
#
# FRONT_OBJECT=LoggerFactory.new("/tmp/dlog")
#
# $SAFE = 1 # disable eval() and friends
#
# DRb.start_service(URI, FRONT_OBJECT)
# DRb.thread.join
#
# ==== Client code
#
# require 'drb/drb'
#
# SERVER_URI="druby://localhost:8787"
#
# DRb.start_service
#
# log_service=DRbObject.new_with_uri(SERVER_URI)
#
# ["loga", "logb", "logc"].each do |logname|
#
# logger=log_service.get_logger(logname)
#
# logger.log("Hello, world!")
# logger.log("Goodbye, world!")
# logger.log("=== EOT ===")
#
# end
#
# == Security
#
# As with all network services, security needs to be considered when
# using dRuby. By allowing external access to a Ruby object, you are
# not only allowing outside clients to call the methods you have
# defined for that object, but by default to execute arbitrary Ruby
# code on your server. Consider the following:
#
# # !!! UNSAFE CODE !!!
# ro = DRbObject::new_with_uri("druby://your.server.com:8989")
# class << ro
# undef :instance_eval # force call to be passed to remote object
# end
# ro.instance_eval("`rm -rf *`")
#
# The dangers posed by instance_eval and friends are such that a
# DRbServer should generally be run with $SAFE set to at least
# level 1. This will disable eval() and related calls on strings
# passed across the wire. The sample usage code given above follows
# this practice.
#
# A DRbServer can be configured with an access control list to
# selectively allow or deny access from specified IP addresses. The
# main druby distribution provides the ACL class for this purpose. In
# general, this mechanism should only be used alongside, rather than
# as a replacement for, a good firewall.
#
# == dRuby internals
#
# dRuby is implemented using three main components: a remote method
# call marshaller/unmarshaller; a transport protocol; and an
# ID-to-object mapper. The latter two can be directly, and the first
# indirectly, replaced, in order to provide different behaviour and
# capabilities.
#
# Marshalling and unmarshalling of remote method calls is performed by
# a DRb::DRbMessage instance. This uses the Marshal module to dump
# the method call before sending it over the transport layer, then
# reconstitute it at the other end. There is normally no need to
# replace this component, and no direct way is provided to do so.
# However, it is possible to implement an alternative marshalling
# scheme as part of an implementation of the transport layer.
#
# The transport layer is responsible for opening client and server
# network connections and forwarding dRuby request across them.
# Normally, it uses DRb::DRbMessage internally to manage marshalling
# and unmarshalling. The transport layer is managed by
# DRb::DRbProtocol. Multiple protocols can be installed in
# DRbProtocol at the one time; selection between them is determined by
# the scheme of a dRuby URI. The default transport protocol is
# selected by the scheme 'druby:', and implemented by
# DRb::DRbTCPSocket. This uses plain TCP/IP sockets for
# communication. An alternative protocol, using UNIX domain sockets,
# is implemented by DRb::DRbUNIXSocket in the file drb/unix.rb, and
# selected by the scheme 'drbunix:'. A sample implementation over
# HTTP can be found in the samples accompanying the main dRuby
# distribution.
#
# The ID-to-object mapping component maps dRuby object ids to the
# objects they refer to, and vice versa. The implementation to use
# can be specified as part of a DRb::DRbServer's configuration. The
# default implementation is provided by DRb::DRbIdConv. It uses an
# object's ObjectSpace id as its dRuby id. This means that the dRuby
# reference to that object only remains meaningful for the lifetime of
# the object's process and the lifetime of the object within that
# process. A modified implementation is provided by DRb::TimerIdConv
# in the file drb/timeridconv.rb. This implementation retains a local
# reference to all objects exported over dRuby for a configurable
# period of time (defaulting to ten minutes), to prevent them being
# garbage-collected within this time. Another sample implementation
# is provided in sample/name.rb in the main dRuby distribution. This
# allows objects to specify their own id or "name". A dRuby reference
# can be made persistent across processes by having each process
# register an object using the same dRuby name.
#
module DRb
# Superclass of all errors raised in the DRb module.
class DRbError < RuntimeError; end
# Error raised when an error occurs on the underlying communication
# protocol.
class DRbConnError < DRbError; end
# Class responsible for converting between an object and its id.
#
# This, the default implementation, uses an object's local ObjectSpace
# __id__ as its id. This means that an object's identification over
# drb remains valid only while that object instance remains alive
# within the server runtime.
#
# For alternative mechanisms, see DRb::TimerIdConv in rdb/timeridconv.rb
# and DRbNameIdConv in sample/name.rb in the full drb distribution.
class DRbIdConv
def initialize
@id2ref = {}
end
# Convert an object reference id to an object.
#
# This implementation looks up the reference id in the local object
# space and returns the object it refers to.
def to_obj(ref)
_get(ref)
end
# Convert an object into a reference id.
#
# This implementation returns the object's __id__ in the local
# object space.
def to_id(obj)
obj.nil? ? nil : _put(obj)
end
def _clean
dead = []
@id2ref.each {|id,weakref| dead << id unless weakref.weakref_alive?}
dead.each {|id| @id2ref.delete(id)}
end
def _put(obj)
_clean
@id2ref[obj.__id__] = WeakRef.new(obj)
obj.__id__
end
def _get(id)
weakref = @id2ref[id]
if weakref
result = weakref.__getobj__ rescue nil
if result
return result
else
@id2ref.delete id
end
end
nil
end
private :_clean, :_put, :_get
end
# Mixin module making an object undumpable or unmarshallable.
#
# If an object which includes this module is returned by method
# called over drb, then the object remains in the server space
# and a reference to the object is returned, rather than the
# object being marshalled and moved into the client space.
module DRbUndumped
def _dump(dummy) # :nodoc:
raise TypeError, 'can\'t dump'
end
end
# Error raised by the DRb module when an attempt is made to refer to
# the context's current drb server but the context does not have one.
# See #current_server.
class DRbServerNotFound < DRbError; end
# Error raised by the DRbProtocol module when it cannot find any
# protocol implementation support the scheme specified in a URI.
class DRbBadURI < DRbError; end
# Error raised by a dRuby protocol when it doesn't support the
# scheme specified in a URI. See DRb::DRbProtocol.
class DRbBadScheme < DRbError; end
# An exception wrapping a DRb::DRbUnknown object
class DRbUnknownError < DRbError
# Create a new DRbUnknownError for the DRb::DRbUnknown object +unknown+
def initialize(unknown)
@unknown = unknown
super(unknown.name)
end
# Get the wrapped DRb::DRbUnknown object.
attr_reader :unknown
def self._load(s) # :nodoc:
Marshal::load(s)
end
def _dump(lv) # :nodoc:
Marshal::dump(@unknown)
end
end
# An exception wrapping an error object
class DRbRemoteError < DRbError
def initialize(error)
@reason = error.class.to_s
super("#{error.message} (#{error.class})")
set_backtrace(error.backtrace)
end
# the class of the error, as a string.
attr_reader :reason
end
# Class wrapping a marshalled object whose type is unknown locally.
#
# If an object is returned by a method invoked over drb, but the
# class of the object is unknown in the client namespace, or
# the object is a constant unknown in the client namespace, then
# the still-marshalled object is returned wrapped in a DRbUnknown instance.
#
# If this object is passed as an argument to a method invoked over
# drb, then the wrapped object is passed instead.
#
# The class or constant name of the object can be read from the
# +name+ attribute. The marshalled object is held in the +buf+
# attribute.
class DRbUnknown
# Create a new DRbUnknown object.
#
# +buf+ is a string containing a marshalled object that could not
# be unmarshalled. +err+ is the error message that was raised
# when the unmarshalling failed. It is used to determine the
# name of the unmarshalled object.
def initialize(err, buf)
case err.to_s
when /uninitialized constant (\S+)/
@name = $1
when /undefined class\/module (\S+)/
@name = $1
else
@name = nil
end
@buf = buf
end
# The name of the unknown thing.
#
# Class name for unknown objects; variable name for unknown
# constants.
attr_reader :name
# Buffer contained the marshalled, unknown object.
attr_reader :buf
def self._load(s) # :nodoc:
begin
Marshal::load(s)
rescue NameError, ArgumentError
DRbUnknown.new($!, s)
end
end
def _dump(lv) # :nodoc:
@buf
end
# Attempt to load the wrapped marshalled object again.
#
# If the class of the object is now known locally, the object
# will be unmarshalled and returned. Otherwise, a new
# but identical DRbUnknown object will be returned.
def reload
self.class._load(@buf)
end
# Create a DRbUnknownError exception containing this object.
def exception
DRbUnknownError.new(self)
end
end
class DRbArray
def initialize(ary)
@ary = ary.collect { |obj|
if obj.kind_of? DRbUndumped
DRbObject.new(obj)
else
begin
Marshal.dump(obj)
obj
rescue
DRbObject.new(obj)
end
end
}
end
def self._load(s)
Marshal::load(s)
end
def _dump(lv)
Marshal.dump(@ary)
end
end
# Handler for sending and receiving drb messages.
#
# This takes care of the low-level marshalling and unmarshalling
# of drb requests and responses sent over the wire between server
# and client. This relieves the implementor of a new drb
# protocol layer with having to deal with these details.
#
# The user does not have to directly deal with this object in
# normal use.
class DRbMessage
def initialize(config) # :nodoc:
@load_limit = config[:load_limit]
@argc_limit = config[:argc_limit]
end
def dump(obj, error=false) # :nodoc:
obj = make_proxy(obj, error) if obj.kind_of? DRbUndumped
begin
str = Marshal::dump(obj)
rescue
str = Marshal::dump(make_proxy(obj, error))
end
[str.size].pack('N') + str
end
def load(soc) # :nodoc:
begin
sz = soc.read(4) # sizeof (N)
rescue
raise(DRbConnError, $!.message, $!.backtrace)
end
raise(DRbConnError, 'connection closed') if sz.nil?
raise(DRbConnError, 'premature header') if sz.size < 4
sz = sz.unpack('N')[0]
raise(DRbConnError, "too large packet #{sz}") if @load_limit < sz
begin
str = soc.read(sz)
rescue
raise(DRbConnError, $!.message, $!.backtrace)
end
raise(DRbConnError, 'connection closed') if str.nil?
raise(DRbConnError, 'premature marshal format(can\'t read)') if str.size < sz
DRb.mutex.synchronize do
begin
save = Thread.current[:drb_untaint]
Thread.current[:drb_untaint] = []
Marshal::load(str)
rescue NameError, ArgumentError
DRbUnknown.new($!, str)
ensure
Thread.current[:drb_untaint].each do |x|
x.untaint
end
Thread.current[:drb_untaint] = save
end
end
end
def send_request(stream, ref, msg_id, arg, b) # :nodoc:
ary = []
ary.push(dump(ref.__drbref))
ary.push(dump(msg_id.id2name))
ary.push(dump(arg.length))
arg.each do |e|
ary.push(dump(e))
end
ary.push(dump(b))
stream.write(ary.join(''))
rescue
raise(DRbConnError, $!.message, $!.backtrace)
end
def recv_request(stream) # :nodoc:
ref = load(stream)
ro = DRb.to_obj(ref)
msg = load(stream)
argc = load(stream)
raise ArgumentError, 'too many arguments' if @argc_limit < argc
argv = Array.new(argc, nil)
argc.times do |n|
argv[n] = load(stream)
end
block = load(stream)
return ro, msg, argv, block
end
def send_reply(stream, succ, result) # :nodoc:
stream.write(dump(succ) + dump(result, !succ))
rescue
raise(DRbConnError, $!.message, $!.backtrace)
end
def recv_reply(stream) # :nodoc:
succ = load(stream)
result = load(stream)
[succ, result]
end
private
def make_proxy(obj, error=false)
if error
DRbRemoteError.new(obj)
else
DRbObject.new(obj)
end
end
end
# Module managing the underlying network protocol(s) used by drb.
#
# By default, drb uses the DRbTCPSocket protocol. Other protocols
# can be defined. A protocol must define the following class methods:
#
# [open(uri, config)] Open a client connection to the server at +uri+,
# using configuration +config+. Return a protocol
# instance for this connection.
# [open_server(uri, config)] Open a server listening at +uri+,
# using configuration +config+. Return a
# protocol instance for this listener.
# [uri_option(uri, config)] Take a URI, possibly containing an option
# component (e.g. a trailing '?param=val'),
# and return a [uri, option] tuple.
#
# All of these methods should raise a DRbBadScheme error if the URI
# does not identify the protocol they support (e.g. "druby:" for
# the standard Ruby protocol). This is how the DRbProtocol module,
# given a URI, determines which protocol implementation serves that
# protocol.
#
# The protocol instance returned by #open_server must have the
# following methods:
#
# [accept] Accept a new connection to the server. Returns a protocol
# instance capable of communicating with the client.
# [close] Close the server connection.
# [uri] Get the URI for this server.
#
# The protocol instance returned by #open must have the following methods:
#
# [send_request (ref, msg_id, arg, b)]
# Send a request to +ref+ with the given message id and arguments.
# This is most easily implemented by calling DRbMessage.send_request,
# providing a stream that sits on top of the current protocol.
# [recv_reply]
# Receive a reply from the server and return it as a [success-boolean,
# reply-value] pair. This is most easily implemented by calling
# DRb.recv_reply, providing a stream that sits on top of the
# current protocol.
# [alive?]
# Is this connection still alive?
# [close]
# Close this connection.
#
# The protocol instance returned by #open_server().accept() must have
# the following methods:
#
# [recv_request]
# Receive a request from the client and return a [object, message,
# args, block] tuple. This is most easily implemented by calling
# DRbMessage.recv_request, providing a stream that sits on top of
# the current protocol.
# [send_reply(succ, result)]
# Send a reply to the client. This is most easily implemented
# by calling DRbMessage.send_reply, providing a stream that sits
# on top of the current protocol.
# [close]
# Close this connection.
#
# A new protocol is registered with the DRbProtocol module using
# the add_protocol method.
#
# For examples of other protocols, see DRbUNIXSocket in drb/unix.rb,
# and HTTP0 in sample/http0.rb and sample/http0serv.rb in the full
# drb distribution.
module DRbProtocol
# Add a new protocol to the DRbProtocol module.
def add_protocol(prot)
@protocol.push(prot)
end
module_function :add_protocol
# Open a client connection to +uri+ with the configuration +config+.
#
# The DRbProtocol module asks each registered protocol in turn to
# try to open the URI. Each protocol signals that it does not handle that
# URI by raising a DRbBadScheme error. If no protocol recognises the
# URI, then a DRbBadURI error is raised. If a protocol accepts the
# URI, but an error occurs in opening it, a DRbConnError is raised.
def open(uri, config, first=true)
@protocol.each do |prot|
begin
return prot.open(uri, config)
rescue DRbBadScheme
rescue DRbConnError
raise($!)
rescue
raise(DRbConnError, "#{uri} - #{$!.inspect}")
end
end
if first && (config[:auto_load] != false)
auto_load(uri, config)
return open(uri, config, false)
end
raise DRbBadURI, 'can\'t parse uri:' + uri
end
module_function :open
# Open a server listening for connections at +uri+ with
# configuration +config+.
#
# The DRbProtocol module asks each registered protocol in turn to
# try to open a server at the URI. Each protocol signals that it does
# not handle that URI by raising a DRbBadScheme error. If no protocol
# recognises the URI, then a DRbBadURI error is raised. If a protocol
# accepts the URI, but an error occurs in opening it, the underlying
# error is passed on to the caller.
def open_server(uri, config, first=true)
@protocol.each do |prot|
begin
return prot.open_server(uri, config)
rescue DRbBadScheme
end
end
if first && (config[:auto_load] != false)
auto_load(uri, config)
return open_server(uri, config, false)
end
raise DRbBadURI, 'can\'t parse uri:' + uri
end
module_function :open_server
# Parse +uri+ into a [uri, option] pair.
#
# The DRbProtocol module asks each registered protocol in turn to
# try to parse the URI. Each protocol signals that it does not handle that
# URI by raising a DRbBadScheme error. If no protocol recognises the
# URI, then a DRbBadURI error is raised.
def uri_option(uri, config, first=true)
@protocol.each do |prot|
begin
uri, opt = prot.uri_option(uri, config)
# opt = nil if opt == ''
return uri, opt
rescue DRbBadScheme
end
end
if first && (config[:auto_load] != false)
auto_load(uri, config)
return uri_option(uri, config, false)
end
raise DRbBadURI, 'can\'t parse uri:' + uri
end
module_function :uri_option
def auto_load(uri, config) # :nodoc:
if uri =~ /^drb([a-z0-9]+):/
require("drb/#{$1}") rescue nil
end
end
module_function :auto_load
end
# The default drb protocol.
#
# Communicates over a TCP socket.
class DRbTCPSocket
private
def self.parse_uri(uri)
if uri =~ /^druby:\/\/(.*?):(\d+)(\?(.*))?$/
host = $1
port = $2.to_i
option = $4
[host, port, option]
else
raise(DRbBadScheme, uri) unless uri =~ /^druby:/
raise(DRbBadURI, 'can\'t parse uri:' + uri)
end
end
public
# Open a client connection to +uri+ using configuration +config+.
def self.open(uri, config)
host, port, option = parse_uri(uri)
host.untaint
port.untaint
soc = TCPSocket.open(host, port)
self.new(uri, soc, config)
end
def self.getservername
host = Socket::gethostname
begin
Socket::gethostbyname(host)[0]
rescue
'localhost'
end
end
def self.open_server_inaddr_any(host, port)
infos = Socket::getaddrinfo(host, nil,
Socket::AF_UNSPEC,
Socket::SOCK_STREAM,
0,
Socket::AI_PASSIVE)
families = Hash[*infos.collect { |af, *_| af }.uniq.zip([]).flatten]
return TCPServer.open('0.0.0.0', port) if families.has_key?('AF_INET')
return TCPServer.open('::', port) if families.has_key?('AF_INET6')
return TCPServer.open(port)
end
# Open a server listening for connections at +uri+ using
# configuration +config+.
def self.open_server(uri, config)
uri = 'druby://:0' unless uri
host, port, opt = parse_uri(uri)
config = {:tcp_original_host => host}.update(config)
if host.size == 0
host = getservername
soc = open_server_inaddr_any(host, port)
else
soc = TCPServer.open(host, port)
end
port = soc.addr[1] if port == 0
config[:tcp_port] = port
uri = "druby://#{host}:#{port}"
self.new(uri, soc, config)
end
# Parse +uri+ into a [uri, option] pair.
def self.uri_option(uri, config)
host, port, option = parse_uri(uri)
return "druby://#{host}:#{port}", option
end
# Create a new DRbTCPSocket instance.
#
# +uri+ is the URI we are connected to.
# +soc+ is the tcp socket we are bound to. +config+ is our
# configuration.
def initialize(uri, soc, config={})
@uri = uri
@socket = soc
@config = config
@acl = config[:tcp_acl]
@msg = DRbMessage.new(config)
set_sockopt(@socket)
end
# Get the URI that we are connected to.
attr_reader :uri
# Get the address of our TCP peer (the other end of the socket
# we are bound to.
def peeraddr
@socket.peeraddr
end
# Get the socket.
def stream; @socket; end
# On the client side, send a request to the server.
def send_request(ref, msg_id, arg, b)
@msg.send_request(stream, ref, msg_id, arg, b)
end
# On the server side, receive a request from the client.
def recv_request
@msg.recv_request(stream)
end
# On the server side, send a reply to the client.
def send_reply(succ, result)
@msg.send_reply(stream, succ, result)
end
# On the client side, receive a reply from the server.
def recv_reply
@msg.recv_reply(stream)
end
public
# Close the connection.
#
# If this is an instance returned by #open_server, then this stops
# listening for new connections altogether. If this is an instance
# returned by #open or by #accept, then it closes this particular
# client-server session.
def close
if @socket
@socket.close
@socket = nil
end
end
# On the server side, for an instance returned by #open_server,
# accept a client connection and return a new instance to handle
# the server's side of this client-server session.
def accept
while true
s = @socket.accept
break if (@acl ? @acl.allow_socket?(s) : true)
s.close
end
if @config[:tcp_original_host].to_s.size == 0
uri = "druby://#{s.addr[3]}:#{@config[:tcp_port]}"
else
uri = @uri
end
self.class.new(uri, s, @config)
end
# Check to see if this connection is alive.
def alive?
return false unless @socket
if IO.select([@socket], nil, nil, 0)
close
return false
end
true
end
def set_sockopt(soc) # :nodoc:
soc.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
soc.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) if defined? Fcntl::FD_CLOEXEC
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | true |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/drb/invokemethod.rb | tools/jruby-1.5.1/lib/ruby/1.9/drb/invokemethod.rb | # for ruby-1.8.0
module DRb
class DRbServer
module InvokeMethod18Mixin
def block_yield(x)
if x.size == 1 && x[0].class == Array
x[0] = DRbArray.new(x[0])
end
block_value = @block.call(*x)
end
def perform_with_block
@obj.__send__(@msg_id, *@argv) do |*x|
jump_error = nil
begin
block_value = block_yield(x)
rescue LocalJumpError
jump_error = $!
end
if jump_error
case jump_error.reason
when :break
break(jump_error.exit_value)
else
raise jump_error
end
end
block_value
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/drb/unix.rb | tools/jruby-1.5.1/lib/ruby/1.9/drb/unix.rb | require 'socket'
require 'drb/drb'
require 'tmpdir'
raise(LoadError, "UNIXServer is required") unless defined?(UNIXServer)
module DRb
class DRbUNIXSocket < DRbTCPSocket
def self.parse_uri(uri)
if /^drbunix:(.*?)(\?(.*))?$/ =~ uri
filename = $1
option = $3
[filename, option]
else
raise(DRbBadScheme, uri) unless uri =~ /^drbunix:/
raise(DRbBadURI, 'can\'t parse uri:' + uri)
end
end
def self.open(uri, config)
filename, option = parse_uri(uri)
filename.untaint
soc = UNIXSocket.open(filename)
self.new(uri, soc, config)
end
def self.open_server(uri, config)
filename, option = parse_uri(uri)
if filename.size == 0
soc = temp_server
filename = soc.path
uri = 'drbunix:' + soc.path
else
soc = UNIXServer.open(filename)
end
owner = config[:UNIXFileOwner]
group = config[:UNIXFileGroup]
if owner || group
require 'etc'
owner = Etc.getpwnam( owner ).uid if owner
group = Etc.getgrnam( group ).gid if group
File.chown owner, group, filename
end
mode = config[:UNIXFileMode]
File.chmod(mode, filename) if mode
self.new(uri, soc, config, true)
end
def self.uri_option(uri, config)
filename, option = parse_uri(uri)
return "drbunix:#{filename}", option
end
def initialize(uri, soc, config={}, server_mode = false)
super(uri, soc, config)
set_sockopt(@socket)
@server_mode = server_mode
@acl = nil
end
# import from tempfile.rb
Max_try = 10
private
def self.temp_server
tmpdir = Dir::tmpdir
n = 0
while true
begin
tmpname = sprintf('%s/druby%d.%d', tmpdir, $$, n)
lock = tmpname + '.lock'
unless File.exist?(tmpname) or File.exist?(lock)
Dir.mkdir(lock)
break
end
rescue
raise "cannot generate tempfile `%s'" % tmpname if n >= Max_try
#sleep(1)
end
n += 1
end
soc = UNIXServer.new(tmpname)
Dir.rmdir(lock)
soc
end
public
def close
return unless @socket
path = @socket.path if @server_mode
@socket.close
File.unlink(path) if @server_mode
@socket = nil
end
def accept
s = @socket.accept
self.class.new(nil, s, @config)
end
def set_sockopt(soc)
soc.fcntl(Fcntl::F_SETFL, Fcntl::FD_CLOEXEC) if defined? Fcntl::FD_CLOEXEC
end
end
DRbProtocol.add_protocol(DRbUNIXSocket)
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/drb/eq.rb | tools/jruby-1.5.1/lib/ruby/1.9/drb/eq.rb | require 'drb/drb'
module DRb
class DRbObject
def ==(other)
return false unless DRbObject === other
(@ref == other.__drbref) && (@uri == other.__drburi)
end
def hash
[@uri, @ref].hash
end
alias eql? ==
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/drb/gw.rb | tools/jruby-1.5.1/lib/ruby/1.9/drb/gw.rb | require 'drb/drb'
require 'monitor'
module DRb
class GWIdConv < DRbIdConv
def to_obj(ref)
if Array === ref && ref[0] == :DRbObject
return DRbObject.new_with(ref[1], ref[2])
end
super(ref)
end
end
class GW
include MonitorMixin
def initialize
super()
@hash = {}
end
def [](key)
synchronize do
@hash[key]
end
end
def []=(key, v)
synchronize do
@hash[key] = v
end
end
end
class DRbObject
def self._load(s)
uri, ref = Marshal.load(s)
if DRb.uri == uri
return ref ? DRb.to_obj(ref) : DRb.front
end
self.new_with(DRb.uri, [:DRbObject, uri, ref])
end
def _dump(lv)
if DRb.uri == @uri
if Array === @ref && @ref[0] == :DRbObject
Marshal.dump([@ref[1], @ref[2]])
else
Marshal.dump([@uri, @ref]) # ??
end
else
Marshal.dump([DRb.uri, [:DRbObject, @uri, @ref]])
end
end
end
end
=begin
DRb.install_id_conv(DRb::GWIdConv.new)
front = DRb::GW.new
s1 = DRb::DRbServer.new('drbunix:/tmp/gw_b_a', front)
s2 = DRb::DRbServer.new('drbunix:/tmp/gw_b_c', front)
s1.thread.join
s2.thread.join
=end
=begin
# foo.rb
require 'drb/drb'
class Foo
include DRbUndumped
def initialize(name, peer=nil)
@name = name
@peer = peer
end
def ping(obj)
puts "#{@name}: ping: #{obj.inspect}"
@peer.ping(self) if @peer
end
end
=end
=begin
# gw_a.rb
require 'drb/unix'
require 'foo'
obj = Foo.new('a')
DRb.start_service("drbunix:/tmp/gw_a", obj)
robj = DRbObject.new_with_uri('drbunix:/tmp/gw_b_a')
robj[:a] = obj
DRb.thread.join
=end
=begin
# gw_c.rb
require 'drb/unix'
require 'foo'
foo = Foo.new('c', nil)
DRb.start_service("drbunix:/tmp/gw_c", nil)
robj = DRbObject.new_with_uri("drbunix:/tmp/gw_b_c")
puts "c->b"
a = robj[:a]
sleep 2
a.ping(foo)
DRb.thread.join
=end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/gemconfigure.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/gemconfigure.rb | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
module Gem
# Activate the gems specfied by the gem_pairs list.
#
# gem_pairs ::
# List of gem/version pairs.
# Eg. [['rake', '= 0.8.15'], ['RedCloth', '~> 3.0']]
# options ::
# options[:verbose] => print gems as they are required.
#
def self.configure(gem_pairs, options={})
gem_pairs.each do |name, version|
require 'rubygems'
puts "Activating gem #{name} (version #{version})" if options[:verbose]
gem name, version
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems.rb | # -*- ruby -*-
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'rubygems/defaults'
require 'thread'
require 'etc'
##
# RubyGems is the Ruby standard for publishing and managing third party
# libraries.
#
# For user documentation, see:
#
# * <tt>gem help</tt> and <tt>gem help [command]</tt>
# * {RubyGems User Guide}[http://docs.rubygems.org/read/book/1]
# * {Frequently Asked Questions}[http://docs.rubygems.org/read/book/3]
#
# For gem developer documentation see:
#
# * {Creating Gems}[http://docs.rubygems.org/read/chapter/5]
# * Gem::Specification
# * Gem::Version for version dependency notes
#
# Further RubyGems documentation can be found at:
#
# * {RubyGems API}[http://rubygems.rubyforge.org/rdoc] (also available from
# <tt>gem server</tt>)
# * {RubyGems Bookshelf}[http://rubygem.org]
#
# == RubyGems Plugins
#
# As of RubyGems 1.3.2, RubyGems will load plugins installed in gems or
# $LOAD_PATH. Plugins must be named 'rubygems_plugin' (.rb, .so, etc) and
# placed at the root of your gem's #require_path. Plugins are discovered via
# Gem::find_files then loaded. Take care when implementing a plugin as your
# plugin file may be loaded multiple times if multiple versions of your gem
# are installed.
#
# For an example plugin, see the graph gem which adds a `gem graph` command.
#
# == RubyGems Defaults, Packaging
#
# RubyGems defaults are stored in rubygems/defaults.rb. If you're packaging
# RubyGems or implementing Ruby you can change RubyGems' defaults.
#
# For RubyGems packagers, provide lib/rubygems/operating_system.rb and
# override any defaults from lib/rubygems/defaults.rb.
#
# For Ruby implementers, provide lib/rubygems/#{RUBY_ENGINE}.rb and override
# any defaults from lib/rubygems/defaults.rb.
#
# If you need RubyGems to perform extra work on install or uninstall, your
# defaults override file can set pre and post install and uninstall hooks.
# See Gem::pre_install, Gem::pre_uninstall, Gem::post_install,
# Gem::post_uninstall.
#
# == Bugs
#
# You can submit bugs to the
# {RubyGems bug tracker}[http://rubyforge.org/tracker/?atid=575&group_id=126]
# on RubyForge
#
# == Credits
#
# RubyGems is currently maintained by Eric Hodel.
#
# RubyGems was originally developed at RubyConf 2003 by:
#
# * Rich Kilmer -- rich(at)infoether.com
# * Chad Fowler -- chad(at)chadfowler.com
# * David Black -- dblack(at)wobblini.net
# * Paul Brannan -- paul(at)atdesk.com
# * Jim Weirch -- jim(at)weirichhouse.org
#
# Contributors:
#
# * Gavin Sinclair -- gsinclair(at)soyabean.com.au
# * George Marrows -- george.marrows(at)ntlworld.com
# * Dick Davies -- rasputnik(at)hellooperator.net
# * Mauricio Fernandez -- batsman.geo(at)yahoo.com
# * Simon Strandgaard -- neoneye(at)adslhome.dk
# * Dave Glasser -- glasser(at)mit.edu
# * Paul Duncan -- pabs(at)pablotron.org
# * Ville Aine -- vaine(at)cs.helsinki.fi
# * Eric Hodel -- drbrain(at)segment7.net
# * Daniel Berger -- djberg96(at)gmail.com
# * Phil Hagelberg -- technomancy(at)gmail.com
# * Ryan Davis -- ryand-ruby(at)zenspider.com
#
# (If your name is missing, PLEASE let us know!)
#
# Thanks!
#
# -The RubyGems Team
module Gem
RubyGemsVersion = VERSION = '1.3.6'
##
# Raised when RubyGems is unable to load or activate a gem. Contains the
# name and version requirements of the gem that either conflicts with
# already activated gems or that RubyGems is otherwise unable to activate.
class LoadError < ::LoadError
# Name of gem
attr_accessor :name
# Version requirement of gem
attr_accessor :version_requirement
end
##
# Configuration settings from ::RbConfig
ConfigMap = {} unless defined?(ConfigMap)
require 'rbconfig'
ConfigMap.merge!(
:EXEEXT => RbConfig::CONFIG["EXEEXT"],
:RUBY_SO_NAME => RbConfig::CONFIG["RUBY_SO_NAME"],
:arch => RbConfig::CONFIG["arch"],
:bindir => RbConfig::CONFIG["bindir"],
:datadir => RbConfig::CONFIG["datadir"],
:libdir => RbConfig::CONFIG["libdir"],
:ruby_install_name => RbConfig::CONFIG["ruby_install_name"],
:ruby_version => RbConfig::CONFIG["ruby_version"],
:sitedir => RbConfig::CONFIG["sitedir"],
:sitelibdir => RbConfig::CONFIG["sitelibdir"],
:vendordir => RbConfig::CONFIG["vendordir"] ,
:vendorlibdir => RbConfig::CONFIG["vendorlibdir"]
)
##
# Default directories in a gem repository
DIRECTORIES = %w[cache doc gems specifications] unless defined?(DIRECTORIES)
# :stopdoc:
MUTEX = Mutex.new
RubyGemsPackageVersion = RubyGemsVersion
# :startdoc:
##
# An Array of Regexps that match windows ruby platforms.
WIN_PATTERNS = [
/bccwin/i,
/cygwin/i,
/djgpp/i,
/mingw/i,
/mswin/i,
/wince/i,
]
@@source_index = nil
@@win_platform = nil
@configuration = nil
@loaded_specs = {}
@loaded_stacks = {}
@platforms = []
@ruby = nil
@sources = []
@post_install_hooks ||= []
@post_uninstall_hooks ||= []
@pre_uninstall_hooks ||= []
@pre_install_hooks ||= []
##
# Activates an installed gem matching +gem+. The gem must satisfy
# +version_requirements+.
#
# Returns true if the gem is activated, false if it is already
# loaded, or an exception otherwise.
#
# Gem#activate adds the library paths in +gem+ to $LOAD_PATH. Before a Gem
# is activated its required Gems are activated. If the version information
# is omitted, the highest version Gem of the supplied name is loaded. If a
# Gem is not found that meets the version requirements or a required Gem is
# not found, a Gem::LoadError is raised.
#
# More information on version requirements can be found in the
# Gem::Requirement and Gem::Version documentation.
def self.activate(gem, *version_requirements)
if version_requirements.last.is_a?(Hash)
options = version_requirements.pop
else
options = {}
end
sources = options[:sources] || []
if version_requirements.empty? then
version_requirements = Gem::Requirement.default
end
unless gem.respond_to?(:name) and
gem.respond_to?(:requirement) then
gem = Gem::Dependency.new(gem, version_requirements)
end
matches = Gem.source_index.find_name(gem.name, gem.requirement)
report_activate_error(gem) if matches.empty?
if @loaded_specs[gem.name] then
# This gem is already loaded. If the currently loaded gem is not in the
# list of candidate gems, then we have a version conflict.
existing_spec = @loaded_specs[gem.name]
unless matches.any? { |spec| spec.version == existing_spec.version } then
sources_message = sources.map { |spec| spec.full_name }
stack_message = @loaded_stacks[gem.name].map { |spec| spec.full_name }
msg = "can't activate #{gem} for #{sources_message.inspect}, "
msg << "already activated #{existing_spec.full_name} for "
msg << "#{stack_message.inspect}"
e = Gem::LoadError.new msg
e.name = gem.name
e.version_requirement = gem.requirement
raise e
end
return false
end
# new load
spec = matches.last
return false if spec.loaded?
spec.loaded = true
@loaded_specs[spec.name] = spec
@loaded_stacks[spec.name] = sources.dup
# Load dependent gems first
spec.runtime_dependencies.each do |dep_gem|
activate dep_gem, :sources => [spec, *sources]
end
# bin directory must come before library directories
spec.require_paths.unshift spec.bindir if spec.bindir
require_paths = spec.require_paths.map do |path|
File.join spec.full_gem_path, path
end
sitelibdir = ConfigMap[:sitelibdir]
# gem directories must come after -I and ENV['RUBYLIB']
insert_index = load_path_insert_index
if insert_index then
# gem directories must come after -I and ENV['RUBYLIB']
$LOAD_PATH.insert(insert_index, *require_paths)
else
# we are probably testing in core, -I and RUBYLIB don't apply
$LOAD_PATH.unshift(*require_paths)
end
return true
end
##
# An Array of all possible load paths for all versions of all gems in the
# Gem installation.
def self.all_load_paths
result = []
Gem.path.each do |gemdir|
each_load_path all_partials(gemdir) do |load_path|
result << load_path
end
end
result
end
##
# Return all the partial paths in +gemdir+.
def self.all_partials(gemdir)
Dir[File.join(gemdir, 'gems/*')]
end
private_class_method :all_partials
##
# See if a given gem is available.
def self.available?(gem, *requirements)
requirements = Gem::Requirement.default if requirements.empty?
unless gem.respond_to?(:name) and
gem.respond_to?(:requirement) then
gem = Gem::Dependency.new gem, requirements
end
!Gem.source_index.search(gem).empty?
end
##
# Find the full path to the executable for gem +name+. If the +exec_name+
# is not given, the gem's default_executable is chosen, otherwise the
# specifed executable's path is returned. +version_requirements+ allows you
# to specify specific gem versions.
def self.bin_path(name, exec_name = nil, *version_requirements)
version_requirements = Gem::Requirement.default if
version_requirements.empty?
spec = Gem.source_index.find_name(name, version_requirements).last
raise Gem::GemNotFoundException,
"can't find gem #{name} (#{version_requirements})" unless spec
exec_name ||= spec.default_executable
unless exec_name
msg = "no default executable for #{spec.full_name}"
raise Gem::Exception, msg
end
unless spec.executables.include? exec_name
msg = "can't find executable #{exec_name} for #{spec.full_name}"
raise Gem::Exception, msg
end
File.join(spec.full_gem_path, spec.bindir, exec_name)
end
##
# The mode needed to read a file as straight binary.
def self.binary_mode
@binary_mode ||= RUBY_VERSION > '1.9' ? 'rb:ascii-8bit' : 'rb'
end
##
# The path where gem executables are to be installed.
def self.bindir(install_dir=Gem.dir)
return File.join(install_dir, 'bin') unless
install_dir.to_s == Gem.default_dir
Gem.default_bindir
end
##
# Reset the +dir+ and +path+ values. The next time +dir+ or +path+
# is requested, the values will be calculated from scratch. This is
# mainly used by the unit tests to provide test isolation.
def self.clear_paths
@gem_home = nil
@gem_path = nil
@user_home = nil
@@source_index = nil
MUTEX.synchronize do
@searcher = nil
end
end
##
# The path to standard location of the user's .gemrc file.
def self.config_file
File.join Gem.user_home, '.gemrc'
end
##
# The standard configuration object for gems.
def self.configuration
@configuration ||= Gem::ConfigFile.new []
end
##
# Use the given configuration object (which implements the ConfigFile
# protocol) as the standard configuration object.
def self.configuration=(config)
@configuration = config
end
##
# The path the the data directory specified by the gem name. If the
# package is not available as a gem, return nil.
def self.datadir(gem_name)
spec = @loaded_specs[gem_name]
return nil if spec.nil?
File.join(spec.full_gem_path, 'data', gem_name)
end
##
# A Zlib::Deflate.deflate wrapper
def self.deflate(data)
require 'zlib'
Zlib::Deflate.deflate data
end
##
# The path where gems are to be installed.
def self.dir
@gem_home ||= nil
set_home(ENV['GEM_HOME'] || Gem.configuration.home || default_dir) unless @gem_home
@gem_home
end
##
# Expand each partial gem path with each of the required paths specified
# in the Gem spec. Each expanded path is yielded.
def self.each_load_path(partials)
partials.each do |gp|
base = File.basename(gp)
specfn = File.join(dir, "specifications", base + ".gemspec")
if File.exist?(specfn)
spec = eval(File.read(specfn))
spec.require_paths.each do |rp|
yield(File.join(gp, rp))
end
else
filename = File.join(gp, 'lib')
yield(filename) if File.exist?(filename)
end
end
end
private_class_method :each_load_path
##
# Quietly ensure the named Gem directory contains all the proper
# subdirectories. If we can't create a directory due to a permission
# problem, then we will silently continue.
def self.ensure_gem_subdirectories(gemdir)
require 'fileutils'
Gem::DIRECTORIES.each do |filename|
fn = File.join gemdir, filename
FileUtils.mkdir_p fn rescue nil unless File.exist? fn
end
end
##
# Returns a list of paths matching +file+ that can be used by a gem to pick
# up features from other gems. For example:
#
# Gem.find_files('rdoc/discover').each do |path| load path end
#
# find_files search $LOAD_PATH for files as well as gems.
#
# Note that find_files will return all files even if they are from different
# versions of the same gem.
def self.find_files(path)
load_path_files = $LOAD_PATH.map do |load_path|
files = Dir["#{File.expand_path path, load_path}#{Gem.suffix_pattern}"]
files.select do |load_path_file|
File.file? load_path_file.untaint
end
end.flatten
specs = searcher.find_all path
specs_files = specs.map do |spec|
searcher.matching_files spec, path
end.flatten
(load_path_files + specs_files).flatten.uniq
end
##
# Finds the user's home directory.
#--
# Some comments from the ruby-talk list regarding finding the home
# directory:
#
# I have HOME, USERPROFILE and HOMEDRIVE + HOMEPATH. Ruby seems
# to be depending on HOME in those code samples. I propose that
# it should fallback to USERPROFILE and HOMEDRIVE + HOMEPATH (at
# least on Win32).
def self.find_home
unless RUBY_VERSION > '1.9' then
['HOME', 'USERPROFILE'].each do |homekey|
return ENV[homekey] if ENV[homekey]
end
if ENV['HOMEDRIVE'] && ENV['HOMEPATH'] then
return "#{ENV['HOMEDRIVE']}#{ENV['HOMEPATH']}"
end
end
File.expand_path "~"
rescue
if File::ALT_SEPARATOR then
"C:/"
else
"/"
end
end
private_class_method :find_home
##
# Zlib::GzipReader wrapper that unzips +data+.
def self.gunzip(data)
require 'stringio'
require 'zlib'
data = StringIO.new data
Zlib::GzipReader.new(data).read
end
##
# Zlib::GzipWriter wrapper that zips +data+.
def self.gzip(data)
require 'stringio'
require 'zlib'
zipped = StringIO.new
Zlib::GzipWriter.wrap zipped do |io| io.write data end
zipped.string
end
##
# A Zlib::Inflate#inflate wrapper
def self.inflate(data)
require 'zlib'
Zlib::Inflate.inflate data
end
##
# Return a list of all possible load paths for the latest version for all
# gems in the Gem installation.
def self.latest_load_paths
result = []
Gem.path.each do |gemdir|
each_load_path(latest_partials(gemdir)) do |load_path|
result << load_path
end
end
result
end
##
# Return only the latest partial paths in the given +gemdir+.
def self.latest_partials(gemdir)
latest = {}
all_partials(gemdir).each do |gp|
base = File.basename(gp)
if base =~ /(.*)-((\d+\.)*\d+)/ then
name, version = $1, $2
ver = Gem::Version.new(version)
if latest[name].nil? || ver > latest[name][0]
latest[name] = [ver, gp]
end
end
end
latest.collect { |k,v| v[1] }
end
private_class_method :latest_partials
##
# The index to insert activated gem paths into the $LOAD_PATH.
#
# Defaults to the site lib directory unless gem_prelude.rb has loaded paths,
# then it inserts the activated gem's paths before the gem_prelude.rb paths
# so you can override the gem_prelude.rb default $LOAD_PATH paths.
def self.load_path_insert_index
index = $LOAD_PATH.index ConfigMap[:sitelibdir]
$LOAD_PATH.each_with_index do |path, i|
if path.instance_variables.include?(:@gem_prelude_index) or
path.instance_variables.include?('@gem_prelude_index') then
index = i
break
end
end
index
end
##
# The file name and line number of the caller of the caller of this method.
def self.location_of_caller
caller[1] =~ /(.*?):(\d+).*?$/i
file = $1
lineno = $2.to_i
[file, lineno]
end
##
# The version of the Marshal format for your Ruby.
def self.marshal_version
"#{Marshal::MAJOR_VERSION}.#{Marshal::MINOR_VERSION}"
end
##
# Array of paths to search for Gems.
def self.path
@gem_path ||= nil
unless @gem_path then
paths = [ENV['GEM_PATH'] || Gem.configuration.path || default_path]
if defined?(APPLE_GEM_HOME) and not ENV['GEM_PATH'] then
paths << APPLE_GEM_HOME
end
set_paths paths.compact.join(File::PATH_SEPARATOR)
end
@gem_path
end
##
# Set array of platforms this RubyGems supports (primarily for testing).
def self.platforms=(platforms)
@platforms = platforms
end
##
# Array of platforms this RubyGems supports.
def self.platforms
@platforms ||= []
if @platforms.empty?
@platforms = [Gem::Platform::RUBY, Gem::Platform.local]
end
@platforms
end
##
# Adds a post-install hook that will be passed an Gem::Installer instance
# when Gem::Installer#install is called
def self.post_install(&hook)
@post_install_hooks << hook
end
##
# Adds a post-uninstall hook that will be passed a Gem::Uninstaller instance
# and the spec that was uninstalled when Gem::Uninstaller#uninstall is
# called
def self.post_uninstall(&hook)
@post_uninstall_hooks << hook
end
##
# Adds a pre-install hook that will be passed an Gem::Installer instance
# when Gem::Installer#install is called
def self.pre_install(&hook)
@pre_install_hooks << hook
end
##
# Adds a pre-uninstall hook that will be passed an Gem::Uninstaller instance
# and the spec that will be uninstalled when Gem::Uninstaller#uninstall is
# called
def self.pre_uninstall(&hook)
@pre_uninstall_hooks << hook
end
##
# The directory prefix this RubyGems was installed at.
def self.prefix
prefix = File.dirname File.expand_path(__FILE__)
if File.dirname(prefix) == File.expand_path(ConfigMap[:sitelibdir]) or
File.dirname(prefix) == File.expand_path(ConfigMap[:libdir]) or
'lib' != File.basename(prefix) then
nil
else
File.dirname prefix
end
end
##
# Promotes the load paths of the +gem_name+ over the load paths of
# +over_name+. Useful for allowing one gem to override features in another
# using #find_files.
def self.promote_load_path(gem_name, over_name)
gem = Gem.loaded_specs[gem_name]
over = Gem.loaded_specs[over_name]
raise ArgumentError, "gem #{gem_name} is not activated" if gem.nil?
raise ArgumentError, "gem #{over_name} is not activated" if over.nil?
last_gem_path = File.join gem.full_gem_path, gem.require_paths.last
over_paths = over.require_paths.map do |path|
File.join over.full_gem_path, path
end
over_paths.each do |path|
$LOAD_PATH.delete path
end
gem = $LOAD_PATH.index(last_gem_path) + 1
$LOAD_PATH.insert(gem, *over_paths)
end
##
# Refresh source_index from disk and clear searcher.
def self.refresh
source_index.refresh!
MUTEX.synchronize do
@searcher = nil
end
end
##
# Safely read a file in binary mode on all platforms.
def self.read_binary(path)
File.open path, binary_mode do |f| f.read end
end
##
# Report a load error during activation. The message of load error
# depends on whether it was a version mismatch or if there are not gems of
# any version by the requested name.
def self.report_activate_error(gem)
matches = Gem.source_index.find_name(gem.name)
if matches.empty? then
error = Gem::LoadError.new(
"Could not find RubyGem #{gem.name} (#{gem.requirement})\n")
else
error = Gem::LoadError.new(
"RubyGem version error: " +
"#{gem.name}(#{matches.first.version} not #{gem.requirement})\n")
end
error.name = gem.name
error.version_requirement = gem.requirement
raise error
end
private_class_method :report_activate_error
##
# Full path to +libfile+ in +gemname+. Searches for the latest gem unless
# +requirements+ is given.
def self.required_location(gemname, libfile, *requirements)
requirements = Gem::Requirement.default if requirements.empty?
matches = Gem.source_index.find_name gemname, requirements
return nil if matches.empty?
spec = matches.last
spec.require_paths.each do |path|
result = File.join spec.full_gem_path, path, libfile
return result if File.exist? result
end
nil
end
##
# The path to the running Ruby interpreter.
def self.ruby
if @ruby.nil? then
@ruby = File.join(ConfigMap[:bindir],
ConfigMap[:ruby_install_name])
@ruby << ConfigMap[:EXEEXT]
# escape string in case path to ruby executable contain spaces.
@ruby.sub!(/.*\s.*/m, '"\&"')
end
@ruby
end
##
# A Gem::Version for the currently running ruby.
def self.ruby_version
return @ruby_version if defined? @ruby_version
version = RUBY_VERSION.dup
if defined?(RUBY_PATCHLEVEL) && RUBY_PATCHLEVEL != -1 then
version << ".#{RUBY_PATCHLEVEL}"
elsif defined?(RUBY_REVISION) then
version << ".dev.#{RUBY_REVISION}"
end
@ruby_version = Gem::Version.new version
end
##
# The GemPathSearcher object used to search for matching installed gems.
def self.searcher
MUTEX.synchronize do
@searcher ||= Gem::GemPathSearcher.new
end
end
##
# Set the Gem home directory (as reported by Gem.dir).
def self.set_home(home)
home = home.gsub File::ALT_SEPARATOR, File::SEPARATOR if File::ALT_SEPARATOR
@gem_home = home
end
private_class_method :set_home
##
# Set the Gem search path (as reported by Gem.path).
def self.set_paths(gpaths)
if gpaths
@gem_path = gpaths.split(File::PATH_SEPARATOR)
if File::ALT_SEPARATOR then
@gem_path.map! do |path|
path.gsub File::ALT_SEPARATOR, File::SEPARATOR
end
end
@gem_path << Gem.dir
else
# TODO: should this be Gem.default_path instead?
@gem_path = [Gem.dir]
end
@gem_path.uniq!
end
private_class_method :set_paths
##
# Returns the Gem::SourceIndex of specifications that are in the Gem.path
def self.source_index
@@source_index ||= SourceIndex.from_installed_gems
end
##
# Returns an Array of sources to fetch remote gems from. If the sources
# list is empty, attempts to load the "sources" gem, then uses
# default_sources if it is not installed.
def self.sources
if @sources.empty? then
begin
gem 'sources', '> 0.0.1'
require 'sources'
rescue LoadError
@sources = default_sources
end
end
@sources
end
##
# Need to be able to set the sources without calling
# Gem.sources.replace since that would cause an infinite loop.
def self.sources=(new_sources)
@sources = new_sources
end
##
# Glob pattern for require-able path suffixes.
def self.suffix_pattern
@suffix_pattern ||= "{#{suffixes.join(',')}}"
end
##
# Suffixes for require-able paths.
def self.suffixes
['', '.rb', '.rbw', '.so', '.bundle', '.dll', '.sl', '.jar']
end
##
# Prints the amount of time the supplied block takes to run using the debug
# UI output.
def self.time(msg, width = 0, display = Gem.configuration.verbose)
now = Time.now
value = yield
elapsed = Time.now - now
ui.say "%2$*1$s: %3$3.3fs" % [-width, msg, elapsed] if display
value
end
##
# Lazily loads DefaultUserInteraction and returns the default UI.
def self.ui
require 'rubygems/user_interaction'
Gem::DefaultUserInteraction.ui
end
##
# Use the +home+ and +paths+ values for Gem.dir and Gem.path. Used mainly
# by the unit tests to provide environment isolation.
def self.use_paths(home, paths=[])
clear_paths
set_home(home) if home
set_paths(paths.join(File::PATH_SEPARATOR)) if paths
end
##
# The home directory for the user.
def self.user_home
@user_home ||= find_home
end
##
# Is this a windows platform?
def self.win_platform?
if @@win_platform.nil? then
@@win_platform = !!WIN_PATTERNS.find { |r| RUBY_PLATFORM =~ r }
end
@@win_platform
end
class << self
##
# Hash of loaded Gem::Specification keyed by name
attr_reader :loaded_specs
##
# The list of hooks to be run before Gem::Install#install does any work
attr_reader :post_install_hooks
##
# The list of hooks to be run before Gem::Uninstall#uninstall does any
# work
attr_reader :post_uninstall_hooks
##
# The list of hooks to be run after Gem::Install#install is finished
attr_reader :pre_install_hooks
##
# The list of hooks to be run after Gem::Uninstall#uninstall is finished
attr_reader :pre_uninstall_hooks
# :stopdoc:
alias cache source_index # an alias for the old name
# :startdoc:
end
##
# Location of Marshal quick gemspecs on remote repositories
MARSHAL_SPEC_DIR = "quick/Marshal.#{Gem.marshal_version}/"
##
# Location of legacy YAML quick gemspecs on remote repositories
YAML_SPEC_DIR = 'quick/'
end
module Kernel
##
# Use Kernel#gem to activate a specific version of +gem_name+.
#
# +version_requirements+ is a list of version requirements that the
# specified gem must match, most commonly "= example.version.number". See
# Gem::Requirement for how to specify a version requirement.
#
# If you will be activating the latest version of a gem, there is no need to
# call Kernel#gem, Kernel#require will do the right thing for you.
#
# Kernel#gem returns true if the gem was activated, otherwise false. If the
# gem could not be found, didn't match the version requirements, or a
# different version was already activated, an exception will be raised.
#
# Kernel#gem should be called *before* any require statements (otherwise
# RubyGems may load a conflicting library version).
#
# In older RubyGems versions, the environment variable GEM_SKIP could be
# used to skip activation of specified gems, for example to test out changes
# that haven't been installed yet. Now RubyGems defers to -I and the
# RUBYLIB environment variable to skip activation of a gem.
#
# Example:
#
# GEM_SKIP=libA:libB ruby -I../libA -I../libB ./mycode.rb
def gem(gem_name, *version_requirements) # :doc:
skip_list = (ENV['GEM_SKIP'] || "").split(/:/)
raise Gem::LoadError, "skipping #{gem_name}" if skip_list.include? gem_name
Gem.activate(gem_name, *version_requirements)
end
private :gem
end
##
# Return the path to the data directory associated with the named package. If
# the package is loaded as a gem, return the gem specific data directory.
# Otherwise return a path to the share area as define by
# "#{ConfigMap[:datadir]}/#{package_name}".
def RbConfig.datadir(package_name)
Gem.datadir(package_name) ||
File.join(Gem::ConfigMap[:datadir], package_name)
end
require 'rubygems/exceptions'
require 'rubygems/version'
require 'rubygems/requirement'
require 'rubygems/dependency'
require 'rubygems/gem_path_searcher' # Needed for Kernel#gem
require 'rubygems/source_index' # Needed for Kernel#gem
require 'rubygems/platform'
require 'rubygems/builder' # HACK: Needed for rake's package task.
begin
require 'rubygems/defaults/operating_system'
rescue LoadError
end
if defined?(RUBY_ENGINE) then
begin
require "rubygems/defaults/#{RUBY_ENGINE}"
rescue LoadError
end
end
require 'rubygems/config_file'
if RUBY_VERSION < '1.9' then
require 'rubygems/custom_require'
end
Gem.clear_paths
plugins = Gem.find_files 'rubygems_plugin'
plugins.each do |plugin|
# Skip older versions of the GemCutter plugin: Its commands are in
# RubyGems proper now.
next if plugin =~ /gemcutter-0\.[0-3]/
begin
load plugin
rescue => e
warn "error loading #{plugin.inspect}: #{e.message} (#{e.class})"
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/ubygems.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/ubygems.rb | # This file allows for the running of rubygems with a nice
# command line look-and-feel: ruby -rubygems foo.rb
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'rubygems'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/gauntlet_rubygems.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/gauntlet_rubygems.rb | require 'rubygems'
require 'gauntlet'
##
# GemGauntlet validates all current gems. Currently these packages are
# borked:
#
# Asami-0.04 : No such file or directory - bin/Asami.rb
# ObjectGraph-1.0.1 : No such file or directory - bin/objectgraph
# evil-ruby-0.1.0 : authors must be Array of Strings
# fresh_cookies-1.0.0 : authors must be Array of Strings
# plugems_deploy-0.2.0 : authors must be Array of Strings
# pmsrb-0.2.0 : authors must be Array of Strings
# pqa-1.6 : authors must be Array of Strings
# rant-0.5.7 : authors must be Array of Strings
# rvsh-0.4.5 : No such file or directory - bin/rvsh
# xen-0.1.2.1 : authors must be Array of Strings
class GemGauntlet < Gauntlet
def run(name)
warn name
spec = begin
Gem::Specification.load 'gemspec'
rescue SyntaxError
Gem::Specification.from_yaml File.read('gemspec')
end
spec.validate
self.data[name] = false
self.dirty = true
rescue SystemCallError, Gem::InvalidSpecificationException => e
self.data[name] = e.message
self.dirty = true
end
def should_skip?(name)
self.data[name] == false
end
def report
self.data.sort.reject { |k,v| !v }.each do |k,v|
puts "%-21s: %s" % [k, v]
end
end
end
gauntlet = GemGauntlet.new
gauntlet.run_the_gauntlet ARGV.shift
gauntlet.report
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rbconfig/datadir.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rbconfig/datadir.rb | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
module RbConfig
##
# Return the path to the data directory associated with the given package
# name. Normally this is just
# "#{RbConfig::CONFIG['datadir']}/#{package_name}", but may be modified by
# packages like RubyGems to handle versioned data directories.
def self.datadir(package_name)
File.join(CONFIG['datadir'], package_name)
end unless RbConfig.respond_to?(:datadir)
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/command.rb | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'optparse'
require 'rubygems/user_interaction'
##
# Base class for all Gem commands. When creating a new gem command, define
# #new, #execute, #arguments, #defaults_str, #description and #usage
# (as appropriate). See the above mentioned methods for details.
#
# A very good example to look at is Gem::Commands::ContentsCommand
class Gem::Command
include Gem::UserInteraction
##
# The name of the command.
attr_reader :command
##
# The options for the command.
attr_reader :options
##
# The default options for the command.
attr_accessor :defaults
##
# The name of the command for command-line invocation.
attr_accessor :program_name
##
# A short description of the command.
attr_accessor :summary
##
# Arguments used when building gems
def self.build_args
@build_args ||= []
end
def self.build_args=(value)
@build_args = value
end
def self.common_options
@common_options ||= []
end
def self.add_common_option(*args, &handler)
Gem::Command.common_options << [args, handler]
end
def self.extra_args
@extra_args ||= []
end
def self.extra_args=(value)
case value
when Array
@extra_args = value
when String
@extra_args = value.split
end
end
##
# Return an array of extra arguments for the command. The extra arguments
# come from the gem configuration file read at program startup.
def self.specific_extra_args(cmd)
specific_extra_args_hash[cmd]
end
##
# Add a list of extra arguments for the given command. +args+ may be an
# array or a string to be split on white space.
def self.add_specific_extra_args(cmd,args)
args = args.split(/\s+/) if args.kind_of? String
specific_extra_args_hash[cmd] = args
end
##
# Accessor for the specific extra args hash (self initializing).
def self.specific_extra_args_hash
@specific_extra_args_hash ||= Hash.new do |h,k|
h[k] = Array.new
end
end
##
# Initializes a generic gem command named +command+. +summary+ is a short
# description displayed in `gem help commands`. +defaults+ are the default
# options. Defaults should be mirrored in #defaults_str, unless there are
# none.
#
# When defining a new command subclass, use add_option to add command-line
# switches.
#
# Unhandled arguments (gem names, files, etc.) are left in
# <tt>options[:args]</tt>.
def initialize(command, summary=nil, defaults={})
@command = command
@summary = summary
@program_name = "gem #{command}"
@defaults = defaults
@options = defaults.dup
@option_groups = Hash.new { |h,k| h[k] = [] }
@parser = nil
@when_invoked = nil
end
##
# True if +long+ begins with the characters from +short+.
def begins?(long, short)
return false if short.nil?
long[0, short.length] == short
end
##
# Override to provide command handling.
#
# #options will be filled in with your parsed options, unparsed options will
# be left in <tt>options[:args]</tt>.
#
# See also: #get_all_gem_names, #get_one_gem_name,
# #get_one_optional_argument
def execute
raise Gem::Exception, "generic command has no actions"
end
##
# Get all gem names from the command line.
def get_all_gem_names
args = options[:args]
if args.nil? or args.empty? then
raise Gem::CommandLineError,
"Please specify at least one gem name (e.g. gem build GEMNAME)"
end
gem_names = args.select { |arg| arg !~ /^-/ }
end
##
# Get a single gem name from the command line. Fail if there is no gem name
# or if there is more than one gem name given.
def get_one_gem_name
args = options[:args]
if args.nil? or args.empty? then
raise Gem::CommandLineError,
"Please specify a gem name on the command line (e.g. gem build GEMNAME)"
end
if args.size > 1 then
raise Gem::CommandLineError,
"Too many gem names (#{args.join(', ')}); please specify only one"
end
args.first
end
##
# Get a single optional argument from the command line. If more than one
# argument is given, return only the first. Return nil if none are given.
def get_one_optional_argument
args = options[:args] || []
args.first
end
##
# Override to provide details of the arguments a command takes. It should
# return a left-justified string, one argument per line.
#
# For example:
#
# def usage
# "#{program_name} FILE [FILE ...]"
# end
#
# def arguments
# "FILE name of file to find"
# end
def arguments
""
end
##
# Override to display the default values of the command options. (similar to
# +arguments+, but displays the default values).
#
# For example:
#
# def defaults_str
# --no-gems-first --no-all
# end
def defaults_str
""
end
##
# Override to display a longer description of what this command does.
def description
nil
end
##
# Override to display the usage for an individual gem command.
#
# The text "[options]" is automatically appended to the usage text.
def usage
program_name
end
##
# Display the help message for the command.
def show_help
parser.program_name = usage
say parser
end
##
# Invoke the command with the given list of arguments.
def invoke(*args)
handle_options args
if options[:help] then
show_help
elsif @when_invoked then
@when_invoked.call options
else
execute
end
end
##
# Call the given block when invoked.
#
# Normal command invocations just executes the +execute+ method of the
# command. Specifying an invocation block allows the test methods to
# override the normal action of a command to determine that it has been
# invoked correctly.
def when_invoked(&block)
@when_invoked = block
end
##
# Add a command-line option and handler to the command.
#
# See OptionParser#make_switch for an explanation of +opts+.
#
# +handler+ will be called with two values, the value of the argument and
# the options hash.
#
# If the first argument of add_option is a Symbol, it's used to group
# options in output. See `gem help list` for an example.
def add_option(*opts, &handler) # :yields: value, options
group_name = Symbol === opts.first ? opts.shift : :options
@option_groups[group_name] << [opts, handler]
end
##
# Remove previously defined command-line argument +name+.
def remove_option(name)
@option_groups.each do |_, option_list|
option_list.reject! { |args, _| args.any? { |x| x =~ /^#{name}/ } }
end
end
##
# Merge a set of command options with the set of default options (without
# modifying the default option hash).
def merge_options(new_options)
@options = @defaults.clone
new_options.each do |k,v| @options[k] = v end
end
##
# True if the command handles the given argument list.
def handles?(args)
begin
parser.parse!(args.dup)
return true
rescue
return false
end
end
##
# Handle the given list of arguments by parsing them and recording the
# results.
def handle_options(args)
args = add_extra_args(args)
@options = @defaults.clone
parser.parse!(args)
@options[:args] = args
end
##
# Adds extra args from ~/.gemrc
def add_extra_args(args)
result = []
s_extra = Gem::Command.specific_extra_args(@command)
extra = Gem::Command.extra_args + s_extra
until extra.empty? do
ex = []
ex << extra.shift
ex << extra.shift if extra.first.to_s =~ /^[^-]/
result << ex if handles?(ex)
end
result.flatten!
result.concat(args)
result
end
private
##
# Create on demand parser.
def parser
create_option_parser if @parser.nil?
@parser
end
def create_option_parser
@parser = OptionParser.new
@parser.separator nil
regular_options = @option_groups.delete :options
configure_options "", regular_options
@option_groups.sort_by { |n,_| n.to_s }.each do |group_name, option_list|
@parser.separator nil
configure_options group_name, option_list
end
@parser.separator nil
configure_options "Common", Gem::Command.common_options
unless arguments.empty?
@parser.separator nil
@parser.separator " Arguments:"
arguments.split(/\n/).each do |arg_desc|
@parser.separator " #{arg_desc}"
end
end
@parser.separator nil
@parser.separator " Summary:"
wrap(@summary, 80 - 4).split("\n").each do |line|
@parser.separator " #{line.strip}"
end
if description then
formatted = description.split("\n\n").map do |chunk|
wrap chunk, 80 - 4
end.join "\n"
@parser.separator nil
@parser.separator " Description:"
formatted.split("\n").each do |line|
@parser.separator " #{line.rstrip}"
end
end
unless defaults_str.empty?
@parser.separator nil
@parser.separator " Defaults:"
defaults_str.split(/\n/).each do |line|
@parser.separator " #{line}"
end
end
end
def configure_options(header, option_list)
return if option_list.nil? or option_list.empty?
header = header.to_s.empty? ? '' : "#{header} "
@parser.separator " #{header}Options:"
option_list.each do |args, handler|
dashes = args.select { |arg| arg =~ /^-/ }
@parser.on(*args) do |value|
handler.call(value, @options)
end
end
@parser.separator ''
end
##
# Wraps +text+ to +width+
def wrap(text, width) # :doc:
text.gsub(/(.{1,#{width}})( +|$\n?)|(.{1,#{width}})/, "\\1\\3\n")
end
# ----------------------------------------------------------------
# Add the options common to all commands.
add_common_option('-h', '--help',
'Get help on this command') do |value, options|
options[:help] = true
end
add_common_option('-V', '--[no-]verbose',
'Set the verbose level of output') do |value, options|
# Set us to "really verbose" so the progress meter works
if Gem.configuration.verbose and value then
Gem.configuration.verbose = 1
else
Gem.configuration.verbose = value
end
end
add_common_option('-q', '--quiet', 'Silence commands') do |value, options|
Gem.configuration.verbose = false
end
# Backtrace and config-file are added so they show up in the help
# commands. Both options are actually handled before the other
# options get parsed.
add_common_option('--config-file FILE',
'Use this config file instead of default') do
end
add_common_option('--backtrace',
'Show stack backtrace on errors') do
end
add_common_option('--debug',
'Turn on Ruby debugging') do
end
# :stopdoc:
HELP = <<-HELP
RubyGems is a sophisticated package manager for Ruby. This is a
basic help message containing pointers to more information.
Usage:
gem -h/--help
gem -v/--version
gem command [arguments...] [options...]
Examples:
gem install rake
gem list --local
gem build package.gemspec
gem help install
Further help:
gem help commands list all 'gem' commands
gem help examples show some examples of usage
gem help platforms show information about platforms
gem help <COMMAND> show help on COMMAND
(e.g. 'gem help install')
gem server present a web page at
http://localhost:8808/
with info about installed gems
Further information:
http://rubygems.rubyforge.org
HELP
# :startdoc:
end
##
# This is where Commands will be placed in the namespace
module Gem::Commands
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/security.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/security.rb | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'rubygems'
require 'rubygems/gem_openssl'
# = Signed Gems README
#
# == Table of Contents
# * Overview
# * Walkthrough
# * Command-Line Options
# * OpenSSL Reference
# * Bugs/TODO
# * About the Author
#
# == Overview
#
# Gem::Security implements cryptographic signatures in RubyGems. The section
# below is a step-by-step guide to using signed gems and generating your own.
#
# == Walkthrough
#
# In order to start signing your gems, you'll need to build a private key and
# a self-signed certificate. Here's how:
#
# # build a private key and certificate for gemmaster@example.com
# $ gem cert --build gemmaster@example.com
#
# This could take anywhere from 5 seconds to 10 minutes, depending on the
# speed of your computer (public key algorithms aren't exactly the speediest
# crypto algorithms in the world). When it's finished, you'll see the files
# "gem-private_key.pem" and "gem-public_cert.pem" in the current directory.
#
# First things first: take the "gem-private_key.pem" file and move it
# somewhere private, preferably a directory only you have access to, a floppy
# (yuck!), a CD-ROM, or something comparably secure. Keep your private key
# hidden; if it's compromised, someone can sign packages as you (note: PKI has
# ways of mitigating the risk of stolen keys; more on that later).
#
# Now, let's sign an existing gem. I'll be using my Imlib2-Ruby bindings, but
# you can use whatever gem you'd like. Open up your existing gemspec file and
# add the following lines:
#
# # signing key and certificate chain
# s.signing_key = '/mnt/floppy/gem-private_key.pem'
# s.cert_chain = ['gem-public_cert.pem']
#
# (Be sure to replace "/mnt/floppy" with the ultra-secret path to your private
# key).
#
# After that, go ahead and build your gem as usual. Congratulations, you've
# just built your first signed gem! If you peek inside your gem file, you'll
# see a couple of new files have been added:
#
# $ tar tf tar tf Imlib2-Ruby-0.5.0.gem
# data.tar.gz
# data.tar.gz.sig
# metadata.gz
# metadata.gz.sig
#
# Now let's verify the signature. Go ahead and install the gem, but add the
# following options: "-P HighSecurity", like this:
#
# # install the gem with using the security policy "HighSecurity"
# $ sudo gem install Imlib2-Ruby-0.5.0.gem -P HighSecurity
#
# The -P option sets your security policy -- we'll talk about that in just a
# minute. Eh, what's this?
#
# Attempting local installation of 'Imlib2-Ruby-0.5.0.gem'
# ERROR: Error installing gem Imlib2-Ruby-0.5.0.gem[.gem]: Couldn't
# verify data signature: Untrusted Signing Chain Root: cert =
# '/CN=gemmaster/DC=example/DC=com', error = 'path
# "/root/.rubygems/trust/cert-15dbb43a6edf6a70a85d4e784e2e45312cff7030.pem"
# does not exist'
#
# The culprit here is the security policy. RubyGems has several different
# security policies. Let's take a short break and go over the security
# policies. Here's a list of the available security policies, and a brief
# description of each one:
#
# * NoSecurity - Well, no security at all. Signed packages are treated like
# unsigned packages.
# * LowSecurity - Pretty much no security. If a package is signed then
# RubyGems will make sure the signature matches the signing
# certificate, and that the signing certificate hasn't expired, but
# that's it. A malicious user could easily circumvent this kind of
# security.
# * MediumSecurity - Better than LowSecurity and NoSecurity, but still
# fallible. Package contents are verified against the signing
# certificate, and the signing certificate is checked for validity,
# and checked against the rest of the certificate chain (if you don't
# know what a certificate chain is, stay tuned, we'll get to that).
# The biggest improvement over LowSecurity is that MediumSecurity
# won't install packages that are signed by untrusted sources.
# Unfortunately, MediumSecurity still isn't totally secure -- a
# malicious user can still unpack the gem, strip the signatures, and
# distribute the gem unsigned.
# * HighSecurity - Here's the bugger that got us into this mess.
# The HighSecurity policy is identical to the MediumSecurity policy,
# except that it does not allow unsigned gems. A malicious user
# doesn't have a whole lot of options here; he can't modify the
# package contents without invalidating the signature, and he can't
# modify or remove signature or the signing certificate chain, or
# RubyGems will simply refuse to install the package. Oh well, maybe
# he'll have better luck causing problems for CPAN users instead :).
#
# So, the reason RubyGems refused to install our shiny new signed gem was
# because it was from an untrusted source. Well, my code is infallible
# (hah!), so I'm going to add myself as a trusted source.
#
# Here's how:
#
# # add trusted certificate
# gem cert --add gem-public_cert.pem
#
# I've added my public certificate as a trusted source. Now I can install
# packages signed my private key without any hassle. Let's try the install
# command above again:
#
# # install the gem with using the HighSecurity policy (and this time
# # without any shenanigans)
# $ sudo gem install Imlib2-Ruby-0.5.0.gem -P HighSecurity
#
# This time RubyGems should accept your signed package and begin installing.
# While you're waiting for RubyGems to work it's magic, have a look at some of
# the other security commands:
#
# Usage: gem cert [options]
#
# Options:
# -a, --add CERT Add a trusted certificate.
# -l, --list List trusted certificates.
# -r, --remove STRING Remove trusted certificates containing STRING.
# -b, --build EMAIL_ADDR Build private key and self-signed certificate
# for EMAIL_ADDR.
# -C, --certificate CERT Certificate for --sign command.
# -K, --private-key KEY Private key for --sign command.
# -s, --sign NEWCERT Sign a certificate with my key and certificate.
#
# (By the way, you can pull up this list any time you'd like by typing "gem
# cert --help")
#
# Hmm. We've already covered the "--build" option, and the "--add", "--list",
# and "--remove" commands seem fairly straightforward; they allow you to add,
# list, and remove the certificates in your trusted certificate list. But
# what's with this "--sign" option?
#
# To answer that question, let's take a look at "certificate chains", a
# concept I mentioned earlier. There are a couple of problems with
# self-signed certificates: first of all, self-signed certificates don't offer
# a whole lot of security. Sure, the certificate says Yukihiro Matsumoto, but
# how do I know it was actually generated and signed by matz himself unless he
# gave me the certificate in person?
#
# The second problem is scalability. Sure, if there are 50 gem authors, then
# I have 50 trusted certificates, no problem. What if there are 500 gem
# authors? 1000? Having to constantly add new trusted certificates is a
# pain, and it actually makes the trust system less secure by encouraging
# RubyGems users to blindly trust new certificates.
#
# Here's where certificate chains come in. A certificate chain establishes an
# arbitrarily long chain of trust between an issuing certificate and a child
# certificate. So instead of trusting certificates on a per-developer basis,
# we use the PKI concept of certificate chains to build a logical hierarchy of
# trust. Here's a hypothetical example of a trust hierarchy based (roughly)
# on geography:
#
#
# --------------------------
# | rubygems@rubyforge.org |
# --------------------------
# |
# -----------------------------------
# | |
# ---------------------------- -----------------------------
# | seattle.rb@zenspider.com | | dcrubyists@richkilmer.com |
# ---------------------------- -----------------------------
# | | | |
# --------------- ---------------- ----------- --------------
# | alf@seattle | | bob@portland | | pabs@dc | | tomcope@dc |
# --------------- ---------------- ----------- --------------
#
#
# Now, rather than having 4 trusted certificates (one for alf@seattle,
# bob@portland, pabs@dc, and tomecope@dc), a user could actually get by with 1
# certificate: the "rubygems@rubyforge.org" certificate. Here's how it works:
#
# I install "Alf2000-Ruby-0.1.0.gem", a package signed by "alf@seattle". I've
# never heard of "alf@seattle", but his certificate has a valid signature from
# the "seattle.rb@zenspider.com" certificate, which in turn has a valid
# signature from the "rubygems@rubyforge.org" certificate. Voila! At this
# point, it's much more reasonable for me to trust a package signed by
# "alf@seattle", because I can establish a chain to "rubygems@rubyforge.org",
# which I do trust.
#
# And the "--sign" option allows all this to happen. A developer creates
# their build certificate with the "--build" option, then has their
# certificate signed by taking it with them to their next regional Ruby meetup
# (in our hypothetical example), and it's signed there by the person holding
# the regional RubyGems signing certificate, which is signed at the next
# RubyConf by the holder of the top-level RubyGems certificate. At each point
# the issuer runs the same command:
#
# # sign a certificate with the specified key and certificate
# # (note that this modifies client_cert.pem!)
# $ gem cert -K /mnt/floppy/issuer-priv_key.pem -C issuer-pub_cert.pem
# --sign client_cert.pem
#
# Then the holder of issued certificate (in this case, our buddy
# "alf@seattle"), can start using this signed certificate to sign RubyGems.
# By the way, in order to let everyone else know about his new fancy signed
# certificate, "alf@seattle" would change his gemspec file to look like this:
#
# # signing key (still kept in an undisclosed location!)
# s.signing_key = '/mnt/floppy/alf-private_key.pem'
#
# # certificate chain (includes the issuer certificate now too)
# s.cert_chain = ['/home/alf/doc/seattlerb-public_cert.pem',
# '/home/alf/doc/alf_at_seattle-public_cert.pem']
#
# Obviously, this RubyGems trust infrastructure doesn't exist yet. Also, in
# the "real world" issuers actually generate the child certificate from a
# certificate request, rather than sign an existing certificate. And our
# hypothetical infrastructure is missing a certificate revocation system.
# These are that can be fixed in the future...
#
# I'm sure your new signed gem has finished installing by now (unless you're
# installing rails and all it's dependencies, that is ;D). At this point you
# should know how to do all of these new and interesting things:
#
# * build a gem signing key and certificate
# * modify your existing gems to support signing
# * adjust your security policy
# * modify your trusted certificate list
# * sign a certificate
#
# If you've got any questions, feel free to contact me at the email address
# below. The next couple of sections
#
#
# == Command-Line Options
#
# Here's a brief summary of the certificate-related command line options:
#
# gem install
# -P, --trust-policy POLICY Specify gem trust policy.
#
# gem cert
# -a, --add CERT Add a trusted certificate.
# -l, --list List trusted certificates.
# -r, --remove STRING Remove trusted certificates containing
# STRING.
# -b, --build EMAIL_ADDR Build private key and self-signed
# certificate for EMAIL_ADDR.
# -C, --certificate CERT Certificate for --sign command.
# -K, --private-key KEY Private key for --sign command.
# -s, --sign NEWCERT Sign a certificate with my key and
# certificate.
#
# A more detailed description of each options is available in the walkthrough
# above.
#
#
# == OpenSSL Reference
#
# The .pem files generated by --build and --sign are just basic OpenSSL PEM
# files. Here's a couple of useful commands for manipulating them:
#
# # convert a PEM format X509 certificate into DER format:
# # (note: Windows .cer files are X509 certificates in DER format)
# $ openssl x509 -in input.pem -outform der -out output.der
#
# # print out the certificate in a human-readable format:
# $ openssl x509 -in input.pem -noout -text
#
# And you can do the same thing with the private key file as well:
#
# # convert a PEM format RSA key into DER format:
# $ openssl rsa -in input_key.pem -outform der -out output_key.der
#
# # print out the key in a human readable format:
# $ openssl rsa -in input_key.pem -noout -text
#
# == Bugs/TODO
#
# * There's no way to define a system-wide trust list.
# * custom security policies (from a YAML file, etc)
# * Simple method to generate a signed certificate request
# * Support for OCSP, SCVP, CRLs, or some other form of cert
# status check (list is in order of preference)
# * Support for encrypted private keys
# * Some sort of semi-formal trust hierarchy (see long-winded explanation
# above)
# * Path discovery (for gem certificate chains that don't have a self-signed
# root) -- by the way, since we don't have this, THE ROOT OF THE CERTIFICATE
# CHAIN MUST BE SELF SIGNED if Policy#verify_root is true (and it is for the
# MediumSecurity and HighSecurity policies)
# * Better explanation of X509 naming (ie, we don't have to use email
# addresses)
# * Possible alternate signing mechanisms (eg, via PGP). this could be done
# pretty easily by adding a :signing_type attribute to the gemspec, then add
# the necessary support in other places
# * Honor AIA field (see note about OCSP above)
# * Maybe honor restriction extensions?
# * Might be better to store the certificate chain as a PKCS#7 or PKCS#12
# file, instead of an array embedded in the metadata. ideas?
# * Possibly embed signature and key algorithms into metadata (right now
# they're assumed to be the same as what's set in Gem::Security::OPT)
#
# == About the Author
#
# Paul Duncan <pabs@pablotron.org>
# http://pablotron.org/
module Gem::Security
class Exception < Gem::Exception; end
#
# default options for most of the methods below
#
OPT = {
# private key options
:key_algo => Gem::SSL::PKEY_RSA,
:key_size => 2048,
# public cert options
:cert_age => 365 * 24 * 3600, # 1 year
:dgst_algo => Gem::SSL::DIGEST_SHA1,
# x509 certificate extensions
:cert_exts => {
'basicConstraints' => 'CA:FALSE',
'subjectKeyIdentifier' => 'hash',
'keyUsage' => 'keyEncipherment,dataEncipherment,digitalSignature',
},
# save the key and cert to a file in build_self_signed_cert()?
:save_key => true,
:save_cert => true,
# if you define either of these, then they'll be used instead of
# the output_fmt macro below
:save_key_path => nil,
:save_cert_path => nil,
# output name format for self-signed certs
:output_fmt => 'gem-%s.pem',
:munge_re => Regexp.new(/[^a-z0-9_.-]+/),
# output directory for trusted certificate checksums
:trust_dir => File::join(Gem.user_home, '.gem', 'trust'),
# default permissions for trust directory and certs
:perms => {
:trust_dir => 0700,
:trusted_cert => 0600,
:signing_cert => 0600,
:signing_key => 0600,
},
}
#
# A Gem::Security::Policy object encapsulates the settings for verifying
# signed gem files. This is the base class. You can either declare an
# instance of this or use one of the preset security policies below.
#
class Policy
attr_accessor :verify_data, :verify_signer, :verify_chain,
:verify_root, :only_trusted, :only_signed
#
# Create a new Gem::Security::Policy object with the given mode and
# options.
#
def initialize(policy = {}, opt = {})
# set options
@opt = Gem::Security::OPT.merge(opt)
# build policy
policy.each_pair do |key, val|
case key
when :verify_data then @verify_data = val
when :verify_signer then @verify_signer = val
when :verify_chain then @verify_chain = val
when :verify_root then @verify_root = val
when :only_trusted then @only_trusted = val
when :only_signed then @only_signed = val
end
end
end
#
# Get the path to the file for this cert.
#
def self.trusted_cert_path(cert, opt = {})
opt = Gem::Security::OPT.merge(opt)
# get digest algorithm, calculate checksum of root.subject
algo = opt[:dgst_algo]
dgst = algo.hexdigest(cert.subject.to_s)
# build path to trusted cert file
name = "cert-#{dgst}.pem"
# join and return path components
File::join(opt[:trust_dir], name)
end
#
# Verify that the gem data with the given signature and signing chain
# matched this security policy at the specified time.
#
def verify_gem(signature, data, chain, time = Time.now)
Gem.ensure_ssl_available
cert_class = OpenSSL::X509::Certificate
exc = Gem::Security::Exception
chain ||= []
chain = chain.map{ |str| cert_class.new(str) }
signer, ch_len = chain[-1], chain.size
# make sure signature is valid
if @verify_data
# get digest algorithm (TODO: this should be configurable)
dgst = @opt[:dgst_algo]
# verify the data signature (this is the most important part, so don't
# screw it up :D)
v = signer.public_key.verify(dgst.new, signature, data)
raise exc, "Invalid Gem Signature" unless v
# make sure the signer is valid
if @verify_signer
# make sure the signing cert is valid right now
v = signer.check_validity(nil, time)
raise exc, "Invalid Signature: #{v[:desc]}" unless v[:is_valid]
end
end
# make sure the certificate chain is valid
if @verify_chain
# iterate down over the chain and verify each certificate against it's
# issuer
(ch_len - 1).downto(1) do |i|
issuer, cert = chain[i - 1, 2]
v = cert.check_validity(issuer, time)
raise exc, "%s: cert = '%s', error = '%s'" % [
'Invalid Signing Chain', cert.subject, v[:desc]
] unless v[:is_valid]
end
# verify root of chain
if @verify_root
# make sure root is self-signed
root = chain[0]
raise exc, "%s: %s (subject = '%s', issuer = '%s')" % [
'Invalid Signing Chain Root',
'Subject does not match Issuer for Gem Signing Chain',
root.subject.to_s,
root.issuer.to_s,
] unless root.issuer.to_s == root.subject.to_s
# make sure root is valid
v = root.check_validity(root, time)
raise exc, "%s: cert = '%s', error = '%s'" % [
'Invalid Signing Chain Root', root.subject, v[:desc]
] unless v[:is_valid]
# verify that the chain root is trusted
if @only_trusted
# get digest algorithm, calculate checksum of root.subject
algo = @opt[:dgst_algo]
path = Gem::Security::Policy.trusted_cert_path(root, @opt)
# check to make sure trusted path exists
raise exc, "%s: cert = '%s', error = '%s'" % [
'Untrusted Signing Chain Root',
root.subject.to_s,
"path \"#{path}\" does not exist",
] unless File.exist?(path)
# load calculate digest from saved cert file
save_cert = OpenSSL::X509::Certificate.new(File.read(path))
save_dgst = algo.digest(save_cert.public_key.to_s)
# create digest of public key
pkey_str = root.public_key.to_s
cert_dgst = algo.digest(pkey_str)
# now compare the two digests, raise exception
# if they don't match
raise exc, "%s: %s (saved = '%s', root = '%s')" % [
'Invalid Signing Chain Root',
"Saved checksum doesn't match root checksum",
save_dgst, cert_dgst,
] unless save_dgst == cert_dgst
end
end
# return the signing chain
chain.map { |cert| cert.subject }
end
end
end
#
# No security policy: all package signature checks are disabled.
#
NoSecurity = Policy.new(
:verify_data => false,
:verify_signer => false,
:verify_chain => false,
:verify_root => false,
:only_trusted => false,
:only_signed => false
)
#
# AlmostNo security policy: only verify that the signing certificate is the
# one that actually signed the data. Make no attempt to verify the signing
# certificate chain.
#
# This policy is basically useless. better than nothing, but can still be
# easily spoofed, and is not recommended.
#
AlmostNoSecurity = Policy.new(
:verify_data => true,
:verify_signer => false,
:verify_chain => false,
:verify_root => false,
:only_trusted => false,
:only_signed => false
)
#
# Low security policy: only verify that the signing certificate is actually
# the gem signer, and that the signing certificate is valid.
#
# This policy is better than nothing, but can still be easily spoofed, and
# is not recommended.
#
LowSecurity = Policy.new(
:verify_data => true,
:verify_signer => true,
:verify_chain => false,
:verify_root => false,
:only_trusted => false,
:only_signed => false
)
#
# Medium security policy: verify the signing certificate, verify the signing
# certificate chain all the way to the root certificate, and only trust root
# certificates that we have explicitly allowed trust for.
#
# This security policy is reasonable, but it allows unsigned packages, so a
# malicious person could simply delete the package signature and pass the
# gem off as unsigned.
#
MediumSecurity = Policy.new(
:verify_data => true,
:verify_signer => true,
:verify_chain => true,
:verify_root => true,
:only_trusted => true,
:only_signed => false
)
#
# High security policy: only allow signed gems to be installed, verify the
# signing certificate, verify the signing certificate chain all the way to
# the root certificate, and only trust root certificates that we have
# explicitly allowed trust for.
#
# This security policy is significantly more difficult to bypass, and offers
# a reasonable guarantee that the contents of the gem have not been altered.
#
HighSecurity = Policy.new(
:verify_data => true,
:verify_signer => true,
:verify_chain => true,
:verify_root => true,
:only_trusted => true,
:only_signed => true
)
#
# Hash of configured security policies
#
Policies = {
'NoSecurity' => NoSecurity,
'AlmostNoSecurity' => AlmostNoSecurity,
'LowSecurity' => LowSecurity,
'MediumSecurity' => MediumSecurity,
'HighSecurity' => HighSecurity,
}
#
# Sign the cert cert with @signing_key and @signing_cert, using the digest
# algorithm opt[:dgst_algo]. Returns the newly signed certificate.
#
def self.sign_cert(cert, signing_key, signing_cert, opt = {})
opt = OPT.merge(opt)
# set up issuer information
cert.issuer = signing_cert.subject
cert.sign(signing_key, opt[:dgst_algo].new)
cert
end
#
# Make sure the trust directory exists. If it does exist, make sure it's
# actually a directory. If not, then create it with the appropriate
# permissions.
#
def self.verify_trust_dir(path, perms)
# if the directory exists, then make sure it is in fact a directory. if
# it doesn't exist, then create it with the appropriate permissions
if File.exist?(path)
# verify that the trust directory is actually a directory
unless File.directory?(path)
err = "trust directory #{path} isn't a directory"
raise Gem::Security::Exception, err
end
else
# trust directory doesn't exist, so create it with permissions
FileUtils.mkdir_p(path)
FileUtils.chmod(perms, path)
end
end
#
# Build a certificate from the given DN and private key.
#
def self.build_cert(name, key, opt = {})
Gem.ensure_ssl_available
opt = OPT.merge(opt)
# create new cert
ret = OpenSSL::X509::Certificate.new
# populate cert attributes
ret.version = 2
ret.serial = 0
ret.public_key = key.public_key
ret.not_before = Time.now
ret.not_after = Time.now + opt[:cert_age]
ret.subject = name
# add certificate extensions
ef = OpenSSL::X509::ExtensionFactory.new(nil, ret)
ret.extensions = opt[:cert_exts].map { |k, v| ef.create_extension(k, v) }
# sign cert
i_key, i_cert = opt[:issuer_key] || key, opt[:issuer_cert] || ret
ret = sign_cert(ret, i_key, i_cert, opt)
# return cert
ret
end
#
# Build a self-signed certificate for the given email address.
#
def self.build_self_signed_cert(email_addr, opt = {})
Gem.ensure_ssl_available
opt = OPT.merge(opt)
path = { :key => nil, :cert => nil }
# split email address up
cn, dcs = email_addr.split('@')
dcs = dcs.split('.')
# munge email CN and DCs
cn = cn.gsub(opt[:munge_re], '_')
dcs = dcs.map { |dc| dc.gsub(opt[:munge_re], '_') }
# create DN
name = "CN=#{cn}/" << dcs.map { |dc| "DC=#{dc}" }.join('/')
name = OpenSSL::X509::Name::parse(name)
# build private key
key = opt[:key_algo].new(opt[:key_size])
# method name pretty much says it all :)
verify_trust_dir(opt[:trust_dir], opt[:perms][:trust_dir])
# if we're saving the key, then write it out
if opt[:save_key]
path[:key] = opt[:save_key_path] || (opt[:output_fmt] % 'private_key')
File.open(path[:key], 'wb') do |file|
file.chmod(opt[:perms][:signing_key])
file.write(key.to_pem)
end
end
# build self-signed public cert from key
cert = build_cert(name, key, opt)
# if we're saving the cert, then write it out
if opt[:save_cert]
path[:cert] = opt[:save_cert_path] || (opt[:output_fmt] % 'public_cert')
File.open(path[:cert], 'wb') do |file|
file.chmod(opt[:perms][:signing_cert])
file.write(cert.to_pem)
end
end
# return key, cert, and paths (if applicable)
{ :key => key, :cert => cert,
:key_path => path[:key], :cert_path => path[:cert] }
end
#
# Add certificate to trusted cert list.
#
# Note: At the moment these are stored in OPT[:trust_dir], although that
# directory may change in the future.
#
def self.add_trusted_cert(cert, opt = {})
opt = OPT.merge(opt)
# get destination path
path = Gem::Security::Policy.trusted_cert_path(cert, opt)
# verify trust directory (can't write to nowhere, you know)
verify_trust_dir(opt[:trust_dir], opt[:perms][:trust_dir])
# write cert to output file
File.open(path, 'wb') do |file|
file.chmod(opt[:perms][:trusted_cert])
file.write(cert.to_pem)
end
# return nil
nil
end
#
# Basic OpenSSL-based package signing class.
#
class Signer
attr_accessor :key, :cert_chain
def initialize(key, cert_chain)
Gem.ensure_ssl_available
@algo = Gem::Security::OPT[:dgst_algo]
@key, @cert_chain = key, cert_chain
# check key, if it's a file, and if it's key, leave it alone
if @key && !@key.kind_of?(OpenSSL::PKey::PKey)
@key = OpenSSL::PKey::RSA.new(File.read(@key))
end
# check cert chain, if it's a file, load it, if it's cert data, convert
# it into a cert object, and if it's a cert object, leave it alone
if @cert_chain
@cert_chain = @cert_chain.map do |cert|
# check cert, if it's a file, load it, if it's cert data, convert it
# into a cert object, and if it's a cert object, leave it alone
if cert && !cert.kind_of?(OpenSSL::X509::Certificate)
cert = File.read(cert) if File::exist?(cert)
cert = OpenSSL::X509::Certificate.new(cert)
end
cert
end
end
end
#
# Sign data with given digest algorithm
#
def sign(data)
@key.sign(@algo.new, data)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/platform.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/platform.rb | ##
# Available list of platforms for targeting Gem installations.
class Gem::Platform
@local = nil
attr_accessor :cpu
attr_accessor :os
attr_accessor :version
def self.local
arch = Gem::ConfigMap[:arch]
arch = "#{arch}_60" if arch =~ /mswin32$/
@local ||= new(arch)
end
def self.match(platform)
Gem.platforms.any? do |local_platform|
platform.nil? or local_platform == platform or
(local_platform != Gem::Platform::RUBY and local_platform =~ platform)
end
end
def self.new(arch) # :nodoc:
case arch
when Gem::Platform::CURRENT then
Gem::Platform.local
when Gem::Platform::RUBY, nil, '' then
Gem::Platform::RUBY
else
super
end
end
def initialize(arch)
case arch
when Array then
@cpu, @os, @version = arch
when String then
arch = arch.split '-'
if arch.length > 2 and arch.last !~ /\d/ then # reassemble x86-linux-gnu
extra = arch.pop
arch.last << "-#{extra}"
end
cpu = arch.shift
@cpu = case cpu
when /i\d86/ then 'x86'
else cpu
end
if arch.length == 2 and arch.last =~ /^\d+(\.\d+)?$/ then # for command-line
@os, @version = arch
return
end
os, = arch
@cpu, os = nil, cpu if os.nil? # legacy jruby
@os, @version = case os
when /aix(\d+)/ then [ 'aix', $1 ]
when /cygwin/ then [ 'cygwin', nil ]
when /darwin(\d+)?/ then [ 'darwin', $1 ]
when /freebsd(\d+)/ then [ 'freebsd', $1 ]
when /hpux(\d+)/ then [ 'hpux', $1 ]
when /^java$/, /^jruby$/ then [ 'java', nil ]
when /^java([\d.]*)/ then [ 'java', $1 ]
when /linux/ then [ 'linux', $1 ]
when /mingw32/ then [ 'mingw32', nil ]
when /(mswin\d+)(\_(\d+))?/ then
os, version = $1, $3
@cpu = 'x86' if @cpu.nil? and os =~ /32$/
[os, version]
when /netbsdelf/ then [ 'netbsdelf', nil ]
when /openbsd(\d+\.\d+)/ then [ 'openbsd', $1 ]
when /solaris(\d+\.\d+)/ then [ 'solaris', $1 ]
# test
when /^(\w+_platform)(\d+)/ then [ $1, $2 ]
else [ 'unknown', nil ]
end
when Gem::Platform then
@cpu = arch.cpu
@os = arch.os
@version = arch.version
else
raise ArgumentError, "invalid argument #{arch.inspect}"
end
end
def inspect
"#<%s:0x%x @cpu=%p, @os=%p, @version=%p>" % [self.class, object_id, *to_a]
end
def to_a
[@cpu, @os, @version]
end
def to_s
to_a.compact.join '-'
end
def empty?
to_s.empty?
end
##
# Is +other+ equal to this platform? Two platforms are equal if they have
# the same CPU, OS and version.
def ==(other)
self.class === other and
@cpu == other.cpu and @os == other.os and @version == other.version
end
##
# Does +other+ match this platform? Two platforms match if they have the
# same CPU, or either has a CPU of 'universal', they have the same OS, and
# they have the same version, or either has no version.
def ===(other)
return nil unless Gem::Platform === other
# cpu
(@cpu == 'universal' or other.cpu == 'universal' or @cpu == other.cpu) and
# os
@os == other.os and
# version
(@version.nil? or other.version.nil? or @version == other.version)
end
##
# Does +other+ match this platform? If +other+ is a String it will be
# converted to a Gem::Platform first. See #=== for matching rules.
def =~(other)
case other
when Gem::Platform then # nop
when String then
# This data is from http://gems.rubyforge.org/gems/yaml on 19 Aug 2007
other = case other
when /^i686-darwin(\d)/ then ['x86', 'darwin', $1 ]
when /^i\d86-linux/ then ['x86', 'linux', nil ]
when 'java', 'jruby' then [nil, 'java', nil ]
when /mswin32(\_(\d+))?/ then ['x86', 'mswin32', $2 ]
when 'powerpc-darwin' then ['powerpc', 'darwin', nil ]
when /powerpc-darwin(\d)/ then ['powerpc', 'darwin', $1 ]
when /sparc-solaris2.8/ then ['sparc', 'solaris', '2.8' ]
when /universal-darwin(\d)/ then ['universal', 'darwin', $1 ]
else other
end
other = Gem::Platform.new other
else
return nil
end
self === other
end
##
# A pure-ruby gem that may use Gem::Specification#extensions to build
# binary files.
RUBY = 'ruby'
##
# A platform-specific gem that is built for the packaging ruby's platform.
# This will be replaced with Gem::Platform::local.
CURRENT = 'current'
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/spec_fetcher.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/spec_fetcher.rb | require 'zlib'
require 'fileutils'
require 'rubygems/remote_fetcher'
require 'rubygems/user_interaction'
##
# SpecFetcher handles metadata updates from remote gem repositories.
class Gem::SpecFetcher
include Gem::UserInteraction
##
# The SpecFetcher cache dir.
attr_reader :dir # :nodoc:
##
# Cache of latest specs
attr_reader :latest_specs # :nodoc:
##
# Cache of all released specs
attr_reader :specs # :nodoc:
##
# Cache of prerelease specs
attr_reader :prerelease_specs # :nodoc:
@fetcher = nil
def self.fetcher
@fetcher ||= new
end
def self.fetcher=(fetcher) # :nodoc:
@fetcher = fetcher
end
def initialize
@dir = File.join Gem.user_home, '.gem', 'specs'
@update_cache = File.stat(Gem.user_home).uid == Process.uid
@specs = {}
@latest_specs = {}
@prerelease_specs = {}
@fetcher = Gem::RemoteFetcher.fetcher
end
##
# Retuns the local directory to write +uri+ to.
def cache_dir(uri)
File.join @dir, "#{uri.host}%#{uri.port}", File.dirname(uri.path)
end
##
# Fetch specs matching +dependency+. If +all+ is true, all matching
# (released) versions are returned. If +matching_platform+ is
# false, all platforms are returned. If +prerelease+ is true,
# prerelease versions are included.
def fetch(dependency, all = false, matching_platform = true, prerelease = false)
specs_and_sources = find_matching dependency, all, matching_platform, prerelease
specs_and_sources.map do |spec_tuple, source_uri|
[fetch_spec(spec_tuple, URI.parse(source_uri)), source_uri]
end
rescue Gem::RemoteFetcher::FetchError => e
raise unless warn_legacy e do
require 'rubygems/source_info_cache'
return Gem::SourceInfoCache.search_with_source(dependency,
matching_platform, all)
end
end
def fetch_spec(spec, source_uri)
spec = spec - [nil, 'ruby', '']
spec_file_name = "#{spec.join '-'}.gemspec"
uri = source_uri + "#{Gem::MARSHAL_SPEC_DIR}#{spec_file_name}"
cache_dir = cache_dir uri
local_spec = File.join cache_dir, spec_file_name
if File.exist? local_spec then
spec = Gem.read_binary local_spec
else
uri.path << '.rz'
spec = @fetcher.fetch_path uri
spec = Gem.inflate spec
if @update_cache then
FileUtils.mkdir_p cache_dir
open local_spec, 'wb' do |io|
io.write spec
end
end
end
# TODO: Investigate setting Gem::Specification#loaded_from to a URI
Marshal.load spec
end
##
# Find spec names that match +dependency+. If +all+ is true, all
# matching released versions are returned. If +matching_platform+
# is false, gems for all platforms are returned.
def find_matching(dependency, all = false, matching_platform = true, prerelease = false)
found = {}
list(all, prerelease).each do |source_uri, specs|
found[source_uri] = specs.select do |spec_name, version, spec_platform|
dependency =~ Gem::Dependency.new(spec_name, version) and
(not matching_platform or Gem::Platform.match(spec_platform))
end
end
specs_and_sources = []
found.each do |source_uri, specs|
uri_str = source_uri.to_s
specs_and_sources.push(*specs.map { |spec| [spec, uri_str] })
end
specs_and_sources
end
##
# Returns Array of gem repositories that were generated with RubyGems less
# than 1.2.
def legacy_repos
Gem.sources.reject do |source_uri|
source_uri = URI.parse source_uri
spec_path = source_uri + "specs.#{Gem.marshal_version}.gz"
begin
@fetcher.fetch_size spec_path
rescue Gem::RemoteFetcher::FetchError
begin
@fetcher.fetch_size(source_uri + 'yaml') # re-raise if non-repo
rescue Gem::RemoteFetcher::FetchError
alert_error "#{source_uri} does not appear to be a repository"
raise
end
false
end
end
end
##
# Returns a list of gems available for each source in Gem::sources. If
# +all+ is true, all released versions are returned instead of only latest
# versions. If +prerelease+ is true, include prerelease versions.
def list(all = false, prerelease = false)
# TODO: make type the only argument
type = if all
:all
elsif prerelease
:prerelease
else
:latest
end
list = {}
file = { :latest => 'latest_specs',
:prerelease => 'prerelease_specs',
:all => 'specs' }[type]
cache = { :latest => @latest_specs,
:prerelease => @prerelease_specs,
:all => @specs }[type]
Gem.sources.each do |source_uri|
source_uri = URI.parse source_uri
unless cache.include? source_uri
cache[source_uri] = load_specs source_uri, file
end
list[source_uri] = cache[source_uri]
end
if type == :all
list.values.map do |gems|
gems.reject! { |g| !g[1] || g[1].prerelease? }
end
end
list
end
##
# Loads specs in +file+, fetching from +source_uri+ if the on-disk cache is
# out of date.
def load_specs(source_uri, file)
file_name = "#{file}.#{Gem.marshal_version}"
spec_path = source_uri + "#{file_name}.gz"
cache_dir = cache_dir spec_path
local_file = File.join(cache_dir, file_name)
loaded = false
if File.exist? local_file then
spec_dump = @fetcher.fetch_path spec_path, File.mtime(local_file)
if spec_dump.nil? then
spec_dump = Gem.read_binary local_file
else
loaded = true
end
else
spec_dump = @fetcher.fetch_path spec_path
loaded = true
end
specs = begin
Marshal.load spec_dump
rescue ArgumentError
spec_dump = @fetcher.fetch_path spec_path
loaded = true
Marshal.load spec_dump
end
if loaded and @update_cache then
begin
FileUtils.mkdir_p cache_dir
open local_file, 'wb' do |io|
io << spec_dump
end
rescue
end
end
specs
end
##
# Warn about legacy repositories if +exception+ indicates only legacy
# repositories are available, and yield to the block. Returns false if the
# exception indicates some other FetchError.
def warn_legacy(exception)
uri = exception.uri.to_s
if uri =~ /specs\.#{Regexp.escape Gem.marshal_version}\.gz$/ then
alert_warning <<-EOF
RubyGems 1.2+ index not found for:
\t#{legacy_repos.join "\n\t"}
RubyGems will revert to legacy indexes degrading performance.
EOF
yield
return true
end
false
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/version.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/version.rb | ##
# The Version class processes string versions into comparable
# values. A version string should normally be a series of numbers
# separated by periods. Each part (digits separated by periods) is
# considered its own number, and these are used for sorting. So for
# instance, 3.10 sorts higher than 3.2 because ten is greater than
# two.
#
# If any part contains letters (currently only a-z are supported) then
# that version is considered prerelease. Versions with a prerelease
# part in the Nth part sort less than versions with N-1 parts. Prerelease
# parts are sorted alphabetically using the normal Ruby string sorting
# rules.
#
# Prereleases sort between real releases (newest to oldest):
#
# 1. 1.0
# 2. 1.0.b
# 3. 1.0.a
# 4. 0.9
#
# == How Software Changes
#
# Users expect to be able to specify a version constraint that gives them
# some reasonable expectation that new versions of a library will work with
# their software if the version constraint is true, and not work with their
# software if the version constraint is false. In other words, the perfect
# system will accept all compatible versions of the library and reject all
# incompatible versions.
#
# Libraries change in 3 ways (well, more than 3, but stay focused here!).
#
# 1. The change may be an implementation detail only and have no effect on
# the client software.
# 2. The change may add new features, but do so in a way that client software
# written to an earlier version is still compatible.
# 3. The change may change the public interface of the library in such a way
# that old software is no longer compatible.
#
# Some examples are appropriate at this point. Suppose I have a Stack class
# that supports a <tt>push</tt> and a <tt>pop</tt> method.
#
# === Examples of Category 1 changes:
#
# * Switch from an array based implementation to a linked-list based
# implementation.
# * Provide an automatic (and transparent) backing store for large stacks.
#
# === Examples of Category 2 changes might be:
#
# * Add a <tt>depth</tt> method to return the current depth of the stack.
# * Add a <tt>top</tt> method that returns the current top of stack (without
# changing the stack).
# * Change <tt>push</tt> so that it returns the item pushed (previously it
# had no usable return value).
#
# === Examples of Category 3 changes might be:
#
# * Changes <tt>pop</tt> so that it no longer returns a value (you must use
# <tt>top</tt> to get the top of the stack).
# * Rename the methods to <tt>push_item</tt> and <tt>pop_item</tt>.
#
# == RubyGems Rational Versioning
#
# * Versions shall be represented by three non-negative integers, separated
# by periods (e.g. 3.1.4). The first integers is the "major" version
# number, the second integer is the "minor" version number, and the third
# integer is the "build" number.
#
# * A category 1 change (implementation detail) will increment the build
# number.
#
# * A category 2 change (backwards compatible) will increment the minor
# version number and reset the build number.
#
# * A category 3 change (incompatible) will increment the major build number
# and reset the minor and build numbers.
#
# * Any "public" release of a gem should have a different version. Normally
# that means incrementing the build number. This means a developer can
# generate builds all day long for himself, but as soon as he/she makes a
# public release, the version must be updated.
#
# === Examples
#
# Let's work through a project lifecycle using our Stack example from above.
#
# Version 0.0.1:: The initial Stack class is release.
# Version 0.0.2:: Switched to a linked=list implementation because it is
# cooler.
# Version 0.1.0:: Added a <tt>depth</tt> method.
# Version 1.0.0:: Added <tt>top</tt> and made <tt>pop</tt> return nil
# (<tt>pop</tt> used to return the old top item).
# Version 1.1.0:: <tt>push</tt> now returns the value pushed (it used it
# return nil).
# Version 1.1.1:: Fixed a bug in the linked list implementation.
# Version 1.1.2:: Fixed a bug introduced in the last fix.
#
# Client A needs a stack with basic push/pop capability. He writes to the
# original interface (no <tt>top</tt>), so his version constraint looks
# like:
#
# gem 'stack', '~> 0.0'
#
# Essentially, any version is OK with Client A. An incompatible change to
# the library will cause him grief, but he is willing to take the chance (we
# call Client A optimistic).
#
# Client B is just like Client A except for two things: (1) He uses the
# <tt>depth</tt> method and (2) he is worried about future
# incompatibilities, so he writes his version constraint like this:
#
# gem 'stack', '~> 0.1'
#
# The <tt>depth</tt> method was introduced in version 0.1.0, so that version
# or anything later is fine, as long as the version stays below version 1.0
# where incompatibilities are introduced. We call Client B pessimistic
# because he is worried about incompatible future changes (it is OK to be
# pessimistic!).
#
# == Preventing Version Catastrophe:
#
# From: http://blog.zenspider.com/2008/10/rubygems-howto-preventing-cata.html
#
# Let's say you're depending on the fnord gem version 2.y.z. If you
# specify your dependency as ">= 2.0.0" then, you're good, right? What
# happens if fnord 3.0 comes out and it isn't backwards compatible
# with 2.y.z? Your stuff will break as a result of using ">=". The
# better route is to specify your dependency with a "spermy" version
# specifier. They're a tad confusing, so here is how the dependency
# specifiers work:
#
# Specification From ... To (exclusive)
# ">= 3.0" 3.0 ... ∞
# "~> 3.0" 3.0 ... 4.0
# "~> 3.0.0" 3.0.0 ... 3.1
# "~> 3.5" 3.5 ... 4.0
# "~> 3.5.0" 3.5.0 ... 3.6
class Gem::Version
include Comparable
VERSION_PATTERN = '[0-9]+(\.[0-9a-zA-Z]+)*' # :nodoc:
ANCHORED_VERSION_PATTERN = /\A\s*(#{VERSION_PATTERN})*\s*\z/ # :nodoc:
##
# A string representation of this Version.
attr_reader :version
alias to_s version
##
# True if the +version+ string matches RubyGems' requirements.
def self.correct? version
version.to_s =~ ANCHORED_VERSION_PATTERN
end
##
# Factory method to create a Version object. Input may be a Version
# or a String. Intended to simplify client code.
#
# ver1 = Version.create('1.3.17') # -> (Version object)
# ver2 = Version.create(ver1) # -> (ver1)
# ver3 = Version.create(nil) # -> nil
def self.create input
if input.respond_to? :version then
input
elsif input.nil? then
nil
else
new input
end
end
##
# Constructs a Version from the +version+ string. A version string is a
# series of digits or ASCII letters separated by dots.
def initialize version
raise ArgumentError, "Malformed version number string #{version}" unless
self.class.correct?(version)
@version = version.to_s
@version.strip!
segments # prime @segments
end
##
# Return a new version object where the next to the last revision
# number is one greater (e.g., 5.3.1 => 5.4).
#
# Pre-release (alpha) parts, e.g, 5.3.1.b2 => 5.4, are ignored.
def bump
segments = self.segments.dup
segments.pop while segments.any? { |s| String === s }
segments.pop if segments.size > 1
segments[-1] = segments[-1].succ
self.class.new segments.join(".")
end
##
# A Version is only eql? to another version if it's specified to the
# same precision. Version "1.0" is not the same as version "1".
def eql? other
self.class === other and segments == other.segments
end
def hash # :nodoc:
segments.hash
end
def inspect # :nodoc:
"#<#{self.class} #{version.inspect}>"
end
##
# Dump only the raw version string, not the complete object. It's a
# string for backwards (RubyGems 1.3.5 and earlier) compatibility.
def marshal_dump
[version]
end
##
# Load custom marshal format. It's a string for backwards (RubyGems
# 1.3.5 and earlier) compatibility.
def marshal_load array
initialize array[0]
end
##
# A version is considered a prerelease if it contains a letter.
def prerelease?
@prerelease ||= segments.any? { |s| String === s }
end
def pretty_print q # :nodoc:
q.text "Gem::Version.new(#{version.inspect})"
end
##
# The release for this version (e.g. 1.2.0.a -> 1.2.0).
# Non-prerelease versions return themselves.
def release
return self unless prerelease?
segments = self.segments.dup
segments.pop while segments.any? { |s| String === s }
self.class.new segments.join('.')
end
def segments # :nodoc:
# @segments is lazy so it can pick up @version values that come
# from old marshaled versions, which don't go through
# marshal_load. +segments+ is called in +initialize+ to "prime
# the pump" in normal cases.
@segments ||= @version.scan(/[0-9a-z]+/i).map do |s|
/^\d+$/ =~ s ? s.to_i : s
end
end
##
# A recommended version for use with a ~> Requirement.
def spermy_recommendation
segments = self.segments.dup
segments.pop while segments.any? { |s| String === s }
segments.pop while segments.size > 2
segments.push 0 while segments.size < 2
"~> #{segments.join(".")}"
end
##
# Compares this version with +other+ returning -1, 0, or 1 if the other
# version is larger, the same, or smaller than this one.
def <=> other
return 1 unless other # HACK: comparable with nil? why?
return nil unless self.class === other
lhsize = segments.size
rhsize = other.segments.size
limit = (lhsize > rhsize ? lhsize : rhsize) - 1
0.upto(limit) do |i|
lhs, rhs = segments[i] || 0, other.segments[i] || 0
return -1 if String === lhs && Numeric === rhs
return 1 if Numeric === lhs && String === rhs
return lhs <=> rhs if lhs != rhs
end
return 0
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/gem_runner.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/gem_runner.rb | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'rubygems/command_manager'
require 'rubygems/config_file'
require 'rubygems/doc_manager'
##
# Run an instance of the gem program.
#
# Gem::GemRunner is only intended for internal use by RubyGems itself. It
# does not form any public API and may change at any time for any reason.
#
# If you would like to duplicate functionality of `gem` commands, use the
# classes they call directly.
class Gem::GemRunner
def initialize(options={})
@command_manager_class = options[:command_manager] || Gem::CommandManager
@config_file_class = options[:config_file] || Gem::ConfigFile
@doc_manager_class = options[:doc_manager] || Gem::DocManager
end
##
# Run the gem command with the following arguments.
def run(args)
start_time = Time.now
if args.include?('--')
# We need to preserve the original ARGV to use for passing gem options
# to source gems. If there is a -- in the line, strip all options after
# it...its for the source building process.
build_args = args[args.index("--") + 1...args.length]
args = args[0...args.index("--")]
end
Gem::Command.build_args = build_args if build_args
do_configuration args
cmd = @command_manager_class.instance
cmd.command_names.each do |command_name|
config_args = Gem.configuration[command_name]
config_args = case config_args
when String
config_args.split ' '
else
Array(config_args)
end
Gem::Command.add_specific_extra_args command_name, config_args
end
cmd.run Gem.configuration.args
end_time = Time.now
if Gem.configuration.benchmark then
printf "\nExecution time: %0.2f seconds.\n", end_time - start_time
puts "Press Enter to finish"
STDIN.gets
end
end
private
def do_configuration(args)
Gem.configuration = @config_file_class.new(args)
Gem.use_paths(Gem.configuration[:gemhome], Gem.configuration[:gempath])
Gem::Command.extra_args = Gem.configuration[:gem]
@doc_manager_class.configured_args = Gem.configuration[:rdoc]
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/ext.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/ext.rb | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'rubygems'
##
# Classes for building C extensions live here.
module Gem::Ext; end
require 'rubygems/ext/builder'
require 'rubygems/ext/configure_builder'
require 'rubygems/ext/ext_conf_builder'
require 'rubygems/ext/rake_builder'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/exceptions.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/exceptions.rb | ##
# Base exception class for RubyGems. All exception raised by RubyGems are a
# subclass of this one.
class Gem::Exception < RuntimeError; end
class Gem::CommandLineError < Gem::Exception; end
class Gem::DependencyError < Gem::Exception; end
class Gem::DependencyRemovalException < Gem::Exception; end
##
# Raised when attempting to uninstall a gem that isn't in GEM_HOME.
class Gem::GemNotInHomeException < Gem::Exception
attr_accessor :spec
end
class Gem::DocumentError < Gem::Exception; end
##
# Potentially raised when a specification is validated.
class Gem::EndOfYAMLException < Gem::Exception; end
##
# Signals that a file permission error is preventing the user from
# installing in the requested directories.
class Gem::FilePermissionError < Gem::Exception
def initialize(path)
super("You don't have write permissions into the #{path} directory.")
end
end
##
# Used to raise parsing and loading errors
class Gem::FormatException < Gem::Exception
attr_accessor :file_path
end
class Gem::GemNotFoundException < Gem::Exception; end
class Gem::InstallError < Gem::Exception; end
##
# Potentially raised when a specification is validated.
class Gem::InvalidSpecificationException < Gem::Exception; end
class Gem::OperationNotSupportedError < Gem::Exception; end
##
# Signals that a remote operation cannot be conducted, probably due to not
# being connected (or just not finding host).
#--
# TODO: create a method that tests connection to the preferred gems server.
# All code dealing with remote operations will want this. Failure in that
# method should raise this error.
class Gem::RemoteError < Gem::Exception; end
class Gem::RemoteInstallationCancelled < Gem::Exception; end
class Gem::RemoteInstallationSkipped < Gem::Exception; end
##
# Represents an error communicating via HTTP.
class Gem::RemoteSourceException < Gem::Exception; end
class Gem::VerificationError < Gem::Exception; end
##
# Raised to indicate that a system exit should occur with the specified
# exit_code
class Gem::SystemExitException < SystemExit
attr_accessor :exit_code
def initialize(exit_code)
@exit_code = exit_code
super "Exiting RubyGems with exit_code #{exit_code}"
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/requirement.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/requirement.rb | require "rubygems/version"
##
# A Requirement is a set of one or more version restrictions. It supports a
# few (<tt>=, !=, >, <, >=, <=, ~></tt>) different restriction operators.
class Gem::Requirement
include Comparable
OPS = { #:nodoc:
"=" => lambda { |v, r| v == r },
"!=" => lambda { |v, r| v != r },
">" => lambda { |v, r| v > r },
"<" => lambda { |v, r| v < r },
">=" => lambda { |v, r| v >= r },
"<=" => lambda { |v, r| v <= r },
"~>" => lambda { |v, r| v = v.release; v >= r && v < r.bump }
}
quoted = OPS.keys.map { |k| Regexp.quote k }.join "|"
PATTERN = /\A\s*(#{quoted})?\s*(#{Gem::Version::VERSION_PATTERN})\s*\z/
##
# Factory method to create a Gem::Requirement object. Input may be
# a Version, a String, or nil. Intended to simplify client code.
#
# If the input is "weird", the default version requirement is
# returned.
def self.create input
case input
when Gem::Requirement then
input
when Gem::Version, Array then
new input
else
if input.respond_to? :to_str then
new [input.to_str]
else
default
end
end
end
##
# A default "version requirement" can surely _only_ be '>= 0'.
#--
# This comment once said:
#
# "A default "version requirement" can surely _only_ be '> 0'."
def self.default
new '>= 0'
end
##
# Parse +obj+, returning an <tt>[op, version]</tt> pair. +obj+ can
# be a String or a Gem::Version.
#
# If +obj+ is a String, it can be either a full requirement
# specification, like <tt>">= 1.2"</tt>, or a simple version number,
# like <tt>"1.2"</tt>.
#
# parse("> 1.0") # => [">", "1.0"]
# parse("1.0") # => ["=", "1.0"]
# parse(Gem::Version.new("1.0")) # => ["=, "1.0"]
def self.parse obj
return ["=", obj] if Gem::Version === obj
unless PATTERN =~ obj.to_s
raise ArgumentError, "Illformed requirement [#{obj.inspect}]"
end
[$1 || "=", Gem::Version.new($2)]
end
##
# An array of requirement pairs. The first element of the pair is
# the op, and the second is the Gem::Version.
attr_reader :requirements #:nodoc:
##
# Constructs a requirement from +requirements+. Requirements can be
# Strings, Gem::Versions, or Arrays of those. +nil+ and duplicate
# requirements are ignored. An empty set of +requirements+ is the
# same as <tt>">= 0"</tt>.
def initialize *requirements
requirements = requirements.flatten
requirements.compact!
requirements.uniq!
requirements << ">= 0" if requirements.empty?
@requirements = requirements.map! { |r| self.class.parse r }
end
def as_list # :nodoc:
requirements.map { |op, version| "#{op} #{version}" }
end
def hash # :nodoc:
requirements.hash
end
def marshal_dump # :nodoc:
[@requirements]
end
def marshal_load array # :nodoc:
@requirements = array[0]
end
def prerelease?
requirements.any? { |r| r.last.prerelease? }
end
def pretty_print q # :nodoc:
q.group 1, 'Gem::Requirement.new(', ')' do
q.pp as_list
end
end
##
# True if +version+ satisfies this Requirement.
def satisfied_by? version
requirements.all? { |op, rv| OPS[op].call version, rv }
end
def to_s # :nodoc:
as_list.join ", "
end
def <=> other # :nodoc:
to_s <=> other.to_s
end
end
# :stopdoc:
# Gem::Version::Requirement is used in a lot of old YAML specs. It's aliased
# here for backwards compatibility. I'd like to remove this, maybe in RubyGems
# 2.0.
::Gem::Version::Requirement = ::Gem::Requirement
# :startdoc:
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/config_file.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/config_file.rb | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
##
# Gem::ConfigFile RubyGems options and gem command options from ~/.gemrc.
#
# ~/.gemrc is a YAML file that uses strings to match gem command arguments and
# symbols to match RubyGems options.
#
# Gem command arguments use a String key that matches the command name and
# allow you to specify default arguments:
#
# install: --no-rdoc --no-ri
# update: --no-rdoc --no-ri
#
# You can use <tt>gem:</tt> to set default arguments for all commands.
#
# RubyGems options use symbol keys. Valid options are:
#
# +:backtrace+:: See #backtrace
# +:benchmark+:: See #benchmark
# +:sources+:: Sets Gem::sources
# +:verbose+:: See #verbose
class Gem::ConfigFile
DEFAULT_BACKTRACE = false
DEFAULT_BENCHMARK = false
DEFAULT_BULK_THRESHOLD = 1000
DEFAULT_VERBOSITY = true
DEFAULT_UPDATE_SOURCES = true
##
# For Ruby packagers to set configuration defaults. Set in
# rubygems/defaults/operating_system.rb
OPERATING_SYSTEM_DEFAULTS = {}
##
# For Ruby implementers to set configuration defaults. Set in
# rubygems/defaults/#{RUBY_ENGINE}.rb
PLATFORM_DEFAULTS = {}
system_config_path =
begin
require 'Win32API'
CSIDL_COMMON_APPDATA = 0x0023
path = 0.chr * 260
if RUBY_VERSION > '1.9' then
SHGetFolderPath = Win32API.new 'shell32', 'SHGetFolderPath', 'PLPLP',
'L', :stdcall
SHGetFolderPath.call nil, CSIDL_COMMON_APPDATA, nil, 1, path
else
SHGetFolderPath = Win32API.new 'shell32', 'SHGetFolderPath', 'LLLLP',
'L'
SHGetFolderPath.call 0, CSIDL_COMMON_APPDATA, 0, 1, path
end
path.strip
rescue LoadError
'/etc'
end
SYSTEM_WIDE_CONFIG_FILE = File.join system_config_path, 'gemrc'
##
# List of arguments supplied to the config file object.
attr_reader :args
##
# Where to look for gems (deprecated)
attr_accessor :path
##
# Where to install gems (deprecated)
attr_accessor :home
##
# True if we print backtraces on errors.
attr_writer :backtrace
##
# True if we are benchmarking this run.
attr_accessor :benchmark
##
# Bulk threshold value. If the number of missing gems are above this
# threshold value, then a bulk download technique is used. (deprecated)
attr_accessor :bulk_threshold
##
# Verbose level of output:
# * false -- No output
# * true -- Normal output
# * :loud -- Extra output
attr_accessor :verbose
##
# True if we want to update the SourceInfoCache every time, false otherwise
attr_accessor :update_sources
##
# API key for RubyGems.org
attr_reader :rubygems_api_key
##
# Create the config file object. +args+ is the list of arguments
# from the command line.
#
# The following command line options are handled early here rather
# than later at the time most command options are processed.
#
# <tt>--config-file</tt>, <tt>--config-file==NAME</tt>::
# Obviously these need to be handled by the ConfigFile object to ensure we
# get the right config file.
#
# <tt>--backtrace</tt>::
# Backtrace needs to be turned on early so that errors before normal
# option parsing can be properly handled.
#
# <tt>--debug</tt>::
# Enable Ruby level debug messages. Handled early for the same reason as
# --backtrace.
def initialize(arg_list)
@config_file_name = nil
need_config_file_name = false
arg_list = arg_list.map do |arg|
if need_config_file_name then
@config_file_name = arg
need_config_file_name = false
nil
elsif arg =~ /^--config-file=(.*)/ then
@config_file_name = $1
nil
elsif arg =~ /^--config-file$/ then
need_config_file_name = true
nil
else
arg
end
end.compact
@backtrace = DEFAULT_BACKTRACE
@benchmark = DEFAULT_BENCHMARK
@bulk_threshold = DEFAULT_BULK_THRESHOLD
@verbose = DEFAULT_VERBOSITY
@update_sources = DEFAULT_UPDATE_SOURCES
operating_system_config = Marshal.load Marshal.dump(OPERATING_SYSTEM_DEFAULTS)
platform_config = Marshal.load Marshal.dump(PLATFORM_DEFAULTS)
system_config = load_file SYSTEM_WIDE_CONFIG_FILE
user_config = load_file config_file_name.dup.untaint
@hash = operating_system_config.merge platform_config
@hash = @hash.merge system_config
@hash = @hash.merge user_config
# HACK these override command-line args, which is bad
@backtrace = @hash[:backtrace] if @hash.key? :backtrace
@benchmark = @hash[:benchmark] if @hash.key? :benchmark
@bulk_threshold = @hash[:bulk_threshold] if @hash.key? :bulk_threshold
@home = @hash[:gemhome] if @hash.key? :gemhome
@path = @hash[:gempath] if @hash.key? :gempath
@update_sources = @hash[:update_sources] if @hash.key? :update_sources
@verbose = @hash[:verbose] if @hash.key? :verbose
load_rubygems_api_key
Gem.sources = @hash[:sources] if @hash.key? :sources
handle_arguments arg_list
end
##
# Location of RubyGems.org credentials
def credentials_path
File.join(Gem.user_home, '.gem', 'credentials')
end
def load_rubygems_api_key
api_key_hash = File.exists?(credentials_path) ? load_file(credentials_path) : @hash
@rubygems_api_key = api_key_hash[:rubygems_api_key] if api_key_hash.key? :rubygems_api_key
end
def rubygems_api_key=(api_key)
config = load_file(credentials_path).merge(:rubygems_api_key => api_key)
dirname = File.dirname(credentials_path)
Dir.mkdir(dirname) unless File.exists?(dirname)
require 'yaml'
File.open(credentials_path, 'w') do |f|
f.write config.to_yaml
end
@rubygems_api_key = api_key
end
def load_file(filename)
return {} unless filename and File.exists?(filename)
begin
require 'yaml'
YAML.load(File.read(filename))
rescue ArgumentError
warn "Failed to load #{config_file_name}"
rescue Errno::EACCES
warn "Failed to load #{config_file_name} due to permissions problem."
end or {}
end
# True if the backtrace option has been specified, or debug is on.
def backtrace
@backtrace or $DEBUG
end
# The name of the configuration file.
def config_file_name
@config_file_name || Gem.config_file
end
# Delegates to @hash
def each(&block)
hash = @hash.dup
hash.delete :update_sources
hash.delete :verbose
hash.delete :benchmark
hash.delete :backtrace
hash.delete :bulk_threshold
yield :update_sources, @update_sources
yield :verbose, @verbose
yield :benchmark, @benchmark
yield :backtrace, @backtrace
yield :bulk_threshold, @bulk_threshold
yield 'config_file_name', @config_file_name if @config_file_name
hash.each(&block)
end
# Handle the command arguments.
def handle_arguments(arg_list)
@args = []
arg_list.each do |arg|
case arg
when /^--(backtrace|traceback)$/ then
@backtrace = true
when /^--bench(mark)?$/ then
@benchmark = true
when /^--debug$/ then
$DEBUG = true
else
@args << arg
end
end
end
# Really verbose mode gives you extra output.
def really_verbose
case verbose
when true, false, nil then false
else true
end
end
# to_yaml only overwrites things you can't override on the command line.
def to_yaml # :nodoc:
yaml_hash = {}
yaml_hash[:backtrace] = @hash.key?(:backtrace) ? @hash[:backtrace] :
DEFAULT_BACKTRACE
yaml_hash[:benchmark] = @hash.key?(:benchmark) ? @hash[:benchmark] :
DEFAULT_BENCHMARK
yaml_hash[:bulk_threshold] = @hash.key?(:bulk_threshold) ?
@hash[:bulk_threshold] : DEFAULT_BULK_THRESHOLD
yaml_hash[:sources] = Gem.sources
yaml_hash[:update_sources] = @hash.key?(:update_sources) ?
@hash[:update_sources] : DEFAULT_UPDATE_SOURCES
yaml_hash[:verbose] = @hash.key?(:verbose) ? @hash[:verbose] :
DEFAULT_VERBOSITY
keys = yaml_hash.keys.map { |key| key.to_s }
keys << 'debug'
re = Regexp.union(*keys)
@hash.each do |key, value|
key = key.to_s
next if key =~ re
yaml_hash[key.to_s] = value
end
yaml_hash.to_yaml
end
# Writes out this config file, replacing its source.
def write
require 'yaml'
open config_file_name, 'w' do |io|
io.write to_yaml
end
end
# Return the configuration information for +key+.
def [](key)
@hash[key.to_s]
end
# Set configuration option +key+ to +value+.
def []=(key, value)
@hash[key.to_s] = value
end
def ==(other) # :nodoc:
self.class === other and
@backtrace == other.backtrace and
@benchmark == other.benchmark and
@bulk_threshold == other.bulk_threshold and
@verbose == other.verbose and
@update_sources == other.update_sources and
@hash == other.hash
end
protected
attr_reader :hash
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/format.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/format.rb | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'fileutils'
require 'rubygems/package'
##
# Gem::Format knows the guts of the RubyGem .gem file format and provides the
# capability to read gem files
class Gem::Format
attr_accessor :spec
attr_accessor :file_entries
attr_accessor :gem_path
extend Gem::UserInteraction
##
# Constructs a Format representing the gem's data which came from +gem_path+
def initialize(gem_path)
@gem_path = gem_path
end
##
# Reads the gem +file_path+ using +security_policy+ and returns a Format
# representing the data in the gem
def self.from_file_by_path(file_path, security_policy = nil)
format = nil
unless File.exist?(file_path)
raise Gem::Exception, "Cannot load gem at [#{file_path}] in #{Dir.pwd}"
end
start = File.read file_path, 20
if start.nil? or start.length < 20 then
nil
elsif start.include?("MD5SUM =") # old version gems
require 'rubygems/old_format'
Gem::OldFormat.from_file_by_path file_path
else
open file_path, Gem.binary_mode do |io|
from_io io, file_path, security_policy
end
end
end
##
# Reads a gem from +io+ at +gem_path+ using +security_policy+ and returns a
# Format representing the data from the gem
def self.from_io(io, gem_path="(io)", security_policy = nil)
format = new gem_path
Gem::Package.open io, 'r', security_policy do |pkg|
format.spec = pkg.metadata
format.file_entries = []
pkg.each do |entry|
size = entry.header.size
mode = entry.header.mode
format.file_entries << [{
"size" => size, "mode" => mode, "path" => entry.full_name,
},
entry.read
]
end
end
format
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/text.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/text.rb | require 'rubygems'
##
# A collection of text-wrangling methods
module Gem::Text
##
# Wraps +text+ to +wrap+ characters and optionally indents by +indent+
# characters
def format_text(text, wrap, indent=0)
result = []
work = text.dup
while work.length > wrap do
if work =~ /^(.{0,#{wrap}})[ \n]/ then
result << $1
work.slice!(0, $&.length)
else
result << work.slice!(0, wrap)
end
end
result << work if work.length.nonzero?
result.join("\n").gsub(/^/, " " * indent)
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/gem_path_searcher.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/gem_path_searcher.rb | ##
# GemPathSearcher has the capability to find loadable files inside
# gems. It generates data up front to speed up searches later.
class Gem::GemPathSearcher
##
# Initialise the data we need to make searches later.
def initialize
# We want a record of all the installed gemspecs, in the order we wish to
# examine them.
@gemspecs = init_gemspecs
# Map gem spec to glob of full require_path directories. Preparing this
# information may speed up searches later.
@lib_dirs = {}
@gemspecs.each do |spec|
@lib_dirs[spec.object_id] = lib_dirs_for spec
end
end
##
# Look in all the installed gems until a matching _path_ is found.
# Return the _gemspec_ of the gem where it was found. If no match
# is found, return nil.
#
# The gems are searched in alphabetical order, and in reverse
# version order.
#
# For example:
#
# find('log4r') # -> (log4r-1.1 spec)
# find('log4r.rb') # -> (log4r-1.1 spec)
# find('rake/rdoctask') # -> (rake-0.4.12 spec)
# find('foobarbaz') # -> nil
#
# Matching paths can have various suffixes ('.rb', '.so', and
# others), which may or may not already be attached to _file_.
# This method doesn't care about the full filename that matches;
# only that there is a match.
def find(path)
@gemspecs.find do |spec| matching_file? spec, path end
end
##
# Works like #find, but finds all gemspecs matching +path+.
def find_all(path)
@gemspecs.select do |spec|
matching_file? spec, path
end
end
##
# Attempts to find a matching path using the require_paths of the given
# +spec+.
def matching_file?(spec, path)
!matching_files(spec, path).empty?
end
##
# Returns files matching +path+ in +spec+.
#--
# Some of the intermediate results are cached in @lib_dirs for speed.
def matching_files(spec, path)
return [] unless @lib_dirs[spec.object_id] # case no paths
glob = File.join @lib_dirs[spec.object_id], "#{path}#{Gem.suffix_pattern}"
Dir[glob].select { |f| File.file? f.untaint }
end
##
# Return a list of all installed gemspecs, sorted by alphabetical order and
# in reverse version order. (bar-2, bar-1, foo-2)
def init_gemspecs
specs = Gem.source_index.map { |_, spec| spec }
specs.sort { |a, b|
names = a.name <=> b.name
next names if names.nonzero?
b.version <=> a.version
}
end
##
# Returns library directories glob for a gemspec. For example,
# '/usr/local/lib/ruby/gems/1.8/gems/foobar-1.0/{lib,ext}'
def lib_dirs_for(spec)
"#{spec.full_gem_path}/{#{spec.require_paths.join(',')}}" if
spec.require_paths
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/old_format.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/old_format.rb | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'rubygems'
require 'fileutils'
require 'yaml'
require 'zlib'
##
# The format class knows the guts of the RubyGem .gem file format and provides
# the capability to read gem files
class Gem::OldFormat
attr_accessor :spec, :file_entries, :gem_path
##
# Constructs an instance of a Format object, representing the gem's data
# structure.
#
# gem:: [String] The file name of the gem
def initialize(gem_path)
@gem_path = gem_path
end
##
# Reads the named gem file and returns a Format object, representing the
# data from the gem file
#
# file_path:: [String] Path to the gem file
def self.from_file_by_path(file_path)
unless File.exist?(file_path)
raise Gem::Exception, "Cannot load gem file [#{file_path}]"
end
File.open(file_path, 'rb') do |file|
from_io(file, file_path)
end
end
##
# Reads a gem from an io stream and returns a Format object, representing
# the data from the gem file
#
# io:: [IO] Stream from which to read the gem
def self.from_io(io, gem_path="(io)")
format = self.new(gem_path)
skip_ruby(io)
format.spec = read_spec(io)
format.file_entries = []
read_files_from_gem(io) do |entry, file_data|
format.file_entries << [entry, file_data]
end
format
end
private
##
# Skips the Ruby self-install header. After calling this method, the
# IO index will be set after the Ruby code.
#
# file:: [IO] The IO to process (skip the Ruby code)
def self.skip_ruby(file)
end_seen = false
loop {
line = file.gets
if(line == nil || line.chomp == "__END__") then
end_seen = true
break
end
}
if end_seen == false then
raise Gem::Exception.new("Failed to find end of ruby script while reading gem")
end
end
##
# Reads the specification YAML from the supplied IO and constructs
# a Gem::Specification from it. After calling this method, the
# IO index will be set after the specification header.
#
# file:: [IO] The IO to process
def self.read_spec(file)
yaml = ''
read_until_dashes file do |line|
yaml << line
end
Gem::Specification.from_yaml yaml
rescue YAML::Error => e
raise Gem::Exception, "Failed to parse gem specification out of gem file"
rescue ArgumentError => e
raise Gem::Exception, "Failed to parse gem specification out of gem file"
end
##
# Reads lines from the supplied IO until a end-of-yaml (---) is
# reached
#
# file:: [IO] The IO to process
# block:: [String] The read line
def self.read_until_dashes(file)
while((line = file.gets) && line.chomp.strip != "---") do
yield line
end
end
##
# Reads the embedded file data from a gem file, yielding an entry
# containing metadata about the file and the file contents themselves
# for each file that's archived in the gem.
# NOTE: Many of these methods should be extracted into some kind of
# Gem file read/writer
#
# gem_file:: [IO] The IO to process
def self.read_files_from_gem(gem_file)
errstr = "Error reading files from gem"
header_yaml = ''
begin
self.read_until_dashes(gem_file) do |line|
header_yaml << line
end
header = YAML.load(header_yaml)
raise Gem::Exception, errstr unless header
header.each do |entry|
file_data = ''
self.read_until_dashes(gem_file) do |line|
file_data << line
end
yield [entry, Zlib::Inflate.inflate(file_data.strip.unpack("m")[0])]
end
rescue Zlib::DataError => e
raise Gem::Exception, errstr
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/rubygems_version.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/rubygems_version.rb | #--
# DO NOT EDIT
# This file is auto-generated by build scripts.
# See: rake update_version
#++
module Gem
##
# The version of RubyGems you are using
RubyGemsVersion = '1.3.3'
##
# The version of RubyGems you are using (duplicated for familiarity)
VERSION = RubyGemsVersion
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/source_info_cache_entry.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/source_info_cache_entry.rb | require 'rubygems'
require 'rubygems/source_index'
require 'rubygems/remote_fetcher'
##
# Entries held by a SourceInfoCache.
class Gem::SourceInfoCacheEntry
##
# The source index for this cache entry.
attr_reader :source_index
##
# The size of the source entry. Used to determine if the source index has
# changed.
attr_reader :size
##
# Create a cache entry.
def initialize(si, size)
@source_index = si || Gem::SourceIndex.new({})
@size = size
@all = false
end
def refresh(source_uri, all)
begin
marshal_uri = URI.join source_uri.to_s, "Marshal.#{Gem.marshal_version}"
remote_size = Gem::RemoteFetcher.fetcher.fetch_size marshal_uri
rescue Gem::RemoteSourceException
yaml_uri = URI.join source_uri.to_s, 'yaml'
remote_size = Gem::RemoteFetcher.fetcher.fetch_size yaml_uri
end
# TODO Use index_signature instead of size?
return false if @size == remote_size and @all
updated = @source_index.update source_uri, all
@size = remote_size
@all = all
updated
end
def ==(other) # :nodoc:
self.class === other and
@size == other.size and
@source_index == other.source_index
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/install_update_options.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/install_update_options.rb | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'rubygems'
require 'rubygems/security'
##
# Mixin methods for install and update options for Gem::Commands
module Gem::InstallUpdateOptions
##
# Add the install/update options to the option parser.
def add_install_update_options
OptionParser.accept Gem::Security::Policy do |value|
value = Gem::Security::Policies[value]
raise OptionParser::InvalidArgument, value if value.nil?
value
end
add_option(:"Install/Update", '-i', '--install-dir DIR',
'Gem repository directory to get installed',
'gems') do |value, options|
options[:install_dir] = File.expand_path(value)
end
add_option(:"Install/Update", '-n', '--bindir DIR',
'Directory where binary files are',
'located') do |value, options|
options[:bin_dir] = File.expand_path(value)
end
add_option(:"Install/Update", '-d', '--[no-]rdoc',
'Generate RDoc documentation for the gem on',
'install') do |value, options|
options[:generate_rdoc] = value
end
add_option(:"Install/Update", '--[no-]ri',
'Generate RI documentation for the gem on',
'install') do |value, options|
options[:generate_ri] = value
end
add_option(:"Install/Update", '-E', '--[no-]env-shebang',
"Rewrite the shebang line on installed",
"scripts to use /usr/bin/env") do |value, options|
options[:env_shebang] = value
end
add_option(:"Install/Update", '-f', '--[no-]force',
'Force gem to install, bypassing dependency',
'checks') do |value, options|
options[:force] = value
end
add_option(:"Install/Update", '-t', '--[no-]test',
'Run unit tests prior to installation') do |value, options|
options[:test] = value
end
add_option(:"Install/Update", '-w', '--[no-]wrappers',
'Use bin wrappers for executables',
'Not available on dosish platforms') do |value, options|
options[:wrappers] = value
end
add_option(:"Install/Update", '-P', '--trust-policy POLICY',
Gem::Security::Policy,
'Specify gem trust policy') do |value, options|
options[:security_policy] = value
end
add_option(:"Install/Update", '--ignore-dependencies',
'Do not install any required dependent gems') do |value, options|
options[:ignore_dependencies] = value
end
add_option(:"Install/Update", '-y', '--include-dependencies',
'Unconditionally install the required',
'dependent gems') do |value, options|
options[:include_dependencies] = value
end
add_option(:"Install/Update", '--[no-]format-executable',
'Make installed executable names match ruby.',
'If ruby is ruby18, foo_exec will be',
'foo_exec18') do |value, options|
options[:format_executable] = value
end
add_option(:"Install/Update", '--[no-]user-install',
'Install in user\'s home directory instead',
'of GEM_HOME.') do |value, options|
options[:user_install] = value
end
add_option(:"Install/Update", "--development",
"Install any additional development",
"dependencies") do |value, options|
options[:development] = true
end
end
##
# Default options for the gem install command.
def install_update_defaults_str
'--rdoc --no-force --no-test --wrappers'
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/gemcutter_utilities.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/gemcutter_utilities.rb | require 'net/http'
require 'rubygems/remote_fetcher'
module Gem::GemcutterUtilities
def sign_in
return if Gem.configuration.rubygems_api_key
say "Enter your RubyGems.org credentials."
say "Don't have an account yet? Create one at http://rubygems.org/sign_up"
email = ask " Email: "
password = ask_for_password "Password: "
say "\n"
response = rubygems_api_request :get, "api/v1/api_key" do |request|
request.basic_auth email, password
end
with_response response do |resp|
say "Signed in."
Gem.configuration.rubygems_api_key = resp.body
end
end
def rubygems_api_request(method, path, &block)
host = ENV['RUBYGEMS_HOST'] || 'https://rubygems.org'
uri = URI.parse "#{host}/#{path}"
request_method = Net::HTTP.const_get method.to_s.capitalize
Gem::RemoteFetcher.fetcher.request(uri, request_method, &block)
end
def with_response(resp)
case resp
when Net::HTTPSuccess then
if block_given? then
yield resp
else
say resp.body
end
else
say resp.body
terminate_interaction 1
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/remote_fetcher.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/remote_fetcher.rb | require 'net/http'
require 'stringio'
require 'time'
require 'uri'
require 'rubygems'
##
# RemoteFetcher handles the details of fetching gems and gem information from
# a remote source.
class Gem::RemoteFetcher
include Gem::UserInteraction
##
# A FetchError exception wraps up the various possible IO and HTTP failures
# that could happen while downloading from the internet.
class FetchError < Gem::Exception
##
# The URI which was being accessed when the exception happened.
attr_accessor :uri
def initialize(message, uri)
super message
@uri = uri
end
def to_s # :nodoc:
"#{super} (#{uri})"
end
end
@fetcher = nil
##
# Cached RemoteFetcher instance.
def self.fetcher
@fetcher ||= self.new Gem.configuration[:http_proxy]
end
##
# Initialize a remote fetcher using the source URI and possible proxy
# information.
#
# +proxy+
# * [String]: explicit specification of proxy; overrides any environment
# variable setting
# * nil: respect environment variables (HTTP_PROXY, HTTP_PROXY_USER,
# HTTP_PROXY_PASS)
# * <tt>:no_proxy</tt>: ignore environment variables and _don't_ use a proxy
def initialize(proxy = nil)
Socket.do_not_reverse_lookup = true
@connections = {}
@requests = Hash.new 0
@proxy_uri =
case proxy
when :no_proxy then nil
when nil then get_proxy_from_env
when URI::HTTP then proxy
else URI.parse(proxy)
end
end
##
# Moves the gem +spec+ from +source_uri+ to the cache dir unless it is
# already there. If the source_uri is local the gem cache dir copy is
# always replaced.
def download(spec, source_uri, install_dir = Gem.dir)
if File.writable?(install_dir)
cache_dir = File.join install_dir, 'cache'
else
cache_dir = File.join(Gem.user_dir, 'cache')
end
gem_file_name = spec.file_name
local_gem_path = File.join cache_dir, gem_file_name
FileUtils.mkdir_p cache_dir rescue nil unless File.exist? cache_dir
# Always escape URI's to deal with potential spaces and such
unless URI::Generic === source_uri
source_uri = URI.parse(URI.escape(source_uri))
end
scheme = source_uri.scheme
# URI.parse gets confused by MS Windows paths with forward slashes.
scheme = nil if scheme =~ /^[a-z]$/i
case scheme
when 'http', 'https' then
unless File.exist? local_gem_path then
begin
say "Downloading gem #{gem_file_name}" if
Gem.configuration.really_verbose
remote_gem_path = source_uri + "gems/#{gem_file_name}"
gem = self.fetch_path remote_gem_path
rescue Gem::RemoteFetcher::FetchError
raise if spec.original_platform == spec.platform
alternate_name = "#{spec.original_name}.gem"
say "Failed, downloading gem #{alternate_name}" if
Gem.configuration.really_verbose
remote_gem_path = source_uri + "gems/#{alternate_name}"
gem = self.fetch_path remote_gem_path
end
File.open local_gem_path, 'wb' do |fp|
fp.write gem
end
end
when 'file' then
begin
path = source_uri.path
path = File.dirname(path) if File.extname(path) == '.gem'
remote_gem_path = File.join(path, 'gems', gem_file_name)
FileUtils.cp(remote_gem_path, local_gem_path)
rescue Errno::EACCES
local_gem_path = source_uri.to_s
end
say "Using local gem #{local_gem_path}" if
Gem.configuration.really_verbose
when nil then # TODO test for local overriding cache
source_path = if Gem.win_platform? && source_uri.scheme &&
!source_uri.path.include?(':') then
"#{source_uri.scheme}:#{source_uri.path}"
else
source_uri.path
end
source_path = URI.unescape source_path
begin
FileUtils.cp source_path, local_gem_path unless
File.expand_path(source_path) == File.expand_path(local_gem_path)
rescue Errno::EACCES
local_gem_path = source_uri.to_s
end
say "Using local gem #{local_gem_path}" if
Gem.configuration.really_verbose
else
raise Gem::InstallError, "unsupported URI scheme #{source_uri.scheme}"
end
local_gem_path
end
##
# Downloads +uri+ and returns it as a String.
def fetch_path(uri, mtime = nil, head = false)
data = open_uri_or_path uri, mtime, head
data = Gem.gunzip data if data and not head and uri.to_s =~ /gz$/
data
rescue FetchError
raise
rescue Timeout::Error
raise FetchError.new('timed out', uri)
rescue IOError, SocketError, SystemCallError => e
raise FetchError.new("#{e.class}: #{e}", uri)
end
##
# Returns the size of +uri+ in bytes.
def fetch_size(uri) # TODO: phase this out
response = fetch_path(uri, nil, true)
response['content-length'].to_i
end
def escape(str)
return unless str
URI.escape(str)
end
def unescape(str)
return unless str
URI.unescape(str)
end
##
# Returns an HTTP proxy URI if one is set in the environment variables.
def get_proxy_from_env
env_proxy = ENV['http_proxy'] || ENV['HTTP_PROXY']
return nil if env_proxy.nil? or env_proxy.empty?
uri = URI.parse(normalize_uri(env_proxy))
if uri and uri.user.nil? and uri.password.nil? then
# Probably we have http_proxy_* variables?
uri.user = escape(ENV['http_proxy_user'] || ENV['HTTP_PROXY_USER'])
uri.password = escape(ENV['http_proxy_pass'] || ENV['HTTP_PROXY_PASS'])
end
uri
end
##
# Normalize the URI by adding "http://" if it is missing.
def normalize_uri(uri)
(uri =~ /^(https?|ftp|file):/) ? uri : "http://#{uri}"
end
##
# Creates or an HTTP connection based on +uri+, or retrieves an existing
# connection, using a proxy if needed.
def connection_for(uri)
net_http_args = [uri.host, uri.port]
if @proxy_uri then
net_http_args += [
@proxy_uri.host,
@proxy_uri.port,
@proxy_uri.user,
@proxy_uri.password
]
end
connection_id = net_http_args.join ':'
@connections[connection_id] ||= Net::HTTP.new(*net_http_args)
connection = @connections[connection_id]
if uri.scheme == 'https' and not connection.started? then
require 'net/https'
connection.use_ssl = true
connection.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
connection.start unless connection.started?
connection
end
##
# Read the data from the (source based) URI, but if it is a file:// URI,
# read from the filesystem instead.
def open_uri_or_path(uri, last_modified = nil, head = false, depth = 0)
raise "block is dead" if block_given?
uri = URI.parse uri unless URI::Generic === uri
# This check is redundant unless Gem::RemoteFetcher is likely
# to be used directly, since the scheme is checked elsewhere.
# - Daniel Berger
unless ['http', 'https', 'file'].include?(uri.scheme)
raise ArgumentError, 'uri scheme is invalid'
end
if uri.scheme == 'file'
path = uri.path
# Deal with leading slash on Windows paths
if path[0].chr == '/' && path[1].chr =~ /[a-zA-Z]/ && path[2].chr == ':'
path = path[1..-1]
end
return Gem.read_binary(path)
end
fetch_type = head ? Net::HTTP::Head : Net::HTTP::Get
response = request uri, fetch_type, last_modified
case response
when Net::HTTPOK, Net::HTTPNotModified then
head ? response : response.body
when Net::HTTPMovedPermanently, Net::HTTPFound, Net::HTTPSeeOther,
Net::HTTPTemporaryRedirect then
raise FetchError.new('too many redirects', uri) if depth > 10
open_uri_or_path(response['Location'], last_modified, head, depth + 1)
else
raise FetchError.new("bad response #{response.message} #{response.code}", uri)
end
end
##
# Performs a Net::HTTP request of type +request_class+ on +uri+ returning
# a Net::HTTP response object. request maintains a table of persistent
# connections to reduce connect overhead.
def request(uri, request_class, last_modified = nil)
request = request_class.new uri.request_uri
unless uri.nil? || uri.user.nil? || uri.user.empty? then
request.basic_auth uri.user, uri.password
end
ua = "RubyGems/#{Gem::RubyGemsVersion} #{Gem::Platform.local}"
ua << " Ruby/#{RUBY_VERSION} (#{RUBY_RELEASE_DATE}"
ua << " patchlevel #{RUBY_PATCHLEVEL}" if defined? RUBY_PATCHLEVEL
ua << ")"
request.add_field 'User-Agent', ua
request.add_field 'Connection', 'keep-alive'
request.add_field 'Keep-Alive', '30'
if last_modified then
last_modified = last_modified.utc
request.add_field 'If-Modified-Since', last_modified.rfc2822
end
yield request if block_given?
connection = connection_for uri
retried = false
bad_response = false
begin
@requests[connection.object_id] += 1
say "#{request.method} #{uri}" if
Gem.configuration.really_verbose
response = connection.request request
say "#{response.code} #{response.message}" if
Gem.configuration.really_verbose
rescue Net::HTTPBadResponse
say "bad response" if Gem.configuration.really_verbose
reset connection
raise FetchError.new('too many bad responses', uri) if bad_response
bad_response = true
retry
# HACK work around EOFError bug in Net::HTTP
# NOTE Errno::ECONNABORTED raised a lot on Windows, and make impossible
# to install gems.
rescue EOFError, Errno::ECONNABORTED, Errno::ECONNRESET, Errno::EPIPE
requests = @requests[connection.object_id]
say "connection reset after #{requests} requests, retrying" if
Gem.configuration.really_verbose
raise FetchError.new('too many connection resets', uri) if retried
reset connection
retried = true
retry
end
response
end
##
# Resets HTTP connection +connection+.
def reset(connection)
@requests.delete connection.object_id
connection.finish
connection.start
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/source_index.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/source_index.rb | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'rubygems/user_interaction'
require 'rubygems/specification'
# :stopdoc:
module Gem
autoload :SpecFetcher, 'rubygems/spec_fetcher'
end
# :startdoc:
##
# The SourceIndex object indexes all the gems available from a
# particular source (e.g. a list of gem directories, or a remote
# source). A SourceIndex maps a gem full name to a gem
# specification.
#
# NOTE:: The class used to be named Cache, but that became
# confusing when cached source fetchers where introduced. The
# constant Gem::Cache is an alias for this class to allow old
# YAMLized source index objects to load properly.
class Gem::SourceIndex
include Enumerable
include Gem::UserInteraction
attr_reader :gems # :nodoc:
##
# Directories to use to refresh this SourceIndex when calling refresh!
attr_accessor :spec_dirs
class << self
include Gem::UserInteraction
##
# Factory method to construct a source index instance for a given
# path.
#
# deprecated::
# If supplied, from_installed_gems will act just like
# +from_gems_in+. This argument is deprecated and is provided
# just for backwards compatibility, and should not generally
# be used.
#
# return::
# SourceIndex instance
def from_installed_gems(*deprecated)
if deprecated.empty?
from_gems_in(*installed_spec_directories)
else
from_gems_in(*deprecated) # HACK warn
end
end
##
# Returns a list of directories from Gem.path that contain specifications.
def installed_spec_directories
Gem.path.collect { |dir| File.join(dir, "specifications") }
end
##
# Creates a new SourceIndex from the ruby format gem specifications in
# +spec_dirs+.
def from_gems_in(*spec_dirs)
source_index = new
source_index.spec_dirs = spec_dirs
source_index.refresh!
end
##
# Loads a ruby-format specification from +file_name+ and returns the
# loaded spec.
def load_specification(file_name)
return nil unless file_name and File.exist? file_name
spec_code = if RUBY_VERSION < '1.9' then
File.read file_name
else
File.read file_name, :encoding => 'UTF-8'
end.untaint
begin
gemspec = eval spec_code, binding, file_name
if gemspec.is_a?(Gem::Specification)
gemspec.loaded_from = file_name
return gemspec
end
alert_warning "File '#{file_name}' does not evaluate to a gem specification"
rescue SignalException, SystemExit
raise
rescue SyntaxError => e
alert_warning e
alert_warning spec_code
rescue Exception => e
alert_warning "#{e.inspect}\n#{spec_code}"
alert_warning "Invalid .gemspec format in '#{file_name}'"
end
return nil
end
end
##
# Constructs a source index instance from the provided specifications, which
# is a Hash of gem full names and Gem::Specifications.
#--
# TODO merge @gems and @prerelease_gems and provide a separate method
# #prerelease_gems
def initialize(specifications={})
@gems = {}
specifications.each{ |full_name, spec| add_spec spec }
@spec_dirs = nil
end
# TODO: remove method
def all_gems
@gems
end
def prerelease_gems
@gems.reject{ |name, gem| !gem.version.prerelease? }
end
def released_gems
@gems.reject{ |name, gem| gem.version.prerelease? }
end
##
# Reconstruct the source index from the specifications in +spec_dirs+.
def load_gems_in(*spec_dirs)
@gems.clear
spec_dirs.reverse_each do |spec_dir|
spec_files = Dir.glob File.join(spec_dir, '*.gemspec')
spec_files.each do |spec_file|
gemspec = self.class.load_specification spec_file.untaint
add_spec gemspec if gemspec
end
end
self
end
##
# Returns an Array specifications for the latest released versions
# of each gem in this index.
def latest_specs
result = Hash.new { |h,k| h[k] = [] }
latest = {}
sort.each do |_, spec|
name = spec.name
curr_ver = spec.version
prev_ver = latest.key?(name) ? latest[name].version : nil
next if curr_ver.prerelease?
next unless prev_ver.nil? or curr_ver >= prev_ver or
latest[name].platform != Gem::Platform::RUBY
if prev_ver.nil? or
(curr_ver > prev_ver and spec.platform == Gem::Platform::RUBY) then
result[name].clear
latest[name] = spec
end
if spec.platform != Gem::Platform::RUBY then
result[name].delete_if do |result_spec|
result_spec.platform == spec.platform
end
end
result[name] << spec
end
# TODO: why is this a hash while @gems is an array? Seems like
# structural similarity would be good.
result.values.flatten
end
##
# An array including only the prerelease gemspecs
def prerelease_specs
prerelease_gems.values
end
##
# An array including only the released gemspecs
def released_specs
released_gems.values
end
##
# Add a gem specification to the source index.
def add_spec(gem_spec, name = gem_spec.full_name)
# No idea why, but the Indexer wants to insert them using original_name
# instead of full_name. So we make it an optional arg.
@gems[name] = gem_spec
end
##
# Add gem specifications to the source index.
def add_specs(*gem_specs)
gem_specs.each do |spec|
add_spec spec
end
end
##
# Remove a gem specification named +full_name+.
def remove_spec(full_name)
@gems.delete full_name
end
##
# Iterate over the specifications in the source index.
def each(&block) # :yields: gem.full_name, gem
@gems.each(&block)
end
##
# The gem specification given a full gem spec name.
def specification(full_name)
@gems[full_name]
end
##
# The signature for the source index. Changes in the signature indicate a
# change in the index.
def index_signature
require 'digest'
Digest::SHA256.new.hexdigest(@gems.keys.sort.join(',')).to_s
end
##
# The signature for the given gem specification.
def gem_signature(gem_full_name)
require 'digest'
Digest::SHA256.new.hexdigest(@gems[gem_full_name].to_yaml).to_s
end
def size
@gems.size
end
alias length size
##
# Find a gem by an exact match on the short name.
def find_name(gem_name, version_requirement = Gem::Requirement.default)
dep = Gem::Dependency.new gem_name, version_requirement
search dep
end
##
# Search for a gem by Gem::Dependency +gem_pattern+. If +only_platform+
# is true, only gems matching Gem::Platform.local will be returned. An
# Array of matching Gem::Specification objects is returned.
#
# For backwards compatibility, a String or Regexp pattern may be passed as
# +gem_pattern+, and a Gem::Requirement for +platform_only+. This
# behavior is deprecated and will be removed.
def search(gem_pattern, platform_only = false)
version_requirement = nil
only_platform = false
# TODO - Remove support and warning for legacy arguments after 2008/11
unless Gem::Dependency === gem_pattern
warn "#{Gem.location_of_caller.join ':'}:Warning: Gem::SourceIndex#search support for #{gem_pattern.class} patterns is deprecated, use #find_name"
end
case gem_pattern
when Regexp then
version_requirement = platform_only || Gem::Requirement.default
when Gem::Dependency then
only_platform = platform_only
version_requirement = gem_pattern.requirement
gem_pattern = if Regexp === gem_pattern.name then
gem_pattern.name
elsif gem_pattern.name.empty? then
//
else
/^#{Regexp.escape gem_pattern.name}$/
end
else
version_requirement = platform_only || Gem::Requirement.default
gem_pattern = /#{gem_pattern}/i
end
unless Gem::Requirement === version_requirement then
version_requirement = Gem::Requirement.create version_requirement
end
specs = all_gems.values.select do |spec|
spec.name =~ gem_pattern and
version_requirement.satisfied_by? spec.version
end
if only_platform then
specs = specs.select do |spec|
Gem::Platform.match spec.platform
end
end
specs.sort_by { |s| s.sort_obj }
end
##
# Replaces the gems in the source index from specifications in the
# directories this source index was created from. Raises an exception if
# this source index wasn't created from a directory (via from_gems_in or
# from_installed_gems, or having spec_dirs set).
def refresh!
raise 'source index not created from disk' if @spec_dirs.nil?
load_gems_in(*@spec_dirs)
end
##
# Returns an Array of Gem::Specifications that are not up to date.
def outdated
outdateds = []
latest_specs.each do |local|
dependency = Gem::Dependency.new local.name, ">= #{local.version}"
begin
fetcher = Gem::SpecFetcher.fetcher
remotes = fetcher.find_matching dependency
remotes = remotes.map { |(name, version,_),_| version }
rescue Gem::RemoteFetcher::FetchError => e
raise unless fetcher.warn_legacy e do
require 'rubygems/source_info_cache'
specs = Gem::SourceInfoCache.search_with_source dependency, true
remotes = specs.map { |spec,| spec.version }
end
end
latest = remotes.sort.last
outdateds << local.name if latest and local.version < latest
end
outdateds
end
##
# Updates this SourceIndex from +source_uri+. If +all+ is false, only the
# latest gems are fetched.
def update(source_uri, all)
source_uri = URI.parse source_uri unless URI::Generic === source_uri
source_uri.path += '/' unless source_uri.path =~ /\/$/
use_incremental = false
begin
gem_names = fetch_quick_index source_uri, all
remove_extra gem_names
missing_gems = find_missing gem_names
return false if missing_gems.size.zero?
say "Missing metadata for #{missing_gems.size} gems" if
missing_gems.size > 0 and Gem.configuration.really_verbose
use_incremental = missing_gems.size <= Gem.configuration.bulk_threshold
rescue Gem::OperationNotSupportedError => ex
alert_error "Falling back to bulk fetch: #{ex.message}" if
Gem.configuration.really_verbose
use_incremental = false
end
if use_incremental then
update_with_missing(source_uri, missing_gems)
else
new_index = fetch_bulk_index(source_uri)
@gems.replace(new_index.gems)
end
true
end
def ==(other) # :nodoc:
self.class === other and @gems == other.gems
end
def dump
Marshal.dump(self)
end
private
def fetcher
require 'rubygems/remote_fetcher'
Gem::RemoteFetcher.fetcher
end
def fetch_index_from(source_uri)
@fetch_error = nil
indexes = %W[
Marshal.#{Gem.marshal_version}.Z
Marshal.#{Gem.marshal_version}
yaml.Z
yaml
]
indexes.each do |name|
spec_data = nil
index = source_uri + name
begin
spec_data = fetcher.fetch_path index
spec_data = unzip(spec_data) if name =~ /\.Z$/
if name =~ /Marshal/ then
return Marshal.load(spec_data)
else
return YAML.load(spec_data)
end
rescue => e
if Gem.configuration.really_verbose then
alert_error "Unable to fetch #{name}: #{e.message}"
end
@fetch_error = e
end
end
nil
end
def fetch_bulk_index(source_uri)
say "Bulk updating Gem source index for: #{source_uri}" if
Gem.configuration.verbose
index = fetch_index_from(source_uri)
if index.nil? then
raise Gem::RemoteSourceException,
"Error fetching remote gem cache: #{@fetch_error}"
end
@fetch_error = nil
index
end
##
# Get the quick index needed for incremental updates.
def fetch_quick_index(source_uri, all)
index = all ? 'index' : 'latest_index'
zipped_index = fetcher.fetch_path source_uri + "quick/#{index}.rz"
unzip(zipped_index).split("\n")
rescue ::Exception => e
unless all then
say "Latest index not found, using quick index" if
Gem.configuration.really_verbose
fetch_quick_index source_uri, true
else
raise Gem::OperationNotSupportedError,
"No quick index found: #{e.message}"
end
end
##
# Make a list of full names for all the missing gemspecs.
def find_missing(spec_names)
unless defined? @originals then
@originals = {}
each do |full_name, spec|
@originals[spec.original_name] = spec
end
end
spec_names.find_all { |full_name|
@originals[full_name].nil?
}
end
def remove_extra(spec_names)
dictionary = spec_names.inject({}) { |h, k| h[k] = true; h }
each do |name, spec|
remove_spec name unless dictionary.include? spec.original_name
end
end
##
# Unzip the given string.
def unzip(string)
require 'zlib'
Gem.inflate string
end
##
# Tries to fetch Marshal representation first, then YAML
def fetch_single_spec(source_uri, spec_name)
@fetch_error = nil
begin
marshal_uri = source_uri + "quick/Marshal.#{Gem.marshal_version}/#{spec_name}.gemspec.rz"
zipped = fetcher.fetch_path marshal_uri
return Marshal.load(unzip(zipped))
rescue => ex
@fetch_error = ex
if Gem.configuration.really_verbose then
say "unable to fetch marshal gemspec #{marshal_uri}: #{ex.class} - #{ex}"
end
end
begin
yaml_uri = source_uri + "quick/#{spec_name}.gemspec.rz"
zipped = fetcher.fetch_path yaml_uri
return YAML.load(unzip(zipped))
rescue => ex
@fetch_error = ex
if Gem.configuration.really_verbose then
say "unable to fetch YAML gemspec #{yaml_uri}: #{ex.class} - #{ex}"
end
end
nil
end
##
# Update the cached source index with the missing names.
def update_with_missing(source_uri, missing_names)
progress = ui.progress_reporter(missing_names.size,
"Updating metadata for #{missing_names.size} gems from #{source_uri}")
missing_names.each do |spec_name|
gemspec = fetch_single_spec(source_uri, spec_name)
if gemspec.nil? then
ui.say "Failed to download spec #{spec_name} from #{source_uri}:\n" \
"\t#{@fetch_error.message}"
else
add_spec gemspec
progress.updated spec_name
end
@fetch_error = nil
end
progress.done
progress.count
end
end
# :stopdoc:
module Gem
##
# Cache is an alias for SourceIndex to allow older YAMLized source index
# objects to load properly.
Cache = SourceIndex
end
# :startdoc:
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/package_task.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/package_task.rb | # Copyright (c) 2003, 2004 Jim Weirich, 2009 Eric Hodel
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'rubygems'
begin
gem 'rake'
rescue Gem::LoadError
end
require 'rake/packagetask'
##
# Create a package based upon a Gem::Specification. Gem packages, as well as
# zip files and tar/gzipped packages can be produced by this task.
#
# In addition to the Rake targets generated by Rake::PackageTask, a
# Gem::PackageTask will also generate the following tasks:
#
# [<b>"<em>package_dir</em>/<em>name</em>-<em>version</em>.gem"</b>]
# Create a RubyGems package with the given name and version.
#
# Example using a Gem::Specification:
#
# require 'rubygems'
# require 'rubygems/package_task'
#
# spec = Gem::Specification.new do |s|
# s.platform = Gem::Platform::RUBY
# s.summary = "Ruby based make-like utility."
# s.name = 'rake'
# s.version = PKG_VERSION
# s.requirements << 'none'
# s.require_path = 'lib'
# s.autorequire = 'rake'
# s.files = PKG_FILES
# s.description = <<-EOF
# Rake is a Make-like program implemented in Ruby. Tasks
# and dependencies are specified in standard Ruby syntax.
# EOF
# end
#
# Gem::PackageTask.new(spec) do |pkg|
# pkg.need_zip = true
# pkg.need_tar = true
# end
class Gem::PackageTask < Rake::PackageTask
##
# Ruby Gem::Specification containing the metadata for this package. The
# name, version and package_files are automatically determined from the
# gemspec and don't need to be explicitly provided.
attr_accessor :gem_spec
##
# Create a Gem Package task library. Automatically define the gem if a
# block is given. If no block is supplied, then #define needs to be called
# to define the task.
def initialize(gem_spec)
init gem_spec
yield self if block_given?
define if block_given?
end
##
# Initialization tasks without the "yield self" or define operations.
def init(gem)
super gem.name, gem.version
@gem_spec = gem
@package_files += gem_spec.files if gem_spec.files
end
##
# Create the Rake tasks and actions specified by this Gem::PackageTask.
# (+define+ is automatically called if a block is given to +new+).
def define
super
task :package => [:gem]
gem_file = gem_spec.file_name
gem_path = File.join package_dir, gem_file
desc "Build the gem file #{gem_file}"
task :gem => [gem_path]
trace = Rake.application.options.trace
Gem.configuration.verbose = trace
file gem_path => [package_dir] + @gem_spec.files do
when_writing "Creating #{gem_spec.file_name}" do
Gem::Builder.new(gem_spec).build
verbose trace do
mv gem_file, gem_path
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/require_paths_builder.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/require_paths_builder.rb | require 'rubygems'
module Gem::RequirePathsBuilder
def write_require_paths_file_if_needed(spec = @spec, gem_home = @gem_home)
return if spec.require_paths == ["lib"] &&
(spec.bindir.nil? || spec.bindir == "bin")
file_name = File.join(gem_home, 'gems', "#{@spec.full_name}", ".require_paths")
file_name.untaint
File.open(file_name, "w") do |file|
spec.require_paths.each do |path|
file.puts path
end
file.puts spec.bindir if spec.bindir
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/specification.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/specification.rb | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'rubygems/version'
require 'rubygems/requirement'
require 'rubygems/platform'
# :stopdoc:
class Date; end # for ruby_code if date.rb wasn't required
# :startdoc:
##
# The Specification class contains the metadata for a Gem. Typically
# defined in a .gemspec file or a Rakefile, and looks like this:
#
# spec = Gem::Specification.new do |s|
# s.name = 'example'
# s.version = '1.0'
# s.summary = 'Example gem specification'
# ...
# end
#
# For a great way to package gems, use Hoe.
class Gem::Specification
##
# Allows deinstallation of gems with legacy platforms.
attr_accessor :original_platform # :nodoc:
##
# The the version number of a specification that does not specify one
# (i.e. RubyGems 0.7 or earlier).
NONEXISTENT_SPECIFICATION_VERSION = -1
##
# The specification version applied to any new Specification instances
# created. This should be bumped whenever something in the spec format
# changes.
#--
# When updating this number, be sure to also update #to_ruby.
#
# NOTE RubyGems < 1.2 cannot load specification versions > 2.
CURRENT_SPECIFICATION_VERSION = 3
##
# An informal list of changes to the specification. The highest-valued
# key should be equal to the CURRENT_SPECIFICATION_VERSION.
SPECIFICATION_VERSION_HISTORY = {
-1 => ['(RubyGems versions up to and including 0.7 did not have versioned specifications)'],
1 => [
'Deprecated "test_suite_file" in favor of the new, but equivalent, "test_files"',
'"test_file=x" is a shortcut for "test_files=[x]"'
],
2 => [
'Added "required_rubygems_version"',
'Now forward-compatible with future versions',
],
3 => [
'Added Fixnum validation to the specification_version'
]
}
# :stopdoc:
MARSHAL_FIELDS = { -1 => 16, 1 => 16, 2 => 16, 3 => 17 }
now = Time.at(Time.now.to_i)
TODAY = now - ((now.to_i + now.gmt_offset) % 86400)
# :startdoc:
##
# Optional block used to gather newly defined instances.
@@gather = nil
##
# List of attribute names: [:name, :version, ...]
@@required_attributes = []
##
# List of _all_ attributes and default values:
#
# [[:name, nil],
# [:bindir, 'bin'],
# ...]
@@attributes = []
@@nil_attributes = []
@@non_nil_attributes = [:@original_platform]
##
# List of array attributes
@@array_attributes = []
##
# Map of attribute names to default values.
@@default_value = {}
##
# Names of all specification attributes
def self.attribute_names
@@attributes.map { |name, default| name }
end
##
# Default values for specification attributes
def self.attribute_defaults
@@attributes.dup
end
##
# The default value for specification attribute +name+
def self.default_value(name)
@@default_value[name]
end
##
# Required specification attributes
def self.required_attributes
@@required_attributes.dup
end
##
# Is +name+ a required attribute?
def self.required_attribute?(name)
@@required_attributes.include? name.to_sym
end
##
# Specification attributes that are arrays (appendable and so-forth)
def self.array_attributes
@@array_attributes.dup
end
##
# Specifies the +name+ and +default+ for a specification attribute, and
# creates a reader and writer method like Module#attr_accessor.
#
# The reader method returns the default if the value hasn't been set.
def self.attribute(name, default=nil)
ivar_name = "@#{name}".intern
if default.nil? then
@@nil_attributes << ivar_name
else
@@non_nil_attributes << [ivar_name, default]
end
@@attributes << [name, default]
@@default_value[name] = default
attr_accessor(name)
end
##
# Same as :attribute, but ensures that values assigned to the attribute
# are array values by applying :to_a to the value.
def self.array_attribute(name)
@@non_nil_attributes << ["@#{name}".intern, []]
@@array_attributes << name
@@attributes << [name, []]
@@default_value[name] = []
code = %{
def #{name}
@#{name} ||= []
end
def #{name}=(value)
@#{name} = Array(value)
end
}
module_eval code, __FILE__, __LINE__ - 9
end
##
# Same as attribute above, but also records this attribute as mandatory.
def self.required_attribute(*args)
@@required_attributes << args.first
attribute(*args)
end
##
# Sometimes we don't want the world to use a setter method for a
# particular attribute.
#
# +read_only+ makes it private so we can still use it internally.
def self.read_only(*names)
names.each do |name|
private "#{name}="
end
end
# Shortcut for creating several attributes at once (each with a default
# value of +nil+).
def self.attributes(*args)
args.each do |arg|
attribute(arg, nil)
end
end
##
# Some attributes require special behaviour when they are accessed. This
# allows for that.
def self.overwrite_accessor(name, &block)
remove_method name
define_method(name, &block)
end
##
# Defines a _singular_ version of an existing _plural_ attribute (i.e. one
# whose value is expected to be an array). This means just creating a
# helper method that takes a single value and appends it to the array.
# These are created for convenience, so that in a spec, one can write
#
# s.require_path = 'mylib'
#
# instead of:
#
# s.require_paths = ['mylib']
#
# That above convenience is available courtesy of:
#
# attribute_alias_singular :require_path, :require_paths
def self.attribute_alias_singular(singular, plural)
define_method("#{singular}=") { |val|
send("#{plural}=", [val])
}
define_method("#{singular}") {
val = send("#{plural}")
val.nil? ? nil : val.first
}
end
##
# Dump only crucial instance variables.
#--
# MAINTAIN ORDER!
def _dump(limit)
Marshal.dump [
@rubygems_version,
@specification_version,
@name,
@version,
(Time === @date ? @date : (require 'time'; Time.parse(@date.to_s))),
@summary,
@required_ruby_version,
@required_rubygems_version,
@original_platform,
@dependencies,
@rubyforge_project,
@email,
@authors,
@description,
@homepage,
@has_rdoc,
@new_platform,
@licenses
]
end
##
# Load custom marshal format, re-initializing defaults as needed
def self._load(str)
array = Marshal.load str
spec = Gem::Specification.new
spec.instance_variable_set :@specification_version, array[1]
current_version = CURRENT_SPECIFICATION_VERSION
field_count = if spec.specification_version > current_version then
spec.instance_variable_set :@specification_version,
current_version
MARSHAL_FIELDS[current_version]
else
MARSHAL_FIELDS[spec.specification_version]
end
if array.size < field_count then
raise TypeError, "invalid Gem::Specification format #{array.inspect}"
end
spec.instance_variable_set :@rubygems_version, array[0]
# spec version
spec.instance_variable_set :@name, array[2]
spec.instance_variable_set :@version, array[3]
spec.instance_variable_set :@date, array[4]
spec.instance_variable_set :@summary, array[5]
spec.instance_variable_set :@required_ruby_version, array[6]
spec.instance_variable_set :@required_rubygems_version, array[7]
spec.instance_variable_set :@original_platform, array[8]
spec.instance_variable_set :@dependencies, array[9]
spec.instance_variable_set :@rubyforge_project, array[10]
spec.instance_variable_set :@email, array[11]
spec.instance_variable_set :@authors, array[12]
spec.instance_variable_set :@description, array[13]
spec.instance_variable_set :@homepage, array[14]
spec.instance_variable_set :@has_rdoc, array[15]
spec.instance_variable_set :@new_platform, array[16]
spec.instance_variable_set :@platform, array[16].to_s
spec.instance_variable_set :@license, array[17]
spec.instance_variable_set :@loaded, false
spec
end
##
# List of depedencies that will automatically be activated at runtime.
def runtime_dependencies
dependencies.select { |d| d.type == :runtime || d.type == nil }
end
##
# List of dependencies that are used for development
def development_dependencies
dependencies.select { |d| d.type == :development }
end
def test_suite_file # :nodoc:
warn 'test_suite_file deprecated, use test_files'
test_files.first
end
def test_suite_file=(val) # :nodoc:
warn 'test_suite_file= deprecated, use test_files='
@test_files = [] unless defined? @test_files
@test_files << val
end
##
# true when this gemspec has been loaded from a specifications directory.
# This attribute is not persisted.
attr_accessor :loaded
##
# Path this gemspec was loaded from. This attribute is not persisted.
attr_accessor :loaded_from
##
# Returns an array with bindir attached to each executable in the
# executables list
def add_bindir(executables)
return nil if executables.nil?
if @bindir then
Array(executables).map { |e| File.join(@bindir, e) }
else
executables
end
rescue
return nil
end
##
# Files in the Gem under one of the require_paths
def lib_files
@files.select do |file|
require_paths.any? do |path|
file.index(path) == 0
end
end
end
##
# True if this gem was loaded from disk
alias :loaded? :loaded
##
# True if this gem has files in test_files
def has_unit_tests?
not test_files.empty?
end
# :stopdoc:
alias has_test_suite? has_unit_tests?
# :startdoc:
##
# Specification constructor. Assigns the default values to the
# attributes and yields itself for further
# initialization. Optionally takes +name+ and +version+.
def initialize name = nil, version = nil
@new_platform = nil
assign_defaults
@loaded = false
@loaded_from = nil
self.name = name if name
self.version = version if version
yield self if block_given?
@@gather.call(self) if @@gather
end
##
# Duplicates array_attributes from +other_spec+ so state isn't shared.
def initialize_copy(other_spec)
other_ivars = other_spec.instance_variables
other_ivars = other_ivars.map { |ivar| ivar.intern } if # for 1.9
other_ivars.any? { |ivar| String === ivar }
self.class.array_attributes.each do |name|
name = :"@#{name}"
next unless other_ivars.include? name
instance_variable_set name, other_spec.instance_variable_get(name).dup
end
end
##
# Each attribute has a default value (possibly nil). Here, we initialize
# all attributes to their default value. This is done through the
# accessor methods, so special behaviours will be honored. Furthermore,
# we take a _copy_ of the default so each specification instance has its
# own empty arrays, etc.
def assign_defaults
@@nil_attributes.each do |name|
instance_variable_set name, nil
end
@@non_nil_attributes.each do |name, default|
value = case default
when Time, Numeric, Symbol, true, false, nil then default
else default.dup
end
instance_variable_set name, value
end
# HACK
instance_variable_set :@new_platform, Gem::Platform::RUBY
end
##
# Special loader for YAML files. When a Specification object is loaded
# from a YAML file, it bypasses the normal Ruby object initialization
# routine (#initialize). This method makes up for that and deals with
# gems of different ages.
#
# 'input' can be anything that YAML.load() accepts: String or IO.
def self.from_yaml(input)
input = normalize_yaml_input input
spec = YAML.load input
if spec && spec.class == FalseClass then
raise Gem::EndOfYAMLException
end
unless Gem::Specification === spec then
raise Gem::Exception, "YAML data doesn't evaluate to gem specification"
end
unless (spec.instance_variables.include? '@specification_version' or
spec.instance_variables.include? :@specification_version) and
spec.instance_variable_get :@specification_version
spec.instance_variable_set :@specification_version,
NONEXISTENT_SPECIFICATION_VERSION
end
spec
end
##
# Loads ruby format gemspec from +filename+
def self.load(filename)
gemspec = nil
raise "NESTED Specification.load calls not allowed!" if @@gather
@@gather = proc { |gs| gemspec = gs }
data = File.read(filename)
eval(data)
gemspec
ensure
@@gather = nil
end
##
# Make sure the YAML specification is properly formatted with dashes
def self.normalize_yaml_input(input)
result = input.respond_to?(:read) ? input.read : input
result = "--- " + result unless result =~ /^--- /
result
end
##
# Sets the rubygems_version to the current RubyGems version
def mark_version
@rubygems_version = Gem::RubyGemsVersion
end
##
# Ignore unknown attributes while loading
def method_missing(sym, *a, &b) # :nodoc:
if @specification_version > CURRENT_SPECIFICATION_VERSION and
sym.to_s =~ /=$/ then
warn "ignoring #{sym} loading #{full_name}" if $DEBUG
else
super
end
end
##
# Adds a development dependency named +gem+ with +requirements+ to this
# Gem. For example:
#
# spec.add_development_dependency 'jabber4r', '> 0.1', '<= 0.5'
#
# Development dependencies aren't installed by default and aren't
# activated when a gem is required.
def add_development_dependency(gem, *requirements)
add_dependency_with_type(gem, :development, *requirements)
end
##
# Adds a runtime dependency named +gem+ with +requirements+ to this Gem.
# For example:
#
# spec.add_runtime_dependency 'jabber4r', '> 0.1', '<= 0.5'
def add_runtime_dependency(gem, *requirements)
add_dependency_with_type(gem, :runtime, *requirements)
end
##
# Adds a runtime dependency
alias add_dependency add_runtime_dependency
##
# Returns the full name (name-version) of this Gem. Platform information
# is included (name-version-platform) if it is specified and not the
# default Ruby platform.
def full_name
if platform == Gem::Platform::RUBY or platform.nil? then
"#{@name}-#{@version}"
else
"#{@name}-#{@version}-#{platform}"
end
end
##
# Returns the full name (name-version) of this gemspec using the original
# platform. For use with legacy gems.
def original_name # :nodoc:
if platform == Gem::Platform::RUBY or platform.nil? then
"#{@name}-#{@version}"
else
"#{@name}-#{@version}-#{@original_platform}"
end
end
##
# The full path to the gem (install path + full name).
def full_gem_path
path = File.join installation_path, 'gems', full_name
return path if File.directory? path
File.join installation_path, 'gems', original_name
end
##
# The default (generated) file name of the gem. See also #spec_name.
#
# spec.file_name # => "example-1.0.gem"
def file_name
full_name + '.gem'
end
##
# The directory that this gem was installed into.
def installation_path
unless @loaded_from then
raise Gem::Exception, "spec #{full_name} is not from an installed gem"
end
File.expand_path File.dirname(File.dirname(@loaded_from))
end
##
# Checks if this specification meets the requirement of +dependency+.
def satisfies_requirement?(dependency)
return @name == dependency.name &&
dependency.requirement.satisfied_by?(@version)
end
##
# Returns an object you can use to sort specifications in #sort_by.
def sort_obj
[@name, @version, @new_platform == Gem::Platform::RUBY ? -1 : 1]
end
##
# The default name of the gemspec. See also #file_name
#
# spec.spec_name # => "example-1.0.gemspec"
def spec_name
full_name + '.gemspec'
end
def <=>(other) # :nodoc:
sort_obj <=> other.sort_obj
end
##
# Tests specs for equality (across all attributes).
def ==(other) # :nodoc:
self.class === other && same_attributes?(other)
end
alias eql? == # :nodoc:
##
# True if this gem has the same attributes as +other+.
def same_attributes?(other)
@@attributes.each do |name, default|
return false unless self.send(name) == other.send(name)
end
true
end
private :same_attributes?
def hash # :nodoc:
@@attributes.inject(0) { |hash_code, (name, default_value)|
n = self.send(name).hash
hash_code + n
}
end
def to_yaml(opts = {}) # :nodoc:
mark_version
attributes = @@attributes.map { |name,| name.to_s }.sort
attributes = attributes - %w[name version platform]
yaml = YAML.quick_emit object_id, opts do |out|
out.map taguri, to_yaml_style do |map|
map.add 'name', @name
map.add 'version', @version
platform = case @original_platform
when nil, '' then
'ruby'
when String then
@original_platform
else
@original_platform.to_s
end
map.add 'platform', platform
attributes.each do |name|
map.add name, instance_variable_get("@#{name}")
end
end
end
end
def yaml_initialize(tag, vals) # :nodoc:
vals.each do |ivar, val|
instance_variable_set "@#{ivar}", val
end
@original_platform = @platform # for backwards compatibility
self.platform = Gem::Platform.new @platform
end
##
# Returns a Ruby code representation of this specification, such that it
# can be eval'ed and reconstruct the same specification later. Attributes
# that still have their default values are omitted.
def to_ruby
mark_version
result = []
result << "# -*- encoding: utf-8 -*-"
result << nil
result << "Gem::Specification.new do |s|"
result << " s.name = #{ruby_code name}"
result << " s.version = #{ruby_code version}"
unless platform.nil? or platform == Gem::Platform::RUBY then
result << " s.platform = #{ruby_code original_platform}"
end
result << ""
result << " s.required_rubygems_version = #{ruby_code required_rubygems_version} if s.respond_to? :required_rubygems_version="
handled = [
:dependencies,
:name,
:platform,
:required_rubygems_version,
:specification_version,
:version,
]
attributes = @@attributes.sort_by { |attr_name,| attr_name.to_s }
attributes.each do |attr_name, default|
next if handled.include? attr_name
current_value = self.send(attr_name)
if current_value != default or
self.class.required_attribute? attr_name then
result << " s.#{attr_name} = #{ruby_code current_value}"
end
end
result << nil
result << " if s.respond_to? :specification_version then"
result << " current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION"
result << " s.specification_version = #{specification_version}"
result << nil
result << " if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then"
unless dependencies.empty? then
dependencies.each do |dep|
version_reqs_param = dep.requirements_list.inspect
dep.instance_variable_set :@type, :runtime if dep.type.nil? # HACK
result << " s.add_#{dep.type}_dependency(%q<#{dep.name}>, #{version_reqs_param})"
end
end
result << " else"
unless dependencies.empty? then
dependencies.each do |dep|
version_reqs_param = dep.requirements_list.inspect
result << " s.add_dependency(%q<#{dep.name}>, #{version_reqs_param})"
end
end
result << ' end'
result << " else"
dependencies.each do |dep|
version_reqs_param = dep.requirements_list.inspect
result << " s.add_dependency(%q<#{dep.name}>, #{version_reqs_param})"
end
result << " end"
result << "end"
result << nil
result.join "\n"
end
##
# Checks that the specification contains all required fields, and does a
# very basic sanity check.
#
# Raises InvalidSpecificationException if the spec does not pass the
# checks..
def validate
extend Gem::UserInteraction
normalize
if rubygems_version != Gem::RubyGemsVersion then
raise Gem::InvalidSpecificationException,
"expected RubyGems version #{Gem::RubyGemsVersion}, was #{rubygems_version}"
end
@@required_attributes.each do |symbol|
unless self.send symbol then
raise Gem::InvalidSpecificationException,
"missing value for attribute #{symbol}"
end
end
unless String === name then
raise Gem::InvalidSpecificationException,
"invalid value for attribute name: \"#{name.inspect}\""
end
if require_paths.empty? then
raise Gem::InvalidSpecificationException,
'specification must have at least one require_path'
end
@files.delete_if do |file| File.directory? file end
@test_files.delete_if do |file| File.directory? file end
@executables.delete_if do |file|
File.directory? File.join(bindir, file)
end
@extra_rdoc_files.delete_if do |file| File.directory? file end
@extensions.delete_if do |file| File.directory? file end
non_files = files.select do |file|
!File.file? file
end
unless non_files.empty? then
non_files = non_files.map { |file| file.inspect }
raise Gem::InvalidSpecificationException,
"[#{non_files.join ", "}] are not files"
end
unless specification_version.is_a?(Fixnum)
raise Gem::InvalidSpecificationException,
'specification_version must be a Fixnum (did you mean version?)'
end
case platform
when Gem::Platform, Gem::Platform::RUBY then # ok
else
raise Gem::InvalidSpecificationException,
"invalid platform #{platform.inspect}, see Gem::Platform"
end
unless Array === authors and
authors.all? { |author| String === author } then
raise Gem::InvalidSpecificationException,
'authors must be Array of Strings'
end
licenses.each { |license|
if license.length > 64
raise Gem::InvalidSpecificationException,
"each license must be 64 characters or less"
end
}
# reject FIXME and TODO
unless authors.grep(/FIXME|TODO/).empty? then
raise Gem::InvalidSpecificationException,
'"FIXME" or "TODO" is not an author'
end
unless Array(email).grep(/FIXME|TODO/).empty? then
raise Gem::InvalidSpecificationException,
'"FIXME" or "TODO" is not an email address'
end
if description =~ /FIXME|TODO/ then
raise Gem::InvalidSpecificationException,
'"FIXME" or "TODO" is not a description'
end
if summary =~ /FIXME|TODO/ then
raise Gem::InvalidSpecificationException,
'"FIXME" or "TODO" is not a summary'
end
if homepage and not homepage.empty? and
homepage !~ /\A[a-z][a-z\d+.-]*:/i then
raise Gem::InvalidSpecificationException,
"\"#{homepage}\" is not a URI"
end
# Warnings
%w[author description email homepage rubyforge_project summary].each do |attribute|
value = self.send attribute
alert_warning "no #{attribute} specified" if value.nil? or value.empty?
end
if summary and not summary.empty? and description == summary then
alert_warning 'description and summary are identical'
end
alert_warning "deprecated autorequire specified" if autorequire
executables.each do |executable|
executable_path = File.join bindir, executable
shebang = File.read(executable_path, 2) == '#!'
alert_warning "#{executable_path} is missing #! line" unless shebang
end
true
end
##
# Normalize the list of files so that:
# * All file lists have redundancies removed.
# * Files referenced in the extra_rdoc_files are included in the package
# file list.
def normalize
if defined?(@extra_rdoc_files) and @extra_rdoc_files then
@extra_rdoc_files.uniq!
@files ||= []
@files.concat(@extra_rdoc_files)
end
@files.uniq! if @files
end
##
# Return a list of all gems that have a dependency on this gemspec. The
# list is structured with entries that conform to:
#
# [depending_gem, dependency, [list_of_gems_that_satisfy_dependency]]
def dependent_gems
out = []
Gem.source_index.each do |name,gem|
gem.dependencies.each do |dep|
if self.satisfies_requirement?(dep) then
sats = []
find_all_satisfiers(dep) do |sat|
sats << sat
end
out << [gem, dep, sats]
end
end
end
out
end
def to_s # :nodoc:
"#<Gem::Specification name=#{@name} version=#{@version}>"
end
def pretty_print(q) # :nodoc:
q.group 2, 'Gem::Specification.new do |s|', 'end' do
q.breakable
attributes = @@attributes.sort_by { |attr_name,| attr_name.to_s }
attributes.each do |attr_name, default|
current_value = self.send attr_name
if current_value != default or
self.class.required_attribute? attr_name then
q.text "s.#{attr_name} = "
if attr_name == :date then
current_value = current_value.utc
q.text "Time.utc(#{current_value.year}, #{current_value.month}, #{current_value.day})"
else
q.pp current_value
end
q.breakable
end
end
end
end
##
# Adds a dependency on gem +dependency+ with type +type+ that requires
# +requirements+. Valid types are currently <tt>:runtime</tt> and
# <tt>:development</tt>.
def add_dependency_with_type(dependency, type, *requirements)
requirements = if requirements.empty? then
Gem::Requirement.default
else
requirements.flatten
end
unless dependency.respond_to?(:name) &&
dependency.respond_to?(:version_requirements)
dependency = Gem::Dependency.new(dependency, requirements, type)
end
dependencies << dependency
end
private :add_dependency_with_type
##
# Finds all gems that satisfy +dep+
def find_all_satisfiers(dep)
Gem.source_index.each do |_, gem|
yield gem if gem.satisfies_requirement? dep
end
end
private :find_all_satisfiers
##
# Return a string containing a Ruby code representation of the given
# object.
def ruby_code(obj)
case obj
when String then '%q{' + obj + '}'
when Array then obj.inspect
when Gem::Version then obj.to_s.inspect
when Date then '%q{' + obj.strftime('%Y-%m-%d') + '}'
when Time then '%q{' + obj.strftime('%Y-%m-%d') + '}'
when Numeric then obj.inspect
when true, false, nil then obj.inspect
when Gem::Platform then "Gem::Platform.new(#{obj.to_a.inspect})"
when Gem::Requirement then "Gem::Requirement.new(#{obj.to_s.inspect})"
else raise Gem::Exception, "ruby_code case not handled: #{obj.class}"
end
end
private :ruby_code
# :section: Required gemspec attributes
##
# :attr_accessor: rubygems_version
#
# The version of RubyGems used to create this gem.
#
# Do not set this, it is set automatically when the gem is packaged.
required_attribute :rubygems_version, Gem::RubyGemsVersion
##
# :attr_accessor: specification_version
#
# The Gem::Specification version of this gemspec.
#
# Do not set this, it is set automatically when the gem is packaged.
required_attribute :specification_version, CURRENT_SPECIFICATION_VERSION
##
# :attr_accessor: name
#
# This gem's name
required_attribute :name
##
# :attr_accessor: version
#
# This gem's version
required_attribute :version
##
# :attr_accessor: date
#
# The date this gem was created
#
# Do not set this, it is set automatically when the gem is packaged.
required_attribute :date, TODAY
##
# :attr_accessor: summary
#
# A short summary of this gem's description. Displayed in `gem list -d`.
#
# The description should be more detailed than the summary. For example,
# you might wish to copy the entire README into the description.
#
# As of RubyGems 1.3.2 newlines are no longer stripped.
required_attribute :summary
##
# :attr_accessor: require_paths
#
# Paths in the gem to add to $LOAD_PATH when this gem is activated.
#
# The default 'lib' is typically sufficient.
required_attribute :require_paths, ['lib']
# :section: Optional gemspec attributes
##
# :attr_accessor: email
#
# A contact email for this gem
#
# If you are providing multiple authors and multiple emails they should be
# in the same order such that:
#
# Hash[*spec.authors.zip(spec.emails).flatten]
#
# Gives a hash of author name to email address.
attribute :email
##
# :attr_accessor: homepage
#
# The URL of this gem's home page
attribute :homepage
##
# :attr_accessor: rubyforge_project
#
# The rubyforge project this gem lives under. i.e. RubyGems'
# rubyforge_project is "rubygems".
attribute :rubyforge_project
##
# :attr_accessor: description
#
# A long description of this gem
attribute :description
##
# :attr_accessor: autorequire
#
# Autorequire was used by old RubyGems to automatically require a file.
# It no longer is supported.
attribute :autorequire
##
# :attr_accessor: default_executable
#
# The default executable for this gem.
#
# This is not used.
attribute :default_executable
##
# :attr_accessor: bindir
#
# The path in the gem for executable scripts
attribute :bindir, 'bin'
##
# :attr_accessor: has_rdoc
#
# Deprecated and ignored, defaults to true.
#
# Formerly used to indicate this gem was RDoc-capable.
attribute :has_rdoc, true
##
# True if this gem supports RDoc
alias :has_rdoc? :has_rdoc
##
# :attr_accessor: required_ruby_version
#
# The version of ruby required by this gem
attribute :required_ruby_version, Gem::Requirement.default
##
# :attr_accessor: required_rubygems_version
#
# The RubyGems version required by this gem
attribute :required_rubygems_version, Gem::Requirement.default
##
# :attr_accessor: platform
#
# The platform this gem runs on. See Gem::Platform for details.
#
# Setting this to any value other than Gem::Platform::RUBY or
# Gem::Platform::CURRENT is probably wrong.
attribute :platform, Gem::Platform::RUBY
##
# :attr_accessor: signing_key
#
# The key used to sign this gem. See Gem::Security for details.
attribute :signing_key, nil
##
# :attr_accessor: cert_chain
#
# The certificate chain used to sign this gem. See Gem::Security for
# details.
attribute :cert_chain, []
##
# :attr_accessor: post_install_message
#
# A message that gets displayed after the gem is installed
attribute :post_install_message, nil
##
# :attr_accessor: authors
#
# The list of author names who wrote this gem.
#
# If you are providing multiple authors and multiple emails they should be
# in the same order such that:
#
# Hash[*spec.authors.zip(spec.emails).flatten]
#
# Gives a hash of author name to email address.
array_attribute :authors
##
# :attr_accessor: licenses
#
# The license(s) for the library. Each license must be a short name, no
# more than 64 characters.
array_attribute :licenses
##
# :attr_accessor: files
#
# Files included in this gem. You cannot append to this accessor, you must
# assign to it.
#
# Only add files you can require to this list, not directories, etc.
#
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | true |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/command_manager.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/command_manager.rb | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'timeout'
require 'rubygems/command'
require 'rubygems/user_interaction'
##
# The command manager registers and installs all the individual sub-commands
# supported by the gem command.
#
# Extra commands can be provided by writing a rubygems_plugin.rb
# file in an installed gem. You should register your command against the
# Gem::CommandManager instance, like this:
#
# # file rubygems_plugin.rb
# require 'rubygems/command_manager'
#
# class Gem::Commands::EditCommand < Gem::Command
# # ...
# end
#
# Gem::CommandManager.instance.register_command :edit
#
# See Gem::Command for instructions on writing gem commands.
class Gem::CommandManager
include Gem::UserInteraction
##
# Return the authoritative instance of the command manager.
def self.instance
@command_manager ||= new
end
##
# Register all the subcommands supported by the gem command.
def initialize
@commands = {}
register_command :build
register_command :cert
register_command :check
register_command :cleanup
register_command :contents
register_command :dependency
register_command :environment
register_command :fetch
register_command :generate_index
register_command :help
register_command :install
register_command :list
register_command :lock
register_command :mirror
register_command :outdated
register_command :owner
register_command :pristine
register_command :push
register_command :query
register_command :rdoc
register_command :search
register_command :server
register_command :sources
register_command :specification
register_command :stale
register_command :uninstall
register_command :unpack
register_command :update
register_command :which
end
##
# Register the command object.
def register_command(command_obj)
@commands[command_obj] = false
end
##
# Return the registered command from the command name.
def [](command_name)
command_name = command_name.intern
return nil if @commands[command_name].nil?
@commands[command_name] ||= load_and_instantiate(command_name)
end
##
# Return a sorted list of all command names (as strings).
def command_names
@commands.keys.collect {|key| key.to_s}.sort
end
##
# Run the config specified by +args+.
def run(args)
process_args(args)
rescue StandardError, Timeout::Error => ex
alert_error "While executing gem ... (#{ex.class})\n #{ex.to_s}"
ui.errs.puts "\t#{ex.backtrace.join "\n\t"}" if
Gem.configuration.backtrace
terminate_interaction(1)
rescue Interrupt
alert_error "Interrupted"
terminate_interaction(1)
end
def process_args(args)
args = args.to_str.split(/\s+/) if args.respond_to?(:to_str)
if args.size == 0
say Gem::Command::HELP
terminate_interaction(1)
end
case args[0]
when '-h', '--help'
say Gem::Command::HELP
terminate_interaction(0)
when '-v', '--version'
say Gem::RubyGemsVersion
terminate_interaction(0)
when /^-/
alert_error "Invalid option: #{args[0]}. See 'gem --help'."
terminate_interaction(1)
else
cmd_name = args.shift.downcase
cmd = find_command(cmd_name)
cmd.invoke(*args)
end
end
def find_command(cmd_name)
possibilities = find_command_possibilities cmd_name
if possibilities.size > 1 then
raise "Ambiguous command #{cmd_name} matches [#{possibilities.join(', ')}]"
elsif possibilities.size < 1 then
raise "Unknown command #{cmd_name}"
end
self[possibilities.first]
end
def find_command_possibilities(cmd_name)
len = cmd_name.length
command_names.select { |n| cmd_name == n[0, len] }
end
private
def load_and_instantiate(command_name)
command_name = command_name.to_s
retried = false
begin
const_name = command_name.capitalize.gsub(/_(.)/) { $1.upcase }
Gem::Commands.const_get("#{const_name}Command").new
rescue NameError
if retried then
raise
else
retried = true
require "rubygems/commands/#{command_name}_command"
retry
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/validator.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/validator.rb | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'find'
require 'digest'
require 'rubygems/format'
require 'rubygems/installer'
# Load test-unit 2.x if it's a gem
begin
Gem.activate('test-unit')
rescue Gem::LoadError
# Ignore - use the test-unit library that's part of the standard library
end
##
# Validator performs various gem file and gem database validation
class Gem::Validator
include Gem::UserInteraction
##
# Given a gem file's contents, validates against its own MD5 checksum
# gem_data:: [String] Contents of the gem file
def verify_gem(gem_data)
raise Gem::VerificationError, 'empty gem file' if gem_data.size == 0
unless gem_data =~ /MD5SUM/ then
return # Don't worry about it...this sucks. Need to fix MD5 stuff for
# new format
# FIXME
end
sum_data = gem_data.gsub(/MD5SUM = "([a-z0-9]+)"/,
"MD5SUM = \"#{"F" * 32}\"")
unless Digest::MD5.hexdigest(sum_data) == $1.to_s then
raise Gem::VerificationError, 'invalid checksum for gem file'
end
end
##
# Given the path to a gem file, validates against its own MD5 checksum
#
# gem_path:: [String] Path to gem file
def verify_gem_file(gem_path)
open gem_path, Gem.binary_mode do |file|
gem_data = file.read
verify_gem gem_data
end
rescue Errno::ENOENT, Errno::EINVAL
raise Gem::VerificationError, "missing gem file #{gem_path}"
end
private
def find_files_for_gem(gem_directory)
installed_files = []
Find.find gem_directory do |file_name|
fn = file_name[gem_directory.size..file_name.size-1].sub(/^\//, "")
installed_files << fn unless
fn =~ /CVS/ || fn.empty? || File.directory?(file_name)
end
installed_files
end
public
ErrorData = Struct.new :path, :problem
##
# Checks the gem directory for the following potential
# inconsistencies/problems:
#
# * Checksum gem itself
# * For each file in each gem, check consistency of installed versions
# * Check for files that aren't part of the gem but are in the gems directory
# * 1 cache - 1 spec - 1 directory.
#
# returns a hash of ErrorData objects, keyed on the problem gem's name.
def alien(gems=[])
errors = Hash.new { |h,k| h[k] = {} }
Gem::SourceIndex.from_installed_gems.each do |gem_name, gem_spec|
next unless gems.include? gem_spec.name unless gems.empty?
install_dir = gem_spec.installation_path
gem_path = File.join install_dir, "cache", gem_spec.file_name
spec_path = File.join install_dir, "specifications", gem_spec.spec_name
gem_directory = gem_spec.full_gem_path
unless File.directory? gem_directory then
errors[gem_name][gem_spec.full_name] =
"Gem registered but doesn't exist at #{gem_directory}"
next
end
unless File.exist? spec_path then
errors[gem_name][spec_path] = "Spec file missing for installed gem"
end
begin
verify_gem_file(gem_path)
good, gone, unreadable = nil, nil, nil, nil
open gem_path, Gem.binary_mode do |file|
format = Gem::Format.from_file_by_path(gem_path)
good, gone = format.file_entries.partition { |entry, _|
File.exist? File.join(gem_directory, entry['path'])
}
gone.map! { |entry, _| entry['path'] }
gone.sort.each do |path|
errors[gem_name][path] = "Missing file"
end
good, unreadable = good.partition { |entry, _|
File.readable? File.join(gem_directory, entry['path'])
}
unreadable.map! { |entry, _| entry['path'] }
unreadable.sort.each do |path|
errors[gem_name][path] = "Unreadable file"
end
good.each do |entry, data|
begin
next unless data # HACK `gem check -a mkrf`
open File.join(gem_directory, entry['path']), Gem.binary_mode do |f|
unless Digest::MD5.hexdigest(f.read).to_s ==
Digest::MD5.hexdigest(data).to_s then
errors[gem_name][entry['path']] = "Modified from original"
end
end
end
end
end
installed_files = find_files_for_gem(gem_directory)
good.map! { |entry, _| entry['path'] }
extras = installed_files - good - unreadable
extras.each do |extra|
errors[gem_name][extra] = "Extra file"
end
rescue Gem::VerificationError => e
errors[gem_name][gem_path] = e.message
end
end
errors.each do |name, subhash|
errors[name] = subhash.map { |path, msg| ErrorData.new(path, msg) }
end
errors
end
if RUBY_VERSION < '1.9' then
class TestRunner
def initialize(suite, ui)
@suite = suite
@ui = ui
end
def self.run(suite, ui)
require 'test/unit/ui/testrunnermediator'
return new(suite, ui).start
end
def start
@mediator = Test::Unit::UI::TestRunnerMediator.new(@suite)
@mediator.add_listener(Test::Unit::TestResult::FAULT, &method(:add_fault))
return @mediator.run_suite
end
def add_fault(fault)
if Gem.configuration.verbose then
@ui.say fault.long_display
end
end
end
autoload :TestRunner, 'test/unit/ui/testrunnerutilities'
end
##
# Runs unit tests for a given gem specification
def unit_test(gem_spec)
start_dir = Dir.pwd
Dir.chdir(gem_spec.full_gem_path)
$: << gem_spec.full_gem_path
# XXX: why do we need this gem_spec when we've already got 'spec'?
test_files = gem_spec.test_files
if test_files.empty? then
say "There are no unit tests to run for #{gem_spec.full_name}"
return nil
end
gem gem_spec.name, "= #{gem_spec.version.version}"
test_files.each do |f| require f end
if RUBY_VERSION < '1.9' then
suite = Test::Unit::TestSuite.new("#{gem_spec.name}-#{gem_spec.version}")
ObjectSpace.each_object(Class) do |klass|
suite << klass.suite if (klass < Test::Unit::TestCase)
end
result = TestRunner.run suite, ui
alert_error result.to_s unless result.passed?
else
result = MiniTest::Unit.new
result.run
end
result
ensure
Dir.chdir(start_dir)
end
def remove_leading_dot_dir(path)
path.sub(/^\.\//, "")
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/user_interaction.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/user_interaction.rb | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
##
# Module that defines the default UserInteraction. Any class including this
# module will have access to the +ui+ method that returns the default UI.
module Gem::DefaultUserInteraction
##
# The default UI is a class variable of the singleton class for this
# module.
@ui = nil
##
# Return the default UI.
def self.ui
@ui ||= Gem::ConsoleUI.new
end
##
# Set the default UI. If the default UI is never explicitly set, a simple
# console based UserInteraction will be used automatically.
def self.ui=(new_ui)
@ui = new_ui
end
##
# Use +new_ui+ for the duration of +block+.
def self.use_ui(new_ui)
old_ui = @ui
@ui = new_ui
yield
ensure
@ui = old_ui
end
##
# See DefaultUserInteraction::ui
def ui
Gem::DefaultUserInteraction.ui
end
##
# See DefaultUserInteraction::ui=
def ui=(new_ui)
Gem::DefaultUserInteraction.ui = new_ui
end
##
# See DefaultUserInteraction::use_ui
def use_ui(new_ui, &block)
Gem::DefaultUserInteraction.use_ui(new_ui, &block)
end
end
##
# Make the default UI accessable without the "ui." prefix. Classes
# including this module may use the interaction methods on the default UI
# directly. Classes may also reference the ui and ui= methods.
#
# Example:
#
# class X
# include Gem::UserInteraction
#
# def get_answer
# n = ask("What is the meaning of life?")
# end
# end
module Gem::UserInteraction
include Gem::DefaultUserInteraction
##
# :method: alert
##
# :method: alert_error
##
# :method: alert_warning
##
# :method: ask
##
# :method: ask_yes_no
##
# :method: choose_from_list
##
# :method: say
##
# :method: terminate_interaction
[:alert,
:alert_error,
:alert_warning,
:ask,
:ask_for_password,
:ask_yes_no,
:choose_from_list,
:say,
:terminate_interaction ].each do |methname|
class_eval %{
def #{methname}(*args)
ui.#{methname}(*args)
end
}, __FILE__, __LINE__
end
end
##
# Gem::StreamUI implements a simple stream based user interface.
class Gem::StreamUI
attr_reader :ins, :outs, :errs
def initialize(in_stream, out_stream, err_stream=STDERR)
@ins = in_stream
@outs = out_stream
@errs = err_stream
end
##
# Choose from a list of options. +question+ is a prompt displayed above
# the list. +list+ is a list of option strings. Returns the pair
# [option_name, option_index].
def choose_from_list(question, list)
@outs.puts question
list.each_with_index do |item, index|
@outs.puts " #{index+1}. #{item}"
end
@outs.print "> "
@outs.flush
result = @ins.gets
return nil, nil unless result
result = result.strip.to_i - 1
return list[result], result
end
##
# Ask a question. Returns a true for yes, false for no. If not connected
# to a tty, raises an exception if default is nil, otherwise returns
# default.
def ask_yes_no(question, default=nil)
unless @ins.tty? then
if default.nil? then
raise Gem::OperationNotSupportedError,
"Not connected to a tty and no default specified"
else
return default
end
end
qstr = case default
when nil
'yn'
when true
'Yn'
else
'yN'
end
result = nil
while result.nil?
result = ask("#{question} [#{qstr}]")
result = case result
when /^[Yy].*/
true
when /^[Nn].*/
false
when /^$/
default
else
nil
end
end
return result
end
##
# Ask a question. Returns an answer if connected to a tty, nil otherwise.
def ask(question)
return nil if not @ins.tty?
@outs.print(question + " ")
@outs.flush
result = @ins.gets
result.chomp! if result
result
end
##
# Ask for a password. Does not echo response to terminal.
def ask_for_password(question)
return nil if not @ins.tty?
@outs.print(question + " ")
@outs.flush
Gem.win_platform? ? ask_for_password_on_windows : ask_for_password_on_unix
end
##
# Asks for a password that works on windows. Ripped from the Heroku gem.
def ask_for_password_on_windows
require "Win32API"
char = nil
password = ''
while char = Win32API.new("crtdll", "_getch", [ ], "L").Call do
break if char == 10 || char == 13 # received carriage return or newline
if char == 127 || char == 8 # backspace and delete
password.slice!(-1, 1)
else
password << char.chr
end
end
puts
password
end
##
# Asks for a password that works on unix
def ask_for_password_on_unix
system "stty -echo"
password = @ins.gets
password.chomp! if password
system "stty echo"
password
end
##
# Display a statement.
def say(statement="")
@outs.puts statement
end
##
# Display an informational alert. Will ask +question+ if it is not nil.
def alert(statement, question=nil)
@outs.puts "INFO: #{statement}"
ask(question) if question
end
##
# Display a warning in a location expected to get error messages. Will
# ask +question+ if it is not nil.
def alert_warning(statement, question=nil)
@errs.puts "WARNING: #{statement}"
ask(question) if question
end
##
# Display an error message in a location expected to get error messages.
# Will ask +question+ if it is not nil.
def alert_error(statement, question=nil)
@errs.puts "ERROR: #{statement}"
ask(question) if question
end
##
# Display a debug message on the same location as error messages.
def debug(statement)
@errs.puts statement
end
##
# Terminate the application with exit code +status+, running any exit
# handlers that might have been defined.
def terminate_interaction(status = 0)
raise Gem::SystemExitException, status
end
##
# Return a progress reporter object chosen from the current verbosity.
def progress_reporter(*args)
case Gem.configuration.verbose
when nil, false
SilentProgressReporter.new(@outs, *args)
when true
SimpleProgressReporter.new(@outs, *args)
else
VerboseProgressReporter.new(@outs, *args)
end
end
##
# An absolutely silent progress reporter.
class SilentProgressReporter
attr_reader :count
def initialize(out_stream, size, initial_message, terminal_message = nil)
end
def updated(message)
end
def done
end
end
##
# A basic dotted progress reporter.
class SimpleProgressReporter
include Gem::DefaultUserInteraction
attr_reader :count
def initialize(out_stream, size, initial_message,
terminal_message = "complete")
@out = out_stream
@total = size
@count = 0
@terminal_message = terminal_message
@out.puts initial_message
end
##
# Prints out a dot and ignores +message+.
def updated(message)
@count += 1
@out.print "."
@out.flush
end
##
# Prints out the terminal message.
def done
@out.puts "\n#{@terminal_message}"
end
end
##
# A progress reporter that prints out messages about the current progress.
class VerboseProgressReporter
include Gem::DefaultUserInteraction
attr_reader :count
def initialize(out_stream, size, initial_message,
terminal_message = 'complete')
@out = out_stream
@total = size
@count = 0
@terminal_message = terminal_message
@out.puts initial_message
end
##
# Prints out the position relative to the total and the +message+.
def updated(message)
@count += 1
@out.puts "#{@count}/#{@total}: #{message}"
end
##
# Prints out the terminal message.
def done
@out.puts @terminal_message
end
end
end
##
# Subclass of StreamUI that instantiates the user interaction using STDIN,
# STDOUT, and STDERR.
class Gem::ConsoleUI < Gem::StreamUI
def initialize
super STDIN, STDOUT, STDERR
end
end
##
# SilentUI is a UI choice that is absolutely silent.
class Gem::SilentUI
def method_missing(sym, *args, &block)
self
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/installer.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/installer.rb | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'fileutils'
require 'rbconfig'
require 'rubygems/format'
require 'rubygems/ext'
require 'rubygems/require_paths_builder'
##
# The installer class processes RubyGem .gem files and installs the files
# contained in the .gem into the Gem.path.
#
# Gem::Installer does the work of putting files in all the right places on the
# filesystem including unpacking the gem into its gem dir, installing the
# gemspec in the specifications dir, storing the cached gem in the cache dir,
# and installing either wrappers or symlinks for executables.
#
# The installer fires pre and post install hooks. Hooks can be added either
# through a rubygems_plugin.rb file in an installed gem or via a
# rubygems/defaults/#{RUBY_ENGINE}.rb or rubygems/defaults/operating_system.rb
# file. See Gem.pre_install and Gem.post_install for details.
class Gem::Installer
##
# Paths where env(1) might live. Some systems are broken and have it in
# /bin
ENV_PATHS = %w[/usr/bin/env /bin/env]
##
# Raised when there is an error while building extensions.
#
class ExtensionBuildError < Gem::InstallError; end
include Gem::UserInteraction
include Gem::RequirePathsBuilder
##
# The directory a gem's executables will be installed into
attr_reader :bin_dir
##
# The gem repository the gem will be installed into
attr_reader :gem_home
##
# The Gem::Specification for the gem being installed
attr_reader :spec
@path_warning = false
class << self
##
# True if we've warned about PATH not including Gem.bindir
attr_accessor :path_warning
attr_writer :exec_format
# Defaults to use Ruby's program prefix and suffix.
def exec_format
@exec_format ||= Gem.default_exec_format
end
end
##
# Constructs an Installer instance that will install the gem located at
# +gem+. +options+ is a Hash with the following keys:
#
# :env_shebang:: Use /usr/bin/env in bin wrappers.
# :force:: Overrides all version checks and security policy checks, except
# for a signed-gems-only policy.
# :ignore_dependencies:: Don't raise if a dependency is missing.
# :install_dir:: The directory to install the gem into.
# :format_executable:: Format the executable the same as the ruby executable.
# If your ruby is ruby18, foo_exec will be installed as
# foo_exec18.
# :security_policy:: Use the specified security policy. See Gem::Security
# :wrappers:: Install wrappers if true, symlinks if false.
def initialize(gem, options={})
@gem = gem
options = {
:bin_dir => nil,
:env_shebang => false,
:exec_format => false,
:force => false,
:install_dir => Gem.dir,
:source_index => Gem.source_index,
}.merge options
@env_shebang = options[:env_shebang]
@force = options[:force]
gem_home = options[:install_dir]
@gem_home = File.expand_path(gem_home)
@ignore_dependencies = options[:ignore_dependencies]
@format_executable = options[:format_executable]
@security_policy = options[:security_policy]
@wrappers = options[:wrappers]
@bin_dir = options[:bin_dir]
@development = options[:development]
@source_index = options[:source_index]
begin
@format = Gem::Format.from_file_by_path @gem, @security_policy
rescue Gem::Package::FormatError
raise Gem::InstallError, "invalid gem format for #{@gem}"
end
if options[:user_install] and not options[:unpack] then
@gem_home = Gem.user_dir
user_bin_dir = File.join(@gem_home, 'bin')
unless ENV['PATH'].split(File::PATH_SEPARATOR).include? user_bin_dir then
unless self.class.path_warning then
alert_warning "You don't have #{user_bin_dir} in your PATH,\n\t gem executables will not run."
self.class.path_warning = true
end
end
end
FileUtils.mkdir_p @gem_home
raise Gem::FilePermissionError, @gem_home unless File.writable? @gem_home
@spec = @format.spec
@gem_dir = File.join(@gem_home, "gems", @spec.full_name).untaint
end
##
# Installs the gem and returns a loaded Gem::Specification for the installed
# gem.
#
# The gem will be installed with the following structure:
#
# @gem_home/
# cache/<gem-version>.gem #=> a cached copy of the installed gem
# gems/<gem-version>/... #=> extracted files
# specifications/<gem-version>.gemspec #=> the Gem::Specification
def install
# If we're forcing the install then disable security unless the security
# policy says that we only install singed gems.
@security_policy = nil if @force and @security_policy and
not @security_policy.only_signed
unless @force then
if rrv = @spec.required_ruby_version then
unless rrv.satisfied_by? Gem.ruby_version then
raise Gem::InstallError, "#{@spec.name} requires Ruby version #{rrv}."
end
end
if rrgv = @spec.required_rubygems_version then
unless rrgv.satisfied_by? Gem::Version.new(Gem::RubyGemsVersion) then
raise Gem::InstallError,
"#{@spec.name} requires RubyGems version #{rrgv}. " +
"Try 'gem update --system' to update RubyGems itself."
end
end
unless @ignore_dependencies then
deps = @spec.runtime_dependencies
deps |= @spec.development_dependencies if @development
deps.each do |dep_gem|
ensure_dependency @spec, dep_gem
end
end
end
Gem.pre_install_hooks.each do |hook|
hook.call self
end
FileUtils.mkdir_p @gem_home unless File.directory? @gem_home
Gem.ensure_gem_subdirectories @gem_home
FileUtils.mkdir_p @gem_dir
extract_files
generate_bin
build_extensions
write_spec
write_require_paths_file_if_needed
# HACK remove? Isn't this done in multiple places?
cached_gem = File.join @gem_home, "cache", @gem.split(/\//).pop
unless File.exist? cached_gem then
FileUtils.cp @gem, File.join(@gem_home, "cache")
end
say @spec.post_install_message unless @spec.post_install_message.nil?
@spec.loaded_from = File.join(@gem_home, 'specifications', @spec.spec_name)
@source_index.add_spec @spec
Gem.post_install_hooks.each do |hook|
hook.call self
end
return @spec
rescue Zlib::GzipFile::Error
raise Gem::InstallError, "gzip error installing #{@gem}"
end
##
# Ensure that the dependency is satisfied by the current installation of
# gem. If it is not an exception is raised.
#
# spec :: Gem::Specification
# dependency :: Gem::Dependency
def ensure_dependency(spec, dependency)
unless installation_satisfies_dependency? dependency then
raise Gem::InstallError, "#{spec.name} requires #{dependency}"
end
true
end
##
# True if the gems in the source_index satisfy +dependency+.
def installation_satisfies_dependency?(dependency)
@source_index.find_name(dependency.name, dependency.requirement).size > 0
end
##
# Unpacks the gem into the given directory.
def unpack(directory)
@gem_dir = directory
@format = Gem::Format.from_file_by_path @gem, @security_policy
extract_files
end
##
# Writes the .gemspec specification (in Ruby) to the gem home's
# specifications directory.
def write_spec
rubycode = @spec.to_ruby
file_name = File.join @gem_home, 'specifications', @spec.spec_name
file_name.untaint
File.open(file_name, "w") do |file|
file.puts rubycode
end
end
##
# Creates windows .bat files for easy running of commands
def generate_windows_script(bindir, filename)
if Gem.win_platform? then
script_name = filename + ".bat"
script_path = File.join bindir, File.basename(script_name)
File.open script_path, 'w' do |file|
file.puts windows_stub_script(bindir, filename)
end
say script_path if Gem.configuration.really_verbose
end
end
def generate_bin
return if @spec.executables.nil? or @spec.executables.empty?
# If the user has asked for the gem to be installed in a directory that is
# the system gem directory, then use the system bin directory, else create
# (or use) a new bin dir under the gem_home.
bindir = @bin_dir ? @bin_dir : Gem.bindir(@gem_home)
Dir.mkdir bindir unless File.exist? bindir
raise Gem::FilePermissionError.new(bindir) unless File.writable? bindir
@spec.executables.each do |filename|
filename.untaint
bin_path = File.expand_path File.join(@gem_dir, @spec.bindir, filename)
mode = File.stat(bin_path).mode | 0111
File.chmod mode, bin_path
if @wrappers then
generate_bin_script filename, bindir
else
generate_bin_symlink filename, bindir
end
end
end
##
# Creates the scripts to run the applications in the gem.
#--
# The Windows script is generated in addition to the regular one due to a
# bug or misfeature in the Windows shell's pipe. See
# http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/193379
def generate_bin_script(filename, bindir)
bin_script_path = File.join bindir, formatted_program_filename(filename)
exec_path = File.join @gem_dir, @spec.bindir, filename
# HACK some gems don't have #! in their executables, restore 2008/06
#if File.read(exec_path, 2) == '#!' then
FileUtils.rm_f bin_script_path # prior install may have been --no-wrappers
File.open bin_script_path, 'w', 0755 do |file|
file.print app_script_text(filename)
end
say bin_script_path if Gem.configuration.really_verbose
generate_windows_script bindir, filename
#else
# FileUtils.rm_f bin_script_path
# FileUtils.cp exec_path, bin_script_path,
# :verbose => Gem.configuration.really_verbose
#end
end
##
# Creates the symlinks to run the applications in the gem. Moves
# the symlink if the gem being installed has a newer version.
def generate_bin_symlink(filename, bindir)
if Gem.win_platform? then
alert_warning "Unable to use symlinks on Windows, installing wrapper"
generate_bin_script filename, bindir
return
end
src = File.join @gem_dir, 'bin', filename
dst = File.join bindir, formatted_program_filename(filename)
if File.exist? dst then
if File.symlink? dst then
link = File.readlink(dst).split File::SEPARATOR
cur_version = Gem::Version.create(link[-3].sub(/^.*-/, ''))
return if @spec.version < cur_version
end
File.unlink dst
end
FileUtils.symlink src, dst, :verbose => Gem.configuration.really_verbose
end
##
# Generates a #! line for +bin_file_name+'s wrapper copying arguments if
# necessary.
def shebang(bin_file_name)
ruby_name = Gem::ConfigMap[:ruby_install_name] if @env_shebang
path = File.join @gem_dir, @spec.bindir, bin_file_name
first_line = File.open(path, "rb") {|file| file.gets}
if /\A#!/ =~ first_line then
# Preserve extra words on shebang line, like "-w". Thanks RPA.
shebang = first_line.sub(/\A\#!.*?ruby\S*(?=(\s+\S+))/, "#!#{Gem.ruby}")
opts = $1
shebang.strip! # Avoid nasty ^M issues.
end
if not ruby_name then
"#!#{Gem.ruby}#{opts}"
elsif opts then
"#!/bin/sh\n'exec' #{ruby_name.dump} '-x' \"$0\" \"$@\"\n#{shebang}"
else
# Create a plain shebang line.
@env_path ||= ENV_PATHS.find {|env_path| File.executable? env_path }
"#!#{@env_path} #{ruby_name}"
end
end
##
# Return the text for an application file.
def app_script_text(bin_file_name)
<<-TEXT
#{shebang bin_file_name}
#
# This file was generated by RubyGems.
#
# The application '#{@spec.name}' is installed as part of a gem, and
# this file is here to facilitate running it.
#
require 'rubygems'
version = "#{Gem::Requirement.default}"
if ARGV.first =~ /^_(.*)_$/ and Gem::Version.correct? $1 then
version = $1
ARGV.shift
end
gem '#{@spec.name}', version
load Gem.bin_path('#{@spec.name}', '#{bin_file_name}', version)
TEXT
end
##
# return the stub script text used to launch the true ruby script
def windows_stub_script(bindir, bin_file_name)
<<-TEXT
@ECHO OFF
IF NOT "%~f0" == "~f0" GOTO :WinNT
@"#{File.basename(Gem.ruby).chomp('"')}" "#{File.join(bindir, bin_file_name)}" %1 %2 %3 %4 %5 %6 %7 %8 %9
GOTO :EOF
:WinNT
@"#{File.basename(Gem.ruby).chomp('"')}" "%~dpn0" %*
TEXT
end
##
# Builds extensions. Valid types of extensions are extconf.rb files,
# configure scripts and rakefiles or mkrf_conf files.
def build_extensions
return if @spec.extensions.empty?
say "Building native extensions. This could take a while..."
start_dir = Dir.pwd
dest_path = File.join @gem_dir, @spec.require_paths.first
ran_rake = false # only run rake once
@spec.extensions.each do |extension|
break if ran_rake
results = []
builder = case extension
when /extconf/ then
Gem::Ext::ExtConfBuilder
when /configure/ then
Gem::Ext::ConfigureBuilder
when /rakefile/i, /mkrf_conf/i then
ran_rake = true
Gem::Ext::RakeBuilder
else
results = ["No builder for extension '#{extension}'"]
nil
end
begin
Dir.chdir File.join(@gem_dir, File.dirname(extension))
results = builder.build(extension, @gem_dir, dest_path, results)
say results.join("\n") if Gem.configuration.really_verbose
rescue => ex
results = results.join "\n"
File.open('gem_make.out', 'wb') { |f| f.puts results }
message = <<-EOF
ERROR: Failed to build gem native extension.
#{results}
Gem files will remain installed in #{@gem_dir} for inspection.
Results logged to #{File.join(Dir.pwd, 'gem_make.out')}
EOF
raise ExtensionBuildError, message
ensure
Dir.chdir start_dir
end
end
end
##
# Reads the file index and extracts each file into the gem directory.
#
# Ensures that files can't be installed outside the gem directory.
def extract_files
@gem_dir = File.expand_path @gem_dir
raise ArgumentError, "format required to extract from" if @format.nil?
@format.file_entries.each do |entry, file_data|
path = entry['path'].untaint
if path =~ /\A\// then # for extra sanity
raise Gem::InstallError,
"attempt to install file into #{entry['path'].inspect}"
end
path = File.expand_path File.join(@gem_dir, path)
if path !~ /\A#{Regexp.escape @gem_dir}/ then
msg = "attempt to install file into %p under %p" %
[entry['path'], @gem_dir]
raise Gem::InstallError, msg
end
FileUtils.rm_rf(path) if File.exists?(path)
FileUtils.mkdir_p File.dirname(path)
File.open(path, "wb") do |out|
out.write file_data
end
FileUtils.chmod entry['mode'], path
say path if Gem.configuration.really_verbose
end
end
##
# Prefix and suffix the program filename the same as ruby.
def formatted_program_filename(filename)
if @format_executable then
self.class.exec_format % File.basename(filename)
else
filename
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/indexer.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/indexer.rb | require 'fileutils'
require 'tmpdir'
require 'zlib'
require 'rubygems'
require 'rubygems/format'
begin
gem 'builder'
require 'builder/xchar'
rescue LoadError
end
##
# Top level class for building the gem repository index.
class Gem::Indexer
include Gem::UserInteraction
##
# Build indexes for RubyGems older than 1.2.0 when true
attr_accessor :build_legacy
##
# Build indexes for RubyGems 1.2.0 and newer when true
attr_accessor :build_modern
##
# Index install location
attr_reader :dest_directory
##
# Specs index install location
attr_reader :dest_specs_index
##
# Latest specs index install location
attr_reader :dest_latest_specs_index
##
# Prerelease specs index install location
attr_reader :dest_prerelease_specs_index
##
# Index build directory
attr_reader :directory
##
# Create an indexer that will index the gems in +directory+.
def initialize(directory, options = {})
unless ''.respond_to? :to_xs then
raise "Gem::Indexer requires that the XML Builder library be installed:" \
"\n\tgem install builder"
end
options = { :build_legacy => true, :build_modern => true }.merge options
@build_legacy = options[:build_legacy]
@build_modern = options[:build_modern]
@rss_title = options[:rss_title]
@rss_host = options[:rss_host]
@rss_gems_host = options[:rss_gems_host]
@dest_directory = directory
@directory = File.join Dir.tmpdir, "gem_generate_index_#{$$}"
marshal_name = "Marshal.#{Gem.marshal_version}"
@master_index = File.join @directory, 'yaml'
@marshal_index = File.join @directory, marshal_name
@quick_dir = File.join @directory, 'quick'
@quick_marshal_dir = File.join @quick_dir, marshal_name
@quick_index = File.join @quick_dir, 'index'
@latest_index = File.join @quick_dir, 'latest_index'
@specs_index = File.join @directory, "specs.#{Gem.marshal_version}"
@latest_specs_index = File.join @directory,
"latest_specs.#{Gem.marshal_version}"
@prerelease_specs_index = File.join(@directory,
"prerelease_specs.#{Gem.marshal_version}")
@dest_specs_index = File.join @dest_directory,
"specs.#{Gem.marshal_version}"
@dest_latest_specs_index = File.join @dest_directory,
"latest_specs.#{Gem.marshal_version}"
@dest_prerelease_specs_index = File.join @dest_directory,
"prerelease_specs.#{Gem.marshal_version}"
@rss_index = File.join @directory, 'index.rss'
@files = []
end
##
# Abbreviate the spec for downloading. Abbreviated specs are only used for
# searching, downloading and related activities and do not need deployment
# specific information (e.g. list of files). So we abbreviate the spec,
# making it much smaller for quicker downloads.
def abbreviate(spec)
spec.files = []
spec.test_files = []
spec.rdoc_options = []
spec.extra_rdoc_files = []
spec.cert_chain = []
spec
end
##
# Build various indicies
def build_indicies(index)
# Marshal gemspecs are used by both modern and legacy RubyGems
build_marshal_gemspecs index
build_legacy_indicies index if @build_legacy
build_modern_indicies index if @build_modern
build_rss index
compress_indicies
end
##
# Builds indicies for RubyGems older than 1.2.x
def build_legacy_indicies(index)
progress = ui.progress_reporter index.size,
"Generating YAML quick index gemspecs for #{index.size} gems",
"Complete"
Gem.time 'Generated YAML quick index gemspecs' do
index.released_gems.each do |original_name, spec|
spec_file_name = "#{original_name}.gemspec.rz"
yaml_name = File.join @quick_dir, spec_file_name
yaml_zipped = Gem.deflate spec.to_yaml
open yaml_name, 'wb' do |io| io.write yaml_zipped end
progress.updated original_name
end
progress.done
end
say "Generating quick index"
Gem.time 'Generated quick index' do
open @quick_index, 'wb' do |io|
io.puts index.sort.map { |_, spec| spec.original_name }
end
end
say "Generating latest index"
Gem.time 'Generated latest index' do
open @latest_index, 'wb' do |io|
io.puts index.latest_specs.sort.map { |spec| spec.original_name }
end
end
# Don't need prerelease legacy index
say "Generating Marshal master index"
Gem.time 'Generated Marshal master index' do
open @marshal_index, 'wb' do |io|
io.write index.dump
end
end
progress = ui.progress_reporter index.size,
"Generating YAML master index for #{index.size} gems (this may take a while)",
"Complete"
Gem.time 'Generated YAML master index' do
open @master_index, 'wb' do |io|
io.puts "--- !ruby/object:#{index.class}"
io.puts "gems:"
gems = index.sort_by { |name, gemspec| gemspec.sort_obj }
gems.each do |original_name, gemspec|
yaml = gemspec.to_yaml.gsub(/^/, ' ')
yaml = yaml.sub(/\A ---/, '') # there's a needed extra ' ' here
io.print " #{original_name}:"
io.puts yaml
progress.updated original_name
end
end
progress.done
end
@files << @quick_dir
@files << @master_index
@files << "#{@master_index}.Z"
@files << @marshal_index
@files << "#{@marshal_index}.Z"
end
##
# Builds Marshal quick index gemspecs.
def build_marshal_gemspecs(index)
progress = ui.progress_reporter index.size,
"Generating Marshal quick index gemspecs for #{index.size} gems",
"Complete"
files = []
Gem.time 'Generated Marshal quick index gemspecs' do
index.gems.each do |original_name, spec|
spec_file_name = "#{original_name}.gemspec.rz"
marshal_name = File.join @quick_marshal_dir, spec_file_name
marshal_zipped = Gem.deflate Marshal.dump(spec)
open marshal_name, 'wb' do |io| io.write marshal_zipped end
files << marshal_name
progress.updated original_name
end
progress.done
end
@files << @quick_marshal_dir
files
end
##
# Build a single index for RubyGems 1.2 and newer
def build_modern_index(index, file, name)
say "Generating #{name} index"
Gem.time "Generated #{name} index" do
open(file, 'wb') do |io|
specs = index.map do |*spec|
# We have to splat here because latest_specs is an array,
# while the others are hashes. See the TODO in source_index.rb
spec = spec.flatten.last
platform = spec.original_platform
# win32-api-1.0.4-x86-mswin32-60
unless String === platform then
alert_warning "Skipping invalid platform in gem: #{spec.full_name}"
next
end
platform = Gem::Platform::RUBY if platform.nil? or platform.empty?
[spec.name, spec.version, platform]
end
specs = compact_specs(specs)
Marshal.dump(specs, io)
end
end
end
##
# Builds indicies for RubyGems 1.2 and newer. Handles full, latest, prerelease
def build_modern_indicies(index)
build_modern_index(index.released_specs.sort, @specs_index, 'specs')
build_modern_index(index.latest_specs.sort,
@latest_specs_index,
'latest specs')
build_modern_index(index.prerelease_specs.sort,
@prerelease_specs_index,
'prerelease specs')
@files += [@specs_index,
"#{@specs_index}.gz",
@latest_specs_index,
"#{@latest_specs_index}.gz",
@prerelease_specs_index,
"#{@prerelease_specs_index}.gz"]
end
##
# Builds an RSS feed for past two days gem releases according to the gem's
# date.
def build_rss(index)
if @rss_host.nil? or @rss_gems_host.nil? then
if Gem.configuration.really_verbose then
alert_warning "no --rss-host or --rss-gems-host, RSS generation disabled"
end
return
end
require 'cgi'
require 'rubygems/text'
extend Gem::Text
Gem.time 'Generated rss' do
open @rss_index, 'wb' do |io|
rss_host = CGI.escapeHTML @rss_host
rss_title = CGI.escapeHTML(@rss_title || 'gems')
io.puts <<-HEADER
<?xml version="1.0"?>
<rss version="2.0">
<channel>
<title>#{rss_title}</title>
<link>http://#{rss_host}</link>
<description>Recently released gems from http://#{rss_host}</description>
<generator>RubyGems v#{Gem::RubyGemsVersion}</generator>
<docs>http://cyber.law.harvard.edu/rss/rss.html</docs>
HEADER
today = Gem::Specification::TODAY
yesterday = today - 86400
index = index.select do |_, spec|
spec_date = spec.date
case spec_date
when Date
Time.parse(spec_date.to_s) >= yesterday
when Time
spec_date >= yesterday
end
end
index = index.select do |_, spec|
spec_date = spec.date
case spec_date
when Date
Time.parse(spec_date.to_s) <= today
when Time
spec_date <= today
end
end
index.sort_by { |_, spec| [-spec.date.to_i, spec] }.each do |_, spec|
gem_path = CGI.escapeHTML "http://#{@rss_gems_host}/gems/#{spec.file_name}"
size = File.stat(spec.loaded_from).size rescue next
description = spec.description || spec.summary || ''
authors = Array spec.authors
emails = Array spec.email
authors = emails.zip(authors).map do |email, author|
email += " (#{author})" if author and not author.empty?
end.join ', '
description = description.split(/\n\n+/).map do |chunk|
format_text chunk, 78
end
description = description.join "\n\n"
item = ''
item << <<-ITEM
<item>
<title>#{CGI.escapeHTML spec.full_name}</title>
<description>
<pre>#{CGI.escapeHTML description.chomp}</pre>
</description>
<author>#{CGI.escapeHTML authors}</author>
<guid>#{CGI.escapeHTML spec.full_name}</guid>
<enclosure url=\"#{gem_path}\"
length=\"#{size}\" type=\"application/octet-stream\" />
<pubDate>#{spec.date.rfc2822}</pubDate>
ITEM
item << <<-ITEM if spec.homepage
<link>#{CGI.escapeHTML spec.homepage}</link>
ITEM
item << <<-ITEM
</item>
ITEM
io.puts item
end
io.puts <<-FOOTER
</channel>
</rss>
FOOTER
end
end
@files << @rss_index
end
##
# Collect specifications from .gem files from the gem directory.
def collect_specs(gems = gem_file_list)
index = Gem::SourceIndex.new
progress = ui.progress_reporter gems.size,
"Loading #{gems.size} gems from #{@dest_directory}",
"Loaded all gems"
Gem.time 'loaded' do
gems.each do |gemfile|
if File.size(gemfile.to_s) == 0 then
alert_warning "Skipping zero-length gem: #{gemfile}"
next
end
begin
spec = Gem::Format.from_file_by_path(gemfile).spec
spec.loaded_from = gemfile
unless gemfile =~ /\/#{Regexp.escape spec.original_name}.*\.gem\z/i then
expected_name = spec.full_name
expected_name << " (#{spec.original_name})" if
spec.original_name != spec.full_name
alert_warning "Skipping misnamed gem: #{gemfile} should be named #{expected_name}"
next
end
abbreviate spec
sanitize spec
index.add_spec spec, spec.original_name
progress.updated spec.original_name
rescue SignalException => e
alert_error "Received signal, exiting"
raise
rescue Exception => e
alert_error "Unable to process #{gemfile}\n#{e.message} (#{e.class})\n\t#{e.backtrace.join "\n\t"}"
end
end
progress.done
end
index
end
##
# Compresses indicies on disk
#--
# All future files should be compressed using gzip, not deflate
def compress_indicies
say "Compressing indicies"
Gem.time 'Compressed indicies' do
if @build_legacy then
compress @quick_index, 'rz'
paranoid @quick_index, 'rz'
compress @latest_index, 'rz'
paranoid @latest_index, 'rz'
compress @marshal_index, 'Z'
paranoid @marshal_index, 'Z'
compress @master_index, 'Z'
paranoid @master_index, 'Z'
end
if @build_modern then
gzip @specs_index
gzip @latest_specs_index
gzip @prerelease_specs_index
end
end
end
##
# Compacts Marshal output for the specs index data source by using identical
# objects as much as possible.
def compact_specs(specs)
names = {}
versions = {}
platforms = {}
specs.map do |(name, version, platform)|
names[name] = name unless names.include? name
versions[version] = version unless versions.include? version
platforms[platform] = platform unless platforms.include? platform
[names[name], versions[version], platforms[platform]]
end
end
##
# Compress +filename+ with +extension+.
def compress(filename, extension)
data = Gem.read_binary filename
zipped = Gem.deflate data
open "#{filename}.#{extension}", 'wb' do |io|
io.write zipped
end
end
##
# List of gem file names to index.
def gem_file_list
Dir.glob(File.join(@dest_directory, "gems", "*.gem"))
end
##
# Builds and installs indicies.
def generate_index
make_temp_directories
index = collect_specs
build_indicies index
install_indicies
rescue SignalException
ensure
FileUtils.rm_rf @directory
end
##
# Zlib::GzipWriter wrapper that gzips +filename+ on disk.
def gzip(filename)
Zlib::GzipWriter.open "#{filename}.gz" do |io|
io.write Gem.read_binary(filename)
end
end
##
# Install generated indicies into the destination directory.
def install_indicies
verbose = Gem.configuration.really_verbose
say "Moving index into production dir #{@dest_directory}" if verbose
files = @files.dup
files.delete @quick_marshal_dir if files.include? @quick_dir
if files.include? @quick_marshal_dir and
not files.include? @quick_dir then
files.delete @quick_marshal_dir
quick_marshal_dir = @quick_marshal_dir.sub @directory, ''
dst_name = File.join @dest_directory, quick_marshal_dir
FileUtils.mkdir_p File.dirname(dst_name), :verbose => verbose
FileUtils.rm_rf dst_name, :verbose => verbose
FileUtils.mv @quick_marshal_dir, dst_name, :verbose => verbose,
:force => true
end
files = files.map do |path|
path.sub @directory, ''
end
files.each do |file|
src_name = File.join @directory, file
dst_name = File.join @dest_directory, file
FileUtils.rm_rf dst_name, :verbose => verbose
FileUtils.mv src_name, @dest_directory, :verbose => verbose,
:force => true
end
end
##
# Make directories for index generation
def make_temp_directories
FileUtils.rm_rf @directory
FileUtils.mkdir_p @directory, :mode => 0700
FileUtils.mkdir_p @quick_marshal_dir
end
##
# Ensure +path+ and path with +extension+ are identical.
def paranoid(path, extension)
data = Gem.read_binary path
compressed_data = Gem.read_binary "#{path}.#{extension}"
unless data == Gem.inflate(compressed_data) then
raise "Compressed file #{compressed_path} does not match uncompressed file #{path}"
end
end
##
# Sanitize the descriptive fields in the spec. Sometimes non-ASCII
# characters will garble the site index. Non-ASCII characters will
# be replaced by their XML entity equivalent.
def sanitize(spec)
spec.summary = sanitize_string(spec.summary)
spec.description = sanitize_string(spec.description)
spec.post_install_message = sanitize_string(spec.post_install_message)
spec.authors = spec.authors.collect { |a| sanitize_string(a) }
spec
end
##
# Sanitize a single string.
def sanitize_string(string)
# HACK the #to_s is in here because RSpec has an Array of Arrays of
# Strings for authors. Need a way to disallow bad values on gempsec
# generation. (Probably won't happen.)
string ? string.to_s.to_xs : string
end
##
# Perform an in-place update of the repository from newly added gems. Only
# works for modern indicies, and sets #build_legacy to false when run.
def update_index
@build_legacy = false
make_temp_directories
specs_mtime = File.stat(@dest_specs_index).mtime
newest_mtime = Time.at 0
updated_gems = gem_file_list.select do |gem|
gem_mtime = File.stat(gem).mtime
newest_mtime = gem_mtime if gem_mtime > newest_mtime
gem_mtime >= specs_mtime
end
if updated_gems.empty? then
say 'No new gems'
terminate_interaction 0
end
index = collect_specs updated_gems
files = build_marshal_gemspecs index
Gem.time 'Updated indexes' do
update_specs_index index.released_gems, @dest_specs_index, @specs_index
update_specs_index index.released_gems, @dest_latest_specs_index, @latest_specs_index
update_specs_index(index.prerelease_gems, @dest_prerelease_specs_index,
@prerelease_specs_index)
end
compress_indicies
verbose = Gem.configuration.really_verbose
say "Updating production dir #{@dest_directory}" if verbose
files << @specs_index
files << "#{@specs_index}.gz"
files << @latest_specs_index
files << "#{@latest_specs_index}.gz"
files << @prerelease_specs_index
files << "#{@prerelease_specs_index}.gz"
files = files.map do |path|
path.sub @directory, ''
end
files.each do |file|
src_name = File.join @directory, file
dst_name = File.join @dest_directory, File.dirname(file)
FileUtils.mv src_name, dst_name, :verbose => verbose,
:force => true
File.utime newest_mtime, newest_mtime, dst_name
end
end
##
# Combines specs in +index+ and +source+ then writes out a new copy to
# +dest+. For a latest index, does not ensure the new file is minimal.
def update_specs_index(index, source, dest)
specs_index = Marshal.load Gem.read_binary(source)
index.each do |_, spec|
platform = spec.original_platform
platform = Gem::Platform::RUBY if platform.nil? or platform.empty?
specs_index << [spec.name, spec.version, platform]
end
specs_index = compact_specs specs_index.uniq.sort
open dest, 'wb' do |io|
Marshal.dump specs_index, io
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/dependency_list.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/dependency_list.rb | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'tsort'
##
# Gem::DependencyList is used for installing and uninstalling gems in the
# correct order to avoid conflicts.
class Gem::DependencyList
include Enumerable
include TSort
##
# Allows enabling/disabling use of development dependencies
attr_accessor :development
##
# Creates a DependencyList from a Gem::SourceIndex +source_index+
def self.from_source_index(source_index)
list = new
source_index.each do |full_name, spec|
list.add spec
end
list
end
##
# Creates a new DependencyList. If +development+ is true, development
# dependencies will be included.
def initialize development = false
@specs = []
@development = development
end
##
# Adds +gemspecs+ to the dependency list.
def add(*gemspecs)
@specs.push(*gemspecs)
end
##
# Return a list of the gem specifications in the dependency list, sorted in
# order so that no gemspec in the list depends on a gemspec earlier in the
# list.
#
# This is useful when removing gems from a set of installed gems. By
# removing them in the returned order, you don't get into as many dependency
# issues.
#
# If there are circular dependencies (yuck!), then gems will be returned in
# order until only the circular dependents and anything they reference are
# left. Then arbitrary gemspecs will be returned until the circular
# dependency is broken, after which gems will be returned in dependency
# order again.
def dependency_order
sorted = strongly_connected_components.flatten
result = []
seen = {}
sorted.each do |spec|
if index = seen[spec.name] then
if result[index].version < spec.version then
result[index] = spec
end
else
seen[spec.name] = result.length
result << spec
end
end
result.reverse
end
##
# Iterator over dependency_order
def each(&block)
dependency_order.each(&block)
end
def find_name(full_name)
@specs.find { |spec| spec.full_name == full_name }
end
def inspect # :nodoc:
"#<%s:0x%x %p>" % [self.class, object_id, map { |s| s.full_name }]
end
##
# Are all the dependencies in the list satisfied?
def ok?
@specs.all? do |spec|
spec.runtime_dependencies.all? do |dep|
@specs.find { |s| s.satisfies_requirement? dep }
end
end
end
##
# Is is ok to remove a gemspec from the dependency list?
#
# If removing the gemspec creates breaks a currently ok dependency, then it
# is NOT ok to remove the gemspec.
def ok_to_remove?(full_name)
gem_to_remove = find_name full_name
siblings = @specs.find_all { |s|
s.name == gem_to_remove.name &&
s.full_name != gem_to_remove.full_name
}
deps = []
@specs.each do |spec|
spec.dependencies.each do |dep|
deps << dep if gem_to_remove.satisfies_requirement?(dep)
end
end
deps.all? { |dep|
siblings.any? { |s|
s.satisfies_requirement? dep
}
}
end
##
# Removes the gemspec matching +full_name+ from the dependency list
def remove_by_name(full_name)
@specs.delete_if { |spec| spec.full_name == full_name }
end
##
# Return a hash of predecessors. <tt>result[spec]</tt> is an Array of
# gemspecs that have a dependency satisfied by the named gemspec.
def spec_predecessors
result = Hash.new { |h,k| h[k] = [] }
specs = @specs.sort.reverse
specs.each do |spec|
specs.each do |other|
next if spec == other
other.dependencies.each do |dep|
if spec.satisfies_requirement? dep then
result[spec] << other
end
end
end
end
result
end
def tsort_each_node(&block)
@specs.each(&block)
end
def tsort_each_child(node, &block)
specs = @specs.sort.reverse
dependencies = node.runtime_dependencies
dependencies.push(*node.development_dependencies) if @development
dependencies.each do |dep|
specs.each do |spec|
if spec.satisfies_requirement? dep then
begin
yield spec
rescue TSort::Cyclic
end
break
end
end
end
end
private
##
# Count the number of gemspecs in the list +specs+ that are not in
# +ignored+.
def active_count(specs, ignored)
result = 0
specs.each do |spec|
result += 1 unless ignored[spec.full_name]
end
result
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/doc_manager.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/doc_manager.rb | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'fileutils'
require 'rubygems'
##
# The documentation manager generates RDoc and RI for RubyGems.
class Gem::DocManager
include Gem::UserInteraction
@configured_args = []
def self.configured_args
@configured_args ||= []
end
def self.configured_args=(args)
case args
when Array
@configured_args = args
when String
@configured_args = args.split
end
end
##
# Load RDoc from a gem if it is available, otherwise from Ruby's stdlib
def self.load_rdoc
begin
gem 'rdoc'
rescue Gem::LoadError
# use built-in RDoc
end
begin
require 'rdoc/rdoc'
@rdoc_version = if defined? RDoc::VERSION then
Gem::Version.new RDoc::VERSION
else
Gem::Version.new '1.0.1' # HACK parsing is hard
end
rescue LoadError => e
raise Gem::DocumentError,
"ERROR: RDoc documentation generator not installed: #{e}"
end
end
def self.rdoc_version
@rdoc_version
end
##
# Updates the RI cache for RDoc 2 if it is installed
def self.update_ri_cache
load_rdoc rescue return
return unless defined? RDoc::VERSION # RDoc 1 does not have VERSION
require 'rdoc/ri/driver'
options = {
:use_cache => true,
:use_system => true,
:use_site => true,
:use_home => true,
:use_gems => true,
:formatter => RDoc::RI::Formatter,
}
driver = RDoc::RI::Driver.new(options).class_cache
end
##
# Create a document manager for +spec+. +rdoc_args+ contains arguments for
# RDoc (template etc.) as a String.
def initialize(spec, rdoc_args="")
@spec = spec
@doc_dir = File.join(spec.installation_path, "doc", spec.full_name)
@rdoc_args = rdoc_args.nil? ? [] : rdoc_args.split
end
##
# Is the RDoc documentation installed?
def rdoc_installed?
File.exist?(File.join(@doc_dir, "rdoc"))
end
##
# Is the RI documentation installed?
def ri_installed?
File.exist?(File.join(@doc_dir, "ri"))
end
##
# Generate the RI documents for this gem spec.
#
# Note that if both RI and RDoc documents are generated from the same
# process, the RI docs should be done first (a likely bug in RDoc will cause
# RI docs generation to fail if run after RDoc).
def generate_ri
setup_rdoc
install_ri # RDoc bug, ri goes first
FileUtils.mkdir_p @doc_dir unless File.exist?(@doc_dir)
end
##
# Generate the RDoc documents for this gem spec.
#
# Note that if both RI and RDoc documents are generated from the same
# process, the RI docs should be done first (a likely bug in RDoc will cause
# RI docs generation to fail if run after RDoc).
def generate_rdoc
setup_rdoc
install_rdoc
FileUtils.mkdir_p @doc_dir unless File.exist?(@doc_dir)
end
##
# Generate and install RDoc into the documentation directory
def install_rdoc
rdoc_dir = File.join @doc_dir, 'rdoc'
FileUtils.rm_rf rdoc_dir
say "Installing RDoc documentation for #{@spec.full_name}..."
run_rdoc '--op', rdoc_dir
end
##
# Generate and install RI into the documentation directory
def install_ri
ri_dir = File.join @doc_dir, 'ri'
FileUtils.rm_rf ri_dir
say "Installing ri documentation for #{@spec.full_name}..."
run_rdoc '--ri', '--op', ri_dir
end
##
# Run RDoc with +args+, which is an ARGV style argument list
def run_rdoc(*args)
args << @spec.rdoc_options
args << self.class.configured_args
args << '--quiet'
args << @spec.require_paths.clone
args << @spec.extra_rdoc_files
args << '--title' << "#{@spec.full_name} Documentation"
args = args.flatten.map do |arg| arg.to_s end
if self.class.rdoc_version >= Gem::Version.new('2.4.0') then
args.delete '--inline-source'
args.delete '--promiscuous'
args.delete '-p'
args.delete '--one-file'
# HACK more
end
r = RDoc::RDoc.new
old_pwd = Dir.pwd
Dir.chdir(@spec.full_gem_path)
begin
r.document args
rescue Errno::EACCES => e
dirname = File.dirname e.message.split("-")[1].strip
raise Gem::FilePermissionError.new(dirname)
rescue RuntimeError => ex
alert_error "While generating documentation for #{@spec.full_name}"
ui.errs.puts "... MESSAGE: #{ex}"
ui.errs.puts "... RDOC args: #{args.join(' ')}"
ui.errs.puts "\t#{ex.backtrace.join "\n\t"}" if
Gem.configuration.backtrace
ui.errs.puts "(continuing with the rest of the installation)"
ensure
Dir.chdir(old_pwd)
end
end
def setup_rdoc
if File.exist?(@doc_dir) && !File.writable?(@doc_dir) then
raise Gem::FilePermissionError.new(@doc_dir)
end
FileUtils.mkdir_p @doc_dir unless File.exist?(@doc_dir)
self.class.load_rdoc
end
##
# Remove RDoc and RI documentation
def uninstall_doc
raise Gem::FilePermissionError.new(@spec.installation_path) unless
File.writable? @spec.installation_path
original_name = [
@spec.name, @spec.version, @spec.original_platform].join '-'
doc_dir = File.join @spec.installation_path, 'doc', @spec.full_name
unless File.directory? doc_dir then
doc_dir = File.join @spec.installation_path, 'doc', original_name
end
FileUtils.rm_rf doc_dir
ri_dir = File.join @spec.installation_path, 'ri', @spec.full_name
unless File.directory? ri_dir then
ri_dir = File.join @spec.installation_path, 'ri', original_name
end
FileUtils.rm_rf ri_dir
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/dependency_installer.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/dependency_installer.rb | require 'rubygems'
require 'rubygems/dependency_list'
require 'rubygems/installer'
require 'rubygems/spec_fetcher'
require 'rubygems/user_interaction'
##
# Installs a gem along with all its dependencies from local and remote gems.
class Gem::DependencyInstaller
include Gem::UserInteraction
attr_reader :gems_to_install
attr_reader :installed_gems
DEFAULT_OPTIONS = {
:env_shebang => false,
:domain => :both, # HACK dup
:force => false,
:format_executable => false, # HACK dup
:ignore_dependencies => false,
:prerelease => false,
:security_policy => nil, # HACK NoSecurity requires OpenSSL. AlmostNo? Low?
:wrappers => true,
}
##
# Creates a new installer instance.
#
# Options are:
# :cache_dir:: Alternate repository path to store .gem files in.
# :domain:: :local, :remote, or :both. :local only searches gems in the
# current directory. :remote searches only gems in Gem::sources.
# :both searches both.
# :env_shebang:: See Gem::Installer::new.
# :force:: See Gem::Installer#install.
# :format_executable:: See Gem::Installer#initialize.
# :ignore_dependencies:: Don't install any dependencies.
# :install_dir:: See Gem::Installer#install.
# :prerelease:: Allow prerelease versions. See #install.
# :security_policy:: See Gem::Installer::new and Gem::Security.
# :user_install:: See Gem::Installer.new
# :wrappers:: See Gem::Installer::new
def initialize(options = {})
if options[:install_dir] then
spec_dir = options[:install_dir], 'specifications'
@source_index = Gem::SourceIndex.from_gems_in spec_dir
else
@source_index = Gem.source_index
end
options = DEFAULT_OPTIONS.merge options
@bin_dir = options[:bin_dir]
@development = options[:development]
@domain = options[:domain]
@env_shebang = options[:env_shebang]
@force = options[:force]
@format_executable = options[:format_executable]
@ignore_dependencies = options[:ignore_dependencies]
@prerelease = options[:prerelease]
@security_policy = options[:security_policy]
@user_install = options[:user_install]
@wrappers = options[:wrappers]
@installed_gems = []
@install_dir = options[:install_dir] || Gem.dir
@cache_dir = options[:cache_dir] || @install_dir
end
##
# Returns a list of pairs of gemspecs and source_uris that match
# Gem::Dependency +dep+ from both local (Dir.pwd) and remote (Gem.sources)
# sources. Gems are sorted with newer gems prefered over older gems, and
# local gems preferred over remote gems.
def find_gems_with_sources(dep)
gems_and_sources = []
if @domain == :both or @domain == :local then
Dir[File.join(Dir.pwd, "#{dep.name}-[0-9]*.gem")].each do |gem_file|
spec = Gem::Format.from_file_by_path(gem_file).spec
gems_and_sources << [spec, gem_file] if spec.name == dep.name
end
end
if @domain == :both or @domain == :remote then
begin
requirements = dep.requirement.requirements.map do |req, ver|
req
end
all = !dep.prerelease? &&
# we only need latest if there's one requirement and it is
# guaranteed to match the newest specs
(requirements.length > 1 or
(requirements.first != ">=" and requirements.first != ">"))
found = Gem::SpecFetcher.fetcher.fetch dep, all, true, dep.prerelease?
gems_and_sources.push(*found)
rescue Gem::RemoteFetcher::FetchError => e
if Gem.configuration.really_verbose then
say "Error fetching remote data:\t\t#{e.message}"
say "Falling back to local-only install"
end
@domain = :local
end
end
gems_and_sources.sort_by do |gem, source|
[gem, source =~ /^http:\/\// ? 0 : 1] # local gems win
end
end
##
# Gathers all dependencies necessary for the installation from local and
# remote sources unless the ignore_dependencies was given.
def gather_dependencies
specs = @specs_and_sources.map { |spec,_| spec }
dependency_list = Gem::DependencyList.new @development
dependency_list.add(*specs)
unless @ignore_dependencies then
to_do = specs.dup
seen = {}
until to_do.empty? do
spec = to_do.shift
next if spec.nil? or seen[spec.name]
seen[spec.name] = true
deps = spec.runtime_dependencies
deps |= spec.development_dependencies if @development
deps.each do |dep|
results = find_gems_with_sources(dep).reverse
results.reject! do |dep_spec,|
to_do.push dep_spec
@source_index.any? do |_, installed_spec|
dep.name == installed_spec.name and
dep.requirement.satisfied_by? installed_spec.version
end
end
results.each do |dep_spec, source_uri|
next if seen[dep_spec.name]
@specs_and_sources << [dep_spec, source_uri]
dependency_list.add dep_spec
end
end
end
end
@gems_to_install = dependency_list.dependency_order.reverse
end
##
# Finds a spec and the source_uri it came from for gem +gem_name+ and
# +version+. Returns an Array of specs and sources required for
# installation of the gem.
def find_spec_by_name_and_version(gem_name,
version = Gem::Requirement.default,
prerelease = false)
spec_and_source = nil
glob = if File::ALT_SEPARATOR then
gem_name.gsub File::ALT_SEPARATOR, File::SEPARATOR
else
gem_name
end
local_gems = Dir["#{glob}*"].sort.reverse
unless local_gems.empty? then
local_gems.each do |gem_file|
next unless gem_file =~ /gem$/
begin
spec = Gem::Format.from_file_by_path(gem_file).spec
spec_and_source = [spec, gem_file]
break
rescue SystemCallError, Gem::Package::FormatError
end
end
end
if spec_and_source.nil? then
dep = Gem::Dependency.new gem_name, version
dep.prerelease = true if prerelease
spec_and_sources = find_gems_with_sources(dep).reverse
spec_and_source = spec_and_sources.find { |spec, source|
Gem::Platform.match spec.platform
}
end
if spec_and_source.nil? then
raise Gem::GemNotFoundException,
"could not find gem #{gem_name} locally or in a repository"
end
@specs_and_sources = [spec_and_source]
end
##
# Installs the gem +dep_or_name+ and all its dependencies. Returns an Array
# of installed gem specifications.
#
# If the +:prerelease+ option is set and there is a prerelease for
# +dep_or_name+ the prerelease version will be installed.
#
# Unless explicitly specified as a prerelease dependency, prerelease gems
# that +dep_or_name+ depend on will not be installed.
#
# If c-1.a depends on b-1 and a-1.a and there is a gem b-1.a available then
# c-1.a, b-1 and a-1.a will be installed. b-1.a will need to be installed
# separately.
def install dep_or_name, version = Gem::Requirement.default
if String === dep_or_name then
find_spec_by_name_and_version dep_or_name, version, @prerelease
else
dep_or_name.prerelease = @prerelease
@specs_and_sources = [find_gems_with_sources(dep_or_name).last]
end
@installed_gems = []
gather_dependencies
@gems_to_install.each do |spec|
last = spec == @gems_to_install.last
# HACK is this test for full_name acceptable?
next if @source_index.any? { |n,_| n == spec.full_name } and not last
# TODO: make this sorta_verbose so other users can benefit from it
say "Installing gem #{spec.full_name}" if Gem.configuration.really_verbose
_, source_uri = @specs_and_sources.assoc spec
begin
local_gem_path = Gem::RemoteFetcher.fetcher.download spec, source_uri,
@cache_dir
rescue Gem::RemoteFetcher::FetchError
next if @force
raise
end
inst = Gem::Installer.new local_gem_path,
:bin_dir => @bin_dir,
:development => @development,
:env_shebang => @env_shebang,
:force => @force,
:format_executable => @format_executable,
:ignore_dependencies => @ignore_dependencies,
:install_dir => @install_dir,
:security_policy => @security_policy,
:source_index => @source_index,
:user_install => @user_install,
:wrappers => @wrappers
spec = inst.install
@installed_gems << spec
end
@installed_gems
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/server.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/server.rb | require 'webrick'
require 'yaml'
require 'zlib'
require 'erb'
require 'rubygems'
require 'rubygems/doc_manager'
##
# Gem::Server and allows users to serve gems for consumption by
# `gem --remote-install`.
#
# gem_server starts an HTTP server on the given port and serves the following:
# * "/" - Browsing of gem spec files for installed gems
# * "/specs.#{Gem.marshal_version}.gz" - specs name/version/platform index
# * "/latest_specs.#{Gem.marshal_version}.gz" - latest specs
# name/version/platform index
# * "/quick/" - Individual gemspecs
# * "/gems" - Direct access to download the installable gems
# * "/rdoc?q=" - Search for installed rdoc documentation
# * legacy indexes:
# * "/Marshal.#{Gem.marshal_version}" - Full SourceIndex dump of metadata
# for installed gems
# * "/yaml" - YAML dump of metadata for installed gems - deprecated
#
# == Usage
#
# gem_server = Gem::Server.new Gem.dir, 8089, false
# gem_server.run
#
#--
# TODO Refactor into a real WEBrick servlet to remove code duplication.
class Gem::Server
include ERB::Util
include Gem::UserInteraction
SEARCH = <<-SEARCH
<form class="headerSearch" name="headerSearchForm" method="get" action="/rdoc">
<div id="search" style="float:right">
<label for="q">Filter/Search</label>
<input id="q" type="text" style="width:10em" name="q">
<button type="submit" style="display:none"></button>
</div>
</form>
SEARCH
DOC_TEMPLATE = <<-'DOC_TEMPLATE'
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>RubyGems Documentation Index</title>
<link rel="stylesheet" href="gem-server-rdoc-style.css" type="text/css" media="screen" />
</head>
<body>
<div id="fileHeader">
<%= SEARCH %>
<h1>RubyGems Documentation Index</h1>
</div>
<!-- banner header -->
<div id="bodyContent">
<div id="contextContent">
<div id="description">
<h1>Summary</h1>
<p>There are <%=values["gem_count"]%> gems installed:</p>
<p>
<%= values["specs"].map { |v| "<a href=\"##{v["name"]}\">#{v["name"]}</a>" }.join ', ' %>.
<h1>Gems</h1>
<dl>
<% values["specs"].each do |spec| %>
<dt>
<% if spec["first_name_entry"] then %>
<a name="<%=spec["name"]%>"></a>
<% end %>
<b><%=spec["name"]%> <%=spec["version"]%></b>
<% if spec["rdoc_installed"] then %>
<a href="<%=spec["doc_path"]%>">[rdoc]</a>
<% else %>
<span title="rdoc not installed">[rdoc]</span>
<% end %>
<% if spec["homepage"] then %>
<a href="<%=spec["homepage"]%>" title="<%=spec["homepage"]%>">[www]</a>
<% else %>
<span title="no homepage available">[www]</span>
<% end %>
<% if spec["has_deps"] then %>
- depends on
<%= spec["dependencies"].map { |v| "<a href=\"##{v["name"]}\">#{v["name"]}</a>" }.join ', ' %>.
<% end %>
</dt>
<dd>
<%=spec["summary"]%>
<% if spec["executables"] then %>
<br/>
<% if spec["only_one_executable"] then %>
Executable is
<% else %>
Executables are
<%end%>
<%= spec["executables"].map { |v| "<span class=\"context-item-name\">#{v["executable"]}</span>"}.join ', ' %>.
<%end%>
<br/>
<br/>
</dd>
<% end %>
</dl>
</div>
</div>
</div>
<div id="validator-badges">
<p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
</div>
</body>
</html>
DOC_TEMPLATE
# CSS is copy & paste from rdoc-style.css, RDoc V1.0.1 - 20041108
RDOC_CSS = <<-RDOC_CSS
body {
font-family: Verdana,Arial,Helvetica,sans-serif;
font-size: 90%;
margin: 0;
margin-left: 40px;
padding: 0;
background: white;
}
h1,h2,h3,h4 { margin: 0; color: #efefef; background: transparent; }
h1 { font-size: 150%; }
h2,h3,h4 { margin-top: 1em; }
a { background: #eef; color: #039; text-decoration: none; }
a:hover { background: #039; color: #eef; }
/* Override the base stylesheets Anchor inside a table cell */
td > a {
background: transparent;
color: #039;
text-decoration: none;
}
/* and inside a section title */
.section-title > a {
background: transparent;
color: #eee;
text-decoration: none;
}
/* === Structural elements =================================== */
div#index {
margin: 0;
margin-left: -40px;
padding: 0;
font-size: 90%;
}
div#index a {
margin-left: 0.7em;
}
div#index .section-bar {
margin-left: 0px;
padding-left: 0.7em;
background: #ccc;
font-size: small;
}
div#classHeader, div#fileHeader {
width: auto;
color: white;
padding: 0.5em 1.5em 0.5em 1.5em;
margin: 0;
margin-left: -40px;
border-bottom: 3px solid #006;
}
div#classHeader a, div#fileHeader a {
background: inherit;
color: white;
}
div#classHeader td, div#fileHeader td {
background: inherit;
color: white;
}
div#fileHeader {
background: #057;
}
div#classHeader {
background: #048;
}
.class-name-in-header {
font-size: 180%;
font-weight: bold;
}
div#bodyContent {
padding: 0 1.5em 0 1.5em;
}
div#description {
padding: 0.5em 1.5em;
background: #efefef;
border: 1px dotted #999;
}
div#description h1,h2,h3,h4,h5,h6 {
color: #125;;
background: transparent;
}
div#validator-badges {
text-align: center;
}
div#validator-badges img { border: 0; }
div#copyright {
color: #333;
background: #efefef;
font: 0.75em sans-serif;
margin-top: 5em;
margin-bottom: 0;
padding: 0.5em 2em;
}
/* === Classes =================================== */
table.header-table {
color: white;
font-size: small;
}
.type-note {
font-size: small;
color: #DEDEDE;
}
.xxsection-bar {
background: #eee;
color: #333;
padding: 3px;
}
.section-bar {
color: #333;
border-bottom: 1px solid #999;
margin-left: -20px;
}
.section-title {
background: #79a;
color: #eee;
padding: 3px;
margin-top: 2em;
margin-left: -30px;
border: 1px solid #999;
}
.top-aligned-row { vertical-align: top }
.bottom-aligned-row { vertical-align: bottom }
/* --- Context section classes ----------------------- */
.context-row { }
.context-item-name { font-family: monospace; font-weight: bold; color: black; }
.context-item-value { font-size: small; color: #448; }
.context-item-desc { color: #333; padding-left: 2em; }
/* --- Method classes -------------------------- */
.method-detail {
background: #efefef;
padding: 0;
margin-top: 0.5em;
margin-bottom: 1em;
border: 1px dotted #ccc;
}
.method-heading {
color: black;
background: #ccc;
border-bottom: 1px solid #666;
padding: 0.2em 0.5em 0 0.5em;
}
.method-signature { color: black; background: inherit; }
.method-name { font-weight: bold; }
.method-args { font-style: italic; }
.method-description { padding: 0 0.5em 0 0.5em; }
/* --- Source code sections -------------------- */
a.source-toggle { font-size: 90%; }
div.method-source-code {
background: #262626;
color: #ffdead;
margin: 1em;
padding: 0.5em;
border: 1px dashed #999;
overflow: hidden;
}
div.method-source-code pre { color: #ffdead; overflow: hidden; }
/* --- Ruby keyword styles --------------------- */
.standalone-code { background: #221111; color: #ffdead; overflow: hidden; }
.ruby-constant { color: #7fffd4; background: transparent; }
.ruby-keyword { color: #00ffff; background: transparent; }
.ruby-ivar { color: #eedd82; background: transparent; }
.ruby-operator { color: #00ffee; background: transparent; }
.ruby-identifier { color: #ffdead; background: transparent; }
.ruby-node { color: #ffa07a; background: transparent; }
.ruby-comment { color: #b22222; font-weight: bold; background: transparent; }
.ruby-regexp { color: #ffa07a; background: transparent; }
.ruby-value { color: #7fffd4; background: transparent; }
RDOC_CSS
RDOC_NO_DOCUMENTATION = <<-'NO_DOC'
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Found documentation</title>
<link rel="stylesheet" href="gem-server-rdoc-style.css" type="text/css" media="screen" />
</head>
<body>
<div id="fileHeader">
<%= SEARCH %>
<h1>No documentation found</h1>
</div>
<div id="bodyContent">
<div id="contextContent">
<div id="description">
<p>No gems matched <%= h query.inspect %></p>
<p>
Back to <a href="/">complete gem index</a>
</p>
</div>
</div>
</div>
<div id="validator-badges">
<p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
</div>
</body>
</html>
NO_DOC
RDOC_SEARCH_TEMPLATE = <<-'RDOC_SEARCH'
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Found documentation</title>
<link rel="stylesheet" href="gem-server-rdoc-style.css" type="text/css" media="screen" />
</head>
<body>
<div id="fileHeader">
<%= SEARCH %>
<h1>Found documentation</h1>
</div>
<!-- banner header -->
<div id="bodyContent">
<div id="contextContent">
<div id="description">
<h1>Summary</h1>
<p><%=doc_items.length%> documentation topics found.</p>
<h1>Topics</h1>
<dl>
<% doc_items.each do |doc_item| %>
<dt>
<b><%=doc_item[:name]%></b>
<a href="<%=doc_item[:url]%>">[rdoc]</a>
</dt>
<dd>
<%=doc_item[:summary]%>
<br/>
<br/>
</dd>
<% end %>
</dl>
<p>
Back to <a href="/">complete gem index</a>
</p>
</div>
</div>
</div>
<div id="validator-badges">
<p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
</div>
</body>
</html>
RDOC_SEARCH
def self.run(options)
new(options[:gemdir], options[:port], options[:daemon],
options[:addresses]).run
end
def initialize(gem_dir, port, daemon, addresses = nil)
Socket.do_not_reverse_lookup = true
@gem_dir = gem_dir
@port = port
@daemon = daemon
@addresses = addresses
logger = WEBrick::Log.new nil, WEBrick::BasicLog::FATAL
@server = WEBrick::HTTPServer.new :DoNotListen => true, :Logger => logger
@spec_dir = File.join @gem_dir, 'specifications'
unless File.directory? @spec_dir then
raise ArgumentError, "#{@gem_dir} does not appear to be a gem repository"
end
@source_index = Gem::SourceIndex.from_gems_in @spec_dir
end
def Marshal(req, res)
@source_index.refresh!
res['date'] = File.stat(@spec_dir).mtime
index = Marshal.dump @source_index
if req.request_method == 'HEAD' then
res['content-length'] = index.length
return
end
if req.path =~ /Z$/ then
res['content-type'] = 'application/x-deflate'
index = Gem.deflate index
else
res['content-type'] = 'application/octet-stream'
end
res.body << index
end
def latest_specs(req, res)
@source_index.refresh!
res['content-type'] = 'application/x-gzip'
res['date'] = File.stat(@spec_dir).mtime
specs = @source_index.latest_specs.sort.map do |spec|
platform = spec.original_platform
platform = Gem::Platform::RUBY if platform.nil?
[spec.name, spec.version, platform]
end
specs = Marshal.dump specs
if req.path =~ /\.gz$/ then
specs = Gem.gzip specs
res['content-type'] = 'application/x-gzip'
else
res['content-type'] = 'application/octet-stream'
end
if req.request_method == 'HEAD' then
res['content-length'] = specs.length
else
res.body << specs
end
end
##
# Creates server sockets based on the addresses option. If no addresses
# were given a server socket for all interfaces is created.
def listen addresses = @addresses
addresses = [nil] unless addresses
listeners = 0
addresses.each do |address|
begin
@server.listen address, @port
@server.listeners[listeners..-1].each do |listener|
host, port = listener.addr.values_at 2, 1
host = "[#{host}]" if host =~ /:/ # we don't reverse lookup
say "Server started at http://#{host}:#{port}"
end
listeners = @server.listeners.length
rescue SystemCallError
next
end
end
if @server.listeners.empty? then
say "Unable to start a server."
say "Check for running servers or your --bind and --port arguments"
terminate_interaction 1
end
end
def quick(req, res)
@source_index.refresh!
res['content-type'] = 'text/plain'
res['date'] = File.stat(@spec_dir).mtime
case req.request_uri.path
when '/quick/index' then
res.body << @source_index.map { |name,| name }.sort.join("\n")
when '/quick/index.rz' then
index = @source_index.map { |name,| name }.sort.join("\n")
res['content-type'] = 'application/x-deflate'
res.body << Gem.deflate(index)
when '/quick/latest_index' then
index = @source_index.latest_specs.map { |spec| spec.full_name }
res.body << index.sort.join("\n")
when '/quick/latest_index.rz' then
index = @source_index.latest_specs.map { |spec| spec.full_name }
res['content-type'] = 'application/x-deflate'
res.body << Gem.deflate(index.sort.join("\n"))
when %r|^/quick/(Marshal.#{Regexp.escape Gem.marshal_version}/)?(.*?)-([0-9.]+)(-.*?)?\.gemspec\.rz$| then
dep = Gem::Dependency.new $2, $3
specs = @source_index.search dep
marshal_format = $1
selector = [$2, $3, $4].map { |s| s.inspect }.join ' '
platform = if $4 then
Gem::Platform.new $4.sub(/^-/, '')
else
Gem::Platform::RUBY
end
specs = specs.select { |s| s.platform == platform }
if specs.empty? then
res.status = 404
res.body = "No gems found matching #{selector}"
elsif specs.length > 1 then
res.status = 500
res.body = "Multiple gems found matching #{selector}"
elsif marshal_format then
res['content-type'] = 'application/x-deflate'
res.body << Gem.deflate(Marshal.dump(specs.first))
else # deprecated YAML format
res['content-type'] = 'application/x-deflate'
res.body << Gem.deflate(specs.first.to_yaml)
end
else
raise WEBrick::HTTPStatus::NotFound, "`#{req.path}' not found."
end
end
def root(req, res)
@source_index.refresh!
res['date'] = File.stat(@spec_dir).mtime
raise WEBrick::HTTPStatus::NotFound, "`#{req.path}' not found." unless
req.path == '/'
specs = []
total_file_count = 0
@source_index.each do |path, spec|
total_file_count += spec.files.size
deps = spec.dependencies.map do |dep|
{ "name" => dep.name,
"type" => dep.type,
"version" => dep.requirement.to_s, }
end
deps = deps.sort_by { |dep| [dep["name"].downcase, dep["version"]] }
deps.last["is_last"] = true unless deps.empty?
# executables
executables = spec.executables.sort.collect { |exec| {"executable" => exec} }
executables = nil if executables.empty?
executables.last["is_last"] = true if executables
specs << {
"authors" => spec.authors.sort.join(", "),
"date" => spec.date.to_s,
"dependencies" => deps,
"doc_path" => "/doc_root/#{spec.full_name}/rdoc/index.html",
"executables" => executables,
"only_one_executable" => (executables && executables.size == 1),
"full_name" => spec.full_name,
"has_deps" => !deps.empty?,
"homepage" => spec.homepage,
"name" => spec.name,
"rdoc_installed" => Gem::DocManager.new(spec).rdoc_installed?,
"summary" => spec.summary,
"version" => spec.version.to_s,
}
end
specs << {
"authors" => "Chad Fowler, Rich Kilmer, Jim Weirich, Eric Hodel and others",
"dependencies" => [],
"doc_path" => "/doc_root/rubygems-#{Gem::RubyGemsVersion}/rdoc/index.html",
"executables" => [{"executable" => 'gem', "is_last" => true}],
"only_one_executable" => true,
"full_name" => "rubygems-#{Gem::RubyGemsVersion}",
"has_deps" => false,
"homepage" => "http://docs.rubygems.org/",
"name" => 'rubygems',
"rdoc_installed" => true,
"summary" => "RubyGems itself",
"version" => Gem::RubyGemsVersion,
}
specs = specs.sort_by { |spec| [spec["name"].downcase, spec["version"]] }
specs.last["is_last"] = true
# tag all specs with first_name_entry
last_spec = nil
specs.each do |spec|
is_first = last_spec.nil? || (last_spec["name"].downcase != spec["name"].downcase)
spec["first_name_entry"] = is_first
last_spec = spec
end
# create page from template
template = ERB.new(DOC_TEMPLATE)
res['content-type'] = 'text/html'
values = { "gem_count" => specs.size.to_s, "specs" => specs,
"total_file_count" => total_file_count.to_s }
result = template.result binding
res.body = result
end
##
# Can be used for quick navigation to the rdoc documentation. You can then
# define a search shortcut for your browser. E.g. in Firefox connect
# 'shortcut:rdoc' to http://localhost:8808/rdoc?q=%s template. Then you can
# directly open the ActionPack documentation by typing 'rdoc actionp'. If
# there are multiple hits for the search term, they are presented as a list
# with links.
#
# Search algorithm aims for an intuitive search:
# 1. first try to find the gems and documentation folders which name
# starts with the search term
# 2. search for entries, that *contain* the search term
# 3. show all the gems
#
# If there is only one search hit, user is immediately redirected to the
# documentation for the particular gem, otherwise a list with results is
# shown.
#
# === Additional trick - install documentation for ruby core
#
# Note: please adjust paths accordingly use for example 'locate yaml.rb' and
# 'gem environment' to identify directories, that are specific for your
# local installation
#
# 1. install ruby sources
# cd /usr/src
# sudo apt-get source ruby
#
# 2. generate documentation
# rdoc -o /usr/lib/ruby/gems/1.8/doc/core/rdoc \
# /usr/lib/ruby/1.8 ruby1.8-1.8.7.72
#
# By typing 'rdoc core' you can now access the core documentation
def rdoc(req, res)
query = req.query['q']
show_rdoc_for_pattern("#{query}*", res) && return
show_rdoc_for_pattern("*#{query}*", res) && return
template = ERB.new RDOC_NO_DOCUMENTATION
res['content-type'] = 'text/html'
res.body = template.result binding
end
##
# Returns true and prepares http response, if rdoc for the requested gem
# name pattern was found.
#
# The search is based on the file system content, not on the gems metadata.
# This allows additional documentation folders like 'core' for the ruby core
# documentation - just put it underneath the main doc folder.
def show_rdoc_for_pattern(pattern, res)
found_gems = Dir.glob("#{@gem_dir}/doc/#{pattern}").select {|path|
File.exist? File.join(path, 'rdoc/index.html')
}
case found_gems.length
when 0
return false
when 1
new_path = File.basename(found_gems[0])
res.status = 302
res['Location'] = "/doc_root/#{new_path}/rdoc/index.html"
return true
else
doc_items = []
found_gems.each do |file_name|
base_name = File.basename(file_name)
doc_items << {
:name => base_name,
:url => "/doc_root/#{base_name}/rdoc/index.html",
:summary => ''
}
end
template = ERB.new(RDOC_SEARCH_TEMPLATE)
res['content-type'] = 'text/html'
result = template.result binding
res.body = result
return true
end
end
def run
listen
WEBrick::Daemon.start if @daemon
@server.mount_proc "/yaml", method(:yaml)
@server.mount_proc "/yaml.Z", method(:yaml)
@server.mount_proc "/Marshal.#{Gem.marshal_version}", method(:Marshal)
@server.mount_proc "/Marshal.#{Gem.marshal_version}.Z", method(:Marshal)
@server.mount_proc "/specs.#{Gem.marshal_version}", method(:specs)
@server.mount_proc "/specs.#{Gem.marshal_version}.gz", method(:specs)
@server.mount_proc "/latest_specs.#{Gem.marshal_version}",
method(:latest_specs)
@server.mount_proc "/latest_specs.#{Gem.marshal_version}.gz",
method(:latest_specs)
@server.mount_proc "/quick/", method(:quick)
@server.mount_proc("/gem-server-rdoc-style.css") do |req, res|
res['content-type'] = 'text/css'
res['date'] = File.stat(@spec_dir).mtime
res.body << RDOC_CSS
end
@server.mount_proc "/", method(:root)
@server.mount_proc "/rdoc", method(:rdoc)
paths = { "/gems" => "/cache/", "/doc_root" => "/doc/" }
paths.each do |mount_point, mount_dir|
@server.mount(mount_point, WEBrick::HTTPServlet::FileHandler,
File.join(@gem_dir, mount_dir), true)
end
trap("INT") { @server.shutdown; exit! }
trap("TERM") { @server.shutdown; exit! }
@server.start
end
def specs(req, res)
@source_index.refresh!
res['date'] = File.stat(@spec_dir).mtime
specs = @source_index.sort.map do |_, spec|
platform = spec.original_platform
platform = Gem::Platform::RUBY if platform.nil?
[spec.name, spec.version, platform]
end
specs = Marshal.dump specs
if req.path =~ /\.gz$/ then
specs = Gem.gzip specs
res['content-type'] = 'application/x-gzip'
else
res['content-type'] = 'application/octet-stream'
end
if req.request_method == 'HEAD' then
res['content-length'] = specs.length
else
res.body << specs
end
end
def yaml(req, res)
@source_index.refresh!
res['date'] = File.stat(@spec_dir).mtime
index = @source_index.to_yaml
if req.path =~ /Z$/ then
res['content-type'] = 'application/x-deflate'
index = Gem.deflate index
else
res['content-type'] = 'text/plain'
end
if req.request_method == 'HEAD' then
res['content-length'] = index.length
return
end
res.body << index
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/version_option.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/version_option.rb | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'rubygems'
##
# Mixin methods for --version and --platform Gem::Command options.
module Gem::VersionOption
##
# Add the --platform option to the option parser.
def add_platform_option(task = command, *wrap)
OptionParser.accept Gem::Platform do |value|
if value == Gem::Platform::RUBY then
value
else
Gem::Platform.new value
end
end
add_option('--platform PLATFORM', Gem::Platform,
"Specify the platform of gem to #{task}", *wrap) do
|value, options|
unless options[:added_platform] then
Gem.platforms = [Gem::Platform::RUBY]
options[:added_platform] = true
end
Gem.platforms << value unless Gem.platforms.include? value
end
end
##
# Add the --prerelease option to the option parser.
def add_prerelease_option(*wrap)
add_option("--[no-]prerelease",
"Allow prerelease versions of a gem", *wrap) do |value, options|
options[:prerelease] = value
end
end
##
# Add the --version option to the option parser.
def add_version_option(task = command, *wrap)
OptionParser.accept Gem::Requirement do |value|
Gem::Requirement.new value
end
add_option('-v', '--version VERSION', Gem::Requirement,
"Specify version of gem to #{task}", *wrap) do
|value, options|
options[:version] = value
options[:prerelease] = true if value.prerelease?
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/defaults.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/defaults.rb | module Gem
@post_install_hooks ||= []
@post_uninstall_hooks ||= []
@pre_uninstall_hooks ||= []
@pre_install_hooks ||= []
##
# An Array of the default sources that come with RubyGems
def self.default_sources
%w[http://rubygems.org/]
end
##
# Default home directory path to be used if an alternate value is not
# specified in the environment
def self.default_dir
if defined? RUBY_FRAMEWORK_VERSION then
File.join File.dirname(ConfigMap[:sitedir]), 'Gems',
ConfigMap[:ruby_version]
# 1.9.2dev reverted to 1.8 style path
elsif RUBY_VERSION > '1.9' and RUBY_VERSION < '1.9.2' then
File.join(ConfigMap[:libdir], ConfigMap[:ruby_install_name], 'gems',
ConfigMap[:ruby_version])
else
File.join(ConfigMap[:libdir], ruby_engine, 'gems',
ConfigMap[:ruby_version])
end
end
##
# Path for gems in the user's home directory
def self.user_dir
File.join(Gem.user_home, '.gem', ruby_engine,
ConfigMap[:ruby_version])
end
##
# Default gem load path
def self.default_path
if File.exist?(Gem.user_home)
[user_dir, default_dir]
else
[default_dir]
end
end
##
# Deduce Ruby's --program-prefix and --program-suffix from its install name
def self.default_exec_format
exec_format = ConfigMap[:ruby_install_name].sub('ruby', '%s') rescue '%s'
unless exec_format =~ /%s/ then
raise Gem::Exception,
"[BUG] invalid exec_format #{exec_format.inspect}, no %s"
end
exec_format
end
##
# The default directory for binaries
def self.default_bindir
if defined? RUBY_FRAMEWORK_VERSION then # mac framework support
'/usr/bin'
else # generic install
ConfigMap[:bindir]
end
end
##
# The default system-wide source info cache directory
def self.default_system_source_cache_dir
File.join Gem.dir, 'source_cache'
end
##
# The default user-specific source info cache directory
def self.default_user_source_cache_dir
File.join Gem.user_home, '.gem', 'source_cache'
end
##
# A wrapper around RUBY_ENGINE const that may not be defined
def self.ruby_engine
if defined? RUBY_ENGINE then
RUBY_ENGINE
else
'ruby'
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/builder.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/builder.rb | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
##
# The Builder class processes RubyGem specification files
# to produce a .gem file.
class Gem::Builder
include Gem::UserInteraction
##
# Constructs a builder instance for the provided specification
#
# spec:: [Gem::Specification] The specification instance
def initialize(spec)
require "yaml"
require "rubygems/package"
require "rubygems/security"
@spec = spec
end
##
# Builds the gem from the specification. Returns the name of the file
# written.
def build
@spec.mark_version
@spec.validate
@signer = sign
write_package
say success if Gem.configuration.verbose
@spec.file_name
end
def success
<<-EOM
Successfully built RubyGem
Name: #{@spec.name}
Version: #{@spec.version}
File: #{@spec.file_name}
EOM
end
private
##
# If the signing key was specified, then load the file, and swap to the
# public key (TODO: we should probably just omit the signing key in favor of
# the signing certificate, but that's for the future, also the signature
# algorithm should be configurable)
def sign
signer = nil
if @spec.respond_to?(:signing_key) and @spec.signing_key then
signer = Gem::Security::Signer.new @spec.signing_key, @spec.cert_chain
@spec.signing_key = nil
@spec.cert_chain = signer.cert_chain.map { |cert| cert.to_s }
end
signer
end
def write_package
open @spec.file_name, 'wb' do |gem_io|
Gem::Package.open gem_io, 'w', @signer do |pkg|
pkg.metadata = @spec.to_yaml
@spec.files.each do |file|
next if File.directory? file
next if file == @spec.file_name # Don't add gem onto itself
stat = File.stat file
mode = stat.mode & 0777
size = stat.size
pkg.add_file_simple file, mode, size do |tar_io|
tar_io.write open(file, "rb") { |f| f.read }
end
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/timer.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/timer.rb | #
# This file defines a $log variable for logging, and a time() method for
# recording timing information.
#
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'rubygems'
file, lineno = Gem.location_of_caller
warn "#{file}:#{lineno}:Warning: RubyGems' lib/rubygems/timer.rb deprecated and will be removed on or after June 2009."
$log = Object.new
# :stopdoc:
def $log.debug(message)
Gem.debug message
end
def time(msg, width=25, &block)
Gem.time(msg, width, &block)
end
# :startdoc:
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/test_utilities.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/test_utilities.rb | require 'tempfile'
require 'rubygems'
require 'rubygems/remote_fetcher'
##
# A fake Gem::RemoteFetcher for use in tests or to avoid real live HTTP
# requests when testing code that uses RubyGems.
#
# Example:
#
# @fetcher = Gem::FakeFetcher.new
# @fetcher.data['http://gems.example.com/yaml'] = source_index.to_yaml
# Gem::RemoteFetcher.fetcher = @fetcher
#
# # invoke RubyGems code
#
# paths = @fetcher.paths
# assert_equal 'http://gems.example.com/yaml', paths.shift
# assert paths.empty?, paths.join(', ')
#
# See RubyGems' tests for more examples of FakeFetcher.
class Gem::FakeFetcher
attr_reader :data
attr_reader :last_request
attr_accessor :paths
def initialize
@data = {}
@paths = []
end
def find_data(path)
path = path.to_s
@paths << path
raise ArgumentError, 'need full URI' unless path =~ %r'^https?://'
unless @data.key? path then
raise Gem::RemoteFetcher::FetchError.new("no data for #{path}", path)
end
@data[path]
end
def fetch_path path, mtime = nil
data = find_data(path)
if data.respond_to?(:call) then
data.call
else
if path.to_s =~ /gz$/ and not data.nil? and not data.empty? then
data = Gem.gunzip data
end
data
end
end
# Thanks, FakeWeb!
def open_uri_or_path(path)
data = find_data(path)
body, code, msg = data
response = Net::HTTPResponse.send(:response_class, code.to_s).new("1.0", code.to_s, msg)
response.instance_variable_set(:@body, body)
response.instance_variable_set(:@read, true)
response
end
def request(uri, request_class, last_modified = nil)
data = find_data(uri)
body, code, msg = data
@last_request = request_class.new uri.request_uri
yield @last_request if block_given?
response = Net::HTTPResponse.send(:response_class, code.to_s).new("1.0", code.to_s, msg)
response.instance_variable_set(:@body, body)
response.instance_variable_set(:@read, true)
response
end
def fetch_size(path)
path = path.to_s
@paths << path
raise ArgumentError, 'need full URI' unless path =~ %r'^http://'
unless @data.key? path then
raise Gem::RemoteFetcher::FetchError.new("no data for #{path}", path)
end
data = @data[path]
data.respond_to?(:call) ? data.call : data.length
end
def download spec, source_uri, install_dir = Gem.dir
name = spec.file_name
path = File.join(install_dir, 'cache', name)
Gem.ensure_gem_subdirectories install_dir
if source_uri =~ /^http/ then
File.open(path, "wb") do |f|
f.write fetch_path(File.join(source_uri, "gems", name))
end
else
FileUtils.cp source_uri, path
end
path
end
end
# :stopdoc:
class Gem::RemoteFetcher
def self.fetcher=(fetcher)
@fetcher = fetcher
end
end
# :startdoc:
##
# A StringIO duck-typed class that uses Tempfile instead of String as the
# backing store.
#--
# This class was added to flush out problems in Rubinius' IO implementation.
class TempIO
@@count = 0
def initialize(string = '')
@tempfile = Tempfile.new "TempIO-#{@@count += 1}"
@tempfile.binmode
@tempfile.write string
@tempfile.rewind
end
def method_missing(meth, *args, &block)
@tempfile.send(meth, *args, &block)
end
def respond_to?(meth)
@tempfile.respond_to? meth
end
def string
@tempfile.flush
Gem.read_binary @tempfile.path
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/dependency.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/dependency.rb | require "rubygems/requirement"
##
# The Dependency class holds a Gem name and a Gem::Requirement.
class Gem::Dependency
# :stopdoc:
@warned_version_requirement = false
def self.warned_version_requirement
@warned_version_requirement
end
def self.warned_version_requirement= value
@warned_version_requirement = value
end
# :startdoc:
##
# Valid dependency types.
#--
# When this list is updated, be sure to change
# Gem::Specification::CURRENT_SPECIFICATION_VERSION as well.
TYPES = [
:development,
:runtime,
]
##
# Dependency name or regular expression.
attr_accessor :name
##
# Allows you to force this dependency to be a prerelease.
attr_writer :prerelease
##
# Dependency type.
attr_reader :type
##
# Constructs a dependency with +name+ and +requirements+. The last
# argument can optionally be the dependency type, which defaults to
# <tt>:runtime</tt>.
def initialize name, *requirements
type = Symbol === requirements.last ? requirements.pop : :runtime
requirements = requirements.first if 1 == requirements.length # unpack
unless TYPES.include? type
raise ArgumentError, "Valid types are #{TYPES.inspect}, "
+ "not #{@type.inspect}"
end
@name = name
@requirement = Gem::Requirement.create requirements
@type = type
@prerelease = false
# This is for Marshal backwards compatability. See the comments in
# +requirement+ for the dirty details.
@version_requirements = @requirement
end
##
# What does this dependency require?
##
# A dependency's hash is the XOR of the hashes of +name+, +type+,
# and +requirement+.
def hash # :nodoc:
name.hash ^ type.hash ^ requirement.hash
end
def inspect # :nodoc:
"<%s type=%p name=%p requirements=%p>" %
[self.class, @type, @name, requirement.to_s]
end
##
# Does this dependency require a prerelease?
def prerelease?
@prerelease || requirement.prerelease?
end
def pretty_print(q) # :nodoc:
q.group 1, 'Gem::Dependency.new(', ')' do
q.pp name
q.text ','
q.breakable
q.pp requirement
q.text ','
q.breakable
q.pp type
end
end
def requirement
return @requirement if defined?(@requirement) and @requirement
# @version_requirements and @version_requirement are legacy ivar
# names, and supported here because older gems need to keep
# working and Dependency doesn't implement marshal_dump and
# marshal_load. In a happier world, this would be an
# attr_accessor. The horrifying instance_variable_get you see
# below is also the legacy of some old restructurings.
#
# Note also that because of backwards compatibility (loading new
# gems in an old RubyGems installation), we can't add explicit
# marshaling to this class until we want to make a big
# break. Maybe 2.0.
#
# Children, define explicit marshal and unmarshal behavior for
# public classes. Marshal formats are part of your public API.
if defined?(@version_requirement) && @version_requirement
version = @version_requirement.instance_variable_get :@version
@version_requirement = nil
@version_requirements = Gem::Requirement.new version
end
@requirement = @version_requirements if defined?(@version_requirements)
end
##
# Rails subclasses Gem::Dependency and uses this method, so we'll hack
# around it.
alias __requirement requirement # :nodoc:
def requirements_list
requirement.as_list
end
def to_s # :nodoc:
"#{name} (#{requirement}, #{type})"
end
def version_requirements # :nodoc:
unless Gem::Dependency.warned_version_requirement then
warn "#{Gem.location_of_caller.join ':'}:Warning: " \
"Gem::Dependency#version_requirements is deprecated " \
"and will be removed on or after August 2010. " \
"Use #requirement"
Gem::Dependency.warned_version_requirement = true
end
__requirement
end
alias_method :version_requirement, :version_requirements
def == other # :nodoc:
Gem::Dependency === other &&
self.name == other.name &&
self.type == other.type &&
self.requirement == other.requirement
end
##
# Dependencies are ordered by name.
def <=> other
[@name] <=> [other.name]
end
##
# Uses this dependency as a pattern to compare to +other+. This
# dependency will match if the name matches the other's name, and
# other has only an equal version requirement that satisfies this
# dependency.
def =~ other
unless Gem::Dependency === other
other = Gem::Dependency.new other.name, other.version rescue return false
end
pattern = name
pattern = /\A#{Regexp.escape pattern}\Z/ unless Regexp === pattern
return false unless pattern =~ other.name
reqs = other.requirement.requirements
return false unless reqs.length == 1
return false unless reqs.first.first == '='
version = reqs.first.last
requirement.satisfied_by? version
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/local_remote_options.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/local_remote_options.rb | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'uri'
require 'rubygems'
##
# Mixin methods for local and remote Gem::Command options.
module Gem::LocalRemoteOptions
##
# Allows OptionParser to handle HTTP URIs.
def accept_uri_http
OptionParser.accept URI::HTTP do |value|
begin
uri = URI.parse value
rescue URI::InvalidURIError
raise OptionParser::InvalidArgument, value
end
unless ['http', 'https', 'file'].include?(uri.scheme)
raise OptionParser::InvalidArgument, value
end
value
end
end
##
# Add local/remote options to the command line parser.
def add_local_remote_options
add_option(:"Local/Remote", '-l', '--local',
'Restrict operations to the LOCAL domain') do |value, options|
options[:domain] = :local
end
add_option(:"Local/Remote", '-r', '--remote',
'Restrict operations to the REMOTE domain') do |value, options|
options[:domain] = :remote
end
add_option(:"Local/Remote", '-b', '--both',
'Allow LOCAL and REMOTE operations') do |value, options|
options[:domain] = :both
end
add_bulk_threshold_option
add_source_option
add_proxy_option
add_update_sources_option
end
##
# Add the --bulk-threshold option
def add_bulk_threshold_option
add_option(:"Local/Remote", '-B', '--bulk-threshold COUNT',
"Threshold for switching to bulk",
"synchronization (default #{Gem.configuration.bulk_threshold})") do
|value, options|
Gem.configuration.bulk_threshold = value.to_i
end
end
##
# Add the --http-proxy option
def add_proxy_option
accept_uri_http
add_option(:"Local/Remote", '-p', '--[no-]http-proxy [URL]', URI::HTTP,
'Use HTTP proxy for remote operations') do |value, options|
options[:http_proxy] = (value == false) ? :no_proxy : value
Gem.configuration[:http_proxy] = options[:http_proxy]
end
end
##
# Add the --source option
def add_source_option
accept_uri_http
add_option(:"Local/Remote", '--source URL', URI::HTTP,
'Use URL as the remote source for gems') do |source, options|
source << '/' if source !~ /\/\z/
if options[:added_source] then
Gem.sources << source unless Gem.sources.include?(source)
else
options[:added_source] = true
Gem.sources.replace [source]
end
end
end
##
# Add the --update-sources option
def add_update_sources_option
add_option(:"Local/Remote", '-u', '--[no-]update-sources',
'Update local source cache') do |value, options|
Gem.configuration.update_sources = value
end
end
##
# Is fetching of local and remote information enabled?
def both?
options[:domain] == :both
end
##
# Is local fetching enabled?
def local?
options[:domain] == :local || options[:domain] == :both
end
##
# Is remote fetching enabled?
def remote?
options[:domain] == :remote || options[:domain] == :both
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'rubygems'
module Kernel
##
# The Kernel#require from before RubyGems was loaded.
alias gem_original_require require
##
# When RubyGems is required, Kernel#require is replaced with our own which
# is capable of loading gems on demand.
#
# When you call <tt>require 'x'</tt>, this is what happens:
# * If the file can be loaded from the existing Ruby loadpath, it
# is.
# * Otherwise, installed gems are searched for a file that matches.
# If it's found in gem 'y', that gem is activated (added to the
# loadpath).
#
# The normal <tt>require</tt> functionality of returning false if
# that file has already been loaded is preserved.
def require(path) # :doc:
gem_original_require path
rescue LoadError => load_error
if load_error.message =~ /#{Regexp.escape path}\z/ and
spec = Gem.searcher.find(path) then
Gem.activate(spec.name, "= #{spec.version}")
gem_original_require path
else
raise load_error
end
end
private :require
private :gem_original_require
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/source_info_cache.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/source_info_cache.rb | require 'fileutils'
require 'rubygems'
require 'rubygems/source_info_cache_entry'
require 'rubygems/user_interaction'
##
# SourceInfoCache stores a copy of the gem index for each gem source.
#
# There are two possible cache locations, the system cache and the user cache:
# * The system cache is preferred if it is writable or can be created.
# * The user cache is used otherwise
#
# Once a cache is selected, it will be used for all operations.
# SourceInfoCache will not switch between cache files dynamically.
#
# Cache data is a Hash mapping a source URI to a SourceInfoCacheEntry.
#
#--
# To keep things straight, this is how the cache objects all fit together:
#
# Gem::SourceInfoCache
# @cache_data = {
# source_uri => Gem::SourceInfoCacheEntry
# @size = source index size
# @source_index = Gem::SourceIndex
# ...
# }
class Gem::SourceInfoCache
include Gem::UserInteraction
##
# The singleton Gem::SourceInfoCache. If +all+ is true, a full refresh will
# be performed if the singleton instance is being initialized.
def self.cache(all = false)
return @cache if @cache
@cache = new
@cache.refresh all if Gem.configuration.update_sources
@cache
end
def self.cache_data
cache.cache_data
end
##
# The name of the system cache file.
def self.latest_system_cache_file
File.join File.dirname(system_cache_file),
"latest_#{File.basename system_cache_file}"
end
##
# The name of the latest user cache file.
def self.latest_user_cache_file
File.join File.dirname(user_cache_file),
"latest_#{File.basename user_cache_file}"
end
##
# Reset all singletons, discarding any changes.
def self.reset
@cache = nil
@system_cache_file = nil
@user_cache_file = nil
end
##
# Search all source indexes. See Gem::SourceInfoCache#search.
def self.search(*args)
cache.search(*args)
end
##
# Search all source indexes returning the source_uri. See
# Gem::SourceInfoCache#search_with_source.
def self.search_with_source(*args)
cache.search_with_source(*args)
end
##
# The name of the system cache file. (class method)
def self.system_cache_file
@system_cache_file ||= Gem.default_system_source_cache_dir
end
##
# The name of the user cache file.
def self.user_cache_file
@user_cache_file ||=
ENV['GEMCACHE'] || Gem.default_user_source_cache_dir
end
def initialize # :nodoc:
@cache_data = nil
@cache_file = nil
@dirty = false
@only_latest = true
end
##
# The most recent cache data.
def cache_data
return @cache_data if @cache_data
cache_file # HACK writable check
@only_latest = true
@cache_data = read_cache_data latest_cache_file
@cache_data
end
##
# The name of the cache file.
def cache_file
return @cache_file if @cache_file
@cache_file = (try_file(system_cache_file) or
try_file(user_cache_file) or
raise "unable to locate a writable cache file")
end
##
# Write the cache to a local file (if it is dirty).
def flush
write_cache if @dirty
@dirty = false
end
def latest_cache_data
latest_cache_data = {}
cache_data.each do |repo, sice|
latest = sice.source_index.latest_specs
new_si = Gem::SourceIndex.new
new_si.add_specs(*latest)
latest_sice = Gem::SourceInfoCacheEntry.new new_si, sice.size
latest_cache_data[repo] = latest_sice
end
latest_cache_data
end
##
# The name of the latest cache file.
def latest_cache_file
File.join File.dirname(cache_file), "latest_#{File.basename cache_file}"
end
##
# The name of the latest system cache file.
def latest_system_cache_file
self.class.latest_system_cache_file
end
##
# The name of the latest user cache file.
def latest_user_cache_file
self.class.latest_user_cache_file
end
##
# Merges the complete cache file into this Gem::SourceInfoCache.
def read_all_cache_data
if @only_latest then
@only_latest = false
all_data = read_cache_data cache_file
cache_data.update all_data do |source_uri, latest_sice, all_sice|
all_sice.source_index.gems.update latest_sice.source_index.gems
Gem::SourceInfoCacheEntry.new all_sice.source_index, latest_sice.size
end
begin
refresh true
rescue Gem::RemoteFetcher::FetchError
end
end
end
##
# Reads cached data from +file+.
def read_cache_data(file)
# Marshal loads 30-40% faster from a String, and 2MB on 20061116 is small
data = open file, 'rb' do |fp| fp.read end
cache_data = Marshal.load data
cache_data.each do |url, sice|
next unless sice.is_a?(Hash)
update
cache = sice['cache']
size = sice['size']
if cache.is_a?(Gem::SourceIndex) and size.is_a?(Numeric) then
new_sice = Gem::SourceInfoCacheEntry.new cache, size
cache_data[url] = new_sice
else # irreperable, force refetch.
reset_cache_for url, cache_data
end
end
cache_data
rescue Errno::ENOENT
{}
rescue => e
if Gem.configuration.really_verbose then
say "Exception during cache_data handling: #{e.class} - #{e}"
say "Cache file was: #{file}"
say "\t#{e.backtrace.join "\n\t"}"
end
{}
end
##
# Refreshes each source in the cache from its repository. If +all+ is
# false, only latest gems are updated.
def refresh(all)
Gem.sources.each do |source_uri|
cache_entry = cache_data[source_uri]
if cache_entry.nil? then
cache_entry = Gem::SourceInfoCacheEntry.new nil, 0
cache_data[source_uri] = cache_entry
end
update if cache_entry.refresh source_uri, all
end
flush
end
def reset_cache_for(url, cache_data)
say "Reseting cache for #{url}" if Gem.configuration.really_verbose
sice = Gem::SourceInfoCacheEntry.new Gem::SourceIndex.new, 0
sice.refresh url, false # HACK may be unnecessary, see ::cache and #refresh
cache_data[url] = sice
cache_data
end
def reset_cache_data
@cache_data = nil
@only_latest = true
end
##
# Force cache file to be reset, useful for integration testing of rubygems
def reset_cache_file
@cache_file = nil
end
##
# Searches all source indexes. See Gem::SourceIndex#search for details on
# +pattern+ and +platform_only+. If +all+ is set to true, the full index
# will be loaded before searching.
def search(pattern, platform_only = false, all = false)
read_all_cache_data if all
cache_data.map do |source_uri, sic_entry|
next unless Gem.sources.include? source_uri
# TODO - Remove this gunk after 2008/11
unless pattern.kind_of?(Gem::Dependency)
pattern = Gem::Dependency.new(pattern, Gem::Requirement.default)
end
sic_entry.source_index.search pattern, platform_only
end.flatten.compact
end
# Searches all source indexes for +pattern+. If +only_platform+ is true,
# only gems matching Gem.platforms will be selected. Returns an Array of
# pairs containing the Gem::Specification found and the source_uri it was
# found at.
def search_with_source(pattern, only_platform = false, all = false)
read_all_cache_data if all
results = []
cache_data.map do |source_uri, sic_entry|
next unless Gem.sources.include? source_uri
# TODO - Remove this gunk after 2008/11
unless pattern.kind_of?(Gem::Dependency)
pattern = Gem::Dependency.new(pattern, Gem::Requirement.default)
end
sic_entry.source_index.search(pattern, only_platform).each do |spec|
results << [spec, source_uri]
end
end
results
end
##
# Set the source info cache data directly. This is mainly used for unit
# testing when we don't want to read a file system to grab the cached source
# index information. The +hash+ should map a source URL into a
# SourceInfoCacheEntry.
def set_cache_data(hash)
@cache_data = hash
update
end
##
# The name of the system cache file.
def system_cache_file
self.class.system_cache_file
end
##
# Determine if +path+ is a candidate for a cache file. Returns +path+ if
# it is, nil if not.
def try_file(path)
return path if File.writable? path
return nil if File.exist? path
dir = File.dirname path
unless File.exist? dir then
begin
FileUtils.mkdir_p dir
rescue RuntimeError, SystemCallError
return nil
end
end
return path if File.writable? dir
nil
end
##
# Mark the cache as updated (i.e. dirty).
def update
@dirty = true
end
##
# The name of the user cache file.
def user_cache_file
self.class.user_cache_file
end
##
# Write data to the proper cache files.
def write_cache
if not File.exist?(cache_file) or not @only_latest then
open cache_file, 'wb' do |io|
io.write Marshal.dump(cache_data)
end
end
open latest_cache_file, 'wb' do |io|
io.write Marshal.dump(latest_cache_data)
end
end
reset
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/gem_openssl.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/gem_openssl.rb | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
#--
# Some system might not have OpenSSL installed, therefore the core
# library file openssl might not be available. We localize testing
# for the presence of OpenSSL in this file.
#++
module Gem
class << self
##
# Is SSL (used by the signing commands) available on this
# platform?
def ssl_available?
@ssl_available
end
##
# Is SSL available?
attr_writer :ssl_available
##
# Ensure that SSL is available. Throw an exception if it is not.
def ensure_ssl_available
unless ssl_available?
raise Gem::Exception, "SSL is not installed on this system"
end
end
end
end
begin
require 'openssl'
# Reference a constant defined in the .rb portion of ssl (just to
# make sure that part is loaded too).
dummy = OpenSSL::Digest::SHA1
Gem.ssl_available = true
class OpenSSL::X509::Certificate # :nodoc:
# Check the validity of this certificate.
def check_validity(issuer_cert = nil, time = Time.now)
ret = if @not_before && @not_before > time
[false, :expired, "not valid before '#@not_before'"]
elsif @not_after && @not_after < time
[false, :expired, "not valid after '#@not_after'"]
elsif issuer_cert && !verify(issuer_cert.public_key)
[false, :issuer, "#{issuer_cert.subject} is not issuer"]
else
[true, :ok, 'Valid certificate']
end
# return hash
{ :is_valid => ret[0], :error => ret[1], :desc => ret[2] }
end
end
rescue LoadError, StandardError
Gem.ssl_available = false
end
# :stopdoc:
module Gem::SSL
# We make our own versions of the constants here. This allows us
# to reference the constants, even though some systems might not
# have SSL installed in the Ruby core package.
#
# These constants are only used during load time. At runtime, any
# method that makes a direct reference to SSL software must be
# protected with a Gem.ensure_ssl_available call.
if Gem.ssl_available? then
PKEY_RSA = OpenSSL::PKey::RSA
DIGEST_SHA1 = OpenSSL::Digest::SHA1
else
PKEY_RSA = :rsa
DIGEST_SHA1 = :sha1
end
end
# :startdoc:
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/uninstaller.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/uninstaller.rb | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'fileutils'
require 'rubygems'
require 'rubygems/dependency_list'
require 'rubygems/doc_manager'
require 'rubygems/user_interaction'
##
# An Uninstaller.
#
# The uninstaller fires pre and post uninstall hooks. Hooks can be added
# either through a rubygems_plugin.rb file in an installed gem or via a
# rubygems/defaults/#{RUBY_ENGINE}.rb or rubygems/defaults/operating_system.rb
# file. See Gem.pre_uninstall and Gem.post_uninstall for details.
class Gem::Uninstaller
include Gem::UserInteraction
##
# The directory a gem's executables will be installed into
attr_reader :bin_dir
##
# The gem repository the gem will be installed into
attr_reader :gem_home
##
# The Gem::Specification for the gem being uninstalled, only set during
# #uninstall_gem
attr_reader :spec
##
# Constructs an uninstaller that will uninstall +gem+
def initialize(gem, options = {})
@gem = gem
@version = options[:version] || Gem::Requirement.default
gem_home = options[:install_dir] || Gem.dir
@gem_home = File.expand_path gem_home
@force_executables = options[:executables]
@force_all = options[:all]
@force_ignore = options[:ignore]
@bin_dir = options[:bin_dir]
# only add user directory if install_dir is not set
@user_install = false
@user_install = options[:user_install] unless options[:install_dir]
spec_dir = File.join @gem_home, 'specifications'
@source_index = Gem::SourceIndex.from_gems_in spec_dir
if @user_install then
user_dir = File.join Gem.user_dir, 'specifications'
@user_index = Gem::SourceIndex.from_gems_in user_dir
end
end
##
# Performs the uninstall of the gem. This removes the spec, the Gem
# directory, and the cached .gem file.
def uninstall
list = @source_index.find_name @gem, @version
list += @user_index.find_name @gem, @version if @user_install
if list.empty? then
raise Gem::InstallError, "cannot uninstall, check `gem list -d #{@gem}`"
elsif list.size > 1 and @force_all then
remove_all list.dup
elsif list.size > 1 then
gem_names = list.collect {|gem| gem.full_name} + ["All versions"]
say
gem_name, index = choose_from_list "Select gem to uninstall:", gem_names
if index == list.size then
remove_all list.dup
elsif index >= 0 && index < list.size then
uninstall_gem list[index], list.dup
else
say "Error: must enter a number [1-#{list.size+1}]"
end
else
uninstall_gem list.first, list.dup
end
end
##
# Uninstalls gem +spec+
def uninstall_gem(spec, specs)
@spec = spec
Gem.pre_uninstall_hooks.each do |hook|
hook.call self
end
remove_executables @spec
remove @spec, specs
Gem.post_uninstall_hooks.each do |hook|
hook.call self
end
@spec = nil
end
##
# Removes installed executables and batch files (windows only) for
# +gemspec+.
def remove_executables(spec)
return if spec.nil?
unless spec.executables.empty? then
bindir = @bin_dir ? @bin_dir : Gem.bindir(spec.installation_path)
list = @source_index.find_name(spec.name).delete_if { |s|
s.version == spec.version
}
executables = spec.executables.clone
list.each do |s|
s.executables.each do |exe_name|
executables.delete exe_name
end
end
return if executables.empty?
answer = if @force_executables.nil? then
ask_yes_no("Remove executables:\n" \
"\t#{spec.executables.join(", ")}\n\nin addition to the gem?",
true) # " # appease ruby-mode - don't ask
else
@force_executables
end
unless answer then
say "Executables and scripts will remain installed."
else
raise Gem::FilePermissionError, bindir unless File.writable? bindir
spec.executables.each do |exe_name|
say "Removing #{exe_name}"
FileUtils.rm_f File.join(bindir, exe_name)
FileUtils.rm_f File.join(bindir, "#{exe_name}.bat")
end
end
end
end
##
# Removes all gems in +list+.
#
# NOTE: removes uninstalled gems from +list+.
def remove_all(list)
list.dup.each { |spec| uninstall_gem spec, list }
end
##
# spec:: the spec of the gem to be uninstalled
# list:: the list of all such gems
#
# Warning: this method modifies the +list+ parameter. Once it has
# uninstalled a gem, it is removed from that list.
def remove(spec, list)
unless dependencies_ok? spec then
raise Gem::DependencyRemovalException,
"Uninstallation aborted due to dependent gem(s)"
end
unless path_ok?(@gem_home, spec) or
(@user_install and path_ok?(Gem.user_dir, spec)) then
e = Gem::GemNotInHomeException.new \
"Gem is not installed in directory #{@gem_home}"
e.spec = spec
raise e
end
raise Gem::FilePermissionError, spec.installation_path unless
File.writable?(spec.installation_path)
FileUtils.rm_rf spec.full_gem_path
original_platform_name = [
spec.name, spec.version, spec.original_platform].join '-'
spec_dir = File.join spec.installation_path, 'specifications'
gemspec = File.join spec_dir, spec.spec_name
unless File.exist? gemspec then
gemspec = File.join spec_dir, "#{original_platform_name}.gemspec"
end
FileUtils.rm_rf gemspec
cache_dir = File.join spec.installation_path, 'cache'
gem = File.join cache_dir, spec.file_name
unless File.exist? gem then
gem = File.join cache_dir, "#{original_platform_name}.gem"
end
FileUtils.rm_rf gem
Gem::DocManager.new(spec).uninstall_doc
say "Successfully uninstalled #{spec.full_name}"
list.delete spec
end
##
# Is +spec+ in +gem_dir+?
def path_ok?(gem_dir, spec)
full_path = File.join gem_dir, 'gems', spec.full_name
original_path = File.join gem_dir, 'gems', spec.original_name
full_path == spec.full_gem_path || original_path == spec.full_gem_path
end
def dependencies_ok?(spec)
return true if @force_ignore
deplist = Gem::DependencyList.from_source_index @source_index
deplist.add(*@user_index.gems.values) if @user_install
deplist.ok_to_remove?(spec.full_name) || ask_if_ok(spec)
end
def ask_if_ok(spec)
msg = ['']
msg << 'You have requested to uninstall the gem:'
msg << "\t#{spec.full_name}"
spec.dependent_gems.each do |gem,dep,satlist|
msg <<
("#{gem.name}-#{gem.version} depends on " +
"[#{dep.name} (#{dep.requirement})]")
end
msg << 'If you remove this gems, one or more dependencies will not be met.'
msg << 'Continue with Uninstall?'
return ask_yes_no(msg.join("\n"), true)
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/defaults/jruby.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/defaults/jruby.rb | require 'rubygems/config_file'
require 'rbconfig'
module Gem
ConfigFile::PLATFORM_DEFAULTS['install'] = '--env-shebang'
ConfigFile::PLATFORM_DEFAULTS['update'] = '--env-shebang'
@jar_paths = []
class << self
alias_method :original_ensure_gem_subdirectories, :ensure_gem_subdirectories
def ensure_gem_subdirectories(gemdir)
original_ensure_gem_subdirectories(gemdir) unless jarred_path? gemdir.to_s
end
alias_method :original_set_paths, :set_paths
def set_paths(gpaths)
original_set_paths(gpaths)
@gem_path.reject! {|p| !readable_path? p }
@jar_paths.each {|p| @gem_path << p unless @gem_path.include?(p) } if @jar_paths
end
alias_method :original_default_path, :default_path
def default_path
paths = RbConfig::CONFIG["default_gem_path"]
paths = paths.split(':').reject {|p| p.empty? }.compact if paths
paths ||= original_default_path
@jar_paths = paths.select {|p| jarred_path? p }
paths.reject {|p| jarred_path? p }
end
alias_method :original_ruby, :ruby
def ruby
ruby_path = original_ruby
if jarred_path?(ruby_path)
ruby_path = "java -jar #{ruby_path.sub(/^file:/,"").sub(/!.*/,"")}"
end
ruby_path
end
def readable_path?(p)
p =~ /^file:/ || File.exists?(p)
end
def jarred_path?(p)
p =~ /^file:/
end
end
# Default home directory path to be used if an alternate value is not
# specified in the environment.
#
# JRuby: We don't want gems installed in lib/jruby/gems, but rather
# to preserve the old location: lib/ruby/gems.
def self.default_dir
dir = RbConfig::CONFIG["default_gem_home"]
dir ||= File.join(ConfigMap[:libdir], 'ruby', 'gems', '1.8')
dir
end
##
# Is this a windows platform?
#
# JRuby: Look in CONFIG['host_os'] as well.
def self.win_platform?
if @@win_platform.nil? then
@@win_platform = !!WIN_PATTERNS.find { |r| RUBY_PLATFORM =~ r || Config::CONFIG["host_os"] =~ r }
end
@@win_platform
end
end
## JAR FILES: Allow gem path entries to contain jar files
require 'rubygems/source_index'
class Gem::SourceIndex
class << self
def installed_spec_directories
# TODO: fix remaining glob tests
Gem.path.collect do |dir|
if File.file?(dir) && dir =~ /\.jar$/
"file:#{dir}!/specifications"
elsif File.directory?(dir) || dir =~ /^file:/
File.join(dir, "specifications")
end
end.compact + spec_directories_from_classpath
end
def spec_directories_from_classpath
require 'jruby/util'
stuff = JRuby::Util.classloader_resources("specifications")
end
end
end
## END JAR FILES
if (Gem::win_platform?)
module Process
def self.uid
0
end
end
end
# Check for jruby_native and load it if present. jruby_native
# indicates the native launcher is installed and will override
# env-shebang and possibly other options.
begin
require 'rubygems/defaults/jruby_native'
rescue LoadError
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/search_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/search_command.rb | require 'rubygems/command'
require 'rubygems/commands/query_command'
class Gem::Commands::SearchCommand < Gem::Commands::QueryCommand
def initialize
super 'search', 'Display all gems whose name contains STRING'
remove_option '--name-matches'
end
def arguments # :nodoc:
"STRING fragment of gem name to search for"
end
def defaults_str # :nodoc:
"--local --no-details"
end
def usage # :nodoc:
"#{program_name} [STRING]"
end
def execute
string = get_one_optional_argument
options[:name] = /#{string}/i
super
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/list_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/list_command.rb | require 'rubygems/command'
require 'rubygems/commands/query_command'
##
# An alternate to Gem::Commands::QueryCommand that searches for gems starting
# with the the supplied argument.
class Gem::Commands::ListCommand < Gem::Commands::QueryCommand
def initialize
super 'list', 'Display gems whose name starts with STRING'
remove_option('--name-matches')
end
def arguments # :nodoc:
"STRING start of gem name to look for"
end
def defaults_str # :nodoc:
"--local --no-details"
end
def usage # :nodoc:
"#{program_name} [STRING]"
end
def execute
string = get_one_optional_argument || ''
options[:name] = /^#{string}/i
super
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/build_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/build_command.rb | require 'rubygems/command'
require 'rubygems/builder'
class Gem::Commands::BuildCommand < Gem::Command
def initialize
super('build', 'Build a gem from a gemspec')
end
def arguments # :nodoc:
"GEMSPEC_FILE gemspec file name to build a gem for"
end
def usage # :nodoc:
"#{program_name} GEMSPEC_FILE"
end
def execute
gemspec = get_one_gem_name
if File.exist?(gemspec)
specs = load_gemspecs(gemspec)
specs.each do |spec|
Gem::Builder.new(spec).build
end
else
alert_error "Gemspec file not found: #{gemspec}"
end
end
def load_gemspecs(filename)
if yaml?(filename)
result = []
open(filename) do |f|
begin
while not f.eof? and spec = Gem::Specification.from_yaml(f)
result << spec
end
rescue Gem::EndOfYAMLException => e
# OK
end
end
else
result = [Gem::Specification.load(filename)]
end
result
end
def yaml?(filename)
line = open(filename) { |f| line = f.gets }
result = line =~ %r{!ruby/object:Gem::Specification}
result
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/unpack_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/unpack_command.rb | require 'fileutils'
require 'rubygems/command'
require 'rubygems/installer'
require 'rubygems/version_option'
class Gem::Commands::UnpackCommand < Gem::Command
include Gem::VersionOption
def initialize
super 'unpack', 'Unpack an installed gem to the current directory',
:version => Gem::Requirement.default,
:target => Dir.pwd
add_option('--target=DIR', 'target directory for unpacking') do |value, options|
options[:target] = value
end
add_version_option
end
def arguments # :nodoc:
"GEMNAME name of gem to unpack"
end
def defaults_str # :nodoc:
"--version '#{Gem::Requirement.default}'"
end
def usage # :nodoc:
"#{program_name} GEMNAME"
end
#--
# TODO: allow, e.g., 'gem unpack rake-0.3.1'. Find a general solution for
# this, so that it works for uninstall as well. (And check other commands
# at the same time.)
def execute
get_all_gem_names.each do |name|
path = get_path name, options[:version]
if path then
basename = File.basename(path, '.gem')
target_dir = File.expand_path File.join(options[:target], basename)
FileUtils.mkdir_p target_dir
Gem::Installer.new(path, :unpack => true).unpack target_dir
say "Unpacked gem: '#{target_dir}'"
else
alert_error "Gem '#{name}' not installed."
end
end
end
# Return the full path to the cached gem file matching the given
# name and version requirement. Returns 'nil' if no match.
#
# Example:
#
# get_path('rake', '> 0.4') # -> '/usr/lib/ruby/gems/1.8/cache/rake-0.4.2.gem'
# get_path('rake', '< 0.1') # -> nil
# get_path('rak') # -> nil (exact name required)
#--
# TODO: This should be refactored so that it's a general service. I don't
# think any of our existing classes are the right place though. Just maybe
# 'Cache'?
#
# TODO: It just uses Gem.dir for now. What's an easy way to get the list of
# source directories?
def get_path(gemname, version_req)
return gemname if gemname =~ /\.gem$/i
specs = Gem::source_index.find_name gemname, version_req
selected = specs.sort_by { |s| s.version }.last
return nil if selected.nil?
# We expect to find (basename).gem in the 'cache' directory.
# Furthermore, the name match must be exact (ignoring case).
if gemname =~ /^#{selected.name}$/i
filename = selected.file_name
path = nil
Gem.path.find do |gem_dir|
path = File.join gem_dir, 'cache', filename
File.exist? path
end
path
else
nil
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/cleanup_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/cleanup_command.rb | require 'rubygems/command'
require 'rubygems/source_index'
require 'rubygems/dependency_list'
require 'rubygems/uninstaller'
class Gem::Commands::CleanupCommand < Gem::Command
def initialize
super 'cleanup',
'Clean up old versions of installed gems in the local repository',
:force => false, :test => false, :install_dir => Gem.dir
add_option('-d', '--dryrun', "") do |value, options|
options[:dryrun] = true
end
end
def arguments # :nodoc:
"GEMNAME name of gem to cleanup"
end
def defaults_str # :nodoc:
"--no-dryrun"
end
def description # :nodoc:
<<-EOF
The cleanup command removes old gems from GEM_HOME. If an older version is
installed elsewhere in GEM_PATH the cleanup command won't touch it.
EOF
end
def usage # :nodoc:
"#{program_name} [GEMNAME ...]"
end
def execute
say "Cleaning up installed gems..."
primary_gems = {}
Gem.source_index.each do |name, spec|
if primary_gems[spec.name].nil? or
primary_gems[spec.name].version < spec.version then
primary_gems[spec.name] = spec
end
end
gems_to_cleanup = []
unless options[:args].empty? then
options[:args].each do |gem_name|
dep = Gem::Dependency.new gem_name, Gem::Requirement.default
specs = Gem.source_index.search dep
specs.each do |spec|
gems_to_cleanup << spec
end
end
else
Gem.source_index.each do |name, spec|
gems_to_cleanup << spec
end
end
gems_to_cleanup = gems_to_cleanup.select { |spec|
primary_gems[spec.name].version != spec.version
}
deplist = Gem::DependencyList.new
gems_to_cleanup.uniq.each do |spec| deplist.add spec end
deps = deplist.strongly_connected_components.flatten.reverse
deps.each do |spec|
if options[:dryrun] then
say "Dry Run Mode: Would uninstall #{spec.full_name}"
else
say "Attempting to uninstall #{spec.full_name}"
options[:args] = [spec.name]
uninstall_options = {
:executables => false,
:version => "= #{spec.version}",
}
if Gem.user_dir == spec.installation_path then
uninstall_options[:install_dir] = spec.installation_path
end
uninstaller = Gem::Uninstaller.new spec.name, uninstall_options
begin
uninstaller.uninstall
rescue Gem::DependencyRemovalException, Gem::InstallError,
Gem::GemNotInHomeException => e
say "Unable to uninstall #{spec.full_name}:"
say "\t#{e.class}: #{e.message}"
end
end
end
say "Clean Up Complete"
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/push_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/push_command.rb | require 'rubygems/command'
require 'rubygems/local_remote_options'
require 'rubygems/gemcutter_utilities'
class Gem::Commands::PushCommand < Gem::Command
include Gem::LocalRemoteOptions
include Gem::GemcutterUtilities
def description # :nodoc:
'Push a gem up to RubyGems.org'
end
def arguments # :nodoc:
"GEM built gem to push up"
end
def usage # :nodoc:
"#{program_name} GEM"
end
def initialize
super 'push', description
add_proxy_option
end
def execute
sign_in
send_gem get_one_gem_name
end
def send_gem name
say "Pushing gem to RubyGems.org..."
response = rubygems_api_request :post, "api/v1/gems" do |request|
request.body = Gem.read_binary name
request.add_field "Content-Length", request.body.size
request.add_field "Content-Type", "application/octet-stream"
request.add_field "Authorization", Gem.configuration.rubygems_api_key
end
with_response response
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/setup_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/setup_command.rb | require 'rubygems/command'
require 'fileutils'
require 'rbconfig'
require 'tmpdir'
##
# Installs RubyGems itself. This command is ordinarily only available from a
# RubyGems checkout or tarball.
class Gem::Commands::SetupCommand < Gem::Command
def initialize
super 'setup', 'Install RubyGems',
:format_executable => true, :rdoc => true, :ri => true,
:site_or_vendor => :sitelibdir,
:destdir => '', :prefix => ''
add_option '--prefix=PREFIX',
'Prefix path for installing RubyGems',
'Will not affect gem repository location' do |prefix, options|
options[:prefix] = File.expand_path prefix
end
add_option '--destdir=DESTDIR',
'Root directory to install RubyGems into',
'Mainly used for packaging RubyGems' do |destdir, options|
options[:destdir] = File.expand_path destdir
end
add_option '--[no-]vendor',
'Install into vendorlibdir not sitelibdir',
'(Requires Ruby 1.8.7)' do |vendor, options|
if vendor and Gem.ruby_version < Gem::Version.new('1.8.7') then
raise OptionParser::InvalidOption,
"requires ruby 1.8.7+ (you have #{Gem.ruby_version})"
end
options[:site_or_vendor] = vendor ? :vendorlibdir : :sitelibdir
end
add_option '--[no-]format-executable',
'Makes `gem` match ruby',
'If ruby is ruby18, gem will be gem18' do |value, options|
options[:format_executable] = value
end
add_option '--[no-]rdoc',
'Generate RDoc documentation for RubyGems' do |value, options|
options[:rdoc] = value
end
add_option '--[no-]ri',
'Generate RI documentation for RubyGems' do |value, options|
options[:ri] = value
end
end
def check_ruby_version
required_version = Gem::Requirement.new '>= 1.8.6'
unless required_version.satisfied_by? Gem.ruby_version then
alert_error "Expected Ruby version #{required_version}, is #{Gem.ruby_version}"
terminate_interaction 1
end
end
def defaults_str # :nodoc:
"--format-executable --rdoc --ri"
end
def description # :nodoc:
<<-EOF
Installs RubyGems itself.
RubyGems installs RDoc for itself in GEM_HOME. By default this is:
#{Gem.dir}
If you prefer a different directory, set the GEM_HOME environment variable.
RubyGems will install the gem command with a name matching ruby's
prefix and suffix. If ruby was installed as `ruby18`, gem will be
installed as `gem18`.
By default, this RubyGems will install gem as:
#{Gem.default_exec_format % 'gem'}
EOF
end
def execute
@verbose = Gem.configuration.really_verbose
install_destdir = options[:destdir]
unless install_destdir.empty? then
ENV['GEM_HOME'] ||= File.join(install_destdir,
Gem.default_dir.gsub(/^[a-zA-Z]:/, ''))
end
check_ruby_version
if Gem.configuration.really_verbose then
extend FileUtils::Verbose
else
extend FileUtils
end
lib_dir, bin_dir = make_destination_dirs install_destdir
install_lib lib_dir
install_executables bin_dir
remove_old_bin_files bin_dir
remove_source_caches install_destdir
say "RubyGems #{Gem::VERSION} installed"
uninstall_old_gemcutter
install_rdoc
say
if @verbose then
say "-" * 78
say
end
release_notes = File.join Dir.pwd, 'History.txt'
release_notes = if File.exist? release_notes then
open release_notes do |io|
text = io.gets '==='
text << io.gets('===')
text[0...-3]
end
else
"Oh-no! Unable to find release notes!"
end
say release_notes
say
say "-" * 78
say
say "RubyGems installed the following executables:"
say @bin_file_names.map { |name| "\t#{name}\n" }
say
unless @bin_file_names.grep(/#{File::SEPARATOR}gem$/) then
say "If `gem` was installed by a previous RubyGems installation, you may need"
say "to remove it by hand."
say
end
end
def install_executables(bin_dir)
say "Installing gem executable" if @verbose
@bin_file_names = []
Dir.chdir 'bin' do
bin_files = Dir['*']
bin_files.delete 'update_rubygems'
bin_files.each do |bin_file|
bin_file_formatted = if options[:format_executable] then
Gem.default_exec_format % bin_file
else
bin_file
end
dest_file = File.join bin_dir, bin_file_formatted
bin_tmp_file = File.join Dir.tmpdir, bin_file
begin
bin = File.readlines bin_file
bin[0] = "#!#{Gem.ruby}\n"
File.open bin_tmp_file, 'w' do |fp|
fp.puts bin.join
end
install bin_tmp_file, dest_file, :mode => 0755
@bin_file_names << dest_file
ensure
rm bin_tmp_file
end
next unless Gem.win_platform?
begin
bin_cmd_file = File.join Dir.tmpdir, "#{bin_file}.bat"
File.open bin_cmd_file, 'w' do |file|
file.puts <<-TEXT
@ECHO OFF
IF NOT "%~f0" == "~f0" GOTO :WinNT
@"#{File.basename(Gem.ruby).chomp('"')}" "#{dest_file}" %1 %2 %3 %4 %5 %6 %7 %8 %9
GOTO :EOF
:WinNT
@"#{File.basename(Gem.ruby).chomp('"')}" "%~dpn0" %*
TEXT
end
install bin_cmd_file, "#{dest_file}.bat", :mode => 0755
ensure
rm bin_cmd_file
end
end
end
end
def install_lib(lib_dir)
say "Installing RubyGems" if @verbose
Dir.chdir 'lib' do
lib_files = Dir[File.join('**', '*rb')]
lib_files.each do |lib_file|
dest_file = File.join lib_dir, lib_file
dest_dir = File.dirname dest_file
mkdir_p dest_dir unless File.directory? dest_dir
install lib_file, dest_file, :mode => 0644
end
end
end
def install_rdoc
gem_doc_dir = File.join Gem.dir, 'doc'
rubygems_name = "rubygems-#{Gem::RubyGemsVersion}"
rubygems_doc_dir = File.join gem_doc_dir, rubygems_name
if File.writable? gem_doc_dir and
(not File.exist? rubygems_doc_dir or
File.writable? rubygems_doc_dir) then
say "Removing old RubyGems RDoc and ri" if @verbose
Dir[File.join(Gem.dir, 'doc', 'rubygems-[0-9]*')].each do |dir|
rm_rf dir
end
if options[:ri] then
ri_dir = File.join rubygems_doc_dir, 'ri'
say "Installing #{rubygems_name} ri into #{ri_dir}" if @verbose
run_rdoc '--ri', '--op', ri_dir
end
if options[:rdoc] then
rdoc_dir = File.join rubygems_doc_dir, 'rdoc'
say "Installing #{rubygems_name} rdoc into #{rdoc_dir}" if @verbose
run_rdoc '--op', rdoc_dir
end
elsif @verbose then
say "Skipping RDoc generation, #{gem_doc_dir} not writable"
say "Set the GEM_HOME environment variable if you want RDoc generated"
end
end
def make_destination_dirs(install_destdir)
lib_dir = nil
bin_dir = nil
prefix = options[:prefix]
site_or_vendor = options[:site_or_vendor]
if prefix.empty? then
lib_dir = Gem::ConfigMap[site_or_vendor]
bin_dir = Gem::ConfigMap[:bindir]
else
# Apple installed RubyGems into libdir, and RubyGems <= 1.1.0 gets
# confused about installation location, so switch back to
# sitelibdir/vendorlibdir.
if defined?(APPLE_GEM_HOME) and
# just in case Apple and RubyGems don't get this patched up proper.
(prefix == Gem::ConfigMap[:libdir] or
# this one is important
prefix == File.join(Gem::ConfigMap[:libdir], 'ruby')) then
lib_dir = Gem::ConfigMap[site_or_vendor]
bin_dir = Gem::ConfigMap[:bindir]
else
lib_dir = File.join prefix, 'lib'
bin_dir = File.join prefix, 'bin'
end
end
unless install_destdir.empty? then
lib_dir = File.join install_destdir, lib_dir.gsub(/^[a-zA-Z]:/, '')
bin_dir = File.join install_destdir, bin_dir.gsub(/^[a-zA-Z]:/, '')
end
mkdir_p lib_dir
mkdir_p bin_dir
return lib_dir, bin_dir
end
def remove_old_bin_files(bin_dir)
old_bin_files = {
'gem_mirror' => 'gem mirror',
'gem_server' => 'gem server',
'gemlock' => 'gem lock',
'gemri' => 'ri',
'gemwhich' => 'gem which',
'index_gem_repository.rb' => 'gem generate_index',
}
old_bin_files.each do |old_bin_file, new_name|
old_bin_path = File.join bin_dir, old_bin_file
next unless File.exist? old_bin_path
deprecation_message = "`#{old_bin_file}` has been deprecated. Use `#{new_name}` instead."
File.open old_bin_path, 'w' do |fp|
fp.write <<-EOF
#!#{Gem.ruby}
abort "#{deprecation_message}"
EOF
end
next unless Gem.win_platform?
File.open "#{old_bin_path}.bat", 'w' do |fp|
fp.puts %{@ECHO.#{deprecation_message}}
end
end
end
def remove_source_caches(install_destdir)
if install_destdir.empty?
require 'rubygems/source_info_cache'
user_cache_file = File.join(install_destdir,
Gem::SourceInfoCache.user_cache_file)
system_cache_file = File.join(install_destdir,
Gem::SourceInfoCache.system_cache_file)
say "Removing old source_cache files" if Gem.configuration.really_verbose
rm_f user_cache_file if File.writable? File.dirname(user_cache_file)
rm_f system_cache_file if File.writable? File.dirname(system_cache_file)
end
end
def run_rdoc(*args)
begin
gem 'rdoc'
rescue Gem::LoadError
end
require 'rdoc/rdoc'
args << '--quiet'
args << '--main' << 'README'
args << '.' << 'README' << 'LICENSE.txt' << 'GPL.txt'
r = RDoc::RDoc.new
r.document args
end
def uninstall_old_gemcutter
require 'rubygems/uninstaller'
ui = Gem::Uninstaller.new('gemcutter', :all => true, :ignore => true,
:version => '< 0.4')
ui.uninstall
rescue Gem::InstallError
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/outdated_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/outdated_command.rb | require 'rubygems/command'
require 'rubygems/local_remote_options'
require 'rubygems/spec_fetcher'
require 'rubygems/version_option'
class Gem::Commands::OutdatedCommand < Gem::Command
include Gem::LocalRemoteOptions
include Gem::VersionOption
def initialize
super 'outdated', 'Display all gems that need updates'
add_local_remote_options
add_platform_option
end
def execute
locals = Gem::SourceIndex.from_installed_gems
locals.outdated.sort.each do |name|
local = locals.find_name(name).last
dep = Gem::Dependency.new local.name, ">= #{local.version}"
remotes = Gem::SpecFetcher.fetcher.fetch dep
remote = remotes.last.first
say "#{local.name} (#{local.version} < #{remote.version})"
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/specification_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/specification_command.rb | require 'yaml'
require 'rubygems/command'
require 'rubygems/local_remote_options'
require 'rubygems/version_option'
require 'rubygems/source_info_cache'
require 'rubygems/format'
class Gem::Commands::SpecificationCommand < Gem::Command
include Gem::LocalRemoteOptions
include Gem::VersionOption
def initialize
super 'specification', 'Display gem specification (in yaml)',
:domain => :local, :version => Gem::Requirement.default,
:format => :yaml
add_version_option('examine')
add_platform_option
add_option('--all', 'Output specifications for all versions of',
'the gem') do |value, options|
options[:all] = true
end
add_option('--ruby', 'Output ruby format') do |value, options|
options[:format] = :ruby
end
add_option('--yaml', 'Output RUBY format') do |value, options|
options[:format] = :yaml
end
add_option('--marshal', 'Output Marshal format') do |value, options|
options[:format] = :marshal
end
add_local_remote_options
end
def arguments # :nodoc:
<<-ARGS
GEMFILE name of gem to show the gemspec for
FIELD name of gemspec field to show
ARGS
end
def defaults_str # :nodoc:
"--local --version '#{Gem::Requirement.default}' --yaml"
end
def usage # :nodoc:
"#{program_name} [GEMFILE] [FIELD]"
end
def execute
specs = []
gem = options[:args].shift
unless gem then
raise Gem::CommandLineError,
"Please specify a gem name or file on the command line"
end
dep = Gem::Dependency.new gem, options[:version]
field = get_one_optional_argument
if field then
field = field.intern
if options[:format] == :ruby then
raise Gem::CommandLineError, "--ruby and FIELD are mutually exclusive"
end
unless Gem::Specification.attribute_names.include? field then
raise Gem::CommandLineError,
"no field %p on Gem::Specification" % field.to_s
end
end
if local? then
if File.exist? gem then
specs << Gem::Format.from_file_by_path(gem).spec rescue nil
end
if specs.empty? then
specs.push(*Gem.source_index.search(dep))
end
end
if remote? then
found = Gem::SpecFetcher.fetcher.fetch dep
specs.push(*found.map { |spec,| spec })
end
if specs.empty? then
alert_error "Unknown gem '#{gem}'"
terminate_interaction 1
end
output = lambda do |s|
s = s.send field if field
say case options[:format]
when :ruby then s.to_ruby
when :marshal then Marshal.dump s
else s.to_yaml
end
say "\n"
end
if options[:all] then
specs.each(&output)
else
spec = specs.sort_by { |s| s.version }.last
output[spec]
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/lock_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/lock_command.rb | require 'rubygems/command'
class Gem::Commands::LockCommand < Gem::Command
def initialize
super 'lock', 'Generate a lockdown list of gems',
:strict => false
add_option '-s', '--[no-]strict',
'fail if unable to satisfy a dependency' do |strict, options|
options[:strict] = strict
end
end
def arguments # :nodoc:
"GEMNAME name of gem to lock\nVERSION version of gem to lock"
end
def defaults_str # :nodoc:
"--no-strict"
end
def description # :nodoc:
<<-EOF
The lock command will generate a list of +gem+ statements that will lock down
the versions for the gem given in the command line. It will specify exact
versions in the requirements list to ensure that the gems loaded will always
be consistent. A full recursive search of all effected gems will be
generated.
Example:
gemlock rails-1.0.0 > lockdown.rb
will produce in lockdown.rb:
require "rubygems"
gem 'rails', '= 1.0.0'
gem 'rake', '= 0.7.0.1'
gem 'activesupport', '= 1.2.5'
gem 'activerecord', '= 1.13.2'
gem 'actionpack', '= 1.11.2'
gem 'actionmailer', '= 1.1.5'
gem 'actionwebservice', '= 1.0.0'
Just load lockdown.rb from your application to ensure that the current
versions are loaded. Make sure that lockdown.rb is loaded *before* any
other require statements.
Notice that rails 1.0.0 only requires that rake 0.6.2 or better be used.
Rake-0.7.0.1 is the most recent version installed that satisfies that, so we
lock it down to the exact version.
EOF
end
def usage # :nodoc:
"#{program_name} GEMNAME-VERSION [GEMNAME-VERSION ...]"
end
def complain(message)
if options[:strict] then
raise Gem::Exception, message
else
say "# #{message}"
end
end
def execute
say "require 'rubygems'"
locked = {}
pending = options[:args]
until pending.empty? do
full_name = pending.shift
spec = Gem::SourceIndex.load_specification spec_path(full_name)
if spec.nil? then
complain "Could not find gem #{full_name}, try using the full name"
next
end
say "gem '#{spec.name}', '= #{spec.version}'" unless locked[spec.name]
locked[spec.name] = true
spec.runtime_dependencies.each do |dep|
next if locked[dep.name]
candidates = Gem.source_index.search dep
if candidates.empty? then
complain "Unable to satisfy '#{dep}' from currently installed gems"
else
pending << candidates.last.full_name
end
end
end
end
def spec_path(gem_full_name)
gemspecs = Gem.path.map do |path|
File.join path, "specifications", "#{gem_full_name}.gemspec"
end
gemspecs.find { |gemspec| File.exist? gemspec }
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/query_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/query_command.rb | require 'rubygems/command'
require 'rubygems/local_remote_options'
require 'rubygems/spec_fetcher'
require 'rubygems/version_option'
require 'rubygems/text'
class Gem::Commands::QueryCommand < Gem::Command
include Gem::Text
include Gem::LocalRemoteOptions
include Gem::VersionOption
def initialize(name = 'query',
summary = 'Query gem information in local or remote repositories')
super name, summary,
:name => //, :domain => :local, :details => false, :versions => true,
:installed => false, :version => Gem::Requirement.default
add_option('-i', '--[no-]installed',
'Check for installed gem') do |value, options|
options[:installed] = value
end
add_version_option
add_option('-n', '--name-matches REGEXP',
'Name of gem(s) to query on matches the',
'provided REGEXP') do |value, options|
options[:name] = /#{value}/i
end
add_option('-d', '--[no-]details',
'Display detailed information of gem(s)') do |value, options|
options[:details] = value
end
add_option( '--[no-]versions',
'Display only gem names') do |value, options|
options[:versions] = value
options[:details] = false unless value
end
add_option('-a', '--all',
'Display all gem versions') do |value, options|
options[:all] = value
end
add_option( '--[no-]prerelease',
'Display prerelease versions') do |value, options|
options[:prerelease] = value
end
add_local_remote_options
end
def defaults_str # :nodoc:
"--local --name-matches // --no-details --versions --no-installed"
end
def execute
exit_code = 0
name = options[:name]
prerelease = options[:prerelease]
if options[:installed] then
if name.source.empty? then
alert_error "You must specify a gem name"
exit_code |= 4
elsif installed? name, options[:version] then
say "true"
else
say "false"
exit_code |= 1
end
raise Gem::SystemExitException, exit_code
end
dep = Gem::Dependency.new name, Gem::Requirement.default
if local? then
if prerelease and not both? then
alert_warning "prereleases are always shown locally"
end
if ui.outs.tty? or both? then
say
say "*** LOCAL GEMS ***"
say
end
specs = Gem.source_index.search dep
spec_tuples = specs.map do |spec|
[[spec.name, spec.version, spec.original_platform, spec], :local]
end
output_query_results spec_tuples
end
if remote? then
if ui.outs.tty? or both? then
say
say "*** REMOTE GEMS ***"
say
end
all = options[:all]
begin
fetcher = Gem::SpecFetcher.fetcher
spec_tuples = fetcher.find_matching dep, all, false, prerelease
spec_tuples += fetcher.find_matching dep, false, false, true if
prerelease and all
rescue Gem::RemoteFetcher::FetchError => e
if prerelease then
raise Gem::OperationNotSupportedError,
"Prereleases not supported on legacy repositories"
end
raise unless fetcher.warn_legacy e do
require 'rubygems/source_info_cache'
dep.name = '' if dep.name == //
specs = Gem::SourceInfoCache.search_with_source dep, false, all
spec_tuples = specs.map do |spec, source_uri|
[[spec.name, spec.version, spec.original_platform, spec],
source_uri]
end
end
end
output_query_results spec_tuples
end
end
private
##
# Check if gem +name+ version +version+ is installed.
def installed?(name, version = Gem::Requirement.default)
dep = Gem::Dependency.new name, version
!Gem.source_index.search(dep).empty?
end
def output_query_results(spec_tuples)
output = []
versions = Hash.new { |h,name| h[name] = [] }
spec_tuples.each do |spec_tuple, source_uri|
versions[spec_tuple.first] << [spec_tuple, source_uri]
end
versions = versions.sort_by do |(name,_),_|
name.downcase
end
versions.each do |gem_name, matching_tuples|
matching_tuples = matching_tuples.sort_by do |(name, version,_),_|
version
end.reverse
platforms = Hash.new { |h,version| h[version] = [] }
matching_tuples.map do |(name, version, platform,_),_|
platforms[version] << platform if platform
end
seen = {}
matching_tuples.delete_if do |(name, version,_),_|
if seen[version] then
true
else
seen[version] = true
false
end
end
entry = gem_name.dup
if options[:versions] then
versions = matching_tuples.map { |(name, version,_),_| version }.uniq
entry << " (#{versions.join ', '})"
end
if options[:details] then
detail_tuple = matching_tuples.first
spec = if detail_tuple.first.length == 4 then
detail_tuple.first.last
else
uri = URI.parse detail_tuple.last
Gem::SpecFetcher.fetcher.fetch_spec detail_tuple.first, uri
end
entry << "\n"
non_ruby = platforms.any? do |_, pls|
pls.any? { |pl| pl != Gem::Platform::RUBY }
end
if non_ruby then
if platforms.length == 1 then
title = platforms.values.length == 1 ? 'Platform' : 'Platforms'
entry << " #{title}: #{platforms.values.sort.join ', '}\n"
else
entry << " Platforms:\n"
platforms.sort_by do |version,|
version
end.each do |version, pls|
label = " #{version}: "
data = format_text pls.sort.join(', '), 68, label.length
data[0, label.length] = label
entry << data << "\n"
end
end
end
authors = "Author#{spec.authors.length > 1 ? 's' : ''}: "
authors << spec.authors.join(', ')
entry << format_text(authors, 68, 4)
if spec.rubyforge_project and not spec.rubyforge_project.empty? then
rubyforge = "Rubyforge: http://rubyforge.org/projects/#{spec.rubyforge_project}"
entry << "\n" << format_text(rubyforge, 68, 4)
end
if spec.homepage and not spec.homepage.empty? then
entry << "\n" << format_text("Homepage: #{spec.homepage}", 68, 4)
end
if spec.license and not spec.license.empty? then
licenses = "License#{spec.licenses.length > 1 ? 's' : ''}: "
licenses << spec.licenses.join(', ')
entry << "\n" << format_text(licenses, 68, 4)
end
if spec.loaded_from then
if matching_tuples.length == 1 then
loaded_from = File.dirname File.dirname(spec.loaded_from)
entry << "\n" << " Installed at: #{loaded_from}"
else
label = 'Installed at'
matching_tuples.each do |(_,version,_,s),|
loaded_from = File.dirname File.dirname(s.loaded_from)
entry << "\n" << " #{label} (#{version}): #{loaded_from}"
label = ' ' * label.length
end
end
end
entry << "\n\n" << format_text(spec.summary, 68, 4)
end
output << entry
end
say output.join(options[:details] ? "\n\n" : "\n")
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/contents_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/contents_command.rb | require 'rubygems/command'
require 'rubygems/version_option'
class Gem::Commands::ContentsCommand < Gem::Command
include Gem::VersionOption
def initialize
super 'contents', 'Display the contents of the installed gems',
:specdirs => [], :lib_only => false
add_version_option
add_option( '--all',
"Contents for all gems") do |all, options|
options[:all] = all
end
add_option('-s', '--spec-dir a,b,c', Array,
"Search for gems under specific paths") do |spec_dirs, options|
options[:specdirs] = spec_dirs
end
add_option('-l', '--[no-]lib-only',
"Only return files in the Gem's lib_dirs") do |lib_only, options|
options[:lib_only] = lib_only
end
add_option( '--[no-]prefix',
"Don't include installed path prefix") do |prefix, options|
options[:prefix] = prefix
end
end
def arguments # :nodoc:
"GEMNAME name of gem to list contents for"
end
def defaults_str # :nodoc:
"--no-lib-only --prefix"
end
def usage # :nodoc:
"#{program_name} GEMNAME [GEMNAME ...]"
end
def execute
version = options[:version] || Gem::Requirement.default
spec_dirs = options[:specdirs].map do |i|
[i, File.join(i, "specifications")]
end.flatten
path_kind = if spec_dirs.empty? then
spec_dirs = Gem::SourceIndex.installed_spec_directories
"default gem paths"
else
"specified path"
end
si = Gem::SourceIndex.from_gems_in(*spec_dirs)
gem_names = if options[:all] then
si.map { |_, spec| spec.name }
else
get_all_gem_names
end
gem_names.each do |name|
gem_spec = si.find_name(name, version).last
unless gem_spec then
say "Unable to find gem '#{name}' in #{path_kind}"
if Gem.configuration.verbose then
say "\nDirectories searched:"
spec_dirs.each { |dir| say dir }
end
terminate_interaction 1 if gem_names.length == 1
end
files = options[:lib_only] ? gem_spec.lib_files : gem_spec.files
files.each do |f|
path = if options[:prefix] then
File.join gem_spec.full_gem_path, f
else
f
end
say path
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/install_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/install_command.rb | require 'rubygems/command'
require 'rubygems/doc_manager'
require 'rubygems/install_update_options'
require 'rubygems/dependency_installer'
require 'rubygems/local_remote_options'
require 'rubygems/validator'
require 'rubygems/version_option'
##
# Gem installer command line tool
#
# See `gem help install`
class Gem::Commands::InstallCommand < Gem::Command
include Gem::VersionOption
include Gem::LocalRemoteOptions
include Gem::InstallUpdateOptions
def initialize
defaults = Gem::DependencyInstaller::DEFAULT_OPTIONS.merge({
:generate_rdoc => true,
:generate_ri => true,
:format_executable => false,
:test => false,
:version => Gem::Requirement.default,
})
super 'install', 'Install a gem into the local repository', defaults
add_install_update_options
add_local_remote_options
add_platform_option
add_version_option
add_prerelease_option "to be installed. (Only for listed gems)"
end
def arguments # :nodoc:
"GEMNAME name of gem to install"
end
def defaults_str # :nodoc:
"--both --version '#{Gem::Requirement.default}' --rdoc --ri --no-force\n" \
"--no-test --install-dir #{Gem.dir}"
end
def description # :nodoc:
<<-EOF
The install command installs local or remote gem into a gem repository.
For gems with executables ruby installs a wrapper file into the executable
directory by default. This can be overridden with the --no-wrappers option.
The wrapper allows you to choose among alternate gem versions using _version_.
For example `rake _0.7.3_ --version` will run rake version 0.7.3 if a newer
version is also installed.
If an extension fails to compile during gem installation the gem
specification is not written out, but the gem remains unpacked in the
repository. You may need to specify the path to the library's headers and
libraries to continue. You can do this by adding a -- between RubyGems'
options and the extension's build options:
$ gem install some_extension_gem
[build fails]
Gem files will remain installed in \\
/path/to/gems/some_extension_gem-1.0 for inspection.
Results logged to /path/to/gems/some_extension_gem-1.0/gem_make.out
$ gem install some_extension_gem -- --with-extension-lib=/path/to/lib
[build succeeds]
$ gem list some_extension_gem
*** LOCAL GEMS ***
some_extension_gem (1.0)
$
If you correct the compilation errors by editing the gem files you will need
to write the specification by hand. For example:
$ gem install some_extension_gem
[build fails]
Gem files will remain installed in \\
/path/to/gems/some_extension_gem-1.0 for inspection.
Results logged to /path/to/gems/some_extension_gem-1.0/gem_make.out
$ [cd /path/to/gems/some_extension_gem-1.0]
$ [edit files or what-have-you and run make]
$ gem spec ../../cache/some_extension_gem-1.0.gem --ruby > \\
../../specifications/some_extension_gem-1.0.gemspec
$ gem list some_extension_gem
*** LOCAL GEMS ***
some_extension_gem (1.0)
$
EOF
end
def usage # :nodoc:
"#{program_name} GEMNAME [GEMNAME ...] [options] -- --build-flags"
end
def execute
if options[:include_dependencies] then
alert "`gem install -y` is now default and will be removed"
alert "use --ignore-dependencies to install only the gems you list"
end
installed_gems = []
ENV.delete 'GEM_PATH' if options[:install_dir].nil? and RUBY_VERSION > '1.9'
exit_code = 0
get_all_gem_names.each do |gem_name|
begin
inst = Gem::DependencyInstaller.new options
inst.install gem_name, options[:version]
inst.installed_gems.each do |spec|
say "Successfully installed #{spec.full_name}"
end
installed_gems.push(*inst.installed_gems)
rescue Gem::InstallError => e
alert_error "Error installing #{gem_name}:\n\t#{e.message}"
exit_code |= 1
rescue Gem::GemNotFoundException => e
alert_error e.message
exit_code |= 2
end
end
unless installed_gems.empty? then
gems = installed_gems.length == 1 ? 'gem' : 'gems'
say "#{installed_gems.length} #{gems} installed"
# NOTE: *All* of the RI documents must be generated first. For some
# reason, RI docs cannot be generated after any RDoc documents are
# generated.
if options[:generate_ri] then
installed_gems.each do |gem|
Gem::DocManager.new(gem, options[:rdoc_args]).generate_ri
end
Gem::DocManager.update_ri_cache
end
if options[:generate_rdoc] then
installed_gems.each do |gem|
Gem::DocManager.new(gem, options[:rdoc_args]).generate_rdoc
end
end
if options[:test] then
installed_gems.each do |spec|
gem_spec = Gem::SourceIndex.from_installed_gems.find_name(spec.name, spec.version.version).first
result = Gem::Validator.new.unit_test(gem_spec)
if result and not result.passed?
unless ask_yes_no("...keep Gem?", true)
require 'rubygems/uninstaller'
Gem::Uninstaller.new(spec.name, :version => spec.version.version).uninstall
end
end
end
end
end
raise Gem::SystemExitException, exit_code
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/check_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/check_command.rb | require 'rubygems/command'
require 'rubygems/version_option'
require 'rubygems/validator'
class Gem::Commands::CheckCommand < Gem::Command
include Gem::VersionOption
def initialize
super 'check', 'Check installed gems',
:verify => false, :alien => false
add_option( '--verify FILE',
'Verify gem file against its internal',
'checksum') do |value, options|
options[:verify] = value
end
add_option('-a', '--alien', "Report 'unmanaged' or rogue files in the",
"gem repository") do |value, options|
options[:alien] = true
end
add_option('-v', '--verbose', "Spew more words") do |value, options|
options[:verbose] = true
end
add_option('-t', '--test', "Run unit tests for gem") do |value, options|
options[:test] = true
end
add_version_option 'run tests for'
end
def execute
if options[:test]
version = options[:version] || Gem::Requirement.default
dep = Gem::Dependency.new get_one_gem_name, version
gem_spec = Gem::SourceIndex.from_installed_gems.search(dep).first
Gem::Validator.new.unit_test(gem_spec)
end
if options[:alien]
say "Performing the 'alien' operation"
say
gems = get_all_gem_names rescue []
Gem::Validator.new.alien(gems).sort.each do |key, val|
unless val.empty? then
say "#{key} has #{val.size} problems"
val.each do |error_entry|
say " #{error_entry.path}:"
say " #{error_entry.problem}"
end
else
say "#{key} is error-free" if options[:verbose]
end
say
end
end
if options[:verify]
gem_name = options[:verify]
unless gem_name
alert_error "Must specify a .gem file with --verify NAME"
return
end
unless File.exist?(gem_name)
alert_error "Unknown file: #{gem_name}."
return
end
say "Verifying gem: '#{gem_name}'"
begin
Gem::Validator.new.verify_gem_file(gem_name)
rescue Exception => e
alert_error "#{gem_name} is invalid."
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/help_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/help_command.rb | require 'rubygems/command'
class Gem::Commands::HelpCommand < Gem::Command
# :stopdoc:
EXAMPLES = <<-EOF
Some examples of 'gem' usage.
* Install 'rake', either from local directory or remote server:
gem install rake
* Install 'rake', only from remote server:
gem install rake --remote
* Install 'rake' from remote server, and run unit tests,
and generate RDocs:
gem install --remote rake --test --rdoc --ri
* Install 'rake', but only version 0.3.1, even if dependencies
are not met, and into a user-specific directory:
gem install rake --version 0.3.1 --force --user-install
* List local gems whose name begins with 'D':
gem list D
* List local and remote gems whose name contains 'log':
gem search log --both
* List only remote gems whose name contains 'log':
gem search log --remote
* Uninstall 'rake':
gem uninstall rake
* Create a gem:
See http://rubygems.rubyforge.org/wiki/wiki.pl?CreateAGemInTenMinutes
* See information about RubyGems:
gem environment
* Update all gems on your system:
gem update
EOF
PLATFORMS = <<-'EOF'
RubyGems platforms are composed of three parts, a CPU, an OS, and a
version. These values are taken from values in rbconfig.rb. You can view
your current platform by running `gem environment`.
RubyGems matches platforms as follows:
* The CPU must match exactly, unless one of the platforms has
"universal" as the CPU.
* The OS must match exactly.
* The versions must match exactly unless one of the versions is nil.
For commands that install, uninstall and list gems, you can override what
RubyGems thinks your platform is with the --platform option. The platform
you pass must match "#{cpu}-#{os}" or "#{cpu}-#{os}-#{version}". On mswin
platforms, the version is the compiler version, not the OS version. (Ruby
compiled with VC6 uses "60" as the compiler version, VC8 uses "80".)
Example platforms:
x86-freebsd # Any FreeBSD version on an x86 CPU
universal-darwin-8 # Darwin 8 only gems that run on any CPU
x86-mswin32-80 # Windows gems compiled with VC8
When building platform gems, set the platform in the gem specification to
Gem::Platform::CURRENT. This will correctly mark the gem with your ruby's
platform.
EOF
# :startdoc:
def initialize
super 'help', "Provide help on the 'gem' command"
end
def arguments # :nodoc:
args = <<-EOF
commands List all 'gem' commands
examples Show examples of 'gem' usage
<command> Show specific help for <command>
EOF
return args.gsub(/^\s+/, '')
end
def usage # :nodoc:
"#{program_name} ARGUMENT"
end
def execute
command_manager = Gem::CommandManager.instance
arg = options[:args][0]
if begins? "commands", arg then
out = []
out << "GEM commands are:"
out << nil
margin_width = 4
desc_width = command_manager.command_names.map { |n| n.size }.max + 4
summary_width = 80 - margin_width - desc_width
wrap_indent = ' ' * (margin_width + desc_width)
format = "#{' ' * margin_width}%-#{desc_width}s%s"
command_manager.command_names.each do |cmd_name|
summary = command_manager[cmd_name].summary
summary = wrap(summary, summary_width).split "\n"
out << sprintf(format, cmd_name, summary.shift)
until summary.empty? do
out << "#{wrap_indent}#{summary.shift}"
end
end
out << nil
out << "For help on a particular command, use 'gem help COMMAND'."
out << nil
out << "Commands may be abbreviated, so long as they are unambiguous."
out << "e.g. 'gem i rake' is short for 'gem install rake'."
say out.join("\n")
elsif begins? "options", arg then
say Gem::Command::HELP
elsif begins? "examples", arg then
say EXAMPLES
elsif begins? "platforms", arg then
say PLATFORMS
elsif options[:help] then
command = command_manager[options[:help]]
if command
# help with provided command
command.invoke("--help")
else
alert_error "Unknown command #{options[:help]}. Try 'gem help commands'"
end
elsif arg then
possibilities = command_manager.find_command_possibilities(arg.downcase)
if possibilities.size == 1
command = command_manager[possibilities.first]
command.invoke("--help")
elsif possibilities.size > 1
alert_warning "Ambiguous command #{arg} (#{possibilities.join(', ')})"
else
alert_warning "Unknown command #{arg}. Try gem help commands"
end
else
say Gem::Command::HELP
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/stale_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/stale_command.rb | require 'rubygems/command'
class Gem::Commands::StaleCommand < Gem::Command
def initialize
super('stale', 'List gems along with access times')
end
def usage # :nodoc:
"#{program_name}"
end
def execute
gem_to_atime = {}
Gem.source_index.each do |name, spec|
Dir["#{spec.full_gem_path}/**/*.*"].each do |file|
next if File.directory?(file)
stat = File.stat(file)
gem_to_atime[name] ||= stat.atime
gem_to_atime[name] = stat.atime if gem_to_atime[name] < stat.atime
end
end
gem_to_atime.sort_by { |_, atime| atime }.each do |name, atime|
say "#{name} at #{atime.strftime '%c'}"
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/uninstall_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/uninstall_command.rb | require 'rubygems/command'
require 'rubygems/version_option'
require 'rubygems/uninstaller'
##
# Gem uninstaller command line tool
#
# See `gem help uninstall`
class Gem::Commands::UninstallCommand < Gem::Command
include Gem::VersionOption
def initialize
super 'uninstall', 'Uninstall gems from the local repository',
:version => Gem::Requirement.default, :user_install => true
add_option('-a', '--[no-]all',
'Uninstall all matching versions'
) do |value, options|
options[:all] = value
end
add_option('-I', '--[no-]ignore-dependencies',
'Ignore dependency requirements while',
'uninstalling') do |value, options|
options[:ignore] = value
end
add_option('-x', '--[no-]executables',
'Uninstall applicable executables without',
'confirmation') do |value, options|
options[:executables] = value
end
add_option('-i', '--install-dir DIR',
'Directory to uninstall gem from') do |value, options|
options[:install_dir] = File.expand_path(value)
end
add_option('-n', '--bindir DIR',
'Directory to remove binaries from') do |value, options|
options[:bin_dir] = File.expand_path(value)
end
add_option('--[no-]user-install',
'Uninstall from user\'s home directory',
'in addition to GEM_HOME.') do |value, options|
options[:user_install] = value
end
add_version_option
add_platform_option
end
def arguments # :nodoc:
"GEMNAME name of gem to uninstall"
end
def defaults_str # :nodoc:
"--version '#{Gem::Requirement.default}' --no-force " \
"--install-dir #{Gem.dir}\n" \
"--user-install"
end
def usage # :nodoc:
"#{program_name} GEMNAME [GEMNAME ...]"
end
def execute
get_all_gem_names.each do |gem_name|
begin
Gem::Uninstaller.new(gem_name, options).uninstall
rescue Gem::GemNotInHomeException => e
spec = e.spec
alert("In order to remove #{spec.name}, please execute:\n" \
"\tgem uninstall #{spec.name} --install-dir=#{spec.installation_path}")
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/dependency_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/dependency_command.rb | require 'rubygems/command'
require 'rubygems/local_remote_options'
require 'rubygems/version_option'
require 'rubygems/source_info_cache'
class Gem::Commands::DependencyCommand < Gem::Command
include Gem::LocalRemoteOptions
include Gem::VersionOption
def initialize
super 'dependency',
'Show the dependencies of an installed gem',
:version => Gem::Requirement.default, :domain => :local
add_version_option
add_platform_option
add_prerelease_option
add_option('-R', '--[no-]reverse-dependencies',
'Include reverse dependencies in the output') do
|value, options|
options[:reverse_dependencies] = value
end
add_option('-p', '--pipe',
"Pipe Format (name --version ver)") do |value, options|
options[:pipe_format] = value
end
add_local_remote_options
end
def arguments # :nodoc:
"GEMNAME name of gem to show dependencies for"
end
def defaults_str # :nodoc:
"--local --version '#{Gem::Requirement.default}' --no-reverse-dependencies"
end
def usage # :nodoc:
"#{program_name} GEMNAME"
end
def execute
options[:args] << '' if options[:args].empty?
specs = {}
source_indexes = Hash.new do |h, source_uri|
h[source_uri] = Gem::SourceIndex.new
end
pattern = if options[:args].length == 1 and
options[:args].first =~ /\A\/(.*)\/(i)?\z/m then
flags = $2 ? Regexp::IGNORECASE : nil
Regexp.new $1, flags
else
/\A#{Regexp.union(*options[:args])}/
end
dependency = Gem::Dependency.new pattern, options[:version]
dependency.prerelease = options[:prerelease]
if options[:reverse_dependencies] and remote? and not local? then
alert_error 'Only reverse dependencies for local gems are supported.'
terminate_interaction 1
end
if local? then
Gem.source_index.search(dependency).each do |spec|
source_indexes[:local].add_spec spec
end
end
if remote? and not options[:reverse_dependencies] then
fetcher = Gem::SpecFetcher.fetcher
begin
specs_and_sources = fetcher.find_matching(dependency, false, true,
dependency.prerelease?)
specs_and_sources.each do |spec_tuple, source_uri|
spec = fetcher.fetch_spec spec_tuple, URI.parse(source_uri)
source_indexes[source_uri].add_spec spec
end
rescue Gem::RemoteFetcher::FetchError => e
raise unless fetcher.warn_legacy e do
require 'rubygems/source_info_cache'
specs = Gem::SourceInfoCache.search_with_source dependency, false
specs.each do |spec, source_uri|
source_indexes[source_uri].add_spec spec
end
end
end
end
if source_indexes.empty? then
patterns = options[:args].join ','
say "No gems found matching #{patterns} (#{options[:version]})" if
Gem.configuration.verbose
terminate_interaction 1
end
specs = {}
source_indexes.values.each do |source_index|
source_index.gems.each do |name, spec|
specs[spec.full_name] = [source_index, spec]
end
end
reverse = Hash.new { |h, k| h[k] = [] }
if options[:reverse_dependencies] then
specs.values.each do |_, spec|
reverse[spec.full_name] = find_reverse_dependencies spec
end
end
if options[:pipe_format] then
specs.values.sort_by { |_, spec| spec }.each do |_, spec|
unless spec.dependencies.empty?
spec.dependencies.sort_by { |dep| dep.name }.each do |dep|
say "#{dep.name} --version '#{dep.requirement}'"
end
end
end
else
response = ''
specs.values.sort_by { |_, spec| spec }.each do |_, spec|
response << print_dependencies(spec)
unless reverse[spec.full_name].empty? then
response << " Used by\n"
reverse[spec.full_name].each do |sp, dep|
response << " #{sp} (#{dep})\n"
end
end
response << "\n"
end
say response
end
end
def print_dependencies(spec, level = 0)
response = ''
response << ' ' * level + "Gem #{spec.full_name}\n"
unless spec.dependencies.empty? then
spec.dependencies.sort_by { |dep| dep.name }.each do |dep|
response << ' ' * level + " #{dep}\n"
end
end
response
end
# Retuns list of [specification, dep] that are satisfied by spec.
def find_reverse_dependencies(spec)
result = []
Gem.source_index.each do |name, sp|
sp.dependencies.each do |dep|
dep = Gem::Dependency.new(*dep) unless Gem::Dependency === dep
if spec.name == dep.name and
dep.requirement.satisfied_by?(spec.version) then
result << [sp.full_name, dep]
end
end
end
result
end
def find_gems(name, source_index)
specs = {}
spec_list = source_index.search name, options[:version]
spec_list.each do |spec|
specs[spec.full_name] = [source_index, spec]
end
specs
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/fetch_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/fetch_command.rb | require 'rubygems/command'
require 'rubygems/local_remote_options'
require 'rubygems/version_option'
require 'rubygems/source_info_cache'
class Gem::Commands::FetchCommand < Gem::Command
include Gem::LocalRemoteOptions
include Gem::VersionOption
def initialize
super 'fetch', 'Download a gem and place it in the current directory'
add_bulk_threshold_option
add_proxy_option
add_source_option
add_version_option
add_platform_option
add_prerelease_option
end
def arguments # :nodoc:
'GEMNAME name of gem to download'
end
def defaults_str # :nodoc:
"--version '#{Gem::Requirement.default}'"
end
def usage # :nodoc:
"#{program_name} GEMNAME [GEMNAME ...]"
end
def execute
version = options[:version] || Gem::Requirement.default
all = Gem::Requirement.default
gem_names = get_all_gem_names
gem_names.each do |gem_name|
dep = Gem::Dependency.new gem_name, version
dep.prerelease = options[:prerelease]
specs_and_sources = Gem::SpecFetcher.fetcher.fetch(dep, false, true,
dep.prerelease?)
spec, source_uri = specs_and_sources.sort_by { |s,| s.version }.last
if spec.nil? then
alert_error "Could not find #{gem_name} in any repository"
next
end
path = Gem::RemoteFetcher.fetcher.download spec, source_uri
FileUtils.mv path, spec.file_name
say "Downloaded #{spec.full_name}"
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/generate_index_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/generate_index_command.rb | require 'rubygems/command'
require 'rubygems/indexer'
##
# Generates a index files for use as a gem server.
#
# See `gem help generate_index`
class Gem::Commands::GenerateIndexCommand < Gem::Command
def initialize
super 'generate_index',
'Generates the index files for a gem server directory',
:directory => '.', :build_legacy => true, :build_modern => true
add_option '-d', '--directory=DIRNAME',
'repository base dir containing gems subdir' do |dir, options|
options[:directory] = File.expand_path dir
end
add_option '--[no-]legacy',
'Generate indexes for RubyGems older than',
'1.2.0' do |value, options|
unless options[:build_modern] or value then
raise OptionParser::InvalidOption, 'no indicies will be built'
end
options[:build_legacy] = value
end
add_option '--[no-]modern',
'Generate indexes for RubyGems newer',
'than 1.2.0' do |value, options|
unless options[:build_legacy] or value then
raise OptionParser::InvalidOption, 'no indicies will be built'
end
options[:build_modern] = value
end
add_option '--update',
'Update modern indexes with gems added',
'since the last update' do |value, options|
options[:update] = value
end
add_option :RSS, '--rss-gems-host=GEM_HOST',
'Host name where gems are served from,',
'used for GUID and enclosure values' do |value, options|
options[:rss_gems_host] = value
end
add_option :RSS, '--rss-host=HOST',
'Host name for more gems information,',
'used for RSS feed link' do |value, options|
options[:rss_host] = value
end
add_option :RSS, '--rss-title=TITLE',
'Set title for RSS feed' do |value, options|
options[:rss_title] = value
end
end
def defaults_str # :nodoc:
"--directory . --legacy --modern"
end
def description # :nodoc:
<<-EOF
The generate_index command creates a set of indexes for serving gems
statically. The command expects a 'gems' directory under the path given to
the --directory option. The given directory will be the directory you serve
as the gem repository.
For `gem generate_index --directory /path/to/repo`, expose /path/to/repo via
your HTTP server configuration (not /path/to/repo/gems).
When done, it will generate a set of files like this:
gems/*.gem # .gem files you want to
# index
specs.<version>.gz # specs index
latest_specs.<version>.gz # latest specs index
prerelease_specs.<version>.gz # prerelease specs index
quick/Marshal.<version>/<gemname>.gemspec.rz # Marshal quick index file
# these files support legacy RubyGems
quick/index
quick/index.rz # quick index manifest
quick/<gemname>.gemspec.rz # legacy YAML quick index
# file
Marshal.<version>
Marshal.<version>.Z # Marshal full index
yaml
yaml.Z # legacy YAML full index
The .Z and .rz extension files are compressed with the inflate algorithm.
The Marshal version number comes from ruby's Marshal::MAJOR_VERSION and
Marshal::MINOR_VERSION constants. It is used to ensure compatibility.
The yaml indexes exist for legacy RubyGems clients and fallback in case of
Marshal version changes.
If --rss-host and --rss-gem-host are given an RSS feed will be generated at
index.rss containing gems released in the last two days.
EOF
end
def execute
if options[:update] and
(options[:rss_host] or options[:rss_gems_host]) then
alert_error '--update not compatible with RSS generation'
terminate_interaction 1
end
if not File.exist?(options[:directory]) or
not File.directory?(options[:directory]) then
alert_error "unknown directory name #{directory}."
terminate_interaction 1
else
indexer = Gem::Indexer.new options.delete(:directory), options
if options[:update] then
indexer.update_index
else
indexer.generate_index
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/which_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/which_command.rb | require 'rubygems/command'
require 'rubygems/gem_path_searcher'
class Gem::Commands::WhichCommand < Gem::Command
EXT = %w[.rb .rbw .so .dll .bundle] # HACK
def initialize
super 'which', 'Find the location of a library file you can require',
:search_gems_first => false, :show_all => false
add_option '-a', '--[no-]all', 'show all matching files' do |show_all, options|
options[:show_all] = show_all
end
add_option '-g', '--[no-]gems-first',
'search gems before non-gems' do |gems_first, options|
options[:search_gems_first] = gems_first
end
end
def arguments # :nodoc:
"FILE name of file to find"
end
def defaults_str # :nodoc:
"--no-gems-first --no-all"
end
def execute
searcher = Gem::GemPathSearcher.new
found = false
options[:args].each do |arg|
dirs = $LOAD_PATH
spec = searcher.find arg
if spec then
if options[:search_gems_first] then
dirs = gem_paths(spec) + $LOAD_PATH
else
dirs = $LOAD_PATH + gem_paths(spec)
end
end
paths = find_paths arg, dirs
if paths.empty? then
alert_error "Can't find ruby library file or shared library #{arg}"
else
say paths
found = true
end
end
terminate_interaction 1 unless found
end
def find_paths(package_name, dirs)
result = []
dirs.each do |dir|
EXT.each do |ext|
full_path = File.join dir, "#{package_name}#{ext}"
if File.exist? full_path then
result << full_path
return result unless options[:show_all]
end
end
end
result
end
def gem_paths(spec)
spec.require_paths.collect { |d| File.join spec.full_gem_path, d }
end
def usage # :nodoc:
"#{program_name} FILE [FILE ...]"
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/server_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/server_command.rb | require 'rubygems/command'
require 'rubygems/server'
class Gem::Commands::ServerCommand < Gem::Command
def initialize
super 'server', 'Documentation and gem repository HTTP server',
:port => 8808, :gemdir => Gem.dir, :daemon => false
OptionParser.accept :Port do |port|
if port =~ /\A\d+\z/ then
port = Integer port
raise OptionParser::InvalidArgument, "#{port}: not a port number" if
port > 65535
port
else
begin
Socket.getservbyname port
rescue SocketError => e
raise OptionParser::InvalidArgument, "#{port}: no such named service"
end
end
end
add_option '-p', '--port=PORT', :Port,
'port to listen on' do |port, options|
options[:port] = port
end
add_option '-d', '--dir=GEMDIR',
'directory from which to serve gems' do |gemdir, options|
options[:gemdir] = File.expand_path gemdir
end
add_option '--[no-]daemon', 'run as a daemon' do |daemon, options|
options[:daemon] = daemon
end
add_option '-b', '--bind=HOST,HOST',
'addresses to bind', Array do |address, options|
options[:addresses] ||= []
options[:addresses].push(*address)
end
end
def defaults_str # :nodoc:
"--port 8808 --dir #{Gem.dir} --no-daemon"
end
def description # :nodoc:
<<-EOF
The server command starts up a web server that hosts the RDoc for your
installed gems and can operate as a server for installation of gems on other
machines.
The cache files for installed gems must exist to use the server as a source
for gem installation.
To install gems from a running server, use `gem install GEMNAME --source
http://gem_server_host:8808`
You can set up a shortcut to gem server documentation using the URL:
http://localhost:8808/rdoc?q=%s - Firefox
http://localhost:8808/rdoc?q=* - LaunchBar
EOF
end
def execute
Gem::Server.run options
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/sources_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/sources_command.rb | require 'fileutils'
require 'rubygems/command'
require 'rubygems/remote_fetcher'
require 'rubygems/source_info_cache'
require 'rubygems/spec_fetcher'
require 'rubygems/local_remote_options'
class Gem::Commands::SourcesCommand < Gem::Command
include Gem::LocalRemoteOptions
def initialize
super 'sources',
'Manage the sources and cache file RubyGems uses to search for gems'
add_option '-a', '--add SOURCE_URI', 'Add source' do |value, options|
options[:add] = value
end
add_option '-l', '--list', 'List sources' do |value, options|
options[:list] = value
end
add_option '-r', '--remove SOURCE_URI', 'Remove source' do |value, options|
options[:remove] = value
end
add_option '-c', '--clear-all',
'Remove all sources (clear the cache)' do |value, options|
options[:clear_all] = value
end
add_option '-u', '--update', 'Update source cache' do |value, options|
options[:update] = value
end
add_proxy_option
end
def defaults_str
'--list'
end
def execute
options[:list] = !(options[:add] ||
options[:clear_all] ||
options[:remove] ||
options[:update])
if options[:clear_all] then
path = Gem::SpecFetcher.fetcher.dir
FileUtils.rm_rf path
if not File.exist?(path) then
say "*** Removed specs cache ***"
elsif not File.writable?(path) then
say "*** Unable to remove source cache (write protected) ***"
else
say "*** Unable to remove source cache ***"
end
sic = Gem::SourceInfoCache
remove_cache_file 'user', sic.user_cache_file
remove_cache_file 'latest user', sic.latest_user_cache_file
remove_cache_file 'system', sic.system_cache_file
remove_cache_file 'latest system', sic.latest_system_cache_file
end
if options[:add] then
source_uri = options[:add]
uri = URI.parse source_uri
begin
Gem::SpecFetcher.fetcher.load_specs uri, 'specs'
Gem.sources << source_uri
Gem.configuration.write
say "#{source_uri} added to sources"
rescue URI::Error, ArgumentError
say "#{source_uri} is not a URI"
rescue Gem::RemoteFetcher::FetchError => e
yaml_uri = uri + 'yaml'
gem_repo = Gem::RemoteFetcher.fetcher.fetch_size yaml_uri rescue false
if e.uri =~ /specs\.#{Regexp.escape Gem.marshal_version}\.gz$/ and
gem_repo then
alert_warning <<-EOF
RubyGems 1.2+ index not found for:
\t#{source_uri}
Will cause RubyGems to revert to legacy indexes, degrading performance.
EOF
say "#{source_uri} added to sources"
else
say "Error fetching #{source_uri}:\n\t#{e.message}"
end
end
end
if options[:remove] then
source_uri = options[:remove]
unless Gem.sources.include? source_uri then
say "source #{source_uri} not present in cache"
else
Gem.sources.delete source_uri
Gem.configuration.write
say "#{source_uri} removed from sources"
end
end
if options[:update] then
fetcher = Gem::SpecFetcher.fetcher
if fetcher.legacy_repos.empty? then
Gem.sources.each do |update_uri|
update_uri = URI.parse update_uri
fetcher.load_specs update_uri, 'specs'
fetcher.load_specs update_uri, 'latest_specs'
end
else
Gem::SourceInfoCache.cache true
Gem::SourceInfoCache.cache.flush
end
say "source cache successfully updated"
end
if options[:list] then
say "*** CURRENT SOURCES ***"
say
Gem.sources.each do |source|
say source
end
end
end
private
def remove_cache_file(desc, path)
FileUtils.rm_rf path
if not File.exist?(path) then
say "*** Removed #{desc} source cache ***"
elsif not File.writable?(path) then
say "*** Unable to remove #{desc} source cache (write protected) ***"
else
say "*** Unable to remove #{desc} source cache ***"
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/update_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/update_command.rb | require 'rubygems/command'
require 'rubygems/command_manager'
require 'rubygems/install_update_options'
require 'rubygems/local_remote_options'
require 'rubygems/spec_fetcher'
require 'rubygems/version_option'
require 'rubygems/commands/install_command'
class Gem::Commands::UpdateCommand < Gem::Command
include Gem::InstallUpdateOptions
include Gem::LocalRemoteOptions
include Gem::VersionOption
def initialize
super 'update',
'Update the named gems (or all installed gems) in the local repository',
:generate_rdoc => true,
:generate_ri => true,
:force => false,
:test => false
add_install_update_options
add_option('--system',
'Update the RubyGems system software') do |value, options|
options[:system] = value
end
add_local_remote_options
add_platform_option
add_prerelease_option "as update targets"
end
def arguments # :nodoc:
"GEMNAME name of gem to update"
end
def defaults_str # :nodoc:
"--rdoc --ri --no-force --no-test --install-dir #{Gem.dir}"
end
def usage # :nodoc:
"#{program_name} GEMNAME [GEMNAME ...]"
end
def execute
hig = {}
if options[:system] then
say "Updating RubyGems"
unless options[:args].empty? then
raise "No gem names are allowed with the --system option"
end
rubygems_update = Gem::Specification.new
rubygems_update.name = 'rubygems-update'
rubygems_update.version = Gem::Version.new Gem::RubyGemsVersion
hig['rubygems-update'] = rubygems_update
options[:user_install] = false
else
say "Updating installed gems"
hig = {} # highest installed gems
Gem.source_index.each do |name, spec|
if hig[spec.name].nil? or hig[spec.name].version < spec.version then
hig[spec.name] = spec
end
end
end
gems_to_update = which_to_update hig, options[:args]
updated = []
installer = Gem::DependencyInstaller.new options
gems_to_update.uniq.sort.each do |name|
next if updated.any? { |spec| spec.name == name }
success = false
say "Updating #{name}"
begin
installer.install name
success = true
rescue Gem::InstallError => e
alert_error "Error installing #{name}:\n\t#{e.message}"
success = false
end
installer.installed_gems.each do |spec|
updated << spec
say "Successfully installed #{spec.full_name}" if success
end
end
if gems_to_update.include? "rubygems-update" then
Gem.source_index.refresh!
update_gems = Gem.source_index.find_name 'rubygems-update'
latest_update_gem = update_gems.sort_by { |s| s.version }.last
say "Updating RubyGems to #{latest_update_gem.version}"
installed = do_rubygems_update latest_update_gem.version
say "RubyGems system software updated" if installed
else
if updated.empty? then
say "Nothing to update"
else
say "Gems updated: #{updated.map { |spec| spec.name }.join ', '}"
if options[:generate_ri] then
updated.each do |gem|
Gem::DocManager.new(gem, options[:rdoc_args]).generate_ri
end
Gem::DocManager.update_ri_cache
end
if options[:generate_rdoc] then
updated.each do |gem|
Gem::DocManager.new(gem, options[:rdoc_args]).generate_rdoc
end
end
end
end
end
##
# Update the RubyGems software to +version+.
def do_rubygems_update(version)
args = []
args.push '--prefix', Gem.prefix unless Gem.prefix.nil?
args << '--no-rdoc' unless options[:generate_rdoc]
args << '--no-ri' unless options[:generate_ri]
args << '--no-format-executable' if options[:no_format_executable]
update_dir = File.join Gem.dir, 'gems', "rubygems-update-#{version}"
Dir.chdir update_dir do
say "Installing RubyGems #{version}"
setup_cmd = "#{Gem.ruby} setup.rb #{args.join ' '}"
# Make sure old rubygems isn't loaded
old = ENV["RUBYOPT"]
ENV.delete("RUBYOPT")
system setup_cmd
ENV["RUBYOPT"] = old if old
end
end
def which_to_update(highest_installed_gems, gem_names)
result = []
highest_installed_gems.each do |l_name, l_spec|
next if not gem_names.empty? and
gem_names.all? { |name| /#{name}/ !~ l_spec.name }
dependency = Gem::Dependency.new l_spec.name, "> #{l_spec.version}"
begin
fetcher = Gem::SpecFetcher.fetcher
spec_tuples = fetcher.find_matching dependency
rescue Gem::RemoteFetcher::FetchError => e
raise unless fetcher.warn_legacy e do
require 'rubygems/source_info_cache'
dependency.name = '' if dependency.name == //
specs = Gem::SourceInfoCache.search_with_source dependency
spec_tuples = specs.map do |spec, source_uri|
[[spec.name, spec.version, spec.original_platform], source_uri]
end
end
end
matching_gems = spec_tuples.select do |(name, version, platform),|
name == l_name and Gem::Platform.match platform
end
highest_remote_gem = matching_gems.sort_by do |(name, version),|
version
end.last
if highest_remote_gem and
l_spec.version < highest_remote_gem.first[1] then
result << l_name
end
end
result
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/mirror_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/mirror_command.rb | require 'yaml'
require 'zlib'
require 'rubygems/command'
require 'open-uri'
class Gem::Commands::MirrorCommand < Gem::Command
def initialize
super 'mirror', 'Mirror a gem repository'
end
def description # :nodoc:
<<-EOF
The mirror command uses the ~/.gemmirrorrc config file to mirror remote gem
repositories to a local path. The config file is a YAML document that looks
like this:
---
- from: http://gems.example.com # source repository URI
to: /path/to/mirror # destination directory
Multiple sources and destinations may be specified.
EOF
end
def execute
config_file = File.join Gem.user_home, '.gemmirrorrc'
raise "Config file #{config_file} not found" unless File.exist? config_file
mirrors = YAML.load_file config_file
raise "Invalid config file #{config_file}" unless mirrors.respond_to? :each
mirrors.each do |mir|
raise "mirror missing 'from' field" unless mir.has_key? 'from'
raise "mirror missing 'to' field" unless mir.has_key? 'to'
get_from = mir['from']
save_to = File.expand_path mir['to']
raise "Directory not found: #{save_to}" unless File.exist? save_to
raise "Not a directory: #{save_to}" unless File.directory? save_to
gems_dir = File.join save_to, "gems"
if File.exist? gems_dir then
raise "Not a directory: #{gems_dir}" unless File.directory? gems_dir
else
Dir.mkdir gems_dir
end
source_index_data = ''
say "fetching: #{get_from}/Marshal.#{Gem.marshal_version}.Z"
get_from = URI.parse get_from
if get_from.scheme.nil? then
get_from = get_from.to_s
elsif get_from.scheme == 'file' then
# check if specified URI contains a drive letter (file:/D:/Temp)
get_from = get_from.to_s
get_from = if get_from =~ /^file:.*[a-z]:/i then
get_from[6..-1]
else
get_from[5..-1]
end
end
open File.join(get_from.to_s, "Marshal.#{Gem.marshal_version}.Z"), "rb" do |y|
source_index_data = Zlib::Inflate.inflate y.read
open File.join(save_to, "Marshal.#{Gem.marshal_version}"), "wb" do |out|
out.write source_index_data
end
end
source_index = Marshal.load source_index_data
progress = ui.progress_reporter source_index.size,
"Fetching #{source_index.size} gems"
source_index.each do |fullname, gem|
gem_file = gem.file_name
gem_dest = File.join gems_dir, gem_file
unless File.exist? gem_dest then
begin
open "#{get_from}/gems/#{gem_file}", "rb" do |g|
contents = g.read
open gem_dest, "wb" do |out|
out.write contents
end
end
rescue
old_gf = gem_file
gem_file = gem_file.downcase
retry if old_gf != gem_file
alert_error $!
end
end
progress.updated gem_file
end
progress.done
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/environment_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/environment_command.rb | require 'rubygems/command'
class Gem::Commands::EnvironmentCommand < Gem::Command
def initialize
super 'environment', 'Display information about the RubyGems environment'
end
def arguments # :nodoc:
args = <<-EOF
packageversion display the package version
gemdir display the path where gems are installed
gempath display path used to search for gems
version display the gem format version
remotesources display the remote gem servers
<omitted> display everything
EOF
return args.gsub(/^\s+/, '')
end
def description # :nodoc:
<<-EOF
The RubyGems environment can be controlled through command line arguments,
gemrc files, environment variables and built-in defaults.
Command line argument defaults and some RubyGems defaults can be set in
~/.gemrc file for individual users and a /etc/gemrc for all users. A gemrc
is a YAML file with the following YAML keys:
:sources: A YAML array of remote gem repositories to install gems from
:verbose: Verbosity of the gem command. false, true, and :really are the
levels
:update_sources: Enable/disable automatic updating of repository metadata
:backtrace: Print backtrace when RubyGems encounters an error
:bulk_threshold: Switch to a bulk update when this many sources are out of
date (legacy setting)
:gempath: The paths in which to look for gems
gem_command: A string containing arguments for the specified gem command
Example:
:verbose: false
install: --no-wrappers
update: --no-wrappers
RubyGems' default local repository can be overriden with the GEM_PATH and
GEM_HOME environment variables. GEM_HOME sets the default repository to
install into. GEM_PATH allows multiple local repositories to be searched for
gems.
If you are behind a proxy server, RubyGems uses the HTTP_PROXY,
HTTP_PROXY_USER and HTTP_PROXY_PASS environment variables to discover the
proxy server.
If you are packaging RubyGems all of RubyGems' defaults are in
lib/rubygems/defaults.rb. You may override these in
lib/rubygems/defaults/operating_system.rb
EOF
end
def usage # :nodoc:
"#{program_name} [arg]"
end
def execute
out = ''
arg = options[:args][0]
case arg
when /^packageversion/ then
out << Gem::RubyGemsPackageVersion
when /^version/ then
out << Gem::RubyGemsVersion
when /^gemdir/, /^gemhome/, /^home/, /^GEM_HOME/ then
out << Gem.dir
when /^gempath/, /^path/, /^GEM_PATH/ then
out << Gem.path.join(File::PATH_SEPARATOR)
when /^remotesources/ then
out << Gem.sources.join("\n")
when nil then
out = "RubyGems Environment:\n"
out << " - RUBYGEMS VERSION: #{Gem::RubyGemsVersion}\n"
out << " - RUBY VERSION: #{RUBY_VERSION} (#{RUBY_RELEASE_DATE}"
out << " patchlevel #{RUBY_PATCHLEVEL}" if defined? RUBY_PATCHLEVEL
out << ") [#{RUBY_PLATFORM}]\n"
out << " - INSTALLATION DIRECTORY: #{Gem.dir}\n"
out << " - RUBYGEMS PREFIX: #{Gem.prefix}\n" unless Gem.prefix.nil?
out << " - RUBY EXECUTABLE: #{Gem.ruby}\n"
out << " - EXECUTABLE DIRECTORY: #{Gem.bindir}\n"
out << " - RUBYGEMS PLATFORMS:\n"
Gem.platforms.each do |platform|
out << " - #{platform}\n"
end
out << " - GEM PATHS:\n"
out << " - #{Gem.dir}\n"
path = Gem.path.dup
path.delete Gem.dir
path.each do |p|
out << " - #{p}\n"
end
out << " - GEM CONFIGURATION:\n"
Gem.configuration.each do |name, value|
out << " - #{name.inspect} => #{value.inspect}\n"
end
out << " - REMOTE SOURCES:\n"
Gem.sources.each do |s|
out << " - #{s}\n"
end
else
raise Gem::CommandLineError, "Unknown enviroment option [#{arg}]"
end
say out
true
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/rdoc_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/rdoc_command.rb | require 'rubygems/command'
require 'rubygems/version_option'
require 'rubygems/doc_manager'
class Gem::Commands::RdocCommand < Gem::Command
include Gem::VersionOption
def initialize
super 'rdoc', 'Generates RDoc for pre-installed gems',
:version => Gem::Requirement.default,
:include_rdoc => true, :include_ri => true, :overwrite => false
add_option('--all',
'Generate RDoc/RI documentation for all',
'installed gems') do |value, options|
options[:all] = value
end
add_option('--[no-]rdoc',
'Generate RDoc HTML') do |value, options|
options[:include_rdoc] = value
end
add_option('--[no-]ri',
'Generate RI data') do |value, options|
options[:include_ri] = value
end
add_option('--[no-]overwrite',
'Overwrite installed documents') do |value, options|
options[:overwrite] = value
end
add_version_option
end
def arguments # :nodoc:
"GEMNAME gem to generate documentation for (unless --all)"
end
def defaults_str # :nodoc:
"--version '#{Gem::Requirement.default}' --rdoc --ri --no-overwrite"
end
def description # :nodoc:
<<-DESC
The rdoc command builds RDoc and RI documentation for installed gems. Use
--overwrite to force rebuilding of documentation.
DESC
end
def usage # :nodoc:
"#{program_name} [args]"
end
def execute
if options[:all] then
specs = Gem::SourceIndex.from_installed_gems.collect { |name, spec|
spec
}
else
gem_name = get_one_gem_name
dep = Gem::Dependency.new gem_name, options[:version]
specs = Gem::SourceIndex.from_installed_gems.search dep
end
if specs.empty?
raise "Failed to find gem #{gem_name} to generate RDoc for #{options[:version]}"
end
if options[:include_ri]
specs.sort.each do |spec|
doc = Gem::DocManager.new(spec)
doc.generate_ri if options[:overwrite] || !doc.ri_installed?
end
Gem::DocManager.update_ri_cache
end
if options[:include_rdoc]
specs.sort.each do |spec|
doc = Gem::DocManager.new(spec)
doc.generate_rdoc if options[:overwrite] || !doc.rdoc_installed?
end
end
true
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/owner_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/owner_command.rb | require 'rubygems/command'
require 'rubygems/local_remote_options'
require 'rubygems/gemcutter_utilities'
class Gem::Commands::OwnerCommand < Gem::Command
include Gem::LocalRemoteOptions
include Gem::GemcutterUtilities
def description # :nodoc:
'Manage gem owners on RubyGems.org.'
end
def arguments # :nodoc:
"GEM gem to manage owners for"
end
def initialize
super 'owner', description
add_proxy_option
defaults.merge! :add => [], :remove => []
add_option '-a', '--add EMAIL', 'Add an owner' do |value, options|
options[:add] << value
end
add_option '-r', '--remove EMAIL', 'Remove an owner' do |value, options|
options[:remove] << value
end
end
def execute
sign_in
name = get_one_gem_name
add_owners name, options[:add]
remove_owners name, options[:remove]
show_owners name
end
def show_owners name
response = rubygems_api_request :get, "api/v1/gems/#{name}/owners.yaml" do |request|
request.add_field "Authorization", Gem.configuration.rubygems_api_key
end
with_response response do |resp|
owners = YAML.load resp.body
say "Owners for gem: #{name}"
owners.each do |owner|
say "- #{owner['email']}"
end
end
end
def add_owners name, owners
manage_owners :post, name, owners
end
def remove_owners name, owners
manage_owners :delete, name, owners
end
def manage_owners method, name, owners
owners.each do |owner|
response = rubygems_api_request method, "api/v1/gems/#{name}/owners" do |request|
request.set_form_data 'email' => owner
request.add_field "Authorization", Gem.configuration.rubygems_api_key
end
with_response response
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/pristine_command.rb | tools/jruby-1.5.1/lib/ruby/site_ruby/1.8/rubygems/commands/pristine_command.rb | require 'fileutils'
require 'rubygems/command'
require 'rubygems/format'
require 'rubygems/installer'
require 'rubygems/version_option'
class Gem::Commands::PristineCommand < Gem::Command
include Gem::VersionOption
def initialize
super 'pristine',
'Restores installed gems to pristine condition from files located in the gem cache',
:version => Gem::Requirement.default
add_option('--all',
'Restore all installed gems to pristine',
'condition') do |value, options|
options[:all] = value
end
add_version_option('restore to', 'pristine condition')
end
def arguments # :nodoc:
"GEMNAME gem to restore to pristine condition (unless --all)"
end
def defaults_str # :nodoc:
"--all"
end
def description # :nodoc:
<<-EOF
The pristine command compares the installed gems with the contents of the
cached gem and restores any files that don't match the cached gem's copy.
If you have made modifications to your installed gems, the pristine command
will revert them. After all the gem's files have been checked all bin stubs
for the gem are regenerated.
If the cached gem cannot be found, you will need to use `gem install` to
revert the gem.
EOF
end
def usage # :nodoc:
"#{program_name} [args]"
end
def execute
gem_name = nil
specs = if options[:all] then
Gem::SourceIndex.from_installed_gems.map do |name, spec|
spec
end
else
gem_name = get_one_gem_name
Gem::SourceIndex.from_installed_gems.find_name(gem_name,
options[:version])
end
if specs.empty? then
raise Gem::Exception,
"Failed to find gem #{gem_name} #{options[:version]}"
end
install_dir = Gem.dir # TODO use installer option
raise Gem::FilePermissionError.new(install_dir) unless
File.writable?(install_dir)
say "Restoring gem(s) to pristine condition..."
specs.each do |spec|
gem = Dir[File.join(Gem.dir, 'cache', spec.file_name)].first
if gem.nil? then
alert_error "Cached gem for #{spec.full_name} not found, use `gem install` to restore"
next
end
# TODO use installer options
installer = Gem::Installer.new gem, :wrappers => true, :force => true
installer.install
say "Restored #{spec.full_name}"
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.