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.8/io/nonblock.rb | tools/jruby-1.5.1/lib/ruby/1.8/io/nonblock.rb | require "fcntl"
class IO
def nonblock?
(fcntl(Fcntl::F_GETFL) & File::NONBLOCK) != 0
end
def nonblock=(nb)
f = fcntl(Fcntl::F_GETFL)
if nb
f |= File::NONBLOCK
else
f &= ~File::NONBLOCK
end
fcntl(Fcntl::F_SETFL, f)
end
def nonblock(nb = true)
nb, self.nonblock = nonblock?, nb
yield
ensure
self.nonblock = nb
end
end if defined?(Fcntl::F_GETFL)
| 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.8/win32/resolv.rb | tools/jruby-1.5.1/lib/ruby/1.8/win32/resolv.rb | =begin
= Win32 DNS and DHCP I/F
=end
require 'win32/registry'
module Win32
module Resolv
API = Registry::API
def self.get_hosts_path
path = get_hosts_dir
path = File.expand_path('hosts', path)
File.exist?(path) ? path : nil
end
def self.get_resolv_info
search, nameserver = get_info
if search.empty?
search = nil
else
search.delete("")
search.uniq!
end
if nameserver.empty?
nameserver = nil
else
nameserver.delete("")
nameserver.delete("0.0.0.0")
nameserver.uniq!
end
[ search, nameserver ]
end
getv = Win32API.new('kernel32.dll', 'GetVersionExA', 'P', 'L')
info = [ 148, 0, 0, 0, 0 ].pack('V5') + "\0" * 128
getv.call(info)
if info.unpack('V5')[4] == 2 # VER_PLATFORM_WIN32_NT
#====================================================================
# Windows NT
#====================================================================
module_eval <<-'__EOS__', __FILE__, __LINE__+1
TCPIP_NT = 'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters'
class << self
private
def get_hosts_dir
Registry::HKEY_LOCAL_MACHINE.open(TCPIP_NT) do |reg|
reg.read_s_expand('DataBasePath')
end
end
def get_info
search = nil
nameserver = []
Registry::HKEY_LOCAL_MACHINE.open(TCPIP_NT) do |reg|
begin
slist = reg.read_s('SearchList')
search = slist.split(/,\s*/) unless slist.empty?
rescue Registry::Error
end
if add_search = search.nil?
search = []
begin
nvdom = reg.read_s('NV Domain')
unless nvdom.empty?
@search = [ nvdom ]
if reg.read_i('UseDomainNameDevolution') != 0
if /^[\w\d]+\./ =~ nvdom
devo = $'
end
end
end
rescue Registry::Error
end
end
reg.open('Interfaces') do |reg|
reg.each_key do |iface,|
reg.open(iface) do |regif|
begin
[ 'NameServer', 'DhcpNameServer' ].each do |key|
ns = regif.read_s(key)
unless ns.empty?
nameserver.concat(ns.split(/[,\s]\s*/))
break
end
end
rescue Registry::Error
end
if add_search
begin
[ 'Domain', 'DhcpDomain' ].each do |key|
dom = regif.read_s(key)
unless dom.empty?
search.concat(dom.split(/,\s*/))
break
end
end
rescue Registry::Error
end
end
end
end
end
search << devo if add_search and devo
end
[ search.uniq, nameserver.uniq ]
end
end
__EOS__
else
#====================================================================
# Windows 9x
#====================================================================
module_eval <<-'__EOS__', __FILE__, __LINE__+1
TCPIP_9X = 'SYSTEM\CurrentControlSet\Services\VxD\MSTCP'
DHCP_9X = 'SYSTEM\CurrentControlSet\Services\VxD\DHCP'
WINDOWS = 'Software\Microsoft\Windows\CurrentVersion'
class << self
# private
def get_hosts_dir
Registry::HKEY_LOCAL_MACHINE.open(WINDOWS) do |reg|
reg.read_s_expand('SystemRoot')
end
end
def get_info
search = []
nameserver = []
begin
Registry::HKEY_LOCAL_MACHINE.open(TCPIP_9X) do |reg|
if reg.read_s("EnableDNS") == "1"
domain = reg.read_s("Domain")
ns = reg.read_s("NameServer")
slist = reg.read_s("SearchList")
search << domain unless domain.empty?
search.concat(slist.split(/,\s*/))
nameserver.concat(ns.split(/[,\s]\s*/))
end
end
rescue Registry::Error
end
dhcpinfo = get_dhcpinfo
search.concat(dhcpinfo[0])
nameserver.concat(dhcpinfo[1])
[ search, nameserver ]
end
def get_dhcpinfo
macaddrs = {}
ipaddrs = {}
WsControl.get_iflist.each do |index, macaddr, *ipaddr|
macaddrs[macaddr] = 1
ipaddr.each { |ipaddr| ipaddrs[ipaddr] = 1 }
end
iflist = [ macaddrs, ipaddrs ]
search = []
nameserver = []
version = -1
Registry::HKEY_LOCAL_MACHINE.open(DHCP_9X) do |reg|
begin
version = API.unpackdw(reg.read_bin("Version"))
rescue Registry::Error
end
reg.each_key do |key,|
catch(:not_used) do
reg.open(key) do |regdi|
dom, ns = get_dhcpinfo_key(version, regdi, iflist)
search << dom if dom
nameserver.concat(ns) if ns
end
end
end
end
[ search, nameserver ]
end
def get_dhcpinfo_95(reg)
dhcp = reg.read_bin("DhcpInfo")
[
API.unpackdw(dhcp[4..7]),
API.unpackdw(dhcp[8..11]),
1,
dhcp[45..50],
reg.read_bin("OptionInfo"),
]
end
def get_dhcpinfo_98(reg)
[
API.unpackdw(reg.read_bin("DhcpIPAddress")),
API.unpackdw(reg.read_bin("DhcpSubnetMask")),
API.unpackdw(reg.read_bin("HardwareType")),
reg.read_bin("HardwareAddress"),
reg.read_bin("OptionInfo"),
]
end
def get_dhcpinfo_key(version, reg, iflist)
info = case version
when 1
get_dhcpinfo_95(reg)
when 2
get_dhcpinfo_98(reg)
else
begin
get_dhcpinfo_98(reg)
rescue Registry::Error
get_dhcpinfo_95(reg)
end
end
ipaddr, netmask, hwtype, macaddr, opt = info
throw :not_used unless
ipaddr and ipaddr != 0 and
netmask and netmask != 0 and
macaddr and macaddr.size == 6 and
hwtype == 1 and
iflist[0][macaddr] and iflist[1][ipaddr]
size = opt.size
idx = 0
while idx <= size
opttype = opt[idx]
optsize = opt[idx + 1]
optval = opt[idx + 2, optsize]
case opttype
when 0xFF ## term
break
when 0x0F ## domain
domain = optval.chomp("\0")
when 0x06 ## dns
nameserver = optval.scan(/..../).collect { |addr|
"%d.%d.%d.%d" % addr.unpack('C4')
}
end
idx += optsize + 2
end
[ domain, nameserver ]
rescue Registry::Error
throw :not_used
end
end
module WsControl
WsControl = Win32API.new('wsock32.dll', 'WsControl', 'LLPPPP', 'L')
WSAGetLastError = Win32API.new('wsock32.dll', 'WSAGetLastError', 'V', 'L')
MAX_TDI_ENTITIES = 512
IPPROTO_TCP = 6
WSCTL_TCP_QUERY_INFORMATION = 0
INFO_CLASS_GENERIC = 0x100
INFO_CLASS_PROTOCOL = 0x200
INFO_TYPE_PROVIDER = 0x100
ENTITY_LIST_ID = 0
GENERIC_ENTITY = 0
CL_NL_ENTITY = 0x301
IF_ENTITY = 0x200
ENTITY_TYPE_ID = 1
CL_NL_IP = 0x303
IF_MIB = 0x202
IF_MIB_STATS_ID = 1
IP_MIB_ADDRTABLE_ENTRY_ID = 0x102
def self.wsctl(tei_entity, tei_instance,
toi_class, toi_type, toi_id,
buffsize)
reqinfo = [
## TDIEntityID
tei_entity, tei_instance,
## TDIObjectID
toi_class, toi_type, toi_id,
## TCP_REQUEST_INFORMATION_EX
""
].pack('VVVVVa16')
reqsize = API.packdw(reqinfo.size)
buff = "\0" * buffsize
buffsize = API.packdw(buffsize)
result = WsControl.call(
IPPROTO_TCP,
WSCTL_TCP_QUERY_INFORMATION,
reqinfo, reqsize,
buff, buffsize)
if result != 0
raise RuntimeError, "WsControl failed.(#{result})"
end
[ buff, API.unpackdw(buffsize) ]
end
private_class_method :wsctl
def self.get_iflist
# Get TDI Entity List
entities, size =
wsctl(GENERIC_ENTITY, 0,
INFO_CLASS_GENERIC,
INFO_TYPE_PROVIDER,
ENTITY_LIST_ID,
MAX_TDI_ENTITIES * 8) # sizeof(TDIEntityID)
entities = entities[0, size].
scan(/.{8}/).
collect { |e| e.unpack('VV') }
# Get MIB Interface List
iflist = []
ifcount = 0
entities.each do |entity, instance|
if( (entity & IF_ENTITY)>0 )
ifcount += 1
etype, = wsctl(entity, instance,
INFO_CLASS_GENERIC,
INFO_TYPE_PROVIDER,
ENTITY_TYPE_ID,
4)
if( (API.unpackdw(etype) & IF_MIB)==IF_MIB )
ifentry, = wsctl(entity, instance,
INFO_CLASS_PROTOCOL,
INFO_TYPE_PROVIDER,
IF_MIB_STATS_ID,
21 * 4 + 8 + 130) # sizeof(IFEntry)
iflist << [
API.unpackdw(ifentry[0,4]),
ifentry[20, 6]
]
end
end
end
# Get IP Addresses
entities.each do |entity, instance|
if entity == CL_NL_ENTITY
etype, = wsctl(entity, instance,
INFO_CLASS_GENERIC,
INFO_TYPE_PROVIDER,
ENTITY_TYPE_ID,
4)
if API.unpackdw(etype) == CL_NL_IP
ipentries, = wsctl(entity, instance,
INFO_CLASS_PROTOCOL,
INFO_TYPE_PROVIDER,
IP_MIB_ADDRTABLE_ENTRY_ID,
24 * (ifcount+1)) # sizeof(IPAddrEntry)
ipentries.scan(/.{24}/) do |ipentry|
ipaddr, index = ipentry.unpack('VV')
if ifitem = iflist.assoc(index)
ifitem << ipaddr
end
end
end
end
end
iflist
end
end
__EOS__
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.8/win32/registry.rb | tools/jruby-1.5.1/lib/ruby/1.8/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.8/rinda/rinda.rb | tools/jruby-1.5.1/lib/ruby/1.8/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.8/rinda/ring.rb | tools/jruby-1.5.1/lib/ruby/1.8/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, nil])
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 |ts|
p ts
ts.write([:hello, :world])
end
when 'r'
finger = Rinda::RingFinger.new(nil)
finger.lookup_ring do |ts|
p ts
p ts.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.8/rinda/tuplespace.rb | tools/jruby-1.5.1/lib/ruby/1.8/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 = Enumerable::Enumerator.new(self, :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.8/shell/process-controller.rb | tools/jruby-1.5.1/lib/ruby/1.8/shell/process-controller.rb | #
# shell/process-controller.rb -
# $Release Version: 0.6.0 $
# $Revision: 12006 $
# $Date: 2007-03-06 18:59:25 +0900 (Tue, 06 Mar 2007) $
# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
#
# --
#
#
#
require "mutex_m"
require "monitor"
require "sync"
class Shell
class ProcessController
@ProcessControllers = {}
@ProcessControllers.extend Mutex_m
class<<self
def process_controllers_exclusive
begin
@ProcessControllers.lock unless Thread.critical
yield
ensure
@ProcessControllers.unlock unless Thread.critical
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)
end
end
end
end
def each_active_object
process_controllers_exclusive do
for ref in @ProcessControllers.keys
yield ref
end
end
end
end
def initialize(shell)
@shell = shell
@waiting_jobs = []
@active_jobs = []
@jobs_sync = Sync.new
@job_monitor = Mutex.new
@job_condition = ConditionVariable.new
end
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
return unless command
end
@active_jobs.push command
command.start
# start all jobs that input from the job
for job in @waiting_jobs
start_job(job) if job.input == command
end
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?
start_job
end
end
end
# kill a job
def kill_job(sig, command)
@jobs_sync.synchronize(:SH) 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)
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
Thread.critical = true
STDOUT.flush
ProcessController.each_active_object do |pc|
for jobs in pc.active_jobs
jobs.flush
end
end
pid = fork {
Thread.critical = true
Thread.list.each do |th|
th.kill unless [Thread.main, Thread.current].include?(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
}
pipe_peer_in.close
pipe_peer_out.close
command.notify "job(%name:##{pid}) start", @shell.debug?
Thread.critical = false
th = Thread.start {
Thread.critical = true
begin
_pid = nil
command.notify("job(%id) start to waiting finish.", @shell.debug?)
Thread.critical = false
_pid = Process.waitpid(pid, nil)
rescue Errno::ECHILD
command.notify "warn: job(%id) was done already waitipd."
_pid = true
ensure
# when the process ends, wait until the command termintes
if _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
Thread.exclusive do
@job_monitor.synchronize do
terminate_job(command)
@job_condition.signal
command.notify "job(%id) finish.", @shell.debug?
end
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.8/shell/version.rb | tools/jruby-1.5.1/lib/ruby/1.8/shell/version.rb | #
# version.rb - shell version definition file
# $Release Version: 0.6.0$
# $Revision: 11708 $
# $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $
# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
#
# --
#
#
#
class Shell
@RELEASE_VERSION = "0.6.0"
@LAST_UPDATE_DATE = "01/03/19"
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.8/shell/builtin-command.rb | tools/jruby-1.5.1/lib/ruby/1.8/shell/builtin-command.rb | #
# shell/builtin-command.rb -
# $Release Version: 0.6.0 $
# $Revision: 11708 $
# $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $
# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
#
# --
#
#
#
require "shell/filter"
class Shell
class BuiltInCommand<Filter
def wait?
false
end
def active?
true
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
Thread.critical = true
back = Dir.pwd
begin
Dir.chdir @shell.cwd
@files = Dir[pattern]
ensure
Dir.chdir back
Thread.critical = false
end
end
def each(rs = nil)
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.8/shell/filter.rb | tools/jruby-1.5.1/lib/ruby/1.8/shell/filter.rb | #
# shell/filter.rb -
# $Release Version: 0.6.0 $
# $Revision: 11708 $
# $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $
# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
#
# --
#
#
#
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.8/shell/system-command.rb | tools/jruby-1.5.1/lib/ruby/1.8/shell/system-command.rb | #
# shell/system-command.rb -
# $Release Version: 0.6.0 $
# $Revision: 11708 $
# $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $
# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
#
# --
#
#
#
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
@pid, @pipe_in, @pipe_out = @shell.process_controller.sfork(self) {
Dir.chdir @shell.pwd
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
# Thread.critical = true
notify "Job(%id) start imp-pipe.", @shell.debug?
rs = @shell.record_separator unless rs
_eop = true
# Thread.critical = false
th = Thread.start {
Thread.critical = true
begin
Thread.critical = false
while l = @pipe_in.gets
@input_queue.push l
end
_eop = false
rescue Errno::EPIPE
_eop = false
ensure
if _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.")
# Tracer.on
Thread.current.run
redo
end
Thread.exclusive do
notify "job(%id}) close imp-pipe.", @shell.debug?
@input_queue.push :EOF
@pipe_in.close
end
end
}
end
def start_export
notify "job(%id) start exp-pipe.", @shell.debug?
_eop = true
th = Thread.start{
Thread.critical = true
begin
Thread.critical = false
@input.each{|l| @pipe_out.print l}
_eop = false
rescue Errno::EPIPE
_eop = false
ensure
if _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.")
# Tracer.on
redo
end
Thread.exclusive do
notify "job(%id) close exp-pipe.", @shell.debug?
@pipe_out.close
end
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)
Thread.exclusive do
@shell.notify(*opts) {|mes|
yield mes if iterator?
mes.gsub!("%id", "#{@command}:##{@pid}")
mes.gsub!("%name", "#{@command}")
mes.gsub!("%pid", "#{@pid}")
}
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.8/shell/command-processor.rb | tools/jruby-1.5.1/lib/ruby/1.8/shell/command-processor.rb | #
# shell/command-controller.rb -
# $Release Version: 0.6.0 $
# $Revision: 22281 $
# $Date: 2009-02-13 19:05:02 +0900 (Fri, 13 Feb 2009) $
# by Keiju ISHITSUKA(Nippon Rational Inc.)
#
# --
#
#
#
require "e2mmap"
require "ftools"
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.
#
NoDelegateMethods = ["initialize", "expand_path"]
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)
path = expand_path(path)
if File.directory?(path)
Dir.open(path)
else
effect_umask do
File.open(path, mode)
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)
path = expand_path(path)
if File.directory?(path)
Dir.unlink(path)
else
IO.unlink(path)
end
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)
for dir in path
Dir.mkdir(expand_path(dir))
end
end
#
# CommandProcessor#rmdir(*path)
# path: String
# same as Dir.rmdir()
#
def rmdir(*path)
for dir in path
Dir.rmdir(expand_path(dir))
end
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)
Thread.exclusive do
Shell.notify(*opts) {|mes|
yield mes if iterator?
mes.gsub!("%pwd", "#{@cwd}")
mes.gsub!("%cwd", "#{@cwd}")
}
end
end
#
# private functions
#
def effect_umask
if @shell.umask
Thread.critical = true
save = File.umask
begin
yield
ensure
File.umask save
Thread.critical = false
end
else
yield
end
end
private :effect_umask
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.exists?(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"]]})
# method related ftools
normal_delegation_ftools_methods = [
["syscopy", ["FILENAME_FROM", "FILENAME_TO"]],
["copy", ["FILENAME_FROM", "FILENAME_TO"]],
["move", ["FILENAME_FROM", "FILENAME_TO"]],
["compare", ["FILENAME_FROM", "FILENAME_TO"]],
["safe_unlink", ["*FILENAMES"]],
["makedirs", ["*FILENAMES"]],
# ["chmod", ["mode", "*FILENAMES"]],
["install", ["FILENAME_FROM", "FILENAME_TO", "mode"]],
]
def_builtin_commands(File,
normal_delegation_ftools_methods)
alias_method :cmp, :compare
alias_method :mv, :move
alias_method :cp, :copy
alias_method :rm_f, :safe_unlink
alias_method :mkpath, :makedirs
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.8/shell/error.rb | tools/jruby-1.5.1/lib/ruby/1.8/shell/error.rb | #
# shell/error.rb -
# $Release Version: 0.6.0 $
# $Revision: 11708 $
# $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $
# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
#
# --
#
#
#
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.8/drb/extserv.rb | tools/jruby-1.5.1/lib/ruby/1.8/drb/extserv.rb | =begin
external service
Copyright (c) 2000,2002 Masatoshi SEKI
=end
require 'drb/drb'
module DRb
class ExtServ
include DRbUndumped
def initialize(there, name, server=nil)
@server = server || DRb::primary_server
@name = name
ro = DRbObject.new(nil, there)
@invoker = ro.regist(name, DRbObject.new(self, @server.uri))
end
attr_reader :server
def front
DRbObject.new(nil, @server.uri)
end
def stop_service
@invoker.unregist(@name)
server = @server
@server = nil
server.stop_service
true
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.8/drb/extservm.rb | tools/jruby-1.5.1/lib/ruby/1.8/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
if RUBY_PLATFORM =~ /mswin32/ && /NT/ =~ ENV["OS"]
system(%Q'cmd /c start "ruby" /b #{command} #{uri} #{name}')
else
system("#{command} #{uri} #{name} &")
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.8/drb/observer.rb | tools/jruby-1.5.1/lib/ruby/1.8/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
for i in @observer_peers.dup
begin
i.update(*arg)
rescue
delete_observer(i)
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.8/drb/acl.rb | tools/jruby-1.5.1/lib/ruby/1.8/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.8/drb/ssl.rb | tools/jruby-1.5.1/lib/ruby/1.8/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.8/drb/timeridconv.rb | tools/jruby-1.5.1/lib/ruby/1.8/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.8/drb/drb.rb | tools/jruby-1.5.1/lib/ruby/1.8/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)
family = infos.collect { |af, *_| af }.uniq
case family
when ['AF_INET']
return TCPServer.open('0.0.0.0', port)
when ['AF_INET6']
return TCPServer.open('::', port)
else
return TCPServer.open(port)
end
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:
| 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.8/drb/invokemethod.rb | tools/jruby-1.5.1/lib/ruby/1.8/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 :retry
retry
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.8/drb/unix.rb | tools/jruby-1.5.1/lib/ruby/1.8/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.8/drb/eq.rb | tools/jruby-1.5.1/lib/ruby/1.8/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.8/drb/gw.rb | tools/jruby-1.5.1/lib/ruby/1.8/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/1.9/abbrev.rb | tools/jruby-1.5.1/lib/ruby/1.9/abbrev.rb | #!/usr/bin/env ruby
=begin
#
# Copyright (c) 2001,2003 Akinori MUSHA <knu@iDaemons.org>
#
# All rights reserved. You can redistribute and/or modify it under
# the same terms as Ruby.
#
# $Idaemons: /home/cvs/rb/abbrev.rb,v 1.2 2001/05/30 09:37:45 knu Exp $
# $RoughId: abbrev.rb,v 1.4 2003/10/14 19:45:42 knu Exp $
# $Id: abbrev.rb 11708 2007-02-12 23:01:19Z shyouhei $
=end
# Calculate the set of unique abbreviations for a given set of strings.
#
# require 'abbrev'
# require 'pp'
#
# pp Abbrev::abbrev(['ruby', 'rules']).sort
#
# <i>Generates:</i>
#
# [["rub", "ruby"],
# ["ruby", "ruby"],
# ["rul", "rules"],
# ["rule", "rules"],
# ["rules", "rules"]]
#
# Also adds an +abbrev+ method to class +Array+.
module Abbrev
# Given a set of strings, calculate the set of unambiguous
# abbreviations for those strings, and return a hash where the keys
# are all the possible abbreviations and the values are the full
# strings. Thus, given input of "car" and "cone", the keys pointing
# to "car" would be "ca" and "car", while those pointing to "cone"
# would be "co", "con", and "cone".
#
# The optional +pattern+ parameter is a pattern or a string. Only
# those input strings matching the pattern, or begging the string,
# are considered for inclusion in the output hash
def abbrev(words, pattern = nil)
table = {}
seen = Hash.new(0)
if pattern.is_a?(String)
pattern = /^#{Regexp.quote(pattern)}/ # regard as a prefix
end
words.each do |word|
next if (abbrev = word).empty?
while (len = abbrev.rindex(/[\w\W]\z/)) > 0
abbrev = word[0,len]
next if pattern && pattern !~ abbrev
case seen[abbrev] += 1
when 1
table[abbrev] = word
when 2
table.delete(abbrev)
else
break
end
end
end
words.each do |word|
next if pattern && pattern !~ word
table[word] = word
end
table
end
module_function :abbrev
end
class Array
# Calculates the set of unambiguous abbreviations for the strings in
# +self+. If passed a pattern or a string, only the strings matching
# the pattern or starting with the string are considered.
#
# %w{ car cone }.abbrev #=> { "ca" => "car", "car" => "car",
# "co" => "cone", "con" => cone",
# "cone" => "cone" }
def abbrev(pattern = nil)
Abbrev::abbrev(self, pattern)
end
end
if $0 == __FILE__
while line = gets
hash = line.split.abbrev
hash.sort.each do |k, v|
puts "#{k} => #{v}"
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/find.rb | tools/jruby-1.5.1/lib/ruby/1.9/find.rb | #
# find.rb: the Find module for processing all files under a given directory.
#
#
# The +Find+ module supports the top-down traversal of a set of file paths.
#
# For example, to total the size of all files under your home directory,
# ignoring anything in a "dot" directory (e.g. $HOME/.ssh):
#
# require 'find'
#
# total_size = 0
#
# Find.find(ENV["HOME"]) do |path|
# if FileTest.directory?(path)
# if File.basename(path)[0] == ?.
# Find.prune # Don't look any further into this directory.
# else
# next
# end
# else
# total_size += FileTest.size(path)
# end
# end
#
module Find
#
# Calls the associated block with the name of every file and directory listed
# as arguments, then recursively on their subdirectories, and so on.
#
# See the +Find+ module documentation for an example.
#
def find(*paths) # :yield: path
block_given? or return enum_for(__method__, *paths)
paths.collect!{|d| raise Errno::ENOENT unless File.exist?(d); d.dup}
while file = paths.shift
catch(:prune) do
yield file.dup.taint
next unless File.exist? file
begin
if File.lstat(file).directory? then
d = Dir.open(file)
begin
for f in d
next if f == "." or f == ".."
if File::ALT_SEPARATOR and file =~ /^(?:[\/\\]|[A-Za-z]:[\/\\]?)$/ then
f = file + f
elsif file == "/" then
f = "/" + f
else
f = File.join(file, f)
end
paths.unshift f.untaint
end
ensure
d.close
end
end
rescue Errno::ENOENT, Errno::EACCES
end
end
end
end
#
# Skips the current file or directory, restarting the loop with the next
# entry. If the current file is a directory, that directory will not be
# recursively entered. Meaningful only within the block associated with
# Find::find.
#
# See the +Find+ module documentation for an example.
#
def prune
throw :prune
end
module_function :find, :prune
end
| 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/tsort.rb | tools/jruby-1.5.1/lib/ruby/1.9/tsort.rb | #--
# tsort.rb - provides a module for topological sorting and strongly connected components.
#++
#
#
# TSort implements topological sorting using Tarjan's algorithm for
# strongly connected components.
#
# TSort is designed to be able to be used with any object which can be
# interpreted as a directed graph.
#
# TSort requires two methods to interpret an object as a graph,
# tsort_each_node and tsort_each_child.
#
# * tsort_each_node is used to iterate for all nodes over a graph.
# * tsort_each_child is used to iterate for child nodes of a given node.
#
# The equality of nodes are defined by eql? and hash since
# TSort uses Hash internally.
#
# == A Simple Example
#
# The following example demonstrates how to mix the TSort module into an
# existing class (in this case, Hash). Here, we're treating each key in
# the hash as a node in the graph, and so we simply alias the required
# #tsort_each_node method to Hash's #each_key method. For each key in the
# hash, the associated value is an array of the node's child nodes. This
# choice in turn leads to our implementation of the required #tsort_each_child
# method, which fetches the array of child nodes and then iterates over that
# array using the user-supplied block.
#
# require 'tsort'
#
# class Hash
# include TSort
# alias tsort_each_node each_key
# def tsort_each_child(node, &block)
# fetch(node).each(&block)
# end
# end
#
# {1=>[2, 3], 2=>[3], 3=>[], 4=>[]}.tsort
# #=> [3, 2, 1, 4]
#
# {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}.strongly_connected_components
# #=> [[4], [2, 3], [1]]
#
# == A More Realistic Example
#
# A very simple `make' like tool can be implemented as follows:
#
# require 'tsort'
#
# class Make
# def initialize
# @dep = {}
# @dep.default = []
# end
#
# def rule(outputs, inputs=[], &block)
# triple = [outputs, inputs, block]
# outputs.each {|f| @dep[f] = [triple]}
# @dep[triple] = inputs
# end
#
# def build(target)
# each_strongly_connected_component_from(target) {|ns|
# if ns.length != 1
# fs = ns.delete_if {|n| Array === n}
# raise TSort::Cyclic.new("cyclic dependencies: #{fs.join ', '}")
# end
# n = ns.first
# if Array === n
# outputs, inputs, block = n
# inputs_time = inputs.map {|f| File.mtime f}.max
# begin
# outputs_time = outputs.map {|f| File.mtime f}.min
# rescue Errno::ENOENT
# outputs_time = nil
# end
# if outputs_time == nil ||
# inputs_time != nil && outputs_time <= inputs_time
# sleep 1 if inputs_time != nil && inputs_time.to_i == Time.now.to_i
# block.call
# end
# end
# }
# end
#
# def tsort_each_child(node, &block)
# @dep[node].each(&block)
# end
# include TSort
# end
#
# def command(arg)
# print arg, "\n"
# system arg
# end
#
# m = Make.new
# m.rule(%w[t1]) { command 'date > t1' }
# m.rule(%w[t2]) { command 'date > t2' }
# m.rule(%w[t3]) { command 'date > t3' }
# m.rule(%w[t4], %w[t1 t3]) { command 'cat t1 t3 > t4' }
# m.rule(%w[t5], %w[t4 t2]) { command 'cat t4 t2 > t5' }
# m.build('t5')
#
# == Bugs
#
# * 'tsort.rb' is wrong name because this library uses
# Tarjan's algorithm for strongly connected components.
# Although 'strongly_connected_components.rb' is correct but too long.
#
# == References
#
# R. E. Tarjan, "Depth First Search and Linear Graph Algorithms",
# <em>SIAM Journal on Computing</em>, Vol. 1, No. 2, pp. 146-160, June 1972.
#
module TSort
class Cyclic < StandardError
end
#
# Returns a topologically sorted array of nodes.
# The array is sorted from children to parents, i.e.
# the first element has no child and the last node has no parent.
#
# If there is a cycle, TSort::Cyclic is raised.
#
def tsort
result = []
tsort_each {|element| result << element}
result
end
#
# The iterator version of the #tsort method.
# <tt><em>obj</em>.tsort_each</tt> is similar to <tt><em>obj</em>.tsort.each</tt>, but
# modification of _obj_ during the iteration may lead to unexpected results.
#
# #tsort_each returns +nil+.
# If there is a cycle, TSort::Cyclic is raised.
#
def tsort_each # :yields: node
each_strongly_connected_component {|component|
if component.size == 1
yield component.first
else
raise Cyclic.new("topological sort failed: #{component.inspect}")
end
}
end
#
# Returns strongly connected components as an array of arrays of nodes.
# The array is sorted from children to parents.
# Each elements of the array represents a strongly connected component.
#
def strongly_connected_components
result = []
each_strongly_connected_component {|component| result << component}
result
end
#
# The iterator version of the #strongly_connected_components method.
# <tt><em>obj</em>.each_strongly_connected_component</tt> is similar to
# <tt><em>obj</em>.strongly_connected_components.each</tt>, but
# modification of _obj_ during the iteration may lead to unexpected results.
#
#
# #each_strongly_connected_component returns +nil+.
#
def each_strongly_connected_component # :yields: nodes
id_map = {}
stack = []
tsort_each_node {|node|
unless id_map.include? node
each_strongly_connected_component_from(node, id_map, stack) {|c|
yield c
}
end
}
nil
end
#
# Iterates over strongly connected component in the subgraph reachable from
# _node_.
#
# Return value is unspecified.
#
# #each_strongly_connected_component_from doesn't call #tsort_each_node.
#
def each_strongly_connected_component_from(node, id_map={}, stack=[]) # :yields: nodes
minimum_id = node_id = id_map[node] = id_map.size
stack_length = stack.length
stack << node
tsort_each_child(node) {|child|
if id_map.include? child
child_id = id_map[child]
minimum_id = child_id if child_id && child_id < minimum_id
else
sub_minimum_id =
each_strongly_connected_component_from(child, id_map, stack) {|c|
yield c
}
minimum_id = sub_minimum_id if sub_minimum_id < minimum_id
end
}
if node_id == minimum_id
component = stack.slice!(stack_length .. -1)
component.each {|n| id_map[n] = nil}
yield component
end
minimum_id
end
#
# Should be implemented by a extended class.
#
# #tsort_each_node is used to iterate for all nodes over a graph.
#
def tsort_each_node # :yields: node
raise NotImplementedError.new
end
#
# Should be implemented by a extended class.
#
# #tsort_each_child is used to iterate for child nodes of _node_.
#
def tsort_each_child(node) # :yields: child
raise NotImplementedError.new
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/webrick.rb | tools/jruby-1.5.1/lib/ruby/1.9/webrick.rb | #
# WEBrick -- WEB server toolkit.
#
# Author: IPR -- Internet Programming with Ruby -- writers
# Copyright (c) 2000 TAKAHASHI Masayoshi, GOTOU YUUZOU
# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
# reserved.
#
# $IPR: webrick.rb,v 1.12 2002/10/01 17:16:31 gotoyuzo Exp $
require 'webrick/compat.rb'
require 'webrick/version.rb'
require 'webrick/config.rb'
require 'webrick/log.rb'
require 'webrick/server.rb'
require 'webrick/utils.rb'
require 'webrick/accesslog'
require 'webrick/htmlutils.rb'
require 'webrick/httputils.rb'
require 'webrick/cookie.rb'
require 'webrick/httpversion.rb'
require 'webrick/httpstatus.rb'
require 'webrick/httprequest.rb'
require 'webrick/httpresponse.rb'
require 'webrick/httpserver.rb'
require 'webrick/httpservlet.rb'
require 'webrick/httpauth.rb'
| 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/open-uri.rb | tools/jruby-1.5.1/lib/ruby/1.9/open-uri.rb | require 'uri'
require 'stringio'
require 'time'
module Kernel
private
alias open_uri_original_open open # :nodoc:
class << self
alias open_uri_original_open open # :nodoc:
end
# makes possible to open various resources including URIs.
# If the first argument respond to `open' method,
# the method is called with the rest arguments.
#
# If the first argument is a string which begins with xxx://,
# it is parsed by URI.parse. If the parsed object respond to `open' method,
# the method is called with the rest arguments.
#
# Otherwise original open is called.
#
# Since open-uri.rb provides URI::HTTP#open, URI::HTTPS#open and
# URI::FTP#open,
# Kernel[#.]open can accepts such URIs and strings which begins with
# http://, https:// and ftp://.
# In these case, the opened file object is extended by OpenURI::Meta.
def open(name, *rest, &block) # :doc:
if name.respond_to?(:open)
name.open(*rest, &block)
elsif name.respond_to?(:to_str) &&
%r{\A[A-Za-z][A-Za-z0-9+\-\.]*://} =~ name &&
(uri = URI.parse(name)).respond_to?(:open)
uri.open(*rest, &block)
else
open_uri_original_open(name, *rest, &block)
end
end
module_function :open
end
# OpenURI is an easy-to-use wrapper for net/http, net/https and net/ftp.
#
#== Example
#
# It is possible to open http/https/ftp URL as usual like opening a file:
#
# open("http://www.ruby-lang.org/") {|f|
# f.each_line {|line| p line}
# }
#
# The opened file has several methods for meta information as follows since
# it is extended by OpenURI::Meta.
#
# open("http://www.ruby-lang.org/en") {|f|
# f.each_line {|line| p line}
# p f.base_uri # <URI::HTTP:0x40e6ef2 URL:http://www.ruby-lang.org/en/>
# p f.content_type # "text/html"
# p f.charset # "iso-8859-1"
# p f.content_encoding # []
# p f.last_modified # Thu Dec 05 02:45:02 UTC 2002
# }
#
# Additional header fields can be specified by an optional hash argument.
#
# open("http://www.ruby-lang.org/en/",
# "User-Agent" => "Ruby/#{RUBY_VERSION}",
# "From" => "foo@bar.invalid",
# "Referer" => "http://www.ruby-lang.org/") {|f|
# # ...
# }
#
# The environment variables such as http_proxy, https_proxy and ftp_proxy
# are in effect by default. :proxy => nil disables proxy.
#
# open("http://www.ruby-lang.org/en/raa.html", :proxy => nil) {|f|
# # ...
# }
#
# URI objects can be opened in a similar way.
#
# uri = URI.parse("http://www.ruby-lang.org/en/")
# uri.open {|f|
# # ...
# }
#
# URI objects can be read directly. The returned string is also extended by
# OpenURI::Meta.
#
# str = uri.read
# p str.base_uri
#
# Author:: Tanaka Akira <akr@m17n.org>
module OpenURI
Options = {
:proxy => true,
:proxy_http_basic_authentication => true,
:progress_proc => true,
:content_length_proc => true,
:http_basic_authentication => true,
:read_timeout => true,
:ssl_ca_cert => nil,
:ssl_verify_mode => nil,
:ftp_active_mode => false,
:redirect => true,
}
def OpenURI.check_options(options) # :nodoc:
options.each {|k, v|
next unless Symbol === k
unless Options.include? k
raise ArgumentError, "unrecognized option: #{k}"
end
}
end
def OpenURI.scan_open_optional_arguments(*rest) # :nodoc:
if !rest.empty? && (String === rest.first || Integer === rest.first)
mode = rest.shift
if !rest.empty? && Integer === rest.first
perm = rest.shift
end
end
return mode, perm, rest
end
def OpenURI.open_uri(name, *rest) # :nodoc:
uri = URI::Generic === name ? name : URI.parse(name)
mode, perm, rest = OpenURI.scan_open_optional_arguments(*rest)
options = rest.shift if !rest.empty? && Hash === rest.first
raise ArgumentError.new("extra arguments") if !rest.empty?
options ||= {}
OpenURI.check_options(options)
if /\Arb?(?:\Z|:([^:]+))/ =~ mode
encoding, = $1,Encoding.find($1) if $1
mode = nil
end
unless mode == nil ||
mode == 'r' || mode == 'rb' ||
mode == File::RDONLY
raise ArgumentError.new("invalid access mode #{mode} (#{uri.class} resource is read only.)")
end
io = open_loop(uri, options)
io.set_encoding(encoding) if encoding
if block_given?
begin
yield io
ensure
io.close
end
else
io
end
end
def OpenURI.open_loop(uri, options) # :nodoc:
proxy_opts = []
proxy_opts << :proxy_http_basic_authentication if options.include? :proxy_http_basic_authentication
proxy_opts << :proxy if options.include? :proxy
proxy_opts.compact!
if 1 < proxy_opts.length
raise ArgumentError, "multiple proxy options specified"
end
case proxy_opts.first
when :proxy_http_basic_authentication
opt_proxy, proxy_user, proxy_pass = options.fetch(:proxy_http_basic_authentication)
proxy_user = proxy_user.to_str
proxy_pass = proxy_pass.to_str
if opt_proxy == true
raise ArgumentError.new("Invalid authenticated proxy option: #{options[:proxy_http_basic_authentication].inspect}")
end
when :proxy
opt_proxy = options.fetch(:proxy)
proxy_user = nil
proxy_pass = nil
when nil
opt_proxy = true
proxy_user = nil
proxy_pass = nil
end
case opt_proxy
when true
find_proxy = lambda {|u| pxy = u.find_proxy; pxy ? [pxy, nil, nil] : nil}
when nil, false
find_proxy = lambda {|u| nil}
when String
opt_proxy = URI.parse(opt_proxy)
find_proxy = lambda {|u| [opt_proxy, proxy_user, proxy_pass]}
when URI::Generic
find_proxy = lambda {|u| [opt_proxy, proxy_user, proxy_pass]}
else
raise ArgumentError.new("Invalid proxy option: #{opt_proxy}")
end
uri_set = {}
buf = nil
while true
redirect = catch(:open_uri_redirect) {
buf = Buffer.new
uri.buffer_open(buf, find_proxy.call(uri), options)
nil
}
if redirect
if redirect.relative?
# Although it violates RFC2616, Location: field may have relative
# URI. It is converted to absolute URI using uri as a base URI.
redirect = uri + redirect
end
if !options.fetch(:redirect, true)
raise HTTPRedirect.new(buf.io.status.join(' '), buf.io, redirect)
end
unless OpenURI.redirectable?(uri, redirect)
raise "redirection forbidden: #{uri} -> #{redirect}"
end
if options.include? :http_basic_authentication
# send authentication only for the URI directly specified.
options = options.dup
options.delete :http_basic_authentication
end
uri = redirect
raise "HTTP redirection loop: #{uri}" if uri_set.include? uri.to_s
uri_set[uri.to_s] = true
else
break
end
end
io = buf.io
io.base_uri = uri
io
end
def OpenURI.redirectable?(uri1, uri2) # :nodoc:
# This test is intended to forbid a redirection from http://... to
# file:///etc/passwd.
# https to http redirect is also forbidden intentionally.
# It avoids sending secure cookie or referer by non-secure HTTP protocol.
# (RFC 2109 4.3.1, RFC 2965 3.3, RFC 2616 15.1.3)
# However this is ad hoc. It should be extensible/configurable.
uri1.scheme.downcase == uri2.scheme.downcase ||
(/\A(?:http|ftp)\z/i =~ uri1.scheme && /\A(?:http|ftp)\z/i =~ uri2.scheme)
end
def OpenURI.open_http(buf, target, proxy, options) # :nodoc:
if proxy
proxy_uri, proxy_user, proxy_pass = proxy
raise "Non-HTTP proxy URI: #{proxy_uri}" if proxy_uri.class != URI::HTTP
end
if target.userinfo && "1.9.0" <= RUBY_VERSION
# don't raise for 1.8 because compatibility.
raise ArgumentError, "userinfo not supported. [RFC3986]"
end
header = {}
options.each {|k, v| header[k] = v if String === k }
require 'net/http'
klass = Net::HTTP
if URI::HTTP === target
# HTTP or HTTPS
if proxy
if proxy_user && proxy_pass
klass = Net::HTTP::Proxy(proxy_uri.host, proxy_uri.port, proxy_user, proxy_pass)
else
klass = Net::HTTP::Proxy(proxy_uri.host, proxy_uri.port)
end
end
target_host = target.host
target_port = target.port
request_uri = target.request_uri
else
# FTP over HTTP proxy
target_host = proxy_uri.host
target_port = proxy_uri.port
request_uri = target.to_s
if proxy_user && proxy_pass
header["Proxy-Authorization"] = 'Basic ' + ["#{proxy_user}:#{proxy_pass}"].pack('m').delete("\r\n")
end
end
http = klass.new(target_host, target_port)
if target.class == URI::HTTPS
require 'net/https'
http.use_ssl = true
http.verify_mode = options[:ssl_verify_mode] || OpenSSL::SSL::VERIFY_PEER
store = OpenSSL::X509::Store.new
if options[:ssl_ca_cert]
if File.directory? options[:ssl_ca_cert]
store.add_path options[:ssl_ca_cert]
else
store.add_file options[:ssl_ca_cert]
end
else
store.set_default_paths
end
http.cert_store = store
end
if options.include? :read_timeout
http.read_timeout = options[:read_timeout]
end
resp = nil
http.start {
req = Net::HTTP::Get.new(request_uri, header)
if options.include? :http_basic_authentication
user, pass = options[:http_basic_authentication]
req.basic_auth user, pass
end
http.request(req) {|response|
resp = response
if options[:content_length_proc] && Net::HTTPSuccess === resp
if resp.key?('Content-Length')
options[:content_length_proc].call(resp['Content-Length'].to_i)
else
options[:content_length_proc].call(nil)
end
end
resp.read_body {|str|
buf << str
if options[:progress_proc] && Net::HTTPSuccess === resp
options[:progress_proc].call(buf.size)
end
}
}
}
io = buf.io
io.rewind
io.status = [resp.code, resp.message]
resp.each {|name,value| buf.io.meta_add_field name, value }
case resp
when Net::HTTPSuccess
when Net::HTTPMovedPermanently, # 301
Net::HTTPFound, # 302
Net::HTTPSeeOther, # 303
Net::HTTPTemporaryRedirect # 307
begin
loc_uri = URI.parse(resp['location'])
rescue URI::InvalidURIError
raise OpenURI::HTTPError.new(io.status.join(' ') + ' (Invalid Location URI)', io)
end
throw :open_uri_redirect, loc_uri
else
raise OpenURI::HTTPError.new(io.status.join(' '), io)
end
end
class HTTPError < StandardError
def initialize(message, io)
super(message)
@io = io
end
attr_reader :io
end
class HTTPRedirect < HTTPError
def initialize(message, io, uri)
super(message, io)
@uri = uri
end
attr_reader :uri
end
class Buffer # :nodoc:
def initialize
@io = StringIO.new
@size = 0
end
attr_reader :size
StringMax = 10240
def <<(str)
@io << str
@size += str.length
if StringIO === @io && StringMax < @size
require 'tempfile'
io = Tempfile.new('open-uri')
io.binmode
Meta.init io, @io if Meta === @io
io << @io.string
@io = io
end
end
def io
Meta.init @io unless Meta === @io
@io
end
end
# Mixin for holding meta-information.
module Meta
def Meta.init(obj, src=nil) # :nodoc:
obj.extend Meta
obj.instance_eval {
@base_uri = nil
@meta = {}
}
if src
obj.status = src.status
obj.base_uri = src.base_uri
src.meta.each {|name, value|
obj.meta_add_field(name, value)
}
end
end
# returns an Array which consists status code and message.
attr_accessor :status
# returns a URI which is base of relative URIs in the data.
# It may differ from the URI supplied by a user because redirection.
attr_accessor :base_uri
# returns a Hash which represents header fields.
# The Hash keys are downcased for canonicalization.
attr_reader :meta
def meta_setup_encoding # :nodoc:
charset = self.charset
enc = nil
if charset
begin
enc = Encoding.find(charset)
rescue ArgumentError
end
end
enc = Encoding::ASCII_8BIT unless enc
if self.respond_to? :force_encoding
self.force_encoding(enc)
elsif self.respond_to? :string
self.string.force_encoding(enc)
else # Tempfile
self.set_encoding enc
end
end
def meta_add_field(name, value) # :nodoc:
name = name.downcase
@meta[name] = value
meta_setup_encoding if name == 'content-type'
end
# returns a Time which represents Last-Modified field.
def last_modified
if v = @meta['last-modified']
Time.httpdate(v)
else
nil
end
end
RE_LWS = /[\r\n\t ]+/n
RE_TOKEN = %r{[^\x00- ()<>@,;:\\"/\[\]?={}\x7f]+}n
RE_QUOTED_STRING = %r{"(?:[\r\n\t !#-\[\]-~\x80-\xff]|\\[\x00-\x7f])*"}n
RE_PARAMETERS = %r{(?:;#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?=#{RE_LWS}?(?:#{RE_TOKEN}|#{RE_QUOTED_STRING})#{RE_LWS}?)*}n
def content_type_parse # :nodoc:
v = @meta['content-type']
# The last (?:;#{RE_LWS}?)? matches extra ";" which violates RFC2045.
if v && %r{\A#{RE_LWS}?(#{RE_TOKEN})#{RE_LWS}?/(#{RE_TOKEN})#{RE_LWS}?(#{RE_PARAMETERS})(?:;#{RE_LWS}?)?\z}no =~ v
type = $1.downcase
subtype = $2.downcase
parameters = []
$3.scan(/;#{RE_LWS}?(#{RE_TOKEN})#{RE_LWS}?=#{RE_LWS}?(?:(#{RE_TOKEN})|(#{RE_QUOTED_STRING}))/no) {|att, val, qval|
val = qval.gsub(/[\r\n\t !#-\[\]-~\x80-\xff]+|(\\[\x00-\x7f])/n) { $1 ? $1[1,1] : $& } if qval
parameters << [att.downcase, val]
}
["#{type}/#{subtype}", *parameters]
else
nil
end
end
# returns "type/subtype" which is MIME Content-Type.
# It is downcased for canonicalization.
# Content-Type parameters are stripped.
def content_type
type, *parameters = content_type_parse
type || 'application/octet-stream'
end
# returns a charset parameter in Content-Type field.
# It is downcased for canonicalization.
#
# If charset parameter is not given but a block is given,
# the block is called and its result is returned.
# It can be used to guess charset.
#
# If charset parameter and block is not given,
# nil is returned except text type in HTTP.
# In that case, "iso-8859-1" is returned as defined by RFC2616 3.7.1.
def charset
type, *parameters = content_type_parse
if pair = parameters.assoc('charset')
pair.last.downcase
elsif block_given?
yield
elsif type && %r{\Atext/} =~ type &&
@base_uri && /\Ahttp\z/i =~ @base_uri.scheme
"iso-8859-1" # RFC2616 3.7.1
else
nil
end
end
# returns a list of encodings in Content-Encoding field
# as an Array of String.
# The encodings are downcased for canonicalization.
def content_encoding
v = @meta['content-encoding']
if v && %r{\A#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?(?:,#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?)*}o =~ v
v.scan(RE_TOKEN).map {|content_coding| content_coding.downcase}
else
[]
end
end
end
# Mixin for HTTP and FTP URIs.
module OpenRead
# OpenURI::OpenRead#open provides `open' for URI::HTTP and URI::FTP.
#
# OpenURI::OpenRead#open takes optional 3 arguments as:
# OpenURI::OpenRead#open([mode [, perm]] [, options]) [{|io| ... }]
#
# `mode', `perm' is same as Kernel#open.
#
# However, `mode' must be read mode because OpenURI::OpenRead#open doesn't
# support write mode (yet).
# Also `perm' is just ignored because it is meaningful only for file
# creation.
#
# `options' must be a hash.
#
# Each pairs which key is a string in the hash specify a extra header
# field for HTTP.
# I.e. it is ignored for FTP without HTTP proxy.
#
# The hash may include other options which key is a symbol:
#
# [:proxy]
# Synopsis:
# :proxy => "http://proxy.foo.com:8000/"
# :proxy => URI.parse("http://proxy.foo.com:8000/")
# :proxy => true
# :proxy => false
# :proxy => nil
#
# If :proxy option is specified, the value should be String, URI,
# boolean or nil.
# When String or URI is given, it is treated as proxy URI.
# When true is given or the option itself is not specified,
# environment variable `scheme_proxy' is examined.
# `scheme' is replaced by `http', `https' or `ftp'.
# When false or nil is given, the environment variables are ignored and
# connection will be made to a server directly.
#
# [:proxy_http_basic_authentication]
# Synopsis:
# :proxy_http_basic_authentication => ["http://proxy.foo.com:8000/", "proxy-user", "proxy-password"]
# :proxy_http_basic_authentication => [URI.parse("http://proxy.foo.com:8000/"), "proxy-user", "proxy-password"]
#
# If :proxy option is specified, the value should be an Array with 3 elements.
# It should contain a proxy URI, a proxy user name and a proxy password.
# The proxy URI should be a String, an URI or nil.
# The proxy user name and password should be a String.
#
# If nil is given for the proxy URI, this option is just ignored.
#
# If :proxy and :proxy_http_basic_authentication is specified,
# ArgumentError is raised.
#
# [:http_basic_authentication]
# Synopsis:
# :http_basic_authentication=>[user, password]
#
# If :http_basic_authentication is specified,
# the value should be an array which contains 2 strings:
# username and password.
# It is used for HTTP Basic authentication defined by RFC 2617.
#
# [:content_length_proc]
# Synopsis:
# :content_length_proc => lambda {|content_length| ... }
#
# If :content_length_proc option is specified, the option value procedure
# is called before actual transfer is started.
# It takes one argument which is expected content length in bytes.
#
# If two or more transfer is done by HTTP redirection, the procedure
# is called only one for a last transfer.
#
# When expected content length is unknown, the procedure is called with
# nil.
# It is happen when HTTP response has no Content-Length header.
#
# [:progress_proc]
# Synopsis:
# :progress_proc => lambda {|size| ...}
#
# If :progress_proc option is specified, the proc is called with one
# argument each time when `open' gets content fragment from network.
# The argument `size' `size' is a accumulated transfered size in bytes.
#
# If two or more transfer is done by HTTP redirection, the procedure
# is called only one for a last transfer.
#
# :progress_proc and :content_length_proc are intended to be used for
# progress bar.
# For example, it can be implemented as follows using Ruby/ProgressBar.
#
# pbar = nil
# open("http://...",
# :content_length_proc => lambda {|t|
# if t && 0 < t
# pbar = ProgressBar.new("...", t)
# pbar.file_transfer_mode
# end
# },
# :progress_proc => lambda {|s|
# pbar.set s if pbar
# }) {|f| ... }
#
# [:read_timeout]
# Synopsis:
# :read_timeout=>nil (no timeout)
# :read_timeout=>10 (10 second)
#
# :read_timeout option specifies a timeout of read for http connections.
#
# [:ssl_ca_cert]
# Synopsis:
# :ssl_ca_cert=>filename
#
# :ssl_ca_cert is used to specify CA certificate for SSL.
# If it is given, default certificates are not used.
#
# [:ssl_verify_mode]
# Synopsis:
# :ssl_verify_mode=>mode
#
# :ssl_verify_mode is used to specify openssl verify mode.
#
# OpenURI::OpenRead#open returns an IO like object if block is not given.
# Otherwise it yields the IO object and return the value of the block.
# The IO object is extended with OpenURI::Meta.
#
# [:ftp_active_mode]
# Synopsis:
# :ftp_active_mode=>bool
#
# :ftp_active_mode=>true is used to make ftp active mode.
# Note that the active mode is default in Ruby 1.8 or prior.
# Ruby 1.9 uses passive mode by default.
#
# [:redirect]
# Synopsis:
# :redirect=>bool
#
# :redirect=>false is used to disable HTTP redirects at all.
# OpenURI::HTTPRedirect exception raised on redirection.
# It is true by default.
# The true means redirections between http and ftp is permitted.
#
def open(*rest, &block)
OpenURI.open_uri(self, *rest, &block)
end
# OpenURI::OpenRead#read([options]) reads a content referenced by self and
# returns the content as string.
# The string is extended with OpenURI::Meta.
# The argument `options' is same as OpenURI::OpenRead#open.
def read(options={})
self.open(options) {|f|
str = f.read
Meta.init str, f
str
}
end
end
end
module URI
class Generic
# returns a proxy URI.
# The proxy URI is obtained from environment variables such as http_proxy,
# ftp_proxy, no_proxy, etc.
# If there is no proper proxy, nil is returned.
#
# Note that capitalized variables (HTTP_PROXY, FTP_PROXY, NO_PROXY, etc.)
# are examined too.
#
# But http_proxy and HTTP_PROXY is treated specially under CGI environment.
# It's because HTTP_PROXY may be set by Proxy: header.
# So HTTP_PROXY is not used.
# http_proxy is not used too if the variable is case insensitive.
# CGI_HTTP_PROXY can be used instead.
def find_proxy
name = self.scheme.downcase + '_proxy'
proxy_uri = nil
if name == 'http_proxy' && ENV.include?('REQUEST_METHOD') # CGI?
# HTTP_PROXY conflicts with *_proxy for proxy settings and
# HTTP_* for header information in CGI.
# So it should be careful to use it.
pairs = ENV.reject {|k, v| /\Ahttp_proxy\z/i !~ k }
case pairs.length
when 0 # no proxy setting anyway.
proxy_uri = nil
when 1
k, v = pairs.shift
if k == 'http_proxy' && ENV[k.upcase] == nil
# http_proxy is safe to use because ENV is case sensitive.
proxy_uri = ENV[name]
else
proxy_uri = nil
end
else # http_proxy is safe to use because ENV is case sensitive.
proxy_uri = ENV.to_hash[name]
end
if !proxy_uri
# Use CGI_HTTP_PROXY. cf. libwww-perl.
proxy_uri = ENV["CGI_#{name.upcase}"]
end
elsif name == 'http_proxy'
unless proxy_uri = ENV[name]
if proxy_uri = ENV[name.upcase]
warn 'The environment variable HTTP_PROXY is discouraged. Use http_proxy.'
end
end
else
proxy_uri = ENV[name] || ENV[name.upcase]
end
if proxy_uri && self.host
require 'socket'
begin
addr = IPSocket.getaddress(self.host)
proxy_uri = nil if /\A127\.|\A::1\z/ =~ addr
rescue SocketError
end
end
if proxy_uri
proxy_uri = URI.parse(proxy_uri)
name = 'no_proxy'
if no_proxy = ENV[name] || ENV[name.upcase]
no_proxy.scan(/([^:,]*)(?::(\d+))?/) {|host, port|
if /(\A|\.)#{Regexp.quote host}\z/i =~ self.host &&
(!port || self.port == port.to_i)
proxy_uri = nil
break
end
}
end
proxy_uri
else
nil
end
end
end
class HTTP
def buffer_open(buf, proxy, options) # :nodoc:
OpenURI.open_http(buf, self, proxy, options)
end
include OpenURI::OpenRead
end
class FTP
def buffer_open(buf, proxy, options) # :nodoc:
if proxy
OpenURI.open_http(buf, self, proxy, options)
return
end
require 'net/ftp'
directories = self.path.split(%r{/}, -1)
directories.shift if directories[0] == '' # strip a field before leading slash
directories.each {|d|
d.gsub!(/%([0-9A-Fa-f][0-9A-Fa-f])/) { [$1].pack("H2") }
}
unless filename = directories.pop
raise ArgumentError, "no filename: #{self.inspect}"
end
directories.each {|d|
if /[\r\n]/ =~ d
raise ArgumentError, "invalid directory: #{d.inspect}"
end
}
if /[\r\n]/ =~ filename
raise ArgumentError, "invalid filename: #{filename.inspect}"
end
typecode = self.typecode
if typecode && /\A[aid]\z/ !~ typecode
raise ArgumentError, "invalid typecode: #{typecode.inspect}"
end
# The access sequence is defined by RFC 1738
ftp = Net::FTP.open(self.host)
ftp.passive = true if !options[:ftp_active_mode]
# todo: extract user/passwd from .netrc.
user = 'anonymous'
passwd = nil
user, passwd = self.userinfo.split(/:/) if self.userinfo
ftp.login(user, passwd)
directories.each {|cwd|
ftp.voidcmd("CWD #{cwd}")
}
if typecode
# xxx: typecode D is not handled.
ftp.voidcmd("TYPE #{typecode.upcase}")
end
if options[:content_length_proc]
options[:content_length_proc].call(ftp.size(filename))
end
ftp.retrbinary("RETR #{filename}", 4096) { |str|
buf << str
options[:progress_proc].call(buf.size) if options[:progress_proc]
}
ftp.close
buf.io.rewind
end
include OpenURI::OpenRead
end
end
| 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/getoptlong.rb | tools/jruby-1.5.1/lib/ruby/1.9/getoptlong.rb | #
# GetoptLong for Ruby
#
# Copyright (C) 1998, 1999, 2000 Motoyuki Kasahara.
#
# You may redistribute and/or modify this library under the same license
# terms as Ruby.
#
# See GetoptLong for documentation.
#
# Additional documents and the latest version of `getoptlong.rb' can be
# found at http://www.sra.co.jp/people/m-kasahr/ruby/getoptlong/
# The GetoptLong class allows you to parse command line options similarly to
# the GNU getopt_long() C library call. Note, however, that GetoptLong is a
# pure Ruby implementation.
#
# GetoptLong allows for POSIX-style options like <tt>--file</tt> as well
# as single letter options like <tt>-f</tt>
#
# The empty option <tt>--</tt> (two minus symbols) is used to end option
# processing. This can be particularly important if options have optional
# arguments.
#
# Here is a simple example of usage:
#
# require 'getoptlong'
#
# opts = GetoptLong.new(
# [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
# [ '--repeat', '-n', GetoptLong::REQUIRED_ARGUMENT ],
# [ '--name', GetoptLong::OPTIONAL_ARGUMENT ]
# )
#
# dir = nil
# name = nil
# repetitions = 1
# opts.each do |opt, arg|
# case opt
# when '--help'
# puts <<-EOF
# hello [OPTION] ... DIR
#
# -h, --help:
# show help
#
# --repeat x, -n x:
# repeat x times
#
# --name [name]:
# greet user by name, if name not supplied default is John
#
# DIR: The directory in which to issue the greeting.
# EOF
# when '--repeat'
# repetitions = arg.to_i
# when '--name'
# if arg == ''
# name = 'John'
# else
# name = arg
# end
# end
# end
#
# if ARGV.length != 1
# puts "Missing dir argument (try --help)"
# exit 0
# end
#
# dir = ARGV.shift
#
# Dir.chdir(dir)
# for i in (1..repetitions)
# print "Hello"
# if name
# print ", #{name}"
# end
# puts
# end
#
# Example command line:
#
# hello -n 6 --name -- /tmp
#
class GetoptLong
#
# Orderings.
#
ORDERINGS = [REQUIRE_ORDER = 0, PERMUTE = 1, RETURN_IN_ORDER = 2]
#
# Argument flags.
#
ARGUMENT_FLAGS = [NO_ARGUMENT = 0, REQUIRED_ARGUMENT = 1,
OPTIONAL_ARGUMENT = 2]
#
# Status codes.
#
STATUS_YET, STATUS_STARTED, STATUS_TERMINATED = 0, 1, 2
#
# Error types.
#
class Error < StandardError; end
class AmbiguousOption < Error; end
class NeedlessArgument < Error; end
class MissingArgument < Error; end
class InvalidOption < Error; end
#
# Set up option processing.
#
# The options to support are passed to new() as an array of arrays.
# Each sub-array contains any number of String option names which carry
# the same meaning, and one of the following flags:
#
# GetoptLong::NO_ARGUMENT :: Option does not take an argument.
#
# GetoptLong::REQUIRED_ARGUMENT :: Option always takes an argument.
#
# GetoptLong::OPTIONAL_ARGUMENT :: Option may or may not take an argument.
#
# The first option name is considered to be the preferred (canonical) name.
# Other than that, the elements of each sub-array can be in any order.
#
def initialize(*arguments)
#
# Current ordering.
#
if ENV.include?('POSIXLY_CORRECT')
@ordering = REQUIRE_ORDER
else
@ordering = PERMUTE
end
#
# Hash table of option names.
# Keys of the table are option names, and their values are canonical
# names of the options.
#
@canonical_names = Hash.new
#
# Hash table of argument flags.
# Keys of the table are option names, and their values are argument
# flags of the options.
#
@argument_flags = Hash.new
#
# Whether error messages are output to $stderr.
#
@quiet = FALSE
#
# Status code.
#
@status = STATUS_YET
#
# Error code.
#
@error = nil
#
# Error message.
#
@error_message = nil
#
# Rest of catenated short options.
#
@rest_singles = ''
#
# List of non-option-arguments.
# Append them to ARGV when option processing is terminated.
#
@non_option_arguments = Array.new
if 0 < arguments.length
set_options(*arguments)
end
end
#
# Set the handling of the ordering of options and arguments.
# A RuntimeError is raised if option processing has already started.
#
# The supplied value must be a member of GetoptLong::ORDERINGS. It alters
# the processing of options as follows:
#
# <b>REQUIRE_ORDER</b> :
#
# Options are required to occur before non-options.
#
# Processing of options ends as soon as a word is encountered that has not
# been preceded by an appropriate option flag.
#
# For example, if -a and -b are options which do not take arguments,
# parsing command line arguments of '-a one -b two' would result in
# 'one', '-b', 'two' being left in ARGV, and only ('-a', '') being
# processed as an option/arg pair.
#
# This is the default ordering, if the environment variable
# POSIXLY_CORRECT is set. (This is for compatibility with GNU getopt_long.)
#
# <b>PERMUTE</b> :
#
# Options can occur anywhere in the command line parsed. This is the
# default behavior.
#
# Every sequence of words which can be interpreted as an option (with or
# without argument) is treated as an option; non-option words are skipped.
#
# For example, if -a does not require an argument and -b optionally takes
# an argument, parsing '-a one -b two three' would result in ('-a','') and
# ('-b', 'two') being processed as option/arg pairs, and 'one','three'
# being left in ARGV.
#
# If the ordering is set to PERMUTE but the environment variable
# POSIXLY_CORRECT is set, REQUIRE_ORDER is used instead. This is for
# compatibility with GNU getopt_long.
#
# <b>RETURN_IN_ORDER</b> :
#
# All words on the command line are processed as options. Words not
# preceded by a short or long option flag are passed as arguments
# with an option of '' (empty string).
#
# For example, if -a requires an argument but -b does not, a command line
# of '-a one -b two three' would result in option/arg pairs of ('-a', 'one')
# ('-b', ''), ('', 'two'), ('', 'three') being processed.
#
def ordering=(ordering)
#
# The method is failed if option processing has already started.
#
if @status != STATUS_YET
set_error(ArgumentError, "argument error")
raise RuntimeError,
"invoke ordering=, but option processing has already started"
end
#
# Check ordering.
#
if !ORDERINGS.include?(ordering)
raise ArgumentError, "invalid ordering `#{ordering}'"
end
if ordering == PERMUTE && ENV.include?('POSIXLY_CORRECT')
@ordering = REQUIRE_ORDER
else
@ordering = ordering
end
end
#
# Return ordering.
#
attr_reader :ordering
#
# Set options. Takes the same argument as GetoptLong.new.
#
# Raises a RuntimeError if option processing has already started.
#
def set_options(*arguments)
#
# The method is failed if option processing has already started.
#
if @status != STATUS_YET
raise RuntimeError,
"invoke set_options, but option processing has already started"
end
#
# Clear tables of option names and argument flags.
#
@canonical_names.clear
@argument_flags.clear
arguments.each do |*arg|
arg = arg.first # TODO: YARV Hack
#
# Find an argument flag and it set to `argument_flag'.
#
argument_flag = nil
arg.each do |i|
if ARGUMENT_FLAGS.include?(i)
if argument_flag != nil
raise ArgumentError, "too many argument-flags"
end
argument_flag = i
end
end
raise ArgumentError, "no argument-flag" if argument_flag == nil
canonical_name = nil
arg.each do |i|
#
# Check an option name.
#
next if i == argument_flag
begin
if !i.is_a?(String) || i !~ /^-([^-]|-.+)$/
raise ArgumentError, "an invalid option `#{i}'"
end
if (@canonical_names.include?(i))
raise ArgumentError, "option redefined `#{i}'"
end
rescue
@canonical_names.clear
@argument_flags.clear
raise
end
#
# Register the option (`i') to the `@canonical_names' and
# `@canonical_names' Hashes.
#
if canonical_name == nil
canonical_name = i
end
@canonical_names[i] = canonical_name
@argument_flags[i] = argument_flag
end
raise ArgumentError, "no option name" if canonical_name == nil
end
return self
end
#
# Set/Unset `quiet' mode.
#
attr_writer :quiet
#
# Return the flag of `quiet' mode.
#
attr_reader :quiet
#
# `quiet?' is an alias of `quiet'.
#
alias quiet? quiet
#
# Explicitly terminate option processing.
#
def terminate
return nil if @status == STATUS_TERMINATED
raise RuntimeError, "an error has occured" if @error != nil
@status = STATUS_TERMINATED
@non_option_arguments.reverse_each do |argument|
ARGV.unshift(argument)
end
@canonical_names = nil
@argument_flags = nil
@rest_singles = nil
@non_option_arguments = nil
return self
end
#
# Returns true if option processing has terminated, false otherwise.
#
def terminated?
return @status == STATUS_TERMINATED
end
#
# Set an error (a protected method).
#
def set_error(type, message)
$stderr.print("#{$0}: #{message}\n") if !@quiet
@error = type
@error_message = message
@canonical_names = nil
@argument_flags = nil
@rest_singles = nil
@non_option_arguments = nil
raise type, message
end
protected :set_error
#
# Examine whether an option processing is failed.
#
attr_reader :error
#
# `error?' is an alias of `error'.
#
alias error? error
# Return the appropriate error message in POSIX-defined format.
# If no error has occurred, returns nil.
#
def error_message
return @error_message
end
#
# Get next option name and its argument, as an Array of two elements.
#
# The option name is always converted to the first (preferred)
# name given in the original options to GetoptLong.new.
#
# Example: ['--option', 'value']
#
# Returns nil if the processing is complete (as determined by
# STATUS_TERMINATED).
#
def get
option_name, option_argument = nil, ''
#
# Check status.
#
return nil if @error != nil
case @status
when STATUS_YET
@status = STATUS_STARTED
when STATUS_TERMINATED
return nil
end
#
# Get next option argument.
#
if 0 < @rest_singles.length
argument = '-' + @rest_singles
elsif (ARGV.length == 0)
terminate
return nil
elsif @ordering == PERMUTE
while 0 < ARGV.length && ARGV[0] !~ /^-./
@non_option_arguments.push(ARGV.shift)
end
if ARGV.length == 0
terminate
return nil
end
argument = ARGV.shift
elsif @ordering == REQUIRE_ORDER
if (ARGV[0] !~ /^-./)
terminate
return nil
end
argument = ARGV.shift
else
argument = ARGV.shift
end
#
# Check the special argument `--'.
# `--' indicates the end of the option list.
#
if argument == '--' && @rest_singles.length == 0
terminate
return nil
end
#
# Check for long and short options.
#
if argument =~ /^(--[^=]+)/ && @rest_singles.length == 0
#
# This is a long style option, which start with `--'.
#
pattern = $1
if @canonical_names.include?(pattern)
option_name = pattern
else
#
# The option `option_name' is not registered in `@canonical_names'.
# It may be an abbreviated.
#
matches = []
@canonical_names.each_key do |key|
if key.index(pattern) == 0
option_name = key
matches << key
end
end
if 2 <= matches.length
set_error(AmbiguousOption, "option `#{argument}' is ambiguous between #{matches.join(', ')}")
elsif matches.length == 0
set_error(InvalidOption, "unrecognized option `#{argument}'")
end
end
#
# Check an argument to the option.
#
if @argument_flags[option_name] == REQUIRED_ARGUMENT
if argument =~ /=(.*)$/
option_argument = $1
elsif 0 < ARGV.length
option_argument = ARGV.shift
else
set_error(MissingArgument,
"option `#{argument}' requires an argument")
end
elsif @argument_flags[option_name] == OPTIONAL_ARGUMENT
if argument =~ /=(.*)$/
option_argument = $1
elsif 0 < ARGV.length && ARGV[0] !~ /^-./
option_argument = ARGV.shift
else
option_argument = ''
end
elsif argument =~ /=(.*)$/
set_error(NeedlessArgument,
"option `#{option_name}' doesn't allow an argument")
end
elsif argument =~ /^(-(.))(.*)/
#
# This is a short style option, which start with `-' (not `--').
# Short options may be catenated (e.g. `-l -g' is equivalent to
# `-lg').
#
option_name, ch, @rest_singles = $1, $2, $3
if @canonical_names.include?(option_name)
#
# The option `option_name' is found in `@canonical_names'.
# Check its argument.
#
if @argument_flags[option_name] == REQUIRED_ARGUMENT
if 0 < @rest_singles.length
option_argument = @rest_singles
@rest_singles = ''
elsif 0 < ARGV.length
option_argument = ARGV.shift
else
# 1003.2 specifies the format of this message.
set_error(MissingArgument, "option requires an argument -- #{ch}")
end
elsif @argument_flags[option_name] == OPTIONAL_ARGUMENT
if 0 < @rest_singles.length
option_argument = @rest_singles
@rest_singles = ''
elsif 0 < ARGV.length && ARGV[0] !~ /^-./
option_argument = ARGV.shift
else
option_argument = ''
end
end
else
#
# This is an invalid option.
# 1003.2 specifies the format of this message.
#
if ENV.include?('POSIXLY_CORRECT')
set_error(InvalidOption, "invalid option -- #{ch}")
else
set_error(InvalidOption, "invalid option -- #{ch}")
end
end
else
#
# This is a non-option argument.
# Only RETURN_IN_ORDER falled into here.
#
return '', argument
end
return @canonical_names[option_name], option_argument
end
#
# `get_option' is an alias of `get'.
#
alias get_option get
# Iterator version of `get'.
#
# The block is called repeatedly with two arguments:
# The first is the option name.
# The second is the argument which followed it (if any).
# Example: ('--opt', 'value')
#
# The option name is always converted to the first (preferred)
# name given in the original options to GetoptLong.new.
#
def each
loop do
option_name, option_argument = get_option
break if option_name == nil
yield option_name, option_argument
end
end
#
# `each_option' is an alias of `each'.
#
alias each_option each
end
| 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/thread.rb | tools/jruby-1.5.1/lib/ruby/1.9/thread.rb | #
# thread.rb - thread support classes
# by Yukihiro Matsumoto <matz@netlab.co.jp>
#
# Copyright (C) 2001 Yukihiro Matsumoto
# Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
# Copyright (C) 2000 Information-technology Promotion Agency, Japan
#
unless defined? Thread
raise "Thread not available for this ruby interpreter"
end
unless defined? ThreadError
class ThreadError < StandardError
end
end
if $DEBUG
Thread.abort_on_exception = true
end
#
# ConditionVariable objects augment class Mutex. Using condition variables,
# it is possible to suspend while in the middle of a critical section until a
# resource becomes available.
#
# Example:
#
# require 'thread'
#
# mutex = Mutex.new
# resource = ConditionVariable.new
#
# a = Thread.new {
# mutex.synchronize {
# # Thread 'a' now needs the resource
# resource.wait(mutex)
# # 'a' can now have the resource
# }
# }
#
# b = Thread.new {
# mutex.synchronize {
# # Thread 'b' has finished using the resource
# resource.signal
# }
# }
#
class ConditionVariable
#
# Creates a new ConditionVariable
#
def initialize
@waiters = []
@waiters_mutex = Mutex.new
end
#
# Releases the lock held in +mutex+ and waits; reacquires the lock on wakeup.
#
def wait(mutex)
begin
# TODO: mutex should not be used
@waiters_mutex.synchronize do
@waiters.push(Thread.current)
end
mutex.sleep
end
end
#
# Wakes up the first thread in line waiting for this lock.
#
def signal
begin
t = @waiters_mutex.synchronize { @waiters.shift }
t.run if t
rescue ThreadError
retry
end
end
#
# Wakes up all threads waiting for this lock.
#
def broadcast
# TODO: imcomplete
waiters0 = nil
@waiters_mutex.synchronize do
waiters0 = @waiters.dup
@waiters.clear
end
for t in waiters0
begin
t.run
rescue ThreadError
end
end
end
end
#
# This class provides a way to synchronize communication between threads.
#
# Example:
#
# require 'thread'
#
# queue = Queue.new
#
# producer = Thread.new do
# 5.times do |i|
# sleep rand(i) # simulate expense
# queue << i
# puts "#{i} produced"
# end
# end
#
# consumer = Thread.new do
# 5.times do |i|
# value = queue.pop
# sleep rand(i/2) # simulate expense
# puts "consumed #{value}"
# end
# end
#
# consumer.join
#
class Queue
#
# Creates a new queue.
#
def initialize
@que = []
@waiting = []
@que.taint # enable tainted comunication
@waiting.taint
self.taint
@mutex = Mutex.new
end
#
# Pushes +obj+ to the queue.
#
def push(obj)
t = nil
@mutex.synchronize{
@que.push obj
begin
t = @waiting.shift
t.wakeup if t
rescue ThreadError
retry
end
}
begin
t.run if t
rescue ThreadError
end
end
#
# Alias of push
#
alias << push
#
# Alias of push
#
alias enq push
#
# Retrieves data from the queue. If the queue is empty, the calling thread is
# suspended until data is pushed onto the queue. If +non_block+ is true, the
# thread isn't suspended, and an exception is raised.
#
def pop(non_block=false)
while true
@mutex.synchronize{
if @que.empty?
raise ThreadError, "queue empty" if non_block
@waiting.push Thread.current
@mutex.sleep
else
return @que.shift
end
}
end
end
#
# Alias of pop
#
alias shift pop
#
# Alias of pop
#
alias deq pop
#
# Returns +true+ if the queue is empty.
#
def empty?
@que.empty?
end
#
# Removes all objects from the queue.
#
def clear
@que.clear
end
#
# Returns the length of the queue.
#
def length
@que.length
end
#
# Alias of length.
#
alias size length
#
# Returns the number of threads waiting on the queue.
#
def num_waiting
@waiting.size
end
end
#
# This class represents queues of specified size capacity. The push operation
# may be blocked if the capacity is full.
#
# See Queue for an example of how a SizedQueue works.
#
class SizedQueue < Queue
#
# Creates a fixed-length queue with a maximum size of +max+.
#
def initialize(max)
raise ArgumentError, "queue size must be positive" unless max > 0
@max = max
@queue_wait = []
@queue_wait.taint # enable tainted comunication
super()
end
#
# Returns the maximum size of the queue.
#
def max
@max
end
#
# Sets the maximum size of the queue.
#
def max=(max)
diff = nil
@mutex.synchronize {
if max <= @max
@max = max
else
diff = max - @max
@max = max
end
}
if diff
diff.times do
begin
t = @queue_wait.shift
t.run if t
rescue ThreadError
retry
end
end
end
max
end
#
# Pushes +obj+ to the queue. If there is no space left in the queue, waits
# until space becomes available.
#
def push(obj)
t = nil
@mutex.synchronize{
while true
break if @que.length < @max
@queue_wait.push Thread.current
@mutex.sleep
end
@que.push obj
begin
t = @waiting.shift
t.wakeup if t
rescue ThreadError
retry
end
}
begin
t.run if t
rescue ThreadError
end
end
#
# Alias of push
#
alias << push
#
# Alias of push
#
alias enq push
#
# Retrieves data from the queue and runs a waiting thread, if any.
#
def pop(*args)
retval = super
t = nil
@mutex.synchronize {
if @que.length < @max
begin
t = @queue_wait.shift
t.wakeup if t
rescue ThreadError
retry
end
end
}
begin
t.run if t
rescue ThreadError
end
retval
end
#
# Alias of pop
#
alias shift pop
#
# Alias of pop
#
alias deq pop
#
# Returns the number of threads waiting on the queue.
#
def num_waiting
@waiting.size + @queue_wait.size
end
end
# Documentation comments:
# - How do you make RDoc inherit documentation from superclass?
| 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/securerandom.rb | tools/jruby-1.5.1/lib/ruby/1.9/securerandom.rb | # = Secure random number generator interface.
#
# This library is an interface for secure random number generator which is
# suitable for generating session key in HTTP cookies, etc.
#
# It supports following secure random number generators.
#
# * openssl
# * /dev/urandom
# * Win32
#
# == Example
#
# # random hexadecimal string.
# p SecureRandom.hex(10) #=> "52750b30ffbc7de3b362"
# p SecureRandom.hex(10) #=> "92b15d6c8dc4beb5f559"
# p SecureRandom.hex(11) #=> "6aca1b5c58e4863e6b81b8"
# p SecureRandom.hex(12) #=> "94b2fff3e7fd9b9c391a2306"
# p SecureRandom.hex(13) #=> "39b290146bea6ce975c37cfc23"
# ...
#
# # random base64 string.
# p SecureRandom.base64(10) #=> "EcmTPZwWRAozdA=="
# p SecureRandom.base64(10) #=> "9b0nsevdwNuM/w=="
# p SecureRandom.base64(10) #=> "KO1nIU+p9DKxGg=="
# p SecureRandom.base64(11) #=> "l7XEiFja+8EKEtY="
# p SecureRandom.base64(12) #=> "7kJSM/MzBJI+75j8"
# p SecureRandom.base64(13) #=> "vKLJ0tXBHqQOuIcSIg=="
# ...
#
# # random binary string.
# p SecureRandom.random_bytes(10) #=> "\016\t{\370g\310pbr\301"
# p SecureRandom.random_bytes(10) #=> "\323U\030TO\234\357\020\a\337"
# ...
begin
require 'openssl'
rescue LoadError
end
module SecureRandom
# SecureRandom.random_bytes generates a random binary string.
#
# The argument n specifies the length of the result string.
#
# If n is not specified, 16 is assumed.
# It may be larger in future.
#
# The result may contain any byte: "\x00" - "\xff".
#
# p SecureRandom.random_bytes #=> "\xD8\\\xE0\xF4\r\xB2\xFC*WM\xFF\x83\x18\xF45\xB6"
# p SecureRandom.random_bytes #=> "m\xDC\xFC/\a\x00Uf\xB2\xB2P\xBD\xFF6S\x97"
#
# If secure random number generator is not available,
# NotImplementedError is raised.
def self.random_bytes(n=nil)
n ||= 16
if defined? OpenSSL::Random
return OpenSSL::Random.random_bytes(n)
end
if !defined?(@has_urandom) || @has_urandom
flags = File::RDONLY
flags |= File::NONBLOCK if defined? File::NONBLOCK
flags |= File::NOCTTY if defined? File::NOCTTY
flags |= File::NOFOLLOW if defined? File::NOFOLLOW
begin
File.open("/dev/urandom", flags) {|f|
unless f.stat.chardev?
raise Errno::ENOENT
end
@has_urandom = true
ret = f.readpartial(n)
if ret.length != n
raise NotImplementedError, "Unexpected partial read from random device"
end
return ret
}
rescue Errno::ENOENT
@has_urandom = false
end
end
if !defined?(@has_win32)
begin
require 'Win32API'
crypt_acquire_context = Win32API.new("advapi32", "CryptAcquireContext", 'PPPII', 'L')
@crypt_gen_random = Win32API.new("advapi32", "CryptGenRandom", 'LIP', 'L')
hProvStr = " " * 4
prov_rsa_full = 1
crypt_verifycontext = 0xF0000000
if crypt_acquire_context.call(hProvStr, nil, nil, prov_rsa_full, crypt_verifycontext) == 0
raise SystemCallError, "CryptAcquireContext failed: #{lastWin32ErrorMessage}"
end
@hProv, = hProvStr.unpack('L')
@has_win32 = true
rescue LoadError
@has_win32 = false
end
end
if @has_win32
bytes = " ".force_encoding("ASCII-8BIT") * n
if @crypt_gen_random.call(@hProv, bytes.size, bytes) == 0
raise SystemCallError, "CryptGenRandom failed: #{lastWin32ErrorMessage}"
end
return bytes
end
raise NotImplementedError, "No random device"
end
# SecureRandom.hex generates a random hex string.
#
# The argument n specifies the length of the random length.
# The length of the result string is twice of n.
#
# If n is not specified, 16 is assumed.
# It may be larger in future.
#
# The result may contain 0-9 and a-f.
#
# p SecureRandom.hex #=> "eb693ec8252cd630102fd0d0fb7c3485"
# p SecureRandom.hex #=> "91dc3bfb4de5b11d029d376634589b61"
#
# If secure random number generator is not available,
# NotImplementedError is raised.
def self.hex(n=nil)
random_bytes(n).unpack("H*")[0]
end
# SecureRandom.base64 generates a random base64 string.
#
# The argument n specifies the length of the random length.
# The length of the result string is about 4/3 of n.
#
# If n is not specified, 16 is assumed.
# It may be larger in future.
#
# The result may contain A-Z, a-z, 0-9, "+", "/" and "=".
#
# p SecureRandom.base64 #=> "/2BuBuLf3+WfSKyQbRcc/A=="
# p SecureRandom.base64 #=> "6BbW0pxO0YENxn38HMUbcQ=="
#
# If secure random number generator is not available,
# NotImplementedError is raised.
#
# See RFC 3548 for base64.
def self.base64(n=nil)
[random_bytes(n)].pack("m*").delete("\n")
end
# SecureRandom.urlsafe_base64 generates a random URL-safe base64 string.
#
# The argument _n_ specifies the length of the random length.
# The length of the result string is about 4/3 of _n_.
#
# If _n_ is not specified, 16 is assumed.
# It may be larger in future.
#
# The boolean argument _padding_ specifies the padding.
# If it is false or nil, padding is not generated.
# Otherwise padding is generated.
# By default, padding is not generated because "=" may be used as a URL delimiter.
#
# The result may contain A-Z, a-z, 0-9, "-" and "_".
# "=" is also used if _padding_ is true.
#
# p SecureRandom.urlsafe_base64 #=> "b4GOKm4pOYU_-BOXcrUGDg"
# p SecureRandom.urlsafe_base64 #=> "UZLdOkzop70Ddx-IJR0ABg"
#
# p SecureRandom.urlsafe_base64(nil, true) #=> "i0XQ-7gglIsHGV2_BNPrdQ=="
# p SecureRandom.urlsafe_base64(nil, true) #=> "-M8rLhr7JEpJlqFGUMmOxg=="
#
# If secure random number generator is not available,
# NotImplementedError is raised.
#
# See RFC 3548 for URL-safe base64.
def self.urlsafe_base64(n=nil, padding=false)
s = [random_bytes(n)].pack("m*")
s.delete!("\n")
s.tr!("+/", "-_")
s.delete!("=") if !padding
s
end
# SecureRandom.random_number generates a random number.
#
# If an positive integer is given as n,
# SecureRandom.random_number returns an integer:
# 0 <= SecureRandom.random_number(n) < n.
#
# p SecureRandom.random_number(100) #=> 15
# p SecureRandom.random_number(100) #=> 88
#
# If 0 is given or an argument is not given,
# SecureRandom.random_number returns an float:
# 0.0 <= SecureRandom.random_number() < 1.0.
#
# p SecureRandom.random_number #=> 0.596506046187744
# p SecureRandom.random_number #=> 0.350621695741409
#
def self.random_number(n=0)
if 0 < n
hex = n.to_s(16)
hex = '0' + hex if (hex.length & 1) == 1
bin = [hex].pack("H*")
mask = bin[0].ord
mask |= mask >> 1
mask |= mask >> 2
mask |= mask >> 4
begin
rnd = SecureRandom.random_bytes(bin.length)
rnd[0] = (rnd[0].ord & mask).chr
end until rnd < bin
rnd.unpack("H*")[0].hex
else
# assumption: Float::MANT_DIG <= 64
i64 = SecureRandom.random_bytes(8).unpack("Q")[0]
Math.ldexp(i64 >> (64-Float::MANT_DIG), -Float::MANT_DIG)
end
end
# SecureRandom.uuid generates a v4 random UUID (Universally Unique IDentifier).
#
# p SecureRandom.uuid #=> "2d931510-d99f-494a-8c67-87feb05e1594"
# p SecureRandom.uuid #=> "bad85eb9-0713-4da7-8d36-07a8e4b00eab"
# p SecureRandom.uuid #=> "62936e70-1815-439b-bf89-8492855a7e6b"
#
# The version 4 UUID is purely random (except the version).
# It doesn't contain meaningful information such as MAC address, time, etc.
#
# See RFC 4122 for details of UUID.
#
def self.uuid
ary = self.random_bytes(16).unpack("NnnnnN")
ary[2] = (ary[2] & 0x0fff) | 0x4000
ary[3] = (ary[3] & 0x3fff) | 0x8000
"%08x-%04x-%04x-%04x-%04x%08x" % ary
end
# Following code is based on David Garamond's GUID library for Ruby.
def self.lastWin32ErrorMessage # :nodoc:
get_last_error = Win32API.new("kernel32", "GetLastError", '', 'L')
format_message = Win32API.new("kernel32", "FormatMessageA", 'LPLLPLPPPPPPPP', 'L')
format_message_ignore_inserts = 0x00000200
format_message_from_system = 0x00001000
code = get_last_error.call
msg = "\0" * 1024
len = format_message.call(format_message_ignore_inserts + format_message_from_system, 0, code, 0, msg, 1024, nil, nil, nil, nil, nil, nil, nil, nil)
msg[0, len].tr("\r", '').chomp
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/optparse.rb | tools/jruby-1.5.1/lib/ruby/1.9/optparse.rb | #
# optparse.rb - command-line option analysis with the OptionParser class.
#
# Author:: Nobu Nakada
# Documentation:: Nobu Nakada and Gavin Sinclair.
#
# See OptionParser for documentation.
#
# == Developer Documentation (not for RDoc output)
#
# === Class tree
#
# - OptionParser:: front end
# - OptionParser::Switch:: each switches
# - OptionParser::List:: options list
# - OptionParser::ParseError:: errors on parsing
# - OptionParser::AmbiguousOption
# - OptionParser::NeedlessArgument
# - OptionParser::MissingArgument
# - OptionParser::InvalidOption
# - OptionParser::InvalidArgument
# - OptionParser::AmbiguousArgument
#
# === Object relationship diagram
#
# +--------------+
# | OptionParser |<>-----+
# +--------------+ | +--------+
# | ,-| Switch |
# on_head -------->+---------------+ / +--------+
# accept/reject -->| List |<|>-
# | |<|>- +----------+
# on ------------->+---------------+ `-| argument |
# : : | class |
# +---------------+ |==========|
# on_tail -------->| | |pattern |
# +---------------+ |----------|
# OptionParser.accept ->| DefaultList | |converter |
# reject |(shared between| +----------+
# | all instances)|
# +---------------+
#
# == OptionParser
#
# === Introduction
#
# OptionParser is a class for command-line option analysis. It is much more
# advanced, yet also easier to use, than GetoptLong, and is a more Ruby-oriented
# solution.
#
# === Features
#
# 1. The argument specification and the code to handle it are written in the
# same place.
# 2. It can output an option summary; you don't need to maintain this string
# separately.
# 3. Optional and mandatory arguments are specified very gracefully.
# 4. Arguments can be automatically converted to a specified class.
# 5. Arguments can be restricted to a certain set.
#
# All of these features are demonstrated in the examples below.
#
# === Minimal example
#
# require 'optparse'
#
# options = {}
# OptionParser.new do |opts|
# opts.banner = "Usage: example.rb [options]"
#
# opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
# options[:verbose] = v
# end
# end.parse!
#
# p options
# p ARGV
#
# === Complete example
#
# The following example is a complete Ruby program. You can run it and see the
# effect of specifying various options. This is probably the best way to learn
# the features of +optparse+.
#
# require 'optparse'
# require 'optparse/time'
# require 'ostruct'
# require 'pp'
#
# class OptparseExample
#
# CODES = %w[iso-2022-jp shift_jis euc-jp utf8 binary]
# CODE_ALIASES = { "jis" => "iso-2022-jp", "sjis" => "shift_jis" }
#
# #
# # Return a structure describing the options.
# #
# def self.parse(args)
# # The options specified on the command line will be collected in *options*.
# # We set default values here.
# options = OpenStruct.new
# options.library = []
# options.inplace = false
# options.encoding = "utf8"
# options.transfer_type = :auto
# options.verbose = false
#
# opts = OptionParser.new do |opts|
# opts.banner = "Usage: example.rb [options]"
#
# opts.separator ""
# opts.separator "Specific options:"
#
# # Mandatory argument.
# opts.on("-r", "--require LIBRARY",
# "Require the LIBRARY before executing your script") do |lib|
# options.library << lib
# end
#
# # Optional argument; multi-line description.
# opts.on("-i", "--inplace [EXTENSION]",
# "Edit ARGV files in place",
# " (make backup if EXTENSION supplied)") do |ext|
# options.inplace = true
# options.extension = ext || ''
# options.extension.sub!(/\A\.?(?=.)/, ".") # Ensure extension begins with dot.
# end
#
# # Cast 'delay' argument to a Float.
# opts.on("--delay N", Float, "Delay N seconds before executing") do |n|
# options.delay = n
# end
#
# # Cast 'time' argument to a Time object.
# opts.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time|
# options.time = time
# end
#
# # Cast to octal integer.
# opts.on("-F", "--irs [OCTAL]", OptionParser::OctalInteger,
# "Specify record separator (default \\0)") do |rs|
# options.record_separator = rs
# end
#
# # List of arguments.
# opts.on("--list x,y,z", Array, "Example 'list' of arguments") do |list|
# options.list = list
# end
#
# # Keyword completion. We are specifying a specific set of arguments (CODES
# # and CODE_ALIASES - notice the latter is a Hash), and the user may provide
# # the shortest unambiguous text.
# code_list = (CODE_ALIASES.keys + CODES).join(',')
# opts.on("--code CODE", CODES, CODE_ALIASES, "Select encoding",
# " (#{code_list})") do |encoding|
# options.encoding = encoding
# end
#
# # Optional argument with keyword completion.
# opts.on("--type [TYPE]", [:text, :binary, :auto],
# "Select transfer type (text, binary, auto)") do |t|
# options.transfer_type = t
# end
#
# # Boolean switch.
# opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
# options.verbose = v
# end
#
# opts.separator ""
# opts.separator "Common options:"
#
# # No argument, shows at tail. This will print an options summary.
# # Try it and see!
# opts.on_tail("-h", "--help", "Show this message") do
# puts opts
# exit
# end
#
# # Another typical switch to print the version.
# opts.on_tail("--version", "Show version") do
# puts OptionParser::Version.join('.')
# exit
# end
# end
#
# opts.parse!(args)
# options
# end # parse()
#
# end # class OptparseExample
#
# options = OptparseExample.parse(ARGV)
# pp options
#
# === Further documentation
#
# The above examples should be enough to learn how to use this class. If you
# have any questions, email me (gsinclair@soyabean.com.au) and I will update
# this document.
#
class OptionParser
# :stopdoc:
RCSID = %w$Id: optparse.rb 23286 2009-04-26 06:13:11Z nobu $[1..-1].each {|s| s.freeze}.freeze
Version = (RCSID[1].split('.').collect {|s| s.to_i}.extend(Comparable).freeze if RCSID[1])
LastModified = (Time.gm(*RCSID[2, 2].join('-').scan(/\d+/).collect {|s| s.to_i}) if RCSID[2])
Release = RCSID[2]
NoArgument = [NO_ARGUMENT = :NONE, nil].freeze
RequiredArgument = [REQUIRED_ARGUMENT = :REQUIRED, true].freeze
OptionalArgument = [OPTIONAL_ARGUMENT = :OPTIONAL, false].freeze
# :startdoc:
#
# Keyword completion module. This allows partial arguments to be specified
# and resolved against a list of acceptable values.
#
module Completion
def complete(key, icase = false, pat = nil)
pat ||= Regexp.new('\A' + Regexp.quote(key).gsub(/\w+\b/, '\&\w*'),
icase)
canon, sw, cn = nil
candidates = []
each do |k, *v|
(if Regexp === k
kn = nil
k === key
else
kn = defined?(k.id2name) ? k.id2name : k
pat === kn
end) or next
v << k if v.empty?
candidates << [k, v, kn]
end
candidates = candidates.sort_by {|k, v, kn| kn.size}
if candidates.size == 1
canon, sw, * = candidates[0]
elsif candidates.size > 1
canon, sw, cn = candidates.shift
candidates.each do |k, v, kn|
next if sw == v
if String === cn and String === kn
if cn.rindex(kn, 0)
canon, sw, cn = k, v, kn
next
elsif kn.rindex(cn, 0)
next
end
end
throw :ambiguous, key
end
end
if canon
block_given? or return key, *sw
yield(key, *sw)
end
end
def convert(opt = nil, val = nil, *)
val
end
end
#
# Map from option/keyword string to object with completion.
#
class OptionMap < Hash
include Completion
end
#
# Individual switch class. Not important to the user.
#
# Defined within Switch are several Switch-derived classes: NoArgument,
# RequiredArgument, etc.
#
class Switch
attr_reader :pattern, :conv, :short, :long, :arg, :desc, :block
#
# Guesses argument style from +arg+. Returns corresponding
# OptionParser::Switch class (OptionalArgument, etc.).
#
def self.guess(arg)
case arg
when ""
t = self
when /\A=?\[/
t = Switch::OptionalArgument
when /\A\s+\[/
t = Switch::PlacedArgument
else
t = Switch::RequiredArgument
end
self >= t or incompatible_argument_styles(arg, t)
t
end
def self.incompatible_argument_styles(arg, t)
raise(ArgumentError, "#{arg}: incompatible argument styles\n #{self}, #{t}",
ParseError.filter_backtrace(caller(2)))
end
def self.pattern
NilClass
end
def initialize(pattern = nil, conv = nil,
short = nil, long = nil, arg = nil,
desc = ([] if short or long), block = Proc.new)
raise if Array === pattern
@pattern, @conv, @short, @long, @arg, @desc, @block =
pattern, conv, short, long, arg, desc, block
end
#
# Parses +arg+ and returns rest of +arg+ and matched portion to the
# argument pattern. Yields when the pattern doesn't match substring.
#
def parse_arg(arg)
pattern or return nil, [arg]
unless m = pattern.match(arg)
yield(InvalidArgument, arg)
return arg, []
end
if String === m
m = [s = m]
else
m = m.to_a
s = m[0]
return nil, m unless String === s
end
raise InvalidArgument, arg unless arg.rindex(s, 0)
return nil, m if s.length == arg.length
yield(InvalidArgument, arg) # didn't match whole arg
return arg[s.length..-1], m
end
private :parse_arg
#
# Parses argument, converts and returns +arg+, +block+ and result of
# conversion. Yields at semi-error condition instead of raising an
# exception.
#
def conv_arg(arg, val = [])
if conv
val = conv.call(*val)
else
val = proc {|v| v}.call(*val)
end
return arg, block, val
end
private :conv_arg
#
# Produces the summary text. Each line of the summary is yielded to the
# block (without newline).
#
# +sdone+:: Already summarized short style options keyed hash.
# +ldone+:: Already summarized long style options keyed hash.
# +width+:: Width of left side (option part). In other words, the right
# side (description part) starts after +width+ columns.
# +max+:: Maximum width of left side -> the options are filled within
# +max+ columns.
# +indent+:: Prefix string indents all summarized lines.
#
def summarize(sdone = [], ldone = [], width = 1, max = width - 1, indent = "")
sopts, lopts = [], [], nil
@short.each {|s| sdone.fetch(s) {sopts << s}; sdone[s] = true} if @short
@long.each {|s| ldone.fetch(s) {lopts << s}; ldone[s] = true} if @long
return if sopts.empty? and lopts.empty? # completely hidden
left = [sopts.join(', ')]
right = desc.dup
while s = lopts.shift
l = left[-1].length + s.length
l += arg.length if left.size == 1 && arg
l < max or sopts.empty? or left << ''
left[-1] << if left[-1].empty? then ' ' * 4 else ', ' end << s
end
if arg
left[0] << (left[1] ? arg.sub(/\A(\[?)=/, '\1') + ',' : arg)
end
mlen = left.collect {|ss| ss.length}.max.to_i
while mlen > width and l = left.shift
mlen = left.collect {|ss| ss.length}.max.to_i if l.length == mlen
if l.length < width and (r = right[0]) and !r.empty?
l = l.to_s.ljust(width) + ' ' + r
right.shift
end
yield(indent + l)
end
while begin l = left.shift; r = right.shift; l or r end
l = l.to_s.ljust(width) + ' ' + r if r and !r.empty?
yield(indent + l)
end
self
end
def add_banner(to) # :nodoc:
unless @short or @long
s = desc.join
to << " [" + s + "]..." unless s.empty?
end
to
end
def match_nonswitch?(str) # :nodoc:
@pattern =~ str unless @short or @long
end
#
# Main name of the switch.
#
def switch_name
(long.first || short.first).sub(/\A-+(?:\[no-\])?/, '')
end
#
# Switch that takes no arguments.
#
class NoArgument < self
#
# Raises an exception if any arguments given.
#
def parse(arg, argv)
yield(NeedlessArgument, arg) if arg
conv_arg(arg)
end
def self.incompatible_argument_styles(*)
end
def self.pattern
Object
end
end
#
# Switch that takes an argument.
#
class RequiredArgument < self
#
# Raises an exception if argument is not present.
#
def parse(arg, argv)
unless arg
raise MissingArgument if argv.empty?
arg = argv.shift
end
conv_arg(*parse_arg(arg, &method(:raise)))
end
end
#
# Switch that can omit argument.
#
class OptionalArgument < self
#
# Parses argument if given, or uses default value.
#
def parse(arg, argv, &error)
if arg
conv_arg(*parse_arg(arg, &error))
else
conv_arg(arg)
end
end
end
#
# Switch that takes an argument, which does not begin with '-'.
#
class PlacedArgument < self
#
# Returns nil if argument is not present or begins with '-'.
#
def parse(arg, argv, &error)
if !(val = arg) and (argv.empty? or /\A-/ =~ (val = argv[0]))
return nil, block, nil
end
opt = (val = parse_arg(val, &error))[1]
val = conv_arg(*val)
if opt and !arg
argv.shift
else
val[0] = nil
end
val
end
end
end
#
# Simple option list providing mapping from short and/or long option
# string to OptionParser::Switch and mapping from acceptable argument to
# matching pattern and converter pair. Also provides summary feature.
#
class List
# Map from acceptable argument types to pattern and converter pairs.
attr_reader :atype
# Map from short style option switches to actual switch objects.
attr_reader :short
# Map from long style option switches to actual switch objects.
attr_reader :long
# List of all switches and summary string.
attr_reader :list
#
# Just initializes all instance variables.
#
def initialize
@atype = {}
@short = OptionMap.new
@long = OptionMap.new
@list = []
end
#
# See OptionParser.accept.
#
def accept(t, pat = /.*/m, &block)
if pat
pat.respond_to?(:match) or
raise TypeError, "has no `match'", ParseError.filter_backtrace(caller(2))
else
pat = t if t.respond_to?(:match)
end
unless block
block = pat.method(:convert).to_proc if pat.respond_to?(:convert)
end
@atype[t] = [pat, block]
end
#
# See OptionParser.reject.
#
def reject(t)
@atype.delete(t)
end
#
# Adds +sw+ according to +sopts+, +lopts+ and +nlopts+.
#
# +sw+:: OptionParser::Switch instance to be added.
# +sopts+:: Short style option list.
# +lopts+:: Long style option list.
# +nlopts+:: Negated long style options list.
#
def update(sw, sopts, lopts, nsw = nil, nlopts = nil)
sopts.each {|o| @short[o] = sw} if sopts
lopts.each {|o| @long[o] = sw} if lopts
nlopts.each {|o| @long[o] = nsw} if nsw and nlopts
used = @short.invert.update(@long.invert)
@list.delete_if {|o| Switch === o and !used[o]}
end
private :update
#
# Inserts +switch+ at the head of the list, and associates short, long
# and negated long options. Arguments are:
#
# +switch+:: OptionParser::Switch instance to be inserted.
# +short_opts+:: List of short style options.
# +long_opts+:: List of long style options.
# +nolong_opts+:: List of long style options with "no-" prefix.
#
# prepend(switch, short_opts, long_opts, nolong_opts)
#
def prepend(*args)
update(*args)
@list.unshift(args[0])
end
#
# Appends +switch+ at the tail of the list, and associates short, long
# and negated long options. Arguments are:
#
# +switch+:: OptionParser::Switch instance to be inserted.
# +short_opts+:: List of short style options.
# +long_opts+:: List of long style options.
# +nolong_opts+:: List of long style options with "no-" prefix.
#
# append(switch, short_opts, long_opts, nolong_opts)
#
def append(*args)
update(*args)
@list.push(args[0])
end
#
# Searches +key+ in +id+ list. The result is returned or yielded if a
# block is given. If it isn't found, nil is returned.
#
def search(id, key)
if list = __send__(id)
val = list.fetch(key) {return nil}
block_given? ? yield(val) : val
end
end
#
# Searches list +id+ for +opt+ and the optional patterns for completion
# +pat+. If +icase+ is true, the search is case insensitive. The result
# is returned or yielded if a block is given. If it isn't found, nil is
# returned.
#
def complete(id, opt, icase = false, *pat, &block)
__send__(id).complete(opt, icase, *pat, &block)
end
#
# Iterates over each option, passing the option to the +block+.
#
def each_option(&block)
list.each(&block)
end
#
# Creates the summary table, passing each line to the +block+ (without
# newline). The arguments +args+ are passed along to the summarize
# method which is called on every option.
#
def summarize(*args, &block)
sum = []
list.reverse_each do |opt|
if opt.respond_to?(:summarize) # perhaps OptionParser::Switch
s = []
opt.summarize(*args) {|l| s << l}
sum.concat(s.reverse)
elsif !opt or opt.empty?
sum << ""
elsif opt.respond_to?(:each_line)
sum.concat([*opt.each_line].reverse)
else
sum.concat([*opt.each].reverse)
end
end
sum.reverse_each(&block)
end
def add_banner(to) # :nodoc:
list.each do |opt|
if opt.respond_to?(:add_banner)
opt.add_banner(to)
end
end
to
end
end
#
# Hash with completion search feature. See OptionParser::Completion.
#
class CompletingHash < Hash
include Completion
#
# Completion for hash key.
#
def match(key)
*values = fetch(key) {
raise AmbiguousArgument, catch(:ambiguous) {return complete(key)}
}
return key, *values
end
end
# :stopdoc:
#
# Enumeration of acceptable argument styles. Possible values are:
#
# NO_ARGUMENT:: The switch takes no arguments. (:NONE)
# REQUIRED_ARGUMENT:: The switch requires an argument. (:REQUIRED)
# OPTIONAL_ARGUMENT:: The switch requires an optional argument. (:OPTIONAL)
#
# Use like --switch=argument (long style) or -Xargument (short style). For
# short style, only portion matched to argument pattern is dealed as
# argument.
#
ArgumentStyle = {}
NoArgument.each {|el| ArgumentStyle[el] = Switch::NoArgument}
RequiredArgument.each {|el| ArgumentStyle[el] = Switch::RequiredArgument}
OptionalArgument.each {|el| ArgumentStyle[el] = Switch::OptionalArgument}
ArgumentStyle.freeze
#
# Switches common used such as '--', and also provides default
# argument classes
#
DefaultList = List.new
DefaultList.short['-'] = Switch::NoArgument.new {}
DefaultList.long[''] = Switch::NoArgument.new {throw :terminate}
#
# Default options for ARGV, which never appear in option summary.
#
Officious = {}
#
# --help
# Shows option summary.
#
Officious['help'] = proc do |parser|
Switch::NoArgument.new do
puts parser.help
exit
end
end
#
# --version
# Shows version string if Version is defined.
#
Officious['version'] = proc do |parser|
Switch::OptionalArgument.new do |pkg|
if pkg
begin
require 'optparse/version'
rescue LoadError
else
show_version(*pkg.split(/,/)) or
abort("#{parser.program_name}: no version found in package #{pkg}")
exit
end
end
v = parser.ver or abort("#{parser.program_name}: version unknown")
puts v
exit
end
end
# :startdoc:
#
# Class methods
#
#
# Initializes a new instance and evaluates the optional block in context
# of the instance. Arguments +args+ are passed to #new, see there for
# description of parameters.
#
# This method is *deprecated*, its behavior corresponds to the older #new
# method.
#
def self.with(*args, &block)
opts = new(*args)
opts.instance_eval(&block)
opts
end
#
# Returns an incremented value of +default+ according to +arg+.
#
def self.inc(arg, default = nil)
case arg
when Integer
arg.nonzero?
when nil
default.to_i + 1
end
end
def inc(*args)
self.class.inc(*args)
end
#
# Initializes the instance and yields itself if called with a block.
#
# +banner+:: Banner message.
# +width+:: Summary width.
# +indent+:: Summary indent.
#
def initialize(banner = nil, width = 32, indent = ' ' * 4)
@stack = [DefaultList, List.new, List.new]
@program_name = nil
@banner = banner
@summary_width = width
@summary_indent = indent
@default_argv = ARGV
add_officious
yield self if block_given?
end
def add_officious # :nodoc:
list = base()
Officious.each do |opt, block|
list.long[opt] ||= block.call(self)
end
end
#
# Terminates option parsing. Optional parameter +arg+ is a string pushed
# back to be the first non-option argument.
#
def terminate(arg = nil)
self.class.terminate(arg)
end
def self.terminate(arg = nil)
throw :terminate, arg
end
@stack = [DefaultList]
def self.top() DefaultList end
#
# Directs to accept specified class +t+. The argument string is passed to
# the block in which it should be converted to the desired class.
#
# +t+:: Argument class specifier, any object including Class.
# +pat+:: Pattern for argument, defaults to +t+ if it responds to match.
#
# accept(t, pat, &block)
#
def accept(*args, &blk) top.accept(*args, &blk) end
#
# See #accept.
#
def self.accept(*args, &blk) top.accept(*args, &blk) end
#
# Directs to reject specified class argument.
#
# +t+:: Argument class specifier, any object including Class.
#
# reject(t)
#
def reject(*args, &blk) top.reject(*args, &blk) end
#
# See #reject.
#
def self.reject(*args, &blk) top.reject(*args, &blk) end
#
# Instance methods
#
# Heading banner preceding summary.
attr_writer :banner
# Program name to be emitted in error message and default banner,
# defaults to $0.
attr_writer :program_name
# Width for option list portion of summary. Must be Numeric.
attr_accessor :summary_width
# Indentation for summary. Must be String (or have + String method).
attr_accessor :summary_indent
# Strings to be parsed in default.
attr_accessor :default_argv
#
# Heading banner preceding summary.
#
def banner
unless @banner
@banner = "Usage: #{program_name} [options]"
visit(:add_banner, @banner)
end
@banner
end
#
# Program name to be emitted in error message and default banner, defaults
# to $0.
#
def program_name
@program_name || File.basename($0, '.*')
end
# for experimental cascading :-)
alias set_banner banner=
alias set_program_name program_name=
alias set_summary_width summary_width=
alias set_summary_indent summary_indent=
# Version
attr_writer :version
# Release code
attr_writer :release
#
# Version
#
def version
@version || (defined?(::Version) && ::Version)
end
#
# Release code
#
def release
@release || (defined?(::Release) && ::Release) || (defined?(::RELEASE) && ::RELEASE)
end
#
# Returns version string from program_name, version and release.
#
def ver
if v = version
str = "#{program_name} #{[v].join('.')}"
str << " (#{v})" if v = release
str
end
end
def warn(mesg = $!)
super("#{program_name}: #{mesg}")
end
def abort(mesg = $!)
super("#{program_name}: #{mesg}")
end
#
# Subject of #on / #on_head, #accept / #reject
#
def top
@stack[-1]
end
#
# Subject of #on_tail.
#
def base
@stack[1]
end
#
# Pushes a new List.
#
def new
@stack.push(List.new)
if block_given?
yield self
else
self
end
end
#
# Removes the last List.
#
def remove
@stack.pop
end
#
# Puts option summary into +to+ and returns +to+. Yields each line if
# a block is given.
#
# +to+:: Output destination, which must have method <<. Defaults to [].
# +width+:: Width of left side, defaults to @summary_width.
# +max+:: Maximum length allowed for left side, defaults to +width+ - 1.
# +indent+:: Indentation, defaults to @summary_indent.
#
def summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk)
blk ||= proc {|l| to << (l.index($/, -1) ? l : l + $/)}
visit(:summarize, {}, {}, width, max, indent, &blk)
to
end
#
# Returns option summary string.
#
def help; summarize(banner.to_s.sub(/\n?\z/, "\n")) end
alias to_s help
#
# Returns option summary list.
#
def to_a; summarize(banner.to_a.dup) end
#
# Checks if an argument is given twice, in which case an ArgumentError is
# raised. Called from OptionParser#switch only.
#
# +obj+:: New argument.
# +prv+:: Previously specified argument.
# +msg+:: Exception message.
#
def notwice(obj, prv, msg)
unless !prv or prv == obj
raise(ArgumentError, "argument #{msg} given twice: #{obj}",
ParseError.filter_backtrace(caller(2)))
end
obj
end
private :notwice
SPLAT_PROC = proc {|*a| a.length <= 1 ? a.first : a}
#
# Creates an OptionParser::Switch from the parameters. The parsed argument
# value is passed to the given block, where it can be processed.
#
# See at the beginning of OptionParser for some full examples.
#
# +opts+ can include the following elements:
#
# [Argument style:]
# One of the following:
# :NONE, :REQUIRED, :OPTIONAL
#
# [Argument pattern:]
# Acceptable option argument format, must be pre-defined with
# OptionParser.accept or OptionParser#accept, or Regexp. This can appear
# once or assigned as String if not present, otherwise causes an
# ArgumentError. Examples:
# Float, Time, Array
#
# [Possible argument values:]
# Hash or Array.
# [:text, :binary, :auto]
# %w[iso-2022-jp shift_jis euc-jp utf8 binary]
# { "jis" => "iso-2022-jp", "sjis" => "shift_jis" }
#
# [Long style switch:]
# Specifies a long style switch which takes a mandatory, optional or no
# argument. It's a string of the following form:
# "--switch=MANDATORY" or "--switch MANDATORY"
# "--switch[=OPTIONAL]"
# "--switch"
#
# [Short style switch:]
# Specifies short style switch which takes a mandatory, optional or no
# argument. It's a string of the following form:
# "-xMANDATORY"
# "-x[OPTIONAL]"
# "-x"
# There is also a special form which matches character range (not full
# set of regular expression):
# "-[a-z]MANDATORY"
# "-[a-z][OPTIONAL]"
# "-[a-z]"
#
# [Argument style and description:]
# Instead of specifying mandatory or optional arguments directly in the
# switch parameter, this separate parameter can be used.
# "=MANDATORY"
# "=[OPTIONAL]"
#
# [Description:]
# Description string for the option.
# "Run verbosely"
#
# [Handler:]
# Handler for the parsed argument value. Either give a block or pass a
# Proc or Method as an argument.
#
def make_switch(opts, block = nil)
short, long, nolong, style, pattern, conv, not_pattern, not_conv, not_style = [], [], []
ldesc, sdesc, desc, arg = [], [], []
default_style = Switch::NoArgument
default_pattern = nil
klass = nil
n, q, a = nil
opts.each do |o|
# argument class
next if search(:atype, o) do |pat, c|
klass = notwice(o, klass, 'type')
if not_style and not_style != Switch::NoArgument
not_pattern, not_conv = pat, c
else
default_pattern, conv = pat, c
end
end
# directly specified pattern(any object possible to match)
if (!(String === o || Symbol === o)) and o.respond_to?(:match)
pattern = notwice(o, pattern, 'pattern')
if pattern.respond_to?(:convert)
conv = pattern.method(:convert).to_proc
else
conv = SPLAT_PROC
end
next
end
# anything others
case o
when Proc, Method
block = notwice(o, block, 'block')
when Array, Hash
case pattern
when CompletingHash
when nil
pattern = CompletingHash.new
conv = pattern.method(:convert).to_proc if pattern.respond_to?(:convert)
else
raise ArgumentError, "argument pattern given twice"
end
o.each {|pat, *v| pattern[pat] = v.fetch(0) {pat}}
when Module
raise ArgumentError, "unsupported argument type: #{o}", ParseError.filter_backtrace(caller(4))
when *ArgumentStyle.keys
style = notwice(ArgumentStyle[o], style, 'style')
when /^--no-([^\[\]=\s]*)(.+)?/
q, a = $1, $2
o = notwice(a ? Object : TrueClass, klass, 'type')
not_pattern, not_conv = search(:atype, o) unless not_style
not_style = (not_style || default_style).guess(arg = a) if a
default_style = Switch::NoArgument
default_pattern, conv = search(:atype, FalseClass) unless default_pattern
ldesc << "--no-#{q}"
long << 'no-' + (q = q.downcase)
nolong << q
when /^--\[no-\]([^\[\]=\s]*)(.+)?/
q, a = $1, $2
o = notwice(a ? Object : TrueClass, klass, 'type')
if a
default_style = default_style.guess(arg = a)
default_pattern, conv = search(:atype, o) unless default_pattern
end
ldesc << "--[no-]#{q}"
long << (o = q.downcase)
not_pattern, not_conv = search(:atype, FalseClass) unless not_style
not_style = Switch::NoArgument
nolong << 'no-' + o
when /^--([^\[\]=\s]*)(.+)?/
q, a = $1, $2
if a
o = notwice(NilClass, klass, 'type')
default_style = default_style.guess(arg = a)
default_pattern, conv = search(:atype, o) unless default_pattern
end
ldesc << "--#{q}"
long << (o = q.downcase)
when /^-(\[\^?\]?(?:[^\\\]]|\\.)*\])(.+)?/
q, a = $1, $2
o = notwice(Object, klass, 'type')
if a
default_style = default_style.guess(arg = a)
default_pattern, conv = search(:atype, o) unless default_pattern
end
sdesc << "-#{q}"
short << Regexp.new(q)
when /^-(.)(.+)?/
q, a = $1, $2
if a
o = notwice(NilClass, klass, 'type')
default_style = default_style.guess(arg = a)
default_pattern, conv = search(:atype, o) unless default_pattern
end
sdesc << "-#{q}"
short << q
when /^=/
style = notwice(default_style.guess(arg = o), style, 'style')
| 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/English.rb | tools/jruby-1.5.1/lib/ruby/1.9/English.rb | # Include the English library file in a Ruby script, and you can
# reference the global variables such as \VAR{\$\_} using less
# cryptic names, listed in the following table.% \vref{tab:english}.
#
# Without 'English':
#
# $\ = ' -- '
# "waterbuffalo" =~ /buff/
# print $", $', $$, "\n"
#
# With English:
#
# require "English"
#
# $OUTPUT_FIELD_SEPARATOR = ' -- '
# "waterbuffalo" =~ /buff/
# print $LOADED_FEATURES, $POSTMATCH, $PID, "\n"
# The exception object passed to +raise+.
alias $ERROR_INFO $!
# The stack backtrace generated by the last
# exception. <tt>See Kernel.caller</tt> for details. Thread local.
alias $ERROR_POSITION $@
# The default separator pattern used by <tt>String.split</tt>. May be
# set from the command line using the <tt>-F</tt> flag.
alias $FS $;
# The default separator pattern used by <tt>String.split</tt>. May be
# set from the command line using the <tt>-F</tt> flag.
alias $FIELD_SEPARATOR $;
# The separator string output between the parameters to methods such
# as <tt>Kernel.print</tt> and <tt>Array.join</tt>. Defaults to +nil+,
# which adds no text.
alias $OFS $,
# The separator string output between the parameters to methods such
# as <tt>Kernel.print</tt> and <tt>Array.join</tt>. Defaults to +nil+,
# which adds no text.
alias $OUTPUT_FIELD_SEPARATOR $,
# The input record separator (newline by default). This is the value
# that routines such as <tt>Kernel.gets</tt> use to determine record
# boundaries. If set to +nil+, +gets+ will read the entire file.
alias $RS $/
# The input record separator (newline by default). This is the value
# that routines such as <tt>Kernel.gets</tt> use to determine record
# boundaries. If set to +nil+, +gets+ will read the entire file.
alias $INPUT_RECORD_SEPARATOR $/
# The string appended to the output of every call to methods such as
# <tt>Kernel.print</tt> and <tt>IO.write</tt>. The default value is
# +nil+.
alias $ORS $\
# The string appended to the output of every call to methods such as
# <tt>Kernel.print</tt> and <tt>IO.write</tt>. The default value is
# +nil+.
alias $OUTPUT_RECORD_SEPARATOR $\
# The number of the last line read from the current input file.
alias $INPUT_LINE_NUMBER $.
# The number of the last line read from the current input file.
alias $NR $.
# The last line read by <tt>Kernel.gets</tt> or
# <tt>Kernel.readline</tt>. Many string-related functions in the
# +Kernel+ module operate on <tt>$_</tt> by default. The variable is
# local to the current scope. Thread local.
alias $LAST_READ_LINE $_
# The destination of output for <tt>Kernel.print</tt>
# and <tt>Kernel.printf</tt>. The default value is
# <tt>$stdout</tt>.
alias $DEFAULT_OUTPUT $>
# An object that provides access to the concatenation
# of the contents of all the files
# given as command-line arguments, or <tt>$stdin</tt>
# (in the case where there are no
# arguments). <tt>$<</tt> supports methods similar to a
# +File+ object:
# +inmode+, +close+,
# <tt>closed?</tt>, +each+,
# <tt>each_byte</tt>, <tt>each_line</tt>,
# +eof+, <tt>eof?</tt>, +file+,
# +filename+, +fileno+,
# +getc+, +gets+, +lineno+,
# <tt>lineno=</tt>, +path+,
# +pos+, <tt>pos=</tt>,
# +read+, +readchar+,
# +readline+, +readlines+,
# +rewind+, +seek+, +skip+,
# +tell+, <tt>to_a</tt>, <tt>to_i</tt>,
# <tt>to_io</tt>, <tt>to_s</tt>, along with the
# methods in +Enumerable+. The method +file+
# returns a +File+ object for the file currently
# being read. This may change as <tt>$<</tt> reads
# through the files on the command line. Read only.
alias $DEFAULT_INPUT $<
# The process number of the program being executed. Read only.
alias $PID $$
# The process number of the program being executed. Read only.
alias $PROCESS_ID $$
# The exit status of the last child process to terminate. Read
# only. Thread local.
alias $CHILD_STATUS $?
# A +MatchData+ object that encapsulates the results of a successful
# pattern match. The variables <tt>$&</tt>, <tt>$`</tt>, <tt>$'</tt>,
# and <tt>$1</tt> to <tt>$9</tt> are all derived from
# <tt>$~</tt>. Assigning to <tt>$~</tt> changes the values of these
# derived variables. This variable is local to the current
# scope. Thread local.
alias $LAST_MATCH_INFO $~
# If set to any value apart from +nil+ or +false+, all pattern matches
# will be case insensitive, string comparisons will ignore case, and
# string hash values will be case insensitive. Deprecated
alias $IGNORECASE $=
# An array of strings containing the command-line
# options from the invocation of the program. Options
# used by the Ruby interpreter will have been
# removed. Read only. Also known simply as +ARGV+.
alias $ARGV $*
# The string matched by the last successful pattern
# match. This variable is local to the current
# scope. Read only. Thread local.
alias $MATCH $&
# The string preceding the match in the last
# successful pattern match. This variable is local to
# the current scope. Read only. Thread local.
alias $PREMATCH $`
# The string following the match in the last
# successful pattern match. This variable is local to
# the current scope. Read only. Thread local.
alias $POSTMATCH $'
# The contents of the highest-numbered group matched in the last
# successful pattern match. Thus, in <tt>"cat" =~ /(c|a)(t|z)/</tt>,
# <tt>$+</tt> will be set to "t". This variable is local to the
# current scope. Read only. Thread local.
alias $LAST_PAREN_MATCH $+
| 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/logger.rb | tools/jruby-1.5.1/lib/ruby/1.9/logger.rb | # logger.rb - simple logging utility
# Copyright (C) 2000-2003, 2005 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>.
require 'monitor'
# = logger.rb
#
# Simple logging utility.
#
# Author:: NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>
# Documentation:: NAKAMURA, Hiroshi and Gavin Sinclair
# License::
# You can redistribute it and/or modify it under the same terms of Ruby's
# license; either the dual license version in 2003, or any later version.
# Revision:: $Id: logger.rb 20290 2008-11-19 22:35:40Z matz $
#
# See Logger for documentation.
#
#
# == Description
#
# The Logger class provides a simple but sophisticated logging utility that
# anyone can use because it's included in the Ruby 1.8.x standard library.
#
# The HOWTOs below give a code-based overview of Logger's usage, but the basic
# concept is as follows. You create a Logger object (output to a file or
# elsewhere), and use it to log messages. The messages will have varying
# levels (+info+, +error+, etc), reflecting their varying importance. The
# levels, and their meanings, are:
#
# +FATAL+:: an unhandleable error that results in a program crash
# +ERROR+:: a handleable error condition
# +WARN+:: a warning
# +INFO+:: generic (useful) information about system operation
# +DEBUG+:: low-level information for developers
#
# So each message has a level, and the Logger itself has a level, which acts
# as a filter, so you can control the amount of information emitted from the
# logger without having to remove actual messages.
#
# For instance, in a production system, you may have your logger(s) set to
# +INFO+ (or +WARN+ if you don't want the log files growing large with
# repetitive information). When you are developing it, though, you probably
# want to know about the program's internal state, and would set them to
# +DEBUG+.
#
# === Example
#
# A simple example demonstrates the above explanation:
#
# log = Logger.new(STDOUT)
# log.level = Logger::WARN
#
# log.debug("Created logger")
# log.info("Program started")
# log.warn("Nothing to do!")
#
# begin
# File.each_line(path) do |line|
# unless line =~ /^(\w+) = (.*)$/
# log.error("Line in wrong format: #{line}")
# end
# end
# rescue => err
# log.fatal("Caught exception; exiting")
# log.fatal(err)
# end
#
# Because the Logger's level is set to +WARN+, only the warning, error, and
# fatal messages are recorded. The debug and info messages are silently
# discarded.
#
# === Features
#
# There are several interesting features that Logger provides, like
# auto-rolling of log files, setting the format of log messages, and
# specifying a program name in conjunction with the message. The next section
# shows you how to achieve these things.
#
#
# == HOWTOs
#
# === How to create a logger
#
# The options below give you various choices, in more or less increasing
# complexity.
#
# 1. Create a logger which logs messages to STDERR/STDOUT.
#
# logger = Logger.new(STDERR)
# logger = Logger.new(STDOUT)
#
# 2. Create a logger for the file which has the specified name.
#
# logger = Logger.new('logfile.log')
#
# 3. Create a logger for the specified file.
#
# file = File.open('foo.log', File::WRONLY | File::APPEND)
# # To create new (and to remove old) logfile, add File::CREAT like;
# # file = open('foo.log', File::WRONLY | File::APPEND | File::CREAT)
# logger = Logger.new(file)
#
# 4. Create a logger which ages logfile once it reaches a certain size. Leave
# 10 "old log files" and each file is about 1,024,000 bytes.
#
# logger = Logger.new('foo.log', 10, 1024000)
#
# 5. Create a logger which ages logfile daily/weekly/monthly.
#
# logger = Logger.new('foo.log', 'daily')
# logger = Logger.new('foo.log', 'weekly')
# logger = Logger.new('foo.log', 'monthly')
#
# === How to log a message
#
# Notice the different methods (+fatal+, +error+, +info+) being used to log
# messages of various levels. Other methods in this family are +warn+ and
# +debug+. +add+ is used below to log a message of an arbitrary (perhaps
# dynamic) level.
#
# 1. Message in block.
#
# logger.fatal { "Argument 'foo' not given." }
#
# 2. Message as a string.
#
# logger.error "Argument #{ @foo } mismatch."
#
# 3. With progname.
#
# logger.info('initialize') { "Initializing..." }
#
# 4. With severity.
#
# logger.add(Logger::FATAL) { 'Fatal error!' }
#
# === How to close a logger
#
# logger.close
#
# === Setting severity threshold
#
# 1. Original interface.
#
# logger.sev_threshold = Logger::WARN
#
# 2. Log4r (somewhat) compatible interface.
#
# logger.level = Logger::INFO
#
# DEBUG < INFO < WARN < ERROR < FATAL < UNKNOWN
#
#
# == Format
#
# Log messages are rendered in the output stream in a certain format by
# default. The default format and a sample are shown below:
#
# Log format:
# SeverityID, [Date Time mSec #pid] SeverityLabel -- ProgName: message
#
# Log sample:
# I, [Wed Mar 03 02:34:24 JST 1999 895701 #19074] INFO -- Main: info.
#
# You may change the date and time format in this manner:
#
# logger.datetime_format = "%Y-%m-%d %H:%M:%S"
# # e.g. "2004-01-03 00:54:26"
#
# You may change the overall format with Logger#formatter= method.
#
# logger.formatter = proc { |severity, datetime, progname, msg|
# "#{datetime}: #{msg}\n"
# }
# # e.g. "Thu Sep 22 08:51:08 GMT+9:00 2005: hello world"
#
class Logger
VERSION = "1.2.6"
id, name, rev = %w$Id: logger.rb 20290 2008-11-19 22:35:40Z matz $
if name
name = name.chomp(",v")
else
name = File.basename(__FILE__)
end
rev ||= "v#{VERSION}"
ProgName = "#{name}/#{rev}"
class Error < RuntimeError; end
class ShiftingError < Error; end
# Logging severity.
module Severity
DEBUG = 0
INFO = 1
WARN = 2
ERROR = 3
FATAL = 4
UNKNOWN = 5
end
include Severity
# Logging severity threshold (e.g. <tt>Logger::INFO</tt>).
attr_accessor :level
# Logging program name.
attr_accessor :progname
# Logging date-time format (string passed to +strftime+).
def datetime_format=(datetime_format)
@default_formatter.datetime_format = datetime_format
end
def datetime_format
@default_formatter.datetime_format
end
# Logging formatter. formatter#call is invoked with 4 arguments; severity,
# time, progname and msg for each log. Bear in mind that time is a Time and
# msg is an Object that user passed and it could not be a String. It is
# expected to return a logdev#write-able Object. Default formatter is used
# when no formatter is set.
attr_accessor :formatter
alias sev_threshold level
alias sev_threshold= level=
# Returns +true+ iff the current severity level allows for the printing of
# +DEBUG+ messages.
def debug?; @level <= DEBUG; end
# Returns +true+ iff the current severity level allows for the printing of
# +INFO+ messages.
def info?; @level <= INFO; end
# Returns +true+ iff the current severity level allows for the printing of
# +WARN+ messages.
def warn?; @level <= WARN; end
# Returns +true+ iff the current severity level allows for the printing of
# +ERROR+ messages.
def error?; @level <= ERROR; end
# Returns +true+ iff the current severity level allows for the printing of
# +FATAL+ messages.
def fatal?; @level <= FATAL; end
#
# === Synopsis
#
# Logger.new(name, shift_age = 7, shift_size = 1048576)
# Logger.new(name, shift_age = 'weekly')
#
# === Args
#
# +logdev+::
# The log device. This is a filename (String) or IO object (typically
# +STDOUT+, +STDERR+, or an open file).
# +shift_age+::
# Number of old log files to keep, *or* frequency of rotation (+daily+,
# +weekly+ or +monthly+).
# +shift_size+::
# Maximum logfile size (only applies when +shift_age+ is a number).
#
# === Description
#
# Create an instance.
#
def initialize(logdev, shift_age = 0, shift_size = 1048576)
@progname = nil
@level = DEBUG
@default_formatter = Formatter.new
@formatter = nil
@logdev = nil
if logdev
@logdev = LogDevice.new(logdev, :shift_age => shift_age,
:shift_size => shift_size)
end
end
#
# === Synopsis
#
# Logger#add(severity, message = nil, progname = nil) { ... }
#
# === Args
#
# +severity+::
# Severity. Constants are defined in Logger namespace: +DEBUG+, +INFO+,
# +WARN+, +ERROR+, +FATAL+, or +UNKNOWN+.
# +message+::
# The log message. A String or Exception.
# +progname+::
# Program name string. Can be omitted. Treated as a message if no +message+ and
# +block+ are given.
# +block+::
# Can be omitted. Called to get a message string if +message+ is nil.
#
# === Return
#
# +true+ if successful, +false+ otherwise.
#
# When the given severity is not high enough (for this particular logger), log
# no message, and return +true+.
#
# === Description
#
# Log a message if the given severity is high enough. This is the generic
# logging method. Users will be more inclined to use #debug, #info, #warn,
# #error, and #fatal.
#
# <b>Message format</b>: +message+ can be any object, but it has to be
# converted to a String in order to log it. Generally, +inspect+ is used
# if the given object is not a String.
# A special case is an +Exception+ object, which will be printed in detail,
# including message, class, and backtrace. See #msg2str for the
# implementation if required.
#
# === Bugs
#
# * Logfile is not locked.
# * Append open does not need to lock file.
# * But on the OS which supports multi I/O, records possibly be mixed.
#
def add(severity, message = nil, progname = nil, &block)
severity ||= UNKNOWN
if @logdev.nil? or severity < @level
return true
end
progname ||= @progname
if message.nil?
if block_given?
message = yield
else
message = progname
progname = @progname
end
end
@logdev.write(
format_message(format_severity(severity), Time.now, progname, message))
true
end
alias log add
#
# Dump given message to the log device without any formatting. If no log
# device exists, return +nil+.
#
def <<(msg)
unless @logdev.nil?
@logdev.write(msg)
end
end
#
# Log a +DEBUG+ message.
#
# See #info for more information.
#
def debug(progname = nil, &block)
add(DEBUG, nil, progname, &block)
end
#
# Log an +INFO+ message.
#
# The message can come either from the +progname+ argument or the +block+. If
# both are provided, then the +block+ is used as the message, and +progname+
# is used as the program name.
#
# === Examples
#
# logger.info("MainApp") { "Received connection from #{ip}" }
# # ...
# logger.info "Waiting for input from user"
# # ...
# logger.info { "User typed #{input}" }
#
# You'll probably stick to the second form above, unless you want to provide a
# program name (which you can do with <tt>Logger#progname=</tt> as well).
#
# === Return
#
# See #add.
#
def info(progname = nil, &block)
add(INFO, nil, progname, &block)
end
#
# Log a +WARN+ message.
#
# See #info for more information.
#
def warn(progname = nil, &block)
add(WARN, nil, progname, &block)
end
#
# Log an +ERROR+ message.
#
# See #info for more information.
#
def error(progname = nil, &block)
add(ERROR, nil, progname, &block)
end
#
# Log a +FATAL+ message.
#
# See #info for more information.
#
def fatal(progname = nil, &block)
add(FATAL, nil, progname, &block)
end
#
# Log an +UNKNOWN+ message. This will be printed no matter what the logger
# level.
#
# See #info for more information.
#
def unknown(progname = nil, &block)
add(UNKNOWN, nil, progname, &block)
end
#
# Close the logging device.
#
def close
@logdev.close if @logdev
end
private
# Severity label for logging. (max 5 char)
SEV_LABEL = %w(DEBUG INFO WARN ERROR FATAL ANY)
def format_severity(severity)
SEV_LABEL[severity] || 'ANY'
end
def format_message(severity, datetime, progname, msg)
(@formatter || @default_formatter).call(severity, datetime, progname, msg)
end
class Formatter
Format = "%s, [%s#%d] %5s -- %s: %s\n"
attr_accessor :datetime_format
def initialize
@datetime_format = nil
end
def call(severity, time, progname, msg)
Format % [severity[0..0], format_datetime(time), $$, severity, progname,
msg2str(msg)]
end
private
def format_datetime(time)
if @datetime_format.nil?
time.strftime("%Y-%m-%dT%H:%M:%S.") << "%06d " % time.usec
else
time.strftime(@datetime_format)
end
end
def msg2str(msg)
case msg
when ::String
msg
when ::Exception
"#{ msg.message } (#{ msg.class })\n" <<
(msg.backtrace || []).join("\n")
else
msg.inspect
end
end
end
class LogDevice
attr_reader :dev
attr_reader :filename
class LogDeviceMutex
include MonitorMixin
end
def initialize(log = nil, opt = {})
@dev = @filename = @shift_age = @shift_size = nil
@mutex = LogDeviceMutex.new
if log.respond_to?(:write) and log.respond_to?(:close)
@dev = log
else
@dev = open_logfile(log)
@dev.sync = true
@filename = log
@shift_age = opt[:shift_age] || 7
@shift_size = opt[:shift_size] || 1048576
end
end
def write(message)
@mutex.synchronize do
if @shift_age and @dev.respond_to?(:stat)
begin
check_shift_log
rescue
raise Logger::ShiftingError.new("Shifting failed. #{$!}")
end
end
@dev.write(message)
end
end
def close
@mutex.synchronize do
@dev.close
end
end
private
def open_logfile(filename)
if (FileTest.exist?(filename))
open(filename, (File::WRONLY | File::APPEND))
else
create_logfile(filename)
end
end
def create_logfile(filename)
logdev = open(filename, (File::WRONLY | File::APPEND | File::CREAT))
logdev.sync = true
add_log_header(logdev)
logdev
end
def add_log_header(file)
file.write(
"# Logfile created on %s by %s\n" % [Time.now.to_s, Logger::ProgName]
)
end
SiD = 24 * 60 * 60
def check_shift_log
if @shift_age.is_a?(Integer)
# Note: always returns false if '0'.
if @filename && (@shift_age > 0) && (@dev.stat.size > @shift_size)
shift_log_age
end
else
now = Time.now
if @dev.stat.mtime <= previous_period_end(now)
shift_log_period(now)
end
end
end
def shift_log_age
(@shift_age-3).downto(0) do |i|
if FileTest.exist?("#{@filename}.#{i}")
File.rename("#{@filename}.#{i}", "#{@filename}.#{i+1}")
end
end
@dev.close
File.rename("#{@filename}", "#{@filename}.0")
@dev = create_logfile(@filename)
return true
end
def shift_log_period(now)
postfix = previous_period_end(now).strftime("%Y%m%d") # YYYYMMDD
age_file = "#{@filename}.#{postfix}"
if FileTest.exist?(age_file)
raise RuntimeError.new("'#{ age_file }' already exists.")
end
@dev.close
File.rename("#{@filename}", age_file)
@dev = create_logfile(@filename)
return true
end
def previous_period_end(now)
case @shift_age
when /^daily$/
eod(now - 1 * SiD)
when /^weekly$/
eod(now - ((now.wday + 1) * SiD))
when /^monthly$/
eod(now - now.mday * SiD)
else
now
end
end
def eod(t)
Time.mktime(t.year, t.month, t.mday, 23, 59, 59)
end
end
#
# == Description
#
# Application -- Add logging support to your application.
#
# == Usage
#
# 1. Define your application class as a sub-class of this class.
# 2. Override 'run' method in your class to do many things.
# 3. Instantiate it and invoke 'start'.
#
# == Example
#
# class FooApp < Application
# def initialize(foo_app, application_specific, arguments)
# super('FooApp') # Name of the application.
# end
#
# def run
# ...
# log(WARN, 'warning', 'my_method1')
# ...
# @log.error('my_method2') { 'Error!' }
# ...
# end
# end
#
# status = FooApp.new(....).start
#
class Application
include Logger::Severity
# Name of the application given at initialize.
attr_reader :appname
#
# == Synopsis
#
# Application.new(appname = '')
#
# == Args
#
# +appname+:: Name of the application.
#
# == Description
#
# Create an instance. Log device is +STDERR+ by default. This can be
# changed with #set_log.
#
def initialize(appname = nil)
@appname = appname
@log = Logger.new(STDERR)
@log.progname = @appname
@level = @log.level
end
#
# Start the application. Return the status code.
#
def start
status = -1
begin
log(INFO, "Start of #{ @appname }.")
status = run
rescue
log(FATAL, "Detected an exception. Stopping ... #{$!} (#{$!.class})\n" << $@.join("\n"))
ensure
log(INFO, "End of #{ @appname }. (status: #{ status.to_s })")
end
status
end
# Logger for this application. See the class Logger for an explanation.
def logger
@log
end
#
# Sets the logger for this application. See the class Logger for an explanation.
#
def logger=(logger)
@log = logger
end
#
# Sets the log device for this application. See <tt>Logger.new</tt> for an explanation
# of the arguments.
#
def set_log(logdev, shift_age = 0, shift_size = 1024000)
@log = Logger.new(logdev, shift_age, shift_size)
@log.progname = @appname
@log.level = @level
end
def log=(logdev)
set_log(logdev)
end
#
# Set the logging threshold, just like <tt>Logger#level=</tt>.
#
def level=(level)
@level = level
@log.level = @level
end
#
# See Logger#add. This application's +appname+ is used.
#
def log(severity, message = nil, &block)
@log.add(severity, message, @appname, &block) if @log
end
private
def run
raise RuntimeError.new('Method run must be defined in the derived class.')
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/mathn.rb | tools/jruby-1.5.1/lib/ruby/1.9/mathn.rb | #
# mathn.rb -
# $Release Version: 0.5 $
# $Revision: 1.1.1.1.4.1 $
# by Keiju ISHITSUKA(SHL Japan Inc.)
#
# --
#
#
#
require "cmath.rb"
require "matrix.rb"
require "prime.rb"
require "mathn/rational"
require "mathn/complex"
unless defined?(Math.exp!)
Object.instance_eval{remove_const :Math}
Math = CMath
end
class Fixnum
remove_method :/
alias / quo
alias power! ** unless method_defined? :power!
def ** (other)
if self < 0 && other.round != other
Complex(self, 0.0) ** other
else
power!(other)
end
end
end
class Bignum
remove_method :/
alias / quo
alias power! ** unless method_defined? :power!
def ** (other)
if self < 0 && other.round != other
Complex(self, 0.0) ** other
else
power!(other)
end
end
end
class Rational
def ** (other)
if other.kind_of?(Rational)
other2 = other
if self < 0
return Complex(self, 0.0) ** other
elsif other == 0
return Rational(1,1)
elsif self == 0
return Rational(0,1)
elsif self == 1
return Rational(1,1)
end
npd = numerator.prime_division
dpd = denominator.prime_division
if other < 0
other = -other
npd, dpd = dpd, npd
end
for elm in npd
elm[1] = elm[1] * other
if !elm[1].kind_of?(Integer) and elm[1].denominator != 1
return Float(self) ** other2
end
elm[1] = elm[1].to_i
end
for elm in dpd
elm[1] = elm[1] * other
if !elm[1].kind_of?(Integer) and elm[1].denominator != 1
return Float(self) ** other2
end
elm[1] = elm[1].to_i
end
num = Integer.from_prime_division(npd)
den = Integer.from_prime_division(dpd)
Rational(num,den)
elsif other.kind_of?(Integer)
if other > 0
num = numerator ** other
den = denominator ** other
elsif other < 0
num = denominator ** -other
den = numerator ** -other
elsif other == 0
num = 1
den = 1
end
Rational(num, den)
elsif other.kind_of?(Float)
Float(self) ** other
else
x , y = other.coerce(self)
x ** y
end
end
end
module Math
remove_method(:sqrt)
def sqrt(a)
if a.kind_of?(Complex)
abs = sqrt(a.real*a.real + a.imag*a.imag)
# if not abs.kind_of?(Rational)
# return a**Rational(1,2)
# end
x = sqrt((a.real + abs)/Rational(2))
y = sqrt((-a.real + abs)/Rational(2))
# if !(x.kind_of?(Rational) and y.kind_of?(Rational))
# return a**Rational(1,2)
# end
if a.imag >= 0
Complex(x, y)
else
Complex(x, -y)
end
elsif a.respond_to?(:nan?) and a.nan?
a
elsif a >= 0
rsqrt(a)
else
Complex(0,rsqrt(-a))
end
end
def rsqrt(a)
if a.kind_of?(Float)
sqrt!(a)
elsif a.kind_of?(Rational)
rsqrt(a.numerator)/rsqrt(a.denominator)
else
src = a
max = 2 ** 32
byte_a = [src & 0xffffffff]
# ruby's bug
while (src >= max) and (src >>= 32)
byte_a.unshift src & 0xffffffff
end
answer = 0
main = 0
side = 0
for elm in byte_a
main = (main << 32) + elm
side <<= 16
if answer != 0
if main * 4 < side * side
applo = main.div(side)
else
applo = ((sqrt!(side * side + 4 * main) - side)/2.0).to_i + 1
end
else
applo = sqrt!(main).to_i + 1
end
while (x = (side + applo) * applo) > main
applo -= 1
end
main -= x
answer = (answer << 16) + applo
side += applo * 2
end
if main == 0
answer
else
sqrt!(a)
end
end
end
module_function :sqrt
module_function :rsqrt
end
class Float
alias power! **
def ** (other)
if self < 0 && other.round != other
Complex(self, 0.0) ** other
else
power!(other)
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/Win32API.rb | tools/jruby-1.5.1/lib/ruby/1.9/Win32API.rb | require 'rbconfig'
raise LoadError.new("Win32API only supported on win32") unless Config::CONFIG['host_os'] =~ /mswin/
require 'ffi-internal.so'
class Win32API
SUFFIXES = $KCODE == 'UTF8' ? [ '', 'W', 'A' ] : [ '', 'A', 'W' ]
TypeDefs = {
'0' => FFI::Type::VOID,
'V' => FFI::Type::VOID,
'P' => FFI::Type::WIN32PTR,
'I' => FFI::Type::INT,
'N' => FFI::Type::INT,
'L' => FFI::Type::INT,
}
def self.find_type(name)
code = TypeDefs[name] || TypeDefs[name.upcase]
raise TypeError, "Unable to resolve type '#{name}'" unless code
return code
end
def self.map_types(spec)
if spec.kind_of?(String)
spec.split(//)
elsif spec.kind_of?(Array)
spec
else
raise ArgumentError.new("invalid parameter types specification")
end.map { |c| self.find_type(c) }
end
def self.map_library_name(lib)
# Mangle the library name to reflect the native library naming conventions
if lib && File.basename(lib) == lib
ext = ".#{FFI::Platform::LIBSUFFIX}"
lib = FFI::Platform::LIBPREFIX + lib unless lib =~ /^#{FFI::Platform::LIBPREFIX}/
lib += ext unless lib =~ /#{ext}/
end
lib
end
def initialize(lib, func, params, ret='L', calltype = :stdcall)
@lib = lib
@func = func
@params = params
@return = ret
#
# Attach the method as 'call', so it gets all the froody arity-splitting optimizations
#
@lib = FFI::DynamicLibrary.open(Win32API.map_library_name(lib), FFI::DynamicLibrary::RTLD_LAZY | FFI::DynamicLibrary::RTLD_GLOBAL)
SUFFIXES.each do |suffix|
sym = @lib.find_function(func.to_s + suffix)
if sym
options = { :convention => calltype }
@ffi_func = FFI::Function.new(Win32API.find_type(ret), Win32API.map_types(params), sym, options)
@ffi_func.attach(self, :call)
self.instance_eval("alias :Call :call")
break
end
end
raise LoadError.new("Could not locate #{func}") unless @ffi_func
end
def inspect
params = []
if @params.kind_of?(String)
@params.each_byte { |c| params << TypeDefs[c.chr] }
else
params = @params.map { |p| TypeDefs[p]}
end
"#<Win32API::#{@func} library=#{@lib} function=#{@func} parameters=[ #{params.join(',')} ], return=#{Win32API.find_type(@return)}>"
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/thwait.rb | tools/jruby-1.5.1/lib/ruby/1.9/thwait.rb | #
# thwait.rb - thread synchronization class
# $Release Version: 0.9 $
# $Revision: 1.3 $
# by Keiju ISHITSUKA(Nihpon Rational Software Co.,Ltd.)
#
# --
# feature:
# provides synchronization for multiple threads.
#
# class methods:
# * ThreadsWait.all_waits(thread1,...)
# waits until all of specified threads are terminated.
# if a block is supplied for the method, evaluates it for
# each thread termination.
# * th = ThreadsWait.new(thread1,...)
# creates synchronization object, specifying thread(s) to wait.
#
# methods:
# * th.threads
# list threads to be synchronized
# * th.empty?
# is there any thread to be synchronized.
# * th.finished?
# is there already terminated thread.
# * th.join(thread1,...)
# wait for specified thread(s).
# * th.join_nowait(threa1,...)
# specifies thread(s) to wait. non-blocking.
# * th.next_wait
# waits until any of specified threads is terminated.
# * th.all_waits
# waits until all of specified threads are terminated.
# if a block is supplied for the method, evaluates it for
# each thread termination.
#
require "thread.rb"
require "e2mmap.rb"
#
# This class watches for termination of multiple threads. Basic functionality
# (wait until specified threads have terminated) can be accessed through the
# class method ThreadsWait::all_waits. Finer control can be gained using
# instance methods.
#
# Example:
#
# ThreadsWait.all_wait(thr1, thr2, ...) do |t|
# STDERR.puts "Thread #{t} has terminated."
# end
#
class ThreadsWait
RCS_ID='-$Id: thwait.rb,v 1.3 1998/06/26 03:19:34 keiju Exp keiju $-'
extend Exception2MessageMapper
def_exception("ErrNoWaitingThread", "No threads for waiting.")
def_exception("ErrNoFinishedThread", "No finished threads.")
#
# Waits until all specified threads have terminated. If a block is provided,
# it is executed for each thread termination.
#
def ThreadsWait.all_waits(*threads) # :yield: thread
tw = ThreadsWait.new(*threads)
if block_given?
tw.all_waits do |th|
yield th
end
else
tw.all_waits
end
end
#
# Creates a ThreadsWait object, specifying the threads to wait on.
# Non-blocking.
#
def initialize(*threads)
@threads = []
@wait_queue = Queue.new
join_nowait(*threads) unless threads.empty?
end
# Returns the array of threads in the wait queue.
attr :threads
#
# Returns +true+ if there are no threads to be synchronized.
#
def empty?
@threads.empty?
end
#
# Returns +true+ if any thread has terminated.
#
def finished?
!@wait_queue.empty?
end
#
# Waits for specified threads to terminate.
#
def join(*threads)
join_nowait(*threads)
next_wait
end
#
# Specifies the threads that this object will wait for, but does not actually
# wait.
#
def join_nowait(*threads)
threads.flatten!
@threads.concat threads
for th in threads
Thread.start(th) do |t|
begin
t.join
ensure
@wait_queue.push t
end
end
end
end
#
# Waits until any of the specified threads has terminated, and returns the one
# that does.
#
# If there is no thread to wait, raises +ErrNoWaitingThread+. If +nonblock+
# is true, and there is no terminated thread, raises +ErrNoFinishedThread+.
#
def next_wait(nonblock = nil)
ThreadsWait.fail ErrNoWaitingThread if @threads.empty?
begin
@threads.delete(th = @wait_queue.pop(nonblock))
th
rescue ThreadError
ThreadsWait.fail ErrNoFinishedThread
end
end
#
# Waits until all of the specified threads are terminated. If a block is
# supplied for the method, it is executed for each thread termination.
#
# Raises exceptions in the same manner as +next_wait+.
#
def all_waits
until @threads.empty?
th = next_wait
yield th if block_given?
end
end
end
ThWait = ThreadsWait
# Documentation comments:
# - Source of documentation is evenly split between Nutshell, existing
# comments, and my own rephrasing.
# - I'm not particularly confident that the comments are all exactly correct.
# - The history, etc., up the top appears in the RDoc output. Perhaps it would
# be better to direct that not to appear, and put something else there
# instead.
| 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/profiler.rb | tools/jruby-1.5.1/lib/ruby/1.9/profiler.rb | module Profiler__
# internal values
@@start = @@stack = @@map = nil
PROFILE_PROC = proc{|event, file, line, id, binding, klass|
case event
when "call", "c-call"
now = Process.times[0]
@@stack.push [now, 0.0]
when "return", "c-return"
now = Process.times[0]
key = [klass, id]
if tick = @@stack.pop
data = (@@map[key] ||= [0, 0.0, 0.0, key])
data[0] += 1
cost = now - tick[0]
data[1] += cost
data[2] += cost - tick[1]
@@stack[-1][1] += cost if @@stack[-1]
end
end
}
module_function
def start_profile
@@start = Process.times[0]
@@stack = []
@@map = {}
set_trace_func PROFILE_PROC
end
def stop_profile
set_trace_func nil
end
def print_profile(f)
stop_profile
total = Process.times[0] - @@start
if total == 0 then total = 0.01 end
data = @@map.values
data = data.sort_by{|x| -x[2]}
sum = 0
f.printf " %% cumulative self self total\n"
f.printf " time seconds seconds calls ms/call ms/call name\n"
for d in data
sum += d[2]
f.printf "%6.2f %8.2f %8.2f %8d ", d[2]/total*100, sum, d[2], d[0]
f.printf "%8.2f %8.2f %s\n", d[2]*1000/d[0], d[1]*1000/d[0], get_name(*d[3])
end
f.printf "%6.2f %8.2f %8.2f %8d ", 0.0, total, 0.0, 1 # ???
f.printf "%8.2f %8.2f %s\n", 0.0, total*1000, "#toplevel" # ???
end
def get_name(klass, id)
name = klass.to_s || ""
if klass.kind_of? Class
name += "#"
else
name += "."
end
name + id.id2name
end
private :get_name
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/resolv.rb | tools/jruby-1.5.1/lib/ruby/1.9/resolv.rb | require 'socket'
require 'fcntl'
require 'timeout'
require 'thread'
begin
require 'securerandom'
rescue LoadError
end
# Resolv is a thread-aware DNS resolver library written in Ruby. Resolv can
# handle multiple DNS requests concurrently without blocking. The ruby
# interpreter.
#
# See also resolv-replace.rb to replace the libc resolver with # Resolv.
#
# Resolv can look up various DNS resources using the DNS module directly.
#
# Examples:
#
# p Resolv.getaddress "www.ruby-lang.org"
# p Resolv.getname "210.251.121.214"
#
# Resolv::DNS.open do |dns|
# ress = dns.getresources "www.ruby-lang.org", Resolv::DNS::Resource::IN::A
# p ress.map { |r| r.address }
# ress = dns.getresources "ruby-lang.org", Resolv::DNS::Resource::IN::MX
# p ress.map { |r| [r.exchange.to_s, r.preference] }
# end
#
#
# == Bugs
#
# * NIS is not supported.
# * /etc/nsswitch.conf is not supported.
class Resolv
##
# Looks up the first IP address for +name+.
def self.getaddress(name)
DefaultResolver.getaddress(name)
end
##
# Looks up all IP address for +name+.
def self.getaddresses(name)
DefaultResolver.getaddresses(name)
end
##
# Iterates over all IP addresses for +name+.
def self.each_address(name, &block)
DefaultResolver.each_address(name, &block)
end
##
# Looks up the hostname of +address+.
def self.getname(address)
DefaultResolver.getname(address)
end
##
# Looks up all hostnames for +address+.
def self.getnames(address)
DefaultResolver.getnames(address)
end
##
# Iterates over all hostnames for +address+.
def self.each_name(address, &proc)
DefaultResolver.each_name(address, &proc)
end
##
# Creates a new Resolv using +resolvers+.
def initialize(resolvers=[Hosts.new, DNS.new])
@resolvers = resolvers
end
##
# Looks up the first IP address for +name+.
def getaddress(name)
each_address(name) {|address| return address}
raise ResolvError.new("no address for #{name}")
end
##
# Looks up all IP address for +name+.
def getaddresses(name)
ret = []
each_address(name) {|address| ret << address}
return ret
end
##
# Iterates over all IP addresses for +name+.
def each_address(name)
if AddressRegex =~ name
yield name
return
end
yielded = false
@resolvers.each {|r|
r.each_address(name) {|address|
yield address.to_s
yielded = true
}
return if yielded
}
end
##
# Looks up the hostname of +address+.
def getname(address)
each_name(address) {|name| return name}
raise ResolvError.new("no name for #{address}")
end
##
# Looks up all hostnames for +address+.
def getnames(address)
ret = []
each_name(address) {|name| ret << name}
return ret
end
##
# Iterates over all hostnames for +address+.
def each_name(address)
yielded = false
@resolvers.each {|r|
r.each_name(address) {|name|
yield name.to_s
yielded = true
}
return if yielded
}
end
##
# Indicates a failure to resolve a name or address.
class ResolvError < StandardError; end
##
# Indicates a timeout resolving a name or address.
class ResolvTimeout < TimeoutError; end
##
# Resolv::Hosts is a hostname resolver that uses the system hosts file.
class Hosts
require 'rbconfig'
if /mswin32|cygwin|mingw|bccwin/ =~ RUBY_PLATFORM || ::Config::CONFIG['host_os'] =~ /mswin/
require 'win32/resolv'
DefaultFileName = Win32::Resolv.get_hosts_path
else
DefaultFileName = '/etc/hosts'
end
##
# Creates a new Resolv::Hosts, using +filename+ for its data source.
def initialize(filename = DefaultFileName)
@filename = filename
@mutex = Mutex.new
@initialized = nil
end
def lazy_initialize # :nodoc:
@mutex.synchronize {
unless @initialized
@name2addr = {}
@addr2name = {}
open(@filename) {|f|
f.each {|line|
line.sub!(/#.*/, '')
addr, hostname, *aliases = line.split(/\s+/)
next unless addr
addr.untaint
hostname.untaint
@addr2name[addr] = [] unless @addr2name.include? addr
@addr2name[addr] << hostname
@addr2name[addr] += aliases
@name2addr[hostname] = [] unless @name2addr.include? hostname
@name2addr[hostname] << addr
aliases.each {|n|
n.untaint
@name2addr[n] = [] unless @name2addr.include? n
@name2addr[n] << addr
}
}
}
@name2addr.each {|name, arr| arr.reverse!}
@initialized = true
end
}
self
end
##
# Gets the IP address of +name+ from the hosts file.
def getaddress(name)
each_address(name) {|address| return address}
raise ResolvError.new("#{@filename} has no name: #{name}")
end
##
# Gets all IP addresses for +name+ from the hosts file.
def getaddresses(name)
ret = []
each_address(name) {|address| ret << address}
return ret
end
##
# Iterates over all IP addresses for +name+ retrieved from the hosts file.
def each_address(name, &proc)
lazy_initialize
if @name2addr.include?(name)
@name2addr[name].each(&proc)
end
end
##
# Gets the hostname of +address+ from the hosts file.
def getname(address)
each_name(address) {|name| return name}
raise ResolvError.new("#{@filename} has no address: #{address}")
end
##
# Gets all hostnames for +address+ from the hosts file.
def getnames(address)
ret = []
each_name(address) {|name| ret << name}
return ret
end
##
# Iterates over all hostnames for +address+ retrieved from the hosts file.
def each_name(address, &proc)
lazy_initialize
if @addr2name.include?(address)
@addr2name[address].each(&proc)
end
end
end
##
# Resolv::DNS is a DNS stub resolver.
#
# Information taken from the following places:
#
# * STD0013
# * RFC 1035
# * ftp://ftp.isi.edu/in-notes/iana/assignments/dns-parameters
# * etc.
class DNS
##
# Default DNS Port
Port = 53
##
# Default DNS UDP packet size
UDPSize = 512
##
# Creates a new DNS resolver. See Resolv::DNS.new for argument details.
#
# Yields the created DNS resolver to the block, if given, otherwise
# returns it.
def self.open(*args)
dns = new(*args)
return dns unless block_given?
begin
yield dns
ensure
dns.close
end
end
##
# Creates a new DNS resolver.
#
# +config_info+ can be:
#
# nil:: Uses /etc/resolv.conf.
# String:: Path to a file using /etc/resolv.conf's format.
# Hash:: Must contain :nameserver, :search and :ndots keys.
#
# Example:
#
# Resolv::DNS.new(:nameserver => ['210.251.121.21'],
# :search => ['ruby-lang.org'],
# :ndots => 1)
def initialize(config_info=nil)
@mutex = Mutex.new
@config = Config.new(config_info)
@initialized = nil
end
def lazy_initialize # :nodoc:
@mutex.synchronize {
unless @initialized
@config.lazy_initialize
@initialized = true
end
}
self
end
##
# Closes the DNS resolver.
def close
@mutex.synchronize {
if @initialized
@initialized = false
end
}
end
##
# Gets the IP address of +name+ from the DNS resolver.
#
# +name+ can be a Resolv::DNS::Name or a String. Retrieved address will
# be a Resolv::IPv4 or Resolv::IPv6
def getaddress(name)
each_address(name) {|address| return address}
raise ResolvError.new("DNS result has no information for #{name}")
end
##
# Gets all IP addresses for +name+ from the DNS resolver.
#
# +name+ can be a Resolv::DNS::Name or a String. Retrieved addresses will
# be a Resolv::IPv4 or Resolv::IPv6
def getaddresses(name)
ret = []
each_address(name) {|address| ret << address}
return ret
end
##
# Iterates over all IP addresses for +name+ retrieved from the DNS
# resolver.
#
# +name+ can be a Resolv::DNS::Name or a String. Retrieved addresses will
# be a Resolv::IPv4 or Resolv::IPv6
def each_address(name)
each_resource(name, Resource::IN::A) {|resource| yield resource.address}
if use_ipv6?
each_resource(name, Resource::IN::AAAA) {|resource| yield resource.address}
end
end
def use_ipv6?
begin
list = Socket.ip_address_list
rescue NotImplementedError
return true
end
list.any? {|a| a.ipv6? && !a.ipv6_loopback? && !a.ipv6_linklocal? }
end
private :use_ipv6?
##
# Gets the hostname for +address+ from the DNS resolver.
#
# +address+ must be a Resolv::IPv4, Resolv::IPv6 or a String. Retrieved
# name will be a Resolv::DNS::Name.
def getname(address)
each_name(address) {|name| return name}
raise ResolvError.new("DNS result has no information for #{address}")
end
##
# Gets all hostnames for +address+ from the DNS resolver.
#
# +address+ must be a Resolv::IPv4, Resolv::IPv6 or a String. Retrieved
# names will be Resolv::DNS::Name instances.
def getnames(address)
ret = []
each_name(address) {|name| ret << name}
return ret
end
##
# Iterates over all hostnames for +address+ retrieved from the DNS
# resolver.
#
# +address+ must be a Resolv::IPv4, Resolv::IPv6 or a String. Retrieved
# names will be Resolv::DNS::Name instances.
def each_name(address)
case address
when Name
ptr = address
when IPv4::Regex
ptr = IPv4.create(address).to_name
when IPv6::Regex
ptr = IPv6.create(address).to_name
else
raise ResolvError.new("cannot interpret as address: #{address}")
end
each_resource(ptr, Resource::IN::PTR) {|resource| yield resource.name}
end
##
# Look up the +typeclass+ DNS resource of +name+.
#
# +name+ must be a Resolv::DNS::Name or a String.
#
# +typeclass+ should be one of the following:
#
# * Resolv::DNS::Resource::IN::A
# * Resolv::DNS::Resource::IN::AAAA
# * Resolv::DNS::Resource::IN::ANY
# * Resolv::DNS::Resource::IN::CNAME
# * Resolv::DNS::Resource::IN::HINFO
# * Resolv::DNS::Resource::IN::MINFO
# * Resolv::DNS::Resource::IN::MX
# * Resolv::DNS::Resource::IN::NS
# * Resolv::DNS::Resource::IN::PTR
# * Resolv::DNS::Resource::IN::SOA
# * Resolv::DNS::Resource::IN::TXT
# * Resolv::DNS::Resource::IN::WKS
#
# Returned resource is represented as a Resolv::DNS::Resource instance,
# i.e. Resolv::DNS::Resource::IN::A.
def getresource(name, typeclass)
each_resource(name, typeclass) {|resource| return resource}
raise ResolvError.new("DNS result has no information for #{name}")
end
##
# Looks up all +typeclass+ DNS resources for +name+. See #getresource for
# argument details.
def getresources(name, typeclass)
ret = []
each_resource(name, typeclass) {|resource| ret << resource}
return ret
end
##
# Iterates over all +typeclass+ DNS resources for +name+. See
# #getresource for argument details.
def each_resource(name, typeclass, &proc)
lazy_initialize
requester = make_requester
senders = {}
begin
@config.resolv(name) {|candidate, tout, nameserver|
msg = Message.new
msg.rd = 1
msg.add_question(candidate, typeclass)
unless sender = senders[[candidate, nameserver]]
sender = senders[[candidate, nameserver]] =
requester.sender(msg, candidate, nameserver)
end
reply, reply_name = requester.request(sender, tout)
case reply.rcode
when RCode::NoError
extract_resources(reply, reply_name, typeclass, &proc)
return
when RCode::NXDomain
raise Config::NXDomain.new(reply_name.to_s)
else
raise Config::OtherResolvError.new(reply_name.to_s)
end
}
ensure
requester.close
end
end
def make_requester # :nodoc:
if nameserver = @config.single?
Requester::ConnectedUDP.new(nameserver)
else
Requester::UnconnectedUDP.new
end
end
def extract_resources(msg, name, typeclass) # :nodoc:
if typeclass < Resource::ANY
n0 = Name.create(name)
msg.each_answer {|n, ttl, data|
yield data if n0 == n
}
end
yielded = false
n0 = Name.create(name)
msg.each_answer {|n, ttl, data|
if n0 == n
case data
when typeclass
yield data
yielded = true
when Resource::CNAME
n0 = data.name
end
end
}
return if yielded
msg.each_answer {|n, ttl, data|
if n0 == n
case data
when typeclass
yield data
end
end
}
end
if defined? SecureRandom
def self.random(arg) # :nodoc:
begin
SecureRandom.random_number(arg)
rescue NotImplementedError
rand(arg)
end
end
else
def self.random(arg) # :nodoc:
rand(arg)
end
end
def self.rangerand(range) # :nodoc:
base = range.begin
len = range.end - range.begin
if !range.exclude_end?
len += 1
end
base + random(len)
end
RequestID = {}
RequestIDMutex = Mutex.new
def self.allocate_request_id(host, port) # :nodoc:
id = nil
RequestIDMutex.synchronize {
h = (RequestID[[host, port]] ||= {})
begin
id = rangerand(0x0000..0xffff)
end while h[id]
h[id] = true
}
id
end
def self.free_request_id(host, port, id) # :nodoc:
RequestIDMutex.synchronize {
key = [host, port]
if h = RequestID[key]
h.delete id
if h.empty?
RequestID.delete key
end
end
}
end
def self.bind_random_port(udpsock) # :nodoc:
begin
port = rangerand(1024..65535)
udpsock.bind("", port)
rescue Errno::EADDRINUSE
retry
end
end
class Requester # :nodoc:
def initialize
@senders = {}
@sock = nil
end
def request(sender, tout)
timelimit = Time.now + tout
sender.send
while (now = Time.now) < timelimit
timeout = timelimit - now
if !IO.select([@sock], nil, nil, timeout)
raise ResolvTimeout
end
reply, from = recv_reply
begin
msg = Message.decode(reply)
rescue DecodeError
next # broken DNS message ignored
end
if s = @senders[[from,msg.id]]
break
else
# unexpected DNS message ignored
end
end
return msg, s.data
end
def close
sock = @sock
@sock = nil
sock.close if sock
end
class Sender # :nodoc:
def initialize(msg, data, sock)
@msg = msg
@data = data
@sock = sock
end
end
class UnconnectedUDP < Requester # :nodoc:
def initialize
super()
@sock = UDPSocket.new
@sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) if defined? Fcntl::F_SETFD
DNS.bind_random_port(@sock)
end
def recv_reply
reply, from = @sock.recvfrom(UDPSize)
return reply, [from[3],from[1]]
end
def sender(msg, data, host, port=Port)
service = [host, port]
id = DNS.allocate_request_id(host, port)
request = msg.encode
request[0,2] = [id].pack('n')
return @senders[[service, id]] =
Sender.new(request, data, @sock, host, port)
end
def close
super
@senders.each_key {|service, id|
DNS.free_request_id(service[0], service[1], id)
}
end
class Sender < Requester::Sender # :nodoc:
def initialize(msg, data, sock, host, port)
super(msg, data, sock)
@host = host
@port = port
end
attr_reader :data
def send
@sock.send(@msg, 0, @host, @port)
end
end
end
class ConnectedUDP < Requester # :nodoc:
def initialize(host, port=Port)
super()
@host = host
@port = port
@sock = UDPSocket.new(host.index(':') ? Socket::AF_INET6 : Socket::AF_INET)
DNS.bind_random_port(@sock)
@sock.connect(host, port)
@sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) if defined? Fcntl::F_SETFD
end
def recv_reply
reply = @sock.recv(UDPSize)
return reply, nil
end
def sender(msg, data, host=@host, port=@port)
unless host == @host && port == @port
raise RequestError.new("host/port don't match: #{host}:#{port}")
end
id = DNS.allocate_request_id(@host, @port)
request = msg.encode
request[0,2] = [id].pack('n')
return @senders[[nil,id]] = Sender.new(request, data, @sock)
end
def close
super
@senders.each_key {|from, id|
DNS.free_request_id(@host, @port, id)
}
end
class Sender < Requester::Sender # :nodoc:
def send
@sock.send(@msg, 0)
end
attr_reader :data
end
end
class TCP < Requester # :nodoc:
def initialize(host, port=Port)
super()
@host = host
@port = port
@sock = TCPSocket.new(@host, @port)
@sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) if defined? Fcntl::F_SETFD
@senders = {}
end
def recv_reply
len = @sock.read(2).unpack('n')[0]
reply = @sock.read(len)
return reply, nil
end
def sender(msg, data, host=@host, port=@port)
unless host == @host && port == @port
raise RequestError.new("host/port don't match: #{host}:#{port}")
end
id = DNS.allocate_request_id(@host, @port)
request = msg.encode
request[0,2] = [request.length, id].pack('nn')
return @senders[[nil,id]] = Sender.new(request, data, @sock)
end
class Sender < Requester::Sender # :nodoc:
def send
@sock.print(@msg)
@sock.flush
end
attr_reader :data
end
def close
super
@senders.each_key {|from,id|
DNS.free_request_id(@host, @port, id)
}
end
end
##
# Indicates a problem with the DNS request.
class RequestError < StandardError
end
end
class Config # :nodoc:
def initialize(config_info=nil)
@mutex = Mutex.new
@config_info = config_info
@initialized = nil
end
def Config.parse_resolv_conf(filename)
nameserver = []
search = nil
ndots = 1
open(filename) {|f|
f.each {|line|
line.sub!(/[#;].*/, '')
keyword, *args = line.split(/\s+/)
args.each { |arg|
arg.untaint
}
next unless keyword
case keyword
when 'nameserver'
nameserver += args
when 'domain'
next if args.empty?
search = [args[0]]
when 'search'
next if args.empty?
search = args
when 'options'
args.each {|arg|
case arg
when /\Andots:(\d+)\z/
ndots = $1.to_i
end
}
end
}
}
return { :nameserver => nameserver, :search => search, :ndots => ndots }
end
def Config.default_config_hash(filename="/etc/resolv.conf")
if File.exist? filename
config_hash = Config.parse_resolv_conf(filename)
else
require 'rbconfig'
if /mswin32|cygwin|mingw|bccwin/ =~ RUBY_PLATFORM || ::Config::CONFIG['host_os'] =~ /mswin/
require 'win32/resolv'
search, nameserver = Win32::Resolv.get_resolv_info
config_hash = {}
config_hash[:nameserver] = nameserver if nameserver
config_hash[:search] = [search].flatten if search
end
end
config_hash
end
def lazy_initialize
@mutex.synchronize {
unless @initialized
@nameserver = []
@search = nil
@ndots = 1
case @config_info
when nil
config_hash = Config.default_config_hash
when String
config_hash = Config.parse_resolv_conf(@config_info)
when Hash
config_hash = @config_info.dup
if String === config_hash[:nameserver]
config_hash[:nameserver] = [config_hash[:nameserver]]
end
if String === config_hash[:search]
config_hash[:search] = [config_hash[:search]]
end
else
raise ArgumentError.new("invalid resolv configuration: #{@config_info.inspect}")
end
@nameserver = config_hash[:nameserver] if config_hash.include? :nameserver
@search = config_hash[:search] if config_hash.include? :search
@ndots = config_hash[:ndots] if config_hash.include? :ndots
@nameserver = ['0.0.0.0'] if @nameserver.empty?
if @search
@search = @search.map {|arg| Label.split(arg) }
else
hostname = Socket.gethostname
if /\./ =~ hostname
@search = [Label.split($')]
else
@search = [[]]
end
end
if !@nameserver.kind_of?(Array) ||
!@nameserver.all? {|ns| String === ns }
raise ArgumentError.new("invalid nameserver config: #{@nameserver.inspect}")
end
if !@search.kind_of?(Array) ||
!@search.all? {|ls| ls.all? {|l| Label::Str === l } }
raise ArgumentError.new("invalid search config: #{@search.inspect}")
end
if !@ndots.kind_of?(Integer)
raise ArgumentError.new("invalid ndots config: #{@ndots.inspect}")
end
@initialized = true
end
}
self
end
def single?
lazy_initialize
if @nameserver.length == 1
return @nameserver[0]
else
return nil
end
end
def generate_candidates(name)
candidates = nil
name = Name.create(name)
if name.absolute?
candidates = [name]
else
if @ndots <= name.length - 1
candidates = [Name.new(name.to_a)]
else
candidates = []
end
candidates.concat(@search.map {|domain| Name.new(name.to_a + domain)})
end
return candidates
end
InitialTimeout = 5
def generate_timeouts
ts = [InitialTimeout]
ts << ts[-1] * 2 / @nameserver.length
ts << ts[-1] * 2
ts << ts[-1] * 2
return ts
end
def resolv(name)
candidates = generate_candidates(name)
timeouts = generate_timeouts
begin
candidates.each {|candidate|
begin
timeouts.each {|tout|
@nameserver.each {|nameserver|
begin
yield candidate, tout, nameserver
rescue ResolvTimeout
end
}
}
raise ResolvError.new("DNS resolv timeout: #{name}")
rescue NXDomain
end
}
rescue ResolvError
end
end
##
# Indicates no such domain was found.
class NXDomain < ResolvError
end
##
# Indicates some other unhandled resolver error was encountered.
class OtherResolvError < ResolvError
end
end
module OpCode # :nodoc:
Query = 0
IQuery = 1
Status = 2
Notify = 4
Update = 5
end
module RCode # :nodoc:
NoError = 0
FormErr = 1
ServFail = 2
NXDomain = 3
NotImp = 4
Refused = 5
YXDomain = 6
YXRRSet = 7
NXRRSet = 8
NotAuth = 9
NotZone = 10
BADVERS = 16
BADSIG = 16
BADKEY = 17
BADTIME = 18
BADMODE = 19
BADNAME = 20
BADALG = 21
end
##
# Indicates that the DNS response was unable to be decoded.
class DecodeError < StandardError
end
##
# Indicates that the DNS request was unable to be encoded.
class EncodeError < StandardError
end
module Label # :nodoc:
def self.split(arg)
labels = []
arg.scan(/[^\.]+/) {labels << Str.new($&)}
return labels
end
class Str # :nodoc:
def initialize(string)
@string = string
@downcase = string.downcase
end
attr_reader :string, :downcase
def to_s
return @string
end
def inspect
return "#<#{self.class} #{self.to_s}>"
end
def ==(other)
return @downcase == other.downcase
end
def eql?(other)
return self == other
end
def hash
return @downcase.hash
end
end
end
##
# A representation of a DNS name.
class Name
##
# Creates a new DNS name from +arg+. +arg+ can be:
#
# Name:: returns +arg+.
# String:: Creates a new Name.
def self.create(arg)
case arg
when Name
return arg
when String
return Name.new(Label.split(arg), /\.\z/ =~ arg ? true : false)
else
raise ArgumentError.new("cannot interpret as DNS name: #{arg.inspect}")
end
end
def initialize(labels, absolute=true) # :nodoc:
@labels = labels
@absolute = absolute
end
def inspect # :nodoc:
"#<#{self.class}: #{self.to_s}#{@absolute ? '.' : ''}>"
end
##
# True if this name is absolute.
def absolute?
return @absolute
end
def ==(other) # :nodoc:
return false unless Name === other
return @labels.join == other.to_a.join && @absolute == other.absolute?
end
alias eql? == # :nodoc:
##
# Returns true if +other+ is a subdomain.
#
# Example:
#
# domain = Resolv::DNS::Name.create("y.z")
# p Resolv::DNS::Name.create("w.x.y.z").subdomain_of?(domain) #=> true
# p Resolv::DNS::Name.create("x.y.z").subdomain_of?(domain) #=> true
# p Resolv::DNS::Name.create("y.z").subdomain_of?(domain) #=> false
# p Resolv::DNS::Name.create("z").subdomain_of?(domain) #=> false
# p Resolv::DNS::Name.create("x.y.z.").subdomain_of?(domain) #=> false
# p Resolv::DNS::Name.create("w.z").subdomain_of?(domain) #=> false
#
def subdomain_of?(other)
raise ArgumentError, "not a domain name: #{other.inspect}" unless Name === other
return false if @absolute != other.absolute?
other_len = other.length
return false if @labels.length <= other_len
return @labels[-other_len, other_len] == other.to_a
end
def hash # :nodoc:
return @labels.hash ^ @absolute.hash
end
def to_a # :nodoc:
return @labels
end
def length # :nodoc:
return @labels.length
end
def [](i) # :nodoc:
return @labels[i]
end
##
# returns the domain name as a string.
#
# The domain name doesn't have a trailing dot even if the name object is
# absolute.
#
# Example:
#
# p Resolv::DNS::Name.create("x.y.z.").to_s #=> "x.y.z"
# p Resolv::DNS::Name.create("x.y.z").to_s #=> "x.y.z"
def to_s
return @labels.join('.')
end
end
class Message # :nodoc:
@@identifier = -1
def initialize(id = (@@identifier += 1) & 0xffff)
@id = id
@qr = 0
@opcode = 0
@aa = 0
@tc = 0
@rd = 0 # recursion desired
@ra = 0 # recursion available
@rcode = 0
@question = []
@answer = []
@authority = []
@additional = []
end
attr_accessor :id, :qr, :opcode, :aa, :tc, :rd, :ra, :rcode
attr_reader :question, :answer, :authority, :additional
def ==(other)
return @id == other.id &&
@qr == other.qr &&
@opcode == other.opcode &&
@aa == other.aa &&
@tc == other.tc &&
@rd == other.rd &&
@ra == other.ra &&
@rcode == other.rcode &&
@question == other.question &&
@answer == other.answer &&
@authority == other.authority &&
@additional == other.additional
end
def add_question(name, typeclass)
@question << [Name.create(name), typeclass]
end
def each_question
@question.each {|name, typeclass|
yield name, typeclass
}
end
def add_answer(name, ttl, data)
@answer << [Name.create(name), ttl, data]
end
def each_answer
@answer.each {|name, ttl, data|
yield name, ttl, data
}
end
def add_authority(name, ttl, data)
@authority << [Name.create(name), ttl, data]
end
def each_authority
@authority.each {|name, ttl, data|
yield name, ttl, data
}
end
def add_additional(name, ttl, data)
@additional << [Name.create(name), ttl, data]
end
def each_additional
@additional.each {|name, ttl, data|
yield name, ttl, data
}
end
def each_resource
each_answer {|name, ttl, data| yield name, ttl, data}
each_authority {|name, ttl, data| yield name, ttl, data}
each_additional {|name, ttl, data| yield name, ttl, data}
end
def encode
return MessageEncoder.new {|msg|
msg.put_pack('nnnnnn',
@id,
(@qr & 1) << 15 |
(@opcode & 15) << 11 |
(@aa & 1) << 10 |
(@tc & 1) << 9 |
(@rd & 1) << 8 |
(@ra & 1) << 7 |
(@rcode & 15),
@question.length,
@answer.length,
@authority.length,
@additional.length)
@question.each {|q|
name, typeclass = q
msg.put_name(name)
msg.put_pack('nn', typeclass::TypeValue, typeclass::ClassValue)
}
[@answer, @authority, @additional].each {|rr|
rr.each {|r|
name, ttl, data = r
msg.put_name(name)
msg.put_pack('nnN', data.class::TypeValue, data.class::ClassValue, ttl)
msg.put_length16 {data.encode_rdata(msg)}
}
}
}.to_s
end
class MessageEncoder # :nodoc:
def initialize
@data = ''
@names = {}
yield self
end
def to_s
return @data
end
def put_bytes(d)
@data << d
end
def put_pack(template, *d)
@data << d.pack(template)
end
def put_length16
length_index = @data.length
@data << "\0\0"
data_start = @data.length
yield
data_end = @data.length
@data[length_index, 2] = [data_end - data_start].pack("n")
end
def put_string(d)
self.put_pack("C", d.length)
@data << d
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/tracer.rb | tools/jruby-1.5.1/lib/ruby/1.9/tracer.rb | # tracer.rb -
# $Release Version: 0.3$
# $Revision: 1.12 $
# by Keiju ISHITSUKA(keiju@ishitsuka.com)
#
# --
#
#
#
require "thread"
#
# tracer main class
#
class Tracer
class << self
attr_accessor :verbose
alias verbose? verbose
attr_accessor :stdout
attr_reader :stdout_mutex
# display process id?
attr_accessor :display_process_id
alias display_process_id? display_process_id
# display thread id?
attr_accessor :display_thread_id
alias display_thread_id? display_thread_id
# display builtin method call?
attr_accessor :display_c_call
alias display_c_call? display_c_call
end
Tracer::stdout = STDOUT
Tracer::verbose = false
Tracer::display_process_id = false
Tracer::display_thread_id = true
Tracer::display_c_call = false
@stdout_mutex = Mutex.new
EVENT_SYMBOL = {
"line" => "-",
"call" => ">",
"return" => "<",
"class" => "C",
"end" => "E",
"raise" => "^",
"c-call" => "}",
"c-return" => "{",
"unknown" => "?"
}
def initialize
@threads = Hash.new
if defined? Thread.main
@threads[Thread.main.object_id] = 0
else
@threads[Thread.current.object_id] = 0
end
@get_line_procs = {}
@filters = []
end
def stdout
Tracer.stdout
end
def on
if block_given?
on
begin
yield
ensure
off
end
else
set_trace_func method(:trace_func).to_proc
stdout.print "Trace on\n" if Tracer.verbose?
end
end
def off
set_trace_func nil
stdout.print "Trace off\n" if Tracer.verbose?
end
def add_filter(p = proc)
@filters.push p
end
def set_get_line_procs(file, p = proc)
@get_line_procs[file] = p
end
def get_line(file, line)
if p = @get_line_procs[file]
return p.call(line)
end
unless list = SCRIPT_LINES__[file]
begin
f = File::open(file)
begin
SCRIPT_LINES__[file] = list = f.readlines
ensure
f.close
end
rescue
SCRIPT_LINES__[file] = list = []
end
end
if l = list[line - 1]
l
else
"-\n"
end
end
def get_thread_no
if no = @threads[Thread.current.object_id]
no
else
@threads[Thread.current.object_id] = @threads.size
end
end
def trace_func(event, file, line, id, binding, klass, *)
return if file == __FILE__
for p in @filters
return unless p.call event, file, line, id, binding, klass
end
return unless Tracer::display_c_call? or
event != "c-call" && event != "c-return"
Tracer::stdout_mutex.synchronize do
if EVENT_SYMBOL[event]
stdout.printf("<%d>", $$) if Tracer::display_process_id?
stdout.printf("#%d:", get_thread_no) if Tracer::display_thread_id?
if line == 0
source = "?\n"
else
source = get_line(file, line)
end
printf("%s:%d:%s:%s: %s",
file,
line,
klass || '',
EVENT_SYMBOL[event],
source)
end
end
end
Single = new
def Tracer.on
if block_given?
Single.on{yield}
else
Single.on
end
end
def Tracer.off
Single.off
end
def Tracer.set_get_line_procs(file_name, p = proc)
Single.set_get_line_procs(file_name, p)
end
def Tracer.add_filter(p = proc)
Single.add_filter(p)
end
end
SCRIPT_LINES__ = {} unless defined? SCRIPT_LINES__
if $0 == __FILE__
# direct call
$0 = ARGV[0]
ARGV.shift
Tracer.on
require $0
elsif caller.size <= 1
Tracer.on
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/rdoc.rb | tools/jruby-1.5.1/lib/ruby/1.9/rdoc.rb | $DEBUG_RDOC = nil
##
# = \RDoc - Ruby Documentation System
#
# This package contains RDoc and RDoc::Markup. RDoc is an application that
# produces documentation for one or more Ruby source files. It works similarly
# to JavaDoc, parsing the source, and extracting the definition for classes,
# modules, and methods (along with includes and requires). It associates with
# these optional documentation contained in the immediately preceding comment
# block, and then renders the result using a pluggable output formatter.
# RDoc::Markup is a library that converts plain text into various output
# formats. The markup library is used to interpret the comment blocks that
# RDoc uses to document methods, classes, and so on.
#
# == Roadmap
#
# * If you want to use RDoc to create documentation for your Ruby source files,
# read on.
# * If you want to include extensions written in C, see RDoc::Parser::C
# * If you want to drive RDoc programmatically, see RDoc::RDoc.
# * If you want to use the library to format text blocks into HTML, have a look
# at RDoc::Markup.
# * If you want to try writing your own HTML output template, see
# RDoc::Generator::HTML
#
# == Summary
#
# Once installed, you can create documentation using the +rdoc+ command
#
# % rdoc [options] [names...]
#
# For an up-to-date option summary, type
# % rdoc --help
#
# A typical use might be to generate documentation for a package of Ruby
# source (such as RDoc itself).
#
# % rdoc
#
# This command generates documentation for all the Ruby and C source
# files in and below the current directory. These will be stored in a
# documentation tree starting in the subdirectory +doc+.
#
# You can make this slightly more useful for your readers by having the
# index page contain the documentation for the primary file. In our
# case, we could type
#
# % rdoc --main rdoc.rb
#
# You'll find information on the various formatting tricks you can use
# in comment blocks in the documentation this generates.
#
# RDoc uses file extensions to determine how to process each file. File names
# ending +.rb+ and +.rbw+ are assumed to be Ruby source. Files
# ending +.c+ are parsed as C files. All other files are assumed to
# contain just Markup-style markup (with or without leading '#' comment
# markers). If directory names are passed to RDoc, they are scanned
# recursively for C and Ruby source files only.
#
# == \Options
# rdoc can be passed a variety of command-line options. In addition,
# options can be specified via the +RDOCOPT+ environment variable, which
# functions similarly to the +RUBYOPT+ environment variable.
#
# % export RDOCOPT="-S"
#
# will make rdoc default to inline method source code. Command-line options
# always will override those in +RDOCOPT+.
#
# Run
#
# % rdoc --help
#
# for full details on rdoc's options.
#
# Here are some of the most commonly used options.
# [-d, --diagram]
# Generate diagrams showing modules and
# classes. You need dot V1.8.6 or later to
# use the --diagram option correctly. Dot is
# available from http://graphviz.org
#
# [-S, --inline-source]
# Show method source code inline, rather than via a popup link.
#
# [-T, --template=NAME]
# Set the template used when generating output.
#
# == Documenting Source Code
#
# Comment blocks can be written fairly naturally, either using +#+ on
# successive lines of the comment, or by including the comment in
# a =begin/=end block. If you use the latter form, the =begin line must be
# flagged with an RDoc tag:
#
# =begin rdoc
# Documentation to be processed by RDoc.
#
# ...
# =end
#
# RDoc stops processing comments if it finds a comment line containing
# a <tt>--</tt>. This can be used to separate external from internal
# comments, or to stop a comment being associated with a method, class, or
# module. Commenting can be turned back on with a line that starts with a
# <tt>++</tt>.
#
# ##
# # Extract the age and calculate the date-of-birth.
# #--
# # FIXME: fails if the birthday falls on February 29th
# #++
# # The DOB is returned as a Time object.
#
# def get_dob(person)
# # ...
# end
#
# Names of classes, files, and any method names containing an
# underscore or preceded by a hash character are automatically hyperlinked
# from comment text to their description.
#
# Method parameter lists are extracted and displayed with the method
# description. If a method calls +yield+, then the parameters passed to yield
# will also be displayed:
#
# def fred
# ...
# yield line, address
#
# This will get documented as:
#
# fred() { |line, address| ... }
#
# You can override this using a comment containing ':yields: ...' immediately
# after the method definition
#
# def fred # :yields: index, position
# # ...
#
# yield line, address
#
# which will get documented as
#
# fred() { |index, position| ... }
#
# +:yields:+ is an example of a documentation directive. These appear
# immediately after the start of the document element they are modifying.
#
# == \Markup
#
# * The markup engine looks for a document's natural left margin. This is
# used as the initial margin for the document.
#
# * Consecutive lines starting at this margin are considered to be a
# paragraph.
#
# * If a paragraph starts with a "*", "-", or with "<digit>.", then it is
# taken to be the start of a list. The margin in increased to be the first
# non-space following the list start flag. Subsequent lines should be
# indented to this new margin until the list ends. For example:
#
# * this is a list with three paragraphs in
# the first item. This is the first paragraph.
#
# And this is the second paragraph.
#
# 1. This is an indented, numbered list.
# 2. This is the second item in that list
#
# This is the third conventional paragraph in the
# first list item.
#
# * This is the second item in the original list
#
# * You can also construct labeled lists, sometimes called description
# or definition lists. Do this by putting the label in square brackets
# and indenting the list body:
#
# [cat] a small furry mammal
# that seems to sleep a lot
#
# [ant] a little insect that is known
# to enjoy picnics
#
# A minor variation on labeled lists uses two colons to separate the
# label from the list body:
#
# cat:: a small furry mammal
# that seems to sleep a lot
#
# ant:: a little insect that is known
# to enjoy picnics
#
# This latter style guarantees that the list bodies' left margins are
# aligned: think of them as a two column table.
#
# * Any line that starts to the right of the current margin is treated
# as verbatim text. This is useful for code listings. The example of a
# list above is also verbatim text.
#
# * A line starting with an equals sign (=) is treated as a
# heading. Level one headings have one equals sign, level two headings
# have two,and so on.
#
# * A line starting with three or more hyphens (at the current indent)
# generates a horizontal rule. The more hyphens, the thicker the rule
# (within reason, and if supported by the output device)
#
# * You can use markup within text (except verbatim) to change the
# appearance of parts of that text. Out of the box, RDoc::Markup
# supports word-based and general markup.
#
# Word-based markup uses flag characters around individual words:
#
# [\*word*] displays word in a *bold* font
# [\_word_] displays word in an _emphasized_ font
# [\+word+] displays word in a +code+ font
#
# General markup affects text between a start delimiter and and end
# delimiter. Not surprisingly, these delimiters look like HTML markup.
#
# [\<b>text...</b>] displays word in a *bold* font
# [\<em>text...</em>] displays word in an _emphasized_ font
# [\\<i>text...</i>] displays word in an <i>italicized</i> font
# [\<tt>text...</tt>] displays word in a +code+ font
#
# Unlike conventional Wiki markup, general markup can cross line
# boundaries. You can turn off the interpretation of markup by
# preceding the first character with a backslash. This only works for
# simple markup, not HTML-style markup.
#
# * Hyperlinks to the web starting http:, mailto:, ftp:, or www. are
# recognized. An HTTP url that references an external image file is
# converted into an inline <IMG..>. Hyperlinks starting 'link:' are
# assumed to refer to local files whose path is relative to the --op
# directory.
#
# Hyperlinks can also be of the form <tt>label</tt>[url], in which
# case the label is used in the displayed text, and +url+ is
# used as the target. If +label+ contains multiple words,
# put it in braces: <em>{multi word label}[</em>url<em>]</em>.
#
# == Directives
#
# [+:nodoc:+ / +:nodoc:+ all]
# This directive prevents documentation for the element from
# being generated. For classes and modules, the methods, aliases,
# constants, and attributes directly within the affected class or
# module also will be omitted. By default, though, modules and
# classes within that class of module _will_ be documented. This is
# turned off by adding the +all+ modifier.
#
# module MyModule # :nodoc:
# class Input
# end
# end
#
# module OtherModule # :nodoc: all
# class Output
# end
# end
#
# In the above code, only class <tt>MyModule::Input</tt> will be documented.
# The +:nodoc:+ directive is global across all files for the class or module
# to which it applies, so use +:stopdoc:+/+:startdoc:+ to suppress
# documentation only for a particular set of methods, etc.
#
# [+:doc:+]
# Forces a method or attribute to be documented even if it wouldn't be
# otherwise. Useful if, for example, you want to include documentation of a
# particular private method.
#
# [+:notnew:+]
# Only applicable to the +initialize+ instance method. Normally RDoc
# assumes that the documentation and parameters for +initialize+ are
# actually for the +new+ method, and so fakes out a +new+ for the class.
# The +:notnew:+ modifier stops this. Remember that +initialize+ is private,
# so you won't see the documentation unless you use the +-a+ command line
# option.
#
# Comment blocks can contain other directives:
#
# [<tt>:section: title</tt>]
# Starts a new section in the output. The title following +:section:+ is
# used as the section heading, and the remainder of the comment containing
# the section is used as introductory text. Subsequent methods, aliases,
# attributes, and classes will be documented in this section. A :section:
# comment block may have one or more lines before the :section: directive.
# These will be removed, and any identical lines at the end of the block are
# also removed. This allows you to add visual cues such as:
#
# # ----------------------------------------
# # :section: My Section
# # This is the section that I wrote.
# # See it glisten in the noon-day sun.
# # ----------------------------------------
#
# [+:call-seq:+]
# Lines up to the next blank line in the comment are treated as the method's
# calling sequence, overriding the default parsing of method parameters and
# yield arguments.
#
# [+:include:+ _filename_]
# \Include the contents of the named file at this point. The file will be
# searched for in the directories listed by the +--include+ option, or in
# the current directory by default. The contents of the file will be
# shifted to have the same indentation as the ':' at the start of
# the :include: directive.
#
# [+:title:+ _text_]
# Sets the title for the document. Equivalent to the <tt>--title</tt>
# command line parameter. (The command line parameter overrides any :title:
# directive in the source).
#
# [+:enddoc:+]
# Document nothing further at the current level.
#
# [+:main:+ _name_]
# Equivalent to the <tt>--main</tt> command line parameter.
#
# [+:stopdoc:+ / +:startdoc:+]
# Stop and start adding new documentation elements to the current container.
# For example, if a class has a number of constants that you don't want to
# document, put a +:stopdoc:+ before the first, and a +:startdoc:+ after the
# last. If you don't specify a +:startdoc:+ by the end of the container,
# disables documentation for the entire class or module.
#
# == Other stuff
#
# RDoc is currently being maintained by Eric Hodel <drbrain@segment7.net>
#
# Dave Thomas <dave@pragmaticprogrammer.com> is the original author of RDoc.
#
# == Credits
#
# * The Ruby parser in rdoc/parse.rb is based heavily on the outstanding
# work of Keiju ISHITSUKA of Nippon Rational Inc, who produced the Ruby
# parser for irb and the rtags package.
#
# * Code to diagram classes and modules was written by Sergey A Yanovitsky
# (Jah) of Enticla.
#
# * Charset patch from MoonWolf.
#
# * Rich Kilmer wrote the kilmer.rb output template.
#
# * Dan Brickley led the design of the RDF format.
#
# == License
#
# RDoc is Copyright (c) 2001-2003 Dave Thomas, The Pragmatic Programmers. It
# is free software, and may be redistributed under the terms specified
# in the README file of the Ruby distribution.
#
# == Warranty
#
# This software is provided "as is" and without any express or implied
# warranties, including, without limitation, the implied warranties of
# merchantibility and fitness for a particular purpose.
module RDoc
##
# Exception thrown by any rdoc error.
class Error < RuntimeError; end
RDocError = Error # :nodoc:
##
# RDoc version you are using
VERSION = "2.2.2"
##
# Name of the dotfile that contains the description of files to be processed
# in the current directory
DOT_DOC_FILENAME = ".document"
GENERAL_MODIFIERS = %w[nodoc].freeze
CLASS_MODIFIERS = GENERAL_MODIFIERS
ATTR_MODIFIERS = GENERAL_MODIFIERS
CONSTANT_MODIFIERS = GENERAL_MODIFIERS
METHOD_MODIFIERS = GENERAL_MODIFIERS +
%w[arg args yield yields notnew not-new not_new doc]
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/sync.rb | tools/jruby-1.5.1/lib/ruby/1.9/sync.rb | #
# sync.rb - 2 phase lock with counter
# $Release Version: 1.0$
# $Revision: 22784 $
# by Keiju ISHITSUKA(keiju@ishitsuka.com)
#
# --
# Sync_m, Synchronizer_m
# Usage:
# obj.extend(Sync_m)
# or
# class Foo
# include Sync_m
# :
# end
#
# Sync_m#sync_mode
# Sync_m#sync_locked?, locked?
# Sync_m#sync_shared?, shared?
# Sync_m#sync_exclusive?, sync_exclusive?
# Sync_m#sync_try_lock, try_lock
# Sync_m#sync_lock, lock
# Sync_m#sync_unlock, unlock
#
# Sync, Synchronizer:
# Usage:
# sync = Sync.new
#
# Sync#mode
# Sync#locked?
# Sync#shared?
# Sync#exclusive?
# Sync#try_lock(mode) -- mode = :EX, :SH, :UN
# Sync#lock(mode) -- mode = :EX, :SH, :UN
# Sync#unlock
# Sync#synchronize(mode) {...}
#
#
unless defined? Thread
raise "Thread not available for this ruby interpreter"
end
module Sync_m
RCS_ID='-$Header$-'
# lock mode
UN = :UN
SH = :SH
EX = :EX
# exceptions
class Err < StandardError
def Err.Fail(*opt)
fail self, sprintf(self::Message, *opt)
end
class UnknownLocker < Err
Message = "Thread(%s) not locked."
def UnknownLocker.Fail(th)
super(th.inspect)
end
end
class LockModeFailer < Err
Message = "Unknown lock mode(%s)"
def LockModeFailer.Fail(mode)
if mode.id2name
mode = id2name
end
super(mode)
end
end
end
def Sync_m.define_aliases(cl)
cl.module_eval %q{
alias locked? sync_locked?
alias shared? sync_shared?
alias exclusive? sync_exclusive?
alias lock sync_lock
alias unlock sync_unlock
alias try_lock sync_try_lock
alias synchronize sync_synchronize
}
end
def Sync_m.append_features(cl)
super
# do nothing for Modules
# make aliases for Classes.
define_aliases(cl) unless cl.instance_of?(Module)
self
end
def Sync_m.extend_object(obj)
super
obj.sync_extend
end
def sync_extend
unless (defined? locked? and
defined? shared? and
defined? exclusive? and
defined? lock and
defined? unlock and
defined? try_lock and
defined? synchronize)
Sync_m.define_aliases(class<<self;self;end)
end
sync_initialize
end
# accessing
def sync_locked?
sync_mode != UN
end
def sync_shared?
sync_mode == SH
end
def sync_exclusive?
sync_mode == EX
end
# locking methods.
def sync_try_lock(mode = EX)
return unlock if mode == UN
@sync_mutex.synchronize do
ret = sync_try_lock_sub(mode)
end
ret
end
def sync_lock(m = EX)
return unlock if m == UN
while true
@sync_mutex.synchronize do
if sync_try_lock_sub(m)
return self
else
if sync_sh_locker[Thread.current]
sync_upgrade_waiting.push [Thread.current, sync_sh_locker[Thread.current]]
sync_sh_locker.delete(Thread.current)
else
sync_waiting.push Thread.current
end
@sync_mutex.sleep
end
end
end
self
end
def sync_unlock(m = EX)
wakeup_threads = []
@sync_mutex.synchronize do
if sync_mode == UN
Err::UnknownLocker.Fail(Thread.current)
end
m = sync_mode if m == EX and sync_mode == SH
runnable = false
case m
when UN
Err::UnknownLocker.Fail(Thread.current)
when EX
if sync_ex_locker == Thread.current
if (self.sync_ex_count = sync_ex_count - 1) == 0
self.sync_ex_locker = nil
if sync_sh_locker.include?(Thread.current)
self.sync_mode = SH
else
self.sync_mode = UN
end
runnable = true
end
else
Err::UnknownLocker.Fail(Thread.current)
end
when SH
if (count = sync_sh_locker[Thread.current]).nil?
Err::UnknownLocker.Fail(Thread.current)
else
if (sync_sh_locker[Thread.current] = count - 1) == 0
sync_sh_locker.delete(Thread.current)
if sync_sh_locker.empty? and sync_ex_count == 0
self.sync_mode = UN
runnable = true
end
end
end
end
if runnable
if sync_upgrade_waiting.size > 0
th, count = sync_upgrade_waiting.shift
sync_sh_locker[th] = count
th.wakeup
wakeup_threads.push th
else
wait = sync_waiting
self.sync_waiting = []
for th in wait
th.wakeup
wakeup_threads.push th
end
end
end
end
for th in wakeup_threads
th.run
end
self
end
def sync_synchronize(mode = EX)
sync_lock(mode)
begin
yield
ensure
sync_unlock
end
end
attr_accessor :sync_mode
attr_accessor :sync_waiting
attr_accessor :sync_upgrade_waiting
attr_accessor :sync_sh_locker
attr_accessor :sync_ex_locker
attr_accessor :sync_ex_count
def sync_inspect
sync_iv = instance_variables.select{|iv| /^@sync_/ =~ iv.id2name}.collect{|iv| iv.id2name + '=' + instance_eval(iv.id2name).inspect}.join(",")
print "<#{self.class}.extend Sync_m: #{inspect}, <Sync_m: #{sync_iv}>"
end
private
def sync_initialize
@sync_mode = UN
@sync_waiting = []
@sync_upgrade_waiting = []
@sync_sh_locker = Hash.new
@sync_ex_locker = nil
@sync_ex_count = 0
@sync_mutex = Mutex.new
end
def initialize(*args)
super
sync_initialize
end
def sync_try_lock_sub(m)
case m
when SH
case sync_mode
when UN
self.sync_mode = m
sync_sh_locker[Thread.current] = 1
ret = true
when SH
count = 0 unless count = sync_sh_locker[Thread.current]
sync_sh_locker[Thread.current] = count + 1
ret = true
when EX
# in EX mode, lock will upgrade to EX lock
if sync_ex_locker == Thread.current
self.sync_ex_count = sync_ex_count + 1
ret = true
else
ret = false
end
end
when EX
if sync_mode == UN or
sync_mode == SH && sync_sh_locker.size == 1 && sync_sh_locker.include?(Thread.current)
self.sync_mode = m
self.sync_ex_locker = Thread.current
self.sync_ex_count = 1
ret = true
elsif sync_mode == EX && sync_ex_locker == Thread.current
self.sync_ex_count = sync_ex_count + 1
ret = true
else
ret = false
end
else
Err::LockModeFailer.Fail mode
end
return ret
end
end
Synchronizer_m = Sync_m
class Sync
include Sync_m
end
Synchronizer = Sync
| 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/ostruct.rb | tools/jruby-1.5.1/lib/ruby/1.9/ostruct.rb | #
# = ostruct.rb: OpenStruct implementation
#
# Author:: Yukihiro Matsumoto
# Documentation:: Gavin Sinclair
#
# OpenStruct allows the creation of data objects with arbitrary attributes.
# See OpenStruct for an example.
#
#
# OpenStruct allows you to create data objects and set arbitrary attributes.
# For example:
#
# require 'ostruct'
#
# record = OpenStruct.new
# record.name = "John Smith"
# record.age = 70
# record.pension = 300
#
# puts record.name # -> "John Smith"
# puts record.address # -> nil
#
# It is like a hash with a different way to access the data. In fact, it is
# implemented with a hash, and you can initialize it with one.
#
# hash = { "country" => "Australia", :population => 20_000_000 }
# data = OpenStruct.new(hash)
#
# p data # -> <OpenStruct country="Australia" population=20000000>
#
class OpenStruct
#
# Create a new OpenStruct object. The optional +hash+, if given, will
# generate attributes and values. For example.
#
# require 'ostruct'
# hash = { "country" => "Australia", :population => 20_000_000 }
# data = OpenStruct.new(hash)
#
# p data # -> <OpenStruct country="Australia" population=20000000>
#
# By default, the resulting OpenStruct object will have no attributes.
#
def initialize(hash=nil)
@table = {}
if hash
for k,v in hash
@table[k.to_sym] = v
new_ostruct_member(k)
end
end
end
# Duplicate an OpenStruct object members.
def initialize_copy(orig)
super
@table = @table.dup
end
def marshal_dump
@table
end
def marshal_load(x)
@table = x
@table.each_key{|key| new_ostruct_member(key)}
end
def modifiable
begin
@modifiable = true
rescue
raise TypeError, "can't modify frozen #{self.class}", caller(3)
end
@table
end
protected :modifiable
def new_ostruct_member(name)
name = name.to_sym
unless self.respond_to?(name)
class << self; self; end.class_eval do
define_method(name) { @table[name] }
define_method("#{name}=") { |x| modifiable[name] = x }
end
end
name
end
def method_missing(mid, *args) # :nodoc:
mname = mid.id2name
len = args.length
if mname.chomp!('=')
if len != 1
raise ArgumentError, "wrong number of arguments (#{len} for 1)", caller(1)
end
modifiable[new_ostruct_member(mname)] = args[0]
elsif len == 0
@table[mid]
else
raise NoMethodError, "undefined method `#{mname}' for #{self}", caller(1)
end
end
#
# Remove the named field from the object.
#
def delete_field(name)
@table.delete name.to_sym
end
InspectKey = :__inspect_key__ # :nodoc:
#
# Returns a string containing a detailed summary of the keys and values.
#
def inspect
str = "#<#{self.class}"
ids = (Thread.current[InspectKey] ||= [])
if ids.include?(object_id)
return str << ' ...>'
end
ids << object_id
begin
first = true
for k,v in @table
str << "," unless first
first = false
str << " #{k}=#{v.inspect}"
end
return str << '>'
ensure
ids.pop
end
end
alias :to_s :inspect
attr_reader :table # :nodoc:
protected :table
#
# Compare this object and +other+ for equality.
#
def ==(other)
return false unless(other.kind_of?(OpenStruct))
return @table == other.table
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/benchmark.rb | tools/jruby-1.5.1/lib/ruby/1.9/benchmark.rb | =begin
#
# benchmark.rb - a performance benchmarking library
#
# $Id: benchmark.rb 22784 2009-03-06 03:56:38Z nobu $
#
# Created by Gotoken (gotoken@notwork.org).
#
# Documentation by Gotoken (original RD), Lyle Johnson (RDoc conversion), and
# Gavin Sinclair (editing).
#
=end
# == Overview
#
# The Benchmark module provides methods for benchmarking Ruby code, giving
# detailed reports on the time taken for each task.
#
# The Benchmark module provides methods to measure and report the time
# used to execute Ruby code.
#
# * Measure the time to construct the string given by the expression
# <tt>"a"*1_000_000</tt>:
#
# require 'benchmark'
#
# puts Benchmark.measure { "a"*1_000_000 }
#
# On my machine (FreeBSD 3.2 on P5, 100MHz) this generates:
#
# 1.166667 0.050000 1.216667 ( 0.571355)
#
# This report shows the user CPU time, system CPU time, the sum of
# the user and system CPU times, and the elapsed real time. The unit
# of time is seconds.
#
# * Do some experiments sequentially using the #bm method:
#
# require 'benchmark'
#
# n = 50000
# Benchmark.bm do |x|
# x.report { for i in 1..n; a = "1"; end }
# x.report { n.times do ; a = "1"; end }
# x.report { 1.upto(n) do ; a = "1"; end }
# end
#
# The result:
#
# user system total real
# 1.033333 0.016667 1.016667 ( 0.492106)
# 1.483333 0.000000 1.483333 ( 0.694605)
# 1.516667 0.000000 1.516667 ( 0.711077)
#
# * Continuing the previous example, put a label in each report:
#
# require 'benchmark'
#
# n = 50000
# Benchmark.bm(7) do |x|
# x.report("for:") { for i in 1..n; a = "1"; end }
# x.report("times:") { n.times do ; a = "1"; end }
# x.report("upto:") { 1.upto(n) do ; a = "1"; end }
# end
#
# The result:
#
# user system total real
# for: 1.050000 0.000000 1.050000 ( 0.503462)
# times: 1.533333 0.016667 1.550000 ( 0.735473)
# upto: 1.500000 0.016667 1.516667 ( 0.711239)
#
#
# * The times for some benchmarks depend on the order in which items
# are run. These differences are due to the cost of memory
# allocation and garbage collection. To avoid these discrepancies,
# the #bmbm method is provided. For example, to compare ways to
# sort an array of floats:
#
# require 'benchmark'
#
# array = (1..1000000).map { rand }
#
# Benchmark.bmbm do |x|
# x.report("sort!") { array.dup.sort! }
# x.report("sort") { array.dup.sort }
# end
#
# The result:
#
# Rehearsal -----------------------------------------
# sort! 11.928000 0.010000 11.938000 ( 12.756000)
# sort 13.048000 0.020000 13.068000 ( 13.857000)
# ------------------------------- total: 25.006000sec
#
# user system total real
# sort! 12.959000 0.010000 12.969000 ( 13.793000)
# sort 12.007000 0.000000 12.007000 ( 12.791000)
#
#
# * Report statistics of sequential experiments with unique labels,
# using the #benchmark method:
#
# require 'benchmark'
# include Benchmark # we need the CAPTION and FMTSTR constants
#
# n = 50000
# Benchmark.benchmark(" "*7 + CAPTION, 7, FMTSTR, ">total:", ">avg:") do |x|
# tf = x.report("for:") { for i in 1..n; a = "1"; end }
# tt = x.report("times:") { n.times do ; a = "1"; end }
# tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end }
# [tf+tt+tu, (tf+tt+tu)/3]
# end
#
# The result:
#
# user system total real
# for: 1.016667 0.016667 1.033333 ( 0.485749)
# times: 1.450000 0.016667 1.466667 ( 0.681367)
# upto: 1.533333 0.000000 1.533333 ( 0.722166)
# >total: 4.000000 0.033333 4.033333 ( 1.889282)
# >avg: 1.333333 0.011111 1.344444 ( 0.629761)
module Benchmark
BENCHMARK_VERSION = "2002-04-25" #:nodoc"
def Benchmark::times() # :nodoc:
Process::times()
end
# Invokes the block with a <tt>Benchmark::Report</tt> object, which
# may be used to collect and report on the results of individual
# benchmark tests. Reserves <i>label_width</i> leading spaces for
# labels on each line. Prints _caption_ at the top of the
# report, and uses _fmt_ to format each line.
# If the block returns an array of
# <tt>Benchmark::Tms</tt> objects, these will be used to format
# additional lines of output. If _label_ parameters are
# given, these are used to label these extra lines.
#
# _Note_: Other methods provide a simpler interface to this one, and are
# suitable for nearly all benchmarking requirements. See the examples in
# Benchmark, and the #bm and #bmbm methods.
#
# Example:
#
# require 'benchmark'
# include Benchmark # we need the CAPTION and FMTSTR constants
#
# n = 50000
# Benchmark.benchmark(" "*7 + CAPTION, 7, FMTSTR, ">total:", ">avg:") do |x|
# tf = x.report("for:") { for i in 1..n; a = "1"; end }
# tt = x.report("times:") { n.times do ; a = "1"; end }
# tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end }
# [tf+tt+tu, (tf+tt+tu)/3]
# end
#
# <i>Generates:</i>
#
# user system total real
# for: 1.016667 0.016667 1.033333 ( 0.485749)
# times: 1.450000 0.016667 1.466667 ( 0.681367)
# upto: 1.533333 0.000000 1.533333 ( 0.722166)
# >total: 4.000000 0.033333 4.033333 ( 1.889282)
# >avg: 1.333333 0.011111 1.344444 ( 0.629761)
#
def benchmark(caption = "", label_width = nil, fmtstr = nil, *labels) # :yield: report
sync = STDOUT.sync
STDOUT.sync = true
label_width ||= 0
fmtstr ||= FMTSTR
raise ArgumentError, "no block" unless iterator?
print caption
results = yield(Report.new(label_width, fmtstr))
Array === results and results.grep(Tms).each {|t|
print((labels.shift || t.label || "").ljust(label_width),
t.format(fmtstr))
}
STDOUT.sync = sync
end
# A simple interface to the #benchmark method, #bm is generates sequential reports
# with labels. The parameters have the same meaning as for #benchmark.
#
# require 'benchmark'
#
# n = 50000
# Benchmark.bm(7) do |x|
# x.report("for:") { for i in 1..n; a = "1"; end }
# x.report("times:") { n.times do ; a = "1"; end }
# x.report("upto:") { 1.upto(n) do ; a = "1"; end }
# end
#
# <i>Generates:</i>
#
# user system total real
# for: 1.050000 0.000000 1.050000 ( 0.503462)
# times: 1.533333 0.016667 1.550000 ( 0.735473)
# upto: 1.500000 0.016667 1.516667 ( 0.711239)
#
def bm(label_width = 0, *labels, &blk) # :yield: report
benchmark(" "*label_width + CAPTION, label_width, FMTSTR, *labels, &blk)
end
# Sometimes benchmark results are skewed because code executed
# earlier encounters different garbage collection overheads than
# that run later. #bmbm attempts to minimize this effect by running
# the tests twice, the first time as a rehearsal in order to get the
# runtime environment stable, the second time for
# real. <tt>GC.start</tt> is executed before the start of each of
# the real timings; the cost of this is not included in the
# timings. In reality, though, there's only so much that #bmbm can
# do, and the results are not guaranteed to be isolated from garbage
# collection and other effects.
#
# Because #bmbm takes two passes through the tests, it can
# calculate the required label width.
#
# require 'benchmark'
#
# array = (1..1000000).map { rand }
#
# Benchmark.bmbm do |x|
# x.report("sort!") { array.dup.sort! }
# x.report("sort") { array.dup.sort }
# end
#
# <i>Generates:</i>
#
# Rehearsal -----------------------------------------
# sort! 11.928000 0.010000 11.938000 ( 12.756000)
# sort 13.048000 0.020000 13.068000 ( 13.857000)
# ------------------------------- total: 25.006000sec
#
# user system total real
# sort! 12.959000 0.010000 12.969000 ( 13.793000)
# sort 12.007000 0.000000 12.007000 ( 12.791000)
#
# #bmbm yields a Benchmark::Job object and returns an array of
# Benchmark::Tms objects.
#
def bmbm(width = 0, &blk) # :yield: job
job = Job.new(width)
yield(job)
width = job.width
sync = STDOUT.sync
STDOUT.sync = true
# rehearsal
print "Rehearsal "
puts '-'*(width+CAPTION.length - "Rehearsal ".length)
list = []
job.list.each{|label,item|
print(label.ljust(width))
res = Benchmark::measure(&item)
print res.format()
list.push res
}
sum = Tms.new; list.each{|i| sum += i}
ets = sum.format("total: %tsec")
printf("%s %s\n\n",
"-"*(width+CAPTION.length-ets.length-1), ets)
# take
print ' '*width, CAPTION
list = []
ary = []
job.list.each{|label,item|
GC::start
print label.ljust(width)
res = Benchmark::measure(&item)
print res.format()
ary.push res
list.push [label, res]
}
STDOUT.sync = sync
ary
end
#
# Returns the time used to execute the given block as a
# Benchmark::Tms object.
#
def measure(label = "") # :yield:
t0, r0 = Benchmark.times, Time.now
yield
t1, r1 = Benchmark.times, Time.now
Benchmark::Tms.new(t1.utime - t0.utime,
t1.stime - t0.stime,
t1.cutime - t0.cutime,
t1.cstime - t0.cstime,
r1.to_f - r0.to_f,
label)
end
#
# Returns the elapsed real time used to execute the given block.
#
def realtime(&blk) # :yield:
r0 = Time.now
yield
r1 = Time.now
r1.to_f - r0.to_f
end
#
# A Job is a sequence of labelled blocks to be processed by the
# Benchmark.bmbm method. It is of little direct interest to the user.
#
class Job # :nodoc:
#
# Returns an initialized Job instance.
# Usually, one doesn't call this method directly, as new
# Job objects are created by the #bmbm method.
# _width_ is a initial value for the label offset used in formatting;
# the #bmbm method passes its _width_ argument to this constructor.
#
def initialize(width)
@width = width
@list = []
end
#
# Registers the given label and block pair in the job list.
#
def item(label = "", &blk) # :yield:
raise ArgumentError, "no block" unless block_given?
label += ' '
w = label.length
@width = w if @width < w
@list.push [label, blk]
self
end
alias report item
# An array of 2-element arrays, consisting of label and block pairs.
attr_reader :list
# Length of the widest label in the #list, plus one.
attr_reader :width
end
module_function :benchmark, :measure, :realtime, :bm, :bmbm
#
# This class is used by the Benchmark.benchmark and Benchmark.bm methods.
# It is of little direct interest to the user.
#
class Report # :nodoc:
#
# Returns an initialized Report instance.
# Usually, one doesn't call this method directly, as new
# Report objects are created by the #benchmark and #bm methods.
# _width_ and _fmtstr_ are the label offset and
# format string used by Tms#format.
#
def initialize(width = 0, fmtstr = nil)
@width, @fmtstr = width, fmtstr
end
#
# Prints the _label_ and measured time for the block,
# formatted by _fmt_. See Tms#format for the
# formatting rules.
#
def item(label = "", *fmt, &blk) # :yield:
print label.ljust(@width)
res = Benchmark::measure(&blk)
print res.format(@fmtstr, *fmt)
res
end
alias report item
end
#
# A data object, representing the times associated with a benchmark
# measurement.
#
class Tms
CAPTION = " user system total real\n"
FMTSTR = "%10.6u %10.6y %10.6t %10.6r\n"
# User CPU time
attr_reader :utime
# System CPU time
attr_reader :stime
# User CPU time of children
attr_reader :cutime
# System CPU time of children
attr_reader :cstime
# Elapsed real time
attr_reader :real
# Total time, that is _utime_ + _stime_ + _cutime_ + _cstime_
attr_reader :total
# Label
attr_reader :label
#
# Returns an initialized Tms object which has
# _u_ as the user CPU time, _s_ as the system CPU time,
# _cu_ as the children's user CPU time, _cs_ as the children's
# system CPU time, _real_ as the elapsed real time and _l_
# as the label.
#
def initialize(u = 0.0, s = 0.0, cu = 0.0, cs = 0.0, real = 0.0, l = nil)
@utime, @stime, @cutime, @cstime, @real, @label = u, s, cu, cs, real, l
@total = @utime + @stime + @cutime + @cstime
end
#
# Returns a new Tms object whose times are the sum of the times for this
# Tms object, plus the time required to execute the code block (_blk_).
#
def add(&blk) # :yield:
self + Benchmark::measure(&blk)
end
#
# An in-place version of #add.
#
def add!
t = Benchmark::measure(&blk)
@utime = utime + t.utime
@stime = stime + t.stime
@cutime = cutime + t.cutime
@cstime = cstime + t.cstime
@real = real + t.real
self
end
#
# Returns a new Tms object obtained by memberwise summation
# of the individual times for this Tms object with those of the other
# Tms object.
# This method and #/() are useful for taking statistics.
#
def +(other); memberwise(:+, other) end
#
# Returns a new Tms object obtained by memberwise subtraction
# of the individual times for the other Tms object from those of this
# Tms object.
#
def -(other); memberwise(:-, other) end
#
# Returns a new Tms object obtained by memberwise multiplication
# of the individual times for this Tms object by _x_.
#
def *(x); memberwise(:*, x) end
#
# Returns a new Tms object obtained by memberwise division
# of the individual times for this Tms object by _x_.
# This method and #+() are useful for taking statistics.
#
def /(x); memberwise(:/, x) end
#
# Returns the contents of this Tms object as
# a formatted string, according to a format string
# like that passed to Kernel.format. In addition, #format
# accepts the following extensions:
#
# <tt>%u</tt>:: Replaced by the user CPU time, as reported by Tms#utime.
# <tt>%y</tt>:: Replaced by the system CPU time, as reported by #stime (Mnemonic: y of "s*y*stem")
# <tt>%U</tt>:: Replaced by the children's user CPU time, as reported by Tms#cutime
# <tt>%Y</tt>:: Replaced by the children's system CPU time, as reported by Tms#cstime
# <tt>%t</tt>:: Replaced by the total CPU time, as reported by Tms#total
# <tt>%r</tt>:: Replaced by the elapsed real time, as reported by Tms#real
# <tt>%n</tt>:: Replaced by the label string, as reported by Tms#label (Mnemonic: n of "*n*ame")
#
# If _fmtstr_ is not given, FMTSTR is used as default value, detailing the
# user, system and real elapsed time.
#
def format(arg0 = nil, *args)
fmtstr = (arg0 || FMTSTR).dup
fmtstr.gsub!(/(%[-+\.\d]*)n/){"#{$1}s" % label}
fmtstr.gsub!(/(%[-+\.\d]*)u/){"#{$1}f" % utime}
fmtstr.gsub!(/(%[-+\.\d]*)y/){"#{$1}f" % stime}
fmtstr.gsub!(/(%[-+\.\d]*)U/){"#{$1}f" % cutime}
fmtstr.gsub!(/(%[-+\.\d]*)Y/){"#{$1}f" % cstime}
fmtstr.gsub!(/(%[-+\.\d]*)t/){"#{$1}f" % total}
fmtstr.gsub!(/(%[-+\.\d]*)r/){"(#{$1}f)" % real}
arg0 ? Kernel::format(fmtstr, *args) : fmtstr
end
#
# Same as #format.
#
def to_s
format
end
#
# Returns a new 6-element array, consisting of the
# label, user CPU time, system CPU time, children's
# user CPU time, children's system CPU time and elapsed
# real time.
#
def to_a
[@label, @utime, @stime, @cutime, @cstime, @real]
end
protected
def memberwise(op, x)
case x
when Benchmark::Tms
Benchmark::Tms.new(utime.__send__(op, x.utime),
stime.__send__(op, x.stime),
cutime.__send__(op, x.cutime),
cstime.__send__(op, x.cstime),
real.__send__(op, x.real)
)
else
Benchmark::Tms.new(utime.__send__(op, x),
stime.__send__(op, x),
cutime.__send__(op, x),
cstime.__send__(op, x),
real.__send__(op, x)
)
end
end
end
# The default caption string (heading above the output times).
CAPTION = Benchmark::Tms::CAPTION
# The default format string used to display times. See also Benchmark::Tms#format.
FMTSTR = Benchmark::Tms::FMTSTR
end
if __FILE__ == $0
include Benchmark
n = ARGV[0].to_i.nonzero? || 50000
puts %Q([#{n} times iterations of `a = "1"'])
benchmark(" " + CAPTION, 7, FMTSTR) do |x|
x.report("for:") {for i in 1..n; a = "1"; end} # Benchmark::measure
x.report("times:") {n.times do ; a = "1"; end}
x.report("upto:") {1.upto(n) do ; a = "1"; end}
end
benchmark do
[
measure{for i in 1..n; a = "1"; end}, # Benchmark::measure
measure{n.times do ; a = "1"; end},
measure{1.upto(n) do ; a = "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/1.9/set.rb | tools/jruby-1.5.1/lib/ruby/1.9/set.rb | #!/usr/bin/env ruby
#--
# set.rb - defines the Set class
#++
# Copyright (c) 2002-2008 Akinori MUSHA <knu@iDaemons.org>
#
# Documentation by Akinori MUSHA and Gavin Sinclair.
#
# All rights reserved. You can redistribute and/or modify it under the same
# terms as Ruby.
#
# $Id: set.rb 23363 2009-05-07 17:32:48Z knu $
#
# == Overview
#
# This library provides the Set class, which deals with a collection
# of unordered values with no duplicates. It is a hybrid of Array's
# intuitive inter-operation facilities and Hash's fast lookup. If you
# need to keep values ordered, use the SortedSet class.
#
# The method +to_set+ is added to Enumerable for convenience.
#
# See the Set and SortedSet documentation for examples of usage.
#
# Set implements a collection of unordered values with no duplicates.
# This is a hybrid of Array's intuitive inter-operation facilities and
# Hash's fast lookup.
#
# The equality of each couple of elements is determined according to
# Object#eql? and Object#hash, since Set uses Hash as storage.
#
# Set is easy to use with Enumerable objects (implementing +each+).
# Most of the initializer methods and binary operators accept generic
# Enumerable objects besides sets and arrays. An Enumerable object
# can be converted to Set using the +to_set+ method.
#
# == Example
#
# require 'set'
# s1 = Set.new [1, 2] # -> #<Set: {1, 2}>
# s2 = [1, 2].to_set # -> #<Set: {1, 2}>
# s1 == s2 # -> true
# s1.add("foo") # -> #<Set: {1, 2, "foo"}>
# s1.merge([2, 6]) # -> #<Set: {6, 1, 2, "foo"}>
# s1.subset? s2 # -> false
# s2.subset? s1 # -> true
#
# == Contact
#
# - Akinori MUSHA <knu@iDaemons.org> (current maintainer)
#
class Set
include Enumerable
# Creates a new set containing the given objects.
def self.[](*ary)
new(ary)
end
# Creates a new set containing the elements of the given enumerable
# object.
#
# If a block is given, the elements of enum are preprocessed by the
# given block.
def initialize(enum = nil, &block) # :yields: o
@hash ||= Hash.new
enum.nil? and return
if block
enum.each { |o| add(block[o]) }
else
merge(enum)
end
end
# Copy internal hash.
def initialize_copy(orig)
@hash = orig.instance_eval{@hash}.dup
end
def freeze # :nodoc:
super
@hash.freeze
self
end
def taint # :nodoc:
super
@hash.taint
self
end
def untaint # :nodoc:
super
@hash.untaint
self
end
# Returns the number of elements.
def size
@hash.size
end
alias length size
# Returns true if the set contains no elements.
def empty?
@hash.empty?
end
# Removes all elements and returns self.
def clear
@hash.clear
self
end
# Replaces the contents of the set with the contents of the given
# enumerable object and returns self.
def replace(enum)
if enum.class == self.class
@hash.replace(enum.instance_eval { @hash })
else
clear
enum.each { |o| add(o) }
end
self
end
# Converts the set to an array. The order of elements is uncertain.
def to_a
@hash.keys
end
def flatten_merge(set, seen = Set.new)
set.each { |e|
if e.is_a?(Set)
if seen.include?(e_id = e.object_id)
raise ArgumentError, "tried to flatten recursive Set"
end
seen.add(e_id)
flatten_merge(e, seen)
seen.delete(e_id)
else
add(e)
end
}
self
end
protected :flatten_merge
# Returns a new set that is a copy of the set, flattening each
# containing set recursively.
def flatten
self.class.new.flatten_merge(self)
end
# Equivalent to Set#flatten, but replaces the receiver with the
# result in place. Returns nil if no modifications were made.
def flatten!
if detect { |e| e.is_a?(Set) }
replace(flatten())
else
nil
end
end
# Returns true if the set contains the given object.
def include?(o)
@hash.include?(o)
end
alias member? include?
# Returns true if the set is a superset of the given set.
def superset?(set)
set.is_a?(Set) or raise ArgumentError, "value must be a set"
return false if size < set.size
set.all? { |o| include?(o) }
end
# Returns true if the set is a proper superset of the given set.
def proper_superset?(set)
set.is_a?(Set) or raise ArgumentError, "value must be a set"
return false if size <= set.size
set.all? { |o| include?(o) }
end
# Returns true if the set is a subset of the given set.
def subset?(set)
set.is_a?(Set) or raise ArgumentError, "value must be a set"
return false if set.size < size
all? { |o| set.include?(o) }
end
# Returns true if the set is a proper subset of the given set.
def proper_subset?(set)
set.is_a?(Set) or raise ArgumentError, "value must be a set"
return false if set.size <= size
all? { |o| set.include?(o) }
end
# Calls the given block once for each element in the set, passing
# the element as parameter. Returns an enumerator if no block is
# given.
def each
block_given? or return enum_for(__method__)
@hash.each_key { |o| yield(o) }
self
end
# Adds the given object to the set and returns self. Use +merge+ to
# add many elements at once.
def add(o)
@hash[o] = true
self
end
alias << add
# Adds the given object to the set and returns self. If the
# object is already in the set, returns nil.
def add?(o)
if include?(o)
nil
else
add(o)
end
end
# Deletes the given object from the set and returns self. Use +subtract+ to
# delete many items at once.
def delete(o)
@hash.delete(o)
self
end
# Deletes the given object from the set and returns self. If the
# object is not in the set, returns nil.
def delete?(o)
if include?(o)
delete(o)
else
nil
end
end
# Deletes every element of the set for which block evaluates to
# true, and returns self.
def delete_if
block_given? or return enum_for(__method__)
to_a.each { |o| @hash.delete(o) if yield(o) }
self
end
# Replaces the elements with ones returned by collect().
def collect!
block_given? or return enum_for(__method__)
set = self.class.new
each { |o| set << yield(o) }
replace(set)
end
alias map! collect!
# Equivalent to Set#delete_if, but returns nil if no changes were
# made.
def reject!
block_given? or return enum_for(__method__)
n = size
delete_if { |o| yield(o) }
size == n ? nil : self
end
# Merges the elements of the given enumerable object to the set and
# returns self.
def merge(enum)
if enum.instance_of?(self.class)
@hash.update(enum.instance_variable_get(:@hash))
else
enum.each { |o| add(o) }
end
self
end
# Deletes every element that appears in the given enumerable object
# and returns self.
def subtract(enum)
enum.each { |o| delete(o) }
self
end
# Returns a new set built by merging the set and the elements of the
# given enumerable object.
def |(enum)
dup.merge(enum)
end
alias + | ##
alias union | ##
# Returns a new set built by duplicating the set, removing every
# element that appears in the given enumerable object.
def -(enum)
dup.subtract(enum)
end
alias difference - ##
# Returns a new set containing elements common to the set and the
# given enumerable object.
def &(enum)
n = self.class.new
enum.each { |o| n.add(o) if include?(o) }
n
end
alias intersection & ##
# Returns a new set containing elements exclusive between the set
# and the given enumerable object. (set ^ enum) is equivalent to
# ((set | enum) - (set & enum)).
def ^(enum)
n = Set.new(enum)
each { |o| if n.include?(o) then n.delete(o) else n.add(o) end }
n
end
# Returns true if two sets are equal. The equality of each couple
# of elements is defined according to Object#eql?.
def ==(set)
equal?(set) and return true
set.is_a?(Set) && size == set.size or return false
hash = @hash.dup
set.all? { |o| hash.include?(o) }
end
def hash # :nodoc:
@hash.hash
end
def eql?(o) # :nodoc:
return false unless o.is_a?(Set)
@hash.eql?(o.instance_eval{@hash})
end
# Classifies the set by the return value of the given block and
# returns a hash of {value => set of elements} pairs. The block is
# called once for each element of the set, passing the element as
# parameter.
#
# e.g.:
#
# require 'set'
# files = Set.new(Dir.glob("*.rb"))
# hash = files.classify { |f| File.mtime(f).year }
# p hash # => {2000=>#<Set: {"a.rb", "b.rb"}>,
# # 2001=>#<Set: {"c.rb", "d.rb", "e.rb"}>,
# # 2002=>#<Set: {"f.rb"}>}
def classify # :yields: o
block_given? or return enum_for(__method__)
h = {}
each { |i|
x = yield(i)
(h[x] ||= self.class.new).add(i)
}
h
end
# Divides the set into a set of subsets according to the commonality
# defined by the given block.
#
# If the arity of the block is 2, elements o1 and o2 are in common
# if block.call(o1, o2) is true. Otherwise, elements o1 and o2 are
# in common if block.call(o1) == block.call(o2).
#
# e.g.:
#
# require 'set'
# numbers = Set[1, 3, 4, 6, 9, 10, 11]
# set = numbers.divide { |i,j| (i - j).abs == 1 }
# p set # => #<Set: {#<Set: {1}>,
# # #<Set: {11, 9, 10}>,
# # #<Set: {3, 4}>,
# # #<Set: {6}>}>
def divide(&func)
func or return enum_for(__method__)
if func.arity == 2
require 'tsort'
class << dig = {} # :nodoc:
include TSort
alias tsort_each_node each_key
def tsort_each_child(node, &block)
fetch(node).each(&block)
end
end
each { |u|
dig[u] = a = []
each{ |v| func.call(u, v) and a << v }
}
set = Set.new()
dig.each_strongly_connected_component { |css|
set.add(self.class.new(css))
}
set
else
Set.new(classify(&func).values)
end
end
InspectKey = :__inspect_key__ # :nodoc:
# Returns a string containing a human-readable representation of the
# set. ("#<Set: {element1, element2, ...}>")
def inspect
ids = (Thread.current[InspectKey] ||= [])
if ids.include?(object_id)
return sprintf('#<%s: {...}>', self.class.name)
end
begin
ids << object_id
return sprintf('#<%s: {%s}>', self.class, to_a.inspect[1..-2])
ensure
ids.pop
end
end
def pretty_print(pp) # :nodoc:
pp.text sprintf('#<%s: {', self.class.name)
pp.nest(1) {
pp.seplist(self) { |o|
pp.pp o
}
}
pp.text "}>"
end
def pretty_print_cycle(pp) # :nodoc:
pp.text sprintf('#<%s: {%s}>', self.class.name, empty? ? '' : '...')
end
end
#
# SortedSet implements a Set that guarantees that it's element are
# yielded in sorted order (according to the return values of their
# #<=> methods) when iterating over them.
#
# All elements that are added to a SortedSet must respond to the <=>
# method for comparison.
#
# Also, all elements must be <em>mutually comparable</em>: <tt>el1 <=>
# el2</tt> must not return <tt>nil</tt> for any elements <tt>el1</tt>
# and <tt>el2</tt>, else an ArgumentError will be raised when
# iterating over the SortedSet.
#
# == Example
#
# require "set"
#
# set = SortedSet.new([2, 1, 5, 6, 4, 5, 3, 3, 3])
# ary = []
#
# set.each do |obj|
# ary << obj
# end
#
# p ary # => [1, 2, 3, 4, 5, 6]
#
# set2 = SortedSet.new([1, 2, "3"])
# set2.each { |obj| } # => raises ArgumentError: comparison of Fixnum with String failed
#
class SortedSet < Set
@@setup = false
class << self
def [](*ary) # :nodoc:
new(ary)
end
def setup # :nodoc:
@@setup and return
module_eval {
# a hack to shut up warning
alias old_init initialize
remove_method :old_init
}
begin
require 'rbtree'
module_eval %{
def initialize(*args, &block)
@hash = RBTree.new
super
end
def add(o)
o.respond_to?(:<=>) or raise ArgumentError, "value must repond to <=>"
super
end
alias << add
}
rescue LoadError
module_eval %{
def initialize(*args, &block)
@keys = nil
super
end
def clear
@keys = nil
super
end
def replace(enum)
@keys = nil
super
end
def add(o)
o.respond_to?(:<=>) or raise ArgumentError, "value must respond to <=>"
@keys = nil
super
end
alias << add
def delete(o)
@keys = nil
@hash.delete(o)
self
end
def delete_if
block_given? or return enum_for(__method__)
n = @hash.size
super
@keys = nil if @hash.size != n
self
end
def merge(enum)
@keys = nil
super
end
def each
block_given? or return enum_for(__method__)
to_a.each { |o| yield(o) }
self
end
def to_a
(@keys = @hash.keys).sort! unless @keys
@keys
end
}
end
@@setup = true
end
end
def initialize(*args, &block) # :nodoc:
SortedSet.setup
initialize(*args, &block)
end
end
module Enumerable
# Makes a set from the enumerable object with given arguments.
# Needs to +require "set"+ to use this method.
def to_set(klass = Set, *args, &block)
klass.new(self, *args, &block)
end
end
# =begin
# == RestricedSet class
# RestricedSet implements a set with restrictions defined by a given
# block.
#
# === Super class
# Set
#
# === Class Methods
# --- RestricedSet::new(enum = nil) { |o| ... }
# --- RestricedSet::new(enum = nil) { |rset, o| ... }
# Creates a new restricted set containing the elements of the given
# enumerable object. Restrictions are defined by the given block.
#
# If the block's arity is 2, it is called with the RestrictedSet
# itself and an object to see if the object is allowed to be put in
# the set.
#
# Otherwise, the block is called with an object to see if the object
# is allowed to be put in the set.
#
# === Instance Methods
# --- restriction_proc
# Returns the restriction procedure of the set.
#
# =end
#
# class RestricedSet < Set
# def initialize(*args, &block)
# @proc = block or raise ArgumentError, "missing a block"
#
# if @proc.arity == 2
# instance_eval %{
# def add(o)
# @hash[o] = true if @proc.call(self, o)
# self
# end
# alias << add
#
# def add?(o)
# if include?(o) || !@proc.call(self, o)
# nil
# else
# @hash[o] = true
# self
# end
# end
#
# def replace(enum)
# clear
# enum.each { |o| add(o) }
#
# self
# end
#
# def merge(enum)
# enum.each { |o| add(o) }
#
# self
# end
# }
# else
# instance_eval %{
# def add(o)
# if @proc.call(o)
# @hash[o] = true
# end
# self
# end
# alias << add
#
# def add?(o)
# if include?(o) || !@proc.call(o)
# nil
# else
# @hash[o] = true
# self
# end
# end
# }
# end
#
# super(*args)
# end
#
# def restriction_proc
# @proc
# end
# end
if $0 == __FILE__
eval DATA.read, nil, $0, __LINE__+4
end
__END__
require 'test/unit'
class TC_Set < Test::Unit::TestCase
def test_aref
assert_nothing_raised {
Set[]
Set[nil]
Set[1,2,3]
}
assert_equal(0, Set[].size)
assert_equal(1, Set[nil].size)
assert_equal(1, Set[[]].size)
assert_equal(1, Set[[nil]].size)
set = Set[2,4,6,4]
assert_equal(Set.new([2,4,6]), set)
end
def test_s_new
assert_nothing_raised {
Set.new()
Set.new(nil)
Set.new([])
Set.new([1,2])
Set.new('a'..'c')
}
assert_raises(NoMethodError) {
Set.new(false)
}
assert_raises(NoMethodError) {
Set.new(1)
}
assert_raises(ArgumentError) {
Set.new(1,2)
}
assert_equal(0, Set.new().size)
assert_equal(0, Set.new(nil).size)
assert_equal(0, Set.new([]).size)
assert_equal(1, Set.new([nil]).size)
ary = [2,4,6,4]
set = Set.new(ary)
ary.clear
assert_equal(false, set.empty?)
assert_equal(3, set.size)
ary = [1,2,3]
s = Set.new(ary) { |o| o * 2 }
assert_equal([2,4,6], s.sort)
end
def test_clone
set1 = Set.new
set2 = set1.clone
set1 << 'abc'
assert_equal(Set.new, set2)
end
def test_dup
set1 = Set[1,2]
set2 = set1.dup
assert_not_same(set1, set2)
assert_equal(set1, set2)
set1.add(3)
assert_not_equal(set1, set2)
end
def test_size
assert_equal(0, Set[].size)
assert_equal(2, Set[1,2].size)
assert_equal(2, Set[1,2,1].size)
end
def test_empty?
assert_equal(true, Set[].empty?)
assert_equal(false, Set[1, 2].empty?)
end
def test_clear
set = Set[1,2]
ret = set.clear
assert_same(set, ret)
assert_equal(true, set.empty?)
end
def test_replace
set = Set[1,2]
ret = set.replace('a'..'c')
assert_same(set, ret)
assert_equal(Set['a','b','c'], set)
end
def test_to_a
set = Set[1,2,3,2]
ary = set.to_a
assert_equal([1,2,3], ary.sort)
end
def test_flatten
# test1
set1 = Set[
1,
Set[
5,
Set[7,
Set[0]
],
Set[6,2],
1
],
3,
Set[3,4]
]
set2 = set1.flatten
set3 = Set.new(0..7)
assert_not_same(set2, set1)
assert_equal(set3, set2)
# test2; destructive
orig_set1 = set1
set1.flatten!
assert_same(orig_set1, set1)
assert_equal(set3, set1)
# test3; multiple occurrences of a set in an set
set1 = Set[1, 2]
set2 = Set[set1, Set[set1, 4], 3]
assert_nothing_raised {
set2.flatten!
}
assert_equal(Set.new(1..4), set2)
# test4; recursion
set2 = Set[]
set1 = Set[1, set2]
set2.add(set1)
assert_raises(ArgumentError) {
set1.flatten!
}
# test5; miscellaneous
empty = Set[]
set = Set[Set[empty, "a"],Set[empty, "b"]]
assert_nothing_raised {
set.flatten
}
set1 = empty.merge(Set["no_more", set])
assert_nil(Set.new(0..31).flatten!)
x = Set[Set[],Set[1,2]].flatten!
y = Set[1,2]
assert_equal(x, y)
end
def test_include?
set = Set[1,2,3]
assert_equal(true, set.include?(1))
assert_equal(true, set.include?(2))
assert_equal(true, set.include?(3))
assert_equal(false, set.include?(0))
assert_equal(false, set.include?(nil))
set = Set["1",nil,"2",nil,"0","1",false]
assert_equal(true, set.include?(nil))
assert_equal(true, set.include?(false))
assert_equal(true, set.include?("1"))
assert_equal(false, set.include?(0))
assert_equal(false, set.include?(true))
end
def test_superset?
set = Set[1,2,3]
assert_raises(ArgumentError) {
set.superset?()
}
assert_raises(ArgumentError) {
set.superset?(2)
}
assert_raises(ArgumentError) {
set.superset?([2])
}
assert_equal(true, set.superset?(Set[]))
assert_equal(true, set.superset?(Set[1,2]))
assert_equal(true, set.superset?(Set[1,2,3]))
assert_equal(false, set.superset?(Set[1,2,3,4]))
assert_equal(false, set.superset?(Set[1,4]))
assert_equal(true, Set[].superset?(Set[]))
end
def test_proper_superset?
set = Set[1,2,3]
assert_raises(ArgumentError) {
set.proper_superset?()
}
assert_raises(ArgumentError) {
set.proper_superset?(2)
}
assert_raises(ArgumentError) {
set.proper_superset?([2])
}
assert_equal(true, set.proper_superset?(Set[]))
assert_equal(true, set.proper_superset?(Set[1,2]))
assert_equal(false, set.proper_superset?(Set[1,2,3]))
assert_equal(false, set.proper_superset?(Set[1,2,3,4]))
assert_equal(false, set.proper_superset?(Set[1,4]))
assert_equal(false, Set[].proper_superset?(Set[]))
end
def test_subset?
set = Set[1,2,3]
assert_raises(ArgumentError) {
set.subset?()
}
assert_raises(ArgumentError) {
set.subset?(2)
}
assert_raises(ArgumentError) {
set.subset?([2])
}
assert_equal(true, set.subset?(Set[1,2,3,4]))
assert_equal(true, set.subset?(Set[1,2,3]))
assert_equal(false, set.subset?(Set[1,2]))
assert_equal(false, set.subset?(Set[]))
assert_equal(true, Set[].subset?(Set[1]))
assert_equal(true, Set[].subset?(Set[]))
end
def test_proper_subset?
set = Set[1,2,3]
assert_raises(ArgumentError) {
set.proper_subset?()
}
assert_raises(ArgumentError) {
set.proper_subset?(2)
}
assert_raises(ArgumentError) {
set.proper_subset?([2])
}
assert_equal(true, set.proper_subset?(Set[1,2,3,4]))
assert_equal(false, set.proper_subset?(Set[1,2,3]))
assert_equal(false, set.proper_subset?(Set[1,2]))
assert_equal(false, set.proper_subset?(Set[]))
assert_equal(false, Set[].proper_subset?(Set[]))
end
def test_each
ary = [1,3,5,7,10,20]
set = Set.new(ary)
ret = set.each { |o| }
assert_same(set, ret)
e = set.each
assert_instance_of(Enumerator, e)
assert_nothing_raised {
set.each { |o|
ary.delete(o) or raise "unexpected element: #{o}"
}
ary.empty? or raise "forgotten elements: #{ary.join(', ')}"
}
end
def test_add
set = Set[1,2,3]
ret = set.add(2)
assert_same(set, ret)
assert_equal(Set[1,2,3], set)
ret = set.add?(2)
assert_nil(ret)
assert_equal(Set[1,2,3], set)
ret = set.add(4)
assert_same(set, ret)
assert_equal(Set[1,2,3,4], set)
ret = set.add?(5)
assert_same(set, ret)
assert_equal(Set[1,2,3,4,5], set)
end
def test_delete
set = Set[1,2,3]
ret = set.delete(4)
assert_same(set, ret)
assert_equal(Set[1,2,3], set)
ret = set.delete?(4)
assert_nil(ret)
assert_equal(Set[1,2,3], set)
ret = set.delete(2)
assert_equal(set, ret)
assert_equal(Set[1,3], set)
ret = set.delete?(1)
assert_equal(set, ret)
assert_equal(Set[3], set)
end
def test_delete_if
set = Set.new(1..10)
ret = set.delete_if { |i| i > 10 }
assert_same(set, ret)
assert_equal(Set.new(1..10), set)
set = Set.new(1..10)
ret = set.delete_if { |i| i % 3 == 0 }
assert_same(set, ret)
assert_equal(Set[1,2,4,5,7,8,10], set)
end
def test_collect!
set = Set[1,2,3,'a','b','c',-1..1,2..4]
ret = set.collect! { |i|
case i
when Numeric
i * 2
when String
i.upcase
else
nil
end
}
assert_same(set, ret)
assert_equal(Set[2,4,6,'A','B','C',nil], set)
end
def test_reject!
set = Set.new(1..10)
ret = set.reject! { |i| i > 10 }
assert_nil(ret)
assert_equal(Set.new(1..10), set)
ret = set.reject! { |i| i % 3 == 0 }
assert_same(set, ret)
assert_equal(Set[1,2,4,5,7,8,10], set)
end
def test_merge
set = Set[1,2,3]
ret = set.merge([2,4,6])
assert_same(set, ret)
assert_equal(Set[1,2,3,4,6], set)
end
def test_subtract
set = Set[1,2,3]
ret = set.subtract([2,4,6])
assert_same(set, ret)
assert_equal(Set[1,3], set)
end
def test_plus
set = Set[1,2,3]
ret = set + [2,4,6]
assert_not_same(set, ret)
assert_equal(Set[1,2,3,4,6], ret)
end
def test_minus
set = Set[1,2,3]
ret = set - [2,4,6]
assert_not_same(set, ret)
assert_equal(Set[1,3], ret)
end
def test_and
set = Set[1,2,3,4]
ret = set & [2,4,6]
assert_not_same(set, ret)
assert_equal(Set[2,4], ret)
end
def test_xor
set = Set[1,2,3,4]
ret = set ^ [2,4,5,5]
assert_not_same(set, ret)
assert_equal(Set[1,3,5], ret)
end
def test_eq
set1 = Set[2,3,1]
set2 = Set[1,2,3]
assert_equal(set1, set1)
assert_equal(set1, set2)
assert_not_equal(Set[1], [1])
set1 = Class.new(Set)["a", "b"]
set2 = Set["a", "b", set1]
set1 = set1.add(set1.clone)
# assert_equal(set1, set2)
# assert_equal(set2, set1)
assert_equal(set2, set2.clone)
assert_equal(set1.clone, set1)
assert_not_equal(Set[Exception.new,nil], Set[Exception.new,Exception.new], "[ruby-dev:26127]")
end
# def test_hash
# end
# def test_eql?
# end
def test_classify
set = Set.new(1..10)
ret = set.classify { |i| i % 3 }
assert_equal(3, ret.size)
assert_instance_of(Hash, ret)
ret.each_value { |value| assert_instance_of(Set, value) }
assert_equal(Set[3,6,9], ret[0])
assert_equal(Set[1,4,7,10], ret[1])
assert_equal(Set[2,5,8], ret[2])
end
def test_divide
set = Set.new(1..10)
ret = set.divide { |i| i % 3 }
assert_equal(3, ret.size)
n = 0
ret.each { |s| n += s.size }
assert_equal(set.size, n)
assert_equal(set, ret.flatten)
set = Set[7,10,5,11,1,3,4,9,0]
ret = set.divide { |a,b| (a - b).abs == 1 }
assert_equal(4, ret.size)
n = 0
ret.each { |s| n += s.size }
assert_equal(set.size, n)
assert_equal(set, ret.flatten)
ret.each { |s|
if s.include?(0)
assert_equal(Set[0,1], s)
elsif s.include?(3)
assert_equal(Set[3,4,5], s)
elsif s.include?(7)
assert_equal(Set[7], s)
elsif s.include?(9)
assert_equal(Set[9,10,11], s)
else
raise "unexpected group: #{s.inspect}"
end
}
end
def test_inspect
set1 = Set[1]
assert_equal('#<Set: {1}>', set1.inspect)
set2 = Set[Set[0], 1, 2, set1]
assert_equal(false, set2.inspect.include?('#<Set: {...}>'))
set1.add(set2)
assert_equal(true, set1.inspect.include?('#<Set: {...}>'))
end
# def test_pretty_print
# end
# def test_pretty_print_cycle
# end
end
class TC_SortedSet < Test::Unit::TestCase
def test_sortedset
s = SortedSet[4,5,3,1,2]
assert_equal([1,2,3,4,5], s.to_a)
prev = nil
s.each { |o| assert(prev < o) if prev; prev = o }
assert_not_nil(prev)
s.map! { |o| -2 * o }
assert_equal([-10,-8,-6,-4,-2], s.to_a)
prev = nil
ret = s.each { |o| assert(prev < o) if prev; prev = o }
assert_not_nil(prev)
assert_same(s, ret)
s = SortedSet.new([2,1,3]) { |o| o * -2 }
assert_equal([-6,-4,-2], s.to_a)
s = SortedSet.new(['one', 'two', 'three', 'four'])
a = []
ret = s.delete_if { |o| a << o; o.start_with?('t') }
assert_same(s, ret)
assert_equal(['four', 'one'], s.to_a)
assert_equal(['four', 'one', 'three', 'two'], a)
s = SortedSet.new(['one', 'two', 'three', 'four'])
a = []
ret = s.reject! { |o| a << o; o.start_with?('t') }
assert_same(s, ret)
assert_equal(['four', 'one'], s.to_a)
assert_equal(['four', 'one', 'three', 'two'], a)
s = SortedSet.new(['one', 'two', 'three', 'four'])
a = []
ret = s.reject! { |o| a << o; false }
assert_same(nil, ret)
assert_equal(['four', 'one', 'three', 'two'], s.to_a)
assert_equal(['four', 'one', 'three', 'two'], a)
end
end
class TC_Enumerable < Test::Unit::TestCase
def test_to_set
ary = [2,5,4,3,2,1,3]
set = ary.to_set
assert_instance_of(Set, set)
assert_equal([1,2,3,4,5], set.sort)
set = ary.to_set { |o| o * -2 }
assert_instance_of(Set, set)
assert_equal([-10,-8,-6,-4,-2], set.sort)
set = ary.to_set(SortedSet)
assert_instance_of(SortedSet, set)
assert_equal([1,2,3,4,5], set.to_a)
set = ary.to_set(SortedSet) { |o| o * -2 }
assert_instance_of(SortedSet, set)
assert_equal([-10,-8,-6,-4,-2], set.sort)
end
end
# class TC_RestricedSet < Test::Unit::TestCase
# def test_s_new
# assert_raises(ArgumentError) { RestricedSet.new }
#
# s = RestricedSet.new([-1,2,3]) { |o| o > 0 }
# assert_equal([2,3], s.sort)
# end
#
# def test_restriction_proc
# s = RestricedSet.new([-1,2,3]) { |o| o > 0 }
#
# f = s.restriction_proc
# assert_instance_of(Proc, f)
# assert(f[1])
# assert(!f[0])
# end
#
# def test_replace
# s = RestricedSet.new(-3..3) { |o| o > 0 }
# assert_equal([1,2,3], s.sort)
#
# s.replace([-2,0,3,4,5])
# assert_equal([3,4,5], s.sort)
# end
#
# def test_merge
# s = RestricedSet.new { |o| o > 0 }
# s.merge(-5..5)
# assert_equal([1,2,3,4,5], s.sort)
#
# s.merge([10,-10,-8,8])
# assert_equal([1,2,3,4,5,8,10], s.sort)
# 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/time.rb | tools/jruby-1.5.1/lib/ruby/1.9/time.rb |
#
# == Introduction
#
# This library extends the Time class:
# * conversion between date string and time object.
# * date-time defined by RFC 2822
# * HTTP-date defined by RFC 2616
# * dateTime defined by XML Schema Part 2: Datatypes (ISO 8601)
# * various formats handled by Date._parse (string to time only)
#
# == Design Issues
#
# === Specialized interface
#
# This library provides methods dedicated to special purposes:
# * RFC 2822, RFC 2616 and XML Schema.
# * They makes usual life easier.
#
# === Doesn't depend on strftime
#
# This library doesn't use +strftime+. Especially #rfc2822 doesn't depend
# on +strftime+ because:
#
# * %a and %b are locale sensitive
#
# Since they are locale sensitive, they may be replaced to
# invalid weekday/month name in some locales.
# Since ruby-1.6 doesn't invoke setlocale by default,
# the problem doesn't arise until some external library invokes setlocale.
# Ruby/GTK is the example of such library.
#
# * %z is not portable
#
# %z is required to generate zone in date-time of RFC 2822
# but it is not portable.
#
require 'date/format'
#
# Implements the extensions to the Time class that are described in the
# documentation for the time.rb library.
#
class Time
class << Time
ZoneOffset = {
'UTC' => 0,
# ISO 8601
'Z' => 0,
# RFC 822
'UT' => 0, 'GMT' => 0,
'EST' => -5, 'EDT' => -4,
'CST' => -6, 'CDT' => -5,
'MST' => -7, 'MDT' => -6,
'PST' => -8, 'PDT' => -7,
# Following definition of military zones is original one.
# See RFC 1123 and RFC 2822 for the error in RFC 822.
'A' => +1, 'B' => +2, 'C' => +3, 'D' => +4, 'E' => +5, 'F' => +6,
'G' => +7, 'H' => +8, 'I' => +9, 'K' => +10, 'L' => +11, 'M' => +12,
'N' => -1, 'O' => -2, 'P' => -3, 'Q' => -4, 'R' => -5, 'S' => -6,
'T' => -7, 'U' => -8, 'V' => -9, 'W' => -10, 'X' => -11, 'Y' => -12,
}
def zone_offset(zone, year=self.now.year)
off = nil
zone = zone.upcase
if /\A([+-])(\d\d):?(\d\d)\z/ =~ zone
off = ($1 == '-' ? -1 : 1) * ($2.to_i * 60 + $3.to_i) * 60
elsif /\A[+-]\d\d\z/ =~ zone
off = zone.to_i * 3600
elsif ZoneOffset.include?(zone)
off = ZoneOffset[zone] * 3600
elsif ((t = self.local(year, 1, 1)).zone.upcase == zone rescue false)
off = t.utc_offset
elsif ((t = self.local(year, 7, 1)).zone.upcase == zone rescue false)
off = t.utc_offset
end
off
end
def zone_utc?(zone)
# * +0000
# In RFC 2822, +0000 indicate a time zone at Universal Time.
# Europe/London is "a time zone at Universal Time" in Winter.
# Europe/Lisbon is "a time zone at Universal Time" in Winter.
# Atlantic/Reykjavik is "a time zone at Universal Time".
# Africa/Dakar is "a time zone at Universal Time".
# So +0000 is a local time such as Europe/London, etc.
# * GMT
# GMT is used as a time zone abbreviation in Europe/London,
# Africa/Dakar, etc.
# So it is a local time.
#
# * -0000, -00:00
# In RFC 2822, -0000 the date-time contains no information about the
# local time zone.
# In RFC 3339, -00:00 is used for the time in UTC is known,
# but the offset to local time is unknown.
# They are not appropriate for specific time zone such as
# Europe/London because time zone neutral,
# So -00:00 and -0000 are treated as UTC.
if /\A(?:-00:00|-0000|-00|UTC|Z|UT)\z/i =~ zone
true
else
false
end
end
private :zone_utc?
LeapYearMonthDays = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
CommonYearMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def month_days(y, m)
if ((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)
LeapYearMonthDays[m-1]
else
CommonYearMonthDays[m-1]
end
end
private :month_days
def apply_offset(year, mon, day, hour, min, sec, off)
if off < 0
off = -off
off, o = off.divmod(60)
if o != 0 then sec += o; o, sec = sec.divmod(60); off += o end
off, o = off.divmod(60)
if o != 0 then min += o; o, min = min.divmod(60); off += o end
off, o = off.divmod(24)
if o != 0 then hour += o; o, hour = hour.divmod(24); off += o end
if off != 0
day += off
if month_days(year, mon) < day
mon += 1
if 12 < mon
mon = 1
year += 1
end
day = 1
end
end
elsif 0 < off
off, o = off.divmod(60)
if o != 0 then sec -= o; o, sec = sec.divmod(60); off -= o end
off, o = off.divmod(60)
if o != 0 then min -= o; o, min = min.divmod(60); off -= o end
off, o = off.divmod(24)
if o != 0 then hour -= o; o, hour = hour.divmod(24); off -= o end
if off != 0 then
day -= off
if day < 1
mon -= 1
if mon < 1
year -= 1
mon = 12
end
day = month_days(year, mon)
end
end
end
return year, mon, day, hour, min, sec
end
private :apply_offset
def make_time(year, mon, day, hour, min, sec, sec_fraction, zone, now)
usec = nil
usec = sec_fraction * 1000000 if sec_fraction
if now
begin
break if year; year = now.year
break if mon; mon = now.mon
break if day; day = now.day
break if hour; hour = now.hour
break if min; min = now.min
break if sec; sec = now.sec
break if sec_fraction; usec = now.tv_usec
end until true
end
year ||= 1970
mon ||= 1
day ||= 1
hour ||= 0
min ||= 0
sec ||= 0
usec ||= 0
off = nil
off = zone_offset(zone, year) if zone
if off
year, mon, day, hour, min, sec =
apply_offset(year, mon, day, hour, min, sec, off)
t = self.utc(year, mon, day, hour, min, sec, usec)
t.localtime if !zone_utc?(zone)
t
else
self.local(year, mon, day, hour, min, sec, usec)
end
end
private :make_time
#
# Parses +date+ using Date._parse and converts it to a Time object.
#
# If a block is given, the year described in +date+ is converted by the
# block. For example:
#
# Time.parse(...) {|y| 0 <= y && y < 100 ? (y >= 69 ? y + 1900 : y + 2000) : y}
#
# If the upper components of the given time are broken or missing, they are
# supplied with those of +now+. For the lower components, the minimum
# values (1 or 0) are assumed if broken or missing. For example:
#
# # Suppose it is "Thu Nov 29 14:33:20 GMT 2001" now and
# # your timezone is GMT:
# now = Time.parse("Thu Nov 29 14:33:20 GMT 2001")
# Time.parse("16:30", now) #=> 2001-11-29 16:30:00 +0900
# Time.parse("7/23", now) #=> 2001-07-23 00:00:00 +0900
# Time.parse("Aug 31", now) #=> 2001-08-31 00:00:00 +0900
# Time.parse("Aug 2000", now) #=> 2000-08-01 00:00:00 +0900
#
# Since there are numerous conflicts among locally defined timezone
# abbreviations all over the world, this method is not made to
# understand all of them. For example, the abbreviation "CST" is
# used variously as:
#
# -06:00 in America/Chicago,
# -05:00 in America/Havana,
# +08:00 in Asia/Harbin,
# +09:30 in Australia/Darwin,
# +10:30 in Australia/Adelaide,
# etc.
#
# Based on the fact, this method only understands the timezone
# abbreviations described in RFC 822 and the system timezone, in the
# order named. (i.e. a definition in RFC 822 overrides the system
# timezone definition.) The system timezone is taken from
# <tt>Time.local(year, 1, 1).zone</tt> and
# <tt>Time.local(year, 7, 1).zone</tt>.
# If the extracted timezone abbreviation does not match any of them,
# it is ignored and the given time is regarded as a local time.
#
# ArgumentError is raised if Date._parse cannot extract information from
# +date+ or Time class cannot represent specified date.
#
# This method can be used as fail-safe for other parsing methods as:
#
# Time.rfc2822(date) rescue Time.parse(date)
# Time.httpdate(date) rescue Time.parse(date)
# Time.xmlschema(date) rescue Time.parse(date)
#
# A failure for Time.parse should be checked, though.
#
def parse(date, now=self.now)
comp = !block_given?
d = Date._parse(date, comp)
if !d[:year] && !d[:mon] && !d[:mday] && !d[:hour] && !d[:min] && !d[:sec] && !d[:sec_fraction]
raise ArgumentError, "no time information in #{date.inspect}"
end
year = d[:year]
year = yield(year) if year && !comp
make_time(year, d[:mon], d[:mday], d[:hour], d[:min], d[:sec], d[:sec_fraction], d[:zone], now)
end
#
# Parses +date+ using Date._strptime and converts it to a Time object.
#
# If a block is given, the year described in +date+ is converted by the
# block. For example:
#
# Time.strptime(...) {|y| y < 100 ? (y >= 69 ? y + 1900 : y + 2000) : y}
def strptime(date, format, now=self.now)
d = Date._strptime(date, format)
raise ArgumentError, "invalid strptime format - `#{format}'" unless d
year = d[:year]
year = yield(year) if year && block_given?
make_time(year, d[:mon], d[:mday], d[:hour], d[:min], d[:sec], d[:sec_fraction], d[:zone], now)
end
MonthValue = {
'JAN' => 1, 'FEB' => 2, 'MAR' => 3, 'APR' => 4, 'MAY' => 5, 'JUN' => 6,
'JUL' => 7, 'AUG' => 8, 'SEP' => 9, 'OCT' =>10, 'NOV' =>11, 'DEC' =>12
}
#
# Parses +date+ as date-time defined by RFC 2822 and converts it to a Time
# object. The format is identical to the date format defined by RFC 822 and
# updated by RFC 1123.
#
# ArgumentError is raised if +date+ is not compliant with RFC 2822
# or Time class cannot represent specified date.
#
# See #rfc2822 for more information on this format.
#
def rfc2822(date)
if /\A\s*
(?:(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s*,\s*)?
(\d{1,2})\s+
(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+
(\d{2,})\s+
(\d{2})\s*
:\s*(\d{2})\s*
(?::\s*(\d{2}))?\s+
([+-]\d{4}|
UT|GMT|EST|EDT|CST|CDT|MST|MDT|PST|PDT|[A-IK-Z])/ix =~ date
# Since RFC 2822 permit comments, the regexp has no right anchor.
day = $1.to_i
mon = MonthValue[$2.upcase]
year = $3.to_i
hour = $4.to_i
min = $5.to_i
sec = $6 ? $6.to_i : 0
zone = $7
# following year completion is compliant with RFC 2822.
year = if year < 50
2000 + year
elsif year < 1000
1900 + year
else
year
end
year, mon, day, hour, min, sec =
apply_offset(year, mon, day, hour, min, sec, zone_offset(zone))
t = self.utc(year, mon, day, hour, min, sec)
t.localtime if !zone_utc?(zone)
t
else
raise ArgumentError.new("not RFC 2822 compliant date: #{date.inspect}")
end
end
alias rfc822 rfc2822
#
# Parses +date+ as HTTP-date defined by RFC 2616 and converts it to a Time
# object.
#
# ArgumentError is raised if +date+ is not compliant with RFC 2616 or Time
# class cannot represent specified date.
#
# See #httpdate for more information on this format.
#
def httpdate(date)
if /\A\s*
(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),\x20
(\d{2})\x20
(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\x20
(\d{4})\x20
(\d{2}):(\d{2}):(\d{2})\x20
GMT
\s*\z/ix =~ date
self.rfc2822(date)
elsif /\A\s*
(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday),\x20
(\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d)\x20
(\d\d):(\d\d):(\d\d)\x20
GMT
\s*\z/ix =~ date
year = $3.to_i
if year < 50
year += 2000
else
year += 1900
end
self.utc(year, $2, $1.to_i, $4.to_i, $5.to_i, $6.to_i)
elsif /\A\s*
(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\x20
(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\x20
(\d\d|\x20\d)\x20
(\d\d):(\d\d):(\d\d)\x20
(\d{4})
\s*\z/ix =~ date
self.utc($6.to_i, MonthValue[$1.upcase], $2.to_i,
$3.to_i, $4.to_i, $5.to_i)
else
raise ArgumentError.new("not RFC 2616 compliant date: #{date.inspect}")
end
end
#
# Parses +date+ as dateTime defined by XML Schema and converts it to a Time
# object. The format is restricted version of the format defined by ISO
# 8601.
#
# ArgumentError is raised if +date+ is not compliant with the format or Time
# class cannot represent specified date.
#
# See #xmlschema for more information on this format.
#
def xmlschema(date)
if /\A\s*
(-?\d+)-(\d\d)-(\d\d)
T
(\d\d):(\d\d):(\d\d)
(\.\d+)?
(Z|[+-]\d\d:\d\d)?
\s*\z/ix =~ date
year = $1.to_i
mon = $2.to_i
day = $3.to_i
hour = $4.to_i
min = $5.to_i
sec = $6.to_i
usec = 0
if $7
usec = Rational($7) * 1000000
end
if $8
zone = $8
year, mon, day, hour, min, sec =
apply_offset(year, mon, day, hour, min, sec, zone_offset(zone))
self.utc(year, mon, day, hour, min, sec, usec)
else
self.local(year, mon, day, hour, min, sec, usec)
end
else
raise ArgumentError.new("invalid date: #{date.inspect}")
end
end
alias iso8601 xmlschema
end # class << self
#
# Returns a string which represents the time as date-time defined by RFC 2822:
#
# day-of-week, DD month-name CCYY hh:mm:ss zone
#
# where zone is [+-]hhmm.
#
# If +self+ is a UTC time, -0000 is used as zone.
#
def rfc2822
sprintf('%s, %02d %s %04d %02d:%02d:%02d ',
RFC2822_DAY_NAME[wday],
day, RFC2822_MONTH_NAME[mon-1], year,
hour, min, sec) +
if utc?
'-0000'
else
off = utc_offset
sign = off < 0 ? '-' : '+'
sprintf('%s%02d%02d', sign, *(off.abs / 60).divmod(60))
end
end
alias rfc822 rfc2822
RFC2822_DAY_NAME = [
'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
]
RFC2822_MONTH_NAME = [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
]
#
# Returns a string which represents the time as rfc1123-date of HTTP-date
# defined by RFC 2616:
#
# day-of-week, DD month-name CCYY hh:mm:ss GMT
#
# Note that the result is always UTC (GMT).
#
def httpdate
t = dup.utc
sprintf('%s, %02d %s %04d %02d:%02d:%02d GMT',
RFC2822_DAY_NAME[t.wday],
t.day, RFC2822_MONTH_NAME[t.mon-1], t.year,
t.hour, t.min, t.sec)
end
#
# Returns a string which represents the time as dateTime defined by XML
# Schema:
#
# CCYY-MM-DDThh:mm:ssTZD
# CCYY-MM-DDThh:mm:ss.sssTZD
#
# where TZD is Z or [+-]hh:mm.
#
# If self is a UTC time, Z is used as TZD. [+-]hh:mm is used otherwise.
#
# +fractional_seconds+ specifies a number of digits of fractional seconds.
# Its default value is 0.
#
def xmlschema(fraction_digits=0)
sprintf('%04d-%02d-%02dT%02d:%02d:%02d',
year, mon, day, hour, min, sec) +
if fraction_digits == 0
''
else
'.' + sprintf('%0*d', fraction_digits, (subsec * 10**fraction_digits).floor)
end +
if utc?
'Z'
else
off = utc_offset
sign = off < 0 ? '-' : '+'
sprintf('%s%02d:%02d', sign, *(off.abs / 60).divmod(60))
end
end
alias iso8601 xmlschema
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/fileutils.rb | tools/jruby-1.5.1/lib/ruby/1.9/fileutils.rb | #
# = fileutils.rb
#
# Copyright (c) 2000-2007 Minero Aoki
#
# This program is free software.
# You can distribute/modify this program under the same terms of ruby.
#
# == module FileUtils
#
# Namespace for several file utility methods for copying, moving, removing, etc.
#
# === Module Functions
#
# cd(dir, options)
# cd(dir, options) {|dir| .... }
# pwd()
# mkdir(dir, options)
# mkdir(list, options)
# mkdir_p(dir, options)
# mkdir_p(list, options)
# rmdir(dir, options)
# rmdir(list, options)
# ln(old, new, options)
# ln(list, destdir, options)
# ln_s(old, new, options)
# ln_s(list, destdir, options)
# ln_sf(src, dest, options)
# cp(src, dest, options)
# cp(list, dir, options)
# cp_r(src, dest, options)
# cp_r(list, dir, options)
# mv(src, dest, options)
# mv(list, dir, options)
# rm(list, options)
# rm_r(list, options)
# rm_rf(list, options)
# install(src, dest, mode = <src's>, options)
# chmod(mode, list, options)
# chmod_R(mode, list, options)
# chown(user, group, list, options)
# chown_R(user, group, list, options)
# touch(list, options)
#
# The <tt>options</tt> parameter is a hash of options, taken from the list
# <tt>:force</tt>, <tt>:noop</tt>, <tt>:preserve</tt>, and <tt>:verbose</tt>.
# <tt>:noop</tt> means that no changes are made. The other two are obvious.
# Each method documents the options that it honours.
#
# All methods that have the concept of a "source" file or directory can take
# either one file or a list of files in that argument. See the method
# documentation for examples.
#
# There are some `low level' methods, which do not accept any option:
#
# copy_entry(src, dest, preserve = false, dereference = false)
# copy_file(src, dest, preserve = false, dereference = true)
# copy_stream(srcstream, deststream)
# remove_entry(path, force = false)
# remove_entry_secure(path, force = false)
# remove_file(path, force = false)
# compare_file(path_a, path_b)
# compare_stream(stream_a, stream_b)
# uptodate?(file, cmp_list)
#
# == module FileUtils::Verbose
#
# This module has all methods of FileUtils module, but it outputs messages
# before acting. This equates to passing the <tt>:verbose</tt> flag to methods
# in FileUtils.
#
# == module FileUtils::NoWrite
#
# This module has all methods of FileUtils module, but never changes
# files/directories. This equates to passing the <tt>:noop</tt> flag to methods
# in FileUtils.
#
# == module FileUtils::DryRun
#
# This module has all methods of FileUtils module, but never changes
# files/directories. This equates to passing the <tt>:noop</tt> and
# <tt>:verbose</tt> flags to methods in FileUtils.
#
module FileUtils
def self.private_module_function(name) #:nodoc:
module_function name
private_class_method name
end
# This hash table holds command options.
OPT_TABLE = {} #:nodoc: internal use only
#
# Options: (none)
#
# Returns the name of the current directory.
#
def pwd
Dir.pwd
end
module_function :pwd
alias getwd pwd
module_function :getwd
#
# Options: verbose
#
# Changes the current directory to the directory +dir+.
#
# If this method is called with block, resumes to the old
# working directory after the block execution finished.
#
# FileUtils.cd('/', :verbose => true) # chdir and report it
#
def cd(dir, options = {}, &block) # :yield: dir
fu_check_options options, OPT_TABLE['cd']
fu_output_message "cd #{dir}" if options[:verbose]
Dir.chdir(dir, &block)
fu_output_message 'cd -' if options[:verbose] and block
end
module_function :cd
alias chdir cd
module_function :chdir
OPT_TABLE['cd'] =
OPT_TABLE['chdir'] = [:verbose]
#
# Options: (none)
#
# Returns true if +newer+ is newer than all +old_list+.
# Non-existent files are older than any file.
#
# FileUtils.uptodate?('hello.o', %w(hello.c hello.h)) or \
# system 'make hello.o'
#
def uptodate?(new, old_list, options = nil)
raise ArgumentError, 'uptodate? does not accept any option' if options
return false unless File.exist?(new)
new_time = File.mtime(new)
old_list.each do |old|
if File.exist?(old)
return false unless new_time > File.mtime(old)
end
end
true
end
module_function :uptodate?
#
# Options: mode noop verbose
#
# Creates one or more directories.
#
# FileUtils.mkdir 'test'
# FileUtils.mkdir %w( tmp data )
# FileUtils.mkdir 'notexist', :noop => true # Does not really create.
# FileUtils.mkdir 'tmp', :mode => 0700
#
def mkdir(list, options = {})
fu_check_options options, OPT_TABLE['mkdir']
list = fu_list(list)
fu_output_message "mkdir #{options[:mode] ? ('-m %03o ' % options[:mode]) : ''}#{list.join ' '}" if options[:verbose]
return if options[:noop]
list.each do |dir|
fu_mkdir dir, options[:mode]
end
end
module_function :mkdir
OPT_TABLE['mkdir'] = [:mode, :noop, :verbose]
#
# Options: mode noop verbose
#
# Creates a directory and all its parent directories.
# For example,
#
# FileUtils.mkdir_p '/usr/local/lib/ruby'
#
# causes to make following directories, if it does not exist.
# * /usr
# * /usr/local
# * /usr/local/lib
# * /usr/local/lib/ruby
#
# You can pass several directories at a time in a list.
#
def mkdir_p(list, options = {})
fu_check_options options, OPT_TABLE['mkdir_p']
list = fu_list(list)
fu_output_message "mkdir -p #{options[:mode] ? ('-m %03o ' % options[:mode]) : ''}#{list.join ' '}" if options[:verbose]
return *list if options[:noop]
list.map {|path| path.sub(%r</\z>, '') }.each do |path|
# optimize for the most common case
begin
fu_mkdir path, options[:mode]
next
rescue SystemCallError
next if File.directory?(path)
end
stack = []
until path == stack.last # dirname("/")=="/", dirname("C:/")=="C:/"
stack.push path
path = File.dirname(path)
end
stack.reverse_each do |dir|
begin
fu_mkdir dir, options[:mode]
rescue SystemCallError => err
raise unless File.directory?(dir)
end
end
end
return *list
end
module_function :mkdir_p
alias mkpath mkdir_p
alias makedirs mkdir_p
module_function :mkpath
module_function :makedirs
OPT_TABLE['mkdir_p'] =
OPT_TABLE['mkpath'] =
OPT_TABLE['makedirs'] = [:mode, :noop, :verbose]
def fu_mkdir(path, mode) #:nodoc:
path = path.sub(%r</\z>, '')
if mode
Dir.mkdir path, mode
File.chmod mode, path
else
Dir.mkdir path
end
end
private_module_function :fu_mkdir
#
# Options: noop, verbose
#
# Removes one or more directories.
#
# FileUtils.rmdir 'somedir'
# FileUtils.rmdir %w(somedir anydir otherdir)
# # Does not really remove directory; outputs message.
# FileUtils.rmdir 'somedir', :verbose => true, :noop => true
#
def rmdir(list, options = {})
fu_check_options options, OPT_TABLE['rmdir']
list = fu_list(list)
parents = options[:parents]
fu_output_message "rmdir #{parents ? '-p ' : ''}#{list.join ' '}" if options[:verbose]
return if options[:noop]
list.each do |dir|
begin
Dir.rmdir(dir = dir.sub(%r</\z>, ''))
if parents
until (parent = File.dirname(dir)) == '.' or parent == dir
Dir.rmdir(dir)
end
end
rescue Errno::ENOTEMPTY, Errno::ENOENT
end
end
end
module_function :rmdir
OPT_TABLE['rmdir'] = [:parents, :noop, :verbose]
#
# Options: force noop verbose
#
# <b><tt>ln(old, new, options = {})</tt></b>
#
# Creates a hard link +new+ which points to +old+.
# If +new+ already exists and it is a directory, creates a link +new/old+.
# If +new+ already exists and it is not a directory, raises Errno::EEXIST.
# But if :force option is set, overwrite +new+.
#
# FileUtils.ln 'gcc', 'cc', :verbose => true
# FileUtils.ln '/usr/bin/emacs21', '/usr/bin/emacs'
#
# <b><tt>ln(list, destdir, options = {})</tt></b>
#
# Creates several hard links in a directory, with each one pointing to the
# item in +list+. If +destdir+ is not a directory, raises Errno::ENOTDIR.
#
# include FileUtils
# cd '/sbin'
# FileUtils.ln %w(cp mv mkdir), '/bin' # Now /sbin/cp and /bin/cp are linked.
#
def ln(src, dest, options = {})
fu_check_options options, OPT_TABLE['ln']
fu_output_message "ln#{options[:force] ? ' -f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
return if options[:noop]
fu_each_src_dest0(src, dest) do |s,d|
remove_file d, true if options[:force]
File.link s, d
end
end
module_function :ln
alias link ln
module_function :link
OPT_TABLE['ln'] =
OPT_TABLE['link'] = [:force, :noop, :verbose]
#
# Options: force noop verbose
#
# <b><tt>ln_s(old, new, options = {})</tt></b>
#
# Creates a symbolic link +new+ which points to +old+. If +new+ already
# exists and it is a directory, creates a symbolic link +new/old+. If +new+
# already exists and it is not a directory, raises Errno::EEXIST. But if
# :force option is set, overwrite +new+.
#
# FileUtils.ln_s '/usr/bin/ruby', '/usr/local/bin/ruby'
# FileUtils.ln_s 'verylongsourcefilename.c', 'c', :force => true
#
# <b><tt>ln_s(list, destdir, options = {})</tt></b>
#
# Creates several symbolic links in a directory, with each one pointing to the
# item in +list+. If +destdir+ is not a directory, raises Errno::ENOTDIR.
#
# If +destdir+ is not a directory, raises Errno::ENOTDIR.
#
# FileUtils.ln_s Dir.glob('bin/*.rb'), '/home/aamine/bin'
#
def ln_s(src, dest, options = {})
fu_check_options options, OPT_TABLE['ln_s']
fu_output_message "ln -s#{options[:force] ? 'f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
return if options[:noop]
fu_each_src_dest0(src, dest) do |s,d|
remove_file d, true if options[:force]
File.symlink s, d
end
end
module_function :ln_s
alias symlink ln_s
module_function :symlink
OPT_TABLE['ln_s'] =
OPT_TABLE['symlink'] = [:force, :noop, :verbose]
#
# Options: noop verbose
#
# Same as
# #ln_s(src, dest, :force)
#
def ln_sf(src, dest, options = {})
fu_check_options options, OPT_TABLE['ln_sf']
options = options.dup
options[:force] = true
ln_s src, dest, options
end
module_function :ln_sf
OPT_TABLE['ln_sf'] = [:noop, :verbose]
#
# Options: preserve noop verbose
#
# Copies a file content +src+ to +dest+. If +dest+ is a directory,
# copies +src+ to +dest/src+.
#
# If +src+ is a list of files, then +dest+ must be a directory.
#
# FileUtils.cp 'eval.c', 'eval.c.org'
# FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6'
# FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6', :verbose => true
# FileUtils.cp 'symlink', 'dest' # copy content, "dest" is not a symlink
#
def cp(src, dest, options = {})
fu_check_options options, OPT_TABLE['cp']
fu_output_message "cp#{options[:preserve] ? ' -p' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
return if options[:noop]
fu_each_src_dest(src, dest) do |s, d|
copy_file s, d, options[:preserve]
end
end
module_function :cp
alias copy cp
module_function :copy
OPT_TABLE['cp'] =
OPT_TABLE['copy'] = [:preserve, :noop, :verbose]
#
# Options: preserve noop verbose dereference_root remove_destination
#
# Copies +src+ to +dest+. If +src+ is a directory, this method copies
# all its contents recursively. If +dest+ is a directory, copies
# +src+ to +dest/src+.
#
# +src+ can be a list of files.
#
# # Installing ruby library "mylib" under the site_ruby
# FileUtils.rm_r site_ruby + '/mylib', :force
# FileUtils.cp_r 'lib/', site_ruby + '/mylib'
#
# # Examples of copying several files to target directory.
# FileUtils.cp_r %w(mail.rb field.rb debug/), site_ruby + '/tmail'
# FileUtils.cp_r Dir.glob('*.rb'), '/home/aamine/lib/ruby', :noop => true, :verbose => true
#
# # If you want to copy all contents of a directory instead of the
# # directory itself, c.f. src/x -> dest/x, src/y -> dest/y,
# # use following code.
# FileUtils.cp_r 'src/.', 'dest' # cp_r('src', 'dest') makes src/dest,
# # but this doesn't.
#
def cp_r(src, dest, options = {})
fu_check_options options, OPT_TABLE['cp_r']
fu_output_message "cp -r#{options[:preserve] ? 'p' : ''}#{options[:remove_destination] ? ' --remove-destination' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
return if options[:noop]
fu_each_src_dest(src, dest) do |s, d|
copy_entry s, d, options[:preserve], options[:dereference_root], options[:remove_destination]
end
end
module_function :cp_r
OPT_TABLE['cp_r'] = [:preserve, :noop, :verbose,
:dereference_root, :remove_destination]
#
# Copies a file system entry +src+ to +dest+.
# If +src+ is a directory, this method copies its contents recursively.
# This method preserves file types, c.f. symlink, directory...
# (FIFO, device files and etc. are not supported yet)
#
# Both of +src+ and +dest+ must be a path name.
# +src+ must exist, +dest+ must not exist.
#
# If +preserve+ is true, this method preserves owner, group, permissions
# and modified time.
#
# If +dereference_root+ is true, this method dereference tree root.
#
# If +remove_destination+ is true, this method removes each destination file before copy.
#
def copy_entry(src, dest, preserve = false, dereference_root = false, remove_destination = false)
Entry_.new(src, nil, dereference_root).traverse do |ent|
destent = Entry_.new(dest, ent.rel, false)
File.unlink destent.path if remove_destination && File.file?(destent.path)
ent.copy destent.path
ent.copy_metadata destent.path if preserve
end
end
module_function :copy_entry
#
# Copies file contents of +src+ to +dest+.
# Both of +src+ and +dest+ must be a path name.
#
def copy_file(src, dest, preserve = false, dereference = true)
ent = Entry_.new(src, nil, dereference)
ent.copy_file dest
ent.copy_metadata dest if preserve
end
module_function :copy_file
#
# Copies stream +src+ to +dest+.
# +src+ must respond to #read(n) and
# +dest+ must respond to #write(str).
#
def copy_stream(src, dest)
IO.copy_stream(src, dest)
end
module_function :copy_stream
#
# Options: force noop verbose
#
# Moves file(s) +src+ to +dest+. If +file+ and +dest+ exist on the different
# disk partition, the file is copied then the original file is removed.
#
# FileUtils.mv 'badname.rb', 'goodname.rb'
# FileUtils.mv 'stuff.rb', '/notexist/lib/ruby', :force => true # no error
#
# FileUtils.mv %w(junk.txt dust.txt), '/home/aamine/.trash/'
# FileUtils.mv Dir.glob('test*.rb'), 'test', :noop => true, :verbose => true
#
def mv(src, dest, options = {})
fu_check_options options, OPT_TABLE['mv']
fu_output_message "mv#{options[:force] ? ' -f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
return if options[:noop]
fu_each_src_dest(src, dest) do |s, d|
destent = Entry_.new(d, nil, true)
begin
if destent.exist?
if destent.directory?
raise Errno::EEXIST, dest
else
destent.remove_file if rename_cannot_overwrite_file?
end
end
begin
File.rename s, d
rescue Errno::EXDEV
copy_entry s, d, true
if options[:secure]
remove_entry_secure s, options[:force]
else
remove_entry s, options[:force]
end
end
rescue SystemCallError
raise unless options[:force]
end
end
end
module_function :mv
alias move mv
module_function :move
OPT_TABLE['mv'] =
OPT_TABLE['move'] = [:force, :noop, :verbose, :secure]
def rename_cannot_overwrite_file? #:nodoc:
/cygwin|mswin|mingw|bccwin|emx/ =~ RUBY_PLATFORM
end
private_module_function :rename_cannot_overwrite_file?
#
# Options: force noop verbose
#
# Remove file(s) specified in +list+. This method cannot remove directories.
# All StandardErrors are ignored when the :force option is set.
#
# FileUtils.rm %w( junk.txt dust.txt )
# FileUtils.rm Dir.glob('*.so')
# FileUtils.rm 'NotExistFile', :force => true # never raises exception
#
def rm(list, options = {})
fu_check_options options, OPT_TABLE['rm']
list = fu_list(list)
fu_output_message "rm#{options[:force] ? ' -f' : ''} #{list.join ' '}" if options[:verbose]
return if options[:noop]
list.each do |path|
remove_file path, options[:force]
end
end
module_function :rm
alias remove rm
module_function :remove
OPT_TABLE['rm'] =
OPT_TABLE['remove'] = [:force, :noop, :verbose]
#
# Options: noop verbose
#
# Equivalent to
#
# #rm(list, :force => true)
#
def rm_f(list, options = {})
fu_check_options options, OPT_TABLE['rm_f']
options = options.dup
options[:force] = true
rm list, options
end
module_function :rm_f
alias safe_unlink rm_f
module_function :safe_unlink
OPT_TABLE['rm_f'] =
OPT_TABLE['safe_unlink'] = [:noop, :verbose]
#
# Options: force noop verbose secure
#
# remove files +list+[0] +list+[1]... If +list+[n] is a directory,
# removes its all contents recursively. This method ignores
# StandardError when :force option is set.
#
# FileUtils.rm_r Dir.glob('/tmp/*')
# FileUtils.rm_r '/', :force => true # :-)
#
# WARNING: This method causes local vulnerability
# if one of parent directories or removing directory tree are world
# writable (including /tmp, whose permission is 1777), and the current
# process has strong privilege such as Unix super user (root), and the
# system has symbolic link. For secure removing, read the documentation
# of #remove_entry_secure carefully, and set :secure option to true.
# Default is :secure=>false.
#
# NOTE: This method calls #remove_entry_secure if :secure option is set.
# See also #remove_entry_secure.
#
def rm_r(list, options = {})
fu_check_options options, OPT_TABLE['rm_r']
# options[:secure] = true unless options.key?(:secure)
list = fu_list(list)
fu_output_message "rm -r#{options[:force] ? 'f' : ''} #{list.join ' '}" if options[:verbose]
return if options[:noop]
list.each do |path|
if options[:secure]
remove_entry_secure path, options[:force]
else
remove_entry path, options[:force]
end
end
end
module_function :rm_r
OPT_TABLE['rm_r'] = [:force, :noop, :verbose, :secure]
#
# Options: noop verbose secure
#
# Equivalent to
#
# #rm_r(list, :force => true)
#
# WARNING: This method causes local vulnerability.
# Read the documentation of #rm_r first.
#
def rm_rf(list, options = {})
fu_check_options options, OPT_TABLE['rm_rf']
options = options.dup
options[:force] = true
rm_r list, options
end
module_function :rm_rf
alias rmtree rm_rf
module_function :rmtree
OPT_TABLE['rm_rf'] =
OPT_TABLE['rmtree'] = [:noop, :verbose, :secure]
#
# This method removes a file system entry +path+. +path+ shall be a
# regular file, a directory, or something. If +path+ is a directory,
# remove it recursively. This method is required to avoid TOCTTOU
# (time-of-check-to-time-of-use) local security vulnerability of #rm_r.
# #rm_r causes security hole when:
#
# * Parent directory is world writable (including /tmp).
# * Removing directory tree includes world writable directory.
# * The system has symbolic link.
#
# To avoid this security hole, this method applies special preprocess.
# If +path+ is a directory, this method chown(2) and chmod(2) all
# removing directories. This requires the current process is the
# owner of the removing whole directory tree, or is the super user (root).
#
# WARNING: You must ensure that *ALL* parent directories are not
# world writable. Otherwise this method does not work.
# Only exception is temporary directory like /tmp and /var/tmp,
# whose permission is 1777.
#
# WARNING: Only the owner of the removing directory tree, or Unix super
# user (root) should invoke this method. Otherwise this method does not
# work.
#
# For details of this security vulnerability, see Perl's case:
#
# http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CAN-2005-0448
# http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CAN-2004-0452
#
# For fileutils.rb, this vulnerability is reported in [ruby-dev:26100].
#
def remove_entry_secure(path, force = false)
unless fu_have_symlink?
remove_entry path, force
return
end
fullpath = File.expand_path(path)
st = File.lstat(fullpath)
unless st.directory?
File.unlink fullpath
return
end
# is a directory.
parent_st = File.stat(File.dirname(fullpath))
unless parent_st.world_writable?
remove_entry path, force
return
end
unless parent_st.sticky?
raise ArgumentError, "parent directory is world writable, FileUtils#remove_entry_secure does not work; abort: #{path.inspect} (parent directory mode #{'%o' % parent_st.mode})"
end
# freeze tree root
euid = Process.euid
File.open(fullpath + '/.') {|f|
unless fu_stat_identical_entry?(st, f.stat)
# symlink (TOC-to-TOU attack?)
File.unlink fullpath
return
end
f.chown euid, -1
f.chmod 0700
}
# ---- tree root is frozen ----
root = Entry_.new(path)
root.preorder_traverse do |ent|
if ent.directory?
ent.chown euid, -1
ent.chmod 0700
end
end
root.postorder_traverse do |ent|
begin
ent.remove
rescue
raise unless force
end
end
rescue
raise unless force
end
module_function :remove_entry_secure
def fu_have_symlink? #:nodoc
File.symlink nil, nil
rescue NotImplementedError
return false
rescue
return true
end
private_module_function :fu_have_symlink?
def fu_stat_identical_entry?(a, b) #:nodoc:
a.dev == b.dev and a.ino == b.ino
end
private_module_function :fu_stat_identical_entry?
#
# This method removes a file system entry +path+.
# +path+ might be a regular file, a directory, or something.
# If +path+ is a directory, remove it recursively.
#
# See also #remove_entry_secure.
#
def remove_entry(path, force = false)
Entry_.new(path).postorder_traverse do |ent|
begin
ent.remove
rescue
raise unless force
end
end
rescue
raise unless force
end
module_function :remove_entry
#
# Removes a file +path+.
# This method ignores StandardError if +force+ is true.
#
def remove_file(path, force = false)
Entry_.new(path).remove_file
rescue
raise unless force
end
module_function :remove_file
#
# Removes a directory +dir+ and its contents recursively.
# This method ignores StandardError if +force+ is true.
#
def remove_dir(path, force = false)
remove_entry path, force # FIXME?? check if it is a directory
end
module_function :remove_dir
#
# Returns true if the contents of a file A and a file B are identical.
#
# FileUtils.compare_file('somefile', 'somefile') #=> true
# FileUtils.compare_file('/bin/cp', '/bin/mv') #=> maybe false
#
def compare_file(a, b)
return false unless File.size(a) == File.size(b)
File.open(a, 'rb') {|fa|
File.open(b, 'rb') {|fb|
return compare_stream(fa, fb)
}
}
end
module_function :compare_file
alias identical? compare_file
alias cmp compare_file
module_function :identical?
module_function :cmp
#
# Returns true if the contents of a stream +a+ and +b+ are identical.
#
def compare_stream(a, b)
bsize = fu_stream_blksize(a, b)
sa = sb = nil
while sa == sb
sa = a.read(bsize)
sb = b.read(bsize)
unless sa and sb
if sa.nil? and sb.nil?
return true
end
end
end
false
end
module_function :compare_stream
#
# Options: mode preserve noop verbose
#
# If +src+ is not same as +dest+, copies it and changes the permission
# mode to +mode+. If +dest+ is a directory, destination is +dest+/+src+.
# This method removes destination before copy.
#
# FileUtils.install 'ruby', '/usr/local/bin/ruby', :mode => 0755, :verbose => true
# FileUtils.install 'lib.rb', '/usr/local/lib/ruby/site_ruby', :verbose => true
#
def install(src, dest, options = {})
fu_check_options options, OPT_TABLE['install']
fu_output_message "install -c#{options[:preserve] && ' -p'}#{options[:mode] ? (' -m 0%o' % options[:mode]) : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
return if options[:noop]
fu_each_src_dest(src, dest) do |s, d|
unless File.exist?(d) and compare_file(s, d)
remove_file d, true
st = File.stat(s) if options[:preserve]
copy_file s, d
File.utime st.atime, st.mtime, d if options[:preserve]
File.chmod options[:mode], d if options[:mode]
end
end
end
module_function :install
OPT_TABLE['install'] = [:mode, :preserve, :noop, :verbose]
#
# Options: noop verbose
#
# Changes permission bits on the named files (in +list+) to the bit pattern
# represented by +mode+.
#
# FileUtils.chmod 0755, 'somecommand'
# FileUtils.chmod 0644, %w(my.rb your.rb his.rb her.rb)
# FileUtils.chmod 0755, '/usr/bin/ruby', :verbose => true
#
def chmod(mode, list, options = {})
fu_check_options options, OPT_TABLE['chmod']
list = fu_list(list)
fu_output_message sprintf('chmod %o %s', mode, list.join(' ')) if options[:verbose]
return if options[:noop]
list.each do |path|
Entry_.new(path).chmod mode
end
end
module_function :chmod
OPT_TABLE['chmod'] = [:noop, :verbose]
#
# Options: noop verbose force
#
# Changes permission bits on the named files (in +list+)
# to the bit pattern represented by +mode+.
#
# FileUtils.chmod_R 0700, "/tmp/app.#{$$}"
#
def chmod_R(mode, list, options = {})
fu_check_options options, OPT_TABLE['chmod_R']
list = fu_list(list)
fu_output_message sprintf('chmod -R%s %o %s',
(options[:force] ? 'f' : ''),
mode, list.join(' ')) if options[:verbose]
return if options[:noop]
list.each do |root|
Entry_.new(root).traverse do |ent|
begin
ent.chmod mode
rescue
raise unless options[:force]
end
end
end
end
module_function :chmod_R
OPT_TABLE['chmod_R'] = [:noop, :verbose, :force]
#
# Options: noop verbose
#
# Changes owner and group on the named files (in +list+)
# to the user +user+ and the group +group+. +user+ and +group+
# may be an ID (Integer/String) or a name (String).
# If +user+ or +group+ is nil, this method does not change
# the attribute.
#
# FileUtils.chown 'root', 'staff', '/usr/local/bin/ruby'
# FileUtils.chown nil, 'bin', Dir.glob('/usr/bin/*'), :verbose => true
#
def chown(user, group, list, options = {})
fu_check_options options, OPT_TABLE['chown']
list = fu_list(list)
fu_output_message sprintf('chown %s%s',
[user,group].compact.join(':') + ' ',
list.join(' ')) if options[:verbose]
return if options[:noop]
uid = fu_get_uid(user)
gid = fu_get_gid(group)
list.each do |path|
Entry_.new(path).chown uid, gid
end
end
module_function :chown
OPT_TABLE['chown'] = [:noop, :verbose]
#
# Options: noop verbose force
#
# Changes owner and group on the named files (in +list+)
# to the user +user+ and the group +group+ recursively.
# +user+ and +group+ may be an ID (Integer/String) or
# a name (String). If +user+ or +group+ is nil, this
# method does not change the attribute.
#
# FileUtils.chown_R 'www', 'www', '/var/www/htdocs'
# FileUtils.chown_R 'cvs', 'cvs', '/var/cvs', :verbose => true
#
def chown_R(user, group, list, options = {})
fu_check_options options, OPT_TABLE['chown_R']
list = fu_list(list)
fu_output_message sprintf('chown -R%s %s%s',
(options[:force] ? 'f' : ''),
[user,group].compact.join(':') + ' ',
list.join(' ')) if options[:verbose]
return if options[:noop]
uid = fu_get_uid(user)
gid = fu_get_gid(group)
return unless uid or gid
list.each do |root|
Entry_.new(root).traverse do |ent|
begin
ent.chown uid, gid
rescue
raise unless options[:force]
end
end
end
end
module_function :chown_R
OPT_TABLE['chown_R'] = [:noop, :verbose, :force]
begin
require 'etc'
def fu_get_uid(user) #:nodoc:
return nil unless user
user = user.to_s
if /\A\d+\z/ =~ user
then user.to_i
else Etc.getpwnam(user).uid
end
end
private_module_function :fu_get_uid
def fu_get_gid(group) #:nodoc:
return nil unless group
group = group.to_s
if /\A\d+\z/ =~ group
then group.to_i
else Etc.getgrnam(group).gid
end
end
private_module_function :fu_get_gid
rescue LoadError
# need Win32 support???
def fu_get_uid(user) #:nodoc:
user # FIXME
end
private_module_function :fu_get_uid
def fu_get_gid(group) #:nodoc:
group # FIXME
end
private_module_function :fu_get_gid
end
#
# Options: noop verbose
#
# Updates modification time (mtime) and access time (atime) of file(s) in
# +list+. Files are created if they don't exist.
#
# FileUtils.touch 'timestamp'
# FileUtils.touch Dir.glob('*.c'); system 'make'
#
def touch(list, options = {})
fu_check_options options, OPT_TABLE['touch']
list = fu_list(list)
created = nocreate = options[:nocreate]
t = options[:mtime]
if options[:verbose]
fu_output_message "touch #{nocreate ? ' -c' : ''}#{t ? t.strftime(' -t %Y%m%d%H%M.%S') : ''}#{list.join ' '}"
end
return if options[:noop]
list.each do |path|
created = nocreate
begin
File.utime(t, t, path)
rescue Errno::ENOENT
raise if created
File.open(path, 'a') {
;
}
created = true
retry if t
end
end
end
module_function :touch
OPT_TABLE['touch'] = [:noop, :verbose, :mtime, :nocreate]
private
module StreamUtils_
private
def fu_windows?
/mswin|mingw|bccwin|emx/ =~ RUBY_PLATFORM
end
def fu_copy_stream0(src, dest, blksize = nil) #:nodoc:
IO.copy_stream(src, dest)
end
def fu_stream_blksize(*streams)
streams.each do |s|
next unless s.respond_to?(:stat)
size = fu_blksize(s.stat)
return size if size
end
fu_default_blksize()
end
def fu_blksize(st)
s = st.blksize
return nil unless s
return nil if s == 0
s
end
def fu_default_blksize
1024
end
end
include StreamUtils_
extend StreamUtils_
class Entry_ #:nodoc: internal use only
include StreamUtils_
def initialize(a, b = nil, deref = false)
@prefix = @rel = @path = nil
if b
@prefix = a
@rel = b
else
@path = a
end
@deref = deref
@stat = nil
@lstat = nil
end
def inspect
"\#<#{self.class} #{path()}>"
end
def path
if @path
File.path(@path)
else
join(@prefix, @rel)
end
end
def prefix
@prefix || @path
end
def rel
@rel
end
def dereference?
@deref
end
def exist?
lstat! ? true : false
end
def file?
s = lstat!
s and s.file?
end
def directory?
s = lstat!
s and s.directory?
end
def symlink?
s = lstat!
s and s.symlink?
end
def chardev?
s = lstat!
s and s.chardev?
end
def blockdev?
s = lstat!
s and s.blockdev?
end
def socket?
s = lstat!
s and s.socket?
end
| 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/observer.rb | tools/jruby-1.5.1/lib/ruby/1.9/observer.rb | #
# observer.rb implements the _Observer_ object-oriented design pattern. The
# following documentation is copied, with modifications, from "Programming
# Ruby", by Hunt and Thomas; http://www.rubycentral.com/book/lib_patterns.html.
#
# == About
#
# The Observer pattern, also known as Publish/Subscribe, provides a simple
# mechanism for one object to inform a set of interested third-party objects
# when its state changes.
#
# == Mechanism
#
# In the Ruby implementation, the notifying class mixes in the +Observable+
# module, which provides the methods for managing the associated observer
# objects.
#
# The observers must implement the +update+ method to receive notifications.
#
# The observable object must:
# * assert that it has +changed+
# * call +notify_observers+
#
# == Example
#
# The following example demonstrates this nicely. A +Ticker+, when run,
# continually receives the stock +Price+ for its +@symbol+. A +Warner+ is a
# general observer of the price, and two warners are demonstrated, a +WarnLow+
# and a +WarnHigh+, which print a warning if the price is below or above their
# set limits, respectively.
#
# The +update+ callback allows the warners to run without being explicitly
# called. The system is set up with the +Ticker+ and several observers, and the
# observers do their duty without the top-level code having to interfere.
#
# Note that the contract between publisher and subscriber (observable and
# observer) is not declared or enforced. The +Ticker+ publishes a time and a
# price, and the warners receive that. But if you don't ensure that your
# contracts are correct, nothing else can warn you.
#
# require "observer"
#
# class Ticker ### Periodically fetch a stock price.
# include Observable
#
# def initialize(symbol)
# @symbol = symbol
# end
#
# def run
# lastPrice = nil
# loop do
# price = Price.fetch(@symbol)
# print "Current price: #{price}\n"
# if price != lastPrice
# changed # notify observers
# lastPrice = price
# notify_observers(Time.now, price)
# end
# sleep 1
# end
# end
# end
#
# class Price ### A mock class to fetch a stock price (60 - 140).
# def Price.fetch(symbol)
# 60 + rand(80)
# end
# end
#
# class Warner ### An abstract observer of Ticker objects.
# def initialize(ticker, limit)
# @limit = limit
# ticker.add_observer(self)
# end
# end
#
# class WarnLow < Warner
# def update(time, price) # callback for observer
# if price < @limit
# print "--- #{time.to_s}: Price below #@limit: #{price}\n"
# end
# end
# end
#
# class WarnHigh < Warner
# def update(time, price) # callback for observer
# if price > @limit
# print "+++ #{time.to_s}: Price above #@limit: #{price}\n"
# end
# end
# end
#
# ticker = Ticker.new("MSFT")
# WarnLow.new(ticker, 80)
# WarnHigh.new(ticker, 120)
# ticker.run
#
# Produces:
#
# Current price: 83
# Current price: 75
# --- Sun Jun 09 00:10:25 CDT 2002: Price below 80: 75
# Current price: 90
# Current price: 134
# +++ Sun Jun 09 00:10:25 CDT 2002: Price above 120: 134
# Current price: 134
# Current price: 112
# Current price: 79
# --- Sun Jun 09 00:10:25 CDT 2002: Price below 80: 79
#
# Implements the Observable design pattern as a mixin so that other objects can
# be notified of changes in state. See observer.rb for details and an example.
#
module Observable
#
# Add +observer+ as an observer on this object. +observer+ will now receive
# notifications. The second optional argument specifies a method to notify
# updates, of which default value is +update+.
#
def add_observer(observer, func=:update)
@observer_peers = {} unless defined? @observer_peers
unless observer.respond_to? func
raise NoMethodError, "observer does not respond to `#{func.to_s}'"
end
@observer_peers[observer] = func
end
#
# Delete +observer+ as an observer on this object. It will no longer receive
# notifications.
#
def delete_observer(observer)
@observer_peers.delete observer if defined? @observer_peers
end
#
# Delete all observers associated with this object.
#
def delete_observers
@observer_peers.clear if defined? @observer_peers
end
#
# Return the number of observers associated with this object.
#
def count_observers
if defined? @observer_peers
@observer_peers.size
else
0
end
end
#
# Set the changed state of this object. Notifications will be sent only if
# the changed +state+ is +true+.
#
def changed(state=true)
@observer_state = state
end
#
# Query the changed state of this object.
#
def changed?
if defined? @observer_state and @observer_state
true
else
false
end
end
#
# If this object's changed state is +true+, invoke the update method in each
# currently associated observer in turn, passing it the given arguments. The
# changed state is then set to +false+.
#
def notify_observers(*arg)
if defined? @observer_state and @observer_state
if defined? @observer_peers
@observer_peers.each { |k, v|
k.send v, *arg
}
end
@observer_state = false
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/yaml.rb | tools/jruby-1.5.1/lib/ruby/1.9/yaml.rb | # -*- mode: ruby; ruby-indent-level: 4; tab-width: 4 -*- vim: sw=4 ts=4
# $Id: yaml.rb 24625 2009-08-22 04:52:09Z akr $
#
# = yaml.rb: top-level module with methods for loading and parsing YAML documents
#
# Author:: why the lucky stiff
#
require 'stringio'
require 'yaml/error'
require 'yaml/syck'
require 'yaml/tag'
require 'yaml/stream'
require 'yaml/constants'
# == YAML
#
# YAML(tm) (rhymes with 'camel') is a
# straightforward machine parsable data serialization format designed for
# human readability and interaction with scripting languages such as Perl
# and Python. YAML is optimized for data serialization, formatted
# dumping, configuration files, log files, Internet messaging and
# filtering. This specification describes the YAML information model and
# serialization format. Together with the Unicode standard for characters, it
# provides all the information necessary to understand YAML Version 1.0
# and construct computer programs to process it.
#
# See http://yaml.org/ for more information. For a quick tutorial, please
# visit YAML In Five Minutes (http://yaml.kwiki.org/?YamlInFiveMinutes).
#
# == About This Library
#
# The YAML 1.0 specification outlines four stages of YAML loading and dumping.
# This library honors all four of those stages, although data is really only
# available to you in three stages.
#
# The four stages are: native, representation, serialization, and presentation.
#
# The native stage refers to data which has been loaded completely into Ruby's
# own types. (See +YAML::load+.)
#
# The representation stage means data which has been composed into
# +YAML::BaseNode+ objects. In this stage, the document is available as a
# tree of node objects. You can perform YPath queries and transformations
# at this level. (See +YAML::parse+.)
#
# The serialization stage happens inside the parser. The YAML parser used in
# Ruby is called Syck. Serialized nodes are available in the extension as
# SyckNode structs.
#
# The presentation stage is the YAML document itself. This is accessible
# to you as a string. (See +YAML::dump+.)
#
# For more information about the various information models, see Chapter
# 3 of the YAML 1.0 Specification (http://yaml.org/spec/#id2491269).
#
# The YAML module provides quick access to the most common loading (YAML::load)
# and dumping (YAML::dump) tasks. This module also provides an API for registering
# global types (YAML::add_domain_type).
#
# == Example
#
# A simple round-trip (load and dump) of an object.
#
# require "yaml"
#
# test_obj = ["dogs", "cats", "badgers"]
#
# yaml_obj = YAML::dump( test_obj )
# # -> ---
# - dogs
# - cats
# - badgers
# ruby_obj = YAML::load( yaml_obj )
# # => ["dogs", "cats", "badgers"]
# ruby_obj == test_obj
# # => true
#
# To register your custom types with the global resolver, use +add_domain_type+.
#
# YAML::add_domain_type( "your-site.com,2004", "widget" ) do |type, val|
# Widget.new( val )
# end
#
module YAML
Resolver = YAML::Syck::Resolver
DefaultResolver = YAML::Syck::DefaultResolver
DefaultResolver.use_types_at( @@tagged_classes )
GenericResolver = YAML::Syck::GenericResolver
Parser = YAML::Syck::Parser
Emitter = YAML::Syck::Emitter
# Returns a new default parser
def YAML.parser; Parser.new.set_resolver( YAML.resolver ); end
# Returns a new generic parser
def YAML.generic_parser; Parser.new.set_resolver( GenericResolver ); end
# Returns the default resolver
def YAML.resolver; DefaultResolver; end
# Returns a new default emitter
def YAML.emitter; Emitter.new.set_resolver( YAML.resolver ); end
#
# Converts _obj_ to YAML and writes the YAML result to _io_.
#
# File.open( 'animals.yaml', 'w' ) do |out|
# YAML.dump( ['badger', 'elephant', 'tiger'], out )
# end
#
# If no _io_ is provided, a string containing the dumped YAML
# is returned.
#
# YAML.dump( :locked )
# #=> "--- :locked"
#
def YAML.dump( obj, io = nil )
obj.to_yaml( io || io2 = StringIO.new )
io || ( io2.rewind; io2.read )
end
#
# Load a document from the current _io_ stream.
#
# File.open( 'animals.yaml' ) { |yf| YAML::load( yf ) }
# #=> ['badger', 'elephant', 'tiger']
#
# Can also load from a string.
#
# YAML.load( "--- :locked" )
# #=> :locked
#
def YAML.load( io )
yp = parser.load( io )
end
#
# Load a document from the file located at _filepath_.
#
# YAML.load_file( 'animals.yaml' )
# #=> ['badger', 'elephant', 'tiger']
#
def YAML.load_file( filepath )
File.open( filepath ) do |f|
load( f )
end
end
#
# Parse the first document from the current _io_ stream
#
# File.open( 'animals.yaml' ) { |yf| YAML::load( yf ) }
# #=> #<YAML::Syck::Node:0x82ccce0
# @kind=:seq,
# @value=
# [#<YAML::Syck::Node:0x82ccd94
# @kind=:scalar,
# @type_id="str",
# @value="badger">,
# #<YAML::Syck::Node:0x82ccd58
# @kind=:scalar,
# @type_id="str",
# @value="elephant">,
# #<YAML::Syck::Node:0x82ccd1c
# @kind=:scalar,
# @type_id="str",
# @value="tiger">]>
#
# Can also load from a string.
#
# YAML.parse( "--- :locked" )
# #=> #<YAML::Syck::Node:0x82edddc
# @type_id="tag:ruby.yaml.org,2002:sym",
# @value=":locked", @kind=:scalar>
#
def YAML.parse( io )
yp = generic_parser.load( io )
end
#
# Parse a document from the file located at _filepath_.
#
# YAML.parse_file( 'animals.yaml' )
# #=> #<YAML::Syck::Node:0x82ccce0
# @kind=:seq,
# @value=
# [#<YAML::Syck::Node:0x82ccd94
# @kind=:scalar,
# @type_id="str",
# @value="badger">,
# #<YAML::Syck::Node:0x82ccd58
# @kind=:scalar,
# @type_id="str",
# @value="elephant">,
# #<YAML::Syck::Node:0x82ccd1c
# @kind=:scalar,
# @type_id="str",
# @value="tiger">]>
#
def YAML.parse_file( filepath )
File.open( filepath ) do |f|
parse( f )
end
end
#
# Calls _block_ with each consecutive document in the YAML
# stream contained in _io_.
#
# File.open( 'many-docs.yaml' ) do |yf|
# YAML.each_document( yf ) do |ydoc|
# ## ydoc contains the single object
# ## from the YAML document
# end
# end
#
def YAML.each_document( io, &block )
yp = parser.load_documents( io, &block )
end
#
# Calls _block_ with each consecutive document in the YAML
# stream contained in _io_.
#
# File.open( 'many-docs.yaml' ) do |yf|
# YAML.load_documents( yf ) do |ydoc|
# ## ydoc contains the single object
# ## from the YAML document
# end
# end
#
def YAML.load_documents( io, &doc_proc )
YAML.each_document( io, &doc_proc )
end
#
# Calls _block_ with a tree of +YAML::BaseNodes+, one tree for
# each consecutive document in the YAML stream contained in _io_.
#
# File.open( 'many-docs.yaml' ) do |yf|
# YAML.each_node( yf ) do |ydoc|
# ## ydoc contains a tree of nodes
# ## from the YAML document
# end
# end
#
def YAML.each_node( io, &doc_proc )
yp = generic_parser.load_documents( io, &doc_proc )
end
#
# Calls _block_ with a tree of +YAML::BaseNodes+, one tree for
# each consecutive document in the YAML stream contained in _io_.
#
# File.open( 'many-docs.yaml' ) do |yf|
# YAML.parse_documents( yf ) do |ydoc|
# ## ydoc contains a tree of nodes
# ## from the YAML document
# end
# end
#
def YAML.parse_documents( io, &doc_proc )
YAML.each_node( io, &doc_proc )
end
#
# Loads all documents from the current _io_ stream,
# returning a +YAML::Stream+ object containing all
# loaded documents.
#
def YAML.load_stream( io )
d = nil
parser.load_documents( io ) do |doc|
d = YAML::Stream.new if not d
d.add( doc )
end
return d
end
#
# Returns a YAML stream containing each of the items in +objs+,
# each having their own document.
#
# YAML.dump_stream( 0, [], {} )
# #=> --- 0
# --- []
# --- {}
#
def YAML.dump_stream( *objs )
d = YAML::Stream.new
objs.each do |doc|
d.add( doc )
end
d.emit
end
#
# Add a global handler for a YAML domain type.
#
def YAML.add_domain_type( domain, type_tag, &transfer_proc )
resolver.add_type( "tag:#{ domain }:#{ type_tag }", transfer_proc )
end
#
# Add a transfer method for a builtin type
#
def YAML.add_builtin_type( type_tag, &transfer_proc )
resolver.add_type( "tag:yaml.org,2002:#{ type_tag }", transfer_proc )
end
#
# Add a transfer method for a builtin type
#
def YAML.add_ruby_type( type_tag, &transfer_proc )
resolver.add_type( "tag:ruby.yaml.org,2002:#{ type_tag }", transfer_proc )
end
#
# Add a private document type
#
def YAML.add_private_type( type_re, &transfer_proc )
resolver.add_type( "x-private:" + type_re, transfer_proc )
end
#
# Detect typing of a string
#
def YAML.detect_implicit( val )
resolver.detect_implicit( val )
end
#
# Convert a type_id to a taguri
#
def YAML.tagurize( val )
resolver.tagurize( val )
end
#
# Apply a transfer method to a Ruby object
#
def YAML.transfer( type_id, obj )
resolver.transfer( YAML.tagurize( type_id ), obj )
end
#
# Apply any implicit a node may qualify for
#
def YAML.try_implicit( obj )
YAML.transfer( YAML.detect_implicit( obj ), obj )
end
#
# Method to extract colon-seperated type and class, returning
# the type and the constant of the class
#
def YAML.read_type_class( type, obj_class )
scheme, domain, type, tclass = type.split( ':', 4 )
tclass.split( "::" ).each { |c| obj_class = obj_class.const_get( c ) } if tclass
return [ type, obj_class ]
end
#
# Allocate blank object
#
def YAML.object_maker( obj_class, val )
if Hash === val
o = obj_class.allocate
val.each_pair { |k,v|
o.instance_variable_set("@#{k}", v)
}
o
else
raise YAML::Error, "Invalid object explicitly tagged !ruby/Object: " + val.inspect
end
end
#
# Allocate an Emitter if needed
#
def YAML.quick_emit( oid, opts = {}, &e )
out =
if opts.is_a? YAML::Emitter
opts
else
emitter.reset( opts )
end
out.emit( oid, &e )
end
end
require 'yaml/rubytypes'
require 'yaml/types'
module Kernel
#
# ryan:: You know how Kernel.p is a really convenient way to dump ruby
# structures? The only downside is that it's not as legible as
# YAML.
#
# _why:: (listening)
#
# ryan:: I know you don't want to urinate all over your users' namespaces.
# But, on the other hand, convenience of dumping for debugging is,
# IMO, a big YAML use case.
#
# _why:: Go nuts! Have a pony parade!
#
# ryan:: Either way, I certainly will have a pony parade.
#
# Prints any supplied _objects_ out in YAML. Intended as
# a variation on +Kernel::p+.
#
# S = Struct.new(:name, :state)
# s = S['dave', 'TX']
# y s
#
# _produces:_
#
# --- !ruby/struct:S
# name: dave
# state: TX
#
def y( object, *objects )
objects.unshift object
puts( if objects.length == 1
YAML::dump( *objects )
else
YAML::dump_stream( *objects )
end )
end
private :y
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/csv.rb | tools/jruby-1.5.1/lib/ruby/1.9/csv.rb | # encoding: US-ASCII
# = csv.rb -- CSV Reading and Writing
#
# Created by James Edward Gray II on 2005-10-31.
# Copyright 2005 James Edward Gray II. You can redistribute or modify this code
# under the terms of Ruby's license.
#
# See CSV for documentation.
#
# == Description
#
# Welcome to the new and improved CSV.
#
# This version of the CSV library began its life as FasterCSV. FasterCSV was
# intended as a replacement to Ruby's then standard CSV library. It was
# designed to address concerns users of that library had and it had three
# primary goals:
#
# 1. Be significantly faster than CSV while remaining a pure Ruby library.
# 2. Use a smaller and easier to maintain code base. (FasterCSV eventually
# grew larger, was also but considerably richer in features. The parsing
# core remains quite small.)
# 3. Improve on the CSV interface.
#
# Obviously, the last one is subjective. I did try to defer to the original
# interface whenever I didn't have a compelling reason to change it though, so
# hopefully this won't be too radically different.
#
# We must have met our goals because FasterCSV was renamed to CSV and replaced
# the original library.
#
# == What's Different From the Old CSV?
#
# I'm sure I'll miss something, but I'll try to mention most of the major
# differences I am aware of, to help others quickly get up to speed:
#
# === CSV Parsing
#
# * This parser is m17n aware. See CSV for full details.
# * This library has a stricter parser and will throw MalformedCSVErrors on
# problematic data.
# * This library has a less liberal idea of a line ending than CSV. What you
# set as the <tt>:row_sep</tt> is law. It can auto-detect your line endings
# though.
# * The old library returned empty lines as <tt>[nil]</tt>. This library calls
# them <tt>[]</tt>.
# * This library has a much faster parser.
#
# === Interface
#
# * CSV now uses Hash-style parameters to set options.
# * CSV no longer has generate_row() or parse_row().
# * The old CSV's Reader and Writer classes have been dropped.
# * CSV::open() is now more like Ruby's open().
# * CSV objects now support most standard IO methods.
# * CSV now has a new() method used to wrap objects like String and IO for
# reading and writing.
# * CSV::generate() is different from the old method.
# * CSV no longer supports partial reads. It works line-by-line.
# * CSV no longer allows the instance methods to override the separators for
# performance reasons. They must be set in the constructor.
#
# If you use this library and find yourself missing any functionality I have
# trimmed, please {let me know}[mailto:james@grayproductions.net].
#
# == Documentation
#
# See CSV for documentation.
#
# == What is CSV, really?
#
# CSV maintains a pretty strict definition of CSV taken directly from
# {the RFC}[http://www.ietf.org/rfc/rfc4180.txt]. I relax the rules in only one
# place and that is to make using this library easier. CSV will parse all valid
# CSV.
#
# What you don't want to do is feed CSV invalid data. Because of the way the
# CSV format works, it's common for a parser to need to read until the end of
# the file to be sure a field is invalid. This eats a lot of time and memory.
#
# Luckily, when working with invalid CSV, Ruby's built-in methods will almost
# always be superior in every way. For example, parsing non-quoted fields is as
# easy as:
#
# data.split(",")
#
# == Questions and/or Comments
#
# Feel free to email {James Edward Gray II}[mailto:james@grayproductions.net]
# with any questions.
require "forwardable"
require "English"
require "date"
require "stringio"
#
# This class provides a complete interface to CSV files and data. It offers
# tools to enable you to read and write to and from Strings or IO objects, as
# needed.
#
# == Reading
#
# === From a File
#
# ==== A Line at a Time
#
# CSV.foreach("path/to/file.csv") do |row|
# # use row here...
# end
#
# ==== All at Once
#
# arr_of_arrs = CSV.read("path/to/file.csv")
#
# === From a String
#
# ==== A Line at a Time
#
# CSV.parse("CSV,data,String") do |row|
# # use row here...
# end
#
# ==== All at Once
#
# arr_of_arrs = CSV.parse("CSV,data,String")
#
# == Writing
#
# === To a File
#
# CSV.open("path/to/file.csv", "wb") do |csv|
# csv << ["row", "of", "CSV", "data"]
# csv << ["another", "row"]
# # ...
# end
#
# === To a String
#
# csv_string = CSV.generate do |csv|
# csv << ["row", "of", "CSV", "data"]
# csv << ["another", "row"]
# # ...
# end
#
# == Convert a Single Line
#
# csv_string = ["CSV", "data"].to_csv # to CSV
# csv_array = "CSV,String".parse_csv # from CSV
#
# == Shortcut Interface
#
# CSV { |csv_out| csv_out << %w{my data here} } # to $stdout
# CSV(csv = "") { |csv_str| csv_str << %w{my data here} } # to a String
# CSV($stderr) { |csv_err| csv_err << %w{my data here} } # to $stderr
#
# == CSV and Character Encodings (M17n or Multilingualization)
#
# This new CSV parser is m17n savvy. The parser works in the Encoding of the IO
# or String object being read from or written to. Your data is never transcoded
# (unless you ask Ruby to transcode it for you) and will literally be parsed in
# the Encoding it is in. Thus CSV will return Arrays or Rows of Strings in the
# Encoding of your data. This is accomplished by transcoding the parser itself
# into your Encoding.
#
# Some transcoding must take place, of course, to accomplish this multiencoding
# support. For example, <tt>:col_sep</tt>, <tt>:row_sep</tt>, and
# <tt>:quote_char</tt> must be transcoded to match your data. Hopefully this
# makes the entire process feel transparent, since CSV's defaults should just
# magically work for you data. However, you can set these values manually in
# the target Encoding to avoid the translation.
#
# It's also important to note that while all of CSV's core parser is now
# Encoding agnostic, some features are not. For example, the built-in
# converters will try to transcode data to UTF-8 before making conversions.
# Again, you can provide custom converters that are aware of your Encodings to
# avoid this translation. It's just too hard for me to support native
# conversions in all of Ruby's Encodings.
#
# Anyway, the practical side of this is simple: make sure IO and String objects
# passed into CSV have the proper Encoding set and everything should just work.
# CSV methods that allow you to open IO objects (CSV::foreach(), CSV::open(),
# CSV::read(), and CSV::readlines()) do allow you to specify the Encoding.
#
# One minor exception comes when generating CSV into a String with an Encoding
# that is not ASCII compatible. There's no existing data for CSV to use to
# prepare itself and thus you will probably need to manually specify the desired
# Encoding for most of those cases. It will try to guess using the fields in a
# row of output though, when using CSV::generate_line() or Array#to_csv().
#
# I try to point out any other Encoding issues in the documentation of methods
# as they come up.
#
# This has been tested to the best of my ability with all non-"dummy" Encodings
# Ruby ships with. However, it is brave new code and may have some bugs.
# Please feel free to {report}[mailto:james@grayproductions.net] any issues you
# find with it.
#
class CSV
# The version of the installed library.
VERSION = "2.4.5".freeze
#
# A CSV::Row is part Array and part Hash. It retains an order for the fields
# and allows duplicates just as an Array would, but also allows you to access
# fields by name just as you could if they were in a Hash.
#
# All rows returned by CSV will be constructed from this class, if header row
# processing is activated.
#
class Row
#
# Construct a new CSV::Row from +headers+ and +fields+, which are expected
# to be Arrays. If one Array is shorter than the other, it will be padded
# with +nil+ objects.
#
# The optional +header_row+ parameter can be set to +true+ to indicate, via
# CSV::Row.header_row?() and CSV::Row.field_row?(), that this is a header
# row. Otherwise, the row is assumes to be a field row.
#
# A CSV::Row object supports the following Array methods through delegation:
#
# * empty?()
# * length()
# * size()
#
def initialize(headers, fields, header_row = false)
@header_row = header_row
# handle extra headers or fields
@row = if headers.size > fields.size
headers.zip(fields)
else
fields.zip(headers).map { |pair| pair.reverse }
end
end
# Internal data format used to compare equality.
attr_reader :row
protected :row
### Array Delegation ###
extend Forwardable
def_delegators :@row, :empty?, :length, :size
# Returns +true+ if this is a header row.
def header_row?
@header_row
end
# Returns +true+ if this is a field row.
def field_row?
not header_row?
end
# Returns the headers of this row.
def headers
@row.map { |pair| pair.first }
end
#
# :call-seq:
# field( header )
# field( header, offset )
# field( index )
#
# This method will fetch the field value by +header+ or +index+. If a field
# is not found, +nil+ is returned.
#
# When provided, +offset+ ensures that a header match occurrs on or later
# than the +offset+ index. You can use this to find duplicate headers,
# without resorting to hard-coding exact indices.
#
def field(header_or_index, minimum_index = 0)
# locate the pair
finder = header_or_index.is_a?(Integer) ? :[] : :assoc
pair = @row[minimum_index..-1].send(finder, header_or_index)
# return the field if we have a pair
pair.nil? ? nil : pair.last
end
alias_method :[], :field
#
# :call-seq:
# []=( header, value )
# []=( header, offset, value )
# []=( index, value )
#
# Looks up the field by the semantics described in CSV::Row.field() and
# assigns the +value+.
#
# Assigning past the end of the row with an index will set all pairs between
# to <tt>[nil, nil]</tt>. Assigning to an unused header appends the new
# pair.
#
def []=(*args)
value = args.pop
if args.first.is_a? Integer
if @row[args.first].nil? # extending past the end with index
@row[args.first] = [nil, value]
@row.map! { |pair| pair.nil? ? [nil, nil] : pair }
else # normal index assignment
@row[args.first][1] = value
end
else
index = index(*args)
if index.nil? # appending a field
self << [args.first, value]
else # normal header assignment
@row[index][1] = value
end
end
end
#
# :call-seq:
# <<( field )
# <<( header_and_field_array )
# <<( header_and_field_hash )
#
# If a two-element Array is provided, it is assumed to be a header and field
# and the pair is appended. A Hash works the same way with the key being
# the header and the value being the field. Anything else is assumed to be
# a lone field which is appended with a +nil+ header.
#
# This method returns the row for chaining.
#
def <<(arg)
if arg.is_a?(Array) and arg.size == 2 # appending a header and name
@row << arg
elsif arg.is_a?(Hash) # append header and name pairs
arg.each { |pair| @row << pair }
else # append field value
@row << [nil, arg]
end
self # for chaining
end
#
# A shortcut for appending multiple fields. Equivalent to:
#
# args.each { |arg| csv_row << arg }
#
# This method returns the row for chaining.
#
def push(*args)
args.each { |arg| self << arg }
self # for chaining
end
#
# :call-seq:
# delete( header )
# delete( header, offset )
# delete( index )
#
# Used to remove a pair from the row by +header+ or +index+. The pair is
# located as described in CSV::Row.field(). The deleted pair is returned,
# or +nil+ if a pair could not be found.
#
def delete(header_or_index, minimum_index = 0)
if header_or_index.is_a? Integer # by index
@row.delete_at(header_or_index)
else # by header
@row.delete_at(index(header_or_index, minimum_index))
end
end
#
# The provided +block+ is passed a header and field for each pair in the row
# and expected to return +true+ or +false+, depending on whether the pair
# should be deleted.
#
# This method returns the row for chaining.
#
def delete_if(&block)
@row.delete_if(&block)
self # for chaining
end
#
# This method accepts any number of arguments which can be headers, indices,
# Ranges of either, or two-element Arrays containing a header and offset.
# Each argument will be replaced with a field lookup as described in
# CSV::Row.field().
#
# If called with no arguments, all fields are returned.
#
def fields(*headers_and_or_indices)
if headers_and_or_indices.empty? # return all fields--no arguments
@row.map { |pair| pair.last }
else # or work like values_at()
headers_and_or_indices.inject(Array.new) do |all, h_or_i|
all + if h_or_i.is_a? Range
index_begin = h_or_i.begin.is_a?(Integer) ? h_or_i.begin :
index(h_or_i.begin)
index_end = h_or_i.end.is_a?(Integer) ? h_or_i.end :
index(h_or_i.end)
new_range = h_or_i.exclude_end? ? (index_begin...index_end) :
(index_begin..index_end)
fields.values_at(new_range)
else
[field(*Array(h_or_i))]
end
end
end
end
alias_method :values_at, :fields
#
# :call-seq:
# index( header )
# index( header, offset )
#
# This method will return the index of a field with the provided +header+.
# The +offset+ can be used to locate duplicate header names, as described in
# CSV::Row.field().
#
def index(header, minimum_index = 0)
# find the pair
index = headers[minimum_index..-1].index(header)
# return the index at the right offset, if we found one
index.nil? ? nil : index + minimum_index
end
# Returns +true+ if +name+ is a header for this row, and +false+ otherwise.
def header?(name)
headers.include? name
end
alias_method :include?, :header?
#
# Returns +true+ if +data+ matches a field in this row, and +false+
# otherwise.
#
def field?(data)
fields.include? data
end
include Enumerable
#
# Yields each pair of the row as header and field tuples (much like
# iterating over a Hash).
#
# Support for Enumerable.
#
# This method returns the row for chaining.
#
def each(&block)
@row.each(&block)
self # for chaining
end
#
# Returns +true+ if this row contains the same headers and fields in the
# same order as +other+.
#
def ==(other)
@row == other.row
end
#
# Collapses the row into a simple Hash. Be warning that this discards field
# order and clobbers duplicate fields.
#
def to_hash
# flatten just one level of the internal Array
Hash[*@row.inject(Array.new) { |ary, pair| ary.push(*pair) }]
end
#
# Returns the row as a CSV String. Headers are not used. Equivalent to:
#
# csv_row.fields.to_csv( options )
#
def to_csv(options = Hash.new)
fields.to_csv(options)
end
alias_method :to_s, :to_csv
# A summary of fields, by header, in an ASCII compatible String.
def inspect
str = ["#<", self.class.to_s]
each do |header, field|
str << " " << (header.is_a?(Symbol) ? header.to_s : header.inspect) <<
":" << field.inspect
end
str << ">"
begin
str.join
rescue # any encoding error
str.map do |s|
e = Encoding::Converter.asciicompat_encoding(s.encoding)
e ? s.encode(e) : s.force_encoding("ASCII-8BIT")
end.join
end
end
end
#
# A CSV::Table is a two-dimensional data structure for representing CSV
# documents. Tables allow you to work with the data by row or column,
# manipulate the data, and even convert the results back to CSV, if needed.
#
# All tables returned by CSV will be constructed from this class, if header
# row processing is activated.
#
class Table
#
# Construct a new CSV::Table from +array_of_rows+, which are expected
# to be CSV::Row objects. All rows are assumed to have the same headers.
#
# A CSV::Table object supports the following Array methods through
# delegation:
#
# * empty?()
# * length()
# * size()
#
def initialize(array_of_rows)
@table = array_of_rows
@mode = :col_or_row
end
# The current access mode for indexing and iteration.
attr_reader :mode
# Internal data format used to compare equality.
attr_reader :table
protected :table
### Array Delegation ###
extend Forwardable
def_delegators :@table, :empty?, :length, :size
#
# Returns a duplicate table object, in column mode. This is handy for
# chaining in a single call without changing the table mode, but be aware
# that this method can consume a fair amount of memory for bigger data sets.
#
# This method returns the duplicate table for chaining. Don't chain
# destructive methods (like []=()) this way though, since you are working
# with a duplicate.
#
def by_col
self.class.new(@table.dup).by_col!
end
#
# Switches the mode of this table to column mode. All calls to indexing and
# iteration methods will work with columns until the mode is changed again.
#
# This method returns the table and is safe to chain.
#
def by_col!
@mode = :col
self
end
#
# Returns a duplicate table object, in mixed mode. This is handy for
# chaining in a single call without changing the table mode, but be aware
# that this method can consume a fair amount of memory for bigger data sets.
#
# This method returns the duplicate table for chaining. Don't chain
# destructive methods (like []=()) this way though, since you are working
# with a duplicate.
#
def by_col_or_row
self.class.new(@table.dup).by_col_or_row!
end
#
# Switches the mode of this table to mixed mode. All calls to indexing and
# iteration methods will use the default intelligent indexing system until
# the mode is changed again. In mixed mode an index is assumed to be a row
# reference while anything else is assumed to be column access by headers.
#
# This method returns the table and is safe to chain.
#
def by_col_or_row!
@mode = :col_or_row
self
end
#
# Returns a duplicate table object, in row mode. This is handy for chaining
# in a single call without changing the table mode, but be aware that this
# method can consume a fair amount of memory for bigger data sets.
#
# This method returns the duplicate table for chaining. Don't chain
# destructive methods (like []=()) this way though, since you are working
# with a duplicate.
#
def by_row
self.class.new(@table.dup).by_row!
end
#
# Switches the mode of this table to row mode. All calls to indexing and
# iteration methods will work with rows until the mode is changed again.
#
# This method returns the table and is safe to chain.
#
def by_row!
@mode = :row
self
end
#
# Returns the headers for the first row of this table (assumed to match all
# other rows). An empty Array is returned for empty tables.
#
def headers
if @table.empty?
Array.new
else
@table.first.headers
end
end
#
# In the default mixed mode, this method returns rows for index access and
# columns for header access. You can force the index association by first
# calling by_col!() or by_row!().
#
# Columns are returned as an Array of values. Altering that Array has no
# effect on the table.
#
def [](index_or_header)
if @mode == :row or # by index
(@mode == :col_or_row and index_or_header.is_a? Integer)
@table[index_or_header]
else # by header
@table.map { |row| row[index_or_header] }
end
end
#
# In the default mixed mode, this method assigns rows for index access and
# columns for header access. You can force the index association by first
# calling by_col!() or by_row!().
#
# Rows may be set to an Array of values (which will inherit the table's
# headers()) or a CSV::Row.
#
# Columns may be set to a single value, which is copied to each row of the
# column, or an Array of values. Arrays of values are assigned to rows top
# to bottom in row major order. Excess values are ignored and if the Array
# does not have a value for each row the extra rows will receive a +nil+.
#
# Assigning to an existing column or row clobbers the data. Assigning to
# new columns creates them at the right end of the table.
#
def []=(index_or_header, value)
if @mode == :row or # by index
(@mode == :col_or_row and index_or_header.is_a? Integer)
if value.is_a? Array
@table[index_or_header] = Row.new(headers, value)
else
@table[index_or_header] = value
end
else # set column
if value.is_a? Array # multiple values
@table.each_with_index do |row, i|
if row.header_row?
row[index_or_header] = index_or_header
else
row[index_or_header] = value[i]
end
end
else # repeated value
@table.each do |row|
if row.header_row?
row[index_or_header] = index_or_header
else
row[index_or_header] = value
end
end
end
end
end
#
# The mixed mode default is to treat a list of indices as row access,
# returning the rows indicated. Anything else is considered columnar
# access. For columnar access, the return set has an Array for each row
# with the values indicated by the headers in each Array. You can force
# column or row mode using by_col!() or by_row!().
#
# You cannot mix column and row access.
#
def values_at(*indices_or_headers)
if @mode == :row or # by indices
( @mode == :col_or_row and indices_or_headers.all? do |index|
index.is_a?(Integer) or
( index.is_a?(Range) and
index.first.is_a?(Integer) and
index.last.is_a?(Integer) )
end )
@table.values_at(*indices_or_headers)
else # by headers
@table.map { |row| row.values_at(*indices_or_headers) }
end
end
#
# Adds a new row to the bottom end of this table. You can provide an Array,
# which will be converted to a CSV::Row (inheriting the table's headers()),
# or a CSV::Row.
#
# This method returns the table for chaining.
#
def <<(row_or_array)
if row_or_array.is_a? Array # append Array
@table << Row.new(headers, row_or_array)
else # append Row
@table << row_or_array
end
self # for chaining
end
#
# A shortcut for appending multiple rows. Equivalent to:
#
# rows.each { |row| self << row }
#
# This method returns the table for chaining.
#
def push(*rows)
rows.each { |row| self << row }
self # for chaining
end
#
# Removes and returns the indicated column or row. In the default mixed
# mode indices refer to rows and everything else is assumed to be a column
# header. Use by_col!() or by_row!() to force the lookup.
#
def delete(index_or_header)
if @mode == :row or # by index
(@mode == :col_or_row and index_or_header.is_a? Integer)
@table.delete_at(index_or_header)
else # by header
@table.map { |row| row.delete(index_or_header).last }
end
end
#
# Removes any column or row for which the block returns +true+. In the
# default mixed mode or row mode, iteration is the standard row major
# walking of rows. In column mode, interation will +yield+ two element
# tuples containing the column name and an Array of values for that column.
#
# This method returns the table for chaining.
#
def delete_if(&block)
if @mode == :row or @mode == :col_or_row # by index
@table.delete_if(&block)
else # by header
to_delete = Array.new
headers.each_with_index do |header, i|
to_delete << header if block[[header, self[header]]]
end
to_delete.map { |header| delete(header) }
end
self # for chaining
end
include Enumerable
#
# In the default mixed mode or row mode, iteration is the standard row major
# walking of rows. In column mode, interation will +yield+ two element
# tuples containing the column name and an Array of values for that column.
#
# This method returns the table for chaining.
#
def each(&block)
if @mode == :col
headers.each { |header| block[[header, self[header]]] }
else
@table.each(&block)
end
self # for chaining
end
# Returns +true+ if all rows of this table ==() +other+'s rows.
def ==(other)
@table == other.table
end
#
# Returns the table as an Array of Arrays. Headers will be the first row,
# then all of the field rows will follow.
#
def to_a
@table.inject([headers]) do |array, row|
if row.header_row?
array
else
array + [row.fields]
end
end
end
#
# Returns the table as a complete CSV String. Headers will be listed first,
# then all of the field rows.
#
def to_csv(options = Hash.new)
@table.inject([headers.to_csv(options)]) do |rows, row|
if row.header_row?
rows
else
rows + [row.fields.to_csv(options)]
end
end.join
end
alias_method :to_s, :to_csv
# Shows the mode and size of this table in a US-ASCII String.
def inspect
"#<#{self.class} mode:#{@mode} row_count:#{to_a.size}>".encode("US-ASCII")
end
end
# The error thrown when the parser encounters illegal CSV formatting.
class MalformedCSVError < RuntimeError; end
#
# A FieldInfo Struct contains details about a field's position in the data
# source it was read from. CSV will pass this Struct to some blocks that make
# decisions based on field structure. See CSV.convert_fields() for an
# example.
#
# <b><tt>index</tt></b>:: The zero-based index of the field in its row.
# <b><tt>line</tt></b>:: The line of the data source this row is from.
# <b><tt>header</tt></b>:: The header for the column, when available.
#
FieldInfo = Struct.new(:index, :line, :header)
# A Regexp used to find and convert some common Date formats.
DateMatcher = / \A(?: (\w+,?\s+)?\w+\s+\d{1,2},?\s+\d{2,4} |
\d{4}-\d{2}-\d{2} )\z /x
# A Regexp used to find and convert some common DateTime formats.
DateTimeMatcher =
/ \A(?: (\w+,?\s+)?\w+\s+\d{1,2}\s+\d{1,2}:\d{1,2}:\d{1,2},?\s+\d{2,4} |
\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2} )\z /x
# The encoding used by all converters.
ConverterEncoding = Encoding.find("UTF-8")
#
# This Hash holds the built-in converters of CSV that can be accessed by name.
# You can select Converters with CSV.convert() or through the +options+ Hash
# passed to CSV::new().
#
# <b><tt>:integer</tt></b>:: Converts any field Integer() accepts.
# <b><tt>:float</tt></b>:: Converts any field Float() accepts.
# <b><tt>:numeric</tt></b>:: A combination of <tt>:integer</tt>
# and <tt>:float</tt>.
# <b><tt>:date</tt></b>:: Converts any field Date::parse() accepts.
# <b><tt>:date_time</tt></b>:: Converts any field DateTime::parse() accepts.
# <b><tt>:all</tt></b>:: All built-in converters. A combination of
# <tt>:date_time</tt> and <tt>:numeric</tt>.
#
# All built-in converters transcode field data to UTF-8 before attempting a
# conversion. If your data cannot be transcoded to UTF-8 the conversion will
# fail and the field will remain unchanged.
#
# This Hash is intentionally left unfrozen and users should feel free to add
# values to it that can be accessed by all CSV objects.
#
# To add a combo field, the value should be an Array of names. Combo fields
# can be nested with other combo fields.
#
Converters = { integer: lambda { |f|
Integer(f.encode(ConverterEncoding)) rescue f
},
float: lambda { |f|
Float(f.encode(ConverterEncoding)) rescue f
},
numeric: [:integer, :float],
date: lambda { |f|
begin
e = f.encode(ConverterEncoding)
e =~ DateMatcher ? Date.parse(e) : f
rescue # encoding conversion or date parse errors
f
end
},
date_time: lambda { |f|
begin
e = f.encode(ConverterEncoding)
e =~ DateTimeMatcher ? DateTime.parse(e) : f
rescue # encoding conversion or date parse errors
f
end
},
all: [:date_time, :numeric] }
#
# This Hash holds the built-in header converters of CSV that can be accessed
# by name. You can select HeaderConverters with CSV.header_convert() or
# through the +options+ Hash passed to CSV::new().
#
# <b><tt>:downcase</tt></b>:: Calls downcase() on the header String.
# <b><tt>:symbol</tt></b>:: The header String is downcased, spaces are
# replaced with underscores, non-word characters
# are dropped, and finally to_sym() is called.
#
# All built-in header converters transcode header data to UTF-8 before
# attempting a conversion. If your data cannot be transcoded to UTF-8 the
# conversion will fail and the header will remain unchanged.
#
# This Hash is intetionally left unfrozen and users should feel free to add
# values to it that can be accessed by all CSV objects.
#
# To add a combo field, the value should be an Array of names. Combo fields
# can be nested with other combo fields.
#
HeaderConverters = {
downcase: lambda { |h| h.encode(ConverterEncoding).downcase },
symbol: lambda { |h|
h.encode(ConverterEncoding).downcase.gsub(/\s+/, "_").
gsub(/\W+/, "").to_sym
}
}
#
# The options used when no overrides are given by calling code. They are:
#
# <b><tt>:col_sep</tt></b>:: <tt>","</tt>
# <b><tt>:row_sep</tt></b>:: <tt>:auto</tt>
# <b><tt>:quote_char</tt></b>:: <tt>'"'</tt>
# <b><tt>:field_size_limit</tt></b>:: +nil+
# <b><tt>:converters</tt></b>:: +nil+
# <b><tt>:unconverted_fields</tt></b>:: +nil+
# <b><tt>:headers</tt></b>:: +false+
# <b><tt>:return_headers</tt></b>:: +false+
# <b><tt>:header_converters</tt></b>:: +nil+
# <b><tt>:skip_blanks</tt></b>:: +false+
# <b><tt>:force_quotes</tt></b>:: +false+
#
| 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/irb.rb | tools/jruby-1.5.1/lib/ruby/1.9/irb.rb | #
# irb.rb - irb main module
# $Release Version: 0.9.6 $
# $Revision: 24233 $
# by Keiju ISHITSUKA(keiju@ruby-lang.org)
#
# --
#
#
#
require "e2mmap"
require "irb/init"
require "irb/context"
require "irb/extend-command"
#require "irb/workspace"
require "irb/ruby-lex"
require "irb/input-method"
require "irb/locale"
STDOUT.sync = true
module IRB
@RCS_ID='-$Id: irb.rb 24233 2009-07-21 17:35:24Z keiju $-'
class Abort < Exception;end
#
@CONF = {}
def IRB.conf
@CONF
end
# IRB version method
def IRB.version
if v = @CONF[:VERSION] then return v end
require "irb/version"
rv = @RELEASE_VERSION.sub(/\.0/, "")
@CONF[:VERSION] = format("irb %s(%s)", rv, @LAST_UPDATE_DATE)
end
def IRB.CurrentContext
IRB.conf[:MAIN_CONTEXT]
end
# initialize IRB and start TOP_LEVEL irb
def IRB.start(ap_path = nil)
$0 = File::basename(ap_path, ".rb") if ap_path
IRB.setup(ap_path)
if @CONF[:SCRIPT]
irb = Irb.new(nil, @CONF[:SCRIPT])
else
irb = Irb.new
end
@CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC]
@CONF[:MAIN_CONTEXT] = irb.context
trap("SIGINT") do
irb.signal_handle
end
begin
catch(:IRB_EXIT) do
irb.eval_input
end
ensure
irb_at_exit
end
# print "\n"
end
def IRB.irb_at_exit
@CONF[:AT_EXIT].each{|hook| hook.call}
end
def IRB.irb_exit(irb, ret)
throw :IRB_EXIT, ret
end
def IRB.irb_abort(irb, exception = Abort)
if defined? Thread
irb.context.thread.raise exception, "abort then interrupt!!"
else
raise exception, "abort then interrupt!!"
end
end
#
# irb interpreter main routine
#
class Irb
def initialize(workspace = nil, input_method = nil, output_method = nil)
@context = Context.new(self, workspace, input_method, output_method)
@context.main.extend ExtendCommandBundle
@signal_status = :IN_IRB
@scanner = RubyLex.new
@scanner.exception_on_syntax_error = false
end
attr_reader :context
attr_accessor :scanner
def eval_input
@scanner.set_prompt do
|ltype, indent, continue, line_no|
if ltype
f = @context.prompt_s
elsif continue
f = @context.prompt_c
elsif indent > 0
f = @context.prompt_n
else
f = @context.prompt_i
end
f = "" unless f
if @context.prompting?
@context.io.prompt = p = prompt(f, ltype, indent, line_no)
else
@context.io.prompt = p = ""
end
if @context.auto_indent_mode
unless ltype
ind = prompt(@context.prompt_i, ltype, indent, line_no)[/.*\z/].size +
indent * 2 - p.size
ind += 2 if continue
@context.io.prompt = p + " " * ind if ind > 0
end
end
end
@scanner.set_input(@context.io) do
signal_status(:IN_INPUT) do
if l = @context.io.gets
print l if @context.verbose?
else
if @context.ignore_eof? and @context.io.readable_atfer_eof?
l = "\n"
if @context.verbose?
printf "Use \"exit\" to leave %s\n", @context.ap_name
end
end
end
l
end
end
@scanner.each_top_level_statement do |line, line_no|
signal_status(:IN_EVAL) do
begin
line.untaint
@context.evaluate(line, line_no)
output_value if @context.echo?
exc = nil
rescue Interrupt => exc
rescue SystemExit, SignalException
raise
rescue Exception => exc
end
if exc
print exc.class, ": ", exc, "\n"
if exc.backtrace[0] =~ /irb(2)?(\/.*|-.*|\.rb)?:/ && exc.class.to_s !~ /^IRB/ &&
!(SyntaxError === exc)
irb_bug = true
else
irb_bug = false
end
messages = []
lasts = []
levels = 0
for m in exc.backtrace
m = @context.workspace.filter_backtrace(m) unless irb_bug
if m
if messages.size < @context.back_trace_limit
messages.push "\tfrom "+m
else
lasts.push "\tfrom "+m
if lasts.size > @context.back_trace_limit
lasts.shift
levels += 1
end
end
end
end
print messages.join("\n"), "\n"
unless lasts.empty?
printf "... %d levels...\n", levels if levels > 0
print lasts.join("\n")
end
print "Maybe IRB bug!!\n" if irb_bug
end
if $SAFE > 2
abort "Error: irb does not work for $SAFE level higher than 2"
end
end
end
end
def suspend_name(path = nil, name = nil)
@context.irb_path, back_path = path, @context.irb_path if path
@context.irb_name, back_name = name, @context.irb_name if name
begin
yield back_path, back_name
ensure
@context.irb_path = back_path if path
@context.irb_name = back_name if name
end
end
def suspend_workspace(workspace)
@context.workspace, back_workspace = workspace, @context.workspace
begin
yield back_workspace
ensure
@context.workspace = back_workspace
end
end
def suspend_input_method(input_method)
back_io = @context.io
@context.instance_eval{@io = input_method}
begin
yield back_io
ensure
@context.instance_eval{@io = back_io}
end
end
def suspend_context(context)
@context, back_context = context, @context
begin
yield back_context
ensure
@context = back_context
end
end
def signal_handle
unless @context.ignore_sigint?
print "\nabort!!\n" if @context.verbose?
exit
end
case @signal_status
when :IN_INPUT
print "^C\n"
raise RubyLex::TerminateLineInput
when :IN_EVAL
IRB.irb_abort(self)
when :IN_LOAD
IRB.irb_abort(self, LoadAbort)
when :IN_IRB
# ignore
else
# ignore other cases as well
end
end
def signal_status(status)
return yield if @signal_status == :IN_LOAD
signal_status_back = @signal_status
@signal_status = status
begin
yield
ensure
@signal_status = signal_status_back
end
end
def prompt(prompt, ltype, indent, line_no)
p = prompt.dup
p.gsub!(/%([0-9]+)?([a-zA-Z])/) do
case $2
when "N"
@context.irb_name
when "m"
@context.main.to_s
when "M"
@context.main.inspect
when "l"
ltype
when "i"
if $1
format("%" + $1 + "d", indent)
else
indent.to_s
end
when "n"
if $1
format("%" + $1 + "d", line_no)
else
line_no.to_s
end
when "%"
"%"
end
end
p
end
def output_value
printf @context.return_format, @context.inspect_last_value
end
def inspect
ary = []
for iv in instance_variables
case (iv = iv.to_s)
when "@signal_status"
ary.push format("%s=:%s", iv, @signal_status.id2name)
when "@context"
ary.push format("%s=%s", iv, eval(iv).__to_s__)
else
ary.push format("%s=%s", iv, eval(iv))
end
end
format("#<%s: %s>", self.class, ary.join(", "))
end
end
# Singleton method
def @CONF.inspect
IRB.version unless self[:VERSION]
array = []
for k, v in sort{|a1, a2| a1[0].id2name <=> a2[0].id2name}
case k
when :MAIN_CONTEXT, :__TMP__EHV__
array.push format("CONF[:%s]=...myself...", k.id2name)
when :PROMPT
s = v.collect{
|kk, vv|
ss = vv.collect{|kkk, vvv| ":#{kkk.id2name}=>#{vvv.inspect}"}
format(":%s=>{%s}", kk.id2name, ss.join(", "))
}
array.push format("CONF[:%s]={%s}", k.id2name, s.join(", "))
else
array.push format("CONF[:%s]=%s", k.id2name, v.inspect)
end
end
array.join("\n")
end
end
| 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/prime.rb | tools/jruby-1.5.1/lib/ruby/1.9/prime.rb | #
# = prime.rb
#
# Prime numbers and factorization library.
#
# Copyright::
# Copyright (c) 1998-2008 Keiju ISHITSUKA(SHL Japan Inc.)
# Copyright (c) 2008 Yuki Sonoda (Yugui) <yugui@yugui.jp>
#
# Documentation::
# Yuki Sonoda
#
require "singleton"
require "forwardable"
class Integer
# Re-composes a prime factorization and returns the product.
#
# See Prime#int_from_prime_division for more details.
def Integer.from_prime_division(pd)
Prime.int_from_prime_division(pd)
end
# Returns the factorization of +self+.
#
# See Prime#prime_division for more details.
def prime_division(generator = Prime::Generator23.new)
Prime.prime_division(self, generator)
end
# Returns true if +self+ is a prime number, false for a composite.
def prime?
Prime.prime?(self)
end
# Iterates the given block over all prime numbers.
#
# See +Prime+#each for more details.
def Integer.each_prime(ubound, &block) # :yields: prime
Prime.each(ubound, &block)
end
end
#
# The set of all prime numbers.
#
# == Example
# Prime.each(100) do |prime|
# p prime #=> 2, 3, 5, 7, 11, ...., 97
# end
#
# == Retrieving the instance
# +Prime+.new is obsolete. Now +Prime+ has the default instance and you can
# access it as +Prime+.instance.
#
# For convenience, each instance method of +Prime+.instance can be accessed
# as a class method of +Prime+.
#
# e.g.
# Prime.instance.prime?(2) #=> true
# Prime.prime?(2) #=> true
#
# == Generators
# A "generator" provides an implementation of enumerating pseudo-prime
# numbers and it remembers the position of enumeration and upper bound.
# Futhermore, it is a external iterator of prime enumeration which is
# compatible to an Enumerator.
#
# +Prime+::+PseudoPrimeGenerator+ is the base class for generators.
# There are few implementations of generator.
#
# [+Prime+::+EratosthenesGenerator+]
# Uses eratosthenes's sieve.
# [+Prime+::+TrialDivisionGenerator+]
# Uses the trial division method.
# [+Prime+::+Generator23+]
# Generates all positive integers which is not divided by 2 nor 3.
# This sequence is very bad as a pseudo-prime sequence. But this
# is faster and uses much less memory than other generators. So,
# it is suitable for factorizing an integer which is not large but
# has many prime factors. e.g. for Prime#prime? .
class Prime
include Enumerable
@the_instance = Prime.new
# obsolete. Use +Prime+::+instance+ or class methods of +Prime+.
def initialize
@generator = EratosthenesGenerator.new
extend OldCompatibility
warn "Prime::new is obsolete. use Prime::instance or class methods of Prime."
end
class<<self
extend Forwardable
include Enumerable
# Returns the default instance of Prime.
def instance; @the_instance end
def method_added(method) # :nodoc:
(class<<self;self;end).def_delegator :instance, method
end
end
# Iterates the given block over all prime numbers.
#
# == Parameters
# +ubound+::
# Optional. An arbitrary positive number.
# The upper bound of enumeration. The method enumerates
# prime numbers infinitely if +ubound+ is nil.
# +generator+::
# Optional. An implementation of pseudo-prime generator.
#
# == Return value
# An evaluated value of the given block at the last time.
# Or an enumerator which is compatible to an +Enumerator+
# if no block given.
#
# == Description
# Calls +block+ once for each prime number, passing the prime as
# a parameter.
#
# +ubound+::
# Upper bound of prime numbers. The iterator stops after
# yields all prime numbers p <= +ubound+.
#
# == Note
# +Prime+.+new+ returns a object extended by +Prime+::+OldCompatibility+
# in order to compatibility to Ruby 1.8, and +Prime+#each is overwritten
# by +Prime+::+OldCompatibility+#+each+.
#
# +Prime+.+new+ is now obsolete. Use +Prime+.+instance+.+each+ or simply
# +Prime+.+each+.
def each(ubound = nil, generator = EratosthenesGenerator.new, &block)
generator.upper_bound = ubound
generator.each(&block)
end
# Returns true if +value+ is prime, false for a composite.
#
# == Parameters
# +value+:: an arbitrary integer to be checked.
# +generator+:: optional. A pseudo-prime generator.
def prime?(value, generator = Prime::Generator23.new)
value = -value if value < 0
return false if value < 2
for num in generator
q,r = value.divmod num
return true if q < num
return false if r == 0
end
end
# Re-composes a prime factorization and returns the product.
#
# == Parameters
# +pd+:: Array of pairs of integers. The each internal
# pair consists of a prime number -- a prime factor --
# and a natural number -- an exponent.
#
# == Example
# For [[p_1, e_1], [p_2, e_2], ...., [p_n, e_n]], it returns
# p_1**e_1 * p_2**e_2 * .... * p_n**e_n.
#
# Prime.int_from_prime_division([[2,2], [3,1]]) #=> 12
def int_from_prime_division(pd)
pd.inject(1){|value, (prime, index)|
value *= prime**index
}
end
# Returns the factorization of +value+.
#
# == Parameters
# +value+:: An arbitrary integer.
# +generator+:: Optional. A pseudo-prime generator.
# +generator+.succ must return the next
# pseudo-prime number in the ascendent
# order. It must generate all prime numbers,
# but may generate non prime numbers.
#
# === Exceptions
# +ZeroDivisionError+:: when +value+ is zero.
#
# == Example
# For an arbitrary integer
# n = p_1**e_1 * p_2**e_2 * .... * p_n**e_n,
# prime_division(n) returns
# [[p_1, e_1], [p_2, e_2], ...., [p_n, e_n]].
#
# Prime.prime_division(12) #=> [[2,2], [3,1]]
#
def prime_division(value, generator= Prime::Generator23.new)
raise ZeroDivisionError if value == 0
if value < 0
value = -value
pv = [[-1, 1]]
else
pv = []
end
for prime in generator
count = 0
while (value1, mod = value.divmod(prime)
mod) == 0
value = value1
count += 1
end
if count != 0
pv.push [prime, count]
end
break if value1 <= prime
end
if value > 1
pv.push [value, 1]
end
return pv
end
# An abstract class for enumerating pseudo-prime numbers.
#
# Concrete subclasses should override succ, next, rewind.
class PseudoPrimeGenerator
include Enumerable
def initialize(ubound = nil)
@ubound = ubound
end
def upper_bound=(ubound)
@ubound = ubound
end
def upper_bound
@ubound
end
# returns the next pseudo-prime number, and move the internal
# position forward.
#
# +PseudoPrimeGenerator+#succ raises +NotImplementedError+.
def succ
raise NotImplementedError, "need to define `succ'"
end
# alias of +succ+.
def next
raise NotImplementedError, "need to define `next'"
end
# Rewinds the internal position for enumeration.
#
# See +Enumerator+#rewind.
def rewind
raise NotImplementedError, "need to define `rewind'"
end
# Iterates the given block for each prime numbers.
def each(&block)
return self.dup unless block
if @ubound
last_value = nil
loop do
prime = succ
break last_value if prime > @ubound
last_value = block.call(prime)
end
else
loop do
block.call(succ)
end
end
end
# see +Enumerator+#with_index.
alias with_index each_with_index
# see +Enumerator+#with_object.
def with_object(obj)
return enum_for(:with_object) unless block_given?
each do |prime|
yield prime, obj
end
end
end
# An implementation of +PseudoPrimeGenerator+.
#
# Uses +EratosthenesSieve+.
class EratosthenesGenerator < PseudoPrimeGenerator
def initialize
@last_prime = nil
end
def succ
@last_prime = @last_prime ? EratosthenesSieve.instance.next_to(@last_prime) : 2
end
def rewind
initialize
end
alias next succ
end
# An implementation of +PseudoPrimeGenerator+ which uses
# a prime table generated by trial division.
class TrialDivisionGenerator<PseudoPrimeGenerator
def initialize
@index = -1
end
def succ
TrialDivision.instance[@index += 1]
end
def rewind
initialize
end
alias next succ
end
# Generates all integer which are greater than 2 and
# are not divided by 2 nor 3.
#
# This is a pseudo-prime generator, suitable on
# checking primality of a integer by brute force
# method.
class Generator23<PseudoPrimeGenerator
def initialize
@prime = 1
@step = nil
end
def succ
loop do
if (@step)
@prime += @step
@step = 6 - @step
else
case @prime
when 1; @prime = 2
when 2; @prime = 3
when 3; @prime = 5; @step = 2
end
end
return @prime
end
end
alias next succ
def rewind
initialize
end
end
# Internal use. An implementation of prime table by trial division method.
class TrialDivision
include Singleton
def initialize # :nodoc:
# These are included as class variables to cache them for later uses. If memory
# usage is a problem, they can be put in Prime#initialize as instance variables.
# There must be no primes between @primes[-1] and @next_to_check.
@primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
# @next_to_check % 6 must be 1.
@next_to_check = 103 # @primes[-1] - @primes[-1] % 6 + 7
@ulticheck_index = 3 # @primes.index(@primes.reverse.find {|n|
# n < Math.sqrt(@@next_to_check) })
@ulticheck_next_squared = 121 # @primes[@ulticheck_index + 1] ** 2
end
# Returns the cached prime numbers.
def cache
return @primes
end
alias primes cache
alias primes_so_far cache
# Returns the +index+th prime number.
#
# +index+ is a 0-based index.
def [](index)
while index >= @primes.length
# Only check for prime factors up to the square root of the potential primes,
# but without the performance hit of an actual square root calculation.
if @next_to_check + 4 > @ulticheck_next_squared
@ulticheck_index += 1
@ulticheck_next_squared = @primes.at(@ulticheck_index + 1) ** 2
end
# Only check numbers congruent to one and five, modulo six. All others
# are divisible by two or three. This also allows us to skip checking against
# two and three.
@primes.push @next_to_check if @primes[2..@ulticheck_index].find {|prime| @next_to_check % prime == 0 }.nil?
@next_to_check += 4
@primes.push @next_to_check if @primes[2..@ulticheck_index].find {|prime| @next_to_check % prime == 0 }.nil?
@next_to_check += 2
end
return @primes[index]
end
end
# Internal use. An implementation of eratosthenes's sieve
class EratosthenesSieve
include Singleton
def initialize # :nodoc:
# bitmap for odd prime numbers less than 256.
# For an arbitrary odd number n, @table[i][j] is 1 when n is prime where i,j = n.divmod(32) .
@table = [0xcb6e, 0x64b4, 0x129a, 0x816d, 0x4c32, 0x864a, 0x820d, 0x2196]
end
# returns the least odd prime number which is greater than +n+.
def next_to(n)
n = (n-1).div(2)*2+3 # the next odd number of given n
i,j = n.divmod(32)
loop do
extend_table until @table.length > i
if !@table[i].zero?
(j...32).step(2) do |k|
return 32*i+k if !@table[i][k.div(2)].zero?
end
end
i += 1; j = 1
end
end
private
def extend_table
orig_len = @table.length
new_len = [orig_len**2, orig_len+256].min
lbound = orig_len*32
ubound = new_len*32
@table.fill(0xFFFF, orig_len...new_len)
(3..Integer(Math.sqrt(ubound))).step(2) do |p|
i, j = p.divmod(32)
next if @table[i][j.div(2)].zero?
start = (lbound.div(2*p)*2+1)*p # odd multiple of p which is greater than or equal to lbound
(start...ubound).step(2*p) do |n|
i, j = n.divmod(32)
@table[i] &= 0xFFFF ^ (1<<(j.div(2)))
end
end
end
end
# Provides a +Prime+ object with compatibility to Ruby 1.8 when instanciated via +Prime+.+new+.
module OldCompatibility
# Returns the next prime number and forwards internal pointer.
def succ
@generator.succ
end
alias next succ
# Overwrites Prime#each.
#
# Iterates the given block over all prime numbers. Note that enumeration starts from
# the current position of internal pointer, not rewound.
def each(&block)
return @generator.dup unless block_given?
loop do
yield succ
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/base64.rb | tools/jruby-1.5.1/lib/ruby/1.9/base64.rb | #
# = base64.rb: methods for base64-encoding and -decoding strings
#
# The Base64 module provides for the encoding (#encode64, #strict_encode64,
# #urlsafe_encode64) and decoding (#decode64, #strict_decode64,
# #urlsafe_decode64) of binary data using a Base64 representation.
#
# == Example
#
# A simple encoding and decoding.
#
# require "base64"
#
# enc = Base64.encode64('Send reinforcements')
# # -> "U2VuZCByZWluZm9yY2VtZW50cw==\n"
# plain = Base64.decode64(enc)
# # -> "Send reinforcements"
#
# The purpose of using base64 to encode data is that it translates any
# binary data into purely printable characters.
module Base64
module_function
# Returns the Base64-encoded version of +bin+.
# This method complies with RFC 2045.
# Line feeds are added to every 60 encoded charactors.
#
# require 'base64'
# Base64.encode64("Now is the time for all good coders\nto learn Ruby")
#
# <i>Generates:</i>
#
# Tm93IGlzIHRoZSB0aW1lIGZvciBhbGwgZ29vZCBjb2RlcnMKdG8gbGVhcm4g
# UnVieQ==
def encode64(bin)
[bin].pack("m")
end
# Returns the Base64-decoded version of +str+.
# This method complies with RFC 2045.
# Characters outside the base alphabet are ignored.
#
# require 'base64'
# str = 'VGhpcyBpcyBsaW5lIG9uZQpUaGlzIG' +
# 'lzIGxpbmUgdHdvClRoaXMgaXMgbGlu' +
# 'ZSB0aHJlZQpBbmQgc28gb24uLi4K'
# puts Base64.decode64(str)
#
# <i>Generates:</i>
#
# This is line one
# This is line two
# This is line three
# And so on...
def decode64(str)
str.unpack("m").first
end
# Returns the Base64-encoded version of +bin+.
# This method complies with RFC 4648.
# No line feeds are added.
def strict_encode64(bin)
[bin].pack("m0")
end
# Returns the Base64-decoded version of +str+.
# This method complies with RFC 4648.
# ArgumentError is raised if +str+ is incorrectly padded or contains
# non-alphabet characters. Note that CR or LF are also rejected.
def strict_decode64(str)
str.unpack("m0").first
end
# Returns the Base64-encoded version of +bin+.
# This method complies with ``Base 64 Encoding with URL and Filename Safe
# Alphabet'' in RFC 4648.
# The alphabet uses '-' instead of '+' and '_' instead of '/'.
def urlsafe_encode64(bin)
strict_encode64(bin).tr("+/", "-_")
end
# Returns the Base64-decoded version of +str+.
# This method complies with ``Base 64 Encoding with URL and Filename Safe
# Alphabet'' in RFC 4648.
# The alphabet uses '-' instead of '+' and '_' instead of '/'.
def urlsafe_decode64(str)
strict_decode64(str.tr("-_", "+/"))
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/un.rb | tools/jruby-1.5.1/lib/ruby/1.9/un.rb | #
# = un.rb
#
# Copyright (c) 2003 WATANABE Hirofumi <eban@ruby-lang.org>
#
# This program is free software.
# You can distribute/modify this program under the same terms of Ruby.
#
# == Utilities to replace common UNIX commands in Makefiles etc
#
# == SYNOPSIS
#
# ruby -run -e cp -- [OPTION] SOURCE DEST
# ruby -run -e ln -- [OPTION] TARGET LINK_NAME
# ruby -run -e mv -- [OPTION] SOURCE DEST
# ruby -run -e rm -- [OPTION] FILE
# ruby -run -e mkdir -- [OPTION] DIRS
# ruby -run -e rmdir -- [OPTION] DIRS
# ruby -run -e install -- [OPTION] SOURCE DEST
# ruby -run -e chmod -- [OPTION] OCTAL-MODE FILE
# ruby -run -e touch -- [OPTION] FILE
# ruby -run -e wait_writable -- [OPTION] FILE
# ruby -run -e mkmf -- [OPTION] EXTNAME [OPTION]
# ruby -run -e help [COMMAND]
require "fileutils"
require "optparse"
module FileUtils
# @fileutils_label = ""
@fileutils_output = $stdout
end
def setup(options = "", *long_options)
opt_hash = {}
argv = []
OptionParser.new do |o|
options.scan(/.:?/) do |s|
opt_name = s.delete(":").intern
o.on("-" + s.tr(":", " ")) do |val|
opt_hash[opt_name] = val
end
end
long_options.each do |s|
opt_name = s[/\A(?:--)?([^\s=]+)/, 1].intern
o.on(s.sub(/\A(?!--)/, '--')) do |val|
opt_hash[opt_name] = val
end
end
o.on("-v") do opt_hash[:verbose] = true end
o.order!(ARGV) do |x|
if /[*?\[{]/ =~ x
argv.concat(Dir[x])
else
argv << x
end
end
end
yield argv, opt_hash
end
##
# Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY
#
# ruby -run -e cp -- [OPTION] SOURCE DEST
#
# -p preserve file attributes if possible
# -r copy recursively
# -v verbose
#
def cp
setup("pr") do |argv, options|
cmd = "cp"
cmd += "_r" if options.delete :r
options[:preserve] = true if options.delete :p
dest = argv.pop
argv = argv[0] if argv.size == 1
FileUtils.send cmd, argv, dest, options
end
end
##
# Create a link to the specified TARGET with LINK_NAME.
#
# ruby -run -e ln -- [OPTION] TARGET LINK_NAME
#
# -s make symbolic links instead of hard links
# -f remove existing destination files
# -v verbose
#
def ln
setup("sf") do |argv, options|
cmd = "ln"
cmd += "_s" if options.delete :s
options[:force] = true if options.delete :f
dest = argv.pop
argv = argv[0] if argv.size == 1
FileUtils.send cmd, argv, dest, options
end
end
##
# Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.
#
# ruby -run -e mv -- [OPTION] SOURCE DEST
#
# -v verbose
#
def mv
setup do |argv, options|
dest = argv.pop
argv = argv[0] if argv.size == 1
FileUtils.mv argv, dest, options
end
end
##
# Remove the FILE
#
# ruby -run -e rm -- [OPTION] FILE
#
# -f ignore nonexistent files
# -r remove the contents of directories recursively
# -v verbose
#
def rm
setup("fr") do |argv, options|
cmd = "rm"
cmd += "_r" if options.delete :r
options[:force] = true if options.delete :f
FileUtils.send cmd, argv, options
end
end
##
# Create the DIR, if they do not already exist.
#
# ruby -run -e mkdir -- [OPTION] DIR
#
# -p no error if existing, make parent directories as needed
# -v verbose
#
def mkdir
setup("p") do |argv, options|
cmd = "mkdir"
cmd += "_p" if options.delete :p
FileUtils.send cmd, argv, options
end
end
##
# Remove the DIR.
#
# ruby -run -e rmdir -- [OPTION] DIR
#
# -p remove DIRECTORY and its ancestors.
# -v verbose
#
def rmdir
setup("p") do |argv, options|
options[:parents] = true if options.delete :p
FileUtils.rmdir argv, options
end
end
##
# Copy SOURCE to DEST.
#
# ruby -run -e install -- [OPTION] SOURCE DEST
#
# -p apply access/modification times of SOURCE files to
# corresponding destination files
# -m set permission mode (as in chmod), instead of 0755
# -v verbose
#
def install
setup("pm:") do |argv, options|
options[:mode] = (mode = options.delete :m) ? mode.oct : 0755
options[:preserve] = true if options.delete :p
dest = argv.pop
argv = argv[0] if argv.size == 1
FileUtils.install argv, dest, options
end
end
##
# Change the mode of each FILE to OCTAL-MODE.
#
# ruby -run -e chmod -- [OPTION] OCTAL-MODE FILE
#
# -v verbose
#
def chmod
setup do |argv, options|
mode = argv.shift.oct
FileUtils.chmod mode, argv, options
end
end
##
# Update the access and modification times of each FILE to the current time.
#
# ruby -run -e touch -- [OPTION] FILE
#
# -v verbose
#
def touch
setup do |argv, options|
FileUtils.touch argv, options
end
end
##
# Wait until the file becomes writable.
#
# ruby -run -e wait_writable -- [OPTION] FILE
#
# -n RETRY count to retry
# -w SEC each wait time in seconds
# -v verbose
#
def wait_writable
setup("n:w:v") do |argv, options|
verbose = options[:verbose]
n = options[:n] and n = Integer(n)
wait = (wait = options[:w]) ? Float(wait) : 0.2
argv.each do |file|
begin
open(file, "r+b")
rescue Errno::ENOENT
break
rescue Errno::EACCES => e
raise if n and (n -= 1) <= 0
puts e
STDOUT.flush
sleep wait
retry
end
end
end
end
##
# Create makefile using mkmf.
#
# ruby -run -e mkmf -- [OPTION] EXTNAME [OPTION]
#
# -d ARGS run dir_config
# -h ARGS run have_header
# -l ARGS run have_library
# -f ARGS run have_func
# -v ARGS run have_var
# -t ARGS run have_type
# -m ARGS run have_macro
# -c ARGS run have_const
# --vendor install to vendor_ruby
#
def mkmf
setup("d:h:l:f:v:t:m:c:", "vendor") do |argv, options|
require 'mkmf'
opt = options[:d] and opt.split(/:/).each {|n| dir_config(*n.split(/,/))}
opt = options[:h] and opt.split(/:/).each {|n| have_header(*n.split(/,/))}
opt = options[:l] and opt.split(/:/).each {|n| have_library(*n.split(/,/))}
opt = options[:f] and opt.split(/:/).each {|n| have_func(*n.split(/,/))}
opt = options[:v] and opt.split(/:/).each {|n| have_var(*n.split(/,/))}
opt = options[:t] and opt.split(/:/).each {|n| have_type(*n.split(/,/))}
opt = options[:m] and opt.split(/:/).each {|n| have_macro(*n.split(/,/))}
opt = options[:c] and opt.split(/:/).each {|n| have_const(*n.split(/,/))}
$configure_args["--vendor"] = true if options[:vendor]
create_makefile(*argv)
end
end
##
# Display help message.
#
# ruby -run -e help [COMMAND]
#
def help
setup do |argv,|
all = argv.empty?
open(__FILE__) do |me|
while me.gets("##\n")
if help = me.gets("\n\n")
if all or argv.delete help[/-e \w+/].sub(/-e /, "")
print help.gsub(/^# ?/, "")
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/1.9/uri.rb | tools/jruby-1.5.1/lib/ruby/1.9/uri.rb | #
# URI support for Ruby
#
# Author:: Akira Yamada <akira@ruby-lang.org>
# Documentation:: Akira Yamada <akira@ruby-lang.org>, Dmitry V. Sabanin <sdmitry@lrn.ru>
# License::
# Copyright (c) 2001 akira yamada <akira@ruby-lang.org>
# You can redistribute it and/or modify it under the same term as Ruby.
# Revision:: $Id: uri.rb 22784 2009-03-06 03:56:38Z nobu $
#
# See URI for documentation
#
module URI
# :stopdoc:
VERSION_CODE = '000911'.freeze
VERSION = VERSION_CODE.scan(/../).collect{|n| n.to_i}.join('.').freeze
# :startdoc:
end
require 'uri/common'
require 'uri/generic'
require 'uri/ftp'
require 'uri/http'
require 'uri/https'
require 'uri/ldap'
require 'uri/ldaps'
require 'uri/mailto'
| 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/debug.rb | tools/jruby-1.5.1/lib/ruby/1.9/debug.rb | # Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
# Copyright (C) 2000 Information-technology Promotion Agency, Japan
# Copyright (C) 2000-2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>
require 'continuation'
if $SAFE > 0
STDERR.print "-r debug.rb is not available in safe mode\n"
exit 1
end
require 'tracer'
require 'pp'
class Tracer
def Tracer.trace_func(*vars)
Single.trace_func(*vars)
end
end
SCRIPT_LINES__ = {} unless defined? SCRIPT_LINES__
class DEBUGGER__
MUTEX = Mutex.new
class Context
DEBUG_LAST_CMD = []
begin
require 'readline'
def readline(prompt, hist)
Readline::readline(prompt, hist)
end
rescue LoadError
def readline(prompt, hist)
STDOUT.print prompt
STDOUT.flush
line = STDIN.gets
exit unless line
line.chomp!
line
end
USE_READLINE = false
end
def initialize
if Thread.current == Thread.main
@stop_next = 1
else
@stop_next = 0
end
@last_file = nil
@file = nil
@line = nil
@no_step = nil
@frames = []
@finish_pos = 0
@trace = false
@catch = "StandardError"
@suspend_next = false
end
def stop_next(n=1)
@stop_next = n
end
def set_suspend
@suspend_next = true
end
def clear_suspend
@suspend_next = false
end
def suspend_all
DEBUGGER__.suspend
end
def resume_all
DEBUGGER__.resume
end
def check_suspend
while MUTEX.synchronize {
if @suspend_next
DEBUGGER__.waiting.push Thread.current
@suspend_next = false
true
end
}
end
end
def trace?
@trace
end
def set_trace(arg)
@trace = arg
end
def stdout
DEBUGGER__.stdout
end
def break_points
DEBUGGER__.break_points
end
def display
DEBUGGER__.display
end
def context(th)
DEBUGGER__.context(th)
end
def set_trace_all(arg)
DEBUGGER__.set_trace(arg)
end
def set_last_thread(th)
DEBUGGER__.set_last_thread(th)
end
def debug_eval(str, binding)
begin
val = eval(str, binding)
rescue StandardError, ScriptError => e
at = eval("caller(1)", binding)
stdout.printf "%s:%s\n", at.shift, e.to_s.sub(/\(eval\):1:(in `.*?':)?/, '')
for i in at
stdout.printf "\tfrom %s\n", i
end
throw :debug_error
end
end
def debug_silent_eval(str, binding)
begin
eval(str, binding)
rescue StandardError, ScriptError
nil
end
end
def var_list(ary, binding)
ary.sort!
for v in ary
stdout.printf " %s => %s\n", v, eval(v, binding).inspect
end
end
def debug_variable_info(input, binding)
case input
when /^\s*g(?:lobal)?\s*$/
var_list(global_variables, binding)
when /^\s*l(?:ocal)?\s*$/
var_list(eval("local_variables", binding), binding)
when /^\s*i(?:nstance)?\s+/
obj = debug_eval($', binding)
var_list(obj.instance_variables, obj.instance_eval{binding()})
when /^\s*c(?:onst(?:ant)?)?\s+/
obj = debug_eval($', binding)
unless obj.kind_of? Module
stdout.print "Should be Class/Module: ", $', "\n"
else
var_list(obj.constants, obj.module_eval{binding()})
end
end
end
def debug_method_info(input, binding)
case input
when /^i(:?nstance)?\s+/
obj = debug_eval($', binding)
len = 0
for v in obj.methods.sort
len += v.size + 1
if len > 70
len = v.size + 1
stdout.print "\n"
end
stdout.print v, " "
end
stdout.print "\n"
else
obj = debug_eval(input, binding)
unless obj.kind_of? Module
stdout.print "Should be Class/Module: ", input, "\n"
else
len = 0
for v in obj.instance_methods(false).sort
len += v.size + 1
if len > 70
len = v.size + 1
stdout.print "\n"
end
stdout.print v, " "
end
stdout.print "\n"
end
end
end
def thnum
num = DEBUGGER__.instance_eval{@thread_list[Thread.current]}
unless num
DEBUGGER__.make_thread_list
num = DEBUGGER__.instance_eval{@thread_list[Thread.current]}
end
num
end
def debug_command(file, line, id, binding)
MUTEX.lock
unless defined?($debugger_restart) and $debugger_restart
callcc{|c| $debugger_restart = c}
end
set_last_thread(Thread.current)
frame_pos = 0
binding_file = file
binding_line = line
previous_line = nil
if ENV['EMACS']
stdout.printf "\032\032%s:%d:\n", binding_file, binding_line
else
stdout.printf "%s:%d:%s", binding_file, binding_line,
line_at(binding_file, binding_line)
end
@frames[0] = [binding, file, line, id]
display_expressions(binding)
prompt = true
while prompt and input = readline("(rdb:%d) "%thnum(), true)
catch(:debug_error) do
if input == ""
next unless DEBUG_LAST_CMD[0]
input = DEBUG_LAST_CMD[0]
stdout.print input, "\n"
else
DEBUG_LAST_CMD[0] = input
end
case input
when /^\s*tr(?:ace)?(?:\s+(on|off))?(?:\s+(all))?$/
if defined?( $2 )
if $1 == 'on'
set_trace_all true
else
set_trace_all false
end
elsif defined?( $1 )
if $1 == 'on'
set_trace true
else
set_trace false
end
end
if trace?
stdout.print "Trace on.\n"
else
stdout.print "Trace off.\n"
end
when /^\s*b(?:reak)?\s+(?:(.+):)?([^.:]+)$/
pos = $2
if $1
klass = debug_silent_eval($1, binding)
file = $1
end
if pos =~ /^\d+$/
pname = pos
pos = pos.to_i
else
pname = pos = pos.intern.id2name
end
break_points.push [true, 0, klass || file, pos]
stdout.printf "Set breakpoint %d at %s:%s\n", break_points.size, klass || file, pname
when /^\s*b(?:reak)?\s+(.+)[#.]([^.:]+)$/
pos = $2.intern.id2name
klass = debug_eval($1, binding)
break_points.push [true, 0, klass, pos]
stdout.printf "Set breakpoint %d at %s.%s\n", break_points.size, klass, pos
when /^\s*wat(?:ch)?\s+(.+)$/
exp = $1
break_points.push [true, 1, exp]
stdout.printf "Set watchpoint %d:%s\n", break_points.size, exp
when /^\s*b(?:reak)?$/
if break_points.find{|b| b[1] == 0}
n = 1
stdout.print "Breakpoints:\n"
break_points.each do |b|
if b[0] and b[1] == 0
stdout.printf " %d %s:%s\n", n, b[2], b[3]
end
n += 1
end
end
if break_points.find{|b| b[1] == 1}
n = 1
stdout.print "\n"
stdout.print "Watchpoints:\n"
for b in break_points
if b[0] and b[1] == 1
stdout.printf " %d %s\n", n, b[2]
end
n += 1
end
end
if break_points.size == 0
stdout.print "No breakpoints\n"
else
stdout.print "\n"
end
when /^\s*del(?:ete)?(?:\s+(\d+))?$/
pos = $1
unless pos
input = readline("Clear all breakpoints? (y/n) ", false)
if input == "y"
for b in break_points
b[0] = false
end
end
else
pos = pos.to_i
if break_points[pos-1]
break_points[pos-1][0] = false
else
stdout.printf "Breakpoint %d is not defined\n", pos
end
end
when /^\s*disp(?:lay)?\s+(.+)$/
exp = $1
display.push [true, exp]
stdout.printf "%d: ", display.size
display_expression(exp, binding)
when /^\s*disp(?:lay)?$/
display_expressions(binding)
when /^\s*undisp(?:lay)?(?:\s+(\d+))?$/
pos = $1
unless pos
input = readline("Clear all expressions? (y/n) ", false)
if input == "y"
for d in display
d[0] = false
end
end
else
pos = pos.to_i
if display[pos-1]
display[pos-1][0] = false
else
stdout.printf "Display expression %d is not defined\n", pos
end
end
when /^\s*c(?:ont)?$/
prompt = false
when /^\s*s(?:tep)?(?:\s+(\d+))?$/
if $1
lev = $1.to_i
else
lev = 1
end
@stop_next = lev
prompt = false
when /^\s*n(?:ext)?(?:\s+(\d+))?$/
if $1
lev = $1.to_i
else
lev = 1
end
@stop_next = lev
@no_step = @frames.size - frame_pos
prompt = false
when /^\s*w(?:here)?$/, /^\s*f(?:rame)?$/
display_frames(frame_pos)
when /^\s*l(?:ist)?(?:\s+(.+))?$/
if not $1
b = previous_line ? previous_line + 10 : binding_line - 5
e = b + 9
elsif $1 == '-'
b = previous_line ? previous_line - 10 : binding_line - 5
e = b + 9
else
b, e = $1.split(/[-,]/)
if e
b = b.to_i
e = e.to_i
else
b = b.to_i - 5
e = b + 9
end
end
previous_line = b
display_list(b, e, binding_file, binding_line)
when /^\s*up(?:\s+(\d+))?$/
previous_line = nil
if $1
lev = $1.to_i
else
lev = 1
end
frame_pos += lev
if frame_pos >= @frames.size
frame_pos = @frames.size - 1
stdout.print "At toplevel\n"
end
binding, binding_file, binding_line = @frames[frame_pos]
stdout.print format_frame(frame_pos)
when /^\s*down(?:\s+(\d+))?$/
previous_line = nil
if $1
lev = $1.to_i
else
lev = 1
end
frame_pos -= lev
if frame_pos < 0
frame_pos = 0
stdout.print "At stack bottom\n"
end
binding, binding_file, binding_line = @frames[frame_pos]
stdout.print format_frame(frame_pos)
when /^\s*fin(?:ish)?$/
if frame_pos == @frames.size
stdout.print "\"finish\" not meaningful in the outermost frame.\n"
else
@finish_pos = @frames.size - frame_pos
frame_pos = 0
prompt = false
end
when /^\s*cat(?:ch)?(?:\s+(.+))?$/
if $1
excn = $1
if excn == 'off'
@catch = nil
stdout.print "Clear catchpoint.\n"
else
@catch = excn
stdout.printf "Set catchpoint %s.\n", @catch
end
else
if @catch
stdout.printf "Catchpoint %s.\n", @catch
else
stdout.print "No catchpoint.\n"
end
end
when /^\s*q(?:uit)?$/
input = readline("Really quit? (y/n) ", false)
if input == "y"
exit! # exit -> exit!: No graceful way to stop threads...
end
when /^\s*v(?:ar)?\s+/
debug_variable_info($', binding)
when /^\s*m(?:ethod)?\s+/
debug_method_info($', binding)
when /^\s*th(?:read)?\s+/
if DEBUGGER__.debug_thread_info($', binding) == :cont
prompt = false
end
when /^\s*pp\s+/
PP.pp(debug_eval($', binding), stdout)
when /^\s*p\s+/
stdout.printf "%s\n", debug_eval($', binding).inspect
when /^\s*r(?:estart)?$/
$debugger_restart.call
when /^\s*h(?:elp)?$/
debug_print_help()
else
v = debug_eval(input, binding)
stdout.printf "%s\n", v.inspect
end
end
end
MUTEX.unlock
resume_all
end
def debug_print_help
stdout.print <<EOHELP
Debugger help v.-0.002b
Commands
b[reak] [file:|class:]<line|method>
b[reak] [class.]<line|method>
set breakpoint to some position
wat[ch] <expression> set watchpoint to some expression
cat[ch] (<exception>|off) set catchpoint to an exception
b[reak] list breakpoints
cat[ch] show catchpoint
del[ete][ nnn] delete some or all breakpoints
disp[lay] <expression> add expression into display expression list
undisp[lay][ nnn] delete one particular or all display expressions
c[ont] run until program ends or hit breakpoint
s[tep][ nnn] step (into methods) one line or till line nnn
n[ext][ nnn] go over one line or till line nnn
w[here] display frames
f[rame] alias for where
l[ist][ (-|nn-mm)] list program, - lists backwards
nn-mm lists given lines
up[ nn] move to higher frame
down[ nn] move to lower frame
fin[ish] return to outer frame
tr[ace] (on|off) set trace mode of current thread
tr[ace] (on|off) all set trace mode of all threads
q[uit] exit from debugger
v[ar] g[lobal] show global variables
v[ar] l[ocal] show local variables
v[ar] i[nstance] <object> show instance variables of object
v[ar] c[onst] <object> show constants of object
m[ethod] i[nstance] <obj> show methods of object
m[ethod] <class|module> show instance methods of class or module
th[read] l[ist] list all threads
th[read] c[ur[rent]] show current thread
th[read] [sw[itch]] <nnn> switch thread context to nnn
th[read] stop <nnn> stop thread nnn
th[read] resume <nnn> resume thread nnn
p expression evaluate expression and print its value
h[elp] print this help
<everything else> evaluate
EOHELP
end
def display_expressions(binding)
n = 1
for d in display
if d[0]
stdout.printf "%d: ", n
display_expression(d[1], binding)
end
n += 1
end
end
def display_expression(exp, binding)
stdout.printf "%s = %s\n", exp, debug_silent_eval(exp, binding).to_s
end
def frame_set_pos(file, line)
if @frames[0]
@frames[0][1] = file
@frames[0][2] = line
end
end
def display_frames(pos)
0.upto(@frames.size - 1) do |n|
if n == pos
stdout.print "--> "
else
stdout.print " "
end
stdout.print format_frame(n)
end
end
def format_frame(pos)
bind, file, line, id = @frames[pos]
sprintf "#%d %s:%s%s\n", pos + 1, file, line,
(id ? ":in `#{id.id2name}'" : "")
end
def display_list(b, e, file, line)
stdout.printf "[%d, %d] in %s\n", b, e, file
if lines = SCRIPT_LINES__[file] and lines != true
b.upto(e) do |n|
if n > 0 && lines[n-1]
if n == line
stdout.printf "=> %d %s\n", n, lines[n-1].chomp
else
stdout.printf " %d %s\n", n, lines[n-1].chomp
end
end
end
else
stdout.printf "No sourcefile available for %s\n", file
end
end
def line_at(file, line)
lines = SCRIPT_LINES__[file]
if lines
return "\n" if lines == true
line = lines[line-1]
return "\n" unless line
return line
end
return "\n"
end
def debug_funcname(id)
if id.nil?
"toplevel"
else
id.id2name
end
end
def check_break_points(file, klass, pos, binding, id)
return false if break_points.empty?
n = 1
for b in break_points
if b[0] # valid
if b[1] == 0 # breakpoint
if (b[2] == file and b[3] == pos) or
(klass and b[2] == klass and b[3] == pos)
stdout.printf "Breakpoint %d, %s at %s:%s\n", n, debug_funcname(id), file, pos
return true
end
elsif b[1] == 1 # watchpoint
if debug_silent_eval(b[2], binding)
stdout.printf "Watchpoint %d, %s at %s:%s\n", n, debug_funcname(id), file, pos
return true
end
end
end
n += 1
end
return false
end
def excn_handle(file, line, id, binding)
if $!.class <= SystemExit
set_trace_func nil
exit
end
if @catch and ($!.class.ancestors.find { |e| e.to_s == @catch })
stdout.printf "%s:%d: `%s' (%s)\n", file, line, $!, $!.class
fs = @frames.size
tb = caller(0)[-fs..-1]
if tb
for i in tb
stdout.printf "\tfrom %s\n", i
end
end
suspend_all
debug_command(file, line, id, binding)
end
end
def trace_func(event, file, line, id, binding, klass)
Tracer.trace_func(event, file, line, id, binding, klass) if trace?
context(Thread.current).check_suspend
@file = file
@line = line
case event
when 'line'
frame_set_pos(file, line)
if !@no_step or @frames.size == @no_step
@stop_next -= 1
@stop_next = -1 if @stop_next < 0
elsif @frames.size < @no_step
@stop_next = 0 # break here before leaving...
else
# nothing to do. skipped.
end
if @stop_next == 0 or check_break_points(file, nil, line, binding, id)
@no_step = nil
suspend_all
debug_command(file, line, id, binding)
end
when 'call'
@frames.unshift [binding, file, line, id]
if check_break_points(file, klass, id.id2name, binding, id)
suspend_all
debug_command(file, line, id, binding)
end
when 'c-call'
frame_set_pos(file, line)
when 'class'
@frames.unshift [binding, file, line, id]
when 'return', 'end'
if @frames.size == @finish_pos
@stop_next = 1
@finish_pos = 0
end
@frames.shift
when 'raise'
excn_handle(file, line, id, binding)
end
@last_file = file
end
end
trap("INT") { DEBUGGER__.interrupt }
@last_thread = Thread::main
@max_thread = 1
@thread_list = {Thread::main => 1}
@break_points = []
@display = []
@waiting = []
@stdout = STDOUT
class << DEBUGGER__
def stdout
@stdout
end
def stdout=(s)
@stdout = s
end
def display
@display
end
def break_points
@break_points
end
def waiting
@waiting
end
def set_trace( arg )
MUTEX.synchronize do
make_thread_list
for th, in @thread_list
context(th).set_trace arg
end
end
arg
end
def set_last_thread(th)
@last_thread = th
end
def suspend
MUTEX.synchronize do
make_thread_list
for th, in @thread_list
next if th == Thread.current
context(th).set_suspend
end
end
# Schedule other threads to suspend as soon as possible.
Thread.pass
end
def resume
MUTEX.synchronize do
make_thread_list
@thread_list.each do |th,|
next if th == Thread.current
context(th).clear_suspend
end
waiting.each do |th|
th.run
end
waiting.clear
end
# Schedule other threads to restart as soon as possible.
Thread.pass
end
def context(thread=Thread.current)
c = thread[:__debugger_data__]
unless c
thread[:__debugger_data__] = c = Context.new
end
c
end
def interrupt
context(@last_thread).stop_next
end
def get_thread(num)
th = @thread_list.key(num)
unless th
@stdout.print "No thread ##{num}\n"
throw :debug_error
end
th
end
def thread_list(num)
th = get_thread(num)
if th == Thread.current
@stdout.print "+"
else
@stdout.print " "
end
@stdout.printf "%d ", num
@stdout.print th.inspect, "\t"
file = context(th).instance_eval{@file}
if file
@stdout.print file,":",context(th).instance_eval{@line}
end
@stdout.print "\n"
end
def thread_list_all
for th in @thread_list.values.sort
thread_list(th)
end
end
def make_thread_list
hash = {}
for th in Thread::list
if @thread_list.key? th
hash[th] = @thread_list[th]
else
@max_thread += 1
hash[th] = @max_thread
end
end
@thread_list = hash
end
def debug_thread_info(input, binding)
case input
when /^l(?:ist)?/
make_thread_list
thread_list_all
when /^c(?:ur(?:rent)?)?$/
make_thread_list
thread_list(@thread_list[Thread.current])
when /^(?:sw(?:itch)?\s+)?(\d+)/
make_thread_list
th = get_thread($1.to_i)
if th == Thread.current
@stdout.print "It's the current thread.\n"
else
thread_list(@thread_list[th])
context(th).stop_next
th.run
return :cont
end
when /^stop\s+(\d+)/
make_thread_list
th = get_thread($1.to_i)
if th == Thread.current
@stdout.print "It's the current thread.\n"
elsif th.stop?
@stdout.print "Already stopped.\n"
else
thread_list(@thread_list[th])
context(th).suspend
end
when /^resume\s+(\d+)/
make_thread_list
th = get_thread($1.to_i)
if th == Thread.current
@stdout.print "It's the current thread.\n"
elsif !th.stop?
@stdout.print "Already running."
else
thread_list(@thread_list[th])
th.run
end
end
end
end
stdout.printf "Debug.rb\n"
stdout.printf "Emacs support available.\n\n"
RubyVM::InstructionSequence.compile_option = {
trace_instruction: true
}
set_trace_func proc { |event, file, line, id, binding, klass, *rest|
DEBUGGER__.context.trace_func event, file, line, id, binding, klass
}
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.rb | tools/jruby-1.5.1/lib/ruby/1.9/drb.rb | require 'drb/drb'
| 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/matrix.rb | tools/jruby-1.5.1/lib/ruby/1.9/matrix.rb | #--
# matrix.rb -
# $Release Version: 1.0$
# $Revision: 1.13 $
# Original Version from Smalltalk-80 version
# on July 23, 1985 at 8:37:17 am
# by Keiju ISHITSUKA
#++
#
# = matrix.rb
#
# An implementation of Matrix and Vector classes.
#
# Author:: Keiju ISHITSUKA
# Documentation:: Gavin Sinclair (sourced from <i>Ruby in a Nutshell</i> (Matsumoto, O'Reilly))
#
# See classes Matrix and Vector for documentation.
#
require "e2mmap.rb"
module ExceptionForMatrix # :nodoc:
extend Exception2MessageMapper
def_e2message(TypeError, "wrong argument type %s (expected %s)")
def_e2message(ArgumentError, "Wrong # of arguments(%d for %d)")
def_exception("ErrDimensionMismatch", "\#{self.name} dimension mismatch")
def_exception("ErrNotRegular", "Not Regular Matrix")
def_exception("ErrOperationNotDefined", "Operation(%s) can\\'t be defined: %s op %s")
def_exception("ErrOperationNotImplemented", "Sorry, Operation(%s) not implemented: %s op %s")
end
#
# The +Matrix+ class represents a mathematical matrix, and provides methods for creating
# special-case matrices (zero, identity, diagonal, singular, vector), operating on them
# arithmetically and algebraically, and determining their mathematical properties (trace, rank,
# inverse, determinant).
#
# Note that matrices must be rectangular, otherwise an ErrDimensionMismatch is raised.
#
# Also note that the determinant of integer matrices may be approximated unless you
# also <tt>require 'mathn'</tt>. This may be fixed in the future.
#
# == Method Catalogue
#
# To create a matrix:
# * <tt> Matrix[*rows] </tt>
# * <tt> Matrix.[](*rows) </tt>
# * <tt> Matrix.rows(rows, copy = true) </tt>
# * <tt> Matrix.columns(columns) </tt>
# * <tt> Matrix.diagonal(*values) </tt>
# * <tt> Matrix.scalar(n, value) </tt>
# * <tt> Matrix.identity(n) </tt>
# * <tt> Matrix.unit(n) </tt>
# * <tt> Matrix.I(n) </tt>
# * <tt> Matrix.zero(n) </tt>
# * <tt> Matrix.row_vector(row) </tt>
# * <tt> Matrix.column_vector(column) </tt>
#
# To access Matrix elements/columns/rows/submatrices/properties:
# * <tt> [](i, j) </tt>
# * <tt> #row_size </tt>
# * <tt> #column_size </tt>
# * <tt> #row(i) </tt>
# * <tt> #column(j) </tt>
# * <tt> #collect </tt>
# * <tt> #map </tt>
# * <tt> #each </tt>
# * <tt> #each_with_index </tt>
# * <tt> #minor(*param) </tt>
#
# Properties of a matrix:
# * <tt> #real? </tt>
# * <tt> #regular? </tt>
# * <tt> #singular? </tt>
# * <tt> #square? </tt>
#
# Matrix arithmetic:
# * <tt> *(m) </tt>
# * <tt> +(m) </tt>
# * <tt> -(m) </tt>
# * <tt> #/(m) </tt>
# * <tt> #inverse </tt>
# * <tt> #inv </tt>
# * <tt> ** </tt>
#
# Matrix functions:
# * <tt> #determinant </tt>
# * <tt> #det </tt>
# * <tt> #rank </tt>
# * <tt> #trace </tt>
# * <tt> #tr </tt>
# * <tt> #transpose </tt>
# * <tt> #t </tt>
#
# Complex arithmetic:
# * <tt> conj </tt>
# * <tt> conjugate </tt>
# * <tt> imag </tt>
# * <tt> imaginary </tt>
# * <tt> real </tt>
# * <tt> rect </tt>
# * <tt> rectangular </tt>
#
# Conversion to other data types:
# * <tt> #coerce(other) </tt>
# * <tt> #row_vectors </tt>
# * <tt> #column_vectors </tt>
# * <tt> #to_a </tt>
#
# String representations:
# * <tt> #to_s </tt>
# * <tt> #inspect </tt>
#
class Matrix
@RCS_ID='-$Id: matrix.rb,v 1.13 2001/12/09 14:22:23 keiju Exp keiju $-'
# extend Exception2MessageMapper
include Enumerable
include ExceptionForMatrix
# instance creations
private_class_method :new
attr_reader :rows
protected :rows
#
# Creates a matrix where each argument is a row.
# Matrix[ [25, 93], [-1, 66] ]
# => 25 93
# -1 66
#
def Matrix.[](*rows)
Matrix.rows(rows, false)
end
#
# Creates a matrix where +rows+ is an array of arrays, each of which is a row
# of the matrix. If the optional argument +copy+ is false, use the given
# arrays as the internal structure of the matrix without copying.
# Matrix.rows([[25, 93], [-1, 66]])
# => 25 93
# -1 66
#
def Matrix.rows(rows, copy = true)
rows = Matrix.convert_to_array(rows)
rows.map! do |row|
Matrix.convert_to_array(row, copy)
end
size = (rows[0] || []).size
rows.each do |row|
Matrix.Raise ErrDimensionMismatch, "element size differs (#{row.size} should be #{size})" unless row.size == size
end
new rows, size
end
#
# Creates a matrix using +columns+ as an array of column vectors.
# Matrix.columns([[25, 93], [-1, 66]])
# => 25 -1
# 93 66
#
def Matrix.columns(columns)
Matrix.rows(columns, false).transpose
end
#
# Creates a matrix where the diagonal elements are composed of +values+.
# Matrix.diagonal(9, 5, -3)
# => 9 0 0
# 0 5 0
# 0 0 -3
#
def Matrix.diagonal(*values)
size = values.size
rows = (0 ... size).collect {|j|
row = Array.new(size).fill(0, 0, size)
row[j] = values[j]
row
}
new rows
end
#
# Creates an +n+ by +n+ diagonal matrix where each diagonal element is
# +value+.
# Matrix.scalar(2, 5)
# => 5 0
# 0 5
#
def Matrix.scalar(n, value)
Matrix.diagonal(*Array.new(n).fill(value, 0, n))
end
#
# Creates an +n+ by +n+ identity matrix.
# Matrix.identity(2)
# => 1 0
# 0 1
#
def Matrix.identity(n)
Matrix.scalar(n, 1)
end
class << Matrix
alias unit identity
alias I identity
end
#
# Creates an +n+ by +n+ zero matrix.
# Matrix.zero(2)
# => 0 0
# 0 0
#
def Matrix.zero(n)
Matrix.scalar(n, 0)
end
#
# Creates a single-row matrix where the values of that row are as given in
# +row+.
# Matrix.row_vector([4,5,6])
# => 4 5 6
#
def Matrix.row_vector(row)
row = Matrix.convert_to_array(row)
new [row]
end
#
# Creates a single-column matrix where the values of that column are as given
# in +column+.
# Matrix.column_vector([4,5,6])
# => 4
# 5
# 6
#
def Matrix.column_vector(column)
column = Matrix.convert_to_array(column)
new [column].transpose, 1
end
#
# Creates a empty matrix of +row_size+ x +column_size+.
# +row_size+ or +column_size+ must be 0.
#
# m = Matrix.empty(2, 0)
# m == Matrix[ [], [] ]
# => true
# n = Matrix.empty(0, 3)
# n == Matrix.columns([ [], [], [] ])
# => true
# m * n
# => Matrix[[0, 0, 0], [0, 0, 0]]
#
def Matrix.empty(row_size = 0, column_size = 0)
Matrix.Raise ArgumentError, "One size must be 0" if column_size != 0 && row_size != 0
Matrix.Raise ArgumentError, "Negative size" if column_size < 0 || row_size < 0
new([[]]*row_size, column_size)
end
#
# Matrix.new is private; use Matrix.rows, columns, [], etc... to create.
#
def initialize(rows, column_size = rows[0].size)
# No checking is done at this point. rows must be an Array of Arrays.
# column_size must be the size of the first row, if there is one,
# otherwise it *must* be specified and can be any integer >= 0
@rows = rows
@column_size = column_size
end
def new_matrix(rows, column_size = rows[0].size) # :nodoc:
Matrix.send(:new, rows, column_size) # bypass privacy of Matrix.new
end
private :new_matrix
#
# Returns element (+i+,+j+) of the matrix. That is: row +i+, column +j+.
#
def [](i, j)
@rows.fetch(i){return nil}[j]
end
alias element []
alias component []
def []=(i, j, v)
@rows[i][j] = v
end
alias set_element []=
alias set_component []=
private :[]=, :set_element, :set_component
#
# Returns the number of rows.
#
def row_size
@rows.size
end
#
# Returns the number of columns.
#
attr_reader :column_size
#
# Returns row vector number +i+ of the matrix as a Vector (starting at 0 like
# an array). When a block is given, the elements of that vector are iterated.
#
def row(i, &block) # :yield: e
if block_given?
@rows.fetch(i){return self}.each(&block)
self
else
Vector.elements(@rows.fetch(i){return nil})
end
end
#
# Returns column vector number +j+ of the matrix as a Vector (starting at 0
# like an array). When a block is given, the elements of that vector are
# iterated.
#
def column(j) # :yield: e
if block_given?
return self if j >= column_size || j < -column_size
row_size.times do |i|
yield @rows[i][j]
end
self
else
return nil if j >= column_size || j < -column_size
col = (0 ... row_size).collect {|i|
@rows[i][j]
}
Vector.elements(col, false)
end
end
#
# Returns a matrix that is the result of iteration of the given block over all
# elements of the matrix.
# Matrix[ [1,2], [3,4] ].collect { |e| e**2 }
# => 1 4
# 9 16
#
def collect(&block) # :yield: e
return to_enum(:collect) unless block_given?
rows = @rows.collect{|row| row.collect(&block)}
new_matrix rows, column_size
end
alias map collect
#
# Yields all elements of the matrix, starting with those of the first row,
# or returns an Enumerator is no block given
# Matrix[ [1,2], [3,4] ].each { |e| puts e }
# # => prints the numbers 1 to 4
#
def each(&block) # :yield: e
return to_enum(:each) unless block_given?
@rows.each do |row|
row.each(&block)
end
self
end
#
# Yields all elements of the matrix, starting with those of the first row,
# along with the row index and column index,
# or returns an Enumerator is no block given
# Matrix[ [1,2], [3,4] ].each_with_index do |e, row, col|
# puts "#{e} at #{row}, #{col}"
# end
# # => 1 at 0, 0
# # => 2 at 0, 1
# # => 3 at 1, 0
# # => 4 at 1, 1
#
def each_with_index(&block) # :yield: e, row, column
return to_enum(:each_with_index) unless block_given?
@rows.each_with_index do |row, row_index|
row.each_with_index do |e, col_index|
yield e, row_index, col_index
end
end
self
end
#
# Returns a section of the matrix. The parameters are either:
# * start_row, nrows, start_col, ncols; OR
# * col_range, row_range
#
# Matrix.diagonal(9, 5, -3).minor(0..1, 0..2)
# => 9 0 0
# 0 5 0
#
# Like Array#[], negative indices count backward from the end of the
# row or column (-1 is the last element). Returns nil if the starting
# row or column is greater than row_size or column_size respectively.
#
def minor(*param)
case param.size
when 2
from_row = param[0].first
from_row += row_size if from_row < 0
to_row = param[0].end
to_row += row_size if to_row < 0
to_row += 1 unless param[0].exclude_end?
size_row = to_row - from_row
from_col = param[1].first
from_col += column_size if from_col < 0
to_col = param[1].end
to_col += column_size if to_col < 0
to_col += 1 unless param[1].exclude_end?
size_col = to_col - from_col
when 4
from_row, size_row, from_col, size_col = param
return nil if size_row < 0 || size_col < 0
from_row += row_size if from_row < 0
from_col += column_size if from_col < 0
else
Matrix.Raise ArgumentError, param.inspect
end
return nil if from_row > row_size || from_col > column_size || from_row < 0 || from_col < 0
rows = @rows[from_row, size_row].collect{|row|
row[from_col, size_col]
}
new_matrix rows, column_size - from_col
end
#--
# TESTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#++
#
# Returns +true+ if this is an empty matrix, i.e. if the number of rows
# or the number of columns is 0.
#
def empty?
column_size == 0 || row_size == 0
end
#
# Returns +true+ if all entries of the matrix are real.
#
def real?
all?(&:real?)
end
#
# Returns +true+ if this is a regular matrix.
#
def regular?
square? and rank == column_size
end
#
# Returns +true+ is this is a singular (i.e. non-regular) matrix.
#
def singular?
not regular?
end
#
# Returns +true+ is this is a square matrix.
#
def square?
column_size == row_size
end
#--
# OBJECT METHODS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#++
#
# Returns +true+ if and only if the two matrices contain equal elements.
#
def ==(other)
return false unless Matrix === other
rows == other.rows
end
def eql?(other)
return false unless Matrix === other
rows.eql? other.rows
end
#
# Returns a clone of the matrix, so that the contents of each do not reference
# identical objects.
# There should be no good reason to do this since Matrices are immutable.
#
def clone
new_matrix @rows.map{|row| row.dup}, column_size
end
#
# Returns a hash-code for the matrix.
#
def hash
@rows.hash
end
#--
# ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#++
#
# Matrix multiplication.
# Matrix[[2,4], [6,8]] * Matrix.identity(2)
# => 2 4
# 6 8
#
def *(m) # m is matrix or vector or number
case(m)
when Numeric
rows = @rows.collect {|row|
row.collect {|e|
e * m
}
}
return new_matrix rows, column_size
when Vector
m = Matrix.column_vector(m)
r = self * m
return r.column(0)
when Matrix
Matrix.Raise ErrDimensionMismatch if column_size != m.row_size
rows = (0 ... row_size).collect {|i|
(0 ... m.column_size).collect {|j|
(0 ... column_size).inject(0) do |vij, k|
vij + self[i, k] * m[k, j]
end
}
}
return new_matrix rows, m.column_size
else
x, y = m.coerce(self)
return x * y
end
end
#
# Matrix addition.
# Matrix.scalar(2,5) + Matrix[[1,0], [-4,7]]
# => 6 0
# -4 12
#
def +(m)
case m
when Numeric
Matrix.Raise ErrOperationNotDefined, "+", self.class, m.class
when Vector
m = Matrix.column_vector(m)
when Matrix
else
x, y = m.coerce(self)
return x + y
end
Matrix.Raise ErrDimensionMismatch unless row_size == m.row_size and column_size == m.column_size
rows = (0 ... row_size).collect {|i|
(0 ... column_size).collect {|j|
self[i, j] + m[i, j]
}
}
new_matrix rows, column_size
end
#
# Matrix subtraction.
# Matrix[[1,5], [4,2]] - Matrix[[9,3], [-4,1]]
# => -8 2
# 8 1
#
def -(m)
case m
when Numeric
Matrix.Raise ErrOperationNotDefined, "-", self.class, m.class
when Vector
m = Matrix.column_vector(m)
when Matrix
else
x, y = m.coerce(self)
return x - y
end
Matrix.Raise ErrDimensionMismatch unless row_size == m.row_size and column_size == m.column_size
rows = (0 ... row_size).collect {|i|
(0 ... column_size).collect {|j|
self[i, j] - m[i, j]
}
}
new_matrix rows, column_size
end
#
# Matrix division (multiplication by the inverse).
# Matrix[[7,6], [3,9]] / Matrix[[2,9], [3,1]]
# => -7 1
# -3 -6
#
def /(other)
case other
when Numeric
rows = @rows.collect {|row|
row.collect {|e|
e / other
}
}
return new_matrix rows, column_size
when Matrix
return self * other.inverse
else
x, y = other.coerce(self)
return x / y
end
end
#
# Returns the inverse of the matrix.
# Matrix[[-1, -1], [0, -1]].inverse
# => -1 1
# 0 -1
#
def inverse
Matrix.Raise ErrDimensionMismatch unless square?
Matrix.I(row_size).inverse_from(self)
end
alias inv inverse
#
# Not for public consumption?
#
def inverse_from(src)
size = row_size
a = src.to_a
size.times do |k|
i = k
akk = a[k][k].abs
(k+1 ... size).each do |j|
v = a[j][k].abs
if v > akk
i = j
akk = v
end
end
Matrix.Raise ErrNotRegular if akk == 0
if i != k
a[i], a[k] = a[k], a[i]
@rows[i], @rows[k] = @rows[k], @rows[i]
end
akk = a[k][k]
size.times do |ii|
next if ii == k
q = a[ii][k].quo(akk)
a[ii][k] = 0
(k + 1 ... size).each do |j|
a[ii][j] -= a[k][j] * q
end
size.times do |j|
@rows[ii][j] -= @rows[k][j] * q
end
end
(k + 1 ... size).each do |j|
a[k][j] = a[k][j].quo(akk)
end
size.times do |j|
@rows[k][j] = @rows[k][j].quo(akk)
end
end
self
end
#alias reciprocal inverse
#
# Matrix exponentiation. Defined for integer powers only. Equivalent to
# multiplying the matrix by itself N times.
# Matrix[[7,6], [3,9]] ** 2
# => 67 96
# 48 99
#
def ** (other)
if other.kind_of?(Integer)
x = self
if other <= 0
x = self.inverse
return Matrix.identity(self.column_size) if other == 0
other = -other
end
z = nil
loop do
z = z ? z * x : x if other[0] == 1
return z if (other >>= 1).zero?
x *= x
end
elsif other.kind_of?(Float) || defined?(Rational) && other.kind_of?(Rational)
Matrix.Raise ErrOperationNotImplemented, "**", self.class, other.class
else
Matrix.Raise ErrOperationNotDefined, "**", self.class, other.class
end
end
#--
# MATRIX FUNCTIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#++
#
# Returns the determinant of the matrix.
# This method's algorithm is Gaussian elimination method
# and using Numeric#quo(). Beware that using Float values, with their
# usual lack of precision, can affect the value returned by this method. Use
# Rational values or Matrix#det_e instead if this is important to you.
#
# Matrix[[7,6], [3,9]].determinant
# => 45.0
#
def determinant
Matrix.Raise ErrDimensionMismatch unless square?
size = row_size
a = to_a
det = 1
size.times do |k|
if (akk = a[k][k]) == 0
i = (k+1 ... size).find {|ii|
a[ii][k] != 0
}
return 0 if i.nil?
a[i], a[k] = a[k], a[i]
akk = a[k][k]
det *= -1
end
(k + 1 ... size).each do |ii|
q = a[ii][k].quo(akk)
(k + 1 ... size).each do |j|
a[ii][j] -= a[k][j] * q
end
end
det *= akk
end
det
end
alias det determinant
#
# Returns the determinant of the matrix.
# This method's algorithm is Gaussian elimination method.
# This method uses Euclidean algorithm. If all elements are integer,
# really exact value. But, if an element is a float, can't return
# exact value.
#
# Matrix[[7,6], [3,9]].determinant
# => 63
#
def determinant_e
Matrix.Raise ErrDimensionMismatch unless square?
size = row_size
a = to_a
det = 1
size.times do |k|
if a[k][k].zero?
i = (k+1 ... size).find {|ii|
a[ii][k] != 0
}
return 0 if i.nil?
a[i], a[k] = a[k], a[i]
det *= -1
end
(k + 1 ... size).each do |ii|
q = a[ii][k].quo(a[k][k])
(k ... size).each do |j|
a[ii][j] -= a[k][j] * q
end
unless a[ii][k].zero?
a[ii], a[k] = a[k], a[ii]
det *= -1
redo
end
end
det *= a[k][k]
end
det
end
alias det_e determinant_e
#
# Returns the rank of the matrix. Beware that using Float values,
# probably return faild value. Use Rational values or Matrix#rank_e
# for getting exact result.
#
# Matrix[[7,6], [3,9]].rank
# => 2
#
def rank
if column_size > row_size
a = transpose.to_a
a_column_size = row_size
a_row_size = column_size
else
a = to_a
a_column_size = column_size
a_row_size = row_size
end
rank = 0
a_column_size.times do |k|
if (akk = a[k][k]) == 0
i = (k+1 ... a_row_size).find {|ii|
a[ii][k] != 0
}
if i
a[i], a[k] = a[k], a[i]
akk = a[k][k]
else
i = (k+1 ... a_column_size).find {|ii|
a[k][ii] != 0
}
next if i.nil?
(k ... a_column_size).each do |j|
a[j][k], a[j][i] = a[j][i], a[j][k]
end
akk = a[k][k]
end
end
(k + 1 ... a_row_size).each do |ii|
q = a[ii][k].quo(akk)
(k + 1... a_column_size).each do |j|
a[ii][j] -= a[k][j] * q
end
end
rank += 1
end
return rank
end
#
# Returns the rank of the matrix. This method uses Euclidean
# algorithm. If all elements are integer, really exact value. But, if
# an element is a float, can't return exact value.
#
# Matrix[[7,6], [3,9]].rank
# => 2
#
def rank_e
a = to_a
a_column_size = column_size
a_row_size = row_size
pi = 0
a_column_size.times do |j|
if i = (pi ... a_row_size).find{|i0| !a[i0][j].zero?}
if i != pi
a[pi], a[i] = a[i], a[pi]
end
(pi + 1 ... a_row_size).each do |k|
q = a[k][j].quo(a[pi][j])
(pi ... a_column_size).each do |j0|
a[k][j0] -= q * a[pi][j0]
end
if k > pi && !a[k][j].zero?
a[k], a[pi] = a[pi], a[k]
redo
end
end
pi += 1
end
end
pi
end
#
# Returns the trace (sum of diagonal elements) of the matrix.
# Matrix[[7,6], [3,9]].trace
# => 16
#
def trace
Matrix.Raise ErrDimensionMismatch unless square?
(0...column_size).inject(0) do |tr, i|
tr + @rows[i][i]
end
end
alias tr trace
#
# Returns the transpose of the matrix.
# Matrix[[1,2], [3,4], [5,6]]
# => 1 2
# 3 4
# 5 6
# Matrix[[1,2], [3,4], [5,6]].transpose
# => 1 3 5
# 2 4 6
#
def transpose
return Matrix.empty(column_size, 0) if row_size.zero?
new_matrix @rows.transpose, row_size
end
alias t transpose
#--
# COMPLEX ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#++
#
# Returns the conjugate of the matrix.
# Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]]
# => 1+2i i 0
# 1 2 3
# Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]].conjugate
# => 1-2i -i 0
# 1 2 3
#
def conjugate
collect(&:conjugate)
end
alias conj conjugate
#
# Returns the imaginary part of the matrix.
# Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]]
# => 1+2i i 0
# 1 2 3
# Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]].imaginary
# => 2i i 0
# 0 0 0
#
def imaginary
collect(&:imaginary)
end
alias imag imaginary
#
# Returns the real part of the matrix.
# Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]]
# => 1+2i i 0
# 1 2 3
# Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]].real
# => 1 0 0
# 1 2 3
#
def real
collect(&:real)
end
#
# Returns an array containing matrices corresponding to the real and imaginary
# parts of the matrix
#
# m.rect == [m.real, m.imag] # ==> true for all matrices m
#
def rect
[real, imag]
end
alias rectangular rect
#--
# CONVERTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#++
#
# FIXME: describe #coerce.
#
def coerce(other)
case other
when Numeric
return Scalar.new(other), self
else
raise TypeError, "#{self.class} can't be coerced into #{other.class}"
end
end
#
# Returns an array of the row vectors of the matrix. See Vector.
#
def row_vectors
(0 ... row_size).collect {|i|
row(i)
}
end
#
# Returns an array of the column vectors of the matrix. See Vector.
#
def column_vectors
(0 ... column_size).collect {|i|
column(i)
}
end
#
# Returns an array of arrays that describe the rows of the matrix.
#
def to_a
@rows.collect{|row| row.dup}
end
def elements_to_f
collect{|e| e.to_f}
end
def elements_to_i
collect{|e| e.to_i}
end
def elements_to_r
collect{|e| e.to_r}
end
#--
# PRINTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#++
#
# Overrides Object#to_s
#
def to_s
if empty?
"Matrix.empty(#{row_size}, #{column_size})"
else
"Matrix[" + @rows.collect{|row|
"[" + row.collect{|e| e.to_s}.join(", ") + "]"
}.join(", ")+"]"
end
end
#
# Overrides Object#inspect
#
def inspect
if empty?
"Matrix.empty(#{row_size}, #{column_size})"
else
"Matrix#{@rows.inspect}"
end
end
#
# Converts the obj to an Array. If copy is set to true
# a copy of obj will be made if necessary.
#
def Matrix.convert_to_array(obj, copy = false)
case obj
when Array
copy ? obj.dup : obj
when Vector
obj.to_a
else
begin
converted = obj.to_ary
rescue Exception => e
raise TypeError, "can't convert #{obj.class} into an Array (#{e.message})"
end
raise TypeError, "#{obj.class}#to_ary should return an Array" unless converted.is_a? Array
converted
end
end
# Private CLASS
class Scalar < Numeric # :nodoc:
include ExceptionForMatrix
def initialize(value)
@value = value
end
# ARITHMETIC
def +(other)
case other
when Numeric
Scalar.new(@value + other)
when Vector, Matrix
Scalar.Raise ErrOperationNotDefined, "+", @value.class, other.class
else
x, y = other.coerce(self)
x + y
end
end
def -(other)
case other
when Numeric
Scalar.new(@value - other)
when Vector, Matrix
Scalar.Raise ErrOperationNotDefined, "-", @value.class, other.class
else
x, y = other.coerce(self)
x - y
end
end
def *(other)
case other
when Numeric
Scalar.new(@value * other)
when Vector, Matrix
other.collect{|e| @value * e}
else
x, y = other.coerce(self)
x * y
end
end
def / (other)
case other
when Numeric
Scalar.new(@value / other)
when Vector
Scalar.Raise ErrOperationNotDefined, "/", @value.class, other.class
when Matrix
self * other.inverse
else
x, y = other.coerce(self)
x.quo(y)
end
end
def ** (other)
case other
when Numeric
Scalar.new(@value ** other)
when Vector
Scalar.Raise ErrOperationNotDefined, "**", @value.class, other.class
when Matrix
#other.powered_by(self)
Scalar.Raise ErrOperationNotImplemented, "**", @value.class, other.class
else
x, y = other.coerce(self)
x ** y
end
end
end
end
#
# The +Vector+ class represents a mathematical vector, which is useful in its own right, and
# also constitutes a row or column of a Matrix.
#
# == Method Catalogue
#
# To create a Vector:
# * <tt> Vector.[](*array) </tt>
# * <tt> Vector.elements(array, copy = true) </tt>
#
# To access elements:
# * <tt> [](i) </tt>
#
# To enumerate the elements:
# * <tt> #each2(v) </tt>
# * <tt> #collect2(v) </tt>
#
# Vector arithmetic:
# * <tt> *(x) "is matrix or number" </tt>
# * <tt> +(v) </tt>
# * <tt> -(v) </tt>
#
# Vector functions:
# * <tt> #inner_product(v) </tt>
# * <tt> #collect </tt>
# * <tt> #map </tt>
# * <tt> #map2(v) </tt>
# * <tt> #r </tt>
# * <tt> #size </tt>
#
# Conversion to other data types:
# * <tt> #covector </tt>
# * <tt> #to_a </tt>
# * <tt> #coerce(other) </tt>
#
# String representations:
# * <tt> #to_s </tt>
# * <tt> #inspect </tt>
#
class Vector
include ExceptionForMatrix
include Enumerable
#INSTANCE CREATION
private_class_method :new
attr_reader :elements
protected :elements
#
# Creates a Vector from a list of elements.
# Vector[7, 4, ...]
#
def Vector.[](*array)
new Matrix.convert_to_array(array, copy = false)
end
#
# Creates a vector from an Array. The optional second argument specifies
# whether the array itself or a copy is used internally.
#
def Vector.elements(array, copy = true)
new Matrix.convert_to_array(array, copy)
end
#
# Vector.new is private; use Vector[] or Vector.elements to create.
#
def initialize(array)
# No checking is done at this point.
@elements = array
end
# ACCESSING
#
# Returns element number +i+ (starting at zero) of the vector.
#
def [](i)
@elements[i]
end
alias element []
alias component []
def []=(i, v)
@elements[i]= v
end
alias set_element []=
alias set_component []=
private :[]=, :set_element, :set_component
#
# Returns the number of elements in the vector.
#
def size
@elements.size
end
#--
# ENUMERATIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#++
#
# Iterate over the elements of this vector
#
def each(&block)
return to_enum(:each) unless block_given?
@elements.each(&block)
self
end
#
# Iterate over the elements of this vector and +v+ in conjunction.
#
def each2(v) # :yield: e1, e2
raise TypeError, "Integer is not like Vector" if v.kind_of?(Integer)
Vector.Raise ErrDimensionMismatch if size != v.size
return to_enum(:each2, v) unless block_given?
size.times do |i|
yield @elements[i], v[i]
end
self
end
#
# Collects (as in Enumerable#collect) over the elements of this vector and +v+
# in conjunction.
#
def collect2(v) # :yield: e1, e2
raise TypeError, "Integer is not like Vector" if v.kind_of?(Integer)
Vector.Raise ErrDimensionMismatch if size != v.size
return to_enum(:collect2, v) unless block_given?
size.times.collect do |i|
yield @elements[i], v[i]
end
end
#--
# COMPARING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#++
#
# Returns +true+ iff the two vectors have the same elements in the same order.
#
def ==(other)
return false unless Vector === other
@elements == other.elements
end
def eql?(other)
return false unless Vector === other
@elements.eql? other.elements
end
#
# Return a copy of the vector.
#
def clone
Vector.elements(@elements)
end
#
# Return a hash-code for the vector.
#
def hash
@elements.hash
end
#--
# ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#++
#
# Multiplies the vector by +x+, where +x+ is a number or another vector.
#
def *(x)
case x
when Numeric
els = @elements.collect{|e| e * x}
Vector.elements(els, false)
when Matrix
Matrix.column_vector(self) * x
when Vector
Vector.Raise ErrOperationNotDefined, "*", self.class, x.class
else
s, x = x.coerce(self)
s * x
end
end
#
# Vector addition.
#
def +(v)
case v
when Vector
| 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/open3.rb | tools/jruby-1.5.1/lib/ruby/1.9/open3.rb | #
# = open3.rb: Popen, but with stderr, too
#
# Author:: Yukihiro Matsumoto
# Documentation:: Konrad Meyer
#
# Open3 gives you access to stdin, stdout, and stderr when running other
# programs.
#
#
# Open3 grants you access to stdin, stdout, stderr and a thread to wait the
# child process when running another program.
# You can specify various attributes, redirections, current directory, etc., of
# the program as Process.spawn.
#
# - Open3.popen3 : pipes for stdin, stdout, stderr
# - Open3.popen2 : pipes for stdin, stdout
# - Open3.popen2e : pipes for stdin, merged stdout and stderr
# - Open3.capture3 : give a string for stdin. get strings for stdout, stderr
# - Open3.capture2 : give a string for stdin. get a string for stdout
# - Open3.capture2e : give a string for stdin. get a string for merged stdout and stderr
# - Open3.pipeline_rw : pipes for first stdin and last stdout of a pipeline
# - Open3.pipeline_r : pipe for last stdout of a pipeline
# - Open3.pipeline_w : pipe for first stdin of a pipeline
# - Open3.pipeline_start : a pipeline
# - Open3.pipeline : run a pipline and wait
#
module Open3
# Open stdin, stdout, and stderr streams and start external executable.
# In addition, a thread for waiting the started process is noticed.
# The thread has a pid method and thread variable :pid which is the pid of
# the started process.
#
# Block form:
#
# Open3.popen3([env,] cmd... [, opts]) {|stdin, stdout, stderr, wait_thr|
# pid = wait_thr.pid # pid of the started process.
# ...
# exit_status = wait_thr.value # Process::Status object returned.
# }
#
# Non-block form:
#
# stdin, stdout, stderr, wait_thr = Open3.popen3([env,] cmd... [, opts])
# pid = wait_thr[:pid] # pid of the started process.
# ...
# stdin.close # stdin, stdout and stderr should be closed explicitly in this form.
# stdout.close
# stderr.close
# exit_status = wait_thr.value # Process::Status object returned.
#
# The parameters +cmd...+ is passed to Process.spawn.
# So a commandline string and list of argument strings can be accepted as follows.
#
# Open3.popen3("echo a") {|i, o, e, t| ... }
# Open3.popen3("echo", "a") {|i, o, e, t| ... }
# Open3.popen3(["echo", "argv0"], "a") {|i, o, e, t| ... }
#
# If the last parameter, opts, is a Hash, it is recognized as an option for Process.spawn.
#
# Open3.popen3("pwd", :chdir=>"/") {|i,o,e,t|
# p o.read.chomp #=> "/"
# }
#
# wait_thr.value waits the termination of the process.
# The block form also waits the process when it returns.
#
# Closing stdin, stdout and stderr does not wait the process.
#
def popen3(*cmd, &block)
if Hash === cmd.last
opts = cmd.pop.dup
else
opts = {}
end
in_r, in_w = IO.pipe
opts[:in] = in_r
in_w.sync = true
out_r, out_w = IO.pipe
opts[:out] = out_w
err_r, err_w = IO.pipe
opts[:err] = err_w
popen_run(cmd, opts, [in_r, out_w, err_w], [in_w, out_r, err_r], &block)
end
module_function :popen3
# Open3.popen2 is similer to Open3.popen3 except it doesn't make a pipe for
# the standard error stream.
#
# Block form:
#
# Open3.popen2([env,] cmd... [, opts]) {|stdin, stdout, wait_thr|
# pid = wait_thr.pid # pid of the started process.
# ...
# exit_status = wait_thr.value # Process::Status object returned.
# }
#
# Non-block form:
#
# stdin, stdout, wait_thr = Open3.popen2([env,] cmd... [, opts])
# ...
# stdin.close # stdin and stdout should be closed explicitly in this form.
# stdout.close
#
# See Process.spawn for the optional hash arguments _env_ and _opts_.
#
# Example:
#
# Open3.popen2("wc -c") {|i,o,t|
# i.print "answer to life the universe and everything"
# i.close
# p o.gets #=> "42\n"
# }
#
# Open3.popen2("bc -q") {|i,o,t|
# i.puts "obase=13"
# i.puts "6 * 9"
# p o.gets #=> "42\n"
# }
#
# Open3.popen2("dc") {|i,o,t|
# i.print "42P"
# i.close
# p o.read #=> "*"
# }
#
def popen2(*cmd, &block)
if Hash === cmd.last
opts = cmd.pop.dup
else
opts = {}
end
in_r, in_w = IO.pipe
opts[:in] = in_r
in_w.sync = true
out_r, out_w = IO.pipe
opts[:out] = out_w
popen_run(cmd, opts, [in_r, out_w], [in_w, out_r], &block)
end
module_function :popen2
# Open3.popen2e is similer to Open3.popen3 except it merges
# the standard output stream and the standard error stream.
#
# Block form:
#
# Open3.popen2e([env,] cmd... [, opts]) {|stdin, stdout_and_stderr, wait_thr|
# pid = wait_thr.pid # pid of the started process.
# ...
# exit_status = wait_thr.value # Process::Status object returned.
# }
#
# Non-block form:
#
# stdin, stdout_and_stderr, wait_thr = Open3.popen2e([env,] cmd... [, opts])
# ...
# stdin.close # stdin and stdout_and_stderr should be closed explicitly in this form.
# stdout_and_stderr.close
#
# See Process.spawn for the optional hash arguments _env_ and _opts_.
#
# Example:
# # check gcc warnings
# source = "foo.c"
# Open3.popen2e("gcc", "-Wall", source) {|i,oe,t|
# oe.each {|line|
# if /warning/ =~ line
# ...
# end
# }
# }
#
def popen2e(*cmd, &block)
if Hash === cmd.last
opts = cmd.pop.dup
else
opts = {}
end
in_r, in_w = IO.pipe
opts[:in] = in_r
in_w.sync = true
out_r, out_w = IO.pipe
opts[[:out, :err]] = out_w
popen_run(cmd, opts, [in_r, out_w], [in_w, out_r], &block)
end
module_function :popen2e
def popen_run(cmd, opts, child_io, parent_io) # :nodoc:
pid = spawn(*cmd, opts)
wait_thr = Process.detach(pid)
child_io.each {|io| io.close }
result = [*parent_io, wait_thr]
if defined? yield
begin
return yield(*result)
ensure
parent_io.each{|io| io.close unless io.closed?}
wait_thr.join
end
end
result
end
module_function :popen_run
class << self
private :popen_run
end
# Open3.capture3 captures the standard output and the standard error of a command.
#
# stdout_str, stderr_str, status = Open3.capture3([env,] cmd... [, opts])
#
# The arguments env, cmd and opts are passed to Open3.popen3 except
# opts[:stdin_data] and opts[:stdin_data]. See Process.spawn.
#
# If opts[:stdin_data] is specified, it is sent to the command's standard input.
#
# If opts[:binmode] is true, internal pipes are set to binary mode.
#
# Example:
#
# # dot is a command of graphviz.
# graph = <<'End'
# digraph g {
# a -> b
# }
# End
# layouted_graph, dot_log = Open3.capture3("dot -v", :stdin_data=>graph)
#
# o, e, s = Open3.capture3("echo a; sort >&2", :stdin_data=>"foo\nbar\nbaz\n")
# p o #=> "a\n"
# p e #=> "bar\nbaz\nfoo\n"
# p s #=> #<Process::Status: pid 32682 exit 0>
#
# # generate a thumnail image using the convert command of ImageMagick.
# # However, if the image stored really in a file,
# # system("convert", "-thumbnail", "80", "png:#{filename}", "png:-") is better
# # because memory consumption.
# # But if the image is stored in a DB or generated by gnuplot Open3.capture2 example,
# # Open3.capture3 is considerable.
# #
# image = File.read("/usr/share/openclipart/png/animals/mammals/sheep-md-v0.1.png", :binmode=>true)
# thumnail, err, s = Open3.capture3("convert -thumbnail 80 png:- png:-", :stdin_data=>image, :binmode=>true)
# if s.success?
# STDOUT.binmode; print thumnail
# end
#
def capture3(*cmd, &block)
if Hash === cmd.last
opts = cmd.pop.dup
else
opts = {}
end
stdin_data = opts.delete(:stdin_data) || ''
binmode = opts.delete(:binmode)
popen3(*cmd, opts) {|i, o, e, t|
if binmode
i.binmode
o.binmode
e.binmode
end
out_reader = Thread.new { o.read }
err_reader = Thread.new { e.read }
i.write stdin_data
i.close
[out_reader.value, err_reader.value, t.value]
}
end
module_function :capture3
# Open3.capture2 captures the standard output of a command.
#
# stdout_str, status = Open3.capture2([env,] cmd... [, opts])
#
# The arguments env, cmd and opts are passed to Open3.popen3 except
# opts[:stdin_data] and opts[:stdin_data]. See Process.spawn.
#
# If opts[:stdin_data] is specified, it is sent to the command's standard input.
#
# If opts[:binmode] is true, internal pipes are set to binary mode.
#
# Example:
#
# # factor is a command for integer factorization.
# o, s = Open3.capture2("factor", :stdin_data=>"42")
# p o #=> "42: 2 3 7\n"
#
# # generate x**2 graph in png using gnuplot.
# gnuplot_commands = <<"End"
# set terminal png
# plot x**2, "-" with lines
# 1 14
# 2 1
# 3 8
# 4 5
# e
# End
# image, s = Open3.capture2("gnuplot", :stdin_data=>gnuplot_commands, :binmode=>true)
#
def capture2(*cmd, &block)
if Hash === cmd.last
opts = cmd.pop.dup
else
opts = {}
end
stdin_data = opts.delete(:stdin_data) || ''
binmode = opts.delete(:binmode)
popen2(*cmd, opts) {|i, o, t|
if binmode
i.binmode
o.binmode
end
out_reader = Thread.new { o.read }
i.write stdin_data
i.close
[out_reader.value, t.value]
}
end
module_function :capture2
# Open3.capture2e captures the standard output and the standard error of a command.
#
# stdout_and_stderr_str, status = Open3.capture2e([env,] cmd... [, opts])
#
# The arguments env, cmd and opts are passed to Open3.popen3 except
# opts[:stdin_data] and opts[:stdin_data]. See Process.spawn.
#
# If opts[:stdin_data] is specified, it is sent to the command's standard input.
#
# If opts[:binmode] is true, internal pipes are set to binary mode.
#
# Example:
#
# # capture make log
# make_log, s = Open3.capture2e("make")
#
def capture2e(*cmd, &block)
if Hash === cmd.last
opts = cmd.pop.dup
else
opts = {}
end
stdin_data = opts.delete(:stdin_data) || ''
binmode = opts.delete(:binmode)
popen2e(*cmd, opts) {|i, oe, t|
if binmode
i.binmode
oe.binmode
end
outerr_reader = Thread.new { oe.read }
i.write stdin_data
i.close
[outerr_reader.value, t.value]
}
end
module_function :capture2e
# Open3.pipeline_rw starts a list of commands as a pipeline with pipes
# which connects stdin of the first command and stdout of the last command.
#
# Open3.pipeline_rw(cmd1, cmd2, ... [, opts]) {|first_stdin, last_stdout, wait_threads|
# ...
# }
#
# first_stdin, last_stdout, wait_threads = Open3.pipeline_rw(cmd1, cmd2, ... [, opts])
# ...
# first_stdin.close
# last_stdout.close
#
# Each cmd is a string or an array.
# If it is an array, the elements are passed to Process.spawn.
#
# cmd:
# commandline command line string which is passed to a shell
# [env, commandline, opts] command line string which is passed to a shell
# [env, cmdname, arg1, ..., opts] command name and one or more arguments (no shell)
# [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
#
# Note that env and opts are optional, as Process.spawn.
#
# The option to pass Process.spawn is constructed by merging
# +opts+, the last hash element of the array and
# specification for the pipe between each commands.
#
# Example:
#
# Open3.pipeline_rw("tr -dc A-Za-z", "wc -c") {|i,o,ts|
# i.puts "All persons more than a mile high to leave the court."
# i.close
# p o.gets #=> "42\n"
# }
#
# Open3.pipeline_rw("sort", "cat -n") {|stdin, stdout, wait_thrs|
# stdin.puts "foo"
# stdin.puts "bar"
# stdin.puts "baz"
# stdin.close # send EOF to sort.
# p stdout.read #=> " 1\tbar\n 2\tbaz\n 3\tfoo\n"
# }
def pipeline_rw(*cmds, &block)
if Hash === cmds.last
opts = cmds.pop.dup
else
opts = {}
end
in_r, in_w = IO.pipe
opts[:in] = in_r
in_w.sync = true
out_r, out_w = IO.pipe
opts[:out] = out_w
pipeline_run(cmds, opts, [in_r, out_w], [in_w, out_r], &block)
end
module_function :pipeline_rw
# Open3.pipeline_r starts a list of commands as a pipeline with a pipe
# which connects stdout of the last command.
#
# Open3.pipeline_r(cmd1, cmd2, ... [, opts]) {|last_stdout, wait_threads|
# ...
# }
#
# last_stdout, wait_threads = Open3.pipeline_r(cmd1, cmd2, ... [, opts])
# ...
# last_stdout.close
#
# Each cmd is a string or an array.
# If it is an array, the elements are passed to Process.spawn.
#
# cmd:
# commandline command line string which is passed to a shell
# [env, commandline, opts] command line string which is passed to a shell
# [env, cmdname, arg1, ..., opts] command name and one or more arguments (no shell)
# [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
#
# Note that env and opts are optional, as Process.spawn.
#
# Example:
#
# Open3.pipeline_r("zcat /var/log/apache2/access.log.*.gz",
# [{"LANG"=>"C"}, "grep", "GET /favicon.ico"],
# "logresolve") {|r, ts|
# r.each_line {|line|
# ...
# }
# }
#
# Open3.pipeline_r("yes", "head -10") {|r, ts|
# p r.read #=> "y\ny\ny\ny\ny\ny\ny\ny\ny\ny\n"
# p ts[0].value #=> #<Process::Status: pid 24910 SIGPIPE (signal 13)>
# p ts[1].value #=> #<Process::Status: pid 24913 exit 0>
# }
#
def pipeline_r(*cmds, &block)
if Hash === cmds.last
opts = cmds.pop.dup
else
opts = {}
end
out_r, out_w = IO.pipe
opts[:out] = out_w
pipeline_run(cmds, opts, [out_w], [out_r], &block)
end
module_function :pipeline_r
# Open3.pipeline_w starts a list of commands as a pipeline with a pipe
# which connects stdin of the first command.
#
# Open3.pipeline_w(cmd1, cmd2, ... [, opts]) {|first_stdin, wait_threads|
# ...
# }
#
# first_stdin, wait_threads = Open3.pipeline_w(cmd1, cmd2, ... [, opts])
# ...
# first_stdin.close
#
# Each cmd is a string or an array.
# If it is an array, the elements are passed to Process.spawn.
#
# cmd:
# commandline command line string which is passed to a shell
# [env, commandline, opts] command line string which is passed to a shell
# [env, cmdname, arg1, ..., opts] command name and one or more arguments (no shell)
# [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
#
# Note that env and opts are optional, as Process.spawn.
#
# Example:
#
# Open3.pipeline_w("bzip2 -c", :out=>"/tmp/hello.bz2") {|w, ts|
# w.puts "hello"
# }
#
def pipeline_w(*cmds, &block)
if Hash === cmds.last
opts = cmds.pop.dup
else
opts = {}
end
in_r, in_w = IO.pipe
opts[:in] = in_r
in_w.sync = true
pipeline_run(cmds, opts, [in_r], [in_w], &block)
end
module_function :pipeline_w
# Open3.pipeline_start starts a list of commands as a pipeline.
# No pipe made for stdin of the first command and
# stdout of the last command.
#
# Open3.pipeline_start(cmd1, cmd2, ... [, opts]) {|wait_threads|
# ...
# }
#
# wait_threads = Open3.pipeline_start(cmd1, cmd2, ... [, opts])
# ...
#
# Each cmd is a string or an array.
# If it is an array, the elements are passed to Process.spawn.
#
# cmd:
# commandline command line string which is passed to a shell
# [env, commandline, opts] command line string which is passed to a shell
# [env, cmdname, arg1, ..., opts] command name and one or more arguments (no shell)
# [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
#
# Note that env and opts are optional, as Process.spawn.
#
# Example:
#
# # run xeyes in 10 seconds.
# Open3.pipeline_start("xeyes") {|ts|
# sleep 10
# t = ts[0]
# Process.kill("TERM", t.pid)
# p t.value #=> #<Process::Status: pid 911 SIGTERM (signal 15)>
# }
#
# # convert pdf to ps and send it to a printer.
# # collect error message of pdftops and lpr.
# pdf_file = "paper.pdf"
# printer = "printer-name"
# err_r, err_w = IO.pipe
# Open3.pipeline_start(["pdftops", pdf_file, "-"],
# ["lpr", "-P#{printer}"],
# :err=>err_w) {|ts|
# err_w.close
# p err_r.read # error messages of pdftops and lpr.
# }
#
def pipeline_start(*cmds, &block)
if Hash === cmds.last
opts = cmds.pop.dup
else
opts = {}
end
if block
pipeline_run(cmds, opts, [], [], &block)
else
ts, = pipeline_run(cmds, opts, [], [])
ts
end
end
module_function :pipeline_start
# Open3.pipeline starts a list of commands as a pipeline.
# It waits the finish of the commands.
# No pipe made for stdin of the first command and
# stdout of the last command.
#
# status_list = Open3.pipeline(cmd1, cmd2, ... [, opts])
#
# Each cmd is a string or an array.
# If it is an array, the elements are passed to Process.spawn.
#
# cmd:
# commandline command line string which is passed to a shell
# [env, commandline, opts] command line string which is passed to a shell
# [env, cmdname, arg1, ..., opts] command name and one or more arguments (no shell)
# [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
#
# Note that env and opts are optional, as Process.spawn.
#
# Example:
#
# fname = "/usr/share/man/man1/ruby.1.gz"
# p Open3.pipeline(["zcat", fname], "nroff -man", "less")
# #=> [#<Process::Status: pid 11817 exit 0>,
# # #<Process::Status: pid 11820 exit 0>,
# # #<Process::Status: pid 11828 exit 0>]
#
# fname = "/usr/share/man/man1/ls.1.gz"
# Open3.pipeline(["zcat", fname], "nroff -man", "colcrt")
#
# # convert PDF to PS and send to a printer by lpr
# pdf_file = "paper.pdf"
# printer = "printer-name"
# Open3.pipeline(["pdftops", pdf_file, "-"],
# ["lpr", "-P#{printer}"])
#
# # count lines
# Open3.pipeline("sort", "uniq -c", :in=>"names.txt", :out=>"count")
#
# # cyclic pipeline
# r,w = IO.pipe
# w.print "ibase=14\n10\n"
# Open3.pipeline("bc", "tee /dev/tty", :in=>r, :out=>w)
# #=> 14
# # 18
# # 22
# # 30
# # 42
# # 58
# # 78
# # 106
# # 202
#
def pipeline(*cmds)
if Hash === cmds.last
opts = cmds.pop.dup
else
opts = {}
end
pipeline_run(cmds, opts, [], []) {|ts|
ts.map {|t| t.value }
}
end
module_function :pipeline
def pipeline_run(cmds, pipeline_opts, child_io, parent_io, &block) # :nodoc:
if cmds.empty?
raise ArgumentError, "no commands"
end
opts_base = pipeline_opts.dup
opts_base.delete :in
opts_base.delete :out
wait_thrs = []
r = nil
cmds.each_with_index {|cmd, i|
cmd_opts = opts_base.dup
if String === cmd
cmd = [cmd]
else
cmd_opts.update cmd.pop if Hash === cmd.last
end
if i == 0
if !cmd_opts.include?(:in)
if pipeline_opts.include?(:in)
cmd_opts[:in] = pipeline_opts[:in]
end
end
else
cmd_opts[:in] = r
end
if i != cmds.length - 1
r2, w2 = IO.pipe
cmd_opts[:out] = w2
else
if !cmd_opts.include?(:out)
if pipeline_opts.include?(:out)
cmd_opts[:out] = pipeline_opts[:out]
end
end
end
pid = spawn(*cmd, cmd_opts)
wait_thrs << Process.detach(pid)
r.close if r
w2.close if w2
r = r2
}
result = parent_io + [wait_thrs]
child_io.each {|io| io.close }
if defined? yield
begin
return yield(*result)
ensure
parent_io.each{|io| io.close unless io.closed?}
wait_thrs.each {|t| t.join }
end
end
result
end
module_function :pipeline_run
class << self
private :pipeline_run
end
end
if $0 == __FILE__
a = Open3.popen3("nroff -man")
Thread.start do
while line = gets
a[0].print line
end
a[0].close
end
while line = a[1].gets
print ":", line
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/gserver.rb | tools/jruby-1.5.1/lib/ruby/1.9/gserver.rb | #
# Copyright (C) 2001 John W. Small All Rights Reserved
#
# Author:: John W. Small
# Documentation:: Gavin Sinclair
# Licence:: Freeware.
#
# See the class GServer for documentation.
#
require "socket"
require "thread"
#
# GServer implements a generic server, featuring thread pool management,
# simple logging, and multi-server management. See HttpServer in
# <tt>xmlrpc/httpserver.rb</tt> in the Ruby standard library for an example of
# GServer in action.
#
# Any kind of application-level server can be implemented using this class.
# It accepts multiple simultaneous connections from clients, up to an optional
# maximum number. Several _services_ (i.e. one service per TCP port) can be
# run simultaneously, and stopped at any time through the class method
# <tt>GServer.stop(port)</tt>. All the threading issues are handled, saving
# you the effort. All events are optionally logged, but you can provide your
# own event handlers if you wish.
#
# === Example
#
# Using GServer is simple. Below we implement a simple time server, run it,
# query it, and shut it down. Try this code in +irb+:
#
# require 'gserver'
#
# #
# # A server that returns the time in seconds since 1970.
# #
# class TimeServer < GServer
# def initialize(port=10001, *args)
# super(port, *args)
# end
# def serve(io)
# io.puts(Time.now.to_s)
# end
# end
#
# # Run the server with logging enabled (it's a separate thread).
# server = TimeServer.new
# server.audit = true # Turn logging on.
# server.start
#
# # *** Now point your browser to http://localhost:10001 to see it working ***
#
# # See if it's still running.
# GServer.in_service?(10001) # -> true
# server.stopped? # -> false
#
# # Shut the server down gracefully.
# server.shutdown
#
# # Alternatively, stop it immediately.
# GServer.stop(10001)
# # or, of course, "server.stop".
#
# All the business of accepting connections and exception handling is taken
# care of. All we have to do is implement the method that actually serves the
# client.
#
# === Advanced
#
# As the example above shows, the way to use GServer is to subclass it to
# create a specific server, overriding the +serve+ method. You can override
# other methods as well if you wish, perhaps to collect statistics, or emit
# more detailed logging.
#
# connecting
# disconnecting
# starting
# stopping
#
# The above methods are only called if auditing is enabled.
#
# You can also override +log+ and +error+ if, for example, you wish to use a
# more sophisticated logging system.
#
class GServer
DEFAULT_HOST = "127.0.0.1"
def serve(io)
end
@@services = {} # Hash of opened ports, i.e. services
@@servicesMutex = Mutex.new
def GServer.stop(port, host = DEFAULT_HOST)
@@servicesMutex.synchronize {
@@services[host][port].stop
}
end
def GServer.in_service?(port, host = DEFAULT_HOST)
@@services.has_key?(host) and
@@services[host].has_key?(port)
end
def stop
@connectionsMutex.synchronize {
if @tcpServerThread
@tcpServerThread.raise "stop"
end
}
end
def stopped?
@tcpServerThread == nil
end
def shutdown
@shutdown = true
end
def connections
@connections.size
end
def join
@tcpServerThread.join if @tcpServerThread
end
attr_reader :port, :host, :maxConnections
attr_accessor :stdlog, :audit, :debug
def connecting(client)
addr = client.peeraddr
log("#{self.class.to_s} #{@host}:#{@port} client:#{addr[1]} " +
"#{addr[2]}<#{addr[3]}> connect")
true
end
def disconnecting(clientPort)
log("#{self.class.to_s} #{@host}:#{@port} " +
"client:#{clientPort} disconnect")
end
protected :connecting, :disconnecting
def starting()
log("#{self.class.to_s} #{@host}:#{@port} start")
end
def stopping()
log("#{self.class.to_s} #{@host}:#{@port} stop")
end
protected :starting, :stopping
def error(detail)
log(detail.backtrace.join("\n"))
end
def log(msg)
if @stdlog
@stdlog.puts("[#{Time.new.ctime}] %s" % msg)
@stdlog.flush
end
end
protected :error, :log
def initialize(port, host = DEFAULT_HOST, maxConnections = 4,
stdlog = $stderr, audit = false, debug = false)
@tcpServerThread = nil
@port = port
@host = host
@maxConnections = maxConnections
@connections = []
@connectionsMutex = Mutex.new
@connectionsCV = ConditionVariable.new
@stdlog = stdlog
@audit = audit
@debug = debug
end
def start(maxConnections = -1)
raise "running" if !stopped?
@shutdown = false
@maxConnections = maxConnections if maxConnections > 0
@@servicesMutex.synchronize {
if GServer.in_service?(@port,@host)
raise "Port already in use: #{host}:#{@port}!"
end
@tcpServer = TCPServer.new(@host,@port)
@port = @tcpServer.addr[1]
@@services[@host] = {} unless @@services.has_key?(@host)
@@services[@host][@port] = self;
}
@tcpServerThread = Thread.new {
begin
starting if @audit
while !@shutdown
@connectionsMutex.synchronize {
while @connections.size >= @maxConnections
@connectionsCV.wait(@connectionsMutex)
end
}
client = @tcpServer.accept
@connections << Thread.new(client) { |myClient|
begin
myPort = myClient.peeraddr[1]
serve(myClient) if !@audit or connecting(myClient)
rescue => detail
error(detail) if @debug
ensure
begin
myClient.close
rescue
end
@connectionsMutex.synchronize {
@connections.delete(Thread.current)
@connectionsCV.signal
}
disconnecting(myPort) if @audit
end
}
end
rescue => detail
error(detail) if @debug
ensure
begin
@tcpServer.close
rescue
end
if @shutdown
@connectionsMutex.synchronize {
while @connections.size > 0
@connectionsCV.wait(@connectionsMutex)
end
}
else
@connections.each { |c| c.raise "stop" }
end
@tcpServerThread = nil
@@servicesMutex.synchronize {
@@services[@host].delete(@port)
}
stopping if @audit
end
}
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/1.9/rss.rb | tools/jruby-1.5.1/lib/ruby/1.9/rss.rb | # Copyright (c) 2003-2007 Kouhei Sutou. You can redistribute it and/or
# modify it under the same terms as Ruby.
#
# Author:: Kouhei Sutou <kou@cozmixng.org>
# Tutorial:: http://www.cozmixng.org/~rwiki/?cmd=view;name=RSS+Parser%3A%3ATutorial.en
require 'rss/1.0'
require 'rss/2.0'
require 'rss/atom'
require 'rss/content'
require 'rss/dublincore'
require 'rss/image'
require 'rss/itunes'
require 'rss/slash'
require 'rss/syndication'
require 'rss/taxonomy'
require 'rss/trackback'
require "rss/maker"
| 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/complex.rb | tools/jruby-1.5.1/lib/ruby/1.9/complex.rb | # :enddoc:
warn('lib/complex.rb is deprecated') if $VERBOSE
require 'cmath'
unless defined?(Math.exp!)
Object.instance_eval{remove_const :Math}
Math = CMath
end
def Complex.generic? (other)
other.kind_of?(Integer) ||
other.kind_of?(Float) ||
other.kind_of?(Rational)
end
class Complex
alias image imag
end
class Numeric
def im() Complex(0, 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/1.9/forwardable.rb | tools/jruby-1.5.1/lib/ruby/1.9/forwardable.rb | #
# forwardable.rb -
# $Release Version: 1.1$
# $Revision: 22784 $
# by Keiju ISHITSUKA(keiju@ishitsuka.com)
# original definition by delegator.rb
# Revised by Daniel J. Berger with suggestions from Florian Gross.
#
# Documentation by James Edward Gray II and Gavin Sinclair
#
# == Introduction
#
# This library allows you delegate method calls to an object, on a method by
# method basis.
#
# == Notes
#
# Be advised, RDoc will not detect delegated methods.
#
# <b>forwardable.rb provides single-method delegation via the
# def_delegator() and def_delegators() methods. For full-class
# delegation via DelegateClass(), see delegate.rb.</b>
#
# == Examples
#
# === Forwardable
#
# Forwardable makes building a new class based on existing work, with a proper
# interface, almost trivial. We want to rely on what has come before obviously,
# but with delegation we can take just the methods we need and even rename them
# as appropriate. In many cases this is preferable to inheritance, which gives
# us the entire old interface, even if much of it isn't needed.
#
# class Queue
# extend Forwardable
#
# def initialize
# @q = [ ] # prepare delegate object
# end
#
# # setup preferred interface, enq() and deq()...
# def_delegator :@q, :push, :enq
# def_delegator :@q, :shift, :deq
#
# # support some general Array methods that fit Queues well
# def_delegators :@q, :clear, :first, :push, :shift, :size
# end
#
# q = Queue.new
# q.enq 1, 2, 3, 4, 5
# q.push 6
#
# q.shift # => 1
# while q.size > 0
# puts q.deq
# end
#
# q.enq "Ruby", "Perl", "Python"
# puts q.first
# q.clear
# puts q.first
#
# <i>Prints:</i>
#
# 2
# 3
# 4
# 5
# 6
# Ruby
# nil
#
# SingleForwardable can be used to setup delegation at the object level as well.
#
# printer = String.new
# printer.extend SingleForwardable # prepare object for delegation
# printer.def_delegator "STDOUT", "puts" # add delegation for STDOUT.puts()
# printer.puts "Howdy!"
#
# Also, SingleForwardable can be use to Class or Module.
#
# module Facade
# extend SingleForwardable
# def_delegator :Implementation, :service
#
# class Implementation
# def service...
# end
# end
#
# If you want to use both Forwardable and SingleForwardable, you can
# use methods def_instance_delegator and def_single_delegator, etc.
#
# If the object isn't a Module and Class, You can too extend
# Forwardable module.
# printer = String.new
# printer.extend Forwardable # prepare object for delegation
# printer.def_delegator "STDOUT", "puts" # add delegation for STDOUT.puts()
# printer.puts "Howdy!"
#
# <i>Prints:</i>
#
# Howdy!
#
# The Forwardable module provides delegation of specified
# methods to a designated object, using the methods #def_delegator
# and #def_delegators.
#
# For example, say you have a class RecordCollection which
# contains an array <tt>@records</tt>. You could provide the lookup method
# #record_number(), which simply calls #[] on the <tt>@records</tt>
# array, like this:
#
# class RecordCollection
# extend Forwardable
# def_delegator :@records, :[], :record_number
# end
#
# Further, if you wish to provide the methods #size, #<<, and #map,
# all of which delegate to @records, this is how you can do it:
#
# class RecordCollection
# # extend Forwardable, but we did that above
# def_delegators :@records, :size, :<<, :map
# end
# f = Foo.new
# f.printf ...
# f.gets
# f.content_at(1)
#
# Also see the example at forwardable.rb.
module Forwardable
FORWARDABLE_VERSION = "1.1.0"
@debug = nil
class<<self
attr_accessor :debug
end
# Takes a hash as its argument. The key is a symbol or an array of
# symbols. These symbols correspond to method names. The value is
# the accessor to which the methods will be delegated.
#
# :call-seq:
# delegate method => accessor
# delegate [method, method, ...] => accessor
#
def instance_delegate(hash)
hash.each{ |methods, accessor|
methods = methods.to_s unless methods.respond_to?(:each)
methods.each{ |method|
def_instance_delegator(accessor, method)
}
}
end
#
# Shortcut for defining multiple delegator methods, but with no
# provision for using a different name. The following two code
# samples have the same effect:
#
# def_delegators :@records, :size, :<<, :map
#
# def_delegator :@records, :size
# def_delegator :@records, :<<
# def_delegator :@records, :map
#
def def_instance_delegators(accessor, *methods)
methods.delete("__send__")
methods.delete("__id__")
for method in methods
def_instance_delegator(accessor, method)
end
end
def def_instance_delegator(accessor, method, ali = method)
line_no = __LINE__; str = %{
def #{ali}(*args, &block)
begin
#{accessor}.__send__(:#{method}, *args, &block)
rescue Exception
$@.delete_if{|s| %r"#{Regexp.quote(__FILE__)}"o =~ s} unless Forwardable::debug
::Kernel::raise
end
end
}
# If it's not a class or module, it's an instance
begin
module_eval(str, __FILE__, line_no)
rescue
instance_eval(str, __FILE__, line_no)
end
end
alias delegate instance_delegate
alias def_delegators def_instance_delegators
alias def_delegator def_instance_delegator
end
#
# Usage of The SingleForwardable is like Fowadable module.
#
module SingleForwardable
# Takes a hash as its argument. The key is a symbol or an array of
# symbols. These symbols correspond to method names. The value is
# the accessor to which the methods will be delegated.
#
# :call-seq:
# delegate method => accessor
# delegate [method, method, ...] => accessor
#
def single_delegate(hash)
hash.each{ |methods, accessor|
methods = methods.to_s unless methods.respond_to?(:each)
methods.each{ |method|
def_single_delegator(accessor, method)
}
}
end
#
# Shortcut for defining multiple delegator methods, but with no
# provision for using a different name. The following two code
# samples have the same effect:
#
# def_delegators :@records, :size, :<<, :map
#
# def_delegator :@records, :size
# def_delegator :@records, :<<
# def_delegator :@records, :map
#
def def_single_delegators(accessor, *methods)
methods.delete("__send__")
methods.delete("__id__")
for method in methods
def_single_delegator(accessor, method)
end
end
#
# Defines a method _method_ which delegates to _obj_ (i.e. it calls
# the method of the same name in _obj_). If _new_name_ is
# provided, it is used as the name for the delegate method.
#
def def_single_delegator(accessor, method, ali = method)
line_no = __LINE__; str = %{
def #{ali}(*args, &block)
begin
#{accessor}.__send__(:#{method}, *args, &block)
rescue Exception
$@.delete_if{|s| %r"#{Regexp.quote(__FILE__)}"o =~ s} unless Forwardable::debug
::Kernel::raise
end
end
}
instance_eval(str, __FILE__, __LINE__)
end
alias delegate single_delegate
alias def_delegators def_single_delegators
alias def_delegator def_single_delegator
end
| 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.rb | tools/jruby-1.5.1/lib/ruby/1.9/shell.rb | #
# shell.rb -
# $Release Version: 0.7 $
# $Revision: 1.9 $
# by Keiju ISHITSUKA(keiju@ruby-lang.org)
#
# --
#
#
#
require "e2mmap"
require "thread" unless defined?(Mutex)
require "forwardable"
require "shell/error"
require "shell/command-processor"
require "shell/process-controller"
class Shell
@RCS_ID='-$Id: shell.rb,v 1.9 2002/03/04 12:01:10 keiju Exp keiju $-'
include Error
extend Exception2MessageMapper
# @cascade = true
# debug: true -> normal debug
# debug: 1 -> eval definition debug
# debug: 2 -> detail inspect debug
@debug = false
@verbose = true
@debug_display_process_id = false
@debug_display_thread_id = true
@debug_output_mutex = Mutex.new
class << Shell
extend Forwardable
attr_accessor :cascade, :debug, :verbose
# alias cascade? cascade
alias debug? debug
alias verbose? verbose
@verbose = true
def debug=(val)
@debug = val
@verbose = val if val
end
def cd(path)
new(path)
end
def default_system_path
if @default_system_path
@default_system_path
else
ENV["PATH"].split(":")
end
end
def default_system_path=(path)
@default_system_path = path
end
def default_record_separator
if @default_record_separator
@default_record_separator
else
$/
end
end
def default_record_separator=(rs)
@default_record_separator = rs
end
# os resource mutex
mutex_methods = ["unlock", "lock", "locked?", "synchronize", "try_lock", "exclusive_unlock"]
for m in mutex_methods
def_delegator("@debug_output_mutex", m, "debug_output_"+m.to_s)
end
end
def initialize(pwd = Dir.pwd, umask = nil)
@cwd = File.expand_path(pwd)
@dir_stack = []
@umask = umask
@system_path = Shell.default_system_path
@record_separator = Shell.default_record_separator
@command_processor = CommandProcessor.new(self)
@process_controller = ProcessController.new(self)
@verbose = Shell.verbose
@debug = Shell.debug
end
attr_reader :system_path
def system_path=(path)
@system_path = path
rehash
end
attr_accessor :umask, :record_separator
attr_accessor :verbose, :debug
def debug=(val)
@debug = val
@verbose = val if val
end
alias verbose? verbose
alias debug? debug
attr_reader :command_processor
attr_reader :process_controller
def expand_path(path)
File.expand_path(path, @cwd)
end
# Most Shell commands are defined via CommandProcessor
#
# Dir related methods
#
# Shell#cwd/dir/getwd/pwd
# Shell#chdir/cd
# Shell#pushdir/pushd
# Shell#popdir/popd
# Shell#mkdir
# Shell#rmdir
attr_reader :cwd
alias dir cwd
alias getwd cwd
alias pwd cwd
attr_reader :dir_stack
alias dirs dir_stack
# If called as iterator, it restores the current directory when the
# block ends.
def chdir(path = nil, verbose = @verbose)
check_point
if iterator?
notify("chdir(with block) #{path}") if verbose
cwd_old = @cwd
begin
chdir(path, nil)
yield
ensure
chdir(cwd_old, nil)
end
else
notify("chdir #{path}") if verbose
path = "~" unless path
@cwd = expand_path(path)
notify "current dir: #{@cwd}"
rehash
Void.new(self)
end
end
alias cd chdir
def pushdir(path = nil, verbose = @verbose)
check_point
if iterator?
notify("pushdir(with block) #{path}") if verbose
pushdir(path, nil)
begin
yield
ensure
popdir
end
elsif path
notify("pushdir #{path}") if verbose
@dir_stack.push @cwd
chdir(path, nil)
notify "dir stack: [#{@dir_stack.join ', '}]"
self
else
notify("pushdir") if verbose
if pop = @dir_stack.pop
@dir_stack.push @cwd
chdir pop
notify "dir stack: [#{@dir_stack.join ', '}]"
self
else
Shell.Fail DirStackEmpty
end
end
Void.new(self)
end
alias pushd pushdir
def popdir
check_point
notify("popdir")
if pop = @dir_stack.pop
chdir pop
notify "dir stack: [#{@dir_stack.join ', '}]"
self
else
Shell.Fail DirStackEmpty
end
Void.new(self)
end
alias popd popdir
#
# process management
#
def jobs
@process_controller.jobs
end
def kill(sig, command)
@process_controller.kill_job(sig, command)
end
#
# command definitions
#
def Shell.def_system_command(command, path = command)
CommandProcessor.def_system_command(command, path)
end
def Shell.undef_system_command(command)
CommandProcessor.undef_system_command(command)
end
def Shell.alias_command(ali, command, *opts, &block)
CommandProcessor.alias_command(ali, command, *opts, &block)
end
def Shell.unalias_command(ali)
CommandProcessor.unalias_command(ali)
end
def Shell.install_system_commands(pre = "sys_")
CommandProcessor.install_system_commands(pre)
end
#
def inspect
if debug.kind_of?(Integer) && debug > 2
super
else
to_s
end
end
def self.notify(*opts, &block)
Shell::debug_output_synchronize do
if opts[-1].kind_of?(String)
yorn = verbose?
else
yorn = opts.pop
end
return unless yorn
if @debug_display_thread_id
if @debug_display_process_id
prefix = "shell(##{Process.pid}:#{Thread.current.to_s.sub("Thread", "Th")}): "
else
prefix = "shell(#{Thread.current.to_s.sub("Thread", "Th")}): "
end
else
prefix = "shell: "
end
_head = true
STDERR.print opts.collect{|mes|
mes = mes.dup
yield mes if iterator?
if _head
_head = false
# "shell" " + mes
prefix + mes
else
" "* prefix.size + mes
end
}.join("\n")+"\n"
end
end
CommandProcessor.initialize
CommandProcessor.run_config
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/shellwords.rb | tools/jruby-1.5.1/lib/ruby/1.9/shellwords.rb | #
# shellwords.rb: Manipulates strings a la UNIX Bourne shell
#
#
# This module manipulates strings according to the word parsing rules
# of the UNIX Bourne shell.
#
# The shellwords() function was originally a port of shellwords.pl,
# but modified to conform to POSIX / SUSv3 (IEEE Std 1003.1-2001).
#
# Authors:
# - Wakou Aoyama
# - Akinori MUSHA <knu@iDaemons.org>
#
# Contact:
# - Akinori MUSHA <knu@iDaemons.org> (current maintainer)
#
module Shellwords
#
# Splits a string into an array of tokens in the same way the UNIX
# Bourne shell does.
#
# argv = Shellwords.split('here are "two words"')
# argv #=> ["here", "are", "two words"]
#
# +String#shellsplit+ is a shorthand for this function.
#
# argv = 'here are "two words"'.shellsplit
# argv #=> ["here", "are", "two words"]
#
def shellsplit(line)
words = []
field = ''
line.scan(/\G\s*(?>([^\s\\\'\"]+)|'([^\']*)'|"((?:[^\"\\]|\\.)*)"|(\\.?)|(\S))(\s|\z)?/m) do
|word, sq, dq, esc, garbage, sep|
raise ArgumentError, "Unmatched double quote: #{line.inspect}" if garbage
field << (word || sq || (dq || esc).gsub(/\\(?=.)/, ''))
if sep
words << field
field = ''
end
end
words
end
alias shellwords shellsplit
module_function :shellsplit, :shellwords
class << self
alias split shellsplit
end
#
# Escapes a string so that it can be safely used in a Bourne shell
# command line.
#
# Note that a resulted string should be used unquoted and is not
# intended for use in double quotes nor in single quotes.
#
# open("| grep #{Shellwords.escape(pattern)} file") { |pipe|
# # ...
# }
#
# +String#shellescape+ is a shorthand for this function.
#
# open("| grep #{pattern.shellescape} file") { |pipe|
# # ...
# }
#
def shellescape(str)
# An empty argument will be skipped, so return empty quotes.
return "''" if str.empty?
str = str.dup
# Process as a single byte sequence because not all shell
# implementations are multibyte aware.
str.gsub!(/([^A-Za-z0-9_\-.,:\/@\n])/n, "\\\\\\1")
# A LF cannot be escaped with a backslash because a backslash + LF
# combo is regarded as line continuation and simply ignored.
str.gsub!(/\n/, "'\n'")
return str
end
module_function :shellescape
class << self
alias escape shellescape
end
#
# Builds a command line string from an argument list +array+ joining
# all elements escaped for Bourne shell and separated by a space.
#
# open('|' + Shellwords.join(['grep', pattern, *files])) { |pipe|
# # ...
# }
#
# +Array#shelljoin+ is a shorthand for this function.
#
# open('|' + ['grep', pattern, *files].shelljoin) { |pipe|
# # ...
# }
#
def shelljoin(array)
array.map { |arg| shellescape(arg) }.join(' ')
end
module_function :shelljoin
class << self
alias join shelljoin
end
end
class String
#
# call-seq:
# str.shellsplit => array
#
# Splits +str+ into an array of tokens in the same way the UNIX
# Bourne shell does. See +Shellwords::shellsplit+ for details.
#
def shellsplit
Shellwords.split(self)
end
#
# call-seq:
# str.shellescape => string
#
# Escapes +str+ so that it can be safely used in a Bourne shell
# command line. See +Shellwords::shellescape+ for details.
#
def shellescape
Shellwords.escape(self)
end
end
class Array
#
# call-seq:
# array.shelljoin => string
#
# Builds a command line string from an argument list +array+ joining
# all elements escaped for Bourne shell and separated by a space.
# See +Shellwords::shelljoin+ for details.
#
def shelljoin
Shellwords.join(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/1.9/pathname.rb | tools/jruby-1.5.1/lib/ruby/1.9/pathname.rb | #
# = pathname.rb
#
# Object-Oriented Pathname Class
#
# Author:: Tanaka Akira <akr@m17n.org>
# Documentation:: Author and Gavin Sinclair
#
# For documentation, see class Pathname.
#
# <tt>pathname.rb</tt> is distributed with Ruby since 1.8.0.
#
#
# == Pathname
#
# Pathname represents a pathname which locates a file in a filesystem.
# The pathname depends on OS: Unix, Windows, etc.
# Pathname library works with pathnames of local OS.
# However non-Unix pathnames are supported experimentally.
#
# It does not represent the file itself.
# A Pathname can be relative or absolute. It's not until you try to
# reference the file that it even matters whether the file exists or not.
#
# Pathname is immutable. It has no method for destructive update.
#
# The value of this class is to manipulate file path information in a neater
# way than standard Ruby provides. The examples below demonstrate the
# difference. *All* functionality from File, FileTest, and some from Dir and
# FileUtils is included, in an unsurprising way. It is essentially a facade for
# all of these, and more.
#
# == Examples
#
# === Example 1: Using Pathname
#
# require 'pathname'
# pn = Pathname.new("/usr/bin/ruby")
# size = pn.size # 27662
# isdir = pn.directory? # false
# dir = pn.dirname # Pathname:/usr/bin
# base = pn.basename # Pathname:ruby
# dir, base = pn.split # [Pathname:/usr/bin, Pathname:ruby]
# data = pn.read
# pn.open { |f| _ }
# pn.each_line { |line| _ }
#
# === Example 2: Using standard Ruby
#
# pn = "/usr/bin/ruby"
# size = File.size(pn) # 27662
# isdir = File.directory?(pn) # false
# dir = File.dirname(pn) # "/usr/bin"
# base = File.basename(pn) # "ruby"
# dir, base = File.split(pn) # ["/usr/bin", "ruby"]
# data = File.read(pn)
# File.open(pn) { |f| _ }
# File.foreach(pn) { |line| _ }
#
# === Example 3: Special features
#
# p1 = Pathname.new("/usr/lib") # Pathname:/usr/lib
# p2 = p1 + "ruby/1.8" # Pathname:/usr/lib/ruby/1.8
# p3 = p1.parent # Pathname:/usr
# p4 = p2.relative_path_from(p3) # Pathname:lib/ruby/1.8
# pwd = Pathname.pwd # Pathname:/home/gavin
# pwd.absolute? # true
# p5 = Pathname.new "." # Pathname:.
# p5 = p5 + "music/../articles" # Pathname:music/../articles
# p5.cleanpath # Pathname:articles
# p5.realpath # Pathname:/home/gavin/articles
# p5.children # [Pathname:/home/gavin/articles/linux, ...]
#
# == Breakdown of functionality
#
# === Core methods
#
# These methods are effectively manipulating a String, because that's
# all a path is. Except for #mountpoint?, #children, #each_child,
# #realdirpath and #realpath, they don't access the filesystem.
#
# - +
# - #join
# - #parent
# - #root?
# - #absolute?
# - #relative?
# - #relative_path_from
# - #each_filename
# - #cleanpath
# - #realpath
# - #realdirpath
# - #children
# - #each_child
# - #mountpoint?
#
# === File status predicate methods
#
# These methods are a facade for FileTest:
# - #blockdev?
# - #chardev?
# - #directory?
# - #executable?
# - #executable_real?
# - #exist?
# - #file?
# - #grpowned?
# - #owned?
# - #pipe?
# - #readable?
# - #world_readable?
# - #readable_real?
# - #setgid?
# - #setuid?
# - #size
# - #size?
# - #socket?
# - #sticky?
# - #symlink?
# - #writable?
# - #world_writable?
# - #writable_real?
# - #zero?
#
# === File property and manipulation methods
#
# These methods are a facade for File:
# - #atime
# - #ctime
# - #mtime
# - #chmod(mode)
# - #lchmod(mode)
# - #chown(owner, group)
# - #lchown(owner, group)
# - #fnmatch(pattern, *args)
# - #fnmatch?(pattern, *args)
# - #ftype
# - #make_link(old)
# - #open(*args, &block)
# - #readlink
# - #rename(to)
# - #stat
# - #lstat
# - #make_symlink(old)
# - #truncate(length)
# - #utime(atime, mtime)
# - #basename(*args)
# - #dirname
# - #extname
# - #expand_path(*args)
# - #split
#
# === Directory methods
#
# These methods are a facade for Dir:
# - Pathname.glob(*args)
# - Pathname.getwd / Pathname.pwd
# - #rmdir
# - #entries
# - #each_entry(&block)
# - #mkdir(*args)
# - #opendir(*args)
#
# === IO
#
# These methods are a facade for IO:
# - #each_line(*args, &block)
# - #read(*args)
# - #binread(*args)
# - #readlines(*args)
# - #sysopen(*args)
#
# === Utilities
#
# These methods are a mixture of Find, FileUtils, and others:
# - #find(&block)
# - #mkpath
# - #rmtree
# - #unlink / #delete
#
#
# == Method documentation
#
# As the above section shows, most of the methods in Pathname are facades. The
# documentation for these methods generally just says, for instance, "See
# FileTest.writable?", as you should be familiar with the original method
# anyway, and its documentation (e.g. through +ri+) will contain more
# information. In some cases, a brief description will follow.
#
class Pathname
# :stopdoc:
if RUBY_VERSION < "1.9"
TO_PATH = :to_str
else
# to_path is implemented so Pathname objects are usable with File.open, etc.
TO_PATH = :to_path
end
SAME_PATHS = if File::FNM_SYSCASE
proc {|a, b| a.casecmp(b).zero?}
else
proc {|a, b| a == b}
end
# :startdoc:
#
# Create a Pathname object from the given String (or String-like object).
# If +path+ contains a NUL character (<tt>\0</tt>), an ArgumentError is raised.
#
def initialize(path)
path = path.__send__(TO_PATH) if path.respond_to? TO_PATH
@path = path.dup
if /\0/ =~ @path
raise ArgumentError, "pathname contains \\0: #{@path.inspect}"
end
self.taint if @path.tainted?
end
def freeze() super; @path.freeze; self end
def taint() super; @path.taint; self end
def untaint() super; @path.untaint; self end
#
# Compare this pathname with +other+. The comparison is string-based.
# Be aware that two different paths (<tt>foo.txt</tt> and <tt>./foo.txt</tt>)
# can refer to the same file.
#
def ==(other)
return false unless Pathname === other
other.to_s == @path
end
alias === ==
alias eql? ==
# Provides for comparing pathnames, case-sensitively.
def <=>(other)
return nil unless Pathname === other
@path.tr('/', "\0") <=> other.to_s.tr('/', "\0")
end
def hash # :nodoc:
@path.hash
end
# Return the path as a String.
def to_s
@path.dup
end
# to_path is implemented so Pathname objects are usable with File.open, etc.
alias_method TO_PATH, :to_s
def inspect # :nodoc:
"#<#{self.class}:#{@path}>"
end
# Return a pathname which is substituted by String#sub.
def sub(pattern, *rest, &block)
if block
path = @path.sub(pattern, *rest) {|*args|
begin
old = Thread.current[:pathname_sub_matchdata]
Thread.current[:pathname_sub_matchdata] = $~
eval("$~ = Thread.current[:pathname_sub_matchdata]", block.binding)
ensure
Thread.current[:pathname_sub_matchdata] = old
end
yield(*args)
}
else
path = @path.sub(pattern, *rest)
end
self.class.new(path)
end
if File::ALT_SEPARATOR
SEPARATOR_LIST = "#{Regexp.quote File::ALT_SEPARATOR}#{Regexp.quote File::SEPARATOR}"
SEPARATOR_PAT = /[#{SEPARATOR_LIST}]/
else
SEPARATOR_LIST = "#{Regexp.quote File::SEPARATOR}"
SEPARATOR_PAT = /#{Regexp.quote File::SEPARATOR}/
end
# Return a pathname which the extension of the basename is substituted by
# <i>repl</i>.
#
# If self has no extension part, <i>repl</i> is appended.
def sub_ext(repl)
ext = File.extname(@path)
self.class.new(@path.chomp(ext) + repl)
end
# chop_basename(path) -> [pre-basename, basename] or nil
def chop_basename(path)
base = File.basename(path)
if /\A#{SEPARATOR_PAT}?\z/o =~ base
return nil
else
return path[0, path.rindex(base)], base
end
end
private :chop_basename
# split_names(path) -> prefix, [name, ...]
def split_names(path)
names = []
while r = chop_basename(path)
path, basename = r
names.unshift basename
end
return path, names
end
private :split_names
def prepend_prefix(prefix, relpath)
if relpath.empty?
File.dirname(prefix)
elsif /#{SEPARATOR_PAT}/o =~ prefix
prefix = File.dirname(prefix)
prefix = File.join(prefix, "") if File.basename(prefix + 'a') != 'a'
prefix + relpath
else
prefix + relpath
end
end
private :prepend_prefix
# Returns clean pathname of +self+ with consecutive slashes and useless dots
# removed. The filesystem is not accessed.
#
# If +consider_symlink+ is +true+, then a more conservative algorithm is used
# to avoid breaking symbolic linkages. This may retain more <tt>..</tt>
# entries than absolutely necessary, but without accessing the filesystem,
# this can't be avoided. See #realpath.
#
def cleanpath(consider_symlink=false)
if consider_symlink
cleanpath_conservative
else
cleanpath_aggressive
end
end
#
# Clean the path simply by resolving and removing excess "." and ".." entries.
# Nothing more, nothing less.
#
def cleanpath_aggressive
path = @path
names = []
pre = path
while r = chop_basename(pre)
pre, base = r
case base
when '.'
when '..'
names.unshift base
else
if names[0] == '..'
names.shift
else
names.unshift base
end
end
end
if /#{SEPARATOR_PAT}/o =~ File.basename(pre)
names.shift while names[0] == '..'
end
self.class.new(prepend_prefix(pre, File.join(*names)))
end
private :cleanpath_aggressive
# has_trailing_separator?(path) -> bool
def has_trailing_separator?(path)
if r = chop_basename(path)
pre, basename = r
pre.length + basename.length < path.length
else
false
end
end
private :has_trailing_separator?
# add_trailing_separator(path) -> path
def add_trailing_separator(path)
if File.basename(path + 'a') == 'a'
path
else
File.join(path, "") # xxx: Is File.join is appropriate to add separator?
end
end
private :add_trailing_separator
def del_trailing_separator(path)
if r = chop_basename(path)
pre, basename = r
pre + basename
elsif /#{SEPARATOR_PAT}+\z/o =~ path
$` + File.dirname(path)[/#{SEPARATOR_PAT}*\z/o]
else
path
end
end
private :del_trailing_separator
def cleanpath_conservative
path = @path
names = []
pre = path
while r = chop_basename(pre)
pre, base = r
names.unshift base if base != '.'
end
if /#{SEPARATOR_PAT}/o =~ File.basename(pre)
names.shift while names[0] == '..'
end
if names.empty?
self.class.new(File.dirname(pre))
else
if names.last != '..' && File.basename(path) == '.'
names << '.'
end
result = prepend_prefix(pre, File.join(*names))
if /\A(?:\.|\.\.)\z/ !~ names.last && has_trailing_separator?(path)
self.class.new(add_trailing_separator(result))
else
self.class.new(result)
end
end
end
private :cleanpath_conservative
def realpath_rec(prefix, unresolved, h, strict, last = true)
resolved = []
until unresolved.empty?
n = unresolved.shift
if n == '.'
next
elsif n == '..'
resolved.pop
else
path = prepend_prefix(prefix, File.join(*(resolved + [n])))
if h.include? path
if h[path] == :resolving
raise Errno::ELOOP.new(path)
else
prefix, *resolved = h[path]
end
else
begin
s = File.lstat(path)
rescue Errno::ENOENT => e
raise e if strict || !last || !unresolved.empty?
resolved << n
break
end
if s.symlink?
h[path] = :resolving
link_prefix, link_names = split_names(File.readlink(path))
if link_prefix == ''
prefix, *resolved = h[path] = realpath_rec(prefix, resolved + link_names, h, strict, unresolved.empty?)
else
prefix, *resolved = h[path] = realpath_rec(link_prefix, link_names, h, strict, unresolved.empty?)
end
else
resolved << n
h[path] = [prefix, *resolved]
end
end
end
end
return prefix, *resolved
end
private :realpath_rec
def real_path_internal(strict = false)
path = @path
prefix, names = split_names(path)
if prefix == ''
prefix, names2 = split_names(Dir.pwd)
names = names2 + names
end
prefix, *names = realpath_rec(prefix, names, {}, strict)
self.class.new(prepend_prefix(prefix, File.join(*names)))
end
private :real_path_internal
#
# Returns the real (absolute) pathname of +self+ in the actual
# filesystem not containing symlinks or useless dots.
#
# All components of the pathname must exist when this method is
# called.
#
def realpath
real_path_internal(true)
end
#
# Returns the real (absolute) pathname of +self+ in the actual filesystem.
# The real pathname doesn't contain symlinks or useless dots.
#
# The last component of the real pathname can be nonexistent.
#
def realdirpath
real_path_internal(false)
end
# #parent returns the parent directory.
#
# This is same as <tt>self + '..'</tt>.
def parent
self + '..'
end
# #mountpoint? returns +true+ if <tt>self</tt> points to a mountpoint.
def mountpoint?
begin
stat1 = self.lstat
stat2 = self.parent.lstat
stat1.dev == stat2.dev && stat1.ino == stat2.ino ||
stat1.dev != stat2.dev
rescue Errno::ENOENT
false
end
end
#
# #root? is a predicate for root directories. I.e. it returns +true+ if the
# pathname consists of consecutive slashes.
#
# It doesn't access actual filesystem. So it may return +false+ for some
# pathnames which points to roots such as <tt>/usr/..</tt>.
#
def root?
!!(chop_basename(@path) == nil && /#{SEPARATOR_PAT}/o =~ @path)
end
# Predicate method for testing whether a path is absolute.
# It returns +true+ if the pathname begins with a slash.
def absolute?
!relative?
end
# The opposite of #absolute?
def relative?
path = @path
while r = chop_basename(path)
path, basename = r
end
path == ''
end
#
# Iterates over each component of the path.
#
# Pathname.new("/usr/bin/ruby").each_filename {|filename| ... }
# # yields "usr", "bin", and "ruby".
#
def each_filename # :yield: filename
return to_enum(__method__) unless block_given?
prefix, names = split_names(@path)
names.each {|filename| yield filename }
nil
end
# Iterates over and yields a new Pathname object
# for each element in the given path in descending order.
#
# Pathname.new('/path/to/some/file.rb').descend {|v| p v}
# #<Pathname:/>
# #<Pathname:/path>
# #<Pathname:/path/to>
# #<Pathname:/path/to/some>
# #<Pathname:/path/to/some/file.rb>
#
# Pathname.new('path/to/some/file.rb').descend {|v| p v}
# #<Pathname:path>
# #<Pathname:path/to>
# #<Pathname:path/to/some>
# #<Pathname:path/to/some/file.rb>
#
# It doesn't access actual filesystem.
#
# This method is available since 1.8.5.
#
def descend
vs = []
ascend {|v| vs << v }
vs.reverse_each {|v| yield v }
nil
end
# Iterates over and yields a new Pathname object
# for each element in the given path in ascending order.
#
# Pathname.new('/path/to/some/file.rb').ascend {|v| p v}
# #<Pathname:/path/to/some/file.rb>
# #<Pathname:/path/to/some>
# #<Pathname:/path/to>
# #<Pathname:/path>
# #<Pathname:/>
#
# Pathname.new('path/to/some/file.rb').ascend {|v| p v}
# #<Pathname:path/to/some/file.rb>
# #<Pathname:path/to/some>
# #<Pathname:path/to>
# #<Pathname:path>
#
# It doesn't access actual filesystem.
#
# This method is available since 1.8.5.
#
def ascend
path = @path
yield self
while r = chop_basename(path)
path, name = r
break if path.empty?
yield self.class.new(del_trailing_separator(path))
end
end
#
# Pathname#+ appends a pathname fragment to this one to produce a new Pathname
# object.
#
# p1 = Pathname.new("/usr") # Pathname:/usr
# p2 = p1 + "bin/ruby" # Pathname:/usr/bin/ruby
# p3 = p1 + "/etc/passwd" # Pathname:/etc/passwd
#
# This method doesn't access the file system; it is pure string manipulation.
#
def +(other)
other = Pathname.new(other) unless Pathname === other
Pathname.new(plus(@path, other.to_s))
end
def plus(path1, path2) # -> path
prefix2 = path2
index_list2 = []
basename_list2 = []
while r2 = chop_basename(prefix2)
prefix2, basename2 = r2
index_list2.unshift prefix2.length
basename_list2.unshift basename2
end
return path2 if prefix2 != ''
prefix1 = path1
while true
while !basename_list2.empty? && basename_list2.first == '.'
index_list2.shift
basename_list2.shift
end
break unless r1 = chop_basename(prefix1)
prefix1, basename1 = r1
next if basename1 == '.'
if basename1 == '..' || basename_list2.empty? || basename_list2.first != '..'
prefix1 = prefix1 + basename1
break
end
index_list2.shift
basename_list2.shift
end
r1 = chop_basename(prefix1)
if !r1 && /#{SEPARATOR_PAT}/o =~ File.basename(prefix1)
while !basename_list2.empty? && basename_list2.first == '..'
index_list2.shift
basename_list2.shift
end
end
if !basename_list2.empty?
suffix2 = path2[index_list2.first..-1]
r1 ? File.join(prefix1, suffix2) : prefix1 + suffix2
else
r1 ? prefix1 : File.dirname(prefix1)
end
end
private :plus
#
# Pathname#join joins pathnames.
#
# <tt>path0.join(path1, ..., pathN)</tt> is the same as
# <tt>path0 + path1 + ... + pathN</tt>.
#
def join(*args)
args.unshift self
result = args.pop
result = Pathname.new(result) unless Pathname === result
return result if result.absolute?
args.reverse_each {|arg|
arg = Pathname.new(arg) unless Pathname === arg
result = arg + result
return result if result.absolute?
}
result
end
#
# Returns the children of the directory (files and subdirectories, not
# recursive) as an array of Pathname objects. By default, the returned
# pathnames will have enough information to access the files. If you set
# +with_directory+ to +false+, then the returned pathnames will contain the
# filename only.
#
# For example:
# pn = Pathname("/usr/lib/ruby/1.8")
# pn.children
# # -> [ Pathname:/usr/lib/ruby/1.8/English.rb,
# Pathname:/usr/lib/ruby/1.8/Env.rb,
# Pathname:/usr/lib/ruby/1.8/abbrev.rb, ... ]
# pn.children(false)
# # -> [ Pathname:English.rb, Pathname:Env.rb, Pathname:abbrev.rb, ... ]
#
# Note that the result never contain the entries <tt>.</tt> and <tt>..</tt> in
# the directory because they are not children.
#
# This method has existed since 1.8.1.
#
def children(with_directory=true)
with_directory = false if @path == '.'
result = []
Dir.foreach(@path) {|e|
next if e == '.' || e == '..'
if with_directory
result << self.class.new(File.join(@path, e))
else
result << self.class.new(e)
end
}
result
end
# Iterates over the children of the directory
# (files and subdirectories, not recursive).
# It yields Pathname object for each child.
# By default, the yielded pathnames will have enough information to access the files.
# If you set +with_directory+ to +false+, then the returned pathnames will contain the filename only.
#
# Pathname("/usr/local").each_child {|f| p f }
# #=> #<Pathname:/usr/local/share>
# # #<Pathname:/usr/local/bin>
# # #<Pathname:/usr/local/games>
# # #<Pathname:/usr/local/lib>
# # #<Pathname:/usr/local/include>
# # #<Pathname:/usr/local/sbin>
# # #<Pathname:/usr/local/src>
# # #<Pathname:/usr/local/man>
#
# Pathname("/usr/local").each_child(false) {|f| p f }
# #=> #<Pathname:share>
# # #<Pathname:bin>
# # #<Pathname:games>
# # #<Pathname:lib>
# # #<Pathname:include>
# # #<Pathname:sbin>
# # #<Pathname:src>
# # #<Pathname:man>
#
def each_child(with_directory=true, &b)
children(with_directory).each(&b)
end
#
# #relative_path_from returns a relative path from the argument to the
# receiver. If +self+ is absolute, the argument must be absolute too. If
# +self+ is relative, the argument must be relative too.
#
# #relative_path_from doesn't access the filesystem. It assumes no symlinks.
#
# ArgumentError is raised when it cannot find a relative path.
#
# This method has existed since 1.8.1.
#
def relative_path_from(base_directory)
dest_directory = self.cleanpath.to_s
base_directory = base_directory.cleanpath.to_s
dest_prefix = dest_directory
dest_names = []
while r = chop_basename(dest_prefix)
dest_prefix, basename = r
dest_names.unshift basename if basename != '.'
end
base_prefix = base_directory
base_names = []
while r = chop_basename(base_prefix)
base_prefix, basename = r
base_names.unshift basename if basename != '.'
end
unless SAME_PATHS[dest_prefix, base_prefix]
raise ArgumentError, "different prefix: #{dest_prefix.inspect} and #{base_directory.inspect}"
end
while !dest_names.empty? &&
!base_names.empty? &&
SAME_PATHS[dest_names.first, base_names.first]
dest_names.shift
base_names.shift
end
if base_names.include? '..'
raise ArgumentError, "base_directory has ..: #{base_directory.inspect}"
end
base_names.fill('..')
relpath_names = base_names + dest_names
if relpath_names.empty?
Pathname.new('.')
else
Pathname.new(File.join(*relpath_names))
end
end
end
class Pathname # * IO *
#
# #each_line iterates over the line in the file. It yields a String object
# for each line.
#
# This method has existed since 1.8.1.
#
def each_line(*args, &block) # :yield: line
IO.foreach(@path, *args, &block)
end
# See <tt>IO.read</tt>. Returns all data from the file, or the first +N+ bytes
# if specified.
def read(*args) IO.read(@path, *args) end
# See <tt>IO.binread</tt>. Returns all the bytes from the file, or the first +N+
# if specified.
def binread(*args) IO.binread(@path, *args) end
# See <tt>IO.readlines</tt>. Returns all the lines from the file.
def readlines(*args) IO.readlines(@path, *args) end
# See <tt>IO.sysopen</tt>.
def sysopen(*args) IO.sysopen(@path, *args) end
end
class Pathname # * File *
# See <tt>File.atime</tt>. Returns last access time.
def atime() File.atime(@path) end
# See <tt>File.ctime</tt>. Returns last (directory entry, not file) change time.
def ctime() File.ctime(@path) end
# See <tt>File.mtime</tt>. Returns last modification time.
def mtime() File.mtime(@path) end
# See <tt>File.chmod</tt>. Changes permissions.
def chmod(mode) File.chmod(mode, @path) end
# See <tt>File.lchmod</tt>.
def lchmod(mode) File.lchmod(mode, @path) end
# See <tt>File.chown</tt>. Change owner and group of file.
def chown(owner, group) File.chown(owner, group, @path) end
# See <tt>File.lchown</tt>.
def lchown(owner, group) File.lchown(owner, group, @path) end
# See <tt>File.fnmatch</tt>. Return +true+ if the receiver matches the given
# pattern.
def fnmatch(pattern, *args) File.fnmatch(pattern, @path, *args) end
# See <tt>File.fnmatch?</tt> (same as #fnmatch).
def fnmatch?(pattern, *args) File.fnmatch?(pattern, @path, *args) end
# See <tt>File.ftype</tt>. Returns "type" of file ("file", "directory",
# etc).
def ftype() File.ftype(@path) end
# See <tt>File.link</tt>. Creates a hard link.
def make_link(old) File.link(old, @path) end
# See <tt>File.open</tt>. Opens the file for reading or writing.
def open(*args, &block) # :yield: file
File.open(@path, *args, &block)
end
# See <tt>File.readlink</tt>. Read symbolic link.
def readlink() self.class.new(File.readlink(@path)) end
# See <tt>File.rename</tt>. Rename the file.
def rename(to) File.rename(@path, to) end
# See <tt>File.stat</tt>. Returns a <tt>File::Stat</tt> object.
def stat() File.stat(@path) end
# See <tt>File.lstat</tt>.
def lstat() File.lstat(@path) end
# See <tt>File.symlink</tt>. Creates a symbolic link.
def make_symlink(old) File.symlink(old, @path) end
# See <tt>File.truncate</tt>. Truncate the file to +length+ bytes.
def truncate(length) File.truncate(@path, length) end
# See <tt>File.utime</tt>. Update the access and modification times.
def utime(atime, mtime) File.utime(atime, mtime, @path) end
# See <tt>File.basename</tt>. Returns the last component of the path.
def basename(*args) self.class.new(File.basename(@path, *args)) end
# See <tt>File.dirname</tt>. Returns all but the last component of the path.
def dirname() self.class.new(File.dirname(@path)) end
# See <tt>File.extname</tt>. Returns the file's extension.
def extname() File.extname(@path) end
# See <tt>File.expand_path</tt>.
def expand_path(*args) self.class.new(File.expand_path(@path, *args)) end
# See <tt>File.split</tt>. Returns the #dirname and the #basename in an
# Array.
def split() File.split(@path).map {|f| self.class.new(f) } end
end
class Pathname # * FileTest *
# See <tt>FileTest.blockdev?</tt>.
def blockdev?() FileTest.blockdev?(@path) end
# See <tt>FileTest.chardev?</tt>.
def chardev?() FileTest.chardev?(@path) end
# See <tt>FileTest.executable?</tt>.
def executable?() FileTest.executable?(@path) end
# See <tt>FileTest.executable_real?</tt>.
def executable_real?() FileTest.executable_real?(@path) end
# See <tt>FileTest.exist?</tt>.
def exist?() FileTest.exist?(@path) end
# See <tt>FileTest.grpowned?</tt>.
def grpowned?() FileTest.grpowned?(@path) end
# See <tt>FileTest.directory?</tt>.
def directory?() FileTest.directory?(@path) end
# See <tt>FileTest.file?</tt>.
def file?() FileTest.file?(@path) end
# See <tt>FileTest.pipe?</tt>.
def pipe?() FileTest.pipe?(@path) end
# See <tt>FileTest.socket?</tt>.
def socket?() FileTest.socket?(@path) end
# See <tt>FileTest.owned?</tt>.
def owned?() FileTest.owned?(@path) end
# See <tt>FileTest.readable?</tt>.
def readable?() FileTest.readable?(@path) end
# See <tt>FileTest.world_readable?</tt>.
def world_readable?() FileTest.world_readable?(@path) end
# See <tt>FileTest.readable_real?</tt>.
def readable_real?() FileTest.readable_real?(@path) end
# See <tt>FileTest.setuid?</tt>.
def setuid?() FileTest.setuid?(@path) end
# See <tt>FileTest.setgid?</tt>.
def setgid?() FileTest.setgid?(@path) end
# See <tt>FileTest.size</tt>.
def size() FileTest.size(@path) end
# See <tt>FileTest.size?</tt>.
def size?() FileTest.size?(@path) end
# See <tt>FileTest.sticky?</tt>.
def sticky?() FileTest.sticky?(@path) end
# See <tt>FileTest.symlink?</tt>.
def symlink?() FileTest.symlink?(@path) end
# See <tt>FileTest.writable?</tt>.
def writable?() FileTest.writable?(@path) end
# See <tt>FileTest.world_writable?</tt>.
def world_writable?() FileTest.world_writable?(@path) end
# See <tt>FileTest.writable_real?</tt>.
def writable_real?() FileTest.writable_real?(@path) end
# See <tt>FileTest.zero?</tt>.
def zero?() FileTest.zero?(@path) end
end
class Pathname # * Dir *
# See <tt>Dir.glob</tt>. Returns or yields Pathname objects.
def Pathname.glob(*args) # :yield: pathname
if block_given?
Dir.glob(*args) {|f| yield self.new(f) }
else
Dir.glob(*args).map {|f| self.new(f) }
end
end
# See <tt>Dir.getwd</tt>. Returns the current working directory as a Pathname.
def Pathname.getwd() self.new(Dir.getwd) end
class << self; alias pwd getwd end
# Return the entries (files and subdirectories) in the directory, each as a
# Pathname object.
def entries() Dir.entries(@path).map {|f| self.class.new(f) } end
# Iterates over the entries (files and subdirectories) in the directory. It
# yields a Pathname object for each entry.
#
# This method has existed since 1.8.1.
def each_entry(&block) # :yield: pathname
Dir.foreach(@path) {|f| yield self.class.new(f) }
end
# See <tt>Dir.mkdir</tt>. Create the referenced directory.
def mkdir(*args) Dir.mkdir(@path, *args) end
# See <tt>Dir.rmdir</tt>. Remove the referenced directory.
def rmdir() Dir.rmdir(@path) end
# See <tt>Dir.open</tt>.
def opendir(&block) # :yield: dir
Dir.open(@path, &block)
end
end
class Pathname # * Find *
#
# Pathname#find is an iterator to traverse a directory tree in a depth first
# manner. It yields a Pathname for each file under "this" directory.
#
# Since it is implemented by <tt>find.rb</tt>, <tt>Find.prune</tt> can be used
# to control the traverse.
#
# If +self+ is <tt>.</tt>, yielded pathnames begin with a filename in the
# current directory, not <tt>./</tt>.
#
def find(&block) # :yield: pathname
require 'find'
if @path == '.'
Find.find(@path) {|f| yield self.class.new(f.sub(%r{\A\./}, '')) }
else
Find.find(@path) {|f| yield self.class.new(f) }
end
end
end
class Pathname # * FileUtils *
# See <tt>FileUtils.mkpath</tt>. Creates a full path, including any
# intermediate directories that don't yet exist.
def mkpath
require 'fileutils'
FileUtils.mkpath(@path)
nil
end
# See <tt>FileUtils.rm_r</tt>. Deletes a directory and all beneath it.
def rmtree
# The name "rmtree" is borrowed from File::Path of Perl.
# File::Path provides "mkpath" and "rmtree".
require 'fileutils'
FileUtils.rm_r(@path)
nil
end
end
class Pathname # * mixed *
# Removes a file or directory, using <tt>File.unlink</tt> or
# <tt>Dir.unlink</tt> as necessary.
def unlink()
begin
Dir.unlink @path
rescue Errno::ENOTDIR
File.unlink @path
end
end
alias delete unlink
end
class Pathname
undef =~
end
module Kernel
# create a pathname object.
#
# This method is available since 1.8.5.
def Pathname(path) # :doc:
Pathname.new(path)
end
private :Pathname
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/mkmf.rb | tools/jruby-1.5.1/lib/ruby/1.9/mkmf.rb | # module to create Makefile for extension modules
# invoke like: ruby -r mkmf extconf.rb
require 'rbconfig'
require 'fileutils'
require 'shellwords'
CONFIG = RbConfig::MAKEFILE_CONFIG
ORIG_LIBPATH = ENV['LIB']
CXX_EXT = %w[cc cxx cpp]
if File::FNM_SYSCASE.zero?
CXX_EXT.concat(%w[C])
end
SRC_EXT = %w[c m].concat(CXX_EXT)
$static = nil
$config_h = '$(arch_hdrdir)/ruby/config.h'
$default_static = $static
unless defined? $configure_args
$configure_args = {}
args = CONFIG["configure_args"]
if ENV["CONFIGURE_ARGS"]
args << " " << ENV["CONFIGURE_ARGS"]
end
for arg in Shellwords::shellwords(args)
arg, val = arg.split('=', 2)
next unless arg
arg.tr!('_', '-')
if arg.sub!(/^(?!--)/, '--')
val or next
arg.downcase!
end
next if /^--(?:top|topsrc|src|cur)dir$/ =~ arg
$configure_args[arg] = val || true
end
for arg in ARGV
arg, val = arg.split('=', 2)
next unless arg
arg.tr!('_', '-')
if arg.sub!(/^(?!--)/, '--')
val or next
arg.downcase!
end
$configure_args[arg] = val || true
end
end
$libdir = CONFIG["libdir"]
$rubylibdir = CONFIG["rubylibdir"]
$archdir = CONFIG["archdir"]
$sitedir = CONFIG["sitedir"]
$sitelibdir = CONFIG["sitelibdir"]
$sitearchdir = CONFIG["sitearchdir"]
$vendordir = CONFIG["vendordir"]
$vendorlibdir = CONFIG["vendorlibdir"]
$vendorarchdir = CONFIG["vendorarchdir"]
$mswin = /mswin/ =~ RUBY_PLATFORM
$bccwin = /bccwin/ =~ RUBY_PLATFORM
$mingw = /mingw/ =~ RUBY_PLATFORM
$cygwin = /cygwin/ =~ RUBY_PLATFORM
$netbsd = /netbsd/ =~ RUBY_PLATFORM
$os2 = /os2/ =~ RUBY_PLATFORM
$beos = /beos/ =~ RUBY_PLATFORM
$haiku = /haiku/ =~ RUBY_PLATFORM
$solaris = /solaris/ =~ RUBY_PLATFORM
$universal = /universal/ =~ RUBY_PLATFORM
$dest_prefix_pattern = (File::PATH_SEPARATOR == ';' ? /\A([[:alpha:]]:)?/ : /\A/)
# :stopdoc:
def config_string(key, config = CONFIG)
s = config[key] and !s.empty? and block_given? ? yield(s) : s
end
def dir_re(dir)
Regexp.new('\$(?:\('+dir+'\)|\{'+dir+'\})(?:\$(?:\(target_prefix\)|\{target_prefix\}))?')
end
def relative_from(path, base)
dir = File.join(path, "")
if File.expand_path(dir) == File.expand_path(dir, base)
path
else
File.join(base, path)
end
end
INSTALL_DIRS = [
[dir_re('commondir'), "$(RUBYCOMMONDIR)"],
[dir_re('sitedir'), "$(RUBYCOMMONDIR)"],
[dir_re('vendordir'), "$(RUBYCOMMONDIR)"],
[dir_re('rubylibdir'), "$(RUBYLIBDIR)"],
[dir_re('archdir'), "$(RUBYARCHDIR)"],
[dir_re('sitelibdir'), "$(RUBYLIBDIR)"],
[dir_re('vendorlibdir'), "$(RUBYLIBDIR)"],
[dir_re('sitearchdir'), "$(RUBYARCHDIR)"],
[dir_re('vendorarchdir'), "$(RUBYARCHDIR)"],
[dir_re('rubyhdrdir'), "$(RUBYHDRDIR)"],
[dir_re('sitehdrdir'), "$(SITEHDRDIR)"],
[dir_re('vendorhdrdir'), "$(VENDORHDRDIR)"],
[dir_re('bindir'), "$(BINDIR)"],
]
def install_dirs(target_prefix = nil)
if $extout
dirs = [
['BINDIR', '$(extout)/bin'],
['RUBYCOMMONDIR', '$(extout)/common'],
['RUBYLIBDIR', '$(RUBYCOMMONDIR)$(target_prefix)'],
['RUBYARCHDIR', '$(extout)/$(arch)$(target_prefix)'],
['HDRDIR', '$(extout)/include/ruby$(target_prefix)'],
['ARCHHDRDIR', '$(extout)/include/$(arch)/ruby$(target_prefix)'],
['extout', "#$extout"],
['extout_prefix', "#$extout_prefix"],
]
elsif $extmk
dirs = [
['BINDIR', '$(bindir)'],
['RUBYCOMMONDIR', '$(rubylibdir)'],
['RUBYLIBDIR', '$(rubylibdir)$(target_prefix)'],
['RUBYARCHDIR', '$(archdir)$(target_prefix)'],
['HDRDIR', '$(rubyhdrdir)/ruby$(target_prefix)'],
['ARCHHDRDIR', '$(rubyhdrdir)/$(arch)/ruby$(target_prefix)'],
]
elsif $configure_args.has_key?('--vendor')
dirs = [
['BINDIR', '$(bindir)'],
['RUBYCOMMONDIR', '$(vendordir)$(target_prefix)'],
['RUBYLIBDIR', '$(vendorlibdir)$(target_prefix)'],
['RUBYARCHDIR', '$(vendorarchdir)$(target_prefix)'],
['HDRDIR', '$(rubyhdrdir)/ruby$(target_prefix)'],
['ARCHHDRDIR', '$(rubyhdrdir)/$(arch)/ruby$(target_prefix)'],
]
else
dirs = [
['BINDIR', '$(bindir)'],
['RUBYCOMMONDIR', '$(sitedir)$(target_prefix)'],
['RUBYLIBDIR', '$(sitelibdir)$(target_prefix)'],
['RUBYARCHDIR', '$(sitearchdir)$(target_prefix)'],
['HDRDIR', '$(rubyhdrdir)/ruby$(target_prefix)'],
['ARCHHDRDIR', '$(rubyhdrdir)/$(arch)/ruby$(target_prefix)'],
]
end
dirs << ['target_prefix', (target_prefix ? "/#{target_prefix}" : "")]
dirs
end
def map_dir(dir, map = nil)
map ||= INSTALL_DIRS
map.inject(dir) {|d, (orig, new)| d.gsub(orig, new)}
end
topdir = File.dirname(libdir = File.dirname(__FILE__))
extdir = File.expand_path("ext", topdir)
path = File.expand_path($0)
$extmk = path[0, topdir.size+1] == topdir+"/"
$extmk &&= %r"\A(?:ext|enc|tool|test(?:/.+))\z" =~ File.dirname(path[topdir.size+1..-1])
$extmk &&= true
if not $extmk and File.exist?(($hdrdir = RbConfig::CONFIG["rubyhdrdir"]) + "/ruby/ruby.h")
$topdir = $hdrdir
$top_srcdir = $hdrdir
$arch_hdrdir = $hdrdir + "/$(arch)"
elsif File.exist?(($hdrdir = ($top_srcdir ||= topdir) + "/include") + "/ruby.h")
$topdir ||= RbConfig::CONFIG["topdir"]
$arch_hdrdir = "$(extout)/include/$(arch)"
else
abort "mkmf.rb can't find header files for ruby at #{$hdrdir}/ruby.h"
end
OUTFLAG = CONFIG['OUTFLAG']
COUTFLAG = CONFIG['COUTFLAG']
CPPOUTFILE = CONFIG['CPPOUTFILE']
CONFTEST_C = "conftest.c".freeze
class String
# Wraps a string in escaped quotes if it contains whitespace.
def quote
/\s/ =~ self ? "\"#{self}\"" : "#{self}"
end
# Generates a string used as cpp macro name.
def tr_cpp
strip.upcase.tr_s("^A-Z0-9_", "_")
end
end
class Array
# Wraps all strings in escaped quotes if they contain whitespace.
def quote
map {|s| s.quote}
end
end
def rm_f(*files)
opt = ([files.pop] if Hash === files.last)
FileUtils.rm_f(Dir[*files], *opt)
end
def rm_rf(*files)
opt = ([files.pop] if Hash === files.last)
FileUtils.rm_rf(Dir[*files], *opt)
end
# Returns time stamp of the +target+ file if it exists and is newer
# than or equal to all of +times+.
def modified?(target, times)
(t = File.mtime(target)) rescue return nil
Array === times or times = [times]
t if times.all? {|n| n <= t}
end
def merge_libs(*libs)
libs.inject([]) do |x, y|
xy = x & y
xn = yn = 0
y = y.inject([]) {|ary, e| ary.last == e ? ary : ary << e}
y.each_with_index do |v, yi|
if xy.include?(v)
xi = [x.index(v), xn].max()
x[xi, 1] = y[yn..yi]
xn, yn = xi + (yi - yn + 1), yi + 1
end
end
x.concat(y[yn..-1] || [])
end
end
# This is a custom logging module. It generates an mkmf.log file when you
# run your extconf.rb script. This can be useful for debugging unexpected
# failures.
#
# This module and its associated methods are meant for internal use only.
#
module Logging
@log = nil
@logfile = 'mkmf.log'
@orgerr = $stderr.dup
@orgout = $stdout.dup
@postpone = 0
@quiet = $extmk
def self::log_open
@log ||= File::open(@logfile, 'wb')
@log.sync = true
end
def self::open
log_open
$stderr.reopen(@log)
$stdout.reopen(@log)
yield
ensure
$stderr.reopen(@orgerr)
$stdout.reopen(@orgout)
end
def self::message(*s)
log_open
@log.printf(*s)
end
def self::logfile file
@logfile = file
if @log and not @log.closed?
@log.flush
@log.close
@log = nil
end
end
def self::postpone
tmplog = "mkmftmp#{@postpone += 1}.log"
open do
log, *save = @log, @logfile, @orgout, @orgerr
@log, @logfile, @orgout, @orgerr = nil, tmplog, log, log
begin
log.print(open {yield})
ensure
@log.close
File::open(tmplog) {|t| FileUtils.copy_stream(t, log)}
@log, @logfile, @orgout, @orgerr = log, *save
@postpone -= 1
rm_f tmplog
end
end
end
class << self
attr_accessor :quiet
end
end
def xsystem command
varpat = /\$\((\w+)\)|\$\{(\w+)\}/
if varpat =~ command
vars = Hash.new {|h, k| h[k] = ''; ENV[k]}
command = command.dup
nil while command.gsub!(varpat) {vars[$1||$2]}
end
Logging::open do
puts command.quote
system(command)
end
end
def xpopen command, *mode, &block
Logging::open do
case mode[0]
when nil, /^r/
puts "#{command} |"
else
puts "| #{command}"
end
IO.popen(command, *mode, &block)
end
end
def log_src(src)
src = src.split(/^/)
fmt = "%#{src.size.to_s.size}d: %s"
Logging::message <<"EOM"
checked program was:
/* begin */
EOM
src.each_with_index {|line, no| Logging::message fmt, no+1, line}
Logging::message <<"EOM"
/* end */
EOM
end
def create_tmpsrc(src)
src = "#{COMMON_HEADERS}\n#{src}"
src = yield(src) if block_given?
src.gsub!(/[ \t]+$/, '')
src.gsub!(/\A\n+|^\n+$/, '')
src.sub!(/[^\n]\z/, "\\&\n")
count = 0
begin
open(CONFTEST_C, "wb") do |cfile|
cfile.print src
end
rescue Errno::EACCES
if (count += 1) < 5
sleep 0.2
retry
end
end
src
end
def have_devel?
unless defined? $have_devel
$have_devel = true
$have_devel = try_link(MAIN_DOES_NOTHING)
end
$have_devel
end
def try_do(src, command, &b)
unless have_devel?
raise <<MSG
The complier failed to generate an executable file.
You have to install development tools first.
MSG
end
src = create_tmpsrc(src, &b)
xsystem(command)
ensure
log_src(src)
rm_rf 'conftest.dSYM'
end
def link_command(ldflags, opt="", libpath=$DEFLIBPATH|$LIBPATH)
conf = RbConfig::CONFIG.merge('hdrdir' => $hdrdir.quote,
'src' => "#{CONFTEST_C}",
'arch_hdrdir' => "#$arch_hdrdir",
'top_srcdir' => $top_srcdir.quote,
'INCFLAGS' => "#$INCFLAGS",
'CPPFLAGS' => "#$CPPFLAGS",
'CFLAGS' => "#$CFLAGS",
'ARCH_FLAG' => "#$ARCH_FLAG",
'LDFLAGS' => "#$LDFLAGS #{ldflags}",
'LIBPATH' => libpathflag(libpath),
'LOCAL_LIBS' => "#$LOCAL_LIBS #$libs",
'LIBS' => "#$LIBRUBYARG_STATIC #{opt} #$LIBS")
RbConfig::expand(TRY_LINK.dup, conf)
end
def cc_command(opt="")
conf = RbConfig::CONFIG.merge('hdrdir' => $hdrdir.quote, 'srcdir' => $srcdir.quote,
'arch_hdrdir' => "#$arch_hdrdir",
'top_srcdir' => $top_srcdir.quote)
RbConfig::expand("$(CC) #$INCFLAGS #$CPPFLAGS #$CFLAGS #$ARCH_FLAG #{opt} -c #{CONFTEST_C}",
conf)
end
def cpp_command(outfile, opt="")
conf = RbConfig::CONFIG.merge('hdrdir' => $hdrdir.quote, 'srcdir' => $srcdir.quote,
'arch_hdrdir' => "#$arch_hdrdir",
'top_srcdir' => $top_srcdir.quote)
RbConfig::expand("$(CPP) #$INCFLAGS #$CPPFLAGS #$CFLAGS #{opt} #{CONFTEST_C} #{outfile}",
conf)
end
def libpathflag(libpath=$DEFLIBPATH|$LIBPATH)
libpath.map{|x|
case x
when "$(topdir)", /\A\./
LIBPATHFLAG
else
LIBPATHFLAG+RPATHFLAG
end % x.quote
}.join
end
def try_link0(src, opt="", &b)
cmd = link_command("", opt)
if $universal
require 'tmpdir'
Dir.mktmpdir("mkmf_", oldtmpdir = ENV["TMPDIR"]) do |tmpdir|
begin
ENV["TMPDIR"] = tmpdir
try_do(src, cmd, &b)
ensure
ENV["TMPDIR"] = oldtmpdir
end
end
else
try_do(src, cmd, &b)
end
end
def try_link(src, opt="", &b)
try_link0(src, opt, &b)
ensure
rm_f "conftest*", "c0x32*"
end
def try_compile(src, opt="", &b)
try_do(src, cc_command(opt), &b)
ensure
rm_f "conftest*"
end
def try_cpp(src, opt="", &b)
try_do(src, cpp_command(CPPOUTFILE, opt), &b)
ensure
rm_f "conftest*"
end
class Object
alias_method :try_header, (config_string('try_header') || :try_cpp)
end
def cpp_include(header)
if header
header = [header] unless header.kind_of? Array
header.map {|h| String === h ? "#include <#{h}>\n" : h}.join
else
""
end
end
def with_cppflags(flags)
cppflags = $CPPFLAGS
$CPPFLAGS = flags
ret = yield
ensure
$CPPFLAGS = cppflags unless ret
end
def with_cflags(flags)
cflags = $CFLAGS
$CFLAGS = flags
ret = yield
ensure
$CFLAGS = cflags unless ret
end
def with_ldflags(flags)
ldflags = $LDFLAGS
$LDFLAGS = flags
ret = yield
ensure
$LDFLAGS = ldflags unless ret
end
def try_static_assert(expr, headers = nil, opt = "", &b)
headers = cpp_include(headers)
try_compile(<<SRC, opt, &b)
#{headers}
/*top*/
int conftest_const[(#{expr}) ? 1 : -1];
SRC
end
def try_constant(const, headers = nil, opt = "", &b)
includes = cpp_include(headers)
if CROSS_COMPILING
if try_static_assert("#{const} > 0", headers, opt)
# positive constant
elsif try_static_assert("#{const} < 0", headers, opt)
neg = true
const = "-(#{const})"
elsif try_static_assert("#{const} == 0", headers, opt)
return 0
else
# not a constant
return nil
end
upper = 1
lower = 0
until try_static_assert("#{const} <= #{upper}", headers, opt)
lower = upper
upper <<= 1
end
return nil unless lower
while upper > lower + 1
mid = (upper + lower) / 2
if try_static_assert("#{const} > #{mid}", headers, opt)
lower = mid
else
upper = mid
end
end
upper = -upper if neg
return upper
else
src = %{#{includes}
#include <stdio.h>
/*top*/
int conftest_const = (int)(#{const});
int main() {printf("%d\\n", conftest_const); return 0;}
}
if try_link0(src, opt, &b)
xpopen("./conftest") do |f|
return Integer(f.gets)
end
end
end
nil
end
def try_func(func, libs, headers = nil, &b)
headers = cpp_include(headers)
try_link(<<"SRC", libs, &b) or
#{headers}
/*top*/
#{MAIN_DOES_NOTHING}
int t() { void ((*volatile p)()); p = (void ((*)()))#{func}; return 0; }
SRC
try_link(<<"SRC", libs, &b)
#{headers}
/*top*/
#{MAIN_DOES_NOTHING}
int t() { #{func}(); return 0; }
SRC
end
def try_var(var, headers = nil, &b)
headers = cpp_include(headers)
try_compile(<<"SRC", &b)
#{headers}
/*top*/
#{MAIN_DOES_NOTHING}
int t() { const volatile void *volatile p; p = &(&#{var})[0]; return 0; }
SRC
end
def egrep_cpp(pat, src, opt = "", &b)
src = create_tmpsrc(src, &b)
xpopen(cpp_command('', opt)) do |f|
if Regexp === pat
puts(" ruby -ne 'print if #{pat.inspect}'")
f.grep(pat) {|l|
puts "#{f.lineno}: #{l}"
return true
}
false
else
puts(" egrep '#{pat}'")
begin
stdin = $stdin.dup
$stdin.reopen(f)
system("egrep", pat)
ensure
$stdin.reopen(stdin)
end
end
end
ensure
rm_f "conftest*"
log_src(src)
end
# This is used internally by the have_macro? method.
def macro_defined?(macro, src, opt = "", &b)
src = src.sub(/[^\n]\z/, "\\&\n")
try_compile(src + <<"SRC", opt, &b)
/*top*/
#ifndef #{macro}
# error
>>>>>> #{macro} undefined <<<<<<
#endif
SRC
end
def try_run(src, opt = "", &b)
if try_link0(src, opt, &b)
xsystem("./conftest")
else
nil
end
ensure
rm_f "conftest*"
end
def install_files(mfile, ifiles, map = nil, srcprefix = nil)
ifiles or return
ifiles.empty? and return
srcprefix ||= '$(srcdir)'
RbConfig::expand(srcdir = srcprefix.dup)
dirs = []
path = Hash.new {|h, i| h[i] = dirs.push([i])[-1]}
ifiles.each do |files, dir, prefix|
dir = map_dir(dir, map)
prefix &&= %r|\A#{Regexp.quote(prefix)}/?|
if /\A\.\// =~ files
# install files which are in current working directory.
files = files[2..-1]
len = nil
else
# install files which are under the $(srcdir).
files = File.join(srcdir, files)
len = srcdir.size
end
f = nil
Dir.glob(files) do |fx|
f = fx
f[0..len] = "" if len
case File.basename(f)
when *$NONINSTALLFILES
next
end
d = File.dirname(f)
d.sub!(prefix, "") if prefix
d = (d.empty? || d == ".") ? dir : File.join(dir, d)
f = File.join(srcprefix, f) if len
path[d] << f
end
unless len or f
d = File.dirname(files)
d.sub!(prefix, "") if prefix
d = (d.empty? || d == ".") ? dir : File.join(dir, d)
path[d] << files
end
end
dirs
end
def install_rb(mfile, dest, srcdir = nil)
install_files(mfile, [["lib/**/*.rb", dest, "lib"]], nil, srcdir)
end
def append_library(libs, lib) # :no-doc:
format(LIBARG, lib) + " " + libs
end
def message(*s)
unless Logging.quiet and not $VERBOSE
printf(*s)
$stdout.flush
end
end
# This emits a string to stdout that allows users to see the results of the
# various have* and find* methods as they are tested.
#
# Internal use only.
#
def checking_for(m, fmt = nil)
f = caller[0][/in `(.*)'$/, 1] and f << ": " #` for vim #'
m = "checking #{/\Acheck/ =~ f ? '' : 'for '}#{m}... "
message "%s", m
a = r = nil
Logging::postpone do
r = yield
a = (fmt ? fmt % r : r ? "yes" : "no") << "\n"
"#{f}#{m}-------------------- #{a}\n"
end
message(a)
Logging::message "--------------------\n\n"
r
end
def checking_message(target, place = nil, opt = nil)
[["in", place], ["with", opt]].inject("#{target}") do |msg, (pre, noun)|
if noun
[[:to_str], [:join, ","], [:to_s]].each do |meth, *args|
if noun.respond_to?(meth)
break noun = noun.send(meth, *args)
end
end
msg << " #{pre} #{noun}" unless noun.empty?
end
msg
end
end
# :startdoc:
# Returns whether or not +macro+ is defined either in the common header
# files or within any +headers+ you provide.
#
# Any options you pass to +opt+ are passed along to the compiler.
#
def have_macro(macro, headers = nil, opt = "", &b)
checking_for checking_message(macro, headers, opt) do
macro_defined?(macro, cpp_include(headers), opt, &b)
end
end
# Returns whether or not the given entry point +func+ can be found within
# +lib+. If +func+ is nil, the 'main()' entry point is used by default.
# If found, it adds the library to list of libraries to be used when linking
# your extension.
#
# If +headers+ are provided, it will include those header files as the
# header files it looks in when searching for +func+.
#
# The real name of the library to be linked can be altered by
# '--with-FOOlib' configuration option.
#
def have_library(lib, func = nil, headers = nil, &b)
func = "main" if !func or func.empty?
lib = with_config(lib+'lib', lib)
checking_for checking_message("#{func}()", LIBARG%lib) do
if COMMON_LIBS.include?(lib)
true
else
libs = append_library($libs, lib)
if try_func(func, libs, headers, &b)
$libs = libs
true
else
false
end
end
end
end
# Returns whether or not the entry point +func+ can be found within the library
# +lib+ in one of the +paths+ specified, where +paths+ is an array of strings.
# If +func+ is nil , then the main() function is used as the entry point.
#
# If +lib+ is found, then the path it was found on is added to the list of
# library paths searched and linked against.
#
def find_library(lib, func, *paths, &b)
func = "main" if !func or func.empty?
lib = with_config(lib+'lib', lib)
paths = paths.collect {|path| path.split(File::PATH_SEPARATOR)}.flatten
checking_for "#{func}() in #{LIBARG%lib}" do
libpath = $LIBPATH
libs = append_library($libs, lib)
begin
until r = try_func(func, libs, &b) or paths.empty?
$LIBPATH = libpath | [paths.shift]
end
if r
$libs = libs
libpath = nil
end
ensure
$LIBPATH = libpath if libpath
end
r
end
end
# Returns whether or not the function +func+ can be found in the common
# header files, or within any +headers+ that you provide. If found, a
# macro is passed as a preprocessor constant to the compiler using the
# function name, in uppercase, prepended with 'HAVE_'.
#
# For example, if have_func('foo') returned true, then the HAVE_FOO
# preprocessor macro would be passed to the compiler.
#
def have_func(func, headers = nil, &b)
checking_for checking_message("#{func}()", headers) do
if try_func(func, $libs, headers, &b)
$defs.push(format("-DHAVE_%s", func.tr_cpp))
true
else
false
end
end
end
# Returns whether or not the variable +var+ can be found in the common
# header files, or within any +headers+ that you provide. If found, a
# macro is passed as a preprocessor constant to the compiler using the
# variable name, in uppercase, prepended with 'HAVE_'.
#
# For example, if have_var('foo') returned true, then the HAVE_FOO
# preprocessor macro would be passed to the compiler.
#
def have_var(var, headers = nil, &b)
checking_for checking_message(var, headers) do
if try_var(var, headers, &b)
$defs.push(format("-DHAVE_%s", var.tr_cpp))
true
else
false
end
end
end
# Returns whether or not the given +header+ file can be found on your system.
# If found, a macro is passed as a preprocessor constant to the compiler using
# the header file name, in uppercase, prepended with 'HAVE_'.
#
# For example, if have_header('foo.h') returned true, then the HAVE_FOO_H
# preprocessor macro would be passed to the compiler.
#
def have_header(header, preheaders = nil, &b)
checking_for header do
if try_header(cpp_include(preheaders)+cpp_include(header), &b)
$defs.push(format("-DHAVE_%s", header.tr("a-z./\055", "A-Z___")))
true
else
false
end
end
end
# Instructs mkmf to search for the given +header+ in any of the +paths+
# provided, and returns whether or not it was found in those paths.
#
# If the header is found then the path it was found on is added to the list
# of included directories that are sent to the compiler (via the -I switch).
#
def find_header(header, *paths)
message = checking_message(header, paths)
header = cpp_include(header)
checking_for message do
if try_header(header)
true
else
found = false
paths.each do |dir|
opt = "-I#{dir}".quote
if try_header(header, opt)
$INCFLAGS << " " << opt
found = true
break
end
end
found
end
end
end
# Returns whether or not the struct of type +type+ contains +member+. If
# it does not, or the struct type can't be found, then false is returned. You
# may optionally specify additional +headers+ in which to look for the struct
# (in addition to the common header files).
#
# If found, a macro is passed as a preprocessor constant to the compiler using
# the type name and the member name, in uppercase, prepended with 'HAVE_'.
#
# For example, if have_struct_member('struct foo', 'bar') returned true, then the
# HAVE_STRUCT_FOO_BAR preprocessor macro would be passed to the compiler.
#
# HAVE_ST_BAR is also defined for backward compatibility.
#
def have_struct_member(type, member, headers = nil, &b)
checking_for checking_message("#{type}.#{member}", headers) do
if try_compile(<<"SRC", &b)
#{cpp_include(headers)}
/*top*/
#{MAIN_DOES_NOTHING}
int s = (char *)&((#{type}*)0)->#{member} - (char *)0;
SRC
$defs.push(format("-DHAVE_%s_%s", type.tr_cpp, member.tr_cpp))
$defs.push(format("-DHAVE_ST_%s", member.tr_cpp)) # backward compatibility
true
else
false
end
end
end
def try_type(type, headers = nil, opt = "", &b)
if try_compile(<<"SRC", opt, &b)
#{cpp_include(headers)}
/*top*/
typedef #{type} conftest_type;
int conftestval[sizeof(conftest_type)?1:-1];
SRC
$defs.push(format("-DHAVE_TYPE_%s", type.tr_cpp))
true
else
false
end
end
# Returns whether or not the static type +type+ is defined. You may
# optionally pass additional +headers+ to check against in addition to the
# common header files.
#
# You may also pass additional flags to +opt+ which are then passed along to
# the compiler.
#
# If found, a macro is passed as a preprocessor constant to the compiler using
# the type name, in uppercase, prepended with 'HAVE_TYPE_'.
#
# For example, if have_type('foo') returned true, then the HAVE_TYPE_FOO
# preprocessor macro would be passed to the compiler.
#
def have_type(type, headers = nil, opt = "", &b)
checking_for checking_message(type, headers, opt) do
try_type(type, headers, opt, &b)
end
end
# Returns where the static type +type+ is defined.
#
# You may also pass additional flags to +opt+ which are then passed along to
# the compiler.
#
# See also +have_type+.
#
def find_type(type, opt, *headers, &b)
opt ||= ""
fmt = "not found"
def fmt.%(x)
x ? x.respond_to?(:join) ? x.join(",") : x : self
end
checking_for checking_message(type, nil, opt), fmt do
headers.find do |h|
try_type(type, h, opt, &b)
end
end
end
def try_const(const, headers = nil, opt = "", &b)
const, type = *const
if try_compile(<<"SRC", opt, &b)
#{cpp_include(headers)}
/*top*/
typedef #{type || 'int'} conftest_type;
conftest_type conftestval = #{type ? '' : '(int)'}#{const};
SRC
$defs.push(format("-DHAVE_CONST_%s", const.tr_cpp))
true
else
false
end
end
# Returns whether or not the constant +const+ is defined. You may
# optionally pass the +type+ of +const+ as <code>[const, type]</code>,
# like as:
#
# have_const(%w[PTHREAD_MUTEX_INITIALIZER pthread_mutex_t], "pthread.h")
#
# You may also pass additional +headers+ to check against in addition
# to the common header files, and additional flags to +opt+ which are
# then passed along to the compiler.
#
# If found, a macro is passed as a preprocessor constant to the compiler using
# the type name, in uppercase, prepended with 'HAVE_CONST_'.
#
# For example, if have_const('foo') returned true, then the HAVE_CONST_FOO
# preprocessor macro would be passed to the compiler.
#
def have_const(const, headers = nil, opt = "", &b)
checking_for checking_message([*const].compact.join(' '), headers, opt) do
try_const(const, headers, opt, &b)
end
end
# Returns the size of the given +type+. You may optionally specify additional
# +headers+ to search in for the +type+.
#
# If found, a macro is passed as a preprocessor constant to the compiler using
# the type name, in uppercase, prepended with 'SIZEOF_', followed by the type
# name, followed by '=X' where 'X' is the actual size.
#
# For example, if check_sizeof('mystruct') returned 12, then the
# SIZEOF_MYSTRUCT=12 preprocessor macro would be passed to the compiler.
#
def check_sizeof(type, headers = nil, opts = "", &b)
typename, member = type.split('.', 2)
prelude = cpp_include(headers).split(/$/)
prelude << "typedef #{typename} rbcv_typedef_;\n"
prelude << "static rbcv_typedef_ *rbcv_ptr_;\n"
prelude = [prelude]
expr = "sizeof((*rbcv_ptr_)#{"." << member if member})"
fmt = "%s"
def fmt.%(x)
x ? super : "failed"
end
checking_for checking_message("size of #{type}", headers), fmt do
if UNIVERSAL_INTS.include?(type)
type
elsif size = UNIVERSAL_INTS.find {|t|
try_static_assert("#{expr} == sizeof(#{t})", prelude, opts, &b)
}
$defs.push(format("-DSIZEOF_%s=SIZEOF_%s", type.tr_cpp, size.tr_cpp))
size
elsif size = try_constant(expr, prelude, opts, &b)
$defs.push(format("-DSIZEOF_%s=%s", type.tr_cpp, size))
size
end
end
end
# :stopdoc:
# Used internally by the what_type? method to determine if +type+ is a scalar
# pointer.
def scalar_ptr_type?(type, member = nil, headers = nil, &b)
try_compile(<<"SRC", &b) # pointer
#{cpp_include(headers)}
/*top*/
volatile #{type} conftestval;
#{MAIN_DOES_NOTHING}
int t() {return (int)(1-*(conftestval#{member ? ".#{member}" : ""}));}
SRC
end
# Used internally by the what_type? method to determine if +type+ is a scalar
# pointer.
def scalar_type?(type, member = nil, headers = nil, &b)
try_compile(<<"SRC", &b) # pointer
#{cpp_include(headers)}
/*top*/
volatile #{type} conftestval;
#{MAIN_DOES_NOTHING}
int t() {return (int)(1-(conftestval#{member ? ".#{member}" : ""}));}
SRC
end
# Used internally by the what_type? method to check if _typeof_ GCC
# extension is available.
def have_typeof?
return $typeof if defined?($typeof)
$typeof = %w[__typeof__ typeof].find do |t|
try_compile(<<SRC)
int rbcv_foo;
#{t}(rbcv_foo) rbcv_bar;
SRC
end
end
def what_type?(type, member = nil, headers = nil, &b)
m = "#{type}"
var = val = "*rbcv_var_"
func = "rbcv_func_(void)"
if member
m << "." << member
else
type, member = type.split('.', 2)
end
if member
val = "(#{var}).#{member}"
end
prelude = [cpp_include(headers).split(/^/)]
prelude << ["typedef #{type} rbcv_typedef_;\n",
"extern rbcv_typedef_ *#{func};\n",
"static rbcv_typedef_ #{var};\n",
]
type = "rbcv_typedef_"
fmt = member && !(typeof = have_typeof?) ? "seems %s" : "%s"
if typeof
var = "*rbcv_member_"
func = "rbcv_mem_func_(void)"
member = nil
type = "rbcv_mem_typedef_"
prelude[-1] << "typedef #{typeof}(#{val}) #{type};\n"
prelude[-1] << "extern #{type} *#{func};\n"
prelude[-1] << "static #{type} #{var};\n"
val = var
end
def fmt.%(x)
x ? super : "unknown"
end
checking_for checking_message(m, headers), fmt do
if scalar_ptr_type?(type, member, prelude, &b)
if try_static_assert("sizeof(*#{var}) == 1", prelude)
return "string"
end
ptr = "*"
elsif scalar_type?(type, member, prelude, &b)
unless member and !typeof or try_static_assert("(#{type})-1 < 0", prelude)
unsigned = "unsigned"
end
ptr = ""
else
next
end
type = UNIVERSAL_INTS.find do |t|
pre = prelude
unless member
pre += [["static #{unsigned} #{t} #{ptr}#{var};\n",
"extern #{unsigned} #{t} #{ptr}*#{func};\n"]]
end
try_static_assert("sizeof(#{ptr}#{val}) == sizeof(#{unsigned} #{t})", pre)
end
type or next
[unsigned, type, ptr].join(" ").strip
end
end
# This method is used internally by the find_executable method.
#
# Internal use only.
#
def find_executable0(bin, path = nil)
ext = config_string('EXEEXT')
if File.expand_path(bin) == bin
return bin if File.executable?(bin)
ext and File.executable?(file = bin + ext) and return file
return nil
end
if path ||= ENV['PATH']
path = path.split(File::PATH_SEPARATOR)
else
path = %w[/usr/local/bin /usr/ucb /usr/bin /bin]
end
file = nil
path.each do |dir|
return file if File.executable?(file = File.join(dir, bin))
return file if ext and File.executable?(file << ext)
end
nil
end
# :startdoc:
# Searches for the executable +bin+ on +path+. The default path is your
# PATH environment variable. If that isn't defined, it will resort to
# searching /usr/local/bin, /usr/ucb, /usr/bin and /bin.
#
# If found, it will return the full path, including the executable name,
# of where it was found.
#
# Note that this method does not actually affect the generated Makefile.
#
def find_executable(bin, path = nil)
checking_for checking_message(bin, path) do
find_executable0(bin, path)
end
end
# :stopdoc:
def arg_config(config, default=nil, &block)
$arg_config << [config, default]
defaults = []
if default
defaults << default
elsif !block
defaults << nil
end
$configure_args.fetch(config.tr('_', '-'), *defaults, &block)
end
# :startdoc:
# Tests for the presence of a --with-<tt>config</tt> or --without-<tt>config</tt>
# option. Returns true if the with option is given, false if the without
# option is given, and the default value otherwise.
#
# This can be useful for adding custom definitions, such as debug information.
#
# Example:
#
# if with_config("debug")
# $defs.push("-DOSSL_DEBUG") unless $defs.include? "-DOSSL_DEBUG"
# end
#
def with_config(config, default=nil)
config = config.sub(/^--with[-_]/, '')
val = arg_config("--with-"+config) do
if arg_config("--without-"+config)
false
elsif block_given?
yield(config, default)
else
break default
end
end
case val
when "yes"
true
when "no"
false
else
val
end
end
# Tests for the presence of an --enable-<tt>config</tt> or
# --disable-<tt>config</tt> option. Returns true if the enable option is given,
# false if the disable option is given, and the default value otherwise.
#
# This can be useful for adding custom definitions, such as debug information.
#
# Example:
#
# if enable_config("debug")
| 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/pstore.rb | tools/jruby-1.5.1/lib/ruby/1.9/pstore.rb | # = PStore -- Transactional File Storage for Ruby Objects
#
# pstore.rb -
# originally by matz
# documentation by Kev Jackson and James Edward Gray II
# improved by Hongli Lai
#
# See PStore for documentation.
require "fileutils"
require "digest/md5"
require "thread"
#
# PStore implements a file based persistence mechanism based on a Hash. User
# code can store hierarchies of Ruby objects (values) into the data store file
# by name (keys). An object hierarchy may be just a single object. User code
# may later read values back from the data store or even update data, as needed.
#
# The transactional behavior ensures that any changes succeed or fail together.
# This can be used to ensure that the data store is not left in a transitory
# state, where some values were updated but others were not.
#
# Behind the scenes, Ruby objects are stored to the data store file with
# Marshal. That carries the usual limitations. Proc objects cannot be
# marshalled, for example.
#
# == Usage example:
#
# require "pstore"
#
# # a mock wiki object...
# class WikiPage
# def initialize( page_name, author, contents )
# @page_name = page_name
# @revisions = Array.new
#
# add_revision(author, contents)
# end
#
# attr_reader :page_name
#
# def add_revision( author, contents )
# @revisions << { :created => Time.now,
# :author => author,
# :contents => contents }
# end
#
# def wiki_page_references
# [@page_name] + @revisions.last[:contents].scan(/\b(?:[A-Z]+[a-z]+){2,}/)
# end
#
# # ...
# end
#
# # create a new page...
# home_page = WikiPage.new( "HomePage", "James Edward Gray II",
# "A page about the JoysOfDocumentation..." )
#
# # then we want to update page data and the index together, or not at all...
# wiki = PStore.new("wiki_pages.pstore")
# wiki.transaction do # begin transaction; do all of this or none of it
# # store page...
# wiki[home_page.page_name] = home_page
# # ensure that an index has been created...
# wiki[:wiki_index] ||= Array.new
# # update wiki index...
# wiki[:wiki_index].push(*home_page.wiki_page_references)
# end # commit changes to wiki data store file
#
# ### Some time later... ###
#
# # read wiki data...
# wiki.transaction(true) do # begin read-only transaction, no changes allowed
# wiki.roots.each do |data_root_name|
# p data_root_name
# p wiki[data_root_name]
# end
# end
#
# == Transaction modes
#
# By default, file integrity is only ensured as long as the operating system
# (and the underlying hardware) doesn't raise any unexpected I/O errors. If an
# I/O error occurs while PStore is writing to its file, then the file will
# become corrupted.
#
# You can prevent this by setting <em>pstore.ultra_safe = true</em>.
# However, this results in a minor performance loss, and only works on platforms
# that support atomic file renames. Please consult the documentation for
# +ultra_safe+ for details.
#
# Needless to say, if you're storing valuable data with PStore, then you should
# backup the PStore files from time to time.
class PStore
binmode = defined?(File::BINARY) ? File::BINARY : 0
RDWR_ACCESS = File::RDWR | File::CREAT | binmode
RD_ACCESS = File::RDONLY | binmode
WR_ACCESS = File::WRONLY | File::CREAT | File::TRUNC | binmode
# The error type thrown by all PStore methods.
class Error < StandardError
end
# Whether PStore should do its best to prevent file corruptions, even when under
# unlikely-to-occur error conditions such as out-of-space conditions and other
# unusual OS filesystem errors. Setting this flag comes at the price in the form
# of a performance loss.
#
# This flag only has effect on platforms on which file renames are atomic (e.g.
# all POSIX platforms: Linux, MacOS X, FreeBSD, etc). The default value is false.
attr_accessor :ultra_safe
#
# To construct a PStore object, pass in the _file_ path where you would like
# the data to be stored.
#
# PStore objects are always reentrant. But if _thread_safe_ is set to true,
# then it will become thread-safe at the cost of a minor performance hit.
#
def initialize(file, thread_safe = false)
dir = File::dirname(file)
unless File::directory? dir
raise PStore::Error, format("directory %s does not exist", dir)
end
if File::exist? file and not File::readable? file
raise PStore::Error, format("file %s not readable", file)
end
@transaction = false
@filename = file
@abort = false
@ultra_safe = false
if @thread_safe
@lock = Mutex.new
else
@lock = DummyMutex.new
end
end
# Raises PStore::Error if the calling code is not in a PStore#transaction.
def in_transaction
raise PStore::Error, "not in transaction" unless @transaction
end
#
# Raises PStore::Error if the calling code is not in a PStore#transaction or
# if the code is in a read-only PStore#transaction.
#
def in_transaction_wr()
in_transaction()
raise PStore::Error, "in read-only transaction" if @rdonly
end
private :in_transaction, :in_transaction_wr
#
# Retrieves a value from the PStore file data, by _name_. The hierarchy of
# Ruby objects stored under that root _name_ will be returned.
#
# *WARNING*: This method is only valid in a PStore#transaction. It will
# raise PStore::Error if called at any other time.
#
def [](name)
in_transaction
@table[name]
end
#
# This method is just like PStore#[], save that you may also provide a
# _default_ value for the object. In the event the specified _name_ is not
# found in the data store, your _default_ will be returned instead. If you do
# not specify a default, PStore::Error will be raised if the object is not
# found.
#
# *WARNING*: This method is only valid in a PStore#transaction. It will
# raise PStore::Error if called at any other time.
#
def fetch(name, default=PStore::Error)
in_transaction
unless @table.key? name
if default == PStore::Error
raise PStore::Error, format("undefined root name `%s'", name)
else
return default
end
end
@table[name]
end
#
# Stores an individual Ruby object or a hierarchy of Ruby objects in the data
# store file under the root _name_. Assigning to a _name_ already in the data
# store clobbers the old data.
#
# == Example:
#
# require "pstore"
#
# store = PStore.new("data_file.pstore")
# store.transaction do # begin transaction
# # load some data into the store...
# store[:single_object] = "My data..."
# store[:obj_heirarchy] = { "Kev Jackson" => ["rational.rb", "pstore.rb"],
# "James Gray" => ["erb.rb", "pstore.rb"] }
# end # commit changes to data store file
#
# *WARNING*: This method is only valid in a PStore#transaction and it cannot
# be read-only. It will raise PStore::Error if called at any other time.
#
def []=(name, value)
in_transaction_wr()
@table[name] = value
end
#
# Removes an object hierarchy from the data store, by _name_.
#
# *WARNING*: This method is only valid in a PStore#transaction and it cannot
# be read-only. It will raise PStore::Error if called at any other time.
#
def delete(name)
in_transaction_wr()
@table.delete name
end
#
# Returns the names of all object hierarchies currently in the store.
#
# *WARNING*: This method is only valid in a PStore#transaction. It will
# raise PStore::Error if called at any other time.
#
def roots
in_transaction
@table.keys
end
#
# Returns true if the supplied _name_ is currently in the data store.
#
# *WARNING*: This method is only valid in a PStore#transaction. It will
# raise PStore::Error if called at any other time.
#
def root?(name)
in_transaction
@table.key? name
end
# Returns the path to the data store file.
def path
@filename
end
#
# Ends the current PStore#transaction, committing any changes to the data
# store immediately.
#
# == Example:
#
# require "pstore"
#
# store = PStore.new("data_file.pstore")
# store.transaction do # begin transaction
# # load some data into the store...
# store[:one] = 1
# store[:two] = 2
#
# store.commit # end transaction here, committing changes
#
# store[:three] = 3 # this change is never reached
# end
#
# *WARNING*: This method is only valid in a PStore#transaction. It will
# raise PStore::Error if called at any other time.
#
def commit
in_transaction
@abort = false
throw :pstore_abort_transaction
end
#
# Ends the current PStore#transaction, discarding any changes to the data
# store.
#
# == Example:
#
# require "pstore"
#
# store = PStore.new("data_file.pstore")
# store.transaction do # begin transaction
# store[:one] = 1 # this change is not applied, see below...
# store[:two] = 2 # this change is not applied, see below...
#
# store.abort # end transaction here, discard all changes
#
# store[:three] = 3 # this change is never reached
# end
#
# *WARNING*: This method is only valid in a PStore#transaction. It will
# raise PStore::Error if called at any other time.
#
def abort
in_transaction
@abort = true
throw :pstore_abort_transaction
end
#
# Opens a new transaction for the data store. Code executed inside a block
# passed to this method may read and write data to and from the data store
# file.
#
# At the end of the block, changes are committed to the data store
# automatically. You may exit the transaction early with a call to either
# PStore#commit or PStore#abort. See those methods for details about how
# changes are handled. Raising an uncaught Exception in the block is
# equivalent to calling PStore#abort.
#
# If _read_only_ is set to +true+, you will only be allowed to read from the
# data store during the transaction and any attempts to change the data will
# raise a PStore::Error.
#
# Note that PStore does not support nested transactions.
#
def transaction(read_only = false, &block) # :yields: pstore
value = nil
raise PStore::Error, "nested transaction" if @transaction
@lock.synchronize do
@rdonly = read_only
@transaction = true
@abort = false
file = open_and_lock_file(@filename, read_only)
if file
begin
@table, checksum, original_data_size = load_data(file, read_only)
catch(:pstore_abort_transaction) do
value = yield(self)
end
if !@abort && !read_only
save_data(checksum, original_data_size, file)
end
ensure
file.close if !file.closed?
end
else
# This can only occur if read_only == true.
@table = {}
catch(:pstore_abort_transaction) do
value = yield(self)
end
end
end
value
ensure
@transaction = false
end
private
# Constant for relieving Ruby's garbage collector.
EMPTY_STRING = ""
EMPTY_MARSHAL_DATA = Marshal.dump({})
EMPTY_MARSHAL_CHECKSUM = Digest::MD5.digest(EMPTY_MARSHAL_DATA)
class DummyMutex
def synchronize
yield
end
end
#
# Open the specified filename (either in read-only mode or in
# read-write mode) and lock it for reading or writing.
#
# The opened File object will be returned. If _read_only_ is true,
# and the file does not exist, then nil will be returned.
#
# All exceptions are propagated.
#
def open_and_lock_file(filename, read_only)
if read_only
begin
file = File.new(filename, RD_ACCESS)
begin
file.flock(File::LOCK_SH)
return file
rescue
file.close
raise
end
rescue Errno::ENOENT
return nil
end
else
file = File.new(filename, RDWR_ACCESS)
file.flock(File::LOCK_EX)
return file
end
end
# Load the given PStore file.
# If +read_only+ is true, the unmarshalled Hash will be returned.
# If +read_only+ is false, a 3-tuple will be returned: the unmarshalled
# Hash, an MD5 checksum of the data, and the size of the data.
def load_data(file, read_only)
if read_only
begin
table = load(file)
if !table.is_a?(Hash)
raise Error, "PStore file seems to be corrupted."
end
rescue EOFError
# This seems to be a newly-created file.
table = {}
end
table
else
data = file.read
if data.empty?
# This seems to be a newly-created file.
table = {}
checksum = empty_marshal_checksum
size = empty_marshal_data.size
else
table = load(data)
checksum = Digest::MD5.digest(data)
size = data.size
if !table.is_a?(Hash)
raise Error, "PStore file seems to be corrupted."
end
end
data.replace(EMPTY_STRING)
[table, checksum, size]
end
end
def on_windows?
is_windows = RUBY_PLATFORM =~ /mswin/ ||
RUBY_PLATFORM =~ /mingw/ ||
RUBY_PLATFORM =~ /bccwin/ ||
RUBY_PLATFORM =~ /wince/
self.class.__send__(:define_method, :on_windows?) do
is_windows
end
is_windows
end
# Check whether Marshal.dump supports the 'canonical' option. This option
# makes sure that Marshal.dump always dumps data structures in the same order.
# This is important because otherwise, the checksums that we generate may differ.
def marshal_dump_supports_canonical_option?
begin
Marshal.dump(nil, -1, true)
result = true
rescue
result = false
end
self.class.__send__(:define_method, :marshal_dump_supports_canonical_option?) do
result
end
result
end
def save_data(original_checksum, original_file_size, file)
# We only want to save the new data if the size or checksum has changed.
# This results in less filesystem calls, which is good for performance.
if marshal_dump_supports_canonical_option?
new_data = Marshal.dump(@table, -1, true)
else
new_data = dump(@table)
end
new_checksum = Digest::MD5.digest(new_data)
if new_data.size != original_file_size || new_checksum != original_checksum
if @ultra_safe && !on_windows?
# Windows doesn't support atomic file renames.
save_data_with_atomic_file_rename_strategy(new_data, file)
else
save_data_with_fast_strategy(new_data, file)
end
end
new_data.replace(EMPTY_STRING)
end
def save_data_with_atomic_file_rename_strategy(data, file)
temp_filename = "#{@filename}.tmp.#{Process.pid}.#{rand 1000000}"
temp_file = File.new(temp_filename, WR_ACCESS)
begin
temp_file.flock(File::LOCK_EX)
temp_file.write(data)
temp_file.flush
File.rename(temp_filename, @filename)
rescue
File.unlink(temp_file) rescue nil
raise
ensure
temp_file.close
end
end
def save_data_with_fast_strategy(data, file)
file.rewind
file.truncate(0)
file.write(data)
end
# This method is just a wrapped around Marshal.dump
# to allow subclass overriding used in YAML::Store.
def dump(table) # :nodoc:
Marshal::dump(table)
end
# This method is just a wrapped around Marshal.load.
# to allow subclass overriding used in YAML::Store.
def load(content) # :nodoc:
Marshal::load(content)
end
def empty_marshal_data
EMPTY_MARSHAL_DATA
end
def empty_marshal_checksum
EMPTY_MARSHAL_CHECKSUM
end
end
# :enddoc:
if __FILE__ == $0
db = PStore.new("/tmp/foo")
db.transaction do
p db.roots
ary = db["root"] = [1,2,3,4]
ary[1] = [1,1.5]
end
1000.times do
db.transaction do
db["root"][0] += 1
p db["root"][0]
end
end
db.transaction(true) do
p db["root"]
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/prettyprint.rb | tools/jruby-1.5.1/lib/ruby/1.9/prettyprint.rb | # This class implements a pretty printing algorithm. It finds line breaks and
# nice indentations for grouped structure.
#
# By default, the class assumes that primitive elements are strings and each
# byte in the strings have single column in width. But it can be used for
# other situations by giving suitable arguments for some methods:
# * newline object and space generation block for PrettyPrint.new
# * optional width argument for PrettyPrint#text
# * PrettyPrint#breakable
#
# There are several candidate uses:
# * text formatting using proportional fonts
# * multibyte characters which has columns different to number of bytes
# * non-string formatting
#
# == Bugs
# * Box based formatting?
# * Other (better) model/algorithm?
#
# == References
# Christian Lindig, Strictly Pretty, March 2000,
# http://www.st.cs.uni-sb.de/~lindig/papers/#pretty
#
# Philip Wadler, A prettier printer, March 1998,
# http://homepages.inf.ed.ac.uk/wadler/topics/language-design.html#prettier
#
# == Author
# Tanaka Akira <akr@m17n.org>
#
class PrettyPrint
# This is a convenience method which is same as follows:
#
# begin
# q = PrettyPrint.new(output, maxwidth, newline, &genspace)
# ...
# q.flush
# output
# end
#
def PrettyPrint.format(output='', maxwidth=79, newline="\n", genspace=lambda {|n| ' ' * n})
q = PrettyPrint.new(output, maxwidth, newline, &genspace)
yield q
q.flush
output
end
# This is similar to PrettyPrint::format but the result has no breaks.
#
# +maxwidth+, +newline+ and +genspace+ are ignored.
#
# The invocation of +breakable+ in the block doesn't break a line and is
# treated as just an invocation of +text+.
#
def PrettyPrint.singleline_format(output='', maxwidth=nil, newline=nil, genspace=nil)
q = SingleLine.new(output)
yield q
output
end
# Creates a buffer for pretty printing.
#
# +output+ is an output target. If it is not specified, '' is assumed. It
# should have a << method which accepts the first argument +obj+ of
# PrettyPrint#text, the first argument +sep+ of PrettyPrint#breakable, the
# first argument +newline+ of PrettyPrint.new, and the result of a given
# block for PrettyPrint.new.
#
# +maxwidth+ specifies maximum line length. If it is not specified, 79 is
# assumed. However actual outputs may overflow +maxwidth+ if long
# non-breakable texts are provided.
#
# +newline+ is used for line breaks. "\n" is used if it is not specified.
#
# The block is used to generate spaces. {|width| ' ' * width} is used if it
# is not given.
#
def initialize(output='', maxwidth=79, newline="\n", &genspace)
@output = output
@maxwidth = maxwidth
@newline = newline
@genspace = genspace || lambda {|n| ' ' * n}
@output_width = 0
@buffer_width = 0
@buffer = []
root_group = Group.new(0)
@group_stack = [root_group]
@group_queue = GroupQueue.new(root_group)
@indent = 0
end
attr_reader :output, :maxwidth, :newline, :genspace
attr_reader :indent, :group_queue
def current_group
@group_stack.last
end
# first? is a predicate to test the call is a first call to first? with
# current group.
#
# It is useful to format comma separated values as:
#
# q.group(1, '[', ']') {
# xxx.each {|yyy|
# unless q.first?
# q.text ','
# q.breakable
# end
# ... pretty printing yyy ...
# }
# }
#
# first? is obsoleted in 1.8.2.
#
def first?
warn "PrettyPrint#first? is obsoleted at 1.8.2."
current_group.first?
end
def break_outmost_groups
while @maxwidth < @output_width + @buffer_width
return unless group = @group_queue.deq
until group.breakables.empty?
data = @buffer.shift
@output_width = data.output(@output, @output_width)
@buffer_width -= data.width
end
while !@buffer.empty? && Text === @buffer.first
text = @buffer.shift
@output_width = text.output(@output, @output_width)
@buffer_width -= text.width
end
end
end
# This adds +obj+ as a text of +width+ columns in width.
#
# If +width+ is not specified, obj.length is used.
#
def text(obj, width=obj.length)
if @buffer.empty?
@output << obj
@output_width += width
else
text = @buffer.last
unless Text === text
text = Text.new
@buffer << text
end
text.add(obj, width)
@buffer_width += width
break_outmost_groups
end
end
def fill_breakable(sep=' ', width=sep.length)
group { breakable sep, width }
end
# This tells "you can break a line here if necessary", and a +width+\-column
# text +sep+ is inserted if a line is not broken at the point.
#
# If +sep+ is not specified, " " is used.
#
# If +width+ is not specified, +sep.length+ is used. You will have to
# specify this when +sep+ is a multibyte character, for example.
#
def breakable(sep=' ', width=sep.length)
group = @group_stack.last
if group.break?
flush
@output << @newline
@output << @genspace.call(@indent)
@output_width = @indent
@buffer_width = 0
else
@buffer << Breakable.new(sep, width, self)
@buffer_width += width
break_outmost_groups
end
end
# Groups line break hints added in the block. The line break hints are all
# to be used or not.
#
# If +indent+ is specified, the method call is regarded as nested by
# nest(indent) { ... }.
#
# If +open_obj+ is specified, <tt>text open_obj, open_width</tt> is called
# before grouping. If +close_obj+ is specified, <tt>text close_obj,
# close_width</tt> is called after grouping.
#
def group(indent=0, open_obj='', close_obj='', open_width=open_obj.length, close_width=close_obj.length)
text open_obj, open_width
group_sub {
nest(indent) {
yield
}
}
text close_obj, close_width
end
def group_sub
group = Group.new(@group_stack.last.depth + 1)
@group_stack.push group
@group_queue.enq group
begin
yield
ensure
@group_stack.pop
if group.breakables.empty?
@group_queue.delete group
end
end
end
# Increases left margin after newline with +indent+ for line breaks added in
# the block.
#
def nest(indent)
@indent += indent
begin
yield
ensure
@indent -= indent
end
end
# outputs buffered data.
#
def flush
@buffer.each {|data|
@output_width = data.output(@output, @output_width)
}
@buffer.clear
@buffer_width = 0
end
class Text
def initialize
@objs = []
@width = 0
end
attr_reader :width
def output(out, output_width)
@objs.each {|obj| out << obj}
output_width + @width
end
def add(obj, width)
@objs << obj
@width += width
end
end
class Breakable
def initialize(sep, width, q)
@obj = sep
@width = width
@pp = q
@indent = q.indent
@group = q.current_group
@group.breakables.push self
end
attr_reader :obj, :width, :indent
def output(out, output_width)
@group.breakables.shift
if @group.break?
out << @pp.newline
out << @pp.genspace.call(@indent)
@indent
else
@pp.group_queue.delete @group if @group.breakables.empty?
out << @obj
output_width + @width
end
end
end
class Group
def initialize(depth)
@depth = depth
@breakables = []
@break = false
end
attr_reader :depth, :breakables
def break
@break = true
end
def break?
@break
end
def first?
if defined? @first
false
else
@first = false
true
end
end
end
class GroupQueue
def initialize(*groups)
@queue = []
groups.each {|g| enq g}
end
def enq(group)
depth = group.depth
@queue << [] until depth < @queue.length
@queue[depth] << group
end
def deq
@queue.each {|gs|
(gs.length-1).downto(0) {|i|
unless gs[i].breakables.empty?
group = gs.slice!(i, 1).first
group.break
return group
end
}
gs.each {|group| group.break}
gs.clear
}
return nil
end
def delete(group)
@queue[group.depth].delete(group)
end
end
class SingleLine
def initialize(output, maxwidth=nil, newline=nil)
@output = output
@first = [true]
end
def text(obj, width=nil)
@output << obj
end
def breakable(sep=' ', width=nil)
@output << sep
end
def nest(indent)
yield
end
def group(indent=nil, open_obj='', close_obj='', open_width=nil, close_width=nil)
@first.push true
@output << open_obj
yield
@output << close_obj
@first.pop
end
def flush
end
def first?
result = @first[-1]
@first[-1] = false
result
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/profile.rb | tools/jruby-1.5.1/lib/ruby/1.9/profile.rb | require 'profiler'
RubyVM::InstructionSequence.compile_option = {
:trace_instruction => true,
:specialized_instruction => false
}
END {
Profiler__::print_profile(STDERR)
}
Profiler__::start_profile
| 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/erb.rb | tools/jruby-1.5.1/lib/ruby/1.9/erb.rb | # = ERB -- Ruby Templating
#
# Author:: Masatoshi SEKI
# Documentation:: James Edward Gray II and Gavin Sinclair
#
# See ERB for primary documentation and ERB::Util for a couple of utility
# routines.
#
# Copyright (c) 1999-2000,2002,2003 Masatoshi SEKI
#
# You can redistribute it and/or modify it under the same terms as Ruby.
#
# = ERB -- Ruby Templating
#
# == Introduction
#
# ERB provides an easy to use but powerful templating system for Ruby. Using
# ERB, actual Ruby code can be added to any plain text document for the
# purposes of generating document information details and/or flow control.
#
# A very simple example is this:
#
# require 'erb'
#
# x = 42
# template = ERB.new <<-EOF
# The value of x is: <%= x %>
# EOF
# puts template.result(binding)
#
# <em>Prints:</em> The value of x is: 42
#
# More complex examples are given below.
#
#
# == Recognized Tags
#
# ERB recognizes certain tags in the provided template and converts them based
# on the rules below:
#
# <% Ruby code -- inline with output %>
# <%= Ruby expression -- replace with result %>
# <%# comment -- ignored -- useful in testing %>
# % a line of Ruby code -- treated as <% line %> (optional -- see ERB.new)
# %% replaced with % if first thing on a line and % processing is used
# <%% or %%> -- replace with <% or %> respectively
#
# All other text is passed through ERB filtering unchanged.
#
#
# == Options
#
# There are several settings you can change when you use ERB:
# * the nature of the tags that are recognized;
# * the value of <tt>$SAFE</tt> under which the template is run;
# * the binding used to resolve local variables in the template.
#
# See the ERB.new and ERB#result methods for more detail.
#
# == Character encodings
#
# ERB (or ruby code generated by ERB) returns a string in the same
# character encoding as the input string. When the input string has
# a magic comment, however, it returns a string in the encoding specified
# by the magic comment.
#
# # -*- coding: UTF-8 -*-
# require 'erb'
#
# template = ERB.new <<EOF
# <%#-*- coding: Big5 -*-%>
# \_\_ENCODING\_\_ is <%= \_\_ENCODING\_\_ %>.
# EOF
# puts template.result
#
# <em>Prints:</em> \_\_ENCODING\_\_ is Big5.
#
#
# == Examples
#
# === Plain Text
#
# ERB is useful for any generic templating situation. Note that in this example, we use the
# convenient "% at start of line" tag, and we quote the template literally with
# <tt>%q{...}</tt> to avoid trouble with the backslash.
#
# require "erb"
#
# # Create template.
# template = %q{
# From: James Edward Gray II <james@grayproductions.net>
# To: <%= to %>
# Subject: Addressing Needs
#
# <%= to[/\w+/] %>:
#
# Just wanted to send a quick note assuring that your needs are being
# addressed.
#
# I want you to know that my team will keep working on the issues,
# especially:
#
# <%# ignore numerous minor requests -- focus on priorities %>
# % priorities.each do |priority|
# * <%= priority %>
# % end
#
# Thanks for your patience.
#
# James Edward Gray II
# }.gsub(/^ /, '')
#
# message = ERB.new(template, 0, "%<>")
#
# # Set up template data.
# to = "Community Spokesman <spokesman@ruby_community.org>"
# priorities = [ "Run Ruby Quiz",
# "Document Modules",
# "Answer Questions on Ruby Talk" ]
#
# # Produce result.
# email = message.result
# puts email
#
# <i>Generates:</i>
#
# From: James Edward Gray II <james@grayproductions.net>
# To: Community Spokesman <spokesman@ruby_community.org>
# Subject: Addressing Needs
#
# Community:
#
# Just wanted to send a quick note assuring that your needs are being addressed.
#
# I want you to know that my team will keep working on the issues, especially:
#
# * Run Ruby Quiz
# * Document Modules
# * Answer Questions on Ruby Talk
#
# Thanks for your patience.
#
# James Edward Gray II
#
# === Ruby in HTML
#
# ERB is often used in <tt>.rhtml</tt> files (HTML with embedded Ruby). Notice the need in
# this example to provide a special binding when the template is run, so that the instance
# variables in the Product object can be resolved.
#
# require "erb"
#
# # Build template data class.
# class Product
# def initialize( code, name, desc, cost )
# @code = code
# @name = name
# @desc = desc
# @cost = cost
#
# @features = [ ]
# end
#
# def add_feature( feature )
# @features << feature
# end
#
# # Support templating of member data.
# def get_binding
# binding
# end
#
# # ...
# end
#
# # Create template.
# template = %{
# <html>
# <head><title>Ruby Toys -- <%= @name %></title></head>
# <body>
#
# <h1><%= @name %> (<%= @code %>)</h1>
# <p><%= @desc %></p>
#
# <ul>
# <% @features.each do |f| %>
# <li><b><%= f %></b></li>
# <% end %>
# </ul>
#
# <p>
# <% if @cost < 10 %>
# <b>Only <%= @cost %>!!!</b>
# <% else %>
# Call for a price, today!
# <% end %>
# </p>
#
# </body>
# </html>
# }.gsub(/^ /, '')
#
# rhtml = ERB.new(template)
#
# # Set up template data.
# toy = Product.new( "TZ-1002",
# "Rubysapien",
# "Geek's Best Friend! Responds to Ruby commands...",
# 999.95 )
# toy.add_feature("Listens for verbal commands in the Ruby language!")
# toy.add_feature("Ignores Perl, Java, and all C variants.")
# toy.add_feature("Karate-Chop Action!!!")
# toy.add_feature("Matz signature on left leg.")
# toy.add_feature("Gem studded eyes... Rubies, of course!")
#
# # Produce result.
# rhtml.run(toy.get_binding)
#
# <i>Generates (some blank lines removed):</i>
#
# <html>
# <head><title>Ruby Toys -- Rubysapien</title></head>
# <body>
#
# <h1>Rubysapien (TZ-1002)</h1>
# <p>Geek's Best Friend! Responds to Ruby commands...</p>
#
# <ul>
# <li><b>Listens for verbal commands in the Ruby language!</b></li>
# <li><b>Ignores Perl, Java, and all C variants.</b></li>
# <li><b>Karate-Chop Action!!!</b></li>
# <li><b>Matz signature on left leg.</b></li>
# <li><b>Gem studded eyes... Rubies, of course!</b></li>
# </ul>
#
# <p>
# Call for a price, today!
# </p>
#
# </body>
# </html>
#
#
# == Notes
#
# There are a variety of templating solutions available in various Ruby projects:
# * ERB's big brother, eRuby, works the same but is written in C for speed;
# * Amrita (smart at producing HTML/XML);
# * cs/Template (written in C for speed);
# * RDoc, distributed with Ruby, uses its own template engine, which can be reused elsewhere;
# * and others; search the RAA.
#
# Rails, the web application framework, uses ERB to create views.
#
class ERB
Revision = '$Date:: 2009-03-06 12:56:38 +0900#$' #'
# Returns revision information for the erb.rb module.
def self.version
"erb.rb [2.1.0 #{ERB::Revision.split[1]}]"
end
end
#--
# ERB::Compiler
class ERB
class Compiler # :nodoc:
class PercentLine # :nodoc:
def initialize(str)
@value = str
end
attr_reader :value
alias :to_s :value
def empty?
@value.empty?
end
end
class Scanner # :nodoc:
@scanner_map = {}
def self.regist_scanner(klass, trim_mode, percent)
@scanner_map[[trim_mode, percent]] = klass
end
def self.default_scanner=(klass)
@default_scanner = klass
end
def self.make_scanner(src, trim_mode, percent)
klass = @scanner_map.fetch([trim_mode, percent], @default_scanner)
klass.new(src, trim_mode, percent)
end
def initialize(src, trim_mode, percent)
@src = src
@stag = nil
end
attr_accessor :stag
def scan; end
end
class TrimScanner < Scanner # :nodoc:
def initialize(src, trim_mode, percent)
super
@trim_mode = trim_mode
@percent = percent
if @trim_mode == '>'
@scan_line = self.method(:trim_line1)
elsif @trim_mode == '<>'
@scan_line = self.method(:trim_line2)
elsif @trim_mode == '-'
@scan_line = self.method(:explicit_trim_line)
else
@scan_line = self.method(:scan_line)
end
end
attr_accessor :stag
def scan(&block)
@stag = nil
if @percent
@src.each_line do |line|
percent_line(line, &block)
end
else
@scan_line.call(@src, &block)
end
nil
end
def percent_line(line, &block)
if @stag || line[0] != ?%
return @scan_line.call(line, &block)
end
line[0] = ''
if line[0] == ?%
@scan_line.call(line, &block)
else
yield(PercentLine.new(line.chomp))
end
end
def scan_line(line)
line.scan(/(.*?)(<%%|%%>|<%=|<%#|<%|%>|\n|\z)/m) do |tokens|
tokens.each do |token|
next if token.empty?
yield(token)
end
end
end
def trim_line1(line)
line.scan(/(.*?)(<%%|%%>|<%=|<%#|<%|%>\n|%>|\n|\z)/m) do |tokens|
tokens.each do |token|
next if token.empty?
if token == "%>\n"
yield('%>')
yield(:cr)
else
yield(token)
end
end
end
end
def trim_line2(line)
head = nil
line.scan(/(.*?)(<%%|%%>|<%=|<%#|<%|%>\n|%>|\n|\z)/m) do |tokens|
tokens.each do |token|
next if token.empty?
head = token unless head
if token == "%>\n"
yield('%>')
if is_erb_stag?(head)
yield(:cr)
else
yield("\n")
end
head = nil
else
yield(token)
head = nil if token == "\n"
end
end
end
end
def explicit_trim_line(line)
line.scan(/(.*?)(^[ \t]*<%\-|<%\-|<%%|%%>|<%=|<%#|<%|-%>\n|-%>|%>|\z)/m) do |tokens|
tokens.each do |token|
next if token.empty?
if @stag.nil? && /[ \t]*<%-/ =~ token
yield('<%')
elsif @stag && token == "-%>\n"
yield('%>')
yield(:cr)
elsif @stag && token == '-%>'
yield('%>')
else
yield(token)
end
end
end
end
ERB_STAG = %w(<%= <%# <%)
def is_erb_stag?(s)
ERB_STAG.member?(s)
end
end
Scanner.default_scanner = TrimScanner
class SimpleScanner < Scanner # :nodoc:
def scan
@src.scan(/(.*?)(<%%|%%>|<%=|<%#|<%|%>|\n|\z)/m) do |tokens|
tokens.each do |token|
next if token.empty?
yield(token)
end
end
end
end
Scanner.regist_scanner(SimpleScanner, nil, false)
begin
require 'strscan'
class SimpleScanner2 < Scanner # :nodoc:
def scan
stag_reg = /(.*?)(<%%|<%=|<%#|<%|\z)/m
etag_reg = /(.*?)(%%>|%>|\z)/m
scanner = StringScanner.new(@src)
while ! scanner.eos?
scanner.scan(@stag ? etag_reg : stag_reg)
yield(scanner[1])
yield(scanner[2])
end
end
end
Scanner.regist_scanner(SimpleScanner2, nil, false)
class ExplicitScanner < Scanner # :nodoc:
def scan
stag_reg = /(.*?)(^[ \t]*<%-|<%%|<%=|<%#|<%-|<%|\z)/m
etag_reg = /(.*?)(%%>|-%>|%>|\z)/m
scanner = StringScanner.new(@src)
while ! scanner.eos?
scanner.scan(@stag ? etag_reg : stag_reg)
yield(scanner[1])
elem = scanner[2]
if /[ \t]*<%-/ =~ elem
yield('<%')
elsif elem == '-%>'
yield('%>')
yield(:cr) if scanner.scan(/(\n|\z)/)
else
yield(elem)
end
end
end
end
Scanner.regist_scanner(ExplicitScanner, '-', false)
rescue LoadError
end
class Buffer # :nodoc:
def initialize(compiler, enc=nil)
@compiler = compiler
@line = []
@script = enc ? "#coding:#{enc.to_s}\n" : ""
@compiler.pre_cmd.each do |x|
push(x)
end
end
attr_reader :script
def push(cmd)
@line << cmd
end
def cr
@script << (@line.join('; '))
@line = []
@script << "\n"
end
def close
return unless @line
@compiler.post_cmd.each do |x|
push(x)
end
@script << (@line.join('; '))
@line = nil
end
end
def content_dump(s)
n = s.count("\n")
if n > 0
s.dump + "\n" * n
else
s.dump
end
end
def compile(s)
enc = s.encoding
raise ArgumentError, "#{enc} is not ASCII compatible" if enc.dummy?
s = s.dup.force_encoding("ASCII-8BIT") # don't use constant Enoding::ASCII_8BIT for miniruby
enc = detect_magic_comment(s) || enc
out = Buffer.new(self, enc)
content = ''
scanner = make_scanner(s)
scanner.scan do |token|
next if token.nil?
next if token == ''
if scanner.stag.nil?
case token
when PercentLine
out.push("#{@put_cmd} #{content_dump(content)}") if content.size > 0
content = ''
out.push(token.to_s)
out.cr
when :cr
out.cr
when '<%', '<%=', '<%#'
scanner.stag = token
out.push("#{@put_cmd} #{content_dump(content)}") if content.size > 0
content = ''
when "\n"
content << "\n"
out.push("#{@put_cmd} #{content_dump(content)}")
content = ''
when '<%%'
content << '<%'
else
content << token
end
else
case token
when '%>'
case scanner.stag
when '<%'
if content[-1] == ?\n
content.chop!
out.push(content)
out.cr
else
out.push(content)
end
when '<%='
out.push("#{@insert_cmd}((#{content}).to_s)")
when '<%#'
# out.push("# #{content_dump(content)}")
end
scanner.stag = nil
content = ''
when '%%>'
content << '%>'
else
content << token
end
end
end
out.push("#{@put_cmd} #{content_dump(content)}") if content.size > 0
out.close
return out.script, enc
end
def prepare_trim_mode(mode)
case mode
when 1
return [false, '>']
when 2
return [false, '<>']
when 0
return [false, nil]
when String
perc = mode.include?('%')
if mode.include?('-')
return [perc, '-']
elsif mode.include?('<>')
return [perc, '<>']
elsif mode.include?('>')
return [perc, '>']
else
[perc, nil]
end
else
return [false, nil]
end
end
def make_scanner(src)
Scanner.make_scanner(src, @trim_mode, @percent)
end
def initialize(trim_mode)
@percent, @trim_mode = prepare_trim_mode(trim_mode)
@put_cmd = 'print'
@insert_cmd = @put_cmd
@pre_cmd = []
@post_cmd = []
end
attr_reader :percent, :trim_mode
attr_accessor :put_cmd, :insert_cmd, :pre_cmd, :post_cmd
private
def detect_magic_comment(s)
if /\A<%#(.*)%>/ =~ s or (@percent and /\A%#(.*)/ =~ s)
comment = $1
comment = $1 if comment[/-\*-\s*(.*?)\s*-*-$/]
if %r"coding\s*[=:]\s*([[:alnum:]\-_]+)" =~ comment
enc = $1.sub(/-(?:mac|dos|unix)/i, '')
enc = Encoding.find(enc)
end
end
end
end
end
#--
# ERB
class ERB
#
# Constructs a new ERB object with the template specified in _str_.
#
# An ERB object works by building a chunk of Ruby code that will output
# the completed template when run. If _safe_level_ is set to a non-nil value,
# ERB code will be run in a separate thread with <b>$SAFE</b> set to the
# provided level.
#
# If _trim_mode_ is passed a String containing one or more of the following
# modifiers, ERB will adjust its code generation as listed:
#
# % enables Ruby code processing for lines beginning with %
# <> omit newline for lines starting with <% and ending in %>
# > omit newline for lines ending in %>
#
# _eoutvar_ can be used to set the name of the variable ERB will build up
# its output in. This is useful when you need to run multiple ERB
# templates through the same binding and/or when you want to control where
# output ends up. Pass the name of the variable to be used inside a String.
#
# === Example
#
# require "erb"
#
# # build data class
# class Listings
# PRODUCT = { :name => "Chicken Fried Steak",
# :desc => "A well messages pattie, breaded and fried.",
# :cost => 9.95 }
#
# attr_reader :product, :price
#
# def initialize( product = "", price = "" )
# @product = product
# @price = price
# end
#
# def build
# b = binding
# # create and run templates, filling member data variables
# ERB.new(<<-'END_PRODUCT'.gsub(/^\s+/, ""), 0, "", "@product").result b
# <%= PRODUCT[:name] %>
# <%= PRODUCT[:desc] %>
# END_PRODUCT
# ERB.new(<<-'END_PRICE'.gsub(/^\s+/, ""), 0, "", "@price").result b
# <%= PRODUCT[:name] %> -- <%= PRODUCT[:cost] %>
# <%= PRODUCT[:desc] %>
# END_PRICE
# end
# end
#
# # setup template data
# listings = Listings.new
# listings.build
#
# puts listings.product + "\n" + listings.price
#
# _Generates_
#
# Chicken Fried Steak
# A well messages pattie, breaded and fried.
#
# Chicken Fried Steak -- 9.95
# A well messages pattie, breaded and fried.
#
def initialize(str, safe_level=nil, trim_mode=nil, eoutvar='_erbout')
@safe_level = safe_level
compiler = ERB::Compiler.new(trim_mode)
set_eoutvar(compiler, eoutvar)
@src, @enc = *compiler.compile(str)
@filename = nil
end
# The Ruby code generated by ERB
attr_reader :src
# The optional _filename_ argument passed to Kernel#eval when the ERB code
# is run
attr_accessor :filename
#
# Can be used to set _eoutvar_ as described in ERB#new. It's probably easier
# to just use the constructor though, since calling this method requires the
# setup of an ERB _compiler_ object.
#
def set_eoutvar(compiler, eoutvar = '_erbout')
compiler.put_cmd = "#{eoutvar}.concat"
compiler.insert_cmd = "#{eoutvar}.concat"
cmd = []
cmd.push "#{eoutvar} = ''"
compiler.pre_cmd = cmd
cmd = []
cmd.push("#{eoutvar}.force_encoding(__ENCODING__)")
compiler.post_cmd = cmd
end
# Generate results and print them. (see ERB#result)
def run(b=TOPLEVEL_BINDING)
print self.result(b)
end
#
# Executes the generated ERB code to produce a completed template, returning
# the results of that code. (See ERB#new for details on how this process can
# be affected by _safe_level_.)
#
# _b_ accepts a Binding or Proc object which is used to set the context of
# code evaluation.
#
def result(b=TOPLEVEL_BINDING)
if @safe_level
proc {
$SAFE = @safe_level
eval(@src, b, (@filename || '(erb)'), 0)
}.call
else
eval(@src, b, (@filename || '(erb)'), 0)
end
end
# Define _methodname_ as instance method of _mod_ from compiled ruby source.
#
# example:
# filename = 'example.rhtml' # 'arg1' and 'arg2' are used in example.rhtml
# erb = ERB.new(File.read(filename))
# erb.def_method(MyClass, 'render(arg1, arg2)', filename)
# print MyClass.new.render('foo', 123)
def def_method(mod, methodname, fname='(ERB)')
src = self.src
magic_comment = "#coding:#{@enc}\n"
mod.module_eval do
eval(magic_comment + "def #{methodname}\n" + src + "\nend\n", binding, fname, -2)
end
end
# Create unnamed module, define _methodname_ as instance method of it, and return it.
#
# example:
# filename = 'example.rhtml' # 'arg1' and 'arg2' are used in example.rhtml
# erb = ERB.new(File.read(filename))
# erb.filename = filename
# MyModule = erb.def_module('render(arg1, arg2)')
# class MyClass
# include MyModule
# end
def def_module(methodname='erb')
mod = Module.new
def_method(mod, methodname, @filename || '(ERB)')
mod
end
# Define unnamed class which has _methodname_ as instance method, and return it.
#
# example:
# class MyClass_
# def initialize(arg1, arg2)
# @arg1 = arg1; @arg2 = arg2
# end
# end
# filename = 'example.rhtml' # @arg1 and @arg2 are used in example.rhtml
# erb = ERB.new(File.read(filename))
# erb.filename = filename
# MyClass = erb.def_class(MyClass_, 'render()')
# print MyClass.new('foo', 123).render()
def def_class(superklass=Object, methodname='result')
cls = Class.new(superklass)
def_method(cls, methodname, @filename || '(ERB)')
cls
end
end
#--
# ERB::Util
class ERB
# A utility module for conversion routines, often handy in HTML generation.
module Util
public
#
# A utility method for escaping HTML tag characters in _s_.
#
# require "erb"
# include ERB::Util
#
# puts html_escape("is a > 0 & a < 10?")
#
# _Generates_
#
# is a > 0 & a < 10?
#
def html_escape(s)
s.to_s.gsub(/&/, "&").gsub(/\"/, """).gsub(/>/, ">").gsub(/</, "<")
end
alias h html_escape
module_function :h
module_function :html_escape
#
# A utility method for encoding the String _s_ as a URL.
#
# require "erb"
# include ERB::Util
#
# puts url_encode("Programming Ruby: The Pragmatic Programmer's Guide")
#
# _Generates_
#
# Programming%20Ruby%3A%20%20The%20Pragmatic%20Programmer%27s%20Guide
#
def url_encode(s)
s.to_s.dup.force_encoding("ASCII-8BIT").gsub(/[^a-zA-Z0-9_\-.]/n) {
sprintf("%%%02X", $&.unpack("C")[0])
}
end
alias u url_encode
module_function :u
module_function :url_encode
end
end
#--
# ERB::DefMethod
class ERB
# Utility module to define eRuby script as instance method.
#
# === Example
#
# example.rhtml:
# <% for item in @items %>
# <b><%= item %></b>
# <% end %>
#
# example.rb:
# require 'erb'
# class MyClass
# extend ERB::DefMethod
# def_erb_method('render()', 'example.rhtml')
# def initialize(items)
# @items = items
# end
# end
# print MyClass.new([10,20,30]).render()
#
# result:
#
# <b>10</b>
#
# <b>20</b>
#
# <b>30</b>
#
module DefMethod
public
# define _methodname_ as instance method of current module, using ERB object or eRuby file
def def_erb_method(methodname, erb_or_fname)
if erb_or_fname.kind_of? String
fname = erb_or_fname
erb = ERB.new(File.read(fname))
erb.def_method(self, methodname, fname)
else
erb = erb_or_fname
erb.def_method(self, methodname, erb.filename || '(ERB)')
end
end
module_function :def_erb_method
end
end
| 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/ubygems.rb | tools/jruby-1.5.1/lib/ruby/1.9/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/1.9/scanf.rb | tools/jruby-1.5.1/lib/ruby/1.9/scanf.rb | # scanf for Ruby
#
# $Release Version: 1.1.2 $
# $Revision: 22784 $
# $Id: scanf.rb 22784 2009-03-06 03:56:38Z nobu $
# $Author: nobu $
#
# A product of the Austin Ruby Codefest (Austin, Texas, August 2002)
=begin
=scanf for Ruby
==Description
scanf for Ruby is an implementation of the C function scanf(3),
modified as necessary for Ruby compatibility.
The methods provided are String#scanf, IO#scanf, and
Kernel#scanf. Kernel#scanf is a wrapper around STDIN.scanf. IO#scanf
can be used on any IO stream, including file handles and sockets.
scanf can be called either with or without a block.
scanf for Ruby scans an input string or stream according to a
<b>format</b>, as described below ("Conversions"), and returns an
array of matches between the format and the input. The format is
defined in a string, and is similar (though not identical) to the
formats used in Kernel#printf and Kernel#sprintf.
The format may contain <b>conversion specifiers</b>, which tell scanf
what form (type) each particular matched substring should be converted
to (e.g., decimal integer, floating point number, literal string,
etc.) The matches and conversions take place from left to right, and
the conversions themselves are returned as an array.
The format string may also contain characters other than those in the
conversion specifiers. White space (blanks, tabs, or newlines) in the
format string matches any amount of white space, including none, in
the input. Everything else matches only itself.
Scanning stops, and scanf returns, when any input character fails to
match the specifications in the format string, or when input is
exhausted, or when everything in the format string has been
matched. All matches found up to the stopping point are returned in
the return array (or yielded to the block, if a block was given).
==Basic usage
require 'scanf.rb'
# String#scanf and IO#scanf take a single argument (a format string)
array = aString.scanf("%d%s")
array = anIO.scanf("%d%s")
# Kernel#scanf reads from STDIN
array = scanf("%d%s")
==Block usage
When called with a block, scanf keeps scanning the input, cycling back
to the beginning of the format string, and yields a new array of
conversions to the block every time the format string is matched
(including partial matches, but not including complete failures). The
actual return value of scanf when called with a block is an array
containing the results of all the executions of the block.
str = "123 abc 456 def 789 ghi"
str.scanf("%d%s") { |num,str| [ num * 2, str.upcase ] }
# => [[246, "ABC"], [912, "DEF"], [1578, "GHI"]]
==Conversions
The single argument to scanf is a format string, which generally
includes one or more conversion specifiers. Conversion specifiers
begin with the percent character ('%') and include information about
what scanf should next scan for (string, decimal number, single
character, etc.).
There may be an optional maximum field width, expressed as a decimal
integer, between the % and the conversion. If no width is given, a
default of `infinity' is used (with the exception of the %c specifier;
see below). Otherwise, given a field width of <em>n</em> for a given
conversion, at most <em>n</em> characters are scanned in processing
that conversion. Before conversion begins, most conversions skip
white space in the input string; this white space is not counted
against the field width.
The following conversions are available. (See the files EXAMPLES
and <tt>tests/scanftests.rb</tt> for examples.)
[%]
Matches a literal `%'. That is, `%%' in the format string matches a
single input `%' character. No conversion is done, and the resulting
'%' is not included in the return array.
[d]
Matches an optionally signed decimal integer.
[u]
Same as d.
[i]
Matches an optionally signed integer. The integer is read in base
16 if it begins with `0x' or `0X', in base 8 if it begins with `0',
and in base 10 other- wise. Only characters that correspond to the
base are recognized.
[o]
Matches an optionally signed octal integer.
[x,X]
Matches an optionally signed hexadecimal integer,
[f,g,e,E]
Matches an optionally signed floating-point number.
[s]
Matches a sequence of non-white-space character. The input string stops at
white space or at the maximum field width, whichever occurs first.
[c]
Matches a single character, or a sequence of <em>n</em> characters if a
field width of <em>n</em> is specified. The usual skip of leading white
space is suppressed. To skip white space first, use an explicit space in
the format.
[<tt>[</tt>]
Matches a nonempty sequence of characters from the specified set
of accepted characters. The usual skip of leading white space is
suppressed. This bracketed sub-expression is interpreted exactly like a
character class in a Ruby regular expression. (In fact, it is placed as-is
in a regular expression.) The matching against the input string ends with
the appearance of a character not in (or, with a circumflex, in) the set,
or when the field width runs out, whichever comes first.
===Assignment suppression
To require that a particular match occur, but without including the result
in the return array, place the <b>assignment suppression flag</b>, which is
the star character ('*'), immediately after the leading '%' of a format
specifier (just before the field width, if any).
==Examples
See the files <tt>EXAMPLES</tt> and <tt>tests/scanftests.rb</tt>.
==scanf for Ruby compared with scanf in C
scanf for Ruby is based on the C function scanf(3), but with modifications,
dictated mainly by the underlying differences between the languages.
===Unimplemented flags and specifiers
* The only flag implemented in scanf for Ruby is '<tt>*</tt>' (ignore
upcoming conversion). Many of the flags available in C versions of scanf(4)
have to do with the type of upcoming pointer arguments, and are literally
meaningless in Ruby.
* The <tt>n</tt> specifier (store number of characters consumed so far in
next pointer) is not implemented.
* The <tt>p</tt> specifier (match a pointer value) is not implemented.
===Altered specifiers
[o,u,x,X]
In scanf for Ruby, all of these specifiers scan for an optionally signed
integer, rather than for an unsigned integer like their C counterparts.
===Return values
scanf for Ruby returns an array of successful conversions, whereas
scanf(3) returns the number of conversions successfully
completed. (See below for more details on scanf for Ruby's return
values.)
==Return values
Without a block, scanf returns an array containing all the conversions
it has found. If none are found, scanf will return an empty array. An
unsuccesful match is never ignored, but rather always signals the end
of the scanning operation. If the first unsuccessful match takes place
after one or more successful matches have already taken place, the
returned array will contain the results of those successful matches.
With a block scanf returns a 'map'-like array of transformations from
the block -- that is, an array reflecting what the block did with each
yielded result from the iterative scanf operation. (See "Block
usage", above.)
==Test suite
scanf for Ruby includes a suite of unit tests (requiring the
<tt>TestUnit</tt> package), which can be run with the command <tt>ruby
tests/scanftests.rb</tt> or the command <tt>make test</tt>.
==Current limitations and bugs
When using IO#scanf under Windows, make sure you open your files in
binary mode:
File.open("filename", "rb")
so that scanf can keep track of characters correctly.
Support for character classes is reasonably complete (since it
essentially piggy-backs on Ruby's regular expression handling of
character classes), but users are advised that character class testing
has not been exhaustive, and that they should exercise some caution
in using any of the more complex and/or arcane character class
idioms.
==Technical notes
===Rationale behind scanf for Ruby
The impetus for a scanf implementation in Ruby comes chiefly from the fact
that existing pattern matching operations, such as Regexp#match and
String#scan, return all results as strings, which have to be converted to
integers or floats explicitly in cases where what's ultimately wanted are
integer or float values.
===Design of scanf for Ruby
scanf for Ruby is essentially a <format string>-to-<regular
expression> converter.
When scanf is called, a FormatString object is generated from the
format string ("%d%s...") argument. The FormatString object breaks the
format string down into atoms ("%d", "%5f", "blah", etc.), and from
each atom it creates a FormatSpecifier object, which it
saves.
Each FormatSpecifier has a regular expression fragment and a "handler"
associated with it. For example, the regular expression fragment
associated with the format "%d" is "([-+]?\d+)", and the handler
associated with it is a wrapper around String#to_i. scanf itself calls
FormatString#match, passing in the input string. FormatString#match
iterates through its FormatSpecifiers; for each one, it matches the
corresponding regular expression fragment against the string. If
there's a match, it sends the matched string to the handler associated
with the FormatSpecifier.
Thus, to follow up the "%d" example: if "123" occurs in the input
string when a FormatSpecifier consisting of "%d" is reached, the "123"
will be matched against "([-+]?\d+)", and the matched string will be
rendered into an integer by a call to to_i.
The rendered match is then saved to an accumulator array, and the
input string is reduced to the post-match substring. Thus the string
is "eaten" from the left as the FormatSpecifiers are applied in
sequence. (This is done to a duplicate string; the original string is
not altered.)
As soon as a regular expression fragment fails to match the string, or
when the FormatString object runs out of FormatSpecifiers, scanning
stops and results accumulated so far are returned in an array.
==License and copyright
Copyright:: (c) 2002-2003 David Alan Black
License:: Distributed on the same licensing terms as Ruby itself
==Warranty disclaimer
This software is provided "as is" and without any express or implied
warranties, including, without limitation, the implied warranties of
merchantibility and fitness for a particular purpose.
==Credits and acknowledgements
scanf for Ruby was developed as the major activity of the Austin
Ruby Codefest (Austin, Texas, August 2002).
Principal author:: David Alan Black (mailto:dblack@superlink.net)
Co-author:: Hal Fulton (mailto:hal9000@hypermetrics.com)
Project contributors:: Nolan Darilek, Jason Johnston
Thanks to Hal Fulton for hosting the Codefest.
Thanks to Matz for suggestions about the class design.
Thanks to Gavin Sinclair for some feedback on the documentation.
The text for parts of this document, especially the Description and
Conversions sections, above, were adapted from the Linux Programmer's
Manual manpage for scanf(3), dated 1995-11-01.
==Bugs and bug reports
scanf for Ruby is based on something of an amalgam of C scanf
implementations and documentation, rather than on a single canonical
description. Suggestions for features and behaviors which appear in
other scanfs, and would be meaningful in Ruby, are welcome, as are
reports of suspicious behaviors and/or bugs. (Please see "Credits and
acknowledgements", above, for email addresses.)
=end
module Scanf
class FormatSpecifier
attr_reader :re_string, :matched_string, :conversion, :matched
private
def skip; /^\s*%\*/.match(@spec_string); end
def extract_float(s); s.to_f if s &&! skip; end
def extract_decimal(s); s.to_i if s &&! skip; end
def extract_hex(s); s.hex if s &&! skip; end
def extract_octal(s); s.oct if s &&! skip; end
def extract_integer(s); Integer(s) if s &&! skip; end
def extract_plain(s); s unless skip; end
def nil_proc(s); nil; end
public
def to_s
@spec_string
end
def count_space?
/(?:\A|\S)%\*?\d*c|%\d*\[/.match(@spec_string)
end
def initialize(str)
@spec_string = str
h = '[A-Fa-f0-9]'
@re_string, @handler =
case @spec_string
# %[[:...:]]
when /%\*?(\[\[:[a-z]+:\]\])/
[ "(#{$1}+)", :extract_plain ]
# %5[[:...:]]
when /%\*?(\d+)(\[\[:[a-z]+:\]\])/
[ "(#{$2}{1,#{$1}})", :extract_plain ]
# %[...]
when /%\*?\[([^\]]*)\]/
yes = $1
if /^\^/.match(yes) then no = yes[1..-1] else no = '^' + yes end
[ "([#{yes}]+)(?=[#{no}]|\\z)", :extract_plain ]
# %5[...]
when /%\*?(\d+)\[([^\]]*)\]/
yes = $2
w = $1
[ "([#{yes}]{1,#{w}})", :extract_plain ]
# %i
when /%\*?i/
[ "([-+]?(?:(?:0[0-7]+)|(?:0[Xx]#{h}+)|(?:[1-9]\\d*)))", :extract_integer ]
# %5i
when /%\*?(\d+)i/
n = $1.to_i
s = "("
if n > 1 then s += "[1-9]\\d{1,#{n-1}}|" end
if n > 1 then s += "0[0-7]{1,#{n-1}}|" end
if n > 2 then s += "[-+]0[0-7]{1,#{n-2}}|" end
if n > 2 then s += "[-+][1-9]\\d{1,#{n-2}}|" end
if n > 2 then s += "0[Xx]#{h}{1,#{n-2}}|" end
if n > 3 then s += "[-+]0[Xx]#{h}{1,#{n-3}}|" end
s += "\\d"
s += ")"
[ s, :extract_integer ]
# %d, %u
when /%\*?[du]/
[ '([-+]?\d+)', :extract_decimal ]
# %5d, %5u
when /%\*?(\d+)[du]/
n = $1.to_i
s = "("
if n > 1 then s += "[-+]\\d{1,#{n-1}}|" end
s += "\\d{1,#{$1}})"
[ s, :extract_decimal ]
# %x
when /%\*?[Xx]/
[ "([-+]?(?:0[Xx])?#{h}+)", :extract_hex ]
# %5x
when /%\*?(\d+)[Xx]/
n = $1.to_i
s = "("
if n > 3 then s += "[-+]0[Xx]#{h}{1,#{n-3}}|" end
if n > 2 then s += "0[Xx]#{h}{1,#{n-2}}|" end
if n > 1 then s += "[-+]#{h}{1,#{n-1}}|" end
s += "#{h}{1,#{n}}"
s += ")"
[ s, :extract_hex ]
# %o
when /%\*?o/
[ '([-+]?[0-7]+)', :extract_octal ]
# %5o
when /%\*?(\d+)o/
[ "([-+][0-7]{1,#{$1.to_i-1}}|[0-7]{1,#{$1}})", :extract_octal ]
# %f
when /%\*?f/
[ '([-+]?((\d+(?>(?=[^\d.]|$)))|(\d*(\.(\d*([eE][-+]?\d+)?)))))', :extract_float ]
# %5f
when /%\*?(\d+)f/
[ "(\\S{1,#{$1}})", :extract_float ]
# %5s
when /%\*?(\d+)s/
[ "(\\S{1,#{$1}})", :extract_plain ]
# %s
when /%\*?s/
[ '(\S+)', :extract_plain ]
# %c
when /\s%\*?c/
[ "\\s*(.)", :extract_plain ]
# %c
when /%\*?c/
[ "(.)", :extract_plain ]
# %5c (whitespace issues are handled by the count_*_space? methods)
when /%\*?(\d+)c/
[ "(.{1,#{$1}})", :extract_plain ]
# %%
when /%%/
[ '(\s*%)', :nil_proc ]
# literal characters
else
[ "(#{Regexp.escape(@spec_string)})", :nil_proc ]
end
@re_string = '\A' + @re_string
end
def to_re
Regexp.new(@re_string,Regexp::MULTILINE)
end
def match(str)
@matched = false
s = str.dup
s.sub!(/\A\s+/,'') unless count_space?
res = to_re.match(s)
if res
@conversion = send(@handler, res[1])
@matched_string = @conversion.to_s
@matched = true
end
res
end
def letter
@spec_string[/%\*?\d*([a-z\[])/, 1]
end
def width
w = @spec_string[/%\*?(\d+)/, 1]
w && w.to_i
end
def mid_match?
return false unless @matched
cc_no_width = letter == '[' &&! width
c_or_cc_width = (letter == 'c' || letter == '[') && width
width_left = c_or_cc_width && (matched_string.size < width)
return width_left || cc_no_width
end
end
class FormatString
attr_reader :string_left, :last_spec_tried,
:last_match_tried, :matched_count, :space
SPECIFIERS = 'diuXxofeEgsc'
REGEX = /
# possible space, followed by...
(?:\s*
# percent sign, followed by...
%
# another percent sign, or...
(?:%|
# optional assignment suppression flag
\*?
# optional maximum field width
\d*
# named character class, ...
(?:\[\[:\w+:\]\]|
# traditional character class, or...
\[[^\]]*\]|
# specifier letter.
[#{SPECIFIERS}])))|
# or miscellaneous characters
[^%\s]+/ix
def initialize(str)
@specs = []
@i = 1
s = str.to_s
return unless /\S/.match(s)
@space = true if /\s\z/.match(s)
@specs.replace s.scan(REGEX).map {|spec| FormatSpecifier.new(spec) }
end
def to_s
@specs.join('')
end
def prune(n=matched_count)
n.times { @specs.shift }
end
def spec_count
@specs.size
end
def last_spec
@i == spec_count - 1
end
def match(str)
accum = []
@string_left = str
@matched_count = 0
@specs.each_with_index do |spec,i|
@i=i
@last_spec_tried = spec
@last_match_tried = spec.match(@string_left)
break unless @last_match_tried
@matched_count += 1
accum << spec.conversion
@string_left = @last_match_tried.post_match
break if @string_left.empty?
end
return accum.compact
end
end
end
class IO
# The trick here is doing a match where you grab one *line*
# of input at a time. The linebreak may or may not occur
# at the boundary where the string matches a format specifier.
# And if it does, some rule about whitespace may or may not
# be in effect...
#
# That's why this is much more elaborate than the string
# version.
#
# For each line:
# Match succeeds (non-emptily)
# and the last attempted spec/string sub-match succeeded:
#
# could the last spec keep matching?
# yes: save interim results and continue (next line)
#
# The last attempted spec/string did not match:
#
# are we on the next-to-last spec in the string?
# yes:
# is fmt_string.string_left all spaces?
# yes: does current spec care about input space?
# yes: fatal failure
# no: save interim results and continue
# no: continue [this state could be analyzed further]
#
#
def scanf(str,&b)
return block_scanf(str,&b) if b
return [] unless str.size > 0
start_position = pos rescue 0
matched_so_far = 0
source_buffer = ""
result_buffer = []
final_result = []
fstr = Scanf::FormatString.new(str)
loop do
if eof || (tty? &&! fstr.match(source_buffer))
final_result.concat(result_buffer)
break
end
source_buffer << gets
current_match = fstr.match(source_buffer)
spec = fstr.last_spec_tried
if spec.matched
if spec.mid_match?
result_buffer.replace(current_match)
next
end
elsif (fstr.matched_count == fstr.spec_count - 1)
if /\A\s*\z/.match(fstr.string_left)
break if spec.count_space?
result_buffer.replace(current_match)
next
end
end
final_result.concat(current_match)
matched_so_far += source_buffer.size
source_buffer.replace(fstr.string_left)
matched_so_far -= source_buffer.size
break if fstr.last_spec
fstr.prune
end
seek(start_position + matched_so_far, IO::SEEK_SET) rescue Errno::ESPIPE
soak_up_spaces if fstr.last_spec && fstr.space
return final_result
end
private
def soak_up_spaces
c = getc
ungetc(c) if c
until eof ||! c || /\S/.match(c.chr)
c = getc
end
ungetc(c) if (c && /\S/.match(c.chr))
end
def block_scanf(str)
final = []
# Sub-ideal, since another FS gets created in scanf.
# But used here to determine the number of specifiers.
fstr = Scanf::FormatString.new(str)
last_spec = fstr.last_spec
begin
current = scanf(str)
break if current.empty?
final.push(yield(current))
end until eof || fstr.last_spec_tried == last_spec
return final
end
end
class String
def scanf(fstr,&b)
if b
block_scanf(fstr,&b)
else
fs =
if fstr.is_a? Scanf::FormatString
fstr
else
Scanf::FormatString.new(fstr)
end
fs.match(self)
end
end
def block_scanf(fstr,&b)
fs = Scanf::FormatString.new(fstr)
str = self.dup
final = []
begin
current = str.scanf(fs)
final.push(yield(current)) unless current.empty?
str = fs.string_left
end until current.empty? || str.empty?
return final
end
end
module Kernel
private
def scanf(fs,&b)
STDIN.scanf(fs,&b)
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/mutex_m.rb | tools/jruby-1.5.1/lib/ruby/1.9/mutex_m.rb | #
# mutex_m.rb -
# $Release Version: 3.0$
# $Revision: 1.7 $
# Original from mutex.rb
# by Keiju ISHITSUKA(keiju@ishitsuka.com)
# modified by matz
# patched by akira yamada
#
# --
# Usage:
# require "mutex_m.rb"
# obj = Object.new
# obj.extend Mutex_m
# ...
# extended object can be handled like Mutex
# or
# class Foo
# include Mutex_m
# ...
# end
# obj = Foo.new
# this obj can be handled like Mutex
#
require 'thread'
module Mutex_m
def Mutex_m.define_aliases(cl)
cl.module_eval %q{
alias locked? mu_locked?
alias lock mu_lock
alias unlock mu_unlock
alias try_lock mu_try_lock
alias synchronize mu_synchronize
}
end
def Mutex_m.append_features(cl)
super
define_aliases(cl) unless cl.instance_of?(Module)
end
def Mutex_m.extend_object(obj)
super
obj.mu_extended
end
def mu_extended
unless (defined? locked? and
defined? lock and
defined? unlock and
defined? try_lock and
defined? synchronize)
Mutex_m.define_aliases(class<<self;self;end)
end
mu_initialize
end
# locking
def mu_synchronize(&block)
@_mutex.synchronize(&block)
end
def mu_locked?
@_mutex.locked?
end
def mu_try_lock
@_mutex.try_lock
end
def mu_lock
@_mutex.lock
end
def mu_unlock
@_mutex.unlock
end
private
def mu_initialize
@_mutex = Mutex.new
end
def initialize(*args)
mu_initialize
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/1.9/cgi.rb | tools/jruby-1.5.1/lib/ruby/1.9/cgi.rb | #
# cgi.rb - cgi support library
#
# Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
#
# Copyright (C) 2000 Information-technology Promotion Agency, Japan
#
# Author: Wakou Aoyama <wakou@ruby-lang.org>
#
# Documentation: Wakou Aoyama (RDoc'd and embellished by William Webber)
#
# == Overview
#
# The Common Gateway Interface (CGI) is a simple protocol
# for passing an HTTP request from a web server to a
# standalone program, and returning the output to the web
# browser. Basically, a CGI program is called with the
# parameters of the request passed in either in the
# environment (GET) or via $stdin (POST), and everything
# it prints to $stdout is returned to the client.
#
# This file holds the +CGI+ class. This class provides
# functionality for retrieving HTTP request parameters,
# managing cookies, and generating HTML output. See the
# class documentation for more details and examples of use.
#
# The file cgi/session.rb provides session management
# functionality; see that file for more details.
#
# See http://www.w3.org/CGI/ for more information on the CGI
# protocol.
raise "Please, use ruby 1.9.0 or later." if RUBY_VERSION < "1.9.0"
# CGI class. See documentation for the file cgi.rb for an overview
# of the CGI protocol.
#
# == Introduction
#
# CGI is a large class, providing several categories of methods, many of which
# are mixed in from other modules. Some of the documentation is in this class,
# some in the modules CGI::QueryExtension and CGI::HtmlExtension. See
# CGI::Cookie for specific information on handling cookies, and cgi/session.rb
# (CGI::Session) for information on sessions.
#
# For queries, CGI provides methods to get at environmental variables,
# parameters, cookies, and multipart request data. For responses, CGI provides
# methods for writing output and generating HTML.
#
# Read on for more details. Examples are provided at the bottom.
#
# == Queries
#
# The CGI class dynamically mixes in parameter and cookie-parsing
# functionality, environmental variable access, and support for
# parsing multipart requests (including uploaded files) from the
# CGI::QueryExtension module.
#
# === Environmental Variables
#
# The standard CGI environmental variables are available as read-only
# attributes of a CGI object. The following is a list of these variables:
#
#
# AUTH_TYPE HTTP_HOST REMOTE_IDENT
# CONTENT_LENGTH HTTP_NEGOTIATE REMOTE_USER
# CONTENT_TYPE HTTP_PRAGMA REQUEST_METHOD
# GATEWAY_INTERFACE HTTP_REFERER SCRIPT_NAME
# HTTP_ACCEPT HTTP_USER_AGENT SERVER_NAME
# HTTP_ACCEPT_CHARSET PATH_INFO SERVER_PORT
# HTTP_ACCEPT_ENCODING PATH_TRANSLATED SERVER_PROTOCOL
# HTTP_ACCEPT_LANGUAGE QUERY_STRING SERVER_SOFTWARE
# HTTP_CACHE_CONTROL REMOTE_ADDR
# HTTP_FROM REMOTE_HOST
#
#
# For each of these variables, there is a corresponding attribute with the
# same name, except all lower case and without a preceding HTTP_.
# +content_length+ and +server_port+ are integers; the rest are strings.
#
# === Parameters
#
# The method #params() returns a hash of all parameters in the request as
# name/value-list pairs, where the value-list is an Array of one or more
# values. The CGI object itself also behaves as a hash of parameter names
# to values, but only returns a single value (as a String) for each
# parameter name.
#
# For instance, suppose the request contains the parameter
# "favourite_colours" with the multiple values "blue" and "green". The
# following behaviour would occur:
#
# cgi.params["favourite_colours"] # => ["blue", "green"]
# cgi["favourite_colours"] # => "blue"
#
# If a parameter does not exist, the former method will return an empty
# array, the latter an empty string. The simplest way to test for existence
# of a parameter is by the #has_key? method.
#
# === Cookies
#
# HTTP Cookies are automatically parsed from the request. They are available
# from the #cookies() accessor, which returns a hash from cookie name to
# CGI::Cookie object.
#
# === Multipart requests
#
# If a request's method is POST and its content type is multipart/form-data,
# then it may contain uploaded files. These are stored by the QueryExtension
# module in the parameters of the request. The parameter name is the name
# attribute of the file input field, as usual. However, the value is not
# a string, but an IO object, either an IOString for small files, or a
# Tempfile for larger ones. This object also has the additional singleton
# methods:
#
# #local_path():: the path of the uploaded file on the local filesystem
# #original_filename():: the name of the file on the client computer
# #content_type():: the content type of the file
#
# == Responses
#
# The CGI class provides methods for sending header and content output to
# the HTTP client, and mixes in methods for programmatic HTML generation
# from CGI::HtmlExtension and CGI::TagMaker modules. The precise version of HTML
# to use for HTML generation is specified at object creation time.
#
# === Writing output
#
# The simplest way to send output to the HTTP client is using the #out() method.
# This takes the HTTP headers as a hash parameter, and the body content
# via a block. The headers can be generated as a string using the #header()
# method. The output stream can be written directly to using the #print()
# method.
#
# === Generating HTML
#
# Each HTML element has a corresponding method for generating that
# element as a String. The name of this method is the same as that
# of the element, all lowercase. The attributes of the element are
# passed in as a hash, and the body as a no-argument block that evaluates
# to a String. The HTML generation module knows which elements are
# always empty, and silently drops any passed-in body. It also knows
# which elements require matching closing tags and which don't. However,
# it does not know what attributes are legal for which elements.
#
# There are also some additional HTML generation methods mixed in from
# the CGI::HtmlExtension module. These include individual methods for the
# different types of form inputs, and methods for elements that commonly
# take particular attributes where the attributes can be directly specified
# as arguments, rather than via a hash.
#
# == Examples of use
#
# === Get form values
#
# require "cgi"
# cgi = CGI.new
# value = cgi['field_name'] # <== value string for 'field_name'
# # if not 'field_name' included, then return "".
# fields = cgi.keys # <== array of field names
#
# # returns true if form has 'field_name'
# cgi.has_key?('field_name')
# cgi.has_key?('field_name')
# cgi.include?('field_name')
#
# CAUTION! cgi['field_name'] returned an Array with the old
# cgi.rb(included in ruby 1.6)
#
# === Get form values as hash
#
# require "cgi"
# cgi = CGI.new
# params = cgi.params
#
# cgi.params is a hash.
#
# cgi.params['new_field_name'] = ["value"] # add new param
# cgi.params['field_name'] = ["new_value"] # change value
# cgi.params.delete('field_name') # delete param
# cgi.params.clear # delete all params
#
#
# === Save form values to file
#
# require "pstore"
# db = PStore.new("query.db")
# db.transaction do
# db["params"] = cgi.params
# end
#
#
# === Restore form values from file
#
# require "pstore"
# db = PStore.new("query.db")
# db.transaction do
# cgi.params = db["params"]
# end
#
#
# === Get multipart form values
#
# require "cgi"
# cgi = CGI.new
# value = cgi['field_name'] # <== value string for 'field_name'
# value.read # <== body of value
# value.local_path # <== path to local file of value
# value.original_filename # <== original filename of value
# value.content_type # <== content_type of value
#
# and value has StringIO or Tempfile class methods.
#
# === Get cookie values
#
# require "cgi"
# cgi = CGI.new
# values = cgi.cookies['name'] # <== array of 'name'
# # if not 'name' included, then return [].
# names = cgi.cookies.keys # <== array of cookie names
#
# and cgi.cookies is a hash.
#
# === Get cookie objects
#
# require "cgi"
# cgi = CGI.new
# for name, cookie in cgi.cookies
# cookie.expires = Time.now + 30
# end
# cgi.out("cookie" => cgi.cookies) {"string"}
#
# cgi.cookies # { "name1" => cookie1, "name2" => cookie2, ... }
#
# require "cgi"
# cgi = CGI.new
# cgi.cookies['name'].expires = Time.now + 30
# cgi.out("cookie" => cgi.cookies['name']) {"string"}
#
# === Print http header and html string to $DEFAULT_OUTPUT ($>)
#
# require "cgi"
# cgi = CGI.new("html3") # add HTML generation methods
# cgi.out() do
# cgi.html() do
# cgi.head{ cgi.title{"TITLE"} } +
# cgi.body() do
# cgi.form() do
# cgi.textarea("get_text") +
# cgi.br +
# cgi.submit
# end +
# cgi.pre() do
# CGI::escapeHTML(
# "params: " + cgi.params.inspect + "\n" +
# "cookies: " + cgi.cookies.inspect + "\n" +
# ENV.collect() do |key, value|
# key + " --> " + value + "\n"
# end.join("")
# )
# end
# end
# end
# end
#
# # add HTML generation methods
# CGI.new("html3") # html3.2
# CGI.new("html4") # html4.01 (Strict)
# CGI.new("html4Tr") # html4.01 Transitional
# CGI.new("html4Fr") # html4.01 Frameset
#
require 'cgi/core'
require 'cgi/cookie'
require 'cgi/util'
| 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/tmpdir.rb | tools/jruby-1.5.1/lib/ruby/1.9/tmpdir.rb | #
# tmpdir - retrieve temporary directory path
#
# $Id: tmpdir.rb 23661 2009-06-10 09:15:55Z usa $
#
require 'fileutils'
class Dir
@@systmpdir = '/tmp'
begin
require 'Win32API'
CSIDL_LOCAL_APPDATA = 0x001c
max_pathlen = 260
windir = "\0"*(max_pathlen+1)
begin
getdir = Win32API.new('shell32', 'SHGetFolderPath', 'LLLLP', 'L')
raise RuntimeError if getdir.call(0, CSIDL_LOCAL_APPDATA, 0, 0, windir) != 0
windir.rstrip!
rescue RuntimeError
begin
getdir = Win32API.new('kernel32', 'GetSystemWindowsDirectory', 'PL', 'L')
rescue RuntimeError
getdir = Win32API.new('kernel32', 'GetWindowsDirectory', 'PL', 'L')
end
windir[getdir.call(windir, windir.size)..-1] = ""
end
windir.force_encoding(Dir.pwd.encoding)
temp = File.expand_path('temp', windir.untaint)
@@systmpdir = temp if File.directory?(temp) and File.writable?(temp)
rescue LoadError
end
##
# Returns the operating system's temporary file path.
def Dir::tmpdir
tmp = '.'
if $SAFE > 0
tmp = @@systmpdir
else
for dir in [ENV['TMPDIR'], ENV['TMP'], ENV['TEMP'], @@systmpdir, '/tmp']
if dir and stat = File.stat(dir) and stat.directory? and stat.writable?
tmp = dir
break
end rescue nil
end
File.expand_path(tmp)
end
end
# Dir.mktmpdir creates a temporary directory.
#
# The directory is created with 0700 permission.
#
# The prefix and suffix of the name of the directory is specified by
# the optional first argument, <i>prefix_suffix</i>.
# - If it is not specified or nil, "d" is used as the prefix and no suffix is used.
# - If it is a string, it is used as the prefix and no suffix is used.
# - If it is an array, first element is used as the prefix and second element is used as a suffix.
#
# Dir.mktmpdir {|dir| dir is ".../d..." }
# Dir.mktmpdir("foo") {|dir| dir is ".../foo..." }
# Dir.mktmpdir(["foo", "bar"]) {|dir| dir is ".../foo...bar" }
#
# The directory is created under Dir.tmpdir or
# the optional second argument <i>tmpdir</i> if non-nil value is given.
#
# Dir.mktmpdir {|dir| dir is "#{Dir.tmpdir}/d..." }
# Dir.mktmpdir(nil, "/var/tmp") {|dir| dir is "/var/tmp/d..." }
#
# If a block is given,
# it is yielded with the path of the directory.
# The directory and its contents are removed
# using FileUtils.remove_entry_secure before Dir.mktmpdir returns.
# The value of the block is returned.
#
# Dir.mktmpdir {|dir|
# # use the directory...
# open("#{dir}/foo", "w") { ... }
# }
#
# If a block is not given,
# The path of the directory is returned.
# In this case, Dir.mktmpdir doesn't remove the directory.
#
# dir = Dir.mktmpdir
# begin
# # use the directory...
# open("#{dir}/foo", "w") { ... }
# ensure
# # remove the directory.
# FileUtils.remove_entry_secure dir
# end
#
def Dir.mktmpdir(prefix_suffix=nil, tmpdir=nil)
case prefix_suffix
when nil
prefix = "d"
suffix = ""
when String
prefix = prefix_suffix
suffix = ""
when Array
prefix = prefix_suffix[0]
suffix = prefix_suffix[1]
else
raise ArgumentError, "unexpected prefix_suffix: #{prefix_suffix.inspect}"
end
tmpdir ||= Dir.tmpdir
t = Time.now.strftime("%Y%m%d")
n = nil
begin
path = "#{tmpdir}/#{prefix}#{t}-#{$$}-#{rand(0x100000000).to_s(36)}"
path << "-#{n}" if n
path << suffix
Dir.mkdir(path, 0700)
rescue Errno::EEXIST
n ||= 0
n += 1
retry
end
if block_given?
begin
yield path
ensure
FileUtils.remove_entry_secure path
end
else
path
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/rational.rb | tools/jruby-1.5.1/lib/ruby/1.9/rational.rb | # :enddoc:
warn('lib/rational.rb is deprecated') if $VERBOSE
class Fixnum
alias quof fdiv
alias rdiv quo
alias power! ** unless defined?(0.power!)
alias rpower **
end
class Bignum
alias quof fdiv
alias rdiv quo
alias power! ** unless defined?(0.power!)
alias rpower **
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/ipaddr.rb | tools/jruby-1.5.1/lib/ruby/1.9/ipaddr.rb | #
# ipaddr.rb - A class to manipulate an IP address
#
# Copyright (c) 2002 Hajimu UMEMOTO <ume@mahoroba.org>.
# Copyright (c) 2007 Akinori MUSHA <knu@iDaemons.org>.
# All rights reserved.
#
# You can redistribute and/or modify it under the same terms as Ruby.
#
# $Id: ipaddr.rb 24411 2009-08-05 15:13:07Z knu $
#
# Contact:
# - Akinori MUSHA <knu@iDaemons.org> (current maintainer)
#
# TODO:
# - scope_id support
#
require 'socket'
unless Socket.const_defined? "AF_INET6"
class Socket
AF_INET6 = Object.new
end
class << IPSocket
def valid_v4?(addr)
if /\A(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\Z/ =~ addr
return $~.captures.all? {|i| i.to_i < 256}
end
return false
end
def valid_v6?(addr)
# IPv6 (normal)
return true if /\A[\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*\Z/ =~ addr
return true if /\A[\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*::([\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*)?\Z/ =~ addr
return true if /\A::([\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*)?\Z/ =~ addr
# IPv6 (IPv4 compat)
return true if /\A[\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*:/ =~ addr && valid_v4?($')
return true if /\A[\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*::([\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*:)?/ =~ addr && valid_v4?($')
return true if /\A::([\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*:)?/ =~ addr && valid_v4?($')
false
end
def valid?(addr)
valid_v4?(addr) || valid_v6?(addr)
end
alias getaddress_orig getaddress
def getaddress(s)
if valid?(s)
s
elsif /\A[-A-Za-z\d.]+\Z/ =~ s
getaddress_orig(s)
else
raise ArgumentError, "invalid address"
end
end
end
end
# IPAddr provides a set of methods to manipulate an IP address. Both IPv4 and
# IPv6 are supported.
#
# == Example
#
# require 'ipaddr'
#
# ipaddr1 = IPAddr.new "3ffe:505:2::1"
#
# p ipaddr1 #=> #<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0001/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff>
#
# p ipaddr1.to_s #=> "3ffe:505:2::1"
#
# ipaddr2 = ipaddr1.mask(48) #=> #<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0000/ffff:ffff:ffff:0000:0000:0000:0000:0000>
#
# p ipaddr2.to_s #=> "3ffe:505:2::"
#
# ipaddr3 = IPAddr.new "192.168.2.0/24"
#
# p ipaddr3 #=> #<IPAddr: IPv4:192.168.2.0/255.255.255.0>
class IPAddr
IN4MASK = 0xffffffff
IN6MASK = 0xffffffffffffffffffffffffffffffff
IN6FORMAT = (["%.4x"] * 8).join(':')
# Returns the address family of this IP address.
attr_reader :family
# Creates a new ipaddr containing the given network byte ordered
# string form of an IP address.
def IPAddr::new_ntoh(addr)
return IPAddr.new(IPAddr::ntop(addr))
end
# Convert a network byte ordered string form of an IP address into
# human readable form.
def IPAddr::ntop(addr)
case addr.size
when 4
s = addr.unpack('C4').join('.')
when 16
s = IN6FORMAT % addr.unpack('n8')
else
raise ArgumentError, "unsupported address family"
end
return s
end
# Returns a new ipaddr built by bitwise AND.
def &(other)
return self.clone.set(@addr & coerce_other(other).to_i)
end
# Returns a new ipaddr built by bitwise OR.
def |(other)
return self.clone.set(@addr | coerce_other(other).to_i)
end
# Returns a new ipaddr built by bitwise right-shift.
def >>(num)
return self.clone.set(@addr >> num)
end
# Returns a new ipaddr built by bitwise left shift.
def <<(num)
return self.clone.set(addr_mask(@addr << num))
end
# Returns a new ipaddr built by bitwise negation.
def ~
return self.clone.set(addr_mask(~@addr))
end
# Returns true if two ipaddrs are equal.
def ==(other)
other = coerce_other(other)
return @family == other.family && @addr == other.to_i
end
# Returns a new ipaddr built by masking IP address with the given
# prefixlen/netmask. (e.g. 8, 64, "255.255.255.0", etc.)
def mask(prefixlen)
return self.clone.mask!(prefixlen)
end
# Returns true if the given ipaddr is in the range.
#
# e.g.:
# require 'ipaddr'
# net1 = IPAddr.new("192.168.2.0/24")
# net2 = IPAddr.new("192.168.2.100")
# net3 = IPAddr.new("192.168.3.0")
# p net1.include?(net2) #=> true
# p net1.include?(net3) #=> false
def include?(other)
other = coerce_other(other)
if ipv4_mapped?
if (@mask_addr >> 32) != 0xffffffffffffffffffffffff
return false
end
mask_addr = (@mask_addr & IN4MASK)
addr = (@addr & IN4MASK)
family = Socket::AF_INET
else
mask_addr = @mask_addr
addr = @addr
family = @family
end
if other.ipv4_mapped?
other_addr = (other.to_i & IN4MASK)
other_family = Socket::AF_INET
else
other_addr = other.to_i
other_family = other.family
end
if family != other_family
return false
end
return ((addr & mask_addr) == (other_addr & mask_addr))
end
alias === include?
# Returns the integer representation of the ipaddr.
def to_i
return @addr
end
# Returns a string containing the IP address representation.
def to_s
str = to_string
return str if ipv4?
str.gsub!(/\b0{1,3}([\da-f]+)\b/i, '\1')
loop do
break if str.sub!(/\A0:0:0:0:0:0:0:0\Z/, '::')
break if str.sub!(/\b0:0:0:0:0:0:0\b/, ':')
break if str.sub!(/\b0:0:0:0:0:0\b/, ':')
break if str.sub!(/\b0:0:0:0:0\b/, ':')
break if str.sub!(/\b0:0:0:0\b/, ':')
break if str.sub!(/\b0:0:0\b/, ':')
break if str.sub!(/\b0:0\b/, ':')
break
end
str.sub!(/:{3,}/, '::')
if /\A::(ffff:)?([\da-f]{1,4}):([\da-f]{1,4})\Z/i =~ str
str = sprintf('::%s%d.%d.%d.%d', $1, $2.hex / 256, $2.hex % 256, $3.hex / 256, $3.hex % 256)
end
str
end
# Returns a string containing the IP address representation in
# canonical form.
def to_string
return _to_string(@addr)
end
# Returns a network byte ordered string form of the IP address.
def hton
case @family
when Socket::AF_INET
return [@addr].pack('N')
when Socket::AF_INET6
return (0..7).map { |i|
(@addr >> (112 - 16 * i)) & 0xffff
}.pack('n8')
else
raise "unsupported address family"
end
end
# Returns true if the ipaddr is an IPv4 address.
def ipv4?
return @family == Socket::AF_INET
end
# Returns true if the ipaddr is an IPv6 address.
def ipv6?
return @family == Socket::AF_INET6
end
# Returns true if the ipaddr is an IPv4-mapped IPv6 address.
def ipv4_mapped?
return ipv6? && (@addr >> 32) == 0xffff
end
# Returns true if the ipaddr is an IPv4-compatible IPv6 address.
def ipv4_compat?
if !ipv6? || (@addr >> 32) != 0
return false
end
a = (@addr & IN4MASK)
return a != 0 && a != 1
end
# Returns a new ipaddr built by converting the native IPv4 address
# into an IPv4-mapped IPv6 address.
def ipv4_mapped
if !ipv4?
raise ArgumentError, "not an IPv4 address"
end
return self.clone.set(@addr | 0xffff00000000, Socket::AF_INET6)
end
# Returns a new ipaddr built by converting the native IPv4 address
# into an IPv4-compatible IPv6 address.
def ipv4_compat
if !ipv4?
raise ArgumentError, "not an IPv4 address"
end
return self.clone.set(@addr, Socket::AF_INET6)
end
# Returns a new ipaddr built by converting the IPv6 address into a
# native IPv4 address. If the IP address is not an IPv4-mapped or
# IPv4-compatible IPv6 address, returns self.
def native
if !ipv4_mapped? && !ipv4_compat?
return self
end
return self.clone.set(@addr & IN4MASK, Socket::AF_INET)
end
# Returns a string for DNS reverse lookup. It returns a string in
# RFC3172 form for an IPv6 address.
def reverse
case @family
when Socket::AF_INET
return _reverse + ".in-addr.arpa"
when Socket::AF_INET6
return ip6_arpa
else
raise "unsupported address family"
end
end
# Returns a string for DNS reverse lookup compatible with RFC3172.
def ip6_arpa
if !ipv6?
raise ArgumentError, "not an IPv6 address"
end
return _reverse + ".ip6.arpa"
end
# Returns a string for DNS reverse lookup compatible with RFC1886.
def ip6_int
if !ipv6?
raise ArgumentError, "not an IPv6 address"
end
return _reverse + ".ip6.int"
end
# Returns the successor to the ipaddr.
def succ
return self.clone.set(@addr + 1, @family)
end
# Compares the ipaddr with another.
def <=>(other)
other = coerce_other(other)
return nil if other.family != @family
return @addr <=> other.to_i
end
include Comparable
# Checks equality used by Hash.
def eql?(other)
return self.class == other.class && self.hash == other.hash && self == other
end
# Returns a hash value used by Hash, Set, and Array classes
def hash
return ([@addr, @mask_addr].hash << 1) | (ipv4? ? 0 : 1)
end
# Creates a Range object for the network address.
def to_range
begin_addr = (@addr & @mask_addr)
case @family
when Socket::AF_INET
end_addr = (@addr | (IN4MASK ^ @mask_addr))
when Socket::AF_INET6
end_addr = (@addr | (IN6MASK ^ @mask_addr))
else
raise "unsupported address family"
end
return clone.set(begin_addr, @family)..clone.set(end_addr, @family)
end
# Returns a string containing a human-readable representation of the
# ipaddr. ("#<IPAddr: family:address/mask>")
def inspect
case @family
when Socket::AF_INET
af = "IPv4"
when Socket::AF_INET6
af = "IPv6"
else
raise "unsupported address family"
end
return sprintf("#<%s: %s:%s/%s>", self.class.name,
af, _to_string(@addr), _to_string(@mask_addr))
end
protected
def set(addr, *family)
case family[0] ? family[0] : @family
when Socket::AF_INET
if addr < 0 || addr > IN4MASK
raise ArgumentError, "invalid address"
end
when Socket::AF_INET6
if addr < 0 || addr > IN6MASK
raise ArgumentError, "invalid address"
end
else
raise ArgumentError, "unsupported address family"
end
@addr = addr
if family[0]
@family = family[0]
end
return self
end
def mask!(mask)
if mask.kind_of?(String)
if mask =~ /^\d+$/
prefixlen = mask.to_i
else
m = IPAddr.new(mask)
if m.family != @family
raise ArgumentError, "address family is not same"
end
@mask_addr = m.to_i
@addr &= @mask_addr
return self
end
else
prefixlen = mask
end
case @family
when Socket::AF_INET
if prefixlen < 0 || prefixlen > 32
raise ArgumentError, "invalid length"
end
masklen = 32 - prefixlen
@mask_addr = ((IN4MASK >> masklen) << masklen)
when Socket::AF_INET6
if prefixlen < 0 || prefixlen > 128
raise ArgumentError, "invalid length"
end
masklen = 128 - prefixlen
@mask_addr = ((IN6MASK >> masklen) << masklen)
else
raise "unsupported address family"
end
@addr = ((@addr >> masklen) << masklen)
return self
end
private
# Creates a new ipaddr object either from a human readable IP
# address representation in string, or from a packed in_addr value
# followed by an address family.
#
# In the former case, the following are the valid formats that will
# be recognized: "address", "address/prefixlen" and "address/mask",
# where IPv6 address may be enclosed in square brackets (`[' and
# `]'). If a prefixlen or a mask is specified, it returns a masked
# IP address. Although the address family is determined
# automatically from a specified string, you can specify one
# explicitly by the optional second argument.
#
# Otherwise an IP addess is generated from a packed in_addr value
# and an address family.
#
# The IPAddr class defines many methods and operators, and some of
# those, such as &, |, include? and ==, accept a string, or a packed
# in_addr value instead of an IPAddr object.
def initialize(addr = '::', family = Socket::AF_UNSPEC)
if !addr.kind_of?(String)
case family
when Socket::AF_INET, Socket::AF_INET6
set(addr.to_i, family)
@mask_addr = (family == Socket::AF_INET) ? IN4MASK : IN6MASK
return
when Socket::AF_UNSPEC
raise ArgumentError, "address family must be specified"
else
raise ArgumentError, "unsupported address family: #{family}"
end
end
prefix, prefixlen = addr.split('/')
if prefix =~ /^\[(.*)\]$/i
prefix = $1
family = Socket::AF_INET6
end
# It seems AI_NUMERICHOST doesn't do the job.
#Socket.getaddrinfo(left, nil, Socket::AF_INET6, Socket::SOCK_STREAM, nil,
# Socket::AI_NUMERICHOST)
begin
IPSocket.getaddress(prefix) # test if address is vaild
rescue
raise ArgumentError, "invalid address"
end
@addr = @family = nil
if family == Socket::AF_UNSPEC || family == Socket::AF_INET
@addr = in_addr(prefix)
if @addr
@family = Socket::AF_INET
end
end
if !@addr && (family == Socket::AF_UNSPEC || family == Socket::AF_INET6)
@addr = in6_addr(prefix)
@family = Socket::AF_INET6
end
if family != Socket::AF_UNSPEC && @family != family
raise ArgumentError, "address family mismatch"
end
if prefixlen
mask!(prefixlen)
else
@mask_addr = (@family == Socket::AF_INET) ? IN4MASK : IN6MASK
end
end
def coerce_other(other)
case other
when IPAddr
other
when String
self.class.new(other)
else
self.class.new(other, @family)
end
end
def in_addr(addr)
if addr =~ /^\d+\.\d+\.\d+\.\d+$/
return addr.split('.').inject(0) { |i, s|
i << 8 | s.to_i
}
end
return nil
end
def in6_addr(left)
case left
when /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i
return in_addr($1) + 0xffff00000000
when /^::(\d+\.\d+\.\d+\.\d+)$/i
return in_addr($1)
when /[^0-9a-f:]/i
raise ArgumentError, "invalid address"
when /^(.*)::(.*)$/
left, right = $1, $2
else
right = ''
end
l = left.split(':')
r = right.split(':')
rest = 8 - l.size - r.size
if rest < 0
return nil
end
return (l + Array.new(rest, '0') + r).inject(0) { |i, s|
i << 16 | s.hex
}
end
def addr_mask(addr)
case @family
when Socket::AF_INET
return addr & IN4MASK
when Socket::AF_INET6
return addr & IN6MASK
else
raise "unsupported address family"
end
end
def _reverse
case @family
when Socket::AF_INET
return (0..3).map { |i|
(@addr >> (8 * i)) & 0xff
}.join('.')
when Socket::AF_INET6
return ("%.32x" % @addr).reverse!.gsub!(/.(?!$)/, '\&.')
else
raise "unsupported address family"
end
end
def _to_string(addr)
case @family
when Socket::AF_INET
return (0..3).map { |i|
(addr >> (24 - 8 * i)) & 0xff
}.join('.')
when Socket::AF_INET6
return (("%.32x" % addr).gsub!(/.{4}(?!$)/, '\&:'))
else
raise "unsupported address family"
end
end
end
if $0 == __FILE__
eval DATA.read, nil, $0, __LINE__+4
end
__END__
require 'test/unit'
class TC_IPAddr < Test::Unit::TestCase
def test_s_new
assert_nothing_raised {
IPAddr.new("3FFE:505:ffff::/48")
IPAddr.new("0:0:0:1::")
IPAddr.new("2001:200:300::/48")
}
a = IPAddr.new
assert_equal("::", a.to_s)
assert_equal("0000:0000:0000:0000:0000:0000:0000:0000", a.to_string)
assert_equal(Socket::AF_INET6, a.family)
a = IPAddr.new("0123:4567:89ab:cdef:0ABC:DEF0:1234:5678")
assert_equal("123:4567:89ab:cdef:abc:def0:1234:5678", a.to_s)
assert_equal("0123:4567:89ab:cdef:0abc:def0:1234:5678", a.to_string)
assert_equal(Socket::AF_INET6, a.family)
a = IPAddr.new("3ffe:505:2::/48")
assert_equal("3ffe:505:2::", a.to_s)
assert_equal("3ffe:0505:0002:0000:0000:0000:0000:0000", a.to_string)
assert_equal(Socket::AF_INET6, a.family)
assert_equal(false, a.ipv4?)
assert_equal(true, a.ipv6?)
assert_equal("#<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0000/ffff:ffff:ffff:0000:0000:0000:0000:0000>", a.inspect)
a = IPAddr.new("3ffe:505:2::/ffff:ffff:ffff::")
assert_equal("3ffe:505:2::", a.to_s)
assert_equal("3ffe:0505:0002:0000:0000:0000:0000:0000", a.to_string)
assert_equal(Socket::AF_INET6, a.family)
a = IPAddr.new("0.0.0.0")
assert_equal("0.0.0.0", a.to_s)
assert_equal("0.0.0.0", a.to_string)
assert_equal(Socket::AF_INET, a.family)
a = IPAddr.new("192.168.1.2")
assert_equal("192.168.1.2", a.to_s)
assert_equal("192.168.1.2", a.to_string)
assert_equal(Socket::AF_INET, a.family)
assert_equal(true, a.ipv4?)
assert_equal(false, a.ipv6?)
a = IPAddr.new("192.168.1.2/24")
assert_equal("192.168.1.0", a.to_s)
assert_equal("192.168.1.0", a.to_string)
assert_equal(Socket::AF_INET, a.family)
assert_equal("#<IPAddr: IPv4:192.168.1.0/255.255.255.0>", a.inspect)
a = IPAddr.new("192.168.1.2/255.255.255.0")
assert_equal("192.168.1.0", a.to_s)
assert_equal("192.168.1.0", a.to_string)
assert_equal(Socket::AF_INET, a.family)
assert_equal("0:0:0:1::", IPAddr.new("0:0:0:1::").to_s)
assert_equal("2001:200:300::", IPAddr.new("2001:200:300::/48").to_s)
assert_equal("2001:200:300::", IPAddr.new("[2001:200:300::]/48").to_s)
[
["fe80::1%fxp0"],
["::1/255.255.255.0"],
["::1:192.168.1.2/120"],
[IPAddr.new("::1").to_i],
["::ffff:192.168.1.2/120", Socket::AF_INET],
["[192.168.1.2]/120"],
].each { |args|
assert_raises(ArgumentError) {
IPAddr.new(*args)
}
}
end
def test_s_new_ntoh
addr = ''
IPAddr.new("1234:5678:9abc:def0:1234:5678:9abc:def0").hton.each_byte { |c|
addr += sprintf("%02x", c)
}
assert_equal("123456789abcdef0123456789abcdef0", addr)
addr = ''
IPAddr.new("123.45.67.89").hton.each_byte { |c|
addr += sprintf("%02x", c)
}
assert_equal(sprintf("%02x%02x%02x%02x", 123, 45, 67, 89), addr)
a = IPAddr.new("3ffe:505:2::")
assert_equal("3ffe:505:2::", IPAddr.new_ntoh(a.hton).to_s)
a = IPAddr.new("192.168.2.1")
assert_equal("192.168.2.1", IPAddr.new_ntoh(a.hton).to_s)
end
def test_ipv4_compat
a = IPAddr.new("::192.168.1.2")
assert_equal("::192.168.1.2", a.to_s)
assert_equal("0000:0000:0000:0000:0000:0000:c0a8:0102", a.to_string)
assert_equal(Socket::AF_INET6, a.family)
assert_equal(true, a.ipv4_compat?)
b = a.native
assert_equal("192.168.1.2", b.to_s)
assert_equal(Socket::AF_INET, b.family)
assert_equal(false, b.ipv4_compat?)
a = IPAddr.new("192.168.1.2")
b = a.ipv4_compat
assert_equal("::192.168.1.2", b.to_s)
assert_equal(Socket::AF_INET6, b.family)
end
def test_ipv4_mapped
a = IPAddr.new("::ffff:192.168.1.2")
assert_equal("::ffff:192.168.1.2", a.to_s)
assert_equal("0000:0000:0000:0000:0000:ffff:c0a8:0102", a.to_string)
assert_equal(Socket::AF_INET6, a.family)
assert_equal(true, a.ipv4_mapped?)
b = a.native
assert_equal("192.168.1.2", b.to_s)
assert_equal(Socket::AF_INET, b.family)
assert_equal(false, b.ipv4_mapped?)
a = IPAddr.new("192.168.1.2")
b = a.ipv4_mapped
assert_equal("::ffff:192.168.1.2", b.to_s)
assert_equal(Socket::AF_INET6, b.family)
end
def test_reverse
assert_equal("f.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.2.0.0.0.5.0.5.0.e.f.f.3.ip6.arpa", IPAddr.new("3ffe:505:2::f").reverse)
assert_equal("1.2.168.192.in-addr.arpa", IPAddr.new("192.168.2.1").reverse)
end
def test_ip6_arpa
assert_equal("f.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.2.0.0.0.5.0.5.0.e.f.f.3.ip6.arpa", IPAddr.new("3ffe:505:2::f").ip6_arpa)
assert_raises(ArgumentError) {
IPAddr.new("192.168.2.1").ip6_arpa
}
end
def test_ip6_int
assert_equal("f.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.2.0.0.0.5.0.5.0.e.f.f.3.ip6.int", IPAddr.new("3ffe:505:2::f").ip6_int)
assert_raises(ArgumentError) {
IPAddr.new("192.168.2.1").ip6_int
}
end
def test_to_s
assert_equal("3ffe:0505:0002:0000:0000:0000:0000:0001", IPAddr.new("3ffe:505:2::1").to_string)
assert_equal("3ffe:505:2::1", IPAddr.new("3ffe:505:2::1").to_s)
end
end
class TC_Operator < Test::Unit::TestCase
IN6MASK32 = "ffff:ffff::"
IN6MASK128 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"
def setup
@in6_addr_any = IPAddr.new()
@a = IPAddr.new("3ffe:505:2::/48")
@b = IPAddr.new("0:0:0:1::")
@c = IPAddr.new(IN6MASK32)
end
alias set_up setup
def test_or
assert_equal("3ffe:505:2:1::", (@a | @b).to_s)
a = @a
a |= @b
assert_equal("3ffe:505:2:1::", a.to_s)
assert_equal("3ffe:505:2::", @a.to_s)
assert_equal("3ffe:505:2:1::",
(@a | 0x00000000000000010000000000000000).to_s)
end
def test_and
assert_equal("3ffe:505::", (@a & @c).to_s)
a = @a
a &= @c
assert_equal("3ffe:505::", a.to_s)
assert_equal("3ffe:505:2::", @a.to_s)
assert_equal("3ffe:505::", (@a & 0xffffffff000000000000000000000000).to_s)
end
def test_shift_right
assert_equal("0:3ffe:505:2::", (@a >> 16).to_s)
a = @a
a >>= 16
assert_equal("0:3ffe:505:2::", a.to_s)
assert_equal("3ffe:505:2::", @a.to_s)
end
def test_shift_left
assert_equal("505:2::", (@a << 16).to_s)
a = @a
a <<= 16
assert_equal("505:2::", a.to_s)
assert_equal("3ffe:505:2::", @a.to_s)
end
def test_carrot
a = ~@in6_addr_any
assert_equal(IN6MASK128, a.to_s)
assert_equal("::", @in6_addr_any.to_s)
end
def test_equal
assert_equal(true, @a == IPAddr.new("3ffe:505:2::"))
assert_equal(false, @a == IPAddr.new("3ffe:505:3::"))
assert_equal(true, @a != IPAddr.new("3ffe:505:3::"))
assert_equal(false, @a != IPAddr.new("3ffe:505:2::"))
end
def test_mask
a = @a.mask(32)
assert_equal("3ffe:505::", a.to_s)
assert_equal("3ffe:505:2::", @a.to_s)
end
def test_include?
assert_equal(true, @a.include?(IPAddr.new("3ffe:505:2::")))
assert_equal(true, @a.include?(IPAddr.new("3ffe:505:2::1")))
assert_equal(false, @a.include?(IPAddr.new("3ffe:505:3::")))
net1 = IPAddr.new("192.168.2.0/24")
assert_equal(true, net1.include?(IPAddr.new("192.168.2.0")))
assert_equal(true, net1.include?(IPAddr.new("192.168.2.255")))
assert_equal(false, net1.include?(IPAddr.new("192.168.3.0")))
# test with integer parameter
int = (192 << 24) + (168 << 16) + (2 << 8) + 13
assert_equal(true, net1.include?(int))
assert_equal(false, net1.include?(int+255))
end
def test_hash
a1 = IPAddr.new('192.168.2.0')
a2 = IPAddr.new('192.168.2.0')
a3 = IPAddr.new('3ffe:505:2::1')
a4 = IPAddr.new('3ffe:505:2::1')
a5 = IPAddr.new('127.0.0.1')
a6 = IPAddr.new('::1')
a7 = IPAddr.new('192.168.2.0/25')
a8 = IPAddr.new('192.168.2.0/25')
h = { a1 => 'ipv4', a2 => 'ipv4', a3 => 'ipv6', a4 => 'ipv6', a5 => 'ipv4', a6 => 'ipv6', a7 => 'ipv4', a8 => 'ipv4'}
assert_equal(5, h.size)
assert_equal('ipv4', h[a1])
assert_equal('ipv4', h[a2])
assert_equal('ipv6', h[a3])
assert_equal('ipv6', h[a4])
require 'set'
s = Set[a1, a2, a3, a4, a5, a6, a7, a8]
assert_equal(5, s.size)
assert_equal(true, s.include?(a1))
assert_equal(true, s.include?(a2))
assert_equal(true, s.include?(a3))
assert_equal(true, s.include?(a4))
assert_equal(true, s.include?(a5))
assert_equal(true, s.include?(a6))
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/rake.rb | tools/jruby-1.5.1/lib/ruby/1.9/rake.rb | #--
# Copyright 2003, 2004, 2005, 2006, 2007, 2008 by Jim Weirich (jim@weirichhouse.org)
#
# 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.
#++
#
# = Rake -- Ruby Make
#
# This is the main file for the Rake application. Normally it is referenced
# as a library via a require statement, but it can be distributed
# independently as an application.
RAKEVERSION = '0.8.4'
require 'rbconfig'
require 'fileutils'
require 'singleton'
require 'monitor'
require 'optparse'
require 'ostruct'
require 'rake/win32'
######################################################################
# Rake extensions to Module.
#
class Module
# Check for an existing method in the current class before extending. IF
# the method already exists, then a warning is printed and the extension is
# not added. Otherwise the block is yielded and any definitions in the
# block will take effect.
#
# Usage:
#
# class String
# rake_extension("xyz") do
# def xyz
# ...
# end
# end
# end
#
def rake_extension(method)
if method_defined?(method)
$stderr.puts "WARNING: Possible conflict with Rake extension: #{self}##{method} already exists"
else
yield
end
end
end # module Module
######################################################################
# User defined methods to be added to String.
#
class String
rake_extension("ext") do
# Replace the file extension with +newext+. If there is no extension on
# the string, append the new extension to the end. If the new extension
# is not given, or is the empty string, remove any existing extension.
#
# +ext+ is a user added method for the String class.
def ext(newext='')
return self.dup if ['.', '..'].include? self
if newext != ''
newext = (newext =~ /^\./) ? newext : ("." + newext)
end
self.chomp(File.extname(self)) << newext
end
end
rake_extension("pathmap") do
# Explode a path into individual components. Used by +pathmap+.
def pathmap_explode
head, tail = File.split(self)
return [self] if head == self
return [tail] if head == '.' || tail == '/'
return [head, tail] if head == '/'
return head.pathmap_explode + [tail]
end
protected :pathmap_explode
# Extract a partial path from the path. Include +n+ directories from the
# front end (left hand side) if +n+ is positive. Include |+n+|
# directories from the back end (right hand side) if +n+ is negative.
def pathmap_partial(n)
dirs = File.dirname(self).pathmap_explode
partial_dirs =
if n > 0
dirs[0...n]
elsif n < 0
dirs.reverse[0...-n].reverse
else
"."
end
File.join(partial_dirs)
end
protected :pathmap_partial
# Preform the pathmap replacement operations on the given path. The
# patterns take the form 'pat1,rep1;pat2,rep2...'.
def pathmap_replace(patterns, &block)
result = self
patterns.split(';').each do |pair|
pattern, replacement = pair.split(',')
pattern = Regexp.new(pattern)
if replacement == '*' && block_given?
result = result.sub(pattern, &block)
elsif replacement
result = result.sub(pattern, replacement)
else
result = result.sub(pattern, '')
end
end
result
end
protected :pathmap_replace
# Map the path according to the given specification. The specification
# controls the details of the mapping. The following special patterns are
# recognized:
#
# * <b>%p</b> -- The complete path.
# * <b>%f</b> -- The base file name of the path, with its file extension,
# but without any directories.
# * <b>%n</b> -- The file name of the path without its file extension.
# * <b>%d</b> -- The directory list of the path.
# * <b>%x</b> -- The file extension of the path. An empty string if there
# is no extension.
# * <b>%X</b> -- Everything *but* the file extension.
# * <b>%s</b> -- The alternate file separater if defined, otherwise use
# the standard file separator.
# * <b>%%</b> -- A percent sign.
#
# The %d specifier can also have a numeric prefix (e.g. '%2d'). If the
# number is positive, only return (up to) +n+ directories in the path,
# starting from the left hand side. If +n+ is negative, return (up to)
# |+n+| directories from the right hand side of the path.
#
# Examples:
#
# 'a/b/c/d/file.txt'.pathmap("%2d") => 'a/b'
# 'a/b/c/d/file.txt'.pathmap("%-2d") => 'c/d'
#
# Also the %d, %p, %f, %n, %x, and %X operators can take a
# pattern/replacement argument to perform simple string substititions on a
# particular part of the path. The pattern and replacement are speparated
# by a comma and are enclosed by curly braces. The replacement spec comes
# after the % character but before the operator letter. (e.g.
# "%{old,new}d"). Muliple replacement specs should be separated by
# semi-colons (e.g. "%{old,new;src,bin}d").
#
# Regular expressions may be used for the pattern, and back refs may be
# used in the replacement text. Curly braces, commas and semi-colons are
# excluded from both the pattern and replacement text (let's keep parsing
# reasonable).
#
# For example:
#
# "src/org/onestepback/proj/A.java".pathmap("%{^src,bin}X.class")
#
# returns:
#
# "bin/org/onestepback/proj/A.class"
#
# If the replacement text is '*', then a block may be provided to perform
# some arbitrary calculation for the replacement.
#
# For example:
#
# "/path/to/file.TXT".pathmap("%X%{.*,*}x") { |ext|
# ext.downcase
# }
#
# Returns:
#
# "/path/to/file.txt"
#
def pathmap(spec=nil, &block)
return self if spec.nil?
result = ''
spec.scan(/%\{[^}]*\}-?\d*[sdpfnxX%]|%-?\d+d|%.|[^%]+/) do |frag|
case frag
when '%f'
result << File.basename(self)
when '%n'
result << File.basename(self, '.*')
when '%d'
result << File.dirname(self)
when '%x'
result << File.extname(self)
when '%X'
result << self.ext
when '%p'
result << self
when '%s'
result << (File::ALT_SEPARATOR || File::SEPARATOR)
when '%-'
# do nothing
when '%%'
result << "%"
when /%(-?\d+)d/
result << pathmap_partial($1.to_i)
when /^%\{([^}]*)\}(\d*[dpfnxX])/
patterns, operator = $1, $2
result << pathmap('%' + operator).pathmap_replace(patterns, &block)
when /^%/
fail ArgumentError, "Unknown pathmap specifier #{frag} in '#{spec}'"
else
result << frag
end
end
result
end
end
end # class String
##############################################################################
module Rake
# Errors -----------------------------------------------------------
# Error indicating an ill-formed task declaration.
class TaskArgumentError < ArgumentError
end
# Error indicating a recursion overflow error in task selection.
class RuleRecursionOverflowError < StandardError
def initialize(*args)
super
@targets = []
end
def add_target(target)
@targets << target
end
def message
super + ": [" + @targets.reverse.join(' => ') + "]"
end
end
# --------------------------------------------------------------------------
# Rake module singleton methods.
#
class << self
# Current Rake Application
def application
@application ||= Rake::Application.new
end
# Set the current Rake application object.
def application=(app)
@application = app
end
# Return the original directory where the Rake application was started.
def original_dir
application.original_dir
end
end
# ##########################################################################
# Mixin for creating easily cloned objects.
#
module Cloneable
# Clone an object by making a new object and setting all the instance
# variables to the same values.
def dup
sibling = self.class.new
instance_variables.each do |ivar|
value = self.instance_variable_get(ivar)
new_value = value.clone rescue value
sibling.instance_variable_set(ivar, new_value)
end
sibling.taint if tainted?
sibling
end
def clone
sibling = dup
sibling.freeze if frozen?
sibling
end
end
####################################################################
# TaskAguments manage the arguments passed to a task.
#
class TaskArguments
include Enumerable
attr_reader :names
# Create a TaskArgument object with a list of named arguments
# (given by :names) and a set of associated values (given by
# :values). :parent is the parent argument object.
def initialize(names, values, parent=nil)
@names = names
@parent = parent
@hash = {}
names.each_with_index { |name, i|
@hash[name.to_sym] = values[i] unless values[i].nil?
}
end
# Create a new argument scope using the prerequisite argument
# names.
def new_scope(names)
values = names.collect { |n| self[n] }
self.class.new(names, values, self)
end
# Find an argument value by name or index.
def [](index)
lookup(index.to_sym)
end
# Specify a hash of default values for task arguments. Use the
# defaults only if there is no specific value for the given
# argument.
def with_defaults(defaults)
@hash = defaults.merge(@hash)
end
def each(&block)
@hash.each(&block)
end
def method_missing(sym, *args, &block)
lookup(sym.to_sym)
end
def to_hash
@hash
end
def to_s
@hash.inspect
end
def inspect
to_s
end
protected
def lookup(name)
if @hash.has_key?(name)
@hash[name]
elsif ENV.has_key?(name.to_s)
ENV[name.to_s]
elsif ENV.has_key?(name.to_s.upcase)
ENV[name.to_s.upcase]
elsif @parent
@parent.lookup(name)
end
end
end
EMPTY_TASK_ARGS = TaskArguments.new([], [])
####################################################################
# InvocationChain tracks the chain of task invocations to detect
# circular dependencies.
class InvocationChain
def initialize(value, tail)
@value = value
@tail = tail
end
def member?(obj)
@value == obj || @tail.member?(obj)
end
def append(value)
if member?(value)
fail RuntimeError, "Circular dependency detected: #{to_s} => #{value}"
end
self.class.new(value, self)
end
def to_s
"#{prefix}#{@value}"
end
def self.append(value, chain)
chain.append(value)
end
private
def prefix
"#{@tail.to_s} => "
end
class EmptyInvocationChain
def member?(obj)
false
end
def append(value)
InvocationChain.new(value, self)
end
def to_s
"TOP"
end
end
EMPTY = EmptyInvocationChain.new
end # class InvocationChain
end # module Rake
module Rake
# #########################################################################
# A Task is the basic unit of work in a Rakefile. Tasks have associated
# actions (possibly more than one) and a list of prerequisites. When
# invoked, a task will first ensure that all of its prerequisites have an
# opportunity to run and then it will execute its own actions.
#
# Tasks are not usually created directly using the new method, but rather
# use the +file+ and +task+ convenience methods.
#
class Task
# List of prerequisites for a task.
attr_reader :prerequisites
# List of actions attached to a task.
attr_reader :actions
# Application owning this task.
attr_accessor :application
# Comment for this task. Restricted to a single line of no more than 50
# characters.
attr_reader :comment
# Full text of the (possibly multi-line) comment.
attr_reader :full_comment
# Array of nested namespaces names used for task lookup by this task.
attr_reader :scope
# Return task name
def to_s
name
end
def inspect
"<#{self.class} #{name} => [#{prerequisites.join(', ')}]>"
end
# List of sources for task.
attr_writer :sources
def sources
@sources ||= []
end
# First source from a rule (nil if no sources)
def source
@sources.first if defined?(@sources)
end
# Create a task named +task_name+ with no actions or prerequisites. Use
# +enhance+ to add actions and prerequisites.
def initialize(task_name, app)
@name = task_name.to_s
@prerequisites = []
@actions = []
@already_invoked = false
@full_comment = nil
@comment = nil
@lock = Monitor.new
@application = app
@scope = app.current_scope
@arg_names = nil
end
# Enhance a task with prerequisites or actions. Returns self.
def enhance(deps=nil, &block)
@prerequisites |= deps if deps
@actions << block if block_given?
self
end
# Name of the task, including any namespace qualifiers.
def name
@name.to_s
end
# Name of task with argument list description.
def name_with_args # :nodoc:
if arg_description
"#{name}#{arg_description}"
else
name
end
end
# Argument description (nil if none).
def arg_description # :nodoc:
@arg_names ? "[#{(arg_names || []).join(',')}]" : nil
end
# Name of arguments for this task.
def arg_names
@arg_names || []
end
# Reenable the task, allowing its tasks to be executed if the task
# is invoked again.
def reenable
@already_invoked = false
end
# Clear the existing prerequisites and actions of a rake task.
def clear
clear_prerequisites
clear_actions
self
end
# Clear the existing prerequisites of a rake task.
def clear_prerequisites
prerequisites.clear
self
end
# Clear the existing actions on a rake task.
def clear_actions
actions.clear
self
end
# Invoke the task if it is needed. Prerequites are invoked first.
def invoke(*args)
task_args = TaskArguments.new(arg_names, args)
invoke_with_call_chain(task_args, InvocationChain::EMPTY)
end
# Same as invoke, but explicitly pass a call chain to detect
# circular dependencies.
def invoke_with_call_chain(task_args, invocation_chain) # :nodoc:
new_chain = InvocationChain.append(self, invocation_chain)
@lock.synchronize do
if application.options.trace
puts "** Invoke #{name} #{format_trace_flags}"
end
return if @already_invoked
@already_invoked = true
invoke_prerequisites(task_args, new_chain)
execute(task_args) if needed?
end
end
protected :invoke_with_call_chain
# Invoke all the prerequisites of a task.
def invoke_prerequisites(task_args, invocation_chain) # :nodoc:
@prerequisites.each { |n|
prereq = application[n, @scope]
prereq_args = task_args.new_scope(prereq.arg_names)
prereq.invoke_with_call_chain(prereq_args, invocation_chain)
}
end
# Format the trace flags for display.
def format_trace_flags
flags = []
flags << "first_time" unless @already_invoked
flags << "not_needed" unless needed?
flags.empty? ? "" : "(" + flags.join(", ") + ")"
end
private :format_trace_flags
# Execute the actions associated with this task.
def execute(args=nil)
args ||= EMPTY_TASK_ARGS
if application.options.dryrun
puts "** Execute (dry run) #{name}"
return
end
if application.options.trace
puts "** Execute #{name}"
end
application.enhance_with_matching_rule(name) if @actions.empty?
@actions.each do |act|
case act.arity
when 1
act.call(self)
else
act.call(self, args)
end
end
end
# Is this task needed?
def needed?
true
end
# Timestamp for this task. Basic tasks return the current time for their
# time stamp. Other tasks can be more sophisticated.
def timestamp
@prerequisites.collect { |p| application[p].timestamp }.max || Time.now
end
# Add a description to the task. The description can consist of an option
# argument list (enclosed brackets) and an optional comment.
def add_description(description)
return if ! description
comment = description.strip
add_comment(comment) if comment && ! comment.empty?
end
# Writing to the comment attribute is the same as adding a description.
def comment=(description)
add_description(description)
end
# Add a comment to the task. If a comment alread exists, separate
# the new comment with " / ".
def add_comment(comment)
if @full_comment
@full_comment << " / "
else
@full_comment = ''
end
@full_comment << comment
if @full_comment =~ /\A([^.]+?\.)( |$)/
@comment = $1
else
@comment = @full_comment
end
end
private :add_comment
# Set the names of the arguments for this task. +args+ should be
# an array of symbols, one for each argument name.
def set_arg_names(args)
@arg_names = args.map { |a| a.to_sym }
end
# Return a string describing the internal state of a task. Useful for
# debugging.
def investigation
result = "------------------------------\n"
result << "Investigating #{name}\n"
result << "class: #{self.class}\n"
result << "task needed: #{needed?}\n"
result << "timestamp: #{timestamp}\n"
result << "pre-requisites: \n"
prereqs = @prerequisites.collect {|name| application[name]}
prereqs.sort! {|a,b| a.timestamp <=> b.timestamp}
prereqs.each do |p|
result << "--#{p.name} (#{p.timestamp})\n"
end
latest_prereq = @prerequisites.collect{|n| application[n].timestamp}.max
result << "latest-prerequisite time: #{latest_prereq}\n"
result << "................................\n\n"
return result
end
# ----------------------------------------------------------------
# Rake Module Methods
#
class << self
# Clear the task list. This cause rake to immediately forget all the
# tasks that have been assigned. (Normally used in the unit tests.)
def clear
Rake.application.clear
end
# List of all defined tasks.
def tasks
Rake.application.tasks
end
# Return a task with the given name. If the task is not currently
# known, try to synthesize one from the defined rules. If no rules are
# found, but an existing file matches the task name, assume it is a file
# task with no dependencies or actions.
def [](task_name)
Rake.application[task_name]
end
# TRUE if the task name is already defined.
def task_defined?(task_name)
Rake.application.lookup(task_name) != nil
end
# Define a task given +args+ and an option block. If a rule with the
# given name already exists, the prerequisites and actions are added to
# the existing task. Returns the defined task.
def define_task(*args, &block)
Rake.application.define_task(self, *args, &block)
end
# Define a rule for synthesizing tasks.
def create_rule(*args, &block)
Rake.application.create_rule(*args, &block)
end
# Apply the scope to the task name according to the rules for
# this kind of task. Generic tasks will accept the scope as
# part of the name.
def scope_name(scope, task_name)
(scope + [task_name]).join(':')
end
end # class << Rake::Task
end # class Rake::Task
# #########################################################################
# A FileTask is a task that includes time based dependencies. If any of a
# FileTask's prerequisites have a timestamp that is later than the file
# represented by this task, then the file must be rebuilt (using the
# supplied actions).
#
class FileTask < Task
# Is this file task needed? Yes if it doesn't exist, or if its time stamp
# is out of date.
def needed?
! File.exist?(name) || out_of_date?(timestamp)
end
# Time stamp for file task.
def timestamp
if File.exist?(name)
File.mtime(name.to_s)
else
Rake::EARLY
end
end
private
# Are there any prerequisites with a later time than the given time stamp?
def out_of_date?(stamp)
@prerequisites.any? { |n| application[n].timestamp > stamp}
end
# ----------------------------------------------------------------
# Task class methods.
#
class << self
# Apply the scope to the task name according to the rules for this kind
# of task. File based tasks ignore the scope when creating the name.
def scope_name(scope, task_name)
task_name
end
end
end # class Rake::FileTask
# #########################################################################
# A FileCreationTask is a file task that when used as a dependency will be
# needed if and only if the file has not been created. Once created, it is
# not re-triggered if any of its dependencies are newer, nor does trigger
# any rebuilds of tasks that depend on it whenever it is updated.
#
class FileCreationTask < FileTask
# Is this file task needed? Yes if it doesn't exist.
def needed?
! File.exist?(name)
end
# Time stamp for file creation task. This time stamp is earlier
# than any other time stamp.
def timestamp
Rake::EARLY
end
end
# #########################################################################
# Same as a regular task, but the immediate prerequisites are done in
# parallel using Ruby threads.
#
class MultiTask < Task
private
def invoke_prerequisites(args, invocation_chain)
threads = @prerequisites.collect { |p|
Thread.new(p) { |r| application[r].invoke_with_call_chain(args, invocation_chain) }
}
threads.each { |t| t.join }
end
end
end # module Rake
# ###########################################################################
# Task Definition Functions ...
# Declare a basic task.
#
# Example:
# task :clobber => [:clean] do
# rm_rf "html"
# end
#
def task(*args, &block)
Rake::Task.define_task(*args, &block)
end
# Declare a file task.
#
# Example:
# file "config.cfg" => ["config.template"] do
# open("config.cfg", "w") do |outfile|
# open("config.template") do |infile|
# while line = infile.gets
# outfile.puts line
# end
# end
# end
# end
#
def file(*args, &block)
Rake::FileTask.define_task(*args, &block)
end
# Declare a file creation task.
# (Mainly used for the directory command).
def file_create(args, &block)
Rake::FileCreationTask.define_task(args, &block)
end
# Declare a set of files tasks to create the given directories on demand.
#
# Example:
# directory "testdata/doc"
#
def directory(dir)
Rake.each_dir_parent(dir) do |d|
file_create d do |t|
mkdir_p t.name if ! File.exist?(t.name)
end
end
end
# Declare a task that performs its prerequisites in parallel. Multitasks does
# *not* guarantee that its prerequisites will execute in any given order
# (which is obvious when you think about it)
#
# Example:
# multitask :deploy => [:deploy_gem, :deploy_rdoc]
#
def multitask(args, &block)
Rake::MultiTask.define_task(args, &block)
end
# Create a new rake namespace and use it for evaluating the given block.
# Returns a NameSpace object that can be used to lookup tasks defined in the
# namespace.
#
# E.g.
#
# ns = namespace "nested" do
# task :run
# end
# task_run = ns[:run] # find :run in the given namespace.
#
def namespace(name=nil, &block)
Rake.application.in_namespace(name, &block)
end
# Declare a rule for auto-tasks.
#
# Example:
# rule '.o' => '.c' do |t|
# sh %{cc -o #{t.name} #{t.source}}
# end
#
def rule(*args, &block)
Rake::Task.create_rule(*args, &block)
end
# Describe the next rake task.
#
# Example:
# desc "Run the Unit Tests"
# task :test => [:build]
# runtests
# end
#
def desc(description)
Rake.application.last_description = description
end
# Import the partial Rakefiles +fn+. Imported files are loaded _after_ the
# current file is completely loaded. This allows the import statement to
# appear anywhere in the importing file, and yet allowing the imported files
# to depend on objects defined in the importing file.
#
# A common use of the import statement is to include files containing
# dependency declarations.
#
# See also the --rakelibdir command line option.
#
# Example:
# import ".depend", "my_rules"
#
def import(*fns)
fns.each do |fn|
Rake.application.add_import(fn)
end
end
# ###########################################################################
# This a FileUtils extension that defines several additional commands to be
# added to the FileUtils utility functions.
#
module FileUtils
RUBY = File.join(RbConfig::CONFIG['bindir'], RbConfig::CONFIG['ruby_install_name']).
sub(/.*\s.*/m, '"\&"')
OPT_TABLE['sh'] = %w(noop verbose)
OPT_TABLE['ruby'] = %w(noop verbose)
# Run the system command +cmd+. If multiple arguments are given the command
# is not run with the shell (same semantics as Kernel::exec and
# Kernel::system).
#
# Example:
# sh %{ls -ltr}
#
# sh 'ls', 'file with spaces'
#
# # check exit status after command runs
# sh %{grep pattern file} do |ok, res|
# if ! ok
# puts "pattern not found (status = #{res.exitstatus})"
# end
# end
#
def sh(*cmd, &block)
options = (Hash === cmd.last) ? cmd.pop : {}
unless block_given?
show_command = cmd.join(" ")
show_command = show_command[0,42] + "..."
# TODO code application logic heref show_command.length > 45
block = lambda { |ok, status|
ok or fail "Command failed with status (#{status.exitstatus}): [#{show_command}]"
}
end
if RakeFileUtils.verbose_flag == :default
options[:verbose] = true
else
options[:verbose] ||= RakeFileUtils.verbose_flag
end
options[:noop] ||= RakeFileUtils.nowrite_flag
rake_check_options options, :noop, :verbose
rake_output_message cmd.join(" ") if options[:verbose]
unless options[:noop]
res = rake_system(*cmd)
block.call(res, $?)
end
end
def rake_system(*cmd)
system(*cmd)
end
private :rake_system
# Run a Ruby interpreter with the given arguments.
#
# Example:
# ruby %{-pe '$_.upcase!' <README}
#
def ruby(*args,&block)
options = (Hash === args.last) ? args.pop : {}
if args.length > 1 then
sh(*([RUBY] + args + [options]), &block)
else
sh("#{RUBY} #{args.first}", options, &block)
end
end
LN_SUPPORTED = [true]
# Attempt to do a normal file link, but fall back to a copy if the link
# fails.
def safe_ln(*args)
unless LN_SUPPORTED[0]
cp(*args)
else
begin
ln(*args)
rescue StandardError, NotImplementedError => ex
LN_SUPPORTED[0] = false
cp(*args)
end
end
end
# Split a file path into individual directory names.
#
# Example:
# split_all("a/b/c") => ['a', 'b', 'c']
#
def split_all(path)
head, tail = File.split(path)
return [tail] if head == '.' || tail == '/'
return [head, tail] if head == '/'
return split_all(head) + [tail]
end
end
# ###########################################################################
# RakeFileUtils provides a custom version of the FileUtils methods that
# respond to the <tt>verbose</tt> and <tt>nowrite</tt> commands.
#
module RakeFileUtils
include FileUtils
class << self
attr_accessor :verbose_flag, :nowrite_flag
end
RakeFileUtils.verbose_flag = :default
RakeFileUtils.nowrite_flag = false
$fileutils_verbose = true
$fileutils_nowrite = false
FileUtils::OPT_TABLE.each do |name, opts|
default_options = []
if opts.include?(:verbose) || opts.include?("verbose")
default_options << ':verbose => RakeFileUtils.verbose_flag'
end
if opts.include?(:noop) || opts.include?("noop")
default_options << ':noop => RakeFileUtils.nowrite_flag'
end
next if default_options.empty?
module_eval(<<-EOS, __FILE__, __LINE__ + 1)
def #{name}( *args, &block )
super(
*rake_merge_option(args,
#{default_options.join(', ')}
), &block)
end
EOS
end
# Get/set the verbose flag controlling output from the FileUtils utilities.
# If verbose is true, then the utility method is echoed to standard output.
#
# Examples:
# verbose # return the current value of the verbose flag
# verbose(v) # set the verbose flag to _v_.
# verbose(v) { code } # Execute code with the verbose flag set temporarily to _v_.
# # Return to the original value when code is done.
def verbose(value=nil)
oldvalue = RakeFileUtils.verbose_flag
RakeFileUtils.verbose_flag = value unless value.nil?
if block_given?
begin
yield
ensure
RakeFileUtils.verbose_flag = oldvalue
end
end
RakeFileUtils.verbose_flag
end
# Get/set the nowrite flag controlling output from the FileUtils utilities.
# If verbose is true, then the utility method is echoed to standard output.
#
# Examples:
# nowrite # return the current value of the nowrite flag
# nowrite(v) # set the nowrite flag to _v_.
# nowrite(v) { code } # Execute code with the nowrite flag set temporarily to _v_.
# # Return to the original value when code is done.
def nowrite(value=nil)
oldvalue = RakeFileUtils.nowrite_flag
RakeFileUtils.nowrite_flag = value unless value.nil?
if block_given?
begin
yield
ensure
RakeFileUtils.nowrite_flag = oldvalue
end
end
oldvalue
end
# Use this function to prevent protentially destructive ruby code from
# running when the :nowrite flag is set.
#
# Example:
#
# when_writing("Building Project") do
# project.build
# end
#
# The following code will build the project under normal conditions. If the
# nowrite(true) flag is set, then the example will print:
# DRYRUN: Building Project
# instead of actually building the project.
#
def when_writing(msg=nil)
if RakeFileUtils.nowrite_flag
puts "DRYRUN: #{msg}" if msg
else
yield
end
end
# Merge the given options with the default values.
def rake_merge_option(args, defaults)
if Hash === args.last
defaults.update(args.last)
args.pop
end
args.push defaults
args
end
private :rake_merge_option
# Send the message to the default rake output (which is $stderr).
def rake_output_message(message)
$stderr.puts(message)
end
private :rake_output_message
| 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/delegate.rb | tools/jruby-1.5.1/lib/ruby/1.9/delegate.rb | # = delegate -- Support for the Delegation Pattern
#
# Documentation by James Edward Gray II and Gavin Sinclair
#
# == Introduction
#
# This library provides three different ways to delegate method calls to an
# object. The easiest to use is SimpleDelegator. Pass an object to the
# constructor and all methods supported by the object will be delegated. This
# object can be changed later.
#
# Going a step further, the top level DelegateClass method allows you to easily
# setup delegation through class inheritance. This is considerably more
# flexible and thus probably the most common use for this library.
#
# Finally, if you need full control over the delegation scheme, you can inherit
# from the abstract class Delegator and customize as needed. (If you find
# yourself needing this control, have a look at _forwardable_, also in the
# standard library. It may suit your needs better.)
#
# == Notes
#
# Be advised, RDoc will not detect delegated methods.
#
# <b>delegate.rb provides full-class delegation via the
# DelegateClass() method. For single-method delegation via
# def_delegator(), see forwardable.rb.</b>
#
# == Examples
#
# === SimpleDelegator
#
# Here's a simple example that takes advantage of the fact that
# SimpleDelegator's delegation object can be changed at any time.
#
# class Stats
# def initialize
# @source = SimpleDelegator.new([])
# end
#
# def stats( records )
# @source.__setobj__(records)
#
# "Elements: #{@source.size}\n" +
# " Non-Nil: #{@source.compact.size}\n" +
# " Unique: #{@source.uniq.size}\n"
# end
# end
#
# s = Stats.new
# puts s.stats(%w{James Edward Gray II})
# puts
# puts s.stats([1, 2, 3, nil, 4, 5, 1, 2])
#
# <i>Prints:</i>
#
# Elements: 4
# Non-Nil: 4
# Unique: 4
#
# Elements: 8
# Non-Nil: 7
# Unique: 6
#
# === DelegateClass()
#
# Here's a sample of use from <i>tempfile.rb</i>.
#
# A _Tempfile_ object is really just a _File_ object with a few special rules
# about storage location and/or when the File should be deleted. That makes for
# an almost textbook perfect example of how to use delegation.
#
# class Tempfile < DelegateClass(File)
# # constant and class member data initialization...
#
# def initialize(basename, tmpdir=Dir::tmpdir)
# # build up file path/name in var tmpname...
#
# @tmpfile = File.open(tmpname, File::RDWR|File::CREAT|File::EXCL, 0600)
#
# # ...
#
# super(@tmpfile)
#
# # below this point, all methods of File are supported...
# end
#
# # ...
# end
#
# === Delegator
#
# SimpleDelegator's implementation serves as a nice example here.
#
# class SimpleDelegator < Delegator
# def initialize(obj)
# super # pass obj to Delegator constructor, required
# @delegate_sd_obj = obj # store obj for future use
# end
#
# def __getobj__
# @delegate_sd_obj # return object we are delegating to, required
# end
#
# def __setobj__(obj)
# @delegate_sd_obj = obj # change delegation object, a feature we're providing
# end
#
# # ...
# end
#
# Delegator is an abstract class used to build delegator pattern objects from
# subclasses. Subclasses should redefine \_\_getobj\_\_. For a concrete
# implementation, see SimpleDelegator.
#
class Delegator
[:to_s,:inspect,:=~,:!~,:===].each do |m|
undef_method m
end
#
# Pass in the _obj_ to delegate method calls to. All methods supported by
# _obj_ will be delegated to.
#
def initialize(obj)
__setobj__(obj)
end
# Handles the magic of delegation through \_\_getobj\_\_.
def method_missing(m, *args, &block)
begin
target = self.__getobj__
unless target.respond_to?(m)
super(m, *args, &block)
else
target.__send__(m, *args, &block)
end
rescue Exception
$@.delete_if{|s| %r"\A#{Regexp.quote(__FILE__)}:\d+:in `method_missing'\z"o =~ s}
::Kernel::raise
end
end
#
# Checks for a method provided by this the delegate object by fowarding the
# call through \_\_getobj\_\_.
#
def respond_to?(m, include_private = false)
return true if super
return self.__getobj__.respond_to?(m, include_private)
end
#
# Returns true if two objects are considered same.
#
def ==(obj)
return true if obj.equal?(self)
self.__getobj__ == obj
end
#
# This method must be overridden by subclasses and should return the object
# method calls are being delegated to.
#
def __getobj__
raise NotImplementedError, "need to define `__getobj__'"
end
#
# This method must be overridden by subclasses and change the object delegate
# to _obj_.
#
def __setobj__(obj)
raise NotImplementedError, "need to define `__setobj__'"
end
# Serialization support for the object returned by \_\_getobj\_\_.
def marshal_dump
__getobj__
end
# Reinitializes delegation from a serialized object.
def marshal_load(obj)
__setobj__(obj)
end
# Clone support for the object returned by \_\_getobj\_\_.
def clone
new = super
new.__setobj__(__getobj__.clone)
new
end
# Duplication support for the object returned by \_\_getobj\_\_.
def dup
new = super
new.__setobj__(__getobj__.dup)
new
end
end
#
# A concrete implementation of Delegator, this class provides the means to
# delegate all supported method calls to the object passed into the constructor
# and even to change the object being delegated to at a later time with
# \_\_setobj\_\_ .
#
class SimpleDelegator<Delegator
# Returns the current object method calls are being delegated to.
def __getobj__
@delegate_sd_obj
end
#
# Changes the delegate object to _obj_.
#
# It's important to note that this does *not* cause SimpleDelegator's methods
# to change. Because of this, you probably only want to change delegation
# to objects of the same type as the original delegate.
#
# Here's an example of changing the delegation object.
#
# names = SimpleDelegator.new(%w{James Edward Gray II})
# puts names[1] # => Edward
# names.__setobj__(%w{Gavin Sinclair})
# puts names[1] # => Sinclair
#
def __setobj__(obj)
raise ArgumentError, "cannot delegate to self" if self.equal?(obj)
@delegate_sd_obj = obj
end
end
# :stopdoc:
def Delegator.delegating_block(mid)
lambda do |*args, &block|
begin
__getobj__.__send__(mid, *args, &block)
rescue
re = /\A#{Regexp.quote(__FILE__)}:#{__LINE__-2}:/o
$!.backtrace.delete_if {|t| re =~ t}
raise
end
end
end
# :startdoc:
#
# The primary interface to this library. Use to setup delegation when defining
# your class.
#
# class MyClass < DelegateClass( ClassToDelegateTo ) # Step 1
# def initialize
# super(obj_of_ClassToDelegateTo) # Step 2
# end
# end
#
def DelegateClass(superclass)
klass = Class.new(Delegator)
methods = superclass.public_instance_methods(true)
methods -= ::Delegator.public_instance_methods
methods -= [:to_s,:inspect,:=~,:!~,:===]
klass.module_eval {
def __getobj__ # :nodoc:
@delegate_dc_obj
end
def __setobj__(obj) # :nodoc:
raise ArgumentError, "cannot delegate to self" if self.equal?(obj)
@delegate_dc_obj = obj
end
}
klass.module_eval do
methods.each do |method|
define_method(method, Delegator.delegating_block(method))
end
end
return klass
end
# :enddoc:
if __FILE__ == $0
class ExtArray<DelegateClass(Array)
def initialize()
super([])
end
end
ary = ExtArray.new
p ary.class
ary.push 25
p ary
ary.push 42
ary.each {|x| p x}
foo = Object.new
def foo.test
25
end
def foo.iter
yield self
end
def foo.error
raise 'this is OK'
end
foo2 = SimpleDelegator.new(foo)
p foo2
foo2.instance_eval{print "foo\n"}
p foo.test == foo2.test # => true
p foo2.iter{[55,true]} # => true
foo2.error # raise error!
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/monitor.rb | tools/jruby-1.5.1/lib/ruby/1.9/monitor.rb | =begin
= monitor.rb
Copyright (C) 2001 Shugo Maeda <shugo@ruby-lang.org>
This library is distributed under the terms of the Ruby license.
You can freely distribute/modify this library.
== example
This is a simple example.
require 'monitor.rb'
buf = []
buf.extend(MonitorMixin)
empty_cond = buf.new_cond
# consumer
Thread.start do
loop do
buf.synchronize do
empty_cond.wait_while { buf.empty? }
print buf.shift
end
end
end
# producer
while line = ARGF.gets
buf.synchronize do
buf.push(line)
empty_cond.signal
end
end
The consumer thread waits for the producer thread to push a line
to buf while buf.empty?, and the producer thread (main thread)
reads a line from ARGF and push it to buf, then call
empty_cond.signal.
=end
require 'thread'
#
# Adds monitor functionality to an arbitrary object by mixing the module with
# +include+. For example:
#
# require 'monitor'
#
# buf = []
# buf.extend(MonitorMixin)
# empty_cond = buf.new_cond
#
# # consumer
# Thread.start do
# loop do
# buf.synchronize do
# empty_cond.wait_while { buf.empty? }
# print buf.shift
# end
# end
# end
#
# # producer
# while line = ARGF.gets
# buf.synchronize do
# buf.push(line)
# empty_cond.signal
# end
# end
#
# The consumer thread waits for the producer thread to push a line
# to buf while buf.empty?, and the producer thread (main thread)
# reads a line from ARGF and push it to buf, then call
# empty_cond.signal.
#
module MonitorMixin
#
# FIXME: This isn't documented in Nutshell.
#
# Since MonitorMixin.new_cond returns a ConditionVariable, and the example
# above calls while_wait and signal, this class should be documented.
#
class ConditionVariable
class Timeout < Exception; end
def wait(timeout = nil)
if timeout
raise NotImplementedError, "timeout is not implemented yet"
end
@monitor.__send__(:mon_check_owner)
count = @monitor.__send__(:mon_exit_for_cond)
begin
@cond.wait(@monitor.instance_variable_get("@mon_mutex"))
return true
ensure
@monitor.__send__(:mon_enter_for_cond, count)
end
end
def wait_while
while yield
wait
end
end
def wait_until
until yield
wait
end
end
def signal
@monitor.__send__(:mon_check_owner)
@cond.signal
end
def broadcast
@monitor.__send__(:mon_check_owner)
@cond.broadcast
end
def count_waiters
raise NotImplementedError
end
private
def initialize(monitor)
@monitor = monitor
@cond = ::ConditionVariable.new
end
end
def self.extend_object(obj)
super(obj)
obj.__send__(:mon_initialize)
end
#
# Attempts to enter exclusive section. Returns +false+ if lock fails.
#
def mon_try_enter
if @mon_owner != Thread.current
unless @mon_mutex.try_lock
return false
end
@mon_owner = Thread.current
end
@mon_count += 1
return true
end
# For backward compatibility
alias try_mon_enter mon_try_enter
#
# Enters exclusive section.
#
def mon_enter
if @mon_owner != Thread.current
@mon_mutex.lock
@mon_owner = Thread.current
end
@mon_count += 1
end
#
# Leaves exclusive section.
#
def mon_exit
mon_check_owner
@mon_count -=1
if @mon_count == 0
@mon_owner = nil
@mon_mutex.unlock
end
end
#
# Enters exclusive section and executes the block. Leaves the exclusive
# section automatically when the block exits. See example under
# +MonitorMixin+.
#
def mon_synchronize
mon_enter
begin
yield
ensure
mon_exit
end
end
alias synchronize mon_synchronize
#
# FIXME: This isn't documented in Nutshell.
#
def new_cond
return ConditionVariable.new(self)
end
private
def initialize(*args)
super
mon_initialize
end
def mon_initialize
@mon_owner = nil
@mon_count = 0
@mon_mutex = Mutex.new
end
def mon_check_owner
if @mon_owner != Thread.current
raise ThreadError, "current thread not owner"
end
end
def mon_enter_for_cond(count)
@mon_owner = Thread.current
@mon_count = count
end
def mon_exit_for_cond
count = @mon_count
@mon_owner = nil
@mon_count = 0
return count
end
end
class Monitor
include MonitorMixin
alias try_enter try_mon_enter
alias enter mon_enter
alias exit mon_exit
end
# Documentation comments:
# - All documentation comes from Nutshell.
# - MonitorMixin.new_cond appears in the example, but is not documented in
# Nutshell.
# - All the internals (internal modules Accessible and Initializable, class
# ConditionVariable) appear in RDoc. It might be good to hide them, by
# making them private, or marking them :nodoc:, etc.
# - The entire example from the RD section at the top is replicated in the RDoc
# comment for MonitorMixin. Does the RD section need to remain?
# - RDoc doesn't recognise aliases, so we have mon_synchronize documented, but
# not synchronize.
# - mon_owner is in Nutshell, but appears as an accessor in a separate module
# here, so is hard/impossible to RDoc. Some other useful accessors
# (mon_count and some queue stuff) are also in this module, and don't appear
# directly in the RDoc output.
# - in short, it may be worth changing the code layout in this file to make the
# documentation easier
# Local variables:
# mode: Ruby
# tab-width: 8
# End:
| 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/singleton.rb | tools/jruby-1.5.1/lib/ruby/1.9/singleton.rb | # The Singleton module implements the Singleton pattern.
#
# Usage:
# class Klass
# include Singleton
# # ...
# end
#
# * this ensures that only one instance of Klass lets call it
# ``the instance'' can be created.
#
# a,b = Klass.instance, Klass.instance
# a == b # => true
# Klass.new # NoMethodError - new is private ...
#
# * ``The instance'' is created at instantiation time, in other
# words the first call of Klass.instance(), thus
#
# class OtherKlass
# include Singleton
# # ...
# end
# ObjectSpace.each_object(OtherKlass){} # => 0.
#
# * This behavior is preserved under inheritance and cloning.
#
#
#
# This is achieved by marking
# * Klass.new and Klass.allocate - as private
#
# Providing (or modifying) the class methods
# * Klass.inherited(sub_klass) and Klass.clone() -
# to ensure that the Singleton pattern is properly
# inherited and cloned.
#
# * Klass.instance() - returning ``the instance''. After a
# successful self modifying (normally the first) call the
# method body is a simple:
#
# def Klass.instance()
# return @singleton__instance__
# end
#
# * Klass._load(str) - calling Klass.instance()
#
# * Klass._instantiate?() - returning ``the instance'' or
# nil. This hook method puts a second (or nth) thread calling
# Klass.instance() on a waiting loop. The return value
# signifies the successful completion or premature termination
# of the first, or more generally, current "instantiation thread".
#
#
# The instance method of Singleton are
# * clone and dup - raising TypeErrors to prevent cloning or duping
#
# * _dump(depth) - returning the empty string. Marshalling strips
# by default all state information, e.g. instance variables and
# taint state, from ``the instance''. Providing custom _load(str)
# and _dump(depth) hooks allows the (partially) resurrections of
# a previous state of ``the instance''.
require 'thread'
module Singleton
# disable build-in copying methods
def clone
raise TypeError, "can't clone instance of singleton #{self.class}"
end
def dup
raise TypeError, "can't dup instance of singleton #{self.class}"
end
# default marshalling strategy
def _dump(depth = -1)
''
end
module SingletonClassMethods
# properly clone the Singleton pattern - did you know
# that duping doesn't copy class methods?
def clone
Singleton.__init__(super)
end
def _load(str)
instance
end
private
# ensure that the Singleton pattern is properly inherited
def inherited(sub_klass)
super
Singleton.__init__(sub_klass)
end
end
class << Singleton
def __init__(klass)
klass.instance_eval {
@singleton__instance__ = nil
@singleton__mutex__ = Mutex.new
}
def klass.instance
return @singleton__instance__ if @singleton__instance__
@singleton__mutex__.synchronize {
return @singleton__instance__ if @singleton__instance__
@singleton__instance__ = new()
}
@singleton__instance__
end
klass
end
private
# extending an object with Singleton is a bad idea
undef_method :extend_object
def append_features(mod)
# help out people counting on transitive mixins
unless mod.instance_of?(Class)
raise TypeError, "Inclusion of the OO-Singleton module in module #{mod}"
end
super
end
def included(klass)
super
klass.private_class_method :new, :allocate
klass.extend SingletonClassMethods
Singleton.__init__(klass)
end
end
end
if __FILE__ == $0
def num_of_instances(klass)
"#{ObjectSpace.each_object(klass){}} #{klass} instance(s)"
end
# The basic and most important example.
class SomeSingletonClass
include Singleton
end
puts "There are #{num_of_instances(SomeSingletonClass)}"
a = SomeSingletonClass.instance
b = SomeSingletonClass.instance # a and b are same object
puts "basic test is #{a == b}"
begin
SomeSingletonClass.new
rescue NoMethodError => mes
puts mes
end
puts "\nThreaded example with exception and customized #_instantiate?() hook"; p
Thread.abort_on_exception = false
class Ups < SomeSingletonClass
def initialize
self.class.__sleep
puts "initialize called by thread ##{Thread.current[:i]}"
end
end
class << Ups
def _instantiate?
@enter.push Thread.current[:i]
while false.equal?(@singleton__instance__)
@singleton__mutex__.unlock
sleep 0.08
@singleton__mutex__.lock
end
@leave.push Thread.current[:i]
@singleton__instance__
end
def __sleep
sleep(rand(0.08))
end
def new
begin
__sleep
raise "boom - thread ##{Thread.current[:i]} failed to create instance"
ensure
# simple flip-flop
class << self
remove_method :new
end
end
end
def instantiate_all
@enter = []
@leave = []
1.upto(9) {|i|
Thread.new {
begin
Thread.current[:i] = i
__sleep
instance
rescue RuntimeError => mes
puts mes
end
}
}
puts "Before there were #{num_of_instances(self)}"
sleep 3
puts "Now there is #{num_of_instances(self)}"
puts "#{@enter.join '; '} was the order of threads entering the waiting loop"
puts "#{@leave.join '; '} was the order of threads leaving the waiting loop"
end
end
Ups.instantiate_all
# results in message like
# Before there were 0 Ups instance(s)
# boom - thread #6 failed to create instance
# initialize called by thread #3
# Now there is 1 Ups instance(s)
# 3; 2; 1; 8; 4; 7; 5 was the order of threads entering the waiting loop
# 3; 2; 1; 7; 4; 8; 5 was the order of threads leaving the waiting loop
puts "\nLets see if class level cloning really works"
Yup = Ups.clone
def Yup.new
begin
__sleep
raise "boom - thread ##{Thread.current[:i]} failed to create instance"
ensure
# simple flip-flop
class << self
remove_method :new
end
end
end
Yup.instantiate_all
puts "\n\n","Customized marshalling"
class A
include Singleton
attr_accessor :persist, :die
def _dump(depth)
# this strips the @die information from the instance
Marshal.dump(@persist,depth)
end
end
def A._load(str)
instance.persist = Marshal.load(str)
instance
end
a = A.instance
a.persist = ["persist"]
a.die = "die"
a.taint
stored_state = Marshal.dump(a)
# change state
a.persist = nil
a.die = nil
b = Marshal.load(stored_state)
p a == b # => true
p a.persist # => ["persist"]
p a.die # => nil
puts "\n\nSingleton with overridden default #inherited() hook"
class Up
end
def Up.inherited(sub_klass)
puts "#{sub_klass} subclasses #{self}"
end
class Middle < Up
include Singleton
end
class Down < Middle; end
puts "and basic \"Down test\" is #{Down.instance == Down.instance}\n
Various exceptions"
begin
module AModule
include Singleton
end
rescue TypeError => mes
puts mes #=> Inclusion of the OO-Singleton module in module AModule
end
begin
'aString'.extend Singleton
rescue NoMethodError => mes
puts mes #=> undefined method `extend_object' for Singleton:Module
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/date.rb | tools/jruby-1.5.1/lib/ruby/1.9/date.rb | #
# date.rb - date and time library
#
# Author: Tadayoshi Funaba 1998-2009
#
# Documentation: William Webber <william@williamwebber.com>
#
#--
# $Id: date.rb,v 2.37 2008-01-17 20:16:31+09 tadf Exp $
#++
#
# == Overview
#
# This file provides two classes for working with
# dates and times.
#
# The first class, Date, represents dates.
# It works with years, months, weeks, and days.
# See the Date class documentation for more details.
#
# The second, DateTime, extends Date to include hours,
# minutes, seconds, and fractions of a second. It
# provides basic support for time zones. See the
# DateTime class documentation for more details.
#
# === Ways of calculating the date.
#
# In common usage, the date is reckoned in years since or
# before the Common Era (CE/BCE, also known as AD/BC), then
# as a month and day-of-the-month within the current year.
# This is known as the *Civil* *Date*, and abbreviated
# as +civil+ in the Date class.
#
# Instead of year, month-of-the-year, and day-of-the-month,
# the date can also be reckoned in terms of year and
# day-of-the-year. This is known as the *Ordinal* *Date*,
# and is abbreviated as +ordinal+ in the Date class. (Note
# that referring to this as the Julian date is incorrect.)
#
# The date can also be reckoned in terms of year, week-of-the-year,
# and day-of-the-week. This is known as the *Commercial*
# *Date*, and is abbreviated as +commercial+ in the
# Date class. The commercial week runs Monday (day-of-the-week
# 1) to Sunday (day-of-the-week 7), in contrast to the civil
# week which runs Sunday (day-of-the-week 0) to Saturday
# (day-of-the-week 6). The first week of the commercial year
# starts on the Monday on or before January 1, and the commercial
# year itself starts on this Monday, not January 1.
#
# For scientific purposes, it is convenient to refer to a date
# simply as a day count, counting from an arbitrary initial
# day. The date first chosen for this was January 1, 4713 BCE.
# A count of days from this date is the *Julian* *Day* *Number*
# or *Julian* *Date*, which is abbreviated as +jd+ in the
# Date class. This is in local time, and counts from midnight
# on the initial day. The stricter usage is in UTC, and counts
# from midday on the initial day. This is referred to in the
# Date class as the *Astronomical* *Julian* *Day* *Number*, and
# abbreviated as +ajd+. In the Date class, the Astronomical
# Julian Day Number includes fractional days.
#
# Another absolute day count is the *Modified* *Julian* *Day*
# *Number*, which takes November 17, 1858 as its initial day.
# This is abbreviated as +mjd+ in the Date class. There
# is also an *Astronomical* *Modified* *Julian* *Day* *Number*,
# which is in UTC and includes fractional days. This is
# abbreviated as +amjd+ in the Date class. Like the Modified
# Julian Day Number (and unlike the Astronomical Julian
# Day Number), it counts from midnight.
#
# Alternative calendars such as the Chinese Lunar Calendar,
# the Islamic Calendar, or the French Revolutionary Calendar
# are not supported by the Date class; nor are calendars that
# are based on an Era different from the Common Era, such as
# the Japanese Imperial Calendar or the Republic of China
# Calendar.
#
# === Calendar Reform
#
# The standard civil year is 365 days long. However, the
# solar year is fractionally longer than this. To account
# for this, a *leap* *year* is occasionally inserted. This
# is a year with 366 days, the extra day falling on February 29.
# In the early days of the civil calendar, every fourth
# year without exception was a leap year. This way of
# reckoning leap years is the *Julian* *Calendar*.
#
# However, the solar year is marginally shorter than 365 1/4
# days, and so the *Julian* *Calendar* gradually ran slow
# over the centuries. To correct this, every 100th year
# (but not every 400th year) was excluded as a leap year.
# This way of reckoning leap years, which we use today, is
# the *Gregorian* *Calendar*.
#
# The Gregorian Calendar was introduced at different times
# in different regions. The day on which it was introduced
# for a particular region is the *Day* *of* *Calendar*
# *Reform* for that region. This is abbreviated as +sg+
# (for Start of Gregorian calendar) in the Date class.
#
# Two such days are of particular
# significance. The first is October 15, 1582, which was
# the Day of Calendar Reform for Italy and most Catholic
# countries. The second is September 14, 1752, which was
# the Day of Calendar Reform for England and its colonies
# (including what is now the United States). These two
# dates are available as the constants Date::ITALY and
# Date::ENGLAND, respectively. (By comparison, Germany and
# Holland, less Catholic than Italy but less stubborn than
# England, changed over in 1698; Sweden in 1753; Russia not
# till 1918, after the Revolution; and Greece in 1923. Many
# Orthodox churches still use the Julian Calendar. A complete
# list of Days of Calendar Reform can be found at
# http://www.polysyllabic.com/GregConv.html.)
#
# Switching from the Julian to the Gregorian calendar
# involved skipping a number of days to make up for the
# accumulated lag, and the later the switch was (or is)
# done, the more days need to be skipped. So in 1582 in Italy,
# 4th October was followed by 15th October, skipping 10 days; in 1752
# in England, 2nd September was followed by 14th September, skipping
# 11 days; and if I decided to switch from Julian to Gregorian
# Calendar this midnight, I would go from 27th July 2003 (Julian)
# today to 10th August 2003 (Gregorian) tomorrow, skipping
# 13 days. The Date class is aware of this gap, and a supposed
# date that would fall in the middle of it is regarded as invalid.
#
# The Day of Calendar Reform is relevant to all date representations
# involving years. It is not relevant to the Julian Day Numbers,
# except for converting between them and year-based representations.
#
# In the Date and DateTime classes, the Day of Calendar Reform or
# +sg+ can be specified a number of ways. First, it can be as
# the Julian Day Number of the Day of Calendar Reform. Second,
# it can be using the constants Date::ITALY or Date::ENGLAND; these
# are in fact the Julian Day Numbers of the Day of Calendar Reform
# of the respective regions. Third, it can be as the constant
# Date::JULIAN, which means to always use the Julian Calendar.
# Finally, it can be as the constant Date::GREGORIAN, which means
# to always use the Gregorian Calendar.
#
# Note: in the Julian Calendar, New Years Day was March 25. The
# Date class does not follow this convention.
#
# === Time Zones
#
# DateTime objects support a simple representation
# of time zones. Time zones are represented as an offset
# from UTC, as a fraction of a day. This offset is the
# how much local time is later (or earlier) than UTC.
# UTC offset 0 is centred on England (also known as GMT).
# As you travel east, the offset increases until you
# reach the dateline in the middle of the Pacific Ocean;
# as you travel west, the offset decreases. This offset
# is abbreviated as +of+ in the Date class.
#
# This simple representation of time zones does not take
# into account the common practice of Daylight Savings
# Time or Summer Time.
#
# Most DateTime methods return the date and the
# time in local time. The two exceptions are
# #ajd() and #amjd(), which return the date and time
# in UTC time, including fractional days.
#
# The Date class does not support time zone offsets, in that
# there is no way to create a Date object with a time zone.
# However, methods of the Date class when used by a
# DateTime instance will use the time zone offset of this
# instance.
#
# == Examples of use
#
# === Print out the date of every Sunday between two dates.
#
# def print_sundays(d1, d2)
# d1 +=1 while (d1.wday != 0)
# d1.step(d2, 7) do |date|
# puts "#{Date::MONTHNAMES[date.mon]} #{date.day}"
# end
# end
#
# print_sundays(Date::civil(2003, 4, 8), Date::civil(2003, 5, 23))
#
# === Calculate how many seconds to go till midnight on New Year's Day.
#
# def secs_to_new_year(now = DateTime::now())
# new_year = DateTime.new(now.year + 1, 1, 1)
# dif = new_year - now
# hours, mins, secs, ignore_fractions = Date::day_fraction_to_time(dif)
# return hours * 60 * 60 + mins * 60 + secs
# end
#
# puts secs_to_new_year()
require 'date/format'
require 'date/delta'
# Class representing a date.
#
# See the documentation to the file date.rb for an overview.
#
# Internally, the date is represented as an Astronomical
# Julian Day Number, +ajd+. The Day of Calendar Reform, +sg+, is
# also stored, for conversions to other date formats. (There
# is also an +of+ field for a time zone offset, but this
# is only for the use of the DateTime subclass.)
#
# A new Date object is created using one of the object creation
# class methods named after the corresponding date format, and the
# arguments appropriate to that date format; for instance,
# Date::civil() (aliased to Date::new()) with year, month,
# and day-of-month, or Date::ordinal() with year and day-of-year.
# All of these object creation class methods also take the
# Day of Calendar Reform as an optional argument.
#
# Date objects are immutable once created.
#
# Once a Date has been created, date values
# can be retrieved for the different date formats supported
# using instance methods. For instance, #mon() gives the
# Civil month, #cwday() gives the Commercial day of the week,
# and #yday() gives the Ordinal day of the year. Date values
# can be retrieved in any format, regardless of what format
# was used to create the Date instance.
#
# The Date class includes the Comparable module, allowing
# date objects to be compared and sorted, ranges of dates
# to be created, and so forth.
class Date
include Comparable
# Full month names, in English. Months count from 1 to 12; a
# month's numerical representation indexed into this array
# gives the name of that month (hence the first element is nil).
MONTHNAMES = [nil] + %w(January February March April May June July
August September October November December)
# Full names of days of the week, in English. Days of the week
# count from 0 to 6 (except in the commercial week); a day's numerical
# representation indexed into this array gives the name of that day.
DAYNAMES = %w(Sunday Monday Tuesday Wednesday Thursday Friday Saturday)
# Abbreviated month names, in English.
ABBR_MONTHNAMES = [nil] + %w(Jan Feb Mar Apr May Jun
Jul Aug Sep Oct Nov Dec)
# Abbreviated day names, in English.
ABBR_DAYNAMES = %w(Sun Mon Tue Wed Thu Fri Sat)
[MONTHNAMES, DAYNAMES, ABBR_MONTHNAMES, ABBR_DAYNAMES].each do |xs|
xs.each{|x| x.freeze unless x.nil?}.freeze
end
class Infinity < Numeric # :nodoc:
include Comparable
def initialize(d=1) @d = d <=> 0 end
def d() @d end
protected :d
def zero? () false end
def finite? () false end
def infinite? () d.nonzero? end
def nan? () d.zero? end
def abs() self.class.new end
def -@ () self.class.new(-d) end
def +@ () self.class.new(+d) end
def <=> (other)
case other
when Infinity; return d <=> other.d
when Numeric; return d
else
begin
l, r = other.coerce(self)
return l <=> r
rescue NoMethodError
end
end
nil
end
def coerce(other)
case other
when Numeric; return -d, d
else
super
end
end
end
# The Julian Day Number of the Day of Calendar Reform for Italy
# and the Catholic countries.
ITALY = 2299161 # 1582-10-15
# The Julian Day Number of the Day of Calendar Reform for England
# and her Colonies.
ENGLAND = 2361222 # 1752-09-14
# A constant used to indicate that a Date should always use the
# Julian calendar.
JULIAN = Infinity.new
# A constant used to indicate that a Date should always use the
# Gregorian calendar.
GREGORIAN = -Infinity.new
HALF_DAYS_IN_DAY = Rational(1, 2) # :nodoc:
HOURS_IN_DAY = Rational(1, 24) # :nodoc:
MINUTES_IN_DAY = Rational(1, 1440) # :nodoc:
SECONDS_IN_DAY = Rational(1, 86400) # :nodoc:
MILLISECONDS_IN_DAY = Rational(1, 86400*10**3) # :nodoc:
NANOSECONDS_IN_DAY = Rational(1, 86400*10**9) # :nodoc:
MILLISECONDS_IN_SECOND = Rational(1, 10**3) # :nodoc:
NANOSECONDS_IN_SECOND = Rational(1, 10**9) # :nodoc:
MJD_EPOCH_IN_AJD = Rational(4800001, 2) # 1858-11-17 # :nodoc:
UNIX_EPOCH_IN_AJD = Rational(4881175, 2) # 1970-01-01 # :nodoc:
MJD_EPOCH_IN_CJD = 2400001 # :nodoc:
UNIX_EPOCH_IN_CJD = 2440588 # :nodoc:
LD_EPOCH_IN_CJD = 2299160 # :nodoc:
t = Module.new do
private
def find_fdoy(y, sg) # :nodoc:
j = nil
1.upto(31) do |d|
break if j = _valid_civil?(y, 1, d, sg)
end
j
end
def find_ldoy(y, sg) # :nodoc:
j = nil
31.downto(1) do |d|
break if j = _valid_civil?(y, 12, d, sg)
end
j
end
def find_fdom(y, m, sg) # :nodoc:
j = nil
1.upto(31) do |d|
break if j = _valid_civil?(y, m, d, sg)
end
j
end
def find_ldom(y, m, sg) # :nodoc:
j = nil
31.downto(1) do |d|
break if j = _valid_civil?(y, m, d, sg)
end
j
end
# Convert an Ordinal Date to a Julian Day Number.
#
# +y+ and +d+ are the year and day-of-year to convert.
# +sg+ specifies the Day of Calendar Reform.
#
# Returns the corresponding Julian Day Number.
def ordinal_to_jd(y, d, sg=GREGORIAN) # :nodoc:
find_fdoy(y, sg) + d - 1
end
# Convert a Julian Day Number to an Ordinal Date.
#
# +jd+ is the Julian Day Number to convert.
# +sg+ specifies the Day of Calendar Reform.
#
# Returns the corresponding Ordinal Date as
# [year, day_of_year]
def jd_to_ordinal(jd, sg=GREGORIAN) # :nodoc:
y = jd_to_civil(jd, sg)[0]
j = find_fdoy(y, sg)
doy = jd - j + 1
return y, doy
end
# Convert a Civil Date to a Julian Day Number.
# +y+, +m+, and +d+ are the year, month, and day of the
# month. +sg+ specifies the Day of Calendar Reform.
#
# Returns the corresponding Julian Day Number.
def civil_to_jd(y, m, d, sg=GREGORIAN) # :nodoc:
if m <= 2
y -= 1
m += 12
end
a = (y / 100.0).floor
b = 2 - a + (a / 4.0).floor
jd = (365.25 * (y + 4716)).floor +
(30.6001 * (m + 1)).floor +
d + b - 1524
if jd < sg
jd -= b
end
jd
end
# Convert a Julian Day Number to a Civil Date. +jd+ is
# the Julian Day Number. +sg+ specifies the Day of
# Calendar Reform.
#
# Returns the corresponding [year, month, day_of_month]
# as a three-element array.
def jd_to_civil(jd, sg=GREGORIAN) # :nodoc:
if jd < sg
a = jd
else
x = ((jd - 1867216.25) / 36524.25).floor
a = jd + 1 + x - (x / 4.0).floor
end
b = a + 1524
c = ((b - 122.1) / 365.25).floor
d = (365.25 * c).floor
e = ((b - d) / 30.6001).floor
dom = b - d - (30.6001 * e).floor
if e <= 13
m = e - 1
y = c - 4716
else
m = e - 13
y = c - 4715
end
return y, m, dom
end
# Convert a Commercial Date to a Julian Day Number.
#
# +y+, +w+, and +d+ are the (commercial) year, week of the year,
# and day of the week of the Commercial Date to convert.
# +sg+ specifies the Day of Calendar Reform.
def commercial_to_jd(y, w, d, sg=GREGORIAN) # :nodoc:
j = find_fdoy(y, sg) + 3
(j - (((j - 1) + 1) % 7)) +
7 * (w - 1) +
(d - 1)
end
# Convert a Julian Day Number to a Commercial Date
#
# +jd+ is the Julian Day Number to convert.
# +sg+ specifies the Day of Calendar Reform.
#
# Returns the corresponding Commercial Date as
# [commercial_year, week_of_year, day_of_week]
def jd_to_commercial(jd, sg=GREGORIAN) # :nodoc:
a = jd_to_civil(jd - 3, sg)[0]
y = if jd >= commercial_to_jd(a + 1, 1, 1, sg) then a + 1 else a end
w = 1 + ((jd - commercial_to_jd(y, 1, 1, sg)) / 7).floor
d = (jd + 1) % 7
d = 7 if d == 0
return y, w, d
end
def weeknum_to_jd(y, w, d, f=0, sg=GREGORIAN) # :nodoc:
a = find_fdoy(y, sg) + 6
(a - ((a - f) + 1) % 7 - 7) + 7 * w + d
end
def jd_to_weeknum(jd, f=0, sg=GREGORIAN) # :nodoc:
y, m, d = jd_to_civil(jd, sg)
a = find_fdoy(y, sg) + 6
w, d = (jd - (a - ((a - f) + 1) % 7) + 7).divmod(7)
return y, w, d
end
def nth_kday_to_jd(y, m, n, k, sg=GREGORIAN) # :nodoc:
j = if n > 0
find_fdom(y, m, sg) - 1
else
find_ldom(y, m, sg) + 7
end
(j - (((j - k) + 1) % 7)) + 7 * n
end
def jd_to_nth_kday(jd, sg=GREGORIAN) # :nodoc:
y, m, d = jd_to_civil(jd, sg)
j = find_fdom(y, m, sg)
return y, m, ((jd - j) / 7).floor + 1, jd_to_wday(jd)
end
# Convert an Astronomical Julian Day Number to a (civil) Julian
# Day Number.
#
# +ajd+ is the Astronomical Julian Day Number to convert.
# +of+ is the offset from UTC as a fraction of a day (defaults to 0).
#
# Returns the (civil) Julian Day Number as [day_number,
# fraction] where +fraction+ is always 1/2.
def ajd_to_jd(ajd, of=0) (ajd + of + HALF_DAYS_IN_DAY).divmod(1) end # :nodoc:
# Convert a (civil) Julian Day Number to an Astronomical Julian
# Day Number.
#
# +jd+ is the Julian Day Number to convert, and +fr+ is a
# fractional day.
# +of+ is the offset from UTC as a fraction of a day (defaults to 0).
#
# Returns the Astronomical Julian Day Number as a single
# numeric value.
def jd_to_ajd(jd, fr, of=0) jd + fr - of - HALF_DAYS_IN_DAY end # :nodoc:
# Convert a fractional day +fr+ to [hours, minutes, seconds,
# fraction_of_a_second]
def day_fraction_to_time(fr) # :nodoc:
ss, fr = fr.divmod(SECONDS_IN_DAY) # 4p
h, ss = ss.divmod(3600)
min, s = ss.divmod(60)
return h, min, s, fr * 86400
end
# Convert an +h+ hour, +min+ minutes, +s+ seconds period
# to a fractional day.
begin
Rational(Rational(1, 2), 2) # a challenge
def time_to_day_fraction(h, min, s)
Rational(h * 3600 + min * 60 + s, 86400) # 4p
end
rescue
def time_to_day_fraction(h, min, s)
if Integer === h && Integer === min && Integer === s
Rational(h * 3600 + min * 60 + s, 86400) # 4p
else
(h * 3600 + min * 60 + s).to_r/86400 # 4p
end
end
end
# Convert an Astronomical Modified Julian Day Number to an
# Astronomical Julian Day Number.
def amjd_to_ajd(amjd) amjd + MJD_EPOCH_IN_AJD end # :nodoc:
# Convert an Astronomical Julian Day Number to an
# Astronomical Modified Julian Day Number.
def ajd_to_amjd(ajd) ajd - MJD_EPOCH_IN_AJD end # :nodoc:
# Convert a Modified Julian Day Number to a Julian
# Day Number.
def mjd_to_jd(mjd) mjd + MJD_EPOCH_IN_CJD end # :nodoc:
# Convert a Julian Day Number to a Modified Julian Day
# Number.
def jd_to_mjd(jd) jd - MJD_EPOCH_IN_CJD end # :nodoc:
# Convert a count of the number of days since the adoption
# of the Gregorian Calendar (in Italy) to a Julian Day Number.
def ld_to_jd(ld) ld + LD_EPOCH_IN_CJD end # :nodoc:
# Convert a Julian Day Number to the number of days since
# the adoption of the Gregorian Calendar (in Italy).
def jd_to_ld(jd) jd - LD_EPOCH_IN_CJD end # :nodoc:
# Convert a Julian Day Number to the day of the week.
#
# Sunday is day-of-week 0; Saturday is day-of-week 6.
def jd_to_wday(jd) (jd + 1) % 7 end # :nodoc:
# Is +jd+ a valid Julian Day Number?
#
# If it is, returns it. In fact, any value is treated as a valid
# Julian Day Number.
def _valid_jd? (jd, sg=GREGORIAN) jd end # :nodoc:
# Do the year +y+ and day-of-year +d+ make a valid Ordinal Date?
# Returns the corresponding Julian Day Number if they do, or
# nil if they don't.
#
# +d+ can be a negative number, in which case it counts backwards
# from the end of the year (-1 being the last day of the year).
# No year wraparound is performed, however, so valid values of
# +d+ are -365 .. -1, 1 .. 365 on a non-leap-year,
# -366 .. -1, 1 .. 366 on a leap year.
# A date falling in the period skipped in the Day of Calendar Reform
# adjustment is not valid.
#
# +sg+ specifies the Day of Calendar Reform.
def _valid_ordinal? (y, d, sg=GREGORIAN) # :nodoc:
if d < 0
j = find_ldoy(y, sg)
ny, nd = jd_to_ordinal(j + d + 1, sg)
return unless ny == y
d = nd
end
jd = ordinal_to_jd(y, d, sg)
return unless [y, d] == jd_to_ordinal(jd, sg)
jd
end
# Do year +y+, month +m+, and day-of-month +d+ make a
# valid Civil Date? Returns the corresponding Julian
# Day Number if they do, nil if they don't.
#
# +m+ and +d+ can be negative, in which case they count
# backwards from the end of the year and the end of the
# month respectively. No wraparound is performed, however,
# and invalid values cause an ArgumentError to be raised.
# A date falling in the period skipped in the Day of Calendar
# Reform adjustment is not valid.
#
# +sg+ specifies the Day of Calendar Reform.
def _valid_civil? (y, m, d, sg=GREGORIAN) # :nodoc:
if m < 0
m += 13
end
if d < 0
j = find_ldom(y, m, sg)
ny, nm, nd = jd_to_civil(j + d + 1, sg)
return unless [ny, nm] == [y, m]
d = nd
end
jd = civil_to_jd(y, m, d, sg)
return unless [y, m, d] == jd_to_civil(jd, sg)
jd
end
# Do year +y+, week-of-year +w+, and day-of-week +d+ make a
# valid Commercial Date? Returns the corresponding Julian
# Day Number if they do, nil if they don't.
#
# Monday is day-of-week 1; Sunday is day-of-week 7.
#
# +w+ and +d+ can be negative, in which case they count
# backwards from the end of the year and the end of the
# week respectively. No wraparound is performed, however,
# and invalid values cause an ArgumentError to be raised.
# A date falling in the period skipped in the Day of Calendar
# Reform adjustment is not valid.
#
# +sg+ specifies the Day of Calendar Reform.
def _valid_commercial? (y, w, d, sg=GREGORIAN) # :nodoc:
if d < 0
d += 8
end
if w < 0
ny, nw, nd =
jd_to_commercial(commercial_to_jd(y + 1, 1, 1, sg) + w * 7, sg)
return unless ny == y
w = nw
end
jd = commercial_to_jd(y, w, d, sg)
return unless [y, w, d] == jd_to_commercial(jd, sg)
jd
end
def _valid_weeknum? (y, w, d, f, sg=GREGORIAN) # :nodoc:
if d < 0
d += 7
end
if w < 0
ny, nw, nd, nf =
jd_to_weeknum(weeknum_to_jd(y + 1, 1, f, f, sg) + w * 7, f, sg)
return unless ny == y
w = nw
end
jd = weeknum_to_jd(y, w, d, f, sg)
return unless [y, w, d] == jd_to_weeknum(jd, f, sg)
jd
end
def _valid_nth_kday? (y, m, n, k, sg=GREGORIAN) # :nodoc:
if k < 0
k += 7
end
if n < 0
ny, nm = (y * 12 + m).divmod(12)
nm, = (nm + 1) .divmod(1)
ny, nm, nn, nk =
jd_to_nth_kday(nth_kday_to_jd(ny, nm, 1, k, sg) + n * 7, sg)
return unless [ny, nm] == [y, m]
n = nn
end
jd = nth_kday_to_jd(y, m, n, k, sg)
return unless [y, m, n, k] == jd_to_nth_kday(jd, sg)
jd
end
# Do hour +h+, minute +min+, and second +s+ constitute a valid time?
#
# If they do, returns their value as a fraction of a day. If not,
# returns nil.
#
# The 24-hour clock is used. Negative values of +h+, +min+, and
# +sec+ are treating as counting backwards from the end of the
# next larger unit (e.g. a +min+ of -2 is treated as 58). No
# wraparound is performed.
def _valid_time? (h, min, s) # :nodoc:
h += 24 if h < 0
min += 60 if min < 0
s += 60 if s < 0
return unless ((0...24) === h &&
(0...60) === min &&
(0...60) === s) ||
(24 == h &&
0 == min &&
0 == s)
time_to_day_fraction(h, min, s)
end
end
extend t
include t
# Is a year a leap year in the Julian calendar?
#
# All years divisible by 4 are leap years in the Julian calendar.
def self.julian_leap? (y) y % 4 == 0 end
# Is a year a leap year in the Gregorian calendar?
#
# All years divisible by 4 are leap years in the Gregorian calendar,
# except for years divisible by 100 and not by 400.
def self.gregorian_leap? (y) y % 4 == 0 && y % 100 != 0 || y % 400 == 0 end
class << self; alias_method :leap?, :gregorian_leap? end
class << self; alias_method :new!, :new end
def self.valid_jd? (jd, sg=ITALY)
!!_valid_jd?(jd, sg)
end
def self.valid_ordinal? (y, d, sg=ITALY)
!!_valid_ordinal?(y, d, sg)
end
def self.valid_civil? (y, m, d, sg=ITALY)
!!_valid_civil?(y, m, d, sg)
end
class << self; alias_method :valid_date?, :valid_civil? end
def self.valid_commercial? (y, w, d, sg=ITALY)
!!_valid_commercial?(y, w, d, sg)
end
def self.valid_weeknum? (y, w, d, f, sg=ITALY) # :nodoc:
!!_valid_weeknum?(y, w, d, f, sg)
end
private_class_method :valid_weeknum?
def self.valid_nth_kday? (y, m, n, k, sg=ITALY) # :nodoc:
!!_valid_nth_kday?(y, m, n, k, sg)
end
private_class_method :valid_nth_kday?
def self.valid_time? (h, min, s) # :nodoc:
!!_valid_time?(h, min, s)
end
private_class_method :valid_time?
# Create a new Date object from a Julian Day Number.
#
# +jd+ is the Julian Day Number; if not specified, it defaults to
# 0.
# +sg+ specifies the Day of Calendar Reform.
def self.jd(jd=0, sg=ITALY)
jd = _valid_jd?(jd, sg)
new!(jd_to_ajd(jd, 0, 0), 0, sg)
end
# Create a new Date object from an Ordinal Date, specified
# by year +y+ and day-of-year +d+. +d+ can be negative,
# in which it counts backwards from the end of the year.
# No year wraparound is performed, however. An invalid
# value for +d+ results in an ArgumentError being raised.
#
# +y+ defaults to -4712, and +d+ to 1; this is Julian Day
# Number day 0.
#
# +sg+ specifies the Day of Calendar Reform.
def self.ordinal(y=-4712, d=1, sg=ITALY)
unless jd = _valid_ordinal?(y, d, sg)
raise ArgumentError, 'invalid date'
end
new!(jd_to_ajd(jd, 0, 0), 0, sg)
end
# Create a new Date object for the Civil Date specified by
# year +y+, month +m+, and day-of-month +d+.
#
# +m+ and +d+ can be negative, in which case they count
# backwards from the end of the year and the end of the
# month respectively. No wraparound is performed, however,
# and invalid values cause an ArgumentError to be raised.
# can be negative
#
# +y+ defaults to -4712, +m+ to 1, and +d+ to 1; this is
# Julian Day Number day 0.
#
# +sg+ specifies the Day of Calendar Reform.
def self.civil(y=-4712, m=1, d=1, sg=ITALY)
unless jd = _valid_civil?(y, m, d, sg)
raise ArgumentError, 'invalid date'
end
new!(jd_to_ajd(jd, 0, 0), 0, sg)
end
class << self; alias_method :new, :civil end
# Create a new Date object for the Commercial Date specified by
# year +y+, week-of-year +w+, and day-of-week +d+.
#
# Monday is day-of-week 1; Sunday is day-of-week 7.
#
# +w+ and +d+ can be negative, in which case they count
# backwards from the end of the year and the end of the
# week respectively. No wraparound is performed, however,
# and invalid values cause an ArgumentError to be raised.
#
# +y+ defaults to -4712, +w+ to 1, and +d+ to 1; this is
# Julian Day Number day 0.
#
# +sg+ specifies the Day of Calendar Reform.
def self.commercial(y=-4712, w=1, d=1, sg=ITALY)
unless jd = _valid_commercial?(y, w, d, sg)
raise ArgumentError, 'invalid date'
end
new!(jd_to_ajd(jd, 0, 0), 0, sg)
end
def self.weeknum(y=-4712, w=0, d=1, f=0, sg=ITALY)
unless jd = _valid_weeknum?(y, w, d, f, sg)
raise ArgumentError, 'invalid date'
end
new!(jd_to_ajd(jd, 0, 0), 0, sg)
end
private_class_method :weeknum
def self.nth_kday(y=-4712, m=1, n=1, k=1, sg=ITALY)
unless jd = _valid_nth_kday?(y, m, n, k, sg)
raise ArgumentError, 'invalid date'
end
new!(jd_to_ajd(jd, 0, 0), 0, sg)
end
private_class_method :nth_kday
def self.rewrite_frags(elem) # :nodoc:
elem ||= {}
if seconds = elem[:seconds]
d, fr = seconds.divmod(86400)
h, fr = fr.divmod(3600)
min, fr = fr.divmod(60)
s, fr = fr.divmod(1)
elem[:jd] = UNIX_EPOCH_IN_CJD + d
elem[:hour] = h
elem[:min] = min
elem[:sec] = s
elem[:sec_fraction] = fr
elem.delete(:seconds)
elem.delete(:offset)
end
elem
end
private_class_method :rewrite_frags
def self.complete_frags(elem) # :nodoc:
i = 0
g = [[:time, [:hour, :min, :sec]],
[nil, [:jd]],
[:ordinal, [:year, :yday, :hour, :min, :sec]],
[:civil, [:year, :mon, :mday, :hour, :min, :sec]],
[:commercial, [:cwyear, :cweek, :cwday, :hour, :min, :sec]],
[:wday, [:wday, :hour, :min, :sec]],
[:wnum0, [:year, :wnum0, :wday, :hour, :min, :sec]],
[:wnum1, [:year, :wnum1, :wday, :hour, :min, :sec]],
[nil, [:cwyear, :cweek, :wday, :hour, :min, :sec]],
[nil, [:year, :wnum0, :cwday, :hour, :min, :sec]],
[nil, [:year, :wnum1, :cwday, :hour, :min, :sec]]].
collect{|k, a| e = elem.values_at(*a).compact; [k, a, e]}.
select{|k, a, e| e.size > 0}.
sort_by{|k, a, e| [e.size, i -= 1]}.last
d = nil
if g && g[0] && (g[1].size - g[2].size) != 0
d ||= Date.today
case g[0]
when :ordinal
elem[:year] ||= d.year
elem[:yday] ||= 1
when :civil
g[1].each do |e|
break if elem[e]
elem[e] = d.__send__(e)
end
elem[:mon] ||= 1
elem[:mday] ||= 1
when :commercial
g[1].each do |e|
break if elem[e]
elem[e] = d.__send__(e)
end
elem[:cweek] ||= 1
elem[:cwday] ||= 1
when :wday
elem[:jd] ||= (d - d.wday + elem[:wday]).jd
when :wnum0
g[1].each do |e|
break if elem[e]
elem[e] = d.__send__(e)
end
elem[:wnum0] ||= 0
elem[:wday] ||= 0
when :wnum1
g[1].each do |e|
break if elem[e]
elem[e] = d.__send__(e)
end
elem[:wnum1] ||= 0
elem[:wday] ||= 1
end
end
if g && g[0] == :time
if self <= DateTime
d ||= Date.today
elem[:jd] ||= d.jd
end
end
elem[:hour] ||= 0
elem[:min] ||= 0
elem[:sec] ||= 0
elem[:sec] = [elem[:sec], 59].min
elem
end
private_class_method :complete_frags
def self.valid_date_frags?(elem, sg) # :nodoc:
catch :jd do
a = elem.values_at(:jd)
if a.all?
if jd = _valid_jd?(*(a << sg))
throw :jd, jd
end
end
a = elem.values_at(:year, :yday)
if a.all?
if jd = _valid_ordinal?(*(a << sg))
throw :jd, jd
end
end
a = elem.values_at(:year, :mon, :mday)
if a.all?
if jd = _valid_civil?(*(a << sg))
throw :jd, jd
end
end
a = elem.values_at(:cwyear, :cweek, :cwday)
if a[2].nil? && elem[:wday]
a[2] = elem[:wday].nonzero? || 7
end
if a.all?
if jd = _valid_commercial?(*(a << sg))
throw :jd, jd
end
end
a = elem.values_at(:year, :wnum0, :wday)
if a[2].nil? && elem[:cwday]
a[2] = elem[:cwday] % 7
end
if a.all?
if jd = _valid_weeknum?(*(a << 0 << sg))
throw :jd, jd
end
end
a = elem.values_at(:year, :wnum1, :wday)
if a[2]
a[2] = (a[2] - 1) % 7
end
if a[2].nil? && elem[:cwday]
a[2] = (elem[:cwday] - 1) % 7
end
if a.all?
if jd = _valid_weeknum?(*(a << 1 << sg))
throw :jd, jd
end
end
end
end
private_class_method :valid_date_frags?
def self.valid_time_frags? (elem) # :nodoc:
h, min, s = elem.values_at(:hour, :min, :sec)
_valid_time?(h, min, s)
end
private_class_method :valid_time_frags?
def self.new_by_frags(elem, sg) # :nodoc:
elem = rewrite_frags(elem)
elem = complete_frags(elem)
unless jd = valid_date_frags?(elem, sg)
raise ArgumentError, 'invalid date'
end
new!(jd_to_ajd(jd, 0, 0), 0, sg)
end
private_class_method :new_by_frags
# Create a new Date object by parsing from a String
# according to a specified format.
#
# +str+ is a String holding a date representation.
# +fmt+ is the format that the date is in. See
# date/format.rb for details on supported formats.
#
# The default +str+ is '-4712-01-01', and the default
# +fmt+ is '%F', which means Year-Month-Day_of_Month.
| 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/pp.rb | tools/jruby-1.5.1/lib/ruby/1.9/pp.rb | # == Pretty-printer for Ruby objects.
#
# = Which seems better?
#
# non-pretty-printed output by #p is:
# #<PP:0x81fedf0 @genspace=#<Proc:0x81feda0>, @group_queue=#<PrettyPrint::GroupQueue:0x81fed3c @queue=[[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], []]>, @buffer=[], @newline="\n", @group_stack=[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], @buffer_width=0, @indent=0, @maxwidth=79, @output_width=2, @output=#<IO:0x8114ee4>>
#
# pretty-printed output by #pp is:
# #<PP:0x81fedf0
# @buffer=[],
# @buffer_width=0,
# @genspace=#<Proc:0x81feda0>,
# @group_queue=
# #<PrettyPrint::GroupQueue:0x81fed3c
# @queue=
# [[#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
# []]>,
# @group_stack=
# [#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
# @indent=0,
# @maxwidth=79,
# @newline="\n",
# @output=#<IO:0x8114ee4>,
# @output_width=2>
#
# I like the latter. If you do too, this library is for you.
#
# = Usage
#
# pp(obj)
#
# output +obj+ to +$>+ in pretty printed format.
#
# It returns +nil+.
#
# = Output Customization
# To define your customized pretty printing function for your classes,
# redefine a method #pretty_print(+pp+) in the class.
# It takes an argument +pp+ which is an instance of the class PP.
# The method should use PP#text, PP#breakable, PP#nest, PP#group and
# PP#pp to print the object.
#
# = Author
# Tanaka Akira <akr@m17n.org>
require 'prettyprint'
module Kernel
# returns a pretty printed object as a string.
def pretty_inspect
PP.pp(self, '')
end
private
# prints arguments in pretty form.
#
# pp returns nil.
def pp(*objs) # :doc:
objs.each {|obj|
PP.pp(obj)
}
nil
end
module_function :pp
end
class PP < PrettyPrint
# Outputs +obj+ to +out+ in pretty printed format of
# +width+ columns in width.
#
# If +out+ is omitted, +$>+ is assumed.
# If +width+ is omitted, 79 is assumed.
#
# PP.pp returns +out+.
def PP.pp(obj, out=$>, width=79)
q = PP.new(out, width)
q.guard_inspect_key {q.pp obj}
q.flush
#$pp = q
out << "\n"
end
# Outputs +obj+ to +out+ like PP.pp but with no indent and
# newline.
#
# PP.singleline_pp returns +out+.
def PP.singleline_pp(obj, out=$>)
q = SingleLine.new(out)
q.guard_inspect_key {q.pp obj}
q.flush
out
end
# :stopdoc:
def PP.mcall(obj, mod, meth, *args, &block)
mod.instance_method(meth).bind(obj).call(*args, &block)
end
# :startdoc:
@sharing_detection = false
class << self
# Returns the sharing detection flag as a boolean value.
# It is false by default.
attr_accessor :sharing_detection
end
module PPMethods
def guard_inspect_key
if Thread.current[:__recursive_key__] == nil
Thread.current[:__recursive_key__] = {}.untrust
end
if Thread.current[:__recursive_key__][:inspect] == nil
Thread.current[:__recursive_key__][:inspect] = {}.untrust
end
save = Thread.current[:__recursive_key__][:inspect]
begin
Thread.current[:__recursive_key__][:inspect] = {}.untrust
yield
ensure
Thread.current[:__recursive_key__][:inspect] = save
end
end
def check_inspect_key(id)
Thread.current[:__recursive_key__] &&
Thread.current[:__recursive_key__][:inspect] &&
Thread.current[:__recursive_key__][:inspect].include?(id)
end
def push_inspect_key(id)
Thread.current[:__recursive_key__][:inspect][id] = true
end
def pop_inspect_key(id)
Thread.current[:__recursive_key__][:inspect].delete id
end
# Adds +obj+ to the pretty printing buffer
# using Object#pretty_print or Object#pretty_print_cycle.
#
# Object#pretty_print_cycle is used when +obj+ is already
# printed, a.k.a the object reference chain has a cycle.
def pp(obj)
id = obj.object_id
if check_inspect_key(id)
group {obj.pretty_print_cycle self}
return
end
begin
push_inspect_key(id)
group {obj.pretty_print self}
ensure
pop_inspect_key(id) unless PP.sharing_detection
end
end
# A convenience method which is same as follows:
#
# group(1, '#<' + obj.class.name, '>') { ... }
def object_group(obj, &block) # :yield:
group(1, '#<' + obj.class.name, '>', &block)
end
if 0x100000000.class == Bignum
# 32bit
PointerMask = 0xffffffff
else
# 64bit
PointerMask = 0xffffffffffffffff
end
case Object.new.inspect
when /\A\#<Object:0x([0-9a-f]+)>\z/
PointerFormat = "%0#{$1.length}x"
else
PointerFormat = "%x"
end
def object_address_group(obj, &block)
id = PointerFormat % (obj.object_id * 2 & PointerMask)
group(1, "\#<#{obj.class}:0x#{id}", '>', &block)
end
# A convenience method which is same as follows:
#
# text ','
# breakable
def comma_breakable
text ','
breakable
end
# Adds a separated list.
# The list is separated by comma with breakable space, by default.
#
# #seplist iterates the +list+ using +iter_method+.
# It yields each object to the block given for #seplist.
# The procedure +separator_proc+ is called between each yields.
#
# If the iteration is zero times, +separator_proc+ is not called at all.
#
# If +separator_proc+ is nil or not given,
# +lambda { comma_breakable }+ is used.
# If +iter_method+ is not given, :each is used.
#
# For example, following 3 code fragments has similar effect.
#
# q.seplist([1,2,3]) {|v| xxx v }
#
# q.seplist([1,2,3], lambda { q.comma_breakable }, :each) {|v| xxx v }
#
# xxx 1
# q.comma_breakable
# xxx 2
# q.comma_breakable
# xxx 3
def seplist(list, sep=nil, iter_method=:each) # :yield: element
sep ||= lambda { comma_breakable }
first = true
list.__send__(iter_method) {|*v|
if first
first = false
else
sep.call
end
yield(*v)
}
end
def pp_object(obj)
object_address_group(obj) {
seplist(obj.pretty_print_instance_variables, lambda { text ',' }) {|v|
breakable
v = v.to_s if Symbol === v
text v
text '='
group(1) {
breakable ''
pp(obj.instance_eval(v))
}
}
}
end
def pp_hash(obj)
group(1, '{', '}') {
seplist(obj, nil, :each_pair) {|k, v|
group {
pp k
text '=>'
group(1) {
breakable ''
pp v
}
}
}
}
end
end
include PPMethods
class SingleLine < PrettyPrint::SingleLine
include PPMethods
end
module ObjectMixin
# 1. specific pretty_print
# 2. specific inspect
# 3. specific to_s if instance variable is empty
# 4. generic pretty_print
# A default pretty printing method for general objects.
# It calls #pretty_print_instance_variables to list instance variables.
#
# If +self+ has a customized (redefined) #inspect method,
# the result of self.inspect is used but it obviously has no
# line break hints.
#
# This module provides predefined #pretty_print methods for some of
# the most commonly used built-in classes for convenience.
def pretty_print(q)
if /\(Kernel\)#/ !~ Object.instance_method(:method).bind(self).call(:inspect).inspect
q.text self.inspect
elsif /\(Kernel\)#/ !~ Object.instance_method(:method).bind(self).call(:to_s).inspect && instance_variables.empty?
q.text self.to_s
else
q.pp_object(self)
end
end
# A default pretty printing method for general objects that are
# detected as part of a cycle.
def pretty_print_cycle(q)
q.object_address_group(self) {
q.breakable
q.text '...'
}
end
# Returns a sorted array of instance variable names.
#
# This method should return an array of names of instance variables as symbols or strings as:
# +[:@a, :@b]+.
def pretty_print_instance_variables
instance_variables.sort
end
# Is #inspect implementation using #pretty_print.
# If you implement #pretty_print, it can be used as follows.
#
# alias inspect pretty_print_inspect
#
# However, doing this requires that every class that #inspect is called on
# implement #pretty_print, or a RuntimeError will be raised.
def pretty_print_inspect
if /\(PP::ObjectMixin\)#/ =~ Object.instance_method(:method).bind(self).call(:pretty_print).inspect
raise "pretty_print is not overridden for #{self.class}"
end
PP.singleline_pp(self, '')
end
end
end
class Array
def pretty_print(q)
q.group(1, '[', ']') {
q.seplist(self) {|v|
q.pp v
}
}
end
def pretty_print_cycle(q)
q.text(empty? ? '[]' : '[...]')
end
end
class Hash
def pretty_print(q)
q.pp_hash self
end
def pretty_print_cycle(q)
q.text(empty? ? '{}' : '{...}')
end
end
class << ENV
def pretty_print(q)
h = {}
ENV.keys.sort.each {|k|
h[k] = ENV[k]
}
q.pp_hash h
end
end
class Struct
def pretty_print(q)
q.group(1, sprintf("#<struct %s", PP.mcall(self, Kernel, :class).name), '>') {
q.seplist(PP.mcall(self, Struct, :members), lambda { q.text "," }) {|member|
q.breakable
q.text member.to_s
q.text '='
q.group(1) {
q.breakable ''
q.pp self[member]
}
}
}
end
def pretty_print_cycle(q)
q.text sprintf("#<struct %s:...>", PP.mcall(self, Kernel, :class).name)
end
end
class Range
def pretty_print(q)
q.pp self.begin
q.breakable ''
q.text(self.exclude_end? ? '...' : '..')
q.breakable ''
q.pp self.end
end
end
class File
class Stat
def pretty_print(q)
require 'etc.so'
q.object_group(self) {
q.breakable
q.text sprintf("dev=0x%x", self.dev); q.comma_breakable
q.text "ino="; q.pp self.ino; q.comma_breakable
q.group {
m = self.mode
q.text sprintf("mode=0%o", m)
q.breakable
q.text sprintf("(%s %c%c%c%c%c%c%c%c%c)",
self.ftype,
(m & 0400 == 0 ? ?- : ?r),
(m & 0200 == 0 ? ?- : ?w),
(m & 0100 == 0 ? (m & 04000 == 0 ? ?- : ?S) :
(m & 04000 == 0 ? ?x : ?s)),
(m & 0040 == 0 ? ?- : ?r),
(m & 0020 == 0 ? ?- : ?w),
(m & 0010 == 0 ? (m & 02000 == 0 ? ?- : ?S) :
(m & 02000 == 0 ? ?x : ?s)),
(m & 0004 == 0 ? ?- : ?r),
(m & 0002 == 0 ? ?- : ?w),
(m & 0001 == 0 ? (m & 01000 == 0 ? ?- : ?T) :
(m & 01000 == 0 ? ?x : ?t)))
}
q.comma_breakable
q.text "nlink="; q.pp self.nlink; q.comma_breakable
q.group {
q.text "uid="; q.pp self.uid
begin
pw = Etc.getpwuid(self.uid)
rescue ArgumentError
end
if pw
q.breakable; q.text "(#{pw.name})"
end
}
q.comma_breakable
q.group {
q.text "gid="; q.pp self.gid
begin
gr = Etc.getgrgid(self.gid)
rescue ArgumentError
end
if gr
q.breakable; q.text "(#{gr.name})"
end
}
q.comma_breakable
q.group {
q.text sprintf("rdev=0x%x", self.rdev)
q.breakable
q.text sprintf('(%d, %d)', self.rdev_major, self.rdev_minor)
}
q.comma_breakable
q.text "size="; q.pp self.size; q.comma_breakable
q.text "blksize="; q.pp self.blksize; q.comma_breakable
q.text "blocks="; q.pp self.blocks; q.comma_breakable
q.group {
t = self.atime
q.text "atime="; q.pp t
q.breakable; q.text "(#{t.tv_sec})"
}
q.comma_breakable
q.group {
t = self.mtime
q.text "mtime="; q.pp t
q.breakable; q.text "(#{t.tv_sec})"
}
q.comma_breakable
q.group {
t = self.ctime
q.text "ctime="; q.pp t
q.breakable; q.text "(#{t.tv_sec})"
}
}
end
end
end
class MatchData
def pretty_print(q)
nc = []
self.regexp.named_captures.each {|name, indexes|
indexes.each {|i| nc[i] = name }
}
q.object_group(self) {
q.breakable
q.seplist(0...self.size, lambda { q.breakable }) {|i|
if i == 0
q.pp self[i]
else
if nc[i]
q.text nc[i]
else
q.pp i
end
q.text ':'
q.pp self[i]
end
}
}
end
end
class Object
include PP::ObjectMixin
end
[Numeric, Symbol, FalseClass, TrueClass, NilClass, Module].each {|c|
c.class_eval {
def pretty_print_cycle(q)
q.text inspect
end
}
}
[Numeric, FalseClass, TrueClass, Module].each {|c|
c.class_eval {
def pretty_print(q)
q.text inspect
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/resolv-replace.rb | tools/jruby-1.5.1/lib/ruby/1.9/resolv-replace.rb | require 'socket'
require 'resolv'
class << IPSocket
alias original_resolv_getaddress getaddress
def getaddress(host)
begin
return Resolv.getaddress(host).to_s
rescue Resolv::ResolvError
raise SocketError, "Hostname not known: #{host}"
end
end
end
class TCPSocket
alias original_resolv_initialize initialize
def initialize(host, serv, *rest)
rest[0] = IPSocket.getaddress(rest[0]) unless rest.empty?
original_resolv_initialize(IPSocket.getaddress(host), serv, *rest)
end
end
class UDPSocket
alias original_resolv_bind bind
def bind(host, port)
host = IPSocket.getaddress(host) if host != ""
original_resolv_bind(host, port)
end
alias original_resolv_connect connect
def connect(host, port)
original_resolv_connect(IPSocket.getaddress(host), port)
end
alias original_resolv_send send
def send(mesg, flags, *rest)
if rest.length == 2
host, port = rest
begin
addrs = Resolv.getaddresses(host)
rescue Resolv::ResolvError
raise SocketError, "Hostname not known: #{host}"
end
err = nil
addrs[0...-1].each {|addr|
begin
return original_resolv_send(mesg, flags, addr, port)
rescue SystemCallError
end
}
original_resolv_send(mesg, flags, addrs[-1], port)
else
original_resolv_send(mesg, flags, *rest)
end
end
end
class SOCKSSocket
alias original_resolv_initialize initialize
def initialize(host, serv)
original_resolv_initialize(IPSocket.getaddress(host), port)
end
end if defined? SOCKSSocket
| 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/e2mmap.rb | tools/jruby-1.5.1/lib/ruby/1.9/e2mmap.rb | #
# e2mmap.rb - for ruby 1.1
# $Release Version: 2.0$
# $Revision: 1.10 $
# by Keiju ISHITSUKA
#
# --
# Usage:
#
# U1)
# class Foo
# extend Exception2MessageMapper
# def_e2message ExistingExceptionClass, "message..."
# def_exception :NewExceptionClass, "message..."[, superclass]
# ...
# end
#
# U2)
# module Error
# extend Exception2MessageMapper
# def_e2meggage ExistingExceptionClass, "message..."
# def_exception :NewExceptionClass, "message..."[, superclass]
# ...
# end
# class Foo
# include Error
# ...
# end
#
# foo = Foo.new
# foo.Fail ....
#
# U3)
# module Error
# extend Exception2MessageMapper
# def_e2message ExistingExceptionClass, "message..."
# def_exception :NewExceptionClass, "message..."[, superclass]
# ...
# end
# class Foo
# extend Exception2MessageMapper
# include Error
# ...
# end
#
# Foo.Fail NewExceptionClass, arg...
# Foo.Fail ExistingExceptionClass, arg...
#
#
module Exception2MessageMapper
@RCS_ID='-$Id: e2mmap.rb,v 1.10 1999/02/17 12:33:17 keiju Exp keiju $-'
E2MM = Exception2MessageMapper
def E2MM.extend_object(cl)
super
cl.bind(self) unless cl < E2MM
end
def bind(cl)
self.module_eval %[
def Raise(err = nil, *rest)
Exception2MessageMapper.Raise(self.class, err, *rest)
end
alias Fail Raise
def self.included(mod)
mod.extend Exception2MessageMapper
end
]
end
# Fail(err, *rest)
# err: exception
# rest: message arguments
#
def Raise(err = nil, *rest)
E2MM.Raise(self, err, *rest)
end
alias Fail Raise
alias fail Raise
# def_e2message(c, m)
# c: exception
# m: message_form
# define exception c with message m.
#
def def_e2message(c, m)
E2MM.def_e2message(self, c, m)
end
# def_exception(n, m, s)
# n: exception_name
# m: message_form
# s: superclass(default: StandardError)
# define exception named ``c'' with message m.
#
def def_exception(n, m, s = StandardError)
E2MM.def_exception(self, n, m, s)
end
#
# Private definitions.
#
# {[class, exp] => message, ...}
@MessageMap = {}
# E2MM.def_e2message(k, e, m)
# k: class to define exception under.
# e: exception
# m: message_form
# define exception c with message m.
#
def E2MM.def_e2message(k, c, m)
E2MM.instance_eval{@MessageMap[[k, c]] = m}
c
end
# E2MM.def_exception(k, n, m, s)
# k: class to define exception under.
# n: exception_name
# m: message_form
# s: superclass(default: StandardError)
# define exception named ``c'' with message m.
#
def E2MM.def_exception(k, n, m, s = StandardError)
n = n.id2name if n.kind_of?(Fixnum)
e = Class.new(s)
E2MM.instance_eval{@MessageMap[[k, e]] = m}
k.const_set(n, e)
end
# Fail(klass, err, *rest)
# klass: class to define exception under.
# err: exception
# rest: message arguments
#
def E2MM.Raise(klass = E2MM, err = nil, *rest)
if form = e2mm_message(klass, err)
b = $@.nil? ? caller(1) : $@
#p $@
#p __FILE__
b.shift if b[0] =~ /^#{Regexp.quote(__FILE__)}:/
raise err, sprintf(form, *rest), b
else
E2MM.Fail E2MM, ErrNotRegisteredException, err.inspect
end
end
class <<E2MM
alias Fail Raise
end
def E2MM.e2mm_message(klass, exp)
for c in klass.ancestors
if mes = @MessageMap[[c,exp]]
#p mes
m = klass.instance_eval('"' + mes + '"')
return m
end
end
nil
end
class <<self
alias message e2mm_message
end
E2MM.def_exception(E2MM,
:ErrNotRegisteredException,
"not registerd exception(%s)")
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/cmath.rb | tools/jruby-1.5.1/lib/ruby/1.9/cmath.rb | module CMath
include Math
alias exp! exp
alias log! log
alias log2! log2
alias log10! log10
alias sqrt! sqrt
alias cbrt! cbrt
alias sin! sin
alias cos! cos
alias tan! tan
alias sinh! sinh
alias cosh! cosh
alias tanh! tanh
alias asin! asin
alias acos! acos
alias atan! atan
alias atan2! atan2
alias asinh! asinh
alias acosh! acosh
alias atanh! atanh
def exp(z)
if z.real?
exp!(z)
else
ere = exp!(z.real)
Complex(ere * cos!(z.imag),
ere * sin!(z.imag))
end
end
def log(*args)
z, b = args
if z.real? and z >= 0 and (b.nil? or b >= 0)
log!(*args)
else
a = Complex(log!(z.abs), z.arg)
if b
a /= log(b)
end
a
end
end
def log2(z)
if z.real? and z >= 0
log2!(z)
else
log(z) / log!(2)
end
end
def log10(z)
if z.real? and z >= 0
log10!(z)
else
log(z) / log!(10)
end
end
def sqrt(z)
if z.real?
if z < 0
Complex(0, sqrt!(-z))
else
sqrt!(z)
end
else
if z.imag < 0 ||
(z.imag == 0 && z.imag.to_s[0] == '-')
sqrt(z.conjugate).conjugate
else
r = z.abs
x = z.real
Complex(sqrt!((r + x) / 2), sqrt!((r - x) / 2))
end
end
end
def cbrt(z)
if z.real? and z >= 0
cbrt!(z)
else
Complex(z) ** (1.0/3)
end
end
def sin(z)
if z.real?
sin!(z)
else
Complex(sin!(z.real) * cosh!(z.imag),
cos!(z.real) * sinh!(z.imag))
end
end
def cos(z)
if z.real?
cos!(z)
else
Complex(cos!(z.real) * cosh!(z.imag),
-sin!(z.real) * sinh!(z.imag))
end
end
def tan(z)
if z.real?
tan!(z)
else
sin(z) / cos(z)
end
end
def sinh(z)
if z.real?
sinh!(z)
else
Complex(sinh!(z.real) * cos!(z.imag),
cosh!(z.real) * sin!(z.imag))
end
end
def cosh(z)
if z.real?
cosh!(z)
else
Complex(cosh!(z.real) * cos!(z.imag),
sinh!(z.real) * sin!(z.imag))
end
end
def tanh(z)
if z.real?
tanh!(z)
else
sinh(z) / cosh(z)
end
end
def asin(z)
if z.real? and z >= -1 and z <= 1
asin!(z)
else
(-1.0).i * log(1.0.i * z + sqrt(1.0 - z * z))
end
end
def acos(z)
if z.real? and z >= -1 and z <= 1
acos!(z)
else
(-1.0).i * log(z + 1.0.i * sqrt(1.0 - z * z))
end
end
def atan(z)
if z.real?
atan!(z)
else
1.0.i * log((1.0.i + z) / (1.0.i - z)) / 2.0
end
end
def atan2(y,x)
if y.real? and x.real?
atan2!(y,x)
else
(-1.0).i * log((x + 1.0.i * y) / sqrt(x * x + y * y))
end
end
def asinh(z)
if z.real?
asinh!(z)
else
log(z + sqrt(1.0 + z * z))
end
end
def acosh(z)
if z.real? and z >= 1
acosh!(z)
else
log(z + sqrt(z * z - 1.0))
end
end
def atanh(z)
if z.real? and z >= -1 and z <= 1
atanh!(z)
else
log((1.0 + z) / (1.0 - z)) / 2.0
end
end
module_function :exp!
module_function :exp
module_function :log!
module_function :log
module_function :log2!
module_function :log2
module_function :log10!
module_function :log10
module_function :sqrt!
module_function :sqrt
module_function :cbrt!
module_function :cbrt
module_function :sin!
module_function :sin
module_function :cos!
module_function :cos
module_function :tan!
module_function :tan
module_function :sinh!
module_function :sinh
module_function :cosh!
module_function :cosh
module_function :tanh!
module_function :tanh
module_function :asin!
module_function :asin
module_function :acos!
module_function :acos
module_function :atan!
module_function :atan
module_function :atan2!
module_function :atan2
module_function :asinh!
module_function :asinh
module_function :acosh!
module_function :acosh
module_function :atanh!
module_function :atanh
module_function :frexp
module_function :ldexp
module_function :hypot
module_function :erf
module_function :erfc
module_function :gamma
module_function :lgamma
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/cgi/core.rb | tools/jruby-1.5.1/lib/ruby/1.9/cgi/core.rb | class CGI
$CGI_ENV = ENV # for FCGI support
# String for carriage return
CR = "\015"
# String for linefeed
LF = "\012"
# Standard internet newline sequence
EOL = CR + LF
REVISION = '$Id: core.rb 23560 2009-05-24 20:34:21Z matz $' #:nodoc:
NEEDS_BINMODE = true if /WIN/i.match(RUBY_PLATFORM)
# Path separators in different environments.
PATH_SEPARATOR = {'UNIX'=>'/', 'WINDOWS'=>'\\', 'MACINTOSH'=>':'}
# HTTP status codes.
HTTP_STATUS = {
"OK" => "200 OK",
"PARTIAL_CONTENT" => "206 Partial Content",
"MULTIPLE_CHOICES" => "300 Multiple Choices",
"MOVED" => "301 Moved Permanently",
"REDIRECT" => "302 Found",
"NOT_MODIFIED" => "304 Not Modified",
"BAD_REQUEST" => "400 Bad Request",
"AUTH_REQUIRED" => "401 Authorization Required",
"FORBIDDEN" => "403 Forbidden",
"NOT_FOUND" => "404 Not Found",
"METHOD_NOT_ALLOWED" => "405 Method Not Allowed",
"NOT_ACCEPTABLE" => "406 Not Acceptable",
"LENGTH_REQUIRED" => "411 Length Required",
"PRECONDITION_FAILED" => "412 Precondition Failed",
"SERVER_ERROR" => "500 Internal Server Error",
"NOT_IMPLEMENTED" => "501 Method Not Implemented",
"BAD_GATEWAY" => "502 Bad Gateway",
"VARIANT_ALSO_VARIES" => "506 Variant Also Negotiates"
}
# Abbreviated day-of-week names specified by RFC 822
RFC822_DAYS = %w[ Sun Mon Tue Wed Thu Fri Sat ]
# Abbreviated month names specified by RFC 822
RFC822_MONTHS = %w[ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ]
# :startdoc:
def env_table
ENV
end
def stdinput
$stdin
end
def stdoutput
$stdout
end
private :env_table, :stdinput, :stdoutput
# Create an HTTP header block as a string.
#
# Includes the empty line that ends the header block.
#
# +options+ can be a string specifying the Content-Type (defaults
# to text/html), or a hash of header key/value pairs. The following
# header keys are recognized:
#
# type:: the Content-Type header. Defaults to "text/html"
# charset:: the charset of the body, appended to the Content-Type header.
# nph:: a boolean value. If true, prepend protocol string and status code, and
# date; and sets default values for "server" and "connection" if not
# explicitly set.
# status:: the HTTP status code, returned as the Status header. See the
# list of available status codes below.
# server:: the server software, returned as the Server header.
# connection:: the connection type, returned as the Connection header (for
# instance, "close".
# length:: the length of the content that will be sent, returned as the
# Content-Length header.
# language:: the language of the content, returned as the Content-Language
# header.
# expires:: the time on which the current content expires, as a +Time+
# object, returned as the Expires header.
# cookie:: a cookie or cookies, returned as one or more Set-Cookie headers.
# The value can be the literal string of the cookie; a CGI::Cookie
# object; an Array of literal cookie strings or Cookie objects; or a
# hash all of whose values are literal cookie strings or Cookie objects.
# These cookies are in addition to the cookies held in the
# @output_cookies field.
#
# Other header lines can also be set; they are appended as key: value.
#
# header
# # Content-Type: text/html
#
# header("text/plain")
# # Content-Type: text/plain
#
# header("nph" => true,
# "status" => "OK", # == "200 OK"
# # "status" => "200 GOOD",
# "server" => ENV['SERVER_SOFTWARE'],
# "connection" => "close",
# "type" => "text/html",
# "charset" => "iso-2022-jp",
# # Content-Type: text/html; charset=iso-2022-jp
# "length" => 103,
# "language" => "ja",
# "expires" => Time.now + 30,
# "cookie" => [cookie1, cookie2],
# "my_header1" => "my_value"
# "my_header2" => "my_value")
#
# The status codes are:
#
# "OK" --> "200 OK"
# "PARTIAL_CONTENT" --> "206 Partial Content"
# "MULTIPLE_CHOICES" --> "300 Multiple Choices"
# "MOVED" --> "301 Moved Permanently"
# "REDIRECT" --> "302 Found"
# "NOT_MODIFIED" --> "304 Not Modified"
# "BAD_REQUEST" --> "400 Bad Request"
# "AUTH_REQUIRED" --> "401 Authorization Required"
# "FORBIDDEN" --> "403 Forbidden"
# "NOT_FOUND" --> "404 Not Found"
# "METHOD_NOT_ALLOWED" --> "405 Method Not Allowed"
# "NOT_ACCEPTABLE" --> "406 Not Acceptable"
# "LENGTH_REQUIRED" --> "411 Length Required"
# "PRECONDITION_FAILED" --> "412 Precondition Failed"
# "SERVER_ERROR" --> "500 Internal Server Error"
# "NOT_IMPLEMENTED" --> "501 Method Not Implemented"
# "BAD_GATEWAY" --> "502 Bad Gateway"
# "VARIANT_ALSO_VARIES" --> "506 Variant Also Negotiates"
#
# This method does not perform charset conversion.
def header(options='text/html')
if options.is_a?(String)
content_type = options
buf = _header_for_string(content_type)
elsif options.is_a?(Hash)
if options.size == 1 && options.has_key?('type')
content_type = options['type']
buf = _header_for_string(content_type)
else
buf = _header_for_hash(options.dup)
end
else
raise ArgumentError.new("expected String or Hash but got #{options.class}")
end
if defined?(MOD_RUBY)
_header_for_modruby(buf)
return ''
else
buf << EOL # empty line of separator
return buf
end
end # header()
def _header_for_string(content_type) #:nodoc:
buf = ''
if nph?()
buf << "#{$CGI_ENV['SERVER_PROTOCOL'] || 'HTTP/1.0'} 200 OK#{EOL}"
buf << "Date: #{CGI.rfc1123_date(Time.now)}#{EOL}"
buf << "Server: #{$CGI_ENV['SERVER_SOFTWARE']}#{EOL}"
buf << "Connection: close#{EOL}"
end
buf << "Content-Type: #{content_type}#{EOL}"
if @output_cookies
@output_cookies.each {|cookie| buf << "Set-Cookie: #{cookie}#{EOL}" }
end
return buf
end # _header_for_string
private :_header_for_string
def _header_for_hash(options) #:nodoc:
buf = ''
## add charset to option['type']
options['type'] ||= 'text/html'
charset = options.delete('charset')
options['type'] += "; charset=#{charset}" if charset
## NPH
options.delete('nph') if defined?(MOD_RUBY)
if options.delete('nph') || nph?()
protocol = $CGI_ENV['SERVER_PROTOCOL'] || 'HTTP/1.0'
status = options.delete('status')
status = HTTP_STATUS[status] || status || '200 OK'
buf << "#{protocol} #{status}#{EOL}"
buf << "Date: #{CGI.rfc1123_date(Time.now)}#{EOL}"
options['server'] ||= $CGI_ENV['SERVER_SOFTWARE'] || ''
options['connection'] ||= 'close'
end
## common headers
status = options.delete('status')
buf << "Status: #{HTTP_STATUS[status] || status}#{EOL}" if status
server = options.delete('server')
buf << "Server: #{server}#{EOL}" if server
connection = options.delete('connection')
buf << "Connection: #{connection}#{EOL}" if connection
type = options.delete('type')
buf << "Content-Type: #{type}#{EOL}" #if type
length = options.delete('length')
buf << "Content-Length: #{length}#{EOL}" if length
language = options.delete('language')
buf << "Content-Language: #{language}#{EOL}" if language
expires = options.delete('expires')
buf << "Expires: #{CGI.rfc1123_date(expires)}#{EOL}" if expires
## cookie
if cookie = options.delete('cookie')
case cookie
when String, Cookie
buf << "Set-Cookie: #{cookie}#{EOL}"
when Array
arr = cookie
arr.each {|c| buf << "Set-Cookie: #{c}#{EOL}" }
when Hash
hash = cookie
hash.each {|name, c| buf << "Set-Cookie: #{c}#{EOL}" }
end
end
if @output_cookies
@output_cookies.each {|c| buf << "Set-Cookie: #{c}#{EOL}" }
end
## other headers
options.each do |key, value|
buf << "#{key}: #{value}#{EOL}"
end
return buf
end # _header_for_hash
private :_header_for_hash
def nph? #:nodoc:
return /IIS\/(\d+)/.match($CGI_ENV['SERVER_SOFTWARE']) && $1.to_i < 5
end
def _header_for_modruby(buf) #:nodoc:
request = Apache::request
buf.scan(/([^:]+): (.+)#{EOL}/o) do |name, value|
warn sprintf("name:%s value:%s\n", name, value) if $DEBUG
case name
when 'Set-Cookie'
request.headers_out.add(name, value)
when /^status$/i
request.status_line = value
request.status = value.to_i
when /^content-type$/i
request.content_type = value
when /^content-encoding$/i
request.content_encoding = value
when /^location$/i
request.status = 302 if request.status == 200
request.headers_out[name] = value
else
request.headers_out[name] = value
end
end
request.send_http_header
return ''
end
private :_header_for_modruby
#
# Print an HTTP header and body to $DEFAULT_OUTPUT ($>)
#
# The header is provided by +options+, as for #header().
# The body of the document is that returned by the passed-
# in block. This block takes no arguments. It is required.
#
# cgi = CGI.new
# cgi.out{ "string" }
# # Content-Type: text/html
# # Content-Length: 6
# #
# # string
#
# cgi.out("text/plain") { "string" }
# # Content-Type: text/plain
# # Content-Length: 6
# #
# # string
#
# cgi.out("nph" => true,
# "status" => "OK", # == "200 OK"
# "server" => ENV['SERVER_SOFTWARE'],
# "connection" => "close",
# "type" => "text/html",
# "charset" => "iso-2022-jp",
# # Content-Type: text/html; charset=iso-2022-jp
# "language" => "ja",
# "expires" => Time.now + (3600 * 24 * 30),
# "cookie" => [cookie1, cookie2],
# "my_header1" => "my_value",
# "my_header2" => "my_value") { "string" }
#
# Content-Length is automatically calculated from the size of
# the String returned by the content block.
#
# If ENV['REQUEST_METHOD'] == "HEAD", then only the header
# is outputted (the content block is still required, but it
# is ignored).
#
# If the charset is "iso-2022-jp" or "euc-jp" or "shift_jis" then
# the content is converted to this charset, and the language is set
# to "ja".
def out(options = "text/html") # :yield:
options = { "type" => options } if options.kind_of?(String)
content = yield
options["length"] = content.bytesize.to_s
output = stdoutput
output.binmode if defined? output.binmode
output.print header(options)
output.print content unless "HEAD" == env_table['REQUEST_METHOD']
end
# Print an argument or list of arguments to the default output stream
#
# cgi = CGI.new
# cgi.print # default: cgi.print == $DEFAULT_OUTPUT.print
def print(*options)
stdoutput.print(*options)
end
# Parse an HTTP query string into a hash of key=>value pairs.
#
# params = CGI::parse("query_string")
# # {"name1" => ["value1", "value2", ...],
# # "name2" => ["value1", "value2", ...], ... }
#
def CGI::parse(query)
params = {}
query.split(/[&;]/).each do |pairs|
key, value = pairs.split('=',2).collect{|v| CGI::unescape(v) }
if key && value
params.has_key?(key) ? params[key].push(value) : params[key] = [value]
elsif key
params[key]=[]
end
end
params.default=[].freeze
params
end
# Maximum content length of post data
##MAX_CONTENT_LENGTH = 2 * 1024 * 1024
# Maximum content length of multipart data
MAX_MULTIPART_LENGTH = 128 * 1024 * 1024
# Maximum number of request parameters when multipart
MAX_MULTIPART_COUNT = 128
# Mixin module. It provides the follow functionality groups:
#
# 1. Access to CGI environment variables as methods. See
# documentation to the CGI class for a list of these variables.
#
# 2. Access to cookies, including the cookies attribute.
#
# 3. Access to parameters, including the params attribute, and overloading
# [] to perform parameter value lookup by key.
#
# 4. The initialize_query method, for initialising the above
# mechanisms, handling multipart forms, and allowing the
# class to be used in "offline" mode.
#
module QueryExtension
%w[ CONTENT_LENGTH SERVER_PORT ].each do |env|
define_method(env.sub(/^HTTP_/, '').downcase) do
(val = env_table[env]) && Integer(val)
end
end
%w[ AUTH_TYPE CONTENT_TYPE GATEWAY_INTERFACE PATH_INFO
PATH_TRANSLATED QUERY_STRING REMOTE_ADDR REMOTE_HOST
REMOTE_IDENT REMOTE_USER REQUEST_METHOD SCRIPT_NAME
SERVER_NAME SERVER_PROTOCOL SERVER_SOFTWARE
HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING
HTTP_ACCEPT_LANGUAGE HTTP_CACHE_CONTROL HTTP_FROM HTTP_HOST
HTTP_NEGOTIATE HTTP_PRAGMA HTTP_REFERER HTTP_USER_AGENT ].each do |env|
define_method(env.sub(/^HTTP_/, '').downcase) do
env_table[env]
end
end
# Get the raw cookies as a string.
def raw_cookie
env_table["HTTP_COOKIE"]
end
# Get the raw RFC2965 cookies as a string.
def raw_cookie2
env_table["HTTP_COOKIE2"]
end
# Get the cookies as a hash of cookie-name=>Cookie pairs.
attr_accessor :cookies
# Get the parameters as a hash of name=>values pairs, where
# values is an Array.
attr_reader :params
# Get the uploaed files as a hash of name=>values pairs
attr_reader :files
# Set all the parameters.
def params=(hash)
@params.clear
@params.update(hash)
end
def read_multipart(boundary, content_length)
## read first boundary
stdin = $stdin
first_line = "--#{boundary}#{EOL}"
content_length -= first_line.bytesize
status = stdin.read(first_line.bytesize)
raise EOFError.new("no content body") unless status
raise EOFError.new("bad content body") unless first_line == status
## parse and set params
params = {}
@files = {}
boundary_rexp = /--#{Regexp.quote(boundary)}(#{EOL}|--)/
boundary_size = "#{EOL}--#{boundary}#{EOL}".bytesize
boundary_end = nil
buf = ''
bufsize = 10 * 1024
max_count = MAX_MULTIPART_COUNT
n = 0
while true
(n += 1) < max_count or raise StandardError.new("too many parameters.")
## create body (StringIO or Tempfile)
body = create_body(bufsize < content_length)
class << body
if method_defined?(:path)
alias local_path path
else
def local_path
nil
end
end
attr_reader :original_filename, :content_type
end
## find head and boundary
head = nil
separator = EOL * 2
until head && matched = boundary_rexp.match(buf)
if !head && pos = buf.index(separator)
len = pos + EOL.bytesize
head = buf[0, len]
buf = buf[(pos+separator.bytesize)..-1]
else
if head && buf.size > boundary_size
len = buf.size - boundary_size
body.print(buf[0, len])
buf[0, len] = ''
end
c = stdin.read(bufsize < content_length ? bufsize : content_length)
raise EOFError.new("bad content body") if c.nil? || c.empty?
buf << c
content_length -= c.bytesize
end
end
## read to end of boundary
m = matched
len = m.begin(0)
s = buf[0, len]
if s =~ /(\r?\n)\z/
s = buf[0, len - $1.bytesize]
end
body.print(s)
buf = buf[m.end(0)..-1]
boundary_end = m[1]
content_length = -1 if boundary_end == '--'
## reset file cursor position
body.rewind
## original filename
/Content-Disposition:.* filename=(?:"(.*?)"|([^;\r\n]*))/i.match(head)
filename = $1 || $2 || ''
filename = CGI.unescape(filename) if unescape_filename?()
body.instance_variable_set('@original_filename', filename.taint)
## content type
/Content-Type: (.*)/i.match(head)
(content_type = $1 || '').chomp!
body.instance_variable_set('@content_type', content_type.taint)
## query parameter name
/Content-Disposition:.* name=(?:"(.*?)"|([^;\r\n]*))/i.match(head)
name = $1 || $2 || ''
if body.original_filename.empty?
value=body.read.dup.force_encoding(@accept_charset)
(params[name] ||= []) << value
unless value.valid_encoding?
if @accept_charset_error_block
@accept_charset_error_block.call(name,value)
else
raise InvalidEncoding,"Accept-Charset encoding error"
end
end
class << params[name].last;self;end.class_eval do
define_method(:read){self}
define_method(:original_filename){""}
define_method(:content_type){""}
end
else
(params[name] ||= []) << body
@files[name]=body
end
## break loop
break if buf.size == 0
break if content_length == -1
end
raise EOFError, "bad boundary end of body part" unless boundary_end =~ /--/
params.default = []
params
end # read_multipart
private :read_multipart
def create_body(is_large) #:nodoc:
if is_large
require 'tempfile'
body = Tempfile.new('CGI', encoding: "ascii-8bit")
else
begin
require 'stringio'
body = StringIO.new("".force_encoding("ascii-8bit"))
rescue LoadError
require 'tempfile'
body = Tempfile.new('CGI', encoding: "ascii-8bit")
end
end
body.binmode if defined? body.binmode
return body
end
def unescape_filename? #:nodoc:
user_agent = $CGI_ENV['HTTP_USER_AGENT']
return /Mac/i.match(user_agent) && /Mozilla/i.match(user_agent) && !/MSIE/i.match(user_agent)
end
# offline mode. read name=value pairs on standard input.
def read_from_cmdline
require "shellwords"
string = unless ARGV.empty?
ARGV.join(' ')
else
if STDIN.tty?
STDERR.print(
%|(offline mode: enter name=value pairs on standard input)\n|
)
end
readlines.join(' ').gsub(/\n/, '')
end.gsub(/\\=/, '%3D').gsub(/\\&/, '%26')
words = Shellwords.shellwords(string)
if words.find{|x| /=/.match(x) }
words.join('&')
else
words.join('+')
end
end
private :read_from_cmdline
# A wrapper class to use a StringIO object as the body and switch
# to a TempFile when the passed threshold is passed.
# Initialize the data from the query.
#
# Handles multipart forms (in particular, forms that involve file uploads).
# Reads query parameters in the @params field, and cookies into @cookies.
def initialize_query()
if ("POST" == env_table['REQUEST_METHOD']) and
%r|\Amultipart/form-data.*boundary=\"?([^\";,]+)\"?|.match(env_table['CONTENT_TYPE'])
raise StandardError.new("too large multipart data.") if env_table['CONTENT_LENGTH'].to_i > MAX_MULTIPART_LENGTH
boundary = $1.dup
@multipart = true
@params = read_multipart(boundary, Integer(env_table['CONTENT_LENGTH']))
else
@multipart = false
@params = CGI::parse(
case env_table['REQUEST_METHOD']
when "GET", "HEAD"
if defined?(MOD_RUBY)
Apache::request.args or ""
else
env_table['QUERY_STRING'] or ""
end
when "POST"
stdinput.binmode if defined? stdinput.binmode
stdinput.read(Integer(env_table['CONTENT_LENGTH'])) or ''
else
read_from_cmdline
end.dup.force_encoding(@accept_charset)
)
unless Encoding.find(@accept_charset) == Encoding::ASCII_8BIT
@params.each do |key,values|
values.each do |value|
unless value.valid_encoding?
if @accept_charset_error_block
@accept_charset_error_block.call(key,value)
else
raise InvalidEncoding,"Accept-Charset encoding error"
end
end
end
end
end
end
@cookies = CGI::Cookie::parse((env_table['HTTP_COOKIE'] or env_table['COOKIE']))
end
private :initialize_query
def multipart?
@multipart
end
# Get the value for the parameter with a given key.
#
# If the parameter has multiple values, only the first will be
# retrieved; use #params() to get the array of values.
def [](key)
params = @params[key]
return '' unless params
value = params[0]
if @multipart
if value
return value
elsif defined? StringIO
StringIO.new("".force_encoding("ascii-8bit"))
else
Tempfile.new("CGI",encoding:"ascii-8bit")
end
else
str = if value then value.dup else "" end
str
end
end
# Return all parameter keys as an array.
def keys(*args)
@params.keys(*args)
end
# Returns true if a given parameter key exists in the query.
def has_key?(*args)
@params.has_key?(*args)
end
alias key? has_key?
alias include? has_key?
end # QueryExtension
# InvalidEncoding Exception class
class InvalidEncoding < Exception; end
# @@accept_charset is default accept character set.
# This default value default is "UTF-8"
# If you want to change the default accept character set
# when create a new CGI instance, set this:
#
# CGI.accept_charset = "EUC-JP"
#
@@accept_charset="UTF-8"
def self.accept_charset
@@accept_charset
end
def self.accept_charset=(accept_charset)
@@accept_charset=accept_charset
end
# Create a new CGI instance.
#
# CGI accept constructor parameters either in a hash, string as a block.
# But string is as same as using :tag_maker of hash.
#
# CGI.new("html3") #=> CGI.new(:tag_maker=>"html3")
#
# And, if you specify string, @accept_charset cannot be changed.
# Instead, please use hash parameter.
#
# == accept_charset
#
# :accept_charset specifies encoding of received query string.
# ( Default value is @@accept_charset. )
# If not valid, raise CGI::InvalidEncoding
#
# Example. Suppose @@accept_charset # => "UTF-8"
#
# when not specified:
#
# cgi=CGI.new # @accept_charset # => "UTF-8"
#
# when specified "EUC-JP":
#
# cgi=CGI.new(:accept_charset => "EUC-JP") # => "EUC-JP"
#
# == block
#
# When you use a block, you can write a process
# that query encoding is invalid. Example:
#
# encoding_error={}
# cgi=CGI.new(:accept_charset=>"EUC-JP") do |name,value|
# encoding_error[key] = value
# end
#
# == tag_maker
#
# :tag_maker specifies which version of HTML to load the HTML generation
# methods for. The following versions of HTML are supported:
#
# html3:: HTML 3.x
# html4:: HTML 4.0
# html4Tr:: HTML 4.0 Transitional
# html4Fr:: HTML 4.0 with Framesets
#
# If not specified, no HTML generation methods will be loaded.
#
# If the CGI object is not created in a standard CGI call environment
# (that is, it can't locate REQUEST_METHOD in its environment), then
# it will run in "offline" mode. In this mode, it reads its parameters
# from the command line or (failing that) from standard input. Otherwise,
# cookies and other parameters are parsed automatically from the standard
# CGI locations, which varies according to the REQUEST_METHOD. It works this:
#
# CGI.new(:tag_maker=>"html3")
#
# This will be obsolete:
#
# CGI.new("html3")
#
attr_reader :accept_charset
def initialize(options = {},&block)
@accept_charset_error_block=block if block_given?
@options={:accept_charset=>@@accept_charset}
case options
when Hash
@options.merge!(options)
when String
@options[:tag_maker]=options
end
@accept_charset=@options[:accept_charset]
if defined?(MOD_RUBY) && !ENV.key?("GATEWAY_INTERFACE")
Apache.request.setup_cgi_env
end
extend QueryExtension
@multipart = false
initialize_query() # set @params, @cookies
@output_cookies = nil
@output_hidden = nil
case @options[:tag_maker]
when "html3"
require 'cgi/html'
extend Html3
element_init()
extend HtmlExtension
when "html4"
require 'cgi/html'
extend Html4
element_init()
extend HtmlExtension
when "html4Tr"
require 'cgi/html'
extend Html4Tr
element_init()
extend HtmlExtension
when "html4Fr"
require 'cgi/html'
extend Html4Tr
element_init()
extend Html4Fr
element_init()
extend HtmlExtension
end
end
end # class CGI
| 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/cgi/session.rb | tools/jruby-1.5.1/lib/ruby/1.9/cgi/session.rb | #
# cgi/session.rb - session support for cgi scripts
#
# Copyright (C) 2001 Yukihiro "Matz" Matsumoto
# Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
# Copyright (C) 2000 Information-technology Promotion Agency, Japan
#
# Author: Yukihiro "Matz" Matsumoto
#
# Documentation: William Webber (william@williamwebber.com)
#
# == Overview
#
# This file provides the +CGI::Session+ class, which provides session
# support for CGI scripts. A session is a sequence of HTTP requests
# and responses linked together and associated with a single client.
# Information associated with the session is stored
# on the server between requests. A session id is passed between client
# and server with every request and response, transparently
# to the user. This adds state information to the otherwise stateless
# HTTP request/response protocol.
#
# See the documentation to the +CGI::Session+ class for more details
# and examples of usage. See cgi.rb for the +CGI+ class itself.
require 'cgi'
require 'tmpdir'
class CGI
# Class representing an HTTP session. See documentation for the file
# cgi/session.rb for an introduction to HTTP sessions.
#
# == Lifecycle
#
# A CGI::Session instance is created from a CGI object. By default,
# this CGI::Session instance will start a new session if none currently
# exists, or continue the current session for this client if one does
# exist. The +new_session+ option can be used to either always or
# never create a new session. See #new() for more details.
#
# #delete() deletes a session from session storage. It
# does not however remove the session id from the client. If the client
# makes another request with the same id, the effect will be to start
# a new session with the old session's id.
#
# == Setting and retrieving session data.
#
# The Session class associates data with a session as key-value pairs.
# This data can be set and retrieved by indexing the Session instance
# using '[]', much the same as hashes (although other hash methods
# are not supported).
#
# When session processing has been completed for a request, the
# session should be closed using the close() method. This will
# store the session's state to persistent storage. If you want
# to store the session's state to persistent storage without
# finishing session processing for this request, call the update()
# method.
#
# == Storing session state
#
# The caller can specify what form of storage to use for the session's
# data with the +database_manager+ option to CGI::Session::new. The
# following storage classes are provided as part of the standard library:
#
# CGI::Session::FileStore:: stores data as plain text in a flat file. Only
# works with String data. This is the default
# storage type.
# CGI::Session::MemoryStore:: stores data in an in-memory hash. The data
# only persists for as long as the current ruby
# interpreter instance does.
# CGI::Session::PStore:: stores data in Marshalled format. Provided by
# cgi/session/pstore.rb. Supports data of any type,
# and provides file-locking and transaction support.
#
# Custom storage types can also be created by defining a class with
# the following methods:
#
# new(session, options)
# restore # returns hash of session data.
# update
# close
# delete
#
# Changing storage type mid-session does not work. Note in particular
# that by default the FileStore and PStore session data files have the
# same name. If your application switches from one to the other without
# making sure that filenames will be different
# and clients still have old sessions lying around in cookies, then
# things will break nastily!
#
# == Maintaining the session id.
#
# Most session state is maintained on the server. However, a session
# id must be passed backwards and forwards between client and server
# to maintain a reference to this session state.
#
# The simplest way to do this is via cookies. The CGI::Session class
# provides transparent support for session id communication via cookies
# if the client has cookies enabled.
#
# If the client has cookies disabled, the session id must be included
# as a parameter of all requests sent by the client to the server. The
# CGI::Session class in conjunction with the CGI class will transparently
# add the session id as a hidden input field to all forms generated
# using the CGI#form() HTML generation method. No built-in support is
# provided for other mechanisms, such as URL re-writing. The caller is
# responsible for extracting the session id from the session_id
# attribute and manually encoding it in URLs and adding it as a hidden
# input to HTML forms created by other mechanisms. Also, session expiry
# is not automatically handled.
#
# == Examples of use
#
# === Setting the user's name
#
# require 'cgi'
# require 'cgi/session'
# require 'cgi/session/pstore' # provides CGI::Session::PStore
#
# cgi = CGI.new("html4")
#
# session = CGI::Session.new(cgi,
# 'database_manager' => CGI::Session::PStore, # use PStore
# 'session_key' => '_rb_sess_id', # custom session key
# 'session_expires' => Time.now + 30 * 60, # 30 minute timeout
# 'prefix' => 'pstore_sid_') # PStore option
# if cgi.has_key?('user_name') and cgi['user_name'] != ''
# # coerce to String: cgi[] returns the
# # string-like CGI::QueryExtension::Value
# session['user_name'] = cgi['user_name'].to_s
# elsif !session['user_name']
# session['user_name'] = "guest"
# end
# session.close
#
# === Creating a new session safely
#
# require 'cgi'
# require 'cgi/session'
#
# cgi = CGI.new("html4")
#
# # We make sure to delete an old session if one exists,
# # not just to free resources, but to prevent the session
# # from being maliciously hijacked later on.
# begin
# session = CGI::Session.new(cgi, 'new_session' => false)
# session.delete
# rescue ArgumentError # if no old session
# end
# session = CGI::Session.new(cgi, 'new_session' => true)
# session.close
#
class Session
class NoSession < RuntimeError #:nodoc:
end
# The id of this session.
attr_reader :session_id, :new_session
def Session::callback(dbman) #:nodoc:
Proc.new{
dbman[0].close unless dbman.empty?
}
end
# Create a new session id.
#
# The session id is an MD5 hash based upon the time,
# a random number, and a constant string. This routine
# is used internally for automatically generated
# session ids.
def create_new_id
require 'securerandom'
begin
session_id = SecureRandom.hex(16)
rescue NotImplementedError
require 'digest/md5'
md5 = Digest::MD5::new
now = Time::now
md5.update(now.to_s)
md5.update(String(now.usec))
md5.update(String(rand(0)))
md5.update(String($$))
md5.update('foobar')
session_id = md5.hexdigest
end
session_id
end
private :create_new_id
# Create a new CGI::Session object for +request+.
#
# +request+ is an instance of the +CGI+ class (see cgi.rb).
# +option+ is a hash of options for initialising this
# CGI::Session instance. The following options are
# recognised:
#
# session_key:: the parameter name used for the session id.
# Defaults to '_session_id'.
# session_id:: the session id to use. If not provided, then
# it is retrieved from the +session_key+ parameter
# of the request, or automatically generated for
# a new session.
# new_session:: if true, force creation of a new session. If not set,
# a new session is only created if none currently
# exists. If false, a new session is never created,
# and if none currently exists and the +session_id+
# option is not set, an ArgumentError is raised.
# database_manager:: the name of the class providing storage facilities
# for session state persistence. Built-in support
# is provided for +FileStore+ (the default),
# +MemoryStore+, and +PStore+ (from
# cgi/session/pstore.rb). See the documentation for
# these classes for more details.
#
# The following options are also recognised, but only apply if the
# session id is stored in a cookie.
#
# session_expires:: the time the current session expires, as a
# +Time+ object. If not set, the session will terminate
# when the user's browser is closed.
# session_domain:: the hostname domain for which this session is valid.
# If not set, defaults to the hostname of the server.
# session_secure:: if +true+, this session will only work over HTTPS.
# session_path:: the path for which this session applies. Defaults
# to the directory of the CGI script.
#
# +option+ is also passed on to the session storage class initializer; see
# the documentation for each session storage class for the options
# they support.
#
# The retrieved or created session is automatically added to +request+
# as a cookie, and also to its +output_hidden+ table, which is used
# to add hidden input elements to forms.
#
# *WARNING* the +output_hidden+
# fields are surrounded by a <fieldset> tag in HTML 4 generation, which
# is _not_ invisible on many browsers; you may wish to disable the
# use of fieldsets with code similar to the following
# (see http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-list/37805)
#
# cgi = CGI.new("html4")
# class << cgi
# undef_method :fieldset
# end
#
def initialize(request, option={})
@new_session = false
session_key = option['session_key'] || '_session_id'
session_id = option['session_id']
unless session_id
if option['new_session']
session_id = create_new_id
@new_session = true
end
end
unless session_id
if request.key?(session_key)
session_id = request[session_key]
session_id = session_id.read if session_id.respond_to?(:read)
end
unless session_id
session_id, = request.cookies[session_key]
end
unless session_id
unless option.fetch('new_session', true)
raise ArgumentError, "session_key `%s' should be supplied"%session_key
end
session_id = create_new_id
@new_session = true
end
end
@session_id = session_id
dbman = option['database_manager'] || FileStore
begin
@dbman = dbman::new(self, option)
rescue NoSession
unless option.fetch('new_session', true)
raise ArgumentError, "invalid session_id `%s'"%session_id
end
session_id = @session_id = create_new_id unless session_id
@new_session=true
retry
end
request.instance_eval do
@output_hidden = {session_key => session_id} unless option['no_hidden']
@output_cookies = [
Cookie::new("name" => session_key,
"value" => session_id,
"expires" => option['session_expires'],
"domain" => option['session_domain'],
"secure" => option['session_secure'],
"path" =>
if option['session_path']
option['session_path']
elsif ENV["SCRIPT_NAME"]
File::dirname(ENV["SCRIPT_NAME"])
else
""
end)
] unless option['no_cookies']
end
@dbprot = [@dbman]
ObjectSpace::define_finalizer(self, Session::callback(@dbprot))
end
# Retrieve the session data for key +key+.
def [](key)
@data ||= @dbman.restore
@data[key]
end
# Set the session date for key +key+.
def []=(key, val)
@write_lock ||= true
@data ||= @dbman.restore
@data[key] = val
end
# Store session data on the server. For some session storage types,
# this is a no-op.
def update
@dbman.update
end
# Store session data on the server and close the session storage.
# For some session storage types, this is a no-op.
def close
@dbman.close
@dbprot.clear
end
# Delete the session from storage. Also closes the storage.
#
# Note that the session's data is _not_ automatically deleted
# upon the session expiring.
def delete
@dbman.delete
@dbprot.clear
end
# File-based session storage class.
#
# Implements session storage as a flat file of 'key=value' values.
# This storage type only works directly with String values; the
# user is responsible for converting other types to Strings when
# storing and from Strings when retrieving.
class FileStore
# Create a new FileStore instance.
#
# This constructor is used internally by CGI::Session. The
# user does not generally need to call it directly.
#
# +session+ is the session for which this instance is being
# created. The session id must only contain alphanumeric
# characters; automatically generated session ids observe
# this requirement.
#
# +option+ is a hash of options for the initializer. The
# following options are recognised:
#
# tmpdir:: the directory to use for storing the FileStore
# file. Defaults to Dir::tmpdir (generally "/tmp"
# on Unix systems).
# prefix:: the prefix to add to the session id when generating
# the filename for this session's FileStore file.
# Defaults to "cgi_sid_".
# suffix:: the prefix to add to the session id when generating
# the filename for this session's FileStore file.
# Defaults to the empty string.
#
# This session's FileStore file will be created if it does
# not exist, or opened if it does.
def initialize(session, option={})
dir = option['tmpdir'] || Dir::tmpdir
prefix = option['prefix'] || 'cgi_sid_'
suffix = option['suffix'] || ''
id = session.session_id
require 'digest/md5'
md5 = Digest::MD5.hexdigest(id)[0,16]
@path = dir+"/"+prefix+md5+suffix
if File::exist? @path
@hash = nil
else
unless session.new_session
raise CGI::Session::NoSession, "uninitialized session"
end
@hash = {}
end
end
# Restore session state from the session's FileStore file.
#
# Returns the session state as a hash.
def restore
unless @hash
@hash = {}
begin
lockf = File.open(@path+".lock", "r")
lockf.flock File::LOCK_SH
f = File.open(@path, 'r')
for line in f
line.chomp!
k, v = line.split('=',2)
@hash[CGI::unescape(k)] = Marshal.restore(CGI::unescape(v))
end
ensure
f.close unless f.nil?
lockf.close if lockf
end
end
@hash
end
# Save session state to the session's FileStore file.
def update
return unless @hash
begin
lockf = File.open(@path+".lock", File::CREAT|File::RDWR, 0600)
lockf.flock File::LOCK_EX
f = File.open(@path+".new", File::CREAT|File::TRUNC|File::WRONLY, 0600)
for k,v in @hash
f.printf "%s=%s\n", CGI::escape(k), CGI::escape(String(Marshal.dump(v)))
end
f.close
File.rename @path+".new", @path
ensure
f.close if f and !f.closed?
lockf.close if lockf
end
end
# Update and close the session's FileStore file.
def close
update
end
# Close and delete the session's FileStore file.
def delete
File::unlink @path+".lock" rescue nil
File::unlink @path+".new" rescue nil
File::unlink @path rescue Errno::ENOENT
end
end
# In-memory session storage class.
#
# Implements session storage as a global in-memory hash. Session
# data will only persist for as long as the ruby interpreter
# instance does.
class MemoryStore
GLOBAL_HASH_TABLE = {} #:nodoc:
# Create a new MemoryStore instance.
#
# +session+ is the session this instance is associated with.
# +option+ is a list of initialisation options. None are
# currently recognised.
def initialize(session, option=nil)
@session_id = session.session_id
unless GLOBAL_HASH_TABLE.key?(@session_id)
unless session.new_session
raise CGI::Session::NoSession, "uninitialized session"
end
GLOBAL_HASH_TABLE[@session_id] = {}
end
end
# Restore session state.
#
# Returns session data as a hash.
def restore
GLOBAL_HASH_TABLE[@session_id]
end
# Update session state.
#
# A no-op.
def update
# don't need to update; hash is shared
end
# Close session storage.
#
# A no-op.
def close
# don't need to close
end
# Delete the session state.
def delete
GLOBAL_HASH_TABLE.delete(@session_id)
end
end
# Dummy session storage class.
#
# Implements session storage place holder. No actual storage
# will be done.
class NullStore
# Create a new NullStore instance.
#
# +session+ is the session this instance is associated with.
# +option+ is a list of initialisation options. None are
# currently recognised.
def initialize(session, option=nil)
end
# Restore (empty) session state.
def restore
{}
end
# Update session state.
#
# A no-op.
def update
end
# Close session storage.
#
# A no-op.
def close
end
# Delete the session state.
#
# A no-op.
def delete
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/cgi/cookie.rb | tools/jruby-1.5.1/lib/ruby/1.9/cgi/cookie.rb | # Class representing an HTTP cookie.
#
# In addition to its specific fields and methods, a Cookie instance
# is a delegator to the array of its values.
#
# See RFC 2965.
#
# == Examples of use
# cookie1 = CGI::Cookie::new("name", "value1", "value2", ...)
# cookie1 = CGI::Cookie::new("name" => "name", "value" => "value")
# cookie1 = CGI::Cookie::new('name' => 'name',
# 'value' => ['value1', 'value2', ...],
# 'path' => 'path', # optional
# 'domain' => 'domain', # optional
# 'expires' => Time.now, # optional
# 'secure' => true # optional
# )
#
# cgi.out("cookie" => [cookie1, cookie2]) { "string" }
#
# name = cookie1.name
# values = cookie1.value
# path = cookie1.path
# domain = cookie1.domain
# expires = cookie1.expires
# secure = cookie1.secure
#
# cookie1.name = 'name'
# cookie1.value = ['value1', 'value2', ...]
# cookie1.path = 'path'
# cookie1.domain = 'domain'
# cookie1.expires = Time.now + 30
# cookie1.secure = true
class CGI
class Cookie < Array
# Create a new CGI::Cookie object.
#
# The contents of the cookie can be specified as a +name+ and one
# or more +value+ arguments. Alternatively, the contents can
# be specified as a single hash argument. The possible keywords of
# this hash are as follows:
#
# name:: the name of the cookie. Required.
# value:: the cookie's value or list of values.
# path:: the path for which this cookie applies. Defaults to the
# base directory of the CGI script.
# domain:: the domain for which this cookie applies.
# expires:: the time at which this cookie expires, as a +Time+ object.
# secure:: whether this cookie is a secure cookie or not (default to
# false). Secure cookies are only transmitted to HTTPS
# servers.
#
# These keywords correspond to attributes of the cookie object.
def initialize(name = "", *value)
if name.kind_of?(String)
@name = name
@value = value
%r|^(.*/)|.match(ENV["SCRIPT_NAME"])
@path = ($1 or "")
@secure = false
return super(@value)
end
options = name
unless options.has_key?("name")
raise ArgumentError, "`name' required"
end
@name = options["name"]
@value = Array(options["value"])
# simple support for IE
if options["path"]
@path = options["path"]
else
%r|^(.*/)|.match(ENV["SCRIPT_NAME"])
@path = ($1 or "")
end
@domain = options["domain"]
@expires = options["expires"]
@secure = options["secure"] == true ? true : false
super(@value)
end
attr_accessor("name", "value", "path", "domain", "expires")
attr_reader("secure")
# Set whether the Cookie is a secure cookie or not.
#
# +val+ must be a boolean.
def secure=(val)
@secure = val if val == true or val == false
@secure
end
# Convert the Cookie to its string representation.
def to_s
val = @value.kind_of?(String) ? CGI::escape(@value) : @value.collect{|v| CGI::escape(v) }.join("&")
buf = "#{@name}=#{val}"
buf << "; domain=#{@domain}" if @domain
buf << "; path=#{@path}" if @path
buf << "; expires=#{CGI::rfc1123_date(@expires)}" if @expires
buf << "; secure" if @secure == true
buf
end
end # class Cookie
# Parse a raw cookie string into a hash of cookie-name=>Cookie
# pairs.
#
# cookies = CGI::Cookie::parse("raw_cookie_string")
# # { "name1" => cookie1, "name2" => cookie2, ... }
#
def Cookie::parse(raw_cookie)
cookies = Hash.new([])
return cookies unless raw_cookie
raw_cookie.split(/[;,]\s?/).each do |pairs|
name, values = pairs.split('=',2)
next unless name and values
name = CGI::unescape(name)
values ||= ""
values = values.split('&').collect{|v| CGI::unescape(v,@@accept_charset) }
if cookies.has_key?(name)
values = cookies[name].value + values
end
cookies[name] = Cookie::new(name, *values)
end
cookies
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/cgi/util.rb | tools/jruby-1.5.1/lib/ruby/1.9/cgi/util.rb | class CGI
# URL-encode a string.
# url_encoded_string = CGI::escape("'Stop!' said Fred")
# # => "%27Stop%21%27+said+Fred"
def CGI::escape(string)
string.gsub(/([^ a-zA-Z0-9_.-]+)/) do
'%' + $1.unpack('H2' * $1.bytesize).join('%').upcase
end.tr(' ', '+')
end
# URL-decode a string with encoding(optional).
# string = CGI::unescape("%27Stop%21%27+said+Fred")
# # => "'Stop!' said Fred"
def CGI::unescape(string,encoding=@@accept_charset)
str=string.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/) do
[$1.delete('%')].pack('H*')
end.force_encoding(encoding)
str.valid_encoding? ? str : str.force_encoding(string.encoding)
end
TABLE_FOR_ESCAPE_HTML__ = {
'&' => '&',
'"' => '"',
'<' => '<',
'>' => '>',
}
# Escape special characters in HTML, namely &\"<>
# CGI::escapeHTML('Usage: foo "bar" <baz>')
# # => "Usage: foo "bar" <baz>"
def CGI::escapeHTML(string)
string.gsub(/[&\"<>]/, TABLE_FOR_ESCAPE_HTML__)
end
# Unescape a string that has been HTML-escaped
# CGI::unescapeHTML("Usage: foo "bar" <baz>")
# # => "Usage: foo \"bar\" <baz>"
def CGI::unescapeHTML(string)
enc = string.encoding
if [Encoding::UTF_16BE, Encoding::UTF_16LE, Encoding::UTF_32BE, Encoding::UTF_32LE].include?(enc)
return string.gsub(Regexp.new('&(amp|quot|gt|lt|#[0-9]+|#x[0-9A-Fa-f]+);'.encode(enc))) do
case $1.encode("US-ASCII")
when 'amp' then '&'.encode(enc)
when 'quot' then '"'.encode(enc)
when 'gt' then '>'.encode(enc)
when 'lt' then '<'.encode(enc)
when /\A#0*(\d+)\z/ then $1.to_i.chr(enc)
when /\A#x([0-9a-f]+)\z/i then $1.hex.chr(enc)
end
end
end
asciicompat = Encoding.compatible?(string, "a")
string.gsub(/&(amp|quot|gt|lt|\#[0-9]+|\#x[0-9A-Fa-f]+);/) do
match = $1.dup
case match
when 'amp' then '&'
when 'quot' then '"'
when 'gt' then '>'
when 'lt' then '<'
when /\A#0*(\d+)\z/
n = $1.to_i
if enc == Encoding::UTF_8 or
enc == Encoding::ISO_8859_1 && n < 256 or
asciicompat && n < 128
n.chr(enc)
else
"&##{$1};"
end
when /\A#x([0-9a-f]+)\z/i
n = $1.hex
if enc == Encoding::UTF_8 or
enc == Encoding::ISO_8859_1 && n < 256 or
asciicompat && n < 128
n.chr(enc)
else
"&#x#{$1};"
end
else
"&#{match};"
end
end
end
def CGI::escape_html(str)
escapeHTML(str)
end
def CGI::unescape_html(str)
unescapeHTML(str)
end
# Escape only the tags of certain HTML elements in +string+.
#
# Takes an element or elements or array of elements. Each element
# is specified by the name of the element, without angle brackets.
# This matches both the start and the end tag of that element.
# The attribute list of the open tag will also be escaped (for
# instance, the double-quotes surrounding attribute values).
#
# print CGI::escapeElement('<BR><A HREF="url"></A>', "A", "IMG")
# # "<BR><A HREF="url"></A>"
#
# print CGI::escapeElement('<BR><A HREF="url"></A>', ["A", "IMG"])
# # "<BR><A HREF="url"></A>"
def CGI::escapeElement(string, *elements)
elements = elements[0] if elements[0].kind_of?(Array)
unless elements.empty?
string.gsub(/<\/?(?:#{elements.join("|")})(?!\w)(?:.|\n)*?>/i) do
CGI::escapeHTML($&)
end
else
string
end
end
# Undo escaping such as that done by CGI::escapeElement()
#
# print CGI::unescapeElement(
# CGI::escapeHTML('<BR><A HREF="url"></A>'), "A", "IMG")
# # "<BR><A HREF="url"></A>"
#
# print CGI::unescapeElement(
# CGI::escapeHTML('<BR><A HREF="url"></A>'), ["A", "IMG"])
# # "<BR><A HREF="url"></A>"
def CGI::unescapeElement(string, *elements)
elements = elements[0] if elements[0].kind_of?(Array)
unless elements.empty?
string.gsub(/<\/?(?:#{elements.join("|")})(?!\w)(?:.|\n)*?>/i) do
CGI::unescapeHTML($&)
end
else
string
end
end
def CGI::escape_element(str)
escapeElement(str)
end
def CGI::unescape_element(str)
unescapeElement(str)
end
# Format a +Time+ object as a String using the format specified by RFC 1123.
#
# CGI::rfc1123_date(Time.now)
# # Sat, 01 Jan 2000 00:00:00 GMT
def CGI::rfc1123_date(time)
t = time.clone.gmtime
return format("%s, %.2d %s %.4d %.2d:%.2d:%.2d GMT",
RFC822_DAYS[t.wday], t.day, RFC822_MONTHS[t.month-1], t.year,
t.hour, t.min, t.sec)
end
# Prettify (indent) an HTML string.
#
# +string+ is the HTML string to indent. +shift+ is the indentation
# unit to use; it defaults to two spaces.
#
# print CGI::pretty("<HTML><BODY></BODY></HTML>")
# # <HTML>
# # <BODY>
# # </BODY>
# # </HTML>
#
# print CGI::pretty("<HTML><BODY></BODY></HTML>", "\t")
# # <HTML>
# # <BODY>
# # </BODY>
# # </HTML>
#
def CGI::pretty(string, shift = " ")
lines = string.gsub(/(?!\A)<(?:.|\n)*?>/, "\n\\0").gsub(/<(?:.|\n)*?>(?!\n)/, "\\0\n")
end_pos = 0
while end_pos = lines.index(/^<\/(\w+)/, end_pos)
element = $1.dup
start_pos = lines.rindex(/^\s*<#{element}/i, end_pos)
lines[start_pos ... end_pos] = "__" + lines[start_pos ... end_pos].gsub(/\n(?!\z)/, "\n" + shift) + "__"
end
lines.gsub(/^((?:#{Regexp::quote(shift)})*)__(?=<\/?\w)/, '\1')
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/cgi/html.rb | tools/jruby-1.5.1/lib/ruby/1.9/cgi/html.rb | # Base module for HTML-generation mixins.
#
# Provides methods for code generation for tags following
# the various DTD element types.
class CGI
module TagMaker # :nodoc:
# Generate code for an element with required start and end tags.
#
# - -
def nn_element_def(element)
nOE_element_def(element, <<-END)
if block_given?
yield.to_s
else
""
end +
"</#{element.upcase}>"
END
end
# Generate code for an empty element.
#
# - O EMPTY
def nOE_element_def(element, append = nil)
s = <<-END
attributes={attributes=>nil} if attributes.kind_of?(String)
"<#{element.upcase}" + attributes.collect{|name, value|
next unless value
" " + CGI::escapeHTML(name.to_s) +
if true == value
""
else
'="' + CGI::escapeHTML(value.to_s) + '"'
end
}.join + ">"
END
s.sub!(/\Z/, " +") << append if append
s
end
# Generate code for an element for which the end (and possibly the
# start) tag is optional.
#
# O O or - O
def nO_element_def(element)
nOE_element_def(element, <<-END)
if block_given?
yield.to_s + "</#{element.upcase}>"
else
""
end
END
end
end # TagMaker
#
# Mixin module providing HTML generation methods.
#
# For example,
# cgi.a("http://www.example.com") { "Example" }
# # => "<A HREF=\"http://www.example.com\">Example</A>"
#
# Modules Http3, Http4, etc., contain more basic HTML-generation methods
# (:title, :center, etc.).
#
# See class CGI for a detailed example.
#
module HtmlExtension
# Generate an Anchor element as a string.
#
# +href+ can either be a string, giving the URL
# for the HREF attribute, or it can be a hash of
# the element's attributes.
#
# The body of the element is the string returned by the no-argument
# block passed in.
#
# a("http://www.example.com") { "Example" }
# # => "<A HREF=\"http://www.example.com\">Example</A>"
#
# a("HREF" => "http://www.example.com", "TARGET" => "_top") { "Example" }
# # => "<A HREF=\"http://www.example.com\" TARGET=\"_top\">Example</A>"
#
def a(href = "") # :yield:
attributes = if href.kind_of?(String)
{ "HREF" => href }
else
href
end
if block_given?
super(attributes){ yield }
else
super(attributes)
end
end
# Generate a Document Base URI element as a String.
#
# +href+ can either by a string, giving the base URL for the HREF
# attribute, or it can be a has of the element's attributes.
#
# The passed-in no-argument block is ignored.
#
# base("http://www.example.com/cgi")
# # => "<BASE HREF=\"http://www.example.com/cgi\">"
def base(href = "") # :yield:
attributes = if href.kind_of?(String)
{ "HREF" => href }
else
href
end
if block_given?
super(attributes){ yield }
else
super(attributes)
end
end
# Generate a BlockQuote element as a string.
#
# +cite+ can either be a string, give the URI for the source of
# the quoted text, or a hash, giving all attributes of the element,
# or it can be omitted, in which case the element has no attributes.
#
# The body is provided by the passed-in no-argument block
#
# blockquote("http://www.example.com/quotes/foo.html") { "Foo!" }
# #=> "<BLOCKQUOTE CITE=\"http://www.example.com/quotes/foo.html\">Foo!</BLOCKQUOTE>
def blockquote(cite = {}) # :yield:
attributes = if cite.kind_of?(String)
{ "CITE" => cite }
else
cite
end
if block_given?
super(attributes){ yield }
else
super(attributes)
end
end
# Generate a Table Caption element as a string.
#
# +align+ can be a string, giving the alignment of the caption
# (one of top, bottom, left, or right). It can be a hash of
# all the attributes of the element. Or it can be omitted.
#
# The body of the element is provided by the passed-in no-argument block.
#
# caption("left") { "Capital Cities" }
# # => <CAPTION ALIGN=\"left\">Capital Cities</CAPTION>
def caption(align = {}) # :yield:
attributes = if align.kind_of?(String)
{ "ALIGN" => align }
else
align
end
if block_given?
super(attributes){ yield }
else
super(attributes)
end
end
# Generate a Checkbox Input element as a string.
#
# The attributes of the element can be specified as three arguments,
# +name+, +value+, and +checked+. +checked+ is a boolean value;
# if true, the CHECKED attribute will be included in the element.
#
# Alternatively, the attributes can be specified as a hash.
#
# checkbox("name")
# # = checkbox("NAME" => "name")
#
# checkbox("name", "value")
# # = checkbox("NAME" => "name", "VALUE" => "value")
#
# checkbox("name", "value", true)
# # = checkbox("NAME" => "name", "VALUE" => "value", "CHECKED" => true)
def checkbox(name = "", value = nil, checked = nil)
attributes = if name.kind_of?(String)
{ "TYPE" => "checkbox", "NAME" => name,
"VALUE" => value, "CHECKED" => checked }
else
name["TYPE"] = "checkbox"
name
end
input(attributes)
end
# Generate a sequence of checkbox elements, as a String.
#
# The checkboxes will all have the same +name+ attribute.
# Each checkbox is followed by a label.
# There will be one checkbox for each value. Each value
# can be specified as a String, which will be used both
# as the value of the VALUE attribute and as the label
# for that checkbox. A single-element array has the
# same effect.
#
# Each value can also be specified as a three-element array.
# The first element is the VALUE attribute; the second is the
# label; and the third is a boolean specifying whether this
# checkbox is CHECKED.
#
# Each value can also be specified as a two-element
# array, by omitting either the value element (defaults
# to the same as the label), or the boolean checked element
# (defaults to false).
#
# checkbox_group("name", "foo", "bar", "baz")
# # <INPUT TYPE="checkbox" NAME="name" VALUE="foo">foo
# # <INPUT TYPE="checkbox" NAME="name" VALUE="bar">bar
# # <INPUT TYPE="checkbox" NAME="name" VALUE="baz">baz
#
# checkbox_group("name", ["foo"], ["bar", true], "baz")
# # <INPUT TYPE="checkbox" NAME="name" VALUE="foo">foo
# # <INPUT TYPE="checkbox" CHECKED NAME="name" VALUE="bar">bar
# # <INPUT TYPE="checkbox" NAME="name" VALUE="baz">baz
#
# checkbox_group("name", ["1", "Foo"], ["2", "Bar", true], "Baz")
# # <INPUT TYPE="checkbox" NAME="name" VALUE="1">Foo
# # <INPUT TYPE="checkbox" CHECKED NAME="name" VALUE="2">Bar
# # <INPUT TYPE="checkbox" NAME="name" VALUE="Baz">Baz
#
# checkbox_group("NAME" => "name",
# "VALUES" => ["foo", "bar", "baz"])
#
# checkbox_group("NAME" => "name",
# "VALUES" => [["foo"], ["bar", true], "baz"])
#
# checkbox_group("NAME" => "name",
# "VALUES" => [["1", "Foo"], ["2", "Bar", true], "Baz"])
def checkbox_group(name = "", *values)
if name.kind_of?(Hash)
values = name["VALUES"]
name = name["NAME"]
end
values.collect{|value|
if value.kind_of?(String)
checkbox(name, value) + value
else
if value[-1] == true || value[-1] == false
checkbox(name, value[0], value[-1]) +
value[-2]
else
checkbox(name, value[0]) +
value[-1]
end
end
}.join
end
# Generate an File Upload Input element as a string.
#
# The attributes of the element can be specified as three arguments,
# +name+, +size+, and +maxlength+. +maxlength+ is the maximum length
# of the file's _name_, not of the file's _contents_.
#
# Alternatively, the attributes can be specified as a hash.
#
# See #multipart_form() for forms that include file uploads.
#
# file_field("name")
# # <INPUT TYPE="file" NAME="name" SIZE="20">
#
# file_field("name", 40)
# # <INPUT TYPE="file" NAME="name" SIZE="40">
#
# file_field("name", 40, 100)
# # <INPUT TYPE="file" NAME="name" SIZE="40" MAXLENGTH="100">
#
# file_field("NAME" => "name", "SIZE" => 40)
# # <INPUT TYPE="file" NAME="name" SIZE="40">
def file_field(name = "", size = 20, maxlength = nil)
attributes = if name.kind_of?(String)
{ "TYPE" => "file", "NAME" => name,
"SIZE" => size.to_s }
else
name["TYPE"] = "file"
name
end
attributes["MAXLENGTH"] = maxlength.to_s if maxlength
input(attributes)
end
# Generate a Form element as a string.
#
# +method+ should be either "get" or "post", and defaults to the latter.
# +action+ defaults to the current CGI script name. +enctype+
# defaults to "application/x-www-form-urlencoded".
#
# Alternatively, the attributes can be specified as a hash.
#
# See also #multipart_form() for forms that include file uploads.
#
# form{ "string" }
# # <FORM METHOD="post" ENCTYPE="application/x-www-form-urlencoded">string</FORM>
#
# form("get") { "string" }
# # <FORM METHOD="get" ENCTYPE="application/x-www-form-urlencoded">string</FORM>
#
# form("get", "url") { "string" }
# # <FORM METHOD="get" ACTION="url" ENCTYPE="application/x-www-form-urlencoded">string</FORM>
#
# form("METHOD" => "post", "ENCTYPE" => "enctype") { "string" }
# # <FORM METHOD="post" ENCTYPE="enctype">string</FORM>
def form(method = "post", action = script_name, enctype = "application/x-www-form-urlencoded")
attributes = if method.kind_of?(String)
{ "METHOD" => method, "ACTION" => action,
"ENCTYPE" => enctype }
else
unless method.has_key?("METHOD")
method["METHOD"] = "post"
end
unless method.has_key?("ENCTYPE")
method["ENCTYPE"] = enctype
end
method
end
if block_given?
body = yield
else
body = ""
end
if @output_hidden
body += @output_hidden.collect{|k,v|
"<INPUT TYPE=\"HIDDEN\" NAME=\"#{k}\" VALUE=\"#{v}\">"
}.join
end
super(attributes){body}
end
# Generate a Hidden Input element as a string.
#
# The attributes of the element can be specified as two arguments,
# +name+ and +value+.
#
# Alternatively, the attributes can be specified as a hash.
#
# hidden("name")
# # <INPUT TYPE="hidden" NAME="name">
#
# hidden("name", "value")
# # <INPUT TYPE="hidden" NAME="name" VALUE="value">
#
# hidden("NAME" => "name", "VALUE" => "reset", "ID" => "foo")
# # <INPUT TYPE="hidden" NAME="name" VALUE="value" ID="foo">
def hidden(name = "", value = nil)
attributes = if name.kind_of?(String)
{ "TYPE" => "hidden", "NAME" => name, "VALUE" => value }
else
name["TYPE"] = "hidden"
name
end
input(attributes)
end
# Generate a top-level HTML element as a string.
#
# The attributes of the element are specified as a hash. The
# pseudo-attribute "PRETTY" can be used to specify that the generated
# HTML string should be indented. "PRETTY" can also be specified as
# a string as the sole argument to this method. The pseudo-attribute
# "DOCTYPE", if given, is used as the leading DOCTYPE SGML tag; it
# should include the entire text of this tag, including angle brackets.
#
# The body of the html element is supplied as a block.
#
# html{ "string" }
# # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><HTML>string</HTML>
#
# html("LANG" => "ja") { "string" }
# # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><HTML LANG="ja">string</HTML>
#
# html("DOCTYPE" => false) { "string" }
# # <HTML>string</HTML>
#
# html("DOCTYPE" => '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">') { "string" }
# # <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"><HTML>string</HTML>
#
# html("PRETTY" => " ") { "<BODY></BODY>" }
# # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
# # <HTML>
# # <BODY>
# # </BODY>
# # </HTML>
#
# html("PRETTY" => "\t") { "<BODY></BODY>" }
# # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
# # <HTML>
# # <BODY>
# # </BODY>
# # </HTML>
#
# html("PRETTY") { "<BODY></BODY>" }
# # = html("PRETTY" => " ") { "<BODY></BODY>" }
#
# html(if $VERBOSE then "PRETTY" end) { "HTML string" }
#
def html(attributes = {}) # :yield:
if nil == attributes
attributes = {}
elsif "PRETTY" == attributes
attributes = { "PRETTY" => true }
end
pretty = attributes.delete("PRETTY")
pretty = " " if true == pretty
buf = ""
if attributes.has_key?("DOCTYPE")
if attributes["DOCTYPE"]
buf += attributes.delete("DOCTYPE")
else
attributes.delete("DOCTYPE")
end
else
buf += doctype
end
if block_given?
buf += super(attributes){ yield }
else
buf += super(attributes)
end
if pretty
CGI::pretty(buf, pretty)
else
buf
end
end
# Generate an Image Button Input element as a string.
#
# +src+ is the URL of the image to use for the button. +name+
# is the input name. +alt+ is the alternative text for the image.
#
# Alternatively, the attributes can be specified as a hash.
#
# image_button("url")
# # <INPUT TYPE="image" SRC="url">
#
# image_button("url", "name", "string")
# # <INPUT TYPE="image" SRC="url" NAME="name" ALT="string">
#
# image_button("SRC" => "url", "ATL" => "strng")
# # <INPUT TYPE="image" SRC="url" ALT="string">
def image_button(src = "", name = nil, alt = nil)
attributes = if src.kind_of?(String)
{ "TYPE" => "image", "SRC" => src, "NAME" => name,
"ALT" => alt }
else
src["TYPE"] = "image"
src["SRC"] ||= ""
src
end
input(attributes)
end
# Generate an Image element as a string.
#
# +src+ is the URL of the image. +alt+ is the alternative text for
# the image. +width+ is the width of the image, and +height+ is
# its height.
#
# Alternatively, the attributes can be specified as a hash.
#
# img("src", "alt", 100, 50)
# # <IMG SRC="src" ALT="alt" WIDTH="100" HEIGHT="50">
#
# img("SRC" => "src", "ALT" => "alt", "WIDTH" => 100, "HEIGHT" => 50)
# # <IMG SRC="src" ALT="alt" WIDTH="100" HEIGHT="50">
def img(src = "", alt = "", width = nil, height = nil)
attributes = if src.kind_of?(String)
{ "SRC" => src, "ALT" => alt }
else
src
end
attributes["WIDTH"] = width.to_s if width
attributes["HEIGHT"] = height.to_s if height
super(attributes)
end
# Generate a Form element with multipart encoding as a String.
#
# Multipart encoding is used for forms that include file uploads.
#
# +action+ is the action to perform. +enctype+ is the encoding
# type, which defaults to "multipart/form-data".
#
# Alternatively, the attributes can be specified as a hash.
#
# multipart_form{ "string" }
# # <FORM METHOD="post" ENCTYPE="multipart/form-data">string</FORM>
#
# multipart_form("url") { "string" }
# # <FORM METHOD="post" ACTION="url" ENCTYPE="multipart/form-data">string</FORM>
def multipart_form(action = nil, enctype = "multipart/form-data")
attributes = if action == nil
{ "METHOD" => "post", "ENCTYPE" => enctype }
elsif action.kind_of?(String)
{ "METHOD" => "post", "ACTION" => action,
"ENCTYPE" => enctype }
else
unless action.has_key?("METHOD")
action["METHOD"] = "post"
end
unless action.has_key?("ENCTYPE")
action["ENCTYPE"] = enctype
end
action
end
if block_given?
form(attributes){ yield }
else
form(attributes)
end
end
# Generate a Password Input element as a string.
#
# +name+ is the name of the input field. +value+ is its default
# value. +size+ is the size of the input field display. +maxlength+
# is the maximum length of the inputted password.
#
# Alternatively, attributes can be specified as a hash.
#
# password_field("name")
# # <INPUT TYPE="password" NAME="name" SIZE="40">
#
# password_field("name", "value")
# # <INPUT TYPE="password" NAME="name" VALUE="value" SIZE="40">
#
# password_field("password", "value", 80, 200)
# # <INPUT TYPE="password" NAME="name" VALUE="value" SIZE="80" MAXLENGTH="200">
#
# password_field("NAME" => "name", "VALUE" => "value")
# # <INPUT TYPE="password" NAME="name" VALUE="value">
def password_field(name = "", value = nil, size = 40, maxlength = nil)
attributes = if name.kind_of?(String)
{ "TYPE" => "password", "NAME" => name,
"VALUE" => value, "SIZE" => size.to_s }
else
name["TYPE"] = "password"
name
end
attributes["MAXLENGTH"] = maxlength.to_s if maxlength
input(attributes)
end
# Generate a Select element as a string.
#
# +name+ is the name of the element. The +values+ are the options that
# can be selected from the Select menu. Each value can be a String or
# a one, two, or three-element Array. If a String or a one-element
# Array, this is both the value of that option and the text displayed for
# it. If a three-element Array, the elements are the option value, displayed
# text, and a boolean value specifying whether this option starts as selected.
# The two-element version omits either the option value (defaults to the same
# as the display text) or the boolean selected specifier (defaults to false).
#
# The attributes and options can also be specified as a hash. In this
# case, options are specified as an array of values as described above,
# with the hash key of "VALUES".
#
# popup_menu("name", "foo", "bar", "baz")
# # <SELECT NAME="name">
# # <OPTION VALUE="foo">foo</OPTION>
# # <OPTION VALUE="bar">bar</OPTION>
# # <OPTION VALUE="baz">baz</OPTION>
# # </SELECT>
#
# popup_menu("name", ["foo"], ["bar", true], "baz")
# # <SELECT NAME="name">
# # <OPTION VALUE="foo">foo</OPTION>
# # <OPTION VALUE="bar" SELECTED>bar</OPTION>
# # <OPTION VALUE="baz">baz</OPTION>
# # </SELECT>
#
# popup_menu("name", ["1", "Foo"], ["2", "Bar", true], "Baz")
# # <SELECT NAME="name">
# # <OPTION VALUE="1">Foo</OPTION>
# # <OPTION SELECTED VALUE="2">Bar</OPTION>
# # <OPTION VALUE="Baz">Baz</OPTION>
# # </SELECT>
#
# popup_menu("NAME" => "name", "SIZE" => 2, "MULTIPLE" => true,
# "VALUES" => [["1", "Foo"], ["2", "Bar", true], "Baz"])
# # <SELECT NAME="name" MULTIPLE SIZE="2">
# # <OPTION VALUE="1">Foo</OPTION>
# # <OPTION SELECTED VALUE="2">Bar</OPTION>
# # <OPTION VALUE="Baz">Baz</OPTION>
# # </SELECT>
def popup_menu(name = "", *values)
if name.kind_of?(Hash)
values = name["VALUES"]
size = name["SIZE"].to_s if name["SIZE"]
multiple = name["MULTIPLE"]
name = name["NAME"]
else
size = nil
multiple = nil
end
select({ "NAME" => name, "SIZE" => size,
"MULTIPLE" => multiple }){
values.collect{|value|
if value.kind_of?(String)
option({ "VALUE" => value }){ value }
else
if value[value.size - 1] == true
option({ "VALUE" => value[0], "SELECTED" => true }){
value[value.size - 2]
}
else
option({ "VALUE" => value[0] }){
value[value.size - 1]
}
end
end
}.join
}
end
# Generates a radio-button Input element.
#
# +name+ is the name of the input field. +value+ is the value of
# the field if checked. +checked+ specifies whether the field
# starts off checked.
#
# Alternatively, the attributes can be specified as a hash.
#
# radio_button("name", "value")
# # <INPUT TYPE="radio" NAME="name" VALUE="value">
#
# radio_button("name", "value", true)
# # <INPUT TYPE="radio" NAME="name" VALUE="value" CHECKED>
#
# radio_button("NAME" => "name", "VALUE" => "value", "ID" => "foo")
# # <INPUT TYPE="radio" NAME="name" VALUE="value" ID="foo">
def radio_button(name = "", value = nil, checked = nil)
attributes = if name.kind_of?(String)
{ "TYPE" => "radio", "NAME" => name,
"VALUE" => value, "CHECKED" => checked }
else
name["TYPE"] = "radio"
name
end
input(attributes)
end
# Generate a sequence of radio button Input elements, as a String.
#
# This works the same as #checkbox_group(). However, it is not valid
# to have more than one radiobutton in a group checked.
#
# radio_group("name", "foo", "bar", "baz")
# # <INPUT TYPE="radio" NAME="name" VALUE="foo">foo
# # <INPUT TYPE="radio" NAME="name" VALUE="bar">bar
# # <INPUT TYPE="radio" NAME="name" VALUE="baz">baz
#
# radio_group("name", ["foo"], ["bar", true], "baz")
# # <INPUT TYPE="radio" NAME="name" VALUE="foo">foo
# # <INPUT TYPE="radio" CHECKED NAME="name" VALUE="bar">bar
# # <INPUT TYPE="radio" NAME="name" VALUE="baz">baz
#
# radio_group("name", ["1", "Foo"], ["2", "Bar", true], "Baz")
# # <INPUT TYPE="radio" NAME="name" VALUE="1">Foo
# # <INPUT TYPE="radio" CHECKED NAME="name" VALUE="2">Bar
# # <INPUT TYPE="radio" NAME="name" VALUE="Baz">Baz
#
# radio_group("NAME" => "name",
# "VALUES" => ["foo", "bar", "baz"])
#
# radio_group("NAME" => "name",
# "VALUES" => [["foo"], ["bar", true], "baz"])
#
# radio_group("NAME" => "name",
# "VALUES" => [["1", "Foo"], ["2", "Bar", true], "Baz"])
def radio_group(name = "", *values)
if name.kind_of?(Hash)
values = name["VALUES"]
name = name["NAME"]
end
values.collect{|value|
if value.kind_of?(String)
radio_button(name, value) + value
else
if value[-1] == true || value[-1] == false
radio_button(name, value[0], value[-1]) +
value[-2]
else
radio_button(name, value[0]) +
value[-1]
end
end
}.join
end
# Generate a reset button Input element, as a String.
#
# This resets the values on a form to their initial values. +value+
# is the text displayed on the button. +name+ is the name of this button.
#
# Alternatively, the attributes can be specified as a hash.
#
# reset
# # <INPUT TYPE="reset">
#
# reset("reset")
# # <INPUT TYPE="reset" VALUE="reset">
#
# reset("VALUE" => "reset", "ID" => "foo")
# # <INPUT TYPE="reset" VALUE="reset" ID="foo">
def reset(value = nil, name = nil)
attributes = if (not value) or value.kind_of?(String)
{ "TYPE" => "reset", "VALUE" => value, "NAME" => name }
else
value["TYPE"] = "reset"
value
end
input(attributes)
end
alias scrolling_list popup_menu
# Generate a submit button Input element, as a String.
#
# +value+ is the text to display on the button. +name+ is the name
# of the input.
#
# Alternatively, the attributes can be specified as a hash.
#
# submit
# # <INPUT TYPE="submit">
#
# submit("ok")
# # <INPUT TYPE="submit" VALUE="ok">
#
# submit("ok", "button1")
# # <INPUT TYPE="submit" VALUE="ok" NAME="button1">
#
# submit("VALUE" => "ok", "NAME" => "button1", "ID" => "foo")
# # <INPUT TYPE="submit" VALUE="ok" NAME="button1" ID="foo">
def submit(value = nil, name = nil)
attributes = if (not value) or value.kind_of?(String)
{ "TYPE" => "submit", "VALUE" => value, "NAME" => name }
else
value["TYPE"] = "submit"
value
end
input(attributes)
end
# Generate a text field Input element, as a String.
#
# +name+ is the name of the input field. +value+ is its initial
# value. +size+ is the size of the input area. +maxlength+
# is the maximum length of input accepted.
#
# Alternatively, the attributes can be specified as a hash.
#
# text_field("name")
# # <INPUT TYPE="text" NAME="name" SIZE="40">
#
# text_field("name", "value")
# # <INPUT TYPE="text" NAME="name" VALUE="value" SIZE="40">
#
# text_field("name", "value", 80)
# # <INPUT TYPE="text" NAME="name" VALUE="value" SIZE="80">
#
# text_field("name", "value", 80, 200)
# # <INPUT TYPE="text" NAME="name" VALUE="value" SIZE="80" MAXLENGTH="200">
#
# text_field("NAME" => "name", "VALUE" => "value")
# # <INPUT TYPE="text" NAME="name" VALUE="value">
def text_field(name = "", value = nil, size = 40, maxlength = nil)
attributes = if name.kind_of?(String)
{ "TYPE" => "text", "NAME" => name, "VALUE" => value,
"SIZE" => size.to_s }
else
name["TYPE"] = "text"
name
end
attributes["MAXLENGTH"] = maxlength.to_s if maxlength
input(attributes)
end
# Generate a TextArea element, as a String.
#
# +name+ is the name of the textarea. +cols+ is the number of
# columns and +rows+ is the number of rows in the display.
#
# Alternatively, the attributes can be specified as a hash.
#
# The body is provided by the passed-in no-argument block
#
# textarea("name")
# # = textarea("NAME" => "name", "COLS" => 70, "ROWS" => 10)
#
# textarea("name", 40, 5)
# # = textarea("NAME" => "name", "COLS" => 40, "ROWS" => 5)
def textarea(name = "", cols = 70, rows = 10) # :yield:
attributes = if name.kind_of?(String)
{ "NAME" => name, "COLS" => cols.to_s,
"ROWS" => rows.to_s }
else
name
end
if block_given?
super(attributes){ yield }
else
super(attributes)
end
end
end # HtmlExtension
# Mixin module for HTML version 3 generation methods.
module Html3 # :nodoc:
# The DOCTYPE declaration for this version of HTML
def doctype
%|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">|
end
# Initialise the HTML generation methods for this version.
def element_init
extend TagMaker
methods = ""
# - -
for element in %w[ A TT I B U STRIKE BIG SMALL SUB SUP EM STRONG
DFN CODE SAMP KBD VAR CITE FONT ADDRESS DIV center MAP
APPLET PRE XMP LISTING DL OL UL DIR MENU SELECT table TITLE
STYLE SCRIPT H1 H2 H3 H4 H5 H6 TEXTAREA FORM BLOCKQUOTE
CAPTION ]
methods += <<-BEGIN + nn_element_def(element) + <<-END
def #{element.downcase}(attributes = {})
BEGIN
end
END
end
# - O EMPTY
for element in %w[ IMG BASE BASEFONT BR AREA LINK PARAM HR INPUT
ISINDEX META ]
methods += <<-BEGIN + nOE_element_def(element) + <<-END
def #{element.downcase}(attributes = {})
BEGIN
end
END
end
# O O or - O
for element in %w[ HTML HEAD BODY P PLAINTEXT DT DD LI OPTION tr
th td ]
methods += <<-BEGIN + nO_element_def(element) + <<-END
def #{element.downcase}(attributes = {})
BEGIN
end
END
end
eval(methods)
end
end # Html3
# Mixin module for HTML version 4 generation methods.
module Html4 # :nodoc:
# The DOCTYPE declaration for this version of HTML
def doctype
%|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">|
end
# Initialise the HTML generation methods for this version.
def element_init
extend TagMaker
methods = ""
# - -
for element in %w[ TT I B BIG SMALL EM STRONG DFN CODE SAMP KBD
VAR CITE ABBR ACRONYM SUB SUP SPAN BDO ADDRESS DIV MAP OBJECT
H1 H2 H3 H4 H5 H6 PRE Q INS DEL DL OL UL LABEL SELECT OPTGROUP
FIELDSET LEGEND BUTTON TABLE TITLE STYLE SCRIPT NOSCRIPT
TEXTAREA FORM A BLOCKQUOTE CAPTION ]
methods += <<-BEGIN + nn_element_def(element) + <<-END
def #{element.downcase}(attributes = {})
BEGIN
end
END
end
# - O EMPTY
for element in %w[ IMG BASE BR AREA LINK PARAM HR INPUT COL META ]
methods += <<-BEGIN + nOE_element_def(element) + <<-END
def #{element.downcase}(attributes = {})
BEGIN
end
END
end
# O O or - O
for element in %w[ HTML BODY P DT DD LI OPTION THEAD TFOOT TBODY
COLGROUP TR TH TD HEAD]
methods += <<-BEGIN + nO_element_def(element) + <<-END
def #{element.downcase}(attributes = {})
BEGIN
end
END
end
eval(methods)
end
end # Html4
# Mixin module for HTML version 4 transitional generation methods.
module Html4Tr # :nodoc:
# The DOCTYPE declaration for this version of HTML
def doctype
%|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">|
end
# Initialise the HTML generation methods for this version.
def element_init
extend TagMaker
methods = ""
# - -
for element in %w[ TT I B U S STRIKE BIG SMALL EM STRONG DFN
CODE SAMP KBD VAR CITE ABBR ACRONYM FONT SUB SUP SPAN BDO
ADDRESS DIV CENTER MAP OBJECT APPLET H1 H2 H3 H4 H5 H6 PRE Q
INS DEL DL OL UL DIR MENU LABEL SELECT OPTGROUP FIELDSET
LEGEND BUTTON TABLE IFRAME NOFRAMES TITLE STYLE SCRIPT
NOSCRIPT TEXTAREA FORM A BLOCKQUOTE CAPTION ]
| 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/cgi/session/pstore.rb | tools/jruby-1.5.1/lib/ruby/1.9/cgi/session/pstore.rb | #
# cgi/session/pstore.rb - persistent storage of marshalled session data
#
# Documentation: William Webber (william@williamwebber.com)
#
# == Overview
#
# This file provides the CGI::Session::PStore class, which builds
# persistent of session data on top of the pstore library. See
# cgi/session.rb for more details on session storage managers.
require 'cgi/session'
require 'pstore'
class CGI
class Session
# PStore-based session storage class.
#
# This builds upon the top-level PStore class provided by the
# library file pstore.rb. Session data is marshalled and stored
# in a file. File locking and transaction services are provided.
class PStore
# Create a new CGI::Session::PStore instance
#
# This constructor is used internally by CGI::Session. The
# user does not generally need to call it directly.
#
# +session+ is the session for which this instance is being
# created. The session id must only contain alphanumeric
# characters; automatically generated session ids observe
# this requirement.
#
# +option+ is a hash of options for the initializer. The
# following options are recognised:
#
# tmpdir:: the directory to use for storing the PStore
# file. Defaults to Dir::tmpdir (generally "/tmp"
# on Unix systems).
# prefix:: the prefix to add to the session id when generating
# the filename for this session's PStore file.
# Defaults to the empty string.
#
# This session's PStore file will be created if it does
# not exist, or opened if it does.
def initialize(session, option={})
dir = option['tmpdir'] || Dir::tmpdir
prefix = option['prefix'] || ''
id = session.session_id
require 'digest/md5'
md5 = Digest::MD5.hexdigest(id)[0,16]
path = dir+"/"+prefix+md5
path.untaint
if File::exist?(path)
@hash = nil
else
unless session.new_session
raise CGI::Session::NoSession, "uninitialized session"
end
@hash = {}
end
@p = ::PStore.new(path)
@p.transaction do |p|
File.chmod(0600, p.path)
end
end
# Restore session state from the session's PStore file.
#
# Returns the session state as a hash.
def restore
unless @hash
@p.transaction do
@hash = @p['hash'] || {}
end
end
@hash
end
# Save session state to the session's PStore file.
def update
@p.transaction do
@p['hash'] = @hash
end
end
# Update and close the session's PStore file.
def close
update
end
# Close and delete the session's PStore file.
def delete
path = @p.path
File::unlink path
end
end
end
end
if $0 == __FILE__
# :enddoc:
STDIN.reopen("/dev/null")
cgi = CGI.new
session = CGI::Session.new(cgi, 'database_manager' => CGI::Session::PStore)
session['key'] = {'k' => 'v'}
puts session['key'].class
fail unless Hash === session['key']
puts session['key'].inspect
fail unless session['key'].inspect == '{"k"=>"v"}'
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/minitest/unit.rb | tools/jruby-1.5.1/lib/ruby/1.9/minitest/unit.rb | ############################################################
# This file is imported from a different project.
# DO NOT make modifications in this repo.
# File a patch instead and assign it to Ryan Davis
############################################################
##
#
# Totally minimal drop-in replacement for test-unit
#
# TODO: refute -> debunk, prove/rebut, show/deny... lots of possibilities
module MiniTest
class Assertion < Exception; end
class Skip < Assertion; end
file = if RUBY_VERSION =~ /^1\.9/ then # bt's expanded, but __FILE__ isn't :(
File.expand_path __FILE__
elsif __FILE__ =~ /^[^\.]/ then # assume both relative
require 'pathname'
pwd = Pathname.new Dir.pwd
pn = Pathname.new File.expand_path(__FILE__)
pn = File.join(".", pn.relative_path_from(pwd)) unless pn.relative?
pn.to_s
else # assume both are expanded
__FILE__
end
# './lib' in project dir, or '/usr/local/blahblah' if installed
MINI_DIR = File.dirname(File.dirname(file))
def self.filter_backtrace bt
return ["No backtrace"] unless bt
new_bt = []
bt.each do |line|
break if line.rindex(MINI_DIR, 0)
new_bt << line
end
new_bt = bt.reject { |line| line.rindex(MINI_DIR, 0) } if new_bt.empty?
new_bt = bt.dup if new_bt.empty?
new_bt
end
module Assertions
def mu_pp(obj)
s = obj.inspect
s = s.force_encoding(Encoding.default_external) if defined? Encoding
s
end
def _assertions= n
@_assertions = n
end
def _assertions
@_assertions ||= 0
end
def assert test, msg = nil
msg ||= "Failed assertion, no message given."
self._assertions += 1
unless test then
msg = msg.call if Proc === msg
raise MiniTest::Assertion, msg
end
true
end
def assert_block msg = nil
msg = message(msg) { "Expected block to return true value" }
assert yield, msg
end
def assert_empty obj, msg = nil
msg = message(msg) { "Expected #{obj.inspect} to be empty" }
assert_respond_to obj, :empty?
assert obj.empty?, msg
end
def assert_equal exp, act, msg = nil
msg = message(msg) { "Expected #{mu_pp(exp)}, not #{mu_pp(act)}" }
assert(exp == act, msg)
end
def assert_in_delta exp, act, delta = 0.001, msg = nil
n = (exp - act).abs
msg = message(msg) { "Expected #{exp} - #{act} (#{n}) to be < #{delta}" }
assert delta >= n, msg
end
def assert_in_epsilon a, b, epsilon = 0.001, msg = nil
assert_in_delta a, b, [a, b].min * epsilon, msg
end
def assert_includes collection, obj, msg = nil
msg = message(msg) { "Expected #{mu_pp(collection)} to include #{mu_pp(obj)}" }
flip = (obj.respond_to? :include?) && ! (collection.respond_to? :include?) # HACK for specs
obj, collection = collection, obj if flip
assert_respond_to collection, :include?
assert collection.include?(obj), msg
end
def assert_instance_of cls, obj, msg = nil
msg = message(msg) { "Expected #{mu_pp(obj)} to be an instance of #{cls}, not #{obj.class}" }
flip = (Module === obj) && ! (Module === cls) # HACK for specs
obj, cls = cls, obj if flip
assert obj.instance_of?(cls), msg
end
def assert_kind_of cls, obj, msg = nil # TODO: merge with instance_of
msg = message(msg) {
"Expected #{mu_pp(obj)} to be a kind of #{cls}, not #{obj.class}" }
flip = (Module === obj) && ! (Module === cls) # HACK for specs
obj, cls = cls, obj if flip
assert obj.kind_of?(cls), msg
end
def assert_match exp, act, msg = nil
msg = message(msg) { "Expected #{mu_pp(exp)} to match #{mu_pp(act)}" }
assert_respond_to act, :"=~"
exp = /#{Regexp.escape(exp)}/ if String === exp && String === act
assert exp =~ act, msg
end
def assert_nil obj, msg = nil
msg = message(msg) { "Expected #{mu_pp(obj)} to be nil" }
assert obj.nil?, msg
end
def assert_operator o1, op, o2, msg = nil
msg = message(msg) { "Expected #{mu_pp(o1)} to be #{op} #{mu_pp(o2)}" }
assert o1.__send__(op, o2), msg
end
def assert_raises *exp
msg = String === exp.last ? exp.pop : nil
should_raise = false
begin
yield
should_raise = true
rescue Exception => e
assert(exp.any? { |ex|
ex.instance_of?(Module) ? e.kind_of?(ex) : ex == e.class
}, exception_details(e, "#{mu_pp(exp)} exception expected, not"))
return e
end
exp = exp.first if exp.size == 1
flunk "#{mu_pp(exp)} expected but nothing was raised." if should_raise
end
def assert_respond_to obj, meth, msg = nil
msg = message(msg) {
"Expected #{mu_pp(obj)} (#{obj.class}) to respond to ##{meth}"
}
flip = (Symbol === obj) && ! (Symbol === meth) # HACK for specs
obj, meth = meth, obj if flip
assert obj.respond_to?(meth), msg
end
def assert_same exp, act, msg = nil
msg = message(msg) {
data = [mu_pp(act), act.object_id, mu_pp(exp), exp.object_id]
"Expected %s (0x%x) to be the same as %s (0x%x)" % data
}
assert exp.equal?(act), msg
end
def assert_send send_ary, m = nil
recv, msg, *args = send_ary
m = message(m) {
"Expected #{mu_pp(recv)}.#{msg}(*#{mu_pp(args)}) to return true" }
assert recv.__send__(msg, *args), m
end
def assert_throws sym, msg = nil
default = "Expected #{mu_pp(sym)} to have been thrown"
caught = true
catch(sym) do
begin
yield
rescue ArgumentError => e # 1.9 exception
default += ", not #{e.message.split(/ /).last}"
rescue NameError => e # 1.8 exception
default += ", not #{e.name.inspect}"
end
caught = false
end
assert caught, message(msg) { default }
end
def capture_io
require 'stringio'
orig_stdout, orig_stderr = $stdout, $stderr
captured_stdout, captured_stderr = StringIO.new, StringIO.new
$stdout, $stderr = captured_stdout, captured_stderr
yield
return captured_stdout.string, captured_stderr.string
ensure
$stdout = orig_stdout
$stderr = orig_stderr
end
def exception_details e, msg
"#{msg}\nClass: <#{e.class}>\nMessage: <#{e.message.inspect}>\n---Backtrace---\n#{MiniTest::filter_backtrace(e.backtrace).join("\n")}\n---------------"
end
def flunk msg = nil
msg ||= "Epic Fail!"
assert false, msg
end
def message msg = nil, &default
proc {
if msg then
msg = msg.to_s unless String === msg
msg += '.' unless msg.empty?
msg += "\n#{default.call}."
msg.strip
else
"#{default.call}."
end
}
end
# used for counting assertions
def pass msg = nil
assert true
end
def refute test, msg = nil
msg ||= "Failed refutation, no message given"
not assert(! test, msg)
end
def refute_empty obj, msg = nil
msg = message(msg) { "Expected #{obj.inspect} to not be empty" }
assert_respond_to obj, :empty?
refute obj.empty?, msg
end
def refute_equal exp, act, msg = nil
msg = message(msg) { "Expected #{mu_pp(act)} to not be equal to #{mu_pp(exp)}" }
refute exp == act, msg
end
def refute_in_delta exp, act, delta = 0.001, msg = nil
n = (exp - act).abs
msg = message(msg) { "Expected #{exp} - #{act} (#{n}) to not be < #{delta}" }
refute delta > n, msg
end
def refute_in_epsilon a, b, epsilon = 0.001, msg = nil
refute_in_delta a, b, a * epsilon, msg
end
def refute_includes collection, obj, msg = nil
msg = message(msg) { "Expected #{mu_pp(collection)} to not include #{mu_pp(obj)}" }
flip = (obj.respond_to? :include?) && ! (collection.respond_to? :include?) # HACK for specs
obj, collection = collection, obj if flip
assert_respond_to collection, :include?
refute collection.include?(obj), msg
end
def refute_instance_of cls, obj, msg = nil
msg = message(msg) { "Expected #{mu_pp(obj)} to not be an instance of #{cls}" }
flip = (Module === obj) && ! (Module === cls) # HACK for specs
obj, cls = cls, obj if flip
refute obj.instance_of?(cls), msg
end
def refute_kind_of cls, obj, msg = nil # TODO: merge with instance_of
msg = message(msg) { "Expected #{mu_pp(obj)} to not be a kind of #{cls}" }
flip = (Module === obj) && ! (Module === cls) # HACK for specs
obj, cls = cls, obj if flip
refute obj.kind_of?(cls), msg
end
def refute_match exp, act, msg = nil
msg = message(msg) { "Expected #{mu_pp(exp)} to not match #{mu_pp(act)}" }
assert_respond_to act, :"=~"
exp = /#{Regexp.escape(exp)}/ if String === exp && String === act
refute exp =~ act, msg
end
def refute_nil obj, msg = nil
msg = message(msg) { "Expected #{mu_pp(obj)} to not be nil" }
refute obj.nil?, msg
end
def refute_operator o1, op, o2, msg = nil
msg = message(msg) { "Expected #{mu_pp(o1)} to not be #{op} #{mu_pp(o2)}" }
refute o1.__send__(op, o2), msg
end
def refute_respond_to obj, meth, msg = nil
msg = message(msg) { "Expected #{mu_pp(obj)} to not respond to #{meth}" }
flip = (Symbol === obj) && ! (Symbol === meth) # HACK for specs
obj, meth = meth, obj if flip
refute obj.respond_to?(meth), msg
end
def refute_same exp, act, msg = nil
msg = message(msg) { "Expected #{mu_pp(act)} to not be the same as #{mu_pp(exp)}" }
refute exp.equal?(act), msg
end
def skip msg = nil, bt = caller
msg ||= "Skipped, no message given"
raise MiniTest::Skip, msg, bt
end
end
class Unit
VERSION = "1.4.2"
attr_accessor :report, :failures, :errors, :skips
attr_accessor :test_count, :assertion_count
attr_accessor :start_time
@@installed_at_exit ||= false
@@out = $stdout
def self.autorun
at_exit {
next if $! # don't run if there was an exception
exit_code = MiniTest::Unit.new.run(ARGV)
exit false if exit_code && exit_code != 0
} unless @@installed_at_exit
@@installed_at_exit = true
end
def self.output= stream
@@out = stream
end
def location e
last_before_assertion = ""
e.backtrace.reverse_each do |s|
break if s =~ /in .(assert|refute|flunk|pass|fail|raise|must|wont)/
last_before_assertion = s
end
last_before_assertion.sub(/:in .*$/, '')
end
def puke klass, meth, e
e = case e
when MiniTest::Skip then
@skips += 1
"Skipped:\n#{meth}(#{klass}) [#{location e}]:\n#{e.message}\n"
when MiniTest::Assertion then
@failures += 1
"Failure:\n#{meth}(#{klass}) [#{location e}]:\n#{e.message}\n"
else
@errors += 1
bt = MiniTest::filter_backtrace(e.backtrace).join("\n ")
"Error:\n#{meth}(#{klass}):\n#{e.class}: #{e.message}\n #{bt}\n"
end
@report << e
e[0, 1]
end
def initialize
@report = []
@errors = @failures = @skips = 0
@verbose = false
end
##
# Top level driver, controls all output and filtering.
def run args = []
@verbose = args.delete('-v')
filter = if args.first =~ /^(-n|--name)$/ then
args.shift
arg = args.shift
arg =~ /\/(.*)\// ? Regexp.new($1) : arg
else
/./ # anything - ^test_ already filtered by #tests
end
@@out.puts "Loaded suite #{$0.sub(/\.rb$/, '')}\nStarted"
start = Time.now
run_test_suites filter
@@out.puts
@@out.puts "Finished in #{'%.6f' % (Time.now - start)} seconds."
@report.each_with_index do |msg, i|
@@out.puts "\n%3d) %s" % [i + 1, msg]
end
@@out.puts
status
return failures + errors if @test_count > 0 # or return nil...
rescue Interrupt
abort 'Interrupted'
end
def status io = @@out
format = "%d tests, %d assertions, %d failures, %d errors, %d skips"
io.puts format % [test_count, assertion_count, failures, errors, skips]
end
def run_test_suites filter = /./
@test_count, @assertion_count = 0, 0
old_sync, @@out.sync = @@out.sync, true if @@out.respond_to? :sync=
TestCase.test_suites.each do |suite|
suite.test_methods.grep(filter).each do |test|
inst = suite.new test
inst._assertions = 0
@@out.print "#{suite}##{test}: " if @verbose
@start_time = Time.now
result = inst.run(self)
@@out.print "%.2f s: " % (Time.now - @start_time) if @verbose
@@out.print result
@@out.puts if @verbose
@test_count += 1
@assertion_count += inst._assertions
end
end
@@out.sync = old_sync if @@out.respond_to? :sync=
[@test_count, @assertion_count]
end
class TestCase
attr_reader :__name__
PASSTHROUGH_EXCEPTIONS = [NoMemoryError, SignalException, Interrupt,
SystemExit]
SUPPORTS_INFO_SIGNAL = Signal.list['INFO']
def run runner
trap 'INFO' do
warn '%s#%s %.2fs' % [self.class, self.__name__,
(Time.now - runner.start_time)]
runner.status $stderr
end if SUPPORTS_INFO_SIGNAL
result = '.'
begin
@passed = nil
self.setup
self.__send__ self.__name__
@passed = true
rescue *PASSTHROUGH_EXCEPTIONS
raise
rescue Exception => e
@passed = false
result = runner.puke(self.class, self.__name__, e)
ensure
begin
self.teardown
rescue *PASSTHROUGH_EXCEPTIONS
raise
rescue Exception => e
result = runner.puke(self.class, self.__name__, e)
end
trap 'INFO', 'DEFAULT' if SUPPORTS_INFO_SIGNAL
end
result
end
def initialize name
@__name__ = name
@passed = nil
end
def self.reset
@@test_suites = {}
end
reset
def self.inherited klass
@@test_suites[klass] = true
end
def self.test_order
:random
end
def self.test_suites
@@test_suites.keys.sort_by { |ts| ts.name }
end
def self.test_methods
methods = public_instance_methods(true).grep(/^test/).map { |m|
m.to_s
}.sort
if self.test_order == :random then
max = methods.size
methods = methods.sort_by { rand(max) }
end
methods
end
def setup; end
def teardown; end
def passed?
@passed
end
include MiniTest::Assertions
end # class TestCase
end # class Test
end # module Mini
if $DEBUG then
# this helps me ferret out porting issues
module Test; end
module Test::Unit; end
class Test::Unit::TestCase
def self.inherited x
raise "You're running minitest and test/unit in the same process: #{x}"
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/minitest/spec.rb | tools/jruby-1.5.1/lib/ruby/1.9/minitest/spec.rb | ############################################################
# This file is imported from a different project.
# DO NOT make modifications in this repo.
# File a patch instead and assign it to Ryan Davis
############################################################
#!/usr/bin/ruby -w
require 'minitest/unit'
class Module
def infect_with_assertions pos_prefix, neg_prefix, skip_re, map = {}
MiniTest::Assertions.public_instance_methods(false).each do |meth|
meth = meth.to_s
new_name = case meth
when /^assert/ then
meth.sub(/^assert/, pos_prefix.to_s)
when /^refute/ then
meth.sub(/^refute/, neg_prefix.to_s)
end
next unless new_name
next if new_name =~ skip_re
regexp, replacement = map.find { |re, _| new_name =~ re }
new_name.sub! regexp, replacement if replacement
# warn "%-22p -> %p %p" % [meth, new_name, regexp]
self.class_eval <<-EOM
def #{new_name} *args, &block
return MiniTest::Spec.current.#{meth}(*args, &self) if Proc === self
return MiniTest::Spec.current.#{meth}(args.first, self) if args.size == 1
return MiniTest::Spec.current.#{meth}(self, *args)
end
EOM
end
end
end
Object.infect_with_assertions(:must, :wont,
/^(must|wont)$|wont_(throw)|
must_(block|not?_|nothing|raise$)/x,
/(must_throw)s/ => '\1',
/(?!not)_same/ => '_be_same_as',
/_in_/ => '_be_within_',
/_operator/ => '_be',
/_includes/ => '_include',
/(must|wont)_(.*_of|nil|empty)/ => '\1_be_\2',
/must_raises/ => 'must_raise')
class Object
alias :must_be_close_to :must_be_within_delta
alias :wont_be_close_to :wont_be_within_delta
end
module Kernel
def describe desc, &block
stack = MiniTest::Spec.describe_stack
name = desc.to_s.split(/\W+/).map { |s| s.capitalize }.join + "Spec"
cls = Object.class_eval "class #{name} < #{stack.last}; end; #{name}"
cls.nuke_test_methods!
stack.push cls
cls.class_eval(&block)
stack.pop
end
private :describe
end
class MiniTest::Spec < MiniTest::Unit::TestCase
@@describe_stack = [MiniTest::Spec]
def self.describe_stack
@@describe_stack
end
def self.current
@@current_spec
end
def initialize name
super
@@current_spec = self
end
def self.nuke_test_methods!
self.public_instance_methods.grep(/^test_/).each do |name|
send :remove_method, name rescue nil
end
end
def self.define_inheritable_method name, &block
super_method = self.superclass.instance_method name
define_method name do
super_method.bind(self).call if super_method # regular super() warns
instance_eval(&block)
end
end
def self.before(type = :each, &block)
raise "unsupported before type: #{type}" unless type == :each
define_inheritable_method :setup, &block
end
def self.after(type = :each, &block)
raise "unsupported after type: #{type}" unless type == :each
define_inheritable_method :teardown, &block
end
def self.it desc, &block
define_method "test_#{desc.gsub(/\W+/, '_').downcase}", &block
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/minitest/autorun.rb | tools/jruby-1.5.1/lib/ruby/1.9/minitest/autorun.rb | ############################################################
# This file is imported from a different project.
# DO NOT make modifications in this repo.
# File a patch instead and assign it to Ryan Davis
############################################################
require 'minitest/unit'
require 'minitest/spec'
require 'minitest/mock'
MiniTest::Unit.autorun
| 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/minitest/mock.rb | tools/jruby-1.5.1/lib/ruby/1.9/minitest/mock.rb | ############################################################
# This file is imported from a different project.
# DO NOT make modifications in this repo.
# File a patch instead and assign it to Ryan Davis
############################################################
class MockExpectationError < StandardError; end
module MiniTest
class Mock
def initialize
@expected_calls = {}
@actual_calls = Hash.new {|h,k| h[k] = [] }
end
def expect(name, retval, args=[])
n, r, a = name, retval, args # for the closure below
@expected_calls[name] = { :retval => retval, :args => args }
self.class.__send__(:define_method, name) { |*x|
raise ArgumentError unless @expected_calls[n][:args].size == x.size
@actual_calls[n] << { :retval => r, :args => x }
retval
}
self
end
def verify
@expected_calls.each_key do |name|
expected = @expected_calls[name]
msg = "expected #{name}, #{expected.inspect}"
raise MockExpectationError, msg unless
@actual_calls.has_key? name and @actual_calls[name].include?(expected)
end
true
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/uri/generic.rb | tools/jruby-1.5.1/lib/ruby/1.9/uri/generic.rb | #
# = uri/generic.rb
#
# Author:: Akira Yamada <akira@ruby-lang.org>
# License:: You can redistribute it and/or modify it under the same term as Ruby.
# Revision:: $Id: generic.rb 23598 2009-05-27 17:48:54Z akr $
#
require 'uri/common'
module URI
#
# Base class for all URI classes.
# Implements generic URI syntax as per RFC 2396.
#
class Generic
include URI
DEFAULT_PORT = nil
#
# Returns default port
#
def self.default_port
self::DEFAULT_PORT
end
def default_port
self.class.default_port
end
COMPONENT = [
:scheme,
:userinfo, :host, :port, :registry,
:path, :opaque,
:query,
:fragment
].freeze
#
# Components of the URI in the order.
#
def self.component
self::COMPONENT
end
USE_REGISTRY = false
#
# DOC: FIXME!
#
def self.use_registry
self::USE_REGISTRY
end
#
# == Synopsis
#
# See #new
#
# == Description
#
# At first, tries to create a new URI::Generic instance using
# URI::Generic::build. But, if exception URI::InvalidComponentError is raised,
# then it URI::Escape.escape all URI components and tries again.
#
#
def self.build2(args)
begin
return self.build(args)
rescue InvalidComponentError
if args.kind_of?(Array)
return self.build(args.collect{|x|
if x
parser.escape(x)
else
x
end
})
elsif args.kind_of?(Hash)
tmp = {}
args.each do |key, value|
tmp[key] = if value
parser.escape(value)
else
value
end
end
return self.build(tmp)
end
end
end
#
# == Synopsis
#
# See #new
#
# == Description
#
# Creates a new URI::Generic instance from components of URI::Generic
# with check. Components are: scheme, userinfo, host, port, registry, path,
# opaque, query and fragment. You can provide arguments either by an Array or a Hash.
# See #new for hash keys to use or for order of array items.
#
def self.build(args)
if args.kind_of?(Array) &&
args.size == ::URI::Generic::COMPONENT.size
tmp = args
elsif args.kind_of?(Hash)
tmp = ::URI::Generic::COMPONENT.collect do |c|
if args.include?(c)
args[c]
else
nil
end
end
else
raise ArgumentError,
"expected Array of or Hash of components of #{self.class} (#{self.class.component.join(', ')})"
end
tmp << nil
tmp << true
return self.new(*tmp)
end
#
# == Args
#
# +scheme+::
# Protocol scheme, i.e. 'http','ftp','mailto' and so on.
# +userinfo+::
# User name and password, i.e. 'sdmitry:bla'
# +host+::
# Server host name
# +port+::
# Server port
# +registry+::
# DOC: FIXME!
# +path+::
# Path on server
# +opaque+::
# DOC: FIXME!
# +query+::
# Query data
# +fragment+::
# A part of URI after '#' sign
# +parser+::
# Parser for internal use [URI::DEFAULT_PARSER by default]
# +arg_check+::
# Check arguments [false by default]
#
# == Description
#
# Creates a new URI::Generic instance from ``generic'' components without check.
#
def initialize(scheme,
userinfo, host, port, registry,
path, opaque,
query,
fragment,
parser = DEFAULT_PARSER,
arg_check = false)
@scheme = nil
@user = nil
@password = nil
@host = nil
@port = nil
@path = nil
@query = nil
@opaque = nil
@registry = nil
@fragment = nil
@parser = parser == DEFAULT_PARSER ? nil : parser
if arg_check
self.scheme = scheme
self.userinfo = userinfo
self.host = host
self.port = port
self.path = path
self.query = query
self.opaque = opaque
self.registry = registry
self.fragment = fragment
else
self.set_scheme(scheme)
self.set_userinfo(userinfo)
self.set_host(host)
self.set_port(port)
self.set_path(path)
self.set_query(query)
self.set_opaque(opaque)
self.set_registry(registry)
self.set_fragment(fragment)
end
if @registry && !self.class.use_registry
raise InvalidURIError,
"the scheme #{@scheme} does not accept registry part: #{@registry} (or bad hostname?)"
end
@scheme.freeze if @scheme
self.set_path('') if !@path && !@opaque # (see RFC2396 Section 5.2)
self.set_port(self.default_port) if self.default_port && !@port
end
attr_reader :scheme
attr_reader :host
attr_reader :port
attr_reader :registry
attr_reader :path
attr_reader :query
attr_reader :opaque
attr_reader :fragment
def parser
if !defined?(@parser) || !@parser
DEFAULT_PARSER
else
@parser || DEFAULT_PARSER
end
end
# replace self by other URI object
def replace!(oth)
if self.class != oth.class
raise ArgumentError, "expected #{self.class} object"
end
component.each do |c|
self.__send__("#{c}=", oth.__send__(c))
end
end
private :replace!
def component
self.class.component
end
def check_scheme(v)
if v && parser.regexp[:SCHEME] !~ v
raise InvalidComponentError,
"bad component(expected scheme component): #{v}"
end
return true
end
private :check_scheme
def set_scheme(v)
@scheme = v
end
protected :set_scheme
def scheme=(v)
check_scheme(v)
set_scheme(v)
v
end
def check_userinfo(user, password = nil)
if !password
user, password = split_userinfo(user)
end
check_user(user)
check_password(password, user)
return true
end
private :check_userinfo
def check_user(v)
if @registry || @opaque
raise InvalidURIError,
"can not set user with registry or opaque"
end
return v unless v
if parser.regexp[:USERINFO] !~ v
raise InvalidComponentError,
"bad component(expected userinfo component or user component): #{v}"
end
return true
end
private :check_user
def check_password(v, user = @user)
if @registry || @opaque
raise InvalidURIError,
"can not set password with registry or opaque"
end
return v unless v
if !user
raise InvalidURIError,
"password component depends user component"
end
if parser.regexp[:USERINFO] !~ v
raise InvalidComponentError,
"bad component(expected user component): #{v}"
end
return true
end
private :check_password
#
# Sets userinfo, argument is string like 'name:pass'
#
def userinfo=(userinfo)
if userinfo.nil?
return nil
end
check_userinfo(*userinfo)
set_userinfo(*userinfo)
# returns userinfo
end
def user=(user)
check_user(user)
set_user(user)
# returns user
end
def password=(password)
check_password(password)
set_password(password)
# returns password
end
def set_userinfo(user, password = nil)
unless password
user, password = split_userinfo(user)
end
@user = user
@password = password if password
[@user, @password]
end
protected :set_userinfo
def set_user(v)
set_userinfo(v, @password)
v
end
protected :set_user
def set_password(v)
@password = v
# returns v
end
protected :set_password
def split_userinfo(ui)
return nil, nil unless ui
user, password = ui.split(/:/, 2)
return user, password
end
private :split_userinfo
def escape_userpass(v)
v = parser.escape(v, /[@:\/]/o) # RFC 1738 section 3.1 #/
end
private :escape_userpass
def userinfo
if @user.nil?
nil
elsif @password.nil?
@user
else
@user + ':' + @password
end
end
def user
@user
end
def password
@password
end
def check_host(v)
return v unless v
if @registry || @opaque
raise InvalidURIError,
"can not set host with registry or opaque"
elsif parser.regexp[:HOST] !~ v
raise InvalidComponentError,
"bad component(expected host component): #{v}"
end
return true
end
private :check_host
def set_host(v)
@host = v
end
protected :set_host
def host=(v)
check_host(v)
set_host(v)
v
end
def check_port(v)
return v unless v
if @registry || @opaque
raise InvalidURIError,
"can not set port with registry or opaque"
elsif !v.kind_of?(Fixnum) && parser.regexp[:PORT] !~ v
raise InvalidComponentError,
"bad component(expected port component): #{v}"
end
return true
end
private :check_port
def set_port(v)
unless !v || v.kind_of?(Fixnum)
if v.empty?
v = nil
else
v = v.to_i
end
end
@port = v
end
protected :set_port
def port=(v)
check_port(v)
set_port(v)
port
end
def check_registry(v)
return v unless v
# raise if both server and registry are not nil, because:
# authority = server | reg_name
# server = [ [ userinfo "@" ] hostport ]
if @host || @port || @user # userinfo = @user + ':' + @password
raise InvalidURIError,
"can not set registry with host, port, or userinfo"
elsif v && parser.regexp[:REGISTRY] !~ v
raise InvalidComponentError,
"bad component(expected registry component): #{v}"
end
return true
end
private :check_registry
def set_registry(v)
@registry = v
end
protected :set_registry
def registry=(v)
check_registry(v)
set_registry(v)
v
end
def check_path(v)
# raise if both hier and opaque are not nil, because:
# absoluteURI = scheme ":" ( hier_part | opaque_part )
# hier_part = ( net_path | abs_path ) [ "?" query ]
if v && @opaque
raise InvalidURIError,
"path conflicts with opaque"
end
if @scheme
if v && v != '' && parser.regexp[:ABS_PATH] !~ v
raise InvalidComponentError,
"bad component(expected absolute path component): #{v}"
end
else
if v && v != '' && parser.regexp[:ABS_PATH] !~ v && parser.regexp[:REL_PATH] !~ v
raise InvalidComponentError,
"bad component(expected relative path component): #{v}"
end
end
return true
end
private :check_path
def set_path(v)
@path = v
end
protected :set_path
def path=(v)
check_path(v)
set_path(v)
v
end
def check_query(v)
return v unless v
# raise if both hier and opaque are not nil, because:
# absoluteURI = scheme ":" ( hier_part | opaque_part )
# hier_part = ( net_path | abs_path ) [ "?" query ]
if @opaque
raise InvalidURIError,
"query conflicts with opaque"
end
if v && v != '' && parser.regexp[:QUERY] !~ v
raise InvalidComponentError,
"bad component(expected query component): #{v}"
end
return true
end
private :check_query
def set_query(v)
@query = v
end
protected :set_query
def query=(v)
check_query(v)
set_query(v)
v
end
def check_opaque(v)
return v unless v
# raise if both hier and opaque are not nil, because:
# absoluteURI = scheme ":" ( hier_part | opaque_part )
# hier_part = ( net_path | abs_path ) [ "?" query ]
if @host || @port || @user || @path # userinfo = @user + ':' + @password
raise InvalidURIError,
"can not set opaque with host, port, userinfo or path"
elsif v && parser.regexp[:OPAQUE] !~ v
raise InvalidComponentError,
"bad component(expected opaque component): #{v}"
end
return true
end
private :check_opaque
def set_opaque(v)
@opaque = v
end
protected :set_opaque
def opaque=(v)
check_opaque(v)
set_opaque(v)
v
end
def check_fragment(v)
return v unless v
if v && v != '' && parser.regexp[:FRAGMENT] !~ v
raise InvalidComponentError,
"bad component(expected fragment component): #{v}"
end
return true
end
private :check_fragment
def set_fragment(v)
@fragment = v
end
protected :set_fragment
def fragment=(v)
check_fragment(v)
set_fragment(v)
v
end
#
# Checks if URI has a path
#
def hierarchical?
if @path
true
else
false
end
end
#
# Checks if URI is an absolute one
#
def absolute?
if @scheme
true
else
false
end
end
alias absolute absolute?
#
# Checks if URI is relative
#
def relative?
!absolute?
end
def split_path(path)
path.split(%r{/+}, -1)
end
private :split_path
def merge_path(base, rel)
# RFC2396, Section 5.2, 5)
# RFC2396, Section 5.2, 6)
base_path = split_path(base)
rel_path = split_path(rel)
# RFC2396, Section 5.2, 6), a)
base_path << '' if base_path.last == '..'
while i = base_path.index('..')
base_path.slice!(i - 1, 2)
end
if (first = rel_path.first) and first.empty?
base_path.clear
rel_path.shift
end
# RFC2396, Section 5.2, 6), c)
# RFC2396, Section 5.2, 6), d)
rel_path.push('') if rel_path.last == '.' || rel_path.last == '..'
rel_path.delete('.')
# RFC2396, Section 5.2, 6), e)
tmp = []
rel_path.each do |x|
if x == '..' &&
!(tmp.empty? || tmp.last == '..')
tmp.pop
else
tmp << x
end
end
add_trailer_slash = !tmp.empty?
if base_path.empty?
base_path = [''] # keep '/' for root directory
elsif add_trailer_slash
base_path.pop
end
while x = tmp.shift
if x == '..'
# RFC2396, Section 4
# a .. or . in an absolute path has no special meaning
base_path.pop if base_path.size > 1
else
# if x == '..'
# valid absolute (but abnormal) path "/../..."
# else
# valid absolute path
# end
base_path << x
tmp.each {|t| base_path << t}
add_trailer_slash = false
break
end
end
base_path.push('') if add_trailer_slash
return base_path.join('/')
end
private :merge_path
#
# == Args
#
# +oth+::
# URI or String
#
# == Description
#
# Destructive form of #merge
#
# == Usage
#
# require 'uri'
#
# uri = URI.parse("http://my.example.com")
# uri.merge!("/main.rbx?page=1")
# p uri
# # => #<URI::HTTP:0x2021f3b0 URL:http://my.example.com/main.rbx?page=1>
#
def merge!(oth)
t = merge(oth)
if self == t
nil
else
replace!(t)
self
end
end
#
# == Args
#
# +oth+::
# URI or String
#
# == Description
#
# Merges two URI's.
#
# == Usage
#
# require 'uri'
#
# uri = URI.parse("http://my.example.com")
# p uri.merge("/main.rbx?page=1")
# # => #<URI::HTTP:0x2021f3b0 URL:http://my.example.com/main.rbx?page=1>
#
def merge(oth)
begin
base, rel = merge0(oth)
rescue
raise $!.class, $!.message
end
if base == rel
return base
end
authority = rel.userinfo || rel.host || rel.port
# RFC2396, Section 5.2, 2)
if (rel.path.nil? || rel.path.empty?) && !authority && !rel.query
base.set_fragment(rel.fragment) if rel.fragment
return base
end
base.set_query(nil)
base.set_fragment(nil)
# RFC2396, Section 5.2, 4)
if !authority
base.set_path(merge_path(base.path, rel.path)) if base.path && rel.path
else
# RFC2396, Section 5.2, 4)
base.set_path(rel.path) if rel.path
end
# RFC2396, Section 5.2, 7)
base.set_userinfo(rel.userinfo) if rel.userinfo
base.set_host(rel.host) if rel.host
base.set_port(rel.port) if rel.port
base.set_query(rel.query) if rel.query
base.set_fragment(rel.fragment) if rel.fragment
return base
end # merge
alias + merge
# return base and rel.
# you can modify `base', but can not `rel'.
def merge0(oth)
case oth
when Generic
when String
oth = parser.parse(oth)
else
raise ArgumentError,
"bad argument(expected URI object or URI string)"
end
if self.relative? && oth.relative?
raise BadURIError,
"both URI are relative"
end
if self.absolute? && oth.absolute?
#raise BadURIError,
# "both URI are absolute"
# hmm... should return oth for usability?
return oth, oth
end
if self.absolute?
return self.dup, oth
else
return oth, oth
end
end
private :merge0
def route_from_path(src, dst)
# RFC2396, Section 4.2
return '' if src == dst
src_path = split_path(src)
dst_path = split_path(dst)
# hmm... dst has abnormal absolute path,
# like "/./", "/../", "/x/../", ...
if dst_path.include?('..') ||
dst_path.include?('.')
return dst.dup
end
src_path.pop
# discard same parts
while dst_path.first == src_path.first
break if dst_path.empty?
src_path.shift
dst_path.shift
end
tmp = dst_path.join('/')
# calculate
if src_path.empty?
if tmp.empty?
return './'
elsif dst_path.first.include?(':') # (see RFC2396 Section 5)
return './' + tmp
else
return tmp
end
end
return '../' * src_path.size + tmp
end
private :route_from_path
def route_from0(oth)
case oth
when Generic
when String
oth = parser.parse(oth)
else
raise ArgumentError,
"bad argument(expected URI object or URI string)"
end
if self.relative?
raise BadURIError,
"relative URI: #{self}"
end
if oth.relative?
raise BadURIError,
"relative URI: #{oth}"
end
if self.scheme != oth.scheme
return self, self.dup
end
rel = URI::Generic.new(nil, # it is relative URI
self.userinfo, self.host, self.port,
self.registry, self.path, self.opaque,
self.query, self.fragment, parser)
if rel.userinfo != oth.userinfo ||
rel.host.to_s.downcase != oth.host.to_s.downcase ||
rel.port != oth.port
if self.userinfo.nil? && self.host.nil?
return self, self.dup
end
rel.set_port(nil) if rel.port == oth.default_port
return rel, rel
end
rel.set_userinfo(nil)
rel.set_host(nil)
rel.set_port(nil)
if rel.path && rel.path == oth.path
rel.set_path('')
rel.set_query(nil) if rel.query == oth.query
return rel, rel
elsif rel.opaque && rel.opaque == oth.opaque
rel.set_opaque('')
rel.set_query(nil) if rel.query == oth.query
return rel, rel
end
# you can modify `rel', but can not `oth'.
return oth, rel
end
private :route_from0
#
# == Args
#
# +oth+::
# URI or String
#
# == Description
#
# Calculates relative path from oth to self
#
# == Usage
#
# require 'uri'
#
# uri = URI.parse('http://my.example.com/main.rbx?page=1')
# p uri.route_from('http://my.example.com')
# #=> #<URI::Generic:0x20218858 URL:/main.rbx?page=1>
#
def route_from(oth)
# you can modify `rel', but can not `oth'.
begin
oth, rel = route_from0(oth)
rescue
raise $!.class, $!.message
end
if oth == rel
return rel
end
rel.set_path(route_from_path(oth.path, self.path))
if rel.path == './' && self.query
# "./?foo" -> "?foo"
rel.set_path('')
end
return rel
end
alias - route_from
#
# == Args
#
# +oth+::
# URI or String
#
# == Description
#
# Calculates relative path to oth from self
#
# == Usage
#
# require 'uri'
#
# uri = URI.parse('http://my.example.com')
# p uri.route_to('http://my.example.com/main.rbx?page=1')
# #=> #<URI::Generic:0x2020c2f6 URL:/main.rbx?page=1>
#
def route_to(oth)
case oth
when Generic
when String
oth = parser.parse(oth)
else
raise ArgumentError,
"bad argument(expected URI object or URI string)"
end
oth.route_from(self)
end
#
# Returns normalized URI
#
def normalize
uri = dup
uri.normalize!
uri
end
#
# Destructive version of #normalize
#
def normalize!
if path && path == ''
set_path('/')
end
if host && host != host.downcase
set_host(self.host.downcase)
end
end
def path_query
str = @path
if @query
str += '?' + @query
end
str
end
private :path_query
#
# Constructs String from URI
#
def to_s
str = ''
if @scheme
str << @scheme
str << ':'
end
if @opaque
str << @opaque
else
if @registry
str << @registry
else
if @host
str << '//'
end
if self.userinfo
str << self.userinfo
str << '@'
end
if @host
str << @host
end
if @port && @port != self.default_port
str << ':'
str << @port.to_s
end
end
str << path_query
end
if @fragment
str << '#'
str << @fragment
end
str
end
#
# Compares to URI's
#
def ==(oth)
if self.class == oth.class
self.normalize.component_ary == oth.normalize.component_ary
else
false
end
end
def hash
self.component_ary.hash
end
def eql?(oth)
parser == oth.parser &&
self.component_ary.eql?(oth.component_ary)
end
=begin
--- URI::Generic#===(oth)
=end
# def ===(oth)
# raise NotImplementedError
# end
=begin
=end
def component_ary
component.collect do |x|
self.send(x)
end
end
protected :component_ary
# == Args
#
# +components+::
# Multiple Symbol arguments defined in URI::HTTP
#
# == Description
#
# Selects specified components from URI
#
# == Usage
#
# require 'uri'
#
# uri = URI.parse('http://myuser:mypass@my.example.com/test.rbx')
# p uri.select(:userinfo, :host, :path)
# # => ["myuser:mypass", "my.example.com", "/test.rbx"]
#
def select(*components)
components.collect do |c|
if component.include?(c)
self.send(c)
else
raise ArgumentError,
"expected of components of #{self.class} (#{self.class.component.join(', ')})"
end
end
end
@@to_s = Kernel.instance_method(:to_s)
def inspect
@@to_s.bind(self).call.sub!(/>\z/) {" URL:#{self}>"}
end
def coerce(oth)
case oth
when String
oth = parser.parse(oth)
else
super
end
return oth, self
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/uri/common.rb | tools/jruby-1.5.1/lib/ruby/1.9/uri/common.rb | # = uri/common.rb
#
# Author:: Akira Yamada <akira@ruby-lang.org>
# Revision:: $Id: common.rb 24773 2009-09-06 18:24:53Z naruse $
# License::
# You can redistribute it and/or modify it under the same term as Ruby.
#
module URI
module REGEXP
#
# Patterns used to parse URI's
#
module PATTERN
# :stopdoc:
# RFC 2396 (URI Generic Syntax)
# RFC 2732 (IPv6 Literal Addresses in URL's)
# RFC 2373 (IPv6 Addressing Architecture)
# alpha = lowalpha | upalpha
ALPHA = "a-zA-Z"
# alphanum = alpha | digit
ALNUM = "#{ALPHA}\\d"
# hex = digit | "A" | "B" | "C" | "D" | "E" | "F" |
# "a" | "b" | "c" | "d" | "e" | "f"
HEX = "a-fA-F\\d"
# escaped = "%" hex hex
ESCAPED = "%[#{HEX}]{2}"
# mark = "-" | "_" | "." | "!" | "~" | "*" | "'" |
# "(" | ")"
# unreserved = alphanum | mark
UNRESERVED = "-_.!~*'()#{ALNUM}"
# reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
# "$" | ","
# reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
# "$" | "," | "[" | "]" (RFC 2732)
RESERVED = ";/?:@&=+$,\\[\\]"
# domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum
DOMLABEL = "(?:[#{ALNUM}](?:[-#{ALNUM}]*[#{ALNUM}])?)"
# toplabel = alpha | alpha *( alphanum | "-" ) alphanum
TOPLABEL = "(?:[#{ALPHA}](?:[-#{ALNUM}]*[#{ALNUM}])?)"
# hostname = *( domainlabel "." ) toplabel [ "." ]
HOSTNAME = "(?:#{DOMLABEL}\\.)*#{TOPLABEL}\\.?"
# :startdoc:
end # PATTERN
# :startdoc:
end # REGEXP
class Parser
include REGEXP
#
# == Synopsis
#
# URI::Parser.new([opts])
#
# == Args
#
# The constructor accepts a hash as options for parser.
# Keys of options are pattern names of URI components
# and values of options are pattern strings.
# The constructor generetes set of regexps for parsing URIs.
#
# You can use the following keys:
#
# * <tt>:ESCAPED</tt> (URI::PATTERN::ESCAPED in default)
# * <tt>:UNRESERVED</tt> (URI::PATTERN::UNRESERVED in default)
# * <tt>:DOMLABEL</tt> (URI::PATTERN::DOMLABEL in default)
# * <tt>:TOPLABEL</tt> (URI::PATTERN::TOPLABEL in default)
# * <tt>:HOSTNAME</tt> (URI::PATTERN::HOSTNAME in default)
#
# == Examples
#
# p = URI::Parser.new(:ESCPAED => "(?:%[a-fA-F0-9]{2}|%u[a-fA-F0-9]{4})"
# u = p.parse("http://example.jp/%uABCD") #=> #<URI::HTTP:0xb78cf4f8 URL:http://example.jp/%uABCD>
# URI.parse(u.to_s) #=> raises URI::InvalidURIError
#
# s = "http://examle.com/ABCD"
# u1 = p.parse(s) #=> #<URI::HTTP:0xb78c3220 URL:http://example.com/ABCD>
# u2 = URI.parse(s) #=> #<URI::HTTP:0xb78b6d54 URL:http://example.com/ABCD>
# u1 == u2 #=> true
# u1.eql?(u2) #=> false
#
def initialize(opts = {})
@pattern = initialize_pattern(opts)
@pattern.each_value {|v| v.freeze}
@pattern.freeze
@regexp = initialize_regexp(@pattern)
@regexp.each_value {|v| v.freeze}
@regexp.freeze
end
attr_reader :pattern, :regexp
def split(uri)
case uri
when ''
# null uri
when @regexp[:ABS_URI]
scheme, opaque, userinfo, host, port,
registry, path, query, fragment = $~[1..-1]
# URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
# absoluteURI = scheme ":" ( hier_part | opaque_part )
# hier_part = ( net_path | abs_path ) [ "?" query ]
# opaque_part = uric_no_slash *uric
# abs_path = "/" path_segments
# net_path = "//" authority [ abs_path ]
# authority = server | reg_name
# server = [ [ userinfo "@" ] hostport ]
if !scheme
raise InvalidURIError,
"bad URI(absolute but no scheme): #{uri}"
end
if !opaque && (!path && (!host && !registry))
raise InvalidURIError,
"bad URI(absolute but no path): #{uri}"
end
when @regexp[:REL_URI]
scheme = nil
opaque = nil
userinfo, host, port, registry,
rel_segment, abs_path, query, fragment = $~[1..-1]
if rel_segment && abs_path
path = rel_segment + abs_path
elsif rel_segment
path = rel_segment
elsif abs_path
path = abs_path
end
# URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
# relativeURI = ( net_path | abs_path | rel_path ) [ "?" query ]
# net_path = "//" authority [ abs_path ]
# abs_path = "/" path_segments
# rel_path = rel_segment [ abs_path ]
# authority = server | reg_name
# server = [ [ userinfo "@" ] hostport ]
else
raise InvalidURIError, "bad URI(is not URI?): #{uri}"
end
path = '' if !path && !opaque # (see RFC2396 Section 5.2)
ret = [
scheme,
userinfo, host, port, # X
registry, # X
path, # Y
opaque, # Y
query,
fragment
]
return ret
end
def parse(uri)
scheme, userinfo, host, port,
registry, path, opaque, query, fragment = self.split(uri)
if scheme && URI.scheme_list.include?(scheme.upcase)
URI.scheme_list[scheme.upcase].new(scheme, userinfo, host, port,
registry, path, opaque, query,
fragment, self)
else
Generic.new(scheme, userinfo, host, port,
registry, path, opaque, query,
fragment, self)
end
end
def join(*str)
u = self.parse(str[0])
str[1 .. -1].each do |x|
u = u.merge(x)
end
u
end
def extract(str, schemes = nil, &block)
if block_given?
str.scan(make_regexp(schemes)) { yield $& }
nil
else
result = []
str.scan(make_regexp(schemes)) { result.push $& }
result
end
end
def make_regexp(schemes = nil)
unless schemes
@regexp[:ABS_URI_REF]
else
/(?=#{Regexp.union(*schemes)}:)#{@pattern[:X_ABS_URI]}/x
end
end
def escape(str, unsafe = @regexp[:UNSAFE])
unless unsafe.kind_of?(Regexp)
# perhaps unsafe is String object
unsafe = Regexp.new("[#{Regexp.quote(unsafe)}]", false)
end
str.gsub(unsafe) do
us = $&
tmp = ''
us.each_byte do |uc|
tmp << sprintf('%%%02X', uc)
end
tmp
end.force_encoding(Encoding::US_ASCII)
end
def unescape(str, escaped = @regexp[:ESCAPED])
str.gsub(escaped) { [$&[1, 2].hex].pack('C') }.force_encoding(str.encoding)
end
@@to_s = Kernel.instance_method(:to_s)
def inspect
@@to_s.bind(self).call
end
private
def initialize_pattern(opts = {})
ret = {}
ret[:ESCAPED] = escaped = (opts.delete(:ESCAPED) || PATTERN::ESCAPED)
ret[:UNRESERVED] = unreserved = opts.delete(:UNRESERVED) || PATTERN::UNRESERVED
ret[:RESERVED] = reserved = opts.delete(:RESERVED) || PATTERN::RESERVED
ret[:DOMLABEL] = domlabel = opts.delete(:DOMLABEL) || PATTERN::DOMLABEL
ret[:TOPLABEL] = toplabel = opts.delete(:TOPLABEL) || PATTERN::TOPLABEL
ret[:HOSTNAME] = hostname = opts.delete(:HOSTNAME)
# RFC 2396 (URI Generic Syntax)
# RFC 2732 (IPv6 Literal Addresses in URL's)
# RFC 2373 (IPv6 Addressing Architecture)
# uric = reserved | unreserved | escaped
ret[:URIC] = uric = "(?:[#{unreserved}#{reserved}]|#{escaped})"
# uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" |
# "&" | "=" | "+" | "$" | ","
ret[:URIC_NO_SLASH] = uric_no_slash = "(?:[#{unreserved};?:@&=+$,]|#{escaped})"
# query = *uric
ret[:QUERY] = query = "#{uric}*"
# fragment = *uric
ret[:FRAGMENT] = fragment = "#{uric}*"
# hostname = *( domainlabel "." ) toplabel [ "." ]
unless hostname
ret[:HOSTNAME] = hostname = "(?:#{domlabel}\\.)*#{toplabel}\\.?"
end
# RFC 2373, APPENDIX B:
# IPv6address = hexpart [ ":" IPv4address ]
# IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT
# hexpart = hexseq | hexseq "::" [ hexseq ] | "::" [ hexseq ]
# hexseq = hex4 *( ":" hex4)
# hex4 = 1*4HEXDIG
#
# XXX: This definition has a flaw. "::" + IPv4address must be
# allowed too. Here is a replacement.
#
# IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT
ret[:IPV4ADDR] = ipv4addr = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"
# hex4 = 1*4HEXDIG
hex4 = "[#{PATTERN::HEX}]{1,4}"
# lastpart = hex4 | IPv4address
lastpart = "(?:#{hex4}|#{ipv4addr})"
# hexseq1 = *( hex4 ":" ) hex4
hexseq1 = "(?:#{hex4}:)*#{hex4}"
# hexseq2 = *( hex4 ":" ) lastpart
hexseq2 = "(?:#{hex4}:)*#{lastpart}"
# IPv6address = hexseq2 | [ hexseq1 ] "::" [ hexseq2 ]
ret[:IPV6ADDR] = ipv6addr = "(?:#{hexseq2}|(?:#{hexseq1})?::(?:#{hexseq2})?)"
# IPv6prefix = ( hexseq1 | [ hexseq1 ] "::" [ hexseq1 ] ) "/" 1*2DIGIT
# unused
# ipv6reference = "[" IPv6address "]" (RFC 2732)
ret[:IPV6REF] = ipv6ref = "\\[#{ipv6addr}\\]"
# host = hostname | IPv4address
# host = hostname | IPv4address | IPv6reference (RFC 2732)
ret[:HOST] = host = "(?:#{hostname}|#{ipv4addr}|#{ipv6ref})"
# port = *digit
port = '\d*'
# hostport = host [ ":" port ]
ret[:HOSTPORT] = hostport = "#{host}(?::#{port})?"
# userinfo = *( unreserved | escaped |
# ";" | ":" | "&" | "=" | "+" | "$" | "," )
ret[:USERINFO] = userinfo = "(?:[#{unreserved};:&=+$,]|#{escaped})*"
# pchar = unreserved | escaped |
# ":" | "@" | "&" | "=" | "+" | "$" | ","
pchar = "(?:[#{unreserved}:@&=+$,]|#{escaped})"
# param = *pchar
param = "#{pchar}*"
# segment = *pchar *( ";" param )
segment = "#{pchar}*(?:;#{param})*"
# path_segments = segment *( "/" segment )
ret[:PATH_SEGMENTS] = path_segments = "#{segment}(?:/#{segment})*"
# server = [ [ userinfo "@" ] hostport ]
server = "(?:#{userinfo}@)?#{hostport}"
# reg_name = 1*( unreserved | escaped | "$" | "," |
# ";" | ":" | "@" | "&" | "=" | "+" )
ret[:REG_NAME] = reg_name = "(?:[#{unreserved}$,;:@&=+]|#{escaped})+"
# authority = server | reg_name
authority = "(?:#{server}|#{reg_name})"
# rel_segment = 1*( unreserved | escaped |
# ";" | "@" | "&" | "=" | "+" | "$" | "," )
ret[:REL_SEGMENT] = rel_segment = "(?:[#{unreserved};@&=+$,]|#{escaped})+"
# scheme = alpha *( alpha | digit | "+" | "-" | "." )
ret[:SCHEME] = scheme = "[#{PATTERN::ALPHA}][-+.#{PATTERN::ALPHA}\\d]*"
# abs_path = "/" path_segments
ret[:ABS_PATH] = abs_path = "/#{path_segments}"
# rel_path = rel_segment [ abs_path ]
ret[:REL_PATH] = rel_path = "#{rel_segment}(?:#{abs_path})?"
# net_path = "//" authority [ abs_path ]
ret[:NET_PATH] = net_path = "//#{authority}(?:#{abs_path})?"
# hier_part = ( net_path | abs_path ) [ "?" query ]
ret[:HIER_PART] = hier_part = "(?:#{net_path}|#{abs_path})(?:\\?(?:#{query}))?"
# opaque_part = uric_no_slash *uric
ret[:OPAQUE_PART] = opaque_part = "#{uric_no_slash}#{uric}*"
# absoluteURI = scheme ":" ( hier_part | opaque_part )
ret[:ABS_URI] = abs_uri = "#{scheme}:(?:#{hier_part}|#{opaque_part})"
# relativeURI = ( net_path | abs_path | rel_path ) [ "?" query ]
ret[:REL_URI] = rel_uri = "(?:#{net_path}|#{abs_path}|#{rel_path})(?:\\?#{query})?"
# URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
ret[:URI_REF] = uri_ref = "(?:#{abs_uri}|#{rel_uri})?(?:##{fragment})?"
ret[:X_ABS_URI] = "
(#{scheme}): (?# 1: scheme)
(?:
(#{opaque_part}) (?# 2: opaque)
|
(?:(?:
//(?:
(?:(?:(#{userinfo})@)? (?# 3: userinfo)
(?:(#{host})(?::(\\d*))?))? (?# 4: host, 5: port)
|
(#{reg_name}) (?# 6: registry)
)
|
(?!//)) (?# XXX: '//' is the mark for hostport)
(#{abs_path})? (?# 7: path)
)(?:\\?(#{query}))? (?# 8: query)
)
(?:\\#(#{fragment}))? (?# 9: fragment)
"
ret[:X_REL_URI] = "
(?:
(?:
//
(?:
(?:(#{userinfo})@)? (?# 1: userinfo)
(#{host})?(?::(\\d*))? (?# 2: host, 3: port)
|
(#{reg_name}) (?# 4: registry)
)
)
|
(#{rel_segment}) (?# 5: rel_segment)
)?
(#{abs_path})? (?# 6: abs_path)
(?:\\?(#{query}))? (?# 7: query)
(?:\\#(#{fragment}))? (?# 8: fragment)
"
ret
end
def initialize_regexp(pattern)
ret = {}
# for URI::split
ret[:ABS_URI] = Regexp.new('^' + pattern[:X_ABS_URI] + '$', Regexp::EXTENDED)
ret[:REL_URI] = Regexp.new('^' + pattern[:X_REL_URI] + '$', Regexp::EXTENDED)
# for URI::extract
ret[:URI_REF] = Regexp.new(pattern[:URI_REF])
ret[:ABS_URI_REF] = Regexp.new(pattern[:X_ABS_URI], Regexp::EXTENDED)
ret[:REL_URI_REF] = Regexp.new(pattern[:X_REL_URI], Regexp::EXTENDED)
# for URI::escape/unescape
ret[:ESCAPED] = Regexp.new(pattern[:ESCAPED])
ret[:UNSAFE] = Regexp.new("[^#{pattern[:UNRESERVED]}#{pattern[:RESERVED]}]")
# for Generic#initialize
ret[:SCHEME] = Regexp.new("^#{pattern[:SCHEME]}$")
ret[:USERINFO] = Regexp.new("^#{pattern[:USERINFO]}$")
ret[:HOST] = Regexp.new("^#{pattern[:HOST]}$")
ret[:PORT] = Regexp.new("^#{pattern[:PORT]}$")
ret[:OPAQUE] = Regexp.new("^#{pattern[:OPAQUE_PART]}$")
ret[:REGISTRY] = Regexp.new("^#{pattern[:REG_NAME]}$")
ret[:ABS_PATH] = Regexp.new("^#{pattern[:ABS_PATH]}$")
ret[:REL_PATH] = Regexp.new("^#{pattern[:REL_PATH]}$")
ret[:QUERY] = Regexp.new("^#{pattern[:QUERY]}$")
ret[:FRAGMENT] = Regexp.new("^#{pattern[:FRAGMENT]}$")
ret
end
end # class Parser
DEFAULT_PARSER = Parser.new
DEFAULT_PARSER.pattern.each_pair do |sym, str|
unless REGEXP::PATTERN.const_defined?(sym)
REGEXP::PATTERN.const_set(sym, str)
end
end
DEFAULT_PARSER.regexp.each_pair do |sym, str|
const_set(sym, str)
end
module Util # :nodoc:
def make_components_hash(klass, array_hash)
tmp = {}
if array_hash.kind_of?(Array) &&
array_hash.size == klass.component.size - 1
klass.component[1..-1].each_index do |i|
begin
tmp[klass.component[i + 1]] = array_hash[i].clone
rescue TypeError
tmp[klass.component[i + 1]] = array_hash[i]
end
end
elsif array_hash.kind_of?(Hash)
array_hash.each do |key, value|
begin
tmp[key] = value.clone
rescue TypeError
tmp[key] = value
end
end
else
raise ArgumentError,
"expected Array of or Hash of components of #{klass.to_s} (#{klass.component[1..-1].join(', ')})"
end
tmp[:scheme] = klass.to_s.sub(/\A.*::/, '').downcase
return tmp
end
module_function :make_components_hash
end
module Escape
#
# == Synopsis
#
# URI.escape(str [, unsafe])
#
# == Args
#
# +str+::
# String to replaces in.
# +unsafe+::
# Regexp that matches all symbols that must be replaced with codes.
# By default uses <tt>REGEXP::UNSAFE</tt>.
# When this argument is a String, it represents a character set.
#
# == Description
#
# Escapes the string, replacing all unsafe characters with codes.
#
# == Usage
#
# require 'uri'
#
# enc_uri = URI.escape("http://example.com/?a=\11\15")
# p enc_uri
# # => "http://example.com/?a=%09%0D"
#
# p URI.unescape(enc_uri)
# # => "http://example.com/?a=\t\r"
#
# p URI.escape("@?@!", "!?")
# # => "@%3F@%21"
#
def escape(*arg)
warn "#{caller(1)[0]}: warning: URI.escape is obsolete" if $VERBOSE
DEFAULT_PARSER.escape(*arg)
end
alias encode escape
#
# == Synopsis
#
# URI.unescape(str)
#
# == Args
#
# +str+::
# Unescapes the string.
#
# == Usage
#
# require 'uri'
#
# enc_uri = URI.escape("http://example.com/?a=\11\15")
# p enc_uri
# # => "http://example.com/?a=%09%0D"
#
# p URI.unescape(enc_uri)
# # => "http://example.com/?a=\t\r"
#
def unescape(*arg)
warn "#{caller(1)[0]}: warning: URI.unescape is obsolete" if $VERBOSE
DEFAULT_PARSER.unescape(*arg)
end
alias decode unescape
end
extend Escape
include REGEXP
@@schemes = {}
def self.scheme_list
@@schemes
end
#
# Base class for all URI exceptions.
#
class Error < StandardError; end
#
# Not a URI.
#
class InvalidURIError < Error; end
#
# Not a URI component.
#
class InvalidComponentError < Error; end
#
# URI is valid, bad usage is not.
#
class BadURIError < Error; end
#
# == Synopsis
#
# URI::split(uri)
#
# == Args
#
# +uri+::
# String with URI.
#
# == Description
#
# Splits the string on following parts and returns array with result:
#
# * Scheme
# * Userinfo
# * Host
# * Port
# * Registry
# * Path
# * Opaque
# * Query
# * Fragment
#
# == Usage
#
# require 'uri'
#
# p URI.split("http://www.ruby-lang.org/")
# # => ["http", nil, "www.ruby-lang.org", nil, nil, "/", nil, nil, nil]
#
def self.split(uri)
DEFAULT_PARSER.split(uri)
end
#
# == Synopsis
#
# URI::parse(uri_str)
#
# == Args
#
# +uri_str+::
# String with URI.
#
# == Description
#
# Creates one of the URI's subclasses instance from the string.
#
# == Raises
#
# URI::InvalidURIError
# Raised if URI given is not a correct one.
#
# == Usage
#
# require 'uri'
#
# uri = URI.parse("http://www.ruby-lang.org/")
# p uri
# # => #<URI::HTTP:0x202281be URL:http://www.ruby-lang.org/>
# p uri.scheme
# # => "http"
# p uri.host
# # => "www.ruby-lang.org"
#
def self.parse(uri)
DEFAULT_PARSER.parse(uri)
end
#
# == Synopsis
#
# URI::join(str[, str, ...])
#
# == Args
#
# +str+::
# String(s) to work with
#
# == Description
#
# Joins URIs.
#
# == Usage
#
# require 'uri'
#
# p URI.join("http://localhost/","main.rbx")
# # => #<URI::HTTP:0x2022ac02 URL:http://localhost/main.rbx>
#
def self.join(*str)
DEFAULT_PARSER.join(*str)
end
#
# == Synopsis
#
# URI::extract(str[, schemes][,&blk])
#
# == Args
#
# +str+::
# String to extract URIs from.
# +schemes+::
# Limit URI matching to a specific schemes.
#
# == Description
#
# Extracts URIs from a string. If block given, iterates through all matched URIs.
# Returns nil if block given or array with matches.
#
# == Usage
#
# require "uri"
#
# URI.extract("text here http://foo.example.org/bla and here mailto:test@example.com and here also.")
# # => ["http://foo.example.com/bla", "mailto:test@example.com"]
#
def self.extract(str, schemes = nil, &block)
DEFAULT_PARSER.extract(str, schemes, &block)
end
#
# == Synopsis
#
# URI::regexp([match_schemes])
#
# == Args
#
# +match_schemes+::
# Array of schemes. If given, resulting regexp matches to URIs
# whose scheme is one of the match_schemes.
#
# == Description
# Returns a Regexp object which matches to URI-like strings.
# The Regexp object returned by this method includes arbitrary
# number of capture group (parentheses). Never rely on it's number.
#
# == Usage
#
# require 'uri'
#
# # extract first URI from html_string
# html_string.slice(URI.regexp)
#
# # remove ftp URIs
# html_string.sub(URI.regexp(['ftp'])
#
# # You should not rely on the number of parentheses
# html_string.scan(URI.regexp) do |*matches|
# p $&
# end
#
def self.regexp(schemes = nil)
DEFAULT_PARSER.make_regexp(schemes)
end
end
module Kernel
# alias for URI.parse.
#
# This method is introduced at 1.8.2.
def URI(uri_str) # :doc:
URI.parse(uri_str)
end
module_function :URI
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.