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 |
|---|---|---|---|---|---|---|---|---|
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/lib/strings/version.rb | lib/strings/version.rb | # frozen_string_literal: true
module Strings
VERSION = "0.2.1"
end # Strings
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/lib/strings/extensions.rb | lib/strings/extensions.rb | # frozen_string_literal: true
require_relative "../strings"
module Strings
module Extensions
refine String do
def align(*args, **kws)
Align.align(self, *args, **kws)
end
def align_left(*args, **kws)
Align.align_left(self, *args, **kws)
end
def align_center(*args, **kws)
Align.align_center(self, *args, **kws)
end
def align_right(*args, **kws)
Align.align_right(self, *args, **kws)
end
def ansi?
ANSI.ansi?(self)
end
def fold(*args)
Fold.fold(self, *args)
end
def pad(*args, **kws)
Pad.pad(self, *args, **kws)
end
def sanitize
ANSI.sanitize(self)
end
def truncate(*args)
Truncate.truncate(self, *args)
end
def wrap(*args, **kws)
Wrap.wrap(self, *args, **kws)
end
end
end # Extensions
end # Strings
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/lib/strings/truncate.rb | lib/strings/truncate.rb | # frozen_string_literal: true
require "strings-ansi"
require "unicode/display_width"
require "unicode_utils/each_grapheme"
module Strings
# A module responsible for text truncation
module Truncate
DEFAULT_TRAILING = "…".freeze
DEFAULT_LENGTH = 30
# Truncate a text at a given length (defualts to 30)
#
# @param [String] text
# the text to be truncated
#
# @param [Integer] truncate_at
# the width at which to truncate the text
#
# @param [Hash] options
# @option options [Symbol] :separator the character for splitting words
# @option options [Symbol] :trailing the character for ending sentence
#
# @example
# text = "The sovereignest thing on earth is parmacetti for an inward bruise."
#
# Strings::Truncate.truncate(text)
# # => "The sovereignest thing on ea…"
#
# Strings::Truncate.truncate(text, 20)
# # => "The sovereignest t…"
#
# Strings::Truncate.truncate(text, 20, separator: " " )
# # => "The sovereignest…"
#
# Strings::Truncate.truncate(text, 40, trailing: "... (see more)" )
# # => "The sovereignest thing on... (see more)"
#
# @api public
def truncate(text, truncate_at = DEFAULT_LENGTH, options = {})
if truncate_at.is_a?(Hash)
options = truncate_at
truncate_at = DEFAULT_LENGTH
end
if display_width(text) <= truncate_at.to_i || truncate_at.to_i.zero?
return text.dup
end
trail = options.fetch(:trailing) { DEFAULT_TRAILING }
separation = options.fetch(:separator) { nil }
sanitized_text = Strings::ANSI.sanitize(text)
length_without_trailing = truncate_at - display_width(trail)
chars = to_chars(sanitized_text).to_a
stop = chars[0, length_without_trailing].rindex(separation)
slice_length = stop || length_without_trailing
sliced_chars = chars[0, slice_length]
original_chars = to_chars(text).to_a[0, 3 * slice_length]
shorten(original_chars, sliced_chars, length_without_trailing).join + trail
end
module_function :truncate
# Perform actual shortening of the text
#
# @return [String]
#
# @api private
def shorten(original_chars, chars, length_without_trailing)
truncated = []
return truncated if length_without_trailing.zero?
char_width = display_width(chars[0])
while length_without_trailing - char_width > 0
orig_char = original_chars.shift
char = chars.shift
break unless char
while orig_char != char # consume ansi
ansi = true
truncated << orig_char
orig_char = original_chars.shift
end
truncated << char
char_width = display_width(char)
length_without_trailing -= char_width
end
truncated << ["\e[0m"] if ansi
truncated
end
module_function :shorten
# @api private
def to_chars(text)
UnicodeUtils.each_grapheme(text)
end
module_function :to_chars
# Visible width of a string
#
# @api private
def display_width(string)
Unicode::DisplayWidth.of(Strings::ANSI.sanitize(string))
end
module_function :display_width
end # Truncate
end # Strings
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/lib/strings/fold.rb | lib/strings/fold.rb | # frozen_string_literal: true
module Strings
module Fold
LINE_BREAK = "(\r\n+|\r+|\n+|\t+)".freeze
# Fold a multiline text into a single line string
#
# @example
# fold("\tfoo \r\n\n bar") # => " foo bar"
#
# @param [String] text
#
# @param [String] separator
# the separators to be removed from the text, default: (\r\n+|\r+|\n+|\t+)
#
# @return [String]
#
# @api public
def fold(text, separator = LINE_BREAK)
text.gsub(/([ ]+)#{separator}/, "\\1")
.gsub(/#{separator}(?<space>[ ]+)/, "\\k<space>")
.gsub(/#{separator}/, " ")
end
module_function :fold
end # Fold
end # Strings
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/lib/strings/wrap.rb | lib/strings/wrap.rb | # frozen_string_literal: true
require "strings-ansi"
require "unicode/display_width"
require "unicode_utils/each_grapheme"
module Strings
module Wrap
DEFAULT_WIDTH = 80
NEWLINE = "\n"
SPACE = " "
LINE_BREAK = %r{\r\n|\r|\n}.freeze
LINE_BREAKS = "\r\n+|\r+|\n+"
# Wrap a text into lines no longer than wrap_at length.
# Preserves existing lines and existing word boundaries.
#
# @example
# Strings::Wrap.wrap("Some longish text", 8)
# # => "Some \nlongish \ntext"
#
# @api public
def wrap(text, wrap_at = DEFAULT_WIDTH, separator: NEWLINE)
if text.scan(/[[:print:]]/).length < wrap_at.to_i || wrap_at.to_i.zero?
return text
end
ansi_stack = []
text.lines.map do |line|
format_line(line, wrap_at, ansi_stack).join(separator)
end.join
end
module_function :wrap
# Format line to be maximum of wrap_at length
#
# @param [String] text_line
# the line to format
# @param [Integer] wrap_at
# the maximum length to wrap the line
#
# @return [Array[String]]
# the wrapped lines
#
# @api private
def format_line(text_line, wrap_at, ansi_stack)
lines = []
line = []
word = []
ansi = []
ansi_matched = false
word_length = 0
line_length = 0
char_length = 0 # visible char length
text_length = display_width(text_line)
total_length = 0
UnicodeUtils.each_grapheme(text_line) do |char|
# we found ansi let's consume
if char == Strings::ANSI::CSI || ansi.length > 0
ansi << char
if Strings::ANSI.only_ansi?(ansi.join)
ansi_matched = true
elsif ansi_matched
ansi_stack << [ansi[0...-1].join, line_length + word_length]
ansi_matched = false
if ansi.last == Strings::ANSI::CSI
ansi = [ansi.last]
else
ansi = []
end
end
next if ansi.length > 0
end
char_length = display_width(char)
total_length += char_length
if line_length + word_length + char_length <= wrap_at
if char == SPACE || total_length == text_length
line << word.join + char
line_length += word_length + char_length
word = []
word_length = 0
else
word << char
word_length += char_length
end
next
end
if char == SPACE # ends with space
lines << insert_ansi(line.join, ansi_stack)
line = []
line_length = 0
word << char
word_length += char_length
elsif word_length + char_length <= wrap_at
lines << insert_ansi(line.join, ansi_stack)
line = [word.join + char]
line_length = word_length + char_length
word = []
word_length = 0
else # hyphenate word - too long to fit a line
lines << insert_ansi(word.join, ansi_stack)
line_length = 0
word = [char]
word_length = char_length
end
end
lines << insert_ansi(line.join, ansi_stack) unless line.empty?
lines << insert_ansi(word.join, ansi_stack) unless word.empty?
lines
end
module_function :format_line
# Insert ANSI code into string
#
# Check if there are any ANSI states, if present
# insert ANSI codes at given positions unwinding the stack.
#
# @param [String] string
# the string to insert ANSI codes into
#
# @param [Array[Array[String, Integer]]] ansi_stack
# the ANSI codes to apply
#
# @return [String]
#
# @api private
def insert_ansi(string, ansi_stack = [])
return string if ansi_stack.empty?
return string if string.empty?
new_stack = []
output = string.dup
length = string.size
matched_reset = false
ansi_reset = Strings::ANSI::RESET
# Reversed so that string index don't count ansi
ansi_stack.reverse_each do |ansi|
if ansi[0] =~ /#{Regexp.quote(ansi_reset)}/
matched_reset = true
output.insert(ansi[1], ansi_reset)
next
elsif !matched_reset # ansi without reset
matched_reset = false
new_stack << ansi # keep the ansi
next if ansi[1] == length
if output.end_with?(NEWLINE)
output.insert(-2, ansi_reset)
else
output.insert(-1, ansi_reset) # add reset at the end
end
end
output.insert(ansi[1], ansi[0])
end
ansi_stack.replace(new_stack)
output
end
module_function :insert_ansi
# Visible width of a string
#
# @api private
def display_width(string)
Unicode::DisplayWidth.of(Strings::ANSI.sanitize(string))
end
module_function :display_width
end # Wrap
end # Strings
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/lib/strings/padder.rb | lib/strings/padder.rb | # frozen_string_literal: true
module Strings
# A class responsible for parsing padding value
#
# Used internally by {Strings::Pad}
#
# @api private
class Padder
ParseError = Class.new(ArgumentError)
# Parse padding options
#
# Turn possible values into 4 element array
#
# @example
# padder = TTY::Table::Padder.parse(5)
# padder.padding # => [5, 5, 5, 5]
#
# @param [Object] value
#
# @return [TTY::Padder]
# the new padder with padding values
#
# @api public
def self.parse(value = nil)
return value if value.is_a?(self)
new(convert_to_ary(value))
end
# Convert value to 4 element array
#
# @return [Array[Integer]]
# the 4 element padding array
#
# @api private
def self.convert_to_ary(value)
if value.class <= Numeric
[value, value, value, value]
elsif value.nil?
[]
elsif value.size == 2
[value[0], value[1], value[0], value[1]]
elsif value.size == 4
value
else
raise ParseError, "Wrong :padding parameter, must be an array"
end
end
# Padding
#
# @return [Array[Integer]]
attr_reader :padding
# Initialize a Padder
#
# @api public
def initialize(padding)
@padding = padding
end
# Top padding
#
# @return [Integer]
#
# @api public
def top
@padding[0].to_i
end
# Set top padding
#
# @param [Integer] value
#
# @return [nil]
#
# @api public
def top=(value)
@padding[0] = value
end
# Right padding
#
# @return [Integer]
#
# @api public
def right
@padding[1].to_i
end
# Set right padding
#
# @param [Integer] value
#
# @api public
def right=(value)
@padding[1] = value
end
# Bottom padding
#
# @return [Integer]
#
# @api public
def bottom
@padding[2].to_i
end
# Set bottom padding
#
# @param [Integer] value
#
# @return [nil]
#
# @api public
def bottom=(value)
@padding[2] = value
end
# Left padding
#
# @return [Integer]
#
# @api public
def left
@padding[3].to_i
end
# Set left padding
#
# @param [Integer] value
#
# @return [nil]
#
# @api public
def left=(value)
@padding[3] = value
end
# Check if padding is set
#
# @return [Boolean]
#
# @api public
def empty?
padding.empty?
end
# String represenation of this padder with padding values
#
# @return [String]
#
# @api public
def to_s
inspect
end
end # Padder
end
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/lib/strings/pad.rb | lib/strings/pad.rb | # frozen_string_literal: true
require "strings-ansi"
require "unicode/display_width"
require_relative "padder"
module Strings
# Responsible for text padding
module Pad
NEWLINE = "\n"
SPACE = " "
LINE_BREAK = %r{\r\n|\r|\n}.freeze
# Apply padding to multiline text with ANSI codes
#
# @param [String] text
# the text to pad out
# @param [Integer, Array[Integer]] padding
# the padding to apply to text
#
# @example
# text = "Ignorance is the parent of fear."
#
# Strings::Pad.pad(text, [1, 2], fill: "*")
# # =>
# # "************************************\n"
# # "**Ignorance is the parent of fear.**\n"
# # "************************************\n"
#
# @return [String]
#
# @api private
def pad(text, padding, fill: SPACE, separator: nil)
padding = Strings::Padder.parse(padding)
text_copy = text.dup
sep = separator || text[LINE_BREAK] || NEWLINE
line_width = max_line_length(text, sep)
output = []
filler_line = fill * line_width
padding.top.times do
output << pad_around(filler_line, padding, fill: fill)
end
text_copy.split(sep).each do |line|
line = line.empty? ? filler_line : line
output << pad_around(line, padding, fill: fill)
end
padding.bottom.times do
output << pad_around(filler_line, padding, fill: fill)
end
output.join(sep)
end
module_function :pad
# Apply padding to left and right side of string
#
# @param [String] text
#
# @return [String]
#
# @api private
def pad_around(text, padding, fill: SPACE)
fill * padding.left + text + fill * padding.right
end
module_function :pad_around
# Determine maximum length for all multiline content
#
# @param [String] text
# @param [String] separator
#
# @return [Integer]
#
# @api private
def max_line_length(text, separator)
lines = text.split(separator, -1)
display_width(lines.max_by { |line| display_width(line) } || "")
end
module_function :max_line_length
# Calculate visible string width
#
# @return [Integer]
#
# @api private
def display_width(string)
Unicode::DisplayWidth.of(Strings::ANSI.sanitize(string))
end
module_function :display_width
end # Padding
end # Strings
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/samples/mvm.rb | tools/jruby-1.5.1/samples/mvm.rb | require 'jruby/vm'
# create the VMs
vm1 = JRuby::VM.spawn(['-e' "load 'samples/mvm_subvm.rb'"])
vm2 = JRuby::VM.spawn(['-e' "load 'samples/mvm_subvm.rb'"])
# connect them to parent
vm1 << JRuby::VM_ID
vm2 << JRuby::VM_ID
# connect them together
vm1 << vm2.id
vm2 << vm1.id
# start them running
vm1 << 1
# let them run for a while, reading their progress
run = true
Thread.new { while run; puts JRuby::VM.get_message; end }
sleep 20
# shut them down
run = false
vm1 << 'done'
vm2 << 'done'
vm1.join
vm2.join | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/samples/thread.rb | tools/jruby-1.5.1/samples/thread.rb | x = Thread.new { sleep 0.1; print "x"; print "y"; print "z" }
a = Thread.new { print "a"; print "b"; sleep 0.2; print "c" }
x.join # Let the threads finish before
a.join # main thread exits...
puts # newline
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/samples/xslt.rb | tools/jruby-1.5.1/samples/xslt.rb | include Java
require 'optparse'
require 'ostruct'
import java.io.FileOutputStream
import javax.xml.transform.stream.StreamSource
import javax.xml.transform.TransformerFactory
class XSLTOptions
def self.parse(args)
options = OpenStruct.new
options.parameters = {}
opts = OptionParser.new do |opts|
opts.banner = "Usage: [options] xslt {xml} {xslt} [{result}]"
opts.separator ""
opts.separator "Specific options:"
opts.on("-p", "--parameters name=value,name1=value1", Array) do |n|
n.collect do |v|
name, value = v.split(/\s*=\s*/)
options.parameters[name] = value
end
end
end
opts.parse!(args)
options
end
end
options = XSLTOptions.parse(ARGV)
if (ARGV.length < 2 || ARGV.length > 3)
puts "Usage: xslt {xml} {xslt} [{result}]"
exit
end
document = StreamSource.new ARGV[0]
stylesheet = StreamSource.new ARGV[1]
output = ARGV.length < 3 ? java.lang.System::out : FileOutputStream.new(ARGV[2])
result = javax.xml.transform.stream.StreamResult.new output
begin
transformer = TransformerFactory.newInstance.newTransformer(stylesheet)
options.parameters.each {|name, value| transformer.setParameter(name, value) }
transformer.transform(document, result)
rescue java.lang.Exception => e
puts e
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/samples/java2.rb | tools/jruby-1.5.1/samples/java2.rb | require "java"
filename = __FILE__
fr = java.io.FileReader.new filename
br = java.io.BufferedReader.new fr
s = br.readLine
print "------ ", filename, "------\n"
while s
puts s.to_s
s = br.readLine
end
print "------ ", filename, " end ------\n";
br.close
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/samples/swing2.rb | tools/jruby-1.5.1/samples/swing2.rb | # Import Java packages
include Java
import javax.swing.JFrame
frame = JFrame.new("Hello Swing")
button = javax.swing.JButton.new("Klick Me!")
button.add_action_listener do |evt|
javax.swing.JOptionPane.showMessageDialog(nil, <<EOS)
<html>Hello from <b><u>JRuby</u></b>.<br>
Button '#{evt.getActionCommand()}' clicked.
EOS
end
# Add the button to the frame
frame.get_content_pane.add(button)
# Show frame
frame.set_default_close_operation(JFrame::EXIT_ON_CLOSE)
frame.pack
frame.visible = true
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/samples/mvm_subvm.rb | tools/jruby-1.5.1/samples/mvm_subvm.rb | require 'jruby/vm'
VM = JRuby::VM
ID = JRuby::VM_ID
# get the VM id of the parent
parent = VM.get_message
# get the VM id we're sending to
other = VM.get_message
VM.send_message(parent,
"VM #{ID} starting up, sibling is: #{other}, parent is: #{parent}")
# loop until we receive nil, adding one and sending on
while message = VM.get_message
break if message == "done"
sleep 0.5
new_message = message + 1
VM.send_message(parent,
"VM #{JRuby::VM_ID} received: #{message}, sending #{new_message}")
VM.send_message(other, message + 1)
end
VM.send_message(parent,
"VM #{JRuby::VM_ID} terminating") | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/samples/error.rb | tools/jruby-1.5.1/samples/error.rb |
require 'java'
Java::define_exception_handler "java.lang.NumberFormatException" do |e|
puts e.java_type
p e.methods
puts e.java_class.java_method(:getMessage).invoke(e)
end
java.lang.Long.parseLong("23aa")
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/samples/jrubyc_java/simple_class.rb | tools/jruby-1.5.1/samples/jrubyc_java/simple_class.rb | require 'java'
class SimpleRubyClass
java_signature "void simple_method()"
def simple_method
puts "here!"
end
end
=begin
~/projects/jruby/jrubyc_stuff ➔ jrubyc --java simple_class.rb
Compiling simple_class.rb to class simple_class
Generating Java class SimpleRubyClass to SimpleRubyClass.java
javac -cp /Users/headius/projects/jruby/lib/jruby.jar:. SimpleRubyClass.java
~/projects/jruby/jrubyc_stuff ➔ javap SimpleRubyClass
Compiled from "SimpleRubyClass.java"
public class SimpleRubyClass extends org.jruby.RubyObject{
public SimpleRubyClass();
public void simple_method();
static {};
}
=end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/samples/jrubyc_java/overloads.rb | tools/jruby-1.5.1/samples/jrubyc_java/overloads.rb | require 'java'
class OverloadedClass
java_signature "void run(String)"
def run1(a); end
java_signature "void run(int)"
def run2(a); end
end
=begin
~/projects/jruby/samples/jrubyc_java ➔ jrubyc --java overloads.rb
Compiling overloads.rb to class overloads
Generating Java class OverloadedClass to OverloadedClass.java
javac -cp /Users/headius/projects/jruby/lib/jruby.jar:. OverloadedClass.java
Note: OverloadedClass.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
~/projects/jruby/samples/jrubyc_java ➔ cat OverloadedClass.java
import org.jruby.Ruby;
import org.jruby.RubyObject;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.javasupport.JavaUtil;
import org.jruby.RubyClass;
public class OverloadedClass extends RubyObject {
private static final Ruby __ruby__ = Ruby.getGlobalRuntime();
private static final RubyClass __metaclass__;
static {
__ruby__.getLoadService().lockAndRequire("overloads.rb");
RubyClass metaclass = __ruby__.getClass("OverloadedClass");
metaclass.setClassAllocator(OverloadedClass.class);
if (metaclass == null) throw new NoClassDefFoundError("Could not load Ruby class: OverloadedClass");
__metaclass__ = metaclass;
}
public OverloadedClass() {
super(__ruby__, __metaclass__);
}
public void run(String a) {
IRubyObject ruby_a = JavaUtil.convertJavaToRuby(__ruby__, a);
IRubyObject ruby_result = RuntimeHelpers.invoke(__ruby__.getCurrentContext(), this, "run1" ,ruby_a);
}
public void run(int a) {
IRubyObject ruby_a = JavaUtil.convertJavaToRuby(__ruby__, a);
IRubyObject ruby_result = RuntimeHelpers.invoke(__ruby__.getCurrentContext(), this, "run2" ,ruby_a);
}
}
=end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/samples/jrubyc_java/my_runnable.rb | tools/jruby-1.5.1/samples/jrubyc_java/my_runnable.rb | require 'java'
class MyRunnable
java_implements "java.lang.Runnable"
java_signature "void run()"
def run
puts 'here'
end
java_signature "void main(String[])"
def self.main(args)
t = java.lang.Thread.new(MyRunnable.new)
t.start
end
end
=begin
~/projects/jruby/jrubyc_stuff ➔ jrubyc --java my_runnable.rb
Compiling my_runnable.rb to class my_runnable
Generating Java class MyRunnable to MyRunnable.java
javac -cp /Users/headius/projects/jruby/lib/jruby.jar:. MyRunnable.java
~/projects/jruby/jrubyc_stuff ➔ java -cp ../lib/jruby.jar:. MyRunnable
here
~/projects/jruby/jrubyc_stuff ➔ javap MyRunnable
Compiled from "MyRunnable.java"
public class MyRunnable extends org.jruby.RubyObject implements java.lang.Runnable{
public MyRunnable();
public void run();
public static void main(java.lang.String[]);
static {};
}
=end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/samples/jrubyc_java/simple_class2.rb | tools/jruby-1.5.1/samples/jrubyc_java/simple_class2.rb | require 'java'
class MyRubyClass
java_signature 'void helloWorld()'
def helloWorld
puts "Hello from Ruby"
end
java_signature 'void goodbyeWorld(String)'
def goodbyeWorld(a)
puts a
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/samples/jrubyc_java/simple_junit.rb | tools/jruby-1.5.1/samples/jrubyc_java/simple_junit.rb | require 'java'
class TestSomething
java_annotation "org.junit.Test"
def test_jruby_rocks
fail unless "JRuby rocks" == "JRuby" + " " + "rocks"
end
java_annotation "org.junit.Test"
def test_jruby_will_never_support_annotations
fail("JRuby does support annotations!") if "JRuby supports annotations"
end
end
=begin
~/projects/jruby/samples/compiler2 ➔ jrubyc -c ~/Downloads/junit-4.6.jar --java myruby3.rb
Compiling myruby3.rb to class myruby3
Generating Java class TestSomething to TestSomething.java
javac -cp /Users/headius/projects/jruby/lib/jruby.jar:/Users/headius/Downloads/junit-4.6.jar TestSomething.java
~/projects/jruby/samples/compiler2 ➔ cat TestSomething.java
import org.jruby.Ruby;
import org.jruby.RubyObject;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.javasupport.JavaUtil;
import org.jruby.RubyClass;
public class TestSomething extends RubyObject {
private static final Ruby __ruby__ = Ruby.getGlobalRuntime();
private static final RubyClass __metaclass__;
static {
__ruby__.getLoadService().lockAndRequire("myruby3.rb");
RubyClass metaclass = __ruby__.getClass("TestSomething");
metaclass.setClassAllocator(TestSomething.class);
if (metaclass == null) throw new NoClassDefFoundError("Could not load Ruby class: TestSomething");
__metaclass__ = metaclass;
}
public TestSomething() {
super(__ruby__, __metaclass__);
}
@org.junit.Test()
public Object test_jruby_rocks() {
IRubyObject ruby_result = RuntimeHelpers.invoke(__ruby__.getCurrentContext(), this, "test_jruby_rocks" );
return (Object)ruby_result.toJava(Object.class);
}
@org.junit.Test()
public Object test_jruby_will_never_support_annotations() {
IRubyObject ruby_result = RuntimeHelpers.invoke(__ruby__.getCurrentContext(), this, "test_jruby_will_never_support_annotations" );
return (Object)ruby_result.toJava(Object.class);
}
}
=end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/samples/jrubyc_java/annotated.rb | tools/jruby-1.5.1/samples/jrubyc_java/annotated.rb | require 'java'
java_import "java.lang.Deprecated"
java_annotation :Deprecated
class DeprecatedClass
end
=begin
import org.jruby.Ruby;
import org.jruby.RubyObject;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.javasupport.JavaUtil;
import org.jruby.RubyClass;
import java.lang.Deprecated;
@Deprecated()
public class DeprecatedClass extends RubyObject {
private static final Ruby __ruby__ = Ruby.getGlobalRuntime();
private static final RubyClass __metaclass__;
static {
__ruby__.getLoadService().lockAndRequire("annotated.rb");
RubyClass metaclass = __ruby__.getClass("DeprecatedClass");
metaclass.setClassAllocator(DeprecatedClass.class);
if (metaclass == null) throw new NoClassDefFoundError("Could not load Ruby class: DeprecatedClass");
__metaclass__ = metaclass;
}
public DeprecatedClass() {
super(__ruby__, __metaclass__);
}
}
=end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/samples/ext/extconf.rb | tools/jruby-1.5.1/samples/ext/extconf.rb | # Loads mkmf which is used to make makefiles for Ruby extensions
require 'mkmf'
# Give it a name
extension_name = 'mytest'
# The destination
dir_config(extension_name)
# Do the work
create_makefile(extension_name)
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/samples/ffi/qsort.rb | tools/jruby-1.5.1/samples/ffi/qsort.rb | require 'ffi'
module LibC
extend FFI::Library
ffi_lib FFI::Library::LIBC
callback :qsort_cmp, [ :pointer, :pointer ], :int
attach_function :qsort, [ :pointer, :int, :int, :qsort_cmp ], :int
end
p = FFI::MemoryPointer.new(:int, 2)
p.put_array_of_int32(0, [ 2, 1 ])
puts "Before qsort #{p.get_array_of_int32(0, 2).join(', ')}"
LibC.qsort(p, 2, 4) do |p1, p2|
i1 = p1.get_int32(0)
i2 = p2.get_int32(0)
i1 < i2 ? -1 : i1 > i2 ? 1 : 0
end
puts "After qsort #{p.get_array_of_int32(0, 2).join(', ')}"
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/samples/ffi/ffi.rb | tools/jruby-1.5.1/samples/ffi/ffi.rb | require 'ffi'
module POSIX
extend FFI::Library
# this line isn't really necessary since libc is always linked into JVM
ffi_lib 'c'
attach_function :getuid, :getuid, [], :uint
attach_function :getpid, :getpid, [], :uint
end
puts "Process #{POSIX.getpid} running as user #{POSIX.getuid}"
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/samples/ffi/pty.rb | tools/jruby-1.5.1/samples/ffi/pty.rb | require 'ffi'
module PTY
private
module LibC
extend FFI::Library
# forkpty(3) is in libutil on linux, libc on MacOS/BSD
if FFI::Platform.linux?
ffi_lib 'libutil'
else
ffi_lib FFI::Library::LIBC
end
attach_function :forkpty, [ :buffer_out, :buffer_out, :buffer_in, :buffer_in ], :pid_t
attach_function :openpty, [ :buffer_out, :buffer_out, :buffer_out, :buffer_in, :buffer_in ], :int
attach_function :login_tty, [ :int ], :int
attach_function :close, [ :int ], :int
attach_function :strerror, [ :int ], :string
attach_function :fork, [], :pid_t
attach_function :execv, [ :string, :buffer_in ], :int
attach_function :execvp, [ :string, :buffer_in ], :int
attach_function :dup2, [ :int, :int ], :int
attach_function :dup, [ :int ], :int
end
Buffer = FFI::Buffer
def self.build_args(args)
cmd = args.shift
cmd_args = args.map do |arg|
FFI::MemoryPointer.from_string(arg)
end
exec_args = FFI::MemoryPointer.new(:pointer, 1 + cmd_args.length + 1)
exec_cmd = FFI::MemoryPointer.from_string(cmd)
exec_args[0].put_pointer(0, exec_cmd)
cmd_args.each_with_index do |arg, i|
exec_args[i + 1].put_pointer(0, arg)
end
[ cmd, exec_args ]
end
public
def self.getpty(*args)
mfdp = Buffer.new :int
name = Buffer.new 1024
#
# All the execv setup is done in the parent, since doing anything other than
# execv in the child after fork is really flakey
#
exec_cmd, exec_args = build_args(args)
pid = LibC.forkpty(mfdp, name, nil, nil)
raise "forkpty failed: #{LibC.strerror(FFI.errno)}" if pid < 0
if pid == 0
LibC.execvp(exec_cmd, exec_args)
exit 1
end
masterfd = mfdp.get_int(0)
rfp = FFI::IO.for_fd(masterfd, "r")
wfp = FFI::IO.for_fd(LibC.dup(masterfd), "w")
if block_given?
yield rfp, wfp, pid
rfp.close unless rfp.closed?
wfp.close unless wfp.closed?
else
[ rfp, wfp, pid ]
end
end
def self.spawn(*args, &block)
self.getpty("/bin/sh", "-c", args[0], &block)
end
end
module LibC
extend FFI::Library
ffi_lib FFI::Library::LIBC
attach_function :close, [ :int ], :int
attach_function :write, [ :int, :buffer_in, :size_t ], :ssize_t
attach_function :read, [ :int, :buffer_out, :size_t ], :ssize_t
end
PTY.getpty("/bin/ls", "-alR", "/") { |rfd, wfd, pid|
#PTY.spawn("ls -laR /") { |rfd, wfd, pid|
puts "child pid=#{pid}"
while !rfd.eof? && (buf = rfd.gets)
puts "child: '#{buf.strip}'"
end
} | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/samples/ffi/win32api.rb | tools/jruby-1.5.1/samples/ffi/win32api.rb | require 'ffi'
module Win32
class API < Module
CONVENTION = FFI::Platform.windows? ? :stdcall : :default
SUFFIXES = $KCODE == 'UTF8' ? [ '', 'W', 'A' ] : [ '', 'A', 'W' ]
TypeDefs = {
'V' => :void,
'S' => :string,
'P' => :pointer,
'I' => :int,
'L' => :long,
}
def self.find_type(name)
code = TypeDefs[name]
raise TypeError, "Unable to resolve type '#{name}'" unless code
return code
end
def self.map_types(spec)
types = []
for i in 0..(spec.length - 1)
if spec[i].chr == 'V'
return []
end
types[i] = self.find_type(spec.slice(i,1))
end
types
end
def initialize(func, params, ret='L', lib='kernel32')
#
# Attach the method as 'call', so it gets all the froody arity-splitting optimizations
#
extend FFI::Library
ffi_lib lib
ffi_convention CONVENTION
attached = false
SUFFIXES.each { |suffix|
begin
attach_function(:call, func.to_s + suffix, API.map_types(params), API.map_types(ret)[0])
attached = true
break
rescue FFI::NotFoundError => ex
end
}
raise FFI::NotFoundError, "Could not locate #{func}" if !attached
end
end
end
unless FFI::Platform.windows?
cputs = Win32::API.new("puts", "S", 'L', 'c')
cputs.call("Hello, World")
exit 0
end
beep = Win32::API.new("MessageBeep", 'L', 'L', 'user32')
2.times { beep.call(0) }
buf = 0.chr * 260
GetComputerName = Win32::API.new("GetComputerName", 'PP', 'L', 'kernel32')
ret = GetComputerName.call(buf, [buf.length].pack("V"))
puts "GetComputerName returned #{ret}"
puts "computer name=#{buf.strip}"
len = [buf.length].pack('V')
GetUserName = Win32::API.new("GetUserName", 'PP', 'I', 'advapi32')
ret = GetUserName.call(buf, len)
puts "GetUserName returned #{ret}"
puts "username=#{buf.strip}"
puts "len=#{len.unpack('V')}"
getcwd = Win32::API.new("GetCurrentDirectory", 'LP')
buf = 0.chr * 260
getcwd.call(buf.length, buf)
puts "current dir=#{buf.strip}"
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/samples/ffi/gettimeofday.rb | tools/jruby-1.5.1/samples/ffi/gettimeofday.rb | require 'rubygems'
require 'ffi'
class Timeval < FFI::Struct
rb_maj, rb_min, rb_micro = RUBY_VERSION.split('.')
if rb_maj.to_i >= 1 && rb_min.to_i >= 9 || RUBY_PLATFORM =~ /java/
layout :tv_sec => :ulong, :tv_usec => :ulong
else
layout :tv_sec, :ulong, 0, :tv_usec, :ulong, 4
end
end
module LibC
extend FFI::Library
ffi_lib FFI::Library::LIBC
attach_function :gettimeofday, [ :pointer, :pointer ], :int
end
t = Timeval.new
LibC.gettimeofday(t.pointer, nil)
puts "t.tv_sec=#{t[:tv_sec]} t.tv_usec=#{t[:tv_usec]}"
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/bin/prettify_json.rb | tools/jruby-1.5.1/bin/prettify_json.rb | #!/usr/bin/env jruby
#
# This file was generated by RubyGems.
#
# The application 'json_pure' is installed as part of a gem, and
# this file is here to facilitate running it.
#
require 'rubygems'
version = ">= 0"
if ARGV.first =~ /^_(.*)_$/ and Gem::Version.correct? $1 then
version = $1
ARGV.shift
end
gem 'json_pure', version
load Gem.bin_path('json_pure', 'prettify_json.rb', version)
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/bin/generate_yaml_index.rb | tools/jruby-1.5.1/bin/generate_yaml_index.rb | #!/usr/bin/env jruby
# Generate the yaml/yaml.Z index files for a gem server directory.
#
# Usage: generate_yaml_index.rb --dir DIR [--verbose]
$:.unshift '~/rubygems' if File.exist? "~/rubygems"
require 'optparse'
require 'rubygems'
require 'zlib'
Gem.manage_gems
class Indexer
def initialize(options)
@options = options
@directory = options[:directory]
end
def gem_file_list
Dir.glob(File.join(@directory, "gems", "*.gem"))
end
def build_index
build_uncompressed_index
build_compressed_index
end
def build_uncompressed_index
puts "Building yaml file" if @options[:verbose]
File.open(File.join(@directory, "yaml"), "w") do |file|
file.puts "--- !ruby/object:Gem::Cache"
file.puts "gems:"
gem_file_list.each do |gemfile|
spec = Gem::Format.from_file_by_path(gemfile).spec
puts " ... adding #{spec.full_name}" if @options[:verbose]
file.puts " #{spec.full_name}: #{spec.to_yaml.gsub(/\n/, "\n ")[4..-1]}"
end
end
end
def build_compressed_index
puts "Building yaml.Z file" if @options[:verbose]
File.open(File.join(@directory, "yaml.Z"), "w") do |file|
file.write(Zlib::Deflate.deflate(File.read(File.join(@directory, "yaml"))))
end
end
end
options = {
:directory => '.',
:verbose => false,
}
ARGV.options do |opts|
opts.on_tail("--help", "show this message") {puts opts; exit}
opts.on('-d', '--dir=DIRNAME', "base directory containing gems subdirectory", String) do |value|
options[:directory] = value
end
opts.on('-v', '--verbose', "show verbose output") do |value|
options[:verbose] = value
end
opts.parse!
end
if options[:directory].nil?
puts "Error, must specify directory name. Use --help"
exit
elsif ! File.exist?(options[:directory]) ||
! File.directory?(options[:directory])
puts "Error, unknown directory name #{directory}."
exit
end
Indexer.new(options).build_index
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/bin/edit_json.rb | tools/jruby-1.5.1/bin/edit_json.rb | #!/usr/bin/env jruby
#
# This file was generated by RubyGems.
#
# The application 'json_pure' is installed as part of a gem, and
# this file is here to facilitate running it.
#
require 'rubygems'
version = ">= 0"
if ARGV.first =~ /^_(.*)_$/ and Gem::Version.correct? $1 then
version = $1
ARGV.shift
end
gem 'json_pure', version
load Gem.bin_path('json_pure', 'edit_json.rb', version)
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/setup.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/setup.rb | #
# setup.rb
#
# Copyright (c) 2000-2005 Minero Aoki
#
# This program is free software.
# You can distribute/modify this program under the terms of
# the GNU LGPL, Lesser General Public License version 2.1.
#
unless Enumerable.method_defined?(:map) # Ruby 1.4.6
module Enumerable
alias map collect
end
end
unless File.respond_to?(:read) # Ruby 1.6
def File.read(fname)
open(fname) {|f|
return f.read
}
end
end
unless Errno.const_defined?(:ENOTEMPTY) # Windows?
module Errno
class ENOTEMPTY
# We do not raise this exception, implementation is not needed.
end
end
end
def File.binread(fname)
open(fname, 'rb') {|f|
return f.read
}
end
# for corrupted Windows' stat(2)
def File.dir?(path)
File.directory?((path[-1,1] == '/') ? path : path + '/')
end
class ConfigTable
include Enumerable
def initialize(rbconfig)
@rbconfig = rbconfig
@items = []
@table = {}
# options
@install_prefix = nil
@config_opt = nil
@verbose = true
@no_harm = false
end
attr_accessor :install_prefix
attr_accessor :config_opt
attr_writer :verbose
def verbose?
@verbose
end
attr_writer :no_harm
def no_harm?
@no_harm
end
def [](key)
lookup(key).resolve(self)
end
def []=(key, val)
lookup(key).set val
end
def names
@items.map {|i| i.name }
end
def each(&block)
@items.each(&block)
end
def key?(name)
@table.key?(name)
end
def lookup(name)
@table[name] or setup_rb_error "no such config item: #{name}"
end
def add(item)
@items.push item
@table[item.name] = item
end
def remove(name)
item = lookup(name)
@items.delete_if {|i| i.name == name }
@table.delete_if {|name, i| i.name == name }
item
end
def load_script(path, inst = nil)
if File.file?(path)
MetaConfigEnvironment.new(self, inst).instance_eval File.read(path), path
end
end
def savefile
'.config'
end
def load_savefile
begin
File.foreach(savefile()) do |line|
k, v = *line.split(/=/, 2)
self[k] = v.strip
end
rescue Errno::ENOENT
setup_rb_error $!.message + "\n#{File.basename($0)} config first"
end
end
def save
@items.each {|i| i.value }
File.open(savefile(), 'w') {|f|
@items.each do |i|
f.printf "%s=%s\n", i.name, i.value if i.value? and i.value
end
}
end
def load_standard_entries
standard_entries(@rbconfig).each do |ent|
add ent
end
end
def standard_entries(rbconfig)
c = rbconfig
rubypath = File.join(c['bindir'], c['ruby_install_name'] + c['EXEEXT'])
major = c['MAJOR'].to_i
minor = c['MINOR'].to_i
teeny = c['TEENY'].to_i
version = "#{major}.#{minor}"
# ruby ver. >= 1.4.4?
newpath_p = ((major >= 2) or
((major == 1) and
((minor >= 5) or
((minor == 4) and (teeny >= 4)))))
if c['rubylibdir']
# V > 1.6.3
libruby = "#{c['prefix']}/lib/ruby"
librubyver = c['rubylibdir']
librubyverarch = c['archdir']
siteruby = c['sitedir']
siterubyver = c['sitelibdir']
siterubyverarch = c['sitearchdir']
elsif newpath_p
# 1.4.4 <= V <= 1.6.3
libruby = "#{c['prefix']}/lib/ruby"
librubyver = "#{c['prefix']}/lib/ruby/#{version}"
librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}"
siteruby = c['sitedir']
siterubyver = "$siteruby/#{version}"
siterubyverarch = "$siterubyver/#{c['arch']}"
else
# V < 1.4.4
libruby = "#{c['prefix']}/lib/ruby"
librubyver = "#{c['prefix']}/lib/ruby/#{version}"
librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}"
siteruby = "#{c['prefix']}/lib/ruby/#{version}/site_ruby"
siterubyver = siteruby
siterubyverarch = "$siterubyver/#{c['arch']}"
end
parameterize = lambda {|path|
path.sub(/\A#{Regexp.quote(c['prefix'])}/, '$prefix')
}
if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg }
makeprog = arg.sub(/'/, '').split(/=/, 2)[1]
else
makeprog = 'make'
end
[
ExecItem.new('installdirs', 'std/site/home',
'std: install under libruby; site: install under site_ruby; home: install under $HOME')\
{|val, table|
case val
when 'std'
table['rbdir'] = '$librubyver'
table['sodir'] = '$librubyverarch'
when 'site'
table['rbdir'] = '$siterubyver'
table['sodir'] = '$siterubyverarch'
when 'home'
setup_rb_error '$HOME was not set' unless ENV['HOME']
table['prefix'] = ENV['HOME']
table['rbdir'] = '$libdir/ruby'
table['sodir'] = '$libdir/ruby'
end
},
PathItem.new('prefix', 'path', c['prefix'],
'path prefix of target environment'),
PathItem.new('bindir', 'path', parameterize.call(c['bindir']),
'the directory for commands'),
PathItem.new('libdir', 'path', parameterize.call(c['libdir']),
'the directory for libraries'),
PathItem.new('datadir', 'path', parameterize.call(c['datadir']),
'the directory for shared data'),
PathItem.new('mandir', 'path', parameterize.call(c['mandir']),
'the directory for man pages'),
PathItem.new('sysconfdir', 'path', parameterize.call(c['sysconfdir']),
'the directory for system configuration files'),
PathItem.new('localstatedir', 'path', parameterize.call(c['localstatedir']),
'the directory for local state data'),
PathItem.new('libruby', 'path', libruby,
'the directory for ruby libraries'),
PathItem.new('librubyver', 'path', librubyver,
'the directory for standard ruby libraries'),
PathItem.new('librubyverarch', 'path', librubyverarch,
'the directory for standard ruby extensions'),
PathItem.new('siteruby', 'path', siteruby,
'the directory for version-independent aux ruby libraries'),
PathItem.new('siterubyver', 'path', siterubyver,
'the directory for aux ruby libraries'),
PathItem.new('siterubyverarch', 'path', siterubyverarch,
'the directory for aux ruby binaries'),
PathItem.new('rbdir', 'path', '$siterubyver',
'the directory for ruby scripts'),
PathItem.new('sodir', 'path', '$siterubyverarch',
'the directory for ruby extentions'),
PathItem.new('rubypath', 'path', rubypath,
'the path to set to #! line'),
ProgramItem.new('rubyprog', 'name', rubypath,
'the ruby program using for installation'),
ProgramItem.new('makeprog', 'name', makeprog,
'the make program to compile ruby extentions'),
SelectItem.new('shebang', 'all/ruby/never', 'ruby',
'shebang line (#!) editing mode'),
BoolItem.new('without-ext', 'yes/no', 'no',
'does not compile/install ruby extentions')
]
end
private :standard_entries
def load_multipackage_entries
multipackage_entries().each do |ent|
add ent
end
end
def multipackage_entries
[
PackageSelectionItem.new('with', 'name,name...', '', 'ALL',
'package names that you want to install'),
PackageSelectionItem.new('without', 'name,name...', '', 'NONE',
'package names that you do not want to install')
]
end
private :multipackage_entries
ALIASES = {
'std-ruby' => 'librubyver',
'stdruby' => 'librubyver',
'rubylibdir' => 'librubyver',
'archdir' => 'librubyverarch',
'site-ruby-common' => 'siteruby', # For backward compatibility
'site-ruby' => 'siterubyver', # For backward compatibility
'bin-dir' => 'bindir',
'bin-dir' => 'bindir',
'rb-dir' => 'rbdir',
'so-dir' => 'sodir',
'data-dir' => 'datadir',
'ruby-path' => 'rubypath',
'ruby-prog' => 'rubyprog',
'ruby' => 'rubyprog',
'make-prog' => 'makeprog',
'make' => 'makeprog'
}
def fixup
ALIASES.each do |ali, name|
@table[ali] = @table[name]
end
@items.freeze
@table.freeze
@options_re = /\A--(#{@table.keys.join('|')})(?:=(.*))?\z/
end
def parse_opt(opt)
m = @options_re.match(opt) or setup_rb_error "config: unknown option #{opt}"
m.to_a[1,2]
end
def dllext
@rbconfig['DLEXT']
end
def value_config?(name)
lookup(name).value?
end
class Item
def initialize(name, template, default, desc)
@name = name.freeze
@template = template
@value = default
@default = default
@description = desc
end
attr_reader :name
attr_reader :description
attr_accessor :default
alias help_default default
def help_opt
"--#{@name}=#{@template}"
end
def value?
true
end
def value
@value
end
def resolve(table)
@value.gsub(%r<\$([^/]+)>) { table[$1] }
end
def set(val)
@value = check(val)
end
private
def check(val)
setup_rb_error "config: --#{name} requires argument" unless val
val
end
end
class BoolItem < Item
def config_type
'bool'
end
def help_opt
"--#{@name}"
end
private
def check(val)
return 'yes' unless val
case val
when /\Ay(es)?\z/i, /\At(rue)?\z/i then 'yes'
when /\An(o)?\z/i, /\Af(alse)\z/i then 'no'
else
setup_rb_error "config: --#{@name} accepts only yes/no for argument"
end
end
end
class PathItem < Item
def config_type
'path'
end
private
def check(path)
setup_rb_error "config: --#{@name} requires argument" unless path
path[0,1] == '$' ? path : File.expand_path(path)
end
end
class ProgramItem < Item
def config_type
'program'
end
end
class SelectItem < Item
def initialize(name, selection, default, desc)
super
@ok = selection.split('/')
end
def config_type
'select'
end
private
def check(val)
unless @ok.include?(val.strip)
setup_rb_error "config: use --#{@name}=#{@template} (#{val})"
end
val.strip
end
end
class ExecItem < Item
def initialize(name, selection, desc, &block)
super name, selection, nil, desc
@ok = selection.split('/')
@action = block
end
def config_type
'exec'
end
def value?
false
end
def resolve(table)
setup_rb_error "$#{name()} wrongly used as option value"
end
undef set
def evaluate(val, table)
v = val.strip.downcase
unless @ok.include?(v)
setup_rb_error "invalid option --#{@name}=#{val} (use #{@template})"
end
@action.call v, table
end
end
class PackageSelectionItem < Item
def initialize(name, template, default, help_default, desc)
super name, template, default, desc
@help_default = help_default
end
attr_reader :help_default
def config_type
'package'
end
private
def check(val)
unless File.dir?("packages/#{val}")
setup_rb_error "config: no such package: #{val}"
end
val
end
end
class MetaConfigEnvironment
def initialize(config, installer)
@config = config
@installer = installer
end
def config_names
@config.names
end
def config?(name)
@config.key?(name)
end
def bool_config?(name)
@config.lookup(name).config_type == 'bool'
end
def path_config?(name)
@config.lookup(name).config_type == 'path'
end
def value_config?(name)
@config.lookup(name).config_type != 'exec'
end
def add_config(item)
@config.add item
end
def add_bool_config(name, default, desc)
@config.add BoolItem.new(name, 'yes/no', default ? 'yes' : 'no', desc)
end
def add_path_config(name, default, desc)
@config.add PathItem.new(name, 'path', default, desc)
end
def set_config_default(name, default)
@config.lookup(name).default = default
end
def remove_config(name)
@config.remove(name)
end
# For only multipackage
def packages
raise '[setup.rb fatal] multi-package metaconfig API packages() called for single-package; contact application package vendor' unless @installer
@installer.packages
end
# For only multipackage
def declare_packages(list)
raise '[setup.rb fatal] multi-package metaconfig API declare_packages() called for single-package; contact application package vendor' unless @installer
@installer.packages = list
end
end
end # class ConfigTable
# This module requires: #verbose?, #no_harm?
module FileOperations
def mkdir_p(dirname, prefix = nil)
dirname = prefix + File.expand_path(dirname) if prefix
$stderr.puts "mkdir -p #{dirname}" if verbose?
return if no_harm?
# Does not check '/', it's too abnormal.
dirs = File.expand_path(dirname).split(%r<(?=/)>)
if /\A[a-z]:\z/i =~ dirs[0]
disk = dirs.shift
dirs[0] = disk + dirs[0]
end
dirs.each_index do |idx|
path = dirs[0..idx].join('')
Dir.mkdir path unless File.dir?(path)
end
end
def rm_f(path)
$stderr.puts "rm -f #{path}" if verbose?
return if no_harm?
force_remove_file path
end
def rm_rf(path)
$stderr.puts "rm -rf #{path}" if verbose?
return if no_harm?
remove_tree path
end
def remove_tree(path)
if File.symlink?(path)
remove_file path
elsif File.dir?(path)
remove_tree0 path
else
force_remove_file path
end
end
def remove_tree0(path)
Dir.foreach(path) do |ent|
next if ent == '.'
next if ent == '..'
entpath = "#{path}/#{ent}"
if File.symlink?(entpath)
remove_file entpath
elsif File.dir?(entpath)
remove_tree0 entpath
else
force_remove_file entpath
end
end
begin
Dir.rmdir path
rescue Errno::ENOTEMPTY
# directory may not be empty
end
end
def move_file(src, dest)
force_remove_file dest
begin
File.rename src, dest
rescue
File.open(dest, 'wb') {|f|
f.write File.binread(src)
}
File.chmod File.stat(src).mode, dest
File.unlink src
end
end
def force_remove_file(path)
begin
remove_file path
rescue
end
end
def remove_file(path)
File.chmod 0777, path
File.unlink path
end
def install(from, dest, mode, prefix = nil)
$stderr.puts "install #{from} #{dest}" if verbose?
return if no_harm?
realdest = prefix ? prefix + File.expand_path(dest) : dest
realdest = File.join(realdest, File.basename(from)) if File.dir?(realdest)
str = File.binread(from)
if diff?(str, realdest)
verbose_off {
rm_f realdest if File.exist?(realdest)
}
File.open(realdest, 'wb') {|f|
f.write str
}
File.chmod mode, realdest
File.open("#{objdir_root()}/InstalledFiles", 'a') {|f|
if prefix
f.puts realdest.sub(prefix, '')
else
f.puts realdest
end
}
end
end
def diff?(new_content, path)
return true unless File.exist?(path)
new_content != File.binread(path)
end
def command(*args)
$stderr.puts args.join(' ') if verbose?
system(*args) or raise RuntimeError,
"system(#{args.map{|a| a.inspect }.join(' ')}) failed"
end
def ruby(*args)
command config('rubyprog'), *args
end
def make(task = nil)
command(*[config('makeprog'), task].compact)
end
def extdir?(dir)
File.exist?("#{dir}/MANIFEST") or File.exist?("#{dir}/extconf.rb")
end
def files_of(dir)
Dir.open(dir) {|d|
return d.select {|ent| File.file?("#{dir}/#{ent}") }
}
end
DIR_REJECT = %w( . .. CVS SCCS RCS CVS.adm .svn )
def directories_of(dir)
Dir.open(dir) {|d|
return d.select {|ent| File.dir?("#{dir}/#{ent}") } - DIR_REJECT
}
end
end
# This module requires: #srcdir_root, #objdir_root, #relpath
module HookScriptAPI
def get_config(key)
@config[key]
end
alias config get_config
# obsolete: use metaconfig to change configuration
def set_config(key, val)
@config[key] = val
end
#
# srcdir/objdir (works only in the package directory)
#
def curr_srcdir
"#{srcdir_root()}/#{relpath()}"
end
def curr_objdir
"#{objdir_root()}/#{relpath()}"
end
def srcfile(path)
"#{curr_srcdir()}/#{path}"
end
def srcexist?(path)
File.exist?(srcfile(path))
end
def srcdirectory?(path)
File.dir?(srcfile(path))
end
def srcfile?(path)
File.file?(srcfile(path))
end
def srcentries(path = '.')
Dir.open("#{curr_srcdir()}/#{path}") {|d|
return d.to_a - %w(. ..)
}
end
def srcfiles(path = '.')
srcentries(path).select {|fname|
File.file?(File.join(curr_srcdir(), path, fname))
}
end
def srcdirectories(path = '.')
srcentries(path).select {|fname|
File.dir?(File.join(curr_srcdir(), path, fname))
}
end
end
class ToplevelInstaller
Version = '3.4.1'
Copyright = 'Copyright (c) 2000-2005 Minero Aoki'
TASKS = [
[ 'all', 'do config, setup, then install' ],
[ 'config', 'saves your configurations' ],
[ 'show', 'shows current configuration' ],
[ 'setup', 'compiles ruby extentions and others' ],
[ 'install', 'installs files' ],
[ 'test', 'run all tests in test/' ],
[ 'clean', "does `make clean' for each extention" ],
[ 'distclean',"does `make distclean' for each extention" ]
]
def ToplevelInstaller.invoke
config = ConfigTable.new(load_rbconfig())
config.load_standard_entries
config.load_multipackage_entries if multipackage?
config.fixup
klass = (multipackage?() ? ToplevelInstallerMulti : ToplevelInstaller)
klass.new(File.dirname($0), config).invoke
end
def ToplevelInstaller.multipackage?
File.dir?(File.dirname($0) + '/packages')
end
def ToplevelInstaller.load_rbconfig
if arg = ARGV.detect {|arg| /\A--rbconfig=/ =~ arg }
ARGV.delete(arg)
load File.expand_path(arg.split(/=/, 2)[1])
$".push 'rbconfig.rb'
else
require 'rbconfig'
end
::Config::CONFIG
end
def initialize(ardir_root, config)
@ardir = File.expand_path(ardir_root)
@config = config
# cache
@valid_task_re = nil
end
def config(key)
@config[key]
end
def inspect
"#<#{self.class} #{__id__()}>"
end
def invoke
run_metaconfigs
case task = parsearg_global()
when nil, 'all'
parsearg_config
init_installers
exec_config
exec_setup
exec_install
else
case task
when 'config', 'test'
;
when 'clean', 'distclean'
@config.load_savefile if File.exist?(@config.savefile)
else
@config.load_savefile
end
__send__ "parsearg_#{task}"
init_installers
__send__ "exec_#{task}"
end
end
def run_metaconfigs
@config.load_script "#{@ardir}/metaconfig"
end
def init_installers
@installer = Installer.new(@config, @ardir, File.expand_path('.'))
end
#
# Hook Script API bases
#
def srcdir_root
@ardir
end
def objdir_root
'.'
end
def relpath
'.'
end
#
# Option Parsing
#
def parsearg_global
while arg = ARGV.shift
case arg
when /\A\w+\z/
setup_rb_error "invalid task: #{arg}" unless valid_task?(arg)
return arg
when '-q', '--quiet'
@config.verbose = false
when '--verbose'
@config.verbose = true
when '--help'
print_usage $stdout
exit 0
when '--version'
puts "#{File.basename($0)} version #{Version}"
exit 0
when '--copyright'
puts Copyright
exit 0
else
setup_rb_error "unknown global option '#{arg}'"
end
end
nil
end
def valid_task?(t)
valid_task_re() =~ t
end
def valid_task_re
@valid_task_re ||= /\A(?:#{TASKS.map {|task,desc| task }.join('|')})\z/
end
def parsearg_no_options
unless ARGV.empty?
task = caller(0).first.slice(%r<`parsearg_(\w+)'>, 1)
setup_rb_error "#{task}: unknown options: #{ARGV.join(' ')}"
end
end
alias parsearg_show parsearg_no_options
alias parsearg_setup parsearg_no_options
alias parsearg_test parsearg_no_options
alias parsearg_clean parsearg_no_options
alias parsearg_distclean parsearg_no_options
def parsearg_config
evalopt = []
set = []
@config.config_opt = []
while i = ARGV.shift
if /\A--?\z/ =~ i
@config.config_opt = ARGV.dup
break
end
name, value = *@config.parse_opt(i)
if @config.value_config?(name)
@config[name] = value
else
evalopt.push [name, value]
end
set.push name
end
evalopt.each do |name, value|
@config.lookup(name).evaluate value, @config
end
# Check if configuration is valid
set.each do |n|
@config[n] if @config.value_config?(n)
end
end
def parsearg_install
@config.no_harm = false
@config.install_prefix = ''
while a = ARGV.shift
case a
when '--no-harm'
@config.no_harm = true
when /\A--prefix=/
path = a.split(/=/, 2)[1]
path = File.expand_path(path) unless path[0,1] == '/'
@config.install_prefix = path
else
setup_rb_error "install: unknown option #{a}"
end
end
end
def print_usage(out)
out.puts 'Typical Installation Procedure:'
out.puts " $ ruby #{File.basename $0} config"
out.puts " $ ruby #{File.basename $0} setup"
out.puts " # ruby #{File.basename $0} install (may require root privilege)"
out.puts
out.puts 'Detailed Usage:'
out.puts " ruby #{File.basename $0} <global option>"
out.puts " ruby #{File.basename $0} [<global options>] <task> [<task options>]"
fmt = " %-24s %s\n"
out.puts
out.puts 'Global options:'
out.printf fmt, '-q,--quiet', 'suppress message outputs'
out.printf fmt, ' --verbose', 'output messages verbosely'
out.printf fmt, ' --help', 'print this message'
out.printf fmt, ' --version', 'print version and quit'
out.printf fmt, ' --copyright', 'print copyright and quit'
out.puts
out.puts 'Tasks:'
TASKS.each do |name, desc|
out.printf fmt, name, desc
end
fmt = " %-24s %s [%s]\n"
out.puts
out.puts 'Options for CONFIG or ALL:'
@config.each do |item|
out.printf fmt, item.help_opt, item.description, item.help_default
end
out.printf fmt, '--rbconfig=path', 'rbconfig.rb to load',"running ruby's"
out.puts
out.puts 'Options for INSTALL:'
out.printf fmt, '--no-harm', 'only display what to do if given', 'off'
out.printf fmt, '--prefix=path', 'install path prefix', ''
out.puts
end
#
# Task Handlers
#
def exec_config
@installer.exec_config
@config.save # must be final
end
def exec_setup
@installer.exec_setup
end
def exec_install
@installer.exec_install
end
def exec_test
@installer.exec_test
end
def exec_show
@config.each do |i|
printf "%-20s %s\n", i.name, i.value if i.value?
end
end
def exec_clean
@installer.exec_clean
end
def exec_distclean
@installer.exec_distclean
end
end # class ToplevelInstaller
class ToplevelInstallerMulti < ToplevelInstaller
include FileOperations
def initialize(ardir_root, config)
super
@packages = directories_of("#{@ardir}/packages")
raise 'no package exists' if @packages.empty?
@root_installer = Installer.new(@config, @ardir, File.expand_path('.'))
end
def run_metaconfigs
@config.load_script "#{@ardir}/metaconfig", self
@packages.each do |name|
@config.load_script "#{@ardir}/packages/#{name}/metaconfig"
end
end
attr_reader :packages
def packages=(list)
raise 'package list is empty' if list.empty?
list.each do |name|
raise "directory packages/#{name} does not exist"\
unless File.dir?("#{@ardir}/packages/#{name}")
end
@packages = list
end
def init_installers
@installers = {}
@packages.each do |pack|
@installers[pack] = Installer.new(@config,
"#{@ardir}/packages/#{pack}",
"packages/#{pack}")
end
with = extract_selection(config('with'))
without = extract_selection(config('without'))
@selected = @installers.keys.select {|name|
(with.empty? or with.include?(name)) \
and not without.include?(name)
}
end
def extract_selection(list)
a = list.split(/,/)
a.each do |name|
setup_rb_error "no such package: #{name}" unless @installers.key?(name)
end
a
end
def print_usage(f)
super
f.puts 'Inluded packages:'
f.puts ' ' + @packages.sort.join(' ')
f.puts
end
#
# Task Handlers
#
def exec_config
run_hook 'pre-config'
each_selected_installers {|inst| inst.exec_config }
run_hook 'post-config'
@config.save # must be final
end
def exec_setup
run_hook 'pre-setup'
each_selected_installers {|inst| inst.exec_setup }
run_hook 'post-setup'
end
def exec_install
run_hook 'pre-install'
each_selected_installers {|inst| inst.exec_install }
run_hook 'post-install'
end
def exec_test
run_hook 'pre-test'
each_selected_installers {|inst| inst.exec_test }
run_hook 'post-test'
end
def exec_clean
rm_f @config.savefile
run_hook 'pre-clean'
each_selected_installers {|inst| inst.exec_clean }
run_hook 'post-clean'
end
def exec_distclean
rm_f @config.savefile
run_hook 'pre-distclean'
each_selected_installers {|inst| inst.exec_distclean }
run_hook 'post-distclean'
end
#
# lib
#
def each_selected_installers
Dir.mkdir 'packages' unless File.dir?('packages')
@selected.each do |pack|
$stderr.puts "Processing the package `#{pack}' ..." if verbose?
Dir.mkdir "packages/#{pack}" unless File.dir?("packages/#{pack}")
Dir.chdir "packages/#{pack}"
yield @installers[pack]
Dir.chdir '../..'
end
end
def run_hook(id)
@root_installer.run_hook id
end
# module FileOperations requires this
def verbose?
@config.verbose?
end
# module FileOperations requires this
def no_harm?
@config.no_harm?
end
end # class ToplevelInstallerMulti
class Installer
FILETYPES = %w( bin lib ext data conf man )
include FileOperations
include HookScriptAPI
def initialize(config, srcroot, objroot)
@config = config
@srcdir = File.expand_path(srcroot)
@objdir = File.expand_path(objroot)
@currdir = '.'
end
def inspect
"#<#{self.class} #{File.basename(@srcdir)}>"
end
def noop(rel)
end
#
# Hook Script API base methods
#
def srcdir_root
@srcdir
end
def objdir_root
@objdir
end
def relpath
@currdir
end
#
# Config Access
#
# module FileOperations requires this
def verbose?
@config.verbose?
end
# module FileOperations requires this
def no_harm?
@config.no_harm?
end
def verbose_off
begin
save, @config.verbose = @config.verbose?, false
yield
ensure
@config.verbose = save
end
end
#
# TASK config
#
def exec_config
exec_task_traverse 'config'
end
alias config_dir_bin noop
alias config_dir_lib noop
def config_dir_ext(rel)
extconf if extdir?(curr_srcdir())
end
alias config_dir_data noop
alias config_dir_conf noop
alias config_dir_man noop
def extconf
ruby "#{curr_srcdir()}/extconf.rb", *@config.config_opt
end
#
# TASK setup
#
def exec_setup
exec_task_traverse 'setup'
end
def setup_dir_bin(rel)
files_of(curr_srcdir()).each do |fname|
update_shebang_line "#{curr_srcdir()}/#{fname}"
end
end
alias setup_dir_lib noop
def setup_dir_ext(rel)
make if extdir?(curr_srcdir()) and File.exist?("#{curr_srcdir()}/Makefile")
end
alias setup_dir_data noop
alias setup_dir_conf noop
alias setup_dir_man noop
def update_shebang_line(path)
return if no_harm?
return if config('shebang') == 'never'
old = Shebang.load(path)
if old
$stderr.puts "warning: #{path}: Shebang line includes too many args. It is not portable and your program may not work." if old.args.size > 1
new = new_shebang(old)
return if new.to_s == old.to_s
else
return unless config('shebang') == 'all'
new = Shebang.new(config('rubypath'))
end
$stderr.puts "updating shebang: #{File.basename(path)}" if verbose?
open_atomic_writer(path) {|output|
File.open(path, 'rb') {|f|
f.gets if old # discard
output.puts new.to_s
output.print f.read
}
}
end
def new_shebang(old)
if /\Aruby/ =~ File.basename(old.cmd)
Shebang.new(config('rubypath'), old.args)
elsif File.basename(old.cmd) == 'env' and old.args.first == 'ruby'
puts "Skipping shebang rename"
# We don't want this to happen anymore, it doesn't make sense
# Shebang.new(config('rubypath'), old.args[1..-1])
old
else
return old unless config('shebang') == 'all'
Shebang.new(config('rubypath'))
end
end
def open_atomic_writer(path, &block)
tmpfile = File.basename(path) + '.tmp'
begin
File.open(tmpfile, 'wb', &block)
File.rename tmpfile, File.basename(path)
ensure
File.unlink tmpfile if File.exist?(tmpfile)
end
end
class Shebang
def Shebang.load(path)
line = nil
File.open(path) {|f|
line = f.gets
}
return nil unless /\A#!/ =~ line
parse(line)
end
def Shebang.parse(line)
cmd, *args = *line.strip.sub(/\A\#!/, '').split(' ')
new(cmd, args)
end
def initialize(cmd, args = [])
@cmd = cmd
@args = args
end
attr_reader :cmd
attr_reader :args
def to_s
"#! #{@cmd}" + (@args.empty? ? '' : " #{@args.join(' ')}")
end
end
#
# TASK install
#
def exec_install
rm_f 'InstalledFiles'
exec_task_traverse 'install'
end
def install_dir_bin(rel)
install_files targetfiles(), "#{config('bindir')}/#{rel}", 0755
end
def install_dir_lib(rel)
install_files libfiles(), "#{config('rbdir')}/#{rel}", 0644
end
def install_dir_ext(rel)
return unless extdir?(curr_srcdir())
install_files rubyextentions('.'),
"#{config('sodir')}/#{File.dirname(rel)}",
0555
end
def install_dir_data(rel)
install_files targetfiles(), "#{config('datadir')}/#{rel}", 0644
end
def install_dir_conf(rel)
# FIXME: should not remove current config files
# (rename previous file to .old/.org)
install_files targetfiles(), "#{config('sysconfdir')}/#{rel}", 0644
end
def install_dir_man(rel)
install_files targetfiles(), "#{config('mandir')}/#{rel}", 0644
end
def install_files(list, dest, mode)
mkdir_p dest, @config.install_prefix
list.each do |fname|
install fname, dest, mode, @config.install_prefix
end
end
def libfiles
glob_reject(%w(*.y *.output), targetfiles())
end
def rubyextentions(dir)
ents = glob_select("*.#{@config.dllext}", targetfiles())
if ents.empty?
setup_rb_error "no ruby extention exists: 'ruby #{$0} setup' first"
end
ents
end
def targetfiles
mapdir(existfiles() - hookfiles())
end
def mapdir(ents)
ents.map {|ent|
if File.exist?(ent)
then ent # objdir
else "#{curr_srcdir()}/#{ent}" # srcdir
end
}
end
# picked up many entries from cvs-1.11.1/src/ignore.c
JUNK_FILES = %w(
core RCSLOG tags TAGS .make.state
.nse_depinfo #* .#* cvslog.* ,* .del-* *.olb
*~ *.old *.bak *.BAK *.orig *.rej _$* *$
*.org *.in .*
)
def existfiles
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | true |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/functional_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/functional_test.rb | require File.dirname(__FILE__) + '/test_helper'
=begin
Updating functional testdata automatically is DANGEROUS, so I do manually.
== update functional test
cd ~/src/rcov/test
rcov="ruby ../bin/rcov -I../lib:../ext/rcovrt -o expected_coverage"
$rcov -a sample_04.rb
$rcov sample_04.rb
$rcov --gcc --include-file=sample --exclude=rcov sample_04.rb > expected_coverage/gcc-text.out
cp sample_05-old.rb sample_05.rb
$rcov --no-html --gcc --include-file=sample --exclude=rcov --save=coverage.info sample_05.rb > expected_coverage/diff-gcc-original.out
cp sample_05-new.rb sample_05.rb
$rcov --no-html --gcc -D --include-file=sample --exclude=rcov sample_05.rb > expected_coverage/diff-gcc-diff.out
$rcov --no-html -D --include-file=sample --exclude=rcov sample_05.rb > expected_coverage/diff.out
$rcov --no-html --no-color -D --include-file=sample --exclude=rcov sample_05.rb > expected_coverage/diff-no-color.out
$rcov --no-html --gcc --include-file=sample --exclude=rcov sample_05.rb > expected_coverage/diff-gcc-all.out
=end
class TestFunctional < Test::Unit::TestCase
@@dir = Pathname(__FILE__).expand_path.dirname
def strip_variable_sections(str)
str.sub(/Generated on.+$/, '').sub(/Generated using the.+$/, '').squeeze("\n")
end
def cmp(file)
content = lambda{|dir| strip_variable_sections(File.read(@@dir+dir+file))}
assert_equal(content["expected_coverage"], content["actual_coverage"])
end
def with_testdir(&block)
Dir.chdir(@@dir, &block)
end
def run_rcov(opts, script="assets/sample_04.rb", opts_tail="")
rcov = @@dir+"../bin/rcov"
ruby_opts = "-I../lib:../ext/rcovrt"
ruby = "ruby"
ruby = "jruby" if RUBY_PLATFORM =~ /java/
with_testdir do
`cd #{@@dir}; #{ruby} #{ruby_opts} #{rcov} #{opts} -o actual_coverage #{script} #{opts_tail}`
yield if block_given?
end
end
def test_annotation
run_rcov("-a") do
cmp "../assets/sample_04.rb"
cmp "../assets/sample_03.rb"
end
end
@@selection = "--include-file=sample --exclude=rcov"
def test_text_gcc
run_rcov("--gcc #{@@selection}", "assets/sample_04.rb", "> actual_coverage/gcc-text.out") do
cmp "gcc-text.out"
end
end
def test_diff
with_testdir { FileUtils.cp "assets/sample_05-old.rb", "assets/sample_05.rb" }
run_rcov("--no-html --gcc #{@@selection} --save=coverage.info", "assets/sample_05.rb", "> actual_coverage/diff-gcc-original.out") do
cmp "diff-gcc-original.out"
end
with_testdir { FileUtils.cp "assets/sample_05-new.rb", "assets/sample_05.rb" }
run_rcov("--no-html -D --gcc #{@@selection}", "assets/sample_05.rb", "> actual_coverage/diff-gcc-diff.out") do
cmp "diff-gcc-diff.out"
end
run_rcov("--no-html -D #{@@selection}", "assets/sample_05.rb", "> actual_coverage/diff.out") do
cmp "diff.out"
end
run_rcov("--no-html --no-color -D #{@@selection}", "assets/sample_05.rb", "> actual_coverage/diff-no-color.out") do
cmp "diff-no-color.out"
end
run_rcov("--no-html --gcc #{@@selection}", "assets/sample_05.rb", "> actual_coverage/diff-gcc-all.out") do
cmp "diff-gcc-all.out"
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/file_statistics_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/file_statistics_test.rb | require File.dirname(__FILE__) + '/test_helper'
class TestFileStatistics < Test::Unit::TestCase
def test_trailing_end_is_inferred
verify_everything_marked "trailing end", <<-EOF
1 class X
1 def foo
2 "foo"
0 end
0 end
EOF
verify_everything_marked "trailing end with comments", <<-EOF
1 class X
1 def foo
2 "foo"
0 end
0 # foo bar
0 =begin
0 ....
0 =end
0 end
EOF
end
def test_begin_ensure_else_case_are_inferred
verify_everything_marked "begin ensure else case", <<-EOF
0 begin
# bleh
2 puts a
0 begin
2 raise "foo"
0 rescue Exception => e
2 puts b
0 ensure
2 puts c
0 end
2 if a()
1 b
0 else
1 c
0 end
0 case
2 when bar =~ /foo/
1 puts "bar"
0 else
1 puts "baz"
0 end
0 end
EOF
end
def test_rescue_is_inferred
verify_everything_marked "rescue", <<-EOF
0 begin
1 foo
0 rescue
1 puts "bar"
0 end
EOF
end
def test_code_metrics_are_computed_correctly
lines, coverage, counts = code_info_from_string <<-EOF
1 a = 1
0 # this is a comment
1 if bar
0 b = 2
0 end
0 =begin
0 this too
0 bleh
0 =end
0 puts <<EOF
0 bleh
0 EOF
3 c.times{ i += 1}
EOF
sf = Rcov::FileStatistics.new("metrics", lines, counts)
assert_in_delta(0.307, sf.total_coverage, 0.01)
assert_in_delta(0.375, sf.code_coverage, 0.01)
assert_equal(8, sf.num_code_lines)
assert_equal(13, sf.num_lines)
assert_equal([true, :inferred, true, false, false, false, false, false,
false, false, false, false, true], sf.coverage.to_a)
end
def test_merge
lines, coverage, counts = code_info_from_string <<-EOF
1 a = 1
1 if bar
0 b = 2
0 end
1 puts <<EOF
0 bleh
0 EOF
3 c.times{ i += 1}
EOF
sf = Rcov::FileStatistics.new("merge", lines, counts)
lines, coverage, counts = code_info_from_string <<-EOF
1 a = 1
1 if bar
1 b = 2
0 end
1 puts <<EOF
0 bleh
0 EOF
10 c.times{ i += 1}
EOF
sf2 = Rcov::FileStatistics.new("merge", lines, counts)
expected = [true, true, true, :inferred, true, :inferred, :inferred, true]
assert_equal(expected, sf2.coverage.to_a)
sf.merge(sf2.lines, sf2.coverage, sf2.counts)
assert_equal(expected, sf.coverage.to_a)
assert_equal([2, 2, 1, 0, 2, 0, 0, 13], sf.counts)
end
def test_last_comment_block_is_marked
verify_everything_marked "last comment block", <<-EOF
1 a = 1
1 b = 1
0 # foo
0 # bar baz
EOF
verify_everything_marked "last comment block, =begin/=end", <<-EOF
1 a = 1
2 b = 1
0 # fooo
0 =begin
0 bar baz
0 =end
EOF
verify_everything_marked "last comment block, __END__", <<-EOF
1 a = 1
2 b = 1
0 # fooo
0 =begin
0 bar baz
0 =end
__END__
EOF
end
def test_heredocs_basic
verify_everything_marked "heredocs-basic.rb", <<-EOF
1 puts 1 + 1
1 puts <<HEREDOC
0 first line of the heredoc
0 not marked
0 but should be
0 HEREDOC
1 puts 1
EOF
verify_everything_marked "squote", <<-EOF
1 puts <<'HEREDOC'
0 first line of the heredoc
0 HEREDOC
EOF
verify_everything_marked "dquote", <<-EOF
1 puts <<"HEREDOC"
0 first line of the heredoc
0 HEREDOC
EOF
verify_everything_marked "xquote", <<-EOF
1 puts <<`HEREDOC`
0 first line of the heredoc
0 HEREDOC
EOF
verify_everything_marked "stuff-after-heredoc", <<-EOF
1 full_message = build_message(msg, <<EOT, object1, object2)
0 <?> and <?> do not contain the same elements
0 EOT
EOF
end
def test_heredocs_multiple
verify_everything_marked "multiple-unquoted", <<-EOF
1 puts <<HEREDOC, <<HERE2
0 first line of the heredoc
0 HEREDOC
0 second heredoc
0 HERE2
EOF
verify_everything_marked "multiple-quoted", <<-EOF
1 puts <<'HEREDOC', <<`HERE2`, <<"HERE3"
0 first line of the heredoc
0 HEREDOC
0 second heredoc
0 HERE2
0 dsfdsfffd
0 HERE3
EOF
verify_everything_marked "same-identifier", <<-EOF
1 puts <<H, <<H
0 foo
0 H
0 bar
0 H
EOF
verify_everything_marked "stuff-after-heredoc", <<-EOF
1 full_message = build_message(msg, <<EOT, object1, object2, <<EOT)
0 <?> and <?> do not contain the same elements
0 EOT
0 <?> and <?> are foo bar baz
0 EOT
EOF
end
def test_ignore_non_heredocs
verify_marked_exactly "bitshift-numeric", [0], <<-EOF
1 puts 1<<2
0 return if foo
0 do_stuff()
0 2
EOF
verify_marked_exactly "bitshift-symbolic", [0], <<-EOF
1 puts 1<<LSHIFT
0 return if bar
0 do_stuff()
0 LSHIFT
EOF
verify_marked_exactly "bitshift-symbolic-multi", 0..3, <<-EOF
1 puts <<EOF, 1<<LSHIFT
0 random text
0 EOF
1 return if bar
0 puts "foo"
0 LSHIFT
EOF
verify_marked_exactly "bitshift-symshift-evil", 0..2, <<-EOF
1 foo = 1
1 puts foo<<CONS
1 return if bar
0 foo + baz
EOF
end
def test_heredocs_with_interpolation_alone_in_method
verify_everything_marked "lonely heredocs with interpolation", <<-'EOS'
1 def to_s
0 <<-EOF
1 #{name}
0 #{street}
0 #{city}, #{state}
0 #{zip}
0 EOF
0 end
EOS
end
def test_handle_multiline_expressions
verify_everything_marked "expression", <<-EOF
1 puts 1, 2.
0 abs +
0 1 -
0 1 *
0 1 /
0 1, 1 <
0 2, 3 >
0 4 %
0 3 &&
0 true ||
0 foo <<
0 bar(
0 baz[
0 {
0 1,2}] =
0 1 )
EOF
verify_everything_marked "boolean expression", <<-EOF
1 x = (foo and
0 bar) or
0 baz
EOF
verify_marked_exactly "code blocks", [0, 3, 6], <<-EOF
1 x = foo do # stuff
0 baz
0 end
1 bar do |x|
0 baz
0 end
1 bar {|a, b| # bleh | +1
0 baz
0 }
EOF
verify_everything_marked "escaped linebreaks", <<-EOF
1 def t2
0 puts \\
1 "foo"
0 end
0 end
EOF
end
def test_handle_multiline_blocks_first_not_marked
verify_everything_marked "multiline block first not marked", <<-'EOF'
1 blah = Array.new
1 10.times do
0 blah << lambda do |f|
1 puts "I should say #{f}!"
0 end
0 end
EOF
end
def test_handle_multiline_blocks_last_line_not_marked
verify_everything_marked "multiline block last not marked", <<-'EOF'
1 blee = [1, 2, 3]
0 blee.map! do |e|
1 [e, e]
0 end.flatten!
1 p blee
EOF
end
def test_handle_multiline_data_with_trailing_stuff_on_last_line
verify_everything_marked "multiline data hash", <<-'EOF'
1 @review = Review.new({
0 :product_id => params[:id],
0 :user => current_user
0 }.merge(params[:review])) #red
1 @review.save
EOF
end
def test_handle_multiline_expression_1st_line_ends_in_block_header
# excerpt taken from mongrel/handlers.rb
verify_everything_marked "multiline with block starting on 1st", <<-EOF
1 uris = listener.classifier.handler_map
0 results << table("handlers", uris.map {|uri,handlers|
1 [uri,
0 "<pre>" +
1 handlers.map {|h| h.class.to_s }.join("\n") +
0 "</pre>"
0 ]
1 })
EOF
end
def test_handle_multiple_block_end_delimiters_in_empty_line
verify_everything_marked "multiline with }) delimiter, forward", <<-EOF
1 assert(@c.config == {
0 'host' => 'myhost.tld',
0 'port' => 1234
0 })
EOF
verify_everything_marked "multiline with }) delimiter, backwards", <<-EOF
0 assert(@c.config == {
0 'host' => 'myhost.tld',
0 'port' => 1234
1 })
EOF
end
STRING_DELIMITER_PAIRS = [
%w-%{ }-, %w-%q{ }-, %w-%Q{ }-, %w{%[ ]}, %w{%q[ ]},
%w{%( )}, %w{%Q( )}, %w{%Q[ ]}, %w{%q! !}, %w{%! !},
]
def test_multiline_strings_basic
STRING_DELIMITER_PAIRS.each do |s_delim, e_delim|
verify_everything_marked "multiline strings, basic #{s_delim}", <<-EOF
1 PATTERN_TEXT = #{s_delim}
0 NUMBERS = 'one|two|three|four|five'
0 ON_OFF = 'on|off'
0 #{e_delim}
EOF
end
STRING_DELIMITER_PAIRS.each do |s_delim, e_delim|
verify_marked_exactly "multiline strings, escaped #{s_delim}", [0], <<-EOF
1 PATTERN_TEXT = #{s_delim} foooo bar baz \\#{e_delim} baz #{e_delim}
0 NUMBERS = 'one|two|three|four|five'
0 ON_OFF = 'on|off'
EOF
verify_marked_exactly "multiline strings, #{s_delim}, interpolation",
[0], <<-EOF
1 PATTERN_TEXT = #{s_delim} \#{#{s_delim} foo #{e_delim}} \\#{e_delim} baz #{e_delim}
0 NUMBERS = 'one|two|three|four|five'
0 ON_OFF = 'on|off'
EOF
end
end
def test_multiline_strings_escaped_delimiter
STRING_DELIMITER_PAIRS.each do |s_delim, e_delim|
verify_everything_marked "multiline, escaped #{s_delim}", <<-EOF
1 PATTERN_TEXT = #{s_delim} foo \\#{e_delim}
0 NUMBERS = 'one|two|three|four|five'
0 ON_OFF = 'on|off'
0 #{e_delim}
EOF
end
end
def test_handle_multiline_expressions_with_heredocs
verify_everything_marked "multiline and heredocs", <<-EOF
1 puts <<EOF +
0 testing
0 one two three
0 EOF
0 somevar
EOF
end
def test_begin_end_comment_blocks
verify_everything_marked "=begin/=end", <<-EOF
1 x = foo
0 =begin
0 return if bar(x)
0 =end
1 y = 1
EOF
end
def test_is_code_p
verify_is_code "basic", [true] + [false] * 5 + [true], <<-EOF
1 x = foo
0 =begin
0 return if bar
0 =end
0 # foo
0 # bar
1 y = 1
EOF
end
def test_is_code_p_tricky_heredocs
verify_is_code "tricky heredocs", [true] * 4, <<-EOF
2 x = foo <<EOF and return
0 =begin
0 EOF
0 z = x + 1
EOF
end
def verify_is_code(testname, is_code_arr, str)
lines, coverage, counts = code_info_from_string str
sf = Rcov::FileStatistics.new(testname, lines, counts)
is_code_arr.each_with_index do |val,i|
assert_equal(val, sf.is_code?(i),
"Unable to detect =begin comments properly: #{lines[i].inspect}")
end
end
def verify_marked_exactly(testname, marked_indices, str)
lines, coverage, counts = code_info_from_string(str)
sf = Rcov::FileStatistics.new(testname, lines, counts)
lines.size.times do |i|
if marked_indices.include? i
assert(sf.coverage[i], "Test #{testname}; " +
"line should have been marked: #{lines[i].inspect}.")
else
assert(!sf.coverage[i], "Test #{testname}; " +
"line should not have been marked: #{lines[i].inspect}.")
end
end
end
def verify_everything_marked(testname, str)
verify_marked_exactly(testname, (0...str.size).to_a, str)
end
def code_info_from_string(str)
str = str.gsub(/^\s*/,"")
[ str.lines.map{|line| line.sub(/^\d+ /, "") },
str.lines.map{|line| line[/^\d+/].to_i > 0},
str.lines.map{|line| line[/^\d+/].to_i } ]
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/call_site_analyzer_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/call_site_analyzer_test.rb | require File.dirname(__FILE__) + '/test_helper'
class TestCallSiteAnalyzer < Test::Unit::TestCase
sample_file = File.join(File.dirname(__FILE__), "assets/sample_03.rb")
load sample_file
def setup
@a = Rcov::CallSiteAnalyzer.new
@o = Rcov::Test::Temporary::Sample03.new
end
def verify_callsites_equal(expected, actual)
callsites = expected.inject({}) do |s,(backtrace, count)|
unless $".any?{|x| %r{\brcovrt\b} =~ x}
backtrace = backtrace.map{|_, mid, file, line| [nil, mid, file, line] }
end
backtrace[0][2] = File.expand_path(backtrace[0][2])
s[Rcov::CallSiteAnalyzer::CallSite.new(backtrace)] = count
s
end
act_callsites = actual.inject({}) do |s, (key, value)|
#wow thats obtuse. In a callsite we have an array of arrays. We have to deep copy them because
# if we muck with the actual backtrace it messes things up for accumulation type tests.
# we have to muck with backtrace so that we can normalize file names (it's an issue between MRI and JRuby)
backtrace = key.backtrace.inject([]) {|y, val| y << val.inject([]) {|z, v2| z<< v2}}
backtrace[0][2] = File.expand_path(key.backtrace[0][2])
s[Rcov::CallSiteAnalyzer::CallSite.new(backtrace)] = value
s
end
assert_equal(callsites.to_s, act_callsites.to_s)
end
def verify_defsite_equal(expected, actual)
defsite = Rcov::CallSiteAnalyzer::DefSite.new(*expected)
defsite.file = File.expand_path defsite.file
actual.file = File.expand_path actual.file
assert_equal(defsite.to_s, actual.to_s)
end
def test_callsite_compute_raw_difference
src = [
{ ["Foo", "foo"] => {"bar" => 1},
["Foo", "bar"] => {"baz" => 10} },
{ ["Foo", "foo"] => ["foo.rb", 10] }
]
dst = [
{ ["Foo", "foo"] => {"bar" => 1, "fubar" => 10},
["Foo", "baz"] => {"baz" => 10} },
{ ["Foo", "foo"] => ["fooredef.rb", 10],
["Foo", "baz"] => ["foo.rb", 20]}
]
expected = [
{ ["Foo", "foo"] => {"fubar" => 10},
["Foo", "baz"] => {"baz" => 10} },
{ ["Foo", "foo"] => ["fooredef.rb", 10],
["Foo", "baz"] => ["foo.rb", 20] }
]
assert_equal(expected,
@a.instance_eval{ compute_raw_data_difference(src, dst) } )
end
def test_return_values_when_no_match
@a.run_hooked{ @o.f1 }
assert_equal(nil, @a.defsite("Foobar#bogus"))
assert_equal(nil, @a.defsite("Foobar", "bogus"))
assert_equal(nil, @a.callsites("Foobar", "bogus"))
assert_equal(nil, @a.callsites("Foobar.bogus"))
assert_equal(nil, @a.callsites("<Class:Foobar>", "bogus"))
end
def test_basic_defsite_recording
@a.run_hooked{ @o.f1 }
verify_defsite_equal(["./test/assets/sample_03.rb", 3], @a.defsite("Rcov::Test::Temporary::Sample03", "f1"))
verify_defsite_equal(["./test/assets/sample_03.rb", 7], @a.defsite("Rcov::Test::Temporary::Sample03", "f2"))
verify_defsite_equal(["./test/assets/sample_03.rb", 7], @a.defsite("Rcov::Test::Temporary::Sample03#f2"))
end
def test_basic_callsite_recording
@a.run_hooked{ @o.f1 }
assert(@a.analyzed_classes.include?("Rcov::Test::Temporary::Sample03"))
assert_equal(%w[f1 f2], @a.analyzed_methods("Rcov::Test::Temporary::Sample03"))
verify_callsites_equal({[[Rcov::Test::Temporary::Sample03, :f1, "./test/assets/sample_03.rb", 4]] => 10}, @a.callsites("Rcov::Test::Temporary::Sample03", "f2"))
verify_callsites_equal({[[Rcov::Test::Temporary::Sample03, :f1, "./test/assets/sample_03.rb", 4]] => 10}, @a.callsites("Rcov::Test::Temporary::Sample03#f2"))
end
def test_basic_callsite_recording_API
@a.run_hooked{ @o.f1 }
assert(@a.analyzed_classes.include?("Rcov::Test::Temporary::Sample03"))
assert_equal(%w[f1 f2], @a.analyzed_methods("Rcov::Test::Temporary::Sample03"))
verify_callsites_equal({[[Rcov::Test::Temporary::Sample03, :f1, "./test/assets/sample_03.rb", 4]] => 10}, @a.callsites("Rcov::Test::Temporary::Sample03", "f2"))
verify_callsites_equal({[[Rcov::Test::Temporary::Sample03, :f1, "./test/assets/sample_03.rb", 4]] => 10}, @a.callsites("Rcov::Test::Temporary::Sample03", "f2"))
callsites = @a.callsites("Rcov::Test::Temporary::Sample03", "f2")
callsite = callsites.keys[0]
#expand path is used here to compensate for differences between JRuby and MRI
assert_equal(File.expand_path("./test/assets/sample_03.rb"), File.expand_path(callsite.file))
assert_equal(4, callsite.line)
assert_equal(:f1, callsite.calling_method)
end
def test_basic_callsite_recording_with_singleton_classes
@a.run_hooked{ @o.class.g1 }
assert(@a.analyzed_classes.include?("#<Class:Rcov::Test::Temporary::Sample03>"))
assert_equal(%w[g1 g2], @a.analyzed_methods("#<Class:Rcov::Test::Temporary::Sample03>"))
verify_callsites_equal({[[class << Rcov::Test::Temporary::Sample03; self end, :g1, "./test/assets/sample_03.rb", 15]] => 10}, @a.callsites("Rcov::Test::Temporary::Sample03.g2"))
verify_callsites_equal({[[class << Rcov::Test::Temporary::Sample03; self end, :g1, "./test/assets/sample_03.rb", 15]] => 10}, @a.callsites("#<Class:Rcov::Test::Temporary::Sample03>","g2"))
end
def test_differential_callsite_recording
@a.run_hooked{ @o.f1 }
assert(@a.analyzed_classes.include?("Rcov::Test::Temporary::Sample03"))
assert_equal(%w[f1 f2], @a.analyzed_methods("Rcov::Test::Temporary::Sample03"))
verify_callsites_equal({[[Rcov::Test::Temporary::Sample03, :f1, "./test/assets/sample_03.rb", 4]] => 10}, @a.callsites("Rcov::Test::Temporary::Sample03", "f2"))
@a.run_hooked{ @o.f1 }
assert(@a.analyzed_classes.include?("Rcov::Test::Temporary::Sample03"))
assert_equal(%w[f1 f2], @a.analyzed_methods("Rcov::Test::Temporary::Sample03"))
verify_callsites_equal({[[Rcov::Test::Temporary::Sample03, :f1, "./test/assets/sample_03.rb", 4]] => 20}, @a.callsites("Rcov::Test::Temporary::Sample03", "f2"))
@a.run_hooked{ @o.f3 }
assert_equal(%w[f1 f2 f3], @a.analyzed_methods("Rcov::Test::Temporary::Sample03"))
verify_callsites_equal({[[Rcov::Test::Temporary::Sample03, :f1, "./test/assets/sample_03.rb", 4]] => 120,
[[Rcov::Test::Temporary::Sample03, :f3, "./test/assets/sample_03.rb", 11]] => 100 }, @a.callsites("Rcov::Test::Temporary::Sample03", "f2"))
end
def test_reset
@a.run_hooked do
10.times{ @o.f1 }
@a.reset
@o.f1
end
assert(@a.analyzed_classes.include?("Rcov::Test::Temporary::Sample03"))
assert_equal(%w[f1 f2], @a.analyzed_methods("Rcov::Test::Temporary::Sample03"))
verify_callsites_equal({[[Rcov::Test::Temporary::Sample03, :f1, "./test/assets/sample_03.rb", 4]] => 10}, @a.callsites("Rcov::Test::Temporary::Sample03", "f2"))
end
def test_nested_callsite_recording
a = Rcov::CallSiteAnalyzer.new
b = Rcov::CallSiteAnalyzer.new
a.run_hooked do
b.run_hooked { @o.f1 }
assert(b.analyzed_classes.include?("Rcov::Test::Temporary::Sample03"))
assert_equal(%w[f1 f2], b.analyzed_methods("Rcov::Test::Temporary::Sample03"))
verify_callsites_equal({[[Rcov::Test::Temporary::Sample03, :f1, "./test/assets/sample_03.rb", 4]] => 10}, b.callsites("Rcov::Test::Temporary::Sample03", "f2"))
@o.f1
assert_equal(%w[f1 f2], b.analyzed_methods("Rcov::Test::Temporary::Sample03"))
verify_callsites_equal({[[Rcov::Test::Temporary::Sample03, :f1, "./test/assets/sample_03.rb", 4]] => 10}, b.callsites("Rcov::Test::Temporary::Sample03", "f2"))
assert(a.analyzed_classes.include?("Rcov::Test::Temporary::Sample03"))
assert_equal(%w[f1 f2], a.analyzed_methods("Rcov::Test::Temporary::Sample03"))
verify_callsites_equal({[[Rcov::Test::Temporary::Sample03, :f1, "./test/assets/sample_03.rb", 4]] => 20}, a.callsites("Rcov::Test::Temporary::Sample03", "f2"))
end
b.run_hooked{ @o.f3 }
assert_equal(%w[f1 f2 f3], b.analyzed_methods("Rcov::Test::Temporary::Sample03"))
verify_callsites_equal({[[Rcov::Test::Temporary::Sample03, :f1, "./test/assets/sample_03.rb", 4]] => 110,
[[Rcov::Test::Temporary::Sample03, :f3, "./test/assets/sample_03.rb", 11]]=>100 }, b.callsites("Rcov::Test::Temporary::Sample03", "f2"))
end
def test_expand_name
assert_equal(["Foo", "foo"], @a.instance_eval{ expand_name("Foo#foo") })
assert_equal(["Foo", "foo"], @a.instance_eval{ expand_name("Foo", "foo") })
assert_equal(["#<Class:Foo>", "foo"], @a.instance_eval{ expand_name("Foo.foo") })
assert_equal(["#<Class:Foo>", "foo"], @a.instance_eval{ expand_name("#<Class:Foo>", "foo") })
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/code_coverage_analyzer_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/code_coverage_analyzer_test.rb | require File.dirname(__FILE__) + '/test_helper'
class TestCodeCoverageAnalyzer < Test::Unit::TestCase
LINES = <<-EOF.split "\n"
puts 1
if foo
bar
baz
end
5.times do
foo
bar if baz
end
EOF
def setup
if defined? Rcov::Test::Temporary
Rcov::Test::Temporary.constants.each do |name|
Rcov::Test::Temporary.module_eval{ remove_const(name) }
end
end
end
def test_refine_coverage_info
analyzer = Rcov::CodeCoverageAnalyzer.new
cover = [1, 1, nil, nil, 0, 5, 5, 5, 0]
line_info, marked_info,
count_info = analyzer.instance_eval{ refine_coverage_info(LINES, cover) }
assert_equal(LINES, line_info)
assert_equal([true] * 2 + [false] * 3 + [true] * 3 + [false], marked_info)
assert_equal([1, 1, 0, 0, 0, 5, 5, 5, 0], count_info)
end
def test_analyzed_files_no_analysis
analyzer = Rcov::CodeCoverageAnalyzer.new
assert_equal([], analyzer.analyzed_files)
end
def test_raw_coverage_info
sample_file = File.join(File.dirname(__FILE__), "assets/sample_01.rb")
lines = File.readlines(sample_file)
analyzer = Rcov::CodeCoverageAnalyzer.new
analyzer.run_hooked{ load sample_file }
assert_equal(lines, SCRIPT_LINES__[sample_file][0, lines.size])
assert(analyzer.analyzed_files.include?(sample_file))
line_info, cov_info, count_info = analyzer.data(sample_file)
assert_equal(lines, line_info)
assert_equal([true, true, false, false, true, false, true], cov_info)
assert_equal([1, 2, 0, 0, 1, 0, 11], count_info) unless RUBY_PLATFORM =~ /java/
analyzer.reset
assert_equal(nil, analyzer.data(sample_file))
assert_equal([], analyzer.analyzed_files)
end
def test_script_lines_workaround_detects_correctly
analyzer = Rcov::CodeCoverageAnalyzer.new
lines = ["puts a", "foo", "bar"] * 3
coverage = [true] * 3 + [false] * 6
counts = [1] * 3 + [0] * 6
nlines, ncoverage, ncounts = analyzer.instance_eval do
script_lines_workaround(lines, coverage, counts)
end
assert_equal(["puts a", "foo", "bar"], nlines)
assert_equal([true, true, true], ncoverage)
assert_equal([1, 1, 1], ncounts)
end
def test_script_lines_workaround_no_false_positives
analyzer = Rcov::CodeCoverageAnalyzer.new
lines = ["puts a", "foo", "bar"] * 2 + ["puts a", "foo", "baz"]
coverage = [true] * 9
counts = [1] * 9
nlines, ncoverage, ncounts = analyzer.instance_eval do
script_lines_workaround(lines, coverage, counts)
end
assert_equal(lines, nlines)
assert_equal(coverage, ncoverage)
assert_equal(counts, ncounts)
end
def test_if_elsif_reports_correctly
sample_file = File.join(File.dirname(__FILE__), "assets/sample_06.rb")
lines = File.readlines(sample_file)
analyzer = Rcov::CodeCoverageAnalyzer.new
analyzer.run_hooked{ load sample_file }
assert_equal(lines, SCRIPT_LINES__[sample_file][0, lines.size])
assert(analyzer.analyzed_files.include?(sample_file))
line_info, cov_info, count_info = analyzer.data(sample_file)
assert_equal(lines, line_info)
assert_equal([true, true, false, true, true, false, false, false], cov_info) unless RUBY_PLATFORM == "java"
end
def test_differential_coverage_data
sample_file = File.join(File.dirname(__FILE__), "assets/sample_01.rb")
lines = File.readlines(sample_file)
analyzer = Rcov::CodeCoverageAnalyzer.new
analyzer.run_hooked{ load sample_file }
line_info, cov_info, count_info = analyzer.data(sample_file)
assert_equal([1, 2, 0, 0, 1, 0, 11], count_info) if RUBY_VERSION =~ /1.9/
analyzer.reset
#set_trace_func proc { |event, file, line, id, binding, classname| printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname if (file =~ /sample_02.rb/) }
sample_file = File.join(File.dirname(__FILE__), "assets/sample_02.rb")
analyzer.run_hooked{ load sample_file }
line_info, cov_info, count_info = analyzer.data(sample_file)
if RUBY_PLATFORM == "java"
assert_equal([8, 3, 0, 0, 0], count_info)
else
assert_equal([8, 1, 0, 0, 0], count_info) unless RUBY_VERSION =~ /1.9/
assert_equal([4, 1, 0, 0, 4], count_info) if RUBY_VERSION =~ /1.9/
end
analyzer.reset
assert_equal([], analyzer.analyzed_files)
analyzer.run_hooked{ Rcov::Test::Temporary::Sample02.foo(1, 1) }
line_info, cov_info, count_info = analyzer.data(sample_file)
if RUBY_PLATFORM == "java"
assert_equal([0, 1, 3, 1, 0], count_info) unless RUBY_VERSION =~ /1.9/
else
assert_equal([0, 1, 1, 1, 0], count_info) unless RUBY_VERSION =~ /1.9/
assert_equal([0, 2, 1, 0, 0], count_info) if RUBY_VERSION =~ /1.9/
end
analyzer.run_hooked do
10.times{ Rcov::Test::Temporary::Sample02.foo(1, 1) }
end
line_info, cov_info, count_info = analyzer.data(sample_file)
assert_equal([0, 11, 33, 11, 0], count_info) if RUBY_PLATFORM == "java"
assert_equal([0, 11, 11, 11, 0], count_info) unless RUBY_PLATFORM == "java"
10.times{ analyzer.run_hooked{ Rcov::Test::Temporary::Sample02.foo(1, 1) } }
line_info, cov_info, count_info = analyzer.data(sample_file)
assert_equal([0, 21, 63, 21, 0], count_info) if RUBY_PLATFORM == "java"
assert_equal([0, 21, 21, 21, 0], count_info) unless RUBY_PLATFORM == "java"
count_info2 = nil
10.times do |i|
analyzer.run_hooked do
Rcov::Test::Temporary::Sample02.foo(1, 1)
line_info, cov_info, count_info = analyzer.data(sample_file) if i == 3
line_info2, cov_info2, count_info2 = analyzer.data(sample_file)
end
end
if RUBY_PLATFORM == "java"
assert_equal([0, 25, 75, 25, 0], count_info)
assert_equal([0, 31, 93, 31, 0], count_info2)
else
assert_equal([0, 25, 25, 25, 0], count_info)
assert_equal([0, 31, 31, 31, 0], count_info2)
end
end
def test_nested_analyzer_blocks
a1 = Rcov::CodeCoverageAnalyzer.new
a2 = Rcov::CodeCoverageAnalyzer.new
sample_file = File.join(File.dirname(__FILE__), "assets/sample_02.rb")
load sample_file
a1.run_hooked do
100.times{ Rcov::Test::Temporary::Sample02.foo(1, 1) }
a2.run_hooked do
10.times{ Rcov::Test::Temporary::Sample02.foo(1, 1) }
end
100.times{ Rcov::Test::Temporary::Sample02.foo(1, 1) }
end
a2.run_hooked do
100.times{ Rcov::Test::Temporary::Sample02.foo(1, 1) }
10.times{ a1.run_hooked { Rcov::Test::Temporary::Sample02.foo(1, 1) } }
end
a1.install_hook
Rcov::Test::Temporary::Sample02.foo(1, 1)
a1.remove_hook
a2.install_hook
Rcov::Test::Temporary::Sample02.foo(1, 1)
a2.remove_hook
_, _, counts1 = a1.data(sample_file)
_, _, counts2 = a2.data(sample_file)
if RUBY_PLATFORM == "java"
assert_equal([0, 221, 663, 221, 0], counts1)
assert_equal([0, 121, 363, 121, 0], counts2)
else
assert_equal([0, 221, 221, 221, 0], counts1)
assert_equal([0, 121, 121, 121, 0], counts2)
end
end
def test_reset
a1 = Rcov::CodeCoverageAnalyzer.new
sample_file = File.join(File.dirname(__FILE__), "assets/sample_02.rb")
load sample_file
a1.run_hooked do
100.times do |i|
Rcov::Test::Temporary::Sample02.foo(1, 1)
a1.reset if i == 49
end
end
assert_equal([0, 50, 50, 50, 0], a1.data(sample_file)[2]) unless RUBY_PLATFORM == "java"
assert_equal([0, 50, 150, 50, 0], a1.data(sample_file)[2]) if RUBY_PLATFORM == "java"
end
def test_compute_raw_difference
first = {"a" => [1,1,1,1,1]}
last = {"a" => [2,1,5,2,1], "b" => [1,2,3,4,5]}
a = Rcov::CodeCoverageAnalyzer.new
assert_equal({"a" => [1,0,4,1,0], "b" => [1,2,3,4,5]},
a.instance_eval{ compute_raw_data_difference(first, last)} )
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/test_helper.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/test_helper.rb | require 'test/unit'
require 'rcov'
require 'pathname'
require 'fileutils'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/turn_off_rcovrt.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/turn_off_rcovrt.rb | # When loaded, this file forces rcov to run in pure-Ruby mode even if
# rcovrt.so exists and can be loaded.
$rcov_do_not_use_rcovrt = true
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/expected_coverage/sample_03_rb.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/expected_coverage/sample_03_rb.rb | #o
module Rcov; module Test; module Temporary; class Sample03 #o
def f1 # MUST NOT CHANGE the position or the tests will break # << [[sample_03_rb.rb:10 in Rcov::Test::Temporary::Sample03#f3]], [[sample_04_rb.rb:6 in #]],
10.times { f2 } # >> [[Rcov::Test::Temporary::Sample03#f2 at sample_03_rb.rb:7]],
end #o
#o
def f2; 1 end # << [[sample_03_rb.rb:4 in Rcov::Test::Temporary::Sample03#f1]], [[sample_03_rb.rb:11 in Rcov::Test::Temporary::Sample03#f3]], [[sample_04_rb.rb:7 in #]],
#o
def f3 # << [[sample_04_rb.rb:8 in #]],
10.times{ f1 } # >> [[Rcov::Test::Temporary::Sample03#f1 at sample_03_rb.rb:3]],
100.times{ f2 } # >> [[Rcov::Test::Temporary::Sample03#f2 at sample_03_rb.rb:7]],
end #o
#o
def self.g1 #o
10.times{ g2 }
end
#o
def self.g2; 1 end # << [[sample_04_rb.rb:10 in #]],
# safe from here ...
end end end end
# Total lines : 20
# Lines of code : 14
# Total coverage : 80.0%
# Code coverage : 78.6%
# Local Variables:
# mode: rcov-xref
# End:
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/expected_coverage/sample_04_rb.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/expected_coverage/sample_04_rb.rb | $: << File.dirname(__FILE__) #o
require 'sample_03' #o
#o
klass = Rcov::Test::Temporary::Sample03 #o
obj = klass.new #o
obj.f1 # >> [[Rcov::Test::Temporary::Sample03#f1 at sample_03_rb.rb:3]],
obj.f2 # >> [[Rcov::Test::Temporary::Sample03#f2 at sample_03_rb.rb:7]],
obj.f3 # >> [[Rcov::Test::Temporary::Sample03#f3 at sample_03_rb.rb:9]],
#klass.g1 uncovered #o
klass.g2 # >> [[#<Class:Rcov::Test::Temporary::Sample03>#g2 at sample_03_rb.rb:18]],
# Total lines : 10
# Lines of code : 8
# Total coverage : 100.0%
# Code coverage : 100.0%
# Local Variables:
# mode: rcov-xref
# End:
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/assets/sample_03.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/assets/sample_03.rb |
module Rcov; module Test; module Temporary; class Sample03
def f1 # MUST NOT CHANGE the position or the tests will break
10.times { f2 }
end
def f2; 1 end
def f3
10.times{ f1 }
100.times{ f2 }
end
def self.g1
10.times{ g2 }
end
def self.g2; 1 end
# safe from here ...
end end end end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/assets/sample_01.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/assets/sample_01.rb | a = 1
if a == 2
b = 1
else
b = 2
end
10.times{ b += 1 }
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/assets/sample_04.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/assets/sample_04.rb | $: << File.dirname(__FILE__)
require 'sample_03'
klass = Rcov::Test::Temporary::Sample03
obj = klass.new
obj.f1
obj.f2
obj.f3
#klass.g1 uncovered
klass.g2
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/assets/sample_05-new.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/assets/sample_05-new.rb | def d(x)
4*x
end
def a
b 10
end
def b(x)
x*10
end
def c(x)
3*x
end
a()
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/assets/sample_05-old.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/assets/sample_05-old.rb | def a
b 10
end
def b(x)
x*10
end
def c(x)
3*x
end
a()
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/assets/sample_05.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/assets/sample_05.rb | def d(x)
4*x
end
def a
b 10
end
def b(x)
x*10
end
def c(x)
3*x
end
a()
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/assets/sample_06.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/assets/sample_06.rb | x = 2
if x.nil?
x = 4
elsif x == 2
x = x*x
else
x = x+4
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/assets/sample_02.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/test/assets/sample_02.rb | module Rcov; module Test; module Temporary; module Sample02
def self.foo(a,b)
a + b
end
end end end end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov.rb | # rcov Copyright (c) 2004-2006 Mauricio Fernandez <mfp@acm.org>
#
# See LICENSE for licensing information.
# NOTE: if you're reading this in the XHTML code coverage report generated by
# rcov, you'll notice that only code inside methods is reported as covered,
# very much like what happens when you run it with --test-unit-only.
# This is due to the fact that we're running rcov on itself: the code below is
# already loaded before coverage tracing is activated, so only code inside
# methods is actually executed under rcov's inspection.
require 'rcov/version'
require 'rcov/formatters'
require 'rcov/coverage_info'
require 'rcov/file_statistics'
require 'rcov/differential_analyzer'
require 'rcov/code_coverage_analyzer'
require 'rcov/call_site_analyzer'
SCRIPT_LINES__ = {} unless defined? SCRIPT_LINES__
module Rcov
# TODO: Move to Ruby 1.8.6 Backport module
unless RUBY_VERSION =~ /1.9/
class ::String
def lines
map
end
end
end
autoload :RCOV__, "rcov/lowlevel.rb"
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/file_statistics.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/file_statistics.rb | module Rcov
# A FileStatistics object associates a filename to:
# 1. its source code
# 2. the per-line coverage information after correction using rcov's heuristics
# 3. the per-line execution counts
#
# A FileStatistics object can be therefore be built given the filename, the
# associated source code, and an array holding execution counts (i.e. how many
# times each line has been executed).
#
# FileStatistics is relatively intelligent: it handles normal comments,
# <tt>=begin/=end</tt>, heredocs, many multiline-expressions... It uses a
# number of heuristics to determine what is code and what is a comment, and to
# refine the initial (incomplete) coverage information.
#
# Basic usage is as follows:
# sf = FileStatistics.new("foo.rb", ["puts 1", "if true &&", " false",
# "puts 2", "end"], [1, 1, 0, 0, 0])
# sf.num_lines # => 5
# sf.num_code_lines # => 5
# sf.coverage[2] # => true
# sf.coverage[3] # => :inferred
# sf.code_coverage # => 0.6
#
# The array of strings representing the source code and the array of execution
# counts would normally be obtained from a Rcov::CodeCoverageAnalyzer.
class FileStatistics
attr_reader :name, :lines, :coverage, :counts
def initialize(name, lines, counts, comments_run_by_default = false)
@name = name
@lines = lines
initial_coverage = counts.map{|x| (x || 0) > 0 ? true : false }
@coverage = CoverageInfo.new initial_coverage
@counts = counts
@is_begin_comment = nil
# points to the line defining the heredoc identifier
# but only if it was marked (we don't care otherwise)
@heredoc_start = Array.new(lines.size, false)
@multiline_string_start = Array.new(lines.size, false)
extend_heredocs
find_multiline_strings
precompute_coverage comments_run_by_default
end
# Merge code coverage and execution count information.
# As for code coverage, a line will be considered
# * covered for sure (true) if it is covered in either +self+ or in the
# +coverage+ array
# * considered <tt>:inferred</tt> if the neither +self+ nor the +coverage+ array
# indicate that it was definitely executed, but it was <tt>inferred</tt>
# in either one
# * not covered (<tt>false</tt>) if it was uncovered in both
#
# Execution counts are just summated on a per-line basis.
def merge(lines, coverage, counts)
coverage.each_with_index do |v, idx|
case @coverage[idx]
when :inferred
@coverage[idx] = v || @coverage[idx]
when false
@coverage[idx] ||= v
end
end
counts.each_with_index{|v, idx| @counts[idx] += v }
precompute_coverage false
end
# Total coverage rate if comments are also considered "executable", given as
# a fraction, i.e. from 0 to 1.0.
# A comment is attached to the code following it (RDoc-style): it will be
# considered executed if the the next statement was executed.
def total_coverage
return 0 if @coverage.size == 0
@coverage.inject(0.0) {|s,a| s + (a ? 1:0) } / @coverage.size
end
# Code coverage rate: fraction of lines of code executed, relative to the
# total amount of lines of code (loc). Returns a float from 0 to 1.0.
def code_coverage
indices = (0...@lines.size).select{|i| is_code? i }
return 0 if indices.size == 0
count = 0
indices.each {|i| count += 1 if @coverage[i] }
1.0 * count / indices.size
end
def code_coverage_for_report
code_coverage * 100
end
def total_coverage_for_report
total_coverage * 100
end
# Number of lines of code (loc).
def num_code_lines
(0...@lines.size).select{|i| is_code? i}.size
end
# Total number of lines.
def num_lines
@lines.size
end
# Returns true if the given line number corresponds to code, as opposed to a
# comment (either # or =begin/=end blocks).
def is_code?(lineno)
unless @is_begin_comment
@is_begin_comment = Array.new(@lines.size, false)
pending = []
state = :code
@lines.each_with_index do |line, index|
case state
when :code
if /^=begin\b/ =~ line
state = :comment
pending << index
end
when :comment
pending << index
if /^=end\b/ =~ line
state = :code
pending.each{|idx| @is_begin_comment[idx] = true}
pending.clear
end
end
end
end
@lines[lineno] && !@is_begin_comment[lineno] && @lines[lineno] !~ /^\s*(#|$)/
end
private
def find_multiline_strings
state = :awaiting_string
wanted_delimiter = nil
string_begin_line = 0
@lines.each_with_index do |line, i|
matching_delimiters = Hash.new{|h,k| k}
matching_delimiters.update("{" => "}", "[" => "]", "(" => ")")
case state
when :awaiting_string
# very conservative, doesn't consider the last delimited string but
# only the very first one
if md = /^[^#]*%(?:[qQ])?(.)/.match(line)
if !/"%"/.match(line)
wanted_delimiter = /(?!\\).#{Regexp.escape(matching_delimiters[md[1]])}/
# check if closed on the very same line
# conservative again, we might have several quoted strings with the
# same delimiter on the same line, leaving the last one open
unless wanted_delimiter.match(md.post_match)
state = :want_end_delimiter
string_begin_line = i
end
end
end
when :want_end_delimiter
@multiline_string_start[i] = string_begin_line
if wanted_delimiter.match(line)
state = :awaiting_string
end
end
end
end
def is_nocov?(line)
line =~ /#:nocov:/
end
def mark_nocov_regions(nocov_line_numbers, coverage)
while nocov_line_numbers.size > 0
begin_line, end_line = nocov_line_numbers.shift, nocov_line_numbers.shift
next unless begin_line && end_line
(begin_line..end_line).each do |line_num|
coverage[line_num] ||= :inferred
end
end
end
def precompute_coverage(comments_run_by_default = true)
changed = false
lastidx = lines.size - 1
if (!is_code?(lastidx) || /^__END__$/ =~ @lines[-1]) && !@coverage[lastidx]
# mark the last block of comments
@coverage[lastidx] ||= :inferred
(lastidx-1).downto(0) do |i|
break if is_code?(i)
@coverage[i] ||= :inferred
end
end
nocov_line_numbers = []
(0...lines.size).each do |i|
nocov_line_numbers << i if is_nocov?(@lines[i])
next if @coverage[i]
line = @lines[i]
if /^\s*(begin|ensure|else|case)\s*(?:#.*)?$/ =~ line && next_expr_marked?(i) or
/^\s*(?:end|\})\s*(?:#.*)?$/ =~ line && prev_expr_marked?(i) or
/^\s*(?:end\b|\})/ =~ line && prev_expr_marked?(i) && next_expr_marked?(i) or
/^\s*rescue\b/ =~ line && next_expr_marked?(i) or
/(do|\{)\s*(\|[^|]*\|\s*)?(?:#.*)?$/ =~ line && next_expr_marked?(i) or
prev_expr_continued?(i) && prev_expr_marked?(i) or
comments_run_by_default && !is_code?(i) or
/^\s*((\)|\]|\})\s*)+(?:#.*)?$/ =~ line && prev_expr_marked?(i) or
prev_expr_continued?(i+1) && next_expr_marked?(i)
@coverage[i] ||= :inferred
changed = true
end
end
mark_nocov_regions(nocov_line_numbers, @coverage)
(@lines.size-1).downto(0) do |i|
next if @coverage[i]
if !is_code?(i) and @coverage[i+1]
@coverage[i] = :inferred
changed = true
end
end
extend_heredocs if changed
# if there was any change, we have to recompute; we'll eventually
# reach a fixed point and stop there
precompute_coverage(comments_run_by_default) if changed
end
require 'strscan'
def extend_heredocs
i = 0
while i < @lines.size
unless is_code? i
i += 1
next
end
#FIXME: using a restrictive regexp so that only <<[A-Z_a-z]\w*
# matches when unquoted, so as to avoid problems with 1<<2
# (keep in mind that whereas puts <<2 is valid, puts 1<<2 is a
# parse error, but a = 1<<2 is of course fine)
scanner = StringScanner.new(@lines[i])
j = k = i
loop do
scanned_text = scanner.search_full(/<<(-?)(?:(['"`])((?:(?!\2).)+)\2|([A-Z_a-z]\w*))/, true, true)
# k is the first line after the end delimiter for the last heredoc
# scanned so far
unless scanner.matched?
i = k
break
end
term = scanner[3] || scanner[4]
# try to ignore symbolic bitshifts like 1<<LSHIFT
ident_text = "<<#{scanner[1]}#{scanner[2]}#{term}#{scanner[2]}"
if scanned_text[/\d+\s*#{Regexp.escape(ident_text)}/]
# it was preceded by a number, ignore
i = k
break
end
must_mark = []
end_of_heredoc = (scanner[1] == "-") ? /^\s*#{Regexp.escape(term)}$/ : /^#{Regexp.escape(term)}$/
loop do
break if j == @lines.size
must_mark << j
if end_of_heredoc =~ @lines[j]
must_mark.each do |n|
@heredoc_start[n] = i
end
if (must_mark + [i]).any?{|lineidx| @coverage[lineidx]}
@coverage[i] ||= :inferred
must_mark.each{|lineidx| @coverage[lineidx] ||= :inferred}
end
# move the "first line after heredocs" index
if @lines[j+=1] =~ /^\s*\n$/
k = j
end
break
end
j += 1
end
end
i += 1
end
end
def next_expr_marked?(lineno)
return false if lineno >= @lines.size
found = false
idx = (lineno+1).upto(@lines.size-1) do |i|
next unless is_code? i
found = true
break i
end
return false unless found
@coverage[idx]
end
def prev_expr_marked?(lineno)
return false if lineno <= 0
found = false
idx = (lineno-1).downto(0) do |i|
next unless is_code? i
found = true
break i
end
return false unless found
@coverage[idx]
end
def prev_expr_continued?(lineno)
return false if lineno <= 0
return false if lineno >= @lines.size
found = false
if @multiline_string_start[lineno] &&
@multiline_string_start[lineno] < lineno
return true
end
# find index of previous code line
idx = (lineno-1).downto(0) do |i|
if @heredoc_start[i]
found = true
break @heredoc_start[i]
end
next unless is_code? i
found = true
break i
end
return false unless found
#TODO: write a comprehensive list
if is_code?(lineno) && /^\s*((\)|\]|\})\s*)+(?:#.*)?$/.match(@lines[lineno])
return true
end
#FIXME: / matches regexps too
# the following regexp tries to reject #{interpolation}
r = /(,|\.|\+|-|\*|\/|<|>|%|&&|\|\||<<|\(|\[|\{|=|and|or|\\)\s*(?:#(?![{$@]).*)?$/.match @lines[idx]
# try to see if a multi-line expression with opening, closing delimiters
# started on that line
[%w!( )!].each do |opening_str, closing_str|
# conservative: only consider nesting levels opened in that line, not
# previous ones too.
# next regexp considers interpolation too
line = @lines[idx].gsub(/#(?![{$@]).*$/, "")
opened = line.scan(/#{Regexp.escape(opening_str)}/).size
closed = line.scan(/#{Regexp.escape(closing_str)}/).size
return true if opened - closed > 0
end
if /(do|\{)\s*\|[^|]*\|\s*(?:#.*)?$/.match @lines[idx]
return false
end
r
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/rcovtask.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/rcovtask.rb | #!/usr/bin/env ruby
# Define a task library for performing code coverage analysis of unit tests
# using rcov.
require 'rake'
require 'rake/tasklib'
module Rcov
# Create a task that runs a set of tests through rcov, generating code
# coverage reports.
#
# Example:
#
# require 'rcov/rcovtask'
#
# Rcov::RcovTask.new do |t|
# t.libs << "test"
# t.test_files = FileList['test/test*.rb']
# t.verbose = true
# end
#
# If rake is invoked with a "TEST=filename" command line option,
# then the list of test files will be overridden to include only the
# filename specified on the command line. This provides an easy way
# to run just one test.
#
# If rake is invoked with a "RCOVOPTS=options" command line option,
# then the given options are passed to rcov.
#
# If rake is invoked with a "RCOVPATH=path/to/rcov" command line option,
# then the given rcov executable will be used; otherwise the one in your
# PATH will be used.
#
# Examples:
#
# rake rcov # run tests normally
# rake rcov TEST=just_one_file.rb # run just one test file.
# rake rcov RCOVOPTS="-p" # run in profile mode
# rake rcov RCOVOPTS="-T" # generate text report
#
class RcovTask < Rake::TaskLib
# Name of test task. (default is :rcov)
attr_accessor :name
# List of directories to added to $LOAD_PATH before running the
# tests. (default is 'lib')
attr_accessor :libs
# True if verbose test output desired. (default is false)
attr_accessor :verbose
# Request that the tests be run with the warning flag set.
# E.g. warning=true implies "ruby -w" used to run the tests.
attr_accessor :warning
# Glob pattern to match test files. (default is 'test/test*.rb')
attr_accessor :pattern
# Array of commandline options to pass to ruby when running the rcov loader.
attr_accessor :ruby_opts
# Array of commandline options to pass to rcov. An explicit
# RCOVOPTS=opts on the command line will override this. (default
# is <tt>["--text-report"]</tt>)
attr_accessor :rcov_opts
# Output directory for the XHTML report.
attr_accessor :output_dir
# Explicitly define the list of test files to be included in a
# test. +list+ is expected to be an array of file names (a
# FileList is acceptable). If both +pattern+ and +test_files+ are
# used, then the list of test files is the union of the two.
def test_files=(list)
@test_files = list
end
# Create a testing task.
def initialize(name=:rcov)
@name = name
@libs = ["lib"]
@pattern = nil
@test_files = nil
@verbose = false
@warning = false
@rcov_opts = ["--text-report"]
@ruby_opts = []
@output_dir = "coverage"
yield self if block_given?
@pattern = 'test/test*.rb' if @pattern.nil? && @test_files.nil?
define
end
# Create the tasks defined by this task lib.
def define
lib_path = @libs.join(File::PATH_SEPARATOR)
actual_name = Hash === name ? name.keys.first : name
unless Rake.application.last_comment
desc "Analyze code coverage with tests" +
(@name==:rcov ? "" : " for #{actual_name}")
end
task @name do
run_code = ''
RakeFileUtils.verbose(@verbose) do
run_code =
case rcov_path
when nil, ''
"-S rcov"
else %!"#{rcov_path}"!
end
ruby_opts = @ruby_opts.clone
ruby_opts.push( "-I#{lib_path}" )
ruby_opts.push run_code
ruby_opts.push( "-w" ) if @warning
ruby ruby_opts.join(" ") + " " + option_list +
%[ -o "#{@output_dir}" ] +
file_list.collect { |fn| %["#{fn}"] }.join(' ')
end
end
desc "Remove rcov products for #{actual_name}"
task paste("clobber_", actual_name) do
rm_r @output_dir rescue nil
end
clobber_task = paste("clobber_", actual_name)
task :clobber => [clobber_task]
task actual_name => clobber_task
self
end
def rcov_path # :nodoc:
ENV['RCOVPATH']
end
def option_list # :nodoc:
ENV['RCOVOPTS'] || @rcov_opts.join(" ") || ""
end
def file_list # :nodoc:
if ENV['TEST']
FileList[ ENV['TEST'] ]
else
result = []
result += @test_files.to_a if @test_files
result += FileList[ @pattern ].to_a if @pattern
FileList[result]
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/version.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/version.rb | # rcov Copyright (c) 2004-2006 Mauricio Fernandez <mfp@acm.org>
#
# See LICENSE for licensing information.
module Rcov
VERSION = "0.9.8"
RELEASE_DATE = "2010-02-28"
RCOVRT_ABI = [2,0,0]
UPSTREAM_URL = "http://github.com/relevance/rcov"
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/call_site_analyzer.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/call_site_analyzer.rb | module Rcov
# A CallSiteAnalyzer can be used to obtain information about:
# * where a method is defined ("+defsite+")
# * where a method was called from ("+callsite+")
#
# == Example
# <tt>example.rb</tt>:
# class X
# def f1; f2 end
# def f2; 1 + 1 end
# def f3; f1 end
# end
#
# analyzer = Rcov::CallSiteAnalyzer.new
# x = X.new
# analyzer.run_hooked do
# x.f1
# end
# # ....
#
# analyzer.run_hooked do
# x.f3
# # the information generated in this run is aggregated
# # to the previously recorded one
# end
#
# analyzer.analyzed_classes # => ["X", ... ]
# analyzer.methods_for_class("X") # => ["f1", "f2", "f3"]
# analyzer.defsite("X#f1") # => DefSite object
# analyzer.callsites("X#f2") # => hash with CallSite => count
# # associations
# defsite = analyzer.defsite("X#f1")
# defsite.file # => "example.rb"
# defsite.line # => 2
#
# You can have several CallSiteAnalyzer objects at a time, and it is
# possible to nest the #run_hooked / #install_hook/#remove_hook blocks: each
# analyzer will manage its data separately. Note however that no special
# provision is taken to ignore code executed "inside" the CallSiteAnalyzer
# class.
#
# +defsite+ information is only available for methods that were called under
# the inspection of the CallSiteAnalyzer, i.o.w. you will only have +defsite+
# information for those methods for which callsite information is
# available.
class CallSiteAnalyzer < DifferentialAnalyzer
# A method definition site.
class DefSite < Struct.new(:file, :line)
end
# Object representing a method call site.
# It corresponds to a part of the callstack starting from the context that
# called the method.
class CallSite < Struct.new(:backtrace)
# The depth of a CallSite is the number of stack frames
# whose information is included in the CallSite object.
def depth
backtrace.size
end
# File where the method call originated.
# Might return +nil+ or "" if it is not meaningful (C extensions, etc).
def file(level = 0)
stack_frame = backtrace[level]
stack_frame ? stack_frame[2] : nil
end
# Line where the method call originated.
# Might return +nil+ or 0 if it is not meaningful (C extensions, etc).
def line(level = 0)
stack_frame = backtrace[level]
stack_frame ? stack_frame[3] : nil
end
# Name of the method where the call originated.
# Returns +nil+ if the call originated in +toplevel+.
# Might return +nil+ if it could not be determined.
def calling_method(level = 0)
stack_frame = backtrace[level]
stack_frame ? stack_frame[1] : nil
end
# Name of the class holding the method where the call originated.
# Might return +nil+ if it could not be determined.
def calling_class(level = 0)
stack_frame = backtrace[level]
stack_frame ? stack_frame[0] : nil
end
end
@hook_level = 0
# defined this way instead of attr_accessor so that it's covered
def self.hook_level # :nodoc:
@hook_level
end
def self.hook_level=(x) # :nodoc:
@hook_level = x
end
def initialize
super(:install_callsite_hook, :remove_callsite_hook,
:reset_callsite)
end
# Classes whose methods have been called.
# Returns an array of strings describing the classes (just klass.to_s for
# each of them). Singleton classes are rendered as:
# #<Class:MyNamespace::MyClass>
def analyzed_classes
raw_data_relative.first.keys.map{|klass, meth| klass}.uniq.sort
end
# Methods that were called for the given class. See #analyzed_classes for
# the notation used for singleton classes.
# Returns an array of strings or +nil+
def methods_for_class(classname)
a = raw_data_relative.first.keys.select{|kl,_| kl == classname}.map{|_,meth| meth}.sort
a.empty? ? nil : a
end
alias_method :analyzed_methods, :methods_for_class
# Returns a hash with <tt>CallSite => call count</tt> associations or +nil+
# Can be called in two ways:
# analyzer.callsites("Foo#f1") # instance method
# analyzer.callsites("Foo.g1") # singleton method of the class
# or
# analyzer.callsites("Foo", "f1")
# analyzer.callsites("#<class:Foo>", "g1")
def callsites(classname_or_fullname, methodname = nil)
rawsites = raw_data_relative.first[expand_name(classname_or_fullname, methodname)]
return nil unless rawsites
ret = {}
# could be a job for inject but it's slow and I don't mind the extra loc
rawsites.each_pair do |backtrace, count|
ret[CallSite.new(backtrace)] = count
end
ret
end
# Returns a DefSite object corresponding to the given method
# Can be called in two ways:
# analyzer.defsite("Foo#f1") # instance method
# analyzer.defsite("Foo.g1") # singleton method of the class
# or
# analyzer.defsite("Foo", "f1")
# analyzer.defsite("#<class:Foo>", "g1")
def defsite(classname_or_fullname, methodname = nil)
file, line = raw_data_relative[1][expand_name(classname_or_fullname, methodname)]
return nil unless file && line
DefSite.new(file, line)
end
private
def expand_name(classname_or_fullname, methodname = nil)
if methodname.nil?
case classname_or_fullname
when /(.*)#(.*)/ then classname, methodname = $1, $2
when /(.*)\.(.*)/ then classname, methodname = "#<Class:#{$1}>", $2
else
raise ArgumentError, "Incorrect method name"
end
return [classname, methodname]
end
[classname_or_fullname, methodname]
end
def data_default; [{}, {}] end
def raw_data_absolute
raw, method_def_site = RCOV__.generate_callsite_info
ret1 = {}
ret2 = {}
raw.each_pair do |(klass, method), hash|
begin
key = [klass.to_s, method.to_s]
ret1[key] = hash.clone #Marshal.load(Marshal.dump(hash))
ret2[key] = method_def_site[[klass, method]]
#rescue Exception
end
end
[ret1, ret2]
end
def aggregate_data(aggregated_data, delta)
callsites1, defsites1 = aggregated_data
callsites2, defsites2 = delta
callsites2.each_pair do |(klass, method), hash|
dest_hash = (callsites1[[klass, method]] ||= {})
hash.each_pair do |callsite, count|
dest_hash[callsite] ||= 0
dest_hash[callsite] += count
end
end
defsites1.update(defsites2)
end
def compute_raw_data_difference(first, last)
difference = {}
default = Hash.new(0)
callsites1, defsites1 = *first
callsites2, defsites2 = *last
callsites2.each_pair do |(klass, method), hash|
old_hash = callsites1[[klass, method]] || default
hash.each_pair do |callsite, count|
diff = hash[callsite] - (old_hash[callsite] || 0)
if diff > 0
difference[[klass, method]] ||= {}
difference[[klass, method]][callsite] = diff
end
end
end
[difference, defsites1.update(defsites2)]
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/formatters.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/formatters.rb | require 'rcov/formatters/html_erb_template'
require 'rcov/formatters/base_formatter'
require 'rcov/formatters/text_summary'
require 'rcov/formatters/text_report'
require 'rcov/formatters/text_coverage_diff'
require 'rcov/formatters/full_text_report'
require 'rcov/formatters/html_coverage'
require 'rcov/formatters/failure_report'
module Rcov
module Formatters
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/differential_analyzer.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/differential_analyzer.rb | module Rcov
class DifferentialAnalyzer
require 'thread'
@@mutex = Mutex.new
def initialize(install_hook_meth, remove_hook_meth, reset_meth)
@cache_state = :wait
@start_raw_data = data_default
@end_raw_data = data_default
@aggregated_data = data_default
@install_hook_meth = install_hook_meth
@remove_hook_meth= remove_hook_meth
@reset_meth= reset_meth
end
# Execute the code in the given block, monitoring it in order to gather
# information about which code was executed.
def run_hooked
install_hook
yield
ensure
remove_hook
end
# Start monitoring execution to gather information. Such data will be
# collected until #remove_hook is called.
#
# Use #run_hooked instead if possible.
def install_hook
@start_raw_data = raw_data_absolute
Rcov::RCOV__.send(@install_hook_meth)
@cache_state = :hooked
@@mutex.synchronize{ self.class.hook_level += 1 }
end
# Stop collecting information.
# #remove_hook will also stop collecting info if it is run inside a
# #run_hooked block.
def remove_hook
@@mutex.synchronize do
self.class.hook_level -= 1
Rcov::RCOV__.send(@remove_hook_meth) if self.class.hook_level == 0
end
@end_raw_data = raw_data_absolute
@cache_state = :done
# force computation of the stats for the traced code in this run;
# we cannot simply let it be if self.class.hook_level == 0 because
# some other analyzer could install a hook, causing the raw_data_absolute
# to change again.
# TODO: lazy computation of raw_data_relative, only when the hook gets
# activated again.
raw_data_relative
end
# Remove the data collected so far. Further collection will start from
# scratch.
def reset
@@mutex.synchronize do
if self.class.hook_level == 0
# Unfortunately there's no way to report this as covered with rcov:
# if we run the tests under rcov self.class.hook_level will be >= 1 !
# It is however executed when we run the tests normally.
Rcov::RCOV__.send(@reset_meth)
@start_raw_data = data_default
@end_raw_data = data_default
else
@start_raw_data = @end_raw_data = raw_data_absolute
end
@raw_data_relative = data_default
@aggregated_data = data_default
end
end
protected
def data_default
raise "must be implemented by the subclass"
end
def self.hook_level
raise "must be implemented by the subclass"
end
def raw_data_absolute
raise "must be implemented by the subclass"
end
def aggregate_data(aggregated_data, delta)
raise "must be implemented by the subclass"
end
def compute_raw_data_difference(first, last)
raise "must be implemented by the subclass"
end
private
def raw_data_relative
case @cache_state
when :wait
return @aggregated_data
when :hooked
new_start = raw_data_absolute
new_diff = compute_raw_data_difference(@start_raw_data, new_start)
@start_raw_data = new_start
when :done
@cache_state = :wait
new_diff = compute_raw_data_difference(@start_raw_data,
@end_raw_data)
end
aggregate_data(@aggregated_data, new_diff)
@aggregated_data
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/lowlevel.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/lowlevel.rb | # rcov Copyright (c) 2004-2006 Mauricio Fernandez <mfp@acm.org>
#
# See LEGAL and LICENSE for licensing information.
require 'rcov/version'
module Rcov
# RCOV__ performs the low-level tracing of the execution, gathering code
# coverage information in the process. The C core made available through the
# rcovrt extension will be used if possible. Otherwise the functionality
# will be emulated using set_trace_func, but this is very expensive and
# will fail if other libraries (e.g. breakpoint) change the trace_func.
#
# Do not use this module; it is very low-level and subject to frequent
# changes. Rcov::CodeCoverageAnalyzer offers a much more convenient and
# stable interface.
module RCOV__
COVER = {}
CALLSITES = {}
DEFSITES = {}
pure_ruby_impl_needed = true
unless defined? $rcov_do_not_use_rcovrt
begin
require 'rcovrt'
abi = [0,0,0]
begin
abi = RCOV__.ABI
raise if abi[0] != RCOVRT_ABI[0] || abi[1] < RCOVRT_ABI[1]
pure_ruby_impl_needed = false
rescue
$stderr.puts <<-EOF
The rcovrt extension I found was built for a different version of rcov.
The required ABI is: #{RCOVRT_ABI.join(".")}
Your current rcovrt extension is: #{abi.join(".")}
Please delete rcovrt.{so,bundle,dll,...} and install the required one.
EOF
raise LoadError
end
rescue LoadError
$stderr.puts <<-EOF
Since the rcovrt extension couldn't be loaded, rcov will run in pure-Ruby
mode, which is about two orders of magnitude slower.
If you're on win32, you can find a pre-built extension (usable with recent
One Click Installer and mswin32 builds) at http://eigenclass.org/hiki.rb?rcov .
EOF
end
end
if pure_ruby_impl_needed
methods = %w[install_coverage_hook remove_coverage_hook reset_coverage
install_callsite_hook remove_callsite_hook reset_callsite
generate_coverage_info generate_callsite_info]
sklass = class << self; self end
(methods & sklass.instance_methods).each do |meth|
sklass.class_eval{ remove_method meth }
end
@coverage_hook_activated = @callsite_hook_activated = false
def self.install_coverage_hook # :nodoc:
install_common_hook
@coverage_hook_activated = true
end
def self.install_callsite_hook # :nodoc:
install_common_hook
@callsite_hook_activated = true
end
def self.install_common_hook # :nodoc:
set_trace_func lambda {|event, file, line, id, binding, klass|
next unless SCRIPT_LINES__.has_key? file
case event
when 'call'
if @callsite_hook_activated
receiver = eval("self", binding)
klass = class << klass; self end unless klass === receiver
begin
DEFSITES[[klass.to_s, id.to_s]] = [file, line]
rescue Exception
end
caller_arr = self.format_backtrace_array(caller[1,1])
begin
hash = CALLSITES[[klass.to_s, id.to_s]] ||= {}
hash[caller_arr] ||= 0
hash[caller_arr] += 1
#puts "#{event} #{file} #{line} #{klass.inspect} " +
# "#{klass.object_id} #{id} #{eval('self', binding)}"
rescue Exception
end
end
when 'c-call', 'c-return', 'class'
return
end
if @coverage_hook_activated
COVER[file] ||= Array.new(SCRIPT_LINES__[file].size, 0)
COVER[file][line - 1] ||= 0
COVER[file][line - 1] += 1
end
}
end
def self.remove_coverage_hook # :nodoc:
@coverage_hook_activated = false
set_trace_func(nil) if !@callsite_hook_activated
end
def self.remove_callsite_hook # :nodoc:
@callsite_hook_activated = false
set_trace_func(nil) if !@coverage_hook_activated
end
def self.reset_coverage # :nodoc:
COVER.replace({})
end
def self.reset_callsite # :nodoc:
CALLSITES.replace({})
DEFSITES.replace({})
end
def self.generate_coverage_info # :nodoc:
Marshal.load(Marshal.dump(COVER))
end
def self.generate_callsite_info # :nodoc:
[CALLSITES, DEFSITES]
end
def self.format_backtrace_array(backtrace)
backtrace.map do |line|
md = /^([^:]*)(?::(\d+)(?::in `(.*)'))?/.match(line)
raise "Bad backtrace format" unless md
[nil, md[3] ? md[3].to_sym : nil, md[1], (md[2] || '').to_i]
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/code_coverage_analyzer.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/code_coverage_analyzer.rb | module Rcov
# A CodeCoverageAnalyzer is responsible for tracing code execution and
# returning code coverage and execution count information.
#
# Note that you must <tt>require 'rcov'</tt> before the code you want to
# analyze is parsed (i.e. before it gets loaded or required). You can do that
# by either invoking ruby with the <tt>-rrcov</tt> command-line option or
# just:
# require 'rcov'
# require 'mycode'
# # ....
#
# == Example
#
# analyzer = Rcov::CodeCoverageAnalyzer.new
# analyzer.run_hooked do
# do_foo
# # all the code executed as a result of this method call is traced
# end
# # ....
#
# analyzer.run_hooked do
# do_bar
# # the code coverage information generated in this run is aggregated
# # to the previously recorded one
# end
#
# analyzer.analyzed_files # => ["foo.rb", "bar.rb", ... ]
# lines, marked_info, count_info = analyzer.data("foo.rb")
#
# In this example, two pieces of code are monitored, and the data generated in
# both runs are aggregated. +lines+ is an array of strings representing the
# source code of <tt>foo.rb</tt>. +marked_info+ is an array holding false,
# true values indicating whether the corresponding lines of code were reported
# as executed by Ruby. +count_info+ is an array of integers representing how
# many times each line of code has been executed (more precisely, how many
# events where reported by Ruby --- a single line might correspond to several
# events, e.g. many method calls).
#
# You can have several CodeCoverageAnalyzer objects at a time, and it is
# possible to nest the #run_hooked / #install_hook/#remove_hook blocks: each
# analyzer will manage its data separately. Note however that no special
# provision is taken to ignore code executed "inside" the CodeCoverageAnalyzer
# class. At any rate this will not pose a problem since it's easy to ignore it
# manually: just don't do
# lines, coverage, counts = analyzer.data("/path/to/lib/rcov.rb")
# if you're not interested in that information.
class CodeCoverageAnalyzer < DifferentialAnalyzer
@hook_level = 0
# defined this way instead of attr_accessor so that it's covered
def self.hook_level # :nodoc:
@hook_level
end
def self.hook_level=(x) # :nodoc:
@hook_level = x
end
def initialize
@script_lines__ = SCRIPT_LINES__
super(:install_coverage_hook, :remove_coverage_hook,
:reset_coverage)
end
# Return an array with the names of the files whose code was executed inside
# the block given to #run_hooked or between #install_hook and #remove_hook.
def analyzed_files
update_script_lines__
raw_data_relative.select do |file, lines|
@script_lines__.has_key?(file)
end.map{|fname,| fname}
end
# Return the available data about the requested file, or nil if none of its
# code was executed or it cannot be found.
# The return value is an array with three elements:
# lines, marked_info, count_info = analyzer.data("foo.rb")
# +lines+ is an array of strings representing the
# source code of <tt>foo.rb</tt>. +marked_info+ is an array holding false,
# true values indicating whether the corresponding lines of code were reported
# as executed by Ruby. +count_info+ is an array of integers representing how
# many times each line of code has been executed (more precisely, how many
# events where reported by Ruby --- a single line might correspond to several
# events, e.g. many method calls).
#
# The returned data corresponds to the aggregation of all the statistics
# collected in each #run_hooked or #install_hook/#remove_hook runs. You can
# reset the data at any time with #reset to start from scratch.
def data(filename)
raw_data = raw_data_relative
update_script_lines__
unless @script_lines__.has_key?(filename) &&
raw_data.has_key?(filename)
return nil
end
refine_coverage_info(@script_lines__[filename], raw_data[filename])
end
# Data for the first file matching the given regexp.
# See #data.
def data_matching(filename_re)
raw_data = raw_data_relative
update_script_lines__
match = raw_data.keys.sort.grep(filename_re).first
return nil unless match
refine_coverage_info(@script_lines__[match], raw_data[match])
end
# Execute the code in the given block, monitoring it in order to gather
# information about which code was executed.
def run_hooked; super end
# Start monitoring execution to gather code coverage and execution count
# information. Such data will be collected until #remove_hook is called.
#
# Use #run_hooked instead if possible.
def install_hook; super end
# Stop collecting code coverage and execution count information.
# #remove_hook will also stop collecting info if it is run inside a
# #run_hooked block.
def remove_hook; super end
# Remove the data collected so far. The coverage and execution count
# "history" will be erased, and further collection will start from scratch:
# no code is considered executed, and therefore all execution counts are 0.
# Right after #reset, #analyzed_files will return an empty array, and
# #data(filename) will return nil.
def reset; super end
def dump_coverage_info(formatters) # :nodoc:
update_script_lines__
raw_data_relative.each do |file, lines|
next if @script_lines__.has_key?(file) == false
lines = @script_lines__[file]
raw_coverage_array = raw_data_relative[file]
line_info, marked_info,
count_info = refine_coverage_info(lines, raw_coverage_array)
formatters.each do |formatter|
formatter.add_file(file, line_info, marked_info, count_info)
end
end
formatters.each{|formatter| formatter.execute}
end
private
def data_default; {} end
def raw_data_absolute
Rcov::RCOV__.generate_coverage_info
end
def aggregate_data(aggregated_data, delta)
delta.each_pair do |file, cov_arr|
dest = (aggregated_data[file] ||= Array.new(cov_arr.size, 0))
cov_arr.each_with_index do |x,i|
dest[i] ||= 0
dest[i] += x.to_i
end
end
end
def compute_raw_data_difference(first, last)
difference = {}
last.each_pair do |fname, cov_arr|
unless first.has_key?(fname)
difference[fname] = cov_arr.clone
else
orig_arr = first[fname]
diff_arr = Array.new(cov_arr.size, 0)
changed = false
cov_arr.each_with_index do |x, i|
diff_arr[i] = diff = (x || 0) - (orig_arr[i] || 0)
changed = true if diff != 0
end
difference[fname] = diff_arr if changed
end
end
difference
end
def refine_coverage_info(lines, covers)
marked_info = []
count_info = []
lines.size.times do |i|
c = covers[i]
marked_info << ((c && c > 0) ? true : false)
count_info << (c || 0)
end
script_lines_workaround(lines, marked_info, count_info)
end
# Try to detect repeated data, based on observed repetitions in line_info:
# this is a workaround for SCRIPT_LINES__[filename] including as many copies
# of the file as the number of times it was parsed.
def script_lines_workaround(line_info, coverage_info, count_info)
is_repeated = lambda do |div|
n = line_info.size / div
break false unless line_info.size % div == 0 && n > 1
different = false
n.times do |i|
things = (0...div).map { |j| line_info[i + j * n] }
if things.uniq.size != 1
different = true
break
end
end
! different
end
factors = braindead_factorize(line_info.size)
factors.each do |n|
if is_repeated[n]
line_info = line_info[0, line_info.size / n]
coverage_info = coverage_info[0, coverage_info.size / n]
count_info = count_info[0, count_info.size / n]
end
end if factors.size > 1 # don't even try if it's prime
[line_info, coverage_info, count_info]
end
def braindead_factorize(num)
return [0] if num == 0
return [-1] + braindead_factorize(-num) if num < 0
factors = []
while num % 2 == 0
factors << 2
num /= 2
end
size = num
n = 3
max = Math.sqrt(num)
while n <= max && n <= size
while size % n == 0
size /= n
factors << n
end
n += 2
end
factors << size if size != 1
factors
end
def update_script_lines__
@script_lines__ = @script_lines__.merge(SCRIPT_LINES__)
end
public
def marshal_dump # :nodoc:
# @script_lines__ is updated just before serialization so as to avoid
# missing files in SCRIPT_LINES__
ivs = {}
update_script_lines__
instance_variables.each{|iv| ivs[iv] = instance_variable_get(iv)}
ivs
end
def marshal_load(ivs) # :nodoc:
ivs.each_pair{|iv, val| instance_variable_set(iv, val)}
end
end # CodeCoverageAnalyzer
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/coverage_info.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/coverage_info.rb | # Rcov::CoverageInfo is but a wrapper for an array, with some additional
# checks. It is returned by FileStatistics#coverage.
class CoverageInfo
def initialize(coverage_array)
@cover = coverage_array.clone
end
# Return the coverage status for the requested line. There are four possible
# return values:
# * nil if there's no information for the requested line (i.e. it doesn't exist)
# * true if the line was reported by Ruby as executed
# * :inferred if rcov inferred it was executed, despite not being reported
# by Ruby.
# * false otherwise, i.e. if it was not reported by Ruby and rcov's
# heuristics indicated that it was not executed
def [](line)
@cover[line]
end
def []=(line, val) # :nodoc:
unless [true, false, :inferred].include? val
raise RuntimeError, "What does #{val} mean?"
end
return if line < 0 || line >= @cover.size
@cover[line] = val
end
# Return an Array holding the code coverage information.
def to_a
@cover.clone
end
def method_missing(meth, *a, &b) # :nodoc:
@cover.send(meth, *a, &b)
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/formatters/text_summary.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/formatters/text_summary.rb | module Rcov
class TextSummary < BaseFormatter # :nodoc:
def execute
puts summary
end
def summary
"%.1f%% %d file(s) %d Lines %d LOC" % [code_coverage * 100, @files.size, num_lines, num_code_lines]
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/formatters/html_coverage.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/formatters/html_coverage.rb | module Rcov
class HTMLCoverage < BaseFormatter # :nodoc:
require 'fileutils'
DEFAULT_OPTS = {:color => false, :fsr => 30, :destdir => "coverage",
:callsites => false, :cross_references => false,
:charset => nil }
def initialize(opts = {})
options = DEFAULT_OPTS.clone.update(opts)
super(options)
@dest = options[:destdir]
@css = options[:css]
@color = options[:color]
@fsr = options[:fsr]
@do_callsites = options[:callsites]
@do_cross_references = options[:cross_references]
@span_class_index = 0
@charset = options[:charset]
end
def execute
return if @files.empty?
FileUtils.mkdir_p @dest
# Copy collaterals
['screen.css','print.css','rcov.js','jquery-1.3.2.min.js','jquery.tablesorter.min.js'].each do |_file|
_src = File.expand_path("#{File.dirname(__FILE__)}/../templates/#{_file}")
FileUtils.cp(_src, File.join(@dest, "#{_file}"))
end
# Copy custom CSS, if any
if @css
begin
_src = File.expand_path("#{@dest}/../#{@css}")
FileUtils.cp(_src, File.join(@dest, "custom.css"))
rescue
@css = nil
end
end
create_index(File.join(@dest, "index.html"))
each_file_pair_sorted do |filename, fileinfo|
create_file(File.join(@dest, mangle_filename(filename)), fileinfo)
end
end
private
class SummaryFileInfo # :nodoc:
def initialize(obj)
@o = obj
end
def num_lines
@o.num_lines
end
def num_code_lines
@o.num_code_lines
end
def code_coverage
@o.code_coverage
end
def code_coverage_for_report
code_coverage * 100
end
def total_coverage
@o.total_coverage
end
def total_coverage_for_report
total_coverage * 100
end
def name
"TOTAL"
end
end
def create_index(destname)
doc = Rcov::Formatters::HtmlErbTemplate.new('index.html.erb',
:project_name => project_name,
:generated_on => Time.now,
:css => @css,
:rcov => Rcov,
:formatter => self,
:output_threshold => @output_threshold,
:total => SummaryFileInfo.new(self),
:files => each_file_pair_sorted.map{|k,v| v}
)
File.open(destname, "w") { |f| f.puts doc.render }
end
def create_file(destfile, fileinfo)
doc = Rcov::Formatters::HtmlErbTemplate.new('detail.html.erb',
:project_name => project_name,
:rcov_page_title => fileinfo.name,
:css => @css,
:generated_on => Time.now,
:rcov => Rcov,
:formatter => self,
:output_threshold => @output_threshold,
:fileinfo => fileinfo
)
File.open(destfile, "w") { |f| f.puts doc.render }
end
private
def project_name
Dir.pwd.split('/')[-1].split(/[^a-zA-Z0-9]/).map{|i| i.gsub(/[^a-zA-Z0-9]/,'').capitalize} * " " || ""
end
end
class HTMLProfiling < HTMLCoverage # :nodoc:
DEFAULT_OPTS = {:destdir => "profiling"}
def initialize(opts = {})
options = DEFAULT_OPTS.clone.update(opts)
super(options)
@max_cache = {}
@median_cache = {}
end
def default_title
"Bogo-profile information"
end
def default_color
if @color
"rgb(179,205,255)"
else
"rgb(255, 255, 255)"
end
end
def output_color_table?
false
end
def span_class(sourceinfo, marked, count)
full_scale_range = @fsr # dB
nz_count = sourceinfo.counts.select{|x| x && x != 0}
nz_count << 1 # avoid div by 0
max = @max_cache[sourceinfo] ||= nz_count.max
#avg = @median_cache[sourceinfo] ||= 1.0 *
# nz_count.inject{|a,b| a+b} / nz_count.size
median = @median_cache[sourceinfo] ||= 1.0 * nz_count.sort[nz_count.size/2]
max ||= 2
max = 2 if max == 1
if marked == true
count = 1 if !count || count == 0
idx = 50 + 1.0 * (500/full_scale_range) * Math.log(count/median) / Math.log(10)
idx = idx.to_i
idx = 0 if idx < 0
idx = 100 if idx > 100
"run#{idx}"
else
nil
end
end
end
class RubyAnnotation < BaseFormatter # :nodoc:
DEFAULT_OPTS = { :destdir => "coverage" }
def initialize(opts = {})
options = DEFAULT_OPTS.clone.update(opts)
super(options)
@dest = options[:destdir]
@do_callsites = true
@do_cross_references = true
@mangle_filename = Hash.new{ |h,base|
h[base] = Pathname.new(base).cleanpath.to_s.gsub(%r{^\w:[/\\]}, "").gsub(/\./, "_").gsub(/[\\\/]/, "-") + ".rb"
}
end
def execute
return if @files.empty?
FileUtils.mkdir_p @dest
each_file_pair_sorted do |filename, fileinfo|
create_file(File.join(@dest, mangle_filename(filename)), fileinfo)
end
end
private
def format_lines(file)
result = ""
format_line = "%#{file.num_lines.to_s.size}d"
file.num_lines.times do |i|
line = file.lines[i].chomp
marked = file.coverage[i]
count = file.counts[i]
result << create_cross_refs(file.name, i+1, line, marked) + "\n"
end
result
end
def create_cross_refs(filename, lineno, linetext, marked)
return linetext unless @callsite_analyzer && @do_callsites
ref_blocks = []
_get_defsites(ref_blocks, filename, lineno, linetext, ">>") do |ref|
if ref.file
ref.file.sub!(%r!^./!, '')
where = "at #{mangle_filename(ref.file)}:#{ref.line}"
else
where = "(C extension/core)"
end
"#{ref.klass}##{ref.mid} " + where + ""
end
_get_callsites(ref_blocks, filename, lineno, linetext, "<<") do |ref| # "
ref.file.sub!(%r!^./!, '')
"#{mangle_filename(ref.file||'C code')}:#{ref.line} " + "in #{ref.klass}##{ref.mid}"
end
create_cross_reference_block(linetext, ref_blocks, marked)
end
def create_cross_reference_block(linetext, ref_blocks, marked)
codelen = 75
if ref_blocks.empty?
if marked
return "%-#{codelen}s #o" % linetext
else
return linetext
end
end
ret = ""
@cross_ref_idx ||= 0
@known_files ||= sorted_file_pairs.map{|fname, finfo| normalize_filename(fname)}
ret << "%-#{codelen}s # " % linetext
ref_blocks.each do |refs, toplabel, label_proc|
unless !toplabel || toplabel.empty?
ret << toplabel << " "
end
refs.each do |dst|
dstfile = normalize_filename(dst.file) if dst.file
dstline = dst.line
label = label_proc.call(dst)
if dst.file && @known_files.include?(dstfile)
ret << "[[" << label << "]], "
else
ret << label << ", "
end
end
end
ret
end
def create_file(destfile, fileinfo)
#body = format_lines(fileinfo)
#File.open(destfile, "w") do |f|
#f.puts body
#f.puts footer(fileinfo)
#end
end
def footer(fileinfo)
s = "# Total lines : %d\n" % fileinfo.num_lines
s << "# Lines of code : %d\n" % fileinfo.num_code_lines
s << "# Total coverage : %3.1f%%\n" % [ fileinfo.total_coverage*100 ]
s << "# Code coverage : %3.1f%%\n\n" % [ fileinfo.code_coverage*100 ]
# prevents false positives on Emacs
s << "# Local " "Variables:\n" "# mode: " "rcov-xref\n" "# End:\n"
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/formatters/failure_report.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/formatters/failure_report.rb | module Rcov
class FailureReport < TextSummary # :nodoc:
def execute
puts summary
coverage = code_coverage * 100
if coverage < @failure_threshold
puts "You failed to satisfy the coverage theshold of #{@failure_threshold}%"
exit(1)
end
if (coverage - @failure_threshold) > 3
puts "Your coverage has significantly increased over your threshold of #{@failure_threshold}. Please increase it."
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/formatters/base_formatter.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/formatters/base_formatter.rb | module Rcov
class BaseFormatter # :nodoc:
require 'pathname'
require 'rbconfig'
RCOV_IGNORE_REGEXPS = [ /\A#{Regexp.escape(Pathname.new(::RbConfig::CONFIG['libdir']).cleanpath.to_s)}/,
/\btc_[^.]*.rb/,
/_test\.rb\z/,
/\btest\//,
/\bvendor\//,
/\A#{Regexp.escape(__FILE__)}\z/
]
DEFAULT_OPTS = { :ignore => RCOV_IGNORE_REGEXPS, :sort => :name, :sort_reverse => false,
:output_threshold => 101, :dont_ignore => [], :callsite_analyzer => nil, \
:comments_run_by_default => false }
def initialize(opts = {})
options = DEFAULT_OPTS.clone.update(opts)
@failure_threshold = options[:failure_threshold]
@files = {}
@ignore_files = options[:ignore]
@dont_ignore_files = options[:dont_ignore]
@sort_criterium = case options[:sort]
when :loc then lambda{|fname, finfo| finfo.num_code_lines}
when :coverage then lambda{|fname, finfo| finfo.code_coverage}
else lambda { |fname, finfo| fname }
end
@sort_reverse = options[:sort_reverse]
@output_threshold = options[:output_threshold]
@callsite_analyzer = options[:callsite_analyzer]
@comments_run_by_default = options[:comments_run_by_default]
@callsite_index = nil
@mangle_filename = Hash.new{|h,base|
h[base] = Pathname.new(base).cleanpath.to_s.gsub(%r{^\w:[/\\]}, "").gsub(/\./, "_").gsub(/[\\\/]/, "-") + ".html"
}
end
def add_file(filename, lines, coverage, counts)
old_filename = filename
filename = normalize_filename(filename)
SCRIPT_LINES__[filename] = SCRIPT_LINES__[old_filename]
if @ignore_files.any?{|x| x === filename} &&
!@dont_ignore_files.any?{|x| x === filename}
return nil
end
if @files[filename]
@files[filename].merge(lines, coverage, counts)
else
@files[filename] = FileStatistics.new(filename, lines, counts,
@comments_run_by_default)
end
end
def normalize_filename(filename)
File.expand_path(filename).gsub(/^#{Regexp.escape(Dir.getwd)}\//, '')
end
def mangle_filename(base)
@mangle_filename[base]
end
def each_file_pair_sorted(&b)
return sorted_file_pairs unless block_given?
sorted_file_pairs.each(&b)
end
def sorted_file_pairs
pairs = @files.sort_by do |fname, finfo|
@sort_criterium.call(fname, finfo)
end.select{|_, finfo| 100 * finfo.code_coverage < @output_threshold}
@sort_reverse ? pairs.reverse : pairs
end
def total_coverage
lines = 0
total = 0.0
@files.each do |k,f|
total += f.num_lines * f.total_coverage
lines += f.num_lines
end
return 0 if lines == 0
total / lines
end
def code_coverage
lines = 0
total = 0.0
@files.each do |k,f|
total += f.num_code_lines * f.code_coverage
lines += f.num_code_lines
end
return 0 if lines == 0
total / lines
end
def num_code_lines
lines = 0
@files.each{|k, f| lines += f.num_code_lines }
lines
end
def num_lines
lines = 0
@files.each{|k, f| lines += f.num_lines }
lines
end
private
def cross_references_for(filename, lineno)
return nil unless @callsite_analyzer
@callsite_index ||= build_callsite_index
@callsite_index[normalize_filename(filename)][lineno]
end
def reverse_cross_references_for(filename, lineno)
return nil unless @callsite_analyzer
@callsite_reverse_index ||= build_reverse_callsite_index
@callsite_reverse_index[normalize_filename(filename)][lineno]
end
def build_callsite_index
index = Hash.new{|h,k| h[k] = {}}
@callsite_analyzer.analyzed_classes.each do |classname|
@callsite_analyzer.analyzed_methods(classname).each do |methname|
defsite = @callsite_analyzer.defsite(classname, methname)
index[normalize_filename(defsite.file)][defsite.line] =
@callsite_analyzer.callsites(classname, methname)
end
end
index
end
def build_reverse_callsite_index
index = Hash.new{|h,k| h[k] = {}}
@callsite_analyzer.analyzed_classes.each do |classname|
@callsite_analyzer.analyzed_methods(classname).each do |methname|
callsites = @callsite_analyzer.callsites(classname, methname)
defsite = @callsite_analyzer.defsite(classname, methname)
callsites.each_pair do |callsite, count|
next unless callsite.file
fname = normalize_filename(callsite.file)
(index[fname][callsite.line] ||= []) << [classname, methname, defsite, count]
end
end
end
index
end
class XRefHelper < Struct.new(:file, :line, :klass, :mid, :count) # :nodoc:
end
def _get_defsites(ref_blocks, filename, lineno, linetext, label, &format_call_ref)
if @do_cross_references and
(rev_xref = reverse_cross_references_for(filename, lineno))
refs = rev_xref.map do |classname, methodname, defsite, count|
XRefHelper.new(defsite.file, defsite.line, classname, methodname, count)
end.sort_by{|r| r.count}.reverse
ref_blocks << [refs, label, format_call_ref]
end
end
def _get_callsites(ref_blocks, filename, lineno, linetext, label, &format_called_ref)
if @do_callsites and
(refs = cross_references_for(filename, lineno))
refs = refs.sort_by{|k,count| count}.map do |ref, count|
XRefHelper.new(ref.file, ref.line, ref.calling_class, ref.calling_method, count)
end.reverse
ref_blocks << [refs, label, format_called_ref]
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/formatters/text_report.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/formatters/text_report.rb | module Rcov
class TextReport < TextSummary # :nodoc:
def execute
print_lines
print_header
print_lines
each_file_pair_sorted do |fname, finfo|
name = fname.size < 52 ? fname : "..." + fname[-48..-1]
print_info(name, finfo.num_lines, finfo.num_code_lines,
finfo.code_coverage)
end
print_lines
print_info("Total", num_lines, num_code_lines, code_coverage)
print_lines
puts summary
end
def print_info(name, lines, loc, coverage)
puts "|%-51s | %5d | %5d | %5.1f%% |" % [name, lines, loc, 100 * coverage]
end
def print_lines
puts "+----------------------------------------------------+-------+-------+--------+"
end
def print_header
puts "| File | Lines | LOC | COV |"
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/formatters/text_coverage_diff.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/formatters/text_coverage_diff.rb | module Rcov
class TextCoverageDiff < BaseFormatter # :nodoc:
FORMAT_VERSION = [0, 1, 0]
DEFAULT_OPTS = { :textmode => :coverage_diff, :coverage_diff_mode => :record,
:coverage_diff_file => "coverage.info", :diff_cmd => "diff",
:comments_run_by_default => true }
HUNK_HEADER = /@@ -\d+,\d+ \+(\d+),(\d+) @@/
def SERIALIZER
# mfp> this was going to be YAML but I caught it failing at basic
# round-tripping, turning "\n" into "" and corrupting the data, so
# it must be Marshal for now
Marshal
end
def initialize(opts = {})
options = DEFAULT_OPTS.clone.update(opts)
@textmode = options[:textmode]
@color = options[:color]
@mode = options[:coverage_diff_mode]
@state_file = options[:coverage_diff_file]
@diff_cmd = options[:diff_cmd]
@gcc_output = options[:gcc_output]
super(options)
end
def execute
case @mode
when :record
record_state
when :compare
compare_state
else
raise "Unknown TextCoverageDiff mode: #{mode.inspect}."
end
end
def record_state
state = {}
each_file_pair_sorted do |filename, fileinfo|
state[filename] = {:lines => SCRIPT_LINES__[filename], :coverage => fileinfo.coverage.to_a,:counts => fileinfo.counts}
end
File.open(@state_file, "w") do |f|
self.SERIALIZER.dump([FORMAT_VERSION, state], f)
end
rescue
$stderr.puts <<-EOF
Couldn't save coverage data to #{@state_file}.
EOF
end # '
require 'tempfile'
def compare_state
return unless verify_diff_available
begin
format, prev_state = File.open(@state_file){|f| self.SERIALIZER.load(f) }
rescue
$stderr.puts <<-EOF
Couldn't load coverage data from #{@state_file}.
EOF
return # '
end
if !(Array === format) or
FORMAT_VERSION[0] != format[0] || FORMAT_VERSION[1] < format[1]
$stderr.puts <<-EOF
Couldn't load coverage data from #{@state_file}.
The file is saved in the format #{format.inspect[0..20]}.
This rcov executable understands #{FORMAT_VERSION.inspect}.
EOF
return # '
end
each_file_pair_sorted do |filename, fileinfo|
old_data = Tempfile.new("#{mangle_filename(filename)}-old")
new_data = Tempfile.new("#{mangle_filename(filename)}-new")
if prev_state.has_key? filename
old_code, old_cov = prev_state[filename].values_at(:lines, :coverage)
old_code.each_with_index do |line, i|
prefix = old_cov[i] ? " " : "!! "
old_data.write "#{prefix}#{line}"
end
else
old_data.write ""
end
old_data.close
SCRIPT_LINES__[filename].each_with_index do |line, i|
prefix = fileinfo.coverage[i] ? " " : "!! "
new_data.write "#{prefix}#{line}"
end
new_data.close
diff = `#{@diff_cmd} -u "#{old_data.path}" "#{new_data.path}"`
new_uncovered_hunks = process_unified_diff(filename, diff)
old_data.close!
new_data.close!
display_hunks(filename, new_uncovered_hunks)
end
end
def display_hunks(filename, hunks)
return if hunks.empty?
puts
puts "=" * 80
puts "!!!!! Uncovered code introduced in #{filename}"
hunks.each do |offset, lines|
if @gcc_output
lines.each_with_index do |line,i|
lineno = offset + i
flag = (/^!! / !~ line) ? "-" : ":"
prefix = "#{filename}#{flag}#{lineno}#{flag}"
puts "#{prefix}#{line[3..-1]}"
end
elsif @color
puts "### #{filename}:#{offset}"
lines.each do |line|
prefix = (/^!! / !~ line) ? "\e[32;40m" : "\e[31;40m"
puts "#{prefix}#{line[3..-1].chomp}\e[37;40m"
end
else
puts "### #{filename}:#{offset}"
puts lines
end
end
end
def verify_diff_available
old_stderr = STDERR.dup
old_stdout = STDOUT.dup
new_stderr = Tempfile.new("rcov_check_diff")
STDERR.reopen new_stderr.path
STDOUT.reopen new_stderr.path
retval = system "#{@diff_cmd} --version"
unless retval
old_stderr.puts <<EOF
The '#{@diff_cmd}' executable seems not to be available.
You can specify which diff executable should be used with --diff-cmd.
If your system doesn't have one, you might want to use Diff::LCS's:
gem install diff-lcs
and use --diff-cmd=ldiff.
EOF
return false
end
true
ensure
STDOUT.reopen old_stdout
STDERR.reopen old_stderr
new_stderr.close!
end
def process_unified_diff(filename, diff)
current_hunk = []
current_hunk_start = 0
keep_current_hunk = false
state = :init
interesting_hunks = []
diff.each_with_index do |line, i|
#puts "#{state} %5d #{line}" % i
case state
when :init
if md = HUNK_HEADER.match(line)
current_hunk = []
current_hunk_start = md[1].to_i
state = :body
end
when :body
case line
when HUNK_HEADER
new_start = $1.to_i
if keep_current_hunk
interesting_hunks << [current_hunk_start, current_hunk]
end
current_hunk_start = new_start
current_hunk = []
keep_current_hunk = false
when /^-/
# ignore
when /^\+!! /
keep_current_hunk = true
current_hunk << line[1..-1]
else
current_hunk << line[1..-1]
end
end
end
if keep_current_hunk
interesting_hunks << [current_hunk_start, current_hunk]
end
interesting_hunks
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/formatters/full_text_report.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/formatters/full_text_report.rb | module Rcov
class FullTextReport < BaseFormatter # :nodoc:
DEFAULT_OPTS = {:textmode => :coverage}
def initialize(opts = {})
options = DEFAULT_OPTS.clone.update(opts)
@textmode = options[:textmode]
@color = options[:color]
super(options)
end
def execute
each_file_pair_sorted do |filename, fileinfo|
puts "=" * 80
puts filename
puts "=" * 80
lines = SCRIPT_LINES__[filename]
unless lines
# try to get the source code from the global code coverage
# analyzer
re = /#{Regexp.escape(filename)}\z/
if $rcov_code_coverage_analyzer and
(data = $rcov_code_coverage_analyzer.data_matching(re))
lines = data[0]
end
end
(lines || []).each_with_index do |line, i|
case @textmode
when :counts
puts "%-70s| %6d" % [line.chomp[0,70], fileinfo.counts[i]]
when :gcc
puts "%s:%d:%s" % [filename, i+1, line.chomp] unless fileinfo.coverage[i]
when :coverage
if @color
prefix = fileinfo.coverage[i] ? "\e[32;40m" : "\e[31;40m"
puts "#{prefix}%s\e[37;40m" % line.chomp
else
prefix = fileinfo.coverage[i] ? " " : "!! "
puts "#{prefix}#{line}"
end
end
end
end
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/formatters/html_erb_template.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rcov-0.9.8-java/lib/rcov/formatters/html_erb_template.rb | module Rcov
module Formatters
class HtmlErbTemplate
attr_accessor :local_variables
def initialize(template_file, locals={})
require "erb"
template_path = File.expand_path("#{File.dirname(__FILE__)}/../templates/#{template_file}")
@template = ERB.new(File.read(template_path))
@local_variables = locals
@path_relativizer = Hash.new{|h,base|
h[base] = Pathname.new(base).cleanpath.to_s.gsub(%r{^\w:[/\\]}, "").gsub(/\./, "_").gsub(/[\\\/]/, "-") + ".html"
}
end
def render
@template.result(get_binding)
end
def coverage_threshold_classes(percentage)
return 110 if percentage == 100
return (1..10).find_all{|i| i * 10 > percentage}.map{|i| i.to_i * 10} * " "
end
def code_coverage_html(code_coverage_percentage, is_total=false)
%{<div class="percent_graph_legend"><tt class='#{ is_total ? 'coverage_total' : ''}'>#{ "%3.2f" % code_coverage_percentage }%</tt></div>
<div class="percent_graph">
<div class="covered" style="width:#{ code_coverage_percentage.round }px"></div>
<div class="uncovered" style="width:#{ 100 - code_coverage_percentage.round }px"></div>
</div>}
end
def file_filter_classes(file_path)
file_path.split('/')[0..-2] * " "
end
def relative_filename(path)
@path_relativizer[path]
end
def line_css(line_number)
case fileinfo.coverage[line_number]
when true
"marked"
when :inferred
"inferred"
else
"uncovered"
end
end
def method_missing(key, *args)
local_variables.has_key?(key) ? local_variables[key] : super
end
def get_binding
binding
end
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/spec/jetty_merb_spec.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/spec/jetty_merb_spec.rb | require File.dirname(__FILE__) + '/spec_helper.rb'
describe "binary executable with no command line arguments" do
it "should set adapter to merb" do
runner = mock("runner", :null_object => true)
current_dir = Dir.pwd
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:adapter)
config[:adapter].should == :merb
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_merb'
end
it "should provide the current execution dir as basedir" do
runner = mock("runner", :null_object => true)
current_dir = Dir.pwd
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:base)
config[:base].should == current_dir
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_merb'
end
it "should not set the context path by default" do
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should_not have_key(:context_path)
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_merb'
end
it "should not set the environment by default" do
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should_not have_key(:environment)
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_merb'
end
it "should set the port to 4000 by default" do
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:port)
config[:port].should == 4000
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_merb'
end
it "should not set classes dir by default" do
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should_not have_key(:classes_dir)
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_merb'
end
it "should not set lib dir by default" do
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should_not have_key(:lib_dir)
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_merb'
end
end
describe "binary executable with command line arguments" do
it "should take the first command line argument as basedir" do
ARGV[0] = '/any/app/dir'
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:base)
config[:base].should == '/any/app/dir'
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_merb'
end
it "should take --context-path command line option as context path" do
ARGV[0] = '--context-path'
ARGV[1] = '/myapp'
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:context_path)
config[:context_path].should == '/myapp'
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_merb'
end
it "should take -u command line option as context path" do
ARGV[0] = '-u'
ARGV[1] = '/myapp'
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:context_path)
config[:context_path].should == '/myapp'
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_merb'
end
it "should take --environment command line option as custom environment" do
ARGV[0] = '--environment'
ARGV[1] = 'production'
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:environment)
config[:environment].should == 'production'
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_merb'
end
it "should take -e command line option as custom environment" do
ARGV[0] = '-e'
ARGV[1] = 'production'
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:environment)
config[:environment].should == 'production'
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_merb'
end
it "should take --port command line option as custom server port" do
ARGV[0] = '--port'
ARGV[1] = '80'
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:port)
config[:port].should == 80
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_merb'
end
it "should take -p command line option as custom server port" do
ARGV[0] = '-p'
ARGV[1] = '80'
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:port)
config[:port].should == 80
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_merb'
end
it "should take --classes command line option as custom classes dir" do
ARGV[0] = '--classes'
ARGV[1] = 'build/java/classes'
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:classes_dir)
config[:classes_dir].should == 'build/java/classes'
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_merb'
end
it "should take --lib command line option as custom jars dir" do
ARGV[0] = '--lib'
ARGV[1] = 'java/jars'
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:lib_dir)
config[:lib_dir].should == 'java/jars'
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_merb'
end
it "should take --jars command line option as custom jars dir" do
ARGV[0] = '--jars'
ARGV[1] = 'java/jars'
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:lib_dir)
config[:lib_dir].should == 'java/jars'
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_merb'
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/spec/jetty_rails_spec.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/spec/jetty_rails_spec.rb | require File.dirname(__FILE__) + '/spec_helper.rb'
describe "binary executable with no command line arguments" do
it "should set adapter to rails" do
runner = mock("runner", :null_object => true)
current_dir = Dir.pwd
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:adapter)
config[:adapter].should == :rails
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_rails'
end
it "should provide the current execution dir as basedir" do
runner = mock("runner", :null_object => true)
current_dir = Dir.pwd
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:base)
config[:base].should == current_dir
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_rails'
end
it "should not set the context path by default" do
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should_not have_key(:context_path)
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_rails'
end
it "should not set the environment by default" do
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should_not have_key(:environment)
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_rails'
end
it "should set the port to 3000 by default" do
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:port)
config[:port].should == 3000
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_rails'
end
it "should not set classes dir by default" do
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should_not have_key(:classes_dir)
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_rails'
end
it "should not set lib dir by default" do
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should_not have_key(:lib_dir)
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_rails'
end
end
describe "binary executable with command line arguments" do
it "should take the first command line argument as basedir" do
ARGV[0] = '/any/app/dir'
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:base)
config[:base].should == '/any/app/dir'
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_rails'
end
it "should take --context-path command line option as context path" do
ARGV[0] = '--context-path'
ARGV[1] = '/myapp'
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:context_path)
config[:context_path].should == '/myapp'
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_rails'
end
it "should take -u command line option as context path" do
ARGV[0] = '-u'
ARGV[1] = '/myapp'
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:context_path)
config[:context_path].should == '/myapp'
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_rails'
end
it "should take --environment command line option as custom environment" do
ARGV[0] = '--environment'
ARGV[1] = 'production'
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:environment)
config[:environment].should == 'production'
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_rails'
end
it "should take -e command line option as custom environment" do
ARGV[0] = '-e'
ARGV[1] = 'production'
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:environment)
config[:environment].should == 'production'
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_rails'
end
it "should take --port command line option as custom server port" do
ARGV[0] = '--port'
ARGV[1] = '80'
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:port)
config[:port].should == 80
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_rails'
end
it "should take -p command line option as custom server port" do
ARGV[0] = '-p'
ARGV[1] = '80'
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:port)
config[:port].should == 80
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_rails'
end
it "should take --classes command line option as custom classes dir" do
ARGV[0] = '--classes'
ARGV[1] = 'build/java/classes'
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:classes_dir)
config[:classes_dir].should == 'build/java/classes'
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_rails'
end
it "should take --lib command line option as custom jars dir" do
ARGV[0] = '--lib'
ARGV[1] = 'java/jars'
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:lib_dir)
config[:lib_dir].should == 'java/jars'
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_rails'
end
it "should take --jars command line option as custom jars dir" do
ARGV[0] = '--jars'
ARGV[1] = 'java/jars'
runner = mock("runner", :null_object => true)
JettyRails::Runner.should_receive(:new) do |config|
config.should have_key(:lib_dir)
config[:lib_dir].should == 'java/jars'
runner
end
load File.dirname(__FILE__) + '/../bin/jetty_rails'
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/spec/spec_helper.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/spec/spec_helper.rb | begin
require 'spec'
rescue LoadError
require 'rubygems' unless ENV['NO_RUBYGEMS']
gem 'rspec'
require 'spec'
end
$:.unshift(File.dirname(__FILE__) + '/../lib')
$:.unshift(File.dirname(__FILE__) + '/../jetty-libs')
require 'jetty_rails'
require 'yaml'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/spec/jetty_rails/config_file_spec.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/spec/jetty_rails/config_file_spec.rb | require File.dirname(__FILE__) + '/../spec_helper'
describe JettyRails::Runner, "with config file containing several servers and apps" do
before do
@yaml_config = YAML.load_file(File.join(File.dirname(__FILE__), '..', 'config.yml'))
end
it "should instantiate runner with config.yml and setup servers" do
runner = JettyRails::Runner.new(@yaml_config)
runner.servers.size.should == 3
runner.servers[4000].should_not == nil
runner.servers[3000].should_not == nil
server = runner.servers[8080]
server.should_not == nil
server.app_contexts.size.should == 2
end
it "should setup correct context_paths" do
runner = JettyRails::Runner.new(@yaml_config)
runner.servers[4000].config[:context_path].should == "/testB"
runner.servers[3000].config[:context_path].should == "/testA"
runner.servers[8080].config[:context_path].should == "/"
runner.servers[8080].app_contexts[0].context_path.should == "/testC"
runner.servers[8080].app_contexts[1].context_path.should == "/testD"
end
it "should setup correct adapters" do
runner = JettyRails::Runner.new(@yaml_config)
runner.servers[4000].config[:adapter].should == :merb
runner.servers[3000].config[:adapter].should == :rails
runner.servers[8080].config[:adapter].should == :rails # default
runner.servers[8080].app_contexts[0].config[:adapter].should == :merb
runner.servers[8080].app_contexts[1].config[:adapter].should == :rails
end
it "should inherit environment" do
runner = JettyRails::Runner.new(@yaml_config)
runner.servers[4000].config[:environment].should == "production"
runner.servers[3000].config[:environment].should == "development"
runner.servers[8080].config[:environment].should == "production"
runner.servers[8080].app_contexts[0].config[:environment].should =="test"
runner.servers[8080].app_contexts[1].config[:environment].should =="production"
end
it "should setup jruby environment" do
runner = JettyRails::Runner.new(@yaml_config)
runner.servers[4000].app_contexts.first.adapter.init_params['jruby.min.runtimes'].should == '1'
runner.servers[4000].app_contexts.first.adapter.init_params['jruby.max.runtimes'].should == '2'
runner.servers[3000].app_contexts.first.adapter.init_params['jruby.min.runtimes'].should == '2'
runner.servers[3000].app_contexts.first.adapter.init_params['jruby.max.runtimes'].should == '2'
end
it "should setup the server thread pool" do
runner = JettyRails::Runner.new(@yaml_config)
runner.servers[4000].server.thread_pool.max_threads.should == 40
runner.servers[4000].server.thread_pool.min_threads.should == 1
end
it "should setup the server acceptors" do
runner = JettyRails::Runner.new(@yaml_config)
runner.servers[3000].server.connectors[0].acceptors.should == 20
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/spec/jetty_rails/runner_spec.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/spec/jetty_rails/runner_spec.rb | require File.dirname(__FILE__) + '/../spec_helper'
describe JettyRails::Runner, "with no extra configuration (rails adapter)" do
it "should require basedir to be run" do
lambda { JettyRails::Runner.new }.should raise_error
end
it "should receive basedir configuration" do
runner = JettyRails::Runner.new :base => '/any/app/dir'
runner.servers[8080].config.should have_key(:base)
runner.servers[8080].config[:base].should == '/any/app/dir'
end
it "should default to development environment" do
runner = JettyRails::Runner.new :base => Dir.pwd
runner.servers[8080].config.should have_key(:environment)
runner.servers[8080].config[:environment].should == 'development'
runner.servers[8080].app_contexts.first.init_params['rails.env'].should == 'development'
end
it "should default to the root context path" do
runner = JettyRails::Runner.new :base => Dir.pwd
runner.servers[8080].config.should have_key(:context_path)
runner.servers[8080].config[:context_path].should == '/'
runner.servers[8080].app_contexts.first.context_path.should == '/'
end
it "should set server default port to 8080" do
runner = JettyRails::Runner.new :base => Dir.pwd
runner.servers[8080].config.should have_key(:port)
runner.servers[8080].config[:port].should == 8080
end
it "should default lib_dir to lib" do
runner = JettyRails::Runner.new :base => Dir.pwd
runner.servers[8080].config.should have_key(:lib_dir)
runner.servers[8080].config[:lib_dir].should == 'lib'
end
it "should set rails root" do
runner = JettyRails::Runner.new :base => Dir.pwd
runner.servers[8080].app_contexts.first.init_params['rails.root'].should == '/'
end
it "should set public root" do
runner = JettyRails::Runner.new :base => Dir.pwd
runner.servers[8080].app_contexts.first.init_params['public.root'].should == '/public'
end
it "should set gem path" do
original = ENV['GEM_PATH']
ENV['GEM_PATH'] = nil
begin
runner = JettyRails::Runner.new :base => Dir.pwd
runner.servers[8080].app_contexts.first.init_params['gem.path'].should == 'tmp/war/WEB-INF/gems'
ensure
ENV['GEM_PATH'] = original
end
end
it "should set gem path from environment" do
original = ENV['GEM_PATH']
ENV['GEM_PATH'] = "/usr/lib/ruby/gems/1.8/gems"
begin
runner = JettyRails::Runner.new :base => Dir.pwd
runner.servers[8080].app_contexts.first.init_params['gem.path'].should == ENV['GEM_PATH']
ensure
ENV['GEM_PATH'] = original
end
end
it "should install RailsServletContextListener" do
runner = JettyRails::Runner.new :base => Dir.pwd
listeners = runner.servers[8080].app_contexts.first.event_listeners
listeners.size.should == 1
listeners[0].should be_kind_of(JettyRails::Rack::RailsServletContextListener)
end
it "should have handlers for static and dynamic content" do
runner = JettyRails::Runner.new :base => Dir.pwd
runner.servers[8080].server.handlers.size.should == 2
resource_handlers = runner.servers[8080].server.getChildHandlersByClass(JettyRails::Jetty::Handler::ResourceHandler)
resource_handlers.size.should == 1
webapp_handlers = runner.servers[8080].server.getChildHandlersByClass(JettyRails::Jetty::Handler::WebAppContext)
webapp_handlers.size.should == 1
end
it "should delegate to rails handler if requested dir has no welcome file" do
runner = JettyRails::Runner.new :base => Dir.pwd
delegate_handler = runner.servers[8080].server.handlers[0]
delegate_handler.should be_kind_of(JettyRails::Handler::DelegateOnErrorsHandler)
end
end
describe JettyRails::Runner, "with custom configuration" do
it "should allow to override the environment" do
runner = JettyRails::Runner.new :base => Dir.pwd, :environment => 'production'
runner.servers[8080].config.should have_key(:environment)
runner.servers[8080].config[:environment].should == 'production'
runner.servers[8080].app_contexts.first.init_params['rails.env'].should == 'production'
end
it "should allow to override the context path" do
runner = JettyRails::Runner.new :base => Dir.pwd, :context_path => "/myapp"
runner.servers[8080].config.should have_key(:context_path)
runner.servers[8080].config[:context_path].should == '/myapp'
runner.servers[8080].app_contexts.first.context_path.should == '/myapp'
end
it "should allow to override the server port" do
runner = JettyRails::Runner.new :base => Dir.pwd, :port => 8585
runner.servers[8585].config.should have_key(:port)
runner.servers[8585].config[:port].should == 8585
runner.servers[8585].server.connectors[0].port.should == 8585
end
it "should handle custom context paths for static and dynamic content" do
runner = JettyRails::Runner.new :base => Dir.pwd, :context_path => "/myapp"
context_handlers = runner.servers[8080].server.getChildHandlersByClass(JettyRails::Jetty::Handler::ContextHandler)
context_handlers.size.should == 2 # one for static, one for dynamic
end
end
describe JettyRails::Runner, "with merb adapter" do
it "should set merb root" do
runner = JettyRails::Runner.new :adapter => :merb, :base => Dir.pwd
runner.servers[8080].app_contexts.first.init_params['merb.root'].should == '/'
end
it "should set public root" do
runner = JettyRails::Runner.new :adapter => :merb, :base => Dir.pwd
runner.servers[8080].app_contexts.first.init_params['public.root'].should == '/public'
end
it "should set gem path" do
original = ENV['GEM_PATH']
ENV['GEM_PATH'] = nil
begin
runner = JettyRails::Runner.new :adapter => :merb, :base => Dir.pwd
runner.servers[8080].app_contexts.first.init_params['gem.path'].should == 'tmp/war/WEB-INF/gems'
ensure
ENV['GEM_PATH'] = original
end
end
it "should set merb environment to development" do
runner = JettyRails::Runner.new :adapter => :merb, :base => Dir.pwd
runner.servers[8080].app_contexts.first.init_params['merb.environment'].should == 'development'
end
it "should install MerbServletContextListener and SignalHandler" do
runner = JettyRails::Runner.new :adapter => :merb, :base => Dir.pwd
listeners = runner.servers[8080].app_contexts.first.event_listeners
listeners.size.should == 2
listeners[0].should be_kind_of(JettyRails::Rack::MerbServletContextListener)
listeners[1].should be_kind_of(JettyRails::Adapters::MerbAdapter::SignalHandler)
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/spec/jetty_rails/handler/delegate_on_errors_handler_spec.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/spec/jetty_rails/handler/delegate_on_errors_handler_spec.rb | require File.dirname(__FILE__) + '/../../spec_helper'
describe JettyRails::Handler::DelegateOnErrorsHandler do
it "should decorate the original HttpServletResponse" do
original = mock("original handler", :null_object => true)
original.should_receive(:handle).once do |target, request, response, dispatch|
response.should be_kind_of(JettyRails::Handler::DelegateOnErrorsResponse)
end
delegator = JettyRails::Handler::DelegateOnErrorsHandler.new
delegator.handler = original
delegator.handle('/any/target', mock("request"), mock("response"), 0)
end
end
describe JettyRails::Handler::DelegateOnErrorsResponse do
it "should delegate all method calls to wrapped response" do
response = mock('original response')
response.should_receive(:getContentType).once.and_return('text/html; charset=UTF-8')
wrapper = JettyRails::Handler::DelegateOnErrorsResponse.new response, mock('request')
wrapper.getContentType.should == 'text/html; charset=UTF-8'
end
it "should set request to not handled state on error" do
request = mock('request')
request.should_receive(:handled=).once.with(false)
wrapper = JettyRails::Handler::DelegateOnErrorsResponse.new mock('response'), request
wrapper.sendError(403)
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails.rb | jetty_libs_dir = "#{File.dirname(__FILE__)}/../jetty-libs"
$:.unshift(File.expand_path(jetty_libs_dir)) unless
$:.include?(jetty_libs_dir) || $:.include?(File.expand_path(jetty_libs_dir))
$:.unshift(File.dirname(__FILE__)) unless
$:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
require "java"
require "rubygems"
require "activesupport"
require "jetty_rails/jars"
require "jetty_rails/adapters/abstract_adapter"
require "jetty_rails/adapters/rails_adapter"
require "jetty_rails/adapters/merb_adapter"
require "jetty_rails/runner"
require "jetty_rails/server"
require "jetty_rails/handler/delegate_on_errors_handler"
require "jetty_rails/handler/public_directory_handler"
require "jetty_rails/handler/web_app_handler"
require "jetty_rails/config/command_line_reader"
module JettyRails
VERSION = '0.8.1'
JETTY_RAILS_HOME = File.dirname(__FILE__) + "/.." unless defined?(JETTY_RAILS_HOME)
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails/warbler_reader.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails/warbler_reader.rb | class WarblerReader
def initialize(config)
# TODO ignore jruby and jruby-rack
warbler_config = load("#{config[:base]}/config/warble.rb")
warbler_config.java_libs.each do |jar|
require jar
end
# TODO require custom classes
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails/jars.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails/jars.rb | module JettyRails
require "servlet-api-2.5-6.1.14"
require "jetty-6.1.14"
require "jetty-util-6.1.14"
require "jetty-plus-6.1.14"
require "core-3.1.1"
require "jsp-api-2.1"
require "jsp-2.1"
module Jetty
include_package "org.mortbay.jetty"
include_package "org.mortbay.jetty.servlet"
include_package "org.mortbay.jetty.nio"
include_package "org.mortbay.resource"
module Handler
include_package "org.mortbay.jetty.handler"
include_package "org.mortbay.jetty.webapp"
end
module Thread
include_package "org.mortbay.thread"
end
module Security
include_package 'org.mortbay.jetty.security'
end
end
require "jruby-rack-1.0.1"
module Rack
include_package "org.jruby.rack"
include_package "org.jruby.rack.rails"
include_package "org.jruby.rack.merb"
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails/runner.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails/runner.rb | require "jruby"
module JettyRails
class Runner
attr_reader :servers
def initialize(config = {})
@servers = {}
config.symbolize_keys!
if config[:servers].nil?
add_server(config)
else
config[:servers].each do |server_config|
server_config.symbolize_keys!
server_config.reverse_merge!(config)
server_config.delete(:servers)
add_server(server_config)
end
end
end
def add_server(config = {})
server = JettyRails::Server.new(config)
@servers[server.config[:port]] = server
end
def start
server_threads = ThreadGroup.new
@servers.each do |base, server|
log("Starting server #{base}")
server_threads.add(Thread.new do
server.start
end)
end
server_threads.list.each {|thread| thread.join } unless server_threads.list.empty?
end
private
def log(msg)
$stdout.puts(msg)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails/server.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails/server.rb | module JettyRails
class Server
attr_reader :config
attr_reader :app_contexts
attr_reader :server
@@defaults = {
:adapter => :rails,
:environment => 'development',
:context_path => '/',
:lib_dir => 'lib',
:classes_dir => 'classes',
:web_xml => 'config/web.xml',
:port => 8080,
:ssl_port => 8081,
:jruby_min_runtimes => 1,
:jruby_max_runtimes => 5,
:thread_pool_max => 20,
:thread_pool_min => 1,
:acceptor_size => 5
}
def initialize(config = {})
java.lang.System.setProperty('JETTY_HTTP_PORT', config[:port].to_s)
java.lang.System.setProperty('JETTY_HTTPS_PORT', config[:ssl_port].to_s)
@config = config.symbolize_keys!.reverse_merge!(@@defaults)
@server = Jetty::Server.new
# setup the thread pool for the server
thread_pool = Jetty::Thread::QueuedThreadPool.new
thread_pool.set_max_threads(config[:thread_pool_max])
thread_pool.set_min_threads(config[:thread_pool_min])
@server.set_thread_pool(thread_pool)
connector = Jetty::SelectChannelConnector.new
connector.set_acceptors(config[:acceptor_size])
connector.port = config[:port]
@server.add_connector(connector)
ssl_connector = Jetty::Security::SslSocketConnector.new
ssl_connector.port = config[:ssl_port]
ssl_connector.set_acceptors(config[:acceptor_size])
ssl_connector.set_keystore('ssl/keystore')
ssl_connector.set_password('123456')
ssl_connector.set_key_password('123456')
ssl_connector.set_truststore('ssl/keystore')
ssl_connector.set_trust_password('123456')
@server.add_connector(ssl_connector)
if config[:apps].nil?
add_app(config)
else
config[:apps].each do |app_config|
app_config.reverse_merge!(config)
app_config.delete(:apps)
add_app(app_config)
end
end
end
def add_app(config)
raise 'Base dir to be run must be provided' unless config[:base]
config[:context_path].extend ContextPath
@server.add_handler(JettyRails::Handler::PublicDirectoryHandler.new(config))
web_app_handler = JettyRails::Handler::WebAppHandler.new(config)
(@app_contexts ||= []) << web_app_handler
@server.add_handler(web_app_handler)
end
def start
@server.start
@server.join
end
private
def read_warble_config
require 'warbler'
WarblerReader.new(config)
end
module ContextPath
def root?
self == '/'
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails/adapters/rails_adapter.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails/adapters/rails_adapter.rb | module JettyRails
module Adapters
class RailsAdapter < AbstractAdapter
def init_params
# please refer to goldspike and jruby-rack documentation
# in: PoolingRackApplicationFactory
@rails_params ||= {
'rails.root' => '/',
'rails.env' => config[:environment]
}.merge(base_init_params)
end
def event_listeners
[ Rack::RailsServletContextListener.new ]
end
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails/adapters/merb_adapter.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails/adapters/merb_adapter.rb | module JettyRails
module Adapters
class MerbAdapter < AbstractAdapter
def init_params
# please refer to goldspike and jruby-rack documentation
@merb_params ||= {
'merb.root' => '/',
'merb.environment' => config[:environment]
}.merge(base_init_params)
end
def event_listeners
[ Rack::MerbServletContextListener.new, SignalHandler.new ]
end
class SignalHandler
include Java::JavaxServlet::ServletContextListener
def contextInitialized(cfg)
trap("INT") do
puts "\nbye!"
java.lang.System.exit(0)
end
end
def contextDestroyed(cfg)
end
end
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails/adapters/abstract_adapter.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails/adapters/abstract_adapter.rb | module JettyRails
module Adapters
class AbstractAdapter
attr_reader :config
def initialize(config)
@config = config
end
def base_init_params()
@base_init_params ||= {
'public.root' => '/public',
'gem.path' => config[:gem_path] || ENV['GEM_PATH'] || 'tmp/war/WEB-INF/gems',
'jruby.initial.runtimes' => "#{config[:jruby_min_runtimes]}",
'jruby.min.runtimes' => "#{config[:jruby_min_runtimes]}",
'jruby.max.runtimes' => "#{config[:jruby_max_runtimes]}"
}
end
def event_listeners
[]
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails/config/rdoc_fix.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails/config/rdoc_fix.rb | require 'rdoc/usage'
# fix to work with rubygems (use current file instead of main)
def RDoc.usage_no_exit(*args)
comment = File.open(File.join(File.dirname(__FILE__), %w(.. .. .. bin), File.basename($0))) do |file|
find_comment(file)
end
comment = comment.gsub(/^\s*#/, '')
markup = SM::SimpleMarkup.new
flow_convertor = SM::ToFlow.new
flow = markup.convert(comment, flow_convertor)
format = "plain"
unless args.empty?
flow = extract_sections(flow, args)
end
options = RI::Options.instance
if args = ENV["RI"]
options.parse(args.split)
end
formatter = options.formatter.new(options, "")
formatter.display_flow(flow)
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails/config/command_line_reader.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails/config/command_line_reader.rb | require 'getoptlong'
require 'jetty_rails/config/rdoc_fix'
class CommandLineReader
def default_config()
@@config ||= {
:rails => {
:base => Dir.pwd,
:port => 3000,
:ssl_port => 3443,
:config_file => "#{File.join(Dir.pwd, 'config', 'jetty_rails.yml')}",
:adapter => :rails
},
:merb => {
:base => Dir.pwd,
:port => 4000,
:config_file => "#{File.join(Dir.pwd, 'config', 'jetty_merb.yml')}",
:adapter => :merb
}
}
end
def read(default_adapter = :rails)
config = default_config[default_adapter]
opts = GetoptLong.new(
[ '--version', '-v', GetoptLong::NO_ARGUMENT ],
[ '--help', '-h', GetoptLong::NO_ARGUMENT ],
[ '--context-path', '-u', GetoptLong::REQUIRED_ARGUMENT ],
[ '--port', '-p', GetoptLong::REQUIRED_ARGUMENT ],
[ '--ssl-port', '-s', GetoptLong::REQUIRED_ARGUMENT ],
[ '--environment', '-e', GetoptLong::REQUIRED_ARGUMENT ],
[ '--lib', '--jars', GetoptLong::REQUIRED_ARGUMENT ],
[ '--classes', GetoptLong::REQUIRED_ARGUMENT ],
[ '--config', '-c', GetoptLong::OPTIONAL_ARGUMENT ]
)
opts.each do |opt, arg|
case opt
when '--version'
require 'jetty_rails/version'
puts "JettyRails version #{JettyRails::VERSION::STRING} - http://jetty-rails.rubyforge.org"
exit(0)
when '--help'
RDoc::usage
when '--context-path'
config[:context_path] = arg
when '--port'
config[:port] = arg.to_i
when '--ssl-port'
config[:ssl_port] = arg.to_i
when '--environment'
config[:environment] = arg
when '--classes'
config[:classes_dir] = arg
when '--lib'
config[:lib_dir] = arg
when '--config'
config[:config_file] = arg if !arg.nil? && arg != ""
config.merge!(YAML.load_file(config[:config_file]))
end
end
config[:base] = ARGV.shift unless ARGV.empty?
config
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails/handler/web_app_handler.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails/handler/web_app_handler.rb | module JettyRails
module Handler
class WebAppHandler < Jetty::Handler::WebAppContext
attr_reader :config, :adapter
def initialize(config)
super("/", config[:context_path])
@config = config
self.class_loader = each_context_has_its_own_classloader
self.resource_base = "#{config[:base]}/public"
self.descriptor = config[:web_xml]
add_classes_dir_to_classpath(config)
add_lib_dir_jars_to_classpath(config)
@adapter = adapter_for(config[:adapter])
self.init_params = @adapter.init_params
unless File.exist?(self.descriptor)
@adapter.event_listeners.each do |listener|
add_event_listener(listener)
end
add_filter(rack_filter, "/*", Jetty::Context::DEFAULT)
end
end
def self.add_adapter(adapter_key, adapter)
adapters[adapter_key] = adapter
end
def self.adapters
@adapters ||= {
:rails => JettyRails::Adapters::RailsAdapter,
:merb => JettyRails::Adapters::MerbAdapter
}
end
def adapters
self.class.adapters
end
alias :get_from_public_otherwise :getResource
def getResource(resource)
return fix_for_base_url if resource == '/'
get_from_public_otherwise resource
end
protected
def rack_filter
Jetty::FilterHolder.new(Rack::RackFilter.new)
end
def adapter_for(kind)
adapters[kind.to_sym].new(@config)
end
private
def fix_for_base_url
Jetty::FileResource.new(java.io.File.new(config[:base]).to_url)
end
def add_lib_dir_jars_to_classpath(config)
lib_dir = "#{config[:base]}/#{config[:lib_dir]}/**/*.jar"
Dir[lib_dir].each do |jar|
url = java.io.File.new(jar).to_url
self.class_loader.add_url(url)
end
end
def add_classes_dir_to_classpath(config)
classes_dir = "#{config[:base]}/#{config[:classes_dir]}"
url = java.io.File.new(classes_dir).to_url
self.class_loader.add_url(url)
end
def each_context_has_its_own_classloader()
org.jruby.util.JRubyClassLoader.new(JRuby.runtime.jruby_class_loader)
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails/handler/delegate_on_errors_handler.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails/handler/delegate_on_errors_handler.rb | module JettyRails
module Handler
class DelegateOnErrorsResponse
include Java::JavaxServletHttp::HttpServletResponse
def initialize(original, request)
@original = original
@request = request
end
def sendError(status_code)
@request.handled = false
end
def method_missing(method, *args, &blk)
@original.send(method, *args, &blk)
end
end
class DelegateOnErrorsHandler < Jetty::Handler::HandlerWrapper
def handle(target, request, response, dispatch)
decorated_response = DelegateOnErrorsResponse.new(response, request)
self.handler.handle(target, request, decorated_response, dispatch)
end
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails/handler/public_directory_handler.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jetty-rails-0.8.1/lib/jetty_rails/handler/public_directory_handler.rb |
module JettyRails
module Handler
class PublicDirectoryHandler < JettyRails::Handler::DelegateOnErrorsHandler
def initialize(config)
super()
@config = config
@resources = Jetty::Handler::ResourceHandler.new
@resources.resource_base = @config[:base] + '/public'
context_capable = add_context_capability_to @resources
self.handler = context_capable
end
def add_context_capability_to(handler)
return handler if @config[:context_path].root?
context_handler = Jetty::Handler::ContextHandler.new(@config[:context_path])
context_handler.handler = handler
context_handler
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/install.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/install.rb | #!/usr/bin/env ruby
require 'rbconfig'
require 'fileutils'
include FileUtils::Verbose
include Config
bindir = CONFIG["bindir"]
cd 'bin' do
filename = 'edit_json.rb'
#install(filename, bindir)
end
sitelibdir = CONFIG["sitelibdir"]
cd 'lib' do
install('json.rb', sitelibdir)
mkdir_p File.join(sitelibdir, 'json')
for file in Dir['json/**/*.{rb,xpm}']
d = File.join(sitelibdir, file)
mkdir_p File.dirname(d)
install(file, d)
end
install(File.join('json', 'editor.rb'), File.join(sitelibdir,'json'))
install(File.join('json', 'json.xpm'), File.join(sitelibdir,'json'))
end
warn " *** Installed PURE ruby library."
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/benchmarks/parser2_benchmark.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/benchmarks/parser2_benchmark.rb | #!/usr/bin/env ruby
# CODING: UTF-8
require 'rbconfig'
RUBY_PATH=File.join(Config::CONFIG['bindir'], Config::CONFIG['ruby_install_name'])
RAKE_PATH=File.join(Config::CONFIG['bindir'], 'rake')
require 'bullshit'
case ARGV.first
when 'ext'
require 'json/ext'
when 'pure'
require 'json/pure'
when 'yaml'
require 'yaml'
require 'json/pure'
when 'rails'
require 'active_support'
require 'json/pure'
when 'yajl'
require 'yajl'
require 'json/pure'
else
require 'json/pure'
end
module Parser2BenchmarkCommon
include JSON
def setup
@big = @json = File.read(File.join(File.dirname(__FILE__), 'ohai.json'))
end
def generic_reset_method
@result == @big or raise "not equal"
end
end
class Parser2BenchmarkExt < Bullshit::RepeatCase
include Parser2BenchmarkCommon
warmup yes
iterations 2000
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def benchmark_parser
@result = JSON.parse(@json)
end
alias reset_parser generic_reset_method
def benchmark_parser_symbolic
@result = JSON.parse(@json, :symbolize_names => true)
end
alias reset_parser_symbolc generic_reset_method
end
class Parser2BenchmarkPure < Bullshit::RepeatCase
include Parser2BenchmarkCommon
warmup yes
iterations 400
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def benchmark_parser
@result = JSON.parse(@json)
end
alias reset_parser generic_reset_method
def benchmark_parser_symbolic
@result = JSON.parse(@json, :symbolize_names => true)
end
alias reset_parser_symbolc generic_reset_method
end
class Parser2BenchmarkYAML < Bullshit::RepeatCase
warmup yes
iterations 400
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def setup
@big = @json = File.read(File.join(File.dirname(__FILE__), 'ohai.json'))
end
def benchmark_parser
@result = YAML.load(@json)
end
def generic_reset_method
@result == @big or raise "not equal"
end
end
class Parser2BenchmarkRails < Bullshit::RepeatCase
warmup yes
iterations 400
truncate_data do
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def setup
a = [ nil, false, true, "fÖß\nÄr", [ "n€st€d", true ], { "fooß" => "bär", "qu\r\nux" => true } ]
@big = a * 100
@json = JSON.generate(@big)
end
def benchmark_parser
@result = ActiveSupport::JSON.decode(@json)
end
def generic_reset_method
@result == @big or raise "not equal"
end
end
class Parser2BenchmarkYajl < Bullshit::RepeatCase
warmup yes
iterations 2000
truncate_data do
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def setup
@big = @json = File.read(File.join(File.dirname(__FILE__), 'ohai.json'))
end
def benchmark_parser
@result = Yajl::Parser.new.parse(@json)
end
def generic_reset_method
@result == @big or raise "not equal"
end
end
if $0 == __FILE__
Bullshit::Case.autorun false
case ARGV.first
when 'ext'
Parser2BenchmarkExt.run
when 'pure'
Parser2BenchmarkPure.run
when 'yaml'
Parser2BenchmarkYAML.run
when 'rails'
Parser2BenchmarkRails.run
when 'yajl'
Parser2BenchmarkYajl.run
else
system "#{RAKE_PATH} clean"
system "#{RUBY_PATH} #$0 yaml"
system "#{RUBY_PATH} #$0 rails"
system "#{RUBY_PATH} #$0 pure"
system "#{RAKE_PATH} compile_ext"
system "#{RUBY_PATH} #$0 ext"
system "#{RUBY_PATH} #$0 yajl"
Bullshit.compare do
output_filename File.join(File.dirname(__FILE__), 'data', 'Parser2BenchmarkComparison.log')
benchmark Parser2BenchmarkExt, :parser, :load => yes
benchmark Parser2BenchmarkExt, :parser_symbolic, :load => yes
benchmark Parser2BenchmarkPure, :parser, :load => yes
benchmark Parser2BenchmarkPure, :parser_symbolic, :load => yes
benchmark Parser2BenchmarkYAML, :parser, :load => yes
benchmark Parser2BenchmarkRails, :parser, :load => yes
benchmark Parser2BenchmarkYajl, :parser, :load => yes
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/benchmarks/parser_benchmark.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/benchmarks/parser_benchmark.rb | #!/usr/bin/env ruby
# CODING: UTF-8
require 'rbconfig'
RUBY_PATH=File.join(Config::CONFIG['bindir'], Config::CONFIG['ruby_install_name'])
RAKE_PATH=File.join(Config::CONFIG['bindir'], 'rake')
require 'bullshit'
case ARGV.first
when 'ext'
require 'json/ext'
when 'pure'
require 'json/pure'
when 'yaml'
require 'yaml'
require 'json/pure'
when 'rails'
require 'active_support'
require 'json/pure'
when 'yajl'
require 'yajl'
require 'json/pure'
else
require 'json/pure'
end
module ParserBenchmarkCommon
include JSON
def setup
a = [ nil, false, true, "fÖß\nÄr", [ "n€st€d", true ], { "fooß" => "bär", "qu\r\nux" => true } ]
@big = a * 100
@json = JSON.generate(@big)
end
def generic_reset_method
@result == @big or raise "not equal"
end
end
class ParserBenchmarkExt < Bullshit::RepeatCase
include ParserBenchmarkCommon
warmup yes
iterations 2000
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def benchmark_parser
@result = JSON.parse(@json)
end
alias reset_parser generic_reset_method
def benchmark_parser_symbolic
@result = JSON.parse(@json, :symbolize_names => true)
end
alias reset_parser_symbolc generic_reset_method
end
class ParserBenchmarkPure < Bullshit::RepeatCase
include ParserBenchmarkCommon
warmup yes
iterations 400
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def benchmark_parser
@result = JSON.parse(@json)
end
alias reset_parser generic_reset_method
def benchmark_parser_symbolic
@result = JSON.parse(@json, :symbolize_names => true)
end
alias reset_parser_symbolc generic_reset_method
end
class ParserBenchmarkYAML < Bullshit::RepeatCase
warmup yes
iterations 400
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def setup
a = [ nil, false, true, "fÖß\nÄr", [ "n€st€d", true ], { "fooß" => "bär", "qu\r\nux" => true } ]
@big = a * 100
@json = JSON.pretty_generate(@big)
end
def benchmark_parser
@result = YAML.load(@json)
end
def generic_reset_method
@result == @big or raise "not equal"
end
end
class ParserBenchmarkRails < Bullshit::RepeatCase
warmup yes
iterations 400
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def setup
a = [ nil, false, true, "fÖß\nÄr", [ "n€st€d", true ], { "fooß" => "bär", "qu\r\nux" => true } ]
@big = a * 100
@json = JSON.generate(@big)
end
def benchmark_parser
@result = ActiveSupport::JSON.decode(@json)
end
def generic_reset_method
@result == @big or raise "not equal"
end
end
class ParserBenchmarkYajl < Bullshit::RepeatCase
warmup yes
iterations 2000
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def setup
a = [ nil, false, true, "fÖß\nÄr", [ "n€st€d", true ], { "fooß" => "bär", "qu\r\nux" => true } ]
@big = a * 100
@json = JSON.generate(@big)
end
def benchmark_parser
@result = Yajl::Parser.new.parse(@json)
end
def generic_reset_method
@result == @big or raise "not equal"
end
end
if $0 == __FILE__
Bullshit::Case.autorun false
case ARGV.first
when 'ext'
ParserBenchmarkExt.run
when 'pure'
ParserBenchmarkPure.run
when 'yaml'
ParserBenchmarkYAML.run
when 'rails'
ParserBenchmarkRails.run
when 'yajl'
ParserBenchmarkYajl.run
else
system "#{RAKE_PATH} clean"
system "#{RUBY_PATH} #$0 yaml"
system "#{RUBY_PATH} #$0 rails"
system "#{RUBY_PATH} #$0 pure"
system "#{RAKE_PATH} compile_ext"
system "#{RUBY_PATH} #$0 ext"
system "#{RUBY_PATH} #$0 yajl"
Bullshit.compare do
output_filename File.join(File.dirname(__FILE__), 'data', 'ParserBenchmarkComparison.log')
benchmark ParserBenchmarkExt, :parser, :load => yes
benchmark ParserBenchmarkExt, :parser_symbolic, :load => yes
benchmark ParserBenchmarkPure, :parser, :load => yes
benchmark ParserBenchmarkPure, :parser_symbolic, :load => yes
benchmark ParserBenchmarkYAML, :parser, :load => yes
benchmark ParserBenchmarkRails, :parser, :load => yes
benchmark ParserBenchmarkYajl, :parser, :load => yes
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/benchmarks/generator2_benchmark.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/benchmarks/generator2_benchmark.rb | #!/usr/bin/env ruby
# CODING: UTF-8
require 'rbconfig'
RUBY_PATH=File.join(Config::CONFIG['bindir'], Config::CONFIG['ruby_install_name'])
RAKE_PATH=File.join(Config::CONFIG['bindir'], 'rake')
require 'bullshit'
case ARGV.first
when 'ext'
require 'json/ext'
when 'pure'
require 'json/pure'
when 'rails'
require 'active_support'
when 'yajl'
require 'yajl'
require 'yajl/json_gem'
require 'stringio'
end
module JSON
def self.[](*) end
end
module Generator2BenchmarkCommon
include JSON
def setup
@big = eval File.read(File.join(File.dirname(__FILE__), 'ohai.ruby'))
end
def generic_reset_method
@result and @result.size >= 16 or raise @result.to_s
end
end
module JSONGeneratorCommon
include Generator2BenchmarkCommon
def benchmark_generator_fast
@result = JSON.fast_generate(@big)
end
alias reset_benchmark_generator_fast generic_reset_method
def benchmark_generator_safe
@result = JSON.generate(@big)
end
alias reset_benchmark_generator_safe generic_reset_method
def benchmark_generator_pretty
@result = JSON.pretty_generate(@big)
end
alias reset_benchmark_generator_pretty generic_reset_method
def benchmark_generator_ascii
@result = JSON.generate(@big, :ascii_only => true)
end
alias reset_benchmark_generator_ascii generic_reset_method
end
class Generator2BenchmarkExt < Bullshit::RepeatCase
include JSONGeneratorCommon
warmup yes
iterations 2000
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
end
class Generator2BenchmarkPure < Bullshit::RepeatCase
include JSONGeneratorCommon
warmup yes
iterations 400
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
end
class Generator2BenchmarkRails < Bullshit::RepeatCase
include Generator2BenchmarkCommon
warmup yes
iterations 400
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def benchmark_generator
@result = @big.to_json
end
alias reset_benchmark_generator generic_reset_method
end
class Generator2BenchmarkYajl < Bullshit::RepeatCase
include Generator2BenchmarkCommon
warmup yes
iterations 2000
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def benchmark_generator
output = StringIO.new
Yajl::Encoder.new.encode(@big, output)
@result = output.string
end
def benchmark_generator_gem_api
@result = @big.to_json
end
def reset_benchmark_generator
generic_reset_method
end
end
if $0 == __FILE__
Bullshit::Case.autorun false
case ARGV.first
when 'ext'
Generator2BenchmarkExt.run
when 'pure'
Generator2BenchmarkPure.run
when 'rails'
Generator2BenchmarkRails.run
when 'yajl'
Generator2BenchmarkYajl.run
else
system "#{RAKE_PATH} clean"
system "#{RUBY_PATH} #$0 rails"
system "#{RUBY_PATH} #$0 pure"
system "#{RAKE_PATH} compile_ext"
system "#{RUBY_PATH} #$0 ext"
system "#{RUBY_PATH} #$0 yajl"
Bullshit.compare do
output_filename File.join(File.dirname(__FILE__), 'data', 'Generator2BenchmarkComparison.log')
benchmark Generator2BenchmarkExt, :generator_fast, :load => yes
benchmark Generator2BenchmarkExt, :generator_safe, :load => yes
benchmark Generator2BenchmarkExt, :generator_pretty, :load => yes
benchmark Generator2BenchmarkExt, :generator_ascii, :load => yes
benchmark Generator2BenchmarkPure, :generator_fast, :load => yes
benchmark Generator2BenchmarkPure, :generator_safe, :load => yes
benchmark Generator2BenchmarkPure, :generator_pretty, :load => yes
benchmark Generator2BenchmarkPure, :generator_ascii, :load => yes
benchmark Generator2BenchmarkRails, :generator, :load => yes
benchmark Generator2BenchmarkYajl, :generator, :load => yes
benchmark Generator2BenchmarkYajl, :generator_gem_api, :load => yes
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/benchmarks/generator_benchmark.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/benchmarks/generator_benchmark.rb | #!/usr/bin/env ruby
# CODING: UTF-8
require 'rbconfig'
RUBY_PATH=File.join(Config::CONFIG['bindir'], Config::CONFIG['ruby_install_name'])
RAKE_PATH=File.join(Config::CONFIG['bindir'], 'rake')
require 'bullshit'
case ARGV.first
when 'ext'
require 'json/ext'
when 'pure'
require 'json/pure'
when 'rails'
require 'active_support'
when 'yajl'
require 'yajl'
require 'yajl/json_gem'
require 'stringio'
end
module JSON
def self.[](*) end
end
module GeneratorBenchmarkCommon
include JSON
def setup
a = [ nil, false, true, "fÖßÄr", [ "n€st€d", true ], { "fooß" => "bär", "quux" => true } ]
puts a.to_json if a.respond_to?(:to_json)
@big = a * 100
end
def generic_reset_method
@result and @result.size > 2 + 6 * @big.size or raise @result.to_s
end
end
module JSONGeneratorCommon
include GeneratorBenchmarkCommon
def benchmark_generator_fast
@result = JSON.fast_generate(@big)
end
alias reset_benchmark_generator_fast generic_reset_method
def benchmark_generator_safe
@result = JSON.generate(@big)
end
alias reset_benchmark_generator_safe generic_reset_method
def benchmark_generator_pretty
@result = JSON.pretty_generate(@big)
end
alias reset_benchmark_generator_pretty generic_reset_method
def benchmark_generator_ascii
@result = JSON.generate(@big, :ascii_only => true)
end
alias reset_benchmark_generator_ascii generic_reset_method
end
class GeneratorBenchmarkExt < Bullshit::RepeatCase
include JSONGeneratorCommon
warmup yes
iterations 2000
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
end
class GeneratorBenchmarkPure < Bullshit::RepeatCase
include JSONGeneratorCommon
warmup yes
iterations 400
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
end
class GeneratorBenchmarkRails < Bullshit::RepeatCase
include GeneratorBenchmarkCommon
warmup yes
iterations 400
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def benchmark_generator
@result = @big.to_json
end
alias reset_benchmark_generator generic_reset_method
end
class GeneratorBenchmarkYajl < Bullshit::RepeatCase
include GeneratorBenchmarkCommon
warmup yes
iterations 2000
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def benchmark_generator
output = StringIO.new
Yajl::Encoder.new.encode(@big, output)
@result = output.string
end
def benchmark_generator_gem_api
@result = @big.to_json
end
def reset_benchmark_generator
generic_reset_method
end
end
if $0 == __FILE__
Bullshit::Case.autorun false
case ARGV.first
when 'ext'
GeneratorBenchmarkExt.run
when 'pure'
GeneratorBenchmarkPure.run
when 'rails'
GeneratorBenchmarkRails.run
when 'yajl'
GeneratorBenchmarkYajl.run
else
system "#{RAKE_PATH} clean"
system "#{RUBY_PATH} #$0 rails"
system "#{RUBY_PATH} #$0 pure"
system "#{RAKE_PATH} compile_ext"
system "#{RUBY_PATH} #$0 ext"
system "#{RUBY_PATH} #$0 yajl"
Bullshit.compare do
output_filename File.join(File.dirname(__FILE__), 'data', 'GeneratorBenchmarkComparison.log')
benchmark GeneratorBenchmarkExt, :generator_fast, :load => yes
benchmark GeneratorBenchmarkExt, :generator_safe, :load => yes
benchmark GeneratorBenchmarkExt, :generator_pretty, :load => yes
benchmark GeneratorBenchmarkExt, :generator_ascii, :load => yes
benchmark GeneratorBenchmarkPure, :generator_fast, :load => yes
benchmark GeneratorBenchmarkPure, :generator_safe, :load => yes
benchmark GeneratorBenchmarkPure, :generator_pretty, :load => yes
benchmark GeneratorBenchmarkPure, :generator_ascii, :load => yes
benchmark GeneratorBenchmarkRails, :generator, :load => yes
benchmark GeneratorBenchmarkYajl, :generator, :load => yes
benchmark GeneratorBenchmarkYajl, :generator_gem_api, :load => yes
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/tools/fuzz.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/tools/fuzz.rb | require 'json'
require 'iconv'
ISO_8859_1_TO_UTF8 = Iconv.new('utf-8', 'iso-8859-15')
class ::String
def to_utf8
ISO_8859_1_TO_UTF8.iconv self
end
end
class Fuzzer
def initialize(n, freqs = {})
sum = freqs.inject(0.0) { |s, x| s + x.last }
freqs.each_key { |x| freqs[x] /= sum }
s = 0.0
freqs.each_key do |x|
freqs[x] = s .. (s + t = freqs[x])
s += t
end
@freqs = freqs
@n = n
@alpha = (0..0xff).to_a
end
def random_string
s = ''
30.times { s << @alpha[rand(@alpha.size)] }
s.to_utf8
end
def pick
r = rand
found = @freqs.find { |k, f| f.include? rand }
found && found.first
end
def make_pick
k = pick
case
when k == Hash, k == Array
k.new
when k == true, k == false, k == nil
k
when k == String
random_string
when k == Fixnum
rand(2 ** 30) - 2 ** 29
when k == Bignum
rand(2 ** 70) - 2 ** 69
end
end
def fuzz(current = nil)
if @n > 0
case current
when nil
@n -= 1
current = fuzz [ Hash, Array ][rand(2)].new
when Array
while @n > 0
@n -= 1
current << case p = make_pick
when Array, Hash
fuzz(p)
else
p
end
end
when Hash
while @n > 0
@n -= 1
current[random_string] = case p = make_pick
when Array, Hash
fuzz(p)
else
p
end
end
end
end
current
end
end
class MyState < JSON.state
WS = " \r\t\n"
def initialize
super(
:indent => make_spaces,
:space => make_spaces,
:space_before => make_spaces,
:object_nl => make_spaces,
:array_nl => make_spaces,
:max_nesting => false
)
end
def make_spaces
s = ''
rand(1).times { s << WS[rand(WS.size)] }
s
end
end
n = (ARGV.shift || 500).to_i
loop do
fuzzer = Fuzzer.new(n,
Hash => 25,
Array => 25,
String => 10,
Fixnum => 10,
Bignum => 10,
nil => 5,
true => 5,
false => 5
)
o1 = fuzzer.fuzz
json = JSON.generate o1, MyState.new
if $DEBUG
puts "-" * 80
puts json, json.size
else
puts json.size
end
begin
o2 = JSON.parse(json, :max_nesting => false)
rescue JSON::ParserError => e
puts "Caught #{e.class}: #{e.message}\n#{e.backtrace * "\n"}"
puts "o1 = #{o1.inspect}", "json = #{json}", "json_str = #{json.inspect}"
puts "locals = #{local_variables.inspect}"
exit
end
if o1 != o2
puts "mismatch", "o1 = #{o1.inspect}", "o2 = #{o2.inspect}",
"json = #{json}", "json_str = #{json.inspect}"
puts "locals = #{local_variables.inspect}"
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/tools/server.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/tools/server.rb | #!/usr/bin/env ruby
require 'webrick'
include WEBrick
$:.unshift 'ext'
$:.unshift 'lib'
require 'json'
class JSONServlet < HTTPServlet::AbstractServlet
@@count = 1
def do_GET(req, res)
obj = {
"TIME" => Time.now.strftime("%FT%T"),
"foo" => "Bär",
"bar" => "© ≠ €!",
'a' => 2,
'b' => 3.141,
'COUNT' => @@count += 1,
'c' => 'c',
'd' => [ 1, "b", 3.14 ],
'e' => { 'foo' => 'bar' },
'g' => "松本行弘",
'h' => 1000.0,
'i' => 0.001,
'j' => "\xf0\xa0\x80\x81",
}
res.body = JSON.generate obj
res['Content-Type'] = "application/json"
end
end
def create_server(err, dir, port)
dir = File.expand_path(dir)
err.puts "Surf to:", "http://#{Socket.gethostname}:#{port}"
s = HTTPServer.new(
:Port => port,
:DocumentRoot => dir,
:Logger => WEBrick::Log.new(err),
:AccessLog => [
[ err, WEBrick::AccessLog::COMMON_LOG_FORMAT ],
[ err, WEBrick::AccessLog::REFERER_LOG_FORMAT ],
[ err, WEBrick::AccessLog::AGENT_LOG_FORMAT ]
]
)
s.mount("/json", JSONServlet)
s
end
default_dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'data'))
dir = ARGV.shift || default_dir
port = (ARGV.shift || 6666).to_i
s = create_server(STDERR, dir, 6666)
t = Thread.new { s.start }
trap(:INT) do
s.shutdown
t.join
exit
end
sleep
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/tests/test_json_generate.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/tests/test_json_generate.rb | #!/usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'test/unit'
case ENV['JSON']
when 'pure' then require 'json/pure'
when 'ext' then require 'json/ext'
else require 'json'
end
class TC_JSONGenerate < Test::Unit::TestCase
include JSON
def setup
@hash = {
'a' => 2,
'b' => 3.141,
'c' => 'c',
'd' => [ 1, "b", 3.14 ],
'e' => { 'foo' => 'bar' },
'g' => "\"\0\037",
'h' => 1000.0,
'i' => 0.001
}
@json2 = '{"a":2,"b":3.141,"c":"c","d":[1,"b",3.14],"e":{"foo":"bar"},' +
'"g":"\\"\\u0000\\u001f","h":1000.0,"i":0.001}'
@json3 = <<'EOT'.chomp
{
"a": 2,
"b": 3.141,
"c": "c",
"d": [
1,
"b",
3.14
],
"e": {
"foo": "bar"
},
"g": "\"\u0000\u001f",
"h": 1000.0,
"i": 0.001
}
EOT
end
def test_generate
json = generate(@hash)
assert_equal(JSON.parse(@json2), JSON.parse(json))
parsed_json = parse(json)
assert_equal(@hash, parsed_json)
json = generate({1=>2})
assert_equal('{"1":2}', json)
parsed_json = parse(json)
assert_equal({"1"=>2}, parsed_json)
assert_raise(GeneratorError) { generate(666) }
end
def test_generate_pretty
json = pretty_generate(@hash)
assert_equal(JSON.parse(@json3), JSON.parse(json))
parsed_json = parse(json)
assert_equal(@hash, parsed_json)
json = pretty_generate({1=>2})
assert_equal(<<'EOT'.chomp, json)
{
"1": 2
}
EOT
parsed_json = parse(json)
assert_equal({"1"=>2}, parsed_json)
assert_raise(GeneratorError) { pretty_generate(666) }
end
def test_fast_generate
json = fast_generate(@hash)
assert_equal(JSON.parse(@json2), JSON.parse(json))
parsed_json = parse(json)
assert_equal(@hash, parsed_json)
json = fast_generate({1=>2})
assert_equal('{"1":2}', json)
parsed_json = parse(json)
assert_equal({"1"=>2}, parsed_json)
assert_raise(GeneratorError) { fast_generate(666) }
end
def test_states
json = generate({1=>2}, nil)
assert_equal('{"1":2}', json)
s = JSON.state.new
assert s.check_circular?
assert s[:check_circular?]
h = { 1=>2 }
h[3] = h
assert_raises(JSON::NestingError) { generate(h) }
assert_raises(JSON::NestingError) { generate(h, s) }
s = JSON.state.new
a = [ 1, 2 ]
a << a
assert_raises(JSON::NestingError) { generate(a, s) }
assert s.check_circular?
assert s[:check_circular?]
end
def test_allow_nan
assert_raises(GeneratorError) { generate([JSON::NaN]) }
assert_equal '[NaN]', generate([JSON::NaN], :allow_nan => true)
assert_raises(GeneratorError) { fast_generate([JSON::NaN]) }
assert_raises(GeneratorError) { pretty_generate([JSON::NaN]) }
assert_equal "[\n NaN\n]", pretty_generate([JSON::NaN], :allow_nan => true)
assert_raises(GeneratorError) { generate([JSON::Infinity]) }
assert_equal '[Infinity]', generate([JSON::Infinity], :allow_nan => true)
assert_raises(GeneratorError) { fast_generate([JSON::Infinity]) }
assert_raises(GeneratorError) { pretty_generate([JSON::Infinity]) }
assert_equal "[\n Infinity\n]", pretty_generate([JSON::Infinity], :allow_nan => true)
assert_raises(GeneratorError) { generate([JSON::MinusInfinity]) }
assert_equal '[-Infinity]', generate([JSON::MinusInfinity], :allow_nan => true)
assert_raises(GeneratorError) { fast_generate([JSON::MinusInfinity]) }
assert_raises(GeneratorError) { pretty_generate([JSON::MinusInfinity]) }
assert_equal "[\n -Infinity\n]", pretty_generate([JSON::MinusInfinity], :allow_nan => true)
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/tests/test_json_encoding.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/tests/test_json_encoding.rb | #!/usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'test/unit'
case ENV['JSON']
when 'pure' then require 'json/pure'
when 'ext' then require 'json/ext'
else require 'json'
end
require 'iconv'
class TC_JSONEncoding < Test::Unit::TestCase
include JSON
def setup
@utf_8 = '["© ≠ €!"]'
@parsed = [ "© ≠ €!" ]
@utf_16_data = Iconv.iconv('utf-16be', 'utf-8', @parsed.first)
@generated = '["\u00a9 \u2260 \u20ac!"]'
if defined?(::Encoding)
@utf_8_ascii_8bit = @utf_8.dup.force_encoding(Encoding::ASCII_8BIT)
@utf_16be, = Iconv.iconv('utf-16be', 'utf-8', @utf_8)
@utf_16be_ascii_8bit = @utf_16be.dup.force_encoding(Encoding::ASCII_8BIT)
@utf_16le, = Iconv.iconv('utf-16le', 'utf-8', @utf_8)
@utf_16le_ascii_8bit = @utf_16le.dup.force_encoding(Encoding::ASCII_8BIT)
@utf_32be, = Iconv.iconv('utf-32be', 'utf-8', @utf_8)
@utf_32be_ascii_8bit = @utf_32be.dup.force_encoding(Encoding::ASCII_8BIT)
@utf_32le, = Iconv.iconv('utf-32le', 'utf-8', @utf_8)
@utf_32le_ascii_8bit = @utf_32le.dup.force_encoding(Encoding::ASCII_8BIT)
else
@utf_8_ascii_8bit = @utf_8.dup
@utf_16be, = Iconv.iconv('utf-16be', 'utf-8', @utf_8)
@utf_16be_ascii_8bit = @utf_16be.dup
@utf_16le, = Iconv.iconv('utf-16le', 'utf-8', @utf_8)
@utf_16le_ascii_8bit = @utf_16le.dup
@utf_32be, = Iconv.iconv('utf-32be', 'utf-8', @utf_8)
@utf_32be_ascii_8bit = @utf_32be.dup
@utf_32le, = Iconv.iconv('utf-32le', 'utf-8', @utf_8)
@utf_32le_ascii_8bit = @utf_32le.dup
end
end
def test_parse
assert_equal @parsed, JSON.parse(@utf_8)
assert_equal @parsed, JSON.parse(@utf_16be)
assert_equal @parsed, JSON.parse(@utf_16le)
assert_equal @parsed, JSON.parse(@utf_32be)
assert_equal @parsed, JSON.parse(@utf_32le)
end
def test_parse_ascii_8bit
assert_equal @parsed, JSON.parse(@utf_8_ascii_8bit)
assert_equal @parsed, JSON.parse(@utf_16be_ascii_8bit)
assert_equal @parsed, JSON.parse(@utf_16le_ascii_8bit)
assert_equal @parsed, JSON.parse(@utf_32be_ascii_8bit)
assert_equal @parsed, JSON.parse(@utf_32le_ascii_8bit)
end
def test_generate
assert_equal @generated, JSON.generate(@parsed, :ascii_only => true)
if defined?(::Encoding)
assert_equal @generated, JSON.generate(@utf_16_data, :ascii_only => true)
else
# XXX checking of correct utf8 data is not as strict (yet?) without :ascii_only
assert_raises(JSON::GeneratorError) { JSON.generate(@utf_16_data, :ascii_only => true) }
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/tests/test_json_unicode.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/tests/test_json_unicode.rb | #!/usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'test/unit'
case ENV['JSON']
when 'pure' then require 'json/pure'
when 'ext' then require 'json/ext'
else require 'json'
end
class TC_JSONUnicode < Test::Unit::TestCase
include JSON
def test_unicode
assert_equal '""', ''.to_json
assert_equal '"\\b"', "\b".to_json
assert_equal '"\u0001"', 0x1.chr.to_json
assert_equal '"\u001f"', 0x1f.chr.to_json
assert_equal '" "', ' '.to_json
assert_equal "\"#{0x7f.chr}\"", 0x7f.chr.to_json
utf8 = [ "© ≠ €! \01" ]
json = '["© ≠ €! \u0001"]'
assert_equal json, utf8.to_json(:ascii_only => false)
assert_equal utf8, parse(json)
json = '["\u00a9 \u2260 \u20ac! \u0001"]'
assert_equal json, utf8.to_json(:ascii_only => true)
assert_equal utf8, parse(json)
utf8 = ["\343\201\202\343\201\204\343\201\206\343\201\210\343\201\212"]
json = "[\"\343\201\202\343\201\204\343\201\206\343\201\210\343\201\212\"]"
assert_equal utf8, parse(json)
assert_equal json, utf8.to_json(:ascii_only => false)
utf8 = ["\343\201\202\343\201\204\343\201\206\343\201\210\343\201\212"]
assert_equal utf8, parse(json)
json = "[\"\\u3042\\u3044\\u3046\\u3048\\u304a\"]"
assert_equal json, utf8.to_json(:ascii_only => true)
assert_equal utf8, parse(json)
utf8 = ['საქართველო']
json = '["საქართველო"]'
assert_equal json, utf8.to_json(:ascii_only => false)
json = "[\"\\u10e1\\u10d0\\u10e5\\u10d0\\u10e0\\u10d7\\u10d5\\u10d4\\u10da\\u10dd\"]"
assert_equal json, utf8.to_json(:ascii_only => true)
assert_equal utf8, parse(json)
assert_equal '["Ã"]', JSON.generate(["Ã"], :ascii_only => false)
assert_equal '["\\u00c3"]', JSON.generate(["Ã"], :ascii_only => true)
assert_equal ["€"], JSON.parse('["\u20ac"]')
utf8 = ["\xf0\xa0\x80\x81"]
json = "[\"\xf0\xa0\x80\x81\"]"
assert_equal json, JSON.generate(utf8, :ascii_only => false)
assert_equal utf8, JSON.parse(json)
json = '["\ud840\udc01"]'
assert_equal json, JSON.generate(utf8, :ascii_only => true)
assert_equal utf8, JSON.parse(json)
end
def test_chars
(0..0x7f).each do |i|
json = '["\u%04x"]' % i
if RUBY_VERSION >= "1.9."
i = i.chr
end
assert_equal i, JSON.parse(json).first[0]
if i == ?\b
generated = JSON.generate(["" << i])
assert '["\b"]' == generated || '["\10"]' == generated
elsif [?\n, ?\r, ?\t, ?\f].include?(i)
assert_equal '[' << ('' << i).dump << ']', JSON.generate(["" << i])
elsif i.chr < 0x20.chr
assert_equal json, JSON.generate(["" << i])
end
end
assert_raise(JSON::GeneratorError) do
JSON.generate(["\x80"], :ascii_only => true)
end
assert_equal "\302\200", JSON.parse('["\u0080"]').first
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/tests/test_json_fixtures.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/tests/test_json_fixtures.rb | #!/usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'test/unit'
case ENV['JSON']
when 'pure' then require 'json/pure'
when 'ext' then require 'json/ext'
else require 'json'
end
class TC_JSONFixtures < Test::Unit::TestCase
def setup
fixtures = File.join(File.dirname(__FILE__), 'fixtures/*.json')
passed, failed = Dir[fixtures].partition { |f| f['pass'] }
@passed = passed.inject([]) { |a, f| a << [ f, File.read(f) ] }.sort
@failed = failed.inject([]) { |a, f| a << [ f, File.read(f) ] }.sort
end
def test_passing
for name, source in @passed
assert JSON.parse(source),
"Did not pass for fixture '#{name}'"
end
end
def test_failing
for name, source in @failed
assert_raises(JSON::ParserError, JSON::NestingError,
"Did not fail for fixture '#{name}'") do
JSON.parse(source)
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/tests/test_json_rails.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/tests/test_json_rails.rb | #!/usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'test/unit'
case ENV['JSON']
when 'pure' then require 'json/pure'
when 'ext' then require 'json/ext'
else require 'json'
end
require 'json/add/rails'
require 'date'
class TC_JSONRails < Test::Unit::TestCase
include JSON
class A
def initialize(a)
@a = a
end
attr_reader :a
def ==(other)
a == other.a
end
def self.json_create(object)
new(*object['args'])
end
def to_json(*args)
{
'json_class' => self.class.name,
'args' => [ @a ],
}.to_json(*args)
end
end
class B
def self.json_creatable?
false
end
def to_json(*args)
{
'json_class' => self.class.name,
}.to_json(*args)
end
end
class C
def to_json(*args)
{
'json_class' => 'TC_JSONRails::Nix',
}.to_json(*args)
end
end
class D
def initialize
@foo = 666
end
attr_reader :foo
def ==(other)
foo == other.foo
end
end
def test_extended_json
a = A.new(666)
assert A.json_creatable?
assert_equal 666, a.a
json = generate(a)
a_again = JSON.parse(json)
assert_kind_of a.class, a_again
assert_equal a, a_again
assert_equal 666, a_again.a
end
def test_extended_json_generic_object
d = D.new
assert D.json_creatable?
assert_equal 666, d.foo
json = generate(d)
d_again = JSON.parse(json)
assert_kind_of d.class, d_again
assert_equal d, d_again
assert_equal 666, d_again.foo
end
def test_extended_json_disabled
a = A.new(666)
assert A.json_creatable?
json = generate(a)
a_again = JSON.parse(json, :create_additions => true)
assert_kind_of a.class, a_again
assert_equal a, a_again
a_hash = JSON.parse(json, :create_additions => false)
assert_kind_of Hash, a_hash
assert_equal(
{"args"=>[666], "json_class"=>"TC_JSONRails::A"}.sort_by { |k,| k },
a_hash.sort_by { |k,| k }
)
end
def test_extended_json_fail1
b = B.new
assert !B.json_creatable?
json = generate(b)
assert_equal({ 'json_class' => B.name }, JSON.parse(json))
end
def test_extended_json_fail2
c = C.new # with rails addition all objects are theoretically creatable
assert C.json_creatable?
json = generate(c)
assert_raises(ArgumentError, NameError) { JSON.parse(json) }
end
def test_raw_strings
raw = ''
raw.respond_to?(:encode!) and raw.encode!(Encoding::ASCII_8BIT)
raw_array = []
for i in 0..255
raw << i
raw_array << i
end
json = raw.to_json_raw
json_raw_object = raw.to_json_raw_object
hash = { 'json_class' => 'String', 'raw'=> raw_array }
assert_equal hash, json_raw_object
assert_match /\A\{.*\}\Z/, json
assert_match /"json_class":"String"/, json
assert_match /"raw":\[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255\]/, json
raw_again = JSON.parse(json)
assert_equal raw, raw_again
end
def test_symbol
assert_equal '"foo"', :foo.to_json # we don't want an object here
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/tests/test_json_addition.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/tests/test_json_addition.rb | #!/usr/bin/env ruby
# -*- coding:utf-8 -*-
require 'test/unit'
case ENV['JSON']
when 'pure' then require 'json/pure'
when 'ext' then require 'json/ext'
else require 'json'
end
require 'json/add/core'
require 'date'
class TC_JSONAddition < Test::Unit::TestCase
include JSON
class A
def initialize(a)
@a = a
end
attr_reader :a
def ==(other)
a == other.a
end
def self.json_create(object)
new(*object['args'])
end
def to_json(*args)
{
'json_class' => self.class.name,
'args' => [ @a ],
}.to_json(*args)
end
end
class B
def self.json_creatable?
false
end
def to_json(*args)
{
'json_class' => self.class.name,
}.to_json(*args)
end
end
class C
def self.json_creatable?
false
end
def to_json(*args)
{
'json_class' => 'TC_JSONAddition::Nix',
}.to_json(*args)
end
end
def test_extended_json
a = A.new(666)
assert A.json_creatable?
json = generate(a)
a_again = JSON.parse(json)
assert_kind_of a.class, a_again
assert_equal a, a_again
end
def test_extended_json_disabled
a = A.new(666)
assert A.json_creatable?
json = generate(a)
a_again = JSON.parse(json, :create_additions => true)
assert_kind_of a.class, a_again
assert_equal a, a_again
a_hash = JSON.parse(json, :create_additions => false)
assert_kind_of Hash, a_hash
assert_equal(
{"args"=>[666], "json_class"=>"TC_JSONAddition::A"}.sort_by { |k,| k },
a_hash.sort_by { |k,| k }
)
end
def test_extended_json_fail1
b = B.new
assert !B.json_creatable?
json = generate(b)
assert_equal({ "json_class"=>"TC_JSONAddition::B" }, JSON.parse(json))
end
def test_extended_json_fail2
c = C.new
assert !C.json_creatable?
json = generate(c)
assert_raises(ArgumentError, NameError) { JSON.parse(json) }
end
def test_raw_strings
raw = ''
raw.respond_to?(:encode!) and raw.encode!(Encoding::ASCII_8BIT)
raw_array = []
for i in 0..255
raw << i
raw_array << i
end
json = raw.to_json_raw
json_raw_object = raw.to_json_raw_object
hash = { 'json_class' => 'String', 'raw'=> raw_array }
assert_equal hash, json_raw_object
assert_match /\A\{.*\}\Z/, json
assert_match /"json_class":"String"/, json
assert_match /"raw":\[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255\]/, json
raw_again = JSON.parse(json)
assert_equal raw, raw_again
end
MyJsonStruct = Struct.new 'MyJsonStruct', :foo, :bar
def test_core
t = Time.now
assert_equal t.inspect, JSON(JSON(t)).inspect
d = Date.today
assert_equal d, JSON(JSON(d))
d = DateTime.civil(2007, 6, 14, 14, 57, 10, Rational(1, 12), 2299161)
assert_equal d, JSON(JSON(d))
assert_equal 1..10, JSON(JSON(1..10))
assert_equal 1...10, JSON(JSON(1...10))
assert_equal "a".."c", JSON(JSON("a".."c"))
assert_equal "a"..."c", JSON(JSON("a"..."c"))
s = MyJsonStruct.new 4711, 'foot'
assert_equal s, JSON(JSON(s))
struct = Struct.new :foo, :bar
s = struct.new 4711, 'foot'
assert_raises(JSONError) { JSON(s) }
begin
raise TypeError, "test me"
rescue TypeError => e
e_json = JSON.generate e
e_again = JSON e_json
assert_kind_of TypeError, e_again
assert_equal e.message, e_again.message
assert_equal e.backtrace, e_again.backtrace
end
assert_equal(/foo/, JSON(JSON(/foo/)))
assert_equal(/foo/i, JSON(JSON(/foo/i)))
end
def test_utc_datetime
now = Time.now
d = DateTime.parse(now.to_s) # usual case
assert d, JSON.parse(d.to_json)
d = DateTime.parse(now.utc.to_s) # of = 0
assert d, JSON.parse(d.to_json)
d = DateTime.civil(2008, 6, 17, 11, 48, 32, 1) # of = 1 / 12 => 1/12
assert d, JSON.parse(d.to_json)
d = DateTime.civil(2008, 6, 17, 11, 48, 32, 12) # of = 12 / 12 => 12
assert d, JSON.parse(d.to_json)
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/tests/test_json.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/tests/test_json.rb | #!/usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'test/unit'
case ENV['JSON']
when 'pure' then require 'json/pure'
when 'ext' then require 'json/ext'
else require 'json'
end
require 'stringio'
unless Array.method_defined?(:permutation)
begin
require 'enumerator'
require 'permutation'
class Array
def permutation
Permutation.for(self).to_enum.map { |x| x.project }
end
end
rescue LoadError
warn "Skipping permutation tests."
end
end
class TC_JSON < Test::Unit::TestCase
include JSON
def setup
@ary = [1, "foo", 3.14, 4711.0, 2.718, nil, [1,-2,3], false, true].map do
|x| [x]
end
@ary_to_parse = ["1", '"foo"', "3.14", "4711.0", "2.718", "null",
"[1,-2,3]", "false", "true"].map do
|x| "[#{x}]"
end
@hash = {
'a' => 2,
'b' => 3.141,
'c' => 'c',
'd' => [ 1, "b", 3.14 ],
'e' => { 'foo' => 'bar' },
'g' => "\"\0\037",
'h' => 1000.0,
'i' => 0.001
}
@json = '{"a":2,"b":3.141,"c":"c","d":[1,"b",3.14],"e":{"foo":"bar"},'\
'"g":"\\"\\u0000\\u001f","h":1.0E3,"i":1.0E-3}'
end
def test_construction
parser = JSON::Parser.new('test')
assert_equal 'test', parser.source
end
def assert_equal_float(expected, is)
assert_in_delta(expected.first, is.first, 1e-2)
end
def test_parse_simple_arrays
assert_equal([], parse('[]'))
assert_equal([], parse(' [ ] '))
assert_equal([nil], parse('[null]'))
assert_equal([false], parse('[false]'))
assert_equal([true], parse('[true]'))
assert_equal([-23], parse('[-23]'))
assert_equal([23], parse('[23]'))
assert_equal([0.23], parse('[0.23]'))
assert_equal([0.0], parse('[0e0]'))
assert_raises(JSON::ParserError) { parse('[+23.2]') }
assert_raises(JSON::ParserError) { parse('[+23]') }
assert_raises(JSON::ParserError) { parse('[.23]') }
assert_raises(JSON::ParserError) { parse('[023]') }
assert_equal_float [3.141], parse('[3.141]')
assert_equal_float [-3.141], parse('[-3.141]')
assert_equal_float [3.141], parse('[3141e-3]')
assert_equal_float [3.141], parse('[3141.1e-3]')
assert_equal_float [3.141], parse('[3141E-3]')
assert_equal_float [3.141], parse('[3141.0E-3]')
assert_equal_float [-3.141], parse('[-3141.0e-3]')
assert_equal_float [-3.141], parse('[-3141e-3]')
assert_raises(ParserError) { parse('[NaN]') }
assert parse('[NaN]', :allow_nan => true).first.nan?
assert_raises(ParserError) { parse('[Infinity]') }
assert_equal [1.0/0], parse('[Infinity]', :allow_nan => true)
assert_raises(ParserError) { parse('[-Infinity]') }
assert_equal [-1.0/0], parse('[-Infinity]', :allow_nan => true)
assert_equal([""], parse('[""]'))
assert_equal(["foobar"], parse('["foobar"]'))
assert_equal([{}], parse('[{}]'))
end
def test_parse_simple_objects
assert_equal({}, parse('{}'))
assert_equal({}, parse(' { } '))
assert_equal({ "a" => nil }, parse('{ "a" : null}'))
assert_equal({ "a" => nil }, parse('{"a":null}'))
assert_equal({ "a" => false }, parse('{ "a" : false } '))
assert_equal({ "a" => false }, parse('{"a":false}'))
assert_raises(JSON::ParserError) { parse('{false}') }
assert_equal({ "a" => true }, parse('{"a":true}'))
assert_equal({ "a" => true }, parse(' { "a" : true } '))
assert_equal({ "a" => -23 }, parse(' { "a" : -23 } '))
assert_equal({ "a" => -23 }, parse(' { "a" : -23 } '))
assert_equal({ "a" => 23 }, parse('{"a":23 } '))
assert_equal({ "a" => 23 }, parse(' { "a" : 23 } '))
assert_equal({ "a" => 0.23 }, parse(' { "a" : 0.23 } '))
assert_equal({ "a" => 0.23 }, parse(' { "a" : 0.23 } '))
end
if Array.method_defined?(:permutation)
def test_parse_more_complex_arrays
a = [ nil, false, true, "foßbar", [ "n€st€d", true ], { "nested" => true, "n€ßt€ð2" => {} }]
a.permutation.each do |perm|
json = pretty_generate(perm)
assert_equal perm, parse(json)
end
end
def test_parse_complex_objects
a = [ nil, false, true, "foßbar", [ "n€st€d", true ], { "nested" => true, "n€ßt€ð2" => {} }]
a.permutation.each do |perm|
s = "a"
orig_obj = perm.inject({}) { |h, x| h[s.dup] = x; s = s.succ; h }
json = pretty_generate(orig_obj)
assert_equal orig_obj, parse(json)
end
end
end
def test_parse_arrays
assert_equal([1,2,3], parse('[1,2,3]'))
assert_equal([1.2,2,3], parse('[1.2,2,3]'))
assert_equal([[],[[],[]]], parse('[[],[[],[]]]'))
end
def test_parse_values
assert_equal([""], parse('[""]'))
assert_equal(["\\"], parse('["\\\\"]'))
assert_equal(['"'], parse('["\""]'))
assert_equal(['\\"\\'], parse('["\\\\\\"\\\\"]'))
assert_equal(["\"\b\n\r\t\0\037"],
parse('["\"\b\n\r\t\u0000\u001f"]'))
for i in 0 ... @ary.size
assert_equal(@ary[i], parse(@ary_to_parse[i]))
end
end
def test_parse_array
assert_equal([], parse('[]'))
assert_equal([], parse(' [ ] '))
assert_equal([1], parse('[1]'))
assert_equal([1], parse(' [ 1 ] '))
assert_equal(@ary,
parse('[[1],["foo"],[3.14],[47.11e+2],[2718.0E-3],[null],[[1,-2,3]]'\
',[false],[true]]'))
assert_equal(@ary, parse(%Q{ [ [1] , ["foo"] , [3.14] \t , [47.11e+2]
, [2718.0E-3 ],\r[ null] , [[1, -2, 3 ]], [false ],[ true]\n ] }))
end
class SubArray < Array; end
def test_parse_array_custom_class
res = parse('[]', :array_class => SubArray)
assert_equal([], res)
assert_equal(SubArray, res.class)
end
def test_parse_object
assert_equal({}, parse('{}'))
assert_equal({}, parse(' { } '))
assert_equal({'foo'=>'bar'}, parse('{"foo":"bar"}'))
assert_equal({'foo'=>'bar'}, parse(' { "foo" : "bar" } '))
end
class SubHash < Hash
def to_json(*a)
{
JSON.create_id => self.class.name,
}.merge(self).to_json(*a)
end
def self.json_create(o)
o.delete JSON.create_id
new.merge(o)
end
end
def test_parse_object_custom_class
res = parse('{}', :object_class => SubHash)
assert_equal({}, res)
assert_equal(SubHash, res.class)
end
def test_generation_of_core_subclasses
obj = SubHash.new.merge( "foo" => SubHash.new.merge("bar" => true))
obj_json = JSON(obj)
obj_again = JSON(obj_json)
assert_kind_of SubHash, obj_again
assert_kind_of SubHash, obj_again['foo']
assert obj_again['foo']['bar']
assert_equal obj, obj_again
end
def test_parser_reset
parser = Parser.new(@json)
assert_equal(@hash, parser.parse)
assert_equal(@hash, parser.parse)
end
def test_comments
json = <<EOT
{
"key1":"value1", // eol comment
"key2":"value2" /* multi line
* comment */,
"key3":"value3" /* multi line
// nested eol comment
* comment */
}
EOT
assert_equal(
{ "key1" => "value1", "key2" => "value2", "key3" => "value3" },
parse(json))
json = <<EOT
{
"key1":"value1" /* multi line
// nested eol comment
/* illegal nested multi line comment */
* comment */
}
EOT
assert_raises(ParserError) { parse(json) }
json = <<EOT
{
"key1":"value1" /* multi line
// nested eol comment
closed multi comment */
and again, throw an Error */
}
EOT
assert_raises(ParserError) { parse(json) }
json = <<EOT
{
"key1":"value1" /*/*/
}
EOT
assert_equal({ "key1" => "value1" }, parse(json))
end
def test_backslash
data = [ '\\.(?i:gif|jpe?g|png)$' ]
json = '["\\\\.(?i:gif|jpe?g|png)$"]'
assert_equal json, JSON.generate(data)
assert_equal data, JSON.parse(json)
#
data = [ '\\"' ]
json = '["\\\\\""]'
assert_equal json, JSON.generate(data)
assert_equal data, JSON.parse(json)
#
json = '["/"]'
data = JSON.parse(json)
assert_equal ['/'], data
assert_equal json, JSON.generate(data)
#
json = '["\""]'
data = JSON.parse(json)
assert_equal ['"'], data
assert_equal json, JSON.generate(data)
json = '["\\\'"]'
data = JSON.parse(json)
assert_equal ["'"], data
assert_equal '["\'"]', JSON.generate(data)
end
def test_wrong_inputs
assert_raises(ParserError) { JSON.parse('"foo"') }
assert_raises(ParserError) { JSON.parse('123') }
assert_raises(ParserError) { JSON.parse('[] bla') }
assert_raises(ParserError) { JSON.parse('[] 1') }
assert_raises(ParserError) { JSON.parse('[] []') }
assert_raises(ParserError) { JSON.parse('[] {}') }
assert_raises(ParserError) { JSON.parse('{} []') }
assert_raises(ParserError) { JSON.parse('{} {}') }
assert_raises(ParserError) { JSON.parse('[NULL]') }
assert_raises(ParserError) { JSON.parse('[FALSE]') }
assert_raises(ParserError) { JSON.parse('[TRUE]') }
assert_raises(ParserError) { JSON.parse('[07] ') }
assert_raises(ParserError) { JSON.parse('[0a]') }
assert_raises(ParserError) { JSON.parse('[1.]') }
assert_raises(ParserError) { JSON.parse(' ') }
end
def test_nesting
assert_raises(JSON::NestingError) { JSON.parse '[[]]', :max_nesting => 1 }
assert_raises(JSON::NestingError) { JSON.parser.new('[[]]', :max_nesting => 1).parse }
assert_equal [[]], JSON.parse('[[]]', :max_nesting => 2)
too_deep = '[[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]'
too_deep_ary = eval too_deep
assert_raises(JSON::NestingError) { JSON.parse too_deep }
assert_raises(JSON::NestingError) { JSON.parser.new(too_deep).parse }
assert_raises(JSON::NestingError) { JSON.parse too_deep, :max_nesting => 19 }
ok = JSON.parse too_deep, :max_nesting => 20
assert_equal too_deep_ary, ok
ok = JSON.parse too_deep, :max_nesting => nil
assert_equal too_deep_ary, ok
ok = JSON.parse too_deep, :max_nesting => false
assert_equal too_deep_ary, ok
ok = JSON.parse too_deep, :max_nesting => 0
assert_equal too_deep_ary, ok
assert_raises(JSON::NestingError) { JSON.generate [[]], :max_nesting => 1 }
assert_equal '[[]]', JSON.generate([[]], :max_nesting => 2)
assert_raises(JSON::NestingError) { JSON.generate too_deep_ary }
assert_raises(JSON::NestingError) { JSON.generate too_deep_ary, :max_nesting => 19 }
ok = JSON.generate too_deep_ary, :max_nesting => 20
assert_equal too_deep, ok
ok = JSON.generate too_deep_ary, :max_nesting => nil
assert_equal too_deep, ok
ok = JSON.generate too_deep_ary, :max_nesting => false
assert_equal too_deep, ok
ok = JSON.generate too_deep_ary, :max_nesting => 0
assert_equal too_deep, ok
end
def test_symbolize_names
assert_equal({ "foo" => "bar", "baz" => "quux" },
JSON.parse('{"foo":"bar", "baz":"quux"}'))
assert_equal({ :foo => "bar", :baz => "quux" },
JSON.parse('{"foo":"bar", "baz":"quux"}', :symbolize_names => true))
end
def test_load_dump
too_deep = '[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]'
assert_equal too_deep, JSON.dump(eval(too_deep))
assert_kind_of String, Marshal.dump(eval(too_deep))
assert_raises(ArgumentError) { JSON.dump(eval(too_deep), 19) }
assert_raises(ArgumentError) { Marshal.dump(eval(too_deep), 19) }
assert_equal too_deep, JSON.dump(eval(too_deep), 20)
assert_kind_of String, Marshal.dump(eval(too_deep), 20)
output = StringIO.new
JSON.dump(eval(too_deep), output)
assert_equal too_deep, output.string
output = StringIO.new
JSON.dump(eval(too_deep), output, 20)
assert_equal too_deep, output.string
end
def test_big_integers
json1 = JSON([orig = (1 << 31) - 1])
assert_equal orig, JSON[json1][0]
json2 = JSON([orig = 1 << 31])
assert_equal orig, JSON[json2][0]
json3 = JSON([orig = (1 << 62) - 1])
assert_equal orig, JSON[json3][0]
json4 = JSON([orig = 1 << 62])
assert_equal orig, JSON[json4][0]
json5 = JSON([orig = 1 << 64])
assert_equal orig, JSON[json5][0]
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/bin/prettify_json.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/bin/prettify_json.rb | #!/usr/bin/env ruby
require 'json'
require 'fileutils'
include FileUtils
# Parses the argument array _args_, according to the pattern _s_, to
# retrieve the single character command line options from it. If _s_ is
# 'xy:' an option '-x' without an option argument is searched, and an
# option '-y foo' with an option argument ('foo').
#
# An option hash is returned with all found options set to true or the
# found option argument.
def go(s, args = ARGV)
b, v = s.scan(/(.)(:?)/).inject([{},{}]) { |t,(o,a)|
t[a.empty? ? 0 : 1][o] = a.empty? ? false : nil
t
}
while a = args.shift
a !~ /\A-(.+)/ and args.unshift a and break
p = $1
until p == ''
o = p.slice!(0, 1)
if v.key?(o)
v[o] = if p == '' then args.shift or break 1 else p end
break
elsif b.key?(o)
b[o] = true
else
args.unshift a
break 1
end
end and break
end
b.merge(v)
end
opts = go 'slhi:', args = ARGV.dup
if opts['h'] || opts['l'] && opts['s']
puts <<EOT
Usage: #{File.basename($0)} [OPTION] [FILE]
If FILE is skipped, this scripts waits for input from STDIN. Otherwise
FILE is opened, read, and used as input for the prettifier.
OPTION can be
-s to output the shortest possible JSON (precludes -l)
-l to output a longer, better formatted JSON (precludes -s)
-i EXT prettifies FILE in place, saving a backup to FILE.EXT
-h this help
EOT
exit 0
end
filename = nil
json = JSON[
if args.empty?
STDIN.read
else
File.read filename = args.first
end
]
output = if opts['s']
JSON.fast_generate json
else # default is -l
JSON.pretty_generate json
end
if opts['i'] && filename
cp filename, "#{filename}.#{opts['i']}"
File.open(filename, 'w') { |f| f.puts output }
else
puts output
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/bin/edit_json.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/bin/edit_json.rb | #!/usr/bin/env ruby
require 'json/editor'
filename, encoding = ARGV
JSON::Editor.start(encoding) do |window|
if filename
window.file_open(filename)
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/ext/json/ext/generator/extconf.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/ext/json/ext/generator/extconf.rb | require 'mkmf'
require 'rbconfig'
unless $CFLAGS.gsub!(/ -O[\dsz]?/, ' -O3')
$CFLAGS << ' -O3'
end
if CONFIG['CC'] =~ /gcc/
$CFLAGS << ' -Wall'
#unless $CFLAGS.gsub!(/ -O[\dsz]?/, ' -O0 -ggdb')
# $CFLAGS << ' -O0 -ggdb'
#end
end
have_header("ruby/re.h") || have_header("re.h")
have_header("ruby/encoding.h")
create_makefile 'json/ext/generator'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.