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 |
|---|---|---|---|---|---|---|---|---|
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/webrick.rb | lib/webrick.rb | ##
# = WEB server toolkit.
#
# WEBrick is an HTTP server toolkit that can be configured as an HTTPS server,
# a proxy server, and a virtual-host server. WEBrick features complete
# logging of both server operations and HTTP access. WEBrick supports both
# basic and digest authentication in addition to algorithms not in RFC 2617.
#
# A WEBrick server can be composed of multiple WEBrick servers or servlets to
# provide differing behavior on a per-host or per-path basis. WEBrick
# includes servlets for handling CGI scripts, ERb pages, Ruby blocks and
# directory listings.
#
# WEBrick also includes tools for daemonizing a process and starting a process
# at a higher privilege level and dropping permissions.
#
# == Starting an HTTP server
#
# To create a new WEBrick::HTTPServer that will listen to connections on port
# 8000 and serve documents from the current user's public_html folder:
#
# require 'webrick'
#
# root = File.expand_path '~/public_html'
# server = WEBrick::HTTPServer.new :Port => 8000, :DocumentRoot => root
#
# To run the server you will need to provide a suitable shutdown hook as
# starting the server blocks the current thread:
#
# trap 'INT' do server.shutdown end
#
# server.start
#
# == Custom Behavior
#
# The easiest way to have a server perform custom operations is through
# WEBrick::HTTPServer#mount_proc. The block given will be called with a
# WEBrick::HTTPRequest with request info and a WEBrick::HTTPResponse which
# must be filled in appropriately:
#
# server.mount_proc '/' do |req, res|
# res.body = 'Hello, world!'
# end
#
# Remember that +server.mount_proc+ must precede +server.start+.
#
# == Servlets
#
# Advanced custom behavior can be obtained through mounting a subclass of
# WEBrick::HTTPServlet::AbstractServlet. Servlets provide more modularity
# when writing an HTTP server than mount_proc allows. Here is a simple
# servlet:
#
# class Simple < WEBrick::HTTPServlet::AbstractServlet
# def do_GET request, response
# status, content_type, body = do_stuff_with request
#
# response.status = 200
# response['Content-Type'] = 'text/plain'
# response.body = 'Hello, World!'
# end
# end
#
# To initialize the servlet you mount it on the server:
#
# server.mount '/simple', Simple
#
# See WEBrick::HTTPServlet::AbstractServlet for more details.
#
# == Virtual Hosts
#
# A server can act as a virtual host for multiple host names. After creating
# the listening host, additional hosts that do not listen can be created and
# attached as virtual hosts:
#
# server = WEBrick::HTTPServer.new # ...
#
# vhost = WEBrick::HTTPServer.new :ServerName => 'vhost.example',
# :DoNotListen => true, # ...
# vhost.mount '/', ...
#
# server.virtual_host vhost
#
# If no +:DocumentRoot+ is provided and no servlets or procs are mounted on the
# main server it will return 404 for all URLs.
#
# == HTTPS
#
# To create an HTTPS server you only need to enable SSL and provide an SSL
# certificate name:
#
# require 'webrick'
# require 'webrick/https'
#
# cert_name = [
# %w[CN localhost],
# ]
#
# server = WEBrick::HTTPServer.new(:Port => 8000,
# :SSLEnable => true,
# :SSLCertName => cert_name)
#
# This will start the server with a self-generated self-signed certificate.
# The certificate will be changed every time the server is restarted.
#
# To create a server with a pre-determined key and certificate you can provide
# them:
#
# require 'webrick'
# require 'webrick/https'
# require 'openssl'
#
# cert = OpenSSL::X509::Certificate.new File.read '/path/to/cert.pem'
# pkey = OpenSSL::PKey::RSA.new File.read '/path/to/pkey.pem'
#
# server = WEBrick::HTTPServer.new(:Port => 8000,
# :SSLEnable => true,
# :SSLCertificate => cert,
# :SSLPrivateKey => pkey)
#
# == Proxy Server
#
# WEBrick can act as a proxy server:
#
# require 'webrick'
# require 'webrick/httpproxy'
#
# proxy = WEBrick::HTTPProxyServer.new :Port => 8000
#
# trap 'INT' do proxy.shutdown end
#
# See WEBrick::HTTPProxy for further details including modifying proxied
# responses.
#
# == Basic and Digest authentication
#
# WEBrick provides both Basic and Digest authentication for regular and proxy
# servers. See WEBrick::HTTPAuth, WEBrick::HTTPAuth::BasicAuth and
# WEBrick::HTTPAuth::DigestAuth.
#
# == WEBrick as a Production Web Server
#
# WEBrick can be run as a production server for small loads.
#
# === Daemonizing
#
# To start a WEBrick server as a daemon simple run WEBrick::Daemon.start
# before starting the server.
#
# === Dropping Permissions
#
# WEBrick can be started as one user to gain permission to bind to port 80 or
# 443 for serving HTTP or HTTPS traffic then can drop these permissions for
# regular operation. To listen on all interfaces for HTTP traffic:
#
# sockets = WEBrick::Utils.create_listeners nil, 80
#
# Then drop privileges:
#
# WEBrick::Utils.su 'www'
#
# Then create a server that does not listen by default:
#
# server = WEBrick::HTTPServer.new :DoNotListen => true, # ...
#
# Then overwrite the listening sockets with the port 80 sockets:
#
# server.listeners.replace sockets
#
# === Logging
#
# WEBrick can separately log server operations and end-user access. For
# server operations:
#
# log_file = File.open '/var/log/webrick.log', 'a+'
# log = WEBrick::Log.new log_file
#
# For user access logging:
#
# access_log = [
# [log_file, WEBrick::AccessLog::COMBINED_LOG_FORMAT],
# ]
#
# server = WEBrick::HTTPServer.new :Logger => log, :AccessLog => access_log
#
# See WEBrick::AccessLog for further log formats.
#
# === Log Rotation
#
# To rotate logs in WEBrick on a HUP signal (like syslogd can send), open the
# log file in 'a+' mode (as above) and trap 'HUP' to reopen the log file:
#
# trap 'HUP' do log_file.reopen '/path/to/webrick.log', 'a+'
#
# == Copyright
#
# 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 $
module WEBrick
end
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 | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/open-uri.rb | lib/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
# Allows the opening of various resources including URIs.
#
# If the first argument responds to the 'open' method, 'open' is called on
# it with the rest of the arguments.
#
# If the first argument is a string that begins with xxx://, it is parsed by
# URI.parse. If the parsed object responds to the 'open' method,
# 'open' is called on it with the rest of the arguments.
#
# Otherwise, the original Kernel#open is called.
#
# OpenURI::OpenRead#open provides URI::HTTP#open, URI::HTTPS#open and
# URI::FTP#open, Kernel#open.
#
# We can accept URIs and strings that begin with http://, https:// and
# ftp://. In these cases, the opened file object is extended by OpenURI::Meta.
def open(name, *rest, &block) # :doc:
if name.respond_to?(:open)
name.open(*rest, &block)
elsif name.respond_to?(:to_str) &&
%r{\A[A-Za-z][A-Za-z0-9+\-\.]*://} =~ name &&
(uri = URI.parse(name)).respond_to?(:open)
uri.open(*rest, &block)
else
open_uri_original_open(name, *rest, &block)
end
end
module_function :open
end
# OpenURI is an easy-to-use wrapper for Net::HTTP, Net::HTTPS and Net::FTP.
#
# == Example
#
# It is possible to open an http, https or ftp URL as though it were a file:
#
# open("http://www.ruby-lang.org/") {|f|
# f.each_line {|line| p line}
# }
#
# The opened file has several getter methods for its meta-information, as
# follows, since it is extended by OpenURI::Meta.
#
# open("http://www.ruby-lang.org/en") {|f|
# f.each_line {|line| p line}
# p f.base_uri # <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. Here we disable proxy:
#
# open("http://www.ruby-lang.org/en/", :proxy => nil) {|f|
# # ...
# }
#
# See OpenURI::OpenRead.open and Kernel#open for more on available options.
#
# URI objects can be opened in a similar way.
#
# uri = URI.parse("http://www.ruby-lang.org/en/")
# uri.open {|f|
# # ...
# }
#
# URI objects can be read directly. The returned string is also extended by
# OpenURI::Meta.
#
# str = uri.read
# p str.base_uri
#
# Author:: Tanaka Akira <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, _, rest = OpenURI.scan_open_optional_arguments(*rest)
options = rest.shift if !rest.empty? && Hash === rest.first
raise ArgumentError.new("extra arguments") if !rest.empty?
options ||= {}
OpenURI.check_options(options)
if /\Arb?(?:\Z|:([^:]+))/ =~ mode
encoding, = $1,Encoding.find($1) if $1
mode = nil
end
unless mode == nil ||
mode == 'r' || mode == 'rb' ||
mode == File::RDONLY
raise ArgumentError.new("invalid access mode #{mode} (#{uri.class} resource is read only.)")
end
io = open_loop(uri, options)
io.set_encoding(encoding) if encoding
if block_given?
begin
yield io
ensure
if io.respond_to? :close!
io.close! # Tempfile
else
io.close
end
end
else
io
end
end
def OpenURI.open_loop(uri, options) # :nodoc:
proxy_opts = []
proxy_opts << :proxy_http_basic_authentication if options.include? :proxy_http_basic_authentication
proxy_opts << :proxy if options.include? :proxy
proxy_opts.compact!
if 1 < proxy_opts.length
raise ArgumentError, "multiple proxy options specified"
end
case proxy_opts.first
when :proxy_http_basic_authentication
opt_proxy, proxy_user, proxy_pass = options.fetch(:proxy_http_basic_authentication)
proxy_user = proxy_user.to_str
proxy_pass = proxy_pass.to_str
if opt_proxy == true
raise ArgumentError.new("Invalid authenticated proxy option: #{options[:proxy_http_basic_authentication].inspect}")
end
when :proxy
opt_proxy = options.fetch(:proxy)
proxy_user = nil
proxy_pass = nil
when nil
opt_proxy = true
proxy_user = nil
proxy_pass = nil
end
case opt_proxy
when true
find_proxy = lambda {|u| pxy = u.find_proxy; pxy ? [pxy, nil, nil] : nil}
when nil, false
find_proxy = lambda {|u| nil}
when String
opt_proxy = URI.parse(opt_proxy)
find_proxy = lambda {|u| [opt_proxy, proxy_user, proxy_pass]}
when URI::Generic
find_proxy = lambda {|u| [opt_proxy, proxy_user, proxy_pass]}
else
raise ArgumentError.new("Invalid proxy option: #{opt_proxy}")
end
uri_set = {}
buf = nil
while true
redirect = catch(:open_uri_redirect) {
buf = Buffer.new
uri.buffer_open(buf, find_proxy.call(uri), options)
nil
}
if redirect
if redirect.relative?
# Although it violates RFC2616, Location: field may have relative
# URI. It is converted to absolute URI using uri as a base URI.
redirect = uri + redirect
end
if !options.fetch(:redirect, true)
raise HTTPRedirect.new(buf.io.status.join(' '), buf.io, redirect)
end
unless OpenURI.redirectable?(uri, redirect)
raise "redirection forbidden: #{uri} -> #{redirect}"
end
if options.include? :http_basic_authentication
# send authentication only for the URI directly specified.
options = options.dup
options.delete :http_basic_authentication
end
uri = redirect
raise "HTTP redirection loop: #{uri}" if uri_set.include? uri.to_s
uri_set[uri.to_s] = true
else
break
end
end
io = buf.io
io.base_uri = uri
io
end
def OpenURI.redirectable?(uri1, uri2) # :nodoc:
# This test is intended to forbid a redirection from http://... to
# file:///etc/passwd, file:///dev/zero, etc. CVE-2011-1521
# https to http redirect is also forbidden intentionally.
# It avoids sending secure cookie or referer by non-secure HTTP protocol.
# (RFC 2109 4.3.1, RFC 2965 3.3, RFC 2616 15.1.3)
# However this is ad hoc. It should be extensible/configurable.
uri1.scheme.downcase == uri2.scheme.downcase ||
(/\A(?:http|ftp)\z/i =~ uri1.scheme && /\A(?:http|ftp)\z/i =~ uri2.scheme)
end
def OpenURI.open_http(buf, target, proxy, options) # :nodoc:
if proxy
proxy_uri, proxy_user, proxy_pass = proxy
raise "Non-HTTP proxy URI: #{proxy_uri}" if proxy_uri.class != URI::HTTP
end
if target.userinfo && "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.hostname, proxy_uri.port, proxy_user, proxy_pass)
else
klass = Net::HTTP::Proxy(proxy_uri.hostname, proxy_uri.port)
end
end
target_host = target.hostname
target_port = target.port
request_uri = target.request_uri
else
# FTP over HTTP proxy
target_host = proxy_uri.hostname
target_port = proxy_uri.port
request_uri = target.to_s
if proxy_user && proxy_pass
header["Proxy-Authorization"] = 'Basic ' + ["#{proxy_user}:#{proxy_pass}"].pack('m').delete("\r\n")
end
end
http = proxy ? klass.new(target_host, target_port) : klass.new(target_host, target_port, nil)
if target.class == URI::HTTPS
require 'net/https'
http.use_ssl = true
http.verify_mode = options[:ssl_verify_mode] || OpenSSL::SSL::VERIFY_PEER
store = OpenSSL::X509::Store.new
if options[:ssl_ca_cert]
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 {|name| buf.io.meta_add_field2 name, resp.get_fields(name) }
case resp
when Net::HTTPSuccess
when Net::HTTPMovedPermanently, # 301
Net::HTTPFound, # 302
Net::HTTPSeeOther, # 303
Net::HTTPTemporaryRedirect # 307
begin
loc_uri = URI.parse(resp['location'])
rescue URI::InvalidURIError
raise OpenURI::HTTPError.new(io.status.join(' ') + ' (Invalid Location URI)', io)
end
throw :open_uri_redirect, loc_uri
else
raise OpenURI::HTTPError.new(io.status.join(' '), io)
end
end
class HTTPError < StandardError
def initialize(message, io)
super(message)
@io = io
end
attr_reader :io
end
# Raised on redirection,
# only occurs when +redirect+ option for HTTP is +false+.
class HTTPRedirect < HTTPError
def initialize(message, io, uri)
super(message, io)
@uri = uri
end
attr_reader :uri
end
class Buffer # :nodoc: all
def initialize
@io = StringIO.new
@size = 0
end
attr_reader :size
StringMax = 10240
def <<(str)
@io << str
@size += str.length
if StringIO === @io && StringMax < @size
require 'tempfile'
io = Tempfile.new('open-uri')
io.binmode
Meta.init io, @io if Meta === @io
io << @io.string
@io = io
end
end
def io
Meta.init @io unless Meta === @io
@io
end
end
# Mixin for holding meta-information.
module Meta
def Meta.init(obj, src=nil) # :nodoc:
obj.extend Meta
obj.instance_eval {
@base_uri = nil
@meta = {} # name to string. legacy.
@metas = {} # name to array of strings.
}
if src
obj.status = src.status
obj.base_uri = src.base_uri
src.metas.each {|name, values|
obj.meta_add_field2(name, values)
}
end
end
# returns an Array that consists of status code and message.
attr_accessor :status
# returns a URI that is the base of relative URIs in the data.
# It may differ from the URI supplied by a user due to redirection.
attr_accessor :base_uri
# returns a Hash that represents header fields.
# The Hash keys are downcased for canonicalization.
# The Hash values are a field body.
# If there are multiple field with same field name,
# the field values are concatenated with a comma.
attr_reader :meta
# returns a Hash that represents header fields.
# The Hash keys are downcased for canonicalization.
# The Hash value are an array of field values.
attr_reader :metas
def meta_setup_encoding # :nodoc:
charset = self.charset
enc = nil
if charset
begin
enc = Encoding.find(charset)
rescue ArgumentError
end
end
enc = Encoding::ASCII_8BIT unless enc
if self.respond_to? :force_encoding
self.force_encoding(enc)
elsif self.respond_to? :string
self.string.force_encoding(enc)
else # Tempfile
self.set_encoding enc
end
end
def meta_add_field2(name, values) # :nodoc:
name = name.downcase
@metas[name] = values
@meta[name] = values.join(', ')
meta_setup_encoding if name == 'content-type'
end
def meta_add_field(name, value) # :nodoc:
meta_add_field2(name, [value])
end
# returns a Time that represents the Last-Modified field.
def last_modified
if vs = @metas['last-modified']
v = vs.join(', ')
Time.httpdate(v)
else
nil
end
end
# :stopdoc:
RE_LWS = /[\r\n\t ]+/n
RE_TOKEN = %r{[^\x00- ()<>@,;:\\"/\[\]?={}\x7f]+}n
RE_QUOTED_STRING = %r{"(?:[\r\n\t !#-\[\]-~\x80-\xff]|\\[\x00-\x7f])*"}n
RE_PARAMETERS = %r{(?:;#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?=#{RE_LWS}?(?:#{RE_TOKEN}|#{RE_QUOTED_STRING})#{RE_LWS}?)*}n
# :startdoc:
def content_type_parse # :nodoc:
vs = @metas['content-type']
# The last (?:;#{RE_LWS}?)? matches extra ";" which violates RFC2045.
if vs && %r{\A#{RE_LWS}?(#{RE_TOKEN})#{RE_LWS}?/(#{RE_TOKEN})#{RE_LWS}?(#{RE_PARAMETERS})(?:;#{RE_LWS}?)?\z}no =~ vs.join(', ')
type = $1.downcase
subtype = $2.downcase
parameters = []
$3.scan(/;#{RE_LWS}?(#{RE_TOKEN})#{RE_LWS}?=#{RE_LWS}?(?:(#{RE_TOKEN})|(#{RE_QUOTED_STRING}))/no) {|att, val, qval|
if qval
val = qval[1...-1].gsub(/[\r\n\t !#-\[\]-~\x80-\xff]+|(\\[\x00-\x7f])/n) { $1 ? $1[1,1] : $& }
end
parameters << [att.downcase, val]
}
["#{type}/#{subtype}", *parameters]
else
nil
end
end
# returns "type/subtype" which is MIME Content-Type.
# It is downcased for canonicalization.
# Content-Type parameters are stripped.
def content_type
type, *_ = content_type_parse
type || 'application/octet-stream'
end
# returns a charset parameter in Content-Type field.
# It is downcased for canonicalization.
#
# If charset parameter is not given but a block is given,
# the block is called and its result is returned.
# It can be used to guess charset.
#
# If charset parameter and block is not given,
# nil is returned except text type in HTTP.
# In that case, "iso-8859-1" is returned as defined by RFC2616 3.7.1.
def charset
type, *parameters = content_type_parse
if pair = parameters.assoc('charset')
pair.last.downcase
elsif block_given?
yield
elsif type && %r{\Atext/} =~ type &&
@base_uri && /\Ahttp\z/i =~ @base_uri.scheme
"iso-8859-1" # RFC2616 3.7.1
else
nil
end
end
# Returns a list of encodings in Content-Encoding field as an array of
# strings.
#
# The encodings are downcased for canonicalization.
def content_encoding
vs = @metas['content-encoding']
if vs && %r{\A#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?(?:,#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?)*}o =~ (v = vs.join(', '))
v.scan(RE_TOKEN).map {|content_coding| content_coding.downcase}
else
[]
end
end
end
# Mixin for HTTP and FTP URIs.
module OpenRead
# OpenURI::OpenRead#open provides `open' for URI::HTTP and URI::FTP.
#
# OpenURI::OpenRead#open takes optional 3 arguments as:
#
# OpenURI::OpenRead#open([mode [, perm]] [, options]) [{|io| ... }]
#
# OpenURI::OpenRead#open returns an IO-like object if block is not given.
# Otherwise it yields the IO object and return the value of the block.
# The IO object is extended with OpenURI::Meta.
#
# +mode+ and +perm+ are the same as Kernel#open.
#
# However, +mode+ must be read mode because OpenURI::OpenRead#open doesn't
# support write mode (yet).
# Also +perm+ is ignored because it is meaningful only for file creation.
#
# +options+ must be a hash.
#
# Each option with a string key specifies an extra header field for HTTP.
# I.e., it is ignored for FTP without HTTP proxy.
#
# The hash may include other options, where keys are symbols:
#
# [:proxy]
# Synopsis:
# :proxy => "http://proxy.foo.com:8000/"
# :proxy => URI.parse("http://proxy.foo.com:8000/")
# :proxy => true
# :proxy => false
# :proxy => nil
#
# If :proxy option is specified, the value should be String, URI,
# boolean or nil.
#
# When String or URI is given, it is treated as proxy URI.
#
# When true is given or the option itself is not specified,
# environment variable `scheme_proxy' is examined.
# `scheme' is replaced by `http', `https' or `ftp'.
#
# When false or nil is given, the environment variables are ignored and
# connection will be made to a server directly.
#
# [:proxy_http_basic_authentication]
# Synopsis:
# :proxy_http_basic_authentication =>
# ["http://proxy.foo.com:8000/", "proxy-user", "proxy-password"]
# :proxy_http_basic_authentication =>
# [URI.parse("http://proxy.foo.com:8000/"),
# "proxy-user", "proxy-password"]
#
# If :proxy option is specified, the value should be an Array with 3
# elements. It should contain a proxy URI, a proxy user name and a proxy
# password. The proxy URI should be a String, an URI or nil. The proxy
# user name and password should be a String.
#
# If nil is given for the proxy URI, this option is just ignored.
#
# If :proxy and :proxy_http_basic_authentication is specified,
# ArgumentError is raised.
#
# [:http_basic_authentication]
# Synopsis:
# :http_basic_authentication=>[user, password]
#
# If :http_basic_authentication is specified,
# the value should be an array which contains 2 strings:
# username and password.
# It is used for HTTP Basic authentication defined by RFC 2617.
#
# [:content_length_proc]
# Synopsis:
# :content_length_proc => lambda {|content_length| ... }
#
# If :content_length_proc option is specified, the option value procedure
# is called before actual transfer is started.
# It takes one argument, which is expected content length in bytes.
#
# If two or more transfer is done by HTTP redirection, the procedure
# is called only one for a last transfer.
#
# When expected content length is unknown, the procedure is called with
# nil. This happens when the HTTP response has no Content-Length header.
#
# [:progress_proc]
# Synopsis:
# :progress_proc => lambda {|size| ...}
#
# If :progress_proc option is specified, the proc is called with one
# argument each time when `open' gets content fragment from network.
# The argument +size+ is the accumulated transferred size in bytes.
#
# If two or more transfer is done by HTTP redirection, the procedure
# is called only one for a last transfer.
#
# :progress_proc and :content_length_proc are intended to be used for
# progress bar.
# For example, it can be implemented as follows using Ruby/ProgressBar.
#
# pbar = nil
# open("http://...",
# :content_length_proc => lambda {|t|
# if t && 0 < t
# pbar = ProgressBar.new("...", t)
# pbar.file_transfer_mode
# end
# },
# :progress_proc => lambda {|s|
# pbar.set s if pbar
# }) {|f| ... }
#
# [:read_timeout]
# Synopsis:
# :read_timeout=>nil (no timeout)
# :read_timeout=>10 (10 second)
#
# :read_timeout option specifies a timeout of read for http connections.
#
# [: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.
#
# [:ftp_active_mode]
# Synopsis:
# :ftp_active_mode=>bool
#
# <tt>:ftp_active_mode => true</tt> is used to make ftp active mode.
# Ruby 1.9 uses passive mode by default.
# Note that the active mode is default in Ruby 1.8 or prior.
#
# [:redirect]
# Synopsis:
# :redirect=>bool
#
# +:redirect+ is true by default. <tt>:redirect => false</tt> is used to
# disable all HTTP redirects.
#
# OpenURI::HTTPRedirect exception raised on redirection.
# Using +true+ also means that redirections between http and ftp are
# permitted.
#
def open(*rest, &block)
OpenURI.open_uri(self, *rest, &block)
end
# OpenURI::OpenRead#read([options]) reads a content referenced by self and
# returns the content as string.
# The string is extended with OpenURI::Meta.
# The argument +options+ is same as OpenURI::OpenRead#open.
def read(options={})
self.open(options) {|f|
str = f.read
Meta.init str, f
str
}
end
end
end
module URI
class HTTP
def buffer_open(buf, proxy, options) # :nodoc:
OpenURI.open_http(buf, self, proxy, options)
end
include OpenURI::OpenRead
end
class FTP
def buffer_open(buf, proxy, options) # :nodoc:
if proxy
OpenURI.open_http(buf, self, proxy, options)
return
end
require 'net/ftp'
path = self.path
path = path.sub(%r{\A/}, '%2F') # re-encode the beginning slash because uri library decodes it.
directories = path.split(%r{/}, -1)
directories.each {|d|
d.gsub!(/%([0-9A-Fa-f][0-9A-Fa-f])/) { [$1].pack("H2") }
}
unless filename = directories.pop
raise ArgumentError, "no filename: #{self.inspect}"
end
directories.each {|d|
if /[\r\n]/ =~ d
raise ArgumentError, "invalid directory: #{d.inspect}"
end
}
if /[\r\n]/ =~ filename
raise ArgumentError, "invalid filename: #{filename.inspect}"
end
typecode = self.typecode
if typecode && /\A[aid]\z/ !~ typecode
raise ArgumentError, "invalid typecode: #{typecode.inspect}"
end
# The access sequence is defined by RFC 1738
ftp = Net::FTP.new
ftp.connect(self.hostname, self.port)
ftp.passive = true if !options[:ftp_active_mode]
# todo: extract user/passwd from .netrc.
user = 'anonymous'
passwd = nil
user, passwd = self.userinfo.split(/:/) if self.userinfo
ftp.login(user, passwd)
directories.each {|cwd|
ftp.voidcmd("CWD #{cwd}")
}
if typecode
# xxx: typecode D is not handled.
ftp.voidcmd("TYPE #{typecode.upcase}")
end
if options[:content_length_proc]
options[:content_length_proc].call(ftp.size(filename))
end
ftp.retrbinary("RETR #{filename}", 4096) { |str|
buf << str
options[:progress_proc].call(buf.size) if options[:progress_proc]
}
ftp.close
buf.io.rewind
end
include OpenURI::OpenRead
end
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/getoptlong.rb | lib/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|
if !arg.is_a?(Array)
raise ArgumentError, "the option list contains non-Array argument"
end
#
# Find an argument flag and it set to `argument_flag'.
#
argument_flag = nil
arg.each do |i|
if ARGUMENT_FLAGS.include?(i)
if argument_flag != nil
raise ArgumentError, "too many argument-flags"
end
argument_flag = i
end
end
raise ArgumentError, "no argument-flag" if argument_flag == nil
canonical_name = nil
arg.each do |i|
#
# Check an option name.
#
next if i == argument_flag
begin
if !i.is_a?(String) || i !~ /^-([^-]|-.+)$/
raise ArgumentError, "an invalid option `#{i}'"
end
if (@canonical_names.include?(i))
raise ArgumentError, "option redefined `#{i}'"
end
rescue
@canonical_names.clear
@argument_flags.clear
raise
end
#
# Register the option (`i') to the `@canonical_names' and
# `@canonical_names' Hashes.
#
if canonical_name == nil
canonical_name = i
end
@canonical_names[i] = canonical_name
@argument_flags[i] = argument_flag
end
raise ArgumentError, "no option name" if canonical_name == nil
end
return self
end
#
# Set/Unset `quiet' mode.
#
attr_writer :quiet
#
# Return the flag of `quiet' mode.
#
attr_reader :quiet
#
# `quiet?' is an alias of `quiet'.
#
alias quiet? quiet
#
# Explicitly terminate option processing.
#
def terminate
return nil if @status == STATUS_TERMINATED
raise RuntimeError, "an error has occurred" if @error != nil
@status = STATUS_TERMINATED
@non_option_arguments.reverse_each do |argument|
ARGV.unshift(argument)
end
@canonical_names = nil
@argument_flags = nil
@rest_singles = nil
@non_option_arguments = nil
return self
end
#
# Returns true if option processing has terminated, false otherwise.
#
def terminated?
return @status == STATUS_TERMINATED
end
#
# Set an error (a protected method).
#
def set_error(type, message)
$stderr.print("#{$0}: #{message}\n") if !@quiet
@error = type
@error_message = message
@canonical_names = nil
@argument_flags = nil
@rest_singles = nil
@non_option_arguments = nil
raise type, message
end
protected :set_error
#
# Examine whether an option processing is failed.
#
attr_reader :error
#
# `error?' is an alias of `error'.
#
alias error? error
# Return the appropriate error message in POSIX-defined format.
# If no error has occurred, returns nil.
#
def error_message
return @error_message
end
#
# Get next option name and its argument, as an Array of two elements.
#
# The option name is always converted to the first (preferred)
# name given in the original options to GetoptLong.new.
#
# Example: ['--option', 'value']
#
# Returns nil if the processing is complete (as determined by
# STATUS_TERMINATED).
#
def get
option_name, option_argument = nil, ''
#
# Check status.
#
return nil if @error != nil
case @status
when STATUS_YET
@status = STATUS_STARTED
when STATUS_TERMINATED
return nil
end
#
# Get next option argument.
#
if 0 < @rest_singles.length
argument = '-' + @rest_singles
elsif (ARGV.length == 0)
terminate
return nil
elsif @ordering == PERMUTE
while 0 < ARGV.length && ARGV[0] !~ /^-./
@non_option_arguments.push(ARGV.shift)
end
if ARGV.length == 0
terminate
return nil
end
argument = ARGV.shift
elsif @ordering == REQUIRE_ORDER
if (ARGV[0] !~ /^-./)
terminate
return nil
end
argument = ARGV.shift
else
argument = ARGV.shift
end
#
# Check the special argument `--'.
# `--' indicates the end of the option list.
#
if argument == '--' && @rest_singles.length == 0
terminate
return nil
end
#
# Check for long and short options.
#
if argument =~ /^(--[^=]+)/ && @rest_singles.length == 0
#
# This is a long style option, which start with `--'.
#
pattern = $1
if @canonical_names.include?(pattern)
option_name = pattern
else
#
# The option `option_name' is not registered in `@canonical_names'.
# It may be an abbreviated.
#
matches = []
@canonical_names.each_key do |key|
if key.index(pattern) == 0
option_name = key
matches << key
end
end
if 2 <= matches.length
set_error(AmbiguousOption, "option `#{argument}' is ambiguous between #{matches.join(', ')}")
elsif matches.length == 0
set_error(InvalidOption, "unrecognized option `#{argument}'")
end
end
#
# Check an argument to the option.
#
if @argument_flags[option_name] == REQUIRED_ARGUMENT
if argument =~ /=(.*)$/
option_argument = $1
elsif 0 < ARGV.length
option_argument = ARGV.shift
else
set_error(MissingArgument,
"option `#{argument}' requires an argument")
end
elsif @argument_flags[option_name] == OPTIONAL_ARGUMENT
if argument =~ /=(.*)$/
option_argument = $1
elsif 0 < ARGV.length && ARGV[0] !~ /^-./
option_argument = ARGV.shift
else
option_argument = ''
end
elsif argument =~ /=(.*)$/
set_error(NeedlessArgument,
"option `#{option_name}' doesn't allow an argument")
end
elsif argument =~ /^(-(.))(.*)/
#
# This is a short style option, which start with `-' (not `--').
# Short options may be catenated (e.g. `-l -g' is equivalent to
# `-lg').
#
option_name, ch, @rest_singles = $1, $2, $3
if @canonical_names.include?(option_name)
#
# The option `option_name' is found in `@canonical_names'.
# Check its argument.
#
if @argument_flags[option_name] == REQUIRED_ARGUMENT
if 0 < @rest_singles.length
option_argument = @rest_singles
@rest_singles = ''
elsif 0 < ARGV.length
option_argument = ARGV.shift
else
# 1003.2 specifies the format of this message.
set_error(MissingArgument, "option requires an argument -- #{ch}")
end
elsif @argument_flags[option_name] == OPTIONAL_ARGUMENT
if 0 < @rest_singles.length
option_argument = @rest_singles
@rest_singles = ''
elsif 0 < ARGV.length && ARGV[0] !~ /^-./
option_argument = ARGV.shift
else
option_argument = ''
end
end
else
#
# This is an invalid option.
# 1003.2 specifies the format of this message.
#
if ENV.include?('POSIXLY_CORRECT')
set_error(InvalidOption, "invalid option -- #{ch}")
else
set_error(InvalidOption, "invalid option -- #{ch}")
end
end
else
#
# This is a non-option argument.
# Only RETURN_IN_ORDER falled into here.
#
return '', argument
end
return @canonical_names[option_name], option_argument
end
#
# `get_option' is an alias of `get'.
#
alias get_option get
# Iterator version of `get'.
#
# The block is called repeatedly with two arguments:
# The first is the option name.
# The second is the argument which followed it (if any).
# Example: ('--opt', 'value')
#
# The option name is always converted to the first (preferred)
# name given in the original options to GetoptLong.new.
#
def each
loop do
option_name, option_argument = get_option
break if option_name == nil
yield option_name, option_argument
end
end
#
# `each_option' is an alias of `each'.
#
alias each_option each
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/tkafter.rb | lib/tkafter.rb | #
# tkafter.rb - load tk/after.rb
#
require 'tk/timer'
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/securerandom.rb | lib/securerandom.rb | begin
require 'openssl'
rescue LoadError
end
# == 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
#
# === Examples
#
# Hexadecimal string.
#
# p SecureRandom.hex(10) #=> "52750b30ffbc7de3b362"
# p SecureRandom.hex(10) #=> "92b15d6c8dc4beb5f559"
# p SecureRandom.hex(13) #=> "39b290146bea6ce975c37cfc23"
#
# Base64 string.
#
# p SecureRandom.base64(10) #=> "EcmTPZwWRAozdA=="
# p SecureRandom.base64(10) #=> "KO1nIU+p9DKxGg=="
# p SecureRandom.base64(12) #=> "7kJSM/MzBJI+75j8"
#
# Binary string.
#
# p SecureRandom.random_bytes(10) #=> "\016\t{\370g\310pbr\301"
# p SecureRandom.random_bytes(10) #=> "\323U\030TO\234\357\020\a\337"
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 or is nil, 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 = n ? n.to_int : 16
if defined? OpenSSL::Random
@pid = 0 unless defined?(@pid)
pid = $$
unless @pid == pid
now = Process.clock_gettime(Process::CLOCK_REALTIME, :nanosecond)
ary = [now, @pid, pid]
OpenSSL::Random.random_add(ary.join("").to_s, 0.0)
@pid = pid
end
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
begin
File.open("/dev/urandom", flags) {|f|
unless f.stat.chardev?
raise Errno::ENOENT
end
@has_urandom = true
ret = f.read(n)
unless ret.length == n
raise NotImplementedError, "Unexpected partial read from random device: only #{ret.length} for #{n} bytes"
end
return ret
}
rescue Errno::ENOENT
@has_urandom = false
end
end
unless defined?(@has_win32)
begin
require 'Win32API'
crypt_acquire_context = Win32API.new("advapi32", "CryptAcquireContext", 'PPPII', 'L')
@crypt_gen_random = Win32API.new("advapi32", "CryptGenRandom", 'VIP', 'L')
hProvStr = " " * DL::SIZEOF_VOIDP
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
type = DL::SIZEOF_VOIDP == DL::SIZEOF_LONG_LONG ? 'q' : 'l'
@hProv, = hProvStr.unpack(type)
@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 hexadecimal string.
#
# The argument _n_ specifies the length, in bytes, of the random number to be generated.
# The length of the resulting hexadecimal string is twice _n_.
#
# If _n_ is not specified or is nil, 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, in bytes, of the random number
# to be generated. The length of the result string is about 4/3 of _n_.
#
# If _n_ is not specified or is nil, 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 the definition of 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, in bytes, of the random number
# to be generated. The length of the result string is about 4/3 of _n_.
#
# If _n_ is not specified or is nil, 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 the definition of URL-safe base64.
def self.urlsafe_base64(n=nil, padding=false)
s = [random_bytes(n)].pack("m*")
s.delete!("\n")
s.tr!("+/", "-_")
s.delete!("=") unless padding
s
end
# SecureRandom.random_number generates a random number.
#
# If a 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 a 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].force_encoding("filesystem").tr("\r", '').chomp
end
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/tkpalette.rb | lib/tkpalette.rb | #
# tkpalette.rb - load tk/palette.rb
#
require 'tk/palette'
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/dl.rb | lib/dl.rb | require 'dl.so'
begin
require 'fiddle' unless Object.const_defined?(:Fiddle)
rescue LoadError
end
warn "DL is deprecated, please use Fiddle"
module DL
# Returns true if DL is using Fiddle, the libffi wrapper.
def self.fiddle?
Object.const_defined?(:Fiddle)
end
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/weakref.rb | lib/weakref.rb | require "delegate"
# Weak Reference class that allows a referenced object to be
# garbage-collected.
#
# A WeakRef may be used exactly like the object it references.
#
# Usage:
#
# foo = Object.new # create a new object instance
# p foo.to_s # original's class
# foo = WeakRef.new(foo) # reassign foo with WeakRef instance
# p foo.to_s # should be same class
# GC.start # start the garbage collector
# p foo.to_s # should raise exception (recycled)
#
# == Example
#
# With help from WeakRef, we can implement our own rudimentary WeakHash class.
#
# We will call it WeakHash, since it's really just a Hash except all of it's
# keys and values can be garbage collected.
#
# require 'weakref'
#
# class WeakHash < Hash
# def []= key, obj
# super WeakRef.new(key), WeakRef.new(obj)
# end
# end
#
# This is just a simple implementation, we've opened the Hash class and changed
# Hash#store to create a new WeakRef object with +key+ and +obj+ parameters
# before passing them as our key-value pair to the hash.
#
# With this you will have to limit your self to String keys, otherwise you
# will get an ArgumentError because WeakRef cannot create a finalizer for a
# Symbol. Symbols are immutable and cannot be garbage collected.
#
# Let's see it in action:
#
# omg = "lol"
# c = WeakHash.new
# c['foo'] = "bar"
# c['baz'] = Object.new
# c['qux'] = omg
# puts c.inspect
# #=> {"foo"=>"bar", "baz"=>#<Object:0x007f4ddfc6cb48>, "qux"=>"lol"}
#
# # Now run the garbage collector
# GC.start
# c['foo'] #=> nil
# c['baz'] #=> nil
# c['qux'] #=> nil
# omg #=> "lol"
#
# puts c.inspect
# #=> WeakRef::RefError: Invalid Reference - probably recycled
#
# You can see the local variable +omg+ stayed, although its reference in our
# hash object was garbage collected, along with the rest of the keys and
# values. Also, when we tried to inspect our hash, we got a WeakRef::RefError.
# This is because these objects were also garbage collected.
class WeakRef < Delegator
##
# RefError is raised when a referenced object has been recycled by the
# garbage collector
class RefError < StandardError
end
@@__map = ::ObjectSpace::WeakMap.new
##
# Creates a weak reference to +orig+
#
# Raises an ArgumentError if the given +orig+ is immutable, such as Symbol,
# Fixnum, or Float.
def initialize(orig)
case orig
when true, false, nil
@delegate_sd_obj = orig
else
@@__map[self] = orig
end
super
end
def __getobj__ # :nodoc:
@@__map[self] or defined?(@delegate_sd_obj) ? @delegate_sd_obj :
Kernel::raise(RefError, "Invalid Reference - probably recycled", Kernel::caller(2))
end
def __setobj__(obj) # :nodoc:
end
##
# Returns true if the referenced object is still alive.
def weakref_alive?
@@__map.key?(self) or defined?(@delegate_sd_obj)
end
end
if __FILE__ == $0
# require 'thread'
foo = Object.new
p foo.to_s # original's class
foo = WeakRef.new(foo)
p foo.to_s # should be same class
ObjectSpace.garbage_collect
ObjectSpace.garbage_collect
p foo.to_s # should raise exception (recycled)
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/optparse.rb | lib/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. See
# #make_switch for full documentation.
#
# === Minimal example
#
# require 'optparse'
#
# options = {}
# OptionParser.new do |opts|
# opts.banner = "Usage: example.rb [options]"
#
# opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
# options[:verbose] = v
# end
# end.parse!
#
# p options
# p ARGV
#
# === Complete example
#
# The following example is a complete Ruby program. You can run it and see the
# effect of specifying various options. This is probably the best way to learn
# the features of +optparse+.
#
# require 'optparse'
# require 'optparse/time'
# require 'ostruct'
# require 'pp'
#
# class OptparseExample
#
# CODES = %w[iso-2022-jp shift_jis euc-jp utf8 binary]
# CODE_ALIASES = { "jis" => "iso-2022-jp", "sjis" => "shift_jis" }
#
# #
# # Return a structure describing the options.
# #
# def self.parse(args)
# # The options specified on the command line will be collected in *options*.
# # We set default values here.
# options = OpenStruct.new
# options.library = []
# options.inplace = false
# options.encoding = "utf8"
# options.transfer_type = :auto
# options.verbose = false
#
# opt_parser = OptionParser.new do |opts|
# opts.banner = "Usage: example.rb [options]"
#
# opts.separator ""
# opts.separator "Specific options:"
#
# # Mandatory argument.
# opts.on("-r", "--require LIBRARY",
# "Require the LIBRARY before executing your script") do |lib|
# options.library << lib
# end
#
# # Optional argument; multi-line description.
# opts.on("-i", "--inplace [EXTENSION]",
# "Edit ARGV files in place",
# " (make backup if EXTENSION supplied)") do |ext|
# options.inplace = true
# options.extension = ext || ''
# options.extension.sub!(/\A\.?(?=.)/, ".") # Ensure extension begins with dot.
# end
#
# # Cast 'delay' argument to a Float.
# opts.on("--delay N", Float, "Delay N seconds before executing") do |n|
# options.delay = n
# end
#
# # Cast 'time' argument to a Time object.
# opts.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time|
# options.time = time
# end
#
# # Cast to octal integer.
# opts.on("-F", "--irs [OCTAL]", OptionParser::OctalInteger,
# "Specify record separator (default \\0)") do |rs|
# options.record_separator = rs
# end
#
# # List of arguments.
# opts.on("--list x,y,z", Array, "Example 'list' of arguments") do |list|
# options.list = list
# end
#
# # Keyword completion. We are specifying a specific set of arguments (CODES
# # and CODE_ALIASES - notice the latter is a Hash), and the user may provide
# # the shortest unambiguous text.
# code_list = (CODE_ALIASES.keys + CODES).join(',')
# opts.on("--code CODE", CODES, CODE_ALIASES, "Select encoding",
# " (#{code_list})") do |encoding|
# options.encoding = encoding
# end
#
# # Optional argument with keyword completion.
# opts.on("--type [TYPE]", [:text, :binary, :auto],
# "Select transfer type (text, binary, auto)") do |t|
# options.transfer_type = t
# end
#
# # Boolean switch.
# opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
# options.verbose = v
# end
#
# opts.separator ""
# opts.separator "Common options:"
#
# # No argument, shows at tail. This will print an options summary.
# # Try it and see!
# opts.on_tail("-h", "--help", "Show this message") do
# puts opts
# exit
# end
#
# # Another typical switch to print the version.
# opts.on_tail("--version", "Show version") do
# puts ::Version.join('.')
# exit
# end
# end
#
# opt_parser.parse!(args)
# options
# end # parse()
#
# end # class OptparseExample
#
# options = OptparseExample.parse(ARGV)
# pp options
# pp ARGV
#
# === Shell Completion
#
# For modern shells (e.g. bash, zsh, etc.), you can use shell
# completion for command line options.
#
# === Further documentation
#
# The above examples should be enough to learn how to use this class. If you
# have any questions, file a ticket at http://bugs.ruby-lang.org.
#
class OptionParser
# :stopdoc:
NoArgument = [NO_ARGUMENT = :NONE, nil].freeze
RequiredArgument = [REQUIRED_ARGUMENT = :REQUIRED, true].freeze
OptionalArgument = [OPTIONAL_ARGUMENT = :OPTIONAL, false].freeze
# :startdoc:
#
# Keyword completion module. This allows partial arguments to be specified
# and resolved against a list of acceptable values.
#
module Completion
def self.regexp(key, icase)
Regexp.new('\A' + Regexp.quote(key).gsub(/\w+\b/, '\&\w*'), icase)
end
def self.candidate(key, icase = false, pat = nil, &block)
pat ||= Completion.regexp(key, icase)
candidates = []
block.call do |k, *v|
(if Regexp === k
kn = nil
k === key
else
kn = defined?(k.id2name) ? k.id2name : k
pat === kn
end) or next
v << k if v.empty?
candidates << [k, v, kn]
end
candidates
end
def candidate(key, icase = false, pat = nil)
Completion.candidate(key, icase, pat, &method(:each))
end
public
def complete(key, icase = false, pat = nil)
candidates = candidate(key, icase, pat, &method(:each)).sort_by {|k, v, kn| kn.size}
if candidates.size == 1
canon, sw, * = candidates[0]
elsif candidates.size > 1
canon, sw, cn = candidates.shift
candidates.each do |k, v, kn|
next if sw == v
if String === cn and String === kn
if cn.rindex(kn, 0)
canon, sw, cn = k, v, kn
next
elsif kn.rindex(cn, 0)
next
end
end
throw :ambiguous, key
end
end
if canon
block_given? or return key, *sw
yield(key, *sw)
end
end
def convert(opt = nil, val = nil, *)
val
end
end
#
# Map from option/keyword string to object with completion.
#
class OptionMap < Hash
include Completion
end
#
# Individual switch class. Not important to the user.
#
# Defined within Switch are several Switch-derived classes: NoArgument,
# RequiredArgument, etc.
#
class Switch
attr_reader :pattern, :conv, :short, :long, :arg, :desc, :block
#
# Guesses argument style from +arg+. Returns corresponding
# OptionParser::Switch class (OptionalArgument, etc.).
#
def self.guess(arg)
case arg
when ""
t = self
when /\A=?\[/
t = Switch::OptionalArgument
when /\A\s+\[/
t = Switch::PlacedArgument
else
t = Switch::RequiredArgument
end
self >= t or incompatible_argument_styles(arg, t)
t
end
def self.incompatible_argument_styles(arg, t)
raise(ArgumentError, "#{arg}: incompatible argument styles\n #{self}, #{t}",
ParseError.filter_backtrace(caller(2)))
end
def self.pattern
NilClass
end
def initialize(pattern = nil, conv = nil,
short = nil, long = nil, arg = nil,
desc = ([] if short or long), block = Proc.new)
raise if Array === pattern
@pattern, @conv, @short, @long, @arg, @desc, @block =
pattern, conv, short, long, arg, desc, block
end
#
# Parses +arg+ and returns rest of +arg+ and matched portion to the
# argument pattern. Yields when the pattern doesn't match substring.
#
def parse_arg(arg)
pattern or return nil, [arg]
unless m = pattern.match(arg)
yield(InvalidArgument, arg)
return arg, []
end
if String === m
m = [s = m]
else
m = m.to_a
s = m[0]
return nil, m unless String === s
end
raise InvalidArgument, arg unless arg.rindex(s, 0)
return nil, m if s.length == arg.length
yield(InvalidArgument, arg) # didn't match whole arg
return arg[s.length..-1], m
end
private :parse_arg
#
# Parses argument, converts and returns +arg+, +block+ and result of
# conversion. Yields at semi-error condition instead of raising an
# exception.
#
def conv_arg(arg, val = [])
if conv
val = conv.call(*val)
else
val = proc {|v| v}.call(*val)
end
return arg, block, val
end
private :conv_arg
#
# Produces the summary text. Each line of the summary is yielded to the
# block (without newline).
#
# +sdone+:: Already summarized short style options keyed hash.
# +ldone+:: Already summarized long style options keyed hash.
# +width+:: Width of left side (option part). In other words, the right
# side (description part) starts after +width+ columns.
# +max+:: Maximum width of left side -> the options are filled within
# +max+ columns.
# +indent+:: Prefix string indents all summarized lines.
#
def summarize(sdone = [], ldone = [], width = 1, max = width - 1, indent = "")
sopts, lopts = [], [], nil
@short.each {|s| sdone.fetch(s) {sopts << s}; sdone[s] = true} if @short
@long.each {|s| ldone.fetch(s) {lopts << s}; ldone[s] = true} if @long
return if sopts.empty? and lopts.empty? # completely hidden
left = [sopts.join(', ')]
right = desc.dup
while s = lopts.shift
l = left[-1].length + s.length
l += arg.length if left.size == 1 && arg
l < max or sopts.empty? or left << ''
left[-1] << if left[-1].empty? then ' ' * 4 else ', ' end << s
end
if arg
left[0] << (left[1] ? arg.sub(/\A(\[?)=/, '\1') + ',' : arg)
end
mlen = left.collect {|ss| ss.length}.max.to_i
while mlen > width and l = left.shift
mlen = left.collect {|ss| ss.length}.max.to_i if l.length == mlen
if l.length < width and (r = right[0]) and !r.empty?
l = l.to_s.ljust(width) + ' ' + r
right.shift
end
yield(indent + l)
end
while begin l = left.shift; r = right.shift; l or r end
l = l.to_s.ljust(width) + ' ' + r if r and !r.empty?
yield(indent + l)
end
self
end
def add_banner(to) # :nodoc:
unless @short or @long
s = desc.join
to << " [" + s + "]..." unless s.empty?
end
to
end
def match_nonswitch?(str) # :nodoc:
@pattern =~ str unless @short or @long
end
#
# Main name of the switch.
#
def switch_name
(long.first || short.first).sub(/\A-+(?:\[no-\])?/, '')
end
def compsys(sdone, ldone) # :nodoc:
sopts, lopts = [], []
@short.each {|s| sdone.fetch(s) {sopts << s}; sdone[s] = true} if @short
@long.each {|s| ldone.fetch(s) {lopts << s}; ldone[s] = true} if @long
return if sopts.empty? and lopts.empty? # completely hidden
(sopts+lopts).each do |opt|
# "(-x -c -r)-l[left justify]" \
if /^--\[no-\](.+)$/ =~ opt
o = $1
yield("--#{o}", desc.join(""))
yield("--no-#{o}", desc.join(""))
else
yield("#{opt}", desc.join(""))
end
end
end
#
# Switch that takes no arguments.
#
class NoArgument < self
#
# Raises an exception if any arguments given.
#
def parse(arg, argv)
yield(NeedlessArgument, arg) if arg
conv_arg(arg)
end
def self.incompatible_argument_styles(*)
end
def self.pattern
Object
end
end
#
# Switch that takes an argument.
#
class RequiredArgument < self
#
# Raises an exception if argument is not present.
#
def parse(arg, argv)
unless arg
raise MissingArgument if argv.empty?
arg = argv.shift
end
conv_arg(*parse_arg(arg, &method(:raise)))
end
end
#
# Switch that can omit argument.
#
class OptionalArgument < self
#
# Parses argument if given, or uses default value.
#
def parse(arg, argv, &error)
if arg
conv_arg(*parse_arg(arg, &error))
else
conv_arg(arg)
end
end
end
#
# Switch that takes an argument, which does not begin with '-'.
#
class PlacedArgument < self
#
# Returns nil if argument is not present or begins with '-'.
#
def parse(arg, argv, &error)
if !(val = arg) and (argv.empty? or /\A-/ =~ (val = argv[0]))
return nil, block, nil
end
opt = (val = parse_arg(val, &error))[1]
val = conv_arg(*val)
if opt and !arg
argv.shift
else
val[0] = nil
end
val
end
end
end
#
# Simple option list providing mapping from short and/or long option
# string to OptionParser::Switch and mapping from acceptable argument to
# matching pattern and converter pair. Also provides summary feature.
#
class List
# Map from acceptable argument types to pattern and converter pairs.
attr_reader :atype
# Map from short style option switches to actual switch objects.
attr_reader :short
# Map from long style option switches to actual switch objects.
attr_reader :long
# List of all switches and summary string.
attr_reader :list
#
# Just initializes all instance variables.
#
def initialize
@atype = {}
@short = OptionMap.new
@long = OptionMap.new
@list = []
end
#
# See OptionParser.accept.
#
def accept(t, pat = /.*/m, &block)
if pat
pat.respond_to?(:match) or
raise TypeError, "has no `match'", ParseError.filter_backtrace(caller(2))
else
pat = t if t.respond_to?(:match)
end
unless block
block = pat.method(:convert).to_proc if pat.respond_to?(:convert)
end
@atype[t] = [pat, block]
end
#
# See OptionParser.reject.
#
def reject(t)
@atype.delete(t)
end
#
# Adds +sw+ according to +sopts+, +lopts+ and +nlopts+.
#
# +sw+:: OptionParser::Switch instance to be added.
# +sopts+:: Short style option list.
# +lopts+:: Long style option list.
# +nlopts+:: Negated long style options list.
#
def update(sw, sopts, lopts, nsw = nil, nlopts = nil)
sopts.each {|o| @short[o] = sw} if sopts
lopts.each {|o| @long[o] = sw} if lopts
nlopts.each {|o| @long[o] = nsw} if nsw and nlopts
used = @short.invert.update(@long.invert)
@list.delete_if {|o| Switch === o and !used[o]}
end
private :update
#
# Inserts +switch+ at the head of the list, and associates short, long
# and negated long options. Arguments are:
#
# +switch+:: OptionParser::Switch instance to be inserted.
# +short_opts+:: List of short style options.
# +long_opts+:: List of long style options.
# +nolong_opts+:: List of long style options with "no-" prefix.
#
# prepend(switch, short_opts, long_opts, nolong_opts)
#
def prepend(*args)
update(*args)
@list.unshift(args[0])
end
#
# Appends +switch+ at the tail of the list, and associates short, long
# and negated long options. Arguments are:
#
# +switch+:: OptionParser::Switch instance to be inserted.
# +short_opts+:: List of short style options.
# +long_opts+:: List of long style options.
# +nolong_opts+:: List of long style options with "no-" prefix.
#
# append(switch, short_opts, long_opts, nolong_opts)
#
def append(*args)
update(*args)
@list.push(args[0])
end
#
# Searches +key+ in +id+ list. The result is returned or yielded if a
# block is given. If it isn't found, nil is returned.
#
def search(id, key)
if list = __send__(id)
val = list.fetch(key) {return nil}
block_given? ? yield(val) : val
end
end
#
# Searches list +id+ for +opt+ and the optional patterns for completion
# +pat+. If +icase+ is true, the search is case insensitive. The result
# is returned or yielded if a block is given. If it isn't found, nil is
# returned.
#
def complete(id, opt, icase = false, *pat, &block)
__send__(id).complete(opt, icase, *pat, &block)
end
#
# Iterates over each option, passing the option to the +block+.
#
def each_option(&block)
list.each(&block)
end
#
# Creates the summary table, passing each line to the +block+ (without
# newline). The arguments +args+ are passed along to the summarize
# method which is called on every option.
#
def summarize(*args, &block)
sum = []
list.reverse_each do |opt|
if opt.respond_to?(:summarize) # perhaps OptionParser::Switch
s = []
opt.summarize(*args) {|l| s << l}
sum.concat(s.reverse)
elsif !opt or opt.empty?
sum << ""
elsif opt.respond_to?(:each_line)
sum.concat([*opt.each_line].reverse)
else
sum.concat([*opt.each].reverse)
end
end
sum.reverse_each(&block)
end
def add_banner(to) # :nodoc:
list.each do |opt|
if opt.respond_to?(:add_banner)
opt.add_banner(to)
end
end
to
end
def compsys(*args, &block) # :nodoc:
list.each do |opt|
if opt.respond_to?(:compsys)
opt.compsys(*args, &block)
end
end
end
end
#
# Hash with completion search feature. See OptionParser::Completion.
#
class CompletingHash < Hash
include Completion
#
# Completion for hash key.
#
def match(key)
*values = fetch(key) {
raise AmbiguousArgument, catch(:ambiguous) {return complete(key)}
}
return key, *values
end
end
# :stopdoc:
#
# Enumeration of acceptable argument styles. Possible values are:
#
# NO_ARGUMENT:: The switch takes no arguments. (:NONE)
# REQUIRED_ARGUMENT:: The switch requires an argument. (:REQUIRED)
# OPTIONAL_ARGUMENT:: The switch requires an optional argument. (:OPTIONAL)
#
# Use like --switch=argument (long style) or -Xargument (short style). For
# short style, only portion matched to argument pattern is treated as
# argument.
#
ArgumentStyle = {}
NoArgument.each {|el| ArgumentStyle[el] = Switch::NoArgument}
RequiredArgument.each {|el| ArgumentStyle[el] = Switch::RequiredArgument}
OptionalArgument.each {|el| ArgumentStyle[el] = Switch::OptionalArgument}
ArgumentStyle.freeze
#
# Switches common used such as '--', and also provides default
# argument classes
#
DefaultList = List.new
DefaultList.short['-'] = Switch::NoArgument.new {}
DefaultList.long[''] = Switch::NoArgument.new {throw :terminate}
COMPSYS_HEADER = <<'XXX' # :nodoc:
typeset -A opt_args
local context state line
_arguments -s -S \
XXX
def compsys(to, name = File.basename($0)) # :nodoc:
to << "#compdef #{name}\n"
to << COMPSYS_HEADER
visit(:compsys, {}, {}) {|o, d|
to << %Q[ "#{o}[#{d.gsub(/[\"\[\]]/, '\\\\\&')}]" \\\n]
}
to << " '*:file:_files' && return 0\n"
end
#
# Default options for ARGV, which never appear in option summary.
#
Officious = {}
#
# --help
# Shows option summary.
#
Officious['help'] = proc do |parser|
Switch::NoArgument.new do |arg|
puts parser.help
exit
end
end
#
# --*-completion-bash=WORD
# Shows candidates for command line completion.
#
Officious['*-completion-bash'] = proc do |parser|
Switch::RequiredArgument.new do |arg|
puts parser.candidate(arg)
exit
end
end
#
# --*-completion-zsh[=NAME:FILE]
# Creates zsh completion file.
#
Officious['*-completion-zsh'] = proc do |parser|
Switch::OptionalArgument.new do |arg|
parser.compsys(STDOUT, arg)
exit
end
end
#
# --version
# Shows version string if Version is defined.
#
Officious['version'] = proc do |parser|
Switch::OptionalArgument.new do |pkg|
if pkg
begin
require 'optparse/version'
rescue LoadError
else
show_version(*pkg.split(/,/)) or
abort("#{parser.program_name}: no version found in package #{pkg}")
exit
end
end
v = parser.ver or abort("#{parser.program_name}: version unknown")
puts v
exit
end
end
# :startdoc:
#
# Class methods
#
#
# Initializes a new instance and evaluates the optional block in context
# of the instance. Arguments +args+ are passed to #new, see there for
# description of parameters.
#
# This method is *deprecated*, its behavior corresponds to the older #new
# method.
#
def self.with(*args, &block)
opts = new(*args)
opts.instance_eval(&block)
opts
end
#
# Returns an incremented value of +default+ according to +arg+.
#
def self.inc(arg, default = nil)
case arg
when Integer
arg.nonzero?
when nil
default.to_i + 1
end
end
def inc(*args)
self.class.inc(*args)
end
#
# Initializes the instance and yields itself if called with a block.
#
# +banner+:: Banner message.
# +width+:: Summary width.
# +indent+:: Summary indent.
#
def initialize(banner = nil, width = 32, indent = ' ' * 4)
@stack = [DefaultList, List.new, List.new]
@program_name = nil
@banner = banner
@summary_width = width
@summary_indent = indent
@default_argv = ARGV
add_officious
yield self if block_given?
end
def add_officious # :nodoc:
list = base()
Officious.each do |opt, block|
list.long[opt] ||= block.call(self)
end
end
#
# Terminates option parsing. Optional parameter +arg+ is a string pushed
# back to be the first non-option argument.
#
def terminate(arg = nil)
self.class.terminate(arg)
end
def self.terminate(arg = nil)
throw :terminate, arg
end
@stack = [DefaultList]
def self.top() DefaultList end
#
# Directs to accept specified class +t+. The argument string is passed to
# the block in which it should be converted to the desired class.
#
# +t+:: Argument class specifier, any object including Class.
# +pat+:: Pattern for argument, defaults to +t+ if it responds to match.
#
# accept(t, pat, &block)
#
def accept(*args, &blk) top.accept(*args, &blk) end
#
# See #accept.
#
def self.accept(*args, &blk) top.accept(*args, &blk) end
#
# Directs to reject specified class argument.
#
# +t+:: Argument class specifier, any object including Class.
#
# reject(t)
#
def reject(*args, &blk) top.reject(*args, &blk) end
#
# See #reject.
#
def self.reject(*args, &blk) top.reject(*args, &blk) end
#
# Instance methods
#
# Heading banner preceding summary.
attr_writer :banner
# Program name to be emitted in error message and default banner,
# defaults to $0.
attr_writer :program_name
# Width for option list portion of summary. Must be Numeric.
attr_accessor :summary_width
# Indentation for summary. Must be String (or have + String method).
attr_accessor :summary_indent
# Strings to be parsed in default.
attr_accessor :default_argv
#
# Heading banner preceding summary.
#
def banner
unless @banner
@banner = "Usage: #{program_name} [options]"
visit(:add_banner, @banner)
end
@banner
end
#
# Program name to be emitted in error message and default banner, defaults
# to $0.
#
def program_name
@program_name || File.basename($0, '.*')
end
# for experimental cascading :-)
alias set_banner banner=
alias set_program_name program_name=
alias set_summary_width summary_width=
alias set_summary_indent summary_indent=
# Version
attr_writer :version
# Release code
attr_writer :release
#
# Version
#
def version
@version || (defined?(::Version) && ::Version)
end
#
# Release code
#
def release
@release || (defined?(::Release) && ::Release) || (defined?(::RELEASE) && ::RELEASE)
end
#
# Returns version string from program_name, version and release.
#
def ver
if v = version
str = "#{program_name} #{[v].join('.')}"
str << " (#{v})" if v = release
str
end
end
def warn(mesg = $!)
super("#{program_name}: #{mesg}")
end
def abort(mesg = $!)
super("#{program_name}: #{mesg}")
end
#
# Subject of #on / #on_head, #accept / #reject
#
def top
@stack[-1]
end
#
# Subject of #on_tail.
#
def base
@stack[1]
end
#
# Pushes a new List.
#
def new
@stack.push(List.new)
if block_given?
yield self
else
self
end
end
#
# Removes the last List.
#
def remove
@stack.pop
end
#
# Puts option summary into +to+ and returns +to+. Yields each line if
# a block is given.
#
# +to+:: Output destination, which must have method <<. Defaults to [].
# +width+:: Width of left side, defaults to @summary_width.
# +max+:: Maximum length allowed for left side, defaults to +width+ - 1.
# +indent+:: Indentation, defaults to @summary_indent.
#
def summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk)
blk ||= proc {|l| to << (l.index($/, -1) ? l : l + $/)}
visit(:summarize, {}, {}, width, max, indent, &blk)
to
end
#
# Returns option summary string.
#
def help; summarize("#{banner}".sub(/\n?\z/, "\n")) end
alias to_s help
#
# Returns option summary list.
#
def to_a; summarize("#{banner}".split(/^/)) end
#
# Checks if an argument is given twice, in which case an ArgumentError is
# raised. Called from OptionParser#switch only.
#
# +obj+:: New argument.
# +prv+:: Previously specified argument.
# +msg+:: Exception message.
#
def notwice(obj, prv, msg)
unless !prv or prv == obj
raise(ArgumentError, "argument #{msg} given twice: #{obj}",
ParseError.filter_backtrace(caller(2)))
end
obj
end
private :notwice
SPLAT_PROC = proc {|*a| a.length <= 1 ? a.first : a} # :nodoc:
#
# Creates an OptionParser::Switch from the parameters. The parsed argument
# value is passed to the given block, where it can be processed.
#
# See at the beginning of OptionParser for some full examples.
#
# +opts+ can include the following elements:
#
# [Argument style:]
# One of the following:
# :NONE, :REQUIRED, :OPTIONAL
#
# [Argument pattern:]
# Acceptable option argument format, must be pre-defined with
# OptionParser.accept or OptionParser#accept, or Regexp. This can appear
# once or assigned as String if not present, otherwise causes an
# ArgumentError. Examples:
# Float, Time, Array
#
# [Possible argument values:]
# Hash or Array.
# [:text, :binary, :auto]
# %w[iso-2022-jp shift_jis euc-jp utf8 binary]
# { "jis" => "iso-2022-jp", "sjis" => "shift_jis" }
#
# [Long style switch:]
# Specifies a long style switch which takes a mandatory, optional or no
# argument. It's a string of the following form:
# "--switch=MANDATORY" or "--switch MANDATORY"
# "--switch[=OPTIONAL]"
# "--switch"
#
# [Short style switch:]
# Specifies short style switch which takes a mandatory, optional or no
# argument. It's a string of the following form:
# "-xMANDATORY"
# "-x[OPTIONAL]"
# "-x"
# There is also a special form which matches character range (not full
# set of regular expression):
# "-[a-z]MANDATORY"
# "-[a-z][OPTIONAL]"
# "-[a-z]"
#
# [Argument style and description:]
# Instead of specifying mandatory or optional arguments directly in the
# switch parameter, this separate parameter can be used.
# "=MANDATORY"
# "=[OPTIONAL]"
#
# [Description:]
# Description string for the option.
# "Run verbosely"
#
# [Handler:]
# Handler for the parsed argument value. Either give a block or pass a
# Proc or Method as an argument.
#
def make_switch(opts, block = nil)
short, long, nolong, style, pattern, conv, not_pattern, not_conv, not_style = [], [], []
ldesc, sdesc, desc, arg = [], [], []
default_style = Switch::NoArgument
default_pattern = nil
klass = nil
q, a = nil
opts.each do |o|
# argument class
next if search(:atype, o) do |pat, c|
klass = notwice(o, klass, 'type')
if not_style and not_style != Switch::NoArgument
not_pattern, not_conv = pat, c
else
default_pattern, conv = pat, c
end
end
# directly specified pattern(any object possible to match)
if (!(String === o || Symbol === o)) and o.respond_to?(:match)
pattern = notwice(o, pattern, 'pattern')
if pattern.respond_to?(:convert)
conv = pattern.method(:convert).to_proc
else
conv = SPLAT_PROC
end
next
end
# anything others
case o
when Proc, Method
block = notwice(o, block, 'block')
when Array, Hash
case pattern
when CompletingHash
when nil
pattern = CompletingHash.new
conv = pattern.method(:convert).to_proc if pattern.respond_to?(:convert)
else
raise ArgumentError, "argument pattern given twice"
end
o.each {|pat, *v| pattern[pat] = v.fetch(0) {pat}}
when Module
raise ArgumentError, "unsupported argument type: #{o}", ParseError.filter_backtrace(caller(4))
when *ArgumentStyle.keys
style = notwice(ArgumentStyle[o], style, 'style')
when /^--no-([^\[\]=\s]*)(.+)?/
q, a = $1, $2
o = notwice(a ? Object : TrueClass, klass, 'type')
not_pattern, not_conv = search(:atype, o) unless not_style
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | true |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/tkvirtevent.rb | lib/tkvirtevent.rb | #
# tkvirtevent.rb - load tk/virtevent.rb
#
require 'tk/virtevent'
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/ripper.rb | lib/ripper.rb | require 'ripper/core'
require 'ripper/lexer'
require 'ripper/filter'
require 'ripper/sexp'
# Ripper is a Ruby script parser.
#
# You can get information from the parser with event-based style.
# Information such as abstract syntax trees or simple lexical analysis of the
# Ruby program.
#
# == Usage
#
# Ripper provides an easy interface for parsing your program into a symbolic
# expression tree (or S-expression).
#
# Understanding the output of the parser may come as a challenge, it's
# recommended you use PP to format the output for legibility.
#
# require 'ripper'
# require 'pp'
#
# pp Ripper.sexp('def hello(world) "Hello, #{world}!"; end')
# #=> [:program,
# [[:def,
# [:@ident, "hello", [1, 4]],
# [:paren,
# [:params, [[:@ident, "world", [1, 10]]], nil, nil, nil, nil, nil, nil]],
# [:bodystmt,
# [[:string_literal,
# [:string_content,
# [:@tstring_content, "Hello, ", [1, 18]],
# [:string_embexpr, [[:var_ref, [:@ident, "world", [1, 27]]]]],
# [:@tstring_content, "!", [1, 33]]]]],
# nil,
# nil,
# nil]]]]
#
# You can see in the example above, the expression starts with +:program+.
#
# From here, a method definition at +:def+, followed by the method's identifier
# <code>:@ident</code>. After the method's identifier comes the parentheses
# +:paren+ and the method parameters under +:params+.
#
# Next is the method body, starting at +:bodystmt+ (+stmt+ meaning statement),
# which contains the full definition of the method.
#
# In our case, we're simply returning a String, so next we have the
# +:string_literal+ expression.
#
# Within our +:string_literal+ you'll notice two <code>@tstring_content</code>,
# this is the literal part for <code>Hello, </code> and <code>!</code>. Between
# the two <code>@tstring_content</code> statements is a +:string_embexpr+,
# where _embexpr_ is an embedded expression. Our expression consists of a local
# variable, or +var_ref+, with the identifier (<code>@ident</code>) of +world+.
#
# == Resources
#
# * {Ruby Inside}[http://www.rubyinside.com/using-ripper-to-see-how-ruby-is-parsing-your-code-5270.html]
#
# == Requirements
#
# * ruby 1.9 (support CVS HEAD only)
# * bison 1.28 or later (Other yaccs do not work)
#
# == License
#
# Ruby License.
#
# Minero Aoki
# aamine@loveruby.net
# http://i.loveruby.net
class Ripper; end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/English.rb | lib/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"
#
# Below is a full list of descriptive aliases and their associated global
# variable:
#
# $ERROR_INFO:: $!
# $ERROR_POSITION:: $@
# $FS:: $;
# $FIELD_SEPARATOR:: $;
# $OFS:: $,
# $OUTPUT_FIELD_SEPARATOR:: $,
# $RS:: $/
# $INPUT_RECORD_SEPARATOR:: $/
# $ORS:: $\
# $OUTPUT_RECORD_SEPARATOR:: $\
# $INPUT_LINE_NUMBER:: $.
# $NR:: $.
# $LAST_READ_LINE:: $_
# $DEFAULT_OUTPUT:: $>
# $DEFAULT_INPUT:: $<
# $PID:: $$
# $PROCESS_ID:: $$
# $CHILD_STATUS:: $?
# $LAST_MATCH_INFO:: $~
# $IGNORECASE:: $=
# $ARGV:: $*
# $MATCH:: $&
# $PREMATCH:: $`
# $POSTMATCH:: $'
# $LAST_PAREN_MATCH:: $+
#
module English end if false
# 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.
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.
alias $MATCH $&
# The string preceding the match in the last
# successful pattern match. This variable is local to
# the current scope. Read only.
alias $PREMATCH $`
# The string following the match in the last
# successful pattern match. This variable is local to
# the current scope. Read only.
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.
alias $LAST_PAREN_MATCH $+
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/logger.rb | lib/logger.rb | # logger.rb - simple logging utility
# Copyright (C) 2000-2003, 2005, 2008, 2011 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
#
# 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 44203 2013-12-14 05:43:01Z nobu $
#
# A simple system for logging messages. See Logger for more documentation.
require 'monitor'
# == Description
#
# The Logger class provides a simple but sophisticated logging utility that
# you can use to output messages.
#
# The messages have associated levels, such as +INFO+ or +ERROR+ that indicate
# their importance. You can then give the Logger a level, and only messages
# at that level or higher will be printed.
#
# The levels are:
#
# +UNKNOWN+:: An unknown message that should always be logged.
# +FATAL+:: An unhandleable error that results in a program crash.
# +ERROR+:: A handleable error condition.
# +WARN+:: A warning.
# +INFO+:: Generic (useful) information about system operation.
# +DEBUG+:: Low-level information for developers.
#
# For instance, in a production system, you may have your Logger set to
# +INFO+ or even +WARN+.
# When you are developing the system, however, you probably
# want to know about the program's internal state, and would set the Logger to
# +DEBUG+.
#
# *Note*: Logger does not escape or sanitize any messages passed to it.
# Developers should be aware of when potentially malicious data (user-input)
# is passed to Logger, and manually escape the untrusted data:
#
# logger.info("User-input: #{input.dump}")
# logger.info("User-input: %p" % input)
#
# You can use #formatter= for escaping all data.
#
# original_formatter = Logger::Formatter.new
# logger.formatter = proc { |severity, datetime, progname, msg|
# original_formatter.call(severity, datetime, progname, msg.dump)
# }
# logger.info(input)
#
# === Example
#
# This creates a Logger that outputs to the standard output stream, with a
# level of +WARN+:
#
# require 'logger'
#
# logger = Logger.new(STDOUT)
# logger.level = Logger::WARN
#
# logger.debug("Created logger")
# logger.info("Program started")
# logger.warn("Nothing to do!")
#
# path = "a_non_existent_file"
#
# begin
# File.foreach(path) do |line|
# unless line =~ /^(\w+) = (.*)$/
# logger.error("Line in wrong format: #{line.chomp}")
# end
# end
# rescue => err
# logger.fatal("Caught exception; exiting")
# logger.fatal(err)
# end
#
# Because the Logger's level is set to +WARN+, only the warning, error, and
# fatal messages are recorded. The debug and info messages are silently
# discarded.
#
# === Features
#
# There are several interesting features that Logger provides, like
# auto-rolling of log files, setting the format of log messages, and
# specifying a program name in conjunction with the message. The next section
# shows you how to achieve these things.
#
#
# == HOWTOs
#
# === How to create a logger
#
# The options below give you various choices, in more or less increasing
# complexity.
#
# 1. Create a logger which logs messages to STDERR/STDOUT.
#
# logger = Logger.new(STDERR)
# logger = Logger.new(STDOUT)
#
# 2. Create a logger for the file which has the specified name.
#
# logger = Logger.new('logfile.log')
#
# 3. Create a logger for the specified file.
#
# file = File.open('foo.log', File::WRONLY | File::APPEND)
# # To create new (and to remove old) logfile, add File::CREAT like:
# # file = File.open('foo.log', File::WRONLY | File::APPEND | File::CREAT)
# logger = Logger.new(file)
#
# 4. Create a logger which ages the logfile once it reaches a certain size.
# Leave 10 "old" log files where each file is about 1,024,000 bytes.
#
# logger = Logger.new('foo.log', 10, 1024000)
#
# 5. Create a logger which ages the logfile daily/weekly/monthly.
#
# logger = Logger.new('foo.log', 'daily')
# logger = Logger.new('foo.log', 'weekly')
# logger = Logger.new('foo.log', 'monthly')
#
# === How to log a message
#
# Notice the different methods (+fatal+, +error+, +info+) being used to log
# messages of various levels? Other methods in this family are +warn+ and
# +debug+. +add+ is used below to log a message of an arbitrary (perhaps
# dynamic) level.
#
# 1. Message in a block.
#
# logger.fatal { "Argument 'foo' not given." }
#
# 2. Message as a string.
#
# logger.error "Argument #{@foo} mismatch."
#
# 3. With progname.
#
# logger.info('initialize') { "Initializing..." }
#
# 4. With severity.
#
# logger.add(Logger::FATAL) { 'Fatal error!' }
#
# The block form allows you to create potentially complex log messages,
# but to delay their evaluation until and unless the message is
# logged. For example, if we have the following:
#
# logger.debug { "This is a " + potentially + " expensive operation" }
#
# If the logger's level is +INFO+ or higher, no debug messages will be logged,
# and the entire block will not even be evaluated. Compare to this:
#
# logger.debug("This is a " + potentially + " expensive operation")
#
# Here, the string concatenation is done every time, even if the log
# level is not set to show the debug message.
#
# === How to close a logger
#
# logger.close
#
# === Setting severity threshold
#
# 1. Original interface.
#
# logger.sev_threshold = Logger::WARN
#
# 2. Log4r (somewhat) compatible interface.
#
# logger.level = Logger::INFO
#
# # DEBUG < INFO < WARN < ERROR < FATAL < UNKNOWN
#
# == Format
#
# Log messages are rendered in the output stream in a certain format by
# default. The default format and a sample are shown below:
#
# Log format:
# SeverityID, [DateTime #pid] SeverityLabel -- ProgName: message
#
# Log sample:
# I, [1999-03-03T02:34:24.895701 #19074] INFO -- Main: info.
#
# You may change the date and time format via #datetime_format=.
#
# logger.datetime_format = '%Y-%m-%d %H:%M:%S'
# # e.g. "2004-01-03 00:54:26"
#
# Or, you may change the overall format via the #formatter= method.
#
# logger.formatter = proc do |severity, datetime, progname, msg|
# "#{datetime}: #{msg}\n"
# end
# # e.g. "2005-09-22 08:51:08 +0900: hello world"
#
class Logger
VERSION = "1.2.7"
_, name, rev = %w$Id: logger.rb 44203 2013-12-14 05:43:01Z nobu $
if name
name = name.chomp(",v")
else
name = File.basename(__FILE__)
end
rev ||= "v#{VERSION}"
ProgName = "#{name}/#{rev}"
class Error < RuntimeError # :nodoc:
end
# not used after 1.2.7. just for compat.
class ShiftingError < Error # :nodoc:
end
# Logging severity.
module Severity
# Low-level information, mostly for developers.
DEBUG = 0
# Generic (useful) information about system operation.
INFO = 1
# A warning.
WARN = 2
# A handleable error condition.
ERROR = 3
# An unhandleable error that results in a program crash.
FATAL = 4
# An unknown message that should always be logged.
UNKNOWN = 5
end
include Severity
# Logging severity threshold (e.g. <tt>Logger::INFO</tt>).
attr_accessor :level
# Program name to include in log messages.
attr_accessor :progname
# Set date-time format.
#
# +datetime_format+:: A string suitable for passing to +strftime+.
def datetime_format=(datetime_format)
@default_formatter.datetime_format = datetime_format
end
# Returns the date format being used. See #datetime_format=
def datetime_format
@default_formatter.datetime_format
end
# Logging formatter, as a +Proc+ that will take four arguments and
# return the formatted message. The arguments are:
#
# +severity+:: The Severity of the log message.
# +time+:: A Time instance representing when the message was logged.
# +progname+:: The #progname configured, or passed to the logger method.
# +msg+:: The _Object_ the user passed to the log message; not necessarily a
# String.
#
# The block should return an Object that can be written to the logging
# device via +write+. The default formatter is used when no formatter is
# set.
attr_accessor :formatter
alias sev_threshold level
alias sev_threshold= level=
# Returns +true+ iff the current severity level allows for the printing of
# +DEBUG+ messages.
def debug?; @level <= DEBUG; end
# Returns +true+ iff the current severity level allows for the printing of
# +INFO+ messages.
def info?; @level <= INFO; end
# Returns +true+ iff the current severity level allows for the printing of
# +WARN+ messages.
def warn?; @level <= WARN; end
# Returns +true+ iff the current severity level allows for the printing of
# +ERROR+ messages.
def error?; @level <= ERROR; end
# Returns +true+ iff the current severity level allows for the printing of
# +FATAL+ messages.
def fatal?; @level <= FATAL; end
#
# :call-seq:
# Logger.new(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
#
# :call-seq:
# Logger#add(severity, message = nil, progname = nil) { ... }
#
# === Args
#
# +severity+::
# Severity. Constants are defined in Logger namespace: +DEBUG+, +INFO+,
# +WARN+, +ERROR+, +FATAL+, or +UNKNOWN+.
# +message+::
# The log message. A String or Exception.
# +progname+::
# Program name string. Can be omitted. Treated as a message if no
# +message+ and +block+ are given.
# +block+::
# Can be omitted. Called to get a message string if +message+ is nil.
#
# === Return
#
# When the given severity is not high enough (for this particular logger),
# log no message, and return +true+.
#
# === Description
#
# Log a message if the given severity is high enough. This is the generic
# logging method. Users will be more inclined to use #debug, #info, #warn,
# #error, and #fatal.
#
# <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.
# * If the OS supports multi I/O, records possibly may be mixed.
#
def add(severity, message = nil, progname = nil, &block)
severity ||= UNKNOWN
if @logdev.nil? or severity < @level
return true
end
progname ||= @progname
if message.nil?
if block_given?
message = yield
else
message = progname
progname = @progname
end
end
@logdev.write(
format_message(format_severity(severity), Time.now, progname, message))
true
end
alias log add
#
# Dump given message to the log device without any formatting. If no log
# device exists, return +nil+.
#
def <<(msg)
unless @logdev.nil?
@logdev.write(msg)
end
end
#
# Log a +DEBUG+ message.
#
# See #info for more information.
#
def debug(progname = nil, &block)
add(DEBUG, nil, progname, &block)
end
#
# :call-seq:
# info(message)
# info(progname, &block)
#
# Log an +INFO+ message.
#
# +message+:: The message to log; does not need to be a String.
# +progname+:: In the block form, this is the #progname to use in the
# log message. The default can be set with #progname=.
# +block+:: Evaluates to the message to log. This is not evaluated unless
# the logger's level is sufficient to log the message. This
# allows you to create potentially expensive logging messages that
# are only called when the logger is configured to show them.
#
# === Examples
#
# logger.info("MainApp") { "Received connection from #{ip}" }
# # ...
# logger.info "Waiting for input from user"
# # ...
# logger.info { "User typed #{input}" }
#
# You'll probably stick to the second form above, unless you want to provide a
# program name (which you can do with #progname= as well).
#
# === Return
#
# See #add.
#
def info(progname = nil, &block)
add(INFO, nil, progname, &block)
end
#
# Log a +WARN+ message.
#
# See #info for more information.
#
def warn(progname = nil, &block)
add(WARN, nil, progname, &block)
end
#
# Log an +ERROR+ message.
#
# See #info for more information.
#
def error(progname = nil, &block)
add(ERROR, nil, progname, &block)
end
#
# Log a +FATAL+ message.
#
# See #info for more information.
#
def fatal(progname = nil, &block)
add(FATAL, nil, progname, &block)
end
#
# Log an +UNKNOWN+ message. This will be printed no matter what the logger's
# level is.
#
# See #info for more information.
#
def unknown(progname = nil, &block)
add(UNKNOWN, nil, progname, &block)
end
#
# Close the logging device.
#
def close
@logdev.close if @logdev
end
private
# Severity label for logging (max 5 chars).
SEV_LABEL = %w(DEBUG INFO WARN ERROR FATAL ANY)
def format_severity(severity)
SEV_LABEL[severity] || 'ANY'
end
def format_message(severity, datetime, progname, msg)
(@formatter || @default_formatter).call(severity, datetime, progname, msg)
end
# Default formatter for log messages.
class Formatter
Format = "%s, [%s#%d] %5s -- %s: %s\n"
attr_accessor :datetime_format
def initialize
@datetime_format = nil
end
def call(severity, time, progname, msg)
Format % [severity[0..0], format_datetime(time), $$, severity, progname,
msg2str(msg)]
end
private
def format_datetime(time)
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
# Device used for logging messages.
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)
begin
@mutex.synchronize do
if @shift_age and @dev.respond_to?(:stat)
begin
check_shift_log
rescue
warn("log shifting failed. #{$!}")
end
end
begin
@dev.write(message)
rescue
warn("log writing failed. #{$!}")
end
end
rescue Exception => ignored
warn("log writing failed. #{ignored}")
end
end
def close
begin
@mutex.synchronize do
@dev.close rescue nil
end
rescue Exception
@dev.close rescue nil
end
end
private
def open_logfile(filename)
begin
open(filename, (File::WRONLY | File::APPEND))
rescue Errno::ENOENT
create_logfile(filename)
end
end
def create_logfile(filename)
begin
logdev = open(filename, (File::WRONLY | File::APPEND | File::CREAT | File::EXCL))
logdev.flock(File::LOCK_EX)
logdev.sync = true
add_log_header(logdev)
logdev.flock(File::LOCK_UN)
rescue Errno::EEXIST
# file is created by another process
logdev = open_logfile(filename)
logdev.sync = true
end
logdev
end
def add_log_header(file)
file.write(
"# Logfile created on %s by %s\n" % [Time.now.to_s, Logger::ProgName]
) if file.size == 0
end
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)
lock_shift_log { shift_log_age }
end
else
now = Time.now
period_end = previous_period_end(now)
if @dev.stat.mtime <= period_end
lock_shift_log { shift_log_period(period_end) }
end
end
end
if /mswin|mingw/ =~ RUBY_PLATFORM
def lock_shift_log
yield
end
else
def lock_shift_log
retry_limit = 8
retry_sleep = 0.1
begin
File.open(@filename, File::WRONLY | File::APPEND) do |lock|
lock.flock(File::LOCK_EX) # inter-process locking. will be unlocked at closing file
if File.identical?(@filename, lock) and File.identical?(lock, @dev)
yield # log shifting
else
# log shifted by another process (i-node before locking and i-node after locking are different)
@dev.close rescue nil
@dev = open_logfile(@filename)
@dev.sync = true
end
end
rescue Errno::ENOENT
# @filename file would not exist right after #rename and before #create_logfile
if retry_limit <= 0
warn("log rotation inter-process lock failed. #{$!}")
else
sleep retry_sleep
retry_limit -= 1
retry_sleep *= 2
retry
end
end
rescue
warn("log rotation inter-process lock failed. #{$!}")
end
end
def shift_log_age
(@shift_age-3).downto(0) do |i|
if FileTest.exist?("#{@filename}.#{i}")
File.rename("#{@filename}.#{i}", "#{@filename}.#{i+1}")
end
end
@dev.close rescue nil
File.rename("#{@filename}", "#{@filename}.0")
@dev = create_logfile(@filename)
return true
end
def shift_log_period(period_end)
postfix = period_end.strftime("%Y%m%d") # YYYYMMDD
age_file = "#{@filename}.#{postfix}"
if FileTest.exist?(age_file)
# try to avoid filename crash caused by Timestamp change.
idx = 0
# .99 can be overridden; avoid too much file search with 'loop do'
while idx < 100
idx += 1
age_file = "#{@filename}.#{postfix}.#{idx}"
break unless FileTest.exist?(age_file)
end
end
@dev.close rescue nil
File.rename("#{@filename}", age_file)
@dev = create_logfile(@filename)
return true
end
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
#
# Logger::Application --- Add logging support to your application.
#
# == Usage
#
# 1. Define your application class as a sub-class of this class.
# 2. Override the +run+ method in your class to do many things.
# 3. Instantiate it and invoke #start.
#
# == Example
#
# class FooApp < Logger::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
#
# :call-seq:
# Logger::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
@log.progname = @appname
@log.level = @level
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
# TODO: should be an NotImplementedError
raise RuntimeError.new('Method run must be defined in the derived class.')
end
end
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/mathn.rb | lib/mathn.rb | #--
# $Release Version: 0.5 $
# $Revision: 1.1.1.1.4.1 $
##
# = mathn
#
# mathn is a library for changing the way Ruby does math. If you need
# more precise rounding with multiple division or exponentiation
# operations, then mathn is the right tool.
#
# Without mathn:
#
# 3 / 2 => 1 # Integer
#
# With mathn:
#
# 3 / 2 => 3/2 # Rational
#
# mathn features late rounding and lacks truncation of intermediate results:
#
# Without mathn:
#
# 20 / 9 * 3 * 14 / 7 * 3 / 2 # => 18
#
# With mathn:
#
# 20 / 9 * 3 * 14 / 7 * 3 / 2 # => 20
#
#
# When you require 'mathn', the libraries for Prime, CMath, Matrix and Vector
# are also loaded.
#
# == Copyright
#
# Author: Keiju ISHITSUKA (SHL Japan Inc.)
#--
# class Numeric follows to make this documentation findable in a reasonable
# location
class Numeric; end
require "cmath.rb"
require "matrix.rb"
require "prime.rb"
require "mathn/rational"
require "mathn/complex"
unless defined?(Math.exp!)
Object.instance_eval{remove_const :Math}
Math = CMath # :nodoc:
end
##
# When mathn is required, Fixnum's division and exponentiation are enhanced to
# return more precise values from mathematical expressions.
#
# 2/3*3 # => 0
# require 'mathn'
# 2/3*3 # => 2
class Fixnum
remove_method :/
##
# +/+ defines the Rational division for Fixnum.
#
# 1/3 # => (1/3)
alias / quo
alias power! ** unless method_defined? :power!
##
# Exponentiate by +other+
def ** (other)
if self < 0 && other.round != other
Complex(self, 0.0) ** other
else
power!(other)
end
end
end
##
# When mathn is required Bignum's division and exponentiation are enhanced to
# return more precise values from mathematical expressions.
class Bignum
remove_method :/
##
# +/+ defines the Rational division for Bignum.
#
# (2**72) / ((2**70) * 3) # => 4/3
alias / quo
alias power! ** unless method_defined? :power!
##
# Exponentiate by +other+
def ** (other)
if self < 0 && other.round != other
Complex(self, 0.0) ** other
else
power!(other)
end
end
end
##
# When mathn is required Rational is changed to simplify the use of Rational
# operations.
#
# Normal behaviour:
#
# Rational.new!(1,3) ** 2 # => Rational(1, 9)
# (1 / 3) ** 2 # => 0
#
# require 'mathn' behaviour:
#
# (1 / 3) ** 2 # => 1/9
class Rational
remove_method :**
##
# Exponentiate by +other+
#
# (1/3) ** 2 # => 1/9
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
##
# When mathn is required, the Math module changes as follows:
#
# Standard Math module behaviour:
# Math.sqrt(4/9) # => 0.0
# Math.sqrt(4.0/9.0) # => 0.666666666666667
# Math.sqrt(- 4/9) # => Errno::EDOM: Numerical argument out of domain - sqrt
#
# After require 'mathn', this is changed to:
#
# require 'mathn'
# Math.sqrt(4/9) # => 2/3
# Math.sqrt(4.0/9.0) # => 0.666666666666667
# Math.sqrt(- 4/9) # => Complex(0, 2/3)
module Math
remove_method(:sqrt)
##
# Computes the square root of +a+. It makes use of Complex and
# Rational to have no rounding errors if possible.
#
# Math.sqrt(4/9) # => 2/3
# Math.sqrt(- 4/9) # => Complex(0, 2/3)
# Math.sqrt(4.0/9.0) # => 0.666666666666667
def sqrt(a)
if a.kind_of?(Complex)
abs = sqrt(a.real*a.real + a.imag*a.imag)
# 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
##
# Compute square root of a non negative number. This method is
# internally used by +Math.sqrt+.
def rsqrt(a)
if a.kind_of?(Float)
sqrt!(a)
elsif a.kind_of?(Rational)
rsqrt(a.numerator)/rsqrt(a.denominator)
else
src = a
max = 2 ** 32
byte_a = [src & 0xffffffff]
# ruby's bug
while (src >= max) and (src >>= 32)
byte_a.unshift src & 0xffffffff
end
answer = 0
main = 0
side = 0
for elm in byte_a
main = (main << 32) + elm
side <<= 16
if answer != 0
if main * 4 < side * side
applo = main.div(side)
else
applo = ((sqrt!(side * side + 4 * main) - side)/2.0).to_i + 1
end
else
applo = sqrt!(main).to_i + 1
end
while (x = (side + applo) * applo) > main
applo -= 1
end
main -= x
answer = (answer << 16) + applo
side += applo * 2
end
if main == 0
answer
else
sqrt!(a)
end
end
end
class << self
remove_method(:sqrt)
end
module_function :sqrt
module_function :rsqrt
end
##
# When mathn is required, Float is changed to handle Complex numbers.
class Float
alias power! **
##
# Exponentiate by +other+
def ** (other)
if self < 0 && other.round != other
Complex(self, 0.0) ** other
else
power!(other)
end
end
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/thwait.rb | lib/thwait.rb | #
# thwait.rb - thread synchronization class
# $Release Version: 0.9 $
# $Revision: 1.3 $
# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd.)
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_waits(thr1, thr2, ...) do |t|
# STDERR.puts "Thread #{t} has terminated."
# end
#
#
# th = ThreadsWait.new(thread1,...)
# th.next_wait # next one to be done
#
#
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 as they terminate.
#
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 that have not terminated yet.
attr :threads
#
# Returns +true+ if there are no threads in the pool still running.
#
def empty?
@threads.empty?
end
#
# Returns +true+ if any thread has terminated and is ready to be collected.
#
def finished?
!@wait_queue.empty?
end
#
# Waits for specified threads to terminate, and returns when one of
# the threads terminated.
#
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
##
# An alias for ThreadsWait from thwait.rb
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.
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/tempfile.rb | lib/tempfile.rb | #
# tempfile - manipulates temporary files
#
# $Id: tempfile.rb 43758 2013-11-21 09:28:43Z nobu $
#
require 'delegate'
require 'tmpdir'
require 'thread'
# A utility class for managing temporary files. When you create a Tempfile
# object, it will create a temporary file with a unique filename. A Tempfile
# objects behaves just like a File object, and you can perform all the usual
# file operations on it: reading data, writing data, changing its permissions,
# etc. So although this class does not explicitly document all instance methods
# supported by File, you can in fact call any File instance method on a
# Tempfile object.
#
# == Synopsis
#
# require 'tempfile'
#
# file = Tempfile.new('foo')
# file.path # => A unique filename in the OS's temp directory,
# # e.g.: "/tmp/foo.24722.0"
# # This filename contains 'foo' in its basename.
# file.write("hello world")
# file.rewind
# file.read # => "hello world"
# file.close
# file.unlink # deletes the temp file
#
# == Good practices
#
# === Explicit close
#
# When a Tempfile object is garbage collected, or when the Ruby interpreter
# exits, its associated temporary file is automatically deleted. This means
# that's it's unnecessary to explicitly delete a Tempfile after use, though
# it's good practice to do so: not explicitly deleting unused Tempfiles can
# potentially leave behind large amounts of tempfiles on the filesystem
# until they're garbage collected. The existence of these temp files can make
# it harder to determine a new Tempfile filename.
#
# Therefore, one should always call #unlink or close in an ensure block, like
# this:
#
# file = Tempfile.new('foo')
# begin
# ...do something with file...
# ensure
# file.close
# file.unlink # deletes the temp file
# end
#
# === Unlink after creation
#
# On POSIX systems, it's possible to unlink a file right after creating it,
# and before closing it. This removes the filesystem entry without closing
# the file handle, so it ensures that only the processes that already had
# the file handle open can access the file's contents. It's strongly
# recommended that you do this if you do not want any other processes to
# be able to read from or write to the Tempfile, and you do not need to
# know the Tempfile's filename either.
#
# For example, a practical use case for unlink-after-creation would be this:
# you need a large byte buffer that's too large to comfortably fit in RAM,
# e.g. when you're writing a web server and you want to buffer the client's
# file upload data.
#
# Please refer to #unlink for more information and a code example.
#
# == Minor notes
#
# Tempfile's filename picking method is both thread-safe and inter-process-safe:
# it guarantees that no other threads or processes will pick the same filename.
#
# Tempfile itself however may not be entirely thread-safe. If you access the
# same Tempfile object from multiple threads then you should protect it with a
# mutex.
class Tempfile < DelegateClass(File)
include Dir::Tmpname
# call-seq:
# new(basename, [tmpdir = Dir.tmpdir], [options])
#
# Creates a temporary file with permissions 0600 (= only readable and
# writable by the owner) and opens it with mode "w+".
#
# The +basename+ parameter is used to determine the name of the
# temporary file. You can either pass a String or an Array with
# 2 String elements. In the former form, the temporary file's base
# name will begin with the given string. In the latter form,
# the temporary file's base name will begin with the array's first
# element, and end with the second element. For example:
#
# file = Tempfile.new('hello')
# file.path # => something like: "/tmp/hello2843-8392-92849382--0"
#
# # Use the Array form to enforce an extension in the filename:
# file = Tempfile.new(['hello', '.jpg'])
# file.path # => something like: "/tmp/hello2843-8392-92849382--0.jpg"
#
# The temporary file will be placed in the directory as specified
# by the +tmpdir+ parameter. By default, this is +Dir.tmpdir+.
# When $SAFE > 0 and the given +tmpdir+ is tainted, it uses
# '/tmp' as the temporary directory. Please note that ENV values
# are tainted by default, and +Dir.tmpdir+'s return value might
# come from environment variables (e.g. <tt>$TMPDIR</tt>).
#
# file = Tempfile.new('hello', '/home/aisaka')
# file.path # => something like: "/home/aisaka/hello2843-8392-92849382--0"
#
# You can also pass an options hash. Under the hood, Tempfile creates
# the temporary file using +File.open+. These options will be passed to
# +File.open+. This is mostly useful for specifying encoding
# options, e.g.:
#
# Tempfile.new('hello', '/home/aisaka', :encoding => 'ascii-8bit')
#
# # You can also omit the 'tmpdir' parameter:
# Tempfile.new('hello', :encoding => 'ascii-8bit')
#
# === Exceptions
#
# If Tempfile.new cannot find a unique filename within a limited
# number of tries, then it will raise an exception.
def initialize(basename, *rest)
if block_given?
warn "Tempfile.new doesn't call the given block."
end
@data = []
@clean_proc = Remover.new(@data)
ObjectSpace.define_finalizer(self, @clean_proc)
::Dir::Tmpname.create(basename, *rest) do |tmpname, n, opts|
mode = File::RDWR|File::CREAT|File::EXCL
perm = 0600
if opts
mode |= opts.delete(:mode) || 0
opts[:perm] = perm
perm = nil
else
opts = perm
end
@data[1] = @tmpfile = File.open(tmpname, mode, opts)
@data[0] = @tmpname = tmpname
@mode = mode & ~(File::CREAT|File::EXCL)
perm or opts.freeze
@opts = opts
end
super(@tmpfile)
end
# Opens or reopens the file with mode "r+".
def open
@tmpfile.close if @tmpfile
@tmpfile = File.open(@tmpname, @mode, @opts)
@data[1] = @tmpfile
__setobj__(@tmpfile)
end
def _close # :nodoc:
begin
@tmpfile.close if @tmpfile
ensure
@tmpfile = nil
@data[1] = nil if @data
end
end
protected :_close
# Closes the file. If +unlink_now+ is true, then the file will be unlinked
# (deleted) after closing. Of course, you can choose to later call #unlink
# if you do not unlink it now.
#
# If you don't explicitly unlink the temporary file, the removal
# will be delayed until the object is finalized.
def close(unlink_now=false)
if unlink_now
close!
else
_close
end
end
# Closes and unlinks (deletes) the file. Has the same effect as called
# <tt>close(true)</tt>.
def close!
_close
unlink
end
# Unlinks (deletes) the file from the filesystem. One should always unlink
# the file after using it, as is explained in the "Explicit close" good
# practice section in the Tempfile overview:
#
# file = Tempfile.new('foo')
# begin
# ...do something with file...
# ensure
# file.close
# file.unlink # deletes the temp file
# end
#
# === Unlink-before-close
#
# On POSIX systems it's possible to unlink a file before closing it. This
# practice is explained in detail in the Tempfile overview (section
# "Unlink after creation"); please refer there for more information.
#
# However, unlink-before-close may not be supported on non-POSIX operating
# systems. Microsoft Windows is the most notable case: unlinking a non-closed
# file will result in an error, which this method will silently ignore. If
# you want to practice unlink-before-close whenever possible, then you should
# write code like this:
#
# file = Tempfile.new('foo')
# file.unlink # On Windows this silently fails.
# begin
# ... do something with file ...
# ensure
# file.close! # Closes the file handle. If the file wasn't unlinked
# # because #unlink failed, then this method will attempt
# # to do so again.
# end
def unlink
return unless @tmpname
begin
File.unlink(@tmpname)
rescue Errno::ENOENT
rescue Errno::EACCES
# may not be able to unlink on Windows; just ignore
return
end
# remove tmpname from remover
@data[0] = @data[1] = nil
@tmpname = nil
ObjectSpace.undefine_finalizer(self)
end
alias delete unlink
# Returns the full path name of the temporary file.
# This will be nil if #unlink has been called.
def path
@tmpname
end
# Returns the size of the temporary file. As a side effect, the IO
# buffer is flushed before determining the size.
def size
if @tmpfile
@tmpfile.flush
@tmpfile.stat.size
elsif @tmpname
File.size(@tmpname)
else
0
end
end
alias length size
# :stopdoc:
def inspect
"#<#{self.class}:#{path}>"
end
class Remover
def initialize(data)
@pid = $$
@data = data
end
def call(*args)
return if @pid != $$
path, tmpfile = *@data
STDERR.print "removing ", path, "..." if $DEBUG
tmpfile.close if tmpfile
if path
begin
File.unlink(path)
rescue Errno::ENOENT
end
end
STDERR.print "done\n" if $DEBUG
end
end
# :startdoc:
class << self
# Creates a new Tempfile.
#
# If no block is given, this is a synonym for Tempfile.new.
#
# If a block is given, then a Tempfile object will be constructed,
# and the block is run with said object as argument. The Tempfile
# object will be automatically closed after the block terminates.
# The call returns the value of the block.
#
# In any case, all arguments (+*args+) will be passed to Tempfile.new.
#
# Tempfile.open('foo', '/home/temp') do |f|
# ... do something with f ...
# end
#
# # Equivalent:
# f = Tempfile.open('foo', '/home/temp')
# begin
# ... do something with f ...
# ensure
# f.close
# end
def open(*args)
tempfile = new(*args)
if block_given?
begin
yield(tempfile)
ensure
tempfile.close
end
else
tempfile
end
end
end
end
# Creates a temporally file as usual File object (not Tempfile).
# It don't use finalizer and delegation.
#
# If no block is given, this is similar to Tempfile.new except
# creating File instead of Tempfile.
# The created file is not removed automatically.
# You should use File.unlink to remove it.
#
# If a block is given, then a File object will be constructed,
# and the block is invoked with the object as the argument.
# The File object will be automatically closed and
# the temporally file is removed after the block terminates.
# The call returns the value of the block.
#
# In any case, all arguments (+*args+) will be treated as Tempfile.new.
#
# Tempfile.create('foo', '/home/temp') do |f|
# ... do something with f ...
# end
#
def Tempfile.create(basename, *rest)
tmpfile = nil
Dir::Tmpname.create(basename, *rest) do |tmpname, n, opts|
mode = File::RDWR|File::CREAT|File::EXCL
perm = 0600
if opts
mode |= opts.delete(:mode) || 0
opts[:perm] = perm
perm = nil
else
opts = perm
end
tmpfile = File.open(tmpname, mode, opts)
end
if block_given?
begin
yield tmpfile
ensure
tmpfile.close if !tmpfile.closed?
File.unlink tmpfile
end
else
tmpfile
end
end
if __FILE__ == $0
# $DEBUG = true
f = Tempfile.new("foo")
f.print("foo\n")
f.close
f.open
p f.gets # => "foo\n"
f.close!
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/profiler.rb | lib/profiler.rb | # Profile provides a way to Profile your Ruby application.
#
# Profiling your program is a way of determining which methods are called and
# how long each method takes to complete. This way you can detect which
# methods are possible bottlenecks.
#
# Profiling your program will slow down your execution time considerably,
# so activate it only when you need it. Don't confuse benchmarking with
# profiling.
#
# There are two ways to activate Profiling:
#
# == Command line
#
# Run your Ruby script with <code>-rprofile</code>:
#
# ruby -rprofile example.rb
#
# If you're profiling an executable in your <code>$PATH</code> you can use
# <code>ruby -S</code>:
#
# ruby -rprofile -S some_executable
#
# == From code
#
# Just require 'profile':
#
# require 'profile'
#
# def slow_method
# 5000.times do
# 9999999999999999*999999999
# end
# end
#
# def fast_method
# 5000.times do
# 9999999999999999+999999999
# end
# end
#
# slow_method
# fast_method
#
# The output in both cases is a report when the execution is over:
#
# ruby -rprofile example.rb
#
# % cumulative self self total
# time seconds seconds calls ms/call ms/call name
# 68.42 0.13 0.13 2 65.00 95.00 Integer#times
# 15.79 0.16 0.03 5000 0.01 0.01 Fixnum#*
# 15.79 0.19 0.03 5000 0.01 0.01 Fixnum#+
# 0.00 0.19 0.00 2 0.00 0.00 IO#set_encoding
# 0.00 0.19 0.00 1 0.00 100.00 Object#slow_method
# 0.00 0.19 0.00 2 0.00 0.00 Module#method_added
# 0.00 0.19 0.00 1 0.00 90.00 Object#fast_method
# 0.00 0.19 0.00 1 0.00 190.00 #toplevel
module Profiler__
class Wrapper < Struct.new(:defined_class, :method_id, :hash) # :nodoc:
private :defined_class=, :method_id=, :hash=
def initialize(klass, mid)
super(klass, mid, nil)
self.hash = Struct.instance_method(:hash).bind(self).call
end
def to_s
"#{defined_class.inspect}#".sub(/\A\#<Class:(.*)>#\z/, '\1.') << method_id.to_s
end
alias inspect to_s
end
# internal values
@@start = nil # the start time that profiling began
@@stacks = nil # the map of stacks keyed by thread
@@maps = nil # the map of call data keyed by thread, class and id. Call data contains the call count, total time,
PROFILE_CALL_PROC = TracePoint.new(*%i[call c_call b_call]) {|tp| # :nodoc:
now = Process.times[0]
stack = (@@stacks[Thread.current] ||= [])
stack.push [now, 0.0]
}
PROFILE_RETURN_PROC = TracePoint.new(*%i[return c_return b_return]) {|tp| # :nodoc:
now = Process.times[0]
key = Wrapper.new(tp.defined_class, tp.method_id)
stack = (@@stacks[Thread.current] ||= [])
if tick = stack.pop
threadmap = (@@maps[Thread.current] ||= {})
data = (threadmap[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
}
module_function
# Starts the profiler.
#
# See Profiler__ for more information.
def start_profile
@@start = Process.times[0]
@@stacks = {}
@@maps = {}
PROFILE_CALL_PROC.enable
PROFILE_RETURN_PROC.enable
end
# Stops the profiler.
#
# See Profiler__ for more information.
def stop_profile
PROFILE_CALL_PROC.disable
PROFILE_RETURN_PROC.disable
end
# Outputs the results from the profiler.
#
# See Profiler__ for more information.
def print_profile(f)
stop_profile
total = Process.times[0] - @@start
if total == 0 then total = 0.01 end
totals = {}
@@maps.values.each do |threadmap|
threadmap.each do |key, data|
total_data = (totals[key] ||= [0, 0.0, 0.0, key])
total_data[0] += data[0]
total_data[1] += data[1]
total_data[2] += data[2]
end
end
# Maybe we should show a per thread output and a totals view?
data = totals.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], 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
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/expect.rb | lib/expect.rb | $expect_verbose = false
# Expect library adds the IO instance method #expect, which does similar act to
# tcl's expect extension.
#
# In order to use this method, you must require expect:
#
# require 'expect'
#
# Please see #expect for usage.
class IO
# call-seq:
# IO#expect(pattern,timeout=9999999) -> Array
# IO#expect(pattern,timeout=9999999) { |result| ... } -> nil
#
# Reads from the IO until the given +pattern+ matches or the +timeout+ is over.
#
# It returns an array with the read buffer, followed by the matches.
# If a block is given, the result is yielded to the block and returns nil.
#
# When called without a block, it waits until the input that matches the
# given +pattern+ is obtained from the IO or the time specified as the
# timeout passes. An array is returned when the pattern is obtained from the
# IO. The first element of the array is the entire string obtained from the
# IO until the pattern matches, followed by elements indicating which the
# pattern which matched to the anchor in the regular expression.
#
# The optional timeout parameter defines, in seconds, the total time to wait
# for the pattern. If the timeout expires or eof is found, nil is returned
# or yielded. However, the buffer in a timeout session is kept for the next
# expect call. The default timeout is 9999999 seconds.
def expect(pat,timeout=9999999)
buf = ''
case pat
when String
e_pat = Regexp.new(Regexp.quote(pat))
when Regexp
e_pat = pat
else
raise TypeError, "unsupported pattern class: #{pat.class}"
end
@unusedBuf ||= ''
while true
if not @unusedBuf.empty?
c = @unusedBuf.slice!(0).chr
elsif !IO.select([self],nil,nil,timeout) or eof? then
result = nil
@unusedBuf = buf
break
else
c = getc.chr
end
buf << c
if $expect_verbose
STDOUT.print c
STDOUT.flush
end
if mat=e_pat.match(buf) then
result = [buf,*mat.to_a[1..-1]]
break
end
end
if block_given? then
yield result
else
return result
end
nil
end
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/timeout.rb | lib/timeout.rb | # Timeout long-running blocks
#
# == Synopsis
#
# require 'timeout'
# status = Timeout::timeout(5) {
# # Something that should be interrupted if it takes more than 5 seconds...
# }
#
# == Description
#
# Timeout provides a way to auto-terminate a potentially long-running
# operation if it hasn't finished in a fixed amount of time.
#
# Previous versions didn't use a module for namespacing, however
# #timeout is provided for backwards compatibility. You
# should prefer Timeout#timeout instead.
#
# == Copyright
#
# Copyright:: (C) 2000 Network Applied Communication Laboratory, Inc.
# Copyright:: (C) 2000 Information-technology Promotion Agency, Japan
module Timeout
# Raised by Timeout#timeout when the block times out.
class Error < RuntimeError
end
class ExitException < ::Exception # :nodoc:
attr_reader :thread
def self.catch(*args)
exc = new(*args)
exc.instance_variable_set(:@thread, Thread.current)
exc.freeze
::Kernel.catch(exc) {yield exc}
end
def exception(*)
if self.thread == Thread.current
bt = caller
begin
throw(self, bt)
rescue ArgumentError => e
raise unless e.message.start_with?("uncaught throw")
raise Error, message, backtrace
end
end
self
end
end
# :stopdoc:
THIS_FILE = /\A#{Regexp.quote(__FILE__)}:/o
CALLER_OFFSET = ((c = caller[0]) && THIS_FILE =~ c) ? 1 : 0
# :startdoc:
# Perform an operation in a block, raising an error if it takes longer than
# +sec+ seconds to complete.
#
# +sec+:: Number of seconds to wait for the block to terminate. Any number
# may be used, including Floats to specify fractional seconds. A
# value of 0 or +nil+ will execute the block without any timeout.
# +klass+:: Exception Class to raise if the block fails to terminate
# in +sec+ seconds. Omitting will use the default, Timeout::Error
#
# Returns the result of the block *if* the block completed before
# +sec+ seconds, otherwise throws an exception, based on the value of +klass+.
#
# The exception thrown to terminate the given block cannot be rescued inside
# the block unless +klass+ is given explicitly.
#
# Note that this is both a method of module Timeout, so you can <tt>include
# Timeout</tt> into your classes so they have a #timeout method, as well as
# a module method, so you can call it directly as Timeout.timeout().
def timeout(sec, klass = nil) #:yield: +sec+
return yield(sec) if sec == nil or sec.zero?
message = "execution expired"
e = Error
bl = proc do |exception|
begin
x = Thread.current
y = Thread.start {
begin
sleep sec
rescue => e
x.raise e
else
x.raise exception, message
end
}
return yield(sec)
ensure
if y
y.kill
y.join # make sure y is dead.
end
end
end
if klass
begin
bl.call(klass)
rescue klass => e
bt = e.backtrace
end
else
bt = ExitException.catch(message, &bl)
end
rej = /\A#{Regexp.quote(__FILE__)}:#{__LINE__-4}\z/o
bt.reject! {|m| rej =~ m}
level = -caller(CALLER_OFFSET).size
while THIS_FILE =~ bt[level]
bt.delete_at(level)
end
raise(e, message, bt)
end
module_function :timeout
end
# Identical to:
#
# Timeout::timeout(n, e, &block).
#
# This method is deprecated and provided only for backwards compatibility.
# You should use Timeout#timeout instead.
def timeout(n, e = nil, &block)
Timeout::timeout(n, e, &block)
end
# Another name for Timeout::Error, defined for backwards compatibility with
# earlier versions of timeout.rb.
TimeoutError = Timeout::Error
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/resolv.rb | lib/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 entire 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
begin
raise LoadError unless /mswin|mingw|cygwin/ =~ RUBY_PLATFORM
require 'win32/resolv'
DefaultFileName = Win32::Resolv.get_hosts_path
rescue LoadError
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, 'rb') {|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.
# :nameserver_port can be used to specify port number of nameserver address.
#
# The value of :nameserver should be an address string or
# an array of address strings.
# - :nameserver => '8.8.8.8'
# - :nameserver => ['8.8.8.8', '8.8.4.4']
#
# The value of :nameserver_port should be an array of
# pair of nameserver address and port number.
# - :nameserver_port => [['8.8.8.8', 53], ['8.8.4.4', 53]]
#
# 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
# Sets the resolver timeouts. This may be a single positive number
# or an array of positive numbers representing timeouts in seconds.
# If an array is specified, a DNS request will retry and wait for
# each successive interval in the array until a successful response
# is received. Specifying +nil+ reverts to the default timeouts:
# [ 5, second = 5 * 2 / nameserver_count, 2 * second, 4 * second ]
#
# Example:
#
# dns.timeouts = 3
#
def timeouts=(values)
@config.timeouts = values
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? # :nodoc:
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)
fetch_resource(name, typeclass) {|reply, reply_name|
extract_resources(reply, reply_name, typeclass, &proc)
}
end
def fetch_resource(name, typeclass)
lazy_initialize
requester = make_udp_requester
senders = {}
begin
@config.resolv(name) {|candidate, tout, nameserver, port|
msg = Message.new
msg.rd = 1
msg.add_question(candidate, typeclass)
unless sender = senders[[candidate, nameserver, port]]
sender = requester.sender(msg, candidate, nameserver, port)
next if !sender
senders[[candidate, nameserver, port]] = sender
end
reply, reply_name = requester.request(sender, tout)
case reply.rcode
when RCode::NoError
if reply.tc == 1 and not Requester::TCP === requester
requester.close
# Retry via TCP:
requester = make_tcp_requester(nameserver, port)
senders = {}
# This will use TCP for all remaining candidates (assuming the
# current candidate does not already respond successfully via
# TCP). This makes sense because we already know the full
# response will not fit in an untruncated UDP packet.
redo
else
yield(reply, reply_name)
end
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_udp_requester # :nodoc:
nameserver_port = @config.nameserver_port
if nameserver_port.length == 1
Requester::ConnectedUDP.new(*nameserver_port[0])
else
Requester::UnconnectedUDP.new(*nameserver_port)
end
end
def make_tcp_requester(host, port) # :nodoc:
return Requester::TCP.new(host, port)
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 = {} # :nodoc:
RequestIDMutex = Mutex.new # :nodoc:
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, bind_host="0.0.0.0") # :nodoc:
begin
port = rangerand(1024..65535)
udpsock.bind(bind_host, port)
rescue Errno::EADDRINUSE, Errno::EACCES
retry
end
end
class Requester # :nodoc:
def initialize
@senders = {}
@socks = nil
end
def request(sender, tout)
start = Time.now
timelimit = start + tout
begin
sender.send
rescue Errno::EHOSTUNREACH
# multi-homed IPv6 may generate this
raise ResolvTimeout
end
while true
before_select = Time.now
timeout = timelimit - before_select
if timeout <= 0
raise ResolvTimeout
end
select_result = IO.select(@socks, nil, nil, timeout)
if !select_result
after_select = Time.now
next if after_select < timelimit
raise ResolvTimeout
end
begin
reply, from = recv_reply(select_result[0])
rescue Errno::ECONNREFUSED, # GNU/Linux, FreeBSD
Errno::ECONNRESET # Windows
# No name server running on the server?
# Don't wait anymore.
raise ResolvTimeout
end
begin
msg = Message.decode(reply)
rescue DecodeError
next # broken DNS message ignored
end
if s = sender_for(from, msg)
break
else
# unexpected DNS message ignored
end
end
return msg, s.data
end
def sender_for(addr, msg)
@senders[[addr,msg.id]]
end
def close
socks = @socks
@socks = nil
if socks
socks.each {|sock| sock.close }
end
end
class Sender # :nodoc:
def initialize(msg, data, sock)
@msg = msg
@data = data
@sock = sock
end
end
class UnconnectedUDP < Requester # :nodoc:
def initialize(*nameserver_port)
super()
@nameserver_port = nameserver_port
@socks_hash = {}
@socks = []
nameserver_port.each {|host, port|
if host.index(':')
bind_host = "::"
af = Socket::AF_INET6
else
bind_host = "0.0.0.0"
af = Socket::AF_INET
end
next if @socks_hash[bind_host]
begin
sock = UDPSocket.new(af)
rescue Errno::EAFNOSUPPORT
next # The kernel doesn't support the address family.
end
sock.do_not_reverse_lookup = true
sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) if defined? Fcntl::F_SETFD
DNS.bind_random_port(sock, bind_host)
@socks << sock
@socks_hash[bind_host] = sock
}
end
def recv_reply(readable_socks)
reply, from = readable_socks[0].recvfrom(UDPSize)
return reply, [from[3],from[1]]
end
def sender(msg, data, host, port=Port)
sock = @socks_hash[host.index(':') ? "::" : "0.0.0.0"]
return nil if !sock
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
raise "@sock is nil." if @sock.nil?
@sock.send(@msg, 0, @host, @port)
end
end
end
class ConnectedUDP < Requester # :nodoc:
def initialize(host, port=Port)
super()
@host = host
@port = port
is_ipv6 = host.index(':')
sock = UDPSocket.new(is_ipv6 ? Socket::AF_INET6 : Socket::AF_INET)
@socks = [sock]
sock.do_not_reverse_lookup = true
sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) if defined? Fcntl::F_SETFD
DNS.bind_random_port(sock, is_ipv6 ? "::" : "0.0.0.0")
sock.connect(host, port)
end
def recv_reply(readable_socks)
reply = readable_socks[0].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, @socks[0])
end
def close
super
@senders.each_key {|from, id|
DNS.free_request_id(@host, @port, id)
}
end
class Sender < Requester::Sender # :nodoc:
def send
raise "@sock is nil." if @sock.nil?
@sock.send(@msg, 0)
end
attr_reader :data
end
end
class MDNSOneShot < UnconnectedUDP # :nodoc:
def sender(msg, data, host, port=Port)
id = DNS.allocate_request_id(host, port)
request = msg.encode
request[0,2] = [id].pack('n')
sock = @socks_hash[host.index(':') ? "::" : "0.0.0.0"]
return @senders[id] =
UnconnectedUDP::Sender.new(request, data, sock, host, port)
end
def sender_for(addr, msg)
@senders[msg.id]
end
end
class TCP < Requester # :nodoc:
def initialize(host, port=Port)
super()
@host = host
@port = port
sock = TCPSocket.new(@host, @port)
@socks = [sock]
sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) if defined? Fcntl::F_SETFD
@senders = {}
end
def recv_reply(readable_socks)
len = readable_socks[0].read(2).unpack('n')[0]
reply = @socks[0].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, @socks[0])
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
@timeouts = nil
end
def timeouts=(values)
if values
values = Array(values)
values.each do |t|
Numeric === t or raise ArgumentError, "#{t.inspect} is not numeric"
t > 0.0 or raise ArgumentError, "timeout=#{t} must be positive"
end
@timeouts = values
else
@timeouts = nil
end
end
def Config.parse_resolv_conf(filename)
nameserver = []
search = nil
ndots = 1
open(filename, 'rb') {|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
if /mswin|cygwin|mingw|bccwin/ =~ RUBY_PLATFORM
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_port = []
@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
if config_hash.include? :nameserver
@nameserver_port = config_hash[:nameserver].map {|ns| [ns, Port] }
end
if config_hash.include? :nameserver_port
@nameserver_port = config_hash[:nameserver_port].map {|ns, port| [ns, (port || Port)] }
end
@search = config_hash[:search] if config_hash.include? :search
@ndots = config_hash[:ndots] if config_hash.include? :ndots
if @nameserver_port.empty?
@nameserver_port << ['0.0.0.0', Port]
end
if @search
@search = @search.map {|arg| Label.split(arg) }
else
hostname = Socket.gethostname
if /\./ =~ hostname
@search = [Label.split($')]
else
@search = [[]]
end
end
if !@nameserver_port.kind_of?(Array) ||
@nameserver_port.any? {|ns_port|
!(Array === ns_port) ||
ns_port.length != 2
!(String === ns_port[0]) ||
!(Integer === ns_port[1])
}
raise ArgumentError.new("invalid nameserver config: #{@nameserver_port.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_port.length == 1
return @nameserver_port[0]
else
return nil
end
end
def nameserver_port
@nameserver_port
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_port.length
ts << ts[-1] * 2
ts << ts[-1] * 2
return ts
end
def resolv(name)
candidates = generate_candidates(name)
timeouts = @timeouts || generate_timeouts
begin
candidates.each {|candidate|
begin
timeouts.each {|tout|
@nameserver_port.each {|nameserver, port|
begin
yield candidate, tout, nameserver, port
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:
#
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | true |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/tracer.rb | lib/tracer.rb | #--
# $Release Version: 0.3$
# $Revision: 1.12 $
require "thread"
##
# Outputs a source level execution trace of a Ruby program.
#
# It does this by registering an event handler with Kernel#set_trace_func for
# processing incoming events. It also provides methods for filtering unwanted
# trace output (see Tracer.add_filter, Tracer.on, and Tracer.off).
#
# == Example
#
# Consider the following Ruby script
#
# class A
# def square(a)
# return a*a
# end
# end
#
# a = A.new
# a.square(5)
#
# Running the above script using <code>ruby -r tracer example.rb</code> will
# output the following trace to STDOUT (Note you can also explicitly
# <code>require 'tracer'</code>)
#
# #0:<internal:lib/rubygems/custom_require>:38:Kernel:<: -
# #0:example.rb:3::-: class A
# #0:example.rb:3::C: class A
# #0:example.rb:4::-: def square(a)
# #0:example.rb:7::E: end
# #0:example.rb:9::-: a = A.new
# #0:example.rb:10::-: a.square(5)
# #0:example.rb:4:A:>: def square(a)
# #0:example.rb:5:A:-: return a*a
# #0:example.rb:6:A:<: end
# | | | | |
# | | | | ---------------------+ event
# | | | ------------------------+ class
# | | --------------------------+ line
# | ------------------------------------+ filename
# ---------------------------------------+ thread
#
# Symbol table used for displaying incoming events:
#
# +}+:: call a C-language routine
# +{+:: return from a C-language routine
# +>+:: call a Ruby method
# +C+:: start a class or module definition
# +E+:: finish a class or module definition
# +-+:: execute code on a new line
# +^+:: raise an exception
# +<+:: return from a Ruby method
#
# == Copyright
#
# by Keiju ISHITSUKA(keiju@ishitsuka.com)
#
class Tracer
class << self
# display additional debug information (defaults to false)
attr_accessor :verbose
alias verbose? verbose
# output stream used to output trace (defaults to STDOUT)
attr_accessor :stdout
# mutex lock used by tracer for displaying trace output
attr_reader :stdout_mutex
# display process id in trace output (defaults to false)
attr_accessor :display_process_id
alias display_process_id? display_process_id
# display thread id in trace output (defaults to true)
attr_accessor :display_thread_id
alias display_thread_id? display_thread_id
# display C-routine calls in trace output (defaults to false)
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
# Symbol table used for displaying trace information
EVENT_SYMBOL = {
"line" => "-",
"call" => ">",
"return" => "<",
"class" => "C",
"end" => "E",
"raise" => "^",
"c-call" => "}",
"c-return" => "{",
"unknown" => "?"
}
def initialize # :nodoc:
@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 # :nodoc:
Tracer.stdout
end
def on # :nodoc:
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 # :nodoc:
set_trace_func nil
stdout.print "Trace off\n" if Tracer.verbose?
end
def add_filter(p = proc) # :nodoc:
@filters.push p
end
def set_get_line_procs(file, p = proc) # :nodoc:
@get_line_procs[file] = p
end
def get_line(file, line) # :nodoc:
if p = @get_line_procs[file]
return p.call(line)
end
unless list = SCRIPT_LINES__[file]
list = File.readlines(file) rescue []
SCRIPT_LINES__[file] = list
end
if l = list[line - 1]
l
else
"-\n"
end
end
def get_thread_no # :nodoc:
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, *) # :nodoc:
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
stdout.printf("%s:%d:%s:%s: %s",
file,
line,
klass || '',
EVENT_SYMBOL[event],
source)
end
end
end
# Reference to singleton instance of Tracer
Single = new
##
# Start tracing
#
# === Example
#
# Tracer.on
# # code to trace here
# Tracer.off
#
# You can also pass a block:
#
# Tracer.on {
# # trace everything in this block
# }
def Tracer.on
if block_given?
Single.on{yield}
else
Single.on
end
end
##
# Disable tracing
def Tracer.off
Single.off
end
##
# Register an event handler <code>p</code> which is called everytime a line
# in +file_name+ is executed.
#
# Example:
#
# Tracer.set_get_line_procs("example.rb", lambda { |line|
# puts "line number executed is #{line}"
# })
def Tracer.set_get_line_procs(file_name, p = proc)
Single.set_get_line_procs(file_name, p)
end
##
# Used to filter unwanted trace output
#
# Example which only outputs lines of code executed within the Kernel class:
#
# Tracer.add_filter do |event, file, line, id, binding, klass, *rest|
# "Kernel" == klass.to_s
# end
def Tracer.add_filter(p = proc)
Single.add_filter(p)
end
end
# :stopdoc:
SCRIPT_LINES__ = {} unless defined? SCRIPT_LINES__
if $0 == __FILE__
# direct call
$0 = ARGV[0]
ARGV.shift
Tracer.on
require $0
else
# call Tracer.on only if required by -r command-line option
count = caller.count {|bt| %r%/rubygems/core_ext/kernel_require\.rb:% !~ bt}
if (defined?(Gem) and count == 0) or
(!defined?(Gem) and count <= 1)
Tracer.on
end
end
# :startdoc:
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/rdoc.rb | lib/rdoc.rb | $DEBUG_RDOC = nil
# :main: README.rdoc
##
# RDoc produces documentation for Ruby source files by parsing the source and
# extracting the definition for classes, modules, methods, includes and
# requires. It associates these with optional documentation contained in an
# immediately preceding comment block then renders the result using an output
# formatter.
#
# For a simple introduction to writing or generating documentation using RDoc
# see the README.
#
# == Roadmap
#
# If you think you found a bug in RDoc see CONTRIBUTING@Bugs
#
# If you want to use RDoc to create documentation for your Ruby source files,
# see RDoc::Markup and refer to <tt>rdoc --help</tt> for command line usage.
#
# If you want to set the default markup format see
# RDoc::Markup@Supported+Formats
#
# If you want to store rdoc configuration in your gem (such as the default
# markup format) see RDoc::Options@Saved+Options
#
# If you want to write documentation for Ruby files see RDoc::Parser::Ruby
#
# If you want to write documentation for extensions written in C see
# RDoc::Parser::C
#
# If you want to generate documentation using <tt>rake</tt> see RDoc::Task.
#
# If you want to drive RDoc programmatically, see RDoc::RDoc.
#
# If you want to use the library to format text blocks into HTML or other
# formats, look at RDoc::Markup.
#
# If you want to make an RDoc plugin such as a generator or directive handler
# see RDoc::RDoc.
#
# If you want to write your own output generator see RDoc::Generator.
#
# If you want an overview of how RDoc works see CONTRIBUTING
#
# == Credits
#
# RDoc is currently being maintained by Eric Hodel <drbrain@segment7.net>.
#
# Dave Thomas <dave@pragmaticprogrammer.com> is the original author of RDoc.
#
# * 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.
module RDoc
##
# Exception thrown by any rdoc error.
class Error < RuntimeError; end
##
# RDoc version you are using
VERSION = '4.1.0'
##
# Method visibilities
VISIBILITIES = [:public, :protected, :private]
##
# Name of the dotfile that contains the description of files to be processed
# in the current directory
DOT_DOC_FILENAME = ".document"
##
# General RDoc modifiers
GENERAL_MODIFIERS = %w[nodoc].freeze
##
# RDoc modifiers for classes
CLASS_MODIFIERS = GENERAL_MODIFIERS
##
# RDoc modifiers for attributes
ATTR_MODIFIERS = GENERAL_MODIFIERS
##
# RDoc modifiers for constants
CONSTANT_MODIFIERS = GENERAL_MODIFIERS
##
# RDoc modifiers for methods
METHOD_MODIFIERS = GENERAL_MODIFIERS +
%w[arg args yield yields notnew not-new not_new doc]
##
# Loads the best available YAML library.
def self.load_yaml
begin
gem 'psych'
rescue Gem::LoadError
end
begin
require 'psych'
rescue ::LoadError
ensure
require 'yaml'
end
end
autoload :RDoc, 'rdoc/rdoc'
autoload :TestCase, 'rdoc/test_case'
autoload :CrossReference, 'rdoc/cross_reference'
autoload :ERBIO, 'rdoc/erbio'
autoload :ERBPartial, 'rdoc/erb_partial'
autoload :Encoding, 'rdoc/encoding'
autoload :Generator, 'rdoc/generator'
autoload :Options, 'rdoc/options'
autoload :Parser, 'rdoc/parser'
autoload :Servlet, 'rdoc/servlet'
autoload :RI, 'rdoc/ri'
autoload :Stats, 'rdoc/stats'
autoload :Store, 'rdoc/store'
autoload :Task, 'rdoc/task'
autoload :Text, 'rdoc/text'
autoload :Markdown, 'rdoc/markdown'
autoload :Markup, 'rdoc/markup'
autoload :RD, 'rdoc/rd'
autoload :TomDoc, 'rdoc/tom_doc'
autoload :KNOWN_CLASSES, 'rdoc/known_classes'
autoload :RubyLex, 'rdoc/ruby_lex'
autoload :RubyToken, 'rdoc/ruby_token'
autoload :TokenStream, 'rdoc/token_stream'
autoload :Comment, 'rdoc/comment'
# code objects
#
# We represent the various high-level code constructs that appear in Ruby
# programs: classes, modules, methods, and so on.
autoload :CodeObject, 'rdoc/code_object'
autoload :Context, 'rdoc/context'
autoload :TopLevel, 'rdoc/top_level'
autoload :AnonClass, 'rdoc/anon_class'
autoload :ClassModule, 'rdoc/class_module'
autoload :NormalClass, 'rdoc/normal_class'
autoload :NormalModule, 'rdoc/normal_module'
autoload :SingleClass, 'rdoc/single_class'
autoload :Alias, 'rdoc/alias'
autoload :AnyMethod, 'rdoc/any_method'
autoload :MethodAttr, 'rdoc/method_attr'
autoload :GhostMethod, 'rdoc/ghost_method'
autoload :MetaMethod, 'rdoc/meta_method'
autoload :Attr, 'rdoc/attr'
autoload :Constant, 'rdoc/constant'
autoload :Mixin, 'rdoc/mixin'
autoload :Include, 'rdoc/include'
autoload :Extend, 'rdoc/extend'
autoload :Require, 'rdoc/require'
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/sync.rb | lib/sync.rb | #
# sync.rb - 2 phase lock with counter
# $Release Version: 1.0$
# $Revision: 40825 $
# 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
##
# A module that provides a two-phase lock with a counter.
module Sync_m
# 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(singleton_class)
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
sync_try_lock_sub(mode)
end
end
def sync_lock(m = EX)
return unlock if m == UN
Thread.handle_interrupt(StandardError => :on_blocking) do
while true
@sync_mutex.synchronize do
begin
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
unless sync_waiting.include?(Thread.current) || sync_upgrade_waiting.reverse_each.any?{|w| w.first == Thread.current }
sync_waiting.push Thread.current
end
end
@sync_mutex.sleep
end
ensure
sync_waiting.delete(Thread.current)
end
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)
Thread.handle_interrupt(StandardError => :on_blocking) do
sync_lock(mode)
begin
yield
ensure
sync_unlock
end
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
##
# An alias for Sync_m from sync.rb
Synchronizer_m = Sync_m
##
# A class that provides two-phase lock with a counter. See Sync_m for
# details.
class Sync
include Sync_m
end
##
# An alias for Sync from sync.rb. See Sync_m for details.
Synchronizer = Sync
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/digest.rb | lib/digest.rb | require 'digest.so'
module Digest
def self.const_missing(name) # :nodoc:
case name
when :SHA256, :SHA384, :SHA512
lib = 'digest/sha2.so'
else
lib = File.join('digest', name.to_s.downcase)
end
begin
require lib
rescue LoadError
raise LoadError, "library not found for class Digest::#{name} -- #{lib}", caller(1)
end
unless Digest.const_defined?(name)
raise NameError, "uninitialized constant Digest::#{name}", caller(1)
end
Digest.const_get(name)
end
class ::Digest::Class
# Creates a digest object and reads a given file, _name_.
# Optional arguments are passed to the constructor of the digest
# class.
#
# p Digest::SHA256.file("X11R6.8.2-src.tar.bz2").hexdigest
# # => "f02e3c85572dc9ad7cb77c2a638e3be24cc1b5bea9fdbb0b0299c9668475c534"
def self.file(name, *args)
new(*args).file(name)
end
# Returns the base64 encoded hash value of a given _string_. The
# return value is properly padded with '=' and contains no line
# feeds.
def self.base64digest(str, *args)
[digest(str, *args)].pack('m0')
end
end
module Instance
# Updates the digest with the contents of a given file _name_ and
# returns self.
def file(name)
File.open(name, "rb") {|f|
buf = ""
while f.read(16384, buf)
update buf
end
}
self
end
# If none is given, returns the resulting hash value of the digest
# in a base64 encoded form, keeping the digest's state.
#
# If a +string+ is given, returns the hash value for the given
# +string+ in a base64 encoded form, resetting the digest to the
# initial state before and after the process.
#
# In either case, the return value is properly padded with '=' and
# contains no line feeds.
def base64digest(str = nil)
[str ? digest(str) : digest].pack('m0')
end
# Returns the resulting hash value and resets the digest to the
# initial state.
def base64digest!
[digest!].pack('m0')
end
end
end
# call-seq:
# Digest(name) -> digest_subclass
#
# Returns a Digest subclass by +name+.
#
# require 'digest'
#
# Digest("MD5")
# # => Digest::MD5
#
# Digest("Foo")
# # => LoadError: library not found for class Digest::Foo -- digest/foo
def Digest(name)
Digest.const_get(name)
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/tkmngfocus.rb | lib/tkmngfocus.rb | #
# tkmngfocus.rb - load tk/mngfocus.rb
#
require 'tk/mngfocus'
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/socket.rb | lib/socket.rb | require 'socket.so'
class Addrinfo
# creates an Addrinfo object from the arguments.
#
# The arguments are interpreted as similar to self.
#
# Addrinfo.tcp("0.0.0.0", 4649).family_addrinfo("www.ruby-lang.org", 80)
# #=> #<Addrinfo: 221.186.184.68:80 TCP (www.ruby-lang.org:80)>
#
# Addrinfo.unix("/tmp/sock").family_addrinfo("/tmp/sock2")
# #=> #<Addrinfo: /tmp/sock2 SOCK_STREAM>
#
def family_addrinfo(*args)
if args.empty?
raise ArgumentError, "no address specified"
elsif Addrinfo === args.first
raise ArgumentError, "too many arguments" if args.length != 1
addrinfo = args.first
if (self.pfamily != addrinfo.pfamily) ||
(self.socktype != addrinfo.socktype)
raise ArgumentError, "Addrinfo type mismatch"
end
addrinfo
elsif self.ip?
raise ArgumentError, "IP address needs host and port but #{args.length} arguments given" if args.length != 2
host, port = args
Addrinfo.getaddrinfo(host, port, self.pfamily, self.socktype, self.protocol)[0]
elsif self.unix?
raise ArgumentError, "UNIX socket needs single path argument but #{args.length} arguments given" if args.length != 1
path, = args
Addrinfo.unix(path)
else
raise ArgumentError, "unexpected family"
end
end
# creates a new Socket connected to the address of +local_addrinfo+.
#
# If _local_addrinfo_ is nil, the address of the socket is not bound.
#
# The _timeout_ specify the seconds for timeout.
# Errno::ETIMEDOUT is raised when timeout occur.
#
# If a block is given the created socket is yielded for each address.
#
def connect_internal(local_addrinfo, timeout=nil) # :yields: socket
sock = Socket.new(self.pfamily, self.socktype, self.protocol)
begin
sock.ipv6only! if self.ipv6?
sock.bind local_addrinfo if local_addrinfo
if timeout
begin
sock.connect_nonblock(self)
rescue IO::WaitWritable
if !IO.select(nil, [sock], nil, timeout)
raise Errno::ETIMEDOUT, 'user specified timeout'
end
begin
sock.connect_nonblock(self) # check connection failure
rescue Errno::EISCONN
end
end
else
sock.connect(self)
end
rescue Exception
sock.close
raise
end
if block_given?
begin
yield sock
ensure
sock.close if !sock.closed?
end
else
sock
end
end
private :connect_internal
# :call-seq:
# addrinfo.connect_from([local_addr_args], [opts]) {|socket| ... }
# addrinfo.connect_from([local_addr_args], [opts])
#
# creates a socket connected to the address of self.
#
# If one or more arguments given as _local_addr_args_,
# it is used as the local address of the socket.
# _local_addr_args_ is given for family_addrinfo to obtain actual address.
#
# If _local_addr_args_ is not given, the local address of the socket is not bound.
#
# The optional last argument _opts_ is options represented by a hash.
# _opts_ may have following options:
#
# [:timeout] specify the timeout in seconds.
#
# If a block is given, it is called with the socket and the value of the block is returned.
# The socket is returned otherwise.
#
# Addrinfo.tcp("www.ruby-lang.org", 80).connect_from("0.0.0.0", 4649) {|s|
# s.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n"
# puts s.read
# }
#
# # Addrinfo object can be taken for the argument.
# Addrinfo.tcp("www.ruby-lang.org", 80).connect_from(Addrinfo.tcp("0.0.0.0", 4649)) {|s|
# s.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n"
# puts s.read
# }
#
def connect_from(*args, &block)
opts = Hash === args.last ? args.pop : {}
local_addr_args = args
connect_internal(family_addrinfo(*local_addr_args), opts[:timeout], &block)
end
# :call-seq:
# addrinfo.connect([opts]) {|socket| ... }
# addrinfo.connect([opts])
#
# creates a socket connected to the address of self.
#
# The optional argument _opts_ is options represented by a hash.
# _opts_ may have following options:
#
# [:timeout] specify the timeout in seconds.
#
# If a block is given, it is called with the socket and the value of the block is returned.
# The socket is returned otherwise.
#
# Addrinfo.tcp("www.ruby-lang.org", 80).connect {|s|
# s.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n"
# puts s.read
# }
#
def connect(opts={}, &block)
connect_internal(nil, opts[:timeout], &block)
end
# :call-seq:
# addrinfo.connect_to([remote_addr_args], [opts]) {|socket| ... }
# addrinfo.connect_to([remote_addr_args], [opts])
#
# creates a socket connected to _remote_addr_args_ and bound to self.
#
# The optional last argument _opts_ is options represented by a hash.
# _opts_ may have following options:
#
# [:timeout] specify the timeout in seconds.
#
# If a block is given, it is called with the socket and the value of the block is returned.
# The socket is returned otherwise.
#
# Addrinfo.tcp("0.0.0.0", 4649).connect_to("www.ruby-lang.org", 80) {|s|
# s.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n"
# puts s.read
# }
#
def connect_to(*args, &block)
opts = Hash === args.last ? args.pop : {}
remote_addr_args = args
remote_addrinfo = family_addrinfo(*remote_addr_args)
remote_addrinfo.send(:connect_internal, self, opts[:timeout], &block)
end
# creates a socket bound to self.
#
# If a block is given, it is called with the socket and the value of the block is returned.
# The socket is returned otherwise.
#
# Addrinfo.udp("0.0.0.0", 9981).bind {|s|
# s.local_address.connect {|s| s.send "hello", 0 }
# p s.recv(10) #=> "hello"
# }
#
def bind
sock = Socket.new(self.pfamily, self.socktype, self.protocol)
begin
sock.ipv6only! if self.ipv6?
sock.setsockopt(:SOCKET, :REUSEADDR, 1)
sock.bind(self)
rescue Exception
sock.close
raise
end
if block_given?
begin
yield sock
ensure
sock.close if !sock.closed?
end
else
sock
end
end
# creates a listening socket bound to self.
def listen(backlog=Socket::SOMAXCONN)
sock = Socket.new(self.pfamily, self.socktype, self.protocol)
begin
sock.ipv6only! if self.ipv6?
sock.setsockopt(:SOCKET, :REUSEADDR, 1)
sock.bind(self)
sock.listen(backlog)
rescue Exception
sock.close
raise
end
if block_given?
begin
yield sock
ensure
sock.close if !sock.closed?
end
else
sock
end
end
# iterates over the list of Addrinfo objects obtained by Addrinfo.getaddrinfo.
#
# Addrinfo.foreach(nil, 80) {|x| p x }
# #=> #<Addrinfo: 127.0.0.1:80 TCP (:80)>
# # #<Addrinfo: 127.0.0.1:80 UDP (:80)>
# # #<Addrinfo: [::1]:80 TCP (:80)>
# # #<Addrinfo: [::1]:80 UDP (:80)>
#
def self.foreach(nodename, service, family=nil, socktype=nil, protocol=nil, flags=nil, &block)
Addrinfo.getaddrinfo(nodename, service, family, socktype, protocol, flags).each(&block)
end
end
class BasicSocket < IO
# Returns an address of the socket suitable for connect in the local machine.
#
# This method returns _self_.local_address, except following condition.
#
# - IPv4 unspecified address (0.0.0.0) is replaced by IPv4 loopback address (127.0.0.1).
# - IPv6 unspecified address (::) is replaced by IPv6 loopback address (::1).
#
# If the local address is not suitable for connect, SocketError is raised.
# IPv4 and IPv6 address which port is 0 is not suitable for connect.
# Unix domain socket which has no path is not suitable for connect.
#
# Addrinfo.tcp("0.0.0.0", 0).listen {|serv|
# p serv.connect_address #=> #<Addrinfo: 127.0.0.1:53660 TCP>
# serv.connect_address.connect {|c|
# s, _ = serv.accept
# p [c, s] #=> [#<Socket:fd 4>, #<Socket:fd 6>]
# }
# }
#
def connect_address
addr = local_address
afamily = addr.afamily
if afamily == Socket::AF_INET
raise SocketError, "unbound IPv4 socket" if addr.ip_port == 0
if addr.ip_address == "0.0.0.0"
addr = Addrinfo.new(["AF_INET", addr.ip_port, nil, "127.0.0.1"], addr.pfamily, addr.socktype, addr.protocol)
end
elsif defined?(Socket::AF_INET6) && afamily == Socket::AF_INET6
raise SocketError, "unbound IPv6 socket" if addr.ip_port == 0
if addr.ip_address == "::"
addr = Addrinfo.new(["AF_INET6", addr.ip_port, nil, "::1"], addr.pfamily, addr.socktype, addr.protocol)
elsif addr.ip_address == "0.0.0.0" # MacOS X 10.4 returns "a.b.c.d" for IPv4-mapped IPv6 address.
addr = Addrinfo.new(["AF_INET6", addr.ip_port, nil, "::1"], addr.pfamily, addr.socktype, addr.protocol)
elsif addr.ip_address == "::ffff:0.0.0.0" # MacOS X 10.6 returns "::ffff:a.b.c.d" for IPv4-mapped IPv6 address.
addr = Addrinfo.new(["AF_INET6", addr.ip_port, nil, "::1"], addr.pfamily, addr.socktype, addr.protocol)
end
elsif defined?(Socket::AF_UNIX) && afamily == Socket::AF_UNIX
raise SocketError, "unbound Unix socket" if addr.unix_path == ""
end
addr
end
end
class Socket < BasicSocket
# enable the socket option IPV6_V6ONLY if IPV6_V6ONLY is available.
def ipv6only!
if defined? Socket::IPV6_V6ONLY
self.setsockopt(:IPV6, :V6ONLY, 1)
end
end
# :call-seq:
# Socket.tcp(host, port, local_host=nil, local_port=nil, [opts]) {|socket| ... }
# Socket.tcp(host, port, local_host=nil, local_port=nil, [opts])
#
# creates a new socket object connected to host:port using TCP/IP.
#
# If local_host:local_port is given,
# the socket is bound to it.
#
# The optional last argument _opts_ is options represented by a hash.
# _opts_ may have following options:
#
# [:connect_timeout] specify the timeout in seconds.
#
# If a block is given, the block is called with the socket.
# The value of the block is returned.
# The socket is closed when this method returns.
#
# If no block is given, the socket is returned.
#
# Socket.tcp("www.ruby-lang.org", 80) {|sock|
# sock.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n"
# sock.close_write
# puts sock.read
# }
#
def self.tcp(host, port, *rest) # :yield: socket
opts = Hash === rest.last ? rest.pop : {}
raise ArgumentError, "wrong number of arguments (#{rest.length} for 2)" if 2 < rest.length
local_host, local_port = rest
last_error = nil
ret = nil
connect_timeout = opts[:connect_timeout]
local_addr_list = nil
if local_host != nil || local_port != nil
local_addr_list = Addrinfo.getaddrinfo(local_host, local_port, nil, :STREAM, nil)
end
Addrinfo.foreach(host, port, nil, :STREAM) {|ai|
if local_addr_list
local_addr = local_addr_list.find {|local_ai| local_ai.afamily == ai.afamily }
next if !local_addr
else
local_addr = nil
end
begin
sock = local_addr ?
ai.connect_from(local_addr, :timeout => connect_timeout) :
ai.connect(:timeout => connect_timeout)
rescue SystemCallError
last_error = $!
next
end
ret = sock
break
}
if !ret
if last_error
raise last_error
else
raise SocketError, "no appropriate local address"
end
end
if block_given?
begin
yield ret
ensure
ret.close if !ret.closed?
end
else
ret
end
end
# :stopdoc:
def self.ip_sockets_port0(ai_list, reuseaddr)
sockets = []
begin
sockets.clear
port = nil
ai_list.each {|ai|
begin
s = Socket.new(ai.pfamily, ai.socktype, ai.protocol)
rescue SystemCallError
next
end
sockets << s
s.ipv6only! if ai.ipv6?
if reuseaddr
s.setsockopt(:SOCKET, :REUSEADDR, 1)
end
if !port
s.bind(ai)
port = s.local_address.ip_port
else
s.bind(ai.family_addrinfo(ai.ip_address, port))
end
}
rescue Errno::EADDRINUSE
sockets.each {|s| s.close }
retry
rescue Exception
sockets.each {|s| s.close }
raise
end
sockets
end
class << self
private :ip_sockets_port0
end
def self.tcp_server_sockets_port0(host)
ai_list = Addrinfo.getaddrinfo(host, 0, nil, :STREAM, nil, Socket::AI_PASSIVE)
sockets = ip_sockets_port0(ai_list, true)
begin
sockets.each {|s|
s.listen(Socket::SOMAXCONN)
}
rescue Exception
sockets.each {|s| s.close }
raise
end
sockets
end
class << self
private :tcp_server_sockets_port0
end
# :startdoc:
# creates TCP/IP server sockets for _host_ and _port_.
# _host_ is optional.
#
# If no block given,
# it returns an array of listening sockets.
#
# If a block is given, the block is called with the sockets.
# The value of the block is returned.
# The socket is closed when this method returns.
#
# If _port_ is 0, actual port number is chosen dynamically.
# However all sockets in the result has same port number.
#
# # tcp_server_sockets returns two sockets.
# sockets = Socket.tcp_server_sockets(1296)
# p sockets #=> [#<Socket:fd 3>, #<Socket:fd 4>]
#
# # The sockets contains IPv6 and IPv4 sockets.
# sockets.each {|s| p s.local_address }
# #=> #<Addrinfo: [::]:1296 TCP>
# # #<Addrinfo: 0.0.0.0:1296 TCP>
#
# # IPv6 and IPv4 socket has same port number, 53114, even if it is chosen dynamically.
# sockets = Socket.tcp_server_sockets(0)
# sockets.each {|s| p s.local_address }
# #=> #<Addrinfo: [::]:53114 TCP>
# # #<Addrinfo: 0.0.0.0:53114 TCP>
#
# # The block is called with the sockets.
# Socket.tcp_server_sockets(0) {|sockets|
# p sockets #=> [#<Socket:fd 3>, #<Socket:fd 4>]
# }
#
def self.tcp_server_sockets(host=nil, port)
if port == 0
sockets = tcp_server_sockets_port0(host)
else
last_error = nil
sockets = []
begin
Addrinfo.foreach(host, port, nil, :STREAM, nil, Socket::AI_PASSIVE) {|ai|
begin
s = ai.listen
rescue SystemCallError
last_error = $!
next
end
sockets << s
}
if sockets.empty?
raise last_error
end
rescue Exception
sockets.each {|s| s.close }
raise
end
end
if block_given?
begin
yield sockets
ensure
sockets.each {|s| s.close if !s.closed? }
end
else
sockets
end
end
# yield socket and client address for each a connection accepted via given sockets.
#
# The arguments are a list of sockets.
# The individual argument should be a socket or an array of sockets.
#
# This method yields the block sequentially.
# It means that the next connection is not accepted until the block returns.
# So concurrent mechanism, thread for example, should be used to service multiple clients at a time.
#
def self.accept_loop(*sockets) # :yield: socket, client_addrinfo
sockets.flatten!(1)
if sockets.empty?
raise ArgumentError, "no sockets"
end
loop {
readable, _, _ = IO.select(sockets)
readable.each {|r|
begin
sock, addr = r.accept_nonblock
rescue IO::WaitReadable
next
end
yield sock, addr
}
}
end
# creates a TCP/IP server on _port_ and calls the block for each connection accepted.
# The block is called with a socket and a client_address as an Addrinfo object.
#
# If _host_ is specified, it is used with _port_ to determine the server addresses.
#
# The socket is *not* closed when the block returns.
# So application should close it explicitly.
#
# This method calls the block sequentially.
# It means that the next connection is not accepted until the block returns.
# So concurrent mechanism, thread for example, should be used to service multiple clients at a time.
#
# Note that Addrinfo.getaddrinfo is used to determine the server socket addresses.
# When Addrinfo.getaddrinfo returns two or more addresses,
# IPv4 and IPv6 address for example,
# all of them are used.
# Socket.tcp_server_loop succeeds if one socket can be used at least.
#
# # Sequential echo server.
# # It services only one client at a time.
# Socket.tcp_server_loop(16807) {|sock, client_addrinfo|
# begin
# IO.copy_stream(sock, sock)
# ensure
# sock.close
# end
# }
#
# # Threaded echo server
# # It services multiple clients at a time.
# # Note that it may accept connections too much.
# Socket.tcp_server_loop(16807) {|sock, client_addrinfo|
# Thread.new {
# begin
# IO.copy_stream(sock, sock)
# ensure
# sock.close
# end
# }
# }
#
def self.tcp_server_loop(host=nil, port, &b) # :yield: socket, client_addrinfo
tcp_server_sockets(host, port) {|sockets|
accept_loop(sockets, &b)
}
end
# :call-seq:
# Socket.udp_server_sockets([host, ] port)
#
# Creates UDP/IP sockets for a UDP server.
#
# If no block given, it returns an array of sockets.
#
# If a block is given, the block is called with the sockets.
# The value of the block is returned.
# The sockets are closed when this method returns.
#
# If _port_ is zero, some port is chosen.
# But the chosen port is used for the all sockets.
#
# # UDP/IP echo server
# Socket.udp_server_sockets(0) {|sockets|
# p sockets.first.local_address.ip_port #=> 32963
# Socket.udp_server_loop_on(sockets) {|msg, msg_src|
# msg_src.reply msg
# }
# }
#
def self.udp_server_sockets(host=nil, port)
last_error = nil
sockets = []
ipv6_recvpktinfo = nil
if defined? Socket::AncillaryData
if defined? Socket::IPV6_RECVPKTINFO # RFC 3542
ipv6_recvpktinfo = Socket::IPV6_RECVPKTINFO
elsif defined? Socket::IPV6_PKTINFO # RFC 2292
ipv6_recvpktinfo = Socket::IPV6_PKTINFO
end
end
local_addrs = Socket.ip_address_list
ip_list = []
Addrinfo.foreach(host, port, nil, :DGRAM, nil, Socket::AI_PASSIVE) {|ai|
if ai.ipv4? && ai.ip_address == "0.0.0.0"
local_addrs.each {|a|
next if !a.ipv4?
ip_list << Addrinfo.new(a.to_sockaddr, :INET, :DGRAM, 0);
}
elsif ai.ipv6? && ai.ip_address == "::" && !ipv6_recvpktinfo
local_addrs.each {|a|
next if !a.ipv6?
ip_list << Addrinfo.new(a.to_sockaddr, :INET6, :DGRAM, 0);
}
else
ip_list << ai
end
}
if port == 0
sockets = ip_sockets_port0(ip_list, false)
else
ip_list.each {|ip|
ai = Addrinfo.udp(ip.ip_address, port)
begin
s = ai.bind
rescue SystemCallError
last_error = $!
next
end
sockets << s
}
if sockets.empty?
raise last_error
end
end
sockets.each {|s|
ai = s.local_address
if ipv6_recvpktinfo && ai.ipv6? && ai.ip_address == "::"
s.setsockopt(:IPV6, ipv6_recvpktinfo, 1)
end
}
if block_given?
begin
yield sockets
ensure
sockets.each {|s| s.close if !s.closed? } if sockets
end
else
sockets
end
end
# :call-seq:
# Socket.udp_server_recv(sockets) {|msg, msg_src| ... }
#
# Receive UDP/IP packets from the given _sockets_.
# For each packet received, the block is called.
#
# The block receives _msg_ and _msg_src_.
# _msg_ is a string which is the payload of the received packet.
# _msg_src_ is a Socket::UDPSource object which is used for reply.
#
# Socket.udp_server_loop can be implemented using this method as follows.
#
# udp_server_sockets(host, port) {|sockets|
# loop {
# readable, _, _ = IO.select(sockets)
# udp_server_recv(readable) {|msg, msg_src| ... }
# }
# }
#
def self.udp_server_recv(sockets)
sockets.each {|r|
begin
msg, sender_addrinfo, _, *controls = r.recvmsg_nonblock
rescue IO::WaitReadable
next
end
ai = r.local_address
if ai.ipv6? and pktinfo = controls.find {|c| c.cmsg_is?(:IPV6, :PKTINFO) }
ai = Addrinfo.udp(pktinfo.ipv6_pktinfo_addr.ip_address, ai.ip_port)
yield msg, UDPSource.new(sender_addrinfo, ai) {|reply_msg|
r.sendmsg reply_msg, 0, sender_addrinfo, pktinfo
}
else
yield msg, UDPSource.new(sender_addrinfo, ai) {|reply_msg|
r.send reply_msg, 0, sender_addrinfo
}
end
}
end
# :call-seq:
# Socket.udp_server_loop_on(sockets) {|msg, msg_src| ... }
#
# Run UDP/IP server loop on the given sockets.
#
# The return value of Socket.udp_server_sockets is appropriate for the argument.
#
# It calls the block for each message received.
#
def self.udp_server_loop_on(sockets, &b) # :yield: msg, msg_src
loop {
readable, _, _ = IO.select(sockets)
udp_server_recv(readable, &b)
}
end
# :call-seq:
# Socket.udp_server_loop(port) {|msg, msg_src| ... }
# Socket.udp_server_loop(host, port) {|msg, msg_src| ... }
#
# creates a UDP/IP server on _port_ and calls the block for each message arrived.
# The block is called with the message and its source information.
#
# This method allocates sockets internally using _port_.
# If _host_ is specified, it is used conjunction with _port_ to determine the server addresses.
#
# The _msg_ is a string.
#
# The _msg_src_ is a Socket::UDPSource object.
# It is used for reply.
#
# # UDP/IP echo server.
# Socket.udp_server_loop(9261) {|msg, msg_src|
# msg_src.reply msg
# }
#
def self.udp_server_loop(host=nil, port, &b) # :yield: message, message_source
udp_server_sockets(host, port) {|sockets|
udp_server_loop_on(sockets, &b)
}
end
# UDP/IP address information used by Socket.udp_server_loop.
class UDPSource
# +remote_address+ is an Addrinfo object.
#
# +local_address+ is an Addrinfo object.
#
# +reply_proc+ is a Proc used to send reply back to the source.
def initialize(remote_address, local_address, &reply_proc)
@remote_address = remote_address
@local_address = local_address
@reply_proc = reply_proc
end
# Address of the source
attr_reader :remote_address
# Local address
attr_reader :local_address
def inspect # :nodoc:
"\#<#{self.class}: #{@remote_address.inspect_sockaddr} to #{@local_address.inspect_sockaddr}>"
end
# Sends the String +msg+ to the source
def reply(msg)
@reply_proc.call msg
end
end
# creates a new socket connected to path using UNIX socket socket.
#
# If a block is given, the block is called with the socket.
# The value of the block is returned.
# The socket is closed when this method returns.
#
# If no block is given, the socket is returned.
#
# # talk to /tmp/sock socket.
# Socket.unix("/tmp/sock") {|sock|
# t = Thread.new { IO.copy_stream(sock, STDOUT) }
# IO.copy_stream(STDIN, sock)
# t.join
# }
#
def self.unix(path) # :yield: socket
addr = Addrinfo.unix(path)
sock = addr.connect
if block_given?
begin
yield sock
ensure
sock.close if !sock.closed?
end
else
sock
end
end
# creates a UNIX server socket on _path_
#
# If no block given, it returns a listening socket.
#
# If a block is given, it is called with the socket and the block value is returned.
# When the block exits, the socket is closed and the socket file is removed.
#
# socket = Socket.unix_server_socket("/tmp/s")
# p socket #=> #<Socket:fd 3>
# p socket.local_address #=> #<Addrinfo: /tmp/s SOCK_STREAM>
#
# Socket.unix_server_socket("/tmp/sock") {|s|
# p s #=> #<Socket:fd 3>
# p s.local_address #=> # #<Addrinfo: /tmp/sock SOCK_STREAM>
# }
#
def self.unix_server_socket(path)
if !unix_socket_abstract_name?(path)
begin
st = File.lstat(path)
rescue Errno::ENOENT
end
if st && st.socket? && st.owned?
File.unlink path
end
end
s = Addrinfo.unix(path).listen
if block_given?
begin
yield s
ensure
s.close if !s.closed?
if !unix_socket_abstract_name?(path)
File.unlink path
end
end
else
s
end
end
class << self
private
def unix_socket_abstract_name?(path)
/linux/ =~ RUBY_PLATFORM && /\A(\0|\z)/ =~ path
end
end
# creates a UNIX socket server on _path_.
# It calls the block for each socket accepted.
#
# If _host_ is specified, it is used with _port_ to determine the server ports.
#
# The socket is *not* closed when the block returns.
# So application should close it.
#
# This method deletes the socket file pointed by _path_ at first if
# the file is a socket file and it is owned by the user of the application.
# This is safe only if the directory of _path_ is not changed by a malicious user.
# So don't use /tmp/malicious-users-directory/socket.
# Note that /tmp/socket and /tmp/your-private-directory/socket is safe assuming that /tmp has sticky bit.
#
# # Sequential echo server.
# # It services only one client at a time.
# Socket.unix_server_loop("/tmp/sock") {|sock, client_addrinfo|
# begin
# IO.copy_stream(sock, sock)
# ensure
# sock.close
# end
# }
#
def self.unix_server_loop(path, &b) # :yield: socket, client_addrinfo
unix_server_socket(path) {|serv|
accept_loop(serv, &b)
}
end
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/ostruct.rb | lib/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.
#
#
# An OpenStruct is a data structure, similar to a Hash, that allows the
# definition of arbitrary attributes with their accompanying values. This is
# accomplished by using Ruby's metaprogramming to define methods on the class
# itself.
#
# == Examples:
#
# require 'ostruct'
#
# person = OpenStruct.new
# person.name = "John Smith"
# person.age = 70
# person.pension = 300
#
# puts person.name # -> "John Smith"
# puts person.age # -> 70
# puts person.address # -> nil
#
# An OpenStruct employs a Hash internally to store the methods and values and
# can even be initialized with one:
#
# australia = OpenStruct.new(:country => "Australia", :population => 20_000_000)
# p australia # -> <OpenStruct country="Australia" population=20000000>
#
# Hash keys with spaces or characters that would normally not be able to use for
# method calls (e.g. ()[]*) will not be immediately available on the
# OpenStruct object as a method for retrieval or assignment, but can be still be
# reached through the Object#send method.
#
# measurements = OpenStruct.new("length (in inches)" => 24)
# measurements.send("length (in inches)") # -> 24
#
# data_point = OpenStruct.new(:queued? => true)
# data_point.queued? # -> true
# data_point.send("queued?=",false)
# data_point.queued? # -> false
#
# Removing the presence of a method requires the execution the delete_field
# method as setting the property value to +nil+ will not remove the method.
#
# first_pet = OpenStruct.new(:name => 'Rowdy', :owner => 'John Smith')
# first_pet.owner = nil
# second_pet = OpenStruct.new(:name => 'Rowdy')
#
# first_pet == second_pet # -> false
#
# first_pet.delete_field(:owner)
# first_pet == second_pet # -> true
#
#
# == Implementation:
#
# An OpenStruct utilizes Ruby's method lookup structure to find and define the
# necessary methods for properties. This is accomplished through the method
# method_missing and define_method.
#
# This should be a consideration if there is a concern about the performance of
# the objects that are created, as there is much more overhead in the setting
# of these properties compared to using a Hash or a Struct.
#
class OpenStruct
#
# Creates a new OpenStruct object. By default, the resulting OpenStruct
# object will have no attributes.
#
# The optional +hash+, if given, will generate attributes and values
# (can be a Hash, an OpenStruct or a Struct).
# For example:
#
# require 'ostruct'
# hash = { "country" => "Australia", :population => 20_000_000 }
# data = OpenStruct.new(hash)
#
# p data # -> <OpenStruct country="Australia" population=20000000>
#
def initialize(hash=nil)
@table = {}
if hash
hash.each_pair do |k, v|
k = k.to_sym
@table[k] = v
new_ostruct_member(k)
end
end
end
# Duplicate an OpenStruct object members.
def initialize_copy(orig)
super
@table = @table.dup
@table.each_key{|key| new_ostruct_member(key)}
end
#
# Converts the OpenStruct to a hash with keys representing
# each attribute (as symbols) and their corresponding values
# Example:
#
# require 'ostruct'
# data = OpenStruct.new("country" => "Australia", :population => 20_000_000)
# data.to_h # => {:country => "Australia", :population => 20000000 }
#
def to_h
@table.dup
end
#
# Yields all attributes (as a symbol) along with the corresponding values
# or returns an enumerator if not block is given.
# Example:
#
# require 'ostruct'
# data = OpenStruct.new("country" => "Australia", :population => 20_000_000)
# data.each_pair.to_a # => [[:country, "Australia"], [:population, 20000000]]
#
def each_pair
return to_enum(__method__) { @table.size } unless block_given?
@table.each_pair{|p| yield p}
end
#
# Provides marshalling support for use by the Marshal library.
#
def marshal_dump
@table
end
#
# Provides marshalling support for use by the Marshal library.
#
def marshal_load(x)
@table = x
@table.each_key{|key| new_ostruct_member(key)}
end
#
# Used internally to check if the OpenStruct is able to be
# modified before granting access to the internal Hash table to be modified.
#
def modifiable
begin
@modifiable = true
rescue
raise RuntimeError, "can't modify frozen #{self.class}", caller(3)
end
@table
end
protected :modifiable
#
# Used internally to defined properties on the
# OpenStruct. It does this by using the metaprogramming function
# define_singleton_method for both the getter method and the setter method.
#
def new_ostruct_member(name)
name = name.to_sym
unless respond_to?(name)
define_singleton_method(name) { @table[name] }
define_singleton_method("#{name}=") { |x| modifiable[name] = x }
end
name
end
protected :new_ostruct_member
def method_missing(mid, *args) # :nodoc:
mname = mid.id2name
len = args.length
if mname.chomp!('=')
if len != 1
raise ArgumentError, "wrong number of arguments (#{len} for 1)", caller(1)
end
modifiable[new_ostruct_member(mname)] = args[0]
elsif len == 0
@table[mid]
else
err = NoMethodError.new "undefined method `#{mid}' for #{self}", mid, args
err.set_backtrace caller(1)
raise err
end
end
# Returns the value of a member.
#
# person = OpenStruct.new('name' => 'John Smith', 'age' => 70)
# person[:age] # => 70, same as ostruct.age
#
def [](name)
@table[name.to_sym]
end
#
# Sets the value of a member.
#
# person = OpenStruct.new('name' => 'John Smith', 'age' => 70)
# person[:age] = 42 # => equivalent to ostruct.age = 42
# person.age # => 42
#
def []=(name, value)
modifiable[new_ostruct_member(name)] = value
end
#
# Remove the named field from the object. Returns the value that the field
# contained if it was defined.
#
# require 'ostruct'
#
# person = OpenStruct.new('name' => 'John Smith', 'age' => 70)
#
# person.delete_field('name') # => 'John Smith'
#
def delete_field(name)
sym = name.to_sym
singleton_class.__send__(:remove_method, sym, "#{sym}=")
@table.delete sym
end
InspectKey = :__inspect_key__ # :nodoc:
#
# Returns a string containing a detailed summary of the keys and values.
#
def inspect
str = "#<#{self.class}"
ids = (Thread.current[InspectKey] ||= [])
if ids.include?(object_id)
return str << ' ...>'
end
ids << object_id
begin
first = true
for k,v in @table
str << "," unless first
first = false
str << " #{k}=#{v.inspect}"
end
return str << '>'
ensure
ids.pop
end
end
alias :to_s :inspect
attr_reader :table # :nodoc:
protected :table
#
# Compares this object and +other+ for equality. An OpenStruct is equal to
# +other+ when +other+ is an OpenStruct and the two objects' Hash tables are
# equal.
#
def ==(other)
return false unless other.kind_of?(OpenStruct)
@table == other.table
end
#
# Compares this object and +other+ for equality. An OpenStruct is eql? to
# +other+ when +other+ is an OpenStruct and the two objects' Hash tables are
# eql?.
#
def eql?(other)
return false unless other.kind_of?(OpenStruct)
@table.eql?(other.table)
end
# Compute a hash-code for this OpenStruct.
# Two hashes with the same content will have the same hash code
# (and will be eql?).
def hash
@table.hash
end
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/benchmark.rb | lib/benchmark.rb | #--
# benchmark.rb - a performance benchmarking library
#
# $Id: benchmark.rb 43002 2013-09-20 16:05:48Z zzak $
#
# Created by Gotoken (gotoken@notwork.org).
#
# Documentation by Gotoken (original RD), Lyle Johnson (RDoc conversion), and
# Gavin Sinclair (editing).
#++
#
# == 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
# <code>"a"*1_000_000_000</code>:
#
# require 'benchmark'
#
# puts Benchmark.measure { "a"*1_000_000_000 }
#
# On my machine (OSX 10.8.3 on i5 1.7 Ghz) this generates:
#
# 0.350000 0.400000 0.750000 ( 0.835234)
#
# 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 = 5000000
# 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.010000 0.000000 1.010000 ( 1.014479)
# 1.000000 0.000000 1.000000 ( 0.998261)
# 0.980000 0.000000 0.980000 ( 0.981335)
#
# * Continuing the previous example, put a label in each report:
#
# require 'benchmark'
#
# n = 5000000
# 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.010000 0.000000 1.010000 ( 1.015688)
# times: 1.000000 0.000000 1.000000 ( 1.003611)
# upto: 1.030000 0.000000 1.030000 ( 1.028098)
#
# * 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! 1.490000 0.010000 1.500000 ( 1.490520)
# sort 1.460000 0.000000 1.460000 ( 1.463025)
# -------------------------------- total: 2.960000sec
#
# user system total real
# sort! 1.460000 0.000000 1.460000 ( 1.460465)
# sort 1.450000 0.010000 1.460000 ( 1.448327)
#
# * Report statistics of sequential experiments with unique labels,
# using the #benchmark method:
#
# require 'benchmark'
# include Benchmark # we need the CAPTION and FORMAT constants
#
# n = 5000000
# Benchmark.benchmark(CAPTION, 7, FORMAT, ">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: 0.950000 0.000000 0.950000 ( 0.952039)
# times: 0.980000 0.000000 0.980000 ( 0.984938)
# upto: 0.950000 0.000000 0.950000 ( 0.946787)
# >total: 2.880000 0.000000 2.880000 ( 2.883764)
# >avg: 0.960000 0.000000 0.960000 ( 0.961255)
module Benchmark
BENCHMARK_VERSION = "2002-04-25" # :nodoc:
# Invokes the block with a Benchmark::Report object, which
# may be used to collect and report on the results of individual
# benchmark tests. Reserves +label_width+ leading spaces for
# labels on each line. Prints +caption+ at the top of the
# report, and uses +format+ to format each line.
# Returns an array of Benchmark::Tms objects.
#
# If the block returns an array of
# Benchmark::Tms 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 FORMAT constants
#
# n = 5000000
# Benchmark.benchmark(CAPTION, 7, FORMAT, ">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
#
# Generates:
#
# user system total real
# for: 0.970000 0.000000 0.970000 ( 0.970493)
# times: 0.990000 0.000000 0.990000 ( 0.989542)
# upto: 0.970000 0.000000 0.970000 ( 0.972854)
# >total: 2.930000 0.000000 2.930000 ( 2.932889)
# >avg: 0.976667 0.000000 0.976667 ( 0.977630)
#
def benchmark(caption = "", label_width = nil, format = nil, *labels) # :yield: report
sync = STDOUT.sync
STDOUT.sync = true
label_width ||= 0
label_width += 1
format ||= FORMAT
print ' '*label_width + caption unless caption.empty?
report = Report.new(label_width, format)
results = yield(report)
Array === results and results.grep(Tms).each {|t|
print((labels.shift || t.label || "").ljust(label_width), t.format(format))
}
report.list
ensure
STDOUT.sync = sync unless sync.nil?
end
# A simple interface to the #benchmark method, #bm generates sequential
# reports with labels. The parameters have the same meaning as for
# #benchmark.
#
# require 'benchmark'
#
# n = 5000000
# 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
#
# Generates:
#
# user system total real
# for: 0.960000 0.000000 0.960000 ( 0.957966)
# times: 0.960000 0.000000 0.960000 ( 0.960423)
# upto: 0.950000 0.000000 0.950000 ( 0.954864)
#
def bm(label_width = 0, *labels, &blk) # :yield: report
benchmark(CAPTION, label_width, FORMAT, *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. GC.start 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
#
# Generates:
#
# Rehearsal -----------------------------------------
# sort! 1.440000 0.010000 1.450000 ( 1.446833)
# sort 1.440000 0.000000 1.440000 ( 1.448257)
# -------------------------------- total: 2.890000sec
#
# user system total real
# sort! 1.460000 0.000000 1.460000 ( 1.458065)
# sort 1.450000 0.000000 1.450000 ( 1.455963)
#
# #bmbm yields a Benchmark::Job object and returns an array of
# Benchmark::Tms objects.
#
def bmbm(width = 0) # :yield: job
job = Job.new(width)
yield(job)
width = job.width + 1
sync = STDOUT.sync
STDOUT.sync = true
# rehearsal
puts 'Rehearsal '.ljust(width+CAPTION.length,'-')
ets = job.list.inject(Tms.new) { |sum,(label,item)|
print label.ljust(width)
res = Benchmark.measure(&item)
print res.format
sum + res
}.format("total: %tsec")
print " #{ets}\n\n".rjust(width+CAPTION.length+2,'-')
# take
print ' '*width + CAPTION
job.list.map { |label,item|
GC.start
print label.ljust(width)
Benchmark.measure(label, &item).tap { |res| print res }
}
ensure
STDOUT.sync = sync unless sync.nil?
end
#
# Returns the time used to execute the given block as a
# Benchmark::Tms object.
#
def measure(label = "") # :yield:
t0, r0 = Process.times, Time.now
yield
t1, r1 = Process.times, Time.now
Benchmark::Tms.new(t1.utime - t0.utime,
t1.stime - t0.stime,
t1.cutime - t0.cutime,
t1.cstime - t0.cstime,
r1 - r0,
label)
end
#
# Returns the elapsed real time used to execute the given block.
#
def realtime # :yield:
r0 = Time.now
yield
Time.now - r0
end
module_function :benchmark, :measure, :realtime, :bm, :bmbm
#
# 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 = label.to_s
w = label.length
@width = w if @width < w
@list << [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.
attr_reader :width
end
#
# 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 +format+ are the label offset and
# format string used by Tms#format.
#
def initialize(width = 0, format = nil)
@width, @format, @list = width, format, []
end
#
# Prints the +label+ and measured time for the block,
# formatted by +format+. See Tms#format for the
# formatting rules.
#
def item(label = "", *format, &blk) # :yield:
print label.to_s.ljust(@width)
@list << res = Benchmark.measure(label, &blk)
print res.format(@format, *format)
res
end
alias report item
# An array of Benchmark::Tms objects representing each item.
attr_reader :list
end
#
# A data object, representing the times associated with a benchmark
# measurement.
#
class Tms
# Default caption, see also Benchmark::CAPTION
CAPTION = " user system total real\n"
# Default format string, see also Benchmark::FORMAT
FORMAT = "%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
# +utime+ as the user CPU time, +stime+ as the system CPU time,
# +cutime+ as the children's user CPU time, +cstime+ as the children's
# system CPU time, +real+ as the elapsed real time and +label+ as the label.
#
def initialize(utime = 0.0, stime = 0.0, cutime = 0.0, cstime = 0.0, real = 0.0, label = nil)
@utime, @stime, @cutime, @cstime, @real, @label = utime, stime, cutime, cstime, real, label.to_s
@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!(&blk)
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 _format_ is not given, FORMAT is used as default value, detailing the
# user, system and real elapsed time.
#
def format(format = nil, *args)
str = (format || FORMAT).dup
str.gsub!(/(%[-+.\d]*)n/) { "#{$1}s" % label }
str.gsub!(/(%[-+.\d]*)u/) { "#{$1}f" % utime }
str.gsub!(/(%[-+.\d]*)y/) { "#{$1}f" % stime }
str.gsub!(/(%[-+.\d]*)U/) { "#{$1}f" % cutime }
str.gsub!(/(%[-+.\d]*)Y/) { "#{$1}f" % cstime }
str.gsub!(/(%[-+.\d]*)t/) { "#{$1}f" % total }
str.gsub!(/(%[-+.\d]*)r/) { "(#{$1}f)" % real }
format ? str % args : str
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
#
# Returns a new Tms object obtained by memberwise operation +op+
# of the individual times for this Tms object with those of the other
# Tms object.
#
# +op+ can be a mathematical operation such as <tt>+</tt>, <tt>-</tt>,
# <tt>*</tt>, <tt>/</tt>
#
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.
FORMAT = Benchmark::Tms::FORMAT
end
if __FILE__ == $0
include Benchmark
n = ARGV[0].to_i.nonzero? || 50000
puts %Q([#{n} times iterations of `a = "1"'])
benchmark(CAPTION, 7, FORMAT) do |x|
x.report("for:") {for _ in 1..n; _ = "1"; end} # Benchmark.measure
x.report("times:") {n.times do ; _ = "1"; end}
x.report("upto:") {1.upto(n) do ; _ = "1"; end}
end
benchmark do
[
measure{for _ in 1..n; _ = "1"; end}, # Benchmark.measure
measure{n.times do ; _ = "1"; end},
measure{1.upto(n) do ; _ = "1"; end}
]
end
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/set.rb | lib/set.rb | #--
# set.rb - defines the Set class
#++
# Copyright (c) 2002-2013 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 43808 2013-11-22 23:50:06Z tmm1 $
#
# == 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 sorted in some order, 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.
#
# 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.
#
# Set uses Hash as storage, so you must note the following points:
#
# * Equality of elements is determined according to Object#eql? and
# Object#hash.
# * Set assumes that the identity of each element does not change
# while it is stored. Modifying an element of a set will render the
# set to an unreliable state.
# * When a string is to be stored, a frozen copy of the string is
# stored instead unless the original string is already frozen.
#
# == Comparison
#
# The comparison operators <, >, <= and >= are implemented as
# shorthand for the {proper_,}{subset?,superset?} methods. However,
# the <=> operator is intentionally left out because not every pair of
# sets is comparable. ({x,y} vs. {x,z} for example)
#
# == 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: {1, 2, "foo", 6}>
# 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
do_with_enum(enum) { |o| add(block[o]) }
else
merge(enum)
end
end
def do_with_enum(enum, &block) # :nodoc:
if enum.respond_to?(:each_entry)
enum.each_entry(&block)
elsif enum.respond_to?(:each)
enum.each(&block)
else
raise ArgumentError, "value must be enumerable"
end
end
private :do_with_enum
# Copy internal hash.
def initialize_copy(orig)
@hash = orig.instance_variable_get(:@hash).dup
end
def freeze # :nodoc:
@hash.freeze
super
end
def taint # :nodoc:
@hash.taint
super
end
def untaint # :nodoc:
@hash.untaint
super
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.instance_of?(self.class)
@hash.replace(enum.instance_variable_get(:@hash))
else
clear
merge(enum)
end
self
end
# Converts the set to an array. The order of elements is uncertain.
def to_a
@hash.keys
end
# Returns self if no arguments are given. Otherwise, converts the
# set to another with klass.new(self, *args, &block).
#
# In subclasses, returns klass.new(self, *args, &block) unless
# overridden.
def to_set(klass = Set, *args, &block)
return self if instance_of?(Set) && klass == Set && block.nil? && args.empty?
klass.new(self, *args, &block)
end
def flatten_merge(set, seen = Set.new) # :nodoc:
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
alias >= superset?
# 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
alias > proper_superset?
# 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
alias <= subset?
# 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
alias < proper_subset?
# Returns true if the set and the given set have at least one
# element in common.
def intersect?(set)
set.is_a?(Set) or raise ArgumentError, "value must be a set"
if size < set.size
any? { |o| set.include?(o) }
else
set.any? { |o| include?(o) }
end
end
# Returns true if the set and the given set have no element in
# common. This method is the opposite of +intersect?+.
def disjoint?(set)
!intersect?(set)
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)
block or return enum_for(__method__)
@hash.each_key(&block)
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__)
# @hash.delete_if should be faster, but using it breaks the order
# of enumeration in subclasses.
select { |o| yield o }.each { |o| @hash.delete(o) }
self
end
# Deletes every element of the set for which block evaluates to
# false, and returns self.
def keep_if
block_given? or return enum_for(__method__)
# @hash.keep_if should be faster, but using it breaks the order of
# enumeration in subclasses.
reject { |o| yield o }.each { |o| @hash.delete(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)
block or return enum_for(__method__)
n = size
delete_if(&block)
size == n ? nil : self
end
# Equivalent to Set#keep_if, but returns nil if no changes were
# made.
def select!(&block)
block or return enum_for(__method__)
n = size
keep_if(&block)
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
do_with_enum(enum) { |o| add(o) }
end
self
end
# Deletes every element that appears in the given enumerable object
# and returns self.
def subtract(enum)
do_with_enum(enum) { |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
do_with_enum(enum) { |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 ==(other)
if self.equal?(other)
true
elsif other.instance_of?(self.class)
@hash == other.instance_variable_get(:@hash)
elsif other.is_a?(Set) && self.size == other.size
other.all? { |o| @hash.include?(o) }
else
false
end
end
def hash # :nodoc:
@hash.hash
end
def eql?(o) # :nodoc:
return false unless o.is_a?(Set)
@hash.eql?(o.instance_variable_get(:@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
}
begin
require 'rbtree'
module_eval <<-END, __FILE__, __LINE__+1
def initialize(*args)
@hash = RBTree.new
super
end
def add(o)
o.respond_to?(:<=>) or raise ArgumentError, "value must respond to <=>"
super
end
alias << add
END
rescue LoadError
module_eval <<-END, __FILE__, __LINE__+1
def initialize(*args)
@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 keep_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)
block or return enum_for(__method__)
to_a.each(&block)
self
end
def to_a
(@keys = @hash.keys).sort! unless @keys
@keys
end
END
end
module_eval {
# a hack to shut up warning
remove_method :old_init
}
@@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)
# enum.respond_to?(:each) or raise ArgumentError, "value must be enumerable"
# clear
# enum.each_entry { |o| add(o) }
#
# self
# end
#
# def merge(enum)
# enum.respond_to?(:each) or raise ArgumentError, "value must be enumerable"
# enum.each_entry { |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
# Tests have been moved to test/test_set.rb.
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/time.rb | lib/time.rb | require 'date'
# = time.rb
#
# When 'time' is required, Time is extended with additional methods for parsing
# and converting Times.
#
# == Features
#
# This library extends the Time class with the following conversions between
# date strings and Time objects:
#
# * date-time defined by {RFC 2822}[http://www.ietf.org/rfc/rfc2822.txt]
# * HTTP-date defined by {RFC 2616}[http://www.ietf.org/rfc/rfc2616.txt]
# * dateTime defined by XML Schema Part 2: Datatypes ({ISO
# 8601}[http://www.iso.org/iso/date_and_time_format])
# * various formats handled by Date._parse
# * custom formats handled by Date._strptime
#
# == Examples
#
# All examples assume you have loaded Time with:
#
# require 'time'
#
# All of these examples were done using the EST timezone which is GMT-5.
#
# === Converting to a String
#
# t = Time.now
# t.iso8601 # => "2011-10-05T22:26:12-04:00"
# t.rfc2822 # => "Wed, 05 Oct 2011 22:26:12 -0400"
# t.httpdate # => "Thu, 06 Oct 2011 02:26:12 GMT"
#
# === Time.parse
#
# #parse takes a string representation of a Time and attempts to parse it
# using a heuristic.
#
# Date.parse("2010-10-31") #=> 2010-10-31 00:00:00 -0500
#
# Any missing pieces of the date are inferred based on the current date.
#
# # assuming the current date is "2011-10-31"
# Time.parse("12:00") #=> 2011-10-31 12:00:00 -0500
#
# We can change the date used to infer our missing elements by passing a second
# object that responds to #mon, #day and #year, such as Date, Time or DateTime.
# We can also use our own object.
#
# class MyDate
# attr_reader :mon, :day, :year
#
# def initialize(mon, day, year)
# @mon, @day, @year = mon, day, year
# end
# end
#
# d = Date.parse("2010-10-28")
# t = Time.parse("2010-10-29")
# dt = DateTime.parse("2010-10-30")
# md = MyDate.new(10,31,2010)
#
# Time.parse("12:00", d) #=> 2010-10-28 12:00:00 -0500
# Time.parse("12:00", t) #=> 2010-10-29 12:00:00 -0500
# Time.parse("12:00", dt) #=> 2010-10-30 12:00:00 -0500
# Time.parse("12:00", md) #=> 2010-10-31 12:00:00 -0500
#
# #parse also accepts an optional block. You can use this block to specify how
# to handle the year component of the date. This is specifically designed for
# handling two digit years. For example, if you wanted to treat all two digit
# years prior to 70 as the year 2000+ you could write this:
#
# Time.parse("01-10-31") {|year| year + (year < 70 ? 2000 : 1900)}
# #=> 2001-10-31 00:00:00 -0500
# Time.parse("70-10-31") {|year| year + (year < 70 ? 2000 : 1900)}
# #=> 1970-10-31 00:00:00 -0500
#
# === Time.strptime
#
# #strptime works similar to +parse+ except that instead of using a heuristic
# to detect the format of the input string, you provide a second argument that
# describes the format of the string. For example:
#
# Time.strptime("2000-10-31", "%Y-%m-%d") #=> 2000-10-31 00:00:00 -0500
class Time
class << Time
#
# A hash of timezones mapped to hour differences from UTC. The
# set of time zones corresponds to the ones specified by RFC 2822
# and ISO 8601.
#
ZoneOffset = { # :nodoc:
'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,
}
#
# Return the number of seconds the specified time zone differs
# from UTC.
#
# Numeric time zones that include minutes, such as
# <code>-10:00</code> or <code>+1330</code> will work, as will
# simpler hour-only time zones like <code>-10</code> or
# <code>+13</code>.
#
# Textual time zones listed in ZoneOffset are also supported.
#
# If the time zone does not match any of the above, +zone_offset+
# will check if the local time zone (both with and without
# potential Daylight Saving \Time changes being in effect) matches
# +zone+. Specifying a value for +year+ will change the year used
# to find the local time zone.
#
# If +zone_offset+ is unable to determine the offset, nil will be
# returned.
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/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] # :nodoc:
CommonYearMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # :nodoc:
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 time zone 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 time zone
# abbreviations all over the world, this method is not intended 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 this fact, this method only understands the time zone
# abbreviations described in RFC 822 and the system time zone, in the
# order named. (i.e. a definition in RFC 822 overrides the system
# time zone definition.) The system time zone is taken from
# <tt>Time.local(year, 1, 1).zone</tt> and
# <tt>Time.local(year, 7, 1).zone</tt>.
# If the extracted time zone 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 if the Time class cannot represent specified date.
#
# This method can be used as a 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 of Time.parse should be checked, though.
#
# You must require 'time' to use this method.
#
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}
#
# Below is a list of the formating options:
#
# %a :: The abbreviated weekday name ("Sun")
# %A :: The full weekday name ("Sunday")
# %b :: The abbreviated month name ("Jan")
# %B :: The full month name ("January")
# %c :: The preferred local date and time representation
# %C :: Century (20 in 2009)
# %d :: Day of the month (01..31)
# %D :: Date (%m/%d/%y)
# %e :: Day of the month, blank-padded ( 1..31)
# %F :: Equivalent to %Y-%m-%d (the ISO 8601 date format)
# %h :: Equivalent to %b
# %H :: Hour of the day, 24-hour clock (00..23)
# %I :: Hour of the day, 12-hour clock (01..12)
# %j :: Day of the year (001..366)
# %k :: hour, 24-hour clock, blank-padded ( 0..23)
# %l :: hour, 12-hour clock, blank-padded ( 0..12)
# %L :: Millisecond of the second (000..999)
# %m :: Month of the year (01..12)
# %M :: Minute of the hour (00..59)
# %n :: Newline (\n)
# %N :: Fractional seconds digits, default is 9 digits (nanosecond)
# %3N :: millisecond (3 digits)
# %6N :: microsecond (6 digits)
# %9N :: nanosecond (9 digits)
# %p :: Meridian indicator ("AM" or "PM")
# %P :: Meridian indicator ("am" or "pm")
# %r :: time, 12-hour (same as %I:%M:%S %p)
# %R :: time, 24-hour (%H:%M)
# %s :: Number of seconds since 1970-01-01 00:00:00 UTC.
# %S :: Second of the minute (00..60)
# %t :: Tab character (\t)
# %T :: time, 24-hour (%H:%M:%S)
# %u :: Day of the week as a decimal, Monday being 1. (1..7)
# %U :: Week number of the current year, starting with the first Sunday as
# the first day of the first week (00..53)
# %v :: VMS date (%e-%b-%Y)
# %V :: Week number of year according to ISO 8601 (01..53)
# %W :: Week number of the current year, starting with the first Monday
# as the first day of the first week (00..53)
# %w :: Day of the week (Sunday is 0, 0..6)
# %x :: Preferred representation for the date alone, no time
# %X :: Preferred representation for the time alone, no date
# %y :: Year without a century (00..99)
# %Y :: Year with century
# %z :: Time zone as hour offset from UTC (e.g. +0900)
# %Z :: Time zone name
# %% :: Literal "%" character
def strptime(date, format, now=self.now)
d = Date._strptime(date, format)
raise ArgumentError, "invalid strptime format - `#{format}'" unless d
if seconds = d[:seconds]
if offset = d[:offset]
Time.at(seconds).localtime(offset)
else
Time.at(seconds)
end
else
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
end
MonthValue = { # :nodoc:
'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 if the Time class cannot represent specified date.
#
# See #rfc2822 for more information on this format.
#
# You must require 'time' to use this method.
#
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 an 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 if
# the Time class cannot represent specified date.
#
# See #httpdate for more information on this format.
#
# You must require 'time' to use this method.
#
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 a dateTime defined by the XML Schema and converts it to
# a Time object. The format is a restricted version of the format defined
# by ISO 8601.
#
# ArgumentError is raised if +date+ is not compliant with the format or if
# the Time class cannot represent specified date.
#
# See #xmlschema for more information on this format.
#
# You must require 'time' to use this method.
#
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.
#
# You must require 'time' to use this method.
#
def rfc2822
sprintf('%s, %02d %s %0*d %02d:%02d:%02d ',
RFC2822_DAY_NAME[wday],
day, RFC2822_MONTH_NAME[mon-1], year < 0 ? 5 : 4, 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 = [ # :nodoc:
'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
]
RFC2822_MONTH_NAME = [ # :nodoc:
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
]
#
# Returns a string which represents the time as RFC 1123 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).
#
# You must require 'time' to use this method.
#
def httpdate
t = dup.utc
sprintf('%s, %02d %s %0*d %02d:%02d:%02d GMT',
RFC2822_DAY_NAME[t.wday],
t.day, RFC2822_MONTH_NAME[t.mon-1], t.year < 0 ? 5 : 4, t.year,
t.hour, t.min, t.sec)
end
#
# Returns a string which represents the time as a 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_digits+ specifies a number of digits to use for fractional
# seconds. Its default value is 0.
#
# You must require 'time' to use this method.
#
def xmlschema(fraction_digits=0)
fraction_digits = fraction_digits.to_i
s = strftime("%FT%T")
if fraction_digits > 0
s << strftime(".%#{fraction_digits}N")
end
s << (utc? ? 'Z' : strftime("%:z"))
end
alias iso8601 xmlschema
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/tkdialog.rb | lib/tkdialog.rb | #
# tkdialog.rb - load tk/dialog.rb
#
require 'tk/dialog'
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/remote-tk.rb | lib/remote-tk.rb | #
# remote-tk.rb - supports to control remote Tk interpreters
# by Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
if defined? MultiTkIp
fail RuntimeError, "'remote-tk' library must be required before requiring 'multi-tk'"
end
class MultiTkIp; end
class RemoteTkIp < MultiTkIp; end
class MultiTkIp
@@IP_TABLE = TkUtil.untrust({}) unless defined?(@@IP_TABLE)
@@TK_TABLE_LIST = TkUtil.untrust([]) unless defined?(@@TK_TABLE_LIST)
def self._IP_TABLE; @@IP_TABLE; end
def self._TK_TABLE_LIST; @@TK_TABLE_LIST; end
@flag = true
def self._DEFAULT_MASTER
# work only once
if @flag
@flag = nil
@@DEFAULT_MASTER
else
nil
end
end
end
class RemoteTkIp
@@IP_TABLE = MultiTkIp._IP_TABLE unless defined?(@@IP_TABLE)
@@TK_TABLE_LIST = MultiTkIp._TK_TABLE_LIST unless defined?(@@TK_TABLE_LIST)
end
class << MultiTkIp
undef _IP_TABLE
undef _TK_TABLE_LIST
end
require 'multi-tk'
class RemoteTkIp
if defined?(@@DEFAULT_MASTER)
MultiTkIp._DEFAULT_MASTER
else
@@DEFAULT_MASTER = MultiTkIp._DEFAULT_MASTER
end
end
###############################
class << RemoteTkIp
undef new_master, new_slave, new_safe_slave
undef new_trusted_slave, new_safeTk
def new(*args, &b)
ip = __new(*args)
ip.eval_proc(&b) if b
ip
end
end
class RemoteTkIp
def initialize(remote_ip, displayof=nil, timeout=5)
if $SAFE >= 4
fail SecurityError, "cannot access another interpreter at level #{$SAFE}"
end
@interp = MultiTkIp.__getip
if @interp.safe?
fail SecurityError, "safe-IP cannot create RemoteTkIp"
end
@interp.allow_ruby_exit = false
@appname = @interp._invoke('tk', 'appname')
@remote = remote_ip.to_s.dup.freeze
if displayof.kind_of?(TkWindow)
@displayof = displayof.path.dup.freeze
else
@displayof = nil
end
if self.deleted?
fail RuntimeError, "no Tk application named \"#{@remote}\""
end
@tk_windows = {}
@tk_table_list = []
@slave_ip_tbl = {}
@slave_ip_top = {}
@force_default_encoding ||= TkUtil.untrust([false])
@encoding ||= TkUtil.untrust([nil])
def @encoding.to_s; self.join(nil); end
TkUtil.untrust(@tk_windows) unless @tk_windows.tainted?
TkUtil.untrust(@tk_table_list) unless @tk_table_list.tainted?
TkUtil.untrust(@slave_ip_tbl) unless @slave_ip_tbl.tainted?
TkUtil.untrust(@slave_ip_top) unless @slave_ip_top.tainted?
@system = Object.new
@threadgroup = ThreadGroup.new
@safe_level = [$SAFE]
@wait_on_mainloop = [true, 0]
@cmd_queue = Queue.new
=begin
@cmd_receiver, @receiver_watchdog = _create_receiver_and_watchdog()
@threadgroup.add @cmd_receiver
@threadgroup.add @receiver_watchdog
@threadgroup.enclose
=end
@@DEFAULT_MASTER.assign_receiver_and_watchdog(self)
@@IP_TABLE[@threadgroup] = self
@@TK_TABLE_LIST.size.times{
(tbl = {}).tainted? || TkUtil.untrust(tbl)
@tk_table_list << tbl
}
@ret_val = TkVariable.new
if timeout > 0 && ! _available_check(timeout)
fail RuntimeError, "cannot create connection"
end
@ip_id = _create_connection
class << self
undef :instance_eval
end
self.freeze # defend against modification
end
def manipulable?
return true if (Thread.current.group == ThreadGroup::Default)
MultiTkIp.__getip == @interp && ! @interp.safe?
end
def self.manipulable?
true
end
def _is_master_of?(tcltkip_obj)
tcltkip_obj == @interp
end
protected :_is_master_of?
def _ip_id_
@ip_id
end
def _available_check(timeout = 5)
raise SecurityError, "no permission to manipulate" unless self.manipulable?
return nil if timeout < 1
@ret_val.value = ''
@interp._invoke('send', '-async', @remote,
'send', '-async', Tk.appname,
"set #{@ret_val.id} ready")
Tk.update
if @ret_val != 'ready'
(1..(timeout*5)).each{
sleep 0.2
Tk.update
break if @ret_val == 'ready'
}
end
@ret_val.value == 'ready'
end
private :_available_check
def _create_connection
raise SecurityError, "no permission to manipulate" unless self.manipulable?
ip_id = '_' + @interp._invoke('send', @remote, <<-'EOS') + '_'
if {[catch {set _rubytk_control_ip_id_} ret] != 0} {
set _rubytk_control_ip_id_ 0
} else {
set _rubytk_control_ip_id_ [expr $ret + 1]
}
return $_rubytk_control_ip_id_
EOS
@interp._invoke('send', @remote, <<-EOS)
proc rb_out#{ip_id} args {
send #{@appname} rb_out \$args
}
EOS
ip_id
end
private :_create_connection
def _appsend(enc_mode, async, *cmds)
raise SecurityError, "no permission to manipulate" unless self.manipulable?
p ['_appsend', [@remote, @displayof], enc_mode, async, cmds] if $DEBUG
if $SAFE >= 4
fail SecurityError, "cannot send commands at level 4"
elsif $SAFE >= 1 && cmds.find{|obj| obj.tainted?}
fail SecurityError, "cannot send tainted commands at level #{$SAFE}"
end
cmds = @interp._merge_tklist(*TkUtil::_conv_args([], enc_mode, *cmds))
if @displayof
if async
@interp.__invoke('send', '-async', '-displayof', @displayof,
'--', @remote, *cmds)
else
@interp.__invoke('send', '-displayof', @displayof,
'--', @remote, *cmds)
end
else
if async
@interp.__invoke('send', '-async', '--', @remote, *cmds)
else
@interp.__invoke('send', '--', @remote, *cmds)
end
end
end
private :_appsend
def ready?(timeout=5)
if timeout < 0
fail ArgumentError, "timeout must be positive number"
end
_available_check(timeout)
end
def is_rubytk?
return false if _appsend(false, false, 'info', 'command', 'ruby') == ""
[ _appsend(false, false, 'ruby', 'RUBY_VERSION'),
_appsend(false, false, 'set', 'tk_patchLevel') ]
end
def appsend(async, *args)
raise SecurityError, "no permission to manipulate" unless self.manipulable?
if async != true && async != false && async != nil
args.unshift(async)
async = false
end
if @displayof
Tk.appsend_displayof(@remote, @displayof, async, *args)
else
Tk.appsend(@remote, async, *args)
end
end
def rb_appsend(async, *args)
raise SecurityError, "no permission to manipulate" unless self.manipulable?
if async != true && async != false && async != nil
args.unshift(async)
async = false
end
if @displayof
Tk.rb_appsend_displayof(@remote, @displayof, async, *args)
else
Tk.rb_appsend(@remote, async, *args)
end
end
def create_slave(name, safe=false)
if safe
safe_opt = ''
else
safe_opt = '-safe'
end
_appsend(false, false, "interp create #{safe_opt} -- #{name}")
end
def make_safe
fail RuntimeError, 'cannot change safe mode of the remote interpreter'
end
def safe?
_appsend(false, false, 'interp issafe')
end
def safe_base?
false
end
def allow_ruby_exit?
false
end
def allow_ruby_exit= (mode)
fail RuntimeError, 'cannot change mode of the remote interpreter'
end
def delete
_appsend(false, true, 'exit')
end
def deleted?
raise SecurityError, "no permission to manipulate" unless self.manipulable?
if @displayof
lst = @interp._invoke_without_enc('winfo', 'interps',
'-displayof', @displayof)
else
lst = @interp._invoke_without_enc('winfo', 'interps')
end
# unless @interp._split_tklist(lst).index(@remote)
unless @interp._split_tklist(lst).index(_toUTF8(@remote))
true
else
false
end
end
def has_mainwindow?
raise SecurityError, "no permission to manipulate" unless self.manipulable?
begin
inf = @interp._invoke_without_enc('info', 'command', '.')
rescue Exception
return nil
end
if !inf.kind_of?(String) || inf != '.'
false
else
true
end
end
def invalid_namespace?
false
end
def restart
fail RuntimeError, 'cannot restart the remote interpreter'
end
def __eval(str)
_appsend(false, false, str)
end
def _eval(str)
_appsend(nil, false, str)
end
def _eval_without_enc(str)
_appsend(false, false, str)
end
def _eval_with_enc(str)
_appsend(true, false, str)
end
def _invoke(*args)
_appsend(nil, false, *args)
end
def __invoke(*args)
_appsend(false, false, *args)
end
def _invoke(*args)
_appsend(nil, false, *args)
end
def _invoke_without_enc(*args)
_appsend(false, false, *args)
end
def _invoke_with_enc(*args)
_appsend(true, false, *args)
end
def _toUTF8(str, encoding=nil)
raise SecurityError, "no permission to manipulate" unless self.manipulable?
@interp._toUTF8(str, encoding)
end
def _fromUTF8(str, encoding=nil)
raise SecurityError, "no permission to manipulate" unless self.manipulable?
@interp._fromUTF8(str, encoding)
end
def _thread_vwait(var_name)
_appsend(false, 'thread_vwait', varname)
end
def _thread_tkwait(mode, target)
_appsend(false, 'thread_tkwait', mode, target)
end
def _return_value
raise SecurityError, "no permission to manipulate" unless self.manipulable?
@interp._return_value
end
def _get_variable(var_name, flag)
# ignore flag
_appsend(false, 'set', TkComm::_get_eval_string(var_name))
end
def _get_variable2(var_name, index_name, flag)
# ignore flag
_appsend(false, 'set', "#{TkComm::_get_eval_string(var_name)}(#{TkComm::_get_eval_string(index_name)})")
end
def _set_variable(var_name, value, flag)
# ignore flag
_appsend(false, 'set', TkComm::_get_eval_string(var_name), TkComm::_get_eval_string(value))
end
def _set_variable2(var_name, index_name, value, flag)
# ignore flag
_appsend(false, 'set', "#{TkComm::_get_eval_string(var_name)}(#{TkComm::_get_eval_string(index_name)})", TkComm::_get_eval_string(value))
end
def _unset_variable(var_name, flag)
# ignore flag
_appsend(false, 'unset', TkComm::_get_eval_string(var_name))
end
def _unset_variable2(var_name, index_name, flag)
# ignore flag
_appsend(false, 'unset', "#{var_name}(#{index_name})")
end
def _get_global_var(var_name)
_appsend(false, 'set', TkComm::_get_eval_string(var_name))
end
def _get_global_var2(var_name, index_name)
_appsend(false, 'set', "#{TkComm::_get_eval_string(var_name)}(#{TkComm::_get_eval_string(index_name)})")
end
def _set_global_var(var_name, value)
_appsend(false, 'set', TkComm::_get_eval_string(var_name), TkComm::_get_eval_string(value))
end
def _set_global_var2(var_name, index_name, value)
_appsend(false, 'set', "#{TkComm::_get_eval_string(var_name)}(#{TkComm::_get_eval_string(index_name)})", TkComm::_get_eval_string(value))
end
def _unset_global_var(var_name)
_appsend(false, 'unset', TkComm::_get_eval_string(var_name))
end
def _unset_global_var2(var_name, index_name)
_appsend(false, 'unset', "#{var_name}(#{index_name})")
end
def _split_tklist(str)
raise SecurityError, "no permission to manipulate" unless self.manipulable?
@interp._split_tklist(str)
end
def _merge_tklist(*args)
raise SecurityError, "no permission to manipulate" unless self.manipulable?
@interp._merge_tklist(*args)
end
def _conv_listelement(str)
raise SecurityError, "no permission to manipulate" unless self.manipulable?
@interp._conv_listelement(str)
end
def _create_console
fail RuntimeError, 'not support "_create_console" on the remote interpreter'
end
def mainloop
fail RuntimeError, 'not support "mainloop" on the remote interpreter'
end
def mainloop_watchdog
fail RuntimeError, 'not support "mainloop_watchdog" on the remote interpreter'
end
def do_one_event(flag = nil)
fail RuntimeError, 'not support "do_one_event" on the remote interpreter'
end
def mainloop_abort_on_exception
fail RuntimeError, 'not support "mainloop_abort_on_exception" on the remote interpreter'
end
def mainloop_abort_on_exception=(mode)
fail RuntimeError, 'not support "mainloop_abort_on_exception=" on the remote interpreter'
end
def set_eventloop_tick(*args)
fail RuntimeError, 'not support "set_eventloop_tick" on the remote interpreter'
end
def get_eventloop_tick
fail RuntimeError, 'not support "get_eventloop_tick" on the remote interpreter'
end
def set_no_event_wait(*args)
fail RuntimeError, 'not support "set_no_event_wait" on the remote interpreter'
end
def get_no_event_wait
fail RuntimeError, 'not support "get_no_event_wait" on the remote interpreter'
end
def set_eventloop_weight(*args)
fail RuntimeError, 'not support "set_eventloop_weight" on the remote interpreter'
end
def get_eventloop_weight
fail RuntimeError, 'not support "get_eventloop_weight" on the remote interpreter'
end
end
class << RemoteTkIp
def mainloop(*args)
fail RuntimeError, 'not support "mainloop" on the remote interpreter'
end
def mainloop_watchdog(*args)
fail RuntimeError, 'not support "mainloop_watchdog" on the remote interpreter'
end
def do_one_event(flag = nil)
fail RuntimeError, 'not support "do_one_event" on the remote interpreter'
end
def mainloop_abort_on_exception
fail RuntimeError, 'not support "mainloop_abort_on_exception" on the remote interpreter'
end
def mainloop_abort_on_exception=(mode)
fail RuntimeError, 'not support "mainloop_abort_on_exception=" on the remote interpreter'
end
def set_eventloop_tick(*args)
fail RuntimeError, 'not support "set_eventloop_tick" on the remote interpreter'
end
def get_eventloop_tick
fail RuntimeError, 'not support "get_eventloop_tick" on the remote interpreter'
end
def set_no_event_wait(*args)
fail RuntimeError, 'not support "set_no_event_wait" on the remote interpreter'
end
def get_no_event_wait
fail RuntimeError, 'not support "get_no_event_wait" on the remote interpreter'
end
def set_eventloop_weight(*args)
fail RuntimeError, 'not support "set_eventloop_weight" on the remote interpreter'
end
def get_eventloop_weight
fail RuntimeError, 'not support "get_eventloop_weight" on the remote interpreter'
end
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/fileutils.rb | lib/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
#
# FileUtils.cd('/') do # chdir
# [...] # do something
# end # return to original directory
#
def cd(dir, options = {}, &block) # :yield: dir
fu_check_options options, OPT_TABLE['cd']
fu_output_message "cd #{dir}" if options[:verbose]
Dir.chdir(dir, &block)
fu_output_message 'cd -' if options[:verbose] and block
end
module_function :cd
alias chdir cd
module_function :chdir
OPT_TABLE['cd'] =
OPT_TABLE['chdir'] = [:verbose]
#
# Options: (none)
#
# Returns true if +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)
return false unless File.exist?(new)
new_time = File.mtime(new)
old_list.each do |old|
if File.exist?(old)
return false unless new_time > File.mtime(old)
end
end
true
end
module_function :uptodate?
def remove_tailing_slash(dir)
dir == '/' ? dir : dir.chomp(?/)
end
private_module_function :remove_tailing_slash
#
# Options: mode noop verbose
#
# Creates one or more directories.
#
# FileUtils.mkdir 'test'
# FileUtils.mkdir %w( tmp data )
# FileUtils.mkdir 'notexist', :noop => true # Does not really create.
# FileUtils.mkdir 'tmp', :mode => 0700
#
def mkdir(list, options = {})
fu_check_options options, OPT_TABLE['mkdir']
list = fu_list(list)
fu_output_message "mkdir #{options[:mode] ? ('-m %03o ' % options[:mode]) : ''}#{list.join ' '}" if options[:verbose]
return if options[:noop]
list.each do |dir|
fu_mkdir dir, options[:mode]
end
end
module_function :mkdir
OPT_TABLE['mkdir'] = [:mode, :noop, :verbose]
#
# Options: mode noop verbose
#
# Creates a directory and all its parent directories.
# For example,
#
# FileUtils.mkdir_p '/usr/local/lib/ruby'
#
# causes to make following directories, if it does not exist.
# * /usr
# * /usr/local
# * /usr/local/lib
# * /usr/local/lib/ruby
#
# You can pass several directories at a time in a list.
#
def mkdir_p(list, options = {})
fu_check_options options, OPT_TABLE['mkdir_p']
list = fu_list(list)
fu_output_message "mkdir -p #{options[:mode] ? ('-m %03o ' % options[:mode]) : ''}#{list.join ' '}" if options[:verbose]
return *list if options[:noop]
list.map {|path| remove_tailing_slash(path)}.each do |path|
# optimize for the most common case
begin
fu_mkdir path, options[:mode]
next
rescue SystemCallError
next if File.directory?(path)
end
stack = []
until path == stack.last # dirname("/")=="/", dirname("C:/")=="C:/"
stack.push path
path = File.dirname(path)
end
stack.reverse_each do |dir|
begin
fu_mkdir dir, options[:mode]
rescue SystemCallError
raise unless File.directory?(dir)
end
end
end
return *list
end
module_function :mkdir_p
alias mkpath mkdir_p
alias makedirs mkdir_p
module_function :mkpath
module_function :makedirs
OPT_TABLE['mkdir_p'] =
OPT_TABLE['mkpath'] =
OPT_TABLE['makedirs'] = [:mode, :noop, :verbose]
def fu_mkdir(path, mode) #:nodoc:
path = remove_tailing_slash(path)
if mode
Dir.mkdir path, mode
File.chmod mode, path
else
Dir.mkdir path
end
end
private_module_function :fu_mkdir
#
# Options: noop, verbose
#
# Removes one or more directories.
#
# FileUtils.rmdir 'somedir'
# FileUtils.rmdir %w(somedir anydir otherdir)
# # Does not really remove directory; outputs message.
# FileUtils.rmdir 'somedir', :verbose => true, :noop => true
#
def rmdir(list, options = {})
fu_check_options options, OPT_TABLE['rmdir']
list = fu_list(list)
parents = options[:parents]
fu_output_message "rmdir #{parents ? '-p ' : ''}#{list.join ' '}" if options[:verbose]
return if options[:noop]
list.each do |dir|
begin
Dir.rmdir(dir = remove_tailing_slash(dir))
if parents
until (parent = File.dirname(dir)) == '.' or parent == dir
dir = parent
Dir.rmdir(dir)
end
end
rescue Errno::ENOTEMPTY, Errno::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 => true)
#
def ln_sf(src, dest, options = {})
fu_check_options options, OPT_TABLE['ln_sf']
options = options.dup
options[:force] = true
ln_s src, dest, options
end
module_function :ln_sf
OPT_TABLE['ln_sf'] = [:noop, :verbose]
#
# Options: preserve noop verbose
#
# Copies a file content +src+ to +dest+. If +dest+ is a directory,
# copies +src+ to +dest/src+.
#
# If +src+ is a list of files, then +dest+ must be a directory.
#
# FileUtils.cp 'eval.c', 'eval.c.org'
# FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6'
# FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6', :verbose => true
# FileUtils.cp 'symlink', 'dest' # copy content, "dest" is not a symlink
#
def cp(src, dest, options = {})
fu_check_options options, OPT_TABLE['cp']
fu_output_message "cp#{options[:preserve] ? ' -p' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
return if options[:noop]
fu_each_src_dest(src, dest) do |s, d|
copy_file s, d, options[:preserve]
end
end
module_function :cp
alias copy cp
module_function :copy
OPT_TABLE['cp'] =
OPT_TABLE['copy'] = [:preserve, :noop, :verbose]
#
# Options: preserve noop verbose dereference_root remove_destination
#
# Copies +src+ to +dest+. If +src+ is a directory, this method copies
# all its contents recursively. If +dest+ is a directory, copies
# +src+ to +dest/src+.
#
# +src+ can be a list of files.
#
# # Installing Ruby library "mylib" under the site_ruby
# FileUtils.rm_r site_ruby + '/mylib', :force
# FileUtils.cp_r 'lib/', site_ruby + '/mylib'
#
# # Examples of copying several files to target directory.
# FileUtils.cp_r %w(mail.rb field.rb debug/), site_ruby + '/tmail'
# FileUtils.cp_r Dir.glob('*.rb'), '/home/aamine/lib/ruby', :noop => true, :verbose => true
#
# # If you want to copy all contents of a directory instead of the
# # directory itself, c.f. src/x -> dest/x, src/y -> dest/y,
# # use following code.
# FileUtils.cp_r 'src/.', 'dest' # cp_r('src', 'dest') makes dest/src,
# # but this doesn't.
#
def cp_r(src, dest, options = {})
fu_check_options options, OPT_TABLE['cp_r']
fu_output_message "cp -r#{options[:preserve] ? 'p' : ''}#{options[:remove_destination] ? ' --remove-destination' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
return if options[:noop]
options = options.dup
options[:dereference_root] = true unless options.key?(:dereference_root)
fu_each_src_dest(src, dest) do |s, d|
copy_entry s, d, options[:preserve], options[:dereference_root], options[:remove_destination]
end
end
module_function :cp_r
OPT_TABLE['cp_r'] = [:preserve, :noop, :verbose,
:dereference_root, :remove_destination]
#
# Copies a file system entry +src+ to +dest+.
# If +src+ is a directory, this method copies its contents recursively.
# This method preserves file types, c.f. symlink, directory...
# (FIFO, device files and etc. are not supported yet)
#
# Both of +src+ and +dest+ must be a path name.
# +src+ must exist, +dest+ must not exist.
#
# If +preserve+ is true, this method preserves owner, group, 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).wrap_traverse(proc do |ent|
destent = Entry_.new(dest, ent.rel, false)
File.unlink destent.path if remove_destination && File.file?(destent.path)
ent.copy destent.path
end, proc do |ent|
destent = Entry_.new(dest, ent.rel, false)
ent.copy_metadata destent.path if preserve
end)
end
module_function :copy_entry
#
# Copies file contents of +src+ to +dest+.
# Both of +src+ and +dest+ must be a path name.
#
def copy_file(src, dest, preserve = false, dereference = true)
ent = Entry_.new(src, nil, dereference)
ent.copy_file dest
ent.copy_metadata dest if preserve
end
module_function :copy_file
#
# Copies stream +src+ to +dest+.
# +src+ must respond to #read(n) and
# +dest+ must respond to #write(str).
#
def copy_stream(src, dest)
IO.copy_stream(src, dest)
end
module_function :copy_stream
#
# Options: force noop verbose
#
# Moves file(s) +src+ to +dest+. If +file+ and +dest+ exist on the different
# disk partition, the file is copied then the original file is removed.
#
# FileUtils.mv 'badname.rb', 'goodname.rb'
# FileUtils.mv 'stuff.rb', '/notexist/lib/ruby', :force => true # no error
#
# FileUtils.mv %w(junk.txt dust.txt), '/home/aamine/.trash/'
# FileUtils.mv Dir.glob('test*.rb'), 'test', :noop => true, :verbose => true
#
def mv(src, dest, options = {})
fu_check_options options, OPT_TABLE['mv']
fu_output_message "mv#{options[:force] ? ' -f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
return if options[:noop]
fu_each_src_dest(src, dest) do |s, d|
destent = Entry_.new(d, nil, true)
begin
if destent.exist?
if destent.directory?
raise Errno::EEXIST, 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 cannot be
# moved by other untrusted users. For example, parent directories
# should not be owned by untrusted users, and should not be world
# writable except when the sticky bit set.
#
# WARNING: Only the owner of the removing directory tree, or Unix super
# user (root) should invoke this method. Otherwise this method does not
# work.
#
# For details of this security vulnerability, see Perl's case:
#
# http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CAN-2005-0448
# http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CAN-2004-0452
#
# For fileutils.rb, this vulnerability is reported in [ruby-dev:26100].
#
def remove_entry_secure(path, force = false)
unless fu_have_symlink?
remove_entry path, force
return
end
fullpath = File.expand_path(path)
st = File.lstat(fullpath)
unless st.directory?
File.unlink fullpath
return
end
# is a directory.
parent_st = File.stat(File.dirname(fullpath))
unless parent_st.world_writable?
remove_entry path, force
return
end
unless parent_st.sticky?
raise ArgumentError, "parent directory is world writable, FileUtils#remove_entry_secure does not work; abort: #{path.inspect} (parent directory mode #{'%o' % parent_st.mode})"
end
# freeze tree root
euid = Process.euid
File.open(fullpath + '/.') {|f|
unless fu_stat_identical_entry?(st, f.stat)
# symlink (TOC-to-TOU attack?)
File.unlink fullpath
return
end
f.chown euid, -1
f.chmod 0700
unless fu_stat_identical_entry?(st, File.lstat(fullpath))
# TOC-to-TOU attack?
File.unlink fullpath
return
end
}
# ---- tree root is frozen ----
root = Entry_.new(path)
root.preorder_traverse do |ent|
if ent.directory?
ent.chown euid, -1
ent.chmod 0700
end
end
root.postorder_traverse do |ent|
begin
ent.remove
rescue
raise unless force
end
end
rescue
raise unless force
end
module_function :remove_entry_secure
def fu_have_symlink? #:nodoc:
File.symlink nil, nil
rescue NotImplementedError
return false
rescue TypeError
return true
end
private_module_function :fu_have_symlink?
def fu_stat_identical_entry?(a, b) #:nodoc:
a.dev == b.dev and a.ino == b.ino
end
private_module_function :fu_stat_identical_entry?
#
# This method removes a file system entry +path+.
# +path+ might be a regular file, a directory, or something.
# If +path+ is a directory, remove it recursively.
#
# See also #remove_entry_secure.
#
def remove_entry(path, force = false)
Entry_.new(path).postorder_traverse do |ent|
begin
ent.remove
rescue
raise unless force
end
end
rescue
raise unless force
end
module_function :remove_entry
#
# Removes a file +path+.
# This method ignores StandardError if +force+ is true.
#
def remove_file(path, force = false)
Entry_.new(path).remove_file
rescue
raise unless force
end
module_function :remove_file
#
# Removes a directory +dir+ and its contents recursively.
# This method ignores StandardError if +force+ is true.
#
def remove_dir(path, force = false)
remove_entry path, force # FIXME?? check if it is a directory
end
module_function :remove_dir
#
# Returns true if the contents of a file A and a file B are identical.
#
# FileUtils.compare_file('somefile', 'somefile') #=> true
# FileUtils.compare_file('/bin/cp', '/bin/mv') #=> maybe false
#
def compare_file(a, b)
return false unless File.size(a) == File.size(b)
File.open(a, 'rb') {|fa|
File.open(b, 'rb') {|fb|
return compare_stream(fa, fb)
}
}
end
module_function :compare_file
alias identical? compare_file
alias cmp compare_file
module_function :identical?
module_function :cmp
#
# Returns true if the contents of a stream +a+ and +b+ are identical.
#
def compare_stream(a, b)
bsize = fu_stream_blksize(a, b)
sa = ""
sb = ""
begin
a.read(bsize, sa)
b.read(bsize, sb)
return true if sa.empty? && sb.empty?
end while sa == sb
false
end
module_function :compare_stream
#
# Options: mode preserve noop verbose
#
# If +src+ is not same as +dest+, copies it and changes the permission
# mode to +mode+. If +dest+ is a directory, destination is +dest+/+src+.
# This method removes destination before copy.
#
# FileUtils.install 'ruby', '/usr/local/bin/ruby', :mode => 0755, :verbose => true
# FileUtils.install 'lib.rb', '/usr/local/lib/ruby/site_ruby', :verbose => true
#
def install(src, dest, options = {})
fu_check_options options, OPT_TABLE['install']
fu_output_message "install -c#{options[:preserve] && ' -p'}#{options[:mode] ? (' -m 0%o' % options[:mode]) : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
return if options[:noop]
fu_each_src_dest(src, dest) do |s, d, st|
unless File.exist?(d) and compare_file(s, d)
remove_file d, true
copy_file s, d
File.utime st.atime, st.mtime, d if options[:preserve]
File.chmod options[:mode], d if options[:mode]
end
end
end
module_function :install
OPT_TABLE['install'] = [:mode, :preserve, :noop, :verbose]
def user_mask(target) #:nodoc:
target.each_char.inject(0) do |mask, chr|
case chr
when "u"
mask | 04700
when "g"
mask | 02070
when "o"
mask | 01007
when "a"
mask | 07777
else
raise ArgumentError, "invalid `who' symbol in file mode: #{chr}"
end
end
end
private_module_function :user_mask
def apply_mask(mode, user_mask, op, mode_mask)
case op
when '='
(mode & ~user_mask) | (user_mask & mode_mask)
when '+'
mode | (user_mask & mode_mask)
when '-'
mode & ~(user_mask & mode_mask)
end
end
private_module_function :apply_mask
def symbolic_modes_to_i(mode_sym, path) #:nodoc:
mode_sym.split(/,/).inject(File.stat(path).mode & 07777) do |current_mode, clause|
target, *actions = clause.split(/([=+-])/)
raise ArgumentError, "invalid file mode: #{mode_sym}" if actions.empty?
target = 'a' if target.empty?
user_mask = user_mask(target)
actions.each_slice(2) do |op, perm|
need_apply = op == '='
mode_mask = (perm || '').each_char.inject(0) do |mask, chr|
case chr
when "r"
mask | 0444
when "w"
mask | 0222
when "x"
mask | 0111
when "X"
if FileTest.directory? path
mask | 0111
else
mask
end
when "s"
mask | 06000
when "t"
mask | 01000
when "u", "g", "o"
if mask.nonzero?
current_mode = apply_mask(current_mode, user_mask, op, mask)
end
need_apply = false
copy_mask = user_mask(chr)
(current_mode & copy_mask) / (copy_mask & 0111) * (user_mask & 0111)
else
raise ArgumentError, "invalid `perm' symbol in file mode: #{chr}"
end
end
if mode_mask.nonzero? || need_apply
current_mode = apply_mask(current_mode, user_mask, op, mode_mask)
end
end
current_mode
end
end
private_module_function :symbolic_modes_to_i
def fu_mode(mode, path) #:nodoc:
mode.is_a?(String) ? symbolic_modes_to_i(mode, path) : mode
end
private_module_function :fu_mode
def mode_to_s(mode) #:nodoc:
mode.is_a?(String) ? mode : "%o" % mode
end
private_module_function :mode_to_s
#
# Options: noop verbose
#
# Changes permission bits on the named files (in +list+) to the bit pattern
# represented by +mode+.
#
# +mode+ is the symbolic and absolute mode can be used.
#
# Absolute mode is
# FileUtils.chmod 0755, 'somecommand'
# FileUtils.chmod 0644, %w(my.rb your.rb his.rb her.rb)
# FileUtils.chmod 0755, '/usr/bin/ruby', :verbose => true
#
# Symbolic mode is
# FileUtils.chmod "u=wrx,go=rx", 'somecommand'
# FileUtils.chmod "u=wr,go=rr", %w(my.rb your.rb his.rb her.rb)
# FileUtils.chmod "u=wrx,go=rx", '/usr/bin/ruby', :verbose => true
#
# "a" :: is user, group, other mask.
# "u" :: is user's mask.
# "g" :: is group's mask.
# "o" :: is other's mask.
# "w" :: is write permission.
# "r" :: is read permission.
# "x" :: is execute permission.
# "X" ::
# is execute permission for directories only, must be used in conjunction with "+"
# "s" :: is uid, gid.
# "t" :: is sticky bit.
# "+" :: is added to a class given the specified mode.
# "-" :: Is removed from a given class given mode.
# "=" :: Is the exact nature of the class will be given a specified mode.
def chmod(mode, list, options = {})
fu_check_options options, OPT_TABLE['chmod']
list = fu_list(list)
fu_output_message sprintf('chmod %s %s', mode_to_s(mode), list.join(' ')) if options[:verbose]
return if options[:noop]
list.each do |path|
Entry_.new(path).chmod(fu_mode(mode, path))
end
end
module_function :chmod
OPT_TABLE['chmod'] = [:noop, :verbose]
#
# Options: noop verbose force
#
# Changes permission bits on the named files (in +list+)
# to the bit pattern represented by +mode+.
#
# FileUtils.chmod_R 0700, "/tmp/app.#{$$}"
# FileUtils.chmod_R "u=wrx", "/tmp/app.#{$$}"
#
def chmod_R(mode, list, options = {})
fu_check_options options, OPT_TABLE['chmod_R']
list = fu_list(list)
fu_output_message sprintf('chmod -R%s %s %s',
(options[:force] ? 'f' : ''),
mode_to_s(mode), list.join(' ')) if options[:verbose]
return if options[:noop]
list.each do |root|
Entry_.new(root).traverse do |ent|
begin
ent.chmod(fu_mode(mode, ent.path))
rescue
raise unless options[:force]
end
end
end
end
module_function :chmod_R
OPT_TABLE['chmod_R'] = [:noop, :verbose, :force]
#
# Options: noop verbose
#
# Changes owner and group on the named files (in +list+)
# to the user +user+ and the group +group+. +user+ and +group+
# may be an ID (Integer/String) or a name (String).
# If +user+ or +group+ is nil, this method does not change
# the attribute.
#
# FileUtils.chown 'root', 'staff', '/usr/local/bin/ruby'
# FileUtils.chown nil, 'bin', Dir.glob('/usr/bin/*'), :verbose => true
#
def chown(user, group, list, options = {})
fu_check_options options, OPT_TABLE['chown']
list = fu_list(list)
fu_output_message sprintf('chown %s %s',
(group ? "#{user}:#{group}" : user || ':'),
list.join(' ')) if options[:verbose]
return if options[:noop]
uid = fu_get_uid(user)
gid = fu_get_gid(group)
list.each do |path|
Entry_.new(path).chown uid, gid
end
end
module_function :chown
OPT_TABLE['chown'] = [:noop, :verbose]
#
# Options: noop verbose force
#
# Changes owner and group on the named files (in +list+)
# to the user +user+ and the group +group+ recursively.
# +user+ and +group+ may be an ID (Integer/String) or
# a name (String). If +user+ or +group+ is nil, this
# method does not change the attribute.
#
# FileUtils.chown_R 'www', 'www', '/var/www/htdocs'
# FileUtils.chown_R 'cvs', 'cvs', '/var/cvs', :verbose => true
#
def chown_R(user, group, list, options = {})
fu_check_options options, OPT_TABLE['chown_R']
list = fu_list(list)
fu_output_message sprintf('chown -R%s %s %s',
(options[:force] ? 'f' : ''),
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | true |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/observer.rb | lib/observer.rb | #
# Implementation of the _Observer_ object-oriented design pattern. The
# following documentation is copied, with modifications, from "Programming
# Ruby", by Hunt and Thomas; http://www.ruby-doc.org/docs/ProgrammingRuby/html/lib_patterns.html.
#
# See Observable for more info.
# The Observer pattern (also known as publish/subscribe) provides a simple
# mechanism for one object to inform a set of interested third-party objects
# when its state changes.
#
# == Mechanism
#
# The notifying class mixes in the +Observable+
# module, which provides the methods for managing the associated observer
# objects.
#
# The observable object must:
# * assert that it has +#changed+
# * call +#notify_observers+
#
# An observer subscribes to updates using Observable#add_observer, which also
# specifies the method called via #notify_observers. The default method for
# #notify_observers is #update.
#
# === Example
#
# The following example demonstrates this nicely. A +Ticker+, when run,
# continually receives the stock +Price+ for its <tt>@symbol</tt>. A +Warner+
# is a general observer of the price, and two warners are demonstrated, a
# +WarnLow+ and a +WarnHigh+, which print a warning if the price is below or
# above their set limits, respectively.
#
# The +update+ callback allows the warners to run without being explicitly
# called. The system is set up with the +Ticker+ and several observers, and the
# observers do their duty without the top-level code having to interfere.
#
# Note that the contract between publisher and subscriber (observable and
# observer) is not declared or enforced. The +Ticker+ publishes a time and a
# price, and the warners receive that. But if you don't ensure that your
# contracts are correct, nothing else can warn you.
#
# require "observer"
#
# class Ticker ### Periodically fetch a stock price.
# include Observable
#
# def initialize(symbol)
# @symbol = symbol
# end
#
# def run
# last_price = nil
# loop do
# price = Price.fetch(@symbol)
# print "Current price: #{price}\n"
# if price != last_price
# changed # notify observers
# last_price = price
# notify_observers(Time.now, price)
# end
# sleep 1
# end
# end
# end
#
# class Price ### A mock class to fetch a stock price (60 - 140).
# def self.fetch(symbol)
# 60 + rand(80)
# end
# end
#
# class Warner ### An abstract observer of Ticker objects.
# def initialize(ticker, limit)
# @limit = limit
# ticker.add_observer(self)
# end
# end
#
# class WarnLow < Warner
# def update(time, price) # callback for observer
# if price < @limit
# print "--- #{time.to_s}: Price below #@limit: #{price}\n"
# end
# end
# end
#
# class WarnHigh < Warner
# def update(time, price) # callback for observer
# if price > @limit
# print "+++ #{time.to_s}: Price above #@limit: #{price}\n"
# end
# end
# end
#
# ticker = Ticker.new("MSFT")
# WarnLow.new(ticker, 80)
# WarnHigh.new(ticker, 120)
# ticker.run
#
# Produces:
#
# Current price: 83
# Current price: 75
# --- Sun Jun 09 00:10:25 CDT 2002: Price below 80: 75
# Current price: 90
# Current price: 134
# +++ Sun Jun 09 00:10:25 CDT 2002: Price above 120: 134
# Current price: 134
# Current price: 112
# Current price: 79
# --- Sun Jun 09 00:10:25 CDT 2002: Price below 80: 79
module Observable
#
# Add +observer+ as an observer on this object. so that it will receive
# notifications.
#
# +observer+:: the object that will be notified of changes.
# +func+:: Symbol naming the method that will be called when this Observable
# has changes.
#
# This method must return true for +observer.respond_to?+ and will
# receive <tt>*arg</tt> when #notify_observers is called, where
# <tt>*arg</tt> is the value passed to #notify_observers by this
# Observable
def add_observer(observer, func=:update)
@observer_peers = {} unless defined? @observer_peers
unless observer.respond_to? func
raise NoMethodError, "observer does not respond to `#{func.to_s}'"
end
@observer_peers[observer] = func
end
#
# Remove +observer+ as an observer on this object so that it will no longer
# receive notifications.
#
# +observer+:: An observer of this Observable
def delete_observer(observer)
@observer_peers.delete observer if defined? @observer_peers
end
#
# Remove all observers associated with this object.
#
def delete_observers
@observer_peers.clear if defined? @observer_peers
end
#
# Return the number of observers associated with this object.
#
def count_observers
if defined? @observer_peers
@observer_peers.size
else
0
end
end
#
# Set the changed state of this object. Notifications will be sent only if
# the changed +state+ is +true+.
#
# +state+:: Boolean indicating the changed state of this Observable.
#
def changed(state=true)
@observer_state = state
end
#
# Returns true if this object's state has been changed since the last
# #notify_observers call.
#
def changed?
if defined? @observer_state and @observer_state
true
else
false
end
end
#
# Notify observers of a change in state *if* this object's changed state is
# +true+.
#
# This will invoke the method named in #add_observer, passing <tt>*arg</tt>.
# The changed state is then set to +false+.
#
# <tt>*arg</tt>:: Any arguments to pass to the observers.
def notify_observers(*arg)
if defined? @observer_state and @observer_state
if defined? @observer_peers
@observer_peers.each do |k, v|
k.send v, *arg
end
end
@observer_state = false
end
end
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/yaml.rb | lib/yaml.rb | ##
# The YAML module is an alias of Psych, the YAML engine for Ruby.
begin
require 'psych'
rescue LoadError
warn "#{caller[0]}:"
warn "It seems your ruby installation is missing psych (for YAML output)."
warn "To eliminate this warning, please install libyaml and reinstall your ruby."
raise
end
YAML = Psych # :nodoc:
module Psych # :nodoc:
# For compatibility, deprecated
class EngineManager # :nodoc:
attr_reader :yamler # :nodoc:
def initialize # :nodoc:
@yamler = 'psych'
end
def syck? # :nodoc:
false
end
# Psych is always used and this method has no effect.
#
# This method is still present for compatibility.
#
# You may still use the Syck engine by installing
# the 'syck' gem and using the Syck constant.
def yamler= engine # :nodoc:
case engine
when 'syck' then warn "syck has been removed, psych is used instead"
when 'psych' then @yamler = 'psych'
else
raise(ArgumentError, "bad engine")
end
engine
end
end
ENGINE = EngineManager.new # :nodoc:
end
# YAML Ain't Markup Language
#
# This module provides a Ruby interface for data serialization in YAML format.
#
# The underlying implementation is the libyaml wrapper Psych.
#
# == Usage
#
# Working with YAML can be very simple, for example:
#
# require 'yaml' # STEP ONE, REQUIRE YAML!
# # Parse a YAML string
# YAML.load("--- foo") #=> "foo"
#
# # Emit some YAML
# YAML.dump("foo") # => "--- foo\n...\n"
# { :a => 'b'}.to_yaml # => "---\n:a: b\n"
#
# == Security
#
# Do not use YAML to load untrusted data. Doing so is unsafe and could allow
# malicious input to execute arbitrary code inside your application. Please see
# doc/security.rdoc for more information.
#
# == History
#
# Syck was the original for YAML implementation in Ruby's standard library
# developed by why the lucky stiff.
#
# You can still use Syck, if you prefer, for parsing and emitting YAML, but you
# must install the 'syck' gem now in order to use it.
#
# In older Ruby versions, ie. <= 1.9, Syck is still provided, however it was
# completely removed with the release of Ruby 2.0.0.
#
# == More info
#
# For more advanced details on the implementation see Psych, and also check out
# http://yaml.org for spec details and other helpful information.
module YAML
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/tkentry.rb | lib/tkentry.rb | #
# tkentry.rb - load tk/entry.rb
#
require 'tk/entry'
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/csv.rb | lib/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 as of Ruby 1.9. If you are migrating code from 1.8 or
# earlier, you may have to change your code to comply with the new interface.
#
# == 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($stdin) { |csv_in| csv_in.each { |row| p row } } # from $stdin
#
# == Advanced Usage
#
# === Wrap an IO Object
#
# csv = CSV.new(io, options)
# # ... read (with gets() or each()) from and write (with <<) to csv here ...
#
# == 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.8".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
headers.each { |h| h.freeze if h.is_a? String }
# 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 return the field value by +header+ or +index+. If a field
# is not found, +nil+ is returned.
#
# When provided, +offset+ ensures that a header match occurs 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:
# fetch( header )
# fetch( header ) { |row| ... }
# fetch( header, default )
#
# This method will fetch the field value by +header+. It has the same
# behavior as Hash#fetch: if there is a field with the given +header+, its
# value is returned. Otherwise, if a block is given, it is yielded the
# +header+ and its result is returned; if a +default+ is given as the
# second argument, it is returned; otherwise a KeyError is raised.
#
def fetch(header, *varargs)
raise ArgumentError, "Too many arguments" if varargs.length > 1
pair = @row.assoc(header)
if pair
pair.last
else
if block_given?
yield header
elsif varargs.empty?
raise KeyError, "key not found: #{header}"
else
varargs.first
end
end
end
# Returns +true+ if there is a field with the given +header+.
def has_key?(header)
!!@row.assoc(header)
end
alias_method :include?, :has_key?
alias_method :key?, :has_key?
alias_method :member?, :has_key?
#
# :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)
elsif i = index(header_or_index, minimum_index) # by header
@row.delete_at(i)
else
[ ]
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)
return @row == other.row if other.is_a? CSV::Row
@row == other
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, iteration 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, iteration 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.
#
# This method assumes you want the Table.headers(), unless you explicitly
# pass <tt>:write_headers => false</tt>.
#
def to_csv(options = Hash.new)
wh = options.fetch(:write_headers, true)
@table.inject(wh ? [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
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | true |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/kconv.rb | lib/kconv.rb | #
# kconv.rb - Kanji Converter.
#
# $Id: kconv.rb 30112 2010-12-07 11:47:39Z naruse $
#
# ----
#
# kconv.rb implements the Kconv class for Kanji Converter. Additionally,
# some methods in String classes are added to allow easy conversion.
#
require 'nkf'
#
# Kanji Converter for Ruby.
#
module Kconv
#
# Public Constants
#
#Constant of Encoding
# Auto-Detect
AUTO = NKF::AUTO
# ISO-2022-JP
JIS = NKF::JIS
# EUC-JP
EUC = NKF::EUC
# Shift_JIS
SJIS = NKF::SJIS
# BINARY
BINARY = NKF::BINARY
# NOCONV
NOCONV = NKF::NOCONV
# ASCII
ASCII = NKF::ASCII
# UTF-8
UTF8 = NKF::UTF8
# UTF-16
UTF16 = NKF::UTF16
# UTF-32
UTF32 = NKF::UTF32
# UNKNOWN
UNKNOWN = NKF::UNKNOWN
#
# Public Methods
#
# call-seq:
# Kconv.kconv(str, to_enc, from_enc=nil)
#
# Convert <code>str</code> to <code>to_enc</code>.
# <code>to_enc</code> and <code>from_enc</code> are given as constants of Kconv or Encoding objects.
def kconv(str, to_enc, from_enc=nil)
opt = ''
opt += ' --ic=' + from_enc.to_s if from_enc
opt += ' --oc=' + to_enc.to_s if to_enc
::NKF::nkf(opt, str)
end
module_function :kconv
#
# Encode to
#
# call-seq:
# Kconv.tojis(str) => string
#
# Convert <code>str</code> to ISO-2022-JP
def tojis(str)
kconv(str, JIS)
end
module_function :tojis
# call-seq:
# Kconv.toeuc(str) => string
#
# Convert <code>str</code> to EUC-JP
def toeuc(str)
kconv(str, EUC)
end
module_function :toeuc
# call-seq:
# Kconv.tosjis(str) => string
#
# Convert <code>str</code> to Shift_JIS
def tosjis(str)
kconv(str, SJIS)
end
module_function :tosjis
# call-seq:
# Kconv.toutf8(str) => string
#
# Convert <code>str</code> to UTF-8
def toutf8(str)
kconv(str, UTF8)
end
module_function :toutf8
# call-seq:
# Kconv.toutf16(str) => string
#
# Convert <code>str</code> to UTF-16
def toutf16(str)
kconv(str, UTF16)
end
module_function :toutf16
# call-seq:
# Kconv.toutf32(str) => string
#
# Convert <code>str</code> to UTF-32
def toutf32(str)
kconv(str, UTF32)
end
module_function :toutf32
# call-seq:
# Kconv.tolocale => string
#
# Convert <code>self</code> to locale encoding
def tolocale(str)
kconv(str, Encoding.locale_charmap)
end
module_function :tolocale
#
# guess
#
# call-seq:
# Kconv.guess(str) => encoding
#
# Guess input encoding by NKF.guess
def guess(str)
::NKF::guess(str)
end
module_function :guess
#
# isEncoding
#
# call-seq:
# Kconv.iseuc(str) => true or false
#
# Returns whether input encoding is EUC-JP or not.
#
# *Note* don't expect this return value is MatchData.
def iseuc(str)
str.dup.force_encoding(EUC).valid_encoding?
end
module_function :iseuc
# call-seq:
# Kconv.issjis(str) => true or false
#
# Returns whether input encoding is Shift_JIS or not.
def issjis(str)
str.dup.force_encoding(SJIS).valid_encoding?
end
module_function :issjis
# call-seq:
# Kconv.isjis(str) => true or false
#
# Returns whether input encoding is ISO-2022-JP or not.
def isjis(str)
/\A [\t\n\r\x20-\x7E]*
(?:
(?:\x1b \x28 I [\x21-\x7E]*
|\x1b \x28 J [\x21-\x7E]*
|\x1b \x24 @ (?:[\x21-\x7E]{2})*
|\x1b \x24 B (?:[\x21-\x7E]{2})*
|\x1b \x24 \x28 D (?:[\x21-\x7E]{2})*
)*
\x1b \x28 B [\t\n\r\x20-\x7E]*
)*
\z/nox =~ str.dup.force_encoding('BINARY') ? true : false
end
module_function :isjis
# call-seq:
# Kconv.isutf8(str) => true or false
#
# Returns whether input encoding is UTF-8 or not.
def isutf8(str)
str.dup.force_encoding(UTF8).valid_encoding?
end
module_function :isutf8
end
class String
# call-seq:
# String#kconv(to_enc, from_enc)
#
# Convert <code>self</code> to <code>to_enc</code>.
# <code>to_enc</code> and <code>from_enc</code> are given as constants of Kconv or Encoding objects.
def kconv(to_enc, from_enc=nil)
from_enc = self.encoding if !from_enc && self.encoding != Encoding.list[0]
Kconv::kconv(self, to_enc, from_enc)
end
#
# to Encoding
#
# call-seq:
# String#tojis => string
#
# Convert <code>self</code> to ISO-2022-JP
def tojis; Kconv.tojis(self) end
# call-seq:
# String#toeuc => string
#
# Convert <code>self</code> to EUC-JP
def toeuc; Kconv.toeuc(self) end
# call-seq:
# String#tosjis => string
#
# Convert <code>self</code> to Shift_JIS
def tosjis; Kconv.tosjis(self) end
# call-seq:
# String#toutf8 => string
#
# Convert <code>self</code> to UTF-8
def toutf8; Kconv.toutf8(self) end
# call-seq:
# String#toutf16 => string
#
# Convert <code>self</code> to UTF-16
def toutf16; Kconv.toutf16(self) end
# call-seq:
# String#toutf32 => string
#
# Convert <code>self</code> to UTF-32
def toutf32; Kconv.toutf32(self) end
# call-seq:
# String#tolocale => string
#
# Convert <code>self</code> to locale encoding
def tolocale; Kconv.tolocale(self) end
#
# is Encoding
#
# call-seq:
# String#iseuc => true or false
#
# Returns whether <code>self</code>'s encoding is EUC-JP or not.
def iseuc; Kconv.iseuc(self) end
# call-seq:
# String#issjis => true or false
#
# Returns whether <code>self</code>'s encoding is Shift_JIS or not.
def issjis; Kconv.issjis(self) end
# call-seq:
# String#isjis => true or false
#
# Returns whether <code>self</code>'s encoding is ISO-2022-JP or not.
def isjis; Kconv.isjis(self) end
# call-seq:
# String#isutf8 => true or false
#
# Returns whether <code>self</code>'s encoding is UTF-8 or not.
def isutf8; Kconv.isutf8(self) end
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/json.rb | lib/json.rb | require 'json/common'
##
# = JavaScript Object Notation (JSON)
#
# JSON is a lightweight data-interchange format. It is easy for us
# humans to read and write. Plus, equally simple for machines to generate or parse.
# JSON is completely language agnostic, making it the ideal interchange format.
#
# Built on two universally available structures:
# 1. A collection of name/value pairs. Often referred to as an _object_, hash table, record, struct, keyed list, or associative array.
# 2. An ordered list of values. More commonly called an _array_, vector, sequence or list.
#
# To read more about JSON visit: http://json.org
#
# == Parsing JSON
#
# To parse a JSON string received by another application or generated within
# your existing application:
#
# require 'json'
#
# my_hash = JSON.parse('{"hello": "goodbye"}')
# puts my_hash["hello"] => "goodbye"
#
# Notice the extra quotes <tt>''</tt> around the hash notation. Ruby expects
# the argument to be a string and can't convert objects like a hash or array.
#
# Ruby converts your string into a hash
#
# == Generating JSON
#
# Creating a JSON string for communication or serialization is
# just as simple.
#
# require 'json'
#
# my_hash = {:hello => "goodbye"}
# puts JSON.generate(my_hash) => "{\"hello\":\"goodbye\"}"
#
# Or an alternative way:
#
# require 'json'
# puts {:hello => "goodbye"}.to_json => "{\"hello\":\"goodbye\"}"
#
# <tt>JSON.generate</tt> only allows objects or arrays to be converted
# to JSON syntax. <tt>to_json</tt>, however, accepts many Ruby classes
# even though it acts only as a method for serialization:
#
# require 'json'
#
# 1.to_json => "1"
#
module JSON
require 'json/version'
begin
require 'json/ext'
rescue LoadError
require 'json/pure'
end
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/irb.rb | lib/irb.rb | #
# irb.rb - irb main module
# $Release Version: 0.9.6 $
# $Revision: 42045 $
# 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
# IRB stands for "interactive Ruby" and is a tool to interactively execute Ruby
# expressions read from the standard input.
#
# The +irb+ command from your shell will start the interpreter.
#
# == Usage
#
# Use of irb is easy if you know Ruby.
#
# When executing irb, prompts are displayed as follows. Then, enter the Ruby
# expression. An input is executed when it is syntactically complete.
#
# $ irb
# irb(main):001:0> 1+2
# #=> 3
# irb(main):002:0> class Foo
# irb(main):003:1> def foo
# irb(main):004:2> print 1
# irb(main):005:2> end
# irb(main):006:1> end
# #=> nil
#
# The Readline extension module can be used with irb. Use of Readline is
# default if it's installed.
#
# == Command line options
#
# Usage: irb.rb [options] [programfile] [arguments]
# -f Suppress read of ~/.irbrc
# -m Bc mode (load mathn, fraction or matrix are available)
# -d Set $DEBUG to true (same as `ruby -d')
# -r load-module Same as `ruby -r'
# -I path Specify $LOAD_PATH directory
# -U Same as `ruby -U`
# -E enc Same as `ruby -E`
# -w Same as `ruby -w`
# -W[level=2] Same as `ruby -W`
# --inspect Use `inspect' for output (default except for bc mode)
# --noinspect Don't use inspect for output
# --readline Use Readline extension module
# --noreadline Don't use Readline extension module
# --prompt prompt-mode
# --prompt-mode prompt-mode
# Switch prompt mode. Pre-defined prompt modes are
# `default', `simple', `xmp' and `inf-ruby'
# --inf-ruby-mode Use prompt appropriate for inf-ruby-mode on emacs.
# Suppresses --readline.
# --simple-prompt Simple prompt mode
# --noprompt No prompt mode
# --tracer Display trace for each execution of commands.
# --back-trace-limit n
# Display backtrace top n and tail n. The default
# value is 16.
# --irb_debug n Set internal debug level to n (not for popular use)
# -v, --version Print the version of irb
#
# == Configuration
#
# IRB reads from <code>~/.irbrc</code> when it's invoked.
#
# If <code>~/.irbrc</code> doesn't exist, +irb+ will try to read in the following order:
#
# * +.irbrc+
# * +irb.rc+
# * +_irbrc+
# * <code>$irbrc</code>
#
# The following are alternatives to the command line options. To use them type
# as follows in an +irb+ session:
#
# IRB.conf[:IRB_NAME]="irb"
# IRB.conf[:MATH_MODE]=false
# IRB.conf[:INSPECT_MODE]=nil
# IRB.conf[:IRB_RC] = nil
# IRB.conf[:BACK_TRACE_LIMIT]=16
# IRB.conf[:USE_LOADER] = false
# IRB.conf[:USE_READLINE] = nil
# IRB.conf[:USE_TRACER] = false
# IRB.conf[:IGNORE_SIGINT] = true
# IRB.conf[:IGNORE_EOF] = false
# IRB.conf[:PROMPT_MODE] = :DEFAULT
# IRB.conf[:PROMPT] = {...}
# IRB.conf[:DEBUG_LEVEL]=0
#
# === Auto indentation
#
# To enable auto-indent mode in irb, add the following to your +.irbrc+:
#
# IRB.conf[:AUTO_INDENT] = true
#
# === Autocompletion
#
# To enable autocompletion for irb, add the following to your +.irbrc+:
#
# require 'irb/completion'
#
# === History
#
# By default, irb disables history and will not store any commands you used.
#
# If you want to enable history, add the following to your +.irbrc+:
#
# IRB.conf[:SAVE_HISTORY] = 1000
#
# This will now store the last 1000 commands in <code>~/.irb_history</code>.
#
# See IRB::Context#save_history= for more information.
#
# == Customizing the IRB Prompt
#
# In order to customize the prompt, you can change the following Hash:
#
# IRB.conf[:PROMPT]
#
# This example can be used in your +.irbrc+
#
# IRB.conf[:PROMPT][:MY_PROMPT] = { # name of prompt mode
# :AUTO_INDENT => true # enables auto-indent mode
# :PROMPT_I => nil, # normal prompt
# :PROMPT_S => nil, # prompt for continuated strings
# :PROMPT_C => nil, # prompt for continuated statement
# :RETURN => " ==>%s\n" # format to return value
# }
#
# IRB.conf[:PROMPT_MODE] = :MY_PROMPT
#
# Or, invoke irb with the above prompt mode by:
#
# irb --prompt my-prompt
#
# Constants +PROMPT_I+, +PROMPT_S+ and +PROMPT_C+ specify the format. In the
# prompt specification, some special strings are available:
#
# %N # command name which is running
# %m # to_s of main object (self)
# %M # inspect of main object (self)
# %l # type of string(", ', /, ]), `]' is inner %w[...]
# %NNi # indent level. NN is degits and means as same as printf("%NNd").
# # It can be ommited
# %NNn # line number.
# %% # %
#
# For instance, the default prompt mode is defined as follows:
#
# IRB.conf[:PROMPT_MODE][:DEFAULT] = {
# :PROMPT_I => "%N(%m):%03n:%i> ",
# :PROMPT_S => "%N(%m):%03n:%i%l ",
# :PROMPT_C => "%N(%m):%03n:%i* ",
# :RETURN => "%s\n" # used to printf
# }
#
# irb comes with a number of available modes:
#
# # :NULL:
# # :PROMPT_I:
# # :PROMPT_N:
# # :PROMPT_S:
# # :PROMPT_C:
# # :RETURN: |
# # %s
# # :DEFAULT:
# # :PROMPT_I: ! '%N(%m):%03n:%i> '
# # :PROMPT_N: ! '%N(%m):%03n:%i> '
# # :PROMPT_S: ! '%N(%m):%03n:%i%l '
# # :PROMPT_C: ! '%N(%m):%03n:%i* '
# # :RETURN: |
# # => %s
# # :CLASSIC:
# # :PROMPT_I: ! '%N(%m):%03n:%i> '
# # :PROMPT_N: ! '%N(%m):%03n:%i> '
# # :PROMPT_S: ! '%N(%m):%03n:%i%l '
# # :PROMPT_C: ! '%N(%m):%03n:%i* '
# # :RETURN: |
# # %s
# # :SIMPLE:
# # :PROMPT_I: ! '>> '
# # :PROMPT_N: ! '>> '
# # :PROMPT_S:
# # :PROMPT_C: ! '?> '
# # :RETURN: |
# # => %s
# # :INF_RUBY:
# # :PROMPT_I: ! '%N(%m):%03n:%i> '
# # :PROMPT_N:
# # :PROMPT_S:
# # :PROMPT_C:
# # :RETURN: |
# # %s
# # :AUTO_INDENT: true
# # :XMP:
# # :PROMPT_I:
# # :PROMPT_N:
# # :PROMPT_S:
# # :PROMPT_C:
# # :RETURN: |2
# # ==>%s
#
# == Restrictions
#
# Because irb evaluates input immediately after it is syntactically complete,
# the results may be slightly different than directly using Ruby.
#
# == IRB Sessions
#
# IRB has a special feature, that allows you to manage many sessions at once.
#
# You can create new sessions with Irb.irb, and get a list of current sessions
# with the +jobs+ command in the prompt.
#
# === Commands
#
# JobManager provides commands to handle the current sessions:
#
# jobs # List of current sessions
# fg # Switches to the session of the given number
# kill # Kills the session with the given number
#
# The +exit+ command, or ::irb_exit, will quit the current session and call any
# exit hooks with IRB.irb_at_exit.
#
# A few commands for loading files within the session are also available:
#
# +source+::
# Loads a given file in the current session and displays the source lines,
# see IrbLoader#source_file
# +irb_load+::
# Loads the given file similarly to Kernel#load, see IrbLoader#irb_load
# +irb_require+::
# Loads the given file similarly to Kernel#require
#
# === Configuration
#
# The command line options, or IRB.conf, specify the default behavior of
# Irb.irb.
#
# On the other hand, each conf in IRB@Command+line+options is used to
# individually configure IRB.irb.
#
# If a proc is set for IRB.conf[:IRB_RC], its will be invoked after execution
# of that proc with the context of the current session as its argument. Each
# session can be configured using this mechanism.
#
# === Session variables
#
# There are a few variables in every Irb session that can come in handy:
#
# <code>_</code>::
# The value command executed, as a local variable
# <code>__</code>::
# The history of evaluated commands
# <code>__[line_no]</code>::
# Returns the evaluation value at the given line number, +line_no+.
# If +line_no+ is a negative, the return value +line_no+ many lines before
# the most recent return value.
#
# === Example using IRB Sessions
#
# # invoke a new session
# irb(main):001:0> irb
# # list open sessions
# irb.1(main):001:0> jobs
# #0->irb on main (#<Thread:0x400fb7e4> : stop)
# #1->irb#1 on main (#<Thread:0x40125d64> : running)
#
# # change the active session
# irb.1(main):002:0> fg 0
# # define class Foo in top-level session
# irb(main):002:0> class Foo;end
# # invoke a new session with the context of Foo
# irb(main):003:0> irb Foo
# # define Foo#foo
# irb.2(Foo):001:0> def foo
# irb.2(Foo):002:1> print 1
# irb.2(Foo):003:1> end
#
# # change the active session
# irb.2(Foo):004:0> fg 0
# # list open sessions
# irb(main):004:0> jobs
# #0->irb on main (#<Thread:0x400fb7e4> : running)
# #1->irb#1 on main (#<Thread:0x40125d64> : stop)
# #2->irb#2 on Foo (#<Thread:0x4011d54c> : stop)
# # check if Foo#foo is available
# irb(main):005:0> Foo.instance_methods #=> [:foo, ...]
#
# # change the active sesssion
# irb(main):006:0> fg 2
# # define Foo#bar in the context of Foo
# irb.2(Foo):005:0> def bar
# irb.2(Foo):006:1> print "bar"
# irb.2(Foo):007:1> end
# irb.2(Foo):010:0> Foo.instance_methods #=> [:bar, :foo, ...]
#
# # change the active session
# irb.2(Foo):011:0> fg 0
# irb(main):007:0> f = Foo.new #=> #<Foo:0x4010af3c>
# # invoke a new session with the context of f (instance of Foo)
# irb(main):008:0> irb f
# # list open sessions
# irb.3(<Foo:0x4010af3c>):001:0> jobs
# #0->irb on main (#<Thread:0x400fb7e4> : stop)
# #1->irb#1 on main (#<Thread:0x40125d64> : stop)
# #2->irb#2 on Foo (#<Thread:0x4011d54c> : stop)
# #3->irb#3 on #<Foo:0x4010af3c> (#<Thread:0x4010a1e0> : running)
# # evaluate f.foo
# irb.3(<Foo:0x4010af3c>):002:0> foo #=> 1 => nil
# # evaluate f.bar
# irb.3(<Foo:0x4010af3c>):003:0> bar #=> bar => nil
# # kill jobs 1, 2, and 3
# irb.3(<Foo:0x4010af3c>):004:0> kill 1, 2, 3
# # list open sesssions, should only include main session
# irb(main):009:0> jobs
# #0->irb on main (#<Thread:0x400fb7e4> : running)
# # quit irb
# irb(main):010:0> exit
module IRB
@RCS_ID='-$Id: irb.rb 42045 2013-07-18 13:50:32Z zzak $-'
# An exception raised by IRB.irb_abort
class Abort < Exception;end
@CONF = {}
# Displays current configuration.
#
# Modifing the configuration is achieved by sending a message to IRB.conf.
#
# See IRB@Configuration for more information.
def IRB.conf
@CONF
end
# Returns the current version of IRB, including release version and last
# updated date.
def IRB.version
if v = @CONF[:VERSION] then return v end
require "irb/version"
rv = @RELEASE_VERSION.sub(/\.0/, "")
@CONF[:VERSION] = format("irb %s(%s)", rv, @LAST_UPDATE_DATE)
end
# The current IRB::Context of the session, see IRB.conf
#
# irb
# irb(main):001:0> IRB.CurrentContext.irb_name = "foo"
# foo(main):002:0> IRB.conf[:MAIN_CONTEXT].irb_name #=> "foo"
def IRB.CurrentContext
IRB.conf[:MAIN_CONTEXT]
end
# Initializes IRB and creates a new Irb.irb object at the +TOPLEVEL_BINDING+
def IRB.start(ap_path = nil)
$0 = File::basename(ap_path, ".rb") if ap_path
IRB.setup(ap_path)
if @CONF[:SCRIPT]
irb = Irb.new(nil, @CONF[:SCRIPT])
else
irb = Irb.new
end
@CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC]
@CONF[:MAIN_CONTEXT] = irb.context
trap("SIGINT") do
irb.signal_handle
end
begin
catch(:IRB_EXIT) do
irb.eval_input
end
ensure
irb_at_exit
end
# print "\n"
end
# Calls each event hook of IRB.conf[:AT_EXIT] when the current session quits.
def IRB.irb_at_exit
@CONF[:AT_EXIT].each{|hook| hook.call}
end
# Quits irb
def IRB.irb_exit(irb, ret)
throw :IRB_EXIT, ret
end
# Aborts then interrupts irb.
#
# Will raise an Abort exception, or the given +exception+.
def IRB.irb_abort(irb, exception = Abort)
if defined? Thread
irb.context.thread.raise exception, "abort then interrupt!"
else
raise exception, "abort then interrupt!"
end
end
class Irb
# Creates a new irb session
def initialize(workspace = nil, input_method = nil, output_method = nil)
@context = Context.new(self, workspace, input_method, output_method)
@context.main.extend ExtendCommandBundle
@signal_status = :IN_IRB
@scanner = RubyLex.new
@scanner.exception_on_syntax_error = false
end
# Returns the current context of this irb session
attr_reader :context
# The lexer used by this irb session
attr_accessor :scanner
# Evaluates input for this session.
def eval_input
@scanner.set_prompt do
|ltype, indent, continue, line_no|
if ltype
f = @context.prompt_s
elsif continue
f = @context.prompt_c
elsif indent > 0
f = @context.prompt_n
else
f = @context.prompt_i
end
f = "" unless f
if @context.prompting?
@context.io.prompt = p = prompt(f, ltype, indent, line_no)
else
@context.io.prompt = p = ""
end
if @context.auto_indent_mode
unless ltype
ind = prompt(@context.prompt_i, ltype, indent, line_no)[/.*\z/].size +
indent * 2 - p.size
ind += 2 if continue
@context.io.prompt = p + " " * ind if ind > 0
end
end
end
@scanner.set_input(@context.io) do
signal_status(:IN_INPUT) do
if l = @context.io.gets
print l if @context.verbose?
else
if @context.ignore_eof? and @context.io.readable_after_eof?
l = "\n"
if @context.verbose?
printf "Use \"exit\" to leave %s\n", @context.ap_name
end
else
print "\n"
end
end
l
end
end
@scanner.each_top_level_statement do |line, line_no|
signal_status(:IN_EVAL) do
begin
line.untaint
@context.evaluate(line, line_no)
output_value if @context.echo?
exc = nil
rescue Interrupt => exc
rescue SystemExit, SignalException
raise
rescue Exception => exc
end
if exc
print exc.class, ": ", exc, "\n"
if exc.backtrace[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
# Evaluates the given block using the given +path+ as the Context#irb_path
# and +name+ as the Context#irb_name.
#
# Used by the irb command +source+, see IRB@IRB+Sessions for more
# information.
def suspend_name(path = nil, name = nil)
@context.irb_path, back_path = path, @context.irb_path if path
@context.irb_name, back_name = name, @context.irb_name if name
begin
yield back_path, back_name
ensure
@context.irb_path = back_path if path
@context.irb_name = back_name if name
end
end
# Evaluates the given block using the given +workspace+ as the
# Context#workspace.
#
# Used by the irb command +irb_load+, see IRB@IRB+Sessions for more
# information.
def suspend_workspace(workspace)
@context.workspace, back_workspace = workspace, @context.workspace
begin
yield back_workspace
ensure
@context.workspace = back_workspace
end
end
# Evaluates the given block using the given +input_method+ as the
# Context#io.
#
# Used by the irb commands +source+ and +irb_load+, see IRB@IRB+Sessions
# for more information.
def suspend_input_method(input_method)
back_io = @context.io
@context.instance_eval{@io = input_method}
begin
yield back_io
ensure
@context.instance_eval{@io = back_io}
end
end
# Evaluates the given block using the given +context+ as the Context.
def suspend_context(context)
@context, back_context = context, @context
begin
yield back_context
ensure
@context = back_context
end
end
# Handler for the signal SIGINT, see Kernel#trap for more information.
def signal_handle
unless @context.ignore_sigint?
print "\nabort!\n" if @context.verbose?
exit
end
case @signal_status
when :IN_INPUT
print "^C\n"
raise RubyLex::TerminateLineInput
when :IN_EVAL
IRB.irb_abort(self)
when :IN_LOAD
IRB.irb_abort(self, LoadAbort)
when :IN_IRB
# ignore
else
# ignore other cases as well
end
end
# Evaluates the given block using the given +status+.
def signal_status(status)
return yield if @signal_status == :IN_LOAD
signal_status_back = @signal_status
@signal_status = status
begin
yield
ensure
@signal_status = signal_status_back
end
end
def prompt(prompt, ltype, indent, line_no) # :nodoc:
p = prompt.dup
p.gsub!(/%([0-9]+)?([a-zA-Z])/) do
case $2
when "N"
@context.irb_name
when "m"
@context.main.to_s
when "M"
@context.main.inspect
when "l"
ltype
when "i"
if $1
format("%" + $1 + "d", indent)
else
indent.to_s
end
when "n"
if $1
format("%" + $1 + "d", line_no)
else
line_no.to_s
end
when "%"
"%"
end
end
p
end
def output_value # :nodoc:
printf @context.return_format, @context.inspect_last_value
end
# Outputs the local variables to this current session, including
# #signal_status and #context, using IRB::Locale.
def inspect
ary = []
for iv in instance_variables
case (iv = iv.to_s)
when "@signal_status"
ary.push format("%s=:%s", iv, @signal_status.id2name)
when "@context"
ary.push format("%s=%s", iv, eval(iv).__to_s__)
else
ary.push format("%s=%s", iv, eval(iv))
end
end
format("#<%s: %s>", self.class, ary.join(", "))
end
end
def @CONF.inspect
IRB.version unless self[:VERSION]
array = []
for k, v in sort{|a1, a2| a1[0].id2name <=> a2[0].id2name}
case k
when :MAIN_CONTEXT, :__TMP__EHV__
array.push format("CONF[:%s]=...myself...", k.id2name)
when :PROMPT
s = v.collect{
|kk, vv|
ss = vv.collect{|kkk, vvv| ":#{kkk.id2name}=>#{vvv.inspect}"}
format(":%s=>{%s}", kk.id2name, ss.join(", "))
}
array.push format("CONF[:%s]={%s}", k.id2name, s.join(", "))
else
array.push format("CONF[:%s]=%s", k.id2name, v.inspect)
end
end
array.join("\n")
end
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/prime.rb | lib/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
#
# Prime is Enumerable:
#
# Prime.first 5 # => [2, 3, 5, 7, 11]
#
# == 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.
# Furthermore, it is an external iterator of prime enumeration which is
# compatible with an Enumerator.
#
# +Prime+::+PseudoPrimeGenerator+ is the base class for generators.
# There are few implementations of generator.
#
# [+Prime+::+EratosthenesGenerator+]
# Uses eratosthenes' sieve.
# [+Prime+::+TrialDivisionGenerator+]
# Uses the trial division method.
# [+Prime+::+Generator23+]
# Generates all positive integers which are not divisible by either 2 or 3.
# This sequence is very bad as a pseudo-prime sequence. But this
# is faster and uses much less memory than the 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 it
# yields all prime numbers p <= +ubound+.
#
# == Note
#
# +Prime+.+new+ returns an object extended by +Prime+::+OldCompatibility+
# in order to be compatible with 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 <tt>[[p_1, e_1], [p_2, e_2], ...., [p_n, e_n]]</tt>, 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 ascending
# order. It must generate all prime numbers,
# but may also generate non prime numbers too.
#
# === 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 number.
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_index = -1
super
end
def succ
@last_prime_index += 1
EratosthenesSieve.instance.get_nth_prime(@last_prime_index)
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
super
end
def succ
TrialDivision.instance[@index += 1]
end
def rewind
initialize
end
alias next succ
end
# Generates all integers which are greater than 2 and
# are not divisible by either 2 or 3.
#
# This is a pseudo-prime generator, suitable on
# checking primality of an integer by brute force
# method.
class Generator23<PseudoPrimeGenerator
def initialize
@prime = 1
@step = nil
super
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' sieve
class EratosthenesSieve
include Singleton
def initialize
@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]
# @max_checked must be an even number
@max_checked = @primes.last + 1
end
def get_nth_prime(n)
compute_primes while @primes.size <= n
@primes[n]
end
private
def compute_primes
# max_segment_size must be an even number
max_segment_size = 1e6.to_i
max_cached_prime = @primes.last
# do not double count primes if #compute_primes is interrupted
# by Timeout.timeout
@max_checked = max_cached_prime + 1 if max_cached_prime > @max_checked
segment_min = @max_checked
segment_max = [segment_min + max_segment_size, max_cached_prime * 2].min
root = Integer(Math.sqrt(segment_max).floor)
sieving_primes = @primes[1 .. -1].take_while { |prime| prime <= root }
offsets = Array.new(sieving_primes.size) do |i|
(-(segment_min + 1 + sieving_primes[i]) / 2) % sieving_primes[i]
end
segment = ((segment_min + 1) .. segment_max).step(2).to_a
sieving_primes.each_with_index do |prime, index|
composite_index = offsets[index]
while composite_index < segment.size do
segment[composite_index] = nil
composite_index += prime
end
end
segment.each do |prime|
@primes.push prime unless prime.nil?
end
@max_checked = segment_max
end
end
# Provides a +Prime+ object with compatibility to Ruby 1.8 when instantiated 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 | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/base64.rb | lib/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 characters.
#
# 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 | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/un.rb | lib/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 httpd -- [OPTION] DocumentRoot
# ruby -run -e help [COMMAND]
require "fileutils"
require "optparse"
module FileUtils
# @fileutils_label = ""
@fileutils_output = $stdout
end
# :nodoc:
def setup(options = "", *long_options)
caller = caller_locations(1, 1)[0].label
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, arg_name = s.split(/(?=[\s=])/, 2)
opt_name.sub!(/\A--/, '')
s = "--#{opt_name.gsub(/([A-Z]+|[a-z])([A-Z])/, '\1-\2').downcase}#{arg_name}"
puts "#{opt_name}=>#{s}" if $DEBUG
opt_name = opt_name.intern
o.on(s) do |val|
opt_hash[opt_name] = val
end
end
o.on("-v") do opt_hash[:verbose] = true end
o.on("--help") do
UN.help([caller])
exit
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
if verbose
puts e
STDOUT.flush
end
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
##
# Run WEBrick HTTP server.
#
# ruby -run -e httpd -- [OPTION] DocumentRoot
#
# --bind-address=ADDR address to bind
# --port=NUM listening port number
# --max-clients=MAX max number of simultaneous clients
# --temp-dir=DIR temporary directory
# --do-not-reverse-lookup disable reverse lookup
# --request-timeout=SECOND request timeout in seconds
# --http-version=VERSION HTTP version
# -v verbose
#
def httpd
setup("", "BindAddress=ADDR", "Port=PORT", "MaxClients=NUM", "TempDir=DIR",
"DoNotReverseLookup", "RequestTimeout=SECOND", "HTTPVersion=VERSION") do
|argv, options|
require 'webrick'
opt = options[:RequestTimeout] and options[:RequestTimeout] = opt.to_i
[:Port, :MaxClients].each do |name|
opt = options[name] and (options[name] = Integer(opt)) rescue nil
end
unless argv.size == 1
raise ArgumentError, "DocumentRoot is mandatory"
end
options[:DocumentRoot] = argv.shift
s = WEBrick::HTTPServer.new(options)
shut = proc {s.shutdown}
siglist = %w"TERM QUIT"
siglist.concat(%w"HUP INT") if STDIN.tty?
siglist &= Signal.list.keys
siglist.each do |sig|
Signal.trap(sig, shut)
end
s.start
end
end
##
# Display help message.
#
# ruby -run -e help [COMMAND]
#
def help
setup do |argv,|
UN.help(argv)
end
end
module UN # :nodoc:
module_function
def help(argv, output: $stdout)
all = argv.empty?
cmd = nil
if all
store = proc {|msg| output << msg}
else
messages = {}
store = proc {|msg| messages[cmd] = msg}
end
open(__FILE__) do |me|
while me.gets("##\n")
if help = me.gets("\n\n")
if all or argv.include?(cmd = help[/^#\s*ruby\s.*-e\s+(\w+)/, 1])
store[help.gsub(/^# ?/, "")]
break unless all or argv.size > messages.size
end
end
end
end
if messages
argv.each {|cmd| output << messages[cmd]}
end
end
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/openssl.rb | lib/openssl.rb | =begin
= $RCSfile$ -- Loader for all OpenSSL C-space and Ruby-space definitions
= Info
'OpenSSL for Ruby 2' project
Copyright (C) 2002 Michal Rokos <m.rokos@sh.cvut.cz>
All rights reserved.
= Licence
This program is licenced under the same licence as Ruby.
(See the file 'LICENCE'.)
= Version
$Id: openssl.rb 32664 2011-07-25 06:30:07Z nahi $
=end
require 'openssl.so'
require 'openssl/bn'
require 'openssl/cipher'
require 'openssl/config'
require 'openssl/digest'
require 'openssl/x509'
require 'openssl/ssl'
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/rubygems.rb | lib/rubygems.rb | # -*- ruby -*-
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'rbconfig'
module Gem
VERSION = '2.2.2'
end
# Must be first since it unloads the prelude from 1.9.2
require 'rubygems/compatibility'
require 'rubygems/defaults'
require 'rubygems/deprecate'
require 'rubygems/errors'
##
# RubyGems is the Ruby standard for publishing and managing third party
# libraries.
#
# For user documentation, see:
#
# * <tt>gem help</tt> and <tt>gem help [command]</tt>
# * {RubyGems User Guide}[http://docs.rubygems.org/read/book/1]
# * {Frequently Asked Questions}[http://docs.rubygems.org/read/book/3]
#
# For gem developer documentation see:
#
# * {Creating Gems}[http://docs.rubygems.org/read/chapter/5]
# * Gem::Specification
# * Gem::Version for version dependency notes
#
# Further RubyGems documentation can be found at:
#
# * {RubyGems Guides}[http://guides.rubygems.org]
# * {RubyGems API}[http://rubygems.rubyforge.org/rdoc] (also available from
# <tt>gem server</tt>)
#
# == RubyGems Plugins
#
# As of RubyGems 1.3.2, RubyGems will load plugins installed in gems or
# $LOAD_PATH. Plugins must be named 'rubygems_plugin' (.rb, .so, etc) and
# placed at the root of your gem's #require_path. Plugins are discovered via
# Gem::find_files then loaded. Take care when implementing a plugin as your
# plugin file may be loaded multiple times if multiple versions of your gem
# are installed.
#
# For an example plugin, see the graph gem which adds a `gem graph` command.
#
# == RubyGems Defaults, Packaging
#
# RubyGems defaults are stored in rubygems/defaults.rb. If you're packaging
# RubyGems or implementing Ruby you can change RubyGems' defaults.
#
# For RubyGems packagers, provide lib/rubygems/operating_system.rb and
# override any defaults from lib/rubygems/defaults.rb.
#
# For Ruby implementers, provide lib/rubygems/defaults/#{RUBY_ENGINE}.rb and
# override any defaults from lib/rubygems/defaults.rb.
#
# If you need RubyGems to perform extra work on install or uninstall, your
# defaults override file can set pre and post install and uninstall hooks.
# See Gem::pre_install, Gem::pre_uninstall, Gem::post_install,
# Gem::post_uninstall.
#
# == Bugs
#
# You can submit bugs to the
# {RubyGems bug tracker}[https://github.com/rubygems/rubygems/issues]
# on GitHub
#
# == Credits
#
# RubyGems is currently maintained by Eric Hodel.
#
# RubyGems was originally developed at RubyConf 2003 by:
#
# * Rich Kilmer -- rich(at)infoether.com
# * Chad Fowler -- chad(at)chadfowler.com
# * David Black -- dblack(at)wobblini.net
# * Paul Brannan -- paul(at)atdesk.com
# * Jim Weirch -- jim(at)weirichhouse.org
#
# Contributors:
#
# * Gavin Sinclair -- gsinclair(at)soyabean.com.au
# * George Marrows -- george.marrows(at)ntlworld.com
# * Dick Davies -- rasputnik(at)hellooperator.net
# * Mauricio Fernandez -- batsman.geo(at)yahoo.com
# * Simon Strandgaard -- neoneye(at)adslhome.dk
# * Dave Glasser -- glasser(at)mit.edu
# * Paul Duncan -- pabs(at)pablotron.org
# * Ville Aine -- vaine(at)cs.helsinki.fi
# * Eric Hodel -- drbrain(at)segment7.net
# * Daniel Berger -- djberg96(at)gmail.com
# * Phil Hagelberg -- technomancy(at)gmail.com
# * Ryan Davis -- ryand-ruby(at)zenspider.com
# * Evan Phoenix -- evan(at)fallingsnow.net
# * Steve Klabnik -- steve(at)steveklabnik.com
#
# (If your name is missing, PLEASE let us know!)
#
# See {LICENSE.txt}[rdoc-ref:lib/rubygems/LICENSE.txt] for permissions.
#
# Thanks!
#
# -The RubyGems Team
module Gem
RUBYGEMS_DIR = File.dirname File.expand_path(__FILE__)
##
# An Array of Regexps that match windows Ruby platforms.
WIN_PATTERNS = [
/bccwin/i,
/cygwin/i,
/djgpp/i,
/mingw/i,
/mswin/i,
/wince/i,
]
GEM_DEP_FILES = %w[
gem.deps.rb
Gemfile
Isolate
]
##
# Subdirectories in a gem repository
REPOSITORY_SUBDIRECTORIES = %w[
build_info
cache
doc
extensions
gems
specifications
]
##
# Subdirectories in a gem repository for default gems
REPOSITORY_DEFAULT_GEM_SUBDIRECTORIES = %w[
gems
specifications/default
]
@@win_platform = nil
@configuration = nil
@loaded_specs = {}
@path_to_default_spec_map = {}
@platforms = []
@ruby = nil
@ruby_api_version = nil
@sources = nil
@post_build_hooks ||= []
@post_install_hooks ||= []
@post_uninstall_hooks ||= []
@pre_uninstall_hooks ||= []
@pre_install_hooks ||= []
@pre_reset_hooks ||= []
@post_reset_hooks ||= []
##
# Try to activate a gem containing +path+. Returns true if
# activation succeeded or wasn't needed because it was already
# activated. Returns false if it can't find the path in a gem.
def self.try_activate path
# finds the _latest_ version... regardless of loaded specs and their deps
# if another gem had a requirement that would mean we shouldn't
# activate the latest version, then either it would already be activated
# or if it was ambiguous (and thus unresolved) the code in our custom
# require will try to activate the more specific version.
spec = Gem::Specification.find_inactive_by_path path
unless spec
spec = Gem::Specification.find_by_path path
return true if spec && spec.activated?
return false
end
begin
spec.activate
rescue Gem::LoadError # this could fail due to gem dep collisions, go lax
Gem::Specification.find_by_name(spec.name).activate
end
return true
end
def self.needs
rs = Gem::RequestSet.new
yield rs
finish_resolve rs
end
def self.finish_resolve(request_set=Gem::RequestSet.new)
request_set.import Gem::Specification.unresolved_deps.values
request_set.resolve_current.each do |s|
s.full_spec.activate
end
end
##
# Find the full path to the executable for gem +name+. If the +exec_name+
# is not given, the gem's default_executable is chosen, otherwise the
# specified executable's path is returned. +requirements+ allows
# you to specify specific gem versions.
def self.bin_path(name, exec_name = nil, *requirements)
# TODO: fails test_self_bin_path_bin_file_gone_in_latest
# Gem::Specification.find_by_name(name, *requirements).bin_file exec_name
raise ArgumentError, "you must supply exec_name" unless exec_name
requirements = Gem::Requirement.default if
requirements.empty?
specs = Gem::Dependency.new(name, requirements).matching_specs(true)
raise Gem::GemNotFoundException,
"can't find gem #{name} (#{requirements})" if specs.empty?
specs = specs.find_all { |spec|
spec.executables.include? exec_name
} if exec_name
unless spec = specs.last
msg = "can't find gem #{name} (#{requirements}) with executable #{exec_name}"
raise Gem::GemNotFoundException, msg
end
spec.bin_file exec_name
end
##
# The mode needed to read a file as straight binary.
def self.binary_mode
'rb'
end
##
# The path where gem executables are to be installed.
def self.bindir(install_dir=Gem.dir)
return File.join install_dir, 'bin' unless
install_dir.to_s == Gem.default_dir.to_s
Gem.default_bindir
end
##
# Reset the +dir+ and +path+ values. The next time +dir+ or +path+
# is requested, the values will be calculated from scratch. This is
# mainly used by the unit tests to provide test isolation.
def self.clear_paths
@paths = nil
@user_home = nil
Gem::Specification.reset
Gem::Security.reset if defined?(Gem::Security)
end
##
# The path to standard location of the user's .gemrc file.
def self.config_file
@config_file ||= File.join Gem.user_home, '.gemrc'
end
##
# The standard configuration object for gems.
def self.configuration
@configuration ||= Gem::ConfigFile.new []
end
##
# Use the given configuration object (which implements the ConfigFile
# protocol) as the standard configuration object.
def self.configuration=(config)
@configuration = config
end
##
# The path the the data directory specified by the gem name. If the
# package is not available as a gem, return nil.
def self.datadir(gem_name)
# TODO: deprecate and move to Gem::Specification
# and drop the extra ", gem_name" which is uselessly redundant
spec = @loaded_specs[gem_name]
return nil if spec.nil?
File.join spec.full_gem_path, "data", gem_name
end
##
# A Zlib::Deflate.deflate wrapper
def self.deflate(data)
require 'zlib'
Zlib::Deflate.deflate data
end
# Retrieve the PathSupport object that RubyGems uses to
# lookup files.
def self.paths
@paths ||= Gem::PathSupport.new
end
# Initialize the filesystem paths to use from +env+.
# +env+ is a hash-like object (typically ENV) that
# is queried for 'GEM_HOME', 'GEM_PATH', and 'GEM_SPEC_CACHE'
def self.paths=(env)
clear_paths
@paths = Gem::PathSupport.new env
Gem::Specification.dirs = @paths.path
end
##
# The path where gems are to be installed.
#--
# FIXME deprecate these once everything else has been done -ebh
def self.dir
paths.home
end
def self.path
paths.path
end
def self.spec_cache_dir
paths.spec_cache_dir
end
##
# Quietly ensure the Gem directory +dir+ contains all the proper
# subdirectories. If we can't create a directory due to a permission
# problem, then we will silently continue.
#
# If +mode+ is given, missing directories are created with this mode.
#
# World-writable directories will never be created.
def self.ensure_gem_subdirectories dir = Gem.dir, mode = nil
ensure_subdirectories(dir, mode, REPOSITORY_SUBDIRECTORIES)
end
##
# Quietly ensure the Gem directory +dir+ contains all the proper
# subdirectories for handling default gems. If we can't create a
# directory due to a permission problem, then we will silently continue.
#
# If +mode+ is given, missing directories are created with this mode.
#
# World-writable directories will never be created.
def self.ensure_default_gem_subdirectories dir = Gem.dir, mode = nil
ensure_subdirectories(dir, mode, REPOSITORY_DEFAULT_GEM_SUBDIRECTORIES)
end
def self.ensure_subdirectories dir, mode, subdirs # :nodoc:
old_umask = File.umask
File.umask old_umask | 002
require 'fileutils'
options = {}
options[:mode] = mode if mode
subdirs.each do |name|
subdir = File.join dir, name
next if File.exist? subdir
FileUtils.mkdir_p subdir, options rescue nil
end
ensure
File.umask old_umask
end
##
# The extension API version of ruby. This includes the static vs non-static
# distinction as extensions cannot be shared between the two.
def self.extension_api_version # :nodoc:
if 'no' == RbConfig::CONFIG['ENABLE_SHARED'] then
"#{ruby_api_version}-static"
else
ruby_api_version
end
end
##
# Returns a list of paths matching +glob+ that can be used by a gem to pick
# up features from other gems. For example:
#
# Gem.find_files('rdoc/discover').each do |path| load path end
#
# if +check_load_path+ is true (the default), then find_files also searches
# $LOAD_PATH for files as well as gems.
#
# Note that find_files will return all files even if they are from different
# versions of the same gem. See also find_latest_files
def self.find_files(glob, check_load_path=true)
files = []
files = find_files_from_load_path glob if check_load_path
files.concat Gem::Specification.map { |spec|
spec.matches_for_glob("#{glob}#{Gem.suffix_pattern}")
}.flatten
# $LOAD_PATH might contain duplicate entries or reference
# the spec dirs directly, so we prune.
files.uniq! if check_load_path
return files
end
def self.find_files_from_load_path glob # :nodoc:
$LOAD_PATH.map { |load_path|
Dir["#{File.expand_path glob, load_path}#{Gem.suffix_pattern}"]
}.flatten.select { |file| File.file? file.untaint }
end
##
# Returns a list of paths matching +glob+ from the latest gems that can be
# used by a gem to pick up features from other gems. For example:
#
# Gem.find_latest_files('rdoc/discover').each do |path| load path end
#
# if +check_load_path+ is true (the default), then find_latest_files also
# searches $LOAD_PATH for files as well as gems.
#
# Unlike find_files, find_latest_files will return only files from the
# latest version of a gem.
def self.find_latest_files(glob, check_load_path=true)
files = []
files = find_files_from_load_path glob if check_load_path
files.concat Gem::Specification.latest_specs(true).map { |spec|
spec.matches_for_glob("#{glob}#{Gem.suffix_pattern}")
}.flatten
# $LOAD_PATH might contain duplicate entries or reference
# the spec dirs directly, so we prune.
files.uniq! if check_load_path
return files
end
##
# Finds the user's home directory.
#--
# Some comments from the ruby-talk list regarding finding the home
# directory:
#
# I have HOME, USERPROFILE and HOMEDRIVE + HOMEPATH. Ruby seems
# to be depending on HOME in those code samples. I propose that
# it should fallback to USERPROFILE and HOMEDRIVE + HOMEPATH (at
# least on Win32).
#++
#--
#
# FIXME move to pathsupport
#
#++
def self.find_home
windows = File::ALT_SEPARATOR
if not windows or RUBY_VERSION >= '1.9' then
File.expand_path "~"
else
['HOME', 'USERPROFILE'].each do |key|
return File.expand_path ENV[key] if ENV[key]
end
if ENV['HOMEDRIVE'] && ENV['HOMEPATH'] then
File.expand_path "#{ENV['HOMEDRIVE']}#{ENV['HOMEPATH']}"
end
end
rescue
if windows then
File.expand_path File.join(ENV['HOMEDRIVE'] || ENV['SystemDrive'], '/')
else
File.expand_path "/"
end
end
private_class_method :find_home
# FIXME deprecate these in 3.0
##
# Zlib::GzipReader wrapper that unzips +data+.
def self.gunzip(data)
require 'rubygems/util'
Gem::Util.gunzip data
end
##
# Zlib::GzipWriter wrapper that zips +data+.
def self.gzip(data)
require 'rubygems/util'
Gem::Util.gzip data
end
##
# A Zlib::Inflate#inflate wrapper
def self.inflate(data)
require 'rubygems/util'
Gem::Util.inflate data
end
##
# Top level install helper method. Allows you to install gems interactively:
#
# % irb
# >> Gem.install "minitest"
# Fetching: minitest-3.0.1.gem (100%)
# => [#<Gem::Specification:0x1013b4528 @name="minitest", ...>]
def self.install name, version = Gem::Requirement.default
require "rubygems/dependency_installer"
inst = Gem::DependencyInstaller.new
inst.install name, version
inst.installed_gems
end
##
# Get the default RubyGems API host. This is normally
# <tt>https://rubygems.org</tt>.
def self.host
# TODO: move to utils
@host ||= Gem::DEFAULT_HOST
end
## Set the default RubyGems API host.
def self.host= host
# TODO: move to utils
@host = host
end
##
# The index to insert activated gem paths into the $LOAD_PATH. The activated
# gem's paths are inserted before site lib directory by default.
def self.load_path_insert_index
index = $LOAD_PATH.index RbConfig::CONFIG['sitelibdir']
index
end
@yaml_loaded = false
##
# Loads YAML, preferring Psych
def self.load_yaml
return if @yaml_loaded
return unless defined?(gem)
test_syck = ENV['TEST_SYCK']
unless test_syck
begin
gem 'psych', '~> 1.2', '>= 1.2.1'
rescue Gem::LoadError
# It's OK if the user does not have the psych gem installed. We will
# attempt to require the stdlib version
end
begin
# Try requiring the gem version *or* stdlib version of psych.
require 'psych'
rescue ::LoadError
# If we can't load psych, thats fine, go on.
else
# If 'yaml' has already been required, then we have to
# be sure to switch it over to the newly loaded psych.
if defined?(YAML::ENGINE) && YAML::ENGINE.yamler != "psych"
YAML::ENGINE.yamler = "psych"
end
require 'rubygems/psych_additions'
require 'rubygems/psych_tree'
end
end
require 'yaml'
# If we're supposed to be using syck, then we may have to force
# activate it via the YAML::ENGINE API.
if test_syck and defined?(YAML::ENGINE)
YAML::ENGINE.yamler = "syck" unless YAML::ENGINE.syck?
end
# Now that we're sure some kind of yaml library is loaded, pull
# in our hack to deal with Syck's DefaultKey ugliness.
require 'rubygems/syck_hack'
@yaml_loaded = true
end
##
# The file name and line number of the caller of the caller of this method.
def self.location_of_caller
caller[1] =~ /(.*?):(\d+).*?$/i
file = $1
lineno = $2.to_i
[file, lineno]
end
##
# The version of the Marshal format for your Ruby.
def self.marshal_version
"#{Marshal::MAJOR_VERSION}.#{Marshal::MINOR_VERSION}"
end
##
# Set array of platforms this RubyGems supports (primarily for testing).
def self.platforms=(platforms)
@platforms = platforms
end
##
# Array of platforms this RubyGems supports.
def self.platforms
@platforms ||= []
if @platforms.empty?
@platforms = [Gem::Platform::RUBY, Gem::Platform.local]
end
@platforms
end
##
# Adds a post-build hook that will be passed an Gem::Installer instance
# when Gem::Installer#install is called. The hook is called after the gem
# has been extracted and extensions have been built but before the
# executables or gemspec has been written. If the hook returns +false+ then
# the gem's files will be removed and the install will be aborted.
def self.post_build(&hook)
@post_build_hooks << hook
end
##
# Adds a post-install hook that will be passed an Gem::Installer instance
# when Gem::Installer#install is called
def self.post_install(&hook)
@post_install_hooks << hook
end
##
# Adds a post-installs hook that will be passed a Gem::DependencyInstaller
# and a list of installed specifications when
# Gem::DependencyInstaller#install is complete
def self.done_installing(&hook)
@done_installing_hooks << hook
end
##
# Adds a hook that will get run after Gem::Specification.reset is
# run.
def self.post_reset(&hook)
@post_reset_hooks << hook
end
##
# Adds a post-uninstall hook that will be passed a Gem::Uninstaller instance
# and the spec that was uninstalled when Gem::Uninstaller#uninstall is
# called
def self.post_uninstall(&hook)
@post_uninstall_hooks << hook
end
##
# Adds a pre-install hook that will be passed an Gem::Installer instance
# when Gem::Installer#install is called. If the hook returns +false+ then
# the install will be aborted.
def self.pre_install(&hook)
@pre_install_hooks << hook
end
##
# Adds a hook that will get run before Gem::Specification.reset is
# run.
def self.pre_reset(&hook)
@pre_reset_hooks << hook
end
##
# Adds a pre-uninstall hook that will be passed an Gem::Uninstaller instance
# and the spec that will be uninstalled when Gem::Uninstaller#uninstall is
# called
def self.pre_uninstall(&hook)
@pre_uninstall_hooks << hook
end
##
# The directory prefix this RubyGems was installed at. If your
# prefix is in a standard location (ie, rubygems is installed where
# you'd expect it to be), then prefix returns nil.
def self.prefix
prefix = File.dirname RUBYGEMS_DIR
if prefix != File.expand_path(RbConfig::CONFIG['sitelibdir']) and
prefix != File.expand_path(RbConfig::CONFIG['libdir']) and
'lib' == File.basename(RUBYGEMS_DIR) then
prefix
end
end
##
# Refresh available gems from disk.
def self.refresh
Gem::Specification.reset
end
##
# Safely read a file in binary mode on all platforms.
def self.read_binary(path)
open path, 'rb+' do |f|
f.flock(File::LOCK_EX)
f.read
end
rescue Errno::EACCES
open path, 'rb' do |f|
f.read
end
end
##
# The path to the running Ruby interpreter.
def self.ruby
if @ruby.nil? then
@ruby = File.join(RbConfig::CONFIG['bindir'],
"#{RbConfig::CONFIG['ruby_install_name']}#{RbConfig::CONFIG['EXEEXT']}")
@ruby = "\"#{@ruby}\"" if @ruby =~ /\s/
end
@ruby
end
##
# Returns a String containing the API compatibility version of Ruby
def self.ruby_api_version
@ruby_api_version ||= RbConfig::CONFIG['ruby_version'].dup
end
##
# Returns the latest release-version specification for the gem +name+.
def self.latest_spec_for name
dependency = Gem::Dependency.new name
fetcher = Gem::SpecFetcher.fetcher
spec_tuples, = fetcher.spec_for_dependency dependency
spec, = spec_tuples.first
spec
end
##
# Returns the latest release version of RubyGems.
def self.latest_rubygems_version
latest_version_for('rubygems-update') or
raise "Can't find 'rubygems-update' in any repo. Check `gem source list`."
end
##
# Returns the version of the latest release-version of gem +name+
def self.latest_version_for name
spec = latest_spec_for name
spec and spec.version
end
##
# A Gem::Version for the currently running Ruby.
def self.ruby_version
return @ruby_version if defined? @ruby_version
version = RUBY_VERSION.dup
if defined?(RUBY_PATCHLEVEL) && RUBY_PATCHLEVEL != -1 then
version << ".#{RUBY_PATCHLEVEL}"
elsif defined?(RUBY_REVISION) then
version << ".dev.#{RUBY_REVISION}"
end
@ruby_version = Gem::Version.new version
end
##
# A Gem::Version for the currently running RubyGems
def self.rubygems_version
return @rubygems_version if defined? @rubygems_version
@rubygems_version = Gem::Version.new Gem::VERSION
end
##
# Returns an Array of sources to fetch remote gems from. Uses
# default_sources if the sources list is empty.
def self.sources
@sources ||= Gem::SourceList.from(default_sources)
end
##
# Need to be able to set the sources without calling
# Gem.sources.replace since that would cause an infinite loop.
#
# DOC: This comment is not documentation about the method itself, it's
# more of a code comment about the implementation.
def self.sources= new_sources
if !new_sources
@sources = nil
else
@sources = Gem::SourceList.from(new_sources)
end
end
##
# Glob pattern for require-able path suffixes.
def self.suffix_pattern
@suffix_pattern ||= "{#{suffixes.join(',')}}"
end
##
# Suffixes for require-able paths.
def self.suffixes
@suffixes ||= ['',
'.rb',
*%w(DLEXT DLEXT2).map { |key|
val = RbConfig::CONFIG[key]
next unless val and not val.empty?
".#{val}"
}
].compact.uniq
end
##
# Prints the amount of time the supplied block takes to run using the debug
# UI output.
def self.time(msg, width = 0, display = Gem.configuration.verbose)
now = Time.now
value = yield
elapsed = Time.now - now
ui.say "%2$*1$s: %3$3.3fs" % [-width, msg, elapsed] if display
value
end
##
# Lazily loads DefaultUserInteraction and returns the default UI.
def self.ui
require 'rubygems/user_interaction'
Gem::DefaultUserInteraction.ui
end
##
# Use the +home+ and +paths+ values for Gem.dir and Gem.path. Used mainly
# by the unit tests to provide environment isolation.
def self.use_paths(home, *paths)
paths = nil if paths == [nil]
paths = paths.first if Array === Array(paths).first
self.paths = { "GEM_HOME" => home, "GEM_PATH" => paths }
end
##
# The home directory for the user.
def self.user_home
@user_home ||= find_home.untaint
end
##
# Is this a windows platform?
def self.win_platform?
if @@win_platform.nil? then
ruby_platform = RbConfig::CONFIG['host_os']
@@win_platform = !!WIN_PATTERNS.find { |r| ruby_platform =~ r }
end
@@win_platform
end
##
# Load +plugins+ as Ruby files
def self.load_plugin_files plugins # :nodoc:
plugins.each do |plugin|
# Skip older versions of the GemCutter plugin: Its commands are in
# RubyGems proper now.
next if plugin =~ /gemcutter-0\.[0-3]/
begin
load plugin
rescue ::Exception => e
details = "#{plugin.inspect}: #{e.message} (#{e.class})"
warn "Error loading RubyGems plugin #{details}"
end
end
end
##
# Find the 'rubygems_plugin' files in the latest installed gems and load
# them
def self.load_plugins
# Remove this env var by at least 3.0
if ENV['RUBYGEMS_LOAD_ALL_PLUGINS']
load_plugin_files find_files('rubygems_plugin', false)
else
load_plugin_files find_latest_files('rubygems_plugin', false)
end
end
##
# Find all 'rubygems_plugin' files in $LOAD_PATH and load them
def self.load_env_plugins
path = "rubygems_plugin"
files = []
$LOAD_PATH.each do |load_path|
globbed = Dir["#{File.expand_path path, load_path}#{Gem.suffix_pattern}"]
globbed.each do |load_path_file|
files << load_path_file if File.file?(load_path_file.untaint)
end
end
load_plugin_files files
end
##
# Looks for gem dependency files (gem.deps.rb, Gemfile, Isolate) from the
# current directory up and activates the gems in the first file found.
#
# You can run this automatically when rubygems starts. To enable, set
# the <code>RUBYGEMS_GEMDEPS</code> environment variable to either the path
# of your Gemfile or "-" to auto-discover in parent directories.
#
# NOTE: Enabling automatic discovery on multiuser systems can lead to
# execution of arbitrary code when used from directories outside your
# control.
def self.use_gemdeps
return unless path = ENV['RUBYGEMS_GEMDEPS']
path = path.dup
if path == "-" then
require 'rubygems/util'
Gem::Util.traverse_parents Dir.pwd do |directory|
dep_file = GEM_DEP_FILES.find { |f| File.file?(f) }
next unless dep_file
path = File.join directory, dep_file
break
end
end
path.untaint
return unless File.file? path
rs = Gem::RequestSet.new
rs.load_gemdeps path
rs.resolve_current.map do |s|
sp = s.full_spec
sp.activate
sp
end
end
class << self
##
# TODO remove with RubyGems 3.0
alias detect_gemdeps use_gemdeps # :nodoc:
end
# FIX: Almost everywhere else we use the `def self.` way of defining class
# methods, and then we switch over to `class << self` here. Pick one or the
# other.
class << self
##
# Hash of loaded Gem::Specification keyed by name
attr_reader :loaded_specs
##
# Register a Gem::Specification for default gem.
#
# Two formats for the specification are supported:
#
# * MRI 2.0 style, where spec.files contains unprefixed require names.
# The spec's filenames will be registered as-is.
# * New style, where spec.files contains files prefixed with paths
# from spec.require_paths. The prefixes are stripped before
# registering the spec's filenames. Unprefixed files are omitted.
#
def register_default_spec(spec)
new_format = Gem.default_gems_use_full_paths? || spec.require_paths.any? {|path| spec.files.any? {|f| f.start_with? path } }
if new_format
prefix_group = spec.require_paths.map {|f| f + "/"}.join("|")
prefix_pattern = /^(#{prefix_group})/
end
spec.files.each do |file|
if new_format
file = file.sub(prefix_pattern, "")
next unless $~
end
@path_to_default_spec_map[file] = spec
end
end
##
# Find a Gem::Specification of default gem from +path+
def find_unresolved_default_spec(path)
Gem.suffixes.each do |suffix|
spec = @path_to_default_spec_map["#{path}#{suffix}"]
return spec if spec
end
nil
end
##
# Remove needless Gem::Specification of default gem from
# unresolved default gem list
def remove_unresolved_default_spec(spec)
spec.files.each do |file|
@path_to_default_spec_map.delete(file)
end
end
##
# Clear default gem related variables. It is for test
def clear_default_specs
@path_to_default_spec_map.clear
end
##
# The list of hooks to be run after Gem::Installer#install extracts files
# and builds extensions
attr_reader :post_build_hooks
##
# The list of hooks to be run after Gem::Installer#install completes
# installation
attr_reader :post_install_hooks
##
# The list of hooks to be run after Gem::DependencyInstaller installs a
# set of gems
attr_reader :done_installing_hooks
##
# The list of hooks to be run after Gem::Specification.reset is run.
attr_reader :post_reset_hooks
##
# The list of hooks to be run after Gem::Uninstaller#uninstall completes
# installation
attr_reader :post_uninstall_hooks
##
# The list of hooks to be run before Gem::Installer#install does any work
attr_reader :pre_install_hooks
##
# The list of hooks to be run before Gem::Specification.reset is run.
attr_reader :pre_reset_hooks
##
# The list of hooks to be run before Gem::Uninstaller#uninstall does any
# work
attr_reader :pre_uninstall_hooks
end
##
# Location of Marshal quick gemspecs on remote repositories
MARSHAL_SPEC_DIR = "quick/Marshal.#{Gem.marshal_version}/"
autoload :ConfigFile, 'rubygems/config_file'
autoload :Dependency, 'rubygems/dependency'
autoload :DependencyList, 'rubygems/dependency_list'
autoload :DependencyResolver, 'rubygems/resolver'
autoload :Installer, 'rubygems/installer'
autoload :PathSupport, 'rubygems/path_support'
autoload :Platform, 'rubygems/platform'
autoload :RequestSet, 'rubygems/request_set'
autoload :Requirement, 'rubygems/requirement'
autoload :Resolver, 'rubygems/resolver'
autoload :Source, 'rubygems/source'
autoload :SourceList, 'rubygems/source_list'
autoload :SpecFetcher, 'rubygems/spec_fetcher'
autoload :Specification, 'rubygems/specification'
autoload :Version, 'rubygems/version'
require "rubygems/specification"
end
require 'rubygems/exceptions'
# REFACTOR: This should be pulled out into some kind of hacks file.
gem_preluded = Gem::GEM_PRELUDE_SUCKAGE and defined? Gem
unless gem_preluded then # TODO: remove guard after 1.9.2 dropped
begin
##
# Defaults the operating system (or packager) wants to provide for RubyGems.
require 'rubygems/defaults/operating_system'
rescue LoadError
end
if defined?(RUBY_ENGINE) then
begin
##
# Defaults the Ruby implementation wants to provide for RubyGems
require "rubygems/defaults/#{RUBY_ENGINE}"
rescue LoadError
end
end
end
##
# Loads the default specs.
Gem::Specification.load_defaults
require 'rubygems/core_ext/kernel_gem'
require 'rubygems/core_ext/kernel_require'
Gem.use_gemdeps
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/uri.rb | lib/uri.rb | # URI is a module providing classes to handle Uniform Resource Identifiers
# (RFC2396[http://tools.ietf.org/html/rfc2396])
#
# == Features
#
# * Uniform handling of handling URIs
# * Flexibility to introduce custom URI schemes
# * Flexibility to have an alternate URI::Parser (or just different patterns
# and regexp's)
#
# == Basic example
#
# require 'uri'
#
# uri = URI("http://foo.com/posts?id=30&limit=5#time=1305298413")
# #=> #<URI::HTTP:0x00000000b14880
# URL:http://foo.com/posts?id=30&limit=5#time=1305298413>
# uri.scheme
# #=> "http"
# uri.host
# #=> "foo.com"
# uri.path
# #=> "/posts"
# uri.query
# #=> "id=30&limit=5"
# uri.fragment
# #=> "time=1305298413"
#
# uri.to_s
# #=> "http://foo.com/posts?id=30&limit=5#time=1305298413"
#
# == Adding custom URIs
#
# module URI
# class RSYNC < Generic
# DEFAULT_PORT = 873
# end
# @@schemes['RSYNC'] = RSYNC
# end
# #=> URI::RSYNC
#
# URI.scheme_list
# #=> {"FTP"=>URI::FTP, "HTTP"=>URI::HTTP, "HTTPS"=>URI::HTTPS,
# "LDAP"=>URI::LDAP, "LDAPS"=>URI::LDAPS, "MAILTO"=>URI::MailTo,
# "RSYNC"=>URI::RSYNC}
#
# uri = URI("rsync://rsync.foo.com")
# #=> #<URI::RSYNC:0x00000000f648c8 URL:rsync://rsync.foo.com>
#
# == RFC References
#
# A good place to view an RFC spec is http://www.ietf.org/rfc.html
#
# Here is a list of all related RFC's.
# - RFC822[http://tools.ietf.org/html/rfc822]
# - RFC1738[http://tools.ietf.org/html/rfc1738]
# - RFC2255[http://tools.ietf.org/html/rfc2255]
# - RFC2368[http://tools.ietf.org/html/rfc2368]
# - RFC2373[http://tools.ietf.org/html/rfc2373]
# - RFC2396[http://tools.ietf.org/html/rfc2396]
# - RFC2732[http://tools.ietf.org/html/rfc2732]
# - RFC3986[http://tools.ietf.org/html/rfc3986]
#
# == Class tree
#
# - URI::Generic (in uri/generic.rb)
# - URI::FTP - (in uri/ftp.rb)
# - URI::HTTP - (in uri/http.rb)
# - URI::HTTPS - (in uri/https.rb)
# - URI::LDAP - (in uri/ldap.rb)
# - URI::LDAPS - (in uri/ldaps.rb)
# - URI::MailTo - (in uri/mailto.rb)
# - URI::Parser - (in uri/common.rb)
# - URI::REGEXP - (in uri/common.rb)
# - URI::REGEXP::PATTERN - (in uri/common.rb)
# - URI::Util - (in uri/common.rb)
# - URI::Escape - (in uri/common.rb)
# - URI::Error - (in uri/common.rb)
# - URI::InvalidURIError - (in uri/common.rb)
# - URI::InvalidComponentError - (in uri/common.rb)
# - URI::BadURIError - (in uri/common.rb)
#
# == Copyright Info
#
# Author:: Akira Yamada <akira@ruby-lang.org>
# Documentation::
# Akira Yamada <akira@ruby-lang.org>
# Dmitry V. Sabanin <sdmitry@lrn.ru>
# Vincent Batts <vbatts@hashbangbash.com>
# 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 31555 2011-05-13 20:03:21Z drbrain $
#
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 | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/debug.rb | lib/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 # :nodoc:
def Tracer.trace_func(*vars)
Single.trace_func(*vars)
end
end
SCRIPT_LINES__ = {} unless defined? SCRIPT_LINES__ # :nodoc:
##
# This library provides debugging functionality to Ruby.
#
# To add a debugger to your code, start by requiring +debug+ in your
# program:
#
# def say(word)
# require 'debug'
# puts word
# end
#
# This will cause Ruby to interrupt execution and show a prompt when the +say+
# method is run.
#
# Once you're inside the prompt, you can start debugging your program.
#
# (rdb:1) p word
# "hello"
#
# == Getting help
#
# You can get help at any time by pressing +h+.
#
# (rdb:1) h
# 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
#
# == Usage
#
# The following is a list of common functionalities that the debugger
# provides.
#
# === Navigating through your code
#
# In general, a debugger is used to find bugs in your program, which
# often means pausing execution and inspecting variables at some point
# in time.
#
# Let's look at an example:
#
# def my_method(foo)
# require 'debug'
# foo = get_foo if foo.nil?
# raise if foo.nil?
# end
#
# When you run this program, the debugger will kick in just before the
# +foo+ assignment.
#
# (rdb:1) p foo
# nil
#
# In this example, it'd be interesting to move to the next line and
# inspect the value of +foo+ again. You can do that by pressing +n+:
#
# (rdb:1) n # goes to next line
# (rdb:1) p foo
# nil
#
# You now know that the original value of +foo+ was nil, and that it
# still was nil after calling +get_foo+.
#
# Other useful commands for navigating through your code are:
#
# +c+::
# Runs the program until it either exists or encounters another breakpoint.
# You usually press +c+ when you are finished debugging your program and
# want to resume its execution.
# +s+::
# Steps into method definition. In the previous example, +s+ would take you
# inside the method definition of +get_foo+.
# +r+::
# Restart the program.
# +q+::
# Quit the program.
#
# === Inspecting variables
#
# You can use the debugger to easily inspect both local and global variables.
# We've seen how to inspect local variables before:
#
# (rdb:1) p my_arg
# 42
#
# You can also pretty print the result of variables or expressions:
#
# (rdb:1) pp %w{a very long long array containing many words}
# ["a",
# "very",
# "long",
# ...
# ]
#
# You can list all local variables with +v l+:
#
# (rdb:1) v l
# foo => "hello"
#
# Similarly, you can show all global variables with +v g+:
#
# (rdb:1) v g
# all global variables
#
# Finally, you can omit +p+ if you simply want to evaluate a variable or
# expression
#
# (rdb:1) 5**2
# 25
#
# === Going beyond basics
#
# Ruby Debug provides more advanced functionalities like switching
# between threads, setting breakpoints and watch expressions, and more.
# The full list of commands is available at any time by pressing +h+.
#
# == Staying out of trouble
#
# Make sure you remove every instance of +require 'debug'+ before
# shipping your code. Failing to do so may result in your program
# hanging unpredictably.
#
# Debug is not available in safe mode.
class DEBUGGER__
MUTEX = Mutex.new # :nodoc:
class Context # :nodoc:
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
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.to_s, 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
pp expression evaluate expression and pretty_print its value
p expression evaluate expression and print its value
r[estart] restart program
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)
_, file, line, id = @frames[pos]
sprintf "#%d %s:%s%s\n", pos + 1, file, line,
(id ? ":in `#{id.id2name}'" : "")
end
def script_lines(file, line)
unless (lines = SCRIPT_LINES__[file]) and lines != true
Tracer::Single.get_line(file, line) if File.exist?(file)
lines = SCRIPT_LINES__[file]
lines = nil if lines == true
end
lines
end
def display_list(b, e, file, line)
if lines = script_lines(file, line)
stdout.printf "[%d, %d] in %s\n", b, e, file
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, line)
if lines and line = lines[line-1]
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__
# Returns the IO used as stdout. Defaults to STDOUT
def stdout
@stdout
end
# Sets the IO used as stdout. Defaults to STDOUT
def stdout=(s)
@stdout = s
end
# Returns the display expression list
#
# See DEBUGGER__ for more usage
def display
@display
end
# Returns the list of break points where execution will be stopped.
#
# See DEBUGGER__ for more usage
def break_points
@break_points
end
# Returns the list of waiting threads.
#
# When stepping through the traces of a function, thread gets suspended, to
# be resumed later.
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 | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/drb.rb | lib/drb.rb | require 'drb/drb'
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/matrix.rb | lib/matrix.rb | # encoding: utf-8
#
# = matrix.rb
#
# An implementation of Matrix and Vector classes.
#
# See classes Matrix and Vector for documentation.
#
# Current Maintainer:: Marc-André Lafortune
# Original Author:: Keiju ISHITSUKA
# Original Documentation:: Gavin Sinclair (sourced from <i>Ruby in a Nutshell</i> (Matsumoto, O'Reilly))
##
require "e2mmap.rb"
module ExceptionForMatrix # :nodoc:
extend Exception2MessageMapper
def_e2message(TypeError, "wrong argument type %s (expected %s)")
def_e2message(ArgumentError, "Wrong # of arguments(%d for %d)")
def_exception("ErrDimensionMismatch", "\#{self.name} dimension mismatch")
def_exception("ErrNotRegular", "Not Regular Matrix")
def_exception("ErrOperationNotDefined", "Operation(%s) can\\'t be defined: %s op %s")
def_exception("ErrOperationNotImplemented", "Sorry, Operation(%s) not implemented: %s op %s")
end
#
# The +Matrix+ class represents a mathematical matrix. It provides methods for creating
# matrices, operating on them arithmetically and algebraically,
# and determining their mathematical properties (trace, rank, inverse, determinant).
#
# == Method Catalogue
#
# To create a matrix:
# * Matrix[*rows]
# * Matrix.[](*rows)
# * Matrix.rows(rows, copy = true)
# * Matrix.columns(columns)
# * Matrix.build(row_count, column_count, &block)
# * Matrix.diagonal(*values)
# * Matrix.scalar(n, value)
# * Matrix.identity(n)
# * Matrix.unit(n)
# * Matrix.I(n)
# * Matrix.zero(n)
# * Matrix.row_vector(row)
# * Matrix.column_vector(column)
#
# To access Matrix elements/columns/rows/submatrices/properties:
# * #[](i, j)
# * #row_count (row_size)
# * #column_count (column_size)
# * #row(i)
# * #column(j)
# * #collect
# * #map
# * #each
# * #each_with_index
# * #find_index
# * #minor(*param)
#
# Properties of a matrix:
# * #diagonal?
# * #empty?
# * #hermitian?
# * #lower_triangular?
# * #normal?
# * #orthogonal?
# * #permutation?
# * #real?
# * #regular?
# * #singular?
# * #square?
# * #symmetric?
# * #unitary?
# * #upper_triangular?
# * #zero?
#
# Matrix arithmetic:
# * #*(m)
# * #+(m)
# * #-(m)
# * #/(m)
# * #inverse
# * #inv
# * #**
#
# Matrix functions:
# * #determinant
# * #det
# * #rank
# * #round
# * #trace
# * #tr
# * #transpose
# * #t
#
# Matrix decompositions:
# * #eigen
# * #eigensystem
# * #lup
# * #lup_decomposition
#
# Complex arithmetic:
# * conj
# * conjugate
# * imag
# * imaginary
# * real
# * rect
# * rectangular
#
# Conversion to other data types:
# * #coerce(other)
# * #row_vectors
# * #column_vectors
# * #to_a
#
# String representations:
# * #to_s
# * #inspect
#
class Matrix
include Enumerable
include ExceptionForMatrix
autoload :EigenvalueDecomposition, "matrix/eigenvalue_decomposition"
autoload :LUPDecomposition, "matrix/lup_decomposition"
# instance creations
private_class_method :new
attr_reader :rows
protected :rows
#
# Creates a matrix where each argument is a row.
# Matrix[ [25, 93], [-1, 66] ]
# => 25 93
# -1 66
#
def Matrix.[](*rows)
rows(rows, false)
end
#
# Creates a matrix where +rows+ is an array of arrays, each of which is a row
# of the matrix. If the optional argument +copy+ is false, use the given
# arrays as the internal structure of the matrix without copying.
# Matrix.rows([[25, 93], [-1, 66]])
# => 25 93
# -1 66
#
def Matrix.rows(rows, copy = true)
rows = convert_to_array(rows)
rows.map! do |row|
convert_to_array(row, copy)
end
size = (rows[0] || []).size
rows.each do |row|
raise ErrDimensionMismatch, "row size differs (#{row.size} should be #{size})" unless row.size == size
end
new rows, size
end
#
# Creates a matrix using +columns+ as an array of column vectors.
# Matrix.columns([[25, 93], [-1, 66]])
# => 25 -1
# 93 66
#
def Matrix.columns(columns)
rows(columns, false).transpose
end
#
# Creates a matrix of size +row_count+ x +column_count+.
# It fills the values by calling the given block,
# passing the current row and column.
# Returns an enumerator if no block is given.
#
# m = Matrix.build(2, 4) {|row, col| col - row }
# => Matrix[[0, 1, 2, 3], [-1, 0, 1, 2]]
# m = Matrix.build(3) { rand }
# => a 3x3 matrix with random elements
#
def Matrix.build(row_count, column_count = row_count)
row_count = CoercionHelper.coerce_to_int(row_count)
column_count = CoercionHelper.coerce_to_int(column_count)
raise ArgumentError if row_count < 0 || column_count < 0
return to_enum :build, row_count, column_count unless block_given?
rows = Array.new(row_count) do |i|
Array.new(column_count) do |j|
yield i, j
end
end
new rows, column_count
end
#
# Creates a matrix where the diagonal elements are composed of +values+.
# Matrix.diagonal(9, 5, -3)
# => 9 0 0
# 0 5 0
# 0 0 -3
#
def Matrix.diagonal(*values)
size = values.size
rows = Array.new(size) {|j|
row = Array.new(size, 0)
row[j] = values[j]
row
}
new rows
end
#
# Creates an +n+ by +n+ diagonal matrix where each diagonal element is
# +value+.
# Matrix.scalar(2, 5)
# => 5 0
# 0 5
#
def Matrix.scalar(n, value)
diagonal(*Array.new(n, value))
end
#
# Creates an +n+ by +n+ identity matrix.
# Matrix.identity(2)
# => 1 0
# 0 1
#
def Matrix.identity(n)
scalar(n, 1)
end
class << Matrix
alias unit identity
alias I identity
end
#
# Creates a zero matrix.
# Matrix.zero(2)
# => 0 0
# 0 0
#
def Matrix.zero(row_count, column_count = row_count)
rows = Array.new(row_count){Array.new(column_count, 0)}
new rows, column_count
end
#
# Creates a single-row matrix where the values of that row are as given in
# +row+.
# Matrix.row_vector([4,5,6])
# => 4 5 6
#
def Matrix.row_vector(row)
row = convert_to_array(row)
new [row]
end
#
# Creates a single-column matrix where the values of that column are as given
# in +column+.
# Matrix.column_vector([4,5,6])
# => 4
# 5
# 6
#
def Matrix.column_vector(column)
column = convert_to_array(column)
new [column].transpose, 1
end
#
# Creates a empty matrix of +row_count+ x +column_count+.
# At least one of +row_count+ or +column_count+ must be 0.
#
# m = Matrix.empty(2, 0)
# m == Matrix[ [], [] ]
# => true
# n = Matrix.empty(0, 3)
# n == Matrix.columns([ [], [], [] ])
# => true
# m * n
# => Matrix[[0, 0, 0], [0, 0, 0]]
#
def Matrix.empty(row_count = 0, column_count = 0)
raise ArgumentError, "One size must be 0" if column_count != 0 && row_count != 0
raise ArgumentError, "Negative size" if column_count < 0 || row_count < 0
new([[]]*row_count, column_count)
end
#
# Matrix.new is private; use Matrix.rows, columns, [], etc... to create.
#
def initialize(rows, column_count = rows[0].size)
# No checking is done at this point. rows must be an Array of Arrays.
# column_count must be the size of the first row, if there is one,
# otherwise it *must* be specified and can be any integer >= 0
@rows = rows
@column_count = column_count
end
def new_matrix(rows, column_count = rows[0].size) # :nodoc:
self.class.send(:new, rows, column_count) # bypass privacy of Matrix.new
end
private :new_matrix
#
# Returns element (+i+,+j+) of the matrix. That is: row +i+, column +j+.
#
def [](i, j)
@rows.fetch(i){return nil}[j]
end
alias element []
alias component []
def []=(i, j, v)
@rows[i][j] = v
end
alias set_element []=
alias set_component []=
private :[]=, :set_element, :set_component
#
# Returns the number of rows.
#
def row_count
@rows.size
end
alias_method :row_size, :row_count
#
# Returns the number of columns.
#
attr_reader :column_count
alias_method :column_size, :column_count
#
# Returns row vector number +i+ of the matrix as a Vector (starting at 0 like
# an array). When a block is given, the elements of that vector are iterated.
#
def row(i, &block) # :yield: e
if block_given?
@rows.fetch(i){return self}.each(&block)
self
else
Vector.elements(@rows.fetch(i){return nil})
end
end
#
# Returns column vector number +j+ of the matrix as a Vector (starting at 0
# like an array). When a block is given, the elements of that vector are
# iterated.
#
def column(j) # :yield: e
if block_given?
return self if j >= column_count || j < -column_count
row_count.times do |i|
yield @rows[i][j]
end
self
else
return nil if j >= column_count || j < -column_count
col = Array.new(row_count) {|i|
@rows[i][j]
}
Vector.elements(col, false)
end
end
#
# Returns a matrix that is the result of iteration of the given block over all
# elements of the matrix.
# Matrix[ [1,2], [3,4] ].collect { |e| e**2 }
# => 1 4
# 9 16
#
def collect(&block) # :yield: e
return to_enum(:collect) unless block_given?
rows = @rows.collect{|row| row.collect(&block)}
new_matrix rows, column_count
end
alias map collect
#
# Yields all elements of the matrix, starting with those of the first row,
# or returns an Enumerator is no block given.
# Elements can be restricted by passing an argument:
# * :all (default): yields all elements
# * :diagonal: yields only elements on the diagonal
# * :off_diagonal: yields all elements except on the diagonal
# * :lower: yields only elements on or below the diagonal
# * :strict_lower: yields only elements below the diagonal
# * :strict_upper: yields only elements above the diagonal
# * :upper: yields only elements on or above the diagonal
#
# Matrix[ [1,2], [3,4] ].each { |e| puts e }
# # => prints the numbers 1 to 4
# Matrix[ [1,2], [3,4] ].each(:strict_lower).to_a # => [3]
#
def each(which = :all) # :yield: e
return to_enum :each, which unless block_given?
last = column_count - 1
case which
when :all
block = Proc.new
@rows.each do |row|
row.each(&block)
end
when :diagonal
@rows.each_with_index do |row, row_index|
yield row.fetch(row_index){return self}
end
when :off_diagonal
@rows.each_with_index do |row, row_index|
column_count.times do |col_index|
yield row[col_index] unless row_index == col_index
end
end
when :lower
@rows.each_with_index do |row, row_index|
0.upto([row_index, last].min) do |col_index|
yield row[col_index]
end
end
when :strict_lower
@rows.each_with_index do |row, row_index|
[row_index, column_count].min.times do |col_index|
yield row[col_index]
end
end
when :strict_upper
@rows.each_with_index do |row, row_index|
(row_index+1).upto(last) do |col_index|
yield row[col_index]
end
end
when :upper
@rows.each_with_index do |row, row_index|
row_index.upto(last) do |col_index|
yield row[col_index]
end
end
else
raise ArgumentError, "expected #{which.inspect} to be one of :all, :diagonal, :off_diagonal, :lower, :strict_lower, :strict_upper or :upper"
end
self
end
#
# Same as #each, but the row index and column index in addition to the element
#
# Matrix[ [1,2], [3,4] ].each_with_index do |e, row, col|
# puts "#{e} at #{row}, #{col}"
# end
# # => Prints:
# # 1 at 0, 0
# # 2 at 0, 1
# # 3 at 1, 0
# # 4 at 1, 1
#
def each_with_index(which = :all) # :yield: e, row, column
return to_enum :each_with_index, which unless block_given?
last = column_count - 1
case which
when :all
@rows.each_with_index do |row, row_index|
row.each_with_index do |e, col_index|
yield e, row_index, col_index
end
end
when :diagonal
@rows.each_with_index do |row, row_index|
yield row.fetch(row_index){return self}, row_index, row_index
end
when :off_diagonal
@rows.each_with_index do |row, row_index|
column_count.times do |col_index|
yield row[col_index], row_index, col_index unless row_index == col_index
end
end
when :lower
@rows.each_with_index do |row, row_index|
0.upto([row_index, last].min) do |col_index|
yield row[col_index], row_index, col_index
end
end
when :strict_lower
@rows.each_with_index do |row, row_index|
[row_index, column_count].min.times do |col_index|
yield row[col_index], row_index, col_index
end
end
when :strict_upper
@rows.each_with_index do |row, row_index|
(row_index+1).upto(last) do |col_index|
yield row[col_index], row_index, col_index
end
end
when :upper
@rows.each_with_index do |row, row_index|
row_index.upto(last) do |col_index|
yield row[col_index], row_index, col_index
end
end
else
raise ArgumentError, "expected #{which.inspect} to be one of :all, :diagonal, :off_diagonal, :lower, :strict_lower, :strict_upper or :upper"
end
self
end
SELECTORS = {all: true, diagonal: true, off_diagonal: true, lower: true, strict_lower: true, strict_upper: true, upper: true}.freeze
#
# :call-seq:
# index(value, selector = :all) -> [row, column]
# index(selector = :all){ block } -> [row, column]
# index(selector = :all) -> an_enumerator
#
# The index method is specialized to return the index as [row, column]
# It also accepts an optional +selector+ argument, see #each for details.
#
# Matrix[ [1,2], [3,4] ].index(&:even?) # => [0, 1]
# Matrix[ [1,1], [1,1] ].index(1, :strict_lower) # => [1, 0]
#
def index(*args)
raise ArgumentError, "wrong number of arguments(#{args.size} for 0-2)" if args.size > 2
which = (args.size == 2 || SELECTORS.include?(args.last)) ? args.pop : :all
return to_enum :find_index, which, *args unless block_given? || args.size == 1
if args.size == 1
value = args.first
each_with_index(which) do |e, row_index, col_index|
return row_index, col_index if e == value
end
else
each_with_index(which) do |e, row_index, col_index|
return row_index, col_index if yield e
end
end
nil
end
alias_method :find_index, :index
#
# Returns a section of the matrix. The parameters are either:
# * start_row, nrows, start_col, ncols; OR
# * row_range, col_range
#
# Matrix.diagonal(9, 5, -3).minor(0..1, 0..2)
# => 9 0 0
# 0 5 0
#
# Like Array#[], negative indices count backward from the end of the
# row or column (-1 is the last element). Returns nil if the starting
# row or column is greater than row_count or column_count respectively.
#
def minor(*param)
case param.size
when 2
row_range, col_range = param
from_row = row_range.first
from_row += row_count if from_row < 0
to_row = row_range.end
to_row += row_count if to_row < 0
to_row += 1 unless row_range.exclude_end?
size_row = to_row - from_row
from_col = col_range.first
from_col += column_count if from_col < 0
to_col = col_range.end
to_col += column_count if to_col < 0
to_col += 1 unless col_range.exclude_end?
size_col = to_col - from_col
when 4
from_row, size_row, from_col, size_col = param
return nil if size_row < 0 || size_col < 0
from_row += row_count if from_row < 0
from_col += column_count if from_col < 0
else
raise ArgumentError, param.inspect
end
return nil if from_row > row_count || from_col > column_count || from_row < 0 || from_col < 0
rows = @rows[from_row, size_row].collect{|row|
row[from_col, size_col]
}
new_matrix rows, [column_count - from_col, size_col].min
end
#--
# TESTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#++
#
# Returns +true+ is this is a diagonal matrix.
# Raises an error if matrix is not square.
#
def diagonal?
Matrix.Raise ErrDimensionMismatch unless square?
each(:off_diagonal).all?(&:zero?)
end
#
# Returns +true+ if this is an empty matrix, i.e. if the number of rows
# or the number of columns is 0.
#
def empty?
column_count == 0 || row_count == 0
end
#
# Returns +true+ is this is an hermitian matrix.
# Raises an error if matrix is not square.
#
def hermitian?
Matrix.Raise ErrDimensionMismatch unless square?
each_with_index(:upper).all? do |e, row, col|
e == rows[col][row].conj
end
end
#
# Returns +true+ is this is a lower triangular matrix.
#
def lower_triangular?
each(:strict_upper).all?(&:zero?)
end
#
# Returns +true+ is this is a normal matrix.
# Raises an error if matrix is not square.
#
def normal?
Matrix.Raise ErrDimensionMismatch unless square?
rows.each_with_index do |row_i, i|
rows.each_with_index do |row_j, j|
s = 0
rows.each_with_index do |row_k, k|
s += row_i[k] * row_j[k].conj - row_k[i].conj * row_k[j]
end
return false unless s == 0
end
end
true
end
#
# Returns +true+ is this is an orthogonal matrix
# Raises an error if matrix is not square.
#
def orthogonal?
Matrix.Raise ErrDimensionMismatch unless square?
rows.each_with_index do |row, i|
column_count.times do |j|
s = 0
row_count.times do |k|
s += row[k] * rows[k][j]
end
return false unless s == (i == j ? 1 : 0)
end
end
true
end
#
# Returns +true+ is this is a permutation matrix
# Raises an error if matrix is not square.
#
def permutation?
Matrix.Raise ErrDimensionMismatch unless square?
cols = Array.new(column_count)
rows.each_with_index do |row, i|
found = false
row.each_with_index do |e, j|
if e == 1
return false if found || cols[j]
found = cols[j] = true
elsif e != 0
return false
end
end
return false unless found
end
true
end
#
# Returns +true+ if all entries of the matrix are real.
#
def real?
all?(&:real?)
end
#
# Returns +true+ if this is a regular (i.e. non-singular) matrix.
#
def regular?
not singular?
end
#
# Returns +true+ is this is a singular matrix.
#
def singular?
determinant == 0
end
#
# Returns +true+ is this is a square matrix.
#
def square?
column_count == row_count
end
#
# Returns +true+ is this is a symmetric matrix.
# Raises an error if matrix is not square.
#
def symmetric?
Matrix.Raise ErrDimensionMismatch unless square?
each_with_index(:strict_upper) do |e, row, col|
return false if e != rows[col][row]
end
true
end
#
# Returns +true+ is this is a unitary matrix
# Raises an error if matrix is not square.
#
def unitary?
Matrix.Raise ErrDimensionMismatch unless square?
rows.each_with_index do |row, i|
column_count.times do |j|
s = 0
row_count.times do |k|
s += row[k].conj * rows[k][j]
end
return false unless s == (i == j ? 1 : 0)
end
end
true
end
#
# Returns +true+ is this is an upper triangular matrix.
#
def upper_triangular?
each(:strict_lower).all?(&:zero?)
end
#
# Returns +true+ is this is a matrix with only zero elements
#
def zero?
all?(&:zero?)
end
#--
# OBJECT METHODS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#++
#
# Returns +true+ if and only if the two matrices contain equal elements.
#
def ==(other)
return false unless Matrix === other &&
column_count == other.column_count # necessary for empty matrices
rows == other.rows
end
def eql?(other)
return false unless Matrix === other &&
column_count == other.column_count # necessary for empty matrices
rows.eql? other.rows
end
#
# Returns a clone of the matrix, so that the contents of each do not reference
# identical objects.
# There should be no good reason to do this since Matrices are immutable.
#
def clone
new_matrix @rows.map(&:dup), column_count
end
#
# Returns a hash-code for the matrix.
#
def hash
@rows.hash
end
#--
# ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#++
#
# Matrix multiplication.
# Matrix[[2,4], [6,8]] * Matrix.identity(2)
# => 2 4
# 6 8
#
def *(m) # m is matrix or vector or number
case(m)
when Numeric
rows = @rows.collect {|row|
row.collect {|e| e * m }
}
return new_matrix rows, column_count
when Vector
m = self.class.column_vector(m)
r = self * m
return r.column(0)
when Matrix
Matrix.Raise ErrDimensionMismatch if column_count != m.row_count
rows = Array.new(row_count) {|i|
Array.new(m.column_count) {|j|
(0 ... column_count).inject(0) do |vij, k|
vij + self[i, k] * m[k, j]
end
}
}
return new_matrix rows, m.column_count
else
return apply_through_coercion(m, __method__)
end
end
#
# Matrix addition.
# Matrix.scalar(2,5) + Matrix[[1,0], [-4,7]]
# => 6 0
# -4 12
#
def +(m)
case m
when Numeric
Matrix.Raise ErrOperationNotDefined, "+", self.class, m.class
when Vector
m = self.class.column_vector(m)
when Matrix
else
return apply_through_coercion(m, __method__)
end
Matrix.Raise ErrDimensionMismatch unless row_count == m.row_count and column_count == m.column_count
rows = Array.new(row_count) {|i|
Array.new(column_count) {|j|
self[i, j] + m[i, j]
}
}
new_matrix rows, column_count
end
#
# Matrix subtraction.
# Matrix[[1,5], [4,2]] - Matrix[[9,3], [-4,1]]
# => -8 2
# 8 1
#
def -(m)
case m
when Numeric
Matrix.Raise ErrOperationNotDefined, "-", self.class, m.class
when Vector
m = self.class.column_vector(m)
when Matrix
else
return apply_through_coercion(m, __method__)
end
Matrix.Raise ErrDimensionMismatch unless row_count == m.row_count and column_count == m.column_count
rows = Array.new(row_count) {|i|
Array.new(column_count) {|j|
self[i, j] - m[i, j]
}
}
new_matrix rows, column_count
end
#
# Matrix division (multiplication by the inverse).
# Matrix[[7,6], [3,9]] / Matrix[[2,9], [3,1]]
# => -7 1
# -3 -6
#
def /(other)
case other
when Numeric
rows = @rows.collect {|row|
row.collect {|e| e / other }
}
return new_matrix rows, column_count
when Matrix
return self * other.inverse
else
return apply_through_coercion(other, __method__)
end
end
#
# Returns the inverse of the matrix.
# Matrix[[-1, -1], [0, -1]].inverse
# => -1 1
# 0 -1
#
def inverse
Matrix.Raise ErrDimensionMismatch unless square?
self.class.I(row_count).send(:inverse_from, self)
end
alias inv inverse
def inverse_from(src) # :nodoc:
last = row_count - 1
a = src.to_a
0.upto(last) do |k|
i = k
akk = a[k][k].abs
(k+1).upto(last) do |j|
v = a[j][k].abs
if v > akk
i = j
akk = v
end
end
Matrix.Raise ErrNotRegular if akk == 0
if i != k
a[i], a[k] = a[k], a[i]
@rows[i], @rows[k] = @rows[k], @rows[i]
end
akk = a[k][k]
0.upto(last) do |ii|
next if ii == k
q = a[ii][k].quo(akk)
a[ii][k] = 0
(k + 1).upto(last) do |j|
a[ii][j] -= a[k][j] * q
end
0.upto(last) do |j|
@rows[ii][j] -= @rows[k][j] * q
end
end
(k+1).upto(last) do |j|
a[k][j] = a[k][j].quo(akk)
end
0.upto(last) do |j|
@rows[k][j] = @rows[k][j].quo(akk)
end
end
self
end
private :inverse_from
#
# Matrix exponentiation.
# Equivalent to multiplying the matrix by itself N times.
# Non integer exponents will be handled by diagonalizing the matrix.
#
# Matrix[[7,6], [3,9]] ** 2
# => 67 96
# 48 99
#
def ** (other)
case other
when Integer
x = self
if other <= 0
x = self.inverse
return self.class.identity(self.column_count) if other == 0
other = -other
end
z = nil
loop do
z = z ? z * x : x if other[0] == 1
return z if (other >>= 1).zero?
x *= x
end
when Numeric
v, d, v_inv = eigensystem
v * self.class.diagonal(*d.each(:diagonal).map{|e| e ** other}) * v_inv
else
Matrix.Raise ErrOperationNotDefined, "**", self.class, other.class
end
end
#--
# MATRIX FUNCTIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#++
#
# Returns the determinant of the matrix.
#
# Beware that using Float values can yield erroneous results
# because of their lack of precision.
# Consider using exact types like Rational or BigDecimal instead.
#
# Matrix[[7,6], [3,9]].determinant
# => 45
#
def determinant
Matrix.Raise ErrDimensionMismatch unless square?
m = @rows
case row_count
# Up to 4x4, give result using Laplacian expansion by minors.
# This will typically be faster, as well as giving good results
# in case of Floats
when 0
+1
when 1
+ m[0][0]
when 2
+ m[0][0] * m[1][1] - m[0][1] * m[1][0]
when 3
m0, m1, m2 = m
+ m0[0] * m1[1] * m2[2] - m0[0] * m1[2] * m2[1] \
- m0[1] * m1[0] * m2[2] + m0[1] * m1[2] * m2[0] \
+ m0[2] * m1[0] * m2[1] - m0[2] * m1[1] * m2[0]
when 4
m0, m1, m2, m3 = m
+ m0[0] * m1[1] * m2[2] * m3[3] - m0[0] * m1[1] * m2[3] * m3[2] \
- m0[0] * m1[2] * m2[1] * m3[3] + m0[0] * m1[2] * m2[3] * m3[1] \
+ m0[0] * m1[3] * m2[1] * m3[2] - m0[0] * m1[3] * m2[2] * m3[1] \
- m0[1] * m1[0] * m2[2] * m3[3] + m0[1] * m1[0] * m2[3] * m3[2] \
+ m0[1] * m1[2] * m2[0] * m3[3] - m0[1] * m1[2] * m2[3] * m3[0] \
- m0[1] * m1[3] * m2[0] * m3[2] + m0[1] * m1[3] * m2[2] * m3[0] \
+ m0[2] * m1[0] * m2[1] * m3[3] - m0[2] * m1[0] * m2[3] * m3[1] \
- m0[2] * m1[1] * m2[0] * m3[3] + m0[2] * m1[1] * m2[3] * m3[0] \
+ m0[2] * m1[3] * m2[0] * m3[1] - m0[2] * m1[3] * m2[1] * m3[0] \
- m0[3] * m1[0] * m2[1] * m3[2] + m0[3] * m1[0] * m2[2] * m3[1] \
+ m0[3] * m1[1] * m2[0] * m3[2] - m0[3] * m1[1] * m2[2] * m3[0] \
- m0[3] * m1[2] * m2[0] * m3[1] + m0[3] * m1[2] * m2[1] * m3[0]
else
# For bigger matrices, use an efficient and general algorithm.
# Currently, we use the Gauss-Bareiss algorithm
determinant_bareiss
end
end
alias_method :det, :determinant
#
# Private. Use Matrix#determinant
#
# Returns the determinant of the matrix, using
# Bareiss' multistep integer-preserving gaussian elimination.
# It has the same computational cost order O(n^3) as standard Gaussian elimination.
# Intermediate results are fraction free and of lower complexity.
# A matrix of Integers will have thus intermediate results that are also Integers,
# with smaller bignums (if any), while a matrix of Float will usually have
# intermediate results with better precision.
#
def determinant_bareiss
size = row_count
last = size - 1
a = to_a
no_pivot = Proc.new{ return 0 }
sign = +1
pivot = 1
size.times do |k|
previous_pivot = pivot
if (pivot = a[k][k]) == 0
switch = (k+1 ... size).find(no_pivot) {|row|
a[row][k] != 0
}
a[switch], a[k] = a[k], a[switch]
pivot = a[k][k]
sign = -sign
end
(k+1).upto(last) do |i|
ai = a[i]
(k+1).upto(last) do |j|
ai[j] = (pivot * ai[j] - ai[k] * a[k][j]) / previous_pivot
end
end
end
sign * pivot
end
private :determinant_bareiss
#
# deprecated; use Matrix#determinant
#
def determinant_e
warn "#{caller(1)[0]}: warning: Matrix#determinant_e is deprecated; use #determinant"
determinant
end
alias det_e determinant_e
#
# Returns the rank of the matrix.
# Beware that using Float values can yield erroneous results
# because of their lack of precision.
# Consider using exact types like Rational or BigDecimal instead.
#
# Matrix[[7,6], [3,9]].rank
# => 2
#
def rank
# We currently use Bareiss' multistep integer-preserving gaussian elimination
# (see comments on determinant)
a = to_a
last_column = column_count - 1
last_row = row_count - 1
pivot_row = 0
previous_pivot = 1
0.upto(last_column) do |k|
switch_row = (pivot_row .. last_row).find {|row|
a[row][k] != 0
}
if switch_row
a[switch_row], a[pivot_row] = a[pivot_row], a[switch_row] unless pivot_row == switch_row
pivot = a[pivot_row][k]
(pivot_row+1).upto(last_row) do |i|
ai = a[i]
(k+1).upto(last_column) do |j|
ai[j] = (pivot * ai[j] - ai[k] * a[pivot_row][j]) / previous_pivot
end
end
pivot_row += 1
previous_pivot = pivot
end
end
pivot_row
end
#
# deprecated; use Matrix#rank
#
def rank_e
warn "#{caller(1)[0]}: warning: Matrix#rank_e is deprecated; use #rank"
rank
end
# Returns a matrix with entries rounded to the given precision
# (see Float#round)
#
def round(ndigits=0)
map{|e| e.round(ndigits)}
end
#
# Returns the trace (sum of diagonal elements) of the matrix.
# Matrix[[7,6], [3,9]].trace
# => 16
#
def trace
Matrix.Raise ErrDimensionMismatch unless square?
(0...column_count).inject(0) do |tr, i|
tr + @rows[i][i]
end
end
alias tr trace
#
# Returns the transpose of the matrix.
# Matrix[[1,2], [3,4], [5,6]]
# => 1 2
# 3 4
# 5 6
# Matrix[[1,2], [3,4], [5,6]].transpose
# => 1 3 5
# 2 4 6
#
def transpose
return self.class.empty(column_count, 0) if row_count.zero?
new_matrix @rows.transpose, row_count
end
alias t transpose
#--
# DECOMPOSITIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#++
#
# Returns the Eigensystem of the matrix; see +EigenvalueDecomposition+.
# m = Matrix[[1, 2], [3, 4]]
# v, d, v_inv = m.eigensystem
# d.diagonal? # => true
# v.inv == v_inv # => true
# (v * d * v_inv).round(5) == m # => true
#
def eigensystem
EigenvalueDecomposition.new(self)
end
alias eigen eigensystem
#
# Returns the LUP decomposition of the matrix; see +LUPDecomposition+.
# a = Matrix[[1, 2], [3, 4]]
# l, u, p = a.lup
# l.lower_triangular? # => true
# u.upper_triangular? # => true
# p.permutation? # => true
# l * u == p * a # => true
# a.lup.solve([2, 5]) # => Vector[(1/1), (1/2)]
#
def lup
LUPDecomposition.new(self)
end
alias lup_decomposition lup
#--
# COMPLEX ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#++
#
# Returns the conjugate of the matrix.
# Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]]
# => 1+2i i 0
# 1 2 3
# Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]].conjugate
# => 1-2i -i 0
# 1 2 3
#
def conjugate
collect(&:conjugate)
end
alias conj conjugate
#
# Returns the imaginary part of the matrix.
# Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]]
# => 1+2i i 0
# 1 2 3
# Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]].imaginary
# => 2i i 0
# 0 0 0
#
def imaginary
collect(&:imaginary)
end
alias imag imaginary
#
# Returns the real part of the matrix.
# Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]]
# => 1+2i i 0
# 1 2 3
# Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]].real
# => 1 0 0
# 1 2 3
#
def real
collect(&:real)
end
#
# Returns an array containing matrices corresponding to the real and imaginary
# parts of the matrix
#
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | true |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/open3.rb | lib/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 for the
# child process when running another program.
# You can specify various attributes, redirections, current directory, etc., of
# the program in the same way as for Process.spawn.
#
# - Open3.popen3 : pipes for stdin, stdout, stderr
# - Open3.popen2 : pipes for stdin, stdout
# - Open3.popen2e : pipes for stdin, merged stdout and stderr
# - Open3.capture3 : give a string for stdin; get strings for stdout, stderr
# - Open3.capture2 : give a string for stdin; get a string for stdout
# - Open3.capture2e : give a string for stdin; get a string for merged stdout and stderr
# - Open3.pipeline_rw : pipes for first stdin and last stdout of a pipeline
# - Open3.pipeline_r : pipe for last stdout of a pipeline
# - Open3.pipeline_w : pipe for first stdin of a pipeline
# - Open3.pipeline_start : run a pipeline without waiting
# - Open3.pipeline : run a pipeline and wait for its completion
#
module Open3
# Open stdin, stdout, and stderr streams and start external executable.
# In addition, a thread to wait for the started process is created.
# The thread has a pid method and a thread variable :pid which is the pid of
# the started process.
#
# Block form:
#
# Open3.popen3([env,] cmd... [, opts]) {|stdin, stdout, stderr, wait_thr|
# pid = wait_thr.pid # pid of the started process.
# ...
# exit_status = wait_thr.value # Process::Status object returned.
# }
#
# Non-block form:
#
# stdin, stdout, stderr, wait_thr = Open3.popen3([env,] cmd... [, opts])
# pid = wait_thr[:pid] # pid of the started process
# ...
# stdin.close # stdin, stdout and stderr should be closed explicitly in this form.
# stdout.close
# stderr.close
# exit_status = wait_thr.value # Process::Status object returned.
#
# The parameters env, cmd, and opts are passed to Process.spawn.
# A commandline string and a list of argument strings can be accepted as follows:
#
# Open3.popen3("echo abc") {|i, o, e, t| ... }
# Open3.popen3("echo", "abc") {|i, o, e, t| ... }
# Open3.popen3(["echo", "argv0"], "abc") {|i, o, e, t| ... }
#
# If the last parameter, opts, is a Hash, it is recognized as an option for Process.spawn.
#
# Open3.popen3("pwd", :chdir=>"/") {|i,o,e,t|
# p o.read.chomp #=> "/"
# }
#
# wait_thr.value waits for the termination of the process.
# The block form also waits for the process when it returns.
#
# Closing stdin, stdout and stderr does not wait for the process to complete.
#
# You should be careful to avoid deadlocks.
# Since pipes are fixed length buffers,
# Open3.popen3("prog") {|i, o, e, t| o.read } deadlocks if
# the program generates too much output on stderr.
# You should read stdout and stderr simultaneously (using threads or IO.select).
# However, if you don't need stderr output, you can use Open3.popen2.
# If merged stdout and stderr output is not a problem, you can use Open3.popen2e.
# If you really need stdout and stderr output as separate strings, you can consider Open3.capture3.
#
def popen3(*cmd, **opts, &block)
in_r, in_w = IO.pipe
opts[:in] = in_r
in_w.sync = true
out_r, out_w = IO.pipe
opts[:out] = out_w
err_r, err_w = IO.pipe
opts[:err] = err_w
popen_run(cmd, opts, [in_r, out_w, err_w], [in_w, out_r, err_r], &block)
end
module_function :popen3
# Open3.popen2 is similar to Open3.popen3 except that it doesn't create a pipe for
# the standard error stream.
#
# Block form:
#
# Open3.popen2([env,] cmd... [, opts]) {|stdin, stdout, wait_thr|
# pid = wait_thr.pid # pid of the started process.
# ...
# exit_status = wait_thr.value # Process::Status object returned.
# }
#
# Non-block form:
#
# stdin, stdout, wait_thr = Open3.popen2([env,] cmd... [, opts])
# ...
# stdin.close # stdin and stdout should be closed explicitly in this form.
# stdout.close
#
# See Process.spawn for the optional hash arguments _env_ and _opts_.
#
# Example:
#
# Open3.popen2("wc -c") {|i,o,t|
# i.print "answer to life the universe and everything"
# i.close
# p o.gets #=> "42\n"
# }
#
# Open3.popen2("bc -q") {|i,o,t|
# i.puts "obase=13"
# i.puts "6 * 9"
# p o.gets #=> "42\n"
# }
#
# Open3.popen2("dc") {|i,o,t|
# i.print "42P"
# i.close
# p o.read #=> "*"
# }
#
def popen2(*cmd, **opts, &block)
in_r, in_w = IO.pipe
opts[:in] = in_r
in_w.sync = true
out_r, out_w = IO.pipe
opts[:out] = out_w
popen_run(cmd, opts, [in_r, out_w], [in_w, out_r], &block)
end
module_function :popen2
# Open3.popen2e is similar to Open3.popen3 except that it merges
# the standard output stream and the standard error stream.
#
# Block form:
#
# Open3.popen2e([env,] cmd... [, opts]) {|stdin, stdout_and_stderr, wait_thr|
# pid = wait_thr.pid # pid of the started process.
# ...
# exit_status = wait_thr.value # Process::Status object returned.
# }
#
# Non-block form:
#
# stdin, stdout_and_stderr, wait_thr = Open3.popen2e([env,] cmd... [, opts])
# ...
# stdin.close # stdin and stdout_and_stderr should be closed explicitly in this form.
# stdout_and_stderr.close
#
# See Process.spawn for the optional hash arguments _env_ and _opts_.
#
# Example:
# # check gcc warnings
# source = "foo.c"
# Open3.popen2e("gcc", "-Wall", source) {|i,oe,t|
# oe.each {|line|
# if /warning/ =~ line
# ...
# end
# }
# }
#
def popen2e(*cmd, **opts, &block)
in_r, in_w = IO.pipe
opts[:in] = in_r
in_w.sync = true
out_r, out_w = IO.pipe
opts[[:out, :err]] = out_w
popen_run(cmd, opts, [in_r, out_w], [in_w, out_r], &block)
end
module_function :popen2e
def popen_run(cmd, opts, child_io, parent_io) # :nodoc:
pid = spawn(*cmd, opts)
wait_thr = Process.detach(pid)
child_io.each {|io| io.close }
result = [*parent_io, wait_thr]
if defined? yield
begin
return yield(*result)
ensure
parent_io.each{|io| io.close unless io.closed?}
wait_thr.join
end
end
result
end
module_function :popen_run
class << self
private :popen_run
end
# Open3.capture3 captures the standard output and the standard error of a command.
#
# stdout_str, stderr_str, status = Open3.capture3([env,] cmd... [, opts])
#
# The arguments env, cmd and opts are passed to Open3.popen3 except
# opts[:stdin_data] and opts[:binmode]. See Process.spawn.
#
# If opts[:stdin_data] is specified, it is sent to the command's standard input.
#
# If opts[:binmode] is true, internal pipes are set to binary mode.
#
# Examples:
#
# # dot is a command of graphviz.
# graph = <<'End'
# digraph g {
# a -> b
# }
# End
# drawn_graph, dot_log = Open3.capture3("dot -v", :stdin_data=>graph)
#
# o, e, s = Open3.capture3("echo abc; sort >&2", :stdin_data=>"foo\nbar\nbaz\n")
# p o #=> "abc\n"
# p e #=> "bar\nbaz\nfoo\n"
# p s #=> #<Process::Status: pid 32682 exit 0>
#
# # generate a thumbnail image using the convert command of ImageMagick.
# # However, if the image is really stored in a file,
# # system("convert", "-thumbnail", "80", "png:#{filename}", "png:-") is better
# # because of reduced memory consumption.
# # But if the image is stored in a DB or generated by the gnuplot Open3.capture2 example,
# # Open3.capture3 should be considered.
# #
# image = File.read("/usr/share/openclipart/png/animals/mammals/sheep-md-v0.1.png", :binmode=>true)
# thumbnail, err, s = Open3.capture3("convert -thumbnail 80 png:- png:-", :stdin_data=>image, :binmode=>true)
# if s.success?
# STDOUT.binmode; print thumbnail
# end
#
def capture3(*cmd, stdin_data: '', binmode: false, **opts)
popen3(*cmd, opts) {|i, o, e, t|
if binmode
i.binmode
o.binmode
e.binmode
end
out_reader = Thread.new { o.read }
err_reader = Thread.new { e.read }
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[:binmode]. See Process.spawn.
#
# If opts[:stdin_data] is specified, it is sent to the command's standard input.
#
# If opts[:binmode] is true, internal pipes are set to binary mode.
#
# Example:
#
# # factor is a command for integer factorization.
# o, s = Open3.capture2("factor", :stdin_data=>"42")
# p o #=> "42: 2 3 7\n"
#
# # generate x**2 graph in png using gnuplot.
# gnuplot_commands = <<"End"
# set terminal png
# plot x**2, "-" with lines
# 1 14
# 2 1
# 3 8
# 4 5
# e
# End
# image, s = Open3.capture2("gnuplot", :stdin_data=>gnuplot_commands, :binmode=>true)
#
def capture2(*cmd, stdin_data: '', binmode: false, **opts)
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[:binmode]. See Process.spawn.
#
# If opts[:stdin_data] is specified, it is sent to the command's standard input.
#
# If opts[:binmode] is true, internal pipes are set to binary mode.
#
# Example:
#
# # capture make log
# make_log, s = Open3.capture2e("make")
#
def capture2e(*cmd, stdin_data: '', binmode: false, **opts)
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 connect to stdin of the first command and stdout of the last command.
#
# Open3.pipeline_rw(cmd1, cmd2, ... [, opts]) {|first_stdin, last_stdout, wait_threads|
# ...
# }
#
# first_stdin, last_stdout, wait_threads = Open3.pipeline_rw(cmd1, cmd2, ... [, opts])
# ...
# first_stdin.close
# last_stdout.close
#
# Each cmd is a string or an array.
# If it is an array, the elements are passed to Process.spawn.
#
# cmd:
# commandline command line string which is passed to a shell
# [env, commandline, opts] command line string which is passed to a shell
# [env, cmdname, arg1, ..., opts] command name and one or more arguments (no shell)
# [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
#
# Note that env and opts are optional, as for Process.spawn.
#
# The options to pass to Process.spawn are constructed by merging
# +opts+, the last hash element of the array, and
# specifications for the pipes between each of the commands.
#
# Example:
#
# Open3.pipeline_rw("tr -dc A-Za-z", "wc -c") {|i, o, ts|
# i.puts "All persons more than a mile high to leave the court."
# i.close
# p o.gets #=> "42\n"
# }
#
# Open3.pipeline_rw("sort", "cat -n") {|stdin, stdout, wait_thrs|
# stdin.puts "foo"
# stdin.puts "bar"
# stdin.puts "baz"
# stdin.close # send EOF to sort.
# p stdout.read #=> " 1\tbar\n 2\tbaz\n 3\tfoo\n"
# }
def pipeline_rw(*cmds, **opts, &block)
in_r, in_w = IO.pipe
opts[:in] = in_r
in_w.sync = true
out_r, out_w = IO.pipe
opts[:out] = out_w
pipeline_run(cmds, opts, [in_r, out_w], [in_w, out_r], &block)
end
module_function :pipeline_rw
# Open3.pipeline_r starts a list of commands as a pipeline with a pipe
# which connects to stdout of the last command.
#
# Open3.pipeline_r(cmd1, cmd2, ... [, opts]) {|last_stdout, wait_threads|
# ...
# }
#
# last_stdout, wait_threads = Open3.pipeline_r(cmd1, cmd2, ... [, opts])
# ...
# last_stdout.close
#
# Each cmd is a string or an array.
# If it is an array, the elements are passed to Process.spawn.
#
# cmd:
# commandline command line string which is passed to a shell
# [env, commandline, opts] command line string which is passed to a shell
# [env, cmdname, arg1, ..., opts] command name and one or more arguments (no shell)
# [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
#
# Note that env and opts are optional, as for Process.spawn.
#
# Example:
#
# Open3.pipeline_r("zcat /var/log/apache2/access.log.*.gz",
# [{"LANG"=>"C"}, "grep", "GET /favicon.ico"],
# "logresolve") {|o, ts|
# o.each_line {|line|
# ...
# }
# }
#
# Open3.pipeline_r("yes", "head -10") {|o, ts|
# p o.read #=> "y\ny\ny\ny\ny\ny\ny\ny\ny\ny\n"
# p ts[0].value #=> #<Process::Status: pid 24910 SIGPIPE (signal 13)>
# p ts[1].value #=> #<Process::Status: pid 24913 exit 0>
# }
#
def pipeline_r(*cmds, **opts, &block)
out_r, out_w = IO.pipe
opts[:out] = out_w
pipeline_run(cmds, opts, [out_w], [out_r], &block)
end
module_function :pipeline_r
# Open3.pipeline_w starts a list of commands as a pipeline with a pipe
# which connects to stdin of the first command.
#
# Open3.pipeline_w(cmd1, cmd2, ... [, opts]) {|first_stdin, wait_threads|
# ...
# }
#
# first_stdin, wait_threads = Open3.pipeline_w(cmd1, cmd2, ... [, opts])
# ...
# first_stdin.close
#
# Each cmd is a string or an array.
# If it is an array, the elements are passed to Process.spawn.
#
# cmd:
# commandline command line string which is passed to a shell
# [env, commandline, opts] command line string which is passed to a shell
# [env, cmdname, arg1, ..., opts] command name and one or more arguments (no shell)
# [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
#
# Note that env and opts are optional, as for Process.spawn.
#
# Example:
#
# Open3.pipeline_w("bzip2 -c", :out=>"/tmp/hello.bz2") {|i, ts|
# i.puts "hello"
# }
#
def pipeline_w(*cmds, **opts, &block)
in_r, in_w = IO.pipe
opts[:in] = in_r
in_w.sync = true
pipeline_run(cmds, opts, [in_r], [in_w], &block)
end
module_function :pipeline_w
# Open3.pipeline_start starts a list of commands as a pipeline.
# No pipes are created for stdin of the first command and
# stdout of the last command.
#
# Open3.pipeline_start(cmd1, cmd2, ... [, opts]) {|wait_threads|
# ...
# }
#
# wait_threads = Open3.pipeline_start(cmd1, cmd2, ... [, opts])
# ...
#
# Each cmd is a string or an array.
# If it is an array, the elements are passed to Process.spawn.
#
# cmd:
# commandline command line string which is passed to a shell
# [env, commandline, opts] command line string which is passed to a shell
# [env, cmdname, arg1, ..., opts] command name and one or more arguments (no shell)
# [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
#
# Note that env and opts are optional, as for Process.spawn.
#
# Example:
#
# # Run xeyes in 10 seconds.
# Open3.pipeline_start("xeyes") {|ts|
# sleep 10
# t = ts[0]
# Process.kill("TERM", t.pid)
# p t.value #=> #<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, **opts, &block)
if block
pipeline_run(cmds, opts, [], [], &block)
else
ts, = pipeline_run(cmds, opts, [], [])
ts
end
end
module_function :pipeline_start
# Open3.pipeline starts a list of commands as a pipeline.
# It waits for the completion of the commands.
# No pipes are created for stdin of the first command and
# stdout of the last command.
#
# status_list = Open3.pipeline(cmd1, cmd2, ... [, opts])
#
# Each cmd is a string or an array.
# If it is an array, the elements are passed to Process.spawn.
#
# cmd:
# commandline command line string which is passed to a shell
# [env, commandline, opts] command line string which is passed to a shell
# [env, cmdname, arg1, ..., opts] command name and one or more arguments (no shell)
# [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
#
# Note that env and opts are optional, as Process.spawn.
#
# Example:
#
# fname = "/usr/share/man/man1/ruby.1.gz"
# p Open3.pipeline(["zcat", fname], "nroff -man", "less")
# #=> [#<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, **opts)
pipeline_run(cmds, opts, [], []) {|ts|
ts.map {|t| t.value }
}
end
module_function :pipeline
def pipeline_run(cmds, pipeline_opts, child_io, parent_io) # :nodoc:
if cmds.empty?
raise ArgumentError, "no commands"
end
opts_base = pipeline_opts.dup
opts_base.delete :in
opts_base.delete :out
wait_thrs = []
r = nil
cmds.each_with_index {|cmd, i|
cmd_opts = opts_base.dup
if String === cmd
cmd = [cmd]
else
cmd_opts.update cmd.pop if Hash === cmd.last
end
if i == 0
if !cmd_opts.include?(:in)
if pipeline_opts.include?(:in)
cmd_opts[:in] = pipeline_opts[:in]
end
end
else
cmd_opts[:in] = r
end
if i != cmds.length - 1
r2, w2 = IO.pipe
cmd_opts[:out] = w2
else
if !cmd_opts.include?(:out)
if pipeline_opts.include?(:out)
cmd_opts[:out] = pipeline_opts[:out]
end
end
end
pid = spawn(*cmd, cmd_opts)
wait_thrs << Process.detach(pid)
r.close if r
w2.close if w2
r = r2
}
result = parent_io + [wait_thrs]
child_io.each {|io| io.close }
if defined? yield
begin
return yield(*result)
ensure
parent_io.each{|io| io.close unless io.closed?}
wait_thrs.each {|t| t.join }
end
end
result
end
module_function :pipeline_run
class << self
private :pipeline_run
end
end
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 | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/gserver.rb | lib/gserver.rb | #
# Copyright (C) 2001 John W. Small All Rights Reserved
#
# Author:: John W. Small
# Documentation:: Gavin Sinclair
# Licence:: Ruby License
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, via #audit=.
#
# 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
# Stop the server running on the given port, bound to the given host
#
# +port+:: port, as a Fixnum, of the server to stop
# +host+:: host on which to find the server to stop
def GServer.stop(port, host = DEFAULT_HOST)
@@servicesMutex.synchronize {
@@services[host][port].stop
}
end
# Check if a server is running on the given port and host
#
# +port+:: port, as a Fixnum, of the server to check
# +host+:: host on which to find the server to check
#
# Returns true if a server is running on that port and host.
def GServer.in_service?(port, host = DEFAULT_HOST)
@@services.has_key?(host) and
@@services[host].has_key?(port)
end
# Stop the server
def stop
@connectionsMutex.synchronize {
if @tcpServerThread
@tcpServerThread.raise "stop"
end
}
end
# Returns true if the server has stopped.
def stopped?
@tcpServerThread == nil
end
# Schedule a shutdown for the server
def shutdown
@shutdown = true
end
# Return the current number of connected clients
def connections
@connections.size
end
# Join with the server thread
def join
@tcpServerThread.join if @tcpServerThread
end
# Port on which to listen, as a Fixnum
attr_reader :port
# Host on which to bind, as a String
attr_reader :host
# Maximum number of connections to accept at at ime, as a Fixnum
attr_reader :maxConnections
# IO Device on which log messages should be written
attr_accessor :stdlog
# Set to true to cause the callbacks #connecting, #disconnecting, #starting,
# and #stopping to be called during the server's lifecycle
attr_accessor :audit
# Set to true to show more detailed logging
attr_accessor :debug
# Called when a client connects, if auditing is enabled.
#
# +client+:: a TCPSocket instances representing the client that connected
#
# Return true to allow this client to connect, false to prevent it.
def connecting(client)
addr = client.peeraddr
log("#{self.class.to_s} #{@host}:#{@port} client:#{addr[1]} " +
"#{addr[2]}<#{addr[3]}> connect")
true
end
# Called when a client disconnects, if audition is enabled.
#
# +clientPort+:: the port of the client that is connecting
def disconnecting(clientPort)
log("#{self.class.to_s} #{@host}:#{@port} " +
"client:#{clientPort} disconnect")
end
protected :connecting, :disconnecting
# Called when the server is starting up, if auditing is enabled.
def starting()
log("#{self.class.to_s} #{@host}:#{@port} start")
end
# Called when the server is shutting down, if auditing is enabled.
def stopping()
log("#{self.class.to_s} #{@host}:#{@port} stop")
end
protected :starting, :stopping
# Called if #debug is true whenever an unhandled exception is raised.
# This implementation simply logs the backtrace.
#
# +detail+:: The Exception that was caught
def error(detail)
log(detail.backtrace.join("\n"))
end
# Log a message to #stdlog, if it's defined. This implementation
# outputs the timestamp and message to the log.
#
# +msg+:: the message to log
def log(msg)
if @stdlog
@stdlog.puts("[#{Time.new.ctime}] %s" % msg)
@stdlog.flush
end
end
protected :error, :log
# Create a new server
#
# +port+:: the port, as a Fixnum, on which to listen.
# +host+:: the host to bind to
# +maxConnections+:: The maximum number of simultaneous connections to
# accept
# +stdlog+:: IO device on which to log messages
# +audit+:: if true, lifecycle callbacks will be called. See #audit
# +debug+:: if true, error messages are logged. See #debug
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
# Start the server if it isn't already running
#
# +maxConnections+::
# override +maxConnections+ given to the constructor. A negative
# value indicates that the value from the constructor should be used.
def start(maxConnections = -1)
raise "server is already 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
Thread.new(client) { |myClient|
@connections << Thread.current
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 | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/tktext.rb | lib/tktext.rb | #
# tktext.rb - load tk/text.rb
#
require 'tk/text'
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/tkscrollbox.rb | lib/tkscrollbox.rb | #
# tkscrollbox.rb - load tk/scrollbox.rb
#
require 'tk/scrollbox'
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/rss.rb | lib/rss.rb | ##
# = RSS reading and writing
#
# Really Simple Syndication (RSS) is a family of formats that describe 'feeds,'
# specially constructed XML documents that allow an interested person to
# subscribe and receive updates from a particular web service. This portion of
# the standard library provides tooling to read and create these feeds.
#
# The standard library supports RSS 0.91, 1.0, 2.0, and Atom, a related format.
# Here are some links to the standards documents for these formats:
#
# * RSS
# * 0.9.1[http://www.rssboard.org/rss-0-9-1-netscape]
# * 1.0[http://web.resource.org/rss/1.0/]
# * 2.0[http://www.rssboard.org/rss-specification]
# * Atom[http://tools.ietf.org/html/rfc4287]
#
# == Consuming RSS
#
# If you'd like to read someone's RSS feed with your Ruby code, you've come to
# the right place. It's really easy to do this, but we'll need the help of
# open-uri:
#
# require 'rss'
# require 'open-uri'
#
# url = 'http://www.ruby-lang.org/en/feeds/news.rss'
# open(url) do |rss|
# feed = RSS::Parser.parse(rss)
# puts "Title: #{feed.channel.title}"
# feed.items.each do |item|
# puts "Item: #{item.title}"
# end
# end
#
# As you can see, the workhorse is RSS::Parser#parse, which takes the source of
# the feed and a parameter that performs validation on the feed. We get back an
# object that has all of the data from our feed, accessible through methods.
# This example shows getting the title out of the channel element, and looping
# through the list of items.
#
# == Producing RSS
#
# Producing our own RSS feeds is easy as well. Let's make a very basic feed:
#
# require "rss"
#
# rss = RSS::Maker.make("atom") do |maker|
# maker.channel.author = "matz"
# maker.channel.updated = Time.now.to_s
# maker.channel.about = "http://www.ruby-lang.org/en/feeds/news.rss"
# maker.channel.title = "Example Feed"
#
# maker.items.new_item do |item|
# item.link = "http://www.ruby-lang.org/en/news/2010/12/25/ruby-1-9-2-p136-is-released/"
# item.title = "Ruby 1.9.2-p136 is released"
# item.updated = Time.now.to_s
# end
# end
#
# puts rss
#
# As you can see, this is a very Builder-like DSL. This code will spit out an
# Atom feed with one item. If we needed a second item, we'd make another block
# with maker.items.new_item and build a second one.
#
# == Copyright
#
# Copyright (c) 2003-2007 Kouhei Sutou <kou@cozmixng.org>
#
# You can redistribute it and/or modify it under the same terms as Ruby.
#
# There is an additional tutorial by the author of RSS at:
# http://www.cozmixng.org/~rwiki/?cmd=view;name=RSS+Parser%3A%3ATutorial.en
module RSS
end
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 | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/complex.rb | lib/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 | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/xmlrpc.rb | lib/xmlrpc.rb | # == Author and Copyright
#
# Copyright (C) 2001-2004 by Michael Neumann (mailto:mneumann@ntecs.de)
#
# Released under the same term of license as Ruby.
#
# == Overview
#
# XMLRPC is a lightweight protocol that enables remote procedure calls over
# HTTP. It is defined at http://www.xmlrpc.com.
#
# XMLRPC allows you to create simple distributed computing solutions that span
# computer languages. Its distinctive feature is its simplicity compared to
# other approaches like SOAP and CORBA.
#
# The Ruby standard library package 'xmlrpc' enables you to create a server that
# implements remote procedures and a client that calls them. Very little code
# is required to achieve either of these.
#
# == Example
#
# Try the following code. It calls a standard demonstration remote procedure.
#
# require 'xmlrpc/client'
# require 'pp'
#
# server = XMLRPC::Client.new2("http://xmlrpc-c.sourceforge.net/api/sample.php")
# result = server.call("sample.sumAndDifference", 5, 3)
# pp result
#
# == Documentation
#
# See http://www.ntecs.de/ruby/xmlrpc4r/. There is plenty of detail there to
# use the client and implement a server.
#
# == Features of XMLRPC for Ruby
#
# * Extensions
# * Introspection
# * multiCall
# * optionally nil values and integers larger than 32 Bit
#
# * Server
# * Standalone XML-RPC server
# * CGI-based (works with FastCGI)
# * Apache mod_ruby server
# * WEBrick servlet
#
# * Client
# * synchronous/asynchronous calls
# * Basic HTTP-401 Authentication
# * HTTPS protocol (SSL)
#
# * Parsers
# * NQXML (XMLParser::NQXMLStreamParser, XMLParser::NQXMLTreeParser)
# * Expat (XMLParser::XMLStreamParser, XMLParser::XMLTreeParser)
# * REXML (XMLParser::REXMLStreamParser)
# * xml-scan (XMLParser::XMLScanStreamParser)
# * Fastest parser is Expat's XMLParser::XMLStreamParser!
#
# * General
# * possible to choose between XMLParser module (Expat wrapper) and REXML/NQXML (pure Ruby) parsers
# * Marshalling Ruby objects to Hashs and reconstruct them later from a Hash
# * SandStorm component architecture XMLRPC::Client interface
#
# == Howto
#
# === Client
#
# require "xmlrpc/client"
#
# # Make an object to represent the XML-RPC server.
# server = XMLRPC::Client.new( "xmlrpc-c.sourceforge.net", "/api/sample.php")
#
# # Call the remote server and get our result
# result = server.call("sample.sumAndDifference", 5, 3)
#
# sum = result["sum"]
# difference = result["difference"]
#
# puts "Sum: #{sum}, Difference: #{difference}"
#
# === XMLRPC::Client with XML-RPC fault-structure handling
#
# There are two possible ways, of handling a fault-structure:
#
# ==== by catching a XMLRPC::FaultException exception
#
# require "xmlrpc/client"
#
# # Make an object to represent the XML-RPC server.
# server = XMLRPC::Client.new( "xmlrpc-c.sourceforge.net", "/api/sample.php")
#
# begin
# # Call the remote server and get our result
# result = server.call("sample.sumAndDifference", 5, 3)
#
# sum = result["sum"]
# difference = result["difference"]
#
# puts "Sum: #{sum}, Difference: #{difference}"
#
# rescue XMLRPC::FaultException => e
# puts "Error: "
# puts e.faultCode
# puts e.faultString
# end
#
# ==== by calling "call2" which returns a boolean
#
# require "xmlrpc/client"
#
# # Make an object to represent the XML-RPC server.
# server = XMLRPC::Client.new( "xmlrpc-c.sourceforge.net", "/api/sample.php")
#
# # Call the remote server and get our result
# ok, result = server.call2("sample.sumAndDifference", 5, 3)
#
# if ok
# sum = result["sum"]
# difference = result["difference"]
#
# puts "Sum: #{sum}, Difference: #{difference}"
# else
# puts "Error: "
# puts result.faultCode
# puts result.faultString
# end
#
# === Using XMLRPC::Client::Proxy
#
# You can create a Proxy object onto which you can call methods. This way it
# looks nicer. Both forms, _call_ and _call2_ are supported through _proxy_ and
# _proxy2_. You can additionally give arguments to the Proxy, which will be
# given to each XML-RPC call using that Proxy.
#
# require "xmlrpc/client"
#
# # Make an object to represent the XML-RPC server.
# server = XMLRPC::Client.new( "xmlrpc-c.sourceforge.net", "/api/sample.php")
#
# # Create a Proxy object
# sample = server.proxy("sample")
#
# # Call the remote server and get our result
# result = sample.sumAndDifference(5,3)
#
# sum = result["sum"]
# difference = result["difference"]
#
# puts "Sum: #{sum}, Difference: #{difference}"
#
# === CGI-based server using XMLRPC::CGIServer
#
# There are also two ways to define handler, the first is
# like C/PHP, the second like Java, of course both ways
# can be mixed:
#
# ==== C/PHP-like (handler functions)
#
# require "xmlrpc/server"
#
# s = XMLRPC::CGIServer.new
#
# s.add_handler("sample.sumAndDifference") do |a,b|
# { "sum" => a + b, "difference" => a - b }
# end
#
# s.serve
#
# ==== Java-like (handler classes)
#
# require "xmlrpc/server"
#
# s = XMLRPC::CGIServer.new
#
# class MyHandler
# def sumAndDifference(a, b)
# { "sum" => a + b, "difference" => a - b }
# end
# end
#
# # NOTE: Security Hole (read below)!!!
# s.add_handler("sample", MyHandler.new)
# s.serve
#
#
# To return a fault-structure you have to raise an XMLRPC::FaultException e.g.:
#
# raise XMLRPC::FaultException.new(3, "division by Zero")
#
# ===== Security Note
#
# From Brian Candler:
#
# Above code sample has an extremely nasty security hole, in that you can now call
# any method of 'MyHandler' remotely, including methods inherited from Object
# and Kernel! For example, in the client code, you can use
#
# puts server.call("sample.send","`","ls")
#
# (backtick being the method name for running system processes). Needless to
# say, 'ls' can be replaced with something else.
#
# The version which binds proc objects (or the version presented below in the next section)
# doesn't have this problem, but people may be tempted to use the second version because it's
# so nice and 'Rubyesque'. I think it needs a big red disclaimer.
#
#
# From Michael:
#
# A solution is to undef insecure methods or to use
# XMLRPC::Service::PublicInstanceMethodsInterface as shown below:
#
# class MyHandler
# def sumAndDifference(a, b)
# { "sum" => a + b, "difference" => a - b }
# end
# end
#
# # ... server initialization ...
#
# s.add_handler(XMLRPC::iPIMethods("sample"), MyHandler.new)
#
# # ...
#
# This adds only public instance methods explicitly declared in class MyHandler
# (and not those inherited from any other class).
#
# ==== With interface declarations
#
# Code sample from the book Ruby Developer's Guide:
#
# require "xmlrpc/server"
#
# class Num
# INTERFACE = XMLRPC::interface("num") {
# meth 'int add(int, int)', 'Add two numbers', 'add'
# meth 'int div(int, int)', 'Divide two numbers'
# }
#
# def add(a, b) a + b end
# def div(a, b) a / b end
# end
#
#
# s = XMLRPC::CGIServer.new
# s.add_handler(Num::INTERFACE, Num.new)
# s.serve
#
# === Standalone XMLRPC::Server
#
# Same as CGI-based server, the only difference being
#
# server = XMLRPC::CGIServer.new
#
# must be changed to
#
# server = XMLRPC::Server.new(8080)
#
# if you want a server listening on port 8080.
# The rest is the same.
#
# === Choosing a different XMLParser or XMLWriter
#
# The examples above all use the default parser (which is now since 1.8
# XMLParser::REXMLStreamParser) and a default XMLRPC::XMLWriter.
# If you want to use a different XMLParser, then you have to call the
# ParserWriterChooseMixin#set_parser method of XMLRPC::Client instances
# or instances of subclasses of XMLRPC::BasicServer or by editing
# xmlrpc/config.rb.
#
# XMLRPC::Client Example:
#
# # ...
# server = XMLRPC::Client.new( "xmlrpc-c.sourceforge.net", "/api/sample.php")
# server.set_parser(XMLRPC::XMLParser::XMLParser.new)
# # ...
#
# XMLRPC::Server Example:
#
# # ...
# s = XMLRPC::CGIServer.new
# s.set_parser(XMLRPC::XMLParser::XMLStreamParser.new)
# # ...
#
# or:
#
# # ...
# server = XMLRPC::Server.new(8080)
# server.set_parser(XMLRPC::XMLParser::NQXMLParser.new)
# # ...
#
#
# Note that XMLParser::XMLStreamParser is incredible faster (and uses less memory) than any
# other parser and scales well for large documents. For example for a 0.5 MB XML
# document with many tags, XMLParser::XMLStreamParser is ~350 (!) times faster than
# XMLParser::NQXMLTreeParser and still ~18 times as fast as XMLParser::XMLTreeParser.
#
# You can change the XML-writer by calling method ParserWriterChooseMixin#set_writer.
module XMLRPC; end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/forwardable.rb | lib/forwardable.rb | #
# forwardable.rb -
# $Release Version: 1.1$
# $Revision: 40906 $
# by Keiju ISHITSUKA(keiju@ishitsuka.com)
# original definition by delegator.rb
# Revised by Daniel J. Berger with suggestions from Florian Gross.
#
# Documentation by James Edward Gray II and Gavin Sinclair
# The Forwardable module provides delegation of specified
# methods to a designated object, using the methods #def_delegator
# and #def_delegators.
#
# For example, say you have a class RecordCollection which
# contains an array <tt>@records</tt>. You could provide the lookup method
# #record_number(), which simply calls #[] on the <tt>@records</tt>
# array, like this:
#
# require 'forwardable'
#
# class RecordCollection
# attr_accessor :records
# extend Forwardable
# def_delegator :@records, :[], :record_number
# end
#
# We can use the lookup method like so:
#
# r = RecordCollection.new
# r.records = [4,5,6]
# r.record_number(0) # => 4
#
# Further, if you wish to provide the methods #size, #<<, and #map,
# all of which delegate to @records, this is how you can do it:
#
# class RecordCollection # re-open RecordCollection class
# def_delegators :@records, :size, :<<, :map
# end
#
# r = RecordCollection.new
# r.records = [1,2,3]
# r.record_number(0) # => 1
# r.size # => 3
# r << 4 # => [1, 2, 3, 4]
# r.map { |x| x * 2 } # => [2, 4, 6, 8]
#
# You can even extend regular objects with Forwardable.
#
# my_hash = Hash.new
# my_hash.extend Forwardable # prepare object for delegation
# my_hash.def_delegator "STDOUT", "puts" # add delegation for STDOUT.puts()
# my_hash.puts "Howdy!"
#
# == Another example
#
# We want to rely on what has come before obviously, but with delegation we can
# take just the methods we need and even rename them as appropriate. In many
# cases this is preferable to inheritance, which gives us the entire old
# interface, even if much of it isn't needed.
#
# class Queue
# extend Forwardable
#
# def initialize
# @q = [ ] # prepare delegate object
# end
#
# # setup preferred interface, enq() and deq()...
# def_delegator :@q, :push, :enq
# def_delegator :@q, :shift, :deq
#
# # support some general Array methods that fit Queues well
# def_delegators :@q, :clear, :first, :push, :shift, :size
# end
#
# q = Queue.new
# q.enq 1, 2, 3, 4, 5
# q.push 6
#
# q.shift # => 1
# while q.size > 0
# puts q.deq
# end
#
# q.enq "Ruby", "Perl", "Python"
# puts q.first
# q.clear
# puts q.first
#
# This should output:
#
# 2
# 3
# 4
# 5
# 6
# Ruby
# nil
#
# == Notes
#
# Be advised, RDoc will not detect delegated methods.
#
# +forwardable.rb+ provides single-method delegation via the def_delegator and
# def_delegators methods. For full-class delegation via DelegateClass, see
# +delegate.rb+.
#
module Forwardable
# Version of +forwardable.rb+
FORWARDABLE_VERSION = "1.1.0"
FILE_REGEXP = %r"#{Regexp.quote(__FILE__)}"
@debug = nil
class << self
# If true, <tt>__FILE__</tt> will remain in the backtrace in the event an
# Exception is raised.
attr_accessor :debug
end
# Takes a hash as its argument. The key is a symbol or an array of
# symbols. These symbols correspond to method names. The value is
# the accessor to which the methods will be delegated.
#
# :call-seq:
# delegate method => accessor
# delegate [method, method, ...] => accessor
#
def instance_delegate(hash)
hash.each{ |methods, accessor|
methods = [methods] unless methods.respond_to?(:each)
methods.each{ |method|
def_instance_delegator(accessor, method)
}
}
end
#
# Shortcut for defining multiple delegator methods, but with no
# provision for using a different name. The following two code
# samples have the same effect:
#
# def_delegators :@records, :size, :<<, :map
#
# def_delegator :@records, :size
# def_delegator :@records, :<<
# def_delegator :@records, :map
#
def def_instance_delegators(accessor, *methods)
methods.delete("__send__")
methods.delete("__id__")
for method in methods
def_instance_delegator(accessor, method)
end
end
# Define +method+ as delegator instance method with an optional
# alias name +ali+. Method calls to +ali+ will be delegated to
# +accessor.method+.
#
# class MyQueue
# extend Forwardable
# attr_reader :queue
# def initialize
# @queue = []
# end
#
# def_delegator :@queue, :push, :mypush
# end
#
# q = MyQueue.new
# q.mypush 42
# q.queue #=> [42]
# q.push 23 #=> NoMethodError
#
def def_instance_delegator(accessor, method, ali = method)
line_no = __LINE__; str = %{
def #{ali}(*args, &block)
begin
#{accessor}.__send__(:#{method}, *args, &block)
rescue Exception
$@.delete_if{|s| Forwardable::FILE_REGEXP =~ s} unless Forwardable::debug
::Kernel::raise
end
end
}
# If it's not a class or module, it's an instance
begin
module_eval(str, __FILE__, line_no)
rescue
instance_eval(str, __FILE__, line_no)
end
end
alias delegate instance_delegate
alias def_delegators def_instance_delegators
alias def_delegator def_instance_delegator
end
# SingleForwardable can be used to setup delegation at the object level as well.
#
# printer = String.new
# printer.extend SingleForwardable # prepare object for delegation
# printer.def_delegator "STDOUT", "puts" # add delegation for STDOUT.puts()
# printer.puts "Howdy!"
#
# Also, SingleForwardable can be used to set up delegation for a Class or Module.
#
# class Implementation
# def self.service
# puts "serviced!"
# end
# end
#
# module Facade
# extend SingleForwardable
# def_delegator :Implementation, :service
# end
#
# Facade.service #=> serviced!
#
# If you want to use both Forwardable and SingleForwardable, you can
# use methods def_instance_delegator and def_single_delegator, etc.
module SingleForwardable
# Takes a hash as its argument. The key is a symbol or an array of
# symbols. These symbols correspond to method names. The value is
# the accessor to which the methods will be delegated.
#
# :call-seq:
# delegate method => accessor
# delegate [method, method, ...] => accessor
#
def single_delegate(hash)
hash.each{ |methods, accessor|
methods = [methods] unless methods.respond_to?(:each)
methods.each{ |method|
def_single_delegator(accessor, method)
}
}
end
#
# Shortcut for defining multiple delegator methods, but with no
# provision for using a different name. The following two code
# samples have the same effect:
#
# def_delegators :@records, :size, :<<, :map
#
# def_delegator :@records, :size
# def_delegator :@records, :<<
# def_delegator :@records, :map
#
def def_single_delegators(accessor, *methods)
methods.delete("__send__")
methods.delete("__id__")
for method in methods
def_single_delegator(accessor, method)
end
end
# :call-seq:
# def_single_delegator(accessor, method, new_name=method)
#
# Defines a method _method_ which delegates to _accessor_ (i.e. it calls
# the method of the same name in _accessor_). If _new_name_ is
# provided, it is used as the name for the delegate method.
def def_single_delegator(accessor, method, ali = method)
str = %{
def #{ali}(*args, &block)
begin
#{accessor}.__send__(:#{method}, *args, &block)
rescue Exception
$@.delete_if{|s| Forwardable::FILE_REGEXP =~ s} unless Forwardable::debug
::Kernel::raise
end
end
}
instance_eval(str, __FILE__, __LINE__)
end
alias delegate single_delegate
alias def_delegators def_single_delegators
alias def_delegator def_single_delegator
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/shell.rb | lib/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"
# Shell implements an idiomatic Ruby interface for common UNIX shell commands.
#
# It provides users the ability to execute commands with filters and pipes,
# like +sh+/+csh+ by using native facilities of Ruby.
#
# == Examples
#
# === Temp file creation
#
# In this example we will create three +tmpFile+'s in three different folders
# under the +/tmp+ directory.
#
# sh = Shell.cd("/tmp") # Change to the /tmp directory
# sh.mkdir "shell-test-1" unless sh.exists?("shell-test-1")
# # make the 'shell-test-1' directory if it doesn't already exist
# sh.cd("shell-test-1") # Change to the /tmp/shell-test-1 directory
# for dir in ["dir1", "dir3", "dir5"]
# if !sh.exists?(dir)
# sh.mkdir dir # make dir if it doesnt' already exist
# sh.cd(dir) do
# # change to the `dir` directory
# f = sh.open("tmpFile", "w") # open a new file in write mode
# f.print "TEST\n" # write to the file
# f.close # close the file handler
# end
# print sh.pwd # output the process working directory
# end
# end
#
# === Temp file creation with self
#
# This example is identical to the first, except we're using
# CommandProcessor#transact.
#
# CommandProcessor#transact executes the given block against self, in this case
# +sh+; our Shell object. Within the block we can substitute +sh.cd+ to +cd+,
# because the scope within the block uses +sh+ already.
#
# sh = Shell.cd("/tmp")
# sh.transact do
# mkdir "shell-test-1" unless exists?("shell-test-1")
# cd("shell-test-1")
# for dir in ["dir1", "dir3", "dir5"]
# if !exists?(dir)
# mkdir dir
# cd(dir) do
# f = open("tmpFile", "w")
# f.print "TEST\n"
# f.close
# end
# print pwd
# end
# end
# end
#
# === Pipe /etc/printcap into a file
#
# In this example we will read the operating system file +/etc/printcap+,
# generated by +cupsd+, and then output it to a new file relative to the +pwd+
# of +sh+.
#
# sh = Shell.new
# sh.cat("/etc/printcap") | sh.tee("tee1") > "tee2"
# (sh.cat < "/etc/printcap") | sh.tee("tee11") > "tee12"
# sh.cat("/etc/printcap") | sh.tee("tee1") >> "tee2"
# (sh.cat < "/etc/printcap") | sh.tee("tee11") >> "tee12"
#
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
# call-seq:
# Shell.cd(path)
#
# Creates a new Shell instance with the current working directory
# set to +path+.
def cd(path)
new(path)
end
# Returns the directories in the current shell's PATH environment variable
# as an array of directory names. This sets the system_path for all
# instances of Shell.
#
# Example: If in your current shell, you did:
#
# $ echo $PATH
# /usr/bin:/bin:/usr/local/bin
#
# Running this method in the above shell would then return:
#
# ["/usr/bin", "/bin", "/usr/local/bin"]
#
def default_system_path
if @default_system_path
@default_system_path
else
ENV["PATH"].split(":")
end
end
# Sets the system_path that new instances of Shell should have as their
# initial system_path.
#
# +path+ should be an array of directory name strings.
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
# call-seq:
# Shell.new(pwd, umask) -> obj
#
# Creates a Shell object which current directory is set to the process
# current directory, unless otherwise specified by the +pwd+ argument.
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
# Returns the command search path in an array
attr_reader :system_path
# Sets the system path (the Shell instance's PATH environment variable).
#
# +path+ should be an array of directory name strings.
def system_path=(path)
@system_path = path
rehash
end
# Returns the umask
attr_accessor :umask
attr_accessor :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
# Returns the current working directory.
attr_reader :cwd
alias dir cwd
alias getwd cwd
alias pwd cwd
attr_reader :dir_stack
alias dirs dir_stack
# call-seq:
# Shell.chdir(path)
#
# Creates a Shell object which current directory is set to +path+.
#
# If a block is given, it restores the current directory when the block ends.
#
# 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
# call-seq:
# pushdir(path)
# pushdir(path) { &block }
#
# Pushes the current directory to the directory stack, changing the current
# directory to +path+.
#
# If +path+ is omitted, it exchanges its current directory and the top of its
# directory stack.
#
# If a block is given, it restores the current directory when the block ends.
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
# Pops a directory from the directory stack, and sets the current directory
# to it.
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
# Returns a list of scheduled jobs.
def jobs
@process_controller.jobs
end
# call-seq:
# kill(signal, job)
#
# Sends the given +signal+ to the given +job+
def kill(sig, command)
@process_controller.kill_job(sig, command)
end
# Convenience method for Shell::CommandProcessor.def_system_command
def Shell.def_system_command(command, path = command)
CommandProcessor.def_system_command(command, path)
end
# Convenience method for Shell::CommandProcessor.undef_system_command
def Shell.undef_system_command(command)
CommandProcessor.undef_system_command(command)
end
# Convenience method for Shell::CommandProcessor.alias_command
def Shell.alias_command(ali, command, *opts, &block)
CommandProcessor.alias_command(ali, command, *opts, &block)
end
# Convenience method for Shell::CommandProcessor.unalias_command
def Shell.unalias_command(ali)
CommandProcessor.unalias_command(ali)
end
# Convenience method for Shell::CommandProcessor.install_system_commands
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)
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 | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/shellwords.rb | lib/shellwords.rb | ##
# == Manipulates strings like the 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 [1]).
#
# === Usage
#
# You can use shellwords to parse a string into a Bourne shell friendly Array.
#
# require 'shellwords'
#
# argv = Shellwords.split('three blind "mice"')
# argv #=> ["three", "blind", "mice"]
#
# Once you've required Shellwords, you can use the #split alias
# String#shellsplit.
#
# argv = "see how they run".shellsplit
# argv #=> ["see", "how", "they", "run"]
#
# Be careful you don't leave a quote unmatched.
#
# argv = "they all ran after the farmer's wife".shellsplit
# #=> ArgumentError: Unmatched double quote: ...
#
# In this case, you might want to use Shellwords.escape, or it's alias
# String#shellescape.
#
# This method will escape the String for you to safely use with a Bourne shell.
#
# argv = Shellwords.escape("special's.txt")
# argv #=> "special\\'s.txt"
# system("cat " + argv)
#
# Shellwords also comes with a core extension for Array, Array#shelljoin.
#
# argv = %w{ls -lta lib}
# system(argv.shelljoin)
#
# You can use this method to create an escaped string out of an array of tokens
# separated by a space. In this example we'll use the literal shortcut for
# Array.new.
#
# === Authors
# * Wakou Aoyama
# * Akinori MUSHA <knu@iDaemons.org>
#
# === Contact
# * Akinori MUSHA <knu@iDaemons.org> (current maintainer)
#
# === Resources
#
# 1: {IEEE Std 1003.1-2004}[http://pubs.opengroup.org/onlinepubs/009695399/toc.htm]
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 shortcut 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(/\\(.)/, '\\1'))
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. +str+ can be a non-string object that responds to
# +to_s+.
#
# Note that a resulted string should be used unquoted and is not
# intended for use in double quotes nor in single quotes.
#
# argv = Shellwords.escape("It's better to give than to receive")
# argv #=> "It\\'s\\ better\\ to\\ give\\ than\\ to\\ receive"
#
# String#shellescape is a shorthand for this function.
#
# argv = "It's better to give than to receive".shellescape
# argv #=> "It\\'s\\ better\\ to\\ give\\ than\\ to\\ receive"
#
# # Search files in lib for method definitions
# pattern = "^[ \t]*def "
# open("| grep -Ern #{pattern.shellescape} lib") { |grep|
# grep.each_line { |line|
# file, lineno, matched_line = line.split(':', 3)
# # ...
# }
# }
#
# It is the caller's responsibility to encode the string in the right
# encoding for the shell environment where this string is used.
#
# Multibyte characters are treated as multibyte characters, not bytes.
#
# Returns an empty quoted String if +str+ has a length of zero.
def shellescape(str)
str = str.to_s
# An empty argument will be skipped, so return empty quotes.
return "''" if str.empty?
str = str.dup
# Treat multibyte characters as is. It is caller's responsibility
# to encode the string in the right encoding for the shell
# environment.
str.gsub!(/([^A-Za-z0-9_\-.,:\/@\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+.
#
# All elements are joined into a single string with fields separated by a
# space, where each element is escaped for Bourne shell and stringified using
# +to_s+.
#
# ary = ["There's", "a", "time", "and", "place", "for", "everything"]
# argv = Shellwords.join(ary)
# argv #=> "There\\'s a time and place for everything"
#
# Array#shelljoin is a shortcut for this function.
#
# ary = ["Don't", "rock", "the", "boat"]
# argv = ary.shelljoin
# argv #=> "Don\\'t rock the boat"
#
# You can also mix non-string objects in the elements as allowed in Array#join.
#
# output = `#{['ps', '-p', $$].shelljoin}`
#
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 | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/tkcanvas.rb | lib/tkcanvas.rb | #
# tkcanvas.rb - load tk/canvas.rb
#
require 'tk/canvas'
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/pathname.rb | lib/pathname.rb | #
# = pathname.rb
#
# Object-Oriented Pathname Class
#
# Author:: Tanaka Akira <akr@m17n.org>
# Documentation:: Author and Gavin Sinclair
#
# For documentation, see class Pathname.
#
require 'pathname.so'
class Pathname
# :stopdoc:
if RUBY_VERSION < "1.9"
TO_PATH = :to_str
else
# to_path is implemented so Pathname objects are usable with File.open, etc.
TO_PATH = :to_path
end
SAME_PATHS = if File::FNM_SYSCASE.nonzero?
proc {|a, b| a.casecmp(b).zero?}
else
proc {|a, b| a == b}
end
if File::ALT_SEPARATOR
SEPARATOR_LIST = "#{Regexp.quote File::ALT_SEPARATOR}#{Regexp.quote File::SEPARATOR}"
SEPARATOR_PAT = /[#{SEPARATOR_LIST}]/
else
SEPARATOR_LIST = "#{Regexp.quote File::SEPARATOR}"
SEPARATOR_PAT = /#{Regexp.quote File::SEPARATOR}/
end
# :startdoc:
# chop_basename(path) -> [pre-basename, basename] or nil
def chop_basename(path) # :nodoc:
base = File.basename(path)
if /\A#{SEPARATOR_PAT}?\z/o =~ base
return nil
else
return path[0, path.rindex(base)], base
end
end
private :chop_basename
# split_names(path) -> prefix, [name, ...]
def split_names(path) # :nodoc:
names = []
while r = chop_basename(path)
path, basename = r
names.unshift basename
end
return path, names
end
private :split_names
def prepend_prefix(prefix, relpath) # :nodoc:
if relpath.empty?
File.dirname(prefix)
elsif /#{SEPARATOR_PAT}/o =~ prefix
prefix = File.dirname(prefix)
prefix = File.join(prefix, "") if File.basename(prefix + 'a') != 'a'
prefix + relpath
else
prefix + relpath
end
end
private :prepend_prefix
# Returns clean pathname of +self+ with consecutive slashes and useless dots
# removed. The filesystem is not accessed.
#
# If +consider_symlink+ is +true+, then a more conservative algorithm is used
# to avoid breaking symbolic linkages. This may retain more +..+
# entries than absolutely necessary, but without accessing the filesystem,
# this can't be avoided.
#
# See Pathname#realpath.
#
def cleanpath(consider_symlink=false)
if consider_symlink
cleanpath_conservative
else
cleanpath_aggressive
end
end
#
# Clean the path simply by resolving and removing excess +.+ and +..+ entries.
# Nothing more, nothing less.
#
def cleanpath_aggressive # :nodoc:
path = @path
names = []
pre = path
while r = chop_basename(pre)
pre, base = r
case base
when '.'
when '..'
names.unshift base
else
if names[0] == '..'
names.shift
else
names.unshift base
end
end
end
if /#{SEPARATOR_PAT}/o =~ File.basename(pre)
names.shift while names[0] == '..'
end
self.class.new(prepend_prefix(pre, File.join(*names)))
end
private :cleanpath_aggressive
# has_trailing_separator?(path) -> bool
def has_trailing_separator?(path) # :nodoc:
if r = chop_basename(path)
pre, basename = r
pre.length + basename.length < path.length
else
false
end
end
private :has_trailing_separator?
# add_trailing_separator(path) -> path
def add_trailing_separator(path) # :nodoc:
if File.basename(path + 'a') == 'a'
path
else
File.join(path, "") # xxx: Is File.join is appropriate to add separator?
end
end
private :add_trailing_separator
def del_trailing_separator(path) # :nodoc:
if r = chop_basename(path)
pre, basename = r
pre + basename
elsif /#{SEPARATOR_PAT}+\z/o =~ path
$` + File.dirname(path)[/#{SEPARATOR_PAT}*\z/o]
else
path
end
end
private :del_trailing_separator
def cleanpath_conservative # :nodoc:
path = @path
names = []
pre = path
while r = chop_basename(pre)
pre, base = r
names.unshift base if base != '.'
end
if /#{SEPARATOR_PAT}/o =~ File.basename(pre)
names.shift while names[0] == '..'
end
if names.empty?
self.class.new(File.dirname(pre))
else
if names.last != '..' && File.basename(path) == '.'
names << '.'
end
result = prepend_prefix(pre, File.join(*names))
if /\A(?:\.|\.\.)\z/ !~ names.last && has_trailing_separator?(path)
self.class.new(add_trailing_separator(result))
else
self.class.new(result)
end
end
end
private :cleanpath_conservative
# Returns the parent directory.
#
# This is same as <code>self + '..'</code>.
def parent
self + '..'
end
# Returns +true+ if +self+ points to a mountpoint.
def mountpoint?
begin
stat1 = self.lstat
stat2 = self.parent.lstat
stat1.dev == stat2.dev && stat1.ino == stat2.ino ||
stat1.dev != stat2.dev
rescue Errno::ENOENT
false
end
end
#
# Predicate method for root directories. Returns +true+ if the
# pathname consists of consecutive slashes.
#
# It doesn't access the filesystem. So it may return +false+ for some
# pathnames which points to roots such as <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.
#
# p = Pathname.new('/im/sure')
# p.absolute?
# #=> true
#
# p = Pathname.new('not/so/sure')
# p.absolute?
# #=> false
def absolute?
!relative?
end
# The opposite of Pathname#absolute?
#
# It returns +false+ if the pathname begins with a slash.
#
# p = Pathname.new('/im/sure')
# p.relative?
# #=> false
#
# p = Pathname.new('not/so/sure')
# p.relative?
# #=> true
def relative?
path = @path
while r = chop_basename(path)
path, = r
end
path == ''
end
#
# Iterates over each component of the path.
#
# Pathname.new("/usr/bin/ruby").each_filename {|filename| ... }
# # yields "usr", "bin", and "ruby".
#
# Returns an Enumerator if no block was given.
#
# enum = Pathname.new("/usr/bin/ruby").each_filename
# # ... do stuff ...
# enum.each { |e| ... }
# # yields "usr", "bin", and "ruby".
#
def each_filename # :yield: filename
return to_enum(__method__) unless block_given?
_, names = split_names(@path)
names.each {|filename| yield filename }
nil
end
# Iterates over and yields a new Pathname object
# for each element in the given path in descending order.
#
# Pathname.new('/path/to/some/file.rb').descend {|v| p v}
# #<Pathname:/>
# #<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 the filesystem.
#
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 the filesystem.
#
def ascend
path = @path
yield self
while r = chop_basename(path)
path, = r
break if path.empty?
yield self.class.new(del_trailing_separator(path))
end
end
#
# Appends a pathname fragment to +self+ 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 # :nodoc:
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
#
# Joins the given pathnames onto +self+ to create a new Pathname object.
#
# path0 = Pathname.new("/usr") # Pathname:/usr
# path0 = path0.join("bin/ruby") # Pathname:/usr/bin/ruby
# # is the same as
# path1 = Pathname.new("/usr") + "bin/ruby" # Pathname:/usr/bin/ruby
# path0 == path1
# #=> true
#
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 results never contain the entries +.+ and +..+ in
# the directory because they are not children.
#
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>
#
# Note that the results never contain the entries +.+ and +..+ in
# the directory because they are not children.
#
# See Pathname#children
#
def each_child(with_directory=true, &b)
children(with_directory).each(&b)
end
#
# Returns a relative path from the given +base_directory+ to the receiver.
#
# If +self+ is absolute, then +base_directory+ must be absolute too.
#
# If +self+ is relative, then +base_directory+ must be relative too.
#
# This method doesn't access the filesystem. It assumes no symlinks.
#
# ArgumentError is raised when it cannot find a relative path.
#
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 # * Find *
#
# Iterates over the directory tree in a depth first manner, yielding a
# Pathname for each file under "this" directory.
#
# Returns an Enumerator if no block is given.
#
# Since it is implemented by the standard library module Find, Find.prune can
# be used to control the traversal.
#
# If +self+ is +.+, yielded pathnames begin with a filename in the
# current directory, not +./+.
#
# See Find.find
#
def find # :yield: pathname
return to_enum(__method__) unless block_given?
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 *
# Creates a full path, including any intermediate directories that don't yet
# exist.
#
# See FileUtils.mkpath and FileUtils.mkdir_p
def mkpath
require 'fileutils'
FileUtils.mkpath(@path)
nil
end
# Recursively deletes a directory, including all directories beneath it.
#
# See FileUtils.rm_r
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
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/mkmf.rb | lib/mkmf.rb | # -*- coding: us-ascii -*-
# module to create Makefile for extension modules
# invoke like: ruby -r mkmf extconf.rb
require 'rbconfig'
require 'fileutils'
require 'shellwords'
# :stopdoc:
class String
# Wraps a string in escaped quotes if it contains whitespace.
def quote
/\s/ =~ self ? "\"#{self}\"" : "#{self}"
end
# Escape whitespaces for Makefile.
def unspace
gsub(/\s/, '\\\\\\&')
end
# Generates a string used as cpp macro name.
def tr_cpp
strip.upcase.tr_s("^A-Z0-9_*", "_").tr_s("*", "P")
end
def funcall_style
/\)\z/ =~ self ? dup : "#{self}()"
end
def sans_arguments
self[/\A[^()]+/]
end
end
class Array
# Wraps all strings in escaped quotes if they contain whitespace.
def quote
map {|s| s.quote}
end
end
# :startdoc:
##
# mkmf.rb is used by Ruby C extensions to generate a Makefile which will
# correctly compile and link the C extension to Ruby and a third-party
# library.
module MakeMakefile
#### defer until this module become global-state free.
# def self.extended(obj)
# obj.init_mkmf
# super
# end
#
# def initialize(*args, rbconfig: RbConfig, **rest)
# init_mkmf(rbconfig::MAKEFILE_CONFIG, rbconfig::CONFIG)
# super(*args, **rest)
# end
##
# The makefile configuration using the defaults from when Ruby was built.
CONFIG = RbConfig::MAKEFILE_CONFIG
ORIG_LIBPATH = ENV['LIB']
##
# Extensions for files compiled with a C compiler
C_EXT = %w[c m]
##
# Extensions for files complied with a C++ compiler
CXX_EXT = %w[cc mm cxx cpp]
if File::FNM_SYSCASE.zero?
CXX_EXT.concat(%w[C])
end
##
# Extensions for source files
SRC_EXT = C_EXT + CXX_EXT
##
# Extensions for header files
HDR_EXT = %w[h hpp]
$static = nil
$config_h = '$(arch_hdrdir)/ruby/config.h'
$default_static = $static
unless defined? $configure_args
$configure_args = {}
args = CONFIG["configure_args"]
if ENV["CONFIGURE_ARGS"]
args << " " << ENV["CONFIGURE_ARGS"]
end
for arg in Shellwords::shellwords(args)
arg, val = arg.split('=', 2)
next unless arg
arg.tr!('_', '-')
if arg.sub!(/^(?!--)/, '--')
val or next
arg.downcase!
end
next if /^--(?:top|topsrc|src|cur)dir$/ =~ arg
$configure_args[arg] = val || true
end
for arg in ARGV
arg, val = arg.split('=', 2)
next unless arg
arg.tr!('_', '-')
if arg.sub!(/^(?!--)/, '--')
val or next
arg.downcase!
end
$configure_args[arg] = val || true
end
end
$libdir = CONFIG["libdir"]
$rubylibdir = CONFIG["rubylibdir"]
$archdir = CONFIG["archdir"]
$sitedir = CONFIG["sitedir"]
$sitelibdir = CONFIG["sitelibdir"]
$sitearchdir = CONFIG["sitearchdir"]
$vendordir = CONFIG["vendordir"]
$vendorlibdir = CONFIG["vendorlibdir"]
$vendorarchdir = CONFIG["vendorarchdir"]
$mswin = /mswin/ =~ RUBY_PLATFORM
$bccwin = /bccwin/ =~ RUBY_PLATFORM
$mingw = /mingw/ =~ RUBY_PLATFORM
$cygwin = /cygwin/ =~ RUBY_PLATFORM
$netbsd = /netbsd/ =~ RUBY_PLATFORM
$os2 = /os2/ =~ RUBY_PLATFORM
$beos = /beos/ =~ RUBY_PLATFORM
$haiku = /haiku/ =~ RUBY_PLATFORM
$solaris = /solaris/ =~ RUBY_PLATFORM
$universal = /universal/ =~ RUBY_PLATFORM
$dest_prefix_pattern = (File::PATH_SEPARATOR == ';' ? /\A([[:alpha:]]:)?/ : /\A/)
# :stopdoc:
def config_string(key, config = CONFIG)
s = config[key] and !s.empty? and block_given? ? yield(s) : s
end
module_function :config_string
def dir_re(dir)
Regexp.new('\$(?:\('+dir+'\)|\{'+dir+'\})(?:\$(?:\(target_prefix\)|\{target_prefix\}))?')
end
module_function :dir_re
def relative_from(path, base)
dir = File.join(path, "")
if File.expand_path(dir) == File.expand_path(dir, base)
path
else
File.join(base, path)
end
end
INSTALL_DIRS = [
[dir_re('commondir'), "$(RUBYCOMMONDIR)"],
[dir_re('sitedir'), "$(RUBYCOMMONDIR)"],
[dir_re('vendordir'), "$(RUBYCOMMONDIR)"],
[dir_re('rubylibdir'), "$(RUBYLIBDIR)"],
[dir_re('archdir'), "$(RUBYARCHDIR)"],
[dir_re('sitelibdir'), "$(RUBYLIBDIR)"],
[dir_re('vendorlibdir'), "$(RUBYLIBDIR)"],
[dir_re('sitearchdir'), "$(RUBYARCHDIR)"],
[dir_re('vendorarchdir'), "$(RUBYARCHDIR)"],
[dir_re('rubyhdrdir'), "$(RUBYHDRDIR)"],
[dir_re('sitehdrdir'), "$(SITEHDRDIR)"],
[dir_re('vendorhdrdir'), "$(VENDORHDRDIR)"],
[dir_re('bindir'), "$(BINDIR)"],
]
def install_dirs(target_prefix = nil)
if $extout
dirs = [
['BINDIR', '$(extout)/bin'],
['RUBYCOMMONDIR', '$(extout)/common'],
['RUBYLIBDIR', '$(RUBYCOMMONDIR)$(target_prefix)'],
['RUBYARCHDIR', '$(extout)/$(arch)$(target_prefix)'],
['HDRDIR', '$(extout)/include/ruby$(target_prefix)'],
['ARCHHDRDIR', '$(extout)/include/$(arch)/ruby$(target_prefix)'],
['extout', "#$extout"],
['extout_prefix', "#$extout_prefix"],
]
elsif $extmk
dirs = [
['BINDIR', '$(bindir)'],
['RUBYCOMMONDIR', '$(rubylibdir)'],
['RUBYLIBDIR', '$(rubylibdir)$(target_prefix)'],
['RUBYARCHDIR', '$(archdir)$(target_prefix)'],
['HDRDIR', '$(rubyhdrdir)/ruby$(target_prefix)'],
['ARCHHDRDIR', '$(rubyhdrdir)/$(arch)/ruby$(target_prefix)'],
]
elsif $configure_args.has_key?('--vendor')
dirs = [
['BINDIR', '$(bindir)'],
['RUBYCOMMONDIR', '$(vendordir)$(target_prefix)'],
['RUBYLIBDIR', '$(vendorlibdir)$(target_prefix)'],
['RUBYARCHDIR', '$(vendorarchdir)$(target_prefix)'],
['HDRDIR', '$(rubyhdrdir)/ruby$(target_prefix)'],
['ARCHHDRDIR', '$(rubyhdrdir)/$(arch)/ruby$(target_prefix)'],
]
else
dirs = [
['BINDIR', '$(bindir)'],
['RUBYCOMMONDIR', '$(sitedir)$(target_prefix)'],
['RUBYLIBDIR', '$(sitelibdir)$(target_prefix)'],
['RUBYARCHDIR', '$(sitearchdir)$(target_prefix)'],
['HDRDIR', '$(rubyhdrdir)/ruby$(target_prefix)'],
['ARCHHDRDIR', '$(rubyhdrdir)/$(arch)/ruby$(target_prefix)'],
]
end
dirs << ['target_prefix', (target_prefix ? "/#{target_prefix}" : "")]
dirs
end
def map_dir(dir, map = nil)
map ||= INSTALL_DIRS
map.inject(dir) {|d, (orig, new)| d.gsub(orig, new)}
end
topdir = File.dirname(File.dirname(__FILE__))
path = File.expand_path($0)
until (dir = File.dirname(path)) == path
if File.identical?(dir, topdir)
$extmk = true if %r"\A(?:ext|enc|tool|test)\z" =~ File.basename(path)
break
end
path = dir
end
$extmk ||= false
if not $extmk and File.exist?(($hdrdir = RbConfig::CONFIG["rubyhdrdir"]) + "/ruby/ruby.h")
$topdir = $hdrdir
$top_srcdir = $hdrdir
$arch_hdrdir = RbConfig::CONFIG["rubyarchhdrdir"]
elsif File.exist?(($hdrdir = ($top_srcdir ||= topdir) + "/include") + "/ruby.h")
$topdir ||= RbConfig::CONFIG["topdir"]
$arch_hdrdir = "$(extout)/include/$(arch)"
else
abort "mkmf.rb can't find header files for ruby at #{$hdrdir}/ruby.h"
end
CONFTEST = "conftest".freeze
CONFTEST_C = "#{CONFTEST}.c"
OUTFLAG = CONFIG['OUTFLAG']
COUTFLAG = CONFIG['COUTFLAG']
CPPOUTFILE = config_string('CPPOUTFILE') {|str| str.sub(/\bconftest\b/, CONFTEST)}
def rm_f(*files)
opt = (Hash === files.last ? [files.pop] : [])
FileUtils.rm_f(Dir[*files.flatten], *opt)
end
module_function :rm_f
def rm_rf(*files)
opt = (Hash === files.last ? [files.pop] : [])
FileUtils.rm_rf(Dir[*files.flatten], *opt)
end
module_function :rm_rf
# Returns time stamp of the +target+ file if it exists and is newer than or
# equal to all of +times+.
def modified?(target, times)
(t = File.mtime(target)) rescue return nil
Array === times or times = [times]
t if times.all? {|n| n <= t}
end
def split_libs(*strs)
strs.map {|s| s.split(/\s+(?=-|\z)/)}.flatten
end
def merge_libs(*libs)
libs.inject([]) do |x, y|
y = y.inject([]) {|ary, e| ary.last == e ? ary : ary << e}
y.each_with_index do |v, yi|
if xi = x.rindex(v)
x[(xi+1)..-1] = merge_libs(y[(yi+1)..-1], x[(xi+1)..-1])
x[xi, 0] = y[0...yi]
break
end
end and x.concat(y)
x
end
end
# This is a custom logging module. It generates an mkmf.log file when you
# run your extconf.rb script. This can be useful for debugging unexpected
# failures.
#
# This module and its associated methods are meant for internal use only.
#
module Logging
@log = nil
@logfile = 'mkmf.log'
@orgerr = $stderr.dup
@orgout = $stdout.dup
@postpone = 0
@quiet = $extmk
def self::log_open
@log ||= File::open(@logfile, 'wb')
@log.sync = true
end
def self::log_opened?
@log and not @log.closed?
end
def self::open
log_open
$stderr.reopen(@log)
$stdout.reopen(@log)
yield
ensure
$stderr.reopen(@orgerr)
$stdout.reopen(@orgout)
end
def self::message(*s)
log_open
@log.printf(*s)
end
def self::logfile file
@logfile = file
log_close
end
def self::log_close
if @log and not @log.closed?
@log.flush
@log.close
@log = nil
end
end
def self::postpone
tmplog = "mkmftmp#{@postpone += 1}.log"
open do
log, *save = @log, @logfile, @orgout, @orgerr
@log, @logfile, @orgout, @orgerr = nil, tmplog, log, log
begin
log.print(open {yield @log})
ensure
@log.close if @log and not @log.closed?
File::open(tmplog) {|t| FileUtils.copy_stream(t, log)} if File.exist?(tmplog)
@log, @logfile, @orgout, @orgerr = log, *save
@postpone -= 1
MakeMakefile.rm_f tmplog
end
end
end
class << self
attr_accessor :quiet
end
end
def libpath_env
# used only if native compiling
if libpathenv = config_string("LIBPATHENV")
pathenv = ENV[libpathenv]
libpath = RbConfig.expand($DEFLIBPATH.join(File::PATH_SEPARATOR))
{libpathenv => [libpath, pathenv].compact.join(File::PATH_SEPARATOR)}
else
{}
end
end
def xsystem command, opts = nil
varpat = /\$\((\w+)\)|\$\{(\w+)\}/
if varpat =~ command
vars = Hash.new {|h, k| h[k] = ENV[k]}
command = command.dup
nil while command.gsub!(varpat) {vars[$1||$2]}
end
Logging::open do
puts command.quote
if opts and opts[:werror]
result = nil
Logging.postpone do |log|
result = (system(libpath_env, command) and File.zero?(log.path))
""
end
result
else
system(libpath_env, command)
end
end
end
def xpopen command, *mode, &block
Logging::open do
case mode[0]
when nil, /^r/
puts "#{command} |"
else
puts "| #{command}"
end
IO.popen(libpath_env, command, *mode, &block)
end
end
def log_src(src, heading="checked program was")
src = src.split(/^/)
fmt = "%#{src.size.to_s.size}d: %s"
Logging::message <<"EOM"
#{heading}:
/* begin */
EOM
src.each_with_index {|line, no| Logging::message fmt, no+1, line}
Logging::message <<"EOM"
/* end */
EOM
end
def create_tmpsrc(src)
src = "#{COMMON_HEADERS}\n#{src}"
src = yield(src) if block_given?
src.gsub!(/[ \t]+$/, '')
src.gsub!(/\A\n+|^\n+$/, '')
src.sub!(/[^\n]\z/, "\\&\n")
count = 0
begin
open(CONFTEST_C, "wb") do |cfile|
cfile.print src
end
rescue Errno::EACCES
if (count += 1) < 5
sleep 0.2
retry
end
end
src
end
def have_devel?
unless defined? $have_devel
$have_devel = true
$have_devel = try_link(MAIN_DOES_NOTHING)
end
$have_devel
end
def try_do(src, command, *opts, &b)
unless have_devel?
raise <<MSG
The compiler failed to generate an executable file.
You have to install development tools first.
MSG
end
begin
src = create_tmpsrc(src, &b)
xsystem(command, *opts)
ensure
log_src(src)
MakeMakefile.rm_rf "#{CONFTEST}.dSYM"
end
end
def link_command(ldflags, opt="", libpath=$DEFLIBPATH|$LIBPATH)
librubyarg = $extmk ? $LIBRUBYARG_STATIC : "$(LIBRUBYARG)"
conf = RbConfig::CONFIG.merge('hdrdir' => $hdrdir.quote,
'src' => "#{CONFTEST_C}",
'arch_hdrdir' => $arch_hdrdir.quote,
'top_srcdir' => $top_srcdir.quote,
'INCFLAGS' => "#$INCFLAGS",
'CPPFLAGS' => "#$CPPFLAGS",
'CFLAGS' => "#$CFLAGS",
'ARCH_FLAG' => "#$ARCH_FLAG",
'LDFLAGS' => "#$LDFLAGS #{ldflags}",
'LOCAL_LIBS' => "#$LOCAL_LIBS #$libs",
'LIBS' => "#{librubyarg} #{opt} #$LIBS")
conf['LIBPATH'] = libpathflag(libpath.map {|s| RbConfig::expand(s.dup, conf)})
RbConfig::expand(TRY_LINK.dup, conf)
end
def cc_command(opt="")
conf = RbConfig::CONFIG.merge('hdrdir' => $hdrdir.quote, 'srcdir' => $srcdir.quote,
'arch_hdrdir' => $arch_hdrdir.quote,
'top_srcdir' => $top_srcdir.quote)
RbConfig::expand("$(CC) #$INCFLAGS #$CPPFLAGS #$CFLAGS #$ARCH_FLAG #{opt} -c #{CONFTEST_C}",
conf)
end
def cpp_command(outfile, opt="")
conf = RbConfig::CONFIG.merge('hdrdir' => $hdrdir.quote, 'srcdir' => $srcdir.quote,
'arch_hdrdir' => $arch_hdrdir.quote,
'top_srcdir' => $top_srcdir.quote)
if $universal and (arch_flag = conf['ARCH_FLAG']) and !arch_flag.empty?
conf['ARCH_FLAG'] = arch_flag.gsub(/(?:\G|\s)-arch\s+\S+/, '')
end
RbConfig::expand("$(CPP) #$INCFLAGS #$CPPFLAGS #$CFLAGS #{opt} #{CONFTEST_C} #{outfile}",
conf)
end
def libpathflag(libpath=$DEFLIBPATH|$LIBPATH)
libpath.map{|x|
case x
when "$(topdir)", /\A\./
LIBPATHFLAG
else
LIBPATHFLAG+RPATHFLAG
end % x.quote
}.join
end
def with_werror(opt, opts = nil)
if opts
if opts[:werror] and config_string("WERRORFLAG") {|flag| opt = opt ? "#{opt} #{flag}" : flag}
(opts = opts.dup).delete(:werror)
end
yield(opt, opts)
else
yield(opt)
end
end
def try_link0(src, opt="", *opts, &b) # :nodoc:
cmd = link_command("", opt)
if $universal
require 'tmpdir'
Dir.mktmpdir("mkmf_", oldtmpdir = ENV["TMPDIR"]) do |tmpdir|
begin
ENV["TMPDIR"] = tmpdir
try_do(src, cmd, *opts, &b)
ensure
ENV["TMPDIR"] = oldtmpdir
end
end
else
try_do(src, cmd, *opts, &b)
end and File.executable?(CONFTEST+$EXEEXT)
end
# Returns whether or not the +src+ can be compiled as a C source and linked
# with its depending libraries successfully. +opt+ is passed to the linker
# as options. Note that +$CFLAGS+ and +$LDFLAGS+ are also passed to the
# linker.
#
# If a block given, it is called with the source before compilation. You can
# modify the source in the block.
#
# [+src+] a String which contains a C source
# [+opt+] a String which contains linker options
def try_link(src, opt="", *opts, &b)
try_link0(src, opt, *opts, &b)
ensure
MakeMakefile.rm_f "#{CONFTEST}*", "c0x32*"
end
# Returns whether or not the +src+ can be compiled as a C source. +opt+ is
# passed to the C compiler as options. Note that +$CFLAGS+ is also passed to
# the compiler.
#
# If a block given, it is called with the source before compilation. You can
# modify the source in the block.
#
# [+src+] a String which contains a C source
# [+opt+] a String which contains compiler options
def try_compile(src, opt="", *opts, &b)
with_werror(opt, *opts) {|_opt, *_opts| try_do(src, cc_command(_opt), *_opts, &b)} and
File.file?("#{CONFTEST}.#{$OBJEXT}")
ensure
MakeMakefile.rm_f "#{CONFTEST}*"
end
# Returns whether or not the +src+ can be preprocessed with the C
# preprocessor. +opt+ is passed to the preprocessor as options. Note that
# +$CFLAGS+ is also passed to the preprocessor.
#
# If a block given, it is called with the source before preprocessing. You
# can modify the source in the block.
#
# [+src+] a String which contains a C source
# [+opt+] a String which contains preprocessor options
def try_cpp(src, opt="", *opts, &b)
try_do(src, cpp_command(CPPOUTFILE, opt), *opts, &b) and
File.file?("#{CONFTEST}.i")
ensure
MakeMakefile.rm_f "#{CONFTEST}*"
end
alias_method :try_header, (config_string('try_header') || :try_cpp)
def cpp_include(header)
if header
header = [header] unless header.kind_of? Array
header.map {|h| String === h ? "#include <#{h}>\n" : h}.join
else
""
end
end
def with_cppflags(flags)
cppflags = $CPPFLAGS
$CPPFLAGS = flags
ret = yield
ensure
$CPPFLAGS = cppflags unless ret
end
def try_cppflags(flags)
with_cppflags(flags) do
try_header("int main() {return 0;}")
end
end
def with_cflags(flags)
cflags = $CFLAGS
$CFLAGS = flags
ret = yield
ensure
$CFLAGS = cflags unless ret
end
def try_cflags(flags)
with_cflags(flags) do
try_compile("int main() {return 0;}")
end
end
def with_ldflags(flags)
ldflags = $LDFLAGS
$LDFLAGS = flags
ret = yield
ensure
$LDFLAGS = ldflags unless ret
end
def try_ldflags(flags)
with_ldflags(flags) do
try_link("int main() {return 0;}")
end
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)
neg = try_static_assert("#{const} < 0", headers, opt)
if CROSS_COMPILING
if neg
const = "-(#{const})"
elsif try_static_assert("#{const} > 0", headers, opt)
# positive constant
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*/
typedef#{neg ? '' : ' unsigned'}
#ifdef PRI_LL_PREFIX
#define PRI_CONFTEST_PREFIX PRI_LL_PREFIX
LONG_LONG
#else
#define PRI_CONFTEST_PREFIX "l"
long
#endif
conftest_type;
conftest_type conftest_const = (conftest_type)(#{const});
int main() {printf("%"PRI_CONFTEST_PREFIX"#{neg ? 'd' : 'u'}\\n", conftest_const); return 0;}
}
begin
if try_link0(src, opt, &b)
xpopen("./#{CONFTEST}") do |f|
return Integer(f.gets)
end
end
ensure
MakeMakefile.rm_f "#{CONFTEST}*"
end
end
nil
end
# You should use +have_func+ rather than +try_func+.
#
# [+func+] a String which contains a symbol name
# [+libs+] a String which contains library names.
# [+headers+] a String or an Array of strings which contains names of header
# files.
def try_func(func, libs, headers = nil, opt = "", &b)
headers = cpp_include(headers)
case func
when /^&/
decltype = proc {|x|"const volatile void *#{x}"}
when /\)$/
call = func
else
call = "#{func}()"
decltype = proc {|x| "void ((*#{x})())"}
end
if opt and !opt.empty?
[[:to_str], [:join, " "], [:to_s]].each do |meth, *args|
if opt.respond_to?(meth)
break opt = opt.send(meth, *args)
end
end
opt = "#{opt} #{libs}"
else
opt = libs
end
decltype && try_link(<<"SRC", opt, &b) or
#{headers}
/*top*/
extern int t(void);
#{MAIN_DOES_NOTHING 't'}
int t(void) { #{decltype["volatile p"]}; p = (#{decltype[]})#{func}; return 0; }
SRC
call && try_link(<<"SRC", opt, &b)
#{headers}
/*top*/
extern int t(void);
#{MAIN_DOES_NOTHING 't'}
int t(void) { #{call}; return 0; }
SRC
end
# You should use +have_var+ rather than +try_var+.
def try_var(var, headers = nil, opt = "", &b)
headers = cpp_include(headers)
try_compile(<<"SRC", opt, &b)
#{headers}
/*top*/
extern int t(void);
#{MAIN_DOES_NOTHING 't'}
int t(void) { const volatile void *volatile p; p = &(&#{var})[0]; return 0; }
SRC
end
# Returns whether or not the +src+ can be preprocessed with the C
# preprocessor and matches with +pat+.
#
# If a block given, it is called with the source before compilation. You can
# modify the source in the block.
#
# [+pat+] a Regexp or a String
# [+src+] a String which contains a C source
# [+opt+] a String which contains preprocessor options
#
# NOTE: When pat is a Regexp the matching will be checked in process,
# otherwise egrep(1) will be invoked to check it.
def egrep_cpp(pat, src, opt = "", &b)
src = create_tmpsrc(src, &b)
xpopen(cpp_command('', opt)) do |f|
if Regexp === pat
puts(" ruby -ne 'print if #{pat.inspect}'")
f.grep(pat) {|l|
puts "#{f.lineno}: #{l}"
return true
}
false
else
puts(" egrep '#{pat}'")
begin
stdin = $stdin.dup
$stdin.reopen(f)
system("egrep", pat)
ensure
$stdin.reopen(stdin)
end
end
end
ensure
MakeMakefile.rm_f "#{CONFTEST}*"
log_src(src)
end
# This is used internally by the have_macro? method.
def macro_defined?(macro, src, opt = "", &b)
src = src.sub(/[^\n]\z/, "\\&\n")
try_compile(src + <<"SRC", opt, &b)
/*top*/
#ifndef #{macro}
# error
|:/ === #{macro} undefined === /:|
#endif
SRC
end
# Returns whether or not:
# * the +src+ can be compiled as a C source,
# * the result object can be linked with its depending libraries
# successfully,
# * the linked file can be invoked as an executable
# * and the executable exits successfully
#
# +opt+ is passed to the linker as options. Note that +$CFLAGS+ and
# +$LDFLAGS+ are also passed to the linker.
#
# If a block given, it is called with the source before compilation. You can
# modify the source in the block.
#
# [+src+] a String which contains a C source
# [+opt+] a String which contains linker options
#
# Returns true when the executable exits successfully, false when it fails,
# or nil when preprocessing, compilation or link fails.
def try_run(src, opt = "", &b)
raise "cannot run test program while cross compiling" if CROSS_COMPILING
if try_link0(src, opt, &b)
xsystem("./#{CONFTEST}")
else
nil
end
ensure
MakeMakefile.rm_f "#{CONFTEST}*"
end
def install_files(mfile, ifiles, map = nil, srcprefix = nil)
ifiles or return
ifiles.empty? and return
srcprefix ||= "$(srcdir)/#{srcprefix}".chomp('/')
RbConfig::expand(srcdir = srcprefix.dup)
dirs = []
path = Hash.new {|h, i| h[i] = dirs.push([i])[-1]}
ifiles.each do |files, dir, prefix|
dir = map_dir(dir, map)
prefix &&= %r|\A#{Regexp.quote(prefix)}/?|
if /\A\.\// =~ files
# install files which are in current working directory.
files = files[2..-1]
len = nil
else
# install files which are under the $(srcdir).
files = File.join(srcdir, files)
len = srcdir.size
end
f = nil
Dir.glob(files) do |fx|
f = fx
f[0..len] = "" if len
case File.basename(f)
when *$NONINSTALLFILES
next
end
d = File.dirname(f)
d.sub!(prefix, "") if prefix
d = (d.empty? || d == ".") ? dir : File.join(dir, d)
f = File.join(srcprefix, f) if len
path[d] << f
end
unless len or f
d = File.dirname(files)
d.sub!(prefix, "") if prefix
d = (d.empty? || d == ".") ? dir : File.join(dir, d)
path[d] << files
end
end
dirs
end
def install_rb(mfile, dest, srcdir = nil)
install_files(mfile, [["lib/**/*.rb", dest, "lib"]], nil, srcdir)
end
def append_library(libs, lib) # :no-doc:
format(LIBARG, lib) + " " + libs
end
def message(*s)
unless Logging.quiet and not $VERBOSE
printf(*s)
$stdout.flush
end
end
# This emits a string to stdout that allows users to see the results of the
# various have* and find* methods as they are tested.
#
# Internal use only.
#
def checking_for(m, fmt = nil)
f = caller[0][/in `([^<].*)'$/, 1] and f << ": " #` for vim #'
m = "checking #{/\Acheck/ =~ f ? '' : 'for '}#{m}... "
message "%s", m
a = r = nil
Logging::postpone do
r = yield
a = (fmt ? "#{fmt % r}" : r ? "yes" : "no") << "\n"
"#{f}#{m}-------------------- #{a}\n"
end
message(a)
Logging::message "--------------------\n\n"
r
end
def checking_message(target, place = nil, opt = nil)
[["in", place], ["with", opt]].inject("#{target}") do |msg, (pre, noun)|
if noun
[[:to_str], [:join, ","], [:to_s]].each do |meth, *args|
if noun.respond_to?(meth)
break noun = noun.send(meth, *args)
end
end
msg << " #{pre} #{noun}" unless noun.empty?
end
msg
end
end
# :startdoc:
# Returns whether or not +macro+ is defined either in the common header
# files or within any +headers+ you provide.
#
# Any options you pass to +opt+ are passed along to the compiler.
#
def have_macro(macro, headers = nil, opt = "", &b)
checking_for checking_message(macro, headers, opt) do
macro_defined?(macro, cpp_include(headers), opt, &b)
end
end
# Returns whether or not the given entry point +func+ can be found within
# +lib+. If +func+ is +nil+, the <code>main()</code> 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
# <code>--with-FOOlib</code> configuration option.
#
def have_library(lib, func = nil, headers = nil, opt = "", &b)
func = "main" if !func or func.empty?
lib = with_config(lib+'lib', lib)
checking_for checking_message(func.funcall_style, LIBARG%lib, opt) do
if COMMON_LIBS.include?(lib)
true
else
libs = append_library($libs, lib)
if try_func(func, libs, headers, opt, &b)
$libs = libs
true
else
false
end
end
end
end
# Returns whether or not the entry point +func+ can be found within the
# library +lib+ in one of the +paths+ specified, where +paths+ is an array
# of strings. If +func+ is +nil+ , then the <code>main()</code> function is
# used as the entry point.
#
# If +lib+ is found, then the path it was found on is added to the list of
# library paths searched and linked against.
#
def find_library(lib, func, *paths, &b)
func = "main" if !func or func.empty?
lib = with_config(lib+'lib', lib)
paths = paths.collect {|path| path.split(File::PATH_SEPARATOR)}.flatten
checking_for checking_message(func.funcall_style, LIBARG%lib) do
libpath = $LIBPATH
libs = append_library($libs, lib)
begin
until r = try_func(func, libs, &b) or paths.empty?
$LIBPATH = libpath | [paths.shift]
end
if r
$libs = libs
libpath = nil
end
ensure
$LIBPATH = libpath if libpath
end
r
end
end
# Returns whether or not the function +func+ can be found in the common
# header files, or within any +headers+ that you provide. If found, a macro
# is passed as a preprocessor constant to the compiler using the function
# name, in uppercase, prepended with +HAVE_+.
#
# To check functions in an additional library, you need to check that
# library first using <code>have_library()</code>. The +func+ shall be
# either mere function name or function name with arguments.
#
# For example, if <code>have_func('foo')</code> returned +true+, then the
# +HAVE_FOO+ preprocessor macro would be passed to the compiler.
#
def have_func(func, headers = nil, opt = "", &b)
checking_for checking_message(func.funcall_style, headers, opt) do
if try_func(func, $libs, headers, opt, &b)
$defs << "-DHAVE_#{func.sans_arguments.tr_cpp}"
true
else
false
end
end
end
# Returns whether or not the variable +var+ can be found in the common
# header files, or within any +headers+ that you provide. If found, a macro
# is passed as a preprocessor constant to the compiler using the variable
# name, in uppercase, prepended with +HAVE_+.
#
# To check variables in an additional library, you need to check that
# library first using <code>have_library()</code>.
#
# For example, if <code>have_var('foo')</code> returned true, then the
# +HAVE_FOO+ preprocessor macro would be passed to the compiler.
#
def have_var(var, headers = nil, opt = "", &b)
checking_for checking_message(var, headers, opt) do
if try_var(var, headers, opt, &b)
$defs.push(format("-DHAVE_%s", var.tr_cpp))
true
else
false
end
end
end
# Returns whether or not the given +header+ file can be found on your system.
# If found, a macro is passed as a preprocessor constant to the compiler
# using the header file name, in uppercase, prepended with +HAVE_+.
#
# For example, if <code>have_header('foo.h')</code> returned true, then the
# +HAVE_FOO_H+ preprocessor macro would be passed to the compiler.
#
def have_header(header, preheaders = nil, opt = "", &b)
checking_for header do
if try_header(cpp_include(preheaders)+cpp_include(header), opt, &b)
$defs.push(format("-DHAVE_%s", header.tr_cpp))
true
else
false
end
end
end
# Returns whether or not the given +framework+ can be found on your system.
# If found, a macro is passed as a preprocessor constant to the compiler
# using the framework name, in uppercase, prepended with +HAVE_FRAMEWORK_+.
#
# For example, if <code>have_framework('Ruby')</code> returned true, then
# the +HAVE_FRAMEWORK_RUBY+ preprocessor macro would be passed to the
# compiler.
#
# If +fw+ is a pair of the framework name and its header file name
# that header file is checked, instead of the normally used header
# file which is named same as the framework.
def have_framework(fw, &b)
if Array === fw
fw, header = *fw
else
header = "#{fw}.h"
end
checking_for fw do
src = cpp_include("#{fw}/#{header}") << "\n" "int main(void){return 0;}"
opt = " -framework #{fw}"
if try_link(src, "-ObjC#{opt}", &b)
$defs.push(format("-DHAVE_FRAMEWORK_%s", fw.tr_cpp))
# TODO: non-worse way than this hack, to get rid of separating
# option and its argument.
$LDFLAGS << " -ObjC" unless /(\A|\s)-ObjC(\s|\z)/ =~ $LDFLAGS
$LIBS << opt
true
else
false
end
end
end
# Instructs mkmf to search for the given +header+ in any of the +paths+
# provided, and returns whether or not it was found in those paths.
#
# If the header is found then the path it was found on is added to the list
# of included directories that are sent to the compiler (via the
# <code>-I</code> 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)
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | true |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/tkclass.rb | lib/tkclass.rb | #
# tkclass.rb - Tk classes
# Date: 2000/11/27 09:23:36
# by Yukihiro Matsumoto <matz@caelum.co.jp>
#
# $Id: tkclass.rb 25189 2009-10-02 12:04:37Z akr $
require "tk"
TopLevel = TkToplevel
Frame = TkFrame
Label = TkLabel
Button = TkButton
Radiobutton = TkRadioButton
Checkbutton = TkCheckButton
Message = TkMessage
Entry = TkEntry
Spinbox = TkSpinbox
Text = TkText
Scale = TkScale
Scrollbar = TkScrollbar
Listbox = TkListbox
Menu = TkMenu
Menubutton = TkMenubutton
Canvas = TkCanvas
Arc = TkcArc
Bitmap = TkcBitmap
Line = TkcLine
Oval = TkcOval
Polygon = TkcPolygon
Rectangle = TkcRectangle
TextItem = TkcText
WindowItem = TkcWindow
BitmapImage = TkBitmapImage
PhotoImage = TkPhotoImage
Selection = TkSelection
Winfo = TkWinfo
Pack = TkPack
Grid = TkGrid
Place = TkPlace
Variable = TkVariable
Font = TkFont
VirtualEvent = TkVirtualEvent
def Mainloop
Tk.mainloop
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/pstore.rb | lib/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 "digest/md5"
#
# 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
RDWR_ACCESS = {mode: IO::RDWR | IO::CREAT | IO::BINARY, encoding: Encoding::ASCII_8BIT}.freeze
RD_ACCESS = {mode: IO::RDONLY | IO::BINARY, encoding: Encoding::ASCII_8BIT}.freeze
WR_ACCESS = {mode: IO::WRONLY | IO::CREAT | IO::TRUNC | IO::BINARY, encoding: Encoding::ASCII_8BIT}.freeze
# 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
@filename = file
@abort = false
@ultra_safe = false
@thread_safe = thread_safe
@lock = Mutex.new
end
# Raises PStore::Error if the calling code is not in a PStore#transaction.
def in_transaction
raise PStore::Error, "not in transaction" unless @lock.locked?
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) # :yields: pstore
value = nil
if !@thread_safe
raise PStore::Error, "nested transaction" unless @lock.try_lock
else
begin
@lock.lock
rescue ThreadError
raise PStore::Error, "nested transaction"
end
end
begin
@rdonly = read_only
@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
ensure
@lock.unlock
end
value
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)
#
# 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)
raise Error, "PStore file seems to be corrupted." unless table.is_a?(Hash)
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.bytesize
else
table = load(data)
checksum = Digest::MD5.digest(data)
size = data.bytesize
raise Error, "PStore file seems to be corrupted." unless table.is_a?(Hash)
end
data.replace(EMPTY_STRING)
[table, checksum, size]
end
end
def on_windows?
is_windows = RUBY_PLATFORM =~ /mswin|mingw|bccwin|wince/
self.class.__send__(:define_method, :on_windows?) do
is_windows
end
is_windows
end
def save_data(original_checksum, original_file_size, file)
new_data = dump(@table)
if new_data.bytesize != original_file_size || Digest::MD5.digest(new_data) != 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.write(data)
file.truncate(data.bytesize)
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 | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/prettyprint.rb | lib/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?
#
# Report any bugs at http://bugs.ruby-lang.org
#
# == 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@fsij.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
# The output object.
#
# This defaults to '', and should accept the << method
attr_reader :output
# The maximum width of a line, before it is separated in to a newline
#
# This defaults to 79, and should be a Fixnum
attr_reader :maxwidth
# The value that is appended to +output+ to add a new line.
#
# This defaults to "\n", and should be String
attr_reader :newline
# A lambda or Proc, that takes one argument, of a Fixnum, and returns
# the corresponding number of spaces.
#
# By default this is:
# lambda {|n| ' ' * n}
attr_reader :genspace
# The number of spaces to be indented
attr_reader :indent
# The PrettyPrint::GroupQueue of groups in stack to be pretty printed
attr_reader :group_queue
# Returns the group most recently added to the stack.
#
# Contrived example:
# out = ""
# => ""
# q = PrettyPrint.new(out)
# => #<PrettyPrint:0x82f85c0 @output="", @maxwidth=79, @newline="\n", @genspace=#<Proc:0x82f8368@/home/vbatts/.rvm/rubies/ruby-head/lib/ruby/2.0.0/prettyprint.rb:82 (lambda)>, @output_width=0, @buffer_width=0, @buffer=[], @group_stack=[#<PrettyPrint::Group:0x82f8138 @depth=0, @breakables=[], @break=false>], @group_queue=#<PrettyPrint::GroupQueue:0x82fb7c0 @queue=[[#<PrettyPrint::Group:0x82f8138 @depth=0, @breakables=[], @break=false>]]>, @indent=0>
# q.group {
# q.text q.current_group.inspect
# q.text q.newline
# q.group(q.current_group.depth + 1) {
# q.text q.current_group.inspect
# q.text q.newline
# q.group(q.current_group.depth + 1) {
# q.text q.current_group.inspect
# q.text q.newline
# q.group(q.current_group.depth + 1) {
# q.text q.current_group.inspect
# q.text q.newline
# }
# }
# }
# }
# => 284
# puts out
# #<PrettyPrint::Group:0x8354758 @depth=1, @breakables=[], @break=false>
# #<PrettyPrint::Group:0x8354550 @depth=2, @breakables=[], @break=false>
# #<PrettyPrint::Group:0x83541cc @depth=3, @breakables=[], @break=false>
# #<PrettyPrint::Group:0x8347e54 @depth=4, @breakables=[], @break=false>
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
# Breaks the buffer into lines that are shorter than #maxwidth
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
# This is similar to #breakable except
# the decision to break or not is determined individually.
#
# Two #fill_breakable under a group may cause 4 results:
# (break,break), (break,non-break), (non-break,break), (non-break,non-break).
# This is different to #breakable because two #breakable under a group
# may cause 2 results:
# (break,break), (non-break,non-break).
#
# The text +sep+ is inserted if a line is not broken at this 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 fill_breakable(sep=' ', width=sep.length)
group { breakable sep, width }
end
# This says "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
# Takes a block and queues a new group that is indented 1 level further.
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
# The Text class is the means by which to collect strings from objects.
#
# This class is intended for internal use of the PrettyPrint buffers.
class Text # :nodoc:
# Creates a new text object.
#
# This constructor takes no arguments.
#
# The workflow is to append a PrettyPrint::Text object to the buffer, and
# being able to call the buffer.last() to reference it.
#
# As there are objects, use PrettyPrint::Text#add to include the objects
# and the width to utilized by the String version of this object.
def initialize
@objs = []
@width = 0
end
# The total width of the objects included in this Text object.
attr_reader :width
# Render the String text of the objects that have been added to this Text object.
#
# Output the text to +out+, and increment the width to +output_width+
def output(out, output_width)
@objs.each {|obj| out << obj}
output_width + @width
end
# Include +obj+ in the objects to be pretty printed, and increment
# this Text object's total width by +width+
def add(obj, width)
@objs << obj
@width += width
end
end
# The Breakable class is used for breaking up object information
#
# This class is intended for internal use of the PrettyPrint buffers.
class Breakable # :nodoc:
# Create a new Breakable object.
#
# Arguments:
# * +sep+ String of the separator
# * +width+ Fixnum width of the +sep+
# * +q+ parent PrettyPrint object, to base from
def initialize(sep, width, q)
@obj = sep
@width = width
@pp = q
@indent = q.indent
@group = q.current_group
@group.breakables.push self
end
# Holds the separator String
#
# The +sep+ argument from ::new
attr_reader :obj
# The width of +obj+ / +sep+
attr_reader :width
# The number of spaces to indent.
#
# This is inferred from +q+ within PrettyPrint, passed in ::new
attr_reader :indent
# Render the String text of the objects that have been added to this
# Breakable object.
#
# Output the text to +out+, and increment the width to +output_width+
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
# The Group class is used for making indentation easier.
#
# While this class does neither the breaking into newlines nor indentation,
# it is used in a stack (as well as a queue) within PrettyPrint, to group
# objects.
#
# For information on using groups, see PrettyPrint#group
#
# This class is intended for internal use of the PrettyPrint buffers.
class Group # :nodoc:
# Create a Group object
#
# Arguments:
# * +depth+ - this group's relation to previous groups
def initialize(depth)
@depth = depth
@breakables = []
@break = false
end
# This group's relation to previous groups
attr_reader :depth
# Array to hold the Breakable objects for this Group
attr_reader :breakables
# Makes a break for this Group, and returns true
def break
@break = true
end
# Boolean of whether this Group has made a break
def break?
@break
end
# Boolean of whether this Group has been queried for being first
#
# This is used as a predicate, and ought to be called first.
def first?
if defined? @first
false
else
@first = false
true
end
end
end
# The GroupQueue class is used for managing the queue of Group to be pretty
# printed.
#
# This queue groups the Group objects, based on their depth.
#
# This class is intended for internal use of the PrettyPrint buffers.
class GroupQueue # :nodoc:
# Create a GroupQueue object
#
# Arguments:
# * +groups+ - one or more PrettyPrint::Group objects
def initialize(*groups)
@queue = []
groups.each {|g| enq g}
end
# Enqueue +group+
#
# This does not strictly append the group to the end of the queue,
# but instead adds it in line, base on the +group.depth+
def enq(group)
depth = group.depth
@queue << [] until depth < @queue.length
@queue[depth] << group
end
# Returns the outer group of the queue
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
# Remote +group+ from this queue
def delete(group)
@queue[group.depth].delete(group)
end
end
# PrettyPrint::SingleLine is used by PrettyPrint.singleline_format
#
# It is passed to be similar to a PrettyPrint object itself, by responding to:
# * #text
# * #breakable
# * #nest
# * #group
# * #flush
# * #first?
#
# but instead, the output has no line breaks
#
class SingleLine
# Create a PrettyPrint::SingleLine object
#
# Arguments:
# * +output+ - String (or similar) to store rendered text. Needs to respond to '<<'
# * +maxwidth+ - Argument position expected to be here for compatibility.
# This argument is a noop.
# * +newline+ - Argument position expected to be here for compatibility.
# This argument is a noop.
def initialize(output, maxwidth=nil, newline=nil)
@output = output
@first = [true]
end
# Add +obj+ to the text to be output.
#
# +width+ argument is here for compatibility. It is a noop argument.
def text(obj, width=nil)
@output << obj
end
# Appends +sep+ to the text to be output. By default +sep+ is ' '
#
# +width+ argument is here for compatibility. It is a noop argument.
def breakable(sep=' ', width=nil)
@output << sep
end
# Takes +indent+ arg, but does nothing with it.
#
# Yields to a block.
def nest(indent) # :nodoc:
yield
end
# Opens a block for grouping objects to be pretty printed.
#
# Arguments:
# * +indent+ - noop argument. Present for compatibility.
# * +open_obj+ - text appended before the &blok. Default is ''
# * +close_obj+ - text appended after the &blok. Default is ''
# * +open_width+ - noop argument. Present for compatibility.
# * +close_width+ - noop argument. Present for compatibility.
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
# Method present for compatibility, but is a noop
def flush # :nodoc:
end
# This is used as a predicate, and ought to be called first.
def first?
result = @first[-1]
@first[-1] = false
result
end
end
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/rbconfig.rb | lib/rbconfig.rb |
# This file was blindly copied from MRI 2.1.1 by Tim Jarratt when grubby was built.
# He then modified it to suit his whims and needs at the time.
# Any inconsistencies in this file are entirely his fault.
module RbConfig
CONFIG = {}
CONFIG["MAJOR"] = "2"
CONFIG["MINOR"] = "1"
CONFIG["TEENY"] = "1"
CONFIG["PATCHLEVEL"] = "0"
CONFIG["ruby_install_name"] = "grubby"
CONFIG["RUBY_INSTALL_NAME"] = "grubby"
CONFIG["RUBY_SO_NAME"] = "grubby.2.1.0"
CONFIG["PACKAGE"] = "ruby"
CONFIG["RUBY_SEARCH_PATH"] = ""
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/tkbgerror.rb | lib/tkbgerror.rb | #
# tkbgerror.rb - load tk/bgerror.rb
#
require 'tk/bgerror'
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/fiddle.rb | lib/fiddle.rb | require 'fiddle.so'
require 'fiddle/function'
require 'fiddle/closure'
module Fiddle
if WINDOWS
# Returns the last win32 +Error+ of the current executing +Thread+ or nil
# if none
def self.win32_last_error
Thread.current[:__FIDDLE_WIN32_LAST_ERROR__]
end
# Sets the last win32 +Error+ of the current executing +Thread+ to +error+
def self.win32_last_error= error
Thread.current[:__FIDDLE_WIN32_LAST_ERROR__] = error
end
end
# Returns the last +Error+ of the current executing +Thread+ or nil if none
def self.last_error
Thread.current[:__FIDDLE_LAST_ERROR__]
end
# Sets the last +Error+ of the current executing +Thread+ to +error+
def self.last_error= error
Thread.current[:__DL2_LAST_ERROR__] = error
Thread.current[:__FIDDLE_LAST_ERROR__] = error
end
# call-seq: dlopen(library) => Fiddle::Handle
#
# Creates a new handler that opens +library+, and returns an instance of
# Fiddle::Handle.
#
# If +nil+ is given for the +library+, Fiddle::Handle::DEFAULT is used, which
# is the equivalent to RTLD_DEFAULT. See <code>man 3 dlopen</code> for more.
#
# lib = Fiddle.dlopen(nil)
#
# The default is dependent on OS, and provide a handle for all libraries
# already loaded. For example, in most cases you can use this to access
# +libc+ functions, or ruby functions like +rb_str_new+.
#
# See Fiddle::Handle.new for more.
def dlopen library
Fiddle::Handle.new library
end
module_function :dlopen
# Add constants for backwards compat
RTLD_GLOBAL = Handle::RTLD_GLOBAL # :nodoc:
RTLD_LAZY = Handle::RTLD_LAZY # :nodoc:
RTLD_NOW = Handle::RTLD_NOW # :nodoc:
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/psych.rb | lib/psych.rb | require 'psych.so'
require 'psych/nodes'
require 'psych/streaming'
require 'psych/visitors'
require 'psych/handler'
require 'psych/tree_builder'
require 'psych/parser'
require 'psych/omap'
require 'psych/set'
require 'psych/coder'
require 'psych/core_ext'
require 'psych/deprecated'
require 'psych/stream'
require 'psych/json/tree_builder'
require 'psych/json/stream'
require 'psych/handlers/document_stream'
require 'psych/class_loader'
###
# = Overview
#
# Psych is a YAML parser and emitter.
# Psych leverages libyaml [Home page: http://pyyaml.org/wiki/LibYAML]
# or [Git repo: https://github.com/zerotao/libyaml] for its YAML parsing
# and emitting capabilities. In addition to wrapping libyaml, Psych also
# knows how to serialize and de-serialize most Ruby objects to and from
# the YAML format.
#
# = I NEED TO PARSE OR EMIT YAML RIGHT NOW!
#
# # Parse some YAML
# Psych.load("--- foo") # => "foo"
#
# # Emit some YAML
# Psych.dump("foo") # => "--- foo\n...\n"
# { :a => 'b'}.to_yaml # => "---\n:a: b\n"
#
# Got more time on your hands? Keep on reading!
#
# == YAML Parsing
#
# Psych provides a range of interfaces for parsing a YAML document ranging from
# low level to high level, depending on your parsing needs. At the lowest
# level, is an event based parser. Mid level is access to the raw YAML AST,
# and at the highest level is the ability to unmarshal YAML to Ruby objects.
#
# == YAML Emitting
#
# Psych provides a range of interfaces ranging from low to high level for
# producing YAML documents. Very similar to the YAML parsing interfaces, Psych
# provides at the lowest level, an event based system, mid-level is building
# a YAML AST, and the highest level is converting a Ruby object straight to
# a YAML document.
#
# == High-level API
#
# === Parsing
#
# The high level YAML parser provided by Psych simply takes YAML as input and
# returns a Ruby data structure. For information on using the high level parser
# see Psych.load
#
# ==== Reading from a string
#
# Psych.load("--- a") # => 'a'
# Psych.load("---\n - a\n - b") # => ['a', 'b']
#
# ==== Reading from a file
#
# Psych.load_file("database.yml")
#
# ==== Exception handling
#
# begin
# # The second argument chnages only the exception contents
# Psych.parse("--- `", "file.txt")
# rescue Psych::SyntaxError => ex
# ex.file # => 'file.txt'
# ex.message # => "(file.txt): found character that cannot start any token"
# end
#
# === Emitting
#
# The high level emitter has the easiest interface. Psych simply takes a Ruby
# data structure and converts it to a YAML document. See Psych.dump for more
# information on dumping a Ruby data structure.
#
# ==== Writing to a string
#
# # Dump an array, get back a YAML string
# Psych.dump(['a', 'b']) # => "---\n- a\n- b\n"
#
# # Dump an array to an IO object
# Psych.dump(['a', 'b'], StringIO.new) # => #<StringIO:0x000001009d0890>
#
# # Dump an array with indentation set
# Psych.dump(['a', ['b']], :indentation => 3) # => "---\n- a\n- - b\n"
#
# # Dump an array to an IO with indentation set
# Psych.dump(['a', ['b']], StringIO.new, :indentation => 3)
#
# ==== Writing to a file
#
# Currently there is no direct API for dumping Ruby structure to file:
#
# File.open('database.yml', 'w') do |file|
# file.write(Psych.dump(['a', 'b']))
# end
#
# == Mid-level API
#
# === Parsing
#
# Psych provides access to an AST produced from parsing a YAML document. This
# tree is built using the Psych::Parser and Psych::TreeBuilder. The AST can
# be examined and manipulated freely. Please see Psych::parse_stream,
# Psych::Nodes, and Psych::Nodes::Node for more information on dealing with
# YAML syntax trees.
#
# ==== Reading from a string
#
# # Returns Psych::Nodes::Stream
# Psych.parse_stream("---\n - a\n - b")
#
# # Returns Psych::Nodes::Document
# Psych.parse("---\n - a\n - b")
#
# ==== Reading from a file
#
# # Returns Psych::Nodes::Stream
# Psych.parse_stream(File.read('database.yml'))
#
# # Returns Psych::Nodes::Document
# Psych.parse_file('database.yml')
#
# ==== Exception handling
#
# begin
# # The second argument chnages only the exception contents
# Psych.parse("--- `", "file.txt")
# rescue Psych::SyntaxError => ex
# ex.file # => 'file.txt'
# ex.message # => "(file.txt): found character that cannot start any token"
# end
#
# === Emitting
#
# At the mid level is building an AST. This AST is exactly the same as the AST
# used when parsing a YAML document. Users can build an AST by hand and the
# AST knows how to emit itself as a YAML document. See Psych::Nodes,
# Psych::Nodes::Node, and Psych::TreeBuilder for more information on building
# a YAML AST.
#
# ==== Writing to a string
#
# # We need Psych::Nodes::Stream (not Psych::Nodes::Document)
# stream = Psych.parse_stream("---\n - a\n - b")
#
# stream.to_yaml # => "---\n- a\n- b\n"
#
# ==== Writing to a file
#
# # We need Psych::Nodes::Stream (not Psych::Nodes::Document)
# stream = Psych.parse_stream(File.read('database.yml'))
#
# File.open('database.yml', 'w') do |file|
# file.write(stream.to_yaml)
# end
#
# == Low-level API
#
# === Parsing
#
# The lowest level parser should be used when the YAML input is already known,
# and the developer does not want to pay the price of building an AST or
# automatic detection and conversion to Ruby objects. See Psych::Parser for
# more information on using the event based parser.
#
# ==== Reading to Psych::Nodes::Stream structure
#
# parser = Psych::Parser.new(TreeBuilder.new) # => #<Psych::Parser>
# parser = Psych.parser # it's an alias for the above
#
# parser.parse("---\n - a\n - b") # => #<Psych::Parser>
# parser.handler # => #<Psych::TreeBuilder>
# parser.handler.root # => #<Psych::Nodes::Stream>
#
# ==== Receiving an events stream
#
# parser = Psych::Parser.new(Psych::Handlers::Recorder.new)
#
# parser.parse("---\n - a\n - b")
# parser.events # => [list of [event, args] lists]
# # event is one of: Psych::Handler::EVENTS
# # args are the arguments passed to the event
#
# === Emitting
#
# The lowest level emitter is an event based system. Events are sent to a
# Psych::Emitter object. That object knows how to convert the events to a YAML
# document. This interface should be used when document format is known in
# advance or speed is a concern. See Psych::Emitter for more information.
#
# ==== Writing to a Ruby structure
#
# Psych.parser.parse("--- a") # => #<Psych::Parser>
#
# parser.handler.first # => #<Psych::Nodes::Stream>
# parser.handler.first.to_ruby # => ["a"]
#
# parser.handler.root.first # => #<Psych::Nodes::Document>
# parser.handler.root.first.to_ruby # => "a"
#
# # You can instantiate an Emitter manually
# Psych::Visitors::ToRuby.new.accept(parser.handler.root.first)
# # => "a"
module Psych
# The version is Psych you're using
VERSION = '2.0.3'
# The version of libyaml Psych is using
LIBYAML_VERSION = Psych.libyaml_version.join '.'
###
# Load +yaml+ in to a Ruby data structure. If multiple documents are
# provided, the object contained in the first document will be returned.
# +filename+ will be used in the exception message if any exception is raised
# while parsing.
#
# Raises a Psych::SyntaxError when a YAML syntax error is detected.
#
# Example:
#
# Psych.load("--- a") # => 'a'
# Psych.load("---\n - a\n - b") # => ['a', 'b']
#
# begin
# Psych.load("--- `", "file.txt")
# rescue Psych::SyntaxError => ex
# ex.file # => 'file.txt'
# ex.message # => "(file.txt): found character that cannot start any token"
# end
def self.load yaml, filename = nil
result = parse(yaml, filename)
result ? result.to_ruby : result
end
###
# Safely load the yaml string in +yaml+. By default, only the following
# classes are allowed to be deserialized:
#
# * TrueClass
# * FalseClass
# * NilClass
# * Numeric
# * String
# * Array
# * Hash
#
# Recursive data structures are not allowed by default. Arbitrary classes
# can be allowed by adding those classes to the +whitelist+. They are
# additive. For example, to allow Date deserialization:
#
# Psych.safe_load(yaml, [Date])
#
# Now the Date class can be loaded in addition to the classes listed above.
#
# Aliases can be explicitly allowed by changing the +aliases+ parameter.
# For example:
#
# x = []
# x << x
# yaml = Psych.dump x
# Psych.safe_load yaml # => raises an exception
# Psych.safe_load yaml, [], [], true # => loads the aliases
#
# A Psych::DisallowedClass exception will be raised if the yaml contains a
# class that isn't in the whitelist.
#
# A Psych::BadAlias exception will be raised if the yaml contains aliases
# but the +aliases+ parameter is set to false.
def self.safe_load yaml, whitelist_classes = [], whitelist_symbols = [], aliases = false, filename = nil
result = parse(yaml, filename)
return unless result
class_loader = ClassLoader::Restricted.new(whitelist_classes.map(&:to_s),
whitelist_symbols.map(&:to_s))
scanner = ScalarScanner.new class_loader
if aliases
visitor = Visitors::ToRuby.new scanner, class_loader
else
visitor = Visitors::NoAliasRuby.new scanner, class_loader
end
visitor.accept result
end
###
# Parse a YAML string in +yaml+. Returns the Psych::Nodes::Document.
# +filename+ is used in the exception message if a Psych::SyntaxError is
# raised.
#
# Raises a Psych::SyntaxError when a YAML syntax error is detected.
#
# Example:
#
# Psych.parse("---\n - a\n - b") # => #<Psych::Nodes::Document:0x00>
#
# begin
# Psych.parse("--- `", "file.txt")
# rescue Psych::SyntaxError => ex
# ex.file # => 'file.txt'
# ex.message # => "(file.txt): found character that cannot start any token"
# end
#
# See Psych::Nodes for more information about YAML AST.
def self.parse yaml, filename = nil
parse_stream(yaml, filename) do |node|
return node
end
false
end
###
# Parse a file at +filename+. Returns the Psych::Nodes::Document.
#
# Raises a Psych::SyntaxError when a YAML syntax error is detected.
def self.parse_file filename
File.open filename, 'r:bom|utf-8' do |f|
parse f, filename
end
end
###
# Returns a default parser
def self.parser
Psych::Parser.new(TreeBuilder.new)
end
###
# Parse a YAML string in +yaml+. Returns the Psych::Nodes::Stream.
# This method can handle multiple YAML documents contained in +yaml+.
# +filename+ is used in the exception message if a Psych::SyntaxError is
# raised.
#
# If a block is given, a Psych::Nodes::Document node will be yielded to the
# block as it's being parsed.
#
# Raises a Psych::SyntaxError when a YAML syntax error is detected.
#
# Example:
#
# Psych.parse_stream("---\n - a\n - b") # => #<Psych::Nodes::Stream:0x00>
#
# Psych.parse_stream("--- a\n--- b") do |node|
# node # => #<Psych::Nodes::Document:0x00>
# end
#
# begin
# Psych.parse_stream("--- `", "file.txt")
# rescue Psych::SyntaxError => ex
# ex.file # => 'file.txt'
# ex.message # => "(file.txt): found character that cannot start any token"
# end
#
# See Psych::Nodes for more information about YAML AST.
def self.parse_stream yaml, filename = nil, &block
if block_given?
parser = Psych::Parser.new(Handlers::DocumentStream.new(&block))
parser.parse yaml, filename
else
parser = self.parser
parser.parse yaml, filename
parser.handler.root
end
end
###
# call-seq:
# Psych.dump(o) -> string of yaml
# Psych.dump(o, options) -> string of yaml
# Psych.dump(o, io) -> io object passed in
# Psych.dump(o, io, options) -> io object passed in
#
# Dump Ruby object +o+ to a YAML string. Optional +options+ may be passed in
# to control the output format. If an IO object is passed in, the YAML will
# be dumped to that IO object.
#
# Example:
#
# # Dump an array, get back a YAML string
# Psych.dump(['a', 'b']) # => "---\n- a\n- b\n"
#
# # Dump an array to an IO object
# Psych.dump(['a', 'b'], StringIO.new) # => #<StringIO:0x000001009d0890>
#
# # Dump an array with indentation set
# Psych.dump(['a', ['b']], :indentation => 3) # => "---\n- a\n- - b\n"
#
# # Dump an array to an IO with indentation set
# Psych.dump(['a', ['b']], StringIO.new, :indentation => 3)
def self.dump o, io = nil, options = {}
if Hash === io
options = io
io = nil
end
visitor = Psych::Visitors::YAMLTree.create options
visitor << o
visitor.tree.yaml io, options
end
###
# Dump a list of objects as separate documents to a document stream.
#
# Example:
#
# Psych.dump_stream("foo\n ", {}) # => "--- ! \"foo\\n \"\n--- {}\n"
def self.dump_stream *objects
visitor = Psych::Visitors::YAMLTree.create({})
objects.each do |o|
visitor << o
end
visitor.tree.yaml
end
###
# Dump Ruby +object+ to a JSON string.
def self.to_json object
visitor = Psych::Visitors::JSONTree.create
visitor << object
visitor.tree.yaml
end
###
# Load multiple documents given in +yaml+. Returns the parsed documents
# as a list. If a block is given, each document will be converted to Ruby
# and passed to the block during parsing
#
# Example:
#
# Psych.load_stream("--- foo\n...\n--- bar\n...") # => ['foo', 'bar']
#
# list = []
# Psych.load_stream("--- foo\n...\n--- bar\n...") do |ruby|
# list << ruby
# end
# list # => ['foo', 'bar']
#
def self.load_stream yaml, filename = nil
if block_given?
parse_stream(yaml, filename) do |node|
yield node.to_ruby
end
else
parse_stream(yaml, filename).children.map { |child| child.to_ruby }
end
end
###
# Load the document contained in +filename+. Returns the yaml contained in
# +filename+ as a Ruby object
def self.load_file filename
File.open(filename, 'r:bom|utf-8') { |f| self.load f, filename }
end
# :stopdoc:
@domain_types = {}
def self.add_domain_type domain, type_tag, &block
key = ['tag', domain, type_tag].join ':'
@domain_types[key] = [key, block]
@domain_types["tag:#{type_tag}"] = [key, block]
end
def self.add_builtin_type type_tag, &block
domain = 'yaml.org,2002'
key = ['tag', domain, type_tag].join ':'
@domain_types[key] = [key, block]
end
def self.remove_type type_tag
@domain_types.delete type_tag
end
@load_tags = {}
@dump_tags = {}
def self.add_tag tag, klass
@load_tags[tag] = klass.name
@dump_tags[klass] = tag
end
class << self
attr_accessor :load_tags
attr_accessor :dump_tags
attr_accessor :domain_types
end
# :startdoc:
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/profile.rb | lib/profile.rb | require 'profiler'
RubyVM::InstructionSequence.compile_option = {
:trace_instruction => true,
:specialized_instruction => false
}
END {
Profiler__::print_profile(STDERR)
}
Profiler__::start_profile
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/erb.rb | lib/erb.rb | # -*- coding: us-ascii -*-
# = ERB -- Ruby Templating
#
# Author:: Masatoshi SEKI
# Documentation:: James Edward Gray II, Gavin Sinclair, and Simon Chiang
#
# 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.
require "cgi/util"
#
# = 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 {RubyGems.org}[https://rubygems.org/] or
# {The Ruby Toolbox}[https://www.ruby-toolbox.com/].
#
# Rails, the web application framework, uses ERB to create views.
#
class ERB
Revision = '$Date:: 2013-12-06 11:54:55 +0900#$' # :nodoc: #'
# Returns revision information for the erb.rb module.
def self.version
"erb.rb [2.1.0 #{ERB::Revision.split[1]}]"
end
end
#--
# ERB::Compiler
class ERB
# = ERB::Compiler
#
# Compiles ERB templates into Ruby code; the compiled code produces the
# template result when evaluated. ERB::Compiler provides hooks to define how
# generated output is handled.
#
# Internally ERB does something like this to generate the code returned by
# ERB#src:
#
# compiler = ERB::Compiler.new('<>')
# compiler.pre_cmd = ["_erbout=''"]
# compiler.put_cmd = "_erbout.concat"
# compiler.insert_cmd = "_erbout.concat"
# compiler.post_cmd = ["_erbout"]
#
# code, enc = compiler.compile("Got <%= obj %>!\n")
# puts code
#
# <i>Generates</i>:
#
# #coding:UTF-8
# _erbout=''; _erbout.concat "Got "; _erbout.concat(( obj ).to_s); _erbout.concat "!\n"; _erbout
#
# By default the output is sent to the print method. For example:
#
# compiler = ERB::Compiler.new('<>')
# code, enc = compiler.compile("Got <%= obj %>!\n")
# puts code
#
# <i>Generates</i>:
#
# #coding:UTF-8
# print "Got "; print(( obj ).to_s); print "!\n"
#
# == Evaluation
#
# The compiled code can be used in any context where the names in the code
# correctly resolve. Using the last example, each of these print 'Got It!'
#
# Evaluate using a variable:
#
# obj = 'It'
# eval code
#
# Evaluate using an input:
#
# mod = Module.new
# mod.module_eval %{
# def get(obj)
# #{code}
# end
# }
# extend mod
# get('It')
#
# Evaluate using an accessor:
#
# klass = Class.new Object
# klass.class_eval %{
# attr_accessor :obj
# def initialize(obj)
# @obj = obj
# end
# def get_it
# #{code}
# end
# }
# klass.new('It').get_it
#
# Good! See also ERB#def_method, ERB#def_module, and ERB#def_class.
class Compiler # :nodoc:
class PercentLine # :nodoc:
def initialize(str)
@value = str
end
attr_reader :value
alias :to_s :value
def empty?
@value.empty?
end
end
class Scanner # :nodoc:
@scanner_map = {}
def self.regist_scanner(klass, trim_mode, percent)
@scanner_map[[trim_mode, percent]] = klass
end
def self.default_scanner=(klass)
@default_scanner = klass
end
def self.make_scanner(src, trim_mode, percent)
klass = @scanner_map.fetch([trim_mode, percent], @default_scanner)
klass.new(src, trim_mode, percent)
end
def initialize(src, trim_mode, percent)
@src = src
@stag = nil
end
attr_accessor :stag
def scan; end
end
class TrimScanner < Scanner # :nodoc:
def initialize(src, trim_mode, percent)
super
@trim_mode = trim_mode
@percent = percent
if @trim_mode == '>'
@scan_line = self.method(:trim_line1)
elsif @trim_mode == '<>'
@scan_line = self.method(:trim_line2)
elsif @trim_mode == '-'
@scan_line = self.method(:explicit_trim_line)
else
@scan_line = self.method(:scan_line)
end
end
attr_accessor :stag
def scan(&block)
@stag = nil
if @percent
@src.each_line do |line|
percent_line(line, &block)
end
else
@scan_line.call(@src, &block)
end
nil
end
def percent_line(line, &block)
if @stag || line[0] != ?%
return @scan_line.call(line, &block)
end
line[0] = ''
if line[0] == ?%
@scan_line.call(line, &block)
else
yield(PercentLine.new(line.chomp))
end
end
def scan_line(line)
line.scan(/(.*?)(<%%|%%>|<%=|<%#|<%|%>|\n|\z)/m) do |tokens|
tokens.each do |token|
next if token.empty?
yield(token)
end
end
end
def trim_line1(line)
line.scan(/(.*?)(<%%|%%>|<%=|<%#|<%|%>\n|%>|\n|\z)/m) do |tokens|
tokens.each do |token|
next if token.empty?
if token == "%>\n"
yield('%>')
yield(:cr)
else
yield(token)
end
end
end
end
def trim_line2(line)
head = nil
line.scan(/(.*?)(<%%|%%>|<%=|<%#|<%|%>\n|%>|\n|\z)/m) do |tokens|
tokens.each do |token|
next if token.empty?
head = token unless head
if token == "%>\n"
yield('%>')
if is_erb_stag?(head)
yield(:cr)
else
yield("\n")
end
head = nil
else
yield(token)
head = nil if token == "\n"
end
end
end
end
def explicit_trim_line(line)
line.scan(/(.*?)(^[ \t]*<%\-|<%\-|<%%|%%>|<%=|<%#|<%|-%>\n|-%>|%>|\z)/m) do |tokens|
tokens.each do |token|
next if token.empty?
if @stag.nil? && /[ \t]*<%-/ =~ token
yield('<%')
elsif @stag && token == "-%>\n"
yield('%>')
yield(:cr)
elsif @stag && token == '-%>'
yield('%>')
else
yield(token)
end
end
end
end
ERB_STAG = %w(<%= <%# <%)
def is_erb_stag?(s)
ERB_STAG.member?(s)
end
end
Scanner.default_scanner = TrimScanner
class SimpleScanner < Scanner # :nodoc:
def scan
@src.scan(/(.*?)(<%%|%%>|<%=|<%#|<%|%>|\n|\z)/m) do |tokens|
tokens.each do |token|
next if token.empty?
yield(token)
end
end
end
end
Scanner.regist_scanner(SimpleScanner, nil, false)
begin
require 'strscan'
class SimpleScanner2 < Scanner # :nodoc:
def scan
stag_reg = /(.*?)(<%%|<%=|<%#|<%|\z)/m
etag_reg = /(.*?)(%%>|%>|\z)/m
scanner = StringScanner.new(@src)
while ! scanner.eos?
scanner.scan(@stag ? etag_reg : stag_reg)
yield(scanner[1])
yield(scanner[2])
end
end
end
Scanner.regist_scanner(SimpleScanner2, nil, false)
class ExplicitScanner < Scanner # :nodoc:
def scan
stag_reg = /(.*?)(^[ \t]*<%-|<%%|<%=|<%#|<%-|<%|\z)/m
etag_reg = /(.*?)(%%>|-%>|%>|\z)/m
scanner = StringScanner.new(@src)
while ! scanner.eos?
scanner.scan(@stag ? etag_reg : stag_reg)
yield(scanner[1])
elem = scanner[2]
if /[ \t]*<%-/ =~ elem
yield('<%')
elsif elem == '-%>'
yield('%>')
yield(:cr) if scanner.scan(/(\n|\z)/)
else
yield(elem)
end
end
end
end
Scanner.regist_scanner(ExplicitScanner, '-', false)
rescue LoadError
end
class Buffer # :nodoc:
def initialize(compiler, enc=nil)
@compiler = compiler
@line = []
@script = enc ? "#coding:#{enc.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) # :nodoc:
n = s.count("\n")
if n > 0
s.dump + "\n" * n
else
s.dump
end
end
def add_put_cmd(out, content)
out.push("#{@put_cmd} #{content_dump(content)}")
end
def add_insert_cmd(out, content)
out.push("#{@insert_cmd}((#{content}).to_s)")
end
# Compiles an ERB template into Ruby code. Returns an array of the code
# and encoding like ["code", Encoding].
def compile(s)
enc = s.encoding
raise ArgumentError, "#{enc} is not ASCII compatible" if enc.dummy?
s = s.b # see String#b
enc = detect_magic_comment(s) || enc
out = Buffer.new(self, enc)
content = ''
scanner = make_scanner(s)
scanner.scan do |token|
next if token.nil?
next if token == ''
if scanner.stag.nil?
case token
when PercentLine
add_put_cmd(out, content) if content.size > 0
content = ''
out.push(token.to_s)
out.cr
when :cr
out.cr
when '<%', '<%=', '<%#'
scanner.stag = token
add_put_cmd(out, content) if content.size > 0
content = ''
when "\n"
content << "\n"
add_put_cmd(out, content)
content = ''
when '<%%'
content << '<%'
else
content << token
end
else
case token
when '%>'
case scanner.stag
when '<%'
if content[-1] == ?\n
content.chop!
out.push(content)
out.cr
else
out.push(content)
end
when '<%='
add_insert_cmd(out, content)
when '<%#'
# out.push("# #{content_dump(content)}")
end
scanner.stag = nil
content = ''
when '%%>'
content << '%>'
else
content << token
end
end
end
add_put_cmd(out, content) if content.size > 0
out.close
return out.script, enc
end
def prepare_trim_mode(mode) # :nodoc:
case mode
when 1
return [false, '>']
when 2
return [false, '<>']
when 0
return [false, nil]
when String
perc = mode.include?('%')
if mode.include?('-')
return [perc, '-']
elsif mode.include?('<>')
return [perc, '<>']
elsif mode.include?('>')
return [perc, '>']
else
[perc, nil]
end
else
return [false, nil]
end
end
def make_scanner(src) # :nodoc:
Scanner.make_scanner(src, @trim_mode, @percent)
end
# Construct a new compiler using the trim_mode. See ERB::new for available
# trim modes.
def initialize(trim_mode)
@percent, @trim_mode = prepare_trim_mode(trim_mode)
@put_cmd = 'print'
@insert_cmd = @put_cmd
@pre_cmd = []
@post_cmd = []
end
attr_reader :percent, :trim_mode
# The command to handle text that ends with a newline
attr_accessor :put_cmd
# The command to handle text that is inserted prior to a newline
attr_accessor :insert_cmd
# An array of commands prepended to compiled code
attr_accessor :pre_cmd
# An array of commands appended to compiled code
attr_accessor :post_cmd
private
def detect_magic_comment(s)
if /\A<%#(.*)%>/ =~ s or (@percent and /\A%#(.*)/ =~ s)
comment = $1
comment = $1 if comment[/-\*-\s*(.*?)\s*-*-$/]
if %r"coding\s*[=:]\s*([[:alnum:]\-_]+)" =~ comment
enc = $1.sub(/-(?:mac|dos|unix)/i, '')
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 %>
# - omit blank lines ending in -%>
#
# _eoutvar_ can be used to set the name of the variable ERB will build up
# its output in. This is useful when you need to run multiple ERB
# templates through the same binding and/or when you want to control where
# output ends up. Pass the name of the variable to be used inside a String.
#
# === Example
#
# require "erb"
#
# # build data class
# class Listings
# PRODUCT = { :name => "Chicken Fried Steak",
# :desc => "A well messages pattie, breaded and fried.",
# :cost => 9.95 }
#
# attr_reader :product, :price
#
# def initialize( product = "", price = "" )
# @product = product
# @price = price
# end
#
# def build
# b = binding
# # create and run templates, filling member data variables
# ERB.new(<<-'END_PRODUCT'.gsub(/^\s+/, ""), 0, "", "@product").result b
# <%= PRODUCT[:name] %>
# <%= PRODUCT[:desc] %>
# END_PRODUCT
# ERB.new(<<-'END_PRICE'.gsub(/^\s+/, ""), 0, "", "@price").result b
# <%= PRODUCT[:name] %> -- <%= PRODUCT[:cost] %>
# <%= PRODUCT[:desc] %>
# END_PRICE
# end
# end
#
# # setup template data
# listings = Listings.new
# listings.build
#
# puts listings.product + "\n" + listings.price
#
# _Generates_
#
# Chicken Fried Steak
# A well messages pattie, breaded and fried.
#
# Chicken Fried Steak -- 9.95
# A well messages pattie, breaded and fried.
#
def initialize(str, safe_level=nil, trim_mode=nil, eoutvar='_erbout')
@safe_level = safe_level
compiler = make_compiler(trim_mode)
set_eoutvar(compiler, eoutvar)
@src, @enc = *compiler.compile(str)
@filename = nil
end
##
# Creates a new compiler for ERB. See ERB::Compiler.new for details
def make_compiler(trim_mode)
ERB::Compiler.new(trim_mode)
end
# The Ruby code generated by ERB
attr_reader :src
# The 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"
compiler.pre_cmd = ["#{eoutvar} = ''"]
compiler.post_cmd = ["#{eoutvar}.force_encoding(__ENCODING__)"]
end
# Generate results and print them. (see ERB#result)
def run(b=new_toplevel)
print self.result(b)
end
#
# Executes the generated ERB code to produce a completed template, returning
# the results of that code. (See ERB::new for details on how this process
# can be affected by _safe_level_.)
#
# _b_ accepts a Binding or Proc object which is used to set the context of
# code evaluation.
#
def result(b=new_toplevel)
if @safe_level
proc {
$SAFE = @safe_level
eval(@src, b, (@filename || '(erb)'), 0)
}.call
else
eval(@src, b, (@filename || '(erb)'), 0)
end
end
##
# Returns a new binding each time *near* TOPLEVEL_BINDING for runs that do
# not specify a binding.
def new_toplevel
TOPLEVEL_BINDING.dup
end
private :new_toplevel
# Define _methodname_ as instance method of _mod_ from compiled Ruby source.
#
# example:
# filename = 'example.rhtml' # 'arg1' and 'arg2' are used in example.rhtml
# erb = ERB.new(File.read(filename))
# erb.def_method(MyClass, 'render(arg1, arg2)', filename)
# print MyClass.new.render('foo', 123)
def def_method(mod, methodname, fname='(ERB)')
src = self.src
magic_comment = "#coding:#{@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)
CGI.escapeHTML(s.to_s)
end
alias h html_escape
module_function :h
module_function :html_escape
#
# A utility method for encoding the String _s_ as a URL.
#
# require "erb"
# include ERB::Util
#
# puts url_encode("Programming Ruby: The Pragmatic Programmer's Guide")
#
# _Generates_
#
# Programming%20Ruby%3A%20%20The%20Pragmatic%20Programmer%27s%20Guide
#
def url_encode(s)
s.to_s.b.gsub(/[^a-zA-Z0-9_\-.]/n) { |m|
sprintf("%%%02X", m.unpack("C")[0])
}
end
alias u url_encode
module_function :u
module_function :url_encode
end
end
#--
# ERB::DefMethod
class ERB
# Utility module to define eRuby script as instance method.
#
# === Example
#
# example.rhtml:
# <% for item in @items %>
# <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 | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/ubygems.rb | lib/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 | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/scanf.rb | lib/scanf.rb | # scanf for Ruby
#
#--
# $Release Version: 1.1.2 $
# $Revision: 44196 $
# $Id: scanf.rb 44196 2013-12-14 02:55:33Z nobu $
# $Author: nobu $
#++
#
# == Description
#
# scanf 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 scans an input string or stream according to a <b>format</b>, as
# described below in 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'
#
# # String#scanf and IO#scanf take a single argument, the format string
# array = a_string.scanf("%d%s")
# array = an_io.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.
#
# [%]
# 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,
#
# [a, e, f, g, A, E, F, G]
# 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.
#
# [[]
# 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).
#
# == 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(3) have to do with the type of upcoming pointer arguments, and are
# 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
# unsuccessful 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.)
#
# == 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.
#
# == 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
# merchantability and fitness for a particular purpose.
#
# == Credits and acknowledgements
#
# scanf 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.)
module Scanf
# :stopdoc:
# ==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.
class FormatSpecifier
attr_reader :re_string, :matched_string, :conversion, :matched
private
def skip; /^\s*%\*/.match(@spec_string); end
def extract_float(s)
return nil unless s &&! skip
if /\A(?<sign>[-+]?)0[xX](?<frac>\.\h+|\h+(?:\.\h*)?)[pP](?<exp>[-+]\d+)/ =~ s
f1, f2 = frac.split('.')
f = f1.hex
if f2
len = f2.length
if len > 0
f += f2.hex / (16.0 ** len)
end
end
(sign == ?- ? -1 : 1) * Math.ldexp(f, exp.to_i)
elsif /\A([-+]?\d+)\.([eE][-+]\d+)/ =~ s
($1 << $2).to_f
else
s.to_f
end
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 /%\*?[aefgAEFG]/
[ '([-+]?(?:0[xX](?:\.\h+|\h+(?:\.\h*)?)[pP][-+]\d+|\d+(?![\d.])|\d*\.\d*(?:[eE][-+]?\d+)?))', :extract_float ]
# %5f
when /%\*?(\d+)[aefgAEFG]/
[ '(?=[-+]?(?:0[xX](?:\.\h+|\h+(?:\.\h*)?)[pP][-+]\d+|\d+(?![\d.])|\d*\.\d*(?:[eE][-+]?\d+)?))' +
"(\\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 = 'diuXxofFeEgGscaA'
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
# :startdoc:
end
class IO
#:stopdoc:
# 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]
#
#:startdoc:
# Scans the current string until the match is exhausted,
# yielding each match as it is encountered in the string.
# A block is not necessary though, as the results will simply
# be aggregated into the final array.
#
# "123 456".block_scanf("%d")
# # => [123, 456]
#
# If a block is given, the value from that is returned from
# the yield is added to an output array.
#
# "123 456".block_scanf("%d) do |digit,| # the ',' unpacks the Array
# digit + 100
# end
# # => [223, 556]
#
# See Scanf for details on creating a format string.
#
# You will need to require 'scanf' to use use IO#scanf.
def scanf(str,&b) #:yield: current_match
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
begin
seek(start_position + matched_so_far, IO::SEEK_SET)
rescue Errno::ESPIPE
end
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
# :section: scanf
#
# You will need to require 'scanf' to use these methods
# Scans the current string. If a block is given, it
# functions exactly like block_scanf.
#
# arr = "123 456".scanf("%d%d")
# # => [123, 456]
#
# require 'pp'
#
# "this 123 read that 456 other".scanf("%s%d%s") {|m| pp m}
#
# # ["this", 123, "read"]
# # ["that", 456, "other"]
# # => [["this", 123, "read"], ["that", 456, "other"]]
#
# See Scanf for details on creating a format string.
#
# You will need to require 'scanf' to use String#scanf
def scanf(fstr,&b) #:yield: current_match
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
# Scans the current string until the match is exhausted
# yielding each match as it is encountered in the string.
# A block is not necessary as the results will simply
# be aggregated into the final array.
#
# "123 456".block_scanf("%d")
# # => [123, 456]
#
# If a block is given, the value from that is returned from
# the yield is added to an output array.
#
# "123 456".block_scanf("%d) do |digit,| # the ',' unpacks the Array
# digit + 100
# end
# # => [223, 556]
#
# See Scanf for details on creating a format string.
#
# You will need to require 'scanf' to use String#block_scanf
def block_scanf(fstr) #:yield: current_match
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
# Scans STDIN for data matching +format+. See IO#scanf for details.
#
# See Scanf for details on creating a format string.
#
# You will need to require 'scanf' to use Kernel#scanf.
def scanf(format, &b) #:doc:
STDIN.scanf(format ,&b)
end
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/tkmenubar.rb | lib/tkmenubar.rb | #
# tkmenubar.rb - load tk/menubar.rb
#
require 'tk/menubar'
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/tkmacpkg.rb | lib/tkmacpkg.rb | #
# tkmacpkg.rb - load tk/macpkg.rb
#
require 'tk/macpkg'
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/mutex_m.rb | lib/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
#
# --
require 'thread'
# = mutex_m.rb
#
# When 'mutex_m' is required, any object that extends or includes Mutex_m will
# be treated like a Mutex.
#
# Start by requiring the standard library Mutex_m:
#
# require "mutex_m.rb"
#
# From here you can extend an object with Mutex instance methods:
#
# obj = Object.new
# obj.extend Mutex_m
#
# Or mixin Mutex_m into your module to your class inherit Mutex instance
# methods.
#
# class Foo
# include Mutex_m
# # ...
# end
# obj = Foo.new
# # this obj can be handled like Mutex
#
module Mutex_m
def Mutex_m.define_aliases(cl) # :nodoc:
cl.module_eval %q{
alias locked? mu_locked?
alias lock mu_lock
alias unlock mu_unlock
alias try_lock mu_try_lock
alias synchronize mu_synchronize
}
end
def Mutex_m.append_features(cl) # :nodoc:
super
define_aliases(cl) unless cl.instance_of?(Module)
end
def Mutex_m.extend_object(obj) # :nodoc:
super
obj.mu_extended
end
def mu_extended # :nodoc:
unless (defined? locked? and
defined? lock and
defined? unlock and
defined? try_lock and
defined? synchronize)
Mutex_m.define_aliases(singleton_class)
end
mu_initialize
end
# See Mutex#synchronize
def mu_synchronize(&block)
@_mutex.synchronize(&block)
end
# See Mutex#locked?
def mu_locked?
@_mutex.locked?
end
# See Mutex#try_lock
def mu_try_lock
@_mutex.try_lock
end
# See Mutex#lock
def mu_lock
@_mutex.lock
end
# See Mutex#unlock
def mu_unlock
@_mutex.unlock
end
# See Mutex#sleep
def sleep(timeout = nil)
@_mutex.sleep(timeout)
end
private
def mu_initialize # :nodoc:
@_mutex = Mutex.new
end
def initialize(*args) # :nodoc:
mu_initialize
super
end
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/tcltk.rb | lib/tcltk.rb | # tof
#### tcltk library, more direct manipulation of tcl/tk
#### Sep. 5, 1997 Y. Shigehiro
require "tcltklib"
################
# module TclTk: collection of tcl/tk utilities (supplies namespace.)
module TclTk
# initialize Hash to hold unique symbols and such
@namecnt = {}
# initialize Hash to hold callbacks
@callback = {}
end
# TclTk.mainloop(): call TclTkLib.mainloop()
def TclTk.mainloop()
print("mainloop: start\n") if $DEBUG
TclTkLib.mainloop()
print("mainloop: end\n") if $DEBUG
end
# TclTk.deletecallbackkey(ca): remove callback from TclTk module
# this does not remove callbacks from tcl/tk interpreter
# without calling this method, TclTkInterpreter will not be GCed
# ca: callback(TclTkCallback)
def TclTk.deletecallbackkey(ca)
print("deletecallbackkey: ", ca.to_s(), "\n") if $DEBUG
@callback.delete(ca.to_s)
end
# TclTk.dcb(ca, wid, W): call TclTk.deletecallbackkey() for each callbacks
# in an array.
# this is for callback for top-level <Destroy>
# ca: array of callbacks(TclTkCallback)
# wid: top-level widget(TclTkWidget)
# w: information about window given by %W(String)
def TclTk.dcb(ca, wid, w)
if wid.to_s() == w
ca.each{|i|
TclTk.deletecallbackkey(i)
}
end
end
# TclTk._addcallback(ca): register callback
# ca: callback(TclTkCallback)
def TclTk._addcallback(ca)
print("_addcallback: ", ca.to_s(), "\n") if $DEBUG
@callback[ca.to_s()] = ca
end
# TclTk._callcallback(key, arg): invoke registered callback
# key: key to select callback (to_s value of the TclTkCallback)
# arg: parameter from tcl/tk interpreter
def TclTk._callcallback(key, arg)
print("_callcallback: ", @callback[key].inspect, "\n") if $DEBUG
@callback[key]._call(arg)
# throw out callback value
# should return String to satisfy rb_eval_string()
return ""
end
# TclTk._newname(prefix): generate unique name(String)
# prefix: prefix of the unique name
def TclTk._newname(prefix)
# generated name counter is stored in @namecnt
if !@namecnt.key?(prefix)
# first appearing prefix, initialize
@namecnt[prefix] = 1
else
# already appeared prefix, generate next name
@namecnt[prefix] += 1
end
return "#{prefix}#{@namecnt[prefix]}"
end
################
# class TclTkInterpreter: tcl/tk interpreter
class TclTkInterpreter
# initialize():
def initialize()
# generate interpreter object
@ip = TclTkIp.new()
# add ruby_fmt command to tcl interpreter
# ruby_fmt command format arguments by `format' and call `ruby' command
# (notice ruby command receives only one argument)
if $DEBUG
@ip._eval("proc ruby_fmt {fmt args} { puts \"ruby_fmt: $fmt $args\" ; set cmd [list ruby [format $fmt $args]] ; uplevel $cmd }")
else
@ip._eval("proc ruby_fmt {fmt args} { set cmd [list ruby [format $fmt $args]] ; uplevel $cmd }")
end
# @ip._get_eval_string(*args): generate string to evaluate in tcl interpreter
# *args: script which is going to be evaluated under tcl/tk
def @ip._get_eval_string(*args)
argstr = ""
args.each{|arg|
argstr += " " if argstr != ""
# call to_eval if it is defined
if (arg.respond_to?(:to_eval))
argstr += arg.to_eval()
else
# call to_s unless defined
argstr += arg.to_s()
end
}
return argstr
end
# @ip._eval_args(*args): evaluate string under tcl/tk interpreter
# returns result string.
# *args: script which is going to be evaluated under tcl/tk
def @ip._eval_args(*args)
# calculate the string to eval in the interpreter
argstr = _get_eval_string(*args)
# evaluate under the interpreter
print("_eval: \"", argstr, "\"") if $DEBUG
res = _eval(argstr)
if $DEBUG
print(" -> \"", res, "\"\n")
elsif _return_value() != 0
print(res, "\n")
end
fail(%Q/can't eval "#{argstr}"/) if _return_value() != 0 #'
return res
end
# generate tcl/tk command object and register in the hash
@commands = {}
# for all commands registered in tcl/tk interpreter:
@ip._eval("info command").split(/ /).each{|comname|
if comname =~ /^[.]/
# if command is a widget (path), generate TclTkWidget,
# and register it in the hash
@commands[comname] = TclTkWidget.new(@ip, comname)
else
# otherwise, generate TclTkCommand
@commands[comname] = TclTkCommand.new(@ip, comname)
end
}
end
# commands(): returns hash of the tcl/tk commands
def commands()
return @commands
end
# rootwidget(): returns root widget(TclTkWidget)
def rootwidget()
return @commands["."]
end
# _tcltkip(): returns @ip(TclTkIp)
def _tcltkip()
return @ip
end
# method_missing(id, *args): execute undefined method as tcl/tk command
# id: method symbol
# *args: method arguments
def method_missing(id, *args)
# if command named by id registered, then execute it
if @commands.key?(id.id2name)
return @commands[id.id2name].e(*args)
else
# otherwise, exception
super
end
end
end
# class TclTkObject: base class of the tcl/tk objects
class TclTkObject
# initialize(ip, exp):
# ip: interpreter(TclTkIp)
# exp: tcl/tk representation
def initialize(ip, exp)
fail("type is not TclTkIp") if !ip.kind_of?(TclTkIp)
@ip = ip
@exp = exp
end
# to_s(): returns tcl/tk representation
def to_s()
return @exp
end
end
# class TclTkCommand: tcl/tk commands
# you should not call TclTkCommand.new()
# commands are created by TclTkInterpreter:initialize()
class TclTkCommand < TclTkObject
# e(*args): execute command. returns String (e is for exec or eval)
# *args: command arguments
def e(*args)
return @ip._eval_args(to_s(), *args)
end
end
# class TclTkLibCommand: tcl/tk commands in the library
class TclTkLibCommand < TclTkCommand
# initialize(ip, name):
# ip: interpreter(TclTkInterpreter)
# name: command name (String)
def initialize(ip, name)
super(ip._tcltkip, name)
end
end
# class TclTkVariable: tcl/tk variable
class TclTkVariable < TclTkObject
# initialize(interp, dat):
# interp: interpreter(TclTkInterpreter)
# dat: the value to set(String)
# if nil, not initialize variable
def initialize(interp, dat)
# auto-generate tcl/tk representation (variable name)
exp = TclTk._newname("v_")
# initialize TclTkObject
super(interp._tcltkip(), exp)
# safe this for `set' command
@set = interp.commands()["set"]
# set value
set(dat) if dat
end
# although you can set/read variables by using set in tcl/tk,
# we provide the method for accessing variables
# set(data): set tcl/tk variable using `set'
# data: new value
def set(data)
@set.e(to_s(), data.to_s())
end
# get(): read tcl/tk variable(String) using `set'
def get()
return @set.e(to_s())
end
end
# class TclTkWidget: tcl/tk widget
class TclTkWidget < TclTkCommand
# initialize(*args):
# *args: parameters
def initialize(*args)
if args[0].kind_of?(TclTkIp)
# in case the 1st argument is TclTkIp:
# Wrap tcl/tk widget by TclTkWidget
# (used in TclTkInterpreter#initialize())
# need two arguments
fail("invalid # of parameter") if args.size != 2
# ip: interpreter(TclTkIp)
# exp: tcl/tk representation
ip, exp = args
# initialize TclTkObject
super(ip, exp)
elsif args[0].kind_of?(TclTkInterpreter)
# in case 1st parameter is TclTkInterpreter:
# generate new widget from parent widget
# interp: interpreter(TclTkInterpreter)
# parent: parent widget
# command: widget generating tk command(label 等)
# *args: argument to the command
interp, parent, command, *args = args
# generate widget name
exp = parent.to_s()
exp += "." if exp !~ /[.]$/
exp += TclTk._newname("w_")
# initialize TclTkObject
super(interp._tcltkip(), exp)
# generate widget
res = @ip._eval_args(command, exp, *args)
# fail("can't create Widget") if res != exp
# for tk_optionMenu, it is legal res != exp
else
fail("first parameter is not TclTkInterpreter")
end
end
end
# class TclTkCallback: tcl/tk callbacks
class TclTkCallback < TclTkObject
# initialize(interp, pr, arg):
# interp: interpreter(TclTkInterpreter)
# pr: callback procedure(Proc)
# arg: string to pass as block parameters of pr
# bind command of tcl/tk uses % replacement for parameters
# pr can receive replaced data using block parameter
# its format is specified by arg string
# You should not specify arg for the command like
# scrollbar with -command option, which receives parameters
# without specifying any replacement
def initialize(interp, pr, arg = nil)
# auto-generate tcl/tk representation (variable name)
exp = TclTk._newname("c_")
# initialize TclTkObject
super(interp._tcltkip(), exp)
# save parameters
@pr = pr
@arg = arg
# register in the module
TclTk._addcallback(self)
end
# to_eval(): retuens string representation for @ip._eval_args
def to_eval()
if @arg
# bind replaces %s before calling ruby_fmt, so %%s is used
s = %Q/{ruby_fmt {TclTk._callcallback("#{to_s()}", "%%s")} #{@arg}}/
else
s = %Q/{ruby_fmt {TclTk._callcallback("#{to_s()}", "%s")}}/
end
return s
end
# _call(arg): invoke callback
# arg: callback parameter
def _call(arg)
@pr.call(arg)
end
end
# class TclTkImage: tcl/tk images
class TclTkImage < TclTkCommand
# initialize(interp, t, *args):
# generating image is done by TclTkImage.new()
# destrying is done by image delete (inconsistent, sigh)
# interp: interpreter(TclTkInterpreter)
# t: image type (photo, bitmap, etc.)
# *args: command argument
def initialize(interp, t, *args)
# auto-generate tcl/tk representation
exp = TclTk._newname("i_")
# initialize TclTkObject
super(interp._tcltkip(), exp)
# generate image
res = @ip._eval_args("image create", t, exp, *args)
fail("can't create Image") if res != exp
end
end
# eof
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/cgi.rb | lib/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)
#
raise "Please, use ruby 1.9.0 or later." if RUBY_VERSION < "1.9.0"
# == 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.
#
# The file CGI::Session provides session management functionality; see that
# class for more details.
#
# See http://www.w3.org/CGI/ for more information on 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 #http_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.
#
# === Utility HTML escape and other methods like a function.
#
# There are some utility tool defined in cgi/util.rb .
# And when include, you can use utility methods like a function.
#
# == 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("html4") # add HTML generation methods
# cgi.out do
# cgi.html do
# cgi.head do
# cgi.title { "TITLE" }
# end +
# cgi.body do
# cgi.form("ACTION" => "uri") do
# cgi.p do
# cgi.textarea("get_text") +
# cgi.br +
# cgi.submit
# end
# 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
# CGI.new("html5") # html5
#
# === Some utility methods
#
# require 'cgi/util'
# CGI.escapeHTML('Usage: foo "bar" <baz>')
#
#
# === Some utility methods like a function
#
# require 'cgi/util'
# include CGI::Util
# escapeHTML('Usage: foo "bar" <baz>')
# h('Usage: foo "bar" <baz>') # alias
#
#
class CGI
end
require 'cgi/core'
require 'cgi/cookie'
require 'cgi/util'
CGI.autoload(:HtmlExtension, 'cgi/html')
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/tmpdir.rb | lib/tmpdir.rb | #
# tmpdir - retrieve temporary directory path
#
# $Id: tmpdir.rb 40825 2013-05-19 03:10:21Z ktsj $
#
require 'fileutils'
begin
require 'etc.so'
rescue LoadError
end
class Dir
@@systmpdir ||= defined?(Etc.systmpdir) ? Etc.systmpdir : '/tmp'
##
# Returns the operating system's temporary file path.
def Dir::tmpdir
if $SAFE > 0
tmp = @@systmpdir
else
tmp = nil
for dir in [ENV['TMPDIR'], ENV['TMP'], ENV['TEMP'], @@systmpdir, '/tmp', '.']
next if !dir
dir = File.expand_path(dir)
if stat = File.stat(dir) and stat.directory? and stat.writable? and
(!stat.world_writable? or stat.sticky?)
tmp = dir
break
end rescue nil
end
raise ArgumentError, "could not find a temporary directory" if !tmp
tmp
end
end
# Dir.mktmpdir creates a temporary directory.
#
# The directory is created with 0700 permission.
# Application should not change the permission to make the temporary directory accessible from other users.
#
# 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 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 dir
# end
#
def Dir.mktmpdir(prefix_suffix=nil, *rest)
path = Tmpname.create(prefix_suffix || "d", *rest) {|n| mkdir(n, 0700)}
if block_given?
begin
yield path
ensure
stat = File.stat(File.dirname(path))
if stat.world_writable? and !stat.sticky?
raise ArgumentError, "parent directory is world writable but not sticky"
end
FileUtils.remove_entry path
end
else
path
end
end
module Tmpname # :nodoc:
module_function
def tmpdir
Dir.tmpdir
end
def make_tmpname(prefix_suffix, n)
case prefix_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
t = Time.now.strftime("%Y%m%d")
path = "#{prefix}#{t}-#{$$}-#{rand(0x100000000).to_s(36)}"
path << "-#{n}" if n
path << suffix
end
def create(basename, *rest)
if opts = Hash.try_convert(rest[-1])
opts = opts.dup if rest.pop.equal?(opts)
max_try = opts.delete(:max_try)
opts = [opts]
else
opts = []
end
tmpdir, = *rest
if $SAFE > 0 and tmpdir.tainted?
tmpdir = '/tmp'
else
tmpdir ||= tmpdir()
end
n = nil
begin
path = File.join(tmpdir, make_tmpname(basename, n))
yield(path, n, *opts)
rescue Errno::EEXIST
n ||= 0
n += 1
retry if !max_try or n < max_try
raise "cannot generate temporary name using `#{basename}' under `#{tmpdir}'"
end
path
end
end
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/rational.rb | lib/rational.rb | # :enddoc:
warn('lib/rational.rb is deprecated') if $VERBOSE
class Fixnum
alias quof fdiv
alias rdiv quo
alias power! ** unless method_defined? :power!
alias rpower **
end
class Bignum
alias quof fdiv
alias rdiv quo
alias power! ** unless method_defined? :power!
alias rpower **
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/ipaddr.rb | lib/ipaddr.rb | #
# ipaddr.rb - A class to manipulate an IP address
#
# Copyright (c) 2002 Hajimu UMEMOTO <ume@mahoroba.org>.
# Copyright (c) 2007, 2009, 2012 Akinori MUSHA <knu@iDaemons.org>.
# All rights reserved.
#
# You can redistribute and/or modify it under the same terms as Ruby.
#
# $Id: ipaddr.rb 39300 2013-02-18 07:31:17Z knu $
#
# Contact:
# - Akinori MUSHA <knu@iDaemons.org> (current maintainer)
#
# TODO:
# - scope_id support
#
require 'socket'
# IPAddr provides a set of methods to manipulate an IP address. Both IPv4 and
# IPv6 are supported.
#
# == Example
#
# require 'ipaddr'
#
# ipaddr1 = IPAddr.new "3ffe:505:2::1"
#
# p ipaddr1 #=> #<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
# 32 bit mask for IPv4
IN4MASK = 0xffffffff
# 128 bit mask for IPv4
IN6MASK = 0xffffffffffffffffffffffffffffffff
# Format string for IPv6
IN6FORMAT = (["%.4x"] * 8).join(':')
# Regexp _internally_ used for parsing IPv4 address.
RE_IPV4ADDRLIKE = %r{
\A
(\d+) \. (\d+) \. (\d+) \. (\d+)
\z
}x
# Regexp _internally_ used for parsing IPv6 address.
RE_IPV6ADDRLIKE_FULL = %r{
\A
(?:
(?: [\da-f]{1,4} : ){7} [\da-f]{1,4}
|
( (?: [\da-f]{1,4} : ){6} )
(\d+) \. (\d+) \. (\d+) \. (\d+)
)
\z
}xi
# Regexp _internally_ used for parsing IPv6 address.
RE_IPV6ADDRLIKE_COMPRESSED = %r{
\A
( (?: (?: [\da-f]{1,4} : )* [\da-f]{1,4} )? )
::
( (?:
( (?: [\da-f]{1,4} : )* )
(?:
[\da-f]{1,4}
|
(\d+) \. (\d+) \. (\d+) \. (\d+)
)
)? )
\z
}xi
# Generic IPAddr related error. Exceptions raised in this class should
# inherit from Error.
class Error < ArgumentError; end
# Raised when the provided IP address is an invalid address.
class InvalidAddressError < Error; end
# Raised when the address family is invalid such as an address with an
# unsupported family, an address with an inconsistent family, or an address
# who's family cannot be determined.
class AddressFamilyError < Error; end
# Raised when the address is an invalid length.
class InvalidPrefixError < InvalidAddressError; end
# Returns the address family of this IP address.
attr_reader :family
# Creates a new ipaddr containing the given network byte ordered
# string form of an IP address.
def IPAddr::new_ntoh(addr)
return IPAddr.new(IPAddr::ntop(addr))
end
# Convert a network byte ordered string form of an IP address into
# human readable form.
def IPAddr::ntop(addr)
case addr.size
when 4
s = addr.unpack('C4').join('.')
when 16
s = IN6FORMAT % addr.unpack('n8')
else
raise AddressFamilyError, "unsupported address family"
end
return s
end
# Returns a new ipaddr built by bitwise AND.
def &(other)
return self.clone.set(@addr & coerce_other(other).to_i)
end
# Returns a new ipaddr built by bitwise OR.
def |(other)
return self.clone.set(@addr | coerce_other(other).to_i)
end
# Returns a new ipaddr built by bitwise right-shift.
def >>(num)
return self.clone.set(@addr >> num)
end
# Returns a new ipaddr built by bitwise left shift.
def <<(num)
return self.clone.set(addr_mask(@addr << num))
end
# Returns a new ipaddr built by bitwise negation.
def ~
return self.clone.set(addr_mask(~@addr))
end
# Returns true if two ipaddrs are equal.
def ==(other)
other = coerce_other(other)
return @family == other.family && @addr == other.to_i
end
# Returns a new ipaddr built by masking IP address with the given
# prefixlen/netmask. (e.g. 8, 64, "255.255.255.0", etc.)
def mask(prefixlen)
return self.clone.mask!(prefixlen)
end
# Returns true if the given ipaddr is in the range.
#
# e.g.:
# require 'ipaddr'
# net1 = IPAddr.new("192.168.2.0/24")
# net2 = IPAddr.new("192.168.2.100")
# net3 = IPAddr.new("192.168.3.0")
# p net1.include?(net2) #=> true
# p net1.include?(net3) #=> false
def include?(other)
other = coerce_other(other)
if ipv4_mapped?
if (@mask_addr >> 32) != 0xffffffffffffffffffffffff
return false
end
mask_addr = (@mask_addr & IN4MASK)
addr = (@addr & IN4MASK)
family = Socket::AF_INET
else
mask_addr = @mask_addr
addr = @addr
family = @family
end
if other.ipv4_mapped?
other_addr = (other.to_i & IN4MASK)
other_family = Socket::AF_INET
else
other_addr = other.to_i
other_family = other.family
end
if family != other_family
return false
end
return ((addr & mask_addr) == (other_addr & mask_addr))
end
alias === include?
# Returns the integer representation of the ipaddr.
def to_i
return @addr
end
# Returns a string containing the IP address representation.
def to_s
str = to_string
return str if ipv4?
str.gsub!(/\b0{1,3}([\da-f]+)\b/i, '\1')
loop do
break if str.sub!(/\A0:0:0:0:0:0:0:0\z/, '::')
break if str.sub!(/\b0:0:0:0:0:0:0\b/, ':')
break if str.sub!(/\b0:0:0:0:0:0\b/, ':')
break if str.sub!(/\b0:0:0:0:0\b/, ':')
break if str.sub!(/\b0:0:0:0\b/, ':')
break if str.sub!(/\b0:0:0\b/, ':')
break if str.sub!(/\b0:0\b/, ':')
break
end
str.sub!(/:{3,}/, '::')
if /\A::(ffff:)?([\da-f]{1,4}):([\da-f]{1,4})\z/i =~ str
str = sprintf('::%s%d.%d.%d.%d', $1, $2.hex / 256, $2.hex % 256, $3.hex / 256, $3.hex % 256)
end
str
end
# Returns a string containing the IP address representation in
# canonical form.
def to_string
return _to_string(@addr)
end
# Returns a network byte ordered string form of the IP address.
def hton
case @family
when Socket::AF_INET
return [@addr].pack('N')
when Socket::AF_INET6
return (0..7).map { |i|
(@addr >> (112 - 16 * i)) & 0xffff
}.pack('n8')
else
raise AddressFamilyError, "unsupported address family"
end
end
# Returns true if the ipaddr is an IPv4 address.
def ipv4?
return @family == Socket::AF_INET
end
# Returns true if the ipaddr is an IPv6 address.
def ipv6?
return @family == Socket::AF_INET6
end
# Returns true if the ipaddr is an IPv4-mapped IPv6 address.
def ipv4_mapped?
return ipv6? && (@addr >> 32) == 0xffff
end
# Returns true if the ipaddr is an IPv4-compatible IPv6 address.
def ipv4_compat?
if !ipv6? || (@addr >> 32) != 0
return false
end
a = (@addr & IN4MASK)
return a != 0 && a != 1
end
# Returns a new ipaddr built by converting the native IPv4 address
# into an IPv4-mapped IPv6 address.
def ipv4_mapped
if !ipv4?
raise InvalidAddressError, "not an IPv4 address"
end
return self.clone.set(@addr | 0xffff00000000, Socket::AF_INET6)
end
# Returns a new ipaddr built by converting the native IPv4 address
# into an IPv4-compatible IPv6 address.
def ipv4_compat
if !ipv4?
raise InvalidAddressError, "not an IPv4 address"
end
return self.clone.set(@addr, Socket::AF_INET6)
end
# Returns a new ipaddr built by converting the IPv6 address into a
# native IPv4 address. If the IP address is not an IPv4-mapped or
# IPv4-compatible IPv6 address, returns self.
def native
if !ipv4_mapped? && !ipv4_compat?
return self
end
return self.clone.set(@addr & IN4MASK, Socket::AF_INET)
end
# Returns a string for DNS reverse lookup. It returns a string in
# RFC3172 form for an IPv6 address.
def reverse
case @family
when Socket::AF_INET
return _reverse + ".in-addr.arpa"
when Socket::AF_INET6
return ip6_arpa
else
raise AddressFamilyError, "unsupported address family"
end
end
# Returns a string for DNS reverse lookup compatible with RFC3172.
def ip6_arpa
if !ipv6?
raise InvalidAddressError, "not an IPv6 address"
end
return _reverse + ".ip6.arpa"
end
# Returns a string for DNS reverse lookup compatible with RFC1886.
def ip6_int
if !ipv6?
raise InvalidAddressError, "not an IPv6 address"
end
return _reverse + ".ip6.int"
end
# Returns the successor to the ipaddr.
def succ
return self.clone.set(@addr + 1, @family)
end
# Compares the ipaddr with another.
def <=>(other)
other = coerce_other(other)
return nil if other.family != @family
return @addr <=> other.to_i
end
include Comparable
# Checks equality used by Hash.
def eql?(other)
return self.class == other.class && self.hash == other.hash && self == other
end
# Returns a hash value used by Hash, Set, and Array classes
def hash
return ([@addr, @mask_addr].hash << 1) | (ipv4? ? 0 : 1)
end
# Creates a Range object for the network address.
def to_range
begin_addr = (@addr & @mask_addr)
case @family
when Socket::AF_INET
end_addr = (@addr | (IN4MASK ^ @mask_addr))
when Socket::AF_INET6
end_addr = (@addr | (IN6MASK ^ @mask_addr))
else
raise AddressFamilyError, "unsupported address family"
end
return clone.set(begin_addr, @family)..clone.set(end_addr, @family)
end
# Returns a string containing a human-readable representation of the
# ipaddr. ("#<IPAddr: family:address/mask>")
def inspect
case @family
when Socket::AF_INET
af = "IPv4"
when Socket::AF_INET6
af = "IPv6"
else
raise AddressFamilyError, "unsupported address family"
end
return sprintf("#<%s: %s:%s/%s>", self.class.name,
af, _to_string(@addr), _to_string(@mask_addr))
end
protected
# Set +@addr+, the internal stored ip address, to given +addr+. The
# parameter +addr+ is validated using the first +family+ member,
# which is +Socket::AF_INET+ or +Socket::AF_INET6+.
def set(addr, *family)
case family[0] ? family[0] : @family
when Socket::AF_INET
if addr < 0 || addr > IN4MASK
raise InvalidAddressError, "invalid address"
end
when Socket::AF_INET6
if addr < 0 || addr > IN6MASK
raise InvalidAddressError, "invalid address"
end
else
raise AddressFamilyError, "unsupported address family"
end
@addr = addr
if family[0]
@family = family[0]
end
return self
end
# Set current netmask to given mask.
def mask!(mask)
if mask.kind_of?(String)
if mask =~ /^\d+$/
prefixlen = mask.to_i
else
m = IPAddr.new(mask)
if m.family != @family
raise InvalidPrefixError, "address family is not same"
end
@mask_addr = m.to_i
@addr &= @mask_addr
return self
end
else
prefixlen = mask
end
case @family
when Socket::AF_INET
if prefixlen < 0 || prefixlen > 32
raise InvalidPrefixError, "invalid length"
end
masklen = 32 - prefixlen
@mask_addr = ((IN4MASK >> masklen) << masklen)
when Socket::AF_INET6
if prefixlen < 0 || prefixlen > 128
raise InvalidPrefixError, "invalid length"
end
masklen = 128 - prefixlen
@mask_addr = ((IN6MASK >> masklen) << masklen)
else
raise AddressFamilyError, "unsupported address family"
end
@addr = ((@addr >> masklen) << masklen)
return self
end
private
# Creates a new ipaddr object either from a human readable IP
# address representation in string, or from a packed in_addr value
# followed by an address family.
#
# In the former case, the following are the valid formats that will
# be recognized: "address", "address/prefixlen" and "address/mask",
# where IPv6 address may be enclosed in square brackets (`[' and
# `]'). If a prefixlen or a mask is specified, it returns a masked
# IP address. Although the address family is determined
# automatically from a specified string, you can specify one
# explicitly by the optional second argument.
#
# Otherwise an IP address is generated from a packed in_addr value
# and an address family.
#
# The IPAddr class defines many methods and operators, and some of
# those, such as &, |, include? and ==, accept a string, or a packed
# in_addr value instead of an IPAddr object.
def initialize(addr = '::', family = Socket::AF_UNSPEC)
if !addr.kind_of?(String)
case family
when Socket::AF_INET, Socket::AF_INET6
set(addr.to_i, family)
@mask_addr = (family == Socket::AF_INET) ? IN4MASK : IN6MASK
return
when Socket::AF_UNSPEC
raise AddressFamilyError, "address family must be specified"
else
raise AddressFamilyError, "unsupported address family: #{family}"
end
end
prefix, prefixlen = addr.split('/')
if prefix =~ /^\[(.*)\]$/i
prefix = $1
family = Socket::AF_INET6
end
# It seems AI_NUMERICHOST doesn't do the job.
#Socket.getaddrinfo(left, nil, Socket::AF_INET6, Socket::SOCK_STREAM, nil,
# Socket::AI_NUMERICHOST)
@addr = @family = nil
if family == Socket::AF_UNSPEC || family == Socket::AF_INET
@addr = in_addr(prefix)
if @addr
@family = Socket::AF_INET
end
end
if !@addr && (family == Socket::AF_UNSPEC || family == Socket::AF_INET6)
@addr = in6_addr(prefix)
@family = Socket::AF_INET6
end
if family != Socket::AF_UNSPEC && @family != family
raise AddressFamilyError, "address family mismatch"
end
if prefixlen
mask!(prefixlen)
else
@mask_addr = (@family == Socket::AF_INET) ? IN4MASK : IN6MASK
end
end
def coerce_other(other)
case other
when IPAddr
other
when String
self.class.new(other)
else
self.class.new(other, @family)
end
end
def in_addr(addr)
case addr
when Array
octets = addr
else
m = RE_IPV4ADDRLIKE.match(addr) or return nil
octets = m.captures
end
octets.inject(0) { |i, s|
(n = s.to_i) < 256 or raise InvalidAddressError, "invalid address"
s.match(/\A0./) and raise InvalidAddressError, "zero-filled number in IPv4 address is ambiguous"
i << 8 | n
}
end
def in6_addr(left)
case left
when RE_IPV6ADDRLIKE_FULL
if $2
addr = in_addr($~[2,4])
left = $1 + ':'
else
addr = 0
end
right = ''
when RE_IPV6ADDRLIKE_COMPRESSED
if $4
left.count(':') <= 6 or raise InvalidAddressError, "invalid address"
addr = in_addr($~[4,4])
left = $1
right = $3 + '0:0'
else
left.count(':') <= ($1.empty? || $2.empty? ? 8 : 7) or
raise InvalidAddressError, "invalid address"
left = $1
right = $2
addr = 0
end
else
raise InvalidAddressError, "invalid address"
end
l = left.split(':')
r = right.split(':')
rest = 8 - l.size - r.size
if rest < 0
return nil
end
(l + Array.new(rest, '0') + r).inject(0) { |i, s|
i << 16 | s.hex
} | addr
end
def addr_mask(addr)
case @family
when Socket::AF_INET
return addr & IN4MASK
when Socket::AF_INET6
return addr & IN6MASK
else
raise AddressFamilyError, "unsupported address family"
end
end
def _reverse
case @family
when Socket::AF_INET
return (0..3).map { |i|
(@addr >> (8 * i)) & 0xff
}.join('.')
when Socket::AF_INET6
return ("%.32x" % @addr).reverse!.gsub!(/.(?!$)/, '\&.')
else
raise AddressFamilyError, "unsupported address family"
end
end
def _to_string(addr)
case @family
when Socket::AF_INET
return (0..3).map { |i|
(addr >> (24 - 8 * i)) & 0xff
}.join('.')
when Socket::AF_INET6
return (("%.32x" % addr).gsub!(/.{4}(?!$)/, '\&:'))
else
raise AddressFamilyError, "unsupported address family"
end
end
end
unless Socket.const_defined? :AF_INET6
class Socket < BasicSocket
# IPv6 protocol family
AF_INET6 = Object.new
end
class << IPSocket
private
def valid_v6?(addr)
case addr
when IPAddr::RE_IPV6ADDRLIKE_FULL
if $2
$~[2,4].all? {|i| i.to_i < 256 }
else
true
end
when IPAddr::RE_IPV6ADDRLIKE_COMPRESSED
if $4
addr.count(':') <= 6 && $~[4,4].all? {|i| i.to_i < 256}
else
addr.count(':') <= 7
end
else
false
end
end
alias getaddress_orig getaddress
public
# Returns a +String+ based representation of a valid DNS hostname,
# IPv4 or IPv6 address.
#
# IPSocket.getaddress 'localhost' #=> "::1"
# IPSocket.getaddress 'broadcasthost' #=> "255.255.255.255"
# IPSocket.getaddress 'www.ruby-lang.org' #=> "221.186.184.68"
# IPSocket.getaddress 'www.ccc.de' #=> "2a00:1328:e102:ccc0::122"
def getaddress(s)
if valid_v6?(s)
s
else
getaddress_orig(s)
end
end
end
end
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
[
["3FFE:505:ffff::/48"],
["0:0:0:1::"],
["2001:200:300::/48"],
["2001:200:300::192.168.1.2/48"],
["1:2:3:4:5:6:7::"],
["::2:3:4:5:6:7:8"],
].each { |args|
assert_nothing_raised {
IPAddr.new(*args)
}
}
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)
assert_equal("1:2:3:4:5:6:7:0", IPAddr.new("1:2:3:4:5:6:7::").to_s)
assert_equal("0:2:3:4:5:6:7:8", IPAddr.new("::2:3:4:5:6:7:8").to_s)
assert_raises(IPAddr::InvalidAddressError) { IPAddr.new("192.168.0.256") }
assert_raises(IPAddr::InvalidAddressError) { IPAddr.new("192.168.0.011") }
assert_raises(IPAddr::InvalidAddressError) { IPAddr.new("fe80::1%fxp0") }
assert_raises(IPAddr::InvalidAddressError) { IPAddr.new("[192.168.1.2]/120") }
assert_raises(IPAddr::InvalidPrefixError) { IPAddr.new("::1/255.255.255.0") }
assert_raises(IPAddr::InvalidPrefixError) { IPAddr.new("::1/129") }
assert_raises(IPAddr::InvalidPrefixError) { IPAddr.new("192.168.0.1/33") }
assert_raises(IPAddr::AddressFamilyError) { IPAddr.new(1) }
assert_raises(IPAddr::AddressFamilyError) { IPAddr.new("::ffff:192.168.1.2/120", Socket::AF_INET) }
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(IPAddr::InvalidAddressError) {
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(IPAddr::InvalidAddressError) {
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(true, @a == IPAddr.new("3ffe:0505:0002::"))
assert_equal(true, @a == IPAddr.new("3ffe:0505:0002:0:0:0:0:0"))
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 | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/rake.rb | lib/rake.rb | #--
# Copyright 2003-2010 by Jim Weirich (jim.weirich@gmail.com)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#++
require 'rake/version'
# :stopdoc:
RAKEVERSION = Rake::VERSION
# :startdoc:
require 'rbconfig'
require 'fileutils'
require 'singleton'
require 'monitor'
require 'optparse'
require 'ostruct'
require 'rake/ext/module'
require 'rake/ext/string'
require 'rake/ext/time'
require 'rake/win32'
require 'rake/linked_list'
require 'rake/scope'
require 'rake/task_argument_error'
require 'rake/rule_recursion_overflow_error'
require 'rake/rake_module'
require 'rake/trace_output'
require 'rake/pseudo_status'
require 'rake/task_arguments'
require 'rake/invocation_chain'
require 'rake/task'
require 'rake/file_task'
require 'rake/file_creation_task'
require 'rake/multi_task'
require 'rake/dsl_definition'
require 'rake/file_utils_ext'
require 'rake/file_list'
require 'rake/default_loader'
require 'rake/early_time'
require 'rake/name_space'
require 'rake/task_manager'
require 'rake/application'
require 'rake/backtrace'
$trace = false
# :stopdoc:
#
# Some top level Constants.
FileList = Rake::FileList
RakeFileUtils = Rake::FileUtilsExt
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/tkfont.rb | lib/tkfont.rb | #
# tkfont.rb - load tk/font.rb
#
require 'tk/font'
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/delegate.rb | lib/delegate.rb | # = delegate -- Support for the Delegation Pattern
#
# Documentation by James Edward Gray II and Gavin Sinclair
##
# 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 which is also in
# the standard library. It may suit your needs better.)
#
# SimpleDelegator's implementation serves as a nice example if the use of
# Delegator:
#
# 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
#
# == Notes
#
# Be advised, RDoc will not detect delegated methods.
#
class Delegator < BasicObject
kernel = ::Kernel.dup
kernel.class_eval do
alias __raise__ raise
[:to_s,:inspect,:=~,:!~,:===,:<=>,:eql?,:hash].each do |m|
undef_method m
end
private_instance_methods.each do |m|
if /\Ablock_given\?\z|iterator\?\z|\A__.*__\z/ =~ m
next
end
undef_method m
end
end
include kernel
# :stopdoc:
def self.const_missing(n)
::Object.const_get(n)
end
# :startdoc:
#
# 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)
r = true
target = self.__getobj__ {r = false}
begin
if r && target.respond_to?(m)
target.__send__(m, *args, &block)
elsif ::Kernel.respond_to?(m, true)
::Kernel.instance_method(m).bind(self).(*args, &block)
else
super(m, *args, &block)
end
ensure
$@.delete_if {|t| %r"\A#{Regexp.quote(__FILE__)}:(?:#{[__LINE__-7, __LINE__-5, __LINE__-3].join('|')}):"o =~ t} if $@
end
end
#
# Checks for a method provided by this the delegate object by forwarding the
# call through \_\_getobj\_\_.
#
def respond_to_missing?(m, include_private)
r = true
target = self.__getobj__ {r = false}
r &&= target.respond_to?(m, include_private)
if r && include_private && !target.respond_to?(m, false)
warn "#{caller(3)[0]}: delegator does not forward private method \##{m}"
return false
end
r
end
#
# Returns the methods available to this delegate object as the union
# of this object's and \_\_getobj\_\_ methods.
#
def methods(all=true)
__getobj__.methods(all) | super
end
#
# Returns the methods available to this delegate object as the union
# of this object's and \_\_getobj\_\_ public methods.
#
def public_methods(all=true)
__getobj__.public_methods(all) | super
end
#
# Returns the methods available to this delegate object as the union
# of this object's and \_\_getobj\_\_ protected methods.
#
def protected_methods(all=true)
__getobj__.protected_methods(all) | super
end
# Note: no need to specialize private_methods, since they are not forwarded
#
# Returns true if two objects are considered of equal value.
#
def ==(obj)
return true if obj.equal?(self)
self.__getobj__ == obj
end
#
# Returns true if two objects are not considered of equal value.
#
def !=(obj)
return false if obj.equal?(self)
__getobj__ != obj
end
#
# Delegates ! to the \_\_getobj\_\_
#
def !
!__getobj__
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
ivars = instance_variables.reject {|var| /\A@delegate_/ =~ var}
[
:__v2__,
ivars, ivars.map{|var| instance_variable_get(var)},
__getobj__
]
end
#
# Reinitializes delegation from a serialized object.
#
def marshal_load(data)
version, vars, values, obj = data
if version == :__v2__
vars.each_with_index{|var, i| instance_variable_set(var, values[i])}
__setobj__(obj)
else
__setobj__(data)
end
end
def initialize_clone(obj) # :nodoc:
self.__setobj__(obj.__getobj__.clone)
end
def initialize_dup(obj) # :nodoc:
self.__setobj__(obj.__getobj__.dup)
end
private :initialize_clone, :initialize_dup
##
# :method: trust
# Trust both the object returned by \_\_getobj\_\_ and self.
#
##
# :method: untrust
# Untrust both the object returned by \_\_getobj\_\_ and self.
#
##
# :method: taint
# Taint both the object returned by \_\_getobj\_\_ and self.
#
##
# :method: untaint
# Untaint both the object returned by \_\_getobj\_\_ and self.
#
##
# :method: freeze
# Freeze both the object returned by \_\_getobj\_\_ and self.
#
[:trust, :untrust, :taint, :untaint, :freeze].each do |method|
define_method method do
__getobj__.send(method)
super()
end
end
@delegator_api = self.public_instance_methods
def self.public_api # :nodoc:
@delegator_api
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 User
# def born_on
# Date.new(1989, 09, 10)
# end
# end
#
# class UserDecorator < SimpleDelegator
# def birth_year
# born_on.year
# end
# end
#
# decorated_user = UserDecorator.new(User.new)
# decorated_user.birth_year #=> 1989
# decorated_user.__getobj__ #=> #<User: ...>
#
# A SimpleDelegator instance can take advantage of the fact that SimpleDelegator
# is a subclass of +Delegator+ to call <tt>super</tt> to have methods called on
# the object being delegated to.
#
# class SuperArray < SimpleDelegator
# def [](*args)
# super + 1
# end
# end
#
# SuperArray.new([1])[0] #=> 2
#
# 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])
#
# Prints:
#
# Elements: 4
# Non-Nil: 4
# Unique: 4
#
# Elements: 8
# Non-Nil: 7
# Unique: 6
#
class SimpleDelegator<Delegator
# Returns the current object method calls are being delegated to.
def __getobj__
unless defined?(@delegate_sd_obj)
return yield if block_given?
__raise__ ::ArgumentError, "not delegated"
end
@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
def Delegator.delegating_block(mid) # :nodoc:
lambda do |*args, &block|
target = self.__getobj__
begin
target.__send__(mid, *args, &block)
ensure
$@.delete_if {|t| /\A#{Regexp.quote(__FILE__)}:#{__LINE__-2}:/o =~ t} if $@
end
end
end
#
# 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
#
# Here's a sample of use from Tempfile which is really a File object with a
# few special rules about storage location and 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
#
def DelegateClass(superclass)
klass = Class.new(Delegator)
methods = superclass.instance_methods
methods -= ::Delegator.public_api
methods -= [:to_s,:inspect,:=~,:!~,:===]
klass.module_eval do
def __getobj__ # :nodoc:
unless defined?(@delegate_dc_obj)
return yield if block_given?
__raise__ ::ArgumentError, "not delegated"
end
@delegate_dc_obj
end
def __setobj__(obj) # :nodoc:
__raise__ ::ArgumentError, "cannot delegate to self" if self.equal?(obj)
@delegate_dc_obj = obj
end
methods.each do |method|
define_method(method, Delegator.delegating_block(method))
end
end
klass.define_singleton_method :public_instance_methods do |all=true|
super(all) - superclass.protected_instance_methods
end
klass.define_singleton_method :protected_instance_methods do |all=true|
super(all) | superclass.protected_instance_methods
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 | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/monitor.rb | lib/monitor.rb | # = 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.
#
require 'thread'
#
# In concurrent programming, a monitor is an object or module intended to be
# used safely by more than one thread. The defining characteristic of a
# monitor is that its methods are executed with mutual exclusion. That is, at
# each point in time, at most one thread may be executing any of its methods.
# This mutual exclusion greatly simplifies reasoning about the implementation
# of monitors compared to reasoning about parallel code that updates a data
# structure.
#
# You can read more about the general principles on the Wikipedia page for
# Monitors[http://en.wikipedia.org/wiki/Monitor_%28synchronization%29]
#
# == Examples
#
# === Simple object.extend
#
# require 'monitor.rb'
#
# buf = []
# buf.extend(MonitorMixin)
# empty_cond = buf.new_cond
#
# # consumer
# Thread.start do
# loop do
# buf.synchronize do
# empty_cond.wait_while { buf.empty? }
# print buf.shift
# end
# end
# end
#
# # producer
# while line = ARGF.gets
# buf.synchronize do
# buf.push(line)
# empty_cond.signal
# end
# end
#
# The consumer thread waits for the producer thread to push a line to buf
# while <tt>buf.empty?</tt>. The producer thread (main thread) reads a
# line from ARGF and pushes it into buf then calls <tt>empty_cond.signal</tt>
# to notify the consumer thread of new data.
#
# === Simple Class include
#
# require 'monitor'
#
# class SynchronizedArray < Array
#
# include MonitorMixin
#
# def initialize(*args)
# super(*args)
# end
#
# alias :old_shift :shift
# alias :old_unshift :unshift
#
# def shift(n=1)
# self.synchronize do
# self.old_shift(n)
# end
# end
#
# def unshift(item)
# self.synchronize do
# self.old_unshift(item)
# end
# end
#
# # other methods ...
# end
#
# +SynchronizedArray+ implements an Array with synchronized access to items.
# This Class is implemented as subclass of Array which includes the
# MonitorMixin module.
#
module MonitorMixin
#
# FIXME: This isn't documented in Nutshell.
#
# Since MonitorMixin.new_cond returns a ConditionVariable, and the example
# above calls while_wait and signal, this class should be documented.
#
class ConditionVariable
class Timeout < Exception; end
#
# Releases the lock held in the associated monitor and waits; reacquires the lock on wakeup.
#
# If +timeout+ is given, this method returns after +timeout+ seconds passed,
# even if no other thread doesn't signal.
#
def wait(timeout = nil)
@monitor.__send__(:mon_check_owner)
count = @monitor.__send__(:mon_exit_for_cond)
begin
@cond.wait(@monitor.instance_variable_get(:@mon_mutex), timeout)
return true
ensure
@monitor.__send__(:mon_enter_for_cond, count)
end
end
#
# Calls wait repeatedly while the given block yields a truthy value.
#
def wait_while
while yield
wait
end
end
#
# Calls wait repeatedly until the given block yields a truthy value.
#
def wait_until
until yield
wait
end
end
#
# Wakes up the first thread in line waiting for this lock.
#
def signal
@monitor.__send__(:mon_check_owner)
@cond.signal
end
#
# Wakes up all threads waiting for this lock.
#
def broadcast
@monitor.__send__(:mon_check_owner)
@cond.broadcast
end
private
def initialize(monitor)
@monitor = monitor
@cond = ::ConditionVariable.new
end
end
def self.extend_object(obj)
super(obj)
obj.__send__(:mon_initialize)
end
#
# Attempts to enter exclusive section. Returns +false+ if lock fails.
#
def mon_try_enter
if @mon_owner != Thread.current
unless @mon_mutex.try_lock
return false
end
@mon_owner = Thread.current
end
@mon_count += 1
return true
end
# For backward compatibility
alias try_mon_enter mon_try_enter
#
# Enters exclusive section.
#
def mon_enter
if @mon_owner != Thread.current
@mon_mutex.lock
@mon_owner = Thread.current
end
@mon_count += 1
end
#
# Leaves exclusive section.
#
def mon_exit
mon_check_owner
@mon_count -=1
if @mon_count == 0
@mon_owner = nil
@mon_mutex.unlock
end
end
#
# Enters exclusive section and executes the block. Leaves the exclusive
# section automatically when the block exits. See example under
# +MonitorMixin+.
#
def mon_synchronize
mon_enter
begin
yield
ensure
mon_exit
end
end
alias synchronize mon_synchronize
#
# Creates a new MonitorMixin::ConditionVariable associated with the
# receiver.
#
def new_cond
return ConditionVariable.new(self)
end
private
# Use <tt>extend MonitorMixin</tt> or <tt>include MonitorMixin</tt> instead
# of this constructor. Have look at the examples above to understand how to
# use this module.
def initialize(*args)
super
mon_initialize
end
# Initializes the MonitorMixin after being included in a class or when an
# object has been extended with the MonitorMixin
def mon_initialize
@mon_owner = nil
@mon_count = 0
@mon_mutex = Mutex.new
end
def mon_check_owner
if @mon_owner != Thread.current
raise ThreadError, "current thread not owner"
end
end
def mon_enter_for_cond(count)
@mon_owner = Thread.current
@mon_count = count
end
def mon_exit_for_cond
count = @mon_count
@mon_owner = nil
@mon_count = 0
return count
end
end
# Use the Monitor class when you want to have a lock object for blocks with
# mutual exclusion.
#
# require 'monitor'
#
# lock = Monitor.new
# lock.synchronize do
# # exclusive access
# end
#
class Monitor
include MonitorMixin
alias try_enter try_mon_enter
alias enter mon_enter
alias exit mon_exit
end
# Documentation comments:
# - All documentation comes from Nutshell.
# - MonitorMixin.new_cond appears in the example, but is not documented in
# Nutshell.
# - All the internals (internal modules Accessible and Initializable, class
# ConditionVariable) appear in RDoc. It might be good to hide them, by
# making them private, or marking them :nodoc:, etc.
# - RDoc doesn't recognise aliases, so we have mon_synchronize documented, but
# not synchronize.
# - mon_owner is in Nutshell, but appears as an accessor in a separate module
# here, so is hard/impossible to RDoc. Some other useful accessors
# (mon_count and some queue stuff) are also in this module, and don't appear
# directly in the RDoc output.
# - in short, it may be worth changing the code layout in this file to make the
# documentation easier
# Local variables:
# mode: Ruby
# tab-width: 8
# End:
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/singleton.rb | lib/singleton.rb | require 'thread'
# The Singleton module implements the Singleton pattern.
#
# == Usage
#
# To use Singleton, include the module in your class.
#
# class Klass
# include Singleton
# # ...
# end
#
# This ensures that only one instance of Klass can be created.
#
# a,b = Klass.instance, Klass.instance
#
# a == b
# # => true
#
# Klass.new
# # => NoMethodError - new is private ...
#
# The instance is created at upon the first call of Klass.instance().
#
# class OtherKlass
# include Singleton
# # ...
# end
#
# ObjectSpace.each_object(OtherKlass){}
# # => 0
#
# OtherKlass.instance
# ObjectSpace.each_object(OtherKlass){}
# # => 1
#
#
# This behavior is preserved under inheritance and cloning.
#
# == Implementation
#
# This above is achieved by:
#
# * Making Klass.new and Klass.allocate private.
#
# * Overriding Klass.inherited(sub_klass) and Klass.clone() to ensure that the
# Singleton properties are kept when inherited and cloned.
#
# * Providing the Klass.instance() method that returns the same object each
# time it is called.
#
# * Overriding Klass._load(str) to call Klass.instance().
#
# * Overriding Klass#clone and Klass#dup to raise TypeErrors to prevent
# cloning or duping.
#
# == Singleton and Marshal
#
# By default Singleton's #_dump(depth) returns the empty string. Marshalling by
# default will strip state information, e.g. instance variables and taint
# state, from the instance. Classes using Singleton can provide custom
# _load(str) and _dump(depth) methods to retain some of the previous state of
# the instance.
#
# require 'singleton'
#
# class Example
# include Singleton
# attr_accessor :keep, :strip
# def _dump(depth)
# # this strips the @strip information from the instance
# Marshal.dump(@keep, depth)
# end
#
# def self._load(str)
# instance.keep = Marshal.load(str)
# instance
# end
# end
#
# a = Example.instance
# a.keep = "keep this"
# a.strip = "get rid of this"
# a.taint
#
# stored_state = Marshal.dump(a)
#
# a.keep = nil
# a.strip = nil
# b = Marshal.load(stored_state)
# p a == b # => true
# p a.keep # => "keep this"
# p a.strip # => nil
#
module Singleton
# Raises a TypeError to prevent cloning.
def clone
raise TypeError, "can't clone instance of singleton #{self.class}"
end
# Raises a TypeError to prevent duping.
def dup
raise TypeError, "can't dup instance of singleton #{self.class}"
end
# By default, do not retain any state when marshalling.
def _dump(depth = -1)
''
end
module SingletonClassMethods # :nodoc:
def clone # :nodoc:
Singleton.__init__(super)
end
# By default calls instance(). Override to retain singleton state.
def _load(str)
instance
end
private
def inherited(sub_klass)
super
Singleton.__init__(sub_klass)
end
end
class << Singleton # :nodoc:
def __init__(klass) # :nodoc:
klass.instance_eval {
@singleton__instance__ = nil
@singleton__mutex__ = Mutex.new
}
def klass.instance # :nodoc:
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
##
# :singleton-method: _load
# By default calls instance(). Override to retain singleton state.
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/date.rb | lib/date.rb | # date.rb: Written by Tadayoshi Funaba 1998-2011
require 'date_core'
require 'date/format'
class Date
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
def to_f
return 0 if @d == 0
if @d > 0
Float::INFINITY
else
-Float::INFINITY
end
end
end
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/pp.rb | lib/pp.rb | require 'prettyprint'
module Kernel
# Returns a pretty printed object as a string.
#
# In order to use this method you must first require the PP module:
#
# require 'pp'
#
# See the PP module for more information.
def pretty_inspect
PP.pp(self, '')
end
private
# prints arguments in pretty form.
#
# pp returns argument(s).
def pp(*objs) # :nodoc:
objs.each {|obj|
PP.pp(obj)
}
objs.size <= 1 ? objs.first : objs
end
module_function :pp # :nodoc:
end
##
# A pretty-printer for Ruby objects.
#
# All examples assume you have loaded the PP class with:
# require 'pp'
#
##
# == What PP Does
#
# Standard output by #p returns this:
# #<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 returns this:
# #<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>
#
##
# == Usage
#
# pp(obj) #=> obj
# pp obj #=> obj
# pp(obj1, obj2, ...) #=> [obj1, obj2, ...]
# pp() #=> nil
#
# Output <tt>obj(s)</tt> to <tt>$></tt> in pretty printed format.
#
# It returns <tt>obj(s)</tt>.
#
##
# == Output Customization
#
# To define a customized pretty printing function for your classes,
# redefine method <code>#pretty_print(pp)</code> in the class.
#
# <code>#pretty_print</code> takes the +pp+ argument, which is an instance of the PP class.
# The method uses #text, #breakable, #nest, #group and #pp to print the
# object.
#
##
# == Pretty-Print JSON
#
# To pretty-print JSON refer to JSON#pretty_generate.
#
##
# == Author
# Tanaka Akira <akr@fsij.org>
class PP < PrettyPrint
# Outputs +obj+ to +out+ in pretty printed format of
# +width+ columns in width.
#
# If +out+ is omitted, <code>$></code> 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
# Yields to a block
# and preserves the previous set of objects being printed.
def guard_inspect_key
if Thread.current[:__recursive_key__] == nil
Thread.current[:__recursive_key__] = {}.taint
end
if Thread.current[:__recursive_key__][:inspect] == nil
Thread.current[:__recursive_key__][:inspect] = {}.taint
end
save = Thread.current[:__recursive_key__][:inspect]
begin
Thread.current[:__recursive_key__][:inspect] = {}.taint
yield
ensure
Thread.current[:__recursive_key__][:inspect] = save
end
end
# Check whether the object_id +id+ is in the current buffer of objects
# to be pretty printed. Used to break cycles in chains of objects to be
# pretty printed.
def check_inspect_key(id)
Thread.current[:__recursive_key__] &&
Thread.current[:__recursive_key__][:inspect] &&
Thread.current[:__recursive_key__][:inspect].include?(id)
end
# Adds the object_id +id+ to the set of objects being pretty printed, so
# as to not repeat objects.
def push_inspect_key(id)
Thread.current[:__recursive_key__][:inspect][id] = true
end
# Removes an object from the set of objects being pretty printed.
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
# A convenience method, like object_group, but also reformats the Object's
# object_id.
def object_address_group(obj, &block)
str = Kernel.instance_method(:to_s).bind(obj).call
str.chomp!('>')
group(1, str, '>', &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
# A present standard failsafe for pretty printing any given Object
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
# A pretty print for a Hash
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 # :nodoc:
include PPMethods
end
module ObjectMixin # :nodoc:
# 1. specific pretty_print
# 2. specific inspect
# 3. 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)
method_method = Object.instance_method(:method).bind(self)
begin
inspect_method = method_method.call(:inspect)
rescue NameError
end
if inspect_method && /\(Kernel\)#/ !~ inspect_method.inspect
q.text self.inspect
elsif !inspect_method && self.respond_to?(:inspect)
q.text self.inspect
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 # :nodoc:
def pretty_print(q) # :nodoc:
q.group(1, '[', ']') {
q.seplist(self) {|v|
q.pp v
}
}
end
def pretty_print_cycle(q) # :nodoc:
q.text(empty? ? '[]' : '[...]')
end
end
class Hash # :nodoc:
def pretty_print(q) # :nodoc:
q.pp_hash self
end
def pretty_print_cycle(q) # :nodoc:
q.text(empty? ? '{}' : '{...}')
end
end
class << ENV # :nodoc:
def pretty_print(q) # :nodoc:
h = {}
ENV.keys.sort.each {|k|
h[k] = ENV[k]
}
q.pp_hash h
end
end
class Struct # :nodoc:
def pretty_print(q) # :nodoc:
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) # :nodoc:
q.text sprintf("#<struct %s:...>", PP.mcall(self, Kernel, :class).name)
end
end
class Range # :nodoc:
def pretty_print(q) # :nodoc:
q.pp self.begin
q.breakable ''
q.text(self.exclude_end? ? '...' : '..')
q.breakable ''
q.pp self.end
end
end
class File < IO # :nodoc:
class Stat # :nodoc:
def pretty_print(q) # :nodoc:
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 # :nodoc:
def pretty_print(q) # :nodoc:
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 < BasicObject # :nodoc:
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 | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/resolv-replace.rb | lib/resolv-replace.rb | require 'socket'
require 'resolv'
class << IPSocket
# :stopdoc:
alias original_resolv_getaddress getaddress
# :startdoc:
def getaddress(host)
begin
return Resolv.getaddress(host).to_s
rescue Resolv::ResolvError
raise SocketError, "Hostname not known: #{host}"
end
end
end
class TCPSocket < IPSocket
# :stopdoc:
alias original_resolv_initialize initialize
# :startdoc:
def initialize(host, serv, *rest)
rest[0] = IPSocket.getaddress(rest[0]) if rest[0]
original_resolv_initialize(IPSocket.getaddress(host), serv, *rest)
end
end
class UDPSocket < IPSocket
# :stopdoc:
alias original_resolv_bind bind
# :startdoc:
def bind(host, port)
host = IPSocket.getaddress(host) if host != ""
original_resolv_bind(host, port)
end
# :stopdoc:
alias original_resolv_connect connect
# :startdoc:
def connect(host, port)
original_resolv_connect(IPSocket.getaddress(host), port)
end
# :stopdoc:
alias original_resolv_send send
# :startdoc:
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
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 < TCPSocket
# :stopdoc:
alias original_resolv_initialize initialize
# :startdoc:
def initialize(host, serv)
original_resolv_initialize(IPSocket.getaddress(host), port)
end
end if defined? SOCKSSocket
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/tkconsole.rb | lib/tkconsole.rb | #
# tkconsole.rb - load tk/console.rb
#
require 'tk/console'
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/tkwinpkg.rb | lib/tkwinpkg.rb | #
# tkwinpkg.rb - load tk/winpkg.rb
#
require 'tk/winpkg'
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/e2mmap.rb | lib/e2mmap.rb | #
#--
# e2mmap.rb - for Ruby 1.1
# $Release Version: 2.0$
# $Revision: 1.10 $
# by Keiju ISHITSUKA
#
#++
#
# Helper module for easily defining exceptions with predefined messages.
#
# == Usage
#
# 1.
# class Foo
# extend Exception2MessageMapper
# def_e2message ExistingExceptionClass, "message..."
# def_exception :NewExceptionClass, "message..."[, superclass]
# ...
# end
#
# 2.
# module Error
# extend Exception2MessageMapper
# def_e2message ExistingExceptionClass, "message..."
# def_exception :NewExceptionClass, "message..."[, superclass]
# ...
# end
# class Foo
# include Error
# ...
# end
#
# foo = Foo.new
# foo.Fail ....
#
# 3.
# 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 # :nodoc:
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 registered exception(%s)")
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/cmath.rb | lib/cmath.rb | ##
# CMath is a library that provides trigonometric and transcendental
# functions for complex numbers.
#
# == Usage
#
# To start using this library, simply:
#
# require "cmath"
#
# Square root of a negative number is a complex number.
#
# CMath.sqrt(-9) #=> 0+3.0i
#
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
##
# Math::E raised to the +z+ power
#
# exp(Complex(0,0)) #=> 1.0+0.0i
# exp(Complex(0,PI)) #=> -1.0+1.2246467991473532e-16i
# exp(Complex(0,PI/2.0)) #=> 6.123233995736766e-17+1.0i
def exp(z)
begin
if z.real?
exp!(z)
else
ere = exp!(z.real)
Complex(ere * cos!(z.imag),
ere * sin!(z.imag))
end
rescue NoMethodError
handle_no_method_error
end
end
##
# Returns the natural logarithm of Complex. If a second argument is given,
# it will be the base of logarithm.
#
# log(Complex(0,0)) #=> -Infinity+0.0i
def log(*args)
begin
z, b = args
unless b.nil? || b.kind_of?(Numeric)
raise TypeError, "Numeric Number required"
end
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
rescue NoMethodError
handle_no_method_error
end
end
##
# returns the base 2 logarithm of +z+
def log2(z)
begin
if z.real? and z >= 0
log2!(z)
else
log(z) / log!(2)
end
rescue NoMethodError
handle_no_method_error
end
end
##
# returns the base 10 logarithm of +z+
def log10(z)
begin
if z.real? and z >= 0
log10!(z)
else
log(z) / log!(10)
end
rescue NoMethodError
handle_no_method_error
end
end
##
# Returns the non-negative square root of Complex.
# sqrt(-1) #=> 0+1.0i
# sqrt(Complex(-1,0)) #=> 0.0+1.0i
# sqrt(Complex(0,8)) #=> 2.0+2.0i
def sqrt(z)
begin
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.0), sqrt!((r - x) / 2.0))
end
end
rescue NoMethodError
handle_no_method_error
end
end
##
# returns the principal value of the cube root of +z+
def cbrt(z)
z ** (1.0/3)
end
##
# returns the sine of +z+, where +z+ is given in radians
def sin(z)
begin
if z.real?
sin!(z)
else
Complex(sin!(z.real) * cosh!(z.imag),
cos!(z.real) * sinh!(z.imag))
end
rescue NoMethodError
handle_no_method_error
end
end
##
# returns the cosine of +z+, where +z+ is given in radians
def cos(z)
begin
if z.real?
cos!(z)
else
Complex(cos!(z.real) * cosh!(z.imag),
-sin!(z.real) * sinh!(z.imag))
end
rescue NoMethodError
handle_no_method_error
end
end
##
# returns the tangent of +z+, where +z+ is given in radians
def tan(z)
begin
if z.real?
tan!(z)
else
sin(z) / cos(z)
end
rescue NoMethodError
handle_no_method_error
end
end
##
# returns the hyperbolic sine of +z+, where +z+ is given in radians
def sinh(z)
begin
if z.real?
sinh!(z)
else
Complex(sinh!(z.real) * cos!(z.imag),
cosh!(z.real) * sin!(z.imag))
end
rescue NoMethodError
handle_no_method_error
end
end
##
# returns the hyperbolic cosine of +z+, where +z+ is given in radians
def cosh(z)
begin
if z.real?
cosh!(z)
else
Complex(cosh!(z.real) * cos!(z.imag),
sinh!(z.real) * sin!(z.imag))
end
rescue NoMethodError
handle_no_method_error
end
end
##
# returns the hyperbolic tangent of +z+, where +z+ is given in radians
def tanh(z)
begin
if z.real?
tanh!(z)
else
sinh(z) / cosh(z)
end
rescue NoMethodError
handle_no_method_error
end
end
##
# returns the arc sine of +z+
def asin(z)
begin
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
rescue NoMethodError
handle_no_method_error
end
end
##
# returns the arc cosine of +z+
def acos(z)
begin
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
rescue NoMethodError
handle_no_method_error
end
end
##
# returns the arc tangent of +z+
def atan(z)
begin
if z.real?
atan!(z)
else
1.0.i * log((1.0.i + z) / (1.0.i - z)) / 2.0
end
rescue NoMethodError
handle_no_method_error
end
end
##
# returns the arc tangent of +y+ divided by +x+ using the signs of +y+ and
# +x+ to determine the quadrant
def atan2(y,x)
begin
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
rescue NoMethodError
handle_no_method_error
end
end
##
# returns the inverse hyperbolic sine of +z+
def asinh(z)
begin
if z.real?
asinh!(z)
else
log(z + sqrt(1.0 + z * z))
end
rescue NoMethodError
handle_no_method_error
end
end
##
# returns the inverse hyperbolic cosine of +z+
def acosh(z)
begin
if z.real? and z >= 1
acosh!(z)
else
log(z + sqrt(z * z - 1.0))
end
rescue NoMethodError
handle_no_method_error
end
end
##
# returns the inverse hyperbolic tangent of +z+
def atanh(z)
begin
if z.real? and z >= -1 and z <= 1
atanh!(z)
else
log((1.0 + z) / (1.0 - z)) / 2.0
end
rescue NoMethodError
handle_no_method_error
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
private
def handle_no_method_error # :nodoc:
if $!.name == :real?
raise TypeError, "Numeric Number required"
else
raise
end
end
module_function :handle_no_method_error
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
joker1007/rukawa | https://github.com/joker1007/rukawa/blob/23b32adbbb61a42c549b582f03df92b8cc548746/spec/rukawa_spec.rb | spec/rukawa_spec.rb | require 'spec_helper'
describe Rukawa do
it 'run jobs correctly' do
Rukawa.configure do |c|
c.logger = Logger.new($stdout)
end
Rukawa::Runner.run(SampleJobNet.new(variables: {"var1" => "value1"}), true)
expect(ExecuteLog.store).to match({
Job1 => an_instance_of(Time),
Job3 => an_instance_of(Time),
Job4 => an_instance_of(Time),
Job6 => an_instance_of(Time),
Job7 => an_instance_of(Time),
InnerJob3 => an_instance_of(Time),
InnerJob1 => an_instance_of(Time),
InnerJob4 => an_instance_of(Time),
})
expect(ExecuteLog.store[Job3]).to satisfy { |v| v > ExecuteLog.store[Job1] }
expect(ExecuteLog.store[Job4]).to satisfy { |v| v > ExecuteLog.store[Job3] }
expect(ExecuteLog.store[Job6]).to satisfy { |v| v > ExecuteLog.store[Job4] }
expect(ExecuteLog.store[Job7]).to satisfy { |v| v > ExecuteLog.store[Job6] }
expect(ExecuteLog.store[InnerJob3]).to satisfy { |v| v > ExecuteLog.store[Job3] }
expect(ExecuteLog.store[InnerJob1]).to satisfy { |v| v > ExecuteLog.store[Job3] }
expect(ExecuteLog.store[InnerJob4]).to satisfy { |v| v > ExecuteLog.store[Job4] }
end
def find_job(job_net, job_class)
job_net.dag.jobs.find { |n| n.is_a?(job_class) }.tap do |j|
raise "Notfound" unless j
end
end
it 'constructs dag correctly' do
job_net = SampleJobNet.new
job_classes = Set.new
collect_jobs = ->(j, set) {
j.dependencies.each_key do |n|
if n.respond_to?(:dependencies)
collect_jobs.call(n, set)
else
set << n
end
end
j.dependencies.each_value do |parents|
parents.each do |n|
if n.respond_to?(:dependencies)
collect_jobs.call(n, set)
else
set << n
end
end
end
}
collect_jobs.call(SampleJobNet, job_classes)
aggregate_failures do
assert { job_net.dag.jobs.size == job_classes.size}
job4 = find_job(job_net, Job4)
expect(job4.in_comings.map(&:from)).to match_array([an_instance_of(Job2), an_instance_of(Job3)])
job8 = find_job(job_net, Job8)
expect(job8.in_comings.map(&:from)).to match_array([an_instance_of(InnerJob2)])
expect(job8.out_goings.map(&:to)).to match_array([an_instance_of(InnerJob7), an_instance_of(InnerJob8)])
inner_job11 = find_job(job_net, InnerJob11)
expect(inner_job11.in_comings.map(&:from)).to match_array([an_instance_of(InnerJob9), an_instance_of(InnerJob10)])
expect(inner_job11.out_goings.map(&:to)).to match_array([an_instance_of(NestedJob1)])
inner_job12 = find_job(job_net, InnerJob12)
expect(inner_job12.in_comings.map(&:from)).to match_array([an_instance_of(InnerJob9), an_instance_of(InnerJob10)])
expect(inner_job12.out_goings.map(&:to)).to match_array([an_instance_of(NestedJob1)])
end
end
it 'skip hierarchy' do
subclass = Class.new(InnerJobNet4) do
add_skip_rule ->(job_net) { true }
end
job_net = subclass.new
expect(job_net).to be_skip
expect(job_net.dag.jobs).to all(be_skip)
end
end
| ruby | MIT | 23b32adbbb61a42c549b582f03df92b8cc548746 | 2026-01-04T17:51:46.689670Z | false |
joker1007/rukawa | https://github.com/joker1007/rukawa/blob/23b32adbbb61a42c549b582f03df92b8cc548746/spec/spec_helper.rb | spec/spec_helper.rb | $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'rukawa'
require 'rukawa/runner'
require 'rspec-power_assert'
require 'rspec-parameterized'
require 'active_job'
RSpec::PowerAssert.example_assertion_alias :assert
Dir.glob(File.expand_path('../../sample/job_nets/**/*.rb', __FILE__)).each { |f| require f }
Dir.glob(File.expand_path('../../sample/jobs/**/*.rb', __FILE__)).each { |f| require f }
redis_host = ENV["REDIS_HOST"] || "localhost:6379"
Rukawa.configure do |c|
c.status_store = ActiveSupport::Cache::RedisCacheStore.new(url: "redis://#{redis_host}")
end
Rukawa.config.status_store.write("rukawa.test", "test", expires_in: 60)
unless Rukawa.config.status_store.fetch("rukawa.test") == "test"
raise "status_store is bad"
end
ActiveJob::Base.queue_adapter = :sucker_punch
| ruby | MIT | 23b32adbbb61a42c549b582f03df92b8cc548746 | 2026-01-04T17:51:46.689670Z | false |
joker1007/rukawa | https://github.com/joker1007/rukawa/blob/23b32adbbb61a42c549b582f03df92b8cc548746/spec/rukawa/dependency_spec.rb | spec/rukawa/dependency_spec.rb | require 'spec_helper'
describe Rukawa::Dependency do
describe "AllSuccess" do
describe "#resolve" do
using RSpec::Parameterized::TableSyntax
where(:result1, :result2, :result3, :resolved) do
Rukawa::State.get(:finished) | Rukawa::State.get(:finished) | Rukawa::State.get(:finished) | true
Rukawa::State.get(:finished) | Rukawa::State.get(:bypassed) | Rukawa::State.get(:finished) | true
Rukawa::State.get(:finished) | Rukawa::State.get(:skipped) | Rukawa::State.get(:finished) | false
nil | Rukawa::State.get(:finished) | Rukawa::State.get(:finished) | false
end
with_them do
subject { Rukawa::Dependency::AllSuccess.new(result1, result2, result3).resolve }
it { is_expected.to eq(resolved) }
end
end
end
describe "AllDone" do
describe "#resolve" do
using RSpec::Parameterized::TableSyntax
where(:result1, :result2, :result3, :resolved) do
Rukawa::State.get(:finished) | Rukawa::State.get(:finished) | Rukawa::State.get(:finished) | true
Rukawa::State.get(:finished) | Rukawa::State.get(:bypassed) | Rukawa::State.get(:finished) | true
Rukawa::State.get(:finished) | Rukawa::State.get(:skipped) | Rukawa::State.get(:finished) | true
nil | Rukawa::State.get(:finished) | Rukawa::State.get(:finished) | true
end
with_them do
subject { Rukawa::Dependency::AllDone.new(result1, result2, result3).resolve }
it { is_expected.to eq(resolved) }
end
end
end
describe "OneSuccess" do
describe "#resolve" do
using RSpec::Parameterized::TableSyntax
where(:result1, :result2, :result3, :resolved) do
Rukawa::State.get(:finished) | Rukawa::State.get(:finished) | Rukawa::State.get(:finished) | true
Rukawa::State.get(:finished) | Rukawa::State.get(:skipped) | Rukawa::State.get(:finished) | true
nil | Rukawa::State.get(:finished) | Rukawa::State.get(:finished) | true
nil | nil | Rukawa::State.get(:finished) | true
nil | nil | Rukawa::State.get(:skipped) | false
nil | nil | nil | false
Rukawa::State.get(:skipped) | Rukawa::State.get(:skipped) | Rukawa::State.get(:skipped) | false
nil | nil | Rukawa::State.get(:bypassed) | true
end
with_them do
subject { Rukawa::Dependency::OneSuccess.new(result1, result2, result3).resolve }
it { is_expected.to eq(resolved) }
end
end
end
describe "AllSuccessOrSkipped" do
describe "#resolve" do
using RSpec::Parameterized::TableSyntax
where(:result1, :result2, :result3, :resolved) do
Rukawa::State.get(:finished) | Rukawa::State.get(:finished) | Rukawa::State.get(:finished) | true
Rukawa::State.get(:finished) | Rukawa::State.get(:skipped) | Rukawa::State.get(:finished) | true
nil | Rukawa::State.get(:finished) | Rukawa::State.get(:finished) | false
Rukawa::State.get(:skipped) | Rukawa::State.get(:skipped) | Rukawa::State.get(:skipped) | true
Rukawa::State.get(:bypassed) | Rukawa::State.get(:skipped) | Rukawa::State.get(:skipped) | true
end
with_them do
subject { Rukawa::Dependency::AllSuccessOrSkipped.new(result1, result2, result3).resolve }
it { is_expected.to eq(resolved) }
end
end
end
describe "OneSuccessOrSkipped" do
describe "#resolve" do
using RSpec::Parameterized::TableSyntax
where(:result1, :result2, :result3, :resolved) do
Rukawa::State.get(:finished) | Rukawa::State.get(:finished) | Rukawa::State.get(:finished) | true
Rukawa::State.get(:finished) | Rukawa::State.get(:skipped) | Rukawa::State.get(:finished) | true
nil | Rukawa::State.get(:finished) | Rukawa::State.get(:finished) | true
nil | nil | Rukawa::State.get(:finished) | true
nil | nil | nil | false
Rukawa::State.get(:skipped) | Rukawa::State.get(:skipped) | Rukawa::State.get(:skipped) | true
nil | Rukawa::State.get(:skipped) | Rukawa::State.get(:skipped) | true
nil | nil | Rukawa::State.get(:skipped) | true
nil | nil | Rukawa::State.get(:bypassed) | true
end
with_them do
subject { Rukawa::Dependency::OneSuccessOrSkipped.new(result1, result2, result3).resolve }
it { is_expected.to eq(resolved) }
end
end
end
describe "AllFailed" do
describe "#resolve" do
using RSpec::Parameterized::TableSyntax
where(:result1, :result2, :result3, :resolved) do
Rukawa::State.get(:finished) | Rukawa::State.get(:finished) | Rukawa::State.get(:finished) | false
Rukawa::State.get(:finished) | Rukawa::State.get(:skipped) | Rukawa::State.get(:finished) | false
nil | Rukawa::State.get(:finished) | Rukawa::State.get(:finished) | false
nil | nil | Rukawa::State.get(:finished) | false
nil | nil | nil | true
Rukawa::State.get(:skipped) | Rukawa::State.get(:skipped) | Rukawa::State.get(:skipped) | false
nil | Rukawa::State.get(:skipped) | Rukawa::State.get(:skipped) | false
nil | nil | Rukawa::State.get(:skipped) | false
nil | nil | Rukawa::State.get(:bypassed) | false
end
with_them do
subject { Rukawa::Dependency::AllFailed.new(result1, result2, result3).resolve }
it { is_expected.to eq(resolved) }
end
end
end
describe "OneFailed" do
describe "#resolve" do
using RSpec::Parameterized::TableSyntax
where(:result1, :result2, :result3, :resolved) do
Rukawa::State.get(:finished) | Rukawa::State.get(:finished) | Rukawa::State.get(:finished) | false
Rukawa::State.get(:finished) | Rukawa::State.get(:skipped) | Rukawa::State.get(:finished) | false
nil | Rukawa::State.get(:finished) | Rukawa::State.get(:finished) | true
nil | nil | Rukawa::State.get(:finished) | true
nil | nil | nil | true
Rukawa::State.get(:skipped) | Rukawa::State.get(:skipped) | Rukawa::State.get(:skipped) | false
nil | Rukawa::State.get(:skipped) | Rukawa::State.get(:skipped) | true
nil | nil | Rukawa::State.get(:skipped) | true
nil | nil | Rukawa::State.get(:bypassed) | true
end
with_them do
subject { Rukawa::Dependency::OneFailed.new(result1, result2, result3).resolve }
it { is_expected.to eq(resolved) }
end
end
end
end
| ruby | MIT | 23b32adbbb61a42c549b582f03df92b8cc548746 | 2026-01-04T17:51:46.689670Z | false |
joker1007/rukawa | https://github.com/joker1007/rukawa/blob/23b32adbbb61a42c549b582f03df92b8cc548746/spec/rukawa/abstract_job_spec.rb | spec/rukawa/abstract_job_spec.rb | require 'spec_helper'
describe Rukawa::AbstractJob do
describe ".add_skip_rule" do
it "inheritable" do
job_class1 = Class.new(Rukawa::AbstractJob) do
add_skip_rule -> { true }
end
job_class2 = Class.new(job_class1)
expect(job_class2.skip_rules.size).to eq(1)
end
it "changeable independent parent class" do
job_class1 = Class.new(Rukawa::AbstractJob) do
add_skip_rule -> { true }
end
job_class2 = Class.new(job_class1) do
add_skip_rule -> { true }
end
expect(job_class1.skip_rules.size).to eq(1)
expect(job_class2.skip_rules.size).to eq(2)
end
end
describe "#formatted_elapsed_time_from" do
using RSpec::Parameterized::TableSyntax
where(:finished_at_time, :started_at_time, :result) do
i = 1460286755
Time.at(i) | Time.at(i - 30) | "30s"
Time.at(i) | Time.at(i - 60) | "1m 0s"
Time.at(i) | Time.at(i - 3600) | "1h 0m 0s"
Time.at(i) | Time.at(i - 3620) | "1h 0m 20s"
Time.at(i) | Time.at(i - 3680) | "1h 1m 20s"
end
with_them do
it do
_finished_at_time = finished_at_time
_started_at_time = started_at_time
job_class1 = Class.new(Rukawa::AbstractJob) do
define_method(:finished_at) do
_finished_at_time
end
define_method(:started_at) do
_started_at_time
end
end
job = job_class1.new
assert do
job.formatted_elapsed_time_from == result
end
end
end
end
end
| ruby | MIT | 23b32adbbb61a42c549b582f03df92b8cc548746 | 2026-01-04T17:51:46.689670Z | false |
joker1007/rukawa | https://github.com/joker1007/rukawa/blob/23b32adbbb61a42c549b582f03df92b8cc548746/lib/rukawa.rb | lib/rukawa.rb | require "concurrent"
module Rukawa
class << self
def logger
config.logger
end
def configure
yield config
end
def config
Configuration.instance
end
def load_jobs
job_dirs = config.job_dirs.map { |d| File.expand_path(d) }.uniq
job_dirs.each do |dir|
Dir.glob(File.join(dir, "**/*.rb")) { |f| load f }
end
end
end
end
require 'active_support'
require "rukawa/version"
require 'rukawa/context'
require 'rukawa/errors'
require 'rukawa/state'
require 'rukawa/dependency'
require 'rukawa/configuration'
require 'rukawa/job_net'
require 'rukawa/job'
require 'rukawa/dag'
require 'rukawa/wrapper/active_job'
| ruby | MIT | 23b32adbbb61a42c549b582f03df92b8cc548746 | 2026-01-04T17:51:46.689670Z | false |
joker1007/rukawa | https://github.com/joker1007/rukawa/blob/23b32adbbb61a42c549b582f03df92b8cc548746/lib/rukawa/job_net.rb | lib/rukawa/job_net.rb | require 'rukawa/abstract_job'
module Rukawa
class JobNet < AbstractJob
include Enumerable
attr_reader :dag, :context, :variables
class << self
def dependencies
raise NotImplementedError, "Please override"
end
end
def initialize(variables: {}, context: Context.new, parent_job_net: nil, resume_job_classes: [])
@parent_job_net = parent_job_net
@variables = variables
@context = context
@dag = Dag.new
@dag.build(self, variables, context, self.class.dependencies)
@resume_job_classes = resume_job_classes
unless resume_job_classes.empty?
resume_targets = []
@dag.tsort_each_node do |node|
node.set_state(:bypassed)
resume_targets << node if resume_job_classes.include?(node.class)
end
resume_targets.each do |node|
@dag.each_strongly_connected_component_from(node) do |nodes|
nodes.each { |connected| connected.set_state(:waiting) }
end
end
end
end
def execute
dataflows.each(&:execute)
end
def run(wait_interval = 1)
promise = Concurrent::Promise.new do
futures = execute
until futures.all?(&:complete?)
yield self if block_given?
sleep wait_interval
end
errors = futures.map(&:reason).compact
unless errors.empty?
errors.each do |err|
next if err.is_a?(DependencyUnsatisfied)
Rukawa.logger.error(err)
end
end
futures
end
promise.execute
end
def started_at
@dag.nodes.min_by { |j| j.started_at ? j.started_at.to_i : Float::INFINITY }.started_at
end
def finished_at
@dag.nodes.max_by { |j| j.finished_at.to_i }.finished_at
end
def toplevel?
@parent_job_net.nil?
end
def subgraph?
!toplevel?
end
def dataflows
@dag.leveled_each.map(&:dataflow)
end
def state
inject(Rukawa::State::Waiting) do |state, j|
state.merge(j.state)
end
end
def output_dot(filename, format: nil)
if format && format != "dot"
io = IO.popen(["#{Rukawa.config.dot_command}", "-T#{format}", "-o", filename], "w")
io.write(to_dot)
io.close
else
File.open(filename, 'w') { |f| f.write(to_dot) }
end
end
def to_dot(subgraph = false)
graphdef = subgraph ? "subgraph" : "digraph"
buf = %Q|#{graphdef} "#{subgraph ? "cluster_" : ""}#{name}" {\n|
buf += %Q{label = "#{graph_label}";\n}
buf += Rukawa.config.graph.attrs
buf += Rukawa.config.graph.node.attrs
buf += "color = blue;\n" if subgraph
dag.each do |j|
buf += j.to_dot_def
end
dag.edges.each do |edge|
buf += %Q|"#{edge.from.name}" -> "#{edge.to.name}";\n|
end
buf += "}\n"
end
def to_dot_def
to_dot(true)
end
def jobs_as_to
@dag.jobs.select { |j| j.in_comings.select { |edge| edge.cluster == self }.empty? && j.root? }
end
def jobs_as_from
@dag.jobs.select { |j| j.out_goings.select { |edge| edge.cluster == self }.empty? && j.leaf? }
end
def each(&block)
@dag.each(&block)
end
private
def graph_label
if @resume_job_classes.empty?
name
else
"#{name} resume from (#{@resume_job_classes.join(", ")})"
end
end
end
end
| ruby | MIT | 23b32adbbb61a42c549b582f03df92b8cc548746 | 2026-01-04T17:51:46.689670Z | false |
joker1007/rukawa | https://github.com/joker1007/rukawa/blob/23b32adbbb61a42c549b582f03df92b8cc548746/lib/rukawa/version.rb | lib/rukawa/version.rb | module Rukawa
VERSION = "0.9.2"
end
| ruby | MIT | 23b32adbbb61a42c549b582f03df92b8cc548746 | 2026-01-04T17:51:46.689670Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.