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 |
|---|---|---|---|---|---|---|---|---|
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/cluster_accept_loop_delay.rb | lib/puma/cluster_accept_loop_delay.rb | # frozen_string_literal: true
module Puma
# Calculate a delay value for sleeping when running in clustered mode
#
# The main reason this is a class is so it can be unit tested independently.
# This makes modification easier in the future if we can encode properties of the
# delay into a test instead of relying on end-to-end testing only.
#
# This is an imprecise mechanism to address specific goals:
#
# - Evenly distribute requests across all workers at start
# - Evenly distribute CPU resources across all workers
#
# ## Goal: Distribute requests across workers at start
#
# There was a perf bug in Puma where one worker would wake up slightly before the rest and accept
# all the requests on the socket even though it didn't have enough resources to process all of them.
# This was originally fixed by never calling accept when a worker had more requests than threads
# already https://github.com/puma/puma/pull/3678/files/2736ebddb3fc8528e5150b5913fba251c37a8bf7#diff-a95f46e7ce116caddc9b9a9aa81004246d5210d5da5f4df90a818c780630166bL251-L291
#
# With the introduction of true keepalive support, there are two ways a request can come in:
# - A new request from a new client comes into the socket and it must be "accept"-ed
# - A keepalive request is served and the connection is retained. Another request is then accepted
#
# Ideally the server handles requests in the order they come in, and ideally it doesn't accept more requests than it can handle.
# These goals are contradictory, because when the server is at maximum capacity due to keepalive connections, it could mean we
# block all new requests, even if those came in before the new request on the older keepalive connection.
#
# ## Goal: Distribute CPU resources across all workers
#
# - This issue was opened https://github.com/puma/puma/issues/2078
#
# There are several entangled issues and it's not exactly clear what the root cause is, but the observable outcome
# was that performance was better with a small sleep, and that eventually became the default.
#
# An attempt to describe why this works is here: https://github.com/puma/puma/issues/2078#issuecomment-3287032470.
#
# Summarizing: The delay is for tuning the rate at which "accept" is called on the socket.
# Puma works by calling "accept" nonblock on the socket in a loop. When there are multiple workers
# (processes), they will "race" to accept a request at roughly the same rate. However, if one
# worker has all threads busy processing requests, then accepting a new request might "steal" it from
# a less busy worker. If a worker has no work to do, it should loop as fast as possible.
#
# ## Solution: Distribute requests across workers at start
#
# For now, both goals are framed as "load balancing" across workers (processes) and achieved through
# the same mechanism of sleeping longer to delay busier workers. Rather than the prior Puma 6.x
# and earlier behavior of using a binary on/off sleep value, we increase it an amount proportional
# to the load the server is under, capping the maximum delay to the scenario where all threads are busy
# and the todo list has reached a multiplier of the maximum number of threads.
#
# Private: API may change unexpectedly
class ClusterAcceptLoopDelay
attr_reader :max_delay
# Initialize happens once, `call` happens often. Perform global calculations here.
def initialize(
# Number of workers in the cluster
workers: ,
# Maximum delay in seconds i.e. 0.005 is 5 milliseconds
max_delay:
)
@on = max_delay > 0 && workers >= 2
@max_delay = max_delay.to_f
# Reach maximum delay when `max_threads * overload_multiplier` is reached in the system
@overload_multiplier = 25.0
end
def on?
@on
end
# We want the extreme values of this delay to be known (minimum and maximum) as well as
# a predictable curve between the two. i.e. no step functions or hard cliffs.
#
# Return value is always numeric. Returns 0 if there should be no delay.
def calculate(
# Number of threads working right now, plus number of requests in the todo list
busy_threads_plus_todo:,
# Maximum number of threads in the pool, note that the busy threads (alone) may go over this value at times
# if the pool needs to be reaped. The busy thread plus todo count may go over this value by a large amount.
max_threads:
)
max_value = @overload_multiplier * max_threads
# Approaches max delay when `busy_threads_plus_todo` approaches `max_value`
return max_delay * busy_threads_plus_todo.clamp(0, max_value) / max_value
end
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/error_logger.rb | lib/puma/error_logger.rb | # frozen_string_literal: true
require_relative 'const'
module Puma
# The implementation of a detailed error logging.
# @version 5.0.0
#
class ErrorLogger
include Const
attr_reader :ioerr
REQUEST_FORMAT = %{"%s %s%s" - (%s)}
LOG_QUEUE = Queue.new
def initialize(ioerr, env: ENV)
@ioerr = ioerr
@debug = env.key?('PUMA_DEBUG')
end
def self.stdio(env: ENV)
new($stderr, env: env)
end
# Print occurred error details.
# +options+ hash with additional options:
# - +error+ is an exception object
# - +req+ the http request
# - +text+ (default nil) custom string to print in title
# and before all remaining info.
#
def info(options={})
internal_write title(options)
end
# Print occurred error details only if
# environment variable PUMA_DEBUG is defined.
# +options+ hash with additional options:
# - +error+ is an exception object
# - +req+ the http request
# - +text+ (default nil) custom string to print in title
# and before all remaining info.
#
def debug(options={})
return unless @debug
error = options[:error]
req = options[:req]
string_block = []
string_block << title(options)
string_block << request_dump(req) if request_parsed?(req)
string_block << error.backtrace if error
internal_write string_block.join("\n")
end
def title(options={})
text = options[:text]
req = options[:req]
error = options[:error]
string_block = ["#{Time.now}"]
string_block << " #{text}" if text
string_block << " (#{request_title(req)})" if request_parsed?(req)
string_block << ": #{error.inspect}" if error
string_block.join('')
end
def request_dump(req)
"Headers: #{request_headers(req)}\n" \
"Body: #{req.body}"
end
def request_title(req)
env = req.env
query_string = env[QUERY_STRING]
REQUEST_FORMAT % [
env[REQUEST_METHOD],
env[REQUEST_PATH] || env[PATH_INFO],
query_string.nil? || query_string.empty? ? "" : "?#{query_string}",
env[HTTP_X_FORWARDED_FOR] || env[REMOTE_ADDR] || "-"
]
end
def request_headers(req)
headers = req.env.select { |key, _| key.start_with?('HTTP_') }
headers.map { |key, value| [key[5..-1], value] }.to_h.inspect
end
def request_parsed?(req)
req && req.env[REQUEST_METHOD]
end
def internal_write(str)
LOG_QUEUE << str
while (w_str = LOG_QUEUE.pop(true)) do
begin
@ioerr.is_a?(IO) and @ioerr.wait_writable(1)
@ioerr.write "#{w_str}\n"
@ioerr.flush unless @ioerr.sync
rescue Errno::EPIPE, Errno::EBADF, IOError, Errno::EINVAL
# 'Invalid argument' (Errno::EINVAL) may be raised by flush
end
end
rescue ThreadError
end
private :internal_write
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/binder.rb | lib/puma/binder.rb | # frozen_string_literal: true
require 'uri'
require 'socket'
require_relative 'const'
require_relative 'util'
module Puma
if HAS_SSL
require_relative 'minissl'
require_relative 'minissl/context_builder'
end
class Binder
include Puma::Const
RACK_VERSION = [1,6].freeze
def initialize(log_writer, options, env: ENV)
@log_writer = log_writer
@options = options
@listeners = []
@inherited_fds = {}
@activated_sockets = {}
@unix_paths = []
@env = env
@proto_env = {
"rack.version".freeze => RACK_VERSION,
"rack.errors".freeze => log_writer.stderr,
"rack.multithread".freeze => options[:max_threads] > 1,
"rack.multiprocess".freeze => options[:workers] >= 1,
"rack.run_once".freeze => false,
RACK_URL_SCHEME => options[:rack_url_scheme],
"SCRIPT_NAME".freeze => env['SCRIPT_NAME'] || "",
# I'd like to set a default CONTENT_TYPE here but some things
# depend on their not being a default set and inferring
# it from the content. And so if i set it here, it won't
# infer properly.
"QUERY_STRING".freeze => "",
SERVER_SOFTWARE => PUMA_SERVER_STRING,
GATEWAY_INTERFACE => CGI_VER,
RACK_AFTER_REPLY => nil,
RACK_RESPONSE_FINISHED => nil,
}
@envs = {}
@ios = []
end
attr_reader :ios
# @version 5.0.0
attr_reader :activated_sockets, :envs, :inherited_fds, :listeners, :proto_env, :unix_paths
# @version 5.0.0
attr_writer :ios, :listeners
def env(sock)
@envs.fetch(sock, @proto_env)
end
def close
@ios.each { |i| i.close }
end
# @!attribute [r] connected_ports
# @version 5.0.0
def connected_ports
t = ios.map { |io| io.addr[1] }; t.uniq!; t
end
# @version 5.0.0
def create_inherited_fds(env_hash)
env_hash.select {|k,v| k =~ /PUMA_INHERIT_\d+/}.each do |_k, v|
fd, url = v.split(":", 2)
@inherited_fds[url] = fd.to_i
end.keys # pass keys back for removal
end
# systemd socket activation.
# LISTEN_FDS = number of listening sockets. e.g. 2 means accept on 2 sockets w/descriptors 3 and 4.
# LISTEN_PID = PID of the service process, aka us
# @see https://www.freedesktop.org/software/systemd/man/systemd-socket-activate.html
# @version 5.0.0
#
def create_activated_fds(env_hash)
@log_writer.debug "ENV['LISTEN_FDS'] #{@env['LISTEN_FDS'].inspect} env_hash['LISTEN_PID'] #{env_hash['LISTEN_PID'].inspect}"
return [] unless env_hash['LISTEN_FDS'] && env_hash['LISTEN_PID'].to_i == $$
env_hash['LISTEN_FDS'].to_i.times do |index|
sock = TCPServer.for_fd(socket_activation_fd(index))
key = begin # Try to parse as a path
[:unix, Socket.unpack_sockaddr_un(sock.getsockname)]
rescue ArgumentError # Try to parse as a port/ip
port, addr = Socket.unpack_sockaddr_in(sock.getsockname)
addr = "[#{addr}]" if addr&.include? ':'
[:tcp, addr, port]
end
@activated_sockets[key] = sock
@log_writer.debug "Registered #{key.join ':'} for activation from LISTEN_FDS"
end
["LISTEN_FDS", "LISTEN_PID"] # Signal to remove these keys from ENV
end
# Synthesize binds from systemd socket activation
#
# When systemd socket activation is enabled, it can be tedious to keep the
# binds in sync. This method can synthesize any binds based on the received
# activated sockets. Any existing matching binds will be respected.
#
# When only_matching is true in, all binds that do not match an activated
# socket is removed in place.
#
# It's a noop if no activated sockets were received.
def synthesize_binds_from_activated_fs(binds, only_matching)
return binds unless activated_sockets.any?
activated_binds = []
activated_sockets.keys.each do |proto, addr, port|
if port
tcp_url = "#{proto}://#{addr}:#{port}"
ssl_url = "ssl://#{addr}:#{port}"
ssl_url_prefix = "#{ssl_url}?"
existing = binds.find { |bind| bind == tcp_url || bind == ssl_url || bind.start_with?(ssl_url_prefix) }
activated_binds << (existing || tcp_url)
else
# TODO: can there be a SSL bind without a port?
activated_binds << "#{proto}://#{addr}"
end
end
if only_matching
activated_binds
else
binds | activated_binds
end
end
def before_parse(&block)
@before_parse ||= []
@before_parse << block if block
@before_parse
end
def parse(binds, log_writer = nil, log_msg = 'Listening')
before_parse.each(&:call)
log_writer ||= @log_writer
binds.each do |str|
uri = URI.parse str
case uri.scheme
when "tcp"
if fd = @inherited_fds.delete(str)
io = inherit_tcp_listener uri.host, uri.port, fd
log_writer.log "* Inherited #{str}"
elsif sock = @activated_sockets.delete([ :tcp, uri.host, uri.port ])
io = inherit_tcp_listener uri.host, uri.port, sock
log_writer.log "* Activated #{str}"
else
ios_len = @ios.length
params = Util.parse_query uri.query
low_latency = params.key?('low_latency') && params['low_latency'] != 'false'
backlog = params.fetch('backlog', 1024).to_i
io = add_tcp_listener uri.host, uri.port, low_latency, backlog
@ios[ios_len..-1].each do |i|
addr = loc_addr_str i
log_writer.log "* #{log_msg} on http://#{addr}"
end
end
@listeners << [str, io] if io
when "unix"
path = "#{uri.host}#{uri.path}".gsub("%20", " ")
abstract = false
if str.start_with? 'unix://@'
raise "OS does not support abstract UNIXSockets" unless Puma.abstract_unix_socket?
abstract = true
path = "@#{path}"
end
if fd = @inherited_fds.delete(str)
@unix_paths << path unless abstract || File.exist?(path)
io = inherit_unix_listener path, fd
log_writer.log "* Inherited #{str}"
elsif sock = @activated_sockets.delete([ :unix, path ]) ||
!abstract && @activated_sockets.delete([ :unix, File.realdirpath(path) ])
@unix_paths << path unless abstract || File.exist?(path)
io = inherit_unix_listener path, sock
log_writer.log "* Activated #{str}"
else
umask = nil
mode = nil
backlog = 1024
if uri.query
params = Util.parse_query uri.query
if u = params['umask']
# Use Integer() to respect the 0 prefix as octal
umask = Integer(u)
end
if u = params['mode']
mode = Integer('0'+u)
end
if u = params['backlog']
backlog = Integer(u)
end
end
@unix_paths << path unless abstract || File.exist?(path)
io = add_unix_listener path, umask, mode, backlog
log_writer.log "* #{log_msg} on #{str}"
end
@listeners << [str, io]
when "ssl"
cert_key = %w[cert key]
raise "Puma compiled without SSL support" unless HAS_SSL
params = Util.parse_query uri.query
# If key and certs are not defined and localhost gem is required.
# localhost gem will be used for self signed
# Load localhost authority if not loaded.
# Ruby 3 `values_at` accepts an array, earlier do not
if params.values_at(*cert_key).all? { |v| v.to_s.empty? }
ctx = localhost_authority && localhost_authority_context
end
ctx ||=
begin
# Extract cert_pem and key_pem from options[:store] if present
cert_key.each do |v|
if params[v]&.start_with?('store:')
index = Integer(params.delete(v).split('store:').last)
params["#{v}_pem"] = @options[:store][index]
end
end
MiniSSL::ContextBuilder.new(params, @log_writer).context
end
if fd = @inherited_fds.delete(str)
log_writer.log "* Inherited #{str}"
io = inherit_ssl_listener fd, ctx
elsif sock = @activated_sockets.delete([ :tcp, uri.host, uri.port ])
io = inherit_ssl_listener sock, ctx
log_writer.log "* Activated #{str}"
else
ios_len = @ios.length
backlog = params.fetch('backlog', 1024).to_i
low_latency = params['low_latency'] != 'false'
io = add_ssl_listener uri.host, uri.port, ctx, low_latency, backlog
@ios[ios_len..-1].each do |i|
addr = loc_addr_str i
log_writer.log "* #{log_msg} on ssl://#{addr}?#{uri.query}"
end
end
@listeners << [str, io] if io
else
log_writer.error "Invalid URI: #{str}"
end
end
# If we inherited fds but didn't use them (because of a
# configuration change), then be sure to close them.
@inherited_fds.each do |str, fd|
log_writer.log "* Closing unused inherited connection: #{str}"
begin
IO.for_fd(fd).close
rescue SystemCallError
end
# We have to unlink a unix socket path that's not being used
uri = URI.parse str
if uri.scheme == "unix"
path = "#{uri.host}#{uri.path}"
File.unlink path
end
end
# Also close any unused activated sockets
unless @activated_sockets.empty?
fds = @ios.map(&:to_i)
@activated_sockets.each do |key, sock|
next if fds.include? sock.to_i
log_writer.log "* Closing unused activated socket: #{key.first}://#{key[1..-1].join ':'}"
begin
sock.close
rescue SystemCallError
end
# We have to unlink a unix socket path that's not being used
File.unlink key[1] if key.first == :unix
end
end
end
def localhost_authority
@localhost_authority ||= Localhost::Authority.fetch if defined?(Localhost::Authority) && !Puma::IS_JRUBY
end
def localhost_authority_context
return unless localhost_authority
key_path, crt_path = if [:key_path, :certificate_path].all? { |m| localhost_authority.respond_to?(m) }
[localhost_authority.key_path, localhost_authority.certificate_path]
else
local_certificates_path = File.expand_path("~/.localhost")
[File.join(local_certificates_path, "localhost.key"), File.join(local_certificates_path, "localhost.crt")]
end
MiniSSL::ContextBuilder.new({ "key" => key_path, "cert" => crt_path }, @log_writer).context
end
# Tell the server to listen on host +host+, port +port+.
# If +optimize_for_latency+ is true (the default) then clients connecting
# will be optimized for latency over throughput.
#
# +backlog+ indicates how many unaccepted connections the kernel should
# allow to accumulate before returning connection refused.
#
def add_tcp_listener(host, port, optimize_for_latency=true, backlog=1024)
if host == "localhost"
loopback_addresses.each do |addr|
add_tcp_listener addr, port, optimize_for_latency, backlog
end
return
end
host = host[1..-2] if host&.start_with? '['
tcp_server = TCPServer.new(host, port)
if optimize_for_latency
tcp_server.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
end
tcp_server.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true)
tcp_server.listen backlog
@ios << tcp_server
tcp_server
end
def inherit_tcp_listener(host, port, fd)
s = fd.kind_of?(::TCPServer) ? fd : ::TCPServer.for_fd(fd)
@ios << s
s
end
def add_ssl_listener(host, port, ctx,
optimize_for_latency=true, backlog=1024)
raise "Puma compiled without SSL support" unless HAS_SSL
# Puma will try to use local authority context if context is supplied nil
ctx ||= localhost_authority_context
if host == "localhost"
loopback_addresses.each do |addr|
add_ssl_listener addr, port, ctx, optimize_for_latency, backlog
end
return
end
host = host[1..-2] if host&.start_with? '['
s = TCPServer.new(host, port)
if optimize_for_latency
s.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
end
s.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true)
s.listen backlog
ssl = MiniSSL::Server.new s, ctx
env = @proto_env.dup
env[HTTPS_KEY] = HTTPS
@envs[ssl] = env
@ios << ssl
s
end
def inherit_ssl_listener(fd, ctx)
raise "Puma compiled without SSL support" unless HAS_SSL
# Puma will try to use local authority context if context is supplied nil
ctx ||= localhost_authority_context
s = fd.kind_of?(::TCPServer) ? fd : ::TCPServer.for_fd(fd)
ssl = MiniSSL::Server.new(s, ctx)
env = @proto_env.dup
env[HTTPS_KEY] = HTTPS
@envs[ssl] = env
@ios << ssl
s
end
# Tell the server to listen on +path+ as a UNIX domain socket.
#
def add_unix_listener(path, umask=nil, mode=nil, backlog=1024)
# Let anyone connect by default
umask ||= 0
begin
old_mask = File.umask(umask)
if File.exist? path
begin
old = UNIXSocket.new path
rescue SystemCallError, IOError
File.unlink path
else
old.close
raise "There is already a server bound to: #{path}"
end
end
s = UNIXServer.new path.sub(/\A@/, "\0") # check for abstract UNIXSocket
s.listen backlog
@ios << s
ensure
File.umask old_mask
end
if mode
File.chmod mode, path
end
env = @proto_env.dup
env[REMOTE_ADDR] = "127.0.0.1"
@envs[s] = env
s
end
def inherit_unix_listener(path, fd)
s = fd.kind_of?(::TCPServer) ? fd : ::UNIXServer.for_fd(fd)
@ios << s
env = @proto_env.dup
env[REMOTE_ADDR] = "127.0.0.1"
@envs[s] = env
s
end
def close_listeners
@listeners.each do |l, io|
begin
io.close unless io.closed?
uri = URI.parse l
next unless uri.scheme == 'unix'
unix_path = "#{uri.host}#{uri.path}"
File.unlink unix_path if @unix_paths.include?(unix_path) && File.exist?(unix_path)
rescue Errno::EBADF
end
end
end
def redirects_for_restart
redirects = @listeners.map { |a| [a[1].to_i, a[1].to_i] }.to_h
redirects[:close_others] = true
redirects
end
# @version 5.0.0
def redirects_for_restart_env
@listeners.each_with_object({}).with_index do |(listen, memo), i|
memo["PUMA_INHERIT_#{i}"] = "#{listen[1].to_i}:#{listen[0]}"
end
end
private
# @!attribute [r] loopback_addresses
def loopback_addresses
t = Socket.ip_address_list.select do |addrinfo|
addrinfo.ipv6_loopback? || addrinfo.ipv4_loopback?
end
t.map! { |addrinfo| addrinfo.ip_address }; t.uniq!; t
end
def loc_addr_str(io)
loc_addr = io.to_io.local_address
if loc_addr.ipv6?
"[#{loc_addr.ip_unpack[0]}]:#{loc_addr.ip_unpack[1]}"
else
loc_addr.ip_unpack.join(':')
end
end
# @version 5.0.0
def socket_activation_fd(int)
int + 3 # 3 is the magic number you add to follow the SA protocol
end
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/util.rb | lib/puma/util.rb | # frozen_string_literal: true
require 'uri/common'
module Puma
module Util
module_function
def pipe
IO.pipe
end
# Escapes and unescapes a URI escaped string with
# +encoding+. +encoding+ will be the target encoding of the string
# returned, and it defaults to UTF-8
if defined?(::Encoding)
def escape(s, encoding = Encoding::UTF_8)
URI.encode_www_form_component(s, encoding)
end
def unescape(s, encoding = Encoding::UTF_8)
URI.decode_www_form_component(s, encoding)
end
else
def escape(s, encoding = nil)
URI.encode_www_form_component(s, encoding)
end
def unescape(s, encoding = nil)
URI.decode_www_form_component(s, encoding)
end
end
module_function :unescape, :escape
DEFAULT_SEP = /[&;] */n
# Stolen from Mongrel, with some small modifications:
# Parses a query string by breaking it up at the '&'
# and ';' characters. You can also use this to parse
# cookies by changing the characters used in the second
# parameter (which defaults to '&;').
def parse_query(qs, d = nil, &unescaper)
unescaper ||= method(:unescape)
params = {}
(qs || '').split(d ? /[#{d}] */n : DEFAULT_SEP).each do |p|
next if p.empty?
k, v = p.split('=', 2).map(&unescaper)
if cur = params[k]
if cur.class == Array
params[k] << v
else
params[k] = [cur, v]
end
else
params[k] = v
end
end
params
end
# A case-insensitive Hash that preserves the original case of a
# header when set.
class HeaderHash < Hash
def self.new(hash={})
HeaderHash === hash ? hash : super(hash)
end
def initialize(hash={})
super()
@names = {}
hash.each { |k, v| self[k] = v }
end
def each
super do |k, v|
yield(k, v.respond_to?(:to_ary) ? v.to_ary.join("\n") : v)
end
end
# @!attribute [r] to_hash
def to_hash
hash = {}
each { |k,v| hash[k] = v }
hash
end
def [](k)
super(k) || super(@names[k.downcase])
end
def []=(k, v)
canonical = k.downcase
delete k if @names[canonical] && @names[canonical] != k # .delete is expensive, don't invoke it unless necessary
@names[k] = @names[canonical] = k
super k, v
end
def delete(k)
canonical = k.downcase
result = super @names.delete(canonical)
@names.delete_if { |name,| name.downcase == canonical }
result
end
def include?(k)
@names.include?(k) || @names.include?(k.downcase)
end
alias_method :has_key?, :include?
alias_method :member?, :include?
alias_method :key?, :include?
def merge!(other)
other.each { |k, v| self[k] = v }
self
end
def merge(other)
hash = dup
hash.merge! other
end
def replace(other)
clear
other.each { |k, v| self[k] = v }
self
end
end
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/json_serialization.rb | lib/puma/json_serialization.rb | # frozen_string_literal: true
require 'stringio'
module Puma
# Puma deliberately avoids the use of the json gem and instead performs JSON
# serialization without any external dependencies. In a puma cluster, loading
# any gem into the puma master process means that operators cannot use a
# phased restart to upgrade their application if the new version of that
# application uses a different version of that gem. The json gem in
# particular is additionally problematic because it leverages native
# extensions. If the puma master process relies on a gem with native
# extensions and operators remove gems from disk related to old releases,
# subsequent phased restarts can fail.
#
# The implementation of JSON serialization in this module is not designed to
# be particularly full-featured or fast. It just has to handle the few places
# where Puma relies on JSON serialization internally.
module JSONSerialization
QUOTE = /"/
BACKSLASH = /\\/
CONTROL_CHAR_TO_ESCAPE = /[\x00-\x1F]/ # As required by ECMA-404
CHAR_TO_ESCAPE = Regexp.union QUOTE, BACKSLASH, CONTROL_CHAR_TO_ESCAPE
class SerializationError < StandardError; end
class << self
def generate(value)
StringIO.open do |io|
serialize_value io, value
io.string
end
end
private
def serialize_value(output, value)
case value
when Hash
output << '{'
value.each_with_index do |(k, v), index|
output << ',' if index != 0
serialize_object_key output, k
output << ':'
serialize_value output, v
end
output << '}'
when Array
output << '['
value.each_with_index do |member, index|
output << ',' if index != 0
serialize_value output, member
end
output << ']'
when Integer, Float
output << value.to_s
when String
serialize_string output, value
when true
output << 'true'
when false
output << 'false'
when nil
output << 'null'
else
raise SerializationError, "Unexpected value of type #{value.class}"
end
end
def serialize_string(output, value)
output << '"'
output << value.gsub(CHAR_TO_ESCAPE) do |character|
case character
when BACKSLASH
'\\\\'
when QUOTE
'\\"'
when CONTROL_CHAR_TO_ESCAPE
'\u%.4X' % character.ord
end
end
output << '"'
end
def serialize_object_key(output, value)
case value
when Symbol, String
serialize_string output, value.to_s
else
raise SerializationError, "Could not serialize object of type #{value.class} as object key"
end
end
end
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/minissl/context_builder.rb | lib/puma/minissl/context_builder.rb | module Puma
module MiniSSL
class ContextBuilder
def initialize(params, log_writer)
@params = params
@log_writer = log_writer
end
def context
ctx = MiniSSL::Context.new
if defined?(JRUBY_VERSION)
unless params['keystore']
log_writer.error "Please specify the Java keystore via 'keystore='"
end
ctx.keystore = params['keystore']
unless params['keystore-pass']
log_writer.error "Please specify the Java keystore password via 'keystore-pass='"
end
ctx.keystore_pass = params['keystore-pass']
ctx.keystore_type = params['keystore-type']
if truststore = params['truststore']
ctx.truststore = truststore.eql?('default') ? :default : truststore
ctx.truststore_pass = params['truststore-pass']
ctx.truststore_type = params['truststore-type']
end
ctx.cipher_suites = params['cipher_suites'] || params['ssl_cipher_list']
ctx.protocols = params['protocols'] if params['protocols']
else
if params['key'].nil? && params['key_pem'].nil?
log_writer.error "Please specify the SSL key via 'key=' or 'key_pem='"
end
ctx.key = params['key'] if params['key']
ctx.key_pem = params['key_pem'] if params['key_pem']
ctx.key_password_command = params['key_password_command'] if params['key_password_command']
if params['cert'].nil? && params['cert_pem'].nil?
log_writer.error "Please specify the SSL cert via 'cert=' or 'cert_pem='"
end
ctx.cert = params['cert'] if params['cert']
ctx.cert_pem = params['cert_pem'] if params['cert_pem']
if ['peer', 'force_peer'].include?(params['verify_mode'])
unless params['ca']
log_writer.error "Please specify the SSL ca via 'ca='"
end
# needed for Puma::MiniSSL::Socket#peercert, env['puma.peercert']
require 'openssl'
end
ctx.ca = params['ca'] if params['ca']
ctx.ssl_cipher_filter = params['ssl_cipher_filter'] if params['ssl_cipher_filter']
ctx.ssl_ciphersuites = params['ssl_ciphersuites'] if params['ssl_ciphersuites'] && HAS_TLS1_3
ctx.reuse = params['reuse'] if params['reuse']
end
ctx.no_tlsv1 = params['no_tlsv1'] == 'true'
ctx.no_tlsv1_1 = params['no_tlsv1_1'] == 'true'
if params['verify_mode']
ctx.verify_mode = case params['verify_mode']
when "peer"
MiniSSL::VERIFY_PEER
when "force_peer"
MiniSSL::VERIFY_PEER | MiniSSL::VERIFY_FAIL_IF_NO_PEER_CERT
when "none"
MiniSSL::VERIFY_NONE
else
log_writer.error "Please specify a valid verify_mode="
MiniSSL::VERIFY_NONE
end
end
if params['verification_flags']
ctx.verification_flags = params['verification_flags'].split(',').
map { |flag| MiniSSL::VERIFICATION_FLAGS.fetch(flag) }.
inject { |sum, flag| sum ? sum | flag : flag }
end
ctx
end
private
attr_reader :params, :log_writer
end
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/plugin/systemd.rb | lib/puma/plugin/systemd.rb | # frozen_string_literal: true
require_relative '../plugin'
# Puma's systemd integration allows Puma to inform systemd:
# 1. when it has successfully started
# 2. when it is starting shutdown
# 3. periodically for a liveness check with a watchdog thread
# 4. periodically set the status
Puma::Plugin.create do
def start(launcher)
require_relative '../sd_notify'
launcher.log_writer.log "* Enabling systemd notification integration"
# hook_events
launcher.events.after_booted { Puma::SdNotify.ready }
launcher.events.after_stopped { Puma::SdNotify.stopping }
launcher.events.before_restart { Puma::SdNotify.reloading }
# start watchdog
if Puma::SdNotify.watchdog?
ping_f = watchdog_sleep_time
in_background do
launcher.log_writer.log "Pinging systemd watchdog every #{ping_f.round(1)} sec"
loop do
sleep ping_f
Puma::SdNotify.watchdog
end
end
end
# start status loop
instance = self
sleep_time = 1.0
in_background do
launcher.log_writer.log "Sending status to systemd every #{sleep_time.round(1)} sec"
loop do
sleep sleep_time
# TODO: error handling?
Puma::SdNotify.status(instance.status)
end
end
end
def status
if clustered?
messages = stats[:worker_status].map do |worker|
common_message(worker[:last_status])
end.join(',')
"Puma #{Puma::Const::VERSION}: cluster: #{booted_workers}/#{workers}, worker_status: [#{messages}]"
else
"Puma #{Puma::Const::VERSION}: worker: #{common_message(stats)}"
end
end
private
def watchdog_sleep_time
usec = Integer(ENV["WATCHDOG_USEC"])
sec_f = usec / 1_000_000.0
# "It is recommended that a daemon sends a keep-alive notification message
# to the service manager every half of the time returned here."
sec_f / 2
end
def stats
Puma.stats_hash
end
def clustered?
stats.has_key?(:workers)
end
def workers
stats.fetch(:workers, 1)
end
def booted_workers
stats.fetch(:booted_workers, 1)
end
def common_message(stats)
"{ #{stats[:running]}/#{stats[:max_threads]} threads, #{stats[:pool_capacity]} available, #{stats[:backlog]} backlog }"
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/plugin/tmp_restart.rb | lib/puma/plugin/tmp_restart.rb | # frozen_string_literal: true
require_relative '../plugin'
Puma::Plugin.create do
def start(launcher)
path = File.join("tmp", "restart.txt")
orig = nil
# If we can't write to the path, then just don't bother with this plugin
begin
File.write(path, "") unless File.exist?(path)
orig = File.stat(path).mtime
rescue SystemCallError
return
end
in_background do
while true
sleep 2
begin
mtime = File.stat(path).mtime
rescue SystemCallError
# If the file has disappeared, assume that means don't restart
else
if mtime > orig
launcher.restart
break
end
end
end
end
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/launcher/bundle_pruner.rb | lib/puma/launcher/bundle_pruner.rb | # frozen_string_literal: true
module Puma
class Launcher
# This class is used to pickup Gemfile changes during
# application restarts.
class BundlePruner
def initialize(original_argv, extra_runtime_dependencies, log_writer)
@original_argv = Array(original_argv)
@extra_runtime_dependencies = Array(extra_runtime_dependencies)
@log_writer = log_writer
end
def prune
return if ENV['PUMA_BUNDLER_PRUNED']
return unless defined?(Bundler)
require_rubygems_min_version!
unless puma_wild_path
log "! Unable to prune Bundler environment, continuing"
return
end
dirs = paths_to_require_after_prune
log '* Pruning Bundler environment'
home = ENV['GEM_HOME']
bundle_gemfile = Bundler.original_env['BUNDLE_GEMFILE']
bundle_app_config = Bundler.original_env['BUNDLE_APP_CONFIG']
with_unbundled_env do
ENV['GEM_HOME'] = home
ENV['BUNDLE_GEMFILE'] = bundle_gemfile
ENV['PUMA_BUNDLER_PRUNED'] = '1'
ENV["BUNDLE_APP_CONFIG"] = bundle_app_config
args = [Gem.ruby, puma_wild_path, '-I', dirs.join(':')] + @original_argv
# Defaults to true which breaks socket activation
args += [{:close_others => false}]
Kernel.exec(*args)
end
end
private
def require_rubygems_min_version!
min_version = Gem::Version.new('2.2')
return if min_version <= Gem::Version.new(Gem::VERSION)
raise "prune_bundler is not supported on your version of RubyGems. " \
"You must have RubyGems #{min_version}+ to use this feature."
end
def puma_wild_path
puma_lib_dir = puma_require_paths.detect { |x| File.exist? File.join(x, '../bin/puma-wild') }
File.expand_path(File.join(puma_lib_dir, '../bin/puma-wild'))
end
def with_unbundled_env
bundler_ver = Gem::Version.new(Bundler::VERSION)
if bundler_ver < Gem::Version.new('2.1.0')
Bundler.with_clean_env { yield }
else
Bundler.with_unbundled_env { yield }
end
end
def paths_to_require_after_prune
puma_require_paths + extra_runtime_deps_paths
end
def extra_runtime_deps_paths
t = @extra_runtime_dependencies.map do |dep_name|
if (spec = spec_for_gem(dep_name))
require_paths_for_gem(spec)
else
log "* Could not load extra dependency: #{dep_name}"
nil
end
end
t.flatten!; t.compact!; t
end
def puma_require_paths
require_paths_for_gem(spec_for_gem('puma'))
end
def spec_for_gem(gem_name)
Bundler.rubygems.loaded_specs(gem_name)
end
def require_paths_for_gem(gem_spec)
gem_spec.full_require_paths
end
def log(str)
@log_writer.log(str)
end
end
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/app/status.rb | lib/puma/app/status.rb | # frozen_string_literal: true
require_relative '../json_serialization'
module Puma
module App
# Check out {#call}'s source code to see what actions this web application
# can respond to.
class Status
OK_STATUS = '{ "status": "ok" }'.freeze
READ_ONLY_COMMANDS = %w[gc-stats stats].freeze
# @param launcher [::Puma::Launcher]
# @param token [String, nil] the token used for authentication
# @param data_only [Boolean] if true, restrict to read-only data commands
#
def initialize(launcher, token: nil, data_only: false)
@launcher = launcher
@auth_token = token
@enabled_commands = READ_ONLY_COMMANDS if data_only
end
# most commands call methods in `::Puma::Launcher` based on command in
# `env['PATH_INFO']`
def call(env)
unless authenticate(env)
return rack_response(403, 'Invalid auth token', 'text/plain')
end
# resp_type is processed by following case statement, return
# is a number (status) or a string used as the body of a 200 response
command = env['PATH_INFO'][/\/([^\/]+)$/, 1]
if @enabled_commands && !@enabled_commands.include?(command)
return rack_response(404, "Command #{command.inspect} unavailable", 'text/plain')
end
resp_type =
case command
when 'stop'
@launcher.stop ; 200
when 'halt'
@launcher.halt ; 200
when 'restart'
@launcher.restart ; 200
when 'phased-restart'
@launcher.phased_restart ? 200 : 404
when 'refork'
@launcher.refork ? 200 : 404
when 'reload-worker-directory'
@launcher.send(:reload_worker_directory) ? 200 : 404
when 'gc'
GC.start ; 200
when 'gc-stats'
Puma::JSONSerialization.generate GC.stat
when 'stats'
Puma::JSONSerialization.generate @launcher.stats
when 'thread-backtraces'
backtraces = []
@launcher.thread_status do |name, backtrace|
backtraces << { name: name, backtrace: backtrace }
end
Puma::JSONSerialization.generate backtraces
else
return rack_response(404, "Unsupported action", 'text/plain')
end
case resp_type
when String
rack_response 200, resp_type
when 200
rack_response 200, OK_STATUS
when 404
str = env['PATH_INFO'][/\/(\S+)/, 1].tr '-', '_'
rack_response 404, "{ \"error\": \"#{str} not available\" }"
end
end
private
def authenticate(env)
return true unless @auth_token
env['QUERY_STRING'].to_s.split(/[&;]/).include? "token=#{@auth_token}"
end
def rack_response(status, body, content_type='application/json')
headers = {
'content-type' => content_type,
'content-length' => body.bytesize.to_s
}
[status, headers, [body]]
end
end
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/rack/urlmap.rb | lib/puma/rack/urlmap.rb | # frozen_string_literal: true
module Puma::Rack
# Rack::URLMap takes a hash mapping urls or paths to apps, and
# dispatches accordingly. Support for HTTP/1.1 host names exists if
# the URLs start with <tt>http://</tt> or <tt>https://</tt>.
#
# URLMap modifies the SCRIPT_NAME and PATH_INFO such that the part
# relevant for dispatch is in the SCRIPT_NAME, and the rest in the
# PATH_INFO. This should be taken care of when you need to
# reconstruct the URL in order to create links.
#
# URLMap dispatches in such a way that the longest paths are tried
# first, since they are most specific.
class URLMap
NEGATIVE_INFINITY = -1.0 / 0.0
INFINITY = 1.0 / 0.0
def initialize(map = {})
remap(map)
end
def remap(map)
@mapping = map.map { |location, app|
if location =~ %r{\Ahttps?://(.*?)(/.*)}
host, location = $1, $2
else
host = nil
end
unless location[0] == ?/
raise ArgumentError, "paths need to start with /"
end
location = location.chomp('/')
match = Regexp.new("^#{Regexp.quote(location).gsub('/', '/+')}(.*)", Regexp::NOENCODING)
[host, location, match, app]
}.sort_by do |(host, location, _, _)|
[host ? -host.size : INFINITY, -location.size]
end
end
def call(env)
path = env['PATH_INFO']
script_name = env['SCRIPT_NAME']
http_host = env['HTTP_HOST']
server_name = env['SERVER_NAME']
server_port = env['SERVER_PORT']
is_same_server = casecmp?(http_host, server_name) ||
casecmp?(http_host, "#{server_name}:#{server_port}")
@mapping.each do |host, location, match, app|
unless casecmp?(http_host, host) \
|| casecmp?(server_name, host) \
|| (!host && is_same_server)
next
end
next unless m = match.match(path.to_s)
rest = m[1]
next unless !rest || rest.empty? || rest[0] == ?/
env['SCRIPT_NAME'] = (script_name + location)
env['PATH_INFO'] = rest
return app.call(env)
end
[404, {'content-type' => "text/plain", "x-cascade" => "pass"}, ["Not Found: #{path}"]]
ensure
env['PATH_INFO'] = path
env['SCRIPT_NAME'] = script_name
end
private
def casecmp?(v1, v2)
# if both nil, or they're the same string
return true if v1 == v2
# if either are nil... (but they're not the same)
return false if v1.nil?
return false if v2.nil?
# otherwise check they're not case-insensitive the same
v1.casecmp(v2).zero?
end
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/rack/builder.rb | lib/puma/rack/builder.rb | # frozen_string_literal: true
module Puma
end
module Puma::Rack
class Options
def parse!(args)
options = {}
opt_parser = OptionParser.new("", 24, ' ') do |opts|
opts.banner = "Usage: rackup [ruby options] [rack options] [rackup config]"
opts.separator ""
opts.separator "Ruby options:"
lineno = 1
opts.on("-e", "--eval LINE", "evaluate a LINE of code") { |line|
eval line, TOPLEVEL_BINDING, "-e", lineno
lineno += 1
}
opts.on("-b", "--builder BUILDER_LINE", "evaluate a BUILDER_LINE of code as a builder script") { |line|
options[:builder] = line
}
opts.on("-d", "--debug", "set debugging flags (set $DEBUG to true)") {
options[:debug] = true
}
opts.on("-w", "--warn", "turn warnings on for your script") {
options[:warn] = true
}
opts.on("-q", "--quiet", "turn off logging") {
options[:quiet] = true
}
opts.on("-I", "--include PATH",
"specify $LOAD_PATH (may be used more than once)") { |path|
(options[:include] ||= []).concat(path.split(":"))
}
opts.on("-r", "--require LIBRARY",
"require the library, before executing your script") { |library|
options[:require] = library
}
opts.separator ""
opts.separator "Rack options:"
opts.on("-s", "--server SERVER", "serve using SERVER (thin/puma/webrick/mongrel)") { |s|
options[:server] = s
}
opts.on("-o", "--host HOST", "listen on HOST (default: localhost)") { |host|
options[:Host] = host
}
opts.on("-p", "--port PORT", "use PORT (default: 9292)") { |port|
options[:Port] = port
}
opts.on("-O", "--option NAME[=VALUE]", "pass VALUE to the server as option NAME. If no VALUE, sets it to true. Run '#{$0} -s SERVER -h' to get a list of options for SERVER") { |name|
name, value = name.split('=', 2)
value = true if value.nil?
options[name.to_sym] = value
}
opts.on("-E", "--env ENVIRONMENT", "use ENVIRONMENT for defaults (default: development)") { |e|
options[:environment] = e
}
opts.on("-P", "--pid FILE", "file to store PID") { |f|
options[:pid] = ::File.expand_path(f)
}
opts.separator ""
opts.separator "Common options:"
opts.on_tail("-h", "-?", "--help", "Show this message") do
puts opts
puts handler_opts(options)
exit
end
opts.on_tail("--version", "Show version") do
puts "Rack #{Rack.version} (Release: #{Rack.release})"
exit
end
end
begin
opt_parser.parse! args
rescue OptionParser::InvalidOption => e
warn e.message
abort opt_parser.to_s
end
options[:config] = args.last if args.last
options
end
def handler_opts(options)
begin
info = []
server = Rack::Handler.get(options[:server]) || Rack::Handler.default(options)
if server&.respond_to?(:valid_options)
info << ""
info << "Server-specific options for #{server.name}:"
has_options = false
server.valid_options.each do |name, description|
next if /^(Host|Port)[^a-zA-Z]/.match? name.to_s # ignore handler's host and port options, we do our own.
info << " -O %-21s %s" % [name, description]
has_options = true
end
return "" if !has_options
end
info.join("\n")
rescue NameError
return "Warning: Could not find handler specified (#{options[:server] || 'default'}) to determine handler-specific options"
end
end
end
# Rack::Builder implements a small DSL to iteratively construct Rack
# applications.
#
# Example:
#
# require 'rack/lobster'
# app = Rack::Builder.new do
# use Rack::CommonLogger
# use Rack::ShowExceptions
# map "/lobster" do
# use Rack::Lint
# run Rack::Lobster.new
# end
# end
#
# run app
#
# Or
#
# app = Rack::Builder.app do
# use Rack::CommonLogger
# run lambda { |env| [200, {'Content-Type' => 'text/plain'}, ['OK']] }
# end
#
# run app
#
# +use+ adds middleware to the stack, +run+ dispatches to an application.
# You can use +map+ to construct a Rack::URLMap in a convenient way.
class Builder
def self.parse_file(config, opts = Options.new)
options = {}
if config =~ /\.ru$/
cfgfile = ::File.read(config)
if cfgfile[/^#\\(.*)/] && opts
options = opts.parse! $1.split(/\s+/)
end
cfgfile.sub!(/^__END__\n.*\Z/m, '')
app = new_from_string cfgfile, config
else
require config
app = Object.const_get(::File.basename(config, '.rb').capitalize)
end
[app, options]
end
def self.new_from_string(builder_script, file="(rackup)")
eval "Puma::Rack::Builder.new {\n" + builder_script + "\n}.to_app",
TOPLEVEL_BINDING, file, 0
end
def initialize(default_app = nil, &block)
@use, @map, @run, @warmup = [], nil, default_app, nil
# Conditionally load rack now, so that any rack middlewares,
# etc are available.
begin
require 'rack'
rescue LoadError
end
instance_eval(&block) if block
end
def self.app(default_app = nil, &block)
self.new(default_app, &block).to_app
end
# Specifies middleware to use in a stack.
#
# class Middleware
# def initialize(app)
# @app = app
# end
#
# def call(env)
# env["rack.some_header"] = "setting an example"
# @app.call(env)
# end
# end
#
# use Middleware
# run lambda { |env| [200, { "Content-Type" => "text/plain" }, ["OK"]] }
#
# All requests through to this application will first be processed by the middleware class.
# The +call+ method in this example sets an additional environment key which then can be
# referenced in the application if required.
def use(middleware, *args, &block)
if @map
mapping, @map = @map, nil
@use << proc { |app| generate_map app, mapping }
end
@use << proc { |app| middleware.new(app, *args, &block) }
end
# Takes an argument that is an object that responds to #call and returns a Rack response.
# The simplest form of this is a lambda object:
#
# run lambda { |env| [200, { "Content-Type" => "text/plain" }, ["OK"]] }
#
# However this could also be a class:
#
# class Heartbeat
# def self.call(env)
# [200, { "Content-Type" => "text/plain" }, ["OK"]]
# end
# end
#
# run Heartbeat
def run(app)
@run = app
end
# Takes a lambda or block that is used to warm-up the application.
#
# warmup do |app|
# client = Rack::MockRequest.new(app)
# client.get('/')
# end
#
# use SomeMiddleware
# run MyApp
def warmup(prc=nil, &block)
@warmup = prc || block
end
# Creates a route within the application.
#
# Rack::Builder.app do
# map '/' do
# run Heartbeat
# end
# end
#
# The +use+ method can also be used here to specify middleware to run under a specific path:
#
# Rack::Builder.app do
# map '/' do
# use Middleware
# run Heartbeat
# end
# end
#
# This example includes a piece of middleware which will run before requests hit +Heartbeat+.
#
def map(path, &block)
@map ||= {}
@map[path] = block
end
def to_app
app = @map ? generate_map(@run, @map) : @run
fail "missing run or map statement" unless app
app = @use.reverse.inject(app) { |a,e| e[a] }
@warmup&.call app
app
end
def call(env)
to_app.call(env)
end
private
def generate_map(default_app, mapping)
require_relative 'urlmap'
mapped = default_app ? {'/' => default_app} : {}
mapping.each { |r,b| mapped[r] = self.class.new(default_app, &b).to_app }
URLMap.new(mapped)
end
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/cluster/worker_handle.rb | lib/puma/cluster/worker_handle.rb | # frozen_string_literal: true
module Puma
class Cluster < Runner
#—————————————————————— DO NOT USE — this class is for internal use only ———
# This class represents a worker process from the perspective of the puma
# master process. It contains information about the process and its health
# and it exposes methods to control the process via IPC. It does not
# include the actual logic executed by the worker process itself. For that,
# see Puma::Cluster::Worker.
class WorkerHandle # :nodoc:
# array of stat 'max' keys
WORKER_MAX_KEYS = [:backlog_max, :reactor_max]
def initialize(idx, pid, phase, options)
@index = idx
@pid = pid
@phase = phase
@stage = :started
@signal = "TERM"
@options = options
@first_term_sent = nil
@started_at = Time.now
@last_checkin = Time.now
@last_status = {}
@term = false
@worker_max = Array.new WORKER_MAX_KEYS.length, 0
end
attr_reader :index, :pid, :phase, :signal, :last_checkin, :last_status, :started_at, :process_status
# @version 5.0.0
attr_writer :pid, :phase, :process_status
def booted?
@stage == :booted
end
def uptime
Time.now - started_at
end
def boot!
@last_checkin = Time.now
@stage = :booted
end
def term!
@term = true
end
def term?
@term
end
def ping!(status)
hsh = {}
k, v = nil, nil
status.tr('}{"', '').strip.split(", ") do |kv|
cntr = 0
kv.split(':') do |t|
if cntr == 0
k = t
cntr = 1
else
v = t
end
end
hsh[k.to_sym] = v.to_i
end
# check stat max values, we can't signal workers to reset the max values,
# so we do so here
WORKER_MAX_KEYS.each_with_index do |key, idx|
next unless hsh[key]
if hsh[key] < @worker_max[idx]
hsh[key] = @worker_max[idx]
else
@worker_max[idx] = hsh[key]
end
end
@last_checkin = Time.now
@last_status = hsh
end
# Resets max values to zero. Called whenever `Cluster#stats` is called
def reset_max
WORKER_MAX_KEYS.length.times { |idx| @worker_max[idx] = 0 }
end
# @see Puma::Cluster#check_workers
# @version 5.0.0
def ping_timeout
@last_checkin +
(booted? ?
@options[:worker_timeout] :
@options[:worker_boot_timeout]
)
end
def term
begin
if @first_term_sent && (Time.now - @first_term_sent) > @options[:worker_shutdown_timeout]
@signal = "KILL"
else
@term ||= true
@first_term_sent ||= Time.now
end
Process.kill @signal, @pid if @pid
rescue Errno::ESRCH
end
end
def kill
@signal = 'KILL'
term
end
def hup
Process.kill "HUP", @pid
rescue Errno::ESRCH
end
end
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/cluster/worker.rb | lib/puma/cluster/worker.rb | # frozen_string_literal: true
module Puma
class Cluster < Puma::Runner
#—————————————————————— DO NOT USE — this class is for internal use only ———
# This class is instantiated by the `Puma::Cluster` and represents a single
# worker process.
#
# At the core of this class is running an instance of `Puma::Server` which
# gets created via the `start_server` method from the `Puma::Runner` class
# that this inherits from.
class Worker < Puma::Runner # :nodoc:
attr_reader :index, :master
def initialize(index:, master:, launcher:, pipes:, app: nil)
super(launcher)
@index = index
@master = master
@check_pipe = pipes[:check_pipe]
@worker_write = pipes[:worker_write]
@fork_pipe = pipes[:fork_pipe]
@wakeup = pipes[:wakeup]
@app = app
@server = nil
@hook_data = {}
end
def run
title = "puma: cluster worker #{index}: #{master}"
title += " [#{@options[:tag]}]" if @options[:tag] && !@options[:tag].empty?
$0 = title
Signal.trap "SIGINT", "IGNORE"
Signal.trap "SIGCHLD", "DEFAULT"
Thread.new do
Puma.set_thread_name "wrkr check"
@check_pipe.wait_readable
log "! Detected parent died, dying"
exit! 1
end
# If we're not running under a Bundler context, then
# report the info about the context we will be using
if !ENV['BUNDLE_GEMFILE']
if File.exist?("Gemfile")
log "+ Gemfile in context: #{File.expand_path("Gemfile")}"
elsif File.exist?("gems.rb")
log "+ Gemfile in context: #{File.expand_path("gems.rb")}"
end
end
# Invoke any worker boot hooks so they can get
# things in shape before booting the app.
@config.run_hooks(:before_worker_boot, index, @log_writer, @hook_data)
begin
@server = start_server
rescue Exception => e
log "! Unable to start worker"
log e
log e.backtrace.join("\n ")
exit 1
end
restart_server = Queue.new << true << false
fork_worker = @options[:fork_worker] && index == 0
if fork_worker
restart_server.clear
worker_pids = []
Signal.trap "SIGCHLD" do
wakeup! if worker_pids.reject! do |p|
Process.wait(p, Process::WNOHANG) rescue true
end
end
Thread.new do
Puma.set_thread_name "wrkr fork"
while (idx = @fork_pipe.gets)
idx = idx.to_i
if idx == -1 # stop server
if restart_server.length > 0
restart_server.clear
@server.begin_restart(true)
@config.run_hooks(:before_refork, nil, @log_writer, @hook_data)
end
elsif idx == -2 # refork cycle is done
@config.run_hooks(:after_refork, nil, @log_writer, @hook_data)
elsif idx == 0 # restart server
restart_server << true << false
else # fork worker
worker_pids << pid = spawn_worker(idx)
@worker_write << "#{PIPE_FORK}#{pid}:#{idx}\n" rescue nil
end
end
end
end
Signal.trap "SIGTERM" do
@worker_write << "#{PIPE_EXTERNAL_TERM}#{Process.pid}\n" rescue nil
restart_server.clear
@server.stop
restart_server << false
end
begin
@worker_write << "#{PIPE_BOOT}#{Process.pid}:#{index}\n"
rescue SystemCallError, IOError
STDERR.puts "Master seems to have exited, exiting."
return
end
while restart_server.pop
server_thread = @server.run
if @log_writer.debug? && index == 0
debug_loaded_extensions "Loaded Extensions - worker 0:"
end
stat_thread ||= Thread.new(@worker_write) do |io|
Puma.set_thread_name "stat pld"
base_payload = "#{PIPE_PING}#{Process.pid}"
while true
begin
payload = base_payload.dup
hsh = @server.stats
hsh.each do |k, v|
payload << %Q! "#{k}":#{v || 0},!
end
# sub call properly adds 'closing' string
io << payload.sub(/,\z/, " }\n")
@server.reset_max
rescue IOError
break
end
sleep @options[:worker_check_interval]
end
end
server_thread.join
end
# Invoke any worker shutdown hooks so they can prevent the worker
# exiting until any background operations are completed
@config.run_hooks(:before_worker_shutdown, index, @log_writer, @hook_data)
ensure
@worker_write << "#{PIPE_TERM}#{Process.pid}\n" rescue nil
@worker_write.close
end
private
def spawn_worker(idx)
@config.run_hooks(:before_worker_fork, idx, @log_writer, @hook_data)
pid = fork do
new_worker = Worker.new index: idx,
master: master,
launcher: @launcher,
pipes: { check_pipe: @check_pipe,
worker_write: @worker_write },
app: @app
new_worker.run
end
if !pid
log "! Complete inability to spawn new workers detected"
log "! Seppuku is the only choice."
exit! 1
end
@config.run_hooks(:after_worker_fork, idx, @log_writer, @hook_data)
pid
end
end
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/rack/handler/puma.rb | lib/rack/handler/puma.rb | # frozen_string_literal: true
module Puma
# This module is used as an 'include' file in code at bottom of file. It loads
# into either `Rackup::Handler::Puma` or `Rack::Handler::Puma`.
module RackHandler
DEFAULT_OPTIONS = {
:Verbose => false,
:Silent => false
}
def config(app, options = {})
require_relative '../../puma'
require_relative '../../puma/configuration'
require_relative '../../puma/log_writer'
require_relative '../../puma/launcher'
default_options = DEFAULT_OPTIONS.dup
# Libraries pass in values such as :Port and there is no way to determine
# if it is a default provided by the library or a special value provided
# by the user. A special key `user_supplied_options` can be passed. This
# contains an array of all explicitly defined user options. We then
# know that all other values are defaults
if user_supplied_options = options.delete(:user_supplied_options)
(options.keys - user_supplied_options).each do |k|
default_options[k] = options.delete(k)
end
end
@events = options[:events] || ::Puma::Events.new
conf = ::Puma::Configuration.new(options, default_options.merge({ events: @events })) do |user_config, file_config, default_config|
if options.delete(:Verbose)
begin
require 'rack/commonlogger' # Rack 1.x
rescue LoadError
require 'rack/common_logger' # Rack 2 and later
end
app = ::Rack::CommonLogger.new(app, STDOUT)
end
if options[:environment]
user_config.environment options[:environment]
end
if options[:Threads]
min, max = options.delete(:Threads).split(':', 2)
user_config.threads min, max
end
if options[:Host] || options[:Port]
host = options[:Host] || default_options[:Host]
port = options[:Port] || default_options[:Port]
self.set_host_port_to_config(host, port, user_config)
end
if default_options[:Host]
file_config.set_default_host(default_options[:Host])
end
self.set_host_port_to_config(default_options[:Host], default_options[:Port], default_config)
user_config.app app
end
conf
end
def run(app, **options)
conf = self.config(app, options)
log_writer = options.delete(:Silent) ? ::Puma::LogWriter.strings : ::Puma::LogWriter.stdio
launcher = ::Puma::Launcher.new(conf, log_writer: log_writer, events: @events)
yield launcher if block_given?
begin
launcher.run
rescue Interrupt
puts "* Gracefully stopping, waiting for requests to finish"
launcher.stop
puts "* Goodbye!"
end
end
def valid_options
{
"Host=HOST" => "Hostname to listen on (default: localhost)",
"Port=PORT" => "Port to listen on (default: 8080)",
"Threads=MIN:MAX" => "min:max threads to use (default 0:16)",
"Verbose" => "Don't report each request (default: false)"
}
end
def set_host_port_to_config(host, port, config)
config.clear_binds! if host || port
if host&.start_with? '.', '/', '@'
config.bind "unix://#{host}"
elsif host&.start_with? 'ssl://'
uri = URI.parse(host)
uri.port ||= port || ::Puma::Configuration::DEFAULTS[:tcp_port]
config.bind uri.to_s
else
if host
port ||= ::Puma::Configuration::DEFAULTS[:tcp_port]
end
if port
host ||= ::Puma::Configuration::DEFAULTS[:tcp_host]
config.port port, host
end
end
end
end
end
# rackup was removed in Rack 3, it is now a separate gem
if Object.const_defined?(:Rackup) && ::Rackup.const_defined?(:Handler)
module Rackup
module Handler
module Puma
class << self
include ::Puma::RackHandler
end
end
register :puma, Puma
end
end
else
do_register = Object.const_defined?(:Rack) && ::Rack.release < '3'
module Rack
module Handler
module Puma
class << self
include ::Puma::RackHandler
end
end
end
end
::Rack::Handler.register(:puma, ::Rack::Handler::Puma) if do_register
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/cops/tests_puma.rb | cops/tests_puma.rb | require 'rubocop'
module RuboCop
module Cop
module Puma
class TestsMustUsePumaTest < Base
extend AutoCorrector
MSG = 'Inherit from PumaTest instead of Minitest::Test'
def_node_matcher :inherits_from_minitest_test?, <<~PATTERN
(class _ (const (const nil? :Minitest) :Test) ...)
PATTERN
def on_class(node)
return unless inherits_from_minitest_test?(node)
add_offense(node.children[1]) do |corrector|
corrector.replace(node.children[1], 'PumaTest')
end
end
end
end
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
skwp/dotfiles | https://github.com/skwp/dotfiles/blob/9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23/bin/marky.rb | bin/marky.rb | #!/usr/bin/env ruby
# source http://brettterpstra.com/marky-the-markdownifier-reintroductions/
require 'open-uri'
require 'net/http'
require 'iconv'
require 'optparse'
require 'fileutils'
require 'cgi'
$options = {}
# $fymdhost = "http://fym.dev"
$fymdhost = "http://heckyesmarkdown.com"
optparse = OptionParser.new do|opts|
opts.banner = "Usage: #{File.basename(__FILE__)} [-o OUTPUT_PATH] -f TYPE [-t TYPE] input1 [input2, ...]"
$options[:outfolder] = false
opts.on( '-o DIR','--output DIR', 'Output folder, default STDOUT. Use "." for current folder, void if output type is "nv"' ) do |outfolder|
filepath = File.expand_path(outfolder)
unless File.exists?(filepath) && File.directory?(filepath)
if File.exists?(filepath)
puts "Output folder is not a directory"
exit
else
FileUtils.mkdir_p(filepath)
puts "Created #{filepath}"
end
end
$options[:outfolder] = filepath.gsub(/\/$/,'') + "/"
puts "Output folder: #{$options[:outfolder]}"
end
if STDIN.stat.nlink == 1
if ARGV[-1] =~ /https?:/
$options[:inputtype] = 'url'
else
$options[:inputtype] = case File.extname(File.expand_path(ARGV[-1]))
when '.html' then 'htmlfile'
when '.htm' then 'htmlfile'
when '.txt' then 'htmlfile'
when '.webarchive' then 'webarchive'
when '.webloc' then 'bookmark'
when '.webbookmark' then 'bookmark'
else 'url'
end
end
else
$options[:inputtype] = 'html'
end
opts.on( '-f TYPE','--from TYPE', 'Input type (html, htmlfile, url [default], bookmark, webarchive, webarchiveurl)') do |input_type|
$options[:inputtype] = input_type
end
$options[:outputtype] = 'md'
opts.on( '-t TYPE', '--to TYPE', 'Output type (md [default], nv)') do |output_type|
$options[:outputtype] = output_type
end
opts.on( '-h', '--help', 'Display this screen' ) do
puts opts
exit
end
end
optparse.parse!
$input = STDIN.stat.nlink == 0 ? STDIN.read : ARGV
# Convert html input to readable Markdown
def html_to_markdown(input,filename = false)
input = input.class == Array ? input.join : input
res = Net::HTTP.post_form(URI.parse("#{$fymdhost}/go/"),{'html'=>input,'read'=>'1'})
if res.code.to_i == 200
if $options[:outfolder]
outfile = $options[:outfolder]
if filename
outfile += File.basename(filename,'.html')+'.md'
else
outfile += res.body.split("\n")[2].gsub(/^#\s*/,'').strip.gsub(/[!?*$^()]+/,'') + '.md'
end
File.open(outfile,'w') {|f|
f.puts res.body
}
puts "Markdown written to #{outfile}"
else
puts res.body
end
else
puts "Error converting HTML"
end
end
def html_file_to_markdown(outtype)
$input.each {|file|
input = File.expand_path(file)
if File.exists?(input)
html = File.open(input,'r') {|infile|
CGI.escape(CGI.unescapeHTML(infile.read))
}
if outtype == 'md'
html_to_markdown(html,input)
else
html_to_nv(html)
end
else
puts "File does not exist: #{input}"
end
}
end
def url_to_markdown
$input.each {|input|
res = Net::HTTP.post_form(URI.parse("#{$fymdhost}/go/"),{'u'=>input,'read'=>'1'})
if res.code.to_i == 200
if $options[:outfolder]
outfile = $options[:outfolder]
outfile += input.gsub(/^https?:\/\//,'').strip.gsub(/\//,'_').gsub(/[!?*$^()]+/,'') + '.md'
File.open(outfile,'w') {|f|
f.puts res.body
}
puts "Markdown written to #{outfile}"
else
puts res.body
end
else
puts "Error opening URL: #{input}"
end
}
end
# Convert html input to Markdown and add to nvALT
def html_to_nv(input)
input = input.class == Array ? input.join : input
res = Net::HTTP.post_form(URI.parse("#{$fymdhost}/go/"),{'html'=>input,'read'=>'1','output' => 'nv'})
if res.code.to_i == 200
%x{osascript -e 'tell app "nvALT" to activate'}
%x{open "#{res.body}"}
else
puts "Error converting HTML"
end
end
# Capture URL as Markdown note in nvALT
def url_to_nv
$input.each {|input|
res = Net::HTTP.post_form(URI.parse("#{$fymdhost}/go/"),{'u'=>input,'read'=>'1','output' => 'nv'})
if res.code.to_i == 200
%x{osascript -e 'tell app "nvALT" to activate'}
%x{open "#{res.body}"}
else
puts "Error opening URL: #{input}"
end
}
end
# Convert url of web archive to Markdown
def webarchive_url_to_markdown(outtype)
$input.each {|f|
file = File.expand_path(f)
source_url = %x{mdls -name 'kMDItemWhereFroms' -raw #{file}}.split("\n")[1].strip.gsub(/(^"|"$)/,'')
res = Net::HTTP.post_form(URI.parse("#{$fymdhost}/go/"),{'u'=>source_url,'read'=>'1','output' => outtype})
if res.code.to_i == 200
if outtype == 'nv'
%x{osascript -e 'tell app "nvALT" to activate'}
%x{open "#{res.body}"}
elsif ($options[:outfolder])
outfile = $options[:outfolder]
outfile += %x{textutil -info #{file} | grep "Title:"}.gsub(/^\s*Title:\s*/,'').strip.gsub(/[!?*$^()]+/,'') + '.md'
File.open(outfile,'w') {|f|
f.puts res.body
}
puts "Webarchive origin converted and saved to #{outfile}"
else
puts res.body
end
else
puts "Error opening URL: #{source_url}"
end
}
end
# Convert webarchive contents to Markdown
def webarchive_to_markdown(outtype)
$input.each {|f|
file = File.expand_path(f)
html = %x{textutil -convert html -noload -nostore -stdout #{file} 2> /dev/null}
res = Net::HTTP.post_form(URI.parse("#{$fymdhost}/go/"),{'html'=>html,'read'=>'1','output' => outtype})
if res.code.to_i == 200
if outtype == 'nv'
%x{osascript -e 'tell app "nvALT" to activate'}
%x{open "#{res.body}"}
elsif ($options[:outfolder])
outfile = $options[:outfolder]
outfile += %x{textutil -info #{file} | grep "Title:"}.gsub(/^\s*Title:\s*/,'').strip.gsub(/[!?*$^()]+/,'') + '.md'
File.open(outfile,'w') {|out|
out.puts res.body
}
puts "Webarchive converted and saved to #{outfile}"
else
puts res.body
end
else
puts "Error converting HTML"
end
}
end
# Save the contents of a webbookmark or webloc url as Markdown
def bookmark_to_markdown(outtype)
$input.each {|f|
file = File.expand_path(f)
if File.exists?(file)
outfile = $options[:outfolder] ? $options[:outfolder] : ""
outfile += %x{mdls -name 'kMDItemDisplayName' -raw "#{file}"}.strip.gsub(/(\.webbookmark|\.webloc)$/,'') + '.md'
source_url = %x{mdls -name 'kMDItemURL' -raw "#{file}"}.strip
if source_url.nil? || source_url == "(null)"
source_url = File.open(file,'r') do |infile|
ic = Iconv.new('UTF-8//IGNORE', 'UTF-8')
urlstring = ic.iconv(infile.read + ' ')[0..-2].match(/\<key\>URL\<\/key\>\n\s*\<string\>(.*?)\<\/string\>/)
urlstring.nil? ? nil : urlstring[1]
end
end
if source_url.nil?
puts "Could not locate URL for bookmark"
else
res = Net::HTTP.post_form(URI.parse("#{$fymdhost}/go/"),{'u'=>source_url,'read'=>'1','output' => outtype})
if res.code.to_i == 200
if outtype == 'nv'
%x{osascript -e 'tell app "nvALT" to activate'}
%x{open "#{res.body}"}
elsif ($options[:outfolder])
File.open(outfile,'w') {|f|
f.puts res.body
}
puts "Bookmark converted and saved to #{outfile}"
else
puts res.body
end
else
puts "Error opening URL: #{source_url}"
end
end
end
}
end
def bad_combo
puts "Bad input/output combination"
exit
end
if ($options[:inputtype] == 'url' || $options[:inputtype] == 'bookmark') && $input.class != Array
p $input
puts "Wrong argument format. This input type should be a space-separated list of urls or bookmark files."
exit
end
if $options[:inputtype] == 'url'
if $options[:outputtype] == 'md'
url_to_markdown
elsif $options[:outputtype] == 'nv'
url_to_nv
else
bad_combo
end
elsif $options[:inputtype] == 'html'
if $options[:outputtype] == 'md'
html_to_markdown($input)
elsif $options[:outputtype] == 'nv'
html_to_nv($input)
else
bad_combo
end
elsif $options[:inputtype] == 'htmlfile'
if $options[:outputtype] == 'md'
html_file_to_markdown('md')
elsif $options[:outputtype] == 'nv'
html_file_to_markdown('nv')
else
bad_combo
end
elsif $options[:inputtype] == 'bookmark'
if $options[:outputtype] == 'md'
bookmark_to_markdown('md')
elsif $options[:outputtype] == 'nv'
bookmark_to_nv('nv')
else
bad_combo
end
elsif $options[:inputtype] == 'webarchiveurl'
if $options[:outputtype] == 'md'
webarchive_url_to_markdown('md')
elsif $options[:outputtype] == 'nv'
webarchive_url_to_nv('nv')
else
bad_combo
end
elsif $options[:inputtype] == 'webarchive'
if $options[:outputtype] == 'md'
webarchive_to_markdown('md')
elsif $options[:outputtype] == 'nv'
webarchive_to_nv('nv')
else
bad_combo
end
else
bad_combo
end
| ruby | BSD-2-Clause | 9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23 | 2026-01-04T15:39:44.665514Z | false |
skwp/dotfiles | https://github.com/skwp/dotfiles/blob/9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23/bin/yadr/vundle.rb | bin/yadr/vundle.rb | require 'fileutils'
module Vundle
@vundles_path = File.expand_path File.join(ENV['HOME'], '.vim', '.vundles.local')
def self.add_plugin_to_vundle(plugin_repo)
return if contains_vundle? plugin_repo
vundles = vundles_from_file
last_bundle_dir = vundles.rindex{ |line| line =~ /^Bundle / }
last_bundle_dir = last_bundle_dir ? last_bundle_dir+1 : 0
vundles.insert last_bundle_dir, "Bundle \"#{plugin_repo}\""
write_vundles_to_file vundles
end
def self.remove_plugin_from_vundle(plugin_repo)
vundles = vundles_from_file
deleted_value = vundles.reject!{ |line| line =~ /Bundle "#{plugin_repo}"/ }
write_vundles_to_file vundles
!deleted_value.nil?
end
def self.vundle_list
vundles_from_file.select{ |line| line =~ /^Bundle .*/ }.map{ |line| line.gsub(/Bundle "(.*)"/, '\1')}
end
def self.update_vundle
system "vim --noplugin -u #{ENV['HOME']}/.vim/vundles.vim -N \"+set hidden\" \"+syntax on\" \"+let g:session_autosave = 'no'\" +BundleClean +BundleInstall! +qall"
end
private
def self.contains_vundle?(vundle_name)
FileUtils.touch(@vundles_path) unless File.exists? @vundles_path
File.read(@vundles_path).include?(vundle_name)
end
def self.vundles_from_file
FileUtils.touch(@vundles_path) unless File.exists? @vundles_path
File.read(@vundles_path).split("\n")
end
def self.write_vundles_to_file(vundles)
FileUtils.cp(@vundles_path, "#{@vundles_path}.bak")
vundle_file = File.open(@vundles_path, "w")
vundle_file.write(vundles.join("\n"))
vundle_file.close
end
end
| ruby | BSD-2-Clause | 9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23 | 2026-01-04T15:39:44.665514Z | false |
skwp/dotfiles | https://github.com/skwp/dotfiles/blob/9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23/bin/yadr/default_libs.rb | bin/yadr/default_libs.rb | Dir[File.join(File.dirname(__FILE__),"lib/**/lib")].each {|dir| $LOAD_PATH << dir}
require 'git-style-binary/command'
$yadr = File.join(ENV['HOME'], ".yadr")
| ruby | BSD-2-Clause | 9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23 | 2026-01-04T15:39:44.665514Z | false |
skwp/dotfiles | https://github.com/skwp/dotfiles/blob/9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23/bin/yadr/lib/trollop-1.16.2/test/test_trollop.rb | bin/yadr/lib/trollop-1.16.2/test/test_trollop.rb | ## test/test_trollop.rb -- unit tests for trollop
## Author:: William Morgan (mailto: wmorgan-trollop@masanjin.net)
## Copyright:: Copyright 2007 William Morgan
## License:: GNU GPL version 2
require 'test/unit'
require 'stringio'
require 'trollop'
module Trollop
module Test
class Trollop < ::Test::Unit::TestCase
def setup
@p = Parser.new
end
def test_unknown_arguments
assert_raise(CommandlineError) { @p.parse(%w(--arg)) }
@p.opt "arg"
assert_nothing_raised { @p.parse(%w(--arg)) }
assert_raise(CommandlineError) { @p.parse(%w(--arg2)) }
end
def test_syntax_check
@p.opt "arg"
assert_nothing_raised { @p.parse(%w(--arg)) }
assert_nothing_raised { @p.parse(%w(arg)) }
assert_raise(CommandlineError) { @p.parse(%w(---arg)) }
assert_raise(CommandlineError) { @p.parse(%w(-arg)) }
end
def test_required_flags_are_required
@p.opt "arg", "desc", :required => true
@p.opt "arg2", "desc", :required => false
@p.opt "arg3", "desc", :required => false
assert_nothing_raised { @p.parse(%w(--arg)) }
assert_nothing_raised { @p.parse(%w(--arg --arg2)) }
assert_raise(CommandlineError) { @p.parse(%w(--arg2)) }
assert_raise(CommandlineError) { @p.parse(%w(--arg2 --arg3)) }
end
## flags that take an argument error unless given one
def test_argflags_demand_args
@p.opt "goodarg", "desc", :type => String
@p.opt "goodarg2", "desc", :type => String
assert_nothing_raised { @p.parse(%w(--goodarg goat)) }
assert_raise(CommandlineError) { @p.parse(%w(--goodarg --goodarg2 goat)) }
assert_raise(CommandlineError) { @p.parse(%w(--goodarg)) }
end
## flags that don't take arguments ignore them
def test_arglessflags_refuse_args
@p.opt "goodarg"
@p.opt "goodarg2"
assert_nothing_raised { @p.parse(%w(--goodarg)) }
assert_nothing_raised { @p.parse(%w(--goodarg --goodarg2)) }
opts = @p.parse %w(--goodarg a)
assert_equal true, opts["goodarg"]
assert_equal ["a"], @p.leftovers
end
## flags that require args of a specific type refuse args of other
## types
def test_typed_args_refuse_args_of_other_types
assert_nothing_raised { @p.opt "goodarg", "desc", :type => :int }
assert_raise(ArgumentError) { @p.opt "badarg", "desc", :type => :asdf }
assert_nothing_raised { @p.parse(%w(--goodarg 3)) }
assert_raise(CommandlineError) { @p.parse(%w(--goodarg 4.2)) }
assert_raise(CommandlineError) { @p.parse(%w(--goodarg hello)) }
end
## type is correctly derived from :default
def test_type_correctly_derived_from_default
assert_raise(ArgumentError) { @p.opt "badarg", "desc", :default => [] }
opts = nil
# single arg: int
assert_nothing_raised { @p.opt "argsi", "desc", :default => 0 }
assert_nothing_raised { opts = @p.parse(%w(--)) }
assert_equal 0, opts["argsi"]
assert_nothing_raised { opts = @p.parse(%w(--argsi 4)) }
assert_equal 4, opts["argsi"]
assert_raise(CommandlineError) { @p.parse(%w(--argsi 4.2)) }
assert_raise(CommandlineError) { @p.parse(%w(--argsi hello)) }
# single arg: float
assert_nothing_raised { @p.opt "argsf", "desc", :default => 3.14 }
assert_nothing_raised { opts = @p.parse(%w(--)) }
assert_equal 3.14, opts["argsf"]
assert_nothing_raised { opts = @p.parse(%w(--argsf 2.41)) }
assert_equal 2.41, opts["argsf"]
assert_nothing_raised { opts = @p.parse(%w(--argsf 2)) }
assert_equal 2, opts["argsf"]
assert_nothing_raised { opts = @p.parse(%w(--argsf 1.0e-2)) }
assert_equal 1.0e-2, opts["argsf"]
assert_raise(CommandlineError) { @p.parse(%w(--argsf hello)) }
# single arg: date
date = Date.today
assert_nothing_raised { @p.opt "argsd", "desc", :default => date }
assert_nothing_raised { opts = @p.parse(%w(--)) }
assert_equal Date.today, opts["argsd"]
assert_nothing_raised { opts = @p.parse(['--argsd', 'Jan 4, 2007']) }
assert_equal Date.civil(2007, 1, 4), opts["argsd"]
assert_raise(CommandlineError) { @p.parse(%w(--argsd hello)) }
# single arg: string
assert_nothing_raised { @p.opt "argss", "desc", :default => "foobar" }
assert_nothing_raised { opts = @p.parse(%w(--)) }
assert_equal "foobar", opts["argss"]
assert_nothing_raised { opts = @p.parse(%w(--argss 2.41)) }
assert_equal "2.41", opts["argss"]
assert_nothing_raised { opts = @p.parse(%w(--argss hello)) }
assert_equal "hello", opts["argss"]
# multi args: ints
assert_nothing_raised { @p.opt "argmi", "desc", :default => [3, 5] }
assert_nothing_raised { opts = @p.parse(%w(--)) }
assert_equal [3, 5], opts["argmi"]
assert_nothing_raised { opts = @p.parse(%w(--argmi 4)) }
assert_equal [4], opts["argmi"]
assert_raise(CommandlineError) { @p.parse(%w(--argmi 4.2)) }
assert_raise(CommandlineError) { @p.parse(%w(--argmi hello)) }
# multi args: floats
assert_nothing_raised { @p.opt "argmf", "desc", :default => [3.34, 5.21] }
assert_nothing_raised { opts = @p.parse(%w(--)) }
assert_equal [3.34, 5.21], opts["argmf"]
assert_nothing_raised { opts = @p.parse(%w(--argmf 2)) }
assert_equal [2], opts["argmf"]
assert_nothing_raised { opts = @p.parse(%w(--argmf 4.0)) }
assert_equal [4.0], opts["argmf"]
assert_raise(CommandlineError) { @p.parse(%w(--argmf hello)) }
# multi args: dates
dates = [Date.today, Date.civil(2007, 1, 4)]
assert_nothing_raised { @p.opt "argmd", "desc", :default => dates }
assert_nothing_raised { opts = @p.parse(%w(--)) }
assert_equal dates, opts["argmd"]
assert_nothing_raised { opts = @p.parse(['--argmd', 'Jan 4, 2007']) }
assert_equal [Date.civil(2007, 1, 4)], opts["argmd"]
assert_raise(CommandlineError) { @p.parse(%w(--argmd hello)) }
# multi args: strings
assert_nothing_raised { @p.opt "argmst", "desc", :default => %w(hello world) }
assert_nothing_raised { opts = @p.parse(%w(--)) }
assert_equal %w(hello world), opts["argmst"]
assert_nothing_raised { opts = @p.parse(%w(--argmst 3.4)) }
assert_equal ["3.4"], opts["argmst"]
assert_nothing_raised { opts = @p.parse(%w(--argmst goodbye)) }
assert_equal ["goodbye"], opts["argmst"]
end
## :type and :default must match if both are specified
def test_type_and_default_must_match
assert_raise(ArgumentError) { @p.opt "badarg", "desc", :type => :int, :default => "hello" }
assert_raise(ArgumentError) { @p.opt "badarg2", "desc", :type => :String, :default => 4 }
assert_raise(ArgumentError) { @p.opt "badarg2", "desc", :type => :String, :default => ["hi"] }
assert_raise(ArgumentError) { @p.opt "badarg2", "desc", :type => :ints, :default => [3.14] }
assert_nothing_raised { @p.opt "argsi", "desc", :type => :int, :default => 4 }
assert_nothing_raised { @p.opt "argsf", "desc", :type => :float, :default => 3.14 }
assert_nothing_raised { @p.opt "argsd", "desc", :type => :date, :default => Date.today }
assert_nothing_raised { @p.opt "argss", "desc", :type => :string, :default => "yo" }
assert_nothing_raised { @p.opt "argmi", "desc", :type => :ints, :default => [4] }
assert_nothing_raised { @p.opt "argmf", "desc", :type => :floats, :default => [3.14] }
assert_nothing_raised { @p.opt "argmd", "desc", :type => :dates, :default => [Date.today] }
assert_nothing_raised { @p.opt "argmst", "desc", :type => :strings, :default => ["yo"] }
end
def test_long_detects_bad_names
assert_nothing_raised { @p.opt "goodarg", "desc", :long => "none" }
assert_nothing_raised { @p.opt "goodarg2", "desc", :long => "--two" }
assert_raise(ArgumentError) { @p.opt "badarg", "desc", :long => "" }
assert_raise(ArgumentError) { @p.opt "badarg2", "desc", :long => "--" }
assert_raise(ArgumentError) { @p.opt "badarg3", "desc", :long => "-one" }
assert_raise(ArgumentError) { @p.opt "badarg4", "desc", :long => "---toomany" }
end
def test_short_detects_bad_names
assert_nothing_raised { @p.opt "goodarg", "desc", :short => "a" }
assert_nothing_raised { @p.opt "goodarg2", "desc", :short => "-b" }
assert_raise(ArgumentError) { @p.opt "badarg", "desc", :short => "" }
assert_raise(ArgumentError) { @p.opt "badarg2", "desc", :short => "-ab" }
assert_raise(ArgumentError) { @p.opt "badarg3", "desc", :short => "--t" }
end
def test_short_names_created_automatically
@p.opt "arg"
@p.opt "arg2"
@p.opt "arg3"
opts = @p.parse %w(-a -g)
assert_equal true, opts["arg"]
assert_equal false, opts["arg2"]
assert_equal true, opts["arg3"]
end
def test_short_autocreation_skips_dashes_and_numbers
@p.opt :arg # auto: a
@p.opt :arg_potato # auto: r
@p.opt :arg_muffin # auto: g
assert_nothing_raised { @p.opt :arg_daisy } # auto: d (not _)!
assert_nothing_raised { @p.opt :arg_r2d2f } # auto: f (not 2)!
opts = @p.parse %w(-f -d)
assert_equal true, opts[:arg_daisy]
assert_equal true, opts[:arg_r2d2f]
assert_equal false, opts[:arg]
assert_equal false, opts[:arg_potato]
assert_equal false, opts[:arg_muffin]
end
def test_short_autocreation_is_ok_with_running_out_of_chars
@p.opt :arg1 # auto: a
@p.opt :arg2 # auto: r
@p.opt :arg3 # auto: g
@p.opt :arg4 # auto: uh oh!
assert_nothing_raised { @p.parse [] }
end
def test_short_can_be_nothing
assert_nothing_raised do
@p.opt "arg", "desc", :short => :none
@p.parse []
end
sio = StringIO.new "w"
@p.educate sio
assert sio.string =~ /--arg:\s+desc/
assert_raise(CommandlineError) { @p.parse %w(-a) }
end
## two args can't have the same name
def test_conflicting_names_are_detected
assert_nothing_raised { @p.opt "goodarg" }
assert_raise(ArgumentError) { @p.opt "goodarg" }
end
## two args can't have the same :long
def test_conflicting_longs_detected
assert_nothing_raised { @p.opt "goodarg", "desc", :long => "--goodarg" }
assert_raise(ArgumentError) { @p.opt "badarg", "desc", :long => "--goodarg" }
end
## two args can't have the same :short
def test_conflicting_shorts_detected
assert_nothing_raised { @p.opt "goodarg", "desc", :short => "-g" }
assert_raise(ArgumentError) { @p.opt "badarg", "desc", :short => "-g" }
end
def test_flag_defaults
@p.opt "defaultfalse", "desc"
@p.opt "defaulttrue", "desc", :default => true
opts = @p.parse []
assert_equal false, opts["defaultfalse"]
assert_equal true, opts["defaulttrue"]
opts = @p.parse %w(--defaultfalse --defaulttrue)
assert_equal true, opts["defaultfalse"]
assert_equal false, opts["defaulttrue"]
end
def test_special_flags_work
@p.version "asdf fdas"
assert_raise(VersionNeeded) { @p.parse(%w(-v)) }
assert_raise(HelpNeeded) { @p.parse(%w(-h)) }
end
def test_short_options_combine
@p.opt :arg1, "desc", :short => "a"
@p.opt :arg2, "desc", :short => "b"
@p.opt :arg3, "desc", :short => "c", :type => :int
opts = nil
assert_nothing_raised { opts = @p.parse %w(-a -b) }
assert_equal true, opts[:arg1]
assert_equal true, opts[:arg2]
assert_equal nil, opts[:arg3]
assert_nothing_raised { opts = @p.parse %w(-ab) }
assert_equal true, opts[:arg1]
assert_equal true, opts[:arg2]
assert_equal nil, opts[:arg3]
assert_nothing_raised { opts = @p.parse %w(-ac 4 -b) }
assert_equal true, opts[:arg1]
assert_equal true, opts[:arg2]
assert_equal 4, opts[:arg3]
assert_raises(CommandlineError) { @p.parse %w(-cab 4) }
assert_raises(CommandlineError) { @p.parse %w(-cba 4) }
end
def test_version_only_appears_if_set
@p.opt "arg"
assert_raise(CommandlineError) { @p.parse %w(-v) }
@p.version "trollop 1.2.3.4"
assert_raise(VersionNeeded) { @p.parse %w(-v) }
end
def test_doubledash_ends_option_processing
@p.opt :arg1, "desc", :short => "a", :default => 0
@p.opt :arg2, "desc", :short => "b", :default => 0
opts = nil
assert_nothing_raised { opts = @p.parse %w(-- -a 3 -b 2) }
assert_equal opts[:arg1], 0
assert_equal opts[:arg2], 0
assert_equal %w(-a 3 -b 2), @p.leftovers
assert_nothing_raised { opts = @p.parse %w(-a 3 -- -b 2) }
assert_equal opts[:arg1], 3
assert_equal opts[:arg2], 0
assert_equal %w(-b 2), @p.leftovers
assert_nothing_raised { opts = @p.parse %w(-a 3 -b 2 --) }
assert_equal opts[:arg1], 3
assert_equal opts[:arg2], 2
assert_equal %w(), @p.leftovers
end
def test_wrap
assert_equal [""], @p.wrap("")
assert_equal ["a"], @p.wrap("a")
assert_equal ["one two", "three"], @p.wrap("one two three", :width => 8)
assert_equal ["one two three"], @p.wrap("one two three", :width => 80)
assert_equal ["one", "two", "three"], @p.wrap("one two three", :width => 3)
assert_equal ["onetwothree"], @p.wrap("onetwothree", :width => 3)
assert_equal [
"Test is an awesome program that does something very, very important.",
"",
"Usage:",
" test [options] <filenames>+",
"where [options] are:"], @p.wrap(<<EOM, :width => 100)
Test is an awesome program that does something very, very important.
Usage:
test [options] <filenames>+
where [options] are:
EOM
end
def test_floating_point_formatting
@p.opt :arg, "desc", :type => :float, :short => "f"
opts = nil
assert_nothing_raised { opts = @p.parse %w(-f 1) }
assert_equal 1.0, opts[:arg]
assert_nothing_raised { opts = @p.parse %w(-f 1.0) }
assert_equal 1.0, opts[:arg]
assert_nothing_raised { opts = @p.parse %w(-f 0.1) }
assert_equal 0.1, opts[:arg]
assert_nothing_raised { opts = @p.parse %w(-f .1) }
assert_equal 0.1, opts[:arg]
assert_nothing_raised { opts = @p.parse %w(-f .99999999999999999999) }
assert_equal 1.0, opts[:arg]
assert_nothing_raised { opts = @p.parse %w(-f -1) }
assert_equal(-1.0, opts[:arg])
assert_nothing_raised { opts = @p.parse %w(-f -1.0) }
assert_equal(-1.0, opts[:arg])
assert_nothing_raised { opts = @p.parse %w(-f -0.1) }
assert_equal(-0.1, opts[:arg])
assert_nothing_raised { opts = @p.parse %w(-f -.1) }
assert_equal(-0.1, opts[:arg])
assert_raises(CommandlineError) { @p.parse %w(-f a) }
assert_raises(CommandlineError) { @p.parse %w(-f 1a) }
assert_raises(CommandlineError) { @p.parse %w(-f 1.a) }
assert_raises(CommandlineError) { @p.parse %w(-f a.1) }
assert_raises(CommandlineError) { @p.parse %w(-f 1.0.0) }
assert_raises(CommandlineError) { @p.parse %w(-f .) }
assert_raises(CommandlineError) { @p.parse %w(-f -.) }
end
def test_date_formatting
@p.opt :arg, "desc", :type => :date, :short => 'd'
opts = nil
assert_nothing_raised { opts = @p.parse(['-d', 'Jan 4, 2007']) }
assert_equal Date.civil(2007, 1, 4), opts[:arg]
begin
require 'chronic'
assert_nothing_raised { opts = @p.parse(['-d', 'today']) }
assert_equal Date.today, opts[:arg]
rescue LoadError
# chronic is not available
end
end
def test_short_options_cant_be_numeric
assert_raises(ArgumentError) { @p.opt :arg, "desc", :short => "-1" }
@p.opt :a1b, "desc"
@p.opt :a2b, "desc"
assert_not_equal "2", @p.specs[:a2b][:short]
end
def test_short_options_can_be_weird
assert_nothing_raised { @p.opt :arg1, "desc", :short => "#" }
assert_nothing_raised { @p.opt :arg2, "desc", :short => "." }
assert_raises(ArgumentError) { @p.opt :arg3, "desc", :short => "-" }
end
def test_options_cant_be_set_multiple_times_if_not_specified
@p.opt :arg, "desc", :short => "-x"
assert_nothing_raised { @p.parse %w(-x) }
assert_raises(CommandlineError) { @p.parse %w(-x -x) }
assert_raises(CommandlineError) { @p.parse %w(-xx) }
end
def test_options_can_be_set_multiple_times_if_specified
assert_nothing_raised do
@p.opt :arg, "desc", :short => "-x", :multi => true
end
assert_nothing_raised { @p.parse %w(-x) }
assert_nothing_raised { @p.parse %w(-x -x) }
assert_nothing_raised { @p.parse %w(-xx) }
end
def test_short_options_with_multiple_options
opts = nil
assert_nothing_raised do
@p.opt :xarg, "desc", :short => "-x", :type => String, :multi => true
end
assert_nothing_raised { opts = @p.parse %w(-x a -x b) }
assert_equal %w(a b), opts[:xarg]
assert_equal [], @p.leftovers
end
def short_options_with_multiple_options_does_not_affect_flags_type
opts = nil
assert_nothing_raised do
@p.opt :xarg, "desc", :short => "-x", :type => :flag, :multi => true
end
assert_nothing_raised { opts = @p.parse %w(-x a) }
assert_equal true, opts[:xarg]
assert_equal %w(a), @p.leftovers
assert_nothing_raised { opts = @p.parse %w(-x a -x b) }
assert_equal true, opts[:xarg]
assert_equal %w(a b), @p.leftovers
assert_nothing_raised { opts = @p.parse %w(-xx a -x b) }
assert_equal true, opts[:xarg]
assert_equal %w(a b), @p.leftovers
end
def test_short_options_with_multiple_arguments
opts = nil
@p.opt :xarg, "desc", :type => :ints
assert_nothing_raised { opts = @p.parse %w(-x 3 4 0) }
assert_equal [3, 4, 0], opts[:xarg]
assert_equal [], @p.leftovers
@p.opt :yarg, "desc", :type => :floats
assert_nothing_raised { opts = @p.parse %w(-y 3.14 4.21 0.66) }
assert_equal [3.14, 4.21, 0.66], opts[:yarg]
assert_equal [], @p.leftovers
@p.opt :zarg, "desc", :type => :strings
assert_nothing_raised { opts = @p.parse %w(-z a b c) }
assert_equal %w(a b c), opts[:zarg]
assert_equal [], @p.leftovers
end
def test_short_options_with_multiple_options_and_arguments
opts = nil
@p.opt :xarg, "desc", :type => :ints, :multi => true
assert_nothing_raised { opts = @p.parse %w(-x 3 4 5 -x 6 7) }
assert_equal [[3, 4, 5], [6, 7]], opts[:xarg]
assert_equal [], @p.leftovers
@p.opt :yarg, "desc", :type => :floats, :multi => true
assert_nothing_raised { opts = @p.parse %w(-y 3.14 4.21 5.66 -y 6.99 7.01) }
assert_equal [[3.14, 4.21, 5.66], [6.99, 7.01]], opts[:yarg]
assert_equal [], @p.leftovers
@p.opt :zarg, "desc", :type => :strings, :multi => true
assert_nothing_raised { opts = @p.parse %w(-z a b c -z d e) }
assert_equal [%w(a b c), %w(d e)], opts[:zarg]
assert_equal [], @p.leftovers
end
def test_combined_short_options_with_multiple_arguments
@p.opt :arg1, "desc", :short => "a"
@p.opt :arg2, "desc", :short => "b"
@p.opt :arg3, "desc", :short => "c", :type => :ints
@p.opt :arg4, "desc", :short => "d", :type => :floats
opts = nil
assert_nothing_raised { opts = @p.parse %w(-abc 4 6 9) }
assert_equal true, opts[:arg1]
assert_equal true, opts[:arg2]
assert_equal [4, 6, 9], opts[:arg3]
assert_nothing_raised { opts = @p.parse %w(-ac 4 6 9 -bd 3.14 2.41) }
assert_equal true, opts[:arg1]
assert_equal true, opts[:arg2]
assert_equal [4, 6, 9], opts[:arg3]
assert_equal [3.14, 2.41], opts[:arg4]
assert_raises(CommandlineError) { opts = @p.parse %w(-abcd 3.14 2.41) }
end
def test_long_options_with_multiple_options
@p.opt :xarg, "desc", :type => String, :multi => true
opts = nil
assert_nothing_raised { opts = @p.parse %w(--xarg=a --xarg=b) }
assert_equal %w(a b), opts[:xarg]
assert_equal [], @p.leftovers
assert_nothing_raised { opts = @p.parse %w(--xarg a --xarg b) }
assert_equal %w(a b), opts[:xarg]
assert_equal [], @p.leftovers
end
def test_long_options_with_multiple_arguments
opts = nil
@p.opt :xarg, "desc", :type => :ints
assert_nothing_raised { opts = @p.parse %w(--xarg 3 2 5) }
assert_equal [3, 2, 5], opts[:xarg]
assert_equal [], @p.leftovers
assert_nothing_raised { opts = @p.parse %w(--xarg=3) }
assert_equal [3], opts[:xarg]
assert_equal [], @p.leftovers
@p.opt :yarg, "desc", :type => :floats
assert_nothing_raised { opts = @p.parse %w(--yarg 3.14 2.41 5.66) }
assert_equal [3.14, 2.41, 5.66], opts[:yarg]
assert_equal [], @p.leftovers
assert_nothing_raised { opts = @p.parse %w(--yarg=3.14) }
assert_equal [3.14], opts[:yarg]
assert_equal [], @p.leftovers
@p.opt :zarg, "desc", :type => :strings
assert_nothing_raised { opts = @p.parse %w(--zarg a b c) }
assert_equal %w(a b c), opts[:zarg]
assert_equal [], @p.leftovers
assert_nothing_raised { opts = @p.parse %w(--zarg=a) }
assert_equal %w(a), opts[:zarg]
assert_equal [], @p.leftovers
end
def test_long_options_with_multiple_options_and_arguments
opts = nil
@p.opt :xarg, "desc", :type => :ints, :multi => true
assert_nothing_raised { opts = @p.parse %w(--xarg 3 2 5 --xarg 2 1) }
assert_equal [[3, 2, 5], [2, 1]], opts[:xarg]
assert_equal [], @p.leftovers
assert_nothing_raised { opts = @p.parse %w(--xarg=3 --xarg=2) }
assert_equal [[3], [2]], opts[:xarg]
assert_equal [], @p.leftovers
@p.opt :yarg, "desc", :type => :floats, :multi => true
assert_nothing_raised { opts = @p.parse %w(--yarg 3.14 2.72 5 --yarg 2.41 1.41) }
assert_equal [[3.14, 2.72, 5], [2.41, 1.41]], opts[:yarg]
assert_equal [], @p.leftovers
assert_nothing_raised { opts = @p.parse %w(--yarg=3.14 --yarg=2.41) }
assert_equal [[3.14], [2.41]], opts[:yarg]
assert_equal [], @p.leftovers
@p.opt :zarg, "desc", :type => :strings, :multi => true
assert_nothing_raised { opts = @p.parse %w(--zarg a b c --zarg d e) }
assert_equal [%w(a b c), %w(d e)], opts[:zarg]
assert_equal [], @p.leftovers
assert_nothing_raised { opts = @p.parse %w(--zarg=a --zarg=d) }
assert_equal [%w(a), %w(d)], opts[:zarg]
assert_equal [], @p.leftovers
end
def test_long_options_also_take_equals
@p.opt :arg, "desc", :long => "arg", :type => String, :default => "hello"
opts = nil
assert_nothing_raised { opts = @p.parse %w() }
assert_equal "hello", opts[:arg]
assert_nothing_raised { opts = @p.parse %w(--arg goat) }
assert_equal "goat", opts[:arg]
assert_nothing_raised { opts = @p.parse %w(--arg=goat) }
assert_equal "goat", opts[:arg]
## actually, this next one is valid. empty string for --arg, and goat as a
## leftover.
## assert_raises(CommandlineError) { opts = @p.parse %w(--arg= goat) }
end
def test_auto_generated_long_names_convert_underscores_to_hyphens
@p.opt :hello_there
assert_equal "hello-there", @p.specs[:hello_there][:long]
end
def test_arguments_passed_through_block
@goat = 3
boat = 4
Parser.new(@goat) do |goat|
boat = goat
end
assert_equal @goat, boat
end
def test_help_has_default_banner
@p = Parser.new
sio = StringIO.new "w"
@p.parse []
@p.educate sio
help = sio.string.split "\n"
assert help[0] =~ /options/i
assert_equal 2, help.length # options, then -h
@p = Parser.new
@p.version "my version"
sio = StringIO.new "w"
@p.parse []
@p.educate sio
help = sio.string.split "\n"
assert help[0] =~ /my version/i
assert_equal 4, help.length # version, options, -h, -v
@p = Parser.new
@p.banner "my own banner"
sio = StringIO.new "w"
@p.parse []
@p.educate sio
help = sio.string.split "\n"
assert help[0] =~ /my own banner/i
assert_equal 2, help.length # banner, -h
end
def test_help_preserves_positions
@p.opt :zzz, "zzz"
@p.opt :aaa, "aaa"
sio = StringIO.new "w"
@p.educate sio
help = sio.string.split "\n"
assert help[1] =~ /zzz/
assert help[2] =~ /aaa/
end
def test_version_and_help_short_args_can_be_overridden
@p.opt :verbose, "desc", :short => "-v"
@p.opt :hello, "desc", :short => "-h"
@p.version "version"
assert_nothing_raised { @p.parse(%w(-v)) }
assert_raises(VersionNeeded) { @p.parse(%w(--version)) }
assert_nothing_raised { @p.parse(%w(-h)) }
assert_raises(HelpNeeded) { @p.parse(%w(--help)) }
end
def test_version_and_help_long_args_can_be_overridden
@p.opt :asdf, "desc", :long => "help"
@p.opt :asdf2, "desc2", :long => "version"
assert_nothing_raised { @p.parse %w() }
assert_nothing_raised { @p.parse %w(--help) }
assert_nothing_raised { @p.parse %w(--version) }
assert_nothing_raised { @p.parse %w(-h) }
assert_nothing_raised { @p.parse %w(-v) }
end
def test_version_and_help_override_errors
@p.opt :asdf, "desc", :type => String
@p.version "version"
assert_nothing_raised { @p.parse %w(--asdf goat) }
assert_raises(CommandlineError) { @p.parse %w(--asdf) }
assert_raises(HelpNeeded) { @p.parse %w(--asdf --help) }
assert_raises(VersionNeeded) { @p.parse %w(--asdf --version) }
end
def test_conflicts
@p.opt :one
assert_raises(ArgumentError) { @p.conflicts :one, :two }
@p.opt :two
assert_nothing_raised { @p.conflicts :one, :two }
assert_nothing_raised { @p.parse %w(--one) }
assert_nothing_raised { @p.parse %w(--two) }
assert_raises(CommandlineError) { opts = @p.parse %w(--one --two) }
@p.opt :hello
@p.opt :yellow
@p.opt :mellow
@p.opt :jello
@p.conflicts :hello, :yellow, :mellow, :jello
assert_raises(CommandlineError) { opts = @p.parse %w(--hello --yellow --mellow --jello) }
assert_raises(CommandlineError) { opts = @p.parse %w(--hello --mellow --jello) }
assert_raises(CommandlineError) { opts = @p.parse %w(--hello --jello) }
assert_nothing_raised { opts = @p.parse %w(--hello) }
assert_nothing_raised { opts = @p.parse %w(--jello) }
assert_nothing_raised { opts = @p.parse %w(--yellow) }
assert_nothing_raised { opts = @p.parse %w(--mellow) }
assert_nothing_raised { opts = @p.parse %w(--mellow --one) }
assert_nothing_raised { opts = @p.parse %w(--mellow --two) }
assert_raises(CommandlineError) { opts = @p.parse %w(--mellow --two --jello) }
assert_raises(CommandlineError) { opts = @p.parse %w(--one --mellow --two --jello) }
end
def test_conflict_error_messages
@p.opt :one
@p.opt "two"
@p.conflicts :one, "two"
begin
@p.parse %w(--one --two)
flunk "no error thrown"
rescue CommandlineError => e
assert_match(/--one/, e.message)
assert_match(/--two/, e.message)
end
end
def test_depends
@p.opt :one
assert_raises(ArgumentError) { @p.depends :one, :two }
@p.opt :two
assert_nothing_raised { @p.depends :one, :two }
assert_nothing_raised { opts = @p.parse %w(--one --two) }
assert_raises(CommandlineError) { @p.parse %w(--one) }
assert_raises(CommandlineError) { @p.parse %w(--two) }
@p.opt :hello
@p.opt :yellow
@p.opt :mellow
@p.opt :jello
@p.depends :hello, :yellow, :mellow, :jello
assert_nothing_raised { opts = @p.parse %w(--hello --yellow --mellow --jello) }
assert_raises(CommandlineError) { opts = @p.parse %w(--hello --mellow --jello) }
assert_raises(CommandlineError) { opts = @p.parse %w(--hello --jello) }
assert_raises(CommandlineError) { opts = @p.parse %w(--hello) }
assert_raises(CommandlineError) { opts = @p.parse %w(--mellow) }
assert_nothing_raised { opts = @p.parse %w(--hello --yellow --mellow --jello --one --two) }
assert_nothing_raised { opts = @p.parse %w(--hello --yellow --mellow --jello --one --two a b c) }
assert_raises(CommandlineError) { opts = @p.parse %w(--mellow --two --jello --one) }
end
def test_depend_error_messages
@p.opt :one
@p.opt "two"
@p.depends :one, "two"
assert_nothing_raised { @p.parse %w(--one --two) }
begin
@p.parse %w(--one)
flunk "no error thrown"
rescue CommandlineError => e
assert_match(/--one/, e.message)
assert_match(/--two/, e.message)
end
begin
@p.parse %w(--two)
flunk "no error thrown"
rescue CommandlineError => e
assert_match(/--one/, e.message)
assert_match(/--two/, e.message)
end
end
## courtesy neill zero
def test_two_required_one_missing_accuses_correctly
@p.opt "arg1", "desc1", :required => true
@p.opt "arg2", "desc2", :required => true
begin
@p.parse(%w(--arg1))
flunk "should have failed on a missing req"
rescue CommandlineError => e
assert e.message =~ /arg2/, "didn't mention arg2 in the error msg: #{e.message}"
end
begin
@p.parse(%w(--arg2))
flunk "should have failed on a missing req"
rescue CommandlineError => e
assert e.message =~ /arg1/, "didn't mention arg1 in the error msg: #{e.message}"
end
assert_nothing_raised { @p.parse(%w(--arg1 --arg2)) }
end
def test_stopwords_mixed
@p.opt "arg1", :default => false
@p.opt "arg2", :default => false
@p.stop_on %w(happy sad)
opts = @p.parse %w(--arg1 happy --arg2)
assert_equal true, opts["arg1"]
assert_equal false, opts["arg2"]
## restart parsing
@p.leftovers.shift
opts = @p.parse @p.leftovers
assert_equal false, opts["arg1"]
assert_equal true, opts["arg2"]
end
def test_stopwords_no_stopwords
@p.opt "arg1", :default => false
@p.opt "arg2", :default => false
@p.stop_on %w(happy sad)
opts = @p.parse %w(--arg1 --arg2)
assert_equal true, opts["arg1"]
assert_equal true, opts["arg2"]
## restart parsing
@p.leftovers.shift
opts = @p.parse @p.leftovers
assert_equal false, opts["arg1"]
assert_equal false, opts["arg2"]
end
def test_stopwords_multiple_stopwords
@p.opt "arg1", :default => false
@p.opt "arg2", :default => false
@p.stop_on %w(happy sad)
opts = @p.parse %w(happy sad --arg1 --arg2)
assert_equal false, opts["arg1"]
assert_equal false, opts["arg2"]
## restart parsing
@p.leftovers.shift
opts = @p.parse @p.leftovers
assert_equal false, opts["arg1"]
assert_equal false, opts["arg2"]
## restart parsing again
@p.leftovers.shift
opts = @p.parse @p.leftovers
assert_equal true, opts["arg1"]
assert_equal true, opts["arg2"]
end
def test_stopwords_with_short_args
@p.opt :global_option, "This is a global option", :short => "-g"
@p.stop_on %w(sub-command-1 sub-command-2)
global_opts = @p.parse %w(-g sub-command-1 -c)
cmd = @p.leftovers.shift
@q = Parser.new
@q.opt :cmd_option, "This is an option only for the subcommand", :short => "-c"
cmd_opts = @q.parse @p.leftovers
assert_equal true, global_opts[:global_option]
assert_nil global_opts[:cmd_option]
assert_equal true, cmd_opts[:cmd_option]
assert_nil cmd_opts[:global_option]
assert_equal cmd, "sub-command-1"
assert_equal @q.leftovers, []
end
def assert_parses_correctly(parser, commandline, expected_opts,
expected_leftovers)
opts = parser.parse commandline
assert_equal expected_opts, opts
assert_equal expected_leftovers, parser.leftovers
end
def test_unknown_subcommand
@p.opt :global_flag, "Global flag", :short => "-g", :type => :flag
@p.opt :global_param, "Global parameter", :short => "-p", :default => 5
@p.stop_on_unknown
expected_opts = { :global_flag => true, :help => false, :global_param => 5, :global_flag_given => true }
expected_leftovers = [ "my_subcommand", "-c" ]
assert_parses_correctly @p, %w(--global-flag my_subcommand -c), \
expected_opts, expected_leftovers
assert_parses_correctly @p, %w(-g my_subcommand -c), \
expected_opts, expected_leftovers
expected_opts = { :global_flag => false, :help => false, :global_param => 5, :global_param_given => true }
expected_leftovers = [ "my_subcommand", "-c" ]
assert_parses_correctly @p, %w(-p 5 my_subcommand -c), \
expected_opts, expected_leftovers
assert_parses_correctly @p, %w(--global-param 5 my_subcommand -c), \
expected_opts, expected_leftovers
end
def test_alternate_args
args = %w(-a -b -c)
opts = ::Trollop.options(args) do
opt :alpher, "Ralph Alpher", :short => "-a"
opt :bethe, "Hans Bethe", :short => "-b"
opt :gamow, "George Gamow", :short => "-c"
end
physicists_with_humor = [:alpher, :bethe, :gamow]
physicists_with_humor.each do |physicist|
assert_equal true, opts[physicist]
end
end
def test_io_arg_type
@p.opt :arg, "desc", :type => :io
@p.opt :arg2, "desc", :type => IO
@p.opt :arg3, "desc", :default => $stdout
opts = nil
assert_nothing_raised { opts = @p.parse() }
assert_equal $stdout, opts[:arg3]
assert_nothing_raised { opts = @p.parse %w(--arg /dev/null) }
assert_kind_of File, opts[:arg]
assert_equal "/dev/null", opts[:arg].path
#TODO: move to mocks
| ruby | BSD-2-Clause | 9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23 | 2026-01-04T15:39:44.665514Z | true |
skwp/dotfiles | https://github.com/skwp/dotfiles/blob/9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23/bin/yadr/lib/trollop-1.16.2/lib/trollop.rb | bin/yadr/lib/trollop-1.16.2/lib/trollop.rb | ## lib/trollop.rb -- trollop command-line processing library
## Author:: William Morgan (mailto: wmorgan-trollop@masanjin.net)
## Copyright:: Copyright 2007 William Morgan
## License:: the same terms as ruby itself
require 'date'
module Trollop
VERSION = "1.16.2"
## Thrown by Parser in the event of a commandline error. Not needed if
## you're using the Trollop::options entry.
class CommandlineError < StandardError; end
## Thrown by Parser if the user passes in '-h' or '--help'. Handled
## automatically by Trollop#options.
class HelpNeeded < StandardError; end
## Thrown by Parser if the user passes in '-h' or '--version'. Handled
## automatically by Trollop#options.
class VersionNeeded < StandardError; end
## Regex for floating point numbers
FLOAT_RE = /^-?((\d+(\.\d+)?)|(\.\d+))([eE][-+]?[\d]+)?$/
## Regex for parameters
PARAM_RE = /^-(-|\.$|[^\d\.])/
## The commandline parser. In typical usage, the methods in this class
## will be handled internally by Trollop::options. In this case, only the
## #opt, #banner and #version, #depends, and #conflicts methods will
## typically be called.
##
## If you want to instantiate this class yourself (for more complicated
## argument-parsing logic), call #parse to actually produce the output hash,
## and consider calling it from within
## Trollop::with_standard_exception_handling.
class Parser
## The set of values that indicate a flag option when passed as the
## +:type+ parameter of #opt.
FLAG_TYPES = [:flag, :bool, :boolean]
## The set of values that indicate a single-parameter (normal) option when
## passed as the +:type+ parameter of #opt.
##
## A value of +io+ corresponds to a readable IO resource, including
## a filename, URI, or the strings 'stdin' or '-'.
SINGLE_ARG_TYPES = [:int, :integer, :string, :double, :float, :io, :date]
## The set of values that indicate a multiple-parameter option (i.e., that
## takes multiple space-separated values on the commandline) when passed as
## the +:type+ parameter of #opt.
MULTI_ARG_TYPES = [:ints, :integers, :strings, :doubles, :floats, :ios, :dates]
## The complete set of legal values for the +:type+ parameter of #opt.
TYPES = FLAG_TYPES + SINGLE_ARG_TYPES + MULTI_ARG_TYPES
INVALID_SHORT_ARG_REGEX = /[\d-]/ #:nodoc:
## The values from the commandline that were not interpreted by #parse.
attr_reader :leftovers
## The complete configuration hashes for each option. (Mainly useful
## for testing.)
attr_reader :specs
## Initializes the parser, and instance-evaluates any block given.
def initialize *a, &b
@version = nil
@leftovers = []
@specs = {}
@long = {}
@short = {}
@order = []
@constraints = []
@stop_words = []
@stop_on_unknown = false
#instance_eval(&b) if b # can't take arguments
cloaker(&b).bind(self).call(*a) if b
end
## Define an option. +name+ is the option name, a unique identifier
## for the option that you will use internally, which should be a
## symbol or a string. +desc+ is a string description which will be
## displayed in help messages.
##
## Takes the following optional arguments:
##
## [+:long+] Specify the long form of the argument, i.e. the form with two dashes. If unspecified, will be automatically derived based on the argument name by turning the +name+ option into a string, and replacing any _'s by -'s.
## [+:short+] Specify the short form of the argument, i.e. the form with one dash. If unspecified, will be automatically derived from +name+.
## [+:type+] Require that the argument take a parameter or parameters of type +type+. For a single parameter, the value can be a member of +SINGLE_ARG_TYPES+, or a corresponding Ruby class (e.g. +Integer+ for +:int+). For multiple-argument parameters, the value can be any member of +MULTI_ARG_TYPES+ constant. If unset, the default argument type is +:flag+, meaning that the argument does not take a parameter. The specification of +:type+ is not necessary if a +:default+ is given.
## [+:default+] Set the default value for an argument. Without a default value, the hash returned by #parse (and thus Trollop::options) will have a +nil+ value for this key unless the argument is given on the commandline. The argument type is derived automatically from the class of the default value given, so specifying a +:type+ is not necessary if a +:default+ is given. (But see below for an important caveat when +:multi+: is specified too.) If the argument is a flag, and the default is set to +true+, then if it is specified on the the commandline the value will be +false+.
## [+:required+] If set to +true+, the argument must be provided on the commandline.
## [+:multi+] If set to +true+, allows multiple occurrences of the option on the commandline. Otherwise, only a single instance of the option is allowed. (Note that this is different from taking multiple parameters. See below.)
##
## Note that there are two types of argument multiplicity: an argument
## can take multiple values, e.g. "--arg 1 2 3". An argument can also
## be allowed to occur multiple times, e.g. "--arg 1 --arg 2".
##
## Arguments that take multiple values should have a +:type+ parameter
## drawn from +MULTI_ARG_TYPES+ (e.g. +:strings+), or a +:default:+
## value of an array of the correct type (e.g. [String]). The
## value of this argument will be an array of the parameters on the
## commandline.
##
## Arguments that can occur multiple times should be marked with
## +:multi+ => +true+. The value of this argument will also be an array.
## In contrast with regular non-multi options, if not specified on
## the commandline, the default value will be [], not nil.
##
## These two attributes can be combined (e.g. +:type+ => +:strings+,
## +:multi+ => +true+), in which case the value of the argument will be
## an array of arrays.
##
## There's one ambiguous case to be aware of: when +:multi+: is true and a
## +:default+ is set to an array (of something), it's ambiguous whether this
## is a multi-value argument as well as a multi-occurrence argument.
## In thise case, Trollop assumes that it's not a multi-value argument.
## If you want a multi-value, multi-occurrence argument with a default
## value, you must specify +:type+ as well.
def opt name, desc="", opts={}
raise ArgumentError, "you already have an argument named '#{name}'" if @specs.member? name
## fill in :type
opts[:type] = # normalize
case opts[:type]
when :boolean, :bool; :flag
when :integer; :int
when :integers; :ints
when :double; :float
when :doubles; :floats
when Class
case opts[:type].name
when 'TrueClass', 'FalseClass'; :flag
when 'String'; :string
when 'Integer'; :int
when 'Float'; :float
when 'IO'; :io
when 'Date'; :date
else
raise ArgumentError, "unsupported argument type '#{opts[:type].class.name}'"
end
when nil; nil
else
raise ArgumentError, "unsupported argument type '#{opts[:type]}'" unless TYPES.include?(opts[:type])
opts[:type]
end
## for options with :multi => true, an array default doesn't imply
## a multi-valued argument. for that you have to specify a :type
## as well. (this is how we disambiguate an ambiguous situation;
## see the docs for Parser#opt for details.)
disambiguated_default =
if opts[:multi] && opts[:default].is_a?(Array) && !opts[:type]
opts[:default].first
else
opts[:default]
end
type_from_default =
case disambiguated_default
when Integer; :int
when Numeric; :float
when TrueClass, FalseClass; :flag
when String; :string
when IO; :io
when Date; :date
when Array
if opts[:default].empty?
raise ArgumentError, "multiple argument type cannot be deduced from an empty array for '#{opts[:default][0].class.name}'"
end
case opts[:default][0] # the first element determines the types
when Integer; :ints
when Numeric; :floats
when String; :strings
when IO; :ios
when Date; :dates
else
raise ArgumentError, "unsupported multiple argument type '#{opts[:default][0].class.name}'"
end
when nil; nil
else
raise ArgumentError, "unsupported argument type '#{opts[:default].class.name}'"
end
raise ArgumentError, ":type specification and default type don't match (default type is #{type_from_default})" if opts[:type] && type_from_default && opts[:type] != type_from_default
opts[:type] = opts[:type] || type_from_default || :flag
## fill in :long
opts[:long] = opts[:long] ? opts[:long].to_s : name.to_s.gsub("_", "-")
opts[:long] =
case opts[:long]
when /^--([^-].*)$/
$1
when /^[^-]/
opts[:long]
else
raise ArgumentError, "invalid long option name #{opts[:long].inspect}"
end
raise ArgumentError, "long option name #{opts[:long].inspect} is already taken; please specify a (different) :long" if @long[opts[:long]]
## fill in :short
opts[:short] = opts[:short].to_s if opts[:short] unless opts[:short] == :none
opts[:short] = case opts[:short]
when /^-(.)$/; $1
when nil, :none, /^.$/; opts[:short]
else raise ArgumentError, "invalid short option name '#{opts[:short].inspect}'"
end
if opts[:short]
raise ArgumentError, "short option name #{opts[:short].inspect} is already taken; please specify a (different) :short" if @short[opts[:short]]
raise ArgumentError, "a short option name can't be a number or a dash" if opts[:short] =~ INVALID_SHORT_ARG_REGEX
end
## fill in :default for flags
opts[:default] = false if opts[:type] == :flag && opts[:default].nil?
## autobox :default for :multi (multi-occurrence) arguments
opts[:default] = [opts[:default]] if opts[:default] && opts[:multi] && !opts[:default].is_a?(Array)
## fill in :multi
opts[:multi] ||= false
opts[:desc] ||= desc
@long[opts[:long]] = name
@short[opts[:short]] = name if opts[:short] && opts[:short] != :none
@specs[name] = opts
@order << [:opt, name]
end
## Sets the version string. If set, the user can request the version
## on the commandline. Should probably be of the form "<program name>
## <version number>".
def version s=nil; @version = s if s; @version end
## Adds text to the help display. Can be interspersed with calls to
## #opt to build a multi-section help page.
def banner s; @order << [:text, s] end
alias :text :banner
## Marks two (or more!) options as requiring each other. Only handles
## undirected (i.e., mutual) dependencies. Directed dependencies are
## better modeled with Trollop::die.
def depends *syms
syms.each { |sym| raise ArgumentError, "unknown option '#{sym}'" unless @specs[sym] }
@constraints << [:depends, syms]
end
## Marks two (or more!) options as conflicting.
def conflicts *syms
syms.each { |sym| raise ArgumentError, "unknown option '#{sym}'" unless @specs[sym] }
@constraints << [:conflicts, syms]
end
## Defines a set of words which cause parsing to terminate when
## encountered, such that any options to the left of the word are
## parsed as usual, and options to the right of the word are left
## intact.
##
## A typical use case would be for subcommand support, where these
## would be set to the list of subcommands. A subsequent Trollop
## invocation would then be used to parse subcommand options, after
## shifting the subcommand off of ARGV.
def stop_on *words
@stop_words = [*words].flatten
end
## Similar to #stop_on, but stops on any unknown word when encountered
## (unless it is a parameter for an argument). This is useful for
## cases where you don't know the set of subcommands ahead of time,
## i.e., without first parsing the global options.
def stop_on_unknown
@stop_on_unknown = true
end
## Parses the commandline. Typically called by Trollop::options,
## but you can call it directly if you need more control.
##
## throws CommandlineError, HelpNeeded, and VersionNeeded exceptions.
def parse cmdline=ARGV
vals = {}
required = {}
opt :version, "Print version and exit" if @version unless @specs[:version] || @long["version"]
opt :help, "Show this message" unless @specs[:help] || @long["help"]
@specs.each do |sym, opts|
required[sym] = true if opts[:required]
vals[sym] = opts[:default]
vals[sym] = [] if opts[:multi] && !opts[:default] # multi arguments default to [], not nil
end
resolve_default_short_options
## resolve symbols
given_args = {}
@leftovers = each_arg cmdline do |arg, params|
sym = case arg
when /^-([^-])$/
@short[$1]
when /^--([^-]\S*)$/
@long[$1]
else
raise CommandlineError, "invalid argument syntax: '#{arg}'"
end
raise CommandlineError, "unknown argument '#{arg}'" unless sym
if given_args.include?(sym) && !@specs[sym][:multi]
raise CommandlineError, "option '#{arg}' specified multiple times"
end
given_args[sym] ||= {}
given_args[sym][:arg] = arg
given_args[sym][:params] ||= []
# The block returns the number of parameters taken.
num_params_taken = 0
unless params.nil?
if SINGLE_ARG_TYPES.include?(@specs[sym][:type])
given_args[sym][:params] << params[0, 1] # take the first parameter
num_params_taken = 1
elsif MULTI_ARG_TYPES.include?(@specs[sym][:type])
given_args[sym][:params] << params # take all the parameters
num_params_taken = params.size
end
end
num_params_taken
end
## check for version and help args
raise VersionNeeded if given_args.include? :version
raise HelpNeeded if given_args.include? :help
## check constraint satisfaction
@constraints.each do |type, syms|
constraint_sym = syms.find { |sym| given_args[sym] }
next unless constraint_sym
case type
when :depends
syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym][:long]} requires --#{@specs[sym][:long]}" unless given_args.include? sym }
when :conflicts
syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym][:long]} conflicts with --#{@specs[sym][:long]}" if given_args.include?(sym) && (sym != constraint_sym) }
end
end
required.each do |sym, val|
raise CommandlineError, "option --#{@specs[sym][:long]} must be specified" unless given_args.include? sym
end
## parse parameters
given_args.each do |sym, given_data|
arg = given_data[:arg]
params = given_data[:params]
opts = @specs[sym]
raise CommandlineError, "option '#{arg}' needs a parameter" if params.empty? && opts[:type] != :flag
vals["#{sym}_given".intern] = true # mark argument as specified on the commandline
case opts[:type]
when :flag
vals[sym] = !opts[:default]
when :int, :ints
vals[sym] = params.map { |pg| pg.map { |p| parse_integer_parameter p, arg } }
when :float, :floats
vals[sym] = params.map { |pg| pg.map { |p| parse_float_parameter p, arg } }
when :string, :strings
vals[sym] = params.map { |pg| pg.map { |p| p.to_s } }
when :io, :ios
vals[sym] = params.map { |pg| pg.map { |p| parse_io_parameter p, arg } }
when :date, :dates
vals[sym] = params.map { |pg| pg.map { |p| parse_date_parameter p, arg } }
end
if SINGLE_ARG_TYPES.include?(opts[:type])
unless opts[:multi] # single parameter
vals[sym] = vals[sym][0][0]
else # multiple options, each with a single parameter
vals[sym] = vals[sym].map { |p| p[0] }
end
elsif MULTI_ARG_TYPES.include?(opts[:type]) && !opts[:multi]
vals[sym] = vals[sym][0] # single option, with multiple parameters
end
# else: multiple options, with multiple parameters
end
## modify input in place with only those
## arguments we didn't process
cmdline.clear
@leftovers.each { |l| cmdline << l }
## allow openstruct-style accessors
class << vals
def method_missing(m, *args)
self[m] || self[m.to_s]
end
end
vals
end
def parse_date_parameter param, arg #:nodoc:
begin
begin
time = Chronic.parse(param)
rescue NameError
# chronic is not available
end
time ? Date.new(time.year, time.month, time.day) : Date.parse(param)
rescue ArgumentError => e
raise CommandlineError, "option '#{arg}' needs a date"
end
end
## Print the help message to +stream+.
def educate stream=$stdout
width # just calculate it now; otherwise we have to be careful not to
# call this unless the cursor's at the beginning of a line.
left = {}
@specs.each do |name, spec|
left[name] = "--#{spec[:long]}" +
(spec[:short] && spec[:short] != :none ? ", -#{spec[:short]}" : "") +
case spec[:type]
when :flag; ""
when :int; " <i>"
when :ints; " <i+>"
when :string; " <s>"
when :strings; " <s+>"
when :float; " <f>"
when :floats; " <f+>"
when :io; " <filename/uri>"
when :ios; " <filename/uri+>"
when :date; " <date>"
when :dates; " <date+>"
end
end
leftcol_width = left.values.map { |s| s.length }.max || 0
rightcol_start = leftcol_width + 6 # spaces
unless @order.size > 0 && @order.first.first == :text
stream.puts "#@version\n" if @version
stream.puts "Options:"
end
@order.each do |what, opt|
if what == :text
stream.puts wrap(opt)
next
end
spec = @specs[opt]
stream.printf " %#{leftcol_width}s: ", left[opt]
desc = spec[:desc] + begin
default_s = case spec[:default]
when $stdout; "<stdout>"
when $stdin; "<stdin>"
when $stderr; "<stderr>"
when Array
spec[:default].join(", ")
else
spec[:default].to_s
end
if spec[:default]
if spec[:desc] =~ /\.$/
" (Default: #{default_s})"
else
" (default: #{default_s})"
end
else
""
end
end
stream.puts wrap(desc, :width => width - rightcol_start - 1, :prefix => rightcol_start)
end
end
def width #:nodoc:
@width ||= if $stdout.tty?
begin
require 'curses'
Curses::init_screen
x = Curses::cols
Curses::close_screen
x
rescue Exception
80
end
else
80
end
end
def wrap str, opts={} # :nodoc:
if str == ""
[""]
else
str.split("\n").map { |s| wrap_line s, opts }.flatten
end
end
## The per-parser version of Trollop::die (see that for documentation).
def die arg, msg
if msg
$stderr.puts "Error: argument --#{@specs[arg][:long]} #{msg}."
else
$stderr.puts "Error: #{arg}."
end
$stderr.puts "Try --help for help."
exit(-1)
end
private
## yield successive arg, parameter pairs
def each_arg args
remains = []
i = 0
until i >= args.length
if @stop_words.member? args[i]
remains += args[i .. -1]
return remains
end
case args[i]
when /^--$/ # arg terminator
remains += args[(i + 1) .. -1]
return remains
when /^--(\S+?)=(.*)$/ # long argument with equals
yield "--#{$1}", [$2]
i += 1
when /^--(\S+)$/ # long argument
params = collect_argument_parameters(args, i + 1)
unless params.empty?
num_params_taken = yield args[i], params
unless num_params_taken
if @stop_on_unknown
remains += args[i + 1 .. -1]
return remains
else
remains += params
end
end
i += 1 + num_params_taken
else # long argument no parameter
yield args[i], nil
i += 1
end
when /^-(\S+)$/ # one or more short arguments
shortargs = $1.split(//)
shortargs.each_with_index do |a, j|
if j == (shortargs.length - 1)
params = collect_argument_parameters(args, i + 1)
unless params.empty?
num_params_taken = yield "-#{a}", params
unless num_params_taken
if @stop_on_unknown
remains += args[i + 1 .. -1]
return remains
else
remains += params
end
end
i += 1 + num_params_taken
else # argument no parameter
yield "-#{a}", nil
i += 1
end
else
yield "-#{a}", nil
end
end
else
if @stop_on_unknown
remains += args[i .. -1]
return remains
else
remains << args[i]
i += 1
end
end
end
remains
end
def parse_integer_parameter param, arg
raise CommandlineError, "option '#{arg}' needs an integer" unless param =~ /^\d+$/
param.to_i
end
def parse_float_parameter param, arg
raise CommandlineError, "option '#{arg}' needs a floating-point number" unless param =~ FLOAT_RE
param.to_f
end
def parse_io_parameter param, arg
case param
when /^(stdin|-)$/i; $stdin
else
require 'open-uri'
begin
open param
rescue SystemCallError => e
raise CommandlineError, "file or url for option '#{arg}' cannot be opened: #{e.message}"
end
end
end
def collect_argument_parameters args, start_at
params = []
pos = start_at
while args[pos] && args[pos] !~ PARAM_RE && !@stop_words.member?(args[pos]) do
params << args[pos]
pos += 1
end
params
end
def resolve_default_short_options
@order.each do |type, name|
next unless type == :opt
opts = @specs[name]
next if opts[:short]
c = opts[:long].split(//).find { |d| d !~ INVALID_SHORT_ARG_REGEX && !@short.member?(d) }
if c # found a character to use
opts[:short] = c
@short[c] = name
end
end
end
def wrap_line str, opts={}
prefix = opts[:prefix] || 0
width = opts[:width] || (self.width - 1)
start = 0
ret = []
until start > str.length
nextt =
if start + width >= str.length
str.length
else
x = str.rindex(/\s/, start + width)
x = str.index(/\s/, start) if x && x < start
x || str.length
end
ret << (ret.empty? ? "" : " " * prefix) + str[start ... nextt]
start = nextt + 1
end
ret
end
## instance_eval but with ability to handle block arguments
## thanks to why: http://redhanded.hobix.com/inspect/aBlockCostume.html
def cloaker &b
(class << self; self; end).class_eval do
define_method :cloaker_, &b
meth = instance_method :cloaker_
remove_method :cloaker_
meth
end
end
end
## The easy, syntactic-sugary entry method into Trollop. Creates a Parser,
## passes the block to it, then parses +args+ with it, handling any errors or
## requests for help or version information appropriately (and then exiting).
## Modifies +args+ in place. Returns a hash of option values.
##
## The block passed in should contain zero or more calls to +opt+
## (Parser#opt), zero or more calls to +text+ (Parser#text), and
## probably a call to +version+ (Parser#version).
##
## The returned block contains a value for every option specified with
## +opt+. The value will be the value given on the commandline, or the
## default value if the option was not specified on the commandline. For
## every option specified on the commandline, a key "<option
## name>_given" will also be set in the hash.
##
## Example:
##
## require 'trollop'
## opts = Trollop::options do
## opt :monkey, "Use monkey mode" # a flag --monkey, defaulting to false
## opt :goat, "Use goat mode", :default => true # a flag --goat, defaulting to true
## opt :num_limbs, "Number of limbs", :default => 4 # an integer --num-limbs <i>, defaulting to 4
## opt :num_thumbs, "Number of thumbs", :type => :int # an integer --num-thumbs <i>, defaulting to nil
## end
##
## ## if called with no arguments
## p opts # => { :monkey => false, :goat => true, :num_limbs => 4, :num_thumbs => nil }
##
## ## if called with --monkey
## p opts # => {:monkey_given=>true, :monkey=>true, :goat=>true, :num_limbs=>4, :help=>false, :num_thumbs=>nil}
##
## See more examples at http://trollop.rubyforge.org.
def options args=ARGV, *a, &b
@last_parser = Parser.new(*a, &b)
with_standard_exception_handling(@last_parser) { @last_parser.parse args }
end
## If Trollop::options doesn't do quite what you want, you can create a Parser
## object and call Parser#parse on it. That method will throw CommandlineError,
## HelpNeeded and VersionNeeded exceptions when necessary; if you want to
## have these handled for you in the standard manner (e.g. show the help
## and then exit upon an HelpNeeded exception), call your code from within
## a block passed to this method.
##
## Note that this method will call System#exit after handling an exception!
##
## Usage example:
##
## require 'trollop'
## p = Trollop::Parser.new do
## opt :monkey, "Use monkey mode" # a flag --monkey, defaulting to false
## opt :goat, "Use goat mode", :default => true # a flag --goat, defaulting to true
## end
##
## opts = Trollop::with_standard_exception_handling p do
## p.parse ARGV
## raise Trollop::HelpNeeded if ARGV.empty? # show help screen
## end
##
## Requires passing in the parser object.
def with_standard_exception_handling parser
begin
yield
rescue CommandlineError => e
$stderr.puts "Error: #{e.message}."
$stderr.puts "Try --help for help."
exit(-1)
rescue HelpNeeded
parser.educate
exit
rescue VersionNeeded
puts parser.version
exit
end
end
## Informs the user that their usage of 'arg' was wrong, as detailed by
## 'msg', and dies. Example:
##
## options do
## opt :volume, :default => 0.0
## end
##
## die :volume, "too loud" if opts[:volume] > 10.0
## die :volume, "too soft" if opts[:volume] < 0.1
##
## In the one-argument case, simply print that message, a notice
## about -h, and die. Example:
##
## options do
## opt :whatever # ...
## end
##
## Trollop::die "need at least one filename" if ARGV.empty?
def die arg, msg=nil
if @last_parser
@last_parser.die arg, msg
else
raise ArgumentError, "Trollop::die can only be called after Trollop::options"
end
end
module_function :options, :die, :with_standard_exception_handling
end # module
| ruby | BSD-2-Clause | 9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23 | 2026-01-04T15:39:44.665514Z | false |
skwp/dotfiles | https://github.com/skwp/dotfiles/blob/9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23/bin/yadr/lib/git-style-binaries-0.1.11/test/test_helper.rb | bin/yadr/lib/git-style-binaries-0.1.11/test/test_helper.rb | require 'rubygems'
require 'test/unit'
require 'shoulda'
begin require 'redgreen'; rescue LoadError; end
require 'open3'
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
Dir[File.join(File.dirname(__FILE__), "shoulda_macros", "*.rb")].each {|f| require f}
ENV['NO_COLOR'] = "true"
require 'git-style-binary'
GitStyleBinary.run = true
class Test::Unit::TestCase
def fixtures_dir
File.join(File.dirname(__FILE__), "fixtures")
end
end
module RunsBinaryFixtures
# run the specified cmd returning the string values of [stdout,stderr]
def bin(cmd)
stdin, stdout, stderr = Open3.popen3("#{fixtures_dir}/#{cmd}")
[stdout.read, stderr.read]
end
end
| ruby | BSD-2-Clause | 9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23 | 2026-01-04T15:39:44.665514Z | false |
skwp/dotfiles | https://github.com/skwp/dotfiles/blob/9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23/bin/yadr/lib/git-style-binaries-0.1.11/test/git_style_binary_test.rb | bin/yadr/lib/git-style-binaries-0.1.11/test/git_style_binary_test.rb | require File.dirname(__FILE__) + "/test_helper.rb"
class GitStyleBinariesTest < Test::Unit::TestCase
context "parsing basenames" do
should "accurately parse basenames" do
assert_equal "wordpress", GitStyleBinary.basename("bin/wordpress")
assert_equal "wordpress", GitStyleBinary.basename("bin/wordpress-post")
assert_equal "wordpress", GitStyleBinary.basename("wordpress-post")
end
should "get the current command name" do
# doesn't really apply any more b/c it calls 'current' which is never the
# current when your running rake_test_loader.rb
#
# assert_equal "wordpress", GitStyleBinary.current_command_name("bin/wordpress", ["--help"])
# assert_equal "post", GitStyleBinary.current_command_name("bin/wordpress-post", ["--help"])
# assert_equal "post", GitStyleBinary.current_command_name("bin/wordpress post", ["--help"])
#assert_equal "post", GitStyleBinary.current_command_name("bin/wordpress post", [])
end
end
end
| ruby | BSD-2-Clause | 9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23 | 2026-01-04T15:39:44.665514Z | false |
skwp/dotfiles | https://github.com/skwp/dotfiles/blob/9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23/bin/yadr/lib/git-style-binaries-0.1.11/test/running_binaries_test.rb | bin/yadr/lib/git-style-binaries-0.1.11/test/running_binaries_test.rb | require File.dirname(__FILE__) + "/test_helper.rb"
THIS_YEAR=Time.now.year # todo
class RunningBinariesTest < Test::Unit::TestCase
include RunsBinaryFixtures
context "when running primary" do
["wordpress -h", "wordpress help"].each do |format|
context "and getting help as a '#{format}'" do
setup { @stdout, @stderr = bin(format) }
should "have the command name and short description" do
unless format == "wordpress -h" # doesn't apply to wordpress -h
output_matches /NAME\n\s*wordpress\-help \- get help for a specific command/m
end
end
should "have a local (not default) version string" do
output_matches /0\.0\.1 \(c\) 2009 Nate Murray - local/
end
should "get a list of subcommands" do
output_matches /subcommands/mi
end
should "have subcommand short descriptions" do
output_matches /post\s*create a blog post/
output_matches /categories\s*do something with categories/
output_matches /help\s*get help for a specific command/
output_matches /list\s*list blog postings/
end
should "have a usage" do
output_matches /SYNOPSIS/i
output_matches /wordpress(\-help)? \[/
end
should "be able to ask for help about help"
end
end
context "and getting help as subcommand" do
# ["wordpress -h", "wordpress help"].each do |format|
["wordpress help"].each do |format|
context "'#{format}'" do
should "get help on subcommand post"
end
end
end
context "with no options" do
setup { @stdout, @stderr = bin("wordpress") }
should "output the options" do
output_matches /Primary Options:/
end
should "have the test_primary option" do
output_matches /test_primary=>nil/
end
end
should "be able to require 'primary' and run just fine"
end
context "when running with an action" do
# should be the same for both formats
["wordpress-categories", "wordpress categories"].each do |bin_format|
context "#{bin_format}" do
context "with action block" do
setup { @stdout, @stderr = bin("#{bin_format}") }
should "have the parsed action items in the help output" do
output_matches /sports news/m
end
end
end
end
end
context "callbacks" do
context "on a binary" do
setup { @stdout, @stderr = bin("wordpress") }
%w(before after).each do |time|
should "run the callback #{time}_run}" do
assert @stdout.match(/#{time}_run command/)
end
end
end
context "on help" do
setup { @stdout, @stderr = bin("wordpress -h") }
%w(before after).each do |time|
should "not run the callback #{time}_run" do
assert_nil @stdout.match(/#{time}_run command/)
end
end
end
end
context "when running the subcommand" do
# should be the same for both formats
["wordpress-post", "wordpress post"].each do |bin_format|
context "#{bin_format}" do
context "with no options" do
setup { @stdout, @stderr = bin("#{bin_format}") }
should "fail because title is required" do
output_matches /Error: option 'title' must be specified.\s*Try --help for help/m
end
end
context "with options" do
setup { @stdout, @stderr = bin("#{bin_format} --title='glendale'") }
should "be running the subcommand's run block" do
output_matches /Subcommand name/
end
should "have some default options" do
output_matches /version=>false/
output_matches /help=>false/
end
should "have some primary options" do
output_matches /test_primary=>nil/
end
should "have some local options" do
output_matches /title=>"glendale"/
output_matches /type=>"html"/
end
end
context "testing die statements" do
setup { @stdout, @stderr = bin("#{bin_format} --title='glendale' --type=yaml") }
should "die on invalid options" do
output_matches /argument \-\-type type must be one of \[html\|xhtml\|text\]/
end
end
end # end bin_format
end # end #each
end
["wordpress help post", "wordpress post -h"].each do |format|
context "when calling '#{format}'" do
setup { @stdout, @stderr = bin(format) }
should "have a description" do
output_matches /create a blog post/
end
should "have the proper usage line" do
output_matches /SYNOPSIS\n\s*wordpress\-post/m
output_matches /\[--title\]/
end
should "have option flags" do
output_matches /\-\-title(.*)<s>/
end
should "have primary option flags" do
output_matches /\-\-test-primary(.*)<s>/
end
should "have default option flags" do
output_matches /\-\-verbose/
end
should "have trollop default option flags" do
output_matches /\-e, \-\-version/
end
should "have the correct binary name and short description" do
output_matches /NAME\n\s*wordpress\-post \- create a blog post/m
end
should "have a the primaries version string" do
output_matches /0\.0\.1 \(c\) 2009 Nate Murray - local/
end
should "have options" do
output_matches /Options/i
output_matches /\-b, \-\-blog=<s>/
output_matches /short name of the blog to use/
output_matches /-i, \-\-title=<s>/
output_matches /title for the post/
end
end
end
context "when running a bare primary" do
["flickr -h", "flickr help"].each do |format|
context format do
setup { @stdout, @stderr = bin(format) }
should "have the name and short description" do
unless format == "flickr -h" # hmm
output_matches /NAME\n\s*flickr\-help \- get help for a specific command/m
end
end
should "have a local (not default) version string" do
output_matches /0\.0\.2 \(c\) #{Time.now.year}/
end
end
end
["flickr-download -h", "flickr download -h"].each do |format|
context format do
setup { @stdout, @stderr = bin(format) }
should "match on usage" do
output_matches /SYNOPSIS\n\s*flickr\-download/m
end
end
end
end
end
| ruby | BSD-2-Clause | 9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23 | 2026-01-04T15:39:44.665514Z | false |
skwp/dotfiles | https://github.com/skwp/dotfiles/blob/9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23/bin/yadr/lib/git-style-binaries-0.1.11/test/shoulda_macros/matching_stdio.rb | bin/yadr/lib/git-style-binaries-0.1.11/test/shoulda_macros/matching_stdio.rb | class Test::Unit::TestCase
def output_should_match(regexp)
assert_match regexp, @stdout + @stderr
end
alias_method :output_matches, :output_should_match
def stdout_should_match(regexp)
assert_match regexp, @stdout
end
def stderr_should_match(regexp)
assert_match regexp, @stderr
end
end
| ruby | BSD-2-Clause | 9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23 | 2026-01-04T15:39:44.665514Z | false |
skwp/dotfiles | https://github.com/skwp/dotfiles/blob/9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23/bin/yadr/lib/git-style-binaries-0.1.11/test/git-style-binary/command_test.rb | bin/yadr/lib/git-style-binaries-0.1.11/test/git-style-binary/command_test.rb | require File.dirname(__FILE__) + "/../test_helper.rb"
require 'git-style-binary/command'
class CommandTest < Test::Unit::TestCase
context "cmd" do
setup do
@c = GitStyleBinary::Command.new
end
should "be able to easily work with constraints" do
assert_equal @c.constraints, []
@c.constraints << "foo"
assert_equal @c.constraints, ["foo"]
end
end
end
| ruby | BSD-2-Clause | 9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23 | 2026-01-04T15:39:44.665514Z | false |
skwp/dotfiles | https://github.com/skwp/dotfiles/blob/9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23/bin/yadr/lib/git-style-binaries-0.1.11/lib/git-style-binary.rb | bin/yadr/lib/git-style-binaries-0.1.11/lib/git-style-binary.rb | $:.unshift(File.dirname(__FILE__))
require 'rubygems'
# Load the vendor gems
$:.unshift(File.dirname(__FILE__) + "/../vendor/gems")
%w(trollop).each do |library|
begin
require "#{library}/lib/#{library}"
rescue LoadError
begin
require 'trollop'
rescue LoadError
puts "There was an error loading #{library}. Try running 'gem install #{library}' to correct the problem"
end
end
end
require 'ext/core'
require 'ext/colorize'
require 'git-style-binary/autorunner'
Dir[File.dirname(__FILE__) + "/git-style-binary/helpers/*.rb"].each {|f| require f}
module GitStyleBinary
class << self
include Helpers::NameResolver
attr_accessor :current_command
attr_accessor :primary_command
attr_writer :known_commands
# If set to false GitStyleBinary will not automatically run at exit.
attr_writer :run
# Automatically run at exit?
def run?
@run ||= false
end
def parser
@p ||= Parser.new
end
def known_commands
@known_commands ||= {}
end
def load_primary
unless @loaded_primary
@loaded_primary = true
primary_file = File.join(binary_directory, basename)
load primary_file
if !GitStyleBinary.primary_command # you still dont have a primary load a default
GitStyleBinary.primary do
run do |command|
educate
end
end
end
end
end
def load_subcommand
unless @loaded_subcommand
@loaded_subcommand = true
cmd_file = GitStyleBinary.binary_filename_for(GitStyleBinary.current_command_name)
load cmd_file
end
end
def load_command_file(name, file)
self.name_of_command_being_loaded = name
load file
self.name_of_command_being_loaded = nil
end
# UGLY eek
attr_accessor :name_of_command_being_loaded
end
end
at_exit do
unless $! || GitStyleBinary.run?
command = GitStyleBinary::AutoRunner.run
exit 0
end
end
| ruby | BSD-2-Clause | 9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23 | 2026-01-04T15:39:44.665514Z | false |
skwp/dotfiles | https://github.com/skwp/dotfiles/blob/9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23/bin/yadr/lib/git-style-binaries-0.1.11/lib/ext/core.rb | bin/yadr/lib/git-style-binaries-0.1.11/lib/ext/core.rb | class Object
def returning(value)
yield(value)
value
end unless Object.respond_to?(:returning)
end
class Symbol
def to_proc
Proc.new { |*args| args.shift.__send__(self, *args) }
end
end
class IO
attr_accessor :use_color
end
| ruby | BSD-2-Clause | 9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23 | 2026-01-04T15:39:44.665514Z | false |
skwp/dotfiles | https://github.com/skwp/dotfiles/blob/9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23/bin/yadr/lib/git-style-binaries-0.1.11/lib/ext/colorize.rb | bin/yadr/lib/git-style-binaries-0.1.11/lib/ext/colorize.rb | #
# Colorize String class extension.
#
class String
#
# Version string
#
COLORIZE_VERSION = '0.5.6'
#
# Colors Hash
#
COLORS = {
:black => 0,
:red => 1,
:green => 2,
:yellow => 3,
:blue => 4,
:magenta => 5,
:cyan => 6,
:white => 7,
:default => 9,
:light_black => 10,
:light_red => 11,
:light_green => 12,
:light_yellow => 13,
:light_blue => 14,
:light_magenta => 15,
:light_cyan => 16,
:light_white => 17
}
#
# Modes Hash
#
MODES = {
:default => 0, # Turn off all attributes
#:bright => 1, # Set bright mode
:underline => 4, # Set underline mode
:blink => 5, # Set blink mode
:swap => 7, # Exchange foreground and background colors
:hide => 8 # Hide text (foreground color would be the same as background)
}
protected
#
# Set color values in new string intance
#
def set_color_parameters( params )
if (params.instance_of?(Hash))
@color = params[:color]
@background = params[:background]
@mode = params[:mode]
@uncolorized = params[:uncolorized]
self
else
nil
end
end
public
#
# Change color of string
#
# Examples:
#
# puts "This is blue".colorize( :blue )
# puts "This is light blue".colorize( :light_blue )
# puts "This is also blue".colorize( :color => :blue )
# puts "This is blue with red background".colorize( :color => :light_blue, :background => :red )
# puts "This is blue with red background".colorize( :light_blue ).colorize( :background => :red )
# puts "This is blue text on red".blue.on_red
# puts "This is red on blue".colorize( :red ).on_blue
# puts "This is red on blue and underline".colorize( :red ).on_blue.underline
# puts "This is blue text on red".blue.on_red.blink
#
def colorize( params )
unless STDOUT.use_color
return self unless STDOUT.isatty
end
return self if ENV['NO_COLOR']
begin
require 'Win32/Console/ANSI' if RUBY_PLATFORM =~ /win32/
rescue LoadError
raise 'You must gem install win32console to use color on Windows'
end
color_parameters = {}
if (params.instance_of?(Hash))
color_parameters[:color] = COLORS[params[:color]]
color_parameters[:background] = COLORS[params[:background]]
color_parameters[:mode] = MODES[params[:mode]]
elsif (params.instance_of?(Symbol))
color_parameters[:color] = COLORS[params]
end
color_parameters[:color] ||= @color || 9
color_parameters[:background] ||= @background || 9
color_parameters[:mode] ||= @mode || 0
color_parameters[:uncolorized] ||= @uncolorized || self.dup
# calculate bright mode
color_parameters[:color] += 50 if color_parameters[:color] > 10
color_parameters[:background] += 50 if color_parameters[:background] > 10
return "\033[#{color_parameters[:mode]};#{color_parameters[:color]+30};#{color_parameters[:background]+40}m#{color_parameters[:uncolorized]}\033[0m".set_color_parameters( color_parameters )
end
#
# Return uncolorized string
#
def uncolorize
return @uncolorized || self
end
#
# Return true if sting is colorized
#
def colorized?
return !@uncolorized.nil?
end
#
# Make some color and on_color methods
#
COLORS.each_key do | key |
eval <<-"end_eval"
def #{key.to_s}
return self.colorize( :color => :#{key.to_s} )
end
def on_#{key.to_s}
return self.colorize( :background => :#{key.to_s} )
end
end_eval
end
#
# Methods for modes
#
MODES.each_key do | key |
eval <<-"end_eval"
def #{key.to_s}
return self.colorize( :mode => :#{key.to_s} )
end
end_eval
end
class << self
#
# Return array of available modes used by colorize method
#
def modes
keys = []
MODES.each_key do | key |
keys << key
end
keys
end
#
# Return array of available colors used by colorize method
#
def colors
keys = []
COLORS.each_key do | key |
keys << key
end
keys
end
#
# Display color matrix with color names.
#
def color_matrix( txt = "[X]" )
size = String.colors.length
String.colors.each do | color |
String.colors.each do | back |
print txt.colorize( :color => color, :background => back )
end
puts " < #{color}"
end
String.colors.reverse.each_with_index do | back, index |
puts "#{"|".rjust(txt.length)*(size-index)} < #{back}"
end
end
end
end
| ruby | BSD-2-Clause | 9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23 | 2026-01-04T15:39:44.665514Z | false |
skwp/dotfiles | https://github.com/skwp/dotfiles/blob/9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23/bin/yadr/lib/git-style-binaries-0.1.11/lib/git-style-binary/command.rb | bin/yadr/lib/git-style-binaries-0.1.11/lib/git-style-binary/command.rb | require 'git-style-binary'
module GitStyleBinary
def self.command(&block)
returning Command.new(:constraints => [block]) do |c|
c.name ||= (GitStyleBinary.name_of_command_being_loaded || GitStyleBinary.current_command_name)
GitStyleBinary.known_commands[c.name] = c
if !GitStyleBinary.current_command || GitStyleBinary.current_command.is_primary?
GitStyleBinary.current_command = c
end
end
end
def self.primary(&block)
returning Primary.new(:constraints => [block]) do |c|
c.name ||= (GitStyleBinary.name_of_command_being_loaded || GitStyleBinary.current_command_name)
GitStyleBinary.known_commands[c.name] = c
GitStyleBinary.primary_command = c unless GitStyleBinary.primary_command
GitStyleBinary.current_command = c unless GitStyleBinary.current_command
end
end
class Command
class << self
def defaults
lambda do
name_desc "#{command.full_name}\#{command.short_desc ? ' - ' + command.short_desc : ''}" # eval jit
version_string = defined?(VERSION) ? VERSION : "0.0.1"
version "#{version_string} (c) #{Time.now.year}"
banner <<-EOS
#{"SYNOPSIS".colorize(:red)}
#{command.full_name.colorize(:light_blue)} #{all_options_string}
#{"SUBCOMMANDS".colorize(:red)}
\#{GitStyleBinary.pretty_known_subcommands.join("\n ")}
See '#{command.full_name} help COMMAND' for more information on a specific command.
EOS
opt :verbose, "verbose", :default => false
end
end
end
attr_reader :constraints
attr_reader :opts
attr_accessor :name
def initialize(o={})
o.each do |k,v|
eval "@#{k.to_s}= v"
end
end
def parser
@parser ||= begin
p = Parser.new
p.command = self
p
end
end
def constraints
@constraints ||= []
end
def run
GitStyleBinary.load_primary unless is_primary?
GitStyleBinary.load_subcommand if is_primary? && running_subcommand?
load_all_parser_constraints
@opts = process_args_with_subcmd
call_parser_run_block
self
end
def running_subcommand?
GitStyleBinary.valid_subcommand?(GitStyleBinary.current_command_name)
end
def load_all_parser_constraints
@loaded_all_parser_constraints ||= begin
load_parser_default_constraints
load_parser_primary_constraints
load_parser_local_constraints
true
end
end
def load_parser_default_constraints
parser.consume_all([self.class.defaults])
end
def load_parser_primary_constraints
parser.consume_all(GitStyleBinary.primary_command.constraints)
end
def load_parser_local_constraints
cur = GitStyleBinary.current_command # see, why isn't 'this' current_command?
unless self.is_primary? && cur == self
# TODO TODO - the key lies in this function. figure out when you hav emore engergy
# soo UGLY. see #process_parser! unify with that method
# parser.consume_all(constraints) rescue ArgumentError
parser.consume_all(cur.constraints)
end
end
def call_parser_run_block
runs = GitStyleBinary.current_command.parser.runs
parser.run_callbacks(:before_run, self)
parser.runs.last.call(self) # ... not too happy with this
parser.run_callbacks(:after_run, self)
end
def process_args_with_subcmd(args = ARGV, *a, &b)
cmd = GitStyleBinary.current_command_name
vals = process_args(args, *a, &b)
parser.leftovers.shift if parser.leftovers[0] == cmd
vals
end
# TOOooootally ugly! why? bc load_parser_local_constraints doesn't work
# when loading the indivdual commands because it depends on
# #current_command. This really sucks and is UGLY.
# the todo is to put in 'load_all_parser_constraints' and this works
def process_parser!
# load_all_parser_constraints
load_parser_default_constraints
load_parser_primary_constraints
# load_parser_local_constraints
parser.consume_all(constraints)
# hack
parser.consume {
opt :version, "Print version and exit" if @version unless @specs[:version] || @long["version"]
opt :help, "Show this message" unless @specs[:help] || @long["help"]
resolve_default_short_options
} # hack
end
def process_args(args = ARGV, *a, &b)
p = parser
begin
vals = p.parse args
args.clear
p.leftovers.each { |l| args << l }
vals # ugly todo
rescue Trollop::CommandlineError => e
$stderr.puts "Error: #{e.message}."
$stderr.puts "Try --help for help."
exit(-1)
rescue Trollop::HelpNeeded
p.educate
exit
rescue Trollop::VersionNeeded
puts p.version
exit
end
end
def is_primary?
false
end
def argv
parser.leftovers
end
def short_desc
parser.short_desc
end
def full_name
# ugly, should be is_primary?
GitStyleBinary.primary_name == name ? GitStyleBinary.primary_name : GitStyleBinary.primary_name + "-" + name
end
def die arg, msg=nil
p = parser # create local copy
Trollop.instance_eval { @p = p }
Trollop::die(arg, msg)
end
# Helper to return the option
def [](k)
opts[k]
end
end
class Primary < Command
def is_primary?
true
end
def primary
self
end
end
end
| ruby | BSD-2-Clause | 9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23 | 2026-01-04T15:39:44.665514Z | false |
skwp/dotfiles | https://github.com/skwp/dotfiles/blob/9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23/bin/yadr/lib/git-style-binaries-0.1.11/lib/git-style-binary/autorunner.rb | bin/yadr/lib/git-style-binaries-0.1.11/lib/git-style-binary/autorunner.rb | require 'git-style-binary/parser'
module GitStyleBinary
class AutoRunner
def self.run(argv=ARGV)
r = new
r.run
end
def run
unless GitStyleBinary.run?
if !GitStyleBinary.current_command
GitStyleBinary.load_primary
end
GitStyleBinary.current_command.run
end
end
end
end
| ruby | BSD-2-Clause | 9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23 | 2026-01-04T15:39:44.665514Z | false |
skwp/dotfiles | https://github.com/skwp/dotfiles/blob/9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23/bin/yadr/lib/git-style-binaries-0.1.11/lib/git-style-binary/parser.rb | bin/yadr/lib/git-style-binaries-0.1.11/lib/git-style-binary/parser.rb | module GitStyleBinary
class Parser < Trollop::Parser
attr_reader :runs, :callbacks
attr_reader :short_desc
attr_accessor :command
def initialize *a, &b
super
@runs = []
setup_callbacks
end
def setup_callbacks
@callbacks = {}
%w(run).each do |event|
%w(before after).each do |time|
@callbacks["#{time}_#{event}".to_sym] = []
instance_eval "def #{time}_#{event}(&block);@callbacks[:#{time}_#{event}] << block;end"
end
end
end
def run_callbacks(at, from)
@callbacks[at].each {|c| c.call(from) }
end
def banner s=nil; @banner = s if s; @banner end
def short_desc s=nil; @short_desc = s if s; @short_desc end
def name_desc s=nil; @name_desc = s if s; @name_desc end
# Set the theme. Valid values are +:short+ or +:long+. Default +:long+
attr_writer :theme
def theme
@theme ||= :long
end
## Adds text to the help display.
def text s; @order << [:text, s] end
def spec_names
@specs.collect{|name, spec| spec[:long]}
end
# should probably be somewhere else
def load_all_commands
GitStyleBinary.subcommand_names.each do |name|
cmd_file = GitStyleBinary.binary_filename_for(name)
GitStyleBinary.load_command_file(name, cmd_file)
end
end
## Print the help message to 'stream'.
def educate(stream=$stdout)
load_all_commands
width # just calculate it now; otherwise we have to be careful not to
# call this unless the cursor's at the beginning of a line.
GitStyleBinary::Helpers::Pager.run_pager
self.send("educate_#{theme}", stream)
end
def educate_long(stream=$stdout)
left = {}
@specs.each do |name, spec|
left[name] =
((spec[:short] ? "-#{spec[:short]}, " : "") +
"--#{spec[:long]}" +
case spec[:type]
when :flag; ""
when :int; "=<i>"
when :ints; "=<i+>"
when :string; "=<s>"
when :strings; "=<s+>"
when :float; "=<f>"
when :floats; "=<f+>"
end).colorize(:red)
end
leftcol_width = left.values.map { |s| s.length }.max || 0
rightcol_start = leftcol_width + 6 # spaces
leftcol_start = 6
leftcol_spaces = " " * leftcol_start
unless @order.size > 0 && @order.first.first == :text
if @name_desc
stream.puts "NAME".colorize(:red)
stream.puts "#{leftcol_spaces}"+ colorize_known_words(eval(%Q["#{@name_desc}"])) + "\n"
stream.puts
end
if @version
stream.puts "VERSION".colorize(:red)
stream.puts "#{leftcol_spaces}#@version\n"
end
stream.puts
banner = colorize_known_words_array(wrap(eval(%Q["#{@banner}"]) + "\n", :prefix => leftcol_start)) if @banner # lazy banner
stream.puts banner
stream.puts
stream.puts "OPTIONS".colorize(:red)
else
stream.puts "#@banner\n" if @banner
end
@order.each do |what, opt|
if what == :text
stream.puts wrap(opt)
next
end
spec = @specs[opt]
stream.printf " %-#{leftcol_width}s\n", left[opt]
desc = spec[:desc] +
if spec[:default]
if spec[:desc] =~ /\.$/
" (Default: #{spec[:default]})"
else
" (default: #{spec[:default]})"
end
else
""
end
stream.puts wrap(" %s" % [desc], :prefix => leftcol_start, :width => width - rightcol_start - 1 )
stream.puts
stream.puts
end
end
def educate_short(stream=$stdout)
left = {}
@specs.each do |name, spec|
left[name] = "--#{spec[:long]}" +
(spec[:short] ? ", -#{spec[:short]}" : "") +
case spec[:type]
when :flag; ""
when :int; " <i>"
when :ints; " <i+>"
when :string; " <s>"
when :strings; " <s+>"
when :float; " <f>"
when :floats; " <f+>"
end
end
leftcol_width = left.values.map { |s| s.length }.max || 0
rightcol_start = leftcol_width + 6 # spaces
leftcol_start = 0
unless @order.size > 0 && @order.first.first == :text
stream.puts "#@version\n" if @version
stream.puts colorize_known_words_array(wrap(eval(%Q["#{@banner}"]) + "\n", :prefix => leftcol_start)) if @banner # jit banner
stream.puts "Options:"
else
stream.puts "#@banner\n" if @banner
end
@order.each do |what, opt|
if what == :text
stream.puts wrap(opt)
next
end
spec = @specs[opt]
stream.printf " %#{leftcol_width}s: ", left[opt]
desc = spec[:desc] +
if spec[:default]
if spec[:desc] =~ /\.$/
" (Default: #{spec[:default]})"
else
" (default: #{spec[:default]})"
end
else
""
end
stream.puts wrap(desc, :width => width - rightcol_start - 1, :prefix => rightcol_start)
end
end
def colorize_known_words_array(txts)
txts.collect{|txt| colorize_known_words(txt)}
end
def colorize_known_words(txt)
txt = txt.gsub(/^([A-Z]+\s*)$/, '\1'.colorize(:red)) # all caps words on their own line
txt = txt.gsub(/\b(#{bin_name})\b/, '\1'.colorize(:light_blue)) # the current command name
txt = txt.gsub(/\[([^\s]+)\]/, "[".colorize(:magenta) + '\1'.colorize(:green) + "]".colorize(:magenta)) # synopsis options
end
def consume(&block)
cloaker(&block).bind(self).call
end
def consume_all(blocks)
blocks.each {|b| consume(&b)}
end
def bin_name
GitStyleBinary.full_current_command_name
end
def all_options_string
# '#{spec_names.collect(&:to_s).collect{|name| "[".colorize(:magenta) + "--" + name + "]".colorize(:magenta)}.join(" ")} COMMAND [ARGS]'
'#{spec_names.collect(&:to_s).collect{|name| "[" + "--" + name + "]"}.join(" ")} COMMAND [ARGS]'
end
def run(&block)
@runs << block
end
def action(name = :action, &block)
block.call(self) if block
end
end
end
| ruby | BSD-2-Clause | 9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23 | 2026-01-04T15:39:44.665514Z | false |
skwp/dotfiles | https://github.com/skwp/dotfiles/blob/9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23/bin/yadr/lib/git-style-binaries-0.1.11/lib/git-style-binary/helpers/pager.rb | bin/yadr/lib/git-style-binaries-0.1.11/lib/git-style-binary/helpers/pager.rb | module GitStyleBinary
module Helpers
module Pager
# by Nathan Weizenbaum - http://nex-3.com/posts/73-git-style-automatic-paging-in-ruby
def run_pager
return if RUBY_PLATFORM =~ /win32/
return unless STDOUT.tty?
STDOUT.use_color = true
read, write = IO.pipe
unless Kernel.fork # Child process
STDOUT.reopen(write)
STDERR.reopen(write) if STDERR.tty?
read.close
write.close
return
end
# Parent process, become pager
STDIN.reopen(read)
read.close
write.close
ENV['LESS'] = 'FSRX' # Don't page if the input is short enough
Kernel.select [STDIN] # Wait until we have input before we start the pager
pager = ENV['PAGER'] || 'less -erXF'
exec pager rescue exec "/bin/sh", "-c", pager
end
module_function :run_pager
end
end
end
| ruby | BSD-2-Clause | 9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23 | 2026-01-04T15:39:44.665514Z | false |
skwp/dotfiles | https://github.com/skwp/dotfiles/blob/9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23/bin/yadr/lib/git-style-binaries-0.1.11/lib/git-style-binary/helpers/name_resolver.rb | bin/yadr/lib/git-style-binaries-0.1.11/lib/git-style-binary/helpers/name_resolver.rb | module GitStyleBinary
module Helpers
module NameResolver
def basename(filename=zero)
File.basename(filename).match(/(.*?)(\-|$)/).captures.first
end
alias_method :primary_name, :basename
# checks the bin directory for all files starting with +basename+ and
# returns an array of strings specifying the subcommands
def subcommand_names(filename=zero)
subfiles = Dir[File.join(binary_directory, basename + "-*")]
cmds = subfiles.collect{|file| File.basename(file).sub(/^#{basename}-/, '')}.sort
cmds += built_in_command_names
cmds.uniq
end
def binary_directory(filename=zero)
File.dirname(filename)
end
def built_in_commands_directory
File.dirname(__FILE__) + "/../commands"
end
def built_in_command_names
Dir[built_in_commands_directory + "/*.rb"].collect{|f| File.basename(f.sub(/\.rb$/,''))}
end
def list_subcommands(filename=zero)
subcommand_names(filename).join(", ")
end
# load first from users binary directory. then load built-in commands if
# available
def binary_filename_for(name)
user_file = File.join(binary_directory, "#{basename}-#{name}")
return user_file if File.exists?(user_file)
built_in = File.join(built_in_commands_directory, "#{name}.rb")
return built_in if File.exists?(built_in)
user_file
end
def current_command_name(filename=zero,argv=ARGV)
current = File.basename(zero)
first_arg = ARGV[0]
return first_arg if valid_subcommand?(first_arg)
return basename if basename == current
current.sub(/^#{basename}-/, '')
end
# returns the command name with the prefix if needed
def full_current_command_name(filename=zero,argv=ARGV)
cur = current_command_name(filename, argv)
subcmd = cur == basename(filename) ? false : true # is this a subcmd?
"%s%s%s" % [basename(filename), subcmd ? "-" : "", subcmd ? current_command_name(filename, argv) : ""]
end
def valid_subcommand?(name)
subcommand_names.include?(name)
end
def zero
$0
end
def pretty_known_subcommands(theme=:long)
GitStyleBinary.known_commands.collect do |k,cmd|
next if k == basename
cmd.process_parser!
("%-s%s%-10s" % [basename, '-', k]).colorize(:light_blue) + ("%s " % [theme == :long ? "\n" : ""]) + ("%s" % [cmd.short_desc]) + "\n"
end.compact.sort
end
end
end
end
| ruby | BSD-2-Clause | 9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23 | 2026-01-04T15:39:44.665514Z | false |
skwp/dotfiles | https://github.com/skwp/dotfiles/blob/9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23/bin/yadr/lib/git-style-binaries-0.1.11/lib/git-style-binary/commands/help.rb | bin/yadr/lib/git-style-binaries-0.1.11/lib/git-style-binary/commands/help.rb | module GitStyleBinary
module Commands
class Help
# not loving this syntax, but works for now
GitStyleBinary.command do
short_desc "get help for a specific command"
run do |command|
# this is slightly ugly b/c it has to muck around in the internals to
# get information about commands other than itself. This isn't a
# typical case
self.class.send :define_method, :educate_about_command do |name|
load_all_commands
if GitStyleBinary.known_commands.has_key?(name)
cmd = GitStyleBinary.known_commands[name]
cmd.process_parser!
cmd.parser.educate
else
puts "Unknown command '#{name}'"
end
end
if command.argv.size > 0
command.argv.first == "help" ? educate : educate_about_command(command.argv.first)
else
educate
end
end
end
end
end
end
| ruby | BSD-2-Clause | 9e3425d11dcde7706fbeabc3e9c3f7a7bdc63e23 | 2026-01-04T15:39:44.665514Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/spec/without_binding_of_caller.rb | spec/without_binding_of_caller.rb | module Kernel
alias_method :require_with_binding_of_caller, :require
def require(feature)
raise LoadError if feature == "binding_of_caller"
require_with_binding_of_caller(feature)
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/spec/spec_helper.rb | spec/spec_helper.rb | $: << File.expand_path("../../lib", __FILE__)
ENV["EDITOR"] = nil
ENV["BETTER_ERRORS"] = nil
require 'simplecov'
require 'simplecov-lcov'
# Fix incompatibility of simplecov-lcov with older versions of simplecov that are not expresses in its gemspec.
# https://github.com/fortissimo1997/simplecov-lcov/pull/25
if !SimpleCov.respond_to?(:branch_coverage)
module SimpleCov
def self.branch_coverage?
false
end
end
end
SimpleCov::Formatter::LcovFormatter.config do |c|
c.report_with_single_file = true
c.single_report_path = 'coverage/lcov.info'
end
SimpleCov.formatters = SimpleCov::Formatter::MultiFormatter.new(
[
SimpleCov::Formatter::HTMLFormatter,
SimpleCov::Formatter::LcovFormatter,
]
)
SimpleCov.start do
add_filter 'spec/'
end
require 'bundler/setup'
Bundler.require(:default)
require 'rspec-html-matchers'
RSpec.configure do |config|
config.include RSpecHtmlMatchers
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/spec/better_errors_spec.rb | spec/better_errors_spec.rb | require "spec_helper"
RSpec.describe BetterErrors do
describe ".editor" do
context "when set to a specific value" do
before do
allow(BetterErrors::Editor).to receive(:editor_from_symbol).and_return(:editor_from_symbol)
allow(BetterErrors::Editor).to receive(:for_formatting_string).and_return(:editor_from_formatting_string)
allow(BetterErrors::Editor).to receive(:for_proc).and_return(:editor_from_proc)
end
context "when the value is a string" do
it "uses BetterErrors::Editor.for_formatting_string to set the value" do
subject.editor = "thing://%{file}"
expect(BetterErrors::Editor).to have_received(:for_formatting_string).with("thing://%{file}")
expect(subject.editor).to eq(:editor_from_formatting_string)
end
end
context "when the value is a Proc" do
it "uses BetterErrors::Editor.for_proc to set the value" do
my_proc = proc { "thing" }
subject.editor = my_proc
expect(BetterErrors::Editor).to have_received(:for_proc).with(my_proc)
expect(subject.editor).to eq(:editor_from_proc)
end
end
context "when the value is a symbol" do
it "uses BetterErrors::Editor.editor_from_symbol to set the value" do
subject.editor = :subl
expect(BetterErrors::Editor).to have_received(:editor_from_symbol).with(:subl)
expect(subject.editor).to eq(:editor_from_symbol)
end
end
context "when set to something else" do
it "raises an ArgumentError" do
expect { subject.editor = Class.new }.to raise_error(ArgumentError)
end
end
end
context "when no value has been set" do
before do
BetterErrors.instance_variable_set('@editor', nil)
allow(BetterErrors::Editor).to receive(:default_editor).and_return(:default_editor)
end
it "uses BetterErrors::Editor.default_editor to set the default value" do
expect(subject.editor).to eq(:default_editor)
expect(BetterErrors::Editor).to have_received(:default_editor)
end
end
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/spec/better_errors/middleware_spec.rb | spec/better_errors/middleware_spec.rb | require "spec_helper"
module BetterErrors
describe Middleware do
let(:app) { Middleware.new(->env { ":)" }) }
let(:exception) { RuntimeError.new("oh no :(") }
let(:status) { response_env[0] }
let(:headers) { response_env[1] }
let(:body) { response_env[2].join }
context 'when the application raises no exception' do
it "passes non-error responses through" do
expect(app.call({})).to eq(":)")
end
end
it "calls the internal methods" do
expect(app).to receive :internal_call
app.call("PATH_INFO" => "/__better_errors/1/preform_awesomness")
end
it "calls the internal methods on any subfolder path" do
expect(app).to receive :internal_call
app.call("PATH_INFO" => "/any_sub/folder/path/__better_errors/1/preform_awesomness")
end
it "shows the error page" do
expect(app).to receive :show_error_page
app.call("PATH_INFO" => "/__better_errors/")
end
it "doesn't show the error page to a non-local address" do
expect(app).not_to receive :better_errors_call
app.call("REMOTE_ADDR" => "1.2.3.4")
end
it "shows to a whitelisted IP" do
BetterErrors::Middleware.allow_ip! '77.55.33.11'
expect(app).to receive :better_errors_call
app.call("REMOTE_ADDR" => "77.55.33.11")
end
it "shows to a whitelisted IPAddr" do
BetterErrors::Middleware.allow_ip! IPAddr.new('77.55.33.0/24')
expect(app).to receive :better_errors_call
app.call("REMOTE_ADDR" => "77.55.33.11")
end
it "respects the X-Forwarded-For header" do
expect(app).not_to receive :better_errors_call
app.call(
"REMOTE_ADDR" => "127.0.0.1",
"HTTP_X_FORWARDED_FOR" => "1.2.3.4",
)
end
it "doesn't blow up when given a blank REMOTE_ADDR" do
expect { app.call("REMOTE_ADDR" => " ") }.to_not raise_error
end
it "doesn't blow up when given an IP address with a zone index" do
expect { app.call("REMOTE_ADDR" => "0:0:0:0:0:0:0:1%0" ) }.to_not raise_error
end
context "when /__better_errors is requested directly" do
let(:response_env) { app.call("PATH_INFO" => "/__better_errors") }
context "when no error has been recorded since startup" do
it "shows that no errors have been recorded" do
expect(body).to match /No errors have been recorded yet./
end
it 'does not attempt to use ActionDispatch::ExceptionWrapper on the nil exception' do
ad_ew = double("ActionDispatch::ExceptionWrapper")
stub_const('ActionDispatch::ExceptionWrapper', ad_ew)
expect(ad_ew).to_not receive :new
response_env
end
context 'when requested inside a subfolder path' do
let(:response_env) { app.call("PATH_INFO" => "/any_sub/folder/__better_errors") }
it "shows that no errors have been recorded" do
expect(body).to match /No errors have been recorded yet./
end
end
end
context 'when an error has been recorded' do
let(:app) {
Middleware.new(->env do
# Only raise on the first request
raise exception unless @already_raised
@already_raised = true
end)
}
before do
app.call({})
end
it 'returns the information of the most recent error' do
expect(body).to include("oh no :(")
end
it 'does not attempt to use ActionDispatch::ExceptionWrapper' do
ad_ew = double("ActionDispatch::ExceptionWrapper")
stub_const('ActionDispatch::ExceptionWrapper', ad_ew)
expect(ad_ew).to_not receive :new
response_env
end
context 'when inside a subfolder path' do
let(:response_env) { app.call("PATH_INFO" => "/any_sub/folder/__better_errors") }
it "shows the error page on any subfolder path" do
expect(app).to receive :show_error_page
app.call("PATH_INFO" => "/any_sub/folder/path/__better_errors/")
end
end
end
end
context "when handling an error" do
let(:app) { Middleware.new(->env { raise exception }) }
let(:response_env) { app.call({}) }
it "returns status 500" do
expect(status).to eq(500)
end
context "when the exception has a cause" do
before do
pending "This Ruby does not support `cause`" unless Exception.new.respond_to?(:cause)
end
let(:app) {
Middleware.new(->env {
begin
raise "First Exception"
rescue
raise "Second Exception"
end
})
}
it "shows the exception as-is" do
expect(status).to eq(500)
expect(body).to match(/\nSecond Exception\n/)
expect(body).not_to match(/\nFirst Exception\n/)
end
end
context "when the exception responds to #original_exception" do
class OriginalExceptionException < Exception
attr_reader :original_exception
def initialize(message, original_exception = nil)
super(message)
@original_exception = original_exception
end
end
context 'and has one' do
let(:app) {
Middleware.new(->env {
raise OriginalExceptionException.new("Second Exception", Exception.new("First Exception"))
})
}
it "shows the original exception instead of the last-raised one" do
expect(status).to eq(500)
expect(body).not_to match(/Second Exception/)
expect(body).to match(/First Exception/)
end
end
context 'and does not have one' do
let(:app) {
Middleware.new(->env {
raise OriginalExceptionException.new("The Exception")
})
}
it "shows the exception as-is" do
expect(status).to eq(500)
expect(body).to match(/The Exception/)
end
end
end
it "returns ExceptionWrapper's status_code" do
ad_ew = double("ActionDispatch::ExceptionWrapper")
allow(ad_ew).to receive('new').with(anything, exception) { double("ExceptionWrapper", status_code: 404) }
stub_const('ActionDispatch::ExceptionWrapper', ad_ew)
expect(status).to eq(404)
end
it "returns UTF-8 error pages" do
expect(headers["Content-Type"]).to match /charset=utf-8/
end
it "returns text content by default" do
expect(headers["Content-Type"]).to match /text\/plain/
end
context 'when a CSRF token cookie is not specified' do
it 'includes a newly-generated CSRF token cookie' do
expect(headers).to include(
'Set-Cookie' => /BetterErrors-#{BetterErrors::VERSION}-CSRF-Token=[-a-z0-9]+; path=\/; HttpOnly; SameSite=Strict/,
)
end
end
context 'when a CSRF token cookie is specified' do
let(:response_env) { app.call({ 'HTTP_COOKIE' => "BetterErrors-#{BetterErrors::VERSION}-CSRF-Token=abc123" }) }
it 'does not set a new CSRF token cookie' do
expect(headers).not_to include('Set-Cookie')
end
end
context 'when the Accept header specifies HTML first' do
let(:response_env) { app.call("HTTP_ACCEPT" => "text/html,application/xhtml+xml;q=0.9,*/*") }
it "returns HTML content" do
expect(headers["Content-Type"]).to match /text\/html/
end
it 'includes the newly-generated CSRF token in the body of the page' do
matches = headers['Set-Cookie'].match(/BetterErrors-#{BetterErrors::VERSION}-CSRF-Token=(?<tok>[-a-z0-9]+); path=\/; HttpOnly; SameSite=Strict/)
expect(body).to include(matches[:tok])
end
context 'when a CSRF token cookie is specified' do
let(:response_env) {
app.call({
'HTTP_COOKIE' => "BetterErrors-#{BetterErrors::VERSION}-CSRF-Token=csrfTokenGHI",
"HTTP_ACCEPT" => "text/html,application/xhtml+xml;q=0.9,*/*",
})
}
it 'includes that CSRF token in the body of the page' do
expect(body).to include('csrfTokenGHI')
end
end
end
context 'the logger' do
let(:logger) { double('logger', fatal: nil) }
before do
allow(BetterErrors).to receive(:logger).and_return(logger)
end
it "receives the exception as a fatal message" do
expect(logger).to receive(:fatal).with(/RuntimeError/)
response_env
end
context 'when Rails is being used' do
before do
skip("Rails not included in this run") unless defined? Rails
end
it "receives the exception without filtered backtrace frames" do
expect(logger).to receive(:fatal) do |message|
expect(message).to_not match(/rspec-core/)
end
response_env
end
end
context 'when Rails is not being used' do
before do
skip("Rails is included in this run") if defined? Rails
end
it "receives the exception with all backtrace frames" do
expect(logger).to receive(:fatal) do |message|
expect(message).to match(/rspec-core/)
end
response_env
end
end
end
end
context "requesting the variables for a specific frame" do
let(:env) { {} }
let(:response_env) {
app.call(request_env)
}
let(:request_env) {
Rack::MockRequest.env_for("/__better_errors/#{id}/variables", input: StringIO.new(JSON.dump(request_body_data)))
}
let(:request_body_data) { { "index" => 0 } }
let(:json_body) { JSON.parse(body) }
let(:id) { 'abcdefg' }
context 'when no errors have been recorded' do
it 'returns a JSON error' do
expect(json_body).to match(
'error' => 'No exception information available',
'explanation' => /application has been restarted/,
)
end
context 'when Middleman is in use' do
let!(:middleman) { class_double("Middleman").as_stubbed_const }
it 'returns a JSON error' do
expect(json_body['explanation'])
.to match(/Middleman reloads all dependencies/)
end
end
context 'when Shotgun is in use' do
let!(:shotgun) { class_double("Shotgun").as_stubbed_const }
it 'returns a JSON error' do
expect(json_body['explanation'])
.to match(/The shotgun gem/)
end
context 'when Hanami is also in use' do
let!(:hanami) { class_double("Hanami").as_stubbed_const }
it 'returns a JSON error' do
expect(json_body['explanation'])
.to match(/--no-code-reloading/)
end
end
end
end
context 'when an error has been recorded' do
let(:error_page) { ErrorPage.new(exception, env) }
before do
app.instance_variable_set('@error_page', error_page)
end
context 'but it does not match the request' do
it 'returns a JSON error' do
expect(json_body).to match(
'error' => 'Session expired',
'explanation' => /no longer available in memory/,
)
end
end
context 'and its ID matches the requested ID' do
let(:id) { error_page.id }
context 'when the body csrfToken matches the CSRF token cookie' do
let(:request_body_data) { { "index" => 0, "csrfToken" => "csrfToken123" } }
before do
request_env["HTTP_COOKIE"] = "BetterErrors-#{BetterErrors::VERSION}-CSRF-Token=csrfToken123"
end
context 'when the Content-Type of the request is application/json' do
before do
request_env['CONTENT_TYPE'] = 'application/json'
end
it 'returns JSON containing the HTML content' do
expect(error_page).to receive(:do_variables).and_return(html: "<content>")
expect(json_body).to match(
'html' => '<content>',
)
end
end
context 'when the Content-Type of the request is application/json' do
before do
request_env['HTTP_CONTENT_TYPE'] = 'application/json'
end
it 'returns a JSON error' do
expect(json_body).to match(
'error' => 'Request not acceptable',
'explanation' => /did not match an acceptable content type/,
)
end
end
end
context 'when the body csrfToken does not match the CSRF token cookie' do
let(:request_body_data) { { "index" => 0, "csrfToken" => "csrfToken123" } }
before do
request_env["HTTP_COOKIE"] = "BetterErrors-#{BetterErrors::VERSION}-CSRF-Token=csrfToken456"
end
it 'returns a JSON error' do
expect(json_body).to match(
'error' => 'Invalid CSRF Token',
'explanation' => /session might have been cleared/,
)
end
end
context 'when there is no CSRF token in the request' do
it 'returns a JSON error' do
expect(json_body).to match(
'error' => 'Invalid CSRF Token',
'explanation' => /session might have been cleared/,
)
end
end
end
end
end
context "requesting eval for a specific frame" do
let(:env) { {} }
let(:response_env) {
app.call(request_env)
}
let(:request_env) {
Rack::MockRequest.env_for("/__better_errors/#{id}/eval", input: StringIO.new(JSON.dump(request_body_data)))
}
let(:request_body_data) { { "index" => 0, source: "do_a_thing" } }
let(:json_body) { JSON.parse(body) }
let(:id) { 'abcdefg' }
context 'when no errors have been recorded' do
it 'returns a JSON error' do
expect(json_body).to match(
'error' => 'No exception information available',
'explanation' => /application has been restarted/,
)
end
context 'when Middleman is in use' do
let!(:middleman) { class_double("Middleman").as_stubbed_const }
it 'returns a JSON error' do
expect(json_body['explanation'])
.to match(/Middleman reloads all dependencies/)
end
end
context 'when Shotgun is in use' do
let!(:shotgun) { class_double("Shotgun").as_stubbed_const }
it 'returns a JSON error' do
expect(json_body['explanation'])
.to match(/The shotgun gem/)
end
context 'when Hanami is also in use' do
let!(:hanami) { class_double("Hanami").as_stubbed_const }
it 'returns a JSON error' do
expect(json_body['explanation'])
.to match(/--no-code-reloading/)
end
end
end
end
context 'when an error has been recorded' do
let(:error_page) { ErrorPage.new(exception, env) }
before do
app.instance_variable_set('@error_page', error_page)
end
context 'but it does not match the request' do
it 'returns a JSON error' do
expect(json_body).to match(
'error' => 'Session expired',
'explanation' => /no longer available in memory/,
)
end
end
context 'and its ID matches the requested ID' do
let(:id) { error_page.id }
context 'when the body csrfToken matches the CSRF token cookie' do
let(:request_body_data) { { "index" => 0, "csrfToken" => "csrfToken123" } }
before do
request_env["HTTP_COOKIE"] = "BetterErrors-#{BetterErrors::VERSION}-CSRF-Token=csrfToken123"
end
context 'when the Content-Type of the request is application/json' do
before do
request_env['CONTENT_TYPE'] = 'application/json'
end
it 'returns JSON containing the eval result' do
expect(error_page).to receive(:do_eval).and_return(prompt: '#', result: "much_stuff_here")
expect(json_body).to match(
'prompt' => '#',
'result' => 'much_stuff_here',
)
end
end
context 'when the Content-Type of the request is application/json' do
before do
request_env['HTTP_CONTENT_TYPE'] = 'application/json'
end
it 'returns a JSON error' do
expect(json_body).to match(
'error' => 'Request not acceptable',
'explanation' => /did not match an acceptable content type/,
)
end
end
end
context 'when the body csrfToken does not match the CSRF token cookie' do
let(:request_body_data) { { "index" => 0, "csrfToken" => "csrfToken123" } }
before do
request_env["HTTP_COOKIE"] = "BetterErrors-#{BetterErrors::VERSION}-CSRF-Token=csrfToken456"
end
it 'returns a JSON error' do
expect(json_body).to match(
'error' => 'Invalid CSRF Token',
'explanation' => /session might have been cleared/,
)
end
end
context 'when there is no CSRF token in the request' do
it 'returns a JSON error' do
expect(json_body).to match(
'error' => 'Invalid CSRF Token',
'explanation' => /session might have been cleared/,
)
end
end
end
end
end
context "requesting an invalid internal method" do
let(:env) { {} }
let(:response_env) {
app.call(request_env)
}
let(:request_env) {
Rack::MockRequest.env_for("/__better_errors/#{id}/invalid", input: StringIO.new(JSON.dump(request_body_data)))
}
let(:request_body_data) { { "index" => 0 } }
let(:json_body) { JSON.parse(body) }
let(:id) { 'abcdefg' }
it 'returns a JSON error' do
expect(json_body).to match(
'error' => 'Not found',
'explanation' => /recognized internal call/,
)
end
end
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/spec/better_errors/editor_spec.rb | spec/better_errors/editor_spec.rb | require "spec_helper"
RSpec.describe BetterErrors::Editor do
describe ".for_formatting_string" do
it "returns an object that reponds to #url" do
editor = described_class.for_formatting_string("custom://%{file}:%{file_unencoded}:%{line}")
expect(editor.url("/path&file", 42)).to eq("custom://%2Fpath%26file:/path&file:42")
end
end
describe ".for_proc" do
it "returns an object that responds to #url, which calls the proc" do
editor = described_class.for_proc(proc { |file, line| "result" } )
expect(editor.url("foo", 42)).to eq("result")
end
end
describe ".default_editor" do
subject(:default_editor) { described_class.default_editor }
before do
ENV['BETTER_ERRORS_EDITOR_URL'] = nil
ENV['BETTER_ERRORS_EDITOR'] = nil
ENV['EDITOR'] = nil
end
it "returns an object that responds to #url" do
expect(default_editor.url("foo", 123)).to match(/foo/)
end
context "when $BETTER_ERRORS_EDITOR_URL is set" do
before do
ENV['BETTER_ERRORS_EDITOR_URL'] = "custom://%{file}:%{file_unencoded}:%{line}"
end
it "uses the value as a formatting string to build the editor URL" do
expect(default_editor.url("/path&file", 42)).to eq("custom://%2Fpath%26file:/path&file:42")
end
end
context "when $BETTER_ERRORS_EDITOR is set to one of the preset commands" do
before do
ENV['BETTER_ERRORS_EDITOR'] = "subl"
end
it "returns an object that builds URLs for the corresponding editor" do
expect(default_editor.url("foo", 123)).to start_with('subl://')
end
end
context "when $EDITOR is set to one of the preset commands" do
before do
ENV['EDITOR'] = "subl"
end
it "returns an object that builds URLs for the corresponding editor" do
expect(default_editor.url("foo", 123)).to start_with('subl://')
end
context "when $BETTER_ERRORS_EDITOR is set to one of the preset commands" do
before do
ENV['BETTER_ERRORS_EDITOR'] = "emacs"
end
it "returns an object that builds URLs for that editor instead" do
expect(default_editor.url("foo", 123)).to start_with('emacs://')
end
end
context "when $BETTER_ERRORS_EDITOR is set to an unrecognized command" do
before do
ENV['BETTER_ERRORS_EDITOR'] = "fubarcmd"
end
it "returns an object that builds URLs for the $EDITOR instead" do
expect(default_editor.url("foo", 123)).to start_with('subl://')
end
end
end
context "when $EDITOR is set to an unrecognized command" do
before do
ENV['EDITOR'] = "fubarcmd"
end
it "returns an object that builds URLs for TextMate" do
expect(default_editor.url("foo", 123)).to start_with('txmt://')
end
end
context "when $EDITOR and $BETTER_ERRORS_EDITOR are not set" do
it "returns an object that builds URLs for TextMate" do
expect(default_editor.url("foo", 123)).to start_with('txmt://')
end
end
end
describe ".editor_from_command" do
subject { described_class.editor_from_command(command_line) }
["atom -w", "/usr/bin/atom -w"].each do |command|
context "when editor command is '#{command}'" do
let(:command_line) { command }
it "uses atom:// scheme" do
expect(subject.url("file", 42)).to start_with("atom://")
end
end
end
["emacsclient", "/usr/local/bin/emacsclient"].each do |command|
context "when editor command is '#{command}'" do
let(:command_line) { command }
it "uses emacs:// scheme" do
expect(subject.url("file", 42)).to start_with("emacs://")
end
end
end
["idea"].each do |command|
context "when editor command is '#{command}'" do
let(:command_line) { command }
it "uses idea:// scheme" do
expect(subject.url("file", 42)).to start_with("idea://")
end
end
end
["mate -w", "/usr/bin/mate -w"].each do |command|
context "when editor command is '#{command}'" do
let(:command_line) { command }
it "uses txmt:// scheme" do
expect(subject.url("file", 42)).to start_with("txmt://")
end
end
end
["mine"].each do |command|
context "when editor command is '#{command}'" do
let(:command_line) { command }
it "uses x-mine:// scheme" do
expect(subject.url("file", 42)).to start_with("x-mine://")
end
end
end
["mvim -f", "/usr/local/bin/mvim -f"].each do |command|
context "when editor command is '#{command}'" do
let(:command_line) { command }
it "uses mvim:// scheme" do
expect(subject.url("file", 42)).to start_with("mvim://")
end
end
end
["subl -w", "/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl"].each do |command|
context "when editor command is '#{command}'" do
let(:command_line) { command }
it "uses subl:// scheme" do
expect(subject.url("file", 42)).to start_with("subl://")
end
end
end
["vscode", "code"].each do |command|
context "when editor command is '#{command}'" do
let(:command_line) { command }
it "uses vscode:// scheme" do
expect(subject.url("file", 42)).to start_with("vscode://")
end
end
end
end
describe ".editor_from_symbol" do
subject { described_class.editor_from_symbol(symbol) }
[:atom].each do |symbol|
context "when symbol is '#{symbol}'" do
let(:symbol) { symbol }
it "uses atom:// scheme" do
expect(subject.url("file", 42)).to start_with("atom://")
end
end
end
[:emacs, :emacsclient].each do |symbol|
context "when symbol is '#{symbol}'" do
let(:symbol) { symbol }
it "uses emacs:// scheme" do
expect(subject.url("file", 42)).to start_with("emacs://")
end
end
end
[:macvim, :mvim].each do |symbol|
context "when symbol is '#{symbol}'" do
let(:symbol) { symbol }
it "uses mvim:// scheme" do
expect(subject.url("file", 42)).to start_with("mvim://")
end
end
end
[:sublime, :subl, :st].each do |symbol|
context "when symbol is '#{symbol}'" do
let(:symbol) { symbol }
it "uses subl:// scheme" do
expect(subject.url("file", 42)).to start_with("subl://")
end
end
end
[:textmate, :txmt, :tm].each do |symbol|
context "when symbol is '#{symbol}'" do
let(:symbol) { symbol }
it "uses txmt:// scheme" do
expect(subject.url("file", 42)).to start_with("txmt://")
end
end
end
end
describe "#url" do
subject(:url) { described_instance.url("/full/path/to/lib/file.rb", 42) }
let(:described_instance) { described_class.for_formatting_string("%{file_unencoded}")}
before do
ENV['BETTER_ERRORS_VIRTUAL_PATH'] = virtual_path
ENV['BETTER_ERRORS_HOST_PATH'] = host_path
end
let(:virtual_path) { nil }
let(:host_path) { nil }
context "when $BETTER_ERRORS_VIRTUAL_PATH is set" do
let(:virtual_path) { "/full/path/to" }
context "when $BETTER_ERRORS_HOST_PATH is not set" do
let(:host_path) { nil }
it "removes the VIRTUAL_PATH prefix, making the path relative" do
expect(url).to eq("lib/file.rb")
end
end
context "when $BETTER_ERRORS_HOST_PATH is set" do
let(:host_path) { '/Users/myname/Code' }
it "replaces the VIRTUAL_PATH prefix with the HOST_PATH" do
expect(url).to eq("/Users/myname/Code/lib/file.rb")
end
end
end
context "when $BETTER_ERRORS_VIRTUAL_PATH is not set" do
it "does not alter file paths" do
expect(url).to eq("/full/path/to/lib/file.rb")
end
end
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/spec/better_errors/stack_frame_spec.rb | spec/better_errors/stack_frame_spec.rb | require "spec_helper"
module BetterErrors
describe StackFrame do
context "#application?" do
it "is true for application filenames" do
allow(BetterErrors).to receive(:application_root).and_return("/abc/xyz")
frame = StackFrame.new("/abc/xyz/app/controllers/crap_controller.rb", 123, "index")
expect(frame).to be_application
end
it "is false for everything else" do
allow(BetterErrors).to receive(:application_root).and_return("/abc/xyz")
frame = StackFrame.new("/abc/nope", 123, "foo")
expect(frame).not_to be_application
end
it "doesn't care if no application_root is set" do
frame = StackFrame.new("/abc/xyz/app/controllers/crap_controller.rb", 123, "index")
expect(frame).not_to be_application
end
end
context "#gem?" do
it "is true for gem filenames" do
allow(Gem).to receive(:path).and_return(["/abc/xyz"])
frame = StackFrame.new("/abc/xyz/gems/whatever-1.2.3/lib/whatever.rb", 123, "foo")
expect(frame).to be_gem
end
it "is false for everything else" do
allow(Gem).to receive(:path).and_return(["/abc/xyz"])
frame = StackFrame.new("/abc/nope", 123, "foo")
expect(frame).not_to be_gem
end
end
context "#application_path" do
it "chops off the application root" do
allow(BetterErrors).to receive(:application_root).and_return("/abc/xyz")
frame = StackFrame.new("/abc/xyz/app/controllers/crap_controller.rb", 123, "index")
expect(frame.application_path).to eq("app/controllers/crap_controller.rb")
end
end
context "#gem_path" do
it "chops of the gem path and stick (gem) there" do
allow(Gem).to receive(:path).and_return(["/abc/xyz"])
frame = StackFrame.new("/abc/xyz/gems/whatever-1.2.3/lib/whatever.rb", 123, "foo")
expect(frame.gem_path).to eq("whatever (1.2.3) lib/whatever.rb")
end
it "prioritizes gem path over application path" do
allow(BetterErrors).to receive(:application_root).and_return("/abc/xyz")
allow(Gem).to receive(:path).and_return(["/abc/xyz/vendor"])
frame = StackFrame.new("/abc/xyz/vendor/gems/whatever-1.2.3/lib/whatever.rb", 123, "foo")
expect(frame.gem_path).to eq("whatever (1.2.3) lib/whatever.rb")
end
end
context "#pretty_path" do
it "returns #application_path for application paths" do
allow(BetterErrors).to receive(:application_root).and_return("/abc/xyz")
frame = StackFrame.new("/abc/xyz/app/controllers/crap_controller.rb", 123, "index")
expect(frame.pretty_path).to eq(frame.application_path)
end
it "returns #gem_path for gem paths" do
allow(Gem).to receive(:path).and_return(["/abc/xyz"])
frame = StackFrame.new("/abc/xyz/gems/whatever-1.2.3/lib/whatever.rb", 123, "foo")
expect(frame.pretty_path).to eq(frame.gem_path)
end
end
context "#local_variable" do
it "returns exception details when #get_local_variable raises NameError" do
frame = StackFrame.new("/abc/xyz/app/controllers/crap_controller.rb", 123, "index")
allow(frame).to receive(:get_local_variable).and_raise(NameError.new("details"))
expect(frame.local_variable("foo")).to eq("NameError: details")
end
it "returns exception details when #eval_local_variable raises NameError" do
frame = StackFrame.new("/abc/xyz/app/controllers/crap_controller.rb", 123, "index")
allow(frame).to receive(:eval_local_variable).and_raise(NameError.new("details"))
expect(frame.local_variable("foo")).to eq("NameError: details")
end
it "raises on non-NameErrors" do
frame = StackFrame.new("/abc/xyz/app/controllers/crap_controller.rb", 123, "index")
allow(frame).to receive(:get_local_variable).and_raise(ArgumentError)
expect { frame.local_variable("foo") }.to raise_error(ArgumentError)
end
end
it "special cases SyntaxErrors" do
begin
eval(%{ raise SyntaxError, "you wrote bad ruby!" }, nil, "my_file.rb", 123)
rescue SyntaxError => syntax_error
end
frames = StackFrame.from_exception(syntax_error)
expect(frames.first.filename).to eq("my_file.rb")
expect(frames.first.line).to eq(123)
end
it "doesn't blow up if no method name is given" do
error = StandardError.allocate
allow(error).to receive(:backtrace).and_return(["foo.rb:123"])
frames = StackFrame.from_exception(error)
expect(frames.first.filename).to eq("foo.rb")
expect(frames.first.line).to eq(123)
allow(error).to receive(:backtrace).and_return(["foo.rb:123: this is an error message"])
frames = StackFrame.from_exception(error)
expect(frames.first.filename).to eq("foo.rb")
expect(frames.first.line).to eq(123)
end
it "ignores a backtrace line if its format doesn't make any sense at all" do
error = StandardError.allocate
allow(error).to receive(:backtrace).and_return(["foo.rb:123:in `foo'", "C:in `find'", "bar.rb:123:in `bar'"])
frames = StackFrame.from_exception(error)
expect(frames.count).to eq(2)
end
it "doesn't blow up if a filename contains a colon" do
error = StandardError.allocate
allow(error).to receive(:backtrace).and_return(["crap:filename.rb:123"])
frames = StackFrame.from_exception(error)
expect(frames.first.filename).to eq("crap:filename.rb")
end
it "doesn't blow up with a BasicObject as frame binding" do
obj = BasicObject.new
def obj.my_binding
::Kernel.binding
end
frame = StackFrame.new("/abc/xyz/app/controllers/crap_controller.rb", 123, "index", obj.my_binding)
expect(frame.class_name).to eq('BasicObject')
end
it "sets method names properly" do
obj = "string"
def obj.my_method
begin
raise "foo"
rescue => err
err
end
end
frame = StackFrame.from_exception(obj.my_method).first
if BetterErrors.binding_of_caller_available?
expect(frame.method_name).to eq("#my_method")
expect(frame.class_name).to eq("String")
else
expect(frame.method_name).to eq("my_method")
expect(frame.class_name).to eq(nil)
end
end
if RUBY_ENGINE == "java"
it "doesn't blow up on a native Java exception" do
expect { StackFrame.from_exception(java.lang.Exception.new) }.to_not raise_error
end
end
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/spec/better_errors/exception_hint_spec.rb | spec/better_errors/exception_hint_spec.rb | require 'spec_helper'
RSpec.describe BetterErrors::ExceptionHint do
let(:described_instance) { described_class.new(exception) }
describe '#hint' do
subject(:hint) { described_instance.hint }
context "when the exception is a NameError" do
let(:exception) {
begin
foo
rescue NameError => e
e
end
}
it { is_expected.to eq("`foo` is probably misspelled.") }
end
context "when the exception is a NoMethodError" do
let(:exception) {
begin
val.foo
rescue NoMethodError => e
e
end
}
context "on `nil`" do
let(:val) { nil }
it { is_expected.to eq("Something is `nil` when it probably shouldn't be.") }
end
context 'on an unnamed object type' do
let(:val) { Class.new }
it { is_expected.to be_nil }
end
context "on other values" do
let(:val) { 42 }
it {
is_expected.to match(
/`foo` is being called on a `(Integer|Fixnum)` object, which might not be the type of object you were expecting./
)
}
end
end
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/spec/better_errors/error_page_spec.rb | spec/better_errors/error_page_spec.rb | require "spec_helper"
class ErrorPageTestIgnoredClass; end
module BetterErrors
describe ErrorPage do
# It's necessary to use HTML matchers here that are specific as possible.
# This is because if there's an exception within this file, the lines of code will be reflected in the
# generated HTML, so any strings being matched against the HTML content will be there if they're within 5
# lines of code of the exception that was raised.
let!(:exception) { raise ZeroDivisionError, "you divided by zero you silly goose!" rescue $! }
let(:error_page) { ErrorPage.new exception, { "PATH_INFO" => "/some/path" } }
let(:response) { error_page.render_main("CSRF_TOKEN", "CSP_NONCE") }
let(:exception_binding) {
local_a = :value_for_local_a
local_b = :value_for_local_b
@inst_c = :value_for_inst_c
@inst_d = :value_for_inst_d
binding
}
it "includes the error message" do
expect(response).to have_tag('.exception p', text: /you divided by zero you silly goose!/)
end
it "includes the request path" do
expect(response).to have_tag('.exception h2', %r{/some/path})
end
it "includes the exception class" do
expect(response).to have_tag('.exception h2', /ZeroDivisionError/)
end
context 'when ActiveSupport::ActionableError is available' do
before do
skip "ActiveSupport missing on this platform" unless Object.constants.include?(:ActiveSupport)
skip "ActionableError missing on this platform" unless ActiveSupport.constants.include?(:ActionableError)
end
context 'when ActiveSupport provides one or more actions for this error type' do
let(:exception_class) {
Class.new(StandardError) do
include ActiveSupport::ActionableError
action "Do a thing" do
puts "Did a thing"
end
end
}
let(:exception) { exception_binding.eval("raise exception_class") rescue $! }
it "includes a fix-action form for each action" do
expect(response).to have_tag('.fix-actions') do
with_tag('form.button_to')
with_tag('form.button_to input[type=submit][value="Do a thing"]')
end
end
end
context 'when ActiveSupport does not provide any actions for this error type' do
let(:exception_class) {
Class.new(StandardError)
}
let(:exception) { exception_binding.eval("raise exception_class") rescue $! }
it "does not include a fix-action form" do
expect(response).not_to have_tag('.fix-actions')
end
end
end
context "variable inspection" do
let(:html) { error_page.do_variables("index" => 0)[:html] }
let(:exception) { exception_binding.eval("raise") rescue $! }
it 'includes an editor link for the full path of the current frame' do
expect(html).to have_tag('.location .filename') do
with_tag('a[href*="better_errors"]')
end
end
context 'when BETTER_ERRORS_INSIDE_FRAME is set in the environment' do
before do
ENV['BETTER_ERRORS_INSIDE_FRAME'] = '1'
end
after do
ENV['BETTER_ERRORS_INSIDE_FRAME'] = nil
end
it 'includes an editor link with target=_blank' do
expect(html).to have_tag('.location .filename') do
with_tag('a[href*="better_errors"][target="_blank"]')
end
end
end
context 'when BETTER_ERRORS_INSIDE_FRAME is not set in the environment' do
it 'includes an editor link without target=_blank' do
expect(html).to have_tag('.location .filename') do
with_tag('a[href*="better_errors"]:not([target="_blank"])')
end
end
end
context "when binding_of_caller is loaded" do
before do
skip "binding_of_caller is not loaded" unless BetterErrors.binding_of_caller_available?
end
it "shows local variables" do
expect(html).to have_tag('div.variables tr') do
with_tag('td.name', text: 'local_a')
with_tag('pre', text: ':value_for_local_a')
end
expect(html).to have_tag('div.variables tr') do
with_tag('td.name', text: 'local_b')
with_tag('pre', text: ':value_for_local_b')
end
end
it "shows instance variables" do
expect(html).to have_tag('div.variables tr') do
with_tag('td.name', text: '@inst_c')
with_tag('pre', text: ':value_for_inst_c')
end
expect(html).to have_tag('div.variables tr') do
with_tag('td.name', text: '@inst_d')
with_tag('pre', text: ':value_for_inst_d')
end
end
context 'when ignored_classes includes the class name of a local variable' do
before do
allow(BetterErrors).to receive(:ignored_classes).and_return(['ErrorPageTestIgnoredClass'])
end
let(:exception_binding) {
local_a = :value_for_local_a
local_b = ErrorPageTestIgnoredClass.new
@inst_c = :value_for_inst_c
@inst_d = ErrorPageTestIgnoredClass.new
binding
}
it "does not include that value" do
expect(html).to have_tag('div.variables tr') do
with_tag('td.name', text: 'local_a')
with_tag('pre', text: ':value_for_local_a')
end
expect(html).to have_tag('div.variables tr') do
with_tag('td.name', text: 'local_b')
with_tag('.unsupported', text: /Instance of ignored class/)
with_tag('.unsupported', text: /BetterErrors\.ignored_classes/)
end
expect(html).to have_tag('div.variables tr') do
with_tag('td.name', text: '@inst_c')
with_tag('pre', text: ':value_for_inst_c')
end
expect(html).to have_tag('div.variables tr') do
with_tag('td.name', text: '@inst_d')
with_tag('.unsupported', text: /Instance of ignored class/)
with_tag('.unsupported', text: /BetterErrors\.ignored_classes/)
end
end
end
it "does not show filtered variables" do
allow(BetterErrors).to receive(:ignored_instance_variables).and_return([:@inst_d])
expect(html).to have_tag('div.variables tr') do
with_tag('td.name', text: '@inst_c')
with_tag('pre', text: ':value_for_inst_c')
end
expect(html).not_to have_tag('div.variables td.name', text: '@inst_d')
end
context 'when maximum_variable_inspect_size is set' do
before do
BetterErrors.maximum_variable_inspect_size = 1010
end
context 'on a platform with ObjectSpace' do
before do
skip "Missing on this platform" unless Object.constants.include?(:ObjectSpace)
end
context 'with a variable that is smaller than maximum_variable_inspect_size' do
let(:exception_binding) {
@small = content
binding
}
let(:content) { 'A' * 480 }
it "shows the variable content" do
expect(html).to have_tag('div.variables', text: %r{#{content}})
end
end
context 'with a variable that is larger than maximum_variable_inspect_size' do
context 'but has an #inspect that returns a smaller value' do
let(:exception_binding) {
@big = content
binding
}
let(:content) {
class ExtremelyLargeInspectableTestValue
def initialize
@a = 'A' * 1101
end
def inspect
"shortval"
end
end
ExtremelyLargeInspectableTestValue.new
}
it "shows the variable content" do
expect(html).to have_tag('div.variables', text: /shortval/)
end
end
context 'and does not implement #inspect' do
let(:exception_binding) {
@big = content
binding
}
let(:content) { 'A' * 1101 }
it "includes an indication that the variable was too large" do
expect(html).not_to have_tag('div.variables', text: %r{#{content}})
expect(html).to have_tag('div.variables', text: /Object too large/)
end
end
context "when the variable's class is anonymous" do
let(:exception_binding) {
@big_anonymous = Class.new do
def initialize
@content = 'A' * 1101
end
end.new
binding
}
it "does not attempt to show the class name" do
expect(html).to have_tag('div.variables tr') do
with_tag('td.name', text: '@big_anonymous')
with_tag('.unsupported', text: /Object too large/)
with_tag('.unsupported', text: /Adjust BetterErrors.maximum_variable_inspect_size/)
end
end
end
end
end
context 'on a platform without ObjectSpace' do
before do
Object.send(:remove_const, :ObjectSpace) if Object.constants.include?(:ObjectSpace)
end
after do
require "objspace" rescue nil
end
context 'with a variable that is smaller than maximum_variable_inspect_size' do
let(:exception_binding) {
@small = content
binding
}
let(:content) { 'A' * 480 }
it "shows the variable content" do
expect(html).to have_tag('div.variables', text: %r{#{content}})
end
end
context 'with a variable that is larger than maximum_variable_inspect_size' do
context 'but has an #inspect that returns a smaller value' do
let(:exception_binding) {
@big = content
binding
}
let(:content) {
class ExtremelyLargeInspectableTestValue
def initialize
@a = 'A' * 1101
end
def inspect
"shortval"
end
end
ExtremelyLargeInspectableTestValue.new
}
it "shows the variable content" do
expect(html).to have_tag('div.variables', text: /shortval/)
end
end
context 'and does not implement #inspect' do
let(:exception_binding) {
@big = content
binding
}
let(:content) { 'A' * 1101 }
it "includes an indication that the variable was too large" do
expect(html).not_to have_tag('div.variables', text: %r{#{content}})
expect(html).to have_tag('div.variables', text: /Object too large/)
end
end
end
context "when the variable's class is anonymous" do
let(:exception_binding) {
@big_anonymous = Class.new do
def initialize
@content = 'A' * 1101
end
end.new
binding
}
it "does not attempt to show the class name" do
expect(html).to have_tag('div.variables tr') do
with_tag('td.name', text: '@big_anonymous')
with_tag('.unsupported', text: /Object too large/)
with_tag('.unsupported', text: /Adjust BetterErrors.maximum_variable_inspect_size/)
end
end
end
end
end
context 'when maximum_variable_inspect_size is disabled' do
before do
BetterErrors.maximum_variable_inspect_size = nil
end
let(:exception_binding) {
@big = content
binding
}
let(:content) { 'A' * 100_001 }
it "includes the content of large variables" do
expect(html).to have_tag('div.variables', text: %r{#{content}})
expect(html).not_to have_tag('div.variables', text: /Object too large/)
end
end
end
context "when binding_of_caller is not loaded" do
before do
skip "binding_of_caller is loaded" if BetterErrors.binding_of_caller_available?
end
it "tells the user to add binding_of_caller to their gemfile to get fancy features" do
expect(html).not_to have_tag('div.variables', text: /gem "binding_of_caller"/)
end
end
end
it "doesn't die if the source file is not a real filename" do
allow(exception).to receive(:__better_errors_bindings_stack).and_return([])
allow(exception).to receive(:backtrace).and_return([
"<internal:prelude>:10:in `spawn_rack_application'"
])
expect(response).to have_tag('.frames li .location .filename', text: '<internal:prelude>')
end
context 'with an exception with blank lines' do
class SpacedError < StandardError
def initialize(message = nil)
message = "\n\n#{message}" if message
super
end
end
let!(:exception) { raise SpacedError, "Danger Warning!" rescue $! }
it 'does not include leading blank lines in exception_message' do
expect(exception.message).to match(/\A\n\n/)
expect(error_page.exception_message).not_to match(/\A\n\n/)
end
end
describe '#do_eval' do
let(:exception) { exception_binding.eval("raise") rescue $! }
subject(:do_eval) { error_page.do_eval("index" => 0, "source" => command) }
let(:command) { 'EvalTester.stuff_was_done(:yep)' }
before do
stub_const('EvalTester', eval_tester)
end
let(:eval_tester) { double('EvalTester', stuff_was_done: 'response') }
context 'without binding_of_caller' do
before do
skip("Disabled with binding_of_caller") if defined? ::BindingOfCaller
end
it "does not evaluate the code" do
do_eval
expect(eval_tester).to_not have_received(:stuff_was_done).with(:yep)
end
it 'returns an error indicating no REPL' do
expect(do_eval).to include(
error: "REPL unavailable in this stack frame",
)
end
end
context 'with binding_of_caller available' do
before do
skip("Disabled without binding_of_caller") unless defined? ::BindingOfCaller
end
context 'with Pry disabled or unavailable' do
it "evaluates the code" do
do_eval
expect(eval_tester).to have_received(:stuff_was_done).with(:yep)
end
it 'returns a hash of the code and its result' do
expect(do_eval).to include(
highlighted_input: /stuff_was_done/,
prefilled_input: '',
prompt: '>>',
result: "=> \"response\"\n",
)
end
end
context 'with Pry enabled' do
before do
skip("Disabled without pry") unless defined? ::Pry
BetterErrors.use_pry!
# Cause the provider to be unselected, so that it will be re-detected.
BetterErrors::REPL.provider = nil
end
after do
BetterErrors::REPL::PROVIDERS.shift
BetterErrors::REPL.provider = nil
# Ensure the Pry REPL file has not been included. If this is not done,
# the constant leaks into other examples.
BetterErrors::REPL.send(:remove_const, :Pry)
end
it "evaluates the code" do
BetterErrors::REPL.provider
do_eval
expect(eval_tester).to have_received(:stuff_was_done).with(:yep)
end
it 'returns a hash of the code and its result' do
expect(do_eval).to include(
highlighted_input: /stuff_was_done/,
prefilled_input: '',
prompt: '>>',
result: "=> \"response\"\n",
)
end
end
end
end
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/spec/better_errors/raised_exception_spec.rb | spec/better_errors/raised_exception_spec.rb | require "spec_helper"
require "rspec/its"
module BetterErrors
describe RaisedException do
let(:exception) { RuntimeError.new("whoops") }
subject(:described_instance) { RaisedException.new(exception) }
before do
allow(BetterErrors::ExceptionHint).to receive(:new).and_return(exception_hint)
end
let(:exception_hint) { instance_double(BetterErrors::ExceptionHint, hint: nil) }
its(:exception) { is_expected.to eq exception }
its(:message) { is_expected.to eq "whoops" }
its(:type) { is_expected.to eq RuntimeError }
context 'when the exception is an ActionView::Template::Error that responds to #cause (Rails 6+)' do
before do
stub_const(
"ActionView::Template::Error",
Class.new(StandardError) do
def cause
RuntimeError.new("something went wrong!")
end
end
)
end
let(:exception) {
ActionView::Template::Error.new("undefined method `something!' for #<Class:0x00deadbeef>")
}
its(:message) { is_expected.to eq "something went wrong!" }
its(:type) { is_expected.to eq RuntimeError }
end
context 'when the exception is a Rails < 6 exception that has an #original_exception' do
let(:original_exception) { RuntimeError.new("something went wrong!") }
let(:exception) { double(:original_exception => original_exception) }
its(:exception) { is_expected.to eq original_exception }
its(:message) { is_expected.to eq "something went wrong!" }
its(:type) { is_expected.to eq RuntimeError }
end
context "when the exception is a SyntaxError" do
let(:exception) { SyntaxError.new("foo.rb:123: you made a typo!") }
its(:message) { is_expected.to eq "you made a typo!" }
its(:type) { is_expected.to eq SyntaxError }
it "has the right filename and line number in the backtrace" do
expect(subject.backtrace.first.filename).to eq("foo.rb")
expect(subject.backtrace.first.line).to eq(123)
end
end
context "when the exception is a HAML syntax error" do
before do
stub_const("Haml::SyntaxError", Class.new(SyntaxError))
end
let(:exception) {
Haml::SyntaxError.new("you made a typo!").tap do |ex|
ex.set_backtrace(["foo.rb:123", "haml/internals/blah.rb:123456"])
end
}
its(:message) { is_expected.to eq "you made a typo!" }
its(:type) { is_expected.to eq Haml::SyntaxError }
it "has the right filename and line number in the backtrace" do
expect(subject.backtrace.first.filename).to eq("foo.rb")
expect(subject.backtrace.first.line).to eq(123)
end
end
# context "when the exception is an ActionView::Template::Error" do
#
# let(:exception) {
# ActionView::Template::Error.new("undefined method `something!' for #<Class:0x00deadbeef>")
# }
#
# its(:message) { is_expected.to eq "undefined method `something!' for #<Class:0x00deadbeef>" }
#
# it "has the right filename and line number in the backtrace" do
# expect(subject.backtrace.first.filename).to eq("app/views/foo/bar.haml")
# expect(subject.backtrace.first.line).to eq(42)
# end
# end
#
context "when the exception is a Coffeelint syntax error" do
before do
stub_const("Sprockets::Coffeelint::Error", Class.new(SyntaxError))
end
let(:exception) {
Sprockets::Coffeelint::Error.new("[stdin]:11:88: error: unexpected=").tap do |ex|
ex.set_backtrace(["app/assets/javascripts/files/index.coffee:11", "sprockets/coffeelint.rb:3"])
end
}
its(:message) { is_expected.to eq "[stdin]:11:88: error: unexpected=" }
its(:type) { is_expected.to eq Sprockets::Coffeelint::Error }
it "has the right filename and line number in the backtrace" do
expect(subject.backtrace.first.filename).to eq("app/assets/javascripts/files/index.coffee")
expect(subject.backtrace.first.line).to eq(11)
end
end
describe '#hint' do
subject(:hint) { described_instance.hint }
it 'uses ExceptionHint to get a hint for the exception' do
hint
expect(BetterErrors::ExceptionHint).to have_received(:new).with(exception)
end
context "when ExceptionHint returns a string" do
let(:exception_hint) { instance_double(BetterErrors::ExceptionHint, hint: "Hint text") }
it 'returns the value from ExceptionHint' do
expect(hint).to eq("Hint text")
end
end
end
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/spec/better_errors/support/my_source.rb | spec/better_errors/support/my_source.rb | one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
nineteen
twenty
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/spec/better_errors/repl/shared_examples.rb | spec/better_errors/repl/shared_examples.rb | shared_examples_for "a REPL provider" do
it "evaluates ruby code in a given context" do
repl.send_input("local_a = 456")
expect(fresh_binding.eval("local_a")).to eq(456)
end
it "returns a tuple of output and the new prompt" do
output, prompt = repl.send_input("1 + 2")
expect(output).to eq("=> 3\n")
expect(prompt).to eq(">>")
end
it "doesn't barf if the code throws an exception" do
output, prompt = repl.send_input("raise Exception")
expect(output).to include "Exception: Exception"
expect(prompt).to eq(">>")
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/spec/better_errors/repl/basic_spec.rb | spec/better_errors/repl/basic_spec.rb | require "spec_helper"
require "better_errors/repl/basic"
require "better_errors/repl/shared_examples"
module BetterErrors
module REPL
describe Basic do
let(:fresh_binding) {
local_a = 123
binding
}
let!(:exception) { raise ZeroDivisionError, "you divided by zero you silly goose!" rescue $! }
let(:repl) { Basic.new(fresh_binding, exception) }
it_behaves_like "a REPL provider"
end
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/spec/better_errors/repl/pry_spec.rb | spec/better_errors/repl/pry_spec.rb | require "spec_helper"
require "better_errors/repl/shared_examples"
if defined? ::Pry
RSpec.describe 'BetterErrors::REPL::Pry' do
before(:all) do
load "better_errors/repl/pry.rb"
end
after(:all) do
# Ensure the Pry REPL file has not been included. If this is not done,
# the constant leaks into other examples.
# In practice, this constant is only defined if `use_pry!` is called and then the
# REPL is used, causing BetterErrors::REPL to require the file.
BetterErrors::REPL.send(:remove_const, :Pry)
end
let(:fresh_binding) {
local_a = 123
binding
}
let!(:exception) { raise ZeroDivisionError, "you divided by zero you silly goose!" rescue $! }
let(:repl) { BetterErrors::REPL::Pry.new(fresh_binding, exception) }
it "does line continuation", :aggregate_failures do
output, prompt, filled = repl.send_input ""
expect(output).to eq("=> nil\n")
expect(prompt).to eq(">>")
expect(filled).to eq("")
output, prompt, filled = repl.send_input "def f(x)"
expect(output).to eq("")
expect(prompt).to eq("..")
expect(filled).to eq(" ")
output, prompt, filled = repl.send_input "end"
if RUBY_VERSION >= "2.1.0"
expect(output).to eq("=> :f\n")
else
expect(output).to eq("=> nil\n")
end
expect(prompt).to eq(">>")
expect(filled).to eq("")
end
it_behaves_like "a REPL provider"
end
else
puts "Skipping Pry specs because pry is not in the bundle"
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/spec/better_errors/code_formatter/text_spec.rb | spec/better_errors/code_formatter/text_spec.rb | require "spec_helper"
RSpec.describe BetterErrors::CodeFormatter::Text do
let(:filename) { File.expand_path("../../support/my_source.rb", __FILE__) }
let(:line) { 8 }
let(:formatter) { described_class.new(filename, line) }
it "shows 5 lines of context" do
expect(formatter.line_range).to eq(3..13)
expect(formatter.context_lines).to eq([
"three\n",
"four\n",
"five\n",
"six\n",
"seven\n",
"eight\n",
"nine\n",
"ten\n",
"eleven\n",
"twelve\n",
"thirteen\n"
])
end
context 'when the line is right at the end of the file' do
let(:line) { 20 }
it "ends on the line" do
expect(formatter.line_range).to eq(15..20)
end
end
describe '#output' do
subject(:output) { formatter.output }
it "highlights the erroring line" do
expect(output).to eq <<-TEXT.gsub(/^ /, "")
3 three
4 four
5 five
6 six
7 seven
> 8 eight
9 nine
10 ten
11 eleven
12 twelve
13 thirteen
TEXT
end
context 'when the line is outside the file' do
let(:line) { 999 }
it "returns the 'source unavailable' message" do
expect(output).to eq(formatter.source_unavailable)
end
end
context 'when the the file path is not valid' do
let(:filename) { "fkdguhskd7e l" }
it "returns the 'source unavailable' message" do
expect(output).to eq(formatter.source_unavailable)
end
end
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/spec/better_errors/code_formatter/html_spec.rb | spec/better_errors/code_formatter/html_spec.rb | require "spec_helper"
RSpec.describe BetterErrors::CodeFormatter::HTML do
let(:filename) { File.expand_path("../../support/my_source.rb", __FILE__) }
let(:line) { 8 }
let(:formatter) { described_class.new(filename, line) }
it "shows 5 lines of context above and below the line" do
expect(formatter.line_range).to eq(3..13)
expect(formatter.context_lines).to eq([
"three\n",
"four\n",
"five\n",
"six\n",
"seven\n",
"eight\n",
"nine\n",
"ten\n",
"eleven\n",
"twelve\n",
"thirteen\n"
])
end
context 'when the line is right at the end of the file' do
let(:line) { 20 }
it "ends on the line" do
expect(formatter.line_range).to eq(15..20)
end
end
it "highlights the erroring line" do
formatter = described_class.new(filename, 8)
expect(formatter.output).to match(/highlight.*eight/)
end
it "works when the line is right on the edge" do
formatter = described_class.new(filename, 20)
expect(formatter.output).not_to eq(formatter.source_unavailable)
end
it "doesn't barf when the lines don't make any sense" do
formatter = described_class.new(filename, 999)
expect(formatter.output).to eq(formatter.source_unavailable)
end
it "doesn't barf when the file doesn't exist" do
formatter = described_class.new("fkdguhskd7e l", 1)
expect(formatter.output).to eq(formatter.source_unavailable)
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/lib/better_errors.rb | lib/better_errors.rb | require "pp"
require "erubi"
require "uri"
require "better_errors/version"
require "better_errors/code_formatter"
require "better_errors/inspectable_value"
require "better_errors/error_page"
require "better_errors/middleware"
require "better_errors/raised_exception"
require "better_errors/repl"
require "better_errors/stack_frame"
require "better_errors/editor"
module BetterErrors
class << self
# The path to the root of the application. Better Errors uses this property
# to determine if a file in a backtrace should be considered an application
# frame. If you are using Better Errors with Rails, you do not need to set
# this attribute manually.
#
# @return [String]
attr_accessor :application_root
# The logger to use when logging exception details and backtraces. If you
# are using Better Errors with Rails, you do not need to set this attribute
# manually. If this attribute is `nil`, nothing will be logged.
#
# @return [Logger, nil]
attr_accessor :logger
# @private
attr_accessor :binding_of_caller_available
# @private
alias_method :binding_of_caller_available?, :binding_of_caller_available
# The ignored instance variables.
# @return [Array]
attr_accessor :ignored_instance_variables
# The maximum variable payload size. If variable.inspect exceeds this,
# the variable won't be returned.
# @return int
attr_accessor :maximum_variable_inspect_size
# List of classes that are excluded from inspection.
# @return [Array]
attr_accessor :ignored_classes
end
@ignored_instance_variables = []
@maximum_variable_inspect_size = 100_000
@ignored_classes = ['ActionDispatch::Request', 'ActionDispatch::Response']
# Returns an object which responds to #url, which when called with
# a filename and line number argument,
# returns a URL to open the filename and line in the selected editor.
#
# Generates TextMate URLs by default.
#
# BetterErrors.editor.url("/some/file", 123)
# # => txmt://open?url=file:///some/file&line=123
#
# @return [Proc]
def self.editor
@editor ||= default_editor
end
# Configures how Better Errors generates open-in-editor URLs.
#
# @overload BetterErrors.editor=(sym)
# Uses one of the preset editor configurations. Valid symbols are:
#
# * `:textmate`, `:txmt`, `:tm`
# * `:sublime`, `:subl`, `:st`
# * `:macvim`
# * `:atom`
#
# @param [Symbol] sym
#
# @overload BetterErrors.editor=(str)
# Uses `str` as the format string for generating open-in-editor URLs.
#
# Use `%{file}` and `%{line}` as placeholders for the actual values.
#
# @example
# BetterErrors.editor = "my-editor://open?url=%{file}&line=%{line}"
#
# @param [String] str
#
# @overload BetterErrors.editor=(proc)
# Uses `proc` to generate open-in-editor URLs. The proc will be called
# with `file` and `line` parameters when a URL needs to be generated.
#
# Your proc should take care to escape `file` appropriately with
# `URI.encode_www_form_component` (please note that `URI.escape` is **not**
# a suitable substitute.)
#
# @example
# BetterErrors.editor = proc { |file, line|
# "my-editor://open?url=#{URI.encode_www_form_component file}&line=#{line}"
# }
#
# @param [Proc] proc
#
def self.editor=(editor)
if editor.is_a? Symbol
@editor = Editor.editor_from_symbol(editor)
raise(ArgumentError, "Symbol #{editor} is not a symbol in the list of supported errors.") unless editor
elsif editor.is_a? String
@editor = Editor.for_formatting_string(editor)
elsif editor.respond_to? :call
@editor = Editor.for_proc(editor)
else
raise ArgumentError, "Expected editor to be a valid editor key, a format string or a callable."
end
end
# Enables experimental Pry support in the inline REPL
#
# If you encounter problems while using Pry, *please* file a bug report at
# https://github.com/BetterErrors/better_errors/issues
def self.use_pry!
REPL::PROVIDERS.unshift const: :Pry, impl: "better_errors/repl/pry"
end
# Automatically sniffs a default editor preset based on the EDITOR
# environment variable.
#
# @return [Symbol]
def self.default_editor
Editor.default_editor
end
end
begin
require "binding_of_caller"
require "better_errors/exception_extension"
BetterErrors.binding_of_caller_available = true
rescue LoadError
BetterErrors.binding_of_caller_available = false
end
require "better_errors/rails" if defined? Rails::Railtie
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/lib/better_errors/exception_hint.rb | lib/better_errors/exception_hint.rb | module BetterErrors
class ExceptionHint
def initialize(exception)
@exception = exception
end
def hint
case exception
when NoMethodError
/\Aundefined method `(?<method>[^']+)' for (?<val>[^:]+):(?<klass>\w+)/.match(exception.message) do |match|
if match[:val] == "nil"
return "Something is `nil` when it probably shouldn't be."
elsif !match[:klass].start_with? '0x'
return "`#{match[:method]}` is being called on a `#{match[:klass]}` object, "\
"which might not be the type of object you were expecting."
end
end
when NameError
/\Aundefined local variable or method `(?<method>[^']+)' for/.match(exception.message) do |match|
return "`#{match[:method]}` is probably misspelled."
end
end
end
private
attr_reader :exception
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/lib/better_errors/inspectable_value.rb | lib/better_errors/inspectable_value.rb | require "cgi"
require "objspace" rescue nil
module BetterErrors
class ValueLargerThanConfiguredMaximum < StandardError; end
class InspectableValue
def initialize(value)
@original_value = value
end
def to_html
raise ValueLargerThanConfiguredMaximum unless value_small_enough_to_inspect?
value_as_html
end
private
attr_reader :original_value
def value_as_html
@value_as_html ||= CGI.escapeHTML(value)
end
def value
@value ||= begin
if original_value.respond_to? :inspect
original_value.inspect
else
original_value
end
end
end
def value_small_enough_to_inspect?
return true if BetterErrors.maximum_variable_inspect_size.nil?
if defined?(ObjectSpace) && defined?(ObjectSpace.memsize_of) && ObjectSpace.memsize_of(value)
ObjectSpace.memsize_of(value) <= BetterErrors.maximum_variable_inspect_size
else
value_as_html.length <= BetterErrors.maximum_variable_inspect_size
end
end
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/lib/better_errors/version.rb | lib/better_errors/version.rb | module BetterErrors
# This is changed by CI before building a gem for release, but is not committed.
VERSION = "0.0.1dev"
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/lib/better_errors/rails.rb | lib/better_errors/rails.rb | module BetterErrors
# @private
class Railtie < Rails::Railtie
initializer "better_errors.configure_rails_initialization" do
if use_better_errors?
insert_middleware
BetterErrors.logger = Rails.logger
BetterErrors.application_root = Rails.root.to_s
end
end
def insert_middleware
if defined? ActionDispatch::DebugExceptions
app.middleware.insert_after ActionDispatch::DebugExceptions, BetterErrors::Middleware
else
app.middleware.use BetterErrors::Middleware
end
end
def use_better_errors?
!Rails.env.production? and app.config.consider_all_requests_local
end
def app
Rails.application
end
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/lib/better_errors/raised_exception.rb | lib/better_errors/raised_exception.rb | require 'better_errors/exception_hint'
# @private
module BetterErrors
class RaisedException
attr_reader :exception, :message, :backtrace, :hint
def initialize(exception)
if exception.class.name == "ActionView::Template::Error" && exception.respond_to?(:cause)
# Rails 6+ exceptions of this type wrap the "real" exception, and the real exception
# is actually more useful than the ActionView-provided wrapper. Once Better Errors
# supports showing all exceptions in the cause stack, this should go away. Or perhaps
# this can be changed to provide guidance by showing the second error in the cause stack
# under this condition.
exception = exception.cause if exception.cause
elsif exception.respond_to?(:original_exception) && exception.original_exception
# This supports some specific Rails exceptions, and this is not intended to act the same as
# the Ruby's {Exception#cause}.
# It's possible this should only support ActionView::Template::Error, but by not changing
# this we're preserving longstanding behavior of Better Errors with Rails < 6.
exception = exception.original_exception
end
@exception = exception
@message = exception.message
setup_backtrace
setup_hint
massage_syntax_error
end
def type
exception.class
end
private
def has_bindings?
exception.respond_to?(:__better_errors_bindings_stack) && exception.__better_errors_bindings_stack.any?
end
def setup_backtrace
if has_bindings?
setup_backtrace_from_bindings
else
setup_backtrace_from_backtrace
end
end
def setup_backtrace_from_bindings
@backtrace = exception.__better_errors_bindings_stack.map { |binding|
if binding.respond_to?(:source_location) # Ruby >= 2.6
file = binding.source_location[0]
line = binding.source_location[1]
else
file = binding.eval "__FILE__"
line = binding.eval "__LINE__"
end
name = binding.frame_description
StackFrame.new(file, line, name, binding)
}
end
def setup_backtrace_from_backtrace
@backtrace = (exception.backtrace || []).map { |frame|
if /\A(?<file>.*?):(?<line>\d+)(:in `(?<name>.*)')?/ =~ frame
StackFrame.new(file, line.to_i, name)
end
}.compact
end
def massage_syntax_error
case exception.class.to_s
when "Haml::SyntaxError", "Sprockets::Coffeelint::Error"
if /\A(.+?):(\d+)/ =~ exception.backtrace.first
backtrace.unshift(StackFrame.new($1, $2.to_i, ""))
end
when "SyntaxError"
if /\A(.+?):(\d+): (.*)/m =~ exception.message
backtrace.unshift(StackFrame.new($1, $2.to_i, ""))
@message = $3
end
end
end
def setup_hint
@hint = ExceptionHint.new(exception).hint
end
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/lib/better_errors/middleware.rb | lib/better_errors/middleware.rb | require "json"
require "ipaddr"
require "securerandom"
require "set"
require "rack"
module BetterErrors
# Better Errors' error handling middleware. Including this in your middleware
# stack will show a Better Errors error page for exceptions raised below this
# middleware.
#
# If you are using Ruby on Rails, you do not need to manually insert this
# middleware into your middleware stack.
#
# @example Sinatra
# require "better_errors"
#
# if development?
# use BetterErrors::Middleware
# end
#
# @example Rack
# require "better_errors"
# if ENV["RACK_ENV"] == "development"
# use BetterErrors::Middleware
# end
#
class Middleware
# The set of IP addresses that are allowed to access Better Errors.
#
# Set to `{ "127.0.0.1/8", "::1/128" }` by default.
ALLOWED_IPS = Set.new
# Adds an address to the set of IP addresses allowed to access Better
# Errors.
def self.allow_ip!(addr)
ALLOWED_IPS << (addr.is_a?(IPAddr) ? addr : IPAddr.new(addr))
end
allow_ip! "127.0.0.0/8"
allow_ip! "::1/128" rescue nil # windows ruby doesn't have ipv6 support
CSRF_TOKEN_COOKIE_NAME = "BetterErrors-#{BetterErrors::VERSION}-CSRF-Token"
# A new instance of BetterErrors::Middleware
#
# @param app The Rack app/middleware to wrap with Better Errors
# @param handler The error handler to use.
def initialize(app, handler = ErrorPage)
@app = app
@handler = handler
end
# Calls the Better Errors middleware
#
# @param [Hash] env
# @return [Array]
def call(env)
if allow_ip? env
better_errors_call env
else
@app.call env
end
end
private
def allow_ip?(env)
request = Rack::Request.new(env)
return true unless request.ip and !request.ip.strip.empty?
ip = IPAddr.new request.ip.split("%").first
ALLOWED_IPS.any? { |subnet| subnet.include? ip }
end
def better_errors_call(env)
case env["PATH_INFO"]
when %r{/__better_errors/(?<id>.+?)/(?<method>\w+)\z}
internal_call(env, $~[:id], $~[:method])
when %r{/__better_errors/?\z}
show_error_page env
else
protected_app_call env
end
end
def protected_app_call(env)
@app.call env
rescue Exception => ex
@error_page = @handler.new ex, env
log_exception
show_error_page(env, ex)
end
def show_error_page(env, exception=nil)
request = Rack::Request.new(env)
csrf_token = request.cookies[CSRF_TOKEN_COOKIE_NAME] || SecureRandom.uuid
csp_nonce = SecureRandom.base64(12)
type, content = if @error_page
if text?(env)
[ 'plain', @error_page.render_text ]
else
[ 'html', @error_page.render_main(csrf_token, csp_nonce) ]
end
else
[ 'html', no_errors_page ]
end
status_code = 500
if defined?(ActionDispatch::ExceptionWrapper) && exception
status_code = ActionDispatch::ExceptionWrapper.new(env, exception).status_code
end
headers = {
"Content-Type" => "text/#{type}; charset=utf-8",
"Content-Security-Policy" => [
"default-src 'none'",
# Specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set
# for older browsers without nonce support.
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src
"script-src 'self' 'nonce-#{csp_nonce}' 'unsafe-inline'",
"style-src 'self' 'nonce-#{csp_nonce}' 'unsafe-inline'",
"img-src data:",
"connect-src 'self'",
"navigate-to 'self' #{BetterErrors.editor.scheme}",
].join('; '),
}
response = Rack::Response.new(content, status_code, headers)
unless request.cookies[CSRF_TOKEN_COOKIE_NAME]
response.set_cookie(CSRF_TOKEN_COOKIE_NAME, value: csrf_token, path: "/", httponly: true, same_site: :strict)
end
# In older versions of Rack, the body returned here is actually a Rack::BodyProxy which seems to be a bug.
# (It contains status, headers and body and does not act like an array of strings.)
# Since we already have status code and body here, there's no need to use the ones in the Rack::Response.
(_status_code, headers, _body) = response.finish
[status_code, headers, [content]]
end
def text?(env)
env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest" ||
!env["HTTP_ACCEPT"].to_s.include?('html')
end
def log_exception
return unless BetterErrors.logger
message = "\n#{@error_page.exception_type} - #{@error_page.exception_message}:\n"
message += backtrace_frames.map { |frame| " #{frame}\n" }.join
BetterErrors.logger.fatal message
end
def backtrace_frames
if defined?(Rails) && defined?(Rails.backtrace_cleaner)
Rails.backtrace_cleaner.clean @error_page.backtrace_frames.map(&:to_s)
else
@error_page.backtrace_frames
end
end
def internal_call(env, id, method)
return not_found_json_response unless %w[variables eval].include?(method)
return no_errors_json_response unless @error_page
return invalid_error_json_response if id != @error_page.id
request = Rack::Request.new(env)
return invalid_csrf_token_json_response unless request.cookies[CSRF_TOKEN_COOKIE_NAME]
request.body.rewind
body = JSON.parse(request.body.read)
return invalid_csrf_token_json_response unless request.cookies[CSRF_TOKEN_COOKIE_NAME] == body['csrfToken']
return not_acceptable_json_response unless request.content_type == 'application/json'
response = @error_page.send("do_#{method}", body)
[200, { "Content-Type" => "application/json; charset=utf-8" }, [JSON.dump(response)]]
end
def no_errors_page
"<h1>No errors</h1><p>No errors have been recorded yet.</p><hr>" +
"<code>Better Errors v#{BetterErrors::VERSION}</code>"
end
def no_errors_json_response
explanation = if defined? Middleman
"Middleman reloads all dependencies for each request, " +
"which breaks Better Errors."
elsif defined?(Shotgun) && defined?(Hanami)
"Hanami is likely running with code-reloading enabled, which is the default. " +
"You can disable this by running hanami with the `--no-code-reloading` option."
elsif defined? Shotgun
"The shotgun gem causes everything to be reloaded for every request. " +
"You can disable shotgun in the Gemfile temporarily to use Better Errors."
else
"The application has been restarted since this page loaded, " +
"or the framework is reloading all gems before each request "
end
[200, { "Content-Type" => "application/json; charset=utf-8" }, [JSON.dump(
error: 'No exception information available',
explanation: explanation,
)]]
end
def invalid_error_json_response
[200, { "Content-Type" => "application/json; charset=utf-8" }, [JSON.dump(
error: "Session expired",
explanation: "This page was likely opened from a previous exception, " +
"and the exception is no longer available in memory.",
)]]
end
def invalid_csrf_token_json_response
[200, { "Content-Type" => "application/json; charset=utf-8" }, [JSON.dump(
error: "Invalid CSRF Token",
explanation: "The browser session might have been cleared, " +
"or something went wrong.",
)]]
end
def not_found_json_response
[404, { "Content-Type" => "application/json; charset=utf-8" }, [JSON.dump(
error: "Not found",
explanation: "Not a recognized internal call.",
)]]
end
def not_acceptable_json_response
[406, { "Content-Type" => "application/json; charset=utf-8" }, [JSON.dump(
error: "Request not acceptable",
explanation: "The internal request did not match an acceptable content type.",
)]]
end
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/lib/better_errors/repl.rb | lib/better_errors/repl.rb | module BetterErrors
# @private
module REPL
PROVIDERS = [
{ impl: "better_errors/repl/basic",
const: :Basic },
]
def self.provider
@provider ||= const_get detect[:const]
end
def self.provider=(prov)
@provider = prov
end
def self.detect
PROVIDERS.find { |prov|
test_provider prov
}
end
def self.test_provider(provider)
# We must load this file instead of `require`ing it, since during our tests we want the file
# to be reloaded. In practice, this will only be called once, so `require` is not necessary.
load "#{provider[:impl]}.rb"
true
rescue LoadError
false
end
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/lib/better_errors/error_page_style.rb | lib/better_errors/error_page_style.rb | module BetterErrors
# @private
module ErrorPageStyle
def self.compiled_css(for_deployment = false)
begin
require "sassc"
rescue LoadError
raise LoadError, "The `sassc` gem is required when developing the `better_errors` gem. "\
"If you're using a release of `better_errors`, the compiled CSS is missing from the released gem"
# If you arrived here because sassc is not in your project's Gemfile,
# the issue here is that the release of the better_errors gem
# is supposed to contain the compiled CSS, but that file is missing from the release.
# So better_errors is trying to build the CSS on the fly, which requires the sassc gem.
#
# If you're developing the better_errors gem locally, and you're running a project
# that does not have sassc in its bundle, run `rake style:build` in the better_errors
# project to compile the CSS file.
end
style_dir = File.expand_path("style", File.dirname(__FILE__))
style_file = "#{style_dir}/main.scss"
engine = SassC::Engine.new(
File.read(style_file),
filename: style_file,
style: for_deployment ? :compressed : :expanded,
line_comments: !for_deployment,
load_paths: [style_dir],
)
engine.render
end
def self.style_tag(csp_nonce)
style_file = File.expand_path("templates/main.css", File.dirname(__FILE__))
css = if File.exist?(style_file)
File.open(style_file).read
else
compiled_css(false)
end
"<style type='text/css' nonce='#{csp_nonce}'>\n#{css}\n</style>"
end
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/lib/better_errors/error_page.rb | lib/better_errors/error_page.rb | require "cgi"
require "json"
require "securerandom"
require "rouge"
require "better_errors/error_page_style"
module BetterErrors
# @private
class ErrorPage
VariableInfo = Struct.new(:frame, :editor_url, :rails_params, :rack_session, :start_time)
def self.template_path(template_name)
File.expand_path("../templates/#{template_name}.erb", __FILE__)
end
def self.template(template_name)
Erubi::Engine.new(File.read(template_path(template_name)), escape: true)
end
def self.render_template(template_name, locals)
locals.send(:eval, self.template(template_name).src)
rescue => e
# Fix the backtrace, which doesn't identify the template that failed (within Better Errors).
# We don't know the line number, so just injecting the template path has to be enough.
e.backtrace.unshift "#{self.template_path(template_name)}:0"
raise
end
attr_reader :exception, :env, :repls
def initialize(exception, env)
@exception = RaisedException.new(exception)
@env = env
@start_time = Time.now.to_f
@repls = []
end
def id
@id ||= SecureRandom.hex(8)
end
def render_main(csrf_token, csp_nonce)
frame = backtrace_frames[0]
first_frame_variable_info = VariableInfo.new(frame, editor_url(frame), rails_params, rack_session, Time.now.to_f)
self.class.render_template('main', binding)
end
def render_text
self.class.render_template('text', binding)
end
def do_variables(opts)
index = opts["index"].to_i
frame = backtrace_frames[index]
variable_info = VariableInfo.new(frame, editor_url(frame), rails_params, rack_session, Time.now.to_f)
{ html: self.class.render_template("variable_info", variable_info) }
end
def do_eval(opts)
index = opts["index"].to_i
code = opts["source"]
unless (binding = backtrace_frames[index].frame_binding)
return { error: "REPL unavailable in this stack frame" }
end
@repls[index] ||= REPL.provider.new(binding, exception)
eval_and_respond(index, code)
end
def backtrace_frames
exception.backtrace
end
def exception_type
exception.type
end
def exception_message
exception.message.strip.gsub(/(\r?\n\s*\r?\n)+/, "\n")
end
def exception_hint
exception.hint
end
def active_support_actions
return [] unless defined?(ActiveSupport::ActionableError)
ActiveSupport::ActionableError.actions(exception.type)
end
def action_dispatch_action_endpoint
return unless defined?(ActionDispatch::ActionableExceptions)
ActionDispatch::ActionableExceptions.endpoint
end
def application_frames
backtrace_frames.select(&:application?)
end
def first_frame
application_frames.first || backtrace_frames.first
end
private
def editor_url(frame)
BetterErrors.editor.url(frame.filename, frame.line)
end
def rack_session
env['rack.session']
end
def rails_params
env['action_dispatch.request.parameters']
end
def uri_prefix
env["SCRIPT_NAME"] || ""
end
def request_path
env["PATH_INFO"]
end
def self.html_formatted_code_block(frame)
CodeFormatter::HTML.new(frame.filename, frame.line).output
end
def self.text_formatted_code_block(frame)
CodeFormatter::Text.new(frame.filename, frame.line).output
end
def text_heading(char, str)
str + "\n" + char*str.size
end
def self.inspect_value(obj)
if BetterErrors.ignored_classes.include? obj.class.name
"<span class='unsupported'>(Instance of ignored class. "\
"#{obj.class.name ? "Remove #{CGI.escapeHTML(obj.class.name)} from" : "Modify"}"\
" BetterErrors.ignored_classes if you need to see it.)</span>"
else
InspectableValue.new(obj).to_html
end
rescue BetterErrors::ValueLargerThanConfiguredMaximum
"<span class='unsupported'>(Object too large. "\
"#{obj.class.name ? "Modify #{CGI.escapeHTML(obj.class.name)}#inspect or a" : "A"}"\
"djust BetterErrors.maximum_variable_inspect_size if you need to see it.)</span>"
rescue Exception => e
"<span class='unsupported'>(exception #{CGI.escapeHTML(e.class.to_s)} was raised in inspect)</span>"
end
def eval_and_respond(index, code)
result, prompt, prefilled_input = @repls[index].send_input(code)
{
highlighted_input: Rouge::Formatters::HTML.new.format(Rouge::Lexers::Ruby.lex(code)),
prefilled_input: prefilled_input,
prompt: prompt,
result: result
}
end
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/lib/better_errors/code_formatter.rb | lib/better_errors/code_formatter.rb | module BetterErrors
# @private
class CodeFormatter
require "better_errors/code_formatter/html"
require "better_errors/code_formatter/text"
attr_reader :filename, :line, :context
def initialize(filename, line, context = 5)
@filename = filename
@line = line
@context = context
end
def output
formatted_code
rescue Errno::ENOENT, Errno::EINVAL
source_unavailable
end
def line_range
min = [line - context, 1].max
max = [line + context, source_lines.count].min
min..max
end
def context_lines
range = line_range
source_lines[(range.begin - 1)..(range.end - 1)] or raise Errno::EINVAL
end
private
def formatted_code
formatted_lines.join
end
def each_line_of(lines, &blk)
line_range.zip(lines).map { |current_line, str|
yield (current_line == line), current_line, str
}
end
def source
@source ||= File.read(filename)
end
def source_lines
@source_lines ||= source.lines
end
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/lib/better_errors/editor.rb | lib/better_errors/editor.rb | require "uri"
module BetterErrors
class Editor
KNOWN_EDITORS = [
{ symbols: [:atom], sniff: /atom/i, url: "atom://core/open/file?filename=%{file}&line=%{line}" },
{ symbols: [:emacs, :emacsclient], sniff: /emacs/i, url: "emacs://open?url=file://%{file}&line=%{line}" },
{ symbols: [:idea], sniff: /idea/i, url: "idea://open?file=%{file}&line=%{line}" },
{ symbols: [:macvim, :mvim], sniff: /vim/i, url: "mvim://open?url=file://%{file_unencoded}&line=%{line}" },
{ symbols: [:rubymine], sniff: /mine/i, url: "x-mine://open?file=%{file}&line=%{line}" },
{ symbols: [:sublime, :subl, :st], sniff: /subl/i, url: "subl://open?url=file://%{file}&line=%{line}" },
{ symbols: [:textmate, :txmt, :tm], sniff: /mate/i, url: "txmt://open?url=file://%{file}&line=%{line}" },
{ symbols: [:vscode, :code], sniff: /code/i, url: "vscode://file/%{file}:%{line}" },
{ symbols: [:vscodium, :codium], sniff: /codium/i, url: "vscodium://file/%{file}:%{line}" },
]
def self.for_formatting_string(formatting_string)
new proc { |file, line|
formatting_string % { file: URI.encode_www_form_component(file), file_unencoded: file, line: line }
}
end
def self.for_proc(url_proc)
new url_proc
end
# Automatically sniffs a default editor preset based on
# environment variables.
#
# @return [Symbol]
def self.default_editor
editor_from_environment_formatting_string ||
editor_from_environment_editor ||
editor_from_symbol(:textmate)
end
def self.editor_from_environment_editor
if ENV["BETTER_ERRORS_EDITOR"]
editor = editor_from_command(ENV["BETTER_ERRORS_EDITOR"])
return editor if editor
puts "BETTER_ERRORS_EDITOR environment variable is not recognized as a supported Better Errors editor."
end
if ENV["EDITOR"]
editor = editor_from_command(ENV["EDITOR"])
return editor if editor
puts "EDITOR environment variable is not recognized as a supported Better Errors editor. Using TextMate by default."
else
puts "Since there is no EDITOR or BETTER_ERRORS_EDITOR environment variable, using Textmate by default."
end
end
def self.editor_from_command(editor_command)
env_preset = KNOWN_EDITORS.find { |preset| editor_command =~ preset[:sniff] }
for_formatting_string(env_preset[:url]) if env_preset
end
def self.editor_from_environment_formatting_string
return unless ENV['BETTER_ERRORS_EDITOR_URL']
for_formatting_string(ENV['BETTER_ERRORS_EDITOR_URL'])
end
def self.editor_from_symbol(symbol)
KNOWN_EDITORS.each do |preset|
return for_formatting_string(preset[:url]) if preset[:symbols].include?(symbol)
end
end
def initialize(url_proc)
@url_proc = url_proc
end
def url(raw_path, line)
if virtual_path && raw_path.start_with?(virtual_path)
if host_path
file = raw_path.sub(%r{\A#{virtual_path}}, host_path)
else
file = raw_path.sub(%r{\A#{virtual_path}/}, '')
end
else
file = raw_path
end
url_proc.call(file, line)
end
def scheme
url('/fake', 42).sub(/:.*/, ':')
end
private
attr_reader :url_proc
def virtual_path
@virtual_path ||= ENV['BETTER_ERRORS_VIRTUAL_PATH']
end
def host_path
@host_path ||= ENV['BETTER_ERRORS_HOST_PATH']
end
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/lib/better_errors/exception_extension.rb | lib/better_errors/exception_extension.rb | module BetterErrors
module ExceptionExtension
prepend_features Exception
def set_backtrace(*)
if caller_locations.none? { |loc| loc.path == __FILE__ }
@__better_errors_bindings_stack = ::Kernel.binding.callers.drop(1)
end
super
end
def __better_errors_bindings_stack
@__better_errors_bindings_stack || []
end
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/lib/better_errors/stack_frame.rb | lib/better_errors/stack_frame.rb | require "set"
module BetterErrors
# @private
class StackFrame
def self.from_exception(exception)
RaisedException.new(exception).backtrace
end
attr_reader :filename, :line, :name, :frame_binding
def initialize(filename, line, name, frame_binding = nil)
@filename = filename
@line = line
@name = name
@frame_binding = frame_binding
set_pretty_method_name if frame_binding
end
def application?
if root = BetterErrors.application_root
filename.index(root) == 0 && filename.index("#{root}/vendor") != 0
end
end
def application_path
filename[(BetterErrors.application_root.length+1)..-1]
end
def gem?
Gem.path.any? { |path| filename.index(path) == 0 }
end
def gem_path
if path = Gem.path.detect { |p| filename.index(p) == 0 }
gem_name_and_version, path = filename.sub("#{path}/gems/", "").split("/", 2)
/(?<gem_name>.+)-(?<gem_version>[\w.]+)/ =~ gem_name_and_version
"#{gem_name} (#{gem_version}) #{path}"
end
end
def class_name
@class_name
end
def method_name
@method_name || @name
end
def context
if gem?
:gem
elsif application?
:application
else
:dunno
end
end
def pretty_path
case context
when :application; application_path
when :gem; gem_path
else filename
end
end
def local_variables
return {} unless frame_binding
lv = frame_binding.eval("local_variables")
return {} unless lv
lv.each_with_object({}) do |name, hash|
# Ruby 2.2's local_variables will include the hidden #$! variable if
# called from within a rescue context. This is not a valid variable name,
# so the local_variable_get method complains. This should probably be
# considered a bug in Ruby itself, but we need to work around it.
next if name == :"\#$!"
hash[name] = local_variable(name)
end
end
def local_variable(name)
get_local_variable(name) || eval_local_variable(name)
rescue NameError => ex
"#{ex.class}: #{ex.message}"
end
def instance_variables
return {} unless frame_binding
Hash[visible_instance_variables.map { |x|
[x, frame_binding.eval(x.to_s)]
}]
end
def visible_instance_variables
iv = frame_binding.eval("instance_variables")
return {} unless iv
iv - BetterErrors.ignored_instance_variables
end
def to_s
"#{pretty_path}:#{line}:in `#{name}'"
end
private
def set_pretty_method_name
name =~ /\A(block (\([^)]+\) )?in )?/
recv = frame_binding.eval("self")
return unless method_name = frame_binding.eval("::Kernel.__method__")
if Module === recv
@class_name = "#{$1}#{recv}"
@method_name = ".#{method_name}"
else
@class_name = "#{$1}#{Kernel.instance_method(:class).bind(recv).call}"
@method_name = "##{method_name}"
end
end
def get_local_variable(name)
if defined?(frame_binding.local_variable_get)
frame_binding.local_variable_get(name)
end
end
def eval_local_variable(name)
frame_binding.eval(name.to_s)
end
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/lib/better_errors/repl/pry.rb | lib/better_errors/repl/pry.rb | require "fiber"
require "pry"
module BetterErrors
module REPL
class Pry
class Input
def readline
Fiber.yield
end
end
class Output
def initialize
@buffer = ""
end
def puts(*args)
args.each do |arg|
@buffer << "#{arg.chomp}\n"
end
end
def tty?
false
end
def read_buffer
@buffer
ensure
@buffer = ""
end
def print(*args)
@buffer << args.join(' ')
end
end
def initialize(binding, exception)
@fiber = Fiber.new do
@pry.repl binding
end
@input = BetterErrors::REPL::Pry::Input.new
@output = BetterErrors::REPL::Pry::Output.new
@pry = ::Pry.new input: @input, output: @output
@pry.hooks.clear_all if defined?(@pry.hooks.clear_all)
store_last_exception exception
@fiber.resume
end
def store_last_exception(exception)
return unless defined? ::Pry::LastException
@pry.instance_variable_set(:@last_exception, ::Pry::LastException.new(exception.exception))
end
def send_input(str)
local ::Pry.config, color: false, pager: false do
@fiber.resume "#{str}\n"
[@output.read_buffer, *prompt]
end
end
def prompt
if indent = @pry.instance_variable_get(:@indent) and !indent.indent_level.empty?
["..", indent.indent_level]
else
[">>", ""]
end
rescue
[">>", ""]
end
private
def local(obj, attrs)
old_attrs = {}
attrs.each do |k, v|
old_attrs[k] = obj.send k
obj.send "#{k}=", v
end
yield
ensure
old_attrs.each do |k, v|
obj.send "#{k}=", v
end
end
end
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/lib/better_errors/repl/basic.rb | lib/better_errors/repl/basic.rb | module BetterErrors
module REPL
class Basic
def initialize(binding, _exception)
@binding = binding
end
def send_input(str)
[execute(str), ">>", ""]
end
private
def execute(str)
"=> #{@binding.eval(str).inspect}\n"
rescue Exception => e
"!! #{e.inspect rescue e.class.to_s rescue "Exception"}\n"
end
end
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/lib/better_errors/code_formatter/text.rb | lib/better_errors/code_formatter/text.rb | module BetterErrors
# @private
class CodeFormatter::Text < CodeFormatter
def source_unavailable
"# Source is not available"
end
def formatted_lines
each_line_of(context_lines) { |highlight, current_line, str|
sprintf '%s %3d %s', (highlight ? '>' : ' '), current_line, str
}
end
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
BetterErrors/better_errors | https://github.com/BetterErrors/better_errors/blob/fde3b7025db17b5cda13fcf8d08dfb3f76e189f6/lib/better_errors/code_formatter/html.rb | lib/better_errors/code_formatter/html.rb | require "rouge"
module BetterErrors
# @private
class CodeFormatter::HTML < CodeFormatter
def source_unavailable
"<p class='unavailable'>Source is not available</p>"
end
def formatted_lines
each_line_of(highlighted_lines) { |highlight, current_line, str|
class_name = highlight ? "highlight" : ""
sprintf '<pre class="%s">%s</pre>', class_name, str
}
end
def formatted_nums
each_line_of(highlighted_lines) { |highlight, current_line, str|
class_name = highlight ? "highlight" : ""
sprintf '<span class="%s">%5d</span>', class_name, current_line
}
end
def formatted_code
%{
<div class="code_linenums">#{formatted_nums.join}</div>
<div class="code"><div class='code-wrapper'>#{super}</div></div>
}
end
def rouge_lexer
Rouge::Lexer.guess(filename: filename, source: source) { Rouge::Lexers::Ruby }
end
def highlighted_lines
Rouge::Formatters::HTML.new.format(rouge_lexer.lex(context_lines.join)).lines
end
end
end
| ruby | MIT | fde3b7025db17b5cda13fcf8d08dfb3f76e189f6 | 2026-01-04T15:39:58.699166Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/benchmark/parse_ips.rb | benchmark/parse_ips.rb | require "bundler/setup"
require "dotenv"
require "benchmark/ips"
require "tempfile"
f = Tempfile.create("benchmark_ips.env")
1000.times.map { |i| f.puts "VAR_#{i}=#{i}" }
f.close
Benchmark.ips do |x|
x.report("parse, overwrite:false") { Dotenv.parse(f.path, overwrite: false) }
x.report("parse, overwrite:true") { Dotenv.parse(f.path, overwrite: true) }
end
File.unlink(f.path)
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/benchmark/parse_profile.rb | benchmark/parse_profile.rb | require "bundler/setup"
require "dotenv"
require "stackprof"
require "benchmark/ips"
require "tempfile"
f = Tempfile.create("benchmark_ips.env")
1000.times.map { |i| f.puts "VAR_#{i}=#{i}" }
f.close
profile = StackProf.run(mode: :wall, interval: 1_000) do
10_000.times do
Dotenv.parse(f.path, overwrite: false)
end
end
result = StackProf::Report.new(profile)
puts
result.print_text
puts "\n\n\n"
result.print_method(/Dotenv.parse/)
File.unlink(f.path)
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/test/autorestore_test.rb | test/autorestore_test.rb | require "active_support" # Rails 6.1 fails if this is not loaded
require "active_support/test_case"
require "minitest/autorun"
require "dotenv"
require "dotenv/autorestore"
class AutorestoreTest < ActiveSupport::TestCase
test "restores ENV between tests, part 1" do
assert_nil ENV["DOTENV"], "ENV was not restored between tests"
ENV["DOTENV"] = "1"
end
test "restores ENV between tests, part 2" do
assert_nil ENV["DOTENV"], "ENV was not restored between tests"
ENV["DOTENV"] = "2"
end
end
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/spec/dotenv_spec.rb | spec/dotenv_spec.rb | require "spec_helper"
describe Dotenv do
before do
Dir.chdir(File.expand_path("../fixtures", __FILE__))
end
shared_examples "load" do
context "with no args" do
let(:env_files) { [] }
it "defaults to .env" do
expect(Dotenv::Environment).to receive(:new).with(expand(".env"), anything).and_call_original
subject
end
end
context "with a tilde path" do
let(:env_files) { ["~/.env"] }
it "expands the path" do
expected = expand("~/.env")
allow(File).to receive(:exist?) { |arg| arg == expected }
expect(Dotenv::Environment).to receive(:new).with(expected, anything)
.and_return(Dotenv::Environment.new(".env"))
subject
end
end
context "with multiple files" do
let(:env_files) { [".env", fixture_path("plain.env")] }
let(:expected) do
{"OPTION_A" => "1",
"OPTION_B" => "2",
"OPTION_C" => "3",
"OPTION_D" => "4",
"OPTION_E" => "5",
"PLAIN" => "true",
"DOTENV" => "true"}
end
it "loads all files" do
subject
expected.each do |key, value|
expect(ENV[key]).to eq(value)
end
end
it "returns hash of loaded variables" do
expect(subject).to eq(expected)
end
it "does not return unchanged variables" do
ENV["OPTION_A"] = "1"
expect(subject).not_to have_key("OPTION_A")
end
end
end
shared_examples "overwrite" do
it_behaves_like "load"
context "with multiple files" do
let(:env_files) { [fixture_path("important.env"), fixture_path("plain.env")] }
let(:expected) do
{
"OPTION_A" => "abc",
"OPTION_B" => "2",
"OPTION_C" => "3",
"OPTION_D" => "4",
"OPTION_E" => "5",
"PLAIN" => "false"
}
end
it "respects the file importance order" do
subject
expected.each do |key, value|
expect(ENV[key]).to eq(value)
end
end
end
end
describe "load" do
let(:env_files) { [] }
let(:options) { {} }
subject { Dotenv.load(*env_files, **options) }
it_behaves_like "load"
it "initializes the Environment with overwrite: false" do
expect(Dotenv::Environment).to receive(:new).with(anything, overwrite: false)
.and_call_original
subject
end
it "warns about not overwriting when requested" do
options[:overwrite] = :warn
ENV["DOTENV"] = "false"
expect(capture_output { subject }).to eq("Warning: dotenv not overwriting ENV[\"DOTENV\"]\n")
expect(ENV["DOTENV"]).to eq("false")
end
context "when the file does not exist" do
let(:env_files) { [".env_does_not_exist"] }
it "fails silently" do
expect { subject }.not_to raise_error
end
it "does not change ENV" do
expect { subject }.not_to change { ENV.inspect }
end
end
context "when the file is a directory" do
let(:env_files) { [] }
around do |example|
Dir.mktmpdir do |dir|
env_files.push dir
example.run
end
end
it "fails silently with ignore: true (default)" do
expect { subject }.not_to raise_error
end
it "raises error with ignore: false" do
options[:ignore] = false
expect { subject }.to raise_error(/Is a directory/)
end
end
end
describe "load!" do
let(:env_files) { [] }
subject { Dotenv.load!(*env_files) }
it_behaves_like "load"
it "initializes Environment with overwrite: false" do
expect(Dotenv::Environment).to receive(:new).with(anything, overwrite: false)
.and_call_original
subject
end
context "when one file exists and one does not" do
let(:env_files) { [".env", ".env_does_not_exist"] }
it "raises an Errno::ENOENT error" do
expect { subject }.to raise_error(Errno::ENOENT)
end
end
end
describe "overwrite" do
let(:env_files) { [fixture_path("plain.env")] }
subject { Dotenv.overwrite(*env_files) }
it_behaves_like "load"
it_behaves_like "overwrite"
it "initializes the Environment overwrite: true" do
expect(Dotenv::Environment).to receive(:new).with(anything, overwrite: true)
.and_call_original
subject
end
context "when loading a file containing already set variables" do
let(:env_files) { [fixture_path("plain.env")] }
it "overwrites any existing ENV variables" do
ENV["OPTION_A"] = "predefined"
subject
expect(ENV["OPTION_A"]).to eq("1")
end
end
context "when the file does not exist" do
let(:env_files) { [".env_does_not_exist"] }
it "fails silently" do
expect { subject }.not_to raise_error
end
it "does not change ENV" do
expect { subject }.not_to change { ENV.inspect }
end
end
end
describe "overwrite!" do
let(:env_files) { [fixture_path("plain.env")] }
subject { Dotenv.overwrite!(*env_files) }
it_behaves_like "load"
it_behaves_like "overwrite"
it "initializes the Environment with overwrite: true" do
expect(Dotenv::Environment).to receive(:new).with(anything, overwrite: true)
.and_call_original
subject
end
context "when loading a file containing already set variables" do
let(:env_files) { [fixture_path("plain.env")] }
it "overwrites any existing ENV variables" do
ENV["OPTION_A"] = "predefined"
subject
expect(ENV["OPTION_A"]).to eq("1")
end
end
context "when one file exists and one does not" do
let(:env_files) { [".env", ".env_does_not_exist"] }
it "raises an Errno::ENOENT error" do
expect { subject }.to raise_error(Errno::ENOENT)
end
end
end
describe "with an instrumenter" do
let(:instrumenter) { double("instrumenter", instrument: {}) }
before { Dotenv.instrumenter = instrumenter }
after { Dotenv.instrumenter = nil }
describe "load" do
it "instruments if the file exists" do
expect(instrumenter).to receive(:instrument) do |name, payload|
expect(name).to eq("load.dotenv")
expect(payload[:env]).to be_instance_of(Dotenv::Environment)
{}
end
Dotenv.load
end
it "does not instrument if file does not exist" do
expect(instrumenter).to receive(:instrument).never
Dotenv.load ".doesnotexist"
end
end
end
describe "require keys" do
let(:env_files) { [".env", fixture_path("bom.env")] }
before { Dotenv.load(*env_files) }
it "raises exception with not defined mandatory ENV keys" do
expect { Dotenv.require_keys("BOM", "TEST") }.to raise_error(
Dotenv::MissingKeys,
'Missing required configuration key: ["TEST"]'
)
end
it "raises exception when missing multiple mandator keys" do
expect { Dotenv.require_keys("TEST1", "TEST2") }.to raise_error(
Dotenv::MissingKeys,
'Missing required configuration keys: ["TEST1", "TEST2"]'
)
end
end
describe "parse" do
let(:env_files) { [] }
subject { Dotenv.parse(*env_files) }
context "with no args" do
let(:env_files) { [] }
it "defaults to .env" do
expect(Dotenv::Environment).to receive(:new).with(expand(".env"),
anything)
subject
end
end
context "with a tilde path" do
let(:env_files) { ["~/.env"] }
it "expands the path" do
expected = expand("~/.env")
allow(File).to receive(:exist?) { |arg| arg == expected }
expect(Dotenv::Environment).to receive(:new).with(expected, anything)
subject
end
end
context "with multiple files" do
let(:env_files) { [".env", fixture_path("plain.env")] }
let(:expected) do
{"OPTION_A" => "1",
"OPTION_B" => "2",
"OPTION_C" => "3",
"OPTION_D" => "4",
"OPTION_E" => "5",
"PLAIN" => "true",
"DOTENV" => "true"}
end
it "does not modify ENV" do
subject
expected.each do |key, _value|
expect(ENV[key]).to be_nil
end
end
it "returns hash of parsed key/value pairs" do
expect(subject).to eq(expected)
end
end
it "initializes the Environment with overwrite: false" do
expect(Dotenv::Environment).to receive(:new).with(anything, overwrite: false)
subject
end
context "when the file does not exist" do
let(:env_files) { [".env_does_not_exist"] }
it "fails silently" do
expect { subject }.not_to raise_error
expect(subject).to eq({})
end
end
end
describe "Unicode" do
subject { fixture_path("bom.env") }
it "loads a file with a Unicode BOM" do
expect(Dotenv.load(subject)).to eql("BOM" => "UTF-8")
end
it "fixture file has UTF-8 BOM" do
contents = File.binread(subject).force_encoding("UTF-8")
expect(contents).to start_with("\xEF\xBB\xBF".force_encoding("UTF-8"))
end
end
describe "restore" do
it "restores previously saved snapshot" do
ENV["MODIFIED"] = "true"
Dotenv.restore # save was already called in setup
expect(ENV["MODIFIED"]).to be_nil
end
it "raises an error in threads" do
ENV["MODIFIED"] = "true"
Thread.new do
expect { Dotenv.restore }.to raise_error(ThreadError, /not thread safe/)
end.join
expect(ENV["MODIFIED"]).to eq("true")
end
it "is a noop if nil state provided" do
expect { Dotenv.restore(nil) }.not_to raise_error
end
it "is a noop if no previously saved state" do
# Clear state saved in setup
expect(Dotenv.instance_variable_get(:@diff)).to be_instance_of(Dotenv::Diff)
Dotenv.instance_variable_set(:@diff, nil)
expect { Dotenv.restore }.not_to raise_error
end
it "can save and restore stubbed ENV" do
stub_const("ENV", ENV.to_h.merge("STUBBED" => "1"))
Dotenv.save
ENV["MODIFIED"] = "1"
Dotenv.restore
expect(ENV["STUBBED"]).to eq("1")
expect(ENV["MODIFED"]).to be(nil)
end
end
describe "modify" do
it "sets values for the block" do
ENV["FOO"] = "initial"
Dotenv.modify(FOO: "during", BAR: "baz") do
expect(ENV["FOO"]).to eq("during")
expect(ENV["BAR"]).to eq("baz")
end
expect(ENV["FOO"]).to eq("initial")
expect(ENV).not_to have_key("BAR")
end
end
describe "update" do
it "sets new variables" do
Dotenv.update({"OPTION_A" => "1"})
expect(ENV["OPTION_A"]).to eq("1")
end
it "does not overwrite defined variables" do
ENV["OPTION_A"] = "original"
Dotenv.update({"OPTION_A" => "updated"})
expect(ENV["OPTION_A"]).to eq("original")
end
context "with overwrite: true" do
it "sets new variables" do
Dotenv.update({"OPTION_A" => "1"}, overwrite: true)
expect(ENV["OPTION_A"]).to eq("1")
end
it "overwrites defined variables" do
ENV["OPTION_A"] = "original"
Dotenv.update({"OPTION_A" => "updated"}, overwrite: true)
expect(ENV["OPTION_A"]).to eq("updated")
end
end
end
def expand(path)
File.expand_path path
end
end
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/spec/spec_helper.rb | spec/spec_helper.rb | require "dotenv"
require "dotenv/autorestore"
require "tmpdir"
def fixture_path(*parts)
Pathname.new(__dir__).join("./fixtures", *parts)
end
# Capture output to $stdout and $stderr
def capture_output(&_block)
original_stderr = $stderr
original_stdout = $stdout
output = $stderr = $stdout = StringIO.new
yield
output.string
ensure
$stderr = original_stderr
$stdout = original_stdout
end
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/spec/dotenv/rails_spec.rb | spec/dotenv/rails_spec.rb | require "spec_helper"
require "rails"
require "dotenv/rails"
describe Dotenv::Rails do
let(:log_output) { StringIO.new }
let(:application) do
log_output = self.log_output
Class.new(Rails::Application) do
config.load_defaults Rails::VERSION::STRING.to_f
config.eager_load = false
config.logger = ActiveSupport::Logger.new(log_output)
config.root = fixture_path
# Remove method fails since app is reloaded for each test
config.active_support.remove_deprecated_time_with_zone_name = false
end.instance
end
around do |example|
# These get frozen after the app initializes
autoload_paths = ActiveSupport::Dependencies.autoload_paths.dup
autoload_once_paths = ActiveSupport::Dependencies.autoload_once_paths.dup
# Run in fixtures directory
Dir.chdir(fixture_path) { example.run }
ensure
# Restore autoload paths to unfrozen state
ActiveSupport::Dependencies.autoload_paths = autoload_paths
ActiveSupport::Dependencies.autoload_once_paths = autoload_once_paths
end
before do
Rails.env = "test"
Rails.application = nil
Rails.logger = nil
begin
# Remove the singleton instance if it exists
Dotenv::Rails.remove_instance_variable(:@instance)
rescue
nil
end
end
describe "files" do
it "loads files for development environment" do
Rails.env = "development"
expect(Dotenv::Rails.files).to eql(
[
".env.development.local",
".env.local",
".env.development",
".env"
]
)
end
it "does not load .env.local in test rails environment" do
Rails.env = "test"
expect(Dotenv::Rails.files).to eql(
[
".env.test.local",
".env.test",
".env"
]
)
end
it "can be modified in place" do
Dotenv::Rails.files << ".env.shared"
expect(Dotenv::Rails.files.last).to eq(".env.shared")
end
end
it "watches other loaded files with Spring" do
stub_spring(load_watcher: true)
application.initialize!
path = fixture_path("plain.env")
Dotenv.load(path)
expect(Spring.watcher).to include(path.to_s)
end
it "doesn't raise an error if Spring.watch is not defined" do
stub_spring(load_watcher: false)
expect {
application.initialize!
}.to_not raise_error
end
context "before_configuration" do
it "calls #load" do
expect(Dotenv::Rails.instance).to receive(:load)
ActiveSupport.run_load_hooks(:before_configuration)
end
end
context "load" do
subject { application.initialize! }
it "watches .env with Spring" do
stub_spring(load_watcher: true)
subject
expect(Spring.watcher).to include(fixture_path(".env").to_s)
end
it "loads .env.test before .env" do
subject
expect(ENV["DOTENV"]).to eql("test")
end
it "loads configured files" do
Dotenv::Rails.files = [fixture_path("plain.env")]
expect { subject }.to change { ENV["PLAIN"] }.from(nil).to("true")
end
it "loads file relative to Rails.root" do
allow(Rails).to receive(:root).and_return(Pathname.new("/tmp"))
Dotenv::Rails.files = [".env"]
expect(Dotenv).to receive(:load).with("/tmp/.env", {overwrite: false})
subject
end
it "returns absolute paths unchanged" do
Dotenv::Rails.files = ["/tmp/.env"]
expect(Dotenv).to receive(:load).with("/tmp/.env", {overwrite: false})
subject
end
context "with overwrite = true" do
before { Dotenv::Rails.overwrite = true }
it "overwrites .env with .env.test" do
subject
expect(ENV["DOTENV"]).to eql("test")
end
it "overwrites any existing ENV variables" do
ENV["DOTENV"] = "predefined"
expect { subject }.to(change { ENV["DOTENV"] }.from("predefined").to("test"))
end
end
end
describe "root" do
it "returns Rails.root" do
expect(Dotenv::Rails.root).to eql(Rails.root)
end
context "when Rails.root is nil" do
before do
allow(Rails).to receive(:root).and_return(nil)
end
it "falls back to RAILS_ROOT" do
ENV["RAILS_ROOT"] = "/tmp"
expect(Dotenv::Rails.root.to_s).to eql("/tmp")
end
end
end
describe "autorestore" do
it "is loaded if RAILS_ENV=test" do
expect(Dotenv::Rails.autorestore).to eq(true)
expect(Dotenv::Rails.instance).to receive(:require).with("dotenv/autorestore")
application.initialize!
end
it "is not loaded if RAILS_ENV=development" do
Rails.env = "development"
expect(Dotenv::Rails.autorestore).to eq(false)
expect(Dotenv::Rails.instance).not_to receive(:require).with("dotenv/autorestore")
application.initialize!
end
it "is not loaded if autorestore set to false" do
Dotenv::Rails.autorestore = false
expect(Dotenv::Rails.instance).not_to receive(:require).with("dotenv/autorestore")
application.initialize!
end
it "is not loaded if ClimateControl is defined" do
stub_const("ClimateControl", Module.new)
expect(Dotenv::Rails.instance).not_to receive(:require).with("dotenv/autorestore")
application.initialize!
end
it "is not loaded if IceAge is defined" do
stub_const("IceAge", Module.new)
expect(Dotenv::Rails.instance).not_to receive(:require).with("dotenv/autorestore")
application.initialize!
end
end
describe "logger" do
it "replays to Rails.logger" do
expect(Dotenv::Rails.logger).to be_a(Dotenv::ReplayLogger)
Dotenv::Rails.logger.debug("test")
application.initialize!
expect(Dotenv::Rails.logger).not_to be_a(Dotenv::ReplayLogger)
expect(log_output.string).to include("[dotenv] test")
end
it "does not replace custom logger" do
logger = Logger.new(log_output)
Dotenv::Rails.logger = logger
application.initialize!
expect(Dotenv::Rails.logger).to be(logger)
end
end
def stub_spring(load_watcher: true)
spring = Module.new do
if load_watcher
def self.watcher
@watcher ||= Set.new
end
def self.watch(path)
watcher.add path
end
end
end
stub_const "Spring", spring
end
end
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/spec/dotenv/log_subscriber_spec.rb | spec/dotenv/log_subscriber_spec.rb | require "spec_helper"
require "active_support/all"
require "rails"
require "dotenv/rails"
describe Dotenv::LogSubscriber do
let(:logs) { StringIO.new }
before do
Dotenv.instrumenter = ActiveSupport::Notifications
Dotenv::Rails.logger = Logger.new(logs)
end
describe "load" do
it "logs when a file is loaded" do
Dotenv.load(fixture_path("plain.env"))
expect(logs.string).to match(/Loaded.*plain.env/)
expect(logs.string).to match(/Set.*PLAIN/)
end
end
context "update" do
it "logs when a new instance variable is set" do
Dotenv.update({"PLAIN" => "true"})
expect(logs.string).to match(/Set.*PLAIN/)
end
it "logs when an instance variable is overwritten" do
ENV["PLAIN"] = "nope"
Dotenv.update({"PLAIN" => "true"}, overwrite: true)
expect(logs.string).to match(/Set.*PLAIN/)
end
it "does not log when an instance variable is not overwritten" do
ENV["FOO"] = "existing"
Dotenv.update({"FOO" => "new"})
expect(logs.string).not_to match(/FOO/)
end
it "does not log when an instance variable is unchanged" do
ENV["PLAIN"] = "true"
Dotenv.update({"PLAIN" => "true"}, overwrite: true)
expect(logs.string).not_to match(/PLAIN/)
end
end
context "save" do
it "logs when a snapshot is saved" do
Dotenv.save
expect(logs.string).to match(/Saved/)
end
end
context "restore" do
it "logs restored keys" do
previous_value = ENV["PWD"]
ENV["PWD"] = "/tmp"
Dotenv.restore
expect(logs.string).to match(/Restored.*PWD/)
# Does not log value
expect(logs.string).not_to include(previous_value)
end
it "logs unset keys" do
ENV["DOTENV_TEST"] = "LogSubscriber"
Dotenv.restore
expect(logs.string).to match(/Unset.*DOTENV_TEST/)
end
it "does not log if no keys unset or restored" do
Dotenv.restore
expect(logs.string).not_to match(/Restored|Unset/)
end
end
end
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/spec/dotenv/cli_spec.rb | spec/dotenv/cli_spec.rb | require "spec_helper"
require "dotenv/cli"
describe "dotenv binary" do
before do
Dir.chdir(File.expand_path("../../fixtures", __FILE__))
end
def run(*args)
Dotenv::CLI.new(args).run
end
it "loads from .env by default" do
expect(ENV).not_to have_key("DOTENV")
run
expect(ENV).to have_key("DOTENV")
end
it "loads from file specified by -f" do
expect(ENV).not_to have_key("OPTION_A")
run "-f", "plain.env"
expect(ENV).to have_key("OPTION_A")
end
it "dies if file specified by -f doesn't exist" do
expect do
capture_output { run "-f", ".doesnotexist" }
end.to raise_error(SystemExit, /No such file/)
end
it "ignores missing files when --ignore flag given" do
expect do
run "--ignore", "-f", ".doesnotexist"
end.not_to raise_error
end
it "loads from multiple files specified by -f" do
expect(ENV).not_to have_key("PLAIN")
expect(ENV).not_to have_key("QUOTED")
run "-f", "plain.env,quoted.env"
expect(ENV).to have_key("PLAIN")
expect(ENV).to have_key("QUOTED")
end
it "does not consume non-dotenv flags by accident" do
cli = Dotenv::CLI.new(["-f", "plain.env", "foo", "--switch"])
expect(cli.filenames).to eql(["plain.env"])
expect(cli.argv).to eql(["foo", "--switch"])
end
it "does not consume dotenv flags from subcommand" do
cli = Dotenv::CLI.new(["foo", "-f", "something"])
expect(cli.filenames).to eql([])
expect(cli.argv).to eql(["foo", "-f", "something"])
end
it "does not mess with quoted args" do
cli = Dotenv::CLI.new(["foo something"])
expect(cli.filenames).to eql([])
expect(cli.argv).to eql(["foo something"])
end
describe "templates a file specified by -t" do
before do
@buffer = StringIO.new
@origin_filename = "plain.env"
@template_filename = "plain.env.template"
end
it "templates variables" do
@input = StringIO.new("FOO=BAR\nFOO2=BAR2")
allow(File).to receive(:open).with(@origin_filename, "r").and_yield(@input)
allow(File).to receive(:open).with(@template_filename, "w").and_yield(@buffer)
# call the function that writes to the file
Dotenv::CLI.new(["-t", @origin_filename])
# reading the buffer and checking its content.
expect(@buffer.string).to eq("FOO=FOO\nFOO2=FOO2\n")
end
it "templates variables with export prefix" do
@input = StringIO.new("export FOO=BAR\nexport FOO2=BAR2")
allow(File).to receive(:open).with(@origin_filename, "r").and_yield(@input)
allow(File).to receive(:open).with(@template_filename, "w").and_yield(@buffer)
Dotenv::CLI.new(["-t", @origin_filename])
expect(@buffer.string).to eq("export FOO=FOO\nexport FOO2=FOO2\n")
end
it "templates multi-line variables" do
@input = StringIO.new(<<~TEXT)
FOO=BAR
FOO2="BAR2
BAR2"
TEXT
allow(File).to receive(:open).with(@origin_filename, "r").and_yield(@input)
allow(File).to receive(:open).with(@template_filename, "w").and_yield(@buffer)
# call the function that writes to the file
Dotenv::CLI.new(["-t", @origin_filename])
# reading the buffer and checking its content.
expect(@buffer.string).to eq("FOO=FOO\nFOO2=FOO2\n")
end
it "ignores blank lines" do
@input = StringIO.new("\nFOO=BAR\nFOO2=BAR2")
allow(File).to receive(:open).with(@origin_filename, "r").and_yield(@input)
allow(File).to receive(:open).with(@template_filename, "w").and_yield(@buffer)
Dotenv::CLI.new(["-t", @origin_filename])
expect(@buffer.string).to eq("\nFOO=FOO\nFOO2=FOO2\n")
end
it "ignores comments" do
@comment_input = StringIO.new("#Heading comment\nFOO=BAR\nFOO2=BAR2\n")
allow(File).to receive(:open).with(@origin_filename, "r").and_yield(@comment_input)
allow(File).to receive(:open).with(@template_filename, "w").and_yield(@buffer)
Dotenv::CLI.new(["-t", @origin_filename])
expect(@buffer.string).to eq("#Heading comment\nFOO=FOO\nFOO2=FOO2\n")
end
it "ignores comments with =" do
@comment_with_equal_input = StringIO.new("#Heading=comment\nFOO=BAR\nFOO2=BAR2")
allow(File).to receive(:open).with(@origin_filename, "r").and_yield(@comment_with_equal_input)
allow(File).to receive(:open).with(@template_filename, "w").and_yield(@buffer)
Dotenv::CLI.new(["-t", @origin_filename])
expect(@buffer.string).to eq("#Heading=comment\nFOO=FOO\nFOO2=FOO2\n")
end
it "ignores comments with leading spaces" do
@comment_leading_spaces_input = StringIO.new(" #Heading comment\nFOO=BAR\nFOO2=BAR2")
allow(File).to receive(:open).with(@origin_filename, "r").and_yield(@comment_leading_spaces_input)
allow(File).to receive(:open).with(@template_filename, "w").and_yield(@buffer)
Dotenv::CLI.new(["-t", @origin_filename])
expect(@buffer.string).to eq(" #Heading comment\nFOO=FOO\nFOO2=FOO2\n")
end
end
end
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/spec/dotenv/diff_spec.rb | spec/dotenv/diff_spec.rb | require "spec_helper"
describe Dotenv::Diff do
let(:before) { {} }
let(:after) { {} }
subject { Dotenv::Diff.new(a: before, b: after) }
context "no changes" do
let(:before) { {"A" => 1} }
let(:after) { {"A" => 1} }
it { expect(subject.added).to eq({}) }
it { expect(subject.removed).to eq({}) }
it { expect(subject.changed).to eq({}) }
it { expect(subject.any?).to eq(false) }
it { expect(subject.env).to eq({}) }
end
context "key added" do
let(:after) { {"A" => 1} }
it { expect(subject.added).to eq("A" => 1) }
it { expect(subject.removed).to eq({}) }
it { expect(subject.changed).to eq({}) }
it { expect(subject.any?).to eq(true) }
it { expect(subject.env).to eq("A" => 1) }
end
context "key removed" do
let(:before) { {"A" => 1} }
it { expect(subject.added).to eq({}) }
it { expect(subject.removed).to eq("A" => 1) }
it { expect(subject.changed).to eq({}) }
it { expect(subject.any?).to eq(true) }
it { expect(subject.env).to eq("A" => nil) }
end
context "key changed" do
let(:before) { {"A" => 1} }
let(:after) { {"A" => 2} }
it { expect(subject.added).to eq({}) }
it { expect(subject.removed).to eq({}) }
it { expect(subject.changed).to eq("A" => [1, 2]) }
it { expect(subject.any?).to eq(true) }
it { expect(subject.env).to eq("A" => 2) }
end
end
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/spec/dotenv/parser_spec.rb | spec/dotenv/parser_spec.rb | require "spec_helper"
describe Dotenv::Parser do
def env(...)
Dotenv::Parser.call(...)
end
it "parses unquoted values" do
expect(env("FOO=bar")).to eql("FOO" => "bar")
end
it "parses unquoted values with spaces after seperator" do
expect(env("FOO= bar")).to eql("FOO" => "bar")
end
it "parses unquoted escape characters correctly" do
expect(env("FOO=bar\\ bar")).to eql("FOO" => "bar bar")
end
it "parses values with spaces around equal sign" do
expect(env("FOO =bar")).to eql("FOO" => "bar")
expect(env("FOO= bar")).to eql("FOO" => "bar")
end
it "parses values with leading spaces" do
expect(env(" FOO=bar")).to eql("FOO" => "bar")
end
it "parses values with following spaces" do
expect(env("FOO=bar ")).to eql("FOO" => "bar")
end
it "parses double quoted values" do
expect(env('FOO="bar"')).to eql("FOO" => "bar")
end
it "parses double quoted values with following spaces" do
expect(env('FOO="bar" ')).to eql("FOO" => "bar")
end
it "parses single quoted values" do
expect(env("FOO='bar'")).to eql("FOO" => "bar")
end
it "parses single quoted values with following spaces" do
expect(env("FOO='bar' ")).to eql("FOO" => "bar")
end
it "parses escaped double quotes" do
expect(env('FOO="escaped\"bar"')).to eql("FOO" => 'escaped"bar')
end
it "parses empty values" do
expect(env("FOO=")).to eql("FOO" => "")
end
it "expands variables found in values" do
expect(env("FOO=test\nBAR=$FOO")).to eql("FOO" => "test", "BAR" => "test")
end
it "parses variables wrapped in brackets" do
expect(env("FOO=test\nBAR=${FOO}bar"))
.to eql("FOO" => "test", "BAR" => "testbar")
end
it "expands variables from ENV if not found in .env" do
ENV["FOO"] = "test"
expect(env("BAR=$FOO")).to eql("BAR" => "test")
end
it "expands variables from ENV if found in .env during load" do
ENV["FOO"] = "test"
expect(env("FOO=development\nBAR=${FOO}")["BAR"])
.to eql("test")
end
it "doesn't expand variables from ENV if in local env in overwrite" do
ENV["FOO"] = "test"
expect(env("FOO=development\nBAR=${FOO}")["BAR"])
.to eql("test")
end
it "expands undefined variables to an empty string" do
expect(env("BAR=$FOO")).to eql("BAR" => "")
end
it "expands variables in double quoted strings" do
expect(env("FOO=test\nBAR=\"quote $FOO\""))
.to eql("FOO" => "test", "BAR" => "quote test")
end
it "does not expand variables in single quoted strings" do
expect(env("BAR='quote $FOO'")).to eql("BAR" => "quote $FOO")
end
it "does not expand escaped variables" do
expect(env('FOO="foo\$BAR"')).to eql("FOO" => "foo$BAR")
expect(env('FOO="foo\${BAR}"')).to eql("FOO" => "foo${BAR}")
expect(env("FOO=test\nBAR=\"foo\\${FOO} ${FOO}\""))
.to eql("FOO" => "test", "BAR" => "foo${FOO} test")
end
it "parses yaml style options" do
expect(env("OPTION_A: 1")).to eql("OPTION_A" => "1")
end
it "parses export keyword" do
expect(env("export OPTION_A=2")).to eql("OPTION_A" => "2")
end
it "allows export line if you want to do it that way" do
expect(env('OPTION_A=2
export OPTION_A')).to eql("OPTION_A" => "2")
end
it "allows export line if you want to do it that way and checks for unset variables" do
expect do
env('OPTION_A=2
export OH_NO_NOT_SET')
end.to raise_error(Dotenv::FormatError, 'Line "export OH_NO_NOT_SET" has an unset variable')
end
it 'escapes \n in quoted strings' do
expect(env('FOO="bar\nbaz"')).to eql("FOO" => "bar\\nbaz")
expect(env('FOO="bar\\nbaz"')).to eql("FOO" => "bar\\nbaz")
end
it 'expands \n and \r in quoted strings with DOTENV_LINEBREAK_MODE=legacy in current file' do
ENV["DOTENV_LINEBREAK_MODE"] = "strict"
contents = [
"DOTENV_LINEBREAK_MODE=legacy",
'FOO="bar\nbaz\rfizz"'
].join("\n")
expect(env(contents)).to eql("DOTENV_LINEBREAK_MODE" => "legacy", "FOO" => "bar\nbaz\rfizz")
end
it 'expands \n and \r in quoted strings with DOTENV_LINEBREAK_MODE=legacy in ENV' do
ENV["DOTENV_LINEBREAK_MODE"] = "legacy"
contents = 'FOO="bar\nbaz\rfizz"'
expect(env(contents)).to eql("FOO" => "bar\nbaz\rfizz")
end
it 'parses variables with "." in the name' do
expect(env("FOO.BAR=foobar")).to eql("FOO.BAR" => "foobar")
end
it "strips unquoted values" do
expect(env("foo=bar ")).to eql("foo" => "bar") # not 'bar '
end
it "ignores lines that are not variable assignments" do
expect(env("lol$wut")).to eql({})
end
it "ignores empty lines" do
expect(env("\n \t \nfoo=bar\n \nfizz=buzz"))
.to eql("foo" => "bar", "fizz" => "buzz")
end
it "does not ignore empty lines in quoted string" do
value = "a\n\nb\n\nc"
expect(env("FOO=\"#{value}\"")).to eql("FOO" => value)
end
it "ignores inline comments" do
expect(env("foo=bar # this is foo")).to eql("foo" => "bar")
end
it "allows # in quoted value" do
expect(env('foo="bar#baz" # comment')).to eql("foo" => "bar#baz")
end
it "allows # in quoted value with spaces after seperator" do
expect(env('foo= "bar#baz" # comment')).to eql("foo" => "bar#baz")
end
it "ignores comment lines" do
expect(env("\n\n\n # HERE GOES FOO \nfoo=bar")).to eql("foo" => "bar")
end
it "ignores commented out variables" do
expect(env("# HELLO=world\n")).to eql({})
end
it "ignores comment" do
expect(env("# Uncomment to activate:\n")).to eql({})
end
it "includes variables without values" do
input = 'DATABASE_PASSWORD=
DATABASE_USERNAME=root
DATABASE_HOST=/tmp/mysql.sock'
output = {
"DATABASE_PASSWORD" => "",
"DATABASE_USERNAME" => "root",
"DATABASE_HOST" => "/tmp/mysql.sock"
}
expect(env(input)).to eql(output)
end
it "parses # in quoted values" do
expect(env('foo="ba#r"')).to eql("foo" => "ba#r")
expect(env("foo='ba#r'")).to eql("foo" => "ba#r")
end
it "parses # in quoted values with following spaces" do
expect(env('foo="ba#r" ')).to eql("foo" => "ba#r")
expect(env("foo='ba#r' ")).to eql("foo" => "ba#r")
end
it "parses empty values" do
expect(env("foo=")).to eql("foo" => "")
end
it "allows multi-line values in single quotes" do
env_file = %(OPTION_A=first line
export OPTION_B='line 1
line 2
line 3'
OPTION_C="last line"
OPTION_ESCAPED='line one
this is \\'quoted\\'
one more line')
expected_result = {
"OPTION_A" => "first line",
"OPTION_B" => "line 1\nline 2\nline 3",
"OPTION_C" => "last line",
"OPTION_ESCAPED" => "line one\nthis is \\'quoted\\'\none more line"
}
expect(env(env_file)).to eql(expected_result)
end
it "allows multi-line values in double quotes" do
env_file = %(OPTION_A=first line
export OPTION_B="line 1
line 2
line 3"
OPTION_C="last line"
OPTION_ESCAPED="line one
this is \\"quoted\\"
one more line")
expected_result = {
"OPTION_A" => "first line",
"OPTION_B" => "line 1\nline 2\nline 3",
"OPTION_C" => "last line",
"OPTION_ESCAPED" => "line one\nthis is \"quoted\"\none more line"
}
expect(env(env_file)).to eql(expected_result)
end
if RUBY_VERSION > "1.8.7"
it "parses shell commands interpolated in $()" do
expect(env("echo=$(echo hello)")).to eql("echo" => "hello")
end
it "allows balanced parentheses within interpolated shell commands" do
expect(env('echo=$(echo "$(echo "$(echo "$(echo hello)")")")'))
.to eql("echo" => "hello")
end
it "doesn't interpolate shell commands when escape says not to" do
expect(env('echo=escaped-\$(echo hello)'))
.to eql("echo" => "escaped-$(echo hello)")
end
it "is not thrown off by quotes in interpolated shell commands" do
expect(env('interp=$(echo "Quotes won\'t be a problem")')["interp"])
.to eql("Quotes won't be a problem")
end
it "handles parentheses in variables in commands" do
expect(env("FOO='passwo(rd'\nBAR=$(echo '$FOO')")).to eql("FOO" => "passwo(rd", "BAR" => "passwo(rd")
end
it "handles command to variable to command chain" do
expect(env("FOO=$(echo bar)\nBAR=$(echo $FOO)")).to eql("FOO" => "bar", "BAR" => "bar")
end
it "supports carriage return" do
expect(env("FOO=bar\rbaz=fbb")).to eql("FOO" => "bar", "baz" => "fbb")
end
it "supports carriage return combine with new line" do
expect(env("FOO=bar\r\nbaz=fbb")).to eql("FOO" => "bar", "baz" => "fbb")
end
it "escapes carriage return in quoted strings" do
expect(env('FOO="bar\rbaz"')).to eql("FOO" => "bar\\rbaz")
end
it "escape $ properly when no alphabets/numbers/_ are followed by it" do
expect(env("FOO=\"bar\\$ \\$\\$\"")).to eql("FOO" => "bar$ $$")
end
# echo bar $ -> prints bar $ in the shell
it "ignore $ when it is not escaped and no variable is followed by it" do
expect(env("FOO=\"bar $ \"")).to eql("FOO" => "bar $ ")
end
# This functionality is not supported on JRuby or Rubinius
if (!defined?(RUBY_ENGINE) || RUBY_ENGINE != "jruby") &&
!defined?(Rubinius)
it "substitutes shell variables within interpolated shell commands" do
expect(env(%(VAR1=var1\ninterp=$(echo "VAR1 is $VAR1")))["interp"])
.to eql("VAR1 is var1")
end
end
end
it "returns existing value for redefined variable" do
ENV["FOO"] = "existing"
expect(env("FOO=bar")).to eql("FOO" => "existing")
end
end
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/spec/dotenv/environment_spec.rb | spec/dotenv/environment_spec.rb | require "spec_helper"
describe Dotenv::Environment do
subject { env("OPTION_A=1\nOPTION_B=2") }
describe "initialize" do
it "reads the file" do
expect(subject["OPTION_A"]).to eq("1")
expect(subject["OPTION_B"]).to eq("2")
end
it "fails if file does not exist" do
expect do
Dotenv::Environment.new(".does_not_exists")
end.to raise_error(Errno::ENOENT)
end
end
require "tempfile"
def env(text, ...)
file = Tempfile.new("dotenv")
file.write text
file.close
env = Dotenv::Environment.new(file.path, ...)
file.unlink
env
end
end
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/lib/dotenv.rb | lib/dotenv.rb | require "dotenv/version"
require "dotenv/parser"
require "dotenv/environment"
require "dotenv/missing_keys"
require "dotenv/diff"
# Shim to load environment variables from `.env files into `ENV`.
module Dotenv
extend self
# An internal monitor to synchronize access to ENV in multi-threaded environments.
SEMAPHORE = Monitor.new
private_constant :SEMAPHORE
attr_accessor :instrumenter
# Loads environment variables from one or more `.env` files. See `#parse` for more details.
def load(*filenames, overwrite: false, ignore: true)
parse(*filenames, overwrite: overwrite, ignore: ignore) do |env|
instrument(:load, env: env) do |payload|
update(env, overwrite: overwrite)
end
end
end
# Same as `#load`, but raises Errno::ENOENT if any files don't exist
def load!(*filenames)
load(*filenames, ignore: false)
end
# same as `#load`, but will overwrite existing values in `ENV`
def overwrite(*filenames)
load(*filenames, overwrite: true)
end
alias_method :overload, :overwrite
# same as `#overwrite`, but raises Errno::ENOENT if any files don't exist
def overwrite!(*filenames)
load(*filenames, overwrite: true, ignore: false)
end
alias_method :overload!, :overwrite!
# Parses the given files, yielding for each file if a block is given.
#
# @param filenames [String, Array<String>] Files to parse
# @param overwrite [Boolean] Overwrite existing `ENV` values
# @param ignore [Boolean] Ignore non-existent files
# @param block [Proc] Block to yield for each parsed `Dotenv::Environment`
# @return [Hash] parsed key/value pairs
def parse(*filenames, overwrite: false, ignore: true, &block)
filenames << ".env" if filenames.empty?
filenames = filenames.reverse if overwrite
filenames.reduce({}) do |hash, filename|
begin
env = Environment.new(File.expand_path(filename), overwrite: overwrite)
env = block.call(env) if block
rescue Errno::ENOENT, Errno::EISDIR
raise unless ignore
end
hash.merge! env || {}
end
end
# Save the current `ENV` to be restored later
def save
instrument(:save) do |payload|
@diff = payload[:diff] = Dotenv::Diff.new
end
end
# Restore `ENV` to a given state
#
# @param env [Hash] Hash of keys and values to restore, defaults to the last saved state
# @param safe [Boolean] Is it safe to modify `ENV`? Defaults to `true` in the main thread, otherwise raises an error.
def restore(env = @diff&.a, safe: Thread.current == Thread.main)
# No previously saved or provided state to restore
return unless env
diff = Dotenv::Diff.new(b: env)
return unless diff.any?
unless safe
raise ThreadError, <<~EOE.tr("\n", " ")
Dotenv.restore is not thread safe. Use `Dotenv.modify { }` to update ENV for the duration
of the block in a thread safe manner, or call `Dotenv.restore(safe: true)` to ignore
this error.
EOE
end
instrument(:restore, diff: diff) { ENV.replace(env) }
end
# Update `ENV` with the given hash of keys and values
#
# @param env [Hash] Hash of keys and values to set in `ENV`
# @param overwrite [Boolean|:warn] Overwrite existing `ENV` values
def update(env = {}, overwrite: false)
instrument(:update) do |payload|
diff = payload[:diff] = Dotenv::Diff.new do
ENV.update(env.transform_keys(&:to_s)) do |key, old_value, new_value|
# This block is called when a key exists. Return the new value if overwrite is true.
case overwrite
when :warn
# not printing the value since that could be a secret
warn "Warning: dotenv not overwriting ENV[#{key.inspect}]"
old_value
when true then new_value
when false then old_value
else raise ArgumentError, "Invalid value for overwrite: #{overwrite.inspect}"
end
end
end
diff.env
end
end
# Modify `ENV` for the block and restore it to its previous state afterwards.
#
# Note that the block is synchronized to prevent concurrent modifications to `ENV`,
# so multiple threads will be executed serially.
#
# @param env [Hash] Hash of keys and values to set in `ENV`
def modify(env = {}, &block)
SEMAPHORE.synchronize do
diff = Dotenv::Diff.new
update(env, overwrite: true)
block.call
ensure
restore(diff.a, safe: true)
end
end
def require_keys(*keys)
missing_keys = keys.flatten - ::ENV.keys
return if missing_keys.empty?
raise MissingKeys, missing_keys
end
private
def instrument(name, payload = {}, &block)
if instrumenter
instrumenter.instrument("#{name}.dotenv", payload, &block)
else
block&.call payload
end
end
end
require "dotenv/rails" if defined?(Rails::Railtie)
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/lib/dotenv-rails.rb | lib/dotenv-rails.rb | require "dotenv"
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/lib/dotenv/version.rb | lib/dotenv/version.rb | module Dotenv
VERSION = "3.2.0".freeze
end
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/lib/dotenv/rails.rb | lib/dotenv/rails.rb | # Since rubygems doesn't support optional dependencies, we have to manually check
unless Gem::Requirement.new(">= 6.1").satisfied_by?(Gem::Version.new(Rails.version))
warn "dotenv 3.0 only supports Rails 6.1 or later. Use dotenv ~> 2.0."
return
end
require "dotenv/replay_logger"
require "dotenv/log_subscriber"
Dotenv.instrumenter = ActiveSupport::Notifications
# Watch all loaded env files with Spring
ActiveSupport::Notifications.subscribe("load.dotenv") do |*args|
if defined?(Spring) && Spring.respond_to?(:watch)
event = ActiveSupport::Notifications::Event.new(*args)
Spring.watch event.payload[:env].filename if Rails.application
end
end
module Dotenv
# Rails integration for using Dotenv to load ENV variables from a file
class Rails < ::Rails::Railtie
delegate :files, :files=, :overwrite, :overwrite=, :autorestore, :autorestore=, :logger, to: "config.dotenv"
def initialize
super
config.dotenv = ActiveSupport::OrderedOptions.new.update(
# Rails.logger is not available yet, so we'll save log messages and replay them when it is
logger: Dotenv::ReplayLogger.new,
overwrite: false,
files: [
".env.#{env}.local",
(".env.local" unless env.test?),
".env.#{env}",
".env"
].compact,
autorestore: env.test? && !defined?(ClimateControl) && !defined?(IceAge)
)
end
# Public: Load dotenv
#
# This will get called during the `before_configuration` callback, but you
# can manually call `Dotenv::Rails.load` if you needed it sooner.
def load
Dotenv.load(*files.map { |file| root.join(file).to_s }, overwrite: overwrite)
end
def overload
deprecator.warn("Dotenv::Rails.overload is deprecated. Set `Dotenv::Rails.overwrite = true` and call Dotenv::Rails.load instead.")
Dotenv.load(*files.map { |file| root.join(file).to_s }, overwrite: true)
end
# Internal: `Rails.root` is nil in Rails 4.1 before the application is
# initialized, so this falls back to the `RAILS_ROOT` environment variable,
# or the current working directory.
def root
::Rails.root || Pathname.new(ENV["RAILS_ROOT"] || Dir.pwd)
end
# Set a new logger and replay logs
def logger=(new_logger)
logger.replay new_logger if logger.is_a?(ReplayLogger)
config.dotenv.logger = new_logger
end
# The current environment that the app is running in.
#
# When running `rake`, the Rails application is initialized in development, so we have to
# check which rake tasks are being run to determine the environment.
#
# See https://github.com/bkeepers/dotenv/issues/219
def env
@env ||= if defined?(Rake.application) && Rake.application.top_level_tasks.grep(TEST_RAKE_TASKS).any?
env = Rake.application.options.show_tasks ? "development" : "test"
ActiveSupport::EnvironmentInquirer.new(env)
else
::Rails.env
end
end
TEST_RAKE_TASKS = /^(default$|test(:|$)|parallel:spec|spec(:|$))/
def deprecator # :nodoc:
@deprecator ||= ActiveSupport::Deprecation.new
end
# Rails uses `#method_missing` to delegate all class methods to the
# instance, which means `Kernel#load` gets called here. We don't want that.
def self.load
instance.load
end
initializer "dotenv", after: :initialize_logger do |app|
if logger.is_a?(ReplayLogger)
self.logger = ActiveSupport::TaggedLogging.new(::Rails.logger).tagged("dotenv")
end
end
initializer "dotenv.deprecator" do |app|
app.deprecators[:dotenv] = deprecator if app.respond_to?(:deprecators)
end
initializer "dotenv.autorestore" do |app|
require "dotenv/autorestore" if autorestore
end
config.before_configuration { load }
end
Railtie = ActiveSupport::Deprecation::DeprecatedConstantProxy.new("Dotenv::Railtie", "Dotenv::Rails", Dotenv::Rails.deprecator)
end
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/lib/dotenv/rails-now.rb | lib/dotenv/rails-now.rb | # If you use gems that require environment variables to be set before they are
# loaded, then list `dotenv` in the `Gemfile` before those other gems and
# require `dotenv/load`.
#
# gem "dotenv", require: "dotenv/load"
# gem "gem-that-requires-env-variables"
#
require "dotenv/load"
warn '[DEPRECATION] `require "dotenv/rails-now"` is deprecated. Use `require "dotenv/load"` instead.', caller(1..1).first
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/lib/dotenv/diff.rb | lib/dotenv/diff.rb | module Dotenv
# A diff between multiple states of ENV.
class Diff
# The initial state
attr_reader :a
# The final or current state
attr_reader :b
# Create a new diff. If given a block, the state of ENV after the block will be preserved as
# the final state for comparison. Otherwise, the current ENV will be the final state.
#
# @param a [Hash] the initial state, defaults to a snapshot of current ENV
# @param b [Hash] the final state, defaults to the current ENV
# @yield [diff] a block to execute before recording the final state
def initialize(a: snapshot, b: ENV, &block)
@a, @b = a, b
block&.call self
ensure
@b = snapshot if block
end
# Return a Hash of keys added with their new values
def added
b.slice(*(b.keys - a.keys))
end
# Returns a Hash of keys removed with their previous values
def removed
a.slice(*(a.keys - b.keys))
end
# Returns of Hash of keys changed with an array of their previous and new values
def changed
(b.slice(*a.keys).to_a - a.to_a).map do |(k, v)|
[k, [a[k], v]]
end.to_h
end
# Returns a Hash of all added, changed, and removed keys and their new values
def env
b.slice(*(added.keys + changed.keys)).merge(removed.transform_values { |v| nil })
end
# Returns true if any keys were added, removed, or changed
def any?
[added, removed, changed].any?(&:any?)
end
private
def snapshot
# `dup` should not be required here, but some people use `stub_const` to replace ENV with
# a `Hash`. This ensures that we get a frozen copy of that instead of freezing the original.
# https://github.com/bkeepers/dotenv/issues/482
ENV.to_h.dup.freeze
end
end
end
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/lib/dotenv/environment.rb | lib/dotenv/environment.rb | module Dotenv
# A `.env` file that will be read and parsed into a Hash
class Environment < Hash
attr_reader :filename, :overwrite
# Create a new Environment
#
# @param filename [String] the path to the file to read
# @param overwrite [Boolean] whether the parser should assume existing values will be overwritten
def initialize(filename, overwrite: false)
super()
@filename = filename
@overwrite = overwrite
load
end
def load
update Parser.call(read, overwrite: overwrite)
end
def read
File.open(@filename, "rb:bom|utf-8", &:read)
end
end
end
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/lib/dotenv/log_subscriber.rb | lib/dotenv/log_subscriber.rb | require "active_support/log_subscriber"
module Dotenv
# Logs instrumented events
#
# Usage:
# require "active_support/notifications"
# require "dotenv/log_subscriber"
# Dotenv.instrumenter = ActiveSupport::Notifications
#
class LogSubscriber < ActiveSupport::LogSubscriber
attach_to :dotenv
def logger
Dotenv::Rails.logger
end
def load(event)
env = event.payload[:env]
info "Loaded #{color_filename(env.filename)}"
end
def update(event)
diff = event.payload[:diff]
changed = diff.env.keys.map { |key| color_var(key) }
debug "Set #{changed.join(", ")}" if diff.any?
end
def save(event)
info "Saved a snapshot of #{color_env_constant}"
end
def restore(event)
diff = event.payload[:diff]
removed = diff.removed.keys.map { |key| color(key, :RED) }
restored = (diff.changed.keys + diff.added.keys).map { |key| color_var(key) }
if removed.any? || restored.any?
info "Restored snapshot of #{color_env_constant}"
debug "Unset #{removed.join(", ")}" if removed.any?
debug "Restored #{restored.join(", ")}" if restored.any?
end
end
private
def color_filename(filename)
color(Pathname.new(filename).relative_path_from(Dotenv::Rails.root.to_s).to_s, :YELLOW)
end
def color_var(name)
color(name, :CYAN)
end
def color_env_constant
color("ENV", :GREEN)
end
end
end
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/lib/dotenv/load.rb | lib/dotenv/load.rb | require "dotenv"
defined?(Dotenv::Rails) ? Dotenv::Rails.load : Dotenv.load
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/lib/dotenv/parser.rb | lib/dotenv/parser.rb | require "dotenv/substitutions/variable"
require "dotenv/substitutions/command" if RUBY_VERSION > "1.8.7"
module Dotenv
# Error raised when encountering a syntax error while parsing a .env file.
class FormatError < SyntaxError; end
# Parses the `.env` file format into key/value pairs.
# It allows for variable substitutions, command substitutions, and exporting of variables.
class Parser
@substitutions = [
Dotenv::Substitutions::Command,
Dotenv::Substitutions::Variable
]
LINE = /
(?:^|\A) # beginning of line
\s* # leading whitespace
(?<export>export\s+)? # optional export
(?<key>[\w.]+) # key
(?: # optional separator and value
(?:\s*=\s*?|:\s+?) # separator
(?<value> # optional value begin
\s*'(?:\\'|[^'])*' # single quoted value
| # or
\s*"(?:\\"|[^"])*" # double quoted value
| # or
[^\#\n]+ # unquoted value
)? # value end
)? # separator and value end
\s* # trailing whitespace
(?:\#.*)? # optional comment
(?:$|\z) # end of line
/x
QUOTED_STRING = /\A(['"])(.*)\1\z/m
class << self
attr_reader :substitutions
def call(...)
new(...).call
end
end
def initialize(string, overwrite: false)
# Convert line breaks to same format
@string = string.gsub(/\r\n?/, "\n")
@hash = {}
@overwrite = overwrite
end
def call
@string.scan(LINE) do
match = $LAST_MATCH_INFO
if existing?(match[:key])
# Use value from already defined variable
@hash[match[:key]] = ENV[match[:key]]
elsif match[:export] && !match[:value]
# Check for exported variable with no value
if !@hash.member?(match[:key])
raise FormatError, "Line #{match.to_s.inspect} has an unset variable"
end
else
@hash[match[:key]] = parse_value(match[:value] || "")
end
end
@hash
end
private
# Determine if a variable is already defined and should not be overwritten.
def existing?(key)
!@overwrite && key != "DOTENV_LINEBREAK_MODE" && ENV.key?(key)
end
def parse_value(value)
# Remove surrounding quotes
value = value.strip.sub(QUOTED_STRING, '\2')
maybe_quote = Regexp.last_match(1)
# Expand new lines in double quoted values
value = expand_newlines(value) if maybe_quote == '"'
# Unescape characters and performs substitutions unless value is single quoted
if maybe_quote != "'"
value = unescape_characters(value)
self.class.substitutions.each { |proc| value = proc.call(value, @hash) }
end
value
end
def unescape_characters(value)
value.gsub(/\\([^$])/, '\1')
end
def expand_newlines(value)
if (@hash["DOTENV_LINEBREAK_MODE"] || ENV["DOTENV_LINEBREAK_MODE"]) == "legacy"
value.gsub('\n', "\n").gsub('\r', "\r")
else
value.gsub('\n', "\\\\\\n").gsub('\r', "\\\\\\r")
end
end
end
end
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/lib/dotenv/missing_keys.rb | lib/dotenv/missing_keys.rb | module Dotenv
class Error < StandardError; end
class MissingKeys < Error # :nodoc:
def initialize(keys)
key_word = "key#{"s" if keys.size > 1}"
super("Missing required configuration #{key_word}: #{keys.inspect}")
end
end
end
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/lib/dotenv/template.rb | lib/dotenv/template.rb | module Dotenv
EXPORT_COMMAND = "export ".freeze
# Class for creating a template from a env file
class EnvTemplate
def initialize(env_file)
@env_file = env_file
end
def create_template
File.open(@env_file, "r") do |env_file|
File.open("#{@env_file}.template", "w") do |env_template|
env_file.each do |line|
if is_comment?(line)
env_template.puts line
elsif (var = var_defined?(line))
if line.match(EXPORT_COMMAND)
env_template.puts "export #{var}=#{var}"
else
env_template.puts "#{var}=#{var}"
end
elsif line_blank?(line)
env_template.puts
end
end
end
end
end
private
def is_comment?(line)
line.strip.start_with?("#")
end
def var_defined?(line)
match = Dotenv::Parser::LINE.match(line)
match && match[:key]
end
def line_blank?(line)
line.strip.length.zero?
end
end
end
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/lib/dotenv/cli.rb | lib/dotenv/cli.rb | require "dotenv"
require "dotenv/version"
require "dotenv/template"
require "optparse"
module Dotenv
# The `dotenv` command line interface. Run `$ dotenv --help` to see usage.
class CLI < OptionParser
attr_reader :argv, :filenames, :overwrite
def initialize(argv = [])
@argv = argv.dup
@filenames = []
@ignore = false
@overwrite = false
super("Usage: dotenv [options]")
separator ""
on("-f FILES", Array, "List of env files to parse") do |list|
@filenames = list
end
on("-i", "--ignore", "ignore missing env files") do
@ignore = true
end
on("-o", "--overwrite", "overwrite existing ENV variables") do
@overwrite = true
end
on("--overload") { @overwrite = true }
on("-h", "--help", "Display help") do
puts self
exit
end
on("-v", "--version", "Show version") do
puts "dotenv #{Dotenv::VERSION}"
exit
end
on("-t", "--template=FILE", "Create a template env file") do |file|
template = Dotenv::EnvTemplate.new(file)
template.create_template
end
order!(@argv)
end
def run
Dotenv.load(*@filenames, overwrite: @overwrite, ignore: @ignore)
rescue Errno::ENOENT => e
abort e.message
else
exec(*@argv) unless @argv.empty?
end
end
end
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/lib/dotenv/autorestore.rb | lib/dotenv/autorestore.rb | # Automatically restore `ENV` to its original state after
if defined?(RSpec.configure)
RSpec.configure do |config|
# Save ENV before the suite starts
config.before(:suite) { Dotenv.save }
# Restore ENV after each example
config.after { Dotenv.restore }
end
end
if defined?(ActiveSupport)
ActiveSupport.on_load(:active_support_test_case) do
ActiveSupport::TestCase.class_eval do
# Save ENV before each test
setup { Dotenv.save }
# Restore ENV after each test
teardown do
Dotenv.restore
rescue ThreadError => e
# Restore will fail if running tests in parallel.
warn e.message
warn "Set `config.dotenv.autorestore = false` in `config/initializers/test.rb`" if defined?(Dotenv::Rails)
end
end
end
end
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/lib/dotenv/tasks.rb | lib/dotenv/tasks.rb | desc "Load environment settings from .env"
task :dotenv do
require "dotenv"
Dotenv.load
end
task environment: :dotenv
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/lib/dotenv/replay_logger.rb | lib/dotenv/replay_logger.rb | module Dotenv
# A logger that can be used before the apps real logger is initialized.
class ReplayLogger < Logger
def initialize
super(nil) # Doesn't matter what this is, it won't be used.
@logs = []
end
# Override the add method to store logs so we can replay them to a real logger later.
def add(*args, &block)
@logs.push([args, block])
end
# Replay the store logs to a real logger.
def replay(logger)
@logs.each { |args, block| logger.add(*args, &block) }
@logs.clear
end
end
end
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/lib/dotenv/substitutions/command.rb | lib/dotenv/substitutions/command.rb | require "English"
module Dotenv
module Substitutions
# Substitute shell commands in a value.
#
# SHA=$(git rev-parse HEAD)
#
module Command
class << self
INTERPOLATED_SHELL_COMMAND = /
(?<backslash>\\)? # is it escaped with a backslash?
\$ # literal $
(?<cmd> # collect command content for eval
\( # require opening paren
(?:[^()]|\g<cmd>)+ # allow any number of non-parens, or balanced
# parens (by nesting the <cmd> expression
# recursively)
\) # require closing paren
)
/x
def call(value, env)
# Process interpolated shell commands
value.gsub(INTERPOLATED_SHELL_COMMAND) do |*|
# Eliminate opening and closing parentheses
command = $LAST_MATCH_INFO[:cmd][1..-2]
if $LAST_MATCH_INFO[:backslash]
# Command is escaped, don't replace it.
$LAST_MATCH_INFO[0][1..]
else
# Execute the command and return the value
`#{Variable.call(command, env)}`.chomp
end
end
end
end
end
end
end
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
bkeepers/dotenv | https://github.com/bkeepers/dotenv/blob/34156bf400cd67387fa6ed9f146778f6a2f5f743/lib/dotenv/substitutions/variable.rb | lib/dotenv/substitutions/variable.rb | require "English"
module Dotenv
module Substitutions
# Substitute variables in a value.
#
# HOST=example.com
# URL="https://$HOST"
#
module Variable
class << self
VARIABLE = /
(\\)? # is it escaped with a backslash?
(\$) # literal $
(?!\() # shouldn't be followed by parenthesis
\{? # allow brace wrapping
([A-Z0-9_]+)? # optional alpha nums
\}? # closing brace
/xi
def call(value, env)
value.gsub(VARIABLE) do |variable|
match = $LAST_MATCH_INFO
if match[1] == "\\"
variable[1..]
elsif match[3]
env[match[3]] || ENV[match[3]] || ""
else
variable
end
end
end
end
end
end
end
| ruby | MIT | 34156bf400cd67387fa6ed9f146778f6a2f5f743 | 2026-01-04T15:40:05.785256Z | false |
github-linguist/linguist | https://github.com/github-linguist/linguist/blob/a7e40d31e271f6747fa1234df37b5fff3e6e2406/samples/Ruby/sinatra.rb | samples/Ruby/sinatra.rb | # external dependencies
require 'rack'
require 'tilt'
require "rack/protection"
# stdlib dependencies
require 'thread'
require 'time'
require 'uri'
# other files we need
require 'sinatra/showexceptions'
require 'sinatra/version'
module Sinatra
# The request object. See Rack::Request for more info:
# http://rack.rubyforge.org/doc/classes/Rack/Request.html
class Request < Rack::Request
# Returns an array of acceptable media types for the response
def accept
@env['sinatra.accept'] ||= begin
entries = @env['HTTP_ACCEPT'].to_s.split(',')
entries.map { |e| accept_entry(e) }.sort_by(&:last).map(&:first)
end
end
def preferred_type(*types)
return accept.first if types.empty?
types.flatten!
accept.detect do |pattern|
type = types.detect { |t| File.fnmatch(pattern, t) }
return type if type
end
end
alias accept? preferred_type
alias secure? ssl?
def forwarded?
@env.include? "HTTP_X_FORWARDED_HOST"
end
def safe?
get? or head? or options? or trace?
end
def idempotent?
safe? or put? or delete?
end
private
def accept_entry(entry)
type, *options = entry.delete(' ').split(';')
quality = 0 # we sort smallest first
options.delete_if { |e| quality = 1 - e[2..-1].to_f if e.start_with? 'q=' }
[type, [quality, type.count('*'), 1 - options.size]]
end
end
# The response object. See Rack::Response and Rack::ResponseHelpers for
# more info:
# http://rack.rubyforge.org/doc/classes/Rack/Response.html
# http://rack.rubyforge.org/doc/classes/Rack/Response/Helpers.html
class Response < Rack::Response
def body=(value)
value = value.body while Rack::Response === value
@body = String === value ? [value.to_str] : value
end
def each
block_given? ? super : enum_for(:each)
end
def finish
if status.to_i / 100 == 1
headers.delete "Content-Length"
headers.delete "Content-Type"
elsif Array === body and not [204, 304].include?(status.to_i)
# if some other code has already set Content-Length, don't muck with it
# currently, this would be the static file-handler
headers["Content-Length"] ||= body.inject(0) { |l, p| l + Rack::Utils.bytesize(p) }.to_s
end
# Rack::Response#finish sometimes returns self as response body. We don't want that.
status, headers, result = super
result = body if result == self
[status, headers, result]
end
end
# Some Rack handlers (Thin, Rainbows!) implement an extended body object protocol, however,
# some middleware (namely Rack::Lint) will break it by not mirroring the methods in question.
# This middleware will detect an extended body object and will make sure it reaches the
# handler directly. We do this here, so our middleware and middleware set up by the app will
# still be able to run.
class ExtendedRack < Struct.new(:app)
def call(env)
result, callback = app.call(env), env['async.callback']
return result unless callback and async?(*result)
after_response { callback.call result }
setup_close(env, *result)
throw :async
end
private
def setup_close(env, status, header, body)
return unless body.respond_to? :close and env.include? 'async.close'
env['async.close'].callback { body.close }
env['async.close'].errback { body.close }
end
def after_response(&block)
raise NotImplementedError, "only supports EventMachine at the moment" unless defined? EventMachine
EventMachine.next_tick(&block)
end
def async?(status, headers, body)
return true if status == -1
body.respond_to? :callback and body.respond_to? :errback
end
end
# Behaves exactly like Rack::CommonLogger with the notable exception that it does nothing,
# if another CommonLogger is already in the middleware chane.
class CommonLogger < Rack::CommonLogger
def call(env)
env['sinatra.commonlogger'] ? @app.call(env) : super
end
superclass.class_eval do
alias call_without_check call unless method_defined? :call_without_check
def call(env)
env['sinatra.commonlogger'] = true
call_without_check(env)
end
end
end
class NotFound < NameError #:nodoc:
def http_status; 404 end
end
# Methods available to routes, before/after filters, and views.
module Helpers
# Set or retrieve the response status code.
def status(value=nil)
response.status = value if value
response.status
end
# Set or retrieve the response body. When a block is given,
# evaluation is deferred until the body is read with #each.
def body(value=nil, &block)
if block_given?
def block.each; yield(call) end
response.body = block
elsif value
response.body = value
else
response.body
end
end
# Halt processing and redirect to the URI provided.
def redirect(uri, *args)
if env['HTTP_VERSION'] == 'HTTP/1.1' and env["REQUEST_METHOD"] != 'GET'
status 303
else
status 302
end
# According to RFC 2616 section 14.30, "the field value consists of a
# single absolute URI"
response['Location'] = uri(uri, settings.absolute_redirects?, settings.prefixed_redirects?)
halt(*args)
end
# Generates the absolute URI for a given path in the app.
# Takes Rack routers and reverse proxies into account.
def uri(addr = nil, absolute = true, add_script_name = true)
return addr if addr =~ /\A[A-z][A-z0-9\+\.\-]*:/
uri = [host = ""]
if absolute
host << "http#{'s' if request.secure?}://"
if request.forwarded? or request.port != (request.secure? ? 443 : 80)
host << request.host_with_port
else
host << request.host
end
end
uri << request.script_name.to_s if add_script_name
uri << (addr ? addr : request.path_info).to_s
File.join uri
end
alias url uri
alias to uri
# Halt processing and return the error status provided.
def error(code, body=nil)
code, body = 500, code.to_str if code.respond_to? :to_str
response.body = body unless body.nil?
halt code
end
# Halt processing and return a 404 Not Found.
def not_found(body=nil)
error 404, body
end
# Set multiple response headers with Hash.
def headers(hash=nil)
response.headers.merge! hash if hash
response.headers
end
# Access the underlying Rack session.
def session
request.session
end
# Access shared logger object.
def logger
request.logger
end
# Look up a media type by file extension in Rack's mime registry.
def mime_type(type)
Base.mime_type(type)
end
# Set the Content-Type of the response body given a media type or file
# extension.
def content_type(type = nil, params={})
return response['Content-Type'] unless type
default = params.delete :default
mime_type = mime_type(type) || default
fail "Unknown media type: %p" % type if mime_type.nil?
mime_type = mime_type.dup
unless params.include? :charset or settings.add_charset.all? { |p| not p === mime_type }
params[:charset] = params.delete('charset') || settings.default_encoding
end
params.delete :charset if mime_type.include? 'charset'
unless params.empty?
mime_type << (mime_type.include?(';') ? ', ' : ';')
mime_type << params.map { |kv| kv.join('=') }.join(', ')
end
response['Content-Type'] = mime_type
end
# Set the Content-Disposition to "attachment" with the specified filename,
# instructing the user agents to prompt to save.
def attachment(filename=nil)
response['Content-Disposition'] = 'attachment'
if filename
params = '; filename="%s"' % File.basename(filename)
response['Content-Disposition'] << params
ext = File.extname(filename)
content_type(ext) unless response['Content-Type'] or ext.empty?
end
end
# Use the contents of the file at +path+ as the response body.
def send_file(path, opts={})
if opts[:type] or not response['Content-Type']
content_type opts[:type] || File.extname(path), :default => 'application/octet-stream'
end
if opts[:disposition] == 'attachment' || opts[:filename]
attachment opts[:filename] || path
elsif opts[:disposition] == 'inline'
response['Content-Disposition'] = 'inline'
end
last_modified opts[:last_modified] if opts[:last_modified]
file = Rack::File.new nil
file.path = path
result = file.serving env
result[1].each { |k,v| headers[k] ||= v }
headers['Content-Length'] = result[1]['Content-Length']
halt opts[:status] || result[0], result[2]
rescue Errno::ENOENT
not_found
end
# Class of the response body in case you use #stream.
#
# Three things really matter: The front and back block (back being the
# blog generating content, front the one sending it to the client) and
# the scheduler, integrating with whatever concurrency feature the Rack
# handler is using.
#
# Scheduler has to respond to defer and schedule.
class Stream
def self.schedule(*) yield end
def self.defer(*) yield end
def initialize(scheduler = self.class, keep_open = false, &back)
@back, @scheduler, @keep_open = back.to_proc, scheduler, keep_open
@callbacks, @closed = [], false
end
def close
return if @closed
@closed = true
@scheduler.schedule { @callbacks.each { |c| c.call }}
end
def each(&front)
@front = front
@scheduler.defer do
begin
@back.call(self)
rescue Exception => e
@scheduler.schedule { raise e }
end
close unless @keep_open
end
end
def <<(data)
@scheduler.schedule { @front.call(data.to_s) }
self
end
def callback(&block)
return yield if @closed
@callbacks << block
end
alias errback callback
end
# Allows to start sending data to the client even though later parts of
# the response body have not yet been generated.
#
# The close parameter specifies whether Stream#close should be called
# after the block has been executed. This is only relevant for evented
# servers like Thin or Rainbows.
def stream(keep_open = false)
scheduler = env['async.callback'] ? EventMachine : Stream
current = @params.dup
body Stream.new(scheduler, keep_open) { |out| with_params(current) { yield(out) } }
end
# Specify response freshness policy for HTTP caches (Cache-Control header).
# Any number of non-value directives (:public, :private, :no_cache,
# :no_store, :must_revalidate, :proxy_revalidate) may be passed along with
# a Hash of value directives (:max_age, :min_stale, :s_max_age).
#
# cache_control :public, :must_revalidate, :max_age => 60
# => Cache-Control: public, must-revalidate, max-age=60
#
# See RFC 2616 / 14.9 for more on standard cache control directives:
# http://tools.ietf.org/html/rfc2616#section-14.9.1
def cache_control(*values)
if values.last.kind_of?(Hash)
hash = values.pop
hash.reject! { |k,v| v == false }
hash.reject! { |k,v| values << k if v == true }
else
hash = {}
end
values.map! { |value| value.to_s.tr('_','-') }
hash.each do |key, value|
key = key.to_s.tr('_', '-')
value = value.to_i if key == "max-age"
values << [key, value].join('=')
end
response['Cache-Control'] = values.join(', ') if values.any?
end
# Set the Expires header and Cache-Control/max-age directive. Amount
# can be an integer number of seconds in the future or a Time object
# indicating when the response should be considered "stale". The remaining
# "values" arguments are passed to the #cache_control helper:
#
# expires 500, :public, :must_revalidate
# => Cache-Control: public, must-revalidate, max-age=60
# => Expires: Mon, 08 Jun 2009 08:50:17 GMT
#
def expires(amount, *values)
values << {} unless values.last.kind_of?(Hash)
if amount.is_a? Integer
time = Time.now + amount.to_i
max_age = amount
else
time = time_for amount
max_age = time - Time.now
end
values.last.merge!(:max_age => max_age)
cache_control(*values)
response['Expires'] = time.httpdate
end
# Set the last modified time of the resource (HTTP 'Last-Modified' header)
# and halt if conditional GET matches. The +time+ argument is a Time,
# DateTime, or other object that responds to +to_time+.
#
# When the current request includes an 'If-Modified-Since' header that is
# equal or later than the time specified, execution is immediately halted
# with a '304 Not Modified' response.
def last_modified(time)
return unless time
time = time_for time
response['Last-Modified'] = time.httpdate
return if env['HTTP_IF_NONE_MATCH']
if status == 200 and env['HTTP_IF_MODIFIED_SINCE']
# compare based on seconds since epoch
since = Time.httpdate(env['HTTP_IF_MODIFIED_SINCE']).to_i
halt 304 if since >= time.to_i
end
if (success? or status == 412) and env['HTTP_IF_UNMODIFIED_SINCE']
# compare based on seconds since epoch
since = Time.httpdate(env['HTTP_IF_UNMODIFIED_SINCE']).to_i
halt 412 if since < time.to_i
end
rescue ArgumentError
end
# Set the response entity tag (HTTP 'ETag' header) and halt if conditional
# GET matches. The +value+ argument is an identifier that uniquely
# identifies the current version of the resource. The +kind+ argument
# indicates whether the etag should be used as a :strong (default) or :weak
# cache validator.
#
# When the current request includes an 'If-None-Match' header with a
# matching etag, execution is immediately halted. If the request method is
# GET or HEAD, a '304 Not Modified' response is sent.
def etag(value, options = {})
# Before touching this code, please double check RFC 2616 14.24 and 14.26.
options = {:kind => options} unless Hash === options
kind = options[:kind] || :strong
new_resource = options.fetch(:new_resource) { request.post? }
unless [:strong, :weak].include?(kind)
raise ArgumentError, ":strong or :weak expected"
end
value = '"%s"' % value
value = 'W/' + value if kind == :weak
response['ETag'] = value
if success? or status == 304
if etag_matches? env['HTTP_IF_NONE_MATCH'], new_resource
halt(request.safe? ? 304 : 412)
end
if env['HTTP_IF_MATCH']
halt 412 unless etag_matches? env['HTTP_IF_MATCH'], new_resource
end
end
end
# Sugar for redirect (example: redirect back)
def back
request.referer
end
# whether or not the status is set to 1xx
def informational?
status.between? 100, 199
end
# whether or not the status is set to 2xx
def success?
status.between? 200, 299
end
# whether or not the status is set to 3xx
def redirect?
status.between? 300, 399
end
# whether or not the status is set to 4xx
def client_error?
status.between? 400, 499
end
# whether or not the status is set to 5xx
def server_error?
status.between? 500, 599
end
# whether or not the status is set to 404
def not_found?
status == 404
end
# Generates a Time object from the given value.
# Used by #expires and #last_modified.
def time_for(value)
if value.respond_to? :to_time
value.to_time
elsif value.is_a? Time
value
elsif value.respond_to? :new_offset
# DateTime#to_time does the same on 1.9
d = value.new_offset 0
t = Time.utc d.year, d.mon, d.mday, d.hour, d.min, d.sec + d.sec_fraction
t.getlocal
elsif value.respond_to? :mday
# Date#to_time does the same on 1.9
Time.local(value.year, value.mon, value.mday)
elsif value.is_a? Numeric
Time.at value
else
Time.parse value.to_s
end
rescue ArgumentError => boom
raise boom
rescue Exception
raise ArgumentError, "unable to convert #{value.inspect} to a Time object"
end
private
# Helper method checking if a ETag value list includes the current ETag.
def etag_matches?(list, new_resource = request.post?)
return !new_resource if list == '*'
list.to_s.split(/\s*,\s*/).include? response['ETag']
end
def with_params(temp_params)
original, @params = @params, temp_params
yield
ensure
@params = original if original
end
end
private
# Template rendering methods. Each method takes the name of a template
# to render as a Symbol and returns a String with the rendered output,
# as well as an optional hash with additional options.
#
# `template` is either the name or path of the template as symbol
# (Use `:'subdir/myview'` for views in subdirectories), or a string
# that will be rendered.
#
# Possible options are:
# :content_type The content type to use, same arguments as content_type.
# :layout If set to false, no layout is rendered, otherwise
# the specified layout is used (Ignored for `sass` and `less`)
# :layout_engine Engine to use for rendering the layout.
# :locals A hash with local variables that should be available
# in the template
# :scope If set, template is evaluate with the binding of the given
# object rather than the application instance.
# :views Views directory to use.
module Templates
module ContentTyped
attr_accessor :content_type
end
def initialize
super
@default_layout = :layout
end
def erb(template, options={}, locals={})
render :erb, template, options, locals
end
def erubis(template, options={}, locals={})
warn "Sinatra::Templates#erubis is deprecated and will be removed, use #erb instead.\n" \
"If you have Erubis installed, it will be used automatically."
render :erubis, template, options, locals
end
def haml(template, options={}, locals={})
render :haml, template, options, locals
end
def sass(template, options={}, locals={})
options.merge! :layout => false, :default_content_type => :css
render :sass, template, options, locals
end
def scss(template, options={}, locals={})
options.merge! :layout => false, :default_content_type => :css
render :scss, template, options, locals
end
def less(template, options={}, locals={})
options.merge! :layout => false, :default_content_type => :css
render :less, template, options, locals
end
def builder(template=nil, options={}, locals={}, &block)
options[:default_content_type] = :xml
render_ruby(:builder, template, options, locals, &block)
end
def liquid(template, options={}, locals={})
render :liquid, template, options, locals
end
def markdown(template, options={}, locals={})
render :markdown, template, options, locals
end
def textile(template, options={}, locals={})
render :textile, template, options, locals
end
def rdoc(template, options={}, locals={})
render :rdoc, template, options, locals
end
def radius(template, options={}, locals={})
render :radius, template, options, locals
end
def markaby(template=nil, options={}, locals={}, &block)
render_ruby(:mab, template, options, locals, &block)
end
def coffee(template, options={}, locals={})
options.merge! :layout => false, :default_content_type => :js
render :coffee, template, options, locals
end
def nokogiri(template=nil, options={}, locals={}, &block)
options[:default_content_type] = :xml
render_ruby(:nokogiri, template, options, locals, &block)
end
def slim(template, options={}, locals={})
render :slim, template, options, locals
end
def creole(template, options={}, locals={})
render :creole, template, options, locals
end
def yajl(template, options={}, locals={})
options[:default_content_type] = :json
render :yajl, template, options, locals
end
# Calls the given block for every possible template file in views,
# named name.ext, where ext is registered on engine.
def find_template(views, name, engine)
yield ::File.join(views, "#{name}.#{@preferred_extension}")
Tilt.mappings.each do |ext, engines|
next unless ext != @preferred_extension and engines.include? engine
yield ::File.join(views, "#{name}.#{ext}")
end
end
private
# logic shared between builder and nokogiri
def render_ruby(engine, template, options={}, locals={}, &block)
options, template = template, nil if template.is_a?(Hash)
template = Proc.new { block } if template.nil?
render engine, template, options, locals
end
def render(engine, data, options={}, locals={}, &block)
# merge app-level options
options = settings.send(engine).merge(options) if settings.respond_to?(engine)
options[:outvar] ||= '@_out_buf'
options[:default_encoding] ||= settings.default_encoding
# extract generic options
locals = options.delete(:locals) || locals || {}
views = options.delete(:views) || settings.views || "./views"
layout = options.delete(:layout)
eat_errors = layout.nil?
layout = @default_layout if layout.nil? or layout == true
content_type = options.delete(:content_type) || options.delete(:default_content_type)
layout_engine = options.delete(:layout_engine) || engine
scope = options.delete(:scope) || self
# compile and render template
begin
layout_was = @default_layout
@default_layout = false
template = compile_template(engine, data, options, views)
output = template.render(scope, locals, &block)
ensure
@default_layout = layout_was
end
# render layout
if layout
options = options.merge(:views => views, :layout => false, :eat_errors => eat_errors, :scope => scope)
catch(:layout_missing) { return render(layout_engine, layout, options, locals) { output } }
end
output.extend(ContentTyped).content_type = content_type if content_type
output
end
def compile_template(engine, data, options, views)
eat_errors = options.delete :eat_errors
template_cache.fetch engine, data, options do
template = Tilt[engine]
raise "Template engine not found: #{engine}" if template.nil?
case data
when Symbol
body, path, line = settings.templates[data]
if body
body = body.call if body.respond_to?(:call)
template.new(path, line.to_i, options) { body }
else
found = false
@preferred_extension = engine.to_s
find_template(views, data, template) do |file|
path ||= file # keep the initial path rather than the last one
if found = File.exists?(file)
path = file
break
end
end
throw :layout_missing if eat_errors and not found
template.new(path, 1, options)
end
when Proc, String
body = data.is_a?(String) ? Proc.new { data } : data
path, line = settings.caller_locations.first
template.new(path, line.to_i, options, &body)
else
raise ArgumentError, "Sorry, don't know how to render #{data.inspect}."
end
end
end
end
# Base class for all Sinatra applications and middleware.
class Base
include Rack::Utils
include Helpers
include Templates
attr_accessor :app
attr_reader :template_cache
def initialize(app=nil)
super()
@app = app
@template_cache = Tilt::Cache.new
yield self if block_given?
end
# Rack call interface.
def call(env)
dup.call!(env)
end
attr_accessor :env, :request, :response, :params
def call!(env) # :nodoc:
@env = env
@request = Request.new(env)
@response = Response.new
@params = indifferent_params(@request.params)
template_cache.clear if settings.reload_templates
force_encoding(@params)
@response['Content-Type'] = nil
invoke { dispatch! }
invoke { error_block!(response.status) }
unless @response['Content-Type']
if Array === body and body[0].respond_to? :content_type
content_type body[0].content_type
else
content_type :html
end
end
@response.finish
end
# Access settings defined with Base.set.
def self.settings
self
end
# Access settings defined with Base.set.
def settings
self.class.settings
end
def options
warn "Sinatra::Base#options is deprecated and will be removed, " \
"use #settings instead."
settings
end
# Exit the current block, halts any further processing
# of the request, and returns the specified response.
def halt(*response)
response = response.first if response.length == 1
throw :halt, response
end
# Pass control to the next matching route.
# If there are no more matching routes, Sinatra will
# return a 404 response.
def pass(&block)
throw :pass, block
end
# Forward the request to the downstream app -- middleware only.
def forward
fail "downstream app not set" unless @app.respond_to? :call
status, headers, body = @app.call env
@response.status = status
@response.body = body
@response.headers.merge! headers
nil
end
private
# Run filters defined on the class and all superclasses.
def filter!(type, base = settings)
filter! type, base.superclass if base.superclass.respond_to?(:filters)
base.filters[type].each { |args| process_route(*args) }
end
# Run routes defined on the class and all superclasses.
def route!(base = settings, pass_block=nil)
if routes = base.routes[@request.request_method]
routes.each do |pattern, keys, conditions, block|
pass_block = process_route(pattern, keys, conditions) do |*args|
route_eval { block[*args] }
end
end
end
# Run routes defined in superclass.
if base.superclass.respond_to?(:routes)
return route!(base.superclass, pass_block)
end
route_eval(&pass_block) if pass_block
route_missing
end
# Run a route block and throw :halt with the result.
def route_eval
throw :halt, yield
end
# If the current request matches pattern and conditions, fill params
# with keys and call the given block.
# Revert params afterwards.
#
# Returns pass block.
def process_route(pattern, keys, conditions, block = nil, values = [])
route = @request.path_info
route = '/' if route.empty? and not settings.empty_path_info?
return unless match = pattern.match(route)
values += match.captures.to_a.map { |v| force_encoding URI.decode_www_form_component(v) if v }
if values.any?
original, @params = params, params.merge('splat' => [], 'captures' => values)
keys.zip(values) { |k,v| Array === @params[k] ? @params[k] << v : @params[k] = v if v }
end
catch(:pass) do
conditions.each { |c| throw :pass if c.bind(self).call == false }
block ? block[self, values] : yield(self, values)
end
ensure
@params = original if original
end
# No matching route was found or all routes passed. The default
# implementation is to forward the request downstream when running
# as middleware (@app is non-nil); when no downstream app is set, raise
# a NotFound exception. Subclasses can override this method to perform
# custom route miss logic.
def route_missing
if @app
forward
else
raise NotFound
end
end
# Attempt to serve static files from public directory. Throws :halt when
# a matching file is found, returns nil otherwise.
def static!
return if (public_dir = settings.public_folder).nil?
public_dir = File.expand_path(public_dir)
path = File.expand_path(public_dir + unescape(request.path_info))
return unless path.start_with?(public_dir) and File.file?(path)
env['sinatra.static_file'] = path
cache_control(*settings.static_cache_control) if settings.static_cache_control?
send_file path, :disposition => nil
end
# Enable string or symbol key access to the nested params hash.
def indifferent_params(object)
case object
when Hash
new_hash = indifferent_hash
object.each { |key, value| new_hash[key] = indifferent_params(value) }
new_hash
when Array
object.map { |item| indifferent_params(item) }
else
object
end
end
# Creates a Hash with indifferent access.
def indifferent_hash
Hash.new {|hash,key| hash[key.to_s] if Symbol === key }
end
# Run the block with 'throw :halt' support and apply result to the response.
def invoke
res = catch(:halt) { yield }
res = [res] if Fixnum === res or String === res
if Array === res and Fixnum === res.first
status(res.shift)
body(res.pop)
headers(*res)
elsif res.respond_to? :each
body res
end
nil # avoid double setting the same response tuple twice
end
# Dispatch a request with error handling.
def dispatch!
invoke do
static! if settings.static? && (request.get? || request.head?)
filter! :before
route!
end
rescue ::Exception => boom
invoke { handle_exception!(boom) }
ensure
filter! :after unless env['sinatra.static_file']
end
# Error handling during requests.
def handle_exception!(boom)
@env['sinatra.error'] = boom
if boom.respond_to? :http_status
status(boom.http_status)
elsif settings.use_code? and boom.respond_to? :code and boom.code.between? 400, 599
status(boom.code)
else
status(500)
end
status(500) unless status.between? 400, 599
if server_error?
dump_errors! boom if settings.dump_errors?
raise boom if settings.show_exceptions? and settings.show_exceptions != :after_handler
end
if not_found?
headers['X-Cascade'] = 'pass'
body '<h1>Not Found</h1>'
end
res = error_block!(boom.class, boom) || error_block!(status, boom)
return res if res or not server_error?
raise boom if settings.raise_errors? or settings.show_exceptions?
error_block! Exception, boom
end
# Find an custom error block for the key(s) specified.
def error_block!(key, *block_params)
base = settings
while base.respond_to?(:errors)
next base = base.superclass unless args_array = base.errors[key]
args_array.reverse_each do |args|
first = args == args_array.first
args += [block_params]
resp = process_route(*args)
return resp unless resp.nil? && !first
end
end
return false unless key.respond_to? :superclass and key.superclass < Exception
error_block!(key.superclass, *block_params)
end
def dump_errors!(boom)
msg = ["#{boom.class} - #{boom.message}:", *boom.backtrace].join("\n\t")
@env['rack.errors'].puts(msg)
end
class << self
attr_reader :routes, :filters, :templates, :errors
# Removes all routes, filters, middleware and extension hooks from the
# current class (not routes/filters/... defined by its superclass).
def reset!
| ruby | MIT | a7e40d31e271f6747fa1234df37b5fff3e6e2406 | 2026-01-04T15:37:32.851738Z | true |
github-linguist/linguist | https://github.com/github-linguist/linguist/blob/a7e40d31e271f6747fa1234df37b5fff3e6e2406/samples/Ruby/gen-rb-linguist-thrift.rb | samples/Ruby/gen-rb-linguist-thrift.rb | #
# Autogenerated by Thrift Compiler (1.0.0-dev)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
require 'thrift'
require 'linguist_types'
| ruby | MIT | a7e40d31e271f6747fa1234df37b5fff3e6e2406 | 2026-01-04T15:37:32.851738Z | false |
github-linguist/linguist | https://github.com/github-linguist/linguist/blob/a7e40d31e271f6747fa1234df37b5fff3e6e2406/samples/Ruby/resque.rb | samples/Ruby/resque.rb | require 'redis/namespace'
require 'resque/version'
require 'resque/errors'
require 'resque/failure'
require 'resque/failure/base'
require 'resque/helpers'
require 'resque/stat'
require 'resque/job'
require 'resque/worker'
require 'resque/plugin'
require 'resque/queue'
require 'resque/multi_queue'
require 'resque/coder'
require 'resque/multi_json_coder'
module Resque
include Helpers
extend self
# Accepts:
# 1. A 'hostname:port' String
# 2. A 'hostname:port:db' String (to select the Redis db)
# 3. A 'hostname:port/namespace' String (to set the Redis namespace)
# 4. A Redis URL String 'redis://host:port'
# 5. An instance of `Redis`, `Redis::Client`, `Redis::DistRedis`,
# or `Redis::Namespace`.
def redis=(server)
case server
when String
if server =~ /redis\:\/\//
redis = Redis.connect(:url => server, :thread_safe => true)
else
server, namespace = server.split('/', 2)
host, port, db = server.split(':')
redis = Redis.new(:host => host, :port => port,
:thread_safe => true, :db => db)
end
namespace ||= :resque
@redis = Redis::Namespace.new(namespace, :redis => redis)
when Redis::Namespace
@redis = server
else
@redis = Redis::Namespace.new(:resque, :redis => server)
end
@queues = Hash.new { |h,name|
h[name] = Resque::Queue.new(name, @redis, coder)
}
end
# Encapsulation of encode/decode. Overwrite this to use it across Resque.
# This defaults to MultiJson for backwards compatibilty.
def coder
@coder ||= MultiJsonCoder.new
end
attr_writer :coder
# Returns the current Redis connection. If none has been created, will
# create a new one.
def redis
return @redis if @redis
self.redis = Redis.respond_to?(:connect) ? Redis.connect : "localhost:6379"
self.redis
end
def redis_id
# support 1.x versions of redis-rb
if redis.respond_to?(:server)
redis.server
elsif redis.respond_to?(:nodes) # distributed
redis.nodes.map { |n| n.id }.join(', ')
else
redis.client.id
end
end
# The `before_first_fork` hook will be run in the **parent** process
# only once, before forking to run the first job. Be careful- any
# changes you make will be permanent for the lifespan of the
# worker.
#
# Call with a block to set the hook.
# Call with no arguments to return the hook.
def before_first_fork(&block)
block ? (@before_first_fork = block) : @before_first_fork
end
# Set a proc that will be called in the parent process before the
# worker forks for the first time.
attr_writer :before_first_fork
# The `before_fork` hook will be run in the **parent** process
# before every job, so be careful- any changes you make will be
# permanent for the lifespan of the worker.
#
# Call with a block to set the hook.
# Call with no arguments to return the hook.
def before_fork(&block)
block ? (@before_fork = block) : @before_fork
end
# Set the before_fork proc.
attr_writer :before_fork
# The `after_fork` hook will be run in the child process and is passed
# the current job. Any changes you make, therefore, will only live as
# long as the job currently being processed.
#
# Call with a block to set the hook.
# Call with no arguments to return the hook.
def after_fork(&block)
block ? (@after_fork = block) : @after_fork
end
# Set the after_fork proc.
attr_writer :after_fork
def to_s
"Resque Client connected to #{redis_id}"
end
attr_accessor :inline
# If 'inline' is true Resque will call #perform method inline
# without queuing it into Redis and without any Resque callbacks.
# The 'inline' is false Resque jobs will be put in queue regularly.
alias :inline? :inline
#
# queue manipulation
#
# Pushes a job onto a queue. Queue name should be a string and the
# item should be any JSON-able Ruby object.
#
# Resque works generally expect the `item` to be a hash with the following
# keys:
#
# class - The String name of the job to run.
# args - An Array of arguments to pass the job. Usually passed
# via `class.to_class.perform(*args)`.
#
# Example
#
# Resque.push('archive', :class => 'Archive', :args => [ 35, 'tar' ])
#
# Returns nothing
def push(queue, item)
queue(queue) << item
end
# Pops a job off a queue. Queue name should be a string.
#
# Returns a Ruby object.
def pop(queue)
begin
queue(queue).pop(true)
rescue ThreadError
nil
end
end
# Returns an integer representing the size of a queue.
# Queue name should be a string.
def size(queue)
queue(queue).size
end
# Returns an array of items currently queued. Queue name should be
# a string.
#
# start and count should be integer and can be used for pagination.
# start is the item to begin, count is how many items to return.
#
# To get the 3rd page of a 30 item, paginatied list one would use:
# Resque.peek('my_list', 59, 30)
def peek(queue, start = 0, count = 1)
queue(queue).slice start, count
end
# Does the dirty work of fetching a range of items from a Redis list
# and converting them into Ruby objects.
def list_range(key, start = 0, count = 1)
if count == 1
decode redis.lindex(key, start)
else
Array(redis.lrange(key, start, start+count-1)).map do |item|
decode item
end
end
end
# Returns an array of all known Resque queues as strings.
def queues
Array(redis.smembers(:queues))
end
# Given a queue name, completely deletes the queue.
def remove_queue(queue)
queue(queue).destroy
@queues.delete(queue.to_s)
end
# Return the Resque::Queue object for a given name
def queue(name)
@queues[name.to_s]
end
#
# job shortcuts
#
# This method can be used to conveniently add a job to a queue.
# It assumes the class you're passing it is a real Ruby class (not
# a string or reference) which either:
#
# a) has a @queue ivar set
# b) responds to `queue`
#
# If either of those conditions are met, it will use the value obtained
# from performing one of the above operations to determine the queue.
#
# If no queue can be inferred this method will raise a `Resque::NoQueueError`
#
# Returns true if the job was queued, nil if the job was rejected by a
# before_enqueue hook.
#
# This method is considered part of the `stable` API.
def enqueue(klass, *args)
enqueue_to(queue_from_class(klass), klass, *args)
end
# Just like `enqueue` but allows you to specify the queue you want to
# use. Runs hooks.
#
# `queue` should be the String name of the queue you're targeting.
#
# Returns true if the job was queued, nil if the job was rejected by a
# before_enqueue hook.
#
# This method is considered part of the `stable` API.
def enqueue_to(queue, klass, *args)
# Perform before_enqueue hooks. Don't perform enqueue if any hook returns false
before_hooks = Plugin.before_enqueue_hooks(klass).collect do |hook|
klass.send(hook, *args)
end
return nil if before_hooks.any? { |result| result == false }
Job.create(queue, klass, *args)
Plugin.after_enqueue_hooks(klass).each do |hook|
klass.send(hook, *args)
end
return true
end
# This method can be used to conveniently remove a job from a queue.
# It assumes the class you're passing it is a real Ruby class (not
# a string or reference) which either:
#
# a) has a @queue ivar set
# b) responds to `queue`
#
# If either of those conditions are met, it will use the value obtained
# from performing one of the above operations to determine the queue.
#
# If no queue can be inferred this method will raise a `Resque::NoQueueError`
#
# If no args are given, this method will dequeue *all* jobs matching
# the provided class. See `Resque::Job.destroy` for more
# information.
#
# Returns the number of jobs destroyed.
#
# Example:
#
# # Removes all jobs of class `UpdateNetworkGraph`
# Resque.dequeue(GitHub::Jobs::UpdateNetworkGraph)
#
# # Removes all jobs of class `UpdateNetworkGraph` with matching args.
# Resque.dequeue(GitHub::Jobs::UpdateNetworkGraph, 'repo:135325')
#
# This method is considered part of the `stable` API.
def dequeue(klass, *args)
# Perform before_dequeue hooks. Don't perform dequeue if any hook returns false
before_hooks = Plugin.before_dequeue_hooks(klass).collect do |hook|
klass.send(hook, *args)
end
return if before_hooks.any? { |result| result == false }
Job.destroy(queue_from_class(klass), klass, *args)
Plugin.after_dequeue_hooks(klass).each do |hook|
klass.send(hook, *args)
end
end
# Given a class, try to extrapolate an appropriate queue based on a
# class instance variable or `queue` method.
def queue_from_class(klass)
klass.instance_variable_get(:@queue) ||
(klass.respond_to?(:queue) and klass.queue)
end
# This method will return a `Resque::Job` object or a non-true value
# depending on whether a job can be obtained. You should pass it the
# precise name of a queue: case matters.
#
# This method is considered part of the `stable` API.
def reserve(queue)
Job.reserve(queue)
end
# Validates if the given klass could be a valid Resque job
#
# If no queue can be inferred this method will raise a `Resque::NoQueueError`
#
# If given klass is nil this method will raise a `Resque::NoClassError`
def validate(klass, queue = nil)
queue ||= queue_from_class(klass)
if !queue
raise NoQueueError.new("Jobs must be placed onto a queue.")
end
if klass.to_s.empty?
raise NoClassError.new("Jobs must be given a class.")
end
end
#
# worker shortcuts
#
# A shortcut to Worker.all
def workers
Worker.all
end
# A shortcut to Worker.working
def working
Worker.working
end
# A shortcut to unregister_worker
# useful for command line tool
def remove_worker(worker_id)
worker = Resque::Worker.find(worker_id)
worker.unregister_worker
end
#
# stats
#
# Returns a hash, similar to redis-rb's #info, of interesting stats.
def info
return {
:pending => queues.inject(0) { |m,k| m + size(k) },
:processed => Stat[:processed],
:queues => queues.size,
:workers => workers.size.to_i,
:working => working.size,
:failed => Stat[:failed],
:servers => [redis_id],
:environment => ENV['RAILS_ENV'] || ENV['RACK_ENV'] || 'development'
}
end
# Returns an array of all known Resque keys in Redis. Redis' KEYS operation
# is O(N) for the keyspace, so be careful - this can be slow for big databases.
def keys
redis.keys("*").map do |key|
key.sub("#{redis.namespace}:", '')
end
end
end
| ruby | MIT | a7e40d31e271f6747fa1234df37b5fff3e6e2406 | 2026-01-04T15:37:32.851738Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.